xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / scripts / verify.mjs 308 lines14.5 kB Raw
1import { mkdirSync, writeFileSync } from 'node:fs';
2import { join } from 'node:path';
3import { createDriver, sleep } from './driver.mjs';
4import { maxHp } from '../web/js/stats.js';
5import { createBot, playOut, apiIO, finished, night } from './bot.mjs';
6import { layoutIssues } from './layout.mjs';
7import { checkFights } from './fights.mjs';
8
9const [outDir, baseUrl, seedArg] = process.argv.slice(2);
10const SEED = Number(seedArg || 7);
11const SESSION = `verify-${process.pid}`;
12const RESOLUTIONS = [[1280, 720], [1920, 1080], [2560, 1440], [1366, 768], [800, 600], [390, 844]];
13const ONLY = process.env.VERIFY_ONLY ? process.env.VERIFY_ONLY.split(',') : null;
14const FULL_STEPS = Number(process.env.VERIFY_STEPS || 10);
15const SHORT_STEPS = 2;
16
17const driver = createDriver({ session: SESSION, baseUrl, w: 0, h: 0 });
18const { ab, api } = driver;
19
20const sum = (s) => ({ phase: s.phase, day: s.clock.day, time: s.clock.time, 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('/'), hp: s.party.units.map((u) => u.stats.hp).join('/') });
21const fmt = (o) => Object.entries(o).map(([k, v]) => `${k}=${v}`).join(' ');
22
23const report = { seed: SEED, baseUrl, startedAt: new Date().toISOString(), resolutions: [] };
24let failures = 0;
25
26async function runResolution([w, h], record) {
27  const maxSteps = record ? FULL_STEPS : SHORT_STEPS;
28  const tag = `${w}x${h}`;
29  const dir = join(outDir, 'screens', tag);
30  mkdirSync(dir, { recursive: true });
31  const res = { resolution: tag, steps: [], layout: [], consoleErrors: [] };
32  let n = 0;
33  const shot = (name) => {
34    const file = join(dir, `${String(++n).padStart(2, '0')}-${name}.png`);
35    ab('screenshot', file);
36    return file;
37  };
38  const d = createDriver({ session: SESSION, baseUrl, w, h });
39  const { gameState, rects, mode, clickRect, clickTile, fight, openPage } = d;
40  const checkLayout = async (label) => {
41    const issues = layoutIssues(await rects(), w, h);
42    res.layout.push({ label, issues });
43    for (const i of issues) {
44      failures++;
45      console.log(`  FAIL layout [${tag}] ${label}: ${i}`);
46    }
47    return issues;
48  };
49  const step = async (action, fn) => {
50    const apiBefore = sum(await api('/api/state'));
51    let note = '';
52    let ok = true;
53    let detail = '';
54    try {
55      const r = await fn();
56      if (r && r.ok === false) { ok = false; detail = r.detail; }
57      else if (r && r.detail) detail = r.detail;
58    } catch (e) {
59      ok = false;
60      detail = `exception: ${String(e.message).split('\n')[0]}`;
61    }
62    const apiAfter = sum(await api('/api/state'));
63    let local = null;
64    try { local = await gameState(); } catch { note = 'window.__game unavailable'; ok = false; }
65    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}`; }
66    let m = '?';
67    try { m = await mode(); } catch {}
68    if (!ok) failures++;
69    res.steps.push({ action, ok, mode: m, before: fmt(apiBefore), after: fmt(apiAfter), detail: (detail + ' ' + note).trim() });
70    console.log(`  ${ok ? 'ok  ' : 'FAIL'} [${tag}] ${action} | mode=${m} | ${fmt(apiAfter)}${detail ? ' | ' + detail : ''}`);
71    return ok;
72  };
73  await api('/api/new', { seed: SEED });
74  await openPage('title');
75  if (record) ab('record', 'start', join(outDir, 'recording.webm'), '--fps', '10');
76  ab('errors', '--clear');
77
78  await step('load page, expect title screen', async () => {
79    shot('title');
80    await checkLayout('title');
81    const m = await mode();
82    return { ok: m === 'title', detail: `mode=${m}` };
83  });
84
85  await step('click Begin Adventure', async () => {
86    await clickRect('button-0');
87    await sleep(600);
88    shot('explore');
89    return { ok: (await mode()) === 'explore', detail: 'expected mode explore' };
90  });
91  await checkLayout('explore HUD');
92
93  await step('press T at the wagon to open the trader, buy a potion', async () => {
94    const before = await api('/api/state');
95    ab('press', 't');
96    await sleep(500);
97    shot('trader');
98    await checkLayout('trader panel');
99    const open = (await rects()).some((r) => r.name === 'panel-shop');
100    await clickRect('buy-potion');
101    await sleep(500);
102    ab('press', 'Escape');
103    await sleep(300);
104    const after = await api('/api/state');
105    return { ok: open && after.party.potions === before.party.potions + 1, detail: `panel ${open}, potions ${before.party.potions} -> ${after.party.potions}, gold ${before.party.gold} -> ${after.party.gold}` };
106  });
107
108  let s = await api('/api/state');
109  const hexes = Buffer.from(s.map.hexes, 'base64');
110  const walkable = (x, y) => x >= 0 && y >= 0 && x < s.map.width && y < s.map.height && ![0, 5].includes(hexes[(y * s.map.width + x) * 4]) && !s.map.pois.some((p) => p.x === x && p.y === y);
111  const near = [];
112  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 });
113  await step(`click ground tile ${near[0]?.x},${near[0]?.y} to move the party`, async () => {
114    const before = sum(await api('/api/state'));
115    await clickTile(near[0]);
116    shot('after-move');
117    const after = sum(await api('/api/state'));
118    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}` };
119  });
120
121  await step('press I to open inventory', async () => {
122    ab('press', 'i');
123    await sleep(400);
124    shot('inventory');
125    const open = (await rects()).some((r) => r.name === 'panel-inv');
126    await checkLayout('inventory open');
127    return { ok: open, detail: `inventory rect present=${open}` };
128  });
129  await step('press J to switch to journal', async () => {
130    ab('press', 'j');
131    await sleep(400);
132    shot('journal');
133    const open = (await rects()).some((r) => r.name === 'panel-journal');
134    await checkLayout('journal open');
135    return { ok: open, detail: `journal rect present=${open}` };
136  });
137  await step('press Escape to close panels', async () => {
138    ab('press', 'Escape');
139    await sleep(300);
140    const names = (await rects()).filter((r) => r.name.startsWith('panel-'));
141    return { ok: names.length === 0, detail: `open panels=${names.length}` };
142  });
143
144  let combatShots = 0;
145  const observe = async (m) => {
146    if (m === 'combat' && combatShots < 1) {
147      combatShots++;
148      await sleep(900);
149      shot('combat');
150      await checkLayout('combat');
151    }
152  };
153  s = await api('/api/state');
154  const first = s.map.pois.find((p) => p.id === s.campaign.main.steps[0].poi);
155  await step(`click ${first.kind} "${first.name}", read the threat card, prepare, fight`, async () => {
156    const before = sum(await api('/api/state'));
157    await clickTile(first);
158    const m = await mode();
159    const threat = (await api('/api/state')).threat;
160    if (m !== 'threat' || !threat) return { ok: false, detail: `expected threat card, mode=${m}` };
161    shot(threat.band ? 'band' : 'threat');
162    await checkLayout('threat card');
163    await clickRect('threat-prepare');
164    await sleep(500);
165    const pm = await mode();
166    const open = (await rects()).some((r) => r.name === 'prepare-back');
167    shot('prepare');
168    await checkLayout('prepare panel');
169    await clickRect('prepare-back');
170    await sleep(400);
171    const back = await mode();
172    if (pm !== 'prepare' || !open || back !== 'threat') return { ok: false, detail: `prepare flow: mode ${pm}, back button ${open}, after back ${back}` };
173    await fight(observe);
174    const after = sum(await api('/api/state'));
175    return { ok: after.battles === before.battles + 1, detail: `odds ${threat.odds}% wounds ${threat.wounds}%, phase=${after.phase}, battles ${before.battles}->${after.battles}` };
176  });
177
178  let pending = null;
179  const bot = createBot(d.ui(observe), { note: (action, detail) => (pending = { action, detail }) });
180  s = await api('/api/state');
181  for (let i = 0; i < maxSteps && !finished(s); i++) {
182    await step(`bot step ${i + 1} through the UI`, async () => {
183      const print = (q) => JSON.stringify([sum(q), q.party.potions, q.party.units.map((u) => [u.stats.hp, u.gear])]);
184      const before = print(s);
185      pending = null;
186      s = await bot.step(s);
187      const changed = before !== print(s) || ['back off', 'lower the bar'].includes(pending?.action);
188      return { ok: changed, detail: pending ? `${pending.action}: ${pending.detail}` : 'no decision' };
189    });
190  }
191
192  await step('walk until dusk (setup through /api/move), reload, click Make camp', async () => {
193    let g = await api('/api/state');
194    const io = apiIO(api);
195    const spawns = g.map.spawns;
196    for (let i = 0; i < 40 && !night(g) && !finished(g); i++) {
197      g = await io.go(spawns[i % 2]);
198      if (g.threat && !g.threat.barred && g.threat.odds >= 80) g = await io.fight(g);
199    }
200    if (!night(g)) return { ok: false, detail: `no dusk: ${fmt(sum(g))}` };
201    await openPage('title');
202    await clickRect('button-0');
203    await sleep(1500);
204    shot('night');
205    await checkLayout('night HUD');
206    const hasButton = (await rects()).some((r) => r.name === 'btn-camp');
207    await clickRect('btn-camp');
208    await sleep(1400);
209    const during = await mode();
210    shot('camp');
211    await d.waitIdle();
212    await sleep(400);
213    const after = await api('/api/state');
214    const healed = after.party.units.every((u) => u.stats.hp >= maxHp(u));
215    shot('dawn');
216    return { ok: hasButton && during === 'camp' && after.clock.day === g.clock.day + 1 && healed, detail: `button ${hasButton}, mode during ${during}, day ${g.clock.day} -> ${after.clock.day}, healed ${healed}` };
217  });
218
219  await step('fast-forward the campaign with the bot through the API (setup only, not input), reload', async () => {
220    const g = await playOut(apiIO(api), await api('/api/state'));
221    await openPage('end');
222    return { ok: g.phase === 'victory', detail: `phase=${g.phase} day ${g.clock.day}, battles ${g.summary.battles}` };
223  });
224  await step('end screen shown after campaign won', async () => {
225    await sleep(800);
226    const m = await mode();
227    const phase = (await api('/api/state')).phase;
228    shot('victory');
229    if (m === 'end') await checkLayout('victory screen');
230    return { ok: m === 'end' && phase === 'victory', detail: `mode=${m} phase=${phase}` };
231  });
232  await step('click New Game on end screen', async () => {
233    const before = (await api('/api/state')).seed;
234    await clickRect('button-0');
235    await sleep(1500);
236    const after = (await api('/api/state')).seed;
237    const m = await mode();
238    shot('new-game');
239    await checkLayout('new game title');
240    return { ok: m === 'title' && after !== before, detail: `seed ${before} -> ${after}, mode=${m}` };
241  });
242
243  await step('lose a fight far above the party level (setup through the API), reload, expect the defeat screen', async () => {
244    let g = await api('/api/new', { seed: SEED });
245    const boss = g.campaign.main.steps.at(-1).poi;
246    const hard = g.map.pois.filter((p) => !p.cleared && p.id !== boss).sort((a, b) => b.level - a.level)[0];
247    for (let i = 0; i < 30 && !finished(g); i++) {
248      g = await api('/api/move', { x: hard.x, y: hard.y });
249      if (g.threat) g = await api('/api/interact', { id: g.threat.band || g.threat.poi });
250    }
251    await openPage('end');
252    await sleep(800);
253    shot('defeat');
254    await checkLayout('defeat screen');
255    const rejected = await api('/api/move', { x: g.party.x, y: g.party.y });
256    return { ok: g.phase === 'defeat' && !!rejected.error, detail: `phase=${g.phase} vs ${hard.name} Lv${hard.level}, later move rejected: ${rejected.error || 'no'}` };
257  });
258
259  if (record) ab('record', 'stop');
260  const errs = ab('errors').trim();
261  if (errs && !/no (page )?errors/i.test(errs)) {
262    res.consoleErrors = errs.split('\n').filter(Boolean);
263    failures++;
264    console.log(`  FAIL console errors [${tag}]: ${res.consoleErrors[0]}`);
265  }
266  report.resolutions.push(res);
267}
268
269mkdirSync(outDir, { recursive: true });
270const FIGHT_SEEDS = [1, 2, 3, 4, 5];
271console.log(`== fights through the API, seeds ${FIGHT_SEEDS.join(', ')}`);
272report.fights = await checkFights(api, FIGHT_SEEDS);
273for (const want of ['heal', 'buff', 'debuff', 'aoe']) if (!report.fights.kinds[want]) report.fights.problems.push(`no ${want} event in ${report.fights.fights} fights, so it went unchecked`);
274failures += report.fights.problems.length;
275console.log(`  ${report.fights.problems.length ? 'FAIL' : 'ok  '} ${report.fights.fights} fights replayed, kinds ${JSON.stringify(report.fights.kinds)}`);
276for (const p of report.fights.problems.slice(0, 10)) console.log(`  FAIL ${p}`);
277for (const r of RESOLUTIONS) {
278  const tag = `${r[0]}x${r[1]}`;
279  if (ONLY && !ONLY.includes(tag)) continue;
280  console.log(`== ${tag}`);
281  ab('set', 'viewport', String(r[0]), String(r[1]));
282  try {
283    await runResolution(r, tag === '1280x720');
284  } catch (e) {
285    failures++;
286    console.log(`  FAIL [${tag}] harness aborted: ${String(e.message).split('\n')[0]}`);
287    report.resolutions.push({ resolution: tag, steps: [], layout: [], consoleErrors: [], aborted: String(e.message).split('\n')[0] });
288  }
289}
290try { ab('close'); } catch {}
291
292report.failures = failures;
293writeFileSync(join(outDir, 'report.json'), JSON.stringify(report, null, 2));
294const md = [`# Verification report`, ``, `Seed ${SEED}, ${report.startedAt}. Total failures: **${failures}**.`, ``];
295const fr = report.fights;
296md.push(`## Fights through the API`, ``, `${fr.fights} fights on seeds ${FIGHT_SEEDS.join(', ')}, each log replayed through \`web/js/playback.js\` and checked against the server's hp. Event kinds: ${JSON.stringify(fr.kinds)}.`, ``, ...(fr.problems.length ? fr.problems.map((p) => `- FAIL ${p}`) : ['No problems.']), ``);
297for (const r of report.resolutions) {
298  md.push(`## ${r.resolution}`, ``);
299  if (r.aborted) md.push(`Harness aborted: ${r.aborted}`, ``);
300  md.push(`| # | Interaction | Result | Mode | Observed state after (from /api/state) | Detail |`, `|---|---|---|---|---|---|`);
301  r.steps.forEach((q, i) => md.push(`| ${i + 1} | ${q.action} | ${q.ok ? 'ok' : '**FAIL**'} | ${q.mode} | ${q.after} | ${q.detail} |`));
302  md.push(``, `Layout checks:`, ``);
303  for (const l of r.layout) md.push(`- ${l.label}: ${l.issues.length ? '' : 'ok'}`, ...l.issues.map((i) => `  - FAIL ${i}`));
304  md.push(``, `Console errors: ${r.consoleErrors.length || 'none'}`, ...r.consoleErrors.map((e) => `- ${e}`), ``);
305}
306writeFileSync(join(outDir, 'report.md'), md.join('\n'));
307console.log(`\n${failures} failure(s). Report: ${join(outDir, 'report.md')}`);
308process.exit(failures ? 1 : 0);