Public: anyone can read this; the crew can change it.

Migrated from github.com/amirmushichge/pixel-plays

build age of empires 2. take your time and be thorough. focus on a full gamep… #115

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

vesper/pixel-plays:vesper/101-build-age-of-empires-2-take-your-time-an → main 5 commits fork

  • Merged. vesper/101-build-age-of-empires-2-take-your-time-an was merged into main as 7a8fe89.

Review

Sign in to review this change.
20 files changed +2779 −3
README.md +19 −1
@@ -44,6 +44,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
4444 | [Tug of War](tug-of-war/) | A village fete: two teams of four on a rope, a ribbon tied at its middle and a chalk line at each end. A caller beats a steady heave shown as a pulsing marker; a tap within 150 ms of the beat pulls the ribbon towards your line, a tap well off it (over 300 ms) makes your team stumble and the rope slips the other way, and not tapping lets the rival pull steadily, stronger each round. The ribbon crossing your line wins the pull, crossing theirs loses it; five pulls, three won is a win. The marker shows as a lit dot without animation under reduced motion, so it plays muted too (forged by the crew on the engine and shell above, not by the original creators; rules in `tug-of-war/rope.js`) | Tap anywhere on the picture; space |
4545 | [Sheepdog](sheepdog/) | A 90-second dusk over three hillside fields, five sheep each, scattered at the top: drag the dog (or use the arrow keys) so they flee it inside a set radius, flock together and wander when calm, and push one too hard and it bolts the wrong way; each sheep that goes through the dry-stone wall's gate and then into the hurdle pen scores, one that goes round the gate scores nothing once penned; the gate moves every field, the sun lowers with the clock, and 10 or more of 15 wins (forged by the crew on the engine and shell above, not by the original creators) | Drag the dog; arrow keys |
4646 | [Firefly Jar](firefly-jar/) | A 90-second summer night in a back garden: tap a firefly while it glows to catch it into the jar (+1, golden +3), a dim one is scared off and breaks the streak, shoo the moths before they reach the lantern; the third moth ends the night (forged by the crew on the engine and shell above, not by the original creators) | Tap; Tab or arrows + space |
47 | [Empire Age](empire/) | A real-time strategy game on a 44 by 44 map against a red bot (easy, normal or hard): four villagers and a town center each, gather food, wood, gold and stone, build houses, camps, farms and military buildings, climb the Dark, Feudal, Castle and Imperial Ages, research upgrades, train militia, spearmen, archers, knights and rams, and destroy every town center and castle of the enemy; fog of war, a minimap, attack alerts, pause, 1x/2x/4x speed, an autopilot, a save that survives a reload and a best time per level (forged by the crew on the engine and shell above, not by the original creators) | Tap or drag a box to select, tap to command, panel buttons to build and train; arrows move the view, Enter taps its centre cross, 1-9 press buttons |
4748 | [Hot Air Balloon](hot-air-balloon/) | Five flights over patchwork farm fields with hedgerows, a windsock and one field marked with a white cross: hold the burner and the balloon climbs slowly after a short lag, let go and it sinks; the air has three height bands that each blow their own way and a little differently each flight, shown by drifting cloud wisps, three arrows at the left and a pennant on the basket, so you steer only by choosing a height (the ready screen before each flight already shows that flight's winds, so read them first); touching the ground ends the flight and the landing scores by distance from the cross (on it 5, inside its field 3, a neighbouring field 1, trees or the pond 0), each flight from a new launch point; 15 or more of 25 wins; the balloon's shadow on the fields shows where it is over (forged by the crew on the engine and shell above, not by the original creators) | Press and hold the canvas; hold space or the up arrow |
4849
4950 ## Run
@@ -64,7 +65,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
6465 Every page carries Open Graph and Twitter tags (between `og:begin` and `og:end`), and `og/<id>.png` is a 1200x630 card: the game's own opening frame, scaled 2x on white; `og/home.png` is a grid of all of them. Because the games are static, `bun scripts/og.mjs` makes them without a browser: it runs each page's scripts in a `vm` against a stub DOM, captures the canvas pixels and writes the PNG (zlib only, no dependency) and the tags. Run it after adding a game or changing a scene; `serve.test.mjs` fails when a card or its tags are missing or stale. Scenes are rendered with a seeded `Math.random`, so the cards are byte-for-byte reproducible. Absolute URLs use `ORIGIN` at the top of the script (the forge production site), so change it there if the site moves.
6566
6667 ## Add a game
67 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar and Hot Air Balloon play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`.
68 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon and Empire Age play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`.
6869
6970 - `shell.js` provides the game menu, the Rules popup, the credits and the background music. The menu lists the games grouped under their kind (the not-yet-made ones last, under Soon) and scrolls within the screen; type in its find box to narrow it by a word of the title, kind, input or blurb (keys typed there never reach the game), and press Escape to close it.
7071 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
@@ -82,6 +83,23 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
8283 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
8384 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, and Hot Air Balloon's windsock and cloud wisps drift; all of it stops under `prefers-reduced-motion`.
8485
86 ## Empire Age
87
88 `empire/` is the one game that does not use `engine.js`: a strategy game needs a flat map, many units and a minimap, so it has its own small renderer (`paint.js`, an isometric 360 by 280 pixel buffer, tiles 16 by 8) and the rules live apart from the page, each module named for one concept and none depending on the DOM:
89
90 | File | What it holds |
91 |------|---------------|
92 | `tables.js` | resources, the four ages, units, buildings and technologies as data |
93 | `grid.js` | A* path finding on the tile grid |
94 | `realm.js` | the world: `newGame`, `tick`, and the commands `order`, `place`, `train`, `research`, `ageUp`, `cancel`, `rally`, `demolish`, `resign`; `snapshot` and a defensive `restore` |
95 | `regent.js` | the bot, which plays by those same commands (the autopilot runs it on the person's side) |
96 | `paint.js` | draws the state; `pick.js` turns a screen point into the entity under it |
97 | `smart.js` | what a tap means for the selection (move, attack, work, build) |
98 | `panel.js` | the command panel as plain data, and what each button does |
99 | `session.js` | the one save slot and the best time per level, in `localStorage` |
100
101 The simulation advances in 0.1 s steps with a seeded random, so a game is the same every time for the same seed and commands, and a bot-versus-bot game runs in a test. Nothing is fetched or generated outside the page: no assets, no dependencies, and the only server call is the anonymous play count every game makes. `bun test empire/` covers the rules, the bot, saving and the panel; `empire/page.test.mjs` plays the real page through the stand-in browser.
102
85103 ## License
86104 The code is under the [MIT License](LICENSE). The music is not: see [MUSIC.md](MUSIC.md).
87105
empire/grid.js added +83
@@ -0,0 +1,83 @@
1 'use strict';
2 // Path finding on the tile grid: A* with eight directions and no cutting of corners.
3 // A goal is a predicate on a tile, with a heuristic that must never overestimate the steps left.
4 (function (root) {
5 // a binary min-heap of tile numbers ordered by their cost in `f`
6 function Heap(f) {
7 const a = [];
8 return {
9 get size() { return a.length; },
10 push(v) {
11 a.push(v);
12 let i = a.length - 1;
13 while (i > 0) { const p = (i - 1) >> 1; if (f[a[p]] <= f[a[i]]) break; [a[p], a[i]] = [a[i], a[p]]; i = p; }
14 },
15 pop() {
16 const top = a[0], last = a.pop();
17 if (a.length) {
18 a[0] = last;
19 let i = 0;
20 for (;;) {
21 const l = 2 * i + 1, r = l + 1;
22 let m = i;
23 if (l < a.length && f[a[l]] < f[a[m]]) m = l;
24 if (r < a.length && f[a[r]] < f[a[m]]) m = r;
25 if (m === i) break;
26 [a[m], a[i]] = [a[i], a[m]]; i = m;
27 }
28 }
29 return top;
30 },
31 };
32 }
33
34 const DIRS = [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, Math.SQRT2], [1, -1, Math.SQRT2], [-1, 1, Math.SQRT2], [-1, -1, Math.SQRT2]];
35 const LIMIT = 6000; // tiles looked at before giving up on a path
36
37 // tiles from (sx, sy) to the first tile where goal(x, y) holds, as [[x, y], ...] without the start; null when unreachable.
38 // `blocked` is a Uint8Array of size*size; the start tile may itself be blocked (a unit pushed out of a new building).
39 function findPath(blocked, size, sx, sy, goal, h) {
40 sx = Math.max(0, Math.min(size - 1, sx | 0)); sy = Math.max(0, Math.min(size - 1, sy | 0));
41 if (goal(sx, sy)) return [];
42 const n = size * size, g = new Float32Array(n).fill(Infinity), f = new Float32Array(n), from = new Int32Array(n).fill(-1), done = new Uint8Array(n);
43 const heap = Heap(f), start = sy * size + sx;
44 g[start] = 0; f[start] = h(sx, sy); heap.push(start);
45 let looked = 0;
46 while (heap.size && looked++ < LIMIT) {
47 const cur = heap.pop();
48 if (done[cur]) continue;
49 done[cur] = 1;
50 const cx = cur % size, cy = (cur / size) | 0;
51 if (goal(cx, cy)) {
52 const path = [];
53 for (let i = cur; i !== start; i = from[i]) path.push([i % size, (i / size) | 0]);
54 return path.reverse();
55 }
56 for (const [dx, dy, c] of DIRS) {
57 const nx = cx + dx, ny = cy + dy;
58 if (nx < 0 || ny < 0 || nx >= size || ny >= size) continue;
59 const ni = ny * size + nx;
60 if (blocked[ni] || done[ni]) continue;
61 if (dx && dy && (blocked[cy * size + nx] || blocked[ny * size + cx])) continue;
62 const ng = g[cur] + c;
63 if (ng < g[ni]) { g[ni] = ng; from[ni] = cur; f[ni] = ng + h(nx, ny); heap.push(ni); }
64 }
65 }
66 return null;
67 }
68 // the nearest tile (by rings) to (x, y) for which ok(tx, ty) holds, within `max` rings
69 function nearestTile(size, x, y, ok, max = 12) {
70 x |= 0; y |= 0;
71 for (let r = 0; r <= max; r++) {
72 for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) {
73 if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
74 const tx = x + dx, ty = y + dy;
75 if (tx >= 0 && ty >= 0 && tx < size && ty < size && ok(tx, ty)) return [tx, ty];
76 }
77 }
78 return null;
79 }
80
81 const api = { findPath, nearestTile, LIMIT };
82 if (typeof module !== 'undefined') module.exports = api; else root.Grid = api;
83 })(typeof window !== 'undefined' ? window : globalThis);
empire/index.html added +508
@@ -0,0 +1,508 @@
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
6 <title>Empire Age</title>
7 <!-- og:begin -->
8 <meta name="description" content="A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/empire/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Empire Age">
13 <meta property="og:description" content="A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/empire/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/empire.png">
16 <meta property="og:image:type" content="image/png">
17 <meta property="og:image:width" content="1200">
18 <meta property="og:image:height" content="630">
19 <meta property="og:image:alt" content="Empire Age: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #3a5fa8; --line: #d9d6cf; }
24 * { box-sizing: border-box; }
25 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
27 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
28 #app { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; padding: max(40px, calc(env(safe-area-inset-top) + 34px)) max(10px, env(safe-area-inset-left)) max(44px, calc(env(safe-area-inset-bottom) + 34px)); gap: 6px; }
29 #bar { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px 14px; width: 100%; max-width: 760px; font-variant-numeric: tabular-nums; }
30 #bar b { font-weight: 600; color: var(--accent); }
31 #bar span { color: var(--muted); }
32 #stage { flex: 1 1 auto; min-height: 0; width: 100%; max-width: 760px; display: grid; place-items: center; }
33 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: crosshair; outline: none; user-select: none; -webkit-user-select: none; background: #0a0a10; }
34 canvas:focus-visible { box-shadow: 0 0 0 2px var(--accent); }
35 #dock { width: 100%; max-width: 760px; height: min(36vh, 230px); display: flex; flex-direction: column; gap: 4px; }
36 #cmds { overflow-y: auto; min-height: 0; flex: 1 1 auto; align-content: flex-start; }
37 #dock > * { flex: none; }
38 #dock > #cmds { flex: 1 1 auto; }
39 noscript p { position: fixed; z-index: 3; inset: 40px 0 auto; margin: 0; padding: 12px 16px; background: var(--paper); }
40 #info { min-height: 1.35em; }
41 #queue { min-height: 1.35em; margin: 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 4px 10px; color: var(--muted); }
42 #cmds, #ctl { display: flex; flex-wrap: wrap; gap: 6px; }
43 button { font: inherit; color: var(--ink); background: var(--paper); border: 1px solid var(--ink); padding: 6px 9px; min-height: 34px; cursor: pointer; }
44 button:hover, button:focus-visible { background: var(--ink); color: var(--paper); outline: none; }
45 button[aria-disabled="true"] { color: var(--muted); border-color: var(--line); background: var(--paper); }
46 button small { display: block; color: var(--muted); font-size: 11px; }
47 button:hover small, button:focus-visible small { color: #cfcbc2; }
48 #ctl button { border-color: var(--line); color: var(--muted); padding: 4px 8px; min-height: 28px; }
49 #ctl button:hover, #ctl button:focus-visible { color: var(--paper); border-color: var(--ink); }
50 #ctl button[aria-pressed="true"] { color: var(--ink); border-color: var(--ink); }
51 #status { color: var(--muted); min-height: 1.35em; }
52 @media (max-width: 600px) { #bar { gap: 2px 10px; font-size: 12px; } #cmds, #ctl { gap: 4px; } button { padding: 4px 7px; } #app { padding-bottom: max(76px, calc(env(safe-area-inset-bottom) + 62px)); } }
53 </style>
54 </head>
55 <body>
56 <noscript>
57 <p>Empire Age needs JavaScript. It is a real-time strategy game against a bot: gather food, wood, gold and stone with villagers, build houses, camps, farms and a barracks, climb the Feudal, Castle and Imperial Ages, train soldiers, and destroy every town center and castle of the red enemy to win. Losing all of yours is a defeat.</p>
58 </noscript>
59 <div id="app">
60 <div id="bar" aria-label="Resources">
61 <div><b id="food">200</b> <span>food</span></div>
62 <div><b id="wood">200</b> <span>wood</span></div>
63 <div><b id="gold">100</b> <span>gold</span></div>
64 <div><b id="stone">100</b> <span>stone</span></div>
65 <div><b id="pop">4/5</b> <span>population</span></div>
66 <div><b id="age">Dark Age</b></div>
67 <div><b id="clock">0:00</b></div>
68 <div><b id="idle">0</b> <span>idle</span></div>
69 </div>
70 <div id="stage"><canvas id="c" tabindex="0" aria-label="Empire Age: an isometric map with your town center, villagers, forests and mines, and an enemy town in the far corner. Tap or drag a box to select, tap the map to move or work, press the buttons below to build and train. Arrow keys move the view and Enter taps the cross in the middle of it; 1 to 9 press the buttons, period selects an idle villager, comma the army, H the town center, P pauses."></canvas></div>
71 <div id="dock">
72 <div id="info"></div>
73 <ol id="queue"></ol>
74 <div id="cmds"></div>
75 <div id="status" role="status" aria-live="polite"></div>
76 <div id="ctl">
77 <button id="pause" type="button" aria-pressed="false">pause</button>
78 <button id="speed" type="button">speed 1x</button>
79 <button id="auto" type="button" aria-pressed="false">autopilot</button>
80 <button id="new" type="button">new game</button>
81 <button id="resign" type="button">resign</button>
82 <button id="full" type="button" hidden>full screen</button>
83 <button id="mute" type="button" aria-pressed="false">sound on</button>
84 </div>
85 </div>
86 </div>
87 <script src="../shell.js"></script>
88 <script>
89 PixelPlays.mount({
90 id: 'empire',
91 rules: [
92 'Gather food, wood, gold and stone with villagers: select them, then tap a tree, berry bush or mine. They carry it to the nearest drop-off.',
93 'Build houses for population, camps and farms for income, then a barracks. Reach the Feudal, Castle and Imperial Age at the town center.',
94 'Train soldiers and research upgrades. Spearmen beat knights, archers beat spearmen, knights beat archers, rams beat buildings.',
95 'Destroy every town center and castle of the red enemy to win. Lose all of yours and you lose. The game saves itself.',
96 'Touch: tap to select or command, drag the map, the minimap jumps the view. Mouse: drag a box, right-click commands. Keys: arrows move the view, Enter taps the cross, 1-9 press buttons.',
97 ],
98 });
99 </script>
100 <script src="tables.js"></script>
101 <script src="grid.js"></script>
102 <script src="realm.js"></script>
103 <script src="regent.js"></script>
104 <script src="paint.js"></script>
105 <script src="pick.js"></script>
106 <script src="smart.js"></script>
107 <script src="panel.js"></script>
108 <script src="session.js"></script>
109 <script>
110 'use strict';
111
112 const W = 360, H = 280;
113 const canvas = document.getElementById('c');
114 canvas.width = W; canvas.height = H;
115 const ctx = canvas.getContext('2d');
116 const image = ctx.createImageData(W, H);
117 const pix = new Uint32Array(image.data.buffer);
118 const $ = id => document.getElementById(id);
119 // write text only when it differs, so a screen reader is not told the same thing again
120 const shown = new Map();
121 function setText(id, text) { text = String(text); if (shown.get(id) !== text) { shown.set(id, text); $(id).textContent = text; } }
122 const reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
123
124 const V = { camX: 0, camY: 0, sel: new Set(), ghost: null, box: null, marks: [], still: reduced };
125 let S = null; // the game
126 let mode = 'play', placeKind = ''; // what the next tap on the map does
127 let menu = false; // the new-game choices are showing
128 let speed = 1, paused = false, auto = false, kbd = false;
129 let cursor = null; // last pointer position over the map, for the placement ghost
130 let message = '', messageUntil = 0, clockNow = 0;
131 let model = null, modelKey = '', modelAt = 0, hudAt = 0, saveAt = 0, acc = 0, resignArmed = -99;
132 let alertAt = null, lastTap = { t: -9, id: 0 };
133 const keys = new Set();
134
135 /* ---------- a game to play ---------- */
136 function start(level, seed) {
137 S = Realm.newGame(seed, level);
138 V.sel.clear(); V.marks.length = 0; V.ghost = null; V.box = null;
139 mode = 'play'; menu = false; acc = 0; alertAt = null;
140 const tc = S.ents.find(e => e.t === 'b' && e.owner === 0 && e.kind === 'town-center');
141 const [x, y] = Realm.centre(tc);
142 Paint.centreOn(V, x, y, W, H);
143 Session.forget(localStorage);
144 say('Your four villagers wait by the town center. Drag a box round them, then tap the berries or a tree.', 8);
145 }
146 function load() {
147 const saved = Session.read(localStorage);
148 if (!saved) return false;
149 S = saved;
150 const home = S.ents.find(e => e.t === 'b' && e.owner === 0 && Tables.KEEPS.includes(e.kind)) || S.ents.find(e => e.owner === 0);
151 const [x, y] = Realm.centre(home);
152 Paint.centreOn(V, x, y, W, H);
153 menu = !!S.over;
154 say(S.over ? overLine() : 'Welcome back: your game was saved.', 6);
155 return true;
156 }
157 const levelName = () => Realm.LEVELS[S.level].name;
158
159 /* ---------- words ---------- */
160 const clock = t => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, '0')}`;
161 function say(text, seconds = 4) { message = text; messageUntil = clockNow + seconds; hudAt = -9; }
162 let lineFor = null, lineText = '';
163 function overLine() {
164 if (lineFor === S.over) return lineText;
165 lineFor = S.over;
166 lineText = composeOver();
167 return lineText;
168 }
169 function composeOver() {
170 const me = Realm.score(S, 0), won = S.over.winner === 0, at = clock(S.over.time);
171 if (won) {
172 const best = Session.best(localStorage, S.level, S.over.time);
173 return `victory · the enemy has fallen at ${at} · ${me.made} trained, ${me.killed} defeated${best.fresh ? ' · new best' : ' · best ' + clock(best.time)} (${levelName()})`;
174 }
175 return `${S.over.resigned ? 'defeat · you gave up' : 'defeat · your town has fallen'} at ${at} · ${me.made} trained, ${me.killed} defeated (${levelName()})`;
176 }
177
178 /* ---------- sound ---------- */
179 let audio = null, muted = false;
180 function ensureAudio() {
181 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
182 const AC = window.AudioContext || window.webkitAudioContext;
183 if (AC) audio = new AC();
184 }
185 function sound(kind) {
186 if (!audio || muted) return;
187 const spec = { tick: [700, 900, .05, .03, 'square'], ok: [440, 660, .12, .05, 'sine'], build: [260, 520, .25, .06, 'triangle'], alarm: [520, 330, .35, .07, 'sawtooth'], win: [440, 880, .8, .07, 'sine'], lose: [220, 70, .8, .07, 'sawtooth'], no: [180, 120, .1, .04, 'square'] }[kind];
188 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
189 osc.type = spec[4];
190 osc.frequency.setValueAtTime(spec[0], now);
191 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
192 gain.gain.setValueAtTime(spec[3], now);
193 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
194 osc.connect(gain).connect(audio.destination);
195 osc.start(now); osc.stop(now + spec[2] + .01);
196 }
197
198 /* ---------- commands ---------- */
199 const selected = () => [...V.sel];
200 function select(ids) {
201 V.sel.clear();
202 for (const id of ids) V.sel.add(id);
203 refresh();
204 }
205 function flash(x, y) { V.marks.push({ x, y, age: 0, color: Paint.rgb(120, 255, 140) }); }
206 function focus(x, y) { Paint.centreOn(V, x, y, W, H); }
207
208 function finishMode() { mode = 'play'; V.ghost = null; refresh(); }
209 function ghostAt(wx, wy) {
210 const d = Tables.BUILDINGS[placeKind], x = Math.round(wx - d.size / 2), y = Math.round(wy - d.size / 2);
211 return { kind: placeKind, x, y, ok: !Realm.whyNot(S, 0, placeKind, x, y) };
212 }
213 function tapAt(x, y, right) {
214 if (S.over || paused) return;
215 const [wx, wy] = Paint.toWorld(V, x, y);
216 if (mode === 'place') {
217 const g = ghostAt(wx, wy), r = Realm.place(S, 0, placeKind, g.x, g.y, selected());
218 if (r.ok) { sound('build'); flash(g.x + 1, g.y + 1); say(`${Tables.BUILDINGS[placeKind].name} laid out: your villagers are on it.`); finishMode(); }
219 else { sound('no'); say(r.why[0].toUpperCase() + r.why.slice(1) + '.'); V.ghost = g; }
220 return;
221 }
222 const target = Pick.pick(S, V, x, y);
223 if (mode === 'rally') {
224 const b = S.byId.get(selected()[0]);
225 if (b && Realm.rally(S, 0, b.id, wx, wy, target && target.t === 'r' ? target.id : 0)) { sound('ok'); flash(wx, wy); say('New units will go there.'); }
226 finishMode();
227 return;
228 }
229 if (mode === 'amove') {
230 if (Realm.order(S, 0, selected(), { type: 'amove', x: wx, y: wy })) { sound('ok'); flash(wx, wy); }
231 finishMode();
232 return;
233 }
234 const cmd = Smart.intent(S, selected(), target, wx, wy);
235 if (cmd && (right || !target || target.owner !== 0 || target.t === 'b')) {
236 if (Smart.issue(S, selected(), cmd, target)) {
237 sound('ok');
238 const [fx, fy] = target ? (target.t === 'r' ? [target.x + .5, target.y + .5] : Realm.centre(target)) : [wx, wy];
239 flash(fx, fy);
240 }
241 refresh();
242 return;
243 }
244 if (right) return;
245 if (target) {
246 const again = lastTap.id === target.id && clockNow - lastTap.t < .4;
247 lastTap = { t: clockNow, id: target.id };
248 if (again && target.t === 'u' && target.owner === 0) select(Pick.sameKindOnScreen(S, V, target, W, H));
249 else select([target.id]);
250 sound('tick');
251 } else if (V.sel.size) select([]);
252 }
253 function run(act) {
254 if (!act) return;
255 if (act.t === 'new') { start(act.level, (Date.now() & 0xffffff) | 1); say(`A new game on ${Realm.LEVELS[act.level].name}.`); refresh(); return; }
256 const r = Panel.perform(S, selected(), act);
257 if (!r.ok) { sound('no'); say(r.why ? r.why[0].toUpperCase() + r.why.slice(1) + '.' : 'Not now.'); return; }
258 sound('ok');
259 if (r.mode === 'place') { mode = 'place'; placeKind = r.kind; menu = false; V.ghost = null; say(`Tap where the ${Tables.BUILDINGS[r.kind].name.toLowerCase()} goes.`, 30); }
260 else if (r.mode) { mode = r.mode; V.ghost = null; if (r.mode === 'rally') say('Tap where new units should gather, or on a tree or mine.', 30); else if (r.mode === 'amove') say('Tap where the army marches, fighting what it meets.', 30); }
261 if (r.select) select(r.select);
262 if (r.focus) focus(r.focus.x, r.focus.y);
263 refresh();
264 }
265 function resign() {
266 if (S.over) return;
267 if (clockNow - resignArmed > 4) { resignArmed = clockNow; say('Press resign again to give up.', 4); return; }
268 Realm.resign(S, 0);
269 settle();
270 }
271
272 /* ---------- the panel ---------- */
273 const cmds = $('cmds');
274 function levelButtons() {
275 return Realm.LEVELS.map((l, i) => ({ id: 'level-' + i, label: l.name[0].toUpperCase() + l.name.slice(1), sub: i === 1 ? 'a fair fight' : i === 0 ? 'the bot gathers slower' : 'the bot gathers faster', act: { t: 'new', level: i }, on: true, why: null, hot: String(i + 1) }))
276 .concat([{ id: 'level-x', label: S.over ? 'Look at the map' : 'Keep playing', sub: '', act: { t: 'close' }, on: true, why: null, hot: '4' }]);
277 }
278 function refresh() { modelAt = -9; }
279 function rebuild() {
280 const m = Panel.model(S, selected().filter(id => S.byId.has(id)), mode);
281 if (menu) m.buttons = levelButtons();
282 const key = JSON.stringify([m.info, m.queue, m.buttons.map(b => [b.id, b.on, b.sub, b.why])]);
283 model = m;
284 setText('info', menu ? (S.over ? 'Pick a level for the next game.' : 'Start a new game? Pick the level; this game is lost.') : m.info);
285 if (key === modelKey) return;
286 modelKey = key;
287 const q = $('queue');
288 q.textContent = '';
289 for (const it of m.queue) {
290 const li = document.createElement('li');
291 const b = document.createElement('button');
292 b.type = 'button'; b.dataset.q = String(it.i); b.textContent = '× ' + it.text; b.setAttribute('aria-label', 'cancel ' + it.text);
293 b.style.minHeight = '34px'; b.style.padding = '4px 8px'; b.style.border = '1px solid #d9d6cf'; b.style.color = '#8b877f';
294 li.append(b); q.append(li);
295 }
296 cmds.textContent = '';
297 m.buttons.forEach((b, i) => {
298 const el = document.createElement('button');
299 el.type = 'button'; el.dataset.i = String(i);
300 el.setAttribute('aria-disabled', String(!b.on));
301 if (b.why) el.title = b.why;
302 el.textContent = (b.hot ? b.hot + ' ' : '') + b.label;
303 if (b.sub || b.why) { const small = document.createElement('small'); small.textContent = b.why || b.sub; el.append(small); }
304 cmds.append(el);
305 });
306 }
307 cmds.addEventListener('click', e => {
308 ensureAudio();
309 const el = e.target.closest ? e.target.closest('button') : e.target;
310 if (!el || el.dataset.i === undefined || !model) return;
311 press(model.buttons[+el.dataset.i]);
312 });
313 $('queue').addEventListener('click', e => {
314 const el = e.target.closest ? e.target.closest('button') : e.target;
315 if (el && el.dataset.q !== undefined) run({ t: 'cancel', i: +el.dataset.q });
316 });
317 function press(b) {
318 if (!b) return;
319 if (b.act.t === 'close') { menu = false; refresh(); return; }
320 if (!b.on) { sound('no'); say(b.why ? b.why[0].toUpperCase() + b.why.slice(1) + '.' : 'Not now.'); return; }
321 run(b.act);
322 }
323
324 /* ---------- the controls ---------- */
325 const bind = (id, fn) => $(id).addEventListener('click', () => { ensureAudio(); fn(); });
326 bind('pause', () => setPaused(!paused));
327 bind('speed', () => { speed = speed === 1 ? 2 : speed === 2 ? 4 : 1; $('speed').textContent = 'speed ' + speed + 'x'; });
328 bind('auto', () => { auto = !auto; $('auto').setAttribute('aria-pressed', String(auto)); say(auto ? 'The autopilot plays your side.' : 'You have the town again.'); });
329 bind('new', () => { menu = !menu; refresh(); });
330 bind('resign', resign);
331 const muteButton = $('mute');
332 muteButton.addEventListener('click', () => {
333 muted = !muted;
334 muteButton.textContent = muted ? 'sound off' : 'sound on';
335 muteButton.setAttribute('aria-pressed', String(muted));
336 });
337 function setPaused(on) { paused = on; $('pause').setAttribute('aria-pressed', String(on)); $('pause').textContent = on ? 'resume' : 'pause'; if (on) save(); }
338
339 /* ---------- the pointer ---------- */
340 let drag = null;
341 function at(e) {
342 const r = canvas.getBoundingClientRect();
343 return [(e.clientX - r.left) * W / (r.width || W), (e.clientY - r.top) * H / (r.height || H)];
344 }
345 canvas.addEventListener('contextmenu', e => e.preventDefault());
346 canvas.addEventListener('pointerdown', e => {
347 ensureAudio();
348 kbd = false;
349 const [x, y] = at(e);
350 try { canvas.setPointerCapture(e.pointerId); } catch {}
351 if (e.button === 2) { tapAt(x, y, true); return; }
352 if (e.button !== undefined && e.button > 0) return;
353 drag = { x, y, camX: V.camX, camY: V.camY, moved: false, mini: Paint.miniAt(x, y), mouse: e.pointerType === 'mouse', shift: !!e.shiftKey };
354 if (drag.mini) { const [wx, wy] = Paint.miniWorld(x, y); focus(wx, wy); }
355 });
356 canvas.addEventListener('pointermove', e => {
357 const [x, y] = at(e);
358 cursor = [x, y];
359 if (mode === 'place' && !drag) { const [wx, wy] = Paint.toWorld(V, x, y); V.ghost = ghostAt(wx, wy); }
360 if (!drag) return;
361 if (!e.buttons) { drag = null; V.box = null; return; }
362 if (!drag.moved && Math.hypot(x - drag.x, y - drag.y) > 5) drag.moved = true;
363 if (!drag.moved) return;
364 if (drag.mini) { const [wx, wy] = Paint.miniWorld(x, y); focus(wx, wy); }
365 else if (drag.mouse || drag.shift) V.box = { x0: drag.x, y0: drag.y, x1: x, y1: y };
366 else { V.camX = drag.camX - (x - drag.x); V.camY = drag.camY - (y - drag.y); Paint.clampCam(V, W, H); }
367 });
368 function release(e) {
369 if (!drag) return;
370 const d = drag, [x, y] = at(e);
371 drag = null;
372 if (d.mini) return;
373 if (V.box) {
374 const ids = Pick.inBox(S, V, V.box.x0, V.box.y0, V.box.x1, V.box.y1);
375 V.box = null;
376 if (ids.length) { select(ids); sound('tick'); }
377 return;
378 }
379 if (!d.moved) tapAt(x, y, false);
380 }
381 canvas.addEventListener('pointerup', release);
382 canvas.addEventListener('pointercancel', () => { drag = null; V.box = null; });
383
384 /* ---------- the keyboard ---------- */
385 const PAN = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1], a: [-1, 0], d: [1, 0], w: [0, -1], s: [0, 1] };
386 document.addEventListener('keydown', e => {
387 const k = e.key, onButton = e.target && e.target.tagName === 'BUTTON';
388 if (e.ctrlKey || e.metaKey || e.altKey) return;
389 ensureAudio();
390 if (PAN[k] || PAN[k && k.toLowerCase()]) { kbd = true; keys.add(PAN[k] ? k : k.toLowerCase()); e.preventDefault(); return; }
391 if (onButton && (k === 'Enter' || k === ' ')) return;
392 if (k >= '1' && k <= '9') { if (model) press(model.buttons[+k - 1]); e.preventDefault(); return; }
393 if (k === 'Enter') { kbd = true; const [x, y] = [W / 2, H / 2]; if (mode === 'place') { const [wx, wy] = Paint.toWorld(V, x, y); V.ghost = ghostAt(wx, wy); } tapAt(x, y, false); e.preventDefault(); }
394 else if (k === ' ') { kbd = true; if (alertAt && clockNow - alertAt.t < 20) focus(alertAt.x, alertAt.y); else run({ t: 'home' }); e.preventDefault(); }
395 else if (k === '.') run({ t: 'idle' });
396 else if (k === ',') run({ t: 'army' });
397 else if (k === 'h' || k === 'H') run({ t: 'home' });
398 else if (k === 'Escape') { if (mode !== 'play') finishMode(); else if (menu) { menu = false; refresh(); } else select([]); }
399 else if (k === 'p' || k === 'P') setPaused(!paused);
400 else if (k === 'f' || k === 'F') $('speed').click();
401 else if (k === 'r' || k === 'R') resign();
402 else if (k === 'Delete') run({ t: 'demolish' });
403 else if (k === 'x' || k === 'X') run({ t: 'stop' });
404 });
405 document.addEventListener('keyup', e => { keys.delete(e.key); if (e.key && e.key.toLowerCase) keys.delete(e.key.toLowerCase()); });
406 document.addEventListener('visibilitychange', () => { if (document.hidden) { keys.clear(); save(); } });
407 window.addEventListener && window.addEventListener('pagehide', save);
408 window.addEventListener && window.addEventListener('blur', () => keys.clear());
409
410 /* ---------- the loop ---------- */
411 function settle() {
412 menu = true;
413 Session.forget(localStorage);
414 say('', 0);
415 sound(S.over.winner === 0 ? 'win' : 'lose');
416 refresh();
417 }
418 function react(ev) {
419 for (const e of ev) {
420 if (e.type === 'alert') { alertAt = { x: e.x, y: e.y, t: clockNow }; say('Your people are under attack: press space to look.', 6); sound('alarm'); }
421 else if (e.type === 'built' && e.owner === 0) { say(Tables.BUILDINGS[e.kind].name + ' built.'); sound('build'); refresh(); }
422 else if (e.type === 'age' && e.owner === 0) { say('You reach the ' + Tables.AGES[e.age].name + '.', 6); sound('win'); refresh(); }
423 else if (e.type === 'tech' && e.owner === 0) { say(Tables.TECHS[e.id].name + ' researched.'); sound('ok'); }
424 else if (e.type === 'trained' && e.owner === 0 && e.kind !== 'villager') { say(Tables.UNITS[e.kind].name + ' ready.', 2); }
425 else if (e.type === 'housed') say('Build more houses: training waits for room.', 5);
426 else if (e.type === 'lost' && e.owner === 0 && e.building) say('You lost a ' + Tables.BUILDINGS[e.kind].name.toLowerCase() + '.', 5);
427 else if (e.type === 'over') settle();
428 }
429 }
430 function save() { if (S && !S.over) Session.write(localStorage, S); }
431
432 function hud() {
433 const p = S.players[0], r = p.res;
434 setText('food', Math.floor(r.food)); setText('wood', Math.floor(r.wood));
435 setText('gold', Math.floor(r.gold)); setText('stone', Math.floor(r.stone));
436 setText('pop', Realm.popOf(S, 0) + '/' + Realm.popCap(S, 0));
437 setText('age', Tables.AGES[p.age].name);
438 setText('clock', clock(S.over ? S.over.time : S.time));
439 setText('idle', S.ents.filter(e => e.t === 'u' && e.owner === 0 && e.kind === 'villager' && e.o === 'idle').length);
440 const hint = S.over ? overLine() : paused ? 'Paused.' : mode === 'place' ? `Tap where the ${Tables.BUILDINGS[placeKind].name.toLowerCase()} goes (Escape cancels).` : mode === 'rally' ? 'Tap where new units should gather.' : mode === 'amove' ? 'Tap where the army marches.' : '';
441 setText('status', S.over ? hint : clockNow < messageUntil ? message : hint);
442 }
443
444 function frame(now) {
445 const dt = Math.min(.1, Math.max(0, (now - (frame.last || now)) / 1000));
446 frame.last = now;
447 clockNow += dt;
448 V.time = clockNow;
449 const dir = [0, 0];
450 for (const k of keys) { const v = PAN[k]; if (v) { dir[0] += v[0]; dir[1] += v[1]; } }
451 if (dir[0] || dir[1]) { V.camX += dir[0] * 170 * dt; V.camY += dir[1] * 130 * dt; Paint.clampCam(V, W, H); }
452 if (!paused && !S.over) {
453 acc += dt * speed;
454 for (let n = 0; acc >= Realm.DT && n < 24 && !S.over; n++) {
455 acc -= Realm.DT;
456 Regent.step(S, 1, Realm.DT);
457 if (auto) Regent.step(S, 0, Realm.DT);
458 react(Realm.tick(S, Realm.DT));
459 }
460 if (acc > 1) acc = 0;
461 if (clockNow - saveAt > 10) { saveAt = clockNow; save(); }
462 }
463 for (const m of V.marks) m.age += dt;
464 V.marks = V.marks.filter(m => m.age < .6);
465 if (clockNow - modelAt > .25) { modelAt = clockNow; rebuild(); }
466 if (clockNow - hudAt > .2) { hudAt = clockNow; hud(); }
467 Paint.draw(pix, W, H, S, V);
468 if (kbd && !S.over) crosshair();
469 ctx.putImageData(image, 0, 0);
470 requestAnimationFrame(frame);
471 }
472 // the cross in the middle of the view that Enter taps
473 function crosshair() {
474 const white = Paint.rgb(255, 255, 255), dark = Paint.rgb(20, 20, 30), cx = W / 2, cy = H / 2;
475 for (const d of [2, 3, 4, 5]) for (const [x, y] of [[cx + d, cy], [cx - d, cy], [cx, cy + d], [cx, cy - d]]) pix[y * W + x] = d === 5 ? dark : white;
476 }
477
478 /* ---------- fit and boot ---------- */
479 function fit() {
480 const stage = $('stage'), w = stage.clientWidth || W, h = stage.clientHeight || H;
481 let k = Math.min(w / W, h / H);
482 if (k >= 2) k = Math.floor(k);
483 k = Math.max(.5, k);
484 canvas.style.width = Math.floor(W * k) + 'px';
485 canvas.style.height = Math.floor(H * k) + 'px';
486 }
487 addEventListener('resize', fit);
488 // full screen: the app fills the screen, the canvas refits when it changes
489 const fsOn = () => document.fullscreenElement || document.webkitFullscreenElement;
490 const root = $('app');
491 if (root.requestFullscreen || root.webkitRequestFullscreen) {
492 $('full').hidden = false;
493 $('full').addEventListener('click', () => {
494 if (fsOn()) (document.exitFullscreen || document.webkitExitFullscreen).call(document);
495 else Promise.resolve((root.requestFullscreen || root.webkitRequestFullscreen).call(root)).catch(() => {});
496 });
497 const synced = () => { $('full').textContent = fsOn() ? 'exit full screen' : 'full screen'; fit(); };
498 document.addEventListener('fullscreenchange', synced);
499 document.addEventListener('webkitfullscreenchange', synced);
500 }
501 if (!load()) start(1, (Date.now() & 0xffffff) | 1);
502 fit();
503 rebuild();
504 hud();
505 requestAnimationFrame(frame);
506 </script>
507 </body>
508 </html>
empire/page.test.mjs added +191
@@ -0,0 +1,191 @@
1 import { test, expect } from 'bun:test';
2 import { boot } from '../playtest.mjs';
3
4 // the screen point of a tile point, read off the page's own camera
5 const screen = (g, x, y, z = 0) => g.read(`Paint.proj(V, ${x}, ${y}, ${z})`);
6 const selectVillagers = g => { const [x, y] = screen(g, ...g.read('Realm.centre(S.ents.find(e => e.kind === "town-center" && e.owner === 0))')); g.drag([x - 70, y - 20], [x + 70, y + 70], .4); };
7 const press = (g, id) => g.press(String(g.read(`model.buttons.findIndex(b => b.id === '${id}') + 1`)));
8
9 test('a box round the villagers selects them, and a tap on a tree sends them to cut it', () => {
10 const g = boot('empire');
11 g.run(.5);
12 selectVillagers(g);
13 expect(g.el('info').textContent).toMatch(/4 villagers · 4 idle/);
14 const tree = g.read('Realm.nearest(S, 12, 30, e => e.kind === "tree")');
15 const [x, y] = screen(g, tree.x + .5, tree.y + .5, 6);
16 g.tap(x, y);
17 expect(g.read('S.ents.filter(e => e.kind === "villager" && e.owner === 0 && e.o === "gather").length')).toBe(4);
18 const wood = g.read('S.players[0].res.wood');
19 g.run(60);
20 expect(g.read('S.players[0].res.wood')).toBeGreaterThan(wood);
21 expect(Number(g.el('wood').textContent)).toBeGreaterThan(wood);
22 expect(g.errors).toEqual([]);
23 }, 30000);
24
25 test('a building is chosen on the panel, placed with a tap and paid for', () => {
26 const g = boot('empire');
27 g.run(.5);
28 selectVillagers(g);
29 g.run(.5);
30 press(g, 'build-house');
31 expect(g.read('mode')).toBe('place');
32 expect(g.el('status').textContent).toMatch(/Tap where the house goes/);
33 const spot = g.read('(() => { for (let y = 24; y < 40; y++) for (let x = 6; x < 30; x++) if (!Realm.whyNot(S, 0, "house", x, y)) return [x, y]; })()');
34 const [sx, sy] = screen(g, spot[0] + 1, spot[1] + 1);
35 g.tap(sx, sy);
36 expect(g.read('mode')).toBe('play');
37 expect(g.read('S.ents.filter(e => e.kind === "house" && e.owner === 0).length')).toBe(1);
38 expect(g.read('S.players[0].res.wood')).toBe(170);
39 g.run(40);
40 expect(g.read('Realm.popCap(S, 0)')).toBe(10);
41 expect(g.el('pop').textContent).toBe('4/10');
42 });
43
44 test('a house that does not fit is refused with the reason and nothing is spent', () => {
45 const g = boot('empire');
46 g.run(.5);
47 selectVillagers(g);
48 g.run(.5);
49 press(g, 'build-house');
50 const [tx, ty] = screen(g, ...g.read('Realm.centre(S.ents.find(e => e.kind === "town-center" && e.owner === 0))'));
51 g.tap(tx, ty);
52 expect(g.read('mode')).toBe('place');
53 expect(g.el('status').textContent).toMatch(/Something is in the way/);
54 expect(g.read('S.players[0].res.wood')).toBe(200);
55 g.press('Escape');
56 expect(g.read('mode')).toBe('play');
57 });
58
59 test('the town center trains a villager from the keyboard: H, then 1', () => {
60 const g = boot('empire');
61 g.run(.5);
62 g.press('h');
63 expect(g.el('info').textContent).toMatch(/^Town center/);
64 g.press('1');
65 expect(g.read('S.players[0].res.food')).toBe(150);
66 expect(g.el('queue').children.length).toBe(1);
67 g.run(12);
68 expect(g.read('Realm.popOf(S, 0)')).toBe(5);
69 });
70
71 test('the arrows move the view, Enter taps the cross in its middle, and pause holds time', () => {
72 const g = boot('empire');
73 g.run(.5);
74 const x0 = g.read('V.camX');
75 g.press('ArrowLeft', .5);
76 expect(g.read('V.camX')).toBeLessThan(x0);
77 g.press('h');
78 expect(g.read('V.sel.size')).toBe(1);
79 g.press('Escape');
80 expect(g.read('V.sel.size')).toBe(0);
81 g.press('p');
82 const t = g.read('S.time');
83 g.run(3);
84 expect(g.read('S.time')).toBe(t);
85 g.press('p');
86 g.run(3);
87 expect(g.read('S.time')).toBeGreaterThan(t);
88 });
89
90 test('the minimap moves the view', () => {
91 const g = boot('empire');
92 g.run(.5);
93 const before = g.read('V.camX');
94 g.tap(350, 236);
95 expect(g.read('V.camX')).not.toBe(before);
96 });
97
98 test('the game keeps itself in the store as it goes, and not once it is over', () => {
99 const g = boot('empire');
100 g.run(12);
101 const saved = JSON.parse(g.store['empire-age-save']);
102 expect(saved.v).toBe(1);
103 expect(saved.ents.length).toBeGreaterThan(20);
104 g.press('r'); g.press('r');
105 expect(g.store['empire-age-save']).toBeUndefined();
106 });
107
108 test('giving up takes two presses, ends the game with a line, and offers a new one', () => {
109 const g = boot('empire');
110 g.run(1);
111 g.press('r');
112 expect(g.read('S.over')).toBeNull();
113 expect(g.el('status').textContent).toMatch(/again to give up/);
114 g.press('r');
115 expect(g.read('S.over.winner')).toBe(1);
116 expect(g.el('status').textContent).toMatch(/^defeat · you gave up at 0:0\d · 0 trained, 0 defeated \(normal\)$/);
117 expect(g.el('info').textContent).toMatch(/Pick a level/);
118 g.press('3');
119 expect(g.read('S.over')).toBeNull();
120 expect(g.read('S.level')).toBe(2);
121 expect(g.read('S.time')).toBeLessThan(1);
122 });
123
124 test('a win is told with its time and trained and defeated counts', () => {
125 const g = boot('empire');
126 g.run(1);
127 g.read('(() => { for (const e of S.ents.filter(e => e.owner === 1 && e.t === "b")) e.hp = 0; })()');
128 g.run(1);
129 expect(g.read('S.over.winner')).toBe(0);
130 expect(g.el('status').textContent).toMatch(/^victory · the enemy has fallen at 0:0\d · 0 trained, 0 defeated · new best \(normal\)$/);
131 expect(JSON.parse(g.store['empire-age-best'])['1']).toBeGreaterThan(0);
132 });
133
134 test('an attack on the town raises the alarm and Space looks at it', () => {
135 const g = boot('empire');
136 g.run(.5);
137 g.read('(() => { const r = Realm.addUnit(S, 1, "militia", 12, 28); Realm.order(S, 1, [r.id], { type: "attack", target: S.ents.find(e => e.kind === "town-center" && e.owner === 0).id }); })()');
138 let said = '';
139 g.watch(() => { if (/under attack/.test(g.el('status').textContent)) said = g.el('status').textContent; });
140 g.run(30);
141 expect(said).toMatch(/under attack: press space/);
142 const at = g.read('alertAt');
143 expect(at).not.toBeNull();
144 g.keyDown('ArrowRight'); g.run(.5); g.keyUp('ArrowRight');
145 const [cx, cy] = screen(g, at.x, at.y);
146 expect(Math.abs(cx - 180) + Math.abs(cy - 140)).toBeGreaterThan(20);
147 g.press(' ');
148 const [nx, ny] = screen(g, at.x, at.y);
149 expect(Math.abs(nx - 180)).toBeLessThan(2);
150 expect(Math.abs(ny - 140)).toBeLessThan(2);
151 expect(g.errors).toEqual([]);
152 });
153
154 test('the autopilot plays the person\'s side and the screen stays up', () => {
155 const g = boot('empire');
156 g.el('auto').fire('click');
157 g.run(60);
158 expect(g.read('S.ents.filter(e => e.owner === 0 && e.t === "b").length')).toBeGreaterThan(1);
159 expect(g.errors).toEqual([]);
160 }, 30000);
161
162 test('a frame of the page costs well under a frame of a laptop in the stand-in browser too', () => {
163 const g = boot('empire');
164 g.run(5);
165 const t = performance.now();
166 g.run(10);
167 expect((performance.now() - t) / 250).toBeLessThan(16);
168 });
169
170 test('a command flash is a visible ring of green pixels that fades away', () => {
171 const g = boot('empire');
172 g.run(.5);
173 const before = g.picture();
174 g.read('flash(12, 28)');
175 g.step(1);
176 expect(g.picture()).not.toBe(before);
177 expect(g.read('V.marks[0].color')).toBeGreaterThan(0);
178 g.run(1);
179 expect(g.read('V.marks.length')).toBe(0);
180 });
181
182 test('the status line is written only when its words change', () => {
183 const g = boot('empire');
184 g.run(.5);
185 let writes = 0;
186 const el = g.el('status');
187 let value = el.textContent;
188 Object.defineProperty(el, 'textContent', { get: () => value, set: v => { writes++; value = v; } });
189 g.run(3);
190 expect(writes).toBeLessThanOrEqual(1);
191 });
empire/paint.js added +268
@@ -0,0 +1,268 @@
1 'use strict';
2 // The picture of Empire Age: an isometric view of the tile map drawn pixel by pixel into a 360 by 280 buffer.
3 // Tiles are 16 by 8 pixels; the camera is a point in that flat pixel space. Nothing here changes the game:
4 // it reads the state and a `view` (camera, selection, placement ghost, drag box) and paints.
5 (function (root) {
6 const R = typeof module !== 'undefined' ? require('./realm.js') : root.Realm;
7 const T = typeof module !== 'undefined' ? require('./tables.js') : root.Tables;
8 const { SIZE } = R;
9 const TW = 8, TH = 4; // half a tile across and down, in pixels
10 const MINI = { x: 266, y: 232, w: 88, h: 44 }; // the minimap: a tile is 2 by 1 pixels
11
12 const rgb = (r, g, b) => (255 << 24 | Math.min(255, Math.max(0, b | 0)) << 16 | Math.min(255, Math.max(0, g | 0)) << 8 | Math.min(255, Math.max(0, r | 0))) >>> 0;
13 const mul = (c, k) => rgb((c & 255) * k, (c >> 8 & 255) * k, (c >> 16 & 255) * k);
14 const hash = (x, y) => { let h = Math.imul(x * 374761393 + y * 668265263, 1274126177); h ^= h >>> 13; return ((Math.imul(h, 1103515245) >>> 8) & 1023) / 1023; };
15 const TEAM = [rgb(66, 120, 232), rgb(224, 66, 60)];
16 const TEAM_DARK = [rgb(30, 60, 140), rgb(130, 30, 34)];
17 const GRASS = [rgb(86, 138, 62), rgb(92, 146, 66), rgb(80, 130, 58), rgb(98, 150, 70)];
18 const C = {
19 ink: rgb(26, 24, 30), skin: rgb(236, 196, 156), white: rgb(250, 248, 240), red: rgb(210, 50, 56), green: rgb(80, 220, 110), yellow: rgb(255, 214, 80),
20 bark: rgb(110, 78, 48), leaf: rgb(40, 100, 54), leafLight: rgb(66, 134, 66), berry: rgb(200, 40, 70), bush: rgb(48, 112, 56),
21 gold: rgb(240, 196, 60), goldDark: rgb(176, 130, 30), stone: rgb(150, 150, 158), stoneDark: rgb(104, 104, 114), steel: rgb(200, 206, 214), wood: rgb(150, 104, 60),
22 soil: rgb(124, 92, 56), crop: rgb(176, 196, 70), fog: rgb(10, 10, 16),
23 };
24 // wall colours per building: [left face, right face, top]
25 const WALLS = {
26 'town-center': [rgb(218, 196, 150), rgb(176, 154, 112), rgb(190, 120, 80)], house: [rgb(230, 214, 176), rgb(190, 172, 136), rgb(176, 96, 70)],
27 'lumber-camp': [rgb(160, 116, 70), rgb(124, 88, 52), rgb(100, 70, 44)], mill: [rgb(224, 220, 206), rgb(184, 180, 166), rgb(160, 120, 80)], 'mining-camp': [rgb(150, 150, 150), rgb(112, 112, 120), rgb(110, 84, 56)],
28 barracks: [rgb(170, 90, 80), rgb(130, 64, 60), rgb(96, 76, 70)], 'archery-range': [rgb(130, 150, 90), rgb(96, 114, 66), rgb(110, 84, 56)], stable: [rgb(176, 130, 80), rgb(138, 98, 58), rgb(90, 66, 48)],
29 blacksmith: [rgb(120, 120, 130), rgb(88, 88, 98), rgb(70, 70, 80)], tower: [rgb(170, 170, 176), rgb(128, 128, 138), rgb(110, 110, 120)], 'siege-workshop': [rgb(150, 112, 76), rgb(112, 80, 54), rgb(80, 60, 44)],
30 castle: [rgb(190, 190, 196), rgb(144, 144, 156), rgb(120, 120, 134)], farm: [C.soil, C.soil, C.soil],
31 };
32 const HEIGHT = { 'town-center': 14, house: 7, 'lumber-camp': 5, mill: 8, 'mining-camp': 5, barracks: 10, 'archery-range': 8, stable: 9, blacksmith: 8, tower: 22, 'siege-workshop': 10, castle: 24, farm: 0 };
33
34 const proj = (v, x, y, z = 0) => [Math.round((x - y) * TW - v.camX), Math.round((x + y) * TH - v.camY - z)];
35 // the tile coordinates under a canvas point (on the ground)
36 function toWorld(v, sx, sy) {
37 const a = (sx + v.camX) / TW, b = (sy + v.camY) / TH;
38 return [(a + b) / 2, (b - a) / 2];
39 }
40 const clampCam = (v, W, H) => {
41 v.camX = Math.max(-SIZE * TW - 20, Math.min(SIZE * TW + 20 - W, v.camX));
42 v.camY = Math.max(-24, Math.min(SIZE * TH * 2 + 24 - H, v.camY));
43 };
44 // put the camera so a tile point is in the middle of the view
45 function centreOn(v, x, y, W, H) { v.camX = (x - y) * TW - W / 2; v.camY = (x + y) * TH - H / 2; clampCam(v, W, H); }
46 const miniAt = (sx, sy) => sx >= MINI.x && sy >= MINI.y && sx < MINI.x + MINI.w && sy < MINI.y + MINI.h;
47 function make(pix, W, H) {
48 const px = (x, y, c) => { if (x >= 0 && y >= 0 && x < W && y < H) pix[y * W + x] = c; };
49 const rect = (x, y, w, h, c) => { const x0 = Math.max(0, x), x1 = Math.min(W, x + w), y0 = Math.max(0, y), y1 = Math.min(H, y + h); for (let j = y0; j < y1; j++) for (let i = x0; i < x1; i++) pix[j * W + i] = c; };
50 const line = (x0, y0, x1, y1, c) => {
51 const n = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0), 1);
52 for (let i = 0; i <= n; i++) px(Math.round(x0 + (x1 - x0) * i / n), Math.round(y0 + (y1 - y0) * i / n), c);
53 };
54 // fill a convex polygon, scanline by scanline
55 const poly = (pts, c) => {
56 let lo = Infinity, hi = -Infinity;
57 for (const p of pts) { lo = Math.min(lo, p[1]); hi = Math.max(hi, p[1]); }
58 for (let y = Math.max(0, Math.ceil(lo)); y <= Math.min(H - 1, Math.floor(hi)); y++) {
59 let a = Infinity, b = -Infinity;
60 for (let i = 0; i < pts.length; i++) {
61 const p = pts[i], q = pts[(i + 1) % pts.length];
62 if ((p[1] <= y && q[1] >= y) || (q[1] <= y && p[1] >= y)) {
63 const t = p[1] === q[1] ? 0 : (y - p[1]) / (q[1] - p[1]);
64 const x = p[0] + (q[0] - p[0]) * t;
65 if (x < a) a = x; if (x > b) b = x;
66 }
67 }
68 if (a <= b) for (let x = Math.max(0, Math.round(a)); x <= Math.min(W - 1, Math.round(b)); x++) pix[y * W + x] = c;
69 }
70 };
71 return { px, rect, line, poly };
72 }
73
74 const BAND = [4, 8, 12, 16, 16, 12, 8, 4];
75
76 function draw(pix, W, H, s, v) {
77 const { px, rect, line, poly } = make(pix, W, H);
78 pix.fill(C.fog);
79 const still = !!v.still;
80 if (!Number.isFinite(v.time)) v.time = 0;
81 const seen = s.seen;
82 const sees = (x, y) => seen[Math.max(0, Math.min(SIZE - 1, Math.floor(y))) * SIZE + Math.max(0, Math.min(SIZE - 1, Math.floor(x)))];
83
84 /* the ground */
85 for (let ty = 0; ty < SIZE; ty++) for (let tx = 0; tx < SIZE; tx++) {
86 const k = seen[ty * SIZE + tx];
87 const [cx, cy] = proj(v, tx + .5, ty + .5);
88 if (cx < -10 || cx > W + 10 || cy < -6 || cy > H + 6 || !k) continue;
89 const base = GRASS[Math.floor(hash(tx, ty) * 4)];
90 const c = mul(base, (k === 2 ? 1 : .55) * [.94, 1, 1.06][Math.floor(hash(tx * 3 + 1, ty * 5 + 2) * 3)]);
91 const lit = mul(c, 1.14), shade = mul(c, .86);
92 for (let r = 0; r < 8; r++) {
93 const w = BAND[r];
94 rect(cx - w, cy - 4 + r, w * 2, 1, c);
95 // the upper edges catch the light and the lower ones fall into shade, so the tiles read as ground
96 px(cx - w, cy - 4 + r, r < 4 ? lit : shade); px(cx + w - 1, cy - 4 + r, r < 4 ? lit : shade);
97 }
98 if (hash(tx + 91, ty + 7) > .93) px(cx, cy, k === 2 ? rgb(240, 232, 120) : rgb(130, 126, 70));
99 }
100 // the map edge
101 for (let i = 0; i <= SIZE; i++) for (const [x, y] of [[i, 0], [i, SIZE], [0, i], [SIZE, i]]) { const [a, b] = proj(v, x, y); px(a, b, C.ink); }
102
103 /* everything standing on it, back to front */
104 const list = [];
105 for (const e of s.ents) {
106 const z = e.t === 'b' ? R.box(e).x1 - e.x : e.t === 'r' ? 1 : 0;
107 const [mx, my] = R.centre(e);
108 if (e.t === 'u') { if (e.owner !== 0 && sees(e.x, e.y) !== 2) continue; }
109 else if (!sees(mx, my)) continue;
110 const depth = e.t === 'u' ? e.x + e.y : e.x + e.y + z * 2 - (e.t === 'b' && e.kind === 'farm' ? 100 : 0);
111 list.push([depth, e]);
112 }
113 list.sort((a, b) => a[0] - b[0]);
114 for (const [, e] of list) {
115 const dim = e.t !== 'u' && sees(...R.centre(e)) !== 2;
116 if (e.t === 'r') node(e, dim);
117 else if (e.t === 'b') building(e, dim);
118 else unit(e);
119 }
120
121 /* arrows in flight */
122 for (const sh of s.shots) {
123 const k = Math.min(1, (s.time - sh.t) / .25);
124 const [a, b] = proj(v, sh.x0 + (sh.x1 - sh.x0) * k, sh.y0 + (sh.y1 - sh.y0) * k, 6);
125 const [a2, b2] = proj(v, sh.x0 + (sh.x1 - sh.x0) * Math.max(0, k - .15), sh.y0 + (sh.y1 - sh.y0) * Math.max(0, k - .15), 6);
126 line(a2, b2, a, b, C.white);
127 }
128
129 /* what the player is doing: ghost, drag box, rally flags */
130 if (v.ghost) {
131 const d = T.BUILDINGS[v.ghost.kind], c = v.ghost.ok ? rgb(120, 255, 140) : rgb(255, 90, 90);
132 const z = d.size, x = v.ghost.x, y = v.ghost.y;
133 const pts = [proj(v, x, y), proj(v, x + z, y), proj(v, x + z, y + z), proj(v, x, y + z)];
134 for (let i = 0; i < 4; i++) line(pts[i][0], pts[i][1], pts[(i + 1) % 4][0], pts[(i + 1) % 4][1], c);
135 for (let i = 0; i < 4; i++) line(pts[i][0], pts[i][1] - (HEIGHT[v.ghost.kind] || 3), pts[(i + 1) % 4][0], pts[(i + 1) % 4][1] - (HEIGHT[v.ghost.kind] || 3), c);
136 }
137 if (v.box) {
138 const x0 = Math.min(v.box.x0, v.box.x1), x1 = Math.max(v.box.x0, v.box.x1), y0 = Math.min(v.box.y0, v.box.y1), y1 = Math.max(v.box.y0, v.box.y1);
139 line(x0, y0, x1, y0, C.green); line(x0, y1, x1, y1, C.green); line(x0, y0, x0, y1, C.green); line(x1, y0, x1, y1, C.green);
140 }
141 for (const id of v.sel) {
142 const b = s.byId.get(id);
143 if (b && b.t === 'b' && b.rally) { const [a, c] = proj(v, b.rally.x, b.rally.y); line(a, c, a, c - 8, C.yellow); rect(a, c - 8, 4, 3, C.yellow); }
144 }
145 for (const m of v.marks || []) { const [a, b] = proj(v, m.x, m.y); const r = 3 + Math.floor(m.age * 10); for (let k = 0; k < 12; k++) px(Math.round(a + Math.cos(k / 12 * 6.283) * r), Math.round(b + Math.sin(k / 12 * 6.283) * r / 2), m.color || C.green); }
146
147 minimap();
148
149 /* ---- pieces ---- */
150 function ring(sx, sy, w, c) { for (let i = 0; i < 20; i++) px(Math.round(sx + Math.cos(i / 20 * 6.283) * w), Math.round(sy + Math.sin(i / 20 * 6.283) * w / 2), c); }
151 function bar(sx, sy, w, frac) { rect(sx - (w >> 1) - 1, sy - 1, w + 2, 4, C.ink); rect(sx - (w >> 1), sy, Math.max(0, Math.round(w * frac)), 2, frac > .5 ? C.green : frac > .25 ? C.yellow : C.red); }
152
153 function node(e, dim) {
154 const [sx, sy] = proj(v, e.x + .5, e.y + .5);
155 const k = dim ? .55 : 1;
156 const left = Math.max(.35, Math.min(1, e.amount / T.NODES[e.kind].amount));
157 if (e.kind === 'tree') {
158 rect(sx - 1, sy - 4, 3, 5, mul(C.bark, k));
159 const sway = still ? 0 : Math.round(Math.sin(v.time * 1.6 + e.x * 1.7 + e.y) * .6);
160 poly([[sx - 6 + sway, sy - 4], [sx + 6 + sway, sy - 4], [sx + 2 + sway, sy - 13], [sx - 2 + sway, sy - 13]], mul(C.leaf, k));
161 poly([[sx - 4 + sway, sy - 9], [sx + 4 + sway, sy - 9], [sx + sway, sy - 17]], mul(C.leafLight, k));
162 } else if (e.kind === 'berries') {
163 rect(sx - 5, sy - 5, 10, 5, mul(C.bush, k));
164 for (const [dx, dy] of [[-3, -4], [0, -3], [3, -4], [-1, -5], [2, -2]]) px(sx + dx, sy + dy, mul(C.berry, k));
165 } else if (e.kind === 'gold') {
166 poly([[sx - 6, sy], [sx, sy - 4], [sx + 6, sy], [sx, sy + 3]], mul(C.goldDark, k));
167 poly([[sx - 5, sy - 1], [sx - 1, sy - 8 * left - 2], [sx + 3, sy - 1]], mul(C.gold, k));
168 px(sx + 3, sy - 4, mul(C.white, k));
169 } else {
170 poly([[sx - 6, sy], [sx, sy - 4], [sx + 6, sy], [sx, sy + 3]], mul(C.stoneDark, k));
171 poly([[sx - 5, sy - 1], [sx - 1, sy - 8 * left - 2], [sx + 4, sy - 1]], mul(C.stone, k));
172 }
173 }
174
175 function building(e, dim) {
176 const d = T.BUILDINGS[e.kind], z = d.size, [wl, wr, top] = WALLS[e.kind];
177 const k = dim ? .55 : e.built ? 1 : .8;
178 const h = (HEIGHT[e.kind] || 0) * (e.built ? 1 : Math.max(.25, e.prog));
179 const A = proj(v, e.x, e.y), B = proj(v, e.x + z, e.y), Cc = proj(v, e.x + z, e.y + z), D = proj(v, e.x, e.y + z);
180 const up = p => [p[0], p[1] - h];
181 if (e.kind === 'farm') {
182 poly([A, B, Cc, D], mul(C.soil, k));
183 for (let i = 1; i < 4; i++) { const f = i / 4; line(Math.round(A[0] + (D[0] - A[0]) * f), Math.round(A[1] + (D[1] - A[1]) * f), Math.round(B[0] + (Cc[0] - B[0]) * f), Math.round(B[1] + (Cc[1] - B[1]) * f), mul(e.amount > 40 ? C.crop : C.goldDark, k)); }
184 } else {
185 poly([up(D), up(Cc), Cc, D], mul(wl, k)); // front left face
186 poly([up(Cc), up(B), B, Cc], mul(wr, k)); // front right face
187 const hasRoof = ['house', 'barracks', 'stable', 'archery-range', 'mill', 'lumber-camp', 'mining-camp', 'siege-workshop', 'town-center'].includes(e.kind);
188 if (hasRoof && e.built) {
189 const ridge = Math.round(h * .5 + 3), ctr = proj(v, e.x + z / 2, e.y + z / 2, h + ridge);
190 poly([up(D), up(Cc), ctr], mul(top, k * 1.1));
191 poly([up(Cc), up(B), ctr], mul(top, k * .8));
192 poly([up(A), up(B), ctr], mul(top, k * .6));
193 poly([up(A), up(D), ctr], mul(top, k * .9));
194 } else poly([up(A), up(B), up(Cc), up(D)], mul(top, k));
195 if (e.kind === 'tower' || e.kind === 'castle') {
196 for (let i = 0; i < 4; i++) { const p = [up(A), up(B), up(Cc), up(D)][i]; rect(p[0] - 1, p[1] - 3, 3, 3, mul(wl, k)); }
197 }
198 if (e.kind === 'town-center' || e.kind === 'castle') { const c0 = proj(v, e.x + z / 2, e.y + z / 2, h + (e.kind === 'castle' ? 8 : 12)); line(c0[0], c0[1], c0[0], c0[1] - 8, C.ink); rect(c0[0] + 1, c0[1] - 8, 5, 3, TEAM[e.owner]); }
199 else if (e.built) { const c0 = proj(v, e.x + z / 2, e.y + z / 2, h + 3); rect(c0[0], c0[1] - 6, 3, 2, TEAM[e.owner]); }
200 // a door
201 if (e.built && e.kind !== 'tower') { const m = proj(v, e.x + z / 2, e.y + z, 0); rect(m[0] - 1, m[1] - 4, 3, 4, mul(TEAM_DARK[e.owner], k)); }
202 for (let i = 0; i < 3; i++) px(Cc[0], Cc[1] - i * 2, mul(TEAM[e.owner], k));
203 }
204 if (!e.built) {
205 const m = proj(v, e.x + z / 2, e.y + z / 2, h + 8);
206 rect(m[0] - 8, m[1], 17, 4, C.ink); rect(m[0] - 7, m[1] + 1, Math.round(15 * e.prog), 2, C.yellow);
207 }
208 if (v.sel.has(e.id)) { const m = proj(v, e.x + z / 2, e.y + z / 2); for (let i = 0; i < 4; i++) line(...[A, B, Cc, D][i], ...[A, B, Cc, D][(i + 1) % 4], C.green); bar(m[0], m[1] - h - 12, 20, e.hp / T.BUILDINGS[e.kind].hp); }
209 else if (e.hp < d.hp * .85 && e.built) { const m = proj(v, e.x + z / 2, e.y + z / 2); bar(m[0], m[1] - h - 12, 14, e.hp / d.hp); if (e.hp < d.hp * .4 && !still && Math.floor(v.time * 6) % 2) { rect(m[0] - 1, m[1] - h - 8, 3, 3, rgb(255, 150, 40)); } }
210 }
211
212 function unit(e) {
213 const [sx, sy] = proj(v, e.x, e.y);
214 const col = TEAM[e.owner], dk = TEAM_DARK[e.owner];
215 const walk = !still && e.path && e.path.length ? Math.floor(v.time * 8 + e.id) % 2 : 0;
216 px(sx - 1, sy + 1, rgb(0, 0, 0)); px(sx, sy + 1, rgb(0, 0, 0)); px(sx + 1, sy + 1, rgb(0, 0, 0));
217 if (v.sel.has(e.id)) ring(sx, sy, 6, C.green);
218 switch (e.kind) {
219 case 'knight': {
220 rect(sx - 5, sy - 5, 10, 4, rgb(150, 100, 60)); rect(sx + 4, sy - 8, 3, 4, rgb(150, 100, 60)); rect(sx - 4, sy - 1, 2, 2 + walk, C.bark); rect(sx + 2, sy - 1, 2, 3 - walk, C.bark);
221 rect(sx - 2, sy - 10, 4, 5, col); rect(sx - 2, sy - 12, 4, 2, C.steel); line(sx + 3, sy - 12, sx + 3, sy - 4, C.steel);
222 break;
223 }
224 case 'ram': {
225 rect(sx - 7, sy - 6, 14, 5, C.wood); rect(sx - 6, sy - 9, 12, 3, mul(C.wood, .7)); rect(sx + 5, sy - 5, 4, 3, C.steel);
226 rect(sx - 5, sy - 1, 2, 2 + walk, C.ink); rect(sx + 3, sy - 1, 2, 3 - walk, C.ink); rect(sx - 4, sy - 11, 8, 2, col);
227 break;
228 }
229 default: {
230 rect(sx - 1, sy - 1, 1, 2 + walk, dk); rect(sx + 1, sy - 1, 1, 3 - walk, dk); // legs
231 rect(sx - 2, sy - 6, 4, 5, col); // body
232 rect(sx - 1, sy - 9, 3, 3, C.skin); // head
233 if (e.kind === 'villager') { px(sx + 3, sy - 7, C.bark); px(sx + 3, sy - 6, C.bark); px(sx + 3, sy - 5, C.steel); if (e.carry.n >= 1) rect(sx - 3, sy - 7, 2, 2, e.carry.type === 'wood' ? C.bark : e.carry.type === 'food' ? C.berry : e.carry.type === 'gold' ? C.gold : C.stone); }
234 if (e.kind === 'militia') { line(sx + 3, sy - 9, sx + 3, sy - 3, C.steel); px(sx - 1, sy - 10, C.steel); px(sx, sy - 10, C.steel); px(sx + 1, sy - 10, C.steel); }
235 if (e.kind === 'spearman') { line(sx + 3, sy - 13, sx + 3, sy - 1, C.wood); px(sx + 3, sy - 14, C.steel); rect(sx - 2, sy - 10, 4, 1, dk); }
236 if (e.kind === 'archer') { line(sx + 3, sy - 9, sx + 4, sy - 6, C.wood); line(sx + 4, sy - 6, sx + 3, sy - 3, C.wood); px(sx - 1, sy - 10, rgb(60, 120, 60)); px(sx, sy - 10, rgb(60, 120, 60)); px(sx + 1, sy - 10, rgb(60, 120, 60)); }
237 }
238 }
239 const max = R.maxHp(s, e);
240 if (v.sel.has(e.id) || e.hp < max) bar(sx, sy - (e.kind === 'knight' || e.kind === 'ram' ? 15 : 13), 10, e.hp / max);
241 }
242
243 function minimap() {
244 rect(MINI.x - 1, MINI.y - 1, MINI.w + 2, MINI.h + 2, C.ink);
245 rect(MINI.x, MINI.y, MINI.w, MINI.h, rgb(14, 14, 20));
246 const dot = (x, y, c, w = 2, h = 1) => { const a = MINI.x + Math.round((x - y) * (MINI.w / 2 / SIZE) + MINI.w / 2), b = MINI.y + Math.round((x + y) * (MINI.h / 2 / SIZE)); rect(a - (w >> 1), b, w, h, c); };
247 for (let ty = 0; ty < SIZE; ty++) for (let tx = 0; tx < SIZE; tx++) { const k = seen[ty * SIZE + tx]; if (k) dot(tx + .5, ty + .5, k === 2 ? rgb(60, 110, 52) : rgb(34, 60, 34), 2, 1); }
248 for (const e of s.ents) {
249 const [cx, cy] = R.centre(e);
250 if (e.t === 'r') { if (sees(cx, cy)) dot(cx, cy, e.kind === 'tree' ? rgb(24, 70, 36) : e.kind === 'gold' ? C.gold : e.kind === 'stone' ? C.stone : C.berry); }
251 else if (e.t === 'b') { if (sees(cx, cy)) dot(cx, cy, TEAM[e.owner], 4, 2); }
252 else if (e.owner === 0 || sees(e.x, e.y) === 2) dot(e.x, e.y, e.owner === 0 ? rgb(150, 190, 255) : rgb(255, 150, 140));
253 }
254 // the part of the map the screen shows
255 const corners = [[0, 0], [W, 0], [W, H], [0, H]].map(([a, b]) => toWorld(v, a, b)).map(([x, y]) => [MINI.x + Math.round((x - y) * (MINI.w / 2 / SIZE) + MINI.w / 2), MINI.y + Math.round((x + y) * (MINI.h / 2 / SIZE))]);
256 for (let i = 0; i < 4; i++) { const p = corners[i], q = corners[(i + 1) % 4]; const clip = (a, lo, hi) => Math.max(lo, Math.min(hi, a)); line(clip(p[0], MINI.x, MINI.x + MINI.w - 1), clip(p[1], MINI.y, MINI.y + MINI.h - 1), clip(q[0], MINI.x, MINI.x + MINI.w - 1), clip(q[1], MINI.y, MINI.y + MINI.h - 1), C.white); }
257 }
258 }
259
260 // a minimap pixel to the tile under it
261 function miniWorld(sx, sy) {
262 const a = (sx - MINI.x - MINI.w / 2) / (MINI.w / 2 / SIZE), b = (sy - MINI.y) / (MINI.h / 2 / SIZE);
263 return [Math.max(0, Math.min(SIZE - .01, (a + b) / 2)), Math.max(0, Math.min(SIZE - .01, (b - a) / 2))];
264 }
265
266 const api = { TW, TH, MINI, TEAM, rgb, proj, toWorld, clampCam, centreOn, miniAt, miniWorld, draw, HEIGHT };
267 if (typeof module !== 'undefined') module.exports = api; else root.Paint = api;
268 })(typeof window !== 'undefined' ? window : globalThis);
empire/panel.js added +147
@@ -0,0 +1,147 @@
1 'use strict';
2 // The command panel of Empire Age as plain data: for a selection, the line that describes it, its queue and the
3 // buttons that apply (each with a cost, whether it can be pressed now and why not). `perform` carries a button out.
4 // The page only draws what `model` returns and passes the button's `act` back to `perform`.
5 (function (root) {
6 const R = typeof module !== 'undefined' ? require('./realm.js') : root.Realm;
7 const T = typeof module !== 'undefined' ? require('./tables.js') : root.Tables;
8 const { UNITS, BUILDINGS, TECHS, AGES } = T;
9
10 const pct = (a, b) => Math.max(0, Math.min(100, Math.round(a / b * 100)));
11 const plural = (n, word) => n + ' ' + word + (n === 1 ? '' : 's');
12 const doing = (s, u) => {
13 if (u.o === 'gather' || u.o === 'return') {
14 const node = s.byId.get(u.tgt), type = (node && R.nodeType(node)) || u.carry.type;
15 return (u.o === 'return' ? 'carrying ' : 'gathering ') + (type || 'resources');
16 }
17 return { idle: 'idle', move: 'walking', amove: 'on the march', attack: 'fighting', build: 'building' }[u.o] || 'idle';
18 };
19
20 // who is selected: own units, one own building, or something of anyone's to look at
21 function split(s, sel) {
22 const ents = sel.map(id => s.byId.get(id)).filter(Boolean);
23 return {
24 units: ents.filter(e => e.t === 'u' && e.owner === 0),
25 building: ents.length === 1 && ents[0].t === 'b' && ents[0].owner === 0 ? ents[0] : null,
26 other: ents.length === 1 && !(ents[0].owner === 0 && ents[0].t !== 'r') ? ents[0] : null,
27 };
28 }
29
30 function whyNotBuy(s, cost, age) {
31 const p = s.players[0];
32 if (p.age < age) return 'needs the ' + AGES[age].name;
33 if (!T.canAfford(p.res, cost)) return 'needs ' + T.costText(cost);
34 return null;
35 }
36
37 function describe(s, who) {
38 const { units, building, other } = who;
39 if (building) {
40 const d = BUILDINGS[building.kind];
41 if (!building.built) return `${d.name} · ${pct(building.prog, 1)}% built · ${Math.ceil(building.hp)}/${d.hp} hp`;
42 return `${d.name} · ${Math.ceil(building.hp)}/${R.maxHp(s, building)} hp${building.kind === 'farm' ? ` · ${Math.ceil(building.amount)} food left` : ''}`;
43 }
44 if (units.length === 1) {
45 const u = units[0], st = R.stat(s, 0, u.kind);
46 return `${UNITS[u.kind].name} · ${Math.ceil(u.hp)}/${st.hp} hp · attack ${st.atk} · ${doing(s, u)}${u.carry.n ? ` (${Math.floor(u.carry.n)} ${u.carry.type})` : ''}`;
47 }
48 if (units.length) {
49 const kinds = {};
50 for (const u of units) kinds[u.kind] = (kinds[u.kind] || 0) + 1;
51 return Object.keys(kinds).map(k => plural(kinds[k], UNITS[k].name.toLowerCase())).join(', ') + ` · ${units.filter(u => u.o === 'idle').length} idle`;
52 }
53 if (other) {
54 if (other.t === 'r') return `${{ berries: 'Berry bushes', tree: 'Tree', gold: 'Gold mine', stone: 'Stone mine' }[other.kind]} · ${Math.ceil(other.amount)} left`;
55 const name = other.t === 'u' ? UNITS[other.kind].name : BUILDINGS[other.kind].name;
56 return `Enemy ${name.toLowerCase()} · ${Math.ceil(other.hp)} hp`;
57 }
58 return 'Tap a villager or a building. Drag the map with a finger, or use the arrows.';
59 }
60
61 function buttons(s, who, mode) {
62 const out = [];
63 const add = (id, label, sub, act, why = null, on = true) => out.push({ id, label, sub, act, on: on && !why, why });
64 const { units, building } = who;
65 if (mode !== 'play') { add('cancel', 'Cancel', '', { t: 'mode', mode: 'play' }); return out; }
66 if (building && building.built) {
67 const d = BUILDINGS[building.kind], p = s.players[0];
68 const full = building.q.length >= R.QUEUE_MAX ? 'queue is full' : null;
69 for (const k of d.trains || []) add('train-' + k, UNITS[k].name, T.costText(UNITS[k].cost), { t: 'train', kind: k }, full || whyNotBuy(s, UNITS[k].cost, UNITS[k].age));
70 for (const id of d.techs || []) {
71 if (p.techs[id]) continue;
72 const busy = s.ents.some(e => e.t === 'b' && e.owner === 0 && e.q.some(i => i.k === 'tech' && i.id === id));
73 add('tech-' + id, TECHS[id].name, T.costText(TECHS[id].cost), { t: 'research', id }, busy ? 'already being researched' : full || whyNotBuy(s, TECHS[id].cost, TECHS[id].age));
74 }
75 if (building.kind === 'town-center') {
76 const next = AGES[p.age + 1];
77 if (next) {
78 const missing = !R.ageOpen(s, 0, next.needs) ? 'needs ' + next.needs.map(g => g.map(k => BUILDINGS[k].name).join(' or ')).join(' and ') : null;
79 add('age', next.name, T.costText(next.cost), { t: 'age' }, p.aging ? 'already advancing' : missing || full || whyNotBuy(s, next.cost, 0));
80 }
81 }
82 if (d.trains) add('rally', 'Rally point', '', { t: 'mode', mode: 'rally' });
83 }
84 if (building) add('demolish', building.built ? 'Demolish' : 'Cancel building', '', { t: 'demolish' });
85 if (units.length) {
86 if (units.some(u => u.kind === 'villager')) {
87 for (const k of T.BUILD_ORDER) add('build-' + k, BUILDINGS[k].name, T.costText(BUILDINGS[k].cost), { t: 'place', kind: k }, whyNotBuy(s, BUILDINGS[k].cost, BUILDINGS[k].age));
88 }
89 if (units.some(u => u.kind !== 'villager')) add('amove', 'Attack-move', '', { t: 'mode', mode: 'amove' });
90 add('stop', 'Stop', '', { t: 'stop' });
91 } else if (!building) {
92 add('idle', 'Idle villager', '', { t: 'idle' });
93 add('army', 'Army', '', { t: 'army' });
94 add('home', 'Town center', '', { t: 'home' });
95 }
96 return out;
97 }
98
99 const queue = (s, who) => (who.building && who.building.built ? who.building.q.map((it, i) => ({ i, text: `${it.k === 'unit' ? UNITS[it.id].name : it.k === 'tech' ? TECHS[it.id].name : it.id} ${pct(it.t, it.total)}%${it.housed ? ' · needs a house' : ''}` })) : []);
100
101 // sel: array of ids; mode: 'play' | 'place' | 'rally' | 'amove'
102 function model(s, sel, mode = 'play') {
103 const who = split(s, sel);
104 const bs = buttons(s, who, mode);
105 bs.forEach((b, i) => { b.hot = i < 9 ? String(i + 1) : ''; });
106 return { info: describe(s, who), queue: queue(s, who), buttons: bs };
107 }
108
109 const villagers = (s, test = () => true) => s.ents.filter(e => e.t === 'u' && e.owner === 0 && e.kind === 'villager' && test(e)).sort((a, b) => a.id - b.id);
110 // do what a button says; returns { ok, why, mode, select, focus } (mode when the next tap on the map matters)
111 function perform(s, sel, act) {
112 const who = split(s, sel), bid = who.building ? who.building.id : 0;
113 const done = r => (r === true ? { ok: true } : r === false ? { ok: false, why: 'not now' } : r);
114 switch (act && act.t) {
115 case 'mode': return { ok: true, mode: act.mode };
116 case 'place': { const why = whyNotBuy(s, BUILDINGS[act.kind].cost, BUILDINGS[act.kind].age); return why ? { ok: false, why } : { ok: true, mode: 'place', kind: act.kind }; }
117 case 'train': return done(R.train(s, 0, bid, act.kind));
118 case 'research': return done(R.research(s, 0, bid, act.id));
119 case 'age': return done(R.ageUp(s, 0, bid));
120 case 'cancel': return done(R.cancel(s, 0, bid, act.i));
121 case 'demolish': return who.building ? { ok: R.demolish(s, 0, [bid]) > 0, select: [] } : { ok: false, why: 'select a building' };
122 case 'stop': return { ok: R.order(s, 0, who.units.map(u => u.id), { type: 'stop' }) > 0 };
123 case 'idle': {
124 const idle = villagers(s, u => u.o === 'idle');
125 if (!idle.length) return { ok: false, why: 'no idle villagers' };
126 const cur = sel.length === 1 ? sel[0] : 0, next = idle.find(u => u.id > cur) || idle[0];
127 return { ok: true, select: [next.id], focus: { x: next.x, y: next.y } };
128 }
129 case 'army': {
130 const army = s.ents.filter(e => e.t === 'u' && e.owner === 0 && e.kind !== 'villager');
131 if (!army.length) return { ok: false, why: 'no soldiers yet' };
132 const n = army.length;
133 return { ok: true, select: army.map(e => e.id), focus: { x: army.reduce((a, e) => a + e.x, 0) / n, y: army.reduce((a, e) => a + e.y, 0) / n } };
134 }
135 case 'home': {
136 const tc = s.ents.find(e => e.t === 'b' && e.owner === 0 && e.kind === 'town-center') || s.ents.find(e => e.t === 'b' && e.owner === 0 && e.kind === 'castle');
137 if (!tc) return { ok: false, why: 'no town center' };
138 const [x, y] = R.centre(tc);
139 return { ok: true, select: [tc.id], focus: { x, y } };
140 }
141 default: return { ok: false, why: 'unknown command' };
142 }
143 }
144
145 const api = { model, perform, split, describe };
146 if (typeof module !== 'undefined') module.exports = api; else root.Panel = api;
147 })(typeof window !== 'undefined' ? window : globalThis);
empire/pick.js added +73
@@ -0,0 +1,73 @@
1 'use strict';
2 // What is under a finger: hit-testing in screen pixels against the same projection the painter uses.
3 // A unit is a small box above its feet, a tree or mine a taller one, a building a diamond swept up by its height.
4 (function (root) {
5 const R = typeof module !== 'undefined' ? require('./realm.js') : root.Realm;
6 const P = typeof module !== 'undefined' ? require('./paint.js') : root.Paint;
7 const T = typeof module !== 'undefined' ? require('./tables.js') : root.Tables;
8 const { SIZE } = R;
9
10 const tileSeen = (s, x, y) => s.seen[Math.max(0, Math.min(SIZE - 1, Math.floor(y))) * SIZE + Math.max(0, Math.min(SIZE - 1, Math.floor(x)))];
11 // can the person see this entity right now (or remember it, for a building or a resource)?
12 function shown(s, e) {
13 if (e.t === 'u') return e.owner === 0 || tileSeen(s, e.x, e.y) === 2;
14 const [cx, cy] = R.centre(e);
15 return tileSeen(s, cx, cy) > 0;
16 }
17 // the screen point of a unit's feet
18 const feet = (v, e) => P.proj(v, e.x, e.y);
19
20 // a score for the entity at a screen point, or -1 when it is not there; bigger is nearer the viewer
21 function hit(v, e, sx, sy) {
22 if (e.t === 'u') {
23 const [fx, fy] = feet(v, e);
24 // the nearest to the finger wins, so a tight group can be told apart
25 return Math.abs(sx - fx) <= 5 && sy >= fy - 13 && sy <= fy + 3 ? 2000 - Math.hypot(sx - fx, sy - (fy - 5)) : -1;
26 }
27 if (e.t === 'r') {
28 const [fx, fy] = P.proj(v, e.x + .5, e.y + .5);
29 return Math.abs(sx - fx) <= 7 && sy >= fy - 14 && sy <= fy + 4 ? 500 + e.x + e.y : -1;
30 }
31 const z = T.BUILDINGS[e.kind].size, h = P.HEIGHT[e.kind] || 0;
32 const [cx, cy] = P.proj(v, e.x + z / 2, e.y + z / 2);
33 const a = z * P.TW, b = z * P.TH, dx = Math.abs(sx - cx);
34 if (dx > a) return -1;
35 const r = b * (1 - dx / a);
36 return sy <= cy + r && sy + h >= cy - r ? e.x + e.y + z : -1;
37 }
38
39 // the entity under a screen point, or null
40 function pick(s, v, sx, sy) {
41 let best = null, top = -1;
42 for (const e of s.ents) {
43 if (!shown(s, e)) continue;
44 const score = hit(v, e, sx, sy);
45 if (score > top) { top = score; best = e; }
46 }
47 return best;
48 }
49
50 // the person's units whose feet fall in a screen rectangle; soldiers win over villagers when both are caught
51 function inBox(s, v, x0, y0, x1, y1) {
52 const lx = Math.min(x0, x1), hx = Math.max(x0, x1), ly = Math.min(y0, y1), hy = Math.max(y0, y1);
53 const found = s.ents.filter(e => {
54 if (e.t !== 'u' || e.owner !== 0) return false;
55 const [fx, fy] = feet(v, e);
56 return fx >= lx && fx <= hx && fy - 5 >= ly && fy - 5 <= hy;
57 });
58 const soldiers = found.filter(e => e.kind !== 'villager');
59 return (soldiers.length ? soldiers : found).map(e => e.id);
60 }
61
62 // every unit of the same kind as `e` that is inside the view (a double tap)
63 function sameKindOnScreen(s, v, e, W, H) {
64 return s.ents.filter(u => {
65 if (u.t !== 'u' || u.owner !== e.owner || u.kind !== e.kind) return false;
66 const [fx, fy] = feet(v, u);
67 return fx >= 0 && fy >= 0 && fx < W && fy < H;
68 }).map(u => u.id);
69 }
70
71 const api = { pick, inBox, sameKindOnScreen, hit, shown };
72 if (typeof module !== 'undefined') module.exports = api; else root.Pick = api;
73 })(typeof window !== 'undefined' ? window : globalThis);
empire/realm.js added +722
@@ -0,0 +1,722 @@
1 'use strict';
2 // The rules of Empire Age: a small real-time strategy game on a square of tiles. Two players (0 is the person, 1 the
3 // bot) each start with a town center and four villagers, gather food, wood, gold and stone, build, climb four ages,
4 // train an army and fight. A player is beaten when no town center and no castle of theirs is standing.
5 // Plain data in, plain data out, no DOM and no clock: `tick(state, dt)` moves the world, the command functions
6 // (order, place, train, research, ageUp, rally, cancel, demolish) are the only way to change it, and the person and the
7 // bot use the same ones. The page draws what this decides.
8 (function (root) {
9 const T = typeof module !== 'undefined' ? require('./tables.js') : root.Tables;
10 const G = typeof module !== 'undefined' ? require('./grid.js') : root.Grid;
11 const { UNITS, BUILDINGS, NODES, AGES, TECHS, RES } = T;
12
13 const SIZE = 44;
14 const DT = .1; // the step the world is advanced by
15 const QUEUE_MAX = 5;
16 const SCAN = .6; // seconds between a soldier looking about for an enemy
17 const START = { food: 200, wood: 200, gold: 100, stone: 100 };
18 const FOG_EVERY = 4; // ticks between fog updates
19 const SHOT_LIFE = .25;
20 const LEVELS = [{ name: 'easy', gather: .8 }, { name: 'normal', gather: 1 }, { name: 'hard', gather: 1.25 }];
21
22 const finite = v => (Number.isFinite(v) ? v : 0);
23 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
24 const dist = (ax, ay, bx, by) => Math.hypot(ax - bx, ay - by);
25 function rand(s) {
26 s.rng = (s.rng + 0x6d2b79f5) >>> 0;
27 let t = s.rng;
28 t = Math.imul(t ^ (t >>> 15), t | 1);
29 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
30 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
31 }
32
33 /* ---------- entities ---------- */
34 const sizeOf = e => (e.t === 'b' ? BUILDINGS[e.kind].size : e.t === 'r' ? 1 : 0);
35 const ent = (s, id) => s.byId.get(id);
36 // the box an entity covers, in tile coordinates (a unit is a point)
37 function box(e) { const z = sizeOf(e); return z ? { x0: e.x, y0: e.y, x1: e.x + z, y1: e.y + z } : { x0: e.x, y0: e.y, x1: e.x, y1: e.y }; }
38 function distTo(px, py, e) {
39 const b = box(e);
40 return Math.hypot(Math.max(b.x0 - px, 0, px - b.x1), Math.max(b.y0 - py, 0, py - b.y1));
41 }
42 const centre = e => { const z = sizeOf(e) / 2; return [e.x + z, e.y + z]; };
43 const clsOf = e => (e.t === 'b' ? 'building' : UNITS[e.kind].cls);
44 const armorOf = (s, e) => (e.t === 'b' ? BUILDINGS[e.kind].armor : stat(s, e.owner, e.kind).armor);
45 const maxHp = (s, e) => (e.t === 'b' ? BUILDINGS[e.kind].hp : stat(s, e.owner, e.kind).hp);
46
47 function stat(s, owner, kind) {
48 const p = s.players[owner];
49 return (p.stat[kind] ??= T.statsOf(kind, p.techs));
50 }
51 function mark(s, e, v) {
52 const z = sizeOf(e);
53 for (let dy = 0; dy < z; dy++) for (let dx = 0; dx < z; dx++) {
54 const x = e.x + dx, y = e.y + dy;
55 if (x >= 0 && y >= 0 && x < SIZE && y < SIZE) s.blocked[y * SIZE + x] = v;
56 }
57 }
58 function index(s) {
59 s.byId = new Map(s.ents.map(e => [e.id, e]));
60 s.blocked = new Uint8Array(SIZE * SIZE);
61 for (const e of s.ents) if (e.t !== 'u') mark(s, e, 1);
62 }
63 function add(s, e) { e.id = s.nextId++; s.ents.push(e); s.byId.set(e.id, e); if (e.t !== 'u') mark(s, e, 1); return e; }
64 function addUnit(s, owner, kind, x, y) {
65 const st = stat(s, owner, kind);
66 return add(s, { t: 'u', kind, owner, x, y, hp: st.hp, o: 'idle', path: null, tgt: 0, tx: 0, ty: 0, cd: 0, scan: rand(s) * SCAN, carry: { type: '', n: 0 }, res: 0, then: null, fails: 0, repath: 0 });
67 }
68 function addBuilding(s, owner, kind, x, y, built) {
69 const d = BUILDINGS[kind];
70 const b = add(s, { t: 'b', kind, owner, x, y, hp: built ? d.hp : Math.ceil(d.hp * .1), built: !!built, prog: built ? 1 : 0, q: [], rally: null, cd: 0, nb: 0, nbNext: 0 });
71 if (kind === 'farm') b.amount = T.FARM_FOOD;
72 return b;
73 }
74 const addNode = (s, kind, x, y) => add(s, { t: 'r', kind, x, y, amount: NODES[kind].amount });
75
76 /* ---------- the world ---------- */
77 function newGame(seed = 1, level = 1) {
78 const s = { v: 1, size: SIZE, time: 0, tick: 0, rng: (seed >>> 0) || 1, nextId: 1, level: clamp(level | 0, 0, LEVELS.length - 1), over: null, ents: [], seen: new Uint8Array(SIZE * SIZE), shots: [], ai: [{}, {}], lastAlert: -99, events: [] };
79 s.players = [0, 1].map(() => ({ res: { ...START }, age: 0, techs: {}, stat: {}, aging: false, made: 0, killed: 0, lost: 0, gathered: 0 }));
80 index(s);
81 generate(s);
82 updateFog(s);
83 return s;
84 }
85 const mirror = (x, y, z = 1) => [SIZE - x - z, SIZE - y - z];
86 // the map is made for player 0 and mirrored for player 1, so neither has the better ground
87 function generate(s) {
88 const free = (x, y, z) => { for (let dy = 0; dy < z; dy++) for (let dx = 0; dx < z; dx++) { const tx = x + dx, ty = y + dy; if (tx < 1 || ty < 1 || tx >= SIZE - 1 || ty >= SIZE - 1 || s.blocked[ty * SIZE + tx]) return false; } return true; };
89 const put = (kind, x, y) => {
90 if (!free(x, y, 1)) return;
91 const [mx, my] = mirror(x, y);
92 if (mx === x && my === y) return;
93 if (!free(mx, my, 1)) return;
94 addNode(s, kind, x, y); addNode(s, kind, mx, my);
95 };
96 const keepClear = (x, y) => { for (const [bx, by] of [[8, 31], [SIZE - 11, SIZE - 34]]) if (x >= bx - 1 && x <= bx + 4 && y >= by - 1 && y <= by + 6) return true; return false; };
97 // the bases: a town center and four villagers each, the second mirrored from the first
98 const home = [[8, 31], mirror(8, 31, 3)];
99 home.forEach(([x, y], o) => {
100 addBuilding(s, o, 'town-center', x, y, true);
101 for (let k = 0; k < 4; k++) addUnit(s, o, 'villager', x + 1 + k * .6, y + 3.6);
102 s.players[o].res = { ...START };
103 });
104 const blob = (kind, cx, cy, n, spread) => {
105 let x = cx, y = cy;
106 for (let k = 0, tries = 0; k < n && tries < n * 6; tries++) {
107 const before = s.ents.length;
108 if (!keepClear(x, y)) put(kind, x, y);
109 if (s.ents.length > before) k++;
110 x = clamp(cx + Math.round((rand(s) - .5) * spread * 2), 1, SIZE - 2);
111 y = clamp(cy + Math.round((rand(s) - .5) * spread * 2), 1, SIZE - 2);
112 }
113 };
114 blob('berries', 14, 31, 6, 1.6);
115 blob('tree', 4, 26, 22, 3);
116 blob('tree', 15, 25, 14, 2.5);
117 blob('gold', 15, 38, 5, 1.2);
118 blob('stone', 3, 37, 4, 1.2);
119 blob('tree', 20, 36, 10, 2.5);
120 // the middle: more forest, a gold field and stone to fight over, and a few scattered trees
121 blob('tree', 22, 14, 14, 3); blob('tree', 10, 12, 12, 3);
122 blob('gold', 22, 22, 6, 1.5); blob('stone', 26, 18, 3, 1);
123 for (let k = 0; k < 14; k++) put('tree', 1 + Math.floor(rand(s) * (SIZE - 2)), 1 + Math.floor(rand(s) * (SIZE - 2)));
124 }
125
126 /* ---------- fog ---------- */
127 function updateFog(s) {
128 const seen = s.seen;
129 for (let i = 0; i < seen.length; i++) if (seen[i] === 2) seen[i] = 1;
130 for (const e of s.ents) {
131 if (e.owner !== 0 || e.t === 'r') continue;
132 const r = e.t === 'b' ? BUILDINGS[e.kind].sight + sizeOf(e) / 2 : UNITS[e.kind].sight;
133 const [cx, cy] = e.t === 'b' ? centre(e) : [e.x, e.y];
134 const x0 = Math.max(0, Math.floor(cx - r)), x1 = Math.min(SIZE - 1, Math.ceil(cx + r)), y0 = Math.max(0, Math.floor(cy - r)), y1 = Math.min(SIZE - 1, Math.ceil(cy + r));
135 for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) if (dist(x + .5, y + .5, cx, cy) <= r) seen[y * SIZE + x] = 2;
136 }
137 }
138 const visibleAt = (s, x, y) => s.seen[clamp(Math.floor(y), 0, SIZE - 1) * SIZE + clamp(Math.floor(x), 0, SIZE - 1)] === 2;
139
140 /* ---------- population, costs ---------- */
141 const popOf = (s, owner) => s.ents.reduce((n, e) => n + (e.t === 'u' && e.owner === owner ? 1 : 0), 0);
142 const popCap = (s, owner) => Math.min(T.MAX_POP, s.ents.reduce((n, e) => n + (e.t === 'b' && e.owner === owner && e.built ? BUILDINGS[e.kind].pop || 0 : 0), 0));
143 const has = (s, owner, kind) => s.ents.some(e => e.t === 'b' && e.owner === owner && e.built && e.kind === kind);
144 const owns = (s, owner, e) => !!e && e.owner === owner;
145 function pay(p, cost) { for (const r in cost) p.res[r] -= cost[r]; }
146 function refund(p, cost) { for (const r in cost) p.res[r] += cost[r]; }
147 const ageOpen = (s, owner, need) => need.every(group => group.some(k => has(s, owner, k)));
148
149 /* ---------- finding things ---------- */
150 function nearest(s, x, y, test, max = Infinity) {
151 let best = null, bd = max;
152 for (const e of s.ents) { if (!test(e)) continue; const d = distTo(x, y, e); if (d < bd) { bd = d; best = e; } }
153 return best;
154 }
155 const nodeType = e => (e.t === 'r' ? NODES[e.kind].type : e.kind === 'farm' ? 'food' : '');
156 const workers = (s, id) => { let n = 0; for (const e of s.ents) if (e.t === 'u' && e.o === 'gather' && e.tgt === id) n++; return n; };
157 // the closest thing of a resource type to gather from; berries before farms, a farm with a free place
158 function findNode(s, owner, x, y, type, max = 12, skip = null) {
159 const ok = e => (e.t === 'r' ? NODES[e.kind].type === type && e.amount > 0 && !(skip && skip.includes(e.id)) : e.t === 'b' && e.kind === 'farm' && type === 'food' && e.owner === owner && e.built && e.amount > 0 && !(skip && skip.includes(e.id)) && workers(s, e.id) < 2);
160 return nearest(s, x, y, ok, max);
161 }
162 const dropoff = (s, owner, x, y, type) => nearest(s, x, y, e => e.t === 'b' && e.owner === owner && e.built && BUILDINGS[e.kind].drop && BUILDINGS[e.kind].drop.includes(type));
163
164 /* ---------- moving ---------- */
165 function pathTo(s, u, goal, h) {
166 const path = G.findPath(s.blocked, SIZE, Math.floor(u.x), Math.floor(u.y), goal, h);
167 u.path = path; u.repath = 0;
168 return path !== null;
169 }
170 // walk to within `reach` of an entity
171 function goNear(s, u, e, reach) {
172 const b = box(e);
173 const dd = (tx, ty) => Math.hypot(Math.max(b.x0 - tx - .5, 0, tx + .5 - b.x1), Math.max(b.y0 - ty - .5, 0, ty + .5 - b.y1));
174 return pathTo(s, u, (tx, ty) => dd(tx, ty) <= reach, (tx, ty) => Math.max(0, dd(tx, ty) - reach));
175 }
176 function goPoint(s, u, x, y) {
177 let tx = clamp(Math.floor(x), 0, SIZE - 1), ty = clamp(Math.floor(y), 0, SIZE - 1);
178 if (s.blocked[ty * SIZE + tx]) { const t = G.nearestTile(SIZE, tx, ty, (a, c) => !s.blocked[c * SIZE + a], 6); if (!t) return false; [tx, ty] = t; }
179 return pathTo(s, u, (a, c) => a === tx && c === ty, (a, c) => Math.hypot(a - tx, c - ty));
180 }
181 // one step along the path; true when the path is spent
182 function follow(s, u, dt) {
183 if (!u.path || !u.path.length) return true;
184 let move = stat(s, u.owner, u.kind).spd * dt;
185 while (move > 0 && u.path.length) {
186 const [wx, wy] = u.path[0];
187 if (s.blocked[wy * SIZE + wx] && u.path.length > 0 && !(Math.floor(u.x) === wx && Math.floor(u.y) === wy)) { u.path = null; u.repath = 1; return false; }
188 const dx = wx + .5 - u.x, dy = wy + .5 - u.y, d = Math.hypot(dx, dy);
189 if (d <= move) { u.x = wx + .5; u.y = wy + .5; u.path.shift(); move -= d; }
190 else { u.x += dx / d * move; u.y += dy / d * move; move = 0; }
191 }
192 return !u.path.length;
193 }
194 function idle(u) { u.o = 'idle'; u.path = null; u.tgt = 0; u.then = null; u.fails = 0; }
195
196 /* ---------- fighting ---------- */
197 function damageOf(s, from, to) {
198 const st = stat(s, from.owner, from.kind), a = armorOf(s, to);
199 return Math.max(1, st.atk + (st.bonus[clsOf(to)] || 0) - a[st.rng ? 1 : 0]);
200 }
201 function hurt(s, target, dmg, by, ev) {
202 if (target.hp <= 0) return;
203 target.hp -= dmg;
204 if (target.owner === 0 && s.time - s.lastAlert > 8) { s.lastAlert = s.time; ev.push({ type: 'alert', x: target.x, y: target.y }); }
205 if (target.hp <= 0) { if (by) target.killer = by.owner; return; }
206 if (target.t === 'u' && by && by.t === 'u' && (target.o === 'idle' || target.o === 'amove') && UNITS[target.kind].atk > 3 && target.owner !== by.owner) {
207 if (target.o !== 'amove') target.then = null;
208 target.o = 'attack'; target.tgt = by.id; target.path = null;
209 }
210 }
211 // who a soldier would fight: soldiers first, then villagers, then buildings only when close
212 function pickEnemy(s, u, range) {
213 const st = stat(s, u.owner, u.kind);
214 let best = null, bs = Infinity;
215 for (const e of s.ents) {
216 if (e.owner === u.owner || e.owner < 0 || e.t === 'r' || e.hp <= 0) continue;
217 const d = distTo(u.x, u.y, e);
218 if (d > range) continue;
219 if (e.t === 'b' && d > 2.5 && st.cls !== 'siege') continue;
220 if (e.t === 'u' && st.cls === 'siege') continue;
221 const c = e.t === 'b' ? 6 : UNITS[e.kind].cls === 'villager' ? 3 : 0;
222 const score = d + c;
223 if (score < bs) { bs = score; best = e; }
224 }
225 return best;
226 }
227 // a blow that kills is remembered on the victim until the sweep of the tick removes it
228 const killerOf = e => (e.killer === 0 || e.killer === 1 ? { owner: e.killer } : null);
229 function die(s, e, by, ev) {
230 s.ents.splice(s.ents.indexOf(e), 1);
231 s.byId.delete(e.id);
232 if (e.t !== 'u') mark(s, e, 0);
233 if (e.t === 'b') {
234 for (const item of e.q) refund(s.players[e.owner], item.cost || {});
235 for (const u of s.ents) if (u.t === 'u' && u.o === 'build' && u.tgt === e.id) idle(u);
236 }
237 if (e.owner >= 0 && e.t !== 'r') {
238 s.players[e.owner].lost++;
239 if (by && by.owner >= 0 && by.owner !== e.owner) s.players[by.owner].killed++;
240 ev.push({ type: 'lost', owner: e.owner, kind: e.kind, building: e.t === 'b', x: e.x, y: e.y });
241 }
242 }
243 function strike(s, u, target, ev) {
244 const st = stat(s, u.owner, u.kind);
245 u.cd = st.reload;
246 hurt(s, target, damageOf(s, u, target), u, ev);
247 if (st.rng) { const [cx, cy] = centre(target); s.shots.push({ x0: u.x, y0: u.y, x1: target.t === 'b' ? cx : target.x, y1: target.t === 'b' ? cy : target.y, t: s.time }); }
248 ev.push({ type: st.rng ? 'shot' : 'hit', x: u.x, y: u.y });
249 }
250
251 /* ---------- unit orders, one tick ---------- */
252 function actUnit(s, u, dt, ev) {
253 u.cd = Math.max(0, u.cd - dt);
254 u.repath = Math.max(0, u.repath - dt);
255 const st = stat(s, u.owner, u.kind), soldier = st.cls !== 'villager';
256 switch (u.o) {
257 case 'idle':
258 u.scan -= dt;
259 if (soldier && u.scan <= 0) {
260 u.scan = SCAN;
261 const e = pickEnemy(s, u, st.sight);
262 if (e) { u.o = 'attack'; u.tgt = e.id; u.then = null; }
263 }
264 break;
265 case 'move':
266 if (!u.path && !goPoint(s, u, u.tx, u.ty)) { idle(u); break; }
267 if (follow(s, u, dt)) idle(u);
268 break;
269 case 'amove': {
270 u.scan -= dt;
271 if (u.scan <= 0) {
272 u.scan = SCAN;
273 const e = pickEnemy(s, u, st.sight);
274 if (e) { u.then = { x: u.tx, y: u.ty }; u.o = 'attack'; u.tgt = e.id; u.path = null; break; }
275 }
276 if (!u.path && !goPoint(s, u, u.tx, u.ty)) { idle(u); break; }
277 if (follow(s, u, dt)) idle(u);
278 break;
279 }
280 case 'attack': {
281 const t = ent(s, u.tgt);
282 if (!t || t.hp <= 0 || t.owner === u.owner) { resume(s, u); break; }
283 const reach = st.rng ? st.rng : 1;
284 if (distTo(u.x, u.y, t) <= reach) {
285 u.path = null;
286 if (u.cd <= 0) strike(s, u, t, ev);
287 } else if (t.t === 'u' && st.cls !== 'siege' && dist(u.x, u.y, t.x, t.y) > st.sight * 2.2 && u.then === null) { idle(u); }
288 else {
289 if (!u.path || (u.repath <= 0 && t.t === 'u')) { if (!goNear(s, u, t, reach) && !u.path) { u.fails++; if (u.fails > 2) { resume(s, u); break; } } u.repath = .8; }
290 follow(s, u, dt);
291 }
292 break;
293 }
294 case 'gather': gatherTick(s, u, dt, st, ev); break;
295 case 'return': returnTick(s, u, dt); break;
296 case 'build': buildTick(s, u, dt); break;
297 default: idle(u);
298 }
299 }
300 function resume(s, u) {
301 const then = u.then;
302 idle(u);
303 if (then) { u.o = 'amove'; u.tx = then.x; u.ty = then.y; }
304 }
305
306 /* ---------- gathering and building ---------- */
307 function setGather(s, u, node) {
308 u.o = 'gather'; u.tgt = node.id; u.res = node.id; u.path = null; u.fails = 0; u.bad = [];
309 const type = nodeType(node);
310 if (u.carry.type !== type) u.carry = { type, n: 0 };
311 }
312 function gatherTick(s, u, dt, st, ev) {
313 const node = ent(s, u.tgt);
314 const p = s.players[u.owner];
315 if (!node || node.amount <= 0 || (node.t === 'b' && node.hp <= 0)) {
316 // the place is spent: another of its kind close by, or take what is carried home
317 const type = u.carry.type;
318 const next = type && findNode(s, u.owner, u.x, u.y, type, 10, u.bad);
319 if (next && u.fails < 3) { setGather(s, u, next); return; }
320 if (u.carry.n >= 1) { u.o = 'return'; u.path = null; return; }
321 idle(u); return;
322 }
323 if (u.carry.n >= T.CARRY + (p.techs.wheelbarrow ? 5 : 0)) { u.o = 'return'; u.path = null; return; }
324 if (distTo(u.x, u.y, node) > 1.05) {
325 if (!u.path && !goNear(s, u, node, 1)) {
326 // out of reach (a tree in the middle of a forest): remember it, try another
327 (u.bad ??= []).push(node.id); u.fails++;
328 const next = findNode(s, u.owner, u.x, u.y, nodeType(node), 10, u.bad);
329 if (next && u.fails < 4) setGather(s, u, next); else if (u.carry.n >= 1) { u.o = 'return'; u.path = null; } else idle(u);
330 return;
331 }
332 if (follow(s, u, dt)) u.path = null;
333 return;
334 }
335 u.path = null;
336 if (node.t === 'b' && workers(s, node.id) > 2) { const other = findNode(s, u.owner, u.x, u.y, 'food', 10, [node.id]); if (other) setGather(s, u, other); else idle(u); return; }
337 const type = nodeType(node);
338 const rate = (node.t === 'b' ? T.RATE.farm : T.RATE[type]) * (1 + (p.techs.wheelbarrow ? T.TECHS.wheelbarrow.gather : 0)) * (u.owner === 1 ? LEVELS[s.level].gather : 1);
339 const take = Math.min(node.amount, rate * dt);
340 node.amount -= take; u.carry.n += take;
341 if (node.amount <= 0) exhaust(s, node, ev);
342 }
343 function exhaust(s, node, ev) {
344 if (node.t === 'b') {
345 // a farm is sown again if there is wood for it
346 const p = s.players[node.owner];
347 if (p.res.wood >= T.RESEED.wood) { p.res.wood -= T.RESEED.wood; node.amount = T.FARM_FOOD; ev.push({ type: 'reseed', owner: node.owner }); }
348 else die(s, node, null, ev);
349 } else { s.ents.splice(s.ents.indexOf(node), 1); s.byId.delete(node.id); mark(s, node, 0); }
350 }
351 function returnTick(s, u, dt) {
352 const type = u.carry.type;
353 const drop = dropoff(s, u.owner, u.x, u.y, type);
354 if (!drop || u.carry.n <= 0) { idle(u); return; }
355 if (distTo(u.x, u.y, drop) > 1.05) {
356 if (!u.path && !goNear(s, u, drop, 1)) { idle(u); return; }
357 if (follow(s, u, dt)) u.path = null;
358 return;
359 }
360 const p = s.players[u.owner];
361 p.res[type] += u.carry.n; p.gathered += u.carry.n; u.carry.n = 0; u.path = null;
362 const back = ent(s, u.res);
363 const node = back && back.amount > 0 ? back : findNode(s, u.owner, u.x, u.y, type, 12);
364 if (node) setGather(s, u, node); else idle(u);
365 }
366 function buildTick(s, u, dt) {
367 const b = ent(s, u.tgt);
368 if (!b || b.built) { afterBuild(s, u, b); return; }
369 if (distTo(u.x, u.y, b) > 1.05) {
370 if (!u.path && !goNear(s, u, b, 1)) { idle(u); return; }
371 if (follow(s, u, dt)) u.path = null;
372 return;
373 }
374 u.path = null;
375 b.nbNext++;
376 }
377 // a builder with nothing left to build goes to work next to what it made
378 function afterBuild(s, u, b) {
379 idle(u);
380 if (!b) return;
381 const d = BUILDINGS[b.kind];
382 let node = null;
383 if (b.kind === 'farm') node = b;
384 else if (d.drop && d.drop.length < 4) node = findNode(s, u.owner, b.x, b.y, d.drop[0], 8) || (d.drop[1] && findNode(s, u.owner, b.x, b.y, d.drop[1], 8));
385 if (!node) {
386 const site = nearest(s, u.x, u.y, e => e.t === 'b' && e.owner === u.owner && !e.built, 6);
387 if (site) { u.o = 'build'; u.tgt = site.id; return; }
388 }
389 if (node) setGather(s, u, node);
390 }
391
392 /* ---------- buildings, one tick ---------- */
393 function spawnTile(s, b) {
394 const z = sizeOf(b), want = b.rally ? [b.rally.x, b.rally.y] : [SIZE / 2, SIZE / 2];
395 let best = null, bd = Infinity;
396 for (let y = b.y - 1; y <= b.y + z; y++) for (let x = b.x - 1; x <= b.x + z; x++) {
397 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE || s.blocked[y * SIZE + x]) continue;
398 const d = dist(x + .5, y + .5, want[0], want[1]);
399 if (d < bd) { bd = d; best = [x, y]; }
400 }
401 return best;
402 }
403 function finishItem(s, b, item, ev) {
404 const p = s.players[b.owner];
405 if (item.k === 'unit') {
406 const tile = spawnTile(s, b);
407 if (!tile) return false;
408 const u = addUnit(s, b.owner, item.id, tile[0] + .5, tile[1] + .5);
409 p.made++;
410 ev.push({ type: 'trained', owner: b.owner, kind: item.id, id: u.id });
411 if (b.rally) {
412 const r = b.rally.id && ent(s, b.rally.id);
413 if (r && (r.t === 'r' || r.kind === 'farm') && item.id === 'villager') setGather(s, u, r);
414 else { u.o = 'move'; u.tx = b.rally.x; u.ty = b.rally.y; }
415 }
416 } else if (item.k === 'tech') {
417 p.techs[item.id] = true; p.stat = {};
418 if (item.id === 'loom') for (const u of s.ents) if (u.t === 'u' && u.owner === b.owner && u.kind === 'villager') u.hp += TECHS.loom.hp.villager;
419 ev.push({ type: 'tech', owner: b.owner, id: item.id });
420 } else {
421 p.age++; p.aging = false; p.stat = {};
422 ev.push({ type: 'age', owner: b.owner, age: p.age });
423 }
424 return true;
425 }
426 function actBuilding(s, b, dt, ev) {
427 const d = BUILDINGS[b.kind];
428 if (!b.built) {
429 b.nb = b.nbNext; b.nbNext = 0;
430 if (b.nb > 0) {
431 b.prog = Math.min(1, b.prog + dt / d.time / Math.pow(b.nb, .3) * b.nb);
432 b.hp = Math.max(b.hp, Math.ceil(d.hp * b.prog));
433 if (b.prog >= 1) { b.built = true; b.hp = Math.max(b.hp, d.hp * .98 | 0); ev.push({ type: 'built', owner: b.owner, kind: b.kind, id: b.id }); s.players[b.owner].built = (s.players[b.owner].built || 0) + 1; }
434 }
435 return;
436 }
437 const head = b.q[0];
438 if (head) {
439 if (head.k === 'unit' && popOf(s, b.owner) >= popCap(s, b.owner)) { if (!head.housed) { head.housed = true; if (b.owner === 0) ev.push({ type: 'housed' }); } }
440 else {
441 head.t += dt;
442 if (head.t >= head.total) {
443 if (finishItem(s, b, head, ev)) b.q.shift();
444 else head.t = head.total - 1;
445 }
446 }
447 }
448 if (d.shoot) {
449 b.cd = Math.max(0, b.cd - dt);
450 if (b.cd <= 0) {
451 const [cx, cy] = centre(b);
452 let tgt = null, bd = d.shoot.rng + d.size / 2;
453 for (const e of s.ents) { if (e.t !== 'u' || e.owner === b.owner || e.hp <= 0) continue; const dd = dist(cx, cy, e.x, e.y); if (dd < bd) { bd = dd; tgt = e; } }
454 if (tgt) {
455 b.cd = d.shoot.reload;
456 hurt(s, tgt, Math.max(1, d.shoot.atk - stat(s, tgt.owner, tgt.kind).armor[1]), null, ev);
457 s.shots.push({ x0: cx, y0: cy, x1: tgt.x, y1: tgt.y, t: s.time });
458 ev.push({ type: 'shot', x: cx, y: cy });
459 }
460 }
461 }
462 }
463
464 /* ---------- the tick ---------- */
465 function tick(s, dt = DT) {
466 const ev = [];
467 if (s.over) return ev;
468 s.time += dt; s.tick++;
469 for (const e of s.ents.slice()) {
470 if (e.hp <= 0 && e.t !== 'r') { if (s.byId.has(e.id)) die(s, e, killerOf(e), ev); continue; }
471 if (!s.byId.has(e.id)) continue;
472 if (e.t === 'u') actUnit(s, e, dt, ev); else if (e.t === 'b') actBuilding(s, e, dt, ev);
473 }
474 for (const e of s.ents.slice()) if (e.hp <= 0 && e.t !== 'r') die(s, e, killerOf(e), ev);
475 s.shots = s.shots.filter(x => s.time - x.t < SHOT_LIFE);
476 if (s.tick % FOG_EVERY === 0) updateFog(s);
477 for (const o of [0, 1]) {
478 if (!s.ents.some(e => e.t === 'b' && e.owner === o && e.built && T.KEEPS.includes(e.kind))) {
479 s.over = { winner: 1 - o, time: s.time };
480 ev.push({ type: 'over', winner: 1 - o });
481 break;
482 }
483 }
484 for (const x of ev) s.events.push(x);
485 if (s.events.length > 200) s.events.splice(0, s.events.length - 200);
486 return ev;
487 }
488
489 /* ---------- commands ---------- */
490 const mine = (s, owner, ids) => (Array.isArray(ids) ? ids : []).map(id => ent(s, id)).filter(e => e && e.t === 'u' && e.owner === owner);
491 // free tiles nearest a point, one per unit, so a group does not pile on a single tile
492 function spread(s, x, y, n) {
493 const out = [], tx = clamp(Math.floor(x), 0, SIZE - 1), ty = clamp(Math.floor(y), 0, SIZE - 1);
494 for (let r = 0; r < 8 && out.length < n; r++) {
495 const ring = [];
496 for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) {
497 if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
498 const a = tx + dx, c = ty + dy;
499 if (a >= 0 && c >= 0 && a < SIZE && c < SIZE && !s.blocked[c * SIZE + a]) ring.push([a + .5, c + .5, dist(a + .5, c + .5, x, y)]);
500 }
501 ring.sort((p, q) => p[2] - q[2]);
502 for (const t of ring) if (out.length < n) out.push(t);
503 }
504 return out;
505 }
506 // cmd: {type: 'move'|'amove', x, y} | {type: 'attack'|'gather'|'build', target} | {type: 'stop'}; returns how many obeyed
507 function order(s, owner, ids, cmd) {
508 const units = mine(s, owner, ids);
509 if (!cmd || !units.length || s.over) return 0;
510 let n = 0;
511 if (cmd.type === 'stop') { for (const u of units) { idle(u); n++; } return n; }
512 if (cmd.type === 'move' || cmd.type === 'amove') {
513 const x = clamp(finite(cmd.x), 0, SIZE - .01), y = clamp(finite(cmd.y), 0, SIZE - .01);
514 const spots = spread(s, x, y, units.length);
515 units.forEach((u, i) => { const sp = spots[i] || spots[spots.length - 1] || [x, y]; idle(u); u.o = cmd.type; u.tx = sp[0]; u.ty = sp[1]; n++; });
516 return n;
517 }
518 const target = ent(s, cmd.target | 0);
519 if (!target) return 0;
520 for (const u of units) {
521 const soldier = UNITS[u.kind].cls !== 'villager';
522 if (cmd.type === 'attack' && target.owner !== owner && target.t !== 'r' && target.owner >= 0) { idle(u); u.o = 'attack'; u.tgt = target.id; n++; }
523 else if (cmd.type === 'gather' && !soldier && nodeType(target) && target.amount > 0 && (target.t === 'r' || target.owner === owner)) { idle(u); setGather(s, u, target); n++; }
524 else if (cmd.type === 'build' && !soldier && target.t === 'b' && target.owner === owner && !target.built) { idle(u); u.o = 'build'; u.tgt = target.id; n++; }
525 }
526 return n;
527 }
528 // why a building cannot go at (x, y), or null when it can
529 function whyNot(s, owner, kind, x, y) {
530 const d = BUILDINGS[kind];
531 if (!d) return 'unknown building';
532 if (!Number.isInteger(x) || !Number.isInteger(y)) return 'bad place';
533 const p = s.players[owner];
534 if (p.age < d.age) return `needs the ${AGES[d.age].name}`;
535 if (!T.canAfford(p.res, d.cost)) return `needs ${T.costText(d.cost)}`;
536 if (x < 1 || y < 1 || x + d.size > SIZE - 1 || y + d.size > SIZE - 1) return 'too close to the edge';
537 for (let dy = 0; dy < d.size; dy++) for (let dx = 0; dx < d.size; dx++) {
538 if (s.blocked[(y + dy) * SIZE + x + dx]) return 'something is in the way';
539 if (owner === 0 && !s.seen[(y + dy) * SIZE + x + dx]) return 'unexplored ground';
540 }
541 return null;
542 }
543 function place(s, owner, kind, x, y, ids) {
544 if (s.over) return { ok: false, why: 'the game is over' };
545 const why = whyNot(s, owner, kind, x, y);
546 if (why) return { ok: false, why };
547 const builders = mine(s, owner, ids).filter(u => UNITS[u.kind].cls === 'villager');
548 if (!builders.length) return { ok: false, why: 'select a villager to build' };
549 pay(s.players[owner], BUILDINGS[kind].cost);
550 const b = addBuilding(s, owner, kind, x, y, false);
551 const z = BUILDINGS[kind].size;
552 // anyone standing where the walls go is stepped out of the way
553 for (const u of s.ents) if (u.t === 'u' && u.x > x - .01 && u.x < x + z && u.y > y - .01 && u.y < y + z) {
554 const t = G.nearestTile(SIZE, Math.floor(u.x), Math.floor(u.y), (a, c) => !s.blocked[c * SIZE + a], 6);
555 if (t) { u.x = t[0] + .5; u.y = t[1] + .5; u.path = null; }
556 }
557 for (const u of builders) { idle(u); u.o = 'build'; u.tgt = b.id; }
558 return { ok: true, id: b.id };
559 }
560 const mkItem = (k, id, cost, time) => ({ k, id, cost, t: 0, total: time });
561 function queueOn(s, owner, bid) {
562 const b = ent(s, bid);
563 return b && b.t === 'b' && b.owner === owner && b.built && !s.over ? b : null;
564 }
565 function train(s, owner, bid, kind) {
566 const b = queueOn(s, owner, bid), u = UNITS[kind];
567 if (!b || !u || !(BUILDINGS[b.kind].trains || []).includes(kind)) return { ok: false, why: 'cannot train that here' };
568 const p = s.players[owner];
569 if (p.age < u.age) return { ok: false, why: `needs the ${AGES[u.age].name}` };
570 if (b.q.length >= QUEUE_MAX) return { ok: false, why: 'queue is full' };
571 if (!T.canAfford(p.res, u.cost)) return { ok: false, why: `needs ${T.costText(u.cost)}` };
572 pay(p, u.cost);
573 b.q.push(mkItem('unit', kind, u.cost, u.time));
574 return { ok: true };
575 }
576 function research(s, owner, bid, id) {
577 const b = queueOn(s, owner, bid), t = TECHS[id];
578 if (!b || !t || !(BUILDINGS[b.kind].techs || []).includes(id)) return { ok: false, why: 'cannot research that here' };
579 const p = s.players[owner];
580 if (p.techs[id]) return { ok: false, why: 'already researched' };
581 if (s.ents.some(e => e.t === 'b' && e.owner === owner && e.q.some(i => i.k === 'tech' && i.id === id))) return { ok: false, why: 'already being researched' };
582 if (p.age < t.age) return { ok: false, why: `needs the ${AGES[t.age].name}` };
583 if (b.q.length >= QUEUE_MAX) return { ok: false, why: 'queue is full' };
584 if (!T.canAfford(p.res, t.cost)) return { ok: false, why: `needs ${T.costText(t.cost)}` };
585 pay(p, t.cost);
586 b.q.push(mkItem('tech', id, t.cost, t.time));
587 return { ok: true };
588 }
589 function ageUp(s, owner, bid) {
590 const b = queueOn(s, owner, bid), p = s.players[owner];
591 if (!b || b.kind !== 'town-center') return { ok: false, why: 'research ages at a town center' };
592 const next = AGES[p.age + 1];
593 if (!next) return { ok: false, why: 'already the last age' };
594 if (p.aging) return { ok: false, why: 'already advancing' };
595 if (!ageOpen(s, owner, next.needs)) return { ok: false, why: 'needs ' + next.needs.map(g => g.map(k => BUILDINGS[k].name).join(' or ')).join(' and ') };
596 if (!T.canAfford(p.res, next.cost)) return { ok: false, why: `needs ${T.costText(next.cost)}` };
597 pay(p, next.cost); p.aging = true;
598 b.q.push(mkItem('age', next.name, next.cost, next.time));
599 return { ok: true };
600 }
601 function cancel(s, owner, bid, i) {
602 const b = queueOn(s, owner, bid);
603 if (!b || !Number.isInteger(i) || i < 0 || i >= b.q.length) return false;
604 const [item] = b.q.splice(i, 1);
605 refund(s.players[owner], item.cost);
606 if (item.k === 'age') s.players[owner].aging = false;
607 return true;
608 }
609 function rally(s, owner, bid, x, y, target = 0) {
610 const b = ent(s, bid);
611 if (!owns(s, owner, b) || b.t !== 'b') return false;
612 b.rally = { x: clamp(finite(x), 0, SIZE - .01), y: clamp(finite(y), 0, SIZE - .01), id: target | 0 };
613 return true;
614 }
615 function demolish(s, owner, ids) {
616 let n = 0;
617 const ev = [];
618 for (const id of Array.isArray(ids) ? ids : []) {
619 const e = ent(s, id);
620 if (e && e.owner === owner && e.t !== 'r') { if (e.t === 'b') for (const it of e.q) if (it.k === 'age') s.players[owner].aging = false; e.hp = 0; die(s, e, null, ev); n++; }
621 }
622 return n;
623 }
624
625 // giving up hands the game to the other side
626 function resign(s, owner) {
627 if (s.over || (owner !== 0 && owner !== 1)) return false;
628 s.over = { winner: 1 - owner, time: s.time, resigned: true };
629 s.events.push({ type: 'over', winner: 1 - owner });
630 return true;
631 }
632
633 /* ---------- queries for the page and the bot ---------- */
634 // the entity under a point: a unit within half a tile first, then a building or resource whose footprint holds it
635 function at(s, x, y, ok = () => true) {
636 let best = null, bd = .6;
637 for (const e of s.ents) if (e.t === 'u' && ok(e)) { const d = dist(x, y, e.x, e.y); if (d < bd) { bd = d; best = e; } }
638 if (best) return best;
639 for (const e of s.ents) {
640 if (e.t === 'u' || !ok(e)) continue;
641 const z = sizeOf(e);
642 if (x >= e.x && x < e.x + z && y >= e.y && y < e.y + z) return e;
643 }
644 return null;
645 }
646 const ofOwner = (s, owner, test = () => true) => s.ents.filter(e => e.owner === owner && e.t !== 'r' && test(e));
647 const score = (s, owner) => { const p = s.players[owner]; return { made: p.made, killed: p.killed, lost: p.lost, gathered: Math.floor(p.gathered), time: s.time }; };
648
649 /* ---------- saving ---------- */
650 function snapshot(s) {
651 return {
652 v: 1, size: SIZE, time: s.time, tick: s.tick, rng: s.rng, nextId: s.nextId, level: s.level, over: s.over, ai: s.ai, lastAlert: s.lastAlert,
653 seen: Array.from(s.seen),
654 players: s.players.map(p => ({ res: p.res, age: p.age, techs: p.techs, aging: p.aging, made: p.made, killed: p.killed, lost: p.lost, gathered: p.gathered, built: p.built || 0 })),
655 ents: s.ents.map(e => (e.t === 'u' ? { ...e, path: null } : e)),
656 };
657 }
658 const ORDERS = ['idle', 'move', 'amove', 'attack', 'gather', 'return', 'build'];
659 const num = (v, lo, hi, d = 0) => (Number.isFinite(v) ? clamp(v, lo, hi) : d);
660 // rebuild a state from saved JSON text or an object; null when it is not a game of this version
661 function restore(data) {
662 try {
663 const o = typeof data === 'string' ? JSON.parse(data) : data;
664 if (!o || o.v !== 1 || o.size !== SIZE || !Array.isArray(o.ents) || !Array.isArray(o.players) || o.players.length !== 2 || o.ents.length > 3000) return null;
665 const s = newGame(1, 1);
666 s.ents = []; s.nextId = 1;
667 s.time = num(o.time, 0, 1e7); s.tick = num(o.tick, 0, 1e9) | 0; s.rng = (num(o.rng, 0, 4294967295) >>> 0) || 1; s.level = clamp(num(o.level, 0, 2) | 0, 0, 2);
668 s.lastAlert = num(o.lastAlert, -99, 1e7, -99);
669 s.over = o.over && (o.over.winner === 0 || o.over.winner === 1) ? { winner: o.over.winner, time: num(o.over.time, 0, 1e7), resigned: !!o.over.resigned } : null;
670 s.ai = [0, 1].map(i => (o.ai && typeof o.ai[i] === 'object' && o.ai[i] ? o.ai[i] : {}));
671 s.players = o.players.map(p => {
672 const res = {};
673 for (const r of RES) res[r] = num(p && p.res && p.res[r], 0, 1e6);
674 const techs = {};
675 for (const id in (p && p.techs) || {}) if (TECHS[id] && p.techs[id]) techs[id] = true;
676 return { res, age: clamp(num(p && p.age, 0, 3) | 0, 0, 3), techs, stat: {}, aging: !!(p && p.aging), made: num(p && p.made, 0, 1e6), killed: num(p && p.killed, 0, 1e6), lost: num(p && p.lost, 0, 1e6), gathered: num(p && p.gathered, 0, 1e9), built: num(p && p.built, 0, 1e6) };
677 });
678 const seenIn = Array.isArray(o.seen) && o.seen.length === SIZE * SIZE ? o.seen : [];
679 s.seen = new Uint8Array(SIZE * SIZE); seenIn.forEach((v, i) => { s.seen[i] = v === 1 || v === 2 ? v : 0; });
680 let top = 0;
681 for (const e of o.ents) {
682 if (!e || (e.t !== 'u' && e.t !== 'b' && e.t !== 'r')) continue;
683 const table = e.t === 'u' ? UNITS : e.t === 'b' ? BUILDINGS : NODES;
684 if (!Object.prototype.hasOwnProperty.call(table, e.kind)) continue;
685 const owner = e.t === 'r' ? -1 : e.owner === 0 || e.owner === 1 ? e.owner : -2;
686 if (owner === -2 || !Number.isFinite(e.x) || !Number.isFinite(e.y)) continue;
687 const z = e.t === 'b' ? BUILDINGS[e.kind].size : e.t === 'r' ? 1 : 0;
688 const id = e.id | 0;
689 if (id < 1 || s.ents.some(x => x.id === id)) continue;
690 top = Math.max(top, id);
691 const base = { t: e.t, kind: e.kind, owner, id };
692 if (e.t === 'u') {
693 s.ents.push({ ...base, x: clamp(e.x, 0, SIZE - .01), y: clamp(e.y, 0, SIZE - .01), hp: num(e.hp, 1, 1000, 1), o: ORDERS.includes(e.o) ? e.o : 'idle', path: null, tgt: e.tgt | 0, tx: num(e.tx, 0, SIZE), ty: num(e.ty, 0, SIZE), cd: 0, scan: 0, carry: { type: RES.includes(e.carry && e.carry.type) ? e.carry.type : '', n: num(e.carry && e.carry.n, 0, 100) }, res: e.res | 0, then: e.then && Number.isFinite(e.then.x) && Number.isFinite(e.then.y) ? { x: clamp(e.then.x, 0, SIZE), y: clamp(e.then.y, 0, SIZE) } : null, fails: 0, repath: 0 });
694 } else {
695 const x = clamp(e.x | 0, 0, SIZE - z), y = clamp(e.y | 0, 0, SIZE - z);
696 if (e.t === 'r') s.ents.push({ ...base, x, y, amount: num(e.amount, 0, 5000) });
697 else {
698 const d = BUILDINGS[e.kind];
699 const q = (Array.isArray(e.q) ? e.q : []).slice(0, QUEUE_MAX).filter(it => it && (it.k === 'unit' ? UNITS[it.id] : it.k === 'tech' ? TECHS[it.id] : it.k === 'age')).map(it => ({ k: it.k, id: it.k === 'age' ? String(it.id) : it.id, cost: {}, t: num(it.t, 0, 1e4), total: Math.max(1, num(it.total, 1, 1e4, 10)) }));
700 for (const it of q) it.cost = it.k === 'unit' ? { ...UNITS[it.id].cost } : it.k === 'tech' ? { ...TECHS[it.id].cost } : { ...(AGES.find(a => a.name === it.id) || { cost: {} }).cost };
701 const b = { ...base, x, y, hp: num(e.hp, 1, d.hp, d.hp), built: !!e.built, prog: num(e.prog, 0, 1), q, rally: e.rally && Number.isFinite(e.rally.x) && Number.isFinite(e.rally.y) ? { x: clamp(e.rally.x, 0, SIZE), y: clamp(e.rally.y, 0, SIZE), id: e.rally.id | 0 } : null, cd: 0, nb: 0, nbNext: 0 };
702 if (e.kind === 'farm') b.amount = num(e.amount, 0, T.FARM_FOOD, T.FARM_FOOD);
703 s.ents.push(b);
704 }
705 }
706 }
707 s.nextId = top + 1;
708 index(s);
709 // a game with no keep for someone is over or broken: refuse a save that has neither town center
710 if (!s.ents.some(e => e.t === 'b' && e.owner === 0 && T.KEEPS.includes(e.kind)) && !s.over) return null;
711 updateFog(s);
712 return s;
713 } catch (err) { return null; }
714 }
715
716 const api = {
717 SIZE, DT, QUEUE_MAX, LEVELS, START, newGame, tick, order, place, whyNot, train, research, ageUp, cancel, rally, demolish, resign,
718 popOf, popCap, has, ofOwner, at, findNode, dropoff, nearest, distTo, centre, box, spread, stat, maxHp, visibleAt, score, snapshot, restore,
719 addUnit, addBuilding, addNode, index, nodeType, ageOpen, clsOf, rand,
720 };
721 if (typeof module !== 'undefined') module.exports = api; else root.Realm = api;
722 })(typeof window !== 'undefined' ? window : globalThis);
empire/realm.test.mjs added +203
@@ -0,0 +1,203 @@
1 import { test, expect } from 'bun:test';
2 import R from './realm.js';
3 import B from './regent.js';
4 import G from './grid.js';
5 import T from './tables.js';
6
7 const run = (s, seconds, bots = []) => { for (let t = 0; t < seconds; t += R.DT) { for (const o of bots) B.step(s, o, R.DT); R.tick(s, R.DT); } };
8 const mine = (s, kind) => R.ofOwner(s, 0, e => e.kind === kind);
9 const quiet = () => { const s = R.newGame(3, 1); s.ents.filter(e => e.owner === 1).forEach(e => { e.hp = 1e9; }); return s; };
10
11 test('the grid finds a way round a wall and says so when there is none', () => {
12 const size = 10, blocked = new Uint8Array(size * size);
13 for (let y = 0; y < 8; y++) blocked[y * size + 5] = 1;
14 const path = G.findPath(blocked, size, 1, 1, (x, y) => x === 8 && y === 1, (x, y) => Math.hypot(8 - x, 1 - y));
15 expect(path.at(-1)).toEqual([8, 1]);
16 expect(path.some(([x, y]) => y >= 8)).toBe(true);
17 for (let y = 0; y < size; y++) blocked[y * size + 5] = 1;
18 expect(G.findPath(blocked, size, 1, 1, x => x === 8, () => 0)).toBeNull();
19 });
20
21 test('a corner is not cut between two blocked tiles', () => {
22 const size = 4, blocked = new Uint8Array(size * size);
23 blocked[0 * size + 1] = 1; blocked[1 * size + 0] = 1;
24 expect(G.findPath(blocked, size, 0, 0, (x, y) => x === 1 && y === 1, () => 0)).toBeNull();
25 });
26
27 test('the map is the same for both sides and a seed makes the same world', () => {
28 const a = R.newGame(5, 1), b = R.newGame(5, 1), c = R.newGame(6, 1);
29 expect(JSON.stringify(R.snapshot(a))).toBe(JSON.stringify(R.snapshot(b)));
30 expect(JSON.stringify(R.snapshot(a))).not.toBe(JSON.stringify(R.snapshot(c)));
31 for (const kind of ['tree', 'gold', 'stone', 'berries']) {
32 expect(a.ents.filter(e => e.kind === kind && e.t === 'r').length % 2).toBe(0);
33 }
34 expect(mine(a, 'town-center').length).toBe(1);
35 expect(R.ofOwner(a, 1, e => e.kind === 'town-center').length).toBe(1);
36 expect(R.ofOwner(a, 0, e => e.kind === 'villager').length).toBe(4);
37 });
38
39 test('villagers walk to a tree, cut wood and bring it to the town center', () => {
40 const s = quiet(), vills = mine(s, 'villager').map(v => v.id);
41 const tc = mine(s, 'town-center')[0], tree = R.nearest(s, tc.x, tc.y, e => e.kind === 'tree');
42 const before = s.players[0].res.wood;
43 expect(R.order(s, 0, vills, { type: 'gather', target: tree.id })).toBe(4);
44 run(s, 90);
45 expect(s.players[0].res.wood).toBeGreaterThan(before + 20);
46 expect(s.players[0].gathered).toBeGreaterThan(20);
47 });
48
49 test('a house raises the population cap once it is built, and costs wood', () => {
50 const s = quiet(), vills = mine(s, 'villager').map(v => v.id);
51 expect(R.popCap(s, 0)).toBe(5);
52 const wood = s.players[0].res.wood;
53 let spot = null;
54 for (let x = 9; x < 30 && !spot; x++) if (!R.whyNot(s, 0, 'house', x, 27)) spot = [x, 27];
55 expect(spot).not.toBeNull();
56 const r = R.place(s, 0, 'house', spot[0], spot[1], vills);
57 expect(r.ok).toBe(true);
58 expect(s.players[0].res.wood).toBe(wood - T.BUILDINGS.house.cost.wood);
59 expect(R.popCap(s, 0)).toBe(5);
60 run(s, 20);
61 expect(R.popCap(s, 0)).toBe(10);
62 });
63
64 test('a building is refused where something stands, off the edge, or when it cannot be paid for', () => {
65 const s = quiet(), tc = mine(s, 'town-center')[0];
66 expect(R.whyNot(s, 0, 'house', tc.x, tc.y)).toBe('something is in the way');
67 expect(R.whyNot(s, 0, 'house', 0, 0)).toBe('too close to the edge');
68 expect(R.whyNot(s, 0, 'house', 20.5, 20)).toBe('bad place');
69 expect(R.whyNot(s, 0, 'castle', 12, 20)).toMatch(/needs the Castle Age/);
70 s.players[0].res.wood = 0;
71 expect(R.whyNot(s, 0, 'house', 12, 27)).toMatch(/needs 30 wood/);
72 expect(R.place(s, 0, 'house', 12, 27, mine(s, 'villager').map(v => v.id)).ok).toBe(false);
73 });
74
75 test('training costs resources, queues up to five, and waits for a house when the town is full', () => {
76 const s = quiet(), tc = mine(s, 'town-center')[0];
77 s.players[0].res.food = 1000;
78 expect(R.train(s, 0, tc.id, 'villager').ok).toBe(true);
79 expect(s.players[0].res.food).toBe(950);
80 expect(R.train(s, 0, tc.id, 'knight').ok).toBe(false);
81 for (let i = 0; i < 4; i++) expect(R.train(s, 0, tc.id, 'villager').ok).toBe(true);
82 expect(R.train(s, 0, tc.id, 'villager')).toEqual({ ok: false, why: 'queue is full' });
83 run(s, 30);
84 expect(R.popOf(s, 0)).toBe(R.popCap(s, 0));
85 expect(tc.q.length).toBeGreaterThan(0);
86 expect(R.cancel(s, 0, tc.id, 0)).toBe(true);
87 expect(s.players[0].res.food).toBe(750 + 50);
88 });
89
90 test('the next age needs its buildings, then its price, then time', () => {
91 const s = quiet(), tc = mine(s, 'town-center')[0];
92 s.players[0].res.food = 2000; s.players[0].res.wood = 2000;
93 expect(R.ageUp(s, 0, tc.id).why).toBe('needs Barracks');
94 const barracks = R.addBuilding(s, 0, 'barracks', 14, 20, true);
95 expect(barracks.built).toBe(true);
96 expect(R.ageUp(s, 0, tc.id).ok).toBe(true);
97 expect(R.ageUp(s, 0, tc.id).why).toBe('already advancing');
98 run(s, 31);
99 expect(s.players[0].age).toBe(1);
100 expect(s.players[0].aging).toBe(false);
101 });
102
103 test('a technology is researched once and changes the stats of the units it names', () => {
104 const s = quiet(), tc = mine(s, 'town-center')[0];
105 s.players[0].res.food = 500; s.players[0].res.gold = 500;
106 const hp = R.stat(s, 0, 'villager').hp;
107 expect(R.research(s, 0, tc.id, 'loom').ok).toBe(true);
108 expect(R.research(s, 0, tc.id, 'loom').why).toBe('already being researched');
109 run(s, 21);
110 expect(R.research(s, 0, tc.id, 'loom').why).toBe('already researched');
111 expect(T.statsOf('villager', { loom: true }).hp).toBe(hp + 15);
112 });
113
114 test('soldiers fight: spearmen beat a knight on bonus damage, archers shoot from range', () => {
115 const s = quiet();
116 const sp = [0, 1, 2, 3].map(i => R.addUnit(s, 0, 'spearman', 20 + i * .3, 20));
117 const kn = R.addUnit(s, 1, 'knight', 21.5, 20);
118 const bow = R.addUnit(s, 0, 'archer', 20, 17);
119 run(s, 25);
120 expect(s.byId.has(kn.id)).toBe(false);
121 expect(s.players[0].killed).toBeGreaterThanOrEqual(1);
122 expect(T.statsOf('archer').rng).toBeGreaterThan(0);
123 expect(sp.length + bow.id).toBeGreaterThan(0);
124 });
125
126 test('an enemy building under attack raises an alert once in a while', () => {
127 const s = R.newGame(3, 1);
128 const raider = R.addUnit(s, 1, 'militia', 12, 28);
129 R.order(s, 1, [raider.id], { type: 'attack', target: mine(s, 'town-center')[0].id });
130 const seen = [];
131 for (let i = 0; i < 400; i++) seen.push(...R.tick(s, R.DT));
132 expect(seen.some(e => e.type === 'alert')).toBe(true);
133 });
134
135 test('orders are checked: strangers, bad numbers and dead targets do nothing', () => {
136 const s = quiet();
137 const enemy = R.ofOwner(s, 1, e => e.kind === 'villager')[0];
138 expect(R.order(s, 0, [enemy.id], { type: 'move', x: 5, y: 5 })).toBe(0);
139 expect(R.order(s, 0, 'nope', { type: 'move', x: 5, y: 5 })).toBe(0);
140 const v = mine(s, 'villager')[0];
141 expect(R.order(s, 0, [v.id], { type: 'move', x: NaN, y: Infinity })).toBe(1);
142 expect(Number.isFinite(v.tx) && Number.isFinite(v.ty)).toBe(true);
143 expect(R.order(s, 0, [v.id], { type: 'attack', target: 99999 })).toBe(0);
144 expect(R.order(s, 0, [v.id], null)).toBe(0);
145 });
146
147 test('resigning ends the game for the other side and only once', () => {
148 const s = R.newGame(1, 1);
149 expect(R.resign(s, 0)).toBe(true);
150 expect(s.over.winner).toBe(1);
151 expect(s.over.resigned).toBe(true);
152 expect(R.resign(s, 1)).toBe(false);
153 expect(R.train(s, 0, mine(s, 'town-center')[0].id, 'villager').ok).toBe(false);
154 expect(R.place(s, 0, 'house', 12, 27, []).why).toBe('the game is over');
155 });
156
157 test('a saved game comes back the same, and a damaged save is refused', () => {
158 const s = R.newGame(9, 1);
159 run(s, 40, [0, 1]);
160 const text = JSON.stringify(R.snapshot(s));
161 const back = R.restore(text);
162 expect(back).not.toBeNull();
163 expect(R.snapshot(back).ents.length).toBe(R.snapshot(s).ents.length);
164 expect(back.players[0].res).toEqual(s.players[0].res);
165 run(back, 5); run(s, 5);
166 expect(back.time).toBeCloseTo(s.time, 5);
167 expect(R.restore('{')).toBeNull();
168 expect(R.restore(JSON.stringify({ ...JSON.parse(text), size: 9 }))).toBeNull();
169 expect(R.restore(JSON.stringify({ ...JSON.parse(text), ents: [{ t: 'u', kind: 'dragon', owner: 0, x: 1, y: 1, id: 1 }] }))).toBeNull();
170 const hostile = JSON.parse(text);
171 hostile.ents[0].x = 'x'; hostile.players[0].res.food = 'lots'; hostile.players[0].techs = { __proto__: 1, loom: true, bogus: true };
172 const r = R.restore(JSON.stringify(hostile));
173 if (r) { expect(Number.isFinite(r.players[0].res.food)).toBe(true); expect(Object.keys(r.players[0].techs).every(k => T.TECHS[k])).toBe(true); }
174 });
175
176 test('the bot raises an economy and an army on its own, level by level', () => {
177 const s = R.newGame(2, 1);
178 run(s, 240, [1]);
179 const me = R.ofOwner(s, 1);
180 expect(me.filter(e => e.kind === 'villager').length).toBeGreaterThan(8);
181 expect(me.some(e => e.kind === 'house')).toBe(true);
182 expect(s.players[1].gathered).toBeGreaterThan(300);
183 expect(B.PLANS.length).toBe(R.LEVELS.length);
184 });
185
186 test('a bot against a bot ends in a win for one of them within the hour', () => {
187 const s = R.newGame(7, 1);
188 let steps = 0;
189 while (!s.over && s.time < 3600) { B.step(s, 0, R.DT); B.step(s, 1, R.DT); R.tick(s, R.DT); steps++; }
190 expect(s.over).not.toBeNull();
191 expect([0, 1]).toContain(s.over.winner);
192 const loser = 1 - s.over.winner;
193 expect(s.ents.some(e => e.t === 'b' && e.owner === loser && e.built && T.KEEPS.includes(e.kind))).toBe(false);
194 expect(steps).toBeLessThan(36000);
195 }, 60000);
196
197 test('a tick is cheap enough for 60 frames a second on a phone', () => {
198 const s = R.newGame(4, 2);
199 run(s, 200, [0, 1]);
200 const t = performance.now();
201 for (let i = 0; i < 200; i++) { B.step(s, 0, R.DT); B.step(s, 1, R.DT); R.tick(s, R.DT); }
202 expect((performance.now() - t) / 200).toBeLessThan(4);
203 });
empire/regent.js added +184
@@ -0,0 +1,184 @@
1 'use strict';
2 // The bot of Empire Age. It plays by the same commands as the person (place, train, research, ageUp, order) and
3 // sees everything the map holds; the only edge a harder level gives is a faster gather rate (see LEVELS in realm.js).
4 // It builds an economy, raises houses, climbs the ages, trains a mix of soldiers, and sends the army at the enemy
5 // in waves. `step(state, owner, dt)` is called every frame and thinks once a second; the same bot can play the
6 // person's side as an autopilot.
7 (function (root) {
8 const R = typeof module !== 'undefined' ? require('./realm.js') : root.Realm;
9 const T = typeof module !== 'undefined' ? require('./tables.js') : root.Tables;
10 const G = typeof module !== 'undefined' ? require('./grid.js') : root.Grid;
11 const { BUILDINGS, UNITS, AGES } = T;
12
13 const THINK = 1; // seconds between two rounds of thought
14 // per level: villagers wanted per age, the first attack, and the soldiers that make a wave
15 const PLANS = [
16 { vills: [14, 18, 22, 24], first: 540, wave: 10 },
17 { vills: [18, 26, 34, 40], first: 360, wave: 12 },
18 { vills: [20, 30, 40, 46], first: 300, wave: 14 },
19 ];
20 const SPLIT = [{ food: .55, wood: .32, gold: .08, stone: .05 }, { food: .45, wood: .27, gold: .2, stone: .08 }, { food: .4, wood: .24, gold: .27, stone: .09 }, { food: .38, wood: .22, gold: .3, stone: .1 }];
21 const TECH_ORDER = ['loom', 'wheelbarrow', 'forging', 'fletching', 'scale-mail', 'padded-mail'];
22
23 const isVill = e => e.t === 'u' && e.kind === 'villager';
24 function typeOf(s, v) { return v.o === 'gather' ? R.nodeType(s.byId.get(v.tgt) || {}) || v.carry.type : v.o === 'return' ? v.carry.type : ''; }
25
26 // a place for a building near a point with a tile of room all round it, so paths are never walled shut
27 function site(s, owner, kind, cx, cy, min = 0, max = 10) {
28 const z = BUILDINGS[kind].size;
29 for (let r = min; r <= max; r++) {
30 let best = null, bd = Infinity;
31 for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) {
32 if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
33 const x = Math.round(cx + dx - z / 2), y = Math.round(cy + dy - z / 2);
34 if (R.whyNot(s, owner, kind, x, y) !== null) continue;
35 let room = true;
36 for (let ty = y - 1; ty <= y + z && room; ty++) for (let tx = x - 1; tx <= x + z; tx++) if (tx >= 0 && ty >= 0 && tx < s.size && ty < s.size && s.blocked[ty * s.size + tx]) { room = false; break; }
37 if (!room) continue;
38 const d = Math.hypot(dx, dy);
39 if (d < bd) { bd = d; best = [x, y]; }
40 }
41 if (best) return best;
42 }
43 return null;
44 }
45 const countOf = (s, o, kind) => s.ents.filter(e => e.t === 'b' && e.owner === o && e.kind === kind).length;
46 const builtOf = (s, o, kind) => s.ents.filter(e => e.t === 'b' && e.owner === o && e.kind === kind && e.built);
47
48 const near0 = (s, o, x, y) => !!R.nearest(s, x, y, e => e.t === 'u' && e.owner === 1 - o && e.kind !== 'villager', 11);
49 function think(s, o) {
50 const ai = s.ai[o], p = s.players[o], plan = PLANS[s.level], foe = 1 - o;
51 const tcs = builtOf(s, o, 'town-center');
52 if (!tcs.length) return;
53 const tc = tcs[0], [tx, ty] = R.centre(tc);
54 const vills = R.ofOwner(s, o, isVill);
55 const army = R.ofOwner(s, o, e => e.t === 'u' && !isVill(e));
56 const pop = R.popOf(s, o), cap = R.popCap(s, o);
57 const enemyKeep = R.nearest(s, tx, ty, e => e.t === 'b' && e.owner === foe && e.built && T.KEEPS.includes(e.kind)) || R.nearest(s, tx, ty, e => e.t === 'b' && e.owner === foe);
58 const toward = enemyKeep ? Math.atan2(enemyKeep.y - ty, enemyKeep.x - tx) : 0;
59 const spare = () => vills.find(v => v.o === 'idle') || vills.find(v => v.o === 'gather' && v.carry.type === 'wood' && v.carry.n < 4) || vills.find(v => v.o === 'gather' && v.carry.n < 4);
60 const build = (kind, cx, cy, helper = null, min = 0, max = 14) => {
61 if (!T.canAfford(p.res, BUILDINGS[kind].cost) || p.age < BUILDINGS[kind].age) return false;
62 const v = helper || spare();
63 if (!v) return false;
64 const at = site(s, o, kind, cx, cy, min, max);
65 return !!at && R.place(s, o, kind, at[0], at[1], [v.id]).ok;
66 };
67
68 /* houses first: the cap decides everything else */
69 const housing = s.ents.filter(e => e.t === 'b' && e.owner === o && e.kind === 'house' && !e.built).length;
70 if (cap < T.MAX_POP && pop + 3 + Math.floor(army.length / 6) >= cap + housing * 5 && housing < 2) build('house', tx - Math.cos(toward) * 4, ty - Math.sin(toward) * 4, null, 3, 12);
71
72 /* villagers: keep the town center busy until the wanted number */
73 const want = plan.vills[p.age];
74 if (vills.length + tc.q.filter(i => i.k === 'unit').length < want && tc.q.length < 2 && !p.aging) R.train(s, o, tc.id, 'villager');
75
76 /* put idle villagers to work where the shortfall is greatest */
77 const share = SPLIT[p.age], have = { food: 0, wood: 0, gold: 0, stone: 0 };
78 for (const v of vills) { const t = typeOf(s, v); if (t) have[t]++; }
79 const total = Math.max(1, vills.length);
80 for (const v of vills) {
81 if (v.o !== 'idle') continue;
82 let pick = 'wood', gap = -Infinity;
83 for (const r of T.RES) {
84 const g = share[r] * total - have[r];
85 if (g > gap) { gap = g; pick = r; }
86 }
87 if (!assign(s, o, v, pick, tc, build)) assign(s, o, v, 'wood', tc, build);
88 have[pick]++;
89 }
90
91 /* the build order */
92 const have1 = k => countOf(s, o, k);
93 if (vills.length >= 7 && !have1('barracks')) build('barracks', tx + Math.cos(toward) * 6, ty + Math.sin(toward) * 6, null, 2, 10);
94 if (p.age >= 1 && vills.length >= 12) {
95 if (!have1('archery-range')) build('archery-range', tx + Math.cos(toward + .6) * 7, ty + Math.sin(toward + .6) * 7, null, 1, 10);
96 else if (!have1('blacksmith')) build('blacksmith', tx - 5, ty - 4, null, 1, 10);
97 else if (!have1('stable')) build('stable', tx + Math.cos(toward - .6) * 7, ty + Math.sin(toward - .6) * 7, null, 1, 10);
98 }
99 if (p.age >= 2 && vills.length >= 16) {
100 if (!have1('siege-workshop')) build('siege-workshop', tx + Math.cos(toward) * 7, ty + Math.sin(toward) * 7, null, 1, 10);
101 else if (s.level > 0 && !have1('castle') && p.res.stone >= 350) build('castle', tx + Math.cos(toward) * 7, ty + Math.sin(toward) * 7, null, 1, 10);
102 else if (have1('barracks') < 2 && p.res.wood > 400) build('barracks', tx + Math.cos(toward + 1) * 7, ty + Math.sin(toward + 1) * 7, null, 1, 10);
103 }
104
105 /* ages and technologies */
106 if (!p.aging && vills.length >= plan.vills[p.age] - 2 && (p.age < 1 || army.length >= 3 * p.age)) R.ageUp(s, o, tc.id);
107 if (p.res.food > 250 && p.res.gold > 60) for (const id of TECH_ORDER) {
108 if (p.techs[id]) continue;
109 const home = id === 'loom' || id === 'wheelbarrow' ? tc : builtOf(s, o, 'blacksmith')[0];
110 if (home && home.q.length < 1 && R.research(s, o, home.id, id).ok) break;
111 }
112
113 /* soldiers: whatever each building makes, while the villagers are enough */
114 // with the villagers in place and the next age in reach, save the food for it instead of spending it on soldiers
115 const next = AGES[p.age + 1];
116 const saving = !!next && !p.aging && vills.length >= want - 2 && R.ageOpen(s, o, next.needs) && army.length >= 3 * p.age + 2 && !near0(s, o, tx, ty);
117 if (vills.length >= want * .6 && !saving) {
118 const foeCav = R.ofOwner(s, foe, e => e.t === 'u' && UNITS[e.kind].cls === 'cavalry').length;
119 const rams = army.filter(e => e.kind === 'ram').length;
120 for (const b of s.ents) {
121 if (b.t !== 'b' || b.owner !== o || !b.built || b.kind === 'town-center' || !BUILDINGS[b.kind].trains || b.q.length >= 2) continue;
122 let kind = BUILDINGS[b.kind].trains[0];
123 if (b.kind === 'barracks') kind = foeCav > 2 || (p.res.gold < 20 && p.age >= 1) ? (p.age >= 1 ? 'spearman' : 'militia') : (p.age >= 1 && s.time % 7 < 3 ? 'spearman' : 'militia');
124 if (b.kind === 'siege-workshop' && (rams >= 3 || army.length < 8)) continue;
125 if (b.kind === 'castle' && p.res.gold < 300) continue;
126 R.train(s, o, b.id, kind);
127 if (!b.rally) R.rally(s, o, b.id, tx + Math.cos(toward) * 7, ty + Math.sin(toward) * 7);
128 }
129 }
130
131 /* war */
132 const near = R.nearest(s, tx, ty, e => e.t === 'u' && e.owner === foe && UNITS[e.kind].cls !== 'villager', 11);
133 const fighting = army.filter(e => e.o !== 'idle').length;
134 if (ai.attacking) {
135 if (army.length < 3) ai.attacking = false;
136 else for (const u of army) if (u.o === 'idle' && enemyKeep) {
137 const t = R.nearest(s, u.x, u.y, e => e.owner === foe && e.t === 'b') || enemyKeep;
138 R.order(s, o, [u.id], { type: 'amove', x: t.x + 1, y: t.y + 1 });
139 }
140 } else if (near) {
141 R.order(s, o, army.filter(u => u.o === 'idle' || u.o === 'move').map(u => u.id), { type: 'amove', x: near.x, y: near.y });
142 } else if (enemyKeep && s.time >= plan.first + (ai.wave || 0) * 120 && army.filter(u => u.kind !== 'ram').length >= plan.wave + (ai.wave || 0) * 2) {
143 ai.attacking = true; ai.wave = (ai.wave || 0) + 1;
144 R.order(s, o, army.map(u => u.id), { type: 'amove', x: enemyKeep.x + 1, y: enemyKeep.y + 1 });
145 } else if (fighting === 0 && ai.wave) {
146 // gather the survivors back at home
147 R.order(s, o, army.filter(u => u.o === 'idle' && Math.hypot(u.x - tx, u.y - ty) > 14).map(u => u.id), { type: 'move', x: tx + Math.cos(toward) * 7, y: ty + Math.sin(toward) * 7 });
148 }
149 }
150
151 // send a villager to gather `type`, building a camp or a farm first when the nearest drop-off is far
152 function assign(s, o, v, type, tc, build) {
153 const p = s.players[o];
154 const camp = type === 'wood' ? 'lumber-camp' : type === 'food' ? 'mill' : 'mining-camp';
155 let node = R.findNode(s, o, tc.x + 1.5, tc.y + 1.5, type, 40, v.bad);
156 if (type === 'food' && !node) {
157 // the berries are gone: farm
158 const farm = R.nearest(s, tc.x, tc.y, e => e.t === 'b' && e.owner === o && e.kind === 'farm' && !e.built, 10);
159 if (farm) { R.order(s, o, [v.id], { type: 'build', target: farm.id }); return true; }
160 if (build('farm', tc.x + 1.5, tc.y + 1.5, v, 2, 8)) return true;
161 return false;
162 }
163 if (!node) return false;
164 const drop = R.dropoff(s, o, node.x, node.y, type);
165 if (!drop || R.distTo(node.x + .5, node.y + .5, drop) > 6) {
166 const pending = R.nearest(s, node.x, node.y, e => e.t === 'b' && e.owner === o && e.kind === camp && !e.built, 8);
167 if (pending) { R.order(s, o, [v.id], { type: 'build', target: pending.id }); return true; }
168 if (!R.nearest(s, node.x, node.y, e => e.t === 'b' && e.owner === o && e.kind === camp, 5) && build(camp, node.x + .5, node.y + .5, v, 1, 5)) return true;
169 }
170 return R.order(s, o, [v.id], { type: 'gather', target: node.id }) > 0;
171 }
172
173 function step(s, owner, dt) {
174 if (s.over) return;
175 const ai = s.ai[owner];
176 ai.clock = (ai.clock || 0) + dt;
177 if (ai.clock < THINK) return;
178 ai.clock = 0;
179 think(s, owner);
180 }
181
182 const api = { step, think, site, PLANS };
183 if (typeof module !== 'undefined') module.exports = api; else root.Regent = api;
184 })(typeof window !== 'undefined' ? window : globalThis);
empire/session.js added +32
@@ -0,0 +1,32 @@
1 'use strict';
2 // What Empire Age keeps between visits: the game in progress (one slot) and the fastest win on each level.
3 // `store` is anything with getItem, setItem and removeItem (localStorage); a full or blocked store never throws.
4 (function (root) {
5 const R = typeof module !== 'undefined' ? require('./realm.js') : root.Realm;
6 const SAVE = 'empire-age-save', BEST = 'empire-age-best';
7
8 function write(store, s) {
9 try { store.setItem(SAVE, JSON.stringify(R.snapshot(s))); return true; } catch { return false; }
10 }
11 // the saved game, or null when there is none or it is not one of this version
12 function read(store) {
13 try {
14 const text = store.getItem(SAVE);
15 return text && text.length < 4e6 ? R.restore(text) : null;
16 } catch { return null; }
17 }
18 function forget(store) { try { store.removeItem(SAVE); } catch { /* nothing to do */ } }
19
20 // record a win of `time` seconds on `level`; says whether it beat the old record
21 function best(store, level, time) {
22 let all = {};
23 try { const o = JSON.parse(store.getItem(BEST) || '{}'); if (o && typeof o === 'object') all = o; } catch { all = {}; }
24 const old = Number(all[level]);
25 const fresh = !(old > 0) || time < old;
26 if (fresh) { all[level] = Math.round(time); try { store.setItem(BEST, JSON.stringify(all)); } catch { /* full */ } }
27 return { fresh, time: fresh ? Math.round(time) : old };
28 }
29
30 const api = { write, read, forget, best };
31 if (typeof module !== 'undefined') module.exports = api; else root.Session = api;
32 })(typeof window !== 'undefined' ? window : globalThis);
empire/smart.js added +33
@@ -0,0 +1,33 @@
1 'use strict';
2 // What a tap means for the units that are selected: the order that fits what was tapped.
3 // Ground is a move; an enemy is an attack; a tree, mine, berries or a finished farm is work for villagers;
4 // a half-built house of ours is more building. Anything else of ours is a selection, not an order.
5 (function (root) {
6 const R = typeof module !== 'undefined' ? require('./realm.js') : root.Realm;
7
8 const isVill = e => e.kind === 'villager';
9 // the order for a tap at tile point (x, y) on `target` (an entity or null), or null when the tap should select
10 function intent(s, ids, target, x, y) {
11 const own = ids.map(id => s.byId.get(id)).filter(e => e && e.t === 'u' && e.owner === 0);
12 if (!own.length) return null;
13 if (!target) return { type: 'move', x, y };
14 if (target.t !== 'r' && target.owner === 1) return { type: 'attack', target: target.id };
15 if (target.t === 'r' || (target.t === 'b' && target.kind === 'farm' && target.owner === 0 && target.built)) return { type: 'gather', target: target.id };
16 if (target.t === 'b' && target.owner === 0 && !target.built) return { type: 'build', target: target.id };
17 return null;
18 }
19
20 // carry an order out: soldiers who cannot work or build walk to the spot instead; returns how many obeyed
21 function issue(s, ids, cmd, target) {
22 if (!cmd) return 0;
23 if (cmd.type !== 'gather' && cmd.type !== 'build') return R.order(s, 0, ids, cmd);
24 const own = ids.map(id => s.byId.get(id)).filter(e => e && e.t === 'u' && e.owner === 0);
25 const workers = own.filter(isVill).map(e => e.id), others = own.filter(e => !isVill(e)).map(e => e.id);
26 let n = R.order(s, 0, workers, cmd);
27 if (others.length && target) { const [cx, cy] = R.centre(target); n += R.order(s, 0, others, { type: 'move', x: target.t === 'r' ? target.x + .5 : cx, y: target.t === 'r' ? target.y + .5 : cy }); }
28 return n;
29 }
30
31 const api = { intent, issue };
32 if (typeof module !== 'undefined') module.exports = api; else root.Smart = api;
33 })(typeof window !== 'undefined' ? window : globalThis);
empire/tables.js added +81
@@ -0,0 +1,81 @@
1 'use strict';
2 // The numbers of Empire Age: resources, ages, units, buildings and technologies, as plain data.
3 // Nothing here moves or draws; realm.js reads these tables and the page reads them to label buttons.
4 (function (root) {
5 const RES = ['food', 'wood', 'gold', 'stone'];
6 const MAX_POP = 100;
7 const CARRY = 10; // what a villager carries before walking back to a drop-off
8 // food from berries and farms, wood from trees, gold and stone from mines (per villager per second)
9 const RATE = { food: .9, farm: .9, wood: .75, gold: .65, stone: .6 };
10 const NODES = { berries: { type: 'food', amount: 200 }, tree: { type: 'wood', amount: 100 }, gold: { type: 'gold', amount: 700 }, stone: { type: 'stone', amount: 350 } };
11 const FARM_FOOD = 250, RESEED = { wood: 40 };
12
13 // `needs` is a list of groups: the age is open when each group has at least one finished building of its kinds
14 const AGES = [
15 { name: 'Dark Age' },
16 { name: 'Feudal Age', cost: { food: 500 }, time: 30, needs: [['barracks']] },
17 { name: 'Castle Age', cost: { food: 800, gold: 200 }, time: 40, needs: [['blacksmith'], ['archery-range', 'stable']] },
18 { name: 'Imperial Age', cost: { food: 1000, gold: 600 }, time: 50, needs: [['castle']] },
19 ];
20
21 // armor is [melee, pierce]; rng 0 is a melee unit; `bonus` is extra damage against a class
22 const UNITS = {
23 villager: { name: 'Villager', cls: 'villager', hp: 25, atk: 3, rng: 0, reload: 1.5, spd: 1.1, sight: 4, armor: [0, 0], cost: { food: 50 }, time: 10, from: 'town-center', age: 0, bonus: {} },
24 militia: { name: 'Militia', cls: 'infantry', hp: 40, atk: 6, rng: 0, reload: 1.4, spd: 1.1, sight: 5, armor: [1, 1], cost: { food: 60, gold: 20 }, time: 14, from: 'barracks', age: 0, bonus: { building: 2, siege: 6 } },
25 spearman: { name: 'Spearman', cls: 'infantry', hp: 45, atk: 3, rng: 0, reload: 1.4, spd: 1.1, sight: 5, armor: [0, 3], cost: { food: 35, wood: 25 }, time: 14, from: 'barracks', age: 1, bonus: { cavalry: 12 } },
26 archer: { name: 'Archer', cls: 'archer', hp: 30, atk: 4, rng: 5, reload: 1.6, spd: 1.1, sight: 7, armor: [0, 0], cost: { wood: 25, gold: 45 }, time: 15, from: 'archery-range', age: 1, bonus: { infantry: 1 } },
27 knight: { name: 'Knight', cls: 'cavalry', hp: 100, atk: 10, rng: 0, reload: 1.8, spd: 1.8, sight: 5, armor: [2, 2], cost: { food: 60, gold: 75 }, time: 20, from: ['stable', 'castle'], age: 2, bonus: { archer: 4 } },
28 ram: { name: 'Battering ram', cls: 'siege', hp: 175, atk: 3, rng: 0, reload: 2.5, spd: .75, sight: 4, armor: [0, 150], cost: { wood: 160, gold: 75 }, time: 30, from: 'siege-workshop', age: 2, bonus: { building: 45 } },
29 };
30
31 // size is tiles on a side; `drop` is the resources a building takes in; `shoot` makes it fire arrows
32 const BUILDINGS = {
33 'town-center': { name: 'Town center', size: 3, hp: 1200, armor: [3, 8], sight: 9, cost: { wood: 275, stone: 100 }, time: 60, age: 1, pop: 5, drop: RES, trains: ['villager'], shoot: { atk: 5, rng: 6, reload: 2 } },
34 house: { name: 'House', size: 2, hp: 250, armor: [1, 5], sight: 3, cost: { wood: 30 }, time: 15, age: 0, pop: 5 },
35 farm: { name: 'Farm', size: 2, hp: 100, armor: [0, 5], sight: 2, cost: { wood: 60 }, time: 10, age: 0 },
36 'lumber-camp': { name: 'Lumber camp', size: 2, hp: 250, armor: [1, 5], sight: 3, cost: { wood: 50 }, time: 15, age: 0, drop: ['wood'] },
37 mill: { name: 'Mill', size: 2, hp: 250, armor: [1, 5], sight: 3, cost: { wood: 50 }, time: 15, age: 0, drop: ['food'] },
38 'mining-camp': { name: 'Mining camp', size: 2, hp: 250, armor: [1, 5], sight: 3, cost: { wood: 50 }, time: 15, age: 0, drop: ['gold', 'stone'] },
39 barracks: { name: 'Barracks', size: 3, hp: 700, armor: [2, 6], sight: 4, cost: { wood: 150 }, time: 40, age: 0, trains: ['militia', 'spearman'] },
40 'archery-range': { name: 'Archery range', size: 3, hp: 700, armor: [2, 6], sight: 4, cost: { wood: 160 }, time: 40, age: 1, trains: ['archer'] },
41 stable: { name: 'Stable', size: 3, hp: 700, armor: [2, 6], sight: 4, cost: { wood: 160 }, time: 40, age: 1, trains: ['knight'] },
42 blacksmith: { name: 'Blacksmith', size: 2, hp: 600, armor: [2, 6], sight: 4, cost: { wood: 150 }, time: 35, age: 1, techs: ['forging', 'fletching', 'scale-mail', 'padded-mail'] },
43 tower: { name: 'Watch tower', size: 2, hp: 500, armor: [5, 8], sight: 8, cost: { wood: 50, stone: 100 }, time: 40, age: 1, shoot: { atk: 6, rng: 7, reload: 1.8 } },
44 'siege-workshop': { name: 'Siege workshop', size: 3, hp: 700, armor: [2, 6], sight: 4, cost: { wood: 200 }, time: 45, age: 2, trains: ['ram'] },
45 castle: { name: 'Castle', size: 4, hp: 2400, armor: [8, 10], sight: 9, cost: { wood: 100, stone: 350 }, time: 80, age: 2, pop: 5, trains: ['knight'], shoot: { atk: 11, rng: 8, reload: 1.6 } },
46 };
47 BUILDINGS['town-center'].techs = ['loom', 'wheelbarrow'];
48 const BUILD_ORDER = ['house', 'farm', 'lumber-camp', 'mill', 'mining-camp', 'barracks', 'archery-range', 'stable', 'blacksmith', 'tower', 'siege-workshop', 'town-center', 'castle'];
49 const KEEPS = ['town-center', 'castle']; // a player with neither of these standing is beaten
50
51 // `for` lists the classes a technology strengthens; each effect is added to the stat
52 const TECHS = {
53 loom: { name: 'Loom', cost: { food: 50, gold: 25 }, time: 20, age: 0, text: 'villagers +15 hit points and +1 pierce armor', hp: { villager: 15 }, pierce: { villager: 1 } },
54 wheelbarrow: { name: 'Wheelbarrow', cost: { food: 175, wood: 50 }, time: 30, age: 1, text: 'villagers gather 25% faster and carry 5 more', gather: .25 },
55 forging: { name: 'Forging', cost: { food: 150 }, time: 30, age: 1, text: 'infantry and cavalry +1 attack', atk: { infantry: 1, cavalry: 1 } },
56 fletching: { name: 'Fletching', cost: { food: 100, wood: 50 }, time: 30, age: 1, text: 'archers +1 attack and +1 range', atk: { archer: 1 }, rng: { archer: 1 } },
57 'scale-mail': { name: 'Scale mail', cost: { food: 100 }, time: 30, age: 1, text: 'infantry and cavalry +1 melee and +1 pierce armor', melee: { infantry: 1, cavalry: 1 }, pierce: { infantry: 1, cavalry: 1 } },
58 'padded-mail': { name: 'Padded mail', cost: { food: 100 }, time: 30, age: 1, text: 'archers +1 melee and +1 pierce armor', melee: { archer: 1 }, pierce: { archer: 1 } },
59 };
60
61 // the stats of a unit kind for a player who has researched `techs` (an object of tech id -> true)
62 function statsOf(kind, techs = {}) {
63 const u = UNITS[kind];
64 const out = { kind, name: u.name, cls: u.cls, hp: u.hp, atk: u.atk, rng: u.rng, reload: u.reload, spd: u.spd, sight: u.sight, armor: [u.armor[0], u.armor[1]], bonus: u.bonus };
65 for (const id in techs) {
66 const t = TECHS[id];
67 if (!t || !techs[id]) continue;
68 out.hp += (t.hp && t.hp[u.cls]) || 0;
69 out.atk += (t.atk && t.atk[u.cls]) || 0;
70 if (u.rng) out.rng += (t.rng && t.rng[u.cls]) || 0;
71 out.armor[0] += (t.melee && t.melee[u.cls]) || 0;
72 out.armor[1] += (t.pierce && t.pierce[u.cls]) || 0;
73 }
74 return out;
75 }
76 const canAfford = (have, cost) => Object.keys(cost).every(r => (have[r] || 0) >= cost[r]);
77 const costText = cost => RES.filter(r => cost[r]).map(r => cost[r] + ' ' + r).join(', ');
78
79 const api = { RES, MAX_POP, CARRY, RATE, NODES, FARM_FOOD, RESEED, AGES, UNITS, BUILDINGS, BUILD_ORDER, KEEPS, TECHS, statsOf, canAfford, costText };
80 if (typeof module !== 'undefined') module.exports = api; else root.Tables = api;
81 })(typeof window !== 'undefined' ? window : globalThis);
empire/ui.test.mjs added +222
@@ -0,0 +1,222 @@
1 import { test, expect } from 'bun:test';
2 import R from './realm.js';
3 import P from './paint.js';
4 import K from './pick.js';
5 import M from './smart.js';
6 import L from './panel.js';
7 import S from './session.js';
8 import T from './tables.js';
9
10 const W = 360, H = 280;
11 const fresh = () => {
12 const s = R.newGame(3, 1);
13 const tc = s.ents.find(e => e.kind === 'town-center' && e.owner === 0);
14 const v = { camX: 0, camY: 0, sel: new Set() };
15 P.centreOn(v, ...R.centre(tc), W, H);
16 return { s, v, tc, vills: R.ofOwner(s, 0, e => e.kind === 'villager') };
17 };
18 const store = () => { const m = {}; return { getItem: k => m[k] ?? null, setItem: (k, x) => { m[k] = String(x); }, removeItem: k => { delete m[k]; }, m }; };
19
20 test('a tap on a unit, a building and a tree picks each, and bare ground picks nothing', () => {
21 const { s, v, tc, vills } = fresh();
22 const [fx, fy] = P.proj(v, vills[0].x, vills[0].y);
23 expect(K.pick(s, v, fx, fy - 4).id).toBe(vills[0].id);
24 const [cx, cy] = P.proj(v, tc.x + 1.5, tc.y + 1.5);
25 expect(K.pick(s, v, cx, cy - 6).id).toBe(tc.id);
26 s.seen.fill(2);
27 const tree = R.nearest(s, tc.x + 1.5, tc.y + 1.5, e => e.kind === 'tree');
28 const [tx, ty] = P.proj(v, tree.x + .5, tree.y + .5);
29 expect(K.pick(s, v, tx, ty - 6).id).toBe(tree.id);
30 expect(K.pick(s, v, 2, 2)).toBeNull();
31 });
32
33 test('the corner of a flat farm is ground, its middle is the farm', () => {
34 const { s, v } = fresh();
35 let spot = null;
36 for (let y = 24; y < 40 && !spot; y++) for (let x = 6; x < 30 && !spot; x++) if (!R.whyNot(s, 0, 'farm', x, y)) spot = [x, y];
37 const farm = R.addBuilding(s, 0, 'farm', spot[0], spot[1], true);
38 R.index(s);
39 s.seen.fill(2);
40 const [mx, my] = P.proj(v, spot[0] + 1, spot[1] + 1);
41 expect(K.pick(s, v, mx, my).id).toBe(farm.id);
42 const [ax, ay] = P.proj(v, spot[0], spot[1]);
43 expect(K.pick(s, v, ax - 10, ay - 3)?.id).not.toBe(farm.id);
44 });
45
46 test('what is hidden by fog cannot be picked: an enemy unit far off is not there', () => {
47 const { s, v } = fresh();
48 const enemy = s.ents.find(e => e.owner === 1 && e.kind === 'villager');
49 const [x, y] = P.proj(v, enemy.x, enemy.y);
50 expect(K.pick(s, v, x, y - 4)?.id).not.toBe(enemy.id);
51 expect(R.visibleAt(s, enemy.x, enemy.y)).toBe(false);
52 });
53
54 test('a box takes the soldiers inside it, or the villagers when there are none', () => {
55 const { s, v, vills } = fresh();
56 const [a, b] = P.proj(v, vills[0].x, vills[0].y);
57 expect(K.inBox(s, v, a - 60, b - 60, a + 60, b + 60).sort()).toEqual(vills.map(e => e.id).sort());
58 const sp = R.addUnit(s, 0, 'spearman', vills[0].x, vills[0].y);
59 expect(K.inBox(s, v, a - 60, b - 60, a + 60, b + 60)).toEqual([sp.id]);
60 expect(K.inBox(s, v, 0, 0, 5, 5)).toEqual([]);
61 });
62
63 test('a double tap picks every unit of the kind in view', () => {
64 const { s, v, vills } = fresh();
65 R.addUnit(s, 0, 'spearman', 12, 30);
66 expect(K.sameKindOnScreen(s, v, vills[0], W, H).sort()).toEqual(vills.map(e => e.id).sort());
67 });
68
69 test('a tap means move on ground, attack on an enemy, work on a tree and build on a half-built house', () => {
70 const { s, vills } = fresh();
71 const ids = vills.map(e => e.id);
72 const tree = s.ents.find(e => e.kind === 'tree'), enemy = s.ents.find(e => e.owner === 1 && e.kind === 'town-center');
73 expect(M.intent(s, ids, null, 3, 4)).toEqual({ type: 'move', x: 3, y: 4 });
74 expect(M.intent(s, ids, tree, 0, 0)).toEqual({ type: 'gather', target: tree.id });
75 expect(M.intent(s, ids, enemy, 0, 0)).toEqual({ type: 'attack', target: enemy.id });
76 const house = R.addBuilding(s, 0, 'house', 12, 20, false);
77 expect(M.intent(s, ids, house, 0, 0)).toEqual({ type: 'build', target: house.id });
78 const done = R.addBuilding(s, 0, 'barracks', 16, 20, true);
79 expect(M.intent(s, ids, done, 0, 0)).toBeNull();
80 expect(M.intent(s, [], null, 1, 1)).toBeNull();
81 expect(M.intent(s, [enemy.id], null, 1, 1)).toBeNull();
82 });
83
84 test('soldiers sent to a tree walk there instead of being ignored', () => {
85 const { s, vills } = fresh();
86 const sp = R.addUnit(s, 0, 'spearman', 12, 30), tree = s.ents.find(e => e.kind === 'tree');
87 const n = M.issue(s, [sp.id, vills[0].id], { type: 'gather', target: tree.id }, tree);
88 expect(n).toBe(2);
89 expect(sp.o).toBe('move');
90 expect(vills[0].o).toBe('gather');
91 });
92
93 test('the panel offers what the selection can do, with the reason when it cannot', () => {
94 const { s, tc, vills } = fresh();
95 const none = L.model(s, []);
96 expect(none.buttons.map(b => b.id)).toEqual(['idle', 'army', 'home']);
97 const v = L.model(s, vills.map(e => e.id));
98 expect(v.info).toMatch(/4 villagers · 4 idle/);
99 const ids = v.buttons.map(b => b.id);
100 expect(ids).toContain('build-house');
101 expect(v.buttons.find(b => b.id === 'build-house').on).toBe(true);
102 const castle = v.buttons.find(b => b.id === 'build-castle');
103 expect(castle.on).toBe(false);
104 expect(castle.why).toBe('needs the Castle Age');
105 expect(v.buttons.find(b => b.id === 'build-barracks').sub).toBe('150 wood');
106 const town = L.model(s, [tc.id]);
107 expect(town.buttons.map(b => b.id)).toEqual(expect.arrayContaining(['train-villager', 'tech-loom', 'age', 'rally', 'demolish']));
108 expect(town.buttons.find(b => b.id === 'age').why).toBe('needs Barracks');
109 expect(town.buttons.map(b => b.hot).slice(0, 3)).toEqual(['1', '2', '3']);
110 const placing = L.model(s, vills.map(e => e.id), 'place');
111 expect(placing.buttons.map(b => b.id)).toEqual(['cancel']);
112 });
113
114 test('a button trains, queues, shows its queue and cancels it', () => {
115 const { s, tc } = fresh();
116 const r = L.perform(s, [tc.id], { t: 'train', kind: 'villager' });
117 expect(r.ok).toBe(true);
118 const m = L.model(s, [tc.id]);
119 expect(m.queue).toHaveLength(1);
120 expect(m.queue[0].text).toMatch(/^Villager 0%/);
121 expect(L.perform(s, [tc.id], { t: 'cancel', i: 0 }).ok).toBe(true);
122 expect(L.model(s, [tc.id]).queue).toEqual([]);
123 expect(L.perform(s, [tc.id], { t: 'train', kind: 'knight' }).ok).toBe(false);
124 expect(L.perform(s, [tc.id], { t: 'bogus' })).toEqual({ ok: false, why: 'unknown command' });
125 expect(L.perform(s, [tc.id], null).ok).toBe(false);
126 });
127
128 test('a building button asks for a spot, and says why it cannot when the age is wrong', () => {
129 const { s, vills } = fresh();
130 const ids = vills.map(e => e.id);
131 expect(L.perform(s, ids, { t: 'place', kind: 'house' })).toEqual({ ok: true, mode: 'place', kind: 'house' });
132 expect(L.perform(s, ids, { t: 'place', kind: 'castle' })).toEqual({ ok: false, why: 'needs the Castle Age' });
133 });
134
135 test('idle villager steps through the idle ones, army and home find the troops and the town', () => {
136 const { s, tc, vills } = fresh();
137 const first = L.perform(s, [], { t: 'idle' });
138 expect(first.select).toEqual([vills[0].id]);
139 expect(L.perform(s, first.select, { t: 'idle' }).select).toEqual([vills[1].id]);
140 R.order(s, 0, vills.map(e => e.id), { type: 'move', x: 14, y: 30 });
141 expect(L.perform(s, [], { t: 'idle' })).toEqual({ ok: false, why: 'no idle villagers' });
142 expect(L.perform(s, [], { t: 'army' }).why).toBe('no soldiers yet');
143 const sp = R.addUnit(s, 0, 'spearman', 10, 30);
144 expect(L.perform(s, [], { t: 'army' }).select).toEqual([sp.id]);
145 expect(L.perform(s, [], { t: 'home' }).select).toEqual([tc.id]);
146 });
147
148 test('demolishing needs a building and a stop order stops the units', () => {
149 const { s, tc, vills } = fresh();
150 expect(L.perform(s, vills.map(e => e.id), { t: 'demolish' }).ok).toBe(false);
151 R.order(s, 0, [vills[0].id], { type: 'move', x: 20, y: 30 });
152 expect(L.perform(s, [vills[0].id], { t: 'stop' }).ok).toBe(true);
153 expect(vills[0].o).toBe('idle');
154 const house = R.addBuilding(s, 0, 'house', 12, 20, true);
155 expect(L.perform(s, [house.id], { t: 'demolish' })).toEqual({ ok: true, select: [] });
156 expect(s.byId.has(house.id)).toBe(false);
157 expect(s.byId.has(tc.id)).toBe(true);
158 });
159
160 test('what the panel says is text, never markup, for an enemy or a tree', () => {
161 const { s } = fresh();
162 const enemy = s.ents.find(e => e.owner === 1 && e.kind === 'villager'), tree = s.ents.find(e => e.kind === 'tree');
163 expect(L.model(s, [enemy.id]).info).toMatch(/^Enemy villager · 25 hp$/);
164 expect(L.model(s, [tree.id]).info).toMatch(/^Tree · 100 left$/);
165 expect(L.model(s, [99999]).info).toMatch(/^Tap a villager/);
166 expect(L.model(s, [enemy.id]).buttons.map(b => b.id)).toEqual(['idle', 'army', 'home']);
167 });
168
169 test('the game saves to the store and comes back, and a bad or missing save is ignored', () => {
170 const st = store(), { s } = fresh();
171 s.players[0].res.gold = 777;
172 expect(S.write(st, s)).toBe(true);
173 expect(S.read(st).players[0].res.gold).toBe(777);
174 S.forget(st);
175 expect(S.read(st)).toBeNull();
176 st.setItem('empire-age-save', '{"v":1,"size":44,"ents":"x"}');
177 expect(S.read(st)).toBeNull();
178 st.setItem('empire-age-save', 'x'.repeat(5e6));
179 expect(S.read(st)).toBeNull();
180 const broken = { getItem() { throw new Error('blocked'); }, setItem() { throw new Error('full'); }, removeItem() { throw new Error('blocked'); } };
181 expect(S.write(broken, s)).toBe(false);
182 expect(S.read(broken)).toBeNull();
183 expect(() => S.forget(broken)).not.toThrow();
184 });
185
186 test('the best time of a level only improves', () => {
187 const st = store();
188 expect(S.best(st, 1, 900.4)).toEqual({ fresh: true, time: 900 });
189 expect(S.best(st, 1, 1000)).toEqual({ fresh: false, time: 900 });
190 expect(S.best(st, 1, 800)).toEqual({ fresh: true, time: 800 });
191 expect(S.best(st, 2, 1000).fresh).toBe(true);
192 st.setItem('empire-age-best', '[1');
193 expect(S.best(st, 0, 500).fresh).toBe(true);
194 });
195
196 test('every building and unit has a drawing height and a name the panel can use', () => {
197 for (const k of T.BUILD_ORDER) { expect(P.HEIGHT[k]).toBeDefined(); expect(T.BUILDINGS[k].name.length).toBeGreaterThan(2); }
198 for (const k of Object.keys(T.UNITS)) expect(T.UNITS[k].from).toBeDefined();
199 });
200
201 test('a mark with no colour of its own is drawn in green, and a mark changes the picture', () => {
202 const { s, v } = fresh();
203 const draw = marks => { const pix = new Uint32Array(W * H); P.draw(pix, W, H, s, { ...v, marks }); return pix; };
204 const plain = draw([]), ringed = draw([{ x: 11, y: 30, age: 0 }]);
205 let changed = 0;
206 for (let i = 0; i < plain.length; i++) if (plain[i] !== ringed[i]) changed++;
207 expect(changed).toBeGreaterThan(5);
208 expect(new Set(Array.from(ringed).filter((c, i) => c !== plain[i]))).toEqual(new Set([P.rgb(80, 220, 110)]));
209 });
210
211 import { readFileSync as readPage } from 'node:fs';
212 const html = readPage(new URL('./index.html', import.meta.url), 'utf8');
213 {
214 test('the dock has a fixed height so the map never resizes under the player', () => {
215 expect(html).toMatch(/#dock \{[^}]*\bheight: min\(36vh, 230px\)/);
216 expect(html).not.toMatch(/#dock \{[^}]*max-height/);
217 });
218 test('offers full screen, only where the browser can', () => {
219 expect(html).toContain('id="full"');
220 expect(html).toContain('requestFullscreen');
221 });
222 }
index.html +1
@@ -94,6 +94,7 @@ footer a::after { content: none; }
9494 <li data-kind="Sport" data-input="Tap" style="--accent:#c2402f"><a href="tug-of-war/">Tug of War</a><span>Tap on the caller's beat to heave the ribbon over your line, five pulls at the fete</span><span>Game forged by the crew</span><span class="tags">Sport · Tap</span></li>
9595 <li data-kind="Catching" data-input="Drag" style="--accent:#5b8a3a"><a href="sheepdog/">Sheepdog</a><span>Drag the dog to steer five sheep through the gate and into the pen before dusk</span><span>Game forged by the crew</span><span class="tags">Catching · Drag</span></li>
9696 <li data-kind="Catching" data-input="Tap" style="--accent:#c9b43a"><a href="firefly-jar/">Firefly Jar</a><span>Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern</span><span>Game forged by the crew</span><span class="tags">Catching · Tap</span></li>
97 <li data-kind="Strategy" data-input="Tap" style="--accent:#3a5fa8"><a href="empire/">Empire Age</a><span>A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
9798 <li data-kind="Precision" data-input="Hold" style="--accent:#d0453c"><a href="hot-air-balloon/">Hot Air Balloon</a><span>Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
9899 </ul>
99100 <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.<br><a href="stats/">Most played</a></footer>
og/empire.png added
Binary file not shown.
og/home.png
Binary file not shown.
rounds.mjs +2
@@ -19,6 +19,8 @@ export const ROUNDS = {
1919 'campfire': { over: /play again/, outcome: /dawn, the fire held · \d+ s/, beat: g => { if (g.read('G.heat') < 55 && g.read('G.fuel.length') < 3) g.press(' '); g.step(5); } },
2020 'domino-run': { over: /play again/, outcome: /\d+ points/, beat: g => { g.press(' '); g.press('ArrowRight'); g.press('Enter'); g.run(1); } },
2121 // pour while the cup is under the spout, and let go in time for the stream's tail to land on the line
22 // build nothing, march nowhere, and give up: the second press of R confirms
23 'empire': { over: /victory|defeat/, outcome: /defeat · you gave up at \d+:\d\d · \d+ trained, \d+ defeated/, beat: g => { g.drag([140, 120], [220, 200], .4); g.press('r'); g.run(.5); g.press('r'); g.run(.5); } },
2224 'espresso-bar': { over: /pour again/, outcome: /twenty cups poured · \d+/, beat: g => {
2325 const pour = g.read('R.phase === "play" && !R.done && Math.abs(R.x) <= Pour.WINDOW && R.fill + Pour.RATE * Pour.DELAY < Pour.lineOf(R.cup)');
2426 if (pour) g.keyDown(' '); else g.keyUp(' ');
serve.test.mjs +8 −1
@@ -328,7 +328,7 @@ test('every game has a kind, input and accent, and the static list carries them'
328328 delete globalThis.PixelPlays;
329329 }
330330 for (const g of games) {
331 expect(['Sport', 'Throwing', 'Timing', 'Catching', 'Precision', 'Racing', 'Memory']).toContain(g.kind);
331 expect(['Sport', 'Throwing', 'Timing', 'Catching', 'Precision', 'Racing', 'Memory', 'Strategy']).toContain(g.kind);
332332 expect(['Tap', 'Hold', 'Drag']).toContain(g.input);
333333 expect(g.accent).toMatch(/^#[0-9a-f]{6}$/i);
334334 expect(html).toContain(`<li data-kind="${g.kind}" data-input="${g.input}" style="--accent:${g.accent}"><a href="${g.id}/">`);
@@ -423,6 +423,13 @@ test('Soapbox Derby and its rules script are served without a track', async () =
423423 expect((await fetch(base + '/soapbox-derby/cart.js')).status).toBe(200);
424424 });
425425
426 test('Empire Age and each of its scripts are served without a track', async () => {
427 const page = await fetch(base + '/empire/');
428 expect(page.status).toBe(200);
429 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
430 for (const f of ['tables', 'grid', 'realm', 'regent', 'paint', 'pick', 'smart', 'panel', 'session']) expect((await fetch(`${base}/empire/${f}.js`)).status, f).toBe(200);
431 });
432
426433 test('Sheepdog and its rules script are served without a track', async () => {
427434 const page = await fetch(base + '/sheepdog/');
428435 expect(page.status).toBe(200);
shell.js +2 −1
@@ -1,7 +1,7 @@
11 'use strict';
22 // Shared chrome for every game: game menu (top centre) and rules popup (top right).
33 window.PixelPlays = (() => {
4 // add a game here and give it a folder, a one-line `blurb`, a `kind` (Sport, Throwing, Timing, Catching, Precision, Racing, Memory), an `input` (Tap, Hold, Drag) and an `accent` colour for its card (the home page lists it from here) (`music: false` when it has no track, `forged: true` when it was made on the forge rather than by the original creators); `soon` entries show in the menu but do not link
4 // add a game here and give it a folder, a one-line `blurb`, a `kind` (Sport, Throwing, Timing, Catching, Precision, Racing, Memory, Strategy), an `input` (Tap, Hold, Drag) and an `accent` colour for its card (the home page lists it from here) (`music: false` when it has no track, `forged: true` when it was made on the forge rather than by the original creators); `soon` entries show in the menu but do not link
55 const GAMES = [
66 { id: 'balote', title: 'Balote', blurb: 'Bocce against a bot, first to 5', kind: 'Throwing', input: 'Drag', accent: '#d9a441' },
77 { id: 'stari-most', title: 'Stari Most', blurb: 'Five dives off the old bridge, flip and enter the water vertically', kind: 'Timing', input: 'Hold', accent: '#3f8fb5' },
@@ -38,6 +38,7 @@ window.PixelPlays = (() => {
3838 { id: 'tug-of-war', title: 'Tug of War', blurb: 'Tap on the caller\'s beat to heave the ribbon over your line, five pulls at the fete', kind: 'Sport', input: 'Tap', accent: '#c2402f', music: false, forged: true },
3939 { id: 'sheepdog', title: 'Sheepdog', blurb: 'Drag the dog to steer five sheep through the gate and into the pen before dusk', kind: 'Catching', input: 'Drag', accent: '#5b8a3a', music: false, forged: true },
4040 { id: 'firefly-jar', title: 'Firefly Jar', blurb: 'Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern', kind: 'Catching', input: 'Tap', accent: '#c9b43a', music: false, forged: true },
41 { id: 'empire', title: 'Empire Age', blurb: 'A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center', kind: 'Strategy', input: 'Tap', accent: '#3a5fa8', music: false, forged: true },
4142 { id: 'hot-air-balloon', title: 'Hot Air Balloon', blurb: 'Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5', kind: 'Precision', input: 'Hold', accent: '#d0453c', music: false, forged: true },
4243 ];
4344 const MUSIC_VOLUME = .4;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs