xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / scripts / playthrough.mjs 159 lines5.9 kB Raw
1import { mkdirSync, writeFileSync } from 'node:fs';
2import { join } from 'node:path';
3import { createDriver, sleep } from './driver.mjs';
4import { createBot, finished, upgrades } from './bot.mjs';
5import { layoutIssues } from './layout.mjs';
6
7const [outDir, baseUrl, seedArg, wArg, hArg, name] = process.argv.slice(2);
8const SEED = Number(seedArg);
9const W = Number(wArg || 1280);
10const H = Number(hArg || 720);
11const TAG = name || `seed${SEED}`;
12const SESSION = `play-${process.pid}`;
13const MAX_STEPS = Number(process.env.PLAY_MAX_STEPS || 160);
14
15mkdirSync(outDir, { recursive: true });
16const d = createDriver({ session: SESSION, baseUrl, w: W, h: H });
17const { ab, api, rects, mode, clickRect, gameState } = d;
18const log = [];
19let failures = 0;
20
21const brief = (s) => `phase=${s.phase} day=${s.clock.day} time=${s.clock.time} at=${s.party.x},${s.party.y} battles=${s.summary.battles} kills=${s.summary.kills} loot=${s.summary.loot} steps=${s.summary.steps} gold=${s.party.gold} levels=${s.party.units.map((u) => u.level).join('/')}`;
22const record = (action, ok, detail) => {
23  if (!ok) failures++;
24  log.push({ action, ok, detail });
25  console.log(`${ok ? 'ok  ' : 'FAIL'} ${action} | ${detail}`);
26};
27const shot = (label) => ab('screenshot', join(outDir, `${TAG}-${label}.png`));
28const layout = async (label) => {
29  for (const i of layoutIssues(await rects(), W, H)) record(`layout ${label}`, false, i);
30};
31const presses = async (key, settle = 500) => {
32  ab('press', key);
33  await sleep(settle);
34};
35
36ab('set', 'viewport', String(W), String(H));
37await api('/api/new', { seed: SEED });
38await d.openPage('title');
39ab('errors', '--clear');
40ab('record', 'start', join(outDir, `${TAG}.webm`), '--fps', '10');
41
42await layout('title');
43await clickRect('button-0');
44await sleep(600);
45record('click Begin Adventure', (await mode()) === 'explore', `mode=${await mode()}`);
46
47await presses('j');
48record('press J opens journal', (await rects()).some((r) => r.name === 'panel-journal'), 'journal rect');
49shot('journal');
50await presses('Escape');
51
52async function prepare() {
53  const t = (await api('/api/state')).threat;
54  await clickRect('threat-prepare');
55  await sleep(500);
56  const open = (await rects()).some((r) => r.name === 'prepare-back');
57  if (!log.some((l) => l.action.startsWith('prepare'))) {
58    shot('prepare');
59    await layout('prepare');
60  }
61  let picks = 0;
62  for (let st = await api('/api/state'), pick = upgrades(st)[0]; pick && picks < 6; st = await api('/api/state'), pick = upgrades(st)[0]) {
63    await clickRect(`tab-${st.party.units.findIndex((u) => u.id === pick.unit)}`);
64    await sleep(200);
65    const idx = (st.party.inventory || []).findIndex((it) => it.id === pick.item);
66    if (!(await rects()).some((r) => r.name === `item-${idx}`)) break;
67    await clickRect(`item-${idx}`);
68    await sleep(600);
69    picks++;
70  }
71  const after = (await api('/api/state')).threat;
72  await clickRect('prepare-back');
73  await sleep(400);
74  const back = await mode();
75  record('prepare: open inventory from the threat card, click upgrades in the pack, back to the fight', open && back === 'threat', `odds ${t.odds}% -> ${after?.odds}% after ${picks} upgrades, mode=${back}`);
76}
77
78const once = new Set();
79const first = (k) => !once.has(k) && once.add(k);
80const observe = async (m) => {
81  if (m === 'combat' && first('combat')) {
82    await sleep(900);
83    shot('combat');
84    await layout('combat');
85  }
86  if (m === 'camp' && first('camp')) {
87    await sleep(1200);
88    shot('camp');
89  }
90};
91const base = d.ui(observe);
92const io = {
93  ...base,
94  go: async (p) => {
95    const s = await base.go(p);
96    if (s.threat && first('threat')) {
97      shot(s.threat.band ? 'band' : 'threat');
98      await layout('threat');
99      if (!s.threat.barred) await prepare();
100      return api('/api/state');
101    }
102    return s;
103  },
104  buy: async (s) => {
105    if (first('shop')) {
106      ab('press', 't');
107      await sleep(500);
108      shot('shop');
109      await layout('shop');
110      ab('press', 'Escape');
111      await sleep(300);
112    }
113    return base.buy(s);
114  },
115  camp: async (s) => {
116    if (first('night')) {
117      shot('night');
118      await layout('night');
119    }
120    return base.camp(s);
121  },
122};
123let s = await api('/api/state');
124let steps = 0;
125let pending = null;
126const note = (action, detail) => (pending = { action, detail });
127const bot = createBot(io, { note });
128while (!finished(s) && steps < MAX_STEPS) {
129  const before = s;
130  pending = null;
131  s = await bot.step(s);
132  steps++;
133  if (!pending) continue;
134  const local = await gameState();
135  const synced = local.party.x === s.party.x && local.party.y === s.party.y && local.clock.day === s.clock.day;
136  const print = (q) => JSON.stringify([q.summary, q.clock, q.party.x, q.party.y, q.party.potions, q.party.gold, q.party.units.map((u) => [u.stats.hp, u.gear])]);
137  const changed = print(s) !== print(before) || ['back off', 'lower the bar'].includes(pending.action);
138  record(`${pending.action}: ${pending.detail}`, synced && changed, `${brief(s)} client=${local.party.x},${local.party.y} day ${local.clock.day}`);
139  if (steps === 3) shot('explore');
140}
141
142await sleep(800);
143const m = await mode();
144record('end screen reached after victory', s.phase === 'victory' && m === 'end', `mode=${m} ${brief(s)}`);
145if (m === 'end') {
146  shot('end');
147  await layout('end');
148}
149ab('record', 'stop');
150const errs = ab('errors').trim();
151const clean = !errs || /no (page )?errors/i.test(errs);
152record('console errors', clean, clean ? 'none' : errs.split('\n')[0]);
153
154writeFileSync(join(outDir, `${TAG}.json`), JSON.stringify({ seed: SEED, w: W, h: H, steps, failures, log }, null, 2));
155const md = [`# Playthrough ${TAG} (seed ${SEED}, ${W}x${H})`, '', `Failures: **${failures}**, bot steps: ${steps}`, '', '| # | Interaction | Result | Observed |', '|---|---|---|---|', ...log.map((l, i) => `| ${i + 1} | ${l.action} | ${l.ok ? 'ok' : '**FAIL**'} | ${l.detail} |`), ''];
156writeFileSync(join(outDir, `${TAG}.md`), md.join('\n'));
157try { ab('close'); } catch {}
158console.log(`${failures} failure(s)`);
159process.exit(failures ? 1 : 0);