Skip to content

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

A town that goes on: ranks, terms that follow, worked faces, and upgrades

Claude2667962f9bf6
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index ca10fe0..0b9bc18 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -335,23 +335,32 @@ quarry. The bots know the thresholds; the player only has the panel.
`pnpm test` runs model-based tests built on Effect's `Schema` and
`Arbitrary`. They generate sequences of what a mayor can do (roads, homes,
buildings where they fit, bulldozing, taxes, trade, pausing, answering the
-crown, saving and loading, waiting through seasons, and fortune good and
-bad), play them on the real simulation, and after every command check what
+crown, upgrading a building, standing for the next term, saving and
+loading, waiting through seasons, and fortune good and bad), play them on
+the real simulation, and after every command check what
must always be true: goods within their shelves, tiles on the land and
apart, residents and workers within bounds, the census matching the homes,
walkers belonging to standing buildings, approval and prices within their
-bounds, the clock and the record only going forward, and a term ending only
-in the allowed ways. A failure shrinks to the shortest sequence that still
+bounds, the clock and the record only going forward, rocks never below
+their worked faces, a rank never lost, and a term ending only in the
+allowed ways (and following only as the next term, when chosen). A failure shrinks to the shortest sequence that still
breaks a rule. A second property checks that the same charter and commands
always make the same town. `RUNS=200 pnpm test` searches harder;
`SEED=…` replays.
+`test/endless.test.ts` checks the town that goes on, each in seconds of game
+time: each rank asks more than the last, a rock quarried down stays as a
+worked face and gives one more now and then, a market becomes a market hall
+only once the town is a town, and the next term carries on the same town with
+its own winters.
+
`test/share.test.ts` checks the server's routes and what they refuse, and
carries a real town through them into another headless town, which must
then play on step for step the same as the original.
`pnpm check` puts the real simulation into each way a term can end
-(complete, bankrupt, revolt, abandoned, dismissed, run out), checks an unanswered
+(bankrupt, revolt, abandoned, dismissed, run out), raises a town through its
+ranks and into its next term, checks an unanswered
crown request, and checks that a town saved mid-term loads back the same. It
also checks the neighbourhood: a citizens' home next to a smithy goes back to
settlers; an unwatched row of cottages catches fire and the fire spreads, and
diff --git a/README.md b/README.md
index 4c5ec37..505a2a4 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,10 @@
# Inkline Town
-**A town-builder drawn in ink, played in one sitting.** You are the mayor for
-a single term: 45, 60, or 90 minutes. Lay the roads, house the settlers, build
-the chains that feed and clothe them, and grow a busy town of citizens before
-your time runs out. Or watch it go bankrupt, revolt, or empty out.
+**A town-builder drawn in ink, played a term at a time.** You are the mayor
+for a term of 45, 60, or 90 minutes, and then another, for as long as the town
+stands. Lay the roads, house the settlers, build the chains that feed and
+clothe them, and raise a hamlet to a village, a town, and a city of
+burghers. Or watch it go bankrupt, revolt, or empty out.
![A complete town at the end of its fifth year: hundreds of homes, farms, mills, and workshops on a pale island](docs/screenshots/town-complete.webp)
@@ -91,17 +92,25 @@ how much to keep, which buildings to pause, and when to answer the crown.
![A mill selected: working, two workers, 261 batches of flour made](docs/screenshots/ui-building.webp)
-## Every term ends
-
-Hold every goal for two minutes (enough people and coins, three in ten of
-them citizens, a town that approves of you) and the town is **complete**.
-Retire, or keep governing to the end. Three minutes in debt, two minutes of
-uproar, a town that empties out, or three of the crown's requests ignored,
-and the term is **lost**. Otherwise time runs out and the town is judged:
-flourishing, holding on, or declining.
-
-The reckoning shows how it went: residents, coins, and approval across the
-whole term, with the winters shaded, and the chronicle of everything that
+## Every term ends, the town goes on
+
+A town is founded as a hamlet. Hold every goal of the next rank for two
+minutes (enough people and coins, a share of them citizens, a town that
+approves of you) and it rises to a **village**, then a **town**, then a
+**city**, whose finest streets must hold burghers in townhouses. Each rank
+brings a reward from the crown, and the town can upgrade its market to a
+market hall and its chapel to a church. Nothing ends when a rank is
+reached.
+
+Three minutes in debt, two minutes of uproar, a town that empties out, or
+three of the crown's requests ignored, and the term is **lost**. Otherwise
+time runs out and the term is judged: flourishing, holding on, or declining.
+Stand for the **next term** to carry on the same town, or retire and found a
+new one. The open stone and ore run out, but the worked faces they leave keep
+giving a little, so a long reign never runs dry.
+
+The reckoning shows how the term went: residents, coins, and approval
+across it, with the winters shaded, and the chronicle of everything that
happened.
<p align="center"><img src="docs/screenshots/reckoning.webp" width="640" alt="The reckoning of a complete town: 581 residents, 352 citizens, 9000 coins, a chart of the term, and its chronicle"></p>
diff --git a/docs/how-to-play.md b/docs/how-to-play.md
index 54339d7..652349b 100644
--- a/docs/how-to-play.md
+++ b/docs/how-to-play.md
@@ -57,13 +57,17 @@ six months.
people for the same cost;
- *food* is eaten by the resident: a walker's visit feeds a cottage one
fish or loaf, a citizens' home two, a townhouse three;
- - *the crown* asks for goods the town makes, more as the term goes on;
+ - *the crown* asks for goods the town makes, more as the term goes on
+ (and small again when a new term begins);
sending them pays, and an unanswered request is a fine and a snub the
town remembers;
- *the market*: prices fall the more the town sells and rise, three
times as fast, the more it buys; a dear price calms only slowly, so
traders top up a shortfall but a town that lives on bought food pays
- more for it every minute; stone and ore run out;
+ more for it every minute; the open stone and ore are quarried down to
+ worked faces, which give one more every 90 seconds, so a quarry or mine
+ beside them goes on at about a third of its pace (the chronicle says
+ when the last open rock is gone);
- *approval*, from -100 to 100, follows needs met, taxes, unpaid wages,
snubs from the crown, and hungry winters, and decides how many people
each home holds. Taxes above 100% also send residents away directly,
@@ -79,15 +83,25 @@ six months.
nothing until told to); the reserve itself;
pausing a building (no workers, a quarter of its upkeep); answering the
crown; and the speed of time (space pauses, 1, 2, 3 for 1×, 2×, 4×).
-- **The end**: the town is *complete* once it holds every goal for two
- minutes (enough residents and coins for its size, three in ten of them
- citizens, approval 15 or more, not losing coins over the last minute); you may retire or keep
- governing. It is *lost* to bankruptcy (three minutes in debt), revolt
- (approval at -50 or below for two minutes), abandonment (people fall
- below 15% of their peak), or dismissal (three of the crown's requests
- missed in a row). Otherwise the term runs out, and the town
- is judged flourishing, holding on, or declining. The reckoning shows the
- term's history and its chronicle.
+- **Ranks**: a town is founded as a hamlet and rises to a *village*, a
+ *town*, and a *city*. Each rank has its goals (residents and coins for
+ the land's size, a share of them citizens, approval, not losing coins over
+ the last minute; a city also wants 15% of its people burghers, in
+ townhouses). Hold every goal of the next rank for two minutes and the town
+ rises: the crown sends a reward, and play goes on. A rank is never lost.
+ The town panel shows the next rank's goals.
+- **Upgrades**: a town can turn its market into a *market hall*, and a city
+ its chapel into a *church*, where they stand (the building's panel):
+ paid at once in coins, planks, stone, and tools, the walker goes further
+ and more often, the street around it is finer, and the upkeep is higher.
+- **The end of a term**: it is *lost* to bankruptcy (three minutes in
+ debt), revolt (approval at -50 or below for two minutes), abandonment
+ (people fall below 15% of their peak), or dismissal (three of the crown's
+ requests missed in a row). Otherwise the term runs out, and the town is
+ judged flourishing, holding on, or declining. The reckoning shows the
+ term's history, its chronicle, and its score. Then stand for the **next
+ term** (the same town, new winters, the crown's requests small again) or
+ retire and found a new town.
## The neighbourhood
diff --git a/scripts/check-browser.ts b/scripts/check-browser.ts
index 32f7599..577dfeb 100644
--- a/scripts/check-browser.ts
+++ b/scripts/check-browser.ts
@@ -189,7 +189,8 @@ try {
await page.evaluate(save=>localStorage.setItem("inkline-town/save/manual",JSON.stringify({...save,savedAt:Date.now()})),ended)
await page.getByRole("button",{name:"load",exact:true}).click()
await page.getByRole("button",{name:"Load without saving",exact:true}).click()
- await page.getByRole("button",{name:"Found a new town",exact:true}).waitFor({state:"visible"})
+ await page.getByRole("button",{name:"Next term",exact:true}).waitFor({state:"visible"})
+ await page.getByRole("button",{name:"Retire: found a new town",exact:true}).waitFor({state:"visible"})
assert.equal(await page.evaluate(()=>window.town.ui.stats!.fate.state),"over")
facts.reckoning=true
// Sharing: the card, then a link that opens the town in another browser (a phone), which can play on from there.
diff --git a/scripts/check.ts b/scripts/check.ts
index 49a8ebf..f461ee9 100644
--- a/scripts/check.ts
+++ b/scripts/check.ts
@@ -5,8 +5,9 @@
*
* node scripts/check.ts
*
- * - complete: a town meeting every goal, held two minutes, is won; it can
- * carry on governing, and its term then runs out as complete;
+ * - ranks: a town meeting every goal of the next rank, held two minutes,
+ * rises to it (a village, then a town) and plays on; its term then runs
+ * out, and the next term carries on the same town;
* - bankrupt: three minutes in debt;
* - revolt: approval at -50 or below for two minutes;
* - abandoned: residents fall below 15% of their peak;
@@ -39,7 +40,7 @@ const town = (charter: CharterValue = { size: "small", term: 45, land: "fair", s
for (const cell of [{ x: hall.x + 2 + i, y: hall.y + 1 }, { x: hall.x + 1, y: hall.y + 2 + i }, { x: hall.x - i, y: hall.y + 1 }, { x: hall.x + 1, y: hall.y - i }])
s.entities.push({ id: s.nextEntity++, components: { "Town/Tile": { ...cell, size: 1 }, "Town/Road": {} } })
})
- const fate = () => t.snapshot().resources["Town/Fate"] as { state: string; reason: string; at: number; governing: boolean }
+ const fate = () => t.snapshot().resources["Town/Fate"] as { state: string; reason: string; at: number; term: number; began: number; rank: number }
return { ...t, fate }
}
@@ -117,7 +118,7 @@ const check = (name: string, ok: boolean, detail: string) => {
if (!ok) failures += 1
}
-// Complete: 25 citizens' homes is 200 residents, all citizens; plenty of coins.
+// Ranks: 25 citizens' homes is 200 residents, all citizens; plenty of coins.
{
const t = town()
let placed = 0
@@ -125,15 +126,16 @@ const check = (name: string, ok: boolean, detail: string) => {
placed = settle(s, 25)
s.resources["Town/Treasury"].coins = 10_000
})
- t.run(4 * 60)
+ t.run(8 * 60)
const f = t.fate()
- check("complete", f.state === "won", `${placed} homes · ${f.state} at ${(f.at / 3600).toFixed(1)} min: ${f.reason}`)
- t.edit({ type: "govern" })
- t.run(1)
- check("keep governing", t.fate().state === "playing" && t.fate().governing, `${t.fate().state}, governing ${t.fate().governing}`)
- t.run(42 * 60)
+ check("a village, then a town", f.state === "playing" && f.rank === 2, `${placed} homes · ${f.state}, rank ${f.rank}`)
+ t.run(38 * 60)
const end = t.fate()
- check("complete to the end", end.state === "over" && end.governing, `${end.state}: ${end.reason}`)
+ check("the term runs out", end.state === "over" && end.rank === 2, `${end.state}, rank ${end.rank}: ${end.reason}`)
+ t.edit({ type: "nextTerm" })
+ t.run(1)
+ const next = t.fate()
+ check("the next term", next.state === "playing" && next.term === 2 && next.rank === 2 && next.began === 45 * 3600, `${next.state}, term ${next.term} from ${next.began}`)
}
// Bankrupt: deep in debt with nothing coming in.
diff --git a/src/appeal.ts b/src/appeal.ts
index c3e0715..9281f63 100644
--- a/src/appeal.ts
+++ b/src/appeal.ts
@@ -61,10 +61,17 @@ export const effectAt = (source: { readonly value: number; readonly reach: numbe
/** What a source does to a cell at `ring`: a home's lift is for its neighbours, not itself. */
const effectOf = (s: AppealSource, ring: number) => (s.mode === "homes" && ring === 0 ? 0 : effectAt(s, ring))
-/** A building of a kind as a source, if it has any effect. */
-export const buildingSource = (kind: KindId, tile: { readonly x: number; readonly y: number; readonly size: number }, rules: Rules = shippedRules): AppealSource | null => {
- const a = rules.kinds[kind].appeal
- return a ? { ...tile, value: a.value, reach: a.reach, ...(a.full ? { full: a.full } : {}), label: rules.kinds[kind].title.toLowerCase(), mode: "sum" } : null
+/** A building of a kind as a source, if it has any effect: an upgraded one's is its upgrade's (see `Kind.upgrade`). */
+export const buildingSource = (
+ kind: KindId,
+ tile: { readonly x: number; readonly y: number; readonly size: number },
+ rules: Rules = shippedRules,
+ upgraded = false
+): AppealSource | null => {
+ const up = upgraded ? rules.kinds[kind].upgrade : undefined
+ const a = up?.appeal ?? rules.kinds[kind].appeal
+ const title = up?.title ?? rules.kinds[kind].title
+ return a ? { ...tile, value: a.value, reach: a.reach, ...(a.full ? { full: a.full } : {}), label: title.toLowerCase(), mode: "sum" } : null
}
/** A citizens' home or a townhouse lifts the homes beside it; a settlers' cottage does nothing. */
diff --git a/src/art.ts b/src/art.ts
index 1924aa7..c123de2 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -881,6 +881,8 @@ export interface BuildingLook {
readonly site: number | null
/** A map view's colour washed over it, when one is shown. */
readonly tint?: number | undefined
+ /** Upgraded where it stands (see `Kind.upgrade`): drawn taller. */
+ readonly upgraded?: boolean
}
/** A building as drawn: its plate on the floor, its body among the other objects, and its problem marker above everything. */
diff --git a/src/content.ts b/src/content.ts
index 7543058..adad3a5 100644
--- a/src/content.ts
+++ b/src/content.ts
@@ -149,6 +149,26 @@ export interface Kind {
readonly dusty?: boolean
/** A storage that keeps food this many times longer. */
readonly keeps?: number
+ /**
+ * What it becomes when upgraded where it stands, once the town has reached
+ * `rank` (see `ranks`): paid at once from the treasury and the store, as
+ * paving is. Its walker, desirability, and upkeep become these.
+ */
+ readonly upgrade?: Upgrade
+}
+
+/** Coins a minute a building of a kind costs, upgraded or not. */
+export const upkeepOf = (kind: Pick<Kind, "upkeep" | "upgrade">, upgraded: boolean): number => (upgraded && kind.upgrade ? kind.upgrade.upkeep : kind.upkeep)
+
+/** A building upgraded where it stands (see `Kind.upgrade`). */
+export interface Upgrade {
+ readonly title: string
+ readonly blurb: string
+ readonly rank: number
+ readonly cost: { readonly coins: number; readonly materials: Partial<Record<GoodId, number>> }
+ readonly upkeep: number
+ readonly service?: { readonly seconds: number; readonly range: number }
+ readonly appeal?: { readonly value: number; readonly reach: number; readonly full?: number }
}
const free = { residents: 0, citizens: 0 }
@@ -269,13 +289,23 @@ export const kinds: Readonly<Record<KindId, Kind>> = {
category: "services", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 6, topper: "flag",
cost: { coins: 120, materials: { planks: 6, stone: 2 } }, upkeep: 6, workers: 2, crew: "citizens", unlock: free, buildable: true,
holds: { accepts: ["fish", "smoked", "bread", "cloth"], cap: 12 },
- service: { service: "goods", seconds: 6, range: 18 }, appeal: { value: 2, reach: 3, full: 2 }
+ service: { service: "goods", seconds: 6, range: 18 }, appeal: { value: 2, reach: 3, full: 2 },
+ upgrade: {
+ title: "Market hall", blurb: "a covered hall: its walker goes further, more often, and the street around it is finer", rank: 2,
+ cost: { coins: 400, materials: { planks: 6, stone: 12, tools: 2 } }, upkeep: 12,
+ service: { seconds: 4, range: 26 }, appeal: { value: 4, reach: 4, full: 2 }
+ }
},
chapel: {
id: "chapel", title: "Chapel", blurb: "a walker brings faith to the homes it passes",
category: "services", size: 2, half: 12, stories: 2, roof: "flat", bays: 2, window: 6, topper: "cupola",
cost: { coins: 200, materials: { planks: 6, stone: 6 } }, upkeep: 10, workers: 1, crew: "citizens", unlock: { residents: 15, citizens: 0 }, buildable: true,
- service: { service: "faith", seconds: 8, range: 22 }, appeal: { value: 4, reach: 4, full: 2 }
+ service: { service: "faith", seconds: 8, range: 22 }, appeal: { value: 4, reach: 4, full: 2 },
+ upgrade: {
+ title: "Church", blurb: "a church with a tower: its priest walks further, more often, and the streets around it are the finest", rank: 3,
+ cost: { coins: 700, materials: { planks: 8, stone: 20, tools: 3 } }, upkeep: 18,
+ service: { seconds: 6, range: 30 }, appeal: { value: 6, reach: 5, full: 3 }
+ }
},
firewatch: {
id: "firewatch", title: "Fire watch", blurb: "a watchman checks homes and workshops along the way for fire; firefighters run to any blaze",
@@ -576,6 +606,12 @@ export const ROAD_COST = 2
export const GROWN = { tree: ticks(40), field: ticks(20) }
/** The most a rock holds (see `lands` for how much each starts with). */
export const ROCK_AMOUNT = 40
+/**
+ * A rock quarried down to nothing stays as a worked face: it gives one more
+ * stone (or ore) this often, so a quarry or mine beside it keeps going at
+ * about a third of its pace instead of stopping for good.
+ */
+export const FACE_TICKS = ticks(90)
// ── The charter: what a new town is founded on ────────────────────────────
@@ -589,7 +625,7 @@ export const TERMS = [45, 60, 90] as const
/**
* Sizes of land: its rough radius in cells (the coast wanders in and out of
* it, with capes reaching further), and what the town must reach to be
- * complete (see `Fate`).
+ * a town (see `ranks`: a village needs less of both, a city more).
*/
export const sizes: Readonly<Record<SizeId, {
readonly title: string
@@ -765,10 +801,36 @@ export const fate = {
/** Abandonment: residents below this share of their peak, once the peak reached `peak`. */
abandon: 0.15,
peak: 40,
- /** The goals besides residents and coins: a share of them citizens, and approval. */
+ /** The town rank's goals besides residents and coins: a share of them citizens, and approval (see `ranks`). */
citizens: 0.3,
approval: 15
}
+/**
+ * The town's ranks, from the hamlet it is founded as. It rises to the next
+ * once every goal of that rank has held for `fate.hold` minutes together:
+ * `residents` and `coins` (not losing any) as shares of its land's goal
+ * (see `sizes`), a share of the residents `citizens` (those in townhouses
+ * count), a share `burghers`, and approval. A rank is never lost, and the
+ * crown sends `reward` coins on reaching it. The town rank is the old
+ * "complete" town; nothing ends when a rank is reached.
+ */
+export const ranks: ReadonlyArray<{
+ readonly title: string
+ readonly residents: number
+ readonly coins: number
+ readonly citizens: number
+ readonly burghers: number
+ readonly approval: number
+ readonly reward: number
+}> = [
+ { title: "hamlet", residents: 0, coins: 0, citizens: 0, burghers: 0, approval: 0, reward: 0 },
+ { title: "village", residents: 0.35, coins: 0.3, citizens: 0.1, burghers: 0, approval: 0, reward: 300 },
+ { title: "town", residents: 1, coins: 1, citizens: fate.citizens, burghers: 0, approval: fate.approval, reward: 800 },
+ { title: "city", residents: 1.5, coins: 1.5, citizens: 0.5, burghers: 0.15, approval: 25, reward: 1500 }
+]
+/** The rank the old "complete" town is: the goals a balance run plays for. */
+export const TOWN_RANK = 2
+
/** The town's history: a sample this often. */
export const HISTORY_TICKS = ticks(15)
diff --git a/src/host.ts b/src/host.ts
index 19bd074..c697f1e 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -185,7 +185,7 @@ export const createHost = async (
}
stock.append(cell)
}
- // The crown's request, when there is one, and what threatens (or is about to complete) the term.
+ // The crown's request, when there is one, and what threatens the term (or is about to raise the town a rank).
const request = el("div", "card request")
const requestText = el("div", "cell")
const send = el("button", "send", "send")
@@ -883,8 +883,12 @@ export const createHost = async (
const sub = el("p", "sub")
panel.append(header("town", iconEl("town", 30), sub))
- // The goals that complete the town, and how near each one is.
- const goals = section("goals", "goal", "Meet every goal at once and hold them for two minutes to complete the town.")
+ // The town's rank, the goals that raise it to the next, and how near each one is.
+ const goals = section(
+ "goals",
+ "goal",
+ "The town rises from a hamlet to a village, a town, and a city. Meet every goal of the next rank at once and hold them for two minutes: the crown sends a reward, and the game goes on. A rank is never lost."
+ )
const goalRows: Array<{ line: HTMLElement; mark: HTMLElement; text: HTMLElement; value: HTMLElement }> = []
const goalNote = el("p", "empty")
panel.append(goals)
@@ -1062,7 +1066,7 @@ export const createHost = async (
live.push(() => {
const s = ui.stats
if (!s) return
- sub.textContent = `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · ${s.charter.term}-minute term`
+ sub.textContent = `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · a ${s.fate.rankTitle} · term ${s.fate.term}, ${s.charter.term} minutes`
sub.title = `seed ${s.charter.seed}`
// Goals.
while (goalRows.length < s.goals.length) {
@@ -1077,17 +1081,18 @@ export const createHost = async (
goalRows.push({ line, mark, text, value })
}
goals.append(goalNote)
+ goalRows.forEach((r, i) => (r.line.style.display = i < s.goals.length ? "" : "none"))
s.goals.forEach((g, i) => {
const r = goalRows[i]!
r.line.classList.toggle("met", g.met)
r.text.textContent = g.text
r.value.textContent = g.value
})
- goalNote.textContent = s.fate.governing
- ? "Complete: the mayor governs on to the end of the term."
- : s.fate.complete !== null
- ? `All met: hold them ${clockText(s.fate.complete)} more.`
- : ""
+ goalNote.textContent = s.fate.nextTitle === null
+ ? `A ${s.fate.rankTitle}, the highest rank: keep it standing, term after term.`
+ : s.fate.rises !== null
+ ? `All met: hold them ${clockText(s.fate.rises)} more and the ${s.fate.rankTitle} is a ${s.fate.nextTitle}.`
+ : `A ${s.fate.rankTitle} now: these make it a ${s.fate.nextTitle}.`
goalNote.style.display = goalNote.textContent ? "" : "none"
// Approval.
moodValue.textContent = `${signed(s.mood.approval)} → ${signed(s.mood.target)}`
@@ -1212,13 +1217,14 @@ export const createHost = async (
if (p.type === "build") return buildMenu()
if (p.type === "town") return townPanel()
- const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : p.type === "park" ? "park" : "ruin"
+ const upgrade = p.type === "building" && p.upgraded ? kinds[p.kind].upgrade : undefined
+ const title = p.type === "building" ? (upgrade ?? kinds[p.kind]).title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : p.type === "park" ? "park" : "ruin"
const status = el("span", "pill")
const about = el(
"p",
"sub",
p.type === "building"
- ? kinds[p.kind].blurb
+ ? (upgrade ?? kinds[p.kind]).blurb
: p.type === "ruin"
? "bulldoze it to clear the plot"
: p.type === "park"
@@ -1287,6 +1293,21 @@ export const createHost = async (
pause.style.display = now.pausable ? "" : "none"
})
actions.append(pause)
+ // A building that can be upgraded where it stands (see `Kind.upgrade`).
+ if (p.upgrade) {
+ const up = el("button", "frame primary", `Upgrade: ${p.upgrade.title.toLowerCase()}`)
+ up.onclick = () => {
+ const now = ui.panel
+ if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })
+ }
+ live.push(() => {
+ const now = ui.panel
+ if (now?.type !== "building" || !now.upgrade) return
+ up.disabled = now.upgrade.blocked !== null
+ up.title = `${kinds[now.kind].upgrade?.blurb ?? ""} · ${now.upgrade.cost}${now.upgrade.blocked ? ` · ${now.upgrade.blocked}` : ""}`
+ })
+ actions.append(up)
+ }
}
if (p.type === "house") {
const close = el("button", "frame", "Close home")
@@ -1318,7 +1339,11 @@ export const createHost = async (
const syncPanel = () => {
const p = ui.panel
const next =
- p === null ? "" : p.type === "build" || p.type === "town" ? p.type : `${p.type}|${p.id}|${p.type === "house" ? p.tier : ""}`
+ p === null
+ ? ""
+ : p.type === "build" || p.type === "town"
+ ? p.type
+ : `${p.type}|${p.id}|${p.type === "house" ? p.tier : p.type === "building" ? `${p.upgraded}|${p.upgrade !== null}` : ""}`
if (next !== shape) {
shape = next
// Keep the old contents while the closed panel slides away.
@@ -1424,8 +1449,8 @@ export const createHost = async (
"pave",
sizeIds,
(v) => sizes[v].title,
- (v) => `goal ${chip("people", `${sizes[v].goal.residents} residents`)}${chip("coins", `${sizes[v].goal.coins} coins`)}`,
- (v) => `Complete the town with ${sizes[v].goal.residents} residents and ${sizes[v].goal.coins} coins`,
+ (v) => `a town at ${chip("people", `${sizes[v].goal.residents} residents`)}${chip("coins", `${sizes[v].goal.coins} coins`)}`,
+ (v) => `The town rank asks ${sizes[v].goal.residents} residents and ${sizes[v].goal.coins} coins; a village less, a city more`,
() => choice.size,
(v) => (choice.size = v)
),
@@ -1540,7 +1565,7 @@ export const createHost = async (
setSpeed(shareSpeed)
return ui.toast(error instanceof Error ? error.message : "The picture could not be made")
}
- const name = `inkline-town-${s.fate.state === "playing" ? `year-${s.season.year}` : s.fate.state === "won" ? "complete" : "reckoning"}.png`
+ const name = `inkline-town-${s.fate.state === "playing" ? `year-${s.season.year}` : `term-${s.fate.term}`}.png`
const caption = `${metaOf(facts).title} · ${metaOf(facts).description}`
shareBox.replaceChildren()
const sheet = el("div", "sheet")
@@ -1642,24 +1667,28 @@ export const createHost = async (
const chart = (s: Stats): string => {
const w = 520
const h = 150
- const end = Math.max(s.charter.term * 3600, ...s.history.map((p) => p.tick))
+ const from = s.fate.began * 3600
+ const span = s.charter.term * 3600
+ const history = s.history.filter((p) => p.tick >= from)
const line = (values: ReadonlyArray<number>, lo: number, hi: number, color: string, dash = "") => {
if (values.length < 2) return ""
- const span = hi - lo || 1
- const points = s.history
- .map((p, i) => `${((p.tick / end) * w).toFixed(1)},${(h - 4 - ((values[i]! - lo) / span) * (h - 8)).toFixed(1)}`)
+ const range = hi - lo || 1
+ const points = history
+ .map((p, i) => `${(((p.tick - from) / span) * w).toFixed(1)},${(h - 4 - ((values[i]! - lo) / range) * (h - 8)).toFixed(1)}`)
.join(" ")
return `<polyline points="${points}" fill="none" stroke="${color}" stroke-width="1.5" stroke-dasharray="${dash}" vector-effect="non-scaling-stroke"/>`
}
- const residents = s.history.map((p) => p.residents)
- const coinsLine = s.history.map((p) => p.coins)
- const approvalLine = s.history.map((p) => p.approval)
- const top = Math.max(1, ...residents, sizes[s.charter.size].goal.residents)
- const goal = h - 4 - (sizes[s.charter.size].goal.residents / top) * (h - 8)
- const winters = Array.from({ length: 5 }, (_, i) => {
- const y = i + 1
- const from = ((y + 0.7) / 6) * w
- return `<rect x="${from.toFixed(1)}" y="0" width="${((w * 0.3) / 6).toFixed(1)}" height="${h}" fill="#3d6db5" opacity="0.06"/>`
+ const residents = history.map((p) => p.residents)
+ const coinsLine = history.map((p) => p.coins)
+ const approvalLine = history.map((p) => p.approval)
+ const target = s.goals.find((g) => g.id === "residents")?.target ?? sizes[s.charter.size].goal.residents
+ const top = Math.max(1, ...residents, target)
+ const goal = h - 4 - (target / top) * (h - 8)
+ // The first term spares its first year a winter; later terms do not.
+ const winters = Array.from({ length: 6 }, (_, y) => {
+ if (y === 0 && s.fate.term === 1) return ""
+ const at = ((y + 0.7) / 6) * w
+ return `<rect x="${at.toFixed(1)}" y="0" width="${((w * 0.3) / 6).toFixed(1)}" height="${h}" fill="#3d6db5" opacity="0.06"/>`
}).join("")
return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">${winters}<line x1="0" x2="${w}" y1="${goal}" y2="${goal}" stroke="#77817a" stroke-dasharray="3 3" vector-effect="non-scaling-stroke"/>${line(coinsLine, Math.min(0, ...coinsLine), Math.max(1, ...coinsLine), "#d6ae2e")}${line(approvalLine, -100, 100, "#3d6db5", "4 3")}${line(residents, 0, top, "#3d4943")}</svg>`
}
@@ -1678,20 +1707,10 @@ export const createHost = async (
return
}
const id = `${s.charter.seed}|${s.fate.state}|${s.fate.at}`
- result.textContent =
- s.fate.state === "won"
- ? "the town is complete · see how"
- : s.fate.state === "lost"
- ? "the term is lost · see how"
- : "the term is over · see how"
+ result.textContent = s.fate.state === "lost" ? "the term is lost · see how" : `term ${s.fate.term} is over · see how`
if (id === reckoned) return
reckoned = id
- const title =
- s.fate.state === "won"
- ? "the town is complete"
- : s.fate.state === "lost"
- ? s.fate.reason.split(":")[0]!.toLowerCase()
- : `the term is over: ${verdictOf(s)}`
+ const title = s.fate.state === "lost" ? s.fate.reason.split(":")[0]!.toLowerCase() : `term ${s.fate.term} is over: ${verdictOf(s)}`
reckoning.replaceChildren()
const card = el("div", "sheet wide")
card.append(el("h2", "", title), el("p", "sub", s.fate.reason))
@@ -1701,9 +1720,10 @@ export const createHost = async (
f.append(el("b", "", value), el("span", "", label))
facts.append(f)
}
+ fact("rank", s.fate.rankTitle)
fact("minutes in office", `${Math.round(s.fate.at)}`)
fact("residents", `${s.settlers + s.citizens}`)
- fact("citizens", `${s.citizens}`)
+ fact("citizens · burghers", `${s.citizens} · ${s.burghers}`)
fact("coins", `${s.coins}`)
fact("approval", signed(s.mood.approval))
fact("crown met · missed", `${s.crown.met} · ${s.crown.missed}`)
@@ -1711,21 +1731,24 @@ export const createHost = async (
card.append(facts)
const graph = el("div", "chart")
graph.innerHTML = chart(s)
- card.append(graph, el("p", "legend", "— residents (dashed: the goal) · coins · - - approval · shaded: winters"))
+ card.append(graph, el("p", "legend", "— residents (dashed: the next rank) · coins · - - approval · shaded: winters"))
const story = el("div", "chronicle")
- story.innerHTML = s.chronicle.map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`).join("")
+ story.innerHTML = s.chronicle
+ .filter((l) => l.tick >= s.fate.began * 3600)
+ .map((l) => `<p><b>${clockText(Math.round(l.tick / 60))}</b> ${l.text}</p>`)
+ .join("")
card.append(story)
const actions = el("div", "actions")
- if (s.fate.state === "won") {
- const govern = el("button", "frame primary", "Keep governing")
- govern.title = "Stay on to the end of the term: the town is already complete"
- govern.onclick = () => {
- ui.edits.push({ type: "govern" })
+ if (s.fate.state === "over") {
+ const stand = el("button", "frame primary", "Next term")
+ stand.title = `Stand for another ${s.charter.term} minutes: the same town, new winters, and the crown's requests start small again`
+ stand.onclick = () => {
+ ui.edits.push({ type: "nextTerm" })
showReckoning(false)
}
- actions.append(govern)
+ actions.append(stand)
}
- const again = el("button", "frame" + (s.fate.state === "won" ? "" : " primary"), "Found a new town")
+ const again = el("button", "frame" + (s.fate.state === "over" ? "" : " primary"), s.fate.state === "over" ? "Retire: found a new town" : "Found a new town")
again.onclick = () => {
showReckoning(false)
openCharter(true)
@@ -1829,7 +1852,7 @@ export const createHost = async (
? `Coins in the treasury · click for the town's last minute\nLast minute: ${signed(change)} (made ${cf.made}, used ${cf.used}${cf.traded !== 0 ? `, traded ${signed(cf.traded)}` : ""})\nAt the current rates: ${signed(s.net)}/min (taxes, trade, upkeep, administration)`
: `Coins in the treasury, and what it gains (or loses) a minute at the current rates · click for the town's last minute`
coins.classList.toggle("debt", s.coins < 0)
- const left = Math.max(0, s.charter.term * 60 - Math.floor(s.minute * 60))
+ const left = Math.max(0, s.charter.term * 60 - Math.floor((s.minute - s.fate.began) * 60))
const severity = (w: typeof s.season.coming) => (w === null ? "" : ` (${winters[w].title})`)
const until = s.season.winter
? `${winters[s.season.severity ?? "normal"].title} winter · spring in ${clockText(s.season.left)}`
@@ -1882,7 +1905,7 @@ export const createHost = async (
send.title = have < s.crown.amount ? `Not enough ${goods[s.crown.good].title} in store yet` : `Send ${s.crown.amount} ${goods[s.crown.good].title} to the crown for ${s.crown.reward} coins`
send.disabled = have < s.crown.amount
}
- // What threatens the term, or is about to complete it.
+ // What threatens the term, or is about to raise the town a rank.
const warnings: Array<string> = []
if (s.fate.state === "playing") {
if (s.fate.bankrupt !== null)
@@ -1894,7 +1917,7 @@ export const createHost = async (
if (s.crown.streak > 0 && s.crown.streak >= s.crown.patience - 1) {
warnings.push(`<b>The crown's patience:</b> ${s.crown.streak} requests missed in a row; one more and the mayor is dismissed`)
}
- if (s.fate.complete !== null) warnings.push(`<b>Every goal met:</b> the town is complete in ${clockText(s.fate.complete)}`)
+ if (s.fate.rises !== null && s.fate.nextTitle !== null) warnings.push(`<b>Every goal met:</b> the town is a ${s.fate.nextTitle} in ${clockText(s.fate.rises)}`)
}
const html = warnings
.map((w) => `<div class="cell">${icon(w.startsWith("<b>Every goal") ? "goal" : "warning", 16)}<span>${w}</span></div>`)
@@ -1904,7 +1927,7 @@ export const createHost = async (
alarm.innerHTML = html
}
alarm.classList.toggle("show", warnings.length > 0)
- alarm.classList.toggle("good", warnings.length === 1 && s.fate.complete !== null)
+ alarm.classList.toggle("good", warnings.length === 1 && s.fate.rises !== null)
// The ticker: what needs looking at now, then the news of the last minute and a half; click a line to go there.
const minute = Math.round(s.minute * 3600)
const news = s.chronicle.filter((l) => l.alarm && minute - l.tick < 90 * 60).slice(-3).reverse()
diff --git a/src/present.ts b/src/present.ts
index 15ee10a..a500f6e 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -13,7 +13,7 @@ import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, Rui
import type { DoorSet, OverlayCell } from "./render3d/models.ts"
import {
amounts, BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,
- PAVE_COST, propIds, props, risk, RISK_MAX, ROAD_COST, tierHome, total, winters, type Amounts, type GoodId, type Kind, type KindId, type Tier
+ PAVE_COST, propIds, props, ranks, risk, RISK_MAX, ROAD_COST, tierHome, total, upkeepOf, winters, type Amounts, type GoodId, type Kind, type KindId, type Tier
} from "./content.ts"
import { around, canPlace, cellOf, doors, entrances, isRoad, key, lPath, nearest, reach, useAt, type TileLike } from "./grid.ts"
import { GRID, inside, U, type Point } from "./iso.ts"
@@ -47,6 +47,7 @@ import {
Pantry,
Park,
Paused,
+ Upgraded,
Paved,
Policy,
Recipe,
@@ -82,7 +83,7 @@ import {
type GridValue,
type Status as StatusValue
} from "./schema.ts"
-import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, seasonAt, SITE_SHARE, steadyNet, taxOf, termTicks, winterOf } from "./sim/index.ts"
+import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, seasonAt, SITE_SHARE, steadyNet, taxOf, termTicks, upgradeBlock, winterOf } from "./sim/index.ts"
import { Townsfolk } from "./townsfolk.ts"
import { emptyPreview, type Alert as Notice, type HitBox, type Legend, type Line, type View } from "./ui.ts"
import { blockers as blockersOf, streetAdvice, type InTown, type Served, type Street } from "./rules/explain.ts"
@@ -147,6 +148,8 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: C
case "paused":
return "paused: no workers, a quarter of its upkeep"
case "starved":
+ if (kind.gathers && growing && (kind.gathers.source === "stone" || kind.gathers.source === "ore"))
+ return `the worked faces in reach give a little ${kind.gathers.source} now and then; traders sell it`
if (kind.gathers && growing) return `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing`
if (kind.gathers)
return `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells${kind.gathers.source === "tree" ? ": a forester nearby replants" : ""}`
@@ -159,11 +162,16 @@ const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: C
}
}
-/** A tree or field gatherer has young ones within reach: it is waiting on them to grow, not on a forester. */
+/**
+ * A tree or field gatherer has young ones within reach: it is waiting on
+ * them to grow, not on a forester. A quarry or mine has rocks in reach,
+ * worked down to their faces: it is waiting on the next one.
+ */
const growingNear = (grid: GridValue, tile: TileLike, kind: Kind): boolean => {
const g = kind.gathers
- if (!g || (g.source !== "tree" && g.source !== "field")) return false
- return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === g.source)
+ if (!g || g.source === "water") return false
+ const use = g.source === "stone" || g.source === "ore" ? "rock" : g.source
+ return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === use)
}
const BuildingRead = Game.Query({
@@ -180,6 +188,7 @@ const BuildingRead = Game.Query({
walkers: Game.Query.optionalRelated(WalkerOf),
hall: Game.Query.optional(TownHall),
paused: Game.Query.optional(Paused),
+ upgraded: Game.Query.optional(Upgraded),
risk: Game.Query.optional(Risk),
condition: Game.Query.optional(Condition),
burning: Game.Query.optional(Burning)
@@ -515,8 +524,8 @@ export const Interact = Game.System(
}
preview.rangeNote = note
}
- const rangeOfKind = (tile: TileLike, kind: Kind) => {
- if (kind.service) rangeFrom(tile, kind.service.range, `its walkers reach ${kind.service.range} road cells from the door`)
+ const rangeOfKind = (tile: TileLike, kind: Kind, range = kind.service?.range) => {
+ if (kind.service && range !== undefined) rangeFrom(tile, range, `its walkers reach ${range} road cells from the door`)
else if (kind.workers > 0) rangeFrom(tile, COMMUTE + 1, `its workers come from homes within ${COMMUTE} road cells`)
}
// Where the page is pointing (from the ticker): outlined for a few seconds.
@@ -623,7 +632,7 @@ export const Interact = Game.System(
} else if (tile) preview.plots.push({ ...tile, look: "picked" })
if (row && tile) {
showReach(tile, kinds[row.data.building.get().kind])
- rangeOfKind(tile, kinds[row.data.building.get().kind])
+ rangeOfKind(tile, kinds[row.data.building.get().kind], maybe(row.data.service)?.range)
}
}
@@ -634,7 +643,7 @@ export const Interact = Game.System(
sources = []
for (const { data } of buildings) {
if (data.site.present || data.rising.present) continue
- const s = buildingSource(data.building.get().kind, data.tile.get())
+ const s = buildingSource(data.building.get().kind, data.tile.get(), undefined, data.upgraded.present)
if (s) sources.push(s)
}
for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))
@@ -759,15 +768,18 @@ export const Interact = Game.System(
value: `${walkers} out · ${service.range} road cells from the door`,
note: `one sets out every ${Math.round(service.interval / 60)} s while it is staffed, and serves the homes beside its way`
})
- if (kind.appeal)
+ const upgraded = row.data.upgraded.present
+ const appealHere = (upgraded ? kind.upgrade?.appeal : undefined) ?? kind.appeal
+ if (appealHere)
lines.push({
icon: "appeal",
label: "desirability around it",
- value: `${signed(kind.appeal.value)} beside it, fading out to ${kind.appeal.reach} cells`,
- tone: kind.appeal.value < 0 ? "warn" : "ok",
- note: kind.appeal.value < 0 ? "homes this close hold fewer people and pay less; citizens need a street at 5 or more" : undefined
+ value: `${signed(appealHere.value)} beside it, fading out to ${appealHere.reach} cells`,
+ tone: appealHere.value < 0 ? "warn" : "ok",
+ note: appealHere.value < 0 ? "homes this close hold fewer people and pay less; citizens need a street at 5 or more" : undefined
})
- if (kind.upkeep > 0) lines.push({ icon: "upkeep", label: "upkeep", value: `${kind.upkeep} coins a minute` })
+ const upkeep = upkeepOf(kind, upgraded)
+ if (upkeep > 0) lines.push({ icon: "upkeep", label: "upkeep", value: `${upkeep} coins a minute` })
const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind)
const problem = row.data.burning.present ? "on fire!" : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })
return { kind, status, problem, lines }
@@ -959,7 +971,10 @@ export const Interact = Game.System(
const picked = pickedPark ? parkOf(pickedPark.data.tile.get()) : undefined
if (pickedBuilding) {
const { kind, status, problem, lines } = describeBuilding(pickedBuilding)
- const pausable = kind.id !== "townhall" && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present
+ const standing = !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present
+ const pausable = kind.id !== "townhall" && standing
+ const upgraded = pickedBuilding.data.upgraded.present
+ const up = kind.upgrade
ui.panel = {
type: "building",
id: pickedBuilding.entity.id,
@@ -970,7 +985,11 @@ export const Interact = Game.System(
lines,
pausable,
paused: pickedBuilding.data.paused.present,
- salvage: salvageFor(kind.cost, maybe(pickedBuilding.data.site))
+ salvage: salvageFor(kind.cost, maybe(pickedBuilding.data.site)),
+ upgraded,
+ upgrade: up && standing && !upgraded
+ ? { title: up.title, cost: costText(up.cost), blocked: upgradeBlock(up, resources.fate.get().rank, { ranks }) }
+ : null
}
} else if (pickedHouse) {
const { h, lines, blockers } = describeHouse(pickedHouse)
@@ -1176,7 +1195,7 @@ export const Interact = Game.System(
}
const f = resources.fate.get()
const pantry = resources.pantry.get()
- const season = seasonAt(Math.min(Math.max(0, t), termTicks(charter) - 1), charter)
+ const season = seasonAt(Math.min(Math.max(0, t), f.began + termTicks(charter) - 1), charter)
const approvalAt = (r: { readonly settlers: number; readonly citizens: number }, memory: number) =>
approvalTarget(taxed, r, coins, crown.snubs.length, season.winter, undefined, memory).target
const outlookOf = (tier: "settlers" | "citizens") => taxed.some((h) => (h.tier === 1) === (tier === "settlers"))
@@ -1341,14 +1360,23 @@ export const Interact = Game.System(
state: f.state,
reason: f.reason,
at: f.at / 3600,
- governing: f.governing,
+ term: f.term,
+ began: f.began / 3600,
+ rank: f.rank,
+ rankTitle: ranks[f.rank]?.title ?? "",
+ nextTitle: f.rank + 1 < ranks.length ? ranks[f.rank + 1]!.title : null,
score: f.score,
bankrupt: danger(f.debtSince, fate.debt),
revolt: danger(f.revoltSince, fate.revolt),
- complete: danger(f.goalSince, fate.hold),
+ rises: danger(f.goalSince, fate.hold),
peak: f.peak
},
- goals: goalsOf(charter, { settlers: census.settlers, citizens: census.citizens, coins, net: steadyNet(resources.history.get().samples, net), approval: mood.approval }),
+ goals: goalsOf(
+ charter,
+ { settlers: census.settlers, citizens: census.citizens, burghers: census.burghers, coins, net: steadyNet(resources.history.get().samples, net), approval: mood.approval },
+ undefined,
+ f.rank
+ ),
larder: larder(stock),
flow: flowNow === null ? null : { ...flowNow, elsewhere: amounts(Object.fromEntries(goodIds.map((g) => [g, Math.max(0, flowHeld[g] - stock[g])]))) },
eaten: pantry.eatenLast,
@@ -1443,14 +1471,14 @@ export const RenderFields = RenderSync.system(Game, {
export const DrawLand = Game.System(
"Town/DrawLand",
{
- resources: { land: Game.System.readResource(Land), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },
+ resources: { land: Game.System.readResource(Land), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter), fate: Game.System.readResource(Fate) },
services: { stage: Game.System.service(StageService) }
},
({ resources, services }) => {
const mask = resources.land.get().mask
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
- services.stage.setLand(mask, t > 0 && seasonAt(Math.min(t, termTicks(charter) - 1), charter).winter)
+ services.stage.setLand(mask, t > 0 && seasonAt(Math.min(t, resources.fate.get().began + termTicks(charter) - 1), charter).winter)
}
)
@@ -1571,7 +1599,8 @@ export const Animate = Game.System(
build: buildOf(maybe(data.site), maybe(data.rising)),
beat: recipe ? recipe.made : maybe(data.service) ? walkers : 0,
doors: doorsOf(grid, data.tile.get()),
- site: siteShare(maybe(data.site))
+ site: siteShare(maybe(data.site)),
+ upgraded: data.upgraded.present
},
dt,
emphasis(entity.id)
diff --git a/src/render3d/views.ts b/src/render3d/views.ts
index 3804c13..2115abf 100644
--- a/src/render3d/views.ts
+++ b/src/render3d/views.ts
@@ -127,8 +127,11 @@ export class BuildingView extends WorldView {
buildingAsset(this.kindId, build, share, doors, open)
)
this.plate.use(`plate/${kind.size}/${build}`, () => plateAsset(kind.size, build))
- this.body.root.scale.set(1 + this.pulse * 0.04, 1 - this.pulse * 0.06, 1 + this.pulse * 0.04)
- const H = kind.roof === "gable" ? 20 : kind.stories * 32
+ // An upgraded building (a market hall, a church) stands taller.
+ const tall = look.upgraded ? 1.35 : 1
+ this.body.root.scale.set(1 + this.pulse * 0.04, tall * (1 - this.pulse * 0.06), 1 + this.pulse * 0.04)
+ const base = kind.roof === "gable" ? 20 : kind.stories * 32
+ const H = base * tall
this.marker.root.position.set(
0,
(H +
@@ -154,13 +157,13 @@ export class BuildingView extends WorldView {
this.motion.use("flag/" + this.kindId, () => makeFlag(this.kindId))
const a = kind.half * U,
pitch = (2 * a) / kind.bays
- this.motion.root.position.copy(vertex3([-a + pitch * (kind.bays - 0.5), -a + pitch * 0.5, H + 24]))
+ this.motion.root.position.copy(vertex3([-a + pitch * (kind.bays - 0.5), -a + pitch * 0.5, base + 24]))
this.motion.root.rotation.y = Math.sin(this.wave) * 0.15
this.motion.root.scale.set(1 + Math.sin(this.wave) * 0.12, 1, 1 + Math.sin(this.wave) * 0.12)
} else if (kind.topper === "sails") {
if (look.working) this.wave += dt * 3.6
this.motion.use("mill-sails", makeSails)
- this.motion.root.position.copy(vertex3([kind.half * U + 3 * U, 0, H - 6]))
+ this.motion.root.position.copy(vertex3([kind.half * U + 3 * U, 0, base - 6]))
this.motion.root.rotation.x = this.wave
}
const smoking=look.working&&kind.topper==="chimney"&&look.build>=1&&!look.burning
diff --git a/src/rules/config.ts b/src/rules/config.ts
index 7c7142d..053cfc3 100644
--- a/src/rules/config.ts
+++ b/src/rules/config.ts
@@ -10,13 +10,13 @@ const inputs = () => ({
kinds: content.kinds, home: content.home, goods: content.goods, lands: content.lands, sizes: content.sizes,
appeal: content.appeal, grounds: content.grounds, props: content.props, park: content.park,
risk: content.risk, condition: content.condition, winters: content.winters,
- admin: content.admin, mood: content.mood, crown: content.crown, market: content.market, fate: content.fate,
+ admin: content.admin, mood: content.mood, crown: content.crown, market: content.market, fate: content.fate, ranks: content.ranks,
spoils: content.spoils, trade: content.trade, tradeLoad: content.TRADE_LOAD, transport,
stepSeconds: content.STEP_SECONDS, ledgerTicks: content.LEDGER_TICKS, spoilTicks: content.SPOIL_TICKS,
commute: content.COMMUTE, apprentice: content.APPRENTICE, toolStock: content.TOOL_STOCK,
conditionMax: content.CONDITION_MAX, riskMax: content.RISK_MAX, pausedUpkeep: content.PAUSED_UPKEEP, salvage: content.salvage,
buildTicks: content.BUILD_TICKS, roadCost: content.ROAD_COST, paveCost: content.PAVE_COST, pavedPace: content.PAVED_PACE,
- grown: content.GROWN, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,
+ grown: content.GROWN, faceTicks: content.FACE_TICKS, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,
spreadTicks: content.ticks(1.5), growTicks: 10
})
diff --git a/src/rules/goals.ts b/src/rules/goals.ts
index 928736f..4a54664 100644
--- a/src/rules/goals.ts
+++ b/src/rules/goals.ts
@@ -13,22 +13,44 @@ export const steadyNet = (samples: ReadonlyArray<{ readonly net: number }>, now:
return Math.round(recent.concat(now).reduce((n, v) => n + v, 0) / (recent.length + 1))
}
-/** Each goal the town must hold to be complete, met or not. */
+/** The rank a town reaches next: the one after `rank`, or the last when it has reached the top. */
+export const nextRank = (rank: number, rules: Rules = shippedRules) => Math.min(rank + 1, rules.ranks.length - 1)
+
+/**
+ * What the next rank asks of the town (see `ranks`), each goal met or not:
+ * by default the town rank's, the goals a town founded as a village
+ * plays for. A town at the top rank sees its own.
+ */
export const goalsOf = (
charter: { readonly size: keyof Rules["sizes"] },
- s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly net: number; readonly approval: number },
- rules: Rules = shippedRules
+ s: { readonly settlers: number; readonly citizens: number; readonly burghers?: number; readonly coins: number; readonly net: number; readonly approval: number },
+ rules: Rules = shippedRules,
+ rank = 1
) => {
- const goal = rules.sizes[charter.size].goal
- const residents = s.settlers + s.citizens
+ const land = rules.sizes[charter.size].goal, r = rules.ranks[nextRank(rank, rules)]!
+ const residents = s.settlers + s.citizens, burghers = s.burghers ?? 0
+ const wanted = { residents: Math.round((land.residents * r.residents) / 10) * 10, coins: Math.round((land.coins * r.coins) / 100) * 100 }
+ const share = (n: number) => (residents > 0 ? Math.round((n / residents) * 100) : 0)
return [
- { id: "residents", text: `${goal.residents} residents`, value: `${residents}`, met: residents >= goal.residents },
- { id: "citizens", text: `${Math.round(rules.fate.citizens * 100)}% of them citizens`, value: `${residents > 0 ? Math.round((s.citizens / residents) * 100) : 0}%`, met: residents > 0 && s.citizens >= residents * rules.fate.citizens },
- { id: "approval", text: `approval ${rules.fate.approval} or more`, value: `${s.approval}`, met: s.approval >= rules.fate.approval },
- { id: "coins", text: `${goal.coins} coins, not losing any`, value: `${s.coins}`, met: s.coins >= goal.coins && s.net >= 0 }
- ] as const
+ { id: "residents", target: wanted.residents, text: `${wanted.residents} residents`, value: `${residents}`, met: residents >= wanted.residents },
+ ...(r.citizens > 0
+ ? [{ id: "citizens", target: Math.round(r.citizens * 100), text: `${Math.round(r.citizens * 100)}% of them citizens`, value: `${share(s.citizens)}%`, met: residents > 0 && s.citizens >= residents * r.citizens }]
+ : []),
+ ...(r.burghers > 0
+ ? [{ id: "burghers", target: Math.round(r.burghers * 100), text: `${Math.round(r.burghers * 100)}% of them burghers`, value: `${share(burghers)}%`, met: residents > 0 && burghers >= residents * r.burghers }]
+ : []),
+ { id: "approval", target: r.approval, text: `approval ${r.approval} or more`, value: `${s.approval}`, met: s.approval >= r.approval },
+ { id: "coins", target: wanted.coins, text: `${wanted.coins} coins, not losing any`, value: `${s.coins}`, met: s.coins >= wanted.coins && s.net >= 0 }
+ ]
}
-/** The town's score at the end of its term. */
-export const scoreOf = (s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly approval: number; readonly met: number; readonly missed: number }, won: boolean, minutesLeft: number) =>
- Math.max(0, Math.round(s.settlers + 3 * s.citizens + Math.max(0, s.coins) / 20 + 2 * s.approval + 40 * s.met - 40 * s.missed + (won ? 500 + 20 * minutesLeft : 0)))
+/**
+ * A term's score: its people (citizens three times, burghers four), coins,
+ * approval, the crown's requests met and missed, and the rank the town
+ * stands at.
+ */
+export const scoreOf = (
+ s: { readonly settlers: number; readonly citizens: number; readonly burghers?: number; readonly coins: number; readonly approval: number; readonly met: number; readonly missed: number },
+ rank: number
+) =>
+ Math.max(0, Math.round(s.settlers + 3 * s.citizens + (s.burghers ?? 0) + Math.max(0, s.coins) / 20 + 2 * s.approval + 40 * s.met - 40 * s.missed + 250 * rank))
diff --git a/src/rules/seasons.ts b/src/rules/seasons.ts
index 38737ef..7cbd495 100644
--- a/src/rules/seasons.ts
+++ b/src/rules/seasons.ts
@@ -15,17 +15,17 @@ export interface Seasoned {
readonly winters?: Almanac
}
-/** The winter that ends year `year` (from 1), or `null` for none: the first year's, and any past the term. */
+/** The winter that ends year `year` (from 1), or `null` for none: the first year's, and any past the terms rolled so far. */
export const winterOf = (charter: Seasoned, year: number, rules: Rules = shippedRules): WinterId | null => {
- if (year <= 1 || year > rules.yearsPerTerm) return null
+ if (year <= 1 || year > Math.max(rules.yearsPerTerm, charter.winters?.length ?? 0)) return null
const w = charter.winters?.[year - 1]
return w === undefined ? "normal" : w === "none" ? null : w
}
-/** Rolls each year's winter from a random number in 0 → 1 a year (the first year's is spared). */
-export const rollWinters = (next: () => number, rules: Rules = shippedRules): Array<WinterId | "none"> =>
+/** Rolls a term's winters from a random number in 0 → 1 a year: the first term's first year is `spared`, a later term's is not. */
+export const rollWinters = (next: () => number, rules: Rules = shippedRules, spared = true): Array<WinterId | "none"> =>
Array.from({ length: rules.yearsPerTerm }, (_, i) => {
- if (i === 0) return "none"
+ if (i === 0 && spared) return "none"
const r = next()
return r < rules.winters.mild.chance ? "mild" : r < rules.winters.mild.chance + rules.winters.normal.chance ? "normal" : "hard"
})
diff --git a/src/save.ts b/src/save.ts
index cdeafcb..c4c97fe 100644
--- a/src/save.ts
+++ b/src/save.ts
@@ -10,29 +10,48 @@
*/
import { Clock, Context, Effect, Schema } from "effect"
-import { goodIds, TRADE_LOAD } from "./content.ts"
+import { goodIds, TOWN_RANK, TRADE_LOAD } from "./content.ts"
export const SAVE_FORMAT = "inkline-town/save"
/**
* 2: the charter's towns. 3: neighbourhoods and their dangers (desirability, crews, risks, wear, ruins,
* winters). 4: parks and patrols. 5: the grudge over taxes, and where each piece of news happened.
- * 6: how much of each good may be traded at a collection. 7: the mayor's guide.
- * Version 4, 5, and 6 saves are carried forward (see `carry`); older ones cannot be loaded.
+ * 6: how much of each good may be traded at a collection. 7: the mayor's guide. 8: terms that follow one
+ * another, the town's rank, and upgraded buildings.
+ * Version 4 to 7 saves are carried forward (see `carry`); older ones cannot be loaded.
*/
-export const SAVE_VERSION = 7
+export const SAVE_VERSION = 8
/**
* Fills in what a save from an earlier version lacks, so a town in progress
* survives an update: from 4, the mood's grudge (none yet) and the news's
* places (unknown); from 5, trade at full loads, as it was; from 6, the
* guide from its start (it puts away at once what the town has already
- * done). Anything else is left to the world's own validation.
+ * done); from 7, its first term, and its rank: a town that was complete
+ * (or governed on after) is a town, any other a hamlet that rises as its
+ * goals hold. A complete town waiting on its mayor carries on playing.
+ * Anything else is left to the world's own validation.
*/
const carry = (version: number, world: unknown): unknown | null => {
- if ((version !== 4 && version !== 5 && version !== 6) || typeof world !== "object" || world === null) return null
+ if (version < 4 || version > 7 || typeof world !== "object" || world === null) return null
const w = world as { resources?: Record<string, unknown> }
const r = w.resources
if (!r || typeof r !== "object") return null
+ const fate = r["Town/Fate"] as Record<string, unknown> | undefined
+ if (fate && typeof fate === "object" && !("rank" in fate)) {
+ const { governing, won, ...rest } = fate
+ const complete = rest.state === "won" || governing === true || (typeof won === "number" && won >= 0)
+ r["Town/Fate"] = {
+ ...rest,
+ state: rest.state === "won" ? "playing" : rest.state,
+ reason: rest.state === "won" ? "" : rest.reason,
+ term: 1,
+ began: 0,
+ rank: complete ? TOWN_RANK : 0,
+ goalSince: -1
+ }
+ }
+ if (version === 7) return w
if (!("Town/Guide" in r)) r["Town/Guide"] = { done: [], off: false }
if (version === 6) return w
const policy = r["Town/Policy"]
diff --git a/src/schema.ts b/src/schema.ts
index b690909..92f64d5 100644
--- a/src/schema.ts
+++ b/src/schema.ts
@@ -97,6 +97,8 @@ export const TownHall = Descriptor.Tag("Town/TownHall")
export const Status = Descriptor.ConstructedComponent(Decode.literal(...statuses))("Town/Status")
/** Stopped by the town: no workers, a quarter of its upkeep. */
export const Paused = Descriptor.Tag("Town/Paused")
+/** Upgraded where it stands (see `Kind.upgrade`): its walker, desirability, and upkeep are the upgrade's. */
+export const Upgraded = Descriptor.Tag("Town/Upgraded")
/**
* Workers it needs, how many came (`apprentices` of them settlers standing
@@ -269,19 +271,22 @@ export const Crown = Descriptor.ConstructedResource(Decode.struct({
snubs: Decode.array(integer)
}))("Town/Crown")
-export const fateStates = ["playing", "won", "lost", "over"] as const
+export const fateStates = ["playing", "lost", "over"] as const
/**
- * How the term is going: still `playing`; `won` (every goal held), `lost`
- * (bankrupt, in revolt, abandoned, or dismissed by the crown), or `over` (the term ran out), with
- * why and when. `governing`: won, and carried on anyway. The `since`
- * fields are when each danger (or the goals) began, or -1.
+ * How the term is going: still `playing`; `lost` (bankrupt, in revolt,
+ * abandoned, or dismissed by the crown), or `over` (the term ran out: the
+ * mayor may stand for another), with why and when. `term` is which term
+ * this is, from 1, and `began` the step (since the founding) it began on;
+ * `rank` the highest the town has reached (see `ranks`). The `since`
+ * fields are when each danger (or the next rank's goals) began, or -1.
*/
export const Fate = Descriptor.ConstructedResource(Decode.struct({
state: Decode.literal(...fateStates),
reason: Decode.string,
at: integer,
- governing: Decode.boolean,
- won: integer,
+ term: integer,
+ began: integer,
+ rank: integer,
debtSince: integer,
revoltSince: integer,
goalSince: integer,
@@ -408,7 +413,7 @@ export const Game = Schema.bind(
Schema.fragment({
components: {
Tile, Road, Paved, Park, Ruin, Site, Rising, Tree, Rock, Water, Field, House, Risk, Condition, Burning, Sick, Building, TownHall, Status,
- Paused, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Patrol, Figure, Route, Errand, Rescue, Roam
+ Paused, Upgraded, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Patrol, Figure, Route, Errand, Rescue, Roam
},
resources: {
Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Guide, Appeal, Pantry, Fires,
diff --git a/src/share/card.ts b/src/share/card.ts
index 26111f5..7809788 100644
--- a/src/share/card.ts
+++ b/src/share/card.ts
@@ -16,7 +16,6 @@ const INK = "#3d4943",
/** What became of a town whose term ran out. */
export const verdictOf = (s: Stats): string => {
- if (s.fate.governing) return "complete"
const residents = s.settlers + s.citizens
if (s.fate.peak < 40) return "the town never took root"
if (residents >= sizes[s.charter.size].goal.residents * 0.75) return "flourishing"
@@ -36,13 +35,11 @@ const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}
export const cardFacts = (s: Stats): CardFacts => {
const headline =
- s.fate.state === "won"
- ? "The town is complete"
- : s.fate.state === "lost"
- ? capital(s.fate.reason.split(":")[0]!.toLowerCase())
- : s.fate.state === "over"
- ? `The term is over: ${verdictOf(s)}`
- : `Year ${s.season.year} · ${Math.floor(s.minute)} min in`
+ s.fate.state === "lost"
+ ? capital(s.fate.reason.split(":")[0]!.toLowerCase())
+ : s.fate.state === "over"
+ ? `A ${s.fate.rankTitle}: term ${s.fate.term} is over, ${verdictOf(s)}`
+ : `A ${s.fate.rankTitle} · year ${s.season.year} · term ${s.fate.term}`
return {
headline,
land: `${capital(sizes[s.charter.size].title)}, ${lands[s.charter.land].title} land · ${s.charter.term}-minute term`,
diff --git a/src/share/format.ts b/src/share/format.ts
index 249937f..913afe6 100644
--- a/src/share/format.ts
+++ b/src/share/format.ts
@@ -37,7 +37,7 @@ export const PICTURE_HEIGHT = 630
/** The lines about a share, shown in its link's preview. */
export interface ShareMeta {
- /** "Inkline Town · the town is complete" */
+ /** "Inkline Town · A town: term 2 is over, flourishing" */
readonly title: string
/** "Large, fair land · year 5 · 581 residents · 352 citizens · 9000 coins" */
readonly description: string
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
index 8debbf0..589a0e1 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -3,18 +3,19 @@
* roads and homes, laying out parks, bulldozing, pausing, the town's policy, answering the
* crown, and founding a new town. Costs are checked against the treasury
* and the town's stock and paid up front in coins; the materials are
- * carried to the site afterwards. Once the term has ended, only a new town
- * (or carrying on after completing this one) is taken.
+ * 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, rolesOf, startOf, treeDraft, waterDraft } from "../archetypes.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
-import { amounts, goodIds, RESERVE_MAX, TAX_STEPS, type Amounts, type Kind, type ParkPiece } from "../content.ts"
+import { amounts, goodIds, RESERVE_MAX, TAX_STEPS, ticks, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"
import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"
import { inside } from "../iso.ts"
import { generate } from "../mapgen.ts"
-import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rng, Site, Status, Stock, Storage, Time, TownHall, Treasury, Ui } from "../schema.ts"
+import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Service, Site, Status, Stock, Storage, Time, TownHall, Treasury, Ui, Upgraded } from "../schema.ts"
import { salvageOf, salvageText } from "../rules/salvage.ts"
-import { elapsed, rollWinters, TileRead, useOf, write } from "./shared.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.ts"
export const unlocked = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }) =>
@@ -27,6 +28,13 @@ export const lockReason = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { rea
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",
{
@@ -37,7 +45,16 @@ export const ApplyEdits = Game.System(
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) } }),
- stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] })
+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] }),
+ upgradable: Game.Query({
+ selection: {
+ building: Game.Query.read(Building),
+ service: Game.Query.optional(Service),
+ upgraded: Game.Query.optional(Upgraded),
+ site: Game.Query.optional(Site),
+ rising: Game.Query.optional(Rising)
+ }
+ })
},
resources: {
time: Game.System.readResource(Time),
@@ -140,7 +157,7 @@ export const ApplyEdits = Game.System(
const t = elapsed(resources.time.get(), resources.charter.get())
edits: for (const edit of ui.edits.splice(0)) {
- if (edit.type !== "newTown" && edit.type !== "govern" && !playing()) continue
+ if (edit.type !== "newTown" && edit.type !== "nextTerm" && !playing()) continue
switch (edit.type) {
case "building": {
const kind = kinds[edit.kind]
@@ -345,11 +362,58 @@ export const ApplyEdits = Game.System(
ui.toast(`Sent · +${c.reward} coins`)
break
}
- case "govern": {
+ case "nextTerm": {
const f = resources.fate.get()
- if (f.state !== "won") break
- resources.fate.set({ ...f, state: "playing", governing: true, won: f.at, reason: "" })
- write(resources.chronicle, t, "The mayor stays on to govern the town to the end of the term.")
+ 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.
+ resources.crown.update((c) => ({ ...c, open: false, next: began + crownGap(charter, rules) }))
+ 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": {
+ 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 up = kind.upgrade
+ if (!up || data.upgraded.present || data.site.present || data.rising.present) break
+ const blocked = upgradeBlock(up, resources.fate.get().rank, rules)
+ if (blocked) {
+ ui.toast(`${up.title} ${blocked}`)
+ break
+ }
+ const short = afford(up.cost)
+ if (short) {
+ ui.toast(short)
+ break
+ }
+ pay(up.cost)
+ take(up.cost.materials)
+ const service = maybe(data.service)
+ commands.insert(
+ row.value.entity.id,
+ Game.Command.entry(Upgraded, {}),
+ ...(service && up.service ? [Game.Command.entry(Service, { ...service, interval: ticks(up.service.seconds), range: up.service.range })] : [])
+ )
+ write(resources.chronicle, t, `The ${kind.title.toLowerCase()} is now a ${up.title.toLowerCase()}.`)
+ ui.toast(`${up.title} · −${up.cost.coins} coins`)
break
}
case "reserve":
diff --git a/src/sim/hazards.ts b/src/sim/hazards.ts
index 69071d2..f8cbd08 100644
--- a/src/sim/hazards.ts
+++ b/src/sim/hazards.ts
@@ -17,7 +17,7 @@ import { goodIds, risk, type GoodId } from "../content.ts"
import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"
import { counted, placeName, type Landmark } from "../places.ts"
import type { Point } from "../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, WalkerOf, Water, maybe } from "../schema.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, maybe } from "../schema.ts"
import { elapsed, seasonAt, write } from "./shared.ts"
// ── Desirability ──────────────────────────────────────────────────────────
@@ -27,7 +27,7 @@ export const Appraise = Game.System(
"Town/Appraise",
{
queries: {
- buildings: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
+ 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] }),
@@ -46,7 +46,7 @@ export const Appraise = Game.System(
if (resources.time.get().tick % appeal.every !== 0 && 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)
+ const s = buildingSource(data.building.get().kind, data.tile.get(), rules, data.upgraded.present)
if (s) sources.push(s)
}
for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get(), rules))
diff --git a/src/sim/index.ts b/src/sim/index.ts
index 9d7e201..bc9c6bb 100644
--- a/src/sim/index.ts
+++ b/src/sim/index.ts
@@ -84,6 +84,6 @@ export const blankResources = () => ({
export { CELL_STEPS, elapsed, seasonAt, termTicks, winterOf } from "./shared.ts"
export { SITE_SHARE } from "./work.ts"
-export { lockReason, unlocked } from "./edits.ts"
+export { lockReason, unlocked, upgradeBlock } from "./edits.ts"
export { adminOf, askOf, capacity, kept, met, priceOf, satisfaction, taxOf, tierFor } from "./town.ts"
export { crownGap, goalsOf, larder, steadyNet } from "./term.ts"
diff --git a/src/sim/term.ts b/src/sim/term.ts
index 6d91110..fde8e9b 100644
--- a/src/sim/term.ts
+++ b/src/sim/term.ts
@@ -3,7 +3,7 @@ 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,
- * and the term ends: complete, lost, or run out.
+ * the town rises through its ranks, and the term ends: lost, or run out.
*/
import { crown, HISTORY_TICKS, ticks, WINTER_WARNING, type GoodId } from "../content.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
@@ -123,7 +123,8 @@ export const Requests = Game.System(
const random = Random.make(resources.rng.get())
const good = random.pick(options)!
resources.rng.set(random.state)
- const progress = Math.min(1, t / termTicks(charter, rules))
+ // 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.
@@ -174,13 +175,14 @@ export const Approve = Game.System(
// ── The end of the term ───────────────────────────────────────────────────
-/** The fate of a town just founded. */
+/** The fate of a town just founded: its first term, a hamlet. */
export const foundedFate = () => ({
state: "playing" as const,
reason: "",
at: 0,
- governing: false,
- won: -1,
+ term: 1,
+ began: 0,
+ rank: 0,
debtSince: -1,
revoltSince: -1,
goalSince: -1,
@@ -188,15 +190,17 @@ export const foundedFate = () => ({
score: 0
})
-import { goalsOf, larder, scoreOf, steadyNet } from "../rules/goals.ts"
-export { goalsOf, larder, scoreOf, steadyNet } from "../rules/goals.ts"
+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? It 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); won once every goal has held long enough; and over when the
- * term runs out. Dangers write to the chronicle as they begin.
+ * 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",
@@ -205,7 +209,7 @@ export const Judge = Game.System(
time: Game.System.readResource(Time),
charter: Game.System.readResource(Charter),
census: Game.System.readResource(Census),
- treasury: Game.System.readResource(Treasury),
+ treasury: Game.System.writeResource(Treasury),
ledger: Game.System.readResource(Ledger),
mood: Game.System.readResource(Mood),
crown: Game.System.readResource(Crown),
@@ -217,7 +221,7 @@ export const Judge = Game.System(
},
({ resources, services }) => {
const rules = services.rules
- const { crown, fate } = rules
+ const { crown, fate, ranks } = rules
const charter = resources.charter.get()
const t = elapsed(resources.time.get(), charter)
@@ -233,11 +237,9 @@ export const Judge = Game.System(
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) => ticks(n * 60)
- const left = Math.max(0, Math.round((termTicks(charter, rules) - t) / 3600))
- const score = (won: boolean) => scoreOf({ ...census, coins, approval, met: crownNow.met, missed: crownNow.missed }, won, left)
const next = { ...f, peak: Math.max(f.peak, residents) }
- for (const mark of [50, 100, 250, 500]) if (f.peak < mark && residents >= mark) note(`${mark} residents.`)
+ for (const mark of [50, 100, 250, 500, 1000]) if (f.peak < mark && residents >= mark) note(`${mark} residents.`)
// Dangers.
if (coins < 0) {
@@ -249,25 +251,31 @@ export const Judge = Game.System(
next.revoltSince = f.revoltSince < 0 ? t : f.revoltSince
} else next.revoltSince = -1
- const end = (state: "won" | "lost" | "over", reason: string) => {
+ const end = (state: "lost" | "over", reason: string) => {
note(reason)
- resources.fate.set({ ...next, state, reason, at: t, score: score(state === "won" || f.governing) })
+ resources.fate.set({ ...next, state, reason, at: t, score: scoreOf({ ...census, coins, approval, met: crownNow.met, missed: crownNow.missed }, 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 >= termTicks(charter, rules)) {
- return end("over", f.governing ? "The term is over: the town stood complete to the end." : "The term is over.")
+ if (t - f.began >= termTicks(charter, rules)) {
+ return end("over", `Term ${f.term} is over; the ${ranks[f.rank]!.title} stands.`)
}
- // Goals.
- if (!f.governing) {
- const goals = goalsOf(charter, { ...census, coins, net, approval }, rules)
+ // The next rank.
+ if (nextRank(f.rank, rules) > f.rank) {
+ const goals = goalsOf(charter, { ...census, coins, net, approval }, rules, f.rank)
if (goals.every((g) => g.met)) {
- if (f.goalSince < 0) note("Every goal is met: the town needs only to hold them.")
+ 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)) return end("won", "The town is complete.")
+ 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/sim/town.ts b/src/sim/town.ts
index dd8c52b..ea68836 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -6,8 +6,8 @@ import { tradeCollection } from "../rules/trade.ts"
*/
import { appealAt, parkUpkeep } from "../appeal.ts"
import { doors, key, reach } from "../grid.ts"
-import { amounts, goodIds, type GoodId } from "../content.ts"
-import { Appeal, Building, Burning, Census, Charter, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, maybe } from "../schema.ts"
+import { amounts, goodIds, upkeepOf, type GoodId } from "../content.ts"
+import { Appeal, Building, Burning, Census, Charter, Flow, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, Upgraded, maybe } from "../schema.ts"
import { connected, elapsed, seasonAt } from "./shared.ts"
import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, rateOf, taxOf, tierFor } from "../rules/households.ts"
@@ -91,7 +91,7 @@ export const Collect = Game.System(
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) }, without: [Site] }),
+ 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) }, 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) } })
@@ -128,7 +128,7 @@ export const Collect = Game.System(
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 += kinds[data.building.get().kind].upkeep * (data.paused.present ? PAUSED_UPKEEP : 1)
+ for (const { data } of queries.buildings.each()) upkeep += upkeepOf(kinds[data.building.get().kind], data.upgraded.present) * (data.paused.present ? PAUSED_UPKEEP : 1)
for (const { data } of queries.parks.each()) upkeep += parkUpkeep(data.park.get(), rules)
const admin = adminOf(homes, rules)
diff --git a/src/sim/work.ts b/src/sim/work.ts
index 4c8b459..6fa60c5 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -16,8 +16,8 @@ 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 "../grid.ts"
-import { Building, Burning, Charter, Errand, Flow, Roam, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Treasury, Tree, maybe, type Status as StatusValue } from "../schema.ts"
-import { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"
+import { Building, Burning, Charter, Chronicle, Errand, Flow, Roam, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Paved, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Treasury, Tree, maybe, type Status as StatusValue } 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"
@@ -299,7 +299,13 @@ export const Work = Game.System(
rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),
fields: Game.Query({ selection: { field: Game.Query.write(Field) } })
},
- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter), flow: Game.System.writeResource(Flow) },
+ 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) }
},
({ queries, resources, commands, services }) => {
@@ -321,6 +327,12 @@ export const Work = Game.System(
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 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): boolean => {
@@ -341,10 +353,18 @@ export const Work = Game.System(
if (!rock) continue
const r = rock.data.rock.get()
if (r.ore !== (source === "ore") || r.amount <= 0) continue
- if (r.amount <= 1) {
- commands.despawn(rock.entity.id)
- used.add(id)
- } else rock.data.rock.set({ ...r, amount: r.amount - 1 })
+ // 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") {
diff --git a/src/ui.ts b/src/ui.ts
index 3a4eb6c..cacdc69 100644
--- a/src/ui.ts
+++ b/src/ui.ts
@@ -70,8 +70,10 @@ export type Edit =
| { readonly type: "pause"; readonly cell: Point; readonly on: boolean }
/** Sends the crown what it asked for. */
| { readonly type: "deliver" }
- /** Having completed the town, stays on to govern it to the end of the term. */
- | { readonly type: "govern" }
+ /** Once a term has run out, stands for another: the same town, a new term. */
+ | { readonly type: "nextTerm" }
+ /** Upgrades the building on a cell where it stands (see `Kind.upgrade`). */
+ | { readonly type: "upgrade"; readonly cell: Point }
/** Clears everything and founds a new town on the land a charter describes. */
| { readonly type: "newTown"; readonly charter: CharterValue }
@@ -127,6 +129,9 @@ export type Panel =
/** What pulling it down costs and gives back: "pull down: −25 coins · 2 planks back". */
readonly salvage: string
readonly lines: ReadonlyArray<Line>
+ /** Whether it is upgraded; and the upgrade it could have, what it costs, and what keeps it from it now (`null`: nothing). */
+ readonly upgraded: boolean
+ readonly upgrade: { readonly title: string; readonly cost: string; readonly blocked: string | null } | null
}
| {
readonly type: "house"
@@ -202,7 +207,7 @@ export interface Stats {
/** Workplaces short of workers, to step through from the jobs counter. */
readonly shortStaffed: ReadonlyArray<{ readonly id: number; readonly title: string; readonly cell: Point; readonly size: number; readonly assigned: number; readonly needed: number; readonly nobodyNear: boolean }>
readonly charter: CharterValue
- /** Minutes into the term. */
+ /** Minutes since the town was founded (see `fate.began` for this term's). */
readonly minute: number
readonly season: {
readonly year: number
@@ -234,20 +239,28 @@ export interface Stats {
readonly next: number
}
readonly fate: {
- readonly state: "playing" | "won" | "lost" | "over"
+ readonly state: "playing" | "lost" | "over"
readonly reason: string
- /** Minute the term ended. */
+ /** Minute (since the founding) the term ended. */
readonly at: number
- readonly governing: boolean
+ /** Which term this is, from 1, and the minute (since the founding) it began. */
+ readonly term: number
+ readonly began: number
+ /** The rank the town has reached (see `ranks`), and the next one, or `null` at the top. */
+ readonly rank: number
+ readonly rankTitle: string
+ readonly nextTitle: string | null
+ /** This term's score, once it has ended. */
readonly score: number
/** Seconds left before each danger ends the term, or `null` when it is not threatening. */
readonly bankrupt: number | null
readonly revolt: number | null
- /** Seconds the goals have to hold still, or `null` when they are not all met. */
- readonly complete: number | null
+ /** Seconds the next rank's goals have to hold still, or `null` when they are not all met. */
+ readonly rises: number | null
readonly peak: number
}
- readonly goals: ReadonlyArray<{ readonly text: string; readonly value: string; readonly met: boolean }>
+ /** The next rank's goals (see `goalsOf`): what each asks (`target`, in its own unit), how the town stands, and whether it is met. */
+ readonly goals: ReadonlyArray<{ readonly id: string; readonly target: number; readonly text: string; readonly value: string; readonly met: boolean }>
readonly larder: number
/**
* Each good over the last minute: made, used (eaten, worked up, built
diff --git a/test/balance-victory.test.ts b/test/balance-victory.test.ts
index cf57bf1..da5484b 100644
--- a/test/balance-victory.test.ts
+++ b/test/balance-victory.test.ts
@@ -5,10 +5,10 @@ import { tmpdir } from "node:os"
import { join } from "node:path"
import { spawnSync } from "node:child_process"
import { resolveRules } from "../src/rules/config.ts"
-import { goalsOf } from "../src/rules/goals.ts"
+import { TOWN_RANK } from "../src/content.ts"
import { fingerprint } from "../tools/balance/provenance.ts"
-for (const from of [1, 2]) test(`generated charter ${1000 + from * 7919} reaches and holds a full win through ordinary edits`, { timeout: 180000 }, () => {
+for (const from of [1, 2]) test(`generated charter ${1000 + from * 7919} reaches the town rank through ordinary edits`, { timeout: 180000 }, () => {
const directory = mkdtempSync(join(tmpdir(), "inkline-victory-")), file = join(directory, "result.json")
try {
const run = spawnSync(process.execPath, ["scripts/balance.ts", "--seeds", "1", "--from", String(from), "--term", "60", "--json", file],
@@ -16,13 +16,10 @@ for (const from of [1, 2]) test(`generated charter ${1000 + from * 7919} reaches
assert.equal(run.status, 0, run.stderr)
const report = JSON.parse(readFileSync(file, "utf8")), result = report.results[0], final = result.final, rules = resolveRules()
assert.equal(report.rulesSha256, fingerprint(rules))
- assert.equal(final.fate.state, "won", run.stdout)
- assert(result.longestGoalHoldSeconds >= rules.fate.hold * 60)
- assert(final.fate.at - final.fate.goalSince >= rules.fate.hold * 60 / rules.stepSeconds)
- assert(goalsOf(final.charter, { settlers: final.census.settlers, citizens: final.census.citizens,
- coins: final.treasury.coins, net: final.ledger.taxes + final.ledger.trade - final.ledger.upkeep - final.ledger.admin,
- approval: final.mood.approval }, rules).every(goal => goal.met))
- console.log(JSON.stringify({ seed: result.seed, state: final.fate.state, minute: result.end.minute,
+ // The old "complete" town is the town rank: reached (its goals held for `fate.hold`), the term plays on to its end.
+ assert(final.fate.rank >= TOWN_RANK, run.stdout)
+ assert.notEqual(final.fate.state, "lost", run.stdout)
+ console.log(JSON.stringify({ seed: result.seed, state: final.fate.state, rank: final.fate.rank, minute: result.end.minute,
holdSeconds: result.longestGoalHoldSeconds, residents: final.census.settlers + final.census.citizens,
citizens: final.census.citizens, coins: final.treasury.coins, approval: final.mood.approval }))
} finally { rmSync(directory, { recursive: true, force: true }) }
diff --git a/test/endless.test.ts b/test/endless.test.ts
new file mode 100644
index 0000000..fc34ffa
--- /dev/null
+++ b/test/endless.test.ts
@@ -0,0 +1,134 @@
+/**
+ * The town that goes on: ranks as milestones, terms that follow one
+ * another, worked faces that never run dry, and buildings upgraded where
+ * they stand. Each check runs the real simulation, headless, for seconds
+ * of game time, from a town put into the situation through its snapshot.
+ */
+import assert from "node:assert/strict"
+import { test } from "node:test"
+
+import { amounts, FACE_TICKS, goodIds, kinds, ranks, ticks, YEARS_PER_TERM } from "../src/content.ts"
+import { canPlace, GridBuilder } from "../src/grid.ts"
+import { goalsOf, nextRank, scoreOf } from "../src/rules/goals.ts"
+import { headless, type Snapshot } from "../src/sim/headless.ts"
+
+const charter = { size: "small", term: 45, land: "fair", seed: 11 } as const
+
+/** A standing market on free ground beside the town hall's ring road, as a snapshot is changed. */
+const market = (s: Snapshot) => {
+ const grid = new GridBuilder(s.resources["Town/Land"].mask)
+ for (const e of s.entities) {
+ const tile = e.components["Town/Tile"]
+ if (tile) grid.claim(tile, e.id, e.components["Town/Road"] ? "road" : "building")
+ }
+ const hall = s.entities.find((e) => e.components["Town/TownHall"])!.components["Town/Tile"]
+ const spots = [{ x: hall.x + 4, y: hall.y }, { x: hall.x - 4, y: hall.y }, { x: hall.x, y: hall.y + 4 }, { x: hall.x, y: hall.y - 4 }]
+ const at = spots.find((c) => canPlace(grid.value(), { ...c, size: 2 }))!
+ const m = kinds.market
+ s.entities.push({
+ id: s.nextEntity++,
+ components: {
+ "Town/Tile": { ...at, size: 2 },
+ "Town/Building": { kind: "market" },
+ "Town/Status": "idle",
+ "Town/Staff": { needed: 0, assigned: 0, apprentices: 0, nearby: 0 },
+ "Town/Service": { service: "goods", interval: ticks(m.service!.seconds), cooldown: 0, range: m.service!.range },
+ "Town/Inventory": { stock: amounts({}), accepts: ["fish", "smoked", "bread", "cloth"], cap: m.holds!.cap }
+ }
+ })
+ return at
+}
+
+const stockOf = (s: Snapshot, good: (typeof goodIds)[number]) =>
+ s.entities.reduce((n, e) => n + (e.components["Town/Storage"] ? e.components["Town/Inventory"].stock[good] : 0), 0)
+
+test("each rank asks more than the last, and the city asks for burghers", () => {
+ const town = { settlers: 0, citizens: 0, burghers: 0, coins: 0, net: 0, approval: 0 }
+ const village = goalsOf(charter, town, undefined, 0)
+ const towns = goalsOf(charter, town, undefined, 1)
+ const city = goalsOf(charter, town, undefined, 2)
+ const residents = (goals: ReadonlyArray<{ id: string; target: number }>) => goals.find((g) => g.id === "residents")!.target
+ assert(residents(village) < residents(towns) && residents(towns) < residents(city))
+ assert.equal(village.some((g) => g.id === "burghers"), false)
+ assert.equal(city.some((g) => g.id === "burghers"), true)
+ // The town rank is the old complete town; the top rank sees its own goals.
+ assert.equal(residents(towns), 180)
+ assert.equal(nextRank(ranks.length - 1), ranks.length - 1)
+ assert.deepEqual(goalsOf(charter, town, undefined, 3), city)
+ // A rank counts for more than its people.
+ const s = { settlers: 100, citizens: 50, burghers: 10, coins: 2000, approval: 20, met: 2, missed: 0 }
+ assert(scoreOf(s, 2) > scoreOf(s, 1))
+})
+
+test("a rock quarried down stays as a worked face, and gives one more now and then", () => {
+ const t = headless(charter)
+ t.run(1)
+ const rocks = t.snapshot().entities.filter((e) => e.components["Town/Rock"]).length
+ assert(rocks > 0)
+ t.change((s) => {
+ for (const e of s.entities) if (e.components["Town/Rock"]) e.components["Town/Rock"].amount = 0
+ })
+ t.run(FACE_TICKS / 60 + 1)
+ const after = t.snapshot().entities.filter((e) => e.components["Town/Rock"])
+ assert.equal(after.length, rocks)
+ assert(after.every((e) => e.components["Town/Rock"].amount === 1))
+})
+
+test("a market is upgraded to a market hall once the town is a town, and not before", () => {
+ const toasts: Array<string> = []
+ const t = headless(charter, { toast: (m) => toasts.push(m) })
+ t.run(1)
+ let cell = { x: 0, y: 0 }
+ t.change((s) => {
+ cell = market(s)
+ })
+ t.edit({ type: "upgrade", cell })
+ t.run(1)
+ const hamlet = t.snapshot().entities.find((e) => e.components["Town/Building"]?.kind === "market")!
+ assert.equal("Town/Upgraded" in hamlet.components, false)
+ assert(toasts.some((m) => m.includes("needs the town to be a town")), toasts.join(" | "))
+
+ t.change((s) => {
+ s.resources["Town/Fate"].rank = 2
+ })
+ const stone = stockOf(t.snapshot(), "stone")
+ t.edit({ type: "upgrade", cell })
+ t.run(1)
+ const s = t.snapshot()
+ const hall = s.entities.find((e) => e.components["Town/Building"]?.kind === "market")!
+ const up = kinds.market.upgrade!
+ assert.equal("Town/Upgraded" in hall.components, true)
+ assert.equal(hall.components["Town/Service"].range, up.service!.range)
+ assert.equal(hall.components["Town/Service"].interval, ticks(up.service!.seconds))
+ assert.equal(stockOf(s, "stone"), stone - up.cost.materials.stone!)
+ assert(s.resources["Town/Chronicle"].lines.some((l: { text: string }) => l.text === "The market is now a market hall."))
+})
+
+test("once a term runs out, the next one carries on the same town", () => {
+ const t = headless(charter)
+ t.run(1)
+ const end = charter.term * 3600
+ t.change((s) => {
+ s.resources["Town/Fate"] = { ...s.resources["Town/Fate"], state: "over", reason: "Term 1 is over.", at: end, rank: 1 }
+ s.resources["Town/Crown"].open = true
+ })
+ const before = t.snapshot()
+ t.edit({ type: "nextTerm" })
+ t.run(1)
+ const s = t.snapshot()
+ const f = s.resources["Town/Fate"]
+ assert.equal(f.state, "playing")
+ assert.equal(f.term, 2)
+ assert.equal(f.began, end)
+ assert.equal(f.rank, 1)
+ // The same town: its buildings and homes stand; its treasury is its own.
+ assert.equal(s.entities.filter((e) => e.components["Town/Building"]).length, before.entities.filter((e) => e.components["Town/Building"]).length)
+ // Winters for the new term's years, the first of them not spared.
+ const winters = s.resources["Town/Charter"].winters
+ assert.equal(winters.length, 2 * YEARS_PER_TERM)
+ assert.notEqual(winters[YEARS_PER_TERM], "none")
+ // The crown starts over: an open request lapses, and the next comes a while into the term.
+ assert.equal(s.resources["Town/Crown"].open, false)
+ assert(s.resources["Town/Crown"].next > end)
+ assert(s.resources["Town/Chronicle"].lines.some((l: { text: string }) => l.text.startsWith("Term 2:")))
+})
diff --git a/test/model.test.ts b/test/model.test.ts
index 08a9ba3..343304e 100644
--- a/test/model.test.ts
+++ b/test/model.test.ts
@@ -15,7 +15,7 @@ import { test } from "node:test"
import { Arbitrary, Data, Effect, Schema } from "effect"
import {
- CONDITION_MAX, crown, goodIds, groundIds, home, kindOrder, kinds, landIds, market, propIds, RESERVE_MAX, RISK_MAX, TAX_STEPS, TRADE_LOAD, type CharterValue
+ CONDITION_MAX, crown, goodIds, groundIds, home, kindOrder, kinds, landIds, market, propIds, ranks, RESERVE_MAX, RISK_MAX, TAX_STEPS, TRADE_LOAD, type CharterValue
} from "../src/content.ts"
import { canPlace, cellsOf, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"
import { GRID, inside, type Point } from "../src/iso.ts"
@@ -65,7 +65,10 @@ const Command = Schema.Union([
Schema.TaggedStruct("Reserve", { amount: between(0, RESERVE_MAX) }),
Schema.TaggedStruct("Pause", { pick: Pick, on: Schema.Boolean }),
Schema.TaggedStruct("Deliver", {}),
- Schema.TaggedStruct("Govern", {}),
+ // Once a term has run out, another.
+ Schema.TaggedStruct("NextTerm", {}),
+ // A building upgraded where it stands, ready or not.
+ Schema.TaggedStruct("Upgrade", { pick: Pick }),
Schema.TaggedStruct("SaveAndLoad", {}),
// Not a lever the page has: fortune, good or bad, so runs reach debt and plenty.
Schema.TaggedStruct("Windfall", { coins: between(-4000, 6000) }),
@@ -80,7 +83,7 @@ type Command = typeof Command.Type
*/
const weights: Readonly<Record<Command["_tag"], number>> = {
Build: 20, Homes: 15, Road: 12, Pave: 3, Park: 4, Furnish: 4, Season: 10, Wait: 8, Trade: 5, Tax: 4, Remove: 4, Pause: 4, Deliver: 4, SaveAndLoad: 3,
- Windfall: 3, Reserve: 2, BuildAnywhere: 2, Govern: 2, ToTheEnd: 1
+ Windfall: 3, Reserve: 2, BuildAnywhere: 2, NextTerm: 2, Upgrade: 2, ToTheEnd: 1
}
const table = Object.entries(weights).flatMap(([tag, n]) => Array.from({ length: n }, () => tag as Command["_tag"]))
const command = Arbitrary.flatMap(Arbitrary.schema(between(0, table.length - 1)), (i) =>
@@ -146,7 +149,8 @@ const apply = (town: Headless, command: Command): string | null => {
case "ToTheEnd": {
const s = town.snapshot()
const charter = s.resources["Town/Charter"]
- town.run(Math.max(0, charter.founded + charter.term * 3600 - s.resources["Town/Time"].tick) / 60 + 2)
+ const began = s.resources["Town/Fate"].began
+ town.run(Math.max(0, charter.founded + began + charter.term * 3600 - s.resources["Town/Time"].tick) / 60 + 2)
return null
}
case "Road": {
@@ -204,9 +208,14 @@ const apply = (town: Headless, command: Command): string | null => {
case "Deliver":
edit({ type: "deliver" })
break
- case "Govern":
- edit({ type: "govern" })
+ case "NextTerm":
+ edit({ type: "nextTerm" })
break
+ case "Upgrade": {
+ const target = pick(look(town.snapshot()).standing.filter((t) => t.what === "building"), command.pick)
+ if (target) edit({ type: "upgrade", cell: { x: target.tile.x, y: target.tile.y } })
+ break
+ }
case "SaveAndLoad": {
// Through the page's own saving and loading: a save loads back to exactly what was saved.
const world: World["Service"] = {
@@ -246,6 +255,8 @@ interface Memory {
readonly missed: number
readonly peak: number
readonly samples: number
+ readonly term: number
+ readonly rank: number
}
const remember = (s: Snapshot): Memory => ({
@@ -254,7 +265,9 @@ const remember = (s: Snapshot): Memory => ({
met: s.resources["Town/Crown"].met,
missed: s.resources["Town/Crown"].missed,
peak: s.resources["Town/Fate"].peak,
- samples: s.resources["Town/History"].samples.length
+ samples: s.resources["Town/History"].samples.length,
+ term: s.resources["Town/Fate"].term,
+ rank: s.resources["Town/Fate"].rank
})
/** Every rule a town breaks, as a line each. */
@@ -325,6 +338,14 @@ const broken = (s: Snapshot, before: Memory | null, last: Command): Array<string
// A cell of park is only park: nothing else stands on it, and nothing burns or wears there.
if (e.components["Town/Park"] && (e.components["Town/Road"] || e.components["Town/House"] || e.components["Town/Building"] || e.components["Town/Risk"])) fail(`park ${e.id} is something else too`)
}
+ // Rocks are quarried down to a worked face, never below; only a building with an upgrade has one.
+ for (const e of s.entities) {
+ const rock = e.components["Town/Rock"]
+ if (rock && rock.amount < 0) fail(`rock ${e.id} holds ${rock.amount}`)
+ const kind = e.components["Town/Building"]?.kind as keyof typeof kinds | undefined
+ if ("Town/Upgraded" in e.components && (!kind || !kinds[kind].upgrade)) fail(`entity ${e.id} is upgraded but has no upgrade`)
+ }
+ if (r["Town/Fate"].rank < 0 || r["Town/Fate"].rank >= ranks.length) fail(`the town is of rank ${r["Town/Fate"].rank}`)
const cells = r["Town/Appeal"].cells as Array<number>
if (cells.length !== 0 && cells.length !== GRID * GRID) fail(`desirability for ${cells.length} cells`)
if (assigned > residents) fail(`${assigned} at work but only ${residents} residents`)
@@ -360,11 +381,15 @@ const broken = (s: Snapshot, before: Memory | null, last: Command): Array<string
if (now.tick < before.tick) fail(`time went back from ${before.tick} to ${now.tick}`)
if (now.met < before.met || now.missed < before.missed) fail("the crown's tally went down")
if (now.peak < before.peak) fail("the peak went down")
- if (now.samples < before.samples) fail("the history lost samples")
- // A term ends once: lost and over stay; won goes on only by choosing to govern.
+ // A long reign thins its older history only as a new term begins.
+ if (now.samples < before.samples && last._tag !== "NextTerm") fail("the history lost samples")
+ if (now.rank < before.rank) fail(`the town fell from rank ${before.rank} to ${now.rank}`)
+ // A term ends once: a lost one stays lost; an over one goes on only as the next term, by choosing it.
const moved = `${before.state}→${now.state}`
- const allowed = ["playing→playing", "playing→won", "playing→lost", "playing→over", "won→won", "lost→lost", "over→over"]
- if (!allowed.includes(moved) && !(moved === "won→playing" && last._tag === "Govern")) fail(`the term went ${moved}`)
+ const allowed = ["playing→playing", "playing→lost", "playing→over", "lost→lost", "over→over"]
+ const next = moved === "over→playing" && last._tag === "NextTerm" && now.term === before.term + 1
+ if (!allowed.includes(moved) && !next) fail(`the term went ${moved}`)
+ if (now.term !== before.term && !next) fail(`the term went from ${before.term} to ${now.term}`)
}
const samples = r["Town/History"].samples as Array<{ tick: number }>
if (samples.some((p, i) => i > 0 && p.tick <= samples[i - 1]!.tick)) fail("history out of order")
diff --git a/test/save.test.ts b/test/save.test.ts
index 5d7b5fb..d9a6dae 100644
--- a/test/save.test.ts
+++ b/test/save.test.ts
@@ -143,3 +143,35 @@ test("a town saved before the guide loads, with the guide from its start", () =>
assert.equal(run(load("manual"))._tag, "Success")
assert.deepEqual(town.snapshot().resources["Town/Guide"], { done: [], off: false })
})
+
+test("a town saved complete, before terms followed one another, loads as a town playing on", () => {
+ const { town, storage, run } = setup()
+ town.run(10)
+ run(save("manual"))
+ const file = JSON.parse(storage.get("inkline-town/save/manual")!)
+ const { term: _t, began: _b, rank: _r, ...fate } = file.world.resources["Town/Fate"]
+ file.world.resources["Town/Fate"] = { ...fate, state: "won", reason: "The town is complete.", governing: false, won: -1 }
+ storage.set("inkline-town/save/manual", JSON.stringify({ ...file, version: 7 }))
+ assert.equal(run(load("manual"))._tag, "Success")
+ const loaded = town.snapshot().resources["Town/Fate"]
+ assert.equal(loaded.state, "playing")
+ assert.equal(loaded.reason, "")
+ assert.equal(loaded.rank, 2)
+ assert.equal(loaded.term, 1)
+ assert.equal(loaded.began, 0)
+ assert.equal("governing" in loaded, false)
+})
+
+test("a town saved mid-term, before ranks, loads as a hamlet", () => {
+ const { town, storage, run } = setup()
+ town.run(10)
+ run(save("manual"))
+ const file = JSON.parse(storage.get("inkline-town/save/manual")!)
+ const { term: _t, began: _b, rank: _r, ...fate } = file.world.resources["Town/Fate"]
+ file.world.resources["Town/Fate"] = { ...fate, governing: false, won: -1 }
+ storage.set("inkline-town/save/manual", JSON.stringify({ ...file, version: 7 }))
+ assert.equal(run(load("manual"))._tag, "Success")
+ const loaded = town.snapshot().resources["Town/Fate"]
+ assert.equal(loaded.state, "playing")
+ assert.equal(loaded.rank, 0)
+})