A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
The bot takes upgrades, braces for winter, and keeps its chains in proportion
Claudee610f707fd61
diff --git a/docs/balance-model-results.md b/docs/balance-model-results.mdindex d34ec51..3141ec4 100644--- a/docs/balance-model-results.md+++ b/docs/balance-model-results.md@@ -1,10 +1,10 @@# Balance model results-Generated from PR #3 at 619268604f382a5c73b50fc7c4049b90fc63fb07. Current shipped parameters, with no report-time overrides. Rules SHA-256: f3ee5d19da245921f0f6a7ef8ad9eefe92918b02fc9f6b6b1239f9d30963a193.+Generated from PR #3 at d85daeb0dd603bb2331ea3617587ff8311776f94. Current shipped parameters, with no report-time overrides. Rules SHA-256: ab3123a31ccaa327eff54c63532ed318fc298229127c3879e31b2dea52586d9a.## First citizens, with the current rules-An authored starting district pays for its roads and homes, then uses ordinary construction edits and the UI-supported tool reserve of 10. The real game first reaches citizens at 267 seconds; the coarse model estimates 249. At ten minutes the game has 32 citizens, 60 residents and 1310 coins. The forecast has 32 citizens, 60 residents and 1374 coins. This is a progression fixture, not a generated-map victory claim.+An authored starting district pays for its roads and homes, then uses ordinary construction edits and the UI-supported tool reserve of 10. The real game first reaches citizens at 267 seconds; the coarse model estimates 249. At ten minutes the game has 48 citizens, 82 residents and 1728 coins. The forecast has 48 citizens, 82 residents and 1748 coins. This is a progression fixture, not a generated-map victory claim.## Production capacity@@ -23,7 +23,7 @@ Outputs per minute with full crews, sufficient inputs, output room and maintaine## Useful constraints- The first citizen chain alone costs 870 coins and 3 construction tools. Its 3 wearing workshops also need working tools. Total 6, versus 10 at a fair start. Raw industry adds more tool demand.-- The verified park uses three adjacent flower cells, one fountain and one lamp: 97 coins, 2.65/min upkeep, +8 desirability at the nearest cells, reach 2. Its effects combine with industry and chapel effects; nearby raw industry remains a liability. Place furnishings after the ground exists.+- The verified park uses three adjacent flower cells, one fountain and one lamp: 97 coins, 2.65/min upkeep, +6 desirability at the nearest cells, reach 2. Its effects combine with industry and chapel effects; nearby raw industry remains a liability. Place furnishings after the ground exists.- Cloth reaches existing citizens and settlers on eligible streets. Eligible settlers request bread independently of their food meter; other settlers prefer fish and use bread as a fallback.- Skilled jobs receive native crews first. Surplus citizens can fill rough jobs at full speed, and settlers can fill skilled jobs at apprentice pace. The road commute still constrains both.- Build mills/bakeries before farms can plant on their future plots. A previous ordering failed with the real game's “No room there”; the revised verified schedule has 0 rejected-action messages.@@ -45,7 +45,7 @@ Fully staffed, maintained fisheries; homes consume per household. Each figure ex| Check | Expected | Actual | Allowed error | Pass ||---|---:|---:|---:|---|-| collection-rounding | 48 | 48 | 0 | true |+| collection-rounding | 36 | 36 | 0 | true || shared-carrier-capacity | 27.27 | 24 | 8 | true || bakery/citizens/tool/new | 10 | 9 | 1 | true || bakery/apprentices/tool/new | 7.5 | 7 | 1 | true |@@ -70,7 +70,6 @@ Use static constraints and parameter/configuration search to reject weak designs- The construction fixture establishes first citizens on authored flat land, not victory on every generated seed.- The forecast's revisit gaps, shelf allocation, field placement and equipment distribution are approximations. Calibration errors are reported, not hidden.- Wild forest regeneration is bounded in steady-state analysis and excluded from the transient finite-tree forecast. Maintenance and disaster constraints are analyzed; stochastic disasters and repairs are verified in the real game, not reproduced as an exact joint distribution.-## Applied tuning and full victoriesPR #4's mathematical component is merged into PR #3. These changes apply to the shipped game; the report above supplies no additional overrides. The original victory requirements, including the continuous two-minute hold, remain unchanged.@@ -92,24 +91,38 @@ Eligible settlers now request bread independently of their food meter; cloth goeThe bot establishes desirable citizen streets earlier, sizes bread and cloth chains for eligible recipients, avoids industry beside those streets and uses bounded purchases through ordinary trade rules when a functioning chain needs help. These results measure the combined rules, numbers and bot policy, rather than isolating one parameter.-Three deterministic medium/fair charters ran through ordinary player edits with shipped rules, seeded disasters and no direct state injections:+## Ranks on generated charters, with upgrades and furniture++The term no longer ends in a single win: a town rises from hamlet to village, town and city as each rank's goals hold for two minutes, and the term plays on to its end. The town rank (`TOWN_RANK`) is the old "complete" town. The sensible bot plays through ordinary edits, with shipped rules and seeded disasters. It now takes a guildhall once a village (and an ovenworks, estate or masonry once a town, where bread, wheat or stone run short), lays in flour before winter, and builds a carpenter once homes are fit for townhouses.-| Seed | Outcome | End minute | Residents | Citizens | Coins | Approval | Longest goal hold |-|---|---|---:|---:|---:|---:|---:|---:|-| 1000 | won | 22.5 | 384 | 116 | 4948 | 58 | 120 s |-| 8919 | term over | 60 | 271 | 32 | 16067 | 27 | 0 s |-| 16838 | won | 23.5 | 401 | 184 | 4816 | 57 | 120 s |+Fifteen 60-minute charters, at `cd186a3` (upgrades and the income goal, with the old bot) and now (furniture, and the bot below):-Before this tuning, the measured seed-1000 baseline ended its 60-minute term with 297 residents, 16 citizens, approval -4 and coins -1. No baseline result was measured for the other two seeds.+| Charter | Before | After |+|---|---|---|+| medium fair 8919 | town at 45 min | town at 38 min |+| medium fair 16838 | town at 53 min | town at 28 min |+| medium fair 24757 | town at 53 min | town at 55 min |+| medium fair 32676 | village | town at 33 min |+| medium fair 40595 | hamlet | hamlet |+| medium fair 48514 | village | village |+| medium fair 56433 | village | town at 36 min |+| medium harsh 8919 | village | village |+| medium harsh 16838 | village | town at 46 min |+| medium rich 8919 | town at 46 min | village |+| small fair 8919 | town at 27 min | town at 22 min, city at 41 min |+| small fair 16838 | town at 25 min | town at 24 min |+| small harsh 24757 | town at 48 min | bankrupt at 41 min |+| large fair 8919 | hamlet | hamlet |+| large fair 16838 | village | village |-The failed charter has enough money but lacks population and citizens. Layout and eligible housing remain limiting factors. Two of three examples winning establishes legal full victory, not a human success rate or a guarantee across maps. Investigate district placement and citizen coverage on seed 8919 before increasing taxes or reducing win goals.+The two regressions are the bot's, not a rule hole: on small harsh 24757 its decisions match the old run move for move until minute 24, when a lamp goes down one decision earlier, and the run diverges from there. Large charters outgrow the bot's district planning before and after. No bot run reached burghers: a townhouse needs desirability 12, every service calling, and furniture, which takes deliberate zoning the bot does not do.-Reproduce the generated runs:+Reproduce one:```sh-pnpm balance --seeds 3 --term 60 --json output/balance-rules/results.json+pnpm balance --seeds 1 --from 1 --term 60```-Both winning seeds are permanent full-game regressions in `test/balance-victory.test.ts`. Local validation passes: all 37 tests, typecheck, simulation invariants, production build and the documented browser workflow covering placement, save/load, populated towns, camera angles, walkers, phone/touch and reckoning. No hosted CI checks are configured; no production deployment or physical-device validation was performed.+Seeds 8919 and 16838 (medium fair) are permanent regressions in `test/balance-victory.test.ts`: each becomes a village and stands, and reaches the town rank.Generate fresh model results using the CLI documented in [balance-model.md](balance-model.md). The report above records its source commit and exact rule hash.diff --git a/scripts/balance.ts b/scripts/balance.tsindex 2113bc0..db33551 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -486,8 +486,8 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b{ kind: "bakery", when: count(w, "bakery") < Math.min(bakeries, count(w, "mill")) },{ kind: "sheep", when: count(w, "sheep") < weavers },{ kind: "weaver", when: count(w, "weaver") < Math.min(weavers, count(w, "sheep")) },- // Townhouses want furniture: a carpenter once there are citizens to rise.- { kind: "carpenter", when: w.census.citizens! >= 20 && count(w, "carpenter") < 1 + Math.floor(w.census.burghers! / 120) },+ // Townhouses want furniture: a carpenter once homes are fit to rise to them, not before.+ { kind: "carpenter", when: (readyFor(w, 3) >= 2 || w.census.burghers! > 0) && count(w, "carpenter") < 1 + Math.floor(w.census.burghers! / 120) },{ kind: "warehouse", when: count(w, "warehouse") < Math.floor(homes / 25) },// Fish and bread rot: a granary keeps them, and smoked fish keeps.{ kind: "granary", when: homes >= 40 && count(w, "granary") < 1 + Math.floor(homes / 70) },@@ -524,8 +524,9 @@ const decide = (w: World): ReadonlyArray<Edit> => {settlers: w.census.settlers!, citizens: w.census.citizens!, coins: w.coins, net: net(w), approval: w.mood.approval, hall: w.hall}, rules)// Closing in on a complete town: everything but approval and the larder met. Cut taxes, buy food.- const closing = goals.every((g) => g.met || g.id === "approval") && w.coins > 1000- const rate = closing || w.mood.approval < 0 ? 50 : w.mood.approval < 15 ? 75 : w.mood.approval > 45 ? 125 : 100+ // Not by cutting into the income the goals want too: only approval short, and to three-quarters, not half.+ const closing = goals.every((g) => g.met || g.id === "approval") && !goals.find((g) => g.id === "approval")!.met && w.coins > 1000+ const rate = w.mood.approval < 0 ? 50 : closing || w.mood.approval < 15 ? 75 : w.mood.approval > 45 ? 125 : 100if (w.policy.settlers !== rate) edits.push({ type: "tax", tier: "settlers", rate }, { type: "tax", tier: "citizens", rate })// Keep enough to answer the crown, buying what is short of its request.const asked = w.crown.open ? w.crown.amount : 0@@ -537,7 +538,11 @@ const decide = (w: World): ReadonlyArray<Edit> => {// Buy what runs short, while the treasury can bear it; stop once there is enough.// Never at any price: buying drives it up, so stop at half again the usual.const civicShort = w.coins > 600 && count(w, "mill") > 0 && count(w, "weaver") > 0 && count(w, "chapel") > 0 && w.census.citizens! < Math.max(content.sizes[w.charter.size].goal.residents, residents(w)) * content.fate.citizens- const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["bread", civicShort ? 8 : -1, 20], ["cloth", civicShort ? 4 : -1, 12], ["planks", Math.max(6, wanted(w, "planks")), Math.max(14, wanted(w, "planks") + 8)], ["stone", Math.max(4, wanted(w, "stone")), Math.max(12, wanted(w, "stone") + 6)], ["tools", 3, 6], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) ? 1000 : -1, 24]]+ // Winter: the fields lie fallow, so flour (which keeps) is laid in for the bakeries before it, and fish bought while it lasts.+ const season = seasonAt(w.tick - w.charter.founded, w.charter, rules)+ const bracing = w.coins > 800 && count(w, "bakery") > 0 && (season.winter || (season.coming !== null && season.left < content.ticks(180)))+ const wintry = season.winter && w.coins > 800 && fed < 0.8 && w.stock.fish < 20+ const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["flour", bracing ? 15 : -1, 40], ["bread", civicShort ? 8 : -1, 20], ["cloth", civicShort ? 4 : -1, 12], ["planks", Math.max(6, wanted(w, "planks")), Math.max(14, wanted(w, "planks") + 8)], ["stone", Math.max(4, wanted(w, "stone")), Math.max(12, wanted(w, "stone") + 6)], ["tools", 3, 6], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) || wintry ? 1000 : -1, 24]]for (const [g, low, enough] of shortages) {if (g === crownBuy) continueconst buying = w.policy.buys.includes(g)@@ -568,7 +573,10 @@ const decide = (w: World): ReadonlyArray<Edit> => {// A workshop more where what it works piles up in storage (flour with no baker to bake it), before anything else.if (sensible()) {const backlog = (["bakery", "weaver", "mill"] as const).find((k) => w.stock[kinds[k].recipe!.input!] > 40 && unlocked(w, kinds[k]) && affordable(w, kinds[k].cost)- && !w.buildings.some((b) => b.kind === k && (b.site || b.status === "unstaffed")))+ && !w.buildings.some((b) => b.kind === k && (b.site || b.status === "unstaffed"))+ // Not past what feeds it: a mill for every farm and one more, a bakery for every mill and one more, a weaver for every sheep farm and one more.+ && (k !== "mill" || count(w, "mill") <= count(w, "farm")) && (k !== "bakery" || count(w, "bakery") <= count(w, "mill"))+ && (k !== "weaver" || count(w, "weaver") <= count(w, "sheep")))const spot = backlog ? spotFor(w, kinds[backlog]) : nullif (backlog && spot) return [...edits, { type: "building", kind: backlog, cell: spot, open: false }]}@@ -605,6 +613,10 @@ const decide = (w: World): ReadonlyArray<Edit> => {const road = roadToward(w, null)if (road.length > 0 && w.coins > road.length * ROAD_COST + 60) return [...edits, { type: "roads", cells: road }]}+ // An upgrade where it pays, once the coins and the store can bear it (the store is stocked for it meanwhile, see `wanted`).+ const wish = upgradeWish(w)+ if (wish && spare(w) >= wish.up.cost.coins + 300 && (Object.entries(wish.up.cost.materials) as Array<[GoodId, number]>).every(([g, n]) => w.stock[g] >= n))+ return [...edits, { type: "upgrade", cell: { x: wish.tile.x, y: wish.tile.y } }]if (process.env.DEBUG_PLAN) console.log(` t ${w.tick} coins ${w.coins} planks ${w.stock.planks} stone ${w.stock.stone} tools ${w.stock.tools} wants ${plan(w).filter((p) => p.when).map((p) => p.kind).join(",")}`)for (const want of plan(w)) {if (!want.when) continue@@ -672,8 +684,40 @@ const savingFor = (w: World): Kind | null => {const spare = (w: World) => w.coins - (savingFor(w)?.cost.coins ?? 0)/** Homes ready to rise a tier but for its rebuilding (their needs met, their street fine enough). */const readyToRise = (w: World) => w.homes.filter((h) => !h.site && h.provided && h.tier < 3 && (w.appeal[key(h.tile.x, h.tile.y)] ?? 0) >= home.tiers[(h.tier + 1) as 2 | 3].appeal).length-/** Of a good, what the building saved for and a few homes' rebuilding need from the store. */-const wanted = (w: World, g: GoodId) => (savingFor(w)?.cost.materials[g] ?? 0) + Math.min(3, readyToRise(w)) * (home.tiers[2].rise.materials[g] ?? 0)+/** Homes ready to rise to a tier. */+const readyFor = (w: World, tier: 2 | 3) => w.homes.filter((h) => !h.site && h.provided && h.tier === tier - 1 && (w.appeal[key(h.tile.x, h.tile.y)] ?? 0) >= home.tiers[tier].appeal).length+/** Of a good, what the building saved for, the upgrade wished for, and a few homes' rebuilding need from the store. */+const wanted = (w: World, g: GoodId) => {+ const wish = upgradeWish(w)+ return (savingFor(w)?.cost.materials[g] ?? 0)+ + (wish && w.coins >= wish.up.cost.coins + 300 ? wish.up.cost.materials[g] ?? 0 : 0)+ + Math.min(3, readyFor(w, 2)) * (home.tiers[2].rise.materials[g] ?? 0)+ + Math.min(3, readyFor(w, 3)) * (home.tiers[3].rise.materials[g] ?? 0)+}+/**+ * The upgrade the mayor means to make next: a guildhall once a village+ * (administration a tenth cheaper, more shelves and carriers); then, once a+ * town, an ovenworks where bread runs short, an estate where the bakeries+ * wait on wheat, and a masonry where the quarry has worked its rocks down.+ * One at a time.+ */+const upgradeWish = (w: World): { readonly tile: Tile; readonly up: content.Upgrade } | null => {+ if (!sensible() || w.buildings.some((b) => b.works)) return null+ const finer = w.homes.filter((h) => h.tier >= 2).length+ const wishes: ReadonlyArray<readonly [KindId, (b: World["buildings"][number]) => boolean]> = [+ ["townhall", () => residents(w) >= 120],+ ["bakery", (b) => b.status === "working" && w.census.bread! < finer * 0.9],+ ["farm", (b) => b.status === "working" && w.stock.wheat + w.stock.flour < 10 && w.census.bread! < finer * 0.9],+ ["quarry", (b) => b.status !== "working" && w.stock.stone < 20]+ ]+ for (const [kind, ok] of wishes)+ for (const b of w.buildings) {+ if (b.kind !== kind || b.site || b.works) continue+ const up = content.nextUpgrade(kinds[kind], b.level)+ if (up && up.rank <= w.fate.rank && ok(b)) return { tile: b.tile, up }+ }+ return null+}/** Roads laid towards each kind since one was last built, and until when a kind with no room is left alone. */const roading = new Map<KindId, number>()const resting = new Map<KindId, number>()diff --git a/src/rules/guide.ts b/src/rules/guide.tsindex 6cfa4ed..aecb599 100644--- a/src/rules/guide.ts+++ b/src/rules/guide.ts@@ -473,7 +473,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [goal: "a carpenter stands",asks: ["carpenter"],focus: "hall",- when: (f) => f.citizens >= 20 && f.finerHomes >= 3,+ when: (f) => f.citizens >= 60 && f.finerHomes >= 8,done: (f) => has(f, "carpenter"),waiting: rising("carpenter")},