A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Polish the page from a first playthrough: ticker, levers, overlays, icon
SandroMaglione280cf1e25899
diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 5fa8bc6..87432c4 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -55,8 +55,10 @@ New town and load ask before they replace the town you have.each home holds. Taxes above 125% also leave a *grudge* that buildsfor as long as they stay high and fades over ten minutes or so, so aterm of squeezing cannot be undone by cutting taxes at the end.-- **The levers**: taxes per tier; for each good, sell beyond the reserve,- buy up to it (at half again the price), or neither; the reserve itself;+- **The levers**, each a slider: taxes per tier (50% to 200%); for each+ good, sell beyond the reserve or buy up to it (at half again the price),+ and how much each time the traders call, or neither (a new town trades+ nothing until told to); the reserve itself;pausing a building (no workers, a quarter of its upkeep); answering thecrown; 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 twodiff --git a/public/favicon.svg b/public/favicon.svgindex d61f6f5..09a411a 100644--- a/public/favicon.svg+++ b/public/favicon.svg@@ -1 +1 @@-<svg xmlns="http://www.w3.org/2000/svg" class="icon " width="32" height="32" viewBox="0 0 16 16" aria-hidden="true" stroke="#3d4943" stroke-width="1.2" stroke-linejoin="round" stroke-linecap="round"><path d="M2.5 14.5v-7h11v7z" fill="#f5f6f2"/><path d="M5 9.5h1.5v2H5zM9.5 9.5H11v2H9.5z" fill="#f3dca6" stroke-width="1"/><path d="M7 14.5v-3h2v3" fill="none" stroke-width="1"/><path d="M8 7.5V1.5" fill="none"/><path d="M8 1.8l3.5 1.2L8 4.2z" fill="#c4523f" stroke-width="1"/></svg>+<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 16 16" stroke="#3d4943" stroke-linejoin="round" stroke-linecap="round"><g stroke-width="1"><path d="M10.75 5.6L13.5 7.25 8 4.5 5.25 2.85z" fill="#e2e5de"/><path d="M2.5 11.25L8 14V10L2.5 7.25z" fill="#eef0ea"/><path d="M8 14l5.5-2.75v-4L8 10z" fill="#dfe2db"/><path d="M8 10l5.5-2.75L10.75 5.6z" fill="#dfe2db"/><path d="M8 10l2.75-4.4-5.5-2.75L2.5 7.25z" fill="#e6c3b2"/></g><path d="M10.1 12.95l1.3-.65v-2.3l-1.3.65z" fill="#8f9891" stroke-width=".6"/><path d="M4.6 10.6l1.3.65V9.75l-1.3-.65z" fill="#c9d6e6" stroke-width=".6"/></svg>diff --git a/src/content.ts b/src/content.tsindex 32c35be..e15acb7 100644--- a/src/content.ts+++ b/src/content.ts@@ -36,9 +36,10 @@ export const goods: Readonly<Record<GoodId, { readonly title: string; readonly c* reserve it keeps, up to `TRADE_LOAD` of each good.*/export const TRADE_LOAD = 12-export const RESERVES = [10, 25, 50, 100] as const-/** A new town sells its surplus wood, wheat, and wool. Stone is finite: it is not sold until the town says so. */-export const trade = { sells: ["wood", "wheat", "wool"] as ReadonlyArray<GoodId>, reserve: 25 }+/** The most the town can choose to keep of each good before selling it. */+export const RESERVE_MAX = 200+/** A new town neither sells nor buys: what leaves the town, and what it pays for, is the mayor's to decide. */+export const trade = { sells: [] as ReadonlyArray<GoodId>, reserve: 25 }export type Amounts = Readonly<Record<GoodId, number>>export const none: Amounts = { wood: 0, planks: 0, stone: 0, ore: 0, tools: 0, fish: 0, smoked: 0, wheat: 0, flour: 0, bread: 0, wool: 0, cloth: 0 }diff --git a/src/factory.css b/src/factory.cssindex 8af344b..e688947 100644--- a/src/factory.css+++ b/src/factory.css@@ -117,8 +117,17 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;display: flex; align-items: center; gap: 8px; margin: 0 0 10px; font-size: 11px; font-weight: 700;letter-spacing: 0.1em; text-transform: uppercase; color: #5d6861;}-.panel h3 .help { margin-left: auto; opacity: 0.55; cursor: help; }-.panel h3 .help:hover { opacity: 1; }+.panel h3 .help {+ margin: -4px -6px -4px auto; padding: 4px; display: inline-flex; background: none; border: 1px solid transparent; border-radius: 6px;+ opacity: 0.55; cursor: pointer;+}+.panel h3 .help:hover { opacity: 1; background: #eceee8; border-color: #d3d7ce; }+.panel h3 .help[aria-expanded=true] { opacity: 1; background: #e3eaf5; border-color: #c9d6ee; }+.panel .help-text {+ display: none; margin: -2px 0 12px; padding: 9px 12px; font-size: 12px; line-height: 1.5; color: #4f5a53;+ background: #f1f4f8; border: 1px solid #d5dde8; border-radius: 6px; letter-spacing: 0; text-transform: none; font-weight: 400;+}+.panel .help-text.open { display: block; }.panel .row { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 4px 0; }.panel .row + .row { border-top: 1px dashed #e3e6df; }.panel .label { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }@@ -169,8 +178,6 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel .need .fill.low { background: #c98a3a; }.panel .need .fill.none { background: #b04a39; }.panel .need .count { text-align: right; }-.panel .good-row { cursor: default; }-.panel .good-row .price { color: #8a938c; font-size: 11px; }.panel .lines .row { justify-content: flex-start; }/* ── The term: season, approval, the crown, dangers ── */@@ -194,9 +201,6 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel .goal .mark { display: inline-flex; width: 16px; height: 16px; align-items: center; justify-content: center; border: 1px solid #c9cec4; border-radius: 50%; font-size: 10px; color: transparent; }.panel .goal.met .mark { color: #f7f8f4; background: #4f8a3e; border-color: #4f8a3e; font-weight: 700; }.panel .goal.met { color: #4f8a3e; }-.panel .frame.mode { padding: 1px 0; width: 5ch; font-size: 11px; text-align: center; color: #8a938c; border-color: #c9cec4; }-.panel .frame.mode.sell { color: #4f8a3e; border-color: #4f8a3e; background: #e8f0e2; font-weight: 700; }-.panel .frame.mode.buy { color: #3d6db5; border-color: #3d6db5; background: #e3eaf5; font-weight: 700; }.chronicle p { margin: 0 0 6px; font-size: 12px; color: #4f5a53; line-height: 1.45; }.chronicle p b { display: inline-block; min-width: 5ch; color: #8a938c; font-weight: 400; }@@ -270,24 +274,21 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;}/* ── The town ticker, map views and their legend ── */-.hud .ticker { display: none; flex-direction: column; max-width: 420px; }+.hud .ticker { display: none; flex-direction: column; width: 440px; max-width: 100%; }.hud .ticker.show { display: flex; }-.hud .ticker .cell { white-space: normal; padding: 5px 12px; font-size: 11px; line-height: 1.35; }-.hud .ticker .cell + .cell { border-left: none; border-top: 1px dashed #e3e6df; }-.hud .ticker .news { color: #5d6861; }.views {position: fixed; right: 16px; top: 64px; display: flex; flex-direction: column; align-items: stretch; gap: 2px; padding: 5px;background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px; box-shadow: 0 2px 0 #dfe2db; z-index: 2;transition: right 240ms cubic-bezier(.2,.8,.2,1);}-.views > .glyph { align-self: center; opacity: 0.6; padding: 2px 0 4px; }+.views-title { padding: 4px 8px 5px; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: #9aa29b; cursor: help; }.views button {font: inherit; font-size: 11px; color: #3d4943; background: transparent; border: 1px solid transparent; border-radius: 5px;- padding: 4px 8px; display: flex; align-items: center; gap: 6px; cursor: pointer; white-space: nowrap;+ padding: 5px 8px; display: flex; align-items: center; gap: 8px; cursor: pointer; white-space: nowrap;}.views button:hover { background: #eceee8; }.views button.on { background: #3d4943; color: #f7f8f4; }-.views button kbd { font: inherit; font-size: 10px; opacity: 0.55; margin-left: auto; }+.views button kbd { font: inherit; font-size: 10px; opacity: 0.55; margin-left: auto; padding-left: 18px; }.panel-open .views { right: 376px; }.legend {position: fixed; right: 16px; top: 300px; display: none; flex-direction: column; gap: 4px; padding: 10px 12px; max-width: 220px;@@ -302,22 +303,30 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.views { top: auto; bottom: calc(130px + env(safe-area-inset-bottom)); flex-direction: row; flex-wrap: wrap; max-width: calc(100vw - 32px); }.views button { font-size: 0; gap: 0; }.views button kbd { display: none; }+ .views-title { display: none; }.legend { top: auto; bottom: calc(176px + env(safe-area-inset-bottom)); }}/* ── Descriptions as rows: what, how much, and why underneath ── */-.panel .lines .line { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 2px 10px; padding: 6px 0; }+/* Icon, what, and value on one line; chips and the note underneath, aligned with what. */+.panel .lines .line {+ display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; column-gap: 10px; row-gap: 5px; align-items: baseline; padding: 11px 0;+}+.panel .lines .line:first-of-type { padding-top: 2px; }+.panel .lines .line:last-child { padding-bottom: 2px; }.panel .lines .line + .line { border-top: 1px dashed #e3e6df; }-.panel .lines .line .label { font-weight: 600; color: #3d4943; flex: none; max-width: 100%; }-.panel .lines .line .count { text-align: right; white-space: normal; margin-left: auto; line-height: 1.35; }-.panel .lines .line .chips { flex-basis: 100%; margin-top: 3px; }-.panel .lines .line .note { flex-basis: 100%; margin-top: 1px; font-size: 11px; line-height: 1.4; color: #6c766f; }+.panel .lines .line .mark { grid-column: 1; align-self: start; padding-top: 1px; }+.panel .lines .line .what { grid-column: 2; font-weight: 600; color: #3d4943; line-height: 1.35; }+.panel .lines .line .count { grid-column: 3; max-width: 200px; text-align: right; white-space: normal; line-height: 1.35; }+.panel .lines .line .chips { grid-column: 2 / -1; gap: 6px; }+.panel .lines .line.long .count { grid-column: 2 / -1; max-width: none; text-align: left; }+.panel .lines .line .note { grid-column: 2 / -1; font-size: 11px; line-height: 1.5; color: #6c766f; }.panel .lines .line.ok .count { color: #4f8a3e; }.panel .lines .line.warn .count { color: #b8782e; }.panel .lines .line.bad .count { color: #b04a39; font-weight: 700; }.panel .lines .line.bad .note { color: #8f3f31; }.panel .lines .line.warn .note { color: #8a5a22; }-.panel .lines .line.dim .count, .panel .lines .line.dim .label { color: #8a938c; font-weight: 400; }+.panel .lines .line.dim .count, .panel .lines .line.dim .what { color: #8a938c; font-weight: 400; }.panel .lines .line .chip { background: #eef0ea; border-radius: 4px; padding: 1px 6px 1px 4px; }/* ── The build menu: cost and what it does, in labelled rows ── */@@ -329,12 +338,89 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel .chip i { font-style: normal; color: #9aa29b; }/* ── The ticker: now and lately, each line a place to go ── */-.hud .ticker .head { padding: 5px 12px 1px; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: #9aa29b; }-.hud .ticker button.cell { font: inherit; color: inherit; background: none; border: 0; text-align: left; cursor: default; width: 100%; }-.hud .ticker button.cell.place { cursor: pointer; }-.hud .ticker button.cell.place:hover { background: #eef0ea; }-.hud .ticker .cell kbd { margin-left: auto; font: inherit; font-size: 10px; color: #3d6db5; border: 1px solid #c9d6ee; border-radius: 3px; padding: 0 5px; }-.hud .ticker .cell em { font-style: normal; color: #9aa29b; }-.hud .ticker .cell span { flex: 1; }+.hud .ticker .head { padding: 10px 16px 4px; font-size: 10px; letter-spacing: 0.1em; text-transform: uppercase; color: #9aa29b; }+.hud .ticker .head + .cell { border-top: 0; }+.hud .ticker .cell {+ align-items: flex-start; gap: 11px; padding: 9px 8px 9px 16px; white-space: normal; font-size: 12px; line-height: 1.55;+ box-shadow: inset 3px 0 0 transparent;+}+.hud .ticker .cell + .cell { border-left: none; border-top: 1px dashed #e3e6df; }+.hud .ticker .cell .mark { margin-top: 2px; }+.hud .ticker .cell .text { flex: 1; min-width: 0; }+.hud .ticker .cell em { font-style: normal; color: #9aa29b; white-space: nowrap; }+.hud .ticker .cell.place { cursor: pointer; }+.hud .ticker .cell.place:hover { background: #eef0ea; }+.hud .ticker .alert.hint { box-shadow: inset 3px 0 0 #8fa9d6; }+.hud .ticker .alert.warn { box-shadow: inset 3px 0 0 #d9a24e; }+.hud .ticker .alert.bad { box-shadow: inset 3px 0 0 #b04a39; }+.hud .ticker .alert.bad .text { color: #8f3f31; }+.hud .ticker .news .text { color: #5d6861; }+.hud .ticker .acts { display: flex; align-items: center; gap: 2px; margin-top: -1px; }+.hud .ticker .act {+ display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; padding: 0;+ border: 1px solid transparent; border-radius: 6px; background: none; color: #3d4943; cursor: pointer; opacity: 0.4;+}+.hud .ticker .cell:hover .act { opacity: 0.75; }+.hud .ticker .act:hover { opacity: 1 !important; background: #e2e5de; border-color: #c9cec4; }+/* What a message names: a building to click and build, a good with its icon, a key to press. */+.ref {+ display: inline-block; padding: 0 5px 0 4px; margin: 0 1px; border: 1px solid transparent; border-radius: 4px;+ font: inherit; font-weight: 600; line-height: 1.4; vertical-align: baseline; white-space: nowrap;+}+.ref .icon { display: inline-block; width: 13px; height: 13px; margin-right: 3px; vertical-align: -2px; }+.ref.ware { background: #eef0ea; color: #3d4943; }+.ref.kind { background: #eef3fb; border: 1px solid #c9d6ee; color: #2f5a9c; }+button.ref.kind { cursor: pointer; }+button.ref.kind:hover { background: #dce6f5; border-color: #3d6db5; }+kbd.key {+ display: inline-block; min-width: 1.6ch; padding: 0 4px; font: inherit; font-size: 10px; line-height: 1.5; text-align: center;+ color: #3d4943; background: #fbfcf9; border: 1px solid #c9cec4; border-bottom-width: 2px; border-radius: 4px; vertical-align: 1px;+}.hud .cell.jobs { cursor: pointer; }.hud .cell.jobs:hover { background: #eef0ea; }++/* ── Sliders for the town's levers: taxes, what it keeps, what it trades ── */+.panel .slider {+ --at: 50%; --fill: #3d4943; --rail: #dfe2db;+ -webkit-appearance: none; appearance: none; display: block; width: 100%; height: 20px; margin: 2px 0 0; background: transparent; cursor: pointer;+}+.panel .slider:focus-visible { outline: 2px solid #8fa9d6; outline-offset: 2px; border-radius: 4px; }+.panel .slider::-webkit-slider-runnable-track { height: 6px; border-radius: 3px; background: linear-gradient(to right, var(--fill) var(--at), var(--rail) var(--at)); }+.panel .slider::-moz-range-track { height: 6px; border-radius: 3px; background: linear-gradient(to right, var(--fill) var(--at), var(--rail) var(--at)); }+.panel .slider::-webkit-slider-thumb {+ -webkit-appearance: none; width: 16px; height: 16px; margin-top: -5px; border-radius: 50%;+ background: #f7f8f4; border: 1.5px solid #3d4943; box-shadow: 0 1px 0 #c9cec4;+}+.panel .slider::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: #f7f8f4; border: 1.5px solid #3d4943; }+.panel .slider:hover::-webkit-slider-thumb { background: #e6e9e2; }+/* Taxes: a notch at the usual 100% (a third of the way from 50% to 200%). */+.panel .slider.tax::-webkit-slider-runnable-track {+ background: linear-gradient(to right, transparent calc(33.33% - 1px), #77817a calc(33.33% - 1px), #77817a calc(33.33% + 1px), transparent calc(33.33% + 1px)) no-repeat center / 100% 12px,+ linear-gradient(to right, var(--fill) var(--at), var(--rail) var(--at));+}+.panel .lever .rate { font-variant-numeric: tabular-nums; }+.panel .lever + .slider { margin-top: -2px; }+/* Trade: the middle neither sells nor buys; the bar grows out from it, green to sell, blue to buy. */+.panel .trade-row { padding: 7px 0 5px; }+.panel .trade-row + .trade-row, .panel .effect + .trade-row { border-top: 1px dashed #e3e6df; }+.panel .trade-row .row { padding: 0; }+.panel .trade-row .price { color: #8a938c; font-size: 11px; min-width: 5ch; text-align: right; }+.panel .trade-row .count { min-width: 3ch; text-align: right; }+.panel .trade-row .change { font-size: 10px; color: #8a938c; }+.panel .trade-row .change.up { color: #4f8a3e; }+.panel .trade-row .change.down { color: #b04a39; }+.panel .deal-line { display: flex; align-items: center; gap: 12px; }+.panel .deal-line .slider { flex: 1; }+.panel .slider.deal { --fill: #9aa29b; }+.panel .sell .slider.deal { --fill: #4f8a3e; }+.panel .buy .slider.deal { --fill: #3d6db5; }+.panel .slider.deal::-webkit-slider-runnable-track {+ background: linear-gradient(to right, transparent calc(50% - 1px), #77817a calc(50% - 1px), #77817a calc(50% + 1px), transparent calc(50% + 1px)) no-repeat center / 100% 12px,+ linear-gradient(to right, var(--rail) min(var(--at), 50%), var(--fill) min(var(--at), 50%), var(--fill) max(var(--at), 50%), var(--rail) max(var(--at), 50%));+}+.panel .slider.deal::-moz-range-track {+ background: linear-gradient(to right, var(--rail) min(var(--at), 50%), var(--fill) min(var(--at), 50%), var(--fill) max(var(--at), 50%), var(--rail) max(var(--at), 50%));+}+.panel .deal-line .mode { width: 12ch; text-align: right; font-size: 11px; color: #9aa29b; white-space: nowrap; }+.panel .deal-line .mode.sell { color: #4f8a3e; font-weight: 700; }+.panel .deal-line .mode.buy { color: #3d6db5; font-weight: 700; }diff --git a/src/host.ts b/src/host.tsindex 973fd8d..dcebcc7 100644--- a/src/host.ts+++ b/src/host.ts@@ -29,7 +29,10 @@ import {lands,mood as moodRules,needTitle,- RESERVES,+ LEDGER_TICKS,+ RESERVE_MAX,+ STEP_SECONDS,+ TRADE_LOAD,ROAD_COST,sizeIds,sizes,@@ -60,6 +63,45 @@ const el = <K extends keyof HTMLElementTagNameMap>(tag: K, className: string, tenode.textContent = textreturn node}+/**+ * Sets a node's markup only when it changed. Rewriting it every frame would+ * replace the element under the pointer between press and release, and the+ * browser then drops the click.+ */+const setHtml = (node: HTMLElement, html: string) => {+ if (node.dataset.html === html) return+ node.dataset.html = html+ node.innerHTML = html+}+const escapeHtml = (text: string) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)++/** Words in the town's messages that name a building or a good, longest first, so "smoked fish" wins over "fish". */+const namedThings: ReadonlyArray<{ readonly word: string; readonly ref: { readonly kind: KindId } | { readonly good: GoodId } }> = [+ ...kindOrder.flatMap((id) => {+ const title = kinds[id].title.toLowerCase()+ return [title, `${title}s`].map((word) => ({ word, ref: { kind: id } }))+ }),+ ...goodIds.map((id) => ({ word: goods[id].title, ref: { good: id } })),+ { word: "loaves", ref: { good: "bread" as GoodId } },+ { word: "loaf", ref: { good: "bread" as GoodId } }+].sort((a, b) => b.word.length - a.word.length)+const namedPattern = new RegExp(`\\b(${namedThings.map((t) => t.word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b|\\(([A-Z])\\)`, "gi")++/**+ * A message as markup: each building it names becomes a chip to click (to+ * build one), each good a chip with its icon, and each key in brackets a key.+ */+const callouts = (text: string): string =>+ escapeHtml(text).replace(namedPattern, (match, word: string | undefined, key: string | undefined) => {+ if (key) return `<kbd class="key">${key}</kbd>`+ const thing = namedThings.find((t) => t.word === word!.toLowerCase())+ if (!thing) return match+ if ("good" in thing.ref) return `<span class="ref ware" title="${goods[thing.ref.good].title}">${goodIcon(thing.ref.good, 13)}${match}</span>`+ const kind = kinds[thing.ref.kind]+ return kind.buildable+ ? `<button class="ref kind" data-kind="${thing.ref.kind}" title="Build a ${kind.title.toLowerCase()}: ${escapeHtml(kind.blurb)}">${icon("build", 13)}${match}</button>`+ : `<span class="ref kind" title="${escapeHtml(kind.blurb)}">${icon("town", 13)}${match}</span>`+ })const hex = (color: number) => `#${color.toString(16).padStart(6, "0")}`/** Seconds as m:ss. */@@ -287,7 +329,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste{ view: "order", label: "order", key: "O", icon: "order" },{ view: "condition", label: "condition", key: "C", icon: "condition" }]- views.append(iconEl("view", 16))+ const viewsTitle = el("div", "views-title", "map overlays")+ viewsTitle.title = "Colour the map by one of these, to see where the town is doing well or badly. Press the key again (or click) to hide it."+ views.append(viewsTitle)const viewEls = viewButtons.map((v) => {const button = el("button", "")button.title = `Show ${v.label} over the map (${v.key}); again to hide it`@@ -495,15 +539,50 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst h3 = el("h3", "")if (glyph) h3.append(iconEl(glyph))h3.append(document.createTextNode(heading))+ box.append(h3)if (help) {- const info = iconEl("info", 15)- info.classList.add("help")- info.title = help+ const info = el("button", "help")+ info.append(iconEl("info", 15))+ info.title = "What this means"+ info.setAttribute("aria-expanded", "false")+ const text = el("p", "help-text", help)+ info.onclick = () => {+ const open = !text.classList.contains("open")+ text.classList.toggle("open", open)+ info.setAttribute("aria-expanded", String(open))+ }h3.append(info)+ box.append(text)}- box.append(h3)return box}+ /**+ * A slider for one of the town's levers. While it is held, the town's+ * numbers do not move it back; `sync` sets it otherwise.+ */+ const slider = (min: number, max: number, step: number, onInput: (value: number) => void) => {+ const input = el("input", "slider")+ input.type = "range"+ input.min = String(min)+ input.max = String(max)+ input.step = String(step)+ let held = false+ input.addEventListener("pointerdown", () => (held = true))+ input.addEventListener("pointerup", () => (held = false))+ input.addEventListener("blur", () => (held = false))+ const paint = () => input.style.setProperty("--at", `${((Number(input.value) - min) / (max - min)) * 100}%`)+ input.oninput = () => {+ paint()+ onInput(Number(input.value))+ }+ const sync = (value: number) => {+ if (held || input.value === String(value)) return+ input.value = String(value)+ paint()+ }+ paint()+ return { input, sync }+ }const header = (title: string, lead: HTMLElement, below?: HTMLElement) => {const head = el("header", "")const text = el("div", "title")@@ -708,30 +787,23 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste)for (const tier of ["settlers", "citizens"] as const) {const line = el("div", "row lever")- const minus = el("button", "frame step", "−")const value = el("span", "rate")- const plus = el("button", "frame step", "+")- const controls = el("span", "controls")- controls.append(minus, value, plus)const name = el("span", "label")name.innerHTML = icon(tier, 16)name.append(document.createTextNode(tier))- line.append(name, controls)+ line.append(name, value)+ const rate = slider(TAX_STEPS[0], TAX_STEPS.at(-1)!, 5, (to) => ui.edits.push({ type: "tax", tier, rate: to }))+ rate.input.classList.add("tax")+ rate.input.title = "Drag to set the rate; double-click for the usual 100%"+ rate.input.ondblclick = () => ui.edits.push({ type: "tax", tier, rate: 100 })const effect = el("p", "effect")- levers.append(line, effect)- const move = (by: number) => {- const now = ui.stats?.policy[tier] ?? 100- const i = TAX_STEPS.indexOf(now as (typeof TAX_STEPS)[number])- const next = TAX_STEPS[Math.min(TAX_STEPS.length - 1, Math.max(0, (i < 0 ? 2 : i) + by))]!- ui.edits.push({ type: "tax", tier, rate: next })- }- minus.onclick = () => move(-1)- plus.onclick = () => move(1)+ levers.append(line, rate.input, effect)live.push(() => {- const rate = ui.stats?.policy[tier] ?? 100- value.textContent = `${rate}%`- const sway = Math.round((100 - rate) * moodRules.perTaxPoint)- const grudge = rate > moodRules.grudge.above ? " · a grudge builds while it stays this high, and fades slowly" : ""+ const now = ui.stats?.policy[tier] ?? 100+ rate.sync(now)+ value.textContent = `${now}%`+ const sway = Math.round((100 - now) * moodRules.perTaxPoint)+ const grudge = now > moodRules.grudge.above ? " · a grudge builds while it stays this high, and fades slowly" : ""effect.textContent = (sway === 0 ? "the usual rate" : `${signed(sway)} approval`) + grudgeeffect.className = `effect ${sway > 0 ? "up" : sway < 0 ? "down" : ""}`})@@ -792,45 +864,41 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst store = section("goods and trade","trade",- "Traders buy what the town sells beyond what it keeps, and sell it what it buys up to that, at half again the price. Prices fall as the town sells and rise as it buys. Click sell / buy / — to change a good."+ "Traders call every few seconds. Drag a good's slider left to sell it beyond what the town keeps, right to buy it up to that (at half again the price), the further the more each call; the middle neither sells nor buys. Prices fall as the town sells and rise as it buys.")const reserveLine = el("div", "row lever")- const reserveControls = el("span", "controls")- const fewer = el("button", "frame step", "−")const reserveValue = el("span", "rate")- const more = el("button", "frame step", "+")- reserveControls.append(fewer, reserveValue, more)- reserveLine.append(el("span", "label", "keep in store"), reserveControls)- store.append(reserveLine)- const stepReserve = (by: number) => {- const now = ui.stats?.policy.reserve ?? 25- const i = RESERVES.indexOf(now as (typeof RESERVES)[number])- ui.edits.push({ type: "reserve", amount: RESERVES[Math.min(RESERVES.length - 1, Math.max(0, (i < 0 ? 1 : i) + by))]! })- }- fewer.onclick = () => stepReserve(-1)- more.onclick = () => stepReserve(1)- const modes: ReadonlyArray<TradeMode> = ["none", "sell", "buy"]+ reserveLine.append(el("span", "label", "keep in store"), reserveValue)+ const reserve = slider(0, RESERVE_MAX, 5, (amount) => ui.edits.push({ type: "reserve", amount }))+ reserve.input.title = "How much of each good the town keeps: it sells only beyond this, and buys only up to it"+ store.append(reserveLine, reserve.input, el("p", "effect", "of each good: sold only above this, bought only up to it"))+ /** Collections a minute: the traders come at every ledger. */+ const perMinute = 60 / (LEDGER_TICKS * STEP_SECONDS)const goodRows = goodIds.map((g) => {- const line = el("div", "row good-row")- const mode = el("button", "frame mode", "")- mode.title = "Click to sell, buy, or neither"- mode.onclick = () => {- const s = ui.stats- if (!s) return- const now: TradeMode = s.policy.sells.includes(g) ? "sell" : s.policy.buys.includes(g) ? "buy" : "none"- ui.edits.push({ type: "trade", good: g, mode: modes[(modes.indexOf(now) + 1) % modes.length]! })- }+ const line = el("div", "trade-row")const name = el("span", "label")name.innerHTML = goodIcon(g, 16)name.append(document.createTextNode(goods[g].title))- const price = el("span", "price")- name.append(price)const value = el("span", "count")+ const price = el("span", "price")+ const top = el("div", "row")+ const change = el("small", "change")const right = el("span", "label")- right.append(value, mode)- line.append(name, right)+ right.append(change, value, price)+ top.append(name, right)+ // Left of the middle sells, right of it buys, the middle neither; how far out is how much a collection.+ const deal = slider(-TRADE_LOAD, TRADE_LOAD, 1, (v) =>+ ui.edits.push(v === 0 ? { type: "trade", good: g, mode: "none" } : { type: "trade", good: g, mode: v < 0 ? "sell" : "buy", amount: Math.abs(v) })+ )+ deal.input.classList.add("deal")+ deal.input.title = `Drag left to sell ${goods[g].title}, right to buy it; the further, the more each time the traders call. Double-click to stop trading it.`+ deal.input.ondblclick = () => ui.edits.push({ type: "trade", good: g, mode: "none" })+ const mode = el("span", "mode")+ const bottom = el("div", "deal-line")+ bottom.append(deal.input, mode)+ line.append(top, bottom)store.append(line)- return { g, value, mode, price }+ return { g, value, change, mode, price, deal, line }})panel.append(store)@@ -918,14 +986,21 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste// Goods' change over the last minute of samples.const ago = history[Math.max(0, history.length - 1 - Math.round(60 / SAMPLE_SECONDS))]reserveValue.textContent = String(s.policy.reserve)+ reserve.sync(s.policy.reserve)for (const r of goodRows) {const change = ago ? s.stock[r.g] - ago.stock[r.g] : 0- r.value.innerHTML = `${s.stock[r.g]}${change !== 0 ? ` <small class="${change > 0 ? "up" : "down"}">${change > 0 ? "+" : ""}${change}/min</small>` : ""}`+ r.change.textContent = change !== 0 ? `${change > 0 ? "+" : ""}${change}/min` : ""+ r.change.className = `change ${change > 0 ? "up" : "down"}`+ r.value.textContent = String(s.stock[r.g])const now: TradeMode = s.policy.sells.includes(r.g) ? "sell" : s.policy.buys.includes(r.g) ? "buy" : "none"- r.mode.textContent = now === "none" ? "—" : now- r.mode.className = `frame mode ${now === "none" ? "" : now}`+ const load = s.policy.loads[r.g]+ r.deal.sync(now === "sell" ? -load : now === "buy" ? load : 0)+ r.mode.textContent = now === "none" ? "no trade" : `${now} ≤${Math.round(load * perMinute)}/min`+ r.mode.className = `mode ${now}`+ r.line.className = `trade-row ${now}`const price = now === "buy" ? askOf(r.g, s.prices[r.g]) : Math.round(priceOf(r.g, s.prices[r.g]) * 10) / 10r.price.textContent = `${price}c${s.prices[r.g] !== 100 ? ` (${s.prices[r.g]}%)` : ""}`+ r.price.title = now === "buy" ? "what traders ask for one" : "what traders pay for one"}const samples = s.historyconst coinsSvg = sparkline(samples.map((h) => h.coins))@@ -952,9 +1027,10 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste/** A line of a description as a row: its icon and what it is about, its value, any goods as chips, and a note underneath saying why. */const renderLine = (row: HTMLElement, l: Line) => {- row.className = `line ${l.tone ?? ""}`+ // A value too long to sit beside the label goes under it, aligned with it.+ row.className = `line ${l.tone ?? ""}${(l.value ?? "").length > 14 ? " long" : ""}`const chips = l.goods ? `<span class="chips">${l.goods.map((g) => `<span class="chip" title="${goods[g.good].title}">${goodIcon(g.good, 14)}${g.count}</span>`).join("")}</span>` : ""- row.innerHTML = `<span class="label">${icon(l.icon, 16)}<span class="what"></span></span><span class="count"></span>${chips}${l.note ? `<small class="note"></small>` : ""}`+ row.innerHTML = `<span class="mark">${icon(l.icon, 16)}</span><span class="what"></span><span class="count"></span>${chips}${l.note ? `<small class="note"></small>` : ""}`row.querySelector<HTMLElement>(".what")!.textContent = l.labelrow.querySelector<HTMLElement>(".count")!.textContent = l.value ?? ""if (l.note) row.querySelector<HTMLElement>(".note")!.textContent = l.note@@ -1346,6 +1422,32 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteinput.reset()}+ /** Ticker lines the mayor has put away, by what they say (and, for news, when). */+ const dismissed = new Set<string>()+ let tickerLines: { alerts: Stats["alerts"]; news: Stats["chronicle"] } = { alerts: [], news: [] }+ ticker.onclick = (event) => {+ event.stopPropagation()+ const target = event.target as HTMLElement+ const off = target.closest<HTMLElement>("[data-dismiss]")+ if (off) {+ dismissed.add(off.dataset.dismiss!)+ return+ }+ const ref = target.closest<HTMLElement>("[data-kind]")+ if (ref) {+ const kind = ref.dataset.kind as KindId+ // Straight to placing it: the placement itself says if the town cannot build it yet.+ if (kinds[kind].buildable) place(kind)+ return+ }+ const line = target.closest<HTMLElement>(".cell.place")+ if (!line) return+ const alert = line.dataset.alert !== undefined ? tickerLines.alerts[Number(line.dataset.alert)] : undefined+ if (alert?.at) return goTo(alert.at, alert.size, alert.id)+ const news = line.dataset.news !== undefined ? tickerLines.news[Number(line.dataset.news)] : undefined+ if (news?.at) goTo(news.at, 1, null)+ }+/** The last chronicle line announced. */let lastNews = ""/** Copies the town's numbers and preview into the page, once a frame. */@@ -1353,7 +1455,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => PersistesyncPanel()const s = ui.statsif (s) {- coins.innerHTML = `${icon("coins", 20)}<span class="stack"><b>${s.coins}</b><small class="${s.net >= 0 ? "up" : "down"}">${s.net >= 0 ? "+" : ""}${s.net}/min</small></span>`+ setHtml(coins, `${icon("coins", 20)}<span class="stack"><b>${s.coins}</b><small class="${s.net >= 0 ? "up" : "down"}">${s.net >= 0 ? "+" : ""}${s.net}/min</small></span>`)coins.title = "Coins in the treasury, and what it gains (or loses) a minute"coins.classList.toggle("debt", s.coins < 0)const left = Math.max(0, s.charter.term * 60 - Math.floor(s.minute * 60))@@ -1363,14 +1465,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste: s.season.coming === null? "no more winters this term": `winter in ${clockText(s.season.left)}${severity(s.season.coming)}`- clock.innerHTML = `${icon(s.season.winter ? "winter" : "clock", 20)}<span class="stack"><b>${clockText(left)}</b><small class="${s.season.winter ? "winter" : s.season.coming === "hard" ? "down" : ""}">year ${s.season.year} · ${until}</small></span>`+ setHtml(clock, `${icon(s.season.winter ? "winter" : "clock", 20)}<span class="stack"><b>${clockText(left)}</b><small class="${s.season.winter ? "winter" : s.season.coming === "hard" ? "down" : ""}">year ${s.season.year} · ${until}</small></span>`)clock.title = `${s.season.winter ? "Winter: fields lie still, fishing is slow, and homes eat faster" : "Time left in the term"}\nThe almanac: the coming winter is ${s.season.coming === null ? "beyond the term" : winters[s.season.coming].title}, the one after ${s.season.after === null ? "beyond the term" : winters[s.season.after].title}.\nMild: fishing at ${Math.round(winters.mild.fishing * 100)}%. Normal: ${Math.round(winters.normal.fishing * 100)}%. Hard: half as long again, fishing at ${Math.round(winters.hard.fishing * 100)}%, and homes heating are a fire risk.`const trend = s.mood.target > s.mood.approval ? "↑" : s.mood.target < s.mood.approval ? "↓" : ""- approval.innerHTML = `${icon("approval", 18)}<span class="stack"><b class="${s.mood.approval < 0 ? "down" : ""}">${signed(s.mood.approval)} <span class="${s.mood.target >= s.mood.approval ? "up" : "down"}">${trend}</span></b><small>approval</small></span>`- settlerCell.innerHTML = `${icon("settlers", 18)}<span class="stack"><b>${s.settlers}</b><small>settlers</small></span>`- citizenCell.innerHTML = `${icon("citizens", 18)}<span class="stack"><b>${s.citizens}</b><small>citizens${s.burghers > 0 ? ` · ${s.burghers} burghers` : ""}</small></span>`+ setHtml(approval, `${icon("approval", 18)}<span class="stack"><b class="${s.mood.approval < 0 ? "down" : ""}">${signed(s.mood.approval)} <span class="${s.mood.target >= s.mood.approval ? "up" : "down"}">${trend}</span></b><small>approval</small></span>`)+ setHtml(settlerCell, `${icon("settlers", 18)}<span class="stack"><b>${s.settlers}</b><small>settlers</small></span>`)+ setHtml(citizenCell, `${icon("citizens", 18)}<span class="stack"><b>${s.citizens}</b><small>citizens${s.burghers > 0 ? ` · ${s.burghers} burghers` : ""}</small></span>`)const short = s.shortStaffed.length- jobs.innerHTML = `${icon("jobs", 18)}<span class="stack"><b>${s.employed}<span class="of">/${s.jobs}</span></b><small class="${short > 0 ? "down" : ""}">${short > 0 ? `${short} short · click` : "jobs filled"}</small></span>`+ setHtml(jobs, `${icon("jobs", 18)}<span class="stack"><b>${s.employed}<span class="of">/${s.jobs}</span></b><small class="${short > 0 ? "down" : ""}">${short > 0 ? `${short} short · click` : "jobs filled"}</small></span>`)jobs.title = short > 0? `Workers at work over workers needed. ${short} workplace${short > 1 ? "s are" : " is"} short: ${s.shortStaffed.slice(0, 5).map((w) => `${w.title} ${w.assigned}/${w.needed}${w.nobodyNear ? " (no homes within 15 road cells)" : ""}`).join(", ")}. Click to visit them in turn.`: "Workers at work over workers needed: every workplace has its crew. Residents walk at most 15 road cells to work."@@ -1382,7 +1484,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisterequest.classList.toggle("show", s.crown.open && s.fate.state === "playing")if (s.crown.open) {const have = s.stock[s.crown.good]- requestText.innerHTML = `${icon("crown", 18)}<span>the crown asks for <b>${s.crown.amount}</b> ${goodIcon(s.crown.good, 14)} <b>${goods[s.crown.good].title}</b> <span class="muted">(${have} in store)</span> · <b>${clockText(s.crown.left)}</b> · +${s.crown.reward} coins</span>`+ setHtml(requestText, `${icon("crown", 18)}<span>the crown asks for <b>${s.crown.amount}</b> ${goodIcon(s.crown.good, 14)} <b>${goods[s.crown.good].title}</b> <span class="muted">(${have} in store)</span> · <b>${clockText(s.crown.left)}</b> · +${s.crown.reward} coins</span>`)send.disabled = have < s.crown.amount}// What threatens the term, or is about to complete it.@@ -1415,26 +1517,26 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst sec = Math.max(0, Math.round((minute - tick) / 60))return sec < 5 ? "just now" : sec < 60 ? `${sec} s ago` : `${Math.round(sec / 60)} min ago`}+ const alerts = s.alerts.filter((a) => !dismissed.has(`a:${a.text}`))+ const fresh = news.filter((l) => !dismissed.has(`n:${l.tick}:${l.text}`))+ const toneIcon = { hint: "hint", warn: "caution", bad: "warning" } as const+ const row = (kind: string, tone: string, glyph: IconName, text: string, place: boolean, key: string, data: string) =>+ `<div class="cell ${kind} ${tone}${place ? " place" : ""}" ${data}>${icon(glyph, 16, "mark")}<span class="text">${text}</span><span class="acts">${place ? `<button class="act locate" title="Show me where">${icon("locate", 14)}</button>` : ""}<button class="act dismiss" data-dismiss="${escapeHtml(key)}" title="Dismiss">${icon("close", 12)}</button></span></div>`const tickerHtml = [- ...(s.alerts.length > 0 ? [`<div class="head">now</div>`] : []),- ...s.alerts.map((a, i) => `<button class="cell${a.at ? " place" : ""}" data-alert="${i}" title="${a.at ? "Click to go there" : ""}">${icon("warning", 14)}<span>${a.text}</span>${a.at ? `<kbd>go</kbd>` : ""}</button>`),- ...(news.length > 0 ? [`<div class="head">lately</div>`] : []),- ...news.map((l, i) => `<button class="cell news${l.at ? " place" : ""}" data-news="${i}" title="${l.at ? "Click to go there" : ""}">${icon("chronicle", 14)}<span>${l.text} <em>${ago(l.tick)}</em></span>${l.at ? `<kbd>go</kbd>` : ""}</button>`)+ ...(alerts.length > 0 ? [`<div class="head">now</div>`] : []),+ ...alerts.map((a) => row("alert", a.tone, toneIcon[a.tone], callouts(a.text), a.at !== null, `a:${a.text}`, `data-alert="${s.alerts.indexOf(a)}"`)),+ ...(fresh.length > 0 ? [`<div class="head">lately</div>`] : []),+ ...fresh.map((l) => row("news", "", "chronicle", `${callouts(l.text)} <em data-tick="${l.tick}"></em>`, l.at !== null, `n:${l.tick}:${l.text}`, `data-news="${news.indexOf(l)}"`))].join("")if (ticker.dataset.html !== tickerHtml) {ticker.dataset.html = tickerHtmlticker.innerHTML = tickerHtml- for (const b of ticker.querySelectorAll<HTMLButtonElement>("button.place")) {- b.onclick = (event) => {- event.stopPropagation()- const alertIndex = b.dataset.alert- const target = alertIndex !== undefined ? s.alerts[Number(alertIndex)] : null- if (target?.at) return goTo(target.at, target.size, target.id)- const line = news[Number(b.dataset.news)]- if (line?.at) goTo(line.at, 1, null)- }- }}+ for (const em of ticker.querySelectorAll<HTMLElement>("em[data-tick]")) {+ const text = ago(Number(em.dataset.tick))+ if (em.textContent !== text) em.textContent = text+ }+ tickerLines = { alerts: s.alerts, news }ticker.classList.toggle("show", tickerHtml !== "" && s.fate.state === "playing")// News as it happens: a toast for each new alarm line.const latest = s.chronicle.at(-1)diff --git a/src/icons.ts b/src/icons.tsindex df93082..6292d1c 100644--- a/src/icons.ts+++ b/src/icons.ts@@ -34,6 +34,9 @@ const paths: Record<string, string> = {winter: `<path d="M8 2v13M2.5 5.2l11 6.6M2.5 11.8l11-6.6M6.5 2.8L8 4.2l1.5-1.4M6.5 14.2L8 12.8l1.5 1.4" fill="none" stroke="#3d6db5"/>`,summer: `<circle cx="8" cy="8.5" r="3" fill="#f0d98a"/><path d="M8 2.5v1.5M8 13v1.5M2 8.5h1.5M12.5 8.5H14M3.8 4.3l1 1M11.2 11.7l1 1M3.8 12.7l1-1M11.2 5.3l1-1" fill="none"/>`,crown: `<path d="M2.5 12.5l-.5-7 3.5 3L8 3.5l2.5 5 3.5-3-.5 7z" fill="#e3c25a"/><path d="M2.5 12.5h11v1.5h-11z" fill="#d6ae2e"/>`,+ hint: `<path d="M8 1.8c-2.6 0-4.3 1.9-4.3 4.2 0 1.7 1 2.6 1.7 3.5.4.5.6 1 .6 1.7h4c0-.7.2-1.2.6-1.7.7-.9 1.7-1.8 1.7-3.5 0-2.3-1.7-4.2-4.3-4.2z" fill="#dce6f5"/><path d="M6.2 13h3.6M6.8 14.8h2.4" fill="none"/><path d="M8 4.5v3" fill="none" stroke="#3d6db5" stroke-width="1.4"/>`,+ caution: `<path d="M8 2.5l6.5 11.5h-13z" fill="#f6e6c4"/><path d="M8 6.5v4" fill="none" stroke="#b8782e" stroke-width="1.6"/><circle cx="8" cy="12.2" r=".9" fill="#b8782e" stroke="none"/>`,+ locate: `<circle cx="8" cy="8" r="4.5" fill="none"/><circle cx="8" cy="8" r="1.4" fill="currentColor" stroke="none"/><path d="M8 1.5v2.5M8 12v2.5M1.5 8H4M12 8h2.5" fill="none"/>`,warning: `<path d="M8 2.5l6.5 11.5h-13z" fill="#f6e1dc"/><path d="M8 6.5v4" fill="none" stroke="#b04a39" stroke-width="1.6"/><circle cx="8" cy="12.2" r=".9" fill="#b04a39" stroke="none"/>`,goal: `<path d="M3.5 14.5V2" fill="none"/><path d="M3.5 2.5h9l-2 3 2 3h-9z" fill="#e89a7c"/>`,faith: `<path d="M8 2v4M6 3.8h4" fill="none"/><path d="M4 14.5V9.5l4-3.5 4 3.5v5z" fill="#c9d6ee"/><path d="M7 14.5v-3h2v3" fill="none" stroke-width="1"/>`,@@ -48,7 +51,8 @@ const paths: Record<string, string> = {homes: `<path d="M3 8.5v5.5h10V8.5" fill="#f5f6f2"/><path d="M1.5 9L8 3l6.5 6z" fill="#e6c3b2"/><path d="M7 14v-3.5h2V14" fill="#c4523f" stroke-width="1"/>`,build: `<path d="M3 14.5V5.5l5-3 5 3v9z" fill="#f5f6f2"/><path d="M3 5.5l5-3 5 3" fill="#c9d6ee"/><path d="M6 14.5v-4h4v4" fill="#3d6db5" stroke-width="1"/><path d="M5.5 7.5h1.5M9 7.5h1.5" fill="none" stroke-width="1"/>`,bulldoze: `<path d="M3 4.5l9.5 9.5M12.5 4.5L3 14" fill="none" stroke="#b04a39" stroke-width="2"/>`,- town: `<path d="M2.5 14.5v-7h11v7z" fill="#f5f6f2"/><path d="M5 9.5h1.5v2H5zM9.5 9.5H11v2H9.5z" fill="#f3dca6" stroke-width="1"/><path d="M7 14.5v-3h2v3" fill="none" stroke-width="1"/><path d="M8 7.5V1.5" fill="none"/><path d="M8 1.8l3.5 1.2L8 4.2z" fill="#c4523f" stroke-width="1"/>`,+ // The settlers' cottage, as the town draws it: the town's mark (and the page's favicon).+ town: `<g stroke-width="1"><path d="M10.75 5.6L13.5 7.25 8 4.5 5.25 2.85z" fill="#e2e5de"/><path d="M2.5 11.25L8 14V10L2.5 7.25z" fill="#eef0ea"/><path d="M8 14l5.5-2.75v-4L8 10z" fill="#dfe2db"/><path d="M8 10l5.5-2.75L10.75 5.6z" fill="#dfe2db"/><path d="M8 10l2.75-4.4-5.5-2.75L2.5 7.25z" fill="#e6c3b2"/></g><path d="M10.1 12.95l1.3-.65v-2.3l-1.3.65z" fill="#8f9891" stroke-width=".6"/><path d="M4.6 10.6l1.3.65V9.75l-1.3-.65z" fill="#c9d6e6" stroke-width=".6"/>`,pause: `<path d="M5 3.5h2v9H5zM9 3.5h2v9H9z" fill="currentColor" stroke="none"/>`,play: `<path d="M5 3l8 5-8 5z" fill="currentColor" stroke="none"/>`,save: `<path d="M2.5 2.5h9l2 2v9h-11z" fill="#f7f8f4"/><path d="M5 2.5v3.5h5V2.5" fill="#c9d6ee"/><path d="M4.5 13.5V9.5h7v4" fill="#e9ebe5"/>`,diff --git a/src/present.ts b/src/present.tsindex e6804ec..e8efd9a 100644--- a/src/present.ts+++ b/src/present.ts@@ -80,7 +80,7 @@ import {type GridValue,type Status as StatusValue} from "./schema.ts"-import { capacity, CELL_STEPS, elapsed, goalsOf, larder, 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, 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"@@ -234,21 +234,26 @@ const riskText = (value: number) => (value < RISK_MAX * 0.35 ? "ok" : value >= r// ── Map views ─────────────────────────────────────────────────────────────-const GOOD = 0x4f9a6a-const FAIR = 0xc9b45a-const BAD = 0xc4523f-const COOL = 0x3d6db5-/** A meter 0 → `of` as a colour: green when low, amber, red past the warning line. */+// Blue for fine, sand for worth a look, vermilion for wrong: a scale that still reads with+// red-green colour blindness, unlike green to red.+const GOOD = 0x3a78c2+const FAIR = 0xe2c25c+const BAD = 0xc8553d+/** Citizens' homes, in the workers view. */+const COOL = 0x8a58a8+/** The buildings that serve a view (its fire watch, its healer), and a workplace's reach: ink, apart from the scale. */+const MARK = 0x3d4943+/** A meter 0 → `of` as a colour: blue when low, sand, vermilion past the warning line. */const meterColor = (value: number, of: number, warn: number) => (value >= warn ? BAD : value >= of * 0.35 ? FAIR : GOOD)const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {appeal: {title: "desirability",keys: [- { color: 0x2f7a43, label: `${home.tiers[3].appeal}+: townhouses` },+ { color: 0x1f4f8f, label: `${home.tiers[3].appeal}+: townhouses` },{ color: GOOD, label: `${home.tiers[2].appeal}+: citizens` },- { color: 0xc9d6a0, label: "0 to 4: settlers only" },- { color: 0xe0a060, label: "below 0: fewer people, less tax" },+ { color: 0xc6d4e4, label: "0 to 4: settlers only" },+ { color: 0xeaa26a, label: "below 0: fewer people, less tax" },{ color: BAD, label: `${home.squalid} or less: squalid` }],note: "Every point counts: a cottage holds fewer and pays less for each point below 0, and pays more above it. Industry pushes homes away; parks (the more they hold, the further they reach), a chapel, a market, and paved streets draw them in."@@ -271,7 +276,7 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {{ color: FAIR, label: "rising" },{ color: BAD, label: "at risk, or burning" }],- note: "Buildings take the colour too. A fire watch's watchman resets the risk of every home and workshop along the way; red means past half way, so there is time. Wooden cottages, ovens, forges, and crowding raise it."+ note: "Buildings take the colour too. A fire watch's watchman resets the risk of every home and workshop along the way; vermilion means past half way, so there is still time. Wooden cottages, ovens, forges, and crowding raise it."},health: {title: "health",@@ -306,11 +311,11 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {const starvedSince = new Map<number, number>()const ALERT_PATIENCE = ticks(30)/** A view's colour over a model: pale, so the ink still reads. */-const TINT = { good: 0xb6dcc0, fair: 0xf0dea4, bad: 0xefb0a4, cool: 0xb7cdef, settlers: 0xead7bd, fine: 0x9fd0ad, plain: 0xffffff }+const TINT = { good: 0xbcd2ee, fair: 0xf3e3a8, bad: 0xf2b9a0, cool: 0xdccbe8, mark: 0xd5dad3, settlers: 0xead7bd, fine: 0xa9c4e8, plain: 0xffffff }const needIcons = { food: "food", bread: "bread", cloth: "cloth", faith: "faith" } as constconst appealColor = (v: number) =>- v >= home.tiers[3].appeal ? 0x2f7a43 : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc9d6a0 : v > home.squalid ? 0xe0a060 : BAD+ v >= home.tiers[3].appeal ? 0x1f4f8f : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc6d4e4 : v > home.squalid ? 0xeaa26a : BADexport const Interact = Game.System("Town/Interact",@@ -545,7 +550,8 @@ export const Interact = Game.System(showReach(tile, kind)rangeOfKind(tile, kind)if (kind.appeal) preview.plots.push({ x: tile.x - kind.appeal.reach, y: tile.y - kind.appeal.reach, size: tile.size + 2 * kind.appeal.reach, look: kind.appeal.value > 0 ? "reach" : "hover" })- if (canPlace(grid, tile)) preview.ghosts.push({ what: ui.placing, cell: at })+ if (lockReason(kind, resources.census.get())) preview.plots.push({ ...tile, look: "blocked" })+ else if (canPlace(grid, tile)) preview.ghosts.push({ what: ui.placing, cell: at })else preview.plots.push({ ...tile, look: "blocked" })} else if (ui.tool === "bulldoze") {preview.danger = true@@ -861,7 +867,9 @@ export const Interact = Game.System(const kind = kinds[ui.placing]const r = reachOf(kind)const a = kind.appeal- preview.tooltip = `${kind.title.toLowerCase()}${r !== null ? ` · works ${r} cells around` : ""}${a ? ` · desirability ${signed(a.value)} out to ${a.reach} cells` : ""}${preview.rangeNote ? ` · ${preview.rangeNote}` : ""} · needs a road at the middle of a side`+ const lock = lockReason(kind, resources.census.get())+ if (lock) preview.tooltip = `${kind.title.toLowerCase()} · ${lock}`+ else preview.tooltip = `${kind.title.toLowerCase()}${r !== null ? ` · works ${r} cells around` : ""}${a ? ` · desirability ${signed(a.value)} out to ${a.reach} cells` : ""}${preview.rangeNote ? ` · ${preview.rangeNote}` : ""} · needs a road at the middle of a side`} else if (ui.tool === "pave") preview.tooltip = `drag along a road to pave it · ${PAVE_COST.coins} coins and a stone a cell · carriers and walkers go half again as fast on it, and homes beside it like it a little`else if (cell && ui.view === "appeal" && inside(cell.x, cell.y)) preview.tooltip = `desirability ${appealAt(cells, cell.x, cell.y)}`ui.preview = preview@@ -952,7 +960,7 @@ export const Interact = Game.System(const roads = reach(grid, doors(grid, picked.data.tile.get()))for (let k = 0; k < roads.distance.length; k++) {const d = roads.distance[k]!- if (d >= 0 && d <= COMMUTE) out.push({ x: k % GRID, y: Math.floor(k / GRID), size: 1, color: COOL, alpha: 0.18 })+ if (d >= 0 && d <= COMMUTE) out.push({ x: k % GRID, y: Math.floor(k / GRID), size: 1, color: MARK, alpha: 0.14 })}inReach = (t) => doors(grid, t).some((c) => {const n = roads.distance[key(c.x, c.y)]!@@ -986,8 +994,8 @@ export const Interact = Game.System(const service = maybe(data.service)?.serviceconst r = maybe(data.risk)if (service === view) {- out.push({ ...data.tile.get(), color: COOL, alpha: 0.55, ring: true })- tints.set(entity.id, TINT.cool)+ out.push({ ...data.tile.get(), color: MARK, alpha: 0.55, ring: true })+ tints.set(entity.id, TINT.mark)} else if (view === "fire" && r) {const color = data.burning.present ? BAD : meterColor(r.fire, RISK_MAX, risk.warn)out.push({ ...data.tile.get(), color, alpha: 0.4 })@@ -1003,8 +1011,8 @@ export const Interact = Game.System(tints.set(row.entity.id, tintOf(color))}for (const { entity, data } of standing(buildings)) if (maybe(data.service)?.service === "repair") {- out.push({ ...data.tile.get(), color: COOL, alpha: 0.55, ring: true })- tints.set(entity.id, TINT.cool)+ out.push({ ...data.tile.get(), color: MARK, alpha: 0.55, ring: true })+ tints.set(entity.id, TINT.mark)}for (const { data } of ruins) out.push({ ...data.tile.get(), color: BAD, alpha: 0.8 })}@@ -1018,9 +1026,9 @@ export const Interact = Game.System(const census = resources.census.get()const stock = resources.stock.get()const burningRow = [...buildings, ...houses].find(({ data }) => data.burning.present)- if (census.burning > 0) alerts.push({ text: `${census.burning} on fire`, at: burningRow?.data.tile.get() ?? null, size: burningRow?.data.tile.get().size ?? 1, id: burningRow?.entity.id ?? null })+ if (census.burning > 0) alerts.push({ tone: "bad", text: `${census.burning} on fire`, at: burningRow?.data.tile.get() ?? null, size: burningRow?.data.tile.get().size ?? 1, id: burningRow?.entity.id ?? null })const sickRow = houses.find(({ data }) => data.sick.present)- if (census.sick > 0) alerts.push({ text: `${census.sick} home${census.sick > 1 ? "s" : ""} sick`, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })+ if (census.sick > 0) alerts.push({ tone: "warn", text: `${census.sick} home${census.sick > 1 ? "s" : ""} sick`, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })const waiting = new Map<string, { n: number; at: TileLike; id: number }>()const remote = new Map<string, { n: number; at: TileLike; id: number }>()const shortStaffed: Array<{ id: number; title: string; cell: Point; size: number; assigned: number; needed: number; nobodyNear: boolean }> = []@@ -1051,19 +1059,19 @@ export const Interact = Game.System(for (const id of [...starvedSince.keys()]) if (!seen.has(id)) starvedSince.delete(id)const list = (m: Map<string, { n: number }>) => [...m].map(([k, v]) => `${k}${v.n > 1 ? ` ×${v.n}` : ""}`).join(", ")const first = (m: Map<string, { at: TileLike; id: number }>) => [...m.values()][0]- if (waiting.size > 0) alerts.push({ text: `waiting for inputs: ${list(waiting)}`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null })- if (remote.size > 0) alerts.push({ text: `no workers within ${COMMUTE} road cells: ${list(remote)}`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null })+ if (waiting.size > 0) alerts.push({ tone: "warn", text: `waiting for inputs: ${list(waiting)}`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null })+ if (remote.size > 0) alerts.push({ tone: "warn", text: `no workers within ${COMMUTE} road cells: ${list(remote)}`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null })const hallRow = buildings.find(({ data }) => data.hall.present)- if (census.homes > 0 && larder(stock) === 0) alerts.push({ text: "no food in store: homes go hungry", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })+ if (census.homes > 0 && larder(stock) === 0) alerts.push({ tone: "bad", text: "no food in store: homes go hungry", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })// A town's first steps, until it has taken them: the ticker is otherwise silent when there is least to go on.const hallAt = { at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: null }const standingKinds = new Set(buildings.filter(({ data }) => !data.site.present && !data.rising.present).map(({ data }) => data.building.get().kind))const placedKinds = new Set(buildings.map(({ data }) => data.building.get().kind))const residents = census.settlers + census.citizens- if (census.homes === 0 && houses.length === 0) alerts.push({ text: "first: lay a road out from the town hall (R), then drag a row of homes along it (H); settlers move in on their own", ...hallAt })- else if (!placedKinds.has("fishery") && !placedKinds.has("bakery") && residents < 60) alerts.push({ text: "settlers eat: build a fishery (B) within two cells of water, on a road; the town hall's walker hands the fish out", ...hallAt })- else if (residents >= 20 && !placedKinds.has("lumberjack") && stock.planks < 20) alerts.push({ text: "planks are running out: a lumberjack by the woods and a sawmill make more; every home and building needs them", ...hallAt })- else if (residents >= 40 && !placedKinds.has("market") && standingKinds.has("fishery")) alerts.push({ text: "the town hall's walker only reaches 20 road cells: a market (B) hands out food further along the streets", ...hallAt })+ if (census.homes === 0 && houses.length === 0) alerts.push({ tone: "hint", text: "first: lay a road out from the town hall (R), then drag a row of homes along it (H); settlers move in on their own", ...hallAt })+ else if (!placedKinds.has("fishery") && !placedKinds.has("bakery") && residents < 60) alerts.push({ tone: "hint", text: "settlers eat: build a fishery (B) within two cells of water, on a road; the town hall's walker hands the fish out", ...hallAt })+ else if (residents >= 20 && !placedKinds.has("lumberjack") && stock.planks < 20) alerts.push({ tone: "hint", text: "planks are running out: a lumberjack by the woods and a sawmill make more; every home and building needs them", ...hallAt })+ else if (residents >= 40 && !placedKinds.has("market") && standingKinds.has("fishery")) alerts.push({ tone: "hint", text: "the town hall's walker only reaches 20 road cells: a market (B) hands out food further along the streets", ...hallAt })const ledger = resources.ledger.get()const charter = resources.charter.get()diff --git a/src/rules/trade.ts b/src/rules/trade.tsindex e14bbd2..42353b3 100644--- a/src/rules/trade.ts+++ b/src/rules/trade.ts@@ -2,7 +2,8 @@ import { goodIds, type Amounts, type GoodId } from "../content.ts"import { askOf, priceOf } from "./households.ts"import { shippedRules, type Rules } from "./config.ts"-export interface TradePolicy { readonly sells: ReadonlyArray<GoodId>; readonly buys: ReadonlyArray<GoodId>; readonly reserve: number }+/** `loads`: how much of each good may change hands at a collection (at most `rules.tradeLoad`); all of it when absent. */+export interface TradePolicy { readonly sells: ReadonlyArray<GoodId>; readonly buys: ReadonlyArray<GoodId>; readonly reserve: number; readonly loads?: Partial<Amounts> }export interface Shelf { readonly stock: Amounts; readonly accepts: ReadonlyArray<GoodId>; readonly cap: number }/** Exact collection trade, including price drift and refunds. Shelves keep runtime insertion order. */@@ -11,8 +12,9 @@ export const tradeCollection = (initial: ReadonlyArray<Shelf>, policy: TradePolilet coins = startingCoins, traded = 0for (const good of goodIds) {const held = stores.reduce((sum, s) => sum + s.stock[good], 0)+ const load = Math.min(rules.tradeLoad, policy.loads?.[good] ?? rules.tradeLoad)if (policy.sells.includes(good)) {- let surplus = Math.min(rules.tradeLoad, held - policy.reserve)+ let surplus = Math.min(load, held - policy.reserve)if (surplus > 0) {const earned = Math.round(surplus * priceOf(good, prices[good], rules))coins += earned; traded += earned@@ -24,7 +26,7 @@ export const tradeCollection = (initial: ReadonlyArray<Shelf>, policy: TradePoli}} else if (policy.buys.includes(good)) {const ask = askOf(good, prices[good], rules)- let wanted = Math.min(rules.tradeLoad, policy.reserve - held, Math.floor(coins / ask))+ let wanted = Math.min(load, policy.reserve - held, Math.floor(coins / ask))if (wanted > 0) {coins -= wanted * ask; traded -= wanted * askprices[good] = Math.min(rules.market.ceiling, prices[good] + wanted * rules.market.perUnit)diff --git a/src/save.ts b/src/save.tsindex cf74062..7b131b6 100644--- a/src/save.ts+++ b/src/save.ts@@ -10,24 +10,31 @@*/import { Clock, Context, Effect, Schema } from "effect"+import { goodIds, 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.- * A version 4 save is carried forward (see `carry`); older ones cannot be loaded.+ * 6: how much of each good may be traded at a collection.+ * Version 4 and 5 saves are carried forward (see `carry`); older ones cannot be loaded.*/-export const SAVE_VERSION = 5+export const SAVE_VERSION = 6/**- * Fills in what a save from the version before lacks, so a town in progress- * survives an update: the mood's grudge (none yet) and the news's places- * (unknown). Anything else is left to the world's own validation.+ * 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. Anything else is+ * left to the world's own validation.*/const carry = (version: number, world: unknown): unknown | null => {- if (version !== 4 || typeof world !== "object" || world === null) return null+ if ((version !== 4 && version !== 5) || typeof world !== "object" || world === null) return nullconst w = world as { resources?: Record<string, unknown> }const r = w.resourcesif (!r || typeof r !== "object") return null+ const policy = r["Town/Policy"]+ if (policy && typeof policy === "object" && !("loads" in policy)) r["Town/Policy"] = { ...policy, loads: Object.fromEntries(goodIds.map((g) => [g, TRADE_LOAD])) }+ if (version === 5) return wconst mood = r["Town/Mood"]if (mood && typeof mood === "object" && !("grudge" in mood)) r["Town/Mood"] = { ...mood, grudge: 0, memory: 0 }const chronicle = r["Town/Chronicle"] as { lines?: Array<Record<string, unknown>> } | undefineddiff --git a/src/schema.ts b/src/schema.tsindex 739abbe..283adf9 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -203,14 +203,16 @@ export const Census = Descriptor.ConstructedResource(Decode.struct({}))("Town/Census")/*** The town's tax rates (in percent of the usual, for each tier), what it- * sells to traders beyond the reserve it keeps, and what it buys up to it.+ * sells to traders beyond the reserve it keeps, and what it buys up to it;+ * `loads` is how much of each good may change hands at a collection.*/export const Policy = Descriptor.ConstructedResource(Decode.struct({settlers: integer,citizens: integer,sells: Decode.array(good),buys: Decode.array(good),- reserve: integer+ reserve: integer,+ loads: amounts}))("Town/Policy")/**diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex 9040fc5..b62701f 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -8,7 +8,7 @@*/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, type Amounts, type Kind, type ParkPiece } from "../content.ts"+import { amounts, goodIds, RESERVE_MAX, TAX_STEPS, type Amounts, type Kind, type ParkPiece } from "../content.ts"import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"import { inside } from "../iso.ts"import { generate } from "../mapgen.ts"@@ -18,6 +18,13 @@ import { crownGap, foundedFate } from "./term.ts"export const unlocked = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }) =>census.settlers + census.citizens >= kind.unlock.residents && census.citizens >= kind.unlock.citizens+/** What a town still lacks before it can build `kind`, or `null` when it can. */+export const lockReason = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }): string | null => {+ const residents = census.settlers + census.citizens+ if (residents < kind.unlock.residents) return `needs ${kind.unlock.residents} residents (the town has ${residents})`+ if (census.citizens < kind.unlock.citizens) return `needs ${kind.unlock.citizens} citizens (the town has ${census.citizens})`+ return null+}export const ApplyEdits = Game.System("Town/ApplyEdits",@@ -120,7 +127,7 @@ export const ApplyEdits = Game.System(const tile = { ...edit.cell, size: kind.size }if (!kind.buildable) breakif (!unlocked(kind, resources.census.get())) {- ui.toast(`${kind.title} needs a bigger town`)+ ui.toast(`${kind.title} ${lockReason(kind, resources.census.get())}`)break}if (!canPlace(grid.value(), tile)) {@@ -261,13 +268,14 @@ export const ApplyEdits = Game.System(break}case "tax":- resources.policy.update((p) => ({ ...p, [edit.tier]: edit.rate }))+ resources.policy.update((p) => ({ ...p, [edit.tier]: Math.max(TAX_STEPS[0], Math.min(TAX_STEPS.at(-1)!, Math.round(edit.rate))) }))breakcase "trade":resources.policy.update((p) => ({...p,sells: edit.mode === "sell" ? [...p.sells.filter((g) => g !== edit.good), edit.good] : p.sells.filter((g) => g !== edit.good),- buys: edit.mode === "buy" ? [...p.buys.filter((g) => g !== edit.good), edit.good] : p.buys.filter((g) => g !== edit.good)+ buys: edit.mode === "buy" ? [...p.buys.filter((g) => g !== edit.good), edit.good] : p.buys.filter((g) => g !== edit.good),+ loads: edit.amount === undefined ? p.loads : { ...p.loads, [edit.good]: Math.max(0, Math.min(rules.tradeLoad, Math.round(edit.amount))) }}))breakcase "pause": {@@ -308,7 +316,7 @@ export const ApplyEdits = Game.System(break}case "reserve":- resources.policy.update((p) => ({ ...p, reserve: edit.amount }))+ resources.policy.update((p) => ({ ...p, reserve: Math.max(0, Math.min(RESERVE_MAX, Math.round(edit.amount))) }))breakcase "newTown": {for (const id of entities.values()) commands.despawn(id)@@ -335,7 +343,7 @@ export const ApplyEdits = Game.System(resources.fires.set({ fires: [], next: 1 })resources.land.set({ mask: land.mask, cells: land.cells })resources.ledger.set({ taxes: 0, trade: 0, upkeep: 0, admin: 0 })- resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve })+ resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve, loads: amounts(Object.fromEntries(goodIds.map((g) => [g, rules.tradeLoad]))) })resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0, grudge: 0, memory: 0 })resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter, rules), met: 0, missed: 0, streak: 0, snubs: [] })diff --git a/src/sim/index.ts b/src/sim/index.tsindex 22f7a91..6c5fbda 100644--- a/src/sim/index.ts+++ b/src/sim/index.ts@@ -2,7 +2,7 @@* The simulation, one fixed step at a time. Nothing here touches the* renderer, so it runs headless too.*/-import { amounts, defaultCharter } from "../content.ts"+import { amounts, defaultCharter, goodIds, TRADE_LOAD } from "../content.ts"import { Game, Time } from "../schema.ts"import { ApplyEdits } from "./edits.ts"import { Deliver, Dispatch } from "./logistics.ts"@@ -64,7 +64,7 @@ export const blankResources = () => ({Treasury: { coins: 0 },Ledger: { taxes: 0, trade: 0, upkeep: 0, admin: 0 },Census: { homes: 0, settlers: 0, citizens: 0, burghers: 0, jobs: 0, employed: 0, food: 0, bread: 0, cloth: 0, faith: 0, sick: 0, burning: 0 },- Policy: { settlers: 100, citizens: 100, sells: [], buys: [], reserve: 25 },+ Policy: { settlers: 100, citizens: 100, sells: [], buys: [], reserve: 25, loads: amounts(Object.fromEntries(goodIds.map((g) => [g, TRADE_LOAD]))) },Charter: { ...defaultCharter(0), founded: 0, winters: [] as Array<"none" | "mild" | "normal" | "hard"> },Land: { mask: "", cells: 0 },Market: { prices: amounts({}) },@@ -82,6 +82,6 @@ export const blankResources = () => ({export { CELL_STEPS, elapsed, seasonAt, termTicks, winterOf } from "./shared.ts"export { SITE_SHARE } from "./work.ts"-export { unlocked } from "./edits.ts"+export { lockReason, unlocked } 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/ui.ts b/src/ui.tsindex 861f78b..2374160 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -28,6 +28,8 @@ export interface Line {/** Something that needs looking at now, and where (when it is somewhere). */export interface Alert {+ /** A next step to take, something going wrong, or something that costs the town now. */+ readonly tone: "hint" | "warn" | "bad"readonly text: stringreadonly at: Point | null/** The footprint there, cells a side, for the outline. */@@ -58,8 +60,8 @@ export type Edit =| { readonly type: "remove"; readonly cell: Point }/** Sets a tier's tax rate, in percent of the usual. */| { readonly type: "tax"; readonly tier: "settlers" | "citizens"; readonly rate: number }- /** Sells a good to traders beyond the reserve, buys it up to the reserve, or neither. */- | { readonly type: "trade"; readonly good: GoodId; readonly mode: TradeMode }+ /** Sells a good to traders beyond the reserve, buys it up to the reserve, or neither; `amount`, up to how much a collection. */+ | { readonly type: "trade"; readonly good: GoodId; readonly mode: TradeMode; readonly amount?: number }/** How much of each good the town keeps before selling, and buys up to. */| { readonly type: "reserve"; readonly amount: number }/** Pauses the building on a cell, or sets it back to work. */@@ -174,6 +176,7 @@ export interface Stats {readonly sells: ReadonlyArray<GoodId>readonly buys: ReadonlyArray<GoodId>readonly reserve: number+ readonly loads: Amounts}readonly stock: Amounts/** Each good's price with traders, in percent of the usual. */diff --git a/test/model.test.ts b/test/model.test.tsindex 2bcd2d5..08a9ba3 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, RESERVES, RISK_MAX, TAX_STEPS, type CharterValue+ CONDITION_MAX, crown, goodIds, groundIds, home, kindOrder, kinds, landIds, market, propIds, 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"@@ -60,9 +60,9 @@ const Command = Schema.Union([Schema.TaggedStruct("BuildAnywhere", { kind: Schema.Literals(kindOrder), x: Cell, y: Cell }),// One of the buildings, homes, or roads that stand.Schema.TaggedStruct("Remove", { pick: Pick, what: Schema.Literals(["building", "house", "road", "park"]) }),- Schema.TaggedStruct("Tax", { tier: Schema.Literals(["settlers", "citizens"]), rate: Schema.Literals(TAX_STEPS) }),- Schema.TaggedStruct("Trade", { good: Schema.Literals(goodIds), mode: Schema.Literals(["sell", "buy", "none"]) }),- Schema.TaggedStruct("Reserve", { amount: Schema.Literals(RESERVES) }),+ Schema.TaggedStruct("Tax", { tier: Schema.Literals(["settlers", "citizens"]), rate: between(TAX_STEPS[0], TAX_STEPS.at(-1)!) }),+ Schema.TaggedStruct("Trade", { good: Schema.Literals(goodIds), mode: Schema.Literals(["sell", "buy", "none"]), amount: between(0, TRADE_LOAD) }),+ Schema.TaggedStruct("Reserve", { amount: between(0, RESERVE_MAX) }),Schema.TaggedStruct("Pause", { pick: Pick, on: Schema.Boolean }),Schema.TaggedStruct("Deliver", {}),Schema.TaggedStruct("Govern", {}),@@ -191,7 +191,7 @@ const apply = (town: Headless, command: Command): string | null => {edit({ type: "tax", tier: command.tier, rate: command.rate })breakcase "Trade":- edit({ type: "trade", good: command.good, mode: command.mode })+ edit({ type: "trade", good: command.good, mode: command.mode, amount: command.amount })breakcase "Reserve":edit({ type: "reserve", amount: command.amount })diff --git a/tools/balance/verify/fixture.ts b/tools/balance/verify/fixture.tsindex dd8cc31..a4f1255 100644--- a/tools/balance/verify/fixture.ts+++ b/tools/balance/verify/fixture.ts@@ -1,4 +1,5 @@/** This is the only layer that imports the ECS runtime. Model inputs stay plain data. */+import { goodIds } from "../../../src/content.ts"import { GRID } from "../../../src/iso.ts"import { ownerAt } from "../../../src/grid.ts"import { rolesOf, wearOf } from "../../../src/archetypes.ts"@@ -46,7 +47,7 @@ export const fixture = (scenario: Scenario, rules: Rules): Headless => {s.resources["Town/Charter"] = { ...scenario.charter, founded: 1, winters: scenario.charter.winters ?? s.resources["Town/Charter"].winters }s.resources["Town/Treasury"] = { coins: scenario.coins }s.resources["Town/Mood"] = { ...s.resources["Town/Mood"], approval: scenario.approval }- s.resources["Town/Policy"] = { settlers: scenario.policy.settlers, citizens: scenario.policy.citizens, sells: scenario.trade?.sells ?? [], buys: scenario.trade?.buys ?? [], reserve: scenario.trade?.reserve ?? rules.trade.reserve }+ s.resources["Town/Policy"] = { settlers: scenario.policy.settlers, citizens: scenario.policy.citizens, sells: scenario.trade?.sells ?? [], buys: scenario.trade?.buys ?? [], reserve: scenario.trade?.reserve ?? rules.trade.reserve, loads: Object.fromEntries(goodIds.map((g) => [g, scenario.trade?.loads?.[g] ?? rules.tradeLoad])) }if (scenario.trade?.prices) s.resources["Town/Market"] = { prices: scenario.trade.prices }s.resources["Town/Appeal"] = { cells: [] }})