Skip to content

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

Give each simulation system its own file

SandroMaglione8a35aeb88674
diff --git a/src/game/systems/decay/decay.ts b/src/game/systems/decay/decay.ts
new file mode 100644
index 0000000..c3dcac4
--- /dev/null
+++ b/src/game/systems/decay/decay.ts
@@ -0,0 +1,107 @@
+import { spoilExpectation } from "../../rules/decay.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
+import { ruinDraft } from "../../world/archetypes.ts"
+import { foods, goodIds, stepsOf } from "../../content/index.ts"
+import { counted, placeName } from "../../world/places.ts"
+import { Ruin } from "../../schema.ts"
+import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Recipe, Rising, Rng, Site, Staff, Tile, Time } from "../../schema.ts"
+import { elapsed, write } from "../shared.ts"
+
+/** The pantry warns of rotting food at most this often. */
+const ROT_WARNING = stepsOf(5 * 60)
+
+export const Decay = Game.System(
+ "Town/Decay",
+ {
+ queries: {
+ worn: Game.Query({
+ selection: { tile: Game.Query.read(Tile), condition: Game.Query.write(Condition), house: Game.Query.optional(House), building: Game.Query.optional(Building) },
+ without: [Site, Rising, Burning]
+ }),
+ landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
+ shelves: Game.Query({ selection: { inventory: Game.Query.write(Inventory), building: Game.Query.optional(Building) }, without: [Site, Rising] }),
+ /** Who makes food, and whether anyone is at work there: for the rot warning's reckoning of what the town makes. */
+ makers: Game.Query({ selection: { recipe: Game.Query.read(Recipe), staff: Game.Query.read(Staff) }, with: [Building], without: [Site, Rising, Burning] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ rng: Game.System.writeResource(Rng),
+ pantry: Game.System.writeResource(Pantry),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Ruin), Game.System.despawns(Condition))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { kinds, condition: wear, spoils, spoilTicks: SPOIL_TICKS } = rules
+
+ const tick = resources.time.get().step
+ const t = elapsed(resources.time.get(), resources.charter.get())
+
+ // Wear: a point every `wear.every` steps; at nothing it falls down.
+ if (tick % wear.every === 0) {
+ const landmarks = queries.landmarks.each().map(({ data }) => ({ kind: data.building.get().kind, ...data.tile.get() }))
+ for (const { entity, data } of queries.worn.each()) {
+ const value = data.condition.get().value - 1
+ if (value > 0) {
+ data.condition.set({ value })
+ continue
+ }
+ const tile = data.tile.get()
+ const b = data.building.value()
+ commands.despawn(entity)
+ commands.spawn(ruinDraft(tile, "collapsed"))
+ write(
+ resources.chronicle,
+ t,
+ b ? `The ${kinds[b.kind].title.toLowerCase()} on ${placeName(landmarks, tile)} fell down: nobody mended it.` : `A home on ${placeName(landmarks, tile)} fell down: nobody mended it.`,
+ true,
+ tile
+ )
+ }
+ }
+
+ // Spoiling: each shelf loses its share of what spoils, a granary's a fifth as much.
+ if (tick % SPOIL_TICKS === 0) {
+ const random = Random.draw(resources.rng)
+ let rotted = 0
+ for (const { data } of queries.shelves.each()) {
+ const inv = data.inventory.get()
+ const keeps = kinds[data.building.value()?.kind ?? "townhall"].keeps ?? 1
+ let stock = inv.stock
+ for (const g of goodIds) {
+ const life = spoils[g]
+ if (life === undefined || stock[g] <= 0) continue
+ const expected = spoilExpectation(stock[g], g, keeps, rules)
+ const lose = Math.min(stock[g], Math.floor(expected) + (random.next() < expected % 1 ? 1 : 0))
+ if (lose <= 0) continue
+ stock = { ...stock, [g]: stock[g] - lose }
+ rotted += lose
+ }
+ if (stock !== inv.stock) data.inventory.set({ ...inv, stock })
+ }
+ if (rotted > 0) resources.pantry.update((p) => ({ ...p, rotted: p.rotted + rotted }))
+ }
+
+ // The pantry's minute.
+ if (t > 0 && t % 3600 === 0) {
+ const p = resources.pantry.get()
+ const warn = p.rotted >= 6 && p.rotted * 4 >= p.eaten && t - p.warned >= ROT_WARNING
+ if (warn) {
+ // What the town could make of food a minute with the crews it has, against what it ate: rot is the difference, not a want of granaries.
+ let made = 0
+ for (const { data } of queries.makers.each()) {
+ const r = data.recipe.get()
+ if (data.staff.get().assigned > 0 && (foods as ReadonlyArray<string>).includes(r.output)) made += (r.batch * 3600) / r.period
+ }
+ const cause = made > p.eaten * 1.5
+ ? `the town makes about ${Math.round(made)} food a minute and eats ${p.eaten}: fewer fisheries, a smokehouse, or selling fish would stop the waste`
+ : `a granary keeps fish and bread five times as long, and smoked fish keeps`
+ write(resources.chronicle, t, `${counted(p.rotted, "fish or loaf", "fish and loaves")} rotted in store this minute: ${cause}.`, true)
+ }
+ resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: p.eaten, rottedLast: p.rotted, warned: warn ? t : p.warned })
+ }
+ }
+)
diff --git a/src/game/systems/decay/index.ts b/src/game/systems/decay/index.ts
index 98ef787..dc248d9 100644
--- a/src/game/systems/decay/index.ts
+++ b/src/game/systems/decay/index.ts
@@ -1,114 +1,7 @@
-import { spoilExpectation } from "../../rules/decay.ts"
/**
* What time does to the town: homes and buildings run down until a builder
* mends them, and fall into ruin if none does; fish and bread rot on the
* shelf, slower in a granary. The pantry keeps count of what the town ate
* and what rotted, a minute at a time.
*/
-import * as Random from "@typeonce/ritmo-math/Random"
-
-import { ruinDraft } from "../../world/archetypes.ts"
-import { foods, goodIds, stepsOf } from "../../content/index.ts"
-import { counted, placeName } from "../../world/places.ts"
-import { Ruin } from "../../schema.ts"
-import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Recipe, Rising, Rng, Site, Staff, Tile, Time } from "../../schema.ts"
-import { elapsed, write } from "../shared.ts"
-
-/** The pantry warns of rotting food at most this often. */
-const ROT_WARNING = stepsOf(5 * 60)
-
-export const Decay = Game.System(
- "Town/Decay",
- {
- queries: {
- worn: Game.Query({
- selection: { tile: Game.Query.read(Tile), condition: Game.Query.write(Condition), house: Game.Query.optional(House), building: Game.Query.optional(Building) },
- without: [Site, Rising, Burning]
- }),
- landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
- shelves: Game.Query({ selection: { inventory: Game.Query.write(Inventory), building: Game.Query.optional(Building) }, without: [Site, Rising] }),
- /** Who makes food, and whether anyone is at work there: for the rot warning's reckoning of what the town makes. */
- makers: Game.Query({ selection: { recipe: Game.Query.read(Recipe), staff: Game.Query.read(Staff) }, with: [Building], without: [Site, Rising, Burning] })
- },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- rng: Game.System.writeResource(Rng),
- pantry: Game.System.writeResource(Pantry),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.spawns(Ruin), Game.System.despawns(Condition))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { kinds, condition: wear, spoils, spoilTicks: SPOIL_TICKS } = rules
-
- const tick = resources.time.get().step
- const t = elapsed(resources.time.get(), resources.charter.get())
-
- // Wear: a point every `wear.every` steps; at nothing it falls down.
- if (tick % wear.every === 0) {
- const landmarks = queries.landmarks.each().map(({ data }) => ({ kind: data.building.get().kind, ...data.tile.get() }))
- for (const { entity, data } of queries.worn.each()) {
- const value = data.condition.get().value - 1
- if (value > 0) {
- data.condition.set({ value })
- continue
- }
- const tile = data.tile.get()
- const b = data.building.value()
- commands.despawn(entity)
- commands.spawn(ruinDraft(tile, "collapsed"))
- write(
- resources.chronicle,
- t,
- b ? `The ${kinds[b.kind].title.toLowerCase()} on ${placeName(landmarks, tile)} fell down: nobody mended it.` : `A home on ${placeName(landmarks, tile)} fell down: nobody mended it.`,
- true,
- tile
- )
- }
- }
-
- // Spoiling: each shelf loses its share of what spoils, a granary's a fifth as much.
- if (tick % SPOIL_TICKS === 0) {
- const random = Random.draw(resources.rng)
- let rotted = 0
- for (const { data } of queries.shelves.each()) {
- const inv = data.inventory.get()
- const keeps = kinds[data.building.value()?.kind ?? "townhall"].keeps ?? 1
- let stock = inv.stock
- for (const g of goodIds) {
- const life = spoils[g]
- if (life === undefined || stock[g] <= 0) continue
- const expected = spoilExpectation(stock[g], g, keeps, rules)
- const lose = Math.min(stock[g], Math.floor(expected) + (random.next() < expected % 1 ? 1 : 0))
- if (lose <= 0) continue
- stock = { ...stock, [g]: stock[g] - lose }
- rotted += lose
- }
- if (stock !== inv.stock) data.inventory.set({ ...inv, stock })
- }
- if (rotted > 0) resources.pantry.update((p) => ({ ...p, rotted: p.rotted + rotted }))
- }
-
- // The pantry's minute.
- if (t > 0 && t % 3600 === 0) {
- const p = resources.pantry.get()
- const warn = p.rotted >= 6 && p.rotted * 4 >= p.eaten && t - p.warned >= ROT_WARNING
- if (warn) {
- // What the town could make of food a minute with the crews it has, against what it ate: rot is the difference, not a want of granaries.
- let made = 0
- for (const { data } of queries.makers.each()) {
- const r = data.recipe.get()
- if (data.staff.get().assigned > 0 && (foods as ReadonlyArray<string>).includes(r.output)) made += (r.batch * 3600) / r.period
- }
- const cause = made > p.eaten * 1.5
- ? `the town makes about ${Math.round(made)} food a minute and eats ${p.eaten}: fewer fisheries, a smokehouse, or selling fish would stop the waste`
- : `a granary keeps fish and bread five times as long, and smoked fish keeps`
- write(resources.chronicle, t, `${counted(p.rotted, "fish or loaf", "fish and loaves")} rotted in store this minute: ${cause}.`, true)
- }
- resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: p.eaten, rottedLast: p.rotted, warned: warn ? t : p.warned })
- }
- }
-)
+export { Decay } from "./decay.ts"
diff --git a/src/game/systems/edits/apply-edits.ts b/src/game/systems/edits/apply-edits.ts
new file mode 100644
index 0000000..729eb49
--- /dev/null
+++ b/src/game/systems/edits/apply-edits.ts
@@ -0,0 +1,508 @@
+import { buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, RoleParts, rolesOf, StartParts, startOf, treeDraft, waterDraft } from "../../world/archetypes.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
+import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, stepsOf, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../../content/index.ts"
+import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../../world/grid.ts"
+import { inside } from "../../world/iso.ts"
+import { generate } from "../../world/mapgen.ts"
+import { Road, Water, Tree } from "../../schema.ts"
+import { Appeal, Building, Tile, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Toast, Treasury, Upgraded, Works, Edits, Selection } from "../../schema.ts"
+import { salvageOf, salvageText, withWorks } from "../../rules/salvage.ts"
+import { elapsed, rollWinters, termTicks, TileRead, useOf, write } from "../shared.ts"
+import type { Rules as RuleInputs } from "../../rules/config.ts"
+import { crownGap, foundedFate } from "../term/index.ts"
+
+export const unlocked = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }) =>
+ census.settlers + census.citizens >= kind.unlock.residents && census.citizens >= kind.unlock.citizens
+/** What a town still lacks before it can build `kind`, or `null` when it can. */
+export const lockReason = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }): string | null => {
+ const residents = census.settlers + census.citizens
+ if (residents < kind.unlock.residents) return `needs ${kind.unlock.residents} residents (the town has ${residents})`
+ if (census.citizens < kind.unlock.citizens) return `needs ${kind.unlock.citizens} citizens (the town has ${census.citizens})`
+ return null
+}
+
+/** What keeps a town from an upgrade now, or `null` when nothing does. */
+export const upgradeBlock = (up: Pick<Upgrade, "rank">, rank: number, rules: Pick<RuleInputs, "ranks">): string | null =>
+ rank >= up.rank ? null : `needs the town to be a ${rules.ranks[up.rank]!.title}`
+
+/** Samples of history a long reign keeps in full detail before it thins the older half. */
+const HISTORY_KEPT = 1200
+
+export const ApplyEdits = Game.System(
+ "Town/ApplyEdits",
+ {
+ queries: {
+ tiles: TileRead,
+ paved: Game.Query({ selection: { paved: Game.Query.read(Paved) } }),
+ parks: Game.Query({ selection: { park: Game.Query.write(Park) } }),
+ halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } }),
+ /** Whatever was built at a cost, standing or a site: what pulling it down gives back. */
+ built: Game.Query({
+ selection: { building: Game.Query.optional(Building), house: Game.Query.optional(House), site: Game.Query.optional(Site), paused: Game.Query.optional(Paused), upgraded: Game.Query.optional(Upgraded), works: Game.Query.optional(Works) }
+ }),
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] }),
+ rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),
+ upgradable: Game.Query({
+ selection: {
+ building: Game.Query.read(Building),
+ service: Game.Query.optional(Service),
+ upgraded: Game.Query.optional(Upgraded),
+ works: Game.Query.optional(Works),
+ site: Game.Query.optional(Site),
+ rising: Game.Query.optional(Rising)
+ }
+ })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ treasury: Game.System.writeResource(Treasury),
+ ledger: Game.System.writeResource(Ledger),
+ policy: Game.System.writeResource(Policy),
+ rng: Game.System.writeResource(Rng),
+ stock: Game.System.readResource(Stock),
+ census: Game.System.readResource(Census),
+ charter: Game.System.writeResource(Charter),
+ land: Game.System.writeResource(Land),
+ market: Game.System.writeResource(Market),
+ mood: Game.System.writeResource(Mood),
+ crown: Game.System.writeResource(Crown),
+ fate: Game.System.writeResource(Fate),
+ history: Game.System.writeResource(History),
+ chronicle: Game.System.writeResource(Chronicle),
+ guide: Game.System.writeResource(Guide),
+ appeal: Game.System.writeResource(Appeal),
+ pantry: Game.System.writeResource(Pantry),
+ fires: Game.System.writeResource(Fires)
+ },
+ events: { toast: Game.System.writeEvent(Toast), selection: Game.System.writeEvent(Selection) },
+ services: { edits: Game.System.service(Edits), rules: Game.System.service(Rules) },
+ commands: Game.System.commands(
+ Game.System.spawns(Building, House, Road, Park, Water, Tree, Rock),
+ Game.System.inserts(...StartParts, ...RoleParts, Paved, Paused, Works, TownHall, Status, Inventory),
+ Game.System.removes(Paused),
+ Game.System.despawns(Tile)
+ )
+ },
+ ({ queries, resources, events, services, commands }) => {
+ const rules = services.rules
+ const { kinds, home, goods, grounds, props, lands, sizes, trade, roadCost: ROAD_COST, paveCost: PAVE_COST } = rules
+
+ const queued = services.edits.snapshot()
+ if (queued.length === 0) return
+ const grid = new GridBuilder(resources.land.get().mask)
+ const rows = queries.tiles.each()
+ type Id = (typeof rows)[number]["entity"]["id"]
+ const entities = new Map<number, Id>()
+ for (const { entity, data } of rows) {
+ grid.claim(data.tile.get(), entity.id, useOf(data))
+ entities.set(entity.id, entity.id)
+ }
+ const halls = new Set<number>(queries.halls.each().map((row) => row.entity.id))
+ let coins = resources.treasury.get().coins
+ // Works begun in this step: they are in the world only once it ends, so a second click on the same building is refused here.
+ const begun = new Set<number>()
+ // What is left to spend this step: placing several things at once draws on the same stock.
+ const left: Record<string, number> = { ...resources.stock.get() }
+
+ const afford = (cost: Kind["cost"]): string | null => {
+ if (coins < cost.coins) return "Not enough coins"
+ for (const [g, n] of Object.entries(cost.materials)) if ((left[g] ?? 0) < (n ?? 0)) return `Not enough ${g}`
+ return null
+ }
+ const pay = (cost: Kind["cost"]) => {
+ coins -= cost.coins
+ for (const [g, n] of Object.entries(cost.materials)) left[g] = (left[g] ?? 0) - (n ?? 0)
+ }
+ /** Takes goods out of storage at once, fullest first. */
+ const take = (materials: Partial<Record<string, number>>) => {
+ for (const [g, n] of Object.entries(materials) as Array<[keyof Amounts, number]>) {
+ let owed = 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()
+ const n = Math.min(owed, inv.stock[g])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] - n } })
+ owed -= n
+ }
+ }
+ }
+ /** Puts goods into storage at once, where there is most room; returns how many found none. */
+ const stash = (materials: Partial<Record<string, number>>) => {
+ let lost = 0
+ for (const [g, n] of Object.entries(materials) as Array<[keyof Amounts, number]>) {
+ let owed = n
+ for (const { data } of [...queries.stores.each()].sort((a, b) => a.data.inventory.get().stock[g] - b.data.inventory.get().stock[g])) {
+ if (owed <= 0) break
+ const inv = data.inventory.get()
+ const k = Math.max(0, Math.min(owed, inv.cap - inv.stock[g]))
+ if (k > 0) data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] + k } })
+ left[g] = (left[g] ?? 0) + k
+ owed -= k
+ }
+ lost += owed
+ }
+ return lost
+ }
+ /** Fells the trees under a tile about to be built on. */
+ const fell = (tile: { x: number; y: number; size: number }) => {
+ for (const c of cellsOf(tile)) {
+ if (useAt(grid.value(), c.x, c.y) !== "tree") continue
+ const tree = entities.get(ownerAt(grid.value(), c.x, c.y))
+ const row = tree === undefined ? undefined : queries.tiles.get(tree)
+ if (row?.ok) commands.despawn(row.value.entity)
+ }
+ }
+ /**
+ * What this run queued, by id, with how to take it back: no query matches it
+ * before the next `applyDeferred()`, so pulling it down (or a new town) in
+ * the same step despawns it through the id `spawn` returned.
+ */
+ const queuedHere = new Map<number, () => void>()
+ /** Fells what stands on `tile`, spawns what `make` queues there, and claims the tile for it. */
+ const place = <Spawned extends Id>(tile: { x: number; y: number; size: number }, use: "building" | "house" | "road" | "park", make: () => Spawned): Spawned => {
+ fell(tile)
+ const id = make()
+ grid.claim(tile, id, use)
+ entities.set(id, id)
+ return id
+ }
+
+ const playing = () => resources.fate.get().state === "playing"
+ const t = elapsed(resources.time.get(), resources.charter.get())
+
+ edits: for (const edit of queued) {
+ if (edit.type !== "newTown" && edit.type !== "nextTerm" && edit.type !== "guide" && edit.type !== "guideOff" && !playing()) continue
+ switch (edit.type) {
+ case "building": {
+ const kind = kinds[edit.kind]
+ const tile = { ...edit.cell, size: kind.size }
+ if (!kind.buildable) break
+ if (!unlocked(kind, resources.census.get())) {
+ events.toast.emit(`${kind.title} ${lockReason(kind, resources.census.get())}`)
+ break
+ }
+ if (!canPlace(grid.value(), tile)) {
+ events.toast.emit("No room there")
+ break
+ }
+ const short = afford(kind.cost)
+ if (short) {
+ events.toast.emit(short)
+ break
+ }
+ pay(kind.cost)
+ const id = place(tile, "building", () => commands.spawn(buildingDraft(kind, edit.cell)))
+ queuedHere.set(id, () => commands.despawn(id))
+ commands.insert(id, startOf(kind), ...rolesOf(kind, rules))
+ if (edit.open) events.selection.emit({ select: id })
+ break
+ }
+ case "homes": {
+ let short: string | null = null
+ for (const cell of edit.cells) {
+ const tile = { ...cell, size: 1 }
+ if (!canPlace(grid.value(), tile)) continue
+ short = afford(home.cost)
+ if (short) break
+ pay(home.cost)
+ const id = place(tile, "house", () => commands.spawn(houseDraft(cell)))
+ queuedHere.set(id, () => commands.despawn(id))
+ commands.insert(id, ...houseStart(rules))
+ }
+ if (short) events.toast.emit(short)
+ break
+ }
+ case "roads": {
+ let short = false
+ for (const cell of edit.cells) {
+ const tile = { ...cell, size: 1 }
+ if (!canPlace(grid.value(), tile)) continue
+ if (coins < ROAD_COST) {
+ short = true
+ break
+ }
+ coins -= ROAD_COST
+ const id = place(tile, "road", () => commands.spawn(roadDraft(cell)))
+ queuedHere.set(id, () => commands.despawn(id))
+ }
+ if (short) events.toast.emit("Not enough coins")
+ break
+ }
+ case "pave": {
+ // Stone comes out of storage at once, fullest first.
+ const paved = new Set<number>(queries.paved.each().map((row) => row.entity.id))
+ let short: string | null = null
+ let stone = 0
+ for (const cell of edit.cells) {
+ if (!inside(cell.x, cell.y) || useAt(grid.value(), cell.x, cell.y) !== "road") continue
+ const road = entities.get(ownerAt(grid.value(), cell.x, cell.y))
+ if (road === undefined || paved.has(road)) continue
+ short = afford({ coins: PAVE_COST.coins, materials: { stone: PAVE_COST.stone } })
+ if (short) break
+ coins -= PAVE_COST.coins
+ left.stone = (left.stone ?? 0) - PAVE_COST.stone
+ stone += PAVE_COST.stone
+ paved.add(road)
+ commands.insert(road, Game.Command.entry(Paved, {}))
+ }
+ take({ stone })
+ if (short) events.toast.emit(short)
+ break
+ }
+ case "ground": {
+ // Park needs no road: it is laid at once, its materials straight out of storage.
+ const piece = grounds[edit.ground]
+ const parks = new Map(queries.parks.each().map((row) => [row.entity.id as number, row] as const))
+ let short: string | null = null
+ const spent: Record<string, number> = {}
+ for (const cell of edit.cells) {
+ const tile = { ...cell, size: 1 }
+ const relay = useAt(grid.value(), cell.x, cell.y) === "park" ? parks.get(ownerAt(grid.value(), cell.x, cell.y)) : undefined
+ if (relay ? relay.data.park.get().ground === edit.ground : !canPlace(grid.value(), tile)) continue
+ short = afford(piece.cost)
+ if (short) break
+ pay(piece.cost)
+ for (const [g, n] of Object.entries(piece.cost.materials)) spent[g] = (spent[g] ?? 0) + (n ?? 0)
+ if (relay) relay.data.park.set({ ...relay.data.park.get(), ground: edit.ground })
+ else {
+ const id = place(tile, "park", () => commands.spawn(parkDraft(cell, edit.ground)))
+ queuedHere.set(id, () => commands.despawn(id))
+ }
+ }
+ take(spent)
+ if (short) events.toast.emit(short)
+ break
+ }
+ case "prop": {
+ const piece = props[edit.prop]
+ if (!unlocked(piece, resources.census.get())) {
+ events.toast.emit(`${piece.title} needs a bigger town`)
+ break
+ }
+ const row = useAt(grid.value(), edit.cell.x, edit.cell.y) === "park"
+ ? queries.parks.each().find((r) => r.entity.id === ownerAt(grid.value(), edit.cell.x, edit.cell.y))
+ : undefined
+ if (!row) {
+ events.toast.emit("Lay park ground first")
+ break
+ }
+ if (row.data.park.get().prop === edit.prop) break
+ const short = afford(piece.cost)
+ if (short) {
+ events.toast.emit(short)
+ break
+ }
+ pay(piece.cost)
+ take(piece.cost.materials)
+ row.data.park.set({ ...row.data.park.get(), prop: edit.prop })
+ break
+ }
+ case "remove": {
+ if (!inside(edit.cell.x, edit.cell.y)) break
+ const use = useAt(grid.value(), edit.cell.x, edit.cell.y)
+ const owner = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))
+ if (owner === undefined || use === "water") break
+ // A rock goes only once it is quarried down to a worked face, and gives nothing more after.
+ if (use === "rock") {
+ const rock = queries.rocks.get(owner)
+ if (!rock.ok || rock.value.data.rock.get().amount > 1) {
+ events.toast.emit("Quarry it down first: only a worked face can be cleared")
+ break
+ }
+ }
+ if (halls.has(owner)) {
+ events.toast.emit("The town hall stays")
+ break
+ }
+ // A park's furnishing goes before its ground.
+ const furnished = use === "park" ? queries.parks.each().find((r) => r.entity.id === owner && r.data.park.get().prop !== "none") : undefined
+ if (furnished) {
+ furnished.data.park.set({ ...furnished.data.park.get(), prop: "none" })
+ break
+ }
+ // A building or a home: a fee, and part of its materials back (a site's, all of it).
+ const built = queries.built.get(owner)
+ if (built.ok && (built.value.data.building.present || built.value.data.house.present)) {
+ const b = built.value.data.building.value()
+ const own = salvageOf(b ? builtCost(kinds[b.kind], built.value.data.upgraded.value()?.level ?? 0) : home.cost, built.value.data.site.value()?.owed ?? null, rules)
+ const s = b ? withWorks(own, kinds[b.kind], built.value.data.works.value(), rules) : own
+ if (s.fee > 0 && coins < s.fee) {
+ events.toast.emit(`Pulling it down costs ${s.fee} coins`)
+ break
+ }
+ coins -= s.fee
+ const lost = stash(s.back)
+ const said = salvageText(s)
+ if (said !== "") events.toast.emit(`${built.value.data.site.present ? "Cancelled" : "Pulled down"} · ${said}${lost > 0 ? ` (${lost} found no room in storage)` : ""}`)
+ }
+ // A building's walkers and a farm's fields are its children, and go with it.
+ const gone = queries.tiles.get(owner)
+ if (gone.ok) commands.despawn(gone.value.entity)
+ else queuedHere.get(owner)?.()
+ queuedHere.delete(owner)
+ entities.delete(owner)
+ for (let k = 0; k < grid.owner.length; k++) {
+ if (grid.owner[k] === owner) {
+ grid.owner[k] = 0
+ grid.use[k] = "empty"
+ }
+ }
+ events.selection.emit({ clearIf: owner })
+ break
+ }
+ case "tax":
+ resources.policy.update((p) => ({ ...p, [edit.tier]: Math.max(TAX_STEPS[0], Math.min(TAX_STEPS.at(-1)!, Math.round(edit.rate))) }))
+ break
+ case "trade":
+ resources.policy.update((p) => ({
+ ...p,
+ sells: edit.mode === "sell" ? [...p.sells.filter((g) => g !== edit.good), edit.good] : p.sells.filter((g) => g !== edit.good),
+ buys: edit.mode === "buy" ? [...p.buys.filter((g) => g !== edit.good), edit.good] : p.buys.filter((g) => g !== edit.good),
+ loads: edit.amount === undefined ? p.loads : { ...p.loads, [edit.good]: Math.max(0, Math.min(rules.tradeLoad, Math.round(edit.amount))) }
+ }))
+ break
+ case "pause": {
+ const owner = ownerAt(grid.value(), edit.cell.x, edit.cell.y)
+ // A building stops work; a home is closed, and stands empty (see `Households`).
+ const id = entities.get(owner)
+ const row = id === undefined ? undefined : queries.built.get(id)
+ if (!row?.ok || halls.has(owner) || row.value.data.site.present || row.value.data.paused.present === edit.on) break
+ if (!row.value.data.building.present && !row.value.data.house.present) break
+ if (edit.on) commands.insert(row.value.entity, Game.Command.entry(Paused, {}))
+ else commands.remove(row.value.entity, Paused)
+ break
+ }
+ case "deliver": {
+ const c = resources.crown.get()
+ if (!c.open) break
+ if ((left[c.good] ?? 0) < c.amount) {
+ events.toast.emit(`Not enough ${goods[c.good].title}`)
+ break
+ }
+ let owed = c.amount
+ for (const { data } of [...queries.stores.each()].sort((a, b) => b.data.inventory.get().stock[c.good] - a.data.inventory.get().stock[c.good])) {
+ if (owed <= 0) break
+ const inv = data.inventory.get()
+ const take = Math.min(owed, inv.stock[c.good])
+ data.inventory.set({ ...inv, stock: { ...inv.stock, [c.good]: inv.stock[c.good] - take } })
+ owed -= take
+ }
+ left[c.good] = (left[c.good] ?? 0) - c.amount
+ coins += c.reward
+ resources.crown.set({ ...c, open: false, met: c.met + 1, streak: 0 })
+ write(resources.chronicle, t, `Sent the crown ${c.amount} ${goods[c.good].title}, for ${c.reward} coins.`)
+ events.toast.emit(`Sent · +${c.reward} coins`)
+ break
+ }
+ case "nextTerm": {
+ const f = resources.fate.get()
+ if (f.state !== "over") break
+ const charter = resources.charter.get()
+ const term = f.term + 1
+ const began = f.began + termTicks(charter, rules)
+ // The new term's winters, from the seed and the term, on the almanac's own stream; its first year is not spared.
+ const almanac = Random.make((charter.seed ^ 0x5a17c3 ^ Math.imul(term, 0x9e3779b1)) >>> 0)
+ const winters = [...charter.winters]
+ while (winters.length < term * rules.yearsPerTerm) winters.push(...rollWinters(() => almanac.next(), rules, false))
+ resources.charter.set({ ...charter, winters: winters.slice(0, term * rules.yearsPerTerm) })
+ // The crown starts the term afresh: an open request lapses, unfined, and its tally of requests met and missed begins again.
+ resources.crown.update((c) => ({ ...c, open: false, next: began + crownGap(charter, rules), met: 0, missed: 0, streak: 0 }))
+ resources.fate.set({ ...f, state: "playing", reason: "", term, began, debtSince: -1, revoltSince: -1, goalSince: -1, score: 0 })
+ // A long reign keeps its history in less detail the further back it is.
+ const samples = resources.history.get().samples
+ if (samples.length > HISTORY_KEPT) {
+ const half = Math.floor(samples.length / 2)
+ resources.history.set({ samples: [...samples.slice(0, half).filter((_, i) => i % 2 === 0), ...samples.slice(half)] })
+ }
+ write(resources.chronicle, t, `Term ${term}: the mayor stands for another ${charter.term} minutes.`)
+ break
+ }
+ case "upgrade": {
+ // The coins are paid now; carriers bring the materials while it goes on working (see `Works`).
+ if (!inside(edit.cell.x, edit.cell.y)) break
+ const id = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))
+ const row = id === undefined ? undefined : queries.upgradable.get(id)
+ if (!row?.ok) break
+ const { data } = row.value
+ const kind = kinds[data.building.get().kind]
+ const level = data.upgraded.value()?.level ?? 0
+ const up = nextUpgrade(kind, level)
+ if (!up || data.works.present || begun.has(row.value.entity.id) || data.site.present || data.rising.present) break
+ const blocked = upgradeBlock(up, resources.fate.get().rank, rules)
+ if (blocked) {
+ events.toast.emit(`${up.title} ${blocked}`)
+ break
+ }
+ if (coins < up.cost.coins) {
+ events.toast.emit("Not enough coins")
+ break
+ }
+ coins -= up.cost.coins
+ begun.add(row.value.entity.id)
+ const owed = amounts(up.cost.materials)
+ commands.insert(row.value.entity, Game.Command.entry(Works, { owed, total: total(owed), done: 0, level: (level + 1) as 1 | 2 }))
+ const was = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()
+ write(resources.chronicle, t, `Works begin on the ${was}: it is to be ${anA(up.title.toLowerCase())}.`)
+ events.toast.emit(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)
+ break
+ }
+ case "guide":
+ resources.guide.update((g) => {
+ const fresh = edit.done.filter((id) => !g.done.includes(id))
+ return fresh.length === 0 ? g : { ...g, done: [...g.done, ...fresh] }
+ })
+ break
+ case "guideOff":
+ resources.guide.update((g) => (g.off === edit.off ? g : { ...g, off: edit.off }))
+ break
+ case "reserve":
+ resources.policy.update((p) => ({ ...p, reserve: Math.max(0, Math.min(RESERVE_MAX, Math.round(edit.amount))) }))
+ break
+ case "newTown": {
+ for (const { entity } of rows) commands.despawn(entity)
+ for (const drop of queuedHere.values()) drop()
+ queuedHere.clear()
+ entities.clear()
+ const charter = edit.charter
+ const richness = lands[charter.land]
+ const land = generate(charter, rules)
+ for (const c of land.water) commands.spawn(waterDraft(c))
+ for (const tree of land.trees) commands.spawn(treeDraft(tree.cell, tree.growth))
+ for (const r of land.rocks) commands.spawn(rockDraft(r.cell, r.ore, r.amount))
+ for (const c of land.roads) commands.spawn(roadDraft(c))
+ const hall = kinds.townhall
+ const id = commands.spawn(buildingDraft(hall, land.hall))
+ commands.insert(id, ...rolesOf(hall, rules))
+ const stock: Amounts = amounts(richness.stock)
+ commands.insert(id, Game.Command.entry(TownHall, {}), Game.Command.entry(Status, "idle"), Game.Command.entry(Inventory, { stock, accepts: goodIds, cap: hall.holds?.cap ?? 60 }))
+ coins = richness.coins
+ const founded = resources.time.get().step
+ // The almanac: each year's winter, from the seed (on its own stream, so the land's randomness is untouched).
+ const almanac = Random.make((charter.seed ^ 0x5a17c3) >>> 0)
+ resources.charter.set({ ...charter, founded, winters: rollWinters(() => almanac.next(), rules) })
+ resources.appeal.set({ cells: [] })
+ resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 })
+ resources.fires.set({ fires: [], next: 1 })
+ // A new town starts the guide over, unless the mayor turned it off.
+ resources.guide.update((g) => ({ done: [], off: g.off }))
+ resources.land.set({ mask: land.mask, cells: land.cells })
+ resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0, admin: 0 })
+ resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve, loads: amounts(Object.fromEntries(goodIds.map((g) => [g, rules.tradeLoad]))) })
+ resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })
+ resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0, grudge: 0, memory: 0 })
+ resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter, rules), met: 0, missed: 0, streak: 0, snubs: [] })
+ resources.fate.set(foundedFate())
+ resources.history.set({ samples: [] })
+ resources.chronicle.set({
+ lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.`, alarm: false, at: null }]
+ })
+ resources.rng.set(Random.seed(charter.seed))
+ events.selection.emit({ clear: true })
+ // Nothing else this step: the new land is not on the grid yet.
+ break edits
+ }
+ }
+ }
+ resources.treasury.set({ coins })
+ }
+)
diff --git a/src/game/systems/edits/index.ts b/src/game/systems/edits/index.ts
index 2fe2c0d..1f7f676 100644
--- a/src/game/systems/edits/index.ts
+++ b/src/game/systems/edits/index.ts
@@ -6,511 +6,4 @@
* carried to the site afterwards. Upgrading a building is paid at once.
* Once the term has ended, only a new town, or another term, is taken.
*/
-import { buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, RoleParts, rolesOf, StartParts, startOf, treeDraft, waterDraft } from "../../world/archetypes.ts"
-import * as Random from "@typeonce/ritmo-math/Random"
-import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, stepsOf, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../../content/index.ts"
-import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../../world/grid.ts"
-import { inside } from "../../world/iso.ts"
-import { generate } from "../../world/mapgen.ts"
-import { Road, Water, Tree } from "../../schema.ts"
-import { Appeal, Building, Tile, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Toast, Treasury, Upgraded, Works, Edits, Selection } from "../../schema.ts"
-import { salvageOf, salvageText, withWorks } from "../../rules/salvage.ts"
-import { elapsed, rollWinters, termTicks, TileRead, useOf, write } from "../shared.ts"
-import type { Rules as RuleInputs } from "../../rules/config.ts"
-import { crownGap, foundedFate } from "../term/index.ts"
-
-export const unlocked = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }) =>
- census.settlers + census.citizens >= kind.unlock.residents && census.citizens >= kind.unlock.citizens
-/** What a town still lacks before it can build `kind`, or `null` when it can. */
-export const lockReason = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }): string | null => {
- const residents = census.settlers + census.citizens
- if (residents < kind.unlock.residents) return `needs ${kind.unlock.residents} residents (the town has ${residents})`
- if (census.citizens < kind.unlock.citizens) return `needs ${kind.unlock.citizens} citizens (the town has ${census.citizens})`
- return null
-}
-
-/** What keeps a town from an upgrade now, or `null` when nothing does. */
-export const upgradeBlock = (up: Pick<Upgrade, "rank">, rank: number, rules: Pick<RuleInputs, "ranks">): string | null =>
- rank >= up.rank ? null : `needs the town to be a ${rules.ranks[up.rank]!.title}`
-
-/** Samples of history a long reign keeps in full detail before it thins the older half. */
-const HISTORY_KEPT = 1200
-
-export const ApplyEdits = Game.System(
- "Town/ApplyEdits",
- {
- queries: {
- tiles: TileRead,
- paved: Game.Query({ selection: { paved: Game.Query.read(Paved) } }),
- parks: Game.Query({ selection: { park: Game.Query.write(Park) } }),
- halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } }),
- /** Whatever was built at a cost, standing or a site: what pulling it down gives back. */
- built: Game.Query({
- selection: { building: Game.Query.optional(Building), house: Game.Query.optional(House), site: Game.Query.optional(Site), paused: Game.Query.optional(Paused), upgraded: Game.Query.optional(Upgraded), works: Game.Query.optional(Works) }
- }),
- stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] }),
- rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),
- upgradable: Game.Query({
- selection: {
- building: Game.Query.read(Building),
- service: Game.Query.optional(Service),
- upgraded: Game.Query.optional(Upgraded),
- works: Game.Query.optional(Works),
- site: Game.Query.optional(Site),
- rising: Game.Query.optional(Rising)
- }
- })
- },
- resources: {
- time: Game.System.readResource(Time),
- treasury: Game.System.writeResource(Treasury),
- ledger: Game.System.writeResource(Ledger),
- policy: Game.System.writeResource(Policy),
- rng: Game.System.writeResource(Rng),
- stock: Game.System.readResource(Stock),
- census: Game.System.readResource(Census),
- charter: Game.System.writeResource(Charter),
- land: Game.System.writeResource(Land),
- market: Game.System.writeResource(Market),
- mood: Game.System.writeResource(Mood),
- crown: Game.System.writeResource(Crown),
- fate: Game.System.writeResource(Fate),
- history: Game.System.writeResource(History),
- chronicle: Game.System.writeResource(Chronicle),
- guide: Game.System.writeResource(Guide),
- appeal: Game.System.writeResource(Appeal),
- pantry: Game.System.writeResource(Pantry),
- fires: Game.System.writeResource(Fires)
- },
- events: { toast: Game.System.writeEvent(Toast), selection: Game.System.writeEvent(Selection) },
- services: { edits: Game.System.service(Edits), rules: Game.System.service(Rules) },
- commands: Game.System.commands(
- Game.System.spawns(Building, House, Road, Park, Water, Tree, Rock),
- Game.System.inserts(...StartParts, ...RoleParts, Paved, Paused, Works, TownHall, Status, Inventory),
- Game.System.removes(Paused),
- Game.System.despawns(Tile)
- )
- },
- ({ queries, resources, events, services, commands }) => {
- const rules = services.rules
- const { kinds, home, goods, grounds, props, lands, sizes, trade, roadCost: ROAD_COST, paveCost: PAVE_COST } = rules
-
- const queued = services.edits.snapshot()
- if (queued.length === 0) return
- const grid = new GridBuilder(resources.land.get().mask)
- const rows = queries.tiles.each()
- type Id = (typeof rows)[number]["entity"]["id"]
- const entities = new Map<number, Id>()
- for (const { entity, data } of rows) {
- grid.claim(data.tile.get(), entity.id, useOf(data))
- entities.set(entity.id, entity.id)
- }
- const halls = new Set<number>(queries.halls.each().map((row) => row.entity.id))
- let coins = resources.treasury.get().coins
- // Works begun in this step: they are in the world only once it ends, so a second click on the same building is refused here.
- const begun = new Set<number>()
- // What is left to spend this step: placing several things at once draws on the same stock.
- const left: Record<string, number> = { ...resources.stock.get() }
-
- const afford = (cost: Kind["cost"]): string | null => {
- if (coins < cost.coins) return "Not enough coins"
- for (const [g, n] of Object.entries(cost.materials)) if ((left[g] ?? 0) < (n ?? 0)) return `Not enough ${g}`
- return null
- }
- const pay = (cost: Kind["cost"]) => {
- coins -= cost.coins
- for (const [g, n] of Object.entries(cost.materials)) left[g] = (left[g] ?? 0) - (n ?? 0)
- }
- /** Takes goods out of storage at once, fullest first. */
- const take = (materials: Partial<Record<string, number>>) => {
- for (const [g, n] of Object.entries(materials) as Array<[keyof Amounts, number]>) {
- let owed = 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()
- const n = Math.min(owed, inv.stock[g])
- data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] - n } })
- owed -= n
- }
- }
- }
- /** Puts goods into storage at once, where there is most room; returns how many found none. */
- const stash = (materials: Partial<Record<string, number>>) => {
- let lost = 0
- for (const [g, n] of Object.entries(materials) as Array<[keyof Amounts, number]>) {
- let owed = n
- for (const { data } of [...queries.stores.each()].sort((a, b) => a.data.inventory.get().stock[g] - b.data.inventory.get().stock[g])) {
- if (owed <= 0) break
- const inv = data.inventory.get()
- const k = Math.max(0, Math.min(owed, inv.cap - inv.stock[g]))
- if (k > 0) data.inventory.set({ ...inv, stock: { ...inv.stock, [g]: inv.stock[g] + k } })
- left[g] = (left[g] ?? 0) + k
- owed -= k
- }
- lost += owed
- }
- return lost
- }
- /** Fells the trees under a tile about to be built on. */
- const fell = (tile: { x: number; y: number; size: number }) => {
- for (const c of cellsOf(tile)) {
- if (useAt(grid.value(), c.x, c.y) !== "tree") continue
- const tree = entities.get(ownerAt(grid.value(), c.x, c.y))
- const row = tree === undefined ? undefined : queries.tiles.get(tree)
- if (row?.ok) commands.despawn(row.value.entity)
- }
- }
- /**
- * What this run queued, by id, with how to take it back: no query matches it
- * before the next `applyDeferred()`, so pulling it down (or a new town) in
- * the same step despawns it through the id `spawn` returned.
- */
- const queuedHere = new Map<number, () => void>()
- /** Fells what stands on `tile`, spawns what `make` queues there, and claims the tile for it. */
- const place = <Spawned extends Id>(tile: { x: number; y: number; size: number }, use: "building" | "house" | "road" | "park", make: () => Spawned): Spawned => {
- fell(tile)
- const id = make()
- grid.claim(tile, id, use)
- entities.set(id, id)
- return id
- }
-
- const playing = () => resources.fate.get().state === "playing"
- const t = elapsed(resources.time.get(), resources.charter.get())
-
- edits: for (const edit of queued) {
- if (edit.type !== "newTown" && edit.type !== "nextTerm" && edit.type !== "guide" && edit.type !== "guideOff" && !playing()) continue
- switch (edit.type) {
- case "building": {
- const kind = kinds[edit.kind]
- const tile = { ...edit.cell, size: kind.size }
- if (!kind.buildable) break
- if (!unlocked(kind, resources.census.get())) {
- events.toast.emit(`${kind.title} ${lockReason(kind, resources.census.get())}`)
- break
- }
- if (!canPlace(grid.value(), tile)) {
- events.toast.emit("No room there")
- break
- }
- const short = afford(kind.cost)
- if (short) {
- events.toast.emit(short)
- break
- }
- pay(kind.cost)
- const id = place(tile, "building", () => commands.spawn(buildingDraft(kind, edit.cell)))
- queuedHere.set(id, () => commands.despawn(id))
- commands.insert(id, startOf(kind), ...rolesOf(kind, rules))
- if (edit.open) events.selection.emit({ select: id })
- break
- }
- case "homes": {
- let short: string | null = null
- for (const cell of edit.cells) {
- const tile = { ...cell, size: 1 }
- if (!canPlace(grid.value(), tile)) continue
- short = afford(home.cost)
- if (short) break
- pay(home.cost)
- const id = place(tile, "house", () => commands.spawn(houseDraft(cell)))
- queuedHere.set(id, () => commands.despawn(id))
- commands.insert(id, ...houseStart(rules))
- }
- if (short) events.toast.emit(short)
- break
- }
- case "roads": {
- let short = false
- for (const cell of edit.cells) {
- const tile = { ...cell, size: 1 }
- if (!canPlace(grid.value(), tile)) continue
- if (coins < ROAD_COST) {
- short = true
- break
- }
- coins -= ROAD_COST
- const id = place(tile, "road", () => commands.spawn(roadDraft(cell)))
- queuedHere.set(id, () => commands.despawn(id))
- }
- if (short) events.toast.emit("Not enough coins")
- break
- }
- case "pave": {
- // Stone comes out of storage at once, fullest first.
- const paved = new Set<number>(queries.paved.each().map((row) => row.entity.id))
- let short: string | null = null
- let stone = 0
- for (const cell of edit.cells) {
- if (!inside(cell.x, cell.y) || useAt(grid.value(), cell.x, cell.y) !== "road") continue
- const road = entities.get(ownerAt(grid.value(), cell.x, cell.y))
- if (road === undefined || paved.has(road)) continue
- short = afford({ coins: PAVE_COST.coins, materials: { stone: PAVE_COST.stone } })
- if (short) break
- coins -= PAVE_COST.coins
- left.stone = (left.stone ?? 0) - PAVE_COST.stone
- stone += PAVE_COST.stone
- paved.add(road)
- commands.insert(road, Game.Command.entry(Paved, {}))
- }
- take({ stone })
- if (short) events.toast.emit(short)
- break
- }
- case "ground": {
- // Park needs no road: it is laid at once, its materials straight out of storage.
- const piece = grounds[edit.ground]
- const parks = new Map(queries.parks.each().map((row) => [row.entity.id as number, row] as const))
- let short: string | null = null
- const spent: Record<string, number> = {}
- for (const cell of edit.cells) {
- const tile = { ...cell, size: 1 }
- const relay = useAt(grid.value(), cell.x, cell.y) === "park" ? parks.get(ownerAt(grid.value(), cell.x, cell.y)) : undefined
- if (relay ? relay.data.park.get().ground === edit.ground : !canPlace(grid.value(), tile)) continue
- short = afford(piece.cost)
- if (short) break
- pay(piece.cost)
- for (const [g, n] of Object.entries(piece.cost.materials)) spent[g] = (spent[g] ?? 0) + (n ?? 0)
- if (relay) relay.data.park.set({ ...relay.data.park.get(), ground: edit.ground })
- else {
- const id = place(tile, "park", () => commands.spawn(parkDraft(cell, edit.ground)))
- queuedHere.set(id, () => commands.despawn(id))
- }
- }
- take(spent)
- if (short) events.toast.emit(short)
- break
- }
- case "prop": {
- const piece = props[edit.prop]
- if (!unlocked(piece, resources.census.get())) {
- events.toast.emit(`${piece.title} needs a bigger town`)
- break
- }
- const row = useAt(grid.value(), edit.cell.x, edit.cell.y) === "park"
- ? queries.parks.each().find((r) => r.entity.id === ownerAt(grid.value(), edit.cell.x, edit.cell.y))
- : undefined
- if (!row) {
- events.toast.emit("Lay park ground first")
- break
- }
- if (row.data.park.get().prop === edit.prop) break
- const short = afford(piece.cost)
- if (short) {
- events.toast.emit(short)
- break
- }
- pay(piece.cost)
- take(piece.cost.materials)
- row.data.park.set({ ...row.data.park.get(), prop: edit.prop })
- break
- }
- case "remove": {
- if (!inside(edit.cell.x, edit.cell.y)) break
- const use = useAt(grid.value(), edit.cell.x, edit.cell.y)
- const owner = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))
- if (owner === undefined || use === "water") break
- // A rock goes only once it is quarried down to a worked face, and gives nothing more after.
- if (use === "rock") {
- const rock = queries.rocks.get(owner)
- if (!rock.ok || rock.value.data.rock.get().amount > 1) {
- events.toast.emit("Quarry it down first: only a worked face can be cleared")
- break
- }
- }
- if (halls.has(owner)) {
- events.toast.emit("The town hall stays")
- break
- }
- // A park's furnishing goes before its ground.
- const furnished = use === "park" ? queries.parks.each().find((r) => r.entity.id === owner && r.data.park.get().prop !== "none") : undefined
- if (furnished) {
- furnished.data.park.set({ ...furnished.data.park.get(), prop: "none" })
- break
- }
- // A building or a home: a fee, and part of its materials back (a site's, all of it).
- const built = queries.built.get(owner)
- if (built.ok && (built.value.data.building.present || built.value.data.house.present)) {
- const b = built.value.data.building.value()
- const own = salvageOf(b ? builtCost(kinds[b.kind], built.value.data.upgraded.value()?.level ?? 0) : home.cost, built.value.data.site.value()?.owed ?? null, rules)
- const s = b ? withWorks(own, kinds[b.kind], built.value.data.works.value(), rules) : own
- if (s.fee > 0 && coins < s.fee) {
- events.toast.emit(`Pulling it down costs ${s.fee} coins`)
- break
- }
- coins -= s.fee
- const lost = stash(s.back)
- const said = salvageText(s)
- if (said !== "") events.toast.emit(`${built.value.data.site.present ? "Cancelled" : "Pulled down"} · ${said}${lost > 0 ? ` (${lost} found no room in storage)` : ""}`)
- }
- // A building's walkers and a farm's fields are its children, and go with it.
- const gone = queries.tiles.get(owner)
- if (gone.ok) commands.despawn(gone.value.entity)
- else queuedHere.get(owner)?.()
- queuedHere.delete(owner)
- entities.delete(owner)
- for (let k = 0; k < grid.owner.length; k++) {
- if (grid.owner[k] === owner) {
- grid.owner[k] = 0
- grid.use[k] = "empty"
- }
- }
- events.selection.emit({ clearIf: owner })
- break
- }
- case "tax":
- resources.policy.update((p) => ({ ...p, [edit.tier]: Math.max(TAX_STEPS[0], Math.min(TAX_STEPS.at(-1)!, Math.round(edit.rate))) }))
- break
- case "trade":
- resources.policy.update((p) => ({
- ...p,
- sells: edit.mode === "sell" ? [...p.sells.filter((g) => g !== edit.good), edit.good] : p.sells.filter((g) => g !== edit.good),
- buys: edit.mode === "buy" ? [...p.buys.filter((g) => g !== edit.good), edit.good] : p.buys.filter((g) => g !== edit.good),
- loads: edit.amount === undefined ? p.loads : { ...p.loads, [edit.good]: Math.max(0, Math.min(rules.tradeLoad, Math.round(edit.amount))) }
- }))
- break
- case "pause": {
- const owner = ownerAt(grid.value(), edit.cell.x, edit.cell.y)
- // A building stops work; a home is closed, and stands empty (see `Households`).
- const id = entities.get(owner)
- const row = id === undefined ? undefined : queries.built.get(id)
- if (!row?.ok || halls.has(owner) || row.value.data.site.present || row.value.data.paused.present === edit.on) break
- if (!row.value.data.building.present && !row.value.data.house.present) break
- if (edit.on) commands.insert(row.value.entity, Game.Command.entry(Paused, {}))
- else commands.remove(row.value.entity, Paused)
- break
- }
- case "deliver": {
- const c = resources.crown.get()
- if (!c.open) break
- if ((left[c.good] ?? 0) < c.amount) {
- events.toast.emit(`Not enough ${goods[c.good].title}`)
- break
- }
- let owed = c.amount
- for (const { data } of [...queries.stores.each()].sort((a, b) => b.data.inventory.get().stock[c.good] - a.data.inventory.get().stock[c.good])) {
- if (owed <= 0) break
- const inv = data.inventory.get()
- const take = Math.min(owed, inv.stock[c.good])
- data.inventory.set({ ...inv, stock: { ...inv.stock, [c.good]: inv.stock[c.good] - take } })
- owed -= take
- }
- left[c.good] = (left[c.good] ?? 0) - c.amount
- coins += c.reward
- resources.crown.set({ ...c, open: false, met: c.met + 1, streak: 0 })
- write(resources.chronicle, t, `Sent the crown ${c.amount} ${goods[c.good].title}, for ${c.reward} coins.`)
- events.toast.emit(`Sent · +${c.reward} coins`)
- break
- }
- case "nextTerm": {
- const f = resources.fate.get()
- if (f.state !== "over") break
- const charter = resources.charter.get()
- const term = f.term + 1
- const began = f.began + termTicks(charter, rules)
- // The new term's winters, from the seed and the term, on the almanac's own stream; its first year is not spared.
- const almanac = Random.make((charter.seed ^ 0x5a17c3 ^ Math.imul(term, 0x9e3779b1)) >>> 0)
- const winters = [...charter.winters]
- while (winters.length < term * rules.yearsPerTerm) winters.push(...rollWinters(() => almanac.next(), rules, false))
- resources.charter.set({ ...charter, winters: winters.slice(0, term * rules.yearsPerTerm) })
- // The crown starts the term afresh: an open request lapses, unfined, and its tally of requests met and missed begins again.
- resources.crown.update((c) => ({ ...c, open: false, next: began + crownGap(charter, rules), met: 0, missed: 0, streak: 0 }))
- resources.fate.set({ ...f, state: "playing", reason: "", term, began, debtSince: -1, revoltSince: -1, goalSince: -1, score: 0 })
- // A long reign keeps its history in less detail the further back it is.
- const samples = resources.history.get().samples
- if (samples.length > HISTORY_KEPT) {
- const half = Math.floor(samples.length / 2)
- resources.history.set({ samples: [...samples.slice(0, half).filter((_, i) => i % 2 === 0), ...samples.slice(half)] })
- }
- write(resources.chronicle, t, `Term ${term}: the mayor stands for another ${charter.term} minutes.`)
- break
- }
- case "upgrade": {
- // The coins are paid now; carriers bring the materials while it goes on working (see `Works`).
- if (!inside(edit.cell.x, edit.cell.y)) break
- const id = entities.get(ownerAt(grid.value(), edit.cell.x, edit.cell.y))
- const row = id === undefined ? undefined : queries.upgradable.get(id)
- if (!row?.ok) break
- const { data } = row.value
- const kind = kinds[data.building.get().kind]
- const level = data.upgraded.value()?.level ?? 0
- const up = nextUpgrade(kind, level)
- if (!up || data.works.present || begun.has(row.value.entity.id) || data.site.present || data.rising.present) break
- const blocked = upgradeBlock(up, resources.fate.get().rank, rules)
- if (blocked) {
- events.toast.emit(`${up.title} ${blocked}`)
- break
- }
- if (coins < up.cost.coins) {
- events.toast.emit("Not enough coins")
- break
- }
- coins -= up.cost.coins
- begun.add(row.value.entity.id)
- const owed = amounts(up.cost.materials)
- commands.insert(row.value.entity, Game.Command.entry(Works, { owed, total: total(owed), done: 0, level: (level + 1) as 1 | 2 }))
- const was = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()
- write(resources.chronicle, t, `Works begin on the ${was}: it is to be ${anA(up.title.toLowerCase())}.`)
- events.toast.emit(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)
- break
- }
- case "guide":
- resources.guide.update((g) => {
- const fresh = edit.done.filter((id) => !g.done.includes(id))
- return fresh.length === 0 ? g : { ...g, done: [...g.done, ...fresh] }
- })
- break
- case "guideOff":
- resources.guide.update((g) => (g.off === edit.off ? g : { ...g, off: edit.off }))
- break
- case "reserve":
- resources.policy.update((p) => ({ ...p, reserve: Math.max(0, Math.min(RESERVE_MAX, Math.round(edit.amount))) }))
- break
- case "newTown": {
- for (const { entity } of rows) commands.despawn(entity)
- for (const drop of queuedHere.values()) drop()
- queuedHere.clear()
- entities.clear()
- const charter = edit.charter
- const richness = lands[charter.land]
- const land = generate(charter, rules)
- for (const c of land.water) commands.spawn(waterDraft(c))
- for (const tree of land.trees) commands.spawn(treeDraft(tree.cell, tree.growth))
- for (const r of land.rocks) commands.spawn(rockDraft(r.cell, r.ore, r.amount))
- for (const c of land.roads) commands.spawn(roadDraft(c))
- const hall = kinds.townhall
- const id = commands.spawn(buildingDraft(hall, land.hall))
- commands.insert(id, ...rolesOf(hall, rules))
- const stock: Amounts = amounts(richness.stock)
- commands.insert(id, Game.Command.entry(TownHall, {}), Game.Command.entry(Status, "idle"), Game.Command.entry(Inventory, { stock, accepts: goodIds, cap: hall.holds?.cap ?? 60 }))
- coins = richness.coins
- const founded = resources.time.get().step
- // The almanac: each year's winter, from the seed (on its own stream, so the land's randomness is untouched).
- const almanac = Random.make((charter.seed ^ 0x5a17c3) >>> 0)
- resources.charter.set({ ...charter, founded, winters: rollWinters(() => almanac.next(), rules) })
- resources.appeal.set({ cells: [] })
- resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 })
- resources.fires.set({ fires: [], next: 1 })
- // A new town starts the guide over, unless the mayor turned it off.
- resources.guide.update((g) => ({ done: [], off: g.off }))
- resources.land.set({ mask: land.mask, cells: land.cells })
- resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0, admin: 0 })
- resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve, loads: amounts(Object.fromEntries(goodIds.map((g) => [g, rules.tradeLoad]))) })
- resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })
- resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0, grudge: 0, memory: 0 })
- resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter, rules), met: 0, missed: 0, streak: 0, snubs: [] })
- resources.fate.set(foundedFate())
- resources.history.set({ samples: [] })
- resources.chronicle.set({
- lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.`, alarm: false, at: null }]
- })
- resources.rng.set(Random.seed(charter.seed))
- events.selection.emit({ clear: true })
- // Nothing else this step: the new land is not on the grid yet.
- break edits
- }
- }
- }
- resources.treasury.set({ coins })
- }
-)
+export { ApplyEdits, lockReason, unlocked, upgradeBlock } from "./apply-edits.ts"
diff --git a/src/game/systems/hazards/appraise.ts b/src/game/systems/hazards/appraise.ts
new file mode 100644
index 0000000..c997033
--- /dev/null
+++ b/src/game/systems/hazards/appraise.ts
@@ -0,0 +1,45 @@
+import { every } from "../../content/index.ts"
+import { appealGrid, buildingSource, homeSource, landSource, parkSources, type AppealSource } from "../../world/appeal.ts"
+import { Appeal, Building, Condition, Game, Rules, House, Park, Paused, Paved, Rising, Road, Ruin, Site, Tile, Time, Tree, Upgraded, Water } from "../../schema.ts"
+
+/** Reckons every cell's desirability, every `appeal.every` steps (and at once when there is none yet). */
+export const Appraise = Game.System(
+ "Town/Appraise",
+ {
+ queries: {
+ buildings: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building), upgraded: Game.Query.optional(Upgraded) }, without: [Site, Rising] }),
+ trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),
+ water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),
+ paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),
+ parks: Game.Query({ selection: { tile: Game.Query.read(Tile), park: Game.Query.read(Park) } }),
+ roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),
+ ruins: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Ruin] }),
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition), house: Game.Query.read(House), closed: Game.Query.optional(Paused) }, without: [Site, Rising] })
+ },
+ resources: { time: Game.System.readResource(Time), appeal: Game.System.writeResource(Appeal) },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+ const { appeal, condition: wear } = rules
+
+ if (!every(resources.time.get(), appeal.every) && resources.appeal.get().cells.length > 0) return
+ const sources: Array<AppealSource> = []
+ for (const { data } of queries.buildings.each()) {
+ const s = buildingSource(data.building.get().kind, data.tile.get(), rules, data.upgraded.value()?.level ?? 0)
+ if (s) sources.push(s)
+ }
+ for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get(), rules))
+ for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get(), rules))
+ for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get(), rules))
+ const roads = new Set(queries.roads.each().map(({ data }) => `${data.tile.get().x},${data.tile.get().y}`))
+ sources.push(...parkSources(queries.parks.each().map(({ data }) => ({ ...data.tile.get(), ...data.park.get() })), (x, y) => roads.has(`${x},${y}`), rules))
+ for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get(), rules))
+ for (const { data } of queries.homes.each()) {
+ if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get(), rules))
+ const fine = data.closed.present ? null : homeSource(data.house.get().tier, data.tile.get(), rules)
+ if (fine) sources.push(fine)
+ }
+ resources.appeal.set({ cells: appealGrid(sources, rules) })
+ }
+)
diff --git a/src/game/systems/hazards/douse.ts b/src/game/systems/hazards/douse.ts
new file mode 100644
index 0000000..6c38762
--- /dev/null
+++ b/src/game/systems/hazards/douse.ts
@@ -0,0 +1,42 @@
+import { ruinDraft } from "../../world/archetypes.ts"
+import { Burning, Fires, Game, House, Rescue, Route, Ruin, Tile } from "../../schema.ts"
+
+const BurningRead = Game.Query({ selection: { tile: Game.Query.read(Tile), burning: Game.Query.read(Burning), house: Game.Query.optional(House) } })
+
+/**
+ * A firefighter at the blaze puts it out: the house is lost, but the fire
+ * goes no further. Then the firefighter walks back to the watch.
+ */
+export const Douse = Game.System(
+ "Town/Douse",
+ {
+ queries: { crews: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.write(Rescue) } }), burning: BurningRead },
+ resources: { fires: Game.System.writeResource(Fires) },
+ commands: Game.System.commands(Game.System.spawns(Ruin), Game.System.despawns(Rescue, Burning))
+ },
+ ({ queries, resources, commands }) => {
+ for (const { entity, data } of queries.crews.each()) {
+ const route = data.route.get()
+ const rescue = data.rescue.get()
+ const arrived = route.index >= route.cells.length - 1
+ if (!arrived) continue
+ if (rescue.back) {
+ commands.despawn(entity)
+ continue
+ }
+ const target = queries.burning.getHandle(rescue.target)
+ if (target.ok) {
+ const b = target.value.data.burning.get()
+ commands.despawn(target.value.entity)
+ commands.spawn(ruinDraft(target.value.data.tile.get(), "burnt"))
+ const house = target.value.data.house.present
+ resources.fires.update((f) => ({
+ ...f,
+ fires: f.fires.map((x) => (x.id === b.fire ? { ...x, homes: x.homes + (house ? 1 : 0), buildings: x.buildings + (house ? 0 : 1) } : x))
+ }))
+ }
+ data.route.set({ cells: [...route.cells].reverse(), index: 0, step: 0 })
+ data.rescue.set({ ...rescue, back: true })
+ }
+ }
+)
diff --git a/src/game/systems/hazards/hazards.ts b/src/game/systems/hazards/hazards.ts
new file mode 100644
index 0000000..e766962
--- /dev/null
+++ b/src/game/systems/hazards/hazards.ts
@@ -0,0 +1,267 @@
+import { near, riskIncrements } from "../../rules/risks.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
+import { appealAt } from "../../world/appeal.ts"
+import { ruinDraft } from "../../world/archetypes.ts"
+import { goodIds, risk, upgradeAt, type GoodId } from "../../content/index.ts"
+import { doors, nearest, pathTo, reach, useAt } from "../../world/grid.ts"
+import { counted, placeName, type Landmark } from "../../world/places.ts"
+import type { Point } from "../../world/iso.ts"
+import { Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Rules, Grid, House, Inventory, Mood, Paused, Rescue, Rising, Risk, Rng, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Treasury, Upgraded, WalkerOf } from "../../schema.ts"
+import { elapsed, seasonAt, write } from "../shared.ts"
+
+/** The risks are reckoned this often (once a second). */
+export const RISK_TICKS = 60
+
+export const Hazards = Game.System(
+ "Town/Hazards",
+ {
+ queries: {
+ cared: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ risk: Game.Query.write(Risk),
+ condition: Game.Query.read(Condition),
+ house: Game.Query.optional(House),
+ building: Game.Query.optional(Building),
+ sick: Game.Query.optional(Sick),
+ burning: Game.Query.optional(Burning),
+ paused: Game.Query.optional(Paused)
+ },
+ without: [Site, Rising]
+ }),
+ sickness: Game.Query({ selection: { sick: Game.Query.write(Sick) } }),
+ blazes: Game.Query({ selection: { burning: Game.Query.write(Burning) } }),
+ landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
+ watches: Game.Query({
+ selection: { tile: Game.Query.read(Tile), service: Game.Query.read(Service), staff: Game.Query.read(Staff), upgraded: Game.Query.optional(Upgraded) },
+ without: [Site, Rising, Burning]
+ }),
+ crews: Game.Query({ selection: { rescue: Game.Query.read(Rescue), home: Game.Query.readRelation(WalkerOf) } }),
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ grid: Game.System.readResource(Grid),
+ appeal: Game.System.readResource(Appeal),
+ mood: Game.System.readResource(Mood),
+ rng: Game.System.writeResource(Rng),
+ treasury: Game.System.writeResource(Treasury),
+ fires: Game.System.writeResource(Fires),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(
+ Game.System.spawns(Ruin, Rescue),
+ Game.System.inserts(Burning, Sick),
+ Game.System.removes(Sick),
+ Game.System.despawns(Tile),
+ Game.System.relates(WalkerOf)
+ )
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { kinds, goods, risk, winters, riskMax: RISK_MAX, riskTicks: RISK_TICKS } = rules
+
+ const tick = resources.time.get().step
+ if (tick % RISK_TICKS !== 0) return
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ const grid = resources.grid.get()
+ const cells = resources.appeal.get().cells
+ const approval = resources.mood.get().approval
+ const season = seasonAt(t, charter, rules)
+ const heating = season.severity !== null && winters[season.severity].heating
+ const random = Random.draw(resources.rng)
+ const news = (text: string, at: Point | null = null) => write(resources.chronicle, t, text, true, at)
+ const landmarks: Array<Landmark> = queries.landmarks.each().map(({ data }) => ({ kind: data.building.get().kind, ...data.tile.get() }))
+ const where = (cell: Point) => placeName(landmarks, cell)
+ const fires = { ...resources.fires.get(), fires: resources.fires.get().fires.map((f) => ({ ...f })) }
+
+ const rows = queries.cared.each()
+ const hot = rows.filter(({ data }) => {
+ const b = data.building.value()
+ return b !== undefined && kinds[b.kind].hot === true && !data.burning.present
+ }).map(({ data }) => data.tile.get())
+ const dusty = landmarks.filter((l) => kinds[l.kind].dusty)
+ const waterNear = (tile: { readonly x: number; readonly y: number }) => {
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, tile.x + dx, tile.y + dy) === "water") return true
+ return false
+ }
+ const sickNow = rows.filter(({ data }) => data.sick.present).length
+
+ /** Turns a home or building into a ruin. */
+ const ruin = (row: (typeof rows)[number], cause: "burnt" | "collapsed" | "derelict") => {
+ commands.despawn(row.entity)
+ commands.spawn(ruinDraft(row.data.tile.get(), cause))
+ }
+ const lost = new Set<number>()
+ const ignited = new Map<number, number>()
+
+ // Rising risks, and what comes of them.
+ for (const row of rows) {
+ const { data } = row
+ if (data.burning.present) continue
+ const tile = data.tile.get()
+ const h = data.house.value()
+ // A closed home has nobody in it to fall sick, steal, or knock over a lamp.
+ if (h && data.paused.present) continue
+ const b = data.building.value()
+ const r = { ...data.risk.get() }
+ const increments = riskIncrements({
+ tile, condition: data.condition.get().value, desirability: appealAt(cells, tile.x, tile.y), approval, heating,
+ hotNearby: hot.filter((source) => near(source, tile, risk.fire.reach)).length,
+ dusty: dusty.some((d) => near(d, tile, risk.health.reach)), water: waterNear(tile),
+ ...(h ? { house: h } : {}), ...(b ? { kind: b.kind } : {})
+ }, rules)
+ if (h) {
+ if (!data.sick.present) r.health = Math.min(RISK_MAX, r.health + increments.health)
+ r.order = Math.min(RISK_MAX, r.order + increments.order)
+ }
+ r.fire = Math.min(RISK_MAX, r.fire + increments.fire)
+
+ if (r.fire >= RISK_MAX) {
+ // Fire!
+ const id = fires.next
+ fires.next += 1
+ fires.fires.push({ id, x: tile.x, y: tile.y, homes: 0, buildings: 0 })
+ commands.insert(row.entity, Game.Command.entry(Burning, { left: risk.fire.burns, fire: id }))
+ ignited.set(row.entity.id, id)
+ r.fire = 0
+ news(`Fire on ${where(tile)}!`, tile)
+ }
+ if (h && r.health >= RISK_MAX && !data.sick.present) {
+ commands.insert(row.entity, Game.Command.entry(Sick, { left: risk.health.lasts }))
+ r.health = 0
+ if (sickNow === 0) news(`Sickness on ${where(tile)}: a physician can cure it.`, tile)
+ }
+ if (h && r.order >= RISK_MAX) {
+ if (r.thefts === 0) {
+ // A theft: coins from the treasury, or goods from storage when it is empty.
+ const coins = resources.treasury.get().coins
+ const take = Math.min(risk.order.most, Math.max(0, coins), risk.order.coins + Math.floor(Math.max(0, coins) * risk.order.share))
+ if (take > 0) {
+ resources.treasury.set({ coins: coins - take })
+ news(`Thieves on ${where(tile)} made off with ${take} coins.`, tile)
+ } else {
+ const stores = queries.stores.each()
+ const held = (g: GoodId) => stores.reduce((n, s) => n + s.data.inventory.get().stock[g], 0)
+ const good = [...goodIds].sort((a, b) => held(b) * goods[b].price - held(a) * goods[a].price)[0]!
+ let owed = Math.min(risk.order.goods, held(good))
+ for (const { data: s } of stores) {
+ if (owed <= 0) break
+ const inv = s.inventory.get()
+ const n = Math.min(owed, inv.stock[good])
+ s.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - n } })
+ owed -= n
+ }
+ if (held(good) > 0) news(`Thieves on ${where(tile)} made off with ${goods[good].title}.`, tile)
+ }
+ r.thefts += 1
+ r.order = risk.order.after
+ } else {
+ news(`A home on ${where(tile)} stood empty after its thefts, and is left derelict.`, tile)
+ ruin(row, "derelict")
+ lost.add(row.entity.id)
+ continue
+ }
+ }
+ data.risk.set(r)
+ }
+
+ // Sickness runs its course, and spreads to homes close by.
+ const homeRows = rows.filter(({ entity, data }) => data.house.present && !data.burning.present && !lost.has(entity.id))
+ for (const { entity, data } of queries.sickness.each()) {
+ const s = data.sick.get()
+ const left = s.left - RISK_TICKS
+ if (left <= 0) {
+ commands.remove(entity, Sick)
+ continue
+ }
+ data.sick.set({ left })
+ if (random.next() >= risk.health.spreads) continue
+ const me = rows.find((row) => row.entity.id === entity.id)
+ if (!me) continue
+ const at = me.data.tile.get()
+ const target = random.pick(homeRows.filter(({ entity: e, data: d }) => e.id !== entity.id && !d.sick.present && near(d.tile.get(), at, 2)))
+ if (target) {
+ const r = target.data.risk.get()
+ target.data.risk.set({ ...r, health: Math.min(RISK_MAX, r.health + risk.health.contagion) })
+ }
+ }
+
+ // Fires burn down what they hold, and catch what stands beside them.
+ const byId = new Map(rows.map((row) => [row.entity.id as number, row]))
+ for (const { entity, data } of queries.blazes.each()) {
+ const b = data.burning.get()
+ const row = byId.get(entity.id)
+ if (!row) continue
+ const fire = fires.fires.find((f) => f.id === b.fire)
+ const left = b.left - RISK_TICKS
+ if (left <= 0) {
+ ruin(row, "burnt")
+ lost.add(entity.id)
+ if (fire) {
+ if (row.data.house.present) fire.homes += 1
+ else fire.buildings += 1
+ }
+ continue
+ }
+ data.burning.set({ ...b, left })
+ const tile = row.data.tile.get()
+ const neighbour = random.pick(rows.filter(({ entity: e, data: d }) => e.id !== entity.id && !d.burning.present && !ignited.has(e.id) && !lost.has(e.id) && near(d.tile.get(), tile, 1)))
+ if (!neighbour) continue
+ const chance = risk.fire.catches + (risk.fire.spread * neighbour.data.risk.get().fire) / RISK_MAX
+ if (random.next() < chance) {
+ commands.insert(neighbour.entity, Game.Command.entry(Burning, { left: risk.fire.burns, fire: b.fire }))
+ ignited.set(neighbour.entity.id, b.fire)
+ }
+ }
+
+ // Firefighters run from the nearest fire watch to every blaze no one is running to.
+ const out = new Map<number, number>()
+ const crewed = new Set<number>()
+ for (const { data } of queries.crews.each()) {
+ out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
+ if (!data.rescue.get().back) crewed.add(data.rescue.get().target)
+ }
+ const watches = queries.watches.each().filter(({ data }) => data.service.get().service === "fire" && data.staff.get().assigned > 0)
+ const burningNow = [...queries.blazes.each().map(({ entity }) => entity.id as number), ...ignited.keys()].filter((id) => !lost.has(id))
+ for (const id of burningNow) {
+ if (crewed.has(id)) continue
+ const target = byId.get(id)
+ if (!target) continue
+ const goal = doors(grid, target.data.tile.get())
+ let best: { readonly watch: (typeof watches)[number]; readonly roads: ReturnType<typeof reach>; readonly cell: Point; readonly distance: number } | null = null
+ for (const watch of watches) {
+ // A fire brigade sends more (see `Upgrade.crews`).
+ const crews = upgradeAt(kinds.firewatch, watch.data.upgraded.value()?.level ?? 0)?.crews ?? risk.fire.crews
+ if ((out.get(watch.entity.id) ?? 0) >= crews) continue
+ const starts = doors(grid, watch.data.tile.get())
+ if (starts.length === 0) continue
+ const roads = reach(grid, starts)
+ const found = nearest(roads, goal)
+ if (found && (best === null || found.distance < best.distance)) best = { watch, roads, ...found }
+ }
+ if (!best) continue
+ const draft = Game.Command.spawn(
+ [Figure, { role: "walker", color: 0xc4523f }],
+ [Route, { cells: pathTo(best.roads, best.cell), index: 0, step: 0 }],
+ [Rescue, { target: Game.Entity.handle(target.entity.id, Tile), back: false }]
+ )
+ commands.spawn(Game.Command.relate(draft, WalkerOf, best.watch.entity.id))
+ out.set(best.watch.entity.id, (out.get(best.watch.entity.id) ?? 0) + 1)
+ }
+
+ // A fire with nothing left burning is over: the news says what it took.
+ const stillBurning = new Set<number>()
+ for (const { entity, data } of queries.blazes.each()) if (!lost.has(entity.id)) stillBurning.add(data.burning.get().fire)
+ for (const f of ignited.values()) stillBurning.add(f)
+ const over = fires.fires.filter((f) => !stillBurning.has(f.id))
+ for (const f of over) {
+ const took = [f.homes > 0 ? counted(f.homes, "home") : "", f.buildings > 0 ? counted(f.buildings, "building") : ""].filter((s) => s !== "")
+ news(`Fire on ${where(f)}: ${took.length > 0 ? `${took.join(" and ")} lost` : "put out"}.`, { x: f.x, y: f.y })
+ }
+ resources.fires.set({ fires: fires.fires.filter((f) => stillBurning.has(f.id)), next: fires.next })
+ }
+)
diff --git a/src/game/systems/hazards/index.ts b/src/game/systems/hazards/index.ts
index 94641f2..0e4326e 100644
--- a/src/game/systems/hazards/index.ts
+++ b/src/game/systems/hazards/index.ts
@@ -1,5 +1,3 @@
-import { every } from "../../content/index.ts"
-import { near, riskIncrements } from "../../rules/risks.ts"
/**
* The neighbourhood and its dangers. Every so often the town's desirability
* is reckoned cell by cell (`Appraise`). Once a second every home's risk of
@@ -10,358 +8,14 @@ import { near, riskIncrements } from "../../rules/risks.ts"
* home left derelict. A fire watch sends firefighters running to any blaze
* (`Douse`): when they arrive, that house is lost but the fire is out.
*/
-import * as Random from "@typeonce/ritmo-math/Random"
-
-import { appealGrid, appealAt, buildingSource, homeSource, landSource, parkSources, type AppealSource } from "../../world/appeal.ts"
-import { ruinDraft } from "../../world/archetypes.ts"
-import { goodIds, risk, upgradeAt, type GoodId } from "../../content/index.ts"
-import { doors, nearest, pathTo, reach, useAt } from "../../world/grid.ts"
-import { counted, placeName, type Landmark } from "../../world/places.ts"
-import type { Point } from "../../world/iso.ts"
-import { Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Rules, Grid, House, Inventory, Mood, Park, Paused, Paved, Rescue, Rising, Risk, Rng, Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, Upgraded, WalkerOf, Water } from "../../schema.ts"
-import { elapsed, seasonAt, write } from "../shared.ts"
// ── Desirability ──────────────────────────────────────────────────────────
-/** Reckons every cell's desirability, every `appeal.every` steps (and at once when there is none yet). */
-export const Appraise = Game.System(
- "Town/Appraise",
- {
- queries: {
- buildings: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building), upgraded: Game.Query.optional(Upgraded) }, without: [Site, Rising] }),
- trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),
- water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),
- paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),
- parks: Game.Query({ selection: { tile: Game.Query.read(Tile), park: Game.Query.read(Park) } }),
- roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),
- ruins: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Ruin] }),
- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition), house: Game.Query.read(House), closed: Game.Query.optional(Paused) }, without: [Site, Rising] })
- },
- resources: { time: Game.System.readResource(Time), appeal: Game.System.writeResource(Appeal) },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
- const { appeal, condition: wear } = rules
-
- if (!every(resources.time.get(), appeal.every) && resources.appeal.get().cells.length > 0) return
- const sources: Array<AppealSource> = []
- for (const { data } of queries.buildings.each()) {
- const s = buildingSource(data.building.get().kind, data.tile.get(), rules, data.upgraded.value()?.level ?? 0)
- if (s) sources.push(s)
- }
- for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get(), rules))
- for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get(), rules))
- for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get(), rules))
- const roads = new Set(queries.roads.each().map(({ data }) => `${data.tile.get().x},${data.tile.get().y}`))
- sources.push(...parkSources(queries.parks.each().map(({ data }) => ({ ...data.tile.get(), ...data.park.get() })), (x, y) => roads.has(`${x},${y}`), rules))
- for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get(), rules))
- for (const { data } of queries.homes.each()) {
- if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get(), rules))
- const fine = data.closed.present ? null : homeSource(data.house.get().tier, data.tile.get(), rules)
- if (fine) sources.push(fine)
- }
- resources.appeal.set({ cells: appealGrid(sources, rules) })
- }
-)
+export { Appraise } from "./appraise.ts"
// ── Risks ─────────────────────────────────────────────────────────────────
-/** The risks are reckoned this often (once a second). */
-export const RISK_TICKS = 60
-
export { paceAt } from "../../rules/risks.ts"
-export const Hazards = Game.System(
- "Town/Hazards",
- {
- queries: {
- cared: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- risk: Game.Query.write(Risk),
- condition: Game.Query.read(Condition),
- house: Game.Query.optional(House),
- building: Game.Query.optional(Building),
- sick: Game.Query.optional(Sick),
- burning: Game.Query.optional(Burning),
- paused: Game.Query.optional(Paused)
- },
- without: [Site, Rising]
- }),
- sickness: Game.Query({ selection: { sick: Game.Query.write(Sick) } }),
- blazes: Game.Query({ selection: { burning: Game.Query.write(Burning) } }),
- landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
- watches: Game.Query({
- selection: { tile: Game.Query.read(Tile), service: Game.Query.read(Service), staff: Game.Query.read(Staff), upgraded: Game.Query.optional(Upgraded) },
- without: [Site, Rising, Burning]
- }),
- crews: Game.Query({ selection: { rescue: Game.Query.read(Rescue), home: Game.Query.readRelation(WalkerOf) } }),
- stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
- },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- grid: Game.System.readResource(Grid),
- appeal: Game.System.readResource(Appeal),
- mood: Game.System.readResource(Mood),
- rng: Game.System.writeResource(Rng),
- treasury: Game.System.writeResource(Treasury),
- fires: Game.System.writeResource(Fires),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(
- Game.System.spawns(Ruin, Rescue),
- Game.System.inserts(Burning, Sick),
- Game.System.removes(Sick),
- Game.System.despawns(Tile),
- Game.System.relates(WalkerOf)
- )
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { kinds, goods, risk, winters, riskMax: RISK_MAX, riskTicks: RISK_TICKS } = rules
-
- const tick = resources.time.get().step
- if (tick % RISK_TICKS !== 0) return
- const charter = resources.charter.get()
- const t = elapsed(resources.time.get(), charter)
- const grid = resources.grid.get()
- const cells = resources.appeal.get().cells
- const approval = resources.mood.get().approval
- const season = seasonAt(t, charter, rules)
- const heating = season.severity !== null && winters[season.severity].heating
- const random = Random.draw(resources.rng)
- const news = (text: string, at: Point | null = null) => write(resources.chronicle, t, text, true, at)
- const landmarks: Array<Landmark> = queries.landmarks.each().map(({ data }) => ({ kind: data.building.get().kind, ...data.tile.get() }))
- const where = (cell: Point) => placeName(landmarks, cell)
- const fires = { ...resources.fires.get(), fires: resources.fires.get().fires.map((f) => ({ ...f })) }
-
- const rows = queries.cared.each()
- const hot = rows.filter(({ data }) => {
- const b = data.building.value()
- return b !== undefined && kinds[b.kind].hot === true && !data.burning.present
- }).map(({ data }) => data.tile.get())
- const dusty = landmarks.filter((l) => kinds[l.kind].dusty)
- const waterNear = (tile: { readonly x: number; readonly y: number }) => {
- for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, tile.x + dx, tile.y + dy) === "water") return true
- return false
- }
- const sickNow = rows.filter(({ data }) => data.sick.present).length
-
- /** Turns a home or building into a ruin. */
- const ruin = (row: (typeof rows)[number], cause: "burnt" | "collapsed" | "derelict") => {
- commands.despawn(row.entity)
- commands.spawn(ruinDraft(row.data.tile.get(), cause))
- }
- const lost = new Set<number>()
- const ignited = new Map<number, number>()
-
- // Rising risks, and what comes of them.
- for (const row of rows) {
- const { data } = row
- if (data.burning.present) continue
- const tile = data.tile.get()
- const h = data.house.value()
- // A closed home has nobody in it to fall sick, steal, or knock over a lamp.
- if (h && data.paused.present) continue
- const b = data.building.value()
- const r = { ...data.risk.get() }
- const increments = riskIncrements({
- tile, condition: data.condition.get().value, desirability: appealAt(cells, tile.x, tile.y), approval, heating,
- hotNearby: hot.filter((source) => near(source, tile, risk.fire.reach)).length,
- dusty: dusty.some((d) => near(d, tile, risk.health.reach)), water: waterNear(tile),
- ...(h ? { house: h } : {}), ...(b ? { kind: b.kind } : {})
- }, rules)
- if (h) {
- if (!data.sick.present) r.health = Math.min(RISK_MAX, r.health + increments.health)
- r.order = Math.min(RISK_MAX, r.order + increments.order)
- }
- r.fire = Math.min(RISK_MAX, r.fire + increments.fire)
-
- if (r.fire >= RISK_MAX) {
- // Fire!
- const id = fires.next
- fires.next += 1
- fires.fires.push({ id, x: tile.x, y: tile.y, homes: 0, buildings: 0 })
- commands.insert(row.entity, Game.Command.entry(Burning, { left: risk.fire.burns, fire: id }))
- ignited.set(row.entity.id, id)
- r.fire = 0
- news(`Fire on ${where(tile)}!`, tile)
- }
- if (h && r.health >= RISK_MAX && !data.sick.present) {
- commands.insert(row.entity, Game.Command.entry(Sick, { left: risk.health.lasts }))
- r.health = 0
- if (sickNow === 0) news(`Sickness on ${where(tile)}: a physician can cure it.`, tile)
- }
- if (h && r.order >= RISK_MAX) {
- if (r.thefts === 0) {
- // A theft: coins from the treasury, or goods from storage when it is empty.
- const coins = resources.treasury.get().coins
- const take = Math.min(risk.order.most, Math.max(0, coins), risk.order.coins + Math.floor(Math.max(0, coins) * risk.order.share))
- if (take > 0) {
- resources.treasury.set({ coins: coins - take })
- news(`Thieves on ${where(tile)} made off with ${take} coins.`, tile)
- } else {
- const stores = queries.stores.each()
- const held = (g: GoodId) => stores.reduce((n, s) => n + s.data.inventory.get().stock[g], 0)
- const good = [...goodIds].sort((a, b) => held(b) * goods[b].price - held(a) * goods[a].price)[0]!
- let owed = Math.min(risk.order.goods, held(good))
- for (const { data: s } of stores) {
- if (owed <= 0) break
- const inv = s.inventory.get()
- const n = Math.min(owed, inv.stock[good])
- s.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - n } })
- owed -= n
- }
- if (held(good) > 0) news(`Thieves on ${where(tile)} made off with ${goods[good].title}.`, tile)
- }
- r.thefts += 1
- r.order = risk.order.after
- } else {
- news(`A home on ${where(tile)} stood empty after its thefts, and is left derelict.`, tile)
- ruin(row, "derelict")
- lost.add(row.entity.id)
- continue
- }
- }
- data.risk.set(r)
- }
-
- // Sickness runs its course, and spreads to homes close by.
- const homeRows = rows.filter(({ entity, data }) => data.house.present && !data.burning.present && !lost.has(entity.id))
- for (const { entity, data } of queries.sickness.each()) {
- const s = data.sick.get()
- const left = s.left - RISK_TICKS
- if (left <= 0) {
- commands.remove(entity, Sick)
- continue
- }
- data.sick.set({ left })
- if (random.next() >= risk.health.spreads) continue
- const me = rows.find((row) => row.entity.id === entity.id)
- if (!me) continue
- const at = me.data.tile.get()
- const target = random.pick(homeRows.filter(({ entity: e, data: d }) => e.id !== entity.id && !d.sick.present && near(d.tile.get(), at, 2)))
- if (target) {
- const r = target.data.risk.get()
- target.data.risk.set({ ...r, health: Math.min(RISK_MAX, r.health + risk.health.contagion) })
- }
- }
-
- // Fires burn down what they hold, and catch what stands beside them.
- const byId = new Map(rows.map((row) => [row.entity.id as number, row]))
- for (const { entity, data } of queries.blazes.each()) {
- const b = data.burning.get()
- const row = byId.get(entity.id)
- if (!row) continue
- const fire = fires.fires.find((f) => f.id === b.fire)
- const left = b.left - RISK_TICKS
- if (left <= 0) {
- ruin(row, "burnt")
- lost.add(entity.id)
- if (fire) {
- if (row.data.house.present) fire.homes += 1
- else fire.buildings += 1
- }
- continue
- }
- data.burning.set({ ...b, left })
- const tile = row.data.tile.get()
- const neighbour = random.pick(rows.filter(({ entity: e, data: d }) => e.id !== entity.id && !d.burning.present && !ignited.has(e.id) && !lost.has(e.id) && near(d.tile.get(), tile, 1)))
- if (!neighbour) continue
- const chance = risk.fire.catches + (risk.fire.spread * neighbour.data.risk.get().fire) / RISK_MAX
- if (random.next() < chance) {
- commands.insert(neighbour.entity, Game.Command.entry(Burning, { left: risk.fire.burns, fire: b.fire }))
- ignited.set(neighbour.entity.id, b.fire)
- }
- }
-
- // Firefighters run from the nearest fire watch to every blaze no one is running to.
- const out = new Map<number, number>()
- const crewed = new Set<number>()
- for (const { data } of queries.crews.each()) {
- out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
- if (!data.rescue.get().back) crewed.add(data.rescue.get().target)
- }
- const watches = queries.watches.each().filter(({ data }) => data.service.get().service === "fire" && data.staff.get().assigned > 0)
- const burningNow = [...queries.blazes.each().map(({ entity }) => entity.id as number), ...ignited.keys()].filter((id) => !lost.has(id))
- for (const id of burningNow) {
- if (crewed.has(id)) continue
- const target = byId.get(id)
- if (!target) continue
- const goal = doors(grid, target.data.tile.get())
- let best: { readonly watch: (typeof watches)[number]; readonly roads: ReturnType<typeof reach>; readonly cell: Point; readonly distance: number } | null = null
- for (const watch of watches) {
- // A fire brigade sends more (see `Upgrade.crews`).
- const crews = upgradeAt(kinds.firewatch, watch.data.upgraded.value()?.level ?? 0)?.crews ?? risk.fire.crews
- if ((out.get(watch.entity.id) ?? 0) >= crews) continue
- const starts = doors(grid, watch.data.tile.get())
- if (starts.length === 0) continue
- const roads = reach(grid, starts)
- const found = nearest(roads, goal)
- if (found && (best === null || found.distance < best.distance)) best = { watch, roads, ...found }
- }
- if (!best) continue
- const draft = Game.Command.spawn(
- [Figure, { role: "walker", color: 0xc4523f }],
- [Route, { cells: pathTo(best.roads, best.cell), index: 0, step: 0 }],
- [Rescue, { target: Game.Entity.handle(target.entity.id, Tile), back: false }]
- )
- commands.spawn(Game.Command.relate(draft, WalkerOf, best.watch.entity.id))
- out.set(best.watch.entity.id, (out.get(best.watch.entity.id) ?? 0) + 1)
- }
-
- // A fire with nothing left burning is over: the news says what it took.
- const stillBurning = new Set<number>()
- for (const { entity, data } of queries.blazes.each()) if (!lost.has(entity.id)) stillBurning.add(data.burning.get().fire)
- for (const f of ignited.values()) stillBurning.add(f)
- const over = fires.fires.filter((f) => !stillBurning.has(f.id))
- for (const f of over) {
- const took = [f.homes > 0 ? counted(f.homes, "home") : "", f.buildings > 0 ? counted(f.buildings, "building") : ""].filter((s) => s !== "")
- news(`Fire on ${where(f)}: ${took.length > 0 ? `${took.join(" and ")} lost` : "put out"}.`, { x: f.x, y: f.y })
- }
- resources.fires.set({ fires: fires.fires.filter((f) => stillBurning.has(f.id)), next: fires.next })
- }
-)
-
-const BurningRead = Game.Query({ selection: { tile: Game.Query.read(Tile), burning: Game.Query.read(Burning), house: Game.Query.optional(House) } })
-
-/**
- * A firefighter at the blaze puts it out: the house is lost, but the fire
- * goes no further. Then the firefighter walks back to the watch.
- */
-export const Douse = Game.System(
- "Town/Douse",
- {
- queries: { crews: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.write(Rescue) } }), burning: BurningRead },
- resources: { fires: Game.System.writeResource(Fires) },
- commands: Game.System.commands(Game.System.spawns(Ruin), Game.System.despawns(Rescue, Burning))
- },
- ({ queries, resources, commands }) => {
- for (const { entity, data } of queries.crews.each()) {
- const route = data.route.get()
- const rescue = data.rescue.get()
- const arrived = route.index >= route.cells.length - 1
- if (!arrived) continue
- if (rescue.back) {
- commands.despawn(entity)
- continue
- }
- const target = queries.burning.getHandle(rescue.target)
- if (target.ok) {
- const b = target.value.data.burning.get()
- commands.despawn(target.value.entity)
- commands.spawn(ruinDraft(target.value.data.tile.get(), "burnt"))
- const house = target.value.data.house.present
- resources.fires.update((f) => ({
- ...f,
- fires: f.fires.map((x) => (x.id === b.fire ? { ...x, homes: x.homes + (house ? 1 : 0), buildings: x.buildings + (house ? 0 : 1) } : x))
- }))
- }
- data.route.set({ cells: [...route.cells].reverse(), index: 0, step: 0 })
- data.rescue.set({ ...rescue, back: true })
- }
- }
-)
+export { Hazards, RISK_TICKS } from "./hazards.ts"
+export { Douse } from "./douse.ts"
diff --git a/src/game/systems/logistics/deliver.ts b/src/game/systems/logistics/deliver.ts
new file mode 100644
index 0000000..2221838
--- /dev/null
+++ b/src/game/systems/logistics/deliver.ts
@@ -0,0 +1,85 @@
+import type { Point } from "../../world/iso.ts"
+import { Errand, Game, Rules, Inventory, Route, Site, Tile, WalkerOf, Works } from "../../schema.ts"
+import { CELL_STEPS } from "../shared.ts"
+
+const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
+
+/** The way back from where a walker is now, mid-step or not. */
+export const turnAround = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number; readonly step: number }) => {
+ const behind = route.cells.slice(0, route.index + 1).reverse()
+ const ahead = route.cells[route.index + 1]
+ return route.step > 0 && ahead
+ ? { cells: [ahead, ...behind], index: 0, step: CELL_STEPS - route.step }
+ : { cells: behind, index: 0, step: 0 }
+}
+
+const TargetRead = Game.Query({ selection: { tile: Game.Query.read(Tile) } })
+
+/**
+ * A carrier hands its crate over: to a site or an upgrade under way, towards what it is owed; to
+ * anyone else, as much as they have room for. Then it walks back, and puts
+ * whatever it still carries back where it came from.
+ */
+export const Deliver = Game.System(
+ "Town/Deliver",
+ {
+ queries: {
+ carriers: Game.Query({ selection: { route: Game.Query.write(Route), errand: Game.Query.write(Errand), home: Game.Query.readRelation(WalkerOf) } }),
+ targets: TargetRead,
+ inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, without: [Site] }),
+ sites: Game.Query({ selection: { site: Game.Query.write(Site) } }),
+ works: Game.Query({ selection: { works: Game.Query.write(Works) } })
+ },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Errand))
+ },
+ ({ queries, commands, services }) => {
+ const rules = services.rules
+ const { } = rules
+
+ for (const { entity, data } of queries.carriers.each()) {
+ const route = data.route.get()
+ const errand = data.errand.get()
+ if (errand.back) {
+ if (!arrived(route)) continue
+ const home = queries.inventories.get(data.home.get())
+ if (home.ok && errand.count > 0) {
+ const inv = home.value.data.inventory.get()
+ const room = inv.cap - inv.stock[errand.good]
+ home.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + Math.min(room, errand.count) } })
+ }
+ commands.despawn(entity)
+ continue
+ }
+ const target = queries.targets.getHandle(errand.target)
+ if (!target.ok) {
+ // Nowhere to take it: carry it home.
+ data.route.set(turnAround(route))
+ data.errand.set({ ...errand, back: true })
+ continue
+ }
+ if (!arrived(route)) continue
+ let handed = 0
+ const site = queries.sites.get(target.value.entity.id)
+ const works = queries.works.get(target.value.entity.id)
+ const inventory = queries.inventories.get(target.value.entity.id)
+ if (works.ok && works.value.data.works.get().owed[errand.good] > 0) {
+ const w = works.value.data.works.get()
+ handed = Math.min(errand.count, w.owed[errand.good])
+ works.value.data.works.set({ ...w, owed: { ...w.owed, [errand.good]: w.owed[errand.good] - handed } })
+ } else if (site.ok) {
+ const s = site.value.data.site.get()
+ handed = Math.min(errand.count, s.owed[errand.good])
+ site.value.data.site.set({ ...s, owed: { ...s.owed, [errand.good]: s.owed[errand.good] - handed } })
+ } else if (inventory.ok) {
+ const inv = inventory.value.data.inventory.get()
+ if (inv.accepts.includes(errand.good)) {
+ handed = Math.min(errand.count, inv.cap - inv.stock[errand.good])
+ inventory.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + handed } })
+ }
+ }
+ data.route.set({ cells: [...route.cells].reverse(), index: 0, step: 0 })
+ data.errand.set({ ...errand, count: errand.count - handed, back: true })
+ }
+ }
+)
diff --git a/src/game/systems/logistics/dispatch.ts b/src/game/systems/logistics/dispatch.ts
new file mode 100644
index 0000000..1f3bb18
--- /dev/null
+++ b/src/game/systems/logistics/dispatch.ts
@@ -0,0 +1,195 @@
+import { every } from "../../content/index.ts"
+import { transport } from "../../rules/config.ts"
+import { wantsBurgherGoods, wantsCitizenGoods } from "../../rules/households.ts"
+import { appealAt } from "../../world/appeal.ts"
+import { preferDelivery } from "../../rules/transport.ts"
+import { goodIds, provisions, type GoodId } from "../../content/index.ts"
+import { doors, nearest, pathTo, reach, key, type Reach } from "../../world/grid.ts"
+import type { Point } from "../../world/iso.ts"
+import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, House, Appeal, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, Works } from "../../schema.ts"
+
+/** The most a carrier takes at once. */
+const LOAD = transport.load
+/** Carriers are sent out this often: ten times a second, a delay no one sees, at a sixth of the work. */
+const DISPATCH_TICKS = transport.dispatchTicks
+
+export const Dispatch = Game.System(
+ "Town/Dispatch",
+ {
+ queries: {
+ senders: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ inventory: Game.Query.write(Inventory),
+ carriers: Game.Query.read(Carriers),
+ building: Game.Query.optional(Building),
+ storage: Game.Query.optional(Storage),
+ recipe: Game.Query.optional(Recipe)
+ },
+ without: [Site, Rising, Burning]
+ }),
+ wanting: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.optional(Building),
+ inventory: Game.Query.optional(Inventory),
+ recipe: Game.Query.optional(Recipe),
+ service: Game.Query.optional(Service),
+ storage: Game.Query.optional(Storage)
+ },
+ without: [Site, Rising, Burning]
+ }),
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
+ sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),
+ works: Game.Query({ selection: { tile: Game.Query.read(Tile), works: Game.Query.read(Works) }, without: [Burning] }),
+ errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
+ },
+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Errand), Game.System.relates(WalkerOf))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { kinds, goods, spoils, toolStock: TOOL_STOCK } = rules
+
+ if (!every(resources.time.get(), DISPATCH_TICKS)) return
+ const grid = resources.grid.get()
+ const out = new Map<number, number>()
+ const incoming = new Map<string, number>()
+ const inbound = (target: number, good: GoodId) => incoming.get(`${target}:${good}`) ?? 0
+ const expect = (target: number, good: GoodId, count: number) => incoming.set(`${target}:${good}`, inbound(target, good) + count)
+ for (const { data } of queries.errands.each()) {
+ const errand = data.errand.get()
+ out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
+ if (!errand.back) expect(errand.target, errand.good, errand.count)
+ }
+
+ type Id = ReturnType<typeof queries.sites.each>[number]["entity"]["id"]
+ // Outstanding demand and shelf fill, including goods already in transit.
+ interface Want {
+ readonly id: Id
+ readonly doors: ReadonlyArray<Point>
+ readonly good: GoodId
+ readonly want: () => number
+ readonly site: boolean
+ readonly fill?: () => number
+ }
+ const wants: Array<Want> = []
+ for (const { entity, data } of queries.sites.each()) {
+ const site = data.site.get()
+ const ds = doors(grid, data.tile.get())
+ for (const g of goodIds) if (site.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => site.owed[g] - inbound(entity.id, g) })
+ }
+ // An upgrade under way is building work too: its materials go before anyone's shelves.
+ for (const { entity, data } of queries.works.each()) {
+ const works = data.works.get()
+ const ds = doors(grid, data.tile.get())
+ for (const g of goodIds) if (works.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => works.owed[g] - inbound(entity.id, g) })
+ }
+ const sitesWant = new Set(wants.filter((w) => w.want() > 0).map((w) => w.good))
+ const rooms: Array<{ readonly id: Id; readonly doors: ReadonlyArray<Point>; readonly room: (g: GoodId) => number; readonly keeps: boolean }> = []
+ for (const { entity, data } of queries.wanting.each()) {
+ const inventory = data.inventory.value()
+ if (!inventory) continue
+ const ds = doors(grid, data.tile.get())
+ if (ds.length === 0) continue
+ const recipe = data.recipe.value()
+ const space = (g: GoodId) => (inventory.accepts.includes(g) ? inventory.cap - inventory.stock[g] - inbound(entity.id, g) : 0)
+ const kind = data.building.value()?.kind
+ if (data.storage.present) {
+ rooms.push({ id: entity.id, doors: ds, room: space, keeps: kind !== undefined && (kinds[kind].keeps ?? 0) > 1 })
+ }
+ if (recipe && recipe.input !== null) {
+ const g = recipe.input
+ wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g), fill: () => (inventory.stock[g] + inbound(entity.id, g)) / inventory.cap })
+ }
+ // A workshop that wears out tools keeps a couple on hand.
+ if (kind !== undefined && kinds[kind].wear) wants.push({ id: entity.id, doors: ds, good: "tools", site: false, want: () => TOOL_STOCK - inventory.stock.tools - inbound(entity.id, "tools"), fill: () => (inventory.stock.tools + inbound(entity.id, "tools")) / TOOL_STOCK })
+ const service = data.service.value()?.service
+ if (service === "goods") {
+ const roads = reach(grid, [ds[0]!]), range = data.service.value()!.range
+ let citizenDistrict = false, burgherDistrict = false
+ for (const { data: h } of queries.homes.each()) {
+ const tile = h.tile.get(), found = nearest(roads, doors(grid, tile))
+ if (found === null || found.distance >= range) continue
+ const desirability = appealAt(resources.appeal.get().cells, tile.x, tile.y)
+ citizenDistrict ||= wantsCitizenGoods(h.house.get(), desirability, rules)
+ burgherDistrict ||= wantsBurgherGoods(h.house.get(), desirability, rules)
+ if (burgherDistrict) break
+ }
+ for (const g of provisions) {
+ if (g === "cloth" && !citizenDistrict) continue
+ if (g === "furniture" && !burgherDistrict) continue
+ const cap = Math.min(inventory.cap, rules.transport.basket)
+ wants.push({ id: entity.id, doors: ds, good: g, site: false,
+ want: () => cap - inventory.stock[g] - inbound(entity.id, g), fill: () => (inventory.stock[g] + inbound(entity.id, g)) / cap })
+ }
+ }
+ if (service === "repair") for (const g of ["planks", "stone"] as const) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
+ }
+
+ const send = (from: { readonly id: Id; readonly roads: Reach }, to: { readonly id: Id; readonly cell: Point }, good: GoodId, count: number) => {
+ const draft = Game.Command.spawn(
+ [Figure, { role: "carrier", color: goods[good].color }],
+ [Route, { cells: pathTo(from.roads, to.cell), index: 0, step: 0 }],
+ [Errand, { target: Game.Entity.handle(to.id, Tile), good, count, back: false }]
+ )
+ commands.spawn(Game.Command.relate(draft, WalkerOf, from.id))
+ out.set(from.id, (out.get(from.id) ?? 0) + 1)
+ expect(to.id, good, count)
+ }
+
+ for (const { entity, data } of queries.senders.each()) {
+ const carriers = data.carriers.get().count
+ if ((out.get(entity.id) ?? 0) >= carriers) continue
+ const starts = doors(grid, data.tile.get())
+ if (starts.length === 0) continue
+ const roads = reach(grid, starts)
+ const inventory = data.inventory.get()
+ let stock = inventory.stock
+ const recipe = data.recipe.value()
+
+ // A storage meets demands with what it holds; anyone else sends on what it made.
+ // A producer waits for a full load (or a full shelf) so its carriers do not walk with one crate.
+ const ready = recipe ? stock[recipe.output] >= Math.min(LOAD, inventory.cap - recipe.batch) : false
+ // What sites are waiting for goes first: otherwise steady demand for one good keeps every carrier busy.
+ const offers: ReadonlyArray<GoodId> = data.storage.present
+ ? goodIds.filter((g) => stock[g] > 0).sort((a, b) => Number(!sitesWant.has(a)) - Number(!sitesWant.has(b)))
+ : recipe && ready ? [recipe.output] : []
+ for (const good of offers) {
+ if ((out.get(entity.id) ?? 0) >= carriers) break
+ let best: { readonly id: Id; readonly cell: Point; readonly distance: number; readonly count: number; readonly site: boolean; readonly fill?: number } | null = null
+ for (const w of wants) {
+ if (w.good !== good || w.id === entity.id) continue
+ const count = Math.min(LOAD, stock[good], w.want())
+ if (count <= 0) continue
+ const found = nearest(roads, w.doors)
+ // Sites come first, then the lowest shelf fill; distance breaks ties.
+ if (found && preferDelivery({ site: w.site, distance: found.distance, fill: w.fill?.() ?? 0 }, best)) best = { id: w.id, ...found, count, site: w.site, fill: w.fill?.() ?? 0 }
+ }
+ // Food that spoils goes to a granary if there is one in reach, before the nearest storage; a
+ // storage that does not keep food sends it on to a granary that does.
+ const perishable = spoils[good] !== undefined
+ const senderKeeps = (kinds[data.building.value()?.kind ?? "townhall"].keeps ?? 0) > 1
+ if (best === null && (!data.storage.present || (perishable && !senderKeeps))) {
+ let kept = false
+ for (const r of rooms) {
+ if (r.id === entity.id || (data.storage.present && !r.keeps)) continue
+ const count = Math.min(LOAD, stock[good], r.room(good))
+ if (count <= 0) continue
+ const found = nearest(roads, r.doors)
+ const keeps = perishable && r.keeps
+ if (found && (best === null || (keeps && !kept) || (keeps === kept && found.distance < best.distance))) {
+ best = { id: r.id, ...found, count, site: false }
+ kept = keeps
+ }
+ }
+ }
+ if (best === null) continue
+ send({ id: entity.id, roads }, best, good, best.count)
+ stock = { ...stock, [good]: stock[good] - best.count }
+ }
+ if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })
+ }
+ }
+)
diff --git a/src/game/systems/logistics/index.ts b/src/game/systems/logistics/index.ts
index 9b0b3c6..e4a1257 100644
--- a/src/game/systems/logistics/index.ts
+++ b/src/game/systems/logistics/index.ts
@@ -1,8 +1,3 @@
-import { every } from "../../content/index.ts"
-import { transport } from "../../rules/config.ts"
-import { wantsBurgherGoods, wantsCitizenGoods } from "../../rules/households.ts"
-import { appealAt } from "../../world/appeal.ts"
-import { preferDelivery } from "../../rules/transport.ts"
/**
* Carriers: every good that moves walks along the roads in a carrier's
* crate. What a building wants — a site's materials, a workshop's input, a
@@ -11,277 +6,5 @@ import { preferDelivery } from "../../rules/transport.ts"
* storage balances the demands it can meet. Construction comes first. Crates
* already on their way count against a demand, so no one is sent twice.
*/
-import { goodIds, provisions, type GoodId } from "../../content/index.ts"
-import { doors, nearest, pathTo, reach, key, type Reach } from "../../world/grid.ts"
-import type { Point } from "../../world/iso.ts"
-import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, House, Appeal, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, Works } from "../../schema.ts"
-import { CELL_STEPS } from "../shared.ts"
-
-/** The most a carrier takes at once. */
-const LOAD = transport.load
-/** Carriers are sent out this often: ten times a second, a delay no one sees, at a sixth of the work. */
-const DISPATCH_TICKS = transport.dispatchTicks
-
-export const Dispatch = Game.System(
- "Town/Dispatch",
- {
- queries: {
- senders: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- inventory: Game.Query.write(Inventory),
- carriers: Game.Query.read(Carriers),
- building: Game.Query.optional(Building),
- storage: Game.Query.optional(Storage),
- recipe: Game.Query.optional(Recipe)
- },
- without: [Site, Rising, Burning]
- }),
- wanting: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- building: Game.Query.optional(Building),
- inventory: Game.Query.optional(Inventory),
- recipe: Game.Query.optional(Recipe),
- service: Game.Query.optional(Service),
- storage: Game.Query.optional(Storage)
- },
- without: [Site, Rising, Burning]
- }),
- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
- sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),
- works: Game.Query({ selection: { tile: Game.Query.read(Tile), works: Game.Query.read(Works) }, without: [Burning] }),
- errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
- },
- resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.spawns(Errand), Game.System.relates(WalkerOf))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { kinds, goods, spoils, toolStock: TOOL_STOCK } = rules
-
- if (!every(resources.time.get(), DISPATCH_TICKS)) return
- const grid = resources.grid.get()
- const out = new Map<number, number>()
- const incoming = new Map<string, number>()
- const inbound = (target: number, good: GoodId) => incoming.get(`${target}:${good}`) ?? 0
- const expect = (target: number, good: GoodId, count: number) => incoming.set(`${target}:${good}`, inbound(target, good) + count)
- for (const { data } of queries.errands.each()) {
- const errand = data.errand.get()
- out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
- if (!errand.back) expect(errand.target, errand.good, errand.count)
- }
-
- type Id = ReturnType<typeof queries.sites.each>[number]["entity"]["id"]
- // Outstanding demand and shelf fill, including goods already in transit.
- interface Want {
- readonly id: Id
- readonly doors: ReadonlyArray<Point>
- readonly good: GoodId
- readonly want: () => number
- readonly site: boolean
- readonly fill?: () => number
- }
- const wants: Array<Want> = []
- for (const { entity, data } of queries.sites.each()) {
- const site = data.site.get()
- const ds = doors(grid, data.tile.get())
- for (const g of goodIds) if (site.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => site.owed[g] - inbound(entity.id, g) })
- }
- // An upgrade under way is building work too: its materials go before anyone's shelves.
- for (const { entity, data } of queries.works.each()) {
- const works = data.works.get()
- const ds = doors(grid, data.tile.get())
- for (const g of goodIds) if (works.owed[g] > 0) wants.push({ id: entity.id, doors: ds, good: g, site: true, want: () => works.owed[g] - inbound(entity.id, g) })
- }
- const sitesWant = new Set(wants.filter((w) => w.want() > 0).map((w) => w.good))
- const rooms: Array<{ readonly id: Id; readonly doors: ReadonlyArray<Point>; readonly room: (g: GoodId) => number; readonly keeps: boolean }> = []
- for (const { entity, data } of queries.wanting.each()) {
- const inventory = data.inventory.value()
- if (!inventory) continue
- const ds = doors(grid, data.tile.get())
- if (ds.length === 0) continue
- const recipe = data.recipe.value()
- const space = (g: GoodId) => (inventory.accepts.includes(g) ? inventory.cap - inventory.stock[g] - inbound(entity.id, g) : 0)
- const kind = data.building.value()?.kind
- if (data.storage.present) {
- rooms.push({ id: entity.id, doors: ds, room: space, keeps: kind !== undefined && (kinds[kind].keeps ?? 0) > 1 })
- }
- if (recipe && recipe.input !== null) {
- const g = recipe.input
- wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g), fill: () => (inventory.stock[g] + inbound(entity.id, g)) / inventory.cap })
- }
- // A workshop that wears out tools keeps a couple on hand.
- if (kind !== undefined && kinds[kind].wear) wants.push({ id: entity.id, doors: ds, good: "tools", site: false, want: () => TOOL_STOCK - inventory.stock.tools - inbound(entity.id, "tools"), fill: () => (inventory.stock.tools + inbound(entity.id, "tools")) / TOOL_STOCK })
- const service = data.service.value()?.service
- if (service === "goods") {
- const roads = reach(grid, [ds[0]!]), range = data.service.value()!.range
- let citizenDistrict = false, burgherDistrict = false
- for (const { data: h } of queries.homes.each()) {
- const tile = h.tile.get(), found = nearest(roads, doors(grid, tile))
- if (found === null || found.distance >= range) continue
- const desirability = appealAt(resources.appeal.get().cells, tile.x, tile.y)
- citizenDistrict ||= wantsCitizenGoods(h.house.get(), desirability, rules)
- burgherDistrict ||= wantsBurgherGoods(h.house.get(), desirability, rules)
- if (burgherDistrict) break
- }
- for (const g of provisions) {
- if (g === "cloth" && !citizenDistrict) continue
- if (g === "furniture" && !burgherDistrict) continue
- const cap = Math.min(inventory.cap, rules.transport.basket)
- wants.push({ id: entity.id, doors: ds, good: g, site: false,
- want: () => cap - inventory.stock[g] - inbound(entity.id, g), fill: () => (inventory.stock[g] + inbound(entity.id, g)) / cap })
- }
- }
- if (service === "repair") for (const g of ["planks", "stone"] as const) wants.push({ id: entity.id, doors: ds, good: g, site: false, want: () => space(g) })
- }
-
- const send = (from: { readonly id: Id; readonly roads: Reach }, to: { readonly id: Id; readonly cell: Point }, good: GoodId, count: number) => {
- const draft = Game.Command.spawn(
- [Figure, { role: "carrier", color: goods[good].color }],
- [Route, { cells: pathTo(from.roads, to.cell), index: 0, step: 0 }],
- [Errand, { target: Game.Entity.handle(to.id, Tile), good, count, back: false }]
- )
- commands.spawn(Game.Command.relate(draft, WalkerOf, from.id))
- out.set(from.id, (out.get(from.id) ?? 0) + 1)
- expect(to.id, good, count)
- }
-
- for (const { entity, data } of queries.senders.each()) {
- const carriers = data.carriers.get().count
- if ((out.get(entity.id) ?? 0) >= carriers) continue
- const starts = doors(grid, data.tile.get())
- if (starts.length === 0) continue
- const roads = reach(grid, starts)
- const inventory = data.inventory.get()
- let stock = inventory.stock
- const recipe = data.recipe.value()
-
- // A storage meets demands with what it holds; anyone else sends on what it made.
- // A producer waits for a full load (or a full shelf) so its carriers do not walk with one crate.
- const ready = recipe ? stock[recipe.output] >= Math.min(LOAD, inventory.cap - recipe.batch) : false
- // What sites are waiting for goes first: otherwise steady demand for one good keeps every carrier busy.
- const offers: ReadonlyArray<GoodId> = data.storage.present
- ? goodIds.filter((g) => stock[g] > 0).sort((a, b) => Number(!sitesWant.has(a)) - Number(!sitesWant.has(b)))
- : recipe && ready ? [recipe.output] : []
- for (const good of offers) {
- if ((out.get(entity.id) ?? 0) >= carriers) break
- let best: { readonly id: Id; readonly cell: Point; readonly distance: number; readonly count: number; readonly site: boolean; readonly fill?: number } | null = null
- for (const w of wants) {
- if (w.good !== good || w.id === entity.id) continue
- const count = Math.min(LOAD, stock[good], w.want())
- if (count <= 0) continue
- const found = nearest(roads, w.doors)
- // Sites come first, then the lowest shelf fill; distance breaks ties.
- if (found && preferDelivery({ site: w.site, distance: found.distance, fill: w.fill?.() ?? 0 }, best)) best = { id: w.id, ...found, count, site: w.site, fill: w.fill?.() ?? 0 }
- }
- // Food that spoils goes to a granary if there is one in reach, before the nearest storage; a
- // storage that does not keep food sends it on to a granary that does.
- const perishable = spoils[good] !== undefined
- const senderKeeps = (kinds[data.building.value()?.kind ?? "townhall"].keeps ?? 0) > 1
- if (best === null && (!data.storage.present || (perishable && !senderKeeps))) {
- let kept = false
- for (const r of rooms) {
- if (r.id === entity.id || (data.storage.present && !r.keeps)) continue
- const count = Math.min(LOAD, stock[good], r.room(good))
- if (count <= 0) continue
- const found = nearest(roads, r.doors)
- const keeps = perishable && r.keeps
- if (found && (best === null || (keeps && !kept) || (keeps === kept && found.distance < best.distance))) {
- best = { id: r.id, ...found, count, site: false }
- kept = keeps
- }
- }
- }
- if (best === null) continue
- send({ id: entity.id, roads }, best, good, best.count)
- stock = { ...stock, [good]: stock[good] - best.count }
- }
- if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })
- }
- }
-)
-
-const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
-
-/** The way back from where a walker is now, mid-step or not. */
-export const turnAround = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number; readonly step: number }) => {
- const behind = route.cells.slice(0, route.index + 1).reverse()
- const ahead = route.cells[route.index + 1]
- return route.step > 0 && ahead
- ? { cells: [ahead, ...behind], index: 0, step: CELL_STEPS - route.step }
- : { cells: behind, index: 0, step: 0 }
-}
-
-const TargetRead = Game.Query({ selection: { tile: Game.Query.read(Tile) } })
-
-/**
- * A carrier hands its crate over: to a site or an upgrade under way, towards what it is owed; to
- * anyone else, as much as they have room for. Then it walks back, and puts
- * whatever it still carries back where it came from.
- */
-export const Deliver = Game.System(
- "Town/Deliver",
- {
- queries: {
- carriers: Game.Query({ selection: { route: Game.Query.write(Route), errand: Game.Query.write(Errand), home: Game.Query.readRelation(WalkerOf) } }),
- targets: TargetRead,
- inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, without: [Site] }),
- sites: Game.Query({ selection: { site: Game.Query.write(Site) } }),
- works: Game.Query({ selection: { works: Game.Query.write(Works) } })
- },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.despawns(Errand))
- },
- ({ queries, commands, services }) => {
- const rules = services.rules
- const { } = rules
-
- for (const { entity, data } of queries.carriers.each()) {
- const route = data.route.get()
- const errand = data.errand.get()
- if (errand.back) {
- if (!arrived(route)) continue
- const home = queries.inventories.get(data.home.get())
- if (home.ok && errand.count > 0) {
- const inv = home.value.data.inventory.get()
- const room = inv.cap - inv.stock[errand.good]
- home.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + Math.min(room, errand.count) } })
- }
- commands.despawn(entity)
- continue
- }
- const target = queries.targets.getHandle(errand.target)
- if (!target.ok) {
- // Nowhere to take it: carry it home.
- data.route.set(turnAround(route))
- data.errand.set({ ...errand, back: true })
- continue
- }
- if (!arrived(route)) continue
- let handed = 0
- const site = queries.sites.get(target.value.entity.id)
- const works = queries.works.get(target.value.entity.id)
- const inventory = queries.inventories.get(target.value.entity.id)
- if (works.ok && works.value.data.works.get().owed[errand.good] > 0) {
- const w = works.value.data.works.get()
- handed = Math.min(errand.count, w.owed[errand.good])
- works.value.data.works.set({ ...w, owed: { ...w.owed, [errand.good]: w.owed[errand.good] - handed } })
- } else if (site.ok) {
- const s = site.value.data.site.get()
- handed = Math.min(errand.count, s.owed[errand.good])
- site.value.data.site.set({ ...s, owed: { ...s.owed, [errand.good]: s.owed[errand.good] - handed } })
- } else if (inventory.ok) {
- const inv = inventory.value.data.inventory.get()
- if (inv.accepts.includes(errand.good)) {
- handed = Math.min(errand.count, inv.cap - inv.stock[errand.good])
- inventory.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + handed } })
- }
- }
- data.route.set({ cells: [...route.cells].reverse(), index: 0, step: 0 })
- data.errand.set({ ...errand, count: errand.count - handed, back: true })
- }
- }
-)
-
+export { Dispatch } from "./dispatch.ts"
+export { Deliver, turnAround } from "./deliver.ts"
diff --git a/src/game/systems/orphans/drop-orphans.ts b/src/game/systems/orphans/drop-orphans.ts
new file mode 100644
index 0000000..194f913
--- /dev/null
+++ b/src/game/systems/orphans/drop-orphans.ts
@@ -0,0 +1,28 @@
+import { Field, Game, Route, FieldOf, WalkerOf } from "../../schema.ts"
+
+export const DropOrphans = Game.System(
+ "Town/DropOrphans",
+ {
+ queries: {
+ walkers: Game.Query({ selection: { route: Game.Query.read(Route) } }),
+ fields: Game.Query({ selection: { field: Game.Query.read(Field) } })
+ },
+ relationFailures: {
+ walkers: Game.System.readRelationFailures(WalkerOf),
+ fields: Game.System.readRelationFailures(FieldOf)
+ },
+ commands: Game.System.commands(Game.System.despawns(Route, Field))
+ },
+ ({ queries, relationFailures, commands }) => {
+ for (const failure of relationFailures.walkers.all()) {
+ if (failure.operation !== "relate") continue
+ const walker = queries.walkers.get(failure.source)
+ if (walker.ok) commands.despawn(walker.value.entity)
+ }
+ for (const failure of relationFailures.fields.all()) {
+ if (failure.operation !== "relate") continue
+ const field = queries.fields.get(failure.source)
+ if (field.ok) commands.despawn(field.value.entity)
+ }
+ }
+)
diff --git a/src/game/systems/orphans/index.ts b/src/game/systems/orphans/index.ts
index 35273b3..90c49b6 100644
--- a/src/game/systems/orphans/index.ts
+++ b/src/game/systems/orphans/index.ts
@@ -4,31 +4,4 @@
* sending its firefighters, say), the belonging fails and the newcomer would
* stay behind with no home: it goes too, as it would have with its building.
*/
-import { Field, Game, Route, FieldOf, WalkerOf } from "../../schema.ts"
-
-export const DropOrphans = Game.System(
- "Town/DropOrphans",
- {
- queries: {
- walkers: Game.Query({ selection: { route: Game.Query.read(Route) } }),
- fields: Game.Query({ selection: { field: Game.Query.read(Field) } })
- },
- relationFailures: {
- walkers: Game.System.readRelationFailures(WalkerOf),
- fields: Game.System.readRelationFailures(FieldOf)
- },
- commands: Game.System.commands(Game.System.despawns(Route, Field))
- },
- ({ queries, relationFailures, commands }) => {
- for (const failure of relationFailures.walkers.all()) {
- if (failure.operation !== "relate") continue
- const walker = queries.walkers.get(failure.source)
- if (walker.ok) commands.despawn(walker.value.entity)
- }
- for (const failure of relationFailures.fields.all()) {
- if (failure.operation !== "relate") continue
- const field = queries.fields.get(failure.source)
- if (field.ok) commands.despawn(field.value.entity)
- }
- }
-)
+export { DropOrphans } from "./drop-orphans.ts"
diff --git a/src/game/systems/term/approve.ts b/src/game/systems/term/approve.ts
new file mode 100644
index 0000000..c2dde7a
--- /dev/null
+++ b/src/game/systems/term/approve.ts
@@ -0,0 +1,37 @@
+import { approvalTarget, nextApproval } from "../../rules/approval.ts"
+import { stepsOf } from "../../content/index.ts"
+import { Charter, Crown, Game, Rules, House, Mood, Paused, Policy, Rising, Site, Time, Treasury } from "../../schema.ts"
+import { elapsed, seasonAt } from "../shared.ts"
+
+/**
+ * What the town makes of how it is run, every collection: its needs, its
+ * taxes, unpaid wages, snubs from the crown, a hungry winter. Approval
+ * moves towards that a few points at a time.
+ */
+export const Approve = Game.System(
+ "Town/Approve",
+ {
+ queries: { homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising, Paused] }) },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ policy: Game.System.readResource(Policy),
+ treasury: Game.System.readResource(Treasury),
+ crown: Game.System.readResource(Crown),
+ mood: Game.System.writeResource(Mood)
+ },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ if (t % stepsOf(10) !== 0) return
+ const policy = resources.policy.get()
+ const m = resources.mood.get()
+ const parts = approvalTarget(queries.homes.each().map(({ data }) => data.house.get()), policy,
+ resources.treasury.get().coins, resources.crown.get().snubs.length, seasonAt(t, resources.charter.get(), rules).winter, rules, m.memory)
+ resources.mood.set({ approval: nextApproval(m.approval, parts.target, rules), ...parts })
+
+ }
+)
diff --git a/src/game/systems/term/index.ts b/src/game/systems/term/index.ts
index 6484f0b..d667314 100644
--- a/src/game/systems/term/index.ts
+++ b/src/game/systems/term/index.ts
@@ -1,320 +1,24 @@
-import { approvalTarget, nextApproval } from "../../rules/approval.ts"
-import { shippedRules } from "../../rules/config.ts"
/**
* The term in office: the seasons turn, the crown asks for goods, the
* town's approval follows how it is treated, the town's history is kept,
* the town rises through its ranks, and the term ends: lost, or run out.
*/
-import { crown, HISTORY_TICKS, stepsOf, WINTER_WARNING, type GoodId } from "../../content/index.ts"
-import * as Random from "@typeonce/ritmo-math/Random"
-import { Building, Census, Charter, Chronicle, Crown, Fate, Game, Rules, History, House, Inventory, Ledger, Mood, Pantry, Paused, Policy, Recipe, Rising, Rng, Site, Stock, Storage, Time, Treasury, TownHall, Upgraded } from "../../schema.ts"
-import { elapsed, seasonAt, termTicks, write } from "../shared.ts"
// ── Time ──────────────────────────────────────────────────────────────────
-/**
- * Winter comes and goes, and the chronicle says so. A minute before it
- * comes, the almanac warns the town how hard it will be, and how long the
- * food in store would last.
- */
-export const Seasons = Game.System(
- "Town/Seasons",
- {
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- stock: Game.System.readResource(Stock),
- pantry: Game.System.readResource(Pantry),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) }
- },
- ({ resources, services }) => {
- const rules = services.rules
- const { winters } = rules
-
- const charter = resources.charter.get()
- const t = elapsed(resources.time.get(), charter)
- if (t <= 0) return
- const now = seasonAt(t, charter, rules)
- const before = seasonAt(t - 1, charter, rules)
- if (now.winter && !before.winter) {
- const w = now.severity ?? "normal"
- write(
- resources.chronicle,
- t,
- `A ${winters[w].title} winter, year ${now.year}: the fields lie still and fisheries catch ${Math.round(winters[w].fishing * 100)}%${winters[w].heating ? "; homes burn fires to keep warm" : ""}.`
- )
- }
- if (!now.winter && before.winter) write(resources.chronicle, t, `Spring of year ${now.year}.`)
- if (!now.winter && now.coming !== null && now.left === WINTER_WARNING) {
- const w = winters[now.coming]
- const eats = resources.pantry.get().eatenLast
- write(
- resources.chronicle,
- t,
- `Winter in a minute, and the almanac says it will be ${w.title}: ${larder(resources.stock.get())} food in store; the town eats ${eats} a minute.`,
- true
- )
- }
- }
-)
+export { Seasons } from "./seasons.ts"
// ── The crown ─────────────────────────────────────────────────────────────
-/** Steps between the crown's requests. */
-export const crownGap = (charter: { readonly term: number }, rules = shippedRules) => Math.round(termTicks(charter, rules) / (rules.crown.perTerm + 1))
-
-/**
- * Every so often the crown asks for something the town makes, and that
- * keeps (never fish or bread): a share of
- * what its workshops and gatherers could make in the time given, larger the
- * later in the term it is. A request not sent in time is a fine and a snub
- * the town's approval remembers.
- */
-export const Requests = Game.System(
- "Town/Requests",
- {
- queries: {
- makers: Game.Query({ selection: { recipe: Game.Query.read(Recipe) }, with: [Building], without: [Site, Rising] }),
- stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] })
- },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- fate: Game.System.readResource(Fate),
- crown: Game.System.writeResource(Crown),
- treasury: Game.System.writeResource(Treasury),
- rng: Game.System.writeResource(Rng),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
- const { goods, crown, spoils } = rules
-
- if (resources.fate.get().state !== "playing") return
- const charter = resources.charter.get()
- const t = elapsed(resources.time.get(), charter)
- const c = resources.crown.get()
- const remembered = c.snubs.filter((at) => t - at < stepsOf(crown.memory * 60))
- if (remembered.length !== c.snubs.length) resources.crown.set({ ...c, snubs: remembered })
-
- if (c.open && t >= c.due) {
- const fine = Math.round(((c.reward - crown.bonus) / crown.reward) * crown.fine) + crown.bonus
- resources.treasury.update((tr) => ({ coins: tr.coins - fine }))
- resources.crown.set({ ...c, open: false, missed: c.missed + 1, streak: c.streak + 1, snubs: [...remembered, t] })
- write(resources.chronicle, t, `The crown's request for ${c.amount} ${goods[c.good].title} went unanswered: a fine of ${fine} coins.`, true)
- return
- }
- if (c.open || t < c.next) return
- // Something the town makes, sized to what it makes of it: from a third of
- // what it can make in the time given, early in the term, to most of it.
- // The crown waits until the town makes anything.
- const rates = new Map<GoodId, number>()
- for (const { data } of queries.makers.each()) {
- const r = data.recipe.get()
- rates.set(r.output, (rates.get(r.output) ?? 0) + (r.batch * 3600) / r.period)
- }
- // Only what keeps: fish and bread would rot on the way.
- const options = [...rates.keys()].filter((g) => spoils[g] === undefined).sort()
- if (options.length === 0) return
- const good = Random.draw(resources.rng).pick(options)!
- // Larger the later in this term it is: a new term starts the crown small again.
- const progress = Math.min(1, Math.max(0, t - resources.fate.get().began) / termTicks(charter, rules))
- const window = (crownGap(charter, rules) * crown.window) / 3600
- const share = crown.share[0] + (crown.share[1] - crown.share[0]) * progress
- // Never more than the town could keep in store.
- const room = queries.stores.each().reduce((sum, { data }) => sum + data.inventory.get().cap, 0)
- const amount = Math.max(4, Math.min(Math.round(room * crown.room), Math.round(rates.get(good)! * window * share)))
- const reward = Math.round(amount * goods[good].price * crown.reward) + crown.bonus
- const gap = crownGap(charter, rules)
- const due = t + Math.round(gap * crown.window)
- resources.crown.set({ ...c, snubs: remembered, open: true, good, amount, issued: t, due, reward, next: t + gap })
- write(resources.chronicle, t, `The crown asks for ${amount} ${goods[good].title} within ${Math.round(((due - t) / 3600) * 10) / 10} minutes, for ${reward} coins.`, true)
- }
-)
+export { crownGap, Requests } from "./requests.ts"
// ── Approval ──────────────────────────────────────────────────────────────
-/**
- * What the town makes of how it is run, every collection: its needs, its
- * taxes, unpaid wages, snubs from the crown, a hungry winter. Approval
- * moves towards that a few points at a time.
- */
-export const Approve = Game.System(
- "Town/Approve",
- {
- queries: { homes: Game.Query({ selection: { house: Game.Query.read(House) }, without: [Site, Rising, Paused] }) },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- policy: Game.System.readResource(Policy),
- treasury: Game.System.readResource(Treasury),
- crown: Game.System.readResource(Crown),
- mood: Game.System.writeResource(Mood)
- },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
-
- const t = elapsed(resources.time.get(), resources.charter.get())
- if (t % stepsOf(10) !== 0) return
- const policy = resources.policy.get()
- const m = resources.mood.get()
- const parts = approvalTarget(queries.homes.each().map(({ data }) => data.house.get()), policy,
- resources.treasury.get().coins, resources.crown.get().snubs.length, seasonAt(t, resources.charter.get(), rules).winter, rules, m.memory)
- resources.mood.set({ approval: nextApproval(m.approval, parts.target, rules), ...parts })
-
- }
-)
+export { Approve } from "./approve.ts"
// ── The end of the term ───────────────────────────────────────────────────
-/** The fate of a town just founded: its first term, a hamlet. */
-export const foundedFate = () => ({
- state: "playing" as const,
- reason: "",
- at: 0,
- term: 1,
- began: 0,
- rank: 0,
- debtSince: -1,
- revoltSince: -1,
- goalSince: -1,
- peak: 0,
- score: 0
-})
-
-import { goalsOf, larder, nextRank, scoreOf, steadyNet } from "../../rules/goals.ts"
export { goalsOf, larder, nextRank, scoreOf, steadyNet } from "../../rules/goals.ts"
-/**
- * Once a second: does the term end, or the town rise? The term is lost to
- * bankruptcy (in debt too long), revolt (approval too low too long),
- * abandonment (the town emptied), or dismissal (the crown's requests
- * missed too many times in a row); and over when it runs out, when the
- * mayor may stand for another. The town rises a rank once every goal of
- * the next has held long enough, and the crown sends a reward; nothing
- * ends. Dangers write to the chronicle as they begin.
- */
-export const Judge = Game.System(
- "Town/Judge",
- {
- queries: { halls: Game.Query({ selection: { upgraded: Game.Query.optional(Upgraded) }, with: [TownHall] }) },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- census: Game.System.readResource(Census),
- treasury: Game.System.writeResource(Treasury),
- ledger: Game.System.readResource(Ledger),
- mood: Game.System.readResource(Mood),
- crown: Game.System.readResource(Crown),
- history: Game.System.readResource(History),
- fate: Game.System.writeResource(Fate),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
- const { crown, fate, ranks } = rules
- // The town hall's upgrades: a city asks for a guildhall.
- const hallRow = queries.halls.each()[0]
- const hall = hallRow ? hallRow.data.upgraded.value()?.level ?? 0 : 0
-
- const charter = resources.charter.get()
- const t = elapsed(resources.time.get(), charter)
- if (t <= 0 || t % 60 !== 0) return
- const f = resources.fate.get()
- if (f.state !== "playing") return
- const census = resources.census.get()
- const coins = resources.treasury.get().coins
- const ledger = resources.ledger.get()
- const approval = resources.mood.get().approval
- const crownNow = resources.crown.get()
- const residents = census.settlers + census.citizens
- const net = steadyNet(resources.history.get().samples, ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin)
- const note = (text: string, alarm = false) => write(resources.chronicle, t, text, alarm)
- const minutes = (n: number) => stepsOf(n * 60)
-
- const next = { ...f, peak: Math.max(f.peak, residents) }
- for (const mark of [50, 100, 250, 500, 1000]) if (f.peak < mark && residents >= mark) note(`${mark} residents.`)
-
- // Dangers.
- if (coins < 0) {
- if (f.debtSince < 0) note("The treasury is empty: wages go unpaid.", true)
- next.debtSince = f.debtSince < 0 ? t : f.debtSince
- } else next.debtSince = -1
- if (approval <= fate.revoltAt) {
- if (f.revoltSince < 0) note("The town is in uproar.", true)
- next.revoltSince = f.revoltSince < 0 ? t : f.revoltSince
- } else next.revoltSince = -1
-
- const end = (state: "lost" | "over", reason: string) => {
- note(reason)
- resources.fate.set({ ...next, state, reason, at: t, score: scoreOf({ ...census, net, approval, met: crownNow.met, missed: crownNow.missed, hall }, next.rank) })
- }
- if (next.debtSince >= 0 && t - next.debtSince >= minutes(fate.debt)) return end("lost", "Bankrupt: the crown has taken the treasury out of the mayor's hands.")
- if (next.revoltSince >= 0 && t - next.revoltSince >= minutes(fate.revolt)) return end("lost", "Revolt: the town has turned the mayor out.")
- if (next.peak >= fate.peak && residents < next.peak * fate.abandon) return end("lost", "Abandoned: the people have left the town.")
- if (crownNow.streak >= crown.patience) return end("lost", `Dismissed: the crown has replaced a mayor who left ${crown.patience} of its requests unanswered.`)
- if (t - f.began >= termTicks(charter, rules)) {
- return end("over", `Term ${f.term} is over; the ${ranks[f.rank]!.title} stands.`)
- }
-
- // The next rank.
- if (nextRank(f.rank, rules) > f.rank) {
- const goals = goalsOf(charter, { ...census, coins, net, approval, hall }, rules, f.rank)
- if (goals.every((g) => g.met)) {
- const to = ranks[f.rank + 1]!
- if (f.goalSince < 0) note(`Every goal of a ${to.title} is met: the town needs only to hold them.`)
- next.goalSince = f.goalSince < 0 ? t : f.goalSince
- if (t - next.goalSince >= minutes(fate.hold)) {
- next.rank = f.rank + 1
- next.goalSince = -1
- resources.treasury.update((tr) => ({ coins: tr.coins + to.reward }))
- note(`The town is now a ${to.title}: the crown sends ${to.reward} coins.`, true)
- }
- } else next.goalSince = -1
- }
- resources.fate.set(next)
- }
-)
-
-/** A sample of the town every `HISTORY_TICKS`. */
-export const Record = Game.System(
- "Town/Record",
- {
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- census: Game.System.readResource(Census),
- treasury: Game.System.readResource(Treasury),
- ledger: Game.System.readResource(Ledger),
- mood: Game.System.readResource(Mood),
- fate: Game.System.readResource(Fate),
- history: Game.System.writeResource(History)
- }
- },
- ({ resources }) => {
- const t = elapsed(resources.time.get(), resources.charter.get())
- if (t <= 0 || t % HISTORY_TICKS !== 0) return
- const f = resources.fate.get()
- if (f.state !== "playing") return
- const census = resources.census.get()
- const ledger = resources.ledger.get()
- const sample = {
- tick: t,
- coins: resources.treasury.get().coins,
- residents: census.settlers + census.citizens,
- citizens: census.citizens,
- approval: resources.mood.get().approval,
- net: ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
- }
- resources.history.update((h) => ({ samples: [...h.samples, sample].slice(-1000) }))
- }
-)
-
+export { foundedFate, Judge } from "./judge.ts"
+export { Record } from "./record.ts"
diff --git a/src/game/systems/term/judge.ts b/src/game/systems/term/judge.ts
new file mode 100644
index 0000000..d49f413
--- /dev/null
+++ b/src/game/systems/term/judge.ts
@@ -0,0 +1,112 @@
+import { crown, stepsOf } from "../../content/index.ts"
+import { Census, Charter, Chronicle, Crown, Fate, Game, Rules, History, Ledger, Mood, Time, Treasury, TownHall, Upgraded } from "../../schema.ts"
+import { elapsed, termTicks, write } from "../shared.ts"
+import { goalsOf, nextRank, scoreOf, steadyNet } from "../../rules/goals.ts"
+
+/** The fate of a town just founded: its first term, a hamlet. */
+export const foundedFate = () => ({
+ state: "playing" as const,
+ reason: "",
+ at: 0,
+ term: 1,
+ began: 0,
+ rank: 0,
+ debtSince: -1,
+ revoltSince: -1,
+ goalSince: -1,
+ peak: 0,
+ score: 0
+})
+
+/**
+ * Once a second: does the term end, or the town rise? The term is lost to
+ * bankruptcy (in debt too long), revolt (approval too low too long),
+ * abandonment (the town emptied), or dismissal (the crown's requests
+ * missed too many times in a row); and over when it runs out, when the
+ * mayor may stand for another. The town rises a rank once every goal of
+ * the next has held long enough, and the crown sends a reward; nothing
+ * ends. Dangers write to the chronicle as they begin.
+ */
+export const Judge = Game.System(
+ "Town/Judge",
+ {
+ queries: { halls: Game.Query({ selection: { upgraded: Game.Query.optional(Upgraded) }, with: [TownHall] }) },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ census: Game.System.readResource(Census),
+ treasury: Game.System.writeResource(Treasury),
+ ledger: Game.System.readResource(Ledger),
+ mood: Game.System.readResource(Mood),
+ crown: Game.System.readResource(Crown),
+ history: Game.System.readResource(History),
+ fate: Game.System.writeResource(Fate),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+ const { crown, fate, ranks } = rules
+ // The town hall's upgrades: a city asks for a guildhall.
+ const hallRow = queries.halls.each()[0]
+ const hall = hallRow ? hallRow.data.upgraded.value()?.level ?? 0 : 0
+
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ if (t <= 0 || t % 60 !== 0) return
+ const f = resources.fate.get()
+ if (f.state !== "playing") return
+ const census = resources.census.get()
+ const coins = resources.treasury.get().coins
+ const ledger = resources.ledger.get()
+ const approval = resources.mood.get().approval
+ const crownNow = resources.crown.get()
+ const residents = census.settlers + census.citizens
+ const net = steadyNet(resources.history.get().samples, ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin)
+ const note = (text: string, alarm = false) => write(resources.chronicle, t, text, alarm)
+ const minutes = (n: number) => stepsOf(n * 60)
+
+ const next = { ...f, peak: Math.max(f.peak, residents) }
+ for (const mark of [50, 100, 250, 500, 1000]) if (f.peak < mark && residents >= mark) note(`${mark} residents.`)
+
+ // Dangers.
+ if (coins < 0) {
+ if (f.debtSince < 0) note("The treasury is empty: wages go unpaid.", true)
+ next.debtSince = f.debtSince < 0 ? t : f.debtSince
+ } else next.debtSince = -1
+ if (approval <= fate.revoltAt) {
+ if (f.revoltSince < 0) note("The town is in uproar.", true)
+ next.revoltSince = f.revoltSince < 0 ? t : f.revoltSince
+ } else next.revoltSince = -1
+
+ const end = (state: "lost" | "over", reason: string) => {
+ note(reason)
+ resources.fate.set({ ...next, state, reason, at: t, score: scoreOf({ ...census, net, approval, met: crownNow.met, missed: crownNow.missed, hall }, next.rank) })
+ }
+ if (next.debtSince >= 0 && t - next.debtSince >= minutes(fate.debt)) return end("lost", "Bankrupt: the crown has taken the treasury out of the mayor's hands.")
+ if (next.revoltSince >= 0 && t - next.revoltSince >= minutes(fate.revolt)) return end("lost", "Revolt: the town has turned the mayor out.")
+ if (next.peak >= fate.peak && residents < next.peak * fate.abandon) return end("lost", "Abandoned: the people have left the town.")
+ if (crownNow.streak >= crown.patience) return end("lost", `Dismissed: the crown has replaced a mayor who left ${crown.patience} of its requests unanswered.`)
+ if (t - f.began >= termTicks(charter, rules)) {
+ return end("over", `Term ${f.term} is over; the ${ranks[f.rank]!.title} stands.`)
+ }
+
+ // The next rank.
+ if (nextRank(f.rank, rules) > f.rank) {
+ const goals = goalsOf(charter, { ...census, coins, net, approval, hall }, rules, f.rank)
+ if (goals.every((g) => g.met)) {
+ const to = ranks[f.rank + 1]!
+ if (f.goalSince < 0) note(`Every goal of a ${to.title} is met: the town needs only to hold them.`)
+ next.goalSince = f.goalSince < 0 ? t : f.goalSince
+ if (t - next.goalSince >= minutes(fate.hold)) {
+ next.rank = f.rank + 1
+ next.goalSince = -1
+ resources.treasury.update((tr) => ({ coins: tr.coins + to.reward }))
+ note(`The town is now a ${to.title}: the crown sends ${to.reward} coins.`, true)
+ }
+ } else next.goalSince = -1
+ }
+ resources.fate.set(next)
+ }
+)
diff --git a/src/game/systems/term/record.ts b/src/game/systems/term/record.ts
new file mode 100644
index 0000000..b09a2d9
--- /dev/null
+++ b/src/game/systems/term/record.ts
@@ -0,0 +1,37 @@
+import { HISTORY_TICKS } from "../../content/index.ts"
+import { Census, Charter, Fate, Game, History, Ledger, Mood, Time, Treasury } from "../../schema.ts"
+import { elapsed } from "../shared.ts"
+
+/** A sample of the town every `HISTORY_TICKS`. */
+export const Record = Game.System(
+ "Town/Record",
+ {
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ census: Game.System.readResource(Census),
+ treasury: Game.System.readResource(Treasury),
+ ledger: Game.System.readResource(Ledger),
+ mood: Game.System.readResource(Mood),
+ fate: Game.System.readResource(Fate),
+ history: Game.System.writeResource(History)
+ }
+ },
+ ({ resources }) => {
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ if (t <= 0 || t % HISTORY_TICKS !== 0) return
+ const f = resources.fate.get()
+ if (f.state !== "playing") return
+ const census = resources.census.get()
+ const ledger = resources.ledger.get()
+ const sample = {
+ tick: t,
+ coins: resources.treasury.get().coins,
+ residents: census.settlers + census.citizens,
+ citizens: census.citizens,
+ approval: resources.mood.get().approval,
+ net: ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin
+ }
+ resources.history.update((h) => ({ samples: [...h.samples, sample].slice(-1000) }))
+ }
+)
diff --git a/src/game/systems/term/requests.ts b/src/game/systems/term/requests.ts
new file mode 100644
index 0000000..c3ebcbc
--- /dev/null
+++ b/src/game/systems/term/requests.ts
@@ -0,0 +1,79 @@
+import { shippedRules } from "../../rules/config.ts"
+import { stepsOf, type GoodId } from "../../content/index.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
+import { Building, Charter, Chronicle, Crown, Fate, Game, Rules, Inventory, Recipe, Rising, Rng, Site, Storage, Time, Treasury } from "../../schema.ts"
+import { elapsed, termTicks, write } from "../shared.ts"
+
+/** Steps between the crown's requests. */
+export const crownGap = (charter: { readonly term: number }, rules = shippedRules) => Math.round(termTicks(charter, rules) / (rules.crown.perTerm + 1))
+
+/**
+ * Every so often the crown asks for something the town makes, and that
+ * keeps (never fish or bread): a share of
+ * what its workshops and gatherers could make in the time given, larger the
+ * later in the term it is. A request not sent in time is a fine and a snub
+ * the town's approval remembers.
+ */
+export const Requests = Game.System(
+ "Town/Requests",
+ {
+ queries: {
+ makers: Game.Query({ selection: { recipe: Game.Query.read(Recipe) }, with: [Building], without: [Site, Rising] }),
+ stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ fate: Game.System.readResource(Fate),
+ crown: Game.System.writeResource(Crown),
+ treasury: Game.System.writeResource(Treasury),
+ rng: Game.System.writeResource(Rng),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+ const { goods, crown, spoils } = rules
+
+ if (resources.fate.get().state !== "playing") return
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ const c = resources.crown.get()
+ const remembered = c.snubs.filter((at) => t - at < stepsOf(crown.memory * 60))
+ if (remembered.length !== c.snubs.length) resources.crown.set({ ...c, snubs: remembered })
+
+ if (c.open && t >= c.due) {
+ const fine = Math.round(((c.reward - crown.bonus) / crown.reward) * crown.fine) + crown.bonus
+ resources.treasury.update((tr) => ({ coins: tr.coins - fine }))
+ resources.crown.set({ ...c, open: false, missed: c.missed + 1, streak: c.streak + 1, snubs: [...remembered, t] })
+ write(resources.chronicle, t, `The crown's request for ${c.amount} ${goods[c.good].title} went unanswered: a fine of ${fine} coins.`, true)
+ return
+ }
+ if (c.open || t < c.next) return
+ // Something the town makes, sized to what it makes of it: from a third of
+ // what it can make in the time given, early in the term, to most of it.
+ // The crown waits until the town makes anything.
+ const rates = new Map<GoodId, number>()
+ for (const { data } of queries.makers.each()) {
+ const r = data.recipe.get()
+ rates.set(r.output, (rates.get(r.output) ?? 0) + (r.batch * 3600) / r.period)
+ }
+ // Only what keeps: fish and bread would rot on the way.
+ const options = [...rates.keys()].filter((g) => spoils[g] === undefined).sort()
+ if (options.length === 0) return
+ const good = Random.draw(resources.rng).pick(options)!
+ // Larger the later in this term it is: a new term starts the crown small again.
+ const progress = Math.min(1, Math.max(0, t - resources.fate.get().began) / termTicks(charter, rules))
+ const window = (crownGap(charter, rules) * crown.window) / 3600
+ const share = crown.share[0] + (crown.share[1] - crown.share[0]) * progress
+ // Never more than the town could keep in store.
+ const room = queries.stores.each().reduce((sum, { data }) => sum + data.inventory.get().cap, 0)
+ const amount = Math.max(4, Math.min(Math.round(room * crown.room), Math.round(rates.get(good)! * window * share)))
+ const reward = Math.round(amount * goods[good].price * crown.reward) + crown.bonus
+ const gap = crownGap(charter, rules)
+ const due = t + Math.round(gap * crown.window)
+ resources.crown.set({ ...c, snubs: remembered, open: true, good, amount, issued: t, due, reward, next: t + gap })
+ write(resources.chronicle, t, `The crown asks for ${amount} ${goods[good].title} within ${Math.round(((due - t) / 3600) * 10) / 10} minutes, for ${reward} coins.`, true)
+ }
+)
diff --git a/src/game/systems/term/seasons.ts b/src/game/systems/term/seasons.ts
new file mode 100644
index 0000000..ce5216d
--- /dev/null
+++ b/src/game/systems/term/seasons.ts
@@ -0,0 +1,52 @@
+import { WINTER_WARNING } from "../../content/index.ts"
+import { Charter, Chronicle, Game, Rules, Pantry, Stock, Time } from "../../schema.ts"
+import { elapsed, seasonAt, write } from "../shared.ts"
+import { larder } from "../../rules/goals.ts"
+
+/**
+ * Winter comes and goes, and the chronicle says so. A minute before it
+ * comes, the almanac warns the town how hard it will be, and how long the
+ * food in store would last.
+ */
+export const Seasons = Game.System(
+ "Town/Seasons",
+ {
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ stock: Game.System.readResource(Stock),
+ pantry: Game.System.readResource(Pantry),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ resources, services }) => {
+ const rules = services.rules
+ const { winters } = rules
+
+ const charter = resources.charter.get()
+ const t = elapsed(resources.time.get(), charter)
+ if (t <= 0) return
+ const now = seasonAt(t, charter, rules)
+ const before = seasonAt(t - 1, charter, rules)
+ if (now.winter && !before.winter) {
+ const w = now.severity ?? "normal"
+ write(
+ resources.chronicle,
+ t,
+ `A ${winters[w].title} winter, year ${now.year}: the fields lie still and fisheries catch ${Math.round(winters[w].fishing * 100)}%${winters[w].heating ? "; homes burn fires to keep warm" : ""}.`
+ )
+ }
+ if (!now.winter && before.winter) write(resources.chronicle, t, `Spring of year ${now.year}.`)
+ if (!now.winter && now.coming !== null && now.left === WINTER_WARNING) {
+ const w = winters[now.coming]
+ const eats = resources.pantry.get().eatenLast
+ write(
+ resources.chronicle,
+ t,
+ `Winter in a minute, and the almanac says it will be ${w.title}: ${larder(resources.stock.get())} food in store; the town eats ${eats} a minute.`,
+ true
+ )
+ }
+ }
+)
diff --git a/src/game/systems/town/collect.ts b/src/game/systems/town/collect.ts
new file mode 100644
index 0000000..82e68b8
--- /dev/null
+++ b/src/game/systems/town/collect.ts
@@ -0,0 +1,90 @@
+import { every } from "../../content/index.ts"
+import { tradeCollection } from "../../rules/trade.ts"
+import { appealAt, parkUpkeep } from "../../world/appeal.ts"
+import { doors, key, reach } from "../../world/grid.ts"
+import { amounts, goodIds, upgradeAt, upkeepOf, type GoodId } from "../../content/index.ts"
+import { Appeal, Building, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Park, Paused, Policy, Rising, Site, Storage, Tile, Time, TownHall, Treasury, Upgraded } from "../../schema.ts"
+import { baseCollection, adminOf, taxOf } from "../../rules/households.ts"
+
+/**
+ * Every `LEDGER_TICKS`: taxes in from homes the town hall can reach by road;
+ * trade with the travelling merchants, who buy what the town sells beyond
+ * its reserve (taken from its storage, fullest first) and sell it what it
+ * buys up to its reserve (brought to the storage with most room), at prices
+ * that fall the more the town sells and rise the more it buys; upkeep out
+ * for every standing building (a quarter for a paused one); and the town
+ * hall's administration, which grows faster than the town.
+ */
+export const Collect = Game.System(
+ "Town/Collect",
+ {
+ queries: {
+ /** A closed home pays nothing and costs the town hall nothing. */
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Paused] }),
+ buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused), upgraded: Game.Query.optional(Upgraded) }, without: [Site] }),
+ halls: Game.Query({ selection: { tile: Game.Query.read(Tile), upgraded: Game.Query.optional(Upgraded) }, with: [TownHall] }),
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] }),
+ parks: Game.Query({ selection: { park: Game.Query.read(Park) } })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ grid: Game.System.readResource(Grid),
+ appeal: Game.System.readResource(Appeal),
+ policy: Game.System.readResource(Policy),
+ market: Game.System.writeResource(Market),
+ treasury: Game.System.writeResource(Treasury),
+ ledger: Game.System.writeResource(Ledger),
+ flow: Game.System.writeResource(Flow)
+ },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+ const { kinds, ledgerTicks: LEDGER_TICKS, pausedUpkeep: PAUSED_UPKEEP } = rules
+
+ if (!every(resources.time.get(), LEDGER_TICKS)) return
+ const grid = resources.grid.get()
+ const policy = resources.policy.get()
+ const hall = queries.halls.each()[0]
+ const roads = hall ? reach(grid, doors(grid, hall.data.tile.get())) : null
+ const share = LEDGER_TICKS / (60 * 60)
+ const cells = resources.appeal.get().cells
+ let taxes = 0
+ let residents = 0
+ for (const { data } of queries.homes.each()) {
+ 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))
+ }
+ let upkeep = 0
+ for (const { data } of queries.buildings.each()) upkeep += upkeepOf(kinds[data.building.get().kind], data.upgraded.value()?.level ?? 0) * (data.paused.present ? PAUSED_UPKEEP : 1)
+ for (const { data } of queries.parks.each()) upkeep += parkUpkeep(data.park.get(), rules)
+ // A guildhall or a city hall runs the town for less (see `Upgrade.admin`).
+ const saves = (hall ? upgradeAt(kinds.townhall, hall.data.upgraded.value()?.level ?? 0)?.admin : undefined) ?? 0
+ const admin = adminOf(residents, rules, saves)
+
+ 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, residents, rules, saves).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()) {
+ const before = row.data.inventory.get().stock
+ const after = traded.stores[i]!.stock
+ for (const g of goodIds) if (after[g] !== before[g]) moved[g] = (moved[g] ?? 0) + after[g] - before[g]
+ row.data.inventory.set(traded.stores[i]!)
+ }
+ if (Object.keys(moved).length > 0) resources.flow.update((f) => ({ ...f, traded: amounts(Object.fromEntries(goodIds.map((g) => [g, f.traded[g] + (moved[g] ?? 0)]))) }))
+ // And the treasury's: the taxes came in, trade changed hands; upkeep and administration are left over as used.
+ const collected = Math.round(taxes * share)
+ resources.flow.update((f) => ({
+ ...f,
+ coins: { ...f.coins, made: f.coins.made + collected, traded: f.coins.traded + traded.traded, booked: f.coins.booked + traded.coins - before }
+ }))
+ resources.market.set({ prices: traded.prices })
+ resources.treasury.set({ coins: traded.coins })
+ resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(traded.traded / share), upkeep: Math.round(upkeep), admin })
+ }
+)
diff --git a/src/game/systems/town/households.ts b/src/game/systems/town/households.ts
new file mode 100644
index 0000000..1d6435a
--- /dev/null
+++ b/src/game/systems/town/households.ts
@@ -0,0 +1,101 @@
+import { appealAt } from "../../world/appeal.ts"
+import { goodIds, type GoodId } from "../../content/index.ts"
+import { Appeal, Burning, Charter, Game, Rules, Grid, House, Inventory, Mood, Paused, Policy, Rebuilt, Rising, Risk, Sick, Site, Storage, Tile, Time, Treasury } from "../../schema.ts"
+import { connected, elapsed, seasonAt } from "../shared.ts"
+import { ageNeeds, mealDecay, capacity, rateOf, shortOf, tierFor } from "../../rules/households.ts"
+
+/**
+ * Needs wear off, food faster in winter. Every so often a home settles
+ * into its tier (see `tierFor`), rising to a tier it was never rebuilt
+ * for only once the treasury and the store pay for it (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.
+ */
+export const Households = Game.System(
+ "Town/Households",
+ {
+ queries: {
+ homes: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ house: Game.Query.write(House),
+ rebuilt: Game.Query.optional(Rebuilt),
+ risk: Game.Query.optional(Risk),
+ sick: Game.Query.optional(Sick),
+ burning: Game.Query.optional(Burning),
+ 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.thisTick(Game.System.readResource(Grid)),
+ mood: Game.System.readResource(Mood),
+ appeal: Game.System.readResource(Appeal),
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ policy: Game.System.readResource(Policy),
+ treasury: Game.System.writeResource(Treasury)
+ },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.inserts(Rebuilt))
+ },
+ ({ queries, resources, commands, 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
+ const policy = resources.policy.get()
+ const cells = resources.appeal.get().cells
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ // In winter a meal lasts two thirds as long.
+ const eat = mealDecay(t, seasonAt(t, resources.charter.get(), rules).winter)
+ for (const { entity, data } of queries.homes.each()) {
+ const h = data.house.get()
+ const next = ageNeeds(h, eat)
+ // A home on fire, or closed by the town, stands empty.
+ if (data.burning.present || data.closed.present) next.residents = 0
+ else if (next.clock % home.settle === 0) {
+ const tile = data.tile.get()
+ const desirability = appealAt(cells, tile.x, tile.y)
+ const tier = tierFor(next, desirability, data.risk.value() ?? { fire: 0, health: 0, order: 0 }, rules)
+ // Rising a tier is a rebuilding, paid for at once, once: a home that cannot be paid for waits, and one
+ // that stepped down moves back up into what it was rebuilt as.
+ const built = data.rebuilt.value()?.tier ?? 1
+ if (tier <= h.tier || tier <= built) next.tier = tier
+ else if (pay(home.tiers[tier].rise)) {
+ next.tier = tier
+ commands.insert(entity, Game.Command.entry(Rebuilt, { tier: tier as 2 | 3 }))
+ }
+ 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)
+ next.residents += Math.sign(cap - next.residents)
+ }
+ data.house.set(next)
+ }
+ }
+)
diff --git a/src/game/systems/town/index.ts b/src/game/systems/town/index.ts
index 96c5f67..fef05bf 100644
--- a/src/game/systems/town/index.ts
+++ b/src/game/systems/town/index.ts
@@ -1,231 +1,10 @@
-import { every } from "../../content/index.ts"
-import { tradeCollection } from "../../rules/trade.ts"
/**
* The town: homes grow, level up, or empty depending on what reaches them;
* taxes are collected from homes connected to the town hall and upkeep paid
* for every standing building and park; and the census counts it all.
*/
-import { appealAt, parkUpkeep } from "../../world/appeal.ts"
-import { doors, key, reach } from "../../world/grid.ts"
-import { amounts, goodIds, upgradeAt, upkeepOf, type GoodId } from "../../content/index.ts"
-import { Appeal, Building, Burning, Census, Charter, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rebuilt, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, Upgraded } from "../../schema.ts"
-import { connected, elapsed, seasonAt } from "../shared.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`), rising to a tier it was never rebuilt
- * for only once the treasury and the store pay for it (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.
- */
-export const Households = Game.System(
- "Town/Households",
- {
- queries: {
- homes: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- house: Game.Query.write(House),
- rebuilt: Game.Query.optional(Rebuilt),
- risk: Game.Query.optional(Risk),
- sick: Game.Query.optional(Sick),
- burning: Game.Query.optional(Burning),
- 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.thisTick(Game.System.readResource(Grid)),
- mood: Game.System.readResource(Mood),
- appeal: Game.System.readResource(Appeal),
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- policy: Game.System.readResource(Policy),
- treasury: Game.System.writeResource(Treasury)
- },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.inserts(Rebuilt))
- },
- ({ queries, resources, commands, 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
- const policy = resources.policy.get()
- const cells = resources.appeal.get().cells
- const t = elapsed(resources.time.get(), resources.charter.get())
- // In winter a meal lasts two thirds as long.
- const eat = mealDecay(t, seasonAt(t, resources.charter.get(), rules).winter)
- for (const { entity, data } of queries.homes.each()) {
- const h = data.house.get()
- const next = ageNeeds(h, eat)
- // A home on fire, or closed by the town, stands empty.
- if (data.burning.present || data.closed.present) next.residents = 0
- else if (next.clock % home.settle === 0) {
- const tile = data.tile.get()
- const desirability = appealAt(cells, tile.x, tile.y)
- const tier = tierFor(next, desirability, data.risk.value() ?? { fire: 0, health: 0, order: 0 }, rules)
- // Rising a tier is a rebuilding, paid for at once, once: a home that cannot be paid for waits, and one
- // that stepped down moves back up into what it was rebuilt as.
- const built = data.rebuilt.value()?.tier ?? 1
- if (tier <= h.tier || tier <= built) next.tier = tier
- else if (pay(home.tiers[tier].rise)) {
- next.tier = tier
- commands.insert(entity, Game.Command.entry(Rebuilt, { tier: tier as 2 | 3 }))
- }
- 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)
- next.residents += Math.sign(cap - next.residents)
- }
- data.house.set(next)
- }
- }
-)
-
-/**
- * Every `LEDGER_TICKS`: taxes in from homes the town hall can reach by road;
- * trade with the travelling merchants, who buy what the town sells beyond
- * its reserve (taken from its storage, fullest first) and sell it what it
- * buys up to its reserve (brought to the storage with most room), at prices
- * that fall the more the town sells and rise the more it buys; upkeep out
- * for every standing building (a quarter for a paused one); and the town
- * hall's administration, which grows faster than the town.
- */
-export const Collect = Game.System(
- "Town/Collect",
- {
- queries: {
- /** A closed home pays nothing and costs the town hall nothing. */
- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Paused] }),
- buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused), upgraded: Game.Query.optional(Upgraded) }, without: [Site] }),
- halls: Game.Query({ selection: { tile: Game.Query.read(Tile), upgraded: Game.Query.optional(Upgraded) }, with: [TownHall] }),
- stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] }),
- parks: Game.Query({ selection: { park: Game.Query.read(Park) } })
- },
- resources: {
- time: Game.System.readResource(Time),
- grid: Game.System.readResource(Grid),
- appeal: Game.System.readResource(Appeal),
- policy: Game.System.readResource(Policy),
- market: Game.System.writeResource(Market),
- treasury: Game.System.writeResource(Treasury),
- ledger: Game.System.writeResource(Ledger),
- flow: Game.System.writeResource(Flow)
- },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
- const { kinds, ledgerTicks: LEDGER_TICKS, pausedUpkeep: PAUSED_UPKEEP } = rules
-
- if (!every(resources.time.get(), LEDGER_TICKS)) return
- const grid = resources.grid.get()
- const policy = resources.policy.get()
- const hall = queries.halls.each()[0]
- const roads = hall ? reach(grid, doors(grid, hall.data.tile.get())) : null
- const share = LEDGER_TICKS / (60 * 60)
- const cells = resources.appeal.get().cells
- let taxes = 0
- let residents = 0
- for (const { data } of queries.homes.each()) {
- 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))
- }
- let upkeep = 0
- for (const { data } of queries.buildings.each()) upkeep += upkeepOf(kinds[data.building.get().kind], data.upgraded.value()?.level ?? 0) * (data.paused.present ? PAUSED_UPKEEP : 1)
- for (const { data } of queries.parks.each()) upkeep += parkUpkeep(data.park.get(), rules)
- // A guildhall or a city hall runs the town for less (see `Upgrade.admin`).
- const saves = (hall ? upgradeAt(kinds.townhall, hall.data.upgraded.value()?.level ?? 0)?.admin : undefined) ?? 0
- const admin = adminOf(residents, rules, saves)
-
- 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, residents, rules, saves).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()) {
- const before = row.data.inventory.get().stock
- const after = traded.stores[i]!.stock
- for (const g of goodIds) if (after[g] !== before[g]) moved[g] = (moved[g] ?? 0) + after[g] - before[g]
- row.data.inventory.set(traded.stores[i]!)
- }
- if (Object.keys(moved).length > 0) resources.flow.update((f) => ({ ...f, traded: amounts(Object.fromEntries(goodIds.map((g) => [g, f.traded[g] + (moved[g] ?? 0)]))) }))
- // And the treasury's: the taxes came in, trade changed hands; upkeep and administration are left over as used.
- const collected = Math.round(taxes * share)
- resources.flow.update((f) => ({
- ...f,
- coins: { ...f.coins, made: f.coins.made + collected, traded: f.coins.traded + traded.traded, booked: f.coins.booked + traded.coins - before }
- }))
- resources.market.set({ prices: traded.prices })
- resources.treasury.set({ coins: traded.coins })
- resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(traded.traded / share), upkeep: Math.round(upkeep), admin })
- }
-)
-
-export const TakeCensus = Game.System(
- "Town/TakeCensus",
- {
- queries: {
- homes: Game.Query({ selection: { house: Game.Query.read(House), sick: Game.Query.optional(Sick) }, without: [Site, Rising, Paused] }),
- workplaces: Game.Query({ selection: { staff: Game.Query.read(Staff) }, without: [Site, Rising] }),
- burning: Game.Query({ selection: { burning: Game.Query.read(Burning) } })
- },
- resources: { census: Game.System.writeResource(Census) }
- },
- ({ queries, resources }) => {
- let homes = 0
- let settlers = 0
- let citizens = 0
- let burghers = 0
- let sick = 0
- const needs = { food: 0, bread: 0, cloth: 0, faith: 0, furniture: 0 }
- for (const { data } of queries.homes.each()) {
- const h = data.house.get()
- homes += 1
- if (h.tier === 1) settlers += h.residents
- else citizens += h.residents
- if (h.tier === 3) burghers += h.residents
- if (data.sick.present) sick += 1
- for (const n of ["food", "bread", "cloth", "faith", "furniture"] as const) if (met(h, n)) needs[n] += 1
- }
- let jobs = 0
- let employed = 0
- for (const { data } of queries.workplaces.each()) {
- const s = data.staff.get()
- jobs += s.needed
- employed += s.assigned
- }
- resources.census.set({ homes, settlers, citizens, burghers, jobs, employed, ...needs, sick, burning: queries.burning.each().length })
- }
-)
+export { Households } from "./households.ts"
+export { Collect } from "./collect.ts"
+export { TakeCensus } from "./take-census.ts"
diff --git a/src/game/systems/town/take-census.ts b/src/game/systems/town/take-census.ts
new file mode 100644
index 0000000..cce72ad
--- /dev/null
+++ b/src/game/systems/town/take-census.ts
@@ -0,0 +1,39 @@
+import { Burning, Census, Game, House, Paused, Rising, Sick, Site, Staff } from "../../schema.ts"
+import { met } from "../../rules/households.ts"
+
+export const TakeCensus = Game.System(
+ "Town/TakeCensus",
+ {
+ queries: {
+ homes: Game.Query({ selection: { house: Game.Query.read(House), sick: Game.Query.optional(Sick) }, without: [Site, Rising, Paused] }),
+ workplaces: Game.Query({ selection: { staff: Game.Query.read(Staff) }, without: [Site, Rising] }),
+ burning: Game.Query({ selection: { burning: Game.Query.read(Burning) } })
+ },
+ resources: { census: Game.System.writeResource(Census) }
+ },
+ ({ queries, resources }) => {
+ let homes = 0
+ let settlers = 0
+ let citizens = 0
+ let burghers = 0
+ let sick = 0
+ const needs = { food: 0, bread: 0, cloth: 0, faith: 0, furniture: 0 }
+ for (const { data } of queries.homes.each()) {
+ const h = data.house.get()
+ homes += 1
+ if (h.tier === 1) settlers += h.residents
+ else citizens += h.residents
+ if (h.tier === 3) burghers += h.residents
+ if (data.sick.present) sick += 1
+ for (const n of ["food", "bread", "cloth", "faith", "furniture"] as const) if (met(h, n)) needs[n] += 1
+ }
+ let jobs = 0
+ let employed = 0
+ for (const { data } of queries.workplaces.each()) {
+ const s = data.staff.get()
+ jobs += s.needed
+ employed += s.assigned
+ }
+ resources.census.set({ homes, settlers, citizens, burghers, jobs, employed, ...needs, sick, burning: queries.burning.each().length })
+ }
+)
diff --git a/src/game/systems/walkers/index.ts b/src/game/systems/walkers/index.ts
index f46c5b6..951f7a2 100644
--- a/src/game/systems/walkers/index.ts
+++ b/src/game/systems/walkers/index.ts
@@ -1,7 +1,3 @@
-import { serveGoods } from "../../rules/households.ts"
-import { transport } from "../../rules/config.ts"
-import { planPatrols } from "../../rules/patrol.ts"
-import { appealAt } from "../../world/appeal.ts"
/**
* Walking: every walker steps along its route; service buildings send a
* walker out now and then, who wanders the roads serving the homes beside
@@ -10,293 +6,6 @@ import { appealAt } from "../../world/appeal.ts"
* keeping down the risk of fire, sickness, and disorder, a builder's with
* planks and stone to mend — and walks home when its range is walked.
*/
-
-import { amounts, categoryColor, each, provisions, stepsOf, total, type Amounts } from "../../content/index.ts"
-import { DIRS, doors, isRoad, key, nearest, ownerAt, pathTo, reach, useAt } from "../../world/grid.ts"
-import { inside, type Point } from "../../world/iso.ts"
-import { Building, Burning, Condition, Figure, Game, Rules, Grid, Appeal, Handed, Patrol, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Roam, Route, Service, Sick, Site, Staff, Status, Tile, Time, WalkerOf, type HandedValue, type Status as StatusValue } from "../../schema.ts"
-import { CELL_STEPS } from "../shared.ts"
-import { paced } from "../work/index.ts"
-
-/** Steps a walker takes each tick: 1.25 cells a second. */
-const WALK = transport.walk
-/** Firefighters run to a blaze. */
-const RUN = transport.run
-/** Of each provision, the most a walker's basket holds. */
-const BASKET = transport.basket
-/** Walkers a service building may have out on the roads at once. */
-const OUT = transport.active
-
-/**
- * Every walker steps along its route (a firefighter on the way to a blaze
- * runs, and anyone on a paved street goes `pavedPace` as fast); one whose
- * next cell is no longer road is lost.
- */
-export const Walk = Game.System(
- "Town/Walk",
- {
- queries: { walkers: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.optional(Rescue) } }) },
- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.despawns(Route))
- },
- ({ queries, resources, commands, services }) => {
- const grid = resources.grid.get()
- const tick = resources.time.get().step
- const quicker = services.rules.pavedPace - 1
- for (const { entity, data } of queries.walkers.each()) {
- const route = data.route.get()
- const last = route.cells.length - 1
- if (route.index >= last) continue
- const next = route.cells[route.index + 1]!
- if (!isRoad(grid, next.x, next.y)) {
- commands.despawn(entity)
- continue
- }
- const running = data.rescue.present && !data.rescue.get().back
- const paved = !running && quicker > 0 && (grid.paved?.has(key(next.x, next.y)) ?? false) && paced(quicker, tick)
- const step = route.step + (running ? RUN : WALK) + (paved ? 1 : 0)
- if (step < CELL_STEPS) data.route.set({ ...route, step })
- else {
- const index = route.index + 1
- data.route.set({ ...route, index, step: index >= last ? 0 : step - CELL_STEPS })
- }
- }
- }
-)
-
-/**
- * A staffed service building sends a walker every `interval` steps, up to
- * `OUT` at a time. A provisions walker fills its basket from the building's stock, and
- * only goes when there is something to hand out.
- */
-export const SendWalkers = Game.System(
- "Town/SendWalkers",
- {
- queries: {
- services: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- building: Game.Query.read(Building),
- staff: Game.Query.read(Staff),
- service: Game.Query.write(Service),
- status: Game.Query.write(Status),
- inventory: Game.Query.optional(Inventory),
- recipe: Game.Query.optional(Recipe),
- paused: Game.Query.optional(Paused)
- },
- without: [Site, Rising, Burning]
- }),
- inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] }),
- patrols: Game.Query({ selection: { patrol: Game.Query.write(Patrol) } }),
- targets: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.optional(House) }, with: [Condition], without: [Site, Rising, Burning] }),
- walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })
- },
- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.spawns(Roam), Game.System.inserts(Patrol), Game.System.relates(WalkerOf))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { kinds, apprentice: APPRENTICE } = rules
-
- const grid = resources.grid.get()
- const tick = resources.time.get().step
- const out = new Map<number, number>()
- for (const { data } of queries.walkers.each()) out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
-
- for (const { entity, data } of queries.services.each()) {
- const service = data.service.get()
- const staff = data.staff.get()
- const starts = doors(grid, data.tile.get())
- const stock = data.inventory.value()?.stock
- const staffed = !data.paused.present && (staff.needed === 0 || staff.assigned > 0)
- const carries = (g: (typeof provisions)[number]) =>
- service.service === "goods" ? provisions.includes(g) : service.service === "repair" ? g === "planks" || g === "stone" : false
- const basket: Amounts = each((g) => (stock && carries(g) ? Math.min(BASKET, stock[g]) : 0))
- const goes = service.service === "goods" ? total(basket) > 0 : service.service === "repair" ? basket.planks > 0 : true
- if (!data.recipe.value()) {
- const status: StatusValue = data.paused.present
- ? "paused"
- : starts.length === 0
- ? "unconnected"
- : !staffed
- ? "unstaffed"
- : out.has(entity.id)
- ? "working"
- : goes
- ? "idle"
- : "starved"
- if (data.status.get() !== status) data.status.set(status)
- }
-
- // A crew of apprentices sends walkers less often.
- const learning = staff.assigned > 0 && staff.assigned === staff.apprentices && !paced(APPRENTICE, tick)
- const cooldown = learning ? service.cooldown : Math.max(0, service.cooldown - 1)
- if (cooldown === 0 && (out.get(entity.id) ?? 0) < OUT && starts.length > 0 && staffed && goes) {
- const targets = queries.targets.each().filter(({ data }) => service.service === "fire" || service.service === "repair" || data.house.present)
- .map(({ entity, data }) => ({ id: entity.id as number, tile: data.tile.get() }))
- const plan = planPatrols(grid, data.tile.get(), service.range, targets)
- if (plan.tours.length === 0) continue
- const patrol = queries.patrols.get(entity.id)
- const cursor = patrol.ok ? patrol.value.data.patrol.get().next : 0
- const tour = plan.tours[cursor % plan.tours.length]!
- if (patrol.ok) patrol.value.data.patrol.set({ next: (cursor + 1) % plan.tours.length })
- else commands.insert(entity, Game.Command.entry(Patrol, { next: 1 % plan.tours.length }))
- const color = categoryColor[kinds[data.building.get().kind].category]
- const draft = Game.Command.spawn(
- [Figure, { role: "walker", color }],
- [Route, { cells: [...tour], index: 0, step: 0 }],
- [Roam, { service: service.service, left: tour.length, basket, back: false }]
- )
- commands.spawn(Game.Command.relate(draft, WalkerOf, entity.id))
- const inv = queries.inventories.get(entity.id)
- if (inv.ok && total(basket) > 0) {
- const i = inv.value.data.inventory.get()
- inv.value.data.inventory.set({ ...i, stock: each((g) => i.stock[g] - basket[g]) })
- }
- data.service.set({ ...service, cooldown: service.interval })
- } else if (cooldown !== service.cooldown) data.service.set({ ...service, cooldown })
- }
- }
-)
-
-const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
-
-/**
- * A service walker wanders: at each cell it serves the homes (and, for a
- * fire watch or a builder, the buildings) beside it, then follows its planned tour. The service rotates its tours to cover every
- * reachable target. Once its tour is
- * walked, or its basket is empty, it heads home by the shortest road, and
- * puts back what it still carries.
- *
- * A home low on a need takes what meets it: bread or else fish (fresh
- * first, then smoked) for food (bread meets the citizens' bread need too),
- * cloth for cloth; a chapel's walker brings faith. A watchman, a physician,
- * and a constable reset the risk they look after (a physician cures the
- * sick; a constable's visit is the end of a home's thefts); a builder mends
- * whatever is run down, a plank for a home, a plank and a stone for a
- * building.
- */
-export const Wander = Game.System(
- "Town/Wander",
- {
- queries: {
- walkers: Game.Query({ selection: { route: Game.Query.write(Route), roam: Game.Query.write(Roam), home: Game.Query.readRelation(WalkerOf) } }),
- homes: Game.Query({ selection: { house: Game.Query.write(House) }, without: [Site, Rising, Paused] }),
- cared: Game.Query({
- selection: { risk: Game.Query.write(Risk), condition: Game.Query.write(Condition), sick: Game.Query.optional(Sick) },
- without: [Site, Rising]
- }),
- buildings: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Service] }),
- inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })
- },
- resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), pantry: Game.System.writeResource(Pantry), handed: Game.System.writeResource(Handed), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.despawns(Roam), Game.System.removes(Sick))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { home, condition: wear, conditionMax: CONDITION_MAX } = rules
-
- const grid = resources.grid.get()
- const walkers = queries.walkers.each()
- const homes = new Map<number, ReturnType<typeof queries.homes.each>[number]>()
- for (const row of queries.homes.each()) homes.set(row.entity.id, row)
- const cared = new Map<number, ReturnType<typeof queries.cared.each>[number]>()
- for (const row of queries.cared.each()) cared.set(row.entity.id, row)
- let eaten = 0
- // What each walker hands each home, for its building's last minute (see `Handed`).
- const tick = resources.time.get().step
- const handed: Array<HandedValue["log"][number]> = []
-
- for (const { entity, data } of walkers) {
- const route = data.route.get()
- const roam = data.roam.get()
- // left counts cells still to serve. Older saves can finish their current short segment.
- if (roam.back ? !arrived(route) : roam.left > route.cells.length ? !arrived(route) : route.index < route.cells.length - roam.left) continue
- const from = data.home.get()
-
- if (roam.back) {
- const inv = queries.inventories.get(from)
- if (inv.ok && total(roam.basket) > 0) {
- const i = inv.value.data.inventory.get()
- // What it did not hand out goes back on the shelf, even past its room (the shelf filled again meanwhile):
- // the building asks for no more until it is down again, and nothing is lost.
- inv.value.data.inventory.set({ ...i, stock: each((g) => i.stock[g] + roam.basket[g]) })
- }
- commands.despawn(entity)
- continue
- }
-
- // Serve the homes (and buildings) beside this cell.
- const cell = route.cells[route.index]!
- const basket: Record<string, number> = { ...roam.basket }
- const served = new Set<number>()
- for (const d of DIRS) {
- const x = cell.x + d.x
- const y = cell.y + d.y
- if (!inside(x, y)) continue
- const use = useAt(grid, x, y)
- if (use !== "house" && use !== "building") continue
- const id = ownerAt(grid, x, y)
- if (served.has(id)) continue
- served.add(id)
- const row = use === "house" ? homes.get(id) : undefined
- const care = cared.get(id)
- if (row) {
- const h = { ...row.data.house.get() }
- if (roam.service === "faith") h.faith = home.lasts.faith
- else if (roam.service === "goods") {
- const served = serveGoods(h, amounts(basket), rules, appealAt(resources.appeal.get().cells, x, y))
- const given = Object.fromEntries(Object.entries(served.basket).filter(([g, n]) => (basket[g] ?? 0) > n).map(([g, n]) => [g, (basket[g] ?? 0) - n]))
- if (Object.keys(given).length > 0) handed.push({ at: tick, from: data.home.get(), to: id, goods: given })
- Object.assign(h, served.house)
- Object.assign(basket, served.basket)
- eaten += served.eaten
- }
- row.data.house.set(h)
- }
- if (!care) continue
- const r = care.data.risk.get()
- if (roam.service === "fire" && r.fire > 0) care.data.risk.set({ ...r, fire: 0 })
- if (row && roam.service === "health") {
- if (r.health > 0) care.data.risk.set({ ...r, health: 0 })
- if (care.data.sick.present) commands.remove(care.entity, Sick)
- }
- if (row && roam.service === "order" && (r.order > 0 || r.thefts > 0)) care.data.risk.set({ ...r, order: 0, thefts: 0 })
- if (roam.service === "repair") {
- const c = care.data.condition.get().value
- if (c < wear.mend && (basket.planks ?? 0) > 0) {
- basket.planks = (basket.planks ?? 0) - 1
- const stone = !row && (basket.stone ?? 0) > 0
- if (stone) basket.stone = (basket.stone ?? 0) - 1
- care.data.condition.set({ value: row || stone ? CONDITION_MAX : Math.min(CONDITION_MAX, c + 300) })
- }
- }
- }
- const left = roam.left - 1
- const carrying = amounts(basket)
- const keepsGoing = roam.service === "goods" ? total(carrying) > 0 : roam.service === "repair" ? carrying.planks > 0 : true
- if (left > 0 && keepsGoing && !arrived(route)) {
- data.roam.set({ ...roam, left, basket: carrying })
- continue
- }
-
- // Head home.
- const building = queries.buildings.get(from)
- const way = reach(grid, [cell])
- const door = building.ok ? nearest(way, doors(grid, building.value.data.tile.get())) : null
- if (!door) {
- commands.despawn(entity)
- continue
- }
- data.route.set({ cells: pathTo(way, door.cell), index: 0, step: 0 })
- data.roam.set({ ...roam, left: 0, basket: carrying, back: true })
- }
- if (eaten > 0) resources.pantry.update((p) => ({ ...p, eaten: p.eaten + eaten }))
- // The last minute only; a log from another town (its clock behind this one's) is dropped.
- const kept = resources.handed.get().log.filter((l) => l.at <= tick && tick - l.at < stepsOf(60))
- if (handed.length > 0 || kept.length !== resources.handed.get().log.length) resources.handed.set({ log: [...kept, ...handed] })
- }
-)
+export { Walk } from "./walk.ts"
+export { SendWalkers } from "./send-walkers.ts"
+export { Wander } from "./wander.ts"
diff --git a/src/game/systems/walkers/send-walkers.ts b/src/game/systems/walkers/send-walkers.ts
new file mode 100644
index 0000000..344654b
--- /dev/null
+++ b/src/game/systems/walkers/send-walkers.ts
@@ -0,0 +1,107 @@
+import { transport } from "../../rules/config.ts"
+import { planPatrols } from "../../rules/patrol.ts"
+import { categoryColor, each, provisions, total, type Amounts } from "../../content/index.ts"
+import { doors } from "../../world/grid.ts"
+import { Building, Burning, Condition, Figure, Game, Rules, Grid, Patrol, House, Inventory, Paused, Recipe, Rising, Roam, Route, Service, Site, Staff, Status, Tile, Time, WalkerOf, type Status as StatusValue } from "../../schema.ts"
+import { paced } from "../work/index.ts"
+
+/** Of each provision, the most a walker's basket holds. */
+const BASKET = transport.basket
+/** Walkers a service building may have out on the roads at once. */
+const OUT = transport.active
+
+/**
+ * A staffed service building sends a walker every `interval` steps, up to
+ * `OUT` at a time. A provisions walker fills its basket from the building's stock, and
+ * only goes when there is something to hand out.
+ */
+export const SendWalkers = Game.System(
+ "Town/SendWalkers",
+ {
+ queries: {
+ services: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
+ staff: Game.Query.read(Staff),
+ service: Game.Query.write(Service),
+ status: Game.Query.write(Status),
+ inventory: Game.Query.optional(Inventory),
+ recipe: Game.Query.optional(Recipe),
+ paused: Game.Query.optional(Paused)
+ },
+ without: [Site, Rising, Burning]
+ }),
+ inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] }),
+ patrols: Game.Query({ selection: { patrol: Game.Query.write(Patrol) } }),
+ targets: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.optional(House) }, with: [Condition], without: [Site, Rising, Burning] }),
+ walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })
+ },
+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Roam), Game.System.inserts(Patrol), Game.System.relates(WalkerOf))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { kinds, apprentice: APPRENTICE } = rules
+
+ const grid = resources.grid.get()
+ const tick = resources.time.get().step
+ const out = new Map<number, number>()
+ for (const { data } of queries.walkers.each()) out.set(data.home.get(), (out.get(data.home.get()) ?? 0) + 1)
+
+ for (const { entity, data } of queries.services.each()) {
+ const service = data.service.get()
+ const staff = data.staff.get()
+ const starts = doors(grid, data.tile.get())
+ const stock = data.inventory.value()?.stock
+ const staffed = !data.paused.present && (staff.needed === 0 || staff.assigned > 0)
+ const carries = (g: (typeof provisions)[number]) =>
+ service.service === "goods" ? provisions.includes(g) : service.service === "repair" ? g === "planks" || g === "stone" : false
+ const basket: Amounts = each((g) => (stock && carries(g) ? Math.min(BASKET, stock[g]) : 0))
+ const goes = service.service === "goods" ? total(basket) > 0 : service.service === "repair" ? basket.planks > 0 : true
+ if (!data.recipe.value()) {
+ const status: StatusValue = data.paused.present
+ ? "paused"
+ : starts.length === 0
+ ? "unconnected"
+ : !staffed
+ ? "unstaffed"
+ : out.has(entity.id)
+ ? "working"
+ : goes
+ ? "idle"
+ : "starved"
+ if (data.status.get() !== status) data.status.set(status)
+ }
+
+ // A crew of apprentices sends walkers less often.
+ const learning = staff.assigned > 0 && staff.assigned === staff.apprentices && !paced(APPRENTICE, tick)
+ const cooldown = learning ? service.cooldown : Math.max(0, service.cooldown - 1)
+ if (cooldown === 0 && (out.get(entity.id) ?? 0) < OUT && starts.length > 0 && staffed && goes) {
+ const targets = queries.targets.each().filter(({ data }) => service.service === "fire" || service.service === "repair" || data.house.present)
+ .map(({ entity, data }) => ({ id: entity.id as number, tile: data.tile.get() }))
+ const plan = planPatrols(grid, data.tile.get(), service.range, targets)
+ if (plan.tours.length === 0) continue
+ const patrol = queries.patrols.get(entity.id)
+ const cursor = patrol.ok ? patrol.value.data.patrol.get().next : 0
+ const tour = plan.tours[cursor % plan.tours.length]!
+ if (patrol.ok) patrol.value.data.patrol.set({ next: (cursor + 1) % plan.tours.length })
+ else commands.insert(entity, Game.Command.entry(Patrol, { next: 1 % plan.tours.length }))
+ const color = categoryColor[kinds[data.building.get().kind].category]
+ const draft = Game.Command.spawn(
+ [Figure, { role: "walker", color }],
+ [Route, { cells: [...tour], index: 0, step: 0 }],
+ [Roam, { service: service.service, left: tour.length, basket, back: false }]
+ )
+ commands.spawn(Game.Command.relate(draft, WalkerOf, entity.id))
+ const inv = queries.inventories.get(entity.id)
+ if (inv.ok && total(basket) > 0) {
+ const i = inv.value.data.inventory.get()
+ inv.value.data.inventory.set({ ...i, stock: each((g) => i.stock[g] - basket[g]) })
+ }
+ data.service.set({ ...service, cooldown: service.interval })
+ } else if (cooldown !== service.cooldown) data.service.set({ ...service, cooldown })
+ }
+ }
+)
diff --git a/src/game/systems/walkers/walk.ts b/src/game/systems/walkers/walk.ts
new file mode 100644
index 0000000..e4311a9
--- /dev/null
+++ b/src/game/systems/walkers/walk.ts
@@ -0,0 +1,48 @@
+import { transport } from "../../rules/config.ts"
+import { isRoad, key } from "../../world/grid.ts"
+import { Game, Rules, Grid, Rescue, Route, Time } from "../../schema.ts"
+import { CELL_STEPS } from "../shared.ts"
+import { paced } from "../work/index.ts"
+
+/** Steps a walker takes each tick: 1.25 cells a second. */
+const WALK = transport.walk
+/** Firefighters run to a blaze. */
+const RUN = transport.run
+
+/**
+ * Every walker steps along its route (a firefighter on the way to a blaze
+ * runs, and anyone on a paved street goes `pavedPace` as fast); one whose
+ * next cell is no longer road is lost.
+ */
+export const Walk = Game.System(
+ "Town/Walk",
+ {
+ queries: { walkers: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.optional(Rescue) } }) },
+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Route))
+ },
+ ({ queries, resources, commands, services }) => {
+ const grid = resources.grid.get()
+ const tick = resources.time.get().step
+ const quicker = services.rules.pavedPace - 1
+ for (const { entity, data } of queries.walkers.each()) {
+ const route = data.route.get()
+ const last = route.cells.length - 1
+ if (route.index >= last) continue
+ const next = route.cells[route.index + 1]!
+ if (!isRoad(grid, next.x, next.y)) {
+ commands.despawn(entity)
+ continue
+ }
+ const running = data.rescue.present && !data.rescue.get().back
+ const paved = !running && quicker > 0 && (grid.paved?.has(key(next.x, next.y)) ?? false) && paced(quicker, tick)
+ const step = route.step + (running ? RUN : WALK) + (paved ? 1 : 0)
+ if (step < CELL_STEPS) data.route.set({ ...route, step })
+ else {
+ const index = route.index + 1
+ data.route.set({ ...route, index, step: index >= last ? 0 : step - CELL_STEPS })
+ }
+ }
+ }
+)
diff --git a/src/game/systems/walkers/wander.ts b/src/game/systems/walkers/wander.ts
new file mode 100644
index 0000000..fc1364b
--- /dev/null
+++ b/src/game/systems/walkers/wander.ts
@@ -0,0 +1,146 @@
+import { serveGoods } from "../../rules/households.ts"
+import { appealAt } from "../../world/appeal.ts"
+import { amounts, each, stepsOf, total } from "../../content/index.ts"
+import { DIRS, doors, nearest, ownerAt, pathTo, reach, useAt } from "../../world/grid.ts"
+import { inside, type Point } from "../../world/iso.ts"
+import { Condition, Game, Rules, Grid, Appeal, Handed, House, Inventory, Pantry, Paused, Rising, Risk, Roam, Route, Service, Sick, Site, Tile, Time, WalkerOf, type HandedValue } from "../../schema.ts"
+
+const arrived = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number }) => route.index >= route.cells.length - 1
+
+/**
+ * A service walker wanders: at each cell it serves the homes (and, for a
+ * fire watch or a builder, the buildings) beside it, then follows its planned tour. The service rotates its tours to cover every
+ * reachable target. Once its tour is
+ * walked, or its basket is empty, it heads home by the shortest road, and
+ * puts back what it still carries.
+ *
+ * A home low on a need takes what meets it: bread or else fish (fresh
+ * first, then smoked) for food (bread meets the citizens' bread need too),
+ * cloth for cloth; a chapel's walker brings faith. A watchman, a physician,
+ * and a constable reset the risk they look after (a physician cures the
+ * sick; a constable's visit is the end of a home's thefts); a builder mends
+ * whatever is run down, a plank for a home, a plank and a stone for a
+ * building.
+ */
+export const Wander = Game.System(
+ "Town/Wander",
+ {
+ queries: {
+ walkers: Game.Query({ selection: { route: Game.Query.write(Route), roam: Game.Query.write(Roam), home: Game.Query.readRelation(WalkerOf) } }),
+ homes: Game.Query({ selection: { house: Game.Query.write(House) }, without: [Site, Rising, Paused] }),
+ cared: Game.Query({
+ selection: { risk: Game.Query.write(Risk), condition: Game.Query.write(Condition), sick: Game.Query.optional(Sick) },
+ without: [Site, Rising]
+ }),
+ buildings: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Service] }),
+ inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })
+ },
+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), pantry: Game.System.writeResource(Pantry), handed: Game.System.writeResource(Handed), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Roam), Game.System.removes(Sick))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { home, condition: wear, conditionMax: CONDITION_MAX } = rules
+
+ const grid = resources.grid.get()
+ const walkers = queries.walkers.each()
+ const homes = new Map<number, ReturnType<typeof queries.homes.each>[number]>()
+ for (const row of queries.homes.each()) homes.set(row.entity.id, row)
+ const cared = new Map<number, ReturnType<typeof queries.cared.each>[number]>()
+ for (const row of queries.cared.each()) cared.set(row.entity.id, row)
+ let eaten = 0
+ // What each walker hands each home, for its building's last minute (see `Handed`).
+ const tick = resources.time.get().step
+ const handed: Array<HandedValue["log"][number]> = []
+
+ for (const { entity, data } of walkers) {
+ const route = data.route.get()
+ const roam = data.roam.get()
+ // left counts cells still to serve. Older saves can finish their current short segment.
+ if (roam.back ? !arrived(route) : roam.left > route.cells.length ? !arrived(route) : route.index < route.cells.length - roam.left) continue
+ const from = data.home.get()
+
+ if (roam.back) {
+ const inv = queries.inventories.get(from)
+ if (inv.ok && total(roam.basket) > 0) {
+ const i = inv.value.data.inventory.get()
+ // What it did not hand out goes back on the shelf, even past its room (the shelf filled again meanwhile):
+ // the building asks for no more until it is down again, and nothing is lost.
+ inv.value.data.inventory.set({ ...i, stock: each((g) => i.stock[g] + roam.basket[g]) })
+ }
+ commands.despawn(entity)
+ continue
+ }
+
+ // Serve the homes (and buildings) beside this cell.
+ const cell = route.cells[route.index]!
+ const basket: Record<string, number> = { ...roam.basket }
+ const served = new Set<number>()
+ for (const d of DIRS) {
+ const x = cell.x + d.x
+ const y = cell.y + d.y
+ if (!inside(x, y)) continue
+ const use = useAt(grid, x, y)
+ if (use !== "house" && use !== "building") continue
+ const id = ownerAt(grid, x, y)
+ if (served.has(id)) continue
+ served.add(id)
+ const row = use === "house" ? homes.get(id) : undefined
+ const care = cared.get(id)
+ if (row) {
+ const h = { ...row.data.house.get() }
+ if (roam.service === "faith") h.faith = home.lasts.faith
+ else if (roam.service === "goods") {
+ const served = serveGoods(h, amounts(basket), rules, appealAt(resources.appeal.get().cells, x, y))
+ const given = Object.fromEntries(Object.entries(served.basket).filter(([g, n]) => (basket[g] ?? 0) > n).map(([g, n]) => [g, (basket[g] ?? 0) - n]))
+ if (Object.keys(given).length > 0) handed.push({ at: tick, from: data.home.get(), to: id, goods: given })
+ Object.assign(h, served.house)
+ Object.assign(basket, served.basket)
+ eaten += served.eaten
+ }
+ row.data.house.set(h)
+ }
+ if (!care) continue
+ const r = care.data.risk.get()
+ if (roam.service === "fire" && r.fire > 0) care.data.risk.set({ ...r, fire: 0 })
+ if (row && roam.service === "health") {
+ if (r.health > 0) care.data.risk.set({ ...r, health: 0 })
+ if (care.data.sick.present) commands.remove(care.entity, Sick)
+ }
+ if (row && roam.service === "order" && (r.order > 0 || r.thefts > 0)) care.data.risk.set({ ...r, order: 0, thefts: 0 })
+ if (roam.service === "repair") {
+ const c = care.data.condition.get().value
+ if (c < wear.mend && (basket.planks ?? 0) > 0) {
+ basket.planks = (basket.planks ?? 0) - 1
+ const stone = !row && (basket.stone ?? 0) > 0
+ if (stone) basket.stone = (basket.stone ?? 0) - 1
+ care.data.condition.set({ value: row || stone ? CONDITION_MAX : Math.min(CONDITION_MAX, c + 300) })
+ }
+ }
+ }
+ const left = roam.left - 1
+ const carrying = amounts(basket)
+ const keepsGoing = roam.service === "goods" ? total(carrying) > 0 : roam.service === "repair" ? carrying.planks > 0 : true
+ if (left > 0 && keepsGoing && !arrived(route)) {
+ data.roam.set({ ...roam, left, basket: carrying })
+ continue
+ }
+
+ // Head home.
+ const building = queries.buildings.get(from)
+ const way = reach(grid, [cell])
+ const door = building.ok ? nearest(way, doors(grid, building.value.data.tile.get())) : null
+ if (!door) {
+ commands.despawn(entity)
+ continue
+ }
+ data.route.set({ cells: pathTo(way, door.cell), index: 0, step: 0 })
+ data.roam.set({ ...roam, left: 0, basket: carrying, back: true })
+ }
+ if (eaten > 0) resources.pantry.update((p) => ({ ...p, eaten: p.eaten + eaten }))
+ // The last minute only; a log from another town (its clock behind this one's) is dropped.
+ const kept = resources.handed.get().log.filter((l) => l.at <= tick && tick - l.at < stepsOf(60))
+ if (handed.length > 0 || kept.length !== resources.handed.get().log.length) resources.handed.set({ log: [...kept, ...handed] })
+ }
+)
diff --git a/src/game/systems/work/assign-staff.ts b/src/game/systems/work/assign-staff.ts
new file mode 100644
index 0000000..19ef43c
--- /dev/null
+++ b/src/game/systems/work/assign-staff.ts
@@ -0,0 +1,93 @@
+import { every } from "../../content/index.ts"
+import { crewOf, stepsOf, type Crew } from "../../content/index.ts"
+import { doors, key, reach } from "../../world/grid.ts"
+import { Building, Burning, Game, Rules, Grid, House, Paused, Rising, Site, Staff, Tile, Time } from "../../schema.ts"
+import { assignWorkers } from "../../rules/production.ts"
+
+/** Workers are reassigned this often: residents move in and out every few seconds, no faster. */
+export const STAFF_TICKS = stepsOf(0.5)
+
+/**
+ * Residents go to work at the workplaces within a commute of their home
+ * (`COMMUTE` road cells), nearest homes first; the workplaces with the
+ * fewest of their crew within reach are staffed first (in the order they
+ * were placed, among equals), so a mine with its own cottages is not robbed
+ * of them by a workshop in town. Settlers do the rough work and citizens the skilled; citizens
+ * never take a settlers' job, and settlers fill a citizens' job only once
+ * every workplace has had its own crew, as apprentices at a slower pace. A
+ * paused or burning building gets nobody.
+ */
+export const AssignStaff = Game.System(
+ "Town/AssignStaff",
+ {
+ queries: {
+ homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
+ workplaces: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
+ staff: Game.Query.write(Staff),
+ paused: Game.Query.optional(Paused),
+ burning: Game.Query.optional(Burning)
+ },
+ without: [Site, Rising]
+ })
+ },
+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+ const { kinds, commute: COMMUTE, staffTicks: STAFF_TICKS } = rules
+
+ if (!every(resources.time.get(), STAFF_TICKS)) return
+ const grid = resources.grid.get()
+ const homes: Array<{ readonly id: number; readonly crew: Crew; left: number; readonly doors: ReadonlyArray<{ readonly x: number; readonly y: number }> }> = []
+ for (const { entity, data } of queries.homes.each()) {
+ const h = data.house.get()
+ const ds = doors(grid, data.tile.get())
+ if (h.residents > 0 && ds.length > 0) homes.push({ id: entity.id, crew: crewOf(h.tier), left: h.residents, doors: ds })
+ }
+ type Row = ReturnType<typeof queries.workplaces.each>[number]
+ const places: Array<{
+ readonly id: number;
+ readonly data: Row["data"]
+ readonly staff: { readonly needed: number; readonly assigned: number; readonly apprentices: number; readonly nearby: number }
+ readonly crew: Crew
+ readonly within: ReadonlyArray<{ readonly home: (typeof homes)[number]; readonly distance: number }>
+ assigned: number
+ apprentices: number
+ readonly nearby: number
+ }> = []
+ for (const { entity, data } of queries.workplaces.each()) {
+ const staff = data.staff.get()
+ if (staff.needed === 0) continue
+ const crew = kinds[data.building.get().kind].crew
+ const starts = doors(grid, data.tile.get())
+ const within: Array<{ readonly home: (typeof homes)[number]; readonly distance: number }> = []
+ if (starts.length > 0 && !data.paused.present && !data.burning.present) {
+ const roads = reach(grid, starts)
+ for (const home of homes) {
+ let distance = -1
+ for (const d of home.doors) {
+ const n = roads.distance[key(d.x, d.y)]!
+ if (n >= 0 && (distance < 0 || n < distance)) distance = n
+ }
+ if (distance >= 0 && distance <= COMMUTE) within.push({ home, distance })
+ }
+ within.sort((a, b) => a.distance - b.distance)
+ }
+ const nearby = within.reduce((n, w) => n + (w.home.crew === crew ? w.home.left : 0), 0)
+ places.push({ id: entity.id, data, staff, crew, within, assigned: 0, apprentices: 0, nearby })
+ }
+ const assigned = assignWorkers(
+ homes.map((h) => ({ id: h.id, crew: h.crew, residents: h.left })),
+ places.map((p) => ({ id: p.id, crew: p.crew, needed: p.staff.needed,
+ within: p.within.map((w) => ({ home: w.home.id, distance: w.distance })) }))
+ )
+ for (const { id, data, staff } of places) {
+ const next = assigned.get(id)!
+ if (staff.assigned !== next.assigned || staff.apprentices !== next.apprentices || staff.nearby !== next.nearby) data.staff.set({ ...staff, ...next })
+ }
+ }
+)
diff --git a/src/game/systems/work/count-stock.ts b/src/game/systems/work/count-stock.ts
new file mode 100644
index 0000000..8540dbb
--- /dev/null
+++ b/src/game/systems/work/count-stock.ts
@@ -0,0 +1,91 @@
+import { amounts, goodIds, stepsOf, type Amounts } from "../../content/index.ts"
+import { Charter, Errand, Flow, Roam, Game, Inventory, Rising, Site, Stock, Storage, Time, Treasury } from "../../schema.ts"
+import { each } from "./per-good.ts"
+
+/** The flow of goods is counted in slices this many seconds long, and the last `FLOW_SLICES` of them (a minute) are kept. */
+const FLOW_SLICE = 10
+const FLOW_SLICES = 6
+
+/**
+ * The goods in every storage, summed; and everything the town holds,
+ * anywhere, for the minute's `Flow`, which closes every minute.
+ */
+export const CountStock = Game.System(
+ "Town/CountStock",
+ {
+ queries: {
+ stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] }),
+ shelves: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, without: [Site, Rising] }),
+ baskets: Game.Query({ selection: { roam: Game.Query.read(Roam) } }),
+ crates: Game.Query({ selection: { errand: Game.Query.read(Errand) } })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ stock: Game.System.writeResource(Stock),
+ treasury: Game.System.readResource(Treasury),
+ flow: Game.System.writeResource(Flow)
+ }
+ },
+ ({ queries, resources }) => {
+ const sum: Record<string, number> = { ...amounts({}) }
+ for (const { data } of queries.stores.each()) {
+ const s = data.inventory.get().stock
+ for (const g of goodIds) sum[g] = (sum[g] ?? 0) + s[g]
+ }
+ resources.stock.set(sum as Amounts)
+
+ const held: Record<string, number> = { ...amounts({}) }
+ for (const { data } of queries.shelves.each()) {
+ const s = data.inventory.get().stock
+ for (const g of goodIds) held[g] = held[g]! + s[g]
+ }
+ for (const { data } of queries.baskets.each()) {
+ const b = data.roam.get().basket
+ for (const g of goodIds) held[g] = held[g]! + b[g]
+ }
+ for (const { data } of queries.crates.each()) {
+ const e = data.errand.get()
+ held[e.good] = held[e.good]! + e.count
+ }
+ const tick = resources.time.get().step
+ const charter = resources.charter.get()
+ const town = `${charter.seed}:${charter.founded}`
+ const f = resources.flow.get()
+ const now = held as Amounts
+ const treasury = resources.treasury.get().coins
+ const fresh = { start: treasury, made: 0, traded: 0, seen: treasury, booked: 0 }
+ // A new or loaded town, or the clock gone back: start counting again from here.
+ if (f.town !== town || tick < f.since || f.start === null) {
+ resources.flow.set({ town, since: tick, start: now, made: amounts({}), traded: amounts({}), held: now, coins: fresh, slices: [], last: null })
+ return
+ }
+ // Coins that came in other than by the collection (a reward, a refund) were made; any that went out are left over as used.
+ const other = treasury - f.coins.seen - f.coins.booked
+ const coins = { ...f.coins, made: f.coins.made + Math.max(0, other), seen: treasury, booked: 0 }
+ if (tick - f.since < stepsOf(FLOW_SLICE)) {
+ resources.flow.set({ ...f, held: now, coins })
+ return
+ }
+ // A slice is done: the last minute rolls on by one, and is reckoned again.
+ const slices = [...f.slices, { start: f.start, made: f.made, traded: f.traded, coins: { start: coins.start, made: coins.made, traded: coins.traded } }].slice(-FLOW_SLICES)
+ const enough = slices.length >= FLOW_SLICES / 2
+ const scale = FLOW_SLICES / slices.length
+ const over = (key: "made" | "traded") => each((g) => slices.reduce((n, s) => n + s[key][g], 0))
+ const made = over("made"), traded = over("traded")
+ const used = each((g) => Math.max(0, slices[0]!.start[g] + made[g] + traded[g] - now[g]))
+ const perMinute = (a: Amounts) => each((g) => Math.round(a[g] * scale))
+ const coinsMade = slices.reduce((n, s) => n + s.coins.made, 0)
+ const coinsTraded = slices.reduce((n, s) => n + s.coins.traded, 0)
+ const coinsUsed = Math.max(0, slices[0]!.coins.start + coinsMade + coinsTraded - treasury)
+ resources.flow.set({
+ town, since: tick, start: now, made: amounts({}), traded: amounts({}), held: now, coins: fresh, slices,
+ last: enough
+ ? {
+ made: perMinute(made), used: perMinute(used), traded: perMinute(traded),
+ coins: { made: Math.round(coinsMade * scale), used: Math.round(coinsUsed * scale), traded: Math.round(coinsTraded * scale) }
+ }
+ : null
+ })
+ }
+)
diff --git a/src/game/systems/work/grow.ts b/src/game/systems/work/grow.ts
new file mode 100644
index 0000000..d70d76d
--- /dev/null
+++ b/src/game/systems/work/grow.ts
@@ -0,0 +1,31 @@
+import { every } from "../../content/index.ts"
+import { Charter, Field, Game, Rules, Time, Tree } from "../../schema.ts"
+import { elapsed, seasonAt } from "../shared.ts"
+
+/** Trees and fields grow until they are ready; fields not in winter. */
+export const Grow = Game.System(
+ "Town/Grow",
+ {
+ queries: {
+ trees: Game.Query({ selection: { tree: Game.Query.write(Tree) } }),
+ fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
+ },
+ resources: { time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },
+ services: { rules: Game.System.service(Rules) }
+ },
+ ({ queries, resources, services }) => {
+ const rules = services.rules
+ const { grown: GROWN, growTicks: GROW_TICKS } = rules
+
+ if (!every(resources.time.get(), GROW_TICKS)) return
+ for (const { data } of queries.trees.each()) {
+ const growth = data.tree.get().growth
+ if (growth < GROWN.tree) data.tree.set({ growth: Math.min(GROWN.tree, growth + GROW_TICKS) })
+ }
+ if (seasonAt(elapsed(resources.time.get(), resources.charter.get()), resources.charter.get(), rules).winter) return
+ for (const { data } of queries.fields.each()) {
+ const growth = data.field.get().growth
+ if (growth < GROWN.field) data.field.set({ growth: Math.min(GROWN.field, growth + GROW_TICKS) })
+ }
+ }
+)
diff --git a/src/game/systems/work/index-grid.ts b/src/game/systems/work/index-grid.ts
new file mode 100644
index 0000000..6bbd839
--- /dev/null
+++ b/src/game/systems/work/index-grid.ts
@@ -0,0 +1,38 @@
+import { GridBuilder, key, roadPrint } from "../../world/grid.ts"
+import { Game, Grid, Land, Paved, Tile } from "../../schema.ts"
+import { TileRead, useOf } from "../shared.ts"
+
+/**
+ * What stands where on the land, for every system after it this step.
+ * Tiles never move, so the grid is only rebuilt when one is laid or one of
+ * those standing on it goes (a load spawns the whole world again, so it is
+ * rebuilt then too).
+ */
+export const IndexGrid = Game.System(
+ "Town/IndexGrid",
+ {
+ queries: {
+ tiles: TileRead,
+ /** A tile laid, or a road just paved: the grid's paved cells change without any tile coming or going. */
+ laid: Game.Query({ selection: {}, filters: [Game.Query.anyOf(Game.Query.added(Tile), Game.Query.added(Paved))] })
+ },
+ despawned: { entities: Game.System.readDespawned() },
+ resources: { land: Game.System.readResource(Land), grid: Game.System.writeResource(Grid) }
+ },
+ ({ queries, despawned, resources }) => {
+ const known = resources.grid.get().tiles
+ const changed = known === undefined || queries.laid.each().length > 0 || despawned.entities.all().some((id) => known.has(id))
+ if (!changed) return
+ const grid = new GridBuilder(resources.land.get().mask)
+ const tiles = new Set<number>()
+ const paved = new Set<number>()
+ for (const { entity, data } of queries.tiles.each()) {
+ const t = data.tile.get()
+ grid.claim(t, entity.id, useOf(data))
+ tiles.add(entity.id)
+ if (data.road.present && data.paved.present) paved.add(key(t.x, t.y))
+ }
+ const value = grid.value()
+ resources.grid.set({ ...value, roads: roadPrint(value), tiles, paved })
+ }
+)
diff --git a/src/game/systems/work/index.ts b/src/game/systems/work/index.ts
index 6252401..cceada6 100644
--- a/src/game/systems/work/index.ts
+++ b/src/game/systems/work/index.ts
@@ -1,632 +1,28 @@
-import { every } from "../../content/index.ts"
-import { wildTreeSpots, canSeedTree } from "../../rules/land.ts"
/**
* Building and working: the grid and the town's stock are indexed, sites
* whose materials are in start going up, workers are assigned, recipes
* turn inputs (or the land) into goods, planters sow trees and fields, and
* what is sown grows.
*/
-import * as Random from "@typeonce/ritmo-math/Random"
-
-import { fieldDraft, treeDraft } from "../../world/archetypes.ts"
-import { amounts, anA, asUpgraded, crewOf, goodIds, stepsOf, total, upgradeAt, worksNeeded, type Amounts, type Crew } from "../../content/index.ts"
-
-/** The flow of goods is counted in slices this many seconds long, and the last `FLOW_SLICES` of them (a minute) are kept. */
-const FLOW_SLICE = 10
-const FLOW_SLICES = 6
-
-const each = (f: (g: (typeof goodIds)[number]) => number): Amounts => Object.fromEntries(goodIds.map((g) => [g, f(g)])) as Amounts
-import { around, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../../world/grid.ts"
-import { Building, Burning, Carriers, Charter, Chronicle, Errand, Flow, Roam, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Service, Site, Staff, Status, Stock, Storage, Tile, Time, Treasury, Tree, Upgraded, type Status as StatusValue, Water, Works } from "../../schema.ts"
-import { connected, elapsed, seasonAt, TileRead, useOf, write } from "../shared.ts"
-
-import { assignWorkers, equipmentPace, effort, paced } from "../../rules/production.ts"
export { effort, paced } from "../../rules/production.ts"
-/**
- * What stands where on the land, for every system after it this step.
- * Tiles never move, so the grid is only rebuilt when one is laid or one of
- * those standing on it goes (a load spawns the whole world again, so it is
- * rebuilt then too).
- */
-export const IndexGrid = Game.System(
- "Town/IndexGrid",
- {
- queries: {
- tiles: TileRead,
- /** A tile laid, or a road just paved: the grid's paved cells change without any tile coming or going. */
- laid: Game.Query({ selection: {}, filters: [Game.Query.anyOf(Game.Query.added(Tile), Game.Query.added(Paved))] })
- },
- despawned: { entities: Game.System.readDespawned() },
- resources: { land: Game.System.readResource(Land), grid: Game.System.writeResource(Grid) }
- },
- ({ queries, despawned, resources }) => {
- const known = resources.grid.get().tiles
- const changed = known === undefined || queries.laid.each().length > 0 || despawned.entities.all().some((id) => known.has(id))
- if (!changed) return
- const grid = new GridBuilder(resources.land.get().mask)
- const tiles = new Set<number>()
- const paved = new Set<number>()
- for (const { entity, data } of queries.tiles.each()) {
- const t = data.tile.get()
- grid.claim(t, entity.id, useOf(data))
- tiles.add(entity.id)
- if (data.road.present && data.paved.present) paved.add(key(t.x, t.y))
- }
- const value = grid.value()
- resources.grid.set({ ...value, roads: roadPrint(value), tiles, paved })
- }
-)
-
-/**
- * The goods in every storage, summed; and everything the town holds,
- * anywhere, for the minute's `Flow`, which closes every minute.
- */
-export const CountStock = Game.System(
- "Town/CountStock",
- {
- queries: {
- stores: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, with: [Storage], without: [Site, Rising] }),
- shelves: Game.Query({ selection: { inventory: Game.Query.read(Inventory) }, without: [Site, Rising] }),
- baskets: Game.Query({ selection: { roam: Game.Query.read(Roam) } }),
- crates: Game.Query({ selection: { errand: Game.Query.read(Errand) } })
- },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- stock: Game.System.writeResource(Stock),
- treasury: Game.System.readResource(Treasury),
- flow: Game.System.writeResource(Flow)
- }
- },
- ({ queries, resources }) => {
- const sum: Record<string, number> = { ...amounts({}) }
- for (const { data } of queries.stores.each()) {
- const s = data.inventory.get().stock
- for (const g of goodIds) sum[g] = (sum[g] ?? 0) + s[g]
- }
- resources.stock.set(sum as Amounts)
-
- const held: Record<string, number> = { ...amounts({}) }
- for (const { data } of queries.shelves.each()) {
- const s = data.inventory.get().stock
- for (const g of goodIds) held[g] = held[g]! + s[g]
- }
- for (const { data } of queries.baskets.each()) {
- const b = data.roam.get().basket
- for (const g of goodIds) held[g] = held[g]! + b[g]
- }
- for (const { data } of queries.crates.each()) {
- const e = data.errand.get()
- held[e.good] = held[e.good]! + e.count
- }
- const tick = resources.time.get().step
- const charter = resources.charter.get()
- const town = `${charter.seed}:${charter.founded}`
- const f = resources.flow.get()
- const now = held as Amounts
- const treasury = resources.treasury.get().coins
- const fresh = { start: treasury, made: 0, traded: 0, seen: treasury, booked: 0 }
- // A new or loaded town, or the clock gone back: start counting again from here.
- if (f.town !== town || tick < f.since || f.start === null) {
- resources.flow.set({ town, since: tick, start: now, made: amounts({}), traded: amounts({}), held: now, coins: fresh, slices: [], last: null })
- return
- }
- // Coins that came in other than by the collection (a reward, a refund) were made; any that went out are left over as used.
- const other = treasury - f.coins.seen - f.coins.booked
- const coins = { ...f.coins, made: f.coins.made + Math.max(0, other), seen: treasury, booked: 0 }
- if (tick - f.since < stepsOf(FLOW_SLICE)) {
- resources.flow.set({ ...f, held: now, coins })
- return
- }
- // A slice is done: the last minute rolls on by one, and is reckoned again.
- const slices = [...f.slices, { start: f.start, made: f.made, traded: f.traded, coins: { start: coins.start, made: coins.made, traded: coins.traded } }].slice(-FLOW_SLICES)
- const enough = slices.length >= FLOW_SLICES / 2
- const scale = FLOW_SLICES / slices.length
- const over = (key: "made" | "traded") => each((g) => slices.reduce((n, s) => n + s[key][g], 0))
- const made = over("made"), traded = over("traded")
- const used = each((g) => Math.max(0, slices[0]!.start[g] + made[g] + traded[g] - now[g]))
- const perMinute = (a: Amounts) => each((g) => Math.round(a[g] * scale))
- const coinsMade = slices.reduce((n, s) => n + s.coins.made, 0)
- const coinsTraded = slices.reduce((n, s) => n + s.coins.traded, 0)
- const coinsUsed = Math.max(0, slices[0]!.coins.start + coinsMade + coinsTraded - treasury)
- resources.flow.set({
- town, since: tick, start: now, made: amounts({}), traded: amounts({}), held: now, coins: fresh, slices,
- last: enough
- ? {
- made: perMinute(made), used: perMinute(used), traded: perMinute(traded),
- coins: { made: Math.round(coinsMade * scale), used: Math.round(coinsUsed * scale), traded: Math.round(coinsTraded * scale) }
- }
- : null
- })
- }
-)
+export { IndexGrid } from "./index-grid.ts"
+export { CountStock } from "./count-stock.ts"
// ── Going up ──────────────────────────────────────────────────────────────
-/** How often a storage under works takes a crate for it from its own shelves. */
-const SELF_SUPPLY_TICKS = stepsOf(1)
-
-/** Where a site's walls are once its materials are in: it goes on rising from here. */
-export const SITE_SHARE = 0.35
-
-export const Raise = Game.System(
- "Town/Raise",
- {
- queries: {
- sites: Game.Query({ selection: { site: Game.Query.read(Site) } }),
- rising: Game.Query({ selection: { rising: Game.Query.write(Rising), status: Game.Query.optional(Status) } }),
- works: Game.Query({
- selection: {
- works: Game.Query.write(Works),
- building: Game.Query.read(Building),
- staff: Game.Query.write(Staff),
- recipe: Game.Query.optional(Recipe),
- carriers: Game.Query.optional(Carriers),
- service: Game.Query.optional(Service)
- }
- }),
- /** A storage under works (the town hall, a warehouse): its own shelves. */
- stocked: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage, Works] })
- },
- resources: {
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.removes(Works, Site, Rising), Game.System.inserts(Upgraded, Recipe, Carriers, Service, Rising, Status))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { buildTicks: BUILD_TICKS } = rules
-
- // An upgrade whose materials are all in stands upgraded: it works from here on as `asUpgraded` says,
- // keeping what it holds and what it was in the middle of.
- const tick = resources.time.get().step
- for (const { entity, data } of queries.works.each()) {
- let works = data.works.get()
- // A storage under works (the town hall) builds with what it holds itself, a crate at a time.
- const shelves = queries.stocked.get(entity.id)
- if (shelves.ok && tick % SELF_SUPPLY_TICKS === 0) {
- const own = shelves.value.data.inventory.get()
- const g = goodIds.find((g) => works.owed[g] > 0 && own.stock[g] > 0)
- if (g) {
- const n = Math.min(rules.transport.load, works.owed[g], own.stock[g])
- shelves.value.data.inventory.set({ ...own, stock: { ...own.stock, [g]: own.stock[g] - n } })
- works = { ...works, owed: { ...works.owed, [g]: works.owed[g] - n } }
- data.works.set(works)
- }
- }
- // Builders work on as the materials come in, never ahead of them.
- const needed = worksNeeded(works.total, rules), allowed = needed * (1 - total(works.owed) / Math.max(1, works.total))
- if (works.done < allowed) {
- works = { ...works, done: works.done + 1 }
- data.works.set(works)
- }
- if (total(works.owed) > 0 || works.done < needed) continue
- const base = rules.kinds[data.building.get().kind], kind = asUpgraded(base, works.level)
- commands.remove(entity, Works)
- commands.insert(entity, Game.Command.entry(Upgraded, { level: works.level }))
- data.staff.set({ ...data.staff.get(), needed: kind.workers })
- const recipe = data.recipe.value(), carriers = data.carriers.value(), service = data.service.value()
- if (recipe && kind.recipe) commands.insert(entity, Game.Command.entry(Recipe, { ...recipe, period: stepsOf(kind.recipe.seconds) }))
- if (shelves.ok && kind.holds) shelves.value.data.inventory.set({ ...shelves.value.data.inventory.get(), cap: kind.holds.cap })
- if (carriers && kind.carriers) commands.insert(entity, Game.Command.entry(Carriers, { count: kind.carriers }))
- if (service && kind.service) commands.insert(entity, Game.Command.entry(Service, { ...service, interval: stepsOf(kind.service.seconds), range: kind.service.range }))
- const was = (upgradeAt(base, works.level - 1)?.title ?? base.title).toLowerCase()
- write(resources.chronicle, elapsed(resources.time.get(), resources.charter.get()), `The ${was} is now ${anA(upgradeAt(base, works.level)!.title.toLowerCase())}.`, true)
- }
-
- for (const { entity, data } of queries.sites.each()) {
- if (total(data.site.get().owed) > 0) continue
- commands.remove(entity, Site)
- commands.insert(entity, Game.Command.entry(Rising, { ticks: Math.round(BUILD_TICKS * SITE_SHARE) }))
- }
- for (const { entity, data } of queries.rising.each()) {
- const ticks = data.rising.get().ticks + 1
- if (ticks >= BUILD_TICKS) {
- commands.remove(entity, Rising)
- // Up and standing; its work (if it has any) says otherwise from here on.
- if (data.status.present) commands.insert(entity, Game.Command.entry(Status, "idle"))
- } else data.rising.set({ ticks })
- }
- }
-)
+export { Raise, SITE_SHARE } from "./raise.ts"
// ── Workers ───────────────────────────────────────────────────────────────
-/** Workers are reassigned this often: residents move in and out every few seconds, no faster. */
-export const STAFF_TICKS = stepsOf(0.5)
-
-/**
- * Residents go to work at the workplaces within a commute of their home
- * (`COMMUTE` road cells), nearest homes first; the workplaces with the
- * fewest of their crew within reach are staffed first (in the order they
- * were placed, among equals), so a mine with its own cottages is not robbed
- * of them by a workshop in town. Settlers do the rough work and citizens the skilled; citizens
- * never take a settlers' job, and settlers fill a citizens' job only once
- * every workplace has had its own crew, as apprentices at a slower pace. A
- * paused or burning building gets nobody.
- */
-export const AssignStaff = Game.System(
- "Town/AssignStaff",
- {
- queries: {
- homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising, Burning] }),
- workplaces: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- building: Game.Query.read(Building),
- staff: Game.Query.write(Staff),
- paused: Game.Query.optional(Paused),
- burning: Game.Query.optional(Burning)
- },
- without: [Site, Rising]
- })
- },
- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
- const { kinds, commute: COMMUTE, staffTicks: STAFF_TICKS } = rules
-
- if (!every(resources.time.get(), STAFF_TICKS)) return
- const grid = resources.grid.get()
- const homes: Array<{ readonly id: number; readonly crew: Crew; left: number; readonly doors: ReadonlyArray<{ readonly x: number; readonly y: number }> }> = []
- for (const { entity, data } of queries.homes.each()) {
- const h = data.house.get()
- const ds = doors(grid, data.tile.get())
- if (h.residents > 0 && ds.length > 0) homes.push({ id: entity.id, crew: crewOf(h.tier), left: h.residents, doors: ds })
- }
- type Row = ReturnType<typeof queries.workplaces.each>[number]
- const places: Array<{
- readonly id: number;
- readonly data: Row["data"]
- readonly staff: { readonly needed: number; readonly assigned: number; readonly apprentices: number; readonly nearby: number }
- readonly crew: Crew
- readonly within: ReadonlyArray<{ readonly home: (typeof homes)[number]; readonly distance: number }>
- assigned: number
- apprentices: number
- readonly nearby: number
- }> = []
- for (const { entity, data } of queries.workplaces.each()) {
- const staff = data.staff.get()
- if (staff.needed === 0) continue
- const crew = kinds[data.building.get().kind].crew
- const starts = doors(grid, data.tile.get())
- const within: Array<{ readonly home: (typeof homes)[number]; readonly distance: number }> = []
- if (starts.length > 0 && !data.paused.present && !data.burning.present) {
- const roads = reach(grid, starts)
- for (const home of homes) {
- let distance = -1
- for (const d of home.doors) {
- const n = roads.distance[key(d.x, d.y)]!
- if (n >= 0 && (distance < 0 || n < distance)) distance = n
- }
- if (distance >= 0 && distance <= COMMUTE) within.push({ home, distance })
- }
- within.sort((a, b) => a.distance - b.distance)
- }
- const nearby = within.reduce((n, w) => n + (w.home.crew === crew ? w.home.left : 0), 0)
- places.push({ id: entity.id, data, staff, crew, within, assigned: 0, apprentices: 0, nearby })
- }
- const assigned = assignWorkers(
- homes.map((h) => ({ id: h.id, crew: h.crew, residents: h.left })),
- places.map((p) => ({ id: p.id, crew: p.crew, needed: p.staff.needed,
- within: p.within.map((w) => ({ home: w.home.id, distance: w.distance })) }))
- )
- for (const { id, data, staff } of places) {
- const next = assigned.get(id)!
- if (staff.assigned !== next.assigned || staff.apprentices !== next.apprentices || staff.nearby !== next.nearby) data.staff.set({ ...staff, ...next })
- }
- }
-)
+export { AssignStaff, STAFF_TICKS } from "./assign-staff.ts"
// ── Recipes ───────────────────────────────────────────────────────────────
-/**
- * One step of every recipe. A job starts when there is room for what it
- * makes, its input is in, and (for a gatherer) the land has what it needs
- * within reach: a grown tree is felled, a rock chipped, a ripe field
- * reaped, a rested cell of water fished. Then the crew puts its
- * worker-steps in; a full crew finishes in `period` steps. It goes at half
- * pace without the tools it wears out, and
- * at half pace again once it is run down; in winter, fishing goes at the
- * winter's pace (a hard winter's is a quarter).
- */
-export const Work = Game.System(
- "Town/Work",
- {
- queries: {
- workshops: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- building: Game.Query.read(Building),
- staff: Game.Query.read(Staff),
- recipe: Game.Query.write(Recipe),
- inventory: Game.Query.write(Inventory),
- status: Game.Query.write(Status),
- gatherer: Game.Query.optional(Gatherer),
- paused: Game.Query.optional(Paused),
- condition: Game.Query.optional(Condition),
- upgraded: Game.Query.optional(Upgraded)
- },
- without: [Site, Rising]
- }),
- trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),
- rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),
- fields: Game.Query({ selection: { field: Game.Query.write(Field) } }),
- waters: Game.Query({ selection: { water: Game.Query.write(Water) } })
- },
- resources: {
- grid: Game.System.readResource(Grid),
- time: Game.System.readResource(Time),
- charter: Game.System.readResource(Charter),
- flow: Game.System.writeResource(Flow),
- chronicle: Game.System.writeResource(Chronicle)
- },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.despawns(Tree))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { kinds, winters, grown: GROWN } = rules
- const made: Record<string, number> = {}
-
- const grid = resources.grid.get()
- const tick = resources.time.get().step
- const t = elapsed(resources.time.get(), resources.charter.get())
- const season = seasonAt(t, resources.charter.get(), rules)
- const fishing = season.severity ? winters[season.severity].fishing : 1
- // The land by entity, looked up only once some gatherer starts a job this step.
- const lazy = <T>(make: () => T) => {
- let value: T | undefined
- return () => (value ??= make())
- }
- const trees = lazy(() => new Map(queries.trees.each().map((row) => [row.entity.id as number, row])))
- const rocks = lazy(() => new Map(queries.rocks.each().map((row) => [row.entity.id as number, row])))
- const fields = lazy(() => new Map(queries.fields.each().map((row) => [row.entity.id as number, row])))
- const waters = lazy(() => new Map(queries.waters.each().map((row) => [row.entity.id as number, row])))
- const used = new Set<number>()
- // A worked face gives one more now and then.
- if (tick % rules.faceTicks === 0)
- for (const { data } of queries.rocks.each()) {
- const r = data.rock.get()
- if (r.amount <= 0) data.rock.set({ ...r, amount: 1 })
- }
-
- /** Takes what a gatherer needs from the land within reach, or says there is none. */
- const gather = (source: "tree" | "stone" | "ore" | "field" | "water", tile: { x: number; y: number; size: number }, radius: number, deep = false): boolean => {
- for (const c of around(tile, radius)) {
- const use = useAt(grid, c.x, c.y)
- const id = ownerAt(grid, c.x, c.y)
- if (used.has(id)) continue
- if (source === "water" && use === "water") {
- // A cell fished rests a while before it gives another catch.
- const water = waters().get(id)
- if (!water || tick - water.data.water.get().fished < rules.restockTicks) continue
- water.data.water.set({ fished: tick })
- used.add(id)
- return true
- }
- if (source === "tree" && use === "tree") {
- const tree = trees().get(id)
- if (!tree || tree.data.tree.get().growth < GROWN.tree) continue
- commands.despawn(tree.entity)
- used.add(id)
- return true
- }
- if ((source === "stone" || source === "ore") && use === "rock") {
- const rock = rocks().get(id)
- if (!rock) continue
- const r = rock.data.rock.get()
- if (r.ore !== (source === "ore")) continue
- // A masonry cuts a worked face at full pace (see `Upgrade.deep`); anyone else waits for it.
- if (r.amount <= 0) {
- if (!deep) continue
- used.add(id)
- return true
- }
- // Quarried down, a rock stays as a worked face (see `FACE_TICKS`).
- rock.data.rock.set({ ...r, amount: r.amount - 1 })
- if (r.amount === 2 && ![...rocks().values()].some((o) => o !== rock && o.data.rock.get().ore === r.ore && o.data.rock.get().amount >= 2))
- write(
- resources.chronicle,
- t,
- r.ore
- ? "The last of the open ore is dug: the worked faces still give a little, slowly. Traders sell ore and tools."
- : "The last of the open stone is quarried: the worked faces still give a little, slowly. Traders sell stone.",
- true,
- c
- )
- return true
- }
- if (source === "field" && use === "field") {
- const field = fields().get(id)
- if (!field || field.data.field.get().growth < GROWN.field) continue
- field.data.field.set({ growth: 0 })
- used.add(id)
- return true
- }
- }
- return false
- }
-
- for (const { data } of queries.workshops.each()) {
- const tile = data.tile.get()
- const kind = kinds[data.building.get().kind]
- const staff = data.staff.get()
- const gatherer = data.gatherer.value()
- let recipe = data.recipe.get()
- const inventory = data.inventory.get()
- let stock = inventory.stock
- const open = connected(grid, tile)
- const room = stock[recipe.output] + recipe.batch <= inventory.cap
- const fed = recipe.input === null || stock[recipe.input] >= recipe.inputs
- let short = !fed
-
- if (open && staff.assigned > 0 && recipe.progress === 0 && room && fed) {
- const deep = upgradeAt(kind, data.upgraded.value()?.level ?? 0)?.deep ?? false
- if (gatherer && !gather(gatherer.source, tile, gatherer.radius, deep)) short = true
- else {
- if (recipe.input !== null) stock = { ...stock, [recipe.input]: stock[recipe.input] - recipe.inputs }
- recipe = { ...recipe, progress: 1 }
- }
- }
-
- const pace = equipmentPace(kind, stock.tools, data.condition.value()?.value ?? Infinity, fishing, rules)
- const put = effort(staff, tick, rules)
- if (open && recipe.progress > 0 && put > 0 && paced(pace, tick)) {
- const progress = recipe.progress + put
- if (progress > recipe.period * staff.needed) {
- recipe = { ...recipe, progress: 0, made: recipe.made + 1 }
- stock = { ...stock, [recipe.output]: stock[recipe.output] + recipe.batch }
- made[recipe.output] = (made[recipe.output] ?? 0) + recipe.batch
- // Every so many jobs wear out a tool.
- if (kind.wear && recipe.made % kind.wear === 0 && stock.tools > 0) stock = { ...stock, tools: stock.tools - 1 }
- } else recipe = { ...recipe, progress }
- }
- const status: StatusValue = data.paused.present
- ? "paused"
- : !open
- ? "unconnected"
- : staff.assigned === 0
- ? "unstaffed"
- : recipe.progress > 0
- ? "working"
- : !room
- ? "blocked"
- : short
- ? "starved"
- : "idle"
- data.recipe.set(recipe)
- if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })
- if (data.status.get() !== status) data.status.set(status)
- }
- if (Object.keys(made).length > 0) resources.flow.update((f) => ({ ...f, made: each((g) => f.made[g] + (made[g] ?? 0)) }))
- }
-)
+export { Work } from "./work.ts"
// ── The land ──────────────────────────────────────────────────────────────
-/** A forester plants trees and a farm sows fields on free ground within reach, one at a time. */
-export const Plant = Game.System(
- "Town/Plant",
- {
- queries: {
- planters: Game.Query({
- selection: {
- tile: Game.Query.read(Tile),
- staff: Game.Query.read(Staff),
- planter: Game.Query.write(Planter),
- status: Game.Query.write(Status),
- recipe: Game.Query.optional(Recipe),
- paused: Game.Query.optional(Paused)
- },
- without: [Site, Rising]
- })
- },
- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.spawns(Tree, Field), Game.System.relates(FieldOf))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { staffTicks: STAFF_TICKS } = rules
-
- const grid = resources.grid.get()
- const random = Random.draw(resources.rng)
- const sown = new Set<number>()
- const tick = resources.time.get().step
- for (const { entity, data } of queries.planters.each()) {
- const tile = data.tile.get()
- const staff = data.staff.get()
- const planter = data.planter.get()
- // While it waits to plant again, it only counts down (and looks around twice a second for its status).
- if (planter.cooldown > 1 && tick % STAFF_TICKS !== 0) {
- data.planter.set({ ...planter, cooldown: planter.cooldown - 1 })
- continue
- }
- const open = connected(grid, tile)
- const reach = around(tile, planter.radius)
- const grown = reach.filter((c) => useAt(grid, c.x, c.y) === planter.what).length
- const spots = reach.filter((c) => useAt(grid, c.x, c.y) === "empty" && !sown.has(key(c.x, c.y)))
- // A forester has no recipe of its own: its status is its planting.
- if (!data.recipe.value()) {
- const status: StatusValue = data.paused.present ? "paused" : !open ? "unconnected" : staff.assigned === 0 ? "unstaffed" : grown < planter.max && spots.length > 0 ? "working" : "idle"
- if (data.status.get() !== status) data.status.set(status)
- }
- const cooldown = Math.max(0, planter.cooldown - 1)
- if (cooldown > 0 || !open || staff.assigned === 0 || grown >= planter.max || spots.length === 0) {
- if (cooldown !== planter.cooldown) data.planter.set({ ...planter, cooldown })
- continue
- }
- const spot = random.pick(spots)!
- sown.add(key(spot.x, spot.y))
- if (planter.what === "tree") commands.spawn(treeDraft(spot, 0))
- else commands.spawn(Game.Command.relate(fieldDraft(spot), FieldOf, entity.id))
- data.planter.set({ ...planter, cooldown: planter.interval })
- }
- }
-)
-
-/**
- * Wild forests regrow: now and then a grown tree seeds an empty cell beside
- * it, but only one that already has two trees around it, so forests fill
- * back in and creep at their edges without seeding the open town. A cleared
- * patch needs a forester.
- */
-export const Spread = Game.System(
- "Town/Spread",
- {
- queries: { trees: Game.Query({ selection: { tile: Game.Query.read(Tile), tree: Game.Query.read(Tree) } }) },
- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) },
- commands: Game.System.commands(Game.System.spawns(Tree))
- },
- ({ queries, resources, commands, services }) => {
- const rules = services.rules
- const { grown: GROWN, spreadTicks: SPREAD_TICKS } = rules
-
- if (!every(resources.time.get(), SPREAD_TICKS)) return
- const grid = resources.grid.get()
- const random = Random.draw(resources.rng)
- const grown = queries.trees.each().filter(({ data }) => data.tree.get().growth >= GROWN.tree)
- const parent = random.pick(grown)
- if (parent) {
- const t = parent.data.tile.get()
- const spot = random.pick(wildTreeSpots(grid, t))
- if (spot && canSeedTree(grid, spot)) commands.spawn(treeDraft(spot, 0))
- }
- }
-)
-
-/** Trees and fields grow until they are ready; fields not in winter. */
-export const Grow = Game.System(
- "Town/Grow",
- {
- queries: {
- trees: Game.Query({ selection: { tree: Game.Query.write(Tree) } }),
- fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
- },
- resources: { time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },
- services: { rules: Game.System.service(Rules) }
- },
- ({ queries, resources, services }) => {
- const rules = services.rules
- const { grown: GROWN, growTicks: GROW_TICKS } = rules
-
- if (!every(resources.time.get(), GROW_TICKS)) return
- for (const { data } of queries.trees.each()) {
- const growth = data.tree.get().growth
- if (growth < GROWN.tree) data.tree.set({ growth: Math.min(GROWN.tree, growth + GROW_TICKS) })
- }
- if (seasonAt(elapsed(resources.time.get(), resources.charter.get()), resources.charter.get(), rules).winter) return
- for (const { data } of queries.fields.each()) {
- const growth = data.field.get().growth
- if (growth < GROWN.field) data.field.set({ growth: Math.min(GROWN.field, growth + GROW_TICKS) })
- }
- }
-)
+export { Plant } from "./plant.ts"
+export { Spread } from "./spread.ts"
+export { Grow } from "./grow.ts"
diff --git a/src/game/systems/work/per-good.ts b/src/game/systems/work/per-good.ts
new file mode 100644
index 0000000..8f5d114
--- /dev/null
+++ b/src/game/systems/work/per-good.ts
@@ -0,0 +1,4 @@
+import { goodIds, type Amounts } from "../../content/index.ts"
+
+/** An amount of every good, each from `f`: the flow of goods is reckoned good by good. */
+export const each = (f: (g: (typeof goodIds)[number]) => number): Amounts => Object.fromEntries(goodIds.map((g) => [g, f(g)])) as Amounts
diff --git a/src/game/systems/work/plant.ts b/src/game/systems/work/plant.ts
new file mode 100644
index 0000000..bb53424
--- /dev/null
+++ b/src/game/systems/work/plant.ts
@@ -0,0 +1,66 @@
+import * as Random from "@typeonce/ritmo-math/Random"
+import { fieldDraft, treeDraft } from "../../world/archetypes.ts"
+import { around, key, useAt } from "../../world/grid.ts"
+import { Field, FieldOf, Game, Rules, Grid, Paused, Planter, Recipe, Rising, Rng, Site, Staff, Status, Tile, Time, Tree, type Status as StatusValue } from "../../schema.ts"
+import { connected } from "../shared.ts"
+
+/** A forester plants trees and a farm sows fields on free ground within reach, one at a time. */
+export const Plant = Game.System(
+ "Town/Plant",
+ {
+ queries: {
+ planters: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ staff: Game.Query.read(Staff),
+ planter: Game.Query.write(Planter),
+ status: Game.Query.write(Status),
+ recipe: Game.Query.optional(Recipe),
+ paused: Game.Query.optional(Paused)
+ },
+ without: [Site, Rising]
+ })
+ },
+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Tree, Field), Game.System.relates(FieldOf))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { staffTicks: STAFF_TICKS } = rules
+
+ const grid = resources.grid.get()
+ const random = Random.draw(resources.rng)
+ const sown = new Set<number>()
+ const tick = resources.time.get().step
+ for (const { entity, data } of queries.planters.each()) {
+ const tile = data.tile.get()
+ const staff = data.staff.get()
+ const planter = data.planter.get()
+ // While it waits to plant again, it only counts down (and looks around twice a second for its status).
+ if (planter.cooldown > 1 && tick % STAFF_TICKS !== 0) {
+ data.planter.set({ ...planter, cooldown: planter.cooldown - 1 })
+ continue
+ }
+ const open = connected(grid, tile)
+ const reach = around(tile, planter.radius)
+ const grown = reach.filter((c) => useAt(grid, c.x, c.y) === planter.what).length
+ const spots = reach.filter((c) => useAt(grid, c.x, c.y) === "empty" && !sown.has(key(c.x, c.y)))
+ // A forester has no recipe of its own: its status is its planting.
+ if (!data.recipe.value()) {
+ const status: StatusValue = data.paused.present ? "paused" : !open ? "unconnected" : staff.assigned === 0 ? "unstaffed" : grown < planter.max && spots.length > 0 ? "working" : "idle"
+ if (data.status.get() !== status) data.status.set(status)
+ }
+ const cooldown = Math.max(0, planter.cooldown - 1)
+ if (cooldown > 0 || !open || staff.assigned === 0 || grown >= planter.max || spots.length === 0) {
+ if (cooldown !== planter.cooldown) data.planter.set({ ...planter, cooldown })
+ continue
+ }
+ const spot = random.pick(spots)!
+ sown.add(key(spot.x, spot.y))
+ if (planter.what === "tree") commands.spawn(treeDraft(spot, 0))
+ else commands.spawn(Game.Command.relate(fieldDraft(spot), FieldOf, entity.id))
+ data.planter.set({ ...planter, cooldown: planter.interval })
+ }
+ }
+)
diff --git a/src/game/systems/work/raise.ts b/src/game/systems/work/raise.ts
new file mode 100644
index 0000000..c1666b4
--- /dev/null
+++ b/src/game/systems/work/raise.ts
@@ -0,0 +1,93 @@
+import { anA, asUpgraded, goodIds, stepsOf, total, upgradeAt, worksNeeded } from "../../content/index.ts"
+import { Building, Carriers, Charter, Chronicle, Game, Rules, Inventory, Recipe, Rising, Service, Site, Staff, Status, Storage, Time, Upgraded, Works } from "../../schema.ts"
+import { elapsed, write } from "../shared.ts"
+
+/** How often a storage under works takes a crate for it from its own shelves. */
+const SELF_SUPPLY_TICKS = stepsOf(1)
+
+/** Where a site's walls are once its materials are in: it goes on rising from here. */
+export const SITE_SHARE = 0.35
+
+export const Raise = Game.System(
+ "Town/Raise",
+ {
+ queries: {
+ sites: Game.Query({ selection: { site: Game.Query.read(Site) } }),
+ rising: Game.Query({ selection: { rising: Game.Query.write(Rising), status: Game.Query.optional(Status) } }),
+ works: Game.Query({
+ selection: {
+ works: Game.Query.write(Works),
+ building: Game.Query.read(Building),
+ staff: Game.Query.write(Staff),
+ recipe: Game.Query.optional(Recipe),
+ carriers: Game.Query.optional(Carriers),
+ service: Game.Query.optional(Service)
+ }
+ }),
+ /** A storage under works (the town hall, a warehouse): its own shelves. */
+ stocked: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage, Works] })
+ },
+ resources: {
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.removes(Works, Site, Rising), Game.System.inserts(Upgraded, Recipe, Carriers, Service, Rising, Status))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { buildTicks: BUILD_TICKS } = rules
+
+ // An upgrade whose materials are all in stands upgraded: it works from here on as `asUpgraded` says,
+ // keeping what it holds and what it was in the middle of.
+ const tick = resources.time.get().step
+ for (const { entity, data } of queries.works.each()) {
+ let works = data.works.get()
+ // A storage under works (the town hall) builds with what it holds itself, a crate at a time.
+ const shelves = queries.stocked.get(entity.id)
+ if (shelves.ok && tick % SELF_SUPPLY_TICKS === 0) {
+ const own = shelves.value.data.inventory.get()
+ const g = goodIds.find((g) => works.owed[g] > 0 && own.stock[g] > 0)
+ if (g) {
+ const n = Math.min(rules.transport.load, works.owed[g], own.stock[g])
+ shelves.value.data.inventory.set({ ...own, stock: { ...own.stock, [g]: own.stock[g] - n } })
+ works = { ...works, owed: { ...works.owed, [g]: works.owed[g] - n } }
+ data.works.set(works)
+ }
+ }
+ // Builders work on as the materials come in, never ahead of them.
+ const needed = worksNeeded(works.total, rules), allowed = needed * (1 - total(works.owed) / Math.max(1, works.total))
+ if (works.done < allowed) {
+ works = { ...works, done: works.done + 1 }
+ data.works.set(works)
+ }
+ if (total(works.owed) > 0 || works.done < needed) continue
+ const base = rules.kinds[data.building.get().kind], kind = asUpgraded(base, works.level)
+ commands.remove(entity, Works)
+ commands.insert(entity, Game.Command.entry(Upgraded, { level: works.level }))
+ data.staff.set({ ...data.staff.get(), needed: kind.workers })
+ const recipe = data.recipe.value(), carriers = data.carriers.value(), service = data.service.value()
+ if (recipe && kind.recipe) commands.insert(entity, Game.Command.entry(Recipe, { ...recipe, period: stepsOf(kind.recipe.seconds) }))
+ if (shelves.ok && kind.holds) shelves.value.data.inventory.set({ ...shelves.value.data.inventory.get(), cap: kind.holds.cap })
+ if (carriers && kind.carriers) commands.insert(entity, Game.Command.entry(Carriers, { count: kind.carriers }))
+ if (service && kind.service) commands.insert(entity, Game.Command.entry(Service, { ...service, interval: stepsOf(kind.service.seconds), range: kind.service.range }))
+ const was = (upgradeAt(base, works.level - 1)?.title ?? base.title).toLowerCase()
+ write(resources.chronicle, elapsed(resources.time.get(), resources.charter.get()), `The ${was} is now ${anA(upgradeAt(base, works.level)!.title.toLowerCase())}.`, true)
+ }
+
+ for (const { entity, data } of queries.sites.each()) {
+ if (total(data.site.get().owed) > 0) continue
+ commands.remove(entity, Site)
+ commands.insert(entity, Game.Command.entry(Rising, { ticks: Math.round(BUILD_TICKS * SITE_SHARE) }))
+ }
+ for (const { entity, data } of queries.rising.each()) {
+ const ticks = data.rising.get().ticks + 1
+ if (ticks >= BUILD_TICKS) {
+ commands.remove(entity, Rising)
+ // Up and standing; its work (if it has any) says otherwise from here on.
+ if (data.status.present) commands.insert(entity, Game.Command.entry(Status, "idle"))
+ } else data.rising.set({ ticks })
+ }
+ }
+)
diff --git a/src/game/systems/work/spread.ts b/src/game/systems/work/spread.ts
new file mode 100644
index 0000000..1c115a7
--- /dev/null
+++ b/src/game/systems/work/spread.ts
@@ -0,0 +1,36 @@
+import { every } from "../../content/index.ts"
+import { wildTreeSpots, canSeedTree } from "../../rules/land.ts"
+import * as Random from "@typeonce/ritmo-math/Random"
+import { treeDraft } from "../../world/archetypes.ts"
+import { Game, Rules, Grid, Rng, Tile, Time, Tree } from "../../schema.ts"
+
+/**
+ * Wild forests regrow: now and then a grown tree seeds an empty cell beside
+ * it, but only one that already has two trees around it, so forests fill
+ * back in and creep at their edges without seeding the open town. A cleared
+ * patch needs a forester.
+ */
+export const Spread = Game.System(
+ "Town/Spread",
+ {
+ queries: { trees: Game.Query({ selection: { tile: Game.Query.read(Tile), tree: Game.Query.read(Tree) } }) },
+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Tree))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { grown: GROWN, spreadTicks: SPREAD_TICKS } = rules
+
+ if (!every(resources.time.get(), SPREAD_TICKS)) return
+ const grid = resources.grid.get()
+ const random = Random.draw(resources.rng)
+ const grown = queries.trees.each().filter(({ data }) => data.tree.get().growth >= GROWN.tree)
+ const parent = random.pick(grown)
+ if (parent) {
+ const t = parent.data.tile.get()
+ const spot = random.pick(wildTreeSpots(grid, t))
+ if (spot && canSeedTree(grid, spot)) commands.spawn(treeDraft(spot, 0))
+ }
+ }
+)
diff --git a/src/game/systems/work/work.ts b/src/game/systems/work/work.ts
new file mode 100644
index 0000000..98fa5eb
--- /dev/null
+++ b/src/game/systems/work/work.ts
@@ -0,0 +1,189 @@
+import { upgradeAt } from "../../content/index.ts"
+import { around, ownerAt, useAt } from "../../world/grid.ts"
+import { Building, Charter, Chronicle, Flow, Condition, Field, Game, Rules, Gatherer, Grid, Inventory, Paused, Recipe, Rising, Rock, Site, Staff, Status, Tile, Time, Tree, Upgraded, type Status as StatusValue, Water } from "../../schema.ts"
+import { connected, elapsed, seasonAt, write } from "../shared.ts"
+import { equipmentPace, effort, paced } from "../../rules/production.ts"
+import { each } from "./per-good.ts"
+
+/**
+ * One step of every recipe. A job starts when there is room for what it
+ * makes, its input is in, and (for a gatherer) the land has what it needs
+ * within reach: a grown tree is felled, a rock chipped, a ripe field
+ * reaped, a rested cell of water fished. Then the crew puts its
+ * worker-steps in; a full crew finishes in `period` steps. It goes at half
+ * pace without the tools it wears out, and
+ * at half pace again once it is run down; in winter, fishing goes at the
+ * winter's pace (a hard winter's is a quarter).
+ */
+export const Work = Game.System(
+ "Town/Work",
+ {
+ queries: {
+ workshops: Game.Query({
+ selection: {
+ tile: Game.Query.read(Tile),
+ building: Game.Query.read(Building),
+ staff: Game.Query.read(Staff),
+ recipe: Game.Query.write(Recipe),
+ inventory: Game.Query.write(Inventory),
+ status: Game.Query.write(Status),
+ gatherer: Game.Query.optional(Gatherer),
+ paused: Game.Query.optional(Paused),
+ condition: Game.Query.optional(Condition),
+ upgraded: Game.Query.optional(Upgraded)
+ },
+ without: [Site, Rising]
+ }),
+ trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),
+ rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),
+ fields: Game.Query({ selection: { field: Game.Query.write(Field) } }),
+ waters: Game.Query({ selection: { water: Game.Query.write(Water) } })
+ },
+ resources: {
+ grid: Game.System.readResource(Grid),
+ time: Game.System.readResource(Time),
+ charter: Game.System.readResource(Charter),
+ flow: Game.System.writeResource(Flow),
+ chronicle: Game.System.writeResource(Chronicle)
+ },
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Tree))
+ },
+ ({ queries, resources, commands, services }) => {
+ const rules = services.rules
+ const { kinds, winters, grown: GROWN } = rules
+ const made: Record<string, number> = {}
+
+ const grid = resources.grid.get()
+ const tick = resources.time.get().step
+ const t = elapsed(resources.time.get(), resources.charter.get())
+ const season = seasonAt(t, resources.charter.get(), rules)
+ const fishing = season.severity ? winters[season.severity].fishing : 1
+ // The land by entity, looked up only once some gatherer starts a job this step.
+ const lazy = <T>(make: () => T) => {
+ let value: T | undefined
+ return () => (value ??= make())
+ }
+ const trees = lazy(() => new Map(queries.trees.each().map((row) => [row.entity.id as number, row])))
+ const rocks = lazy(() => new Map(queries.rocks.each().map((row) => [row.entity.id as number, row])))
+ const fields = lazy(() => new Map(queries.fields.each().map((row) => [row.entity.id as number, row])))
+ const waters = lazy(() => new Map(queries.waters.each().map((row) => [row.entity.id as number, row])))
+ const used = new Set<number>()
+ // A worked face gives one more now and then.
+ if (tick % rules.faceTicks === 0)
+ for (const { data } of queries.rocks.each()) {
+ const r = data.rock.get()
+ if (r.amount <= 0) data.rock.set({ ...r, amount: 1 })
+ }
+
+ /** Takes what a gatherer needs from the land within reach, or says there is none. */
+ const gather = (source: "tree" | "stone" | "ore" | "field" | "water", tile: { x: number; y: number; size: number }, radius: number, deep = false): boolean => {
+ for (const c of around(tile, radius)) {
+ const use = useAt(grid, c.x, c.y)
+ const id = ownerAt(grid, c.x, c.y)
+ if (used.has(id)) continue
+ if (source === "water" && use === "water") {
+ // A cell fished rests a while before it gives another catch.
+ const water = waters().get(id)
+ if (!water || tick - water.data.water.get().fished < rules.restockTicks) continue
+ water.data.water.set({ fished: tick })
+ used.add(id)
+ return true
+ }
+ if (source === "tree" && use === "tree") {
+ const tree = trees().get(id)
+ if (!tree || tree.data.tree.get().growth < GROWN.tree) continue
+ commands.despawn(tree.entity)
+ used.add(id)
+ return true
+ }
+ if ((source === "stone" || source === "ore") && use === "rock") {
+ const rock = rocks().get(id)
+ if (!rock) continue
+ const r = rock.data.rock.get()
+ if (r.ore !== (source === "ore")) continue
+ // A masonry cuts a worked face at full pace (see `Upgrade.deep`); anyone else waits for it.
+ if (r.amount <= 0) {
+ if (!deep) continue
+ used.add(id)
+ return true
+ }
+ // Quarried down, a rock stays as a worked face (see `FACE_TICKS`).
+ rock.data.rock.set({ ...r, amount: r.amount - 1 })
+ if (r.amount === 2 && ![...rocks().values()].some((o) => o !== rock && o.data.rock.get().ore === r.ore && o.data.rock.get().amount >= 2))
+ write(
+ resources.chronicle,
+ t,
+ r.ore
+ ? "The last of the open ore is dug: the worked faces still give a little, slowly. Traders sell ore and tools."
+ : "The last of the open stone is quarried: the worked faces still give a little, slowly. Traders sell stone.",
+ true,
+ c
+ )
+ return true
+ }
+ if (source === "field" && use === "field") {
+ const field = fields().get(id)
+ if (!field || field.data.field.get().growth < GROWN.field) continue
+ field.data.field.set({ growth: 0 })
+ used.add(id)
+ return true
+ }
+ }
+ return false
+ }
+
+ for (const { data } of queries.workshops.each()) {
+ const tile = data.tile.get()
+ const kind = kinds[data.building.get().kind]
+ const staff = data.staff.get()
+ const gatherer = data.gatherer.value()
+ let recipe = data.recipe.get()
+ const inventory = data.inventory.get()
+ let stock = inventory.stock
+ const open = connected(grid, tile)
+ const room = stock[recipe.output] + recipe.batch <= inventory.cap
+ const fed = recipe.input === null || stock[recipe.input] >= recipe.inputs
+ let short = !fed
+
+ if (open && staff.assigned > 0 && recipe.progress === 0 && room && fed) {
+ const deep = upgradeAt(kind, data.upgraded.value()?.level ?? 0)?.deep ?? false
+ if (gatherer && !gather(gatherer.source, tile, gatherer.radius, deep)) short = true
+ else {
+ if (recipe.input !== null) stock = { ...stock, [recipe.input]: stock[recipe.input] - recipe.inputs }
+ recipe = { ...recipe, progress: 1 }
+ }
+ }
+
+ const pace = equipmentPace(kind, stock.tools, data.condition.value()?.value ?? Infinity, fishing, rules)
+ const put = effort(staff, tick, rules)
+ if (open && recipe.progress > 0 && put > 0 && paced(pace, tick)) {
+ const progress = recipe.progress + put
+ if (progress > recipe.period * staff.needed) {
+ recipe = { ...recipe, progress: 0, made: recipe.made + 1 }
+ stock = { ...stock, [recipe.output]: stock[recipe.output] + recipe.batch }
+ made[recipe.output] = (made[recipe.output] ?? 0) + recipe.batch
+ // Every so many jobs wear out a tool.
+ if (kind.wear && recipe.made % kind.wear === 0 && stock.tools > 0) stock = { ...stock, tools: stock.tools - 1 }
+ } else recipe = { ...recipe, progress }
+ }
+ const status: StatusValue = data.paused.present
+ ? "paused"
+ : !open
+ ? "unconnected"
+ : staff.assigned === 0
+ ? "unstaffed"
+ : recipe.progress > 0
+ ? "working"
+ : !room
+ ? "blocked"
+ : short
+ ? "starved"
+ : "idle"
+ data.recipe.set(recipe)
+ if (stock !== inventory.stock) data.inventory.set({ ...inventory, stock })
+ if (data.status.get() !== status) data.status.set(status)
+ }
+ if (Object.keys(made).length > 0) resources.flow.update((f) => ({ ...f, made: each((g) => f.made[g] + (made[g] ?? 0)) }))
+ }
+)