A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Save and load with Effect; autosave; tests for saving
Claudecc62df51f25e
diff --git a/README.md b/README.mdindex 71a5284..3b5c1dc 100644--- a/README.md+++ b/README.md@@ -10,6 +10,7 @@ that ends with the town complete, lost, or run out. Game logic runs on thepnpm installpnpm dev --host --port 5232pnpm typecheck+pnpm test # model-based tests: random mayors, rules that must always hold; and savingpnpm check # every way a term can end, ends itpnpm balance # a bot plays terms headless and reports the pressure```@@ -87,12 +88,17 @@ pnpm balance # a bot plays terms headless and reports the pressure(seasons, the crown, approval, the end of the term, history).- `src/present.ts`: per-frame interaction, panel, and view sync.- `src/art.ts`: all drawing.+- `src/sim/headless.ts`: a town with no page, stepped from code: what the tests, `check`, and `balance` play.+- `src/save.ts`: saving and loading as [Effect](https://effect.website) programs: a versioned file in a slot+ (the mayor's own, or the autosave), typed errors for each way a load can fail.- `src/ui.ts`, `src/host.ts`, `src/main.ts`: the page bridge, camera, input, panels, and start-up.The simulation runs on bevy-ts-browser's `FixedLoop` at 60 steps a second(times the chosen speed), with integer state and a seeded random resource.Every saved component and resource is validated, so **save** / **load**-snapshot the whole world, history and chronicle included, to localStorage.+snapshot the whole world, history and chronicle included, to localStorage;+the page also autosaves every two minutes of game time, and **load** takes+whichever is newer.In development the console has `town.ui`, `town.runtime`, and`town.advance(seconds)` to fast-forward the simulation.@@ -113,6 +119,25 @@ pnpm balance -- --set crown.fine=2 --set kinds.fishery.recipe.seconds=3pnpm balance -- --seeds 1 --verbose --every 1 # minute by minute```+## Testing++The simulation has no renderer in it: it runs headless (`src/sim/headless.ts`),+about 60 to 80 times faster than real time, so the tests play real towns.++`pnpm test` runs model-based tests built on Effect's `Schema` and+`Arbitrary`. They generate sequences of what a mayor can do (roads, homes,+buildings where they fit, bulldozing, taxes, trade, pausing, answering the+crown, saving and loading, waiting through seasons, and fortune good and+bad), play them on the real simulation, and after every command check what+must always be true: goods within their shelves, tiles on the land and+apart, residents and workers within bounds, the census matching the homes,+walkers belonging to standing buildings, approval and prices within their+bounds, the clock and the record only going forward, and a term ending only+in the allowed ways. A failure shrinks to the shortest sequence that still+breaks a rule. A second property checks that the same charter and commands+always make the same town. `RUNS=200 pnpm test` searches harder;+`SEED=…` replays.+`pnpm check` puts the real simulation into each way a term can end(complete, bankrupt, revolt, abandoned, dismissed, run out), checks an unansweredcrown request, and checks that a town saved mid-term loads back the same.diff --git a/docs/mayor-plan.md b/docs/mayor-plan.mdindex 7c76157..aff09b2 100644--- a/docs/mayor-plan.md+++ b/docs/mayor-plan.md@@ -81,12 +81,15 @@ everything, and ignores the crown. The idle bot founds the basics and stops.| Charter | Mayor | Seeds | Complete | Lost | Ran out ||---------|-------|-------|----------|------|---------|-| small, 45 min | sensible | 8 | 2 (minutes 30, 43) | 1 dismissed (39) | 5 |-| medium, 60 min | sensible | 8 | 1 (minute 58) | — | 7 |+| small, 45 min | sensible | 8 | 1 (minute 40) | — | 7 |+| medium, 60 min | sensible | 8 | 1 (minute 45) | — | 7 || large, 90 min | sensible | 4 | — | 2 bankrupt (61, 89) | 2 |-| medium, 60 min | greedy | 4 | — | 4 in revolt (19–21) | — |+| medium, 60 min | greedy | 4 | — | 3 in revolt, 1 dismissed (19–22) | — || medium, 60 min | idle | 4 | — | 4 dismissed (22) | — |+(Measured again after the simulation was made faster, which changed how+often carriers are sent out; the large row is from before that change.)+So a careless mayor loses, a decent one wins small towns and comes closeon larger ones, and a player who lays out tighter chains than the botshould complete medium and large towns. Most "ran out" terms ended withindiff --git a/package.json b/package.jsonindex 27ca0af..7ce6b73 100644--- a/package.json+++ b/package.json@@ -9,7 +9,7 @@"typecheck": "tsc -p tsconfig.json --pretty false","balance": "node scripts/balance.ts","check": "node scripts/check.ts",- "test": "node --test test/"+ "test": "node --test \"test/*.test.ts\""},"dependencies": {"@typeonce/bevy-ts": "^0.5.0",diff --git a/src/host.ts b/src/host.tsindex 97a7fdb..c428686 100644--- a/src/host.ts+++ b/src/host.ts@@ -211,8 +211,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistetoolbar.append(button)}action("new town", "Found a new town on new land", () => openCharter(true))- action("save", "Save the town in this browser", () => ui.toast(persistence().save() ?? "Saved"))- action("load", "Load the saved town", () => ui.toast(persistence().load() ?? "Loaded"))+ action("save", "Save the town in this browser (it also autosaves every two minutes)", () => ui.toast(persistence().save() ?? "Saved"))+ action("load", "Load the latest save: yours or the autosave, whichever is newer", () => ui.toast(persistence().load() ?? "Loaded"))const refreshTools = () => {for (const { tool, button } of buttons) {diff --git a/src/main.ts b/src/main.tsindex 34a6604..0564ccd 100644--- a/src/main.ts+++ b/src/main.ts@@ -4,18 +4,20 @@* the views follow once a frame.*/import { Result } from "@typeonce/bevy-ts"+import { Effect } from "effect"import { FixedLoop } from "@typeonce/bevy-ts-browser"import { PixiNodeRegistry } from "@typeonce/bevy-ts-pixi"import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./art.ts"-import { STEP_SECONDS } from "./content.ts"+import { lands, sizes, STEP_SECONDS } from "./content.ts"import { createHost, type Persistence } from "./host.ts"import { present } from "./present.ts"+import { browserStorage, describe, loadLatest, save, Storage, World } from "./save.ts"import { BuildingNodes, Clock, FieldNodes, Game, HouseNodes, RockNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"import { blankResources, simulate } from "./sim/index.ts"-/** Saves of the charter's towns: older ones (a square map, no term) do not load into it. */-const SAVE_KEY = "town/save/charter"+/** Minutes of game time between autosaves. */+const AUTOSAVE_MINUTES = 2const start = async () => {const mount = document.getElementById("app")!@@ -51,19 +53,43 @@ const start = async () => {Object.assign(window, { town: { ui, runtime, advance } })}- // Saves are plain data; loading validates every component before touching the world.+ // Saves are Effect programs over the browser's storage and this town (see `save.ts`);+ // loading validates every component before touching the world.+ const world: World["Service"] = {+ snapshot: () => runtime.snapshot(),+ restore: (data) => {+ const restored = runtime.restore(data as never)+ return restored.ok ? null : restored.error._tag+ },+ title: () => {+ const s = ui.stats+ return s ? `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · year ${s.season.year} · ${Math.floor(s.minute)} min in` : "a town"+ }+ }+ const run = <A, E>(program: Effect.Effect<A, E, Storage | World>) =>+ Effect.runSync(Effect.result(program.pipe(Effect.provideService(Storage, browserStorage(localStorage)), Effect.provideService(World, world))))persistence = {save: () => {- localStorage.setItem(SAVE_KEY, JSON.stringify(runtime.snapshot()))- return null+ const saved = run(save("manual"))+ return saved._tag === "Success" ? null : describe(saved.failure)},load: () => {- const raw = localStorage.getItem(SAVE_KEY)- if (raw === null) return "Nothing saved yet"- const restored = runtime.restore(JSON.parse(raw))- return restored.ok ? null : `Could not load: ${restored.error._tag}`+ const loaded = run(loadLatest)+ if (loaded._tag === "Failure") return describe(loaded.failure)+ return loaded.success.slot === "auto" ? `Loaded the autosave: ${loaded.success.title}` : `Loaded ${loaded.success.title}`}}+ /** The page autosaves every `AUTOSAVE_MINUTES` of game time while a term runs. */+ let autosaved = 0+ const autosave = () => {+ const s = ui.stats+ if (!s || s.fate.state !== "playing" || ui.founding) return+ if (s.minute < autosaved) autosaved = 0+ if (s.minute < autosaved + AUTOSAVE_MINUTES) return+ autosaved = Math.floor(s.minute / AUTOSAVE_MINUTES) * AUTOSAVE_MINUTES+ const saved = run(save("auto"))+ if (saved._tag === "Failure") ui.toast(describe(saved.failure))+ }const loop = FixedLoop.start({source: FixedLoop.source((onTick) => {@@ -91,6 +117,7 @@ const start = async () => {clock.elapsed += elapsedSecondsruntime.tick(present)syncPage()+ autosave()},onFailure: (failure) => {mount.textContent = failure.kind === "InvalidTickDelta" ? `Invalid frame delta: ${failure.deltaMS}` : "The town stopped after a system failure."diff --git a/src/save.ts b/src/save.tsnew file mode 100644index 0000000..9c060d0--- /dev/null+++ b/src/save.ts@@ -0,0 +1,155 @@+/**+ * Saving and loading a town, as Effect programs. A save is a versioned file+ * (the world as the simulation snapshots it, with a title and when it was+ * saved) in one of two slots: the mayor's own, and the autosave the page+ * writes every few minutes of game time. Loading reads, checks, and+ * restores it, failing with what went wrong: nothing saved, a file that+ * cannot be read, a version this game does not know, or a world the+ * simulation refuses. Where the files live (the browser's storage, or a map+ * in a test) and the world they come from are services.+ */+import { Clock, Context, Effect, Schema } from "effect"++export const SAVE_FORMAT = "inkline-town/save"+/** 2: the charter's towns. Older saves (a square map, no term) cannot be loaded. */+export const SAVE_VERSION = 2++export type Slot = "manual" | "auto"+export const slots: ReadonlyArray<Slot> = ["manual", "auto"]+const keyOf = (slot: Slot) => `inkline-town/save/${slot}`+/** Where the first charter version kept its one save: the world alone, no envelope. */+const LEGACY_KEY = "town/save/charter"++/** A save file. */+export const SaveFile = Schema.Struct({+ format: Schema.Literal(SAVE_FORMAT),+ version: Schema.Int,+ slot: Schema.Literals(["manual", "auto"]),+ /** When it was saved, in milliseconds since the epoch. */+ savedAt: Schema.Int,+ /** What it is, in a line: "medium, fair land · year 2 · 23 min in". */+ title: Schema.String,+ world: Schema.Unknown+})+export type SaveFile = typeof SaveFile.Type++const decodeFile = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))+const decodeEnvelope = Schema.decodeUnknownEffect(SaveFile)++// ── What can go wrong ─────────────────────────────────────────────────────++export class NothingSaved extends Schema.TaggedError<NothingSaved>()("NothingSaved", { slot: Schema.String }) {}+export class Unreadable extends Schema.TaggedError<Unreadable>()("Unreadable", { slot: Schema.String, reason: Schema.String }) {}+export class WrongVersion extends Schema.TaggedError<WrongVersion>()("WrongVersion", { slot: Schema.String, version: Schema.Number }) {}+export class Rejected extends Schema.TaggedError<Rejected>()("Rejected", { slot: Schema.String, reason: Schema.String }) {}+export class StorageFailed extends Schema.TaggedError<StorageFailed>()("StorageFailed", { slot: Schema.String, reason: Schema.String }) {}++export type LoadError = NothingSaved | Unreadable | WrongVersion | Rejected | StorageFailed++/** What to tell the mayor. */+export const describe = (error: LoadError | StorageFailed): string => {+ switch (error._tag) {+ case "NothingSaved":+ return error.slot === "auto" ? "No autosave yet" : "Nothing saved yet"+ case "Unreadable":+ return "The save could not be read"+ case "WrongVersion":+ return error.version < SAVE_VERSION ? "That save is from an older version of the game" : "That save is from a newer version of the game"+ case "Rejected":+ return `The save does not fit this game: ${error.reason}`+ case "StorageFailed":+ return `Could not save: ${error.reason}`+ }+}++// ── Services ──────────────────────────────────────────────────────────────++/** Where save files are kept, by key. */+export class Storage extends Context.Service<Storage, {+ readonly get: (key: string) => string | null+ readonly set: (key: string, value: string) => void+}>()("inkline-town/Storage") {}++/** The town being saved and loaded. */+export class World extends Context.Service<World, {+ readonly snapshot: () => unknown+ /** Restores a world, or says why it will not. */+ readonly restore: (world: unknown) => string | null+ /** The town in a line, for a save's title. */+ readonly title: () => string+}>()("inkline-town/World") {}++/** The browser's storage (which can throw: full, or blocked). */+export const browserStorage = (store: globalThis.Storage): Storage["Service"] => ({+ get: (key) => store.getItem(key),+ set: (key, value) => store.setItem(key, value)+})++/** Storage in a map, for tests and for running headless. */+export const memoryStorage = (files = new Map<string, string>()): Storage["Service"] & { readonly files: Map<string, string> } => ({+ files,+ get: (key) => files.get(key) ?? null,+ set: (key, value) => {+ files.set(key, value)+ }+})++// ── Saving and loading ────────────────────────────────────────────────────++/** Writes the town to a slot. */+export const save = (slot: Slot) =>+ Effect.gen(function* () {+ const storage = yield* Storage+ const world = yield* World+ const file: SaveFile = {+ format: SAVE_FORMAT,+ version: SAVE_VERSION,+ slot,+ savedAt: yield* Clock.currentTimeMillis,+ title: world.title(),+ world: world.snapshot()+ }+ yield* Effect.try({+ try: () => storage.set(keyOf(slot), JSON.stringify(file)),+ catch: (cause) => new StorageFailed({ slot, reason: cause instanceof Error ? cause.message : String(cause) })+ })+ return file+ })++/** Reads a slot's file, checked, without loading it. A save from before files had envelopes reads as the manual slot. */+export const read = (slot: Slot) =>+ Effect.gen(function* () {+ const storage = yield* Storage+ const raw = yield* Effect.try({+ try: () => storage.get(keyOf(slot)) ?? (slot === "manual" ? storage.get(LEGACY_KEY) : null),+ catch: (cause) => new StorageFailed({ slot, reason: cause instanceof Error ? cause.message : String(cause) })+ })+ if (raw === null) return yield* new NothingSaved({ slot })+ const parsed = yield* decodeFile(raw).pipe(Effect.mapError((e) => new Unreadable({ slot, reason: e.message })))+ // The first charter saves were the world alone.+ if (typeof parsed === "object" && parsed !== null && "entities" in parsed && !("format" in parsed)) {+ return { format: SAVE_FORMAT, version: SAVE_VERSION, slot, savedAt: 0, title: "an earlier save", world: parsed } satisfies SaveFile+ }+ const version = (parsed as { version?: unknown } | null)?.version+ if (typeof version === "number" && version !== SAVE_VERSION) return yield* new WrongVersion({ slot, version })+ return yield* decodeEnvelope(parsed).pipe(Effect.mapError((e) => new Unreadable({ slot, reason: e.message })))+ })++/** Loads a slot into the world. */+export const load = (slot: Slot) =>+ Effect.gen(function* () {+ const file = yield* read(slot)+ const world = yield* World+ const refused = world.restore(file.world)+ if (refused !== null) return yield* new Rejected({ slot, reason: refused })+ return file+ })++/** Loads whichever slot was saved last: the mayor's own save, or the autosave. */+export const loadLatest = Effect.gen(function* () {+ const files = yield* Effect.forEach(slots, (slot) => read(slot).pipe(Effect.option))+ const newest = files+ .flatMap((f) => (f._tag === "Some" ? [f.value] : []))+ .sort((a, b) => b.savedAt - a.savedAt)[0]+ return yield* load(newest?.slot ?? "manual")+})diff --git a/test/model.test.ts b/test/model.test.tsindex e88f5ca..bdcb1a6 100644--- a/test/model.test.ts+++ b/test/model.test.ts@@ -6,7 +6,7 @@* the shortest sequence that still breaks the rule, and printed with its* replay so it can be run again.*- * node --test test/+ * pnpm test* RUNS=200 node --test test/model.test.ts more runs*/import assert from "node:assert/strict"@@ -19,6 +19,7 @@ import {} from "../src/content.ts"import { canPlace, cellsOf, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"import { GRID, inside, type Point } from "../src/iso.ts"+import { load, memoryStorage, save, Storage, World } from "../src/save.ts"import { headless, type Headless, type Snapshot } from "../src/sim/headless.ts"import type { Edit } from "../src/ui.ts"@@ -185,11 +186,22 @@ const apply = (town: Headless, command: Command): string | null => {edit({ type: "govern" })breakcase "SaveAndLoad": {- // A save loads back to exactly what was saved.+ // Through the page's own saving and loading: a save loads back to exactly what was saved.+ const world: World["Service"] = {+ snapshot: () => town.snapshot(),+ restore: (data) => {+ town.restore(data as Snapshot)+ return null+ },+ title: () => "a town under test"+ }const saved = town.snapshot()- town.restore(JSON.parse(JSON.stringify(saved)))- const loaded = town.snapshot()- return JSON.stringify(saved) === JSON.stringify(loaded) ? null : "a saved town did not load back the same"+ const result = Effect.runSync(Effect.result(Effect.andThen(save("manual"), load("manual")).pipe(+ Effect.provideService(Storage, memoryStorage()),+ Effect.provideService(World, world)+ )))+ if (result._tag === "Failure") return `saving and loading failed: ${result.failure._tag}`+ return JSON.stringify(saved) === JSON.stringify(town.snapshot()) ? null : "a saved town did not load back the same"}case "Windfall":town.change((s) => {diff --git a/test/save.test.ts b/test/save.test.tsnew file mode 100644index 0000000..0f2fd9e--- /dev/null+++ b/test/save.test.ts@@ -0,0 +1,134 @@+/**+ * Saving and loading (`src/save.ts`) against a real headless town and+ * storage in a map: every way a load can go, and that a failed one leaves+ * the town as it was.+ */+import assert from "node:assert/strict"+import { test } from "node:test"++import { Effect } from "effect"++import { load, loadLatest, memoryStorage, read, save, SAVE_FORMAT, SAVE_VERSION, Storage, World, type LoadError } from "../src/save.ts"+import { headless, type Headless } from "../src/sim/headless.ts"++const worldOf = (town: Headless): World["Service"] => ({+ snapshot: () => town.snapshot(),+ restore: (data) => {+ try {+ town.restore(data as never)+ return null+ } catch (cause) {+ return cause instanceof Error ? cause.message : String(cause)+ }+ },+ title: () => "a test town"+})++/**+ * The world as it plays: everything but the counter new entity ids come+ * from, which bevy-ts never moves backwards on a load (so ids are never+ * reused), and which nothing in the town reads.+ */+const playing = (town: Headless) => {+ const { nextEntity: _, ...world } = town.snapshot()+ return JSON.stringify(world)+}++const setup = () => {+ const town = headless({ size: "small", term: 45, land: "fair", seed: 5 })+ const storage = memoryStorage()+ const run = <A, E>(program: Effect.Effect<A, E, Storage | World>) =>+ Effect.runSync(Effect.result(program.pipe(Effect.provideService(Storage, storage), Effect.provideService(World, worldOf(town)))))+ return { town, storage, run }+}++const failure = <A>(result: { _tag: "Success"; success: A } | { _tag: "Failure"; failure: LoadError }) => {+ assert.equal(result._tag, "Failure")+ return (result as { failure: LoadError }).failure+}++test("a saved town loads back as it was", () => {+ const { town, run } = setup()+ town.run(30)+ const saved = run(save("manual"))+ assert.equal(saved._tag, "Success")+ const before = playing(town)+ town.run(30)+ assert.notEqual(playing(town), before)+ assert.equal(run(load("manual"))._tag, "Success")+ assert.equal(playing(town), before)+})++test("nothing saved", () => {+ const { run } = setup()+ assert.equal(failure(run(load("manual")))._tag, "NothingSaved")+ assert.equal(failure(run(load("auto")))._tag, "NothingSaved")+})++test("a file that is not a save is unreadable", () => {+ const { storage, run } = setup()+ storage.set("inkline-town/save/manual", "{ not json")+ assert.equal(failure(run(load("manual")))._tag, "Unreadable")+ storage.set("inkline-town/save/manual", JSON.stringify({ format: SAVE_FORMAT, version: SAVE_VERSION, slot: "manual" }))+ assert.equal(failure(run(load("manual")))._tag, "Unreadable")+})++test("a save from another version is refused by name", () => {+ const { storage, run } = setup()+ storage.set("inkline-town/save/manual", JSON.stringify({ format: SAVE_FORMAT, version: 1, slot: "manual", savedAt: 0, title: "", world: {} }))+ const error = failure(run(load("manual")))+ assert.equal(error._tag, "WrongVersion")+})++test("a world the simulation refuses leaves the town untouched", () => {+ const { town, storage, run } = setup()+ town.run(10)+ run(save("manual"))+ const file = JSON.parse(storage.get("inkline-town/save/manual")!)+ file.world.resources["Town/Treasury"] = { coins: "lots" }+ storage.set("inkline-town/save/manual", JSON.stringify(file))+ town.run(10)+ const before = JSON.stringify(town.snapshot())+ assert.equal(failure(run(load("manual")))._tag, "Rejected")+ assert.equal(JSON.stringify(town.snapshot()), before, "a refused load changes nothing, not even the id counter")+})++test("a storage that will not take the save says so", () => {+ const { town } = setup()+ const full: Storage["Service"] = {+ get: () => null,+ set: () => {+ throw new Error("the storage is full")+ }+ }+ const result = Effect.runSync(Effect.result(save("auto").pipe(Effect.provideService(Storage, full), Effect.provideService(World, worldOf(town)))))+ assert.equal(result._tag, "Failure")+ assert.equal((result as { failure: { _tag: string } }).failure._tag, "StorageFailed")+})++test("a save from before files had envelopes still loads", () => {+ const { town, storage, run } = setup()+ town.run(10)+ storage.set("town/save/charter", JSON.stringify(town.snapshot()))+ const before = playing(town)+ town.run(10)+ assert.equal(run(load("manual"))._tag, "Success")+ assert.equal(playing(town), before)+})++test("loading takes the newer of the mayor's save and the autosave", () => {+ const { town, storage, run } = setup()+ run(save("manual"))+ town.run(20)+ run(save("auto"))+ const auto = JSON.parse(storage.get("inkline-town/save/auto")!)+ const manual = JSON.parse(storage.get("inkline-town/save/manual")!)+ storage.set("inkline-town/save/manual", JSON.stringify({ ...manual, savedAt: 1000 }))+ storage.set("inkline-town/save/auto", JSON.stringify({ ...auto, savedAt: 2000 }))+ const loaded = run(loadLatest)+ assert.equal(loaded._tag, "Success")+ assert.equal((loaded as { success: { slot: string } }).success.slot, "auto")+ storage.set("inkline-town/save/manual", JSON.stringify({ ...manual, savedAt: 3000 }))+ assert.equal((run(loadLatest) as { success: { slot: string } }).success.slot, "manual")+ assert.equal(run(read("auto"))._tag, "Success")+})