Skip to content

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

Homes pay to rise a tier, and administration is reckoned by the resident

Claudec7a81c3ffe4b
diff --git a/docs/how-to-play.md b/docs/how-to-play.md
index 16be564..56c515c 100644
--- a/docs/how-to-play.md
+++ b/docs/how-to-play.md
@@ -50,11 +50,12 @@ six months.
- *winters*: a term is six years, and every year but the first ends in a
winter when fields do not grow, fisheries catch half as much, and homes
eat faster;
- - *administration*: the town hall costs more per home the more homes
- there are; by about 80 homes another cottage costs about what it brings
- in once its food is paid for (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;
+ - *administration*: the town hall costs more per resident the more
+ residents there are, so a citizens' home of eight costs twice a cottage
+ of four; by about 500 residents another settler costs about what they
+ bring in once their food is paid for (the build tooltip says what a home
+ would bring in after it), so a town grows past there by finer homes,
+ whose people pay more each;
- *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
@@ -142,7 +143,11 @@ Nobody tells you to build it that way; it works best that way.
something you choose to pay for. Bulldozing a cell takes its furnishing
first, then its ground.
- **Tiers.** Settlers live anywhere. A citizens' home needs desirability 5
- as well as bread, cloth, and faith; a home whose street drops below 5
+ as well as bread, cloth, and faith, and its rebuilding is paid at once
+ from the treasury and the store (35 coins, 4 planks, 2 stone; a
+ townhouse 45 coins, 4 planks, 4 stone, and a tool): a home the store
+ cannot pay for waits at its tier, and one that steps down pays again to
+ rise. A home whose street drops below 5
goes back to settlers even with every need met. A **townhouse** of
burghers (12 residents, the best taxes) needs desirability 12 and a
fire watch, a healer, and a watch house all calling on it. At
diff --git a/scripts/balance.ts b/scripts/balance.ts
index 657c3e1..c9ed9e3 100644
--- a/scripts/balance.ts
+++ b/scripts/balance.ts
@@ -59,7 +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, mealsOf, taxOf } from "../src/rules/households.ts"
+import { capacity, mealsOf, moreAdmin, taxOf } from "../src/rules/households.ts"
// ── Options ───────────────────────────────────────────────────────────────
@@ -424,8 +424,8 @@ const roadToward = (w: World, kind: Kind | null, limit = 16): Array<Point> => {
*/
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))
+ const residents = capacity(cottage, w.mood.approval, 0, rules, w.policy.settlers)
+ return fed * taxOf({ ...cottage, residents }, w.policy, rules) - moreAdmin(w.homes.reduce((n, h) => n + h.residents, 0), residents, rules)
}
/** What the bot wants next, in order: the first it can do, it does. */
diff --git a/scripts/worth.ts b/scripts/worth.ts
index 519e5d6..3a99314 100644
--- a/scripts/worth.ts
+++ b/scripts/worth.ts
@@ -30,7 +30,7 @@ console.table((["fish", "smoked", "bread", "cloth", "planks", "stone", "tools"]
}))
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 })))
+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 resident": 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`)
diff --git a/src/content.ts b/src/content.ts
index 66f62a7..cc7525d 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -425,11 +425,11 @@ export type Need = "food" | "bread" | "cloth" | "faith"
export const home = {
/** Half the house's width, in units: a 1×1 cell is 8 units from centre to edge. */
half: 5,
- cost: { coins: 10, materials: { planks: 1 } } as Kind["cost"],
+ cost: { coins: 15, materials: { planks: 1 } } as Kind["cost"],
tiers: {
- 1: { title: "settlers", residents: 4, tax: 2.5, height: 14, needs: ["food"], appeal: -100 },
- 2: { title: "citizens", residents: 8, tax: 5, height: 26, needs: ["bread", "cloth", "faith"], appeal: 5 },
- 3: { title: "burghers", residents: 12, tax: 6.5, height: 38, needs: ["bread", "cloth", "faith"], appeal: 12 }
+ 1: { title: "settlers", residents: 4, tax: 2.5, height: 14, needs: ["food"], appeal: -100, rise: { coins: 0, materials: {} } },
+ 2: { title: "citizens", residents: 8, tax: 5, height: 26, needs: ["bread", "cloth", "faith"], appeal: 5, rise: { coins: 35, materials: { planks: 4, stone: 2 } } },
+ 3: { title: "burghers", residents: 12, tax: 6.5, height: 38, needs: ["bread", "cloth", "faith"], appeal: 12, rise: { coins: 45, materials: { planks: 4, stone: 4, tools: 1 } } }
} as Readonly<Record<Tier, {
readonly title: string
readonly residents: number
@@ -438,6 +438,13 @@ export const home = {
readonly needs: ReadonlyArray<Need>
/** The desirability a home of this tier needs around it (see `appeal.ts`). */
readonly appeal: number
+ /**
+ * What rebuilding a home into this tier costs, paid at once from the
+ * treasury and the store when it is ready to rise, as paving is: a home
+ * that cannot be paid for waits at its tier. Rising again after
+ * stepping down costs it again.
+ */
+ readonly rise: Kind["cost"]
}>>,
/** A resident moves in (or out) this often. */
settle: ticks(3),
@@ -712,16 +719,16 @@ export const winters: Readonly<Record<WinterId, { readonly title: string; readon
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. Each more home costs `perHome` + 2·homes /
- * `growth`: about 6 coins a minute at 80 homes, about what a cottage
- * brings in once its food is paid for, and a full cottage's taxes by 140,
- * 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.
+ * Running a town costs more the bigger it gets, and it is reckoned by the
+ * person, not the roof: the town hall's administration costs `perResident`
+ * coins a minute a resident, and a further (residents / `growth`) a
+ * resident. Each more resident costs `perResident` + 2·residents /
+ * `growth`: about half a settler's taxes at 320 residents (a medium
+ * town's goal), and all of them by about 580, so past there a town grows by
+ * finer homes; and a citizens' home of eight costs twice a cottage of
+ * four, so finer homes are not had for nothing either.
*/
-export const admin = { perHome: 0.5, growth: 30 }
+export const admin = { perResident: 0.125, growth: 490 }
/**
* Approval, -100 → +100: where the town's mood is heading, and how fast it
diff --git a/src/present.ts b/src/present.ts
index 13ad33d..b2bc3ac 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -87,7 +87,7 @@ import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, season
import { Townsfolk } from "./townsfolk.ts"
import { emptyPreview, type Alert as Notice, type Group, type HitBox, type Legend, type Line, type View } from "./ui.ts"
import { blockers as blockersOf, streetAdvice, streetShort, whyUnmet, type InTown, type Served, type Street } from "./rules/explain.ts"
-import { breadBonus, moreAdmin, streetTax, suppliedTaxOf, taxOutlook, type TaxedHome } from "./rules/households.ts"
+import { breadBonus, moreAdmin, shortOf, 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"
@@ -430,17 +430,19 @@ export const Interact = Game.System(
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.
+ * town hall's administration for their residents (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 standing = houses.filter((row) => !row.data.closed.present).reduce((n, row) => n + row.data.house.get().residents, 0)
const fed = { tier: 1 as Tier, food: 1, bread: 0, cloth: 0, faith: 0, residents: home.tiers[1].residents }
+ let people = 0
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)
+ const d = appealAt(cells, c.x, c.y), residents = capacity(fed, approval, d, undefined, rates.settlers)
+ people += residents
+ return sum + taxOf({ ...fed, residents }, rates, undefined, d)
}, 0)
- const worth = Math.round(pays - moreAdmin(standing, n))
+ const worth = Math.round(pays - moreAdmin(standing, people))
return worth > 0 ? ` · ${signed(worth)} coins a minute once fed` : " · costs more to run than it pays: finer homes pay better"
}
@@ -926,8 +928,15 @@ export const Interact = Game.System(
else needs.push({ icon: "appeal", label: "street", value: signed(desirability), tone: "ok" })
const services = blocks.find((b) => b.what === "services")
if (services) needs.push({ icon: "order", label: "services", value: `for ${home.tiers[3].title}`, tone: "warn", note: services.text })
- if (nextTier && blocks.length === 0)
- needs.push({ icon: "citizens", label: `ready for ${home.tiers[nextTier].title}`, value: "✓", tone: "ok", note: "it grows as the next resident moves in" })
+ // Rising is a rebuilding, paid at once from the treasury and the store.
+ const short = nextTier ? shortOf(home.tiers[nextTier].rise, resources.treasury.get().coins, resources.stock.get()) : null
+ if (nextTier)
+ needs.push({
+ icon: "upkeep", label: "rebuilding", value: costText(home.tiers[nextTier].rise), tone: short ? "warn" : "ok",
+ note: short ? `the town is short of ${short}: it waits at its tier until the store can pay` : undefined
+ })
+ if (nextTier && blocks.length === 0 && !short)
+ needs.push({ icon: "citizens", label: `ready for ${home.tiers[nextTier].title}`, value: "✓", tone: "ok", note: "it grows as the next resident moves in, and pays for its rebuilding then" })
const risky = r ? (["fire", "health", "order"] as const).filter((k) => r[k] >= RISK_MAX * 0.35) : []
const cure = { fire: "a fire watch's watchman lowers it", health: "a healer's physician lowers it", order: "a watch house's constable lowers it" } as const
const safety: Array<Line> = [
diff --git a/src/rules/guide.ts b/src/rules/guide.ts
index 171ed12..7efb1aa 100644
--- a/src/rules/guide.ts
+++ b/src/rules/guide.ts
@@ -330,7 +330,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [
chapter: "Growing citizens",
course: true,
action: "Pick [select] and {tap|click} a home to see what it still lacks to hold citizens.",
- why: "A home becomes a citizens' home with bread, cloth, and faith, on a street of desirability 5 or more. Its panel lists what is missing.",
+ why: "A home becomes a citizens' home with bread, cloth, and faith, on a street of desirability 5 or more, once the store can pay for its rebuilding: planks and stone. Its panel lists what is missing.",
goal: "the first home holds citizens",
focus: "hall",
when: () => true,
diff --git a/src/rules/households.ts b/src/rules/households.ts
index 2bbb3f2..827b9cf 100644
--- a/src/rules/households.ts
+++ b/src/rules/households.ts
@@ -75,12 +75,19 @@ export const tierFor = (h: Needs, desirability: number, r: { readonly fire: numb
return fits(3) && kept(r, rules) ? 3 : 2
}
-/** 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)
+/** Coins a minute the town hall's administration costs for `residents` people in its homes. */
+export const adminOf = (residents: number, rules: Rules = shippedRules): number => Math.round(residents * (rules.admin.perResident + residents / rules.admin.growth))
+/** What `more` residents add to the administration of a town of `residents`, coins a minute (not rounded). */
+export const moreAdmin = (residents: number, more = 1, rules: Rules = shippedRules): number => {
+ const cost = (n: number) => n * (rules.admin.perResident + n / rules.admin.growth)
+ return cost(residents + more) - cost(residents)
+}
+
+/** Whether the treasury and the store can pay `cost`, and if not, what is short ("4 planks"). */
+export const shortOf = (cost: { readonly coins: number; readonly materials: Partial<Record<GoodId, number>> }, coins: number, stock: Readonly<Record<GoodId, number>>): string | null => {
+ const short = (Object.entries(cost.materials) as Array<[GoodId, number]>).filter(([g, n]) => stock[g] < n).map(([g, n]) => `${n - stock[g]} ${g}`)
+ if (coins < cost.coins) short.unshift(`${cost.coins - Math.max(0, coins)} coins`)
+ return short.length > 0 ? short.join(", ") : null
}
/** What traders pay for one of a good now, and what they ask for one. */
@@ -187,8 +194,8 @@ export const taxOutlook = (homes: ReadonlyArray<TaxedHome>, rates: Rates, tier:
}
/** Actual collection rounding, not rounded ledger display values. */
-export const baseCollection = (taxes: number, upkeep: number, homes: number, rules: Rules = shippedRules) => {
+export const baseCollection = (taxes: number, upkeep: number, residents: number, rules: Rules = shippedRules) => {
const share = rules.ledgerTicks * rules.stepSeconds / 60
- const admin = adminOf(homes, rules)
+ const admin = adminOf(residents, rules)
return { admin, delta: Math.round(taxes * share) - Math.round((upkeep + admin) * share) }
}
diff --git a/src/rules/worth.ts b/src/rules/worth.ts
index fa4b7e1..aef9542 100644
--- a/src/rules/worth.ts
+++ b/src/rules/worth.ts
@@ -134,12 +134,12 @@ export interface HomeWorth {
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. */
+ /** The resident, counting from none, whose administration costs more than a resident of 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
+/** What a home rises to a tier for (see `home.tiers`), as coins. */
+export const promotionCost = (tier: Tier, rules: Rules = shippedRules): number => costWorth(rules.home.tiers[tier].rise as Kind["cost"], rules)
export const homeWorth = (tier: Tier, rules: Rules = shippedRules): HomeWorth => {
const t = rules.home.tiers[tier], residents = t.residents
@@ -153,7 +153,7 @@ export const homeWorth = (tier: Tier, rules: Rules = shippedRules): HomeWorth =>
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++
+ while (breakEven < 100_000 && moreAdmin(breakEven, 1, rules) < net / residents) breakEven++
return { tier, residents, tax, eats, net, cost, gain, payback: gain > 0 ? cost / gain : Infinity, breakEven }
}
diff --git a/src/sim/town.ts b/src/sim/town.ts
index ea68836..cfd0671 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -10,12 +10,13 @@ import { amounts, goodIds, upkeepOf, 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, Upgraded, maybe } from "../schema.ts"
import { connected, elapsed, seasonAt } from "./shared.ts"
-import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, rateOf, taxOf, tierFor } from "../rules/households.ts"
+import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, rateOf, shortOf, 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
+ * into its tier (see `tierFor`), rising only once the treasury and the
+ * store pay for the rebuilding (see `home.tiers`), and one resident moves in or out towards
* 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.
@@ -34,7 +35,8 @@ export const Households = Game.System(
closed: Game.Query.optional(Paused)
},
without: [Site, Rising]
- })
+ }),
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
},
resources: {
grid: Game.System.readResource(Grid),
@@ -42,13 +44,33 @@ export const Households = Game.System(
appeal: Game.System.readResource(Appeal),
time: Game.System.readResource(Time),
charter: Game.System.readResource(Charter),
- policy: Game.System.readResource(Policy)
+ policy: Game.System.readResource(Policy),
+ treasury: Game.System.writeResource(Treasury)
},
services: { rules: Game.System.service(Rules) }
},
({ queries, resources, services }) => {
const rules = services.rules
const { home, risk } = rules
+ // What the store holds, reckoned only once some home is ready to rise this step.
+ let stock: Record<GoodId, number> | null = null
+ const held = () => (stock ??= Object.fromEntries(goodIds.map((g) => [g, queries.stores.each().reduce((n, { data }) => n + data.inventory.get().stock[g], 0)])) as Record<GoodId, number>)
+ /** Pays a home's rise from the treasury and the store, fullest first; or says it cannot. */
+ const pay = (cost: { readonly coins: number; readonly materials: Partial<Record<GoodId, number>> }): boolean => {
+ if (shortOf(cost, resources.treasury.get().coins, held())) return false
+ resources.treasury.update((tr) => ({ coins: tr.coins - cost.coins }))
+ for (const [g, n] of Object.entries(cost.materials) as Array<[GoodId, number]>) {
+ let owed = n
+ held()[g] -= n
+ for (const { data } of [...queries.stores.each()].sort((a, b) => b.data.inventory.get().stock[g] - a.data.inventory.get().stock[g])) {
+ if (owed <= 0) break
+ const inv = data.inventory.get(), k = Math.min(owed, inv.stock[g])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] - k } })
+ owed -= k
+ }
+ }
+ return true
+ }
const grid = resources.grid.get()
const approval = resources.mood.get().approval
@@ -65,7 +87,9 @@ export const Households = Game.System(
else if (next.clock % home.settle === 0) {
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 tier = tierFor(next, desirability, maybe(data.risk) ?? { fire: 0, health: 0, order: 0 }, rules)
+ // Rising a tier is a rebuilding, paid for at once; a home that cannot be paid for waits.
+ next.tier = tier > h.tier && !pay(home.tiers[tier].rise) ? h.tier : tier
const well = connected(grid, tile) ? capacity(next, approval, desirability, rules, rateOf(policy, next.tier)) : 0
const cap = data.sick.present ? Math.floor(well * risk.health.sickly) : well
next.residents = Math.min(next.residents, home.tiers[next.tier].residents)
@@ -120,9 +144,9 @@ export const Collect = Game.System(
const share = LEDGER_TICKS / (60 * 60)
const cells = resources.appeal.get().cells
let taxes = 0
- let homes = 0
+ let residents = 0
for (const { data } of queries.homes.each()) {
- homes += 1
+ residents += data.house.get().residents
const tile = data.tile.get()
const reached = roads !== null && doors(grid, tile).some((c) => roads.distance[key(c.x, c.y)]! >= 0)
if (reached) taxes += taxOf(data.house.get(), policy, rules, appealAt(cells, tile.x, tile.y))
@@ -130,12 +154,12 @@ export const Collect = Game.System(
let upkeep = 0
for (const { data } of queries.buildings.each()) upkeep += upkeepOf(kinds[data.building.get().kind], data.upgraded.present) * (data.paused.present ? PAUSED_UPKEEP : 1)
for (const { data } of queries.parks.each()) upkeep += parkUpkeep(data.park.get(), rules)
- const admin = adminOf(homes, rules)
+ const admin = adminOf(residents, rules)
const stores = queries.stores.each()
const before = resources.treasury.get().coins
const traded = tradeCollection(stores.map(({ data }) => data.inventory.get()), policy, resources.market.get().prices,
- before + baseCollection(taxes, upkeep, homes, rules).delta, rules)
+ before + baseCollection(taxes, upkeep, residents, rules).delta, rules)
// What changed hands, for the minute's flow of goods: bought less sold.
const moved: Partial<Record<GoodId, number>> = {}
for (const [i, row] of stores.entries()) {
diff --git a/test/balance-model.test.ts b/test/balance-model.test.ts
index 16c9bc1..90efada 100644
--- a/test/balance-model.test.ts
+++ b/test/balance-model.test.ts
@@ -187,12 +187,13 @@ test("taxes above 100% empty homes directly, settlers sooner, so the most a rate
assert(income.at(-1)! < income[best]!)
})
-test("administration: each more home costs more, and about what a fed cottage pays near the medium goal", () => {
+test("administration: each more resident costs more, and about what a fed settler pays near the medium goal", () => {
const rules = resolveRules()
- assert(moreAdmin(80, 1, rules) > moreAdmin(20, 1, rules) * 2)
+ // 80 cottages and 150 cottages, by their residents.
+ assert(moreAdmin(320, 4, rules) > moreAdmin(80, 4, 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.5 && moreAdmin(80, 1, rules) < cottage, `${moreAdmin(80, 1, rules)} vs ${cottage}`)
- assert(moreAdmin(150, 1, rules) > cottage)
+ assert(moreAdmin(320, 4, rules) > cottage * 0.5 && moreAdmin(320, 4, rules) < cottage, `${moreAdmin(320, 4, rules)} vs ${cottage}`)
+ assert(moreAdmin(600, 4, rules) > cottage)
})
test("buying drives a price up faster than selling drives it down, and a dear price calms slowly", () => {
diff --git a/test/economy.test.ts b/test/economy.test.ts
index 972f6bd..405c7c4 100644
--- a/test/economy.test.ts
+++ b/test/economy.test.ts
@@ -16,7 +16,7 @@ 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 { moreAdmin, 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"
@@ -87,14 +87,21 @@ test("fisheries sharing one stretch of water share its catch", { todo: "water ne
/** 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" }, () => {
+test("a home, and each tier it rises to, costs a few minutes of what it brings in", () => {
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")
+/** A finer home's people stop paying their way at most this many times further on than settlers. */
+const ADMIN_SPREAD = 3
+
+test("administration is charged by the resident, so finer homes pay for their people", () => {
+ const [cottage, citizens] = homes(rules)
+ // A citizens' home of eight costs the town hall twice what a cottage of four does.
+ const at = 300, cost = (n: number) => moreAdmin(at, n, rules)
+ assert(Math.abs(cost(citizens!.residents) / cost(cottage!.residents) - citizens!.residents / cottage!.residents) < 0.05)
+ none(homes(rules).slice(1).filter((h) => h.breakEven > cottage!.breakEven * ADMIN_SPREAD)
+ .map((h) => `tier ${h.tier}: pays its way to resident ${h.breakEven}, settlers to ${cottage!.breakEven}`), "administration too light")
})
// ── The opening ───────────────────────────────────────────────────────────
diff --git a/tools/balance/catalog.ts b/tools/balance/catalog.ts
index f1e2f1e..f53752c 100644
--- a/tools/balance/catalog.ts
+++ b/tools/balance/catalog.ts
@@ -25,7 +25,7 @@ export const buildScenario = (rules: Rules) => {
for (let x = lumber.tile.x - 3; x < lumber.tile.x + 3; x++) for (let y = 35; y < 39; y++) land.push({ tile: { x, y, size: 1 }, type: "tree", amount: 1, growth: rules.grown.tree })
for (let x = quarry.tile.x; x < quarry.tile.x + 2; x++) land.push({ tile: { x, y: 34, size: 1 }, type: "stone", amount: rules.lands.fair.rock, growth: 0 })
const scenario: Scenario = { ...template, land, name: "authored-bootstrap", coins: rules.lands.fair.coins - template.homes.length * rules.home.cost.coins - template.roads.length * rules.roadCost,
- buildings: [{ ...hall, stock: initial }], trade: { buys: ["tools"], sells: [], reserve: 10 } }
+ buildings: [{ ...hall, stock: initial }], trade: { buys: ["tools", "planks"], sells: [], reserve: 10 } }
const order: ReadonlyArray<readonly [KindId, number]> = [["sawmill", 0], ["lumberjack", 0], ["fishery", 0], ["quarry", 30], ["mill", 60], ["bakery", 90], ["farm", 120], ["sheep", 150], ["weaver", 180], ["market", 210], ["chapel", 240]]
const builds: BuildAction[] = order.map(([kind, at]) => ({ kind, at, tile: template.buildings.find((b) => b.kind === kind)!.tile }))
builds.push({ kind: "firewatch", at: 30, tile: { x: 6, y: 29, size: 2 } })
diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.ts
index 6648d21..e1f63a4 100644
--- a/tools/balance/model/analyze.ts
+++ b/tools/balance/model/analyze.ts
@@ -102,7 +102,7 @@ export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions
const taxes = s.homes.reduce((sum, h) => sum + (hallRoads && nearest(hallRoads, doors(g, h.tile)) ? taxOf(h, s.policy, rules, appealAt(appeal, h.tile.x, h.tile.y)) : 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 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 collection = baseCollection(taxes, upkeep + parkCost, s.homes.reduce((n, h) => n + h.residents, 0), 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)
diff --git a/tools/balance/model/project.ts b/tools/balance/model/project.ts
index 4a5f778..3cb75f3 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, rateOf, serveGoods, taxOf, tierFor } from "../../../src/rules/households.ts"
+import { baseCollection, capacity, mealRate, rateOf, serveGoods, shortOf, 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"
@@ -146,7 +146,13 @@ export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions)
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
for (let n = 0; n < settleCount; n++) {
- next.tier = tierFor(next, appeal, next.meters, rules)
+ const tier = tierFor(next, appeal, next.meters, rules), rise = rules.home.tiers[tier].rise
+ // A rise is paid at once from the treasury and the store, as in the game; unpaid, the home waits.
+ if (tier > next.tier && shortOf(rise, coins, stock) === null) {
+ coins -= rise.coins
+ for (const [g, n] of Object.entries(rise.materials) as Array<[keyof Amounts, number]>) stock[g] -= n
+ next.tier = tier
+ } else if (tier <= next.tier) next.tier = tier
const cap = analysis.household.find((a) => a.id === h.id)?.roadConnected ? capacity(next, approval, appeal, rules, rateOf(scenario.policy, next.tier)) : 0
next.residents = Math.min(next.residents, rules.home.tiers[next.tier].residents)
next.residents += Math.sign(cap - next.residents)
@@ -165,7 +171,7 @@ 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) => { const a = analysis.household.find((a) => a.id === h.id); return n + (a?.taxConnected ? taxOf(h, scenario.policy, rules, a.desirability) : 0) }, 0), upkeep = buildings.reduce((n, b) => n + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)
const parkCost = parks.reduce((n, p) => n + parkUpkeep(p, rules), 0)
- coins += baseCollection(tax, upkeep + parkCost, homes.length, rules).delta
+ coins += baseCollection(tax, upkeep + parkCost, homes.reduce((n, h) => n + h.residents, 0), 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) => {