A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Faster headless simulation and model-based tests
Claudea9ee6de0b8c9
diff --git a/package.json b/package.jsonindex ecbaa66..27ca0af 100644--- a/package.json+++ b/package.json@@ -8,7 +8,8 @@"build": "vite build","typecheck": "tsc -p tsconfig.json --pretty false","balance": "node scripts/balance.ts",- "check": "node scripts/check.ts"+ "check": "node scripts/check.ts",+ "test": "node --test test/"},"dependencies": {"@typeonce/bevy-ts": "^0.5.0",@@ -16,6 +17,7 @@"@typeonce/bevy-ts-math": "^0.5.0","@typeonce/bevy-ts-pixi": "^0.5.0","@typeonce/bevy-ts-render": "^0.5.0",+ "effect": "4.0.3","pixi.js": "^8.22.0"},"devDependencies": {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b684562..067948a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -23,6 +23,9 @@ importers:'@typeonce/bevy-ts-render':specifier: ^0.5.0version: 0.5.0([email protected])+ effect:+ specifier: 4.0.3+ version: 4.0.3pixi.js:specifier: ^8.22.0version: 8.22.0@@ -303,6 +306,9 @@ packages:resolution: {integrity: sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q==}+ resolution: {integrity: sha512-LoWn/Uwwx0JjHSDmBAAahx8sB+klzM6vsZovnbYowBNw6B4QScJLRLBByO61plvNiycx7HPN8FnsWUCu0eXW5w==}+resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}@@ -644,6 +650,8 @@ snapshots:+ [email protected]: {}+diff --git a/scripts/balance.ts b/scripts/balance.tsindex a12c2ed..a2cfb27 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -21,13 +21,14 @@* `--set` changes content before the run. The bot only does what a player* could: it reads the world, then pushes the same edits the page does.*/-import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, STEP_SECONDS, total, type Amounts, type CharterValue, type GoodId, type Kind, type KindId } from "../src/content.ts"+import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, type Amounts, type CharterValue, type GoodId, type Kind, type KindId } from "../src/content.ts"import * as content from "../src/content.ts"import { around, canPlace, DIRS, entrances, GridBuilder, isRoad, key, useAt, type Use } from "../src/grid.ts"import { GRID, inside, type Point } from "../src/iso.ts"-import { Game, Ui, type GridValue } from "../src/schema.ts"-import { blankResources, goalsOf, larder, seasonAt, simulate, termTicks } from "../src/sim/index.ts"-import { emptyPreview, type Edit, type UiValue } from "../src/ui.ts"+import type { GridValue } from "../src/schema.ts"+import { headless, type Snapshot } from "../src/sim/headless.ts"+import { goalsOf, larder, seasonAt } from "../src/sim/index.ts"+import type { Edit } from "../src/ui.ts"// ── Options ───────────────────────────────────────────────────────────────@@ -58,11 +59,6 @@ for (let i = 0; i < args.length; i++) {// ── Reading the world ─────────────────────────────────────────────────────-interface Snapshot {- readonly entities: ReadonlyArray<{ readonly id: number; readonly components: Record<string, any> }>- readonly resources: Record<string, any>-}-interface Tile {readonly x: numberreadonly y: number@@ -390,30 +386,20 @@ interface Row {const run = (seed: number) => {roading.clear()resting.clear()- const charter: CharterValue = { size, term, land, seed }- const ui: UiValue = {- tool: "select", placing: null, menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],- edits: [{ type: "newTown", charter }],- preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false, toast: (m) => { if (process.env.DEBUG) console.log("toast:", m) }- }- const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })- if (!made.ok) throw new Error(JSON.stringify(made.error))- const runtime = made.value- const step = (seconds: number) => {- for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)- }- step(0.1)+ const town = headless({ size, term, land, seed }, { toast: (m) => { if (process.env.DEBUG) console.log("toast:", m) } })+ const ui = town.ui+ const step = town.runconst rows: Array<Row> = []const problems: Record<string, number> = {}- let w = read(runtime.snapshot() as unknown as Snapshot)+ let w = read(town.snapshot())const DECIDE = 5for (let t = 0; t < term * 60 + DECIDE && w.fate.state === "playing"; t += DECIDE) {const chosen = decide(w)if (process.env.DEBUG) console.log(t, JSON.stringify(chosen).slice(0, 200))ui.edits.push(...chosen)step(DECIDE)- w = read(runtime.snapshot() as unknown as Snapshot)+ w = read(town.snapshot())if ((t + DECIDE) % 60 !== 0) continueconst minute = (t + DECIDE) / 60const problemsNow: Record<string, number> = {}@@ -509,5 +495,3 @@ const allProblems: Record<string, number> = {}for (const r of results) for (const [k, n] of Object.entries(r.problems)) allProblems[k] = (allProblems[k] ?? 0) + nconst top = Object.entries(allProblems).sort((a, b) => b[1] - a[1]).slice(0, 6)console.log(`\n most common problems ${top.map(([k, n]) => `${k} (${(n / seeds).toFixed(1)} min/seed)`).join(", ") || "none"}`)-void total-void termTicksdiff --git a/scripts/check.ts b/scripts/check.tsindex 2d2cd0d..43780b5 100644--- a/scripts/check.ts+++ b/scripts/check.ts@@ -15,46 +15,15 @@* a row and the mayor is dismissed;* - and a town saved mid-term loads back the same.*/-import { STEP_SECONDS, type CharterValue } from "../src/content.ts"+import type { CharterValue } from "../src/content.ts"import { DIRS, GridBuilder, key } from "../src/grid.ts"import { inside } from "../src/iso.ts"-import { Game, Ui } from "../src/schema.ts"-import { blankResources, simulate } from "../src/sim/index.ts"-import { emptyPreview, type Edit, type UiValue } from "../src/ui.ts"--interface Snapshot {- nextEntity: number- entities: Array<{ id: number; components: Record<string, any> }>- resources: Record<string, any>-}+import { headless, type Snapshot } from "../src/sim/headless.ts"const town = (charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }) => {- const ui: UiValue = {- tool: "select", placing: null, menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],- edits: [{ type: "newTown", charter }],- preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false, toast: () => {}- }- const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })- if (!made.ok) throw new Error(JSON.stringify(made.error))- const runtime = made.value- const run = (seconds: number) => {- for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)- }- const snapshot = () => JSON.parse(JSON.stringify(runtime.snapshot())) as Snapshot- const restore = (s: Snapshot) => {- const restored = runtime.restore(s as never)- if (!restored.ok) throw new Error(`restore failed: ${JSON.stringify(restored.error)}`)- }- /** Changes the world through a snapshot, as a load would. */- const change = (f: (s: Snapshot) => void) => {- const s = snapshot()- f(s)- restore(s)- }- const fate = () => snapshot().resources["Town/Fate"] as { state: string; reason: string; at: number; governing: boolean }- const edit = (...edits: ReadonlyArray<Edit>) => ui.edits.push(...edits)- run(0.1)- return { run, snapshot, restore, change, fate, edit }+ const t = headless(charter)+ const fate = () => t.snapshot().resources["Town/Fate"] as { state: string; reason: string; at: number; governing: boolean }+ return { ...t, fate }}/** Citizens' homes, every need met for good, on free cells beside the roads. */diff --git a/src/schema.ts b/src/schema.tsindex 26232f0..620749a 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -261,6 +261,8 @@ export interface GridValue {readonly use: ReadonlyArray<Use>/** A fingerprint of where the roads are, when known: paths are cached against it. */readonly roads?: number+ /** The entities standing on it, when known: the grid only changes when one of them goes. */+ readonly tiles?: ReadonlySet<number>}export const Grid = Descriptor.TransientResource<GridValue>()("Town/Grid")/** Goods in the town's storage, summed every step. */diff --git a/src/sim/headless.ts b/src/sim/headless.tsnew file mode 100644index 0000000..8a4a3d5--- /dev/null+++ b/src/sim/headless.ts@@ -0,0 +1,63 @@+/**+ * A town with no page: the simulation's runtime, stepped from code. The+ * balance bot, `pnpm check`, and the tests all play the real game through+ * this, pushing the same edits the page does and reading the world through+ * the same snapshots it saves.+ */+import { STEP_SECONDS, type CharterValue } from "../content.ts"+import { Game, Ui } from "../schema.ts"+import { emptyPreview, type Edit, type UiValue } from "../ui.ts"+import { blankResources, simulate } from "./index.ts"++/** A saved world, as plain data. */+export interface Snapshot {+ version: number+ nextEntity: number+ entities: Array<{ id: number; components: Record<string, any> }>+ relations: Record<string, Array<[number, Array<number>]>>+ resources: Record<string, any>+ machines: Record<string, string>+}++export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void } = {}) => {+ const ui: UiValue = {+ tool: "select", placing: null, menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],+ edits: [{ type: "newTown", charter }],+ preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false,+ toast: options.toast ?? (() => {})+ }+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })+ if (!made.ok) throw new Error(`The town could not start: ${JSON.stringify(made.error)}`)+ const runtime = made.value+ const step = () => {+ const stepped = runtime.tick(simulate)+ if (!stepped.ok) throw new Error(`A step failed: ${JSON.stringify(stepped.error)}`)+ }+ const town = {+ ui,+ /** Runs the town on for `seconds` of game time. */+ run: (seconds: number) => {+ for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) step()+ },+ /** Pushes edits, applied on the next step. */+ edit: (...edits: ReadonlyArray<Edit>) => {+ ui.edits.push(...edits)+ },+ /** The world as plain data (a copy: changing it changes nothing until it is restored). */+ snapshot: (): Snapshot => JSON.parse(JSON.stringify(runtime.snapshot())),+ /** Loads a world, validating everything in it. */+ restore: (snapshot: Snapshot) => {+ const restored = runtime.restore(snapshot as never)+ if (!restored.ok) throw new Error(`The town could not be loaded: ${JSON.stringify(restored.error)}`)+ },+ /** Changes the world through a snapshot, as a load would. */+ change: (f: (snapshot: Snapshot) => void) => {+ const snapshot = town.snapshot()+ f(snapshot)+ town.restore(snapshot)+ }+ }+ step()+ return town+}+export type Headless = ReturnType<typeof headless>diff --git a/src/sim/logistics.ts b/src/sim/logistics.tsindex 916e7b6..b6d1155 100644--- a/src/sim/logistics.ts+++ b/src/sim/logistics.ts@@ -10,12 +10,14 @@ import { goods, goodIds, provisions, type GoodId } from "../content.ts"import { doors, nearest, pathTo, reach, type Reach } from "../grid.ts"import type { Point } from "../iso.ts"import {- Carriers, Errand, Figure, Game, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, WalkerOf, maybe+ Carriers, Errand, Figure, Game, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe} from "../schema.ts"import { CELL_STEPS } from "./shared.ts"/** The most a carrier takes at once. */const LOAD = 4+/** Carriers are sent out this often: ten times a second, a delay no one sees, at a sixth of the work. */+const DISPATCH_TICKS = 6export const Dispatch = Game.System("Town/Dispatch",@@ -44,9 +46,10 @@ export const Dispatch = Game.System(sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })},- resources: { grid: Game.System.readResource(Grid) }+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }},({ queries, resources, commands }) => {+ if (resources.time.get().tick % DISPATCH_TICKS !== 0) returnconst grid = resources.grid.get()const out = new Map<number, number>()const incoming = new Map<string, number>()diff --git a/src/sim/walkers.ts b/src/sim/walkers.tsindex 00df25b..3bc33f1 100644--- a/src/sim/walkers.ts+++ b/src/sim/walkers.ts@@ -110,7 +110,7 @@ export const SendWalkers = Game.System(const color = categoryColor[kinds[data.building.get().kind].category]const draft = Game.Command.spawn([Figure, { role: "walker", color }],- [Route, { cells: [starts[0]!], index: 0, step: 0 }],+ [Route, { cells: [{ x: starts[0]!.x, y: starts[0]!.y }], index: 0, step: 0 }],[Roam, { service: service.service, left: service.range, basket, back: false }])commands.spawn(Game.Command.relate(draft, WalkerOf, entity.id))diff --git a/src/sim/work.ts b/src/sim/work.tsindex a0c0dd8..6d9e39b 100644--- a/src/sim/work.ts+++ b/src/sim/work.ts@@ -15,15 +15,31 @@ import {} from "../schema.ts"import { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"-/** What stands where on the land, for every system after it this step. */+/**+ * What stands where on the land, for every system after it this step.+ * Tiles never move, so the grid is only rebuilt when one is laid or one of+ * those standing on it goes (a load spawns the whole world again, so it is+ * rebuilt then too).+ */export const IndexGrid = Game.System("Town/IndexGrid",- { queries: { tiles: TileRead }, resources: { land: Game.System.readResource(Land), grid: Game.System.writeResource(Grid) } },- ({ queries, resources }) => {+ {+ queries: { tiles: TileRead, laid: Game.Query({ selection: { tile: Game.Query.read(Tile) }, filters: [Game.Query.added(Tile)] }) },+ despawned: { entities: Game.System.readDespawned() },+ resources: { land: Game.System.readResource(Land), grid: Game.System.writeResource(Grid) }+ },+ ({ queries, despawned, resources }) => {+ const known = resources.grid.get().tiles+ const changed = known === undefined || queries.laid.each().length > 0 || despawned.entities.all().some((id) => known.has(id))+ if (!changed) returnconst grid = new GridBuilder(resources.land.get().mask)- for (const { entity, data } of queries.tiles.each()) grid.claim(data.tile.get(), entity.id, useOf(data))+ const tiles = new Set<number>()+ for (const { entity, data } of queries.tiles.each()) {+ grid.claim(data.tile.get(), entity.id, useOf(data))+ tiles.add(entity.id)+ }const value = grid.value()- resources.grid.set({ ...value, roads: roadPrint(value) })+ resources.grid.set({ ...value, roads: roadPrint(value), tiles })})@@ -76,6 +92,9 @@ export const Raise = Game.System(// ── Workers ───────────────────────────────────────────────────────────────+/** Workers are reassigned this often: residents move in and out every few seconds, no faster. */+const STAFF_TICKS = ticks(0.5)+/*** Residents go to work in the order buildings were placed, as many as each* needs while any are left; a paused building gets nobody.@@ -87,9 +106,10 @@ export const AssignStaff = Game.System(homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }),workplaces: Game.Query({ selection: { tile: Game.Query.read(Tile), staff: Game.Query.write(Staff), paused: Game.Query.optional(Paused) }, without: [Site, Rising] })},- resources: { grid: Game.System.readResource(Grid) }+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }},({ queries, resources }) => {+ if (resources.time.get().tick % STAFF_TICKS !== 0) returnconst grid = resources.grid.get()let pool = 0for (const { data } of queries.homes.each()) pool += data.house.get().residents@@ -137,9 +157,14 @@ export const Work = Game.System(const grid = resources.grid.get()const t = elapsed(resources.time.get(), resources.charter.get())const slowFishing = seasonAt(t, resources.charter.get()).winter && t % 2 === 1- const trees = new Map(queries.trees.each().map((row) => [row.entity.id as number, row]))- const rocks = new Map(queries.rocks.each().map((row) => [row.entity.id as number, row]))- const fields = new Map(queries.fields.each().map((row) => [row.entity.id as number, row]))+ // The land by entity, looked up only once some gatherer starts a job this step.+ const lazy = <T>(make: () => T) => {+ let value: T | undefined+ return () => (value ??= make())+ }+ const trees = lazy(() => new Map(queries.trees.each().map((row) => [row.entity.id as number, row])))+ const rocks = lazy(() => new Map(queries.rocks.each().map((row) => [row.entity.id as number, row])))+ const fields = lazy(() => new Map(queries.fields.each().map((row) => [row.entity.id as number, row])))const used = new Set<number>()/** Takes what a gatherer needs from the land within reach, or says there is none. */@@ -150,14 +175,14 @@ export const Work = Game.System(if (used.has(id)) continueif (source === "water" && use === "water") return trueif (source === "tree" && use === "tree") {- const tree = trees.get(id)+ const tree = trees().get(id)if (!tree || tree.data.tree.get().growth < GROWN.tree) continuecommands.despawn(tree.entity.id)used.add(id)return true}if ((source === "stone" || source === "ore") && use === "rock") {- const rock = rocks.get(id)+ const rock = rocks().get(id)if (!rock) continueconst r = rock.data.rock.get()if (r.ore !== (source === "ore") || r.amount <= 0) continue@@ -168,7 +193,7 @@ export const Work = Game.System(return true}if (source === "field" && use === "field") {- const field = fields.get(id)+ const field = fields().get(id)if (!field || field.data.field.get().growth < GROWN.field) continuefield.data.field.set({ growth: 0 })used.add(id)@@ -243,16 +268,22 @@ export const Plant = Game.System(without: [Site, Rising]})},- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng) }+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) }},({ queries, resources, commands }) => {const grid = resources.grid.get()const random = Random.make(resources.rng.get())const sown = new Set<number>()+ const tick = resources.time.get().tickfor (const { entity, data } of queries.planters.each()) {const tile = data.tile.get()const staff = data.staff.get()const planter = data.planter.get()+ // While it waits to plant again, it only counts down (and looks around twice a second for its status).+ if (planter.cooldown > 1 && tick % STAFF_TICKS !== 0) {+ data.planter.set({ ...planter, cooldown: planter.cooldown - 1 })+ continue+ }const open = connected(grid, tile)const reach = around(tile, planter.radius)const grown = reach.filter((c) => useAt(grid, c.x, c.y) === planter.what).length@@ -307,6 +338,9 @@ export const Spread = Game.System(})+/** Trees and fields grow this many steps at a time. */+const GROW_TICKS = 10+/** Trees and fields grow until they are ready; fields not in winter. */export const Grow = Game.System("Town/Grow",@@ -318,14 +352,15 @@ export const Grow = Game.System(resources: { time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) }},({ queries, resources }) => {+ if (resources.time.get().tick % GROW_TICKS !== 0) returnfor (const { data } of queries.trees.each()) {const growth = data.tree.get().growth- if (growth < GROWN.tree) data.tree.set({ growth: growth + 1 })+ if (growth < GROWN.tree) data.tree.set({ growth: Math.min(GROWN.tree, growth + GROW_TICKS) })}if (seasonAt(elapsed(resources.time.get(), resources.charter.get()), resources.charter.get()).winter) returnfor (const { data } of queries.fields.each()) {const growth = data.field.get().growth- if (growth < GROWN.field) data.field.set({ growth: growth + 1 })+ if (growth < GROWN.field) data.field.set({ growth: Math.min(GROWN.field, growth + GROW_TICKS) })}})diff --git a/test/model.test.ts b/test/model.test.tsnew file mode 100644index 0000000..e88f5ca--- /dev/null+++ b/test/model.test.ts@@ -0,0 +1,373 @@+/**+ * Model-based tests: generate sequences of what a mayor can do (lay roads+ * and homes, build, bulldoze, set taxes and trade, pause, answer the crown,+ * save and load, wait), run them on the real simulation, and after every+ * command check what must always be true of a town. A failure is shrunk to+ * the shortest sequence that still breaks the rule, and printed with its+ * replay so it can be run again.+ *+ * node --test test/+ * RUNS=200 node --test test/model.test.ts more runs+ */+import assert from "node:assert/strict"+import { test } from "node:test"++import { Arbitrary, Data, Effect, Schema } from "effect"++import {+ crown, goodIds, home, kindOrder, kinds, landIds, market, RESERVES, TAX_STEPS, type CharterValue+} 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 { headless, type Headless, type Snapshot } from "../src/sim/headless.ts"+import type { Edit } from "../src/ui.ts"++const RUNS = Number(process.env.RUNS ?? 25)+/** How large generated scenarios grow: at this size, sequences run to their full length. */+const SIZE = 50++// ── What a mayor can do ───────────────────────────────────────────────────++const between = (minimum: number, maximum: number) => Schema.Int.pipe(Schema.check(Schema.isBetween({ minimum, maximum })))+/** Cells around the town hall (which stands at 30–32), where most of the town goes. */+const Cell = between(18, 44)++/**+ * Which of the places a command could go it picks: the town's own choices+ * (free cells beside a road, spots with a road at a door, what stands) are+ * found when the command runs, so most commands do something.+ */+const Pick = between(0, 999)+const Direction = Schema.Literals(["+x", "+y", "-x", "-y"])++const Command = Schema.Union([+ Schema.TaggedStruct("Wait", { seconds: between(1, 60) }),+ // Long stretches too, so towns live through winters and the crown's requests.+ Schema.TaggedStruct("Season", { minutes: between(1, 6) }),+ // A road out from one of the town's road cells.+ Schema.TaggedStruct("Road", { pick: Pick, toward: Direction, length: between(1, 10) }),+ // A row of homes from a free cell beside a road.+ Schema.TaggedStruct("Homes", { pick: Pick, toward: Direction, length: between(1, 6) }),+ // A building on a spot with room and a road at one of its doors.+ Schema.TaggedStruct("Build", { kind: Schema.Literals(kindOrder), pick: Pick }),+ // Anywhere at all, valid or not.+ Schema.TaggedStruct("BuildAnywhere", { kind: Schema.Literals(kindOrder), x: Cell, y: Cell }),+ // One of the buildings, homes, or roads that stand.+ Schema.TaggedStruct("Remove", { pick: Pick, what: Schema.Literals(["building", "house", "road"]) }),+ Schema.TaggedStruct("Tax", { tier: Schema.Literals(["settlers", "citizens"]), rate: Schema.Literals(TAX_STEPS) }),+ Schema.TaggedStruct("Trade", { good: Schema.Literals(goodIds), mode: Schema.Literals(["sell", "buy", "none"]) }),+ Schema.TaggedStruct("Reserve", { amount: Schema.Literals(RESERVES) }),+ Schema.TaggedStruct("Pause", { pick: Pick, on: Schema.Boolean }),+ Schema.TaggedStruct("Deliver", {}),+ Schema.TaggedStruct("Govern", {}),+ Schema.TaggedStruct("SaveAndLoad", {}),+ // Not a lever the page has: fortune, good or bad, so runs reach debt and plenty.+ Schema.TaggedStruct("Windfall", { coins: between(-4000, 6000) }),+ // The rest of the term, at once.+ Schema.TaggedStruct("ToTheEnd", {})+])+type Command = typeof Command.Type++/**+ * How often a mayor does each thing: mostly building, then waiting; the+ * policy levers now and then; running the term out rarely.+ */+const weights: Readonly<Record<Command["_tag"], number>> = {+ Build: 20, Homes: 15, Road: 12, Season: 10, Wait: 8, Trade: 5, Tax: 4, Remove: 4, Pause: 4, Deliver: 4, SaveAndLoad: 3,+ Windfall: 3, Reserve: 2, BuildAnywhere: 2, Govern: 2, ToTheEnd: 1+}+const table = Object.entries(weights).flatMap(([tag, n]) => Array.from({ length: n }, () => tag as Command["_tag"]))+const command = Arbitrary.flatMap(Arbitrary.schema(between(0, table.length - 1)), (i) =>+ Arbitrary.schema(Command.members.find((m) => m.fields._tag.schema.literal === table[i])!))++const Charter = Schema.Struct({+ size: Schema.Literals(["small", "medium"]),+ term: Schema.Literals([45, 60]),+ land: Schema.Literals(landIds),+ seed: between(0, 100_000)+})++const Scenario = Schema.Struct({ charter: Charter, commands: Schema.Array(Command) })+const scenarios = Arbitrary.all({+ charter: Arbitrary.schema(Charter),+ commands: Arbitrary.array(command as Arbitrary.Arbitrary<Command>, { maxLength: 60 })+})++const steps = { "+x": { x: 1, y: 0 }, "+y": { x: 0, y: 1 }, "-x": { x: -1, y: 0 }, "-y": { x: 0, y: -1 } } as const+const line = (from: Point, length: number, toward: keyof typeof steps) =>+ Array.from({ length }, (_, i) => ({ x: from.x + steps[toward].x * i, y: from.y + steps[toward].y * i }))++/** The town as the commands see it: what stands where, and the places each could go. */+const look = (s: Snapshot) => {+ const builder = new GridBuilder(s.resources["Town/Land"].mask)+ const standing: Array<{ id: number; what: "building" | "house" | "road"; tile: Point & { size: number } }> = []+ for (const e of s.entities) {+ const tile = e.components["Town/Tile"]+ if (!tile) continue+ const c = e.components+ const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : "building"+ builder.claim(tile, e.id, use)+ if (use === "building" || use === "house" || use === "road") standing.push({ id: e.id, what: use, tile })+ }+ const grid = builder.value()+ const cells = (f: (x: number, y: number) => boolean) => {+ const out: Array<Point> = []+ for (let y = 0; y < GRID; y++) for (let x = 0; x < GRID; x++) if (f(x, y)) out.push({ x, y })+ return out+ }+ const besideRoad = (x: number, y: number) => DIRS.some((d) => isRoad(grid, x + d.x, y + d.y))+ return {+ standing,+ roads: () => cells((x, y) => isRoad(grid, x, y)),+ free: () => cells((x, y) => canPlace(grid, { x, y, size: 1 }) && besideRoad(x, y)),+ spots: (size: number) => cells((x, y) => canPlace(grid, { x, y, size }) && entrances({ x, y, size }).some((c) => isRoad(grid, c.x, c.y)))+ }+}+const pick = <A>(options: ReadonlyArray<A>, n: number): A | undefined => (options.length === 0 ? undefined : options[n % options.length])++/** A command as the edits the page would push (or, for the rest, what it does to the town). */+const apply = (town: Headless, command: Command): string | null => {+ const edit = (...edits: ReadonlyArray<Edit>) => town.edit(...edits)+ switch (command._tag) {+ case "Wait":+ town.run(command.seconds)+ return null+ case "Season":+ town.run(command.minutes * 60)+ return null+ case "ToTheEnd": {+ const s = town.snapshot()+ const charter = s.resources["Town/Charter"]+ town.run(Math.max(0, charter.founded + charter.term * 3600 - s.resources["Town/Time"].tick) / 60 + 2)+ return null+ }+ case "Road": {+ const from = pick(look(town.snapshot()).roads(), command.pick)+ if (from) edit({ type: "roads", cells: line(from, command.length + 1, command.toward).slice(1) })+ break+ }+ case "Homes": {+ const from = pick(look(town.snapshot()).free(), command.pick)+ if (from) edit({ type: "homes", cells: line(from, command.length, command.toward) })+ break+ }+ case "Build": {+ const spot = pick(look(town.snapshot()).spots(kinds[command.kind].size), command.pick)+ if (spot) edit({ type: "building", kind: command.kind, cell: spot, open: false })+ break+ }+ case "BuildAnywhere":+ edit({ type: "building", kind: command.kind, cell: { x: command.x, y: command.y }, open: false })+ break+ case "Remove": {+ const target = pick(look(town.snapshot()).standing.filter((t) => t.what === command.what), command.pick)+ if (target) edit({ type: "remove", cell: { x: target.tile.x, y: target.tile.y } })+ break+ }+ case "Tax":+ edit({ type: "tax", tier: command.tier, rate: command.rate })+ break+ case "Trade":+ edit({ type: "trade", good: command.good, mode: command.mode })+ break+ case "Reserve":+ edit({ type: "reserve", amount: command.amount })+ break+ case "Pause": {+ const target = pick(look(town.snapshot()).standing.filter((t) => t.what === "building"), command.pick)+ if (target) edit({ type: "pause", cell: { x: target.tile.x, y: target.tile.y }, on: command.on })+ break+ }+ case "Deliver":+ edit({ type: "deliver" })+ break+ case "Govern":+ edit({ type: "govern" })+ break+ case "SaveAndLoad": {+ // A save loads back to exactly what was saved.+ 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"+ }+ case "Windfall":+ town.change((s) => {+ s.resources["Town/Treasury"].coins += command.coins+ })+ break+ }+ // Edits apply on the next step; give the town a second.+ town.run(1)+ return null+}++// ── What must always be true ──────────────────────────────────────────────++/** What the checks remember from one command to the next. */+interface Memory {+ readonly tick: number+ readonly state: string+ readonly met: number+ readonly missed: number+ readonly peak: number+ readonly samples: number+}++const remember = (s: Snapshot): Memory => ({+ tick: s.resources["Town/Time"].tick,+ state: s.resources["Town/Fate"].state,+ met: s.resources["Town/Crown"].met,+ missed: s.resources["Town/Crown"].missed,+ peak: s.resources["Town/Fate"].peak,+ samples: s.resources["Town/History"].samples.length+})++/** Every rule a town breaks, as a line each. */+const broken = (s: Snapshot, before: Memory | null, last: Command): Array<string> => {+ const out: Array<string> = []+ const fail = (rule: string) => out.push(rule)+ const r = s.resources+ const mask: string = r["Town/Land"].mask+ const ids = new Set(s.entities.map((e) => e.id))++ // The land: every tile on it, none overlapping.+ const taken = new Map<number, number>()+ for (const e of s.entities) {+ const tile = e.components["Town/Tile"]+ if (!tile) continue+ for (const c of cellsOf(tile)) {+ if (!inside(c.x, c.y) || mask[key(c.x, c.y)] !== "1") fail(`entity ${e.id} stands off the land at ${c.x},${c.y}`)+ const k = key(c.x, c.y)+ if (taken.has(k)) fail(`entities ${taken.get(k)} and ${e.id} overlap at ${c.x},${c.y}`)+ taken.set(k, e.id)+ }+ }++ // Goods: never negative, never more than a shelf holds.+ for (const e of s.entities) {+ const inv = e.components["Town/Inventory"]+ if (!inv) continue+ for (const g of goodIds) {+ const n = inv.stock[g]+ if (n < 0) fail(`entity ${e.id} holds ${n} ${g}`)+ if (n > inv.cap) fail(`entity ${e.id} holds ${n} ${g}, more than its ${inv.cap}`)+ if (n > 0 && !inv.accepts.includes(g)) fail(`entity ${e.id} holds ${g}, which it does not take`)+ }+ }++ // Homes and work: residents within what a home holds, workers within who lives here.+ let residents = 0+ let settlers = 0+ let citizens = 0+ for (const e of s.entities) {+ const h = e.components["Town/House"]+ if (!h) continue+ if (h.residents < 0 || h.residents > home.tiers[h.tier as 1 | 2].residents) fail(`home ${e.id} has ${h.residents} residents at tier ${h.tier}`)+ residents += h.residents+ if (h.tier === 1) settlers += h.residents+ else citizens += h.residents+ }+ let assigned = 0+ for (const e of s.entities) {+ const staff = e.components["Town/Staff"]+ if (!staff) continue+ if (staff.assigned < 0 || staff.assigned > staff.needed) fail(`building ${e.id} has ${staff.assigned} of ${staff.needed} workers`)+ assigned += staff.assigned+ }+ if (assigned > residents) fail(`${assigned} at work but only ${residents} residents`)+ const census = r["Town/Census"]+ if (census.settlers !== settlers || census.citizens !== citizens) fail(`census says ${census.settlers}/${census.citizens}, homes ${settlers}/${citizens}`)++ // Walkers belong to a building that still stands.+ for (const [target, sources] of s.relations["Town/WalkerOf"] ?? []) {+ if (!ids.has(target)) fail(`walkers ${sources.join(", ")} belong to a building that is gone`)+ }+ for (const e of s.entities) {+ const tile = s.entities.find((b) => b.id === e.components["Town/Errand"]?.target)+ if (e.components["Town/Errand"] && !e.components["Town/Errand"].back && !tile) fail(`carrier ${e.id} is carrying to a building that is gone`)+ }++ // The town's figures stay within their bounds.+ const mood = r["Town/Mood"]+ if (mood.approval < -100 || mood.approval > 100) fail(`approval ${mood.approval}`)+ for (const g of goodIds) {+ const p = r["Town/Market"].prices[g]+ if (p < market.floor || p > market.ceiling) fail(`${g} at ${p}%`)+ }+ if (!Number.isInteger(r["Town/Treasury"].coins)) fail(`coins ${r["Town/Treasury"].coins}`)+ const c = r["Town/Crown"]+ if (c.streak > crown.patience) fail(`the crown has been snubbed ${c.streak} times in a row`)+ if (c.open && c.amount <= 0) fail(`the crown asks for ${c.amount}`)++ // Over time: the clock, the record, and the crown's tally only go forward.+ const now = remember(s)+ if (before) {+ if (now.tick < before.tick) fail(`time went back from ${before.tick} to ${now.tick}`)+ if (now.met < before.met || now.missed < before.missed) fail("the crown's tally went down")+ if (now.peak < before.peak) fail("the peak went down")+ if (now.samples < before.samples) fail("the history lost samples")+ // A term ends once: lost and over stay; won goes on only by choosing to govern.+ const moved = `${before.state}→${now.state}`+ const allowed = ["playing→playing", "playing→won", "playing→lost", "playing→over", "won→won", "lost→lost", "over→over"]+ if (!allowed.includes(moved) && !(moved === "won→playing" && last._tag === "Govern")) fail(`the term went ${moved}`)+ }+ const samples = r["Town/History"].samples as Array<{ tick: number }>+ if (samples.some((p, i) => i > 0 && p.tick <= samples[i - 1]!.tick)) fail("history out of order")+ return out+}++class Broken extends Data.TaggedError("Broken")<{ readonly step: number; readonly command: Command; readonly rules: ReadonlyArray<string> }> {}++/** Plays a scenario, failing at the first command after which the town breaks a rule. */+const play = (scenario: typeof Scenario.Type) =>+ Effect.gen(function* () {+ const town = headless(scenario.charter as CharterValue)+ let memory: Memory | null = null+ let index = 0+ if (process.env.VERBOSE) console.log(`${scenario.charter.size} ${scenario.charter.land} ${scenario.commands.length} commands, ${scenario.commands.reduce((t, c) => t + (c._tag === "Wait" ? c.seconds : c._tag === "Season" ? c.minutes * 60 : 1), 0)} s${scenario.commands.some((c) => c._tag === "ToTheEnd") ? " and to the end" : ""}`)+ for (const command of scenario.commands) {+ const problem = apply(town, command)+ const s = town.snapshot()+ const rules = [...(problem ? [problem] : []), ...broken(s, memory, command)]+ if (rules.length > 0) return yield* Effect.fail(new Broken({ step: index, command, rules }))+ memory = remember(s)+ index += 1+ }+ if (process.env.VERBOSE) {+ const s = town.snapshot()+ const count = (c: string) => s.entities.filter((e) => e.components[c]).length+ console.log(` → ${count("Town/Building")} buildings, ${count("Town/House")} homes, ${s.resources["Town/Census"].settlers + s.resources["Town/Census"].citizens} residents, ${s.resources["Town/Treasury"].coins} coins, ${s.resources["Town/Fate"].state}`)+ }+ return true+ })++const report = <A, E>(result: Arbitrary.CheckResult<A, E>) => Arbitrary.formatCheckFailure(result) ?? ""++test("a town keeps its rules whatever its mayor does", { timeout: 30 * 60_000 }, async () => {+ const result = await Effect.runPromise(Arbitrary.checkEffect(scenarios, play, { runs: RUNS, size: SIZE, seed: process.env.SEED ?? 1 }))+ const rules = result._tag === "Falsified" && result.failure._tag === "PropertyError"+ ? `\nAfter command ${result.failure.error.step} (${JSON.stringify(result.failure.error.command)}):\n ${result.failure.error.rules.join("\n ")}`+ : ""+ assert.equal(result._tag, "Passed", report(result) + rules)+})++test("the same charter and the same commands make the same town", { timeout: 30 * 60_000 }, async () => {+ const result = await Effect.runPromise(+ Arbitrary.checkEffect(+ scenarios,+ (scenario) => {+ const once = headless(scenario.charter as CharterValue)+ const twice = headless(scenario.charter as CharterValue)+ for (const command of scenario.commands) {+ apply(once, command)+ apply(twice, command)+ }+ return JSON.stringify(once.snapshot()) === JSON.stringify(twice.snapshot())+ },+ { runs: Math.max(3, Math.round(RUNS / 5)), size: SIZE, seed: process.env.SEED ?? 2 }+ )+ )+ assert.equal(result._tag, "Passed", report(result))+})+diff --git a/tsconfig.json b/tsconfig.jsonindex a61cfc8..b3e0360 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,5 +1,5 @@{- "include": ["src/**/*.ts", "scripts/**/*.ts", "vite.config.ts"],+ "include": ["src/**/*.ts", "scripts/**/*.ts", "test/**/*.ts", "vite.config.ts"],"compilerOptions": {"noEmit": true,"target": "ES2022",