Skip to content

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

Dress the town: buildings, land, walkers, townsfolk, and a clearer page

SandroMaglione6eb16e512e64
diff --git a/README.md b/README.md
index 3d619e7..b75ea3c 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ that ends with the town complete, lost, or run out. Game logic runs on the
```sh
pnpm install
-pnpm dev --host --port 5232
+pnpm dev --host --port 5232 # /gallery.html shows every drawing side by side
pnpm typecheck
pnpm test # model-based tests: random mayors, rules that must always hold; and saving
pnpm check # every way a term can end, ends it
diff --git a/gallery.html b/gallery.html
new file mode 100644
index 0000000..f64b583
--- /dev/null
+++ b/gallery.html
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>Town · art gallery</title>
+ <style>html, body { margin: 0; background: #e2e9e6; } canvas { display: block; }</style>
+ </head>
+ <body>
+ <script type="module" src="/src/gallery.ts"></script>
+ </body>
+</html>
diff --git a/src/art.ts b/src/art.ts
index c3c43e2..17a87dc 100644
--- a/src/art.ts
+++ b/src/art.ts
@@ -6,8 +6,11 @@
* `iso.ts`): floor lengths are whole units, heights whole pixels, and lines
* one of two weights.
*
- * Colour is kept for meaning: awnings by what a building is for, crate
- * labels by good, a home's door, the red of a problem marker.
+ * Colour is kept for meaning: each building is dressed in the colour of
+ * what it makes or does (its awnings, roof, trim, and the things in its
+ * yard), crate labels by good, a home's roof, the red of a problem marker.
+ * Trees, rocks, water, and roads vary by cell, so the land is never a
+ * pattern; the same cell always looks the same.
*
* The measures that have to agree:
* - a road is 12 units wide and runs down the middle of a cell;
@@ -18,7 +21,7 @@
*/
import { Container, Graphics } from "pixi.js"
-import { categoryColor, GROWN, home, kinds, ROCK_AMOUNT, type Kind, type KindId, type Tier } from "./content.ts"
+import { goods, GROWN, home, kinds, ROCK_AMOUNT, type GoodId, type Kind, type KindId, type Tier } from "./content.ts"
import { cellOf, DIRS, key } from "./grid.ts"
import { flat, GRID, toScreen, U, type Point } from "./iso.ts"
@@ -29,7 +32,6 @@ const leftFill = 0xe9ebe5
const rightFill = 0xdde0d9
const roadFill = 0xe6e8e2
const marking = 0xb4b9b1
-const leafFill = 0xe7ece0
const waterFill = 0xdfe8e6
const soilFill = 0xece8dc
const ripe = 0xcdb46a
@@ -124,14 +126,14 @@ const square = (u: number, v: number, half: number, z = 0): Array<Point> => [
]
/** A plate, `half` from its centre; while it is marked out, only its outline, growing. */
-const plate = (g: Graphics, half: number, alpha = 1, marked = 1, filled = true) => {
+export const plate = (g: Graphics, half: number, alpha = 1, marked = 1, filled = true) => {
g.poly(flat(square(0, 0, half * (0.8 + 0.2 * marked))))
.fill({ color: plateFill, alpha: filled ? alpha : 0 })
.stroke({ color: ink, width: LINE, alpha: alpha * marked, join: "round" })
}
/** Half a plate's width for a footprint `size` cells a side: a unit inside it. */
-const plateHalf = (size: number) => (size * 8 - 1) * U
+export const plateHalf = (size: number) => (size * 8 - 1) * U
/** The wire frame of a box, `h` pixels tall: every edge, the hidden ones too. */
const drawFrame = (g: Graphics, a: number, h: number) => {
@@ -186,10 +188,10 @@ const gable = (g: Graphics, a: number, H: number, rise: number, ridgeAlong: "x"
}
}
-/** A small window, a unit either side of `along`, `z` to `z + 5` px up a wall. */
-const window_ = (g: Graphics, side: Side, a: number, along: number, z: number) => {
+/** A small glazed window, a unit either side of `along`, `z` to `z + 5` px up a wall. */
+const window_ = (g: Graphics, side: Side, a: number, along: number, z: number, glass = 0xdbe6ea) => {
const p = onWall(side, a)
- outline(g, [p(along - U, 0, z), p(along + U, 0, z), p(along + U, 0, z + 5), p(along - U, 0, z + 5)], DETAIL)
+ g.poly(flat([p(along - U, 0, z), p(along + U, 0, z), p(along + U, 0, z + 5), p(along - U, 0, z + 5)])).fill({ color: glass }).stroke({ color: ink, width: DETAIL, join: "round" })
}
// ── Buildings ─────────────────────────────────────────────────────────────
@@ -198,7 +200,7 @@ const window_ = (g: Graphics, side: Side, a: number, along: number, z: number) =
export const heightOf = (kind: Kind) => (kind.roof === "gable" ? HUT : kind.stories * STORY)
/** Height of a kind's building at full size, roof and topper included. */
export const topOf = (kind: Kind) =>
- heightOf(kind) + (kind.roof === "gable" ? HUT_ROOF : kind.topper === "none" ? 0 : kind.topper === "sails" ? 20 : CHIMNEY)
+ heightOf(kind) + (kind.roof === "gable" ? HUT_ROOF : kind.topper === "none" ? 0 : kind.topper === "sails" ? 24 : CHIMNEY)
/** The centres of a flat roof's bays, back row first, in cells. */
const bays = (kind: Kind): Array<{ readonly u: number; readonly v: number; readonly index: number }> => {
@@ -240,6 +242,28 @@ const drawSeams = (g: Graphics, side: Side, a: number, H: number, door: boolean)
for (const s of seams) line(g, p(s, 0, 0), p(s, 0, H), DETAIL, ink, 0.5)
}
+/**
+ * Windows down a flat-roofed building's wall, on every floor: beside the
+ * door when there is room, else two along it. A chapel's are tall and pointed.
+ */
+const drawWallWindows = (g: Graphics, side: Side, a: number, H: number, door: boolean, stories: number, glass: number, pointed: boolean) => {
+ const p = onWall(side, a)
+ const along = door ? (a >= 12 * U ? [-(a - 3 * U), a - 3 * U] : []) : [-Math.round(a / U / 2) * U, Math.round(a / U / 2) * U]
+ const tall = pointed ? 14 : 8
+ for (let floor = 0; floor < stories; floor++) {
+ const z = floor * STORY + (pointed ? 9 : 12)
+ if (z + tall + 4 > H) continue
+ for (const s of along) {
+ const w = U
+ const shape = pointed
+ ? [p(s - w, 0, z), p(s + w, 0, z), p(s + w, 0, z + tall - 3), p(s, 0, z + tall), p(s - w, 0, z + tall - 3)]
+ : [p(s - w, 0, z), p(s + w, 0, z), p(s + w, 0, z + tall), p(s - w, 0, z + tall)]
+ g.poly(flat(shape)).fill({ color: glass }).stroke({ color: ink, width: DETAIL, join: "round" })
+ line(g, p(s - w - 0.5 * U, 0, z), p(s + w + 0.5 * U, 0, z), DETAIL)
+ }
+ }
+}
+
/** A small box on the roof, `c` from its centre (u, v), from `base` up to `top`. */
const roofBox = (g: Graphics, u: number, v: number, c: number, base: number, top: number) => {
quad(g, [at(u - c, v + c, base), at(u + c, v + c, base), at(u + c, v + c, top), at(u - c, v + c, top)], leftFill)
@@ -252,11 +276,370 @@ export interface Doors {
readonly left: boolean
}
+// ── Solids for props ──
+
+/** Screen pixels a unit along the floor spans. */
+const PX = Math.sqrt(5)
+
+/** A point on an upright plane through (u, v, z) across `axis`: `s` px along the floor (towards +v across "u", +u across "v"), `t` px up. */
+const upright = (axis: "u" | "v", u: number, v: number, z: number) => (s: number, t: number): Point =>
+ axis === "u" ? at(u, v + (s / PX) * U, z + t) : at(u + (s / PX) * U, v, z + t)
+
+/** A circle `r` px across on an upright plane (see `upright`). */
+const ring = (axis: "u" | "v", u: number, v: number, z: number, r: number, n = 18): Array<Point> => {
+ const p = upright(axis, u, v, z)
+ return Array.from({ length: n }, (_, i) => p(Math.cos((i / n) * Math.PI * 2) * r, Math.sin((i / n) * Math.PI * 2) * r))
+}
+
+/** The convex hull of some points (monotone chain). */
+const hull = (points: ReadonlyArray<Point>): Array<Point> => {
+ const sorted = [...points].sort((p, q) => p.x - q.x || p.y - q.y)
+ const cross = (o: Point, p: Point, q: Point) => (p.x - o.x) * (q.y - o.y) - (p.y - o.y) * (q.x - o.x)
+ const half = (list: ReadonlyArray<Point>) => {
+ const out: Array<Point> = []
+ for (const p of list) {
+ while (out.length >= 2 && cross(out[out.length - 2]!, out[out.length - 1]!, p) <= 0) out.pop()
+ out.push(p)
+ }
+ out.pop()
+ return out
+ }
+ return [...half(sorted), ...half([...sorted].reverse())]
+}
+
+/** An ellipse's points: a circle `r` units across on the floor at (cx, cy) on screen, from angle `from` to `to`. */
+const floorArc = (cx: number, cy: number, r: number, from: number, to: number, n = 12): Array<Point> =>
+ Array.from({ length: n + 1 }, (_, i) => {
+ const t = from + ((to - from) * i) / n
+ return { x: cx + Math.cos(t) * (r / U) * 2 * Math.SQRT2, y: cy + Math.sin(t) * (r / U) * Math.SQRT2 }
+ })
+
+/** A box `su` × `sv` from its centre (u, v), `h` px tall from `z`. */
+const box = (g: Graphics, u: number, v: number, su: number, sv: number, z: number, h: number, top = roofFill, left = leftFill, right = rightFill, width = LINE) => {
+ const face = (points: ReadonlyArray<Point>, fill: number) => g.poly(flat(points)).fill({ color: fill }).stroke({ color: ink, width, join: "round" })
+ face([at(u - su, v + sv, z), at(u + su, v + sv, z), at(u + su, v + sv, z + h), at(u - su, v + sv, z + h)], left)
+ face([at(u + su, v - sv, z), at(u + su, v + sv, z), at(u + su, v + sv, z + h), at(u + su, v - sv, z + h)], right)
+ face([at(u - su, v - sv, z + h), at(u + su, v - sv, z + h), at(u + su, v + sv, z + h), at(u - su, v + sv, z + h)], top)
+}
+
+/** A standing cylinder `r` units across at (u, v), `h` px tall from `z`; `cap` puts a pointed roof on it. */
+const cylinder = (g: Graphics, u: number, v: number, r: number, z: number, h: number, side: number, top: number, cap?: number) => {
+ const base = at(u, v, z)
+ const rx = (r / U) * 2 * Math.SQRT2
+ const lid = base.y - h
+ g.poly(flat([{ x: base.x - rx, y: lid }, ...floorArc(base.x, base.y, r, Math.PI, 0), { x: base.x + rx, y: lid }]))
+ .fill({ color: side }).stroke({ color: ink, width: LINE, join: "round" })
+ if (cap === undefined) {
+ g.poly(flat(floorArc(base.x, lid, r, 0, Math.PI * 2, 20))).fill({ color: top }).stroke({ color: ink, width: LINE })
+ return
+ }
+ g.poly(flat([...floorArc(base.x, lid, r, 0, Math.PI), { x: base.x, y: lid - cap }]))
+ .fill({ color: top }).stroke({ color: ink, width: LINE, join: "round" })
+}
+
+/** A cylinder lying along `axis` (a log, a bale), `r` px thick, from `from` to `to` units along it, at `across` and resting on `z`. */
+const log = (g: Graphics, axis: "u" | "v", across: number, from: number, to: number, z: number, r: number, side: number, end: number) => {
+ const ends = (along: number) => (axis === "u" ? ring("u", along, across, z + r, r) : ring("v", across, along, z + r, r))
+ g.poly(flat(hull([...ends(from), ...ends(to)]))).fill({ color: side }).stroke({ color: ink, width: DETAIL, join: "round" })
+ g.poly(flat(ends(to))).fill({ color: end }).stroke({ color: ink, width: DETAIL })
+ const c = axis === "u" ? at(to, across, z + r) : at(across, to, z + r)
+ g.circle(c.x, c.y, Math.max(0.6, r * 0.35)).stroke({ color: ink, width: DETAIL, alpha: 0.45 })
+}
+
+/** A post `h` px tall. */
+const post = (g: Graphics, u: number, v: number, h: number, z = 0) => line(g, at(u, v, z), at(u, v, z + h), LINE)
+
+/** A sack of flour or grain, standing at (u, v). */
+const sack = (g: Graphics, u: number, v: number, fill = 0xf2ecdc, z = 0) => {
+ const c = at(u, v, z)
+ g.roundRect(c.x - 3, c.y - 7, 6, 7, 2.5).fill({ color: fill }).stroke({ color: ink, width: DETAIL })
+ line(g, { x: c.x - 1.5, y: c.y - 5.5 }, { x: c.x + 1.5, y: c.y - 5.5 }, DETAIL, ink, 0.6)
+}
+
+/** A small round bush. */
+const bush = (g: Graphics, u: number, v: number, r: number, leaves: Leaves) => {
+ const c = at(u, v, 0)
+ g.circle(c.x, c.y - r, r).fill({ color: leaves.shade }).stroke({ color: ink, width: DETAIL })
+ g.circle(c.x - r * 0.25, c.y - r * 1.25, r * 0.65).fill({ color: leaves.light })
+}
+
+/** A sheep: a woolly body, a dark head, four legs. */
+const sheepAt = (g: Graphics, u: number, v: number, facing: 1 | -1) => {
+ const c = at(u, v, 0)
+ for (const dx of [-2, 2]) line(g, { x: c.x + dx, y: c.y - 2 }, { x: c.x + dx, y: c.y }, DETAIL)
+ g.ellipse(c.x, c.y - 4.5, 4.5, 3).fill({ color: 0xf8f8f4 }).stroke({ color: ink, width: DETAIL })
+ g.circle(c.x + facing * 4.5, c.y - 5.5, 1.6).fill({ color: ink })
+}
+
+/** A small banner of cloth hung on a line between two posts across `axis`, in turn coloured. */
+const clothLine = (g: Graphics, u: number, v0: number, v1: number, colors: ReadonlyArray<number>) => {
+ post(g, u, v0, 11)
+ post(g, u, v1, 11)
+ line(g, at(u, v0, 11), at(u, v1, 11), DETAIL)
+ const n = colors.length
+ const step = (v1 - v0) / n
+ colors.forEach((color, i) => {
+ const s = v0 + step * i + U * 0.4
+ const e = v0 + step * (i + 1) - U * 0.4
+ quad(g, [at(u, s, 10.5), at(u, e, 10.5), at(u, e, 4 + (i % 2)), at(u, s, 4 + (i % 2))], color)
+ })
+}
+
+// ── How each kind is dressed ──
+
+/** A colour `t` of the way to `to`. */
+const mix = (from: number, to: number, t: number) => {
+ const c = (shift: number) => Math.round(((from >> shift) & 0xff) * (1 - t) + ((to >> shift) & 0xff) * t)
+ return (c(16) << 16) | (c(8) << 8) | c(0)
+}
+const pale = (color: number, t = 0.7) => mix(color, 0xffffff, t)
+const roofOf = (color: number): RoofColors => ({ face: pale(color, 0.7), shade: pale(color, 0.52) })
+
+const glassCool = 0xdbe6ea
+const glassWarm = 0xf3dca6
+
+interface Dress {
+ /** Awnings, the roof's trim, flags. */
+ readonly accent: number
+ /** A gabled kind's roof. */
+ readonly roof?: RoofColors
+ readonly glass?: number
+ readonly flag?: number
+ /** What stands around it on its plate, drawn once it is fitted out: `a` the walls' half width, `p` the plate's. */
+ readonly yard?: (g: Graphics, a: number, p: number, kind: Kind) => void
+}
+
+/** Where things stand on a plate: in the front corner, and in the strips beside the back of each wall facing the viewer. */
+const corner = (a: number, p: number) => (a + p) / 2
+
+const dresses: Readonly<Record<KindId, Dress>> = {
+ townhall: {
+ accent: 0x8a58a8, flag: 0xc4523f, glass: glassWarm,
+ yard: (g, a) => {
+ for (const axis of ["u", "v"] as const) {
+ const face = ring(axis, axis === "u" ? a : 0, axis === "u" ? 0 : a, STORY + 18, 5)
+ g.poly(flat(face)).fill({ color: 0xfaf8ee }).stroke({ color: ink, width: DETAIL })
+ const c = axis === "u" ? at(a, 0, STORY + 18) : at(0, a, STORY + 18)
+ line(g, c, { x: c.x, y: c.y - 3.5 }, DETAIL)
+ line(g, c, { x: c.x + (axis === "u" ? 2.5 : -2.5), y: c.y + 0.5 }, DETAIL)
+ }
+ }
+ },
+ warehouse: {
+ accent: 0x8a58a8,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ drawCrate(g, 0x2f8c87, 1.6 * U, 6, 0, c, c - 1.5 * U)
+ drawCrate(g, 0xd27a34, 1.6 * U, 6, 0, c, c + 1.5 * U)
+ cylinder(g, c, -a - 2 * U, 1.5 * U, 0, 8, 0xc79a5b, 0xe9c48a)
+ }
+ },
+ lumberjack: {
+ accent: 0x8a6a45, roof: roofOf(0x8a6a45),
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ for (const [du, z] of [[-1.6, 0], [0, 0], [1.6, 0], [-0.8, 2.6], [0.8, 2.6]] as const) {
+ log(g, "v", c + du * U, a + 0.5 * U, p - 0.5 * U, z, 1.6, 0xb08a5e, 0xe9d2a8)
+ }
+ cylinder(g, c, -a - 1.5 * U, 1.3 * U, 0, 3, 0xb08a5e, 0xe9d2a8)
+ const top = at(c, -a - 1.5 * U, 3)
+ line(g, { x: top.x - 1, y: top.y - 1 }, { x: top.x + 3, y: top.y - 7 }, LINE, 0x7d6140)
+ g.poly([top.x + 1.5, top.y - 7, top.x + 5, top.y - 8, top.x + 4, top.y - 5]).fill({ color: 0x8f9891 }).stroke({ color: ink, width: DETAIL })
+ }
+ },
+ forester: {
+ accent: 0x6e8f36, roof: roofOf(0x6e8f36),
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ for (const [u, v, s] of [[c, c, 0.8], [c, -a - 2 * U, 0.6], [-a - 2 * U, c, 0.55]] as const) {
+ const base = at(u, v, 0)
+ cylinder(g, u, v, 1.2 * U, 0, 3, 0xd5a86c, 0x7d6140)
+ fir(g, base.x, base.y - 3, s, 2, firLeaves)
+ }
+ }
+ },
+ quarry: {
+ accent: 0x8f9891,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ const stone = { top: 0xeeefea, left: 0xdcded7, right: 0xc9ccc4 }
+ box(g, c - 1 * U, c - 1 * U, 1.2 * U, 1.2 * U, 0, 5, stone.top, stone.left, stone.right)
+ box(g, c + 1.2 * U, c - 0.8 * U, 1.2 * U, 1.2 * U, 0, 5, stone.top, stone.left, stone.right)
+ box(g, c - 0.5 * U, c + 1.4 * U, 1.2 * U, 1.2 * U, 0, 5, stone.top, stone.left, stone.right)
+ box(g, c, c, 1.2 * U, 1.2 * U, 5, 5, stone.top, stone.left, stone.right)
+ // A hoist: an A-frame with a hanging hook.
+ const f = -a - 2.5 * U
+ const top = at(c, f, 16)
+ line(g, at(c - 1.5 * U, f, 0), top, LINE)
+ line(g, at(c + 1.5 * U, f, 0), top, LINE)
+ line(g, top, { x: top.x, y: top.y + 8 }, DETAIL)
+ box(g, c, f, U, U, 4, 4, stone.top, stone.left, stone.right)
+ }
+ },
+ mine: {
+ accent: 0x5a6479, glass: 0xd5dae4,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ // Rails and an ore cart.
+ for (const du of [-1, 1]) line(g, at(c + du * U, a + 0.5 * U, 0), at(c + du * U, p - 0.2 * U, 0), DETAIL, ink, 0.6)
+ box(g, c, c, 1.6 * U, 2 * U, 2, 5, 0x6c7488, 0xd5dae4, 0xbcc3d1)
+ for (const [dx, dy] of [[-2, 0], [1, -1], [3, 1]] as const) {
+ const top = at(c, c, 8)
+ g.circle(top.x + dx, top.y + dy, 1.5).fill({ color: 0x5a6479 }).stroke({ color: ink, width: DETAIL })
+ }
+ for (const dv of [-1.2, 1.2]) {
+ const w = at(c + 1.6 * U, c + dv * U, 1.5)
+ g.circle(w.x, w.y, 1.5).fill({ color: ink })
+ }
+ // A heap of ore by the wall.
+ const h = at(c, -a - 2 * U, 0)
+ g.poly([h.x - 9, h.y, h.x - 2, h.y - 6, h.x + 2, h.y - 5, h.x + 8, h.y]).fill({ color: 0xbcc3d1 }).stroke({ color: ink, width: DETAIL, join: "round" })
+ for (const [dx, dy] of [[-3, -2], [1, -3], [4, -1]] as const) g.rect(h.x + dx, h.y + dy, 2, 2).fill({ color: 0x5a6479 })
+ }
+ },
+ fishery: {
+ accent: 0x2f8c87, roof: roofOf(0x2f8c87),
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ cylinder(g, c, c, 1.5 * U, 0, 7, 0xc79a5b, 0x9fc9c4)
+ // A drying rack, fish hanging from it.
+ const u = c
+ const v0 = -a - 4 * U
+ const v1 = -a + 3 * U
+ post(g, u, v0, 11)
+ post(g, u, v1, 11)
+ line(g, at(u, v0, 11), at(u, v1, 11), DETAIL)
+ for (let i = 1; i <= 3; i++) {
+ const t = at(u, v0 + ((v1 - v0) * i) / 4, 11)
+ line(g, t, { x: t.x, y: t.y + 2 }, DETAIL)
+ g.poly([t.x, t.y + 2, t.x + 1.8, t.y + 5, t.x, t.y + 8, t.x - 1.8, t.y + 5]).fill({ color: 0x2f8c87 }).stroke({ color: ink, width: DETAIL })
+ }
+ }
+ },
+ sawmill: {
+ accent: 0xd27a34, glass: glassCool,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ // Planks stacked by one wall, a log waiting by the other.
+ for (let i = 0; i < 3; i++) box(g, c, -a + 1.5 * U, 1.1 * U, 3 * U, i * 2.5, 2.5, 0xf0c59a, 0xe2a873, 0xd2945c, DETAIL)
+ log(g, "u", c, -a - 3 * U, -a + 4 * U, 0, 2, 0xb08a5e, 0xe9d2a8)
+ }
+ },
+ smithy: {
+ accent: 0xb04a39, glass: glassWarm,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ // An anvil on a block.
+ cylinder(g, c, c, 1 * U, 0, 3, 0xb08a5e, 0xe9d2a8)
+ box(g, c, c, 0.6 * U, 1.4 * U, 3, 3, 0x6d7671, 0x5a625e, 0x4b524e)
+ // A heap of coal by the wall.
+ const h = at(c, -a - 2 * U, 0)
+ g.poly([h.x - 7, h.y, h.x - 1, h.y - 5, h.x + 6, h.y]).fill({ color: 0x5a625e }).stroke({ color: ink, width: DETAIL, join: "round" })
+ }
+ },
+ farm: {
+ accent: 0xd6ae2e, roof: roofOf(0xc4523f),
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ // A silo by the wall, hay bales in the front corner.
+ cylinder(g, c + U, -a - 3 * U, 3.5 * U, 0, 28, 0xeeeae0, pale(0xc4523f, 0.6), 9)
+ line(g, at(c + U, -a - 3 * U, 10), at(c + U, -a - 3 * U, 10), DETAIL)
+ log(g, "u", c - 2.5 * U, a + 2 * U, a + 7 * U, 0, 3, 0xe9cf7c, 0xf3e3a8)
+ log(g, "u", c + 2.5 * U, a + 2 * U, a + 7 * U, 0, 3, 0xe9cf7c, 0xf3e3a8)
+ log(g, "u", c, a + 2 * U, a + 7 * U, 5, 3, 0xe9cf7c, 0xf3e3a8)
+ }
+ },
+ mill: {
+ accent: 0xc9b48a, roof: roofOf(0x8a6a45), glass: glassCool,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ sack(g, c - U, c + U)
+ sack(g, c + 1.5 * U, c - U)
+ sack(g, c + 0.5 * U, c + 2.5 * U)
+ }
+ },
+ bakery: {
+ accent: 0xc4523f, glass: glassWarm,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ sack(g, c, -a - 1 * U)
+ sack(g, c, -a + 2 * U)
+ // A sign with a loaf on it.
+ const s = at(c, c, 0)
+ line(g, s, { x: s.x, y: s.y - 12 }, LINE)
+ g.roundRect(s.x - 4, s.y - 17, 8, 6, 1).fill({ color: 0xfaf3e3 }).stroke({ color: ink, width: DETAIL })
+ g.ellipse(s.x, s.y - 14, 2.6, 1.6).fill({ color: 0xc4523f })
+ }
+ },
+ sheep: {
+ accent: 0xb5654a, roof: roofOf(0xb5654a),
+ yard: (g, a, p) => {
+ // A pen in the front corner: its back rails, the sheep, its front rails.
+ const s = a + U
+ const e = p - U
+ const rails = (points: ReadonlyArray<readonly [number, number]>) => {
+ for (const [u, v] of points) post(g, u, v, 6)
+ for (let i = 1; i < points.length; i++) {
+ for (const z of [2.5, 5.5]) line(g, at(points[i - 1]![0], points[i - 1]![1], z), at(points[i]![0], points[i]![1], z), DETAIL)
+ }
+ }
+ rails([[s, e], [s, s], [e, s]])
+ sheepAt(g, s + 3 * U, s + 4 * U, 1)
+ sheepAt(g, s + 6 * U, s + 2.5 * U, -1)
+ sheepAt(g, s + 5.5 * U, s + 6.5 * U, 1)
+ rails([[s, e], [e, e], [e, s]])
+ cylinder(g, corner(a, p), -a - 3 * U, 2 * U, 0, 5, 0xe9cf7c, 0xf3e3a8)
+ }
+ },
+ weaver: {
+ accent: 0x8a58a8, glass: glassCool,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ clothLine(g, c, -a - 2.5 * U, -a + 5 * U, [0x8a58a8, 0xd6ae2e, 0x3d6db5])
+ sack(g, c, c, 0xeceee8)
+ }
+ },
+ market: {
+ accent: 0x3d6db5, flag: 0x3d6db5,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ // A stall with a striped canopy by one wall, crates by the other.
+ const u0 = c - 1.2 * U
+ const u1 = c + 1.2 * U
+ const v0 = -a - 2.5 * U
+ const v1 = -a + 4.5 * U
+ for (const [u, v] of [[u0, v0], [u1, v0], [u0, v1], [u1, v1]] as const) post(g, u, v, 11)
+ box(g, c, (v0 + v1) / 2, 1.2 * U, (v1 - v0) / 2, 0, 4, 0xe9c48a, 0xd5a86c, 0xc79a5b)
+ const strips = 5
+ for (let i = 0; i < strips; i++) {
+ const s = v0 + ((v1 - v0) * i) / strips
+ const e = v0 + ((v1 - v0) * (i + 1)) / strips
+ quad(g, [at(u0, s, 12), at(u0, e, 12), at(u1 + U, e, 9), at(u1 + U, s, 9)], i % 2 === 0 ? 0xc4523f : 0xf7f3ea)
+ }
+ drawCrate(g, 0x2f8c87, 1.2 * U, 5, 0, -a - 2 * U, c)
+ drawCrate(g, 0xc4523f, 1.2 * U, 5, 0, -a + 1.5 * U, c)
+ drawCrate(g, 0x8a58a8, 1.2 * U, 5, 5, -a - 0.2 * U, c)
+ }
+ },
+ chapel: {
+ accent: 0x3d6db5, glass: 0xc9d6ee,
+ yard: (g, a, p) => {
+ const c = corner(a, p)
+ bush(g, c, c, 4.5, broadLeaves[0]!)
+ bush(g, c, -a - 1 * U, 4, broadLeaves[1]!)
+ bush(g, -a - 1 * U, c, 4, broadLeaves[2]!)
+ }
+ }
+}
+
/**
* A building, `build` 0 → 1 of the way up (see `buildStages`); `door` 0
- * (shut) → 1 (open); `wave` drives flags and sails.
+ * (shut) → 1 (open); `wave` drives flags and sails. `plain` draws it bare
+ * and grey, as a ghost.
*/
-export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: number, wave: number, doors: Doors, color = categoryColor[kind.category]) => {
+export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: number, wave: number, doors: Doors, plain = false) => {
+ const dress: Dress = plain ? { accent: 0xb9beb5 } : dresses[kind.id]
+ const color = dress.accent
const a = kind.half * U
const full = heightOf(kind)
const stage = buildStages(build)
@@ -264,14 +647,22 @@ export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: numbe
if (stage.walls < 1) drawFrame(g, a, Math.round(full * stage.frame))
if (stage.walls <= 0) return
const H = Math.max(2, Math.round(full * stage.walls))
+ const glass = dress.glass ?? glassCool
walls(g, a, H)
- drawSeams(g, "left", a, H, doors.left)
- drawSeams(g, "right", a, H, doors.right)
+ const flatRoof = kind.roof !== "gable"
+ if (!flatRoof) {
+ drawSeams(g, "left", a, H, doors.left)
+ drawSeams(g, "right", a, H, doors.right)
+ }
if (kind.stories === 2 && H > STORY) {
line(g, at(-a, a, STORY), at(a, a, STORY), DETAIL, ink, 0.7)
line(g, at(a, -a, STORY), at(a, a, STORY), DETAIL, ink, 0.7)
}
+ if (flatRoof && stage.fit > 0.4) {
+ drawWallWindows(g, "right", a, H, doors.right, kind.stories, glass, kind.id === "chapel")
+ drawWallWindows(g, "left", a, H, doors.left, kind.stories, glass, kind.id === "chapel")
+ }
if (stage.fit > 0.15) {
if (doors.right) drawDoor(g, "right", a, H, stage.fit, door, color)
if (doors.left) drawDoor(g, "left", a, H, stage.fit, door, color)
@@ -279,21 +670,40 @@ export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: numbe
if (kind.roof === "gable") {
if (stage.fit > 0.4) {
- if (!doors.right) window_(g, "right", a, 0, 6)
- if (!doors.left) window_(g, "left", a, 0, 6)
+ if (!doors.right) window_(g, "right", a, 0, 6, glass)
+ if (!doors.left) window_(g, "left", a, 0, 6, glass)
+ }
+ gable(g, a, H, Math.round(HUT_ROOF * stage.fit), "x", dress.roof ?? paleRoof)
+ } else {
+ // A flat roof (the top of the walls while they rise), a band of colour under its edge, and its skylights, one by one.
+ if (stage.fit > 0.3 && H > 6) {
+ const band = (side: Side) => {
+ const p = onWall(side, a)
+ g.poly(flat([p(-a, 0, H - 3), p(a, 0, H - 3), p(a, 0, H), p(-a, 0, H)])).fill({ color: pale(color, 0.35) })
+ line(g, p(-a, 0, H - 3), p(a, 0, H - 3), DETAIL, ink, 0.6)
+ }
+ band("right")
+ band("left")
+ }
+ quad(g, square(0, 0, a, H), roofFill)
+ if (kind.id === "mill" && stage.fit > 0) {
+ // A pointed cap instead of skylights.
+ const apex = at(0, 0, H + Math.round(16 * stage.fit))
+ const roof = dress.roof ?? paleRoof
+ quad(g, [at(a, -a, H), at(a, a, H), apex], roof.shade)
+ quad(g, [at(-a, a, H), at(a, a, H), apex], roof.face)
+ }
+ const flag = kind.topper === "flag"
+ const usesBack = kind.topper !== "none" && kind.topper !== "flag" && kind.topper !== "sails"
+ if (stage.fit > 0.4 && kind.id !== "mill") {
+ const all = bays(kind).filter((bay) => !(usesBack && bay.index === 0) && !(flag && bay.index === kind.bays - 1))
+ const shown = Math.ceil(all.length * smooth((stage.fit - 0.4) / 0.4))
+ for (const bay of all.slice(0, shown)) {
+ const pane = square(bay.u, bay.v, (kind.window / 2) * U, H)
+ g.poly(flat(pane)).fill({ color: glass }).stroke({ color: ink, width: LINE, join: "round" })
+ line(g, pane[0]!, pane[2]!, DETAIL, ink, 0.25)
+ }
}
- gable(g, a, H, Math.round(HUT_ROOF * stage.fit))
- return
- }
-
- // A flat roof (the top of the walls while they rise) and its windows, one by one.
- quad(g, square(0, 0, a, H), roofFill)
- const flag = kind.topper === "flag"
- const usesBack = kind.topper !== "none" && kind.topper !== "flag" && kind.topper !== "sails"
- if (stage.fit > 0.4) {
- const all = bays(kind).filter((bay) => !(usesBack && bay.index === 0) && !(flag && bay.index === kind.bays - 1))
- const shown = Math.ceil(all.length * smooth((stage.fit - 0.4) / 0.4))
- for (const bay of all.slice(0, shown)) outline(g, square(bay.u, bay.v, (kind.window / 2) * U, H))
}
if (stage.fit > 0) {
@@ -305,47 +715,60 @@ export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: numbe
roofBox(g, u, v, c, H, top)
outline(g, [at(u - U, v + c, top - 7), at(u + U, v + c, top - 7), at(u + U, v + c, top - 2), at(u - U, v + c, top - 2)], DETAIL)
outline(g, [at(u + c, v - U, top - 7), at(u + c, v + U, top - 7), at(u + c, v + U, top - 2), at(u + c, v - U, top - 2)], DETAIL)
- quad(g, [at(u - c, v + c, top), at(u + c, v + c, top), at(u, v, apex)], leftFill)
- quad(g, [at(u + c, v - c, top), at(u + c, v + c, top), at(u, v, apex)], rightFill)
+ const cap = plain ? paleRoof : roofOf(color)
+ quad(g, [at(u - c, v + c, top), at(u + c, v + c, top), at(u, v, apex)], cap.face)
+ quad(g, [at(u + c, v - c, top), at(u + c, v + c, top), at(u, v, apex)], cap.shade)
+ if (stage.fit > 0.9) {
+ const tip = at(u, v, apex)
+ line(g, tip, { x: tip.x, y: tip.y - 7 }, LINE)
+ line(g, { x: tip.x - 2.5, y: tip.y - 5 }, { x: tip.x + 2.5, y: tip.y - 5 }, LINE)
+ }
} else if (kind.topper === "chimney") {
const top = H + Math.round(CHIMNEY * stage.fit)
roofBox(g, u, v, CHIMNEY_HALF, H, top)
quad(g, square(u, v, CHIMNEY_HALF, top), roofFill)
+ if (!plain) g.poly(flat(square(u, v, CHIMNEY_HALF - 0.5 * U, top))).fill({ color: ink, alpha: 0.55 })
} else if (kind.topper === "crates") {
- // Crates stacked on the roof's back bay.
+ // Crates stacked on the roof's back bay, labelled with what is stored.
if (stage.fit > 0.5) {
- drawCrate(g, 0x8f9891, CRATE, CRATE_HEIGHT, H, u, v)
- drawCrate(g, 0x8f9891, CRATE, CRATE_HEIGHT, H, u + 7 * U, v)
- drawCrate(g, 0x8f9891, CRATE, CRATE_HEIGHT, H + CRATE_HEIGHT, u + 3 * U, v)
+ const labels = plain ? [0x8f9891, 0x8f9891, 0x8f9891] : [0xd27a34, 0x2f8c87, 0x8a58a8]
+ drawCrate(g, labels[0]!, CRATE, CRATE_HEIGHT, H, u, v)
+ drawCrate(g, labels[1]!, CRATE, CRATE_HEIGHT, H, u + 7 * U, v)
+ drawCrate(g, labels[2]!, CRATE, CRATE_HEIGHT, H + CRATE_HEIGHT, u + 3 * U, v)
}
} else if (kind.topper === "sails" && stage.fit > 0.6) {
- // Four sails on the wall facing +x, turning with `wave`.
- const hub = at(a + U, 0, H - 8)
+ // Four lattice sails turning with `wave` on the upright plane in front of the wall facing +x.
+ const out = a + 3 * U
+ const hubZ = H - 6
+ line(g, at(a, 0, hubZ), at(out, 0, hubZ), LINE)
+ const p = upright("u", out, 0, hubZ)
for (let i = 0; i < 4; i++) {
const turn = wave * 0.6 + (i * Math.PI) / 2
- const d = { x: Math.cos(turn), y: Math.sin(turn) }
- const n = { x: -d.y, y: d.x }
- const tip = { x: hub.x + d.x * 22, y: hub.y + d.y * 22 }
- line(g, hub, tip, LINE)
- outline(g, [
- { x: hub.x + d.x * 8, y: hub.y + d.y * 8 },
- { x: tip.x, y: tip.y },
- { x: tip.x + n.x * 4, y: tip.y + n.y * 4 },
- { x: hub.x + d.x * 8 + n.x * 4, y: hub.y + d.y * 8 + n.y * 4 }
- ], DETAIL)
+ const d = { s: Math.cos(turn), t: Math.sin(turn) }
+ const n = { s: -d.t, t: d.s }
+ const along = (r: number, w: number) => p(d.s * r + n.s * w, d.t * r + n.t * w)
+ line(g, along(0, 0), along(26, 0), LINE)
+ const sail = [along(8, 0.5), along(26, 0.5), along(26, 6), along(8, 6)]
+ g.poly(flat(sail)).fill({ color: plain ? roofFill : 0xf6f1e4 }).stroke({ color: ink, width: DETAIL, join: "round" })
+ for (const r of [14, 20]) line(g, along(r, 0.5), along(r, 6), DETAIL, ink, 0.6)
+ line(g, along(8, 3.2), along(26, 3.2), DETAIL, ink, 0.4)
}
- g.circle(hub.x, hub.y, 2).fill({ color: roofFill }).stroke({ color: ink, width: DETAIL })
+ const hub = p(0, 0)
+ g.circle(hub.x, hub.y, 2.2).fill({ color: roofFill }).stroke({ color: ink, width: DETAIL })
}
}
- if (flag && stage.fit > 0.9) {
+ if (kind.topper === "flag" && stage.fit > 0.9) {
const { u, v } = flagBay(kind)
const base = at(u, v, H)
const tip = { x: base.x, y: base.y - 24 }
line(g, base, tip, LINE)
const flutter = Math.round(Math.sin(wave) * 2)
- g.poly([tip.x, tip.y, tip.x - 10, tip.y + 4 + flutter, tip.x, tip.y + 8]).fill({ color: ink })
+ g.poly([tip.x, tip.y, tip.x - 11, tip.y + 4 + flutter, tip.x, tip.y + 8])
+ .fill({ color: plain ? ink : dress.flag ?? ink }).stroke({ color: ink, width: DETAIL, join: "round" })
}
+
+ if (!plain && dress.yard && stage.fit > 0.6) dress.yard(g, a, plateHalf(kind.size), kind)
}
/** Where a building's chimney puffs from, around its footprint's centre. */
@@ -488,26 +911,30 @@ export class BuildingView extends Container {
/** A home's full height, roof included. */
export const homeHeight = (tier: Tier) => home.tiers[tier].height + HOUSE_ROOF + (tier === 2 ? 2 : 0)
-/** Roof colours homes are built with: muted terracotta, slate, thatch, and moss. */
-const homeRoofs: ReadonlyArray<RoofColors> = [
- { face: 0xe6c3b2, shade: 0xd3ab98 },
- { face: 0xc9d2da, shade: 0xb3bec8 },
- { face: 0xe4dab8, shade: 0xd1c59f },
- { face: 0xd0d9c5, shade: 0xbac5ae }
+/** Roof colours homes are built with: muted terracotta, slate, thatch, and moss; and the colour the household wears out walking. */
+const homeRoofs: ReadonlyArray<{ readonly roof: RoofColors; readonly cloth: number }> = [
+ { roof: { face: 0xe6c3b2, shade: 0xd3ab98 }, cloth: 0xb5654a },
+ { roof: { face: 0xc9d2da, shade: 0xb3bec8 }, cloth: 0x5f7896 },
+ { roof: { face: 0xe4dab8, shade: 0xd1c59f }, cloth: 0xb8954a },
+ { roof: { face: 0xd0d9c5, shade: 0xbac5ae }, cloth: 0x6e8f56 }
]
/** How a home is built, from a number 0 → 1 fixed for its cell: roof colour, which way its ridge runs, a chimney. */
export interface HomeVariant {
readonly roof: RoofColors
+ /** What its residents wear (see `residentDress`). */
+ readonly cloth: number
readonly ridge: "x" | "y"
readonly chimney: boolean
}
export const homeVariant = (n: number): HomeVariant => ({
- roof: homeRoofs[Math.floor(n * homeRoofs.length) % homeRoofs.length]!,
+ ...homeRoofs[Math.floor(n * homeRoofs.length) % homeRoofs.length]!,
ridge: Math.floor(n * 97) % 2 === 0 ? "x" : "y",
chimney: Math.floor(n * 31) % 3 !== 0
})
-const plainHome: HomeVariant = { roof: paleRoof, ridge: "x", chimney: false }
+/** The look of the home on cell (x, y). */
+export const homeAt = (x: number, y: number): HomeVariant => homeVariant(hash(x, y))
+const plainHome: HomeVariant = { roof: paleRoof, cloth: 0x8f9891, ridge: "x", chimney: false }
/**
* A home, `build` 0 → 1 of the way up: walls, a door on each wall a road
@@ -580,7 +1007,7 @@ export class HouseView extends Container {
this.position.set(centre.x, centre.y)
this.plate.position.set(centre.x, centre.y)
this.zIndex = x + y + 1
- this.variant = homeVariant(hash(x, y))
+ this.variant = homeAt(x, y)
this.drawn = ""
}
@@ -606,26 +1033,77 @@ export class HouseView extends Container {
// ── The land ──────────────────────────────────────────────────────────────
+/** Leaves in light (the side the sun is on) and shade. */
+interface Leaves {
+ readonly light: number
+ readonly shade: number
+}
+const broadLeaves: ReadonlyArray<Leaves> = [
+ { light: 0xe4ecd6, shade: 0xc6d4b2 },
+ { light: 0xdde8cf, shade: 0xbccfa8 },
+ { light: 0xe8ecd2, shade: 0xccd5ae },
+ { light: 0xdbe6d4, shade: 0xb8cbb2 },
+ { light: 0xefe7c9, shade: 0xd7c99c }
+]
+const firLeaves: Leaves = { light: 0xd9e5d7, shade: 0xb3c7b4 }
+const firLeavesDeep: Leaves = { light: 0xd3e0d3, shade: 0xa9bfab }
+
+/** A fir of `tiers` stacked cones, lit from the left, its foot at (x, y) on screen, `size` × full grown. */
+const fir = (g: Graphics, x: number, y: number, size: number, tiers: number, leaves: Leaves) => {
+ const tall = 24 * size
+ const w = 8 * size
+ const step = tall / (tiers + 1)
+ for (let i = 0; i < tiers; i++) {
+ const base = y - i * step
+ const top = base - step * 2
+ const half = w * (1 - i * 0.22)
+ const notch = base + 1.5 * size
+ g.poly([x - half, base, x, top, x, notch]).fill({ color: leaves.light })
+ g.poly([x, top, x + half, base, x, notch]).fill({ color: leaves.shade })
+ g.poly([x - half, base, x, top, x + half, base, x, notch]).stroke({ color: ink, width: LINE, join: "round" })
+ }
+}
+
+/** A round crown lobe, `r` px, shaded below and to the right. */
+const lobe = (g: Graphics, x: number, y: number, rx: number, ry: number, leaves: Leaves) => {
+ g.ellipse(x, y, rx, ry).fill({ color: leaves.shade }).stroke({ color: ink, width: LINE })
+ g.ellipse(x - rx * 0.22, y - ry * 0.24, rx * 0.7, ry * 0.68).fill({ color: leaves.light })
+}
+
/**
- * A tree, `grown` 0 → 1: a trunk and a crown, a pointed fir or a round
- * broadleaf depending on its cell. It grows in three whole-pixel steps.
+ * A tree, `grown` 0 → 1: a fir of two or three tiers, a broadleaf of one to
+ * three lobes, or a slender poplar, each a little larger or smaller, placed
+ * and tinted by its cell, with a shadow at its foot. It grows in three
+ * whole steps.
*/
export const drawTree = (g: Graphics, x: number, y: number, grown: number) => {
const h = hash(x, y)
- const size = grown >= 1 ? 1 : grown >= 0.5 ? 0.75 : 0.5
+ const h2 = hash(y * 3 + 17, x * 5 + 7)
+ const h3 = hash(x * 11 + 101, y * 13 + 3)
+ const size = (grown >= 1 ? 1 : grown >= 0.5 ? 0.75 : 0.5) * (0.85 + h2 * 0.3)
+ const ox = Math.round((h3 - 0.5) * 12)
+ const oy = Math.round((h2 - 0.5) * 5)
+ g.ellipse(ox + 3 * size, oy, 9 * size, 3.5 * size).fill({ color: ink, alpha: 0.07 })
const trunk = Math.round(6 * size)
- const ox = Math.round((h - 0.5) * 8)
- line(g, { x: ox, y: 0 }, { x: ox, y: -trunk }, LINE)
- if (h < 0.55) {
- const w = Math.round(7 * size)
- const tall = Math.round(22 * size)
- g.poly([ox - w, -trunk, ox, -trunk - tall, ox + w, -trunk]).fill({ color: leafFill }).stroke({ color: ink, width: LINE, join: "round" })
- line(g, { x: ox - Math.round(w * 0.6), y: -trunk - Math.round(tall * 0.4) }, { x: ox + Math.round(w * 0.6), y: -trunk - Math.round(tall * 0.4) }, DETAIL, ink, 0.5)
- } else {
- const r = Math.round(7 * size)
- g.circle(ox, -trunk - r, r).fill({ color: leafFill }).stroke({ color: ink, width: LINE })
- line(g, { x: ox - Math.round(r * 0.4), y: -trunk - r + 1 }, { x: ox + Math.round(r * 0.2), y: -trunk - r - Math.round(r * 0.5) }, DETAIL, ink, 0.4)
+ line(g, { x: ox, y: oy }, { x: ox, y: oy - trunk }, LINE, 0x6b5a45)
+ if (h < 0.45) {
+ fir(g, ox, oy - trunk + 2, size, h2 < 0.5 ? 2 : 3, h3 < 0.5 ? firLeaves : firLeavesDeep)
+ return
+ }
+ const leaves = broadLeaves[Math.floor(h2 * 97) % broadLeaves.length]!
+ if (h > 0.88) {
+ // A poplar: tall and narrow.
+ lobe(g, ox, oy - trunk - 10 * size, 4.5 * size, 11 * size, leaves)
+ return
}
+ const r = 7 * size
+ const cy = oy - trunk - r
+ if (size >= 0.75 && h > 0.6) {
+ lobe(g, ox - r * 0.6, cy + r * 0.25, r * 0.7, r * 0.7, leaves)
+ lobe(g, ox + r * 0.65, cy + r * 0.3, r * 0.65, r * 0.65, leaves)
+ }
+ lobe(g, ox, cy, r, r * 0.95, leaves)
+ line(g, { x: ox - r * 0.35, y: cy + r * 0.15 }, { x: ox + r * 0.05, y: cy - r * 0.3 }, DETAIL, ink, 0.35)
}
export class TreeView extends Graphics {
@@ -653,20 +1131,52 @@ export class TreeView extends Graphics {
}
}
-/** A rock: a low faceted boulder, smaller as it is quarried; an ore rock has dark flecks. */
+interface StoneFills {
+ readonly top: number
+ readonly left: number
+ readonly right: number
+}
+const stoneFills: StoneFills = { top: 0xeeefe9, left: 0xdfe1da, right: 0xcbcfc7 }
+const oreFills: StoneFills = { top: 0xe8ebf0, left: 0xd5dae3, right: 0xbcc3d0 }
+
+/** A faceted boulder `s` from its centre at (u, v), `tall` px high, its top cut in by `k` and `j` (0 → 1). */
+const boulder = (g: Graphics, u: number, v: number, s: number, tall: number, k: number, j: number, fills: StoneFills) => {
+ quad(g, [at(u - s, v + s, 0), at(u + s, v + s, 0), at(u + s, v + s * k, tall), at(u - s * j, v + s * k, tall)], fills.left)
+ quad(g, [at(u + s, v - s, 0), at(u + s, v + s, 0), at(u + s, v + s * k, tall), at(u + s * k, v - s * j, tall)], fills.right)
+ quad(g, [at(u - s * j, v - s * j, tall), at(u + s * k, v - s * j, tall), at(u + s, v + s * k, tall), at(u - s * j, v + s * k, tall)], fills.top)
+}
+
+/**
+ * A rock: one to three faceted boulders, shaped by its cell, smaller as it is
+ * quarried, with pebbles around; ore is bluish with dark flecks.
+ */
export const drawRock = (g: Graphics, x: number, y: number, ore: boolean, left: number) => {
const h = hash(x, y)
- const s = left > ROCK_AMOUNT / 2 ? 5 * U : 4 * U
- const tall = left > ROCK_AMOUNT / 2 ? 10 : 7
+ const h2 = hash(x * 7 + 3, y * 5 + 11)
+ const h3 = hash(y * 17 + 5, x * 3 + 29)
+ const full = left > ROCK_AMOUNT / 2
+ const fills = ore ? oreFills : stoneFills
+ const s = (full ? 5 : 4) * U * (0.85 + h2 * 0.3)
+ const tall = Math.round((full ? 10 : 7) * (0.8 + h3 * 0.4))
const u = (h - 0.5) * 4 * U
- quad(g, [at(u - s, s, 0), at(u + s, s, 0), at(u + s, s * 0.4, tall), at(u - s * 0.6, s * 0.4, tall)], leftFill)
- quad(g, [at(u + s, -s, 0), at(u + s, s, 0), at(u + s, s * 0.4, tall), at(u + s * 0.4, -s * 0.6, tall)], rightFill)
- quad(g, [at(u - s * 0.6, -s * 0.6, tall), at(u + s * 0.4, -s * 0.6, tall), at(u + s, s * 0.4, tall), at(u - s * 0.6, s * 0.4, tall)], roofFill)
+ const v = (h3 - 0.5) * 3 * U
+ const c = at(u, v, 0)
+ g.ellipse(c.x + 3, c.y + 1, (s / U) * 3.2, (s / U) * 1.3).fill({ color: ink, alpha: 0.06 })
+ // A smaller boulder behind, then the main one, then one in front.
+ if (h2 > 0.35) boulder(g, u - s * 0.9, v - s * 1.1, s * 0.55, Math.round(tall * 0.6), 0.3 + h * 0.3, 0.5, fills)
+ boulder(g, u, v, s, tall, 0.3 + h2 * 0.3, 0.5 + h3 * 0.2, fills)
+ if (full && h3 > 0.5) boulder(g, u + s * 0.9, v + s * 1.2, s * 0.4, Math.round(tall * 0.45), 0.4, 0.6, fills)
+ for (let i = 0; i < 3; i++) {
+ const p = at(u + (hash(x + i, y * 3) - 0.5) * 14 * U, v + s + (hash(y + i, x * 5) * 3 + 1) * U, 0)
+ g.circle(p.x, p.y, 0.9).fill({ color: ink, alpha: 0.35 })
+ }
if (ore) {
- for (const [du, dv, z] of [[-0.3, 1, 3], [0.2, 1, 6], [1, 0.1, 4]] as const) {
- const p = du === 1 ? at(u + s, dv * s, z) : at(u + du * s, s, z)
- g.rect(Math.round(p.x) - 1, Math.round(p.y) - 1, 2, 2).fill({ color: ink })
+ for (const [du, dv, z] of [[-0.3, 1, 3], [0.2, 1, 6], [1, 0.1, 4], [1, -0.5, 7]] as const) {
+ const p = du === 1 ? at(u + s, v + dv * s, z * (tall / 10)) : at(u + du * s, v + s, z * (tall / 10))
+ g.rect(Math.round(p.x) - 1, Math.round(p.y) - 1, 2, 2).fill({ color: 0x4a5368 })
}
+ const p = at(u - s * 0.2, v + s * 0.1, tall)
+ g.poly([p.x, p.y - 4, p.x + 1.5, p.y, p.x - 1.5, p.y]).fill({ color: 0x8fa3c8 }).stroke({ color: ink, width: DETAIL })
}
}
@@ -729,21 +1239,38 @@ export class FieldView extends Graphics {
}
}
-/** Water on a set of cells (by `key`): pale fill, an ink shoreline where it meets land, and a few ripples. */
+/**
+ * Water on a set of cells (by `key`): paler in the shallows and deeper away
+ * from the shore, an ink shoreline where it meets land, and ripples and
+ * glints scattered by cell.
+ */
export const drawWater = (g: Graphics, cells: ReadonlySet<number>) => {
+ const wet = (x: number, y: number) => cells.has(key(x, y))
for (const k of cells) {
const c = cellOf(k)
- g.poly(flat([toScreen(c.x, c.y), toScreen(c.x + 1, c.y), toScreen(c.x + 1, c.y + 1), toScreen(c.x, c.y + 1)])).fill({ color: waterFill })
+ const near = DIRS.every((d) => wet(c.x + d.x, c.y + d.y))
+ const far = near && DIRS.every((d) => wet(c.x + 2 * d.x, c.y + 2 * d.y) && wet(c.x + d.x + d.y, c.y + d.y - d.x))
+ const fill = far ? 0xdae5e2 : near ? 0xdee8e5 : 0xe2ebe8
+ g.poly(flat([toScreen(c.x, c.y), toScreen(c.x + 1, c.y), toScreen(c.x + 1, c.y + 1), toScreen(c.x, c.y + 1)])).fill({ color: fill })
}
for (const k of cells) {
const c = cellOf(k)
- if (hash(c.x, c.y) < 0.3) {
- const a = toScreen(c.x + 0.3, c.y + 0.5)
- const b = toScreen(c.x + 0.6, c.y + 0.5)
- g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ const h = hash(c.x, c.y)
+ const waves = h < 0.22 ? 1 : h < 0.34 ? 2 : 0
+ for (let i = 0; i < waves; i++) {
+ const p = toScreen(c.x + 0.2 + hash(c.x + i * 7, c.y * 3) * 0.6, c.y + 0.2 + hash(c.y + i * 5, c.x * 7) * 0.6)
+ const w = 3 + Math.round(hash(c.x * 3 + i, c.y) * 2)
+ g.moveTo(p.x - 2 * w, p.y).quadraticCurveTo(p.x - w, p.y - 2, p.x, p.y).quadraticCurveTo(p.x + w, p.y - 2, p.x + 2 * w, p.y)
}
}
- g.stroke({ color: 0x9fb3b0, width: DETAIL })
+ g.stroke({ color: 0x9fb3b0, width: DETAIL, cap: "round" })
+ for (const k of cells) {
+ const c = cellOf(k)
+ if (hash(c.y * 13 + 1, c.x * 31 + 7) > 0.08) continue
+ const p = toScreen(c.x + 0.5, c.y + 0.5)
+ g.moveTo(p.x - 2.5, p.y).lineTo(p.x + 2.5, p.y).moveTo(p.x, p.y - 1.5).lineTo(p.x, p.y + 1.5)
+ }
+ g.stroke({ color: 0xffffff, width: DETAIL, alpha: 0.9 })
for (const k of cells) {
const c = cellOf(k)
const edges: ReadonlyArray<readonly [Point, Point, Point]> = [
@@ -772,29 +1299,42 @@ export const drawWater = (g: Graphics, cells: ReadonlySet<number>) => {
* centre with an arm to every neighbour that is road too, kerbs along the
* outside, and a dashed line down the middle of each arm. Arms meet their
* neighbours' at the cell edge, so a run of road reads as one strip with
- * square joints.
+ * square joints. The paving's tone, and the odd worn stone in it, vary by cell.
*/
export const drawRoads = (g: Graphics, cells: ReadonlySet<number>, alpha = 1, kerb = ink) => {
const w = ROAD
const edge = 8 * U
const kerbs: Array<readonly [Point, Point]> = []
const dashes: Array<readonly [Point, Point]> = []
+ const stones: Array<readonly [Point, Point]> = []
for (const k of cells) {
const c = cellOf(k)
const cx = c.x + 0.5
const cy = c.y + 0.5
const p = (u: number, v: number) => toScreen(cx + u, cy + v)
- g.poly(flat([p(-w, -w), p(w, -w), p(w, w), p(-w, w)])).fill({ color: roadFill, alpha })
+ const h = hash(c.x, c.y)
+ const fill = alpha < 1 ? roadFill : h < 0.3 ? 0xe2e4dd : h > 0.85 ? 0xe9eae4 : roadFill
+ g.poly(flat([p(-w, -w), p(w, -w), p(w, w), p(-w, w)])).fill({ color: fill, alpha })
for (const d of DIRS) {
const n = { x: -d.y, y: d.x }
const q = (along: number, across: number) => p(d.x * along + n.x * across, d.y * along + n.y * across)
if (cells.has(key(c.x + d.x, c.y + d.y))) {
- g.poly(flat([q(w, -w), q(edge, -w), q(edge, w), q(w, w)])).fill({ color: roadFill, alpha })
+ g.poly(flat([q(w, -w), q(edge, -w), q(edge, w), q(w, w)])).fill({ color: fill, alpha })
kerbs.push([q(w, -w), q(edge, -w)], [q(w, w), q(edge, w)])
dashes.push([q(U, 0), q(3 * U, 0)], [q(5 * U, 0), q(7 * U, 0)])
} else kerbs.push([q(w, -w), q(w, w)])
}
+ if (alpha === 1 && hash(c.y * 7 + 3, c.x * 11 + 5) < 0.55) {
+ // A worn paving stone or two: a short tick off the middle line.
+ for (let i = 0; i < 2; i++) {
+ const su = (hash(c.x + i * 13, c.y) < 0.5 ? -1 : 1) * (2.5 + hash(c.x, c.y + i * 13) * 2) * U
+ const sv = (hash(c.y + i * 7, c.x) < 0.5 ? -1 : 1) * (2.5 + hash(c.y, c.x + i * 7) * 2) * U
+ stones.push(i === 0 ? [p(su, sv), p(su + U, sv)] : [p(su, sv), p(su, sv + U)])
+ }
+ }
}
+ for (const [a, b] of stones) g.moveTo(a.x, a.y).lineTo(b.x, b.y)
+ g.stroke({ color: marking, width: DETAIL, alpha: 0.8 })
for (const [a, b] of dashes) g.moveTo(a.x, a.y).lineTo(b.x, b.y)
g.stroke({ color: marking, width: DETAIL, alpha })
for (const [a, b] of kerbs) g.moveTo(a.x, a.y).lineTo(b.x, b.y)
@@ -817,66 +1357,337 @@ export const drawCrate = (g: Graphics, label: number, s = CRATE, h = CRATE_HEIGH
g.poly(flat([at(u - s + U, v + s, lz), at(u + s - U, v + s, lz), at(u + s - U, v + s, lz + lh), at(u - s + U, v + s, lz + lh)])).fill({ color: label })
}
+/** What a figure wears: coat, the trim on its hat, skin, a hat, and whether the coat is long (a citizen's, a cleric's robe). */
+export interface PersonDress {
+ readonly coat: number
+ readonly trim: number
+ readonly skin: number
+ readonly hat: "none" | "cap" | "brim" | "top" | "hood" | "bonnet"
+ readonly long: boolean
+}
+
+/** What a figure has with it. */
+export type Load =
+ | { readonly kind: "none" }
+ /** A carrier's cart: `good` on it, `count` of it (none on the way back). */
+ | { readonly kind: "cart"; readonly good: GoodId; readonly count: number }
+ /** A market walker's basket of provisions. */
+ | { readonly kind: "basket"; readonly goods: ReadonlyArray<GoodId> }
+ /** A chapel walker's bell. */
+ | { readonly kind: "bell" }
+
+/** How a cart is built: one wheel at the front (a barrow) or two at the sides, its wood, spoked wheels or solid. */
+export interface CartLook {
+ readonly wheels: 1 | 2
+ readonly wood: { readonly top: number; readonly left: number; readonly right: number }
+ readonly spokes: boolean
+}
+
+const skins = [0xf3dfcb, 0xe8c7a6, 0xd3a681, 0xae8160, 0x8d644a] as const
+const workCoats = [0x8a6a45, 0x6e8f36, 0x5a6479, 0xb5654a, 0x7d8f9b, 0x9a7b56, 0x587a6e] as const
+const cartWoods = [
+ { top: 0xc79a5b, left: 0xe9c48a, right: 0xd5a86c },
+ { top: 0xa98457, left: 0xd2b088, right: 0xbd9871 },
+ { top: 0x8fa37c, left: 0xc3d1b2, right: 0xaebf9c },
+ { top: 0x8a9bb8, left: 0xc4cfe0, right: 0xadbbd1 },
+ { top: 0xb87a68, left: 0xe2b4a6, right: 0xcf9c8d }
+] as const
+
+const pick = <T>(list: ReadonlyArray<T>, n: number): T => list[Math.floor(n * 9973) % list.length]!
+
+/** A carrier: work clothes and a cap, pushing a cart built by `n` (0 → 1). */
+export const carrierDress = (n: number): PersonDress => ({
+ coat: pick(workCoats, n), trim: pick(workCoats, n * 7 + 0.3), skin: pick(skins, n * 13 + 0.1), hat: n < 0.6 ? "cap" : n < 0.8 ? "brim" : "none", long: false
+})
+export const cartLook = (n: number): CartLook => ({ wheels: n < 0.3 ? 1 : 2, wood: pick(cartWoods, n * 3 + 0.2), spokes: n * 17 % 1 < 0.6 })
+/** A service walker in its building's colour: a market's with a cap, a chapel's in a hooded robe. */
+export const serviceDress = (color: number, n: number, faith: boolean): PersonDress => ({
+ coat: faith ? mix(color, ink, 0.35) : color, trim: faith ? color : 0xf7f8f4, skin: pick(skins, n * 13 + 0.1), hat: faith ? "hood" : "cap", long: faith
+})
/**
- * A walker: a small pale figure on two stepping legs, facing `dir` (a grid
- * step). A service walker's head is in its building's colour, and a
- * provisions walker carries a basket at its side. A carrier's head is pale;
- * it pushes a handcart ahead of it, with a crate labelled with its good on
- * the way out.
+ * A resident out for a walk, dressed in their household's colour (see
+ * `HomeVariant`): settlers plainly, in caps and bonnets; citizens in long
+ * deeper-coloured coats and hats.
*/
-export const drawWalker = (g: Graphics, role: "carrier" | "walker", color: number, cargo: boolean, dir: Point, phase: number) => {
+export const residentDress = (cloth: number, tier: Tier, n: number): PersonDress => ({
+ coat: tier === 2 ? mix(cloth, ink, 0.2) : mix(cloth, 0xffffff, 0.15),
+ trim: tier === 2 ? ink : mix(cloth, 0xffffff, 0.55),
+ skin: pick(skins, n * 13 + 0.1),
+ hat: tier === 2 ? (n < 0.5 ? "top" : "brim") : n < 0.35 ? "bonnet" : n < 0.6 ? "cap" : "none",
+ long: tier === 2 || n > 0.85
+})
+
+/** Where a point on a cart is: `a` along the way it goes, `c` across it, from the cart's centre (u, v). */
+const cartPoint = (u: number, v: number, d: Point) => (a: number, c: number, z: number) => at(u + d.x * a - d.y * c, v + d.y * a + d.x * c, z)
+
+/** A box on a cart, `ha` along and `hc` across from (a, c). */
+const cartBox = (g: Graphics, u: number, v: number, d: Point, a: number, c: number, ha: number, hc: number, z: number, h: number, fills: { readonly top: number; readonly left: number; readonly right: number }, width = DETAIL) => {
+ const cu = u + d.x * a - d.y * c
+ const cv = v + d.y * a + d.x * c
+ const along = d.x !== 0
+ box(g, cu, cv, along ? ha : hc, along ? hc : ha, z, h, fills.top, fills.left, fills.right, width)
+}
+
+/** A log (or a sheaf, a bolt of cloth) lying along a cart, `c` across it. */
+const cartLog = (g: Graphics, u: number, v: number, d: Point, c: number, half: number, z: number, r: number, side: number, end: number) => {
+ if (d.x !== 0) log(g, "u", v + d.x * c, u - half, u + half, z, r, side, end)
+ else log(g, "v", u - d.y * c, v - half, v + half, z, r, side, end)
+}
+
+const wicker = { top: 0xc9a46a, left: 0xe3c592, right: 0xd2b07a }
+
+/** What is on a cart, `z` px up: each good its own way, more of it for a bigger load. */
+const drawCargo = (g: Graphics, u: number, v: number, d: Point, good: GoodId, count: number, z: number) => {
+ const n = count >= 4 ? 3 : count >= 2 ? 2 : 1
+ const p = cartPoint(u, v, d)
+ switch (good) {
+ case "wood": {
+ const rows: ReadonlyArray<ReadonlyArray<number>> = [[-0.9, 0, 0.9], [-0.45, 0.45], [0]]
+ rows.slice(0, n).forEach((row, i) => row.forEach((c) => cartLog(g, u, v, d, c * U, 2.2 * U, z + i * 2, 1.15, 0xb08a5e, 0xe9d2a8)))
+ return
+ }
+ case "wheat":
+ case "cloth":
+ case "wool": {
+ const fills = good === "wheat" ? [0xe9cf7c, 0xf3e3a8] : good === "cloth" ? [0x8a58a8, 0xc7aed6] : [0xf4f4ef, 0xffffff]
+ const rows: ReadonlyArray<ReadonlyArray<number>> = [[-0.75, 0.75], [0]]
+ rows.slice(0, Math.min(2, n)).forEach((row, i) => row.forEach((c, j) => {
+ const side = good === "cloth" && j === 1 ? 0x3d6db5 : fills[0]!
+ cartLog(g, u, v, d, c * U, (good === "wool" ? 1.4 : 2) * U, z + i * 2.6, good === "wool" ? 1.9 : 1.5, side, fills[1]!)
+ }))
+ if (n === 3 && good !== "wool") cartLog(g, u, v, d, 0, 1.4 * U, z + 5, 1.3, fills[0]!, fills[1]!)
+ return
+ }
+ case "planks": {
+ for (let i = 0; i < n + 1; i++) cartBox(g, u, v, d, 0, 0, 2.4 * U, 1.1 * U, z + i * 1.5, 1.5, { top: 0xf0c59a, left: 0xe2a873, right: 0xd2945c })
+ return
+ }
+ case "stone":
+ case "ore": {
+ const fills = good === "stone" ? stoneFills : oreFills
+ const spots: ReadonlyArray<readonly [number, number, number]> = [[-1, -0.5, 0], [1, 0.5, 0], [0, 0, 3]]
+ for (const [a, c, dz] of spots.slice(0, n)) cartBox(g, u, v, d, a * U, c * U, 0.8 * U, 0.8 * U, z + dz, 3, fills)
+ if (good === "ore") {
+ const top = p(0, 0, z + (n >= 3 ? 6 : 3))
+ g.circle(top.x - 1, top.y, 1).fill({ color: 0x4a5368 })
+ g.circle(top.x + 1.5, top.y + 0.5, 0.8).fill({ color: 0x4a5368 })
+ }
+ return
+ }
+ case "fish":
+ case "bread": {
+ cartBox(g, u, v, d, 0, 0, 1.6 * U, 1.1 * U, z, 3, wicker)
+ for (let i = 0; i < n + 1; i++) {
+ const t = p(((i - n / 2) * 0.9) * U, (i % 2 === 0 ? -0.3 : 0.3) * U, z + 3)
+ if (good === "fish") g.poly([t.x - 2.2, t.y, t.x, t.y - 1.4, t.x + 2.2, t.y, t.x, t.y + 1.2]).fill({ color: 0x2f8c87 }).stroke({ color: ink, width: 0.75 })
+ else g.ellipse(t.x, t.y - 0.6, 1.8, 1.2).fill({ color: 0xd98a6a }).stroke({ color: ink, width: 0.75 })
+ }
+ return
+ }
+ case "flour": {
+ const spots = [-1, 1, 0]
+ spots.slice(0, n).forEach((a, i) => sack(g, u + d.x * a * U, v + d.y * a * U, 0xf2ecdc, z + (i === 2 ? 4 : 0)))
+ return
+ }
+ default: {
+ drawCrate(g, goods[good].color, 1.6 * U, 4, z, u, v)
+ if (good === "tools") {
+ const t = p(0, 0, z + 4)
+ line(g, t, { x: t.x + 2, y: t.y - 5 }, LINE, 0x8a6a45)
+ g.rect(t.x + 0.5, t.y - 6.5, 3, 1.6).fill({ color: 0x8f9891 }).stroke({ color: ink, width: 0.75 })
+ }
+ }
+ }
+}
+
+/** A wheel `r` px across, upright along the way the cart goes, its spokes turned by `roll`. */
+const wheel = (g: Graphics, u: number, v: number, d: Point, r: number, roll: number, look: CartLook) => {
+ const axis = d.x !== 0 ? "v" : "u"
+ g.poly(flat(ring(axis, u, v, r, r, 14))).fill({ color: look.spokes ? 0xf2efe6 : look.wood.right }).stroke({ color: ink, width: DETAIL })
+ const p = upright(axis, u, v, r)
+ if (look.spokes) {
+ for (let k = 0; k < 2; k++) {
+ const t = roll + (k * Math.PI) / 2
+ line(g, p(Math.cos(t) * r, Math.sin(t) * r), p(-Math.cos(t) * r, -Math.sin(t) * r), 0.75)
+ }
+ }
+ const hub = p(0, 0)
+ g.circle(hub.x, hub.y, 0.8).fill({ color: ink })
+}
+
+/** A handcart or barrow ahead of a carrier, with its load. */
+const drawCart = (g: Graphics, look: CartLook, load: Load, d: Point, roll: number) => {
+ const u = d.x * CART_AHEAD
+ const v = d.y * CART_AHEAD
+ const p = cartPoint(u, v, d)
+ const L = 2.4 * U
+ const W = 1.6 * U
+ const bed = 5
+ // The near side is the one towards the viewer: +u or +v.
+ const nearSide = d.x !== 0 ? (d.x > 0 ? 1 : -1) : d.y > 0 ? -1 : 1
+ const wheelAt = (c: number) => ({ u: u - d.y * c, v: v + d.x * c })
+ const drawWheel = (c: number, a = 0) => {
+ const w = wheelAt(c)
+ wheel(g, w.u + d.x * a, w.v + d.y * a, d, 2.6, roll, look)
+ }
+ const frontAway = toScreen(d.x, d.y).y < 0
+ if (look.wheels === 2) drawWheel(-nearSide * (W + 0.4 * U))
+ else if (frontAway) drawWheel(0, L + 0.5 * U)
+ // Legs under a barrow's back, then the bed and its sides.
+ if (look.wheels === 1) for (const c of [-W * 0.6, W * 0.6]) line(g, p(-L + U, c, 0), p(-L + U, c, bed - 1), DETAIL)
+ cartBox(g, u, v, d, 0, 0, L, W, bed - 2, 2.5, look.wood, DETAIL)
+ if (load.kind === "cart" && load.count > 0) drawCargo(g, u, v, d, load.good, load.count, bed + 0.5)
+ if (look.wheels === 2) drawWheel(nearSide * (W + 0.4 * U))
+ else if (!frontAway) drawWheel(0, L + 0.5 * U)
+}
+
+/** A hat on a head at (0, y). */
+const drawHat = (g: Graphics, dress: PersonDress, y: number, facing: number) => {
+ switch (dress.hat) {
+ case "cap":
+ g.poly([-2.4, y + 0.2, -2.2, y - 1.4, -1, y - 2.4, 1, y - 2.4, 2.2, y - 1.4, 2.4, y + 0.2]).fill({ color: dress.trim === 0xf7f8f4 ? dress.coat : dress.trim }).stroke({ color: ink, width: 0.75 })
+ line(g, { x: 0, y: y + 0.1 }, { x: facing * 3.4, y: y + 0.4 }, 1, ink)
+ return
+ case "brim":
+ g.roundRect(-1.8, y - 3.4, 3.6, 3, 1).fill({ color: dress.trim }).stroke({ color: ink, width: 0.75 })
+ g.ellipse(0, y, 3.6, 1).fill({ color: dress.trim }).stroke({ color: ink, width: 0.75 })
+ return
+ case "top":
+ g.rect(-1.7, y - 4.6, 3.4, 4.4).fill({ color: ink })
+ g.rect(-1.7, y - 1.6, 3.4, 0.8).fill({ color: dress.coat })
+ line(g, { x: -3, y: y - 0.1 }, { x: 3, y: y - 0.1 }, 1.2)
+ return
+ case "bonnet":
+ g.poly([-2.8, y + 1.6, -2.6, y - 1.2, -1, y - 2.6, 1.4, y - 2.4, 2.8, y - 0.6, facing * 2.8, y + 1.6]).fill({ color: dress.trim }).stroke({ color: ink, width: 0.75 })
+ return
+ case "hood":
+ g.poly([-2.9, y + 3.2, -2.9, y - 0.6, -1.4, y - 2.8, 1.4, y - 2.8, 2.9, y - 0.6, 2.9, y + 3.2]).fill({ color: dress.coat }).stroke({ color: ink, width: 0.75 })
+ g.circle(facing * 0.6, y + 0.6, 1.5).fill({ color: dress.skin })
+ return
+ default:
+ }
+}
+
+/**
+ * A figure on two stepping legs, facing `dir` (a grid step), dressed in
+ * `dress`, with what it has with it: a cart ahead of it (`cart`), a basket at
+ * its side, or a bell. `roll` turns a cart's wheels.
+ */
+export const drawWalker = (g: Graphics, dress: PersonDress, load: Load, cart: CartLook | null, dir: Point, phase: number, roll = 0, part: "all" | "figure" | "cart" = "all") => {
const d = dir.x === 0 && dir.y === 0 ? { x: 1, y: 0 } : dir
- const ahead = { u: d.x * 5 * U, v: d.y * 5 * U }
- const front = toScreen(ahead.u, ahead.v)
+ const front = toScreen(d.x * 5 * U, d.y * 5 * U)
+ const facing = front.x >= 0 ? 1 : -1
+ const away = front.y < 0
const figure = () => {
const swing = phase === 0 ? 1 : -1
+ g.ellipse(0.5, 0, 3.2, 1.1).fill({ color: ink, alpha: 0.1 })
line(g, { x: -1, y: -5 }, { x: -1 + swing, y: 0 }, DETAIL)
line(g, { x: 1, y: -5 }, { x: 1 - swing, y: 0 }, DETAIL)
- g.roundRect(-2.5, -11, 5, 7, 2).fill({ color: plateFill }).stroke({ color: ink, width: DETAIL })
- g.circle(0, -13.5, 2.2).fill({ color: role === "walker" ? color : plateFill }).stroke({ color: ink, width: DETAIL })
- if (role === "walker" && cargo) {
- const side = front.x >= 0 ? -1 : 1
- g.rect(side * 4 - 1.5, -8, 3, 3).fill({ color: 0xe9c48a }).stroke({ color: 0x7d6140, width: DETAIL })
- }
- }
- const cart = () => {
- // Handles from the walker's hands to the cart, a wheel, and the bed or the crate on it.
- line(g, { x: front.x * 0.3, y: front.y * 0.3 - 7 }, { x: front.x * 0.7, y: front.y * 0.7 - 4 }, DETAIL)
- g.circle(front.x, front.y - 1, 1.5).fill({ color: ink })
- if (cargo) drawCrate(g, color, 2 * U, 5, 2, ahead.u, ahead.v)
- else quad(g, square(ahead.u, ahead.v, 2 * U, 2), roofFill)
- }
- if (role === "carrier" && front.y < 0) {
- cart()
+ if (dress.long) g.poly([-2.6, -10.5, 2.6, -10.5, 3.2, -3, -3.2, -3]).fill({ color: dress.coat }).stroke({ color: ink, width: DETAIL, join: "round" })
+ else g.roundRect(-2.5, -11, 5, 7, 2).fill({ color: dress.coat }).stroke({ color: ink, width: DETAIL })
+ // An arm swinging, unless both hands are on a cart.
+ if (!cart) line(g, { x: -facing * 1.8, y: -9.5 }, { x: -facing * 1.8 + swing * 1.2, y: -6 }, DETAIL)
+ g.circle(0, -13.5, 2.2).fill({ color: dress.skin }).stroke({ color: ink, width: DETAIL })
+ if (away && dress.hat !== "hood") g.circle(0, -13.8, 1.9).fill({ color: mix(dress.skin, ink, 0.55) })
+ drawHat(g, dress, -15, facing)
+ if (load.kind === "basket") {
+ const side = -facing
+ const bx = side * 4.5
+ g.poly([bx - 2.2, -8.5, bx + 2.2, -8.5, bx + 1.6, -5, bx - 1.6, -5]).fill({ color: wicker.left }).stroke({ color: ink, width: DETAIL })
+ g.moveTo(bx - 1.8, -8.5).quadraticCurveTo(bx, -12, bx + 1.8, -8.5).stroke({ color: ink, width: 0.75 })
+ load.goods.slice(0, 3).forEach((good, i) => g.circle(bx - 1.2 + i * 1.2, -9, 0.9).fill({ color: goods[good].color }))
+ } else if (load.kind === "bell") {
+ const bx = facing * 3.6
+ line(g, { x: facing * 1.8, y: -9 }, { x: bx, y: -7.5 }, DETAIL)
+ g.poly([bx - 1.3, -5, bx - 0.8, -7.5, bx + 0.8, -7.5, bx + 1.3, -5]).fill({ color: 0xe3c25a }).stroke({ color: ink, width: 0.75 })
+ }
+ }
+ if (!cart || part === "figure") return figure()
+ const handles = () => {
+ const ahead = { x: front.x * 0.62, y: front.y * 0.62 }
+ line(g, { x: front.x * 0.2, y: front.y * 0.2 - 7 }, { x: ahead.x, y: ahead.y - 4 }, DETAIL)
+ }
+ if (part === "cart") {
+ handles()
+ drawCart(g, cart, load, d, roll)
+ return
+ }
+ if (away) {
+ drawCart(g, cart, load, d, roll)
+ handles()
figure()
} else {
figure()
- if (role === "carrier") cart()
+ handles()
+ drawCart(g, cart, load, d, roll)
}
}
+const loadKey = (load: Load) =>
+ load.kind === "cart" ? `${load.good}${load.count}` : load.kind === "basket" ? load.goods.join(",") : load.kind
+
+let walkers = 0
+
+/** How far ahead of its pusher a cart stands, in cells. */
+const CART_AHEAD = 5.5 * U
+
+/**
+ * A figure as drawn, redrawn when its stride, heading, load, or wheels
+ * change. A carrier's cart is drawn apart from it and sorted on its own
+ * place on the road, so figures meeting or passing it overlap the right way.
+ */
export class WalkerView extends Graphics {
- private readonly role: "carrier" | "walker"
- private readonly color: number
+ private readonly dress: PersonDress
+ private readonly cart: CartLook | null
+ private readonly cartView: Graphics | null
+ private faithDress: PersonDress | null = null
private drawn = ""
- constructor(role: "carrier" | "walker", color: number) {
+ constructor(dress: PersonDress, cart: CartLook | null) {
super()
- this.role = role
- this.color = color
+ this.dress = dress
+ this.cart = cart
+ this.cartView = cart ? new Graphics() : null
}
- /** Puts it on the floor at grid point (x, y), facing `dir`, redrawing when its stride, heading, or load changes. */
- update(x: number, y: number, dir: Point, phase: number, cargo: boolean) {
- const key = `${dir.x},${dir.y}|${phase}|${cargo}`
+ /** A walker the town sent out: a carrier with a cart, or a service walker in its building's colour. */
+ static forFigure(role: "carrier" | "walker", color: number): WalkerView {
+ const n = hash(walkers++, 7)
+ if (role === "carrier") return new WalkerView(carrierDress(n), cartLook(hash(walkers, 31)))
+ const view = new WalkerView(serviceDress(color, n, false), null)
+ view.faithDress = serviceDress(color, n, true)
+ return view
+ }
+
+ /** Puts it on the floor at grid point (x, y), facing `dir`. */
+ update(x: number, y: number, dir: Point, phase: number, load: Load) {
+ const roll = this.cart ? Math.round((x + y) * 6) % 3 : 0
+ const key = `${dir.x},${dir.y}|${phase}|${loadKey(load)}|${roll}`
+ const dress = load.kind === "bell" && this.faithDress ? this.faithDress : this.dress
if (key !== this.drawn) {
this.drawn = key
this.clear()
- drawWalker(this, this.role, this.color, cargo, dir, phase)
+ drawWalker(this, dress, load, this.cart, dir, phase, 0, "figure")
+ if (this.cartView) {
+ this.cartView.clear()
+ drawWalker(this.cartView, dress, load, this.cart, dir, phase, (roll * Math.PI) / 6, "cart")
+ }
}
const s = toScreen(x, y)
this.position.set(s.x, s.y)
this.zIndex = x + y
+ if (this.cartView) {
+ if (this.cartView.parent !== this.parent) this.parent?.addChild(this.cartView)
+ const d = dir.x === 0 && dir.y === 0 ? { x: 1, y: 0 } : dir
+ this.cartView.position.set(s.x, s.y)
+ this.cartView.zIndex = x + y + (d.x + d.y) * CART_AHEAD
+ this.cartView.alpha = this.alpha
+ }
+ }
+
+ override destroy(options?: Parameters<Graphics["destroy"]>[0]) {
+ this.cartView?.destroy()
+ super.destroy(options)
}
}
@@ -967,6 +1778,6 @@ export const drawGhost = (g: Graphics, what: KindId | "home", x: number, y: numb
const centre = toScreen(x + size / 2, y + size / 2)
g.translateTransform(centre.x, centre.y)
if (what === "home") drawHouse(g, 1, 1, { right: false, left: false })
- else drawBuilding(g, kinds[what], 1, 0, 0, { right: false, left: false }, 0xb9beb5)
+ else drawBuilding(g, kinds[what], 1, 0, 0, { right: false, left: false }, true)
g.resetTransform()
}
diff --git a/src/factory.css b/src/factory.css
index 9351218..95e1248 100644
--- a/src/factory.css
+++ b/src/factory.css
@@ -3,106 +3,169 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
#app { position: fixed; inset: 0; }
#app canvas { display: block; }
-.hud { position: fixed; top: 12px; left: 16px; display: flex; flex-direction: column; align-items: flex-start; gap: 6px; font-size: 12px; cursor: pointer; max-width: calc(100vw - 32px); }
+.icon { display: block; flex: none; }
+.glyph { display: inline-flex; align-items: center; justify-content: center; flex: none; }
+.glyph .swatch { width: 10px; height: 10px; display: inline-block; }
+
+/* ── The top bar: the term and the treasury on the left, the people on the right ── */
+.hud { position: fixed; top: 12px; display: flex; flex-direction: column; gap: 8px; font-size: 12px; max-width: calc(50vw - 24px); z-index: 2; }
+.hud.left { left: 16px; align-items: flex-start; }
+.hud.right { right: 16px; align-items: flex-end; cursor: pointer; transition: right 240ms cubic-bezier(.2,.8,.2,1); }
+.panel-open .hud.right { right: 376px; }
.card {
- display: flex; align-items: stretch; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 6px;
+ display: flex; align-items: stretch; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px;
box-shadow: 0 2px 0 #dfe2db; overflow: hidden;
}
-.card .cell { display: flex; align-items: center; gap: 12px; padding: 6px 12px; white-space: nowrap; }
-.card .cell + .cell { border-left: 1px solid #d5d9d0; }
-.hud .bar { font-size: 13px; }
-.hud .coins b { font-size: 15px; font-weight: 700; }
+.card .cell { display: flex; align-items: center; gap: 10px; padding: 7px 14px; white-space: nowrap; }
+.card .cell + .cell { border-left: 1px solid #e0e3db; }
+.hud .stack { display: flex; flex-direction: column; line-height: 1.2; }
+.hud .stack b { font-size: 15px; font-weight: 700; }
+.hud .stack small { font-size: 11px; color: #77817a; }
+.hud .stack .of { font-weight: 400; color: #8a938c; font-size: 12px; }
+.hud .coins b { font-size: 17px; }
.hud .coins.debt b { color: #b04a39; }
.hud .up { color: #4f8a3e; }
.hud .down { color: #b04a39; }
-.hud .stock { color: #3d4943; flex-wrap: wrap; }
-.hud .good { display: inline-flex; align-items: center; gap: 5px; }
-.hud .good .label { width: 8px; height: 8px; display: inline-block; }
-.hud .good .count { min-width: 2ch; font-weight: 600; }
+.hud .muted { color: #8a938c; }
+.hud.right .card:hover { border-color: #3d4943; }
-.toolbar {
- position: fixed; left: 16px; bottom: calc(14px + env(safe-area-inset-bottom));
- display: flex; gap: 6px; padding: 6px; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 6px;
- box-shadow: 0 2px 0 #dfe2db; max-width: calc(100vw - 24px); overflow-x: auto;
-}
-.toolbar button {
+/* The goods in stock: each in a chip of its own, in groups. */
+.hud .stock { gap: 0; padding: 5px; }
+.hud .stock .group { display: flex; gap: 4px; padding: 0 5px; }
+.hud .stock .group + .group { border-left: 1px solid #e0e3db; }
+.hud .good { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px 4px 6px; background: #eef0ea; border-radius: 6px; cursor: default; }
+.hud .good .count { min-width: 2.5ch; font-weight: 700; font-size: 13px; }
+.hud .good.empty { opacity: 0.55; }
+
+/* ── The toolbar: the town's panel, the tools, the speed ── */
+.toolbar, .system {
+ position: fixed; bottom: calc(14px + env(safe-area-inset-bottom)); display: flex; align-items: stretch; gap: 8px; z-index: 2;
+}
+.toolbar { left: 16px; max-width: calc(100vw - 32px); overflow-x: auto; }
+.system { right: 16px; transition: right 240ms cubic-bezier(.2,.8,.2,1); }
+.panel-open .system { right: 376px; }
+.panel-open .system button { font-size: 0; gap: 0; padding: 6px 8px; }
+.toolbar .group, .system {
+ display: flex; gap: 4px; padding: 5px; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px; box-shadow: 0 2px 0 #dfe2db;
+}
+.toolbar button, .system button {
font: inherit; font-size: 12px; color: #3d4943; background: transparent; border: 1px solid transparent;
- border-radius: 4px; padding: 6px 10px; display: flex; align-items: center; gap: 7px; cursor: pointer; white-space: nowrap;
+ border-radius: 5px; padding: 6px 10px; display: flex; align-items: center; gap: 7px; cursor: pointer; white-space: nowrap;
}
-.toolbar button:hover { background: #eceee8; }
+.toolbar button:hover, .system button:hover { background: #eceee8; }
.toolbar button.on { background: #3d4943; color: #f7f8f4; }
-.toolbar button .swatch { width: 9px; height: 9px; border: 1px solid currentColor; display: inline-block; }
+.toolbar button.on .glyph { background: #f7f8f4; border-radius: 4px; padding: 1px; margin: -1px; }
.toolbar button kbd { font: inherit; font-size: 10px; opacity: 0.55; }
-.toolbar .sep { width: 1px; background: #d5d9d0; margin: 3px 2px; }
+.toolbar .pause { padding: 6px 9px; }
+.toolbar .pause.on .glyph { background: none; }
+.system button { color: #5d6861; }
+.toolbar .town-button {
+ padding: 8px 18px 8px 12px; gap: 10px; font-size: 14px; font-weight: 700; letter-spacing: 0.02em;
+ background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px; box-shadow: 0 2px 0 #dfe2db;
+}
+.toolbar .town-button:hover { background: #eceee8; border-color: #3d4943; }
+.toolbar .town-button.on { background: #3d4943; color: #f7f8f4; border-color: #3d4943; }
+.toolbar .town-button.on .glyph { background: #f7f8f4; border-radius: 5px; padding: 2px; margin: -2px; }
.tooltip {
position: fixed; pointer-events: none; background: #2f4639; color: #f3f5ef; font-size: 13px;
- padding: 5px 10px; border-radius: 2px; white-space: pre; transform: translate(14px, 10px); display: none;
+ padding: 5px 10px; border-radius: 3px; white-space: pre; transform: translate(14px, 10px); display: none; z-index: 20;
}
.toast {
- position: fixed; bottom: calc(68px + env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); background: #3d4943; color: #f7f8f4;
- font-size: 12px; padding: 6px 12px; border-radius: 3px; opacity: 0; transition: opacity 160ms ease; pointer-events: none;
+ position: fixed; bottom: calc(76px + env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); background: #3d4943; color: #f7f8f4;
+ font-size: 12px; padding: 7px 14px; border-radius: 4px; opacity: 0; transition: opacity 160ms ease; pointer-events: none; z-index: 20;
}
.toast.show { opacity: 1; }
+@media (max-width: 1260px) {
+ .system button { font-size: 0; gap: 0; padding: 6px 8px; }
+}
+@media (max-width: 1000px) {
+ .toolbar button kbd, .toolbar .town-button kbd { display: none; }
+ .hud .stack small { display: none; }
+}
.panel {
position: fixed; top: 0; right: 0; bottom: 0; width: 360px; max-width: 46vw; box-sizing: border-box;
- background: #f1f3ed; border-left: 1px solid #c3c8bf; padding: 22px 24px calc(24px + env(safe-area-inset-bottom));
+ background: #eef0ea; border-left: 1px solid #c3c8bf; padding: 18px 16px calc(24px + env(safe-area-inset-bottom));
overflow-y: auto; transform: translateX(100%); transition: transform 240ms cubic-bezier(.2,.8,.2,1);
- font-size: 14px; color: #3d4943; -webkit-user-select: none; user-select: none;
+ font-size: 13px; color: #3d4943; -webkit-user-select: none; user-select: none; z-index: 3;
}
.panel.open { transform: none; }
-.panel header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 18px; }
-.panel h2 { margin: 6px 0 0; font-size: 16px; font-weight: 700; letter-spacing: 0.01em; word-break: break-all; }
-.panel .sub { margin: 0 0 6px; color: #6c766f; }
+.panel header { display: flex; align-items: center; gap: 12px; margin: 0 4px 6px; }
+.panel header .title { flex: 1; min-width: 0; }
+.panel header .thumb { width: 64px; height: 56px; object-fit: contain; flex: none; }
+.panel header .glyph { width: 40px; height: 40px; background: #f7f8f4; border: 1px solid #d3d7ce; border-radius: 8px; }
+.panel h2 { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.01em; text-transform: capitalize; }
+.panel .close { background: none; border: 1px solid transparent; border-radius: 6px; padding: 5px; display: flex; align-self: flex-start; }
+.panel .close:hover { background: #e2e5de; border-color: #c9cec4; }
+.panel .sub { margin: 3px 0 0; color: #6c766f; font-size: 12px; line-height: 1.4; }
.panel .sub.warn { color: #b04a39; }
-.panel section { margin-top: 24px; }
-.panel h3 {
- margin: 0 0 8px; padding-bottom: 8px; border-bottom: 2px solid #d3d7ce; font-size: 11px; font-weight: 400;
- letter-spacing: 0.12em; text-transform: uppercase; color: #77817a;
+.panel .pill { display: inline-flex; align-items: center; gap: 6px; margin-top: 5px; padding: 2px 9px; border-radius: 999px; font-size: 11px; background: #e2e5de; color: #5d6861; }
+.panel .pill::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
+.panel .pill.working { background: #e1ecd9; color: #4f8a3e; }
+.panel .pill.problem { background: #f4dfda; color: #b04a39; }
+.panel section {
+ margin-top: 12px; padding: 12px 14px; background: #f7f8f4; border: 1px solid #dcdfd7; border-radius: 10px;
}
-.panel .row { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; padding: 4px 0; }
-.panel .count { color: #6c766f; white-space: nowrap; }
-.panel .empty { margin: 4px 0; color: #8a938c; }
+.panel h3 {
+ 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 .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; }
+.panel .count { color: #4f5a53; white-space: nowrap; font-variant-numeric: tabular-nums; }
+.panel .count.up { color: #4f8a3e; }
+.panel .count.down { color: #b04a39; }
+.panel .total { font-weight: 700; }
+.panel .empty { margin: 6px 0 0; color: #8a938c; font-size: 12px; line-height: 1.4; }
.panel button { font: inherit; color: inherit; cursor: pointer; }
-.panel .link {
- background: none; border: 0; padding: 0; text-align: left; text-decoration: underline;
- text-decoration-color: #b5bbb2; text-underline-offset: 4px;
-}
-.panel .link:hover { text-decoration-color: #3d4943; }
-.panel .frame { background: transparent; border: 1px solid #3d4943; border-radius: 2px; padding: 6px 12px; white-space: nowrap; }
+.panel .frame { background: #f7f8f4; border: 1px solid #3d4943; border-radius: 5px; padding: 6px 12px; white-space: nowrap; }
.panel .frame:hover { background: #e6e9e2; }
.panel .frame.danger { border-color: #b04a39; color: #b04a39; }
-.panel .actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 28px; }
+.panel .actions { display: flex; gap: 8px; flex-wrap: wrap; margin: 16px 4px 0; }
+
+/* The build menu: a picture of each building, its cost, and what it does. */
.panel .option {
- display: block; width: 100%; text-align: left; background: none; border: 0; border-radius: 2px;
- padding: 8px 8px; margin: 0 -8px; width: calc(100% + 16px);
-}
-.panel .option:hover:not(:disabled) { background: #e6e9e2; }
-.panel .option:disabled { opacity: 0.4; cursor: default; }
+ display: grid; grid-template-columns: 56px 1fr; gap: 4px 12px; align-items: center; width: 100%; text-align: left;
+ background: none; border: 1px solid transparent; border-radius: 8px; padding: 6px 8px 6px 4px;
+}
+.panel .option + .option { margin-top: 2px; }
+.panel .option:hover:not(:disabled) { background: #eceee8; border-color: #d3d7ce; }
+.panel .option:disabled { opacity: 0.45; cursor: default; }
+.panel .option .thumb { grid-row: span 3; width: 56px; height: 48px; object-fit: contain; }
+.panel .option .name { font-weight: 700; text-transform: capitalize; }
+.panel .option .blurb { color: #77817a; font-size: 12px; line-height: 1.35; }
.panel .option.short .blurb { color: #b04a39; }
-.panel .option .count { white-space: normal; text-align: right; }
-.panel .option .row { padding: 0; }
-.panel .option .name { text-decoration: underline; text-decoration-color: #b5bbb2; text-underline-offset: 4px; }
-.panel .option .blurb { display: block; margin-top: 4px; color: #77817a; }
+.panel .chips { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; color: #4f5a53; }
+.panel .chip { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
+.panel .chip.short { color: #b04a39; font-weight: 700; }
+.panel .chip.dim { color: #8a938c; }
@media (max-height: 500px) {
- .panel { padding: 14px 16px; width: 300px; }
- .panel header { margin-bottom: 8px; }
- .panel section { margin-top: 14px; }
- .panel .option { padding: 5px 8px; }
+ .panel { padding: 12px; width: 300px; }
+ .panel section { margin-top: 8px; padding: 8px 10px; }
+ .panel .option .thumb { width: 44px; height: 38px; }
}
.panel .spark { margin-top: 8px; height: 36px; border-bottom: 1px solid #e0e3db; }
.panel .spark svg { width: 100%; height: 36px; display: block; }
-.panel .lever .controls { display: inline-flex; align-items: center; gap: 8px; }
-.panel .lever .rate { min-width: 4.5ch; text-align: center; font-weight: 600; }
-.panel .frame.step { padding: 2px 10px; }
-.panel .need { display: grid; grid-template-columns: 5ch 1fr 8ch; align-items: center; gap: 10px; padding: 4px 0; }
-.panel .need .track { height: 6px; border: 1px solid #c9cec4; border-radius: 1px; }
-.panel .need .fill { display: block; height: 100%; background: #3d4943; }
+.panel .lever .controls { display: inline-flex; align-items: center; gap: 6px; }
+.panel .lever .rate { min-width: 4.5ch; text-align: center; font-weight: 700; }
+.panel .frame.step { padding: 1px 9px; }
+.panel .effect { margin: -2px 0 4px; font-size: 11px; color: #8a938c; text-align: right; }
+.panel .effect.up { color: #4f8a3e; }
+.panel .effect.down { color: #b04a39; }
+.panel .need { display: grid; grid-template-columns: 7.5ch 1fr 7ch; align-items: center; gap: 10px; padding: 4px 0; }
+.panel .need .track { height: 8px; background: #e6e9e2; border-radius: 4px; overflow: hidden; }
+.panel .need .fill { display: block; height: 100%; background: #6e8f36; border-radius: 4px; }
+.panel .need .fill.low { background: #c98a3a; }
+.panel .need .fill.none { background: #b04a39; }
.panel .need .count { text-align: right; }
-.panel .good-row { cursor: pointer; }
-.panel .good-row input { margin: 0 8px 0 0; accent-color: #3d4943; vertical-align: -2px; }
+.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 ── */
.hud .clock .winter { color: #3d6db5; font-weight: 600; }
@@ -122,11 +185,12 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
.panel .meter::after { content: ""; position: absolute; left: 50%; top: -3px; bottom: -3px; border-left: 1px solid #77817a; }
.panel .meter .fill { position: absolute; top: 0; bottom: 0; background: #4f8a3e; }
.panel .meter .fill.low { background: #b04a39; }
-.panel .goal .mark { display: inline-block; width: 2ch; color: #8a938c; }
-.panel .goal.met .mark { color: #4f8a3e; font-weight: 700; }
+.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; margin-right: 8px; font-size: 12px; text-align: center; color: #8a938c; border-color: #c9cec4; }
-.panel .frame.mode.on { color: #3d4943; border-color: #3d4943; font-weight: 600; }
+.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; }
@@ -141,6 +205,9 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
width: 640px; max-width: 100%; max-height: calc(100vh - 32px); overflow-y: auto; box-sizing: border-box; font-size: 14px;
}
.dialog .sheet.wide { width: 720px; }
+.dialog .sheet.narrow { width: 460px; }
+.dialog .frame.danger { border-color: #b04a39; color: #b04a39; }
+.dialog .frame.danger:hover { background: #f4dfda; }
.dialog h2 { margin: 0 0 6px; font-size: 18px; }
.dialog .sub { margin: 0 0 10px; color: #6c766f; line-height: 1.45; }
.dialog section { margin-top: 16px; }
@@ -175,7 +242,7 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
}
.result {
- position: fixed; top: 12px; right: 16px; display: none; font: inherit; font-size: 12px; padding: 7px 12px; z-index: 5;
+ position: fixed; top: 12px; left: 50%; transform: translateX(-50%); display: none; font: inherit; font-size: 12px; padding: 7px 12px; z-index: 5;
background: #3d4943; color: #f7f8f4; border: 0; border-radius: 4px; cursor: pointer; box-shadow: 0 2px 0 #c9cec4;
}
.result.show { display: block; }
diff --git a/src/gallery.ts b/src/gallery.ts
new file mode 100644
index 0000000..82912e1
--- /dev/null
+++ b/src/gallery.ts
@@ -0,0 +1,155 @@
+/**
+ * A page of every drawing the town is made of, side by side, for working on
+ * the art: open /gallery.html while `pnpm dev` runs. Scroll or drag to look
+ * around, ctrl + wheel (or pinch) to zoom; `?zoom=2&x=…&y=…` to start
+ * somewhere, `?icons=0` with the icon drawer closed. Not part of the game's
+ * build.
+ */
+import { Application, Container, Graphics } from "pixi.js"
+
+import { carrierDress, cartLook, drawBuilding, drawField, drawHouse, drawRoads, drawRock, drawTree, drawWalker, drawWater, homeVariant, plate, plateHalf, residentDress, serviceDress } from "./art.ts"
+import { categoryColor, goodIds, kindIds, kinds } from "./content.ts"
+import { key } from "./grid.ts"
+import { icon, iconNames } from "./icons.ts"
+import { toScreen } from "./iso.ts"
+
+const app = new Application()
+await app.init({ resizeTo: window, antialias: true, background: 0xf0f2ec, resolution: Math.min(window.devicePixelRatio || 1, 2), autoDensity: true })
+document.body.appendChild(app.canvas)
+const world = new Container()
+const params = new URLSearchParams(location.search)
+world.scale.set(Number(params.get("zoom") ?? 1.5))
+world.position.set(-Number(params.get("x") ?? 0), -Number(params.get("y") ?? 0))
+app.stage.addChild(world)
+
+/** Puts a drawing at (x, y) on the page, in unscaled pixels. */
+const put = (g: Graphics, x: number, y: number) => {
+ g.position.set(x, y)
+ world.addChild(g)
+}
+
+// Buildings: no doors, then both doors.
+kindIds.forEach((id, i) => {
+ const kind = kinds[id]
+ ;[{ right: false, left: false }, { right: true, left: true }].forEach((doors, j) => {
+ const g = new Graphics()
+ plate(g, plateHalf(kind.size))
+ drawBuilding(g, kind, 1, 0.5, 1.2, doors)
+ put(g, 70 + (i % 8) * 140, 110 + Math.floor(i / 8) * 230 + j * 110)
+ })
+})
+
+// Homes: settlers and citizens in each variant.
+for (let i = 0; i < 10; i++) {
+ for (const tier of [1, 2] as const) {
+ const g = new Graphics()
+ plate(g, plateHalf(1))
+ drawHouse(g, tier, 1, { right: i % 2 === 0, left: i % 3 === 0 }, homeVariant(i / 10 + 0.03))
+ put(g, 40 + i * 50 + (tier - 1) * 520, 520)
+ }
+}
+
+// Trees, grown and young; rocks, stone and ore, full and quarried; fields; crates and walkers.
+for (let i = 0; i < 32; i++) {
+ const g = new Graphics()
+ drawTree(g, i * 3, i * 7, i < 24 ? 1 : i < 28 ? 0.6 : 0.3)
+ put(g, 30 + i * 30, 590)
+}
+for (let i = 0; i < 16; i++) {
+ const g = new Graphics()
+ drawRock(g, i * 5, i * 3, i % 2 === 1, i < 10 ? 40 : 10)
+ put(g, 40 + i * 50, 640)
+}
+for (let i = 0; i < 4; i++) {
+ const g = new Graphics()
+ drawField(g, i / 3)
+ put(g, 860 + i * 70, 640)
+}
+// Walkers: carriers with each good (a full load, then one crate), facing each way; service walkers; residents.
+const dirs = [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]
+goodIds.forEach((good, i) => {
+ for (const [j, count] of [[0, 4], [1, 1]] as const) {
+ const w = new Graphics()
+ drawWalker(w, carrierDress(i / 11), { kind: "cart", good, count }, cartLook((i * 0.37 + j * 0.5) % 1), dirs[(i + j) % 4]!, i % 2)
+ put(w, 1050 + i * 60, 150 + j * 50)
+ }
+})
+dirs.forEach((dir, i) => {
+ const w = new Graphics()
+ drawWalker(w, carrierDress(0.2 + i / 5), { kind: "none" }, cartLook(i / 4), dir, 0, 0.4)
+ put(w, 1050 + i * 60, 250)
+})
+const basket = new Graphics()
+drawWalker(basket, serviceDress(categoryColor.services, 0.3, false), { kind: "basket", goods: ["fish", "bread", "cloth"] }, null, dirs[0]!, 0)
+put(basket, 1200, 250)
+const bell = new Graphics()
+drawWalker(bell, serviceDress(categoryColor.services, 0.6, true), { kind: "bell" }, null, dirs[1]!, 1)
+put(bell, 1230, 250)
+for (let i = 0; i < 16; i++) {
+ const w = new Graphics()
+ const tier = i < 8 ? 1 : 2
+ drawWalker(w, residentDress(homeVariant(((i % 8) / 8) + 0.03).cloth, tier, (i * 0.37) % 1), { kind: "none" }, null, dirs[i % 4]!, i % 2)
+ put(w, 1050 + i * 30, 310)
+}
+
+// Water and roads, on their own patch of grid.
+const water = new Set<number>()
+for (let y = 0; y < 6; y++) for (let x = 0; x < 6 + (y % 3); x++) water.add(key(x, y))
+const ground = new Graphics()
+drawWater(ground, water)
+const o = toScreen(0, 0)
+put(ground, 260 - o.x, 680)
+const roads = new Set<number>()
+for (let x = 0; x < 10; x++) roads.add(key(x, 3))
+for (let y = 0; y < 8; y++) roads.add(key(4, y))
+for (let y = 1; y < 6; y++) roads.add(key(8, y))
+const road = new Graphics()
+drawRoads(road, roads)
+put(road, 700, 680)
+
+// The page's icons, large, in a drawer that opens and closes.
+const drawer = document.createElement("details")
+drawer.open = params.get("icons") !== "0"
+drawer.style.cssText = "position:fixed;left:0;right:0;bottom:0;max-height:40vh;overflow:auto;background:#f7f8f4;border-top:1px solid #c9cec4;font:11px ui-monospace,monospace;color:#3d4943"
+drawer.innerHTML = `<summary style="padding:8px 12px;cursor:pointer">icons</summary>`
+const strip = document.createElement("div")
+strip.style.cssText = "display:flex;flex-wrap:wrap;gap:10px;padding:0 12px 12px"
+for (const name of iconNames) {
+ const cell = document.createElement("div")
+ cell.style.cssText = "display:flex;flex-direction:column;align-items:center;gap:4px;width:64px"
+ cell.innerHTML = `${icon(name, 32)}<span>${name}</span>`
+ strip.append(cell)
+}
+drawer.append(strip)
+document.body.append(drawer)
+
+// Looking around: the wheel (or a trackpad) scrolls, dragging pans, ctrl + wheel (or pinch) zooms.
+app.canvas.addEventListener("wheel", (event) => {
+ event.preventDefault()
+ if (event.ctrlKey) {
+ const before = { x: (event.clientX - world.position.x) / world.scale.x, y: (event.clientY - world.position.y) / world.scale.y }
+ const zoom = Math.min(6, Math.max(0.5, world.scale.x * Math.exp(-event.deltaY * 0.01)))
+ world.scale.set(zoom)
+ world.position.set(event.clientX - before.x * zoom, event.clientY - before.y * zoom)
+ return
+ }
+ world.position.set(world.position.x - (event.shiftKey ? event.deltaY : event.deltaX), world.position.y - (event.shiftKey ? 0 : event.deltaY))
+}, { passive: false })
+let drag: { x: number; y: number } | null = null
+app.canvas.addEventListener("pointerdown", (event) => {
+ drag = { x: event.clientX, y: event.clientY }
+ app.canvas.setPointerCapture(event.pointerId)
+ app.canvas.style.cursor = "grabbing"
+})
+app.canvas.addEventListener("pointermove", (event) => {
+ if (!drag) return
+ world.position.set(world.position.x + event.clientX - drag.x, world.position.y + event.clientY - drag.y)
+ drag = { x: event.clientX, y: event.clientY }
+})
+const stop = () => {
+ drag = null
+ app.canvas.style.cursor = "grab"
+}
+app.canvas.addEventListener("pointerup", stop)
+app.canvas.addEventListener("pointercancel", stop)
+app.canvas.style.cursor = "grab"
diff --git a/src/host.ts b/src/host.ts
index c428686..99c55dc 100644
--- a/src/host.ts
+++ b/src/host.ts
@@ -6,12 +6,13 @@
*/
import { Application, Container, Graphics } from "pixi.js"
-import { seaFill, type Stage } from "./art.ts"
+import { drawBuilding, drawHouse, homeVariant, plate, plateHalf, seaFill, type Stage } from "./art.ts"
import {
categoryColor, categoryOrder, costText, defaultCharter, goodIds, goods, home, kindOrder, kinds, landIds, lands, mood as moodRules, needTitle,
- RESERVES, ROAD_COST, sizeIds, sizes, TAX_STEPS, TERMS, type CharterValue, type GoodId, type Kind, type KindId
+ RESERVES, ROAD_COST, sizeIds, sizes, TAX_STEPS, TERMS, type Category, type CharterValue, type GoodId, type Kind, type KindId
} from "./content.ts"
import { GRID, toScreen, type Point } from "./iso.ts"
+import { goodIcon, icon, iconEl, type IconName } from "./icons.ts"
import { generate } from "./mapgen.ts"
import { askOf, priceOf } from "./sim/index.ts"
import type { Stats, Tool, TradeMode, UiValue } from "./ui.ts"
@@ -90,26 +91,25 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
// ── DOM ──
- // The top bar: treasury, people, and jobs in one strip; the goods in stock below, grouped.
- const hud = el("div", "hud")
+ // Top left: the term's clock and the treasury, the goods in stock below, then the crown's request and any alarm.
+ // Top right: the people and their mood, which opens the town's panel.
+ const hud = el("div", "hud left")
const bar = el("div", "card bar")
- const coins = el("div", "cell coins")
- const people = el("div", "cell")
- const jobs = el("div", "cell")
const clock = el("div", "cell clock")
- const approval = el("div", "cell")
- bar.append(clock, coins, approval, people, jobs)
+ const coins = el("div", "cell coins")
+ bar.append(clock, coins)
const stock = el("div", "card stock")
const groups: ReadonlyArray<ReadonlyArray<GoodId>> = [["wood", "planks", "stone", "tools"], ["fish", "bread"], ["wool", "cloth"]]
const goodCells = new Map<GoodId, HTMLElement>()
for (const group of groups) {
- const cell = el("div", "cell")
+ const cell = el("div", "group")
for (const g of group) {
const item = el("span", "good")
- const swatch = el("span", "label")
- swatch.style.background = hex(goods[g].color)
+ item.title = goods[g].title
+ const glyph = el("span", "glyph")
+ glyph.innerHTML = goodIcon(g, 18)
const count = el("span", "count", "0")
- item.append(swatch, document.createTextNode(goods[g].title), count)
+ item.append(glyph, count)
cell.append(item)
goodCells.set(g, count)
}
@@ -126,17 +126,27 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
request.append(requestText, send)
const alarm = el("div", "card alarm")
hud.append(bar, stock, request, alarm)
- hud.title = "Open the town's numbers, goals, and levers"
- hud.onclick = () => toggleMenu("town")
+ const people = el("div", "hud right")
+ const folk = el("div", "card bar")
+ const approval = el("div", "cell")
+ const settlerCell = el("div", "cell")
+ const citizenCell = el("div", "cell")
+ const jobs = el("div", "cell")
+ folk.append(approval, settlerCell, citizenCell, jobs)
+ people.append(folk)
+ people.title = "Open the town's numbers, goals, and levers (T)"
+ people.onclick = () => toggleMenu("town")
const tooltip = el("div", "tooltip")
const toastBox = el("div", "toast")
const toolbar = el("div", "toolbar")
+ const system = el("div", "system")
const panel = el("aside", "panel")
const dialog = el("div", "dialog")
+ const confirmBox = el("div", "dialog")
const reckoning = el("div", "dialog")
const result = el("button", "result", "")
result.onclick = () => showReckoning(true)
- document.body.append(hud, tooltip, toastBox, toolbar, panel, result, dialog, reckoning)
+ document.body.append(hud, people, tooltip, toastBox, toolbar, system, panel, result, dialog, confirmBox, reckoning)
let toastTimer = 0
const ui: UiValue = {
@@ -164,36 +174,41 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
}
- const tools: ReadonlyArray<{ readonly tool: Tool | "build" | "town"; readonly label: string; readonly key: string; readonly swatch: string; readonly tip: string }> = [
- { tool: "select", label: "select", key: "S", swatch: "round", tip: "Click a building or home to see what it does · drag to pan · wheel to zoom" },
- { tool: "road", label: "road", key: "R", swatch: "#e6e8e2", tip: `Drag to lay a road · ${ROAD_COST} coins a cell` },
- { tool: "home", label: "homes", key: "H", swatch: "#c4523f", tip: `Drag to lay a row of homes along a road · ${costText(home.cost)} each` },
- { tool: "build", label: "build", key: "B", swatch: "#3d6db5", tip: "Choose a building, then click to place it · Esc to stop" },
- { tool: "bulldoze", label: "bulldoze", key: "X", swatch: "#8f9891", tip: "Click a building, home, road, tree, or field to remove it" },
- { tool: "town", label: "town", key: "T", swatch: "#8a58a8", tip: "The town's numbers, history, and taxes" }
+ const tools: ReadonlyArray<{ readonly tool: Tool | "build"; readonly label: string; readonly key: string; readonly icon: IconName; readonly tip: string }> = [
+ { tool: "select", label: "select", key: "S", icon: "select", tip: "Click a building or home to see what it does · drag to pan · wheel to zoom" },
+ { tool: "road", label: "road", key: "R", icon: "road", tip: `Drag to lay a road · ${ROAD_COST} coins a cell` },
+ { tool: "home", label: "homes", key: "H", icon: "homes", tip: `Drag to lay a row of homes along a road · ${costText(home.cost)} each` },
+ { tool: "build", label: "build", key: "B", icon: "build", tip: "Choose a building, then click to place it · Esc to stop" },
+ { tool: "bulldoze", label: "bulldoze", key: "X", icon: "bulldoze", tip: "Click a building, home, road, tree, or field to remove it" }
]
+ // The town's panel is opened most: it has a button of its own, first and larger.
+ const townButton = el("button", "town-button")
+ townButton.title = "The town's goals, numbers, taxes, and trade (T)"
+ townButton.append(iconEl("town", 22), el("span", "", "town"), el("kbd", "", "T"))
+ townButton.onclick = () => toggleMenu("town")
+ const toolGroup = el("div", "group")
+ toolbar.append(townButton, toolGroup)
const buttons = tools.map((tool) => {
const button = el("button", "")
button.title = tool.tip
- const swatch = el("span", "swatch")
- if (tool.swatch === "round") swatch.style.borderRadius = "50%"
- else swatch.style.background = tool.swatch
- button.append(swatch, document.createTextNode(tool.label), el("kbd", "", tool.key))
- button.onclick = () => (tool.tool === "build" || tool.tool === "town" ? toggleMenu(tool.tool) : choose(tool.tool))
- toolbar.append(button)
+ button.append(iconEl(tool.icon), document.createTextNode(tool.label), el("kbd", "", tool.key))
+ button.onclick = () => (tool.tool === "build" ? toggleMenu("build") : choose(tool.tool))
+ toolGroup.append(button)
return { tool, button }
})
- toolbar.append(el("span", "sep"))
+ const speedGroup = el("div", "group")
+ toolbar.append(speedGroup)
const speeds = [
- { speed: 0, label: "pause", key: "space" },
+ { speed: 0, label: "", key: "space" },
{ speed: 1, label: "1×", key: "1" },
{ speed: 2, label: "2×", key: "2" },
{ speed: 4, label: "4×", key: "3" }
].map(({ speed, label, key }) => {
- const button = el("button", "", label)
+ const button = el("button", speed === 0 ? "pause" : "", label)
+ if (speed === 0) button.append(iconEl("pause", 14))
button.title = speed === 0 ? "Pause the town (space)" : `Run the town at ${label} (${key})`
button.onclick = () => setSpeed(speed)
- toolbar.append(button)
+ speedGroup.append(button)
return { speed, button }
})
let lastSpeed = 1
@@ -203,22 +218,60 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
for (const s of speeds) s.button.classList.toggle("on", s.speed === speed)
}
setSpeed(1)
- toolbar.append(el("span", "sep"))
- const action = (label: string, tip: string, run: () => void) => {
- const button = el("button", "", label)
+ // New town, save, and load, out of the way in the bottom right. Founding or
+ // loading replaces the town, so each asks first.
+ const action = (name: IconName, label: string, tip: string, run: () => void) => {
+ const button = el("button", "")
button.title = tip
+ button.append(iconEl(name), document.createTextNode(label))
button.onclick = run
- toolbar.append(button)
+ system.append(button)
+ }
+ action("save", "save", "Save the town in this browser (it also autosaves every two minutes)", () => ui.toast(persistence().save() ?? "Saved"))
+ action("load", "load", "Load the latest save: yours or the autosave, whichever is newer", () =>
+ confirmLeave("load the latest save?", "The town as it is now is replaced by the latest save (yours or the autosave).", "Load", () => ui.toast(persistence().load() ?? "Loaded")))
+ action("newTown", "new town", "Found a new town on new land", () =>
+ confirmLeave("found a new town?", "This town is left behind for good unless it is saved first.", "Choose new land", () => openCharter(true)))
+
+ /** Asks before something that replaces the town: save first, go ahead, or stay. */
+ const confirmLeave = (title: string, text: string, go: string, run: () => void) => {
+ const wasSpeed = ui.speed
+ setSpeed(0)
+ confirmBox.replaceChildren()
+ const card = el("div", "sheet narrow")
+ card.append(el("h2", "", title), el("p", "sub", text))
+ const actions = el("div", "actions")
+ const close = (resume: boolean) => {
+ confirmBox.classList.remove("open")
+ if (resume) setSpeed(wasSpeed)
+ }
+ const stay = el("button", "frame primary", "Keep playing")
+ stay.onclick = () => close(true)
+ const saveFirst = el("button", "frame", `Save, then ${go.toLowerCase()}`)
+ saveFirst.onclick = () => {
+ const failed = persistence().save()
+ if (failed) return ui.toast(failed)
+ close(true)
+ run()
+ }
+ const leave = el("button", "frame danger", `${go} without saving`)
+ leave.onclick = () => {
+ close(true)
+ run()
+ }
+ actions.append(stay, saveFirst, leave)
+ card.append(actions)
+ confirmBox.append(card)
+ confirmBox.classList.add("open")
+ stay.focus()
}
- action("new town", "Found a new town on new land", () => openCharter(true))
- action("save", "Save the town in this browser (it also autosaves every two minutes)", () => ui.toast(persistence().save() ?? "Saved"))
- action("load", "Load the latest save: yours or the autosave, whichever is newer", () => ui.toast(persistence().load() ?? "Loaded"))
const refreshTools = () => {
for (const { tool, button } of buttons) {
- const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" : tool.tool === "town" ? ui.menu === "town" : tool.tool === ui.tool
+ const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" : tool.tool === ui.tool
button.classList.toggle("on", on)
}
+ townButton.classList.toggle("on", ui.menu === "town")
}
const choose = (tool: Tool) => {
ui.tool = tool
@@ -241,7 +294,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
choose("select")
window.addEventListener("keydown", (event) => {
- if (ui.founding || reckoning.classList.contains("open")) return
+ if (confirmBox.classList.contains("open") && event.key === "Escape") confirmBox.querySelector<HTMLButtonElement>(".primary")?.click()
+ if (ui.founding || reckoning.classList.contains("open") || confirmBox.classList.contains("open")) return
if (event.key === " ") {
event.preventDefault()
setSpeed(ui.speed === 0 ? lastSpeed : 0)
@@ -293,25 +347,66 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
return `<svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="none"><polyline points="${points}" fill="none" stroke="#3d4943" stroke-width="1.5" vector-effect="non-scaling-stroke"/></svg>`
}
+ // ── Pictures of buildings, for the build menu and the panel ──
+ const pictures = new Map<string, Promise<string>>()
+ /** A building (or a home of a tier) drawn as the town draws it, as an image. */
+ const picture = (what: KindId | 1 | 2): HTMLImageElement => {
+ const img = document.createElement("img")
+ img.className = "thumb"
+ img.alt = ""
+ const id = String(what)
+ let url = pictures.get(id)
+ if (!url) {
+ const g = new Graphics()
+ if (what === 1 || what === 2) {
+ plate(g, plateHalf(1))
+ drawHouse(g, what, 1, { right: true, left: false }, homeVariant(0.1))
+ } else {
+ plate(g, plateHalf(kinds[what].size))
+ drawBuilding(g, kinds[what], 1, 0, 0.6, { right: true, left: true })
+ }
+ url = app.renderer.extract.base64({ target: g, resolution: 2 })
+ void url.finally(() => g.destroy())
+ pictures.set(id, url)
+ }
+ void url.then((src) => (img.src = src))
+ return img
+ }
+
// ── Panel ──
/** Volatile parts of the panel, updated in place without rebuilding it. */
let live: Array<() => void> = []
let shape = ""
- const section = (heading: string) => {
+ /** A section of the panel, its heading with an icon; `help` is kept behind an ⓘ rather than spelled out. */
+ const section = (heading: string, glyph?: IconName, help?: string) => {
const box = el("section", "")
- box.append(el("h3", "", heading))
+ const h3 = el("h3", "")
+ if (glyph) h3.append(iconEl(glyph))
+ h3.append(document.createTextNode(heading))
+ if (help) {
+ const info = iconEl("info", 15)
+ info.classList.add("help")
+ info.title = help
+ h3.append(info)
+ }
+ box.append(h3)
return box
}
- const header = (title: string) => {
+ const header = (title: string, lead: HTMLElement, below?: HTMLElement) => {
const head = el("header", "")
- const closeButton = el("button", "frame", "Close")
+ const text = el("div", "title")
+ text.append(el("h2", "", title))
+ if (below) text.append(below)
+ const closeButton = el("button", "close")
+ closeButton.title = "Close (Esc)"
+ closeButton.append(iconEl("close", 18))
closeButton.onclick = () => {
ui.selected = null
ui.menu = null
refreshTools()
}
- head.append(el("h2", "", title), closeButton)
+ head.append(lead, text, closeButton)
return head
}
@@ -323,36 +418,61 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
if (s.citizens < kind.unlock.citizens) return `needs ${kind.unlock.citizens} citizens`
return null
}
- const shortText = (cost: Kind["cost"]): string | null => {
- const s = ui.stats
- if (!s) return null
- if (s.coins < cost.coins) return "not enough coins"
- for (const [g, n] of Object.entries(cost.materials)) if (s.stock[g as keyof typeof s.stock] < (n ?? 0)) return `not enough ${g}`
- return null
+
+ /** A cost as icon chips, each marked when the town is short of it. */
+ const costChips = (cost: Kind["cost"]) => {
+ const box = el("span", "chips")
+ const chips: Array<{ chip: HTMLElement; short: () => boolean }> = []
+ if (cost.coins > 0) {
+ const chip = el("span", "chip")
+ chip.innerHTML = `${icon("coins", 14)}${cost.coins}`
+ chips.push({ chip, short: () => (ui.stats?.coins ?? 0) < cost.coins })
+ }
+ for (const [g, n] of Object.entries(cost.materials) as Array<[GoodId, number]>) {
+ const chip = el("span", "chip")
+ chip.title = goods[g].title
+ chip.innerHTML = `${goodIcon(g, 14)}${n}`
+ chips.push({ chip, short: () => (ui.stats?.stock[g] ?? 0) < n })
+ }
+ box.append(...chips.map((c) => c.chip))
+ const refresh = () => {
+ let short = false
+ for (const c of chips) {
+ const now = c.short()
+ c.chip.classList.toggle("short", now)
+ short ||= now
+ }
+ return short
+ }
+ return { box, refresh }
}
+ const categoryIcon: Readonly<Record<Category, IconName>> = { storage: "jobs", gathering: "wood", crafts: "tools", food: "bread", services: "faith" }
+
const buildMenu = () => {
- panel.append(header("build"))
- panel.append(el("p", "sub", `Choose, then click on the map to place · Esc to stop. Roads ${ROAD_COST} coins a cell (R), homes ${costText(home.cost)} (H).`))
+ panel.append(header("build", iconEl("build", 30), el("p", "sub", "Pick one, then click the map · Esc to stop")))
for (const category of categoryOrder) {
const options = kindOrder.filter((id) => kinds[id].category === category && kinds[id].buildable)
if (options.length === 0) continue
- const box = section(category)
- box.querySelector("h3")!.style.borderBottomColor = hex(categoryColor[category])
+ const box = section(category, categoryIcon[category])
+ box.style.borderTop = `3px solid ${hex(categoryColor[category])}`
for (const id of options) {
const kind = kinds[id]
const option = el("button", "option")
- const top = el("span", "row")
- top.append(el("span", "name", kind.title.toLowerCase()), el("span", "count", costText(kind.cost)))
- const blurb = el("span", "blurb", "")
- option.append(top, blurb)
+ const cost = costChips(kind.cost)
+ const terms = el("span", "chips")
+ terms.innerHTML = `<span class="chip dim" title="workers">${icon("workers", 14)}${kind.workers}</span><span class="chip dim" title="upkeep, coins a minute">${icon("upkeep", 14)}${kind.upkeep}/min</span>`
+ const blurb = el("span", "blurb", kind.blurb)
+ option.append(picture(id), el("span", "name", kind.title.toLowerCase()), cost.box, blurb)
+ option.title = `${kind.title}: ${kind.blurb} · ${kind.workers} workers · ${kind.upkeep} coins a minute`
+ cost.box.append(terms)
option.onclick = () => place(id)
live.push(() => {
const lock = lockText(kind)
- const short = lock ? null : shortText(kind.cost)
+ const short = cost.refresh()
option.disabled = lock !== null
- option.classList.toggle("short", short !== null)
- blurb.textContent = lock ?? `${kind.blurb} · ${kind.workers} workers · ${kind.upkeep}/min${short ? ` · ${short}` : ""}`
+ option.classList.toggle("short", lock === null && short)
+ blurb.textContent = lock ?? kind.blurb
})
box.append(option)
}
@@ -360,48 +480,56 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
}
- const row = (box: HTMLElement, label: string) => {
+ const row = (box: HTMLElement, label: string, glyph?: IconName | GoodId) => {
const line = el("div", "row")
const value = el("span", "count")
- line.append(el("span", "", label), value)
+ const name = el("span", "label")
+ if (glyph) name.innerHTML = icon(glyph, 16)
+ name.append(document.createTextNode(label))
+ line.append(name, value)
box.append(line)
return value
}
+ /** Sets a number with its sign, coloured by it. */
+ const money = (node: HTMLElement, n: number, suffix = "") => {
+ node.textContent = `${signed(n)}${suffix}`
+ node.classList.toggle("up", n > 0)
+ node.classList.toggle("down", n < 0)
+ }
const townPanel = () => {
- panel.append(header("town"))
const sub = el("p", "sub")
- panel.append(sub)
+ panel.append(header("town", iconEl("town", 30), sub))
// The goals that complete the town, and how near each one is.
- const goals = section("to complete the town")
- const goalNote = el("p", "empty")
- goals.append(goalNote)
+ const goals = section("goals", "goal", "Meet every goal at once and hold them for two minutes to complete the town.")
const goalRows: Array<{ line: HTMLElement; mark: HTMLElement; text: HTMLElement; value: HTMLElement }> = []
+ const goalNote = el("p", "empty")
panel.append(goals)
- const mood = section("approval")
+ const mood = section("approval", "approval", `Homes hold more residents when approval is high and fewer when it is low. At −50 for two minutes, the town turns the mayor out.`)
const moodLine = el("div", "row")
- const moodValue = el("span", "count")
- moodLine.append(el("span", "", "now, heading for"), moodValue)
+ const moodValue = el("span", "count total")
+ moodLine.append(el("span", "label", "now → heading for"), moodValue)
const moodTrack = el("div", "meter")
const moodFill = el("span", "fill")
moodTrack.append(moodFill)
const moodParts = el("div", "")
- mood.append(moodLine, moodTrack, moodParts, el("p", "empty", `Homes hold more residents when approval is high and fewer when it is low. At −50 for two minutes, the town turns the mayor out.`))
+ mood.append(moodLine, moodTrack, moodParts)
panel.append(mood)
- const treasury = section("treasury")
- const taxes = row(treasury, "taxes")
- const traded = row(treasury, "trade")
- const upkeep = row(treasury, "upkeep")
- const admin = row(treasury, "administration")
- const net = row(treasury, "a minute")
+ const treasury = section("treasury", "treasury", "Coins a minute. Administration grows faster than the town. Three minutes in debt and the town is bankrupt.")
+ const taxes = row(treasury, "taxes", "taxes")
+ const traded = row(treasury, "trade", "trade")
+ const upkeep = row(treasury, "upkeep", "upkeep")
+ const admin = row(treasury, "administration", "town")
+ const net = row(treasury, "a minute", "coins")
+ net.classList.add("total")
const coinLine = el("div", "spark")
- treasury.append(coinLine, el("p", "empty", "Administration grows faster than the town. Three minutes in debt and the town is bankrupt."))
+ treasury.append(coinLine)
panel.append(treasury)
- const levers = section("taxes")
+ const levers = section("tax rates", "taxes", "Lower taxes raise approval, higher ones lower it, weighed by how many of each tier there are.")
for (const tier of ["settlers", "citizens"] as const) {
const line = el("div", "row lever")
const minus = el("button", "frame step", "−")
@@ -409,8 +537,11 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const plus = el("button", "frame step", "+")
const controls = el("span", "controls")
controls.append(minus, value, plus)
- line.append(el("span", "", tier), controls)
- const effect = el("p", "empty")
+ const name = el("span", "label")
+ name.innerHTML = icon(tier, 16)
+ name.append(document.createTextNode(tier))
+ line.append(name, controls)
+ const effect = el("p", "effect")
levers.append(line, effect)
const move = (by: number) => {
const now = ui.stats?.policy[tier] ?? 100
@@ -424,24 +555,28 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
const rate = ui.stats?.policy[tier] ?? 100
value.textContent = `${rate}%`
const sway = Math.round((100 - rate) * moodRules.perTaxPoint)
- effect.textContent = sway === 0 ? "the usual rate" : `${sway > 0 ? "+" : ""}${sway} approval from ${tier} (weighed by how many there are)`
+ effect.textContent = sway === 0 ? "the usual rate" : `${signed(sway)} approval`
+ effect.className = `effect ${sway > 0 ? "up" : sway < 0 ? "down" : ""}`
})
}
panel.append(levers)
- const town = section("people")
- const settlers = row(town, "settlers")
- const citizens = row(town, "citizens")
- const homes = row(town, "homes")
- const work = row(town, "jobs filled")
+ const town = section("people", "people")
+ const settlers = row(town, "settlers", "settlers")
+ const citizens = row(town, "citizens", "citizens")
+ const homes = row(town, "homes", "homes")
+ const work = row(town, "jobs filled", "jobs")
const peopleLine = el("div", "spark")
town.append(peopleLine)
panel.append(town)
- const needs = section("homes supplied")
+ const needs = section("homes supplied", "homes", "Settlers need food (fish or bread) from a market; citizens need bread, cloth, and faith.")
+ const needIcons: Readonly<Record<"food" | "bread" | "cloth" | "faith", IconName>> = { food: "fish", bread: "bread", cloth: "cloth", faith: "faith" }
const bars = (["food", "bread", "cloth", "faith"] as const).map((n) => {
const line = el("div", "need")
- const label = el("span", "", needTitle[n])
+ const label = el("span", "label")
+ label.innerHTML = icon(needIcons[n], 16)
+ label.append(document.createTextNode(needTitle[n]))
const track = el("span", "track")
const fill = el("span", "fill")
track.append(fill)
@@ -450,23 +585,23 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
needs.append(line)
return { n, fill, value }
})
- const larderLine = row(needs, "food in store")
+ const larderLine = row(needs, "food in store", "flour")
panel.append(needs)
- const crown = section("the crown")
- const crownLine = row(crown, "requests met · missed")
+ const crown = section("the crown", "crown", `Sending what the crown asks for earns coins. A missed request is a fine, and the town remembers the snub for a while; too many missed in a row and the crown dismisses the mayor.`)
+ const crownLine = row(crown, "requests met · missed", "goal")
const crownNext = el("p", "empty")
crown.append(crownNext)
panel.append(crown)
- const store = section("goods and trade")
+ const 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.")
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", "", "keep in store"), reserveControls)
+ reserveLine.append(el("span", "label", "keep in store"), reserveControls)
store.append(reserveLine)
const stepReserve = (by: number) => {
const now = ui.stats?.policy.reserve ?? 25
@@ -475,28 +610,32 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
fewer.onclick = () => stepReserve(-1)
more.onclick = () => stepReserve(1)
- store.append(el("p", "empty", "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."))
const modes: ReadonlyArray<TradeMode> = ["none", "sell", "buy"]
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 name = el("span", "")
- const left = el("span", "")
- left.append(mode, name)
+ 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")
- line.append(left, value)
+ const right = el("span", "label")
+ right.append(value, mode)
+ line.append(name, right)
store.append(line)
- return { g, value, mode, name }
+ return { g, value, mode, price }
})
panel.append(store)
- const chronicle = section("chronicle")
+ const chronicle = section("chronicle", "chronicle")
const lines = el("div", "chronicle")
chronicle.append(lines)
panel.append(chronicle)
@@ -504,22 +643,23 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
live.push(() => {
const s = ui.stats
if (!s) return
- sub.textContent = `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · a ${s.charter.term}-minute term · seed ${s.charter.seed}`
+ sub.textContent = `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · ${s.charter.term}-minute term`
+ sub.title = `seed ${s.charter.seed}`
// Goals.
while (goalRows.length < s.goals.length) {
const line = el("div", "row goal")
- const mark = el("span", "mark")
+ const mark = el("span", "mark", "✓")
const text = el("span", "")
const value = el("span", "count")
- const left = el("span", "")
+ const left = el("span", "label")
left.append(mark, text)
line.append(left, value)
goals.append(line)
goalRows.push({ line, mark, text, value })
}
+ goals.append(goalNote)
s.goals.forEach((g, i) => {
const r = goalRows[i]!
- r.mark.textContent = g.met ? "✓" : "·"
r.line.classList.toggle("met", g.met)
r.text.textContent = g.text
r.value.textContent = g.value
@@ -527,23 +667,25 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
goalNote.textContent = s.fate.governing
? "Complete: the mayor governs on to the end of the term."
: s.fate.complete !== null
- ? `Every goal is met: hold them ${clockText(s.fate.complete)} more.`
- : `Meet every goal at once and hold them for two minutes to complete the town.`
+ ? `All met: hold them ${clockText(s.fate.complete)} more.`
+ : ""
+ goalNote.style.display = goalNote.textContent ? "" : "none"
// Approval.
moodValue.textContent = `${signed(s.mood.approval)} → ${signed(s.mood.target)}`
+ moodValue.classList.toggle("down", s.mood.approval < 0)
moodFill.style.left = `${Math.min(50, 50 + s.mood.approval / 2)}%`
moodFill.style.width = `${Math.abs(s.mood.approval) / 2}%`
moodFill.classList.toggle("low", s.mood.approval < 0)
- const parts = s.mood.parts.map((p) => `<div class="row"><span>${p.label}</span><span class="count">${signed(p.value)}</span></div>`).join("")
+ const parts = s.mood.parts.map((p) => `<div class="row"><span class="label">${p.label}</span><span class="count ${p.value > 0 ? "up" : p.value < 0 ? "down" : ""}">${signed(p.value)}</span></div>`).join("")
if (moodParts.dataset.html !== parts) {
moodParts.dataset.html = parts
moodParts.innerHTML = parts
}
- taxes.textContent = `+${s.taxes}`
- traded.textContent = signed(s.trade)
- upkeep.textContent = signed(-s.upkeep)
- admin.textContent = signed(-s.admin)
- net.textContent = `${signed(s.net)} coins`
+ money(taxes, s.taxes)
+ money(traded, s.trade)
+ money(upkeep, -s.upkeep)
+ money(admin, -s.admin)
+ money(net, s.net, " coins")
settlers.textContent = String(s.settlers)
citizens.textContent = String(s.citizens)
homes.textContent = String(s.homes)
@@ -551,24 +693,25 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
for (const b of bars) {
const share = s.homes > 0 ? s.needs[b.n] / s.homes : 0
b.fill.style.width = `${Math.round(share * 100)}%`
- b.value.textContent = `${s.needs[b.n]} of ${s.homes}`
+ b.fill.className = `fill ${share < 0.34 ? "none" : share < 0.67 ? "low" : ""}`
+ b.value.textContent = `${s.needs[b.n]}/${s.homes}`
}
- larderLine.textContent = `${s.larder} fish and bread`
+ larderLine.textContent = `${s.larder}`
crownLine.textContent = `${s.crown.met} · ${s.crown.missed}`
- crownNext.textContent = s.crown.open
- ? `Asking for ${s.crown.amount} ${goods[s.crown.good].title}: ${clockText(s.crown.left)} left, ${s.crown.reward} coins when sent.`
- : `The next request in ${clockText(s.crown.next)}. A missed one is a fine, and the town remembers the snub for a while; ${s.crown.patience} missed in a row and the crown dismisses the mayor.`
+ crownNext.innerHTML = s.crown.open
+ ? `Wants <b>${s.crown.amount} ${goods[s.crown.good].title}</b> · ${clockText(s.crown.left)} left · +${s.crown.reward} coins`
+ : `Next request in ${clockText(s.crown.next)} · ${s.crown.patience} missed in a row ends the term`
// 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)
for (const r of goodRows) {
const change = ago ? s.stock[r.g] - ago.stock[r.g] : 0
- r.value.textContent = `${s.stock[r.g]}${change !== 0 ? ` ${change > 0 ? "+" : ""}${change}/min` : ""}`
+ r.value.innerHTML = `${s.stock[r.g]}${change !== 0 ? ` <small class="${change > 0 ? "up" : "down"}">${change > 0 ? "+" : ""}${change}/min</small>` : ""}`
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.classList.toggle("on", now !== "none")
+ r.mode.className = `frame mode ${now === "none" ? "" : now}`
const price = now === "buy" ? askOf(r.g, s.prices[r.g]) : Math.round(priceOf(r.g, s.prices[r.g]) * 10) / 10
- r.name.textContent = `${goods[r.g].title} · ${price}c${s.prices[r.g] !== 100 ? ` (${s.prices[r.g]}%)` : ""}`
+ r.price.textContent = `${price}c${s.prices[r.g] !== 100 ? ` (${s.prices[r.g]}%)` : ""}`
}
const samples = s.history
const coinsSvg = sparkline(samples.map((h) => h.coins))
@@ -589,6 +732,21 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
})
}
+ /** An icon for a line of a building's or home's description, by what it is about. */
+ const lineIcon = (text: string): IconName | GoodId => {
+ if (text.startsWith("workers")) return "workers"
+ if (text.startsWith("upkeep")) return "upkeep"
+ if (text.startsWith("pays")) return "coins"
+ if (text.startsWith("needs")) return "homes"
+ if (text.startsWith("to become")) return "citizens"
+ if (text.startsWith("waiting")) return "planks"
+ if (text.includes("residents")) return "people"
+ if (text.includes("out on the roads")) return "settlers"
+ if (text.startsWith("holds")) return "jobs"
+ const made = goodIds.find((g) => text.includes(`${goods[g].title} ·`))
+ return made ?? "info"
+ }
+
const buildPanel = () => {
const p = ui.panel
live = []
@@ -598,24 +756,37 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
if (p.type === "town") return townPanel()
const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : `${home.tiers[p.tier].title}' home`
- const status = el("p", "sub")
- panel.append(header(title), status)
- const box = section(p.type === "building" ? "at work" : "household")
+ const status = el("span", "pill")
+ const about = el("p", "sub", p.type === "building" ? kinds[p.kind].blurb : p.tier === 1 ? "settlers: fish or bread from a market keeps them" : "citizens: they need bread, cloth, and faith")
+ const below = el("div", "")
+ below.append(status, about)
+ panel.append(header(title, picture(p.type === "building" ? p.kind : p.tier), below))
+ const box = section(p.type === "building" ? "at work" : "household", p.type === "building" ? "jobs" : "homes")
+ box.classList.add("lines")
const rows: Array<HTMLElement> = []
panel.append(box)
live.push(() => {
const now = ui.panel
if (!now || now.type === "build" || now.type === "town" || now.type !== p.type) return
if (now.type === "building") {
- status.textContent = now.problem ?? `${now.status} · ${kinds[now.kind].blurb}`
- status.classList.toggle("warn", now.problem !== null)
- } else status.textContent = now.tier === 1 ? "settlers: fish or bread from a market keeps them" : "citizens: they need bread, cloth, and faith"
+ status.textContent = now.problem ?? now.status
+ status.className = `pill ${now.problem !== null ? "problem" : now.status === "working" ? "working" : ""}`
+ } else {
+ status.textContent = `${home.tiers[now.tier].residents} at most`
+ status.className = "pill working"
+ }
while (rows.length < now.lines.length) {
const line = el("div", "row")
rows.push(line)
box.append(line)
}
- rows.forEach((row, i) => (row.textContent = now.lines[i] ?? ""))
+ rows.forEach((row, i) => {
+ const text = now.lines[i] ?? ""
+ if (row.dataset.text === text) return
+ row.dataset.text = text
+ row.innerHTML = `<span class="label">${icon(lineIcon(text), 16)}<span></span></span>`
+ row.querySelector(".label > span")!.textContent = text
+ })
})
if (!(p.type === "building" && p.kind === "townhall")) {
const actions = el("div", "actions")
@@ -650,6 +821,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
// Keep the old contents while the closed panel slides away.
if (p !== null) buildPanel()
panel.classList.toggle("open", p !== null)
+ document.body.classList.toggle("panel-open", p !== null)
refreshTools()
}
for (const update of live) update()
@@ -951,20 +1123,26 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
syncPanel()
const s = ui.stats
if (s) {
- coins.innerHTML = `<b>${s.coins}</b> coins <span class="${s.net >= 0 ? "up" : "down"}">${s.net >= 0 ? "+" : ""}${s.net}/min</span>`
+ 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>`
+ coins.title = "Coins in the treasury, and what it gains (or loses) a minute"
coins.classList.toggle("debt", s.coins < 0)
- people.textContent = `${s.settlers} settlers · ${s.citizens} citizens`
- jobs.textContent = `${s.employed}/${s.jobs} jobs`
const left = Math.max(0, s.charter.term * 60 - Math.floor(s.minute * 60))
- clock.innerHTML = `year ${s.season.year} · ${s.season.winter ? `<span class="winter">winter, spring in ${clockText(s.season.left)}</span>` : `winter in ${clockText(s.season.left)}`} · <b>${clockText(left)}</b> left`
- clock.title = s.season.winter ? "Winter: fields lie still, fishing is slow, and homes eat faster" : `Winter comes in ${clockText(s.season.left)}`
- approval.innerHTML = `approval <b class="${s.mood.approval < 0 ? "down" : ""}">${signed(s.mood.approval)}</b> <span class="${s.mood.target >= s.mood.approval ? "up" : "down"}">${s.mood.target > s.mood.approval ? "↑" : s.mood.target < s.mood.approval ? "↓" : ""}</span>`
- for (const [g, count] of goodCells) count.textContent = String(s.stock[g])
+ clock.innerHTML = `${icon(s.season.winter ? "winter" : "clock", 20)}<span class="stack"><b>${clockText(left)}</b><small class="${s.season.winter ? "winter" : ""}">year ${s.season.year} · ${s.season.winter ? `spring in ${clockText(s.season.left)}` : `winter in ${clockText(s.season.left)}`}</small></span>`
+ clock.title = s.season.winter ? "Winter: fields lie still, fishing is slow, and homes eat faster" : `Time left in the term · winter comes in ${clockText(s.season.left)}`
+ 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</small></span>`
+ jobs.innerHTML = `${icon("jobs", 18)}<span class="stack"><b>${s.employed}<span class="of">/${s.jobs}</span></b><small>jobs</small></span>`
+ for (const [g, count] of goodCells) {
+ count.textContent = String(s.stock[g])
+ count.parentElement!.classList.toggle("empty", s.stock[g] === 0)
+ }
// The crown's request.
request.classList.toggle("show", s.crown.open && s.fate.state === "playing")
if (s.crown.open) {
const have = s.stock[s.crown.good]
- requestText.innerHTML = `the crown asks for <b>${s.crown.amount} ${goods[s.crown.good].title}</b> (${have} in store) · <b>${clockText(s.crown.left)}</b> · ${s.crown.reward} coins`
+ 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>`
send.disabled = have < s.crown.amount
}
// What threatens the term, or is about to complete it.
@@ -980,7 +1158,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste
}
if (s.fate.complete !== null) warnings.push(`<b>Every goal met:</b> the town is complete in ${clockText(s.fate.complete)}`)
}
- const html = warnings.map((w) => `<div class="cell">${w}</div>`).join("")
+ const html = warnings.map((w) => `<div class="cell">${icon(w.startsWith("<b>Every goal") ? "goal" : "warning", 16)}<span>${w}</span></div>`).join("")
if (alarm.dataset.html !== html) {
alarm.dataset.html = html
alarm.innerHTML = html
diff --git a/src/icons.ts b/src/icons.ts
new file mode 100644
index 0000000..ec9fadf
--- /dev/null
+++ b/src/icons.ts
@@ -0,0 +1,78 @@
+/**
+ * Small line-drawn icons for the page, in the town's ink and colours: goods,
+ * the town's numbers, the tools. Each is a 16 × 16 SVG drawn with the same
+ * two line weights as the town, so they sit beside it as part of one drawing.
+ */
+import { goods, type GoodId } from "./content.ts"
+
+const ink = "#3d4943"
+const hex = (color: number) => `#${color.toString(16).padStart(6, "0")}`
+
+/** Shapes inside a 16 × 16 box: `s` strokes in ink, `f(color)` fills with an ink outline. */
+const paths: Record<string, string> = {
+ // ── Goods ──
+ wood: `<path d="M3 6.5h8.5v5H3z" fill="#d9b98c"/><ellipse cx="11.5" cy="9" rx="2" ry="2.5" fill="#f1dcb4"/><circle cx="11.5" cy="9" r=".8" fill="none"/><path d="M3 6.5a2 2.5 0 0 0 0 5" fill="none"/>`,
+ planks: `<path d="M2 10.5l7 3 5-2.5-7-3z" fill="#f0c59a"/><path d="M2 10.5v1.5l7 3v-1.5" fill="#e2a873"/><path d="M9 15v-1.5l5-2.5V12.5z" fill="#d2945c"/><path d="M2 6.5l7 3 5-2.5-7-3z" fill="#f0c59a"/><path d="M2 6.5V8l7 3V9.5" fill="#e2a873"/><path d="M9 11V9.5L14 7v1.5z" fill="#d2945c"/>`,
+ stone: `<path d="M2.5 12.5l2-6 4-2.5 4.5 2 1 6.5-5.5 1.5z" fill="#dfe1da"/><path d="M4.5 6.5l4 1.5 4.5-2M8.5 8v6" fill="none"/><path d="M8.5 8l4.5-2 1 6.5-5.5 1.5z" fill="#cbcfc7"/>`,
+ ore: `<path d="M2.5 12.5l2-6 4-2.5 4.5 2 1 6.5-5.5 1.5z" fill="#d5dae3"/><path d="M8.5 8l4.5-2 1 6.5-5.5 1.5z" fill="#bcc3d0"/><path d="M6 7.5l1-3 1 3z" fill="#5a6479"/><rect x="4.5" y="10" width="1.6" height="1.6" fill="#4a5368" stroke="none"/><rect x="10.5" y="10.5" width="1.6" height="1.6" fill="#4a5368" stroke="none"/>`,
+ tools: `<path d="M3.5 13.5l6-6" fill="none" stroke-width="2.2" stroke="#8a6a45"/><path d="M7 3.5l5.5 5.5 1.5-1.5-2-2 .5-2-2-1.5z" fill="#8f9891"/>`,
+ fish: `<path d="M2 8c2.5-3.5 7-3.5 9.5 0-2.5 3.5-7 3.5-9.5 0z" fill="#9fd0cb"/><path d="M11.5 8l3-2.5v5z" fill="#2f8c87"/><circle cx="5" cy="7.4" r=".7" fill="${ink}" stroke="none"/><path d="M7.5 6v4" fill="none" stroke-width="1"/>`,
+ wheat: `<path d="M8 14.5V4" fill="none"/><path d="M8 5.5c-2 0-2.5-2-2.5-3 1.5 0 2.5 1 2.5 3zM8 5.5c2 0 2.5-2 2.5-3-1.5 0-2.5 1-2.5 3zM8 8.5c-2 0-3-1.5-3-3 1.5 0 3 1 3 3zM8 8.5c2 0 3-1.5 3-3-1.5 0-3 1-3 3zM8 11.5c-2 0-3-1.5-3-3 1.5 0 3 1 3 3zM8 11.5c2 0 3-1.5 3-3-1.5 0-3 1-3 3z" fill="#e9cf7c"/>`,
+ flour: `<path d="M4.5 5.5h7l1 8c0 1-1.5 1.5-4.5 1.5s-4.5-.5-4.5-1.5z" fill="#f2ecdc"/><path d="M4.5 5.5c1-1 1.5-3 3.5-3s2.5 2 3.5 3" fill="#e6dcc2"/><path d="M5.5 9h5" fill="none" stroke="#c9b48a" stroke-width="2"/>`,
+ bread: `<path d="M2 10.5c0-3.5 3-5.5 6-5.5s6 2 6 5.5c0 1.5-1 2.5-2.5 2.5h-7C3 13 2 12 2 10.5z" fill="#e89a7c"/><path d="M5.5 7.5l1 2M8 6.5l1 2M10.5 7l1 2" fill="none" stroke-width="1"/>`,
+ wool: `<circle cx="8" cy="8.5" r="5.5" fill="#eceee8"/><path d="M3.5 6.5c3 1 6 1 9-1M3 9.5c3.5 1.5 7 1.5 10-1M5 13c2.5.5 5 0 7-2" fill="none" stroke-width="1"/><path d="M12 12.5l2.5 1.5" fill="none"/>`,
+ cloth: `<path d="M2.5 5.5l6-2.5 5 2.5-6 2.5z" fill="#c7aed6"/><path d="M2.5 5.5v6l5 2.5V8z" fill="#a37cbe"/><path d="M7.5 8v6l6-2.5v-6z" fill="#8a58a8"/>`,
+ // ── The town ──
+ coins: `<ellipse cx="8" cy="11.5" rx="5" ry="2" fill="#e3c25a"/><path d="M3 11.5v-2c0 1.1 2.2 2 5 2s5-.9 5-2v2" fill="#d6ae2e"/><ellipse cx="8" cy="9.5" rx="5" ry="2" fill="#f0d98a"/><path d="M3 9.5v-2c0 1.1 2.2 2 5 2s5-.9 5-2v2" fill="#d6ae2e"/><ellipse cx="8" cy="7.5" rx="5" ry="2" fill="#f5e3a6"/><ellipse cx="8" cy="7.5" rx="2" ry=".7" fill="none" stroke-width="1"/>`,
+ settlers: `<circle cx="8" cy="4.5" r="2.3" fill="#f5f6f2"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#e6c3b2"/>`,
+ citizens: `<circle cx="8" cy="5" r="2.3" fill="#f5f6f2"/><path d="M5 3h6l-.8-1.8H5.8z" fill="#8a58a8"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#c9d2da"/>`,
+ people: `<circle cx="5.5" cy="5" r="2" fill="#f5f6f2"/><circle cx="11" cy="5.5" r="2" fill="#f5f6f2"/><path d="M1.5 14c0-3 1.7-5 4-5s4 2 4 5z" fill="#e6c3b2"/><path d="M7.5 14c0-3 1.4-4.5 3.5-4.5s3.5 1.5 3.5 4.5z" fill="#c9d2da"/>`,
+ jobs: `<path d="M2.5 6.5h11v7h-11z" fill="#e9c48a"/><path d="M6 6.5V4.5h4v2" fill="none"/><path d="M2.5 9.5h11" fill="none" stroke-width="1"/><path d="M7 9h2v1.5H7z" fill="#8a6a45"/>`,
+ approval: `<path d="M8 14s-5.5-3.3-5.5-7.3C2.5 4.6 4 3 5.7 3 6.9 3 7.6 3.6 8 4.4 8.4 3.6 9.1 3 10.3 3 12 3 13.5 4.6 13.5 6.7 13.5 10.7 8 14 8 14z" fill="#e89a7c"/>`,
+ clock: `<circle cx="8" cy="8.5" r="5.5" fill="#f7f8f4"/><path d="M8 5.5v3l2 1.5" fill="none"/>`,
+ 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"/>`,
+ 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"/>`,
+ food: `<path d="M2 8c2.5-3.5 7-3.5 9.5 0-2.5 3.5-7 3.5-9.5 0z" fill="#9fd0cb"/><path d="M11.5 8l3-2.5v5z" fill="#2f8c87"/>`,
+ trade: `<path d="M2.5 5.5h9.5M9.5 3l2.5 2.5L9.5 8M13.5 10.5H4M6.5 8L4 10.5 6.5 13" fill="none"/>`,
+ treasury: `<path d="M2.5 6.5L8 3l5.5 3.5z" fill="#e3c25a"/><path d="M3.5 6.5v6M6.5 6.5v6M9.5 6.5v6M12.5 6.5v6" fill="none"/><path d="M2 13h12v1.5H2z" fill="#d6ae2e"/>`,
+ taxes: `<path d="M3.5 2.5h9v11l-1.5-1-1.5 1-1.5-1-1.5 1-1.5-1-1.5 1z" fill="#f7f8f4"/><path d="M5.5 5.5h5M5.5 8h5M5.5 10.5h3" fill="none" stroke-width="1"/>`,
+ chronicle: `<path d="M3 3.5h8.5c1 0 1.5.5 1.5 1.5v9H4.5c-1 0-1.5-.5-1.5-1.5z" fill="#f2ecdc"/><path d="M5.5 6.5h5M5.5 9h5M5.5 11.5h3" fill="none" stroke-width="1"/>`,
+ // ── Tools ──
+ select: `<path d="M4 2.5v10.5l3-2.8 2 4.3 2-.9-2-4.2h4z" fill="#f7f8f4"/>`,
+ road: `<path d="M1.5 9l6.5-4.5 6.5 4.5-6.5 4.5z" fill="#e6e8e2"/><path d="M5 7.4l1.2.8M9.8 10.6l1.2.8" fill="none" stroke-width="1"/>`,
+ 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"/>`,
+ 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"/>`,
+ load: `<path d="M2 4.5h4.5l1.5 1.5h6v7.5H2z" fill="#f3dca6"/><path d="M8 7v5M5.8 10L8 12.2 10.2 10" fill="none"/>`,
+ newTown: `<path d="M4 14.5V2" fill="none"/><path d="M4 2.5h8.5l-2 3 2 3H4z" fill="#a6c48a"/><path d="M9.5 11.5h4M11.5 9.5v4" fill="none"/>`,
+ close: `<path d="M4 4l8 8M12 4l-8 8" fill="none"/>`,
+ info: `<circle cx="8" cy="8" r="6" fill="#f7f8f4" stroke-width="1"/><path d="M8 7v4.5" fill="none" stroke-width="1.4"/><circle cx="8" cy="4.9" r=".9" fill="${ink}" stroke="none"/>`,
+ upkeep: `<path d="M8 2.5v11M5 11l3 3 3-3" fill="none" stroke="#b04a39"/>`,
+ workers: `<circle cx="8" cy="5" r="2.3" fill="#f5f6f2"/><path d="M5.3 4.5c0-2 1.2-3 2.7-3s2.7 1 2.7 3z" fill="#e3c25a" stroke-width="1"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#e9c48a"/>`
+}
+
+export type IconName = keyof typeof paths | GoodId
+export const iconNames = Object.keys(paths) as ReadonlyArray<IconName>
+
+/** An icon as an SVG string, `size` px a side. */
+export const icon = (name: IconName, size = 16, extraClass = ""): string =>
+ `<svg class="icon ${extraClass}" width="${size}" height="${size}" viewBox="0 0 16 16" aria-hidden="true" stroke="${ink}" stroke-width="1.2" stroke-linejoin="round" stroke-linecap="round">${paths[name] ?? ""}</svg>`
+
+/** An icon as an element. */
+export const iconEl = (name: IconName, size = 16, extraClass = ""): HTMLElement => {
+ const span = document.createElement("span")
+ span.className = "glyph"
+ span.innerHTML = icon(name, size, extraClass)
+ return span
+}
+
+/** A good's icon, with its colour as a fallback swatch. */
+export const goodIcon = (good: GoodId, size = 16): string => (good in paths ? icon(good, size) : `<span class="swatch" style="background:${hex(goods[good].color)}"></span>`)
diff --git a/src/present.ts b/src/present.ts
index 4aa3b81..9aec9fe 100644
--- a/src/present.ts
+++ b/src/present.ts
@@ -6,10 +6,10 @@
import { RenderSync } from "@typeonce/bevy-ts-render"
import {
- BuildingView, drawFloor, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView,
+ BuildingView, drawFloor, drawGhost, drawPlot, drawRoads, drawWater, FieldView, homeHeight, HouseView, RockView, topOf, TreeView, WalkerView, type Load,
type Doors, type Emphasis
} from "./art.ts"
-import { BUILD_TICKS, crown as crownRules, fate, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"
+import { BUILD_TICKS, crown as crownRules, fate, goodIds, goods, home, kinds, needTitle, total, type Kind } from "./content.ts"
import { around, canPlace, entrances, isRoad, key, lPath, useAt, type TileLike } from "./grid.ts"
import { inside, TILE_H, TILE_W, toGrid, toScreen, U, type Point } from "./iso.ts"
import {
@@ -19,6 +19,7 @@ import {
type GridValue, type Status as StatusValue
} from "./schema.ts"
import { capacity, CELL_STEPS, elapsed, goalsOf, larder, met, seasonAt, SITE_SHARE, taxOf, termTicks } from "./sim/index.ts"
+import { Townsfolk } from "./townsfolk.ts"
import { emptyPreview, type HitBox } from "./ui.ts"
const cellAt = (at: Point): Point => {
@@ -411,7 +412,7 @@ export const RenderWalkers = RenderSync.system(Game, {
name: "Town/RenderWalkers",
renderable: Figure,
registry: WalkerNodes,
- create: ({ renderable }) => new WalkerView(renderable.role, renderable.color),
+ create: ({ renderable }) => WalkerView.forFigure(renderable.role, renderable.color),
apply: () => {}
})
@@ -556,8 +557,14 @@ export const Animate = Game.System(
const p = walkerAt(data.route.get())
const errand = maybe(data.errand)
const roam = maybe(data.roam)
- const cargo = errand ? !errand.back || errand.count > 0 : roam ? total(roam.basket) > 0 : false
- services.walkerNodes.get(entity.id)?.update(p.x, p.y, p.dir, p.phase, cargo)
+ const load: Load = errand
+ ? { kind: "cart", good: errand.good, count: !errand.back || errand.count > 0 ? errand.count : 0 }
+ : roam?.service === "faith"
+ ? { kind: "bell" }
+ : roam && total(roam.basket) > 0
+ ? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }
+ : { kind: "none" }
+ services.walkerNodes.get(entity.id)?.update(p.x, p.y, p.dir, p.phase, load)
}
for (const { entity, data } of queries.trees.each()) services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))
for (const { entity, data } of queries.rocks.each()) {
@@ -584,6 +591,31 @@ export const DrawPreview = Game.System(
}
)
+/** Residents out walking (see `townsfolk.ts`), on the town's time: still while it waits. */
+let townsfolk: { readonly folk: Townsfolk; land: string } | null = null
+export const Stroll = Game.System(
+ "Town/Stroll",
+ {
+ queries: { houses: HouseRead },
+ resources: { grid: Game.System.readResource(Grid), land: Game.System.readResource(Land) },
+ services: { ui: Game.System.service(Ui), clock: Game.System.service(Clock), stage: Game.System.service(StageService) }
+ },
+ ({ queries, resources, services }) => {
+ const ui = services.ui
+ townsfolk ??= { folk: new Townsfolk(services.stage.objects), land: "" }
+ const mask = resources.land.get().mask
+ if (mask !== townsfolk.land) {
+ townsfolk.land = mask
+ townsfolk.folk.clear()
+ }
+ const waiting = ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")
+ const homes = queries.houses.each()
+ .filter(({ data }) => !maybe(data.site) && !maybe(data.rising))
+ .map(({ data }) => ({ ...data.tile.get(), tier: data.house.get().tier, residents: data.house.get().residents }))
+ townsfolk.folk.step(waiting ? 0 : services.clock.deltaSeconds * ui.speed, homes, resources.grid.get())
+ }
+)
+
export const present = Game.Schedule(
Interact,
DrawLand,
@@ -595,5 +627,6 @@ export const present = Game.Schedule(
RenderFields,
DrawGround,
Animate,
+ Stroll,
DrawPreview
)
diff --git a/src/townsfolk.ts b/src/townsfolk.ts
new file mode 100644
index 0000000..0c02279
--- /dev/null
+++ b/src/townsfolk.ts
@@ -0,0 +1,133 @@
+/**
+ * Residents out walking: a few from the town's homes wander its roads for a
+ * while and go back in, dressed in their household's colour (see
+ * `residentDress`). They are only for looking at: not part of the
+ * simulation, not saved, and they do nothing to the town.
+ */
+import type { Container } from "pixi.js"
+
+import { homeAt, residentDress, WalkerView } from "./art.ts"
+import type { Tier } from "./content.ts"
+import { DIRS, doors, isRoad } from "./grid.ts"
+import { U, type Point } from "./iso.ts"
+import type { GridValue } from "./schema.ts"
+
+/** A home as the townsfolk see it. */
+export interface Household {
+ readonly x: number
+ readonly y: number
+ readonly tier: Tier
+ readonly residents: number
+}
+
+interface Stroller {
+ readonly view: WalkerView
+ cell: Point
+ prev: Point | null
+ next: Point
+ /** 0 → 1 of the way from `cell` to `next`. */
+ t: number
+ /** Cells to walk before going home. */
+ left: number
+ readonly pace: number
+ /** How far from the road's middle: on the right, as carriers keep, but further out, by the kerb. */
+ readonly side: number
+ /** 0 → 1 fading in; below 0 fading out. */
+ fade: number
+}
+
+/** About one resident in this many is out walking, up to `MOST`. */
+const PER = 10
+const MOST = 40
+/** Cells a second at 1×. */
+const PACE = 0.7
+
+export class Townsfolk {
+ private readonly layer: Container
+ private folk: Array<Stroller> = []
+ private wait = 0
+
+ constructor(layer: Container) {
+ this.layer = layer
+ }
+
+ /** Everyone goes in: a new town, or one loaded. */
+ clear() {
+ for (const s of this.folk) s.view.destroy()
+ this.folk = []
+ }
+
+ /** Moves everyone on by `dt` seconds of the town's time, and sends someone out now and then. */
+ step(dt: number, homes: ReadonlyArray<Household>, grid: GridValue) {
+ if (dt <= 0) return
+ const residents = homes.reduce((n, h) => n + h.residents, 0)
+ const want = Math.min(MOST, Math.round(residents / PER))
+ this.wait -= dt
+ if (this.wait <= 0 && this.folk.length < want) {
+ this.wait = 0.4 + Math.random() * 0.8
+ this.send(homes, grid)
+ }
+ for (let i = this.folk.length - 1; i >= 0; i--) {
+ const s = this.folk[i]!
+ if (!isRoad(grid, s.cell.x, s.cell.y) || !isRoad(grid, s.next.x, s.next.y)) s.fade = Math.min(s.fade, -0.01)
+ s.t += dt * s.pace
+ while (s.t >= 1) {
+ s.t -= 1
+ s.prev = s.cell
+ s.cell = s.next
+ s.left -= 1
+ if (s.left <= 0 && s.fade > 0) s.fade = -0.01
+ s.next = this.onward(s.cell, s.prev, grid)
+ }
+ s.fade = s.fade >= 0 ? Math.min(1, s.fade + dt * 2) : s.fade - dt * 2
+ if (s.fade <= -1) {
+ s.view.destroy()
+ this.folk.splice(i, 1)
+ continue
+ }
+ this.place(s)
+ }
+ }
+
+ /** Someone leaves a home that has a road at its door. */
+ private send(homes: ReadonlyArray<Household>, grid: GridValue) {
+ const open = homes.filter((h) => h.residents > 0)
+ if (open.length === 0) return
+ const h = open[Math.floor(Math.random() * open.length)]!
+ const out = doors(grid, { x: h.x, y: h.y, size: 1 })
+ if (out.length === 0) return
+ const start = out[Math.floor(Math.random() * out.length)]!
+ const n = Math.random()
+ const view = new WalkerView(residentDress(homeAt(h.x, h.y).cloth, h.tier, n), null)
+ view.alpha = 0
+ this.layer.addChild(view)
+ const cell = { x: start.x, y: start.y }
+ this.folk.push({
+ view, cell, prev: null, next: this.onward(cell, null, grid), t: 0, left: 6 + Math.floor(Math.random() * 14),
+ pace: PACE * (h.tier === 2 ? 0.85 : 1) * (0.85 + n * 0.3), side: (4 + Math.round(n)) * U, fade: 0
+ })
+ }
+
+ /** A road cell to go on to: anywhere but back, unless the road ends. */
+ private onward(cell: Point, prev: Point | null, grid: GridValue): Point {
+ const ways = DIRS.map((d) => ({ x: cell.x + d.x, y: cell.y + d.y })).filter((c) => isRoad(grid, c.x, c.y))
+ const ahead = ways.filter((c) => !prev || c.x !== prev.x || c.y !== prev.y)
+ const choices = ahead.length > 0 ? ahead : ways
+ return choices.length > 0 ? choices[Math.floor(Math.random() * choices.length)]! : cell
+ }
+
+ private place(s: Stroller) {
+ const dir = { x: s.next.x - s.cell.x, y: s.next.y - s.cell.y }
+ // Smoothly, not on the lattice: they walk slower than the town's walkers, and stepping from unit to unit would stutter.
+ const units = Math.floor(s.t * 16)
+ const along = s.t
+ s.view.alpha = s.fade >= 0 ? s.fade : 1 + s.fade
+ s.view.update(
+ s.cell.x + 0.5 + dir.x * along - dir.y * s.side,
+ s.cell.y + 0.5 + dir.y * along + dir.x * s.side,
+ dir,
+ dir.x === 0 && dir.y === 0 ? 0 : Math.floor(units / 3) % 2,
+ { kind: "none" }
+ )
+ }
+}