Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

Tell the player why: causal panels, a clickable ticker, and rules that bite

SandroMaglione90aed9a2f4d5
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index f0e5fe4..4f32cfb 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -251,6 +251,11 @@ pnpm balance -- --snapshot 40 # save each seed's town at minut
The simulation has no renderer in it: it runs headless (`src/sim/headless.ts`),
about 60 to 80 times faster than real time, so the tests play real towns.
+`pnpm test` also runs `test/legibility.test.ts`: when a home is stuck, the
+panel's reasons (`src/rules/explain.ts`) must name the cause in words,
+checked against the usual dead ends and a real town with cottages beside a
+quarry. The bots know the thresholds; the player only has the panel.
+
`pnpm test` runs model-based tests built on Effect's `Schema` and
`Arbitrary`. They generate sequences of what a mayor can do (roads, homes,
buildings where they fit, bulldozing, taxes, trade, pausing, answering the
diff --git a/docs/balance-model.md b/docs/balance-model.md
index 5ff0660..5598023 100644
--- a/docs/balance-model.md
+++ b/docs/balance-model.md
@@ -4,6 +4,8 @@ The model reads the game's content and pure rules. It runs independently of the
No values in `src/content.ts` changed when this component was added. Private carrier/walker constants moved into shared configuration with their original values. `src/rules/` owns immutable inputs and the existing household, tax, trade, approval, production cadence, staffing, season, risk, road-choice and dispatch-priority functions. The simulation calls the same functions. Grid and desirability calculations retain their existing shared implementations.
+The model shares the street factors on room and taxes, the bread bonus, and the continuous desirability rules with the game. It does not model the grudge over taxes (the forecast keeps the memory at zero) nor the faster walking on paved streets; neither appears in the verified scenarios.
+
## Run it
```sh
diff --git a/docs/how-to-play.md b/docs/how-to-play.md
index 8cdbf30..5fa8bc6 100644
--- a/docs/how-to-play.md
+++ b/docs/how-to-play.md
@@ -17,7 +17,7 @@ town, the levers you hold, how a term ends, and how the town works underneath.
| **Home**, camera reset button | restore the original view |
| **S** | select: click a building or a home to see what it does |
| **R** | road: drag to lay one |
-| **P** | pave: drag along a road to pave it (coins and a stone a cell) |
+| **P** | pave: drag along a road to pave it (coins and a stone a cell): carriers and walkers go half again as fast on it |
| **H** | homes: drag to lay a row along a road |
| **B** | build: pick a building, then click the map |
| **X** | bulldoze |
@@ -52,14 +52,16 @@ New town and load ask before they replace the town you have.
it buys; stone and ore run out;
- *approval*, from -100 to 100, follows needs met, taxes, unpaid wages,
snubs from the crown, and hungry winters, and decides how many people
- each home holds.
+ each home holds. Taxes above 125% also leave a *grudge* that builds
+ for as long as they stay high and fades over ten minutes or so, so a
+ term of squeezing cannot be undone by cutting taxes at the end.
- **The levers**: taxes per tier; for each good, sell beyond the reserve,
buy up to it (at half again the price), or neither; the reserve itself;
pausing a building (no workers, a quarter of its upkeep); answering the
crown; and the speed of time (space pauses, 1, 2, 3 for 1×, 2×, 4×).
- **The end**: the town is *complete* once it holds every goal for two
minutes (enough residents and coins for its size, three in ten of them
- citizens, approval 15 or more, not losing coins); you may retire or keep
+ citizens, approval 15 or more, not losing coins over the last minute); you may retire or keep
governing. It is *lost* to bankruptcy (three minutes in debt), revolt
(approval at -50 or below for two minutes), abandonment (people fall
below 15% of their peak), or dismissal (three of the crown's requests
@@ -78,7 +80,11 @@ Nobody tells you to build it that way; it works best that way.
beside it and less out to four cells; a sawmill, bakery, mill, or
smokehouse 4; warehouses, farms, a granary, a builder's yard 2. Water and
woods give 2, a market 2 and a chapel 4, the town hall 4, and a paved
- street 1 beside it. Ruins and run-down homes take a little.
+ street 1 beside it. Ruins and run-down homes take a little. Every point
+ counts: 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.
- **Parks** are laid out cell by cell from the build menu. Drag a
rectangle 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
@@ -104,9 +110,11 @@ Nobody tells you to build it that way; it works best that way.
(lumberjack, forester, quarry, mine, fishery, smokehouse, farm, sheep,
storage, fire watch, watch house, builder's yard); citizens the skilled
(sawmill, smithy, mill, bakery, weaver, market, chapel, healer,
- hospital). Citizens never take settlers' jobs: upgrade every home and the
- quarry stands empty. Until there are citizens, settlers stand in at a
- skilled job as apprentices, at three-quarters pace. A home only supplies workers to
+ hospital). Skilled jobs take their own crew first; citizens left over do
+ rough work, and until there are citizens, settlers stand in at a
+ skilled job as apprentices, at three-quarters pace. The jobs counter in
+ the top right says how many workplaces are short, and clicking it visits
+ them in turn. A home only supplies workers to
workplaces within 15 road cells, so a distant mine needs its own workers'
cottages beside it (they stay settlers in its dust, which is what it
needs). A workplace short of workers says whether anyone lives within
@@ -116,9 +124,10 @@ Nobody tells you to build it that way; it works best that way.
Every home has three risk meters that rise slowly, at a pace fixed by where
it stands, and every building a fire meter. A walker from the matching
-service resets one as it passes. Past 70% a sign goes up over the home (a
-smoke wisp, a pale face, a broken window); disaster comes only if the meter
-reaches the top.
+service resets one as it passes. Past half way a sign goes up over the home (a
+smoke wisp, a pale face, a broken window) and the map views turn it red;
+disaster comes only if the meter reaches the top. The views colour the
+buildings themselves, not only the ground under them.
| Service | Building | What raises the risk | If neglected |
|---|---|---|---|
@@ -129,16 +138,21 @@ reaches the top.
A good layout prevents disasters: streets between rows of homes stop a fire
from spreading, a fire watch near the cottages gets firefighters there in
time, and industry away from homes keeps them healthy and orderly. The town
-ticker under the top bar lists what needs attention now (fires, sickness,
-workshops waiting for inputs, workplaces nobody can walk to, no food in
-store) and the latest news, which also pops up as it happens.
+ticker 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
+and a half, which also pops up as it happens. Click a line to go there.
## Wear, spoilage, and winters
- **Food spoils in store**: fish keeps about three minutes, bread about
five; wheat, flour, and smoked fish keep. A **granary** keeps fish and
bread five times as long, and a **smokehouse** turns fish into smoked
- fish, which keeps through any winter. Markets hand out fresh fish first.
+ fish, which keeps through any winter. Markets hand settlers fresh fish
+ first, and a loaf besides when they have none: a cottage with bread on
+ the table pays a quarter more, so bread is worth baking before anyone is
+ a citizen. When food rots, the news says whether the town simply makes
+ more than it eats.
- **Tools wear out**: a lumberjack, quarry, mine, sawmill, mill, bakery,
weaver, or smokehouse uses up a tool every 50 or 60 jobs, and works at
half pace without one. Carriers keep one on hand at each.
@@ -159,7 +173,10 @@ store) and the latest news, which also pops up as it happens.
- **A new town** has a town hall in a clearing, ringed by road, plus
starting coins and goods.
-- **Coins**: homes the town hall can reach by road pay taxes; traders buy
+- **Coins**: homes the town hall can reach by road pay taxes, in proportion
+ to the needs they have met: a hungry home pays nothing, a cottage with
+ bread pays half again, a fine street up to a quarter more, and the town
+ panel says what the same homes would pay if every one were supplied; traders buy
what the town sells and sell it what it buys; every building costs upkeep
and the town hall costs administration. Building costs coins up front.
The **town** panel (T, the town button, or the people in the top right) shows the goals, approval,
@@ -171,9 +188,13 @@ store) and the latest news, which also pops up as it happens.
(fish, smoked fish, or bread); with bread, cloth, and faith on a street
with desirability 5 a home becomes a two-story citizens' home that holds
and pays twice as much, and on a fine street (15) with every service
- calling, a three-story townhouse.
+ calling, a three-story townhouse. Cloth is only brought to a street fit
+ for citizens, however much is in store: the home's panel says so, and
+ what the street is short of.
- **Buildings** need a road at the middle of a side and workers of their
- crew from homes within 15 road cells. Parks need no road and no
+ crew from homes within 15 road cells. While one is placed (or selected),
+ the roads its walkers or its workers would use are shown; the homes tool
+ shows how far its residents would walk to work. Parks need no road and no
workers; their stone comes straight out of storage. Gatherers work the land within their reach (trees, rocks, water,
fields); workshops turn one good into another.
- **Carriers** walk every good along the roads: producers send to whoever
diff --git a/src/art.ts b/src/art.ts
index 4b11ff1..cefd8b4 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -879,6 +879,8 @@ export interface BuildingLook {
readonly doors: Doors
/** While a site: the share of its materials in, else `null`. */
readonly site: number | null
+ /** A map view's colour washed over it, when one is shown. */
+ readonly tint?: number | undefined
}
/** A building as drawn: its plate on the floor, its body among the other objects, and its problem marker above everything. */
@@ -1062,6 +1064,8 @@ export interface HouseLook {
readonly worn?: boolean
/** Its neighbourhood: poor, plain, or fine (see `HouseView`). */
readonly band?: "poor" | "plain" | "fine"
+ /** A map view's colour washed over it, when one is shown. */
+ readonly tint?: number | undefined
}
/** A sign that goes up over a home or building at risk. */
diff --git a/src/content.ts b/src/content.ts
index 940ea29..32c35be 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -388,7 +388,7 @@ export const home = {
half: 5,
cost: { coins: 10, materials: { planks: 1 } } as Kind["cost"],
tiers: {
- 1: { title: "settlers", residents: 4, tax: 3, height: 14, needs: ["food"], appeal: -100 },
+ 1: { title: "settlers", residents: 4, tax: 2.5, height: 14, needs: ["food"], appeal: -100 },
2: { title: "citizens", residents: 8, tax: 5, height: 26, needs: ["bread", "cloth", "faith"], appeal: 5 },
3: { title: "burghers", residents: 12, tax: 6.5, height: 38, needs: ["bread", "cloth", "faith"], appeal: 15 }
} as Readonly<Record<Tier, {
@@ -404,9 +404,18 @@ export const home = {
settle: ticks(3),
/** How long each need stays met after a walker's visit: cloth and faith last longer than a meal. */
lasts: { food: ticks(90), bread: ticks(120), cloth: ticks(240), faith: ticks(180) } as Readonly<Record<Need, number>>,
- /** Where nobody wants to live: homes at this desirability or less hold `crowded` as many. */
+ /** Where nobody wants to live: the desirability the map's legend calls squalid. */
squalid: -5,
- crowded: 0.6
+ /**
+ * What a street does to a home, point by point of desirability (see
+ * `streetRoom` and `streetTax`): a home holds (1 + d / `room`) of its
+ * residents, never fewer than `roomLeast`; and pays (1 + d / `tax`),
+ * within `taxMost` either way. So a cottage beside a quarry empties a
+ * little and pays less, long before anything is squalid.
+ */
+ street: { room: 12, roomLeast: 0.5, tax: 40, taxMost: 0.25 },
+ /** A settlers' cottage with bread on the table pays this much more: bread is worth baking before anyone is a citizen. */
+ breadBonus: 0.5
}
/** What a tier's homes are called, and what its residents are. */
@@ -444,6 +453,8 @@ export const appeal = {
/** Paving a road cell: coins and stone, the stone taken from storage at once. */
export const PAVE_COST = { coins: 3, stone: 1 }
+/** Carriers and walkers move this much faster along a paved street (see `Walk`). */
+export const PAVED_PACE = 1.5
// ── Risks ─────────────────────────────────────────────────────────────────
@@ -455,7 +466,8 @@ export const PAVE_COST = { coins: 3, stone: 1 }
*/
export const RISK_MAX = 10_000
export const risk = {
- warn: 7000,
+ /** Past this, a sign goes up and the map views turn red: half way, so there is time to act. */
+ warn: 5000,
/** The three services' walkers keep a burghers' home: its meters must stay under this. */
kept: 5000,
/** Each home and building rises at its own pace, between these shares of the usual (fixed by where it stands), so a street does not all go up at once. */
@@ -641,7 +653,7 @@ export const WINTER_WARNING = ticks(60)
* (homes / `growth`) a home, so a large town of poor homes cannot pay
* its way.
*/
-export const admin = { perHome: 0.4, growth: 200 }
+export const admin = { perHome: 0.4, growth: 120 }
/**
* Approval, -100 → +100: where the town's mood is heading, and how fast it
@@ -658,7 +670,15 @@ export const mood = {
/** Per unanswered crown request, while the crown remembers it. */
snub: -20,
winterHunger: -10,
- step: 2
+ step: 2,
+ /**
+ * A grudge: taxes above `above` percent are remembered. Every collection
+ * adds (rate − above) × `perPoint` tenths of a point to the town's memory,
+ * up to `most`; at or below it the memory fades by `decay` tenths. The
+ * grudge takes that many points off approval, so a term of 200% cannot be
+ * undone by cutting taxes in the last three minutes.
+ */
+ grudge: { above: 125, perPoint: 0.05, decay: 5, most: 300 }
}
/**
diff --git a/src/factory.css b/src/factory.css
index e5fdd84..8af344b 100644
--- a/src/factory.css
+++ b/src/factory.css
@@ -304,3 +304,37 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
.views button kbd { display: none; }
.legend { top: auto; bottom: calc(176px + env(safe-area-inset-bottom)); }
}
+
+/* ── Descriptions as rows: what, how much, and why underneath ── */
+.panel .lines .line { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 2px 10px; padding: 6px 0; }
+.panel .lines .line + .line { border-top: 1px dashed #e3e6df; }
+.panel .lines .line .label { font-weight: 600; color: #3d4943; flex: none; max-width: 100%; }
+.panel .lines .line .count { text-align: right; white-space: normal; margin-left: auto; line-height: 1.35; }
+.panel .lines .line .chips { flex-basis: 100%; margin-top: 3px; }
+.panel .lines .line .note { flex-basis: 100%; margin-top: 1px; font-size: 11px; line-height: 1.4; color: #6c766f; }
+.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; }
+.panel .lines .line.dim .count, .panel .lines .line.dim .label { color: #8a938c; font-weight: 400; }
+.panel .lines .line .chip { background: #eef0ea; border-radius: 4px; padding: 1px 6px 1px 4px; }
+
+/* ── The build menu: cost and what it does, in labelled rows ── */
+.panel .option { grid-template-rows: auto auto auto auto; }
+.panel .option .thumb { grid-row: span 4; }
+.panel .chips .cap { font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; color: #9aa29b; min-width: 3.2em; }
+.panel .chip.good { color: #4f8a3e; }
+.panel .chip.bad { color: #b04a39; }
+.panel .chip i { font-style: normal; color: #9aa29b; }
+
+/* ── The ticker: now and lately, each line a place to go ── */
+.hud .ticker .head { padding: 5px 12px 1px; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: #9aa29b; }
+.hud .ticker button.cell { font: inherit; color: inherit; background: none; border: 0; text-align: left; cursor: default; width: 100%; }
+.hud .ticker button.cell.place { cursor: pointer; }
+.hud .ticker button.cell.place:hover { background: #eef0ea; }
+.hud .ticker .cell kbd { margin-left: auto; font: inherit; font-size: 10px; color: #3d6db5; border: 1px solid #c9d6ee; border-radius: 3px; padding: 0 5px; }
+.hud .ticker .cell em { font-style: normal; color: #9aa29b; }
+.hud .ticker .cell span { flex: 1; }
+.hud .cell.jobs { cursor: pointer; }
+.hud .cell.jobs:hover { background: #eef0ea; }
diff --git a/src/host.ts b/src/host.ts
index 2d864b9..973fd8d 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -21,6 +21,7 @@ import {
propIds,
props,
PAVE_COST,
+ PAVED_PACE,
tierHome,
winters,
kinds,
@@ -48,7 +49,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 { Stats, Tool, TradeMode, UiValue, View } from "./ui.ts"
+import type { Line, Stats, Tool, TradeMode, UiValue, View } from "./ui.ts"
import { emptyPreview } from "./ui.ts"
import { GameScene } from "./render3d/scene.ts"
import { MapInput } from "./render3d/input.ts"
@@ -86,17 +87,34 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const coins = el("div", "cell coins")
bar.append(clock, coins)
const stock = el("div", "card stock")
+ /** What each good is for, for the stock bar's tooltips: who makes it, who takes it. */
+ const goodHelp: Readonly<Record<GoodId, string>> = {
+ wood: "lumberjacks fell it; a sawmill saws it into planks",
+ planks: "what homes and buildings are built from: a sawmill makes them from wood",
+ stone: "for building and paving: quarries cut it from rocks, which run out",
+ ore: "mines dig it; a smithy forges it into tools",
+ tools: "for building, and workshops wear one out every 50 or 60 jobs: a smithy forges them, or buy them",
+ fish: "food for settlers: fisheries catch it by the water; it rots in about three minutes",
+ smoked: "fish that keeps all winter: a smokehouse smokes it",
+ wheat: "farms grow it; a mill grinds it into flour (not in winter)",
+ flour: "a mill's; a bakery bakes it into bread",
+ bread: "food that citizens need, and a cottage with bread pays half again: it rots in about five minutes",
+ wool: "sheep farms shear it; a weaver weaves it into cloth",
+ cloth: "citizens need it: only brought to streets with desirability 5 or more"
+ }
const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [
- ["wood", "planks", "stone", "tools"],
- ["fish", "smoked", "bread"],
+ ["wood", "planks", "stone", "ore", "tools"],
+ ["fish", "smoked", "wheat", "flour", "bread"],
["wool", "cloth"]
]
+ stock.title = "Goods in the town's storage · hover one for what it is for"
const goodCells = new Map<GoodId, HTMLElement>()
for (const group of groups) {
const cell = el("div", "group")
for (const g of group) {
const item = el("span", "good")
- item.title = goods[g].title
+ item.title = `${goods[g].title}: ${goodHelp[g]}`
+ item.setAttribute("aria-label", goods[g].title)
const glyph = el("span", "glyph")
glyph.innerHTML = goodIcon(g, 18)
const count = el("span", "count", "0")
@@ -124,11 +142,30 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const approval = el("div", "cell")
const settlerCell = el("div", "cell")
const citizenCell = el("div", "cell")
- const jobs = el("div", "cell")
+ const jobs = el("div", "cell jobs")
folk.append(approval, settlerCell, citizenCell, jobs)
people.append(folk)
people.title = "Open the town's numbers, goals, and levers (T)"
people.onclick = () => toggleMenu("town")
+ /** Points the page at a place: the camera goes there, it is outlined for a moment, and (when it is a thing) it is selected. */
+ const goTo = (at: { readonly x: number; readonly y: number }, size: number, id: number | null) => {
+ stage.focus(at.x + size / 2, at.y + size / 2)
+ ui.flash = { cell: { x: at.x, y: at.y }, size, until: Date.now() + 4000 }
+ if (id !== null) {
+ ui.selected = id
+ ui.menu = null
+ refreshTools()
+ }
+ }
+ let shortCursor = 0
+ jobs.onclick = (event) => {
+ event.stopPropagation()
+ const short = ui.stats?.shortStaffed ?? []
+ if (short.length === 0) return toggleMenu("town")
+ const next = short[shortCursor % short.length]!
+ shortCursor += 1
+ goTo(next.cell, next.size, next.id)
+ }
const tooltip = el("div", "tooltip")
const toastBox = el("div", "toast")
const toolbar = el("div", "toolbar")
@@ -166,7 +203,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
founding: true,
view: "none",
overlay: { key: "", cells: [] },
+ tints: new Map(),
legend: null,
+ flash: null,
toast: (message) => {
toastBox.textContent = message
toastBox.classList.add("show")
@@ -195,7 +234,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
label: "pave",
key: "P",
icon: "pave",
- tip: `Drag along a road to pave it: nicer to live beside · ${PAVE_COST.coins} coins and ${PAVE_COST.stone} stone a cell`
+ tip: `Drag along a road to pave it: carriers and walkers go ${PAVED_PACE}× as fast on it, and homes beside it like it · ${PAVE_COST.coins} coins and ${PAVE_COST.stone} stone a cell`
},
{ tool: "home", label: "homes", key: "H", icon: "homes", tip: `Drag to lay a row of homes along a road · ${costText(home.cost)} each` },
{ tool: "build", label: "build", key: "B", icon: "build", tip: "Choose a building, then click to place it · Esc to stop" },
@@ -538,12 +577,21 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const kind = kinds[id]
const option = el("button", "option")
const cost = costChips(kind.cost)
+ cost.box.prepend(el("span", "cap", "cost"))
const terms = el("span", "chips")
- terms.innerHTML = `${kind.workers > 0 ? `<span class="chip dim" title="workers: ${kind.crew}">${icon(kind.crew === "citizens" ? "citizens" : "settlers", 14)}${kind.workers}</span>` : ""}${kind.appeal ? `<span class="chip dim" title="desirability around it">${icon("appeal", 14)}${kind.appeal.value > 0 ? "+" : ""}${kind.appeal.value}</span>` : ""}<span class="chip dim" title="upkeep, coins a minute">${icon("upkeep", 14)}${kind.upkeep}/min</span>`
+ const r = kind.recipe
+ const does = [
+ r ? `<span class="chip" title="${r.input ? `turns ${r.inputs} ${goods[r.input].title} into ${r.batch} ${goods[r.output].title}` : `makes ${r.batch} ${goods[r.output].title}`} every ${r.seconds} s">${r.input ? `${goodIcon(r.input, 14)}<i>→</i>` : ""}${goodIcon(r.output, 14)}${r.batch > 1 ? r.batch : ""}</span>` : "",
+ kind.service ? `<span class="chip" title="its walkers serve the homes within ${kind.service.range} road cells of its door">${icon(kind.service.service === "goods" ? "trade" : kind.service.service === "faith" ? "faith" : kind.service.service === "repair" ? "repair" : kind.service.service, 14)}${kind.service.range}</span>` : "",
+ kind.holds && !kind.recipe && !kind.service ? `<span class="chip" title="holds up to ${kind.holds.cap} of each good${kind.keeps ? `, and keeps food ${kind.keeps} times as long` : ""}">${icon("jobs", 14)}${kind.holds.cap}</span>` : "",
+ kind.workers > 0 ? `<span class="chip dim" title="${kind.workers} ${kind.crew} to work it, from homes within 15 road cells">${icon(kind.crew === "citizens" ? "citizens" : "settlers", 14)}${kind.workers}</span>` : "",
+ kind.appeal ? `<span class="chip ${kind.appeal.value < 0 ? "bad" : "good"}" title="desirability ${kind.appeal.value > 0 ? "+" : ""}${kind.appeal.value} beside it, out to ${kind.appeal.reach} cells${kind.appeal.value < 0 ? ": keep homes away" : ": homes like it"}">${icon("appeal", 14)}${kind.appeal.value > 0 ? "+" : ""}${kind.appeal.value}</span>` : "",
+ `<span class="chip dim" title="upkeep: coins a minute while it stands (a quarter when paused)">${icon("upkeep", 14)}${kind.upkeep}/min</span>`
+ ].join("")
+ terms.innerHTML = `<span class="cap">does</span>${does}`
const blurb = el("span", "blurb", kind.blurb)
- option.append(picture(id), el("span", "name", kind.title.toLowerCase()), cost.box, blurb)
- option.title = `${kind.title}: ${kind.blurb}${kind.workers > 0 ? ` · ${kind.workers} ${kind.crew === "citizens" ? "citizen" : "settler"} workers` : ""}${kind.appeal ? ` · desirability ${kind.appeal.value > 0 ? "+" : ""}${kind.appeal.value} out to ${kind.appeal.reach} cells` : ""} · ${kind.upkeep} coins a minute`
- cost.box.append(terms)
+ option.append(picture(id), el("span", "name", kind.title.toLowerCase()), cost.box, terms, blurb)
+ option.title = `${kind.title}: ${kind.blurb}${kind.workers > 0 ? ` · ${kind.workers} ${kind.crew === "citizens" ? "citizen" : "settler"} workers from within 15 road cells` : ""}${kind.service ? ` · walkers reach ${kind.service.range} road cells` : ""}${kind.appeal ? ` · desirability ${kind.appeal.value > 0 ? "+" : ""}${kind.appeal.value} out to ${kind.appeal.reach} cells` : ""} · ${kind.upkeep} coins a minute`
option.onclick = () => place(id)
live.push(() => {
const lock = lockText(kind)
@@ -572,12 +620,12 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
if (!ground && id === "lamp") parks.append(el("p", "empty", "furnishings · click a cell of park"))
const option = el("button", "option")
const cost = costChips(piece.cost)
+ cost.box.prepend(el("span", "cap", "cost"))
const terms = el("span", "chips")
- terms.innerHTML = `<span class="chip dim" title="beauty it adds to its park">${icon("appeal", 14)}+${piece.beauty}</span><span class="chip dim" title="upkeep, coins a minute">${icon("upkeep", 14)}${piece.upkeep}/min</span>`
+ terms.innerHTML = `<span class="cap">does</span><span class="chip good" title="beauty it adds to its park">${icon("appeal", 14)}+${piece.beauty}</span><span class="chip dim" title="upkeep, coins a minute">${icon("upkeep", 14)}${piece.upkeep}/min</span>`
const blurb = el("span", "blurb", piece.blurb)
- option.append(picture(`park:${id}`), el("span", "name", piece.title.toLowerCase()), cost.box, blurb)
+ option.append(picture(`park:${id}`), el("span", "name", piece.title.toLowerCase()), cost.box, terms, blurb)
option.title = `${piece.title}: ${piece.blurb} · beauty +${piece.beauty}${ground ? " a cell" : ""} · ${piece.upkeep} coins a minute`
- cost.box.append(terms)
option.onclick = pick
live.push(() => {
const lock = lockText(piece)
@@ -637,9 +685,13 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const treasury = section(
"treasury",
"treasury",
- "Coins a minute. Administration grows faster than the town. Three minutes in debt and the town is bankrupt."
+ "Coins a minute. Taxes come only from homes that are fed, in proportion to the needs they have met. Administration grows faster than the town. Three minutes in debt and the town is bankrupt."
)
const taxes = row(treasury, "taxes", "taxes")
+ const supplied = row(treasury, "if every home were supplied", "homes")
+ supplied.classList.add("dim")
+ const suppliedNote = el("p", "empty")
+ treasury.append(suppliedNote)
const traded = row(treasury, "trade", "trade")
const upkeep = row(treasury, "upkeep", "upkeep")
const admin = row(treasury, "administration", "town")
@@ -652,7 +704,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const levers = section(
"tax rates",
"taxes",
- "Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are."
+ `Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are. Above ${moodRules.grudge.above}% the town also keeps a grudge that outlasts the rate: cutting taxes at the end does not undo a term of squeezing.`
)
for (const tier of ["settlers", "citizens"] as const) {
const line = el("div", "row lever")
@@ -679,7 +731,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const rate = ui.stats?.policy[tier] ?? 100
value.textContent = `${rate}%`
const sway = Math.round((100 - rate) * moodRules.perTaxPoint)
- effect.textContent = sway === 0 ? "the usual rate" : `${signed(sway)} approval`
+ const grudge = rate > moodRules.grudge.above ? " · a grudge builds while it stays this high, and fades slowly" : ""
+ effect.textContent = (sway === 0 ? "the usual rate" : `${signed(sway)} approval`) + grudge
effect.className = `effect ${sway > 0 ? "up" : sway < 0 ? "down" : ""}`
})
}
@@ -691,6 +744,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const burghers = row(town, "of them, burghers", "burghers")
const homes = row(town, "homes", "homes")
const work = row(town, "jobs filled", "jobs")
+ const workNote = el("p", "empty")
+ town.append(workNote)
const peopleLine = el("div", "spark")
town.append(peopleLine)
panel.append(town)
@@ -698,7 +753,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const needs = section(
"homes supplied",
"homes",
- "Settlers need food (fish, smoked fish, or bread) from a market; citizens and burghers need bread, cloth, and faith. Fish rots in about three minutes and bread in five; a granary keeps them five times as long."
+ "A hungry home pays no taxes. Settlers need food (fish, smoked fish, or bread) from a market, and a cottage with bread besides pays half again; citizens and burghers need bread, cloth, and faith. Cloth is only brought to streets with desirability 5 or more. Fish rots in about three minutes and bread in five; a granary keeps them five times as long."
)
const needIcons: Readonly<Record<"food" | "bread" | "cloth" | "faith", IconName>> = {
food: "fish",
@@ -831,6 +886,10 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
moodParts.innerHTML = parts
}
money(taxes, s.taxes)
+ supplied.textContent = `+${s.suppliedTaxes}`
+ const gap = s.suppliedTaxes - s.taxes
+ suppliedNote.textContent = gap > Math.max(10, s.taxes * 0.1) ? `${gap} coins a minute left on the table: a hungry home pays nothing, a cottage with bread pays half again, a fine street a quarter more` : ""
+ suppliedNote.style.display = suppliedNote.textContent ? "" : "none"
money(traded, s.trade)
money(upkeep, -s.upkeep)
money(admin, -s.admin)
@@ -840,6 +899,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
burghers.textContent = String(s.burghers)
homes.textContent = String(s.homes)
work.textContent = `${s.employed} of ${s.jobs}`
+ workNote.textContent = s.shortStaffed.length === 0
+ ? "every workplace has its crew"
+ : `${s.shortStaffed.length} short of workers: ${s.shortStaffed.slice(0, 4).map((w) => `${w.title} ${w.assigned}/${w.needed}${w.nobodyNear ? " (nobody within reach)" : ""}`).join(", ")}${s.shortStaffed.length > 4 ? ", …" : ""} · click the jobs counter to visit them`
for (const b of bars) {
const share = s.homes > 0 ? s.needs[b.n] / s.homes : 0
b.fill.style.width = `${Math.round(share * 100)}%`
@@ -888,28 +950,30 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
})
}
- /** An icon for a line of a building's or home's description, by what it is about. */
- const lineIcon = (text: string): IconName | GoodId => {
- if (text.startsWith("workers")) return "workers"
- if (text.startsWith("settlers within")) return "settlers"
- if (text.startsWith("citizens within")) return "citizens"
- if (text.startsWith("desirability")) return "appeal"
- if (text.startsWith("fire")) return "fire"
- if (text.startsWith("condition")) return "condition"
- if (text.startsWith("work:")) return "jobs"
- if (text.startsWith("tools") || text.startsWith("no tools")) return "tools"
- if (text.startsWith("on fire")) return "fire"
- if (text.startsWith("sick")) return "health"
- if (text.startsWith("upkeep")) return "upkeep"
- if (text.startsWith("pays")) return "coins"
- if (text.startsWith("needs")) return "homes"
- if (text.startsWith("to become")) return "citizens"
- if (text.startsWith("waiting")) return "planks"
- if (text.includes("residents")) return "people"
- if (text.includes("out on the roads")) return "settlers"
- if (text.startsWith("holds")) return "jobs"
- const made = goodIds.find((g) => text.includes(`${goods[g].title} ·`))
- return made ?? "info"
+ /** 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) => {
+ 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="label">${icon(l.icon, 16)}<span class="what"></span></span><span class="count"></span>${chips}${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
+ }
+ /** 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>) => {
+ while (rows.length < lines.length) {
+ const line = el("div", "line")
+ rows.push(line)
+ box.append(line)
+ }
+ rows.forEach((row, i) => {
+ const l = lines[i]
+ const text = l ? JSON.stringify(l) : ""
+ if (row.dataset.text === text) return
+ row.dataset.text = text
+ row.style.display = l ? "" : "none"
+ if (l) renderLine(row, l)
+ })
}
const buildPanel = () => {
@@ -944,6 +1008,15 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
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)
+ }
live.push(() => {
const now = ui.panel
if (!now || now.type === "build" || now.type === "town" || now.type !== p.type) return
@@ -960,18 +1033,13 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
status.textContent = now.cause
status.className = "pill problem"
}
- while (rows.length < now.lines.length) {
- const line = el("div", "row")
- rows.push(line)
- box.append(line)
+ syncLines(box, rows, now.lines)
+ if (nextBox && now.type === "house") {
+ 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)
}
- rows.forEach((row, i) => {
- const text = now.lines[i] ?? ""
- if (row.dataset.text === text) return
- row.dataset.text = text
- row.innerHTML = `<span class="label">${icon(lineIcon(text), 16)}<span></span></span>`
- row.querySelector(".label > span")!.textContent = text
- })
})
if (!(p.type === "building" && p.kind === "townhall")) {
const actions = el("div", "actions")
@@ -1301,7 +1369,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
approval.innerHTML = `${icon("approval", 18)}<span class="stack"><b class="${s.mood.approval < 0 ? "down" : ""}">${signed(s.mood.approval)} <span class="${s.mood.target >= s.mood.approval ? "up" : "down"}">${trend}</span></b><small>approval</small></span>`
settlerCell.innerHTML = `${icon("settlers", 18)}<span class="stack"><b>${s.settlers}</b><small>settlers</small></span>`
citizenCell.innerHTML = `${icon("citizens", 18)}<span class="stack"><b>${s.citizens}</b><small>citizens${s.burghers > 0 ? ` · ${s.burghers} burghers` : ""}</small></span>`
- jobs.innerHTML = `${icon("jobs", 18)}<span class="stack"><b>${s.employed}<span class="of">/${s.jobs}</span></b><small>jobs</small></span>`
+ const short = s.shortStaffed.length
+ jobs.innerHTML = `${icon("jobs", 18)}<span class="stack"><b>${s.employed}<span class="of">/${s.jobs}</span></b><small class="${short > 0 ? "down" : ""}">${short > 0 ? `${short} short · click` : "jobs filled"}</small></span>`
+ jobs.title = short > 0
+ ? `Workers at work over workers needed. ${short} workplace${short > 1 ? "s are" : " is"} short: ${s.shortStaffed.slice(0, 5).map((w) => `${w.title} ${w.assigned}/${w.needed}${w.nobodyNear ? " (no homes within 15 road cells)" : ""}`).join(", ")}. Click to visit them in turn.`
+ : "Workers at work over workers needed: every workplace has its crew. Residents walk at most 15 road cells to work."
for (const [g, count] of goodCells) {
count.textContent = String(s.stock[g])
count.parentElement!.classList.toggle("empty", s.stock[g] === 0)
@@ -1336,16 +1408,32 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
alarm.classList.toggle("show", warnings.length > 0)
alarm.classList.toggle("good", warnings.length === 1 && s.fate.complete !== null)
- // The ticker: alerts now, and the news of the last minute and a half.
+ // The ticker: what needs looking at now, then the news of the last minute and a half; click a line to go there.
const minute = Math.round(s.minute * 3600)
const news = s.chronicle.filter((l) => l.alarm && minute - l.tick < 90 * 60).slice(-3).reverse()
+ const ago = (tick: number) => {
+ const sec = Math.max(0, Math.round((minute - tick) / 60))
+ return sec < 5 ? "just now" : sec < 60 ? `${sec} s ago` : `${Math.round(sec / 60)} min ago`
+ }
const tickerHtml = [
- ...s.alerts.map((a) => `<div class="cell">${icon("warning", 14)}<span>${a}</span></div>`),
- ...news.map((l) => `<div class="cell news">${icon("chronicle", 14)}<span>${l.text}</span></div>`)
+ ...(s.alerts.length > 0 ? [`<div class="head">now</div>`] : []),
+ ...s.alerts.map((a, i) => `<button class="cell${a.at ? " place" : ""}" data-alert="${i}" title="${a.at ? "Click to go there" : ""}">${icon("warning", 14)}<span>${a.text}</span>${a.at ? `<kbd>go</kbd>` : ""}</button>`),
+ ...(news.length > 0 ? [`<div class="head">lately</div>`] : []),
+ ...news.map((l, i) => `<button class="cell news${l.at ? " place" : ""}" data-news="${i}" title="${l.at ? "Click to go there" : ""}">${icon("chronicle", 14)}<span>${l.text} <em>${ago(l.tick)}</em></span>${l.at ? `<kbd>go</kbd>` : ""}</button>`)
].join("")
if (ticker.dataset.html !== tickerHtml) {
ticker.dataset.html = tickerHtml
ticker.innerHTML = tickerHtml
+ for (const b of ticker.querySelectorAll<HTMLButtonElement>("button.place")) {
+ b.onclick = (event) => {
+ event.stopPropagation()
+ const alertIndex = b.dataset.alert
+ const target = alertIndex !== undefined ? s.alerts[Number(alertIndex)] : null
+ if (target?.at) return goTo(target.at, target.size, target.id)
+ const line = news[Number(b.dataset.news)]
+ if (line?.at) goTo(line.at, 1, null)
+ }
+ }
}
ticker.classList.toggle("show", tickerHtml !== "" && s.fate.state === "playing")
// News as it happens: a toast for each new alarm line.
diff --git a/src/present.ts b/src/present.ts
index 2a80f1e..e6804ec 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -13,9 +13,9 @@ import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, Rui
import type { DoorSet, OverlayCell } from "./render3d/models.ts"
import {
BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,
- propIds, props, risk, RISK_MAX, tierHome, total, winters, type Kind, type Tier
+ PAVE_COST, propIds, props, risk, RISK_MAX, ROAD_COST, tierHome, total, winters, type GoodId, type Kind, type Tier
} from "./content.ts"
-import { around, canPlace, doors, entrances, isRoad, key, lPath, reach, useAt, type TileLike } from "./grid.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"
import {
Appeal,
@@ -80,9 +80,12 @@ import {
type GridValue,
type Status as StatusValue
} from "./schema.ts"
-import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, taxOf, termTicks, winterOf } from "./sim/index.ts"
+import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, steadyNet, taxOf, termTicks, winterOf } from "./sim/index.ts"
import { Townsfolk } from "./townsfolk.ts"
-import { emptyPreview, type HitBox, type Legend, type View } from "./ui.ts"
+import { emptyPreview, type Alert as Notice, type HitBox, type Legend, type Line, type View } from "./ui.ts"
+import { blockers as blockersOf, streetAdvice, type InTown, type Served, type Street } from "./rules/explain.ts"
+import { breadBonus, streetTax, suppliedTaxOf } from "./rules/households.ts"
+import { ticks } from "./content.ts"
const cellAt = (at: Point): Point => {
return { x: Math.floor(at.x), y: Math.floor(at.y) }
@@ -244,11 +247,11 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {
keys: [
{ color: 0x2f7a43, label: `${home.tiers[3].appeal}+: townhouses` },
{ color: GOOD, label: `${home.tiers[2].appeal}+: citizens` },
- { color: 0xc9d6a0, label: "0 to 4" },
- { color: 0xe0a060, label: "below 0" },
+ { color: 0xc9d6a0, label: "0 to 4: settlers only" },
+ { color: 0xe0a060, label: "below 0: fewer people, less tax" },
{ color: BAD, label: `${home.squalid} or less: squalid` }
],
- note: "Industry pushes homes away; parks (the more they hold, the further they reach), a chapel, and paved streets draw them in."
+ note: "Every point counts: a cottage holds fewer and pays less for each point below 0, and pays more above it. Industry pushes homes away; parks (the more they hold, the further they reach), a chapel, a market, and paved streets draw them in."
},
workers: {
title: "workers",
@@ -268,7 +271,7 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {
{ color: FAIR, label: "rising" },
{ color: BAD, label: "at risk, or burning" }
],
- note: "A fire watch's watchman resets the risk of every home and workshop along the way. Wooden cottages, ovens, forges, and crowding raise it."
+ note: "Buildings take the colour too. A fire watch's watchman resets the risk of every home and workshop along the way; red means past half way, so there is time. Wooden cottages, ovens, forges, and crowding raise it."
},
health: {
title: "health",
@@ -299,6 +302,13 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {
}
}
+/** When each workshop began waiting for its input: a shelf runs empty for a moment all the time, so the ticker only says so after `ALERT_PATIENCE`. */
+const starvedSince = new Map<number, number>()
+const ALERT_PATIENCE = ticks(30)
+/** A view's colour over a model: pale, so the ink still reads. */
+const TINT = { good: 0xb6dcc0, fair: 0xf0dea4, bad: 0xefb0a4, cool: 0xb7cdef, settlers: 0xead7bd, fine: 0x9fd0ad, plain: 0xffffff }
+const needIcons = { food: "food", bread: "bread", cloth: "cloth", faith: "faith" } as const
+
const appealColor = (v: number) =>
v >= home.tiers[3].appeal ? 0x2f7a43 : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc9d6a0 : v > home.squalid ? 0xe0a060 : BAD
@@ -340,6 +350,7 @@ export const Interact = Game.System(
const rates = resources.policy.get()
const approval = resources.mood.get().approval
const cells = resources.appeal.get().cells
+ const tick = resources.time.get().tick
const buildings = queries.buildings.each()
const houses = queries.houses.each()
const ruins = queries.ruins.each()
@@ -363,18 +374,21 @@ export const Interact = Game.System(
return [{ x: x - p.reach, y: y - p.reach, size: size + 2 * p.reach, look: "reach" as const }]
}
/** A park, for its panel: what it is worth, why, and what would make it better. */
- const describePark = (p: ParkValue) => {
+ const describePark = (p: ParkValue): Array<Line> => {
const has = new Set(p.cells.map((c) => c.prop))
const missing = propIds.filter((id) => !has.has(id)).map((id) => props[id].title.toLowerCase())
const upkeep = p.cells.reduce((n, c) => n + grounds[c.ground].upkeep + (c.prop === "none" ? 0 : props[c.prop].upkeep), 0)
+ const placed = p.cells.filter((c) => c.prop !== "none").length - p.crowded
return [
- `${p.cells.length} cell${p.cells.length === 1 ? "" : "s"} · beauty ${p.beauty}`,
- `made of: ${p.parts.map((part) => `${part.label} ${part.value}`).join(", ") || "nothing yet"}`,
- parkText(p),
- p.entrances > 0 ? `ways in from the street: ${p.entrances}${p.entrances > 2 ? " (2 count)" : ""}` : "no way in: lay a walk or a square out to a road for +1.5 (two count)",
- `one furnishing counts for every 2 cells: ${p.cells.filter((c) => c.prop !== "none").length - p.crowded} of ${Math.ceil(p.cells.length / 2)}${p.crowded > 0 ? ` (${p.crowded} too many)` : ""}`,
- ...(missing.length > 0 ? [`nicer with: ${missing.join(", ")}`] : []),
- `upkeep ${Math.round(upkeep * 10) / 10} coins a minute`
+ { icon: "decor", label: "size", value: `${p.cells.length} cell${p.cells.length === 1 ? "" : "s"} · beauty ${p.beauty}` },
+ { icon: "appeal", label: "made of", value: p.parts.map((part) => `${part.label} ${part.value}`).join(", ") || "nothing yet" },
+ { icon: "homes", label: "the streets around", value: parkText(p), tone: "ok" },
+ p.entrances > 0
+ ? { icon: "road", label: "ways in from the street", value: `${p.entrances}${p.entrances > 2 ? " (2 count)" : ""}` }
+ : { icon: "road", label: "ways in from the street", value: "none", tone: "warn", note: "lay a gravel walk or a paved square out to a road: +1.5 each, two count" },
+ { icon: "decor", label: "furnishings that count", value: `${placed} of ${Math.ceil(p.cells.length / 2)}`, tone: p.crowded > 0 ? "warn" : undefined, note: p.crowded > 0 ? `${p.crowded} too many: one counts for every 2 cells, so lay more ground` : undefined },
+ ...(missing.length > 0 ? [{ icon: "info", label: "nicer with", value: missing.join(", "), tone: "dim" } as Line] : []),
+ { icon: "upkeep", label: "upkeep", value: `${Math.round(upkeep * 10) / 10} coins a minute` }
]
}
/** What the pointer is on: the model the camera ray hit, or else (parks have nothing standing to hit) the park on the cell. */
@@ -455,6 +469,26 @@ export const Interact = Game.System(
if (r !== null) preview.plots.push({ x: tile.x - r, y: tile.y - r, size: tile.size + 2 * r, look: "reach" })
}
const pavedCells = new Set(queries.paved.each().map(({ data }) => key(data.tile.get().x, data.tile.get().y)))
+ /** The road cells within `limit` of a tile's doors: what a service's walkers, or a commute, would reach from here. */
+ const rangeFrom = (tile: TileLike, limit: number, note: string) => {
+ const ds = doors(grid, tile)
+ if (ds.length === 0) return
+ const roads = reach(grid, ds)
+ for (let k = 0; k < roads.distance.length; k++) {
+ const d = roads.distance[k]!
+ if (d >= 0 && d < limit) preview.range.push(cellOf(k))
+ }
+ preview.rangeNote = note
+ }
+ const rangeOfKind = (tile: TileLike, kind: Kind) => {
+ if (kind.service) rangeFrom(tile, kind.service.range, `its walkers reach ${kind.service.range} road cells from the door`)
+ else if (kind.workers > 0) rangeFrom(tile, COMMUTE + 1, `its workers come from homes within ${COMMUTE} road cells`)
+ }
+ // Where the page is pointing (from the ticker): outlined for a few seconds.
+ if (ui.flash) {
+ if (Date.now() < ui.flash.until) preview.plots.push({ x: ui.flash.cell.x, y: ui.flash.cell.y, size: ui.flash.size, look: "picked" })
+ else ui.flash = null
+ }
if (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave") {
const cells = cell === null ? [] : ui.dragFrom ? lPath(ui.dragFrom, cell) : [cell]
@@ -471,6 +505,11 @@ export const Interact = Game.System(
} else if (free) preview.ghosts.push({ what: "home", cell: c })
else preview.plots.push({ ...c, size: 1, look: "blocked" })
}
+ 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 · ${preview.rangeNote ?? "touch a road and residents walk to work within " + COMMUTE + " road cells"}`
+ }
+ if (ui.tool === "road" && cell) preview.tooltip = `road · ${ROAD_COST} coins a cell · buildings need one at the middle of a side`
} else if (ui.tool === "ground" && cell) {
const laid: Array<ParkCell> = []
for (const c of ui.dragFrom ? rectangle(ui.dragFrom, cell) : [cell]) {
@@ -504,7 +543,8 @@ export const Interact = Game.System(
const at = footprintAt(pointer, kind.size)
const tile = { ...at, size: kind.size }
showReach(tile, kind)
- if (kind.appeal && kind.appeal.value > 0) preview.plots.push({ x: tile.x - kind.appeal.reach, y: tile.y - kind.appeal.reach, size: tile.size + 2 * kind.appeal.reach, look: "reach" })
+ 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 (canPlace(grid, tile)) preview.ghosts.push({ what: ui.placing, cell: at })
else preview.plots.push({ ...tile, look: "blocked" })
} else if (ui.tool === "bulldoze") {
@@ -523,7 +563,10 @@ export const Interact = Game.System(
for (const c of whole.cells) preview.plots.push({ x: c.x, y: c.y, size: 1, look: "hover" })
preview.plots.push(...reachPlots(whole))
} else if (tile) preview.plots.push({ ...tile, look: "picked" })
- if (row && tile) showReach(tile, kinds[row.data.building.get().kind])
+ if (row && tile) {
+ showReach(tile, kinds[row.data.building.get().kind])
+ rangeOfKind(tile, kinds[row.data.building.get().kind])
+ }
}
// ── The neighbourhood, explained (only when a home asks) ──
@@ -567,69 +610,233 @@ export const Interact = Game.System(
const kind = kinds[row.data.building.get().kind]
const status = row.data.status.get()
const site = maybe(row.data.site)
- const lines: Array<string> = []
+ const lines: Array<Line> = []
if (site) {
- const owed = Object.entries(site.owed)
- .filter(([, n]) => n > 0)
- .map(([g, n]) => `${n} ${g}`)
- lines.push(owed.length > 0 ? `waiting for ${owed.join(", ")}` : "going up")
+ const owed = (Object.entries(site.owed) as Array<[GoodId, number]>).filter(([, n]) => n > 0)
+ lines.push(
+ 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 }
}
const staff = row.data.staff.get()
if (staff.needed > 0) {
- lines.push(`workers ${staff.assigned} of ${staff.needed}${staff.apprentices > 0 ? ` (${staff.apprentices} settler apprentice${staff.apprentices > 1 ? "s" : ""}: slower)` : ""}`)
- lines.push(`${kind.crew} within ${COMMUTE} cells: ${staff.nearby}`)
+ const crew = kind.crew
+ const one = crew === "citizens" ? "citizen" : "settler"
+ const short = staff.assigned < staff.needed
+ lines.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`
+ : staff.apprentices > 0
+ ? `${staff.apprentices} settler apprentice${staff.apprentices > 1 ? "s" : ""} 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` : ""}`
+ })
+ 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(
- `${recipe.input ? `${recipe.inputs} ${recipe.input} → ` : ""}${recipe.batch} ${goods[recipe.output].title} · ${recipe.made} made`
+ 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" }
)
- if (inventory && !maybe(row.data.hall)) {
- const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => `${inventory.stock[g]} ${goods[g].title}`)
- lines.push(held.length > 0 ? `holds ${held.join(", ")}` : "holds nothing yet")
}
- if (kind.wear && inventory) lines.push(inventory.stock.tools > 0 ? `tools on hand ${inventory.stock.tools} · one wears out every ${kind.wear} jobs` : "no tools: half pace until a carrier brings one")
+ if (kind.wear && inventory)
+ lines.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" }
+ )
const condition = maybe(row.data.condition)
- if (condition) lines.push(`condition ${percent(condition.value, CONDITION_MAX)}${condition.value < wear.worn ? ": run down, half pace" : condition.value < wear.mend ? ": a builder would mend it" : ""}`)
+ if (condition)
+ lines.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"
+ })
const r = maybe(row.data.risk)
- if (r) lines.push(`fire risk ${riskText(r.fire)}${kind.hot ? " · an oven or a forge" : ""}`)
- if (kind.appeal) lines.push(`desirability ${signed(kind.appeal.value)} beside it, out to ${kind.appeal.reach} cells`)
+ if (r)
+ lines.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 (walkers > 0) lines.push(`${walkers} out on the roads`)
- if (kind.upkeep > 0) lines.push(`upkeep ${kind.upkeep} coins a minute`)
+ 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`
+ })
+ 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` })
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 }
}
+ /** What the town has of each provision, in storage and on market shelves. */
+ const inTown = (): InTown => {
+ const stock = resources.stock.get()
+ const sum = { fish: stock.fish, smoked: stock.smoked, bread: stock.bread, cloth: stock.cloth }
+ for (const { data } of buildings) {
+ const inv = maybe(data.inventory)
+ if (!inv || maybe(data.service)?.service !== "goods" || data.site.present || data.rising.present) continue
+ sum.fish += inv.stock.fish
+ sum.smoked += inv.stock.smoked
+ sum.bread += inv.stock.bread
+ sum.cloth += inv.stock.cloth
+ }
+ return sum
+ }
+ /** Which services have a walker that can reach a home: a standing market (or the town hall), and a chapel, within their walks of its door. */
+ const servedAt = (tile: TileLike): Served => {
+ const ds = doors(grid, tile)
+ if (ds.length === 0) return { goods: false, faith: false }
+ const way = reach(grid, ds)
+ const served = { goods: false, faith: false }
+ for (const { data } of buildings) {
+ const service = maybe(data.service)
+ if (!service || data.site.present || data.rising.present || data.burning.present) continue
+ if (service.service !== "goods" && service.service !== "faith") continue
+ if (served[service.service]) continue
+ const found = nearest(way, doors(grid, data.tile.get()))
+ if (found && found.distance < service.range) served[service.service] = true
+ }
+ return served
+ }
const describeHouse = (row: (typeof houses)[number]) => {
const h = row.data.house.get()
const site = maybe(row.data.site)
- if (site) return { h, lines: ["waiting for its planks"] }
+ if (site) return { h, lines: [{ icon: "planks", label: "a site", value: "waiting for its plank", tone: "warn" } as Line], blockers: [] as Array<Line> }
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 mark = (n: Parameters<typeof met>[1]) => `${needTitle[n]} ${met(h, n) ? "✓" : "–"}`
const there = appealParts(appealSources(), tile)
const desirability = appealAt(cells, tile.x, tile.y)
+ const street: Street = { desirability, parts: there.parts }
const r = maybe(row.data.risk)
const work = workOf(tile, h.tier)
const condition = maybe(row.data.condition)
- return {
- h,
- lines: [
- ...(row.data.burning.present ? ["on fire: everyone has fled"] : row.data.sick.present ? ["sick: it holds half as many until it passes or a physician calls, and it may spread"] : []),
- `${h.residents} of ${capacity(h, approval, desirability)} residents (${tier.residents} at most)`,
- `needs: ${tier.needs.map(mark).join(" · ")}`,
- ...(next ? [`to become ${next.title}: ${next.needs.map(mark).join(" · ")} · desirability ${next.appeal}${h.tier === 2 ? " · fire, health, and order kept" : ""}`] : []),
- `desirability ${desirability}${there.parts.length > 0 ? ` (${there.parts.slice(0, 5).map((p) => `${p.label} ${signed(p.value)}`).join(", ")})` : ""}`,
- ...(r ? [`fire ${riskText(r.fire)} · health ${riskText(r.health)} · order ${riskText(r.order)}${r.thefts > 0 ? " · robbed" : ""}`] : []),
- ...(condition ? [`condition ${percent(condition.value, CONDITION_MAX)}`] : []),
- work ? `work: ${work.title}, ${work.distance} cells` : `work: none within ${COMMUTE} cells`,
- `pays ${Math.round(taxOf(h, rates))} coins a minute`
- ]
- }
+ const town = inTown()
+ const served = servedAt(tile)
+ const cap = capacity(h, approval, desirability)
+ const whyFewer =
+ cap >= tier.residents
+ ? undefined
+ : row.data.sick.present
+ ? "half as many while it is sick"
+ : approval < 0
+ ? "fewer while the town disapproves of its mayor"
+ : desirability < 0
+ ? `fewer on a street at ${signed(desirability)}: ${streetAdvice(street)}`
+ : "fewer until every need is met"
+ const taxLine = (() => {
+ const factors: Array<string> = []
+ const rate = h.tier === 1 ? rates.settlers : rates.citizens
+ 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]
+ : []),
+ {
+ 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]
+ : []),
+ ...(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
+ } 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 hovered = preview.hover
@@ -654,8 +861,8 @@ export const Interact = Game.System(
const kind = kinds[ui.placing]
const r = reachOf(kind)
const a = kind.appeal
- preview.tooltip = `${kind.title.toLowerCase()}${r !== null ? ` · works ${r} cells around` : ""}${a ? ` · desirability ${signed(a.value)} out to ${a.reach} cells` : ""}`
- } else if (ui.tool === "pave") preview.tooltip = "drag along a road to pave it · 3 coins and a stone a cell"
+ 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") 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 (cell && ui.view === "appeal" && inside(cell.x, cell.y)) preview.tooltip = `desirability ${appealAt(cells, cell.x, cell.y)}`
ui.preview = preview
@@ -679,8 +886,8 @@ export const Interact = Game.System(
paused: pickedBuilding.data.paused.present
}
} else if (pickedHouse) {
- const { h, lines } = describeHouse(pickedHouse)
- ui.panel = { type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines }
+ const { h, lines, blockers } = describeHouse(pickedHouse)
+ ui.panel = { type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines, blockers }
} else if (pickedPark && picked) {
ui.panel = {
type: "park",
@@ -699,8 +906,8 @@ export const Interact = Game.System(
cell: pickedRuin.data.tile.get(),
cause: r.cause,
lines: [
- r.cause === "burnt" ? "burned down" : r.cause === "collapsed" ? "fell down for want of mending" : "left derelict after its thefts",
- `desirability −3 around it until it is cleared`
+ { 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" }
]
}
} else ui.panel = ui.menu ? { type: ui.menu } : null
@@ -714,13 +921,16 @@ export const Interact = Game.System(
// ── Map views ──
const view = ui.view
- const tick = resources.time.get().tick
const overlayKey = `${view}|${Math.floor(tick / 30)}|${ui.selected}|${buildings.length}|${houses.length}`
if (view === "none") {
if (ui.overlay.key !== "none") ui.overlay = { key: "none", cells: [] }
+ if (ui.tints.size > 0) ui.tints = new Map()
ui.legend = null
} else if (ui.overlay.key !== overlayKey) {
const out: Array<OverlayCell> = []
+ // The same reading washed over each model, so the view is legible where buildings hide the ground.
+ const tints = new Map<number, number>()
+ const tintOf = (color: number) => (color === GOOD ? TINT.good : color === FAIR ? TINT.fair : color === BAD ? TINT.bad : color === COOL ? TINT.cool : TINT.plain)
const standing = <T extends { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }>(rows: ReadonlyArray<T>) =>
rows.filter(({ data }) => !data.site.present && !data.rising.present)
if (view === "appeal") {
@@ -730,6 +940,11 @@ export const Interact = Game.System(
if (use === "void" || use === "water") continue
out.push({ x, y, size: 1, color: appealColor(appealAt(cells, x, y)), alpha: 0.32 })
}
+ for (const { entity, data } of standing(houses)) {
+ const t = data.tile.get()
+ const d = appealAt(cells, t.x, t.y)
+ tints.set(entity.id, d >= home.tiers[2].appeal ? TINT.fine : d >= 0 ? TINT.plain : d > home.squalid ? TINT.fair : TINT.bad)
+ }
} else if (view === "workers") {
const picked = pickedBuilding && pickedBuilding.data.staff.get().needed > 0 ? pickedBuilding : undefined
let inReach: ((t: TileLike) => boolean) | null = null
@@ -744,67 +959,121 @@ export const Interact = Game.System(
return n >= 0 && n <= COMMUTE
})
}
- for (const { data } of standing(houses)) {
+ for (const { entity, data } of standing(houses)) {
const t = data.tile.get()
const h = data.house.get()
const ring = inReach !== null && inReach(t)
out.push({ ...t, color: h.tier === 1 ? 0xd6b48a : COOL, alpha: ring ? 0.75 : 0.45, ...(ring ? { ring: true } : {}) })
+ tints.set(entity.id, h.tier === 1 ? TINT.settlers : TINT.cool)
}
for (const { entity, data } of standing(buildings)) {
const s = data.staff.get()
if (s.needed === 0) continue
const color = s.assigned >= s.needed ? GOOD : s.assigned > 0 ? FAIR : BAD
out.push({ ...data.tile.get(), color, alpha: 0.45, ...(entity.id === picked?.entity.id ? { ring: true } : {}) })
+ tints.set(entity.id, tintOf(color))
}
} else if (view === "fire" || view === "health" || view === "order") {
- for (const { data } of standing(houses)) {
+ for (const { entity, data } of standing(houses)) {
const r = maybe(data.risk)
if (!r) continue
const struck = view === "fire" ? data.burning.present : view === "health" ? data.sick.present : r.thefts > 0
- out.push({ ...data.tile.get(), color: struck ? BAD : meterColor(r[view], RISK_MAX, risk.warn), alpha: struck ? 0.8 : 0.5 })
+ const color = struck ? BAD : meterColor(r[view], RISK_MAX, risk.warn)
+ out.push({ ...data.tile.get(), color, alpha: struck ? 0.8 : 0.5 })
+ tints.set(entity.id, tintOf(color))
}
- for (const { data } of standing(buildings)) {
+ for (const { entity, data } of standing(buildings)) {
const service = maybe(data.service)?.service
const r = maybe(data.risk)
- if (service === view) out.push({ ...data.tile.get(), color: COOL, alpha: 0.55, ring: true })
- else if (view === "fire" && r) out.push({ ...data.tile.get(), color: data.burning.present ? BAD : meterColor(r.fire, RISK_MAX, risk.warn), alpha: 0.4 })
+ if (service === view) {
+ out.push({ ...data.tile.get(), color: COOL, alpha: 0.55, ring: true })
+ tints.set(entity.id, TINT.cool)
+ } else if (view === "fire" && r) {
+ const color = data.burning.present ? BAD : meterColor(r.fire, RISK_MAX, risk.warn)
+ out.push({ ...data.tile.get(), color, alpha: 0.4 })
+ tints.set(entity.id, tintOf(color))
+ }
}
} else if (view === "condition") {
for (const row of [...standing(houses), ...standing(buildings)]) {
const c = maybe(row.data.condition)
if (!c) continue
- out.push({ ...row.data.tile.get(), color: c.value < wear.worn ? BAD : c.value < wear.mend ? FAIR : GOOD, alpha: 0.5 })
+ const color = c.value < wear.worn ? BAD : c.value < wear.mend ? FAIR : GOOD
+ out.push({ ...row.data.tile.get(), color, alpha: 0.5 })
+ tints.set(row.entity.id, tintOf(color))
+ }
+ for (const { entity, data } of standing(buildings)) if (maybe(data.service)?.service === "repair") {
+ out.push({ ...data.tile.get(), color: COOL, alpha: 0.55, ring: true })
+ tints.set(entity.id, TINT.cool)
}
- for (const { data } of standing(buildings)) if (maybe(data.service)?.service === "repair") out.push({ ...data.tile.get(), color: COOL, alpha: 0.55, ring: true })
for (const { data } of ruins) out.push({ ...data.tile.get(), color: BAD, alpha: 0.8 })
}
ui.overlay = { key: overlayKey, cells: out }
+ ui.tints = tints
ui.legend = legends[view]
}
// ── What needs looking at ──
- const alerts: Array<string> = []
+ const alerts: Array<Notice> = []
const census = resources.census.get()
const stock = resources.stock.get()
- if (census.burning > 0) alerts.push(`${census.burning} on fire`)
- if (census.sick > 0) alerts.push(`${census.sick} home${census.sick > 1 ? "s" : ""} sick`)
- const waiting = new Map<string, number>()
- const remote = new Map<string, number>()
- for (const { data } of buildings) {
+ const burningRow = [...buildings, ...houses].find(({ data }) => data.burning.present)
+ if (census.burning > 0) alerts.push({ text: `${census.burning} on fire`, 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({ text: `${census.sick} home${census.sick > 1 ? "s" : ""} sick`, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })
+ const waiting = new Map<string, { n: number; at: TileLike; id: number }>()
+ const remote = new Map<string, { n: number; at: TileLike; id: number }>()
+ const shortStaffed: Array<{ id: number; title: string; cell: Point; size: number; assigned: number; needed: number; nobodyNear: boolean }> = []
+ const seen = new Set<number>()
+ for (const { entity, data } of buildings) {
if (data.site.present || data.rising.present || data.paused.present) continue
const kind = kinds[data.building.get().kind]
const status = data.status.get()
- if (status === "starved" && kind.recipe?.input) waiting.set(`${kind.title.toLowerCase()} (${kind.recipe.input})`, (waiting.get(`${kind.title.toLowerCase()} (${kind.recipe.input})`) ?? 0) + 1)
- if (status === "unstaffed" && data.staff.get().nearby === 0) remote.set(kind.title.toLowerCase(), (remote.get(kind.title.toLowerCase()) ?? 0) + 1)
+ const staff = data.staff.get()
+ const tile = data.tile.get()
+ if (status === "starved" && kind.recipe?.input) {
+ seen.add(entity.id)
+ const since = starvedSince.get(entity.id) ?? tick
+ if (!starvedSince.has(entity.id)) starvedSince.set(entity.id, tick)
+ if (tick - since >= ALERT_PATIENCE) {
+ const label = `${kind.title.toLowerCase()} (${kind.recipe.input})`
+ const was = waiting.get(label)
+ waiting.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id })
+ }
+ }
+ if (staff.needed > 0 && staff.assigned < staff.needed) shortStaffed.push({ id: entity.id, title: kind.title.toLowerCase(), cell: tile, size: tile.size, assigned: staff.assigned, needed: staff.needed, nobodyNear: staff.nearby === 0 })
+ if (status === "unstaffed" && staff.nearby === 0) {
+ const label = kind.title.toLowerCase()
+ const was = remote.get(label)
+ remote.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id })
+ }
}
- const list = (m: Map<string, number>) => [...m].map(([k, n]) => `${k}${n > 1 ? ` ×${n}` : ""}`).join(", ")
- if (waiting.size > 0) alerts.push(`waiting for inputs: ${list(waiting)}`)
- if (remote.size > 0) alerts.push(`no workers nearby: ${list(remote)}`)
- if (census.homes > 0 && larder(stock) === 0) alerts.push("no food in store")
+ for (const id of [...starvedSince.keys()]) if (!seen.has(id)) starvedSince.delete(id)
+ const list = (m: Map<string, { n: number }>) => [...m].map(([k, v]) => `${k}${v.n > 1 ? ` ×${v.n}` : ""}`).join(", ")
+ const first = (m: Map<string, { at: TileLike; id: number }>) => [...m.values()][0]
+ if (waiting.size > 0) alerts.push({ text: `waiting for inputs: ${list(waiting)}`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null })
+ if (remote.size > 0) alerts.push({ text: `no workers within ${COMMUTE} road cells: ${list(remote)}`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null })
+ const hallRow = buildings.find(({ data }) => data.hall.present)
+ if (census.homes > 0 && larder(stock) === 0) alerts.push({ text: "no food in store: homes go hungry", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })
+ // A town's first steps, until it has taken them: the ticker is otherwise silent when there is least to go on.
+ const hallAt = { at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: null }
+ const standingKinds = new Set(buildings.filter(({ data }) => !data.site.present && !data.rising.present).map(({ data }) => data.building.get().kind))
+ const placedKinds = new Set(buildings.map(({ data }) => data.building.get().kind))
+ const residents = census.settlers + census.citizens
+ if (census.homes === 0 && houses.length === 0) alerts.push({ text: "first: lay a road out from the town hall (R), then drag a row of homes along it (H); settlers move in on their own", ...hallAt })
+ else if (!placedKinds.has("fishery") && !placedKinds.has("bakery") && residents < 60) alerts.push({ text: "settlers eat: build a fishery (B) within two cells of water, on a road; the town hall's walker hands the fish out", ...hallAt })
+ else if (residents >= 20 && !placedKinds.has("lumberjack") && stock.planks < 20) alerts.push({ text: "planks are running out: a lumberjack by the woods and a sawmill make more; every home and building needs them", ...hallAt })
+ else if (residents >= 40 && !placedKinds.has("market") && standingKinds.has("fishery")) alerts.push({ text: "the town hall's walker only reaches 20 road cells: a market (B) hands out food further along the streets", ...hallAt })
const ledger = resources.ledger.get()
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
+ let suppliedTaxes = 0
+ for (const { data } of houses) {
+ if (data.site.present || data.rising.present || data.burning.present) continue
+ const tile = data.tile.get()
+ suppliedTaxes += suppliedTaxOf(data.house.get(), rates, undefined, appealAt(cells, tile.x, tile.y))
+ }
const coins = resources.treasury.get().coins
const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
const mood = resources.mood.get()
@@ -819,6 +1088,7 @@ export const Interact = Game.System(
ui.stats = {
coins,
taxes: ledger.taxes,
+ suppliedTaxes: Math.round(suppliedTaxes),
trade: ledger.trade,
upkeep: ledger.upkeep,
admin: ledger.admin,
@@ -833,6 +1103,7 @@ export const Interact = Game.System(
burghers: census.burghers,
jobs: census.jobs,
employed: census.employed,
+ shortStaffed,
charter: { size: charter.size, term: charter.term, land: charter.land, seed: charter.seed },
minute: t / 3600,
season: {
@@ -849,7 +1120,8 @@ export const Interact = Game.System(
parts: [
{ label: "mood of the town", value: mood.base },
{ label: "needs met", value: mood.needs },
- { label: "taxes", value: mood.taxes },
+ { label: "taxes now", value: mood.taxes },
+ { label: "a grudge over taxes past", value: mood.grudge },
{ label: "unpaid wages", value: mood.debt },
{ label: "the crown's displeasure", value: mood.crown },
{ label: "a hungry winter", value: mood.winter }
@@ -878,7 +1150,7 @@ export const Interact = Game.System(
complete: danger(f.goalSince, fate.hold),
peak: f.peak
},
- goals: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net, approval: mood.approval }),
+ goals: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net: steadyNet(resources.history.get().samples, net), approval: mood.approval }),
larder: larder(stock),
eaten: pantry.eatenLast,
rotted: pantry.rottedLast,
@@ -1089,6 +1361,7 @@ export const Animate = Game.System(
fireRisk: hazardStrength(r?.fire??0,risk.warn,RISK_MAX)
},
working: status === "working",
+ tint: services.ui.tints.get(entity.id),
problem: problemOf(kind, status) !== null,
build: buildOf(maybe(data.site), maybe(data.rising)),
beat: recipe ? recipe.made : maybe(data.service) ? walkers : 0,
@@ -1121,7 +1394,8 @@ export const Animate = Game.System(
order: hazardStrength(maybe(data.risk)?.order??0,risk.warn,RISK_MAX),
sick: Number(data.sick.present)
},
- band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain"
+ band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain",
+ tint: services.ui.tints.get(entity.id)
},
emphasis(entity.id)
)
diff --git a/src/render3d/models.ts b/src/render3d/models.ts
index aeaa04e..d7a5465 100644
--- a/src/render3d/models.ts
+++ b/src/render3d/models.ts
@@ -292,6 +292,8 @@ export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<numbe
}
export function previewAsset(preview: Preview, time: number) {
const d = new Drawing("preview", "Preview", "")
+ // The roads a thing being placed would reach: a faint wash along them.
+ for (const c of preview.range) d.face(square(c.x + 0.5, c.y + 0.5, 0.5, 0.11), 0x3d6db5, 0, palette.ink, 0.24)
for (const { x, y, size, look } of preview.plots) {
const color = look === "blocked" ? 0xc4523f : look === "picked" ? 0x3d6db5 : palette.ink,
half = size / 2,
diff --git a/src/render3d/views.ts b/src/render3d/views.ts
index 58164ff..75f93e0 100644
--- a/src/render3d/views.ts
+++ b/src/render3d/views.ts
@@ -68,8 +68,10 @@ export class WorldView implements SceneNode {
orient() {}
/** A tint for what it is like now (run down, a poor street), before winter's frost. */
protected shade = 0xffffff
+ /** A map view's colour over the whole model, so the view reads from the buildings and not only the ground under them. */
+ protected viewTint: number | null = null
protected emphasis(emphasis: Emphasis) {
- const tint = emphasis === "danger" ? 0xf3b5aa : multiply(this.shade, this.stage.frost ? FROST : 0xffffff)
+ const tint = emphasis === "danger" ? 0xf3b5aa : this.viewTint !== null ? multiply(this.viewTint, this.stage.frost ? FROST : 0xffffff) : multiply(this.shade, this.stage.frost ? FROST : 0xffffff)
for (const m of this.models) m.tint.setHex(tint)
}
destroy() {
@@ -169,6 +171,7 @@ export class BuildingView extends WorldView {
this.group.add(this.smoke.group)
}
this.smoke?.update(performance.now()/1000,Number(smoking))
+ this.viewTint = look.tint ?? null
this.emphasis(emphasis)
}
override orient() {
@@ -212,6 +215,7 @@ export class HouseView extends WorldView {
}
this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)
this.shade=0xffffff
+ this.viewTint = look.tint ?? null
this.emphasis(emphasis)
}
}
diff --git a/src/rules/approval.ts b/src/rules/approval.ts
index 61f8378..7f4dbe7 100644
--- a/src/rules/approval.ts
+++ b/src/rules/approval.ts
@@ -1,7 +1,25 @@
import { shippedRules, type Rules } from "./config.ts"
import { satisfaction, type Needs, type Rates } from "./households.ts"
-export const approvalTarget = (homes: ReadonlyArray<Needs & { readonly residents: number }>, policy: Rates, coins: number, snubs: number, winter: boolean, rules: Rules = shippedRules) => {
+/**
+ * The town's memory of high taxes, in tenths of a point: it grows every
+ * collection the average rate is above `mood.grudge.above` and fades when
+ * it is not (see `mood.grudge`).
+ */
+export const grudgeAfter = (memory: number, rate: number, rules: Rules = shippedRules): number => {
+ const excess = Math.max(0, rate - rules.mood.grudge.above)
+ return excess > 0
+ ? Math.min(rules.mood.grudge.most, memory + Math.round(excess * rules.mood.grudge.perPoint))
+ : Math.max(0, memory - rules.mood.grudge.decay)
+}
+
+/**
+ * Where approval is heading and why: the town's mood, its needs, the taxes
+ * now, the grudge over taxes before, unpaid wages, the crown's displeasure,
+ * and a hungry winter. `memory` is the grudge so far (tenths); the one
+ * returned is after this collection.
+ */
+export const approvalTarget = (homes: ReadonlyArray<Needs & { readonly residents: number }>, policy: Rates, coins: number, snubs: number, winter: boolean, rules: Rules = shippedRules, memory = 0) => {
const people = homes.reduce((n, h) => n + h.residents, 0)
const pleased = homes.reduce((n, h) => n + h.residents * satisfaction(h, h.tier, rules), 0)
const taxed = homes.reduce((n, h) => n + h.residents * (h.tier === 1 ? policy.settlers : policy.citizens), 0)
@@ -10,7 +28,11 @@ export const approvalTarget = (homes: ReadonlyArray<Needs & { readonly residents
const needs = Math.round(rules.mood.needs[0] + (rules.mood.needs[1] - rules.mood.needs[0]) * share)
const taxes = Math.round((100 - rate) * rules.mood.perTaxPoint), debt = coins < 0 ? rules.mood.debt : 0
const crown = snubs * rules.mood.snub, hunger = winter && homes.length > 0 && fed / homes.length < 0.5 ? rules.mood.winterHunger : 0
- return { target: Math.max(-100, Math.min(100, rules.mood.base + needs + taxes + debt + crown + hunger)), base: rules.mood.base, needs, taxes, debt, crown, winter: hunger }
+ const kept = grudgeAfter(memory, rate, rules), grudge = -Math.round(kept / 10)
+ return {
+ target: Math.max(-100, Math.min(100, rules.mood.base + needs + taxes + debt + crown + hunger + grudge)),
+ base: rules.mood.base, needs, taxes, debt, crown, winter: hunger, grudge, memory: kept
+ }
}
export const nextApproval = (approval: number, target: number, rules: Rules = shippedRules) =>
approval + Math.max(-rules.mood.step, Math.min(rules.mood.step, target - approval))
diff --git a/src/rules/config.ts b/src/rules/config.ts
index f4dd527..a10a8e0 100644
--- a/src/rules/config.ts
+++ b/src/rules/config.ts
@@ -15,7 +15,7 @@ const inputs = () => ({
stepSeconds: content.STEP_SECONDS, ledgerTicks: content.LEDGER_TICKS, spoilTicks: content.SPOIL_TICKS,
commute: content.COMMUTE, apprentice: content.APPRENTICE, toolStock: content.TOOL_STOCK,
conditionMax: content.CONDITION_MAX, riskMax: content.RISK_MAX, pausedUpkeep: content.PAUSED_UPKEEP,
- buildTicks: content.BUILD_TICKS, roadCost: content.ROAD_COST, paveCost: content.PAVE_COST,
+ buildTicks: content.BUILD_TICKS, roadCost: content.ROAD_COST, paveCost: content.PAVE_COST, pavedPace: content.PAVED_PACE,
grown: content.GROWN, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,
spreadTicks: content.ticks(1.5), growTicks: 10
})
diff --git a/src/rules/explain.ts b/src/rules/explain.ts
new file mode 100644
index 0000000..8811846
--- /dev/null
+++ b/src/rules/explain.ts
@@ -0,0 +1,121 @@
+/**
+ * Why a home is short of something, in a line that names the cause and
+ * what to do about it. The panel reads these out, and the legibility test
+ * checks that the usual dead ends (cloth withheld from a poor street, no
+ * 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 { shippedRules, type Rules } from "./config.ts"
+import { kept as keptBy, met, wantsCitizenGoods, type Needs } from "./households.ts"
+
+export interface Part {
+ readonly label: string
+ readonly value: number
+}
+/** A street as a home sees it: its desirability, and what makes it (strongest first). */
+export interface Street {
+ readonly desirability: number
+ readonly parts: ReadonlyArray<Part>
+}
+/** What the town has of each provision: in storage and on market shelves together. */
+export interface InTown {
+ readonly fish: number
+ readonly smoked: number
+ readonly bread: number
+ readonly cloth: number
+}
+/** Whether a walker of each kind can reach the home at all: a market's (or the town hall's) with provisions, and a chapel's. */
+export interface Served {
+ readonly goods: boolean
+ readonly faith: boolean
+}
+
+export const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`
+
+/** What counts most against a street, for a cause in a line: "quarry −6, warehouse −2". */
+export const against = (parts: ReadonlyArray<Part>, most = 2): string =>
+ parts.filter((p) => p.value < 0).slice(0, most).map((p) => `${p.label} ${signed(p.value)}`).join(", ")
+
+/** A street against what the next tier needs: "−4 here, 5 needed: quarry −6". */
+export const streetShort = (street: Street, needed: number): string => {
+ const why = against(street.parts)
+ return `${signed(street.desirability)} here, ${needed} needed${why ? `: ${why}` : ""}`
+}
+
+/** What would lift a street: the things a mayor can do. */
+export const streetAdvice = (street: Street): string =>
+ street.parts.some((p) => p.value < 0)
+ ? "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 === "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 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 => {
+ if (met(h, need)) return null
+ const needed = rules.home.tiers[2].appeal
+ switch (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 (!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"
+ }
+ 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"
+ }
+ 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"
+ }
+ case "faith": {
+ if (!served.faith) return noWalker("chapel", rules)
+ return "the chapel's walker has not passed lately"
+ }
+ }
+}
+
+export interface Blocker {
+ readonly what: Need | "street" | "services"
+ readonly text: string
+}
+
+/**
+ * Everything keeping a home from the next tier, a line each: unmet needs
+ * with their causes, a street too poor, and (for a townhouse) services not
+ * all calling. Empty when nothing stands in the way.
+ */
+export const blockers = (
+ h: Needs,
+ street: Street,
+ inTown: InTown,
+ served: Served,
+ risk: { readonly fire: number; readonly health: number; readonly order: number } | undefined,
+ rules: Rules = shippedRules
+): ReadonlyArray<Blocker> => {
+ if (h.tier >= 3) return []
+ const next = (h.tier + 1) as Tier
+ const out: Array<Blocker> = []
+ for (const need of rules.home.tiers[next].needs) {
+ const why = whyUnmet(need, h, street, inTown, served, rules)
+ 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` })
+ }
+ return out
+}
diff --git a/src/rules/goals.ts b/src/rules/goals.ts
index bb711a4..928736f 100644
--- a/src/rules/goals.ts
+++ b/src/rules/goals.ts
@@ -3,6 +3,16 @@ import { shippedRules, type Rules } from "./config.ts"
/** Food in storage: what would carry the town through a winter. */
export const larder = (stock: { readonly fish: number; readonly smoked: number; readonly bread: number }) => stock.fish + stock.smoked + stock.bread
+/**
+ * Coins a minute as the goals judge it: the last minute of the town's
+ * history averaged with the ledger now, so one bulk purchase does not flip
+ * "not losing any" off for ten seconds. With no history yet, the ledger.
+ */
+export const steadyNet = (samples: ReadonlyArray<{ readonly net: number }>, now: number, last = 4): number => {
+ const recent = samples.slice(-last).map((s) => s.net)
+ return Math.round(recent.concat(now).reduce((n, v) => n + v, 0) / (recent.length + 1))
+}
+
/** Each goal the town must hold to be complete, met or not. */
export const goalsOf = (
charter: { readonly size: keyof Rules["sizes"] },
diff --git a/src/rules/households.ts b/src/rules/households.ts
index 0f2326a..12c293c 100644
--- a/src/rules/households.ts
+++ b/src/rules/households.ts
@@ -26,17 +26,23 @@ const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rate
/** How approval (-100 → 100) sits with a home: a third as many residents at its worst, half again at its best. */
export const appealOf = (approval: number): number => (approval < 0 ? 1 + approval / 150 : 1 + approval / 200)
+/** The share of its residents a home keeps on a street of this desirability: all at 0 and above, fewer below, point by point. */
+export const streetRoom = (desirability: number, rules: Rules = shippedRules): number =>
+ Math.max(rules.home.street.roomLeast, Math.min(1, 1 + desirability / rules.home.street.room))
+/** What a street does to a home's taxes: more on a fine street, less on a poor one, within a quarter either way. */
+export const streetTax = (desirability: number, rules: Rules = shippedRules): number =>
+ Math.max(1 - rules.home.street.taxMost, Math.min(1 + rules.home.street.taxMost, 1 + desirability / rules.home.street.tax))
+
/**
* Residents a home holds at its tier and satisfaction: half when nothing is
* met, all when everything is; fewer when the town disapproves of its
- * mayor, and up to all of them when it approves, needs or not. Nobody
- * wants to live where it is squalid (desirability `rules.home.squalid` or less):
- * such a home holds fewer.
+ * mayor, and up to all of them when it approves, needs or not. A poor
+ * street (desirability below 0) holds fewer, point by point (see
+ * `streetRoom`): a cottage beside a quarry loses a resident at once.
*/
export const capacity = (h: Needs, approval: number, desirability = 0, rules: Rules = shippedRules): number => {
const max = rules.home.tiers[h.tier].residents
- const squalor = desirability <= rules.home.squalid ? rules.home.crowded : 1
- return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h, h.tier, rules)) * appealOf(approval) * squalor)))
+ return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h, h.tier, rules)) * appealOf(approval) * streetRoom(desirability, rules))))
}
/** Whether every risk meter of a home is kept low: a service walker of each kind passes it. */
@@ -65,9 +71,21 @@ export const adminOf = (homes: number, rules: Rules = shippedRules): number => M
export const priceOf = (good: GoodId, percent: number, rules: Rules = shippedRules) => (rules.goods[good].price * percent) / 100
export const askOf = (good: GoodId, percent: number, rules: Rules = shippedRules) => Math.ceil(priceOf(good, percent, rules) * rules.market.markup)
-/** Coins a home pays a minute. */
-export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates, rules: Rules = shippedRules): number =>
- h.residents * rules.home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h, h.tier, rules))
+/** A settlers' cottage with bread on the table pays `home.breadBonus` more. */
+export const breadBonus = (h: Needs, rules: Rules = shippedRules): number => (h.tier === 1 && met(h, "bread") ? 1 + rules.home.breadBonus : 1)
+
+/**
+ * Coins a home pays a minute: by its tier, the rate, the share of its needs
+ * met, its street, and (for settlers) bread. A hungry home pays nothing:
+ * no food, no taxes.
+ */
+export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates, rules: Rules = shippedRules, desirability = 0): number =>
+ h.food > 0
+ ? h.residents * rules.home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * satisfaction(h, h.tier, rules) * streetTax(desirability, rules) * breadBonus(h, rules)
+ : 0
+/** What the same home would pay with every need met and bread on the table: the money a town leaves on the table. */
+export const suppliedTaxOf = (h: Needs & { readonly residents: number }, rates: Rates, rules: Rules = shippedRules, desirability = 0): number =>
+ taxOf({ ...h, food: 1, bread: 1, cloth: 1, faith: 1 }, rates, rules, desirability)
export const refreshLevel = (need: Need, rules: Rules = shippedRules) => rules.home.lasts[need] / 2
export const lowNeed = (left: number, need: Need, rules: Rules = shippedRules) => left < refreshLevel(need, rules)
@@ -84,7 +102,15 @@ export const ageNeeds = <T extends Needs & { readonly clock: number }>(h: T, eat
export const wantsCitizenGoods = (house: Needs, desirability: number, rules: Rules = shippedRules) =>
house.tier >= 2 || desirability >= rules.home.tiers[2].appeal
-/** Eligible settlers request bread independently of food; other settlers use fish first. */
+/**
+ * What a walker hands a home from its basket, one thing to eat at most:
+ * citizens (and settlers on a street fit for citizens) take bread first;
+ * other settlers eat fish, or bread when there is no fish, and take a loaf
+ * besides when their bread has run out, since a cottage with bread pays
+ * more (see `breadBonus`), but only from the basket's surplus (more than
+ * half of it left), so the citizens further along the walk are not left
+ * without. Cloth goes only where citizens could live.
+ */
export const serveGoods = <T extends Needs>(house: T, available: Readonly<Record<GoodId, number>>, rules: Rules = shippedRules, desirability = 0) => {
const h = { ...house } as Mutable<T>, basket = { ...available }
const citizens = wantsCitizenGoods(h, desirability, rules)
@@ -94,7 +120,7 @@ export const serveGoods = <T extends Needs>(house: T, available: Readonly<Record
} else if (lowNeed(h.food, "food", rules) && (basket.fish > 0 || basket.smoked > 0)) {
const g = basket.fish > 0 ? "fish" : "smoked"
basket[g] -= 1; h.food = rules.home.lasts.food; eaten += 1
- } else if (lowNeed(h.food, "food", rules) && basket.bread > 0) {
+ } else if ((lowNeed(h.food, "food", rules) || (!citizens && lowNeed(h.bread, "bread", rules) && basket.bread > rules.transport.basket / 2)) && basket.bread > 0) {
basket.bread -= 1; h.food = rules.home.lasts.food; h.bread = rules.home.lasts.bread; eaten += 1
}
if (citizens && lowNeed(h.cloth, "cloth", rules) && basket.cloth > 0) {
diff --git a/src/save.ts b/src/save.ts
index c55eb2d..cf74062 100644
--- a/src/save.ts
+++ b/src/save.ts
@@ -13,9 +13,27 @@ import { Clock, Context, Effect, Schema } from "effect"
export const SAVE_FORMAT = "inkline-town/save"
/**
* 2: the charter's towns. 3: neighbourhoods and their dangers (desirability, crews, risks, wear, ruins,
- * winters). Older saves cannot be loaded.
+ * winters). 4: parks and patrols. 5: the grudge over taxes, and where each piece of news happened.
+ * A version 4 save is carried forward (see `carry`); older ones cannot be loaded.
*/
-export const SAVE_VERSION = 4
+export const SAVE_VERSION = 5
+
+/**
+ * Fills in what a save from the version before lacks, so a town in progress
+ * survives an update: the mood's grudge (none yet) and the news's places
+ * (unknown). Anything else is left to the world's own validation.
+ */
+const carry = (version: number, world: unknown): unknown | null => {
+ if (version !== 4 || typeof world !== "object" || world === null) return null
+ const w = world as { resources?: Record<string, unknown> }
+ const r = w.resources
+ if (!r || typeof r !== "object") return null
+ const mood = r["Town/Mood"]
+ if (mood && typeof mood === "object" && !("grudge" in mood)) r["Town/Mood"] = { ...mood, grudge: 0, memory: 0 }
+ const chronicle = r["Town/Chronicle"] as { lines?: Array<Record<string, unknown>> } | undefined
+ if (chronicle && Array.isArray(chronicle.lines)) r["Town/Chronicle"] = { ...chronicle, lines: chronicle.lines.map((l) => ({ at: null, ...l })) }
+ return w
+}
export type Slot = "manual" | "auto"
export const slots: ReadonlyArray<Slot> = ["manual", "auto"]
@@ -134,7 +152,12 @@ export const read = (slot: Slot) =>
return { format: SAVE_FORMAT, version: SAVE_VERSION, slot, savedAt: 0, title: "an earlier save", world: parsed } satisfies SaveFile
}
const version = (parsed as { version?: unknown } | null)?.version
- if (typeof version === "number" && version !== SAVE_VERSION) return yield* new WrongVersion({ slot, version })
+ if (typeof version === "number" && version !== SAVE_VERSION) {
+ const carried = carry(version, (parsed as { world?: unknown }).world)
+ if (carried === null) return yield* new WrongVersion({ slot, version })
+ const file = yield* decodeEnvelope({ ...(parsed as object), version: SAVE_VERSION, world: carried }).pipe(Effect.mapError((e) => new Unreadable({ slot, reason: e.message })))
+ return file
+ }
return yield* decodeEnvelope(parsed).pipe(Effect.mapError((e) => new Unreadable({ slot, reason: e.message })))
})
diff --git a/src/schema.ts b/src/schema.ts
index eb06fa1..739abbe 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -241,7 +241,10 @@ export const Mood = Descriptor.ConstructedResource(Decode.struct({
taxes: integer,
debt: integer,
crown: integer,
- winter: integer
+ winter: integer,
+ /** The grudge over taxes past: points off the target now, and the town's memory of them in tenths (see `mood.grudge`). */
+ grudge: integer,
+ memory: integer
}))("Town/Mood")
/**
@@ -288,9 +291,9 @@ export const Fate = Descriptor.ConstructedResource(Decode.struct({
export const History = Descriptor.ConstructedResource(Decode.struct({
samples: Decode.array(Decode.struct({ tick: integer, coins: integer, residents: integer, citizens: integer, approval: integer, net: integer }))
}))("Town/History")
-/** What happened, in a line each; an `alarm` is news the page announces (a fire, a theft, winter coming). */
+/** What happened, in a line each; an `alarm` is news the page announces (a fire, a theft, winter coming); `at` is where, when it was somewhere. */
export const Chronicle = Descriptor.ConstructedResource(Decode.struct({
- lines: Decode.array(Decode.struct({ tick: integer, text: Decode.string, alarm: Decode.boolean }))
+ lines: Decode.array(Decode.struct({ tick: integer, text: Decode.string, alarm: Decode.boolean, at: Decode.nullable(cell) }))
}))("Town/Chronicle")
/** How desirable each cell is to live on (by `key`), reckoned every `appeal.every` steps; empty before the first. */
@@ -319,6 +322,8 @@ export interface GridValue {
readonly roads?: number
/** The entities standing on it, when known: the grid only changes when one of them goes. */
readonly tiles?: ReadonlySet<number>
+ /** Paved road cells (by `key`), when known: walkers and carriers move faster along them. */
+ readonly paved?: ReadonlySet<number>
}
export const Grid = Descriptor.TransientResource<GridValue>()("Town/Grid")
/** Goods in the town's storage, summed every step. */
diff --git a/src/sim/decay.ts b/src/sim/decay.ts
index 26102bc..0fa90f5 100644
--- a/src/sim/decay.ts
+++ b/src/sim/decay.ts
@@ -8,9 +8,9 @@ import { spoilExpectation } from "../rules/decay.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
import { ruinDraft } from "../archetypes.ts"
-import { goodIds, ticks } from "../content.ts"
+import { foods, goodIds, ticks } from "../content.ts"
import { counted, placeName } from "../places.ts"
-import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Rising, Rng, Site, Tile, Time, maybe } from "../schema.ts"
+import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Recipe, Rising, Rng, Site, Staff, Tile, Time, maybe } from "../schema.ts"
import { elapsed, write } from "./shared.ts"
/** The pantry warns of rotting food at most this often. */
@@ -25,7 +25,9 @@ export const Decay = Game.System(
without: [Site, Rising, Burning]
}),
landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
- shelves: Game.Query({ selection: { inventory: Game.Query.write(Inventory), building: Game.Query.optional(Building) }, without: [Site, Rising] })
+ shelves: Game.Query({ selection: { inventory: Game.Query.write(Inventory), building: Game.Query.optional(Building) }, without: [Site, Rising] }),
+ /** Who makes food, and whether anyone is at work there: for the rot warning's reckoning of what the town makes. */
+ makers: Game.Query({ selection: { recipe: Game.Query.read(Recipe), staff: Game.Query.read(Staff) }, with: [Building], without: [Site, Rising, Burning] })
},
resources: {
time: Game.System.readResource(Time),
@@ -60,7 +62,8 @@ export const Decay = Game.System(
resources.chronicle,
t,
b ? `The ${kinds[b.kind].title.toLowerCase()} on ${placeName(landmarks, tile)} fell down: nobody mended it.` : `A home on ${placeName(landmarks, tile)} fell down: nobody mended it.`,
- true
+ true,
+ tile
)
}
}
@@ -91,8 +94,19 @@ export const Decay = Game.System(
// The pantry's minute.
if (t > 0 && t % 3600 === 0) {
const p = resources.pantry.get()
- const warn = p.rotted >= 6 && t - p.warned >= ROT_WARNING
- if (warn) write(resources.chronicle, t, `${counted(p.rotted, "fish or loaf", "fish and loaves")} rotted in store this minute: a granary keeps them five times as long, and smoked fish keeps.`, true)
+ const warn = p.rotted >= 6 && p.rotted * 4 >= p.eaten && t - p.warned >= ROT_WARNING
+ if (warn) {
+ // What the town could make of food a minute with the crews it has, against what it ate: rot is the difference, not a want of granaries.
+ let made = 0
+ for (const { data } of queries.makers.each()) {
+ const r = data.recipe.get()
+ if (data.staff.get().assigned > 0 && (foods as ReadonlyArray<string>).includes(r.output)) made += (r.batch * 3600) / r.period
+ }
+ const cause = made > p.eaten * 1.5
+ ? `the town makes about ${Math.round(made)} food a minute and eats ${p.eaten}: fewer fisheries, a smokehouse, or selling fish would stop the waste`
+ : `a granary keeps fish and bread five times as long, and smoked fish keeps`
+ write(resources.chronicle, t, `${counted(p.rotted, "fish or loaf", "fish and loaves")} rotted in store this minute: ${cause}.`, true)
+ }
resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: p.eaten, rottedLast: p.rotted, warned: warn ? t : p.warned })
}
}
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
index 5ff4e76..9040fc5 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -337,12 +337,12 @@ export const ApplyEdits = Game.System(
resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0, admin: 0 })
resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve })
resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })
- resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 })
+ resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0, grudge: 0, memory: 0 })
resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter, rules), met: 0, missed: 0, streak: 0, snubs: [] })
resources.fate.set(foundedFate())
resources.history.set({ samples: [] })
resources.chronicle.set({
- lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.`, alarm: false }]
+ lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.`, alarm: false, at: null }]
})
resources.rng.set(charter.seed)
ui.selected = null
diff --git a/src/sim/hazards.ts b/src/sim/hazards.ts
index e0dec0d..a1c2445 100644
--- a/src/sim/hazards.ts
+++ b/src/sim/hazards.ts
@@ -120,7 +120,7 @@ export const Hazards = Game.System(
const season = seasonAt(t, charter, rules)
const heating = season.severity !== null && winters[season.severity].heating
const random = Random.make(resources.rng.get())
- const news = (text: string) => write(resources.chronicle, t, text, true)
+ const news = (text: string, at: Point | null = null) => write(resources.chronicle, t, text, true, at)
const landmarks: Array<Landmark> = queries.landmarks.each().map(({ data }) => ({ kind: data.building.get().kind, ...data.tile.get() }))
const where = (cell: Point) => placeName(landmarks, cell)
const fires = { ...resources.fires.get(), fires: resources.fires.get().fires.map((f) => ({ ...f })) }
@@ -173,12 +173,12 @@ export const Hazards = Game.System(
commands.insert(row.entity.id, Game.Command.entry(Burning, { left: risk.fire.burns, fire: id }))
ignited.set(row.entity.id, id)
r.fire = 0
- news(`Fire on ${where(tile)}!`)
+ news(`Fire on ${where(tile)}!`, tile)
}
if (h && r.health >= RISK_MAX && !data.sick.present) {
commands.insert(row.entity.id, Game.Command.entry(Sick, { left: risk.health.lasts }))
r.health = 0
- if (sickNow === 0) news(`Sickness on ${where(tile)}: a physician can cure it.`)
+ if (sickNow === 0) news(`Sickness on ${where(tile)}: a physician can cure it.`, tile)
}
if (h && r.order >= RISK_MAX) {
if (r.thefts === 0) {
@@ -187,7 +187,7 @@ export const Hazards = Game.System(
const take = Math.min(risk.order.most, Math.max(0, coins), risk.order.coins + Math.floor(Math.max(0, coins) * risk.order.share))
if (take > 0) {
resources.treasury.set({ coins: coins - take })
- news(`Thieves on ${where(tile)} made off with ${take} coins.`)
+ news(`Thieves on ${where(tile)} made off with ${take} coins.`, tile)
} else {
const stores = queries.stores.each()
const held = (g: GoodId) => stores.reduce((n, s) => n + s.data.inventory.get().stock[g], 0)
@@ -200,12 +200,12 @@ export const Hazards = Game.System(
s.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - n } })
owed -= n
}
- if (held(good) > 0) news(`Thieves on ${where(tile)} made off with ${goods[good].title}.`)
+ if (held(good) > 0) news(`Thieves on ${where(tile)} made off with ${goods[good].title}.`, tile)
}
r.thefts += 1
r.order = risk.order.after
} else {
- news(`A home on ${where(tile)} stood empty after its thefts, and is left derelict.`)
+ news(`A home on ${where(tile)} stood empty after its thefts, and is left derelict.`, tile)
ruin(row, "derelict")
lost.add(row.entity.id)
continue
@@ -303,7 +303,7 @@ export const Hazards = Game.System(
const over = fires.fires.filter((f) => !stillBurning.has(f.id))
for (const f of over) {
const took = [f.homes > 0 ? counted(f.homes, "home") : "", f.buildings > 0 ? counted(f.buildings, "building") : ""].filter((s) => s !== "")
- news(`Fire on ${where(f)}: ${took.length > 0 ? `${took.join(" and ")} lost` : "put out"}.`)
+ news(`Fire on ${where(f)}: ${took.length > 0 ? `${took.join(" and ")} lost` : "put out"}.`, { x: f.x, y: f.y })
}
resources.fires.set({ fires: fires.fires.filter((f) => stillBurning.has(f.id)), next: fires.next })
resources.rng.set(random.state)
diff --git a/src/sim/headless.ts b/src/sim/headless.ts
index 5806d78..ad544d3 100644
--- a/src/sim/headless.ts
+++ b/src/sim/headless.ts
@@ -25,7 +25,7 @@ export const headless = (charter: CharterValue, options: { readonly toast?: (mes
tool: "select", placing: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],
edits: [{ type: "newTown", charter }],
preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false,
- view: "none", overlay: { key: "", cells: [] }, legend: null,
+ view: "none", overlay: { key: "", cells: [] }, tints: new Map(), legend: null, flash: null,
toast: options.toast ?? (() => {})
}
const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources() })
diff --git a/src/sim/index.ts b/src/sim/index.ts
index f247873..22f7a91 100644
--- a/src/sim/index.ts
+++ b/src/sim/index.ts
@@ -68,7 +68,7 @@ export const blankResources = () => ({
Charter: { ...defaultCharter(0), founded: 0, winters: [] as Array<"none" | "mild" | "normal" | "hard"> },
Land: { mask: "", cells: 0 },
Market: { prices: amounts({}) },
- Mood: { approval: 0, target: 0, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 },
+ Mood: { approval: 0, target: 0, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0, grudge: 0, memory: 0 },
Crown: { open: false, good: "wood" as const, amount: 0, issued: 0, due: 0, reward: 0, next: 0, met: 0, missed: 0, streak: 0, snubs: [] },
Fate: foundedFate(),
History: { samples: [] },
@@ -84,4 +84,4 @@ export { CELL_STEPS, elapsed, seasonAt, termTicks, winterOf } from "./shared.ts"
export { SITE_SHARE } from "./work.ts"
export { unlocked } from "./edits.ts"
export { adminOf, askOf, capacity, kept, met, priceOf, satisfaction, taxOf, tierFor } from "./town.ts"
-export { crownGap, goalsOf, larder } from "./term.ts"
+export { crownGap, goalsOf, larder, steadyNet } from "./term.ts"
diff --git a/src/sim/shared.ts b/src/sim/shared.ts
index 30d7bae..f633f00 100644
--- a/src/sim/shared.ts
+++ b/src/sim/shared.ts
@@ -1,12 +1,14 @@
/** Queries and small helpers the simulation's systems share. */
import { doors, type TileLike, type Use } from "../grid.ts"
-import { Field, Game, House, Park, Road, Rock, Ruin, Tile, Tree, Water, type GridValue } from "../schema.ts"
+import { Field, Game, House, Park, Paved, Road, Rock, Ruin, Tile, Tree, Water, type GridValue } from "../schema.ts"
+import type { Point } from "../iso.ts"
/** Every tile, with enough to tell what it is. */
export const TileRead = Game.Query({
selection: {
tile: Game.Query.read(Tile),
road: Game.Query.optional(Road),
+ paved: Game.Query.optional(Paved),
park: Game.Query.optional(Park),
house: Game.Query.optional(House),
tree: Game.Query.optional(Tree),
@@ -45,11 +47,12 @@ export { elapsed, termTicks, yearTicks, winterOf, rollWinters, seasonAt, type Al
// ── The chronicle ─────────────────────────────────────────────────────────
-type Lines = ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean }>
-/** A line in the chronicle; an `alarm` is also news the page announces. */
+type Lines = ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean; readonly at: Point | null }>
+/** A line in the chronicle; an `alarm` is also news the page announces; `at` is where it happened, when it was somewhere. */
export const write = (
chronicle: { update: (f: (c: { readonly lines: Lines }) => { lines: Lines }) => void },
tick: number,
text: string,
- alarm = false
-) => chronicle.update((c) => ({ lines: [...c.lines, { tick, text, alarm }].slice(-200) }))
+ alarm = false,
+ at: Point | null = null
+) => chronicle.update((c) => ({ lines: [...c.lines, { tick, text, alarm, at: at ? { x: at.x, y: at.y } : null }].slice(-200) }))
diff --git a/src/sim/term.ts b/src/sim/term.ts
index 0ca8ff5..f10837c 100644
--- a/src/sim/term.ts
+++ b/src/sim/term.ts
@@ -164,9 +164,10 @@ export const Approve = Game.System(
const t = elapsed(resources.time.get(), resources.charter.get())
if (t % ticks(10) !== 0) return
const policy = resources.policy.get()
+ const m = resources.mood.get()
const parts = approvalTarget(queries.homes.each().map(({ data }) => data.house.get()), policy,
- resources.treasury.get().coins, resources.crown.get().snubs.length, seasonAt(t, resources.charter.get(), rules).winter, rules)
- resources.mood.update((m) => ({ approval: nextApproval(m.approval, parts.target, rules), ...parts }))
+ resources.treasury.get().coins, resources.crown.get().snubs.length, seasonAt(t, resources.charter.get(), rules).winter, rules, m.memory)
+ resources.mood.set({ approval: nextApproval(m.approval, parts.target, rules), ...parts })
}
)
@@ -187,8 +188,8 @@ export const foundedFate = () => ({
score: 0
})
-import { goalsOf, larder, scoreOf } from "../rules/goals.ts"
-export { goalsOf, larder, scoreOf } from "../rules/goals.ts"
+import { goalsOf, larder, scoreOf, steadyNet } from "../rules/goals.ts"
+export { goalsOf, larder, scoreOf, steadyNet } from "../rules/goals.ts"
/**
* Once a second: does the term end? It is lost to bankruptcy (in debt too
@@ -208,6 +209,7 @@ export const Judge = Game.System(
ledger: Game.System.readResource(Ledger),
mood: Game.System.readResource(Mood),
crown: Game.System.readResource(Crown),
+ history: Game.System.readResource(History),
fate: Game.System.writeResource(Fate),
chronicle: Game.System.writeResource(Chronicle)
},
@@ -228,7 +230,7 @@ export const Judge = Game.System(
const approval = resources.mood.get().approval
const crownNow = resources.crown.get()
const residents = census.settlers + census.citizens
- const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
+ const net = steadyNet(resources.history.get().samples, ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin)
const note = (text: string, alarm = false) => write(resources.chronicle, t, text, alarm)
const minutes = (n: number) => ticks(n * 60)
const left = Math.max(0, Math.round((termTicks(charter, rules) - t) / 3600))
diff --git a/src/sim/town.ts b/src/sim/town.ts
index 7aa5295..2346487 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -92,6 +92,7 @@ export const Collect = Game.System(
resources: {
time: Game.System.readResource(Time),
grid: Game.System.readResource(Grid),
+ appeal: Game.System.readResource(Appeal),
policy: Game.System.readResource(Policy),
market: Game.System.writeResource(Market),
treasury: Game.System.writeResource(Treasury),
@@ -109,12 +110,14 @@ export const Collect = Game.System(
const hall = queries.halls.each()[0]
const roads = hall ? reach(grid, doors(grid, hall.data.tile.get())) : null
const share = LEDGER_TICKS / (60 * 60)
+ const cells = resources.appeal.get().cells
let taxes = 0
let homes = 0
for (const { data } of queries.homes.each()) {
homes += 1
- const reached = roads !== null && doors(grid, data.tile.get()).some((c) => roads.distance[key(c.x, c.y)]! >= 0)
- if (reached) taxes += taxOf(data.house.get(), policy, rules)
+ const tile = data.tile.get()
+ const reached = roads !== null && doors(grid, tile).some((c) => roads.distance[key(c.x, c.y)]! >= 0)
+ if (reached) taxes += taxOf(data.house.get(), policy, rules, appealAt(cells, tile.x, tile.y))
}
let upkeep = 0
for (const { data } of queries.buildings.each()) upkeep += kinds[data.building.get().kind].upkeep * (data.paused.present ? PAUSED_UPKEEP : 1)
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
index dd7d4b9..c9b4e9e 100644
--- a/src/sim/walkers.ts
+++ b/src/sim/walkers.ts
@@ -12,7 +12,7 @@ import { appealAt } from "../appeal.ts"
*/
import { amounts, categoryColor, each, provisions, total, type Amounts } from "../content.ts"
-import { DIRS, doors, isRoad, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"
+import { DIRS, doors, isRoad, key, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"
import { inside, type Point } from "../iso.ts"
import { Building, Burning, Condition, Figure, Game, Rules, Grid, Appeal, Patrol, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Roam, Route, Service, Sick, Site, Staff, Status, Tile, Time, WalkerOf, maybe, type Status as StatusValue } from "../schema.ts"
import { CELL_STEPS } from "./shared.ts"
@@ -27,15 +27,22 @@ const BASKET = transport.basket
/** Walkers a service building may have out on the roads at once. */
const OUT = transport.active
-/** Every walker steps along its route (a firefighter on the way to a blaze runs); one whose next cell is no longer road is lost. */
+/**
+ * Every walker steps along its route (a firefighter on the way to a blaze
+ * runs, and anyone on a paved street goes `pavedPace` as fast); one whose
+ * next cell is no longer road is lost.
+ */
export const Walk = Game.System(
"Town/Walk",
{
queries: { walkers: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.optional(Rescue) } }) },
- resources: { grid: Game.System.readResource(Grid) }
+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) }
},
- ({ queries, resources, commands }) => {
+ ({ queries, resources, commands, services }) => {
const grid = resources.grid.get()
+ const tick = resources.time.get().tick
+ const quicker = services.rules.pavedPace - 1
for (const { entity, data } of queries.walkers.each()) {
const route = data.route.get()
const last = route.cells.length - 1
@@ -46,7 +53,8 @@ export const Walk = Game.System(
continue
}
const running = data.rescue.present && !data.rescue.get().back
- const step = route.step + (running ? RUN : WALK)
+ const paved = !running && quicker > 0 && (grid.paved?.has(key(next.x, next.y)) ?? false) && paced(quicker, tick)
+ const step = route.step + (running ? RUN : WALK) + (paved ? 1 : 0)
if (step < CELL_STEPS) data.route.set({ ...route, step })
else {
const index = route.index + 1
diff --git a/src/sim/work.ts b/src/sim/work.ts
index f16eb58..4d9f1aa 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -10,7 +10,7 @@ import * as Random from "@typeonce/bevy-ts-math/Random"
import { fieldDraft, treeDraft } from "../archetypes.ts"
import { amounts, crewOf, goodIds, ticks, total, type Amounts, type Crew } from "../content.ts"
import { around, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../grid.ts"
-import { Building, Burning, Charter, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue } from "../schema.ts"
+import { Building, Burning, Charter, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue } from "../schema.ts"
import { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"
import { assignWorkers, equipmentPace, effort, paced } from "../rules/production.ts"
@@ -25,22 +25,30 @@ export { effort, paced } from "../rules/production.ts"
export const IndexGrid = Game.System(
"Town/IndexGrid",
{
- queries: { tiles: TileRead, laid: Game.Query({ selection: { tile: Game.Query.read(Tile) }, filters: [Game.Query.added(Tile)] }) },
+ queries: {
+ tiles: TileRead,
+ laid: Game.Query({ selection: { tile: Game.Query.read(Tile) }, filters: [Game.Query.added(Tile)] }),
+ /** A road just paved: the grid's paved cells change without any tile coming or going. */
+ paved: Game.Query({ selection: { paved: Game.Query.read(Paved) }, filters: [Game.Query.added(Paved)] })
+ },
despawned: { entities: Game.System.readDespawned() },
resources: { land: Game.System.readResource(Land), grid: Game.System.writeResource(Grid) }
},
({ queries, despawned, resources }) => {
const known = resources.grid.get().tiles
- const changed = known === undefined || queries.laid.each().length > 0 || despawned.entities.all().some((id) => known.has(id))
+ const changed = known === undefined || queries.laid.each().length > 0 || queries.paved.each().length > 0 || despawned.entities.all().some((id) => known.has(id))
if (!changed) return
const grid = new GridBuilder(resources.land.get().mask)
const tiles = new Set<number>()
+ const paved = new Set<number>()
for (const { entity, data } of queries.tiles.each()) {
- grid.claim(data.tile.get(), entity.id, useOf(data))
+ const t = data.tile.get()
+ grid.claim(t, entity.id, useOf(data))
tiles.add(entity.id)
+ if (data.road.present && data.paved.present) paved.add(key(t.x, t.y))
}
const value = grid.value()
- resources.grid.set({ ...value, roads: roadPrint(value), tiles })
+ resources.grid.set({ ...value, roads: roadPrint(value), tiles, paved })
}
)
diff --git a/src/ui.ts b/src/ui.ts
index 9cc8774..861f78b 100644
--- a/src/ui.ts
+++ b/src/ui.ts
@@ -5,10 +5,37 @@
* None of it is saved: it is host state, handed to systems as a service.
*/
import type { Amounts, CharterValue, GoodId, GroundId, KindId, PropId, Tier, WinterId } from "./content.ts"
+import type { IconName } from "./icons.ts"
import type { Point } from "./iso.ts"
import type { Status } from "./schema.ts"
import type { OverlayCell } from "./render3d/models.ts"
+/** How a line of a panel reads: fine, worth a look, wrong, or an aside. */
+export type Tone = "ok" | "warn" | "bad" | "dim"
+/**
+ * A line of a building's or home's description: an icon, what it is about,
+ * its value, and (when something is wrong, or worth knowing) a note
+ * underneath saying why and what to do. `goods` are shown as icon chips.
+ */
+export interface Line {
+ readonly icon: IconName | GoodId
+ readonly label: string
+ readonly value?: string | undefined
+ readonly note?: string | undefined
+ readonly tone?: Tone | undefined
+ readonly goods?: ReadonlyArray<{ readonly good: GoodId; readonly count: number }> | undefined
+}
+
+/** Something that needs looking at now, and where (when it is somewhere). */
+export interface Alert {
+ readonly text: string
+ readonly at: Point | null
+ /** The footprint there, cells a side, for the outline. */
+ readonly size: number
+ /** The entity to select on the way there, if there is one. */
+ readonly id: number | null
+}
+
export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place" | "ground" | "prop"
/** What the map shows over the town: nothing, or one of its views, cell by cell. */
@@ -61,6 +88,10 @@ export interface Preview {
ghosts: Array<{ readonly what: KindId | "home"; readonly cell: Point }>
/** Road cells about to be laid. */
roads: Array<Point>
+ /** Road cells a thing being placed would reach: a service's walkers, or the commute its workers (or a home's residents) make. */
+ range: Array<Point>
+ /** What `range` shows, for the tooltip. */
+ rangeNote: string | null
/** Park cells about to be laid or furnished, as they will look. */
parks: Array<{ readonly x: number; readonly y: number; readonly ground: GroundId; readonly prop: PropId | "none" }>
/** The entity under the pointer. */
@@ -70,7 +101,7 @@ export interface Preview {
tooltip: string | null
}
-export const emptyPreview = (): Preview => ({ plots: [], ghosts: [], roads: [], parks: [], hover: null, danger: false, tooltip: null })
+export const emptyPreview = (): Preview => ({ plots: [], ghosts: [], roads: [], range: [], rangeNote: null, parks: [], hover: null, danger: false, tooltip: null })
/** The side panel: the build menu, the town's numbers and taxes, a building, or a home. */
export type Panel =
@@ -87,14 +118,16 @@ export type Panel =
/** Whether it can be paused (not the town hall, not a site), and whether it is. */
readonly pausable: boolean
readonly paused: boolean
- readonly lines: ReadonlyArray<string>
+ readonly lines: ReadonlyArray<Line>
}
| {
readonly type: "house"
readonly id: number
readonly cell: Point
readonly tier: Tier
- readonly lines: ReadonlyArray<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>
}
| {
readonly type: "park"
@@ -104,14 +137,14 @@ export type Panel =
readonly cells: number
readonly value: number
readonly reach: number
- readonly lines: ReadonlyArray<string>
+ readonly lines: ReadonlyArray<Line>
}
| {
readonly type: "ruin"
readonly id: number
readonly cell: Point
readonly cause: "burnt" | "collapsed" | "derelict"
- readonly lines: ReadonlyArray<string>
+ readonly lines: ReadonlyArray<Line>
}
/** A thing's hit area for the pointer, nearest first. */
@@ -125,6 +158,8 @@ export interface HitBox {
export interface Stats {
readonly coins: number
readonly taxes: number
+ /** What the same homes would pay a minute with every need met: taxes left on the table when it is more. */
+ readonly suppliedTaxes: number
readonly trade: number
readonly upkeep: number
readonly admin: number
@@ -149,6 +184,8 @@ export interface Stats {
readonly burghers: number
readonly jobs: number
readonly employed: number
+ /** Workplaces short of workers, to step through from the jobs counter. */
+ readonly shortStaffed: ReadonlyArray<{ readonly id: number; readonly title: string; readonly cell: Point; readonly size: number; readonly assigned: number; readonly needed: number; readonly nobodyNear: boolean }>
readonly charter: CharterValue
/** Minutes into the term. */
readonly minute: number
@@ -211,9 +248,9 @@ export interface Stats {
readonly approval: number
readonly net: number
}>
- readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean }>
+ readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean; readonly at: Point | null }>
/** What needs looking at right now, a line each: workshops waiting, workplaces no one can reach, food running out. */
- readonly alerts: ReadonlyArray<string>
+ readonly alerts: ReadonlyArray<Alert>
}
/** A map view's legend: what each colour means. */
@@ -254,6 +291,10 @@ export interface UiValue {
/** The map view shown over the town, its cells (rebuilt as the town changes), and its legend. */
view: View
overlay: { readonly key: string; readonly cells: ReadonlyArray<OverlayCell> }
+ /** The view's colour for each building and home, washed over the model itself so it reads from above. */
+ tints: ReadonlyMap<number, number>
legend: Legend | null
+ /** A place the page points at (from the ticker): outlined until `until`, in the clock's seconds. */
+ flash: { readonly cell: Point; readonly size: number; readonly until: number } | null
toast: (message: string) => void
}
diff --git a/test/legibility.test.ts b/test/legibility.test.ts
new file mode 100644
index 0000000..d774639
--- /dev/null
+++ b/test/legibility.test.ts
@@ -0,0 +1,120 @@
+/**
+ * Legibility: when a home is stuck, the game must say why in words that
+ * name the cause. The bots win because they know the thresholds; a player
+ * only learns them from the panel. These tests hold the panel's reasons to
+ * the usual dead ends: cloth withheld from a poor street, no walker in
+ * reach, nothing in store, a workshop no one can walk to; and they play a
+ * real town into the commonest one (cottages beside a quarry) and check
+ * what the rules then say about it.
+ */
+import assert from "node:assert/strict"
+import { test } from "node:test"
+
+import { COMMUTE, home, kinds, type CharterValue } from "../src/content.ts"
+import { appealAt } from "../src/appeal.ts"
+import { canPlace, GridBuilder, type Use } from "../src/grid.ts"
+import type { Snapshot } from "../src/sim/headless.ts"
+import { blockers, streetShort, whyUnmet, type InTown, type Served, type Street } from "../src/rules/explain.ts"
+import { capacity, streetRoom, streetTax, taxOf } from "../src/rules/households.ts"
+import { approvalTarget, grudgeAfter } from "../src/rules/approval.ts"
+import { headless } from "../src/sim/headless.ts"
+
+const settlers = { tier: 1 as const, residents: 4, food: 100, bread: 100, cloth: 0, faith: 100, clock: 0 }
+const plenty: InTown = { fish: 20, smoked: 0, bread: 30, cloth: 188 }
+const served: Served = { goods: true, faith: true }
+const quarryStreet: Street = { desirability: -4, parts: [{ label: "quarry", value: -6 }, { label: "chapel", value: 2 }] }
+
+test("cloth withheld from a poor street is told as the street, not as missing cloth", () => {
+ const 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/)
+ 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, /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, { 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/)
+ assert.match(whyUnmet("food", { ...settlers, food: 0 }, fine, { fish: 0, smoked: 0, bread: 0, cloth: 0 }, served)!, /no food in store/)
+ assert.equal(streetShort(quarryStreet, 5), "−4 here, 5 needed: quarry −6")
+})
+
+test("desirability counts point by point: a cottage beside a quarry empties a little and pays less", () => {
+ assert.equal(streetRoom(0), 1)
+ assert.ok(streetRoom(-4) < 0.7 && streetRoom(-4) > 0.6)
+ assert.equal(streetRoom(-30), home.street.roomLeast)
+ assert.equal(capacity(settlers, 0, 0), 4)
+ assert.equal(capacity(settlers, 0, -4), 3)
+ assert.equal(capacity(settlers, 30, -8), 2, "even a town that approves of its mayor will not fill a cottage beside a quarry")
+ assert.ok(streetTax(6) > 1 && streetTax(-6) < 1)
+ const fed = { ...settlers, bread: 100 }, plain = { ...settlers, bread: 0 }
+ assert.ok(taxOf(fed, { settlers: 100, citizens: 100 }) > taxOf(plain, { settlers: 100, citizens: 100 }), "bread on the table pays")
+ assert.equal(taxOf({ ...settlers, food: 0 }, { settlers: 100, citizens: 100 }), 0, "no food, no taxes")
+ assert.ok(taxOf(fed, { settlers: 100, citizens: 100 }) >= 1.5 * taxOf(plain, { settlers: 100, citizens: 100 }), "a cottage with bread pays half again a merely fed one")
+})
+
+test("a grudge over high taxes builds, holds, and fades slowly", () => {
+ let memory = 0
+ for (let i = 0; i < 60; i++) memory = grudgeAfter(memory, 200)
+ assert.ok(memory >= 200, `ten minutes at 200% is a grudge of ${memory / 10} points`)
+ const squeezed = approvalTarget([settlers], { settlers: 50, citizens: 50 }, 100, 0, false, undefined, memory)
+ const spared = approvalTarget([settlers], { settlers: 50, citizens: 50 }, 100, 0, false, undefined, 0)
+ assert.ok(squeezed.target < spared.target - 15, "cutting taxes at the end does not wipe the grudge")
+ let later = memory
+ for (let i = 0; i < 30; i++) later = grudgeAfter(later, 50)
+ assert.ok(later < memory && later > 0, "it fades over minutes, not at once")
+ assert.equal(grudgeAfter(0, 100), 0)
+})
+
+/** The grid as the town's edits see it, from a snapshot: where a building could go. */
+const gridOf = (s: Snapshot) => {
+ const g = new GridBuilder(s.resources["Town/Land"].mask)
+ for (const e of s.entities) {
+ const c = e.components
+ if (!c["Town/Tile"]) continue
+ const use: Use = c["Town/Road"] ? "road" : c["Town/Park"] ? "park" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"
+ g.claim(c["Town/Tile"], e.id, use)
+ }
+ return g.value()
+}
+
+test("a real town: cottages beside a quarry are told why they will not grow", { timeout: 120000 }, () => {
+ const charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }
+ const town = headless(charter)
+ const hall = town.snapshot().entities.find((e) => e.components["Town/TownHall"])!
+ const t = hall.components["Town/Tile"] as { x: number; y: number; size: number }
+ // A street east of the hall's ring, cottages along its north side, and a quarry on the south side, right across from them.
+ const y = t.y + 1
+ const road = Array.from({ length: 9 }, (_, i) => ({ x: t.x + t.size + 1 + i, y }))
+ const homes = Array.from({ length: 4 }, (_, i) => ({ x: t.x + t.size + 2 + i, y: y - 1 }))
+ town.edit({ type: "roads", cells: road }, { type: "homes", cells: homes })
+ town.run(1)
+ const grid = gridOf(town.snapshot())
+ const spot = road.map((c) => ({ x: c.x, y: y + 1 })).find((c) => canPlace(grid, { ...c, size: kinds.quarry.size }))
+ assert.ok(spot, "somewhere along the street a quarry fits; change the seed if the land has moved")
+ town.edit({ type: "building", kind: "quarry", cell: spot, open: false })
+ town.run(90)
+ const s = town.snapshot()
+ const cottages = s.entities.filter((e) => e.components["Town/House"] && homes.some((h) => h.x === e.components["Town/Tile"].x && h.y === e.components["Town/Tile"].y))
+ assert.ok(cottages.length >= 2, "the scenario lays cottages on this seed; change the seed or the cells if the land has moved")
+ assert.ok(s.entities.some((e) => e.components["Town/Building"]?.kind === "quarry" && !e.components["Town/Site"]), "the quarry stands")
+ const cells = s.resources["Town/Appeal"].cells as ReadonlyArray<number>
+ const worst = cottages.map((e) => appealAt(cells, e.components["Town/Tile"].x, e.components["Town/Tile"].y)).sort((a, b) => a - b)[0]!
+ assert.ok(worst < 0, `a cottage beside a quarry is on a poor street (${worst})`)
+ 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 === "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")
+ // A workplace with nobody in reach says so in the same breath.
+ assert.ok(COMMUTE === 15)
+})
diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.ts
index b5e5c53..4558210 100644
--- a/tools/balance/model/analyze.ts
+++ b/tools/balance/model/analyze.ts
@@ -94,7 +94,7 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
if (foodCeiling < needBounds.food.min) findings.push({ code: "food-impossible", confidence: "upper-bound", detail: `Even pooled food capacity ${foodCeiling.toFixed(2)}/min before spoilage is below the no-waste minimum ${needBounds.food.min.toFixed(2)}/min; existing reserves may bridge a finite interval` })
if (net.cloth < needBounds.cloth.min) findings.push({ code: "cloth-capacity", confidence: "upper-bound", detail: `Cloth capacity ${net.cloth.toFixed(2)}/min cannot keep ${clothHomes} eligible homes supplied` })
const hall = s.buildings.find((b) => b.kind === "townhall"), hallRoads = hall ? reach(g, doors(g, hall.tile)) : null
- const taxes = s.homes.reduce((sum, h) => sum + (hallRoads && nearest(hallRoads, doors(g, h.tile)) ? taxOf(h, s.policy, rules) : 0), 0)
+ const taxes = s.homes.reduce((sum, h) => sum + (hallRoads && nearest(hallRoads, doors(g, h.tile)) ? taxOf(h, s.policy, rules, appealAt(appeal, h.tile.x, h.tile.y)) : 0), 0)
const upkeep = s.buildings.filter((b) => !b.site).reduce((sum, b) => sum + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)
const parkCost = (s.parks ?? []).reduce((n, p) => n + parkUpkeep(p, rules), 0)
const collection = baseCollection(taxes, upkeep + parkCost, s.homes.length, rules), cashPerMinute = collection.delta * 60 / (rules.ledgerTicks * rules.stepSeconds)
diff --git a/tools/balance/model/project.ts b/tools/balance/model/project.ts
index 8309f85..3f752e3 100644
--- a/tools/balance/model/project.ts
+++ b/tools/balance/model/project.ts
@@ -163,7 +163,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
for (const g of goodIds) stock[g] = Math.max(0, stock[g] - spoilExpectation(stock[g], g, keeps, rules))
}
if (Math.floor(elapsed / (rules.ledgerTicks * rules.stepSeconds)) > Math.floor(second / (rules.ledgerTicks * rules.stepSeconds))) {
- const tax = homes.reduce((n, h) => n + (analysis.household.find((a) => a.id === h.id)?.taxConnected ? taxOf(h, scenario.policy, rules) : 0), 0), upkeep = buildings.reduce((n, b) => n + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)
+ const tax = homes.reduce((n, h) => { const a = analysis.household.find((a) => a.id === h.id); return n + (a?.taxConnected ? taxOf(h, scenario.policy, rules, a.desirability) : 0) }, 0), upkeep = buildings.reduce((n, b) => n + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)
const parkCost = parks.reduce((n, p) => n + parkUpkeep(p, rules), 0)
coins += baseCollection(tax, upkeep + parkCost, homes.length, rules).delta
if (scenario.trade) {