xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / scripts / driver.mjs 143 lines5.5 kB Raw
1import { execFileSync } from 'node:child_process';
2import { randomBytes } from 'node:crypto';
3
4export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5
6const PLAYER = randomBytes(16).toString('hex');
7
8export function createDriver({ session, baseUrl, w, h, player = PLAYER }) {
9  const ab = (...args) => execFileSync('agent-browser', ['--session', session, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60000 });
10  const ev = (expr) => {
11    const out = JSON.parse(ab('--json', 'eval', expr));
12    if (out.error) throw new Error(out.error);
13    return out.data.result;
14  };
15  const api = async (path, body) => {
16    const headers = { 'Content-Type': 'application/json', 'X-Player': player };
17    const res = await fetch(baseUrl + path, body === undefined ? { headers } : { method: 'POST', headers, body: JSON.stringify(body) });
18    return res.json();
19  };
20  const gameState = async () => JSON.parse(ev('JSON.stringify(window.__game.state())'));
21  const rects = async () => JSON.parse(ev('JSON.stringify(window.__game.rects())'));
22  const mode = async () => ev('window.__game.mode');
23  const clickAt = (x, y) => {
24    ab('mouse', 'move', String(x), String(y));
25    ab('mouse', 'down');
26    ab('mouse', 'up');
27  };
28  const clickRect = async (name) => {
29    const r = (await rects()).find((q) => q.name === name);
30    if (!r) throw new Error(`no rect ${name}`);
31    clickAt(Math.round(r.x + r.w / 2), Math.round(r.y + r.h / 2));
32  };
33  const waitIdle = async (observe) => {
34    const t0 = Date.now();
35    const seen = new Set();
36    while (Date.now() - t0 < 90000) {
37      const [b, m] = JSON.parse(ev('JSON.stringify([window.__game.busy, window.__game.mode])'));
38      if (!seen.has(m)) {
39        seen.add(m);
40        await observe?.(m);
41      }
42      if (!b) return [...seen];
43      await sleep(200);
44    }
45    throw new Error('game stayed busy for 90s');
46  };
47  const clickTile = async (t, observe) => {
48    ev(`window.__game.focusTile(${t.x},${t.y})`);
49    await sleep(600);
50    for (let last = '', same = 0, i = 0; i < 40 && same < 2; i++) {
51      const now = ev(`JSON.stringify(window.__game.tileScreen(${t.x},${t.y}))`);
52      same = now === last ? same + 1 : 0;
53      last = now;
54      await sleep(400);
55    }
56    const p = JSON.parse(ev(`(() => {
57      const c = window.__game.tileScreen(${t.x},${t.y});
58      for (const [dx, dy] of [[0, 0], [0, -12], [0, -24], [10, -8], [-10, -8], [0, -36], [14, -20], [-14, -20], [0, 8]]) {
59        const q = window.__game.pickAt(c.x + dx, c.y + dy);
60        if (q && q.x === ${t.x} && q.y === ${t.y}) return JSON.stringify({ x: c.x + dx, y: c.y + dy });
61      }
62      return JSON.stringify(c);
63    })()`));
64    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}`);
65    clickAt(Math.round(p.x), Math.round(p.y));
66    ev('window.__game.focusTile(null)');
67    for (const t0 = Date.now(); Date.now() - t0 < 3000 && !ev('window.__game.busy'); ) await sleep(100);
68    return waitIdle(observe);
69  };
70  const fight = async (observe) => {
71    await clickRect('threat-fight');
72    await sleep(300);
73    const seen = await waitIdle(observe);
74    const drift = JSON.parse(ev('JSON.stringify(window.__game.drift())'));
75    if (drift.length) throw new Error(`fight playback disagrees with the server: ${drift.join('; ')}`);
76    return seen;
77  };
78  const settle = async (ms = 400) => {
79    await sleep(ms);
80    return api('/api/state');
81  };
82  const ui = (observe) => ({
83    go: async (p) => {
84      await clickTile(p, observe);
85      return api('/api/state');
86    },
87    fight: async () => {
88      await fight(observe);
89      return api('/api/state');
90    },
91    back: async () => {
92      await clickRect('threat-back');
93      return settle();
94    },
95    camp: async (s) => {
96      if (!(await rects()).some((r) => r.name === 'btn-camp')) return { ok: false, state: s, error: 'no Make camp button' };
97      await clickRect('btn-camp');
98      for (const t0 = Date.now(); Date.now() - t0 < 2000 && !ev('window.__game.busy'); ) await sleep(100);
99      await waitIdle(observe);
100      const after = await api('/api/state');
101      return { ok: after.clock.day > s.clock.day, state: after };
102    },
103    drink: async (s, u) => {
104      ab('press', String(s.party.units.findIndex((q) => q.id === u.id) + 1));
105      ab('press', 'p');
106      return settle();
107    },
108    buy: async () => {
109      ab('press', 't');
110      await sleep(400);
111      await clickRect('buy-potion');
112      await sleep(400);
113      ab('press', 'Escape');
114      return settle(200);
115    },
116    equip: async (s, pick) => {
117      ab('press', 'i');
118      await sleep(300);
119      await clickRect(`tab-${s.party.units.findIndex((u) => u.id === pick.unit)}`);
120      await sleep(200);
121      const idx = (s.party.inventory || []).findIndex((it) => it.id === pick.item);
122      const shown = (await rects()).some((r) => r.name === `item-${idx}`);
123      if (shown) await clickRect(`item-${idx}`);
124      else await api('/api/equip', { unit: pick.unit, item: pick.item });
125      await sleep(400);
126      ab('press', 'Escape');
127      return settle(200);
128    },
129  });
130  const openPage = async (want) => {
131    ab('cookies', 'set', 'ta', player, '--url', baseUrl, '--http-only');
132    ab('open', baseUrl);
133    const t0 = Date.now();
134    while (Date.now() - t0 < 30000) {
135      try {
136        if (ev('typeof window.__game') === 'object' && (await mode()) === want) return;
137      } catch {}
138      await sleep(300);
139    }
140    throw new Error(`page did not reach mode ${want}`);
141  };
142  return { ab, ev, api, gameState, rects, mode, clickAt, clickRect, waitIdle, clickTile, openPage, fight, ui };
143}