A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Let only the simulation write the guide; edits live in game/edits.ts
SandroMaglione99c3226106aa
diff --git a/scripts/balance.ts b/scripts/balance.tsindex 580991f..1e6b3ac 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -54,7 +54,7 @@ import { GRID, inside, type Point } from "../src/game/world/iso.ts"import type { GridValue } from "../src/game/schema.ts"import { headless, type Snapshot } from "../src/game/headless.ts"import { goalsOf, larder, seasonAt } from "../src/game/schedule.ts"-import type { Edit } from "../src/view/contracts.ts"+import type { Edit } from "../src/game/edits.ts"import { SAVE_FORMAT, SAVE_VERSION } from "../src/platform/save.ts"import { mkdirSync, writeFileSync } from "node:fs"import { dirname } from "node:path"diff --git a/src/app/browser.ts b/src/app/browser.tsindex 23c9d87..31e5e50 100644--- a/src/app/browser.ts+++ b/src/app/browser.ts@@ -184,7 +184,8 @@ const start = async () => {stage.resetCamera()}const waiting = ui.speed === 0 || ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")- const steps = waiting ? (ui.edits.length > 0 ? 1 : 0) : ui.speed+ // Guide edits are bookkeeping: they wait for the next step rather than run one while the town waits.+ const steps = waiting ? (ui.edits.some((edit) => edit.type !== "guide" && edit.type !== "guideOff") ? 1 : 0) : ui.speedfor (let i = 0; i < steps; i++) {const stepped = runtime.tick(simulate)if (!stepped.ok) return steppeddiff --git a/src/game/edits.ts b/src/game/edits.tsnew file mode 100644index 0000000..47bd3d5--- /dev/null+++ b/src/game/edits.ts@@ -0,0 +1,57 @@+/**+ * What the player can ask of the town. Every UI (the page, a bot, a test)+ * and the view's map gestures send these; only the simulation applies them,+ * at the start of its next step (see `systems/edits`). Replays record them.+ */+import type { CharterValue, GoodId, GroundId, KindId, PropId } from "./content/index.ts"+import type { Point } from "./world/iso.ts"++/** A change to the town, applied by the simulation (see `ApplyEdits`). */+export type Edit =+ /** `open`: show the new building in the panel. */+ | { readonly type: "building"; readonly kind: KindId; readonly cell: Point; readonly open: boolean }+ | { readonly type: "homes"; readonly cells: ReadonlyArray<Point> }+ | { readonly type: "roads"; readonly cells: ReadonlyArray<Point> }+ /** Paves the road on each cell (coins, and stone from storage). */+ | { readonly type: "pave"; readonly cells: ReadonlyArray<Point> }+ /** Lays park ground on each empty cell (or relays a park cell's ground). */+ | { readonly type: "ground"; readonly ground: GroundId; readonly cells: ReadonlyArray<Point> }+ /** Sets a furnishing on a cell of park. */+ | { readonly type: "prop"; readonly prop: PropId; readonly cell: Point }+ /** Removes whatever stands on a cell (not rocks, water, or the town hall); on a park, its furnishing first. */+ | { readonly type: "remove"; readonly cell: Point }+ /** Sets a tier's tax rate, in percent of the usual. */+ | { readonly type: "tax"; readonly tier: "settlers" | "citizens"; readonly rate: number }+ /** Sells a good to traders beyond the reserve, buys it up to the reserve, or neither; `amount`, up to how much a collection. */+ | { readonly type: "trade"; readonly good: GoodId; readonly mode: TradeMode; readonly amount?: number }+ /** How much of each good the town keeps before selling, and buys up to. */+ | { readonly type: "reserve"; readonly amount: number }+ /** Pauses the building on a cell (or closes the home), or sets it back to work. */+ | { readonly type: "pause"; readonly cell: Point; readonly on: boolean }+ /** Sends the crown what it asked for. */+ | { readonly type: "deliver" }+ /** Once a term has run out, stands for another: the same town, a new term. */+ | { readonly type: "nextTerm" }+ /** Upgrades the building on a cell where it stands (see `Kind.upgrade`). */+ | { readonly type: "upgrade"; readonly cell: Point }+ /** Clears everything and founds a new town on the land a charter describes. */+ | { readonly type: "newTown"; readonly charter: CharterValue }+ /** Puts guide steps away: the mayor skipped them, or the town has done them (see `rules/guide.ts`). */+ | { readonly type: "guide"; readonly done: ReadonlyArray<string> }+ /** Turns the mayor's guide off, or back on. */+ | { readonly type: "guideOff"; readonly off: boolean }++export type TradeMode = "sell" | "buy" | "none"++/** Edits waiting for the next step: pushed by the page and the view, taken by the simulation's `Edits` service. */+export const editQueue = () => {+ const queued: Array<Edit> = []+ return {+ queued: queued as ReadonlyArray<Edit>,+ push: (...edits: ReadonlyArray<Edit>) => {+ queued.push(...edits)+ },+ snapshot: (): ReadonlyArray<Edit> => queued.splice(0)+ }+}+export type EditQueue = ReturnType<typeof editQueue>diff --git a/src/game/headless.ts b/src/game/headless.tsindex 8e9aedb..e3cf677 100644--- a/src/game/headless.ts+++ b/src/game/headless.ts@@ -10,7 +10,8 @@ import type * as Replay from "@typeonce/ritmo-devtools/Replay"import { step as simulationStep, type CharterValue } from "./content/index.ts"import { resolveRules, type Rules as RuleInputs } from "./rules/config.ts"import { Edits, Game, Rules, Toast } from "./schema.ts"-import { emptyPreview, type Edit, type UiValue } from "../view/contracts.ts"+import type { Edit } from "./edits.ts"+import { emptyPreview, type UiValue } from "../view/contracts.ts"import { blankResources, simulate } from "./schedule.ts"/** A saved world, as plain data. */diff --git a/src/game/schema.ts b/src/game/schema.tsindex 82b5bc1..791a5af 100644--- a/src/game/schema.ts+++ b/src/game/schema.ts@@ -20,7 +20,8 @@ import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView,import type { GameScene } from "../render/three/scene.ts"import { goodIds, groundIds, kindIds, landIds, propIds, serviceIds, sizeIds, type Amounts, type GoodId } from "./content/index.ts"import type { Rules as RuleInputs } from "./rules/config.ts"-import type { Edit, UiValue } from "../view/contracts.ts"+import type { Edit } from "./edits.ts"+import type { UiValue } from "../view/contracts.ts"export const Root = Schema.defineRoot("Town")diff --git a/src/game/systems/edits/index.ts b/src/game/systems/edits/index.tsindex fbd44e1..2fe2c0d 100644--- a/src/game/systems/edits/index.ts+++ b/src/game/systems/edits/index.ts@@ -1,7 +1,7 @@/*** The player's edits, applied at the start of a step: building, laying* roads and homes, laying out parks, bulldozing, pausing, the town's policy, answering the- * crown, and founding a new town. Costs are checked against the treasury+ * crown, putting guide steps away, and founding a new town. Costs are checked against the treasury* and the town's stock and paid up front in coins; the materials are* carried to the site afterwards. Upgrading a building is paid at once.* Once the term has ended, only a new town, or another term, is taken.@@ -179,7 +179,7 @@ export const ApplyEdits = Game.System(const t = elapsed(resources.time.get(), resources.charter.get())edits: for (const edit of queued) {- if (edit.type !== "newTown" && edit.type !== "nextTerm" && !playing()) continue+ if (edit.type !== "newTown" && edit.type !== "nextTerm" && edit.type !== "guide" && edit.type !== "guideOff" && !playing()) continueswitch (edit.type) {case "building": {const kind = kinds[edit.kind]@@ -454,6 +454,15 @@ export const ApplyEdits = Game.System(events.toast.emit(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)break}+ case "guide":+ resources.guide.update((g) => {+ const fresh = edit.done.filter((id) => !g.done.includes(id))+ return fresh.length === 0 ? g : { ...g, done: [...g.done, ...fresh] }+ })+ break+ case "guideOff":+ resources.guide.update((g) => (g.off === edit.off ? g : { ...g, off: edit.off }))+ breakcase "reserve":resources.policy.update((p) => ({ ...p, reserve: Math.max(0, Math.min(RESERVE_MAX, Math.round(edit.amount))) }))breakdiff --git a/src/ui/dom/host.ts b/src/ui/dom/host.tsindex 7762c3f..8487871 100644--- a/src/ui/dom/host.ts+++ b/src/ui/dom/host.ts@@ -52,7 +52,8 @@ import { GRID } from "../../game/world/iso.ts"import { goodIcon, icon, iconEl, type IconName } from "./kit/icons.ts"import { generate } from "../../game/world/mapgen.ts"import { askOf, priceOf } from "../../game/schedule.ts"-import type { Group, Line, Panel, Stats, Tool, TradeMode, UiValue, View } from "../../view/contracts.ts"+import type { TradeMode } from "../../game/edits.ts"+import type { Group, Line, Panel, Stats, Tool, UiValue, View } from "../../view/contracts.ts"import { emptyPreview } from "../../view/contracts.ts"import { GameScene, type CameraView } from "../../render/three/scene.ts"import { blobOf, cardFacts, drawCard, metaOf, scaled, verdictOf } from "../../platform/share/card.ts"diff --git a/src/view/contracts.ts b/src/view/contracts.tsindex 26a8e13..e3482d5 100644--- a/src/view/contracts.ts+++ b/src/view/contracts.ts@@ -9,6 +9,7 @@ import type { IconName } from "../ui/dom/kit/icons.ts"import type { Point } from "../game/world/iso.ts"import type { Status } from "../game/schema.ts"import type { OverlayCell } from "../render/three/models.ts"+import type { Edit } from "../game/edits.ts"/** How a line of a panel reads: fine, worth a look, wrong, or an aside. */export type Tone = "ok" | "warn" | "bad" | "dim"@@ -60,38 +61,6 @@ export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place" |export const viewIds = ["none", "appeal", "workers", "fire", "health", "order", "condition"] as constexport type View = (typeof viewIds)[number]-/** A change to the town, applied by the simulation (see `ApplyEdits`). */-export type Edit =- /** `open`: show the new building in the panel. */- | { readonly type: "building"; readonly kind: KindId; readonly cell: Point; readonly open: boolean }- | { readonly type: "homes"; readonly cells: ReadonlyArray<Point> }- | { readonly type: "roads"; readonly cells: ReadonlyArray<Point> }- /** Paves the road on each cell (coins, and stone from storage). */- | { readonly type: "pave"; readonly cells: ReadonlyArray<Point> }- /** Lays park ground on each empty cell (or relays a park cell's ground). */- | { readonly type: "ground"; readonly ground: GroundId; readonly cells: ReadonlyArray<Point> }- /** Sets a furnishing on a cell of park. */- | { readonly type: "prop"; readonly prop: PropId; readonly cell: Point }- /** Removes whatever stands on a cell (not rocks, water, or the town hall); on a park, its furnishing first. */- | { readonly type: "remove"; readonly cell: Point }- /** Sets a tier's tax rate, in percent of the usual. */- | { readonly type: "tax"; readonly tier: "settlers" | "citizens"; readonly rate: number }- /** Sells a good to traders beyond the reserve, buys it up to the reserve, or neither; `amount`, up to how much a collection. */- | { readonly type: "trade"; readonly good: GoodId; readonly mode: TradeMode; readonly amount?: number }- /** How much of each good the town keeps before selling, and buys up to. */- | { readonly type: "reserve"; readonly amount: number }- /** Pauses the building on a cell (or closes the home), or sets it back to work. */- | { readonly type: "pause"; readonly cell: Point; readonly on: boolean }- /** Sends the crown what it asked for. */- | { readonly type: "deliver" }- /** Once a term has run out, stands for another: the same town, a new term. */- | { readonly type: "nextTerm" }- /** Upgrades the building on a cell where it stands (see `Kind.upgrade`). */- | { readonly type: "upgrade"; readonly cell: Point }- /** Clears everything and founds a new town on the land a charter describes. */- | { readonly type: "newTown"; readonly charter: CharterValue }--export type TradeMode = "sell" | "buy" | "none"/** What the pointer did, in grid coordinates. */export type Gesture =diff --git a/src/view/present.ts b/src/view/present.tsindex 5c106c9..cb05705 100644--- a/src/view/present.ts+++ b/src/view/present.ts@@ -417,11 +417,13 @@ export const Interact = Game.System(chronicle: Game.System.readResource(Chronicle),appeal: Game.System.readResource(Appeal),pantry: Game.System.readResource(Pantry),- guide: Game.System.writeResource(Guide)+ guide: Game.System.readResource(Guide)},- services: { ui: Game.System.service(Ui) }+ services: { ui: Game.System.service(Ui) },+ /** Guide edits sent but not yet applied by the simulation: they count at once, so the guide moves on before the next step. */+ local: () => ({ guide: { done: new Set<string>(), off: null as boolean | null } })},- ({ queries, resources, services }) => {+ ({ queries, resources, services, local }) => {const ui = services.uiconst grid = resources.grid.get()const rates = resources.policy.get()@@ -1519,10 +1521,16 @@ export const Interact = Game.System(// ── The mayor's guide ──// The page writes what the mayor told it; then the guide puts away what the town has done, and picks the step to show.+ // Only the simulation writes the guide: both go to it as edits, and count here until it has applied them.+ const pending = local.guidefor (const action of ui.guide.splice(0)) {- resources.guide.update((g) =>- action.type === "skip" ? (g.done.includes(action.id) ? g : { ...g, done: [...g.done, action.id] }) : { ...g, off: action.type === "off" }- )+ if (action.type === "skip") {+ pending.done.add(action.id)+ ui.edits.push({ type: "guide", done: [action.id] })+ } else {+ pending.off = action.type === "off"+ ui.edits.push({ type: "guideOff", off: pending.off })+ }}const placedKinds = new Set(buildings.map(({ data }) => data.building.get().kind))const standingKinds = new Set(buildings.filter(({ data }) => !data.site.present && !data.rising.present).map(({ data }) => data.building.get().kind))@@ -1534,7 +1542,10 @@ export const Interact = Game.System(const tile = row.data.tile.get()return met(h, "bread") && met(h, "cloth") && met(h, "faith") && appealAt(cells, tile.x, tile.y) < home.tiers[2].appeal})- const guide = resources.guide.get()+ const saved = resources.guide.get()+ for (const id of saved.done) pending.done.delete(id)+ if (pending.off === saved.off) pending.off = null+ const guide = { done: [...saved.done, ...pending.done], off: pending.off ?? saved.off }const put = new Set(guide.done)/** A road within two cells of water: reckoned only until the guide's road step is put away. */const roadNearWater = () => {@@ -1591,8 +1602,11 @@ export const Interact = Game.System(const playing = f.state === "playing" && !ui.foundingconst newly = playing ? guideDone(facts, put) : []if (newly.length > 0) {- resources.guide.update((g) => ({ ...g, done: [...g.done, ...newly] }))- for (const id of newly) put.add(id)+ ui.edits.push({ type: "guide", done: newly })+ for (const id of newly) {+ put.add(id)+ pending.done.add(id)+ }}// The guide keeps quiet a while after a step is put away; a new town (the clock gone back) starts it afresh.if (t < guidePace.since) Object.assign(guidePace, { shown: null, since: 0, quietUntil: 0 })diff --git a/test/model.test.ts b/test/model.test.tsindex 0c61c6c..78ab2eb 100644--- a/test/model.test.ts+++ b/test/model.test.ts@@ -21,7 +21,7 @@ import { canPlace, cellsOf, DIRS, entrances, GridBuilder, isRoad, key, type Useimport { GRID, inside, type Point } from "../src/game/world/iso.ts"import { load, memoryStorage, save, Storage, World } from "../src/platform/save.ts"import { headless, type Headless, type Snapshot } from "../src/game/headless.ts"-import type { Edit } from "../src/view/contracts.ts"+import type { Edit } from "../src/game/edits.ts"const RUNS = Number(process.env.RUNS ?? 25)/** How large generated scenarios grow: at this size, sequences run to their full length. */