A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Economy pushes back on sprawl: meals by resident, steeper administration, taxes that empty homes, a market for topping up; a sprawl bot
Claude9331149aeadc
diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex d3da74f..66b0bfe 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -51,15 +51,26 @@ six months.winter when fields do not grow, fisheries catch half as much, and homeseat faster;- *administration*: the town hall costs more per home the more homes- there are, so a big town of poor homes cannot pay its way;+ there are; by about 80 homes another cottage costs about what it pays+ (the build tooltip says what a home would bring in after it), so a+ town grows past there by finer homes, which hold two or three times the+ people for the same cost;+ - *food* is eaten by the resident: a walker's visit feeds a cottage one+ fish or loaf, a citizens' home two, a townhouse three;- *the crown* asks for goods the town makes, more as the term goes on;sending them pays, and an unanswered request is a fine and a snub thetown remembers;- - *the market*: prices fall the more the town sells and rise the more- it buys; stone and ore run out;+ - *the market*: prices fall the more the town sells and rise, three+ times as fast, the more it buys; a dear price calms only slowly, so+ traders top up a shortfall but a town that lives on bought food pays+ more for it every minute; stone and ore run out;- *approval*, from -100 to 100, follows needs met, taxes, unpaid wages,snubs from the crown, and hungry winters, and decides how many people- each home holds. Taxes above 125% also leave a *grudge* that builds+ each home holds. Taxes above 100% also send residents away directly,+ settlers sooner than citizens (a cottage holds 80% at 150% and half at+ 200%), so the most a rate brings in comes before the top of the slider:+ the town panel shows what each rate would bring in once the homes+ settle. Taxes above 125% also leave a *grudge* that buildsfor as long as they stay high and fades over ten minutes or so, so aterm of squeezing cannot be undone by cutting taxes at the end.- **The levers**, each a slider: taxes per tier (50% to 200%); for eachdiff --git a/scripts/balance.ts b/scripts/balance.tsindex 94c907b..3f0eed8 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -6,7 +6,7 @@ import { resolveRules } from "../src/rules/config.ts"** node scripts/balance.ts 5 seeds, a medium fair town, a 60-minute term* node scripts/balance.ts --size large --term 90 --land harsh- * node scripts/balance.ts --bot greedy sensible (default), crowded, uncovered, greedy, or idle+ * node scripts/balance.ts --bot greedy sensible (default), crowded, uncovered, greedy, sprawl, or idle* node scripts/balance.ts --versus crowded the bot against another on the same seeds, side by side* node scripts/balance.ts --seeds 10 --from 10 seeds 10 to 19 (to split a sweep across processes)* node scripts/balance.ts --set crown.fine=2 --set kinds.fishery.recipe.seconds=3@@ -22,7 +22,14 @@ import { resolveRules } from "../src/rules/config.ts"* - idle: founds the basics, then leaves the town to itself;* - crowded: the sensible mayor, but homes packed in beside the industry,* and no parks or paving;- * - uncovered: the sensible mayor, but no fire watch, healer, or watch house.+ * - uncovered: the sensible mayor, but no fire watch, healer, or watch house;+ * - sprawl: the quick loop the economy should not reward: taxes as high as+ * the town will stand (200% while it approves, never so low it is+ * pleased), cottages everywhere the coins allow, fish caught or bought to+ * keep them fed, and never a bakery, a chapel, or a finer home.+ *+ * Every mayor but sprawl stops adding cottages for income once the build+ * tooltip says another would bring in little after administration.** The sensible mayor also keeps homes off squalid streets and dirty* workshops a little way from homes, lays out parks and paves streets where@@ -52,6 +59,7 @@ 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"+import { capacity, taxOf } from "../src/rules/households.ts"// ── Options ───────────────────────────────────────────────────────────────@@ -65,8 +73,8 @@ const from = Number(option("from", "0"))const size = option("size", "medium") as CharterValue["size"]const land = option("land", "fair") as CharterValue["land"]const term = Number(option("term", "60"))-type Bot = "sensible" | "greedy" | "idle" | "crowded" | "uncovered"-const bots: ReadonlyArray<Bot> = ["sensible", "greedy", "idle", "crowded", "uncovered"]+type Bot = "sensible" | "greedy" | "idle" | "crowded" | "uncovered" | "sprawl"+const bots: ReadonlyArray<Bot> = ["sensible", "greedy", "idle", "crowded", "uncovered", "sprawl"]/** `--versus <bot>`: run another bot on the same seeds and compare. */const versus = option("versus", "") as Bot | ""let bot = option("bot", "sensible") as Bot@@ -77,7 +85,7 @@ const snapshotAt = Number(option("snapshot", "0"))const out = option("out", "snapshots")if (!sizeIds.includes(size) || !landIds.includes(land) || !bots.includes(bot) || (versus !== "" && !bots.includes(versus))) throw new Error("Unknown --size, --land, --bot, or --versus")/** Mayors who look after the neighbourhood: parks, paving, homes away from industry. */-const zoned = () => bot !== "crowded" && bot !== "idle"+const zoned = () => bot !== "crowded" && bot !== "idle" && bot !== "sprawl"/** Mayors who keep fire watches, healers, and watch houses. */const covered = () => bot !== "uncovered" && bot !== "idle"/** Mayors who run the town as the sensible one does (taxes, trade, the crown). */@@ -410,6 +418,16 @@ const roadToward = (w: World, kind: Kind | null, limit = 16): Array<Point> => {return []}+/**+ * What another cottage would bring in after what it adds to administration (the build tooltip's sum), if it+ * were fed as often as the town's homes are now (`fed`, the share of them fed).+ */+const cottageWorth = (w: World, fed: number) => {+ const cottage = { tier: 1 as const, food: 1, bread: 0, cloth: 0, faith: 0, residents: home.tiers[1].residents }+ const cost = (n: number) => n * (rules.admin.perHome + n / rules.admin.growth)+ return fed * taxOf({ ...cottage, residents: capacity(cottage, w.mood.approval, 0, rules, w.policy.settlers) }, w.policy, rules) - (cost(w.homes.length + 1) - cost(w.homes.length))+}+/** What the bot wants next, in order: the first it can do, it does. */const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: boolean }> => {const homes = w.homes.length@@ -433,7 +451,7 @@ const plan = (w: World): ReadonlyArray<{ readonly kind: KindId; readonly when: b{ kind: "fishery", when: w.census.food! < w.homes.length * 0.6 && count(w, "fishery") < Math.max(2, 1 + Math.floor(homes / 7) - 2 * count(w, "bakery")) },{ kind: "market", when: count(w, "market") < 1 + Math.floor(homes / 20) && w.census.food! < w.homes.length * 0.7 }]- if (bot === "idle") return basics+ if (bot === "idle" || bot === "sprawl") return basics// The citizens' chains, in proportion to the homes: a bakery bakes for about// 16 homes and needs a mill, and a mill most of a farm; a weaver weaves for// about 14 homes from one sheep farm's wool. Upstream first, so what a@@ -478,6 +496,18 @@ const decide = (w: World): ReadonlyArray<Edit> => {for (const g of goodIds) if (!w.policy.sells.includes(g)) edits.push({ type: "trade", good: g, mode: "sell" })}const fed = w.homes.length > 0 ? w.census.food! / w.homes.length : 1+ if (bot === "sprawl") {+ const rate = w.mood.approval > 25 ? 200 : w.mood.approval > 10 ? 175 : w.mood.approval > 0 ? 150 : w.mood.approval > -20 ? 125 : 100+ if (w.policy.settlers !== rate) edits.push({ type: "tax", tier: "settlers", rate }, { type: "tax", tier: "citizens", rate })+ if (w.policy.reserve !== 30) edits.push({ type: "reserve", amount: 30 })+ // Fish bought whenever the homes go short, planks when building runs short; the crown answered when it can be.+ for (const [g, low, enough] of [["fish", fed < 0.8 ? 30 : -1, 30], ["planks", 8, 20]] as const) {+ const buying = w.policy.buys.includes(g)+ if (!buying && w.stock[g] < low && w.coins > 60) edits.push({ type: "trade", good: g, mode: "buy" })+ if (buying && (w.stock[g] >= enough || w.coins < 30)) edits.push({ type: "trade", good: g, mode: "none" })+ }+ if (w.crown.open && w.stock[w.crown.good] >= w.crown.amount) edits.push({ type: "deliver" })+ }if (sensible()) {// Taxes follow the town's mood; once every other goal is met, they come down to win it over.const goals = goalsOf(w.charter, {@@ -548,7 +578,8 @@ 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.1 && w.homes.length < Math.ceil(goal / home.tiers[1].residents))+ const sprawling = bot === "sprawl" && fed >= 0.5 && w.stock.planks >= 4+ const short = sprawling || 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) && cottageWorth(w, fed) > 2)if (short && affordable(w, { coins: home.cost.coins * 4, materials: { planks: 4 } })) {const spots = homeSpots(w, 4)if (spots.length > 0) return [...edits, { type: "homes", cells: spots }]diff --git a/src/content.ts b/src/content.tsindex 024e73e..3991b6d 100644--- a/src/content.ts+++ b/src/content.ts@@ -416,7 +416,22 @@ export const home = {*/street: { room: 12, roomLeast: 0.5, tax: 40, taxMost: 0.25 },/** A settlers' cottage with bread on the table pays this much more: bread is worth baking before anyone is a citizen. */- breadBonus: 0.5+ breadBonus: 0.5,+ /**+ * A walker's visit feeds a home one fish or loaf for every `perMeal`+ * residents (rounded up): a cottage one, a citizens' home two, a+ * townhouse three. Food demand grows with the people, not the roofs.+ */+ perMeal: 4,+ /**+ * Taxes above 100% drive people away directly, besides what they do to+ * approval: at x = (rate − 100) / 100, a home holds 1 − `linear`·x −+ * `square`·x² of its residents (settlers: 80% at 150%, half at 200%);+ * citizens and burghers mind `citizens` as much. So squeezing harder+ * empties the homes it squeezes, and the most a rate can bring in+ * comes well before the top of the slider.+ */+ taxFlight: { linear: 0.3, square: 0.2, citizens: 0.6 }}/** What a tier's homes are called, and what its residents are. */@@ -655,10 +670,13 @@ export const WINTER_WARNING = ticks(60)/*** Running a town costs more the bigger it gets: the town hall's* administration costs `perHome` coins a minute a home, and a further- * (homes / `growth`) a home, so a large town of poor homes cannot pay- * its way.+ * (homes / `growth`) a home. Each more home costs `perHome` + 2·homes /+ * `growth`: about 7 coins a minute at 80 homes, what a fed cottage pays,+ * so past there a town grows by finer homes, not more of them. It is+ * reckoned by the home, so a townhouse of twelve costs no more than a+ * cottage of four.*/-export const admin = { perHome: 0.4, growth: 120 }+export const admin = { perHome: 0.5, growth: 24 }/*** Approval, -100 → +100: where the town's mood is heading, and how fast it@@ -715,10 +733,13 @@ export const crown = {/*** The market: each good's price moves with what the town trades. Selling- * drives it down, buying up; it drifts back by a tenth of the gap every- * collection. Buying costs half again the price.+ * drives it down `perUnit` points a unit, buying up `perBought`. A cheap+ * price drifts back by a tenth of the gap every collection, a dear one by+ * only 1/`calms` of it: traders top up a shortfall, but a town that lives+ * on bought food pays more for it every minute. Buying costs half again+ * the price.*/-export const market = { floor: 30, ceiling: 250, perUnit: 1, markup: 1.5 }+export const market = { floor: 30, ceiling: 250, perUnit: 1, perBought: 3, markup: 1.5, calms: 30 }/** A paused building pays this share of its upkeep. */export const PAUSED_UPKEEP = 0.25diff --git a/src/factory.css b/src/factory.cssindex dd66815..ee10eb0 100644--- a/src/factory.css+++ b/src/factory.css@@ -217,6 +217,7 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel .effect { margin: -2px 0 4px; font-size: 11px; color: #8a938c; text-align: right; }.panel .effect.up { color: #4f8a3e; }.panel .effect.down { color: #b04a39; }+.panel .effect.outlook { text-align: left; }.panel .need { display: grid; grid-template-columns: 7.5ch 1fr 7ch; align-items: center; gap: 10px; padding: 4px 0; }.panel .need .track { height: 8px; background: #e6e9e2; border-radius: 4px; overflow: hidden; }.panel .need .fill { display: block; height: 100%; background: #6e8f36; border-radius: 4px; }diff --git a/src/host.ts b/src/host.tsindex 53cabb2..19bd074 100644--- a/src/host.ts+++ b/src/host.ts@@ -907,7 +907,7 @@ export const createHost = async (const treasury = section("treasury","treasury",- "Coins a minute. Taxes come only from homes that are fed, in proportion to the needs they have met. Administration grows faster than the town. Three minutes in debt and the town is bankrupt."+ "Coins a minute. Taxes come only from homes that are fed, in proportion to the needs they have met. Administration is reckoned by the home and grows faster than the town: in a large town another cottage costs about what it pays, while a citizens' home or a townhouse holds two or three times the people for the same cost. Three minutes in debt and the town is bankrupt.")const taxes = row(treasury, "taxes", "taxes")const supplied = row(treasury, "if every home were supplied", "homes")@@ -926,7 +926,7 @@ export const createHost = async (const levers = section("tax rates","taxes",- `Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are. Above ${moodRules.grudge.above}% the town also keeps a grudge that outlasts the rate: cutting taxes at the end does not undo a term of squeezing.`+ `Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are. Above 100% some residents also move away, settlers sooner than citizens, so a higher rate does not always bring in more: under each rate is what the homes would pay at each step once they settle there. Above ${moodRules.grudge.above}% the town also keeps a grudge that outlasts the rate: cutting taxes at the end does not undo a term of squeezing.`)for (const tier of ["settlers", "citizens"] as const) {const line = el("div", "row lever")@@ -940,7 +940,9 @@ export const createHost = async (rate.input.title = "Drag to set the rate; double-click for the usual 100%"rate.input.ondblclick = () => ui.edits.push({ type: "tax", tier, rate: 100 })const effect = el("p", "effect")- levers.append(line, rate.input, effect)+ const outlook = el("p", "effect outlook")+ outlook.title = "Taxes a minute from every home if this rate stayed there and the homes settled: residents move away above 100%, and approval follows the rate"+ levers.append(line, rate.input, effect, outlook)live.push(() => {const now = ui.stats?.policy[tier] ?? 100rate.sync(now)@@ -949,6 +951,13 @@ export const createHost = async (const grudge = now > moodRules.grudge.above ? " · a grudge builds while it stays this high, and fades slowly" : ""effect.textContent = (sway === 0 ? "the usual rate" : `${signed(sway)} approval`) + grudgeeffect.className = `effect ${sway > 0 ? "up" : sway < 0 ? "down" : ""}`+ const steps = ui.stats?.taxOutlook[tier] ?? []+ const best = steps.reduce<{ rate: number; taxes: number } | null>((b, o) => (b === null || o.taxes > b.taxes ? o : b), null)+ const text = steps.length === 0 || best === null+ ? ""+ : `taxes a minute, once settled: ${steps.map((o) => `${o.rate}% ${o.taxes}`).join(" · ")} · most at ${best.rate}%`+ if (outlook.textContent !== text) outlook.textContent = text+ outlook.style.display = text ? "" : "none"})}panel.append(levers)@@ -968,7 +977,7 @@ export const createHost = async (const needs = section("homes supplied","homes",- "A hungry home pays no taxes. Settlers need food (fish, smoked fish, or bread) from a market, and a cottage with bread besides pays half again; citizens and burghers need bread, cloth, and faith. Cloth is only brought to streets with desirability 5 or more. Fish rots in about three minutes and bread in five; a granary keeps them five times as long."+ "A hungry home pays no taxes. Settlers need food (fish, smoked fish, or bread) from a market, and a cottage with bread besides pays half again; a visit feeds a home a fish or a loaf for every four residents, so a citizens' home eats twice what a cottage does and a townhouse three times; citizens and burghers need bread, cloth, and faith. Cloth is only brought to streets with desirability 5 or more. Fish rots in about three minutes and bread in five; a granary keeps them five times as long.")const needIcons: Readonly<Record<"food" | "bread" | "cloth" | "faith", IconName>> = {food: "fish",@@ -1007,7 +1016,7 @@ export const createHost = async (const store = section("goods and trade","trade",- "Traders call every few seconds. Drag a good's slider left to sell it beyond what the town keeps, right to buy it up to that (at half again the price), the further the more each call; the middle neither sells nor buys. Prices fall as the town sells and rise as it buys."+ "Traders call every few seconds. Drag a good's slider left to sell it beyond what the town keeps, right to buy it up to that (at half again the price), the further the more each call; the middle neither sells nor buys. Prices fall as the town sells and rise, three times as fast, as it buys; a dear price calms only slowly, so buying tops up a shortfall but a town fed on bought food pays more every minute.")const reserveLine = el("div", "row lever")const reserveValue = el("span", "rate")diff --git a/src/present.ts b/src/present.tsindex 24dfacf..15ee10a 100644--- a/src/present.ts+++ b/src/present.ts@@ -86,11 +86,12 @@ import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, seasonimport { Townsfolk } from "./townsfolk.ts"import { emptyPreview, type Alert as Notice, type HitBox, type Legend, type Line, type View } from "./ui.ts"import { blockers as blockersOf, streetAdvice, type InTown, type Served, type Street } from "./rules/explain.ts"-import { breadBonus, streetTax, suppliedTaxOf } from "./rules/households.ts"+import { breadBonus, moreAdmin, streetTax, suppliedTaxOf, taxOutlook, type TaxedHome } from "./rules/households.ts"+import { approvalTarget } from "./rules/approval.ts"import { salvageOf, salvageText } from "./rules/salvage.ts"import { rockBlocks, type RockPart } from "./render3d/rock-blocks.ts"import { GUIDE_QUIET, guideDone, guideStep, guideSteps, type GuideFacts, type GuideFocus } from "./rules/guide.ts"-import { ticks } from "./content.ts"+import { TAX_STEPS, ticks } from "./content.ts"const cellAt = (at: Point): Point => {return { x: Math.floor(at.x), y: Math.floor(at.y) }@@ -416,6 +417,21 @@ export const Interact = Game.System(return hit ?? parkAt.get(key(Math.floor(at.x), Math.floor(at.y)))?.entity.id ?? null}const parkText = (p: ParkValue) => `desirability ${signed(p.value)} out to ${p.reach} cells`+ /**+ * What new cottages would bring in, fed, at the settlers' rate on their streets, less what they add to the+ * town hall's administration (see `moreAdmin`): the sum that turns once a town is large.+ */+ const homesWorth = (at: ReadonlyArray<Point>) => {+ if (at.length === 0) return ""+ const n = at.length, standing = houses.filter((row) => !row.data.closed.present).length+ const fed = { tier: 1 as Tier, food: 1, bread: 0, cloth: 0, faith: 0, residents: home.tiers[1].residents }+ const pays = at.reduce((sum, c) => {+ const d = appealAt(cells, c.x, c.y)+ return sum + taxOf({ ...fed, residents: capacity(fed, approval, d, undefined, rates.settlers) }, rates, undefined, d)+ }, 0)+ const worth = Math.round(pays - moreAdmin(standing, n))+ return ` · ${n === 1 ? "this home" : "these homes"}: ${signed(worth)} coins a minute after administration, once fed${worth <= 0 ? " · past what the town hall can run cheaply: finer homes pay better than more of them" : ""}`+ }const hits: Array<HitBox> = [...buildings.map(({ entity, data }) => {@@ -538,7 +554,7 @@ export const Interact = Game.System(}if (ui.tool === "home" && cell && inside(cell.x, cell.y)) {rangeFrom({ ...(ui.dragFrom ?? cell), size: 1 }, COMMUTE + 1, `residents walk to work within ${COMMUTE} road cells`)- preview.tooltip = `homes · ${costText(home.cost)} each · along a road · ${preview.rangeNote ?? "touch a road and residents walk to work within " + COMMUTE + " road cells"}`+ preview.tooltip = `homes · ${costText(home.cost)} each · along a road${homesWorth(preview.ghosts.map((g) => g.cell))} · ${preview.rangeNote ?? "touch a road and residents walk to work within " + COMMUTE + " road cells"}`}if (ui.tool === "road" && cell) preview.tooltip = `road · ${ROAD_COST} coins a cell · buildings need one at the middle of a side`if (ui.dragFrom && cell) {@@ -547,7 +563,7 @@ export const Interact = Game.System(ui.tool === "road"? `${counted(n, "road cell")} · ${costText({ coins: n * ROAD_COST, materials: {} })}`: ui.tool === "home"- ? `${counted(n, "home")} · ${costText(times(home.cost, n))}`+ ? `${counted(n, "home")} · ${costText(times(home.cost, n))}${homesWorth(preview.ghosts.map((g) => g.cell))}`: `pave ${counted(n, "cell")} · ${costText({ coins: n * PAVE_COST.coins, materials: { stone: n * PAVE_COST.stone } })}`}} else if (ui.tool === "ground" && cell) {@@ -808,7 +824,8 @@ export const Interact = Game.System(const condition = maybe(row.data.condition)const town = inTown()const served = servedAt(tile)- const cap = capacity(h, approval, desirability)+ const rate = h.tier === 1 ? rates.settlers : rates.citizens+ const cap = capacity(h, approval, desirability, undefined, rate)const whyFewer =cap >= tier.residents? undefined@@ -818,10 +835,11 @@ export const Interact = Game.System(? "fewer while the town disapproves of its mayor": desirability < 0? `fewer on a street at ${signed(desirability)}: ${streetAdvice(street)}`- : "fewer until every need is met"+ : rate > 100 && capacity(h, approval, desirability) > cap+ ? `fewer while ${tier.title} are taxed at ${rate}%: some move away`+ : "fewer until every need is met"const taxLine = (() => {const factors: Array<string> = []- const rate = h.tier === 1 ? rates.settlers : rates.citizensif (rate !== 100) factors.push(`taxed at ${rate}%`)const st = Math.round((streetTax(desirability) - 1) * 100)if (st !== 0) factors.push(`street ${signed(st)}%`)@@ -1149,9 +1167,21 @@ export const Interact = Game.System(const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.adminconst mood = resources.mood.get()const crown = resources.crown.get()+ // What the homes would pay at each step of each tier's rate, once settled there (see `taxOutlook`).+ const taxed: Array<TaxedHome> = []+ for (const { data } of houses) {+ if (data.site.present || data.rising.present || data.burning.present || data.closed.present) continue+ const tile = data.tile.get()+ taxed.push({ ...data.house.get(), desirability: appealAt(cells, tile.x, tile.y), paying: true })+ }const f = resources.fate.get()const pantry = resources.pantry.get()const season = seasonAt(Math.min(Math.max(0, t), termTicks(charter) - 1), charter)+ const approvalAt = (r: { readonly settlers: number; readonly citizens: number }, memory: number) =>+ approvalTarget(taxed, r, coins, crown.snubs.length, season.winter, undefined, memory).target+ const outlookOf = (tier: "settlers" | "citizens") => taxed.some((h) => (h.tier === 1) === (tier === "settlers"))+ ? TAX_STEPS.map((rate) => ({ rate, taxes: Math.round(taxOutlook(taxed, rates, tier, rate, approvalAt)) }))+ : []const seconds = (steps: number) => Math.max(0, Math.ceil(steps / 60))const danger = (since: number, minutes: number) => (since < 0 ? null : seconds(since + minutes * 3600 - t))// The winter after the coming one, for the almanac.@@ -1256,6 +1286,7 @@ export const Interact = Game.System(coins,taxes: ledger.taxes,suppliedTaxes: Math.round(suppliedTaxes),+ taxOutlook: { settlers: outlookOf("settlers"), citizens: outlookOf("citizens") },trade: ledger.trade,upkeep: ledger.upkeep,admin: ledger.admin,diff --git a/src/rules/config.ts b/src/rules/config.tsindex 735493b..7c7142d 100644--- a/src/rules/config.ts+++ b/src/rules/config.ts@@ -49,9 +49,9 @@ export const resolveRules = (patches: ReadonlyArray<RulePatch> = []): Rules => {// Structural timing and identifier changes are outside numeric economy experiments.if (parts[0] === "transport" || ["size", "stories", "bays"].includes(key)) throw new Error(`Structural rule cannot be patched: ${path}`)if (["stepSeconds", "ledgerTicks", "spoilTicks", "yearsPerTerm", "staffTicks", "riskTicks", "spreadTicks", "growTicks"].includes(parts[0]!)) throw new Error(`Structural rule cannot be patched: ${path}`)- if ((key === "seconds" || key === "growth" || key === "wear" || key === "every" || key === "lasts") && value === 0) throw new Error(`Rule must be positive: ${path}`)+ if ((key === "seconds" || key === "growth" || key === "wear" || key === "every" || key === "lasts" || key === "perMeal" || key === "calms") && value === 0) throw new Error(`Rule must be positive: ${path}`)if ((path.startsWith("home.lasts.") || path.startsWith("spoils.")) && value === 0) throw new Error(`Rule must be positive: ${path}`)- if ((["workers", "batch", "inputs", "cap", "carriers", "range", "residents", "settle"].includes(key) || path.includes(".cost.")) && !Number.isInteger(value)) throw new Error(`Rule must be an integer: ${path}`)+ if ((["workers", "batch", "inputs", "cap", "carriers", "range", "residents", "settle", "perMeal"].includes(key) || path.includes(".cost.")) && !Number.isInteger(value)) throw new Error(`Rule must be an integer: ${path}`)if (path === "apprentice" && value > 1) throw new Error("Apprentice pace must be at most one")target[key] = value}diff --git a/src/rules/households.ts b/src/rules/households.tsindex 12c293c..2bbb3f2 100644--- a/src/rules/households.ts+++ b/src/rules/households.ts@@ -21,7 +21,7 @@ export interface Rates {readonly settlers: numberreadonly citizens: number}-const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)+export const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)/** How approval (-100 → 100) sits with a home: a third as many residents at its worst, half again at its best. */export const appealOf = (approval: number): number => (approval < 0 ? 1 + approval / 150 : 1 + approval / 200)@@ -33,16 +33,27 @@ export const streetRoom = (desirability: number, rules: Rules = shippedRules): nexport const streetTax = (desirability: number, rules: Rules = shippedRules): number =>Math.max(1 - rules.home.street.taxMost, Math.min(1 + rules.home.street.taxMost, 1 + desirability / rules.home.street.tax))+/**+ * The share of its residents a home keeps at a tax rate: all at 100% and+ * below; above it fewer, faster the higher it goes (see `home.taxFlight`),+ * settlers more than citizens. This is besides what taxes do to approval.+ */+export const taxRoom = (rate: number, tier: Tier, rules: Rules = shippedRules): number => {+ const x = Math.max(0, rate - 100) / 100, f = rules.home.taxFlight+ return Math.max(0, 1 - (tier === 1 ? 1 : f.citizens) * (f.linear * x + f.square * x * x))+}+/*** Residents a home holds at its tier and satisfaction: half when nothing is* met, all when everything is; fewer when the town disapproves of its* mayor, and up to all of them when it approves, needs or not. A poor* street (desirability below 0) holds fewer, point by point (see- * `streetRoom`): a cottage beside a quarry loses a resident at once.+ * `streetRoom`): a cottage beside a quarry loses a resident at once. Taxes+ * above 100% (`rate`, its tier's) send some away (see `taxRoom`).*/-export const capacity = (h: Needs, approval: number, desirability = 0, rules: Rules = shippedRules): number => {+export const capacity = (h: Needs, approval: number, desirability = 0, rules: Rules = shippedRules, rate = 100): number => {const max = rules.home.tiers[h.tier].residents- return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h, h.tier, rules)) * appealOf(approval) * streetRoom(desirability, rules))))+ return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h, h.tier, rules)) * appealOf(approval) * streetRoom(desirability, rules) * taxRoom(rate, h.tier, rules))))}/** Whether every risk meter of a home is kept low: a service walker of each kind passes it. */@@ -66,6 +77,11 @@ export const tierFor = (h: Needs, desirability: number, r: { readonly fire: numb/** Coins a minute the town hall's administration costs for `homes` homes. */export const adminOf = (homes: number, rules: Rules = shippedRules): number => Math.round(homes * (rules.admin.perHome + homes / rules.admin.growth))+/** What `more` homes add to the administration of a town of `homes`, coins a minute (not rounded). */+export const moreAdmin = (homes: number, more = 1, rules: Rules = shippedRules): number => {+ const cost = (n: number) => n * (rules.admin.perHome + n / rules.admin.growth)+ return cost(homes + more) - cost(homes)+}/** What traders pay for one of a good now, and what they ask for one. */export const priceOf = (good: GoodId, percent: number, rules: Rules = shippedRules) => (rules.goods[good].price * percent) / 100@@ -102,26 +118,46 @@ export const ageNeeds = <T extends Needs & { readonly clock: number }>(h: T, eatexport const wantsCitizenGoods = (house: Needs, desirability: number, rules: Rules = shippedRules) =>house.tier >= 2 || desirability >= rules.home.tiers[2].appeal+/** Fish or loaves a home eats at a visit: one for every `home.perMeal` residents, rounded up, and at least one. */+export const mealsOf = (h: { readonly residents: number }, rules: Rules = shippedRules): number => Math.max(1, Math.ceil(h.residents / rules.home.perMeal))+/**- * What a walker hands a home from its basket, one thing to eat at most:- * citizens (and settlers on a street fit for citizens) take bread first;- * other settlers eat fish, or bread when there is no fish, and take a loaf- * besides when their bread has run out, since a cottage with bread pays- * more (see `breadBonus`), but only from the basket's surplus (more than- * half of it left), so the citizens further along the walk are not left- * without. Cloth goes only where citizens could live.+ * What a walker hands a home from its basket: a meal for its residents+ * (see `mealsOf`), of one food or, when the basket runs short, of two.+ * Citizens (and settlers on a street fit for citizens) take bread first,+ * and fish for what bread is missing; other settlers eat fish, or bread+ * when there is no fish, and take loaves besides when their bread has run+ * out, since a cottage with bread pays more (see `breadBonus`), but only+ * from the basket's surplus (more than half of it left), so the citizens+ * further along the walk are not left without. A home fed only part of+ * its meal is fed for that part of the time. Cloth goes only where+ * citizens could live.*/-export const serveGoods = <T extends Needs>(house: T, available: Readonly<Record<GoodId, number>>, rules: Rules = shippedRules, desirability = 0) => {+export const serveGoods = <T extends Needs & { readonly residents: number }>(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)+ const citizens = wantsCitizenGoods(h, desirability, rules), meals = mealsOf(h, rules)+ /** Up to `n` from the basket, of these goods in turn: how many it took. */+ const take = (goods: ReadonlyArray<GoodId>, n: number) => {+ let got = 0+ for (const g of goods) {+ const k = Math.min(n - got, basket[g])+ basket[g] -= k; got += k+ }+ return got+ }+ const lasts = (need: Need, part: number) => Math.round(rules.home.lasts[need] * part / meals)let eaten = 0+ const fed = (loaves: number, fish: number) => {+ h.food = lasts("food", loaves + fish); if (loaves > 0) h.bread = lasts("bread", loaves); eaten += loaves + fish+ }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+ const loaves = take(["bread"], meals)+ fed(loaves, take(["fish", "smoked"], meals - loaves))} 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+ const fish = take(["fish", "smoked"], meals)+ fed(take(["bread"], meals - fish), fish)} else if ((lowNeed(h.food, "food", rules) || (!citizens && lowNeed(h.bread, "bread", rules) && basket.bread > rules.transport.basket / 2)) && basket.bread > 0) {- basket.bread -= 1; h.food = rules.home.lasts.food; h.bread = rules.home.lasts.bread; eaten += 1+ fed(take(["bread"], meals), 0)}if (citizens && lowNeed(h.cloth, "cloth", rules) && basket.cloth > 0) {basket.cloth -= 1; h.cloth = rules.home.lasts.cloth@@ -129,6 +165,27 @@ export const serveGoods = <T extends Needs>(house: T, available: Readonly<Recordreturn { house: h, basket, eaten }}+/**+ * What the town's homes would pay a minute, once settled, if `tier`'s rate+ * were `rate` and stayed there: their residents then are what that rate+ * and the approval it brings let them hold (see `capacity`), with their+ * needs as they are now. Approval is its target at that rate, with the+ * grudge a rate above `mood.grudge.above` builds up to in the end.+ */+export interface TaxedHome extends Needs { readonly residents: number; readonly desirability: number; readonly paying: boolean }+export const taxOutlook = (homes: ReadonlyArray<TaxedHome>, rates: Rates, tier: "settlers" | "citizens", rate: number,+ approvalAt: (rates: Rates, memory: number) => number, rules: Rules = shippedRules): number => {+ const policy = { ...rates, [tier]: rate }+ const people = homes.reduce((n, h) => n + h.residents, 0)+ const mean = people > 0 ? homes.reduce((n, h) => n + h.residents * rateOf(policy, h.tier), 0) / people : rate+ const approval = approvalAt(policy, mean > rules.mood.grudge.above ? rules.mood.grudge.most : 0)+ return homes.reduce((sum, h) => {+ if (!h.paying) return sum+ const residents = capacity(h, approval, h.desirability, rules, rateOf(policy, h.tier))+ return sum + taxOf({ ...h, residents }, policy, rules, h.desirability)+ }, 0)+}+/** Actual collection rounding, not rounded ledger display values. */export const baseCollection = (taxes: number, upkeep: number, homes: number, rules: Rules = shippedRules) => {const share = rules.ledgerTicks * rules.stepSeconds / 60diff --git a/src/rules/trade.ts b/src/rules/trade.tsindex 42353b3..845e445 100644--- a/src/rules/trade.ts+++ b/src/rules/trade.ts@@ -29,7 +29,7 @@ export const tradeCollection = (initial: ReadonlyArray<Shelf>, policy: TradePolilet wanted = Math.min(load, policy.reserve - held, Math.floor(coins / ask))if (wanted > 0) {coins -= wanted * ask; traded -= wanted * ask- prices[good] = Math.min(rules.market.ceiling, prices[good] + wanted * rules.market.perUnit)+ prices[good] = Math.min(rules.market.ceiling, prices[good] + wanted * rules.market.perBought)for (const inv of [...stores].sort((a, b) => a.stock[good] - b.stock[good])) {if (wanted <= 0) breakconst put = inv.accepts.includes(good) ? Math.min(wanted, inv.cap - inv.stock[good]) : 0@@ -39,8 +39,9 @@ export const tradeCollection = (initial: ReadonlyArray<Shelf>, policy: TradePoliif (wanted > 0) { coins += wanted * ask; traded += wanted * ask }}}+ // A cheap price recovers by a tenth of the gap; a dear one calms more slowly.const gap = 100 - prices[good]- prices[good] += gap === 0 ? 0 : Math.sign(gap) * Math.max(1, Math.round(Math.abs(gap) / 10))+ prices[good] += gap === 0 ? 0 : Math.sign(gap) * Math.max(1, Math.round(Math.abs(gap) / (gap > 0 ? 10 : rules.market.calms)))}return { stores, prices, coins, traded }}diff --git a/src/sim/town.ts b/src/sim/town.tsindex 787bdeb..dd8c52b 100644--- a/src/sim/town.ts+++ b/src/sim/town.ts@@ -10,13 +10,14 @@ import { amounts, goodIds, type GoodId } from "../content.ts"import { Appeal, Building, Burning, Census, Charter, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, maybe } from "../schema.ts"import { connected, elapsed, seasonAt } from "./shared.ts"-import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, taxOf, tierFor } from "../rules/households.ts"+import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, rateOf, taxOf, tierFor } from "../rules/households.ts"export { adminOf, appealOf, askOf, capacity, kept, met, priceOf, satisfaction, taxOf, tierFor, type Rates } from "../rules/households.ts"/*** Needs wear off, food faster in winter. Every so often a home settles* into its tier (see `tierFor`) and one resident moves in or out towards- * what the home holds (half as many while it is sick). Everyone leaves a+ * what the home holds (half as many while it is sick, fewer under heavy+ * taxes). Everyone leaves a* home with no road, or on fire.*/export const Households = Game.System(@@ -40,7 +41,8 @@ export const Households = Game.System(mood: Game.System.readResource(Mood),appeal: Game.System.readResource(Appeal),time: Game.System.readResource(Time),- charter: Game.System.readResource(Charter)+ charter: Game.System.readResource(Charter),+ policy: Game.System.readResource(Policy)},services: { rules: Game.System.service(Rules) }},@@ -50,6 +52,7 @@ export const Households = Game.System(const grid = resources.grid.get()const approval = resources.mood.get().approval+ const policy = resources.policy.get()const cells = resources.appeal.get().cellsconst t = elapsed(resources.time.get(), resources.charter.get())// In winter a meal lasts two thirds as long.@@ -63,7 +66,7 @@ export const Households = Game.System(const tile = data.tile.get()const desirability = appealAt(cells, tile.x, tile.y)next.tier = tierFor(next, desirability, maybe(data.risk) ?? { fire: 0, health: 0, order: 0 }, rules)- const well = connected(grid, tile) ? capacity(next, approval, desirability, rules) : 0+ const well = connected(grid, tile) ? capacity(next, approval, desirability, rules, rateOf(policy, next.tier)) : 0const cap = data.sick.present ? Math.floor(well * risk.health.sickly) : wellnext.residents = Math.min(next.residents, home.tiers[next.tier].residents)next.residents += Math.sign(cap - next.residents)diff --git a/src/ui.ts b/src/ui.tsindex f8433d2..3a4eb6c 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -172,6 +172,8 @@ export interface Stats {readonly taxes: number/** What the same homes would pay a minute with every need met: taxes left on the table when it is more. */readonly suppliedTaxes: number+ /** Taxes a minute at each step of a tier's rate, once the homes settle at it; empty while the tier has no homes. */+ readonly taxOutlook: Readonly<Record<"settlers" | "citizens", ReadonlyArray<{ readonly rate: number; readonly taxes: number }>>>readonly trade: numberreadonly upkeep: numberreadonly admin: numberdiff --git a/test/balance-model.test.ts b/test/balance-model.test.tsindex 256b6e7..58e1ecd 100644--- a/test/balance-model.test.ts+++ b/test/balance-model.test.ts@@ -1,7 +1,7 @@import assert from "node:assert/strict"import { test } from "node:test"import { readFileSync, readdirSync } from "node:fs"-import { amounts, kinds } from "../src/content.ts"+import { amounts, goodIds, kinds } from "../src/content.ts"import { resolveRules } from "../src/rules/config.ts"import { analyze } from "../tools/balance/model/analyze.ts"import { project } from "../tools/balance/model/project.ts"@@ -13,7 +13,9 @@ 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 { capacity, moreAdmin, serveGoods, taxOf, taxOutlook, taxRoom, wantsCitizenGoods } from "../src/rules/households.ts"+import { approvalTarget } from "../src/rules/approval.ts"+import { tradeCollection } from "../src/rules/trade.ts"import { assignWorkers } from "../src/rules/production.ts"import { planPatrols } from "../src/rules/patrol.ts"import { scenarioGrid } from "../tools/balance/scenario.ts"@@ -139,7 +141,7 @@ test("the mathematical plan reaches citizens through ordinary game construction"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 rules = resolveRules(), house = { tier: 1 as const, residents: 4, 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)@@ -151,6 +153,60 @@ test("promotion-aware goods preserve cloth and feed an eligible settler bread beassert(fallback.house.food > 0)})+test("a visit feeds a home by its residents: a cottage one meal, a citizens' home two, a townhouse three", () => {+ const rules = resolveRules(), hungry = { food: 0, bread: 0, cloth: 0, faith: 0 }+ const cottage = serveGoods({ ...hungry, tier: 1 as const, residents: 4 }, amounts({ fish: 10 }), rules, 0)+ assert.equal(cottage.eaten, 1)+ assert.equal(cottage.basket.fish, 9)+ const citizens = serveGoods({ ...hungry, tier: 2 as const, residents: 8 }, amounts({ bread: 10, cloth: 2 }), rules, rules.home.tiers[2].appeal)+ assert.equal(citizens.basket.bread, 8)+ assert.equal(citizens.house.food, rules.home.lasts.food)+ const townhouse = serveGoods({ ...hungry, tier: 3 as const, residents: 12 }, amounts({ bread: 10 }), rules, rules.home.tiers[3].appeal)+ assert.equal(townhouse.basket.bread, 7)+ // A basket short of bread makes up the meal with fish, and a basket short of both feeds the home for part of the time.+ const mixed = serveGoods({ ...hungry, tier: 3 as const, residents: 12 }, amounts({ bread: 1, fish: 1 }), rules, rules.home.tiers[3].appeal)+ assert.equal(mixed.eaten, 2)+ assert.equal(mixed.house.food, Math.round(rules.home.lasts.food * 2 / 3))+ assert.equal(mixed.house.bread, Math.round(rules.home.lasts.bread / 3))+})++test("taxes above 100% empty homes directly, settlers sooner, so the most a rate brings in comes before the top", () => {+ const rules = resolveRules(), fed = { tier: 1 as const, residents: 4, food: 1, bread: 0, cloth: 0, faith: 0 }+ assert.equal(taxRoom(100, 1, rules), 1)+ assert.equal(taxRoom(50, 1, rules), 1)+ assert(Math.abs(taxRoom(150, 1, rules) - 0.8) < 1e-9)+ assert(Math.abs(taxRoom(200, 1, rules) - 0.5) < 1e-9)+ assert(taxRoom(200, 2, rules) > taxRoom(200, 1, rules))+ assert.equal(capacity(fed, 0, 0, rules, 200), 2)+ // A town of fed cottages: income rises and then falls with the rate.+ const homes = Array.from({ length: 40 }, () => ({ ...fed, desirability: 0, paying: true }))+ const approvalAt = (r: { settlers: number; citizens: number }, memory: number) => approvalTarget(homes, r, 1000, 0, false, rules, memory).target+ const income = [100, 125, 150, 175, 200].map((rate) => taxOutlook(homes, { settlers: 100, citizens: 100 }, "settlers", rate, approvalAt, rules))+ const best = income.indexOf(Math.max(...income))+ assert(best > 0 && best < income.length - 1, JSON.stringify(income))+ assert(income.at(-1)! < income[best]!)+})++test("administration: each more home costs more, and about what a fed cottage pays near the medium goal", () => {+ const rules = resolveRules()+ assert(moreAdmin(80, 1, rules) > moreAdmin(20, 1, rules) * 2)+ const cottage = taxOf({ tier: 1, residents: 4, food: 1, bread: 0, cloth: 0, faith: 0 }, { settlers: 100, citizens: 100 }, rules)+ assert(moreAdmin(80, 1, rules) > cottage * 0.6 && moreAdmin(80, 1, rules) < cottage * 1.2, `${moreAdmin(80, 1, rules)} vs ${cottage}`)+ assert(moreAdmin(150, 1, rules) > cottage)+})++test("buying drives a price up faster than selling drives it down, and a dear price calms slowly", () => {+ const rules = resolveRules(), prices = amounts(Object.fromEntries(goodIds.map((g) => [g, 100])))+ const shelf = { stock: amounts({ fish: 0 }), accepts: goodIds, cap: 1000 }+ const bought = tradeCollection([shelf], { sells: [], buys: ["fish"], reserve: 12 }, prices, 10000, rules)+ assert.equal(bought.stores[0]!.stock.fish, 12)+ const dear = bought.prices.fish+ assert(dear >= 100 + 12 * rules.market.perBought - 5, String(dear))+ let calm = dear+ for (let i = 0; i < 6; i++) calm = tradeCollection([{ ...shelf, stock: amounts({ fish: 1000 }) }], { sells: [], buys: [], reserve: 0 }, { ...prices, fish: calm }, 0, rules).prices.fish+ assert(calm > 100 + (dear - 100) / 2, `a minute later fish is still dear: ${calm}`)+})+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 }], [diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.tsindex 2e3a568..6648d21 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/conteimport { appealAt, appealGrid, buildingSource, homeSource, 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, wantsCitizenGoods, mealRate, refreshLevel, taxOf, tierFor } from "../../../src/rules/households.ts"+import { baseCollection, wantsCitizenGoods, mealRate, mealsOf, 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"@@ -86,10 +86,11 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptionsconst 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 meals = s.homes.reduce((n, h) => n + mealsOf(h, rules), 0)const clothHomes = s.homes.filter(h => wantsCitizenGoods(h, appealAt(appeal, h.tile.x, h.tile.y), rules)).lengthconst 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) },+ food: { min: meals * foodDecay * 60 / (rules.home.lasts.food * rules.stepSeconds), frequent: meals * foodDecay * 60 / ((rules.home.lasts.food - refreshLevel("food", 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) }}diff --git a/tools/balance/model/project.ts b/tools/balance/model/project.tsindex 3f752e3..4a5f778 100644--- a/tools/balance/model/project.ts+++ b/tools/balance/model/project.ts@@ -1,7 +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, mealRate, serveGoods, taxOf, tierFor } from "../../../src/rules/households.ts"+import { baseCollection, capacity, mealRate, rateOf, 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"@@ -147,7 +147,7 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)const appeal = analysis.household.find((a) => a.id === h.id)?.desirability ?? 0for (let n = 0; n < settleCount; n++) {next.tier = tierFor(next, appeal, next.meters, rules)- const cap = analysis.household.find((a) => a.id === h.id)?.roadConnected ? capacity(next, approval, appeal, rules) : 0+ const cap = analysis.household.find((a) => a.id === h.id)?.roadConnected ? capacity(next, approval, appeal, rules, rateOf(scenario.policy, next.tier)) : 0next.residents = Math.min(next.residents, rules.home.tiers[next.tier].residents)next.residents += Math.sign(cap - next.residents)}