A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Teach newcomers: a guide course that waits for need, plainer panels, phone-ready hints
SandroMaglione4c38ff4f0124
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex ca10fe0..9d43fc4 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -52,7 +52,12 @@ for the guide and the map overlays. `host.ts` sets `body.fold-goods`,`fold-guide`, `fold-views` or `fold-more` while one is open; a tap on the mapfolds it, a pan or pinch does not. Once the town has a minute of goods(`body.flow-ready`), the goods chip opens the made/used table straight away,-each good by its icon. A new guide step peeks above the tool bar for a few seconds. Sheets+each good by its icon. The guide's step stays above the tool bar until tucked away+(its ✕); tucked, the bulb pulses, and a new step (or the same one under way)+comes out again. Guide texts in `src/rules/guide.ts` name tools,+panels and map views as `[homes]`, `[town]` or `[view:fire]` and verbs as+`{tap|click}`, never keys, so they read right on either screen;+`test/guide.test.ts` checks it. Sheetsopen from the side on a landscape phone (`max-height: 500px`) and from thebottom in portrait. Dialogs take the whole screen with their actions pinnedto the bottom. The camera bar is hidden: pinch zooms and turns. New UI needsdiff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 54339d7..dfdbbb3 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -106,8 +106,9 @@ Nobody tells you to build it that way; it works best that way.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- street is made of, and what keeps it from the next tier.+ above 0 it pays more, up to a quarter more. A home's panel lists its needs+ as one checklist: red for what it lacks now, amber for what it lacks to+ grow (its street among them), each with its cause.- **Parks** are laid out cell by cell from the build menu. Drag arectangle of ground (lawn, flower beds, gravel walks, a paved square),then click a cell of it to set a furnishing (a lamp, a fountain once 30@@ -164,23 +165,38 @@ from spreading, a fire watch near the cottages gets firefighters there intime, and industry away from homes keeps them healthy and orderly. The townticker under the top bar lists what needs attention *now* (fires, sickness,workshops that have waited half a minute for inputs, workplaces nobody can-walk to, no food in store) and, under *lately*, the news of the last minute+walk to, no food in store), each saying what to do about it, 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. It opens with homes, food, planks, and stone, one after-another, each once the last is built, and then shows where to look: a-home's panel, and the town panel. Citizens' needs come as one goal once-bread can be made, bread first, since settlers want only food. After that it speaks when the town-needs it (planks or stone running low, the woods thinning, a risk rising)-and keeps quiet for a while after each step; the crown's request, winter, a-fire, and the sick do not wait. A step that asks for a building is done when-the building stands, not when it is laid. 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.+Above them, the **guide** teaches a new mayor the game, one step at a+time: one thing to do, and one reason for it. It is a course, taught in+order chapter by chapter and counted (*step 3 of 8*). *Founding*: lay homes+along the town hall's road, lay a road to the water, build a fishery there,+open its panel to see its workers, build a lumberjack and a sawmill (once+planks run low), open the town panel to read the goal, and grow to ten+homes. *Growing citizens*:+a quarry, cloth, a chapel, bread, a look at what a home still lacks, and the+goals again. *Governing*: every goal met. While a step's homes or building+are going up it says so (carriers bringing planks to the site), so you know+you did your part; when the town cannot build what a step asks for yet, it+says what opens it (*the farm opens at 30 residents*), or that the treasury+must save up, and goes on to a building it can. It never asks for a+building before the town needs it, as upkeep starts the day it stands: the+lumberjack and sawmill wait until planks fall below 25, the quarry until+stone falls below 8, a market until homes lie beyond the town hall's walker,+a smithy until tools run low. Meanwhile the course goes on, and the card+says what comes next and when. Around the course, it speaks up when the town needs+something (stone running low, the woods thinning, a risk rising), ahead of+the course once the town is founded, and keeps quiet about such signs for a+while after each one; the crown's request, winter, a fire, and the sick do+not wait. Each building it asks for is a chip that starts placing one, each+tool, panel, or map view it names is a chip that picks it, and "show me+where" goes to the water, woods, rocks, or building it means. Its words+suit the screen: *tap* on a phone, *click* and the key on a computer. 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@@ -251,7 +267,10 @@ with the town, and starts over with a new one.**closed** from its panel: it stands empty, pays nothing, and costs thetown hall nothing, until it is reopened.- **Buildings** need a road at the middle of a side and workers of their- crew from homes within 15 road cells. While one is placed (or selected),+ crew from homes within 15 road cells. A building is not laid where no road+ touches the middle of a side (the ghost shows red, and says why), and a+ gatherer placed with nothing in reach (no water for a fishery, say) says+ so before it is laid. While one is placed (or selected),the roads its walkers or its workers would use are shown; the homes toolshows how far its residents would walk to work. Parks need no road and noworkers; their stone comes straight out of storage. Gatherers work the land within their reach (trees, rocks, water,diff --git a/src/content.ts b/src/content.tsindex 7543058..48fa272 100644--- a/src/content.ts+++ b/src/content.ts@@ -316,7 +316,7 @@ export const kindOrder: ReadonlyArray<KindId> = []export const costText = (cost: Kind["cost"]): string =>- [cost.coins > 0 ? `${cost.coins} coins` : "", ...Object.entries(cost.materials).map(([g, n]) => `${n} ${g}`)].filter((s) => s !== "").join(" · ")+ [cost.coins > 0 ? `${cost.coins} coins` : "", ...Object.entries(cost.materials).map(([g, n]) => `${n} ${n === 1 && g.endsWith("s") ? g.slice(0, -1) : g}`)].filter((s) => s !== "").join(" · ")// ── Parks ─────────────────────────────────────────────────────────────────diff --git a/src/factory.css b/src/factory.cssindex ee10eb0..1772c99 100644--- a/src/factory.css+++ b/src/factory.css@@ -115,6 +115,8 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.toast {position: fixed; bottom: calc(76px + env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); background: #3d4943; color: #f7f8f4;font-size: 12px; padding: 7px 14px; border-radius: 4px; opacity: 0; transition: opacity 160ms ease; pointer-events: none; z-index: 20;+ /* As wide as its words need, up to the screen: centred from the left edge, a box would only get half the screen to wrap in. */+ width: max-content; max-width: min(560px, calc(100vw - 28px)); box-sizing: border-box; text-align: center;}.toast.show { opacity: 1; }/* A stroke let go of on a touch screen: cancel and build, above the tool bar. */@@ -404,17 +406,17 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;/* ── Descriptions as rows: what, how much, and why underneath ── *//* Icon, what, and value on one line; chips and the note underneath, aligned with what. */.panel .lines .line {- display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; column-gap: 10px; row-gap: 5px; align-items: baseline; padding: 11px 0;+ display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; column-gap: 10px; row-gap: 3px; align-items: baseline; padding: 8px 0;}.panel .lines .line:first-of-type { padding-top: 2px; }.panel .lines .line:last-child { padding-bottom: 2px; }.panel .lines .line + .line { border-top: 1px dashed #e3e6df; }.panel .lines .line .mark { grid-column: 1; align-self: start; padding-top: 1px; }-.panel .lines .line .what { grid-column: 2; font-weight: 600; color: #3d4943; line-height: 1.35; }-.panel .lines .line .count { grid-column: 3; max-width: 200px; text-align: right; white-space: normal; line-height: 1.35; }-.panel .lines .line .chips { grid-column: 2 / -1; gap: 6px; }-.panel .lines .line.long .count { grid-column: 2 / -1; max-width: none; text-align: left; }-.panel .lines .line .note { grid-column: 2 / -1; font-size: 11px; line-height: 1.5; color: #6c766f; }+.panel .lines .line .what { grid-column: 2; font-weight: 400; color: #3d4943; line-height: 1.35; }+.panel .lines .line .count { grid-column: 3; max-width: 180px; text-align: right; white-space: normal; line-height: 1.35; font-variant-numeric: tabular-nums; }+.panel .lines .line .chips { grid-column: 3; justify-self: end; justify-content: flex-end; max-width: 220px; gap: 4px 6px; }+.panel .lines .line .note { grid-column: 2 / -1; font-size: 11px; line-height: 1.45; color: #6c766f; }+.panel .lines .line .count { font-weight: 600; }.panel .lines .line.ok .count { color: #4f8a3e; }.panel .lines .line.warn .count { color: #b8782e; }.panel .lines .line.bad .count { color: #b04a39; font-weight: 700; }@@ -422,6 +424,9 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel .lines .line.warn .note { color: #8a5a22; }.panel .lines .line.dim .count, .panel .lines .line.dim .what { color: #8a938c; font-weight: 400; }.panel .lines .line .chip { background: #eef0ea; border-radius: 4px; padding: 1px 6px 1px 4px; }+/* An amount as its icon and number: a coin and 3/min, a plank and 2. */+.amount { white-space: nowrap; }+.amount .icon { display: inline-block; width: 1.15em; height: 1.15em; margin-right: 2px; vertical-align: -0.2em; }/* ── The build menu: cost and what it does, in labelled rows ── */.panel .option { grid-template-rows: auto auto auto auto; }@@ -460,6 +465,18 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.hud .ticker .cell.guide .goal { display: grid; grid-template-columns: 12px minmax(0, 1fr); column-gap: 7px; align-items: start; margin-top: 6px; font-size: 11px; line-height: 1.7; color: #6d7f9c; }.hud .ticker .cell.guide .goal > .glyph, .hud .ticker .cell.guide .goal > svg { height: 1.7em; }.hud .ticker .cell.guide.place:hover { background: #eef3fb; }+/* What to do, then why under it, quieter. */+.hud .ticker .cell.guide .do { display: block; font-weight: 600; color: #2f3a34; }+.hud .ticker .cell.guide .why { display: block; margin-top: 3px; color: #5d6861; }+/* Under way: what was asked is done, and the town is at work on it. */+.hud .ticker .cell.guide.waiting { box-shadow: inset 3px 0 0 #7aa874; background: #f4f8f2; }+.hud .ticker .cell.guide.waiting .do { font-weight: 400; color: #8a948d; text-decoration: line-through; text-decoration-color: #b9c2bb; }+.hud .ticker .cell.guide.waiting .why { color: #3f6a3b; }+/* What the course waits to ask for, and when. */+.hud .ticker .cell.guide .goal.next { margin-top: 2px; color: #8a948d; }+/* Not yet open: what opens it, and what to do meanwhile. */+.hud .ticker .cell.guide.locked { box-shadow: inset 3px 0 0 #d9a24e; background: #fbf7ee; }+.hud .ticker .cell.guide.locked .why { color: #7a5a22; }.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; }@@ -472,6 +489,8 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;}.hud .ticker .cell:hover .act { opacity: 0.75; }.hud .ticker .act:hover { opacity: 1 !important; background: #e2e5de; border-color: #c9cec4; }+/* Tucking the guide away is a phone's peek's alone. */+.hud .ticker .act.tuck { display: none; }/* What a message names: a building to click and build, a good with its icon, a key to press. */.ref {display: inline-block; padding: 0 5px 0 4px; margin: 0 1px; border: 1px solid transparent; border-radius: 4px;@@ -482,6 +501,13 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.ref.kind { background: #eef3fb; border: 1px solid #c9d6ee; color: #2f5a9c; }button.ref.kind { cursor: pointer; }button.ref.kind:hover { background: #dce6f5; border-color: #3d6db5; }+/* A tool, panel, or map view: its chip picks it, and carries its key for a keyboard. */+.ref.tool { background: #f1f3ed; border: 1px solid #c9cec4; color: #3d4943; cursor: pointer; }+.ref.tool:hover { background: #e4e7df; border-color: #3d4943; }+.ref.tool kbd { margin-left: 4px; font: inherit; font-size: 10px; font-weight: 400; opacity: 0.55; }+@media (pointer: coarse) {+ .ref.tool kbd { display: none; }+}/* A building that stands already: its chip goes there. */.ref.kind.go { background: #f4f2ea; border-color: #d9d3bf; color: #5b5338; }button.ref.kind.go:hover { background: #ebe7d8; border-color: #8a7d55; }diff --git a/src/host.ts b/src/host.tsindex 19bd074..db6856d 100644--- a/src/host.ts+++ b/src/host.ts@@ -53,7 +53,7 @@ import { GRID } from "./iso.ts"import { goodIcon, icon, iconEl, type IconName } from "./icons.ts"import { generate } from "./mapgen.ts"import { askOf, priceOf } from "./sim/index.ts"-import type { Line, Stats, Tool, TradeMode, UiValue, View } from "./ui.ts"+import type { Group, Line, Stats, Tool, TradeMode, UiValue, View } from "./ui.ts"import { emptyPreview } from "./ui.ts"import { GameScene, type CameraView } from "./render3d/scene.ts"import { blobOf, cardFacts, drawCard, metaOf, scaled, verdictOf } from "./share/card.ts"@@ -89,22 +89,77 @@ const namedThings: ReadonlyArray<{ readonly word: string; readonly ref: { readon{ word: "loaves", ref: { good: "bread" as GoodId } },{ word: "loaf", ref: { good: "bread" as GoodId } }].sort((a, b) => b.word.length - a.word.length)-const namedPattern = new RegExp(`\\b(${namedThings.map((t) => t.word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b|\\(([A-Z])\\)`, "gi")+/**+ * Tools, panels, and map views a message can name in brackets ("[homes]",+ * "[view:fire]"): a chip that picks the tool, opens the panel, or shows the+ * view. The key goes beside it, for a keyboard (touch screens hide it).+ */+const toolRefs: Readonly<Record<string, { readonly label: string; readonly icon: IconName; readonly key?: string; readonly title: string }>> = {+ select: { label: "select", icon: "select", key: "S", title: "Select: pick a building or home to see what it does" },+ road: { label: "road", icon: "road", key: "R", title: "Road: drag to lay one" },+ pave: { label: "pave", icon: "pave", key: "P", title: "Pave: drag along a road to pave it" },+ homes: { label: "homes", icon: "homes", key: "H", title: "Homes: drag along a road to lay a row" },+ build: { label: "build", icon: "build", key: "B", title: "Open the build menu" },+ bulldoze: { label: "bulldoze", icon: "bulldoze", key: "X", title: "Bulldoze: remove what stands on a cell" },+ town: { label: "town", icon: "town", key: "T", title: "Open the town panel: goals, taxes, and trade" },+ speed: { label: "speed", icon: "clock", title: "Run time faster: 1×, 2×, 4×" },+ pause: { label: "pause", icon: "pause", key: "space", title: "Pause the town, or run it again" },+ "view:appeal": { label: "desirability map", icon: "appeal", key: "D", title: "Colour the map by desirability" },+ "view:workers": { label: "workers map", icon: "workers", key: "W", title: "Colour the map by workers" },+ "view:fire": { label: "fire map", icon: "fire", key: "F", title: "Colour the map by fire risk" },+ "view:health": { label: "health map", icon: "health", key: "A", title: "Colour the map by health risk" },+ "view:order": { label: "order map", icon: "order", key: "O", title: "Colour the map by the risk of theft" },+ "view:condition": { label: "condition map", icon: "condition", key: "C", title: "Colour the map by the condition of buildings" }+}+const namedPattern = new RegExp(+ `\\b(${namedThings.map((t) => t.word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b|\\(([A-Z])\\)|\\[([a-z]+(?::[a-z]+)?)\\]`,+ "gi"+)+/** Goods as numbers name them ("2 planks", "1 plank"), and as recipes do ("flour → bread"), by title. */+const goodWords: ReadonlyArray<readonly [string, GoodId]> = [+ ...goodIds.map((id) => [goods[id].title, id] as const),+ ...goodIds.filter((id) => goods[id].title.endsWith("s")).map((id) => [goods[id].title.slice(0, -1), id] as const)+].sort((a, b) => b[0].length - a[0].length)+const goodAlternatives = goodWords.map(([w]) => w).join("|")+const goodOf = (word: string) => goodWords.find(([w]) => w === word)![1]+/**+ * Amounts in a line of (escaped) text as icons, where the icon says it as+ * well as the word: "3 coins a minute" as a coin and 3/min, "2 planks" as a+ * plank and 2, "flour → bread" with each good's icon.+ */+const iconize = (html: string): string =>+ html+ .replace(/([+−-]?)(\d+) coins a minute/g, (_, sign: string, n: string) => `<span class="amount">${sign}${icon("coins", 13)}${n}/min</span>`)+ .replace(/(\d+) coins\b/g, (_, n: string) => `<span class="amount">${icon("coins", 13)}${n}</span>`)+ .replace(new RegExp(`(\\d+) (${goodAlternatives})\\b`, "g"), (_, n: string, w: string) => `<span class="amount">${goodIcon(goodOf(w), 13)}${n}</span>`)+ .replace(new RegExp(`\\b(${goodAlternatives}) → (${goodAlternatives})\\b`, "g"), (_, a: string, b: string) => `<span class="amount">${goodIcon(goodOf(a), 13)}${a}</span> → <span class="amount">${goodIcon(goodOf(b), 13)}${b}</span>`)++/** A finger rather than a mouse: messages say "tap", and keys are left out. */+const touchScreen = () => matchMedia("(pointer: coarse)").matches+/** `{tap|click}`: the first on a touch screen, the second with a mouse. */+const forDevice = (text: string) => text.replace(/\{([^{}|]*)\|([^{}|]*)\}/g, (_, touch: string, mouse: string) => (touchScreen() ? touch : mouse))/*** A message as markup: each building it names becomes a chip to click (to- * build one), each good a chip with its icon, and each key in brackets a key.+ * build one), each good a chip with its icon, each key in round brackets a+ * key, and each tool in square brackets a chip that picks it.+ * `standing`: buildings the line is about, which stand already; their chips go to them rather than placing another.+ * `asks`: when given, only these buildings become chips to place one; others it names are plain words.*/-/** `standing`: buildings the line is about, which stand already; their chips go to them rather than placing another. */-const callouts = (text: string, standing: ReadonlySet<KindId> = new Set()): string =>- escapeHtml(text).replace(namedPattern, (match, word: string | undefined, key: string | undefined) => {+const callouts = (text: string, standing: ReadonlySet<KindId> = new Set(), asks?: ReadonlySet<KindId>): string =>+ escapeHtml(forDevice(text)).replace(namedPattern, (match, word: string | undefined, key: string | undefined, tool: string | undefined) => {if (key) return `<kbd class="key">${key}</kbd>`+ if (tool) {+ const ref = toolRefs[tool]+ if (!ref) return match+ return `<button class="ref tool" data-tool="${tool}" title="${escapeHtml(ref.title)}">${icon(ref.icon, 13)}${ref.label}${ref.key ? `<kbd>${ref.key}</kbd>` : ""}</button>`+ }const thing = namedThings.find((t) => t.word === word!.toLowerCase())if (!thing) return matchif ("good" in thing.ref) return `<span class="ref ware" title="${goods[thing.ref.good].title}">${goodIcon(thing.ref.good, 13)}${match}</span>`const kind = kinds[thing.ref.kind]if (standing.has(thing.ref.kind)) return `<button class="ref kind go" data-go="${thing.ref.kind}" title="Go to the ${kind.title.toLowerCase()}">${icon("locate", 13)}${match}</button>`- return kind.buildable+ return kind.buildable && (!asks || asks.has(thing.ref.kind))? `<button class="ref kind" data-kind="${thing.ref.kind}" title="Build a ${kind.title.toLowerCase()}: ${escapeHtml(kind.blurb)}">${icon("build", 13)}${match}</button>`: `<span class="ref kind" title="${escapeHtml(kind.blurb)}">${icon("town", 13)}${match}</span>`})@@ -313,6 +368,11 @@ export const createHost = async (if (mapPress?.id === e.pointerId && Math.hypot(e.clientX - mapPress.x, e.clientY - mapPress.y) > 8) mapPress.moved = true})mount.addEventListener("pointerup", (e) => {+ // A tap on the map puts a toast away (one it raised itself stays): a pan or a pinch, to look for the spot, does not.+ if (mapPress?.id === e.pointerId && !mapPress.moved && toastBox.classList.contains("show") && Date.now() - toastAt > 250) {+ window.clearTimeout(toastTimer)+ toastBox.classList.remove("show")+ }if (mapPress?.id === e.pointerId && !mapPress.moved && fold !== null) setFold(null)if (mapPress?.id === e.pointerId) mapPress = null})@@ -325,6 +385,8 @@ export const createHost = async (}let toastTimer = 0+ /** When the toast showing went up: a press on the map just after does not put it away. */+ let toastAt = 0const ui: UiValue = {tool: "select",placing: null,@@ -350,11 +412,14 @@ export const createHost = async (tints: new Map(),legend: null,flash: null,+ // Long enough to read (about 15 letters a second, and a moment to look), and gone as soon as the mayor+ // touches the map again: by then they have read it, or are acting on it.toast: (message) => {toastBox.textContent = messagetoastBox.classList.add("show")+ toastAt = Date.now()window.clearTimeout(toastTimer)- toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), 1800)+ toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), Math.min(8000, Math.max(2200, 1200 + message.length * 65)))}}@@ -563,19 +628,22 @@ export const createHost = async (ui.placing = kindui.menu = nullchoose("place")- ui.toast(`Click to place a ${kinds[kind].title.toLowerCase()} · Esc to stop`)+ const title = kinds[kind].title.toLowerCase()+ ui.toast(touchScreen() ? `Tap a spot for the ${title}, then tap it again to build it` : `Click to place a ${title} · Esc to stop`)}const layGround = (ground: GroundId) => {ui.ground = groundui.menu = nullchoose("ground")- ui.toast(`Drag a rectangle to lay ${grounds[ground].title.toLowerCase()} · Esc to stop`)+ const title = grounds[ground].title.toLowerCase()+ ui.toast(touchScreen() ? `Drag a rectangle to lay ${title}, then tap Build` : `Drag a rectangle to lay ${title} · Esc to stop`)}const furnish = (prop: PropId) => {ui.prop = propui.menu = nullchoose("prop")- ui.toast(`Click a cell of park to set a ${props[prop].title.toLowerCase()} · Esc to stop`)+ const title = props[prop].title.toLowerCase()+ ui.toast(touchScreen() ? `Tap a cell of park for the ${title}, then tap it again to set it` : `Click a cell of park to set a ${title} · Esc to stop`)}choose("select")@@ -1179,13 +1247,14 @@ export const createHost = async (/** A line of a description as a row: its icon and what it is about, its value, any goods as chips, and a note underneath saying why. */const renderLine = (row: HTMLElement, l: Line) => {- // A value too long to sit beside the label goes under it, aligned with it.- row.className = `line ${l.tone ?? ""}${(l.value ?? "").length > 14 ? " long" : ""}`+ // Every row the same way: what on the left, its value on the right, any note under both.+ row.className = `line ${l.tone ?? ""}`const chips = l.goods ? `<span class="chips">${l.goods.map((g) => `<span class="chip" title="${goods[g.good].title}">${goodIcon(g.good, 14)}${g.count}</span>`).join("")}</span>` : ""- row.innerHTML = `<span class="mark">${icon(l.icon, 16)}</span><span class="what"></span><span class="count"></span>${chips}${l.note ? `<small class="note"></small>` : ""}`+ // Goods take the value's place: chips on the right.+ row.innerHTML = `<span class="mark">${icon(l.icon, 16)}</span><span class="what"></span>${chips || `<span class="count"></span>`}${l.note ? `<small class="note"></small>` : ""}`row.querySelector<HTMLElement>(".what")!.textContent = l.label- row.querySelector<HTMLElement>(".count")!.textContent = l.value ?? ""- if (l.note) row.querySelector<HTMLElement>(".note")!.textContent = l.note+ if (!chips) row.querySelector<HTMLElement>(".count")!.innerHTML = iconize(escapeHtml(l.value ?? ""))+ if (l.note) row.querySelector<HTMLElement>(".note")!.innerHTML = iconize(escapeHtml(l.note))}/** Keeps a box of rows in step with its lines, touching only the rows that changed. */const syncLines = (box: HTMLElement, rows: Array<HTMLElement>, lines: ReadonlyArray<Line>) => {@@ -1224,26 +1293,36 @@ export const createHost = async (: p.type === "park"? "every cell of ground that touches this one: lay more, or set furnishings on it, to make the streets around it nicer": p.tier === 1- ? "settlers: fish or bread from a market keeps them; they do the rough work"+ ? "settlers live here and 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 ${home.tiers[3].appeal}) that every service calls on`+ ? "citizens live here, do the skilled work, and pay twice as much"+ : "burghers live here, and pay the best taxes")const below = el("div", "")below.append(status, about)panel.append(header(title, p.type === "ruin" ? iconEl("condition", 30) : p.type === "park" ? iconEl("decor", 30) : picture(p.type === "building" ? p.kind : p.tier), below))- const box = section(p.type === "building" ? "at work" : p.type === "ruin" ? "what is left" : p.type === "park" ? "what makes it" : "household", p.type === "building" ? "jobs" : p.type === "park" ? "appeal" : "homes")- box.classList.add("lines")- const rows: Array<HTMLElement> = []- panel.append(box)- // A home: what keeps it from the next tier, in its own box, so the cause is never a word in a longer line.- const nextBox = p.type === "house" && p.tier < 3 ? section(`to become ${home.tiers[(p.tier + 1) as Tier].title}`, "citizens", "Every line here must clear before the home grows. Needs come from walkers; the street from what stands around it.") : null- const nextRows: Array<HTMLElement> = []- const nextNote = el("p", "empty")- if (nextBox) {- nextBox.classList.add("lines")- nextBox.append(nextNote)- panel.append(nextBox)+ // A building or a home: its rows in boxes under headings, kept in step with what the town says each frame.+ // A park or a ruin: one box.+ const holder = el("div", "")+ panel.append(holder)+ const slots: Array<{ box: HTMLElement; rows: Array<HTMLElement>; key: string }> = []+ const syncGroups = (groups: ReadonlyArray<Group>) => {+ groups.forEach((g, i) => {+ const key = `${g.title}|${g.icon}|${g.help ?? ""}`+ let slot = slots[i]+ if (!slot || slot.key !== key) {+ const box = section(g.title, g.icon, g.help)+ box.classList.add("lines")+ const fresh = { box, rows: [] as Array<HTMLElement>, key }+ if (slot) slot.box.replaceWith(box)+ else holder.append(box)+ slots[i] = fresh+ slot = fresh+ }+ slot.box.style.display = ""+ syncLines(slot.box, slot.rows, g.lines)+ })+ for (const extra of slots.slice(groups.length)) extra.box.style.display = "none"}live.push(() => {const now = ui.panel@@ -1251,24 +1330,19 @@ export const createHost = async (if (now.type === "building") {status.textContent = now.problem ?? now.statusstatus.className = `pill ${now.problem !== null ? "problem" : now.status === "working" ? "working" : ""}`+ syncGroups(now.groups)} else if (now.type === "house") {- status.textContent = `${home.tiers[now.tier].residents} at most`- status.className = "pill working"+ status.textContent = now.summary+ status.className = `pill ${now.trouble ? "problem" : "working"}`+ syncGroups(now.groups)} else if (now.type === "park") {status.textContent = `${now.value > 0 ? "+" : ""}${now.value} out to ${now.reach} cells`status.className = "pill working"+ syncGroups([{ title: "what makes it", icon: "appeal", lines: now.lines }])} else {status.textContent = now.causestatus.className = "pill problem"- }- 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"- nextBox.append(nextNote)+ syncGroups([{ title: "what is left", icon: "condition", lines: now.lines }])}})if (!(p.type === "building" && p.kind === "townhall")) {@@ -1758,14 +1832,36 @@ export const createHost = async (input.reset()}+ /** What a tool chip in a message does (see `toolRefs`): picks the tool, opens the panel, or shows the map view. */+ const useTool = (id: string) => {+ setFold(null)+ if (id.startsWith("view:")) {+ const view = id.slice(5) as View+ return setView(ui.view === view ? "none" : view)+ }+ if (id === "build" || id === "town") return ui.menu === id ? undefined : toggleMenu(id)+ if (id === "speed") return setSpeed(ui.speed === 0 ? lastSpeed : ui.speed === 4 ? 1 : ui.speed * 2)+ if (id === "pause") return setSpeed(ui.speed === 0 ? lastSpeed : 0)+ ui.menu = null+ choose(id === "homes" ? "home" : (id as Tool))+ }/** Ticker lines the mayor has put away, by what they say (and, for news, when). */const dismissed = new Set<string>()let tickerLines: { guide: Stats["guide"]["step"]; alerts: Stats["alerts"]; news: Stats["chronicle"] } = { guide: null, alerts: [], news: [] }ticker.onclick = (event) => {event.stopPropagation()- // On a phone the peeking line opens the guide in full.- if (ticker.classList.contains("peek")) return setFold("guide")const target = event.target as HTMLElement+ // A tool, panel, or map view the line names: pick it, with the map in view.+ const tool = target.closest<HTMLElement>("[data-tool]")+ if (tool) return useTool(tool.dataset.tool!)+ // On a phone: tuck the step away into the bulb, or open the guide in full.+ if (target.closest("[data-tuck]")) {+ tucked = stepNow+ if (!toldWhere) ui.toast("The guide is in the bulb at the top right")+ toldWhere = true+ return+ }+ if (ticker.classList.contains("peek") && !target.closest("[data-kind]")) return setFold("guide")const off = target.closest<HTMLElement>("[data-dismiss]")if (off) {dismissed.add(off.dataset.dismiss!)@@ -1788,13 +1884,19 @@ export const createHost = async (const row = go.closest<HTMLElement>("[data-alert]")const there = row ? tickerLines.alerts[Number(row.dataset.alert)]?.places?.[go.dataset.go as KindId] : undefinedif (there) goTo(there.at, there.size, there.id)+ // The guide's step names the building it points at.+ const guide = tickerLines.guide+ if (!row && go.closest("[data-guide]") && guide?.at) goTo(guide.at, guide.size, guide.id)return}const ref = target.closest<HTMLElement>("[data-kind]")if (ref) {const kind = ref.dataset.kind as KindId- // Straight to placing it: the placement itself says if the town cannot build it yet.- if (kinds[kind].buildable) place(kind)+ // Straight to placing it, with the map in view: the placement itself says if the town cannot build it yet.+ if (kinds[kind].buildable) {+ setFold(null)+ place(kind)+ }return}const line = target.closest<HTMLElement>(".cell.place")@@ -1808,9 +1910,14 @@ export const createHost = async (/** The last chronicle line announced. */let lastNews = ""- /** The guide step last shown, and the timer that hides its peek. */- let lastStep = ""- let peekTimer = 0+ /**+ * A phone's guide: the step stays above the tool bar until the mayor tucks it away (`tucked`: the step and+ * state they tucked; a new step, or the same one under way, comes out again). Tucked away, the bulb pulses,+ * and the first time a toast says where the guide went.+ */+ let stepNow = ""+ let tucked = ""+ let toldWhere = false/** Copies the town's numbers and preview into the page, once a frame. */const syncPage = () => {syncPanel()@@ -1921,10 +2028,22 @@ export const createHost = async (// The guide's step first: what to do next, and why.const g = s.guide.stepconst 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 class="goal">${icon("goal", 12)}<span>done when ${callouts(g.goal)}</span></span></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 asks = new Set(g.asks)+ const say = (text: string) => callouts(text, new Set(g.near ? [g.near] : []), asks)+ const count = g.count ? `step ${g.count.at} of ${g.count.of}` : ""+ return [+ `<div class="head guide"><span>guide · ${escapeHtml(g.chapter)}</span><span class="progress" title="${g.count ? "The first steps of a new town" : ""}">${count}</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.waiting ? " waiting" : g.locked ? " locked" : ""}${g.at !== null ? " place" : ""}" data-guide>${icon(g.waiting ? "clock" : g.locked ? "caution" : "hint", 16, "mark")}<span class="text">` ++ `<span class="do">${say(g.text)}</span>` ++ (g.waiting ? `<span class="why now">${say(g.waiting)}</span>` : g.locked ? `<span class="why now">${say(g.locked)}</span>` : `<span class="why">${say(g.why)}</span>`) ++ `<span class="goal">${icon("goal", 12)}<span>done when ${say(g.goal)}</span></span>` ++ (g.next ? `<span class="goal next">${icon("clock", 12)}<span>${say(g.next)}</span></span>` : "") ++ `</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>` ++ `<button class="act tuck" data-tuck title="Hide: the guide stays in the bulb at the top right">${icon("close", 12)}</button></div>`+ ]+ })(): []const tickerHtml = [...guideHtml,@@ -1947,18 +2066,18 @@ export const createHost = async (ticker.classList.toggle("show", tickerHtml !== "" && s.fate.state === "playing")// The phone's guide button: the step it is on, or how many things need looking at.const bad = alerts.some((a) => a.tone === "bad")- const badge = g ? `${s.guide.done + 1}/${s.guide.total}` : alerts.length > 0 ? String(alerts.length) : ""+ const things = alerts.length + (g ? 1 : 0)+ const badge = g?.count ? `${g.count.at}/${g.count.of}` : things > 0 ? String(things) : ""if (guideBadge.textContent !== badge) guideBadge.textContent = badgeguideBulb.classList.toggle("alert", bad)- // A new step peeks out above the tool bar for a few seconds.- const stepKey = g?.key ?? ""- // Not behind the town picker: the step waits until the town is founded.- if (stepKey !== lastStep && !ui.founding) {- lastStep = stepKey- window.clearTimeout(peekTimer)- ticker.classList.toggle("peek", stepKey !== "" && phone.matches && fold === null)- if (stepKey !== "") peekTimer = window.setTimeout(() => ticker.classList.remove("peek"), 7000)- }+ // On a phone the step stays out above the tool bar, until tucked away; not behind the town picker or an open sheet.+ const stepKey = g ? `${g.key}${g.waiting ? ":under way" : g.locked ? ":locked" : ""}` : ""+ stepNow = stepKey+ const peeking = stepKey !== "" && phone.matches && fold === null && tucked !== stepKey && !ui.founding && s.fate.state === "playing"+ if (ticker.classList.contains("peek") !== peeking) ticker.classList.toggle("peek", peeking)+ document.body.classList.toggle("peeking", peeking)+ const nudge = stepKey !== "" && phone.matches && tucked === stepKey && fold !== "guide"+ if (guideBulb.classList.contains("nudge") !== nudge) guideBulb.classList.toggle("nudge", nudge)// News as it happens: a toast for each new alarm line.const latest = s.chronicle.at(-1)const seen = `${s.charter.seed}|${latest?.tick ?? -1}|${s.chronicle.length}`@@ -1987,7 +2106,7 @@ export const createHost = async (strokeBar.classList.toggle("open", held)document.body.classList.toggle("stroke-held", held)if (text && screenPointer) {- tooltip.textContent = text+ setHtml(tooltip, iconize(escapeHtml(text)))tooltip.style.display = "block"tooltip.style.left = `${Math.min(screenPointer.x, window.innerWidth - tooltip.offsetWidth - 20)}px`tooltip.style.top = `${screenPointer.y}px`diff --git a/src/phone.css b/src/phone.cssindex 4df1b72..96f4ee7 100644--- a/src/phone.css+++ b/src/phone.css@@ -70,15 +70,24 @@.fold-buttons .badge:empty { display: none; }.fold-buttons .alert .badge { background: #b04a39; }- /* ── The guide: folded to the bulb; a new step peeks above the tool bar; open, a sheet ── */+ /* ── The guide: its step stays above the tool bar until tucked into the bulb; open, a sheet ── */.hud .ticker.show { display: none; width: auto; }.hud .ticker.show.peek {display: flex; position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(58px + env(safe-area-inset-bottom));width: min(460px, calc(100vw - 16px)); cursor: pointer;}- .hud .ticker.peek > :not(.cell.guide), .hud .ticker.peek .goal, .hud .ticker.peek .acts { display: none; }+ /* The peek is what to do now: the step, or once under way, what the town is doing about it. */+ .hud .ticker.peek > :not(.cell.guide), .hud .ticker.peek .cell.guide .goal, .hud .ticker.peek .acts, .hud .ticker.peek .cell.guide .why, .hud .ticker.peek .cell.guide.waiting .do, .hud .ticker.peek .cell.guide.locked .do { display: none; }+ .hud .ticker.peek .cell.guide .why.now { display: inline; margin: 0; }.hud .ticker.peek .cell.guide { padding: 7px 10px 7px 12px; font-size: 11px; line-height: 1.45; }- .hud .ticker.peek .cell.guide .text { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }+ .hud .ticker.peek .cell.guide .text { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden; }+ .hud .ticker.peek .cell.guide .do { display: inline; }+ .hud .ticker.peek .act.tuck { display: flex; flex: none; align-self: center; width: 30px; height: 30px; margin: -4px -4px -4px 0; opacity: 0.6; }+ /* A toast goes above the guide's step, not over it. */+ .peeking .toast { bottom: calc(150px + env(safe-area-inset-bottom)); }+ /* Tucked away, the bulb pulses a few times, so the mayor sees where the guide went. */+ @keyframes guide-nudge { 0% { box-shadow: 0 0 0 0 rgba(47, 90, 156, 0.55); } 70% { box-shadow: 0 0 0 10px rgba(47, 90, 156, 0); } 100% { box-shadow: 0 0 0 0 rgba(47, 90, 156, 0); } }+ .fold-buttons button.nudge { animation: guide-nudge 1.4s ease-out 4; }.fold-guide .hud.left { z-index: 4; }.fold-guide .fold-buttons { z-index: 5; }.fold-guide .hud .ticker.show {@@ -135,7 +144,7 @@font-size: 12px; gap: 10px; padding: 7px 12px 7px 9px; min-height: 34px; justify-content: flex-start; color: #3d4943;}- .toast { bottom: calc(108px + env(safe-area-inset-bottom)); max-width: calc(100vw - 28px); white-space: normal; text-align: center; }+ .toast { bottom: calc(108px + env(safe-area-inset-bottom)); max-width: calc(100vw - 24px); white-space: normal; text-align: center; font-size: 13px; line-height: 1.4; padding: 9px 14px; }.stroke-bar { bottom: calc(56px + env(safe-area-inset-bottom)); }/* A held stroke's buttons take the guide's place above the tool bar. */.stroke-held .hud .ticker.peek { display: none; }diff --git a/src/present.ts b/src/present.tsindex 15ee10a..5b9d21d 100644--- a/src/present.ts+++ b/src/present.ts@@ -13,7 +13,7 @@ import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, Ruiimport type { DoorSet, OverlayCell } from "./render3d/models.ts"import {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+ PAVE_COST, propIds, props, risk, RISK_MAX, ROAD_COST, tierHome, total, winters, type Amounts, type GoodId, type Kind, type KindId, type Need, 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"@@ -84,13 +84,13 @@ import {} from "./schema.ts"import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, seasonAt, SITE_SHARE, steadyNet, taxOf, termTicks, winterOf } from "./sim/index.ts"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 { emptyPreview, type Alert as Notice, type Group, type HitBox, type Legend, type Line, type View } from "./ui.ts"+import { blockers as blockersOf, streetAdvice, streetShort, whyUnmet, type InTown, type Served, type Street } from "./rules/explain.ts"import { breadBonus, moreAdmin, streetTax, suppliedTaxOf, taxOutlook, type TaxedHome } from "./rules/households.ts"import { approvalTarget } from "./rules/approval.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 { courseCount, GUIDE_QUIET, guideDone, guideStep, guideSteps, lockedNote, upcoming, type GuideFacts, type GuideFocus } from "./rules/guide.ts"import { TAX_STEPS, ticks } from "./content.ts"const cellAt = (at: Point): Point => {@@ -430,7 +430,7 @@ export const Interact = Game.System(return sum + taxOf({ ...fed, residents: capacity(fed, approval, d, undefined, rates.settlers) }, rates, undefined, d)}, 0)const worth = Math.round(pays - moreAdmin(standing, n))- return ` · ${n === 1 ? "this home" : "these homes"}: ${signed(worth)} coins a minute after administration, once fed${worth <= 0 ? " · past what the town hall can run cheaply: finer homes pay better than more of them" : ""}`+ return worth > 0 ? ` · ${signed(worth)} coins a minute once fed` : " · costs more to run than it pays: finer homes pay better"}const hits: Array<HitBox> = [@@ -445,6 +445,27 @@ export const Interact = Game.System(ui.hits = hitsconst tileOf = (id: number) => [...buildings, ...houses, ...ruins, ...parkRows].find((row) => row.entity.id === id)?.data.tile.get()+ /**+ * What is wrong with a building where it would stand, before it is laid: no road at the middle of a side (it is+ * not laid: nobody could bring its materials or work there), or nothing in reach to gather (laid, but said).+ */+ const placeProblem = (kind: Kind, tile: TileLike): { readonly refuse: boolean; readonly text: string } | null => {+ if (!canPlace(grid, tile) || lockReason(kind, resources.census.get())) return null+ if (doors(grid, tile).length === 0) return { refuse: true, text: "needs a road at the middle of one side" }+ const source = kind.gathers?.source+ if (!source || source === "field") return null+ const reachCells = around(tile, kind.gathers!.radius)+ const found =+ source === "stone" || source === "ore"+ ? queries.rocks.each().some(({ data }) => {+ const t = data.tile.get()+ return data.rock.get().ore === (source === "ore") && reachCells.some((c) => c.x >= t.x && c.x < t.x + t.size && c.y >= t.y && c.y < t.y + t.size)+ })+ : reachCells.some((c) => useAt(grid, c.x, c.y) === source)+ const what = { tree: "trees", stone: "pale stone rocks", ore: "dark ore rocks", water: "water" }[source]+ return found ? null : { refuse: false, text: `no ${what} within ${kind.gathers!.radius} cells` }+ }+// ── Gestures ──for (const gesture of ui.gestures.splice(0)) {const cell = cellAt(gesture.at)@@ -475,7 +496,14 @@ export const Interact = Game.System(}case "place": {if (gesture.panned || !ui.placing) break- ui.edits.push({ type: "building", kind: ui.placing, cell: footprintAt(gesture.at, kinds[ui.placing].size), open: false })+ const kind = kinds[ui.placing]+ const at = footprintAt(gesture.at, kind.size)+ const problem = placeProblem(kind, { ...at, size: kind.size })+ if (problem?.refuse) {+ ui.toast(`A ${kind.title.toLowerCase()} ${problem.text}`)+ break+ }+ ui.edits.push({ type: "building", kind: ui.placing, cell: at, open: false })break}case "bulldoze": {@@ -554,9 +582,9 @@ export const Interact = Game.System(}if (ui.tool === "home" && cell && inside(cell.x, cell.y)) {rangeFrom({ ...(ui.dragFrom ?? cell), size: 1 }, COMMUTE + 1, `residents walk to work within ${COMMUTE} road cells`)- preview.tooltip = `homes · ${costText(home.cost)} each · along a road${homesWorth(preview.ghosts.map((g) => g.cell))} · ${preview.rangeNote ?? "touch a road and residents walk to work within " + COMMUTE + " road cells"}`+ preview.tooltip = `homes · ${costText(home.cost)} each${preview.rangeNote ? homesWorth(preview.ghosts.map((g) => g.cell)) : " · lay them beside a road"}`}- if (ui.tool === "road" && cell) preview.tooltip = `road · ${ROAD_COST} coins a cell · buildings need one at the middle of a side`+ if (ui.tool === "road" && cell) preview.tooltip = `road · ${ROAD_COST} coins a cell`if (ui.dragFrom && cell) {const n = ui.tool === "road" ? preview.roads.length : ui.tool === "home" ? preview.ghosts.length : preview.plots.filter((p) => p.look === "reach").lengthpreview.stroke =@@ -576,11 +604,9 @@ export const Interact = Game.System(}preview.parks.push(...laid)const after = laid.length > 0 ? parkOf(laid[0]!, laid) : undefined- // What the park it joins gives now, if it joins one.- const before = laid.map((c) => parkOf(c)).find((p) => p !== undefined)const cost = costText(times(grounds[ui.ground].cost, laid.length))if (ui.dragFrom) preview.stroke = `${grounds[ui.ground].title.toLowerCase()} · ${counted(laid.length, "cell")} · ${cost}`- preview.tooltip = `${grounds[ui.ground].title.toLowerCase()} · ${counted(laid.length, "cell")}, ${cost}${after ? ` · the park: ${parkText(after)}${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""} · drag a rectangle`+ preview.tooltip = `${grounds[ui.ground].title.toLowerCase()} · ${cost}${after ? ` · park ${signed(after.value)} desirability` : ""}`if (after) preview.plots.push(...reachPlots(after))} else if (ui.tool === "prop" && cell && inside(cell.x, cell.y)) {const there = parkAt.get(key(cell.x, cell.y))?.data.park.get()@@ -589,7 +615,7 @@ export const Interact = Game.System(preview.parks.push(placed)const before = parkOf(cell)const after = parkOf(cell, [placed])- preview.tooltip = `${props[ui.prop].title.toLowerCase()} · ${costText(props[ui.prop].cost)}${after ? ` · the park: ${parkText(after)}${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""}${after && after.crowded > 0 ? " · too crowded: lay more ground for it to count" : ""}`+ preview.tooltip = `${props[ui.prop].title.toLowerCase()} · ${costText(props[ui.prop].cost)}${after ? ` · park ${signed(after.value)} desirability${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""}${after && after.crowded > 0 ? " · too crowded" : ""}`if (after) preview.plots.push(...reachPlots(after))} else {preview.plots.push({ ...cell, size: 1, look: "blocked" })@@ -603,8 +629,11 @@ export const Interact = Game.System(rangeOfKind(tile, kind)if (kind.appeal) preview.plots.push({ x: tile.x - kind.appeal.reach, y: tile.y - kind.appeal.reach, size: tile.size + 2 * kind.appeal.reach, look: kind.appeal.value > 0 ? "reach" : "hover" })if (lockReason(kind, resources.census.get())) preview.plots.push({ ...tile, look: "blocked" })- else if (canPlace(grid, tile)) preview.ghosts.push({ what: ui.placing, cell: at })- else preview.plots.push({ ...tile, look: "blocked" })+ else if (canPlace(grid, tile)) {+ preview.ghosts.push({ what: ui.placing, cell: at })+ // No road at a side's middle: shown red under the ghost, as it will not be laid there.+ if (placeProblem(kind, tile)?.refuse) preview.plots.push({ ...tile, look: "blocked" })+ } else preview.plots.push({ ...tile, look: "blocked" })} else if (ui.tool === "bulldoze") {preview.danger = trueif ((preview.hover === null || useAt(grid, cell?.x ?? -1, cell?.y ?? -1) === "park") && cell && ["road", "tree", "field", "park"].includes(useAt(grid, cell.x, cell.y)))@@ -669,108 +698,98 @@ export const Interact = Game.System(}// ── Tooltip and panel ──+ /**+ * A building, for its panel: what it is doing (workers, what it makes, what it holds), then what it costs to run+ * (upkeep, wear, fire, its street). Each row is a value; a note only when something wants doing.+ */const describeBuilding = (row: (typeof buildings)[number]) => {const kind = kinds[row.data.building.get().kind]const status = row.data.status.get()const site = maybe(row.data.site)- const lines: Array<Line> = []if (site) {const owed = (Object.entries(site.owed) as Array<[GoodId, number]>).filter(([, n]) => n > 0)- lines.push(+ const line: Line =owed.length > 0- ? { icon: "build", label: "a site", value: "waiting for", goods: owed.map(([good, count]) => ({ good, count })), note: "carriers bring materials from storage; buy what the town lacks in the town panel", tone: "warn" }- : { icon: "build", label: "a site", value: "going up", tone: "ok" }- )- return { kind, status, problem: null, lines }+ ? { icon: "build", label: "waiting for", goods: owed.map(([good, count]) => ({ good, count })), tone: "warn", note: "carriers bring them from storage: buy what the town lacks in the town panel" }+ : { icon: "build", label: "builders", value: "at work", tone: "ok" }+ return { kind, status, problem: null, groups: [{ title: "being built", icon: "build", lines: [line] }] as Array<Group> }}const staff = row.data.staff.get()+ const work: Array<Line> = []if (staff.needed > 0) {const crew = kind.crew- const one = crew === "citizens" ? "citizen" : "settler"const short = staff.assigned < staff.needed- lines.push({+ work.push({icon: "workers",label: "workers",value: `${staff.assigned} of ${staff.needed}`,tone: !short ? "ok" : staff.assigned > 0 ? "warn" : "bad",note: short? staff.nearby === 0- ? `no ${crew} live within ${COMMUTE} road cells: lay homes nearer${crew === "citizens" ? ", or settlers stand in as apprentices" : ""}`- : `every ${one} nearby already has a job: lay more homes within ${COMMUTE} road cells`+ ? `no ${crew} live within ${COMMUTE} road cells: lay homes nearer`+ : `everyone nearby has a job: lay more homes within ${COMMUTE} road cells`: staff.apprentices > 0- ? `${staff.apprentices} settler apprentice${staff.apprentices > 1 ? "s" : ""} stand in for citizens, at three-quarters pace`+ ? `settlers stand in for citizens, at three-quarters pace`: undefined})- lines.push({ icon: crew, label: `${crew} within ${COMMUTE} road cells`, value: `${staff.nearby}`, tone: "dim" })}const recipe = maybe(row.data.recipe)- const inventory = maybe(row.data.inventory)if (recipe)- lines.push({- icon: recipe.output,- label: "makes",- value: `${recipe.input ? `${recipe.inputs} ${goods[recipe.input].title} → ` : ""}${recipe.batch} ${goods[recipe.output].title} · a job every ${Math.round(recipe.period / 60)} s`,- note: `${recipe.made} made so far${recipe.input ? ` · carriers bring ${goods[recipe.input].title} from whoever makes it, or storage` : ""}`+ work.push({ icon: recipe.output, label: "makes", value: recipe.input ? `${goods[recipe.input].title} → ${goods[recipe.output].title}` : goods[recipe.output].title })+ const service = maybe(row.data.service)+ if (service)+ work.push({+ icon: service.service === "goods" ? "trade" : service.service === "faith" ? "faith" : service.service === "repair" ? "repair" : service.service,+ label: "walkers out",+ value: `${maybe(row.data.walkers)?.length ?? 0}`})+ const inventory = maybe(row.data.inventory)if (inventory) {const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => ({ good: g, count: inventory.stock[g] }))- const hall = maybe(row.data.hall) !== undefined- lines.push(- held.length > 0- ? { icon: "jobs", label: "holds", goods: held, note: hall ? `up to ${inventory.cap} of each good; carriers take what sites and workshops ask for, and ${kinds.townhall.carriers} are out at once` : undefined }- : { icon: "jobs", label: "holds", value: "nothing yet", tone: "dim" }- )+ work.push(held.length > 0 ? { icon: "jobs", label: "holds", goods: held } : { icon: "jobs", label: "holds", value: "nothing yet", tone: "dim" })}if (kind.wear && inventory)- lines.push(+ work.push(inventory.stock.tools > 0- ? { icon: "tools", label: "tools", value: `${inventory.stock.tools} on hand`, note: `one wears out every ${kind.wear} jobs; a carrier brings another from storage` }- : { icon: "tools", label: "tools", value: "none", tone: "bad", note: "half pace until a carrier brings one: a smithy forges them, or buy them in the town panel" }+ ? { icon: "tools", label: "tools", value: `${inventory.stock.tools}`, tone: "ok" }+ : { icon: "tools", label: "tools", value: "none", tone: "bad", note: "half pace until one comes: a smithy makes them, or buy them in the town panel" })+ const running: Array<Line> = []+ if (kind.upkeep > 0) running.push({ icon: "upkeep", label: "upkeep", value: `${kind.upkeep} coins a minute` })const condition = maybe(row.data.condition)if (condition)- lines.push({+ running.push({icon: "condition",label: "condition",value: percent(condition.value, CONDITION_MAX),tone: condition.value < wear.worn ? "bad" : condition.value < wear.mend ? "warn" : "ok",- note:- condition.value < wear.worn- ? "run down: half pace, and more likely to burn · a builder's yard mends it with a plank and a stone"- : condition.value < wear.mend- ? "a builder's yard would mend it as its builder passes"- : "everything wears; a builder's yard keeps it mended"+ note: condition.value < wear.worn ? "half pace, and it may fall: a builder's yard mends it" : condition.value < wear.mend ? "a builder's yard mends it as its builder passes" : undefined})const r = maybe(row.data.risk)if (r)- lines.push({+ running.push({icon: "fire",label: "fire risk",value: riskText(r.fire),tone: r.fire >= risk.warn ? "bad" : r.fire >= RISK_MAX * 0.35 ? "warn" : "ok",- note: r.fire >= risk.warn ? "a fire watch's watchman resets it as he passes" : kind.hot ? "an oven or a forge: a risk to itself and to homes within 2 cells" : undefined- })- const service = maybe(row.data.service)- const walkers = maybe(row.data.walkers)?.length ?? 0- if (service)- lines.push({- icon: service.service === "goods" ? "trade" : service.service === "faith" ? "faith" : service.service === "repair" ? "repair" : service.service,- label: "walkers",- value: `${walkers} out · ${service.range} road cells from the door`,- note: `one sets out every ${Math.round(service.interval / 60)} s while it is staffed, and serves the homes beside its way`+ note: r.fire >= RISK_MAX * 0.35 ? "a fire watch's watchman lowers it as he passes" : undefined})- if (kind.appeal)- lines.push({- icon: "appeal",- label: "desirability around it",- value: `${signed(kind.appeal.value)} beside it, fading out to ${kind.appeal.reach} cells`,- tone: kind.appeal.value < 0 ? "warn" : "ok",- note: kind.appeal.value < 0 ? "homes this close hold fewer people and pay less; citizens need a street at 5 or more" : undefined- })- if (kind.upkeep > 0) lines.push({ icon: "upkeep", label: "upkeep", value: `${kind.upkeep} coins a minute` })+ if (kind.appeal) running.push({ icon: "appeal", label: "desirability nearby", value: signed(kind.appeal.value) })+ const help = [+ kind.upkeep > 0 ? "Upkeep is paid every minute it stands, a quarter of it while paused." : "",+ condition ? "Everything wears down; a builder's yard mends it." : "",+ kind.hot ? "An oven or a forge: a fire risk to itself and to homes within 2 cells." : "",+ kind.appeal ? `It changes how nice the streets are out to ${kind.appeal.reach} cells${kind.appeal.value < 0 ? ": homes close by hold fewer people and pay less" : ""}.` : ""+ ]+ .filter((t) => t !== "")+ .join(" ")+ const groups: Array<Group> = [+ ...(work.length > 0 ? [{ title: "at work", icon: "jobs", lines: work } as Group] : []),+ ...(running.length > 0 ? [{ title: "running it", icon: "coins", help, lines: running } as Group] : [])+ ]const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind)const problem = row.data.burning.present ? "on fire!" : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })- return { kind, status, problem, lines }+ return { kind, status, problem, groups }}/** What the town has of each provision, in storage and on market shelves. */const inTown = (): InTown => {@@ -802,20 +821,21 @@ export const Interact = Game.System(}return served}+ /**+ * A home, for its panel: its household (who lives there, what it pays, where they work); what it needs, as one+ * checklist with what it lacks now in red and what it lacks to grow in amber, each with its cause; and its risks+ * and wear. Each row is a value; a note only when something wants doing.+ */const describeHouse = (row: (typeof houses)[number]) => {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 quiet = (summary: string, line: Line) => ({ h, summary, trouble: false, groups: [{ title: "household", icon: "homes", lines: [line] }] as Array<Group> })+ if (site) return quiet("being built", { icon: "planks", label: "builders", value: "waiting for its plank", tone: "warn" })+ if (row.data.closed.present)+ return quiet("closed", { icon: "settlers", label: "closed", value: "empty", tone: "warn", note: "it pays no taxes and costs the town hall nothing: reopen it and settlers move back in" })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+ const nextTier = h.tier < 3 ? ((h.tier + 1) as Tier) : nullconst there = appealParts(appealSources(), tile)const desirability = appealAt(cells, tile.x, tile.y)const street: Street = { desirability, parts: there.parts }@@ -834,81 +854,101 @@ export const Interact = Game.System(: approval < 0? "fewer while the town disapproves of its mayor": desirability < 0- ? `fewer on a street at ${signed(desirability)}: ${streetAdvice(street)}`+ ? `fewer on a poor street: ${streetAdvice(street)}`: rate > 100 && capacity(h, approval, desirability) > cap- ? `fewer while ${tier.title} are taxed at ${rate}%: some move away`+ ? `fewer while taxed at ${rate}%: some move away`: "fewer until every need is met"- const taxLine = (() => {- const factors: Array<string> = []- if (rate !== 100) factors.push(`taxed at ${rate}%`)- const st = Math.round((streetTax(desirability) - 1) * 100)- if (st !== 0) factors.push(`street ${signed(st)}%`)- if (breadBonus(h) > 1) factors.push(`bread on the table +${Math.round(home.breadBonus * 100)}%`)- else if (h.tier === 1) factors.push(`+${Math.round(home.breadBonus * 100)}% with bread on the table`)- if (h.food <= 0) factors.unshift("hungry: no food, no taxes")- const could = Math.round(suppliedTaxOf(h, rates, undefined, desirability))- const pays = Math.round(taxOf(h, rates, undefined, desirability))- if (could > pays) factors.push(`${could} with every need met`)- return { icon: "coins", label: "pays", value: `${pays} coins a minute`, tone: h.food <= 0 ? "bad" : could > pays ? "warn" : "ok", note: factors.join(" · ") || undefined } as Line- })()- const worst = r ? (["fire", "health", "order"] as const).reduce((a, b) => (r[b] > r[a] ? b : a)) : null- const riskNote =- r && worst && r[worst] >= risk.warn- ? worst === "fire"- ? "fire is high: a fire watch's watchman resets it, and firefighters run to a blaze"- : worst === "health"- ? "sickness is near: a healer's physician resets it and cures the sick"- : "theft is near: a watch house's constable keeps order"- : r && worst && r[worst] >= RISK_MAX * 0.35- ? "rising slowly: a walker from the matching service resets it as it passes"- : undefined- const lines: Array<Line> = [- ...(row.data.burning.present- ? [{ icon: "fire", label: "on fire", value: "everyone has fled", tone: "bad" } as Line]- : row.data.sick.present- ? [{ icon: "health", label: "sick", value: "holds half as many", tone: "bad", note: "it passes in a minute, or when a physician calls; meanwhile it may spread to homes within 2 cells" } as Line]- : []),- { icon: "people", label: "residents", value: `${h.residents} of ${cap} (${tier.residents} at most)`, tone: whyFewer ? "warn" : "ok", note: whyFewer },- ...tier.needs.map((n): Line => {- const why = blockersOf({ ...h, tier: h.tier }, street, town, served, r).find((b) => b.what === n)- return { icon: needIcons[n], label: needTitle[n], value: met(h, n) ? "met" : "short", tone: met(h, n) ? "ok" : "bad", note: met(h, n) ? undefined : why?.text }- }),- ...(h.tier === 1- ? [{ icon: "bread", label: "bread", value: met(h, "bread") ? "on the table" : "none lately", tone: met(h, "bread") ? "ok" : "dim", note: met(h, "bread") ? "a cottage with bread pays half again" : "a cottage with bread pays half again: markets hand it out once a bakery bakes it" } as Line]- : []),+ const hungry = h.food <= 0+ const pays = Math.round(taxOf(h, rates, undefined, desirability))+ const could = Math.round(suppliedTaxOf(h, rates, undefined, desirability))+ const household: Array<Line> = [+ ...(row.data.burning.present ? [{ icon: "fire", label: "on fire", value: "everyone fled", tone: "bad" } as Line] : []),+ ...(row.data.sick.present ? [{ icon: "health", label: "sick", value: "half as many", tone: "bad", note: "it passes in a minute, or when a healer's physician calls" } as Line] : []),+ { icon: "people", label: "residents", value: `${h.residents} of ${cap}`, tone: whyFewer ? "warn" : "ok", note: whyFewer },{+ icon: "coins",+ label: "pays",+ value: `${pays} coins a minute`,+ tone: hungry ? "bad" : undefined,+ note: hungry ? "hungry: no food, no taxes" : could > pays ? `${could} coins a minute with every need met` : undefined+ },+ work ? { icon: "jobs", label: "works at", value: `${work.title.toLowerCase()}` } : { icon: "jobs", label: "works at", value: "nothing nearby", tone: "dim" }+ ]+ // What it needs: what it must have now, then what it must have to grow, in the order the town makes them.+ const needs: Array<Line> = []+ const nowNeeds = new Set<Need>(tier.needs)+ const growNeeds = new Set<Need>(nextTier ? home.tiers[nextTier].needs : [])+ for (const n of ["food", "bread", "cloth", "faith"] as const) {+ if (!nowNeeds.has(n) && !growNeeds.has(n)) continue+ if (met(h, n)) {+ needs.push({ icon: needIcons[n], label: needTitle[n], value: "✓", tone: "ok" })+ continue+ }+ const now = nowNeeds.has(n)+ needs.push({+ icon: needIcons[n],+ label: needTitle[n],+ value: now ? "missing" : `for ${home.tiers[nextTier!].title}`,+ tone: now ? "bad" : "warn",+ note: whyUnmet(n, h, street, town, served) ?? undefined+ })+ }+ const blocks = blockersOf(h, street, town, served, r)+ const streetBlock = blocks.find((b) => b.what === "street")+ if (nextTier)+ needs.push({icon: "appeal",label: "street",- value: `desirability ${signed(desirability)}`,- tone: desirability >= home.tiers[2].appeal ? "ok" : desirability < 0 ? "warn" : undefined,- note: there.parts.length > 0 ? there.parts.slice(0, 5).map((p) => `${p.label} ${signed(p.value)}`).join(", ") : "nothing nearby counts either way: a chapel, a market, a park, or paving would lift it"- },- ...(r- ? [{ icon: worst ?? "fire", label: "risks", value: `fire ${riskText(r.fire)} · health ${riskText(r.health)} · order ${riskText(r.order)}${r.thefts > 0 ? " · robbed" : ""}`, tone: worst && r[worst] >= risk.warn ? "bad" : worst && r[worst] >= RISK_MAX * 0.35 ? "warn" : "ok", note: riskNote } as Line]- : []),+ value: streetBlock ? `${signed(desirability)} of ${home.tiers[nextTier].appeal}` : "✓",+ tone: streetBlock ? "warn" : "ok",+ note: streetBlock ? `${streetShort(street, home.tiers[nextTier].appeal)}: ${streetAdvice(street)}` : undefined+ })+ else needs.push({ icon: "appeal", label: "street", value: signed(desirability), tone: "ok" })+ const services = blocks.find((b) => b.what === "services")+ if (services) needs.push({ icon: "order", label: "services", value: `for ${home.tiers[3].title}`, tone: "warn", note: services.text })+ if (nextTier && blocks.length === 0)+ needs.push({ icon: "citizens", label: `ready for ${home.tiers[nextTier].title}`, value: "✓", tone: "ok", note: "it grows as the next resident moves in" })+ const risky = r ? (["fire", "health", "order"] as const).filter((k) => r[k] >= RISK_MAX * 0.35) : []+ const cure = { fire: "a fire watch's watchman lowers it", health: "a healer's physician lowers it", order: "a watch house's constable lowers it" } as const+ const safety: Array<Line> = [+ ...(r && risky.length === 0 ? [{ icon: "fire", label: "risks", value: "all low", tone: "ok" } as Line] : []),+ ...risky.map(+ (k): Line => ({+ icon: k,+ label: `${k === "order" ? "theft" : k} risk`,+ value: riskText(r![k]),+ tone: r![k] >= risk.warn ? "bad" : "warn",+ note: cure[k]+ })+ ),+ ...(r && r.thefts > 0 ? [{ icon: "order", label: "robbed", value: `${r.thefts}×`, tone: "warn" } as Line] : []),...(condition? [{icon: "condition",label: "condition",value: percent(condition.value, CONDITION_MAX),tone: condition.value < wear.worn ? "bad" : condition.value < wear.mend ? "warn" : "ok",- note: condition.value < wear.worn ? "run down: it drags the street down and may fall · a builder's yard mends it with a plank" : condition.value < wear.mend ? "a builder's yard would mend it as its builder passes" : undefined+ note: condition.value < wear.worn ? "it drags the street down and may fall: a builder's yard mends it" : condition.value < wear.mend ? "a builder's yard mends it as its builder passes" : undefined} as Line]- : []),- work- ? { icon: "jobs", label: "work", value: `${work.title}, ${work.distance} road cells away` }- : { icon: "jobs", label: "work", value: `none within ${COMMUTE} road cells`, tone: "dim", note: "residents only work within that walk: a workplace nearer would have them" },- taxLine+ : [])]- const blockers: Array<Line> = next- ? blockersOf(h, street, town, served, r).map((b) => ({- icon: b.what === "street" ? "appeal" : b.what === "services" ? "order" : needIcons[b.what],- label: b.what === "street" ? "street" : b.what === "services" ? "services" : needTitle[b.what],- value: b.text,- tone: "bad"- }))- : []- return { h, lines, blockers }+ const needHelp =+ h.tier === 1+ ? `Red: it needs this now. Amber: it needs this to become a citizens' home, which holds and pays twice as much. Bread alone already makes a cottage pay half again. Walkers bring needs along the road; the street is how nice the place is (desirability ${home.tiers[2].appeal} for citizens).`+ : h.tier === 2+ ? `Red: it needs this now, or goes back to settlers. Amber: it needs this to become a townhouse of burghers, on a street of ${home.tiers[3].appeal} with a fire watch, a healer, and a watch house all calling.`+ : "Red: it needs this now, or goes back to citizens."+ const summary = row.data.burning.present ? "on fire" : row.data.sick.present ? "sick" : hungry ? "hungry" : `${h.residents} resident${h.residents === 1 ? "" : "s"}`+ return {+ h,+ summary,+ trouble: row.data.burning.present || row.data.sick.present || hungry,+ groups: [+ { title: "household", icon: "homes", lines: household },+ { title: "needs", icon: "citizens", help: needHelp, lines: needs },+ { title: "risks and wear", icon: "condition", help: "Every home's risk of fire, sickness, and theft rises slowly; a walker from the matching service lowers it as it passes.", lines: safety }+ ] as Array<Group>+ }}/** What pulling a building or home down would cost and give back, for the bulldozer and the panel. */@@ -933,7 +973,7 @@ export const Interact = Game.System(? `${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" : ""}`+ : `${tierHome[h.tier]} · ${h.residents} resident${h.residents === 1 ? "" : "s"} · 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)) {@@ -943,12 +983,14 @@ export const Interact = Game.System(preview.tooltip = `park · ${here.prop !== "none" ? props[here.prop].title.toLowerCase() : grounds[here.ground].title.toLowerCase()}${p ? ` · ${p.cells.length} cells · ${parkText(p)}` : ""}`} else if (ui.tool === "place" && ui.placing) {const kind = kinds[ui.placing]- const r = reachOf(kind)- const a = kind.appealconst lock = lockReason(kind, resources.census.get())+ const tile = pointer ? { ...footprintAt(pointer, kind.size), size: kind.size } : null+ const problem = tile ? placeProblem(kind, tile) : nullif (lock) preview.tooltip = `${kind.title.toLowerCase()} · ${lock}`- else preview.tooltip = `${kind.title.toLowerCase()}${r !== null ? ` · works ${r} cells around` : ""}${a ? ` · desirability ${signed(a.value)} out to ${a.reach} cells` : ""}${preview.rangeNote ? ` · ${preview.rangeNote}` : ""} · needs a road at the middle of a side`- } else if (ui.tool === "pave" && !dropping) preview.tooltip = `drag along a road to pave it · ${PAVE_COST.coins} coins and a stone a cell · carriers and walkers go half again as fast on it, and homes beside it like it a little`+ else if (tile && !canPlace(grid, tile)) preview.tooltip = `${kind.title.toLowerCase()} · no room here`+ else if (problem) preview.tooltip = `${kind.title.toLowerCase()} · ${problem.text}`+ else preview.tooltip = `${kind.title.toLowerCase()} · ${costText(kind.cost)}`+ } else if (ui.tool === "pave" && !dropping) preview.tooltip = `pave · ${PAVE_COST.coins} coins and a stone a cell · faster walking`else if (cell && ui.view === "appeal" && inside(cell.x, cell.y)) preview.tooltip = `desirability ${appealAt(cells, cell.x, cell.y)}`ui.preview = preview@@ -958,7 +1000,7 @@ export const Interact = Game.System(const pickedPark = ui.selected !== null ? parkRows.find((row) => row.entity.id === ui.selected) : undefinedconst picked = pickedPark ? parkOf(pickedPark.data.tile.get()) : undefinedif (pickedBuilding) {- const { kind, status, problem, lines } = describeBuilding(pickedBuilding)+ const { kind, status, problem, groups } = describeBuilding(pickedBuilding)const pausable = kind.id !== "townhall" && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.presentui.panel = {type: "building",@@ -967,15 +1009,15 @@ export const Interact = Game.System(kind: kind.id,status,problem,- lines,+ groups,pausable,paused: pickedBuilding.data.paused.present,salvage: salvageFor(kind.cost, maybe(pickedBuilding.data.site))}} else if (pickedHouse) {- const { h, lines, blockers } = describeHouse(pickedHouse)+ const { h, summary, trouble, groups } = describeHouse(pickedHouse)ui.panel = {- type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines, blockers,+ type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, summary, trouble, groups,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))@@ -999,7 +1041,7 @@ export const Interact = Game.System(cause: r.cause,lines: [{ icon: "condition", label: "what happened", value: r.cause === "burnt" ? "it burned down" : r.cause === "collapsed" ? "it fell down for want of mending" : "it was left derelict after its thefts", tone: "bad" },- { icon: "appeal", label: "the street", value: "desirability −3 around it until it is cleared", tone: "warn", note: "bulldoze it (X) to clear the plot" }+ { icon: "appeal", label: "desirability nearby", value: "−3", tone: "warn", note: "until it is cleared: bulldoze it" }]}} else ui.panel = ui.menu ? { type: ui.menu } : null@@ -1109,10 +1151,15 @@ export const Interact = Game.System(const alerts: Array<Notice> = []const census = resources.census.get()const stock = resources.stock.get()+ /** A building of this kind stands (built, not a site). */+ const stands = (k: KindId) => buildings.some(({ data }) => data.building.get().kind === k && !data.site.present && !data.rising.present)+ // Each line says what is wrong, then what to do about it.const burningRow = [...buildings, ...houses].find(({ data }) => data.burning.present)- if (census.burning > 0) alerts.push({ tone: "bad", text: `${census.burning} on fire`, at: burningRow?.data.tile.get() ?? null, size: burningRow?.data.tile.get().size ?? 1, id: burningRow?.entity.id ?? null })+ const fireText = `${census.burning} on fire: ${stands("firewatch") ? "the fire watch's firefighters are on their way" : "build a fire watch nearby, whose firefighters put fires out"}`+ if (census.burning > 0) alerts.push({ tone: "bad", text: fireText, at: burningRow?.data.tile.get() ?? null, size: burningRow?.data.tile.get().size ?? 1, id: burningRow?.entity.id ?? null })const sickRow = houses.find(({ data }) => data.sick.present)- if (census.sick > 0) alerts.push({ tone: "warn", text: `${census.sick} home${census.sick > 1 ? "s" : ""} sick`, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })+ const sickText = `${census.sick} home${census.sick > 1 ? "s" : ""} sick, holding half as many people: ${stands("healer") || stands("hospital") ? "a healer within reach of its road cures it" : "build a healer among the homes"}`+ if (census.sick > 0) alerts.push({ tone: "warn", text: sickText, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })const waiting = new Map<string, { n: number; at: TileLike; id: number; kind: KindId }>()const remote = new Map<string, { n: number; at: TileLike; id: number; kind: KindId }>()const shortStaffed: Array<{ id: number; title: string; cell: Point; size: number; assigned: number; needed: number; nobodyNear: boolean }> = []@@ -1128,7 +1175,7 @@ export const Interact = Game.System(const since = starvedSince.get(entity.id) ?? tickif (!starvedSince.has(entity.id)) starvedSince.set(entity.id, tick)if (tick - since >= ALERT_PATIENCE) {- const label = `${kind.title.toLowerCase()} (${kind.recipe.input})`+ const label = `${kind.title.toLowerCase()} needs ${kind.recipe.input}`const was = waiting.get(label)waiting.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id, kind: kind.id })}@@ -1145,15 +1192,15 @@ export const Interact = Game.System(const first = (m: Map<string, { at: TileLike; id: number }>) => [...m.values()][0]const placesOf = (m: Map<string, { at: TileLike; id: number; kind: KindId }>) =>Object.fromEntries([...m.values()].map((v) => [v.kind, { at: v.at, size: v.at.size, id: v.id }]))- if (waiting.size > 0) alerts.push({ tone: "warn", text: `waiting for inputs: ${list(waiting)}`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null, places: placesOf(waiting) })- 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, places: placesOf(remote) })+ if (waiting.size > 0) alerts.push({ tone: "warn", text: `idle: the ${list(waiting)}. Build more of what makes it, or buy it in the [town] panel`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null, places: placesOf(waiting) })+ if (remote.size > 0) alerts.push({ tone: "warn", text: `no workers for the ${list(remote)}: lay [homes] within ${COMMUTE} road cells of it, or a road to homes nearby`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null, places: placesOf(remote) })const hallRow = buildings.find(({ data }) => data.hall.present)const empty = census.homes > 0 && larder(stock) === 0if (!empty || (emptySince !== null && emptySince > tick)) emptySince = nullif (empty && emptySince === null) emptySince = tickif (empty && tick - emptySince! >= HUNGER_PATIENCE) hungryUntil = tick + HUNGER_PATIENCEif (hungryUntil > tick + HUNGER_PATIENCE) hungryUntil = 0- if (census.homes > 0 && tick < hungryUntil) 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 })+ if (census.homes > 0 && tick < hungryUntil) alerts.push({ tone: "bad", text: "no food in store, so homes go hungry and pay no taxes: build another fishery, or buy fish in the [town] panel", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })const ledger = resources.ledger.get()const charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)@@ -1205,6 +1252,29 @@ export const Interact = Game.System(const tile = row.data.tile.get()return met(h, "bread") && met(h, "cloth") && met(h, "faith") && appealAt(cells, tile.x, tile.y) < home.tiers[2].appeal})+ const guide = resources.guide.get()+ const put = new Set(guide.done)+ /** A road within two cells of water: reckoned only until the guide's road step is put away. */+ const roadNearWater = () => {+ for (let y = 0; y < GRID; y++) {+ for (let x = 0; x < GRID; x++) {+ if (useAt(grid, x, y) !== "road") continue+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, x + dx, y + dy) === "water") return true+ }+ }+ return false+ }+ /** Built homes no food walker reaches: reckoned only until a market stands, as it is a walk from each walker's door. */+ const unreachedHomes = () => {+ const walks = buildings+ .filter((row) => maybe(row.data.service)?.service === "goods" && finished(row))+ .map((row) => ({ way: reach(grid, doors(grid, row.data.tile.get())), range: maybe(row.data.service)!.range }))+ return houses.filter((row) => {+ if (!finished(row)) return false+ const ds = doors(grid, row.data.tile.get())+ return ds.length > 0 && !walks.some((w) => (nearest(w.way, ds)?.distance ?? Infinity) < w.range)+ }).length+ }const facts: GuideFacts = {homes: houses.length,builtHomes: houses.filter(finished).length,@@ -1229,6 +1299,11 @@ export const Interact = Game.System(most: Math.max(...goodIds.map((g) => stock[g])),sawTown: ui.menu === "town",sawHome: houses.some((row) => row.entity.id === ui.selected),+ sawBuilding: buildings.some((row) => row.entity.id === ui.selected && !row.data.hall.present),+ roadToWater: put.has("road") || roadNearWater(),+ coins,+ unreached: put.has("market") || standingKinds.has("market") ? 0 : unreachedHomes(),+ goalsMet: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net: steadyNet(resources.history.get().samples, net), approval: mood.approval }).every((g) => g.met),risk: {fire: houses.some((row) => (maybe(row.data.risk)?.fire ?? 0) >= RISK_MAX * 0.35),health: houses.some((row) => (maybe(row.data.risk)?.health ?? 0) >= RISK_MAX * 0.35),@@ -1241,8 +1316,6 @@ export const Interact = Game.System(return queries.trees.each().map(({ data }) => data.tile.get()).filter((t) => t.x >= tile.x - reach && t.x < tile.x + tile.size + reach && t.y >= tile.y - reach && t.y < tile.y + tile.size + reach).length < 6})}- const guide = resources.guide.get()- const put = new Set(guide.done)const playing = f.state === "playing" && !ui.foundingconst newly = playing ? guideDone(facts, put) : []if (newly.length > 0) {@@ -1359,7 +1432,25 @@ export const Interact = Game.System(chronicle: resources.chronicle.get().lines,alerts,guide: {- step: step && shown ? { key: step.id, chapter: step.chapter, goal: step.goal, text: step.text, at: shown.at, size: shown.at?.size ?? 1, id: shown.id } : null,+ step:+ step && shown+ ? {+ key: step.id,+ chapter: step.chapter,+ goal: step.goal,+ text: step.action,+ why: step.why,+ waiting: step.waiting?.(facts) ?? null,+ locked: lockedNote(step, facts),+ next: upcoming(facts, put),+ asks: step.asks ?? [],+ near: step.focus !== null && typeof step.focus === "object" && shown.id !== null ? step.focus.kind : null,+ count: courseCount(step),+ 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.offdiff --git a/src/rules/guide.ts b/src/rules/guide.tsindex be54fe6..0347d30 100644--- a/src/rules/guide.ts+++ b/src/rules/guide.ts@@ -1,27 +1,49 @@/*** 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+ * time, written for someone who has never played a town-builder. Each step+ * is one thing to do (`action`) and one reason for it (`why`), and names the+ * buildings it asks for (`asks`) 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.*- * The first steps (`opening`) come one after another, each once the last- * is built: homes, then food, then planks, then stone, so a new mayor learns- * the store and its chains; then where to look as the town grows (a home's- * panel, the town panel). After them, steps come when the town needs them,- * not back to back: each waits for a- * sign (planks running low, the woods thinning, a fire risk rising), and- * after one is done the guide keeps quiet for `GUIDE_QUIET` seconds. An- * urgent step (the crown's request, winter, a fire, the sick, a building- * falling apart) does not wait for the quiet. A step once shown stays until- * it is done or put away, so the ticker does not hop between steps. A step- * that asks for a building is done when the building stands, not when it is- * laid.+ * Most steps are a course (`course`), taught in order, chapter by chapter,+ * and counted ("step 3 of 8"). Founding: homes, a road to the water, a+ * fishery, a look at what it needs, a lumberjack, a sawmill, the term's goal,+ * and ten homes. Growing citizens: a quarry, cloth, faith, bread, the first+ * citizens, the goals again. Governing: every goal met. The course always has+ * something to say, so the guide never falls silent on a mayor who does not+ * know what comes next; a step whose buildings the town cannot build yet+ * says what opens them (`lockedNote`), and the course goes on to one it can.+ *+ * The course never asks for a building before the town needs it: a+ * building's upkeep starts the day it stands. A step with a `need` waits for+ * it (planks running low, stone running low), the course goes on past it,+ * and the card says what comes next and when (`upcoming`: "next: a+ * lumberjack and a sawmill, once planks fall below 25 (31 now)").+ *+ * Around the course, steps come when the town needs them: each waits for a+ * sign (stone running low, the woods thinning, a fire risk rising), goes+ * ahead of the course once Founding is done, and after one is done the guide+ * keeps quiet about such signs for `GUIDE_QUIET` seconds. An urgent step (the+ * crown's request, winter, a fire, the sick, a building falling apart) does+ * not wait for the quiet. A sign once shown stays until it is done or put+ * away, so the ticker does not hop between steps.+ *+ * A step that asks for a building is done when the building stands, not when+ * it is laid; in between, `waiting` says what is happening (carriers bringing+ * planks to the site), so the mayor knows they did the right thing.+ *+ * The texts are written once for mouse and touch. In them:+ * - a building's name (in `asks`) becomes a chip that starts placing one;+ * - `[homes]`, `[road]`, `[select]`, `[build]`, `[town]`, `[speed]`,+ * `[pause]`, and `[view:fire]` (any map view) become chips that pick that+ * tool, open that panel, or show that view; on a keyboard they carry the key;+ * - `{tap|click}` reads "tap" on a touch screen and "click" with a mouse.*/-import type { Amounts, KindId } from "../content.ts"+import { kinds, type Amounts, type KindId } from "../content.ts"/** What the guide reads of the town. */export interface GuideFacts {@@ -56,9 +78,18 @@ export interface GuideFacts {readonly taxed: boolean/** The most of any one good in store. */readonly most: number- /** The page: the town panel has been open; a home has been selected. */+ /** The page: the town panel is open; a home is selected; a building (not the town hall) is selected. */readonly sawTown: booleanreadonly sawHome: boolean+ readonly sawBuilding: boolean+ /** A road comes within two cells of water, close enough for a fishery on it. */+ readonly roadToWater: boolean+ /** Every goal of the term is met now. */+ readonly goalsMet: boolean+ /** Coins in the treasury. */+ readonly coins: number+ /** Built homes no food walker reaches (the town hall's or a market's). */+ readonly unreached: number/** A home whose risk of fire, sickness, or theft is rising. */readonly risk: { readonly fire: boolean; readonly health: boolean; readonly order: boolean }/** A lumberjack with few trees left in reach. */@@ -77,277 +108,464 @@ export type Chapter = (typeof chapters)[number]export interface GuideStep {readonly id: stringreadonly chapter: Chapter- /** What to do and why. Building names become chips to place one; a key in brackets, a key. */- readonly text: string+ /** What to do, in one sentence. */+ readonly action: string+ /** Why, in a sentence or two. */+ readonly why: string/** When the step is done, in a few words: shown under it, so the mayor knows what closes it. */readonly goal: string+ /** The buildings the step asks for: their names in the text become chips to place one. */+ readonly asks?: ReadonlyArray<KindId>readonly focus: GuideFocus | nullreadonly when: (f: GuideFacts) => boolean- /** One of the first steps, which come one after another, without the quiet. */- readonly opening?: boolean+ /** Part of the course, taught in this order chapter by chapter, without the quiet. */+ readonly course?: boolean+ /** A course step that waits until the town needs it (the course goes on past it meanwhile); and, while it waits, what for. */+ readonly need?: (f: GuideFacts) => boolean+ readonly soon?: (f: GuideFacts) => string/** It cannot wait for the guide's quiet (and goes ahead of the step shown). */readonly urgent?: (f: GuideFacts) => booleanreadonly done: (f: GuideFacts) => boolean+ /** Once the mayor has done their part and the town is at work on it: what is happening (`null`: not yet). */+ readonly waiting?: (f: GuideFacts) => string | null}/** Every one of these buildings stands (built, not only laid). */const has = (f: GuideFacts, ...kinds: ReadonlyArray<KindId>) => kinds.every((k) => f.standing.has(k))+/** Planks and stone low enough that a lumberjack and a sawmill, or a quarry, are worth their upkeep. */+export const PLANKS_LOW = 25+export const STONE_LOW = 8++/** What a site needs while it waits: planks, mostly, carried from the store. */+const siteNote = (f: GuideFacts) =>+ f.stock.planks === 0+ ? "The store has no planks left, so the site waits: sell something in the [town] panel, or buy planks there."+ : "It is a building site for now: carriers bring its planks and stone from the store, then builders put it up. [speed] makes time run faster."++/** The step's buildings are laid but not all standing yet. */+const rising = (...kinds: ReadonlyArray<KindId>) => (f: GuideFacts) =>+ kinds.some((k) => f.placed.has(k) && !f.standing.has(k)) ? siteNote(f) : null+export const guideSteps: ReadonlyArray<GuideStep> = [+ // ── The opening, in order ──{id: "homes",- goal: "a home stands",chapter: "Founding",- text: "Drag a row of homes along the road from the town hall (H), or lay more road first (R). Builders carry planks from the store to each one; once it stands, settlers move in on their own, and every home pays taxes.",+ course: true,+ action: "Pick [homes] and drag along the grey road around the town hall{, then tap Build|}.",+ why: "Settlers move into homes that touch a road, and every home pays taxes: the town's income.",+ goal: "a home stands",focus: "hall",- opening: true,when: () => true,- done: (f) => f.builtHomes > 0+ done: (f) => f.builtHomes > 0,+ waiting: (f) =>+ f.homes > 0+ ? f.stock.planks === 0+ ? "The homes wait for planks, and the store has none."+ : "Builders are carrying planks from the store to the new homes, and settlers move in once one stands. [speed] makes time run faster."+ : null+ },+ {+ id: "road",+ chapter: "Founding",+ course: true,+ action: "Pick [road] and drag a road from the town hall's road towards the water.",+ why: "Every building needs a road touching the middle of one of its sides, or nobody can reach it. The fishery comes next, and it needs water nearby.",+ goal: "a road comes within two cells of water",+ focus: "water",+ when: () => true,+ done: (f) => f.roadToWater || has(f, "fishery") || has(f, "bakery")},{id: "fishery",- goal: "a fishery stands",chapter: "Founding",- text: "The bar at the top is the town's store. Settlers eat fish from it, and the fish there 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.",+ course: true,+ action: "{Tap|Click} fishery, then place it on that road, with water no more than two cells away.",+ why: "Settlers eat fish. The town starts with a little, and fish rots in store.",+ goal: "a fishery stands",+ asks: ["fishery"],focus: "water",- opening: true,- when: (f) => f.builtHomes > 0,- done: (f) => has(f, "fishery") || has(f, "bakery")+ when: () => true,+ done: (f) => has(f, "fishery") || has(f, "bakery"),+ waiting: rising("fishery")},{- id: "crown",- goal: "the goods are sent, with the button on the request",- 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,- urgent: () => true,- done: (f) => f.crown.met > 0+ id: "look",+ chapter: "Founding",+ course: true,+ action: "Pick [select] and {tap|click} the fishery to open its panel.",+ why: "A building needs workers from homes within 15 road cells; its panel says how many it has, and what holds it back. The jobs counter at the top adds them all up.",+ goal: "you open a building's panel",+ focus: { kind: "fishery" },+ when: (f) => f.standing.has("fishery"),+ done: (f) => f.sawBuilding},{- id: "winter",- goal: "a granary or a smokehouse stands",- 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)),- urgent: () => true,- done: (f) => has(f, "granary") || has(f, "smokehouse")+ id: "lumberjack",+ chapter: "Founding",+ course: true,+ action: "Build a lumberjack on a road beside the trees.",+ why: "Planks are running low, and every home and building costs some. Wood is where planks start.",+ goal: "a lumberjack stands",+ asks: ["lumberjack"],+ focus: "trees",+ when: () => true,+ need: (f) => f.stock.planks < PLANKS_LOW || f.placed.has("lumberjack"),+ soon: (f) => `a lumberjack and a sawmill, once planks fall below ${PLANKS_LOW} (${f.stock.planks} now)`,+ done: (f) => has(f, "lumberjack"),+ waiting: rising("lumberjack")},{- id: "tools",- goal: "the town buys tools (town panel, trade), or a smithy stands",- chapter: "Growing citizens",- text: "Tools are running low, and only a smithy makes new ones, which opens at 10 citizens. Until then, buy tools from traders in the town panel (T), and keep them for workshops.",- focus: null,- when: (f) => f.residents >= 15 && f.stock.tools <= 3 && !has(f, "smithy"),- done: (f) => f.buysTools || has(f, "smithy")+ id: "sawmill",+ chapter: "Founding",+ course: true,+ action: "Build a sawmill on a road near the lumberjack.",+ why: "Goods come in chains: the lumberjack fells wood, and the sawmill saws it into planks. Carriers walk the goods between them along the roads.",+ goal: "a sawmill stands",+ asks: ["sawmill"],+ focus: { kind: "lumberjack" },+ when: () => true,+ need: (f) => f.stock.planks < PLANKS_LOW || f.placed.has("lumberjack") || f.placed.has("sawmill"),+ soon: (f) => `a sawmill, once planks fall below ${PLANKS_LOW} (${f.stock.planks} now)`,+ done: (f) => has(f, "sawmill"),+ waiting: rising("sawmill")},{- id: "planks",- goal: "a lumberjack and a sawmill stand",+ id: "term",chapter: "Founding",- text: "Every home and building costs planks from the store, and they run out. Goods come in chains: a lumberjack by the woods fells wood, and a sawmill saws the wood into planks.",- focus: "trees",- opening: true,- when: (f) => f.stock.planks < 25 || f.standing.has("fishery"),- done: (f) => has(f, "lumberjack", "sawmill")+ course: true,+ action: "Open the [town] panel and read the goals at its top.",+ why: "Meet every goal before the clock at the top runs out and the town is complete. [pause] stops the clock whenever you need to think.",+ goal: "you open the town panel",+ focus: null,+ when: () => true,+ done: (f) => f.sawTown},{- id: "forester",- goal: "a forester stands",+ id: "grow",chapter: "Founding",- text: "The lumberjack is running out of trees. A forester beside it plants new ones for it to fell.",- focus: { kind: "lumberjack" },- when: (f) => f.fewTrees,- done: (f) => has(f, "forester")+ course: true,+ action: "Lay more roads and homes until ten homes stand.",+ why: "More people pay more taxes, and unlock new buildings in [build]. The guide asks for a building only once the town needs it.",+ goal: "10 homes stand",+ focus: "hall",+ when: () => true,+ done: (f) => f.builtHomes >= 10,+ waiting: (f) => (f.homes >= 10 && f.builtHomes < 10 ? "Ten homes are laid: builders are putting them up." : null)},++ // ── The course goes on: citizens ──{id: "quarry",+ chapter: "Growing citizens",+ course: true,+ action: "Build a quarry on a road beside the pale rocks.",+ why: "Stone is running low, and the workshops citizens need cost some. The dark rocks are ore, for later.",goal: "a quarry stands",- chapter: "Founding",- text: "Storage, workshops, and paving take stone, and the town starts with little. A quarry cuts it from the pale rocks nearby (the dark ones are ore, for later).",+ asks: ["quarry"],focus: "stone",- opening: true,- when: (f) => f.stock.stone < 10 || has(f, "lumberjack", "sawmill"),- done: (f) => has(f, "quarry")+ when: () => true,+ need: (f) => f.stock.stone < STONE_LOW || f.placed.has("quarry"),+ soon: (f) => `a quarry, once stone falls below ${STONE_LOW} (${f.stock.stone} now)`,+ done: (f) => has(f, "quarry"),+ waiting: rising("quarry")},{- id: "look",- goal: "you click a home",- chapter: "Founding",- text: "The town is on its feet. Click a home to see who lives there, what it needs, and what it pays; click any building to see what it makes and what holds it back.",+ id: "cloth",+ chapter: "Growing citizens",+ course: true,+ action: "Build a sheep farm and a weaver, on roads near each other.",+ why: "A home becomes a citizens' home with bread, cloth, and faith. The sheep farm shears wool, and the weaver weaves it into cloth.",+ goal: "a sheep farm and a weaver stand",+ asks: ["sheep", "weaver"],focus: "hall",- opening: true,- when: (f) => has(f, "quarry") && f.builtHomes > 0,- done: (f) => f.sawHome+ when: () => true,+ done: (f) => has(f, "sheep", "weaver"),+ waiting: rising("sheep", "weaver")},{- id: "watch",- goal: "you open the town panel (T)",- chapter: "Founding",- text: "As the town grows, keep an eye on the store at the top (goods running low), approval and jobs at the top right, and this ticker, which says what needs looking at. The town panel (T) holds the term's goals, trade, and taxes.",+ id: "chapel",+ chapter: "Growing citizens",+ course: true,+ action: "Build a chapel on a road among the homes.",+ why: "Faith is the second need. The chapel's walker brings it to the homes it passes, and the chapel makes its street nicer to live on.",+ goal: "a chapel stands",+ asks: ["chapel"],+ focus: "hall",+ when: () => true,+ done: (f) => has(f, "chapel"),+ waiting: rising("chapel")+ },+ {+ id: "wheat",+ chapter: "Growing citizens",+ course: true,+ action: "Build a farm and a mill.",+ why: "Bread is the third need, and the longest chain: the farm grows wheat, and the mill grinds it into flour.",+ goal: "a farm and a mill stand",+ asks: ["farm", "mill"],+ focus: "hall",+ when: () => true,+ done: (f) => has(f, "farm", "mill"),+ waiting: rising("farm", "mill")+ },+ {+ id: "bakery",+ chapter: "Growing citizens",+ course: true,+ action: "Build a bakery near the mill.",+ why: "It bakes the mill's flour into bread. Even a settlers' cottage with bread on the table pays half again.",+ goal: "a bakery stands",+ asks: ["bakery"],+ focus: { kind: "mill" },+ when: (f) => has(f, "farm", "mill"),+ done: (f) => has(f, "bakery"),+ waiting: rising("bakery")+ },+ {+ id: "citizens",+ chapter: "Growing citizens",+ course: true,+ action: "Pick [select] and {tap|click} a home to see what it still lacks to hold citizens.",+ why: "A home becomes a citizens' home with bread, cloth, and faith, on a street of desirability 5 or more. Its panel lists what is missing.",+ goal: "the first home holds citizens",+ focus: "hall",+ when: () => true,+ done: (f) => f.finerHomes > 0+ },+ {+ id: "goals",+ chapter: "Growing citizens",+ course: true,+ action: "Open the [town] panel to see how close the goals are.",+ why: "The first citizens have moved in, and three in ten residents must be citizens to complete the town.",+ goal: "you open the town panel",focus: null,- opening: true,- when: (f) => has(f, "quarry") && f.builtHomes > 0,+ when: (f) => f.finerHomes > 0,done: (f) => f.sawTown},{- id: "grow",- goal: "10 homes stand",- chapter: "Founding",- text: "Now grow. Lay new streets and homes: more residents pay more taxes and open new buildings in the build menu (B). The guide speaks up again when the town needs something.",+ id: "complete",+ chapter: "Governing",+ course: true,+ action: "Grow the town until every goal in the [town] panel is met.",+ why: "More citizens' homes, approval of 15 or more, and coins to spare. Hold every goal for two minutes and the town is complete. The guide speaks up when something needs you.",+ goal: "every goal is met",+ focus: null,+ when: () => true,+ done: (f) => f.goalsMet+ },++ // ── Around the course, when the town needs them ──+ {+ id: "crown",+ chapter: "Governing",+ action: "Send the crown what it asks for, with the send button on its request at the top.",+ why: "It pays coins. An unanswered request is a fine, and three missed in a row end your term.",+ goal: "the goods are sent",+ focus: null,+ when: (f) => f.crown.open,+ urgent: () => true,+ done: (f) => f.crown.met > 0+ },+ {+ id: "winter",+ chapter: "Keeping it standing",+ action: "Build a granary or a smokehouse before winter comes.",+ why: "In winter fishing slows, homes eat more, and fish rots in store. A granary keeps it five times as long, and smoked fish keeps all winter.",+ goal: "a granary or a smokehouse stands",+ asks: ["granary", "smokehouse"],focus: "hall",- opening: true,- when: (f) => has(f, "quarry") && f.sawHome && f.sawTown,- done: (f) => f.builtHomes >= 10+ when: (f) => f.residents >= 20 && (f.winter || (f.winterIn !== null && f.winterIn <= 120)),+ urgent: () => true,+ done: (f) => has(f, "granary") || has(f, "smokehouse"),+ waiting: rising("granary", "smokehouse")+ },+ {+ id: "tools",+ chapter: "Growing citizens",+ action: "In the [town] panel, under goods and trade, set tools to buy.",+ why: "Workshops use up tools, and only a smithy makes new ones, which opens at 10 citizens.",+ goal: "the town buys tools, or a smithy stands",+ focus: null,+ when: (f) => f.residents >= 15 && f.citizens < 10 && f.stock.tools <= 3 && !has(f, "smithy"),+ done: (f) => f.buysTools || has(f, "smithy")+ },+ {+ id: "forester",+ chapter: "Founding",+ action: "Build a forester next to the lumberjack.",+ why: "The lumberjack is running out of trees, and a forester plants new ones for it.",+ goal: "a forester stands",+ asks: ["forester"],+ focus: { kind: "lumberjack" },+ when: (f) => f.fewTrees,+ done: (f) => has(f, "forester"),+ waiting: rising("forester")},{id: "firewatch",- goal: "a fire watch stands",chapter: "Keeping it standing",- text: "The risk of fire is rising: 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.",+ action: "Build a fire watch on a road among the homes.",+ why: "Wooden cottages catch fire, and a fire spreads to the neighbours. Its watchman keeps the risk down, and its firefighters put fires out. [view:fire] shows the risk.",+ goal: "a fire watch stands",+ asks: ["firewatch"],focus: "hall",when: (f) => f.risk.fire || f.burning > 0,urgent: (f) => f.burning > 0,- done: (f) => has(f, "firewatch")+ done: (f) => has(f, "firewatch"),+ waiting: rising("firewatch")},{id: "builder",- goal: "a builder's yard stands",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.",+ action: "Build a builder's yard near the worn buildings.",+ why: "A run-down building works at half pace and can fall down. Its builder mends what it passes, with planks and stone. [view:condition] shows their state.",+ goal: "a builder's yard stands",+ asks: ["builder"],focus: "worn",when: (f) => f.worn,urgent: () => true,- done: (f) => has(f, "builder")+ done: (f) => has(f, "builder"),+ waiting: rising("builder")},{id: "market",- goal: "a market stands",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.",+ action: "Build a market among the homes furthest from the town hall.",+ why: "Some homes are beyond the town hall's walker, which only reaches 20 road cells, and get no food. A market's walker carries it further.",+ goal: "a market stands",+ asks: ["market"],focus: "hall",- when: (f) => f.residents >= 40 && f.standing.has("fishery"),- done: (f) => has(f, "market")+ when: (f) => f.unreached >= 2,+ done: (f) => has(f, "market"),+ waiting: rising("market")},{id: "street",- goal: "a home on a fine street holds citizens",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.",+ action: "Raise this home's street to desirability 5: add a chapel, a market, or a park nearby, and keep workshops away.",+ why: "It has bread, cloth, and faith, but citizens only live on a decent street. [view:appeal] shows desirability.",+ goal: "a home on a fine street holds citizens",+ asks: ["chapel", "market"],focus: "poorStreet",when: (f) => f.poorStreet,done: (f) => f.finerHomes > 0},- {- id: "wheat",- goal: "a farm and a mill stand",- chapter: "Growing citizens",- text: "Settlers become citizens, who pay twice as much, once they have bread, cloth, and faith, all three; until then they want only food. Start with bread, the longest chain: a farm grows wheat, and a mill grinds it into flour.",- focus: "hall",- when: (f) => f.residents >= 30,- done: (f) => has(f, "farm", "mill")- },- {- id: "bakery",- goal: "a bakery stands",- chapter: "Growing citizens",- text: "A bakery bakes the mill's flour into bread. Citizens need it, and a settlers' cottage with bread on the table pays half again.",- focus: { kind: "mill" },- when: (f) => has(f, "farm", "mill"),- done: (f) => has(f, "bakery")- },- {- id: "cloth",- goal: "a sheep farm and a weaver stand",- chapter: "Growing citizens",- text: "Next, cloth: a sheep farm shears wool, and a weaver weaves it into cloth.",- focus: "hall",- when: (f) => has(f, "bakery") || f.residents >= 60,- done: (f) => has(f, "sheep", "weaver")- },- {- id: "chapel",- goal: "a chapel stands",- chapter: "Growing citizens",- text: "The last need is faith: a chapel's walker brings it to the homes it passes, and the chapel makes its street more desirable.",- focus: "hall",- when: (f) => has(f, "sheep", "weaver"),- done: (f) => has(f, "chapel")- },- {- id: "goals",- goal: "you open the town panel (T)",- 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",- goal: "a healer stands",chapter: "Keeping it standing",- text: "Sickness is spreading: 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.",+ action: "Build a healer on a road among the homes.",+ why: "Sickness is spreading, and a sick home holds half as many people. The healer's physician calls on homes and cures them. [view:health] shows the risk.",+ goal: "a healer stands",+ asks: ["healer"],focus: "hall",when: (f) => f.residents >= 30 && (f.sick > 0 || f.risk.health),urgent: (f) => f.sick > 0,- done: (f) => has(f, "healer") || has(f, "hospital")+ done: (f) => has(f, "healer") || has(f, "hospital"),+ waiting: rising("healer")},{id: "watchhouse",- goal: "a watch house stands",chapter: "Keeping it standing",- text: "Thieves are about: poor streets, half-empty homes, and low approval breed them. A watch house sends a constable along the streets to keep order. Press O to see the risk.",+ action: "Build a watch house on a road among the homes.",+ why: "Poor streets, half-empty homes, and low approval breed thieves. Its constable walks the streets and keeps order. [view:order] shows the risk.",+ goal: "a watch house stands",+ asks: ["watchhouse"],focus: "hall",when: (f) => f.residents >= 40 && f.risk.order,- done: (f) => has(f, "watchhouse")+ done: (f) => has(f, "watchhouse"),+ waiting: rising("watchhouse")},{id: "trade",- goal: "the town sells or buys something (town panel, 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.",+ action: "In the [town] panel, under goods and trade, sell a good that piles up, or buy one that runs short.",+ why: "The town trades nothing until you tell it to, and spare goods are coins waiting to be made.",+ goal: "the town sells or buys something",focus: null,when: (f) => f.residents >= 20 && (f.net < 0 || f.most >= 80),done: (f) => f.trading},{id: "taxes",- goal: "a tax rate is changed (town panel)",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.",+ action: "Raise taxes a little in the [town] panel.",+ why: "The town is content but losing coins, and approval can carry higher taxes. Above 125% leaves a grudge that lasts.",+ goal: "a tax rate is changed",focus: null,when: (f) => f.approval >= 30 && f.net < 0,done: (f) => f.taxed},{id: "smithy",- goal: "a mine and a smithy stand",chapter: "Governing",- text: "Ore is for one thing: tools. Now open: a mine by the dark, rust-veined rocks digs ore, and a smithy forges it into tools, which every workshop and lamp needs and which wear out.",+ action: "Build a mine beside the dark, rust-veined rocks, and a smithy.",+ why: "Tools are running low, and every workshop uses them up. The mine digs ore, and the smithy forges it into tools.",+ goal: "a mine and a smithy stand",+ asks: ["mine", "smithy"],focus: "ore",- when: (f) => f.citizens >= 10,- done: (f) => has(f, "mine", "smithy")+ when: (f) => f.citizens >= 10 && f.stock.tools <= 5,+ done: (f) => has(f, "mine", "smithy"),+ waiting: rising("mine", "smithy")}]+/** The course, in order. */+export const courseSteps: ReadonlyArray<GuideStep> = guideSteps.filter((s) => s.course)++/** Where a course step stands in its chapter ("step 3 of 8"), or `null` for a step not in the course or alone in its chapter. */+export const courseCount = (step: GuideStep): { readonly at: number; readonly of: number } | null => {+ if (!step.course) return null+ const chapter = courseSteps.filter((s) => s.chapter === step.chapter)+ return chapter.length > 1 ? { at: chapter.indexOf(step) + 1, of: chapter.length } : null+}++/** When the town cannot build what a step asks for yet: what opens it, and what to do meanwhile (`null`: it can). */+export const lockedNote = (step: GuideStep, f: GuideFacts): string | null => {+ for (const id of step.asks ?? []) {+ const kind = kinds[id]+ if (kind.unlock.residents > f.residents)+ return `The ${kind.title.toLowerCase()} opens at ${kind.unlock.residents} residents (${f.residents} now): lay more [homes] and keep them fed.`+ if (kind.unlock.citizens > f.citizens) return `The ${kind.title.toLowerCase()} opens at ${kind.unlock.citizens} citizens (${f.citizens} now).`+ }+ // Not yet laid, and the treasury cannot pay for the cheapest of them.+ const unpaid = (step.asks ?? []).filter((id) => !f.placed.has(id)).map((id) => kinds[id])+ const cheapest = unpaid.sort((a, b) => a.cost.coins - b.cost.coins)[0]+ if (cheapest && f.coins < cheapest.cost.coins)+ return `Save up: the ${cheapest.title.toLowerCase()} costs ${cheapest.cost.coins} coins (${f.coins} now). Homes pay taxes every minute.`+ return null+}++/** The next course step that waits for the town to need it: what it is, and when it comes (`null`: none waiting). */+export const upcoming = (f: GuideFacts, done: ReadonlySet<string>): string | null => {+ const step = courseSteps.find((s) => !done.has(s.id) && !s.done(f) && s.when(f) && s.need && !s.need(f) && s.soon)+ return step ? `Next: ${step.soon!(f)}.` : null+}+/** 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: an urgent one first; else the step already- * shown (`shown`), until it is done or put away; else, unless the guide is- * keeping `quiet`, the first that applies.+ * The step to show now, if any: an urgent one first; then the course while+ * the town is being founded; then a sign already shown (`shown`), until it is+ * done or put away; then, unless the guide is keeping `quiet`, a new sign;+ * and otherwise the course: its next step, or when the town cannot build+ * that yet, a later building it can (else the step, saying what opens it).*/export const guideStep = (f: GuideFacts, done: ReadonlySet<string>, pace: { readonly shown?: string | null; readonly quiet?: boolean } = {}): GuideStep | null => {const open = (s: GuideStep) => !done.has(s.id) && !s.done(f)const urgent = guideSteps.find((s) => open(s) && s.when(f) && s.urgent?.(f))if (urgent) return urgent- const shown = guideSteps.find((s) => s.id === pace.shown && open(s) && (!s.urgent || s.when(f)))+ const course = courseSteps.filter((s) => open(s) && s.when(f) && (s.need?.(f) ?? true))+ // A step the town cannot build yet gives way to a later building it can; else it shows, saying what opens it.+ const first = course[0] ?? null+ const next = first && lockedNote(first, f) !== null ? (course.find((s) => s.asks && lockedNote(s, f) === null) ?? first) : first+ if (next?.chapter === "Founding") return next+ const shown = guideSteps.find((s) => s.id === pace.shown && !s.course && open(s) && (!s.urgent || s.when(f)))if (shown) return shown- // The opening steps come one after another; the rest wait out the quiet.- return guideSteps.find((s) => open(s) && s.when(f) && (!pace.quiet || s.opening)) ?? null+ const sign = pace.quiet ? undefined : guideSteps.find((s) => !s.course && open(s) && s.when(f))+ return sign ?? next}diff --git a/src/ui.ts b/src/ui.tsindex 3a4eb6c..c555a0a 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -26,6 +26,18 @@ export interface Line {readonly goods?: ReadonlyArray<{ readonly good: GoodId; readonly count: number }> | undefined}+/**+ * A box of a panel's rows under a heading (`help` sits behind an ⓘ). Every+ * row reads the same way: what, then a short value; a note under it only+ * when there is something to do about it, or a line of context.+ */+export interface Group {+ readonly title: string+ readonly icon: IconName+ readonly help?: string | undefined+ readonly lines: ReadonlyArray<Line>+}+/** Something that needs looking at now, and where (when it is somewhere). */export interface Alert {/** A next step to take, something going wrong, or something that costs the town now. */@@ -126,7 +138,7 @@ export type Panel =readonly paused: boolean/** What pulling it down costs and gives back: "pull down: −25 coins · 2 planks back". */readonly salvage: string- readonly lines: ReadonlyArray<Line>+ readonly groups: ReadonlyArray<Group>}| {readonly type: "house"@@ -137,9 +149,10 @@ export type Panel =readonly closable: booleanreadonly closed: booleanreadonly salvage: string- readonly 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>+ /** How it is, in a word or two for the header ("4 residents", "hungry"), and whether that is trouble. */+ readonly summary: string+ readonly trouble: boolean+ readonly groups: ReadonlyArray<Group>}| {readonly type: "park"@@ -283,7 +296,27 @@ export interface Stats {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; readonly goal: string }) | null+ readonly step:+ | (Omit<Alert, "tone"> & {+ readonly key: string+ readonly chapter: string+ readonly goal: string+ /** Why the step matters, in a sentence or two (`text` is what to do). */+ readonly why: string+ /** The mayor has done their part, and the town is at work on it: what is happening (`null`: not yet). */+ readonly waiting: string | null+ /** The town cannot build what it asks for yet: what opens it (`null`: it can). */+ readonly locked: string | null+ /** The next step that waits for the town to need it, and when it comes ("Next: a quarry, once stone falls below 8"). */+ readonly next: string | null+ /** The buildings it asks for: only these become chips that place one. */+ readonly asks: ReadonlyArray<KindId>+ /** The building it points at, when that stands (`id`): its name goes there rather than placing another. */+ readonly near: KindId | null+ /** Where it stands in the opening ("step 3 of 8"), or `null` after it. */+ readonly count: { readonly at: number; readonly of: number } | null+ })+ | nullreadonly done: numberreadonly total: numberreadonly off: booleandiff --git a/test/guide.test.ts b/test/guide.test.tsindex 0040a98..fbbe89d 100644--- a/test/guide.test.ts+++ b/test/guide.test.ts@@ -1,14 +1,16 @@/**- * 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.+ * The mayor's guide (`src/rules/guide.ts`): it teaches a course in order,+ * chapter by chapter, and never falls silent before the town is complete;+ * signs from the town go ahead of the course once it is founded; it puts+ * away what the town has already done (shown or not); it says what opens a+ * building the town cannot build yet; and its words fit a finger as well as+ * a mouse.*/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"+import { courseCount, courseSteps, guideDone, guideStep, guideSteps, lockedNote, PLANKS_LOW, STONE_LOW, upcoming, type GuideFacts } from "../src/rules/guide.ts"const fresh: GuideFacts = {homes: 0,@@ -34,6 +36,11 @@ const fresh: GuideFacts = {most: 40,sawTown: false,sawHome: false,+ sawBuilding: false,+ roadToWater: false,+ goalsMet: false,+ coins: 1900,+ unreached: 0,risk: { fire: false, health: false, order: false },fewTrees: false}@@ -45,139 +52,182 @@ const town = (over: Partial<GuideFacts>, built: ReadonlyArray<KindId> = []): Gui...over})const none = new Set<string>()--test("a new town is told to lay homes, then to feed them", () => {+/** What the guide says next for a town, with what it has done put away. */+const next = (facts: GuideFacts, pace: { readonly shown?: string | null; readonly quiet?: boolean } = { quiet: true }, skipped: ReadonlyArray<string> = []) =>+ guideStep(facts, new Set([...guideDone(facts, none), ...skipped]), pace)?.id+const founding = courseSteps.filter((s) => s.chapter === "Founding")+/** A town through the Founding chapter. */+const founded = (over: Partial<GuideFacts> = {}, built: ReadonlyArray<KindId> = []) =>+ town({ homes: 10, residents: 30, roadToWater: true, sawBuilding: true, sawTown: true, ...over }, ["fishery", "lumberjack", "sawmill", ...built])++const low = amounts({ planks: PLANKS_LOW - 5, stone: 16, tools: 10, fish: 20 })++test("a new town is founded in order: homes, a road to the water, a fishery, its panel, planks (once low), the goal, ten homes", () => {+ assert.deepEqual(+ founding.map((s) => s.id),+ ["homes", "road", "fishery", "look", "lumberjack", "sawmill", "term", "grow"]+ )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("the opening comes step after step, each once the last is built", () => {- assert.equal(guideStep(fresh, none, { quiet: true })?.id, "homes")- const laid = town({ homes: 4, builtHomes: 0 })- assert.equal(guideStep(laid, new Set(guideDone(laid, none)))?.id, "homes", "laid homes are not yet done")- const housed = town({ homes: 4, residents: 8 })- const put = new Set(guideDone(housed, none))- assert.equal(guideStep(housed, put, { quiet: true })?.id, "fishery", "no quiet in the opening")- const building = { ...housed, placed: new Set<KindId>(["fishery"]) }- assert.equal(guideStep(building, put)?.id, "fishery", "a laid fishery is not done until it stands")- const fed = town({ homes: 4, residents: 8 }, ["fishery"])- assert.equal(guideStep(fed, new Set(guideDone(fed, none)), { quiet: true })?.id, "planks")- const sawn = town({ homes: 4, residents: 8 }, ["fishery", "lumberjack", "sawmill"])- assert.equal(guideStep(sawn, new Set(guideDone(sawn, none)), { quiet: true })?.id, "quarry")- // Then where to look: a home's panel, and the town's.- const quarried = town({ homes: 4, residents: 8 }, ["fishery", "lumberjack", "sawmill", "quarry"])- assert.equal(guideStep(quarried, new Set(guideDone(quarried, none)), { quiet: true })?.id, "look")- const looked = { ...quarried, sawHome: true }- assert.equal(guideStep(looked, new Set(guideDone(looked, none)), { quiet: true })?.id, "watch")- // And last, the go-ahead to grow, until ten homes stand.- const told = { ...looked, sawTown: true }- assert.equal(guideStep(told, new Set(guideDone(told, none)), { quiet: true })?.id, "grow")- const grown = { ...told, homes: 10, builtHomes: 10 }- assert.ok(guideDone(grown, none).includes("grow"))-})--test("citizens' needs come bread first, a building or two at a time, and not before bread can be made", () => {- const ready = town({ homes: 12, residents: 25, sawHome: true, sawTown: true }, ["fishery", "lumberjack", "sawmill", "quarry"])- const put = new Set(guideDone(ready, none))- assert.notEqual(guideStep(ready, put)?.id, "cloth", "cloth and faith are no use to settlers")- const grown = { ...ready, residents: 30 }- assert.equal(guideStep(grown, put)?.id, "wheat")- // One or two buildings at a time: wheat and flour, then the bakery, then cloth, then the chapel.- const chain: ReadonlyArray<[ReadonlyArray<KindId>, string]> = [[["farm", "mill"], "bakery"], [["farm", "mill", "bakery"], "cloth"], [["farm", "mill", "bakery", "sheep", "weaver"], "chapel"]]- for (const [more, next] of chain) {- const facts = town({ homes: 12, residents: 34, sawHome: true, sawTown: true }, ["fishery", "lumberjack", "sawmill", "quarry", ...more])- assert.equal(guideStep(facts, new Set(guideDone(facts, none)))?.id, next)+ assert.equal(next(town({ homes: 4, residents: 8 })), "road", "no quiet in the opening")+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true })), "fishery")+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true }, ["fishery"])), "look")+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true, sawBuilding: true, stock: low }, ["fishery"])), "lumberjack")+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true, sawBuilding: true }, ["fishery", "lumberjack"])), "sawmill", "a lumberjack wants its sawmill")+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true, sawBuilding: true }, ["fishery", "lumberjack", "sawmill"])), "term")+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true, sawBuilding: true, sawTown: true }, ["fishery", "lumberjack", "sawmill"])), "grow")+ assert.ok(guideDone(founded(), none).includes("grow"))+ assert.deepEqual(courseCount(founding[2]!), { at: 3, of: 8 })+})++test("after ten homes the course goes on to citizens, never falling silent, a building the town can build first", () => {+ // Ten homes stand, and quiet or not, the guide has the next step. Stone in store: no quarry yet.+ assert.equal(next(founded()), "cloth")+ assert.equal(next(founded({ stock: amounts({ planks: 30, stone: STONE_LOW - 2 }) })), "quarry", "a quarry once stone runs low")+ // Cloth and faith open at 15 residents, bread at 30: with 20, cloth comes first.+ const twenty = founded({ residents: 20 }, ["quarry"])+ assert.equal(next(twenty), "cloth")+ assert.equal(next(founded({ residents: 20 }, ["quarry", "sheep", "weaver"])), "chapel")+ // Bread cannot be made yet: the step says what opens it.+ const short = founded({ residents: 20 }, ["quarry", "sheep", "weaver", "chapel"])+ assert.equal(next(short), "wheat")+ assert.match(lockedNote(guideSteps.find((s) => s.id === "wheat")!, short)!, /opens at 30 residents \(20 now\)/)+ assert.equal(next(founded({ residents: 30 }, ["quarry", "sheep", "weaver", "chapel", "farm", "mill"])), "bakery")+ const supplied = founded({ residents: 40 }, ["quarry", "sheep", "weaver", "chapel", "farm", "mill", "bakery"])+ assert.equal(next(supplied), "citizens")+ assert.equal(next({ ...supplied, finerHomes: 1, sawTown: false }, { quiet: true }, founding.map((s) => s.id)), "goals")+ // The last word: every goal, until they are met.+ assert.equal(next({ ...supplied, finerHomes: 1 }), "complete")+ assert.equal(next({ ...supplied, finerHomes: 1, goalsMet: true }), undefined)+})++test("the course never asks for a building before the town needs it, and says what comes next", () => {+ // Plenty of planks: past the lumberjack and sawmill to the goal, saying when they come.+ const plenty = town({ homes: 4, residents: 8, roadToWater: true, sawBuilding: true, stock: amounts({ planks: 31, stone: 16 }) }, ["fishery"])+ assert.equal(next(plenty), "term")+ assert.equal(upcoming(plenty, new Set(guideDone(plenty, none))), `Next: a lumberjack and a sawmill, once planks fall below ${PLANKS_LOW} (31 now).`)+ // A laid lumberjack stays asked for while it goes up, whatever the planks.+ const laying = { ...plenty, placed: new Set<KindId>(["fishery", "lumberjack"]) }+ assert.equal(next(laying), "lumberjack")+ // The quarry waits for stone; the market for homes beyond the walkers; the smithy for tools.+ assert.equal(upcoming(founded(), new Set(guideDone(founded(), none))), `Next: a quarry, once stone falls below ${STONE_LOW} (16 now).`)+ assert.notEqual(next(founded({ residents: 60 }), {}), "market")+ assert.equal(next(founded({ unreached: 3 }), {}), "market")+ assert.notEqual(next(founded({ citizens: 12, residents: 80 }, ["quarry", "sheep", "weaver", "chapel", "farm", "mill", "bakery"]), {}), "smithy")+ assert.equal(next(founded({ citizens: 12, residents: 80, stock: amounts({ tools: 3, planks: 40, stone: 20 }) }, ["quarry", "sheep", "weaver", "chapel", "farm", "mill", "bakery"]), {}), "smithy")+})++test("a step the treasury cannot pay for says to save up, and gives way to one it can", () => {+ const poor = founded({ residents: 20, coins: 120 }, [])+ const chapel = guideSteps.find((s) => s.id === "chapel")!+ assert.match(lockedNote(chapel, poor)!, /Save up: the chapel costs 200 coins \(120 now\)/)+ // The sheep farm (100) can be paid for, the weaver (150) not yet: the cloth step asks, the cheaper first.+ assert.equal(lockedNote(guideSteps.find((s) => s.id === "cloth")!, poor), null)+})++test("every course step is one thing to do and one reason, short enough for a phone", () => {+ for (const step of courseSteps) {+ assert.ok(step.action.length <= 110, `${step.id}: the action fits a phone's peek`)+ assert.equal(step.action.match(/[.!?](\s|$)/g)?.length, 1, `${step.id}: the action is one sentence`)+ assert.ok(step.why.length <= 180, `${step.id}: the reason is short`)}})-const founded: ReadonlyArray<KindId> = ["fishery", "lumberjack", "sawmill", "quarry"]+test("no step names a key: tools are chips, and words fit both a finger and a mouse", () => {+ for (const step of guideSteps) {+ for (const text of [step.action, step.why, step.goal, step.waiting?.(fresh) ?? "", lockedNote(step, fresh) ?? ""]) {+ assert.doesNotMatch(text, /\([A-Z]\)|\bpress [A-Z]\b|\bEsc\b/i, `${step.id}: no keys`)+ assert.doesNotMatch(text.replace(/\{[^}]*\}/g, ""), /\bclick/i, `${step.id}: "click" only as {tap|click}`)+ for (const [, tool] of text.matchAll(/\[([a-z:]+)\]/g)) {+ assert.ok(+ ["select", "road", "pave", "homes", "build", "bulldoze", "town", "speed", "pause"].includes(tool!) || /^view:(appeal|workers|fire|health|order|condition)$/.test(tool!),+ `${step.id}: [${tool}] is a tool`+ )+ }+ }+ }+})-test("after the opening, steps wait for the town to need them", () => {- const settled = town({ homes: 10, residents: 20, sawHome: true, sawTown: true }, founded)- const put = new Set(guideDone(settled, none))- // Planks in hand, stone in hand, the woods full, no risk: nothing to say.- assert.equal(guideStep(settled, put), null)- assert.equal(guideStep({ ...settled, fewTrees: true }, put)?.id, "forester")- assert.equal(guideStep({ ...settled, risk: { fire: true, health: false, order: false } }, put)?.id, "firewatch")+test("a step under way says what the town is doing about it", () => {+ const homes = guideSteps.find((s) => s.id === "homes")!+ assert.equal(homes.waiting!(fresh), null, "nothing laid: nothing under way")+ assert.match(homes.waiting!(town({ homes: 4, builtHomes: 0 }))!, /planks/)+ assert.match(homes.waiting!(town({ homes: 4, builtHomes: 0, stock: amounts({ planks: 0 }) }))!, /no(ne| planks)/)+ const fishery = guideSteps.find((s) => s.id === "fishery")!+ const laid = { ...town({ homes: 4, residents: 8 }), placed: new Set<KindId>(["fishery"]) }+ assert.equal(guideStep(laid, new Set(["homes", "road"]))?.id, "fishery", "a laid fishery is not done until it stands")+ assert.match(fishery.waiting!(laid)!, /building site/)+ assert.equal(fishery.waiting!(town({ homes: 4 }, ["fishery"])), null, "standing: no longer under way")})-test("after a step the guide keeps quiet, but not through a fire or the crown's request", () => {- const facts = town({ homes: 10, residents: 20, fewTrees: true, sawHome: true, sawTown: true }, founded)- const put = new Set(guideDone(facts, none))- assert.equal(guideStep(facts, put, { quiet: true }), null)- assert.equal(guideStep({ ...facts, burning: 1 }, put, { quiet: true })?.id, "firewatch")- assert.equal(guideStep({ ...facts, crown: { open: true, met: 0 } }, put, { quiet: true })?.id, "crown")+test("a mayor who already knows the game is not walked through it", () => {+ const experienced = founded({ residents: 40 }, ["quarry"])+ const put = new Set(guideDone(experienced, none))+ for (const step of founding) assert.ok(put.has(step.id), step.id)+ assert.ok(put.has("quarry"))+ // A skipped step stays away, and the next comes.+ assert.equal(guideStep(fresh, new Set(["homes"]))?.id, "road")})-test("a step once shown stays until it is done, even if its sign fades", () => {- const thinning = town({ homes: 10, residents: 20, fewTrees: true, sawHome: true, sawTown: true }, founded)- const put = new Set(guideDone(thinning, none))- assert.equal(guideStep(thinning, put)?.id, "forester")- const planted = { ...thinning, fewTrees: false }- assert.equal(guideStep(planted, put), null)- assert.equal(guideStep(planted, put, { shown: "forester" })?.id, "forester")+test("the founding goes on past a step that cannot apply yet", () => {+ // The fishery was skipped: no panel to look at, so on to the lumberjack.+ assert.equal(next(town({ homes: 4, residents: 8, roadToWater: true, stock: low }), {}, ["fishery"]), "lumberjack")})-test("a step the mayor skipped stays away", () => {- assert.notEqual(guideStep(fresh, new Set(["homes"]))?.id, "homes")+test("signs wait while the town is founded, then go ahead of the course", () => {+ const fire = { fire: true, health: false, order: false }+ assert.equal(next(town({ homes: 4, residents: 8, risk: fire })), "road", "founding first")+ assert.equal(next(founded({ risk: fire }), {}), "firewatch")+ assert.equal(next(founded({ fewTrees: true }), {}), "forester")+ // While the guide keeps quiet, the course speaks instead.+ assert.equal(next(founded({ fewTrees: true }), { quiet: true }), "cloth")})-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("after a step the guide keeps quiet about signs, but not through a fire or the crown's request", () => {+ const facts = founded({ fewTrees: true })+ assert.notEqual(next(facts, { quiet: true }), "forester")+ assert.equal(next({ ...facts, burning: 1 }, { quiet: true }), "firewatch")+ assert.equal(next({ ...facts, crown: { open: true, met: 0 } }, { quiet: true }), "crown")+})++test("a sign once shown stays until it is done, even if it fades", () => {+ const thinning = founded({ fewTrees: true })+ assert.equal(next(thinning, {}), "forester")+ const planted = { ...thinning, fewTrees: false }+ assert.equal(next(planted, {}), "cloth")+ assert.equal(next(planted, { shown: "forester" }), "forester")+})++test("the crown's deadline goes ahead of everything", () => {+ assert.equal(next(town({ homes: 2, residents: 8, crown: { open: true, met: 0 } })), "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")+ assert.notEqual(next(founded({ winterIn: 400 })), "winter")+ assert.equal(next(founded({ winterIn: 90 })), "winter")+ assert.equal(next(founded({ winter: true, winterIn: 300 })), "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"],- wheat: ["farm", "mill"],- bakery: ["bakery"],- chapel: ["chapel"],- healer: ["healer"],- watchhouse: ["watchhouse"],- smithy: ["mine", "smithy"]- }+ assert.equal(next(founded({ stock: amounts({ tools: 2, planks: 30, stone: 10 }) }, ["sheep"]), {}), "tools")+})++test("the guide never sends the mayor to place a building the town cannot build yet", () => {// 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, risk: { fire: true, health: true, order: true }, fewTrees: true }, ["fishery", "lumberjack", "sawmill"])+ founded({ homes: 30, residents, citizens, winter: true, winterIn: 60, worn: true, sick: 3, burning: 1, risk: { fire: true, health: true, order: true }, fewTrees: true, poorStreet: true, unreached: 5, stock: amounts({ tools: 1 }) })for (const step of guideSteps) {- for (const kind of asks[step.id] ?? []) {+ for (const kind of step.asks ?? []) {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`)+ assert.match(step.action.toLowerCase(), new RegExp(kinds[kind].title.toLowerCase()), `${step.id} names the ${kind}, so it becomes a chip`)+ // Short of the unlock: either the step does not apply, or it says what opens it.+ for (const short of [residents > 0 ? everything(residents - 1, citizens) : null, citizens > 0 ? everything(residents + 200, citizens - 1) : null]) {+ if (!short) continue+ if (!step.when(short)) continue+ // A step asking for one of several (a granary or a smokehouse) is fine while one of them is open.+ const any = step.asks!.some((k) => kinds[k].unlock.residents <= short.residents && kinds[k].unlock.citizens <= short.citizens)+ assert.ok(step.course ? lockedNote(step, short) !== null : any, `${step.id} asks for a ${kind} before it opens, and says nothing`)+ }}}})@@ -187,12 +237,12 @@ test("every step says what closes it", () => {})test("every step can be done, and a town that has done them all is told nothing", () => {- const all = guideSteps.flatMap((s) => [s.id])+ const all = guideSteps.map((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, sawHome: true,- winter: true, worn: true, poorStreet: true, approval: 40, net: -5, most: 120, stock: amounts({ tools: 0 })+ homes: 200, residents: 400, citizens: 200, finerHomes: 30, crown: { open: true, met: 3 }, trading: true, taxed: true, sawTown: true, sawHome: true, sawBuilding: true,+ roadToWater: true, goalsMet: true, unreached: 5, 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"])