Skip to content

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

Model cell parks with shared rules and refresh verification results

SandroMaglioned600eaec3bf8
diff --git a/docs/balance-model-results.md b/docs/balance-model-results.md
index d53326c..5db323c 100644
--- a/docs/balance-model-results.md
+++ b/docs/balance-model-results.md
@@ -1,10 +1,10 @@
# Balance model results
-Generated from PR #3 at 8de46be33c351052af64326f034888e0f09092a8. No shipped parameter changes. Rules SHA-256: c2654cafa41aad51176030ba4f2ec484d61bfd372f9d8a247284a64855ab3c7c.
+Generated from PR #3 at 9b7ce7336a18f917a10aa6e21ae32cb57af88643. No shipped parameter changes. Rules SHA-256: 75d55bee5b0cc2f6167082e8e01d3030171fa8fb2eebf35fa966d6c47a778ac1.
## First citizens, with unchanged rules
-An 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 336 seconds; the coarse model estimates 255. At ten minutes the game has 32 citizens, 55 residents and 1149 coins. The forecast has 32 citizens, 61 residents and 1467 coins. This is a progression fixture, not a generated-map victory claim.
+An 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 336 seconds; the coarse model estimates 255. At ten minutes the game has 32 citizens, 54 residents and 1071 coins. The forecast has 32 citizens, 60 residents and 1399 coins. This is a progression fixture, not a generated-map victory claim.
## Production capacity
@@ -23,6 +23,7 @@ Outputs per minute with full crews, sufficient inputs, output room and maintaine
## Useful constraints
- The first citizen chain alone costs 870 coins and 3 construction tools. Its 3 wearing workshops also need working tools. Total 6, versus 8 at a fair start. Raw industry adds more tool demand.
+- The verified park uses three adjacent flower cells, one fountain and one lamp: 97 coins, 2.65/min upkeep, +8 desirability at the nearest cells, reach 2. Its effects combine with industry and chapel effects; nearby raw industry remains a liability. Place furnishings after the ground exists.
- Settlers accept cloth, and bread is preferred for food. Supplying a broad settler district can consume goods intended for citizen upgrades.
- Promotion changes the workforce: citizens cannot fill settlers' jobs. Keep raw-production households within commuting distance.
- 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 0 rejected-action messages.
diff --git a/docs/balance-model.md b/docs/balance-model.md
index 4fbee8d..f4278cc 100644
--- a/docs/balance-model.md
+++ b/docs/balance-model.md
@@ -48,6 +48,18 @@ const transport = assessTransfers(inputs, [
`Scenario` contains plain buildings, households, roads, land, reserves, policy and optional trade conditions. Counts and locations are scenario choices. Rule values come from `resolveRules()`; there is no second recipe table in the analyzer. Construction schedules use the same scenario and ordinary player edits in `verifyBuilds`.
+Parks are individual ground cells with optional furnishings. Their grouping, repeat penalties, entrance bonuses, reach, desirability and upkeep come from the same functions as the game. Construction schedules can place ground and furnishings as well as ordinary buildings. Furnishings are scheduled after the ground's entities exist.
+
+```mermaid
+flowchart LR
+ Content["Game content"] --> Rules["Shared pure rules"]
+ Rules --> Game["Live game"]
+ Rules --> Model["Offline mathematics"]
+ Model --> Candidates["Constraints and candidate plans"]
+ Candidates --> Verify["Real-game verification"]
+ Game --> Verify
+```
+
`src/rules/` contains game behavior. `tools/balance/model/` contains mathematical transformations and approximations. `tools/balance/verify/` owns runtime adapters and controlled experiments. `catalog.ts` contains authored examples, not universal winning layouts.
## What is calculated
@@ -77,13 +89,13 @@ pnpm balance:model sweep --path kinds.weaver.recipe.seconds --values 4,8,12
## Verification and interpreting results
-`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. A candidate weaver period is also executed by the game to verify that both consumers receive the same inputs.
+`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.
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.
-The original seed-1000 sensible mayor's entire minute-30 world is checked against the PR #3 reference SHA-256 `3eff85260d3a97c25ad628dcf244e8f8b4abc6cd02407eed4446807e03d97557`. This checks the shared-rule extraction across production, transport, random streams, risks, economy and persistence. Refresh that reference only after an intentional gameplay or engine change has been reviewed.
+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.
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/src/rules/households.ts b/src/rules/households.ts
index 1b2d1e0..13d26ef 100644
--- a/src/rules/households.ts
+++ b/src/rules/households.ts
@@ -69,8 +69,11 @@ export const askOf = (good: GoodId, percent: number, rules: Rules = shippedRules
export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates, rules: Rules = shippedRules): number =>
h.residents * rules.home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h, h.tier, rules))
-export const lowNeed = (left: number, need: Need, rules: Rules = shippedRules) => left < rules.home.lasts[need] / 2
+export const refreshLevel = (need: Need, rules: Rules = shippedRules) => rules.home.lasts[need] / 2
+export const lowNeed = (left: number, need: Need, rules: Rules = shippedRules) => left < refreshLevel(need, rules)
export const mealDecay = (tick: number, winter: boolean) => winter && tick % 2 === 0 ? 2 : 1
+/** Mean of the same two-tick meal cadence, for rate-based consumers. */
+export const mealRate = (winter: boolean) => (mealDecay(0, winter) + mealDecay(1, winter)) / 2
type Mutable<T> = { -readonly [K in keyof T]: T[K] }
export const ageNeeds = <T extends Needs & { readonly clock: number }>(h: T, eat: number): Mutable<T> => ({
...h, clock: h.clock + 1, food: Math.max(0, h.food - eat), bread: Math.max(0, h.bread - eat),
diff --git a/test/balance-model.test.ts b/test/balance-model.test.ts
index 8ce5919..8486f6d 100644
--- a/test/balance-model.test.ts
+++ b/test/balance-model.test.ts
@@ -52,6 +52,23 @@ test("paused upkeep candidates are shared with the actual ledger", () => {
assert.notEqual(expected, analyze({ rules: resolveRules(), scenario }, { services: false }).economy.roundedNetPerMinute)
})
+test("cell parks share grouping, beauty and upkeep with the real game", () => {
+ const rules = resolveRules([{ path: "grounds.flowers.beauty", value: 1.25 }, { path: "props.fountain.beauty", value: 6 }, { path: "grounds.flowers.upkeep", value: 0.4 }])
+ const base = citizensDistrict(rules), scenario = { ...base,
+ homes: base.homes.map((h) => ({ ...h, food: 10000000 })), buildings: base.buildings.filter((b) => b.kind === "townhall").map((b) => ({ ...b, stock: amounts({}) })) }
+ const expected = analyze({ rules, scenario }, { services: false })
+ const town = fixture(scenario, rules), before = town.snapshot().resources["Town/Treasury"].coins
+ town.run(60)
+ const actual = town.snapshot()
+ 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(expected.economy.parkUpkeepPerMinute > 0)
+ assert.notEqual(expected.household[0]!.desirability, analyze({ rules: resolveRules(), scenario }, { services: false }).household[0]!.desirability)
+})
+
test("desirability rejects an industrial citizen plan even with sufficient goods", () => {
const rules = resolveRules(), industrial = analyze({ rules, scenario: citizensDistrict(rules, false) }), zoned = analyze({ rules, scenario: citizensDistrict(rules, true) })
assert.equal(industrial.household.filter((h) => h.potentialTier >= 2).length, 0)
diff --git a/tools/balance/catalog.ts b/tools/balance/catalog.ts
index 79c1f5f..78ab9ae 100644
--- a/tools/balance/catalog.ts
+++ b/tools/balance/catalog.ts
@@ -1,12 +1,17 @@
-import { amounts, type KindId } from "../../src/content.ts"
+import { type KindId } from "../../src/content.ts"
import type { Rules } from "../../src/rules/config.ts"
import { district } from "./scenario.ts"
import type { BuildAction, Scenario } from "./types.ts"
-export const citizensDistrict = (rules: Rules, gardens = true): Scenario => {
- const s = district(gardens ? "zoned-citizens" : "industrial-citizens", Array(12).fill(1), ["farm", "mill", "bakery", "sheep", "weaver", "market", "chapel"], false, rules)
- return gardens ? { ...s, buildings: [...s.buildings, ...s.homes.slice(0, 4).map((h, i) => ({ id: 300 + i, kind: "garden" as const,
- tile: { x: h.tile.x, y: h.tile.y - 1, size: 1 }, condition: rules.conditionMax, site: false, paused: false, stock: amounts({}) }))] } : s
+/** A three-cell planted park beside four homes; uses the actual cell/prop rules. */
+export const citizenPark = () => [
+ { x: 9, y: 28, ground: "flowers" as const, prop: "fountain" as const },
+ { x: 10, y: 28, ground: "flowers" as const, prop: "lamp" as const },
+ { x: 11, y: 28, ground: "flowers" as const, prop: "none" as const }
+]
+export const citizensDistrict = (rules: Rules, parks = true): Scenario => {
+ const s = district(parks ? "zoned-citizens" : "industrial-citizens", Array(12).fill(1), ["farm", "mill", "bakery", "sheep", "weaver", "market", "chapel"], false, rules)
+ return parks ? { ...s, parks: citizenPark() } : s
}
/** Authored flat-land starting district. Roads/homes are charged; it is not a generated-map or human-win claim. */
@@ -23,6 +28,8 @@ 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 }))
- for (const h of scenario.homes.slice(0, 4)) builds.push({ kind: "garden", at: 0, tile: { x: h.tile.x, y: h.tile.y - 1, size: 1 } })
+ 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 } })
return { scenario, builds }
}
diff --git a/tools/balance/index.ts b/tools/balance/index.ts
index 3139e5b..9a94a98 100644
--- a/tools/balance/index.ts
+++ b/tools/balance/index.ts
@@ -7,3 +7,5 @@ export { serviceProfile, missProbability } from "./model/services.ts"
export { searchParameters, searchDistricts } from "./model/search.ts"
export { fromSnapshot, scenarioGrid, validateScenario, district } from "./scenario.ts"
export type { Scenario, Inputs, Finding, Confidence, BuildAction, ProjectionOptions } from "./types.ts"
+
+export { parkValue, parksOf, parkSources, parkUpkeep, type ParkCell } from "../../src/appeal.ts"
diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.ts
index 6779aff..893c942 100644
--- a/tools/balance/model/analyze.ts
+++ b/tools/balance/model/analyze.ts
@@ -1,8 +1,8 @@
import { amounts, goodIds, type GoodId, type WinterId } from "../../../src/content.ts"
-import { appealAt, appealGrid, buildingSource, landSource } from "../../../src/appeal.ts"
+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, taxOf, tierFor } from "../../../src/rules/households.ts"
+import { baseCollection, 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"
@@ -34,6 +34,8 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
for (const r of s.roads) if (r.paved) sources.push(landSource("paved", r, rules))
for (const r of s.ruins ?? []) sources.push(landSource("ruin", r, rules))
for (const h of s.homes) if (h.condition < rules.condition.worn) sources.push(landSource("worn", h.tile, rules))
+ const roadCells = new Set(s.roads.map((p) => `${p.x},${p.y}`))
+ sources.push(...parkSources(s.parks ?? [], (x, y) => roadCells.has(`${x},${y}`), rules))
const appeal = appealGrid(sources, rules), findings: Finding[] = []
const recipes = s.buildings.filter((b) => !b.site && !b.paused && rules.kinds[b.kind].recipe).map((b) => {
const kind = rules.kinds[b.kind], crew = staff.get(b.id) ?? zero
@@ -79,11 +81,11 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
if (heldTools < toolWorkplaces.length) findings.push({ code: "working-tool-capital", confidence: "exact", detail: `${toolWorkplaces.length} wearing workplaces need ${toolWorkplaces.length} working tools; only ${heldTools} tools are held across all buildings` })
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 = severity === null ? 1 : 1.5
+ const foodDecay = mealRate(severity !== null)
const needBounds = {
- food: { min: s.homes.length * foodDecay * 60 / (rules.home.lasts.food * rules.stepSeconds), frequent: s.homes.length * foodDecay * 120 / (rules.home.lasts.food * rules.stepSeconds) },
- cloth: { min: s.homes.length * 60 / (rules.home.lasts.cloth * rules.stepSeconds), frequent: s.homes.length * 120 / (rules.home.lasts.cloth * 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 * 120 / (rules.home.lasts.cloth * rules.stepSeconds) }
+ 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) },
+ 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
@@ -92,7 +94,8 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
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)
- const collection = baseCollection(taxes, upkeep, s.homes.length, rules), cashPerMinute = collection.delta * 60 / (rules.ledgerTicks * rules.stepSeconds)
+ const parkCost = (s.parks ?? []).reduce((n, p) => n + parkUpkeep(p, rules), 0)
+ const collection = baseCollection(taxes, upkeep + parkCost, s.homes.length, rules), cashPerMinute = collection.delta * 60 / (rules.ledgerTicks * rules.stepSeconds)
const profiles = options.services === false ? [] : s.buildings.flatMap((b) => { const p = serviceProfile(s, b, staff.get(b.id) ?? zero, rules); return p ? [p] : [] })
const household = s.homes.map((h) => {
const desirable = appealAt(appeal, h.tile.x, h.tile.y)
@@ -134,13 +137,13 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
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."],
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, administrationPerMinute: collection.admin, roundedNetPerMinute: cashPerMinute,
+ economy: { taxesPerMinute: taxes, upkeepPerMinute: upkeep + parkCost, parkUpkeepPerMinute: parkCost, administrationPerMinute: collection.admin, roundedNetPerMinute: cashPerMinute,
noTradeRunwayMinutes: cashPerMinute < 0 ? Math.max(0, s.coins) / -cashPerMinute : null },
currentGoalsWithoutTrade: goalsOf(s.charter, { settlers: s.homes.filter((h) => h.tier === 1).reduce((n, h) => n + h.residents, 0), citizens: s.homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0), coins: s.coins, net: cashPerMinute, approval: s.approval }, rules),
tools: { wearingWorkplaces: toolWorkplaces.length, equippedWorkplaces: workingTools, held: heldTools },
repair: { upkeepCycleMinutes: (rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds / 60,
- planksPerMinute: (s.homes.length + s.buildings.filter((b) => !rules.kinds[b.kind].decor && b.kind !== "townhall").length) * 60 / ((rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds),
- stonePerMinute: s.buildings.filter((b) => !rules.kinds[b.kind].decor && b.kind !== "townhall").length * 60 / ((rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds),
+ planksPerMinute: (s.homes.length + s.buildings.filter((b) => b.kind !== "townhall").length) * 60 / ((rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds),
+ stonePerMinute: s.buildings.filter((b) => b.kind !== "townhall").length * 60 / ((rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds),
graceBeforeHalfSpeedSeconds: (rules.condition.mend - rules.condition.worn) * rules.condition.every * rules.stepSeconds },
citizenGoal: { housingCeilingAtCurrentDesirability: citizenHousingCeiling, minimumAtPopulationGoal: requiredCitizensAtPopulationGoal, scope: "Existing homes and frozen neighbourhood; assumes every need/service could be supplied. Clearing ruins, repairs, new homes or amenities can change this ceiling." },
household, transport, services: profiles, findings }
diff --git a/tools/balance/model/project.ts b/tools/balance/model/project.ts
index b1aa750..cc04925 100644
--- a/tools/balance/model/project.ts
+++ b/tools/balance/model/project.ts
@@ -1,6 +1,7 @@
import { amounts, goodIds, type Amounts } from "../../../src/content.ts"
+import { parkUpkeep } from "../../../src/appeal.ts"
import { ruleTicks } from "../../../src/rules/config.ts"
-import { baseCollection, capacity, serveGoods, taxOf, tierFor } from "../../../src/rules/households.ts"
+import { baseCollection, capacity, mealRate, serveGoods, taxOf, tierFor } from "../../../src/rules/households.ts"
import { seasonAt } from "../../../src/rules/seasons.ts"
import { spoilExpectation } from "../../../src/rules/decay.ts"
import { tradeCollection } from "../../../src/rules/trade.ts"
@@ -8,7 +9,7 @@ import { approvalTarget, nextApproval } from "../../../src/rules/approval.ts"
import { analyze } from "./analyze.ts"
import { around, cellsOf, key, ownerAt } from "../../../src/grid.ts"
import { scenarioGrid } from "../scenario.ts"
-import type { Inputs, ModelBuilding, ProjectionOptions, Scenario } from "../types.ts"
+import type { Inputs, BuildingAction, ModelBuilding, ProjectionOptions, Scenario } from "../types.ts"
/** Rate-based forecast with explicit temporal assumptions. It never calls the game runtime. */
export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions) => {
@@ -16,10 +17,11 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
if (!Number.isInteger(step) || step < 1 || step > 3 || !Number.isInteger(options.seconds) || options.seconds <= 0) throw new Error("Projection requires a 1..3 second step and a positive integer horizon")
const stock = { ...amounts({}) }
for (const b of scenario.buildings) if (!b.site) for (const g of goodIds) stock[g] += b.stock[g]
+ let parks = [...scenario.parks ?? []]
let homes = scenario.homes.map((h) => ({ ...h, meters: { ...h.meters } })), buildings = [...scenario.buildings], coins = scenario.coins, approval = scenario.approval
const events: Array<{ second: number; type: string; detail: string }> = [], rows: Array<{ second: number; coins: number; residents: number; citizens: number; approval: number; stock: Amounts }> = []
const builds = [...options.builds ?? []].sort((a, b) => a.at - b.at), crown = [...options.crown ?? []].sort((a, b) => a.at - b.at)
- const pending: Array<{ ready: number; action: typeof builds[number] }> = []
+ const pending: Array<{ ready: number; action: BuildingAction }> = []
let nextId = Math.max(0, ...homes.map((h) => h.id), ...buildings.map((b) => b.id)) + 1
let analysis = analyze({ rules, scenario }, { services: true }), cachedKey = "", firstCitizen: number | null = null
let prices = scenario.trade?.prices ?? amounts(Object.fromEntries(goodIds.map((g) => [g, 100])))
@@ -29,7 +31,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
const crop = (b: ModelBuilding) => {
let state = fields.get(b.id)
if (!state) {
- const grid = scenarioGrid({ ...scenario, buildings, homes }, rules).value()
+ const grid = scenarioGrid({ ...scenario, buildings, homes, parks }, rules).value()
const k = rules.kinds[b.kind], ids = new Set(around(b.tile, k.gathers!.radius).map((p) => ownerAt(grid, p.x, p.y)))
const existing = scenario.land.filter((l, i) => l.type === "field" && ids.has(-1 - i))
state = { credit: existing.filter((l) => l.growth >= rules.grown.field).length, slots: existing.length, planting: 0,
@@ -53,19 +55,30 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
if (second === options.seconds) break
const tick = scenario.tick + ruleTicks(second, rules), season = seasonAt(tick, scenario.charter, rules)
while (builds.length > 0 && builds[0]!.at <= second) {
- const action = builds.shift()!, k = action.kind === "home" ? null : rules.kinds[action.kind], cost = k?.cost ?? rules.home.cost
+ const action = builds.shift()!
+ const piece = action.kind === "ground" ? rules.grounds[action.ground] : action.kind === "prop" ? rules.props[action.prop] : null
+ const k = action.kind === "home" || action.kind === "ground" || action.kind === "prop" ? null : rules.kinds[action.kind]
+ const cost = piece?.cost ?? k?.cost ?? rules.home.cost
if (k?.plants?.what === "field") {
const plantingCells = new Set(around(action.tile, k.plants.radius).map((p) => key(p.x, p.y)))
for (const future of builds) if (cellsOf(future.tile).some((p) => plantingCells.has(key(p.x, p.y)))) events.push({ second, type: "crop-placement-risk", detail: `${future.kind}'s future plot is inside ${action.kind}'s planting area; construct it first or clear fields later` })
}
const people = homes.reduce((n, h) => n + h.residents, 0), citizens = homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0)
const equipped = buildings.filter((b) => rules.kinds[b.kind].wear && b.stock.tools > 0).length
- if ((k && (people < k.unlock.residents || citizens < k.unlock.citizens)) || coins < cost.coins || Object.entries(cost.materials).some(([g, n]) => stock[g as keyof Amounts] - (g === "tools" ? equipped : 0) < n!)) {
+ if (((k || piece) && (people < (k ?? piece)!.unlock.residents || citizens < (k ?? piece)!.unlock.citizens)) || coins < cost.coins || Object.entries(cost.materials).some(([g, n]) => stock[g as keyof Amounts] - (g === "tools" ? equipped : 0) < n!)) {
events.push({ second, type: "build-blocked", detail: `${action.kind}: unlock, coins or materials unavailable` }); continue
}
+ if (action.kind === "prop" && !parks.some((p) => p.x === action.tile.x && p.y === action.tile.y)) {
+ events.push({ second, type: "build-blocked", detail: "A furnishing needs a park cell" }); continue
+ }
coins -= cost.coins
for (const [g, n] of Object.entries(cost.materials)) stock[g as keyof Amounts] -= n!
- pending.push({ ready: second + rules.buildTicks * rules.stepSeconds, action })
+ if (action.kind === "ground") {
+ const cell = parks.find((p) => p.x === action.tile.x && p.y === action.tile.y)
+ if (cell) parks = parks.map((p) => p === cell ? { ...p, ground: action.ground } : p)
+ else parks.push({ x: action.tile.x, y: action.tile.y, ground: action.ground, prop: "none" })
+ } else if (action.kind === "prop") parks = parks.map((p) => p.x === action.tile.x && p.y === action.tile.y ? { ...p, prop: action.prop } : p)
+ else pending.push({ ready: second + rules.buildTicks * rules.stepSeconds, action })
events.push({ second, type: "build-paid", detail: `${action.kind}: ${cost.coins} coins` })
}
for (let i = pending.length - 1; i >= 0; i--) {
@@ -78,9 +91,9 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
}
let toolSlots = Math.floor(stock.tools)
buildings = buildings.map((b) => rules.kinds[b.kind].wear ? { ...b, stock: { ...b.stock, tools: toolSlots-- > 0 ? 1 : 0 } } : b)
- const stateKey = JSON.stringify([homes.map((h) => [h.id, h.tier, h.residents]), buildings.map((b) => [b.id, b.stock.tools, b.condition < rules.condition.worn]), season.severity])
+ const stateKey = JSON.stringify([homes.map((h) => [h.id, h.tier, h.residents]), buildings.map((b) => [b.id, b.stock.tools, b.condition < rules.condition.worn]), season.severity, parks])
if (stateKey !== cachedKey) {
- const current: Scenario = { ...scenario, tick, coins, approval, homes, buildings }
+ const current: Scenario = { ...scenario, tick, coins, approval, homes, buildings, parks }
analysis = analyze({ rules, scenario: current }, { minutes: Math.max(1 / 60, (options.seconds - second) / 60), services: true })
updatePeriods()
cachedKey = stateKey
@@ -103,7 +116,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
jobs = Math.min(jobs, state.credit); state.credit -= jobs
if (jobs > 0) state.growing.push({ left: rules.grown.field * rules.stepSeconds, credit: jobs })
} else if (k.gathers && k.gathers.source !== "water") {
- const b = buildings.find((b) => b.id === row.id)!, grid = scenarioGrid({ ...scenario, buildings, homes }, rules).value()
+ const b = buildings.find((b) => b.id === row.id)!, grid = scenarioGrid({ ...scenario, buildings, homes, parks }, rules).value()
const ids = new Set(around(b.tile, k.gathers.radius).map((p) => ownerAt(grid, p.x, p.y)))
const sources = land.filter((l, i) => ids.has(-1 - i) && l.type === k.gathers!.source && (l.type !== "tree" || l.growth >= rules.grown.tree))
jobs = Math.min(jobs, sources.reduce((n, l) => n + l.remaining, 0))
@@ -128,7 +141,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
next = { ...served.house }
}
if (Number.isFinite(faith) && Math.floor(second / faith) !== Math.floor((second + step) / faith)) next.faith = rules.home.lasts.faith
- const dt = ruleTicks(step, rules), eat = season.winter ? dt * 1.5 : dt
+ const dt = ruleTicks(step, rules), eat = dt * mealRate(season.winter)
next.clock += dt; next.food = Math.max(0, next.food - eat); next.bread = Math.max(0, next.bread - eat); next.cloth = Math.max(0, next.cloth - dt); next.faith = Math.max(0, next.faith - dt)
const settleCount = Math.floor(next.clock / rules.home.settle) - Math.floor(h.clock / rules.home.settle)
const appeal = analysis.household.find((a) => a.id === h.id)?.desirability ?? 0
@@ -143,7 +156,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
})
if (firstCitizen === null && homes.some((h) => h.tier >= 2 && h.residents > 0)) firstCitizen = second + step
for (let i = 0; i < homes.length; i++) if (homes[i]!.tier !== oldTiers[i]) events.push({ second: second + step, type: "tier", detail: `Home #${homes[i]!.id}: ${oldTiers[i]} → ${homes[i]!.tier}` })
- buildings = buildings.map((b) => ({ ...b, condition: rules.kinds[b.kind].decor || b.kind === "townhall" ? b.condition : Math.max(0, b.condition - step / (rules.condition.every * rules.stepSeconds)) }))
+ buildings = buildings.map((b) => ({ ...b, condition: b.kind === "townhall" ? b.condition : Math.max(0, b.condition - step / (rules.condition.every * rules.stepSeconds)) }))
const elapsed = second + step
if (Math.floor(elapsed / (rules.spoilTicks * rules.stepSeconds)) > Math.floor(second / (rules.spoilTicks * rules.stepSeconds))) {
const keeps = buildings.some((b) => rules.kinds[b.kind].keeps) ? Math.max(...buildings.map((b) => rules.kinds[b.kind].keeps ?? 1)) : 1
@@ -151,7 +164,8 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
}
if (Math.floor(elapsed / (rules.ledgerTicks * rules.stepSeconds)) > Math.floor(second / (rules.ledgerTicks * rules.stepSeconds))) {
const tax = homes.reduce((n, h) => n + (analysis.household.find((a) => a.id === h.id)?.taxConnected ? taxOf(h, scenario.policy, rules) : 0), 0), upkeep = buildings.reduce((n, b) => n + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)
- coins += baseCollection(tax, upkeep, homes.length, rules).delta
+ const parkCost = parks.reduce((n, p) => n + parkUpkeep(p, rules), 0)
+ coins += baseCollection(tax, upkeep + parkCost, homes.length, rules).delta
if (scenario.trade) {
const equipped = buildings.filter((b) => rules.kinds[b.kind].wear && b.stock.tools > 0).length
const left = { ...stock, tools: Math.max(0, stock.tools - equipped) }, stores = buildings.filter((b) => rules.kinds[b.kind].holds?.accepts === "all" || rules.kinds[b.kind].keeps).map((b) => {
diff --git a/tools/balance/model/services.ts b/tools/balance/model/services.ts
index e954c20..53c47dc 100644
--- a/tools/balance/model/services.ts
+++ b/tools/balance/model/services.ts
@@ -24,7 +24,7 @@ export const serviceProfile = (scenario: Scenario, building: ModelBuilding, staf
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 && !rules.kinds[b.kind].decor)] : scenario.homes
+ 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)
diff --git a/tools/balance/provenance.ts b/tools/balance/provenance.ts
index a312f86..b2d538a 100644
--- a/tools/balance/provenance.ts
+++ b/tools/balance/provenance.ts
@@ -7,7 +7,7 @@ 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: "8de46be33c351052af64326f034888e0f09092a8",
+ return { modelVersion: 1, referencePr: "https://github.com/SandroMaglione/inkline-town/pull/3", referenceSha: "9b7ce7336a18f917a10aa6e21ae32cb57af88643",
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 aec47d7..63047e4 100644
--- a/tools/balance/report.ts
+++ b/tools/balance/report.ts
@@ -1,10 +1,12 @@
import { amounts, type KindId } from "../../src/content.ts"
import type { Rules } from "../../src/rules/config.ts"
+import { mealRate, refreshLevel } from "../../src/rules/households.ts"
+import { parkValue, parkUpkeep } from "../../src/appeal.ts"
import { recipeCapacity } from "./model/throughput.ts"
import { analyze } from "./model/analyze.ts"
import { searchDistricts } from "./model/search.ts"
import { district } from "./scenario.ts"
-import { citizensDistrict } from "./catalog.ts"
+import { citizensDistrict, citizenPark } from "./catalog.ts"
import { provenance } from "./provenance.ts"
import type { Scenario } from "./types.ts"
import type { Verification } from "./verify/checks.ts"
@@ -24,14 +26,20 @@ export const makeReport = (rules: Rules, verification: ReadonlyArray<Verificatio
apprenticesWithoutTools: rules.kinds[kind].crew === "citizens" ? recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: rules.kinds[kind].workers, nearby: 0 }, 0, rules.conditionMax, null, rules).outputPerMinute : null }))
const winter = (["mild", "normal", "hard"] as const).map((severity) => {
const k = rules.kinds.fishery, perMinute = recipeCapacity(k, { assigned: k.workers, apprentices: 0, nearby: 100 }, 1, rules.conditionMax, severity, rules).outputPerMinute
- return { severity, durationMinutesIn60MinuteTerm: 60 / rules.yearsPerTerm * rules.winters[severity].share, fishPerMinute: perMinute, noWasteHomesPerFishery: perMinute / 1.5, frequentRefreshHomesPerFishery: perMinute / 3 }
+ const minimum = mealRate(true) * 60 / (rules.home.lasts.food * rules.stepSeconds)
+ const frequent = mealRate(true) * 60 / ((rules.home.lasts.food - refreshLevel("food", rules)) * rules.stepSeconds)
+ return { severity, durationMinutesIn60MinuteTerm: 60 / rules.yearsPerTerm * rules.winters[severity].share, fishPerMinute: perMinute, noWasteHomesPerFishery: perMinute / minimum, frequentRefreshHomesPerFishery: perMinute / frequent }
})
+ const parkCells = citizenPark(), amenity = { value: parkValue(parkCells, undefined, rules).value, reach: parkValue(parkCells, undefined, rules).reach,
+ coins: parkCells.reduce((n, p) => n + rules.grounds[p.ground].cost.coins + (p.prop === "none" ? 0 : rules.props[p.prop].cost.coins), 0),
+ upkeepPerMinute: parkCells.reduce((n, p) => n + parkUpkeep(p, rules), 0),
+ layout: "Three adjacent flower cells with one fountain and one lamp; ground before furnishings" }
const configurations = searchDistricts(rules, 8)
return { provenance: provenance(rules, [...scenarios, construction.final]), generatedAt: new Date().toISOString(),
- analysisElapsedMs: performance.now() - started, capacity, winter,
+ analysisElapsedMs: performance.now() - started, capacity, winter, amenity,
firstCitizenChain: { coins: chain.reduce((n, k) => n + rules.kinds[k].cost.coins, 0), upkeepPerMinute: chain.reduce((n, k) => n + rules.kinds[k].upkeep, 0), materials,
workingTools, totalToolsIncludingConstruction: materials.tools + workingTools, fairStartingTools: rules.lands.fair.stock.tools,
- scope: "One of each chain building; excludes homes, roads, market, decorations, raw-material industry and risk services" },
+ scope: "One of each chain building; excludes homes, roads, market, parks, raw-material industry and risk services" },
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" },
@@ -42,7 +50,7 @@ const n = (v: number | null) => v === null ? "n/a" : Number(v.toFixed(2)).toStri
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- 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}. 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`
}
const escape = (s: unknown) => String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;")
@@ -52,7 +60,7 @@ export const htmlReport = (r: Report) => {
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>
${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>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>
+<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>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)]))}
diff --git a/tools/balance/scenario.ts b/tools/balance/scenario.ts
index fdcd5fd..8fce480 100644
--- a/tools/balance/scenario.ts
+++ b/tools/balance/scenario.ts
@@ -1,3 +1,4 @@
+import type { ParkCell } from "../../src/appeal.ts"
import { amounts, goodIds, type KindId, type Tier } from "../../src/content.ts"
import { GridBuilder, canPlace, doors, nearest, reach, type Use, type TileLike } from "../../src/grid.ts"
import { GRID } from "../../src/iso.ts"
@@ -12,6 +13,7 @@ export const scenarioGrid = (s: Scenario, rules: Rules = shippedRules): GridBuil
for (const h of s.homes) grid.claim(h.tile, h.id, "house")
for (const b of s.buildings) grid.claim({ ...b.tile, size: rules.kinds[b.kind].size }, b.id, "building")
for (const [i, r] of (s.ruins ?? []).entries()) grid.claim(r, -200000 - i, "ruin")
+ for (const [i, p] of (s.parks ?? []).entries()) grid.claim({ ...p, size: 1 }, -300000 - i, "park")
return grid
}
@@ -37,16 +39,21 @@ export const validateScenario = (s: Scenario, rules: Rules = shippedRules) => {
lay({ ...b.tile, size: rules.kinds[b.kind].size }, b.id, "building")
}
for (const [i, r] of (s.ruins ?? []).entries()) lay(r, -200000 - i, "ruin")
+ for (const [i, p] of (s.parks ?? []).entries()) {
+ if (!rules.grounds[p.ground] || (p.prop !== "none" && !rules.props[p.prop])) throw new Error("Unknown park piece")
+ lay({ ...p, size: 1 }, -300000 - i, "park")
+ }
}
/** Read-only adapter; loading a snapshot never starts the runtime. */
export const fromSnapshot = (snapshot: Snapshot, name = "saved-town", rules: Rules = shippedRules): Scenario => {
const r = snapshot.resources, homes: ModelHome[] = [], buildings: ModelBuilding[] = [], land: Scenario["land"][number][] = [], roads: Scenario["roads"][number][] = []
- const ruins: TileLike[] = []
+ const ruins: TileLike[] = [], parks: ParkCell[] = []
for (const { id, components: c } of snapshot.entities) {
const tile = c["Town/Tile"]
if (!tile) continue
if (c["Town/Road"]) roads.push({ x: tile.x, y: tile.y, ...(c["Town/Paved"] ? { paved: true } : {}) })
+ if (c["Town/Park"]) parks.push({ x: tile.x, y: tile.y, ...c["Town/Park"] })
if (c["Town/Ruin"]) ruins.push(tile)
if (c["Town/House"] && !c["Town/Site"] && !c["Town/Rising"] && !c["Town/Burning"]) homes.push({ id, tile, ...c["Town/House"], condition: c["Town/Condition"]?.value ?? rules.conditionMax, meters: c["Town/Risk"] ?? { fire: 0, health: 0, order: 0 }, ...(c["Town/Sick"] ? { sick: true } : {}) })
if (c["Town/Building"] && !c["Town/Burning"]) buildings.push({ id, kind: c["Town/Building"].kind, tile, stock: amounts(c["Town/Inventory"]?.stock ?? {}), condition: c["Town/Condition"]?.value ?? rules.conditionMax, paused: !!c["Town/Paused"], site: !!c["Town/Site"] || !!c["Town/Rising"] })
@@ -55,7 +62,7 @@ export const fromSnapshot = (snapshot: Snapshot, name = "saved-town", rules: Rul
}
const charter = r["Town/Charter"]
return { name, charter, tick: r["Town/Time"].tick - charter.founded, coins: r["Town/Treasury"].coins, approval: r["Town/Mood"].approval,
- policy: r["Town/Policy"], trade: { ...r["Town/Policy"], prices: r["Town/Market"].prices }, homes, buildings, roads, land, ruins, mask: r["Town/Land"].mask }
+ policy: r["Town/Policy"], trade: { ...r["Town/Policy"], prices: r["Town/Market"].prices }, homes, buildings, roads, land, ruins, parks, mask: r["Town/Land"].mask }
}
/** Small authored districts. The same geometry is used by analysis and controlled runtime verification. */
diff --git a/tools/balance/types.ts b/tools/balance/types.ts
index 11ce139..e1599eb 100644
--- a/tools/balance/types.ts
+++ b/tools/balance/types.ts
@@ -1,4 +1,5 @@
-import type { Amounts, CharterValue, KindId } from "../../src/content.ts"
+import type { Amounts, CharterValue, GroundId, PropId, KindId } from "../../src/content.ts"
+import type { ParkCell } from "../../src/appeal.ts"
import type { TileLike } from "../../src/grid.ts"
import type { Rules } from "../../src/rules/config.ts"
import type { Needs, Rates } from "../../src/rules/households.ts"
@@ -21,6 +22,7 @@ export interface Scenario {
readonly homes: ReadonlyArray<ModelHome>; readonly buildings: ReadonlyArray<ModelBuilding>
readonly land: ReadonlyArray<LandResource>; readonly mask?: string
readonly ruins?: ReadonlyArray<TileLike>
+ readonly parks?: ReadonlyArray<ParkCell>
readonly imports?: Partial<Record<keyof Amounts, number>>
readonly exports?: Partial<Record<keyof Amounts, number>>
readonly trade?: TradePolicy & { readonly prices?: Amounts }
@@ -32,7 +34,10 @@ export interface RecipeCapacity {
readonly jobsPerMinute: number; readonly outputPerMinute: number; readonly inputPerMinute: number
readonly toolsPerMinute: number; readonly meanJobTicks: number; readonly cadenceTicks: number
}
-export interface BuildAction { readonly at: number; readonly kind: KindId | "home"; readonly tile: TileLike }
+export type BuildingAction = { readonly at: number; readonly kind: KindId | "home"; readonly tile: TileLike }
+export type BuildAction = BuildingAction |
+ { readonly at: number; readonly kind: "ground"; readonly ground: GroundId; readonly tile: TileLike } |
+ { readonly at: number; readonly kind: "prop"; readonly prop: PropId; readonly tile: TileLike }
export interface ProjectionOptions {
readonly seconds: number; readonly stepSeconds?: number; readonly builds?: ReadonlyArray<BuildAction>
readonly feeding?: "fish" | "bread"; readonly visitSeconds?: number; readonly faith?: boolean
diff --git a/tools/balance/verify/checks.ts b/tools/balance/verify/checks.ts
index 7c94732..55926dc 100644
--- a/tools/balance/verify/checks.ts
+++ b/tools/balance/verify/checks.ts
@@ -1,3 +1,4 @@
+import { citizenPark } from "../catalog.ts"
import { amounts, type KindId } from "../../../src/content.ts"
import { type Rules } from "../../../src/rules/config.ts"
import { analyze } from "../model/analyze.ts"
@@ -14,7 +15,7 @@ const compare = (name: string, confidence: string, expected: number, actual: num
export const verifyProduction = (rules: Rules, kind: KindId, apprentices: boolean, tools: boolean, worn = false): Verification => {
let scenario = district(`production-${kind}`, [apprentices ? 1 : 2, apprentices ? 1 : 2], [kind], false, rules)
- scenario = { ...scenario, buildings: [...scenario.buildings, ...scenario.homes.map((h, i) => ({ id: 200 + i, kind: "garden" as const, tile: { x: h.tile.x, y: h.tile.y - 1, size: 1 }, condition: rules.conditionMax, paused: false, site: false, stock: amounts({}) }))] }
+ scenario = { ...scenario, parks: citizenPark() }
const producer = scenario.buildings.find((b) => b.kind === kind)!, recipe = rules.kinds[kind].recipe!
scenario = { ...scenario, homes: scenario.homes.map((h) => ({ ...h, food: 10000000, bread: apprentices ? 0 : 10000000, cloth: apprentices ? 0 : 10000000, faith: apprentices ? 0 : 10000000 })),
buildings: scenario.buildings.map((b) => ({ ...b, stock: amounts(b.id === producer.id ? { tools: tools ? 1 : 0 } : {}), condition: b.id === producer.id && worn ? rules.condition.worn - 1 : b.condition })) }
diff --git a/tools/balance/verify/fixture.ts b/tools/balance/verify/fixture.ts
index baef74d..dd8cc31 100644
--- a/tools/balance/verify/fixture.ts
+++ b/tools/balance/verify/fixture.ts
@@ -9,6 +9,7 @@ import type { BuildAction, Scenario } from "../types.ts"
export const fixture = (scenario: Scenario, rules: Rules): Headless => {
validateScenario(scenario, rules)
+ if (scenario.buildings.some((b) => b.site)) throw new Error("Controlled fixtures require completed buildings; a construction site needs its original owed materials and progress")
const town = headless(scenario.charter, { rules })
town.change((s) => {
s.entities = []; s.relations = {}; s.nextEntity = Math.max(0, ...scenario.homes.map((h) => h.id), ...scenario.buildings.map((b) => b.id)) + 1
@@ -16,7 +17,8 @@ export const fixture = (scenario: Scenario, rules: Rules): Headless => {
for (const h of scenario.homes) add({
"Town/Tile": h.tile, "Town/House": { tier: h.tier, residents: h.residents, food: h.food, bread: h.bread, cloth: h.cloth, faith: h.faith, clock: h.clock },
...Object.fromEntries(wearOf(rules).map(([d, v]) => [d.name, structuredClone(v)])),
- "Town/Risk": { ...h.meters, thefts: 0 }, "Town/Condition": { value: h.condition }
+ "Town/Risk": { ...h.meters, thefts: 0 }, "Town/Condition": { value: h.condition },
+ ...(h.sick ? { "Town/Sick": { left: rules.risk.health.lasts } } : {})
}, h.id)
for (const b of scenario.buildings) {
const kind = rules.kinds[b.kind]
@@ -31,6 +33,8 @@ export const fixture = (scenario: Scenario, rules: Rules): Headless => {
add(components, b.id)
}
for (const p of scenario.roads) add({ "Town/Tile": { x: p.x, y: p.y, size: 1 }, "Town/Road": {}, ...(p.paved ? { "Town/Paved": {} } : {}) })
+ for (const p of scenario.parks ?? []) add({ "Town/Tile": { x: p.x, y: p.y, size: 1 }, "Town/Park": { ground: p.ground, prop: p.prop } })
+ for (const tile of scenario.ruins ?? []) add({ "Town/Tile": tile, "Town/Ruin": { cause: "burnt" } })
const grid = scenarioGrid(scenario, rules).value()
for (const [i, l] of scenario.land.entries()) {
if (ownerAt(grid, l.tile.x, l.tile.y) !== -1 - i) continue
@@ -49,5 +53,9 @@ export const fixture = (scenario: Scenario, rules: Rules): Headless => {
return town
}
-export const pushBuild = (town: Headless, action: BuildAction) => town.edit(action.kind === "home" ? { type: "homes", cells: [action.tile] } : { type: "building", kind: action.kind, cell: action.tile, open: false })
+export const pushBuild = (town: Headless, action: BuildAction) => {
+ if (action.kind === "ground") town.edit({ type: "ground", ground: action.ground, cells: [action.tile] })
+ else if (action.kind === "prop") town.edit({ type: "prop", prop: action.prop, cell: action.tile })
+ else town.edit(action.kind === "home" ? { type: "homes", cells: [action.tile] } : { type: "building", kind: action.kind, cell: action.tile, open: false })
+}
export const component = (snapshot: Snapshot, id: number, name: string): any => snapshot.entities.find((e) => e.id === id)?.components[name]