A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Guide a new mayor through the ticker, one step at a time
Claude78ef2877d867
diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 87432c4..7135da6 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -145,6 +145,16 @@ workshops that have waited half a minute for inputs, workplaces nobody canwalk to, no food in store) and, under *lately*, the news of the last minuteand a half, which also pops up as it happens. Click a line to go there.+Above them, the **guide** tells a new mayor the next step to take and why,+one at a time: homes and food first, then planks and stone, then fire,+winter, wear, and the services, then the chains that turn settlers into+citizens, and last the crown, trade, and taxes. Each building it names is a+chip that starts placing one, and "show me where" goes to the water, woods,+or rocks it means. A step is put away for good once the town has done it+(shown or not), or when the ✕ skips it; *hide guide* turns it off, and the+**guide** button in the bottom right turns it back on. The guide is saved+with the town, and starts over with a new one.+## Wear, spoilage, and winters- **Food spoils in store**: fish keeps about three minutes, bread aboutdiff --git a/scripts/check-browser.ts b/scripts/check-browser.tsindex 5e35a79..78c8366 100644--- a/scripts/check-browser.ts+++ b/scripts/check-browser.ts@@ -124,7 +124,12 @@ try {await page.getByRole("button",{name:"load",exact:true}).click()await page.getByRole("button",{name:"Load without saving",exact:true}).click()await page.waitForFunction(()=>window.town.ui.stats!.settlers>100)- assert.deepEqual(await snapshot(),grown.world)+ // The guide puts away what the bot's town has already done on the page's first frame; the rest loads exactly as saved.+ const withoutGuide=(w:Snapshot)=>({...w,resources:{...w.resources,"Town/Guide":null}})+ const loaded=await snapshot()+ assert.deepEqual(withoutGuide(loaded),withoutGuide(grown.world))+ assert.ok(["homes","fishery","market"].every(id=>loaded.resources["Town/Guide"].done.includes(id)),"The guide puts away what the town has done")+ facts.guide=loaded.resources["Town/Guide"]const settledFrame=await page.evaluate(()=>window.town.view.stats().frames)await page.waitForFunction(start=>window.town.view.stats().frames>start+60,settledFrame)facts.populatedTown=await page.evaluate(()=>window.town.view.stats())diff --git a/src/factory.css b/src/factory.cssindex e688947..64056c8 100644--- a/src/factory.css+++ b/src/factory.css@@ -65,6 +65,7 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.toolbar .pause { padding: 6px 9px; }.toolbar .pause.on .glyph { background: none; }.system button { color: #5d6861; }+.system .guide-toggle.on { color: #2f5a9c; background: #eef3fb; border-color: #c9d6ee; }.toolbar .town-button {padding: 8px 18px 8px 12px; gap: 10px; font-size: 14px; font-weight: 700; letter-spacing: 0.02em;background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px; box-shadow: 0 2px 0 #dfe2db;@@ -351,6 +352,17 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.hud .ticker .cell.place { cursor: pointer; }.hud .ticker .cell.place:hover { background: #eef0ea; }.hud .ticker .alert.hint { box-shadow: inset 3px 0 0 #8fa9d6; }+/* The guide's step: a chapter and progress over it, and a quiet way to turn it off. */+.hud .ticker .head.guide { display: flex; align-items: baseline; gap: 8px; padding-right: 10px; color: #3d6db5; }+.hud .ticker .head.guide .progress { color: #9aa29b; }+.hud .ticker .head.guide .quiet {+ margin-left: auto; padding: 0; border: 0; background: none; font: inherit; letter-spacing: inherit; text-transform: inherit;+ color: #9aa29b; cursor: pointer;+}+.hud .ticker .head.guide .quiet:hover { color: #3d4943; text-decoration: underline; }+.hud .ticker .cell.guide { background: #f6f8fc; }+.hud .ticker .cell.guide.place:hover { background: #eef3fb; }+.hud .ticker .cell.guide + .head { border-top: 1px dashed #e3e6df; }.hud .ticker .alert.warn { box-shadow: inset 3px 0 0 #d9a24e; }.hud .ticker .alert.bad { box-shadow: inset 3px 0 0 #b04a39; }.hud .ticker .alert.bad .text { color: #8f3f31; }diff --git a/src/host.ts b/src/host.tsindex dcebcc7..b431e0d 100644--- a/src/host.ts+++ b/src/host.ts@@ -234,6 +234,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersistedragFrom: null,selected: null,gestures: [],+ guide: [],// A town is founded behind the dialog, so there is land to look at while choosing.edits: [{ type: "newTown", charter: defaultCharter((Date.now() & 0x7fffffff) >>> 0) }],preview: emptyPreview(),@@ -353,6 +354,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistebutton.onclick = runsystem.append(button)}+ // The guide, on or off (it is on for a new mayor).+ const guideButton = el("button", "guide-toggle")+ guideButton.append(iconEl("hint"), document.createTextNode("guide"))+ guideButton.onclick = () => ui.guide.push({ type: ui.stats?.guide.off ? "on" : "off" })+ system.append(guideButton)action("save", "save", "Save the town in this browser (it also autosaves every two minutes)", () =>ui.toast(persistence().save() ?? "Saved"))@@ -1424,7 +1430,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste/** Ticker lines the mayor has put away, by what they say (and, for news, when). */const dismissed = new Set<string>()- let tickerLines: { alerts: Stats["alerts"]; news: Stats["chronicle"] } = { alerts: [], news: [] }+ let tickerLines: { guide: Stats["guide"]["step"]; alerts: Stats["alerts"]; news: Stats["chronicle"] } = { guide: null, alerts: [], news: [] }ticker.onclick = (event) => {event.stopPropagation()const target = event.target as HTMLElement@@ -1433,6 +1439,17 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistedismissed.add(off.dataset.dismiss!)return}+ // The guide: put this step away, or turn the guide off (the bottom-right button turns it back on).+ const skip = target.closest<HTMLElement>("[data-skip]")+ if (skip) {+ ui.guide.push({ type: "skip", id: skip.dataset.skip! })+ return+ }+ if (target.closest("[data-guide-off]")) {+ ui.guide.push({ type: "off" })+ ui.toast("Guide off · turn it back on from the bottom right")+ return+ }const ref = target.closest<HTMLElement>("[data-kind]")if (ref) {const kind = ref.dataset.kind as KindId@@ -1442,6 +1459,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}const line = target.closest<HTMLElement>(".cell.place")if (!line) return+ if (line.dataset.guide !== undefined && tickerLines.guide?.at) return goTo(tickerLines.guide.at, tickerLines.guide.size, tickerLines.guide.id)const alert = line.dataset.alert !== undefined ? tickerLines.alerts[Number(line.dataset.alert)] : undefinedif (alert?.at) return goTo(alert.at, alert.size, alert.id)const news = line.dataset.news !== undefined ? tickerLines.news[Number(line.dataset.news)] : undefined@@ -1522,7 +1540,16 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst toneIcon = { hint: "hint", warn: "caution", bad: "warning" } as constconst row = (kind: string, tone: string, glyph: IconName, text: string, place: boolean, key: string, data: string) =>`<div class="cell ${kind} ${tone}${place ? " place" : ""}" ${data}>${icon(glyph, 16, "mark")}<span class="text">${text}</span><span class="acts">${place ? `<button class="act locate" title="Show me where">${icon("locate", 14)}</button>` : ""}<button class="act dismiss" data-dismiss="${escapeHtml(key)}" title="Dismiss">${icon("close", 12)}</button></span></div>`+ // The guide's step first: what to do next, and why.+ const g = s.guide.step+ const guideHtml = g+ ? [+ `<div class="head guide"><span>guide · ${escapeHtml(g.chapter)}</span><span class="progress" title="Steps of the guide done">${s.guide.done} of ${s.guide.total} done</span><button class="quiet" data-guide-off title="Turn the guide off (the guide button in the bottom right turns it back on)">hide guide</button></div>`,+ `<div class="cell alert hint guide${g.at !== null ? " place" : ""}" data-guide>${icon("hint", 16, "mark")}<span class="text">${callouts(g.text)}</span><span class="acts">${g.at !== null ? `<button class="act locate" title="Show me where">${icon("locate", 14)}</button>` : ""}<button class="act dismiss" data-skip="${escapeHtml(g.key)}" title="Skip this step">${icon("close", 12)}</button></span></div>`+ ]+ : []const tickerHtml = [+ ...guideHtml,...(alerts.length > 0 ? [`<div class="head">now</div>`] : []),...alerts.map((a) => row("alert", a.tone, toneIcon[a.tone], callouts(a.text), a.at !== null, `a:${a.text}`, `data-alert="${s.alerts.indexOf(a)}"`)),...(fresh.length > 0 ? [`<div class="head">lately</div>`] : []),@@ -1536,7 +1563,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst text = ago(Number(em.dataset.tick))if (em.textContent !== text) em.textContent = text}- tickerLines = { alerts: s.alerts, news }+ tickerLines = { guide: g, alerts: s.alerts, news }+ guideButton.classList.toggle("on", !s.guide.off)+ guideButton.title = s.guide.off ? "Turn the guide back on: a next step to take, and why, at the top of the ticker" : "Turn the guide off"ticker.classList.toggle("show", tickerHtml !== "" && s.fate.state === "playing")// News as it happens: a toast for each new alarm line.const latest = s.chronicle.at(-1)diff --git a/src/present.ts b/src/present.tsindex e8efd9a..56b7ced 100644--- a/src/present.ts+++ b/src/present.ts@@ -35,6 +35,7 @@ import {Figure,Game,Grid,+ Guide,History,House,HouseNodes,@@ -85,6 +86,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 { guideDone, guideStep, guideSteps, type GuideFacts, type GuideFocus } from "./rules/guide.ts"import { ticks } from "./content.ts"const cellAt = (at: Point): Point => {@@ -327,6 +329,7 @@ export const Interact = Game.System(parks: ParkRead,trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),+ rocks: Game.Query({ selection: { tile: Game.Query.read(Tile), rock: Game.Query.read(Rock) } }),paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] })},resources: {@@ -345,7 +348,8 @@ export const Interact = Game.System(history: Game.System.readResource(History),chronicle: Game.System.readResource(Chronicle),appeal: Game.System.readResource(Appeal),- pantry: Game.System.readResource(Pantry)+ pantry: Game.System.readResource(Pantry),+ guide: Game.System.writeResource(Guide)},services: { ui: Game.System.service(Ui) }},@@ -1063,16 +1067,6 @@ export const Interact = Game.System(if (remote.size > 0) alerts.push({ tone: "warn", text: `no workers within ${COMMUTE} road cells: ${list(remote)}`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null })const hallRow = buildings.find(({ data }) => data.hall.present)if (census.homes > 0 && larder(stock) === 0) alerts.push({ tone: "bad", text: "no food in store: homes go hungry", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })- // A town's first steps, until it has taken them: the ticker is otherwise silent when there is least to go on.- const hallAt = { at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: null }- const standingKinds = new Set(buildings.filter(({ data }) => !data.site.present && !data.rising.present).map(({ data }) => data.building.get().kind))- const placedKinds = new Set(buildings.map(({ data }) => data.building.get().kind))- const residents = census.settlers + census.citizens- if (census.homes === 0 && houses.length === 0) alerts.push({ tone: "hint", text: "first: lay a road out from the town hall (R), then drag a row of homes along it (H); settlers move in on their own", ...hallAt })- else if (!placedKinds.has("fishery") && !placedKinds.has("bakery") && residents < 60) alerts.push({ tone: "hint", text: "settlers eat: build a fishery (B) within two cells of water, on a road; the town hall's walker hands the fish out", ...hallAt })- else if (residents >= 20 && !placedKinds.has("lumberjack") && stock.planks < 20) alerts.push({ tone: "hint", text: "planks are running out: a lumberjack by the woods and a sawmill make more; every home and building needs them", ...hallAt })- else if (residents >= 40 && !placedKinds.has("market") && standingKinds.has("fishery")) alerts.push({ tone: "hint", text: "the town hall's walker only reaches 20 road cells: a market (B) hands out food further along the streets", ...hallAt })-const ledger = resources.ledger.get()const charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)@@ -1093,6 +1087,81 @@ export const Interact = Game.System(const danger = (since: number, minutes: number) => (since < 0 ? null : seconds(since + minutes * 3600 - t))// The winter after the coming one, for the almanac.const comingYear = season.winter || winterOf(charter, season.year) === null ? season.year + 1 : season.year++ // ── The mayor's guide ──+ // The page writes what the mayor told it; then the guide puts away what the town has done, and picks the step to show.+ for (const action of ui.guide.splice(0)) {+ resources.guide.update((g) =>+ action.type === "skip" ? (g.done.includes(action.id) ? g : { ...g, done: [...g.done, action.id] }) : { ...g, off: action.type === "off" }+ )+ }+ const placedKinds = new Set(buildings.map(({ data }) => data.building.get().kind))+ const standingKinds = new Set(buildings.filter(({ data }) => !data.site.present && !data.rising.present).map(({ data }) => data.building.get().kind))+ const finished = (row: { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }) => !row.data.site.present && !row.data.rising.present+ const wornRow = buildings.find((row) => finished(row) && !row.data.hall.present && (maybe(row.data.condition)?.value ?? CONDITION_MAX) < wear.mend)+ // A settlers' home with bread, cloth, and faith, kept from citizens only by its street.+ const poorRow = houses.find((row) => {+ const h = row.data.house.get()+ if (h.tier !== 1 || !finished(row)) return false+ const tile = row.data.tile.get()+ return met(h, "bread") && met(h, "cloth") && met(h, "faith") && appealAt(cells, tile.x, tile.y) < home.tiers[2].appeal+ })+ const facts: GuideFacts = {+ homes: houses.length,+ residents: census.settlers + census.citizens,+ citizens: census.citizens,+ finerHomes: houses.filter((row) => row.data.house.get().tier > 1).length,+ placed: placedKinds,+ standing: standingKinds,+ stock,+ sick: census.sick,+ burning: census.burning,+ winter: season.winter,+ winterIn: season.coming === null ? null : seconds(season.left),+ worn: wornRow !== undefined,+ poorStreet: poorRow !== undefined,+ crown: { open: crown.open, met: crown.met },+ net: steadyNet(resources.history.get().samples, net),+ approval: mood.approval,+ trading: rates.sells.length > 0 || rates.buys.length > 0,+ taxed: rates.settlers !== 100 || rates.citizens !== 100,+ most: Math.max(...goodIds.map((g) => stock[g])),+ sawTown: ui.menu === "town"+ }+ const guide = resources.guide.get()+ const put = new Set(guide.done)+ const playing = f.state === "playing" && !ui.founding+ const newly = playing ? guideDone(facts, put) : []+ if (newly.length > 0) {+ resources.guide.update((g) => ({ ...g, done: [...g.done, ...newly] }))+ for (const id of newly) put.add(id)+ }+ const step = guide.off || !playing ? null : guideStep(facts, put)+ const hallTile = hallRow?.data.tile.get()+ /** Of some tiles, the one nearest the town hall. */+ const nearestHall = (tiles: ReadonlyArray<TileLike>): TileLike | undefined => {+ if (!hallTile) return tiles[0]+ let best: TileLike | undefined+ let far = Infinity+ for (const tile of tiles) {+ const d = Math.abs(tile.x - hallTile.x) + Math.abs(tile.y - hallTile.y)+ if (d < far) [best, far] = [tile, d]+ }+ return best+ }+ const focusOf = (focus: GuideFocus | null): { at: TileLike | null; id: number | null } => {+ if (focus === null) return { at: null, id: null }+ if (focus === "hall") return { at: hallTile ?? null, id: null }+ if (focus === "water") return { at: nearestHall(queries.water.each().map(({ data }) => data.tile.get())) ?? null, id: null }+ if (focus === "trees") return { at: nearestHall(queries.trees.each().map(({ data }) => data.tile.get())) ?? null, id: null }+ if (focus === "stone" || focus === "ore") {+ const ore = focus === "ore"+ return { at: nearestHall(queries.rocks.each().filter(({ data }) => data.rock.get().ore === ore).map(({ data }) => data.tile.get())) ?? null, id: null }+ }+ const row = focus === "worn" ? wornRow : focus === "poorStreet" ? poorRow : buildings.find(({ data }) => data.building.get().kind === focus.kind)+ return row ? { at: row.data.tile.get(), id: row.entity.id } : { at: null, id: null }+ }+ const shown = step ? focusOf(step.focus) : nullui.stats = {coins,taxes: ledger.taxes,@@ -1166,7 +1235,13 @@ export const Interact = Game.System(burning: census.burning,history: resources.history.get().samples,chronicle: resources.chronicle.get().lines,- alerts+ alerts,+ guide: {+ step: step && shown ? { key: step.id, chapter: step.chapter, text: step.text, at: shown.at, size: shown.at?.size ?? 1, id: shown.id } : null,+ done: guideSteps.filter((s) => put.has(s.id)).length,+ total: guideSteps.length,+ off: guide.off+ }}})diff --git a/src/rules/guide.ts b/src/rules/guide.tsnew file mode 100644index 0000000..3c45851--- /dev/null+++ b/src/rules/guide.ts@@ -0,0 +1,234 @@+/**+ * The mayor's guide: a tutorial told through the ticker, one step at a+ * time. Each step says what to build or do next and why, and names the+ * buildings it means so the ticker can turn them into chips that place+ * them. A step shows while it applies (`when`) and is put away for good+ * once the town has done it (`done`), whether or not it was ever shown, so+ * a mayor who already knows the game is not told what they did. The list+ * is in order of priority, not of chapters: a request from the crown with a+ * deadline goes ahead of a chain that takes minutes to build.+ */+import type { Amounts, KindId } from "../content.ts"++/** What the guide reads of the town. */+export interface GuideFacts {+ /** Homes laid, built or not. */+ readonly homes: number+ readonly residents: number+ /** Citizens, and homes that hold them (citizens' homes and townhouses). */+ readonly citizens: number+ readonly finerHomes: number+ /** Kinds of building placed (sites too), and standing. */+ readonly placed: ReadonlySet<KindId>+ readonly standing: ReadonlySet<KindId>+ readonly stock: Amounts+ readonly sick: number+ readonly burning: number+ /** It is winter now, or the next one is this many seconds away (`null`: none before the term ends). */+ readonly winter: boolean+ readonly winterIn: number | null+ /** A building that wants mending. */+ readonly worn: boolean+ /** A settlers' home with every citizens' need met, on a street too poor for citizens. */+ readonly poorStreet: boolean+ readonly crown: { readonly open: boolean; readonly met: number }+ /** Coins a minute, and approval. */+ readonly net: number+ readonly approval: number+ /** The town buys or sells something; a tax rate is off the usual. */+ readonly trading: boolean+ readonly taxed: boolean+ /** The most of any one good in store. */+ readonly most: number+ /** The page: the town panel has been open. */+ readonly sawTown: boolean+}++/** Where a step's "show me where" goes: a place on the land, or a building of a kind. */+export type GuideFocus = "hall" | "water" | "trees" | "stone" | "ore" | "worn" | "poorStreet" | { readonly kind: KindId }++export const chapters = ["Founding", "Keeping it standing", "Growing citizens", "Governing"] as const+export type Chapter = (typeof chapters)[number]++export interface GuideStep {+ readonly id: string+ readonly chapter: Chapter+ /** What to do and why. Building names become chips to place one; a key in brackets, a key. */+ readonly text: string+ readonly focus: GuideFocus | null+ readonly when: (f: GuideFacts) => boolean+ readonly done: (f: GuideFacts) => boolean+}++const has = (f: GuideFacts, ...kinds: ReadonlyArray<KindId>) => kinds.every((k) => f.placed.has(k))++export const guideSteps: ReadonlyArray<GuideStep> = [+ {+ id: "homes",+ chapter: "Founding",+ text: "Drag a row of homes along the road from the town hall (H), or lay more road first (R). Settlers move in on their own, and every home pays taxes.",+ focus: "hall",+ when: () => true,+ done: (f) => f.homes > 0+ },+ {+ id: "fishery",+ chapter: "Founding",+ text: "Settlers eat, and the fish in store will not last. Build a fishery (B) on a road within two cells of water; the town hall's walker carries the fish to the homes.",+ focus: "water",+ when: (f) => f.homes > 0,+ done: (f) => has(f, "fishery") || has(f, "bakery")+ },+ {+ id: "crown",+ chapter: "Governing",+ text: "The crown asks for goods by a deadline. Send them from the bar at the top for coins; an unanswered request is a fine, and three missed in a row and the mayor is dismissed.",+ focus: null,+ when: (f) => f.crown.open,+ done: (f) => f.crown.met > 0+ },+ {+ id: "winter",+ chapter: "Keeping it standing",+ text: "Winter is coming: fishing slows, homes eat faster, and fish rots in store. A granary keeps fish five times as long, and a smokehouse makes fish that keeps all winter.",+ focus: "hall",+ when: (f) => f.residents >= 20 && (f.winter || (f.winterIn !== null && f.winterIn <= 120)),+ done: (f) => has(f, "granary") || has(f, "smokehouse")+ },+ {+ id: "tools",+ chapter: "Growing citizens",+ text: "Tools are scarce until a smithy makes them, and that needs 10 citizens. Keep them for the weaver, the mill, and the bakery (not lamps), or buy them from traders in the town panel (T).",+ focus: null,+ when: (f) => f.residents >= 15 && f.stock.tools <= 3 && !has(f, "weaver", "mill", "bakery"),+ done: (f) => has(f, "weaver", "mill", "bakery") || has(f, "smithy")+ },+ {+ id: "planks",+ chapter: "Founding",+ text: "Every home and building costs planks. A lumberjack by the woods fells wood, and a sawmill saws it into planks.",+ focus: "trees",+ when: (f) => has(f, "fishery") || f.stock.planks < 20,+ done: (f) => has(f, "lumberjack", "sawmill")+ },+ {+ id: "forester",+ chapter: "Founding",+ text: "The woods run out. A forester beside the lumberjack plants new trees for it to fell.",+ focus: { kind: "lumberjack" },+ when: (f) => has(f, "lumberjack"),+ done: (f) => has(f, "forester")+ },+ {+ id: "quarry",+ chapter: "Founding",+ text: "Storage, workshops, and paving take stone, and the town starts with little. A quarry cuts it from the rocks nearby.",+ focus: "stone",+ when: (f) => has(f, "lumberjack", "sawmill") || f.stock.stone < 6,+ done: (f) => has(f, "quarry")+ },+ {+ id: "firewatch",+ chapter: "Keeping it standing",+ text: "Wooden cottages catch fire, and a fire spreads to its neighbours. A fire watch sends a watchman along the streets, and firefighters to any blaze. Press F to see the risk.",+ focus: "hall",+ when: (f) => f.homes >= 8 || f.burning > 0,+ done: (f) => has(f, "firewatch")+ },+ {+ id: "builder",+ chapter: "Keeping it standing",+ text: "Buildings wear out, and a run-down one works at half pace and may fall. A builder's yard mends what its builder passes, with planks and stone. Press C to see their condition.",+ focus: "worn",+ when: (f) => f.worn,+ done: (f) => has(f, "builder")+ },+ {+ id: "market",+ chapter: "Keeping it standing",+ text: "The town hall's walker only reaches 20 road cells. A market sends a walker with fish, bread, and cloth further along the streets.",+ focus: "hall",+ when: (f) => f.residents >= 40 && f.standing.has("fishery"),+ done: (f) => has(f, "market")+ },+ {+ id: "street",+ chapter: "Growing citizens",+ text: "A home here has bread, cloth, and faith, but its street is too poor for citizens: it needs desirability 5. Press D to see it; keep workshops away, and add a chapel, a market, or a park.",+ focus: "poorStreet",+ when: (f) => f.poorStreet,+ done: (f) => f.finerHomes > 0+ },+ {+ id: "cloth",+ chapter: "Growing citizens",+ text: "Settlers become citizens, who pay twice as much, once they have bread, cloth, and faith. Now open: a sheep farm and a weaver make cloth, and a chapel brings faith.",+ focus: "hall",+ when: (f) => f.residents >= 15,+ done: (f) => has(f, "sheep", "weaver", "chapel")+ },+ {+ id: "bread",+ chapter: "Growing citizens",+ text: "Bread is the last of a citizen's needs. Now open: a farm grows wheat, a mill grinds it into flour, and a bakery bakes the bread.",+ focus: "hall",+ when: (f) => f.residents >= 30,+ done: (f) => has(f, "farm", "mill", "bakery")+ },+ {+ id: "goals",+ chapter: "Growing citizens",+ text: "The first citizens have moved in. Open the town panel (T) to see the goals the term is judged by: residents, citizens, approval, and coins.",+ focus: null,+ when: (f) => f.finerHomes > 0,+ done: (f) => f.sawTown+ },+ {+ id: "healer",+ chapter: "Keeping it standing",+ text: "Hunger, crowding, and a quarry's dust make homes sick, and a sick home holds half as many. A healer's physician calls on the homes and cures them. Press A to see the risk.",+ focus: "hall",+ when: (f) => f.residents >= 30 && (f.sick > 0 || f.residents >= 50),+ done: (f) => has(f, "healer") || has(f, "hospital")+ },+ {+ id: "watchhouse",+ chapter: "Keeping it standing",+ text: "Poor streets, half-empty homes, and low approval breed thieves. A watch house sends a constable along the streets to keep order. Press O to see the risk.",+ focus: "hall",+ when: (f) => f.residents >= 40,+ done: (f) => has(f, "watchhouse")+ },+ {+ id: "trade",+ chapter: "Governing",+ text: "The town trades nothing until told to. In the town panel (T), sell what piles up beyond the reserve, and buy what runs short.",+ focus: null,+ when: (f) => f.residents >= 20 && (f.net < 0 || f.most >= 80),+ done: (f) => f.trading+ },+ {+ id: "taxes",+ chapter: "Governing",+ text: "The town is content, and approval can carry higher taxes. Raise them in the town panel (T); above 125% leaves a grudge that lasts.",+ focus: null,+ when: (f) => f.approval >= 30 && f.net < 0,+ done: (f) => f.taxed+ },+ {+ id: "smithy",+ chapter: "Governing",+ text: "Now open: a mine digs ore from a deposit, and a smithy forges it into tools, which every workshop and lamp needs and which wear out.",+ focus: "ore",+ when: (f) => f.citizens >= 10,+ done: (f) => has(f, "mine", "smithy")+ }+]++/** The steps the town has now done that the guide has not yet put away. */+export const guideDone = (f: GuideFacts, done: ReadonlySet<string>): Array<string> =>+ guideSteps.filter((s) => !done.has(s.id) && s.done(f)).map((s) => s.id)++/** The step to show now, if any: the first that applies and is not yet done or put away. */+export const guideStep = (f: GuideFacts, done: ReadonlySet<string>): GuideStep | null =>+ guideSteps.find((s) => !done.has(s.id) && !s.done(f) && s.when(f)) ?? nulldiff --git a/src/save.ts b/src/save.tsindex 7b131b6..63c2017 100644--- a/src/save.ts+++ b/src/save.ts@@ -16,22 +16,25 @@ export const SAVE_FORMAT = "inkline-town/save"/*** 2: the charter's towns. 3: neighbourhoods and their dangers (desirability, crews, risks, wear, ruins,* winters). 4: parks and patrols. 5: the grudge over taxes, and where each piece of news happened.- * 6: how much of each good may be traded at a collection.- * Version 4 and 5 saves are carried forward (see `carry`); older ones cannot be loaded.+ * 6: how much of each good may be traded at a collection. 7: the mayor's guide.+ * Version 4, 5, and 6 saves are carried forward (see `carry`); older ones cannot be loaded.*/-export const SAVE_VERSION = 6+export const SAVE_VERSION = 7/*** Fills in what a save from an earlier version lacks, so a town in progress* survives an update: from 4, the mood's grudge (none yet) and the news's- * places (unknown); from 5, trade at full loads, as it was. Anything else is- * left to the world's own validation.+ * places (unknown); from 5, trade at full loads, as it was; from 6, the+ * guide from its start (it puts away at once what the town has already+ * done). Anything else is left to the world's own validation.*/const carry = (version: number, world: unknown): unknown | null => {- if ((version !== 4 && version !== 5) || typeof world !== "object" || world === null) return null+ if ((version !== 4 && version !== 5 && version !== 6) || typeof world !== "object" || world === null) return nullconst w = world as { resources?: Record<string, unknown> }const r = w.resourcesif (!r || typeof r !== "object") return null+ if (!("Town/Guide" in r)) r["Town/Guide"] = { done: [], off: false }+ if (version === 6) return wconst policy = r["Town/Policy"]if (policy && typeof policy === "object" && !("loads" in policy)) r["Town/Policy"] = { ...policy, loads: Object.fromEntries(goodIds.map((g) => [g, TRADE_LOAD])) }if (version === 5) return wdiff --git a/src/schema.ts b/src/schema.tsindex 283adf9..d1e76b2 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -298,6 +298,12 @@ export const Chronicle = Descriptor.ConstructedResource(Decode.struct({lines: Decode.array(Decode.struct({ tick: integer, text: Decode.string, alarm: Decode.boolean, at: Decode.nullable(cell) }))}))("Town/Chronicle")+/**+ * The mayor's guide (see `rules/guide.ts`): the steps it has put away, done or+ * dismissed, and whether the mayor turned it off. Written by the page, not the+ * simulation; saved with the town.+ */+export const Guide = Descriptor.ConstructedResource(Decode.struct({ done: Decode.array(Decode.string), off: Decode.boolean }))("Town/Guide")/** How desirable each cell is to live on (by `key`), reckoned every `appeal.every` steps; empty before the first. */export const Appeal = Descriptor.ConstructedResource(Decode.struct({ cells: Decode.array(integer) }))("Town/Appeal")@@ -353,7 +359,7 @@ export const Game = Schema.bind(Paused, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Patrol, Figure, Route, Errand, Rescue, Roam},resources: {- Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Appeal, Pantry, Fires,+ Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Guide, Appeal, Pantry, Fires,Grid, Stock},relations: { WalkerOf, FieldOf }diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex b62701f..bcccf2a 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -12,7 +12,7 @@ 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, 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, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused, Policy, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui } from "../schema.ts"import { elapsed, rollWinters, TileRead, useOf, write } from "./shared.ts"import { crownGap, foundedFate } from "./term.ts"@@ -53,6 +53,7 @@ export const ApplyEdits = Game.System(fate: Game.System.writeResource(Fate),history: Game.System.writeResource(History),chronicle: Game.System.writeResource(Chronicle),+ guide: Game.System.writeResource(Guide),appeal: Game.System.writeResource(Appeal),pantry: Game.System.writeResource(Pantry),fires: Game.System.writeResource(Fires)@@ -341,6 +342,8 @@ export const ApplyEdits = Game.System(resources.appeal.set({ cells: [] })resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 })resources.fires.set({ fires: [], next: 1 })+ // A new town starts the guide over, unless the mayor turned it off.+ resources.guide.update((g) => ({ done: [], off: g.off }))resources.land.set({ mask: land.mask, cells: land.cells })resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0, admin: 0 })resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve, loads: amounts(Object.fromEntries(goodIds.map((g) => [g, rules.tradeLoad]))) })diff --git a/src/sim/headless.ts b/src/sim/headless.tsindex ad544d3..65d27f1 100644--- a/src/sim/headless.ts+++ b/src/sim/headless.ts@@ -22,7 +22,7 @@ export interface Snapshot {export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs } = {}) => {const ui: UiValue = {- tool: "select", placing: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],+ tool: "select", placing: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [], guide: [],edits: [{ type: "newTown", charter }],preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false,view: "none", overlay: { key: "", cells: [] }, tints: new Map(), legend: null, flash: null,diff --git a/src/sim/index.ts b/src/sim/index.tsindex 6c5fbda..ab16c3e 100644--- a/src/sim/index.ts+++ b/src/sim/index.ts@@ -73,6 +73,7 @@ export const blankResources = () => ({Fate: foundedFate(),History: { samples: [] },Chronicle: { lines: [] },+ Guide: { done: [] as Array<string>, off: false },Appeal: { cells: [] },Pantry: { eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 },Fires: { fires: [], next: 1 },diff --git a/src/ui.ts b/src/ui.tsindex 2374160..525aa01 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -254,6 +254,13 @@ export interface Stats {readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean; readonly at: Point | null }>/** What needs looking at right now, a line each: workshops waiting, workplaces no one can reach, food running out. */readonly alerts: ReadonlyArray<Alert>+ /** The mayor's guide: the step to take now (if any, and the guide is on), and how far along it is. */+ readonly guide: {+ readonly step: (Omit<Alert, "tone"> & { readonly key: string; readonly chapter: string }) | null+ readonly done: number+ readonly total: number+ readonly off: boolean+ }}/** A map view's legend: what each colour means. */@@ -299,5 +306,7 @@ export interface UiValue {legend: Legend | null/** A place the page points at (from the ticker): outlined until `until`, in the clock's seconds. */flash: { readonly cell: Point; readonly size: number; readonly until: number } | null+ /** What the mayor told the guide since the last frame: put a step away, or turn the guide off or on (see `Guide`). */+ guide: Array<{ readonly type: "skip"; readonly id: string } | { readonly type: "off" | "on" }>toast: (message: string) => void}diff --git a/test/guide.test.ts b/test/guide.test.tsnew file mode 100644index 0000000..67a6a9f--- /dev/null+++ b/test/guide.test.ts@@ -0,0 +1,122 @@+/**+ * The mayor's guide (`src/rules/guide.ts`): it starts at the first step,+ * goes in order of priority, puts away what the town has already done+ * (shown or not), and never tells the mayor to build what the town cannot+ * build yet.+ */+import assert from "node:assert/strict"+import { test } from "node:test"++import { amounts, kinds, type KindId } from "../src/content.ts"+import { guideDone, guideStep, guideSteps, type GuideFacts } from "../src/rules/guide.ts"++const fresh: GuideFacts = {+ homes: 0,+ residents: 0,+ citizens: 0,+ finerHomes: 0,+ placed: new Set(),+ standing: new Set(),+ stock: amounts({ planks: 40, stone: 16, tools: 10, fish: 20 }),+ sick: 0,+ burning: 0,+ winter: false,+ winterIn: null,+ worn: false,+ poorStreet: false,+ crown: { open: false, met: 0 },+ net: 10,+ approval: 0,+ trading: false,+ taxed: false,+ most: 40,+ sawTown: false+}+const town = (over: Partial<GuideFacts>, built: ReadonlyArray<KindId> = []): GuideFacts => ({+ ...fresh,+ placed: new Set(built),+ standing: new Set(built),+ ...over+})+const none = new Set<string>()++test("a new town is told to lay homes, then to feed them", () => {+ assert.equal(guideStep(fresh, none)?.id, "homes")+ assert.equal(guideStep(town({ homes: 6, residents: 12 }), new Set(["homes"]))?.id, "fishery")+ assert.equal(guideStep(town({ homes: 6, residents: 12 }, ["fishery"]), new Set(["homes", "fishery"]))?.id, "planks")+})++test("what the town has done is put away, shown or not", () => {+ const experienced = town({ homes: 20, residents: 60, citizens: 0 }, ["fishery", "lumberjack", "sawmill", "forester", "quarry", "firewatch"])+ const put = guideDone(experienced, none)+ for (const id of ["homes", "fishery", "planks", "forester", "quarry", "firewatch"]) assert.ok(put.includes(id), id)+ const next = guideStep(experienced, new Set(put))+ assert.ok(next && !put.includes(next.id), "the next step is one not yet done")+})++test("a step the mayor skipped stays away", () => {+ assert.notEqual(guideStep(fresh, new Set(["homes"]))?.id, "homes")+})++test("the crown's deadline goes ahead of a chain that takes minutes", () => {+ const facts = town({ homes: 20, residents: 40, crown: { open: true, met: 0 } }, ["fishery"])+ assert.equal(guideStep(facts, new Set(guideDone(facts, none)))?.id, "crown")+})++test("winter is foretold before it comes, and not long before", () => {+ const ready = new Set(["homes", "fishery"])+ const built: ReadonlyArray<KindId> = ["fishery", "lumberjack", "sawmill", "forester", "quarry"]+ assert.notEqual(guideStep(town({ homes: 10, residents: 30, winterIn: 400 }, built), ready)?.id, "winter")+ assert.equal(guideStep(town({ homes: 10, residents: 30, winterIn: 90 }, built), ready)?.id, "winter")+ assert.equal(guideStep(town({ homes: 10, residents: 30, winter: true, winterIn: 300 }, built), ready)?.id, "winter")+})++test("a town that runs short of tools before its workshops is told to keep them", () => {+ const facts = town({ homes: 12, residents: 30, stock: amounts({ tools: 2, planks: 30, stone: 10 }) }, ["fishery", "sheep"])+ assert.equal(guideStep(facts, new Set(guideDone(facts, none)))?.id, "tools")+})++test("the guide never asks for a building before the town can build it", () => {+ // Each step that names buildings, and what it asks for.+ const asks: Record<string, ReadonlyArray<KindId>> = {+ fishery: ["fishery"],+ winter: ["granary", "smokehouse"],+ planks: ["lumberjack", "sawmill"],+ forester: ["forester"],+ quarry: ["quarry"],+ firewatch: ["firewatch"],+ builder: ["builder"],+ market: ["market"],+ cloth: ["sheep", "weaver", "chapel"],+ bread: ["farm", "mill", "bakery"],+ healer: ["healer"],+ watchhouse: ["watchhouse"],+ smithy: ["mine", "smithy"]+ }+ // Whatever else is true, a town just short of each unlock.+ const everything = (residents: number, citizens: number) =>+ town({ homes: 30, residents, citizens, winter: true, winterIn: 60, worn: true, sick: 3, burning: 1 }, ["fishery", "lumberjack", "sawmill"])+ for (const step of guideSteps) {+ for (const kind of asks[step.id] ?? []) {+ const { residents, citizens } = kinds[kind].unlock+ if (residents > 0) assert.equal(step.when(everything(residents - 1, citizens)), false, `${step.id} asks for a ${kind} before ${residents} residents`)+ if (citizens > 0) assert.equal(step.when(everything(residents + 200, citizens - 1)), false, `${step.id} asks for a ${kind} before ${citizens} citizens`)+ assert.ok(kinds[kind].buildable, `${kind} can be built`)+ assert.match(step.text.toLowerCase(), new RegExp(kinds[kind].title.toLowerCase()), `${step.id} names the ${kind}, so it becomes a chip`)+ }+ }+})++test("every step can be done, and a town that has done them all is told nothing", () => {+ const all = guideSteps.flatMap((s) => [s.id])+ assert.equal(new Set(all).size, all.length, "step ids are unique")+ const finished = town(+ {+ homes: 200, residents: 400, citizens: 200, finerHomes: 30, crown: { open: true, met: 3 }, trading: true, taxed: true, sawTown: true,+ winter: true, worn: true, poorStreet: true, approval: 40, net: -5, most: 120, stock: amounts({ tools: 0 })+ },+ ["fishery", "lumberjack", "sawmill", "forester", "quarry", "granary", "firewatch", "builder", "market", "sheep", "weaver", "chapel", "farm", "mill", "bakery", "healer", "watchhouse", "mine", "smithy"]+ )+ assert.deepEqual(guideDone(finished, none).sort(), [...all].sort())+ assert.equal(guideStep(finished, none), null)+})diff --git a/test/save.test.ts b/test/save.test.tsindex 0f2fd9e..5d7b5fb 100644--- a/test/save.test.ts+++ b/test/save.test.ts@@ -132,3 +132,14 @@ test("loading takes the newer of the mayor's save and the autosave", () => {assert.equal((run(loadLatest) as { success: { slot: string } }).success.slot, "manual")assert.equal(run(read("auto"))._tag, "Success")})++test("a town saved before the guide loads, with the guide from its start", () => {+ const { town, storage, run } = setup()+ town.run(10)+ run(save("manual"))+ const file = JSON.parse(storage.get("inkline-town/save/manual")!)+ delete file.world.resources["Town/Guide"]+ storage.set("inkline-town/save/manual", JSON.stringify({ ...file, version: 6 }))+ assert.equal(run(load("manual"))._tag, "Success")+ assert.deepEqual(town.snapshot().resources["Town/Guide"], { done: [], off: false })+})