xonecas.ioDon't click! Sean Caetano Martin Sign in

tiny-adventure / commits / 57023ec

Add live-game verification harness, window.__game debug hook and verification rules

Co-Authored-By: Claude Sonnet 5.5

sacenox3 days ago57023ecb2fa560e6ee02a5455cfda6026659b14fparent ff5e52a6 files changed

CLAUDE.md+20-0
@@ -0,0 +1,20 @@
1+# Tiny Adventure
2+
3+Go server in `cmd/` and `internal/`, Three.js client in `web/`. API in `docs/api.md`.
4+
5+## Rules
6+
7+- No code comments.
8+- All game UI is drawn in Three.js with generated textures from `web/assets`: HUD, panels, buttons, menus, title and end screens, floating numbers. Do not build UI from DOM panels, CSS-styled divs or HTML buttons. The only DOM elements allowed are the canvas and the error fallback.
9+- `window.__game` (`web/js/debug.js`) must keep working after any UI change. It exposes mode, party state, busy flag, `rects()` (UI rects in CSS pixels, each with a name and `essential` flag), `tileScreen(x, y)` and `focusTile(x, y)`. When the UI moves into Three.js, replace the DOM rect provider with `__game.setRects(fn)` returning the real widget rects. The harness reads layout only from there.
10+- Game code changes need `go vet ./... && go test ./...` plus the live harness.
11+
12+## Definition of done
13+
14+"Done" for any change that touches gameplay, rendering or UI requires all of:
15+
16+1. `scripts/verify.sh <outdir>` was run on the final code and its output is attached. Fix every failure or list each one as known and explained.
17+2. A human-style review of the captured frames: open the PNGs (and the recording) with the image reader, and write down what looks broken, ugly, clipped, overlapping, unreadable or empty. Say it plainly. Stating "looks fine" without naming what you checked is not a review.
18+3. The interaction log in the report shows the game state changing after inputs (party moved, fight resolved, panel opened, end screen reached).
19+
20+One screenshot is never evidence that something is done. A screenshot of a broken UI that is called a success is a failed task. See `docs/verification.md`.
docs/verification.md+55-0
@@ -0,0 +1,55 @@
1+# Verification
2+
3+The harness plays the real game in a real Chrome and checks what it observes. Run it after every change to gameplay, rendering or UI.
4+
5+## Run
6+
7+```
8+scripts/verify.sh <outdir> [seed]
9+```
10+
11+Needs `go`, `node`, `ffmpeg` (for the recording), `python3`, and `agent-browser`. The default seed is 7. The script:
12+
13+1. Builds and starts the server on a free port with `--seed`.
14+2. Opens a headed Chrome on `DISPLAY` (default `:0`) with software WebGL flags, so a window appears on the desktop. Do not touch the desktop while it runs.
15+3. For each of 1280x720, 1920x1080, 2560x1440, 1366x768, 800x600 and 390x844, resets the campaign to the seed and plays through input only: clicks Begin, clicks a ground tile, presses I, J and Escape, clicks each main-quest POI in order (walks there, fights) until the end screen shows.
16+4. Exits non-zero if any assertion failed.
17+
18+`VERIFY_ONLY=1280x720,390x844` limits the resolutions. `VERIFY_ATTEMPTS=n` caps POI clicks (default 14).
19+
20+## Output
21+
22+- `report.md` and `report.json`: per resolution, a table of every interaction with the server state after it (from `/api/state`), the layout checks and console errors.
23+- `screens/<WxH>/NN-*.png`: title, explore, after-move, inventory, journal, combat, end.
24+- `recording.webm`: the whole 1280x720 session.
25+- `server.log`.
26+
27+## Assertions
28+
29+- After each input, `/api/state` must show the expected change (party moved, battle counted, mode changed) and the client party position from `window.__game.state()` must equal the server's.
30+- Layout, read from `window.__game.rects()` only: every `essential` rect is fully inside the viewport, and no two rects partly overlap (full containment is allowed). Checked on title, explore, inventory, journal, combat and end screens.
31+- The page must log no console errors or uncaught exceptions.
32+
33+## Reviewing the output
34+
35+The harness cannot judge looks. After a run, read every PNG for at least 1280x720, 800x600 and 390x844, and the recording frames, and write down what is wrong: clipped text, unreadable sizes, empty panels, UI covering the board, an unplayable end state. Assertions passing does not mean the UI is good.
36+
37+## `window.__game`
38+
39+Defined in `web/js/debug.js`, installed after boot.
40+
41+| Member | Meaning |
42+| --- | --- |
43+| `mode` | `loading`, `title`, `explore`, `combat`, `end` |
44+| `busy` | true while a move, walk or fight animation runs |
45+| `state()` | phase, seed, party x/y/gold/inventory/unit levels, summary, winner |
46+| `rects()` | `[{name, x, y, w, h, essential}]` in CSS pixels |
47+| `setRects(fn)` | replace the rect provider (use when the UI is drawn in Three.js) |
48+| `tileScreen(x, y)` | screen position of a tile, for real clicks |
49+| `focusTile(x, y)` | move the camera to a tile; `focusTile(null)` releases it |
50+
51+## Rules
52+
53+- Never claim done from one screenshot. Attach the harness output and a written frame review.
54+- Game UI is drawn in Three.js with textures. DOM panels are not accepted.
55+- A failing assertion is a bug in the game or in the harness. Fix it. Do not delete the check.
scripts/verify.mjs+287-0
@@ -0,0 +1,287 @@
1+import { execFileSync } from 'node:child_process';
2+import { mkdirSync, writeFileSync } from 'node:fs';
3+import { join } from 'node:path';
4+
5+const [outDir, baseUrl, seedArg] = process.argv.slice(2);
6+const SEED = Number(seedArg || 7);
7+const SESSION = `verify-${process.pid}`;
8+const RESOLUTIONS = [[1280, 720], [1920, 1080], [2560, 1440], [1366, 768], [800, 600], [390, 844]];
9+const ONLY = process.env.VERIFY_ONLY ? process.env.VERIFY_ONLY.split(',') : null;
10+const FULL_ATTEMPTS = Number(process.env.VERIFY_ATTEMPTS || 8);
11+const SHORT_ATTEMPTS = 2;
12+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13+
14+const ab = (...args) => execFileSync('agent-browser', ['--session', SESSION, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60000 });
15+const ev = (expr) => {
16+ const out = JSON.parse(ab('--json', 'eval', expr));
17+ if (out.error) throw new Error(out.error);
18+ return out.data.result;
19+};
20+const api = async (path, body) => {
21+ const res = await fetch(baseUrl + path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
22+ return res.json();
23+};
24+
25+const sum = (s) => ({ phase: s.phase, x: s.party.x, y: s.party.y, battles: s.summary.battles, kills: s.summary.kills, loot: s.summary.loot, steps: s.summary.steps, gold: s.party.gold, inv: s.party.inventory?.length ?? 0, levels: s.party.units.map((u) => u.level).join('/'), winner: s.winner || null });
26+const fmt = (o) => Object.entries(o).map(([k, v]) => `${k}=${v}`).join(' ');
27+
28+export function layoutIssues(rects, w, h) {
29+ const issues = [];
30+ for (const r of rects) {
31+ if (!r.essential) continue;
32+ if (r.x < -0.5 || r.y < -0.5 || r.x + r.w > w + 0.5 || r.y + r.h > h + 0.5) issues.push(`${r.name} outside viewport: x=${r.x | 0} y=${r.y | 0} w=${r.w | 0} h=${r.h | 0} in ${w}x${h}`);
33+ }
34+ const contains = (a, b) => a.x <= b.x + 1 && a.y <= b.y + 1 && a.x + a.w >= b.x + b.w - 1 && a.y + a.h >= b.y + b.h - 1;
35+ for (let i = 0; i < rects.length; i++) {
36+ for (let j = i + 1; j < rects.length; j++) {
37+ const a = rects[i];
38+ const b = rects[j];
39+ const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
40+ const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
41+ if (ox > 1 && oy > 1 && !contains(a, b) && !contains(b, a)) issues.push(`${a.name} overlaps ${b.name} by ${ox | 0}x${oy | 0}px`);
42+ }
43+ }
44+ return issues;
45+}
46+
47+const report = { seed: SEED, baseUrl, startedAt: new Date().toISOString(), resolutions: [] };
48+let failures = 0;
49+
50+async function runResolution([w, h], record) {
51+ const maxAttempts = record ? FULL_ATTEMPTS : SHORT_ATTEMPTS;
52+ const tag = `${w}x${h}`;
53+ const dir = join(outDir, 'screens', tag);
54+ mkdirSync(dir, { recursive: true });
55+ const res = { resolution: tag, steps: [], layout: [], consoleErrors: [] };
56+ let n = 0;
57+ const shot = (name) => {
58+ const file = join(dir, `${String(++n).padStart(2, '0')}-${name}.png`);
59+ ab('screenshot', file);
60+ return file;
61+ };
62+ const gameState = async () => JSON.parse(ev('JSON.stringify(window.__game.state())'));
63+ const rects = async () => JSON.parse(ev('JSON.stringify(window.__game.rects())'));
64+ const mode = async () => ev('window.__game.mode');
65+ const checkLayout = async (label) => {
66+ const issues = layoutIssues(await rects(), w, h);
67+ res.layout.push({ label, issues });
68+ for (const i of issues) {
69+ failures++;
70+ console.log(` FAIL layout [${tag}] ${label}: ${i}`);
71+ }
72+ return issues;
73+ };
74+ const step = async (action, fn) => {
75+ const apiBefore = sum(await api('/api/state'));
76+ let note = '';
77+ let ok = true;
78+ let detail = '';
79+ try {
80+ const r = await fn();
81+ if (r && r.ok === false) { ok = false; detail = r.detail; }
82+ else if (r && r.detail) detail = r.detail;
83+ } catch (e) {
84+ ok = false;
85+ detail = `exception: ${String(e.message).split('\n')[0]}`;
86+ }
87+ const apiAfter = sum(await api('/api/state'));
88+ let local = null;
89+ try { local = await gameState(); } catch { note = 'window.__game unavailable'; ok = false; }
90+ if (local && (local.party.x !== apiAfter.x || local.party.y !== apiAfter.y)) { ok = false; detail += ` client/server party mismatch client=${local.party.x},${local.party.y} server=${apiAfter.x},${apiAfter.y}`; }
91+ let m = '?';
92+ try { m = await mode(); } catch {}
93+ if (!ok) failures++;
94+ res.steps.push({ action, ok, mode: m, before: fmt(apiBefore), after: fmt(apiAfter), detail: (detail + ' ' + note).trim() });
95+ console.log(` ${ok ? 'ok ' : 'FAIL'} [${tag}] ${action} | mode=${m} | ${fmt(apiAfter)}${detail ? ' | ' + detail : ''}`);
96+ return ok;
97+ };
98+ const clickAt = (x, y) => { ab('mouse', 'move', String(x), String(y)); ab('mouse', 'down'); ab('mouse', 'up'); };
99+ const clickRect = async (name) => {
100+ const r = (await rects()).find((q) => q.name === name);
101+ if (!r) throw new Error(`no rect ${name}`);
102+ clickAt(Math.round(r.x + r.w / 2), Math.round(r.y + r.h / 2));
103+ };
104+ const waitIdle = async (observe) => {
105+ const t0 = Date.now();
106+ const seen = new Set();
107+ while (Date.now() - t0 < 90000) {
108+ const [b, m] = JSON.parse(ev('JSON.stringify([window.__game.busy, window.__game.mode])'));
109+ if (!seen.has(m)) { seen.add(m); await observe?.(m); }
110+ if (!b) return [...seen];
111+ await sleep(200);
112+ }
113+ throw new Error('game stayed busy for 90s');
114+ };
115+ const clickTile = async (t, observe) => {
116+ ev(`window.__game.focusTile(${t.x},${t.y})`);
117+ await sleep(1800);
118+ const p = JSON.parse(ev(`JSON.stringify(window.__game.tileScreen(${t.x},${t.y}))`));
119+ if (p.x < 0 || p.y < 0 || p.x > w || p.y > h) throw new Error(`tile ${t.x},${t.y} projects off-screen at ${p.x | 0},${p.y | 0}`);
120+ clickAt(Math.round(p.x), Math.round(p.y));
121+ ev('window.__game.focusTile(null)');
122+ await sleep(300);
123+ return waitIdle(observe);
124+ };
125+
126+ await api('/api/new', { seed: SEED });
127+ ab('open', baseUrl);
128+ const t0 = Date.now();
129+ while (Date.now() - t0 < 30000) {
130+ try { if (ev('typeof window.__game') === 'object' && (await mode()) === 'title') break; } catch {}
131+ await sleep(300);
132+ }
133+ if (record) ab('record', 'start', join(outDir, 'recording.webm'), '--fps', '10');
134+ ab('errors', '--clear');
135+
136+ await step('load page, expect title screen', async () => {
137+ shot('title');
138+ await checkLayout('title');
139+ const m = await mode();
140+ return { ok: m === 'title', detail: `mode=${m}` };
141+ });
142+
143+ await step('click Begin Adventure', async () => {
144+ await clickRect('button-0');
145+ await sleep(600);
146+ shot('explore');
147+ return { ok: (await mode()) === 'explore', detail: 'expected mode explore' };
148+ });
149+ await checkLayout('explore HUD');
150+
151+ let s = await api('/api/state');
152+ const walkable = (x, y) => s.map.tiles[y]?.[x]?.walkable && !s.map.pois.some((p) => p.x === x && p.y === y);
153+ const near = [];
154+ for (let d = 2; d <= 3; d++) for (const [dx, dy] of [[d, 0], [-d, 0], [0, d], [0, -d]]) if (walkable(s.party.x + dx, s.party.y + dy)) near.push({ x: s.party.x + dx, y: s.party.y + dy });
155+ await step(`click ground tile ${near[0]?.x},${near[0]?.y} to move the party`, async () => {
156+ const before = sum(await api('/api/state'));
157+ await clickTile(near[0]);
158+ shot('after-move');
159+ const after = sum(await api('/api/state'));
160+ return { ok: after.x === near[0].x && after.y === near[0].y && (after.x !== before.x || after.y !== before.y), detail: `expected party at ${near[0].x},${near[0].y}` };
161+ });
162+
163+ await step('press I to open inventory', async () => {
164+ ab('press', 'i');
165+ await sleep(400);
166+ shot('inventory');
167+ const open = (await rects()).some((r) => r.name === 'panel-inv');
168+ await checkLayout('inventory open');
169+ return { ok: open, detail: `inventory rect present=${open}` };
170+ });
171+ await step('press J to switch to journal', async () => {
172+ ab('press', 'j');
173+ await sleep(400);
174+ shot('journal');
175+ const open = (await rects()).some((r) => r.name === 'panel-journal');
176+ await checkLayout('journal open');
177+ return { ok: open, detail: `journal rect present=${open}` };
178+ });
179+ await step('press Escape to close panels', async () => {
180+ ab('press', 'Escape');
181+ await sleep(300);
182+ const names = (await rects()).filter((r) => r.name.startsWith('panel-'));
183+ return { ok: names.length === 0, detail: `open panels=${names.length}` };
184+ });
185+
186+ let combatShots = 0;
187+ const observe = async (m) => {
188+ if (m === 'combat' && combatShots < 1) {
189+ combatShots++;
190+ await sleep(900);
191+ shot('combat');
192+ await checkLayout('combat');
193+ }
194+ };
195+ let attempts = 0;
196+ while (attempts < maxAttempts) {
197+ s = await api('/api/state');
198+ if (s.winner || s.phase === 'victory') break;
199+ const next = s.campaign.main.steps.find((q) => !q.done);
200+ const poi = s.map.pois.find((p) => p.id === next.poi);
201+ attempts++;
202+ const before = sum(s);
203+ await step(`click ${poi.kind} "${poi.name}" for main step "${next.text}" (attempt ${attempts})`, async () => {
204+ await clickTile(poi, observe);
205+ const after = sum(await api('/api/state'));
206+ const progressed = after.battles > before.battles || after.x !== before.x || after.y !== before.y;
207+ const moved = `${before.x},${before.y} -> ${after.x},${after.y}`;
208+ return { ok: progressed, detail: `phase=${after.phase} party ${moved}, battles ${before.battles}->${after.battles}` };
209+ });
210+ }
211+
212+ await step('fast-forward the campaign through /api/move (setup only, not input), reload', async () => {
213+ let g = await api('/api/state');
214+ let moves = 0;
215+ while (!g.winner && moves < 80) {
216+ const next = g.campaign.main.steps.find((q) => !q.done);
217+ const poi = g.map.pois.find((p) => p.id === next.poi);
218+ g = await api('/api/move', { x: poi.x, y: poi.y });
219+ moves++;
220+ }
221+ ab('open', baseUrl);
222+ const t1 = Date.now();
223+ while (Date.now() - t1 < 30000) {
224+ try { if ((await mode()) === 'end') break; } catch {}
225+ await sleep(300);
226+ }
227+ return { ok: !!g.winner, detail: `${moves} server moves, winner=${g.winner || 'none'}` };
228+ });
229+ await step('end screen shown after campaign won', async () => {
230+ await sleep(800);
231+ const m = await mode();
232+ shot('end');
233+ if (m === 'end') await checkLayout('end screen');
234+ return { ok: m === 'end', detail: `mode=${m}` };
235+ });
236+ await step('click New Game on end screen', async () => {
237+ const before = (await api('/api/state')).seed;
238+ await clickRect('button-0');
239+ await sleep(1500);
240+ const after = (await api('/api/state')).seed;
241+ const m = await mode();
242+ shot('new-game');
243+ await checkLayout('new game title');
244+ return { ok: m === 'title' && after !== before, detail: `seed ${before} -> ${after}, mode=${m}` };
245+ });
246+
247+ if (record) ab('record', 'stop');
248+ const errs = ab('errors').trim();
249+ if (errs && !/no (page )?errors/i.test(errs)) {
250+ res.consoleErrors = errs.split('\n').filter(Boolean);
251+ failures++;
252+ console.log(` FAIL console errors [${tag}]: ${res.consoleErrors[0]}`);
253+ }
254+ report.resolutions.push(res);
255+}
256+
257+mkdirSync(outDir, { recursive: true });
258+for (const r of RESOLUTIONS) {
259+ const tag = `${r[0]}x${r[1]}`;
260+ if (ONLY && !ONLY.includes(tag)) continue;
261+ console.log(`== ${tag}`);
262+ ab('set', 'viewport', String(r[0]), String(r[1]));
263+ try {
264+ await runResolution(r, tag === '1280x720');
265+ } catch (e) {
266+ failures++;
267+ console.log(` FAIL [${tag}] harness aborted: ${String(e.message).split('\n')[0]}`);
268+ report.resolutions.push({ resolution: tag, steps: [], layout: [], consoleErrors: [], aborted: String(e.message).split('\n')[0] });
269+ }
270+}
271+try { ab('close'); } catch {}
272+
273+report.failures = failures;
274+writeFileSync(join(outDir, 'report.json'), JSON.stringify(report, null, 2));
275+const md = [`# Verification report`, ``, `Seed ${SEED}, ${report.startedAt}. Total failures: **${failures}**.`, ``];
276+for (const r of report.resolutions) {
277+ md.push(`## ${r.resolution}`, ``);
278+ if (r.aborted) md.push(`Harness aborted: ${r.aborted}`, ``);
279+ md.push(`| # | Interaction | Result | Mode | Observed state after (from /api/state) | Detail |`, `|---|---|---|---|---|---|`);
280+ r.steps.forEach((q, i) => md.push(`| ${i + 1} | ${q.action} | ${q.ok ? 'ok' : '**FAIL**'} | ${q.mode} | ${q.after} | ${q.detail} |`));
281+ md.push(``, `Layout checks:`, ``);
282+ for (const l of r.layout) md.push(`- ${l.label}: ${l.issues.length ? '' : 'ok'}`, ...l.issues.map((i) => ` - FAIL ${i}`));
283+ md.push(``, `Console errors: ${r.consoleErrors.length || 'none'}`, ...r.consoleErrors.map((e) => `- ${e}`), ``);
284+}
285+writeFileSync(join(outDir, 'report.md'), md.join('\n'));
286+console.log(`\n${failures} failure(s). Report: ${join(outDir, 'report.md')}`);
287+process.exit(failures ? 1 : 0);
scripts/verify.sh+18-0
@@ -0,0 +1,18 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+out=${1:?usage: scripts/verify.sh <outdir> [seed]}
4+seed=${2:-7}
5+root=$(cd "$(dirname "$0")/.." && pwd)
6+mkdir -p "$out"
7+out=$(cd "$out" && pwd)
8+export DISPLAY=${DISPLAY:-:0}
9+export AGENT_BROWSER_HEADED=1
10+export AGENT_BROWSER_ARGS="--no-sandbox,--disable-dev-shm-usage,--use-angle=swiftshader,--enable-unsafe-swiftshader"
11+port=$(python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])')
12+bin=$(mktemp -d)/server
13+(cd "$root" && go build -o "$bin" ./cmd/server)
14+"$bin" --seed "$seed" --addr "127.0.0.1:$port" --web "$root/web" >"$out/server.log" 2>&1 &
15+pid=$!
16+trap 'kill $pid 2>/dev/null || true' EXIT
17+for _ in $(seq 50); do curl -sf "http://127.0.0.1:$port/api/seed" >/dev/null && break; sleep 0.2; done
18+node "$root/scripts/verify.mjs" "$out" "http://127.0.0.1:$port" "$seed"
web/js/debug.js+71-0
@@ -0,0 +1,71 @@
1+const VISIBLE = [
2+ ['topbar', '#topbar'],
3+ ['log', '#log'],
4+ ['bottom', '#bottom'],
5+ ['portraits', '#portraits'],
6+ ['abilities', '#abilities'],
7+ ['menu', '#menu'],
8+ ['btn-inv', '#btn-inv'],
9+ ['btn-journal', '#btn-journal'],
10+ ['panel-inv', '#panel-inv'],
11+ ['panel-journal', '#panel-journal'],
12+ ['toast.show', '#toast.show'],
13+ ['card', '#screen .card'],
14+];
15+const MULTI = [
16+ ['portrait', '#portraits .portrait'],
17+ ['ability', '#abilities .ability'],
18+ ['button', '#screen button'],
19+];
20+
21+function rectOf(el) {
22+ const r = el.getBoundingClientRect();
23+ if (!r.width || !r.height || el.closest('[hidden]')) return null;
24+ return { x: r.x, y: r.y, w: r.width, h: r.height };
25+}
26+
27+function domRects() {
28+ const out = [];
29+ for (const [name, sel] of VISIBLE) {
30+ const el = document.querySelector(sel);
31+ const r = el && rectOf(el);
32+ if (r) out.push({ name, ...r, essential: name !== 'toast.show' });
33+ }
34+ for (const [name, sel] of MULTI) {
35+ document.querySelectorAll(sel).forEach((el, i) => {
36+ const r = rectOf(el);
37+ if (r) out.push({ name: `${name}-${i}`, ...r, essential: true });
38+ });
39+ }
40+ return out;
41+}
42+
43+export const track = { mode: 'loading', busy: false, rects: domRects };
44+
45+export function installDebug(ctx) {
46+ const { THREE, getState, getWorld, cam, party } = ctx;
47+ const toScreen = (p) => {
48+ const v = p.clone().project(cam.camera);
49+ return { x: ((v.x + 1) / 2) * innerWidth, y: ((1 - v.y) / 2) * innerHeight };
50+ };
51+ window.__game = {
52+ get mode() { return track.mode; },
53+ get busy() { return track.busy; },
54+ viewport: () => ({ w: innerWidth, h: innerHeight, dpr: devicePixelRatio }),
55+ state: () => {
56+ const s = getState();
57+ return s && { phase: s.phase, seed: s.seed, party: { x: s.party.x, y: s.party.y, gold: s.party.gold, inventory: s.party.inventory.length, units: s.party.units.map((u) => ({ id: u.id, level: u.level, hp: u.stats.hp })) }, summary: s.summary, winner: s.winner || null };
58+ },
59+ partyWorld: () => ({ x: party.pos.x, y: party.pos.z }),
60+ rects: () => track.rects(),
61+ tileScreen: (x, y) => {
62+ const w = getWorld();
63+ return toScreen(w.worldPos(x, y));
64+ },
65+ focusTile: (x, y) => {
66+ const w = getWorld();
67+ cam.setFocus(x == null ? null : w.worldPos(x, y), 17);
68+ },
69+ setRects: (fn) => { track.rects = fn; },
70+ };
71+}
web/js/main.js+16-2
@@ -8,6 +8,7 @@ import { createCombat } from './combat.js';
88 import { createUI } from './ui.js';
99 import { showTitle, showEnd } from './screens.js';
1010 import { mat } from './props.js';
11+import { installDebug, track } from './debug.js';
1112
1213 const canvas = document.getElementById('stage');
1314 const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
@@ -110,6 +111,7 @@ canvas.addEventListener('pointermove', (e) => {
110111 async function go(t) {
111112 if (!state.map.tiles[t.y][t.x].walkable) return ui.toast('Impassable terrain');
112113 busy = true;
114+ track.busy = true;
113115 marker.visible = false;
114116 const before = state;
115117 try {
@@ -119,7 +121,9 @@ async function go(t) {
119121 await party.walk(world.path({ x: before.party.x, y: before.party.y }, dest));
120122 if (next.encounter && next.log.length) {
121123 world.showLabels(false);
124+ track.mode = 'combat';
122125 await combat.play(next, before);
126+ track.mode = 'explore';
123127 world.showLabels(true);
124128 const r = next.rewards;
125129 if (r) ui.logLine(`Victory: +${r.xp} XP, +${r.gold} gold${r.items?.length ? ', ' + r.items.map((i) => i.name).join(', ') : ''}`, 'reward');
@@ -133,7 +137,7 @@ async function go(t) {
133137 party.place(p);
134138 cam.snap(p);
135139 }
136- if (next.winner || next.phase === 'victory') return showEnd(next, restart);
140+ if (next.winner || next.phase === 'victory') return endGame(next);
137141 await collectHere();
138142 const sp = state.map.spawns.find((s) => s.x === state.party.x && s.y === state.party.y);
139143 if (sp) ui.logLine(sp.hint, 'hint');
@@ -141,6 +145,7 @@ async function go(t) {
141145 ui.toast(e.message);
142146 } finally {
143147 busy = false;
148+ track.busy = false;
144149 }
145150 }
146151
@@ -158,10 +163,17 @@ async function restart() {
158163 const s = await api.newGame();
159164 load(s);
160165 ui.show(false);
166+ track.mode = 'title';
161167 showTitle(s, { onStart: begin, onNew: restart });
162168 }
163169
170+function endGame(s) {
171+ track.mode = 'end';
172+ showEnd(s, restart);
173+}
174+
164175 function begin() {
176+ track.mode = 'explore';
165177 ui.show(true);
166178 }
167179
@@ -189,7 +201,9 @@ async function boot() {
189201 tex = await loadTextures();
190202 load(await api.getState());
191203 frame();
192- if (state.winner || state.phase === 'victory') return showEnd(state, restart);
204+ installDebug({ THREE, getState: () => state, getWorld: () => world, cam, party });
205+ if (state.winner || state.phase === 'victory') return endGame(state);
206+ track.mode = 'title';
193207 showTitle(state, { onStart: begin, onNew: restart });
194208 }