A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Panels say how a building is, why, and what to do; upgrades begin from the building; fish show on the water
SandroMaglione49f0c717b0d1
diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex a062830..f829092 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -96,10 +96,10 @@ six months.rises: the crown sends a reward, and play goes on. A rank is never lost.The town panel shows the next rank's goals.- **Upgrades** are made where a building stands, so they need no more- land. The build menu's *upgrades* lists every one, what it gives and- what it costs: pick one and the buildings it can go to are outlined;- hover one to see the same, and click it to begin (or use the button in- its panel). The coins are paid when the works begin; carriers then+ land. A gold arrow floats over every building the town can upgrade now+ (the rank reached, the coins in hand). Select the building: its panel+ says what the upgrade gives and costs, and its button begins it. The+ coins are paid when the works begin; carriers thenbring the planks, stone, and tools, builders work them in as they come,and scaffolding rises inside its plot. It goes on working meanwhile.- a village: the town hall becomes a *guildhall* (holds twice as much,diff --git a/scripts/look-ui.ts b/scripts/look-ui.tsindex 0be716d..88b6df0 100644--- a/scripts/look-ui.ts+++ b/scripts/look-ui.ts@@ -1,118 +1,111 @@/**- * A look at the screens PR #20 added, at desktop and phone sizes: the build- * menu's upgrades and the carpenter, the upgrade tool's tooltip, a building- * panel with works under way, a townhouse panel short of furniture, the- * goods bar and the town panel's needs, and the trade rows. Screenshots go- * to `output/look-ui`.+ * A look at the panels and markers in a lived-in town, at desktop and phone+ * sizes: a fishery whose water is fished out (and the fish on the water+ * around it), a settlers' cottage and a citizens' home with what they lack+ * and what to do, the gold arrows over what can be upgraded, the town hall's+ * panel with its upgrade, and the build menu. Screenshots go to+ * `output/look-ui`.*+ * node scripts/balance.ts --size small --seeds 1 --snapshot 30 --out snapshots* pnpm dev --host 127.0.0.1 --port 5232 &- * node scripts/look-ui.ts+ * SAVE=snapshots/small-fair-8919-30min.json node scripts/look-ui.ts*/import { existsSync } from "node:fs"-import { mkdir } from "node:fs/promises"+import { mkdir, readFile } from "node:fs/promises"import { chromium, type Page } from "playwright"const executable = process.env.BROWSER_EXECUTABLE_PATH ?? ["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)const browser = await chromium.launch({ headless: true, ...(executable ? { executablePath: executable } : {}) })const out = process.env.OUT ?? "output/look-ui"await mkdir(out, { recursive: true })+if (!process.env.SAVE) throw new Error("SAVE=<a save file, as `pnpm balance --snapshot` writes>")+const save = await readFile(process.env.SAVE, "utf8")const errors: Array<string> = []-/** A town at the town rank, with a street of townhouses and citizens' homes east of the hall, a market, and goods to spare. */-const stage = async (page: Page) => {- await page.evaluate(() => {- const { runtime } = (window as any).town- const s = runtime.snapshot()- s.resources["Town/Fate"].rank = 2- s.resources["Town/Treasury"].coins = 5000- const hall = s.entities.find((e: any) => e.components["Town/TownHall"])- const t = hall.components["Town/Tile"]- hall.components["Town/Inventory"].stock = { ...hall.components["Town/Inventory"].stock, planks: 90, stone: 90, tools: 20, cloth: 12, bread: 20, furniture: 3 }- const zero = Object.fromEntries(Object.keys(hall.components["Town/Inventory"].stock).map((g) => [g, 0]))- // Homes on the east side of the ring road: three townhouses (one with furniture, two without), then citizens' homes.- for (let i = 0; i < 5; i++) {- const tier = i < 3 ? 3 : 2- s.entities.push({- id: s.nextEntity++,- components: {- "Town/Tile": { x: t.x + 4, y: t.y - 1 + i, size: 1 },- "Town/House": { tier, residents: tier === 3 ? 8 : 6, food: 3, bread: 3, cloth: 3, faith: 3, furniture: i === 0 ? 2 : 0, clock: 0 },- "Town/Risk": { fire: 0, health: 0, order: 0, thefts: 0 },- "Town/Condition": { value: 1000 }- }- })- }- void zero- runtime.restore(s)- })- await page.evaluate(() => (window as any).town.advance(1))-}--const hallTile = (page: Page) =>- page.evaluate(() => (window as any).town.runtime.snapshot().entities.find((e: any) => e.components["Town/TownHall"]).components["Town/Tile"] as { x: number; y: number })--const settle = (page: Page) => page.waitForTimeout(500)+type Tile = { x: number; y: number; size: number }+const town = (page: Page) => page.evaluate(() => (window as any).town.runtime.snapshot()) as Promise<any>+const find = async (page: Page, test: (e: any) => boolean) => (await town(page)).entities.find(test) as anyfor (const [name, width, height, phone] of [["desktop", 1440, 1000, false], ["phone", 390, 844, true]] as const) {const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 2, ...(phone ? { isMobile: true, hasTouch: true } : {}) })page.on("pageerror", (e) => errors.push(`${name}: ${e.message}`))page.on("console", (m) => { if (m.type() === "error") errors.push(`${name}: ${m.text()}`) })- const shot = async (label: string) => { await settle(page); await page.screenshot({ path: `${out}/${name}-${label}.png` }) }- const tap = async (x: number, y: number) => (phone ? page.touchscreen.tap(x, y) : page.mouse.click(x, y))+ const settle = () => page.waitForTimeout(600)+ const shot = async (label: string) => { await settle(); await page.screenshot({ path: `${out}/${name}-${label}.png` }) }const at = (x: number, y: number, z = 0) => page.evaluate(([x, y, z]) => (window as any).town.view.project(x, y, z), [x, y, z]) as Promise<{ x: number; y: number }>- const close = async () => { await page.locator(".panel .close").first().click().catch(() => {}); await settle(page) }+ const look = (x: number, y: number, zoom: number) => page.evaluate(([x, y, zoom]) => { const v = (window as any).town.view; v.focus(x, y); v.camera.zoom = zoom; v.camera.updateProjectionMatrix() }, [x, y, zoom])+ const pick = async (tile: Tile, z = 10) => {+ const p = await at(tile.x + tile.size / 2, tile.y + tile.size / 2, z)+ if (phone) await page.touchscreen.tap(p.x, p.y)+ else {+ await page.mouse.click(p.x, p.y)+ await page.mouse.move(width / 3, height - 140)+ }+ }+ const close = async () => { await page.locator(".panel .close").first().click().catch(() => {}); await settle() }await page.goto(process.env.GAME_BASE_URL ?? "http://127.0.0.1:5232")+ await page.evaluate((text) => localStorage.setItem("inkline-town/save/manual", text), save)+ await page.reload()await page.waitForFunction(() => (window as any).town)- await page.getByRole("button", { name: "small", exact: true }).click()- await page.getByRole("button", { name: "Start new", exact: true }).click()+ await page.getByRole("button", { name: /Continue/ }).first().click()await page.waitForFunction(() => !(window as any).town.ui.founding)await page.locator(".toolbar .pause").click()- await page.locator(".guide .hide, .guide button").filter({ hasText: /hide/i }).first().click().catch(() => {})- await stage(page)- const hall = await hallTile(page)- await page.evaluate(([x, y]) => { const v = (window as any).town.view; v.focus(x, y); v.camera.zoom = 2; v.camera.updateProjectionMatrix() }, [hall.x + 3, hall.y + 1.5])-- // 1. The build menu: its upgrades section, and the carpenter among the workshops.- await page.locator(".toolbar button").filter({ hasText: /^build/i }).first().click()- await settle(page)- await page.locator(".panel .option").filter({ hasText: /carpenter/i }).first().scrollIntoViewIfNeeded().catch(() => {})- await shot("1-build-carpenter")- await page.locator(".panel").getByText(/upgrades/i).first().scrollIntoViewIfNeeded().catch(() => {})- await shot("2-build-upgrades")+ await page.evaluate(() => (window as any).town.ui.guide.push({ type: "off" }))- // 2. The upgrade tool's tooltip over the town hall (desktop only: phones show what is about to be built in a strip).- await page.evaluate(() => { const t = (window as any).town; t.ui.menu = null; t.ui.tool = "upgrade"; t.ui.upgrading = "townhall" })- await close()- const over = await at(hall.x + 1.5, hall.y + 1.5, 40)- await page.mouse.move(over.x, over.y)- await shot("3-upgrade-tooltip")-- // 3. Works begun on the town hall, part way, and its panel.- await page.evaluate(([x, y]) => (window as any).town.ui.edits.push({ type: "upgrade", cell: { x, y } }), [hall.x, hall.y])- await page.evaluate(() => (window as any).town.advance(30))- await page.evaluate(() => { const t = (window as any).town; t.ui.tool = "select"; t.ui.upgrading = null })- await tap(over.x, over.y)- await shot("4-works-panel")- await close()+ // 1. A fishery, its water fished out: its status says so, and what to do; the water beyond it still shows fish.+ const fishery = await find(page, (e) => e.components["Town/Building"]?.kind === "fishery" && !e.components["Town/Site"])+ if (fishery) {+ const f: Tile = fishery.components["Town/Tile"]+ await page.evaluate((f) => {+ const { runtime } = (window as any).town+ const s = runtime.snapshot(), tick = s.resources["Town/Time"].tick+ for (const e of s.entities) {+ const t = e.components["Town/Tile"], w = e.components["Town/Water"]+ if (w && Math.abs(t.x - f.x) <= 3 && Math.abs(t.y - f.y) <= 3) e.components["Town/Water"] = { fished: tick }+ }+ runtime.restore(s)+ }, f)+ await page.evaluate(() => (window as any).town.advance(12))+ await look(f.x + 1, f.y + 1, phone ? 1.4 : 2)+ await pick(f)+ await shot("1-fishery")+ await close()+ }- // 4. A townhouse short of furniture, and one furnished.- for (const [label, dy] of [["5-townhouse-unfurnished", 0], ["6-townhouse-furnished", -1]] as const) {- const p = await at(hall.x + 4.5, hall.y + dy + 0.5, 10)- await tap(p.x, p.y)- if (!phone) await page.mouse.move(width / 3, height - 160)+ // 2. A settlers' cottage and a citizens' home: what they lack, why, and what to do.+ for (const [label, tier] of [["2-cottage", 1], ["3-citizens-home", 2]] as const) {+ const home = await find(page, (e) => e.components["Town/House"]?.tier === tier && e.components["Town/House"].residents > 0 && !e.components["Town/Site"])+ if (!home) continue+ const h: Tile = home.components["Town/Tile"]+ await look(h.x + 0.5, h.y + 0.5, phone ? 1.4 : 2)+ await pick(h, 6)await shot(label)await close()}- // 5. The goods bar (on phones, opened from its chip) and the town panel: needs and trade.- if (phone) await page.locator(".goods-chip").click().catch(() => {})- await shot("7-goods-bar")- if (phone) await page.locator(".goods-chip").click().catch(() => {})- await page.locator(".toolbar button").filter({ hasText: /^town/i }).first().click()- await shot("8-town-panel")- await page.locator(".panel").getByText(/furniture/i).last().scrollIntoViewIfNeeded().catch(() => {})- await shot("9-town-panel-furniture")+ // 3. The upgrades the town can begin now, as gold arrows over the buildings; then the town hall's panel.+ await page.evaluate(() => {+ const { runtime } = (window as any).town+ const s = runtime.snapshot()+ s.resources["Town/Fate"].rank = Math.max(s.resources["Town/Fate"].rank, 2)+ s.resources["Town/Treasury"].coins = 5000+ runtime.restore(s)+ })+ await page.evaluate(() => (window as any).town.advance(1))+ const hall = (await find(page, (e) => e.components["Town/TownHall"])).components["Town/Tile"] as Tile+ await look(hall.x + 1.5, hall.y + 1.5, phone ? 0.9 : 1.2)+ await shot("4-upgrade-arrows")+ await look(hall.x + 1.5, hall.y + 1.5, phone ? 1.4 : 2)+ await pick(hall, 20)+ await shot("5-town-hall")+ await close()++ // 4. The build menu: no upgrades in it now.+ await page.locator(".toolbar button").filter({ hasText: /^build/i }).first().click()+ await settle()+ await page.locator(".panel").getByText(/parks/i).first().scrollIntoViewIfNeeded().catch(() => {})+ await shot("6-build-menu")await page.close()}console.log(JSON.stringify({ errors }))diff --git a/scripts/look-upgrades.ts b/scripts/look-upgrades.tsindex 313bc38..dbd87f9 100644--- a/scripts/look-upgrades.ts+++ b/scripts/look-upgrades.ts@@ -1,7 +1,7 @@/**- * A look at upgrades in the real 3D game: the build menu's upgrades, the- * upgrade tool's tooltip over the town hall, its scaffolding part way, and- * the guildhall it becomes. Screenshots go to `output/upgrades`.+ * A look at upgrades in the real 3D game: the gold arrow over the town+ * hall, its panel's upgrade (begun from its button), its scaffolding part+ * way, and the guildhall it becomes. Screenshots go to `output/upgrades`.** pnpm dev --host 127.0.0.1 --port 5232 &* node scripts/look-upgrades.ts@@ -38,22 +38,18 @@ try {await page.evaluate(() => (window as any).town.advance(1))const hall = await page.evaluate(() => (window as any).town.runtime.snapshot().entities.find((e: any) => e.components["Town/TownHall"]).components["Town/Tile"])await page.evaluate(([x, y]) => { const v = (window as any).town.view; v.focus(x, y); v.camera.zoom = 2.2; v.camera.updateProjectionMatrix() }, [hall.x + 1.5, hall.y + 1.5])- // The build menu, scrolled to its upgrades.- await page.locator(".toolbar button").filter({ hasText: /build/i }).first().click().catch(() => {})- await page.waitForTimeout(400)- await page.locator(".panel h3, .panel .title, .panel summary").filter({ hasText: /upgrades/i }).first().scrollIntoViewIfNeeded().catch(() => {})+ // The gold arrow over the town hall; then its panel, the upgrade first under its status, begun from its button.await page.waitForTimeout(600)- await page.screenshot({ path: `${out}/1-build-menu.png` })- // The upgrade tool over the town hall.- await page.evaluate(() => { const t = (window as any).town; t.ui.menu = null; t.ui.tool = "upgrade"; t.ui.upgrading = "townhall" })- const box = await page.evaluate(([x, y]) => (window as any).town.view.project(x, y, 40), [hall.x + 1.5, hall.y + 1.5])- if (box) await page.mouse.move(box.x, box.y)+ await page.screenshot({ path: `${out}/1-arrow.png` })+ const box = await page.evaluate(([x, y]) => (window as any).town.view.project(x, y, 20), [hall.x + 1.5, hall.y + 1.5])+ await page.mouse.click(box.x, box.y)+ await page.mouse.move(40, 900)+ const begin = page.getByRole("button", { name: /^Begin the guildhall$/ })+ await begin.waitFor()await page.waitForTimeout(300)- await page.screenshot({ path: `${out}/2-hover-tooltip.png` })- // Begin, then part way.- await page.evaluate(([x, y]) => (window as any).town.ui.edits.push({ type: "upgrade", cell: { x, y } }), [hall.x, hall.y])+ await page.screenshot({ path: `${out}/2-panel.png` })+ await begin.click()await page.evaluate(() => (window as any).town.advance(50))- await page.evaluate(() => { const t = (window as any).town; t.ui.tool = "select"; t.ui.upgrading = null })await page.waitForTimeout(300)await page.screenshot({ path: `${out}/3-scaffolding.png` })await page.evaluate(() => (window as any).town.advance(90))@@ -78,16 +74,14 @@ try {await page.screenshot({path:`${out}/5-cityhall.png`})// The new workshop's actual model portrait and upgrade choices must fit a phone.await page.setViewportSize({ width: 390, height: 844 })- await page.evaluate(() => { (window as any).town.ui.menu = "build" })+ await page.evaluate(() => { const ui = (window as any).town.ui; ui.selected = null; ui.menu = "build" })const carpenter = page.locator(".panel .option").filter({ has: page.locator(".name", { hasText: /^carpenter$/i }) })await carpenter.scrollIntoViewIfNeeded()await carpenter.locator("img").evaluate(async (img: HTMLImageElement) => { if (!img.complete) await new Promise<void>(resolve => img.addEventListener("load", () => resolve(), { once: true })) })assert.ok(await carpenter.locator("img").evaluate((img: HTMLImageElement) => img.naturalWidth > 0), "Carpenter portrait must render")await page.screenshot({ path: `${out}/5-carpenter-phone.png` })- const upgrades = page.locator(".panel h3").filter({ hasText: /^upgrades$/i })- await upgrades.scrollIntoViewIfNeeded()- assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "Upgrade menu fits the phone")- await page.screenshot({ path: `${out}/6-upgrades-phone.png` })+ assert.equal(await page.locator(".panel h3").filter({ hasText: /^upgrades$/i }).count(), 0, "upgrades are begun from a building's panel, not the build menu")+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "The build menu fits the phone")assert.deepEqual(errors, [])console.log(JSON.stringify({ errors, upgraded: await page.evaluate(() => (window as any).town.runtime.snapshot().entities.find((e: any) => e.components["Town/TownHall"]).components["Town/Upgraded"] ?? null) }))} finally {diff --git a/src/art.ts b/src/art.tsindex dd987af..7dbc8c2 100644--- a/src/art.ts+++ b/src/art.ts@@ -886,6 +886,8 @@ export interface BuildingLook {readonly level?: number/** An upgrade under way: the share of its materials in (scaffolding rises with it), else `null`. */readonly works?: number | null+ /** An upgrade it could begin now: show the upgrade marker over it. */+ readonly upgradable?: boolean}/** A building as drawn: its plate on the floor, its body among the other objects, and its problem marker above everything. */diff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.tsindex eb3c990..91507f9 100644--- a/src/asset-lab/assets.ts+++ b/src/asset-lab/assets.ts@@ -10,7 +10,7 @@ import { marketHall, church } from "./service-upgrades.ts"import { U } from "../iso.ts"import { makeTree, makeRock, makeField, makeRoadPatch, makeWater } from "./land.ts"import { personCatalogue, makeCarrier, makeGoods, makeCrate } from "./people.ts"-import { makeSite, makeConstruction, makeMarker, makeSmoke, makePlot } from "./construction.ts"+import { makeSite, makeConstruction, makeMarker, makeUpgradeMarker, makeSmoke, makePlot } from "./construction.ts"import { makeParkProp, makeRuin, makeSamplePark } from "./town-props.ts"import { upgradeCatalogue } from "./upgrade-catalogue.ts"@@ -163,6 +163,7 @@ additional.push(makeConstruction("warehouse", 0.3),makeConstruction("warehouse", 0.65),makeMarker(),+ makeUpgradeMarker(),makeSmoke(),...(["burnt", "collapsed", "derelict"] as const).map((cause) => makeRuin(1, cause)),makeRuin(2, "burnt"),diff --git a/src/asset-lab/construction.ts b/src/asset-lab/construction.tsindex bffd9bc..7de2814 100644--- a/src/asset-lab/construction.ts+++ b/src/asset-lab/construction.ts@@ -88,6 +88,21 @@ export function makeMarker() {}return d.asset}+/** Over a building the town can upgrade now: a gold arrow up, on the same thin sign as the problem marker. */+export function makeUpgradeMarker() {+ const d = new Drawing("upgrade-marker", "Upgrade marker", "A gold arrow on a thin world-space sign: this building can be upgraded now.")+ d.asset.category = "construction"+ d.asset.reference = { type: "none" }+ d.asset.footprint = 1+ const gold = 0xb8862f+ const p = (x: number, z: number, out = 0): Vertex => [x / 64 + out, -x / 64 + out, z]+ d.face([p(-7.5, 0), p(7.5, 0), p(7.5, 15), p(-7.5, 15)], 0xfbf6e8, 1, gold)+ for (const out of [-0.008, 0.008]) {+ d.face([p(0, 12.6, out), p(4.6, 7.6, out), p(-4.6, 7.6, out)], gold, 0)+ d.face([p(-1.6, 2.6, out), p(1.6, 2.6, out), p(1.6, 7.8, out), p(-1.6, 7.8, out)], gold, 0)+ }+ return d.asset+}export function makeSmoke() {const d = new Drawing("smoke", "Chimney smoke", "Animated soft smoke rises and disperses from a flue. The plume uses the same particle shader as the live game.")d.asset.category = "construction"diff --git a/src/content.ts b/src/content.tsindex eee4083..f151b66 100644--- a/src/content.ts+++ b/src/content.ts@@ -586,6 +586,9 @@ export const home = {taxFlight: { linear: 0.3, square: 0.2, citizens: 0.6 }}+/** A word with its article: "a guildhall", "an estate". */+export const anA = (word: string): string => `${/^[aeiou]/i.test(word) ? "an" : "a"} ${word}`+/** What a tier's homes are called, and what its residents are. */export const tierHome: Readonly<Record<Tier, string>> = { 1: "settlers' cottage", 2: "citizens' home", 3: "townhouse" }diff --git a/src/factory.css b/src/factory.cssindex 216ebcb..3608c31 100644--- a/src/factory.css+++ b/src/factory.css@@ -434,8 +434,25 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel .lines .line.ok .count { color: #4f8a3e; }.panel .lines .line.warn .count { color: #b8782e; }.panel .lines .line.bad .count { color: #b04a39; font-weight: 700; }-.panel .lines .line.bad .note { color: #8f3f31; }-.panel .lines .line.warn .note { color: #8a5a22; }+/* Why, in grey under the row; what to do, in a box of its own aligned with it, coloured by how pressing it is. */+.panel .lines .line .fix {+ grid-column: 2 / -1; display: flex; align-items: center; gap: 8px; margin-top: 3px; padding: 5px 8px;+ border: 1px solid #dfe3da; border-left: 3px solid #9aa29b; border-radius: 6px; background: #f1f3ee;+ font: inherit; font-size: 11.5px; line-height: 1.4; color: #3d4943; text-align: left;+}+.panel .lines .line .fix .thumb { width: 30px; height: 26px; object-fit: contain; flex: none; }+.panel .lines .line .fix > .icon { flex: none; opacity: 0.7; }+.panel .lines .line button.fix { cursor: pointer; }+.panel .lines .line button.fix:hover { border-color: #3d4943; border-left-color: inherit; background: #eceee8; }+.panel .lines .line.bad .fix { border-left-color: #b04a39; }+.panel .lines .line.warn .fix { border-left-color: #b8782e; }+/* A building's status, first under its header; and its upgrade, gold, when it has one to offer. */+.panel section.state .line .what { font-weight: 700; }+.panel section.state.trouble { border-top: 3px solid #b04a39; }+.panel section.state.trouble .line .what { color: #b04a39; }+.panel section.upgrade { border-top: 3px solid #b39a61; }+.panel section.upgrade .chips { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; margin: 2px 0 6px; }+.panel section.upgrade .cap { font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; color: #9aa29b; margin-right: 4px; }.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. */diff --git a/src/host.ts b/src/host.tsindex 02e454d..92f52f2 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 { Group, Line, Stats, Tool, TradeMode, UiValue, View } from "./ui.ts"+import type { Group, Line, Panel, 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"@@ -648,14 +648,6 @@ export const createHost = async (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`)}- /** Picks a kind's buildings to upgrade: each one it can go to is outlined, and the tooltip says what it gives and costs. */- const upgradeTool = (kind: KindId) => {- ui.menu = null- choose("upgrade")- ui.upgrading = kind- const title = kinds[kind].title.toLowerCase()- ui.toast(touchScreen() ? `Tap a ${title} to see its upgrade, then tap it again to begin` : `Click a ${title} to begin its upgrade · Esc to stop`)- }const furnish = (prop: PropId) => {ui.prop = propui.menu = null@@ -927,41 +919,6 @@ export const createHost = async (}panel.append(box)}- // Upgrades: every building that can be upgraded where it stands, what it becomes, what it gives, and what it costs.- const upgrades = section(- "upgrades",- "build",- "An upgrade is made where the building stands, so it needs no more land. Its coins are paid when the works begin; carriers then bring its materials, scaffolding rises around it, and it goes on working meanwhile. Pick one, then click the building."- )- upgrades.style.borderTop = "3px solid #b39a61"- // The town hall's first: it grows with the town; then the rest in the build menu's order.- for (const u of [...(ui.stats?.upgrades ?? [])].sort((a, b) => Number(b.kind === "townhall") - Number(a.kind === "townhall"))) {- const option = el("button", "option")- const cost = costChips({ coins: u.coins, materials: u.materials })- cost.box.prepend(el("span", "cap", "cost"))- const terms = el("span", "gives")- terms.innerHTML = `<span class="cap">gives</span>${u.changes.map((c) => `<span class="change">${c}</span>`).join("")}`- const blurb = el("span", "blurb", u.blurb)- option.append(picture(u.kind, u.level + 1), el("span", "name", `${u.from} → ${u.to}`), cost.box, terms, blurb)- option.title = `${u.from} → ${u.to}: ${u.blurb} · ${u.price} · ${u.changes.join(" · ")}`- option.onclick = () => upgradeTool(u.kind)- live.push(() => {- const now = ui.stats?.upgrades.find((x) => x.kind === u.kind && x.level === u.level)- option.style.display = now ? "" : "none"- if (!now) return- const short = cost.refresh()- option.disabled = now.blocked !== null || now.ready === 0- option.classList.toggle("short", now.blocked === null && short)- option.classList.toggle("on", ui.tool === "upgrade" && ui.upgrading === u.kind)- blurb.textContent = now.blocked- ? now.blocked- : now.ready === 0- ? now.underway > 0 ? `under way: ${now.underway}` : `build a ${kinds[u.kind].title.toLowerCase()} first`- : `${now.ready} ready${now.underway > 0 ? ` · ${now.underway} under way` : ""} · ${u.blurb}`- })- upgrades.append(option)- }- panel.append(upgrades)// Parks are laid out piece by piece: ground first, then what stands on it.const parks = section("parks",@@ -1331,6 +1288,20 @@ export const createHost = async (row.querySelector<HTMLElement>(".what")!.textContent = l.labelif (!chips) row.querySelector<HTMLElement>(".count")!.innerHTML = iconize(escapeHtml(l.value ?? ""))if (l.note) row.querySelector<HTMLElement>(".note")!.innerHTML = iconize(escapeHtml(l.note))+ // What to do about it, on a row of its own: a building to place shows its picture, and the row places one.+ if (l.fix) {+ const build = l.fix.build && kinds[l.fix.build].buildable ? l.fix.build : undefined+ const fix = el(build ? "button" : "div", "fix")+ if (build) {+ fix.dataset.build = build+ fix.title = `Build a ${kinds[build].title.toLowerCase()}`+ fix.append(picture(build))+ } else fix.append(iconEl("hint", 14))+ const text = el("span", "do")+ text.innerHTML = iconize(callouts(l.fix.text))+ fix.append(text)+ row.append(fix)+ }}/** 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>) => {@@ -1349,6 +1320,31 @@ export const createHost = async (})}+ /** What upgrading a building would give and cost, said in full before the mayor pays for it, with the button that begins it. */+ const upgradeBox = (offer: NonNullable<Extract<Panel, { type: "building" }>["upgrade"]>) => {+ const box = section(`upgrade to ${offer.title.toLowerCase()}`, "build", offer.blurb)+ box.classList.add("lines", "upgrade")+ const cost = costChips(offer.cost)+ cost.box.prepend(el("span", "cap", "cost"))+ const list = el("ul", "changes")+ for (const c of offer.changes) list.append(el("li", "", c))+ const begin = el("button", "frame primary", `Begin the ${offer.title.toLowerCase()}`)+ begin.onclick = () => {+ const now = ui.panel+ if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })+ }+ const why = el("p", "sub", "")+ live.push(() => {+ const now = ui.panel+ if (now?.type !== "building" || !now.upgrade) return+ cost.refresh()+ begin.disabled = now.upgrade.blocked !== null || now.upgrade.short !== null+ why.textContent = now.upgrade.blocked ?? now.upgrade.short ?? "the coins are paid now; carriers bring the rest, scaffolding rises, and it goes on working"+ })+ box.append(cost.box, list, begin, why)+ return box+ }+const buildPanel = () => {const p = ui.panellive = []@@ -1375,8 +1371,24 @@ export const createHost = async (: "burghers live here, and pay the best taxes")const below = el("div", "")- below.append(status, about)+ // A building says how it is in a box of its own, under the header; a home, a park, or a ruin in a word here.+ if (p.type === "building") below.append(about)+ else 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, p.type === "building" ? p.level : 0), below))+ // A building: how it is first, and what to do about it; then its upgrade, when it has one to offer.+ if (p.type === "building") {+ const box = section("status", p.problem !== null ? "warning" : "jobs")+ box.classList.add("lines", "state")+ const rows: Array<HTMLElement> = []+ live.push(() => {+ const now = ui.panel+ if (now?.type !== "building") return+ box.classList.toggle("trouble", now.problem !== null)+ syncLines(box, rows, [now.state])+ })+ panel.append(box)+ }+ if (p.type === "building" && p.upgrade) panel.append(upgradeBox(p.upgrade))// 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", "")@@ -1421,28 +1433,6 @@ export const createHost = async (syncGroups([{ title: "what is left", icon: "condition", lines: now.lines }])}})- // What upgrading it would give and cost, said in full before the mayor pays for it.- if (p.type === "building" && p.upgrade) {- const box = section(`upgrade to ${p.upgrade.title.toLowerCase()}`, "build", p.upgrade.blurb)- box.classList.add("lines")- const price = el("p", "sub", p.upgrade.price)- const list = el("ul", "changes")- for (const c of p.upgrade.changes) list.append(el("li", "", c))- const begin = el("button", "frame primary", `Begin the ${p.upgrade.title.toLowerCase()}`)- begin.onclick = () => {- const now = ui.panel- if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })- }- const why = el("p", "sub", "")- live.push(() => {- const now = ui.panel- if (now?.type !== "building" || !now.upgrade) return- begin.disabled = now.upgrade.blocked !== null || now.upgrade.short !== null- why.textContent = now.upgrade.blocked ?? now.upgrade.short ?? "the coins are paid now; carriers bring the rest, and it goes on working"- })- box.append(price, list, begin, why)- panel.append(box)- }if (p.type === "building" && p.kind === "townhall") return{const actions = el("div", "actions")@@ -1947,6 +1937,18 @@ export const createHost = async (ui.menu = nullchoose(id === "homes" ? "home" : (id as Tool))}+ // A panel row's fix: place the building it names, or pick the tool or panel it names.+ panel.addEventListener("click", (event) => {+ const target = event.target as HTMLElement+ const tool = target.closest<HTMLElement>(".fix [data-tool]")+ if (tool) return useTool(tool.dataset.tool!)+ const build = target.closest<HTMLElement>("[data-build], .fix [data-kind]")+ const kind = (build?.dataset.build ?? build?.dataset.kind) as KindId | undefined+ if (kind && kinds[kind].buildable) {+ ui.selected = null+ place(kind)+ }+ })/** 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: [] }diff --git a/src/present.ts b/src/present.tsindex 5657dd3..a7e0883 100644--- a/src/present.ts+++ b/src/present.ts@@ -12,7 +12,7 @@ import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.timport { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "./render3d/views.ts"import type { DoorSet, OverlayCell } from "./render3d/models.ts"import {- amounts, BUILD_TICKS, builtCost, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,+ amounts, BUILD_TICKS, builtCost, COMMUTE, RESTOCK_TICKS, STEP_SECONDS, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,kindOrder, nextUpgrade, worksNeeded, PAVE_COST, propIds, props, ranks, risk, RISK_MAX, ROAD_COST, tierHome, total, upgradeAt, upkeepOf, 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"@@ -87,14 +87,14 @@ import {import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, seasonAt, SITE_SHARE, steadyNet, taxOf, termTicks, upgradeBlock, winterOf } from "./sim/index.ts"import { Townsfolk } from "./townsfolk.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 { blockers as blockersOf, causeOf, servicesCause, streetAdvice, streetShort, type Cause, type Fix, type InTown, type Served, type Street } from "./rules/explain.ts"import { upgradeChanges, upgradePrice } from "./rules/upgrades.ts"import { breadBonus, moreAdmin, shortOf, streetTax, suppliedTaxOf, taxOutlook, type TaxedHome } from "./rules/households.ts"import { approvalTarget } from "./rules/approval.ts"import { salvageOf, salvageText, withWorks } from "./rules/salvage.ts"import { rockBlocks, type RockPart } from "./render3d/rock-blocks.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"+import { anA, TAX_STEPS, ticks } from "./content.ts"const cellAt = (at: Point): Point => {return { x: Math.floor(at.x), y: Math.floor(at.y) }@@ -136,29 +136,45 @@ interface Crewing {readonly crew: "settlers" | "citizens"}-/** Why a building is not working, in a line, or `null` when it is fine. */-const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: Crewing): string | null => {+/** Why a building is not working: in a word or two, why in a line, and what to do; `null` when it is fine. */+interface Problem extends Cause {+ readonly label: string+}++/** The kind that makes a good, for a fix that builds it. */+const makerOf = (good: GoodId): KindId | undefined => kindOrder.find((id) => kinds[id].recipe?.output === good)++const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: Crewing): Problem | null => {switch (status) {case "unconnected":- return "needs a road at the middle of one of its sides"+ return { label: "no road", why: "it needs a road at the middle of one of its sides", fix: { text: "lay a road along one of its sides" } }case "unstaffed":if (crewing && crewing.nearby === 0)- return `no workers nearby: no ${crewing.crew === "citizens" ? "citizens' (or settlers') homes" : "settlers' cottages"} within ${COMMUTE} road cells`- return "no workers: every one nearby already has a job"+ return { label: "no workers", why: `no ${crewing.crew === "citizens" ? "citizens' (or settlers') homes" : "settlers' cottages"} within ${COMMUTE} road cells`, fix: { text: "lay homes nearer, or a road to homes nearby" } }+ return { label: "no workers", why: "every one nearby already has a job", fix: { text: `lay more homes within ${COMMUTE} road cells` } }case "blocked":- return "full: nowhere to take what it makes"+ return { label: "full", why: "nowhere to take what it makes", fix: { text: "build a warehouse nearby, or sell the surplus in the [town] panel", build: ["warehouse"] } }case "paused":- return "paused: no workers, a quarter of its upkeep"+ return { label: "paused", why: "no workers, a quarter of its upkeep", fix: { text: "resume work below" } }case "starved":+ if (kind.gathers?.source === "water")+ return growing+ ? { label: "no fish", why: `the water in reach is fished out: each stretch rests ${Math.round(RESTOCK_TICKS * STEP_SECONDS)} s after a catch`, fix: { text: "give it a longer shore of its own, or fewer fisheries on this water" } }+ : { label: "no water", why: `no water within ${kind.gathers.radius} cells`, fix: { text: "rebuild it by the shore" } }if (kind.gathers && growing && (kind.gathers.source === "stone" || kind.gathers.source === "ore"))- return `the worked faces in reach give a little ${kind.gathers.source} now and then; traders sell it`- if (kind.gathers && growing) return `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing`+ return { label: "worked out", why: `the worked faces in reach give a little ${kind.gathers.source} now and then`, fix: { text: `build it by fresh rock, or buy ${kind.gathers.source} in the [town] panel` } }+ if (kind.gathers && growing) return { label: "waiting", why: `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing` }if (kind.gathers)- return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`- if (kind.recipe?.input) return `waiting for ${kind.recipe.input}`- if (kind.service?.service === "goods") return "nothing to hand out: no fish, bread, or cloth here"- if (kind.service?.service === "repair") return "no planks to mend with"- return "waiting"+ return kind.gathers.source === "tree"+ ? { label: "no trees", why: `no grown trees within ${kind.gathers.radius} cells`, fix: { text: "build a forester nearby: it replants", build: ["forester"] } }+ : { label: `no ${sourceTitle[kind.gathers.source]}`, why: `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells`, fix: { text: "rebuild it nearer" } }+ if (kind.recipe?.input) {+ const maker = makerOf(kind.recipe.input)+ return { label: `no ${kind.recipe.input}`, why: `waiting for ${kind.recipe.input}`, fix: maker ? { text: `build a ${kinds[maker].title.toLowerCase()}, or buy ${kind.recipe.input} in the [town] panel`, build: [maker] } : { text: `buy ${kind.recipe.input} in the [town] panel` } }+ }+ if (kind.service?.service === "goods") return { label: "nothing to hand out", why: "no fish, bread, or cloth here", fix: { text: "fill the store: it takes from storage" } }+ if (kind.service?.service === "repair") return { label: "no planks", why: "nothing to mend with", fix: { text: "build a sawmill", build: ["lumberjack", "sawmill"] } }+ return { label: "waiting", why: "waiting" }default:return null}@@ -171,7 +187,9 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: C*/const growingNear = (grid: GridValue, tile: TileLike, kind: Kind, rocks: ReadonlyMap<number, { readonly ore: boolean }>): boolean => {const g = kind.gathers- if (!g || g.source === "water") return false+ if (!g) return false+ // Water in reach, fished out: it rests, and gives again.+ if (g.source === "water") return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === "water")if (g.source === "stone" || g.source === "ore") return around(tile, g.radius).some((c) => rocks.get(key(c.x, c.y))?.ore === (g.source === "ore"))return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === g.source)}@@ -762,6 +780,11 @@ export const Interact = Game.System(}// ── Tooltip and panel ──+ // What stands, for a fix that builds something: it offers the first link of the chain the town lacks, else the last.+ const standing = new Set<KindId>(buildings.filter((r) => !r.data.site.present).map((r) => r.data.building.get().kind))+ const fixOf = (f: Fix | undefined): Line["fix"] => f && { text: f.text, build: f.build?.find((k) => !standing.has(k)) ?? f.build?.at(-1) }+ /** A cause as a row's note and fix. */+ const told = (c: Cause | null) => (c ? { note: c.why, fix: fixOf(c.fix) } : {})/*** 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.@@ -776,7 +799,7 @@ export const Interact = Game.System(owed.length > 0? { 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> }+ return { kind, status, problem: null, state: { icon: "build", label: "being built", tone: "warn" } as Line, groups: [{ title: "being built", icon: "build", lines: [line] }] as Array<Group> }}const staff = row.data.staff.get()const work: Array<Line> = []@@ -855,8 +878,13 @@ export const Interact = Game.System(...(running.length > 0 ? [{ title: "running it", icon: "coins", help, lines: running } as Group] : [])]const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind, rockAt)- const problem = row.data.burning.present ? "on fire!" : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })- return { kind, status, problem, groups }+ const trouble: Problem | null = row.data.burning.present+ ? { label: "on fire!", why: "its crew has fled", fix: { text: "a fire watch's watchmen put fires out", build: ["firewatch"] } }+ : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })+ const state: Line = trouble+ ? { icon: "warning", label: trouble.label, tone: "bad", note: trouble.why, fix: fixOf(trouble.fix) }+ : { icon: status === "working" ? "jobs" : "clock", label: status === "working" ? "working" : status, tone: status === "working" ? "ok" : undefined }+ return { kind, status, problem: trouble ? `${trouble.label}: ${trouble.why}` : null, state, groups }}/** What the town has of each provision, in storage and on market shelves. */const inTown = (): InTown => {@@ -958,7 +986,7 @@ export const Interact = Game.System(label: needTitle[n],value: now ? "missing" : `for ${home.tiers[nextTier!].title}`,tone: now ? "bad" : "warn",- note: whyUnmet(n, h, street, town, served) ?? undefined+ ...told(causeOf(n, h, street, town, served))})}const blocks = blockersOf(h, street, town, served, r)@@ -969,18 +997,19 @@ export const Interact = Game.System(label: "street",value: streetBlock ? `${signed(desirability)} of ${home.tiers[nextTier].appeal}` : "✓",tone: streetBlock ? "warn" : "ok",- note: streetBlock ? `${streetShort(street, home.tiers[nextTier].appeal)}: ${streetAdvice(street)}` : undefined+ ...(streetBlock ? { note: streetShort(street, home.tiers[nextTier].appeal), fix: { text: streetAdvice(street) } } : {})})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 (blocks.some((b) => b.what === "services")) needs.push({ icon: "order", label: "services", value: `for ${home.tiers[3].title}`, tone: "warn", ...told(servicesCause(r)) })// Rising is a rebuilding, paid at once from the treasury and the store, once.const rebuilt = nextTier !== null && (maybe(row.data.rebuilt)?.tier ?? 1) >= nextTierconst short = nextTier && !rebuilt ? shortOf(home.tiers[nextTier].rise, resources.treasury.get().coins, resources.stock.get()) : nullif (nextTier)needs.push({icon: "upkeep", label: "rebuilding", value: rebuilt ? "done ✓" : costText(home.tiers[nextTier].rise), tone: short ? "warn" : "ok",- note: short ? `the town is short of ${short}: it waits at its tier until the store can pay` : rebuilt ? "rebuilt already: it rises back for nothing" : undefined+ ...(short+ ? { note: `the town is short of ${short}`, fix: { text: "it waits at its tier until the store holds it: make it, or buy it in the [town] panel" } }+ : rebuilt ? { note: "rebuilt already: it rises back for nothing" } : {})})if (nextTier && blocks.length === 0 && !short)needs.push({ icon: "citizens", label: `ready for ${home.tiers[nextTier].title}`, value: "✓", tone: "ok", note: "it grows as the next resident moves in, and pays for its rebuilding then" })@@ -1045,7 +1074,7 @@ export const Interact = Game.System(const title = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()preview.tooltip = ui.tool === "bulldoze"? `${title} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(builtCost(kind, level), maybe(hoveredBuilding.data.site), works && { kind, ...works })}`- : `${title} · ${problem ?? status}${works ? ` · becoming a ${upgradeAt(kind, works.level)!.title.toLowerCase()}, ${Math.round(worksShare(works)! * 100)}% built` : ""}`+ : `${title} · ${problem ?? status}${works ? ` · becoming ${anA(upgradeAt(kind, works.level)!.title.toLowerCase())}, ${Math.round(worksShare(works)! * 100)}% built` : ""}`} else if (hoveredHouse) {const h = hoveredHouse.data.house.get()const t = hoveredHouse.data.tile.get()@@ -1080,7 +1109,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, groups } = describeBuilding(pickedBuilding)+ const { kind, status, problem, state, groups } = describeBuilding(pickedBuilding)const standing = !pickedBuilding.data.site.present && !pickedBuilding.data.rising.presentconst pausable = kind.id !== "townhall" && standingconst level = maybe(pickedBuilding.data.upgraded)?.level ?? 0@@ -1088,7 +1117,7 @@ export const Interact = Game.System(const works = maybe(pickedBuilding.data.works)const up = works ? undefined : nextUpgrade(kind, level)const upgradeOffer = up && standing- ? { title: up.title, blurb: up.blurb, price: upgradePrice(up), changes: upgradeChanges(kind, level),+ ? { title: up.title, blurb: up.blurb, price: upgradePrice(up), cost: up.cost, changes: upgradeChanges(kind, level),blocked: upgradeBlock(up, resources.fate.get().rank, { ranks }),short: resources.treasury.get().coins < up.cost.coins ? `${up.cost.coins - resources.treasury.get().coins} coins short` : null }: null@@ -1099,9 +1128,9 @@ export const Interact = Game.System(: nullif (worksOf)groups.unshift({- title: `becoming a ${worksOf.title.toLowerCase()}`,+ title: `becoming ${anA(worksOf.title.toLowerCase())}`,icon: "build",- lines: [{ icon: "build", label: "built", value: `${Math.round(worksOf.share * 100)}%`, tone: "warn", note: worksOf.left ? `carriers still bring ${worksOf.left}; it works on meanwhile` : "everything is in: the builders are finishing; it works on meanwhile" }]+ lines: [{ icon: "build", label: "built", value: `${Math.round(worksOf.share * 100)}%`, tone: "warn", note: worksOf.left ? `carriers still bring ${worksOf.left}; it works on meanwhile` : "every material is in; the builders are working it in, and it works on meanwhile" }]})ui.panel = {type: "building",@@ -1112,6 +1141,7 @@ export const Interact = Game.System(blurb: now?.blurb ?? kind.blurb,status,problem,+ state,groups,pausable,paused: pickedBuilding.data.paused.present,@@ -1341,7 +1371,7 @@ export const Interact = Game.System(// A word when an upgrade is open and nothing is being upgraded: where they are found.const open = upgrades.find((u) => u.blocked === null && u.ready > 0 && u.first)if (open && !upgrades.some((u) => u.underway > 0) && resources.treasury.get().coins >= open.coins)- alerts.push({ tone: "hint", text: `the ${open.from} can become a ${open.to}: [build] → upgrades says what it gives and costs`, at: open.first!.data.tile.get(), size: open.first!.data.tile.get().size, id: open.first!.entity.id })+ alerts.push({ tone: "hint", text: `the ${open.from} can become ${anA(open.to)}: {tap|click} it (the gold arrow over it) to see what it gives and costs`, at: open.first!.data.tile.get(), size: open.first!.data.tile.get().size, id: open.first!.entity.id })const ledger = resources.ledger.get()const charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)@@ -1772,10 +1802,12 @@ export const Animate = Game.System(}),trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),rocks: Game.Query({ selection: { rock: Game.Query.read(Rock), tile: Game.Query.read(Tile) } }),- fields: Game.Query({ selection: { field: Game.Query.read(Field) } })+ fields: Game.Query({ selection: { field: Game.Query.read(Field) } }),+ water: Game.Query({ selection: { tile: Game.Query.read(Tile), water: Game.Query.read(Water) } })},- resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal) },+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), fate: Game.System.readResource(Fate), treasury: Game.System.readResource(Treasury), time: Game.System.readResource(Time) },services: {+ stage: Game.System.service(StageService),ui: Game.System.service(Ui),clock: Game.System.service(Clock),ruinNodes: Game.System.service(RuinNodes),@@ -1793,10 +1825,17 @@ export const Animate = Game.System(const { hover, danger } = services.ui.previewconst emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")const dt = services.clock.deltaSeconds+ const rank = resources.fate.get().rank, coins = resources.treasury.get().coins+ // Fish where the water would give a catch now; none where it rests after one.+ const tick = resources.time.get().tick+ services.stage.setFish(queries.water.each().filter(({ data }) => tick - data.water.get().fished >= RESTOCK_TICKS).map(({ data }) => data.tile.get()))for (const { entity, data } of queries.buildings.each()) {const kind = kinds[data.building.get().kind]const status = data.status.get()+ // An upgrade it could begin now: its rank reached, its coins in hand, nothing under way.+ const up = data.works.present || data.site.present || data.rising.present ? undefined : nextUpgrade(kind, maybe(data.upgraded)?.level ?? 0)+ const upgradable = !!up && upgradeBlock(up, rank, { ranks }) === null && coins >= up.cost.coinsconst recipe = maybe(data.recipe)const walkers = maybe(data.walkers)?.length ?? 0const worn = (maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn@@ -1818,7 +1857,8 @@ export const Animate = Game.System(doors: doorsOf(grid, data.tile.get()),site: siteShare(maybe(data.site)),level: maybe(data.upgraded)?.level ?? 0,- works: worksShare(maybe(data.works))+ works: worksShare(maybe(data.works)),+ upgradable},dt,emphasis(entity.id)diff --git a/src/render3d/fish-effects.ts b/src/render3d/fish-effects.tsnew file mode 100644index 0000000..10a3de8--- /dev/null+++ b/src/render3d/fish-effects.ts@@ -0,0 +1,84 @@+import * as THREE from "three"+import { floorScale, vertex3 } from "../asset-lab/renderer.ts"+import type { Point } from "../iso.ts"++const vertex = `+attribute float seed;+varying vec2 point;+varying float phase;+void main(){+ point=position.xz/${(floorScale * 0.5).toFixed(3)};+ phase=seed;+ gl_Position=projectionMatrix*modelViewMatrix*instanceMatrix*vec4(position,1.0);+}`+// Two thin ink rings spreading from a point off the middle, now and then, and a fish's back turning in them.+const fragment = `+uniform float time;+varying vec2 point;+varying float phase;+void main(){+ vec2 at=point-vec2(fract(phase*7.13)-0.5,fract(phase*3.71)-0.5)*0.5;+ float d=length(at);+ float age=fract(time*0.32+phase);+ float ring=0.0;+ for(int i=0;i<2;i++){+ float r=age*0.75-float(i)*0.16;+ ring+=(1.0-smoothstep(0.0,0.035,abs(d-r)))*step(0.0,r)*(1.0-age);+ }+ float back=(1.0-smoothstep(0.05,0.075,length(at*vec2(1.0,2.4))))*(1.0-smoothstep(0.0,0.18,age))*step(0.02,age);+ float edge=1.0-smoothstep(0.85,1.0,max(abs(point.x),abs(point.y)));+ float alpha=clamp(ring*0.55+back*0.7,0.0,1.0)*edge;+ if(alpha<0.01)discard;+ gl_FragColor=vec4(pow(vec3(0.32,0.45,0.52),vec3(2.2)),alpha);+ #include <colorspace_fragment>+}`++/**+ * Fish in the water: ripples spreading now and then on every cell of water+ * that would give a catch, none on a cell resting after one. A fishery's+ * shore reads at a glance as stocked or fished out.+ */+export class FishWater {+ readonly group = new THREE.Group()+ private readonly time = { value: 0 }+ private mesh: THREE.InstancedMesh<THREE.PlaneGeometry, THREE.ShaderMaterial> | null = null+ private key = ""+ set(cells: ReadonlyArray<Point>) {+ const key = cells.map((c) => `${c.x},${c.y}`).join(";")+ if (key === this.key) return+ this.key = key+ if (!this.mesh || this.mesh.instanceMatrix.count < cells.length) {+ this.dispose()+ const capacity = Math.max(64, cells.length)+ const geometry = new THREE.PlaneGeometry(floorScale * 0.96, floorScale * 0.96)+ geometry.rotateX(-Math.PI / 2)+ geometry.setAttribute("seed", new THREE.InstancedBufferAttribute(new Float32Array(capacity), 1))+ const material = new THREE.ShaderMaterial({ vertexShader: vertex, fragmentShader: fragment, uniforms: { time: this.time }, transparent: true, depthWrite: false })+ this.mesh = new THREE.InstancedMesh(geometry, material, capacity)+ this.mesh.frustumCulled = false+ this.mesh.renderOrder = 2+ this.group.add(this.mesh)+ }+ const seeds = this.mesh.geometry.getAttribute("seed") as THREE.InstancedBufferAttribute+ const m = new THREE.Matrix4()+ cells.forEach((c, i) => {+ m.setPosition(vertex3([c.x + 0.5, c.y + 0.5, -0.1]))+ this.mesh!.setMatrixAt(i, m)+ seeds.setX(i, (Math.abs((c.x * 73856093) ^ (c.y * 19349663)) % 1000) / 1000)+ })+ this.mesh.count = cells.length+ this.mesh.instanceMatrix.needsUpdate = true+ seeds.needsUpdate = true+ }+ update(time: number) {+ this.time.value = time+ }+ dispose() {+ if (!this.mesh) return+ this.mesh.removeFromParent()+ this.mesh.geometry.dispose()+ this.mesh.material.dispose()+ this.mesh.dispose()+ this.mesh = null+ }+}diff --git a/src/render3d/scene.ts b/src/render3d/scene.tsindex c63f7b9..da807fe 100644--- a/src/render3d/scene.ts+++ b/src/render3d/scene.ts@@ -11,6 +11,7 @@ import type { Preview, UiValue } from "../ui.ts"import { ModelHandle, ModelPool } from "./pool.ts"import { groundAsset, landAsset, overlayAsset, previewAsset, type OverlayCell } from "./models.ts"import { parkAsset } from "../asset-lab/town-props.ts"+import { FishWater } from "./fish-effects.ts"import type { ParkCell } from "../appeal.ts"/** Where the camera stands: the grid cell it looks at, its zoom, and its angles. */@@ -58,6 +59,7 @@ export class GameScene {private roadPreview: BuiltAsset | null = nullprivate ghostHandles: Array<ModelHandle> = []private raycaster = new THREE.Raycaster()+ private fish = new FishWater()private plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)private width = 1private height = 1@@ -77,7 +79,7 @@ export class GameScene {this.renderer.domElement.setAttribute("aria-label", "Inkline Town 3D map. Drag to pan, right-drag to rotate, wheel to zoom.")this.renderer.domElement.tabIndex = 0mount.append(this.renderer.domElement)- this.scene.add(this.objects, this.pool.root)+ this.scene.add(this.objects, this.pool.root, this.fish.group)this.observer = new ResizeObserver(() => this.resize())this.observer.observe(mount)this.camera.zoom = innerWidth >= 1000 ? 1 : 0.65@@ -225,6 +227,10 @@ export class GameScene {this.groundKey = idthis.ground = this.replace(this.ground, groundAsset(roads, water, false, paved))}+ /** The water that would give a catch now: ripples on it (see `FishWater`). */+ setFish(cells: ReadonlyArray<Point>) {+ this.fish.set(cells)+ }/** The parks, redrawn whenever a cell of one (or a road beside one) changes. */setParks(cells: ReadonlyMap<number, ParkCell>, roads: ReadonlySet<number>) {const id = [...cells].map(([k, c]) => `${k}:${c.ground}:${c.prop}`).join(",") + "|" + [...roads].join(",")@@ -264,6 +270,7 @@ export class GameScene {this.groundDirty = truethis.parksKey = ""this.previewKey = ""+ this.fish.set([])for (const node of [...this.nodes]) node.destroy()this.nodes.clear()for (const handle of this.ghostHandles) handle.dispose()@@ -285,6 +292,7 @@ export class GameScene {this.camera.getWorldDirection(this.pool.viewDirection).negate()this.pool.time.value = now / 1000this.parks?.updateEffects(now/1000)+ this.fish.update(now / 1000)this.parkPreview?.updateEffects(now/1000)this.pool.flush()this.renderer.render(this.scene, this.camera)diff --git a/src/render3d/views.ts b/src/render3d/views.tsindex 690a323..05b0b31 100644--- a/src/render3d/views.ts+++ b/src/render3d/views.ts@@ -16,7 +16,7 @@ import { U, type Point } from "../iso.ts"import { vertex3 } from "../asset-lab/renderer.ts"import { Drawing, type Vertex } from "../asset-lab/primitives.ts"import { makeSails, makeFlag, buildingSmokeOrigin, buildingDimensions } from "../asset-lab/buildings.ts"-import { makeMarker } from "../asset-lab/construction.ts"+import { makeMarker, makeUpgradeMarker } from "../asset-lab/construction.ts"import { makeRuin } from "../asset-lab/town-props.ts"import { StructureEffects } from "./structure-effects.ts"import { SmokePlume } from "./smoke-effects.ts"@@ -89,6 +89,7 @@ export class BuildingView extends WorldView {private body: ModelHandleprivate plate: ModelHandleprivate marker: ModelHandle+ private upgradeMarker: ModelHandleprivate motion: ModelHandleprivate scaffold: ModelHandleprivate smoke: SmokePlume | null = null@@ -107,6 +108,9 @@ export class BuildingView extends WorldView {this.scaffold = this.model()this.marker.use("problem-marker", makeMarker)this.marker.root.visible = false+ this.upgradeMarker = this.model()+ this.upgradeMarker.use("upgrade-marker", makeUpgradeMarker)+ this.upgradeMarker.root.visible = falsethis.body.root.add(this.motion.root)}@@ -146,6 +150,9 @@ export class BuildingView extends WorldView {this.marker.root.position.set(0, (top + 8) / Math.cos(Math.PI / 6), 0)const signed = !!look.burning || (look.alert !== null && look.alert !== undefined)this.marker.root.visible = look.problem && look.build >= 1 && !signed+ // An upgrade it could begin now: a gold arrow in the marker's place, bobbing gently, when nothing is wrong.+ this.upgradeMarker.root.visible = !!look.upgradable && look.build >= 1 && !look.problem && !signed+ if (this.upgradeMarker.root.visible) this.upgradeMarker.root.position.set(0, (top + 8 + Math.sin(performance.now() / 420 + this.entity) * 1.5) / Math.cos(Math.PI / 6), 0)const state = structureState(look,this.stage.frost)this.body.effects = build >= 1 ? state : surfaceState()const serviceModel = upgraded && (this.kindId === "market" || this.kindId === "chapel")@@ -192,6 +199,7 @@ export class BuildingView extends WorldView {}override orient() {this.marker.root.rotation.y = this.stage.heading - Math.PI / 4+ this.upgradeMarker.root.rotation.y = this.stage.heading - Math.PI / 4}override destroy() { this.smoke?.dispose();this.smoke=null;super.destroy() }diff --git a/src/rules/explain.ts b/src/rules/explain.tsindex 0bdd734..523c3b8 100644--- a/src/rules/explain.ts+++ b/src/rules/explain.ts@@ -5,7 +5,7 @@* market in reach, nothing in store) are each told plainly. Plain* functions over plain facts: nothing here knows the ECS.*/-import type { Need, Tier } from "../content.ts"+import type { KindId, Need, Tier } from "../content.ts"import { shippedRules, type Rules } from "./config.ts"import { kept as keptBy, met, wantsBurgherGoods, wantsCitizenGoods, type Needs } from "./households.ts"@@ -50,51 +50,86 @@ export const streetAdvice = (street: Street): string =>? "move industry away, or add a park, a chapel, or paving": "a park, a chapel, or a paved street beside it"-const noWalker = (what: "market" | "chapel", rules: Rules) =>+/**+ * What to do about something: a line, and, when it is building something,+ * the chain that makes it, first link first (the panel offers the first+ * one the town lacks).+ */+export interface Fix {+ readonly text: string+ readonly build?: ReadonlyArray<KindId>+}+/** Why something is so, in a few words, and what to do about it (none: it comes in time). */+export interface Cause {+ readonly why: string+ readonly fix?: Fix+}++/** A cause as one line: "why: what to do". */+export const said = (c: Cause): string => (c.fix ? `${c.why}: ${c.fix.text}` : c.why)++const noWalker = (what: "market" | "chapel", rules: Rules): Cause =>what === "market"- ? `no market walker reaches this street: a market's walks ${rules.kinds.market.service!.range} road cells, the town hall's ${rules.kinds.townhall.service!.range}`- : `no chapel walker reaches this street: a chapel's walks ${rules.kinds.chapel.service!.range} road cells`+ ? { why: "no market walker reaches this street", fix: { text: `build a market: its walker walks ${rules.kinds.market.service!.range} road cells, the town hall's ${rules.kinds.townhall.service!.range}`, build: ["market"] } }+ : { why: "no chapel walker reaches this street", fix: { text: `build a chapel: its walker walks ${rules.kinds.chapel.service!.range} road cells`, build: ["chapel"] } }++/** A street not fine enough for a good to be brought to it: the street's own row says what lifts it. */+const tooPoor = (good: string, street: Street, needed: number): Cause => ({+ why: `${good} is not brought here: only to a street of ${needed} or more, and this one is ${signed(street.desirability)}`,+ fix: { text: "raise the street (see street)" }+})/*** Why a need is unmet, as a cause and a cure, or `null` when it is met.* Cloth is the one a town is most often puzzled by: it is only brought to* a street fit for citizens, however much is in store.*/-export const whyUnmet = (need: Need, h: Needs, street: Street, inTown: InTown, served: Served, rules: Rules = shippedRules): string | null => {+export const causeOf = (need: Need, h: Needs, street: Street, inTown: InTown, served: Served, rules: Rules = shippedRules): Cause | null => {if (met(h, need)) return null- const needed = rules.home.tiers[2].appealswitch (need) {case "cloth": {- if (!wantsCitizenGoods(h, street.desirability, rules))- return `cloth is not brought here: the street is at ${signed(street.desirability)} and needs ${needed}${against(street.parts) ? ` (${against(street.parts)})` : ""}`+ if (!wantsCitizenGoods(h, street.desirability, rules)) return tooPoor("cloth", street, rules.home.tiers[2].appeal)if (!served.goods) return noWalker("market", rules)- if (inTown.cloth === 0) return "the town has no cloth: a weaver makes it from a sheep farm's wool"- return "the market's walker has not passed with cloth lately"+ if (inTown.cloth === 0) return { why: "the town has no cloth", fix: { text: "build a weaver: it weaves a sheep farm's wool", build: ["sheep", "weaver"] } }+ return { why: "the market's walker has not passed with cloth lately" }}case "bread": {if (!served.goods) return noWalker("market", rules)- if (inTown.bread === 0) return "the town has no bread: a farm's wheat goes to a mill, and its flour to a bakery"- return "the market's walker has not passed with bread lately"+ if (inTown.bread === 0) return { why: "the town has no bread", fix: { text: "build a bakery: a farm's wheat goes to a mill, and its flour to a bakery", build: ["farm", "mill", "bakery"] } }+ return { why: "the market's walker has not passed with bread lately" }}case "food": {if (!served.goods) return noWalker("market", rules)- if (inTown.fish + inTown.smoked + inTown.bread === 0) return "the town has no food in store: a fishery by the water is the quickest"- return "the market's walker has not passed lately"+ if (inTown.fish + inTown.smoked + inTown.bread === 0) return { why: "the town has no food in store", fix: { text: "build a fishery by the water: it is the quickest", build: ["fishery"] } }+ return { why: "the market's walker has not passed lately" }}case "faith": {if (!served.faith) return noWalker("chapel", rules)- return "the chapel's walker has not passed lately"+ return { why: "the chapel's walker has not passed lately" }}case "furniture": {- if (!wantsBurgherGoods(h, street.desirability, rules))- return `furniture is not brought here: the street is at ${signed(street.desirability)} and a townhouse needs ${rules.home.tiers[3].appeal}${against(street.parts) ? ` (${against(street.parts)})` : ""}`+ if (!wantsBurgherGoods(h, street.desirability, rules)) return tooPoor("furniture", street, rules.home.tiers[3].appeal)if (!served.goods) return noWalker("market", rules)- if (inTown.furniture === 0) return "the town has no furniture: a carpenter makes it from planks"- return "the market's walker has not passed with furniture lately"+ if (inTown.furniture === 0) return { why: "the town has no furniture", fix: { text: "build a carpenter: it makes furniture from planks", build: ["sawmill", "carpenter"] } }+ return { why: "the market's walker has not passed with furniture lately" }}}}+/** Why a need is unmet, in one line, or `null` when it is met (see `causeOf`). */+export const whyUnmet = (need: Need, h: Needs, street: Street, inTown: InTown, served: Served, rules: Rules = shippedRules): string | null => {+ const c = causeOf(need, h, street, inTown, served, rules)+ return c ? said(c) : null+}++/** The services a townhouse wants calling that are not keeping its risks down, as a cause. */+export const servicesCause = (risk: { readonly fire: number; readonly health: number; readonly order: number } | undefined, rules: Rules = shippedRules): Cause | null => {+ if (risk && keptBy(risk, rules)) return null+ const high = (["fire", "health", "order"] as const).filter((r) => !risk || risk[r] >= rules.risk.kept)+ const by = { fire: "firewatch", health: "healer", order: "watchhouse" } as const+ return { why: `${high.join(", ")} not kept down`, fix: { text: "a fire watch, a healer, and a watch house must all call here", build: high.map((r) => by[r]) } }+}+export interface Blocker {readonly what: Need | "street" | "services"readonly text: string@@ -121,9 +156,7 @@ export const blockers = (if (why) out.push({ what: need, text: why })}if (street.desirability < rules.home.tiers[next].appeal) out.push({ what: "street", text: `the street is ${streetShort(street, rules.home.tiers[next].appeal)} · ${streetAdvice(street)}` })- if (next === 3 && (!risk || !keptBy(risk, rules))) {- const high = risk ? (["fire", "health", "order"] as const).filter((r) => risk[r] >= rules.risk.kept) : ["fire", "health", "order"]- out.push({ what: "services", text: `${high.join(", ")} not kept down: a fire watch, a healer, and a watch house must all call here` })- }+ const services = next === 3 ? servicesCause(risk, rules) : null+ if (services) out.push({ what: "services", text: said(services) })return out}diff --git a/src/rules/guide.ts b/src/rules/guide.tsindex aecb599..c003c08 100644--- a/src/rules/guide.ts+++ b/src/rules/guide.ts@@ -447,7 +447,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [{id: "markethall",chapter: "Keeping it standing",- action: "Open [build], pick the market hall under upgrades, and {tap|click} a market.",+ action: "{Tap|Click} the market (the gold arrow over it) and begin its market hall from its panel.",why: "Some homes are beyond every food walker. A market hall's walker goes further and more often, without a second market's upkeep.",goal: "a market hall stands",focus: { kind: "market" },diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex b21e7c0..220ee5a 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -8,7 +8,7 @@*/import { buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft } from "../archetypes.ts"import * as Random from "@typeonce/bevy-ts-math/Random"-import { amounts, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, ticks, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"+import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, ticks, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"import { inside } from "../iso.ts"import { generate } from "../mapgen.ts"@@ -425,7 +425,7 @@ export const ApplyEdits = Game.System(const owed = amounts(up.cost.materials)commands.insert(row.value.entity.id, Game.Command.entry(Works, { owed, total: total(owed), done: 0, level: (level + 1) as 1 | 2 }))const was = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()- write(resources.chronicle, t, `Works begin on the ${was}: it is to be a ${up.title.toLowerCase()}.`)+ write(resources.chronicle, t, `Works begin on the ${was}: it is to be ${anA(up.title.toLowerCase())}.`)ui.toast(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)break}diff --git a/src/sim/work.ts b/src/sim/work.tsindex 10845b2..da36d01 100644--- a/src/sim/work.ts+++ b/src/sim/work.ts@@ -8,7 +8,7 @@ import { wildTreeSpots, canSeedTree } from "../rules/land.ts"import * as Random from "@typeonce/bevy-ts-math/Random"import { fieldDraft, treeDraft } from "../archetypes.ts"-import { amounts, asUpgraded, crewOf, goodIds, ticks, total, upgradeAt, worksNeeded, type Amounts, type Crew } from "../content.ts"+import { amounts, anA, asUpgraded, crewOf, goodIds, ticks, total, upgradeAt, worksNeeded, type Amounts, type Crew } from "../content.ts"/** The flow of goods is counted in slices this many seconds long, and the last `FLOW_SLICES` of them (a minute) are kept. */const FLOW_SLICE = 10@@ -214,7 +214,7 @@ export const Raise = Game.System(if (carriers && kind.carriers) commands.insert(entity.id, Game.Command.entry(Carriers, { count: kind.carriers }))if (service && kind.service) commands.insert(entity.id, Game.Command.entry(Service, { ...service, interval: ticks(kind.service.seconds), range: kind.service.range }))const was = (upgradeAt(base, works.level - 1)?.title ?? base.title).toLowerCase()- write(resources.chronicle, elapsed(resources.time.get(), resources.charter.get()), `The ${was} is now a ${upgradeAt(base, works.level)!.title.toLowerCase()}.`, true)+ write(resources.chronicle, elapsed(resources.time.get(), resources.charter.get()), `The ${was} is now ${anA(upgradeAt(base, works.level)!.title.toLowerCase())}.`, true)}for (const { entity, data } of queries.sites.each()) {diff --git a/src/ui.ts b/src/ui.tsindex 8f7968b..fb62215 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -24,6 +24,8 @@ export interface Line {readonly note?: string | undefinedreadonly tone?: Tone | undefinedreadonly goods?: ReadonlyArray<{ readonly good: GoodId; readonly count: number }> | undefined+ /** What to do about it, under the note: and, when it is to build something, what (the panel offers to place it). */+ readonly fix?: { readonly text: string; readonly build?: KindId | undefined } | undefined}/**@@ -135,6 +137,8 @@ export type Panel =readonly status: Status/** Why it is not working, when it is not. */readonly problem: string | null+ /** How it is, as a row of its own above the rest: working, or what keeps it from it and what to do. */+ readonly state: Line/** Whether it can be paused (not the town hall, not a site), and whether it is. */readonly pausable: booleanreadonly paused: boolean@@ -155,6 +159,8 @@ export type Panel =readonly title: stringreadonly blurb: stringreadonly price: string+ /** Coins now, and the materials carriers bring. */+ readonly cost: { readonly coins: number; readonly materials: Partial<Record<GoodId, number>> }readonly changes: ReadonlyArray<string>readonly blocked: string | nullreadonly short: string | nulldiff --git a/test/legibility.test.ts b/test/legibility.test.tsindex 602192d..0206c91 100644--- a/test/legibility.test.ts+++ b/test/legibility.test.ts@@ -28,17 +28,19 @@ test("cloth withheld from a poor street is told as the street, not as missing clconst why = whyUnmet("cloth", settlers, quarryStreet, plenty, served)assert.ok(why, "an unmet need has a reason")assert.match(why, /not brought here/)- assert.match(why, /needs 5/)- assert.match(why, /quarry −6/)+ assert.match(why, /street of 5 or more/)+ assert.match(why, /raise the street/)+ // What drags the street down, and what lifts it, is the street's own line.const all = blockers(settlers, quarryStreet, plenty, served, { fire: 0, health: 0, order: 0 })assert.deepEqual(all.map((b) => b.what), ["cloth", "street"])+ assert.match(all[1]!.text, /quarry −6/)assert.match(all[1]!.text, /move industry away|park/)})test("on a street fit for citizens the reason moves to the walker or the store", () => {const fine: Street = { desirability: 6, parts: [{ label: "chapel", value: 4 }, { label: "market", value: 2 }] }assert.match(whyUnmet("cloth", settlers, fine, plenty, served)!, /walker has not passed with cloth/)- assert.match(whyUnmet("cloth", settlers, fine, { ...plenty, cloth: 0 }, served)!, /no cloth: a weaver/)+ assert.match(whyUnmet("cloth", settlers, fine, { ...plenty, cloth: 0 }, served)!, /no cloth: build a weaver/)assert.match(whyUnmet("cloth", settlers, fine, plenty, { goods: false, faith: true })!, new RegExp(`${kinds.market.service!.range} road cells`))assert.equal(whyUnmet("faith", settlers, fine, plenty, served), null)assert.match(whyUnmet("faith", { ...settlers, faith: 0 }, fine, plenty, { goods: true, faith: false })!, /no chapel walker/)@@ -111,7 +113,7 @@ test("a real town: cottages beside a quarry are told why they will not grow", {const house = cottages[0]!.components["Town/House"]const street: Street = { desirability: worst, parts: [{ label: "quarry", value: worst }] }const why = blockers({ ...house, bread: 1, faith: 1, cloth: 0 }, street, plenty, served, undefined)- assert.ok(why.some((b) => b.what === "cloth" && /needs 5/.test(b.text)), "cloth is explained by the street")+ assert.ok(why.some((b) => b.what === "cloth" && /street of 5/.test(b.text)), "cloth is explained by the street")assert.ok(why.some((b) => b.what === "street" && /quarry/.test(b.text)), "the street names the quarry")// And the rules bite at once: the street holds fewer than a plain one would.assert.ok(capacity(house, s.resources["Town/Mood"].approval, worst) < capacity(house, s.resources["Town/Mood"].approval, 0) || worst > -3, "a street below −2 holds fewer")