Skip to content

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

The charter: a term in office with land, pressure, and an end

Claudee560c3ee063f
diff --git a/README.md b/README.md
index 34ffe13..5ab5ac0 100644
--- a/README.md
+++ b/README.md
@@ -2,25 +2,63 @@
A town simulation in the spirit of Anno, drawn in pale isometric line art:
lay roads, house settlers, gather and craft goods, keep homes supplied, and
-grow settlers into citizens. Game logic runs on the [bevy-ts](https://github.com/SandroMaglione/bevy-ts)
-ECS; Pixi draws it.
+grow settlers into citizens, over one term in office of 45 to 90 minutes
+that ends with the town complete, lost, or run out. Game logic runs on the
+[bevy-ts](https://github.com/SandroMaglione/bevy-ts) ECS; Pixi draws it.
```sh
pnpm install
pnpm dev --host --port 5232
pnpm typecheck
+pnpm check # every way a term can end, ends it
+pnpm balance # a bot plays terms headless and reports the pressure
```
+## A term in office
+
+- **The charter**: a new town is founded on land you choose: its size
+ (small, medium, large), its richness (rich, fair, harsh: forests, stone,
+ ore, lakes, and the starting treasury), and the length of the term (45,
+ 60, or 90 minutes at 1×). The land is an island-like stretch with a
+ wandering coast and capes reaching out; the same seed always makes the
+ same land.
+- **Pressure** builds as the town grows:
+ - *winters*: a term is six years, and every year but the first ends in a
+ winter when fields do not grow, fisheries catch half as much, and homes
+ eat faster;
+ - *administration*: the town hall costs more per home the more homes
+ there are, so a big town of poor homes cannot pay its way;
+ - *the crown* asks for goods the town makes, more as the term goes on;
+ sending them pays, and an unanswered request is a fine and a snub the
+ town remembers;
+ - *the market*: prices fall the more the town sells and rise the more
+ it buys; stone and ore run out;
+ - *approval*, from -100 to 100, follows needs met, taxes, unpaid wages,
+ snubs from the crown, and hungry winters, and decides how many people
+ each home holds.
+- **The levers**: taxes per tier; for each good, sell beyond the reserve,
+ buy up to it (at half again the price), or neither; the reserve itself;
+ pausing a building (no workers, a quarter of its upkeep); answering the
+ crown; and the speed of time (space pauses, 1, 2, 3 for 1×, 2×, 4×).
+- **The end**: the town is *complete* once it holds every goal for two
+ minutes (enough residents and coins for its size, two in five of them
+ citizens, approval 20 or more, not losing coins); you may retire or keep
+ governing. It is *lost* to bankruptcy (three minutes in debt), revolt
+ (approval at -50 or below for two minutes), or abandonment (people fall
+ below 15% of their peak). Otherwise the term runs out, and the town
+ is judged flourishing, holding on, or declining. The reckoning shows the
+ term's history and its chronicle.
+
## How the town works
-- **A new town** is generated land (a lake, forests, stone and ore) with a
- town hall in a clearing, ringed by road, plus starting coins and goods.
+- **A new town** has a town hall in a clearing, ringed by road, plus
+ starting coins and goods.
- **Coins**: homes the town hall can reach by road pay taxes; traders buy
- the goods the town chooses to sell beyond a reserve; every building costs
- upkeep. Building costs coins up front. The **town** panel (T, or click the
- top bar) shows the treasury, people, supplies, and goods over time, and
- holds the levers: a tax rate per tier (high taxes shrink homes), which
- goods to sell, and how much to keep.
+ what the town sells and sell it what it buys; every building costs upkeep
+ and the town hall costs administration. Building costs coins up front.
+ The **town** panel (T, or click the top bar) shows the goals, approval,
+ treasury, people, supplies, the crown, goods and trade, and the
+ chronicle, and holds the levers.
- **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
@@ -41,17 +79,19 @@ pnpm typecheck
- `src/iso.ts`: the grid and the unit everything is measured in (1/16 cell = 2×1 px).
- `src/content.ts`: goods, building kinds, home tiers, costs, upkeep, taxes: plain data.
- `src/archetypes.ts`: content to components.
-- `src/mapgen.ts`: the land of a new town, from a seed.
+- `src/mapgen.ts`: the land of a new town, from its charter.
- `src/schema.ts`: the ECS world: components, relations, resources, services.
- `src/grid.ts`: occupancy, entrances, reach, and road paths.
-- `src/sim/`: the fixed-step simulation (no renderer access): edits, work, logistics, walkers, town.
+- `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/present.ts`: per-frame interaction, panel, and view sync.
- `src/art.ts`: all drawing.
- `src/ui.ts`, `src/host.ts`, `src/main.ts`: the page bridge, camera, input, panels, and start-up.
-The simulation runs on bevy-ts-browser's `FixedLoop` at 60 steps a second,
-with integer state and a seeded random resource. Every saved component is
-validated, so **save** / **load** snapshot the whole world to localStorage.
+The simulation runs on bevy-ts-browser's `FixedLoop` at 60 steps a second
+(times the chosen speed), with integer state and a seeded random resource.
+Every saved component and resource is validated, so **save** / **load**
+snapshot the whole world, history and chronicle included, to localStorage.
In development the console has `town.ui`, `town.runtime`, and
`town.advance(seconds)` to fast-forward the simulation.
@@ -59,13 +99,19 @@ In development the console has `town.ui`, `town.runtime`, and
## Balancing
`pnpm balance` runs a bot that plays the real simulation headless, the way a
-sensible player would, on several seeds, and summarises how the towns did:
-residents, coins and where they came from, when citizens first appeared, how
-well homes were supplied, and which buildings were stuck and why.
+kind of mayor would, on several seeds, and reports how each term ended and
+how the pressure on the town built up: residents, coins, costs against
+income, administration, approval, food, the crown, and which goals were met,
+averaged over the seeds still in office every few minutes.
```sh
-pnpm balance -- --seeds 10 --minutes 45
-pnpm balance -- --tax 150
-pnpm balance -- --set kinds.fishery.recipe.seconds=3 --set home.tiers.1.tax=2
-pnpm balance -- --seeds 1 --verbose # minute by minute, what was built, what was left
+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 -- --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
```
+
+`pnpm check` puts the real simulation into each way a term can end
+(complete, bankrupt, revolt, abandoned, run out), checks an unanswered
+crown request, and checks that a town saved mid-term loads back the same.
diff --git a/docs/mayor-plan.md b/docs/mayor-plan.md
index 384070f..8f4847e 100644
--- a/docs/mayor-plan.md
+++ b/docs/mayor-plan.md
@@ -4,8 +4,8 @@ A plan for turning the current simulation into a game you play as the town's
mayor for one sitting of 45, 60, or 90 minutes, which ends with a town that
either flourished or fell apart, and lets you see why.
-It starts with what the code does today and where it will not hold up over a
-long run (§1). Then it covers what similar games do and what they leave out
+Section 0 is the version that was built from it. The rest starts with what
+the code did before it, and where it would not hold up over a long run (§1). Then it covers what similar games do and what they leave out
(§2), how a session should be set up and paced (§3–4), the levers (§5), the
pressures that make decline possible (§6), new content (§7), how you win or
lose (§8),
@@ -13,6 +13,61 @@ what the engine needs (§9), and the order to build it in (§10).
---
+## 0. The version built: "the charter"
+
+The plan below is the full menu. The first version takes the smallest part
+of it that makes a complete game: you feel the pressure of managing the
+town's goods and coins for the whole sitting, and every term ends in a way
+you can read. It keeps the levers few, so the game stays easy to learn and
+to maintain.
+
+### What is in
+
+| Area | In this version | From the plan |
+|------|-----------------|---------------|
+| **Setting up** | A new-town dialog: land size (small, medium, large), richness (rich, fair, harsh), term (45, 60, 90 minutes), and seed, with a preview of the land | §3 |
+| **Land** | An island-like stretch of land on a 64-cell square: a wandering coast, capes reaching out, lakes, forests, stone, and ore, all scaled by size and richness | user request |
+| **Rhythm** | Six years a term; every year after the first ends in a winter (fields stop, fishing halves, homes eat faster) | §6.2 |
+| **Pressure** | Administration grows with the number of homes; prices fall as the town sells and rise as it buys; stone and ore run out; crown requests grow through the term, with fines and snubs for missed ones | §5.4, §6.3, §6.4 |
+| **Approval** | One town-wide figure from needs, taxes, unpaid wages, the crown's snubs, and hungry winters, with its parts shown. It sets how many people each home holds | §6.1, simplified |
+| **Levers** | Taxes per tier; sell, buy, or neither for each good; the reserve; pausing a building; answering the crown; game speed (pause, 1×, 2×, 4×) | §5.1, §5.3, §5.4, §9 |
+| **Ends** | Complete (every goal held two minutes; retire or keep governing); bankrupt; revolt; abandoned; or the term runs out with a verdict. The reckoning shows the term's chart and chronicle | §8 |
+| **Engine** | Road paths cached against a fingerprint of the road network; history and chronicle saved with the town; `pnpm check` drives every end state | §9 |
+
+### What is left for later
+
+Laws and edicts, wages and service funding, loans, tiers 3 and 4,
+desirability, fire and sickness, elections, gold and favor, and great works.
+Each can be added on top of approval and the crown without changing what is
+here.
+
+### What the simulation changed
+
+The bot (`pnpm balance`) played every change before it stayed. These are
+the calls it forced:
+
+- **The first year has no winter.** On a 45-minute term, a winter at
+ minute 5 sent most towns into a hunger spiral, then debt, then bankruptcy
+ by minute 12.
+- **Administration grows per home and more gently.** It started at
+ homes²/45; a town of settlers went bankrupt by minute 15. It is now
+ homes × (0.5 + homes/200).
+- **Crown requests are sized by what the town makes** of the good in the
+ time given, and capped by what it can store. Requests sized by the clock
+ asked a small town for 120 fish.
+- **Markets do more.** A walker's basket holds 10 of each provision (not
+ 6), a market's shelf 12, and two walkers can be out at once. With one
+ small walker, food reached about half the homes however many fisheries
+ there were, which made the game about walkers rather than goods.
+- **Bread, cloth, and faith last longer** (90, 180, and 150 seconds), so a
+ home can have all three at once and become citizens.
+- **Four goals, not five.** "Food in store" fought the markets for the same
+ fish; approval already measures whether homes are fed.
+
+### Measured outcomes
+
+MEASURED
+
## 1. What we have, and how it holds up over a long run
### What works well already
diff --git a/package.json b/package.json
index 2078a0a..ecbaa66 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,8 @@
"dev": "vite",
"build": "vite build",
"typecheck": "tsc -p tsconfig.json --pretty false",
- "balance": "node scripts/balance.ts"
+ "balance": "node scripts/balance.ts",
+ "check": "node scripts/check.ts"
},
"dependencies": {
"@typeonce/bevy-ts": "^0.5.0",
diff --git a/scripts/balance.ts b/scripts/balance.ts
index 04289f9..a12c2ed 100644
--- a/scripts/balance.ts
+++ b/scripts/balance.ts
@@ -1,44 +1,57 @@
/**
- * Balance runs: a bot plays the real simulation headless, the way a
- * sensible player would, on several seeds, and reports how the town does
- * minute by minute and where it got stuck.
+ * Balance runs: a bot plays the real simulation headless on several seeds,
+ * the way a kind of mayor would, and reports how each term ended and how
+ * the pressure on the town built up along the way.
*
- * node scripts/balance.ts 5 seeds, 30 minutes each
- * node scripts/balance.ts --seeds 10 --minutes 45
- * node scripts/balance.ts --tax 125 settlers and citizens taxed at 125%
- * node scripts/balance.ts --set kinds.fishery.recipe.seconds=3 --set home.tiers.1.tax=3
- * node scripts/balance.ts --verbose print every seed's minute-by-minute table
+ * 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 --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)
*
- * `--set` changes content before the run (any number of them), so a sweep is
- * a shell loop over values. The bot only does what a player could: it reads
- * the world, then pushes the same edits the page does.
+ * The mayors:
+ * - sensible: builds out the chains as the town grows, keeps food in store,
+ * answers the crown, eases taxes when the town grumbles and buys the stone
+ * 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.
+ *
+ * `--set` changes content before the run. The bot only does what a player
+ * could: it reads the world, then pushes the same edits the page does.
*/
-import { amounts, goodIds, home, kinds, ROAD_COST, start, STEP_SECONDS, total, type Amounts, type Kind, type KindId } from "../src/content.ts"
+import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, STEP_SECONDS, total, 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 { GRID, inside, type Point } from "../src/iso.ts"
import { Game, Ui, type GridValue } from "../src/schema.ts"
-import { simulate } from "../src/sim/index.ts"
+import { blankResources, goalsOf, larder, seasonAt, simulate, termTicks } from "../src/sim/index.ts"
import { emptyPreview, type Edit, type UiValue } from "../src/ui.ts"
// ── Options ───────────────────────────────────────────────────────────────
const args = process.argv.slice(2)
-const option = (name: string, fallback: number) => {
+const option = (name: string, fallback: string) => {
const i = args.indexOf(`--${name}`)
- return i >= 0 ? Number(args[i + 1]) : fallback
+ return i >= 0 ? args[i + 1]! : fallback
}
-const seeds = option("seeds", 5)
-const minutes = option("minutes", 30)
-const tax = option("tax", 100)
+const seeds = Number(option("seeds", "5"))
+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"
+const every = Number(option("every", "5"))
const verbose = args.includes("--verbose")
+if (!sizeIds.includes(size) || !landIds.includes(land) || !["sensible", "greedy", "idle"].includes(bot)) throw new Error("Unknown --size, --land, or --bot")
/** `--set path=value`: change a number in the content before running. */
-const roots: Record<string, unknown> = { kinds, home, start }
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 = roots as Record<string, unknown>
+ 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)
}
@@ -50,6 +63,12 @@ interface Snapshot {
readonly resources: Record<string, any>
}
+interface Tile {
+ readonly x: number
+ readonly y: number
+ readonly size: number
+}
+
interface World {
readonly grid: GridValue
/** Cells of ore rocks (other rocks are stone). */
@@ -59,19 +78,21 @@ interface World {
readonly stock: Amounts
readonly coins: number
readonly census: Record<string, number>
- readonly ledger: { readonly taxes: number; readonly trade: number; readonly upkeep: number }
-}
-interface Tile {
- readonly x: number
- readonly y: number
- readonly size: number
+ readonly ledger: { readonly taxes: number; readonly trade: number; readonly upkeep: number; readonly admin: number }
+ readonly policy: { readonly settlers: number; readonly citizens: number; readonly sells: ReadonlyArray<GoodId>; readonly buys: ReadonlyArray<GoodId>; readonly reserve: number }
+ readonly mood: { readonly approval: number; readonly target: number }
+ readonly crown: { readonly open: boolean; readonly good: GoodId; readonly amount: number; readonly met: number; readonly missed: number }
+ readonly fate: { readonly state: string; readonly reason: string; readonly at: number; readonly score: number }
+ readonly charter: { readonly size: CharterValue["size"]; readonly term: number; readonly founded: number }
+ readonly tick: number
}
const read = (snapshot: Snapshot): World => {
- const builder = new GridBuilder()
+ const r = snapshot.resources
+ const builder = new GridBuilder(r["Town/Land"].mask)
const buildings: Array<World["buildings"][number]> = []
const homes: Array<World["homes"][number]> = []
- const stock: Record<string, number> = { ...amounts({}) }
+ const stock: Record<string, number> = Object.fromEntries(goodIds.map((g) => [g, 0]))
const ore = new Set<number>()
for (const e of snapshot.entities) {
const c = e.components
@@ -90,26 +111,35 @@ const read = (snapshot: Snapshot): World => {
buildings,
homes,
stock: stock as Amounts,
- coins: snapshot.resources["Town/Treasury"].coins,
- census: snapshot.resources["Town/Census"],
- ledger: snapshot.resources["Town/Ledger"]
+ coins: r["Town/Treasury"].coins,
+ census: r["Town/Census"],
+ ledger: r["Town/Ledger"],
+ policy: r["Town/Policy"],
+ mood: r["Town/Mood"],
+ crown: r["Town/Crown"],
+ fate: r["Town/Fate"],
+ charter: r["Town/Charter"],
+ tick: r["Town/Time"].tick
}
}
// ── The bot ───────────────────────────────────────────────────────────────
+/** Can pay for it and keep a little in hand (more while the town is losing coins). */
const affordable = (w: World, cost: Kind["cost"]) =>
- w.coins >= cost.coins + 40 && Object.entries(cost.materials).every(([g, n]) => w.stock[g as keyof Amounts] >= (n ?? 0))
+ w.coins >= cost.coins + (net(w) < 0 ? 400 : Math.max(150, w.ledger.upkeep + w.ledger.admin)) && Object.entries(cost.materials).every(([g, n]) => w.stock[g as keyof Amounts] >= (n ?? 0))
+const net = (w: World) => w.ledger.taxes + w.ledger.trade - w.ledger.upkeep - w.ledger.admin
const residents = (w: World) => w.census.settlers! + w.census.citizens!
const unlocked = (w: World, kind: Kind) => residents(w) >= kind.unlock.residents && w.census.citizens! >= kind.unlock.citizens
const count = (w: World, kind: KindId) => w.buildings.filter((b) => b.kind === kind).length
-const sites = (w: World) => w.buildings.filter((b) => b.site).length + 0
+const sites = (w: World) => w.buildings.filter((b) => b.site).length + w.homes.length - w.homes.filter((h) => h.residents > 0 || h.tier > 1).length
const sourceUse: Record<string, Use> = { tree: "tree", stone: "rock", ore: "rock", water: "water", field: "empty" }
+const middle = GRID / 2
/** How good a spot is for a kind: how much of what it works lies within reach (or 1 for anything else). */
const score = (w: World, kind: Kind, tile: Tile): number => {
- const g = kind.gathers ?? (kind.plants ? { source: kind.plants.what === "tree" ? "field" : "field", radius: kind.plants.radius } : null)
+ const g = kind.gathers ?? (kind.plants ? { source: "field", radius: kind.plants.radius } : null)
if (!g) return 1
const want = sourceUse[g.source]!
return around(tile, g.radius).filter((c) => useAt(w.grid, c.x, c.y) === want && (want !== "rock" || w.ore.has(key(c.x, c.y)) === (g.source === "ore"))).length
@@ -122,29 +152,41 @@ const spotFor = (w: World, kind: Kind): Point | 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)) continue
+ // Gatherers go where the land is, plan or no plan.
+ if (!canPlace(w.grid, tile) || (!kind.gathers && offPlan(tile))) continue
if (!entrances(tile).some((c) => isRoad(w.grid, c.x, c.y))) continue
const s = score(w, kind, tile)
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) <= 4 && Math.abs(b.tile.y - y) <= 4)) continue
- const value = (kind.gathers || kind.plants ? s * 10 : 0) - Math.hypot(x - GRID / 2, y - GRID / 2)
+ 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)
if (!best || value > best.value) best = { cell: { x, y }, value }
}
}
return best?.cell ?? null
}
-/** Free cells beside a road, nearest the middle first. */
+/**
+ * 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
+ * in the blocks between them, three cells across.
+ */
+const lane = (x: number, y: number) => x % 4 === 1 || y % 4 === 1
+const offPlan = (tile: Tile) => {
+ for (let dy = 0; dy < tile.size; dy++) for (let dx = 0; dx < tile.size; dx++) if (lane(tile.x + dx, tile.y + dy)) return true
+ return false
+}
+
+/** Free cells beside a road and off the lanes, nearest the middle first. */
const homeSpots = (w: World, n: number): Array<Point> => {
const spots: Array<Point> = []
for (let y = 0; y < GRID; y++) {
for (let x = 0; x < GRID; x++) {
- if (useAt(w.grid, x, y) !== "empty") continue
+ if (useAt(w.grid, x, y) !== "empty" || lane(x, y)) continue
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 - GRID / 2, a.y - GRID / 2) - Math.hypot(b.x - GRID / 2, b.y - GRID / 2)).slice(0, n)
+ return spots.sort((a, b) => Math.hypot(a.x - middle, a.y - middle) - Math.hypot(b.x - middle, b.y - middle)).slice(0, n)
}
/**
@@ -152,11 +194,25 @@ const homeSpots = (w: World, n: number): Array<Point> => {
* the shortest run of free cells from the road network to a cell near the
* source, at most `limit` long.
*/
-const roadToward = (w: World, kind: Kind | null, limit = 10): Array<Point> => {
- const free = (x: number, y: number) => inside(x, y) && (useAt(w.grid, x, y) === "empty" || useAt(w.grid, x, y) === "tree")
+const roadToward = (w: World, kind: Kind | null, limit = 16): Array<Point> => {
+ const free = (x: number, y: number) => inside(x, y) && (useAt(w.grid, x, y) === "empty" || useAt(w.grid, x, y) === "tree") && (lane(x, y) || !!kind?.gathers)
const want = kind?.gathers ? sourceUse[kind.gathers.source] : null
const goal = (x: number, y: number) =>
- want ? DIRS.some((d) => useAt(w.grid, x + 2 * d.x, y + 2 * d.y) === want || useAt(w.grid, x + 3 * d.x, y + 3 * d.y) === want) : around({ x, y, size: 1 }, 2).every((c) => free(c.x, c.y))
+ want
+ ? DIRS.some((d) => useAt(w.grid, x + 2 * d.x, y + 2 * d.y) === want || useAt(w.grid, x + 3 * d.x, y + 3 * d.y) === want)
+ : kind === null
+ ? around({ x, y, size: 1 }, 1).filter((c) => !lane(c.x, c.y) && useAt(w.grid, c.x, c.y) === "empty").length >= 3
+ : fitsBeside(x, y, kind.size)
+ // Room for a building `size` cells a side with a door on (x, y), keeping off the road being laid.
+ const fitsBeside = (x: number, y: number, size: number) => {
+ for (let ty = y - size; ty <= y + 1; ty++) {
+ for (let tx = x - size; tx <= x + 1; tx++) {
+ const tile = { x: tx, y: ty, size }
+ if (entrances(tile).some((c) => c.x === x && c.y === y) && canPlace(w.grid, tile) && !offPlan(tile)) return true
+ }
+ }
+ return false
+ }
const previous = new Map<number, number>()
const queue: Array<Point> = []
for (let y = 0; y < GRID; y++) for (let x = 0; x < GRID; x++) if (isRoad(w.grid, x, y)) queue.push({ x, y })
@@ -187,53 +243,128 @@ const roadToward = (w: World, kind: Kind | null, limit = 10): Array<Point> => {
/** What the bot wants next, in order: the first it can do, it does. */
const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: boolean }> => {
const homes = w.homes.length
- const fed = homes > 0 ? w.census.food! / homes : 1
- return [
+ const basics: ReadonlyArray<{ readonly kind: KindId; readonly when: boolean }> = [
{ kind: "fishery", when: count(w, "fishery") < 1 },
{ kind: "lumberjack", when: count(w, "lumberjack") < 1 },
{ kind: "sawmill", when: count(w, "sawmill") < 1 },
- { kind: "quarry", when: count(w, "quarry") < 1 },
- { kind: "market", when: count(w, "market") < 1 && homes >= 6 },
{ kind: "forester", when: count(w, "forester") < count(w, "lumberjack") },
- { kind: "fishery", when: fed < 0.6 && count(w, "fishery") < 1 + Math.floor(homes / 10) },
+ { 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) }
+ ]
+ if (bot === "idle") return basics
+ // The citizens' chains, in proportion to the homes: a bakery bakes for about
+ // 16 homes and needs a mill, and a mill most of a farm; a weaver weaves for
+ // about 14 homes from one sheep farm's wool. Upstream first, so what a
+ // workshop needs is coming before it stands.
+ const bakeries = homes < 20 ? 1 : 1 + Math.floor(homes / 12)
+ 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.
{ kind: "chapel", when: count(w, "chapel") < 1 },
- { kind: "sheep", when: count(w, "sheep") < 1 },
- { kind: "weaver", when: count(w, "weaver") < 1 },
{ kind: "farm", when: count(w, "farm") < 1 },
{ kind: "mill", when: count(w, "mill") < 1 },
{ kind: "bakery", when: count(w, "bakery") < 1 },
- { kind: "market", when: fed < 0.6 && count(w, "market") < Math.floor(homes / 12) + 1 },
- { kind: "lumberjack", when: w.stock.planks < 10 && count(w, "lumberjack") < 3 },
- { kind: "quarry", when: w.stock.stone < 6 && count(w, "quarry") < 3 },
- { kind: "warehouse", when: count(w, "warehouse") < Math.floor(homes / 20) },
+ { kind: "sheep", when: count(w, "sheep") < 1 },
+ { kind: "weaver", when: count(w, "weaver") < 1 },
+ { kind: "smithy", when: count(w, "smithy") < 1 },
{ kind: "mine", when: count(w, "mine") < 1 },
- { kind: "smithy", when: count(w, "smithy") < 1 }
+ { kind: "chapel", when: count(w, "chapel") < 1 + Math.floor(homes / 35) },
+ { kind: "farm", when: count(w, "farm") < Math.ceil(bakeries * 0.8) },
+ { kind: "mill", when: count(w, "mill") < Math.min(bakeries, count(w, "farm") + 1) },
+ { kind: "bakery", when: count(w, "bakery") < Math.min(bakeries, count(w, "mill")) },
+ { 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) },
+ { 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 }
]
}
/** One decision: build what is wanted first, or homes when workers run short, or road towards what is needed. */
const decide = (w: World): ReadonlyArray<Edit> => {
- if (sites(w) > 2) return []
- // Homes when workers run short, or (they are the town's income) whenever food reaches most of them.
+ const edits: Array<Edit> = []
+ // Policy, now and then.
+ if (bot === "greedy") {
+ if (w.policy.settlers !== 200) edits.push({ type: "tax", tier: "settlers", rate: 200 }, { type: "tax", tier: "citizens", rate: 200 }, { type: "reserve", amount: 10 })
+ 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
- const short = w.census.jobs! + 6 > residents(w) || (fed >= 0.7 && w.stock.planks >= 8)
- if (short && affordable(w, { coins: home.cost.coins * 3, materials: { planks: 3 } })) {
- const spots = homeSpots(w, 3)
- if (spots.length > 0) return [{ type: "homes", cells: spots }]
+ if (bot === "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
+ })
+ // Closing in on a complete town: everything but approval and the larder met. Cut taxes, buy food.
+ const closing = goals.every((g) => g.met || g.id === "approval") && w.coins > 1000
+ const rate = closing || w.mood.approval < 0 ? 50 : w.mood.approval < 15 ? 75 : w.mood.approval > 45 ? 125 : 100
+ if (w.policy.settlers !== rate) edits.push({ type: "tax", tier: "settlers", rate }, { type: "tax", tier: "citizens", rate })
+ // Keep enough to answer the crown, buying what is short of its request.
+ const asked = w.crown.open ? w.crown.amount : 0
+ const reserve = asked > 50 ? 100 : 50
+ if (w.policy.reserve !== reserve) edits.push({ type: "reserve", amount: reserve })
+ const cost = w.crown.amount * content.goods[w.crown.good].price * 2
+ 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]]
+ 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" })
+ }
+ 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.
+ 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 })
+ }
+ }
+ if (bot === "idle" && residents(w) > 30) return edits
+
+ 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.
+ const goal = content.sizes[w.charter.size].goal.residents
+ const short = w.census.jobs! + 6 > residents(w) || (fed >= 0.6 && w.stock.planks >= 8 && w.coins > 300 && residents(w) < goal * 1.2)
+ if (short && affordable(w, { coins: home.cost.coins * 4, materials: { planks: 4 } })) {
+ const spots = homeSpots(w, 4)
+ if (spots.length > 0) return [...edits, { type: "homes", cells: spots }]
const road = roadToward(w, null)
- if (road.length > 0 && w.coins > road.length * ROAD_COST + 60) return [{ type: "roads", cells: road }]
+ if (road.length > 0 && w.coins > road.length * ROAD_COST + 60) return [...edits, { type: "roads", cells: road }]
}
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 ((resting.get(want.kind) ?? 0) > w.tick) continue
const spot = spotFor(w, kind)
- if (spot) return [{ type: "building", kind: want.kind, cell: spot, open: false }]
+ if (spot) {
+ roading.delete(want.kind)
+ return [...edits, { type: "building", kind: want.kind, cell: spot, open: false }]
+ }
+ // Lay a road towards what it needs, a few times; if there is still no room, leave it for a few minutes.
const road = roadToward(w, kind)
- if (road.length > 0 && w.coins > road.length * ROAD_COST + kind.cost.coins) return [{ type: "roads", cells: road }]
+ if (road.length > 0 && w.coins > road.length * ROAD_COST + kind.cost.coins && (roading.get(want.kind) ?? 0) < 4) {
+ roading.set(want.kind, (roading.get(want.kind) ?? 0) + 1)
+ return [...edits, { type: "roads", cells: road }]
+ }
+ roading.delete(want.kind)
+ resting.set(want.kind, w.tick + 5 * 3600)
}
- return []
+ return edits
}
+/** 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>()
// ── Running ───────────────────────────────────────────────────────────────
@@ -241,124 +372,142 @@ interface Row {
readonly minute: number
readonly coins: number
readonly net: number
- readonly taxes: number
- readonly trade: number
- readonly upkeep: number
- readonly settlers: number
+ readonly income: number
+ readonly costs: number
+ readonly admin: number
+ readonly approval: number
+ readonly residents: number
readonly citizens: number
readonly homes: number
readonly food: number
- readonly cloth: number
- readonly faith: number
- readonly jobs: string
- readonly buildings: number
+ readonly larder: number
+ readonly winter: boolean
+ readonly crown: string
+ readonly goals: number
readonly problems: Record<string, number>
}
const run = (seed: number) => {
+ roading.clear()
+ resting.clear()
+ const charter: CharterValue = { size, term, land, seed }
const ui: UiValue = {
tool: "select", placing: null, menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],
- edits: [{ type: "newTown", seed }],
- preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, toast: () => {}
+ edits: [{ type: "newTown", charter }],
+ preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false, toast: (m) => { if (process.env.DEBUG) console.log("toast:", m) }
}
- const made = Game.Runtime.make({
- services: Game.Runtime.services(Game.Runtime.service(Ui, ui)),
- resources: {
- Time: { tick: 0 }, Rng: seed, Treasury: { coins: 0 }, Ledger: { taxes: 0, trade: 0, upkeep: 0 },
- Census: { homes: 0, settlers: 0, citizens: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0 },
- Policy: { settlers: 100, citizens: 100, sells: [], reserve: 25 }, Grid: { owner: [], use: [] }, Stock: amounts({})
- }
- })
+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })
if (!made.ok) throw new Error(JSON.stringify(made.error))
const runtime = made.value
const step = (seconds: number) => {
for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)
}
step(0.1)
- // The new town has its usual policy; set the taxes for this run.
- ui.edits.push({ type: "tax", tier: "settlers", rate: tax }, { type: "tax", tier: "citizens", rate: tax })
- step(0.1)
const rows: Array<Row> = []
const problems: Record<string, number> = {}
- let firstCitizen: number | null = null
- let minCoins = Infinity
- let debtMinutes = 0
+ let w = read(runtime.snapshot() as unknown as Snapshot)
const DECIDE = 5
- for (let t = 0; t < minutes * 60; t += DECIDE) {
- const w = read(runtime.snapshot() as unknown as Snapshot)
- ui.edits.push(...decide(w))
+ for (let t = 0; t < term * 60 + DECIDE && w.fate.state === "playing"; t += DECIDE) {
+ const chosen = decide(w)
+ if (process.env.DEBUG) console.log(t, JSON.stringify(chosen).slice(0, 200))
+ ui.edits.push(...chosen)
step(DECIDE)
- minCoins = Math.min(minCoins, w.coins)
- if ((t + DECIDE) % 60 === 0) {
- const now = read(runtime.snapshot() as unknown as Snapshot)
- const minute = (t + DECIDE) / 60
- const problemsNow: Record<string, number> = {}
- for (const b of now.buildings) {
- if (["unconnected", "unstaffed", "starved", "blocked"].includes(b.status) && !b.site) {
- const k = `${b.kind} ${b.status}`
- problemsNow[k] = (problemsNow[k] ?? 0) + 1
- problems[k] = (problems[k] ?? 0) + 1
- }
+ w = read(runtime.snapshot() as unknown as Snapshot)
+ if ((t + DECIDE) % 60 !== 0) continue
+ const minute = (t + DECIDE) / 60
+ const problemsNow: Record<string, number> = {}
+ for (const b of w.buildings) {
+ if (["unconnected", "unstaffed", "starved", "blocked"].includes(b.status) && !b.site) {
+ const k = `${b.kind} ${b.status}`
+ problemsNow[k] = (problemsNow[k] ?? 0) + 1
+ problems[k] = (problems[k] ?? 0) + 1
}
- if (now.coins < 0) debtMinutes += 1
- if (firstCitizen === null && now.census.citizens! > 0) firstCitizen = minute
- const h = Math.max(1, now.homes.length)
- rows.push({
- minute,
- coins: now.coins,
- net: now.ledger.taxes + now.ledger.trade - now.ledger.upkeep,
- taxes: now.ledger.taxes,
- trade: now.ledger.trade,
- upkeep: now.ledger.upkeep,
- settlers: now.census.settlers!,
- citizens: now.census.citizens!,
- homes: now.homes.length,
- food: Math.round((now.census.food! / h) * 100),
- cloth: Math.round((now.census.cloth! / h) * 100),
- faith: Math.round((now.census.faith! / h) * 100),
- jobs: `${now.census.employed}/${now.census.jobs}`,
- buildings: now.buildings.length,
- problems: problemsNow
- })
}
+ const h = Math.max(1, w.homes.length)
+ const income = w.ledger.taxes + Math.max(0, w.ledger.trade)
+ const costs = w.ledger.upkeep + w.ledger.admin + Math.max(0, -w.ledger.trade)
+ const goals = goalsOf(w.charter, {
+ settlers: w.census.settlers!, citizens: w.census.citizens!, coins: w.coins, net: income - costs, approval: w.mood.approval
+ })
+ rows.push({
+ minute,
+ coins: w.coins,
+ net: income - costs,
+ income,
+ costs,
+ admin: w.ledger.admin,
+ approval: w.mood.approval,
+ residents: residents(w),
+ citizens: w.census.citizens!,
+ homes: w.homes.length,
+ food: Math.round((w.census.food! / h) * 100),
+ larder: larder(w.stock),
+ 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,
+ problems: problemsNow
+ })
}
- const end = read(runtime.snapshot() as unknown as Snapshot)
+ 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(" · ")
+ const hh = Math.max(1, w.homes.length)
+ const supplied = `food ${Math.round((w.census.food! / hh) * 100)}% bread ${Math.round((w.census.bread! / hh) * 100)}% cloth ${Math.round((w.census.cloth! / hh) * 100)}% faith ${Math.round((w.census.faith! / hh) * 100)}%`
+ 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 end.buildings) built[b.kind] = (built[b.kind] ?? 0) + 1
- return { seed, rows, problems, firstCitizen, minCoins, debtMinutes, built, stock: end.stock }
+ 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 }
}
const pad = (v: unknown, n: number) => String(v).padStart(n)
-const results = []
+const results: Array<ReturnType<typeof run>> = []
const started = performance.now()
-for (let i = 0; i < seeds; i++) {
+const header = " min coins net income costs admin appr resid citiz homes food% larder season crown(met/missed) goals 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}`
+}
+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(`\nseed ${r.seed}`)
- console.log(" min coins net settlers citizens homes food% cloth% faith% jobs bldgs problems")
- for (const row of r.rows) {
- const p = Object.entries(row.problems).map(([k, n]) => `${k}${n > 1 ? `×${n}` : ""}`).join(", ")
- console.log(`${pad(row.minute, 4)} ${pad(row.coins, 7)} ${pad(row.net, 5)} ${pad(row.settlers, 9)} ${pad(row.citizens, 8)} ${pad(row.homes, 5)} ${pad(row.food, 5)} ${pad(row.cloth, 6)} ${pad(row.faith, 6)} ${pad(row.jobs, 7)} ${pad(row.buildings, 6)} ${p}`)
- }
+ 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(", ")}`)
+ console.log(` stock: ${goodIds.filter((g) => r.stock[g] > 0).map((g) => `${g} ${r.stock[g]}`).join(", ")}\n`)
}
}
// ── Summary ───────────────────────────────────────────────────────────────
const mean = (xs: ReadonlyArray<number>) => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
-const last = results.map((r) => r.rows.at(-1)!)
-console.log(`\n${seeds} seeds × ${minutes} min, tax ${tax}% (${Math.round(performance.now() - started)} ms)`)
-console.log(` residents at the end ${mean(last.map((r) => r.settlers + r.citizens)).toFixed(0)} (citizens ${mean(last.map((r) => r.citizens)).toFixed(0)})`)
-console.log(` coins at the end ${mean(last.map((r) => r.coins)).toFixed(0)}, net ${mean(last.map((r) => r.net)).toFixed(0)}/min (taxes ${mean(last.map((r) => r.taxes)).toFixed(0)}, trade ${mean(last.map((r) => r.trade)).toFixed(0)}, upkeep ${mean(last.map((r) => r.upkeep)).toFixed(0)})`)
-console.log(` lowest coins ${Math.min(...results.map((r) => r.minCoins))} minutes in debt ${mean(results.map((r) => r.debtMinutes)).toFixed(1)}`)
-console.log(` first citizens ${results.map((r) => (r.firstCitizen === null ? "never" : `${r.firstCitizen} min`)).join(", ")}`)
-console.log(` homes supplied food ${mean(last.map((r) => r.food)).toFixed(0)}%, cloth ${mean(last.map((r) => r.cloth)).toFixed(0)}%, faith ${mean(last.map((r) => r.faith)).toFixed(0)}%`)
+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(` most common problems ${top.map(([k, n]) => `${k} (${(n / seeds).toFixed(1)} min/seed)`).join(", ") || "none"}`)
+console.log(`\n most common problems ${top.map(([k, n]) => `${k} (${(n / seeds).toFixed(1)} min/seed)`).join(", ") || "none"}`)
void total
+void termTicks
diff --git a/scripts/check.ts b/scripts/check.ts
new file mode 100644
index 0000000..553adb0
--- /dev/null
+++ b/scripts/check.ts
@@ -0,0 +1,186 @@
+/**
+ * Checks that every way a term can end does end it: the real simulation,
+ * headless, put into each situation through the same snapshots the page
+ * saves and loads.
+ *
+ * node scripts/check.ts
+ *
+ * - complete: a town meeting every goal, held two minutes, is won; it can
+ * carry on governing, and its term then runs out as complete;
+ * - bankrupt: three minutes in debt;
+ * - revolt: approval at -50 or below for two minutes;
+ * - abandoned: residents fall below 15% of their peak;
+ * - over: a term run out;
+ * - the crown: a request left unanswered is a fine and a snub;
+ * - and a town saved mid-term loads back the same.
+ */
+import { STEP_SECONDS, type CharterValue } from "../src/content.ts"
+import { DIRS, GridBuilder, key } from "../src/grid.ts"
+import { inside } from "../src/iso.ts"
+import { Game, Ui } from "../src/schema.ts"
+import { blankResources, simulate } from "../src/sim/index.ts"
+import { emptyPreview, type Edit, type UiValue } from "../src/ui.ts"
+
+interface Snapshot {
+ nextEntity: number
+ entities: Array<{ id: number; components: Record<string, any> }>
+ resources: Record<string, any>
+}
+
+const town = (charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }) => {
+ const ui: UiValue = {
+ 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, toast: () => {}
+ }
+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })
+ if (!made.ok) throw new Error(JSON.stringify(made.error))
+ const runtime = made.value
+ const run = (seconds: number) => {
+ for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)
+ }
+ const snapshot = () => JSON.parse(JSON.stringify(runtime.snapshot())) as Snapshot
+ const restore = (s: Snapshot) => {
+ const restored = runtime.restore(s as never)
+ if (!restored.ok) throw new Error(`restore failed: ${JSON.stringify(restored.error)}`)
+ }
+ /** Changes the world through a snapshot, as a load would. */
+ const change = (f: (s: Snapshot) => void) => {
+ const s = snapshot()
+ f(s)
+ restore(s)
+ }
+ const fate = () => snapshot().resources["Town/Fate"] as { state: string; reason: string; at: number; governing: boolean }
+ const edit = (...edits: ReadonlyArray<Edit>) => ui.edits.push(...edits)
+ run(0.1)
+ return { run, snapshot, restore, change, fate, edit }
+}
+
+/** Citizens' homes, every need met for good, on free cells beside the roads. */
+const settle = (s: Snapshot, homes: number) => {
+ const grid = new GridBuilder(s.resources["Town/Land"].mask)
+ for (const e of s.entities) {
+ const tile = e.components["Town/Tile"]
+ if (tile) grid.claim(tile, e.id, e.components["Town/Road"] ? "road" : "building")
+ }
+ const g = grid.value()
+ let placed = 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
+ s.entities.push({
+ id: s.nextEntity++,
+ components: {
+ "Town/Tile": { x, y, size: 1 },
+ "Town/House": { tier: 2, residents: 8, food: forever, bread: forever, cloth: forever, faith: forever, clock: 1 }
+ }
+ })
+ placed += 1
+ }
+ return placed
+}
+
+let failures = 0
+const check = (name: string, ok: boolean, detail: string) => {
+ console.log(`${ok ? "ok " : "FAIL"} ${name}: ${detail}`)
+ if (!ok) failures += 1
+}
+
+// Complete: 25 citizens' homes is 200 residents, all citizens; plenty of coins.
+{
+ const t = town()
+ let placed = 0
+ t.change((s) => {
+ placed = settle(s, 25)
+ s.resources["Town/Treasury"].coins = 10_000
+ })
+ t.run(4 * 60)
+ const f = t.fate()
+ check("complete", f.state === "won", `${placed} homes · ${f.state} at ${(f.at / 3600).toFixed(1)} min: ${f.reason}`)
+ t.edit({ type: "govern" })
+ t.run(1)
+ check("keep governing", t.fate().state === "playing" && t.fate().governing, `${t.fate().state}, governing ${t.fate().governing}`)
+ t.run(42 * 60)
+ const end = t.fate()
+ check("complete to the end", end.state === "over" && end.governing, `${end.state}: ${end.reason}`)
+}
+
+// Bankrupt: deep in debt with nothing coming in.
+{
+ const t = town()
+ t.change((s) => {
+ s.resources["Town/Treasury"].coins = -5000
+ })
+ t.run(3.5 * 60)
+ const f = t.fate()
+ check("bankrupt", f.state === "lost" && f.reason.startsWith("Bankrupt"), `${f.state} at ${(f.at / 3600).toFixed(1)} min: ${f.reason}`)
+}
+
+// Revolt: an angry town, taxed to the hilt and unpaid.
+{
+ const t = town()
+ t.change((s) => {
+ s.resources["Town/Treasury"].coins = -10
+ s.resources["Town/Mood"].approval = -100
+ s.resources["Town/Policy"].settlers = 200
+ s.resources["Town/Policy"].citizens = 200
+ })
+ t.run(2.5 * 60)
+ const f = t.fate()
+ check("revolt", f.state === "lost" && f.reason.startsWith("Revolt"), `${f.state} at ${(f.at / 3600).toFixed(1)} min: ${f.reason}`)
+}
+
+// Abandoned: a town that once had a hundred people and now has none.
+{
+ const t = town()
+ t.change((s) => {
+ s.resources["Town/Fate"].peak = 100
+ })
+ t.run(2)
+ const f = t.fate()
+ check("abandoned", f.state === "lost" && f.reason.startsWith("Abandoned"), `${f.state}: ${f.reason}`)
+}
+
+// Over: a term left to run out (a short one, to be quick about it).
+{
+ const t = town({ size: "small", term: 45, land: "rich", seed: 3 })
+ t.change((s) => {
+ s.resources["Town/Treasury"].coins = 100_000
+ })
+ t.run(45 * 60 + 2)
+ const f = t.fate()
+ check("over", f.state === "over", `${f.state} at ${(f.at / 3600).toFixed(1)} min: ${f.reason}`)
+}
+
+// The crown: a lumberjack makes wood, the crown asks for some, and nobody sends it.
+{
+ const t = town()
+ const s = t.snapshot()
+ const hall = s.entities.find((e) => e.components["Town/TownHall"])!.components["Town/Tile"]
+ // Against the stub road out of the town hall's east side, its door on the road.
+ t.edit({ type: "building", kind: "lumberjack", cell: { x: hall.x + 4, y: hall.y + 2 }, open: false })
+ t.run(12 * 60)
+ const c = t.snapshot().resources["Town/Crown"]
+ const lines = t.snapshot().resources["Town/Chronicle"].lines as Array<{ text: string }>
+ check("crown", c.missed >= 1 && lines.some((l) => l.text.includes("unanswered")), `met ${c.met}, missed ${c.missed}, snubs ${c.snubs.length}`)
+}
+
+// Save and load: a town mid-term loads back to the same state, and runs on the same.
+{
+ const a = town({ size: "medium", term: 60, land: "harsh", seed: 11 })
+ a.run(30)
+ const saved = JSON.stringify(a.snapshot())
+ a.run(30)
+ const b = town({ size: "medium", term: 60, land: "harsh", seed: 11 })
+ b.restore(JSON.parse(saved))
+ b.run(30)
+ const same = JSON.stringify(a.snapshot().resources["Town/Treasury"]) === JSON.stringify(b.snapshot().resources["Town/Treasury"]) &&
+ a.snapshot().entities.length === b.snapshot().entities.length
+ check("save and load", same, `${a.snapshot().entities.length} entities, ${a.snapshot().resources["Town/Treasury"].coins} coins either way`)
+}
+
+console.log(failures === 0 ? "\nall ends hold" : `\n${failures} failed`)
+if (failures > 0) process.exit(1)
diff --git a/src/art.ts b/src/art.ts
index 999806f..c3c43e2 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -65,6 +65,7 @@ export type Emphasis = "normal" | "danger"
/** The layers of the town, back to front. */
export interface Stage {
readonly world: Container
+ readonly floor: Graphics
readonly ground: Graphics
readonly plates: Container
readonly roads: Graphics
@@ -881,17 +882,57 @@ export class WalkerView extends Graphics {
// ── The floor ─────────────────────────────────────────────────────────────
-/** The grid: a faint line between every two cells, and the map's edge. */
-export const drawFloor = (g: Graphics) => {
- for (let i = 1; i < GRID; i++) {
- const a = toScreen(i, 0)
- const b = toScreen(i, GRID)
- const c = toScreen(0, i)
- const d = toScreen(GRID, i)
- g.moveTo(a.x, a.y).lineTo(b.x, b.y).moveTo(c.x, c.y).lineTo(d.x, d.y)
+/** The open water the land stands in: the page's background. */
+export const seaFill = 0xe2e9e6
+const landFill = 0xf0f2ec
+
+/**
+ * The land (`mask`: "1" for land, by `key`): pale ground, a faint line
+ * between every two cells of it, and an ink coastline.
+ */
+export const drawFloor = (g: Graphics, mask: string) => {
+ const 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++) {
+ for (let x = 0; x < GRID; x++) {
+ if (!land(x, y)) continue
+ g.poly(flat([toScreen(x, y), toScreen(x + 1, y), toScreen(x + 1, y + 1), toScreen(x, y + 1)])).fill({ color: landFill })
+ }
+ }
+ // Grid lines: each cell's far edges, where its neighbour is land too.
+ for (let y = 0; y < GRID; y++) {
+ for (let x = 0; x < GRID; x++) {
+ if (!land(x, y)) continue
+ if (land(x + 1, y)) {
+ const a = toScreen(x + 1, y)
+ const b = toScreen(x + 1, y + 1)
+ g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ }
+ if (land(x, y + 1)) {
+ const a = toScreen(x, y + 1)
+ const b = toScreen(x + 1, y + 1)
+ g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ }
+ }
}
g.stroke({ color: 0xe0e3db, width: DETAIL })
- outline(g, [toScreen(0, 0), toScreen(GRID, 0), toScreen(GRID, GRID), toScreen(0, GRID)], LINE, 0xb9bfb4)
+ for (let y = 0; y < GRID; y++) {
+ for (let x = 0; x < GRID; x++) {
+ if (!land(x, y)) continue
+ const edges: ReadonlyArray<readonly [Point, Point, Point]> = [
+ [DIRS[0]!, { x: x + 1, y }, { x: x + 1, y: y + 1 }],
+ [DIRS[1]!, { x, y: y + 1 }, { x: x + 1, y: y + 1 }],
+ [DIRS[2]!, { x, y }, { x, y: y + 1 }],
+ [DIRS[3]!, { x, y }, { x: x + 1, y }]
+ ]
+ for (const [d, p, q] of edges) {
+ if (land(x + d.x, y + d.y)) continue
+ const a = toScreen(p.x, p.y)
+ const b = toScreen(q.x, q.y)
+ g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ }
+ }
+ }
+ g.stroke({ color: ink, width: LINE, alpha: 0.75, cap: "square" })
}
/**
diff --git a/src/content.ts b/src/content.ts
index 792a284..fe6bf4e 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -36,7 +36,8 @@ export const goods: Readonly<Record<GoodId, { readonly title: string; readonly c
*/
export const TRADE_LOAD = 12
export const RESERVES = [10, 25, 50, 100] as const
-export const trade = { sells: ["wood", "stone", "wheat", "wool"] as ReadonlyArray<GoodId>, reserve: 25 }
+/** A new town sells its surplus wood, wheat, and wool. Stone is finite: it is not sold until the town says so. */
+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 }
@@ -216,7 +217,7 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
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: 8 },
+ holds: { accepts: ["fish", "bread", "cloth"], cap: 12 },
service: { service: "goods", seconds: 6, range: 18 }
},
chapel: {
@@ -252,16 +253,11 @@ export const home = {
/** 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(60), cloth: ticks(150), faith: ticks(90) } as Readonly<Record<Need, number>>
+ lasts: { food: ticks(60), bread: ticks(90), cloth: ticks(180), faith: ticks(150) } as Readonly<Record<Need, number>>
}
/** Tax rates the town can set, in percent of the usual. */
export const TAX_STEPS = [50, 75, 100, 125, 150, 200] as const
-/**
- * How a tax rate sits with residents: low taxes make homes hold more people
- * than their needs alone allow, high ones fewer. 100% is neutral.
- */
-export const appealOf = (rate: number): number => 1.5 - rate / 200
export const needTitle: Readonly<Record<Need, string>> = { food: "food", bread: "bread", cloth: "cloth", faith: "faith" }
@@ -272,11 +268,163 @@ export const BUILD_TICKS = ticks(2.4)
/** Taxes are collected and upkeep paid this often. */
export const LEDGER_TICKS = ticks(10)
export const ROAD_COST = 2
-/** A new town's treasury and the goods in its town hall. */
-export const start = {
- coins: 1500,
- stock: amounts({ wood: 10, planks: 40, stone: 16, tools: 8, fish: 20 })
-}
/** Trees and fields are ready to harvest once this grown. */
export const GROWN = { tree: ticks(40), field: ticks(20) }
+/** The most a rock holds (see `lands` for how much each starts with). */
export const ROCK_AMOUNT = 40
+
+// ── The charter: what a new town is founded on ────────────────────────────
+
+export const sizeIds = ["small", "medium", "large"] as const
+export type SizeId = (typeof sizeIds)[number]
+export const landIds = ["rich", "fair", "harsh"] as const
+export type LandId = (typeof landIds)[number]
+/** How long a term in office runs, in minutes of game time. */
+export const TERMS = [45, 60, 90] as const
+
+/**
+ * Sizes of land: its rough radius in cells (the coast wanders in and out of
+ * it, with capes reaching further), and what the town must reach to be
+ * complete (see `Fate`).
+ */
+export const sizes: Readonly<Record<SizeId, {
+ readonly title: string
+ readonly radius: number
+ readonly goal: { readonly residents: number; readonly coins: number }
+}>> = {
+ small: { title: "small", radius: 14, goal: { residents: 180, coins: 2500 } },
+ medium: { title: "medium", radius: 19, goal: { residents: 320, coins: 4000 } },
+ large: { title: "large", radius: 25, goal: { residents: 520, coins: 6000 } }
+}
+
+/**
+ * How generous the land is: forests, outcrops of stone, deposits of ore
+ * (each per thousand cells of land), how much each rock holds, lakes, and
+ * what the town starts with.
+ */
+export const lands: Readonly<Record<LandId, {
+ readonly title: string
+ readonly blurb: string
+ readonly forests: number
+ readonly stone: number
+ readonly ore: number
+ readonly rock: number
+ readonly lakes: number
+ readonly coins: number
+ readonly stock: Amounts
+}>> = {
+ 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,
+ 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,
+ 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,
+ stock: amounts({ wood: 10, planks: 30, stone: 12, tools: 6, fish: 15 })
+ }
+}
+
+export interface CharterValue {
+ readonly size: SizeId
+ readonly term: number
+ readonly land: LandId
+ readonly seed: number
+}
+export const defaultCharter = (seed: number): CharterValue => ({ size: "medium", term: 60, land: "fair", seed })
+
+// ── Pressure ──────────────────────────────────────────────────────────────
+
+/**
+ * Seasons: a term is six years; the last part of each but the first is
+ * winter, when fields do not grow, fisheries catch half as much, and homes
+ * eat faster.
+ */
+export const YEARS_PER_TERM = 6
+export const WINTER_SHARE = 0.3
+
+/**
+ * Running a town costs more the bigger it gets: the town hall's
+ * administration costs `perHome` coins a minute a home, and a further
+ * (homes / `growth`) a home, so a large town of poor homes cannot pay
+ * its way.
+ */
+export const admin = { perHome: 0.5, growth: 200 }
+
+/**
+ * Approval, -100 → +100: where the town's mood is heading, and how fast it
+ * gets there (points every collection). Homes hold more residents when it
+ * is high and fewer when it is low (see `capacity`).
+ */
+export const mood = {
+ base: 10,
+ /** At no needs met to every need met. */
+ needs: [-35, 30] as const,
+ /** Points for each percent the average tax rate is below (or above) 100%. */
+ perTaxPoint: 0.4,
+ debt: -20,
+ /** Per unanswered crown request, while the crown remembers it. */
+ snub: -20,
+ winterHunger: -10,
+ step: 2
+}
+
+/**
+ * Crown requests: every so often the crown asks for goods within a time.
+ * Requests grow as the term goes on. Sending them earns coins; missing one
+ * costs a fine and the crown's goodwill for a while.
+ */
+export const crown = {
+ /** Requests in a term. */
+ perTerm: 9,
+ /** Share of the gap between requests the town has to answer one. */
+ window: 0.6,
+ /**
+ * How much it asks for: this share of what the town could make of the
+ * good in the time given, from the start of the term to its end.
+ */
+ share: [0.25, 0.6] as const,
+ /** Nor more than this share of what the town's storage holds of one good. */
+ room: 0.6,
+ /** Reward as a multiple of what the goods would fetch from traders, plus a bonus; the fine is the goods' worth plus the bonus. */
+ reward: 2,
+ fine: 1,
+ bonus: 50,
+ /** How long the crown remembers a missed request, in minutes. */
+ memory: 4
+}
+
+/**
+ * The market: each good's price moves with what the town trades. Selling
+ * drives it down, buying up; it drifts back by a tenth of the gap every
+ * collection. Buying costs half again the price.
+ */
+export const market = { floor: 30, ceiling: 250, perUnit: 1, markup: 1.5 }
+
+/** A paused building pays this share of its upkeep. */
+export const PAUSED_UPKEEP = 0.25
+
+/** How long each end state's danger has to last, in minutes, before the term ends with it. */
+export const fate = {
+ /** Victory: every goal held this long. */
+ hold: 2,
+ /** Bankruptcy: in debt this long without a break. */
+ debt: 3,
+ /** Revolt: approval at or below `revolt` this long. */
+ revolt: 2,
+ revoltAt: -50,
+ /** Abandonment: residents below this share of their peak, once the peak reached `peak`. */
+ abandon: 0.15,
+ peak: 40,
+ /** The goals besides residents and coins: a share of them citizens, and approval. */
+ citizens: 0.4,
+ approval: 20
+}
+
+/** The town's history: a sample this often. */
+export const HISTORY_TICKS = ticks(15)
diff --git a/src/factory.css b/src/factory.css
index da9d514..9351218 100644
--- a/src/factory.css
+++ b/src/factory.css
@@ -103,3 +103,79 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
.panel .need .count { text-align: right; }
.panel .good-row { cursor: pointer; }
.panel .good-row input { margin: 0 8px 0 0; accent-color: #3d4943; vertical-align: -2px; }
+
+/* ── The term: season, approval, the crown, dangers ── */
+.hud .clock .winter { color: #3d6db5; font-weight: 600; }
+.hud .request, .hud .alarm { display: none; }
+.hud .request.show, .hud .alarm.show { display: flex; }
+.hud .request { border-color: #d6ae2e; box-shadow: 0 2px 0 #eadca7; }
+.hud .request .send {
+ font: inherit; font-size: 12px; margin: 4px 6px 4px 0; padding: 2px 12px; border: 1px solid #3d4943; border-radius: 3px;
+ background: #3d4943; color: #f7f8f4; cursor: pointer;
+}
+.hud .request .send:disabled { background: transparent; color: #8a938c; border-color: #c9cec4; cursor: default; }
+.hud .alarm { flex-direction: column; border-color: #b04a39; box-shadow: 0 2px 0 #e6c3bc; color: #b04a39; white-space: normal; }
+.hud .alarm .cell + .cell { border-left: 0; border-top: 1px solid #ecd2cc; }
+.hud .alarm.good { border-color: #4f8a3e; box-shadow: 0 2px 0 #cfe0c5; color: #4f8a3e; }
+
+.panel .meter { position: relative; height: 6px; border: 1px solid #c9cec4; margin: 4px 0 10px; }
+.panel .meter::after { content: ""; position: absolute; left: 50%; top: -3px; bottom: -3px; border-left: 1px solid #77817a; }
+.panel .meter .fill { position: absolute; top: 0; bottom: 0; background: #4f8a3e; }
+.panel .meter .fill.low { background: #b04a39; }
+.panel .goal .mark { display: inline-block; width: 2ch; color: #8a938c; }
+.panel .goal.met .mark { color: #4f8a3e; font-weight: 700; }
+.panel .goal.met { color: #4f8a3e; }
+.panel .frame.mode { padding: 1px 0; width: 5ch; margin-right: 8px; font-size: 12px; text-align: center; color: #8a938c; border-color: #c9cec4; }
+.panel .frame.mode.on { color: #3d4943; border-color: #3d4943; font-weight: 600; }
+.chronicle p { margin: 0 0 6px; font-size: 12px; color: #4f5a53; line-height: 1.45; }
+.chronicle p b { display: inline-block; min-width: 5ch; color: #8a938c; font-weight: 400; }
+
+/* ── Dialogs: founding a town, and the reckoning at the end of its term ── */
+.dialog {
+ position: fixed; inset: 0; display: none; align-items: center; justify-content: center; padding: 16px;
+ background: rgba(226, 233, 230, 0.72); z-index: 10;
+}
+.dialog.open { display: flex; }
+.dialog .sheet {
+ background: #f1f3ed; border: 1px solid #c3c8bf; border-radius: 6px; box-shadow: 0 3px 0 #d5d9d0; padding: 22px 26px;
+ width: 640px; max-width: 100%; max-height: calc(100vh - 32px); overflow-y: auto; box-sizing: border-box; font-size: 14px;
+}
+.dialog .sheet.wide { width: 720px; }
+.dialog h2 { margin: 0 0 6px; font-size: 18px; }
+.dialog .sub { margin: 0 0 10px; color: #6c766f; line-height: 1.45; }
+.dialog section { margin-top: 16px; }
+.dialog h3 {
+ margin: 0 0 8px; padding-bottom: 6px; border-bottom: 2px solid #d3d7ce; font-size: 11px; font-weight: 400;
+ letter-spacing: 0.12em; text-transform: uppercase; color: #77817a;
+}
+.dialog .empty { margin: 6px 0 0; color: #8a938c; font-size: 12px; }
+.dialog .row { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
+.dialog button { font: inherit; color: inherit; cursor: pointer; }
+.dialog .frame { background: transparent; border: 1px solid #3d4943; border-radius: 2px; padding: 6px 12px; white-space: nowrap; }
+.dialog .frame:hover { background: #e6e9e2; }
+.dialog .frame.primary { background: #3d4943; color: #f7f8f4; }
+.dialog .actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 22px; }
+.dialog .charter { display: grid; grid-template-columns: 1fr 200px; gap: 22px; }
+.dialog .choices { display: flex; gap: 6px; flex-wrap: wrap; }
+.dialog .choice { border-color: #c9cec4; color: #6c766f; }
+.dialog .choice.on { border-color: #3d4943; color: #3d4943; font-weight: 700; background: #e6e9e2; }
+.dialog .preview { display: flex; flex-direction: column; gap: 8px; }
+.dialog .preview canvas { width: 192px; height: 192px; background: #e2e9e6; border: 1px solid #c9cec4; image-rendering: pixelated; }
+.dialog .preview .sub { font-size: 12px; }
+.dialog .facts { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 10px; margin: 14px 0; }
+.dialog .fact { display: flex; flex-direction: column; border-left: 2px solid #d3d7ce; padding-left: 8px; }
+.dialog .fact b { font-size: 18px; }
+.dialog .fact span { font-size: 11px; color: #77817a; }
+.dialog .chart svg { width: 100%; height: 150px; display: block; border-bottom: 1px solid #d3d7ce; }
+.dialog .legend { margin: 4px 0 12px; font-size: 11px; color: #77817a; }
+.dialog .chronicle { max-height: 180px; overflow-y: auto; border-top: 1px solid #e0e3db; padding-top: 10px; }
+@media (max-width: 600px) {
+ .dialog .charter { grid-template-columns: 1fr; }
+ .dialog .sheet { padding: 16px; }
+}
+
+.result {
+ position: fixed; top: 12px; right: 16px; display: none; font: inherit; font-size: 12px; padding: 7px 12px; z-index: 5;
+ background: #3d4943; color: #f7f8f4; border: 0; border-radius: 4px; cursor: pointer; box-shadow: 0 2px 0 #c9cec4;
+}
+.result.show { display: block; }
diff --git a/src/grid.ts b/src/grid.ts
index 9550e8b..6bf0171 100644
--- a/src/grid.ts
+++ b/src/grid.ts
@@ -21,11 +21,19 @@ export interface TileLike {
export type { Use }
-/** A grid being filled in: tiles are claimed one by one, and placement checks see the claims so far. */
+/**
+ * A grid being filled in: tiles are claimed one by one, and placement checks
+ * see the claims so far. Cells off the land (`mask`, "0" by `key`) are void.
+ */
export class GridBuilder {
readonly owner: Array<number> = new Array(GRID * GRID).fill(0)
readonly use: Array<Use> = new Array(GRID * GRID).fill("empty")
+ constructor(mask?: string) {
+ if (mask === undefined) return
+ for (let k = 0; k < GRID * GRID; k++) if (mask[k] !== "1") this.use[k] = "void"
+ }
+
claim(tile: TileLike, id: number, use: Use) {
for (const c of cellsOf(tile)) {
const k = key(c.x, c.y)
@@ -53,7 +61,7 @@ export const cellsOf = (tile: TileLike): Array<Point> => {
return out
}
-export const useAt = (grid: GridValue, x: number, y: number): Use => (inside(x, y) ? grid.use[key(x, y)]! : "water")
+export const useAt = (grid: GridValue, x: number, y: number): Use => (inside(x, y) ? grid.use[key(x, y)]! : "void")
export const ownerAt = (grid: GridValue, x: number, y: number): number => (inside(x, y) ? grid.owner[key(x, y)]! : 0)
export const isRoad = (grid: GridValue, x: number, y: number): boolean => inside(x, y) && grid.use[key(x, y)] === "road"
@@ -110,7 +118,41 @@ export interface Reach {
readonly previous: Int32Array
}
+/** A fingerprint of where the roads are: paths found on one road network hold until it changes. */
+export const roadPrint = (grid: GridValue): number => {
+ let h = 0x811c9dc5
+ for (let k = 0; k < grid.use.length; k++) {
+ if (grid.use[k] !== "road") continue
+ h = Math.imul(h ^ k, 0x01000193) >>> 0
+ }
+ return h
+}
+
+/** Reaches found on the current road network, by where they start. */
+const reaches = new Map<string, Reach>()
+let reachesFor: number | undefined
+
+/**
+ * Distances along the road from a set of road cells. On a grid with a road
+ * fingerprint the answer is kept until the roads change: every carrier
+ * leaving the same door would otherwise search the whole network again.
+ */
export const reach = (grid: GridValue, from: ReadonlyArray<Point>): Reach => {
+ if (grid.roads === undefined) return search(grid, from)
+ if (reachesFor !== grid.roads) {
+ reaches.clear()
+ reachesFor = grid.roads
+ }
+ const id = from.map((c) => key(c.x, c.y)).join(",")
+ const known = reaches.get(id)
+ if (known) return known
+ if (reaches.size > 2048) reaches.clear()
+ const found = search(grid, from)
+ reaches.set(id, found)
+ return found
+}
+
+const search = (grid: GridValue, from: ReadonlyArray<Point>): Reach => {
const distance = new Int32Array(GRID * GRID).fill(-1)
const previous = new Int32Array(GRID * GRID).fill(-1)
const queue: Array<number> = []
diff --git a/src/host.ts b/src/host.ts
index f575be4..714b5d6 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -1,17 +1,20 @@
/**
* The page around the town: the Pixi stage and its layers, the camera (drag
* to pan, wheel or pinch to zoom), the pointer turned into gestures, and the
- * top bar, toolbar, build menu, panel, tooltip, and toasts.
+ * top bar, toolbar, build menu, panel, tooltip, and toasts; the dialog a new
+ * town is founded from, and the reckoning at the end of its term.
*/
import { Application, Container, Graphics } from "pixi.js"
-import { drawFloor, type Stage } from "./art.ts"
+import { seaFill, type Stage } from "./art.ts"
import {
- appealOf, categoryColor, categoryOrder, costText, goodIds, goods, home, kindOrder, kinds, needTitle, RESERVES, ROAD_COST, TAX_STEPS,
- type GoodId, type Kind, type KindId
+ categoryColor, categoryOrder, costText, defaultCharter, goodIds, goods, home, kindOrder, kinds, landIds, lands, mood as moodRules, needTitle,
+ RESERVES, ROAD_COST, sizeIds, sizes, TAX_STEPS, TERMS, type CharterValue, type GoodId, type Kind, type KindId
} from "./content.ts"
import { GRID, toScreen, type Point } from "./iso.ts"
-import type { Tool, UiValue } from "./ui.ts"
+import { generate } from "./mapgen.ts"
+import { askOf, priceOf } from "./sim/index.ts"
+import type { Stats, Tool, TradeMode, UiValue } from "./ui.ts"
import { emptyPreview } from "./ui.ts"
const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") => {
@@ -22,6 +25,9 @@ const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, te
}
const hex = (color: number) => `#${color.toString(16).padStart(6, "0")}`
+/** Seconds as m:ss. */
+const clockText = (seconds: number) => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`
+const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`
export interface Persistence {
readonly save: () => string | null
@@ -33,7 +39,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
await app.init({
resizeTo: window,
antialias: true,
- background: 0xf0f2ec,
+ background: seaFill,
resolution: Math.min(window.devicePixelRatio || 1, 2),
autoDensity: true
})
@@ -42,7 +48,6 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
// ── Layers ──
const world = new Container()
const floor = new Graphics()
- drawFloor(floor)
const ground = new Graphics()
const plates = new Container()
const roads = new Graphics()
@@ -56,7 +61,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const labels = new Container()
world.addChild(floor, ground, plates, roads, preview, objects, labels)
app.stage.addChild(world)
- const stage: Stage = { world, ground, plates, roads, preview, objects, labels, overlay, ghost }
+ const stage: Stage = { world, floor, ground, plates, roads, preview, objects, labels, overlay, ghost }
// ── Camera ──
const centre = toScreen(GRID / 2, GRID / 2)
@@ -91,7 +96,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const coins = el("div", "cell coins")
const people = el("div", "cell")
const jobs = el("div", "cell")
- bar.append(coins, people, jobs)
+ const clock = el("div", "cell clock")
+ const approval = el("div", "cell")
+ bar.append(clock, coins, approval, people, jobs)
const stock = el("div", "card stock")
const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [["wood", "planks", "stone", "tools"], ["fish", "bread"], ["wool", "cloth"]]
const goodCells = new Map<GoodId, HTMLElement>()
@@ -108,14 +115,28 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
stock.append(cell)
}
- hud.append(bar, stock)
- hud.title = "Open the town's numbers and taxes"
+ // The crown's request, when there is one, and what threatens (or is about to complete) the term.
+ const request = el("div", "card request")
+ const requestText = el("div", "cell")
+ const send = el("button", "send", "send")
+ send.onclick = (event) => {
+ event.stopPropagation()
+ ui.edits.push({ type: "deliver" })
+ }
+ request.append(requestText, send)
+ const alarm = el("div", "card alarm")
+ hud.append(bar, stock, request, alarm)
+ hud.title = "Open the town's numbers, goals, and levers"
hud.onclick = () => toggleMenu("town")
const tooltip = el("div", "tooltip")
const toastBox = el("div", "toast")
const toolbar = el("div", "toolbar")
const panel = el("aside", "panel")
- document.body.append(hud, tooltip, toastBox, toolbar, panel)
+ const dialog = el("div", "dialog")
+ const reckoning = el("div", "dialog")
+ const result = el("button", "result", "")
+ result.onclick = () => showReckoning(true)
+ document.body.append(hud, tooltip, toastBox, toolbar, panel, result, dialog, reckoning)
let toastTimer = 0
const ui: UiValue = {
@@ -126,12 +147,15 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
dragFrom: null,
selected: null,
gestures: [],
- edits: [{ type: "newTown", seed: (Date.now() & 0x7fffffff) >>> 0 }],
+ // A town is founded behind the dialog, so there is land to look at while choosing.
+ edits: [{ type: "newTown", charter: defaultCharter((Date.now() & 0x7fffffff) >>> 0) }],
preview: emptyPreview(),
hits: [],
panel: null,
centres: new Map(),
stats: null,
+ speed: 1,
+ founding: true,
toast: (message) => {
toastBox.textContent = message
toastBox.classList.add("show")
@@ -160,17 +184,33 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
return { tool, button }
})
toolbar.append(el("span", "sep"))
+ const speeds = [
+ { speed: 0, label: "pause", key: "space" },
+ { speed: 1, label: "1×", key: "1" },
+ { speed: 2, label: "2×", key: "2" },
+ { speed: 4, label: "4×", key: "3" }
+ ].map(({ speed, label, key }) => {
+ const button = el("button", "", label)
+ button.title = speed === 0 ? "Pause the town (space)" : `Run the town at ${label} (${key})`
+ button.onclick = () => setSpeed(speed)
+ toolbar.append(button)
+ return { speed, button }
+ })
+ let lastSpeed = 1
+ const setSpeed = (speed: number) => {
+ if (speed > 0) lastSpeed = speed
+ ui.speed = speed
+ for (const s of speeds) s.button.classList.toggle("on", s.speed === speed)
+ }
+ setSpeed(1)
+ toolbar.append(el("span", "sep"))
const action = (label: string, tip: string, run: () => void) => {
const button = el("button", "", label)
button.title = tip
button.onclick = run
toolbar.append(button)
}
- action("new town", "Found a new town on new land", () => {
- ui.edits.push({ type: "newTown", seed: (Date.now() & 0x7fffffff) >>> 0 })
- history.length = 0
- choose("select")
- })
+ action("new town", "Found a new town on new land", () => openCharter(true))
action("save", "Save the town in this browser", () => ui.toast(persistence().save() ?? "Saved"))
action("load", "Load the saved town", () => ui.toast(persistence().load() ?? "Loaded"))
@@ -201,6 +241,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
choose("select")
window.addEventListener("keydown", (event) => {
+ if (ui.founding || reckoning.classList.contains("open")) return
+ if (event.key === " ") {
+ event.preventDefault()
+ setSpeed(ui.speed === 0 ? lastSpeed : 0)
+ }
+ if (event.key === "1") setSpeed(1)
+ if (event.key === "2") setSpeed(2)
+ if (event.key === "3") setSpeed(4)
if (event.key === "Escape") {
if (ui.tool !== "select") choose("select")
else if (ui.menu) ui.menu = null
@@ -325,13 +373,32 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const sub = el("p", "sub")
panel.append(sub)
+ // The goals that complete the town, and how near each one is.
+ const goals = section("to complete the town")
+ const goalNote = el("p", "empty")
+ goals.append(goalNote)
+ const goalRows: Array<{ line: HTMLElement; mark: HTMLElement; text: HTMLElement; value: HTMLElement }> = []
+ panel.append(goals)
+
+ const mood = section("approval")
+ const moodLine = el("div", "row")
+ const moodValue = el("span", "count")
+ moodLine.append(el("span", "", "now, heading for"), moodValue)
+ const moodTrack = el("div", "meter")
+ const moodFill = el("span", "fill")
+ moodTrack.append(moodFill)
+ const moodParts = el("div", "")
+ mood.append(moodLine, moodTrack, moodParts, el("p", "empty", `Homes hold more residents when approval is high and fewer when it is low. At −50 for two minutes, the town turns the mayor out.`))
+ panel.append(mood)
+
const treasury = section("treasury")
const taxes = row(treasury, "taxes")
const traded = row(treasury, "trade")
const upkeep = row(treasury, "upkeep")
+ const admin = row(treasury, "administration")
const net = row(treasury, "a minute")
const coinLine = el("div", "spark")
- treasury.append(coinLine)
+ treasury.append(coinLine, el("p", "empty", "Administration grows faster than the town. Three minutes in debt and the town is bankrupt."))
panel.append(treasury)
const levers = section("taxes")
@@ -356,12 +423,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
live.push(() => {
const rate = ui.stats?.policy[tier] ?? 100
value.textContent = `${rate}%`
- const appeal = Math.round((appealOf(rate) - 1) * 100)
- effect.textContent = appeal === 0
- ? "the usual rate"
- : appeal > 0
- ? `homes keep up to ${appeal}% more residents when short of needs`
- : `homes hold ${-appeal}% fewer residents`
+ const sway = Math.round((100 - rate) * moodRules.perTaxPoint)
+ effect.textContent = sway === 0 ? "the usual rate" : `${sway > 0 ? "+" : ""}${sway} approval from ${tier} (weighed by how many there are)`
})
}
panel.append(levers)
@@ -387,8 +450,15 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
needs.append(line)
return { n, fill, value }
})
+ const larderLine = row(needs, "food in store")
panel.append(needs)
+ const crown = section("the crown")
+ const crownLine = row(crown, "requests met · missed")
+ const crownNext = el("p", "empty")
+ crown.append(crownNext)
+ panel.append(crown)
+
const store = section("goods and trade")
const reserveLine = el("div", "row lever")
const reserveControls = el("span", "controls")
@@ -396,7 +466,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const reserveValue = el("span", "rate")
const more = el("button", "frame step", "+")
reserveControls.append(fewer, reserveValue, more)
- reserveLine.append(el("span", "", "keep before selling"), reserveControls)
+ reserveLine.append(el("span", "", "keep in store"), reserveControls)
store.append(reserveLine)
const stepReserve = (by: number) => {
const now = ui.stats?.policy.reserve ?? 25
@@ -405,30 +475,75 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
fewer.onclick = () => stepReserve(-1)
more.onclick = () => stepReserve(1)
- store.append(el("p", "empty", "Ticked goods are sold to traders beyond what the town keeps, for the price shown."))
+ store.append(el("p", "empty", "Traders buy what the town sells beyond what it keeps, and sell it what it buys up to that, at half again the price. Prices fall as the town sells and rise as it buys."))
+ const modes: ReadonlyArray<TradeMode> = ["none", "sell", "buy"]
const goodRows = goodIds.map((g) => {
- const line = el("label", "row good-row")
- const box = el("input", "")
- box.type = "checkbox"
- box.onchange = () => ui.edits.push({ type: "sell", good: g, on: box.checked })
- const name = el("span", "", `${goods[g].title} · ${goods[g].price}c`)
+ const line = el("div", "row good-row")
+ const mode = el("button", "frame mode", "")
+ mode.onclick = () => {
+ const s = ui.stats
+ if (!s) return
+ const now: TradeMode = s.policy.sells.includes(g) ? "sell" : s.policy.buys.includes(g) ? "buy" : "none"
+ ui.edits.push({ type: "trade", good: g, mode: modes[(modes.indexOf(now) + 1) % modes.length]! })
+ }
+ const name = el("span", "")
const left = el("span", "")
- left.append(box, name)
+ left.append(mode, name)
const value = el("span", "count")
line.append(left, value)
store.append(line)
- return { g, value, box }
+ return { g, value, mode, name }
})
panel.append(store)
+ const chronicle = section("chronicle")
+ const lines = el("div", "chronicle")
+ chronicle.append(lines)
+ panel.append(chronicle)
+
live.push(() => {
const s = ui.stats
if (!s) return
- sub.textContent = `${s.settlers + s.citizens} residents · ${s.coins} coins`
+ sub.textContent = `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · a ${s.charter.term}-minute term · seed ${s.charter.seed}`
+ // Goals.
+ while (goalRows.length < s.goals.length) {
+ const line = el("div", "row goal")
+ const mark = el("span", "mark")
+ const text = el("span", "")
+ const value = el("span", "count")
+ const left = el("span", "")
+ left.append(mark, text)
+ line.append(left, value)
+ goals.append(line)
+ goalRows.push({ line, mark, text, value })
+ }
+ s.goals.forEach((g, i) => {
+ const r = goalRows[i]!
+ r.mark.textContent = g.met ? "✓" : "·"
+ r.line.classList.toggle("met", g.met)
+ r.text.textContent = g.text
+ r.value.textContent = g.value
+ })
+ goalNote.textContent = s.fate.governing
+ ? "Complete: the mayor governs on to the end of the term."
+ : s.fate.complete !== null
+ ? `Every goal is met: hold them ${clockText(s.fate.complete)} more.`
+ : `Meet every goal at once and hold them for two minutes to complete the town.`
+ // Approval.
+ moodValue.textContent = `${signed(s.mood.approval)} → ${signed(s.mood.target)}`
+ moodFill.style.left = `${Math.min(50, 50 + s.mood.approval / 2)}%`
+ moodFill.style.width = `${Math.abs(s.mood.approval) / 2}%`
+ moodFill.classList.toggle("low", s.mood.approval < 0)
+ const parts = s.mood.parts.map((p) => `<div class="row"><span>${p.label}</span><span class="count">${signed(p.value)}</span></div>`).join("")
+ if (moodParts.dataset.html !== parts) {
+ moodParts.dataset.html = parts
+ moodParts.innerHTML = parts
+ }
taxes.textContent = `+${s.taxes}`
- traded.textContent = `+${s.trade}`
- upkeep.textContent = `−${s.upkeep}`
- net.textContent = `${s.net >= 0 ? "+" : ""}${s.net} coins`
+ traded.textContent = signed(s.trade)
+ upkeep.textContent = signed(-s.upkeep)
+ admin.textContent = signed(-s.admin)
+ net.textContent = `${signed(s.net)} coins`
settlers.textContent = String(s.settlers)
citizens.textContent = String(s.citizens)
homes.textContent = String(s.homes)
@@ -438,25 +553,39 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
b.fill.style.width = `${Math.round(share * 100)}%`
b.value.textContent = `${s.needs[b.n]} of ${s.homes}`
}
+ larderLine.textContent = `${s.larder} fish and bread`
+ crownLine.textContent = `${s.crown.met} · ${s.crown.missed}`
+ crownNext.textContent = s.crown.open
+ ? `Asking for ${s.crown.amount} ${goods[s.crown.good].title}: ${clockText(s.crown.left)} left, ${s.crown.reward} coins when sent.`
+ : `The next request in ${clockText(s.crown.next)}. A missed one is a fine, and the town remembers the snub for a while.`
// Goods' change over the last minute of samples.
const ago = history[Math.max(0, history.length - 1 - Math.round(60 / SAMPLE_SECONDS))]
reserveValue.textContent = String(s.policy.reserve)
for (const r of goodRows) {
const change = ago ? s.stock[r.g] - ago.stock[r.g] : 0
r.value.textContent = `${s.stock[r.g]}${change !== 0 ? ` ${change > 0 ? "+" : ""}${change}/min` : ""}`
- const selling = s.policy.sells.includes(r.g)
- if (r.box.checked !== selling) r.box.checked = selling
+ const now: TradeMode = s.policy.sells.includes(r.g) ? "sell" : s.policy.buys.includes(r.g) ? "buy" : "none"
+ r.mode.textContent = now === "none" ? "—" : now
+ r.mode.classList.toggle("on", now !== "none")
+ const price = now === "buy" ? askOf(r.g, s.prices[r.g]) : Math.round(priceOf(r.g, s.prices[r.g]) * 10) / 10
+ r.name.textContent = `${goods[r.g].title} · ${price}c${s.prices[r.g] !== 100 ? ` (${s.prices[r.g]}%)` : ""}`
}
- const coinsSvg = sparkline(history.map((h) => h.coins))
+ const samples = s.history
+ const coinsSvg = sparkline(samples.map((h) => h.coins))
if (coinLine.dataset.svg !== coinsSvg) {
coinLine.dataset.svg = coinsSvg
coinLine.innerHTML = coinsSvg
}
- const peopleSvg = sparkline(history.map((h) => h.residents))
+ const peopleSvg = sparkline(samples.map((h) => h.residents))
if (peopleLine.dataset.svg !== peopleSvg) {
peopleLine.dataset.svg = peopleSvg
peopleLine.innerHTML = peopleSvg
}
+ const recent = s.chronicle.slice(-10).reverse().map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`).join("")
+ if (lines.dataset.html !== recent) {
+ lines.dataset.html = recent
+ lines.innerHTML = recent
+ }
})
}
@@ -490,6 +619,21 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
})
if (!(p.type === "building" && p.kind === "townhall")) {
const actions = el("div", "actions")
+ if (p.type === "building") {
+ const pause = el("button", "frame", "Pause work")
+ pause.title = "A paused building has no workers and pays a quarter of its upkeep"
+ pause.onclick = () => {
+ const now = ui.panel
+ if (now?.type === "building") ui.edits.push({ type: "pause", cell: now.cell, on: !now.paused })
+ }
+ live.push(() => {
+ const now = ui.panel
+ if (now?.type !== "building") return
+ pause.textContent = now.paused ? "Resume work" : "Pause work"
+ pause.style.display = now.pausable ? "" : "none"
+ })
+ actions.append(pause)
+ }
const remove = el("button", "frame danger", "Remove")
remove.onclick = () => ui.edits.push({ type: "remove", cell: p.cell })
actions.append(remove)
@@ -511,6 +655,208 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
for (const update of live) update()
}
+ // ── Founding a town ──
+ const choice: { -readonly [K in keyof CharterValue]: CharterValue[K] } = defaultCharter((Date.now() & 0x7fffffff) >>> 0)
+ /** The land a charter would found, drawn small: a dot a cell. */
+ const drawLand = (canvas: HTMLCanvasElement) => {
+ const land = generate(choice)
+ const water = new Set(land.water.map((c) => c.y * GRID + c.x))
+ const trees = new Set(land.trees.map((t) => t.cell.y * GRID + t.cell.x))
+ const rocks = new Map(land.rocks.map((r) => [r.cell.y * GRID + r.cell.x, r.ore]))
+ const scale = 3
+ canvas.width = GRID * scale
+ canvas.height = GRID * scale
+ const g = canvas.getContext("2d")!
+ g.clearRect(0, 0, canvas.width, canvas.height)
+ for (let y = 0; y < GRID; y++) {
+ for (let x = 0; x < GRID; x++) {
+ const k = y * GRID + x
+ if (land.mask[k] !== "1") continue
+ g.fillStyle = water.has(k) ? "#b9cfcb" : trees.has(k) ? "#9bb08a" : rocks.has(k) ? (rocks.get(k) ? "#5a6479" : "#8f9891") : "#f7f8f4"
+ g.fillRect(x * scale, y * scale, scale, scale)
+ }
+ }
+ return land
+ }
+ const openCharter = (cancellable: boolean) => {
+ ui.founding = true
+ dialog.replaceChildren()
+ const card = el("div", "sheet")
+ card.append(el("h2", "", "found a town"), el("p", "sub", "Choose the land and how long the term runs. Grow the town until it is complete, or keep it from bankruptcy, revolt, and ruin until the term is out."))
+ const body = el("div", "charter")
+ const options = el("div", "")
+ const preview = el("div", "preview")
+ const map = document.createElement("canvas")
+ const facts = el("p", "sub")
+ preview.append(map, facts)
+ body.append(options, preview)
+ const group = <T extends string | number>(title: string, values: ReadonlyArray<T>, label: (v: T) => string, blurb: (v: T) => string, get: () => T, set: (v: T) => void) => {
+ const box = section(title)
+ const row = el("div", "choices")
+ const note = el("p", "empty")
+ const buttons = values.map((v) => {
+ const b = el("button", "frame choice", label(v))
+ b.onclick = () => {
+ set(v)
+ refresh()
+ }
+ row.append(b)
+ return { v, b }
+ })
+ box.append(row, note)
+ options.append(box)
+ return () => {
+ for (const { v, b } of buttons) b.classList.toggle("on", v === get())
+ note.textContent = blurb(get())
+ }
+ }
+ const refreshers = [
+ group("land", sizeIds, (v) => sizes[v].title, (v) => `${sizes[v].goal.residents} residents and ${sizes[v].goal.coins} coins to complete it`, () => choice.size, (v) => (choice.size = v)),
+ group("term", TERMS, (v) => `${v} min`, (v) => `${v} minutes of the town at 1×: six years, a winter at the end of each after the first`, () => choice.term, (v) => (choice.term = v)),
+ group("richness", landIds, (v) => lands[v].title, (v) => lands[v].blurb, () => choice.land, (v) => (choice.land = v))
+ ]
+ const seedLine = el("div", "row")
+ const seedText = el("span", "")
+ const reroll = el("button", "frame", "other land")
+ reroll.onclick = () => {
+ choice.seed = (Math.random() * 0x7fffffff) >>> 0
+ refresh()
+ }
+ seedLine.append(seedText, reroll)
+ preview.append(seedLine)
+ const refresh = () => {
+ for (const r of refreshers) r()
+ const land = drawLand(map)
+ seedText.textContent = `seed ${choice.seed}`
+ facts.textContent = `${land.cells} cells of land · ${land.trees.length} trees · ${land.rocks.filter((r) => !r.ore).length} stone · ${land.rocks.filter((r) => r.ore).length} ore · ${lands[choice.land].coins} coins to start`
+ }
+ refresh()
+ const actions = el("div", "actions")
+ const found = el("button", "frame primary", "Found the town")
+ found.onclick = () => {
+ ui.edits.push({ type: "newTown", charter: { ...choice } })
+ history.length = 0
+ ui.selected = null
+ ui.menu = null
+ closeCharter()
+ showReckoning(false)
+ choose("select")
+ setSpeed(1)
+ }
+ actions.append(found)
+ if (cancellable) {
+ const cancel = el("button", "frame", "Cancel")
+ cancel.onclick = () => closeCharter()
+ actions.append(cancel)
+ }
+ card.append(body, actions)
+ dialog.append(card)
+ dialog.classList.add("open")
+ }
+ const closeCharter = () => {
+ ui.founding = false
+ dialog.classList.remove("open")
+ }
+ openCharter(false)
+
+ // ── The end of the term ──
+ /** Lines of residents, coins, and approval over the term, on the term's own time axis. */
+ const chart = (s: Stats): string => {
+ const w = 520
+ const h = 150
+ const end = Math.max(s.charter.term * 3600, ...s.history.map((p) => p.tick))
+ const line = (values: ReadonlyArray<number>, lo: number, hi: number, color: string, dash = "") => {
+ if (values.length < 2) return ""
+ const span = hi - lo || 1
+ const points = s.history.map((p, i) => `${((p.tick / end) * w).toFixed(1)},${(h - 4 - ((values[i]! - lo) / span) * (h - 8)).toFixed(1)}`).join(" ")
+ return `<polyline points="${points}" fill="none" stroke="${color}" stroke-width="1.5" stroke-dasharray="${dash}" vector-effect="non-scaling-stroke"/>`
+ }
+ const residents = s.history.map((p) => p.residents)
+ const coinsLine = s.history.map((p) => p.coins)
+ const approvalLine = s.history.map((p) => p.approval)
+ const top = Math.max(1, ...residents, sizes[s.charter.size].goal.residents)
+ const goal = h - 4 - (sizes[s.charter.size].goal.residents / top) * (h - 8)
+ const winters = Array.from({ length: 5 }, (_, i) => {
+ const y = i + 1
+ const from = ((y + 0.7) / 6) * w
+ return `<rect x="${from.toFixed(1)}" y="0" width="${(w * 0.3 / 6).toFixed(1)}" height="${h}" fill="#3d6db5" opacity="0.06"/>`
+ }).join("")
+ return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">${winters}<line x1="0" x2="${w}" y1="${goal}" y2="${goal}" stroke="#77817a" stroke-dasharray="3 3" vector-effect="non-scaling-stroke"/>${line(coinsLine, Math.min(0, ...coinsLine), Math.max(1, ...coinsLine), "#d6ae2e")}${line(approvalLine, -100, 100, "#3d6db5", "4 3")}${line(residents, 0, top, "#3d4943")}</svg>`
+ }
+ /** What became of a town whose term ran out. */
+ const verdictOf = (s: Stats): string => {
+ if (s.fate.governing) return "complete"
+ const residents = s.settlers + s.citizens
+ if (s.fate.peak < 40) return "the town never took root"
+ if (residents >= sizes[s.charter.size].goal.residents * 0.75) return "flourishing"
+ if (residents >= s.fate.peak * 0.7) return "holding on"
+ return "declining"
+ }
+ let reckoned = ""
+ let reckoningOpen = false
+ const showReckoning = (open: boolean) => {
+ reckoningOpen = open
+ reckoning.classList.toggle("open", open && ui.stats !== null && ui.stats.fate.state !== "playing")
+ }
+ const syncReckoning = (s: Stats) => {
+ const over = s.fate.state !== "playing"
+ result.classList.toggle("show", over && !reckoningOpen && !ui.founding)
+ if (!over) {
+ reckoned = ""
+ reckoning.classList.remove("open")
+ return
+ }
+ const id = `${s.charter.seed}|${s.fate.state}|${s.fate.at}`
+ result.textContent = s.fate.state === "won" ? "the town is complete · see how" : s.fate.state === "lost" ? "the term is lost · see how" : "the term is over · see how"
+ if (id === reckoned) return
+ reckoned = id
+ const title = s.fate.state === "won" ? "the town is complete" : s.fate.state === "lost" ? s.fate.reason.split(":")[0]!.toLowerCase() : `the term is over: ${verdictOf(s)}`
+ reckoning.replaceChildren()
+ const card = el("div", "sheet wide")
+ card.append(el("h2", "", title), el("p", "sub", s.fate.reason))
+ const facts = el("div", "facts")
+ const fact = (label: string, value: string) => {
+ const f = el("div", "fact")
+ f.append(el("b", "", value), el("span", "", label))
+ facts.append(f)
+ }
+ fact("minutes in office", `${Math.round(s.fate.at)}`)
+ fact("residents", `${s.settlers + s.citizens}`)
+ fact("citizens", `${s.citizens}`)
+ fact("coins", `${s.coins}`)
+ fact("approval", signed(s.mood.approval))
+ fact("crown met · missed", `${s.crown.met} · ${s.crown.missed}`)
+ fact("score", `${s.fate.score}`)
+ card.append(facts)
+ const graph = el("div", "chart")
+ graph.innerHTML = chart(s)
+ card.append(graph, el("p", "legend", "— residents (dashed: the goal) · coins · - - approval · shaded: winters"))
+ const story = el("div", "chronicle")
+ story.innerHTML = s.chronicle.map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`).join("")
+ card.append(story)
+ const actions = el("div", "actions")
+ if (s.fate.state === "won") {
+ const govern = el("button", "frame primary", "Keep governing")
+ govern.title = "Stay on to the end of the term: the town is already complete"
+ govern.onclick = () => {
+ ui.edits.push({ type: "govern" })
+ showReckoning(false)
+ }
+ actions.append(govern)
+ }
+ const again = el("button", "frame" + (s.fate.state === "won" ? "" : " primary"), "Found a new town")
+ again.onclick = () => {
+ showReckoning(false)
+ openCharter(true)
+ }
+ const look = el("button", "frame", "Look at the town")
+ look.onclick = () => showReckoning(false)
+ actions.append(again, look)
+ card.append(actions)
+ reckoning.append(card)
+ showReckoning(true)
+ }
+
// ── Pointer ──
const canvas = app.canvas
const pointers = new Map<number, Point>()
@@ -609,7 +955,36 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
coins.classList.toggle("debt", s.coins < 0)
people.textContent = `${s.settlers} settlers · ${s.citizens} citizens`
jobs.textContent = `${s.employed}/${s.jobs} jobs`
+ const left = Math.max(0, s.charter.term * 60 - Math.floor(s.minute * 60))
+ clock.innerHTML = `year ${s.season.year} · ${s.season.winter ? `<span class="winter">winter, spring in ${clockText(s.season.left)}</span>` : `winter in ${clockText(s.season.left)}`} · <b>${clockText(left)}</b> left`
+ clock.title = s.season.winter ? "Winter: fields lie still, fishing is slow, and homes eat faster" : `Winter comes in ${clockText(s.season.left)}`
+ approval.innerHTML = `approval <b class="${s.mood.approval < 0 ? "down" : ""}">${signed(s.mood.approval)}</b> <span class="${s.mood.target >= s.mood.approval ? "up" : "down"}">${s.mood.target > s.mood.approval ? "↑" : s.mood.target < s.mood.approval ? "↓" : ""}</span>`
for (const [g, count] of goodCells) count.textContent = String(s.stock[g])
+ // The crown's request.
+ request.classList.toggle("show", s.crown.open && s.fate.state === "playing")
+ if (s.crown.open) {
+ const have = s.stock[s.crown.good]
+ requestText.innerHTML = `the crown asks for <b>${s.crown.amount} ${goods[s.crown.good].title}</b> (${have} in store) · <b>${clockText(s.crown.left)}</b> · ${s.crown.reward} coins`
+ send.disabled = have < s.crown.amount
+ }
+ // What threatens the term, or is about to complete it.
+ const warnings: Array<string> = []
+ if (s.fate.state === "playing") {
+ if (s.fate.bankrupt !== null) warnings.push(`<b>In debt:</b> bankrupt in ${clockText(s.fate.bankrupt)} unless the treasury recovers`)
+ else if (s.coins < 0) warnings.push("<b>In debt:</b> wages are going unpaid")
+ if (s.fate.revolt !== null) warnings.push(`<b>Uproar:</b> the town turns the mayor out in ${clockText(s.fate.revolt)}`)
+ else if (s.mood.approval < -30) warnings.push("<b>Restless:</b> approval is falling towards revolt")
+ if (s.fate.peak >= 40 && s.settlers + s.citizens < s.fate.peak * 0.4) warnings.push("<b>Emptying:</b> people are leaving the town")
+ if (s.fate.complete !== null) warnings.push(`<b>Every goal met:</b> the town is complete in ${clockText(s.fate.complete)}`)
+ }
+ const html = warnings.map((w) => `<div class="cell">${w}</div>`).join("")
+ if (alarm.dataset.html !== html) {
+ alarm.dataset.html = html
+ alarm.innerHTML = html
+ }
+ alarm.classList.toggle("show", warnings.length > 0)
+ alarm.classList.toggle("good", warnings.length === 1 && s.fate.complete !== null)
+ syncReckoning(s)
}
const text = ui.preview.tooltip
if (text && screenPointer) {
diff --git a/src/iso.ts b/src/iso.ts
index e87061b..c667099 100644
--- a/src/iso.ts
+++ b/src/iso.ts
@@ -11,10 +11,8 @@ export const TILE_W = 64
export const TILE_H = 32
/** A sixteenth of a cell: the smallest length anything on the floor is measured in. */
export const U = 1 / 16
-/** Cells along each side of the yard. */
-export const GRID = 32
-/** A factory stands on 3×3 cells; belts meet it at the middle cell of a side. */
-export const FOOTPRINT = 3
+/** Cells along each side of the square the land lies in. */
+export const GRID = 64
export interface Point {
readonly x: number
diff --git a/src/main.ts b/src/main.ts
index 65c576f..34a6604 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -3,17 +3,19 @@
* bevy-ts ECS with Pixi drawing it. The simulation runs on a fixed step;
* the views follow once a frame.
*/
+import { Result } from "@typeonce/bevy-ts"
import { FixedLoop } from "@typeonce/bevy-ts-browser"
import { PixiNodeRegistry } from "@typeonce/bevy-ts-pixi"
import type { BuildingView, FieldView, HouseView, RockView, TreeView, WalkerView } from "./art.ts"
-import { amounts, STEP_SECONDS } from "./content.ts"
+import { STEP_SECONDS } from "./content.ts"
import { createHost, type Persistence } from "./host.ts"
import { present } from "./present.ts"
import { BuildingNodes, Clock, FieldNodes, Game, HouseNodes, RockNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"
-import { simulate } from "./sim/index.ts"
+import { blankResources, simulate } from "./sim/index.ts"
-const SAVE_KEY = "town/save"
+/** Saves of the charter's towns: older ones (a square map, no term) do not load into it. */
+const SAVE_KEY = "town/save/charter"
const start = async () => {
const mount = document.getElementById("app")!
@@ -33,16 +35,7 @@ const start = async () => {
Game.Runtime.service(RockNodes, PixiNodeRegistry.make<RockView>(stage.objects)),
Game.Runtime.service(FieldNodes, PixiNodeRegistry.make<FieldView>(stage.plates))
),
- resources: {
- Time: { tick: 0 },
- Rng: 0x5eed,
- Treasury: { coins: 0 },
- Ledger: { taxes: 0, trade: 0, upkeep: 0 },
- Census: { homes: 0, settlers: 0, citizens: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0 },
- Policy: { settlers: 100, citizens: 100, sells: [], reserve: 25 },
- Grid: { owner: [], use: [] },
- Stock: amounts({})
- }
+ resources: blankResources()
})
if (!made.ok) {
mount.textContent = `The town could not start: ${JSON.stringify(made.error)}`
@@ -80,8 +73,19 @@ const start = async () => {
}),
stepSeconds: STEP_SECONDS,
maxFrameSeconds: 0.25,
- maxStepsPerFrame: 8,
- update: () => runtime.tick(simulate),
+ maxStepsPerFrame: 4,
+ // The town runs at the chosen speed; it waits while paused, while the
+ // new-town dialog is open, and once the term has ended (an edit, such as
+ // founding a new town, still gets its step).
+ update: () => {
+ const waiting = ui.speed === 0 || ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")
+ const steps = waiting ? (ui.edits.length > 0 ? 1 : 0) : ui.speed
+ for (let i = 0; i < steps; i++) {
+ const stepped = runtime.tick(simulate)
+ if (!stepped.ok) return stepped
+ }
+ return Result.success(undefined)
+ },
render: ({ elapsedSeconds }) => {
clock.deltaSeconds = elapsedSeconds
clock.elapsed += elapsedSeconds
diff --git a/src/mapgen.ts b/src/mapgen.ts
index a7f3e56..8c1593d 100644
--- a/src/mapgen.ts
+++ b/src/mapgen.ts
@@ -1,33 +1,120 @@
/**
- * A new town's land, from a seed: a lake by one edge, a few forests and
- * single trees, outcrops of stone and a deposit of ore, and a clearing in
- * the middle where the town hall stands, ringed by a road with a stub
- * out from each side.
- * Pure: the same seed always makes the same land.
+ * A new town's land, from its charter: an island-like stretch of land of
+ * the charter's size, its coast wandering in and out and a few capes
+ * reaching out; lakes, forests and single trees, outcrops of stone and
+ * deposits of ore, as many as the land's richness gives; and a clearing in
+ * the middle where the town hall stands, ringed by a road with a stub out
+ * from each side.
+ * Pure: the same charter always makes the same land.
*/
import * as Random from "@typeonce/bevy-ts-math/Random"
-import { GROWN } from "./content.ts"
-import { key } from "./grid.ts"
+import { GROWN, lands, sizes, type CharterValue } from "./content.ts"
+import { DIRS, key } from "./grid.ts"
import { GRID, inside, type Point } from "./iso.ts"
export interface Land {
+ /** "1" for land, "0" for open water, by `key`. */
+ readonly mask: string
+ readonly cells: number
readonly hall: Point
readonly roads: ReadonlyArray<Point>
readonly water: ReadonlyArray<Point>
readonly trees: ReadonlyArray<{ readonly cell: Point; readonly growth: number }>
- readonly rocks: ReadonlyArray<{ readonly cell: Point; readonly ore: boolean }>
+ readonly rocks: ReadonlyArray<{ readonly cell: Point; readonly ore: boolean; readonly amount: number }>
}
-export const generate = (seed: number): Land => {
- const random = Random.make(seed)
+/** The clearing around the town hall that nothing natural grows in. */
+const CLEARING = 7
+
+/** The angle from `a` to `b`, -π → π. */
+const turn = (a: number, b: number) => Math.atan2(Math.sin(b - a), Math.cos(b - a))
+
+/**
+ * The shape of the land: a circle of the size's radius whose edge swells
+ * and dips in a few long waves, with capes reaching out at random angles
+ * and a ragged shoreline; then tidied so it is one piece with no holes and
+ * no lone cells.
+ */
+const shape = (random: Random.Random, radius: number): Array<boolean> => {
+ const centre = GRID / 2
+ const waves = [2, 3, 4, 5].map((k) => ({ k, size: random.range(0, 0.1), phase: random.range(0, Math.PI * 2) }))
+ const capes = Array.from({ length: random.integer(2, 6) }, () => ({
+ at: random.range(0, Math.PI * 2),
+ size: random.range(0.2, 0.5),
+ width: random.range(0.1, 0.28)
+ }))
+ const edge = (angle: number) =>
+ radius *
+ (1 +
+ waves.reduce((sum, w) => sum + w.size * Math.sin(w.k * angle + w.phase), 0) +
+ capes.reduce((sum, c) => sum + c.size * Math.exp(-((turn(c.at, angle) / c.width) ** 2)), 0))
+
+ let land = new Array<boolean>(GRID * GRID).fill(false)
+ for (let y = 1; y < GRID - 1; y++) {
+ for (let x = 1; x < GRID - 1; x++) {
+ const dx = x + 0.5 - centre
+ const dy = y + 0.5 - centre
+ land[key(x, y)] = Math.hypot(dx, dy) < edge(Math.atan2(dy, dx)) + random.range(-0.8, 0.8)
+ }
+ }
+ // Smooth the shore: a cell mostly surrounded by water floods, a cove mostly surrounded by land fills.
+ const neighbours = (cells: ReadonlyArray<boolean>, x: number, y: number) =>
+ DIRS.filter((d) => inside(x + d.x, y + d.y) && cells[key(x + d.x, y + d.y)]).length
+ for (let pass = 0; pass < 2; pass++) {
+ const next = [...land]
+ for (let y = 1; y < GRID - 1; y++) {
+ for (let x = 1; x < GRID - 1; x++) {
+ const n = neighbours(land, x, y)
+ if (land[key(x, y)] && n <= 1) next[key(x, y)] = false
+ else if (!land[key(x, y)] && n >= 3) next[key(x, y)] = true
+ }
+ }
+ land = next
+ }
+ // One piece: what the middle can walk to. Water it can't reach from the open sea is filled in.
+ const flood = (start: Point, on: (k: number) => boolean) => {
+ const seen = new Set<number>([key(start.x, start.y)])
+ const queue = [start]
+ for (let head = 0; head < queue.length; head++) {
+ const c = queue[head]!
+ for (const d of DIRS) {
+ const n = { x: c.x + d.x, y: c.y + d.y }
+ const k = key(n.x, n.y)
+ if (!inside(n.x, n.y) || seen.has(k) || !on(k)) continue
+ seen.add(k)
+ queue.push(n)
+ }
+ }
+ return seen
+ }
+ const main = flood({ x: centre, y: centre }, (k) => land[k]!)
+ const sea = flood({ x: 0, y: 0 }, (k) => !main.has(k))
+ return land.map((_, k) => main.has(k) || !sea.has(k))
+}
+
+export const generate = (charter: CharterValue): Land => {
+ const random = Random.make(charter.seed)
+ const richness = lands[charter.land]
+ const ground = shape(random, sizes[charter.size].radius)
+ const cells = ground.filter(Boolean).length
+ const per = (perThousand: number) => Math.max(1, Math.round((cells / 1000) * perThousand))
+
const taken = new Set<number>()
const centre = { x: GRID / 2, y: GRID / 2 }
const hall = { x: centre.x - 2, y: centre.y - 2 }
- const clearing = 7
const near = (c: Point, r: number) => Math.hypot(c.x + 0.5 - centre.x, c.y + 0.5 - centre.y) < r
- const free = (c: Point) => inside(c.x, c.y) && !taken.has(key(c.x, c.y)) && !near(c, clearing)
+ const onLand = (c: Point) => inside(c.x, c.y) && ground[key(c.x, c.y)]!
+ const free = (c: Point) => onLand(c) && !taken.has(key(c.x, c.y)) && !near(c, CLEARING)
const take = (c: Point) => taken.add(key(c.x, c.y))
+ /** A random cell of land at least `from` cells from the middle. */
+ const somewhere = (from: number): Point => {
+ for (let tries = 0; tries < 200; tries++) {
+ const c = { x: random.integer(1, GRID - 1), y: random.integer(1, GRID - 1) }
+ if (free(c) && !near(c, from)) return c
+ }
+ return { x: random.integer(1, GRID - 1), y: random.integer(1, GRID - 1) }
+ }
// The town hall, a ring road around it, and a stub out from the middle of each side.
for (let dx = 0; dx < 3; dx++) for (let dy = 0; dy < 3; dy++) take({ x: hall.x + dx, y: hall.y + dy })
@@ -42,25 +129,21 @@ export const generate = (seed: number): Land => {
}
roads.forEach(take)
- // A lake against one edge.
+ // Lakes, the first not too far from the town.
const water: Array<Point> = []
- const side = random.integer(0, 4)
- const along = random.integer(6, GRID - 6)
- const lake = [
- { x: GRID - 2, y: along },
- { x: along, y: GRID - 2 },
- { x: 1, y: along },
- { x: along, y: 1 }
- ][side]!
- const rx = random.integer(4, 7)
- const ry = random.integer(3, 6)
- for (let y = 0; y < GRID; y++) {
- for (let x = 0; x < GRID; x++) {
- const d = ((x - lake.x) / rx) ** 2 + ((y - lake.y) / ry) ** 2
- const c = { x, y }
- if (d < 1 + random.range(-0.2, 0.2) && free(c)) {
- water.push(c)
- take(c)
+ const scale = Math.sqrt(cells / 1000)
+ for (let l = 0; l < richness.lakes; l++) {
+ const at = somewhere(CLEARING + 3 + (l === 0 ? 0 : 4))
+ const rx = Math.max(2, Math.round(random.range(2.5, 5) * scale))
+ const ry = Math.max(2, Math.round(random.range(2, 4.5) * scale))
+ for (let y = at.y - ry - 1; y <= at.y + ry + 1; y++) {
+ for (let x = at.x - rx - 1; x <= at.x + rx + 1; x++) {
+ const c = { x, y }
+ const d = ((x - at.x) / rx) ** 2 + ((y - at.y) / ry) ** 2
+ if (d < 1 + random.range(-0.2, 0.2) && free(c)) {
+ water.push(c)
+ take(c)
+ }
}
}
}
@@ -72,43 +155,35 @@ export const generate = (seed: number): Land => {
trees.push({ cell: c, growth: random.next() < 0.8 ? GROWN.tree : random.integer(0, GROWN.tree) })
take(c)
}
- for (let f = 0; f < 6; f++) {
- let at = { x: random.integer(2, GRID - 2), y: random.integer(2, GRID - 2) }
- for (let tries = 0; tries < 20 && near(at, clearing + 3); tries++) at = { x: random.integer(2, GRID - 2), y: random.integer(2, GRID - 2) }
- const count = random.integer(18, 30)
+ for (let f = 0; f < per(richness.forests); f++) {
+ const at = somewhere(CLEARING + 3)
+ const count = random.integer(16, 30)
let placed = 0
for (let tries = 0; placed < count && tries < count * 4; tries++) {
const spread = Math.sqrt(random.next()) * 4
- const turn = random.range(0, Math.PI * 2)
- const c = { x: Math.round(at.x + Math.cos(turn) * spread), y: Math.round(at.y + Math.sin(turn) * spread) }
+ const angle = random.range(0, Math.PI * 2)
+ const c = { x: Math.round(at.x + Math.cos(angle) * spread), y: Math.round(at.y + Math.sin(angle) * spread) }
if (!free(c)) continue
plant(c)
placed += 1
}
}
- for (let i = 0; i < 24; i++) plant({ x: random.integer(0, GRID), y: random.integer(0, GRID) })
+ for (let i = 0; i < Math.round(cells / 45); i++) plant({ x: random.integer(0, GRID), y: random.integer(0, GRID) })
- // Outcrops of stone, and a deposit of ore.
- const rocks: Array<{ cell: Point; ore: boolean }> = []
+ // Outcrops of stone, and deposits of ore.
+ const rocks: Array<{ cell: Point; ore: boolean; amount: number }> = []
const outcrop = (ore: boolean) => {
- for (let tries = 0; tries < 20; tries++) {
- const at = { x: random.integer(2, GRID - 2), y: random.integer(2, GRID - 2) }
- if (!free(at) || near(at, clearing + 1)) continue
- const count = random.integer(3, 6)
- for (let i = 0; i < count; i++) {
- const c = { x: at.x + random.integer(-1, 2), y: at.y + random.integer(-1, 2) }
- if (!free(c)) continue
- rocks.push({ cell: c, ore })
- take(c)
- }
- return
+ const at = somewhere(CLEARING + 1)
+ const count = random.integer(3, 7)
+ for (let i = 0; i < count; i++) {
+ const c = { x: at.x + random.integer(-1, 2), y: at.y + random.integer(-1, 2) }
+ if (!free(c)) continue
+ rocks.push({ cell: c, ore, amount: richness.rock })
+ take(c)
}
}
- outcrop(false)
- outcrop(false)
- outcrop(false)
- outcrop(true)
- outcrop(true)
+ for (let i = 0; i < per(richness.stone); i++) outcrop(false)
+ for (let i = 0; i < per(richness.ore); i++) outcrop(true)
- return { hall, roads, water, trees, rocks }
+ return { mask: ground.map((g) => (g ? "1" : "0")).join(""), cells, hall, roads, water, trees, rocks }
}
diff --git a/src/present.ts b/src/present.ts
index f986132..8d52f4e 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -6,18 +6,19 @@
import { RenderSync } from "@typeonce/bevy-ts-render"
import {
- BuildingView, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView,
+ BuildingView, drawFloor, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView,
type Doors, type Emphasis
} from "./art.ts"
-import { BUILD_TICKS, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"
+import { BUILD_TICKS, fate, 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, TILE_H, TILE_W, toGrid, toScreen, U, type Point } from "./iso.ts"
import {
- Building, BuildingNodes, Census, Clock, Errand, Field, FieldNodes, Figure, Game, Grid, House, HouseNodes, Inventory,
- Ledger, Policy, Recipe, Rising, Road, Roam, Rock, RockNodes, Route, Service, Site, Staff, StageService, Status, Stock, Tile,
- TownHall, Treasury, Tree, TreeNodes, Ui, WalkerNodes, WalkerOf, Water, maybe, type GridValue, type Status as StatusValue
+ Building, BuildingNodes, Census, Charter, Chronicle, Clock, Crown, Errand, Fate, Field, FieldNodes, Figure, Game, Grid, History, House,
+ HouseNodes, Inventory, Land, Ledger, Market, Mood, Paused, Policy, Recipe, Rising, Road, Roam, Rock, RockNodes, Route, Service, Site,
+ Staff, StageService, Status, Stock, Tile, Time, TownHall, Treasury, Tree, TreeNodes, Ui, WalkerNodes, WalkerOf, Water, maybe,
+ type GridValue, type Status as StatusValue
} from "./schema.ts"
-import { capacity, CELL_STEPS, met, SITE_SHARE, taxOf } from "./sim/index.ts"
+import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, taxOf, termTicks } from "./sim/index.ts"
import { emptyPreview, type HitBox } from "./ui.ts"
const cellAt = (at: Point): Point => {
@@ -69,6 +70,8 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false): string | n
return "no workers: the town needs more residents"
case "blocked":
return "full: nowhere to take what it makes"
+ case "paused":
+ return "paused: no workers, a quarter of its upkeep"
case "starved":
if (kind.gathers && growing) return `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing`
if (kind.gathers) return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`
@@ -99,7 +102,8 @@ const BuildingRead = Game.Query({
inventory: Game.Query.optional(Inventory),
service: Game.Query.optional(Service),
walkers: Game.Query.optionalRelated(WalkerOf),
- hall: Game.Query.optional(TownHall)
+ hall: Game.Query.optional(TownHall),
+ paused: Game.Query.optional(Paused)
}
})
const HouseRead = Game.Query({
@@ -127,7 +131,15 @@ export const Interact = Game.System(
treasury: Game.System.readResource(Treasury),
ledger: Game.System.readResource(Ledger),
stock: Game.System.readResource(Stock),
- policy: Game.System.readResource(Policy)
+ policy: Game.System.readResource(Policy),
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ market: Game.System.readResource(Market),
+ mood: Game.System.readResource(Mood),
+ crown: Game.System.readResource(Crown),
+ fate: Game.System.readResource(Fate),
+ history: Game.System.readResource(History),
+ chronicle: Game.System.readResource(Chronicle)
},
services: { ui: Game.System.service(Ui) }
},
@@ -135,6 +147,7 @@ export const Interact = Game.System(
const ui = services.ui
const grid = resources.grid.get()
const rates = resources.policy.get()
+ const approval = resources.mood.get().approval
const buildings = queries.buildings.each()
const houses = queries.houses.each()
@@ -260,7 +273,7 @@ export const Interact = Game.System(
return {
h,
lines: [
- `${h.residents} of ${capacity(h, rates)} residents (${tier.residents} at most)`,
+ `${h.residents} of ${capacity(h, approval)} residents (${tier.residents} at most)`,
`needs: ${tier.needs.map(mark).join(" · ")}`,
...(next ? [`to become citizens: ${next.needs.map(mark).join(" · ")}`] : []),
`pays ${Math.round(taxOf(h, rates))} coins a minute`
@@ -288,7 +301,11 @@ export const Interact = Game.System(
const pickedHouse = ui.selected !== null ? houses.find((row) => row.entity.id === ui.selected) : undefined
if (pickedBuilding) {
const { kind, status, problem, lines } = describeBuilding(pickedBuilding)
- ui.panel = { type: "building", id: pickedBuilding.entity.id, cell: pickedBuilding.data.tile.get(), kind: kind.id, status, problem, lines }
+ const pausable = kind.id !== "townhall" && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present
+ ui.panel = {
+ type: "building", id: pickedBuilding.entity.id, cell: pickedBuilding.data.tile.get(), kind: kind.id, status, problem, lines,
+ pausable, paused: pickedBuilding.data.paused.present
+ }
} else if (pickedHouse) {
const { h, lines } = describeHouse(pickedHouse)
ui.panel = { type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines }
@@ -303,20 +320,67 @@ export const Interact = Game.System(
const census = resources.census.get()
const ledger = resources.ledger.get()
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ const coins = resources.treasury.get().coins
+ const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
+ const mood = resources.mood.get()
+ const crown = resources.crown.get()
+ const f = resources.fate.get()
+ const stock = resources.stock.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))
ui.stats = {
- coins: resources.treasury.get().coins,
+ coins,
taxes: ledger.taxes,
trade: ledger.trade,
upkeep: ledger.upkeep,
- net: ledger.taxes + ledger.trade - ledger.upkeep,
+ admin: ledger.admin,
+ net,
homes: census.homes,
needs: { food: census.food, bread: census.bread, cloth: census.cloth, faith: census.faith },
policy: rates,
- stock: resources.stock.get(),
+ stock,
+ prices: resources.market.get().prices,
settlers: census.settlers,
citizens: census.citizens,
jobs: census.jobs,
- employed: census.employed
+ 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) },
+ mood: {
+ approval: mood.approval,
+ target: mood.target,
+ parts: [
+ { label: "mood of the town", value: mood.base },
+ { label: "needs met", value: mood.needs },
+ { label: "taxes", value: mood.taxes },
+ { label: "unpaid wages", value: mood.debt },
+ { label: "the crown's displeasure", value: mood.crown },
+ { label: "a hungry winter", value: mood.winter }
+ ].filter((p) => p.value !== 0)
+ },
+ crown: {
+ open: crown.open, good: crown.good, amount: crown.amount, left: seconds(crown.due - t), reward: crown.reward, met: crown.met,
+ missed: crown.missed, next: seconds(crown.next - t)
+ },
+ fate: {
+ state: f.state,
+ reason: f.reason,
+ at: f.at / 3600,
+ governing: f.governing,
+ score: f.score,
+ bankrupt: danger(f.debtSince, fate.debt),
+ revolt: danger(f.revoltSince, fate.revolt),
+ complete: danger(f.goalSince, fate.hold),
+ peak: f.peak
+ },
+ goals: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net, approval: mood.approval }),
+ larder: larder(stock),
+ history: resources.history.get().samples,
+ chronicle: resources.chronicle.get().lines
}
}
)
@@ -378,6 +442,20 @@ 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). */
+let floorFor = ""
+export const DrawLand = Game.System(
+ "Town/DrawLand",
+ { resources: { land: Game.System.readResource(Land) }, services: { stage: Game.System.service(StageService) } },
+ ({ resources, services }) => {
+ const mask = resources.land.get().mask
+ if (mask === floorFor) return
+ floorFor = mask
+ services.stage.floor.clear()
+ drawFloor(services.stage.floor, mask)
+ }
+)
+
/** Roads and water, each redrawn as one layer whenever one is laid or anything is removed. */
export const DrawGround = Game.System(
"Town/DrawGround",
@@ -508,6 +586,7 @@ export const DrawPreview = Game.System(
export const present = Game.Schedule(
Interact,
+ DrawLand,
RenderBuildings,
RenderHouses,
RenderWalkers,
diff --git a/src/schema.ts b/src/schema.ts
index f780962..e5d9df1 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -16,7 +16,7 @@ import type { OptionalReadCell } from "@typeonce/bevy-ts/Query"
import type { NodeRegistry } from "@typeonce/bevy-ts-render"
import type { BuildingView, FieldView, HouseView, RockView, Stage, TreeView, WalkerView } from "./art.ts"
-import { goodIds, kindIds, type Amounts } from "./content.ts"
+import { goodIds, kindIds, landIds, sizeIds, type Amounts } from "./content.ts"
import type { UiValue } from "./ui.ts"
export const Root = Schema.defineRoot("Town")
@@ -34,7 +34,7 @@ const amounts = Decode.struct({
wheat: integer, flour: integer, bread: integer, wool: integer, cloth: integer
})
-export const statuses = ["building", "idle", "working", "starved", "blocked", "unstaffed", "unconnected"] as const
+export const statuses = ["building", "idle", "working", "starved", "blocked", "unstaffed", "unconnected", "paused"] as const
export type Status = (typeof statuses)[number]
// ── On the grid ───────────────────────────────────────────────────────────
@@ -72,6 +72,8 @@ export const House = Descriptor.ConstructedComponent(Decode.struct({
export const Building = Descriptor.ConstructedComponent(Decode.struct({ kind: Decode.literal(...kindIds) }))("Town/Building")
export const TownHall = Descriptor.Tag("Town/TownHall")
export const Status = Descriptor.ConstructedComponent(Decode.literal(...statuses))("Town/Status")
+/** 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")
@@ -148,8 +150,8 @@ export const Time = Descriptor.ConstructedResource(Decode.struct({ tick: integer
/** The deterministic random state (see `@typeonce/bevy-ts-math/Random`). */
export const Rng = Descriptor.ConstructedResource(integer)("Town/Rng")
export const Treasury = Descriptor.ConstructedResource(Decode.struct({ coins: integer }))("Town/Treasury")
-/** The last collection's taxes, trade, and upkeep, per minute. */
-export const Ledger = Descriptor.ConstructedResource(Decode.struct({ taxes: integer, trade: integer, upkeep: integer }))("Town/Ledger")
+/** The last collection's taxes, trade (sold less bought), upkeep, and administration, per minute. */
+export const Ledger = Descriptor.ConstructedResource(Decode.struct({ taxes: integer, trade: integer, upkeep: integer, admin: integer }))("Town/Ledger")
export const Census = Descriptor.ConstructedResource(Decode.struct({
homes: integer,
settlers: integer,
@@ -162,15 +164,101 @@ export const Census = Descriptor.ConstructedResource(Decode.struct({
cloth: integer,
faith: integer
}))("Town/Census")
-/** The town's tax rates (in percent of the usual, for each tier), and what it sells to traders beyond the reserve it keeps. */
-export const Policy = Descriptor.ConstructedResource(Decode.struct({ settlers: integer, citizens: integer, sells: Decode.array(good), reserve: integer }))("Town/Policy")
+/**
+ * The town's tax rates (in percent of the usual, for each tier), what it
+ * sells to traders beyond the reserve it keeps, and what it buys up to it.
+ */
+export const Policy = Descriptor.ConstructedResource(Decode.struct({
+ settlers: integer,
+ citizens: integer,
+ sells: Decode.array(good),
+ buys: Decode.array(good),
+ reserve: integer
+}))("Town/Policy")
+
+/**
+ * What the town was founded on: the size of its land, its term in minutes,
+ * how rich the land is, its seed, and the step it was founded on.
+ */
+export const Charter = Descriptor.ConstructedResource(Decode.struct({
+ size: Decode.literal(...sizeIds),
+ term: integer,
+ land: Decode.literal(...landIds),
+ seed: integer,
+ founded: integer
+}))("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")
+
+/** Each good's price with traders, in percent of the usual (see `market`). */
+export const Market = Descriptor.ConstructedResource(Decode.struct({ prices: amounts }))("Town/Market")
+
+/** The town's approval, -100 → 100, where it is heading, and why: each part of the target. */
+export const Mood = Descriptor.ConstructedResource(Decode.struct({
+ approval: integer,
+ target: integer,
+ base: integer,
+ needs: integer,
+ taxes: integer,
+ debt: integer,
+ crown: integer,
+ winter: integer
+}))("Town/Mood")
+
+/**
+ * The crown's requests: the one open now (if `open`), when the next comes,
+ * how many were met and missed, and when the misses the crown still
+ * remembers were.
+ */
+export const Crown = Descriptor.ConstructedResource(Decode.struct({
+ open: Decode.boolean,
+ good,
+ amount: integer,
+ issued: integer,
+ due: integer,
+ reward: integer,
+ next: integer,
+ met: integer,
+ missed: integer,
+ snubs: Decode.array(integer)
+}))("Town/Crown")
+
+export const fateStates = ["playing", "won", "lost", "over"] as const
+/**
+ * How the term is going: still `playing`; `won` (every goal held), `lost`
+ * (bankrupt, in revolt, or abandoned), or `over` (the term ran out), with
+ * why and when. `governing`: won, and carried on anyway. The `since`
+ * fields are when each danger (or the goals) began, or -1.
+ */
+export const Fate = Descriptor.ConstructedResource(Decode.struct({
+ state: Decode.literal(...fateStates),
+ reason: Decode.string,
+ at: integer,
+ governing: Decode.boolean,
+ won: integer,
+ debtSince: integer,
+ revoltSince: integer,
+ goalSince: integer,
+ peak: integer,
+ score: integer
+}))("Town/Fate")
+
+/** The town over its term: a sample every `HISTORY_TICKS`. */
+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 stands on each cell, rebuilt every step from the tiles (see `grid.ts`). */
-export type Use = "empty" | "road" | "house" | "building" | "tree" | "rock" | "water" | "field"
+/** `void`: off the land, past the coast. */
+export type Use = "empty" | "road" | "house" | "building" | "tree" | "rock" | "water" | "field" | "void"
export interface GridValue {
/** Entity id on each cell (by `key`), or 0. */
readonly owner: ReadonlyArray<number>
readonly use: ReadonlyArray<Use>
+ /** A fingerprint of where the roads are, when known: paths are cached against it. */
+ readonly roads?: number
}
export const Grid = Descriptor.TransientResource<GridValue>()("Town/Grid")
/** Goods in the town's storage, summed every step. */
@@ -192,10 +280,12 @@ export const FieldNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FieldView
export const Game = Schema.bind(
Schema.fragment({
components: {
- Tile, Road, Site, Rising, Tree, Rock, Water, Field, House, Building, TownHall, Status, Staff, Inventory, Storage,
+ 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
},
- resources: { Time, Rng, Treasury, Ledger, Census, Policy, Grid, Stock },
+ resources: {
+ Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Grid, Stock
+ },
relations: { WalkerOf, FieldOf }
}),
Root
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
index a26e25b..66d8c88 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -1,18 +1,24 @@
/**
* The player's edits, applied at the start of a step: building, laying
- * roads and homes, bulldozing, and founding a new town. Costs are checked
- * against the treasury and the town's stock and paid up front in coins; the
- * materials are carried to the site afterwards.
+ * roads and homes, bulldozing, pausing, the town's policy, answering the
+ * crown, and founding a new town. Costs are checked against the treasury
+ * and the town's stock and paid up front in coins; the materials are
+ * carried to the site afterwards. Once the term has ended, only a new town
+ * (or carrying on after completing this one) is taken.
*/
import {
buildingDraft, houseDraft, houseStart, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft
} from "../archetypes.ts"
-import { amounts, goodIds, home, kinds, ROAD_COST, ROCK_AMOUNT, start, trade, type Amounts, type Kind } from "../content.ts"
+import { amounts, goodIds, goods, home, kinds, lands, 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 { Census, Game, Inventory, Ledger, Policy, Rng, Status, Stock, TownHall, Treasury, Ui } from "../schema.ts"
-import { TileRead, useOf } from "./shared.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
+} from "../schema.ts"
+import { elapsed, TileRead, useOf } from "./shared.ts"
+import { crownGap, foundedFate } from "./term.ts"
export const unlocked = (kind: Kind, census: { readonly settlers: number; readonly citizens: number }) =>
census.settlers + census.citizens >= kind.unlock.residents && census.citizens >= kind.unlock.citizens
@@ -22,22 +28,33 @@ export const ApplyEdits = Game.System(
{
queries: {
tiles: TileRead,
- halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } })
+ 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] })
},
resources: {
+ time: Game.System.readResource(Time),
treasury: Game.System.writeResource(Treasury),
ledger: Game.System.writeResource(Ledger),
policy: Game.System.writeResource(Policy),
rng: Game.System.writeResource(Rng),
stock: Game.System.readResource(Stock),
- census: Game.System.readResource(Census)
+ census: Game.System.readResource(Census),
+ charter: Game.System.writeResource(Charter),
+ land: Game.System.writeResource(Land),
+ market: Game.System.writeResource(Market),
+ mood: Game.System.writeResource(Mood),
+ crown: Game.System.writeResource(Crown),
+ fate: Game.System.writeResource(Fate),
+ history: Game.System.writeResource(History),
+ chronicle: Game.System.writeResource(Chronicle)
},
services: { ui: Game.System.service(Ui) }
},
({ queries, resources, services, commands }) => {
const ui = services.ui
if (ui.edits.length === 0) return
- const grid = new GridBuilder()
+ const grid = new GridBuilder(resources.land.get().mask)
const rows = queries.tiles.each()
type Id = (typeof rows)[number]["entity"]["id"]
const entities = new Map<number, Id>()
@@ -75,7 +92,11 @@ export const ApplyEdits = Game.System(
return id
}
+ const playing = () => resources.fate.get().state === "playing"
+ const t = elapsed(resources.time.get(), resources.charter.get())
+
edits: for (const edit of ui.edits.splice(0)) {
+ if (edit.type !== "newTown" && edit.type !== "govern" && !playing()) continue
switch (edit.type) {
case "building": {
const kind = kinds[edit.kind]
@@ -153,29 +174,83 @@ export const ApplyEdits = Game.System(
case "tax":
resources.policy.update((p) => ({ ...p, [edit.tier]: edit.rate }))
break
- case "sell":
- resources.policy.update((p) => ({ ...p, sells: edit.on ? [...p.sells.filter((g) => g !== edit.good), edit.good] : p.sells.filter((g) => g !== edit.good) }))
+ case "trade":
+ resources.policy.update((p) => ({
+ ...p,
+ sells: edit.mode === "sell" ? [...p.sells.filter((g) => g !== edit.good), edit.good] : p.sells.filter((g) => g !== edit.good),
+ buys: edit.mode === "buy" ? [...p.buys.filter((g) => g !== edit.good), edit.good] : p.buys.filter((g) => g !== edit.good)
+ }))
+ break
+ case "pause": {
+ const owner = ownerAt(grid.value(), edit.cell.x, edit.cell.y)
+ const row = queries.buildings.each().find((b) => b.entity.id === owner)
+ if (!row || halls.has(owner) || row.data.paused.present === edit.on) break
+ if (edit.on) commands.insert(row.entity.id, Game.Command.entry(Paused, {}))
+ else commands.remove(row.entity.id, Paused)
break
+ }
+ case "deliver": {
+ const c = resources.crown.get()
+ if (!c.open) break
+ if ((left[c.good] ?? 0) < c.amount) {
+ ui.toast(`Not enough ${goods[c.good].title}`)
+ break
+ }
+ let owed = c.amount
+ for (const { data } of [...queries.stores.each()].sort((a, b) => b.data.inventory.get().stock[c.good] - a.data.inventory.get().stock[c.good])) {
+ if (owed <= 0) break
+ const inv = data.inventory.get()
+ const take = Math.min(owed, inv.stock[c.good])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [c.good]: inv.stock[c.good] - take } })
+ owed -= take
+ }
+ left[c.good] = (left[c.good] ?? 0) - c.amount
+ coins += c.reward
+ resources.crown.set({ ...c, open: false, met: c.met + 1 })
+ 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) }))
+ ui.toast(`Sent · +${c.reward} coins`)
+ break
+ }
+ case "govern": {
+ 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) }))
+ break
+ }
case "reserve":
resources.policy.update((p) => ({ ...p, reserve: edit.amount }))
break
case "newTown": {
for (const id of entities.values()) commands.despawn(id)
entities.clear()
- const land = generate(edit.seed)
+ const charter = edit.charter
+ const richness = lands[charter.land]
+ const land = generate(charter)
for (const c of land.water) commands.spawn(waterDraft(c))
- for (const t of land.trees) commands.spawn(treeDraft(t.cell, t.growth))
- for (const r of land.rocks) commands.spawn(rockDraft(r.cell, r.ore, ROCK_AMOUNT))
+ for (const tree of land.trees) commands.spawn(treeDraft(tree.cell, tree.growth))
+ for (const r of land.rocks) commands.spawn(rockDraft(r.cell, r.ore, r.amount))
for (const c of land.roads) commands.spawn(roadDraft(c))
const hall = kinds.townhall
const id = commands.spawn(buildingDraft(hall, land.hall))
commands.insert(id, ...rolesOf(hall))
- const stock: Amounts = amounts(start.stock)
+ const stock: Amounts = amounts(richness.stock)
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 = start.coins
- resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0 })
- resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, reserve: trade.reserve })
- resources.rng.set(edit.seed)
+ coins = richness.coins
+ const founded = resources.time.get().tick
+ resources.charter.set({ ...charter, founded })
+ 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 })
+ resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })
+ resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 })
+ resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter), met: 0, missed: 0, snubs: [] })
+ resources.fate.set(foundedFate())
+ resources.history.set({ samples: [] })
+ resources.chronicle.set({
+ lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.` }]
+ })
+ resources.rng.set(charter.seed)
ui.selected = null
// Nothing else this step: the new land is not on the grid yet.
break edits
diff --git a/src/sim/index.ts b/src/sim/index.ts
index b32eb14..bf88e03 100644
--- a/src/sim/index.ts
+++ b/src/sim/index.ts
@@ -2,9 +2,11 @@
* The simulation, one fixed step at a time. Nothing here touches the
* renderer, so it runs headless too.
*/
+import { amounts, defaultCharter } from "../content.ts"
import { Game, Time } from "../schema.ts"
import { ApplyEdits } from "./edits.ts"
import { Deliver, Dispatch } from "./logistics.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"
import { AssignStaff, CountStock, Grow, IndexGrid, Plant, Raise, Spread, Work } from "./work.ts"
@@ -23,6 +25,7 @@ export const simulate = Game.Schedule(
ApplyEdits,
Game.Schedule.applyDeferred(),
IndexGrid,
+ Seasons,
Raise,
AssignStaff,
Grow,
@@ -39,10 +42,35 @@ export const simulate = Game.Schedule(
Households,
Collect,
CountStock,
- TakeCensus
+ TakeCensus,
+ Requests,
+ Approve,
+ Judge,
+ Record
)
-export { CELL_STEPS } from "./shared.ts"
+/** The world's resources before any town is founded (a `newTown` edit fills them in). */
+export const blankResources = () => ({
+ Time: { tick: 0 },
+ 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 },
+ Policy: { settlers: 100, citizens: 100, sells: [], buys: [], reserve: 25 },
+ Charter: { ...defaultCharter(0), founded: 0 },
+ Land: { mask: "", cells: 0 },
+ Market: { prices: amounts({}) },
+ Mood: { approval: 0, target: 0, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 },
+ Crown: { open: false, good: "wood" as const, amount: 0, issued: 0, due: 0, reward: 0, next: 0, met: 0, missed: 0, snubs: [] },
+ Fate: foundedFate(),
+ History: { samples: [] },
+ Chronicle: { lines: [] },
+ Grid: { owner: [], use: [] },
+ Stock: amounts({})
+})
+
+export { CELL_STEPS, elapsed, seasonAt, termTicks } from "./shared.ts"
export { SITE_SHARE } from "./work.ts"
export { unlocked } from "./edits.ts"
-export { capacity, met, satisfaction, taxOf } from "./town.ts"
+export { adminOf, askOf, capacity, met, priceOf, satisfaction, taxOf } from "./town.ts"
+export { crownGap, goalsOf, larder } from "./term.ts"
diff --git a/src/sim/shared.ts b/src/sim/shared.ts
index 7f8a0a0..36933a6 100644
--- a/src/sim/shared.ts
+++ b/src/sim/shared.ts
@@ -1,4 +1,5 @@
/** Queries and small helpers the simulation's systems share. */
+import { ticks, WINTER_SHARE, YEARS_PER_TERM } 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"
@@ -35,3 +36,26 @@ export const connected = (grid: GridValue, tile: TileLike): boolean => doors(gri
/** A walker's steps from one cell's centre to the next: three to a unit, so it moves on the lattice. */
export const CELL_STEPS = 48
+
+// ── Time ──────────────────────────────────────────────────────────────────
+
+/** Steps since the town was founded. */
+export const elapsed = (time: { readonly tick: number }, charter: { readonly founded: number }) => time.tick - charter.founded
+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)
+
+/**
+ * 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.
+ */
+export const seasonAt = (t: number, charter: { readonly term: number }) => {
+ 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 }
+}
+
diff --git a/src/sim/term.ts b/src/sim/term.ts
new file mode 100644
index 0000000..73e96b6
--- /dev/null
+++ b/src/sim/term.ts
@@ -0,0 +1,313 @@
+/**
+ * The term in office: the seasons turn, the crown asks for goods, the
+ * town's approval follows how it is treated, the town's history is kept,
+ * and the term ends: complete, lost, or run out.
+ */
+import {
+ crown, fate, goods, HISTORY_TICKS, mood, sizes, ticks, 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
+} from "../schema.ts"
+import { elapsed, seasonAt, termTicks } 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. */
+export const Seasons = Game.System(
+ "Town/Seasons",
+ {
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ chronicle: Game.System.writeResource(Chronicle)
+ }
+ },
+ ({ resources }) => {
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ 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.`)
+ if (!now.winter && before.winter) write(resources.chronicle, t, `Spring of year ${now.year}.`)
+ }
+)
+
+// ── The crown ─────────────────────────────────────────────────────────────
+
+/** Steps between the crown's requests. */
+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
+ * 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.
+ */
+export const Requests = Game.System(
+ "Town/Requests",
+ {
+ queries: {
+ makers: Game.Query({ selection: { recipe: Game.Query.read(Recipe) }, with: [Building], without: [Site, Rising] }),
+ stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ fate: Game.System.readResource(Fate),
+ crown: Game.System.writeResource(Crown),
+ treasury: Game.System.writeResource(Treasury),
+ rng: Game.System.writeResource(Rng),
+ chronicle: Game.System.writeResource(Chronicle)
+ }
+ },
+ ({ queries, resources }) => {
+ if (resources.fate.get().state !== "playing") return
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ const c = resources.crown.get()
+ const remembered = c.snubs.filter((at) => t - at < ticks(crown.memory * 60))
+ if (remembered.length !== c.snubs.length) resources.crown.set({ ...c, snubs: remembered })
+
+ if (c.open && t >= c.due) {
+ 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, 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.`)
+ return
+ }
+ if (c.open || t < c.next) return
+ // Something the town makes, sized to what it makes of it: from a third of
+ // what it can make in the time given, early in the term, to most of it.
+ // The crown waits until the town makes anything.
+ const rates = new Map<GoodId, number>()
+ for (const { data } of queries.makers.each()) {
+ const r = data.recipe.get()
+ rates.set(r.output, (rates.get(r.output) ?? 0) + (r.batch * 3600) / r.period)
+ }
+ const options = [...rates.keys()].sort()
+ if (options.length === 0) return
+ const random = Random.make(resources.rng.get())
+ const good = random.pick(options)!
+ resources.rng.set(random.state)
+ const progress = Math.min(1, t / termTicks(charter))
+ const window = (crownGap(charter) * crown.window) / 3600
+ const share = crown.share[0] + (crown.share[1] - crown.share[0]) * progress
+ // Never more than the town could keep in store.
+ const room = queries.stores.each().reduce((sum, { data }) => sum + data.inventory.get().cap, 0)
+ const amount = Math.max(4, Math.min(Math.round(room * crown.room), Math.round(rates.get(good)! * window * share)))
+ const reward = Math.round(amount * goods[good].price * crown.reward) + crown.bonus
+ 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.`)
+ }
+)
+
+// ── Approval ──────────────────────────────────────────────────────────────
+
+/**
+ * What the town makes of how it is run, every collection: its needs, its
+ * taxes, unpaid wages, snubs from the crown, a hungry winter. Approval
+ * moves towards that a few points at a time.
+ */
+export const Approve = Game.System(
+ "Town/Approve",
+ {
+ queries: { homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising] }) },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ policy: Game.System.readResource(Policy),
+ treasury: Game.System.readResource(Treasury),
+ crown: Game.System.readResource(Crown),
+ mood: Game.System.writeResource(Mood)
+ }
+ },
+ ({ queries, resources }) => {
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ if (t % ticks(10) !== 0) return
+ const policy = resources.policy.get()
+ let people = 0
+ let pleased = 0
+ let taxed = 0
+ let fed = 0
+ let homes = 0
+ for (const { data } of queries.homes.each()) {
+ const h = data.house.get()
+ homes += 1
+ if (h.food > 0) fed += 1
+ people += h.residents
+ pleased += h.residents * satisfaction(h)
+ taxed += h.residents * (h.tier === 1 ? policy.settlers : policy.citizens)
+ }
+ const share = people > 0 ? pleased / people : 0.5
+ const rate = people > 0 ? taxed / people : 100
+ const needs = Math.round(mood.needs[0] + (mood.needs[1] - mood.needs[0]) * share)
+ const taxes = Math.round((100 - rate) * mood.perTaxPoint)
+ const debt = resources.treasury.get().coins < 0 ? mood.debt : 0
+ const crownPart = resources.crown.get().snubs.length * mood.snub
+ const winter = seasonAt(t, resources.charter.get()).winter && homes > 0 && fed / homes < 0.5 ? mood.winterHunger : 0
+ const target = Math.max(-100, Math.min(100, mood.base + needs + taxes + debt + crownPart + winter))
+ resources.mood.update((m) => {
+ const approval = m.approval + Math.max(-mood.step, Math.min(mood.step, target - m.approval))
+ return { approval, target, base: mood.base, needs, taxes, debt, crown: crownPart, winter }
+ })
+ }
+)
+
+// ── The end of the term ───────────────────────────────────────────────────
+
+/** The fate of a town just founded. */
+export const foundedFate = () => ({
+ state: "playing" as const,
+ reason: "",
+ at: 0,
+ governing: false,
+ won: -1,
+ debtSince: -1,
+ revoltSince: -1,
+ goalSince: -1,
+ peak: 0,
+ score: 0
+})
+
+/** 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
+
+/** Each goal the town must hold to be complete, met or not. */
+export const goalsOf = (
+ charter: { readonly size: keyof typeof sizes },
+ s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly net: number; readonly approval: number }
+) => {
+ const goal = sizes[charter.size].goal
+ const residents = s.settlers + s.citizens
+ return [
+ { id: "residents", text: `${goal.residents} residents`, value: `${residents}`, met: residents >= goal.residents },
+ { id: "citizens", text: `${Math.round(fate.citizens * 100)}% of them citizens`, value: `${residents > 0 ? Math.round((s.citizens / residents) * 100) : 0}%`, met: residents > 0 && s.citizens >= residents * fate.citizens },
+ { id: "approval", text: `approval ${fate.approval} or more`, value: `${s.approval}`, met: s.approval >= fate.approval },
+ { id: "coins", text: `${goal.coins} coins, not losing any`, value: `${s.coins}`, met: s.coins >= goal.coins && s.net >= 0 }
+ ] as const
+}
+
+/** The town's score at the end of its term. */
+export const scoreOf = (s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly approval: number; readonly met: number; readonly missed: number }, won: boolean, minutesLeft: number) =>
+ Math.max(0, Math.round(s.settlers + 3 * s.citizens + Math.max(0, s.coins) / 20 + 2 * s.approval + 40 * s.met - 40 * s.missed + (won ? 500 + 20 * minutesLeft : 0)))
+
+/**
+ * Once a second: does the term end? It is lost to bankruptcy (in debt too
+ * long), revolt (approval too low too long), or abandonment (the town
+ * emptied); won once every goal has held long enough; and over when the
+ * term runs out. Dangers write to the chronicle as they begin.
+ */
+export const Judge = Game.System(
+ "Town/Judge",
+ {
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ census: Game.System.readResource(Census),
+ treasury: Game.System.readResource(Treasury),
+ ledger: Game.System.readResource(Ledger),
+ mood: Game.System.readResource(Mood),
+ crown: Game.System.readResource(Crown),
+ fate: Game.System.writeResource(Fate),
+ chronicle: Game.System.writeResource(Chronicle)
+ }
+ },
+ ({ resources }) => {
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ if (t <= 0 || t % 60 !== 0) return
+ const f = resources.fate.get()
+ if (f.state !== "playing") return
+ const census = resources.census.get()
+ const coins = resources.treasury.get().coins
+ const ledger = resources.ledger.get()
+ const approval = resources.mood.get().approval
+ const crownNow = resources.crown.get()
+ const residents = census.settlers + census.citizens
+ const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
+ const note = (text: string) => write(resources.chronicle, t, text)
+ 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)
+
+ const next = { ...f, peak: Math.max(f.peak, residents) }
+ for (const mark of [50, 100, 250, 500]) if (f.peak < mark && residents >= mark) note(`${mark} residents.`)
+
+ // Dangers.
+ if (coins < 0) {
+ if (f.debtSince < 0) note("The treasury is empty: wages go unpaid.")
+ 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.")
+ next.revoltSince = f.revoltSince < 0 ? t : f.revoltSince
+ } else next.revoltSince = -1
+
+ const end = (state: "won" | "lost" | "over", reason: string) => {
+ note(reason)
+ resources.fate.set({ ...next, state, reason, at: t, score: score(state === "won" || f.governing) })
+ }
+ if (next.debtSince >= 0 && t - next.debtSince >= minutes(fate.debt)) return end("lost", "Bankrupt: the crown has taken the treasury out of the mayor's hands.")
+ if (next.revoltSince >= 0 && t - next.revoltSince >= minutes(fate.revolt)) return end("lost", "Revolt: the town has turned the mayor out.")
+ if (next.peak >= fate.peak && residents < next.peak * fate.abandon) return end("lost", "Abandoned: the people have left the town.")
+ if (t >= termTicks(charter)) {
+ return end("over", f.governing ? "The term is over: the town stood complete to the end." : "The term is over.")
+ }
+
+ // Goals.
+ if (!f.governing) {
+ const goals = goalsOf(charter, { ...census, coins, net, approval })
+ if (goals.every((g) => g.met)) {
+ if (f.goalSince < 0) note("Every goal is met: the town needs only to hold them.")
+ next.goalSince = f.goalSince < 0 ? t : f.goalSince
+ if (t - next.goalSince >= minutes(fate.hold)) return end("won", "The town is complete.")
+ } else next.goalSince = -1
+ }
+ resources.fate.set(next)
+ }
+)
+
+/** A sample of the town every `HISTORY_TICKS`. */
+export const Record = Game.System(
+ "Town/Record",
+ {
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ census: Game.System.readResource(Census),
+ treasury: Game.System.readResource(Treasury),
+ ledger: Game.System.readResource(Ledger),
+ mood: Game.System.readResource(Mood),
+ fate: Game.System.readResource(Fate),
+ history: Game.System.writeResource(History)
+ }
+ },
+ ({ resources }) => {
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ if (t <= 0 || t % HISTORY_TICKS !== 0) return
+ const f = resources.fate.get()
+ if (f.state !== "playing") return
+ const census = resources.census.get()
+ const ledger = resources.ledger.get()
+ const sample = {
+ tick: t,
+ coins: resources.treasury.get().coins,
+ residents: census.settlers + census.citizens,
+ citizens: census.citizens,
+ approval: resources.mood.get().approval,
+ net: ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
+ }
+ resources.history.update((h) => ({ samples: [...h.samples, sample].slice(-1000) }))
+ }
+)
+
diff --git a/src/sim/town.ts b/src/sim/town.ts
index e8a16a9..e02ea5d 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -3,10 +3,13 @@
* taxes are collected from homes connected to the town hall and upkeep paid
* for every standing building; and the census counts it all.
*/
-import { appealOf, goods, home, kinds, LEDGER_TICKS, TRADE_LOAD, type Need, type Tier } from "../content.ts"
+import { admin, goodIds, goods, home, kinds, LEDGER_TICKS, market, PAUSED_UPKEEP, TRADE_LOAD, type GoodId, type Need, type Tier } from "../content.ts"
import { doors, key, reach } from "../grid.ts"
-import { Building, Census, Game, Grid, House, Inventory, Ledger, Policy, Rising, Site, Staff, Storage, Tile, Time, TownHall, Treasury } from "../schema.ts"
-import { connected } from "./shared.ts"
+import {
+ Building, Census, Charter, Game, Grid, House, Inventory, Ledger, Market, Mood, Paused, Policy, Rising, Site, Staff, Storage, Tile, Time,
+ TownHall, Treasury
+} from "../schema.ts"
+import { connected, elapsed, seasonAt } from "./shared.ts"
interface Needs {
readonly tier: Tier
@@ -30,49 +33,68 @@ export interface Rates {
}
const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)
+/** How approval (-100 → 100) sits with a home: half as many residents at its worst, half again at its best. */
+export const appealOf = (approval: number): number => 1 + approval / 200
+
/**
* Residents a home holds at its tier and satisfaction: half when nothing is
- * met, all when everything is; fewer under high taxes, and up to all of
- * them under low ones.
+ * 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.
*/
-export const capacity = (h: Needs, rates: Rates): number => {
+export const capacity = (h: Needs, approval: number): 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(rateOf(rates, h.tier)))))
+ return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h)) * appealOf(approval))))
}
+/** Coins a minute the town hall's administration costs for `homes` homes. */
+export const adminOf = (homes: number): number => Math.round(homes * (admin.perHome + homes / admin.growth))
+
+/** What traders pay for one of a good now, and what they ask for one. */
+export const priceOf = (good: GoodId, percent: number) => (goods[good].price * percent) / 100
+export const askOf = (good: GoodId, percent: number) => Math.ceil(priceOf(good, percent) * market.markup)
+
/** Coins a home pays a minute. */
export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates): number =>
h.residents * home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h))
/**
- * Needs wear off. 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:
+ * 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.
*/
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] }) },
- resources: { grid: Game.System.readResource(Grid), policy: Game.System.readResource(Policy) }
+ resources: {
+ grid: Game.System.readResource(Grid),
+ mood: Game.System.readResource(Mood),
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter)
+ }
},
({ queries, resources }) => {
const grid = resources.grid.get()
- const rates = resources.policy.get()
+ const approval = resources.mood.get().approval
+ 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
for (const { data } of queries.homes.each()) {
const h = data.house.get()
const next = {
...h,
clock: h.clock + 1,
- food: Math.max(0, h.food - 1),
- bread: Math.max(0, h.bread - 1),
+ food: Math.max(0, h.food - eat),
+ bread: Math.max(0, h.bread - eat),
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, rates) : 0
+ const cap = connected(grid, data.tile.get()) ? capacity(next, approval) : 0
next.residents += Math.sign(cap - next.residents)
}
data.house.set(next)
@@ -81,16 +103,20 @@ export const Households = Game.System(
)
/**
- * Every `LEDGER_TICKS`: taxes in from homes the town hall can reach by road,
- * coins from traders for what the town sells beyond its reserve (taken from
- * its storage, fullest first), and upkeep out for every standing building.
+ * Every `LEDGER_TICKS`: taxes in from homes the town hall can reach by road;
+ * trade with the travelling merchants, who buy what the town sells beyond
+ * its reserve (taken from its storage, fullest first) and sell it what it
+ * buys up to its reserve (brought to the storage with most room), at prices
+ * that fall the more the town sells and rise the more it buys; upkeep out
+ * for every standing building (a quarter for a paused one); and the town
+ * hall's administration, which grows faster than the town.
*/
export const Collect = Game.System(
"Town/Collect",
{
queries: {
homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising] }),
- buildings: Game.Query({ selection: { building: Game.Query.read(Building) }, without: [Site] }),
+ buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused) }, without: [Site] }),
halls: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [TownHall] }),
stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
},
@@ -98,6 +124,7 @@ export const Collect = Game.System(
time: Game.System.readResource(Time),
grid: Game.System.readResource(Grid),
policy: Game.System.readResource(Policy),
+ market: Game.System.writeResource(Market),
treasury: Game.System.writeResource(Treasury),
ledger: Game.System.writeResource(Ledger)
}
@@ -105,35 +132,72 @@ export const Collect = Game.System(
({ queries, resources }) => {
if (resources.time.get().tick % LEDGER_TICKS !== 0) return
const grid = resources.grid.get()
+ const policy = resources.policy.get()
const hall = queries.halls.each()[0]
const roads = hall ? reach(grid, doors(grid, hall.data.tile.get())) : null
const share = LEDGER_TICKS / (60 * 60)
let taxes = 0
+ let homes = 0
for (const { data } of queries.homes.each()) {
+ homes += 1
const reached = roads !== null && doors(grid, data.tile.get()).some((c) => roads.distance[key(c.x, c.y)]! >= 0)
- if (reached) taxes += taxOf(data.house.get(), resources.policy.get())
+ if (reached) taxes += taxOf(data.house.get(), policy)
}
let upkeep = 0
- for (const { data } of queries.buildings.each()) upkeep += kinds[data.building.get().kind].upkeep
- // Traders take the surplus.
- const policy = resources.policy.get()
+ for (const { data } of queries.buildings.each()) upkeep += kinds[data.building.get().kind].upkeep * (data.paused.present ? PAUSED_UPKEEP : 1)
+ const admin = adminOf(homes)
+
+ // Trade.
const stores = queries.stores.each()
- let sold = 0
- for (const good of policy.sells) {
+ const prices: Record<GoodId, number> = { ...resources.market.get().prices }
+ let coins = resources.treasury.get().coins + Math.round(taxes * share) - Math.round((upkeep + admin) * share)
+ let traded = 0
+ for (const good of goodIds) {
const held = stores.reduce((sum, { data }) => sum + data.inventory.get().stock[good], 0)
- let surplus = Math.min(TRADE_LOAD, held - policy.reserve)
- if (surplus <= 0) continue
- sold += surplus * goods[good].price
- for (const { data } of [...stores].sort((a, b) => b.data.inventory.get().stock[good] - a.data.inventory.get().stock[good])) {
- if (surplus <= 0) break
- const inv = data.inventory.get()
- const take = Math.min(surplus, inv.stock[good])
- data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - take } })
- surplus -= take
+ if (policy.sells.includes(good)) {
+ let surplus = Math.min(TRADE_LOAD, held - policy.reserve)
+ if (surplus > 0) {
+ const earned = Math.round(surplus * priceOf(good, prices[good]))
+ coins += earned
+ traded += earned
+ prices[good] = Math.max(market.floor, prices[good] - surplus * market.perUnit)
+ for (const { data } of [...stores].sort((a, b) => b.data.inventory.get().stock[good] - a.data.inventory.get().stock[good])) {
+ if (surplus <= 0) break
+ const inv = data.inventory.get()
+ const take = Math.min(surplus, inv.stock[good])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - take } })
+ surplus -= take
+ }
+ }
+ } else if (policy.buys.includes(good)) {
+ const ask = askOf(good, prices[good])
+ let wanted = Math.min(TRADE_LOAD, policy.reserve - held, Math.floor(coins / ask))
+ if (wanted > 0) {
+ coins -= wanted * ask
+ traded -= wanted * ask
+ prices[good] = Math.min(market.ceiling, prices[good] + wanted * market.perUnit)
+ 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])
+ if (put <= 0) continue
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] + put } })
+ wanted -= put
+ }
+ // What found no room is refunded.
+ if (wanted > 0) {
+ coins += wanted * ask
+ traded += wanted * ask
+ }
+ }
}
+ // Prices drift back towards the usual.
+ const gap = 100 - prices[good]
+ prices[good] += gap === 0 ? 0 : Math.sign(gap) * Math.max(1, Math.round(Math.abs(gap) / 10))
}
- resources.treasury.update((t) => ({ coins: t.coins + Math.round(taxes * share) + sold - Math.round(upkeep * share) }))
- resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(sold / share), upkeep: Math.round(upkeep) })
+ resources.market.set({ prices })
+ resources.treasury.set({ coins })
+ resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(traded / share), upkeep: Math.round(upkeep), admin })
}
)
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
index 385db82..00df25b 100644
--- a/src/sim/walkers.ts
+++ b/src/sim/walkers.ts
@@ -10,7 +10,7 @@ import { amounts, categoryColor, each, home, kinds, provisions, total, type Amou
import { DIRS, doors, isRoad, key, nearest, pathTo, reach } from "../grid.ts"
import { inside, type Point } from "../iso.ts"
import {
- Building, Figure, Game, Grid, House, Inventory, Recipe, Rising, Rng, Roam, Route, Service, Site, Staff, Status, Tile, WalkerOf,
+ Building, Figure, Game, Grid, House, Inventory, Paused, Recipe, Rising, Rng, Roam, Route, Service, Site, Staff, Status, Tile, WalkerOf,
maybe, type Status as StatusValue
} from "../schema.ts"
import { CELL_STEPS } from "./shared.ts"
@@ -18,7 +18,9 @@ import { CELL_STEPS } from "./shared.ts"
/** Steps a walker takes each tick: 1.25 cells a second. */
const WALK = 1
/** Of each provision, the most a walker's basket holds. */
-const BASKET = 6
+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. */
export const Walk = Game.System(
@@ -49,8 +51,8 @@ export const Walk = Game.System(
)
/**
- * A staffed service building sends one walker at a time, every `interval`
- * steps. A provisions walker fills its basket from the building's stock, and
+ * A staffed service building sends a walker every `interval` steps, up to
+ * `OUT` at a time. A provisions walker fills its basket from the building's stock, and
* only goes when there is something to hand out.
*/
export const SendWalkers = Game.System(
@@ -65,7 +67,8 @@ export const SendWalkers = Game.System(
service: Game.Query.write(Service),
status: Game.Query.write(Status),
inventory: Game.Query.optional(Inventory),
- recipe: Game.Query.optional(Recipe)
+ recipe: Game.Query.optional(Recipe),
+ paused: Game.Query.optional(Paused)
},
without: [Site, Rising]
}),
@@ -76,19 +79,21 @@ export const SendWalkers = Game.System(
},
({ queries, resources, commands }) => {
const grid = resources.grid.get()
- const out = new Set<number>()
- for (const { data } of queries.walkers.each()) out.add(data.home.get())
+ 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)
for (const { entity, data } of queries.services.each()) {
const service = data.service.get()
const staff = data.staff.get()
const starts = doors(grid, data.tile.get())
const stock = maybe(data.inventory)?.stock
- const staffed = staff.needed === 0 || staff.assigned > 0
+ 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
if (!maybe(data.recipe)) {
- const status: StatusValue = starts.length === 0
+ const status: StatusValue = data.paused.present
+ ? "paused"
+ : starts.length === 0
? "unconnected"
: !staffed
? "unstaffed"
@@ -101,7 +106,7 @@ export const SendWalkers = Game.System(
}
const cooldown = Math.max(0, service.cooldown - 1)
- if (cooldown === 0 && !out.has(entity.id) && starts.length > 0 && staffed && goes) {
+ 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(
[Figure, { role: "walker", color }],
diff --git a/src/sim/work.ts b/src/sim/work.ts
index 560f248..a0c0dd8 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -8,21 +8,22 @@ 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, useAt } from "../grid.ts"
+import { around, DIRS, GridBuilder, key, ownerAt, roadPrint, useAt } from "../grid.ts"
import {
- Field, FieldOf, Game, Gatherer, Grid, House, Inventory, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock,
- Storage, Tile, Time, Tree, maybe, type Status as StatusValue
+ 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
} from "../schema.ts"
-import { connected, TileRead, useOf } from "./shared.ts"
+import { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"
-/** What stands where, for every system after it this step. */
+/** What stands where on the land, for every system after it this step. */
export const IndexGrid = Game.System(
"Town/IndexGrid",
- { queries: { tiles: TileRead }, resources: { grid: Game.System.writeResource(Grid) } },
+ { queries: { tiles: TileRead }, resources: { land: Game.System.readResource(Land), grid: Game.System.writeResource(Grid) } },
({ queries, resources }) => {
- const grid = new GridBuilder()
+ const grid = new GridBuilder(resources.land.get().mask)
for (const { entity, data } of queries.tiles.each()) grid.claim(data.tile.get(), entity.id, useOf(data))
- resources.grid.set(grid.value())
+ const value = grid.value()
+ resources.grid.set({ ...value, roads: roadPrint(value) })
}
)
@@ -75,13 +76,16 @@ export const Raise = Game.System(
// ── Workers ───────────────────────────────────────────────────────────────
-/** Residents go to work in the order buildings were placed, as many as each needs while any are left. */
+/**
+ * Residents go to work in the order buildings were placed, as many as each
+ * needs while any are left; a paused 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) }, 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] })
},
resources: { grid: Game.System.readResource(Grid) }
},
@@ -91,7 +95,7 @@ export const AssignStaff = Game.System(
for (const { data } of queries.homes.each()) pool += data.house.get().residents
for (const { data } of queries.workplaces.each()) {
const staff = data.staff.get()
- const assigned = connected(grid, data.tile.get()) ? Math.min(staff.needed, pool) : 0
+ 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 })
}
@@ -105,7 +109,7 @@ 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.
+ * `period` steps. In winter, fishing goes at half pace.
*/
export const Work = Game.System(
"Town/Work",
@@ -118,7 +122,8 @@ export const Work = Game.System(
recipe: Game.Query.write(Recipe),
inventory: Game.Query.write(Inventory),
status: Game.Query.write(Status),
- gatherer: Game.Query.optional(Gatherer)
+ gatherer: Game.Query.optional(Gatherer),
+ paused: Game.Query.optional(Paused)
},
without: [Site, Rising]
}),
@@ -126,10 +131,12 @@ export const Work = Game.System(
rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),
fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
},
- resources: { grid: Game.System.readResource(Grid) }
+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) }
},
({ queries, resources, commands }) => {
const grid = resources.grid.get()
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ const slowFishing = seasonAt(t, resources.charter.get()).winter && t % 2 === 1
const trees = new Map(queries.trees.each().map((row) => [row.entity.id as number, row]))
const rocks = new Map(queries.rocks.each().map((row) => [row.entity.id as number, row]))
const fields = new Map(queries.fields.each().map((row) => [row.entity.id as number, row]))
@@ -190,14 +197,16 @@ export const Work = Game.System(
recipe = { ...recipe, progress: 1 }
}
}
- if (open && recipe.progress > 0 && staff.assigned > 0) {
+ if (open && recipe.progress > 0 && staff.assigned > 0 && !(slowFishing && gatherer?.source === "water")) {
const progress = recipe.progress + staff.assigned
if (progress > recipe.period * staff.needed) {
recipe = { ...recipe, progress: 0, made: recipe.made + 1 }
stock = { ...stock, [recipe.output]: stock[recipe.output] + recipe.batch }
} else recipe = { ...recipe, progress }
}
- const status: StatusValue = !open
+ const status: StatusValue = data.paused.present
+ ? "paused"
+ : !open
? "unconnected"
: staff.assigned === 0
? "unstaffed"
@@ -228,7 +237,8 @@ export const Plant = Game.System(
staff: Game.Query.read(Staff),
planter: Game.Query.write(Planter),
status: Game.Query.write(Status),
- recipe: Game.Query.optional(Recipe)
+ recipe: Game.Query.optional(Recipe),
+ paused: Game.Query.optional(Paused)
},
without: [Site, Rising]
})
@@ -249,7 +259,7 @@ export const Plant = Game.System(
const spots = reach.filter((c) => useAt(grid, c.x, c.y) === "empty" && !sown.has(key(c.x, c.y)))
// A forester has no recipe of its own: its status is its planting.
if (!maybe(data.recipe)) {
- const status: StatusValue = !open ? "unconnected" : staff.assigned === 0 ? "unstaffed" : grown < planter.max && spots.length > 0 ? "working" : "idle"
+ const status: StatusValue = data.paused.present ? "paused" : !open ? "unconnected" : staff.assigned === 0 ? "unstaffed" : grown < planter.max && spots.length > 0 ? "working" : "idle"
if (data.status.get() !== status) data.status.set(status)
}
const cooldown = Math.max(0, planter.cooldown - 1)
@@ -297,20 +307,22 @@ export const Spread = Game.System(
}
)
-/** Trees and fields grow until they are ready. */
+/** Trees and fields grow until they are ready; fields not in winter. */
export const Grow = Game.System(
"Town/Grow",
{
queries: {
trees: Game.Query({ selection: { tree: Game.Query.write(Tree) } }),
fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
- }
+ },
+ resources: { time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) }
},
- ({ queries }) => {
+ ({ queries, resources }) => {
for (const { data } of queries.trees.each()) {
const growth = data.tree.get().growth
if (growth < GROWN.tree) data.tree.set({ growth: growth + 1 })
}
+ if (seasonAt(elapsed(resources.time.get(), resources.charter.get()), resources.charter.get()).winter) return
for (const { data } of queries.fields.each()) {
const growth = data.field.get().growth
if (growth < GROWN.field) data.field.set({ growth: growth + 1 })
diff --git a/src/ui.ts b/src/ui.ts
index 69e93df..dd063f9 100644
--- a/src/ui.ts
+++ b/src/ui.ts
@@ -4,7 +4,7 @@
* 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, GoodId, KindId, Tier } from "./content.ts"
+import type { Amounts, CharterValue, GoodId, KindId, Tier } from "./content.ts"
import type { Point } from "./iso.ts"
import type { Status } from "./schema.ts"
@@ -20,12 +20,20 @@ export type Edit =
| { readonly type: "remove"; readonly cell: Point }
/** Sets a tier's tax rate, in percent of the usual. */
| { readonly type: "tax"; readonly tier: "settlers" | "citizens"; readonly rate: number }
- /** Sells a good to traders, or stops selling it. */
- | { readonly type: "sell"; readonly good: GoodId; readonly on: boolean }
- /** How much of each good the town keeps before selling. */
+ /** Sells a good to traders beyond the reserve, buys it up to the reserve, or neither. */
+ | { readonly type: "trade"; readonly good: GoodId; readonly mode: TradeMode }
+ /** How much of each good the town keeps before selling, and buys up to. */
| { readonly type: "reserve"; readonly amount: number }
- /** Clears everything and founds a new town on land grown from `seed`. */
- | { readonly type: "newTown"; readonly seed: number }
+ /** Pauses the building on a cell, or sets it back to work. */
+ | { readonly type: "pause"; readonly cell: Point; readonly on: boolean }
+ /** Sends the crown what it asked for. */
+ | { readonly type: "deliver" }
+ /** Having completed the town, stays on to govern it to the end of the term. */
+ | { readonly type: "govern" }
+ /** Clears everything and founds a new town on the land a charter describes. */
+ | { readonly type: "newTown"; readonly charter: CharterValue }
+
+export type TradeMode = "sell" | "buy" | "none"
/** What the pointer did, in world pixels. */
export type Gesture =
@@ -63,6 +71,9 @@ export type Panel =
readonly status: Status
/** Why it is not working, when it is not. */
readonly problem: string | null
+ /** Whether it can be paused (not the town hall, not a site), and whether it is. */
+ readonly pausable: boolean
+ readonly paused: boolean
readonly lines: ReadonlyArray<string>
}
| {
@@ -80,23 +91,71 @@ export interface HitBox {
readonly contains: (at: Point) => boolean
}
-/** The town's numbers for the top bar. */
+/** The town's numbers for the top bar and the panels. */
export interface Stats {
readonly coins: number
readonly taxes: number
readonly trade: number
readonly upkeep: number
- /** Coins a minute: taxes less upkeep. */
+ readonly admin: number
+ /** Coins a minute: taxes and trade less upkeep and administration. */
readonly net: number
readonly homes: number
/** Homes with each need met. */
readonly needs: { readonly food: number; readonly bread: number; readonly cloth: number; readonly faith: number }
- readonly policy: { readonly settlers: number; readonly citizens: number; readonly sells: ReadonlyArray<GoodId>; readonly reserve: number }
+ readonly policy: {
+ readonly settlers: number
+ readonly citizens: number
+ readonly sells: ReadonlyArray<GoodId>
+ readonly buys: ReadonlyArray<GoodId>
+ readonly reserve: number
+ }
readonly stock: Amounts
+ /** Each good's price with traders, in percent of the usual. */
+ readonly prices: Amounts
readonly settlers: number
readonly citizens: 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 mood: {
+ readonly approval: number
+ readonly target: number
+ readonly parts: ReadonlyArray<{ readonly label: string; readonly value: number }>
+ }
+ /** The crown's open request, if any: seconds left to answer it. */
+ readonly crown: {
+ readonly open: boolean
+ readonly good: GoodId
+ readonly amount: number
+ readonly left: number
+ readonly reward: number
+ readonly met: number
+ readonly missed: number
+ /** Seconds until the next request. */
+ readonly next: number
+ }
+ readonly fate: {
+ readonly state: "playing" | "won" | "lost" | "over"
+ readonly reason: string
+ /** Minute the term ended. */
+ readonly at: number
+ readonly governing: boolean
+ readonly score: number
+ /** Seconds left before each danger ends the term, or `null` when it is not threatening. */
+ readonly bankrupt: number | null
+ readonly revolt: number | null
+ /** Seconds the goals have to hold still, or `null` when they are not all met. */
+ readonly complete: number | null
+ readonly peak: number
+ }
+ readonly goals: ReadonlyArray<{ readonly text: string; readonly value: string; readonly met: boolean }>
+ readonly larder: number
+ readonly history: ReadonlyArray<{ readonly tick: number; readonly coins: number; readonly residents: number; readonly citizens: number; readonly approval: number; readonly net: number }>
+ readonly chronicle: ReadonlyArray<{ readonly tick: number; readonly text: string }>
}
export interface UiValue {
@@ -118,5 +177,9 @@ export interface UiValue {
/** Where each building and home stands (world pixels), for the camera to look at. */
centres: ReadonlyMap<number, Point>
stats: Stats | null
+ /** Steps of the simulation a fixed step: 0 (paused), 1, 2, or 4. */
+ speed: number
+ /** The new-town dialog is open: the town waits. */
+ founding: boolean
toast: (message: string) => void
}