xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / scripts / bot.mjs 170 lines6.0 kB Raw
1import { hexDistance } from '../web/js/hex.js';
2import { maxHp } from '../web/js/stats.js';
3
4const SAFE = 80;
5const FLOOR = 50;
6const WOUNDS = 50;
7const BOSS = 90;
8const SHOP_KINDS = ['camp', 'village'];
9
10const score = (it) => it.bonus.maxHp / 3 + it.bonus.attack + it.bonus.defense + it.bonus.magic + it.bonus.speed / 2;
11export function upgrades(s) {
12  const out = [];
13  const taken = new Set();
14  for (const u of s.party.units) {
15    for (const it of s.party.inventory || []) {
16      if (!it.slot || taken.has(it.id)) continue;
17      const old = u.gear?.[it.slot];
18      if (!old || score(old) < score(it)) {
19        out.push({ unit: u.id, item: it.id });
20        taken.add(it.id);
21        break;
22      }
23    }
24  }
25  return out;
26}
27
28export const finished = (s) => s.phase === 'victory' || s.phase === 'defeat';
29export const night = (s) => s.clock.time >= s.clock.dayLength;
30const weak = (s) => s.party.units.some((u) => u.stats.hp * 2 < maxHp(u));
31const full = (s) => s.party.units.every((u) => u.stats.hp >= maxHp(u));
32const levels = (s) => s.party.units.reduce((n, u) => n + u.level, 0);
33const away = (s) => (p) => hexDistance(p.x, p.y, s.party.x, s.party.y);
34const sites = (s) => [...s.map.spawns, ...s.map.pois.filter((p) => p.cleared)].sort((a, b) => away(s)(a) - away(s)(b));
35const shops = (s) => [...s.map.spawns, ...s.map.pois.filter((p) => p.cleared && SHOP_KINDS.includes(p.kind))].sort((a, b) => away(s)(a) - away(s)(b));
36
37function target(s, seen) {
38  const lv = levels(s);
39  const main = s.campaign.main.steps;
40  const open = main.filter((q) => !q.done);
41  const boss = main.at(-1).poi;
42  const fresh = (id) => seen[id]?.lv !== lv;
43  const next = s.map.pois.find((p) => p.id === open[0]?.poi);
44  if (next && fresh(next.id) && next.id !== boss) return next;
45  const pois = s.map.pois.filter((p) => !p.cleared && fresh(p.id) && p.id !== boss);
46  const bands = (s.map.bands || []).filter((b) => !b.cleared && fresh(b.id));
47  const other = [...pois, ...bands].sort((a, b) => a.level - b.level || away(s)(a) - away(s)(b))[0];
48  return (next && fresh(next.id) && open.length === 1 && (!other || full(s)) ? next : other) || null;
49}
50
51export function createBot(io, { safe = SAFE, note = () => {} } = {}) {
52  let bar = safe;
53  const seen = {};
54  const worn = {};
55
56  async function engage(s) {
57    const t = s.threat;
58    const id = t.poi || t.band;
59    const boss = id === s.campaign.main.steps.at(-1).poi;
60    const costly = t.wounds > WOUNDS && !full(s) && (worn[id] || 0) < 2;
61    if (!t.barred && !costly && t.odds >= (boss ? BOSS : bar)) {
62      note('fight', `${id} at ${t.odds}% odds, ${t.wounds}% wounds`);
63      const after = await io.fight(s);
64      if (after.phase !== 'defeat') bar = safe;
65      return after;
66    }
67    if (t.wounds > WOUNDS && !full(s)) worn[id] = (worn[id] || 0) + 1;
68    seen[id] = { lv: levels(s), hurt: !full(s) && t.odds >= bar };
69    note('back off', `${id} at ${t.odds}% odds, ${t.wounds}% wounds${t.barred ? ', barred' : ''}`);
70    return io.back(s);
71  }
72
73  async function travel(s, p) {
74    const after = await io.go(p);
75    return after.threat ? engage(after) : after;
76  }
77
78  async function dusk(s) {
79    for (let i = 0; i < 12 && !night(s) && !finished(s); i++) {
80      const far = sites(s).find((p) => away(s)(p) >= 5) || sites(s).at(-1);
81      note('wait for dusk', `walk to ${far.kind || far.name} at ${far.x},${far.y}`);
82      s = await travel(s, far);
83    }
84    return s;
85  }
86
87  async function camp(s) {
88    for (const p of [null, ...sites(s).slice(0, 3)]) {
89      if (p) s = await travel(s, p);
90      if (finished(s) || !night(s)) return s;
91      const r = await io.camp(s);
92      if (r.ok) {
93        note('camp', `day ${r.state.clock.day} begins`);
94        for (const k of Object.keys(seen)) if (seen[k].hurt) delete seen[k];
95        return r.state;
96      }
97      s = r.state;
98    }
99    return s;
100  }
101
102  async function drinkUp(s) {
103    for (const u of s.party.units) {
104      if (!s.party.potions || u.stats.hp * 2 >= maxHp(u)) continue;
105      note('drink', `${u.name} at ${u.stats.hp}/${maxHp(u)}`);
106      s = await io.drink(s, u);
107    }
108    return s;
109  }
110
111  async function recover(s) {
112    if (night(s)) return camp(s);
113    s = await drinkUp(s);
114    if (!weak(s)) return s;
115    const shop = shops(s)[0];
116    if (shop && s.party.gold >= 30) {
117      if (away(s)(shop)) s = await travel(s, shop);
118      for (let i = 0; i < 2 && s.shop && s.party.gold >= s.shop.potionPrice; i++) {
119        note('buy', `potion for ${s.shop.potionPrice} gold at ${s.shop.name}`);
120        s = await io.buy(s);
121      }
122      s = await drinkUp(s);
123      if (!weak(s)) return s;
124    }
125    return camp(await dusk(s));
126  }
127
128  async function step(s) {
129    for (const u of upgrades(s)) {
130      note('equip', `${u.item} on ${u.unit}`);
131      s = await io.equip(s, u);
132    }
133    if (weak(s)) return recover(s);
134    const t = target(s, seen);
135    if (t) return travel(s, t);
136    if (!full(s)) return camp(await dusk(s));
137    bar = Math.max(FLOOR, bar - 10);
138    for (const k of Object.keys(seen)) delete seen[k];
139    note('lower the bar', `fight at ${bar}% odds or better`);
140    return s;
141  }
142
143  return { step };
144}
145
146export async function playOut(io, s, { steps = 400, ...o } = {}) {
147  const bot = createBot(io, o);
148  for (let i = 0; i < steps && !finished(s); i++) s = await bot.step(s);
149  return s;
150}
151
152export function apiIO(api) {
153  const state = () => api('/api/state');
154  const call = async (path, body) => {
155    const r = await api(path, body);
156    return r.error ? { error: r.error, state: await state() } : { state: r };
157  };
158  return {
159    go: async (p) => (await call('/api/move', { x: p.x, y: p.y })).state,
160    fight: async (s) => (await call('/api/interact', { id: s.threat.poi || s.threat.band })).state,
161    back: () => state(),
162    camp: async () => {
163      const r = await call('/api/rest', {});
164      return { ok: !r.error, state: r.state, error: r.error };
165    },
166    drink: async (s, u) => (await call('/api/drink', { unit: u.id })).state,
167    buy: async () => (await call('/api/buy', { item: 'potion' })).state,
168    equip: async (s, u) => (await call('/api/equip', { unit: u.unit, item: u.item })).state,
169  };
170}