A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Goods flow arrows, salvage and closed homes, and wider desirability
SandroMaglione59b594157639
diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 1af76d1..217aff1 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -88,8 +88,11 @@ Nobody tells you to build it that way; it works best that way.take from it, fading with distance: a smithy, quarry, or mine takes 8beside it and less out to four cells; a sawmill, bakery, mill, orsmokehouse 4; warehouses, farms, a granary, a builder's yard 2. Water and- woods give 2, a market 2 and a chapel 4, the town hall 4, and a paved- street 1 beside it. Ruins and run-down homes take a little. Every point+ woods give 2, and a paved street 1 beside it. The good places carry+ further: a chapel and the town hall give 4 out to two cells before they+ fade (to four), a market 2 out to two. Fine homes lift the homes beside+ them, never themselves: a citizens' home 1, a townhouse 2, up to 3 in all,+ so a good quarter keeps itself up. Ruins and run-down homes take a little. Every pointcounts: below 0 a home holds fewer residents (a twentieth fewer a point,down to half) and pays less (a fortieth a point, down to three quarters);above 0 it pays more, up to a quarter more. A home's panel says what its@@ -103,7 +106,8 @@ Nobody tells you to build it that way; it works best that way.kind in full, each more of it half as much, and one for every twocells), and its ways in from the street (a walk or a square beside aroad: 1.5 each, two count), up to 15, out to 2 cells and one more for- every 6 cells of park, up to 5. A lone statue is worth little; a lawn+ every 6 cells of park, up to 5; its whole worth reaches half that far+ before it fades. A lone statue is worth little; a lawnwith walks in from the street, lamps, and a statue is worth a street ofcitizens.Parks cost upkeep by the cell and by the furnishing: a fine centre is@@ -112,7 +116,7 @@ Nobody tells you to build it that way; it works best that way.- **Tiers.** Settlers live anywhere. A citizens' home needs desirability 5as well as bread, cloth, and faith; a home whose street drops below 5goes back to settlers even with every need met. A **townhouse** of- burghers (12 residents, the best taxes) needs desirability 15 and a+ burghers (12 residents, the best taxes) needs desirability 12 and afire watch, a healer, and a watch house all calling on it. Atdesirability −5 or less a home is squalid and holds fewer people.- **Workers by tier, and the commute.** Settlers do the rough work@@ -206,15 +210,29 @@ with the town, and starts over with a new one.The **town** panel (T, the town button, or the people in the top right) shows the goals, approval,treasury, people, supplies, the crown, goods and trade, and thechronicle, and holds the levers.+- **The goods bar** at the top counts what is in storage. Food and other+ goods often go straight from who makes them to who wants them (a market,+ a workshop), so storage can read 0 while the homes are well fed: the+ arrow beside each good says which way it went over the last minute (made+ and bought against used and sold; → holding steady), reckoned again every+ ten seconds. Click the bar for each good's minute side by side: made,+ used, traded, in storage, and about town (in workshops, markets, baskets,+ and crates).- **Materials** (planks, stone, tools) come from storage: a new building is asite until carriers have brought what it costs, then it goes up.- **Homes** fill with settlers once a road touches them. Settlers need food(fish, smoked fish, or bread); with bread, cloth, and faith on a streetwith desirability 5 a home becomes a two-story citizens' home that holds- and pays twice as much, and on a fine street (15) with every service+ and pays twice as much, and on a fine street (12) with every servicecalling, a three-story townhouse. Cloth is only brought to a street fitfor citizens, however much is in store: the home's panel says so, andwhat the street is short of.+- **Pulling down** a building or a home costs a tenth of what it cost in+ coins, and half its materials (rounded down) go back into storage, to+ build with or sell. A site not yet going up is cancelled instead: its+ coins and whatever was brought to it come back. A home can also be+ **closed** from its panel: it stands empty, pays nothing, and costs the+ town hall nothing, until it is reopened.- **Buildings** need a road at the middle of a side and workers of theircrew from homes within 15 road cells. While one is placed (or selected),the roads its walkers or its workers would use are shown; the homes tooldiff --git a/scripts/check.ts b/scripts/check.tsindex 6b539db..49a8ebf 100644--- a/scripts/check.ts+++ b/scripts/check.ts@@ -284,6 +284,7 @@ const standing = (s: Snapshot, kind: KindId, x: number, y: number, stock: Partias.entities.push({ id, components: c })return id}+const signedText = (n: number) => (n > 0 ? `+${n}` : `${n}`)const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entities.find((e) => e.id === id)// A citizens' home on a fine street stays citizens; a smithy beside it sends it back to settlers.@@ -555,5 +556,77 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entitiescheck("park entrances", open.entrances === 2 && open.value === shut.value + 3, `shut in: ${shut.value}; two walks out to the road: ${open.value}`)}+// Pulling down a sawmill: a tenth of its coins, and half its planks and stone back in storage.+{+ const t = town()+ let mill = { x: 0, y: 0 }+ t.change((s) => {+ const g = gridOf(s)+ mill = find(g, 2, doorOnRoad(g, 2))+ standing(s, "sawmill", mill.x, mill.y)+ })+ const held = () => t.snapshot().entities.find((e) => e.components["Town/TownHall"])!.components["Town/Inventory"].stock+ const coins = () => t.snapshot().resources["Town/Treasury"].coins+ t.run(1)+ const before = { coins: coins(), ...held() }+ t.edit({ type: "remove", cell: mill })+ t.run(0.05)+ const after = { coins: coins(), ...held() }+ const gone = !t.snapshot().entities.some((e) => e.components["Town/Building"]?.kind === "sawmill")+ check("salvage", gone && before.coins - after.coins === 10 && after.planks - before.planks === 1 && after.stone - before.stone === 1,+ `${before.coins - after.coins} coins, +${after.planks - before.planks} planks, +${after.stone - before.stone} stone`)+}++// A closed home stands empty and costs the town hall nothing; reopened, settlers come back.+{+ const t = town()+ let home = 0+ let spot = { x: 0, y: 0 }+ t.change((s) => {+ const g = gridOf(s)+ spot = find(g, 1, besideRoad(g), "house")+ home = homeAt(s, spot.x, spot.y, 1, 4)+ })+ t.run(2)+ const homes = () => t.snapshot().resources["Town/Census"].homes+ const open = homes()+ t.edit({ type: "pause", cell: spot, on: true })+ t.run(2)+ const emptied = entity(t, home)?.components["Town/House"]?.residents+ const closedHomes = homes()+ const closed = Boolean(entity(t, home)?.components["Town/Paused"] !== undefined)+ t.edit({ type: "pause", cell: spot, on: false })+ t.run(30)+ const back = entity(t, home)?.components["Town/House"]?.residents+ check("closing a home", closed && emptied === 0 && closedHomes === open - 1 && back > 0, `residents 4 → ${emptied} closed (homes ${open} → ${closedHomes}), ${back} after reopening`)+}++// Fine homes lift their neighbours, not themselves.+{+ const t = town()+ let a = { x: 0, y: 0 }+ t.change((s) => {+ const g = gridOf(s)+ a = find(g, 1, (x, y) => besideRoad(g)(x, y) && canPlace(g.value(), { x: x + 1, y, size: 1 }) && canPlace(g.value(), { x: x - 1, y, size: 1 }), "house")+ g.claim({ x: a.x + 1, y: a.y, size: 1 }, -1, "house")+ homeAt(s, a.x, a.y, 3, 12)+ homeAt(s, a.x + 1, a.y, 1, 4)+ })+ t.run(1)+ const cells = t.snapshot().resources["Town/Appeal"].cells as Array<number>+ const lone = (() => {+ const u = town()+ u.change((s) => {+ const g = gridOf(s)+ const b = find(g, 1, (x, y) => x === a.x + 1 && y === a.y, "house")+ homeAt(s, b.x, b.y, 1, 4)+ })+ u.run(1)+ return u.snapshot().resources["Town/Appeal"].cells as Array<number>+ })()+ const lift = cells[key(a.x + 1, a.y)]! - lone[key(a.x + 1, a.y)]!+ check("fine homes lift the street", lift === 2, `a townhouse next door: ${signedText(lift)} desirability`)+}+console.log(failures === 0 ? "\nall ends hold" : `\n${failures} failed`)if (failures > 0) process.exit(1)diff --git a/src/appeal.ts b/src/appeal.tsindex 239b963..c3e0715 100644--- a/src/appeal.ts+++ b/src/appeal.ts@@ -5,7 +5,8 @@ import { shippedRules, type Rules } from "./rules/config.ts"* `appeal` in content): industry pushes homes away, parks and a chapel* draw them in. A park is its cells of ground taken together (see* `parkSources`): its reach is measured from its nearest cell. Buildings' effects add up; water and woods count- * once however many are near, and so do paved streets. Plain functions,+ * once however many are near, and so do paved streets. Fine homes lift the+ * homes beside them (not themselves), up to `appeal.homesMost`. Plain functions,* shared by the simulation (which keeps the whole grid, see `Appraise`) and* the page (which explains one cell).*/@@ -20,10 +21,16 @@ export interface AppealSource {readonly size: numberreadonly value: numberreadonly reach: number+ /** Rings it gives its whole value out to before it starts to fade (1 when not given). */+ readonly full?: number/** What it is, for the readout: "park", "smithy", "water". */readonly label: string- /** `sum`: adds up with others; `nature` and `paved`: only the strongest of their kind counts. */- readonly mode: "sum" | "nature" | "paved"+ /**+ * `sum`: adds up with others; `nature` and `paved`: only the strongest of+ * their kind counts; `homes`: adds up, to `appeal.homesMost` at most, and+ * never on the home's own cell.+ */+ readonly mode: "sum" | "nature" | "paved" | "homes"/** A park: the cells it covers, inside the square (x, y, size) around them. */readonly cells?: ReadonlyArray<Point>}@@ -40,18 +47,30 @@ const ringTo = (s: AppealSource, x: number, y: number) => {return best}-/** What a source does at `ring` cells from its footprint: all of it beside it, fading to a little at its reach. */-export const effectAt = (source: { readonly value: number; readonly reach: number }, ring: number): number => {+/**+ * What a source does at `ring` cells from its footprint: all of it out to+ * `full` rings (beside it, when not given), then fading to a little at its+ * reach. A chapel (4, out to 4, full 2) gives 4, 4, 2, 1.+ */+export const effectAt = (source: { readonly value: number; readonly reach: number; readonly full?: number }, ring: number): number => {if (ring > source.reach) return 0- return Math.trunc((source.value * (source.reach - Math.max(1, ring) + 1)) / source.reach)+ const full = Math.max(1, Math.min(source.reach, source.full ?? 1))+ if (ring <= full) return source.value+ return Math.trunc((source.value * (source.reach - ring + 1)) / (source.reach - full + 1))}+/** What a source does to a cell at `ring`: a home's lift is for its neighbours, not itself. */+const effectOf = (s: AppealSource, ring: number) => (s.mode === "homes" && ring === 0 ? 0 : effectAt(s, ring))/** A building of a kind as a source, if it has any effect. */export const buildingSource = (kind: KindId, tile: { readonly x: number; readonly y: number; readonly size: number }, rules: Rules = shippedRules): AppealSource | null => {const a = rules.kinds[kind].appeal- return a ? { ...tile, value: a.value, reach: a.reach, label: rules.kinds[kind].title.toLowerCase(), mode: "sum" } : null+ return a ? { ...tile, value: a.value, reach: a.reach, ...(a.full ? { full: a.full } : {}), label: rules.kinds[kind].title.toLowerCase(), mode: "sum" } : null}+/** A citizens' home or a townhouse lifts the homes beside it; a settlers' cottage does nothing. */+export const homeSource = (tier: 1 | 2 | 3, tile: { readonly x: number; readonly y: number; readonly size?: number }, rules: Rules = shippedRules): AppealSource | null =>+ tier === 1 ? null : { x: tile.x, y: tile.y, size: tile.size ?? 1, ...(tier === 2 ? rules.appeal.citizens : rules.appeal.burghers), label: "fine homes beside it", mode: "homes" }+export const landSource = (what: "water" | "forest" | "paved" | "ruin" | "worn", cell: { readonly x: number; readonly y: number; readonly size?: number }, rules: Rules = shippedRules): AppealSource => ({x: cell.x,y: cell.y,@@ -68,32 +87,35 @@ export const appealGrid = (sources: ReadonlyArray<AppealSource>, rules: Rules =const sum = new Int32Array(GRID * GRID)const nature = new Int32Array(GRID * GRID)const paved = new Int32Array(GRID * GRID)+ const homes = new Int32Array(GRID * GRID)for (const s of sources) {- const into = s.mode === "sum" ? sum : s.mode === "nature" ? nature : paved+ const into = s.mode === "sum" ? sum : s.mode === "nature" ? nature : s.mode === "paved" ? paved : homesfor (let y = Math.max(0, s.y - s.reach); y < Math.min(GRID, s.y + s.size + s.reach); y++) {for (let x = Math.max(0, s.x - s.reach); x < Math.min(GRID, s.x + s.size + s.reach); x++) {- const e = effectAt(s, ringTo(s, x, y))+ const e = effectOf(s, ringTo(s, x, y))if (e === 0) continueconst k = key(x, y)- if (s.mode === "sum") into[k] = into[k]! + e+ if (s.mode === "sum" || s.mode === "homes") into[k] = into[k]! + eelse if (e > 0 ? e > into[k]! : e < into[k]!) into[k] = e}}}- return Array.from({ length: GRID * GRID }, (_, k) => clamp(sum[k]! + nature[k]! + paved[k]!, rules))+ return Array.from({ length: GRID * GRID }, (_, k) => clamp(sum[k]! + nature[k]! + paved[k]! + Math.min(rules.appeal.homesMost, homes[k]!), rules))}/** One cell's desirability and what makes it, strongest first: "park +6", "bakery −4". */export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readonly x: number; readonly y: number }, rules: Rules = shippedRules) => {const parts = new Map<string, number>()const best = { nature: { label: "", value: 0 }, paved: { label: "", value: 0 } }+ let homes = { label: "", value: 0 }for (const s of sources) {- const e = effectAt(s, ringTo(s, cell.x, cell.y))+ const e = effectOf(s, ringTo(s, cell.x, cell.y))if (e === 0) continueif (s.mode === "sum") parts.set(s.label, (parts.get(s.label) ?? 0) + e)+ else if (s.mode === "homes") homes = { label: s.label, value: Math.min(rules.appeal.homesMost, homes.value + e) }else if (Math.abs(e) > Math.abs(best[s.mode].value)) best[s.mode] = { label: s.label, value: e }}- for (const b of [best.nature, best.paved]) if (b.value !== 0) parts.set(b.label, (parts.get(b.label) ?? 0) + b.value)+ for (const b of [best.nature, best.paved, homes]) if (b.value !== 0) parts.set(b.label, (parts.get(b.label) ?? 0) + b.value)const list = [...parts].map(([label, value]) => ({ label, value })).filter((p) => p.value !== 0)list.sort((a, b) => Math.abs(b.value) - Math.abs(a.value))return { value: clamp(list.reduce((n, p) => n + p.value, 0), rules), parts: list }@@ -212,7 +234,8 @@ export const parkSources = (cells: ReadonlyArray<ParkCell>, road?: (x: number, yconst x = Math.min(...xs)const y = Math.min(...ys)const size = Math.max(Math.max(...xs) - x, Math.max(...ys) - y) + 1- return { x, y, size, value: p.value, reach: p.reach, label: "park", mode: "sum", cells: p.cells }+ // A bigger park gives its whole worth further out: half its reach, rounded down.+ return { x, y, size, value: p.value, reach: p.reach, full: Math.max(1, Math.floor(p.reach / 2)), label: "park", mode: "sum", cells: p.cells }})/** Per-minute upkeep paid for a park cell, including its furnishing. */diff --git a/src/art.ts b/src/art.tsindex cefd8b4..1924aa7 100644--- a/src/art.ts+++ b/src/art.ts@@ -1064,6 +1064,8 @@ export interface HouseLook {readonly worn?: boolean/** Its neighbourhood: poor, plain, or fine (see `HouseView`). */readonly band?: "poor" | "plain" | "fine"+ /** Closed by the town: it stands empty, shuttered and greyed. */+ readonly closed?: boolean/** A map view's colour washed over it, when one is shown. */readonly tint?: number | undefined}diff --git a/src/content.ts b/src/content.tsindex e15acb7..024e73e 100644--- a/src/content.ts+++ b/src/content.ts@@ -140,7 +140,7 @@ export interface Kind {readonly service?: { readonly service: ServiceId; readonly seconds: number; readonly range: number }// ── Its neighbourhood ──/** What it does to the desirability of the cells around it, fading out to `reach` cells (see `appeal.ts`). */- readonly appeal?: { readonly value: number; readonly reach: number }+ readonly appeal?: { readonly value: number; readonly reach: number; readonly full?: number }/** Uses up a tool every `wear` jobs, and works at half pace without one. */readonly wear?: number/** Ovens and forges: a fire risk to itself and to homes beside it. */@@ -161,7 +161,7 @@ export const kinds: Readonly<Record<KindId, Kind>> = {category: "storage", size: 3, half: 20, stories: 2, roof: "flat", bays: 2, window: 8, topper: "flag",cost: { coins: 0, materials: {} }, upkeep: 0, workers: 0, crew: "settlers", unlock: free, buildable: false,holds: { accepts: "all", cap: 100 }, carriers: 6,- service: { service: "goods", seconds: 8, range: 20 }, appeal: { value: 4, reach: 3 }+ service: { service: "goods", seconds: 8, range: 20 }, appeal: { value: 4, reach: 4, full: 2 }},warehouse: {id: "warehouse", title: "Warehouse", blurb: "stores goods nearer where they are made and used",@@ -269,13 +269,13 @@ export const kinds: Readonly<Record<KindId, Kind>> = {category: "services", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "flag",cost: { coins: 120, materials: { planks: 6, stone: 2 } }, upkeep: 6, workers: 2, crew: "citizens", unlock: free, buildable: true,holds: { accepts: ["fish", "smoked", "bread", "cloth"], cap: 12 },- service: { service: "goods", seconds: 6, range: 18 }, appeal: { value: 2, reach: 3 }+ service: { service: "goods", seconds: 6, range: 18 }, appeal: { value: 2, reach: 3, full: 2 }},chapel: {id: "chapel", title: "Chapel", blurb: "a walker brings faith to the homes it passes",category: "services", size: 2, half: 12, stories: 2, roof: "flat", bays: 2, window: 6, topper: "cupola",cost: { coins: 200, materials: { planks: 6, stone: 6 } }, upkeep: 10, workers: 1, crew: "citizens", unlock: { residents: 15, citizens: 0 }, buildable: true,- service: { service: "faith", seconds: 8, range: 22 }, appeal: { value: 4, reach: 3 }+ service: { service: "faith", seconds: 8, range: 22 }, appeal: { value: 4, reach: 4, full: 2 }},firewatch: {id: "firewatch", title: "Fire watch", blurb: "a watchman checks homes and workshops along the way for fire; firefighters run to any blaze",@@ -293,7 +293,7 @@ export const kinds: Readonly<Record<KindId, Kind>> = {id: "hospital", title: "Hospital", blurb: "physicians call more often and walk further",category: "services", size: 3, half: 16, stories: 2, roof: "flat", bays: 2, window: 6, topper: "cupola",cost: { coins: 400, materials: { planks: 10, stone: 10, tools: 2 } }, upkeep: 16, workers: 4, crew: "citizens", unlock: { residents: 0, citizens: 40 }, buildable: true,- service: { service: "health", seconds: 4, range: 40 }, appeal: { value: 2, reach: 3 }+ service: { service: "health", seconds: 4, range: 40 }, appeal: { value: 2, reach: 3, full: 2 }},watchhouse: {id: "watchhouse", title: "Watch house", blurb: "a constable walks the streets, keeping order in the homes along the way",@@ -391,7 +391,7 @@ export const home = {tiers: {1: { title: "settlers", residents: 4, tax: 2.5, height: 14, needs: ["food"], appeal: -100 },2: { title: "citizens", residents: 8, tax: 5, height: 26, needs: ["bread", "cloth", "faith"], appeal: 5 },- 3: { title: "burghers", residents: 12, tax: 6.5, height: 38, needs: ["bread", "cloth", "faith"], appeal: 15 }+ 3: { title: "burghers", residents: 12, tax: 6.5, height: 38, needs: ["bread", "cloth", "faith"], appeal: 12 }} as Readonly<Record<Tier, {readonly title: stringreadonly residents: number@@ -445,6 +445,10 @@ export const appeal = {paved: { value: 1, reach: 1 },ruin: { value: -3, reach: 2 },worn: { value: -2, reach: 1 },+ /** A citizens' home and a townhouse lift the homes beside them (never themselves), all told up to `homesMost`. */+ citizens: { value: 1, reach: 1 },+ burghers: { value: 2, reach: 1 },+ homesMost: 3,/** Desirability is reckoned this often. */every: 30,/** And kept within these bounds. */@@ -719,6 +723,14 @@ export const market = { floor: 30, ceiling: 250, perUnit: 1, markup: 1.5 }/** A paused building pays this share of its upkeep. */export const PAUSED_UPKEEP = 0.25+/**+ * Pulling down a standing building or home: a `fee` of what it cost in+ * coins, and `back` of its materials (rounded down) carried back into+ * storage. A site not yet going up is cancelled instead: its coins and+ * whatever was brought to it come back in full.+ */+export const salvage = { fee: 0.1, back: 0.5 }+/** How long each end state's danger has to last, in minutes, before the term ends with it. */export const fate = {/** Victory: every goal held this long. */diff --git a/src/factory.css b/src/factory.cssindex 31639c1..e4fec2f 100644--- a/src/factory.css+++ b/src/factory.css@@ -48,6 +48,26 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.hud .good { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px 4px 6px; background: #eef0ea; border-radius: 6px; cursor: default; }.hud .good .count { min-width: 2.5ch; font-weight: 700; font-size: 13px; }.hud .good.empty { opacity: 0.55; }+.hud .stock { cursor: pointer; }+.hud .stock:hover { border-color: #3d4943; }+.hud .good { cursor: inherit; }+/* Which way a good went over the last minute: room kept for it so the bar does not jump. */+.hud .good .trend { display: inline-block; width: 1ch; margin-left: -3px; font-weight: 700; font-size: 12px; }++/* Under the goods, on a click: the last minute of each, side by side. */+.hud .flow { display: none; flex-direction: column; align-items: stretch; padding: 6px 14px 8px; cursor: pointer; max-width: 500px; }+.hud .flow.open { display: flex; }+.hud .flow .flow-grid { display: grid; grid-template-columns: minmax(9.5em, auto) repeat(5, minmax(6.5ch, auto)); column-gap: 0; font-size: 13px; font-variant-numeric: tabular-nums; }+.hud .flow .flow-grid > * { padding: 6px 0 6px 18px; border-top: 1px solid #e6e9e2; }+.hud .flow .flow-grid > :nth-child(6n + 1) { padding-left: 0; }+.hud .flow .flow-grid > :nth-child(-n + 6) { border-top: 0; padding-top: 4px; }+.hud .flow .flow-grid > b { font-size: 11px; font-weight: 600; letter-spacing: 0.02em; color: #77817a; text-align: right; white-space: nowrap; }+.hud .flow .flow-grid > span:not(.name) { text-align: right; }+.hud .flow .flow-grid i { font-style: normal; color: #c3c8c0; }+.hud .flow .name { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }+.hud .flow .name .trend { margin-left: 2px; }+.hud .flow .sub { margin: 4px 0; font-size: 12px; color: #77817a; }+.hud .trend.steady { color: #a3aaa2; font-weight: 400; }/* ── The toolbar: the town's panel, the tools, the speed ── */.toolbar, .system {diff --git a/src/host.ts b/src/host.tsindex 908e6a6..7594f88 100644--- a/src/host.ts+++ b/src/host.ts@@ -157,8 +157,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste["fish", "smoked", "wheat", "flour", "bread"],["wool", "cloth"]]- stock.title = "Goods in the town's storage · hover one for what it is for"+ stock.title = "Goods in the town's storage, and which way each is going · click for what the town makes and uses"const goodCells = new Map<GoodId, HTMLElement>()+ const goodTrends = new Map<GoodId, HTMLElement>()for (const group of groups) {const cell = el("div", "group")for (const g of group) {@@ -168,9 +169,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst glyph = el("span", "glyph")glyph.innerHTML = goodIcon(g, 18)const count = el("span", "count", "0")- item.append(glyph, count)+ const trend = el("span", "trend")+ item.append(glyph, count, trend)cell.append(item)goodCells.set(g, count)+ goodTrends.set(g, trend)}stock.append(cell)}@@ -191,7 +194,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst goodsChip = el("button", "card goods-chip")goodsChip.title = "The goods in storage"topline.append(bar, goodsChip)- hud.append(topline, stock, request, alarm, ticker)+ // Under the goods, on a click: each good's last minute, made against used, and where it is held.+ const flowCard = el("div", "card flow")+ stock.onclick = (event) => {+ event.stopPropagation()+ flowCard.classList.toggle("open")+ }+ flowCard.onclick = () => flowCard.classList.remove("open")+ hud.append(topline, stock, flowCard, request, alarm, ticker)const people = el("div", "hud right")const folk = el("div", "card bar folk")const approval = el("div", "cell")@@ -789,7 +799,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst parks = section("parks","decor",- `Lay ground, then set furnishings on it. Ground that touches is one park: the more it holds the nicer the streets around it (citizens need 5, townhouses 15). One furnishing counts for every ${parkRules.cellsPerProp} cells.`+ `Lay ground, then set furnishings on it. Ground that touches is one park: the more it holds the nicer the streets around it (citizens need ${home.tiers[2].appeal}, townhouses ${home.tiers[3].appeal}). One furnishing counts for every ${parkRules.cellsPerProp} cells.`)parks.style.borderTop = "3px solid #4f9a6a"const pieces: ReadonlyArray<{ readonly id: GroundId | PropId; readonly piece: ParkPiece; readonly pick: () => void; readonly ground: boolean }> = [@@ -1177,7 +1187,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste? "settlers: fish or bread from a market keeps them; they do the rough work": p.tier === 2? "citizens: they need bread, cloth, and faith, and a street with desirability 5; they do the skilled work"- : "burghers: a citizens' home on a fine street (desirability 15) that every service calls on"+ : `burghers: a citizens' home on a fine street (desirability ${home.tiers[3].appeal}) that every service calls on`)const below = el("div", "")below.append(status, about)@@ -1213,6 +1223,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}syncLines(box, rows, now.lines)if (nextBox && now.type === "house") {+ // A closed home has nobody in it to grow.+ nextBox.style.display = now.closed ? "none" : ""syncLines(nextBox, nextRows, now.blockers)nextNote.textContent = now.blockers.length === 0 ? "nothing stands in the way: it grows when the next resident settles in" : ""nextNote.style.display = now.blockers.length === 0 ? "" : "none"@@ -1236,8 +1248,27 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste})actions.append(pause)}+ if (p.type === "house") {+ const close = el("button", "frame", "Close home")+ close.title = "A closed home stands empty: no taxes, and no cost to the town hall's administration. Reopen it and settlers move back in."+ close.onclick = () => {+ const now = ui.panel+ if (now?.type === "house") ui.edits.push({ type: "pause", cell: now.cell, on: !now.closed })+ }+ live.push(() => {+ const now = ui.panel+ if (now?.type !== "house") return+ close.textContent = now.closed ? "Reopen home" : "Close home"+ close.style.display = now.closable ? "" : "none"+ })+ actions.append(close)+ }const remove = el("button", "frame danger", "Remove")remove.onclick = () => ui.edits.push({ type: "remove", cell: p.cell })+ live.push(() => {+ const now = ui.panel+ remove.title = now?.type === "building" || now?.type === "house" ? now.salvage : ""+ })actions.append(remove)panel.append(actions)}@@ -1731,8 +1762,17 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}for (const [g, count] of goodCells) {count.textContent = String(s.stock[g])- count.parentElement!.classList.toggle("empty", s.stock[g] === 0)+ const way = s.flow ? flowTrend(s.flow, g) : 0+ const trend = goodTrends.get(g)!+ trend.textContent = s.flow ? trendMark(way) : ""+ trend.className = `trend ${trendClass(way)}`+ // Empty storage is only worth dimming when nothing is held anywhere else either.+ count.parentElement!.classList.toggle("empty", s.stock[g] === 0 && (s.flow?.elsewhere[g] ?? 0) === 0)+ count.parentElement!.title = `${goods[g].title}: ${goodHelp[g]}` + (s.flow+ ? `\nLast minute: made ${s.flow.made[g]}, used ${s.flow.used[g]}${s.flow.traded[g] !== 0 ? `, ${s.flow.traded[g] > 0 ? "bought" : "sold"} ${Math.abs(s.flow.traded[g])}` : ""}. ${s.stock[g]} in storage, ${s.flow.elsewhere[g]} about town (in workshops and markets, and on the way).`+ : "")}+ if (flowCard.classList.contains("open")) setHtml(flowCard, flowHtml(s))// The crown's request.request.classList.toggle("show", s.crown.open && s.fate.state === "playing")if (s.crown.open) {@@ -1855,3 +1895,31 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistereturn { app, stage, ui, syncPage, resetPage, input, visit, visitFailed, visiting: () => visiting }}++/** Which way a good went over the last minute: made and bought against used and sold, past a tenth of the traffic either way. */+const flowTrend = (flow: NonNullable<Stats["flow"]>, g: GoodId): number => {+ const net = flow.made[g] + flow.traded[g] - flow.used[g]+ const room = Math.max(1, Math.round((flow.made[g] + flow.used[g] + Math.abs(flow.traded[g])) / 10))+ return net > room ? 1 : net < -room ? -1 : 0+}++/** A good's way over the last minute: up, down, or holding steady. */+const trendMark = (way: number) => (way > 0 ? "↑" : way < 0 ? "↓" : "→")+const trendClass = (way: number) => (way > 0 ? "up" : way < 0 ? "down" : "steady")++/** The goods' last minute, side by side: only the goods the town has touched. */+const flowHtml = (s: Stats): string => {+ const f = s.flow+ if (f === null) return `<p class="sub">Counting the town's goods: the first numbers come in half a minute…</p>`+ const rows = goodIds.filter((g) => f.made[g] + f.used[g] + Math.abs(f.traded[g]) + s.stock[g] + f.elsewhere[g] > 0)+ if (rows.length === 0) return `<p class="sub">Nothing made or used yet.</p>`+ const head = `<span></span><b title="Made by workshops and gatherers over the last minute">made</b><b title="Eaten, worked up, built with, rotted, or sent away over the last minute">used</b><b title="Bought (+) or sold (−) over the last minute">traded</b><b title="In the town hall, warehouses, and granaries">storage</b><b title="In workshops and markets, walkers' baskets, and carriers' crates">about town</b>`+ const cell = (n: number) => `<span>${n === 0 ? `<i>–</i>` : n}</span>`+ const body = rows.map((g) => {+ const way = flowTrend(f, g)+ const traded = f.traded[g] === 0 ? `<i>–</i>` : f.traded[g] > 0 ? `+${f.traded[g]}` : `−${-f.traded[g]}`+ return `<span class="name">${goodIcon(g, 14)}${goods[g].title}<span class="trend ${trendClass(way)}">${trendMark(way)}</span></span>` ++ `${cell(f.made[g])}${cell(f.used[g])}<span>${traded}</span>${cell(s.stock[g])}${cell(f.elsewhere[g])}`+ }).join("")+ return `<div class="flow-grid">${head}${body}</div>`+}diff --git a/src/phone.css b/src/phone.cssindex af39cf6..50035e2 100644--- a/src/phone.css+++ b/src/phone.css@@ -35,6 +35,8 @@/* The goods: folded into the chip; open, every good in a wrapped card under the top line. */.hud .stock { display: none; }+ .hud .flow.open { display: none; }+ .fold-goods .hud .flow.open { display: flex; max-width: min(430px, 100%); }.fold-goods .hud .stock { display: flex; flex-wrap: wrap; gap: 4px 0; padding: 5px; max-width: min(430px, 100%); }.hud .stock .group { flex-wrap: wrap; gap: 3px; padding: 0 3px; }.hud .good { gap: 4px; padding: 3px 7px 3px 4px; }diff --git a/src/present.ts b/src/present.tsindex 28f4de8..dff32e7 100644--- a/src/present.ts+++ b/src/present.ts@@ -7,13 +7,13 @@import { RenderSync } from "@typeonce/bevy-ts-render"import { hazardStrength } from "./render3d/surface-state.ts"-import { appealAt, appealParts, buildingSource, landSource, parkSources, parksOf, type AppealSource, type ParkCell, type ParkValue } from "./appeal.ts"+import { appealAt, appealParts, buildingSource, homeSource, landSource, parkSources, parksOf, type AppealSource, type ParkCell, type ParkValue } from "./appeal.ts"import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.ts"import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "./render3d/views.ts"import type { DoorSet, OverlayCell } from "./render3d/models.ts"import {- BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,- PAVE_COST, propIds, props, risk, RISK_MAX, ROAD_COST, tierHome, total, winters, type GoodId, type Kind, type KindId, type Tier+ amounts, BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,+ PAVE_COST, propIds, props, risk, RISK_MAX, ROAD_COST, tierHome, total, winters, type Amounts, type GoodId, type Kind, type KindId, type Tier} from "./content.ts"import { around, canPlace, cellOf, doors, entrances, isRoad, key, lPath, nearest, reach, useAt, type TileLike } from "./grid.ts"import { GRID, inside, U, type Point } from "./iso.ts"@@ -67,6 +67,7 @@ import {StageService,Status,Stock,+ Flow,Tile,Time,TownHall,@@ -86,6 +87,7 @@ import { Townsfolk } from "./townsfolk.ts"import { emptyPreview, type Alert as Notice, type HitBox, type Legend, type Line, type View } from "./ui.ts"import { blockers as blockersOf, streetAdvice, type InTown, type Served, type Street } from "./rules/explain.ts"import { breadBonus, streetTax, suppliedTaxOf } from "./rules/households.ts"+import { salvageOf, salvageText } from "./rules/salvage.ts"import { rockBlocks, type RockPart } from "./render3d/rock-blocks.ts"import { GUIDE_QUIET, guideDone, guideStep, guideSteps, type GuideFacts, type GuideFocus } from "./rules/guide.ts"import { ticks } from "./content.ts"@@ -191,7 +193,8 @@ const HouseRead = Game.Query({risk: Game.Query.optional(Risk),condition: Game.Query.optional(Condition),burning: Game.Query.optional(Burning),- sick: Game.Query.optional(Sick)+ sick: Game.Query.optional(Sick),+ closed: Game.Query.optional(Paused)}})const RuinRead = Game.Query({ selection: { tile: Game.Query.read(Tile), ruin: Game.Query.read(Ruin) } })@@ -344,6 +347,7 @@ export const Interact = Game.System(treasury: Game.System.readResource(Treasury),ledger: Game.System.readResource(Ledger),stock: Game.System.readResource(Stock),+ flow: Game.System.readResource(Flow),policy: Game.System.readResource(Policy),time: Game.System.readResource(Time),charter: Game.System.readResource(Charter),@@ -600,7 +604,12 @@ export const Interact = Game.System(for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get()))sources.push(...parkSources(parkCells, road))for (const { data } of ruins) sources.push(landSource("ruin", data.tile.get()))- for (const { data } of houses) if ((maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn) sources.push(landSource("worn", data.tile.get()))+ for (const { data } of houses) {+ if (data.site.present || data.rising.present) continue+ if ((maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn) sources.push(landSource("worn", data.tile.get()))+ const fine = data.closed.present ? null : homeSource(data.house.get().tier, data.tile.get())+ if (fine) sources.push(fine)+ }return sources}/** Where a home's residents work: the nearest workplace of their crew in reach that has them. */@@ -759,6 +768,13 @@ export const Interact = Game.System(const h = row.data.house.get()const site = maybe(row.data.site)if (site) return { h, lines: [{ icon: "planks", label: "a site", value: "waiting for its plank", tone: "warn" } as Line], blockers: [] as Array<Line> }+ if (row.data.closed.present) {+ return {+ h,+ lines: [{ icon: "settlers", label: "closed", value: "empty: it pays no taxes and costs the town hall nothing", tone: "warn", note: "reopen it and settlers move back in, a resident at a time" } as Line],+ blockers: [] as Array<Line>+ }+ }const tile = row.data.tile.get()const tier = home.tiers[h.tier]const next = h.tier < 3 ? home.tiers[(h.tier + 1) as Tier] : null@@ -855,17 +871,29 @@ export const Interact = Game.System(return { h, lines, blockers }}+ /** What pulling a building or home down would cost and give back, for the bulldozer and the panel. */+ const salvageFor = (cost: Kind["cost"], site: { readonly owed: Amounts } | undefined) => {+ const s = salvageOf(cost, site?.owed ?? null)+ const said = salvageText(s)+ return `${site ? "cancel" : "pull down"}${said ? `: ${said}` : ""}`+ }const hovered = preview.hoverconst hoveredBuilding = hovered !== null ? buildings.find((row) => row.entity.id === hovered) : undefinedconst hoveredHouse = hovered !== null ? houses.find((row) => row.entity.id === hovered) : undefinedconst hoveredRuin = hovered !== null ? ruins.find((row) => row.entity.id === hovered) : undefinedif (hoveredBuilding) {const { kind, status, problem } = describeBuilding(hoveredBuilding)- preview.tooltip = `${kind.title.toLowerCase()} · ${problem ?? status}`+ preview.tooltip = ui.tool === "bulldoze"+ ? `${kind.title.toLowerCase()} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(kind.cost, maybe(hoveredBuilding.data.site))}`+ : `${kind.title.toLowerCase()} · ${problem ?? status}`} else if (hoveredHouse) {const h = hoveredHouse.data.house.get()const t = hoveredHouse.data.tile.get()- preview.tooltip = `${tierHome[h.tier]} · ${h.residents} residents · desirability ${appealAt(cells, t.x, t.y)}${hoveredHouse.data.burning.present ? " · on fire!" : hoveredHouse.data.sick.present ? " · sick" : ""}`+ preview.tooltip = ui.tool === "bulldoze"+ ? `${tierHome[h.tier]} · ${salvageFor(home.cost, maybe(hoveredHouse.data.site))}`+ : hoveredHouse.data.closed.present+ ? `${tierHome[h.tier]} · closed`+ : `${tierHome[h.tier]} · ${h.residents} residents · desirability ${appealAt(cells, t.x, t.y)}${hoveredHouse.data.burning.present ? " · on fire!" : hoveredHouse.data.sick.present ? " · sick" : ""}`} else if (hoveredRuin) {preview.tooltip = `ruin · ${hoveredRuin.data.ruin.get().cause} · bulldoze to clear`} else if (hovered !== null && ui.tool === "select" && parkRows.some((row) => row.entity.id === hovered)) {@@ -901,11 +929,17 @@ export const Interact = Game.System(problem,lines,pausable,- paused: pickedBuilding.data.paused.present+ paused: pickedBuilding.data.paused.present,+ salvage: salvageFor(kind.cost, maybe(pickedBuilding.data.site))}} else if (pickedHouse) {const { h, lines, blockers } = describeHouse(pickedHouse)- ui.panel = { type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines, blockers }+ ui.panel = {+ type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines, blockers,+ closable: !pickedHouse.data.site.present && !pickedHouse.data.rising.present && !pickedHouse.data.burning.present,+ closed: pickedHouse.data.closed.present,+ salvage: salvageFor(home.cost, maybe(pickedHouse.data.site))+ }} else if (pickedPark && picked) {ui.panel = {type: "park",@@ -1194,6 +1228,8 @@ export const Interact = Game.System(return row ? { at: row.data.tile.get(), id: row.entity.id } : { at: null, id: null }}const shown = step ? focusOf(step.focus) : null+ const flowNow = resources.flow.get().last+ const flowHeld = resources.flow.get().heldui.stats = {coins,taxes: ledger.taxes,@@ -1261,6 +1297,7 @@ export const Interact = Game.System(},goals: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net: steadyNet(resources.history.get().samples, net), approval: mood.approval }),larder: larder(stock),+ flow: flowNow === null ? null : { ...flowNow, elsewhere: amounts(Object.fromEntries(goodIds.map((g) => [g, Math.max(0, flowHeld[g] - stock[g])]))) },eaten: pantry.eatenLast,rotted: pantry.rottedLast,sick: census.sick,@@ -1510,6 +1547,7 @@ export const Animate = Game.System(sick: Number(data.sick.present)},band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain",+ closed: data.closed.present,tint: services.ui.tints.get(entity.id)},emphasis(entity.id)diff --git a/src/render3d/views.ts b/src/render3d/views.tsindex d36826d..3804c13 100644--- a/src/render3d/views.ts+++ b/src/render3d/views.ts@@ -181,6 +181,9 @@ export class BuildingView extends WorldView {}+/** A closed home, washed a cold grey: nobody lives there. */+const CLOSED_SHADE = 0xa3abb6+export class HouseView extends WorldView {private body: ModelHandleprivate plate: ModelHandle@@ -214,7 +217,7 @@ export class HouseView extends WorldView {this.effects.group.userData.tier=look.tier;this.group.add(this.effects.group)}this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)- this.shade=0xffffff+ this.shade=look.closed?CLOSED_SHADE:0xffffffthis.viewTint = look.tint ?? nullthis.emphasis(emphasis)}diff --git a/src/rules/config.ts b/src/rules/config.tsindex a10a8e0..735493b 100644--- a/src/rules/config.ts+++ b/src/rules/config.ts@@ -14,7 +14,7 @@ const inputs = () => ({spoils: content.spoils, trade: content.trade, tradeLoad: content.TRADE_LOAD, transport,stepSeconds: content.STEP_SECONDS, ledgerTicks: content.LEDGER_TICKS, spoilTicks: content.SPOIL_TICKS,commute: content.COMMUTE, apprentice: content.APPRENTICE, toolStock: content.TOOL_STOCK,- conditionMax: content.CONDITION_MAX, riskMax: content.RISK_MAX, pausedUpkeep: content.PAUSED_UPKEEP,+ conditionMax: content.CONDITION_MAX, riskMax: content.RISK_MAX, pausedUpkeep: content.PAUSED_UPKEEP, salvage: content.salvage,buildTicks: content.BUILD_TICKS, roadCost: content.ROAD_COST, paveCost: content.PAVE_COST, pavedPace: content.PAVED_PACE,grown: content.GROWN, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,spreadTicks: content.ticks(1.5), growTicks: 10diff --git a/src/rules/salvage.ts b/src/rules/salvage.tsnew file mode 100644index 0000000..e415edf--- /dev/null+++ b/src/rules/salvage.ts@@ -0,0 +1,31 @@+import type { GoodId, Kind } from "../content.ts"+import { shippedRules, type Rules } from "./config.ts"++/** What pulling something down costs, and what comes back into storage. */+export interface Salvage {+ /** Coins it costs (negative: coins back, for a cancelled site). */+ readonly fee: number+ readonly back: Partial<Record<GoodId, number>>+}++/**+ * Pulling down what was built at `cost`: a standing one costs a share of its+ * coins and gives back part of its materials (see `salvage` in content); a+ * site still owed materials (`owed`) is cancelled, and its coins and what+ * was already brought to it come back whole.+ */+export const salvageOf = (cost: Kind["cost"], owed: Partial<Record<GoodId, number>> | null = null, rules: Rules = shippedRules): Salvage => {+ const back: Partial<Record<GoodId, number>> = {}+ for (const [g, n] of Object.entries(cost.materials) as Array<[GoodId, number]>) {+ const k = owed ? n - (owed[g] ?? 0) : Math.floor(n * rules.salvage.back)+ if (k > 0) back[g] = k+ }+ return { fee: owed ? -cost.coins : Math.ceil(cost.coins * rules.salvage.fee), back }+}++/** "−25 coins · 2 planks, 3 stone back", for the bulldozer's tooltip and the toast. */+export const salvageText = (s: Salvage): string => {+ const goods = Object.entries(s.back).map(([g, n]) => `${n} ${g}`).join(", ")+ const coins = s.fee > 0 ? `−${s.fee} coins` : s.fee < 0 ? `+${-s.fee} coins` : ""+ return [coins, goods ? `${goods} back` : ""].filter((p) => p !== "").join(" · ")+}diff --git a/src/schema.ts b/src/schema.tsindex d1e76b2..d25209e 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -336,6 +336,35 @@ export interface GridValue {export const Grid = Descriptor.TransientResource<GridValue>()("Town/Grid")/** Goods in the town's storage, summed every step. */export const Stock = Descriptor.TransientResource<Amounts>()("Town/Stock")+/** Ten seconds of goods: what the town held as it began, what was made, and what was traded. */+export interface FlowSlice {+ readonly start: Amounts+ readonly made: Amounts+ readonly traded: Amounts+}+/**+ * Where the town's goods go, over the last minute, a slice of `FLOW_SLICE`+ * at a time (not saved: it starts over on a load). `made` by workshops and+ * gatherers and `traded` (bought less sold) are counted into the slice under+ * way, which began at `since` holding `start`; `held` is everything the+ * town holds now, in storage or not (workshops, markets, walkers' baskets,+ * carriers' crates). What was used (eaten, worked up, built with, rotted,+ * sent to the crown) is what is left over: `start + made + traded − held`.+ */+export interface FlowValue {+ /** Which town it counts (its seed and founding step): a new or loaded town starts over. */+ readonly town: string+ readonly since: number+ readonly start: Amounts | null+ readonly made: Amounts+ readonly traded: Amounts+ readonly held: Amounts+ /** The last minute's slices, oldest first. */+ readonly slices: ReadonlyArray<FlowSlice>+ /** A minute's worth over the slices kept, or `null` before there are enough to say. */+ readonly last: { readonly made: Amounts; readonly used: Amounts; readonly traded: Amounts } | null+}+export const Flow = Descriptor.TransientResource<FlowValue>()("Town/Flow")// ── Host services ─────────────────────────────────────────────────────────@@ -360,7 +389,7 @@ export const Game = Schema.bind(},resources: {Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Guide, Appeal, Pantry, Fires,- Grid, Stock+ Grid, Stock, Flow},relations: { WalkerOf, FieldOf }}),diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex bcccf2a..8debbf0 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -12,7 +12,8 @@ import { amounts, goodIds, RESERVE_MAX, TAX_STEPS, type Amounts, type Kind, typeimport { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"import { inside } from "../iso.ts"import { generate } from "../mapgen.ts"-import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused, Policy, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui } from "../schema.ts"+import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rng, Site, Status, Stock, Storage, Time, TownHall, Treasury, Ui } from "../schema.ts"+import { salvageOf, salvageText } from "../rules/salvage.ts"import { elapsed, rollWinters, TileRead, useOf, write } from "./shared.ts"import { crownGap, foundedFate } from "./term.ts"@@ -34,7 +35,8 @@ export const ApplyEdits = Game.System(paved: Game.Query({ selection: { paved: Game.Query.read(Paved) } }),parks: Game.Query({ selection: { park: Game.Query.write(Park) } }),halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } }),- buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused) } }),+ /** Whatever was built at a cost, standing or a site: what pulling it down gives back. */+ built: Game.Query({ selection: { building: Game.Query.optional(Building), house: Game.Query.optional(House), site: Game.Query.optional(Site), paused: Game.Query.optional(Paused) } }),stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] })},resources: {@@ -101,6 +103,23 @@ export const ApplyEdits = Game.System(}}}+ /** Puts goods into storage at once, where there is most room; returns how many found none. */+ const stash = (materials: Partial<Record<string, number>>) => {+ let lost = 0+ for (const [g, n] of Object.entries(materials) as Array<[keyof Amounts, number]>) {+ let owed = n+ for (const { data } of [...queries.stores.each()].sort((a, b) => a.data.inventory.get().stock[g] - b.data.inventory.get().stock[g])) {+ if (owed <= 0) break+ const inv = data.inventory.get()+ const k = Math.max(0, Math.min(owed, inv.cap - inv.stock[g]))+ if (k > 0) data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] + k } })+ left[g] = (left[g] ?? 0) + k+ owed -= k+ }+ lost += owed+ }+ return lost+ }/** Fells the trees under a tile about to be built on. */const fell = (tile: { x: number; y: number; size: number }) => {for (const c of cellsOf(tile)) {@@ -256,6 +275,20 @@ export const ApplyEdits = Game.System(furnished.data.park.set({ ...furnished.data.park.get(), prop: "none" })break}+ // A building or a home: a fee, and part of its materials back (a site's, all of it).+ const built = queries.built.get(owner)+ if (built.ok && (built.value.data.building.present || built.value.data.house.present)) {+ const b = maybe(built.value.data.building)+ const s = salvageOf(b ? kinds[b.kind].cost : home.cost, maybe(built.value.data.site)?.owed ?? null, rules)+ if (s.fee > 0 && coins < s.fee) {+ ui.toast(`Pulling it down costs ${s.fee} coins`)+ break+ }+ coins -= s.fee+ const lost = stash(s.back)+ const said = salvageText(s)+ if (said !== "") ui.toast(`${built.value.data.site.present ? "Cancelled" : "Pulled down"} · ${said}${lost > 0 ? ` (${lost} found no room in storage)` : ""}`)+ }// A building's walkers and a farm's fields are its children, and go with it.commands.despawn(owner)entities.delete(owner)@@ -281,10 +314,13 @@ export const ApplyEdits = Game.System(breakcase "pause": {const owner = ownerAt(grid.value(), edit.cell.x, edit.cell.y)- const row = queries.buildings.each().find((b) => b.entity.id === owner)- if (!row || halls.has(owner) || row.data.paused.present === edit.on) break- if (edit.on) commands.insert(row.entity.id, Game.Command.entry(Paused, {}))- else commands.remove(row.entity.id, Paused)+ // A building stops work; a home is closed, and stands empty (see `Households`).+ const id = entities.get(owner)+ const row = id === undefined ? undefined : queries.built.get(id)+ if (!row?.ok || halls.has(owner) || row.value.data.site.present || row.value.data.paused.present === edit.on) break+ if (!row.value.data.building.present && !row.value.data.house.present) break+ if (edit.on) commands.insert(row.value.entity.id, Game.Command.entry(Paused, {}))+ else commands.remove(row.value.entity.id, Paused)break}case "deliver": {diff --git a/src/sim/hazards.ts b/src/sim/hazards.tsindex a1c2445..69071d2 100644--- a/src/sim/hazards.ts+++ b/src/sim/hazards.ts@@ -11,13 +11,13 @@ import { near, riskIncrements } from "../rules/risks.ts"*/import * as Random from "@typeonce/bevy-ts-math/Random"-import { appealGrid, appealAt, buildingSource, landSource, parkSources, type AppealSource } from "../appeal.ts"+import { appealGrid, appealAt, buildingSource, homeSource, landSource, parkSources, type AppealSource } from "../appeal.ts"import { ruinDraft } from "../archetypes.ts"import { goodIds, risk, type GoodId } from "../content.ts"import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"import { counted, placeName, type Landmark } from "../places.ts"import type { Point } from "../iso.ts"-import { Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Rules, Grid, House, Inventory, Mood, Park, Paved, Rescue, Rising, Risk, Rng, Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, WalkerOf, Water, maybe } from "../schema.ts"+import { Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Rules, Grid, House, Inventory, Mood, Park, Paused, Paved, Rescue, Rising, Risk, Rng, Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, WalkerOf, Water, maybe } from "../schema.ts"import { elapsed, seasonAt, write } from "./shared.ts"// ── Desirability ──────────────────────────────────────────────────────────@@ -34,7 +34,7 @@ export const Appraise = Game.System(parks: Game.Query({ selection: { tile: Game.Query.read(Tile), park: Game.Query.read(Park) } }),roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),ruins: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Ruin] }),- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition) }, with: [House], without: [Site, Rising] })+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition), house: Game.Query.read(House), closed: Game.Query.optional(Paused) }, without: [Site, Rising] })},resources: { time: Game.System.readResource(Time), appeal: Game.System.writeResource(Appeal) },services: { rules: Game.System.service(Rules) }@@ -55,7 +55,11 @@ export const Appraise = Game.System(const roads = new Set(queries.roads.each().map(({ data }) => `${data.tile.get().x},${data.tile.get().y}`))sources.push(...parkSources(queries.parks.each().map(({ data }) => ({ ...data.tile.get(), ...data.park.get() })), (x, y) => roads.has(`${x},${y}`), rules))for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get(), rules))- for (const { data } of queries.homes.each()) if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get(), rules))+ for (const { data } of queries.homes.each()) {+ if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get(), rules))+ const fine = data.closed.present ? null : homeSource(data.house.get().tier, data.tile.get(), rules)+ if (fine) sources.push(fine)+ }resources.appeal.set({ cells: appealGrid(sources, rules) })})@@ -79,7 +83,8 @@ export const Hazards = Game.System(house: Game.Query.optional(House),building: Game.Query.optional(Building),sick: Game.Query.optional(Sick),- burning: Game.Query.optional(Burning)+ burning: Game.Query.optional(Burning),+ paused: Game.Query.optional(Paused)},without: [Site, Rising]}),@@ -151,6 +156,8 @@ export const Hazards = Game.System(if (data.burning.present) continueconst tile = data.tile.get()const h = maybe(data.house)+ // A closed home has nobody in it to fall sick, steal, or knock over a lamp.+ if (h && data.paused.present) continueconst b = maybe(data.building)const r = { ...data.risk.get() }const increments = riskIncrements({diff --git a/src/sim/index.ts b/src/sim/index.tsindex ab16c3e..aa4fafa 100644--- a/src/sim/index.ts+++ b/src/sim/index.ts@@ -78,7 +78,8 @@ export const blankResources = () => ({Pantry: { eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 },Fires: { fires: [], next: 1 },Grid: { owner: [], use: [] },- Stock: amounts({})+ Stock: amounts({}),+ Flow: { town: "", since: 0, start: null, made: amounts({}), traded: amounts({}), held: amounts({}), slices: [], last: null }})export { CELL_STEPS, elapsed, seasonAt, termTicks, winterOf } from "./shared.ts"diff --git a/src/sim/term.ts b/src/sim/term.tsindex f10837c..6d91110 100644--- a/src/sim/term.ts+++ b/src/sim/term.ts@@ -7,7 +7,7 @@ import { shippedRules } from "../rules/config.ts"*/import { crown, HISTORY_TICKS, ticks, WINTER_WARNING, type GoodId } from "../content.ts"import * as Random from "@typeonce/bevy-ts-math/Random"-import { Building, Census, Charter, Chronicle, Crown, Fate, Game, Rules, History, House, Inventory, Ledger, Mood, Pantry, Policy, Recipe, Rising, Rng, Site, Stock, Storage, Time, Treasury } from "../schema.ts"+import { Building, Census, Charter, Chronicle, Crown, Fate, Game, Rules, History, House, Inventory, Ledger, Mood, Pantry, Paused, Policy, Recipe, Rising, Rng, Site, Stock, Storage, Time, Treasury } from "../schema.ts"import { elapsed, seasonAt, termTicks, write } from "./shared.ts"// ── Time ──────────────────────────────────────────────────────────────────@@ -147,7 +147,7 @@ export const Requests = Game.System(export const Approve = Game.System("Town/Approve",{- queries: { homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }) },+ queries: { homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising, Paused] }) },resources: {time: Game.System.readResource(Time),charter: Game.System.readResource(Charter),diff --git a/src/sim/town.ts b/src/sim/town.tsindex 2346487..35579cd 100644--- a/src/sim/town.ts+++ b/src/sim/town.ts@@ -6,7 +6,8 @@ import { tradeCollection } from "../rules/trade.ts"*/import { appealAt, parkUpkeep } from "../appeal.ts"import { doors, key, reach } from "../grid.ts"-import { Appeal, Building, Burning, Census, Charter, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, maybe } from "../schema.ts"+import { amounts, goodIds, type GoodId } from "../content.ts"+import { Appeal, Building, Burning, Census, Charter, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, maybe } from "../schema.ts"import { connected, elapsed, seasonAt } from "./shared.ts"import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, taxOf, tierFor } from "../rules/households.ts"@@ -28,7 +29,8 @@ export const Households = Game.System(house: Game.Query.write(House),risk: Game.Query.optional(Risk),sick: Game.Query.optional(Sick),- burning: Game.Query.optional(Burning)+ burning: Game.Query.optional(Burning),+ closed: Game.Query.optional(Paused)},without: [Site, Rising]})@@ -55,7 +57,8 @@ export const Households = Game.System(for (const { data } of queries.homes.each()) {const h = data.house.get()const next = ageNeeds(h, eat)- if (data.burning.present) next.residents = 0+ // A home on fire, or closed by the town, stands empty.+ if (data.burning.present || data.closed.present) next.residents = 0else if (next.clock % home.settle === 0) {const tile = data.tile.get()const desirability = appealAt(cells, tile.x, tile.y)@@ -83,7 +86,8 @@ export const Collect = Game.System("Town/Collect",{queries: {- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising] }),+ /** A closed home pays nothing and costs the town hall nothing. */+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Paused] }),buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused) }, without: [Site] }),halls: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [TownHall] }),stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] }),@@ -96,7 +100,8 @@ export const Collect = Game.System(policy: Game.System.readResource(Policy),market: Game.System.writeResource(Market),treasury: Game.System.writeResource(Treasury),- ledger: Game.System.writeResource(Ledger)+ ledger: Game.System.writeResource(Ledger),+ flow: Game.System.writeResource(Flow)},services: { rules: Game.System.service(Rules) }},@@ -127,7 +132,15 @@ export const Collect = Game.System(const stores = queries.stores.each()const traded = tradeCollection(stores.map(({ data }) => data.inventory.get()), policy, resources.market.get().prices,resources.treasury.get().coins + baseCollection(taxes, upkeep, homes, rules).delta, rules)- for (const [i, row] of stores.entries()) row.data.inventory.set(traded.stores[i]!)+ // What changed hands, for the minute's flow of goods: bought less sold.+ const moved: Partial<Record<GoodId, number>> = {}+ for (const [i, row] of stores.entries()) {+ const before = row.data.inventory.get().stock+ const after = traded.stores[i]!.stock+ for (const g of goodIds) if (after[g] !== before[g]) moved[g] = (moved[g] ?? 0) + after[g] - before[g]+ row.data.inventory.set(traded.stores[i]!)+ }+ if (Object.keys(moved).length > 0) resources.flow.update((f) => ({ ...f, traded: amounts(Object.fromEntries(goodIds.map((g) => [g, f.traded[g] + (moved[g] ?? 0)]))) }))resources.market.set({ prices: traded.prices })resources.treasury.set({ coins: traded.coins })resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(traded.traded / share), upkeep: Math.round(upkeep), admin })@@ -138,7 +151,7 @@ export const TakeCensus = Game.System("Town/TakeCensus",{queries: {- homes: Game.Query({ selection: { house: Game.Query.read(House), sick: Game.Query.optional(Sick) }, without: [Site, Rising] }),+ homes: Game.Query({ selection: { house: Game.Query.read(House), sick: Game.Query.optional(Sick) }, without: [Site, Rising, Paused] }),workplaces: Game.Query({ selection: { staff: Game.Query.read(Staff) }, without: [Site, Rising] }),burning: Game.Query({ selection: { burning: Game.Query.read(Burning) } })},diff --git a/src/sim/walkers.ts b/src/sim/walkers.tsindex c9b4e9e..7d6ad8b 100644--- a/src/sim/walkers.ts+++ b/src/sim/walkers.ts@@ -181,7 +181,7 @@ export const Wander = Game.System({queries: {walkers: Game.Query({ selection: { route: Game.Query.write(Route), roam: Game.Query.write(Roam), home: Game.Query.readRelation(WalkerOf) } }),- homes: Game.Query({ selection: { house: Game.Query.write(House) }, without: [Site, Rising] }),+ homes: Game.Query({ selection: { house: Game.Query.write(House) }, without: [Site, Rising, Paused] }),cared: Game.Query({selection: { risk: Game.Query.write(Risk), condition: Game.Query.write(Condition), sick: Game.Query.optional(Sick) },without: [Site, Rising]diff --git a/src/sim/work.ts b/src/sim/work.tsindex 4d9f1aa..f3f0d5e 100644--- a/src/sim/work.ts+++ b/src/sim/work.ts@@ -9,8 +9,14 @@ import * as Random from "@typeonce/bevy-ts-math/Random"import { fieldDraft, treeDraft } from "../archetypes.ts"import { amounts, crewOf, goodIds, ticks, total, type Amounts, type Crew } from "../content.ts"++/** The flow of goods is counted in slices this many seconds long, and the last `FLOW_SLICES` of them (a minute) are kept. */+const FLOW_SLICE = 10+const FLOW_SLICES = 6++const each = (f: (g: (typeof goodIds)[number]) => number): Amounts => Object.fromEntries(goodIds.map((g) => [g, f(g)])) as Amountsimport { around, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../grid.ts"-import { Building, Burning, Charter, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue } from "../schema.ts"+import { Building, Burning, Charter, Errand, Flow, Roam, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue } from "../schema.ts"import { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"import { assignWorkers, equipmentPace, effort, paced } from "../rules/production.ts"@@ -52,12 +58,25 @@ export const IndexGrid = Game.System(})-/** The goods in every storage, summed. */+/**+ * The goods in every storage, summed; and everything the town holds,+ * anywhere, for the minute's `Flow`, which closes every minute.+ */export const CountStock = Game.System("Town/CountStock",{- queries: { stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] }) },- resources: { stock: Game.System.writeResource(Stock) }+ queries: {+ stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] }),+ shelves: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, without: [Site, Rising] }),+ baskets: Game.Query({ selection: { roam: Game.Query.read(Roam) } }),+ crates: Game.Query({ selection: { errand: Game.Query.read(Errand) } })+ },+ resources: {+ time: Game.System.readResource(Time),+ charter: Game.System.readResource(Charter),+ stock: Game.System.writeResource(Stock),+ flow: Game.System.writeResource(Flow)+ }},({ queries, resources }) => {const sum: Record<string, number> = { ...amounts({}) }@@ -66,6 +85,46 @@ export const CountStock = Game.System(for (const g of goodIds) sum[g] = (sum[g] ?? 0) + s[g]}resources.stock.set(sum as Amounts)++ const held: Record<string, number> = { ...amounts({}) }+ for (const { data } of queries.shelves.each()) {+ const s = data.inventory.get().stock+ for (const g of goodIds) held[g] = held[g]! + s[g]+ }+ for (const { data } of queries.baskets.each()) {+ const b = data.roam.get().basket+ for (const g of goodIds) held[g] = held[g]! + b[g]+ }+ for (const { data } of queries.crates.each()) {+ const e = data.errand.get()+ held[e.good] = held[e.good]! + e.count+ }+ const tick = resources.time.get().tick+ const charter = resources.charter.get()+ const town = `${charter.seed}:${charter.founded}`+ const f = resources.flow.get()+ const now = held as Amounts+ // A new or loaded town, or the clock gone back: start counting again from here.+ if (f.town !== town || tick < f.since || f.start === null) {+ resources.flow.set({ town, since: tick, start: now, made: amounts({}), traded: amounts({}), held: now, slices: [], last: null })+ return+ }+ if (tick - f.since < ticks(FLOW_SLICE)) {+ resources.flow.set({ ...f, held: now })+ return+ }+ // A slice is done: the last minute rolls on by one, and is reckoned again.+ const slices = [...f.slices, { start: f.start, made: f.made, traded: f.traded }].slice(-FLOW_SLICES)+ const enough = slices.length >= FLOW_SLICES / 2+ const scale = FLOW_SLICES / slices.length+ const over = (key: "made" | "traded") => each((g) => slices.reduce((n, s) => n + s[key][g], 0))+ const made = over("made"), traded = over("traded")+ const used = each((g) => Math.max(0, slices[0]!.start[g] + made[g] + traded[g] - now[g]))+ const perMinute = (a: Amounts) => each((g) => Math.round(a[g] * scale))+ resources.flow.set({+ town, since: tick, start: now, made: amounts({}), traded: amounts({}), held: now, slices,+ last: enough ? { made: perMinute(made), used: perMinute(used), traded: perMinute(traded) } : null+ })})@@ -226,12 +285,13 @@ export const Work = Game.System(rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),fields: Game.Query({ selection: { field: Game.Query.write(Field) } })},- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter), flow: Game.System.writeResource(Flow) },services: { rules: Game.System.service(Rules) }},({ queries, resources, commands, services }) => {const rules = services.rulesconst { kinds, winters, grown: GROWN } = rules+ const made: Record<string, number> = {}const grid = resources.grid.get()const tick = resources.time.get().tick@@ -312,6 +372,7 @@ export const Work = Game.System(if (progress > recipe.period * staff.needed) {recipe = { ...recipe, progress: 0, made: recipe.made + 1 }stock = { ...stock, [recipe.output]: stock[recipe.output] + recipe.batch }+ made[recipe.output] = (made[recipe.output] ?? 0) + recipe.batch// Every so many jobs wear out a tool.if (kind.wear && recipe.made % kind.wear === 0 && stock.tools > 0) stock = { ...stock, tools: stock.tools - 1 }} else recipe = { ...recipe, progress }@@ -333,6 +394,7 @@ export const Work = Game.System(if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })if (data.status.get() !== status) data.status.set(status)}+ if (Object.keys(made).length > 0) resources.flow.update((f) => ({ ...f, made: each((g) => f.made[g] + (made[g] ?? 0)) }))})diff --git a/src/ui.ts b/src/ui.tsindex cec0966..b423ea9 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -66,7 +66,7 @@ export type Edit =| { 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 sets it back to work. */+ /** 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" }@@ -122,6 +122,8 @@ export type Panel =/** Whether it can be paused (not the town hall, not a site), and whether it is. */readonly pausable: booleanreadonly paused: boolean+ /** What pulling it down costs and gives back: "pull down: −25 coins · 2 planks back". */+ readonly salvage: stringreadonly lines: ReadonlyArray<Line>}| {@@ -129,6 +131,10 @@ export type Panel =readonly id: numberreadonly cell: Pointreadonly tier: Tier+ /** Whether it can be closed (standing, not on fire), and whether it is: a closed home stands empty and costs nothing. */+ readonly closable: boolean+ readonly closed: boolean+ readonly salvage: stringreadonly lines: ReadonlyArray<Line>/** What keeps it from the next tier, a line each; empty when nothing does (or there is no next tier). */readonly blockers: ReadonlyArray<Line>@@ -239,6 +245,14 @@ export interface Stats {}readonly goals: ReadonlyArray<{ readonly text: string; readonly value: string; readonly met: boolean }>readonly larder: number+ /**+ * Each good over the last minute: made, used (eaten, worked up, built+ * with, rotted, sent away), and bought less sold; and how much the town+ * holds outside storage now (workshops, markets, baskets, crates). A+ * rolling minute, reckoned again every ten seconds; `null` for the+ * first half minute.+ */+ readonly flow: { readonly made: Amounts; readonly used: Amounts; readonly traded: Amounts; readonly elsewhere: Amounts } | null/** Food the town ate, and food that rotted in store, over the last minute. */readonly eaten: numberreadonly rotted: numberdiff --git a/test/balance-model.test.ts b/test/balance-model.test.tsindex 26d5cd5..256b6e7 100644--- a/test/balance-model.test.ts+++ b/test/balance-model.test.ts@@ -129,9 +129,10 @@ test("the mathematical plan reaches citizens through ordinary game construction"const rules = resolveRules(), { scenario, builds } = buildScenario(rules)const r = verifyBuilds({ rules, scenario }, builds)assert.deepEqual(r.messages, [])- assert.equal(r.actual.at(-1)!.citizens, 32)+ // 32 in citizens' homes, and 12 more once fine homes lift one of them past the townhouse threshold.+ assert.equal(r.actual.at(-1)!.citizens, 44)assert(r.firstCitizenSecond !== null && r.firstCitizenSecond <= 300)- assert.equal(r.prediction.rows.at(-1)!.citizens, 32)+ assert.equal(r.prediction.rows.at(-1)!.citizens, 44)assert(r.prediction.assumptions.length > 0)assert.equal(r.errors.length, r.actual.length)})diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.tsindex 4558210..2e3a568 100644--- a/tools/balance/model/analyze.ts+++ b/tools/balance/model/analyze.ts@@ -1,5 +1,5 @@import { amounts, goodIds, type GoodId, type WinterId } from "../../../src/content.ts"-import { appealAt, appealGrid, buildingSource, landSource, parkSources, parkUpkeep } from "../../../src/appeal.ts"+import { appealAt, appealGrid, buildingSource, homeSource, landSource, parkSources, parkUpkeep } from "../../../src/appeal.ts"import { doors, nearest, reach } from "../../../src/grid.ts"import { assignWorkers, type Assignment } from "../../../src/rules/production.ts"import { baseCollection, wantsCitizenGoods, mealRate, refreshLevel, taxOf, tierFor } from "../../../src/rules/households.ts"@@ -33,7 +33,11 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptionsfor (const l of s.land) if (l.type === "water" || l.type === "tree") sources.push(landSource(l.type === "tree" ? "forest" : "water", l.tile, rules))for (const r of s.roads) if (r.paved) sources.push(landSource("paved", r, rules))for (const r of s.ruins ?? []) sources.push(landSource("ruin", r, rules))- for (const h of s.homes) if (h.condition < rules.condition.worn) sources.push(landSource("worn", h.tile, rules))+ for (const h of s.homes) {+ if (h.condition < rules.condition.worn) sources.push(landSource("worn", h.tile, rules))+ const fine = homeSource(h.tier, h.tile, rules)+ if (fine) sources.push(fine)+ }const roadCells = new Set(s.roads.map((p) => `${p.x},${p.y}`))sources.push(...parkSources(s.parks ?? [], (x, y) => roadCells.has(`${x},${y}`), rules))const appeal = appealGrid(sources, rules), findings: Finding[] = []