A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Add an economy ledger and the rules it must keep, with the open holes as todos
Claude358fcfd81490
diff --git a/package.json b/package.jsonindex bef0217..0fe18ba 100644--- a/package.json+++ b/package.json@@ -10,6 +10,7 @@"typecheck": "tsc -p tsconfig.json --pretty false","balance": "node scripts/balance.ts","balance:model": "node tools/balance/cli.ts",+ "balance:worth": "node scripts/worth.ts","balance:model:check": "node --test test/balance-model.test.ts","check": "node scripts/check.ts","check:browser": "node scripts/check-browser.ts",diff --git a/scripts/worth.ts b/scripts/worth.tsnew file mode 100644index 0000000..519e5d6--- /dev/null+++ b/scripts/worth.ts@@ -0,0 +1,43 @@+/**+ * The economy's ledger, as tables: what every producer, food, home,+ * service, and the opening cost and give back (see `src/rules/worth.ts`),+ * and what answering the crown with bought goods leaves the town.+ *+ * node scripts/worth.ts+ * node scripts/worth.ts --set kinds.fishery.upkeep=5 with candidate rules+ */+import { resolveRules, type RulePatch } from "../src/rules/config.ts"+import { chainWorth, crownMargin, homes, median, openingKit, producers, services } from "../src/rules/worth.ts"+import type { GoodId } from "../src/content.ts"++const patches: Array<RulePatch> = []+for (let i = 2; i < process.argv.length; i++)+ if (process.argv[i] === "--set") {+ const [path, value] = process.argv[++i]!.split("=")+ patches.push({ path: path!, value: Number(value) })+ }+const rules = resolveRules(patches)+const r = (n: number) => (Number.isFinite(n) ? Math.round(n * 100) / 100 : n)++const made = producers(rules), usual = median(made.map((p) => p.perUpkeep))+console.log(`Producers (usual value added per coin of upkeep: ${r(usual)})`)+console.table(made.map((p) => ({ building: p.id, cost: p.cost, upkeep: p.upkeep, "adds/min": r(p.adds), "per upkeep": r(p.perUpkeep), "of usual": r(p.perUpkeep / usual), "payback min": r(p.payback) })))++console.log("Making one a minute, from the land up")+console.table((["fish", "smoked", "bread", "cloth", "planks", "stone", "tools"] as Array<GoodId>).map((g) => {+ const c = chainWorth(g, rules)+ return { good: g, cost: r(c.cost), upkeep: r(c.upkeep), workers: r(c.workers), "tools/min": r(c.tools), winter: c.winter, "keeps s": c.keeps, meets: c.meets.join(", ") }+}))++console.log("Homes (100% tax, every need met, a plain street)")+console.table(homes(rules).map((h) => ({ tier: h.tier, residents: h.residents, "tax/min": r(h.tax), "eats/min": r(h.eats), "net/min": r(h.net), cost: h.cost, "gain/min": r(h.gain), "payback min": r(h.payback), "pays its way to home": h.breakEven })))++const kit = openingKit(10, rules)+console.log(`The first citizens' kit: ${kit.kinds.join(", ")} and 10 homes: ${kit.cost} coins, ${kit.upkeep}/min upkeep, all open at ${kit.unlockHomes} cottages`)+console.table(Object.entries(rules.lands).map(([land, l]) => ({ land, coins: l.coins, "share of kit": `${Math.round((l.coins / kit.cost) * 100)}%` })))++console.log("Services")+console.table(services(rules).map((s) => ({ building: s.id, service: s.service, cost: s.cost, upkeep: s.upkeep, "cells walked/min": r(s.reach), "per upkeep": r(s.perUpkeep) })))++console.log("The crown, answered with bought goods")+console.table((["planks", "stone", "tools", "cloth"] as Array<GoodId>).flatMap((g) => [10, 30, 60].map((n) => crownMargin(g, n, rules))))diff --git a/src/rules/worth.ts b/src/rules/worth.tsnew file mode 100644index 0000000..fa4b7e1--- /dev/null+++ b/src/rules/worth.ts@@ -0,0 +1,240 @@+/**+ * What everything a mayor can lay down is worth: what it costs, what it+ * costs to keep, and what it gives back, all in coins at the traders'+ * usual prices, so a fishery, a citizens' home, a fire watch, and a+ * fountain can be weighed on one scale. A piece that gives back far more+ * than its kind usually does, for what it costs, is a hole a player will+ * find and play over and over: `test/economy.test.ts` holds the shipped+ * rules (or any candidate rules) to the bands these figures should keep.+ * Plain functions over the rules: nothing here knows the ECS.+ */+import { amounts, foods, goodIds, type GoodId, type Kind, type KindId, type Need, type Tier } from "../content.ts"+import { shippedRules, type Rules } from "./config.ts"+import { mealsOf, moreAdmin, taxOf } from "./households.ts"+import { tradeCollection } from "./trade.ts"++const kindIds = (rules: Rules) => Object.keys(rules.kinds) as Array<KindId>++/** Coins and materials as coins: materials at the traders' usual price. */+export const costWorth = (cost: Kind["cost"], rules: Rules = shippedRules): number =>+ cost.coins + (Object.entries(cost.materials) as Array<[GoodId, number]>).reduce((n, [g, k]) => n + k * rules.goods[g].price, 0)++/** The median of some numbers: what a kind usually does. */+export const median = (xs: ReadonlyArray<number>): number => {+ const s = [...xs].sort((a, b) => a - b), mid = Math.floor(s.length / 2)+ return s.length === 0 ? 0 : s.length % 2 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2+}++// ── Producers ─────────────────────────────────────────────────────────────++export interface ProducerWorth {+ readonly id: KindId+ /** One-off: coins and materials. */+ readonly cost: number+ /** Coins a minute. */+ readonly upkeep: number+ /** Coins a minute of value added: its output less its input and the tools it wears, with a full crew and a tool. */+ readonly adds: number+ /** What it adds for each coin of upkeep. */+ readonly perUpkeep: number+ /** Minutes until what it adds, less its upkeep, has paid for it. */+ readonly payback: number+}++/** Jobs a minute a maker does with a full crew, a tool, and good repair. */+export const jobsPerMinute = (kind: Kind): number => (kind.recipe ? 60 / kind.recipe.seconds : 0)++export const producerWorth = (id: KindId, rules: Rules = shippedRules): ProducerWorth => {+ const kind = rules.kinds[id], r = kind.recipe!, jobs = jobsPerMinute(kind)+ const out = jobs * r.batch * rules.goods[r.output].price+ const inp = r.input ? jobs * r.inputs * rules.goods[r.input].price : 0+ const tools = kind.wear ? (jobs / kind.wear) * rules.goods.tools.price : 0+ const adds = out - inp - tools, cost = costWorth(kind.cost, rules)+ return { id, cost, upkeep: kind.upkeep, adds, perUpkeep: adds / kind.upkeep, payback: adds > kind.upkeep ? cost / (adds - kind.upkeep) : Infinity }+}++export const producers = (rules: Rules = shippedRules): Array<ProducerWorth> =>+ kindIds(rules).filter((id) => rules.kinds[id].recipe && rules.kinds[id].buildable).map((id) => producerWorth(id, rules))++// ── Chains: what a unit of a good a minute takes, from the land up ──────++const needIds: ReadonlyArray<Need> = ["food", "bread", "cloth", "faith"]++/** The needs a good meets when a walker hands it to a home: every food meets food; a good named for a need meets it. */+export const meets = (good: GoodId): ReadonlyArray<Need> => [+ ...(foods.includes(good) ? ["food" as const] : []),+ ...(needIds as ReadonlyArray<string>).filter((n) => n !== "food" && n === good) as Array<Need>+]++export interface ChainWorth {+ readonly good: GoodId+ /** The buildings it takes, as fractions of one, to make one a minute. */+ readonly buildings: Readonly<Partial<Record<KindId, number>>>+ /** Per unit a minute: one-off cost, upkeep, workers, and tools worn a minute. */+ readonly cost: number+ readonly upkeep: number+ readonly workers: number+ readonly tools: number+ /** What it makes in a normal winter, as a share of the summer. */+ readonly winter: number+ /** Seconds a unit keeps in store (`Infinity`: it keeps). */+ readonly keeps: number+ readonly meets: ReadonlyArray<Need>+}++/** The maker of a good: the building whose recipe turns out the most of it. */+const makerOf = (good: GoodId, rules: Rules): KindId | undefined =>+ kindIds(rules).filter((id) => rules.kinds[id].buildable && rules.kinds[id].recipe?.output === good)+ .sort((a, b) => rules.kinds[b].recipe!.batch * jobsPerMinute(rules.kinds[b]) - rules.kinds[a].recipe!.batch * jobsPerMinute(rules.kinds[a]))[0]++export const chainWorth = (good: GoodId, rules: Rules = shippedRules): ChainWorth => {+ const buildings: Partial<Record<KindId, number>> = {}+ let winter = 1+ const need = (g: GoodId, perMinute: number) => {+ const id = makerOf(g, rules)+ if (!id) throw new Error(`Nothing makes ${g}`)+ const kind = rules.kinds[id], r = kind.recipe!, count = perMinute / (r.batch * jobsPerMinute(kind))+ buildings[id] = (buildings[id] ?? 0) + count+ if (kind.gathers?.source === "water") winter = Math.min(winter, rules.winters.normal.fishing)+ if (kind.gathers?.source === "field") winter = 0+ if (r.input) need(r.input, count * jobsPerMinute(kind) * r.inputs)+ }+ need(good, 1)+ const sum = (f: (k: Kind) => number) => (Object.entries(buildings) as Array<[KindId, number]>).reduce((n, [id, c]) => n + c * f(rules.kinds[id]), 0)+ return {+ good, buildings, winter,+ cost: sum((k) => costWorth(k.cost, rules)), upkeep: sum((k) => k.upkeep), workers: sum((k) => k.workers),+ tools: sum((k) => (k.wear ? jobsPerMinute(k) / k.wear : 0)),+ keeps: rules.spoils[good] ?? Infinity,+ meets: meets(good)+ }+}++/** The ways of making `a` that are at least as cheap as making `b` on every count, and cheaper on one: `a` dominates `b`. */+export const dominates = (a: ChainWorth, b: ChainWorth): boolean => {+ const costs = [[a.cost, b.cost], [a.upkeep, b.upkeep], [a.workers, b.workers], [a.tools, b.tools]] as const+ const gains = [[a.winter, b.winter], [a.keeps, b.keeps]] as const+ const noWorse = costs.every(([x, y]) => x <= y) && gains.every(([x, y]) => x >= y)+ return noWorse && (costs.some(([x, y]) => x < y) || gains.some(([x, y]) => x > y))+}++// ── Homes ─────────────────────────────────────────────────────────────────++export interface HomeWorth {+ readonly tier: Tier+ readonly residents: number+ /** Coins a minute at 100%, every need met, on a plain street. */+ readonly tax: number+ /** Coins a minute of goods it eats and wears out, at the usual price. */+ readonly eats: number+ readonly net: number+ /** What it cost to lay (tier 1), or to rise to this tier from the one below. */+ readonly cost: number+ /** What it gains over the tier below, a minute. */+ readonly gain: number+ /** Minutes the gain takes to pay for the cost. */+ readonly payback: number+ /** The first home, counting from none, whose administration costs more than this tier pays. */+ readonly breakEven: number+}++/** What a home rises a tier for: the content gives no price, so nothing. */+export const promotionCost = (_tier: Tier, _rules: Rules = shippedRules): number => 0++export const homeWorth = (tier: Tier, rules: Rules = shippedRules): HomeWorth => {+ const t = rules.home.tiers[tier], residents = t.residents+ const needs = { food: 1, bread: tier >= 2 ? 1 : 0, cloth: tier >= 2 ? 1 : 0, faith: tier >= 2 ? 1 : 0 }+ const tax = taxOf({ tier, residents, ...needs }, { settlers: 100, citizens: 100 }, rules)+ const seconds = (ticks: number) => ticks * rules.stepSeconds+ const meals = mealsOf({ residents }, rules) * 60 / seconds(rules.home.lasts.food)+ const staple = tier >= 2 ? rules.goods.bread.price : rules.goods.fish.price+ const eats = meals * staple + (tier >= 2 ? (60 / seconds(rules.home.lasts.cloth)) * rules.goods.cloth.price : 0)+ const below = tier > 1 ? homeWorth((tier - 1) as Tier, rules) : null+ const cost = tier === 1 ? costWorth(rules.home.cost as Kind["cost"], rules) : promotionCost(tier, rules)+ const net = tax - eats, gain = below ? net - below.net : net+ let breakEven = 0+ while (breakEven < 100_000 && moreAdmin(breakEven, 1, rules) < net) breakEven+++ return { tier, residents, tax, eats, net, cost, gain, payback: gain > 0 ? cost / gain : Infinity, breakEven }+}++export const homes = (rules: Rules = shippedRules): Array<HomeWorth> => ([1, 2, 3] as const).map((t) => homeWorth(t, rules))++// ── The opening ───────────────────────────────────────────────────────────++/**+ * What it takes to found a town and raise its first citizens: `homes`+ * cottages, a maker of every good a citizen needs and of every good+ * those makers are built from, back to the land (but not those that wait+ * for citizens, like the smithy), and a building for every service a+ * citizen needs (the chapel).+ */+export const openingKit = (homesLaid = 10, rules: Rules = shippedRules) => {+ const kit = new Set<KindId>()+ const open = (k: Kind) => k.unlock.citizens === 0 && k.buildable+ const add = (good: GoodId) => {+ const id = makerOf(good, rules)+ if (!id || kit.has(id) || !open(rules.kinds[id])) return+ kit.add(id)+ const r = rules.kinds[id].recipe!+ if (r.input) add(r.input)+ for (const g of Object.keys(rules.kinds[id].cost.materials) as Array<GoodId>) add(g)+ }+ add("fish")+ for (const g of goodIds) if (meets(g).some((n) => rules.home.tiers[2].needs.includes(n) && n !== "food")) add(g)+ add("planks"); add("stone")+ for (const need of rules.home.tiers[2].needs) {+ const service = kindIds(rules).find((id) => rules.kinds[id].service?.service === need && open(rules.kinds[id]))+ if (service) kit.add(service)+ }+ const kinds = [...kit]+ const cost = kinds.reduce((n, id) => n + rules.kinds[id].cost.coins, 0) + homesLaid * rules.home.cost.coins+ const unlockHomes = Math.ceil(Math.max(...kinds.map((id) => rules.kinds[id].unlock.residents)) / rules.home.tiers[1].residents)+ return { kinds, cost, upkeep: kinds.reduce((n, id) => n + rules.kinds[id].upkeep, 0), unlockHomes }+}++// ── The crown ─────────────────────────────────────────────────────────────++/** Coins to buy `amount` of a good from traders, one collection at a time, at prices that climb as the town buys. */+export const buyCost = (good: GoodId, amount: number, rules: Rules = shippedRules): number => {+ let prices = amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))), held = 0, spent = 0+ for (let i = 0; i < 1000 && held < amount; i++) {+ const shelf = { stock: amounts({ [good]: held }), accepts: goodIds, cap: 100_000 }+ const r = tradeCollection([shelf], { sells: [], buys: [good], reserve: amount }, prices, 1_000_000, rules)+ spent += 1_000_000 - r.coins; held = r.stores[0]!.stock[good]; prices = r.prices+ }+ return spent+}++/** What answering a request for `amount` of a good with goods bought for it leaves the town: the reward less the buying. */+export const crownMargin = (good: GoodId, amount: number, rules: Rules = shippedRules) => {+ const reward = Math.round(amount * rules.goods[good].price * rules.crown.reward) + rules.crown.bonus+ const bought = buyCost(good, amount, rules)+ return { good, amount, reward, bought, margin: reward - bought }+}++// ── Services ──────────────────────────────────────────────────────────────++export interface ServiceWorth {+ readonly id: string+ readonly service: string+ readonly cost: number+ readonly upkeep: number+ /** Road cells walked a minute: its range times its walks a minute. */+ readonly reach: number+ readonly perUpkeep: number+}++/** Every service building, and each upgraded one as its own entry. */+export const services = (rules: Rules = shippedRules): Array<ServiceWorth> =>+ kindIds(rules).flatMap((id) => {+ const k = rules.kinds[id]+ if (!k.service || !k.buildable) return []+ const plain = { id, service: k.service.service, cost: costWorth(k.cost, rules), upkeep: k.upkeep, reach: (k.service.range * 60) / k.service.seconds }+ const out: Array<ServiceWorth> = [{ ...plain, perUpkeep: plain.reach / plain.upkeep }]+ if (k.upgrade?.service) {+ const up = { id: `${id}+${k.upgrade.title.toLowerCase()}`, service: k.service.service, cost: plain.cost + costWorth(k.upgrade.cost, rules), upkeep: k.upgrade.upkeep,+ reach: (k.upgrade.service.range * 60) / k.upgrade.service.seconds }+ out.push({ ...up, perUpkeep: up.reach / up.upkeep })+ }+ return out+ })diff --git a/test/economy.test.ts b/test/economy.test.tsnew file mode 100644index 0000000..972f6bd--- /dev/null+++ b/test/economy.test.ts@@ -0,0 +1,171 @@+/**+ * The economy's rules that must hold however the numbers are tuned: no+ * piece a mayor can lay down gives back far more than its kind usually+ * does for what it costs, and nothing comes for free. The figures come+ * from `src/rules/worth.ts`; the bands are the design's, so a change to+ * one number that opens a hole a player could play over and over fails+ * here.+ *+ * A rule the shipped game breaks today is marked `todo` with what breaks+ * it: the suite stays green, and `node --test` lists each one, so this+ * file is also the list of holes still open. Once a hole is closed, drop+ * its `todo` and the rule holds from then on.+ */+import assert from "node:assert/strict"+import { test } from "node:test"+import { amounts, type GoodId, type GroundId, type Need, type PropId } from "../src/content.ts"+import { parksOf } from "../src/appeal.ts"+import { shippedRules } from "../src/rules/config.ts"+import { tierFor } from "../src/rules/households.ts"+import { chainWorth, crownMargin, dominates, homes, median, openingKit, producers, services } from "../src/rules/worth.ts"+import { district } from "../tools/balance/scenario.ts"+import { component, fixture } from "../tools/balance/verify/fixture.ts"++const rules = shippedRules+/** Fails with every offender listed, not just the first. */+const none = (offenders: ReadonlyArray<string>, rule: string) => assert.deepEqual(offenders, [], `${rule}:\n ${offenders.join("\n ")}`)+const round = (n: number) => Math.round(n * 100) / 100++// ── Producers ─────────────────────────────────────────────────────────────++/** A producer adds between half and twice what producers usually add for each coin of upkeep. */+const PRODUCER_BAND = [0.5, 2] as const++test("every producer adds about what producers usually do for its upkeep", { todo: "fishery ×2.8 and bakery ×2.0 of the usual; mill ×0.29 and mine ×0.47" }, () => {+ const all = producers(rules), usual = median(all.map((p) => p.perUpkeep))+ none(all.filter((p) => p.perUpkeep < usual * PRODUCER_BAND[0] || p.perUpkeep > usual * PRODUCER_BAND[1])+ .map((p) => `${p.id}: adds ${round(p.adds)}/min for ${p.upkeep} upkeep, ×${round(p.perUpkeep / usual)} of the usual ${round(usual)}`), "producer outside the band")+})++// ── Food ──────────────────────────────────────────────────────────────────++const foods: ReadonlyArray<GoodId> = ["fish", "smoked", "bread"]+/** Goods that meet the same need cost within this many times one another to keep making. */+const SUBSTITUTES = 3++test("no way of making a food is cheaper on every count than another that meets the same needs", () => {+ const chains = foods.map((g) => chainWorth(g, rules))+ const same = (a: ReadonlyArray<Need>, b: ReadonlyArray<Need>) => a.length === b.length && a.every((n) => b.includes(n))+ none(chains.flatMap((a) => chains.filter((b) => a !== b && same(a.meets, b.meets) && dominates(a, b)).map((b) => `${a.good} dominates ${b.good}`)), "dominated food")+})++test("foods that all meet a need cost within a few times one another to keep making", { todo: "bread's chain costs 4.8× fish's upkeep a unit, and stops in winter" }, () => {+ const chains = foods.map((g) => chainWorth(g, rules))+ const out: Array<string> = []+ for (const need of ["food"] as const) {+ const meeting = chains.filter((c) => c.meets.includes(need))+ const cheap = meeting.reduce((a, b) => (a.upkeep <= b.upkeep ? a : b))+ for (const c of meeting) if (c.upkeep > cheap.upkeep * SUBSTITUTES) out.push(`${need}: ${c.good} ${round(c.upkeep)}/unit upkeep vs ${cheap.good} ${round(cheap.upkeep)}`)+ }+ none(out, "substitutes too far apart")+})++test("a tier's staple is needed to keep the tier: a citizens' home fed fish instead of bread steps down", { todo: "a citizens' home keeps its tier on fish, cloth, and faith (2 of 3 needs)" }, () => {+ const fish = { tier: 2 as const, food: 100, bread: 0, cloth: 100, faith: 100 }+ assert.equal(tierFor(fish, rules.home.tiers[3].appeal, { fire: 0, health: 0, order: 0 }, rules), 1)+})++test("fisheries sharing one stretch of water share its catch", { todo: "water never runs out: every fishery on it catches at full pace" }, () => {+ const base = district("shared-water", [1, 1, 1, 1], ["fishery", "fishery"], false, rules)+ const [a, b] = base.buildings.filter((x) => x.kind === "fishery")+ // One cell of water, within reach of both.+ const water = { x: b!.tile.x, y: a!.tile.y + a!.tile.size + 1, size: 1 }+ const scenario = { ...base, homes: base.homes.map((h) => ({ ...h, food: 10_000_000 })), land: [{ tile: water, type: "water" as const, amount: 1, growth: 0 }] }+ const town = fixture(scenario, rules)+ for (let s = 0; s < 60; s++) {+ town.change((snap) => { for (const f of [a!, b!]) component(snap, f.id, "Town/Inventory").stock.fish = 0 })+ town.run(1)+ }+ const made = [a!, b!].map((f) => component(town.snapshot(), f.id, "Town/Recipe").made as number)+ const alone = 60 / rules.kinds.fishery.recipe!.seconds+ assert(made[0]! > 0 && made[1]! > 0, `both fish: ${made}`)+ assert(made[0]! + made[1]! <= alone * 1.25, `two fisheries on one cell of water caught ${made.join(" + ")}, one alone catches ${alone}`)+})++// ── Homes ─────────────────────────────────────────────────────────────────++/** Minutes of what it adds that laying a home, or raising it a tier, should cost at least. */+const HOME_PAYBACK = 2++test("a home, and each tier it rises to, costs a few minutes of what it brings in", { todo: "a cottage pays back in 1.5 min; rising to citizens or burghers costs nothing" }, () => {+ none(homes(rules).filter((h) => h.payback < HOME_PAYBACK)+ .map((h) => `tier ${h.tier}: costs ${h.cost}, adds ${round(h.gain)}/min, pays back in ${round(h.payback)} min`), "home too cheap")+})++test("administration weighs on finer homes as it does on cottages", { todo: "a citizens' home pays its way to the 490th home, a townhouse to the 1020th; a cottage only to the 123rd" }, () => {+ const [cottage, ...finer] = homes(rules)+ none(finer.filter((h) => h.breakEven > cottage!.breakEven * 2).map((h) => `tier ${h.tier}: pays its way to home ${h.breakEven}, a cottage to ${cottage!.breakEven}`), "administration too light")+})++// ── The opening ───────────────────────────────────────────────────────────++/** The share of the first citizens' buildings a new town's treasury pays for, at most; and the homes they need, at least. */+const OPENING_SHARE = 0.7+const OPENING_HOMES = 15++test("a new town's treasury pays for only part of the first citizens' buildings", { todo: "every land's treasury buys the whole kit (1260 coins): rich 190%, fair 151%, harsh 119%" }, () => {+ const kit = openingKit(10, rules)+ none((Object.entries(rules.lands) as Array<[string, { coins: number }]>).filter(([, l]) => l.coins > kit.cost * OPENING_SHARE)+ .map(([id, l]) => `${id}: ${l.coins} coins for a ${kit.cost}-coin kit (${kit.kinds.join(", ")}), ${Math.round((l.coins / kit.cost) * 100)}%`), "opening paid for")+})++test("the first citizens' buildings open only once the town has grown", { todo: "all of them open by the 8th cottage" }, () => {+ const kit = openingKit(10, rules)+ assert(kit.unlockHomes >= OPENING_HOMES, `the ${kit.kinds.join(", ")} all open at ${kit.unlockHomes} cottages`)+})++// ── The crown ─────────────────────────────────────────────────────────────++test("answering the crown with bought goods does not pay", { todo: "the reward (2× price + 50) beats buying at 1.5× on requests of 10 to 30" }, () => {+ const goods = (Object.keys(rules.goods) as Array<GoodId>).filter((g) => rules.spoils[g] === undefined)+ none(goods.flatMap((g) => [10, 20, 30].map((n) => crownMargin(g, n, rules))).filter((m) => m.margin > 0)+ .map((m) => `${m.amount} ${m.good}: reward ${m.reward}, bought for ${m.bought}, +${m.margin}`), "crown pays for bought goods")+})++// ── Services ──────────────────────────────────────────────────────────────++test("a bigger building for a service walks at least as far for its upkeep as a smaller one", { todo: "a hospital walks 37.5 cells a coin of upkeep, a healer 56" }, () => {+ const all = services(rules), out: Array<string> = []+ for (const big of all) for (const small of all)+ if (big.service === small.service && big.cost > small.cost && big.perUpkeep < small.perUpkeep)+ out.push(`${big.id} ${round(big.perUpkeep)} cells/upkeep < ${small.id} ${round(small.perUpkeep)}`)+ none(out, "a dearer service building does less a coin")+})++// ── Parks ─────────────────────────────────────────────────────────────────++/** The most a park of one cell gives: no more than a street or a little more. */+const ONE_CELL_MOST = 2+const road = (_x: number, y: number) => y === 0++test("a park of one cell gives little, whatever stands on it", { todo: "a lamp makes it 3, a fountain 6, a statue 7: more than a chapel" }, () => {+ const out: Array<string> = []+ for (const ground of ["lawn", "flowers", "path", "square"] as Array<GroundId>)+ for (const prop of ["none", "lamp", "fountain", "statue"] as Array<PropId | "none">) {+ const [park] = parksOf([{ x: 5, y: 1, ground, prop }], road, rules)+ if (park && park.value > ONE_CELL_MOST) out.push(`${ground} + ${prop}: ${park.value}`)+ }+ none(out, "one-cell park too fine")+})++test("cells laid as separate parks give no more than the same cells as one", { todo: "parks touching only at a corner are separate, and their values add up" }, () => {+ const out: Array<string> = []+ for (const n of [2, 3, 4, 5])+ for (const prop of ["none", "lamp"] as const) {+ // A diagonal of cells (each its own park) against a row of them (one park), both beside the road.+ const apart = Array.from({ length: n }, (_, i) => ({ x: 2 * i, y: 1 + (i % 2), ground: "path" as const, prop }))+ const joined = Array.from({ length: n }, (_, i) => ({ x: i, y: 1, ground: "path" as const, prop }))+ const value = (cells: typeof apart) => parksOf(cells, road, rules).reduce((s, p) => s + p.value, 0)+ if (value(apart) > value(joined)) out.push(`${n} paths${prop === "none" ? "" : ` with ${prop}s`}: ${value(apart)} apart, ${value(joined)} as one`)+ }+ none(out, "splitting a park pays")+})++// ── The ledger itself ─────────────────────────────────────────────────────++test("the ledger's figures follow the rules it is given", () => {+ assert.equal(chainWorth("fish", rules).buildings.fishery, 1 / 15)+ const dearer = { ...rules, kinds: { ...rules.kinds, fishery: { ...rules.kinds.fishery, upkeep: 9 } } }+ assert(chainWorth("fish", dearer).upkeep > chainWorth("fish", rules).upkeep)+ assert.equal(amounts({}).fish, 0)+})