fertig-classic-games/src/games/go/GoEngine.js

96 lines
3.8 KiB
JavaScript

// GoEngine.js: runs the opponents (GoAI) and Hōun's problem solver
// (GoTsumego) off the main thread, so the temple keeps breathing (mist,
// petals, incense) while someone thinks.
//
// handle(kind, payload) the actual work (shared by the worker and the
// synchronous fallback)
// class Engine main-thread client: request(kind, payload) →
// Promise. Uses a module Worker (GoWorker.js);
// if that can't start, runs the same code inline.
//
// Kinds (pos: see GoAI.posOf):
// move { pos, skill } → { sq, resign, winrate, lead, ownership, pv }
// hint { pos, playouts, ms } → { best, top, winrate, lead, ownership, pv }
// estimate { pos, playouts, ms } → same as hint (cheaper budget; the score bar)
// dead { pos, playouts, ms } → { dead[], ownership[] }
// review { positions, playouts, ms } → [{ lead, winrate, best }]
// puzzleReply { prob } → { sq, refutes }
// puzzleCheck { prob, human } → { wins, settled, terminal }
import * as AI from './GoAI.js';
import * as T from './GoTsumego.js';
export function handle(kind, p) {
switch (kind) {
case 'move': return AI.chooseMove(p.pos, p.skill, { scale: p.scale ?? 1 });
case 'hint':
case 'estimate': return AI.analyse(p.pos, { playouts: p.playouts ?? 6000, ms: p.ms ?? 1200 });
case 'dead': return AI.estimateDead(p.pos, { playouts: p.playouts ?? 3000, ms: p.ms ?? 1500 });
case 'review': return AI.reviewPositions(p.positions, { playouts: p.playouts ?? 500, ms: p.ms ?? 250 });
case 'puzzleReply': return T.reply(p.prob, { maxNodes: 200000 });
case 'puzzleCheck': {
const term = T.terminal(p.prob);
const wins = term ? (term === 'dead') === (p.human === p.prob.attacker) : T.wins(p.prob, p.human, { maxNodes: 200000 });
const settled = wins && (term ? true : T.settled(p.prob, p.human, { maxNodes: 200000 }));
return { wins, settled, terminal: term };
}
default: return null;
}
}
export class Engine {
constructor() {
this.seq = 0;
this.pending = new Map();
this.worker = null;
try {
if (typeof Worker !== 'undefined') {
this.worker = new Worker(new URL('./GoWorker.js', import.meta.url), { type: 'module' });
this.worker.onmessage = (e) => this.settle(e.data);
this.worker.onerror = (e) => { e?.preventDefault?.(); this.fallBack(); };
}
} catch (_) { this.worker = null; }
}
settle({ id, res, err }) {
const job = this.pending.get(id);
if (!job) return;
this.pending.delete(id);
if (err) job.reject(new Error(err)); else job.resolve(res);
}
fallBack() {
// the worker couldn't start (or died): finish everything inline
try { this.worker?.terminate(); } catch (_) { /* */ }
this.worker = null;
for (const [id, job] of this.pending) this.runInline(id, job.kind, job.payload);
}
runInline(id, kind, payload) {
setTimeout(() => {
let res = null, err = null;
try { res = handle(kind, payload); } catch (e) { err = String(e?.message ?? e); }
this.settle({ id, res, err });
}, 0);
}
request(kind, payload) {
const id = ++this.seq;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject, kind, payload });
if (this.worker) {
try { this.worker.postMessage({ id, kind, payload }); } catch (_) { this.fallBack(); }
} else this.runInline(id, kind, payload);
});
}
/** Drop the answers to everything asked so far (a new game, an undo). */
forget() { for (const job of this.pending.values()) job.stale = true; }
destroy() {
try { this.worker?.terminate(); } catch (_) { /* */ }
this.worker = null;
this.pending.clear();
}
}