Skip to content

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

Balance promotion, labor, supplies and rotating service patrols

SandroMaglione619268604f38
diff --git a/.gitignore b/.gitignore
index c781d0d..75e9a75 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ dist
snapshots/
output/inkline-3d/
output/balance-model/
+output/balance-rules/
diff --git a/docs/balance-model.md b/docs/balance-model.md
index f4278cc..5ff0660 100644
--- a/docs/balance-model.md
+++ b/docs/balance-model.md
@@ -15,9 +15,10 @@ pnpm balance:model search --homes 8
pnpm balance:model verify --seeds 32
pnpm balance:model report --seeds 32
pnpm balance:model:check
+pnpm balance --seeds 3 --term 60 --json output/balance-rules/results.json
```
-`report` writes `results.json`, `results.md` and a standalone `results.html` to `output/balance-model/`. `--out` chooses another directory. JSON preserves detailed capacities, household constraints, service probabilities, calibration errors and provenance. Reports always use the shipped parameters.
+`report` writes `results.json`, `results.md` and a standalone `results.html` to `output/balance-model/`. `--out` chooses another directory. JSON preserves detailed capacities, household constraints, service coverage, calibration errors and provenance. Reports always use the shipped parameters.
To reproduce the original bot-town analysis, first capture the PR's default sensible mayor:
@@ -64,11 +65,11 @@ flowchart LR
## What is calculated
-- Staffing uses the real commute graph, scarcity-first assignment, insertion-order tie breaks and apprenticeship pass.
+- Staffing uses the real commute graph, scarcity-first assignment, insertion-order tie breaks, skilled-job priority, citizen fallback into rough work and the apprenticeship pass.
- Workshop throughput integrates the actual periodic tick cadence. Apprentice and equipment factors can overlap, so multiplying average factors is insufficient.
- Resource flow is a pooled steady-state relaxation constrained by upstream recipes and accessible sources. Initial perishable stock supplies an instantaneous expected spoilage estimate. Food feasibility uses capacity before spoilage, so a large reserve does not create a false impossibility claim.
- Carrier budgets use real road distances, speed, load size and pools shared across goods. Specified transfers expose a necessary workload constraint. The live dispatch policy still has queues and finite inventory effects.
-- Service analysis enumerates finite non-backtracking random-walk paths by dynamic programming. Path hitting probabilities are exact for uniform choices on fixed roads. Mean occupancy, independent-excursion gap estimates and unlimited goods baskets are explicit approximations.
+- Service analysis uses the live game's deterministic tour planner. Bounded tours rotate so every reachable target is assigned a visit. Tour visit fractions are exact. Mean occupancy, evenly spaced launches and unlimited baskets remain explicit approximations.
- Desirability, tier eligibility, tax rounding, price changes, refunds, approval and seasonal timing use shared game functions.
- Local disaster deadlines use shared integer risk increments. Their inputs are held fixed; contagion and changing neighbourhoods require verification. Maintenance reports material demand and the repair-to-half-speed window.
- Progression evolves finite reserves, recipe rates, crop maturation, purchases, construction and household tiers in coarse time steps. It exposes construction conflicts, including farms planting over future workshop plots.
@@ -91,11 +92,11 @@ pnpm balance:model sweep --path kinds.weaver.recipe.seconds --values 4,8,12
`balance:model:check` checks module boundaries, immutable candidate inputs, staffing, inaccessible workplaces, resource conservation, desirability, carrier-pool accounting, configuration search and controlled real-game comparisons. Candidate weaver periods and park beauty/upkeep values are also executed by the game to verify that both consumers receive the same inputs.
-The construction case starts on authored flat land with roads and homes charged against fair starting funds, then builds through ordinary edits. It demonstrates a reachable citizen district in that stated starting configuration. It does not establish victory from every generated charter.
+The construction case starts on authored flat land with roads and homes charged against fair starting funds, then builds through ordinary edits, including a fire watch. It demonstrates a reachable citizen district in that stated starting configuration. Separate generated-charter regression checks require actual wins and the full two-minute goal hold through the ordinary mayor commands, without resource injections or parameter overrides. These examples do not establish victory from every generated charter.
-Production comparisons allow one incomplete job; transport allows one in-flight load per carrier at the observation boundary. Service comparisons use independent fixed seeds and report their sample sizes and statistical tolerances. The coarse forecast's timing and cash errors remain visible. Passing the controlled checks does not turn an approximate forecast into an exact outcome prediction.
+Production comparisons allow one incomplete job; transport allows one in-flight load per carrier at the observation boundary. Service comparisons measure complete tour rotations over fixed seeds and require exact visit fractions. The coarse forecast's timing and cash errors remain visible. Passing the controlled checks does not turn an approximate forecast into an exact outcome prediction.
-The original seed-1000 sensible mayor's entire minute-30 world is checked against PR #3 commit `9b7ce7336a18f917a10aa6e21ae32cb57af88643`, with reference SHA-256 `3eff85260d3a97c25ad628dcf244e8f8b4abc6cd02407eed4446807e03d97557`. This checks the shared-rule extraction across production, transport, random streams, risks, economy and persistence. The bot has no parks by minute 30; a separate real-game park comparison covers that rule family. Refresh the reference only after an intentional gameplay or engine change has been reviewed.
+Before gameplay tuning, the pure-rule extraction was verified against PR #3 commit `9b7ce7336a18f917a10aa6e21ae32cb57af88643`: the seed-1000 minute-30 world had SHA-256 `3eff85260d3a97c25ad628dcf244e8f8b4abc6cd02407eed4446807e03d97557`. The subsequent intentional promotion, staffing, patrol, delivery and parameter changes supersede that historical golden world. Current checks exercise the changed behavior, deterministic replay, save/load and full victory through legal player actions.
Every report includes rule, content, source and scenario fingerprints. A rule change recomputes the analysis; a semantic change in the game must either update a shared function or fail the behavior/verification checks. Mathematical approximations also need calibration when their assumptions change.
diff --git a/scripts/balance.ts b/scripts/balance.ts
index be03f09..94c907b 100644
--- a/scripts/balance.ts
+++ b/scripts/balance.ts
@@ -41,8 +41,8 @@ import { resolveRules } from "../src/rules/config.ts"
*/
import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, type Amounts, type CharterValue, type GoodId, type GroundId, type Kind, type KindId, type PropId } 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 { parksOf, ringOf } from "../src/appeal.ts"
+import { around, canPlace, DIRS, entrances, GridBuilder, isRoad, key, doors, nearest, reach, roadPrint, useAt, type Use } from "../src/grid.ts"
+import { parksOf, ringOf, effectAt } from "../src/appeal.ts"
import { GRID, inside, type Point } from "../src/iso.ts"
import type { GridValue } from "../src/schema.ts"
import { headless, type Snapshot } from "../src/sim/headless.ts"
@@ -50,6 +50,8 @@ import { goalsOf, larder, seasonAt } from "../src/sim/index.ts"
import type { Edit } from "../src/ui.ts"
import { SAVE_FORMAT, SAVE_VERSION } from "../src/save.ts"
import { mkdirSync, writeFileSync } from "node:fs"
+import { dirname } from "node:path"
+import { fingerprint } from "../tools/balance/provenance.ts"
// ── Options ───────────────────────────────────────────────────────────────
@@ -131,7 +133,7 @@ interface World {
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 fate: { readonly state: string; readonly reason: string; readonly at: number; readonly score: number; readonly goalSince: number }
readonly charter: { readonly size: CharterValue["size"]; readonly term: number; readonly founded: number }
readonly tick: number
}
@@ -170,7 +172,7 @@ const read = (snapshot: Snapshot): World => {
if (c["Town/Storage"] && c["Town/Inventory"]) for (const g of goodIds) stock[g] = (stock[g] ?? 0) + c["Town/Inventory"].stock[g]
}
return {
- grid: builder.value(),
+ grid: { ...builder.value(), roads: roadPrint(builder.value()) },
appeal: r["Town/Appeal"].cells,
paved,
parks,
@@ -201,6 +203,7 @@ const net = (w: World) => w.ledger.taxes + w.ledger.trade - w.ledger.upkeep - w.
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 citizenHomeTarget = (w: World) => Math.ceil(Math.max(content.sizes[w.charter.size].goal.residents, residents(w)) * content.fate.citizens / content.home.tiers[2].residents * 4 / 3)
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" }
@@ -216,6 +219,7 @@ const score = (w: World, kind: Kind, tile: Tile): number => {
/** Where to put a kind: road at a door, room for it, and (for gatherers) the most to work, nearest the middle as a tiebreak. */
const spotFor = (w: World, kind: Kind): Point | null => {
+ const workersRoads = w.homes.map(home => ({ home, roads: reach(w.grid, doors(w.grid, home.tile)) }))
let best: { cell: Point; value: number } | null = null
const needs = kind.gathers ? (kind.gathers.source === "tree" ? 8 : kind.gathers.source === "water" ? 2 : kind.gathers.source === "field" ? 0 : 2) : 0
for (let y = 0; y + kind.size <= GRID; y++) {
@@ -229,7 +233,9 @@ const spotFor = (w: World, kind: Kind): Point | null => {
// A forester belongs beside a lumberjack, replanting what it fells.
if (kind.id === "forester" && !w.buildings.some((b) => b.kind === "lumberjack" && Math.abs(b.tile.x - x) <= 5 && Math.abs(b.tile.y - y) <= 5)) continue
// A zoning mayor keeps dirty workshops a couple of cells clear of homes; services go among the homes.
- const dirty = zoned() && (kind.appeal?.value ?? 0) <= -4 && !kind.gathers ? Math.min(2, nearestHome(w, tile)) * 2 : 0
+ const dirty = zoned() && kind.appeal && kind.appeal.value < 0
+ ? w.homes.reduce((n, h) => n + effectAt(kind.appeal!, ringOf(tile, h.tile.x, h.tile.y)) * (h.tier >= 2 ? 6 : 2), 0)
+ : 0
// A fire watch, healer, or watch house goes among the homes whose signs are up; a builder among run-down ones.
const risky = kind.service?.service === "fire" || kind.service?.service === "health" || kind.service?.service === "order" ? kind.service.service : null
const amid = risky !== null
@@ -238,7 +244,14 @@ const spotFor = (w: World, kind: Kind): Point | null => {
? w.homes.filter((h) => h.condition < 700 && ringOf(tile, h.tile.x, h.tile.y) <= 6).length * 3
: kind.service && kind.id !== "market" ? homesAround(w, tile, 4) : 0
// Workers walk at most `COMMUTE` road cells: a workplace well away from every home stands empty.
- if (w.homes.length > 0 && kind.workers > 0 && nearestHome(w, tile) > 9) continue
+ if (w.homes.length > 0 && kind.workers > 0) {
+ const entrances = doors(w.grid, tile)
+ const workers = workersRoads.reduce((n, h) => {
+ const found = nearest(h.roads, entrances)
+ return n + (found && found.distance <= content.COMMUTE ? h.home.residents : 0)
+ }, 0)
+ if (workers < kind.workers) continue
+ }
// Services go where they are needed, wherever that is; everything else as near the middle as it can.
const value = (kind.gathers || kind.plants ? s * 10 : 0) + dirty + amid * 2 - Math.hypot(x - middle, y - middle) / (risky !== null ? 4 : 1)
if (!best || value > best.value) best = { cell: { x, y }, value }
@@ -299,12 +312,13 @@ const homeSpots = (w: World, n: number, near?: Tile): Array<Point> => {
*/
const parkFor = (w: World, size: number, value: number): Point | null => {
const short = w.homes.filter((h) => {
- if (h.site || h.tier === 3 || !h.provided) return false
+ if (h.site || h.tier === 3) return false
const v = w.appeal[key(h.tile.x, h.tile.y)] ?? 0
const goal = content.home.tiers[h.tier === 1 ? 2 : 3].appeal
return v < goal && v >= goal - value
})
- if (short.length < 3) return null
+ const minimum = size === 1 ? 1 : 3
+ if (short.length < minimum) return null
const reach = content.park.reach[0] + Math.floor((size * size) / content.park.reach[1])
let best: { cell: Point; value: number } | null = null
for (let y = 0; y + size <= GRID; y++) {
@@ -312,7 +326,7 @@ const parkFor = (w: World, size: number, value: number): Point | null => {
const tile = { x, y, size }
if (!canPlace(w.grid, tile) || offPlan(tile)) continue
const value = short.filter((h) => ringOf(tile, h.tile.x, h.tile.y) <= Math.max(1, reach - 1)).length
- if (value >= 3 && (!best || value > best.value)) best = { cell: { x, y }, value }
+ if (value >= minimum && (!best || value > best.value)) best = { cell: { x, y }, value }
}
}
return best?.cell ?? null
@@ -424,8 +438,10 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b
// 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)
+ const plannedHomes = citizenHomeTarget(w)
+ const citizenHomes = Math.max(plannedHomes, w.homes.filter(h => !h.site && (h.tier >= 2 || (w.appeal[key(h.tile.x, h.tile.y)] ?? 0) >= home.tiers[2].appeal)).length)
+ const bakeries = Math.max(1, Math.ceil(citizenHomes / 8))
+ const weavers = Math.max(1, Math.ceil(citizenHomes / 12))
return [
...basics,
// One of each first, saved up for (see `saving`): tools are scarce until there are citizens to run a smithy.
@@ -447,7 +463,7 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b
{ kind: "warehouse", when: count(w, "warehouse") < Math.floor(homes / 25) },
// Fish and bread rot: a granary keeps them, and smoked fish keeps.
{ kind: "granary", when: homes >= 40 && count(w, "granary") < 1 + Math.floor(homes / 70) },
- { kind: "smokehouse", when: larder(w.stock) >= homes && count(w, "smokehouse") < Math.floor(count(w, "fishery") / 5) },
+ { kind: "smokehouse", when: homes >= 30 && count(w, "smokehouse") < Math.floor(count(w, "fishery") / 3) },
{ 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 }
]
@@ -480,7 +496,8 @@ const decide = (w: World): ReadonlyArray<Edit> => {
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.
// Never at any price: buying drives it up, so stop at half again the usual.
- const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["planks", 6, 14], ["stone", 4, 12], ["tools", 3, 6], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) ? 1000 : -1, 24]]
+ const civicShort = w.coins > 1500 && count(w, "mill") > 0 && count(w, "weaver") > 0 && count(w, "chapel") > 0 && w.census.citizens! < Math.max(content.sizes[w.charter.size].goal.residents, residents(w)) * content.fate.citizens
+ const shortages: ReadonlyArray<readonly [GoodId, number, number]> = [["bread", civicShort ? 8 : -1, 20], ["cloth", civicShort ? 4 : -1, 12], ["planks", 6, 14], ["stone", 4, 12], ["tools", 3, 6], ["fish", (fed < 0.5 && w.stock.fish < 10) || (closing && fed < 0.7 && w.stock.fish < 20) ? 1000 : -1, 24]]
for (const [g, low, enough] of shortages) {
if (g === crownBuy) continue
const buying = w.policy.buys.includes(g)
@@ -507,8 +524,22 @@ const decide = (w: World): ReadonlyArray<Edit> => {
if (bot !== "idle") for (const r of w.ruins) edits.push({ type: "remove", cell: { x: r.tile.x, y: r.tile.y } })
if (bot === "idle" && residents(w) > 30) return edits
+ // Establish enough desirable homes before adding more cottages or repeating industrial chains.
+ const citizenHomes = citizenHomeTarget(w)
+ const eligible = w.homes.filter(h => !h.site && (w.appeal[key(h.tile.x, h.tile.y)] ?? 0) >= content.home.tiers[2].appeal).length
+ if (zoned() && residents(w) >= 30 && count(w, "chapel") > 0 && eligible < citizenHomes && w.coins > 250) {
+ const furnishingEdit = furnishing(w)
+ if (furnishingEdit) return [...edits, furnishingEdit]
+ const large = parkFor(w, 2, 9)
+ const size = large ? 2 : 1
+ const spot = large ?? parkFor(w, 1, w.census.citizens! >= 20 ? 6 : 5)
+ if (spot && affordable(w, { coins: size * size * content.grounds.flowers.cost.coins, materials: {} })) {
+ const cells = Array.from({ length: size * size }, (_, i) => ({ x: spot.x + i % size, y: spot.y + Math.floor(i / size) }))
+ return [...edits, { type: "ground", ground: "flowers", cells }]
+ }
+ }
// Workers' cottages beside a workplace no settler can walk to.
- const lonely = w.buildings.find((b) => !b.site && b.status === "unstaffed" && b.nearby === 0 && kinds[b.kind].crew === "settlers" && kinds[b.kind].workers > 0)
+ const lonely = w.buildings.find((b) => !b.site && b.status === "unstaffed" && kinds[b.kind].workers > 0)
if (lonely && affordable(w, { coins: home.cost.coins * 3, materials: { planks: 3 } })) {
const spots = homeSpots(w, 3, lonely.tile).filter((c) => ringOf(lonely.tile, c.x, c.y) <= 6)
if (spots.length > 0) return [...edits, { type: "homes", cells: spots }]
@@ -517,7 +548,7 @@ const decide = (w: World): ReadonlyArray<Edit> => {
// 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)
+ const short = w.census.jobs! + 6 > residents(w) || (fed >= 0.6 && w.stock.planks >= 8 && w.coins > 300 && residents(w) < goal * 1.1 && w.homes.length < Math.ceil(goal / home.tiers[1].residents))
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 }]
@@ -622,6 +653,7 @@ const run = (seed: number) => {
const problems: Record<string, number> = {}
const ruined = new Set<number>()
const spend: Record<string, number> = {}
+ let longestGoalHold = 0
let w = read(town.snapshot())
const DECIDE = 5
for (let t = 0; t < term * 60 + DECIDE && w.fate.state === "playing"; t += DECIDE) {
@@ -642,6 +674,7 @@ const run = (seed: number) => {
ui.edits.push(...chosen)
step(DECIDE)
w = read(town.snapshot())
+ if (w.fate.goalSince >= 0) longestGoalHold = Math.max(longestGoalHold, (w.tick - w.charter.founded - w.fate.goalSince) / 60)
for (const r of w.ruins) ruined.add(r.id)
if ((t + DECIDE) % 60 !== 0) continue
if (process.env.TRACE) {
@@ -705,11 +738,15 @@ const run = (seed: number) => {
settlers: w.census.settlers!, citizens: w.census.citizens!, coins: w.coins, net: net(w), approval: w.mood.approval
}, rules).map((g) => `${g.met ? "✓" : "✗"} ${g.text} (${g.value})`).join(" · ")
const hh = Math.max(1, w.homes.length)
+ console.log(` longest continuous goal hold: ${longestGoalHold.toFixed(1)} seconds`)
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 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, lost: ruined.size }
+ const final = town.snapshot().resources
+ return { seed, rows, problems, end, score: w.fate.score, built, stock: w.stock, crown: w.crown, lastGoals, supplied, lost: ruined.size,
+ longestGoalHoldSeconds: longestGoalHold,
+ final: { census: final["Town/Census"], treasury: final["Town/Treasury"], ledger: final["Town/Ledger"], mood: final["Town/Mood"], fate: final["Town/Fate"], charter: final["Town/Charter"] } }
}
const pad = (v: unknown, n: number) => String(v).padStart(n)
@@ -769,6 +806,11 @@ const play = (which: Bot) => {
}
const mine = play(bot)
+const jsonOut = option("json", "")
+if (jsonOut) {
+ mkdirSync(dirname(jsonOut), { recursive: true })
+ writeFileSync(jsonOut, JSON.stringify({ size, land, term, bot, rulesSha256: fingerprint(rules), results: mine }, null, 2))
+}
if (versus !== "") {
const first = bot
const theirs = play(versus)
diff --git a/scripts/check.ts b/scripts/check.ts
index c346213..57b48d2 100644
--- a/scripts/check.ts
+++ b/scripts/check.ts
@@ -449,7 +449,7 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entities
const w2 = entity(t, sawmill)!.components["Town/Staff"]
check(
"crews",
- q1.assigned === 0 && w1.assigned === 2 && w1.apprentices === 0 && w2.apprentices > 0 && q2.assigned > 0,
+ q1.assigned === 3 && q1.apprentices === 0 && w1.assigned === 2 && w1.apprentices === 0 && w2.apprentices > 0 && q2.assigned > 0,
`citizens only: quarry ${q1.assigned}/3, sawmill ${w1.assigned}/2; settlers only: quarry ${q2.assigned}/3, sawmill ${w2.assigned}/2 (${w2.apprentices} apprentices)`
)
}
diff --git a/src/content.ts b/src/content.ts
index 753e62a..940ea29 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -85,7 +85,7 @@ export const homeColor = 0xc4523f
export type Source = "tree" | "stone" | "ore" | "field" | "water"
export const serviceIds = ["goods", "faith", "fire", "health", "order", "repair"] as const
export type ServiceId = (typeof serviceIds)[number]
-/** Who works a building: settlers do the rough work, citizens the skilled (see `AssignStaff`). */
+/** Native crews: surplus citizens can also do rough work; settlers learn skilled jobs as apprentices. */
export type Crew = "settlers" | "citizens"
export type Topper = "none" | "chimney" | "flag" | "cupola" | "sails" | "crates"
@@ -254,13 +254,13 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
id: "sheep", title: "Sheep farm", blurb: "shears sheep for wool",
category: "crafts", size: 3, half: 12, stories: 1, roof: "gable", bays: 2, window: 4, topper: "none",
cost: { coins: 100, materials: { planks: 4 } }, upkeep: 5, workers: 2, crew: "settlers", unlock: { residents: 15, citizens: 0 }, buildable: true,
- recipe: { input: null, inputs: 0, output: "wool", batch: 1, seconds: 8 }, carriers: 2, appeal: { value: -2, reach: 2 }
+ recipe: { input: null, inputs: 0, output: "wool", batch: 1, seconds: 6 }, carriers: 2, appeal: { value: -2, reach: 2 }
},
weaver: {
id: "weaver", title: "Weaver", blurb: "weaves wool into cloth",
category: "crafts", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "none",
cost: { coins: 150, materials: { planks: 4, stone: 2, tools: 1 } }, upkeep: 8, workers: 2, crew: "citizens", unlock: { residents: 15, citizens: 0 }, buildable: true,
- recipe: { input: "wool", inputs: 1, output: "cloth", batch: 1, seconds: 8 }, holds: { accepts: ["wool", "cloth"], cap: 8 }, carriers: 2,
+ recipe: { input: "wool", inputs: 1, output: "cloth", batch: 1, seconds: 6 }, holds: { accepts: ["wool", "cloth"], cap: 8 }, carriers: 2,
wear: 60, appeal: { value: -2, reach: 2 }
},
market: {
@@ -403,7 +403,7 @@ 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(90), cloth: ticks(180), faith: ticks(150) } as Readonly<Record<Need, number>>,
+ lasts: { food: ticks(90), bread: ticks(120), cloth: ticks(240), faith: ticks(180) } as Readonly<Record<Need, number>>,
/** Where nobody wants to live: homes at this desirability or less hold `crowded` as many. */
squalid: -5,
crowded: 0.6
@@ -522,8 +522,8 @@ export const CONDITION_MAX = 1000
export const condition = {
/** A point lost every `every` steps: from new to run down in about 33 minutes, and fallen down in 67, unmended. */
every: ticks(4),
- /** Below this, a builder mends it as they pass (about every half hour). */
- mend: 550,
+ /** Below this, a builder mends it as they pass (after about 23 minutes without repair). */
+ mend: 650,
/** Below this, it works at half pace, and its fire risk rises. */
worn: 500
}
@@ -593,12 +593,12 @@ export const lands: Readonly<Record<LandId, {
fair: {
title: "fair", blurb: "enough of everything, if it is not wasted",
forests: 5.5, stone: 3, ore: 2, rock: 32, lakes: 2, coins: 1900,
- stock: amounts({ wood: 10, planks: 40, stone: 16, tools: 8, fish: 20 })
+ stock: amounts({ wood: 10, planks: 40, stone: 16, tools: 10, 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: 1500,
- stock: amounts({ wood: 10, planks: 30, stone: 12, tools: 6, fish: 15 })
+ stock: amounts({ wood: 10, planks: 30, stone: 12, tools: 8, fish: 15 })
}
}
@@ -630,7 +630,7 @@ export type WinterId = (typeof winterIds)[number]
export const winters: Readonly<Record<WinterId, { readonly title: string; readonly share: number; readonly fishing: number; readonly heating: boolean; readonly chance: number }>> = {
mild: { title: "mild", share: WINTER_SHARE, fishing: 0.75, heating: false, chance: 0.3 },
normal: { title: "normal", share: WINTER_SHARE, fishing: 0.5, heating: false, chance: 0.45 },
- hard: { title: "hard", share: WINTER_SHARE * 1.5, fishing: 0.25, heating: true, chance: 0.25 }
+ hard: { title: "hard", share: WINTER_SHARE * 1.5, fishing: 0.4, heating: true, chance: 0.25 }
}
/** The almanac warns of winter this many steps before it comes. */
export const WINTER_WARNING = ticks(60)
diff --git a/src/rules/households.ts b/src/rules/households.ts
index 13d26ef..0f2326a 100644
--- a/src/rules/households.ts
+++ b/src/rules/households.ts
@@ -80,17 +80,24 @@ export const ageNeeds = <T extends Needs & { readonly clock: number }>(h: T, eat
cloth: Math.max(0, h.cloth - 1), faith: Math.max(0, h.faith - 1)
})
-/** One goods visit. Bread is preferred for food even at a settlers' home. */
-export const serveGoods = <T extends Needs>(house: T, available: Readonly<Record<GoodId, number>>, rules: Rules = shippedRules) => {
+/** Citizen goods also reach settlers whose neighbourhood permits promotion. */
+export const wantsCitizenGoods = (house: Needs, desirability: number, rules: Rules = shippedRules) =>
+ house.tier >= 2 || desirability >= rules.home.tiers[2].appeal
+
+/** Eligible settlers request bread independently of food; other settlers use fish first. */
+export const serveGoods = <T extends Needs>(house: T, available: Readonly<Record<GoodId, number>>, rules: Rules = shippedRules, desirability = 0) => {
const h = { ...house } as Mutable<T>, basket = { ...available }
+ const citizens = wantsCitizenGoods(h, desirability, rules)
let eaten = 0
- if ((lowNeed(h.food, "food", rules) || (h.tier >= 2 && lowNeed(h.bread, "bread", rules))) && basket.bread > 0) {
+ if (citizens && (lowNeed(h.food, "food", rules) || lowNeed(h.bread, "bread", rules)) && basket.bread > 0) {
basket.bread -= 1; h.food = rules.home.lasts.food; h.bread = rules.home.lasts.bread; eaten += 1
} else if (lowNeed(h.food, "food", rules) && (basket.fish > 0 || basket.smoked > 0)) {
const g = basket.fish > 0 ? "fish" : "smoked"
basket[g] -= 1; h.food = rules.home.lasts.food; eaten += 1
+ } else if (lowNeed(h.food, "food", rules) && basket.bread > 0) {
+ basket.bread -= 1; h.food = rules.home.lasts.food; h.bread = rules.home.lasts.bread; eaten += 1
}
- if (lowNeed(h.cloth, "cloth", rules) && basket.cloth > 0) {
+ if (citizens && lowNeed(h.cloth, "cloth", rules) && basket.cloth > 0) {
basket.cloth -= 1; h.cloth = rules.home.lasts.cloth
}
return { house: h, basket, eaten }
diff --git a/src/rules/patrol.ts b/src/rules/patrol.ts
new file mode 100644
index 0000000..c378926
--- /dev/null
+++ b/src/rules/patrol.ts
@@ -0,0 +1,54 @@
+import { around, doors, isRoad, key, nearest, pathTo, reach, roadPrint, type TileLike } from "../grid.ts"
+import type { GridValue } from "../schema.ts"
+import type { Point } from "../iso.ts"
+
+export interface PatrolTarget { readonly id: number; readonly tile: TileLike }
+export interface PatrolPlan {
+ readonly tours: ReadonlyArray<ReadonlyArray<Point>>
+ readonly unreachable: ReadonlyArray<number>
+}
+
+/** Every edge cell can serve a building, matching the runtime's adjacent-cell check. */
+export const serviceDoors = (grid: GridValue, tile: TileLike) => around(tile, 1).filter(p =>
+ isRoad(grid, p.x, p.y) && ((p.x >= tile.x && p.x < tile.x + tile.size) || (p.y >= tile.y && p.y < tile.y + tile.size)))
+
+const cache = new Map<string, PatrolPlan>()
+/** Bounded outbound tours, rotated on each dispatch. Return distance still occupies a walker. */
+export const planPatrols = (grid: GridValue, source: TileLike, range: number, targets: ReadonlyArray<PatrolTarget>): PatrolPlan => {
+ const fingerprint = grid.roads ?? roadPrint(grid)
+ const id = JSON.stringify([fingerprint, source, range, targets])
+ const known = cache.get(id)
+ if (known) return known
+ const starts = doors(grid, source)
+ if (starts.length === 0 || range < 1) return { tours: [], unreachable: targets.map(t => t.id) }
+ const start: Point = { x: starts[0]!.x, y: starts[0]!.y }
+ const local = { ...grid, roads: fingerprint }, from = reach(local, [start])
+ const at = targets.map(t => ({ ...t, doors: serviceDoors(local, t.tile) }))
+ const remaining = at.filter(t => { const n = nearest(from, t.doors); return n !== null && n.distance < range })
+ const unreachable = at.filter(t => !remaining.includes(t)).map(t => t.id)
+ const tours: Point[][] = []
+ while (remaining.length > 0) {
+ const tour: Point[] = [start]
+ for (;;) {
+ const way = reach(local, [tour.at(-1)!])
+ let best: { index: number; path: Point[]; distance: number } | null = null
+ for (const [index, target] of remaining.entries()) {
+ const found = nearest(way, target.doors)
+ if (!found || tour.length + found.distance > range) continue
+ if (!best || found.distance < best.distance || (found.distance === best.distance && target.id < remaining[best.index]!.id))
+ best = { index, path: pathTo(way, found.cell), distance: found.distance }
+ }
+ if (!best) break
+ tour.push(...best.path.slice(1))
+ // Every target beside any cell on this tour is already covered.
+ const visited = new Set(tour.map(p => key(p.x, p.y)))
+ for (let i = remaining.length - 1; i >= 0; i--)
+ if (remaining[i]!.doors.some(p => visited.has(key(p.x, p.y)))) remaining.splice(i, 1)
+ }
+ tours.push(tour)
+ }
+ const result = { tours, unreachable }
+ if (cache.size >= 256) cache.clear()
+ cache.set(id, result)
+ return result
+}
diff --git a/src/rules/production.ts b/src/rules/production.ts
index 3e6c9f7..5d591b7 100644
--- a/src/rules/production.ts
+++ b/src/rules/production.ts
@@ -30,10 +30,12 @@ export const assignWorkers = (homes: ReadonlyArray<CrewHome>, workplaces: Readon
if (!h || h.crew !== crew || h.left === 0) continue
const take = Math.min(place.needed - place.assigned, h.left)
h.left -= take; place.assigned += take
- if (crew !== place.crew) place.apprentices += take
+ if (place.crew === "citizens" && crew === "settlers") place.apprentices += take
}
}
for (const p of order) fill(p, p.crew)
+ // Skilled jobs retain their crews; surplus citizens may do rough work at full pace.
+ for (const p of order) if (p.crew === "settlers") fill(p, "citizens")
for (const p of order) if (p.crew === "citizens") fill(p, "settlers")
return new Map(places.map((p) => [p.id, { assigned: p.assigned, apprentices: p.apprentices, nearby: p.nearby }]))
}
diff --git a/src/rules/transport.ts b/src/rules/transport.ts
index b109798..7dbb639 100644
--- a/src/rules/transport.ts
+++ b/src/rules/transport.ts
@@ -8,8 +8,10 @@ export const onwardRoads = (grid: GridValue, cell: Point, previous: Point | null
.filter((c) => isRoad(grid, c.x, c.y) && !(previous && c.x === previous.x && c.y === previous.y))
export interface DeliveryCandidate {
- readonly site: boolean; readonly distance: number
+ readonly site: boolean; readonly distance: number; readonly fill?: number
}
-/** Construction first, then nearest; exact ties keep the earlier candidate. */
+/** Construction first; operating shelves with the lowest fill come next, then distance. */
export const preferDelivery = (candidate: DeliveryCandidate, best: DeliveryCandidate | null): boolean =>
- best === null || (candidate.site && !best.site) || (candidate.site === best.site && candidate.distance < best.distance)
+ best === null || (candidate.site && !best.site) || (candidate.site === best.site &&
+ (candidate.site ? candidate.distance < best.distance :
+ (candidate.fill ?? 0) < (best.fill ?? 0) || ((candidate.fill ?? 0) === (best.fill ?? 0) && candidate.distance < best.distance)))
diff --git a/src/schema.ts b/src/schema.ts
index 43adadf..eb06fa1 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -141,6 +141,8 @@ export const Carriers = Descriptor.ConstructedComponent(Decode.struct({ count: i
/** Sends a walker out every `interval` steps. */
export const Service = Descriptor.ConstructedComponent(Decode.struct({ service, interval: integer, cooldown: integer, range: integer }))("Town/Service")
+/** The next tour of a service's district. Optional in older saved worlds. */
+export const Patrol = Descriptor.ConstructedComponent(Decode.struct({ next: integer }))("Town/Patrol")
// ── Walkers ───────────────────────────────────────────────────────────────
@@ -341,7 +343,7 @@ export const Game = Schema.bind(
Schema.fragment({
components: {
Tile, Road, Paved, Park, Ruin, Site, Rising, Tree, Rock, Water, Field, House, Risk, Condition, Burning, Sick, Building, TownHall, Status,
- Paused, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Figure, Route, Errand, Rescue, Roam
+ Paused, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Patrol, Figure, Route, Errand, Rescue, Roam
},
resources: {
Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Appeal, Pantry, Fires,
diff --git a/src/sim/logistics.ts b/src/sim/logistics.ts
index c8deb28..3160a0d 100644
--- a/src/sim/logistics.ts
+++ b/src/sim/logistics.ts
@@ -1,17 +1,19 @@
import { transport } from "../rules/config.ts"
+import { wantsCitizenGoods } from "../rules/households.ts"
+import { appealAt } from "../appeal.ts"
import { preferDelivery } from "../rules/transport.ts"
/**
* Carriers: every good that moves walks along the roads in a carrier's
* crate. What a building wants — a site's materials, a workshop's input, a
* market's provisions — is a demand; a producer sends what it makes to the
- * nearest demand for it, or else to the nearest storage with room, and a
- * storage sends what it holds to the nearest demands it can meet. Crates
+ * emptiest operating shelf, or else to the nearest storage with room, and a
+ * storage balances the demands it can meet. Construction comes first. Crates
* already on their way count against a demand, so no one is sent twice.
*/
import { goodIds, provisions, type GoodId } from "../content.ts"
-import { doors, nearest, pathTo, reach, type Reach } from "../grid.ts"
+import { doors, nearest, pathTo, reach, key, type Reach } from "../grid.ts"
import type { Point } from "../iso.ts"
-import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe } from "../schema.ts"
+import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, House, Appeal, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe } from "../schema.ts"
import { CELL_STEPS } from "./shared.ts"
/** The most a carrier takes at once. */
@@ -45,10 +47,11 @@ export const Dispatch = Game.System(
},
without: [Site, Rising, Burning]
}),
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),
errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
},
- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), time: Game.System.readResource(Time) },
services: { rules: Game.System.service(Rules) }
},
({ queries, resources, commands, services }) => {
@@ -68,13 +71,14 @@ export const Dispatch = Game.System(
}
type Id = ReturnType<typeof queries.sites.each>[number]["entity"]["id"]
- // What every building wants, nearest first once a sender is known.
+ // Outstanding demand and shelf fill, including goods already in transit.
interface Want {
readonly id: Id
readonly doors: ReadonlyArray<Point>
readonly good: GoodId
readonly want: () => number
readonly site: boolean
+ readonly fill?: () => number
}
const wants: Array<Want> = []
for (const { entity, data } of queries.sites.each()) {
@@ -94,16 +98,27 @@ export const Dispatch = Game.System(
const kind = maybe(data.building)?.kind
if (data.storage.present) {
rooms.push({ id: entity.id, doors: ds, room: space, keeps: kind !== undefined && (kinds[kind].keeps ?? 0) > 1 })
- continue
}
if (recipe && recipe.input !== null) {
const g = recipe.input
- wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
+ wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g), fill: () => (inventory.stock[g] + inbound(entity.id, g)) / inventory.cap })
}
// A workshop that wears out tools keeps a couple on hand.
- if (kind !== undefined && kinds[kind].wear) wants.push({ id: entity.id, doors: ds, good: "tools", site: false, want: () => TOOL_STOCK - inventory.stock.tools - inbound(entity.id, "tools") })
+ if (kind !== undefined && kinds[kind].wear) wants.push({ id: entity.id, doors: ds, good: "tools", site: false, want: () => TOOL_STOCK - inventory.stock.tools - inbound(entity.id, "tools"), fill: () => (inventory.stock.tools + inbound(entity.id, "tools")) / TOOL_STOCK })
const service = maybe(data.service)?.service
- if (service === "goods") for (const g of provisions) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
+ if (service === "goods") {
+ const roads = reach(grid, [ds[0]!]), range = maybe(data.service)!.range
+ const citizenDistrict = queries.homes.each().some(({ data: h }) => {
+ const tile = h.tile.get(), found = nearest(roads, doors(grid, tile))
+ return found !== null && found.distance < range && wantsCitizenGoods(h.house.get(), appealAt(resources.appeal.get().cells, tile.x, tile.y), rules)
+ })
+ for (const g of provisions) {
+ if (g === "cloth" && !citizenDistrict) continue
+ const cap = Math.min(inventory.cap, rules.transport.basket)
+ wants.push({ id: entity.id, doors: ds, good: g, site: false,
+ want: () => cap - inventory.stock[g] - inbound(entity.id, g), fill: () => (inventory.stock[g] + inbound(entity.id, g)) / cap })
+ }
+ }
if (service === "repair") for (const g of ["planks", "stone"] as const) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
}
@@ -137,14 +152,14 @@ export const Dispatch = Game.System(
: recipe && ready ? [recipe.output] : []
for (const good of offers) {
if ((out.get(entity.id) ?? 0) >= carriers) break
- let best: { readonly id: Id; readonly cell: Point; readonly distance: number; readonly count: number; readonly site: boolean } | null = null
+ let best: { readonly id: Id; readonly cell: Point; readonly distance: number; readonly count: number; readonly site: boolean; readonly fill?: number } | null = null
for (const w of wants) {
if (w.good !== good || w.id === entity.id) continue
const count = Math.min(LOAD, stock[good], w.want())
if (count <= 0) continue
const found = nearest(roads, w.doors)
- // Sites come first, then whoever is nearest.
- if (found && preferDelivery({ site: w.site, distance: found.distance }, best)) best = { id: w.id, ...found, count, site: w.site }
+ // Sites come first, then the lowest shelf fill; distance breaks ties.
+ if (found && preferDelivery({ site: w.site, distance: found.distance, fill: w.fill?.() ?? 0 }, best)) best = { id: w.id, ...found, count, site: w.site, fill: w.fill?.() ?? 0 }
}
// Food that spoils goes to a granary if there is one in reach, before the nearest storage; a
// storage that does not keep food sends it on to a granary that does.
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
index 140b6b0..dd7d4b9 100644
--- a/src/sim/walkers.ts
+++ b/src/sim/walkers.ts
@@ -1,6 +1,7 @@
import { serveGoods } from "../rules/households.ts"
import { transport } from "../rules/config.ts"
-import { onwardRoads } from "../rules/transport.ts"
+import { planPatrols } from "../rules/patrol.ts"
+import { appealAt } from "../appeal.ts"
/**
* Walking: every walker steps along its route; service buildings send a
* walker out now and then, who wanders the roads serving the homes beside
@@ -9,12 +10,11 @@ import { onwardRoads } from "../rules/transport.ts"
* keeping down the risk of fire, sickness, and disorder, a builder's with
* planks and stone to mend — and walks home when its range is walked.
*/
-import * as Random from "@typeonce/bevy-ts-math/Random"
import { amounts, categoryColor, each, provisions, total, type Amounts } from "../content.ts"
import { DIRS, doors, isRoad, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"
import { inside, type Point } from "../iso.ts"
-import { Building, Burning, Condition, Figure, Game, Rules, Grid, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Rng, Roam, Route, Service, Sick, Site, Staff, Status, Tile, Time, WalkerOf, maybe, type Status as StatusValue } from "../schema.ts"
+import { Building, Burning, Condition, Figure, Game, Rules, Grid, Appeal, Patrol, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Roam, Route, Service, Sick, Site, Staff, Status, Tile, Time, WalkerOf, maybe, type Status as StatusValue } from "../schema.ts"
import { CELL_STEPS } from "./shared.ts"
import { paced } from "./work.ts"
@@ -79,6 +79,8 @@ export const SendWalkers = Game.System(
without: [Site, Rising, Burning]
}),
inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] }),
+ patrols: Game.Query({ selection: { patrol: Game.Query.write(Patrol) } }),
+ targets: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.optional(House) }, with: [Condition], without: [Site, Rising, Burning] }),
walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })
},
resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
@@ -122,11 +124,20 @@ export const SendWalkers = Game.System(
const learning = staff.assigned > 0 && staff.assigned === staff.apprentices && !paced(APPRENTICE, tick)
const cooldown = learning ? service.cooldown : Math.max(0, service.cooldown - 1)
if (cooldown === 0 && (out.get(entity.id) ?? 0) < OUT && starts.length > 0 && staffed && goes) {
+ const targets = queries.targets.each().filter(({ data }) => service.service === "fire" || service.service === "repair" || data.house.present)
+ .map(({ entity, data }) => ({ id: entity.id as number, tile: data.tile.get() }))
+ const plan = planPatrols(grid, data.tile.get(), service.range, targets)
+ if (plan.tours.length === 0) continue
+ const patrol = queries.patrols.get(entity.id)
+ const cursor = patrol.ok ? patrol.value.data.patrol.get().next : 0
+ const tour = plan.tours[cursor % plan.tours.length]!
+ if (patrol.ok) patrol.value.data.patrol.set({ next: (cursor + 1) % plan.tours.length })
+ else commands.insert(entity.id, Game.Command.entry(Patrol, { next: 1 % plan.tours.length }))
const color = categoryColor[kinds[data.building.get().kind].category]
const draft = Game.Command.spawn(
[Figure, { role: "walker", color }],
- [Route, { cells: [{ x: starts[0]!.x, y: starts[0]!.y }], index: 0, step: 0 }],
- [Roam, { service: service.service, left: service.range, basket, back: false }]
+ [Route, { cells: [...tour], index: 0, step: 0 }],
+ [Roam, { service: service.service, left: tour.length, basket, back: false }]
)
commands.spawn(Game.Command.relate(draft, WalkerOf, entity.id))
const inv = queries.inventories.get(entity.id)
@@ -144,8 +155,8 @@ const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index:
/**
* A service walker wanders: at each cell it serves the homes (and, for a
- * fire watch or a builder, the buildings) beside it, then picks a road
- * onward at random (never straight back, unless it must). Once its range is
+ * fire watch or a builder, the buildings) beside it, then follows its planned tour. The service rotates its tours to cover every
+ * reachable target. Once its tour is
* walked, or its basket is empty, it heads home by the shortest road, and
* puts back what it still carries.
*
@@ -170,7 +181,7 @@ export const Wander = Game.System(
buildings: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Service] }),
inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })
},
- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), pantry: Game.System.writeResource(Pantry) },
+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), pantry: Game.System.writeResource(Pantry) },
services: { rules: Game.System.service(Rules) }
},
({ queries, resources, commands, services }) => {
@@ -178,9 +189,7 @@ export const Wander = Game.System(
const { home, condition: wear, conditionMax: CONDITION_MAX } = rules
const grid = resources.grid.get()
- const random = Random.make(resources.rng.get())
const walkers = queries.walkers.each()
- if (!walkers.some(({ data }) => arrived(data.route.get()))) return
const homes = new Map<number, ReturnType<typeof queries.homes.each>[number]>()
for (const row of queries.homes.each()) homes.set(row.entity.id, row)
const cared = new Map<number, ReturnType<typeof queries.cared.each>[number]>()
@@ -189,8 +198,9 @@ export const Wander = Game.System(
for (const { entity, data } of walkers) {
const route = data.route.get()
- if (!arrived(route)) continue
const roam = data.roam.get()
+ // left counts cells still to serve. Older saves can finish their current short segment.
+ if (roam.back ? !arrived(route) : roam.left > route.cells.length ? !arrived(route) : route.index < route.cells.length - roam.left) continue
const from = data.home.get()
if (roam.back) {
@@ -204,7 +214,7 @@ export const Wander = Game.System(
}
// Serve the homes (and buildings) beside this cell.
- const cell = route.cells[route.cells.length - 1]!
+ const cell = route.cells[route.index]!
const basket: Record<string, number> = { ...roam.basket }
const served = new Set<number>()
for (const d of DIRS) {
@@ -222,7 +232,7 @@ export const Wander = Game.System(
const h = { ...row.data.house.get() }
if (roam.service === "faith") h.faith = home.lasts.faith
else if (roam.service === "goods") {
- const served = serveGoods(h, amounts(basket), rules)
+ const served = serveGoods(h, amounts(basket), rules, appealAt(resources.appeal.get().cells, x, y))
Object.assign(h, served.house)
Object.assign(basket, served.basket)
eaten += served.eaten
@@ -250,15 +260,9 @@ export const Wander = Game.System(
const left = roam.left - 1
const carrying = amounts(basket)
const keepsGoing = roam.service === "goods" ? total(carrying) > 0 : roam.service === "repair" ? carrying.planks > 0 : true
- if (left > 0 && keepsGoing) {
- const previous = route.cells.length >= 2 ? route.cells[route.cells.length - 2]! : null
- const onward = onwardRoads(grid, cell, previous)
- const next = random.pick(onward) ?? previous
- if (next) {
- data.route.set({ cells: [cell, next], index: 0, step: 0 })
- data.roam.set({ ...roam, left, basket: carrying })
- continue
- }
+ if (left > 0 && keepsGoing && !arrived(route)) {
+ data.roam.set({ ...roam, left, basket: carrying })
+ continue
}
// Head home.
@@ -272,7 +276,6 @@ export const Wander = Game.System(
data.route.set({ cells: pathTo(way, door.cell), index: 0, step: 0 })
data.roam.set({ ...roam, left: 0, basket: carrying, back: true })
}
- resources.rng.set(random.state)
if (eaten > 0) resources.pantry.update((p) => ({ ...p, eaten: p.eaten + eaten }))
}
)
diff --git a/test/balance-model.test.ts b/test/balance-model.test.ts
index 8486f6d..26d5cd5 100644
--- a/test/balance-model.test.ts
+++ b/test/balance-model.test.ts
@@ -1,10 +1,6 @@
import assert from "node:assert/strict"
import { test } from "node:test"
-import { readFileSync, readdirSync, mkdtempSync, rmSync } from "node:fs"
-import { join } from "node:path"
-import { tmpdir } from "node:os"
-import { spawnSync } from "node:child_process"
-import { createHash } from "node:crypto"
+import { readFileSync, readdirSync } from "node:fs"
import { amounts, kinds } from "../src/content.ts"
import { resolveRules } from "../src/rules/config.ts"
import { analyze } from "../tools/balance/model/analyze.ts"
@@ -17,6 +13,11 @@ import { verifyBuilds } from "../tools/balance/verify/builds.ts"
import { provenance } from "../tools/balance/provenance.ts"
import { assessTransfers } from "../tools/balance/model/transport.ts"
import { fixture } from "../tools/balance/verify/fixture.ts"
+import { serveGoods, wantsCitizenGoods } from "../src/rules/households.ts"
+import { assignWorkers } from "../src/rules/production.ts"
+import { planPatrols } from "../src/rules/patrol.ts"
+import { scenarioGrid } from "../tools/balance/scenario.ts"
+import { GRID } from "../src/iso.ts"
test("candidate rules are immutable, isolated and also executed by the game", () => {
const base = resolveRules(), original = kinds.weaver.recipe!.seconds
@@ -63,7 +64,7 @@ test("cell parks share grouping, beauty and upkeep with the real game", () => {
assert.equal(actual.resources["Town/Treasury"].coins - before, expected.economy.roundedNetPerMinute)
for (const h of expected.household) {
const tile = scenario.homes.find((home) => home.id === h.id)!.tile
- assert.equal(actual.resources["Town/Appeal"].cells[tile.y * 64 + tile.x], h.desirability)
+ assert.equal(actual.resources["Town/Appeal"].cells[tile.y * GRID + tile.x], h.desirability)
}
assert(expected.economy.parkUpkeepPerMinute > 0)
assert.notEqual(expected.household[0]!.desirability, analyze({ rules: resolveRules(), scenario }, { services: false }).household[0]!.desirability)
@@ -76,10 +77,11 @@ test("desirability rejects an industrial citizen plan even with sufficient goods
assert(industrial.findings.some((f) => f.code === "appeal-blocks-citizens"))
})
-test("isolated workplaces and citizen-only raw industry cannot borrow global workers", () => {
+test("citizens can do rough work but isolated workplaces cannot borrow global workers", () => {
const rules = resolveRules(), s = district("unreachable", [2, 2], ["fishery"])
const a = analyze({ rules, scenario: s }, { services: false })
- assert.equal(a.recipes[0]!.staff.assigned, 0)
+ assert.equal(a.recipes[0]!.staff.assigned, 2)
+ assert.equal(a.recipes[0]!.staff.apprentices, 0)
const distant = { ...s, homes: s.homes.map((h) => ({ ...h, tier: 1 as const, residents: 4, tile: { ...h.tile, x: h.tile.x + 30 } })) }
assert.equal(analyze({ rules, scenario: distant }, { services: false }).recipes[0]!.staff.assigned, 0)
})
@@ -118,8 +120,8 @@ test("steady-state search counts working tools separately and leaves shipped par
assert.equal(provenance(rules, []).parametersChanged, false)
})
-test("controlled production, ledger and stochastic service comparisons pass", () => {
- const comparisons = verify(resolveRules(), 12)
+test("controlled production, ledger and planned service comparisons pass", () => {
+ const comparisons = verify(resolveRules(), 3)
for (const c of comparisons) assert(c.pass, JSON.stringify(c))
})
@@ -128,18 +130,52 @@ test("the mathematical plan reaches citizens through ordinary game construction"
const r = verifyBuilds({ rules, scenario }, builds)
assert.deepEqual(r.messages, [])
assert.equal(r.actual.at(-1)!.citizens, 32)
- assert.equal(r.firstCitizenSecond, 336)
+ assert(r.firstCitizenSecond !== null && r.firstCitizenSecond <= 300)
assert.equal(r.prediction.rows.at(-1)!.citizens, 32)
assert(r.prediction.assumptions.length > 0)
assert.equal(r.errors.length, r.actual.length)
})
-test("shared-rule extraction preserves the original PR's complete minute-30 world", { timeout: 180000 }, () => {
- const out = mkdtempSync(join(tmpdir(), "inkline-rule-parity-"))
- try {
- const child = spawnSync(process.execPath, ["scripts/balance.ts", "--seeds", "1", "--term", "60", "--snapshot", "30", "--out", out], { encoding: "utf8", timeout: 160000 })
- assert.equal(child.status, 0, child.stderr)
- const world = JSON.parse(readFileSync(join(out, "medium-fair-1000-30min.json"), "utf8")).world
- assert.equal(createHash("sha256").update(JSON.stringify(world)).digest("hex"), "3eff85260d3a97c25ad628dcf244e8f8b4abc6cd02407eed4446807e03d97557")
- } finally { rmSync(out, { recursive: true, force: true }) }
+
+test("promotion-aware goods preserve cloth and feed an eligible settler bread before food expires", () => {
+ const rules = resolveRules(), house = { tier: 1 as const, food: rules.home.lasts.food, bread: 0, cloth: 0, faith: 0 }
+ const eligible = serveGoods(house, amounts({ bread: 2, cloth: 2, fish: 2 }), rules, rules.home.tiers[2].appeal)
+ assert(eligible.house.bread > 0 && eligible.house.cloth > 0)
+ const worker = serveGoods({ ...house, food: 0 }, amounts({ bread: 2, cloth: 2, fish: 2 }), rules, 0)
+ assert.equal(worker.basket.fish, 1)
+ assert.equal(worker.basket.bread, 2)
+ assert.equal(worker.basket.cloth, 2)
+ assert.equal(wantsCitizenGoods(house, 0, rules), false)
+ const fallback = serveGoods({ ...house, food: 0 }, amounts({ bread: 1 }), rules, 0)
+ assert(fallback.house.food > 0)
+})
+
+test("surplus citizens fill rough jobs after skilled jobs without an apprentice penalty", () => {
+ const within = [{ home: 1, distance: 1 }]
+ const staff = assignWorkers([{ id: 1, crew: "citizens", residents: 8 }], [
+ { id: 1, crew: "settlers", needed: 7, within },
+ { id: 2, crew: "citizens", needed: 3, within }
+ ])
+ assert.equal(staff.get(2)!.assigned, 3)
+ assert.equal(staff.get(1)!.assigned, 5)
+ assert.equal(staff.get(1)!.apprentices, 0)
+})
+
+test("rotating patrols cover every reachable branch and survive save/load with their cursor", () => {
+ const rules = resolveRules(), scenario = district("patrol-branches", Array(10).fill(1), ["chapel"], true, rules)
+ const source = scenario.buildings.find(b => b.kind === "chapel")!, grid = scenarioGrid(scenario, rules).value()
+ const plan = planPatrols(grid, source.tile, rules.kinds.chapel.service!.range, scenario.homes)
+ assert.deepEqual(plan.unreachable, [])
+ assert(plan.tours.every(tour => tour.length <= rules.kinds.chapel.service!.range))
+ const town = fixture(scenario, rules)
+ town.run(0.5)
+ const saved = town.snapshot()
+ assert(saved.entities.some(e => e.components["Town/Patrol"]))
+ town.run(30)
+ const expected = town.snapshot()
+ const restored = fixture(scenario, rules)
+ restored.restore(saved)
+ assert.equal(JSON.stringify(restored.snapshot()), JSON.stringify(saved))
+ restored.run(30)
+ assert.deepEqual(restored.snapshot(), expected)
})
diff --git a/test/balance-victory.test.ts b/test/balance-victory.test.ts
new file mode 100644
index 0000000..3e93587
--- /dev/null
+++ b/test/balance-victory.test.ts
@@ -0,0 +1,29 @@
+import assert from "node:assert/strict"
+import { test } from "node:test"
+import { mkdtempSync, readFileSync, rmSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { spawnSync } from "node:child_process"
+import { resolveRules } from "../src/rules/config.ts"
+import { goalsOf } from "../src/rules/goals.ts"
+import { fingerprint } from "../tools/balance/provenance.ts"
+
+for (const from of [0, 2]) test(`generated charter ${1000 + from * 7919} reaches and holds a full win through ordinary edits`, { timeout: 180000 }, () => {
+ const directory = mkdtempSync(join(tmpdir(), "inkline-victory-")), file = join(directory, "result.json")
+ try {
+ const run = spawnSync(process.execPath, ["scripts/balance.ts", "--seeds", "1", "--from", String(from), "--term", "60", "--json", file],
+ { encoding: "utf8", timeout: 150000 })
+ assert.equal(run.status, 0, run.stderr)
+ const report = JSON.parse(readFileSync(file, "utf8")), result = report.results[0], final = result.final, rules = resolveRules()
+ assert.equal(report.rulesSha256, fingerprint(rules))
+ assert.equal(final.fate.state, "won", run.stdout)
+ assert(result.longestGoalHoldSeconds >= rules.fate.hold * 60)
+ assert(final.fate.at - final.fate.goalSince >= rules.fate.hold * 60 / rules.stepSeconds)
+ assert(goalsOf(final.charter, { settlers: final.census.settlers, citizens: final.census.citizens,
+ coins: final.treasury.coins, net: final.ledger.taxes + final.ledger.trade - final.ledger.upkeep - final.ledger.admin,
+ approval: final.mood.approval }, rules).every(goal => goal.met))
+ console.log(JSON.stringify({ seed: result.seed, state: final.fate.state, minute: result.end.minute,
+ holdSeconds: result.longestGoalHoldSeconds, residents: final.census.settlers + final.census.citizens,
+ citizens: final.census.citizens, coins: final.treasury.coins, approval: final.mood.approval }))
+ } finally { rmSync(directory, { recursive: true, force: true }) }
+})
diff --git a/tools/balance/catalog.ts b/tools/balance/catalog.ts
index 78ab9ae..f1e2f1e 100644
--- a/tools/balance/catalog.ts
+++ b/tools/balance/catalog.ts
@@ -28,6 +28,7 @@ export const buildScenario = (rules: Rules) => {
buildings: [{ ...hall, stock: initial }], trade: { buys: ["tools"], sells: [], reserve: 10 } }
const order: ReadonlyArray<readonly [KindId, number]> = [["sawmill", 0], ["lumberjack", 0], ["fishery", 0], ["quarry", 30], ["mill", 60], ["bakery", 90], ["farm", 120], ["sheep", 150], ["weaver", 180], ["market", 210], ["chapel", 240]]
const builds: BuildAction[] = order.map(([kind, at]) => ({ kind, at, tile: template.buildings.find((b) => b.kind === kind)!.tile }))
+ builds.push({ kind: "firewatch", at: 30, tile: { x: 6, y: 29, size: 2 } })
for (const p of citizenPark()) builds.push({ kind: "ground", ground: p.ground, at: 0, tile: { x: p.x, y: p.y, size: 1 } })
// Ground commands must have been applied before a furnishing can address their entities.
for (const p of citizenPark()) if (p.prop !== "none") builds.push({ kind: "prop", prop: p.prop, at: 1, tile: { x: p.x, y: p.y, size: 1 } })
diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.ts
index 893c942..b5e5c53 100644
--- a/tools/balance/model/analyze.ts
+++ b/tools/balance/model/analyze.ts
@@ -2,7 +2,7 @@ import { amounts, goodIds, type GoodId, type WinterId } from "../../../src/conte
import { appealAt, appealGrid, buildingSource, landSource, parkSources, parkUpkeep } from "../../../src/appeal.ts"
import { doors, nearest, reach } from "../../../src/grid.ts"
import { assignWorkers, type Assignment } from "../../../src/rules/production.ts"
-import { baseCollection, mealRate, refreshLevel, taxOf, tierFor } from "../../../src/rules/households.ts"
+import { baseCollection, wantsCitizenGoods, mealRate, refreshLevel, taxOf, tierFor } from "../../../src/rules/households.ts"
import { riskIncrements, near } from "../../../src/rules/risks.ts"
import { seasonAt } from "../../../src/rules/seasons.ts"
import { spoilExpectation } from "../../../src/rules/decay.ts"
@@ -82,15 +82,17 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
const spoil = { ...amounts({}) }
for (const b of s.buildings.filter((b) => !b.site)) for (const g of goodIds) spoil[g] += spoilExpectation(b.stock[g], g, rules.kinds[b.kind].keeps ?? 1, rules) * 60 / (rules.spoilTicks * rules.stepSeconds)
const foodDecay = mealRate(severity !== null)
+ const clothHomes = s.homes.filter(h => wantsCitizenGoods(h, appealAt(appeal, h.tile.x, h.tile.y), rules)).length
const needBounds = {
+ clothRecipients: clothHomes,
food: { min: s.homes.length * foodDecay * 60 / (rules.home.lasts.food * rules.stepSeconds), frequent: s.homes.length * foodDecay * 60 / ((rules.home.lasts.food - refreshLevel("food", rules)) * rules.stepSeconds) },
- cloth: { min: s.homes.length * 60 / (rules.home.lasts.cloth * rules.stepSeconds), frequent: s.homes.length * 60 / ((rules.home.lasts.cloth - refreshLevel("cloth", rules)) * rules.stepSeconds) },
+ cloth: { min: clothHomes * 60 / (rules.home.lasts.cloth * rules.stepSeconds), frequent: clothHomes * 60 / ((rules.home.lasts.cloth - refreshLevel("cloth", rules)) * rules.stepSeconds) },
citizenCloth: { min: s.homes.filter((h) => h.tier >= 2).length * 60 / (rules.home.lasts.cloth * rules.stepSeconds), frequent: s.homes.filter((h) => h.tier >= 2).length * 60 / ((rules.home.lasts.cloth - refreshLevel("cloth", rules)) * rules.stepSeconds) }
}
const net = Object.fromEntries(goodIds.map((g) => [g, supply[g] - inputs[g] - spoil[g]])) as Record<GoodId, number>
const foodCeiling = supply.fish + supply.smoked + supply.bread - inputs.fish - inputs.smoked - inputs.bread
if (foodCeiling < needBounds.food.min) findings.push({ code: "food-impossible", confidence: "upper-bound", detail: `Even pooled food capacity ${foodCeiling.toFixed(2)}/min before spoilage is below the no-waste minimum ${needBounds.food.min.toFixed(2)}/min; existing reserves may bridge a finite interval` })
- if (net.cloth < needBounds.cloth.min) findings.push({ code: "cloth-spread", confidence: "upper-bound", detail: `Cloth capacity ${net.cloth.toFixed(2)}/min cannot keep ${s.homes.length} homes supplied; settlers also accept cloth` })
+ if (net.cloth < needBounds.cloth.min) findings.push({ code: "cloth-capacity", confidence: "upper-bound", detail: `Cloth capacity ${net.cloth.toFixed(2)}/min cannot keep ${clothHomes} eligible homes supplied` })
const hall = s.buildings.find((b) => b.kind === "townhall"), hallRoads = hall ? reach(g, doors(g, hall.tile)) : null
const taxes = s.homes.reduce((sum, h) => sum + (hallRoads && nearest(hallRoads, doors(g, h.tile)) ? taxOf(h, s.policy, rules) : 0), 0)
const upkeep = s.buildings.filter((b) => !b.site).reduce((sum, b) => sum + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)
@@ -134,7 +136,7 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
})
if (storage.length === 0) findings.push({ code: "no-storage", confidence: "exact", detail: "No completed storage accepts town reserves" })
return { name: s.name, severity, minutes, elapsedMs: performance.now() - started,
- assumptions: ["Resource flow is a steady-state pooled relaxation; it is an upper bound before household demand and transport cuts.", "Transport ceilings assume full loads and available destinations; nearest-demand dispatch and construction can lower realized throughput.", "Service path probabilities are exact for the stated uniform-walk graph; renewal timing and unlimited baskets are estimates.", "Risk deadlines freeze hunger, approval, neighbourhood and condition; contagion and fire spread are excluded from these local deadlines."],
+ assumptions: ["Resource flow is a steady-state pooled relaxation; it is an upper bound before household demand and transport cuts.", "Transport ceilings assume full loads and available destinations; shelf balancing and construction can lower realized throughput.", "Service coverage uses the actual deterministic tours; launch timing and unlimited baskets are estimates.", "Risk deadlines freeze hunger, approval, neighbourhood and condition; contagion and fire spread are excluded from these local deadlines."],
staff: Object.fromEntries(staff), recipes: recipes.map((r) => ({ ...r, flowCeiling: rates.get(r.id)! })),
supply, workshopDemand: inputs, spoilage: spoil, availableAfterWorkshops: net, needBounds,
economy: { taxesPerMinute: taxes, upkeepPerMinute: upkeep + parkCost, parkUpkeepPerMinute: parkCost, administrationPerMinute: collection.admin, roundedNetPerMinute: cashPerMinute,
diff --git a/tools/balance/model/project.ts b/tools/balance/model/project.ts
index cc04925..8309f85 100644
--- a/tools/balance/model/project.ts
+++ b/tools/balance/model/project.ts
@@ -136,7 +136,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
if (Number.isFinite(goods) && Math.floor(second / goods) !== Math.floor((second + step) / goods)) {
const basket = Object.fromEntries(goodIds.map((g) => [g, Math.max(0, Math.floor(stock[g]))])) as Record<keyof Amounts, number>
if (options.feeding === "fish") basket.bread = 0
- const served = serveGoods(next, basket, rules)
+ const served = serveGoods(next, basket, rules, analysis.household.find(a => a.id === h.id)?.desirability ?? 0)
for (const g of goodIds) stock[g] -= basket[g] - served.basket[g]
next = { ...served.house }
}
@@ -187,5 +187,5 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
}
}
return { name: scenario.name, firstCitizenSecond: firstCitizen, rows, events,
- assumptions: ["One-second pooled rate model; integer recipe phases and local storage are approximated.", "Contacts are periodic mean visits unless explicitly supplied; faith has no goods cost. This understates long revisit gaps.", "Construction spends materials at placement and ignores carrier latency; completion is optimistic.", "Granary protection and tool availability are pooled; source accessibility is frozen between analysis updates.", "Market prices and collection rules are shared; shelf allocation is pooled and optimistic. No disaster losses, repair recovery or victory classification are predicted. Explicit imports/exports and crown events are scenario conditions."] }
+ assumptions: ["One-second pooled rate model; integer recipe phases and local storage are approximated.", "Contacts use periodic mean visits from planned tours unless explicitly supplied; faith has no goods cost. Basket depletion and actual launch gaps can lower coverage.", "Construction spends materials at placement and ignores carrier latency; completion is optimistic.", "Granary protection and tool availability are pooled; source accessibility is frozen between analysis updates.", "Market prices and collection rules are shared; shelf allocation is pooled and optimistic. No disaster losses, repair recovery or victory classification are predicted. Explicit imports/exports and crown events are scenario conditions."] }
}
diff --git a/tools/balance/model/services.ts b/tools/balance/model/services.ts
index 53c47dc..b8cc508 100644
--- a/tools/balance/model/services.ts
+++ b/tools/balance/model/services.ts
@@ -1,6 +1,5 @@
-import { doors, key, reach, type TileLike } from "../../../src/grid.ts"
-import { GRID } from "../../../src/iso.ts"
-import { onwardRoads } from "../../../src/rules/transport.ts"
+import { doors, key, nearest, reach, type TileLike } from "../../../src/grid.ts"
+import { planPatrols, serviceDoors } from "../../../src/rules/patrol.ts"
import type { Rules } from "../../../src/rules/config.ts"
import type { Assignment } from "../../../src/rules/production.ts"
import { scenarioGrid } from "../scenario.ts"
@@ -9,85 +8,56 @@ import type { ModelBuilding, Scenario } from "../types.ts"
export interface Contact {
readonly target: number; readonly expectedVisitsPerTrip: number; readonly hitProbability: number
readonly firstHitSeconds: number | null; readonly visitsPerMinute: number
+ readonly maximumVisitGapSeconds: number; readonly visitGapsSeconds: ReadonlyArray<number>
}
export interface ServiceProfile {
readonly source: number; readonly service: string; readonly tripsPerMinute: number
readonly meanTripSeconds: number; readonly contacts: ReadonlyArray<Contact>
+ readonly tours: number; readonly cycleSeconds: number; readonly unreachable: ReadonlyArray<number>
readonly assumption: string
}
-interface State { readonly previous: number; readonly cell: number; readonly probability: number }
-/** Finite non-backtracking random-walk DP. No random samples or headless runtime are used. */
+/** The actual deterministic route planner; no runtime or random sampler is used. */
export const serviceProfile = (scenario: Scenario, building: ModelBuilding, staff: Assignment, rules: Rules): ServiceProfile | null => {
const kind = rules.kinds[building.kind], service = kind.service
if (!service || building.paused || building.site || (kind.workers > 0 && staff.assigned === 0)) return null
const grid = scenarioGrid(scenario, rules).value(), starts = doors(grid, building.tile)
if (starts.length === 0) return null
- const homeRoads = reach(grid, starts), secondsPerCell = rules.transport.cellSteps * rules.stepSeconds / rules.transport.walk
- const targets: ReadonlyArray<{ readonly id: number; readonly tile: TileLike }> = service.service === "fire" || service.service === "repair" ? [...scenario.homes, ...scenario.buildings.filter((b) => !b.site && b.kind !== "townhall")] : scenario.homes
- const beside = new Map<number, Set<number>>()
- for (const t of targets) for (const d of doors(grid, t.tile)) {
- const k = key(d.x, d.y), set = beside.get(k) ?? new Set<number>(); set.add(t.id); beside.set(k, set)
- }
- const next = (state: State): ReadonlyArray<number> => {
- const cell = { x: state.cell % GRID, y: Math.floor(state.cell / GRID) }
- const previous = state.previous < 0 ? null : { x: state.previous % GRID, y: Math.floor(state.previous / GRID) }
- const candidates = onwardRoads(grid, cell, previous).map((p) => key(p.x, p.y))
- return candidates.length > 0 ? candidates : state.previous < 0 ? [] : [state.previous]
- }
- const advance = (states: ReadonlyArray<State>, avoid = -1): State[] => {
- const result = new Map<string, State>()
- for (const s of states) {
- if (beside.get(s.cell)?.has(avoid)) continue
- const choices = next(s)
- for (const cell of choices) {
- const id = `${s.cell}:${cell}`, probability = s.probability / choices.length
- const old = result.get(id)
- result.set(id, { previous: s.cell, cell, probability: probability + (old?.probability ?? 0) })
- }
- }
- return [...result.values()]
- }
- const initial: State[] = [{ previous: -1, cell: key(starts[0]!.x, starts[0]!.y), probability: 1 }]
- const expected = new Map<number, number>()
- let states = initial, meanTripSeconds = 0
- for (let step = 0; step < service.range; step++) {
- for (const state of states) {
- for (const id of beside.get(state.cell) ?? []) expected.set(id, (expected.get(id) ?? 0) + state.probability)
- if (step === service.range - 1 || next(state).length === 0) {
- const distance = homeRoads.distance[state.cell]!
- meanTripSeconds += state.probability * (step + Math.max(0, distance)) * secondsPerCell
- }
- }
- states = advance(states)
- }
+ const targets: ReadonlyArray<{ readonly id: number; readonly tile: TileLike }> = service.service === "fire" || service.service === "repair"
+ ? [...scenario.homes, ...scenario.buildings.filter(b => !b.site && b.kind !== "townhall")] : scenario.homes
+ const plan = planPatrols(grid, building.tile, service.range, targets)
+ if (plan.tours.length === 0) return null
+ const secondsPerCell = rules.transport.cellSteps * rules.stepSeconds / rules.transport.walk
+ const homeRoads = reach(grid, starts)
+ const meanTripSeconds = plan.tours.reduce((n, tour) => n + (tour.length - 1 + (nearest(homeRoads, [tour.at(-1)!])?.distance ?? 0)) * secondsPerCell, 0) / plan.tours.length
const apprenticed = staff.assigned > 0 && staff.assigned === staff.apprentices
const launchSeconds = service.seconds / (apprenticed ? rules.apprentice : 1)
const tripsPerMinute = Math.min(60 / launchSeconds, meanTripSeconds > 0 ? rules.transport.active * 60 / meanTripSeconds : Infinity)
- const contacts = targets.filter((t) => expected.has(t.id)).map((t): Contact => {
- let unhit = initial, hitProbability = 0, firstHit = 0
- for (let step = 0; step < service.range; step++) {
- const now = unhit.filter((s) => beside.get(s.cell)?.has(t.id)).reduce((sum, s) => sum + s.probability, 0)
- hitProbability += now; firstHit += now * step * secondsPerCell
- unhit = advance(unhit, t.id)
- }
- return { target: t.id, expectedVisitsPerTrip: expected.get(t.id)!, hitProbability,
- firstHitSeconds: hitProbability > 0 ? firstHit / hitProbability : null,
- visitsPerMinute: expected.get(t.id)! * tripsPerMinute }
+ const cadence = 60 / tripsPerMinute, cycleSeconds = cadence * plan.tours.length
+ const contacts = targets.flatMap((target): Contact[] => {
+ const beside = new Set(serviceDoors(grid, target.tile).map(p => key(p.x, p.y)))
+ const visits = plan.tours.map(tour => tour.flatMap((p, i) => beside.has(key(p.x, p.y)) ? [i * secondsPerCell] : []))
+ const hits = visits.filter(v => v.length > 0)
+ if (hits.length === 0) return []
+ const times = visits.flatMap((v, tour) => v.map(t => (tour * cadence + t) % cycleSeconds)).sort((a, b) => a - b)
+ const gaps = times.map((t, i) => i + 1 < times.length ? times[i + 1]! - t : times[0]! + cycleSeconds - t)
+ const expectedVisitsPerTrip = times.length / plan.tours.length
+ return [{ target: target.id, expectedVisitsPerTrip, hitProbability: hits.length / plan.tours.length,
+ firstHitSeconds: hits.reduce((n, v) => n + v[0]!, 0) / hits.length, visitsPerMinute: expectedVisitsPerTrip * tripsPerMinute,
+ maximumVisitGapSeconds: Math.max(...gaps), visitGapsSeconds: gaps }]
})
return { source: building.id, service: service.service, tripsPerMinute, meanTripSeconds, contacts,
- assumption: "Exact finite-path probabilities for uniform choices on fixed roads; trip rate uses mean occupancy. Goods/repair profiles assume unlimited baskets. Revisit-gap estimates assume independent excursions." }
+ tours: plan.tours.length, cycleSeconds, unreachable: plan.unreachable,
+ assumption: "Exact planned coverage and tour visit fractions. Launch timing uses mean occupancy; goods and repair baskets may empty sooner. Revisit gaps assume evenly spaced launches; service phases are not independent in the runtime." }
}
-/** Excursion-level renewal approximation; avoids counting repeated visits on one trip as independent protection. */
+/** Fraction of a uniformly placed window missing a visit under the stated periodic timing estimate. */
export const missProbability = (profiles: ReadonlyArray<ServiceProfile>, target: number, seconds: number): number => {
- let log = 0
+ let miss = 1
for (const p of profiles) {
- const c = p.contacts.find((c) => c.target === target)
- if (!c || c.hitProbability === 0) continue
- const trips = p.tripsPerMinute * seconds / 60
- if (c.hitProbability >= 1 && trips >= 1) return 0
- log += trips * Math.log(Math.max(1e-12, 1 - c.hitProbability))
+ const c = p.contacts.find(c => c.target === target)
+ if (!c) continue
+ miss *= c.visitGapsSeconds.reduce((n, gap) => n + Math.max(0, gap - seconds), 0) / p.cycleSeconds
}
- return Math.exp(log)
+ return miss
}
diff --git a/tools/balance/provenance.ts b/tools/balance/provenance.ts
index b2d538a..0a1f0d2 100644
--- a/tools/balance/provenance.ts
+++ b/tools/balance/provenance.ts
@@ -1,3 +1,4 @@
+import { execFileSync } from "node:child_process"
import { createHash } from "node:crypto"
import { readFileSync, readdirSync } from "node:fs"
import { resolveRules, type Rules } from "../../src/rules/config.ts"
@@ -7,7 +8,8 @@ const stable = (value: unknown): unknown => Array.isArray(value) ? value.map(sta
export const fingerprint = (value: unknown) => createHash("sha256").update(JSON.stringify(stable(value))).digest("hex")
export const provenance = (rules: Rules, scenarios: ReadonlyArray<Scenario>) => {
const paths = ["src/content.ts", "src/grid.ts", "src/appeal.ts", "tools/balance/catalog.ts", "tools/balance/scenario.ts", "tools/balance/types.ts", ...readdirSync("src/rules").filter((f) => f.endsWith(".ts")).map((f) => `src/rules/${f}`), ...readdirSync("src/sim").filter((f) => f.endsWith(".ts")).map((f) => `src/sim/${f}`), ...readdirSync("tools/balance/model").filter((f) => f.endsWith(".ts")).map((f) => `tools/balance/model/${f}`)].sort()
- return { modelVersion: 1, referencePr: "https://github.com/SandroMaglione/inkline-town/pull/3", referenceSha: "9b7ce7336a18f917a10aa6e21ae32cb57af88643",
+ return { modelVersion: 2, referencePr: "https://github.com/SandroMaglione/inkline-town/pull/3", referenceSha: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(), baselineReferenceSha: "9b7ce7336a18f917a10aa6e21ae32cb57af88643",
+ uncommittedSource: execFileSync("git", ["status", "--porcelain", "--", "src", "scripts", "tools/balance"], { encoding: "utf8" }).trim().length > 0,
rulesSha256: fingerprint(rules), contentSha256: createHash("sha256").update(readFileSync("src/content.ts")).digest("hex"),
modelSourceSha256: fingerprint(paths.map((p) => [p, readFileSync(p, "utf8")])), scenarioSha256: scenarios.map((s) => ({ name: s.name, sha256: fingerprint(s) })),
parametersChanged: fingerprint(rules) !== fingerprint(resolveRules()) }
diff --git a/tools/balance/report.ts b/tools/balance/report.ts
index 63047e4..f485aef 100644
--- a/tools/balance/report.ts
+++ b/tools/balance/report.ts
@@ -43,14 +43,14 @@ export const makeReport = (rules: Rules, verification: ReadonlyArray<Verificatio
analyses, verification, construction: { ...construction, final: undefined },
configurations: { evaluated: configurations.length, affordableAtFoundation: configurations.filter((c) => c.affordableAtFoundation).length, cheapest: configurations.slice(0, 5),
scope: "Fixed-layout resource relaxation; affordability includes installed working tools but excludes initial homes, roads and services" },
- limits: ["Exact functions and finite-path probabilities are separated from steady-state ceilings and coarse forecasts.", "The construction fixture establishes first citizens on authored flat land, not victory on every generated seed.", "The forecast's revisit gaps, shelf allocation, field placement and equipment distribution are approximations. Calibration errors are reported, not hidden.", "Wild forest regeneration is bounded in steady-state analysis and excluded from the transient finite-tree forecast. Maintenance and disaster constraints are analyzed; stochastic disasters and repairs are verified in the real game, not reproduced as an exact joint distribution."] }
+ limits: ["Exact functions and planned tour coverage are separated from steady-state ceilings and coarse forecasts.", "The construction fixture establishes first citizens on authored flat land, not victory on every generated seed.", "The forecast's revisit gaps, shelf allocation, field placement and equipment distribution are approximations. Calibration errors are reported, not hidden.", "Wild forest regeneration is bounded in steady-state analysis and excluded from the transient finite-tree forecast. Maintenance and disaster constraints are analyzed; stochastic disasters and repairs are verified in the real game, not reproduced as an exact joint distribution."] }
}
export type Report = ReturnType<typeof makeReport>
const n = (v: number | null) => v === null ? "n/a" : Number(v.toFixed(2)).toString()
export const markdownReport = (r: Report) => {
const a = r.construction.actual.at(-1)!, p = r.construction.prediction.rows.at(-1)!
const saved = r.analyses.find((a) => a.name === "pr3-bot-minute-30")
- return `# Balance model results\n\nGenerated from PR #3 at ${r.provenance.referenceSha}. No shipped parameter changes. Rules SHA-256: ${r.provenance.rulesSha256}.\n\n## First citizens, with unchanged rules\n\nAn authored starting district pays for its roads and homes, then uses ordinary construction edits and the UI-supported tool reserve of 10. The real game first reaches citizens at ${r.construction.firstCitizenSecond ?? "never"} seconds; the coarse model estimates ${r.construction.prediction.firstCitizenSecond ?? "never"}. At ten minutes the game has ${a.citizens} citizens, ${a.residents} residents and ${a.coins} coins. The forecast has ${p.citizens} citizens, ${p.residents} residents and ${p.coins} coins. This is a progression fixture, not a generated-map victory claim.\n\n## Production capacity\n\nOutputs per minute with full crews, sufficient inputs, output room and maintained condition. Apprentice rows deliberately include the actual tick alignment. These are workshop ceilings, not delivered food.\n\n| Building | Own crew + tool | Apprentices + tool | Apprentices, no tool |\n|---|---:|---:|---:|\n${r.capacity.map((c) => `| ${c.kind} | ${n(c.staffed)} | ${n(c.apprentices)} | ${n(c.apprenticesWithoutTools)} |`).join("\n")}\n\n## Useful constraints\n\n- The first citizen chain alone costs ${r.firstCitizenChain.coins} coins and ${r.firstCitizenChain.materials.tools} construction tools. Its ${r.firstCitizenChain.workingTools} wearing workshops also need working tools. Total ${r.firstCitizenChain.totalToolsIncludingConstruction}, versus ${r.firstCitizenChain.fairStartingTools} at a fair start. Raw industry adds more tool demand.\n- The verified park uses three adjacent flower cells, one fountain and one lamp: ${r.amenity.coins} coins, ${n(r.amenity.upkeepPerMinute)}/min upkeep, +${r.amenity.value} desirability at the nearest cells, reach ${r.amenity.reach}. Its effects combine with industry and chapel effects; nearby raw industry remains a liability. Place furnishings after the ground exists.\n- Settlers accept cloth, and bread is preferred for food. Supplying a broad settler district can consume goods intended for citizen upgrades.\n- Promotion changes the workforce: citizens cannot fill settlers' jobs. Keep raw-production households within commuting distance.\n- Build mills/bakeries before farms can plant on their future plots. A previous ordering failed with the real game's “No room there”; the revised verified schedule has ${r.construction.messages.length} rejected-action messages.\n- An unmaintained building loses half speed after about 33 minutes. After it crosses the repair threshold there are ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds} seconds before half speed.\n${saved ? `- The original sensible bot's minute-30 town has ${saved.household.length} completed homes. Its pooled cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min against ${n(saved.needBounds.cloth.min)}..${n(saved.needBounds.cloth.frequent)}/min to supply every home. ${saved.household.filter((h) => h.potentialTier >= 2).length} homes satisfy the desirability gate even if all citizen needs were supplied. Even granting burghers wherever desirability permits, citizen housing is capped at ${saved.citizenGoal.housingCeilingAtCurrentDesirability}, below the ${saved.citizenGoal.minimumAtPopulationGoal} citizens required at the population goal.\n` : ""}\n## Winters\n\nFully staffed, maintained fisheries; homes consume per household. Each figure excludes spoilage and delivery loss.\n\n| Winter | Duration in a 60-minute term | Fish/min/fishery | Homes supported, late refresh | Homes supported, frequent refresh |\n|---|---:|---:|---:|---:|\n${r.winter.map((w) => `| ${w.severity} | ${n(w.durationMinutesIn60MinuteTerm)} min | ${n(w.fishPerMinute)} | ${n(w.noWasteHomesPerFishery)} | ${n(w.frequentRefreshHomesPerFishery)} |`).join("\n")}\n\n## Verification\n\n${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons pass. Production tolerances allow one incomplete job at the window boundary; ledger rounding is exact. Service checks compare finite-path mathematics to actual game excursions.\n\n| Check | Expected | Actual | Allowed error | Pass |\n|---|---:|---:|---:|---|\n${r.verification.map((v) => `| ${v.name} | ${n(v.expected)} | ${n(v.actual)} | ${n(v.tolerance)} | ${v.pass} |`).join("\n")}\n\n## Practical suggestions\n\nConcentrate bread, cloth and faith in a small desirable district before scaling the whole town. Budget working tools separately from construction tools. Keep a settler workforce near farms and resource gatherers. Reserve workshop plots before agriculture expands. Size winter food capacity from household demand and storage losses, not resident count or summer fishing. Place repair services before condition crosses the half-speed threshold.\n\nUse static constraints and parameter/configuration search to reject weak designs quickly; verify promising designs and thresholds in the real game. Use the coarse forecast as an estimate with its measured timing and cash errors, not as a precise victory predictor.\n\n## Scope and limitations\n\n${r.limits.map((l) => `- ${l}`).join("\n")}\n`
+ return `# Balance model results\n\nGenerated from PR #3 at ${r.provenance.referenceSha}. Current shipped parameters, with no report-time overrides. Rules SHA-256: ${r.provenance.rulesSha256}.\n\n## First citizens, with the current rules\n\nAn authored starting district pays for its roads and homes, then uses ordinary construction edits and the UI-supported tool reserve of 10. The real game first reaches citizens at ${r.construction.firstCitizenSecond ?? "never"} seconds; the coarse model estimates ${r.construction.prediction.firstCitizenSecond ?? "never"}. At ten minutes the game has ${a.citizens} citizens, ${a.residents} residents and ${a.coins} coins. The forecast has ${p.citizens} citizens, ${p.residents} residents and ${p.coins} coins. This is a progression fixture, not a generated-map victory claim.\n\n## Production capacity\n\nOutputs per minute with full crews, sufficient inputs, output room and maintained condition. Apprentice rows deliberately include the actual tick alignment. These are workshop ceilings, not delivered food.\n\n| Building | Own crew + tool | Apprentices + tool | Apprentices, no tool |\n|---|---:|---:|---:|\n${r.capacity.map((c) => `| ${c.kind} | ${n(c.staffed)} | ${n(c.apprentices)} | ${n(c.apprenticesWithoutTools)} |`).join("\n")}\n\n## Useful constraints\n\n- The first citizen chain alone costs ${r.firstCitizenChain.coins} coins and ${r.firstCitizenChain.materials.tools} construction tools. Its ${r.firstCitizenChain.workingTools} wearing workshops also need working tools. Total ${r.firstCitizenChain.totalToolsIncludingConstruction}, versus ${r.firstCitizenChain.fairStartingTools} at a fair start. Raw industry adds more tool demand.\n- The verified park uses three adjacent flower cells, one fountain and one lamp: ${r.amenity.coins} coins, ${n(r.amenity.upkeepPerMinute)}/min upkeep, +${r.amenity.value} desirability at the nearest cells, reach ${r.amenity.reach}. Its effects combine with industry and chapel effects; nearby raw industry remains a liability. Place furnishings after the ground exists.\n- Cloth reaches existing citizens and settlers on eligible streets. Eligible settlers request bread independently of their food meter; other settlers prefer fish and use bread as a fallback.\n- Skilled jobs receive native crews first. Surplus citizens can fill rough jobs at full speed, and settlers can fill skilled jobs at apprentice pace. The road commute still constrains both.\n- Build mills/bakeries before farms can plant on their future plots. A previous ordering failed with the real game's “No room there”; the revised verified schedule has ${r.construction.messages.length} rejected-action messages.\n- An unmaintained building loses half speed after about 33 minutes. After it crosses the repair threshold there are ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds} seconds before half speed.\n${saved ? `- The captured sensible bot's minute-30 town has ${saved.household.length} completed homes. Its pooled cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min against ${n(saved.needBounds.cloth.min)}..${n(saved.needBounds.cloth.frequent)}/min to supply eligible homes. ${saved.household.filter((h) => h.potentialTier >= 2).length} homes satisfy the desirability gate even if all citizen needs were supplied. Even granting burghers wherever desirability permits, citizen housing is capped at ${saved.citizenGoal.housingCeilingAtCurrentDesirability}, versus the ${saved.citizenGoal.minimumAtPopulationGoal} citizens required at the population goal.\n` : ""}\n## Winters\n\nFully staffed, maintained fisheries; homes consume per household. Each figure excludes spoilage and delivery loss.\n\n| Winter | Duration in a 60-minute term | Fish/min/fishery | Homes supported, late refresh | Homes supported, frequent refresh |\n|---|---:|---:|---:|---:|\n${r.winter.map((w) => `| ${w.severity} | ${n(w.durationMinutesIn60MinuteTerm)} min | ${n(w.fishPerMinute)} | ${n(w.noWasteHomesPerFishery)} | ${n(w.frequentRefreshHomesPerFishery)} |`).join("\n")}\n\n## Verification\n\n${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons pass. Production tolerances allow one incomplete job at the window boundary; ledger rounding is exact. Service checks compare whole dispatch rotations to the shared planner, with exact visit fractions.\n\n| Check | Expected | Actual | Allowed error | Pass |\n|---|---:|---:|---:|---|\n${r.verification.map((v) => `| ${v.name} | ${n(v.expected)} | ${n(v.actual)} | ${n(v.tolerance)} | ${v.pass} |`).join("\n")}\n\n## Practical suggestions\n\nConcentrate bread, cloth and faith in a small desirable district before scaling the whole town. Budget working tools separately from construction tools. Keep available workers within commuting distance of farms and resource gatherers. Reserve workshop plots before agriculture expands. Size winter food capacity from household demand and storage losses, not resident count or summer fishing. Place repair services before condition crosses the half-speed threshold.\n\nUse static constraints and parameter/configuration search to reject weak designs quickly; verify promising designs and thresholds in the real game. Use the coarse forecast as an estimate with its measured timing and cash errors, not as a precise victory predictor.\n\n## Scope and limitations\n\n${r.limits.map((l) => `- ${l}`).join("\n")}\n`
}
const escape = (s: unknown) => String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;")
@@ -58,10 +58,10 @@ export const htmlReport = (r: Report) => {
const end = r.construction.actual.at(-1)!, predicted = r.construction.prediction.rows.at(-1)!
const saved = r.analyses.find((a) => a.name === "pr3-bot-minute-30")
const table = (headers: string[], rows: unknown[][]) => `<div class="scroll"><table><thead><tr>${headers.map((h) => `<th>${escape(h)}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((c) => `<td>${escape(c)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`
- return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Unchanged-rule balance results</title><style>:root{color-scheme:light dark}body{margin:0;font:14px system-ui;color:var(--foreground,CanvasText)}h2{font-size:17px;font-weight:500;margin:24px 0 12px}h3{font-size:15px;font-weight:500}p{line-height:1.5}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}th,td{text-align:left;padding:10px 6px;border-bottom:1px solid var(--border,GrayText);font-size:12px}th{font-weight:500}.scroll{overflow-x:auto}.muted{color:var(--muted-foreground,GrayText)}details{margin:16px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}ul{padding-left:20px;line-height:1.55}.lead{font-weight:500}</style></head><body><h2>First citizens with unchanged game parameters</h2><p class="lead">${end.citizens} citizens verified in the real game. First citizen at ${r.construction.firstCitizenSecond ?? "never"} seconds on the authored construction fixture.</p><p class="muted">PR #3 · shared game rules · ${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons passed. This establishes a working progression example, not a full-term victory.</p>
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Current-rule balance results</title><style>:root{color-scheme:light dark}body{margin:0;font:14px system-ui;color:var(--foreground,CanvasText)}h2{font-size:17px;font-weight:500;margin:24px 0 12px}h3{font-size:15px;font-weight:500}p{line-height:1.5}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}th,td{text-align:left;padding:10px 6px;border-bottom:1px solid var(--border,GrayText);font-size:12px}th{font-weight:500}.scroll{overflow-x:auto}.muted{color:var(--muted-foreground,GrayText)}details{margin:16px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}ul{padding-left:20px;line-height:1.55}.lead{font-weight:500}</style></head><body><h2>First citizens with the current game parameters</h2><p class="lead">${end.citizens} citizens verified in the real game. First citizen at ${r.construction.firstCitizenSecond ?? "never"} seconds on the authored construction fixture.</p><p class="muted">PR #3 · shared game rules · ${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons passed. This establishes a working progression example, not a full-term victory.</p>
${table(["At 10 minutes", "Model estimate", "Real game"], [["Citizens", predicted.citizens, end.citizens], ["Residents", predicted.residents, end.residents], ["Coins", predicted.coins, end.coins], ["First citizen, seconds", r.construction.prediction.firstCitizenSecond ?? "none", r.construction.firstCitizenSecond ?? "none"]])}
-<h2>Economic constraints worth acting on</h2><ul><li>First citizen chain: ${r.firstCitizenChain.coins} coins; ${r.firstCitizenChain.materials.tools} construction tools + ${r.firstCitizenChain.workingTools} working tools. Fair land starts with ${r.firstCitizenChain.fairStartingTools} tools.</li><li>The three-cell park with a fountain and lamp costs ${r.amenity.coins} coins and ${n(r.amenity.upkeepPerMinute)}/min. It contributes +${r.amenity.value} nearby desirability; industry can cancel that benefit.</li><li>Settlers also consume cloth and take bread preferentially for food. Start with a small, desirable district.</li><li>Promotions remove workers from settler jobs. Keep farms and gatherers staffed.</li><li>Place workshops before farms can plant over their future plots.</li><li>Repair services have a ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds}-second window between the repair threshold and half speed.</li></ul>
-${saved ? `<h2>Original bot town · minute 30</h2><p>Only ${saved.household.filter((h) => h.potentialTier >= 2).length} of ${saved.household.length} homes pass the current desirability gate. Even granting unlimited needs and services, those homes hold at most ${saved.citizenGoal.housingCeilingAtCurrentDesirability} citizens/burghers, versus ${saved.citizenGoal.minimumAtPopulationGoal} required at the population goal.</p><p>Cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min; supplying every home needs at least ${n(saved.needBounds.cloth.min)}/min. The current layout and broad distribution are bottlenecks before any rate tuning.</p>` : ""}
+<h2>Economic constraints worth acting on</h2><ul><li>First citizen chain: ${r.firstCitizenChain.coins} coins; ${r.firstCitizenChain.materials.tools} construction tools + ${r.firstCitizenChain.workingTools} working tools. Fair land starts with ${r.firstCitizenChain.fairStartingTools} tools.</li><li>The three-cell park with a fountain and lamp costs ${r.amenity.coins} coins and ${n(r.amenity.upkeepPerMinute)}/min. It contributes +${r.amenity.value} nearby desirability; industry can cancel that benefit.</li><li>Citizen goods go to eligible households. Start with a small, desirable district.</li><li>Surplus citizens can fill rough jobs at full pace. Keep workshops within road commuting distance.</li><li>Place workshops before farms can plant over their future plots.</li><li>Repair services have a ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds}-second window between the repair threshold and half speed.</li></ul>
+${saved ? `<h2>Captured bot town · minute 30</h2><p>Only ${saved.household.filter((h) => h.potentialTier >= 2).length} of ${saved.household.length} homes pass the current desirability gate. Even granting unlimited needs and services, those homes hold at most ${saved.citizenGoal.housingCeilingAtCurrentDesirability} citizens/burghers, versus ${saved.citizenGoal.minimumAtPopulationGoal} required at the population goal.</p><p>Cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min; supplying eligible homes needs at least ${n(saved.needBounds.cloth.min)}/min. Compare those constraints with the observed staffing, deliveries and goal-hold duration.</p>` : ""}
<h2>Workshop ceilings · output per minute</h2>${table(["Building", "Own crew + tool", "Apprentices + tool", "Apprentices, no tool"], r.capacity.map((c) => [c.kind, n(c.staffed), n(c.apprentices), n(c.apprenticesWithoutTools)]))}
<h2>Winter fishing · household capacity before losses</h2>${table(["Winter", "Fish/min", "Homes, late refresh", "Homes, frequent refresh"], r.winter.map((w) => [w.severity, n(w.fishPerMinute), n(w.noWasteHomesPerFishery), n(w.frequentRefreshHomesPerFishery)]))}
<details><summary>Verification and limitations</summary>${table(["Check", "Expected", "Actual", "Pass"], r.verification.map((v) => [v.name, n(v.expected), n(v.actual), v.pass]))}<ul>${r.limits.map((l) => `<li>${escape(l)}</li>`).join("")}</ul></details><p class="muted">Rules SHA-256 <code>${r.provenance.rulesSha256}</code></p></body></html>`
diff --git a/tools/balance/verify/checks.ts b/tools/balance/verify/checks.ts
index 55926dc..5fd126e 100644
--- a/tools/balance/verify/checks.ts
+++ b/tools/balance/verify/checks.ts
@@ -65,33 +65,37 @@ export const verifyTransport = (rules: Rules): Verification => {
"Real full-load trips to a distant warehouse; tolerance permits one in-flight load per carrier at the measurement boundary")
}
-/** Independent runtime excursions, compared with finite-path DP rather than another mathematical sampler. */
-export const verifyService = (rules: Rules, branched: boolean, seeds = 16): Verification => {
+/** Complete dispatch cycles checked against the shared deterministic tours. */
+export const verifyService = (rules: Rules, branched: boolean, seeds = 4): Verification => {
const base = district(branched ? "branched-faith" : "straight-faith", Array(10).fill(1), ["chapel"], branched, rules)
- const scenario = { ...base, homes: base.homes.map((h) => ({ ...h, food: 10000000 })), buildings: base.buildings.map((b) => ({ ...b, stock: amounts({}) })) }
- const chapel = scenario.buildings.find((b) => b.kind === "chapel")!, target = scenario.homes[scenario.homes.length - 1]!
- const predicted = analyze({ rules, scenario }).services.find((p) => p.source === chapel.id)!.contacts.find((c) => c.target === target.id)?.hitProbability ?? 0
+ const scenario = { ...base, homes: base.homes.map(h => ({ ...h, food: 10000000 })), buildings: base.buildings.map(b => ({ ...b, stock: amounts({}) })) }
+ const chapel = scenario.buildings.find(b => b.kind === "chapel")!, target = scenario.homes.at(-1)!
+ const profile = analyze({ rules, scenario }).services.find(p => p.source === chapel.id)!
+ const predicted = profile.contacts.find(c => c.target === target.id)?.hitProbability ?? 0
+ const wanted = profile.tours * 2
let trips = 0, hits = 0
for (let seed = 0; seed < seeds; seed++) {
const town = fixture({ ...scenario, charter: { ...scenario.charter, seed: 1000 + seed * 7919 } }, rules)
const seen = new Map<number, { hit: boolean; completed: boolean }>()
- for (let second = 0; second < 80; second += 0.4) {
+ for (let second = 0; second < 300; second += 0.4) {
town.run(0.4)
- const snapshot = town.snapshot()
- const walkers = snapshot.entities.filter((e) => e.components["Town/Roam"]?.service === "faith")
- for (const e of walkers) {
+ for (const e of town.snapshot().entities.filter(e => e.components["Town/Roam"]?.service === "faith")) {
+ if (!seen.has(e.id) && seen.size >= wanted) continue
const roam = e.components["Town/Roam"], route = e.components["Town/Route"]
const record = seen.get(e.id) ?? { hit: false, completed: false }
const cell = roam.back ? route.cells[0] : route.cells[route.index]
if (!record.completed && cell && Math.abs(cell.x - target.tile.x) + Math.abs(cell.y - target.tile.y) === 1) record.hit = true
- if (roam.back && !record.completed) { trips += 1; hits += Number(record.hit); record.completed = true }
+ if (roam.back) record.completed = true
seen.set(e.id, record)
}
+ if (seen.size === wanted && [...seen.values()].every(r => r.completed)) break
}
+ if (seen.size !== wanted || [...seen.values()].some(r => !r.completed)) throw new Error("Service tours did not complete in 300 seconds")
+ trips += seen.size
+ hits += [...seen.values()].filter(r => r.hit).length
}
- const actual = trips > 0 ? hits / trips : 0, tolerance = 3 * Math.sqrt(Math.max(0.01, predicted * (1 - predicted)) / Math.max(1, trips)) + 0.03
- return compare(branched ? "branched-service-hit" : "straight-service-hit", "finite-path probability", predicted, actual, tolerance,
- `${hits}/${trips} completed excursions across ${seeds} fixed seeds; tolerance is 3 standard errors plus 0.03 sampling allowance. No basket depletion in faith service.`)
+ return compare(branched ? "branched-service-coverage" : "straight-service-coverage", "exact tour fraction", predicted, hits / trips, 1e-12,
+ `${hits}/${trips} completed dispatches across ${seeds} seeds; two whole rotation cycles per seed, unlimited faith baskets`)
}
export const verifyProjection = (inputs: Inputs, options: ProjectionOptions) => {