Skip to content

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

A town that looks and works like a real one

Claude4ba881d3a864
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index 2efc556..5a1d606 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -68,21 +68,21 @@ and elevation controls also work with a keyboard. The original view uses a
| Collection | Models | Coverage |
| --- | ---: | --- |
-| Buildings | 16 | Every building kind, with its roof, topper and yard |
-| Homes | 8 | Both tiers in all four roof palettes |
+| Buildings | 28 | Every building kind, with its roof, topper and yard (the twelve added with the neighbourhood are placeholders, see below) |
+| Homes | 9 | Settlers' and citizens' homes in all four roof palettes, and the placeholder townhouse |
| Land | 19 | Three tree shapes at three growth stages, stone and ore in both resource states, four crop stages, roads and water |
| People | 27 | Carriers, settlers, citizens, market and chapel walkers, all six hats and the sixteen reference-gallery residents |
-| Cargo and vehicles | 69 | Eleven distinct goods and labelled crates; empty handcart/barrow and small/full loads of each good; the approved mixed goods plate |
-| Construction and effects | 10 | Empty/supplied sites, frame/walls, problem sign, smoke and four placement/reach outlines |
+| Cargo and vehicles | 75 | Twelve distinct goods and labelled crates; empty handcart/barrow and small/full loads of each good; the approved mixed goods plate |
+| Construction and effects | 20 | Empty/supplied sites, frame/walls, problem sign, smoke, four placement/reach outlines, and the placeholder ruins, warning signs, and flames |
-The 149 entries cover object families and representative seeded variants.
+The 178 entries cover object families and representative seeded variants.
Continuous growth, construction progress, walk poses and colours can be
generated; this is not a list of every possible random seed. Page icons
remain the game's original 2D UI art.
![Complete 3D world catalogue at a rotated angle](screenshots/3d-catalogue.webp)
-`pnpm assets:build` exports 149 GLBs and editable geometry descriptions,
+`pnpm assets:build` exports 178 GLBs and editable geometry descriptions,
a manifest, and two standalone viewers to `output/inkline-3d/`:
`inkline-3d-study.html` and `inkline-3d-map.html`. It reimports every GLB and
checks geometry and unlit materials. The viewers work without a dev server;
@@ -113,7 +113,7 @@ Double-click the ground to focus the camera there.
![Every model together on the review island](screenshots/3d-map-complete.webp)
District shortcuts focus the town, workshops, homes, people, cargo yard or
-forest. Inspect selects any of the 149 models and links to its original
+forest. Inspect selects any of the 178 models and links to its original
drawing comparison. Eight additional people walk along the street using two
procedural poses; pause them for review. Smoke and the problem sign face
the camera so they stay readable when the map turns.
@@ -142,12 +142,31 @@ That is how the README's screenshots of grown towns were made.
- `src/archetypes.ts`: content to components.
- `src/mapgen.ts`: the land of a new town, from its charter.
- `src/schema.ts`: the ECS world: components, relations, resources, services.
+- `src/appeal.ts`: desirability: what buildings and the land do to the cells around them, the whole grid, and one cell explained.
+- `src/places.ts`: street names for the news ("Mill Lane"), from the nearest landmark.
- `src/grid.ts`: occupancy, entrances, reach, and road paths.
-- `src/sim/`: the fixed-step simulation (no renderer access): edits, work, logistics, walkers, town, and the term
- (seasons, the crown, approval, the end of the term, history).
+- `src/sim/`: the fixed-step simulation (no renderer access): edits, work (staffing by crew and commute, tools,
+ pace), logistics, walkers (services, mending), town (households and tiers), hazards (desirability, risk
+ meters, fire and firefighters, sickness, theft), decay (wear, collapse, spoilage, the pantry), and the term
+ (seasons and the almanac, the crown, approval, the end of the term, history).
- `src/present.ts`: per-frame interaction, panel, and view sync.
- `src/art.ts`: all drawing: buildings and their yards, homes, the land, roads, carts, and figures.
-- `src/render3d/`: live world renderer, model instances, camera and map input.
+- `src/render3d/`: live world renderer, model instances, camera and map input, the map views' overlay,
+ warning signs, flames, ruins, and winter frost.
+- `src/asset-lab/placeholders.ts`: stand-in models for ornaments, ruins, warning signs, and flames.
+
+**Placeholders.** The neighbourhood brought kinds with no approved model yet.
+They are drawn so the game is playable, and are meant to be replaced:
+the granary, smokehouse, fire watch, healer, hospital, watch house, and
+builder's yard use the generic building in their colour; the garden, park,
+fountain, statue, and plaza are simple shapes (`placeholders.ts`, and
+`drawDecor` in `art.ts` for the menu pictures); the townhouse is the
+citizens' home raised a storey; ruins, the warning signs over homes,
+and flames are simple stand-ins; a paved street is the road with setts
+drawn on it; a home's neighbourhood (fine or poor) and a run-down building
+are shown only as a tint, not as fences, gardens, or a patched roof; and
+winter frosts the land and tints what stands, rather than putting snow on
+roofs.
- `src/townsfolk.ts`: residents out walking, for looking at only: not simulated, not saved.
- `src/icons.ts`: the page's line-drawn icons.
- `src/gallery.ts`: the dev-only art gallery (see above).
@@ -176,7 +195,12 @@ averaged over the seeds still in office every few minutes.
```sh
pnpm balance -- --size large --term 90 --land harsh
-pnpm balance -- --bot greedy # sensible (default), greedy (taxes at 200%, sells everything, ignores the crown), idle
+pnpm balance -- --bot greedy # sensible (default), greedy (taxes at 200%, sells everything, ignores the crown), idle,
+ # crowded (homes packed beside industry, no ornaments), uncovered (no fire, health, or order services)
+pnpm balance -- --versus crowded # the bot against another on the same seeds: citizens, burghers, homes lost
+pnpm balance -- --versus uncovered
+pnpm balance -- --set kinds.sawmill.crew=settlers --set risk.fire.wooden=0 # content changes, numbers or words
+CHRONICLE=1 pnpm balance -- --seeds 1 # each seed's chronicle too
pnpm balance -- --seeds 4 --from 4 # seeds 4 to 7, to split a sweep across processes
pnpm balance -- --set crown.fine=2 --set kinds.fishery.recipe.seconds=3
pnpm balance -- --seeds 1 --verbose --every 1 # minute by minute
@@ -204,7 +228,14 @@ always make the same town. `RUNS=200 pnpm test` searches harder;
`pnpm check` puts the real simulation into each way a term can end
(complete, bankrupt, revolt, abandoned, dismissed, run out), checks an unanswered
-crown request, and checks that a town saved mid-term loads back the same.
+crown request, and checks that a town saved mid-term loads back the same. It
+also checks the neighbourhood: a citizens' home next to a smithy goes back to
+settlers; an unwatched row of cottages catches fire and the fire spreads, and
+firefighters from a fire watch stop it at one home; fish rots in the town
+hall and keeps in a granary; a workplace with no homes within reach stays
+unstaffed until a cottage goes up on its road; citizens will not do settlers'
+work while settlers stand in for citizens as apprentices; and a home nobody
+mends falls down while one by a builder's yard is kept.
## Releasing to Cloudflare
diff --git a/README.md b/README.md
index 8e192ea..71a8524 100644
--- a/README.md
+++ b/README.md
@@ -47,6 +47,26 @@ cottages grow into two-story citizens' homes that hold and pay twice as
much. Then they come out in long coats and top hats, each household dressed
in the colour of its roof.
+## A town that looks and works like a real one
+
+Every street has a desirability. A smithy or a quarry drags it down for
+several cells around; gardens, parks, fountains, statues, a chapel, and
+paved streets lift it. Citizens will only live on a decent street, and the
+finest streets, with every service calling, grow three-storey townhouses.
+Settlers do the rough work and citizens the skilled, and nobody walks more
+than fifteen road cells to a job, so the far-off mine needs its own
+workers' cottages. Zone the town well and it sorts itself into a fine
+centre, an industrial edge, and cottages by the mill.
+
+Then keep it standing. A fire watch, a healer, and a watch house send
+walkers to keep down the risk of fire, sickness, and theft; a sign goes up
+over a home long before disaster, and a fire watch's firefighters race to
+any blaze. Fish and bread rot unless a granary keeps them, tools wear out,
+and a builder's yard has to mend what runs down. Each year's winter is
+mild, normal, or hard, and the almanac tells you which a year ahead. Map
+views show desirability, workers, fire, health, order, and condition across
+the town.
+
## Govern under pressure
The bigger the town, the harder it pulls. Winters stop the fields and thin
diff --git a/docs/how-to-play.md b/docs/how-to-play.md
index c8d0b18..5238119 100644
--- a/docs/how-to-play.md
+++ b/docs/how-to-play.md
@@ -17,10 +17,12 @@ 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) |
| **H** | homes: drag to lay a row along a road |
| **B** | build: pick a building, then click the map |
| **X** | bulldoze |
| **T** | the town panel: goals, approval, treasury, taxes, people, the crown, trade |
+| **D**, **W**, **F**, **A**, **O**, **C** | map views: desirability, workers, fire, health (aid), order, condition; the same key again hides it |
| **space** | pause |
| **1**, **2**, **3** | run at 1×, 2×, 4× |
| **Esc** | stop placing, close the panel |
@@ -65,6 +67,81 @@ New town and load ask before they replace the town you have.
is judged flourishing, holding on, or declining. The reckoning shows the
term's history and its chronicle.
+## The neighbourhood
+
+The town is meant to look and work like a real one: a fine centre, an
+industrial edge, and workers' cottages clustered by the mill or the mine.
+Nobody tells you to build it that way; it works best that way.
+
+- **Desirability.** Every cell has one. Buildings and the land add to it or
+ take from it, fading with distance: a smithy, quarry, or mine takes 8
+ 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 garden 3, a park or fountain 6, a statue or plaza 10, 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. Ornaments cost upkeep: a fine
+ centre is something you choose to pay for.
+- **Tiers.** Settlers live anywhere. A citizens' home needs desirability 5
+ as well as bread, cloth, and faith; a home whose street drops below 5
+ goes back to settlers even with every need met. A **townhouse** of
+ burghers (12 residents, the best taxes) needs desirability 15 and a
+ fire watch, a healer, and a watch house all calling on it. At
+ desirability −5 or less a home is squalid and holds fewer people.
+- **Workers by tier, and the commute.** Settlers do the rough work
+ (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
+ 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
+ reach.
+
+## Services, and what goes wrong without them
+
+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 | Building | What raises the risk | If neglected |
+|---|---|---|---|
+| fire | **fire watch**: a watchman, and firefighters who run to any blaze | wooden settlers' cottages, a bakery, smithy, or smokehouse within two cells, crowding, a run-down building, heating in a hard winter | the home catches fire; it burns for 20 seconds and may set its neighbours alight. When firefighters arrive, that house is lost but the fire goes no further. A ruin is left to clear |
+| health | **healer**, later a **hospital** | hunger, crowding, desirability below 0, a quarry's or mine's dust, still water | sickness: the home holds half as many until it passes or a physician calls, and it raises the risk of homes around it |
+| order | **watch house**: a constable | approval below 0, desirability below 0, a half-empty home, a burghers' townhouse | a theft (coins, or goods when the treasury is empty), then the home is left derelict |
+
+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.
+
+## 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.
+- **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.
+- **Buildings and homes run down**, in about half an hour to half and an
+ hour and more to nothing. A **builder's yard** sends a builder to mend whatever is run
+ down along the way, a plank for a home and a plank and a stone for a
+ building. Below half, a workshop works at half pace and its fire risk
+ rises, and a home looks worn and drags its street down; at nothing it
+ falls into a ruin.
+- **Winters vary**: each year's is mild (fishing at 75%), normal (50%), or
+ hard (half as long again, fishing at 25%, and heating raises every home's
+ fire risk), rolled from the seed. The almanac in the clock shows the
+ coming winter a year ahead (hover it for the one after), a minute before
+ each winter the news says how much food is in store and how much the
+ town eats a minute, and through winter the map lies frosted.
+
## How the town works
- **A new town** has a town hall in a clearing, ringed by road, plus
@@ -78,14 +155,18 @@ New town and load ask before they replace the town you have.
- **Materials** (planks, stone, tools) come from storage: a new building is a
site until carriers have brought what it costs, then it goes up.
- **Homes** fill with settlers once a road touches them. Settlers need food
- (fish or bread); with bread, cloth, and faith a home becomes a two-story
- citizens' home that holds and pays twice as much.
-- **Buildings** need a road at the middle of a side and workers from the
- homes. Gatherers work the land within their reach (trees, rocks, water,
+ (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.
+- **Buildings** need a road at the middle of a side and workers of their
+ crew from homes within 15 road cells. Ornaments 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
wants it (a site, a workshop, a market) or else to storage; storage sends
to whoever wants what it holds.
- **Walkers** from the town hall and markets hand out food and cloth to the
- homes they pass; the chapel's brings faith.
+ homes they pass; the chapel's brings faith; a fire watch's, a healer's,
+ and a watch house's keep down the risks; a builder's mends.
- Larger buildings unlock as the town grows (by residents, then citizens).
diff --git a/scripts/balance.ts b/scripts/balance.ts
index 827f8bf..81b9b2d 100644
--- a/scripts/balance.ts
+++ b/scripts/balance.ts
@@ -5,7 +5,8 @@
*
* node scripts/balance.ts 5 seeds, a medium fair town, a 60-minute term
* node scripts/balance.ts --size large --term 90 --land harsh
- * node scripts/balance.ts --bot greedy sensible (default), greedy, or idle
+ * node scripts/balance.ts --bot greedy sensible (default), crowded, uncovered, greedy, or idle
+ * node scripts/balance.ts --versus crowded the bot against another on the same seeds, side by side
* node scripts/balance.ts --seeds 10 --from 10 seeds 10 to 19 (to split a sweep across processes)
* node scripts/balance.ts --set crown.fine=2 --set kinds.fishery.recipe.seconds=3
* node scripts/balance.ts --verbose every seed's table, every `--every` minutes (default 5)
@@ -17,14 +18,30 @@
* and tools its land runs out of;
* - greedy: the same town, taxed at 200%, selling everything it can and
* ignoring the crown;
- * - idle: founds the basics, then leaves the town to itself.
+ * - idle: founds the basics, then leaves the town to itself;
+ * - crowded: the sensible mayor, but homes packed in beside the industry,
+ * and no gardens, parks, statues, or paving;
+ * - uncovered: the sensible mayor, but no fire watch, healer, or watch house.
*
- * `--set` changes content before the run. The bot only does what a player
+ * The sensible mayor also keeps homes off squalid streets and dirty
+ * workshops a little way from homes, plants gardens and paves streets where
+ * homes are just short of the next tier, sends for a fire watch, a healer,
+ * or a watch house when warning signs go up over a few homes and for a
+ * builder when homes start to run down, clears ruins, and puts workers'
+ * cottages beside a workplace no settler can walk to.
+ *
+ * `--set` changes content before the run (numbers, or words such as a crew).
+ *
+ * To see why a run went the way it did: `CHRONICLE=1` prints each seed's
+ * chronicle, `TRACE=1` the citizens' chain minute by minute, `SPEND=1` the
+ * ledger and what the bot spent every five minutes, `DEBUG_PLAN=1` what it
+ * wants at each decision, and `DEBUG=1` every edit it pushes. The bot only does what a player
* could: it reads the world, then pushes the same edits the page does.
*/
import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, type Amounts, type CharterValue, type GoodId, type Kind, type KindId } from "../src/content.ts"
import * as content from "../src/content.ts"
import { around, canPlace, DIRS, entrances, GridBuilder, isRoad, key, useAt, type Use } from "../src/grid.ts"
+import { ringOf } from "../src/appeal.ts"
import { GRID, inside, type Point } from "../src/iso.ts"
import type { GridValue } from "../src/schema.ts"
import { headless, type Snapshot } from "../src/sim/headless.ts"
@@ -45,22 +62,32 @@ const from = Number(option("from", "0"))
const size = option("size", "medium") as CharterValue["size"]
const land = option("land", "fair") as CharterValue["land"]
const term = Number(option("term", "60"))
-const bot = option("bot", "sensible") as "sensible" | "greedy" | "idle"
+type Bot = "sensible" | "greedy" | "idle" | "crowded" | "uncovered"
+const bots: ReadonlyArray<Bot> = ["sensible", "greedy", "idle", "crowded", "uncovered"]
+/** `--versus <bot>`: run another bot on the same seeds and compare. */
+const versus = option("versus", "") as Bot | ""
+let bot = option("bot", "sensible") as Bot
const every = Number(option("every", "5"))
const verbose = args.includes("--verbose")
/** `--snapshot <minute>`: write each seed's town at that minute to `--out` (default `snapshots/`), as a save file. */
const snapshotAt = Number(option("snapshot", "0"))
const out = option("out", "snapshots")
-if (!sizeIds.includes(size) || !landIds.includes(land) || !["sensible", "greedy", "idle"].includes(bot)) throw new Error("Unknown --size, --land, or --bot")
+if (!sizeIds.includes(size) || !landIds.includes(land) || !bots.includes(bot) || (versus !== "" && !bots.includes(versus))) throw new Error("Unknown --size, --land, --bot, or --versus")
+/** Mayors who look after the neighbourhood: gardens, paving, homes away from industry. */
+const zoned = () => bot !== "crowded" && bot !== "idle"
+/** Mayors who keep fire watches, healers, and watch houses. */
+const covered = () => bot !== "uncovered" && bot !== "idle"
+/** Mayors who run the town as the sensible one does (taxes, trade, the crown). */
+const sensible = () => bot === "sensible" || bot === "crowded" || bot === "uncovered"
-/** `--set path=value`: change a number in the content before running. */
+/** `--set path=value`: change a number (or a word, such as a crew) in the content before running. */
for (let i = 0; i < args.length; i++) {
if (args[i] !== "--set") continue
const [path, value] = args[i + 1]!.split("=")
const parts = path!.split(".")
let target = content as unknown as Record<string, unknown>
for (const part of parts.slice(0, -1)) target = target[part] as Record<string, unknown>
- target[parts.at(-1)!] = Number(value)
+ target[parts.at(-1)!] = value === "" || Number.isNaN(Number(value)) ? value : Number(value)
}
// ── Reading the world ─────────────────────────────────────────────────────
@@ -73,11 +100,26 @@ interface Tile {
interface World {
readonly grid: GridValue
+ /** Desirability by cell (see `appeal.ts`), paved road cells, and ruins. */
+ readonly appeal: ReadonlyArray<number>
+ readonly paved: ReadonlySet<number>
+ readonly ruins: ReadonlyArray<{ readonly id: number; readonly tile: Tile }>
/** Cells of ore rocks (other rocks are stone). */
readonly ore: ReadonlySet<number>
- readonly buildings: ReadonlyArray<{ readonly kind: KindId; readonly tile: Tile; readonly status: string; readonly site: boolean }>
- readonly homes: ReadonlyArray<{ readonly tile: Tile; readonly tier: number; readonly residents: number }>
+ readonly buildings: ReadonlyArray<{ readonly kind: KindId; readonly tile: Tile; readonly status: string; readonly site: boolean; readonly nearby: number }>
+ readonly homes: ReadonlyArray<{
+ readonly tile: Tile
+ readonly tier: number
+ readonly residents: number
+ readonly site: boolean
+ readonly risk: { readonly fire: number; readonly health: number; readonly order: number }
+ readonly condition: number
+ /** Bread, cloth, and faith all met: only its street keeps it from being a citizens' home. */
+ readonly provided: boolean
+ }>
readonly stock: Amounts
+ /** Each good's price with traders, in percent of the usual. */
+ readonly prices: Amounts
readonly coins: number
readonly census: Record<string, number>
readonly ledger: { readonly taxes: number; readonly trade: number; readonly upkeep: number; readonly admin: number }
@@ -96,23 +138,40 @@ const read = (snapshot: Snapshot): World => {
const homes: Array<World["homes"][number]> = []
const stock: Record<string, number> = Object.fromEntries(goodIds.map((g) => [g, 0]))
const ore = new Set<number>()
+ const paved = new Set<number>()
+ const ruins: Array<World["ruins"][number]> = []
for (const e of snapshot.entities) {
const c = e.components
const tile = c["Town/Tile"] as Tile | undefined
if (!tile) continue
- const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : "building"
+ const use: Use = c["Town/Road"] ? "road" : 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"
builder.claim(tile, e.id, use)
if (c["Town/Rock"]?.ore) ore.add(key(tile.x, tile.y))
- if (c["Town/Building"]) buildings.push({ kind: c["Town/Building"].kind, tile, status: c["Town/Status"], site: !!c["Town/Site"] })
- if (c["Town/House"]) homes.push({ tile, tier: c["Town/House"].tier, residents: c["Town/House"].residents })
+ if (c["Town/Paved"]) paved.add(key(tile.x, tile.y))
+ if (c["Town/Ruin"]) ruins.push({ id: e.id, tile })
+ if (c["Town/Building"]) buildings.push({ kind: c["Town/Building"].kind, tile, status: c["Town/Status"], site: !!c["Town/Site"], nearby: c["Town/Staff"]?.nearby ?? 0 })
+ if (c["Town/House"])
+ homes.push({
+ tile,
+ tier: c["Town/House"].tier,
+ residents: c["Town/House"].residents,
+ site: !!c["Town/Site"] || !!c["Town/Rising"],
+ risk: c["Town/Risk"] ?? { fire: 0, health: 0, order: 0 },
+ condition: c["Town/Condition"]?.value ?? 1000,
+ provided: c["Town/House"].bread > 0 && c["Town/House"].cloth > 0 && c["Town/House"].faith > 0
+ })
if (c["Town/Storage"] && c["Town/Inventory"]) for (const g of goodIds) stock[g] = (stock[g] ?? 0) + c["Town/Inventory"].stock[g]
}
return {
grid: builder.value(),
+ appeal: r["Town/Appeal"].cells,
+ paved,
+ ruins,
ore,
buildings,
homes,
stock: stock as Amounts,
+ prices: r["Town/Market"].prices,
coins: r["Town/Treasury"].coins,
census: r["Town/Census"],
ledger: r["Town/Ledger"],
@@ -161,13 +220,33 @@ const spotFor = (w: World, kind: Kind): Point | null => {
if (s < needs) continue
// A forester belongs beside a lumberjack, replanting what it fells.
if (kind.id === "forester" && !w.buildings.some((b) => b.kind === "lumberjack" && Math.abs(b.tile.x - x) <= 5 && Math.abs(b.tile.y - y) <= 5)) continue
- const value = (kind.gathers || kind.plants ? s * 10 : 0) - Math.hypot(x - middle, y - middle)
+ // A zoning mayor keeps dirty workshops a couple of cells clear of homes; services go among the homes.
+ const dirty = zoned() && (kind.appeal?.value ?? 0) <= -4 && !kind.gathers ? Math.min(2, nearestHome(w, tile)) * 2 : 0
+ // A fire watch, healer, or watch house goes among the homes whose signs are up; a builder among run-down ones.
+ const risky = kind.service?.service === "fire" || kind.service?.service === "health" || kind.service?.service === "order" ? kind.service.service : null
+ const amid = risky !== null
+ ? w.homes.filter((h) => h.risk[risky] >= content.risk.warn * 0.6 && ringOf(tile, h.tile.x, h.tile.y) <= 6).length * 3
+ : kind.service?.service === "repair"
+ ? w.homes.filter((h) => h.condition < 700 && ringOf(tile, h.tile.x, h.tile.y) <= 6).length * 3
+ : kind.service && kind.id !== "market" ? homesAround(w, tile, 4) : 0
+ // Workers walk at most `COMMUTE` road cells: a workplace well away from every home stands empty.
+ if (w.homes.length > 0 && kind.workers > 0 && nearestHome(w, tile) > 9) continue
+ // Services go where they are needed, wherever that is; everything else as near the middle as it can.
+ const value = (kind.gathers || kind.plants ? s * 10 : 0) + dirty + amid * 2 - Math.hypot(x - middle, y - middle) / (risky !== null ? 4 : 1)
if (!best || value > best.value) best = { cell: { x, y }, value }
}
}
return best?.cell ?? null
}
+/** Rings from a tile to the nearest home (or 99 when there are none). */
+const nearestHome = (w: World, tile: Tile) => {
+ let best = 99
+ for (const h of w.homes) best = Math.min(best, ringOf(tile, h.tile.x, h.tile.y))
+ return best
+}
+const homesAround = (w: World, tile: Tile, r: number) => w.homes.filter((h) => ringOf(tile, h.tile.x, h.tile.y) <= r).length
+
/**
* The bot keeps a street plan: every fourth row and column (in line with the
* ring road around the town hall) is for roads, and everything else stands
@@ -179,8 +258,13 @@ const offPlan = (tile: Tile) => {
return false
}
-/** Free cells beside a road and off the lanes, nearest the middle first. */
-const homeSpots = (w: World, n: number): Array<Point> => {
+/**
+ * Free cells beside a road and off the lanes, nearest the middle first: a
+ * zoning mayor passes over squalid ones and leans towards nicer ones (or,
+ * for workers' cottages, takes those nearest the workplace); a crowding one
+ * packs homes in beside the industry.
+ */
+const homeSpots = (w: World, n: number, near?: Tile): Array<Point> => {
const spots: Array<Point> = []
for (let y = 0; y < GRID; y++) {
for (let x = 0; x < GRID; x++) {
@@ -188,9 +272,46 @@ const homeSpots = (w: World, n: number): Array<Point> => {
if (DIRS.some((d) => isRoad(w.grid, x + d.x, y + d.y))) spots.push({ x, y })
}
}
- return spots.sort((a, b) => Math.hypot(a.x - middle, a.y - middle) - Math.hypot(b.x - middle, b.y - middle)).slice(0, n)
+ const industry = bot === "crowded" ? w.buildings.filter((b) => (kinds[b.kind].appeal?.value ?? 0) <= -2) : []
+ const score = (c: Point) => {
+ const distance = Math.hypot(c.x - middle, c.y - middle)
+ if (near) return ringOf(near, c.x, c.y)
+ if (bot === "crowded") return industry.length > 0 ? Math.min(...industry.map((b) => ringOf(b.tile, c.x, c.y))) + distance / 20 : distance
+ if (!zoned()) return distance
+ const v = w.appeal[key(c.x, c.y)] ?? 0
+ return distance - v / 2 + (v <= content.home.squalid ? 30 : 0)
+ }
+ return spots.sort((a, b) => score(a) - score(b)).slice(0, n)
}
+/**
+ * Where a garden (or park, or statue) helps most: the free cell off the
+ * lanes with the most homes within its reach that fall just short of the
+ * next tier's desirability.
+ */
+const ornamentFor = (w: World, kind: Kind): Point | null => {
+ const short = w.homes.filter((h) => {
+ if (h.site || h.tier === 3 || !h.provided) return false
+ const v = w.appeal[key(h.tile.x, h.tile.y)] ?? 0
+ const goal = content.home.tiers[h.tier === 1 ? 2 : 3].appeal
+ return v < goal && v >= goal - kind.appeal!.value
+ })
+ if (short.length < 3) return null
+ let best: { cell: Point; value: number } | null = null
+ for (let y = 0; y + kind.size <= GRID; y++) {
+ for (let x = 0; x + kind.size <= GRID; x++) {
+ const tile = { x, y, size: kind.size }
+ if (!canPlace(w.grid, tile) || offPlan(tile)) continue
+ const value = short.filter((h) => ringOf(tile, h.tile.x, h.tile.y) <= Math.max(1, kind.appeal!.reach - 1)).length
+ if (value >= 3 && (!best || value > best.value)) best = { cell: { x, y }, value }
+ }
+ }
+ return best?.cell ?? null
+}
+
+/** Homes whose sign for a risk is up, or nearly. */
+const atRisk = (w: World, r: "fire" | "health" | "order") => w.homes.filter((h) => !h.site && h.risk[r] >= content.risk.warn * 0.8).length
+
/**
* A road towards what a kind needs (or, for anything else, into open land):
* the shortest run of free cells from the road network to a cell near the
@@ -247,13 +368,22 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b
const homes = w.homes.length
const basics: ReadonlyArray<{ readonly kind: KindId; readonly when: boolean }> = [
{ kind: "fishery", when: count(w, "fishery") < 1 },
+ // Services once their warning signs go up over a few homes; a builder once homes start to run down.
+ { kind: "firewatch", when: covered() && atRisk(w, "fire") >= 3 && count(w, "firewatch") < 1 + Math.floor(homes / 30) },
+ { kind: "healer", when: covered() && atRisk(w, "health") >= 3 && count(w, "healer") + count(w, "hospital") < 1 + Math.floor(homes / 40) },
+ { kind: "watchhouse", when: covered() && atRisk(w, "order") >= 3 && count(w, "watchhouse") < 1 + Math.floor(homes / 40) },
+ { kind: "builder", when: w.homes.filter((h) => h.condition < 650).length >= 3 && count(w, "builder") < 1 + Math.floor((homes + w.buildings.length) / 80) },
{ kind: "lumberjack", when: count(w, "lumberjack") < 1 },
{ kind: "sawmill", when: count(w, "sawmill") < 1 },
{ kind: "forester", when: count(w, "forester") < count(w, "lumberjack") },
{ kind: "market", when: count(w, "market") < 1 && homes >= 6 },
{ kind: "quarry", when: count(w, "quarry") < 1 },
// A lumberjack that has felled everything in reach is replaced by one in a forest.
- { kind: "lumberjack", when: w.stock.planks < 20 && w.buildings.filter((b) => b.kind === "lumberjack" && b.status !== "starved").length < 1 + Math.floor(homes / 40) }
+ { kind: "lumberjack", when: w.stock.planks < 20 && w.buildings.filter((b) => b.kind === "lumberjack" && b.status !== "starved").length < 1 + Math.floor(homes / 40) && count(w, "lumberjack") < 2 + Math.floor(homes / 30) },
+ // Food: a fishery more while homes go hungry (fish rots, so the larder alone is no guide), and a
+ // market for every eighteen homes or so, or what is caught is never handed out.
+ { kind: "fishery", when: (larder(w.stock) < homes / 2 || w.census.food! < w.homes.length * 0.6) && count(w, "fishery") < 1 + Math.floor(homes / 7) },
+ { kind: "market", when: count(w, "market") < 1 + Math.floor(homes / 18) && w.census.food! < w.homes.length * 0.7 }
]
if (bot === "idle") return basics
// The citizens' chains, in proportion to the homes: a bakery bakes for about
@@ -264,14 +394,14 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b
const weavers = homes < 20 ? 1 : 1 + Math.floor(homes / 12)
return [
...basics,
- { kind: "fishery", when: larder(w.stock) < homes && count(w, "fishery") < 1 + Math.floor(homes / 7) },
- // One of each first: tools are scarce until there are citizens to run a smithy.
+ // One of each first, saved up for (see `saving`): tools are scarce until there are citizens to run a smithy.
{ kind: "chapel", when: count(w, "chapel") < 1 },
{ kind: "farm", when: count(w, "farm") < 1 },
{ kind: "mill", when: count(w, "mill") < 1 },
{ kind: "bakery", when: count(w, "bakery") < 1 },
{ kind: "sheep", when: count(w, "sheep") < 1 },
{ kind: "weaver", when: count(w, "weaver") < 1 },
+ { kind: "market", when: count(w, "market") < 1 + Math.floor(homes / 18) },
{ kind: "smithy", when: count(w, "smithy") < 1 },
{ kind: "mine", when: count(w, "mine") < 1 },
{ kind: "chapel", when: count(w, "chapel") < 1 + Math.floor(homes / 35) },
@@ -281,7 +411,9 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b
{ kind: "sheep", when: count(w, "sheep") < weavers },
{ kind: "weaver", when: count(w, "weaver") < Math.min(weavers, count(w, "sheep")) },
{ kind: "warehouse", when: count(w, "warehouse") < Math.floor(homes / 25) },
- { kind: "market", when: count(w, "market") < 1 + Math.floor(homes / 16) },
+ // Fish and bread rot: a granary keeps them, and smoked fish keeps.
+ { kind: "granary", when: homes >= 40 && count(w, "granary") < 1 + Math.floor(homes / 70) },
+ { kind: "smokehouse", when: larder(w.stock) >= homes && count(w, "smokehouse") < Math.floor(count(w, "fishery") / 5) },
{ kind: "sawmill", when: w.stock.planks < 15 && w.stock.wood > 10 && count(w, "sawmill") < 3 },
{ kind: "quarry", when: w.stock.stone < 8 && count(w, "quarry") < 3 }
]
@@ -296,7 +428,7 @@ const decide = (w: World): ReadonlyArray<Edit> => {
for (const g of goodIds) if (!w.policy.sells.includes(g)) edits.push({ type: "trade", good: g, mode: "sell" })
}
const fed = w.homes.length > 0 ? w.census.food! / w.homes.length : 1
- if (bot === "sensible") {
+ if (sensible()) {
// Taxes follow the town's mood; once every other goal is met, they come down to win it over.
const goals = goalsOf(w.charter, {
settlers: w.census.settlers!, citizens: w.census.citizens!, coins: w.coins, net: net(w), approval: w.mood.approval
@@ -313,25 +445,40 @@ const decide = (w: World): ReadonlyArray<Edit> => {
const crownBuy = w.crown.open && w.stock[w.crown.good] < w.crown.amount && w.coins > cost + 200 ? w.crown.good : null
if (crownBuy && !w.policy.buys.includes(crownBuy)) edits.push({ type: "trade", good: crownBuy, mode: "buy" })
// Buy what runs short, while the treasury can bear it; stop once there is enough.
- const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["planks", 10, 30], ["stone", 6, 20], ["tools", 4, 8], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) ? 1000 : -1, 30]]
+ // Never at any price: buying drives it up, so stop at half again the usual.
+ const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["planks", 6, 14], ["stone", 4, 12], ["tools", 3, 6], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) ? 1000 : -1, 24]]
for (const [g, low, enough] of shortages) {
if (g === crownBuy) continue
const buying = w.policy.buys.includes(g)
- if (!buying && w.stock[g] < low && w.coins > 150) edits.push({ type: "trade", good: g, mode: "buy" })
- if (buying && (w.stock[g] >= enough || w.coins < 50)) edits.push({ type: "trade", good: g, mode: "none" })
+ const dear = w.prices[g] > 150
+ if (!buying && w.stock[g] < low && w.coins > 150 && !dear) edits.push({ type: "trade", good: g, mode: "buy" })
+ if (buying && (w.stock[g] >= enough || w.coins < 50 || dear)) edits.push({ type: "trade", good: g, mode: "none" })
}
if (w.crown.open && w.stock[w.crown.good] >= w.crown.amount) edits.push({ type: "deliver" })
// Stop buying what was only bought for the crown.
for (const g of w.policy.buys) if (g !== crownBuy && !shortages.some(([s]) => s === g)) edits.push({ type: "trade", good: g, mode: content.trade.sells.includes(g) ? "sell" : "none" })
- // In debt: stop what is idle anyway; back to work once there is money again.
+ // In debt: stop what is idle anyway; back to work once there is money again. While the crown waits
+ // for something the town's own workshops use up (wood, wool, ore), those workshops wait instead; the
+ // bread chain is too precious to stop, so wheat and flour are bought instead.
+ const hoarding = w.crown.open && w.stock[w.crown.good] < w.crown.amount && !["wheat", "flour"].includes(w.crown.good) ? w.crown.good : null
for (const b of w.buildings) {
if (b.site || b.kind === "townhall") continue
- if (w.coins < 0 && net(w) < 0 && ["blocked", "starved"].includes(b.status)) edits.push({ type: "pause", cell: b.tile, on: true })
- if (b.status === "paused" && w.coins > 300) edits.push({ type: "pause", cell: b.tile, on: false })
+ const consumer = hoarding !== null && kinds[b.kind].recipe?.input === hoarding
+ if (consumer && b.status !== "paused") edits.push({ type: "pause", cell: b.tile, on: true })
+ else if (w.coins < 0 && net(w) < 0 && ["blocked", "starved"].includes(b.status)) edits.push({ type: "pause", cell: b.tile, on: true })
+ else if (b.status === "paused" && !consumer && w.coins > 300) edits.push({ type: "pause", cell: b.tile, on: false })
}
}
+ // Ruins are cleared.
+ if (bot !== "idle") for (const r of w.ruins) edits.push({ type: "remove", cell: { x: r.tile.x, y: r.tile.y } })
if (bot === "idle" && residents(w) > 30) return edits
+ // Workers' cottages beside a workplace no settler can walk to.
+ const lonely = w.buildings.find((b) => !b.site && b.status === "unstaffed" && b.nearby === 0 && kinds[b.kind].crew === "settlers" && kinds[b.kind].workers > 0)
+ if (lonely && affordable(w, { coins: home.cost.coins * 3, materials: { planks: 3 } })) {
+ const spots = homeSpots(w, 3, lonely.tile).filter((c) => ringOf(lonely.tile, c.x, c.y) <= 6)
+ if (spots.length > 0) return [...edits, { type: "homes", cells: spots }]
+ }
if (sites(w) > 3) return edits
// Homes when workers run short, or (they are the town's income) when food reaches most of them and
// there are coins to spare; not far past the goal, where upgrading homes pays better than more of them.
@@ -343,10 +490,18 @@ const decide = (w: World): ReadonlyArray<Edit> => {
const road = roadToward(w, null)
if (road.length > 0 && w.coins > road.length * ROAD_COST + 60) return [...edits, { type: "roads", cells: road }]
}
+ if (process.env.DEBUG_PLAN) console.log(` t ${w.tick} coins ${w.coins} planks ${w.stock.planks} stone ${w.stock.stone} tools ${w.stock.tools} wants ${plan(w).filter((p) => p.when).map((p) => p.kind).join(",")}`)
for (const want of plan(w)) {
if (!want.when) continue
const kind = kinds[want.kind]
- if (!unlocked(w, kind) || !affordable(w, kind.cost)) continue
+ if (!unlocked(w, kind)) continue
+ // The first of each of the citizens' chain is saved up for, rather than spending on what comes after it.
+ if (!affordable(w, kind.cost)) {
+ if (saving.includes(want.kind) && count(w, want.kind) < 1) break
+ continue
+ }
+ // Another of a kind will not help while one stands without workers.
+ if (want.kind !== "fishery" && w.buildings.some((b) => b.kind === want.kind && !b.site && b.status === "unstaffed")) continue
if ((resting.get(want.kind) ?? 0) > w.tick) continue
const spot = spotFor(w, kind)
if (spot) {
@@ -362,8 +517,35 @@ const decide = (w: World): ReadonlyArray<Edit> => {
roading.delete(want.kind)
resting.set(want.kind, w.tick + 5 * 3600)
}
+ // Ornaments, then (with stone to spare) paving, where homes fall a little short of the next tier: a
+ // garden is cheap; parks and statues once the treasury is comfortable.
+ if (zoned() && w.coins > 150) {
+ // A fountain in the middle of a block lifts all eight homes around it past what citizens need.
+ const options: ReadonlyArray<KindId> = w.coins > 1500 ? ["statue", "fountain", "garden"] : w.coins > 300 ? ["fountain", "garden"] : ["garden"]
+ for (const id of options) {
+ const kind = kinds[id]
+ if (!unlocked(w, kind) || !affordable(w, kind.cost)) continue
+ const spot = ornamentFor(w, kind)
+ if (spot) return [...edits, { type: "building", kind: id, cell: spot, open: false }]
+ }
+ if (w.stock.stone >= 15 && w.coins > 400) {
+ const cells: Array<Point> = []
+ for (const h of w.homes) {
+ if (h.tier === 3 || h.site) continue
+ const v = w.appeal[key(h.tile.x, h.tile.y)] ?? 0
+ if (v !== content.home.tiers[h.tier === 1 ? 2 : 3].appeal - 1) continue
+ for (const d of DIRS) {
+ const c = { x: h.tile.x + d.x, y: h.tile.y + d.y }
+ if (isRoad(w.grid, c.x, c.y) && !w.paved.has(key(c.x, c.y)) && !cells.some((p) => p.x === c.x && p.y === c.y)) cells.push(c)
+ }
+ }
+ if (cells.length > 0) return [...edits, { type: "pave", cells: cells.slice(0, 4) }]
+ }
+ }
return edits
}
+/** What a mayor saves up for (the first of each), rather than spend on anything later in the plan. */
+const saving: ReadonlyArray<KindId> = ["chapel", "farm", "mill", "bakery", "sheep", "weaver"]
/** Roads laid towards each kind since one was last built, and until when a kind with no room is left alone. */
const roading = new Map<KindId, number>()
const resting = new Map<KindId, number>()
@@ -386,6 +568,11 @@ interface Row {
readonly winter: boolean
readonly crown: string
readonly goals: number
+ /** Homes sick and things on fire now; homes and buildings lost to fire, collapse, and dereliction so far. */
+ readonly sick: number
+ readonly burning: number
+ readonly lost: number
+ readonly burghers: number
readonly problems: Record<string, number>
}
@@ -398,15 +585,41 @@ const run = (seed: number) => {
const rows: Array<Row> = []
const problems: Record<string, number> = {}
+ const ruined = new Set<number>()
+ const spend: Record<string, number> = {}
let w = read(town.snapshot())
const DECIDE = 5
for (let t = 0; t < term * 60 + DECIDE && w.fate.state === "playing"; t += DECIDE) {
const chosen = decide(w)
+ if (process.env.SPEND) {
+ for (const e of chosen) {
+ const k = e.type === "building" ? kinds[e.kind].category === "services" || kinds[e.kind].decor ? e.kind : kinds[e.kind].category : e.type
+ const cost = e.type === "building" ? kinds[e.kind].cost.coins : e.type === "homes" ? e.cells.length * home.cost.coins : e.type === "roads" ? e.cells.length * ROAD_COST : e.type === "pave" ? e.cells.length * 3 : 0
+ if (cost > 0) spend[k] = (spend[k] ?? 0) + cost
+ }
+ if ((t + DECIDE) % 300 === 0) {
+ const l = w.ledger
+ console.log(` ${(t + DECIDE) / 60}m ledger/min taxes ${l.taxes} trade ${l.trade} upkeep ${l.upkeep} admin ${l.admin} · spent last 5 min: ${Object.entries(spend).map(([k, n]) => `${k} ${n}`).join(", ")}`)
+ for (const k of Object.keys(spend)) delete spend[k]
+ }
+ }
if (process.env.DEBUG) console.log(t, JSON.stringify(chosen).slice(0, 200))
ui.edits.push(...chosen)
step(DECIDE)
w = read(town.snapshot())
+ for (const r of w.ruins) ruined.add(r.id)
if ((t + DECIDE) % 60 !== 0) continue
+ if (process.env.TRACE) {
+ const snap = town.snapshot()
+ const chain = ["farm", "mill", "bakery", "sheep", "weaver", "chapel", "market"].map((k) => {
+ const all = snap.entities.filter((e) => e.components["Town/Building"]?.kind === k)
+ const up = all.filter((e) => !e.components["Town/Site"] && !e.components["Town/Rising"])
+ const made = up.reduce((n, e) => n + (e.components["Town/Recipe"]?.made ?? 0), 0)
+ return `${k} ${up.length}/${all.length}${made ? ` made ${made}` : ""}${up.length ? ` ${up.map((e) => e.components["Town/Status"][0]).join("")}` : ""}`
+ })
+ const homes = snap.entities.filter((e) => e.components["Town/House"]).map((e) => e.components["Town/House"])
+ console.log(` ${(t + DECIDE) / 60}m coins ${w.coins} · ${chain.join(" · ")} · bread ${homes.filter((h) => h.bread > 0).length} cloth ${homes.filter((h) => h.cloth > 0).length} faith ${homes.filter((h) => h.faith > 0).length} /${homes.length} · stock bread ${w.stock.bread} flour ${w.stock.flour} wheat ${w.stock.wheat} tools ${w.stock.tools}`)
+ }
const minute = (t + DECIDE) / 60
if (minute === snapshotAt) {
mkdirSync(out, { recursive: true })
@@ -445,9 +658,14 @@ const run = (seed: number) => {
winter: seasonAt(w.tick - w.charter.founded, w.charter).winter,
crown: `${w.crown.open ? `${w.crown.amount} ${w.crown.good}` : "-"} ${w.crown.met}/${w.crown.missed}`,
goals: goals.filter((g) => g.met).length,
+ sick: w.census.sick!,
+ burning: w.census.burning!,
+ lost: ruined.size,
+ burghers: w.census.burghers!,
problems: problemsNow
})
}
+ if (process.env.CHRONICLE) for (const l of town.snapshot().resources["Town/Chronicle"].lines as Array<{ tick: number; text: string }>) console.log(` ${(l.tick / 3600).toFixed(1)} ${l.text}`)
const lastGoals = goalsOf(w.charter, {
settlers: w.census.settlers!, citizens: w.census.citizens!, coins: w.coins, net: net(w), approval: w.mood.approval
}).map((g) => `${g.met ? "✓" : "✗"} ${g.text} (${g.value})`).join(" · ")
@@ -456,55 +674,82 @@ const run = (seed: number) => {
const end = w.fate.state === "playing" ? { state: "playing", reason: "", minute: term } : { state: w.fate.state, reason: w.fate.reason, minute: Math.round(w.fate.at / 360) / 10 }
const built: Record<string, number> = {}
for (const b of w.buildings) built[b.kind] = (built[b.kind] ?? 0) + 1
- return { seed, rows, problems, end, score: w.fate.score, built, stock: w.stock, crown: w.crown, lastGoals, supplied }
+ return { seed, rows, problems, end, score: w.fate.score, built, stock: w.stock, crown: w.crown, lastGoals, supplied, lost: ruined.size }
}
const pad = (v: unknown, n: number) => String(v).padStart(n)
-const results: Array<ReturnType<typeof run>> = []
-const started = performance.now()
-const header = " min coins net income costs admin appr resid citiz homes food% larder season crown(met/missed) goals problems"
+const header = " min coins net income costs admin appr resid citiz burgh homes food% larder season crown(met/missed) goals sick fire lost problems"
const line = (r: Row) => {
const p = Object.entries(r.problems).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")
- return `${pad(r.minute, 5)} ${pad(r.coins, 7)} ${pad(r.net, 5)} ${pad(r.income, 7)} ${pad(r.costs, 5)} ${pad(r.admin, 5)} ${pad(r.approval, 5)} ${pad(r.residents, 6)} ${pad(r.citizens, 6)} ${pad(r.homes, 5)} ${pad(r.food, 5)} ${pad(r.larder, 6)} ${pad(r.winter ? "winter" : "", 6)} ${pad(r.crown, 18)} ${pad(r.goals, 5)} ${p}`
+ return `${pad(r.minute, 5)} ${pad(r.coins, 7)} ${pad(r.net, 5)} ${pad(r.income, 7)} ${pad(r.costs, 5)} ${pad(r.admin, 5)} ${pad(r.approval, 5)} ${pad(r.residents, 6)} ${pad(r.citizens, 6)} ${pad(r.burghers, 5)} ${pad(r.homes, 5)} ${pad(r.food, 5)} ${pad(r.larder, 6)} ${pad(r.winter ? "winter" : "", 6)} ${pad(r.crown, 18)} ${pad(r.goals, 5)} ${pad(r.sick, 4)} ${pad(r.burning, 4)} ${pad(r.lost, 4)} ${p}`
}
-for (let i = from; i < from + seeds; i++) {
- const r = run(1000 + i * 7919)
- results.push(r)
- const outcome = r.end.state === "playing" ? "still playing" : `${r.end.state} at ${r.end.minute} min: ${r.end.reason}`
- console.log(`seed ${r.seed}: ${outcome} (score ${r.score})`)
- console.log(` goals: ${r.lastGoals}`)
- console.log(` homes supplied: ${r.supplied} · built ${Object.entries(r.built).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")}`)
- if (verbose) {
- console.log(header)
- for (const row of r.rows) if (row.minute % every === 0 || row === r.rows.at(-1)) console.log(line(row))
- console.log(` built: ${Object.entries(r.built).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")}`)
- console.log(` stock: ${goodIds.filter((g) => r.stock[g] > 0).map((g) => `${g} ${r.stock[g]}`).join(", ")}\n`)
+const mean = (xs: ReadonlyArray<number>) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
+
+/** Plays every seed with one mayor, reporting as it goes. */
+const play = (which: Bot) => {
+ bot = which
+ const results: Array<ReturnType<typeof run>> = []
+ const started = performance.now()
+ for (let i = from; i < from + seeds; i++) {
+ const r = run(1000 + i * 7919)
+ results.push(r)
+ const outcome = r.end.state === "playing" ? "still playing" : `${r.end.state} at ${r.end.minute} min: ${r.end.reason}`
+ console.log(`seed ${r.seed}: ${outcome} (score ${r.score})`)
+ console.log(` goals: ${r.lastGoals}`)
+ console.log(` homes supplied: ${r.supplied} · built ${Object.entries(r.built).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")}`)
+ if (verbose) {
+ console.log(header)
+ for (const row of r.rows) if (row.minute % every === 0 || row === r.rows.at(-1)) console.log(line(row))
+ console.log(` built: ${Object.entries(r.built).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")}`)
+ console.log(` stock: ${goodIds.filter((g) => r.stock[g] > 0).map((g) => `${g} ${r.stock[g]}`).join(", ")}\n`)
+ }
}
-}
-// ── Summary ───────────────────────────────────────────────────────────────
+ // ── Summary ───────────────────────────────────────────────────────────────
-const mean = (xs: ReadonlyArray<number>) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
-console.log(`\n${seeds} seeds · ${size} ${land} land · ${term}-minute term · ${bot} mayor (${Math.round((performance.now() - started) / 1000)} s)`)
-const outcomes: Record<string, Array<number>> = {}
-for (const r of results) {
- const k = r.end.state === "lost" ? `lost (${r.end.reason.split(":")[0]!.toLowerCase()})` : r.end.state
- ;(outcomes[k] ??= []).push(r.end.minute)
+ console.log(`\n${seeds} seeds · ${size} ${land} land · ${term}-minute term · ${bot} mayor (${Math.round((performance.now() - started) / 1000)} s)`)
+ const outcomes: Record<string, Array<number>> = {}
+ for (const r of results) {
+ const k = r.end.state === "lost" ? `lost (${r.end.reason.split(":")[0]!.toLowerCase()})` : r.end.state
+ ;(outcomes[k] ??= []).push(r.end.minute)
+ }
+ console.log(` outcomes ${Object.entries(outcomes).map(([k, ms]) => `${k} ×${ms.length} (around minute ${Math.round(mean(ms))})`).join(", ")}`)
+ console.log(` score ${Math.round(mean(results.map((r) => r.score)))}`)
+ console.log(` crown met ${mean(results.map((r) => r.crown.met)).toFixed(1)}, missed ${mean(results.map((r) => r.crown.missed)).toFixed(1)}`)
+ // The pressure curve: each checkpoint averaged over the seeds still running then.
+ console.log(`\n pressure, averaged over the seeds still in office:`)
+ console.log(" min seeds resid citiz homes coins net costs/income admin appr food% larder/homes goals")
+ for (let m = every; m <= term; m += every) {
+ const at = results.map((r) => r.rows.find((row) => row.minute === m)).filter((row): row is Row => row !== undefined)
+ if (at.length === 0) break
+ console.log(
+ `${pad(m, 5)} ${pad(at.length, 6)} ${pad(Math.round(mean(at.map((r) => r.residents))), 6)} ${pad(Math.round(mean(at.map((r) => r.citizens))), 6)} ${pad(Math.round(mean(at.map((r) => r.homes))), 6)} ${pad(Math.round(mean(at.map((r) => r.coins))), 7)} ${pad(Math.round(mean(at.map((r) => r.net))), 6)} ${pad(mean(at.map((r) => r.costs / Math.max(1, r.income))).toFixed(2), 13)} ${pad(Math.round(mean(at.map((r) => r.admin))), 6)} ${pad(Math.round(mean(at.map((r) => r.approval))), 5)} ${pad(Math.round(mean(at.map((r) => r.food))), 6)} ${pad(mean(at.map((r) => r.larder / Math.max(1, r.homes))).toFixed(2), 13)} ${pad(mean(at.map((r) => r.goals)).toFixed(1), 6)}`
+ )
+ }
+ const allProblems: Record<string, number> = {}
+ for (const r of results) for (const [k, n] of Object.entries(r.problems)) allProblems[k] = (allProblems[k] ?? 0) + n
+ const top = Object.entries(allProblems).sort((a, b) => b[1] - a[1]).slice(0, 6)
+ console.log(`\n most common problems ${top.map(([k, n]) => `${k} (${(n / seeds).toFixed(1)} min/seed)`).join(", ") || "none"}`)
+ return results
}
-console.log(` outcomes ${Object.entries(outcomes).map(([k, ms]) => `${k} ×${ms.length} (around minute ${Math.round(mean(ms))})`).join(", ")}`)
-console.log(` score ${Math.round(mean(results.map((r) => r.score)))}`)
-console.log(` crown met ${mean(results.map((r) => r.crown.met)).toFixed(1)}, missed ${mean(results.map((r) => r.crown.missed)).toFixed(1)}`)
-// The pressure curve: each checkpoint averaged over the seeds still running then.
-console.log(`\n pressure, averaged over the seeds still in office:`)
-console.log(" min seeds resid citiz homes coins net costs/income admin appr food% larder/homes goals")
-for (let m = every; m <= term; m += every) {
- const at = results.map((r) => r.rows.find((row) => row.minute === m)).filter((row): row is Row => row !== undefined)
- if (at.length === 0) break
- console.log(
- `${pad(m, 5)} ${pad(at.length, 6)} ${pad(Math.round(mean(at.map((r) => r.residents))), 6)} ${pad(Math.round(mean(at.map((r) => r.citizens))), 6)} ${pad(Math.round(mean(at.map((r) => r.homes))), 6)} ${pad(Math.round(mean(at.map((r) => r.coins))), 7)} ${pad(Math.round(mean(at.map((r) => r.net))), 6)} ${pad(mean(at.map((r) => r.costs / Math.max(1, r.income))).toFixed(2), 13)} ${pad(Math.round(mean(at.map((r) => r.admin))), 6)} ${pad(Math.round(mean(at.map((r) => r.approval))), 5)} ${pad(Math.round(mean(at.map((r) => r.food))), 6)} ${pad(mean(at.map((r) => r.larder / Math.max(1, r.homes))).toFixed(2), 13)} ${pad(mean(at.map((r) => r.goals)).toFixed(1), 6)}`
- )
+
+const mine = play(bot)
+if (versus !== "") {
+ const first = bot
+ const theirs = play(versus)
+ /** Each mayor's towns, side by side: how far they got, and what they lost. */
+ const at = (rs: ReadonlyArray<ReturnType<typeof run>>, minute: number, f: (r: Row) => number) =>
+ mean(rs.map((r) => r.rows.filter((row) => row.minute <= minute).at(-1)).filter((row): row is Row => row !== undefined).map(f))
+ const peak = (rs: ReadonlyArray<ReturnType<typeof run>>, f: (r: Row) => number) => mean(rs.map((r) => Math.max(0, ...r.rows.map(f))))
+ console.log(`\n${first} against ${versus}, the same ${seeds} seeds:`)
+ console.log(` ${"".padEnd(34)}${first.padStart(12)}${versus.padStart(12)}`)
+ const lineOf = (label: string, f: (rs: ReadonlyArray<ReturnType<typeof run>>) => number) =>
+ console.log(` ${label.padEnd(34)}${pad(Math.round(f(mine)), 12)}${pad(Math.round(f(theirs)), 12)}`)
+ lineOf("most citizens", (rs) => peak(rs, (r) => r.citizens))
+ lineOf("most burghers", (rs) => peak(rs, (r) => r.burghers))
+ lineOf("most residents", (rs) => peak(rs, (r) => r.residents))
+ lineOf("citizens at minute 30", (rs) => at(rs, 30, (r) => r.citizens))
+ lineOf("homes and buildings lost by minute 30", (rs) => at(rs, 30, (r) => r.lost))
+ lineOf("lost by the end", (rs) => mean(rs.map((r) => r.lost)))
+ lineOf("score", (rs) => mean(rs.map((r) => r.score)))
}
-const allProblems: Record<string, number> = {}
-for (const r of results) for (const [k, n] of Object.entries(r.problems)) allProblems[k] = (allProblems[k] ?? 0) + n
-const top = Object.entries(allProblems).sort((a, b) => b[1] - a[1]).slice(0, 6)
-console.log(`\n most common problems ${top.map(([k, n]) => `${k} (${(n / seeds).toFixed(1)} min/seed)`).join(", ") || "none"}`)
diff --git a/scripts/check.ts b/scripts/check.ts
index 43780b5..ec03984 100644
--- a/scripts/check.ts
+++ b/scripts/check.ts
@@ -14,10 +14,20 @@
* - the crown: a request left unanswered is a fine and a snub, and three in
* a row and the mayor is dismissed;
* - and a town saved mid-term loads back the same.
+ *
+ * And the neighbourhood and its dangers:
+ * - a citizens' home next to a smithy goes back to settlers;
+ * - an unwatched home catches fire, and the fire spreads;
+ * - fish rots without a granary, and keeps in one;
+ * - a workplace with no homes within reach stays unstaffed;
+ * - a home nobody mends falls down, and a builder keeps it standing;
+ * - citizens will not take settlers' work, and settlers stand in for citizens as apprentices;
+ * - and homes with every need met become citizens on a street with fountains, not packed beside industry.
*/
-import type { CharterValue } from "../src/content.ts"
-import { DIRS, GridBuilder, key } from "../src/grid.ts"
+import { amounts, CONDITION_MAX, goodIds, kinds, RISK_MAX, ticks, type CharterValue, type KindId } from "../src/content.ts"
+import { canPlace, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"
import { inside } from "../src/iso.ts"
+import { ringOf } from "../src/appeal.ts"
import { headless, type Snapshot } from "../src/sim/headless.ts"
const town = (charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }) => {
@@ -26,7 +36,23 @@ const town = (charter: CharterValue = { size: "small", term: 45, land: "fair", s
return { ...t, fate }
}
-/** Citizens' homes, every need met for good, on free cells beside the roads. */
+/** A building on a snapshot, standing and idle. */
+const building = (s: Snapshot, kind: string, x: number, y: number, size: number, extra: Record<string, unknown> = {}) => {
+ const id = s.nextEntity++
+ s.entities.push({
+ id,
+ components: {
+ "Town/Tile": { x, y, size },
+ "Town/Building": { kind },
+ "Town/Status": "idle",
+ "Town/Staff": { needed: 0, assigned: 0, apprentices: 0, nearby: 0 },
+ ...extra
+ }
+ })
+ return id
+}
+
+/** Citizens' homes, every need met for good, on free cells beside the roads; every third free cell a statue, so the street is fine enough for them. */
const settle = (s: Snapshot, homes: number) => {
const grid = new GridBuilder(s.resources["Town/Land"].mask)
for (const e of s.entities) {
@@ -35,12 +61,18 @@ const settle = (s: Snapshot, homes: number) => {
}
const g = grid.value()
let placed = 0
+ let statues = 0
for (let k = 0; k < g.use.length && placed < homes; k++) {
if (g.use[k] !== "empty") continue
const x = k % 64
const y = Math.floor(k / 64)
if (!DIRS.some((d) => inside(x + d.x, y + d.y) && g.use[key(x + d.x, y + d.y)] === "road")) continue
const forever = 10_000_000
+ if ((placed + statues) % 3 === 2) {
+ building(s, "statue", x, y, 1)
+ statues += 1
+ continue
+ }
s.entities.push({
id: s.nextEntity++,
components: {
@@ -53,6 +85,9 @@ const settle = (s: Snapshot, homes: number) => {
return placed
}
+/** An entity's components on a snapshot being changed. */
+const entityIn = (s: Snapshot, id: number) => s.entities.find((e) => e.id === id)!.components
+
let failures = 0
const check = (name: string, ok: boolean, detail: string) => {
console.log(`${ok ? "ok " : "FAIL"} ${name}: ${detail}`)
@@ -155,5 +190,334 @@ const check = (name: string, ok: boolean, detail: string) => {
check("save and load", same, `${a.snapshot().entities.length} entities, ${a.snapshot().resources["Town/Treasury"].coins} coins either way`)
}
+// ── The neighbourhood and its dangers ─────────────────────────────────────
+
+/** What stands where on a snapshot. */
+const gridOf = (s: Snapshot) => {
+ const builder = new GridBuilder(s.resources["Town/Land"].mask)
+ for (const e of s.entities) {
+ const c = e.components
+ const tile = c["Town/Tile"]
+ if (!tile) continue
+ const use: Use = c["Town/Road"] ? "road" : 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"
+ builder.claim(tile, e.id, use)
+ }
+ return builder
+}
+/** The first spot (nearest the town hall) for a tile `size` a side where `ok` holds, claimed so the next search skips it. */
+const find = (g: GridBuilder, size: number, ok: (x: number, y: number) => boolean, use: Use = "building") => {
+ const spots: Array<{ x: number; y: number }> = []
+ for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) if (canPlace(g.value(), { x, y, size }) && ok(x, y)) spots.push({ x, y })
+ spots.sort((a, b) => Math.hypot(a.x - 31, a.y - 31) - Math.hypot(b.x - 31, b.y - 31))
+ const spot = spots[0]
+ if (!spot) throw new Error("no room for the check")
+ g.claim({ ...spot, size }, -1, use)
+ return spot
+}
+const besideRoad = (g: GridBuilder) => (x: number, y: number) => DIRS.some((d) => isRoad(g.value(), x + d.x, y + d.y))
+const doorOnRoad = (g: GridBuilder, size: number) => (x: number, y: number) => entrances({ x, y, size }).some((c) => isRoad(g.value(), c.x, c.y))
+
+/** A home on a snapshot: its tier, residents, needs (met for good, or not), and risks. */
+const homeAt = (s: Snapshot, x: number, y: number, tier: 1 | 2 | 3, residents: number, needs = true, r: Partial<Record<"fire" | "health" | "order", number>> = {}) => {
+ const forever = 10_000_000
+ const id = s.nextEntity++
+ s.entities.push({
+ id,
+ components: {
+ "Town/Tile": { x, y, size: 1 },
+ "Town/House": { tier, residents, food: needs ? forever : 0, bread: needs ? forever : 0, cloth: needs ? forever : 0, faith: needs ? forever : 0, clock: 1 },
+ "Town/Risk": { fire: r.fire ?? 0, health: r.health ?? 0, order: r.order ?? 0, thefts: 0 },
+ "Town/Condition": { value: CONDITION_MAX }
+ }
+ })
+ return id
+}
+
+/** A building on a snapshot, standing, with every role its kind has (as `rolesOf` gives it). */
+const standing = (s: Snapshot, kind: KindId, x: number, y: number, stock: Partial<Record<string, number>> = {}) => {
+ const k = kinds[kind]
+ const c: Record<string, unknown> = {
+ "Town/Tile": { x, y, size: k.size },
+ "Town/Building": { kind },
+ "Town/Status": "idle",
+ "Town/Staff": { needed: k.workers, assigned: 0, apprentices: 0, nearby: 0 }
+ }
+ if (k.recipe) {
+ const r = k.recipe
+ c["Town/Recipe"] = { input: r.input, inputs: r.inputs, output: r.output, batch: r.batch, period: ticks(r.seconds), progress: 0, made: 0 }
+ }
+ if (k.gathers) c["Town/Gatherer"] = { ...k.gathers }
+ const tools = k.wear ? ["tools"] : []
+ if (k.holds) {
+ const all = k.holds.accepts === "all"
+ c["Town/Inventory"] = { stock: amounts(stock), accepts: all ? goodIds : [...k.holds.accepts, ...tools], cap: k.holds.cap }
+ if (all || k.keeps) c["Town/Storage"] = {}
+ } else if (k.recipe) c["Town/Inventory"] = { stock: amounts(stock), accepts: [k.recipe.output, ...tools], cap: 8 }
+ if (k.carriers) c["Town/Carriers"] = { count: k.carriers }
+ if (k.service) c["Town/Service"] = { service: k.service.service, interval: ticks(k.service.seconds), cooldown: 0, range: k.service.range }
+ if (!k.decor) {
+ c["Town/Risk"] = { fire: 0, health: 0, order: 0, thefts: 0 }
+ c["Town/Condition"] = { value: CONDITION_MAX }
+ }
+ const id = s.nextEntity++
+ s.entities.push({ id, components: c })
+ return id
+}
+const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entities.find((e) => e.id === id)
+
+// A citizens' home on a fine street stays citizens; a smithy beside it sends it back to settlers.
+{
+ const t = town()
+ let home = 0
+ let spot = { x: 0, y: 0 }
+ t.change((s) => {
+ const g = gridOf(s)
+ // Room for a smithy right beside it.
+ spot = find(g, 1, (x, y) => besideRoad(g)(x, y) && [[1, 0], [-2, 0], [0, 1], [0, -2]].some(([dx, dy]) => canPlace(g.value(), { x: x + dx!, y: y + dy!, size: 2 })), "house")
+ home = homeAt(s, spot.x, spot.y, 2, 8)
+ // A statue two cells off makes the street fine enough for citizens.
+ const statue = find(g, 1, (x, y) => ringOf({ x, y, size: 1 }, spot.x, spot.y) === 2 && !isRoad(g.value(), x, y))
+ building(s, "statue", statue.x, statue.y, 1)
+ })
+ t.run(10)
+ const before = entity(t, home)?.components["Town/House"]?.tier
+ t.change((s) => {
+ const g = gridOf(s)
+ const near = find(g, 2, (x, y) => ringOf({ x, y, size: 2 }, spot.x, spot.y) === 1)
+ standing(s, "smithy", near.x, near.y)
+ })
+ t.run(10)
+ const after = entity(t, home)?.components["Town/House"]?.tier
+ check("a smithy next door", before === 2 && after === 1, `citizens' home before the smithy (tier ${before}), tier ${after} after`)
+}
+
+// An unwatched row of cottages: one catches fire, and it spreads.
+{
+ const t = town()
+ const homes: Array<number> = []
+ t.change((s) => {
+ const g = gridOf(s)
+ const row = find(g, 1, (x, y) => [0, 1, 2, 3, 4].every((i) => canPlace(g.value(), { x: x + i, y, size: 1 })), "house")
+ for (let i = 0; i < 5; i++) {
+ g.claim({ x: row.x + i, y: row.y, size: 1 }, -1, "house")
+ homes.push(homeAt(s, row.x + i, row.y, 1, 4, true, { fire: i === 2 ? RISK_MAX - 20 : 8500 }))
+ }
+ })
+ let most = 0
+ for (let i = 0; i < 40; i++) {
+ t.run(1)
+ most = Math.max(most, t.snapshot().resources["Town/Census"].burning)
+ }
+ const ruins = t.snapshot().entities.filter((e) => e.components["Town/Ruin"]?.cause === "burnt").length
+ const news = (t.snapshot().resources["Town/Chronicle"].lines as Array<{ text: string }>).filter((l) => l.text.startsWith("Fire on")).map((l) => l.text)
+ check("fire spreads", most >= 2 && ruins >= 2, `${most} burning at once, ${ruins} burnt down · ${news.at(-1) ?? "no news"}`)
+}
+
+// A fire watch nearby: firefighters reach the blaze, and it goes no further.
+{
+ const t = town()
+ const homes: Array<number> = []
+ t.change((s) => {
+ const g = gridOf(s)
+ // A street along the top of the town hall's ring, off its northern stub.
+ const hall = s.entities.find((e) => e.components["Town/TownHall"])!.components["Town/Tile"]
+ for (let x = hall.x - 3; x <= hall.x + 5; x++) {
+ const y = hall.y - 4
+ if (!canPlace(g.value(), { x, y, size: 1 })) continue
+ s.entities.push({ id: s.nextEntity++, components: { "Town/Tile": { x, y, size: 1 }, "Town/Road": {} } })
+ g.claim({ x, y, size: 1 }, -1, "road")
+ }
+ const row = find(g, 1, (x, y) => [0, 1, 2].every((i) => canPlace(g.value(), { x: x + i, y, size: 1 }) && besideRoad(g)(x + i, y)), "house")
+ for (let i = 0; i < 3; i++) {
+ g.claim({ x: row.x + i, y: row.y, size: 1 }, -1, "house")
+ homes.push(homeAt(s, row.x + i, row.y, 1, 4, true, { fire: i === 1 ? RISK_MAX - 20 : 6000 }))
+ }
+ const watch = find(g, 2, doorOnRoad(g, 2))
+ standing(s, "firewatch", watch.x, watch.y)
+ // Workers for the watch.
+ const cottage = find(g, 1, besideRoad(g), "house")
+ homeAt(s, cottage.x, cottage.y, 1, 4)
+ })
+ t.run(40)
+ const ruins = t.snapshot().entities.filter((e) => e.components["Town/Ruin"]?.cause === "burnt").length
+ const standingHomes = homes.filter((id) => entity(t, id)).length
+ const news = (t.snapshot().resources["Town/Chronicle"].lines as Array<{ text: string }>).filter((l) => l.text.startsWith("Fire on")).map((l) => l.text)
+ check("firefighters", ruins === 1 && standingHomes === 2, `${ruins} burnt down, ${standingHomes} of 3 still standing · ${news.at(-1) ?? "no news"}`)
+}
+
+// Food rots in the town hall; it keeps in a granary.
+{
+ const t = town()
+ let granary = 0
+ t.change((s) => {
+ const hall = s.entities.find((e) => e.components["Town/TownHall"])!
+ hall.components["Town/Inventory"].stock.fish = 100
+ // The town hall's walker would hand fish out: keep it home.
+ hall.components["Town/Service"].cooldown = 1_000_000
+ const g = gridOf(s)
+ // Off the roads, so no carrier moves the fish between them.
+ const spot = find(g, 2, (x, y) => !doorOnRoad(g, 2)(x, y) && !entrances({ x, y, size: 2 }).some((c) => DIRS.some((d) => isRoad(g.value(), c.x + d.x, c.y + d.y))))
+ granary = standing(s, "granary", spot.x, spot.y, { fish: 60 })
+ })
+ t.run(3 * 60)
+ const s = t.snapshot()
+ const hallFish = s.entities.find((e) => e.components["Town/TownHall"])!.components["Town/Inventory"].stock.fish
+ const kept = s.entities.find((e) => e.id === granary)!.components["Town/Inventory"].stock.fish
+ check("food rots", hallFish <= 45 && kept >= 45, `town hall: 100 fish → ${hallFish} in three minutes; granary: 60 → ${kept}`)
+}
+
+// A workplace no home can reach stays unstaffed; a home within reach staffs it.
+{
+ const t = town()
+ let lumberjack = 0
+ t.change((s) => {
+ const g = gridOf(s)
+ const spot = find(g, 2, doorOnRoad(g, 2))
+ lumberjack = standing(s, "lumberjack", spot.x, spot.y)
+ // Cottages on a road of their own, joined to nothing.
+ const island = find(g, 1, (x, y) => {
+ if ([-2, -1, 0, 1, 2].some((dy) => [-2, -1, 0, 1, 2, 3].some((dx) => g.value().use[key(x + dx, y + dy)] !== "empty"))) return false
+ return true
+ }, "road")
+ s.entities.push({ id: s.nextEntity++, components: { "Town/Tile": { x: island.x, y: island.y, size: 1 }, "Town/Road": {} } })
+ homeAt(s, island.x + 1, island.y, 1, 4)
+ homeAt(s, island.x - 1, island.y, 1, 4)
+ })
+ t.run(5)
+ const alone = entity(t, lumberjack)!.components
+ t.change((s) => {
+ const g = gridOf(s)
+ const near = find(g, 1, besideRoad(g), "house")
+ homeAt(s, near.x, near.y, 1, 4)
+ })
+ t.run(5)
+ const joined = entity(t, lumberjack)!.components
+ check(
+ "commuting",
+ alone["Town/Status"] === "unstaffed" && alone["Town/Staff"].nearby === 0 && joined["Town/Staff"].assigned === 2,
+ `alone: ${alone["Town/Status"]}, ${alone["Town/Staff"].nearby} settlers within reach; with a cottage on its road: ${joined["Town/Staff"].assigned} of 2 workers`
+ )
+}
+
+// Citizens will not take settlers' work; settlers stand in for citizens as apprentices.
+{
+ const t = town()
+ let quarry = 0
+ let sawmill = 0
+ t.change((s) => {
+ const g = gridOf(s)
+ const a = find(g, 2, doorOnRoad(g, 2))
+ quarry = standing(s, "quarry", a.x, a.y)
+ const b = find(g, 2, doorOnRoad(g, 2))
+ sawmill = standing(s, "sawmill", b.x, b.y)
+ for (let i = 0; i < 3; i++) {
+ const c = find(g, 1, besideRoad(g), "house")
+ homeAt(s, c.x, c.y, 2, 8)
+ building(s, "statue", ...(() => { const st = find(g, 1, () => true); return [st.x, st.y] as const })(), 1)
+ }
+ })
+ t.run(3)
+ const q1 = entity(t, quarry)!.components["Town/Staff"]
+ const w1 = entity(t, sawmill)!.components["Town/Staff"]
+ t.change((s) => {
+ // Every citizen moves out; a settlers' cottage moves in.
+ for (const e of s.entities) if (e.components["Town/House"]?.tier === 2) e.components["Town/House"].residents = 0
+ const g = gridOf(s)
+ const c = find(g, 1, besideRoad(g), "house")
+ homeAt(s, c.x, c.y, 1, 4, false)
+ })
+ t.run(1)
+ const q2 = entity(t, quarry)!.components["Town/Staff"]
+ const w2 = entity(t, sawmill)!.components["Town/Staff"]
+ check(
+ "crews",
+ q1.assigned === 0 && w1.assigned === 2 && w1.apprentices === 0 && w2.apprentices > 0 && q2.assigned > 0,
+ `citizens only: quarry ${q1.assigned}/3, sawmill ${w1.assigned}/2; settlers only: quarry ${q2.assigned}/3, sawmill ${w2.assigned}/2 (${w2.apprentices} apprentices)`
+ )
+}
+
+// A home nobody mends falls down; a builder next door keeps one standing.
+{
+ const t = town()
+ let neglected = 0
+ let mended = 0
+ t.change((s) => {
+ const g = gridOf(s)
+ // Off the roads altogether, so no builder ever passes it.
+ const a = find(g, 1, (x, y) => !besideRoad(g)(x, y), "house")
+ neglected = homeAt(s, a.x, a.y, 1, 4)
+ entityIn(s, neglected)["Town/Condition"].value = 3
+ // Right by the builder's door, so the builder's first step passes it.
+ const doorWithRoom = (x: number, y: number) =>
+ entrances({ x, y, size: 2 }).some((c) => isRoad(g.value(), c.x, c.y) && DIRS.some((d) => canPlace(g.value(), { x: c.x + d.x, y: c.y + d.y, size: 1 }) && ringOf({ x, y, size: 2 }, c.x + d.x, c.y + d.y) > 0))
+ const yard = find(g, 2, doorWithRoom)
+ standing(s, "builder", yard.x, yard.y, { planks: 10, stone: 4 })
+ const door = entrances({ ...yard, size: 2 }).find((c) => isRoad(g.value(), c.x, c.y) && DIRS.some((d) => canPlace(g.value(), { x: c.x + d.x, y: c.y + d.y, size: 1 })))!
+ const by = DIRS.map((d) => ({ x: door.x + d.x, y: door.y + d.y })).find((c) => canPlace(g.value(), { ...c, size: 1 }))!
+ g.claim({ ...by, size: 1 }, -1, "house")
+ mended = homeAt(s, by.x, by.y, 1, 4)
+ entityIn(s, mended)["Town/Condition"].value = 500
+ })
+ t.run(30)
+ const fell = !entity(t, neglected) && t.snapshot().entities.some((e) => e.components["Town/Ruin"]?.cause === "collapsed")
+ const kept = entity(t, mended)?.components["Town/Condition"]?.value ?? 0
+ check("wear and mending", fell && kept > 900, `the neglected home ${fell ? "fell down" : "still stands"}; the one by the builder's yard is at ${Math.round(kept / 10)}%`)
+}
+
+// Zoned against crowded: the same homes, every need met, on a street with fountains away from industry,
+// and packed in beside a smithy and a quarry. Only the first become citizens.
+{
+ const t = town()
+ const zoned: Array<number> = []
+ const crowded: Array<number> = []
+ t.change((s) => {
+ const g = gridOf(s)
+ const hall = s.entities.find((e) => e.components["Town/TownHall"])!.components["Town/Tile"]
+ const empty = (x: number, y: number, size = 1) => {
+ for (let dy = 0; dy < size; dy++) for (let dx = 0; dx < size; dx++) if (g.value().use[key(x + dx, y + dy)] !== "empty") return false
+ return true
+ }
+ const lay = (x: number, y: number, use: Use) => g.claim({ x, y, size: 1 }, -1, use)
+ // Two streets off the town hall's ring: one to the north, one to the south.
+ for (const [y, homesAt, besideAt] of [[hall.y - 4, hall.y - 5, hall.y - 6], [hall.y + 6, hall.y + 7, hall.y + 8]] as const) {
+ for (let x = hall.x - 3; x <= hall.x + 5; x++) {
+ if (!empty(x, y)) continue
+ s.entities.push({ id: s.nextEntity++, components: { "Town/Tile": { x, y, size: 1 }, "Town/Road": {} } })
+ lay(x, y, "road")
+ }
+ for (let x = hall.x - 2; x <= hall.x + 4; x++) {
+ if (!empty(x, homesAt)) continue
+ lay(x, homesAt, "house")
+ const id = homeAt(s, x, homesAt, 1, 4)
+ ;(y < hall.y ? zoned : crowded).push(id)
+ }
+ if (y < hall.y) {
+ // Fountains behind the zoned homes.
+ for (const x of [hall.x - 1, hall.x + 3]) if (empty(x, besideAt)) {
+ building(s, "fountain", x, besideAt, 1)
+ lay(x, besideAt, "building")
+ }
+ } else {
+ // A smithy and a quarry right behind the crowded ones.
+ for (const [kind, x] of [["smithy", hall.x - 1], ["quarry", hall.x + 2]] as const) if (empty(x, besideAt, 2)) {
+ standing(s, kind, x, besideAt)
+ g.claim({ x, y: besideAt, size: 2 }, -1, "building")
+ }
+ }
+ }
+ })
+ t.run(20)
+ const tiers = (ids: Array<number>) => ids.map((id) => entity(t, id)?.components["Town/House"]?.tier ?? 0)
+ const citizens = (ids: Array<number>) => ids.reduce((n, id) => {
+ const h = entity(t, id)?.components["Town/House"]
+ return n + (h && h.tier >= 2 ? h.residents : 0)
+ }, 0)
+ check(
+ "zoned against crowded",
+ zoned.length >= 4 && crowded.length >= 4 && citizens(zoned) > 0 && citizens(crowded) === 0,
+ `zoned street: ${citizens(zoned)} citizens (tiers ${tiers(zoned).join("")}); crowded street: ${citizens(crowded)} citizens (tiers ${tiers(crowded).join("")})`
+ )
+}
+
console.log(failures === 0 ? "\nall ends hold" : `\n${failures} failed`)
if (failures > 0) process.exit(1)
diff --git a/src/appeal.ts b/src/appeal.ts
new file mode 100644
index 0000000..e7afa6d
--- /dev/null
+++ b/src/appeal.ts
@@ -0,0 +1,91 @@
+/**
+ * Desirability: how pleasant each cell is to live on. Buildings and the land
+ * add to it or take from it, fading with distance (see `Kind.appeal` and
+ * `appeal` in content): industry pushes homes away, parks, fountains, and a
+ * chapel draw them in. Buildings' effects add up; water and woods count
+ * once however many are near, and so do paved streets. Plain functions,
+ * shared by the simulation (which keeps the whole grid, see `Appraise`) and
+ * the page (which explains one cell).
+ */
+import { appeal, kinds, type KindId } from "./content.ts"
+import { key } from "./grid.ts"
+import { GRID } from "./iso.ts"
+
+/** Something that makes the cells around it nicer or worse to live on. */
+export interface AppealSource {
+ readonly x: number
+ readonly y: number
+ readonly size: number
+ readonly value: number
+ readonly reach: number
+ /** What it is, for the readout: "park", "smithy", "water". */
+ readonly label: string
+ /** `sum`: adds up with others; `nature` and `paved`: only the strongest of their kind counts. */
+ readonly mode: "sum" | "nature" | "paved"
+}
+
+/** How far a cell is from a footprint, in rings: 0 on it, 1 beside it. */
+export const ringOf = (s: { readonly x: number; readonly y: number; readonly size: number }, x: number, y: number) =>
+ Math.max(0, s.x - x, x - (s.x + s.size - 1), s.y - y, y - (s.y + s.size - 1))
+
+/** What a source does at `ring` cells from its footprint: all of it beside it, fading to a little at its reach. */
+export const effectAt = (source: { readonly value: number; readonly reach: number }, ring: number): number => {
+ if (ring > source.reach) return 0
+ return Math.trunc((source.value * (source.reach - Math.max(1, ring) + 1)) / source.reach)
+}
+
+/** A building of a kind as a source, if it has any effect. */
+export const buildingSource = (kind: KindId, tile: { readonly x: number; readonly y: number; readonly size: number }): AppealSource | null => {
+ const a = kinds[kind].appeal
+ return a ? { ...tile, value: a.value, reach: a.reach, label: kinds[kind].title.toLowerCase(), mode: "sum" } : null
+}
+
+export const landSource = (what: "water" | "forest" | "paved" | "ruin" | "worn", cell: { readonly x: number; readonly y: number; readonly size?: number }): AppealSource => ({
+ x: cell.x,
+ y: cell.y,
+ size: cell.size ?? 1,
+ ...appeal[what],
+ label: what === "forest" ? "woods" : what === "paved" ? "paved street" : what === "worn" ? "a run-down home" : what,
+ mode: what === "water" || what === "forest" ? "nature" : what === "paved" ? "paved" : "sum"
+})
+
+const clamp = (n: number) => Math.max(appeal.floor, Math.min(appeal.ceiling, n))
+
+/** Every cell's desirability, by `key`. */
+export const appealGrid = (sources: ReadonlyArray<AppealSource>): Array<number> => {
+ const sum = new Int32Array(GRID * GRID)
+ const nature = new Int32Array(GRID * GRID)
+ const paved = new Int32Array(GRID * GRID)
+ for (const s of sources) {
+ const into = s.mode === "sum" ? sum : s.mode === "nature" ? nature : paved
+ for (let y = Math.max(0, s.y - s.reach); y < Math.min(GRID, s.y + s.size + s.reach); y++) {
+ for (let x = Math.max(0, s.x - s.reach); x < Math.min(GRID, s.x + s.size + s.reach); x++) {
+ const e = effectAt(s, ringOf(s, x, y))
+ if (e === 0) continue
+ const k = key(x, y)
+ if (s.mode === "sum") into[k] = into[k]! + e
+ else if (e > 0 ? e > into[k]! : e < into[k]!) into[k] = e
+ }
+ }
+ }
+ return Array.from({ length: GRID * GRID }, (_, k) => clamp(sum[k]! + nature[k]! + paved[k]!))
+}
+
+/** One cell's desirability and what makes it, strongest first: "park +6", "bakery −4". */
+export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readonly x: number; readonly y: number }) => {
+ const parts = new Map<string, number>()
+ const best = { nature: { label: "", value: 0 }, paved: { label: "", value: 0 } }
+ for (const s of sources) {
+ const e = effectAt(s, ringOf(s, cell.x, cell.y))
+ if (e === 0) continue
+ if (s.mode === "sum") parts.set(s.label, (parts.get(s.label) ?? 0) + e)
+ else if (Math.abs(e) > Math.abs(best[s.mode].value)) best[s.mode] = { label: s.label, value: e }
+ }
+ for (const b of [best.nature, best.paved]) if (b.value !== 0) parts.set(b.label, (parts.get(b.label) ?? 0) + b.value)
+ const list = [...parts].map(([label, value]) => ({ label, value })).filter((p) => p.value !== 0)
+ list.sort((a, b) => Math.abs(b.value) - Math.abs(a.value))
+ return { value: clamp(list.reduce((n, p) => n + p.value, 0)), parts: list }
+}
+
+/** A cell's desirability from a reckoned grid (0 before the first reckoning). */
+export const appealAt = (cells: ReadonlyArray<number>, x: number, y: number): number => cells[key(x, y)] ?? 0
diff --git a/src/archetypes.ts b/src/archetypes.ts
index a66cd63..5e7d693 100644
--- a/src/archetypes.ts
+++ b/src/archetypes.ts
@@ -5,11 +5,11 @@
* costs materials starts as a `Site`, anything else starts `Rising`; the
* land is a `Tile` and its own marker.
*/
-import { amounts, goodIds, home, total, type Kind } from "./content.ts"
+import { amounts, CONDITION_MAX, goodIds, home, total, type Kind } from "./content.ts"
import type { Point } from "./iso.ts"
import {
- Building, Carriers, Field, Game, Gatherer, House, Inventory, Planter, Recipe, Rising, Road, Rock, Service, Site, Staff,
- Status, Storage, Tile, Tree, Water
+ Building, Carriers, Condition, Field, Game, Gatherer, House, Inventory, Planter, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Site,
+ Staff, Status, Storage, Tile, Tree, Water
} from "./schema.ts"
import { ticks } from "./content.ts"
@@ -24,9 +24,15 @@ export const buildingDraft = (kind: Kind, cell: Point) =>
[Tile, { x: cell.x, y: cell.y, size: kind.size }],
[Building, { kind: kind.id }],
[Status, "building"],
- [Staff, { needed: kind.workers, assigned: 0 }]
+ [Staff, { needed: kind.workers, assigned: 0, apprentices: 0, nearby: 0 }]
)
+/** What every home and every working building carries: its risks, and how well kept it is. */
+export const wearOf = () => [
+ Game.Command.entry(Risk, { fire: 0, health: 0, order: 0, thefts: 0 }),
+ Game.Command.entry(Condition, { value: CONDITION_MAX })
+]
+
/** How a new building starts: owed its materials, or rising straight away. */
export const startOf = (kind: Kind) => site(kind.cost)
@@ -42,19 +48,25 @@ export const rolesOf = (kind: Kind) => {
const p = kind.plants
roles.push(Game.Command.entry(Planter, { what: p.what, radius: p.radius, interval: ticks(p.seconds), cooldown: 0, max: p.max }))
}
+ // A workshop that wears out tools keeps a few on its shelf too.
+ const tools = kind.wear ? ["tools" as const] : []
if (kind.holds) {
const all = kind.holds.accepts === "all"
- roles.push(Game.Command.entry(Inventory, { stock: amounts({}), accepts: all ? goodIds : kind.holds.accepts, cap: kind.holds.cap }))
- if (all) roles.push(Game.Command.entry(Storage, {}))
+ const accepts = all ? goodIds : [...kind.holds.accepts, ...tools.filter((g) => !kind.holds!.accepts.includes(g))]
+ roles.push(Game.Command.entry(Inventory, { stock: amounts({}), accepts, cap: kind.holds.cap }))
+ // Storage takes in and sends out any good it accepts: everything, or (a granary) food.
+ if (all || kind.keeps) roles.push(Game.Command.entry(Storage, {}))
} else if (kind.recipe) {
// A gatherer keeps what it makes until a carrier takes it.
- roles.push(Game.Command.entry(Inventory, { stock: amounts({}), accepts: [kind.recipe.output], cap: 8 }))
+ roles.push(Game.Command.entry(Inventory, { stock: amounts({}), accepts: [kind.recipe.output, ...tools], cap: 8 }))
}
if (kind.carriers) roles.push(Game.Command.entry(Carriers, { count: kind.carriers }))
if (kind.service) {
const s = kind.service
roles.push(Game.Command.entry(Service, { service: s.service, interval: ticks(s.seconds), cooldown: 0, range: s.range }))
}
+ // Ornaments and the town hall neither burn nor wear.
+ if (!kind.decor && kind.id !== "townhall") roles.push(...wearOf())
return roles
}
@@ -63,7 +75,9 @@ export const houseDraft = (cell: Point) =>
[Tile, { x: cell.x, y: cell.y, size: 1 }],
[House, { tier: 1, residents: 0, food: 0, bread: 0, cloth: 0, faith: 0, clock: 0 }]
)
-export const houseStart = () => site(home.cost)
+export const houseStart = () => [site(home.cost), ...wearOf()]
+export const ruinDraft = (tile: { readonly x: number; readonly y: number; readonly size: number }, cause: "burnt" | "collapsed" | "derelict") =>
+ Game.Command.spawn([Tile, { x: tile.x, y: tile.y, size: tile.size }], [Ruin, { cause }])
export const roadDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Road, {}])
export const treeDraft = (cell: Point, growth: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Tree, { growth }])
diff --git a/src/art.ts b/src/art.ts
index 232bef0..6c9d942 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -629,7 +629,20 @@ const dresses: Readonly<Record<KindId, Dress>> = {
bush(g, c, -a - 1 * U, 4, broadLeaves[1]!)
bush(g, -a - 1 * U, c, 4, broadLeaves[2]!)
}
- }
+ },
+ // New kinds: plain dresses in their colour until they get drawings of their own.
+ granary: { accent: 0xd6ae2e },
+ smokehouse: { accent: 0x9a5b3a, roof: roofOf(0x9a5b3a) },
+ firewatch: { accent: 0xc4523f, roof: roofOf(0xc4523f) },
+ healer: { accent: 0x4f9a8a },
+ hospital: { accent: 0x4f9a8a, glass: glassCool },
+ watchhouse: { accent: 0x3d4f6e, flag: 0x3d4f6e },
+ builder: { accent: 0x8a6a45, roof: roofOf(0xb08a5a) },
+ garden: { accent: 0x4f9a6a },
+ park: { accent: 0x4f9a6a },
+ fountain: { accent: 0x5f8fb0 },
+ statue: { accent: 0x8f9891 },
+ plaza: { accent: 0x8f9891 }
}
/**
@@ -637,7 +650,37 @@ const dresses: Readonly<Record<KindId, Dress>> = {
* (shut) → 1 (open); `wave` drives flags and sails. `plain` draws it bare
* and grey, as a ghost.
*/
+/**
+ * An ornament (a garden, park, fountain, statue, or plaza), drawn simply: a
+ * placeholder until each has a drawing of its own.
+ */
+export const drawDecor = (g: Graphics, kind: Kind) => {
+ const p = plateHalf(kind.size)
+ const green = 0xd8e6c9
+ const stone = 0xe4e6e0
+ quad(g, square(0, 0, p), kind.id === "plaza" ? stone : green)
+ if (kind.id === "garden" || kind.id === "park") {
+ const spots = kind.id === "garden" ? [[-0.2, -0.2], [0.2, 0.2]] : [[-0.5, -0.5], [0.5, -0.4], [-0.4, 0.5], [0.45, 0.45]]
+ for (const [u, v] of spots) {
+ const c = at(u!, v!, 0)
+ g.ellipse(c.x, c.y - 9, 6, 6).fill({ color: 0xa9c79a }).stroke({ color: ink, width: DETAIL })
+ line(g, c, { x: c.x, y: c.y - 4 }, LINE, 0x6b5a45)
+ }
+ if (kind.id === "garden") for (const [u, v] of [[0.25, -0.25], [-0.25, 0.25]]) g.circle(at(u!, v!, 0).x, at(u!, v!, 0).y - 1, 1.6).fill({ color: 0xe89a7c })
+ return
+ }
+ if (kind.id === "fountain") {
+ cylinder(g, 0, 0, 5 * U, 0, 4, 0xdfe3dc, 0xc9dde6)
+ cylinder(g, 0, 0, 1.2 * U, 4, 8, 0xdfe3dc, 0xeef0ea)
+ return
+ }
+ // A statue (on its own, or in the middle of a plaza).
+ cylinder(g, 0, 0, 2.5 * U, 0, 6, 0xdfe3dc, stone)
+ cylinder(g, 0, 0, 1.2 * U, 6, 16, 0xc9ccc4, 0xb9beb5)
+}
+
export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: number, wave: number, doors: Doors, plain = false) => {
+ if (kind.decor) return drawDecor(g, kind)
const dress: Dress = plain ? { accent: 0xb9beb5 } : dresses[kind.id]
const color = dress.accent
const a = kind.half * U
@@ -804,6 +847,10 @@ export const drawSite = (g: Graphics, half: number, share: number) => {
/** What a building view shows each frame. */
export interface BuildingLook {
+ /** A sign over it, and whether it is on fire. */
+ readonly alert?: Alert | null
+ readonly burning?: boolean
+ readonly worn?: boolean
readonly working: boolean
/** Something keeps it from working: show the marker. */
readonly problem: boolean
@@ -909,7 +956,7 @@ export class BuildingView extends Container {
// ── Homes ─────────────────────────────────────────────────────────────────
/** A home's full height, roof included. */
-export const homeHeight = (tier: Tier) => home.tiers[tier].height + HOUSE_ROOF + (tier === 2 ? 2 : 0)
+export const homeHeight = (tier: Tier) => home.tiers[tier].height + HOUSE_ROOF + (tier >= 2 ? 2 : 0)
/** Roof colours homes are built with: muted terracotta, slate, thatch, and moss; and the colour the household wears out walking. */
const homeRoofs: ReadonlyArray<{ readonly roof: RoofColors; readonly cloth: number }> = [
@@ -943,7 +990,7 @@ const plainHome: HomeVariant = { roof: paleRoof, cloth: 0x8f9891, ridge: "x", ch
* either side on every floor.
*/
export const drawHouse = (g: Graphics, tier: Tier, build: number, doors: Doors, variant: HomeVariant = plainHome) => {
- const a = (tier === 2 ? home.half + 1 : home.half) * U
+ const a = (tier >= 2 ? home.half + 1 : home.half) * U
const full = home.tiers[tier].height
const stage = buildStages(build)
if (stage.frame <= 0) return
@@ -952,10 +999,11 @@ export const drawHouse = (g: Graphics, tier: Tier, build: number, doors: Doors,
const H = Math.max(2, Math.round(full * stage.walls))
walls(g, a, H)
- const floors = tier === 2 ? [0, 12] : [0]
- if (tier === 2 && H > 13) {
- line(g, at(-a, a, 13), at(a, a, 13), DETAIL, ink, 0.7)
- line(g, at(a, -a, 13), at(a, a, 13), DETAIL, ink, 0.7)
+ const floors = tier === 3 ? [0, 12, 24] : tier === 2 ? [0, 12] : [0]
+ for (const z of tier === 3 ? [13, 25] : tier === 2 ? [13] : []) {
+ if (H <= z) continue
+ line(g, at(-a, a, z), at(a, a, z), DETAIL, ink, 0.7)
+ line(g, at(a, -a, z), at(a, a, z), DETAIL, ink, 0.7)
}
if (stage.fit > 0.15) {
for (const side of ["right", "left"] as const) {
@@ -972,13 +1020,13 @@ export const drawHouse = (g: Graphics, tier: Tier, build: number, doors: Doors,
}
}
if (floor + 10 > H) return
- if (tier === 2) {
+ if (tier >= 2) {
for (const along of [-3 * U, 3 * U]) if (!(door && Math.abs(along) < HOUSE_DOOR + 2 * U)) window_(g, side, a, along, floor + 5)
} else if (!door) window_(g, side, a, 0, floor + 5)
})
}
}
- gable(g, a, H, Math.round((HOUSE_ROOF + (tier === 2 ? 2 : 0)) * stage.fit), variant.ridge, variant.roof, variant.chimney || tier === 2)
+ gable(g, a, H, Math.round((HOUSE_ROOF + (tier >= 2 ? 2 : 0)) * stage.fit), variant.ridge, variant.roof, variant.chimney || tier >= 2)
}
/** What a home view shows each frame. */
@@ -988,8 +1036,18 @@ export interface HouseLook {
readonly doors: Doors
/** While a site: the share of its materials in, else `null`. */
readonly site: number | null
+ /** A sign over it: the risk most at hand, or that it is sick. */
+ readonly alert?: Alert | null
+ readonly burning?: boolean
+ /** Run down (see `condition.worn`). */
+ readonly worn?: boolean
+ /** Its neighbourhood: poor, plain, or fine (see `HouseView`). */
+ readonly band?: "poor" | "plain" | "fine"
}
+/** A sign that goes up over a home or building at risk. */
+export type Alert = "fire" | "health" | "order" | "sick" | "worn"
+
export class HouseView extends Container {
private readonly plate = new Graphics()
private readonly body = new Graphics()
@@ -1410,11 +1468,11 @@ export const serviceDress = (color: number, n: number, faith: boolean): PersonDr
* deeper-coloured coats and hats.
*/
export const residentDress = (cloth: number, tier: Tier, n: number): PersonDress => ({
- coat: tier === 2 ? mix(cloth, ink, 0.2) : mix(cloth, 0xffffff, 0.15),
- trim: tier === 2 ? ink : mix(cloth, 0xffffff, 0.55),
+ coat: tier >= 2 ? mix(cloth, ink, tier === 3 ? 0.35 : 0.2) : mix(cloth, 0xffffff, 0.15),
+ trim: tier >= 2 ? ink : mix(cloth, 0xffffff, 0.55),
skin: pick(skins, n * 13 + 0.1),
- hat: tier === 2 ? (n < 0.5 ? "top" : "brim") : n < 0.35 ? "bonnet" : n < 0.6 ? "cap" : "none",
- long: tier === 2 || n > 0.85
+ hat: tier === 3 ? "top" : tier === 2 ? (n < 0.5 ? "top" : "brim") : n < 0.35 ? "bonnet" : n < 0.6 ? "cap" : "none",
+ long: tier >= 2 || n > 0.85
})
/** Where a point on a cart is: `a` along the way it goes, `c` across it, from the cart's centre (u, v). */
@@ -1475,11 +1533,12 @@ export const drawCargo = (g: Graphics, u: number, v: number, d: Point, good: Goo
return
}
case "fish":
+ case "smoked":
case "bread": {
cartBox(g, u, v, d, 0, 0, 1.6 * U, 1.1 * U, z, 3, wicker)
for (let i = 0; i < n + 1; i++) {
const t = p(((i - n / 2) * 0.9) * U, (i % 2 === 0 ? -0.3 : 0.3) * U, z + 3)
- if (good === "fish") g.poly([t.x - 2.2, t.y, t.x, t.y - 1.4, t.x + 2.2, t.y, t.x, t.y + 1.2]).fill({ color: 0x2f8c87 }).stroke({ color: ink, width: 0.75 })
+ if (good !== "bread") g.poly([t.x - 2.2, t.y, t.x, t.y - 1.4, t.x + 2.2, t.y, t.x, t.y + 1.2]).fill({ color: good === "fish" ? 0x2f8c87 : 0x9a5b3a }).stroke({ color: ink, width: 0.75 })
else g.ellipse(t.x, t.y - 0.6, 1.8, 1.2).fill({ color: 0xd98a6a }).stroke({ color: ink, width: 0.75 })
}
return
diff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.ts
index 0f289b8..0bd84d1 100644
--- a/src/asset-lab/assets.ts
+++ b/src/asset-lab/assets.ts
@@ -7,6 +7,7 @@ import { U } from "../iso.ts"
import { makeTree, makeRock, makeField, makeRoadPatch, makeWater } from "./land.ts"
import { personCatalogue, makeCarrier, makeGoods, makeCrate } from "./people.ts"
import { makeSite, makeConstruction, makeMarker, makeSmoke, makePlot } from "./construction.ts"
+import { makeFlames, makeRuin, makeWarning } from "./placeholders.ts"
import { Drawing, mix, pale, square, sides, palette, type InkAsset, type Vertex } from "./primitives.ts"
export * from "./primitives.ts"
@@ -114,6 +115,7 @@ for (const tier of [1, 2] as const)
asset.title = `${tier === 1 ? "Cottage" : "Citizen home"} · ${names[i]}`
additional.push(asset)
}
+additional.push(house(3))
for (const type of ["fir", "broadleaf", "poplar"] as const)
for (const grown of [0.3, 0.6, 1]) {
if (type === "fir" && grown === 1) continue
@@ -134,6 +136,10 @@ additional.push(
makeConstruction("warehouse", 0.65),
makeMarker(),
makeSmoke(),
+ ...(["burnt", "collapsed", "derelict"] as const).map((cause) => makeRuin(1, cause)),
+ makeRuin(2, "burnt"),
+ ...(["fire", "health", "order", "sick", "worn"] as const).map((kind) => makeWarning(kind)),
+ makeFlames(0),
...["hover", "picked", "blocked", "reach"].map((look) => makePlot(look as "hover" | "picked" | "blocked" | "reach"))
)
export const inkAssets: ReadonlyArray<InkAsset> = [...approvedAssets, ...additional]
diff --git a/src/asset-lab/buildings.ts b/src/asset-lab/buildings.ts
index 9e97f16..1d6128f 100644
--- a/src/asset-lab/buildings.ts
+++ b/src/asset-lab/buildings.ts
@@ -1,6 +1,7 @@
import { kinds, type KindId } from "../content.ts"
import { U } from "../iso.ts"
import { Drawing, palette, pale, square, sides, type Vertex, type Side } from "./primitives.ts"
+import { makeDecor } from "./placeholders.ts"
const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }> = {
townhall: { accent: 0x8a58a8, glass: 0xf3dca6 },
@@ -18,7 +19,20 @@ const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }>
sheep: { accent: 0xb5654a, roof: 0xb5654a },
weaver: { accent: 0x8a58a8 },
market: { accent: 0x3d6db5 },
- chapel: { accent: 0x3d6db5, glass: 0xc9d6ee }
+ chapel: { accent: 0x3d6db5, glass: 0xc9d6ee },
+ // New kinds: the plain building in their colour, a placeholder until each has a model of its own.
+ granary: { accent: 0xd6ae2e },
+ smokehouse: { accent: 0x9a5b3a, roof: 0x9a5b3a },
+ firewatch: { accent: 0xc4523f, roof: 0xc4523f },
+ healer: { accent: 0x4f9a8a },
+ hospital: { accent: 0x4f9a8a, glass: 0xc9d6ee },
+ watchhouse: { accent: 0x3d4f6e },
+ builder: { accent: 0x8a6a45, roof: 0xb08a5a },
+ garden: { accent: 0x4f9a6a },
+ park: { accent: 0x4f9a6a },
+ fountain: { accent: 0x5f8fb0 },
+ statue: { accent: 0x8f9891 },
+ plaza: { accent: 0x8f9891 }
}
export interface BuildingOptions {
@@ -29,6 +43,7 @@ export interface BuildingOptions {
motion?: boolean
}
export function makeBuilding(id: KindId, options: BuildingOptions = {}) {
+ if (kinds[id].decor) return makeDecor(id)
const fit = options.fit ?? 1
const kind = kinds[id],
a = kind.half * U,
diff --git a/src/asset-lab/homes.ts b/src/asset-lab/homes.ts
index 310a9a0..b6219ed 100644
--- a/src/asset-lab/homes.ts
+++ b/src/asset-lab/homes.ts
@@ -4,19 +4,21 @@ import { U } from "../iso.ts"
import { Drawing, palette, sides, type Side } from "./primitives.ts"
export function house(
- tier: 1 | 2,
+ tier: 1 | 2 | 3,
variantN = tier === 1 ? 0.03 : 0.28,
- id = tier === 1 ? "cottage" : "citizen",
+ id = tier === 1 ? "cottage" : tier === 2 ? "citizen" : "townhouse",
options: { doors?: Partial<Record<Side, boolean>>; fit?: number; plate?: boolean } = {}
) {
const fit = options.fit ?? 1
const d = new Drawing(
id,
- tier === 1 ? "Settler cottage" : "Citizen home",
- "Original roof palette, footprint, chimney, windows and awnings. Rear walls completed for rotation."
+ tier === 1 ? "Settler cottage" : tier === 2 ? "Citizen home" : "Townhouse",
+ tier === 3
+ ? "Placeholder townhouse: the citizens' home raised a storey, until it has a model of its own."
+ : "Original roof palette, footprint, chimney, windows and awnings. Rear walls completed for rotation."
)
const variant = homeVariant(variantN)
- const a = (home.half + (tier === 2 ? 1 : 0)) * U,
+ const a = (home.half + (tier >= 2 ? 1 : 0)) * U,
H = home.tiers[tier].height
d.asset.category = "homes"
d.asset.reference = { type: "house", tier, variant: variantN }
@@ -25,10 +27,10 @@ export function house(
d.box(0, 0, a, a, 0, H)
for (const side of sides) {
const door = options.doors ? !!options.doors[side] : side === "right"
- if (tier === 2) d.line([d.wall(side, a, -a, 13), d.wall(side, a, a, 13)], 1, palette.ink, 0.7)
+ for (const z of tier === 3 ? [13, 25] : tier === 2 ? [13] : []) d.line([d.wall(side, a, -a, z), d.wall(side, a, a, z)], 1, palette.ink, 0.7)
if (door && fit > 0.15) d.door(side, a, Math.max(2, 9 * fit), 2 * U, 3 * U, 2 * U, variant.roof.shade)
- for (const floor of fit > 0.4 ? (tier === 2 ? [0, 12] : [0]) : []) {
- if (tier === 2) {
+ for (const floor of fit > 0.4 ? (tier === 3 ? [0, 12, 24] : tier === 2 ? [0, 12] : [0]) : []) {
+ if (tier >= 2) {
for (const along of [-3 * U, 3 * U]) if (!(door && floor === 0)) d.window(side, a, along, floor + 5)
} else if (!door) d.window(side, a, 0, 5)
}
@@ -37,11 +39,11 @@ export function house(
d.gable(
a,
H,
- (tier === 2 ? 10 : 8) * fit,
+ (tier >= 2 ? 10 : 8) * fit,
variant.ridge,
variant.roof.face,
variant.roof.shade,
- fit > 0.8 && (variant.chimney || tier === 2)
+ fit > 0.8 && (variant.chimney || tier >= 2)
)
return d.asset
}
diff --git a/src/asset-lab/people.ts b/src/asset-lab/people.ts
index 9f4369e..27ed42b 100644
--- a/src/asset-lab/people.ts
+++ b/src/asset-lab/people.ts
@@ -162,24 +162,29 @@ export function drawCargo(d: Drawing, good: GoodId, count: number, u: number, v:
break
}
case "fish":
- case "bread":
+ case "smoked":
+ case "bread": {
+ // Smoked fish is fish in the smokehouse's brown.
+ const fishy = good !== "bread",
+ tint = good === "fish" ? 0x2f8c87 : good === "smoked" ? 0x9a5b3a : 0xd98a6a
d.box(u, v, 1.6 * U, 1.1 * U, z, 3, 0xc9a46a, 0xe3c592, 0xd2b07a, 1)
for (let i = 0; i < n + 1; i++) {
const x = u + (i - n / 2) * 0.9 * U,
y = v + (i % 2 === 0 ? -0.3 : 0.3) * U
- d.ellipsoid(x, y, z + 3.6, good === "fish" ? 0.049 : 0.04, 0.028, 0.75, good === "fish" ? 0x2f8c87 : 0xd98a6a, 0.75)
- if (good === "fish")
+ d.ellipsoid(x, y, z + 3.6, fishy ? 0.049 : 0.04, 0.028, 0.75, tint, 0.75)
+ if (fishy)
d.face(
[
[x - 0.055, y - 0.03, z + 3.6],
[x - 0.055, y + 0.03, z + 3.6],
[x - 0.02, y, z + 3.6]
],
- 0x2f8c87,
+ tint,
0.75
)
}
break
+ }
case "flour":
;[-1, 1, 0].slice(0, n).forEach((a, i) => d.sack(u + a * U, v, z + (i === 2 ? 4 : 0)))
break
diff --git a/src/asset-lab/placeholders.ts b/src/asset-lab/placeholders.ts
new file mode 100644
index 0000000..a9248de
--- /dev/null
+++ b/src/asset-lab/placeholders.ts
@@ -0,0 +1,132 @@
+/**
+ * Placeholder models for what the town gained with desirability, services,
+ * and decay: ornaments (garden, park, fountain, statue, plaza), ruins, the
+ * signs that go up over a home at risk, and flames. They are built from the
+ * same primitives as everything else so they sit in the drawing, but they
+ * are simple stand-ins until each gets a proper model.
+ */
+import { kinds, type KindId } from "../content.ts"
+import { U } from "../iso.ts"
+import { Drawing, palette, square, type Vertex } from "./primitives.ts"
+
+const green = 0xd8e6c9
+const leaves = 0xa9c79a
+const stone = 0xe4e6e0
+const water = 0xc9dde6
+
+const tree = (d: Drawing, u: number, v: number, size = 1) => {
+ d.line([[u, v, 0], [u, v, 5 * size]], 1.5, 0x6b5a45)
+ d.ellipsoid(u, v, 5 * size + 6 * size, (5 * size) / 64, (5 * size) / 64, 6 * size, leaves, 1)
+}
+
+const figure = (d: Drawing, u: number, v: number, z: number) => {
+ d.box(u, v, 2.5 * U, 2.5 * U, z - 6, 6, stone, 0xdcded7, 0xc9ccc4)
+ d.cylinder(u, v, 0.9 * U, z, 11, 0xb9beb5, 0xc9ccc4, 1, 10)
+ d.ellipsoid(u, v, z + 13, 0.9 * U, 0.9 * U, 2.2, 0xc9ccc4, 1, undefined, 10)
+}
+
+/** An ornament of `id`, `size` cells a side, on its plate. */
+export function makeDecor(id: KindId) {
+ const kind = kinds[id],
+ p = (kind.size * 8 - 1) * U
+ const d = new Drawing(id, kind.title, "Placeholder ornament: simple shapes standing in until it has a model of its own.")
+ d.asset.category = "buildings"
+ d.asset.reference = { type: "building", kind: id }
+ d.asset.footprint = kind.size
+ d.face(square(0, 0, p, -0.15), id === "plaza" || id === "statue" || id === "fountain" ? stone : green)
+ if (id === "garden") {
+ tree(d, -p / 2, -p / 2, 0.7)
+ tree(d, p / 2, p / 2, 0.8)
+ for (const [u, v, c] of [[p / 2, -p / 2, 0xe89a7c], [-p / 2, p / 2, 0xe3c25a], [0, 0, 0xc9a0d6]] as const) d.box(u, v, 1.5 * U, 1.5 * U, 0, 2, c, c, c, 1)
+ } else if (id === "park") {
+ tree(d, -p / 2, -p / 2, 1.1)
+ tree(d, p / 2, -p / 3, 0.9)
+ tree(d, -p / 3, p / 2, 1)
+ d.line([[-p, p / 6, 0.02], [p, -p / 6, 0.02]], 3, 0xe6e8e2)
+ d.box(p / 2, p / 2, 3 * U, U, 0, 3, 0xd5a86c, 0xc79a5b, 0xb08a5a, 1)
+ } else if (id === "fountain") {
+ d.cylinder(0, 0, 5.5 * U, 0, 4, 0xdfe3dc, water, 1, 16)
+ d.cylinder(0, 0, 1.2 * U, 4, 7, 0xdfe3dc, stone, 1, 10)
+ d.cylinder(0, 0, 2.5 * U, 11, 2, 0xdfe3dc, water, 1, 12)
+ } else if (id === "statue") {
+ figure(d, 0, 0, 6)
+ } else if (id === "plaza") {
+ for (let i = -2; i <= 2; i++) {
+ d.line([[-p, (i * p) / 3, 0.02], [p, (i * p) / 3, 0.02]], 1, 0xc9ccc4)
+ d.line([[(i * p) / 3, -p, 0.02], [(i * p) / 3, p, 0.02]], 1, 0xc9ccc4)
+ }
+ figure(d, 0, 0, 6)
+ tree(d, -p * 0.75, -p * 0.75, 0.7)
+ tree(d, p * 0.75, p * 0.75, 0.7)
+ }
+ return d.asset
+}
+
+/** What is left of a home or building: charred, tumbled down, or boarded up. */
+export function makeRuin(size: number, cause: "burnt" | "collapsed" | "derelict") {
+ const d = new Drawing(`ruin-${cause}-${size}`, `Ruin · ${cause}`, "Placeholder ruin: broken walls on a cleared plate, until it has a model of its own.")
+ d.asset.category = "construction"
+ d.asset.reference = { type: "none" }
+ d.asset.footprint = size
+ const p = (size * 8 - 1) * U,
+ a = p - 2 * U
+ const wall = cause === "burnt" ? 0x77736b : cause === "collapsed" ? 0xe2ddd0 : 0xd9d4c7
+ d.face(square(0, 0, p, -0.15), cause === "burnt" ? 0xb9b5ab : 0xe9e6dd)
+ if (cause === "derelict") {
+ d.box(0, 0, a, a, 0, 9, 0xcfcabd, wall, 0xc4bfb2)
+ for (const s of [-1, 1]) d.line([[a + 0.004, s * a * 0.4, 2], [a + 0.004, -s * a * 0.4, 7]], 1.5, 0x8a6a45)
+ return d.asset
+ }
+ const pieces: ReadonlyArray<readonly [number, number, number]> = [[-a, -a, 7], [a * 0.3, -a, 4], [-a, a * 0.2, 5], [a * 0.6, a * 0.6, 3]]
+ for (const [u, v, h] of pieces) d.box(u + U, v + U, 1.2 * U * size, 1.2 * U * size, 0, h, wall, wall, 0xc4bfb2, 1)
+ if (cause === "burnt") for (let i = 0; i < 3; i++) d.line([[-a + i * a * 0.6, -a * 0.5, 0.5], [-a + i * a * 0.7 + a * 0.4, a * 0.4, 3]], 2, 0x3d4943)
+ else for (let i = 0; i < 4; i++) d.box(-a * 0.2 + i * U * 2, a * 0.1, U, U, 0, 1.5, wall, wall, wall, 1)
+ return d.asset
+}
+
+export type WarningKind = "fire" | "health" | "order" | "sick" | "worn"
+
+/** A sign over a home at risk, facing the camera: a smoke wisp, a pale face, a broken window, a sick face, a cracked wall. */
+export function makeWarning(kind: WarningKind) {
+ const d = new Drawing(`warning-${kind}`, `Warning · ${kind}`, "Placeholder sign over a home or building at risk.")
+ d.asset.category = "construction"
+ d.asset.reference = { type: "none" }
+ d.asset.footprint = 1
+ const at = (x: number, z: number): Vertex => [x / 64, -x / 64, z]
+ const edge = kind === "fire" ? 0xc4523f : kind === "health" || kind === "sick" ? 0x4f9a6a : kind === "order" ? 0x3d4f6e : 0x8a6a45
+ d.face([at(-7, 0), at(7, 0), at(7, 14), at(-7, 14)], 0xf6f7f3, 1, edge)
+ if (kind === "fire") {
+ d.line([at(-1, 2), at(-3, 5), at(0, 8), at(-2, 11), at(1, 13)], 1.5, 0x77817a)
+ d.line([at(3, 3), at(2, 6), at(4, 9)], 1, 0x9aa29b)
+ } else if (kind === "health" || kind === "sick") {
+ const ring = Array.from({ length: 16 }, (_, i): Vertex => at(Math.cos((i / 16) * Math.PI * 2) * 4.5, 7 + Math.sin((i / 16) * Math.PI * 2) * 4.5))
+ d.face(ring, kind === "sick" ? 0xc9dfb4 : 0xf1f0e6, 1)
+ d.face([at(-2.2, 8), at(-1.2, 8), at(-1.2, 9), at(-2.2, 9)], palette.ink, 0)
+ d.face([at(1.2, 8), at(2.2, 8), at(2.2, 9), at(1.2, 9)], palette.ink, 0)
+ d.line([at(-2, 4.5), at(0, 5.5), at(2, 4.5)], 1)
+ } else if (kind === "order") {
+ d.face([at(-4, 3), at(4, 3), at(4, 11), at(-4, 11)], 0xdbe6ea, 1)
+ d.line([at(0, 3), at(0, 11)], 1)
+ d.line([at(-4, 7), at(4, 7)], 1)
+ d.line([at(-3, 10), at(1, 6), at(-1, 5), at(3, 3.5)], 1.5, 0xc4523f)
+ } else {
+ d.line([at(-4, 12), at(-1, 8), at(-3, 6), at(1, 2)], 1.5, 0x8a6a45)
+ d.line([at(2, 12), at(4, 9)], 1, 0x8a6a45)
+ }
+ return d.asset
+}
+
+/** Flames over a burning home or building, facing the camera; `phase` 0 or 1 flickers them. */
+export function makeFlames(phase: number) {
+ const d = new Drawing(`flames-${phase}`, "Flames", "Placeholder flames over a burning home or building.")
+ d.asset.category = "construction"
+ d.asset.reference = { type: "none" }
+ d.asset.footprint = 1
+ const at = (x: number, z: number): Vertex => [x / 64, -x / 64, z]
+ const tongue = (x: number, w: number, h: number, color: number) =>
+ d.face([at(x - w, 0), at(x - w * 0.4, h * 0.55), at(x + (phase ? w * 0.3 : -w * 0.3), h), at(x + w * 0.5, h * 0.5), at(x + w, 0)], color, 1, 0xc4523f)
+ tongue(-5, 4, phase ? 14 : 12, 0xf0a868)
+ tongue(4, 4, phase ? 11 : 15, 0xf0a868)
+ tongue(0, 5, phase ? 20 : 18, 0xf3c76b)
+ return d.asset
+}
diff --git a/src/content.ts b/src/content.ts
index 849beab..61b6c86 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -12,7 +12,7 @@ export const ticks = (seconds: number): number => Math.round(seconds / STEP_SECO
// ── Goods ─────────────────────────────────────────────────────────────────
-export const goodIds = ["wood", "planks", "stone", "ore", "tools", "fish", "wheat", "flour", "bread", "wool", "cloth"] as const
+export const goodIds = ["wood", "planks", "stone", "ore", "tools", "fish", "smoked", "wheat", "flour", "bread", "wool", "cloth"] as const
export type GoodId = (typeof goodIds)[number]
/** Each good's crate label colour (the only colour a good has), and what traders pay for one. */
@@ -23,6 +23,7 @@ export const goods: Readonly<Record<GoodId, { readonly title: string; readonly c
ore: { title: "ore", color: 0x5a6479, price: 3 },
tools: { title: "tools", color: 0x3d4943, price: 10 },
fish: { title: "fish", color: 0x2f8c87, price: 2 },
+ smoked: { title: "smoked fish", color: 0x9a5b3a, price: 4 },
wheat: { title: "wheat", color: 0xd6ae2e, price: 1 },
flour: { title: "flour", color: 0xc9b48a, price: 2 },
bread: { title: "bread", color: 0xc4523f, price: 4 },
@@ -40,7 +41,7 @@ export const RESERVES = [10, 25, 50, 100] as const
export const trade = { sells: ["wood", "wheat", "wool"] as ReadonlyArray<GoodId>, reserve: 25 }
export type Amounts = Readonly<Record<GoodId, number>>
-export const none: Amounts = { wood: 0, planks: 0, stone: 0, ore: 0, tools: 0, fish: 0, wheat: 0, flour: 0, bread: 0, wool: 0, cloth: 0 }
+export const none: Amounts = { wood: 0, planks: 0, stone: 0, ore: 0, tools: 0, fish: 0, smoked: 0, wheat: 0, flour: 0, bread: 0, wool: 0, cloth: 0 }
export const amounts = (some: Partial<Record<GoodId, number>>): Amounts => ({ ...none, ...some })
export const total = (a: Amounts): number => goodIds.reduce((sum, g) => sum + a[g], 0)
/** Amounts made good by good. */
@@ -51,14 +52,24 @@ export const each = (f: (good: GoodId) => number): Amounts => {
}
/** Goods a market walker hands out to homes. */
-export const provisions: ReadonlyArray<GoodId> = ["fish", "bread", "cloth"]
+export const provisions: ReadonlyArray<GoodId> = ["fish", "smoked", "bread", "cloth"]
/** Goods the top bar shows, in order. */
-export const shownGoods: ReadonlyArray<GoodId> = ["wood", "planks", "stone", "tools", "fish", "bread", "cloth"]
+export const shownGoods: ReadonlyArray<GoodId> = ["wood", "planks", "stone", "tools", "fish", "smoked", "bread", "cloth"]
+/** Goods that are food in store (see `larder`). */
+export const foods: ReadonlyArray<GoodId> = ["fish", "smoked", "bread"]
+
+/**
+ * Food spoils in store: about how many seconds a fish or a loaf keeps. A
+ * granary keeps it `KEEPS` times as long; smoked fish, wheat, and flour keep.
+ * Every `SPOIL_TICKS`, each shelf loses its share of what it holds.
+ */
+export const spoils: Partial<Record<GoodId, number>> = { fish: 180, bread: 300 }
+export const SPOIL_TICKS = 600
// ── Buildings ─────────────────────────────────────────────────────────────
-export type Category = "storage" | "gathering" | "crafts" | "food" | "services"
-export const categoryOrder: ReadonlyArray<Category> = ["storage", "gathering", "crafts", "food", "services"]
+export type Category = "storage" | "gathering" | "crafts" | "food" | "services" | "decor"
+export const categoryOrder: ReadonlyArray<Category> = ["storage", "gathering", "crafts", "food", "services", "decor"]
/** Awnings are coloured by what a building is for. */
export const categoryColor: Readonly<Record<Category, number>> = {
@@ -66,19 +77,25 @@ export const categoryColor: Readonly<Record<Category, number>> = {
gathering: 0x6e8f36,
crafts: 0xd27a34,
food: 0xd6ae2e,
- services: 0x3d6db5
+ services: 0x3d6db5,
+ decor: 0x4f9a6a
}
export const homeColor = 0xc4523f
/** What a gatherer takes from the land around it. */
export type Source = "tree" | "stone" | "ore" | "field" | "water"
-export type ServiceId = "goods" | "faith"
+export const serviceIds = ["goods", "faith", "fire", "health", "order", "repair"] as const
+export type ServiceId = (typeof serviceIds)[number]
+/** Who works a building: settlers do the rough work, citizens the skilled (see `AssignStaff`). */
+export type Crew = "settlers" | "citizens"
export type Topper = "none" | "chimney" | "flag" | "cupola" | "sails" | "crates"
export const kindIds = [
"townhall", "warehouse", "lumberjack", "forester", "quarry", "mine", "fishery", "sawmill",
- "smithy", "farm", "mill", "bakery", "sheep", "weaver", "market", "chapel"
+ "smithy", "farm", "mill", "bakery", "sheep", "weaver", "market", "chapel",
+ "granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder",
+ "garden", "park", "fountain", "statue", "plaza"
] as const
export type KindId = (typeof kindIds)[number]
@@ -88,7 +105,7 @@ export interface Kind {
readonly blurb: string
readonly category: Category
/** Cells a side. */
- readonly size: 2 | 3
+ readonly size: 1 | 2 | 3
// ── Look (see `art.ts`) ──
/** Half the building's width, in units: its walls stand this far from its centre. */
readonly half: number
@@ -103,6 +120,8 @@ export interface Kind {
/** Coins a minute while it stands. */
readonly upkeep: number
readonly workers: number
+ /** Who works it: settlers, or citizens (settlers stand in as apprentices, at a slower pace). */
+ readonly crew: Crew
/** Residents (and of them citizens) the town needs before it can be built. */
readonly unlock: { readonly residents: number; readonly citizens: number }
/** In the build menu (the town hall is not). */
@@ -120,6 +139,19 @@ export interface Kind {
readonly carriers?: number
/** Sends a walker down the roads every `seconds`, `range` cells out. */
readonly service?: { readonly service: ServiceId; readonly seconds: number; readonly range: number }
+ // ── Its neighbourhood ──
+ /** What it does to the desirability of the cells around it, fading out to `reach` cells (see `appeal.ts`). */
+ readonly appeal?: { readonly value: number; readonly reach: number }
+ /** Uses up a tool every `wear` jobs, and works at half pace without one. */
+ readonly wear?: number
+ /** Ovens and forges: a fire risk to itself and to homes beside it. */
+ readonly hot?: boolean
+ /** Dust: a health risk to homes nearby. */
+ readonly dusty?: boolean
+ /** A storage that keeps food this many times longer. */
+ readonly keeps?: number
+ /** An ornament: no workers, no road, no wear; only its desirability. */
+ readonly decor?: boolean
}
const free = { residents: 0, citizens: 0 }
@@ -130,107 +162,191 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
townhall: {
id: "townhall", title: "Town hall", blurb: "the heart of the town: storage, taxes, and a walker with provisions",
category: "storage", size: 3, half: 20, stories: 2, roof: "flat", bays: 2, window: 8, topper: "flag",
- cost: { coins: 0, materials: {} }, upkeep: 0, workers: 0, unlock: free, buildable: false,
+ cost: { coins: 0, materials: {} }, upkeep: 0, workers: 0, crew: "settlers", unlock: free, buildable: false,
holds: { accepts: "all", cap: 100 }, carriers: 6,
- service: { service: "goods", seconds: 8, range: 20 }
+ service: { service: "goods", seconds: 8, range: 20 }, appeal: { value: 4, reach: 3 }
},
warehouse: {
id: "warehouse", title: "Warehouse", blurb: "stores goods nearer where they are made and used",
category: "storage", size: 3, half: 18, stories: 1, roof: "flat", bays: 3, window: 6, topper: "crates",
- cost: { coins: 150, materials: { planks: 8, stone: 4 } }, upkeep: 6, workers: 2, unlock: free, buildable: true,
- holds: { accepts: "all", cap: 50 }, carriers: 4
+ cost: { coins: 150, materials: { planks: 8, stone: 4 } }, upkeep: 6, workers: 2, crew: "settlers", unlock: free, buildable: true,
+ holds: { accepts: "all", cap: 50 }, carriers: 4, appeal: { value: -2, reach: 2 }
+ },
+ granary: {
+ id: "granary", title: "Granary", blurb: "stores food, and keeps fish and bread five times as long",
+ category: "storage", size: 2, half: 11, stories: 2, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 120, materials: { planks: 6, stone: 2 } }, upkeep: 4, workers: 1, crew: "settlers", unlock: { residents: 20, citizens: 0 }, buildable: true,
+ holds: { accepts: ["fish", "smoked", "bread", "wheat", "flour"], cap: 60 }, carriers: 3, keeps: 5, appeal: { value: -2, reach: 2 }
},
lumberjack: {
id: "lumberjack", title: "Lumberjack", blurb: "fells grown trees nearby for wood",
category: "gathering", size: 2, half: 10, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
- cost: { coins: 50, materials: { planks: 2 } }, upkeep: 3, workers: 2, unlock: free, buildable: true,
- recipe: { input: null, inputs: 0, output: "wood", batch: 1, seconds: 6 }, gathers: { source: "tree", radius: 4 }, carriers: 2
+ cost: { coins: 50, materials: { planks: 2 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: free, buildable: true,
+ recipe: { input: null, inputs: 0, output: "wood", batch: 1, seconds: 6 }, gathers: { source: "tree", radius: 4 }, carriers: 2,
+ wear: 60, appeal: { value: -2, reach: 2 }
},
forester: {
id: "forester", title: "Forester", blurb: "plants trees on free ground nearby",
category: "gathering", size: 2, half: 9, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
- cost: { coins: 40, materials: { planks: 2 } }, upkeep: 2, workers: 1, unlock: free, buildable: true,
+ cost: { coins: 40, materials: { planks: 2 } }, upkeep: 2, workers: 1, crew: "settlers", unlock: free, buildable: true,
plants: { what: "tree", radius: 3, seconds: 6, max: 20 }
},
quarry: {
id: "quarry", title: "Quarry", blurb: "cuts stone from rocks nearby",
category: "gathering", size: 2, half: 10, stories: 1, roof: "flat", bays: 2, window: 6, topper: "none",
- cost: { coins: 80, materials: { planks: 4 } }, upkeep: 5, workers: 3, unlock: free, buildable: true,
- recipe: { input: null, inputs: 0, output: "stone", batch: 1, seconds: 8 }, gathers: { source: "stone", radius: 3 }, carriers: 2
+ cost: { coins: 80, materials: { planks: 4 } }, upkeep: 5, workers: 3, crew: "settlers", unlock: free, buildable: true,
+ recipe: { input: null, inputs: 0, output: "stone", batch: 1, seconds: 8 }, gathers: { source: "stone", radius: 3 }, carriers: 2,
+ wear: 50, dusty: true, appeal: { value: -8, reach: 4 }
},
mine: {
id: "mine", title: "Mine", blurb: "digs ore from a deposit nearby",
category: "gathering", size: 2, half: 10, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
- cost: { coins: 200, materials: { planks: 6, stone: 4 } }, upkeep: 10, workers: 4, unlock: { residents: 0, citizens: 10 }, buildable: true,
- recipe: { input: null, inputs: 0, output: "ore", batch: 1, seconds: 10 }, gathers: { source: "ore", radius: 3 }, carriers: 2
+ cost: { coins: 200, materials: { planks: 6, stone: 4 } }, upkeep: 10, workers: 4, crew: "settlers", unlock: { residents: 0, citizens: 10 }, buildable: true,
+ recipe: { input: null, inputs: 0, output: "ore", batch: 1, seconds: 10 }, gathers: { source: "ore", radius: 3 }, carriers: 2,
+ wear: 50, dusty: true, appeal: { value: -8, reach: 4 }
},
fishery: {
id: "fishery", title: "Fishery", blurb: "catches fish; needs water within two cells",
category: "food", size: 2, half: 10, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
- cost: { coins: 60, materials: { planks: 3 } }, upkeep: 3, workers: 2, unlock: free, buildable: true,
- recipe: { input: null, inputs: 0, output: "fish", batch: 1, seconds: 4 }, gathers: { source: "water", radius: 2 }, carriers: 2
+ cost: { coins: 60, materials: { planks: 3 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: free, buildable: true,
+ recipe: { input: null, inputs: 0, output: "fish", batch: 1, seconds: 4 }, gathers: { source: "water", radius: 2 }, carriers: 2,
+ appeal: { value: -2, reach: 2 }
+ },
+ smokehouse: {
+ id: "smokehouse", title: "Smokehouse", blurb: "smokes fish, which then keeps all winter",
+ category: "food", size: 2, half: 10, stories: 1, roof: "gable", bays: 2, window: 4, topper: "chimney",
+ cost: { coins: 90, materials: { planks: 4, stone: 1 } }, upkeep: 4, workers: 2, crew: "settlers", unlock: { residents: 20, citizens: 0 }, buildable: true,
+ recipe: { input: "fish", inputs: 1, output: "smoked", batch: 1, seconds: 5 }, holds: { accepts: ["fish", "smoked"], cap: 8 }, carriers: 2,
+ wear: 60, hot: true, appeal: { value: -4, reach: 3 }
},
sawmill: {
id: "sawmill", title: "Sawmill", blurb: "saws wood into planks",
category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
- cost: { coins: 100, materials: { planks: 2, stone: 2 } }, upkeep: 6, workers: 2, unlock: free, buildable: true,
- recipe: { input: "wood", inputs: 1, output: "planks", batch: 1, seconds: 5 }, holds: { accepts: ["wood", "planks"], cap: 8 }, carriers: 2
+ cost: { coins: 100, materials: { planks: 2, stone: 2 } }, upkeep: 6, workers: 2, crew: "citizens", unlock: free, buildable: true,
+ recipe: { input: "wood", inputs: 1, output: "planks", batch: 1, seconds: 5 }, holds: { accepts: ["wood", "planks"], cap: 8 }, carriers: 2,
+ wear: 60, appeal: { value: -4, reach: 3 }
},
smithy: {
id: "smithy", title: "Smithy", blurb: "forges ore into tools",
category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
- cost: { coins: 250, materials: { planks: 4, stone: 6 } }, upkeep: 12, workers: 3, unlock: { residents: 0, citizens: 10 }, buildable: true,
- recipe: { input: "ore", inputs: 1, output: "tools", batch: 1, seconds: 10 }, holds: { accepts: ["ore", "tools"], cap: 8 }, carriers: 2
+ cost: { coins: 250, materials: { planks: 4, stone: 6 } }, upkeep: 12, workers: 3, crew: "citizens", unlock: { residents: 0, citizens: 10 }, buildable: true,
+ recipe: { input: "ore", inputs: 1, output: "tools", batch: 1, seconds: 10 }, holds: { accepts: ["ore", "tools"], cap: 8 }, carriers: 2,
+ hot: true, appeal: { value: -8, reach: 4 }
},
farm: {
id: "farm", title: "Farm", blurb: "sows fields around it and harvests the wheat",
category: "food", size: 3, half: 12, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
- cost: { coins: 120, materials: { planks: 4 } }, upkeep: 5, workers: 2, unlock: { residents: 30, citizens: 0 }, buildable: true,
+ cost: { coins: 120, materials: { planks: 4 } }, upkeep: 5, workers: 2, crew: "settlers", unlock: { residents: 30, citizens: 0 }, buildable: true,
recipe: { input: null, inputs: 0, output: "wheat", batch: 1, seconds: 4 }, gathers: { source: "field", radius: 2 },
- plants: { what: "field", radius: 2, seconds: 3, max: 8 }, carriers: 2
+ plants: { what: "field", radius: 2, seconds: 3, max: 8 }, carriers: 2, appeal: { value: -2, reach: 2 }
},
mill: {
id: "mill", title: "Mill", blurb: "grinds wheat into flour",
category: "food", size: 2, half: 8, stories: 2, roof: "flat", bays: 2, window: 4, topper: "sails",
- cost: { coins: 150, materials: { planks: 6, stone: 2, tools: 2 } }, upkeep: 8, workers: 2, unlock: { residents: 30, citizens: 0 }, buildable: true,
- recipe: { input: "wheat", inputs: 1, output: "flour", batch: 1, seconds: 6 }, holds: { accepts: ["wheat", "flour"], cap: 8 }, carriers: 2
+ cost: { coins: 150, materials: { planks: 6, stone: 2, tools: 2 } }, upkeep: 8, workers: 2, crew: "citizens", unlock: { residents: 30, citizens: 0 }, buildable: true,
+ recipe: { input: "wheat", inputs: 1, output: "flour", batch: 1, seconds: 6 }, holds: { accepts: ["wheat", "flour"], cap: 8 }, carriers: 2,
+ wear: 60, appeal: { value: -4, reach: 3 }
},
bakery: {
id: "bakery", title: "Bakery", blurb: "bakes flour into bread",
category: "food", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "chimney",
- cost: { coins: 150, materials: { planks: 4, stone: 4, tools: 2 } }, upkeep: 8, workers: 2, unlock: { residents: 30, citizens: 0 }, buildable: true,
- recipe: { input: "flour", inputs: 1, output: "bread", batch: 2, seconds: 6 }, holds: { accepts: ["flour", "bread"], cap: 8 }, carriers: 2
+ cost: { coins: 150, materials: { planks: 4, stone: 4, tools: 2 } }, upkeep: 8, workers: 2, crew: "citizens", unlock: { residents: 30, citizens: 0 }, buildable: true,
+ recipe: { input: "flour", inputs: 1, output: "bread", batch: 2, seconds: 6 }, holds: { accepts: ["flour", "bread"], cap: 8 }, carriers: 2,
+ wear: 60, hot: true, appeal: { value: -4, reach: 3 }
},
sheep: {
id: "sheep", title: "Sheep farm", blurb: "shears sheep for wool",
category: "crafts", size: 3, half: 12, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
- cost: { coins: 100, materials: { planks: 4 } }, upkeep: 5, workers: 2, unlock: { residents: 15, citizens: 0 }, buildable: true,
- recipe: { input: null, inputs: 0, output: "wool", batch: 1, seconds: 8 }, carriers: 2
+ cost: { coins: 100, materials: { planks: 4 } }, upkeep: 5, workers: 2, crew: "settlers", unlock: { residents: 15, citizens: 0 }, buildable: true,
+ recipe: { input: null, inputs: 0, output: "wool", batch: 1, seconds: 8 }, carriers: 2, appeal: { value: -2, reach: 2 }
},
weaver: {
id: "weaver", title: "Weaver", blurb: "weaves wool into cloth",
category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "none",
- cost: { coins: 150, materials: { planks: 4, stone: 2, tools: 2 } }, upkeep: 8, workers: 2, unlock: { residents: 15, citizens: 0 }, buildable: true,
- recipe: { input: "wool", inputs: 1, output: "cloth", batch: 1, seconds: 8 }, holds: { accepts: ["wool", "cloth"], cap: 8 }, carriers: 2
+ cost: { coins: 150, materials: { planks: 4, stone: 2, tools: 2 } }, upkeep: 8, workers: 2, crew: "citizens", unlock: { residents: 15, citizens: 0 }, buildable: true,
+ recipe: { input: "wool", inputs: 1, output: "cloth", batch: 1, seconds: 8 }, holds: { accepts: ["wool", "cloth"], cap: 8 }, carriers: 2,
+ wear: 60, appeal: { value: -2, reach: 2 }
},
market: {
id: "market", title: "Market", blurb: "a walker carries fish, bread, and cloth to the homes it passes",
category: "services", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "flag",
- cost: { coins: 120, materials: { planks: 6, stone: 2 } }, upkeep: 6, workers: 2, unlock: free, buildable: true,
- holds: { accepts: ["fish", "bread", "cloth"], cap: 12 },
- service: { service: "goods", seconds: 6, range: 18 }
+ cost: { coins: 120, materials: { planks: 6, stone: 2 } }, upkeep: 6, workers: 2, crew: "citizens", unlock: free, buildable: true,
+ holds: { accepts: ["fish", "smoked", "bread", "cloth"], cap: 12 },
+ service: { service: "goods", seconds: 6, range: 18 }, appeal: { value: 2, reach: 3 }
},
chapel: {
id: "chapel", title: "Chapel", blurb: "a walker brings faith to the homes it passes",
category: "services", size: 2, half: 12, stories: 2, roof: "flat", bays: 2, window: 6, topper: "cupola",
- cost: { coins: 200, materials: { planks: 6, stone: 6 } }, upkeep: 10, workers: 1, unlock: { residents: 15, citizens: 0 }, buildable: true,
- service: { service: "faith", seconds: 8, range: 22 }
+ cost: { coins: 200, materials: { planks: 6, stone: 6 } }, upkeep: 10, workers: 1, crew: "citizens", unlock: { residents: 15, citizens: 0 }, buildable: true,
+ service: { service: "faith", seconds: 8, range: 22 }, appeal: { value: 4, reach: 3 }
+ },
+ firewatch: {
+ id: "firewatch", title: "Fire watch", blurb: "a watchman checks homes and workshops along the way for fire; firefighters run to any blaze",
+ category: "services", size: 2, half: 9, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 70, materials: { planks: 3 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: free, buildable: true,
+ service: { service: "fire", seconds: 7, range: 30 }
+ },
+ healer: {
+ id: "healer", title: "Healer", blurb: "a physician calls on the homes along the way and cures the sick",
+ category: "services", size: 2, half: 10, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 110, materials: { planks: 4, stone: 2 } }, upkeep: 4, workers: 1, crew: "citizens", unlock: { residents: 30, citizens: 0 }, buildable: true,
+ service: { service: "health", seconds: 8, range: 30 }, appeal: { value: 1, reach: 2 }
+ },
+ hospital: {
+ id: "hospital", title: "Hospital", blurb: "physicians call more often and walk further",
+ category: "services", size: 3, half: 16, stories: 2, roof: "flat", bays: 2, window: 6, topper: "cupola",
+ cost: { coins: 400, materials: { planks: 10, stone: 10, tools: 2 } }, upkeep: 16, workers: 4, crew: "citizens", unlock: { residents: 0, citizens: 40 }, buildable: true,
+ service: { service: "health", seconds: 4, range: 40 }, appeal: { value: 2, reach: 3 }
+ },
+ watchhouse: {
+ id: "watchhouse", title: "Watch house", blurb: "a constable walks the streets, keeping order in the homes along the way",
+ category: "services", size: 2, half: 10, stories: 1, roof: "flat", bays: 2, window: 4, topper: "flag",
+ cost: { coins: 100, materials: { planks: 4, stone: 2 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: { residents: 40, citizens: 0 }, buildable: true,
+ service: { service: "order", seconds: 8, range: 30 }
+ },
+ builder: {
+ id: "builder", title: "Builder's yard", blurb: "a builder mends the homes and buildings along the way, with planks and stone",
+ category: "services", size: 2, half: 10, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
+ cost: { coins: 90, materials: { planks: 4 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: free, buildable: true,
+ holds: { accepts: ["planks", "stone"], cap: 6 },
+ service: { service: "repair", seconds: 8, range: 20 }, appeal: { value: -2, reach: 2 }
+ },
+ garden: {
+ id: "garden", title: "Garden", blurb: "a row of trees and flowers: the street around it is nicer to live on",
+ category: "decor", size: 1, half: 6, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 15, materials: {} }, upkeep: 0.5, workers: 0, crew: "settlers", unlock: free, buildable: true,
+ appeal: { value: 3, reach: 2 }, decor: true
+ },
+ park: {
+ id: "park", title: "Park", blurb: "lawns, trees, and a bench",
+ category: "decor", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 60, materials: { planks: 1 } }, upkeep: 2, workers: 0, crew: "settlers", unlock: free, buildable: true,
+ appeal: { value: 6, reach: 3 }, decor: true
+ },
+ fountain: {
+ id: "fountain", title: "Fountain", blurb: "a stone basin of fresh water",
+ category: "decor", size: 1, half: 6, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 80, materials: { stone: 3 } }, upkeep: 2, workers: 0, crew: "settlers", unlock: { residents: 30, citizens: 0 }, buildable: true,
+ appeal: { value: 6, reach: 3 }, decor: true
+ },
+ statue: {
+ id: "statue", title: "Statue", blurb: "a founder in stone, for the town's best street",
+ category: "decor", size: 1, half: 6, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 180, materials: { stone: 6 } }, upkeep: 3, workers: 0, crew: "settlers", unlock: { residents: 0, citizens: 20 }, buildable: true,
+ appeal: { value: 10, reach: 4 }, decor: true
+ },
+ plaza: {
+ id: "plaza", title: "Plaza", blurb: "a paved square with a statue in the middle",
+ category: "decor", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",
+ cost: { coins: 260, materials: { stone: 10 } }, upkeep: 4, workers: 0, crew: "settlers", unlock: { residents: 0, citizens: 40 }, buildable: true,
+ appeal: { value: 10, reach: 4 }, decor: true
}
}
export const kindOrder: ReadonlyArray<KindId> = [
- "warehouse", "lumberjack", "forester", "quarry", "mine", "sawmill", "smithy", "sheep", "weaver",
- "fishery", "farm", "mill", "bakery", "market", "chapel"
+ "warehouse", "granary", "lumberjack", "forester", "quarry", "mine", "sawmill", "smithy", "sheep", "weaver",
+ "fishery", "smokehouse", "farm", "mill", "bakery", "market", "chapel", "firewatch", "healer", "hospital", "watchhouse", "builder",
+ "garden", "park", "fountain", "statue", "plaza"
]
export const costText = (cost: Kind["cost"]): string =>
@@ -238,8 +354,9 @@ export const costText = (cost: Kind["cost"]): string =>
// ── Homes ─────────────────────────────────────────────────────────────────
-export type Tier = 1 | 2
-/** What a home can be short of. Settlers need food (fish or bread); citizens bread, cloth, and faith. */
+export type Tier = 1 | 2 | 3
+export const tierIds: ReadonlyArray<Tier> = [1, 2, 3]
+/** What a home can be short of. Settlers need food (fish, smoked fish, or bread); citizens and burghers bread, cloth, and faith. */
export type Need = "food" | "bread" | "cloth" | "faith"
export const home = {
@@ -247,13 +364,144 @@ export const home = {
half: 5,
cost: { coins: 10, materials: { planks: 1 } } as Kind["cost"],
tiers: {
- 1: { title: "settlers", residents: 4, tax: 1.8, height: 14, needs: ["food"] },
- 2: { title: "citizens", residents: 8, tax: 3.6, height: 26, needs: ["bread", "cloth", "faith"] }
- } as Readonly<Record<Tier, { readonly title: string; readonly residents: number; readonly tax: number; readonly height: number; readonly needs: ReadonlyArray<Need> }>>,
+ 1: { title: "settlers", residents: 4, tax: 2, height: 14, needs: ["food"], appeal: -100 },
+ 2: { title: "citizens", residents: 8, tax: 4, 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, {
+ readonly title: string
+ readonly residents: number
+ readonly tax: number
+ readonly height: number
+ readonly needs: ReadonlyArray<Need>
+ /** The desirability a home of this tier needs around it (see `appeal.ts`). */
+ readonly appeal: number
+ }>>,
/** A resident moves in (or out) this often. */
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(60), bread: ticks(90), cloth: ticks(180), faith: ticks(150) } as Readonly<Record<Need, number>>
+ lasts: { food: ticks(60), bread: ticks(90), cloth: ticks(180), faith: ticks(150) } as Readonly<Record<Need, number>>,
+ /** Where nobody wants to live: homes at this desirability or less hold `crowded` as many. */
+ squalid: -5,
+ crowded: 0.6
+}
+
+/** What a tier's homes are called, and what its residents are. */
+export const tierHome: Readonly<Record<Tier, string>> = { 1: "settlers' cottage", 2: "citizens' home", 3: "townhouse" }
+
+/** Which crew a tier's residents work in. */
+export const crewOf = (tier: Tier): Crew => (tier === 1 ? "settlers" : "citizens")
+
+/** Road cells a resident walks to work, at most (see `AssignStaff`). */
+export const COMMUTE = 15
+/** An apprentice (a settler in a citizens' job) works at this share of the pace. */
+export const APPRENTICE = 0.75
+/** Tools a workshop that wears them keeps on hand. */
+export const TOOL_STOCK = 1
+
+// ── Desirability ──────────────────────────────────────────────────────────
+
+/**
+ * What the land and the town do to the cells around them, besides the
+ * buildings' own (`Kind.appeal`). Water and woods count once, however many
+ * are near; so do paved streets.
+ */
+export const appeal = {
+ water: { value: 2, reach: 2 },
+ forest: { value: 2, reach: 2 },
+ paved: { value: 1, reach: 1 },
+ ruin: { value: -3, reach: 2 },
+ worn: { value: -2, reach: 1 },
+ /** Desirability is reckoned this often. */
+ every: 30,
+ /** And kept within these bounds. */
+ floor: -30,
+ ceiling: 40
+}
+
+/** Paving a road cell: coins and stone, the stone taken from storage at once. */
+export const PAVE_COST = { coins: 3, stone: 1 }
+
+// ── Risks ─────────────────────────────────────────────────────────────────
+
+/**
+ * Every home has three risk meters, 0 → `RISK_MAX`, and every building a
+ * fire meter. Each rises a little every second, faster for the reasons
+ * below (points a second); the matching service walker passing resets it.
+ * Over `warn` a sign goes up over the home; at the top, disaster.
+ */
+export const RISK_MAX = 10_000
+export const risk = {
+ warn: 7000,
+ /** 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. */
+ pace: [0.75, 1.25] as const,
+ fire: {
+ /** Settlers' cottages are wooden. */
+ wooden: 6,
+ stone: 4,
+ building: 2,
+ /** A bakery's oven, a smithy's forge: in itself, and to each home within `reach`. */
+ hot: 10,
+ near: 6,
+ reach: 2,
+ crowded: 3,
+ worn: 6,
+ /** Heating through a hard winter. */
+ winter: 6,
+ /** How long a blaze burns before the house is lost. */
+ burns: ticks(20),
+ /** A burning house sets a neighbour alight, each second: this chance, and up to `spread` more for a neighbour at the top of its own meter. */
+ catches: 0.03,
+ spread: 0.12,
+ /** Firefighters a fire watch may have out at once. */
+ crews: 2
+ },
+ health: {
+ base: 3,
+ hungry: 6,
+ crowded: 3,
+ squalid: 4,
+ /** A quarry's or a mine's dust, within `reach`. */
+ dust: 6,
+ reach: 3,
+ /** Still water within two cells. */
+ water: 3,
+ /** How long a sickness lasts if no physician comes; meanwhile the home holds `sickly` as many. */
+ lasts: ticks(60),
+ sickly: 0.5,
+ /** Each second, the chance it reaches a home within two cells: raising its risk by `contagion` (a home a physician calls on shrugs it off). */
+ spreads: 0.04,
+ contagion: 3000
+ },
+ order: {
+ base: 3,
+ /** For every 50 points of approval below nothing. */
+ unrest: 8,
+ squalid: 4,
+ /** A home standing half empty. */
+ vacant: 4,
+ /** A burghers' home is worth robbing. */
+ wealth: 3,
+ /** A theft takes this many coins and this share of the treasury, or goods instead when it is empty. */
+ coins: 10,
+ share: 0.02,
+ most: 80,
+ goods: 4,
+ /** After a theft its meter falls only to here; reaching the top again, the home empties and is left derelict. */
+ after: 3000
+ }
+}
+
+/** How well kept a building or home is, 0 → `CONDITION_MAX`. */
+export const CONDITION_MAX = 1000
+export const condition = {
+ /** A point lost every `every` steps: from new to run down in about 33 minutes, and fallen down in 67, unmended. */
+ every: ticks(4),
+ /** Below this, a builder mends it as they pass (about every half hour). */
+ mend: 550,
+ /** Below this, it works at half pace, and its fire risk rises. */
+ worn: 500
}
/** Tax rates the town can set, in percent of the usual. */
@@ -315,17 +563,17 @@ export const lands: Readonly<Record<LandId, {
}>> = {
rich: {
title: "rich", blurb: "deep forests, plenty of stone and ore, two lakes, a full treasury",
- forests: 7, stone: 4.5, ore: 3, rock: 40, lakes: 2, coins: 2000,
+ forests: 7, stone: 4.5, ore: 3, rock: 40, lakes: 2, coins: 2400,
stock: amounts({ wood: 15, planks: 50, stone: 24, tools: 10, fish: 30 })
},
fair: {
title: "fair", blurb: "enough of everything, if it is not wasted",
- forests: 5.5, stone: 3, ore: 2, rock: 32, lakes: 2, coins: 1500,
+ forests: 5.5, stone: 3, ore: 2, rock: 32, lakes: 2, coins: 1900,
stock: amounts({ wood: 10, planks: 40, stone: 16, tools: 8, fish: 20 })
},
harsh: {
title: "harsh", blurb: "thin woods, little stone, one deposit of ore, one lake",
- forests: 4, stone: 2, ore: 1, rock: 24, lakes: 1, coins: 1100,
+ forests: 4, stone: 2, ore: 1, rock: 24, lakes: 1, coins: 1500,
stock: amounts({ wood: 10, planks: 30, stone: 12, tools: 6, fish: 15 })
}
}
@@ -348,6 +596,21 @@ export const defaultCharter = (seed: number): CharterValue => ({ size: "medium",
export const YEARS_PER_TERM = 6
export const WINTER_SHARE = 0.3
+/**
+ * Each year's winter is mild, normal, or hard, rolled from the seed when the
+ * town is founded (see `Charter.winters`): how much of the year it takes,
+ * what fisheries catch, and whether homes heat (a fire risk).
+ */
+export const winterIds = ["mild", "normal", "hard"] as const
+export type WinterId = (typeof winterIds)[number]
+export const winters: Readonly<Record<WinterId, { readonly title: string; readonly share: number; readonly fishing: number; readonly heating: boolean; readonly chance: number }>> = {
+ mild: { title: "mild", share: WINTER_SHARE, fishing: 0.75, heating: false, chance: 0.3 },
+ normal: { title: "normal", share: WINTER_SHARE, fishing: 0.5, heating: false, chance: 0.45 },
+ hard: { title: "hard", share: WINTER_SHARE * 1.5, fishing: 0.25, heating: true, chance: 0.25 }
+}
+/** The almanac warns of winter this many steps before it comes. */
+export const WINTER_WARNING = ticks(60)
+
/**
* Running a town costs more the bigger it gets: the town hall's
* administration costs `perHome` coins a minute a home, and a further
diff --git a/src/factory.css b/src/factory.css
index 6ff70be..e5fdd84 100644
--- a/src/factory.css
+++ b/src/factory.css
@@ -268,3 +268,39 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
.panel {width:calc(100vw - 24px);max-width:360px}
.toast {bottom:calc(165px + env(safe-area-inset-bottom));max-width:calc(100vw - 28px)}
}
+
+/* ── The town ticker, map views and their legend ── */
+.hud .ticker { display: none; flex-direction: column; max-width: 420px; }
+.hud .ticker.show { display: flex; }
+.hud .ticker .cell { white-space: normal; padding: 5px 12px; font-size: 11px; line-height: 1.35; }
+.hud .ticker .cell + .cell { border-left: none; border-top: 1px dashed #e3e6df; }
+.hud .ticker .news { color: #5d6861; }
+.views {
+ position: fixed; right: 16px; top: 64px; display: flex; flex-direction: column; align-items: stretch; gap: 2px; padding: 5px;
+ background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px; box-shadow: 0 2px 0 #dfe2db; z-index: 2;
+ transition: right 240ms cubic-bezier(.2,.8,.2,1);
+}
+.views > .glyph { align-self: center; opacity: 0.6; padding: 2px 0 4px; }
+.views button {
+ font: inherit; font-size: 11px; color: #3d4943; background: transparent; border: 1px solid transparent; border-radius: 5px;
+ padding: 4px 8px; display: flex; align-items: center; gap: 6px; cursor: pointer; white-space: nowrap;
+}
+.views button:hover { background: #eceee8; }
+.views button.on { background: #3d4943; color: #f7f8f4; }
+.views button kbd { font: inherit; font-size: 10px; opacity: 0.55; margin-left: auto; }
+.panel-open .views { right: 376px; }
+.legend {
+ position: fixed; right: 16px; top: 300px; display: none; flex-direction: column; gap: 4px; padding: 10px 12px; max-width: 220px;
+ font-size: 11px; z-index: 2; transition: right 240ms cubic-bezier(.2,.8,.2,1);
+}
+.legend.show { display: flex; }
+.legend .key { display: flex; align-items: center; gap: 7px; }
+.legend .key i { width: 11px; height: 11px; border-radius: 3px; display: inline-block; opacity: 0.8; }
+.legend small { color: #77817a; line-height: 1.35; margin-top: 3px; }
+.panel-open .legend { right: 376px; }
+@media (max-width: 1000px) {
+ .views { top: auto; bottom: calc(130px + env(safe-area-inset-bottom)); flex-direction: row; flex-wrap: wrap; max-width: calc(100vw - 32px); }
+ .views button { font-size: 0; gap: 0; }
+ .views button kbd { display: none; }
+ .legend { top: auto; bottom: calc(176px + env(safe-area-inset-bottom)); }
+}
diff --git a/src/host.ts b/src/host.ts
index f1a337f..6ed1127 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -15,6 +15,9 @@ import {
goods,
home,
kindOrder,
+ PAVE_COST,
+ tierHome,
+ winters,
kinds,
landIds,
lands,
@@ -30,13 +33,14 @@ import {
type CharterValue,
type GoodId,
type Kind,
- type KindId
+ type KindId,
+ type Tier
} from "./content.ts"
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 } from "./ui.ts"
+import type { 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"
@@ -76,7 +80,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const stock = el("div", "card stock")
const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [
["wood", "planks", "stone", "tools"],
- ["fish", "bread"],
+ ["fish", "smoked", "bread"],
["wool", "cloth"]
]
const goodCells = new Map<GoodId, HTMLElement>()
@@ -104,7 +108,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
request.append(requestText, send)
const alarm = el("div", "card alarm")
- hud.append(bar, stock, request, alarm)
+ // The town ticker: what needs looking at now, and the latest news.
+ const ticker = el("div", "card ticker")
+ hud.append(bar, stock, request, alarm, ticker)
const people = el("div", "hud right")
const folk = el("div", "card bar")
const approval = el("div", "cell")
@@ -125,7 +131,10 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const reckoning = el("div", "dialog")
const result = el("button", "result", "")
result.onclick = () => showReckoning(true)
- document.body.append(hud, people, tooltip, toastBox, toolbar, system, panel, result, dialog, confirmBox, reckoning)
+ // Map views, and the legend of the one shown.
+ const views = el("div", "views")
+ const legend = el("div", "card legend")
+ document.body.append(hud, people, tooltip, toastBox, toolbar, system, panel, result, dialog, confirmBox, reckoning, views, legend)
let toastTimer = 0
const ui: UiValue = {
@@ -145,6 +154,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
stats: null,
speed: 1,
founding: true,
+ view: "none",
+ overlay: { key: "", cells: [] },
+ legend: null,
toast: (message) => {
toastBox.textContent = message
toastBox.classList.add("show")
@@ -168,6 +180,13 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
tip: "Click a building or home to see what it does · drag to pan · wheel to zoom"
},
{ tool: "road", label: "road", key: "R", icon: "road", tip: `Drag to lay a road · ${ROAD_COST} coins a cell` },
+ {
+ tool: "pave",
+ 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`
+ },
{ 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" },
{ tool: "bulldoze", label: "bulldoze", key: "X", icon: "bulldoze", tip: "Click a building, home, road, tree, or field to remove it" }
@@ -209,6 +228,29 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
for (const s of speeds) s.button.classList.toggle("on", s.speed === speed)
}
setSpeed(1)
+
+ // ── Map views ──
+ const viewButtons: ReadonlyArray<{ readonly view: Exclude<View, "none">; readonly label: string; readonly key: string; readonly icon: IconName }> = [
+ { view: "appeal", label: "desirability", key: "D", icon: "appeal" },
+ { view: "workers", label: "workers", key: "W", icon: "workers" },
+ { view: "fire", label: "fire", key: "F", icon: "fire" },
+ { view: "health", label: "health", key: "A", icon: "health" },
+ { view: "order", label: "order", key: "O", icon: "order" },
+ { view: "condition", label: "condition", key: "C", icon: "condition" }
+ ]
+ views.append(iconEl("view", 16))
+ const viewEls = viewButtons.map((v) => {
+ const button = el("button", "")
+ button.title = `Show ${v.label} over the map (${v.key}); again to hide it`
+ button.append(iconEl(v.icon, 15), document.createTextNode(v.label), el("kbd", "", v.key))
+ button.onclick = () => setView(ui.view === v.view ? "none" : v.view)
+ views.append(button)
+ return { ...v, button }
+ })
+ const setView = (view: View) => {
+ ui.view = view
+ for (const v of viewEls) v.button.classList.toggle("on", v.view === view)
+ }
// New town, save, and load, out of the way in the bottom right. Founding or
// loading replaces the town, so each asks first.
const action = (name: IconName, label: string, tip: string, run: () => void) => {
@@ -313,6 +355,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const key = event.key.toLowerCase()
if (key === "s") choose("select")
if (key === "r") choose("road")
+ if (key === "p") choose("pave")
+ const viewKey = viewButtons.find((v) => v.key.toLowerCase() === key)
+ if (viewKey) setView(ui.view === viewKey.view ? "none" : viewKey.view)
if (key === "h") choose("home")
if (key === "x") choose("bulldoze")
if (key === "b") toggleMenu("build")
@@ -353,7 +398,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
// ── Pictures of buildings, for the build menu and the panel ──
const pictures = new Map<string, Promise<string>>()
/** A building (or a home of a tier) drawn as the town draws it, as an image. */
- const picture = (what: KindId | 1 | 2): HTMLImageElement => {
+ const picture = (what: KindId | Tier): HTMLImageElement => {
const img = document.createElement("img")
img.className = "thumb"
img.alt = ""
@@ -361,7 +406,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
let url = pictures.get(id)
if (!url) {
const g = new Graphics()
- if (what === 1 || what === 2) {
+ if (what === 1 || what === 2 || what === 3) {
plate(g, plateHalf(1))
drawHouse(g, what, 1, { right: true, left: false }, homeVariant(0.1))
} else {
@@ -455,7 +500,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
gathering: "wood",
crafts: "tools",
food: "bread",
- services: "faith"
+ services: "faith",
+ decor: "decor"
}
const buildMenu = () => {
@@ -463,17 +509,17 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
for (const category of categoryOrder) {
const options = kindOrder.filter((id) => kinds[id].category === category && kinds[id].buildable)
if (options.length === 0) continue
- const box = section(category, categoryIcon[category])
+ const box = section(category === "decor" ? "decorations" : category, categoryIcon[category], category === "decor" ? "Ornaments raise the desirability of the streets around them: citizens need 5, townhouses 15." : undefined)
box.style.borderTop = `3px solid ${hex(categoryColor[category])}`
for (const id of options) {
const kind = kinds[id]
const option = el("button", "option")
const cost = costChips(kind.cost)
const terms = el("span", "chips")
- terms.innerHTML = `<span class="chip dim" title="workers">${icon("workers", 14)}${kind.workers}</span><span class="chip dim" title="upkeep, coins a minute">${icon("upkeep", 14)}${kind.upkeep}/min</span>`
+ 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 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} workers · ${kind.upkeep} coins a minute`
+ 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.onclick = () => place(id)
live.push(() => {
@@ -585,6 +631,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const town = section("people", "people")
const settlers = row(town, "settlers", "settlers")
const citizens = row(town, "citizens", "citizens")
+ const burghers = row(town, "of them, burghers", "burghers")
const homes = row(town, "homes", "homes")
const work = row(town, "jobs filled", "jobs")
const peopleLine = el("div", "spark")
@@ -594,7 +641,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const needs = section(
"homes supplied",
"homes",
- "Settlers need food (fish or bread) from a market; citizens need bread, cloth, and faith."
+ "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."
)
const needIcons: Readonly<Record<"food" | "bread" | "cloth" | "faith", IconName>> = {
food: "fish",
@@ -616,6 +663,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
return { n, fill, value }
})
const larderLine = row(needs, "food in store", "flour")
+ const eatenLine = row(needs, "eaten · rotted last minute", "fish")
+ const troubleLine = row(needs, "sick homes · on fire", "health")
panel.append(needs)
const crown = section(
@@ -731,6 +780,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
money(net, s.net, " coins")
settlers.textContent = String(s.settlers)
citizens.textContent = String(s.citizens)
+ burghers.textContent = String(s.burghers)
homes.textContent = String(s.homes)
work.textContent = `${s.employed} of ${s.jobs}`
for (const b of bars) {
@@ -740,6 +790,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
b.value.textContent = `${s.needs[b.n]}/${s.homes}`
}
larderLine.textContent = `${s.larder}`
+ eatenLine.textContent = `${s.eaten} · ${s.rotted}`
+ troubleLine.textContent = `${s.sick} · ${s.burning}`
crownLine.textContent = `${s.crown.met} · ${s.crown.missed}`
crownNext.innerHTML = s.crown.open
? `Wants <b>${s.crown.amount} ${goods[s.crown.good].title}</b> · ${clockText(s.crown.left)} left · +${s.crown.reward} coins`
@@ -782,6 +834,15 @@ 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"
@@ -802,21 +863,25 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
if (p.type === "build") return buildMenu()
if (p.type === "town") return townPanel()
- const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : `${home.tiers[p.tier].title}' home`
+ const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : "ruin"
const status = el("span", "pill")
const about = el(
"p",
"sub",
p.type === "building"
? kinds[p.kind].blurb
- : p.tier === 1
- ? "settlers: fish or bread from a market keeps them"
- : "citizens: they need bread, cloth, and faith"
+ : p.type === "ruin"
+ ? "bulldoze it to clear the plot"
+ : p.tier === 1
+ ? "settlers: fish or bread from a market keeps them; they do the rough work"
+ : p.tier === 2
+ ? "citizens: they need bread, cloth, and faith, and a street with desirability 5; they do the skilled work"
+ : "burghers: a citizens' home on a fine street (desirability 15) that every service calls on"
)
const below = el("div", "")
below.append(status, about)
- panel.append(header(title, picture(p.type === "building" ? p.kind : p.tier), below))
- const box = section(p.type === "building" ? "at work" : "household", p.type === "building" ? "jobs" : "homes")
+ panel.append(header(title, p.type === "ruin" ? iconEl("condition", 30) : picture(p.type === "building" ? p.kind : p.tier), below))
+ const box = section(p.type === "building" ? "at work" : p.type === "ruin" ? "what is left" : "household", p.type === "building" ? "jobs" : "homes")
box.classList.add("lines")
const rows: Array<HTMLElement> = []
panel.append(box)
@@ -826,9 +891,12 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
if (now.type === "building") {
status.textContent = now.problem ?? now.status
status.className = `pill ${now.problem !== null ? "problem" : now.status === "working" ? "working" : ""}`
- } else {
+ } else if (now.type === "house") {
status.textContent = `${home.tiers[now.tier].residents} at most`
status.className = "pill working"
+ } else {
+ status.textContent = now.cause
+ status.className = "pill problem"
}
while (rows.length < now.lines.length) {
const line = el("div", "row")
@@ -1148,6 +1216,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
input.reset()
}
+ /** The last chronicle line announced. */
+ let lastNews = ""
/** Copies the town's numbers and preview into the page, once a frame. */
const syncPage = () => {
syncPanel()
@@ -1157,14 +1227,18 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
coins.title = "Coins in the treasury, and what it gains (or loses) a minute"
coins.classList.toggle("debt", s.coins < 0)
const left = Math.max(0, s.charter.term * 60 - Math.floor(s.minute * 60))
- clock.innerHTML = `${icon(s.season.winter ? "winter" : "clock", 20)}<span class="stack"><b>${clockText(left)}</b><small class="${s.season.winter ? "winter" : ""}">year ${s.season.year} · ${s.season.winter ? `spring in ${clockText(s.season.left)}` : `winter in ${clockText(s.season.left)}`}</small></span>`
- clock.title = s.season.winter
- ? "Winter: fields lie still, fishing is slow, and homes eat faster"
- : `Time left in the term · winter comes in ${clockText(s.season.left)}`
+ const severity = (w: typeof s.season.coming) => (w === null ? "" : ` (${winters[w].title})`)
+ const until = s.season.winter
+ ? `${winters[s.season.severity ?? "normal"].title} winter · spring in ${clockText(s.season.left)}`
+ : s.season.coming === null
+ ? "no more winters this term"
+ : `winter in ${clockText(s.season.left)}${severity(s.season.coming)}`
+ clock.innerHTML = `${icon(s.season.winter ? "winter" : "clock", 20)}<span class="stack"><b>${clockText(left)}</b><small class="${s.season.winter ? "winter" : s.season.coming === "hard" ? "down" : ""}">year ${s.season.year} · ${until}</small></span>`
+ clock.title = `${s.season.winter ? "Winter: fields lie still, fishing is slow, and homes eat faster" : "Time left in the term"}\nThe almanac: the coming winter is ${s.season.coming === null ? "beyond the term" : winters[s.season.coming].title}, the one after ${s.season.after === null ? "beyond the term" : winters[s.season.after].title}.\nMild: fishing at 75%. Normal: 50%. Hard: half as long again, fishing at 25%, and homes heating are a fire risk.`
const trend = s.mood.target > s.mood.approval ? "↑" : s.mood.target < s.mood.approval ? "↓" : ""
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</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>`
for (const [g, count] of goodCells) {
count.textContent = String(s.stock[g])
@@ -1200,6 +1274,35 @@ 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.
+ const minute = Math.round(s.minute * 3600)
+ const news = s.chronicle.filter((l) => l.alarm && minute - l.tick < 90 * 60).slice(-3).reverse()
+ 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>`)
+ ].join("")
+ if (ticker.dataset.html !== tickerHtml) {
+ ticker.dataset.html = tickerHtml
+ ticker.innerHTML = tickerHtml
+ }
+ ticker.classList.toggle("show", tickerHtml !== "" && s.fate.state === "playing")
+ // News as it happens: a toast for each new alarm line.
+ const latest = s.chronicle.at(-1)
+ const seen = `${s.charter.seed}|${latest?.tick ?? -1}|${s.chronicle.length}`
+ if (seen !== lastNews) {
+ if (lastNews !== "" && latest?.alarm && minute - latest.tick < 120) ui.toast(latest.text)
+ lastNews = seen
+ }
+ // The map view's legend.
+ const l = ui.legend
+ const legendHtml = l
+ ? `<b>${l.title}</b>${l.keys.map((k) => `<span class="key"><i style="background:${hex(k.color)}"></i>${k.label}</span>`).join("")}<small>${l.note}</small>`
+ : ""
+ if (legend.dataset.html !== legendHtml) {
+ legend.dataset.html = legendHtml
+ legend.innerHTML = legendHtml
+ }
+ legend.classList.toggle("show", l !== null)
syncReckoning(s)
}
input.sync()
diff --git a/src/icons.ts b/src/icons.ts
index ec9fadf..df93082 100644
--- a/src/icons.ts
+++ b/src/icons.ts
@@ -17,6 +17,7 @@ const paths: Record<string, string> = {
ore: `<path d="M2.5 12.5l2-6 4-2.5 4.5 2 1 6.5-5.5 1.5z" fill="#d5dae3"/><path d="M8.5 8l4.5-2 1 6.5-5.5 1.5z" fill="#bcc3d0"/><path d="M6 7.5l1-3 1 3z" fill="#5a6479"/><rect x="4.5" y="10" width="1.6" height="1.6" fill="#4a5368" stroke="none"/><rect x="10.5" y="10.5" width="1.6" height="1.6" fill="#4a5368" stroke="none"/>`,
tools: `<path d="M3.5 13.5l6-6" fill="none" stroke-width="2.2" stroke="#8a6a45"/><path d="M7 3.5l5.5 5.5 1.5-1.5-2-2 .5-2-2-1.5z" fill="#8f9891"/>`,
fish: `<path d="M2 8c2.5-3.5 7-3.5 9.5 0-2.5 3.5-7 3.5-9.5 0z" fill="#9fd0cb"/><path d="M11.5 8l3-2.5v5z" fill="#2f8c87"/><circle cx="5" cy="7.4" r=".7" fill="${ink}" stroke="none"/><path d="M7.5 6v4" fill="none" stroke-width="1"/>`,
+ smoked: `<path d="M2 9c2.5-3.5 7-3.5 9.5 0-2.5 3.5-7 3.5-9.5 0z" fill="#d9a07c"/><path d="M11.5 9l3-2.5v5z" fill="#9a5b3a"/><path d="M5 2.5c-1 1 1 2 0 3M8 2c-1 1 1 2 0 3" fill="none" stroke-width="1" stroke="#77817a"/><path d="M5 8.5h4" fill="none" stroke-width="1"/>`,
wheat: `<path d="M8 14.5V4" fill="none"/><path d="M8 5.5c-2 0-2.5-2-2.5-3 1.5 0 2.5 1 2.5 3zM8 5.5c2 0 2.5-2 2.5-3-1.5 0-2.5 1-2.5 3zM8 8.5c-2 0-3-1.5-3-3 1.5 0 3 1 3 3zM8 8.5c2 0 3-1.5 3-3-1.5 0-3 1-3 3zM8 11.5c-2 0-3-1.5-3-3 1.5 0 3 1 3 3zM8 11.5c2 0 3-1.5 3-3-1.5 0-3 1-3 3z" fill="#e9cf7c"/>`,
flour: `<path d="M4.5 5.5h7l1 8c0 1-1.5 1.5-4.5 1.5s-4.5-.5-4.5-1.5z" fill="#f2ecdc"/><path d="M4.5 5.5c1-1 1.5-3 3.5-3s2.5 2 3.5 3" fill="#e6dcc2"/><path d="M5.5 9h5" fill="none" stroke="#c9b48a" stroke-width="2"/>`,
bread: `<path d="M2 10.5c0-3.5 3-5.5 6-5.5s6 2 6 5.5c0 1.5-1 2.5-2.5 2.5h-7C3 13 2 12 2 10.5z" fill="#e89a7c"/><path d="M5.5 7.5l1 2M8 6.5l1 2M10.5 7l1 2" fill="none" stroke-width="1"/>`,
@@ -56,6 +57,16 @@ const paths: Record<string, string> = {
close: `<path d="M4 4l8 8M12 4l-8 8" fill="none"/>`,
info: `<circle cx="8" cy="8" r="6" fill="#f7f8f4" stroke-width="1"/><path d="M8 7v4.5" fill="none" stroke-width="1.4"/><circle cx="8" cy="4.9" r=".9" fill="${ink}" stroke="none"/>`,
upkeep: `<path d="M8 2.5v11M5 11l3 3 3-3" fill="none" stroke="#b04a39"/>`,
+ burghers: `<circle cx="8" cy="5.5" r="2.3" fill="#f5f6f2"/><path d="M5.5 3.2h5V1.5h-5z" fill="${ink}"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#8a58a8"/>`,
+ decor: `<path d="M8 14.5v-5" fill="none" stroke="#6b5a45"/><circle cx="8" cy="6.5" r="4.5" fill="#a9c79a"/><circle cx="3.5" cy="13" r="1.4" fill="#e89a7c"/><circle cx="12.5" cy="13" r="1.4" fill="#e3c25a"/>`,
+ pave: `<path d="M1.5 9l6.5-4.5 6.5 4.5-6.5 4.5z" fill="#d8dbd4"/><path d="M4.8 6.8l6.5 4.5M8 4.5L4.8 11.3M11.2 6.8L8 13.5" fill="none" stroke-width="1" stroke="#9aa29b"/>`,
+ fire: `<path d="M8 14.5c-3 0-4.5-2-4.5-4.5 0-2.5 2-3.5 2.5-6 1.5 1 2 2.5 2 3.5.8-.8 1-2 1-3 2 1.5 3.5 3.5 3.5 5.5 0 2.5-1.5 4.5-4.5 4.5z" fill="#f0a868"/><path d="M8 14.5c-1.3 0-2-1-2-2.2 0-1.3 1-2 1.3-3 .9.7 2.7 1.8 2.7 3 0 1.2-.7 2.2-2 2.2z" fill="#f3c76b"/>`,
+ health: `<path d="M6 2.5h4v3.5h3.5v4H10v3.5H6V10H2.5V6H6z" fill="#cfe5d6"/>`,
+ order: `<path d="M8 1.5l5.5 2v4.5c0 3.5-2.5 5.5-5.5 6.5-3-1-5.5-3-5.5-6.5V3.5z" fill="#c9d2da"/><path d="M5.5 8l2 2 3-3.5" fill="none" stroke-width="1.4"/>`,
+ repair: `<path d="M3 13l6-6" fill="none" stroke="#8a6a45" stroke-width="2"/><path d="M8 3.5l2.5-1.5 3 3-1.5 2.5-2-.5-1.5-1.5z" fill="#8f9891"/>`,
+ appeal: `<path d="M8 1.8l1.8 3.9 4.2.5-3.1 2.9.8 4.2L8 11.2l-3.7 2.1.8-4.2L2 6.2l4.2-.5z" fill="#cfe5b8"/>`,
+ condition: `<path d="M2.5 14.5v-8l5.5-4 5.5 4v8z" fill="#f5f6f2"/><path d="M6 6.5l2 2.5-1.5 2 2 3" fill="none" stroke="#b04a39" stroke-width="1.2"/>`,
+ view: `<path d="M1.5 8s2.5-4.5 6.5-4.5S14.5 8 14.5 8s-2.5 4.5-6.5 4.5S1.5 8 1.5 8z" fill="#f7f8f4"/><circle cx="8" cy="8" r="2.3" fill="#c9d6ee"/>`,
workers: `<circle cx="8" cy="5" r="2.3" fill="#f5f6f2"/><path d="M5.3 4.5c0-2 1.2-3 2.7-3s2.7 1 2.7 3z" fill="#e3c25a" stroke-width="1"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#e9c48a"/>`
}
diff --git a/src/main.ts b/src/main.ts
index 0c9b39e..a5e2cea 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -7,12 +7,12 @@ import { Result } from "@typeonce/bevy-ts"
import { Effect } from "effect"
import { FixedLoop } from "@typeonce/bevy-ts-browser"
-import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./render3d/views.ts"
+import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./render3d/views.ts"
import { lands, sizes, STEP_SECONDS } from "./content.ts"
import { createHost, type Persistence } from "./host.ts"
import { present } from "./present.ts"
import { browserStorage, describe, loadLatest, save, Storage, World } from "./save.ts"
-import { BuildingNodes, Clock, FieldNodes, Game, HouseNodes, RockNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"
+import { BuildingNodes, Clock, FieldNodes, Game, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"
import { blankResources, simulate } from "./sim/index.ts"
/** Minutes of game time between autosaves. */
@@ -29,9 +29,10 @@ const start = async () => {
walkerNodes = stage.registry<WalkerView>(),
treeNodes = stage.registry<TreeView>(),
rockNodes = stage.registry<RockView>(),
- fieldNodes = stage.registry<FieldView>()
+ fieldNodes = stage.registry<FieldView>(),
+ ruinNodes = stage.registry<RuinView>()
const resetPresentation = () => {
- for (const registry of [buildingNodes, houseNodes, walkerNodes, treeNodes, rockNodes, fieldNodes]) registry.clear()
+ for (const registry of [buildingNodes, houseNodes, walkerNodes, treeNodes, rockNodes, fieldNodes, ruinNodes]) registry.clear()
stage.resetPresentation()
resetPage()
}
@@ -45,7 +46,8 @@ const start = async () => {
Game.Runtime.service(WalkerNodes, walkerNodes),
Game.Runtime.service(TreeNodes, treeNodes),
Game.Runtime.service(RockNodes, rockNodes),
- Game.Runtime.service(FieldNodes, fieldNodes)
+ Game.Runtime.service(FieldNodes, fieldNodes),
+ Game.Runtime.service(RuinNodes, ruinNodes)
),
resources: blankResources()
})
diff --git a/src/map-lab/map.ts b/src/map-lab/map.ts
index 9298f2b..0f86d0c 100644
--- a/src/map-lab/map.ts
+++ b/src/map-lab/map.ts
@@ -121,6 +121,22 @@ const layout: Array<[string, number, number]> = [
["fishery", 13, 1]
]
for (const [id, x, y] of layout) place(id, x, y)
+// The newer quarter: services, food stores, and ornaments (placeholder models), along the south-west street.
+const quarter: Array<[string, number, number]> = [
+ ["firewatch", -17, -2],
+ ["healer", -17, 1],
+ ["watchhouse", -10.5, -8],
+ ["builder", -17, -5],
+ ["granary", -9.5, 1],
+ ["smokehouse", 10, 1],
+ ["hospital", 9.5, -11],
+ ["garden", -15, -8],
+ ["park", -16.5, -8],
+ ["fountain", 0.5, -8],
+ ["statue", 4.5, -8],
+ ["plaza", 9, -8]
+]
+for (const [id, x, y] of quarter) place(id, x, y)
const homes = inkAssets.filter((a) => a.category === "homes")
homes.forEach((a, i) => place(a.id, -7 + (i % 4) * 1.8, 6 + Math.floor(i / 4) * 2))
const trees = inkAssets.filter((a) => a.reference?.type === "tree")
diff --git a/src/places.ts b/src/places.ts
new file mode 100644
index 0000000..339f581
--- /dev/null
+++ b/src/places.ts
@@ -0,0 +1,43 @@
+/**
+ * Where something happened, in words: a street named after the nearest
+ * landmark ("Mill Lane", "Chapel Street"), so a fire or a theft can be told
+ * as news. The same building always gives its streets the same name.
+ */
+import type { KindId } from "./content.ts"
+import { ringOf } from "./appeal.ts"
+
+const streetOf: Readonly<Record<KindId, string>> = {
+ townhall: "Hall", warehouse: "Warehouse", granary: "Granary", lumberjack: "Timber", forester: "Forest", quarry: "Quarry",
+ mine: "Mine", fishery: "Fisher", smokehouse: "Smokehouse", sawmill: "Sawmill", smithy: "Smithy", farm: "Farm", mill: "Mill",
+ bakery: "Baker", sheep: "Shepherd", weaver: "Weaver", market: "Market", chapel: "Chapel", firewatch: "Watch", healer: "Healer",
+ hospital: "Hospital", watchhouse: "Constable", builder: "Builder", garden: "Garden", park: "Park", fountain: "Fountain",
+ statue: "Statue", plaza: "Plaza"
+}
+const suffixes = ["Lane", "Street", "Row", "Way", "Close", "Walk"] as const
+
+export interface Landmark {
+ readonly kind: KindId
+ readonly x: number
+ readonly y: number
+ readonly size: number
+}
+
+/** The street a cell is on: named after the nearest landmark within eight cells, or the edge of town. */
+export const placeName = (landmarks: ReadonlyArray<Landmark>, cell: { readonly x: number; readonly y: number }): string => {
+ let best: Landmark | null = null
+ let distance = 9
+ for (const l of landmarks) {
+ const d = ringOf(l, cell.x, cell.y)
+ if (d < distance) {
+ best = l
+ distance = d
+ }
+ }
+ if (!best) return "the edge of town"
+ const suffix = suffixes[(Math.imul(best.x * 73 + best.y * 31 + 7, 2654435761) >>> 0) % suffixes.length]!
+ return `${streetOf[best.kind]} ${best.kind === "townhall" ? "Square" : suffix}`
+}
+
+/** "one", "two", … for small counts in the news. */
+export const counted = (n: number, one: string, many = `${one}s`) =>
+ `${n <= 10 ? ["no", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"][n] : n} ${n === 1 ? one : many}`
diff --git a/src/present.ts b/src/present.ts
index d8dac57..3afdd14 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -1,23 +1,31 @@
/**
* What runs once a frame, after the simulation's steps: the pointer's
* gestures become a selection, a preview, and edits for the next step; the
- * panel, tooltip, and top bar are filled in; and the views follow the world.
+ * panel, tooltip, top bar, map views, and the town's alerts are filled in;
+ * and the views follow the world.
*/
import { RenderSync } from "@typeonce/bevy-ts-render"
-import { homeHeight, topOf, type Load, type Emphasis } from "./art.ts"
-import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView } from "./render3d/views.ts"
-import type { DoorSet } from "./render3d/models.ts"
-import { BUILD_TICKS, crown as crownRules, fate, goodIds, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"
-import { around, canPlace, entrances, isRoad, key, lPath, useAt, type TileLike } from "./grid.ts"
-import { inside, U, type Point } from "./iso.ts"
+import { appealAt, appealParts, buildingSource, landSource, type AppealSource } from "./appeal.ts"
+import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.ts"
+import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "./render3d/views.ts"
+import type { DoorSet, OverlayCell } from "./render3d/models.ts"
import {
+ BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, crewOf, crown as crownRules, fate, goodIds, goods, home, kinds, needTitle, risk,
+ RISK_MAX, tierHome, total, winters, type Kind, type Tier
+} from "./content.ts"
+import { around, canPlace, doors, entrances, isRoad, key, lPath, reach, useAt, type TileLike } from "./grid.ts"
+import { GRID, inside, U, type Point } from "./iso.ts"
+import {
+ Appeal,
Building,
BuildingNodes,
+ Burning,
Census,
Charter,
Chronicle,
Clock,
+ Condition,
Crown,
Errand,
Fate,
@@ -34,16 +42,23 @@ import {
Ledger,
Market,
Mood,
+ Pantry,
Paused,
+ Paved,
Policy,
Recipe,
+ Rescue,
Rising,
+ Risk,
Road,
Roam,
Rock,
RockNodes,
Route,
+ Ruin,
+ RuinNodes,
Service,
+ Sick,
Site,
Staff,
StageService,
@@ -63,9 +78,9 @@ import {
type GridValue,
type Status as StatusValue
} from "./schema.ts"
-import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, taxOf, termTicks } from "./sim/index.ts"
+import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, taxOf, termTicks, winterOf } from "./sim/index.ts"
import { Townsfolk } from "./townsfolk.ts"
-import { emptyPreview, type HitBox } from "./ui.ts"
+import { emptyPreview, type HitBox, type Legend, type View } from "./ui.ts"
const cellAt = (at: Point): Point => {
return { x: Math.floor(at.x), y: Math.floor(at.y) }
@@ -101,13 +116,21 @@ const reachOf = (kind: Kind): number | null => kind.gathers?.radius ?? kind.plan
const sourceTitle = { tree: "grown trees", stone: "stone", ore: "ore", field: "ripe fields", water: "water" } as const
+/** What a building's crew is short of, for its problem line. */
+interface Crewing {
+ readonly nearby: number
+ readonly crew: "settlers" | "citizens"
+}
+
/** Why a building is not working, in a line, or `null` when it is fine. */
-const problemOf = (kind: Kind, status: StatusValue, growing = false): string | null => {
+const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: Crewing): string | null => {
switch (status) {
case "unconnected":
return "needs a road at the middle of one of its sides"
case "unstaffed":
- return "no workers: the town needs more residents"
+ if (crewing && crewing.nearby === 0)
+ return `no workers nearby: no ${crewing.crew === "citizens" ? "citizens' (or settlers') homes" : "settlers' cottages"} within ${COMMUTE} road cells`
+ return "no workers: every one nearby already has a job"
case "blocked":
return "full: nowhere to take what it makes"
case "paused":
@@ -118,6 +141,7 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false): string | n
return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`
if (kind.recipe?.input) return `waiting for ${kind.recipe.input}`
if (kind.service?.service === "goods") return "nothing to hand out: no fish, bread, or cloth here"
+ if (kind.service?.service === "repair") return "no planks to mend with"
return "waiting"
default:
return null
@@ -144,7 +168,10 @@ const BuildingRead = Game.Query({
service: Game.Query.optional(Service),
walkers: Game.Query.optionalRelated(WalkerOf),
hall: Game.Query.optional(TownHall),
- paused: Game.Query.optional(Paused)
+ paused: Game.Query.optional(Paused),
+ risk: Game.Query.optional(Risk),
+ condition: Game.Query.optional(Condition),
+ burning: Game.Query.optional(Burning)
}
})
const HouseRead = Game.Query({
@@ -152,9 +179,14 @@ const HouseRead = Game.Query({
tile: Game.Query.read(Tile),
house: Game.Query.read(House),
site: Game.Query.optional(Site),
- rising: Game.Query.optional(Rising)
+ rising: Game.Query.optional(Rising),
+ risk: Game.Query.optional(Risk),
+ condition: Game.Query.optional(Condition),
+ burning: Game.Query.optional(Burning),
+ sick: Game.Query.optional(Sick)
}
})
+const RuinRead = Game.Query({ selection: { tile: Game.Query.read(Tile), ruin: Game.Query.read(Ruin) } })
/** How far up a building or home is: a site rises to its frame as materials come in, then the rest of the way. */
const buildOf = (
@@ -171,10 +203,106 @@ const PLATE_SHARE = 0.12
const delivered = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number }) =>
1 - total(site.owed) / Math.max(1, site.total)
+const percent = (n: number, of: number) => `${Math.round((n / of) * 100)}%`
+const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`
+
+/** The sign over a home or building: what is wrong now, or the risk nearest the top past `risk.warn`. */
+const alertOf = (r: { readonly fire: number; readonly health: number; readonly order: number } | undefined, sick: boolean, worn: boolean): Alert | null => {
+ if (sick) return "sick"
+ if (r) {
+ const worst = (["fire", "health", "order"] as const).reduce((a, b) => (r[b] > r[a] ? b : a))
+ if (r[worst] >= risk.warn) return worst
+ }
+ return worn ? "worn" : null
+}
+
+/** How a risk reads: "low", "40%", or "high: 85%". */
+const riskText = (value: number) => (value < RISK_MAX * 0.35 ? "ok" : value >= risk.warn ? `high, ${percent(value, RISK_MAX)}` : percent(value, RISK_MAX))
+
+// ── Map views ─────────────────────────────────────────────────────────────
+
+const GOOD = 0x4f9a6a
+const FAIR = 0xc9b45a
+const BAD = 0xc4523f
+const COOL = 0x3d6db5
+/** A meter 0 → `of` as a colour: green when low, amber, red past the warning line. */
+const meterColor = (value: number, of: number, warn: number) => (value >= warn ? BAD : value >= of * 0.35 ? FAIR : GOOD)
+
+const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {
+ appeal: {
+ title: "desirability",
+ 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: BAD, label: `${home.squalid} or less: squalid` }
+ ],
+ note: "Industry pushes homes away; gardens, parks, fountains, statues, a chapel, and paved streets draw them in."
+ },
+ workers: {
+ title: "workers",
+ keys: [
+ { color: GOOD, label: "fully staffed" },
+ { color: FAIR, label: "short of workers" },
+ { color: BAD, label: "no workers" },
+ { color: 0xd6b48a, label: "settlers' homes" },
+ { color: COOL, label: "citizens' homes" }
+ ],
+ note: `Residents walk at most ${COMMUTE} road cells to work. Select a workplace to see its reach and the homes inside it.`
+ },
+ fire: {
+ title: "fire",
+ keys: [
+ { color: GOOD, label: "watched" },
+ { 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."
+ },
+ health: {
+ title: "health",
+ keys: [
+ { color: GOOD, label: "visited" },
+ { color: FAIR, label: "rising" },
+ { color: BAD, label: "at risk, or sick" }
+ ],
+ note: "A healer's physician resets the risk and cures the sick. Hunger, crowding, squalor, quarry dust, and still water raise it."
+ },
+ order: {
+ title: "order",
+ keys: [
+ { color: GOOD, label: "kept" },
+ { color: FAIR, label: "rising" },
+ { color: BAD, label: "thieves about" }
+ ],
+ note: "A watch house's constable keeps order. Low approval, squalor, and homes not full raise it; theft first, then the home is left derelict."
+ },
+ condition: {
+ title: "condition",
+ keys: [
+ { color: GOOD, label: "well kept" },
+ { color: FAIR, label: "needs mending" },
+ { color: BAD, label: "run down: half pace" }
+ ],
+ note: "A builder's yard mends what its builder passes with planks and stone. At nothing it falls down."
+ }
+}
+
+const appealColor = (v: number) =>
+ v >= home.tiers[3].appeal ? 0x2f7a43 : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc9d6a0 : v > home.squalid ? 0xe0a060 : BAD
+
export const Interact = Game.System(
"Town/Interact",
{
- queries: { buildings: BuildingRead, houses: HouseRead },
+ queries: {
+ buildings: BuildingRead,
+ houses: HouseRead,
+ ruins: RuinRead,
+ trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),
+ water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),
+ paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] })
+ },
resources: {
grid: Game.System.readResource(Grid),
census: Game.System.readResource(Census),
@@ -189,7 +317,9 @@ export const Interact = Game.System(
crown: Game.System.readResource(Crown),
fate: Game.System.readResource(Fate),
history: Game.System.readResource(History),
- chronicle: Game.System.readResource(Chronicle)
+ chronicle: Game.System.readResource(Chronicle),
+ appeal: Game.System.readResource(Appeal),
+ pantry: Game.System.readResource(Pantry)
},
services: { ui: Game.System.service(Ui) }
},
@@ -198,32 +328,36 @@ export const Interact = Game.System(
const grid = resources.grid.get()
const rates = resources.policy.get()
const approval = resources.mood.get().approval
+ const cells = resources.appeal.get().cells
const buildings = queries.buildings.each()
const houses = queries.houses.each()
+ const ruins = queries.ruins.each()
const hits: Array<HitBox> = [
...buildings.map(({ entity, data }) => {
const kind = kinds[data.building.get().kind]
return hitBox(entity.id, data.tile.get(), kind.half, topOf(kind))
}),
- ...houses.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), home.half, homeHeight(data.house.get().tier)))
+ ...houses.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), home.half, homeHeight(data.house.get().tier))),
+ ...ruins.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), 0, 0))
].sort((l, r) => r.depth - l.depth)
ui.hits = hits
- const tileOf = (id: number) => [...buildings, ...houses].find((row) => row.entity.id === id)?.data.tile.get()
+ const tileOf = (id: number) => [...buildings, ...houses, ...ruins].find((row) => row.entity.id === id)?.data.tile.get()
// ── Gestures ──
for (const gesture of ui.gestures.splice(0)) {
const cell = cellAt(gesture.at)
if (gesture.type === "press") {
- ui.dragFrom = (ui.tool === "road" || ui.tool === "home") && inside(cell.x, cell.y) ? cell : null
+ ui.dragFrom = (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave") && inside(cell.x, cell.y) ? cell : null
continue
}
switch (ui.tool) {
case "road":
+ case "pave":
case "home": {
if (ui.dragFrom) {
const cells = lPath(ui.dragFrom, cell).filter((c) => inside(c.x, c.y))
- ui.edits.push(ui.tool === "road" ? { type: "roads", cells } : { type: "homes", cells })
+ ui.edits.push(ui.tool === "road" ? { type: "roads", cells } : ui.tool === "pave" ? { type: "pave", cells } : { type: "homes", cells })
}
ui.dragFrom = null
break
@@ -258,8 +392,9 @@ export const Interact = Game.System(
const r = reachOf(kind)
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)))
- if (ui.tool === "road" || ui.tool === "home") {
+ if (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave") {
const cells = cell === null ? [] : ui.dragFrom ? lPath(ui.dragFrom, cell) : [cell]
for (const c of cells) {
if (!inside(c.x, c.y)) continue
@@ -267,6 +402,10 @@ export const Interact = Game.System(
if (ui.tool === "road") {
if (free) preview.roads.push(c)
else if (useAt(grid, c.x, c.y) !== "road") preview.plots.push({ ...c, size: 1, look: "blocked" })
+ } else if (ui.tool === "pave") {
+ const road = useAt(grid, c.x, c.y) === "road"
+ if (road && !pavedCells.has(key(c.x, c.y))) preview.plots.push({ ...c, size: 1, look: "reach" })
+ else if (!road) preview.plots.push({ ...c, size: 1, look: "blocked" })
} else if (free) preview.ghosts.push({ what: "home", cell: c })
else preview.plots.push({ ...c, size: 1, look: "blocked" })
}
@@ -275,6 +414,7 @@ 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" })
if (canPlace(grid, tile)) preview.ghosts.push({ what: ui.placing, cell: at })
else preview.plots.push({ ...tile, look: "blocked" })
} else if (ui.tool === "bulldoze") {
@@ -289,6 +429,41 @@ export const Interact = Game.System(
if (row && tile) showReach(tile, kinds[row.data.building.get().kind])
}
+ // ── The neighbourhood, explained (only when a home asks) ──
+ let sources: Array<AppealSource> | null = null
+ const appealSources = () => {
+ if (sources) return sources
+ sources = []
+ for (const { data } of buildings) {
+ if (data.site.present || data.rising.present) continue
+ const s = buildingSource(data.building.get().kind, data.tile.get())
+ if (s) sources.push(s)
+ }
+ for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))
+ for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get()))
+ for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get()))
+ for (const { data } of ruins) sources.push(landSource("ruin", data.tile.get()))
+ for (const { data } of houses) if ((maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn) sources.push(landSource("worn", data.tile.get()))
+ return sources
+ }
+ /** Where a home's residents work: the nearest workplace of their crew in reach that has them. */
+ const workOf = (tile: TileLike, tier: Tier) => {
+ const ds = doors(grid, tile)
+ if (ds.length === 0) return null
+ const roads = reach(grid, ds)
+ let best: { title: string; distance: number } | null = null
+ for (const { data } of buildings) {
+ const kind = kinds[data.building.get().kind]
+ const staff = data.staff.get()
+ if (staff.needed === 0 || staff.assigned === 0 || (kind.crew !== crewOf(tier) && !(tier === 1 && staff.apprentices > 0))) continue
+ for (const d of doors(grid, data.tile.get())) {
+ const n = roads.distance[key(d.x, d.y)]!
+ if (n >= 0 && n <= COMMUTE && (best === null || n < best.distance)) best = { title: kind.title.toLowerCase(), distance: n }
+ }
+ }
+ return best
+ }
+
// ── Tooltip and panel ──
const describeBuilding = (row: (typeof buildings)[number]) => {
const kind = kinds[row.data.building.get().kind]
@@ -303,7 +478,10 @@ export const Interact = Game.System(
return { kind, status, problem: null, lines }
}
const staff = row.data.staff.get()
- if (staff.needed > 0) lines.push(`workers ${staff.assigned} of ${staff.needed}`)
+ 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 recipe = maybe(row.data.recipe)
const inventory = maybe(row.data.inventory)
if (recipe)
@@ -311,27 +489,46 @@ export const Interact = Game.System(
`${recipe.input ? `${recipe.inputs} ${recipe.input} → ` : ""}${recipe.batch} ${goods[recipe.output].title} · ${recipe.made} made`
)
if (inventory && !maybe(row.data.hall)) {
- const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => `${inventory.stock[g]} ${g}`)
+ 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")
+ 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" : ""}`)
+ 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`)
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`)
- return { kind, status, problem: problemOf(kind, status, status === "starved" && growingNear(grid, row.data.tile.get(), kind)), lines }
+ 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 }
}
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"] }
+ const tile = row.data.tile.get()
const tier = home.tiers[h.tier]
- const next = h.tier === 1 ? home.tiers[2] : null
+ 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 r = maybe(row.data.risk)
+ const work = workOf(tile, h.tier)
+ const condition = maybe(row.data.condition)
return {
h,
lines: [
- `${h.residents} of ${capacity(h, approval)} residents (${tier.residents} at most)`,
+ ...(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 citizens: ${next.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`
]
}
@@ -340,24 +537,31 @@ export const Interact = Game.System(
const hovered = preview.hover
const hoveredBuilding = hovered !== null ? buildings.find((row) => row.entity.id === hovered) : undefined
const hoveredHouse = hovered !== null ? houses.find((row) => row.entity.id === hovered) : undefined
+ const hoveredRuin = hovered !== null ? ruins.find((row) => row.entity.id === hovered) : undefined
if (hoveredBuilding) {
const { kind, status, problem } = describeBuilding(hoveredBuilding)
preview.tooltip = `${kind.title.toLowerCase()} · ${problem ?? status}`
} else if (hoveredHouse) {
const h = hoveredHouse.data.house.get()
- preview.tooltip = `${home.tiers[h.tier].title}' home · ${h.residents} residents`
+ const t = hoveredHouse.data.tile.get()
+ preview.tooltip = `${tierHome[h.tier]} · ${h.residents} residents · desirability ${appealAt(cells, t.x, t.y)}${hoveredHouse.data.burning.present ? " · on fire!" : hoveredHouse.data.sick.present ? " · sick" : ""}`
+ } else if (hoveredRuin) {
+ preview.tooltip = `ruin · ${hoveredRuin.data.ruin.get().cause} · bulldoze to clear`
} else if (ui.tool === "place" && ui.placing) {
const kind = kinds[ui.placing]
const r = reachOf(kind)
- preview.tooltip = `${kind.title.toLowerCase()}${r !== null ? ` · works ${r} cells around` : ""}`
- }
+ 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"
+ else if (cell && ui.view === "appeal" && inside(cell.x, cell.y)) preview.tooltip = `desirability ${appealAt(cells, cell.x, cell.y)}`
ui.preview = preview
const pickedBuilding = ui.selected !== null ? buildings.find((row) => row.entity.id === ui.selected) : undefined
const pickedHouse = ui.selected !== null ? houses.find((row) => row.entity.id === ui.selected) : undefined
+ const pickedRuin = ui.selected !== null ? ruins.find((row) => row.entity.id === ui.selected) : undefined
if (pickedBuilding) {
const { kind, status, problem, lines } = describeBuilding(pickedBuilding)
- const pausable = kind.id !== "townhall" && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present
+ const pausable = kind.id !== "townhall" && !kind.decor && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present
ui.panel = {
type: "building",
id: pickedBuilding.entity.id,
@@ -372,6 +576,18 @@ export const Interact = Game.System(
} 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 }
+ } else if (pickedRuin) {
+ const r = pickedRuin.data.ruin.get()
+ ui.panel = {
+ type: "ruin",
+ id: pickedRuin.entity.id,
+ 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`
+ ]
+ }
} else ui.panel = ui.menu ? { type: ui.menu } : null
const centres = new Map<number, Point>()
@@ -381,7 +597,96 @@ export const Interact = Game.System(
}
ui.centres = centres
+ // ── 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: [] }
+ ui.legend = null
+ } else if (ui.overlay.key !== overlayKey) {
+ const out: Array<OverlayCell> = []
+ 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") {
+ for (let y = 0; y < GRID; y++)
+ for (let x = 0; x < GRID; x++) {
+ const use = useAt(grid, x, y)
+ if (use === "void" || use === "water") continue
+ out.push({ x, y, size: 1, color: appealColor(appealAt(cells, x, y)), alpha: 0.32 })
+ }
+ } else if (view === "workers") {
+ const picked = pickedBuilding && pickedBuilding.data.staff.get().needed > 0 ? pickedBuilding : undefined
+ let inReach: ((t: TileLike) => boolean) | null = null
+ if (picked) {
+ const roads = reach(grid, doors(grid, picked.data.tile.get()))
+ for (let k = 0; k < roads.distance.length; k++) {
+ const d = roads.distance[k]!
+ if (d >= 0 && d <= COMMUTE) out.push({ x: k % GRID, y: Math.floor(k / GRID), size: 1, color: COOL, alpha: 0.18 })
+ }
+ inReach = (t) => doors(grid, t).some((c) => {
+ const n = roads.distance[key(c.x, c.y)]!
+ return n >= 0 && n <= COMMUTE
+ })
+ }
+ for (const { 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 } : {}) })
+ }
+ 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 } : {}) })
+ }
+ } else if (view === "fire" || view === "health" || view === "order") {
+ for (const { 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 })
+ }
+ for (const { 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 })
+ }
+ } 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 })
+ }
+ 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.legend = legends[view]
+ }
+
+ // ── What needs looking at ──
+ const alerts: Array<string> = []
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) {
+ 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 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")
+
const ledger = resources.ledger.get()
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
@@ -390,10 +695,12 @@ export const Interact = Game.System(
const mood = resources.mood.get()
const crown = resources.crown.get()
const f = resources.fate.get()
- const stock = resources.stock.get()
+ const pantry = resources.pantry.get()
const season = seasonAt(Math.min(Math.max(0, t), termTicks(charter) - 1), charter)
const seconds = (steps: number) => Math.max(0, Math.ceil(steps / 60))
const danger = (since: number, minutes: number) => (since < 0 ? null : seconds(since + minutes * 3600 - t))
+ // The winter after the coming one, for the almanac.
+ const comingYear = season.winter || winterOf(charter, season.year) === null ? season.year + 1 : season.year
ui.stats = {
coins,
taxes: ledger.taxes,
@@ -408,11 +715,19 @@ export const Interact = Game.System(
prices: resources.market.get().prices,
settlers: census.settlers,
citizens: census.citizens,
+ burghers: census.burghers,
jobs: census.jobs,
employed: census.employed,
charter: { size: charter.size, term: charter.term, land: charter.land, seed: charter.seed },
minute: t / 3600,
- season: { year: season.year, winter: season.winter, left: seconds(season.left) },
+ season: {
+ year: season.year,
+ winter: season.winter,
+ left: seconds(season.left),
+ severity: season.severity,
+ coming: season.coming,
+ after: winterOf(charter, comingYear + 1)
+ },
mood: {
approval: mood.approval,
target: mood.target,
@@ -450,8 +765,13 @@ export const Interact = Game.System(
},
goals: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net, approval: mood.approval }),
larder: larder(stock),
+ eaten: pantry.eatenLast,
+ rotted: pantry.rottedLast,
+ sick: census.sick,
+ burning: census.burning,
history: resources.history.get().samples,
- chronicle: resources.chronicle.get().lines
+ chronicle: resources.chronicle.get().lines,
+ alerts
}
}
)
@@ -507,6 +827,16 @@ export const RenderRocks = RenderSync.system(Game, {
apply: (node, { transform }) => node.place(transform.x, transform.y)
})
+export const RenderRuins = RenderSync.system(Game, {
+ name: "Town/RenderRuins",
+ renderable: Ruin,
+ transform: Tile,
+ registry: RuinNodes,
+ services: { stage: StageService },
+ create: ({ renderable, services, entity }) => new RuinView(renderable.cause, services.stage, entity),
+ apply: (node, { transform }) => node.place(transform.x, transform.y, transform.size)
+})
+
export const RenderFields = RenderSync.system(Game, {
name: "Town/RenderFields",
renderable: Field,
@@ -517,13 +847,27 @@ export const RenderFields = RenderSync.system(Game, {
apply: (node, { transform }) => node.place(transform.x, transform.y)
})
-/** The land, redrawn when a new town is founded (or one loaded). */
+/** The land, redrawn when a new town is founded (or one loaded), and frosted through winter. */
export const DrawLand = Game.System(
"Town/DrawLand",
- { resources: { land: Game.System.readResource(Land) }, services: { stage: Game.System.service(StageService) } },
+ {
+ resources: { land: Game.System.readResource(Land), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },
+ services: { stage: Game.System.service(StageService) }
+ },
({ resources, services }) => {
const mask = resources.land.get().mask
- services.stage.setLand(mask)
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ services.stage.setLand(mask, t > 0 && seasonAt(Math.min(t, termTicks(charter) - 1), charter).winter)
+ }
+)
+
+/** The map view, washed over the town. */
+export const DrawOverlay = Game.System(
+ "Town/DrawOverlay",
+ { services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService) } },
+ ({ services }) => {
+ services.stage.setOverlay(services.ui.overlay.key, services.ui.overlay.cells)
}
)
@@ -533,6 +877,8 @@ export const DrawGround = Game.System(
{
queries: {
roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),
+ paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),
+ added: Game.Query({ selection: { paved: Game.Query.read(Paved) }, filters: [Game.Query.added(Paved)] }),
water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),
laid: Game.Query({ selection: { tile: Game.Query.read(Tile) }, filters: [Game.Query.added(Tile)] })
},
@@ -540,10 +886,10 @@ export const DrawGround = Game.System(
services: { stage: Game.System.service(StageService) }
},
({ queries, despawned, services }) => {
- if (!services.stage.groundDirty && queries.laid.each().length === 0 && despawned.entities.all().length === 0) return
+ if (!services.stage.groundDirty && queries.laid.each().length === 0 && queries.added.each().length === 0 && despawned.entities.all().length === 0) return
const cellsOf = (rows: ReadonlyArray<{ readonly data: { readonly tile: { get(): TileLike } } }>) =>
new Set(rows.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))
- services.stage.setGround(cellsOf(queries.roads.each()), cellsOf(queries.water.each()))
+ services.stage.setGround(cellsOf(queries.roads.each()), cellsOf(queries.water.each()), cellsOf(queries.paved.each()))
}
)
@@ -573,17 +919,24 @@ export const Animate = Game.System(
queries: {
buildings: BuildingRead,
houses: HouseRead,
+ ruins: RuinRead,
walkers: Game.Query({
- selection: { route: Game.Query.read(Route), errand: Game.Query.optional(Errand), roam: Game.Query.optional(Roam) }
+ selection: {
+ route: Game.Query.read(Route),
+ errand: Game.Query.optional(Errand),
+ roam: Game.Query.optional(Roam),
+ rescue: Game.Query.optional(Rescue)
+ }
}),
trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),
rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),
fields: Game.Query({ selection: { field: Game.Query.read(Field) } })
},
- resources: { grid: Game.System.readResource(Grid) },
+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal) },
services: {
ui: Game.System.service(Ui),
clock: Game.System.service(Clock),
+ ruinNodes: Game.System.service(RuinNodes),
buildingNodes: Game.System.service(BuildingNodes),
houseNodes: Game.System.service(HouseNodes),
walkerNodes: Game.System.service(WalkerNodes),
@@ -594,6 +947,7 @@ export const Animate = Game.System(
},
({ queries, resources, services }) => {
const grid = resources.grid.get()
+ const cells = resources.appeal.get().cells
const { hover, danger } = services.ui.preview
const emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")
const dt = services.clock.deltaSeconds
@@ -603,8 +957,13 @@ export const Animate = Game.System(
const status = data.status.get()
const recipe = maybe(data.recipe)
const walkers = maybe(data.walkers)?.length ?? 0
+ const worn = (maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn
+ const r = maybe(data.risk)
services.buildingNodes.get(entity.id)?.update(
{
+ alert: alertOf(r ? { fire: r.fire, health: 0, order: 0 } : undefined, false, worn),
+ burning: data.burning.present,
+ worn,
working: status === "working",
problem: problemOf(kind, status) !== null,
build: buildOf(maybe(data.site), maybe(data.rising)),
@@ -617,25 +976,33 @@ export const Animate = Game.System(
)
}
for (const { entity, data } of queries.houses.each()) {
+ const tile = data.tile.get()
+ const worn = (maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn
+ const desirability = appealAt(cells, tile.x, tile.y)
services.houseNodes
.get(entity.id)
?.update(
{
tier: data.house.get().tier,
build: buildOf(maybe(data.site), maybe(data.rising)),
- doors: doorsOf(grid, data.tile.get()),
- site: siteShare(maybe(data.site))
+ doors: doorsOf(grid, tile),
+ site: siteShare(maybe(data.site)),
+ alert: data.site.present ? null : alertOf(maybe(data.risk), data.sick.present, worn),
+ burning: data.burning.present,
+ worn,
+ band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain"
},
emphasis(entity.id)
)
}
+ for (const { entity } of queries.ruins.each()) services.ruinNodes.get(entity.id)?.update(emphasis(entity.id))
for (const { entity, data } of queries.walkers.each()) {
const p = walkerAt(data.route.get())
const errand = maybe(data.errand)
const roam = maybe(data.roam)
const load: Load = errand
? { kind: "cart", good: errand.good, count: !errand.back || errand.count > 0 ? errand.count : 0 }
- : roam?.service === "faith"
+ : roam?.service === "faith" || roam?.service === "health"
? { kind: "bell" }
: roam && total(roam.basket) > 0
? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }
@@ -700,7 +1067,9 @@ export const present = Game.Schedule(
RenderTrees,
RenderRocks,
RenderFields,
+ RenderRuins,
DrawGround,
+ DrawOverlay,
Animate,
Stroll,
DrawPreview
diff --git a/src/render3d/models.ts b/src/render3d/models.ts
index 5a828ca..0af997f 100644
--- a/src/render3d/models.ts
+++ b/src/render3d/models.ts
@@ -63,11 +63,13 @@ export function constructionAsset(size: number, half: number, height: number, bu
export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number) {
const kind = kinds[id],
stage = buildStages(build)
+ // An ornament is laid out at once.
+ if (kind.decor) return makeBuilding(id)
if (build < 0.78) return constructionAsset(kind.size, kind.half, kind.roof === "gable" ? 20 : kind.stories * 32, build, share)
return makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)
}
export function homeAsset(tier: Tier, n: number, build: number, share: number | null, doors: DoorSet) {
- if (build < 0.78) return constructionAsset(1, home.half + (tier === 2 ? 1 : 0), home.tiers[tier].height, build, share)
+ if (build < 0.78) return constructionAsset(1, home.half + (tier >= 2 ? 1 : 0), home.tiers[tier].height, build, share)
return house(tier, n, "home", { doors, fit: buildStages(build).fit, plate: false })
}
export function homeKey(n: number) {
@@ -114,7 +116,7 @@ export function treeVariant(x: number, y: number) {
return { id, type, seed, scale, offset: [dx / 64 + dy / 32, -dx / 64 + dy / 32, 0] as Vertex }
}
-export function landAsset(mask: string) {
+export function landAsset(mask: string, frost = false) {
const d = new Drawing("land", "Land", ""),
land = (x: number, y: number) => x >= 0 && y >= 0 && x < GRID && y < GRID && mask[key(x, y)] === "1"
for (let y = 0; y < GRID; y++)
@@ -127,9 +129,15 @@ export function landAsset(mask: string) {
[x + 1, y + 1, -0.3],
[x, y + 1, -0.3]
],
- 0xf0f2ec,
+ frost ? 0xf7f9fb : 0xf0f2ec,
0
)
+ // Frost: a few pale flecks of snow (a placeholder for a proper winter look).
+ if (frost && hash(x * 7 + 3, y * 5 + 1) < 0.18) {
+ const u = x + 0.2 + hash(x, y * 3) * 0.6,
+ v = y + 0.2 + hash(y, x * 3) * 0.6
+ d.line([[u - 0.05, v, -0.26], [u + 0.05, v, -0.26]], 1, 0xc9d6e4)
+ }
if (land(x + 1, y))
d.line(
[
@@ -180,7 +188,7 @@ export function landAsset(mask: string) {
}
return d.asset
}
-export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<number>, preview = false) {
+export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<number>, preview = false, paved: ReadonlySet<number> = new Set()) {
const d = new Drawing("ground", "Ground", ""),
z = preview ? 0.16 : -0.14
for (const k of roads) {
@@ -188,7 +196,14 @@ export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<numbe
x = cell.x + 0.5,
y = cell.y + 0.5,
half = 0.375,
- color = hash(cell.x, cell.y) < 0.25 ? 0xe2e4dd : 0xe6e8e2
+ stone = paved.has(k),
+ color = stone ? (hash(cell.x, cell.y) < 0.25 ? 0xd3d6cf : 0xd8dbd4) : hash(cell.x, cell.y) < 0.25 ? 0xe2e4dd : 0xe6e8e2
+ // Paved: setts in rows across the street (a placeholder for a proper paved road).
+ if (stone)
+ for (const t of [-0.22, 0, 0.22]) {
+ d.line([[x - 0.3, y + t, z + 0.015], [x + 0.3, y + t, z + 0.015]], 1, 0xb4b9b1, 0.8)
+ d.line([[x + t, y - 0.3, z + 0.015], [x + t, y + 0.3, z + 0.015]], 1, 0xb4b9b1, 0.5)
+ }
d.face(square(x, y, half, z), color, 0)
for (const { x: dx, y: dy } of DIRS) {
const q = (along: number, across: number, height = z + 0.02): Vertex => [
@@ -306,3 +321,24 @@ export function previewAsset(preview: Preview, time: number) {
return d.asset
}
export const quantizeBuild = (build: number) => Math.min(1, Math.round(build * 32) / 32)
+
+/** A footprint washed in a colour, for a map view. */
+export interface OverlayCell {
+ readonly x: number
+ readonly y: number
+ readonly size: number
+ readonly color: number
+ readonly alpha: number
+ /** Outlined, for what the view is about (a workplace and its homes). */
+ readonly ring?: boolean
+}
+export function overlayAsset(cells: ReadonlyArray<OverlayCell>) {
+ const d = new Drawing("overlay", "Map view", "")
+ for (const c of cells) {
+ const half = c.size / 2,
+ ring = square(c.x + half, c.y + half, half - 0.03, 0.12)
+ d.face(ring, c.color, 0, palette.ink, c.alpha)
+ if (c.ring) d.line([...ring, ring[0]!], 1.5, c.color, 0.95)
+ }
+ return d.asset
+}
diff --git a/src/render3d/scene.ts b/src/render3d/scene.ts
index c24c038..4b879aa 100644
--- a/src/render3d/scene.ts
+++ b/src/render3d/scene.ts
@@ -9,7 +9,7 @@ import { key } from "../grid.ts"
import { kinds } from "../content.ts"
import type { Preview, UiValue } from "../ui.ts"
import { ModelHandle, ModelPool } from "./pool.ts"
-import { groundAsset, landAsset, previewAsset } from "./models.ts"
+import { groundAsset, landAsset, overlayAsset, previewAsset, type OverlayCell } from "./models.ts"
export interface SceneNode {
readonly group: THREE.Group
@@ -31,6 +31,10 @@ export class GameScene {
elevation = Math.PI / 6
generation = 0
groundDirty = true
+ /** Winter: the land is frosted and everything standing tinted cold. */
+ frost = false
+ private overlayKey = ""
+ private overlay: BuiltAsset | null = null
private landKey: string | null = null
private groundKey = ""
private previewKey = ""
@@ -192,17 +196,26 @@ export class GameScene {
this.scene.add(model.group)
return model
}
- setLand(mask: string) {
- if (mask === this.landKey) return
- this.landKey = mask
- this.land = this.replace(this.land, landAsset(mask))
+ setLand(mask: string, frost = false) {
+ const id = `${frost}|${mask}`
+ if (id === this.landKey) return
+ this.landKey = id
+ this.frost = frost
+ this.renderer.setClearColor(frost ? 0xe6edf1 : 0xe2e9e6)
+ this.land = this.replace(this.land, landAsset(mask, frost))
}
- setGround(roads: ReadonlySet<number>, water: ReadonlySet<number>) {
- const id = [...roads].join(",") + "|" + [...water].join(",")
+ setGround(roads: ReadonlySet<number>, water: ReadonlySet<number>, paved: ReadonlySet<number> = new Set()) {
+ const id = [...roads].join(",") + "|" + [...water].join(",") + "|" + [...paved].join(",")
if (!this.groundDirty && id === this.groundKey) return
this.groundDirty = false
this.groundKey = id
- this.ground = this.replace(this.ground, groundAsset(roads, water))
+ this.ground = this.replace(this.ground, groundAsset(roads, water, false, paved))
+ }
+ /** A map view: each cell (or footprint) washed in a colour, or nothing. */
+ setOverlay(id: string, cells: ReadonlyArray<OverlayCell>) {
+ if (id === this.overlayKey) return
+ this.overlayKey = id
+ this.overlay = this.replace(this.overlay, overlayAsset(cells))
}
setPreview(preview: Preview, time: number) {
const beat = preview.plots.some((p) => p.look === "picked" || p.look === "blocked") ? Math.floor(time * 8) : 0
@@ -233,6 +246,8 @@ export class GameScene {
for (const handle of this.ghostHandles) handle.dispose()
this.ghostHandles = []
this.overlays = this.replace(this.overlays, { id: "empty", title: "", note: "", faces: [], strokes: [] })
+ this.overlayKey = ""
+ this.overlay = this.replace(this.overlay, { id: "empty", title: "", note: "", faces: [], strokes: [] })
this.roadPreview = this.replace(this.roadPreview, { id: "empty", title: "", note: "", faces: [], strokes: [] })
}
subscribe(onTick: (tick: { deltaMS: number }) => void) {
diff --git a/src/render3d/views.ts b/src/render3d/views.ts
index 539628c..659a129 100644
--- a/src/render3d/views.ts
+++ b/src/render3d/views.ts
@@ -2,7 +2,9 @@ import * as THREE from "three"
import {
carrierDress,
cartLook,
+ homeHeight,
serviceDress,
+ type Alert,
type BuildingLook,
type HouseLook,
type PersonDress,
@@ -16,12 +18,50 @@ import { vertex3 } from "../asset-lab/renderer.ts"
import { Drawing, type Vertex } from "../asset-lab/primitives.ts"
import { makeSails, makeFlag } from "../asset-lab/buildings.ts"
import { makeMarker } from "../asset-lab/construction.ts"
+import { makeFlames, makeRuin, makeWarning } from "../asset-lab/placeholders.ts"
import { makePerson } from "../asset-lab/people.ts"
import { makeTree, makeRock, makeField, hash } from "../asset-lab/land.ts"
import { ModelHandle } from "./pool.ts"
import { buildingAsset, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, treeVariant } from "./models.ts"
import type { GameScene, SceneNode } from "./scene.ts"
+/** Winter's cold tint over everything that stands (a placeholder for snowy roofs). */
+const FROST = 0xe4ecf6
+/** Run down, and a poor street: duller, browner. */
+const WORN = 0xe2d9c8
+const POOR = 0xeee8dc
+const multiply = (a: number, b: number) => {
+ const c = (shift: number) => Math.round((((a >> shift) & 0xff) * ((b >> shift) & 0xff)) / 255)
+ return (c(16) << 16) | (c(8) << 8) | c(0)
+}
+
+/** A sign over a home or building at risk, and flames when it burns: both face the camera. */
+class Signs {
+ private readonly sign: ModelHandle
+ private readonly flames: ModelHandle
+ constructor(make: (pickable?: boolean) => ModelHandle) {
+ this.sign = make(false)
+ this.flames = make(false)
+ this.sign.root.visible = false
+ this.flames.root.visible = false
+ }
+ update(alert: Alert | null | undefined, burning: boolean, height: number) {
+ this.sign.root.visible = !burning && alert !== null && alert !== undefined
+ if (alert && !burning) this.sign.use("warning-" + alert, () => makeWarning(alert))
+ this.sign.root.position.set(0, (height + 10) / Math.cos(Math.PI / 6), 0)
+ this.flames.root.visible = burning
+ if (burning) {
+ const phase = Math.floor(performance.now() / 160) % 2
+ this.flames.use("flames-" + phase, () => makeFlames(phase))
+ this.flames.root.position.set(0, (height * 0.6) / Math.cos(Math.PI / 6), 0)
+ }
+ }
+ orient(heading: number) {
+ this.sign.root.rotation.y = heading - Math.PI / 4
+ this.flames.root.rotation.y = heading - Math.PI / 4
+ }
+}
+
export class WorldView implements SceneNode {
readonly group = new THREE.Group()
readonly anchor = { x: 0, y: 0 }
@@ -48,8 +88,11 @@ export class WorldView implements SceneNode {
for (const m of this.models) m.alpha = value
}
orient() {}
+ /** A tint for what it is like now (run down, a poor street), before winter's frost. */
+ protected shade = 0xffffff
protected emphasis(emphasis: Emphasis) {
- for (const m of this.models) m.tint.setHex(emphasis === "danger" ? 0xf3b5aa : 0xffffff)
+ const tint = emphasis === "danger" ? 0xf3b5aa : multiply(this.shade, this.stage.frost ? FROST : 0xffffff)
+ for (const m of this.models) m.tint.setHex(tint)
}
destroy() {
if (this.disposed) return
@@ -73,12 +116,14 @@ export class BuildingView extends WorldView {
private opening = 0
private beat = -1
private pulse = 0
+ private signs: Signs
constructor(kindId: KindId, stage: GameScene, entity: number) {
super(stage, entity)
this.kindId = kindId
this.body = this.model()
this.plate = this.model()
this.marker = this.model()
+ this.signs = new Signs((pickable) => this.model(pickable))
this.motion = this.model()
this.marker.use("problem-marker", makeMarker)
this.marker.root.visible = false
@@ -116,7 +161,10 @@ export class BuildingView extends WorldView {
Math.cos(Math.PI / 6),
0
)
- this.marker.root.visible = look.problem && look.build >= 1
+ const signed = !!look.burning || (look.alert !== null && look.alert !== undefined)
+ this.marker.root.visible = look.problem && look.build >= 1 && !signed
+ this.signs.update(look.alert, !!look.burning, H + (kind.topper === "none" ? 0 : 16))
+ this.shade = look.worn ? WORN : 0xffffff
this.motion.root.visible = look.build >= 1 && (kind.topper === "flag" || kind.topper === "sails")
if (kind.topper === "flag") {
this.wave += dt * (look.working ? 6 : 3)
@@ -170,17 +218,23 @@ export class BuildingView extends WorldView {
override orient() {
this.marker.root.rotation.y = this.stage.heading - Math.PI / 4
for (const smoke of this.smokes) smoke.root.rotation.y = this.stage.heading - Math.PI / 4
+ this.signs.orient(this.stage.heading)
}
}
export class HouseView extends WorldView {
private body: ModelHandle
private plate: ModelHandle
+ private signs: Signs
private n = 0.03
constructor(stage: GameScene, entity: number) {
super(stage, entity)
this.body = this.model()
this.plate = this.model()
+ this.signs = new Signs((pickable) => this.model(pickable))
+ }
+ override orient() {
+ this.signs.orient(this.stage.heading)
}
place(x: number, y: number) {
this.n = hash(x, y)
@@ -196,6 +250,29 @@ export class HouseView extends WorldView {
homeAsset(look.tier, this.n, build, share, doors)
)
this.plate.use(`plate/1/${build}`, () => plateAsset(1, build))
+ this.signs.update(look.alert, !!look.burning, homeHeight(look.tier))
+ // Placeholder for homes that look like their street: fences and gardens on a fine one, a patched roof on a poor one.
+ this.shade = look.worn ? WORN : look.band === "poor" ? POOR : 0xffffff
+ this.emphasis(emphasis)
+ }
+}
+
+/** What is left of a home or building, until it is cleared. */
+export class RuinView extends WorldView {
+ private body: ModelHandle
+ private cause: "burnt" | "collapsed" | "derelict"
+ constructor(cause: "burnt" | "collapsed" | "derelict", stage: GameScene, entity: number) {
+ super(stage, entity)
+ this.cause = cause
+ this.body = this.model()
+ }
+ place(x: number, y: number, size: number) {
+ this.anchor.x = x + size / 2
+ this.anchor.y = y + size / 2
+ this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))
+ this.body.use(`ruin/${this.cause}/${size}`, () => makeRuin(size, this.cause))
+ }
+ update(emphasis: Emphasis) {
this.emphasis(emphasis)
}
}
diff --git a/src/save.ts b/src/save.ts
index 9c060d0..2620d1e 100644
--- a/src/save.ts
+++ b/src/save.ts
@@ -11,8 +11,11 @@
import { Clock, Context, Effect, Schema } from "effect"
export const SAVE_FORMAT = "inkline-town/save"
-/** 2: the charter's towns. Older saves (a square map, no term) cannot be loaded. */
-export const SAVE_VERSION = 2
+/**
+ * 2: the charter's towns. 3: neighbourhoods and their dangers (desirability, crews, risks, wear, ruins,
+ * winters). Older saves cannot be loaded.
+ */
+export const SAVE_VERSION = 3
export type Slot = "manual" | "auto"
export const slots: ReadonlyArray<Slot> = ["manual", "auto"]
diff --git a/src/schema.ts b/src/schema.ts
index b944bc7..07796f2 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -15,9 +15,9 @@ import { Decode, Descriptor, Schema } from "@typeonce/bevy-ts"
import type { OptionalReadCell } from "@typeonce/bevy-ts/Query"
import type { NodeRegistry } from "@typeonce/bevy-ts-render"
-import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./render3d/views.ts"
+import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./render3d/views.ts"
import type { GameScene } from "./render3d/scene.ts"
-import { goodIds, kindIds, landIds, sizeIds, type Amounts } from "./content.ts"
+import { goodIds, kindIds, landIds, serviceIds, sizeIds, type Amounts } from "./content.ts"
import type { UiValue } from "./ui.ts"
export const Root = Schema.defineRoot("Town")
@@ -28,10 +28,10 @@ export const maybe = <T>(cell: OptionalReadCell<T>) => (cell.present ? cell.get(
const integer = Decode.integer
const cell = Decode.struct({ x: integer, y: integer })
const good = Decode.literal(...goodIds)
-const service = Decode.literal("goods", "faith")
+const service = Decode.literal(...serviceIds)
/** A count of every good. */
const amounts = Decode.struct({
- wood: integer, planks: integer, stone: integer, ore: integer, tools: integer, fish: integer,
+ wood: integer, planks: integer, stone: integer, ore: integer, tools: integer, fish: integer, smoked: integer,
wheat: integer, flour: integer, bread: integer, wool: integer, cloth: integer
})
@@ -43,6 +43,10 @@ export type Status = (typeof statuses)[number]
/** A square of cells on the grid, by its top cell, `size` cells a side. */
export const Tile = Descriptor.ConstructedComponent(Decode.struct({ x: integer, y: integer, size: integer }))("Town/Tile")
export const Road = Descriptor.Tag("Town/Road")
+/** A road paved with stone: a little nicer to live on (see `appeal.ts`). */
+export const Paved = Descriptor.Tag("Town/Paved")
+/** What is left of a home or building that burned, fell down, or was left derelict, until it is cleared. */
+export const Ruin = Descriptor.ConstructedComponent(Decode.struct({ cause: Decode.literal("burnt", "collapsed", "derelict") }))("Town/Ruin")
/** Materials still owed before it can go up, out of `total`. */
export const Site = Descriptor.ConstructedComponent(Decode.struct({ owed: amounts, total: integer }))("Town/Site")
/** Going up: steps since its materials were all in (see `BUILD_TICKS`). Removed once it stands. */
@@ -59,7 +63,7 @@ export const Field = Descriptor.ConstructedComponent(Decode.struct({ growth: int
/** A home: its tier, residents, and steps left of each need a walker last met. */
export const House = Descriptor.ConstructedComponent(Decode.struct({
- tier: Decode.literal(1, 2),
+ tier: Decode.literal(1, 2, 3),
residents: integer,
food: integer,
bread: integer,
@@ -68,6 +72,21 @@ export const House = Descriptor.ConstructedComponent(Decode.struct({
clock: integer
}))("Town/House")
+// ── Risks and wear (homes and buildings) ──────────────────────────────────
+
+/**
+ * Risk meters, 0 → `RISK_MAX` (see `risk` in content): fire, sickness, and
+ * disorder (a building only has the first), and thefts since a constable last
+ * passed.
+ */
+export const Risk = Descriptor.ConstructedComponent(Decode.struct({ fire: integer, health: integer, order: integer, thefts: integer }))("Town/Risk")
+/** How well kept it is, 0 → `CONDITION_MAX`; it falls into ruin at nothing. */
+export const Condition = Descriptor.ConstructedComponent(Decode.struct({ value: integer }))("Town/Condition")
+/** On fire: steps until it is lost, and which fire (see `Fires`) it belongs to. */
+export const Burning = Descriptor.ConstructedComponent(Decode.struct({ left: integer, fire: integer }))("Town/Burning")
+/** A sick household: steps until it passes on its own. */
+export const Sick = Descriptor.ConstructedComponent(Decode.struct({ left: integer }))("Town/Sick")
+
// ── Buildings and their roles ─────────────────────────────────────────────
export const Building = Descriptor.ConstructedComponent(Decode.struct({ kind: Decode.literal(...kindIds) }))("Town/Building")
@@ -76,8 +95,11 @@ export const Status = Descriptor.ConstructedComponent(Decode.literal(...statuses
/** Stopped by the town: no workers, a quarter of its upkeep. */
export const Paused = Descriptor.Tag("Town/Paused")
-/** Workers it needs, and how many the town could spare it this step. */
-export const Staff = Descriptor.ConstructedComponent(Decode.struct({ needed: integer, assigned: integer }))("Town/Staff")
+/**
+ * Workers it needs, how many came (`apprentices` of them settlers standing
+ * in for citizens), and how many of its crew live within a commute.
+ */
+export const Staff = Descriptor.ConstructedComponent(Decode.struct({ needed: integer, assigned: integer, apprentices: integer, nearby: integer }))("Town/Staff")
/** Goods on hand: only the ones it `accepts`, up to `cap` of each. */
export const Inventory = Descriptor.ConstructedComponent(Decode.struct({ stock: amounts, accepts: Decode.array(good), cap: integer }))("Town/Inventory")
@@ -137,6 +159,9 @@ export const Errand = Descriptor.ConstructedComponent(Decode.struct({
back: Decode.boolean
}))("Town/Errand")
+/** A firefighter running to a blaze, then walking back. */
+export const Rescue = Descriptor.ConstructedComponent(Decode.struct({ target: Decode.handle(Root, Tile), back: Decode.boolean }))("Town/Rescue")
+
/** Wandering the roads serving homes, `left` cells more, then walking back with what is left in its basket. */
export const Roam = Descriptor.ConstructedComponent(Decode.struct({ service, left: integer, basket: amounts, back: Decode.boolean }))("Town/Roam")
@@ -156,14 +181,20 @@ export const Ledger = Descriptor.ConstructedResource(Decode.struct({ taxes: inte
export const Census = Descriptor.ConstructedResource(Decode.struct({
homes: integer,
settlers: integer,
+ /** Residents of citizens' homes and townhouses together: the citizens the goals count. */
citizens: integer,
+ /** Of the citizens, those in townhouses. */
+ burghers: integer,
jobs: integer,
employed: integer,
/** Homes with each need met right now. */
food: integer,
bread: integer,
cloth: integer,
- faith: integer
+ faith: integer,
+ /** Homes sick, and homes and buildings on fire, right now. */
+ sick: integer,
+ burning: integer
}))("Town/Census")
/**
* The town's tax rates (in percent of the usual, for each tier), what it
@@ -186,7 +217,9 @@ export const Charter = Descriptor.ConstructedResource(Decode.struct({
term: integer,
land: Decode.literal(...landIds),
seed: integer,
- founded: integer
+ founded: integer,
+ /** Each year's winter, rolled when the town is founded: "none" for the first, then mild, normal, or hard. */
+ winters: Decode.array(Decode.literal("none", "mild", "normal", "hard"))
}))("Town/Charter")
/** Which cells are land ("1") and which open water beyond the coast ("0"), by `key`; and how many are land. */
export const Land = Descriptor.ConstructedResource(Decode.struct({ mask: Decode.string, cells: integer }))("Town/Land")
@@ -250,12 +283,29 @@ 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. */
-export const Chronicle = Descriptor.ConstructedResource(Decode.struct({ lines: Decode.array(Decode.struct({ tick: integer, text: Decode.string })) }))("Town/Chronicle")
+/** What happened, in a line each; an `alarm` is news the page announces (a fire, a theft, winter coming). */
+export const Chronicle = Descriptor.ConstructedResource(Decode.struct({
+ lines: Decode.array(Decode.struct({ tick: integer, text: Decode.string, alarm: Decode.boolean }))
+}))("Town/Chronicle")
+
+/** How desirable each cell is to live on (by `key`), reckoned every `appeal.every` steps; empty before the first. */
+export const Appeal = Descriptor.ConstructedResource(Decode.struct({ cells: Decode.array(integer) }))("Town/Appeal")
+
+/**
+ * The town's food over the last minute: what walkers handed out and what
+ * rotted, counting now, and the last full minute's totals.
+ */
+export const Pantry = Descriptor.ConstructedResource(Decode.struct({ eaten: integer, rotted: integer, eatenLast: integer, rottedLast: integer, warned: integer }))("Town/Pantry")
+
+/** Fires burning now (each started at a cell, the homes and buildings it took so far), and the next fire's number. */
+export const Fires = Descriptor.ConstructedResource(Decode.struct({
+ fires: Decode.array(Decode.struct({ id: integer, x: integer, y: integer, homes: integer, buildings: integer })),
+ next: integer
+}))("Town/Fires")
/** What stands on each cell, rebuilt every step from the tiles (see `grid.ts`). */
/** `void`: off the land, past the coast. */
-export type Use = "empty" | "road" | "house" | "building" | "tree" | "rock" | "water" | "field" | "void"
+export type Use = "empty" | "road" | "house" | "building" | "tree" | "rock" | "water" | "field" | "ruin" | "void"
export interface GridValue {
/** Entity id on each cell (by `key`), or 0. */
readonly owner: ReadonlyArray<number>
@@ -281,15 +331,17 @@ export const WalkerNodes = Descriptor.Service<NodeRegistry.NodeRegistry<WalkerVi
export const TreeNodes = Descriptor.Service<NodeRegistry.NodeRegistry<TreeView>>()("Town/TreeNodes")
export const RockNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RockView>>()("Town/RockNodes")
export const FieldNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FieldView>>()("Town/FieldNodes")
+export const RuinNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RuinView>>()("Town/RuinNodes")
export const Game = Schema.bind(
Schema.fragment({
components: {
- Tile, Road, Site, Rising, Tree, Rock, Water, Field, House, Building, TownHall, Status, Paused, Staff, Inventory, Storage,
- Recipe, Gatherer, Planter, Carriers, Service, Figure, Route, Errand, Roam
+ Tile, Road, Paved, Ruin, Site, Rising, Tree, Rock, Water, Field, House, Risk, Condition, Burning, Sick, Building, TownHall, Status,
+ Paused, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Figure, Route, Errand, Rescue, Roam
},
resources: {
- Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Grid, Stock
+ Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Appeal, Pantry, Fires,
+ Grid, Stock
},
relations: { WalkerOf, FieldOf }
}),
diff --git a/src/sim/decay.ts b/src/sim/decay.ts
new file mode 100644
index 0000000..0c96cb3
--- /dev/null
+++ b/src/sim/decay.ts
@@ -0,0 +1,96 @@
+/**
+ * What time does to the town: homes and buildings run down until a builder
+ * mends them, and fall into ruin if none does; fish and bread rot on the
+ * shelf, slower in a granary. The pantry keeps count of what the town ate
+ * and what rotted, a minute at a time.
+ */
+import * as Random from "@typeonce/bevy-ts-math/Random"
+
+import { ruinDraft } from "../archetypes.ts"
+import { condition as wear, goodIds, kinds, SPOIL_TICKS, spoils, ticks } from "../content.ts"
+import { counted, placeName } from "../places.ts"
+import {
+ Building, Burning, Charter, Chronicle, Condition, Game, House, Inventory, Pantry, Rising, Rng, Site, Tile, Time, maybe
+} from "../schema.ts"
+import { elapsed, write } from "./shared.ts"
+
+/** The pantry warns of rotting food at most this often. */
+const ROT_WARNING = ticks(5 * 60)
+
+export const Decay = Game.System(
+ "Town/Decay",
+ {
+ queries: {
+ worn: Game.Query({
+ selection: { tile: Game.Query.read(Tile), condition: Game.Query.write(Condition), house: Game.Query.optional(House), building: Game.Query.optional(Building) },
+ 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] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ rng: Game.System.writeResource(Rng),
+ pantry: Game.System.writeResource(Pantry),
+ chronicle: Game.System.writeResource(Chronicle)
+ }
+ },
+ ({ queries, resources, commands }) => {
+ const tick = resources.time.get().tick
+ const t = elapsed(resources.time.get(), resources.charter.get())
+
+ // Wear: a point every `wear.every` steps; at nothing it falls down.
+ if (tick % wear.every === 0) {
+ const landmarks = queries.landmarks.each().map(({ data }) => ({ kind: data.building.get().kind, ...data.tile.get() }))
+ for (const { entity, data } of queries.worn.each()) {
+ const value = data.condition.get().value - 1
+ if (value > 0) {
+ data.condition.set({ value })
+ continue
+ }
+ const tile = data.tile.get()
+ const b = maybe(data.building)
+ commands.despawn(entity.id)
+ commands.spawn(ruinDraft(tile, "collapsed"))
+ write(
+ 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
+ )
+ }
+ }
+
+ // Spoiling: each shelf loses its share of what spoils, a granary's a fifth as much.
+ if (tick % SPOIL_TICKS === 0) {
+ const random = Random.make(resources.rng.get())
+ let rotted = 0
+ for (const { data } of queries.shelves.each()) {
+ const inv = data.inventory.get()
+ const keeps = kinds[maybe(data.building)?.kind ?? "townhall"].keeps ?? 1
+ let stock = inv.stock
+ for (const g of goodIds) {
+ const life = spoils[g]
+ if (life === undefined || stock[g] <= 0) continue
+ const expected = (stock[g] * SPOIL_TICKS) / (life * 60 * keeps)
+ const lose = Math.min(stock[g], Math.floor(expected) + (random.next() < expected % 1 ? 1 : 0))
+ if (lose <= 0) continue
+ stock = { ...stock, [g]: stock[g] - lose }
+ rotted += lose
+ }
+ if (stock !== inv.stock) data.inventory.set({ ...inv, stock })
+ }
+ resources.rng.set(random.state)
+ if (rotted > 0) resources.pantry.update((p) => ({ ...p, rotted: p.rotted + rotted }))
+ }
+
+ // 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)
+ 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 858a3d3..3bb93db 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -9,15 +9,17 @@
import {
buildingDraft, houseDraft, houseStart, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft
} from "../archetypes.ts"
-import { amounts, goodIds, goods, home, kinds, lands, ROAD_COST, sizes, trade, type Amounts, type Kind } from "../content.ts"
+import * as Random from "@typeonce/bevy-ts-math/Random"
+
+import { amounts, goodIds, goods, home, kinds, lands, PAVE_COST, ROAD_COST, sizes, trade, type Amounts, type Kind } from "../content.ts"
import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"
import { inside } from "../iso.ts"
import { generate } from "../mapgen.ts"
import {
- Building, Census, Charter, Chronicle, Crown, Fate, Game, History, Inventory, Land, Ledger, Market, Mood, Paused, Policy, Rng, Status, Stock,
- Storage, Time, TownHall, Treasury, Ui
+ Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, History, Inventory, Land, Ledger, Market, Mood, Pantry, Paved, Paused,
+ Policy, Rising, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui
} from "../schema.ts"
-import { elapsed, TileRead, useOf } from "./shared.ts"
+import { elapsed, rollWinters, TileRead, useOf, write } from "./shared.ts"
import { crownGap, foundedFate } from "./term.ts"
export const unlocked = (kind: Kind, census: { readonly settlers: number; readonly citizens: number }) =>
@@ -28,6 +30,7 @@ export const ApplyEdits = Game.System(
{
queries: {
tiles: TileRead,
+ paved: Game.Query({ selection: { paved: Game.Query.read(Paved) } }),
halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } }),
buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused) } }),
stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] })
@@ -47,7 +50,10 @@ export const ApplyEdits = Game.System(
crown: Game.System.writeResource(Crown),
fate: Game.System.writeResource(Fate),
history: Game.System.writeResource(History),
- chronicle: Game.System.writeResource(Chronicle)
+ chronicle: Game.System.writeResource(Chronicle),
+ appeal: Game.System.writeResource(Appeal),
+ pantry: Game.System.writeResource(Pantry),
+ fires: Game.System.writeResource(Fires)
},
services: { ui: Game.System.service(Ui) }
},
@@ -76,6 +82,19 @@ export const ApplyEdits = Game.System(
coins -= cost.coins
for (const [g, n] of Object.entries(cost.materials)) left[g] = (left[g] ?? 0) - (n ?? 0)
}
+ /** Takes goods out of storage at once, fullest first. */
+ const take = (materials: Partial<Record<string, number>>) => {
+ for (const [g, n] of Object.entries(materials) as Array<[keyof Amounts, number]>) {
+ let owed = n
+ for (const { data } of [...queries.stores.each()].sort((a, b) => b.data.inventory.get().stock[g] - a.data.inventory.get().stock[g])) {
+ if (owed <= 0) break
+ const inv = data.inventory.get()
+ const n = Math.min(owed, inv.stock[g])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] - n } })
+ owed -= n
+ }
+ }
+ }
/** Fells the trees under a tile about to be built on. */
const fell = (tile: { x: number; y: number; size: number }) => {
for (const c of cellsOf(tile)) {
@@ -117,7 +136,11 @@ export const ApplyEdits = Game.System(
}
pay(kind.cost)
const id = spawn(buildingDraft(kind, edit.cell), tile, "building")
- commands.insert(id, startOf(kind), ...rolesOf(kind))
+ if (kind.decor) {
+ // An ornament needs no road: its materials come out of storage at once, and it goes straight up.
+ take(kind.cost.materials)
+ commands.insert(id, Game.Command.entry(Rising, { ticks: 0 }), ...rolesOf(kind))
+ } else commands.insert(id, startOf(kind), ...rolesOf(kind))
if (edit.open) ui.selected = id
break
}
@@ -130,7 +153,7 @@ export const ApplyEdits = Game.System(
if (short) break
pay(home.cost)
const id = spawn(houseDraft(cell), tile, "house")
- commands.insert(id, houseStart())
+ commands.insert(id, ...houseStart())
}
if (short) ui.toast(short)
break
@@ -150,6 +173,27 @@ export const ApplyEdits = Game.System(
if (short) ui.toast("Not enough coins")
break
}
+ case "pave": {
+ // Stone comes out of storage at once, fullest first.
+ const paved = new Set<number>(queries.paved.each().map((row) => row.entity.id))
+ let short: string | null = null
+ let stone = 0
+ for (const cell of edit.cells) {
+ if (!inside(cell.x, cell.y) || useAt(grid.value(), cell.x, cell.y) !== "road") continue
+ const road = entities.get(ownerAt(grid.value(), cell.x, cell.y))
+ if (road === undefined || paved.has(road)) continue
+ short = afford({ coins: PAVE_COST.coins, materials: { stone: PAVE_COST.stone } })
+ if (short) break
+ coins -= PAVE_COST.coins
+ left.stone = (left.stone ?? 0) - PAVE_COST.stone
+ stone += PAVE_COST.stone
+ paved.add(road)
+ commands.insert(road, Game.Command.entry(Paved, {}))
+ }
+ take({ stone })
+ if (short) ui.toast(short)
+ break
+ }
case "remove": {
if (!inside(edit.cell.x, edit.cell.y)) break
const use = useAt(grid.value(), edit.cell.x, edit.cell.y)
@@ -207,7 +251,7 @@ export const ApplyEdits = Game.System(
left[c.good] = (left[c.good] ?? 0) - c.amount
coins += c.reward
resources.crown.set({ ...c, open: false, met: c.met + 1, streak: 0 })
- resources.chronicle.update((ch) => ({ lines: [...ch.lines, { tick: t, text: `Sent the crown ${c.amount} ${goods[c.good].title}, for ${c.reward} coins.` }].slice(-200) }))
+ write(resources.chronicle, t, `Sent the crown ${c.amount} ${goods[c.good].title}, for ${c.reward} coins.`)
ui.toast(`Sent · +${c.reward} coins`)
break
}
@@ -215,7 +259,7 @@ export const ApplyEdits = Game.System(
const f = resources.fate.get()
if (f.state !== "won") break
resources.fate.set({ ...f, state: "playing", governing: true, won: f.at, reason: "" })
- resources.chronicle.update((ch) => ({ lines: [...ch.lines, { tick: t, text: "The mayor stays on to govern the town to the end of the term." }].slice(-200) }))
+ write(resources.chronicle, t, "The mayor stays on to govern the town to the end of the term.")
break
}
case "reserve":
@@ -238,7 +282,12 @@ export const ApplyEdits = Game.System(
commands.insert(id, Game.Command.entry(TownHall, {}), Game.Command.entry(Status, "idle"), Game.Command.entry(Inventory, { stock, accepts: goodIds, cap: hall.holds?.cap ?? 60 }))
coins = richness.coins
const founded = resources.time.get().tick
- resources.charter.set({ ...charter, founded })
+ // The almanac: each year's winter, from the seed (on its own stream, so the land's randomness is untouched).
+ const almanac = Random.make((charter.seed ^ 0x5a17c3) >>> 0)
+ resources.charter.set({ ...charter, founded, winters: rollWinters(() => almanac.next()) })
+ resources.appeal.set({ cells: [] })
+ resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 })
+ resources.fires.set({ fires: [], next: 1 })
resources.land.set({ mask: land.mask, cells: land.cells })
resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0, admin: 0 })
resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve })
@@ -248,7 +297,7 @@ export const ApplyEdits = Game.System(
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.` }]
+ lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.`, alarm: false }]
})
resources.rng.set(charter.seed)
ui.selected = null
diff --git a/src/sim/hazards.ts b/src/sim/hazards.ts
new file mode 100644
index 0000000..3ca47b0
--- /dev/null
+++ b/src/sim/hazards.ts
@@ -0,0 +1,360 @@
+/**
+ * The neighbourhood and its dangers. Every so often the town's desirability
+ * is reckoned cell by cell (`Appraise`). Once a second every home's risk of
+ * fire, sickness, and disorder rises, and every building's risk of fire
+ * (`Hazards`): the matching service walker resets it (see `Wander`). A
+ * risk at the top is a disaster: a fire that burns the home down and may
+ * spread, a sickness that thins it out and may spread, a theft, and then a
+ * home left derelict. A fire watch sends firefighters running to any blaze
+ * (`Douse`): when they arrive, that house is lost but the fire is out.
+ */
+import * as Random from "@typeonce/bevy-ts-math/Random"
+
+import { appealGrid, appealAt, buildingSource, landSource, type AppealSource } from "../appeal.ts"
+import { ruinDraft } from "../archetypes.ts"
+import { appeal, condition as wear, goodIds, goods, home, kinds, risk, RISK_MAX, winters, type GoodId } from "../content.ts"
+import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"
+import { counted, placeName, type Landmark } from "../places.ts"
+import type { Point } from "../iso.ts"
+import {
+ Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Grid, House, Inventory, Mood, Paved, Rescue, Rising, Risk, Rng,
+ Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, WalkerOf, Water, maybe
+} from "../schema.ts"
+import { elapsed, seasonAt, write } from "./shared.ts"
+
+// ── Desirability ──────────────────────────────────────────────────────────
+
+/** Reckons every cell's desirability, every `appeal.every` steps (and at once when there is none yet). */
+export const Appraise = Game.System(
+ "Town/Appraise",
+ {
+ queries: {
+ buildings: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
+ trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),
+ water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),
+ paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),
+ ruins: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Ruin] }),
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition) }, with: [House], without: [Site, Rising] })
+ },
+ resources: { time: Game.System.readResource(Time), appeal: Game.System.writeResource(Appeal) }
+ },
+ ({ queries, resources }) => {
+ if (resources.time.get().tick % appeal.every !== 0 && resources.appeal.get().cells.length > 0) return
+ const sources: Array<AppealSource> = []
+ for (const { data } of queries.buildings.each()) {
+ const s = buildingSource(data.building.get().kind, data.tile.get())
+ if (s) sources.push(s)
+ }
+ for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))
+ for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get()))
+ for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get()))
+ for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get()))
+ for (const { data } of queries.homes.each()) if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get()))
+ resources.appeal.set({ cells: appealGrid(sources) })
+ }
+)
+
+// ── Risks ─────────────────────────────────────────────────────────────────
+
+/** The risks are reckoned this often (once a second). */
+export const RISK_TICKS = 60
+
+/** A stable number 0 → 1 for a cell. */
+const hash = (x: number, y: number) => {
+ let h = (x * 374761393 + y * 668265263) >>> 0
+ h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296
+}
+/** How fast the risks of whatever stands on a cell rise, against the usual. */
+export const paceAt = (x: number, y: number) => risk.pace[0] + (risk.pace[1] - risk.pace[0]) * hash(x, y)
+
+/** Within `r` rings of a footprint. */
+const near = (a: { readonly x: number; readonly y: number; readonly size: number }, b: { readonly x: number; readonly y: number; readonly size: number }, r: number) =>
+ Math.max(a.x - (b.x + b.size - 1), b.x - (a.x + a.size - 1), a.y - (b.y + b.size - 1), b.y - (a.y + a.size - 1)) <= r
+
+export const Hazards = Game.System(
+ "Town/Hazards",
+ {
+ queries: {
+ cared: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ risk: Game.Query.write(Risk),
+ condition: Game.Query.read(Condition),
+ house: Game.Query.optional(House),
+ building: Game.Query.optional(Building),
+ sick: Game.Query.optional(Sick),
+ burning: Game.Query.optional(Burning)
+ },
+ without: [Site, Rising]
+ }),
+ sickness: Game.Query({ selection: { sick: Game.Query.write(Sick) } }),
+ blazes: Game.Query({ selection: { burning: Game.Query.write(Burning) } }),
+ landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
+ watches: Game.Query({
+ selection: { tile: Game.Query.read(Tile), service: Game.Query.read(Service), staff: Game.Query.read(Staff) },
+ without: [Site, Rising, Burning]
+ }),
+ crews: Game.Query({ selection: { rescue: Game.Query.read(Rescue), home: Game.Query.readRelation(WalkerOf) } }),
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ grid: Game.System.readResource(Grid),
+ appeal: Game.System.readResource(Appeal),
+ mood: Game.System.readResource(Mood),
+ rng: Game.System.writeResource(Rng),
+ treasury: Game.System.writeResource(Treasury),
+ fires: Game.System.writeResource(Fires),
+ chronicle: Game.System.writeResource(Chronicle)
+ }
+ },
+ ({ queries, resources, commands }) => {
+ const tick = resources.time.get().tick
+ if (tick % RISK_TICKS !== 0) return
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ const grid = resources.grid.get()
+ const cells = resources.appeal.get().cells
+ const approval = resources.mood.get().approval
+ const season = seasonAt(t, charter)
+ 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 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 })) }
+
+ const rows = queries.cared.each()
+ const hot = rows.filter(({ data }) => {
+ const b = maybe(data.building)
+ return b !== undefined && kinds[b.kind].hot === true && !data.burning.present
+ }).map(({ data }) => data.tile.get())
+ const dusty = landmarks.filter((l) => kinds[l.kind].dusty)
+ const waterNear = (tile: { readonly x: number; readonly y: number }) => {
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, tile.x + dx, tile.y + dy) === "water") return true
+ return false
+ }
+ const sickNow = rows.filter(({ data }) => data.sick.present).length
+
+ /** Turns a home or building into a ruin. */
+ const ruin = (row: (typeof rows)[number], cause: "burnt" | "collapsed" | "derelict") => {
+ commands.despawn(row.entity.id)
+ commands.spawn(ruinDraft(row.data.tile.get(), cause))
+ }
+ const lost = new Set<number>()
+ const ignited = new Map<number, number>()
+
+ // Rising risks, and what comes of them.
+ for (const row of rows) {
+ const { data } = row
+ if (data.burning.present) continue
+ const tile = data.tile.get()
+ const h = maybe(data.house)
+ const b = maybe(data.building)
+ const r = { ...data.risk.get() }
+ const worn = data.condition.get().value < wear.worn
+ const desirability = appealAt(cells, tile.x, tile.y)
+ const squalid = desirability < 0
+ const pace = paceAt(tile.x, tile.y)
+ let fire = 0
+ if (h) {
+ const max = home.tiers[h.tier].residents
+ const crowded = h.residents >= max * 0.75
+ fire = (h.tier === 1 ? risk.fire.wooden : risk.fire.stone) +
+ Math.min(2, hot.filter((s) => near(s, tile, risk.fire.reach)).length) * risk.fire.near +
+ (crowded ? risk.fire.crowded : 0) + (worn ? risk.fire.worn : 0) + (heating ? risk.fire.winter : 0)
+ const health = risk.health.base + (h.food <= 0 ? risk.health.hungry : 0) + (crowded ? risk.health.crowded : 0) +
+ (squalid ? risk.health.squalid : 0) + (dusty.some((d) => near(d, tile, risk.health.reach)) ? risk.health.dust : 0) +
+ (waterNear(tile) ? risk.health.water : 0)
+ const order = risk.order.base + (approval < 0 ? Math.round((-approval / 50) * risk.order.unrest) : 0) + (squalid ? risk.order.squalid : 0) +
+ (h.residents < max / 2 ? risk.order.vacant : 0) + (h.tier === 3 ? risk.order.wealth : 0)
+ if (!data.sick.present) r.health = Math.min(RISK_MAX, r.health + Math.round(health * pace))
+ r.order = Math.min(RISK_MAX, r.order + Math.round(order * pace))
+ } else if (b) fire = risk.fire.building + (kinds[b.kind].hot ? risk.fire.hot : 0) + (worn ? risk.fire.worn : 0)
+ r.fire = Math.min(RISK_MAX, r.fire + Math.round(fire * pace))
+
+ if (r.fire >= RISK_MAX) {
+ // Fire!
+ const id = fires.next
+ fires.next += 1
+ fires.fires.push({ id, x: tile.x, y: tile.y, homes: 0, buildings: 0 })
+ 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)}!`)
+ }
+ 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 (h && r.order >= RISK_MAX) {
+ if (r.thefts === 0) {
+ // A theft: coins from the treasury, or goods from storage when it is empty.
+ const coins = resources.treasury.get().coins
+ 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.`)
+ } else {
+ const stores = queries.stores.each()
+ const held = (g: GoodId) => stores.reduce((n, s) => n + s.data.inventory.get().stock[g], 0)
+ const good = [...goodIds].sort((a, b) => held(b) * goods[b].price - held(a) * goods[a].price)[0]!
+ let owed = Math.min(risk.order.goods, held(good))
+ for (const { data: s } of stores) {
+ if (owed <= 0) break
+ const inv = s.inventory.get()
+ const n = Math.min(owed, inv.stock[good])
+ 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}.`)
+ }
+ r.thefts += 1
+ r.order = risk.order.after
+ } else {
+ news(`A home on ${where(tile)} stood empty after its thefts, and is left derelict.`)
+ ruin(row, "derelict")
+ lost.add(row.entity.id)
+ continue
+ }
+ }
+ data.risk.set(r)
+ }
+
+ // Sickness runs its course, and spreads to homes close by.
+ const homeRows = rows.filter(({ entity, data }) => data.house.present && !data.burning.present && !lost.has(entity.id))
+ for (const { entity, data } of queries.sickness.each()) {
+ const s = data.sick.get()
+ const left = s.left - RISK_TICKS
+ if (left <= 0) {
+ commands.remove(entity.id, Sick)
+ continue
+ }
+ data.sick.set({ left })
+ if (random.next() >= risk.health.spreads) continue
+ const me = rows.find((row) => row.entity.id === entity.id)
+ if (!me) continue
+ const at = me.data.tile.get()
+ const target = random.pick(homeRows.filter(({ entity: e, data: d }) => e.id !== entity.id && !d.sick.present && near(d.tile.get(), at, 2)))
+ if (target) {
+ const r = target.data.risk.get()
+ target.data.risk.set({ ...r, health: Math.min(RISK_MAX, r.health + risk.health.contagion) })
+ }
+ }
+
+ // Fires burn down what they hold, and catch what stands beside them.
+ const byId = new Map(rows.map((row) => [row.entity.id as number, row]))
+ for (const { entity, data } of queries.blazes.each()) {
+ const b = data.burning.get()
+ const row = byId.get(entity.id)
+ if (!row) continue
+ const fire = fires.fires.find((f) => f.id === b.fire)
+ const left = b.left - RISK_TICKS
+ if (left <= 0) {
+ ruin(row, "burnt")
+ lost.add(entity.id)
+ if (fire) {
+ if (row.data.house.present) fire.homes += 1
+ else fire.buildings += 1
+ }
+ continue
+ }
+ data.burning.set({ ...b, left })
+ const tile = row.data.tile.get()
+ const neighbour = random.pick(rows.filter(({ entity: e, data: d }) => e.id !== entity.id && !d.burning.present && !ignited.has(e.id) && !lost.has(e.id) && near(d.tile.get(), tile, 1)))
+ if (!neighbour) continue
+ const chance = risk.fire.catches + (risk.fire.spread * neighbour.data.risk.get().fire) / RISK_MAX
+ if (random.next() < chance) {
+ commands.insert(neighbour.entity.id, Game.Command.entry(Burning, { left: risk.fire.burns, fire: b.fire }))
+ ignited.set(neighbour.entity.id, b.fire)
+ }
+ }
+
+ // Firefighters run from the nearest fire watch to every blaze no one is running to.
+ const out = new Map<number, number>()
+ const crewed = new Set<number>()
+ for (const { data } of queries.crews.each()) {
+ out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
+ if (!data.rescue.get().back) crewed.add(data.rescue.get().target as unknown as number)
+ }
+ const watches = queries.watches.each().filter(({ data }) => data.service.get().service === "fire" && data.staff.get().assigned > 0)
+ const burningNow = [...queries.blazes.each().map(({ entity }) => entity.id as number), ...ignited.keys()].filter((id) => !lost.has(id))
+ for (const id of burningNow) {
+ if (crewed.has(id)) continue
+ const target = byId.get(id)
+ if (!target) continue
+ const goal = doors(grid, target.data.tile.get())
+ let best: { readonly watch: (typeof watches)[number]; readonly roads: ReturnType<typeof reach>; readonly cell: Point; readonly distance: number } | null = null
+ for (const watch of watches) {
+ if ((out.get(watch.entity.id) ?? 0) >= risk.fire.crews) continue
+ const starts = doors(grid, watch.data.tile.get())
+ if (starts.length === 0) continue
+ const roads = reach(grid, starts)
+ const found = nearest(roads, goal)
+ if (found && (best === null || found.distance < best.distance)) best = { watch, roads, ...found }
+ }
+ if (!best) continue
+ const draft = Game.Command.spawn(
+ [Figure, { role: "walker", color: 0xc4523f }],
+ [Route, { cells: pathTo(best.roads, best.cell), index: 0, step: 0 }],
+ [Rescue, { target: Game.Entity.handle(target.entity.id, Tile), back: false }]
+ )
+ commands.spawn(Game.Command.relate(draft, WalkerOf, best.watch.entity.id))
+ out.set(best.watch.entity.id, (out.get(best.watch.entity.id) ?? 0) + 1)
+ }
+
+ // A fire with nothing left burning is over: the news says what it took.
+ const stillBurning = new Set<number>()
+ for (const { entity, data } of queries.blazes.each()) if (!lost.has(entity.id)) stillBurning.add(data.burning.get().fire)
+ for (const f of ignited.values()) stillBurning.add(f)
+ 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"}.`)
+ }
+ resources.fires.set({ fires: fires.fires.filter((f) => stillBurning.has(f.id)), next: fires.next })
+ resources.rng.set(random.state)
+ }
+)
+
+const BurningRead = Game.Query({ selection: { tile: Game.Query.read(Tile), burning: Game.Query.read(Burning), house: Game.Query.optional(House) } })
+
+/**
+ * A firefighter at the blaze puts it out: the house is lost, but the fire
+ * goes no further. Then the firefighter walks back to the watch.
+ */
+export const Douse = Game.System(
+ "Town/Douse",
+ {
+ queries: { crews: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.write(Rescue) } }) },
+ resources: { fires: Game.System.writeResource(Fires) }
+ },
+ ({ queries, resources, commands, lookup }) => {
+ for (const { entity, data } of queries.crews.each()) {
+ const route = data.route.get()
+ const rescue = data.rescue.get()
+ const arrived = route.index >= route.cells.length - 1
+ if (!arrived) continue
+ if (rescue.back) {
+ commands.despawn(entity.id)
+ continue
+ }
+ const target = lookup.getHandle(rescue.target, BurningRead)
+ if (target.ok) {
+ const b = target.value.data.burning.get()
+ commands.despawn(target.value.entity.id)
+ commands.spawn(ruinDraft(target.value.data.tile.get(), "burnt"))
+ const house = target.value.data.house.present
+ resources.fires.update((f) => ({
+ ...f,
+ fires: f.fires.map((x) => (x.id === b.fire ? { ...x, homes: x.homes + (house ? 1 : 0), buildings: x.buildings + (house ? 0 : 1) } : x))
+ }))
+ }
+ data.route.set({ cells: [...route.cells].reverse(), index: 0, step: 0 })
+ data.rescue.set({ ...rescue, back: true })
+ }
+ }
+)
diff --git a/src/sim/headless.ts b/src/sim/headless.ts
index 8a4a3d5..5b8999e 100644
--- a/src/sim/headless.ts
+++ b/src/sim/headless.ts
@@ -24,6 +24,7 @@ export const headless = (charter: CharterValue, options: { readonly toast?: (mes
tool: "select", placing: null, 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,
toast: options.toast ?? (() => {})
}
const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })
diff --git a/src/sim/index.ts b/src/sim/index.ts
index a09430a..f247873 100644
--- a/src/sim/index.ts
+++ b/src/sim/index.ts
@@ -6,6 +6,8 @@ import { amounts, defaultCharter } from "../content.ts"
import { Game, Time } from "../schema.ts"
import { ApplyEdits } from "./edits.ts"
import { Deliver, Dispatch } from "./logistics.ts"
+import { Decay } from "./decay.ts"
+import { Appraise, Douse, Hazards } from "./hazards.ts"
import { Approve, foundedFate, Judge, Record, Requests, Seasons } from "./term.ts"
import { Collect, Households, TakeCensus } from "./town.ts"
import { SendWalkers, Walk, Wander } from "./walkers.ts"
@@ -25,6 +27,7 @@ export const simulate = Game.Schedule(
ApplyEdits,
Game.Schedule.applyDeferred(),
IndexGrid,
+ Appraise,
Seasons,
Raise,
AssignStaff,
@@ -38,8 +41,13 @@ export const simulate = Game.Schedule(
Walk,
Deliver,
Wander,
+ Douse,
Game.Schedule.applyDeferred(),
Households,
+ Hazards,
+ Game.Schedule.applyDeferred(),
+ Decay,
+ Game.Schedule.applyDeferred(),
Collect,
CountStock,
TakeCensus,
@@ -55,9 +63,9 @@ export const blankResources = () => ({
Rng: 0x5eed,
Treasury: { coins: 0 },
Ledger: { taxes: 0, trade: 0, upkeep: 0, admin: 0 },
- Census: { homes: 0, settlers: 0, citizens: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0 },
+ Census: { homes: 0, settlers: 0, citizens: 0, burghers: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0, sick: 0, burning: 0 },
Policy: { settlers: 100, citizens: 100, sells: [], buys: [], reserve: 25 },
- Charter: { ...defaultCharter(0), founded: 0 },
+ 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 },
@@ -65,12 +73,15 @@ export const blankResources = () => ({
Fate: foundedFate(),
History: { samples: [] },
Chronicle: { lines: [] },
+ Appeal: { cells: [] },
+ Pantry: { eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 },
+ Fires: { fires: [], next: 1 },
Grid: { owner: [], use: [] },
Stock: amounts({})
})
-export { CELL_STEPS, elapsed, seasonAt, termTicks } from "./shared.ts"
+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, met, priceOf, satisfaction, taxOf } from "./town.ts"
+export { adminOf, askOf, capacity, kept, met, priceOf, satisfaction, taxOf, tierFor } from "./town.ts"
export { crownGap, goalsOf, larder } from "./term.ts"
diff --git a/src/sim/logistics.ts b/src/sim/logistics.ts
index b6d1155..24b5e1c 100644
--- a/src/sim/logistics.ts
+++ b/src/sim/logistics.ts
@@ -6,12 +6,13 @@
* storage sends what it holds to the nearest demands it can meet. Crates
* already on their way count against a demand, so no one is sent twice.
*/
-import { goods, goodIds, provisions, type GoodId } from "../content.ts"
+import { goods, goodIds, provisions, spoils, TOOL_STOCK, type GoodId } from "../content.ts"
import { doors, nearest, pathTo, reach, type Reach } from "../grid.ts"
import type { Point } from "../iso.ts"
import {
- Carriers, Errand, Figure, Game, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe
+ Building, Burning, Carriers, Errand, Figure, Game, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe
} from "../schema.ts"
+import { kinds } from "../content.ts"
import { CELL_STEPS } from "./shared.ts"
/** The most a carrier takes at once. */
@@ -28,20 +29,22 @@ export const Dispatch = Game.System(
tile: Game.Query.read(Tile),
inventory: Game.Query.write(Inventory),
carriers: Game.Query.read(Carriers),
+ building: Game.Query.optional(Building),
storage: Game.Query.optional(Storage),
recipe: Game.Query.optional(Recipe)
},
- without: [Site, Rising]
+ without: [Site, Rising, Burning]
}),
wanting: Game.Query({
selection: {
tile: Game.Query.read(Tile),
+ building: Game.Query.optional(Building),
inventory: Game.Query.optional(Inventory),
recipe: Game.Query.optional(Recipe),
service: Game.Query.optional(Service),
storage: Game.Query.optional(Storage)
},
- without: [Site, Rising]
+ without: [Site, Rising, Burning]
}),
sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),
errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
@@ -76,21 +79,29 @@ export const Dispatch = Game.System(
const ds = doors(grid, data.tile.get())
for (const g of goodIds) if (site.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => site.owed[g] - inbound(entity.id, g) })
}
- const rooms: Array<{ readonly id: Id; readonly doors: ReadonlyArray<Point>; readonly room: (g: GoodId) => number }> = []
+ const sitesWant = new Set(wants.filter((w) => w.want() > 0).map((w) => w.good))
+ const rooms: Array<{ readonly id: Id; readonly doors: ReadonlyArray<Point>; readonly room: (g: GoodId) => number; readonly keeps: boolean }> = []
for (const { entity, data } of queries.wanting.each()) {
const inventory = maybe(data.inventory)
if (!inventory) continue
const ds = doors(grid, data.tile.get())
if (ds.length === 0) continue
const recipe = maybe(data.recipe)
- const space = (g: GoodId) => inventory.cap - inventory.stock[g] - inbound(entity.id, g)
- if (data.storage.present) rooms.push({ id: entity.id, doors: ds, room: space })
- else if (recipe && recipe.input !== null) {
+ const space = (g: GoodId) => (inventory.accepts.includes(g) ? inventory.cap - inventory.stock[g] - inbound(entity.id, g) : 0)
+ const kind = maybe(data.building)?.kind
+ if (data.storage.present) {
+ rooms.push({ id: entity.id, doors: ds, room: space, keeps: kind !== undefined && (kinds[kind].keeps ?? 0) > 1 })
+ continue
+ }
+ if (recipe && recipe.input !== null) {
const g = recipe.input
wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
- } else if (maybe(data.service)?.service === "goods") {
- for (const g of provisions) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
}
+ // A workshop that wears out tools keeps a couple on hand.
+ if (kind !== undefined && kinds[kind].wear) wants.push({ id: entity.id, doors: ds, good: "tools", site: false, want: () => TOOL_STOCK - inventory.stock.tools - inbound(entity.id, "tools") })
+ const service = maybe(data.service)?.service
+ if (service === "goods") for (const g of provisions) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
+ if (service === "repair") for (const g of ["planks", "stone"] as const) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
}
const send = (from: { readonly id: Id; readonly roads: Reach }, to: { readonly id: Id; readonly cell: Point }, good: GoodId, count: number) => {
@@ -117,7 +128,10 @@ export const Dispatch = Game.System(
// A storage meets demands with what it holds; anyone else sends on what it made.
// A producer waits for a full load (or a full shelf) so its carriers do not walk with one crate.
const ready = recipe ? stock[recipe.output] >= Math.min(LOAD, inventory.cap - recipe.batch) : false
- const offers: ReadonlyArray<GoodId> = data.storage.present ? goodIds.filter((g) => stock[g] > 0) : recipe && ready ? [recipe.output] : []
+ // What sites are waiting for goes first: otherwise steady demand for one good keeps every carrier busy.
+ const offers: ReadonlyArray<GoodId> = data.storage.present
+ ? goodIds.filter((g) => stock[g] > 0).sort((a, b) => Number(!sitesWant.has(a)) - Number(!sitesWant.has(b)))
+ : recipe && ready ? [recipe.output] : []
for (const good of offers) {
if ((out.get(entity.id) ?? 0) >= carriers) break
let best: { readonly id: Id; readonly cell: Point; readonly distance: number; readonly count: number; readonly site: boolean } | null = null
@@ -129,13 +143,22 @@ export const Dispatch = Game.System(
// Sites come first, then whoever is nearest.
if (found && (best === null || (w.site && !best.site) || (w.site === best.site && found.distance < best.distance))) best = { id: w.id, ...found, count, site: w.site }
}
- if (best === null && !data.storage.present) {
+ // Food that spoils goes to a granary if there is one in reach, before the nearest storage; a
+ // storage that does not keep food sends it on to a granary that does.
+ const perishable = spoils[good] !== undefined
+ const senderKeeps = (kinds[maybe(data.building)?.kind ?? "townhall"].keeps ?? 0) > 1
+ if (best === null && (!data.storage.present || (perishable && !senderKeeps))) {
+ let kept = false
for (const r of rooms) {
- if (r.id === entity.id) continue
+ if (r.id === entity.id || (data.storage.present && !r.keeps)) continue
const count = Math.min(LOAD, stock[good], r.room(good))
if (count <= 0) continue
const found = nearest(roads, r.doors)
- if (found && (best === null || found.distance < best.distance)) best = { id: r.id, ...found, count, site: false }
+ const keeps = perishable && r.keeps
+ if (found && (best === null || (keeps && !kept) || (keeps === kept && found.distance < best.distance))) {
+ best = { id: r.id, ...found, count, site: false }
+ kept = keeps
+ }
}
}
if (best === null) continue
diff --git a/src/sim/shared.ts b/src/sim/shared.ts
index 36933a6..ce1cf2e 100644
--- a/src/sim/shared.ts
+++ b/src/sim/shared.ts
@@ -1,7 +1,7 @@
/** Queries and small helpers the simulation's systems share. */
-import { ticks, WINTER_SHARE, YEARS_PER_TERM } from "../content.ts"
+import { ticks, winters, YEARS_PER_TERM, type WinterId } from "../content.ts"
import { doors, type TileLike, type Use } from "../grid.ts"
-import { Field, Game, House, Road, Rock, Tile, Tree, Water, type GridValue } from "../schema.ts"
+import { Field, Game, House, Road, Rock, Ruin, Tile, Tree, Water, type GridValue } from "../schema.ts"
/** Every tile, with enough to tell what it is. */
export const TileRead = Game.Query({
@@ -12,7 +12,8 @@ export const TileRead = Game.Query({
tree: Game.Query.optional(Tree),
rock: Game.Query.optional(Rock),
water: Game.Query.optional(Water),
- field: Game.Query.optional(Field)
+ field: Game.Query.optional(Field),
+ ruin: Game.Query.optional(Ruin)
}
})
@@ -23,6 +24,7 @@ export const useOf = (data: {
readonly rock: { readonly present: boolean }
readonly water: { readonly present: boolean }
readonly field: { readonly present: boolean }
+ readonly ruin: { readonly present: boolean }
}): Use =>
data.road.present ? "road"
: data.house.present ? "house"
@@ -30,6 +32,7 @@ export const useOf = (data: {
: data.rock.present ? "rock"
: data.water.present ? "water"
: data.field.present ? "field"
+ : data.ruin.present ? "ruin"
: "building"
export const connected = (grid: GridValue, tile: TileLike): boolean => doors(grid, tile).length > 0
@@ -44,18 +47,66 @@ export const elapsed = (time: { readonly tick: number }, charter: { readonly fou
export const termTicks = (charter: { readonly term: number }) => ticks(charter.term * 60)
export const yearTicks = (charter: { readonly term: number }) => Math.round(termTicks(charter) / YEARS_PER_TERM)
+/** A charter's winters: the first year has none. */
+export type Almanac = ReadonlyArray<WinterId | "none">
+interface Seasoned {
+ readonly term: number
+ readonly winters?: Almanac
+}
+
+/** The winter that ends year `year` (from 1), or `null` for none: the first year's, and any past the term. */
+export const winterOf = (charter: Seasoned, year: number): WinterId | null => {
+ if (year <= 1 || year > YEARS_PER_TERM) return null
+ const w = charter.winters?.[year - 1]
+ return w === undefined ? "normal" : w === "none" ? null : w
+}
+
+/** Rolls each year's winter from a random number in 0 → 1 a year (the first year's is spared). */
+export const rollWinters = (next: () => number): Array<WinterId | "none"> =>
+ Array.from({ length: YEARS_PER_TERM }, (_, i) => {
+ if (i === 0) return "none"
+ const r = next()
+ return r < winters.mild.chance ? "mild" : r < winters.mild.chance + winters.normal.chance ? "normal" : "hard"
+ })
+
/**
- * The season `t` steps into a term: which year, whether it is winter, and
- * how long until that changes. The first year is spared its winter: a new
- * town has a year to find its feet.
+ * The season `t` steps into a term: which year, whether it is winter (and
+ * which), how long until that changes, and the next winter the almanac
+ * foresees. The first year is spared its winter: a new town has a year to
+ * find its feet. A hard winter starts earlier in its year and lasts half
+ * as long again.
*/
-export const seasonAt = (t: number, charter: { readonly term: number }) => {
+export const seasonAt = (t: number, charter: Seasoned) => {
const year = yearTicks(charter)
const into = t % year
- const thaw = Math.round(year * (1 - WINTER_SHARE))
const number = Math.floor(t / year) + 1
- const winter = number > 1 && into >= thaw
- const left = winter ? year - into : number === 1 ? year + thaw - into : into >= thaw ? year + thaw - into : thaw - into
- return { year: number, winter, left }
+ const thawOf = (n: number) => {
+ const w = winterOf(charter, n)
+ return w === null ? year : Math.round(year * (1 - winters[w].share))
+ }
+ const thaw = thawOf(number)
+ const winter = into >= thaw
+ // The next winter to come: this year's, if it is still ahead, or the next's.
+ const ahead = !winter && winterOf(charter, number) !== null ? number : number + 1
+ const left = winter ? year - into : ahead === number ? thaw - into : year - into + thawOf(number + 1)
+ return {
+ year: number,
+ winter,
+ /** This winter's severity, while it lasts. */
+ severity: winter ? winterOf(charter, number) : null,
+ /** The coming winter's severity, or `null` when the term ends first. */
+ coming: winterOf(charter, ahead),
+ left
+ }
}
+// ── 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. */
+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) }))
diff --git a/src/sim/term.ts b/src/sim/term.ts
index 6ff1377..62c5864 100644
--- a/src/sim/term.ts
+++ b/src/sim/term.ts
@@ -4,39 +4,59 @@
* and the term ends: complete, lost, or run out.
*/
import {
- crown, fate, goods, HISTORY_TICKS, mood, sizes, ticks, type GoodId
+ crown, fate, goods, HISTORY_TICKS, mood, sizes, spoils, ticks, WINTER_WARNING, winters, type GoodId
} from "../content.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
import {
- Building, Census, Charter, Chronicle, Crown, Fate, Game, History, House, Inventory, Ledger, Mood, Policy, Recipe, Rising, Rng, Site,
- Storage, Time, Treasury
+ Building, Census, Charter, Chronicle, Crown, Fate, Game, History, House, Inventory, Ledger, Mood, Pantry, Policy, Recipe, Rising, Rng, Site,
+ Stock, Storage, Time, Treasury
} from "../schema.ts"
-import { elapsed, seasonAt, termTicks } from "./shared.ts"
+import { elapsed, seasonAt, termTicks, write } from "./shared.ts"
import { satisfaction } from "./town.ts"
// ── Time ──────────────────────────────────────────────────────────────────
-/** A line in the chronicle. */
-const write = (chronicle: { update: (f: (c: { readonly lines: ReadonlyArray<{ tick: number; text: string }> }) => { lines: ReadonlyArray<{ tick: number; text: string }> }) => void }, tick: number, text: string) =>
- chronicle.update((c) => ({ lines: [...c.lines, { tick, text }].slice(-200) }))
-
-/** Winter comes and goes, and the chronicle says so. */
+/**
+ * Winter comes and goes, and the chronicle says so. A minute before it
+ * comes, the almanac warns the town how hard it will be, and how long the
+ * food in store would last.
+ */
export const Seasons = Game.System(
"Town/Seasons",
{
resources: {
time: Game.System.readResource(Time),
charter: Game.System.readResource(Charter),
+ stock: Game.System.readResource(Stock),
+ pantry: Game.System.readResource(Pantry),
chronicle: Game.System.writeResource(Chronicle)
}
},
({ resources }) => {
- const t = elapsed(resources.time.get(), resources.charter.get())
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
if (t <= 0) return
- const now = seasonAt(t, resources.charter.get())
- const before = seasonAt(t - 1, resources.charter.get())
- if (now.winter && !before.winter) write(resources.chronicle, t, `Winter of year ${now.year}: the fields lie still and the fish are few.`)
+ const now = seasonAt(t, charter)
+ const before = seasonAt(t - 1, charter)
+ if (now.winter && !before.winter) {
+ const w = now.severity ?? "normal"
+ write(
+ resources.chronicle,
+ t,
+ `A ${winters[w].title} winter, year ${now.year}: the fields lie still and fisheries catch ${Math.round(winters[w].fishing * 100)}%${winters[w].heating ? "; homes burn fires to keep warm" : ""}.`
+ )
+ }
if (!now.winter && before.winter) write(resources.chronicle, t, `Spring of year ${now.year}.`)
+ if (!now.winter && now.coming !== null && now.left === WINTER_WARNING) {
+ const w = winters[now.coming]
+ const eats = resources.pantry.get().eatenLast
+ write(
+ resources.chronicle,
+ t,
+ `Winter in a minute, and the almanac says it will be ${w.title}: ${larder(resources.stock.get())} food in store; the town eats ${eats} a minute.`,
+ true
+ )
+ }
}
)
@@ -46,7 +66,8 @@ export const Seasons = Game.System(
export const crownGap = (charter: { readonly term: number }) => Math.round(termTicks(charter) / (crown.perTerm + 1))
/**
- * Every so often the crown asks for something the town makes: a share of
+ * Every so often the crown asks for something the town makes, and that
+ * keeps (never fish or bread): a share of
* what its workshops and gatherers could make in the time given, larger the
* later in the term it is. A request not sent in time is a fine and a snub
* the town's approval remembers.
@@ -80,7 +101,7 @@ export const Requests = Game.System(
const fine = Math.round(((c.reward - crown.bonus) / crown.reward) * crown.fine) + crown.bonus
resources.treasury.update((tr) => ({ coins: tr.coins - fine }))
resources.crown.set({ ...c, open: false, missed: c.missed + 1, streak: c.streak + 1, snubs: [...remembered, t] })
- write(resources.chronicle, t, `The crown's request for ${c.amount} ${goods[c.good].title} went unanswered: a fine of ${fine} coins.`)
+ write(resources.chronicle, t, `The crown's request for ${c.amount} ${goods[c.good].title} went unanswered: a fine of ${fine} coins.`, true)
return
}
if (c.open || t < c.next) return
@@ -92,7 +113,8 @@ export const Requests = Game.System(
const r = data.recipe.get()
rates.set(r.output, (rates.get(r.output) ?? 0) + (r.batch * 3600) / r.period)
}
- const options = [...rates.keys()].sort()
+ // Only what keeps: fish and bread would rot on the way.
+ const options = [...rates.keys()].filter((g) => spoils[g] === undefined).sort()
if (options.length === 0) return
const random = Random.make(resources.rng.get())
const good = random.pick(options)!
@@ -107,7 +129,7 @@ export const Requests = Game.System(
const gap = crownGap(charter)
const due = t + Math.round(gap * crown.window)
resources.crown.set({ ...c, snubs: remembered, open: true, good, amount, issued: t, due, reward, next: t + gap })
- write(resources.chronicle, t, `The crown asks for ${amount} ${goods[good].title} within ${Math.round(((due - t) / 3600) * 10) / 10} minutes, for ${reward} coins.`)
+ write(resources.chronicle, t, `The crown asks for ${amount} ${goods[good].title} within ${Math.round(((due - t) / 3600) * 10) / 10} minutes, for ${reward} coins.`, true)
}
)
@@ -180,7 +202,7 @@ export const foundedFate = () => ({
})
/** Food in storage: what would carry the town through a winter. */
-export const larder = (stock: { readonly fish: number; readonly bread: number }) => stock.fish + stock.bread
+export const larder = (stock: { readonly fish: number; readonly smoked: number; readonly bread: number }) => stock.fish + stock.smoked + stock.bread
/** Each goal the town must hold to be complete, met or not. */
export const goalsOf = (
@@ -236,7 +258,7 @@ export const Judge = Game.System(
const crownNow = resources.crown.get()
const residents = census.settlers + census.citizens
const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
- const note = (text: string) => write(resources.chronicle, t, text)
+ 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) - t) / 3600))
const score = (won: boolean) => scoreOf({ ...census, coins, approval, met: crownNow.met, missed: crownNow.missed }, won, left)
@@ -246,11 +268,11 @@ export const Judge = Game.System(
// Dangers.
if (coins < 0) {
- if (f.debtSince < 0) note("The treasury is empty: wages go unpaid.")
+ if (f.debtSince < 0) note("The treasury is empty: wages go unpaid.", true)
next.debtSince = f.debtSince < 0 ? t : f.debtSince
} else next.debtSince = -1
if (approval <= fate.revoltAt) {
- if (f.revoltSince < 0) note("The town is in uproar.")
+ if (f.revoltSince < 0) note("The town is in uproar.", true)
next.revoltSince = f.revoltSince < 0 ? t : f.revoltSince
} else next.revoltSince = -1
diff --git a/src/sim/town.ts b/src/sim/town.ts
index bdd8205..2bb66ea 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -3,11 +3,14 @@
* taxes are collected from homes connected to the town hall and upkeep paid
* for every standing building; and the census counts it all.
*/
-import { admin, goodIds, goods, home, kinds, LEDGER_TICKS, market, PAUSED_UPKEEP, TRADE_LOAD, type GoodId, type Need, type Tier } from "../content.ts"
+import { appealAt } from "../appeal.ts"
+import {
+ admin, goodIds, goods, home, kinds, LEDGER_TICKS, market, PAUSED_UPKEEP, risk, TRADE_LOAD, type GoodId, type Need, type Tier
+} from "../content.ts"
import { doors, key, reach } from "../grid.ts"
import {
- Building, Census, Charter, Game, Grid, House, Inventory, Ledger, Market, Mood, Paused, Policy, Rising, Site, Staff, Storage, Tile, Time,
- TownHall, Treasury
+ Appeal, Building, Burning, Census, Charter, Game, Grid, House, Inventory, Ledger, Market, Mood, Paused, Policy, Rising, Risk, Sick, Site,
+ Staff, Storage, Tile, Time, TownHall, Treasury, maybe
} from "../schema.ts"
import { connected, elapsed, seasonAt } from "./shared.ts"
@@ -39,11 +42,33 @@ export const appealOf = (approval: number): number => (approval < 0 ? 1 + approv
/**
* 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.
+ * mayor, and up to all of them when it approves, needs or not. Nobody
+ * wants to live where it is squalid (desirability `home.squalid` or less):
+ * such a home holds fewer.
*/
-export const capacity = (h: Needs, approval: number): number => {
+export const capacity = (h: Needs, approval: number, desirability = 0): number => {
const max = home.tiers[h.tier].residents
- return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h)) * appealOf(approval))))
+ const squalor = desirability <= home.squalid ? home.crowded : 1
+ return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h)) * appealOf(approval) * squalor)))
+}
+
+/** Whether every risk meter of a home is kept low: a service walker of each kind passes it. */
+export const kept = (r: { readonly fire: number; readonly health: number; readonly order: number }) =>
+ r.fire < risk.kept && r.health < risk.kept && r.order < risk.kept
+
+/**
+ * The tier a home settles into: settlers whose every citizens' need is met,
+ * on a street desirable enough, become citizens; citizens with a street
+ * nicer still and all three services calling become burghers in a
+ * townhouse. A home that loses more than one of its needs, or whose street
+ * falls below its tier, steps back down.
+ */
+export const tierFor = (h: Needs, desirability: number, r: { readonly fire: number; readonly health: number; readonly order: number }): Tier => {
+ const fits = (tier: Tier) => desirability >= home.tiers[tier].appeal
+ if (h.tier === 1) return satisfaction(h, 2) === 1 && fits(2) ? 2 : 1
+ if (satisfaction(h) < 2 / 3 || !fits(2)) return 1
+ if (h.tier === 2) return satisfaction(h, 3) === 1 && fits(3) && kept(r) ? 3 : 2
+ return fits(3) && kept(r) ? 3 : 2
}
/** Coins a minute the town hall's administration costs for `homes` homes. */
@@ -58,19 +83,30 @@ export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates):
h.residents * home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h))
/**
- * Needs wear off, food faster in winter. Every so often a home settles:
- * settlers whose every citizens' need is met become citizens; citizens
- * missing more than one need go back to being settlers. One resident moves
- * in or out towards what the home holds; everyone leaves a home with no
- * road.
+ * Needs wear off, food faster in winter. Every so often a home settles
+ * into its tier (see `tierFor`) and one resident moves in or out towards
+ * what the home holds (half as many while it is sick). Everyone leaves a
+ * home with no road, or on fire.
*/
export const Households = Game.System(
"Town/Households",
{
- queries: { homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.write(House) }, without: [Site, Rising] }) },
+ queries: {
+ homes: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ house: Game.Query.write(House),
+ risk: Game.Query.optional(Risk),
+ sick: Game.Query.optional(Sick),
+ burning: Game.Query.optional(Burning)
+ },
+ without: [Site, Rising]
+ })
+ },
resources: {
grid: Game.System.readResource(Grid),
mood: Game.System.readResource(Mood),
+ appeal: Game.System.readResource(Appeal),
time: Game.System.readResource(Time),
charter: Game.System.readResource(Charter)
}
@@ -78,6 +114,7 @@ export const Households = Game.System(
({ queries, resources }) => {
const grid = resources.grid.get()
const approval = resources.mood.get().approval
+ const cells = resources.appeal.get().cells
const t = elapsed(resources.time.get(), resources.charter.get())
// In winter a meal lasts two thirds as long.
const eat = seasonAt(t, resources.charter.get()).winter && t % 2 === 0 ? 2 : 1
@@ -91,10 +128,14 @@ export const Households = Game.System(
cloth: Math.max(0, h.cloth - 1),
faith: Math.max(0, h.faith - 1)
}
- if (next.clock % home.settle === 0) {
- if (next.tier === 1 && satisfaction(next, 2) === 1) next.tier = 2
- else if (next.tier === 2 && satisfaction(next) < 2 / 3) next.tier = 1
- const cap = connected(grid, data.tile.get()) ? capacity(next, approval) : 0
+ if (data.burning.present) next.residents = 0
+ else if (next.clock % home.settle === 0) {
+ const tile = data.tile.get()
+ const desirability = appealAt(cells, tile.x, tile.y)
+ next.tier = tierFor(next, desirability, maybe(data.risk) ?? { fire: 0, health: 0, order: 0 })
+ const well = connected(grid, tile) ? capacity(next, approval, desirability) : 0
+ const cap = data.sick.present ? Math.floor(well * risk.health.sickly) : well
+ next.residents = Math.min(next.residents, home.tiers[next.tier].residents)
next.residents += Math.sign(cap - next.residents)
}
data.house.set(next)
@@ -179,7 +220,7 @@ export const Collect = Game.System(
for (const { data } of [...stores].sort((a, b) => a.data.inventory.get().stock[good] - b.data.inventory.get().stock[good])) {
if (wanted <= 0) break
const inv = data.inventory.get()
- const put = Math.min(wanted, inv.cap - inv.stock[good])
+ const put = inv.accepts.includes(good) ? Math.min(wanted, inv.cap - inv.stock[good]) : 0
if (put <= 0) continue
data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] + put } })
wanted -= put
@@ -205,8 +246,9 @@ export const TakeCensus = Game.System(
"Town/TakeCensus",
{
queries: {
- homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }),
- workplaces: Game.Query({ selection: { staff: Game.Query.read(Staff) }, without: [Site, Rising] })
+ homes: Game.Query({ selection: { house: Game.Query.read(House), sick: Game.Query.optional(Sick) }, without: [Site, Rising] }),
+ workplaces: Game.Query({ selection: { staff: Game.Query.read(Staff) }, without: [Site, Rising] }),
+ burning: Game.Query({ selection: { burning: Game.Query.read(Burning) } })
},
resources: { census: Game.System.writeResource(Census) }
},
@@ -214,12 +256,16 @@ export const TakeCensus = Game.System(
let homes = 0
let settlers = 0
let citizens = 0
+ let burghers = 0
+ let sick = 0
const needs = { food: 0, bread: 0, cloth: 0, faith: 0 }
for (const { data } of queries.homes.each()) {
const h = data.house.get()
homes += 1
if (h.tier === 1) settlers += h.residents
else citizens += h.residents
+ if (h.tier === 3) burghers += h.residents
+ if (data.sick.present) sick += 1
for (const n of ["food", "bread", "cloth", "faith"] as const) if (met(h, n)) needs[n] += 1
}
let jobs = 0
@@ -229,6 +275,6 @@ export const TakeCensus = Game.System(
jobs += s.needed
employed += s.assigned
}
- resources.census.set({ homes, settlers, citizens, jobs, employed, ...needs })
+ resources.census.set({ homes, settlers, citizens, burghers, jobs, employed, ...needs, sick, burning: queries.burning.each().length })
}
)
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
index 3bc33f1..187f9b9 100644
--- a/src/sim/walkers.ts
+++ b/src/sim/walkers.ts
@@ -2,31 +2,38 @@
* Walking: every walker steps along its route; service buildings send a
* walker out now and then, who wanders the roads serving the homes beside
* it — a market's (or the town hall's) with a basket of provisions, a
- * chapel's with faith — and walks home when its range is walked.
+ * chapel's with faith, a fire watch's, a healer's, and a watch house's
+ * keeping down the risk of fire, sickness, and disorder, a builder's with
+ * planks and stone to mend — and walks home when its range is walked.
*/
import * as Random from "@typeonce/bevy-ts-math/Random"
-import { amounts, categoryColor, each, home, kinds, provisions, total, type Amounts, type Need } from "../content.ts"
-import { DIRS, doors, isRoad, key, nearest, pathTo, reach } from "../grid.ts"
+import {
+ amounts, APPRENTICE, categoryColor, condition as wear, CONDITION_MAX, each, home, kinds, provisions, total, type Amounts, type Need
+} from "../content.ts"
+import { DIRS, doors, isRoad, key, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"
import { inside, type Point } from "../iso.ts"
import {
- Building, Figure, Game, Grid, House, Inventory, Paused, Recipe, Rising, Rng, Roam, Route, Service, Site, Staff, Status, Tile, WalkerOf,
- maybe, type Status as StatusValue
+ Building, Burning, Condition, Figure, Game, Grid, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Rng, Roam, Route, Service, Sick,
+ Site, Staff, Status, Tile, Time, WalkerOf, maybe, type Status as StatusValue
} from "../schema.ts"
import { CELL_STEPS } from "./shared.ts"
+import { paced } from "./work.ts"
/** Steps a walker takes each tick: 1.25 cells a second. */
const WALK = 1
+/** Firefighters run to a blaze. */
+const RUN = 3
/** Of each provision, the most a walker's basket holds. */
const BASKET = 10
/** Walkers a service building may have out on the roads at once. */
const OUT = 2
-/** Every walker steps along its route; 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); 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) } }) },
+ queries: { walkers: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.optional(Rescue) } }) },
resources: { grid: Game.System.readResource(Grid) }
},
({ queries, resources, commands }) => {
@@ -40,7 +47,8 @@ export const Walk = Game.System(
commands.despawn(entity.id)
continue
}
- const step = route.step + WALK
+ const running = data.rescue.present && !data.rescue.get().back
+ const step = route.step + (running ? RUN : WALK)
if (step < CELL_STEPS) data.route.set({ ...route, step })
else {
const index = route.index + 1
@@ -70,15 +78,16 @@ export const SendWalkers = Game.System(
recipe: Game.Query.optional(Recipe),
paused: Game.Query.optional(Paused)
},
- without: [Site, Rising]
+ without: [Site, Rising, Burning]
}),
inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] }),
walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })
},
- resources: { grid: Game.System.readResource(Grid) }
+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }
},
({ queries, resources, commands }) => {
const grid = resources.grid.get()
+ const tick = resources.time.get().tick
const out = new Map<number, number>()
for (const { data } of queries.walkers.each()) out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
@@ -88,8 +97,10 @@ export const SendWalkers = Game.System(
const starts = doors(grid, data.tile.get())
const stock = maybe(data.inventory)?.stock
const staffed = !data.paused.present && (staff.needed === 0 || staff.assigned > 0)
- const basket: Amounts = each((g) => (service.service === "goods" && stock && provisions.includes(g) ? Math.min(BASKET, stock[g]) : 0))
- const goes = service.service === "faith" || total(basket) > 0
+ const carries = (g: (typeof provisions)[number]) =>
+ service.service === "goods" ? provisions.includes(g) : service.service === "repair" ? g === "planks" || g === "stone" : false
+ const basket: Amounts = each((g) => (stock && carries(g) ? Math.min(BASKET, stock[g]) : 0))
+ const goes = service.service === "goods" ? total(basket) > 0 : service.service === "repair" ? basket.planks > 0 : true
if (!maybe(data.recipe)) {
const status: StatusValue = data.paused.present
? "paused"
@@ -105,7 +116,9 @@ export const SendWalkers = Game.System(
if (data.status.get() !== status) data.status.set(status)
}
- const cooldown = Math.max(0, service.cooldown - 1)
+ // A crew of apprentices sends walkers less often.
+ const learning = staff.assigned > 0 && staff.assigned === staff.apprentices && !paced(APPRENTICE, tick)
+ const cooldown = learning ? service.cooldown : Math.max(0, service.cooldown - 1)
if (cooldown === 0 && (out.get(entity.id) ?? 0) < OUT && starts.length > 0 && staffed && goes) {
const color = categoryColor[kinds[data.building.get().kind].category]
const draft = Game.Command.spawn(
@@ -128,37 +141,48 @@ export const SendWalkers = Game.System(
const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
/**
- * A service walker wanders: at each cell it serves the homes beside it, then
- * picks a road onward at random (never straight back, unless it must). Once
- * its range is walked, or its basket is empty, it heads home by the shortest
- * road, and puts back what it still carries.
+ * A service walker wanders: at each cell it serves the homes (and, for a
+ * fire watch or a builder, the buildings) beside it, then picks a road
+ * onward at random (never straight back, unless it must). Once its range is
+ * walked, or its basket is empty, it heads home by the shortest road, and
+ * puts back what it still carries.
*
- * A home low on a need takes what meets it: bread or else fish for food
- * (bread meets the citizens' bread need too), cloth for cloth; a chapel's
- * walker brings faith.
+ * A home low on a need takes what meets it: bread or else fish (fresh
+ * first, then smoked) for food (bread meets the citizens' bread need too),
+ * cloth for cloth; a chapel's walker brings faith. A watchman, a physician,
+ * and a constable reset the risk they look after (a physician cures the
+ * sick; a constable's visit is the end of a home's thefts); a builder mends
+ * whatever is run down, a plank for a home, a plank and a stone for a
+ * building.
*/
export const Wander = Game.System(
"Town/Wander",
{
queries: {
walkers: Game.Query({ selection: { route: Game.Query.write(Route), roam: Game.Query.write(Roam), home: Game.Query.readRelation(WalkerOf) } }),
- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.write(House) }, without: [Site, Rising] }),
+ homes: Game.Query({ selection: { house: Game.Query.write(House) }, without: [Site, Rising] }),
+ cared: Game.Query({
+ selection: { risk: Game.Query.write(Risk), condition: Game.Query.write(Condition), sick: Game.Query.optional(Sick) },
+ without: [Site, Rising]
+ }),
buildings: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Service] }),
inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })
},
- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng) }
+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), pantry: Game.System.writeResource(Pantry) }
},
({ queries, resources, commands }) => {
const grid = resources.grid.get()
const random = Random.make(resources.rng.get())
+ const walkers = queries.walkers.each()
+ if (!walkers.some(({ data }) => arrived(data.route.get()))) return
const homes = new Map<number, ReturnType<typeof queries.homes.each>[number]>()
- for (const row of queries.homes.each()) {
- const t = row.data.tile.get()
- homes.set(key(t.x, t.y), row)
- }
+ for (const row of queries.homes.each()) homes.set(row.entity.id, row)
+ const cared = new Map<number, ReturnType<typeof queries.cared.each>[number]>()
+ for (const row of queries.cared.each()) cared.set(row.entity.id, row)
const low = (left: number, need: Need) => left < home.lasts[need] / 2
+ let eaten = 0
- for (const { entity, data } of queries.walkers.each()) {
+ for (const { entity, data } of walkers) {
const route = data.route.get()
if (!arrived(route)) continue
const roam = data.roam.get()
@@ -174,35 +198,65 @@ export const Wander = Game.System(
continue
}
- // Serve the homes beside this cell.
+ // Serve the homes (and buildings) beside this cell.
const cell = route.cells[route.cells.length - 1]!
const basket: Record<string, number> = { ...roam.basket }
+ const served = new Set<number>()
for (const d of DIRS) {
const x = cell.x + d.x
const y = cell.y + d.y
- const row = inside(x, y) ? homes.get(key(x, y)) : undefined
- if (!row) continue
- const h = { ...row.data.house.get() }
- if (roam.service === "faith") h.faith = home.lasts.faith
- else {
- if ((low(h.food, "food") || (h.tier === 2 && low(h.bread, "bread"))) && (basket.bread ?? 0) > 0) {
- basket.bread = (basket.bread ?? 0) - 1
- h.food = home.lasts.food
- h.bread = home.lasts.bread
- } else if (low(h.food, "food") && (basket.fish ?? 0) > 0) {
- basket.fish = (basket.fish ?? 0) - 1
- h.food = home.lasts.food
+ if (!inside(x, y)) continue
+ const use = useAt(grid, x, y)
+ if (use !== "house" && use !== "building") continue
+ const id = ownerAt(grid, x, y)
+ if (served.has(id)) continue
+ served.add(id)
+ const row = use === "house" ? homes.get(id) : undefined
+ const care = cared.get(id)
+ if (row) {
+ const h = { ...row.data.house.get() }
+ if (roam.service === "faith") h.faith = home.lasts.faith
+ else if (roam.service === "goods") {
+ if ((low(h.food, "food") || (h.tier >= 2 && low(h.bread, "bread"))) && (basket.bread ?? 0) > 0) {
+ basket.bread = (basket.bread ?? 0) - 1
+ h.food = home.lasts.food
+ h.bread = home.lasts.bread
+ eaten += 1
+ } else if (low(h.food, "food") && ((basket.fish ?? 0) > 0 || (basket.smoked ?? 0) > 0)) {
+ const g = (basket.fish ?? 0) > 0 ? "fish" : "smoked"
+ basket[g] = (basket[g] ?? 0) - 1
+ h.food = home.lasts.food
+ eaten += 1
+ }
+ if (low(h.cloth, "cloth") && (basket.cloth ?? 0) > 0) {
+ basket.cloth = (basket.cloth ?? 0) - 1
+ h.cloth = home.lasts.cloth
+ }
}
- if (low(h.cloth, "cloth") && (basket.cloth ?? 0) > 0) {
- basket.cloth = (basket.cloth ?? 0) - 1
- h.cloth = home.lasts.cloth
+ row.data.house.set(h)
+ }
+ if (!care) continue
+ const r = care.data.risk.get()
+ if (roam.service === "fire" && r.fire > 0) care.data.risk.set({ ...r, fire: 0 })
+ if (row && roam.service === "health") {
+ if (r.health > 0) care.data.risk.set({ ...r, health: 0 })
+ if (care.data.sick.present) commands.remove(care.entity.id, Sick)
+ }
+ if (row && roam.service === "order" && (r.order > 0 || r.thefts > 0)) care.data.risk.set({ ...r, order: 0, thefts: 0 })
+ if (roam.service === "repair") {
+ const c = care.data.condition.get().value
+ if (c < wear.mend && (basket.planks ?? 0) > 0) {
+ basket.planks = (basket.planks ?? 0) - 1
+ const stone = !row && (basket.stone ?? 0) > 0
+ if (stone) basket.stone = (basket.stone ?? 0) - 1
+ care.data.condition.set({ value: row || stone ? CONDITION_MAX : Math.min(CONDITION_MAX, c + 300) })
}
}
- row.data.house.set(h)
}
const left = roam.left - 1
const carrying = amounts(basket)
- if (left > 0 && (roam.service !== "goods" || total(carrying) > 0)) {
+ const keepsGoing = roam.service === "goods" ? total(carrying) > 0 : roam.service === "repair" ? carrying.planks > 0 : true
+ if (left > 0 && keepsGoing) {
const previous = route.cells.length >= 2 ? route.cells[route.cells.length - 2]! : null
const onward = DIRS
.map((d) => ({ x: cell.x + d.x, y: cell.y + d.y }))
@@ -227,5 +281,6 @@ export const Wander = Game.System(
data.roam.set({ ...roam, left: 0, basket: carrying, back: true })
}
resources.rng.set(random.state)
+ if (eaten > 0) resources.pantry.update((p) => ({ ...p, eaten: p.eaten + eaten }))
}
)
diff --git a/src/sim/work.ts b/src/sim/work.ts
index 6d9e39b..7cf15be 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -7,14 +7,23 @@
import * as Random from "@typeonce/bevy-ts-math/Random"
import { fieldDraft, treeDraft } from "../archetypes.ts"
-import { amounts, BUILD_TICKS, goodIds, GROWN, ticks, total, type Amounts } from "../content.ts"
-import { around, DIRS, GridBuilder, key, ownerAt, roadPrint, useAt } from "../grid.ts"
import {
- Charter, Field, FieldOf, Game, Gatherer, Grid, House, Inventory, Land, Paused, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status,
- Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue
+ amounts, APPRENTICE, BUILD_TICKS, COMMUTE, condition, crewOf, goodIds, GROWN, kinds, ticks, total, winters, type Amounts, type Crew
+} from "../content.ts"
+import { around, DIRS, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../grid.ts"
+import {
+ Building, Burning, Charter, Condition, Field, FieldOf, Game, 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 { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"
+/**
+ * Whether a building working at `pace` (a share of full speed, a sum of
+ * halves and quarters) gets its step in on step `tick`: at a half, every
+ * other step; at a quarter, every fourth.
+ */
+export const paced = (pace: number, tick: number): boolean => pace >= 1 || Math.floor((tick + 1) * pace) > Math.floor(tick * pace)
+
/**
* What stands where on the land, for every system after it this step.
* Tiles never move, so the grid is only rebuilt when one is laid or one of
@@ -93,35 +102,99 @@ export const Raise = Game.System(
// ── Workers ───────────────────────────────────────────────────────────────
/** Workers are reassigned this often: residents move in and out every few seconds, no faster. */
-const STAFF_TICKS = ticks(0.5)
+export const STAFF_TICKS = ticks(0.5)
/**
- * Residents go to work in the order buildings were placed, as many as each
- * needs while any are left; a paused building gets nobody.
+ * Residents go to work at the workplaces within a commute of their home
+ * (`COMMUTE` road cells), nearest homes first; the workplaces with the
+ * fewest of their crew within reach are staffed first (in the order they
+ * were placed, among equals), so a mine with its own cottages is not robbed
+ * of them by a workshop in town. Settlers do the rough work and citizens the skilled; citizens
+ * never take a settlers' job, and settlers fill a citizens' job only once
+ * every workplace has had its own crew, as apprentices at a slower pace. A
+ * paused or burning building gets nobody.
*/
export const AssignStaff = Game.System(
"Town/AssignStaff",
{
queries: {
- homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }),
- workplaces: Game.Query({ selection: { tile: Game.Query.read(Tile), staff: Game.Query.write(Staff), paused: Game.Query.optional(Paused) }, without: [Site, Rising] })
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
+ workplaces: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
+ staff: Game.Query.write(Staff),
+ paused: Game.Query.optional(Paused),
+ burning: Game.Query.optional(Burning)
+ },
+ without: [Site, Rising]
+ })
},
resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }
},
({ queries, resources }) => {
if (resources.time.get().tick % STAFF_TICKS !== 0) return
const grid = resources.grid.get()
- let pool = 0
- for (const { data } of queries.homes.each()) pool += data.house.get().residents
+ const homes: Array<{ readonly crew: Crew; left: number; readonly doors: ReadonlyArray<{ readonly x: number; readonly y: number }> }> = []
+ for (const { data } of queries.homes.each()) {
+ const h = data.house.get()
+ const ds = doors(grid, data.tile.get())
+ if (h.residents > 0 && ds.length > 0) homes.push({ crew: crewOf(h.tier), left: h.residents, doors: ds })
+ }
+ type Row = ReturnType<typeof queries.workplaces.each>[number]
+ const places: Array<{
+ readonly data: Row["data"]
+ readonly staff: { readonly needed: number; readonly assigned: number; readonly apprentices: number; readonly nearby: number }
+ readonly crew: Crew
+ readonly within: ReadonlyArray<{ readonly home: (typeof homes)[number]; readonly distance: number }>
+ assigned: number
+ apprentices: number
+ readonly nearby: number
+ }> = []
for (const { data } of queries.workplaces.each()) {
const staff = data.staff.get()
- const assigned = connected(grid, data.tile.get()) && !data.paused.present ? Math.min(staff.needed, pool) : 0
- pool -= assigned
- if (assigned !== staff.assigned) data.staff.set({ ...staff, assigned })
+ if (staff.needed === 0) continue
+ const crew = kinds[data.building.get().kind].crew
+ const starts = doors(grid, data.tile.get())
+ const within: Array<{ readonly home: (typeof homes)[number]; readonly distance: number }> = []
+ if (starts.length > 0 && !data.paused.present && !data.burning.present) {
+ const roads = reach(grid, starts)
+ for (const home of homes) {
+ let distance = -1
+ for (const d of home.doors) {
+ const n = roads.distance[key(d.x, d.y)]!
+ if (n >= 0 && (distance < 0 || n < distance)) distance = n
+ }
+ if (distance >= 0 && distance <= COMMUTE) within.push({ home, distance })
+ }
+ within.sort((a, b) => a.distance - b.distance)
+ }
+ const nearby = within.reduce((n, w) => n + (w.home.crew === crew ? w.home.left : 0), 0)
+ places.push({ data, staff, crew, within, assigned: 0, apprentices: 0, nearby })
+ }
+ const fill = (place: (typeof places)[number], from: Crew) => {
+ for (const { home } of place.within) {
+ if (place.assigned >= place.staff.needed) return
+ if (home.crew !== from || home.left === 0) continue
+ const take = Math.min(place.staff.needed - place.assigned, home.left)
+ home.left -= take
+ place.assigned += take
+ if (from !== place.crew) place.apprentices += take
+ }
+ }
+ const order = places.map((place, index) => ({ place, index })).sort((a, b) => a.place.nearby - b.place.nearby || a.index - b.index)
+ for (const { place } of order) fill(place, place.crew)
+ for (const { place } of order) if (place.crew === "citizens") fill(place, "settlers")
+ for (const { data, staff, assigned, apprentices, nearby } of places) {
+ if (staff.assigned !== assigned || staff.apprentices !== apprentices || staff.nearby !== nearby) data.staff.set({ ...staff, assigned, apprentices, nearby })
}
}
)
+/** Worker-steps a crew puts in this step: apprentices only on their share of the steps (see `APPRENTICE`). */
+export const effort = (staff: { readonly assigned: number; readonly apprentices: number }, tick: number) =>
+ staff.assigned - staff.apprentices + (paced(APPRENTICE, tick) ? staff.apprentices : 0)
+
// ── Recipes ───────────────────────────────────────────────────────────────
/**
@@ -129,7 +202,9 @@ export const AssignStaff = Game.System(
* makes, its input is in, and (for a gatherer) the land has what it needs
* within reach: a grown tree is felled, a rock chipped, a ripe field
* reaped. Then the crew puts its worker-steps in; a full crew finishes in
- * `period` steps. In winter, fishing goes at half pace.
+ * `period` steps. It goes at half pace without the tools it wears out, and
+ * at half pace again once it is run down; in winter, fishing goes at the
+ * winter's pace (a hard winter's is a quarter).
*/
export const Work = Game.System(
"Town/Work",
@@ -138,12 +213,14 @@ export const Work = Game.System(
workshops: Game.Query({
selection: {
tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
staff: Game.Query.read(Staff),
recipe: Game.Query.write(Recipe),
inventory: Game.Query.write(Inventory),
status: Game.Query.write(Status),
gatherer: Game.Query.optional(Gatherer),
- paused: Game.Query.optional(Paused)
+ paused: Game.Query.optional(Paused),
+ condition: Game.Query.optional(Condition)
},
without: [Site, Rising]
}),
@@ -155,8 +232,10 @@ export const Work = Game.System(
},
({ queries, resources, commands }) => {
const grid = resources.grid.get()
+ const tick = resources.time.get().tick
const t = elapsed(resources.time.get(), resources.charter.get())
- const slowFishing = seasonAt(t, resources.charter.get()).winter && t % 2 === 1
+ const season = seasonAt(t, resources.charter.get())
+ const fishing = season.severity ? winters[season.severity].fishing : 1
// The land by entity, looked up only once some gatherer starts a job this step.
const lazy = <T>(make: () => T) => {
let value: T | undefined
@@ -205,6 +284,7 @@ export const Work = Game.System(
for (const { data } of queries.workshops.each()) {
const tile = data.tile.get()
+ const kind = kinds[data.building.get().kind]
const staff = data.staff.get()
const gatherer = maybe(data.gatherer)
let recipe = data.recipe.get()
@@ -222,11 +302,16 @@ export const Work = Game.System(
recipe = { ...recipe, progress: 1 }
}
}
- if (open && recipe.progress > 0 && staff.assigned > 0 && !(slowFishing && gatherer?.source === "water")) {
- const progress = recipe.progress + staff.assigned
+ const worn = (maybe(data.condition)?.value ?? Infinity) < condition.worn
+ const pace = (kind.wear && stock.tools === 0 ? 0.5 : 1) * (worn ? 0.5 : 1) * (gatherer?.source === "water" ? fishing : 1)
+ const put = effort(staff, tick)
+ if (open && recipe.progress > 0 && put > 0 && paced(pace, tick)) {
+ const progress = recipe.progress + put
if (progress > recipe.period * staff.needed) {
recipe = { ...recipe, progress: 0, made: recipe.made + 1 }
stock = { ...stock, [recipe.output]: stock[recipe.output] + recipe.batch }
+ // Every so many jobs wear out a tool.
+ if (kind.wear && recipe.made % kind.wear === 0 && stock.tools > 0) stock = { ...stock, tools: stock.tools - 1 }
} else recipe = { ...recipe, progress }
}
const status: StatusValue = data.paused.present
diff --git a/src/ui.ts b/src/ui.ts
index b8464c6..d94294a 100644
--- a/src/ui.ts
+++ b/src/ui.ts
@@ -4,11 +4,16 @@
* preview, and edits; the simulation applies the edits on its next step.
* None of it is saved: it is host state, handed to systems as a service.
*/
-import type { Amounts, CharterValue, GoodId, KindId, Tier } from "./content.ts"
+import type { Amounts, CharterValue, GoodId, KindId, Tier, WinterId } from "./content.ts"
import type { Point } from "./iso.ts"
import type { Status } from "./schema.ts"
+import type { OverlayCell } from "./render3d/models.ts"
-export type Tool = "select" | "road" | "home" | "bulldoze" | "place"
+export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place"
+
+/** What the map shows over the town: nothing, or one of its views, cell by cell. */
+export const viewIds = ["none", "appeal", "workers", "fire", "health", "order", "condition"] as const
+export type View = (typeof viewIds)[number]
/** A change to the town, applied by the simulation (see `ApplyEdits`). */
export type Edit =
@@ -16,6 +21,8 @@ export type Edit =
| { readonly type: "building"; readonly kind: KindId; readonly cell: Point; readonly open: boolean }
| { readonly type: "homes"; readonly cells: ReadonlyArray<Point> }
| { readonly type: "roads"; readonly cells: ReadonlyArray<Point> }
+ /** Paves the road on each cell (coins, and stone from storage). */
+ | { readonly type: "pave"; readonly cells: ReadonlyArray<Point> }
/** Removes whatever stands on a cell (not rocks, water, or the town hall). */
| { readonly type: "remove"; readonly cell: Point }
/** Sets a tier's tax rate, in percent of the usual. */
@@ -83,6 +90,13 @@ export type Panel =
readonly tier: Tier
readonly lines: ReadonlyArray<string>
}
+ | {
+ readonly type: "ruin"
+ readonly id: number
+ readonly cell: Point
+ readonly cause: "burnt" | "collapsed" | "derelict"
+ readonly lines: ReadonlyArray<string>
+ }
/** A thing's hit area for the pointer, nearest first. */
export interface HitBox {
@@ -114,13 +128,23 @@ export interface Stats {
/** Each good's price with traders, in percent of the usual. */
readonly prices: Amounts
readonly settlers: number
+ /** Citizens in citizens' homes and townhouses; of them, `burghers` in townhouses. */
readonly citizens: number
+ readonly burghers: number
readonly jobs: number
readonly employed: number
readonly charter: CharterValue
/** Minutes into the term. */
readonly minute: number
- readonly season: { readonly year: number; readonly winter: boolean; readonly left: number }
+ readonly season: {
+ readonly year: number
+ readonly winter: boolean
+ readonly left: number
+ /** This winter's severity, while it lasts; and the next one the almanac foresees, and the one after. */
+ readonly severity: WinterId | null
+ readonly coming: WinterId | null
+ readonly after: WinterId | null
+ }
readonly mood: {
readonly approval: number
readonly target: number
@@ -157,6 +181,12 @@ export interface Stats {
}
readonly goals: ReadonlyArray<{ readonly text: string; readonly value: string; readonly met: boolean }>
readonly larder: number
+ /** Food the town ate, and food that rotted in store, over the last minute. */
+ readonly eaten: number
+ readonly rotted: number
+ /** Homes sick, and homes and buildings on fire, right now. */
+ readonly sick: number
+ readonly burning: number
readonly history: ReadonlyArray<{
readonly tick: number
readonly coins: number
@@ -165,7 +195,16 @@ export interface Stats {
readonly approval: number
readonly net: number
}>
- readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string }>
+ readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string; readonly alarm: boolean }>
+ /** What needs looking at right now, a line each: workshops waiting, workplaces no one can reach, food running out. */
+ readonly alerts: ReadonlyArray<string>
+}
+
+/** A map view's legend: what each colour means. */
+export interface Legend {
+ readonly title: string
+ readonly keys: ReadonlyArray<{ readonly color: number; readonly label: string }>
+ readonly note: string
}
export interface UiValue {
@@ -193,5 +232,9 @@ export interface UiValue {
speed: number
/** The new-town dialog is open: the town waits. */
founding: boolean
+ /** 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> }
+ legend: Legend | null
toast: (message: string) => void
}
diff --git a/test/model.test.ts b/test/model.test.ts
index bdcb1a6..11cf57b 100644
--- a/test/model.test.ts
+++ b/test/model.test.ts
@@ -15,7 +15,7 @@ import { test } from "node:test"
import { Arbitrary, Data, Effect, Schema } from "effect"
import {
- crown, goodIds, home, kindOrder, kinds, landIds, market, RESERVES, TAX_STEPS, type CharterValue
+ CONDITION_MAX, crown, goodIds, home, kindOrder, kinds, landIds, market, RESERVES, RISK_MAX, TAX_STEPS, type CharterValue
} from "../src/content.ts"
import { canPlace, cellsOf, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"
import { GRID, inside, type Point } from "../src/iso.ts"
@@ -47,6 +47,8 @@ const Command = Schema.Union([
Schema.TaggedStruct("Season", { minutes: between(1, 6) }),
// A road out from one of the town's road cells.
Schema.TaggedStruct("Road", { pick: Pick, toward: Direction, length: between(1, 10) }),
+ // Paving a stretch of road (or whatever lies along it).
+ Schema.TaggedStruct("Pave", { pick: Pick, toward: Direction, length: between(1, 8) }),
// A row of homes from a free cell beside a road.
Schema.TaggedStruct("Homes", { pick: Pick, toward: Direction, length: between(1, 6) }),
// A building on a spot with room and a road at one of its doors.
@@ -74,7 +76,7 @@ type Command = typeof Command.Type
* policy levers now and then; running the term out rarely.
*/
const weights: Readonly<Record<Command["_tag"], number>> = {
- Build: 20, Homes: 15, Road: 12, Season: 10, Wait: 8, Trade: 5, Tax: 4, Remove: 4, Pause: 4, Deliver: 4, SaveAndLoad: 3,
+ Build: 20, Homes: 15, Road: 12, Pave: 3, Season: 10, Wait: 8, Trade: 5, Tax: 4, Remove: 4, Pause: 4, Deliver: 4, SaveAndLoad: 3,
Windfall: 3, Reserve: 2, BuildAnywhere: 2, Govern: 2, ToTheEnd: 1
}
const table = Object.entries(weights).flatMap(([tag, n]) => Array.from({ length: n }, () => tag as Command["_tag"]))
@@ -106,9 +108,11 @@ const look = (s: Snapshot) => {
const tile = e.components["Town/Tile"]
if (!tile) continue
const c = e.components
- const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : "building"
+ const use: Use = c["Town/Road"] ? "road" : 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"
builder.claim(tile, e.id, use)
if (use === "building" || use === "house" || use === "road") standing.push({ id: e.id, what: use, tile })
+ // A ruin is cleared like a building.
+ if (use === "ruin") standing.push({ id: e.id, what: "building", tile })
}
const grid = builder.value()
const cells = (f: (x: number, y: number) => boolean) => {
@@ -147,6 +151,11 @@ const apply = (town: Headless, command: Command): string | null => {
if (from) edit({ type: "roads", cells: line(from, command.length + 1, command.toward).slice(1) })
break
}
+ case "Pave": {
+ const from = pick(look(town.snapshot()).roads(), command.pick)
+ if (from) edit({ type: "pave", cells: line(from, command.length, command.toward) })
+ break
+ }
case "Homes": {
const from = pick(look(town.snapshot()).free(), command.pick)
if (from) edit({ type: "homes", cells: line(from, command.length, command.toward) })
@@ -275,7 +284,8 @@ const broken = (s: Snapshot, before: Memory | null, last: Command): Array<string
for (const e of s.entities) {
const h = e.components["Town/House"]
if (!h) continue
- if (h.residents < 0 || h.residents > home.tiers[h.tier as 1 | 2].residents) fail(`home ${e.id} has ${h.residents} residents at tier ${h.tier}`)
+ if (![1, 2, 3].includes(h.tier)) fail(`home ${e.id} is of tier ${h.tier}`)
+ if (h.residents < 0 || h.residents > home.tiers[h.tier as 1 | 2 | 3].residents) fail(`home ${e.id} has ${h.residents} residents at tier ${h.tier}`)
residents += h.residents
if (h.tier === 1) settlers += h.residents
else citizens += h.residents
@@ -285,11 +295,28 @@ const broken = (s: Snapshot, before: Memory | null, last: Command): Array<string
const staff = e.components["Town/Staff"]
if (!staff) continue
if (staff.assigned < 0 || staff.assigned > staff.needed) fail(`building ${e.id} has ${staff.assigned} of ${staff.needed} workers`)
+ if (staff.apprentices < 0 || staff.apprentices > staff.assigned) fail(`building ${e.id} has ${staff.apprentices} apprentices of ${staff.assigned} workers`)
+ // Citizens never do settlers' work: only a citizens' workplace takes apprentices.
+ const kind = e.components["Town/Building"]?.kind as keyof typeof kinds | undefined
+ if (kind && kinds[kind].crew === "settlers" && staff.apprentices > 0) fail(`${kind} ${e.id} has apprentices`)
assigned += staff.assigned
}
+ // Risks and wear stay within their bounds; ruins and decorations neither burn nor wear.
+ for (const e of s.entities) {
+ const r = e.components["Town/Risk"]
+ if (r) for (const k of ["fire", "health", "order"] as const) if (r[k] < 0 || r[k] > RISK_MAX) fail(`entity ${e.id} has ${k} risk ${r[k]}`)
+ const c = e.components["Town/Condition"]
+ if (c && (c.value < 0 || c.value > CONDITION_MAX)) fail(`entity ${e.id} is in condition ${c.value}`)
+ if (e.components["Town/Sick"] && !e.components["Town/House"]) fail(`entity ${e.id} is sick but no home`)
+ if (e.components["Town/Ruin"] && (e.components["Town/House"] || e.components["Town/Building"])) fail(`ruin ${e.id} still stands`)
+ }
+ const cells = r["Town/Appeal"].cells as Array<number>
+ if (cells.length !== 0 && cells.length !== GRID * GRID) fail(`desirability for ${cells.length} cells`)
if (assigned > residents) fail(`${assigned} at work but only ${residents} residents`)
const census = r["Town/Census"]
if (census.settlers !== settlers || census.citizens !== citizens) fail(`census says ${census.settlers}/${census.citizens}, homes ${settlers}/${citizens}`)
+ const burning = s.entities.filter((e) => e.components["Town/Burning"]).length
+ if (census.burning !== burning) fail(`census says ${census.burning} on fire, ${burning} are`)
// Walkers belong to a building that still stands.
for (const [target, sources] of s.relations["Town/WalkerOf"] ?? []) {
diff --git a/test/render3d.test.ts b/test/render3d.test.ts
index c74a14d..17661e2 100644
--- a/test/render3d.test.ts
+++ b/test/render3d.test.ts
@@ -18,12 +18,12 @@ function valid(asset: InkAsset) {
for (const stroke of asset.strokes) assert.ok(stroke.points.every(p => p.every(Number.isFinite)), asset.id)
}
-test("live construction and fitting are valid for every building and both home tiers", () => {
+test("live construction and fitting are valid for every building and all three home tiers", () => {
for (const build of [0, 0.125, 0.3, 0.55, 0.77, 0.78, 0.8, 0.9, 1]) {
for (const kind of kindIds) for (const side of Object.keys(noDoors)) {
valid(buildingAsset(kind, build, 0.5, { ...noDoors, [side]: true }, 0.5))
}
- for (const tier of [1, 2] as const) valid(homeAsset(tier, 0.62, build, 1, { ...noDoors, backLeft: true }))
+ for (const tier of [1, 2, 3] as const) valid(homeAsset(tier, 0.62, build, 1, { ...noDoors, backLeft: true }))
}
})