A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Tune the term with the simulation: goals, greed, neglect
Claude1376f6b908de
diff --git a/README.md b/README.mdindex 5ab5ac0..71a5284 100644--- a/README.md+++ b/README.md@@ -41,11 +41,12 @@ pnpm balance # a bot plays terms headless and reports the pressurepausing a building (no workers, a quarter of its upkeep); answering thecrown; and the speed of time (space pauses, 1, 2, 3 for 1×, 2×, 4×).- **The end**: the town is *complete* once it holds every goal for two- minutes (enough residents and coins for its size, two in five of them- citizens, approval 20 or more, not losing coins); you may retire or keep+ minutes (enough residents and coins for its size, three in ten of them+ citizens, approval 15 or more, not losing coins); you may retire or keepgoverning. It is *lost* to bankruptcy (three minutes in debt), revolt- (approval at -50 or below for two minutes), or abandonment (people fall- below 15% of their peak). Otherwise the term runs out, and the town+ (approval at -50 or below for two minutes), abandonment (people fall+ below 15% of their peak), or dismissal (three of the crown's requests+ missed in a row). Otherwise the term runs out, and the townis judged flourishing, holding on, or declining. The reckoning shows theterm's history and its chronicle.@@ -113,5 +114,5 @@ pnpm balance -- --seeds 1 --verbose --every 1 # minute by minute````pnpm check` puts the real simulation into each way a term can end-(complete, bankrupt, revolt, abandoned, run out), checks an unanswered+(complete, bankrupt, revolt, abandoned, dismissed, run out), checks an unansweredcrown request, and checks that a town saved mid-term loads back the same.diff --git a/docs/mayor-plan.md b/docs/mayor-plan.mdindex 8f4847e..7c76157 100644--- a/docs/mayor-plan.md+++ b/docs/mayor-plan.md@@ -31,7 +31,7 @@ to maintain.| **Pressure** | Administration grows with the number of homes; prices fall as the town sells and rise as it buys; stone and ore run out; crown requests grow through the term, with fines and snubs for missed ones | §5.4, §6.3, §6.4 || **Approval** | One town-wide figure from needs, taxes, unpaid wages, the crown's snubs, and hungry winters, with its parts shown. It sets how many people each home holds | §6.1, simplified || **Levers** | Taxes per tier; sell, buy, or neither for each good; the reserve; pausing a building; answering the crown; game speed (pause, 1×, 2×, 4×) | §5.1, §5.3, §5.4, §9 |-| **Ends** | Complete (every goal held two minutes; retire or keep governing); bankrupt; revolt; abandoned; or the term runs out with a verdict. The reckoning shows the term's chart and chronicle | §8 |+| **Ends** | Complete (every goal held two minutes; retire or keep governing); bankrupt; revolt; abandoned; dismissed by the crown (three requests missed in a row); or the term runs out with a verdict. The reckoning shows the term's chart and chronicle | §8 || **Engine** | Road paths cached against a fingerprint of the road network; history and chronicle saved with the town; `pnpm check` drives every end state | §9 |### What is left for later@@ -62,11 +62,56 @@ the calls it forced:- **Bread, cloth, and faith last longer** (90, 180, and 150 seconds), so ahome can have all three at once and become citizens.- **Four goals, not five.** "Food in store" fought the markets for the same- fish; approval already measures whether homes are fed.+ fish; approval already measures whether homes are fed. Goals are a share+ of citizens (30%) and approval (15) on top of residents and coins for the+ land's size.+- **Greed and neglect must lose.** Taxing at 200% still grew towns to 40,000+ coins, so taxes now weigh more on approval (0.6 a point) and low approval+ empties homes faster. A town left to itself sat safe until its term ran+ out, so the crown now dismisses a mayor who misses three requests in a+ row.### Measured outcomes-MEASURED+Fair land throughout. The sensible bot is a mediocre player: it lays out a+rough street grid, builds chains in fixed ratios, answers the crown when it+can (buying what it lacks), and cuts taxes once only approval stands+between it and a complete town. The greedy bot taxes at 200%, sells+everything, and ignores the crown. The idle bot founds the basics and stops.++| Charter | Mayor | Seeds | Complete | Lost | Ran out |+|---------|-------|-------|----------|------|---------|+| small, 45 min | sensible | 8 | 2 (minutes 30, 43) | 1 dismissed (39) | 5 |+| medium, 60 min | sensible | 8 | 1 (minute 58) | — | 7 |+| large, 90 min | sensible | 4 | — | 2 bankrupt (61, 89) | 2 |+| medium, 60 min | greedy | 4 | — | 4 in revolt (19–21) | — |+| medium, 60 min | idle | 4 | — | 4 dismissed (22) | — |++So a careless mayor loses, a decent one wins small towns and comes close+on larger ones, and a player who lays out tighter chains than the bot+should complete medium and large towns. Most "ran out" terms ended within+one or two goals, nearly always the share of citizens or the coins.++**How the pressure builds** (sensible mayor, medium land, 60 minutes,+averaged over the 8 seeds every 10 minutes):++| Minute | Residents | Citizens | Coins | Costs ÷ income | Administration a minute | Approval | Homes fed |+|--------|-----------|----------|-------|----------------|-------------------------|----------|-----------|+| 10 | 163 | 0 | 224 | 0.73 | 39 | 25 | 58% |+| 20 | 230 | 5 | 237 | 0.95 | 70 | 18 | 48% |+| 30 | 284 | 45 | 401 | 0.72 | 89 | 17 | 45% |+| 40 | 321 | 39 | 847 | 1.22 | 106 | 15 | 44% |+| 50 | 355 | 61 | 1545 | 1.03 | 114 | 20 | 48% |+| 60 | 335 | 49 | 1802 | 1.34 | 118 | 15 | 38% |++Costs climb from about three quarters of income to more than all of it,+administration triples, and fewer homes are fed as the town spreads. Each+new year's winter pulls the curve down before spring lets it recover. On+large land over 90 minutes the same shape stretches out: administration+grows from 27 to 226 coins a minute.++Reproduce with `pnpm balance -- --size medium --term 60 --seeds 8` (a few+minutes a seed headless; split seeds across processes with `--from`).## 1. What we have, and how it holds up over a long rundiff --git a/scripts/check.ts b/scripts/check.tsindex 553adb0..2d2cd0d 100644--- a/scripts/check.ts+++ b/scripts/check.ts@@ -11,7 +11,8 @@* - revolt: approval at -50 or below for two minutes;* - abandoned: residents fall below 15% of their peak;* - over: a term run out;- * - the crown: a request left unanswered is a fine and a snub;+ * - the crown: a request left unanswered is a fine and a snub, and three in+ * a row and the mayor is dismissed;* - and a town saved mid-term loads back the same.*/import { STEP_SECONDS, type CharterValue } from "../src/content.ts"@@ -166,6 +167,9 @@ const check = (name: string, ok: boolean, detail: string) => {const c = t.snapshot().resources["Town/Crown"]const lines = t.snapshot().resources["Town/Chronicle"].lines as Array<{ text: string }>check("crown", c.missed >= 1 && lines.some((l) => l.text.includes("unanswered")), `met ${c.met}, missed ${c.missed}, snubs ${c.snubs.length}`)+ t.run(6 * 60)+ const f = t.fate()+ check("dismissed", f.state === "lost" && f.reason.startsWith("Dismissed"), `${f.state} at ${(f.at / 3600).toFixed(1)} min: ${f.reason}`)}// Save and load: a town mid-term loads back to the same state, and runs on the same.diff --git a/src/content.ts b/src/content.tsindex fe6bf4e..849beab 100644--- a/src/content.ts+++ b/src/content.ts@@ -294,7 +294,7 @@ export const sizes: Readonly<Record<SizeId, {}>> = {small: { title: "small", radius: 14, goal: { residents: 180, coins: 2500 } },medium: { title: "medium", radius: 19, goal: { residents: 320, coins: 4000 } },- large: { title: "large", radius: 25, goal: { residents: 520, coins: 6000 } }+ large: { title: "large", radius: 25, goal: { residents: 520, coins: 5000 } }}/**@@ -366,7 +366,7 @@ export const mood = {/** At no needs met to every need met. */needs: [-35, 30] as const,/** Points for each percent the average tax rate is below (or above) 100%. */- perTaxPoint: 0.4,+ perTaxPoint: 0.6,debt: -20,/** Per unanswered crown request, while the crown remembers it. */snub: -20,@@ -396,7 +396,9 @@ export const crown = {fine: 1,bonus: 50,/** How long the crown remembers a missed request, in minutes. */- memory: 4+ memory: 4,+ /** Requests missed in a row before the crown dismisses the mayor. */+ patience: 3}/**@@ -422,8 +424,8 @@ export const fate = {abandon: 0.15,peak: 40,/** The goals besides residents and coins: a share of them citizens, and approval. */- citizens: 0.4,- approval: 20+ citizens: 0.3,+ approval: 15}/** The town's history: a sample this often. */diff --git a/src/host.ts b/src/host.tsindex 714b5d6..97a7fdb 100644--- a/src/host.ts+++ b/src/host.ts@@ -557,7 +557,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersistecrownLine.textContent = `${s.crown.met} · ${s.crown.missed}`crownNext.textContent = s.crown.open? `Asking for ${s.crown.amount} ${goods[s.crown.good].title}: ${clockText(s.crown.left)} left, ${s.crown.reward} coins when sent.`- : `The next request in ${clockText(s.crown.next)}. A missed one is a fine, and the town remembers the snub for a while.`+ : `The next request in ${clockText(s.crown.next)}. A missed one is a fine, and the town remembers the snub for a while; ${s.crown.patience} missed in a row and the crown dismisses the mayor.`// Goods' change over the last minute of samples.const ago = history[Math.max(0, history.length - 1 - Math.round(60 / SAMPLE_SECONDS))]reserveValue.textContent = String(s.policy.reserve)@@ -975,6 +975,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteif (s.fate.revolt !== null) warnings.push(`<b>Uproar:</b> the town turns the mayor out in ${clockText(s.fate.revolt)}`)else if (s.mood.approval < -30) warnings.push("<b>Restless:</b> approval is falling towards revolt")if (s.fate.peak >= 40 && s.settlers + s.citizens < s.fate.peak * 0.4) warnings.push("<b>Emptying:</b> people are leaving the town")+ if (s.crown.streak > 0 && s.crown.streak >= s.crown.patience - 1) {+ warnings.push(`<b>The crown's patience:</b> ${s.crown.streak} requests missed in a row; one more and the mayor is dismissed`)+ }if (s.fate.complete !== null) warnings.push(`<b>Every goal met:</b> the town is complete in ${clockText(s.fate.complete)}`)}const html = warnings.map((w) => `<div class="cell">${w}</div>`).join("")diff --git a/src/present.ts b/src/present.tsindex 8d52f4e..4aa3b81 100644--- a/src/present.ts+++ b/src/present.ts@@ -9,7 +9,7 @@ import {BuildingView, drawFloor, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView,type Doors, type Emphasis} from "./art.ts"-import { BUILD_TICKS, fate, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"+import { BUILD_TICKS, crown as crownRules, fate, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"import { around, canPlace, entrances, isRoad, key, lPath, useAt, type TileLike } from "./grid.ts"import { inside, TILE_H, TILE_W, toGrid, toScreen, U, type Point } from "./iso.ts"import {@@ -364,7 +364,7 @@ export const Interact = Game.System(},crown: {open: crown.open, good: crown.good, amount: crown.amount, left: seconds(crown.due - t), reward: crown.reward, met: crown.met,- missed: crown.missed, next: seconds(crown.next - t)+ missed: crown.missed, streak: crown.streak, patience: crownRules.patience, next: seconds(crown.next - t)},fate: {state: f.state,diff --git a/src/schema.ts b/src/schema.tsindex e5d9df1..26232f0 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -207,8 +207,8 @@ export const Mood = Descriptor.ConstructedResource(Decode.struct({/*** The crown's requests: the one open now (if `open`), when the next comes,- * how many were met and missed, and when the misses the crown still- * remembers were.+ * how many were met and missed (and missed in a row), and when the misses+ * the crown still remembers were.*/export const Crown = Descriptor.ConstructedResource(Decode.struct({open: Decode.boolean,@@ -220,13 +220,15 @@ export const Crown = Descriptor.ConstructedResource(Decode.struct({next: integer,met: integer,missed: integer,+ /** Requests missed since one was last met. */+ streak: integer,snubs: Decode.array(integer)}))("Town/Crown")export const fateStates = ["playing", "won", "lost", "over"] as const/*** How the term is going: still `playing`; `won` (every goal held), `lost`- * (bankrupt, in revolt, or abandoned), or `over` (the term ran out), with+ * (bankrupt, in revolt, abandoned, or dismissed by the crown), or `over` (the term ran out), with* why and when. `governing`: won, and carried on anyway. The `since`* fields are when each danger (or the goals) began, or -1.*/diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex 66d8c88..858a3d3 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -206,7 +206,7 @@ export const ApplyEdits = Game.System(}left[c.good] = (left[c.good] ?? 0) - c.amountcoins += c.reward- resources.crown.set({ ...c, open: false, met: c.met + 1 })+ resources.crown.set({ ...c, open: false, met: c.met + 1, streak: 0 })resources.chronicle.update((ch) => ({ lines: [...ch.lines, { tick: t, text: `Sent the crown ${c.amount} ${goods[c.good].title}, for ${c.reward} coins.` }].slice(-200) }))ui.toast(`Sent · +${c.reward} coins`)break@@ -244,7 +244,7 @@ export const ApplyEdits = Game.System(resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve })resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 })- resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter), met: 0, missed: 0, snubs: [] })+ resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter), met: 0, missed: 0, streak: 0, snubs: [] })resources.fate.set(foundedFate())resources.history.set({ samples: [] })resources.chronicle.set({diff --git a/src/sim/index.ts b/src/sim/index.tsindex bf88e03..a09430a 100644--- a/src/sim/index.ts+++ b/src/sim/index.ts@@ -61,7 +61,7 @@ export const blankResources = () => ({Land: { mask: "", cells: 0 },Market: { prices: amounts({}) },Mood: { approval: 0, target: 0, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 },- Crown: { open: false, good: "wood" as const, amount: 0, issued: 0, due: 0, reward: 0, next: 0, met: 0, missed: 0, snubs: [] },+ Crown: { open: false, good: "wood" as const, amount: 0, issued: 0, due: 0, reward: 0, next: 0, met: 0, missed: 0, streak: 0, snubs: [] },Fate: foundedFate(),History: { samples: [] },Chronicle: { lines: [] },diff --git a/src/sim/term.ts b/src/sim/term.tsindex 73e96b6..6ff1377 100644--- a/src/sim/term.ts+++ b/src/sim/term.ts@@ -79,7 +79,7 @@ export const Requests = Game.System(if (c.open && t >= c.due) {const fine = Math.round(((c.reward - crown.bonus) / crown.reward) * crown.fine) + crown.bonusresources.treasury.update((tr) => ({ coins: tr.coins - fine }))- resources.crown.set({ ...c, open: false, missed: c.missed + 1, snubs: [...remembered, t] })+ resources.crown.set({ ...c, open: false, missed: c.missed + 1, streak: c.streak + 1, snubs: [...remembered, t] })write(resources.chronicle, t, `The crown's request for ${c.amount} ${goods[c.good].title} went unanswered: a fine of ${fine} coins.`)return}@@ -203,8 +203,9 @@ export const scoreOf = (s: { readonly settlers: number; readonly citizens: numbe/*** Once a second: does the term end? It is lost to bankruptcy (in debt too- * long), revolt (approval too low too long), or abandonment (the town- * emptied); won once every goal has held long enough; and over when the+ * long), revolt (approval too low too long), abandonment (the town+ * emptied), or dismissal (the crown's requests missed too many times in a+ * row); won once every goal has held long enough; and over when the* term runs out. Dangers write to the chronicle as they begin.*/export const Judge = Game.System(@@ -260,6 +261,7 @@ export const Judge = Game.System(if (next.debtSince >= 0 && t - next.debtSince >= minutes(fate.debt)) return end("lost", "Bankrupt: the crown has taken the treasury out of the mayor's hands.")if (next.revoltSince >= 0 && t - next.revoltSince >= minutes(fate.revolt)) return end("lost", "Revolt: the town has turned the mayor out.")if (next.peak >= fate.peak && residents < next.peak * fate.abandon) return end("lost", "Abandoned: the people have left the town.")+ if (crownNow.streak >= crown.patience) return end("lost", `Dismissed: the crown has replaced a mayor who left ${crown.patience} of its requests unanswered.`)if (t >= termTicks(charter)) {return end("over", f.governing ? "The term is over: the town stood complete to the end." : "The term is over.")}diff --git a/src/sim/town.ts b/src/sim/town.tsindex e02ea5d..bdd8205 100644--- a/src/sim/town.ts+++ b/src/sim/town.ts@@ -33,8 +33,8 @@ export interface Rates {}const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)-/** How approval (-100 → 100) sits with a home: half as many residents at its worst, half again at its best. */-export const appealOf = (approval: number): number => 1 + approval / 200+/** How approval (-100 → 100) sits with a home: a third as many residents at its worst, half again at its best. */+export const appealOf = (approval: number): number => (approval < 0 ? 1 + approval / 150 : 1 + approval / 200)/*** Residents a home holds at its tier and satisfaction: half when nothing isdiff --git a/src/ui.ts b/src/ui.tsindex dd063f9..fc88439 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -135,6 +135,9 @@ export interface Stats {readonly reward: numberreadonly met: numberreadonly missed: number+ /** Missed in a row, and how many in a row the crown puts up with. */+ readonly streak: number+ readonly patience: number/** Seconds until the next request. */readonly next: number}