673 lines
26 KiB
JavaScript
673 lines
26 KiB
JavaScript
// OthelloAI.js: the opponents and the Master's analysis. Phaser-free; runs
|
||
// in the engine worker (OthelloEngine.js) and in tools/verifyOthello.js.
|
||
//
|
||
// The searcher keeps a padded "mailbox" board (works for 6×6, 8×8, 10×10),
|
||
// makes and unmakes moves in place with a flip stack and Zobrist hashing,
|
||
// and runs negamax alpha-beta with PVS, a transposition table, iterative
|
||
// deepening and "fastest-first" move ordering. With few squares left it
|
||
// solves the game exactly (final disc difference).
|
||
//
|
||
// Positions passed in are plain: { size, variant, board: [null|'black'|'white'…], turn }.
|
||
//
|
||
// chooseMove(pos, skill, { line, rnd }) → { sq, score, book, exact }
|
||
// hint(pos, { ms }) → { sq, score, exact, depth }
|
||
// rankMoves(pos, { depth, ms }) → [{ sq, score }] best first
|
||
// review(positions, { ms }) → [{ i, best, played, loss, exact }]
|
||
// describeIdea(pos, sq, res) → coach text ("takes a corner")
|
||
// describeMistake(pos, played, best) → what went wrong ("gave up a corner")
|
||
//
|
||
// Scores are from the side to move, in hundredths of a disc. A finished
|
||
// game scores ±(WIN + |diff|·10), so any win beats any non-final position.
|
||
|
||
import {
|
||
flipsFor, movesFor, isCorner, isEdge, xCorner, cCorner, other, parseSq, BLACK,
|
||
} from './OthelloLogic.js';
|
||
import { bookReplies } from './OthelloBook.js';
|
||
|
||
export const WIN = 20000;
|
||
const INF = 1e9;
|
||
const EMPTY = 0, OUT = 3;
|
||
|
||
export const PROFILES = {
|
||
1: { depth: 1, ms: 60, noise: 900, blunder: 0.2, solve: 0, solveMs: 0, book: 0, style: 'greedy' },
|
||
2: { depth: 2, ms: 150, noise: 380, blunder: 0.06, solve: 4, solveMs: 200, book: 0, style: 'greedy' },
|
||
3: { depth: 4, ms: 320, noise: 140, blunder: 0, solve: 8, solveMs: 600, book: 0.6, style: 'edgy' },
|
||
4: { depth: 7, ms: 650, noise: 30, blunder: 0, solve: 12, solveMs: 1500, book: 1, style: 'sound' },
|
||
5: { depth: 16, ms: 1100, noise: 0, blunder: 0, solve: 16, solveMs: 3500, book: 1, style: 'sound' },
|
||
};
|
||
|
||
export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
|
||
export const profileFor = (skill) => PROFILES[clampSkill(skill)];
|
||
|
||
function rand32(rnd) { return (Math.floor(rnd() * 0x100000000) | 0); }
|
||
function seeded(seed) {
|
||
let a = seed >>> 0;
|
||
return () => {
|
||
a = (a + 0x6d2b79f5) >>> 0;
|
||
let t = a;
|
||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
}
|
||
|
||
const TT_BITS = 18, TT_SIZE = 1 << TT_BITS, TT_MASK = TT_SIZE - 1;
|
||
const F_EXACT = 1, F_LOWER = 2, F_UPPER = 3;
|
||
|
||
class Searcher {
|
||
constructor(size, variant) {
|
||
const n = size, P = n + 2;
|
||
this.n = n; this.P = P; this.N = n * n;
|
||
this.anti = variant === 'anti';
|
||
this.dirs = [-P - 1, -P, -P + 1, -1, 1, P - 1, P, P + 1];
|
||
this.b = new Int8Array(P * P).fill(OUT);
|
||
this.cells = new Int16Array(this.N); // sq → padded index
|
||
this.sqOf = new Int16Array(P * P).fill(-1);
|
||
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
|
||
const i = (r + 1) * P + c + 1;
|
||
this.cells[r * n + c] = i; this.sqOf[i] = r * n + c;
|
||
}
|
||
// flips + per-ply move buffers
|
||
this.stack = new Int16Array(16384); this.sp = 0;
|
||
this.moveBuf = new Int16Array((this.N + 24) * this.N);
|
||
this.scoreBuf = new Int32Array((this.N + 24) * this.N);
|
||
// empties set
|
||
this.empties = new Int16Array(this.N); this.epos = new Int16Array(P * P); this.ne = 0;
|
||
// zobrist
|
||
const rnd = seeded(0x0e110 + n);
|
||
this.zLo = [null, new Int32Array(P * P), new Int32Array(P * P)];
|
||
this.zHi = [null, new Int32Array(P * P), new Int32Array(P * P)];
|
||
this.zfLo = new Int32Array(P * P); this.zfHi = new Int32Array(P * P);
|
||
for (let i = 0; i < P * P; i++) {
|
||
for (const v of [1, 2]) { this.zLo[v][i] = rand32(rnd); this.zHi[v][i] = rand32(rnd); }
|
||
this.zfLo[i] = this.zLo[1][i] ^ this.zLo[2][i]; this.zfHi[i] = this.zHi[1][i] ^ this.zHi[2][i];
|
||
}
|
||
this.sideLo = rand32(rnd); this.sideHi = rand32(rnd);
|
||
this.hLo = 0; this.hHi = 0;
|
||
// TT
|
||
this.ttLo = new Int32Array(TT_SIZE); this.ttHi = new Int32Array(TT_SIZE);
|
||
this.ttDepth = new Int8Array(TT_SIZE); this.ttFlag = new Int8Array(TT_SIZE);
|
||
this.ttScore = new Int32Array(TT_SIZE); this.ttMove = new Int16Array(TT_SIZE);
|
||
// square weights & corner geometry
|
||
this.w = new Int16Array(P * P);
|
||
this.cornerInfo = [];
|
||
const e = n - 1;
|
||
for (let sq = 0; sq < this.N; sq++) {
|
||
const r = Math.floor(sq / n), c = sq % n, i = this.cells[sq];
|
||
let w;
|
||
if (isCorner(sq, n)) w = 0; // scored by the corner term
|
||
else if (xCorner(sq, n) >= 0) w = -25;
|
||
else if (cCorner(sq, n) >= 0) w = -6;
|
||
else if (r === 0 || r === e || c === 0 || c === e) w = (r === 2 || r === e - 2 || c === 2 || c === e - 2) ? 10 : 6;
|
||
else if (r === 1 || r === e - 1 || c === 1 || c === e - 1) w = -4;
|
||
else w = (r === 2 || r === e - 2 || c === 2 || c === e - 2) ? 3 : 1;
|
||
this.w[i] = w;
|
||
}
|
||
for (const [cr, cc, dr, dc] of [[0, 0, 1, 1], [0, e, 1, -1], [e, 0, -1, 1], [e, e, -1, -1]]) {
|
||
const at = (r, c) => this.cells[r * n + c];
|
||
this.cornerInfo.push({
|
||
corner: at(cr, cc), x: at(cr + dr, cc + dc), c1: at(cr + dr, cc), c2: at(cr, cc + dc),
|
||
// walking along the two edges away from the corner
|
||
stepA: dr * P, stepB: dc,
|
||
});
|
||
}
|
||
this.abort = false; this.deadline = Infinity; this.nodes = 0;
|
||
}
|
||
|
||
load(board, turn) {
|
||
this.b.fill(OUT);
|
||
this.ne = 0; this.hLo = 0; this.hHi = 0; this.sp = 0;
|
||
for (let sq = 0; sq < this.N; sq++) {
|
||
const i = this.cells[sq], v = board[sq];
|
||
if (v === null || v === undefined) {
|
||
this.b[i] = EMPTY; this.empties[this.ne] = i; this.epos[i] = this.ne++;
|
||
} else {
|
||
const k = v === BLACK ? 1 : 2;
|
||
this.b[i] = k; this.hLo ^= this.zLo[k][i]; this.hHi ^= this.zHi[k][i];
|
||
}
|
||
}
|
||
const me = turn === BLACK ? 1 : 2;
|
||
if (me === 2) { this.hLo ^= this.sideLo; this.hHi ^= this.sideHi; }
|
||
return me;
|
||
}
|
||
|
||
clearTT() { this.ttDepth.fill(-1); this.ttLo.fill(0); this.ttHi.fill(0); }
|
||
|
||
legal(i, me) {
|
||
const b = this.b, opp = 3 - me;
|
||
for (let k = 0; k < 8; k++) {
|
||
const d = this.dirs[k];
|
||
let p = i + d;
|
||
if (b[p] !== opp) continue;
|
||
p += d;
|
||
while (b[p] === opp) p += d;
|
||
if (b[p] === me) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
gen(me, ply) {
|
||
const base = ply * this.N;
|
||
let n = 0;
|
||
for (let k = 0; k < this.ne; k++) {
|
||
const i = this.empties[k];
|
||
if (this.legal(i, me)) this.moveBuf[base + n++] = i;
|
||
}
|
||
return n;
|
||
}
|
||
|
||
mobility(me) {
|
||
let n = 0;
|
||
for (let k = 0; k < this.ne; k++) if (this.legal(this.empties[k], me)) n++;
|
||
return n;
|
||
}
|
||
|
||
/** Place for `me` at i; returns flips (0 = illegal, nothing changed). */
|
||
make(i, me) {
|
||
const b = this.b, opp = 3 - me, st = this.stack;
|
||
let n = 0;
|
||
for (let k = 0; k < 8; k++) {
|
||
const d = this.dirs[k];
|
||
let p = i + d;
|
||
if (b[p] !== opp) continue;
|
||
p += d;
|
||
while (b[p] === opp) p += d;
|
||
if (b[p] !== me) continue;
|
||
p -= d;
|
||
while (p !== i) {
|
||
b[p] = me; st[this.sp++] = p; n++;
|
||
this.hLo ^= this.zfLo[p]; this.hHi ^= this.zfHi[p];
|
||
p -= d;
|
||
}
|
||
}
|
||
if (!n) return 0;
|
||
st[this.sp++] = n;
|
||
b[i] = me;
|
||
this.hLo ^= this.zLo[me][i] ^ this.sideLo; this.hHi ^= this.zHi[me][i] ^ this.sideHi;
|
||
const at = this.epos[i], last = this.empties[--this.ne];
|
||
this.empties[at] = last; this.epos[last] = at;
|
||
return n;
|
||
}
|
||
|
||
unmake(i, me) {
|
||
const b = this.b, opp = 3 - me, st = this.stack;
|
||
const n = st[--this.sp];
|
||
for (let k = 0; k < n; k++) {
|
||
const p = st[--this.sp];
|
||
b[p] = opp;
|
||
this.hLo ^= this.zfLo[p]; this.hHi ^= this.zfHi[p];
|
||
}
|
||
b[i] = EMPTY;
|
||
this.hLo ^= this.zLo[me][i] ^ this.sideLo; this.hHi ^= this.zHi[me][i] ^ this.sideHi;
|
||
this.empties[this.ne] = i; this.epos[i] = this.ne++;
|
||
}
|
||
|
||
pass() { this.hLo ^= this.sideLo; this.hHi ^= this.sideHi; }
|
||
|
||
discDiff(me) {
|
||
const b = this.b, opp = 3 - me;
|
||
let d = 0;
|
||
for (let s = 0; s < this.N; s++) { const v = b[this.cells[s]]; if (v === me) d++; else if (v === opp) d--; }
|
||
return d;
|
||
}
|
||
|
||
terminal(me) {
|
||
let d = this.discDiff(me);
|
||
if (this.anti) d = -d;
|
||
return d > 0 ? WIN + d * 10 : d < 0 ? -WIN + d * 10 : 0;
|
||
}
|
||
|
||
evaluate(me) {
|
||
if (this.ne === 0) return this.terminal(me);
|
||
const opp = 3 - me, b = this.b;
|
||
const mm = this.mobility(me), om = this.mobility(opp);
|
||
if (mm === 0 && om === 0) return this.terminal(me);
|
||
const sgn = this.anti ? -1 : 1;
|
||
let pos = 0, discs = 0;
|
||
for (let s = 0; s < this.N; s++) {
|
||
const i = this.cells[s], v = b[i];
|
||
if (v === me) { pos += this.w[i]; discs++; } else if (v === opp) { pos -= this.w[i]; discs--; }
|
||
}
|
||
let corner = 0, risk = 0, stable = 0;
|
||
for (const ci of this.cornerInfo) {
|
||
const cv = b[ci.corner];
|
||
if (cv === EMPTY) {
|
||
const xv = b[ci.x];
|
||
if (xv === me) risk -= 120; else if (xv === opp) risk += 120;
|
||
for (const c of [ci.c1, ci.c2]) { const v = b[c]; if (v === me) risk -= 30; else if (v === opp) risk += 30; }
|
||
} else {
|
||
corner += cv === me ? 1 : -1;
|
||
// edge discs anchored to the corner can never flip
|
||
for (const step of [ci.stepA, ci.stepB]) {
|
||
let p = ci.corner + step, k = 0;
|
||
while (b[p] === cv && k < this.n - 2) { k++; p += step; }
|
||
stable += cv === me ? k : -k;
|
||
}
|
||
}
|
||
}
|
||
// potential mobility: empty squares next to the other side's discs
|
||
let pm = 0;
|
||
for (let k = 0; k < this.ne; k++) {
|
||
const i = this.empties[k];
|
||
for (let d = 0; d < 8; d++) { const v = b[i + this.dirs[d]]; if (v === opp) pm++; else if (v === me) pm--; }
|
||
}
|
||
const fill = 1 - this.ne / this.N;
|
||
const late = fill > 0.75;
|
||
let score = sgn * (pos * 4 + corner * 360 + risk + stable * 70);
|
||
score += (mm - om) * (late ? 30 : 48) + pm * 5;
|
||
if (late) score += sgn * discs * 22;
|
||
else if (fill < 0.4) score -= sgn * discs * 4;
|
||
if (fill > 0.7) score += (this.ne & 1) ? 35 : -35;
|
||
if (mm === 0) score -= 120;
|
||
if (om === 0) score += 120;
|
||
return score;
|
||
}
|
||
|
||
probe() {
|
||
const k = this.hLo & TT_MASK;
|
||
if (this.ttDepth[k] >= 0 && this.ttLo[k] === this.hLo && this.ttHi[k] === this.hHi) return k;
|
||
return -1;
|
||
}
|
||
|
||
store(depth, flag, score, move) {
|
||
const k = this.hLo & TT_MASK;
|
||
if (this.ttDepth[k] > depth && this.ttLo[k] === this.hLo && this.ttHi[k] === this.hHi && this.ttFlag[k] === F_EXACT) return;
|
||
this.ttLo[k] = this.hLo; this.ttHi[k] = this.hHi; this.ttDepth[k] = Math.min(127, depth);
|
||
this.ttFlag[k] = flag; this.ttScore[k] = score; this.ttMove[k] = move;
|
||
}
|
||
|
||
order(me, ply, n, depth, ttMove) {
|
||
const base = ply * this.N, mv = this.moveBuf, sc = this.scoreBuf, opp = 3 - me;
|
||
for (let j = 0; j < n; j++) {
|
||
const i = mv[base + j];
|
||
let s;
|
||
if (i === ttMove) s = 1e7;
|
||
else if (depth >= 3) {
|
||
this.make(i, me);
|
||
s = -this.mobility(opp) * 100 + this.w[i] * 3;
|
||
this.unmake(i, me);
|
||
} else s = this.w[i];
|
||
if (this.isCornerIdx(i)) s += this.anti ? -500 : 500;
|
||
sc[base + j] = s;
|
||
}
|
||
// insertion sort, best first
|
||
for (let a = 1; a < n; a++) {
|
||
const m = mv[base + a], s = sc[base + a];
|
||
let c = a - 1;
|
||
while (c >= 0 && sc[base + c] < s) { mv[base + c + 1] = mv[base + c]; sc[base + c + 1] = sc[base + c]; c--; }
|
||
mv[base + c + 1] = m; sc[base + c + 1] = s;
|
||
}
|
||
}
|
||
|
||
isCornerIdx(i) { for (const ci of this.cornerInfo) if (ci.corner === i) return true; return false; }
|
||
|
||
tick() {
|
||
if ((++this.nodes & 2047) === 0 && Date.now() > this.deadline) this.abort = true;
|
||
return this.abort;
|
||
}
|
||
|
||
search(me, depth, alpha, beta, passed, ply) {
|
||
if (this.tick()) return 0;
|
||
if (depth <= 0 || this.ne === 0) return this.evaluate(me);
|
||
const a0 = alpha;
|
||
let ttMove = -1;
|
||
const t = this.probe();
|
||
if (t >= 0) {
|
||
ttMove = this.ttMove[t];
|
||
if (this.ttDepth[t] >= depth) {
|
||
const s = this.ttScore[t], f = this.ttFlag[t];
|
||
if (f === F_EXACT) return s;
|
||
if (f === F_LOWER && s > alpha) alpha = s;
|
||
else if (f === F_UPPER && s < beta) beta = s;
|
||
if (alpha >= beta) return s;
|
||
}
|
||
}
|
||
const n = this.gen(me, ply);
|
||
if (n === 0) {
|
||
if (passed) return this.terminal(me);
|
||
this.pass();
|
||
const v = -this.search(3 - me, depth, -beta, -alpha, true, ply + 1);
|
||
this.pass();
|
||
return v;
|
||
}
|
||
if (n > 1) this.order(me, ply, n, depth, ttMove);
|
||
const base = ply * this.N;
|
||
let best = -INF, bestMove = -1;
|
||
for (let j = 0; j < n; j++) {
|
||
const i = this.moveBuf[base + j];
|
||
this.make(i, me);
|
||
let v;
|
||
if (j === 0) v = -this.search(3 - me, depth - 1, -beta, -alpha, false, ply + 1);
|
||
else {
|
||
v = -this.search(3 - me, depth - 1, -alpha - 1, -alpha, false, ply + 1);
|
||
if (v > alpha && v < beta && !this.abort) v = -this.search(3 - me, depth - 1, -beta, -alpha, false, ply + 1);
|
||
}
|
||
this.unmake(i, me);
|
||
if (this.abort) return 0;
|
||
if (v > best) { best = v; bestMove = i; }
|
||
if (v > alpha) alpha = v;
|
||
if (alpha >= beta) break;
|
||
}
|
||
this.store(depth, best <= a0 ? F_UPPER : best >= beta ? F_LOWER : F_EXACT, best, bestMove);
|
||
return best;
|
||
}
|
||
|
||
/** Full-window score of every root move at `depth` (all-moves search). */
|
||
rankAt(me, depth) {
|
||
const n = this.gen(me, 0);
|
||
const out = [];
|
||
for (let j = 0; j < n; j++) {
|
||
const i = this.moveBuf[j];
|
||
this.make(i, me);
|
||
const v = -this.search(3 - me, depth - 1, -INF, INF, false, 1);
|
||
this.unmake(i, me);
|
||
if (this.abort) return null;
|
||
out.push({ i, score: v });
|
||
}
|
||
out.sort((a, b) => b.score - a.score);
|
||
return out;
|
||
}
|
||
|
||
/** Iterative-deepening alpha-beta at the root. */
|
||
think(me, { ms, maxDepth, exact = false }) {
|
||
this.abort = false; this.nodes = 0; this.deadline = Date.now() + ms;
|
||
let rootMoves = [];
|
||
{
|
||
const n = this.gen(me, 0);
|
||
for (let j = 0; j < n; j++) rootMoves.push({ i: this.moveBuf[j], score: 0 });
|
||
}
|
||
if (!rootMoves.length) return null;
|
||
let result = { i: rootMoves[0].i, score: 0, depth: 0 };
|
||
for (let d = 1; d <= maxDepth; d++) {
|
||
let alpha = -INF, best = null;
|
||
const scored = [];
|
||
for (let j = 0; j < rootMoves.length; j++) {
|
||
const m = rootMoves[j];
|
||
this.make(m.i, me);
|
||
let v;
|
||
if (j === 0) v = -this.search(3 - me, d - 1, -INF, -alpha, false, 1);
|
||
else {
|
||
v = -this.search(3 - me, d - 1, -alpha - 1, -alpha, false, 1);
|
||
if (v > alpha && !this.abort) v = -this.search(3 - me, d - 1, -INF, -alpha, false, 1);
|
||
}
|
||
this.unmake(m.i, me);
|
||
if (this.abort) break;
|
||
scored.push({ i: m.i, score: v });
|
||
if (v > alpha) { alpha = v; best = { i: m.i, score: v, depth: d }; }
|
||
}
|
||
if (this.abort) {
|
||
// a first move that already beat the last iteration's choice is safe to keep
|
||
// (rootMoves[0] is last iteration's choice; anything in `best` beat it at this depth)
|
||
if (best && best.i !== result.i) result = best;
|
||
break;
|
||
}
|
||
result = best;
|
||
// re-order: best first, then by this iteration's scores (fail-low bounds)
|
||
const seen = new Map(scored.map((s) => [s.i, s.score]));
|
||
rootMoves = rootMoves.map((m) => ({ i: m.i, score: m.i === best.i ? INF : (seen.get(m.i) ?? -INF) }))
|
||
.sort((a, b) => b.score - a.score);
|
||
if (!exact && Math.abs(best.score) >= WIN) break; // a forced result: deeper won't change it
|
||
if (d >= this.ne) break; // reached the end of the game
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/** Exact solve; null if it ran out of time. */
|
||
solve(me, ms) {
|
||
this.abort = false; this.nodes = 0; this.deadline = Date.now() + ms;
|
||
const r = this.think(me, { ms, maxDepth: this.ne, exact: true });
|
||
if (!r || this.abort || r.depth < this.ne) { this.abort = false; return null; }
|
||
return r;
|
||
}
|
||
|
||
/** Every move scored, deepening until the time runs out. */
|
||
rankAll(me, { depth, ms }) {
|
||
this.abort = false; this.nodes = 0; this.deadline = Date.now() + ms;
|
||
let last = null;
|
||
for (let d = 1; d <= depth; d++) {
|
||
const r = this.rankAt(me, d);
|
||
if (!r) break;
|
||
last = r;
|
||
if (d >= this.ne) break;
|
||
}
|
||
this.abort = false;
|
||
return last ?? (() => {
|
||
// not even depth 1 finished (shouldn't happen): fall back to static order
|
||
const n = this.gen(me, 0); const out = [];
|
||
for (let j = 0; j < n; j++) out.push({ i: this.moveBuf[j], score: this.w[this.moveBuf[j]] });
|
||
return out.sort((a, b) => b.score - a.score);
|
||
})();
|
||
}
|
||
}
|
||
|
||
const searchers = new Map();
|
||
function searcherFor(size, variant) {
|
||
const key = `${size}|${variant}`;
|
||
if (!searchers.has(key)) searchers.set(key, new Searcher(size, variant));
|
||
return searchers.get(key);
|
||
}
|
||
|
||
function setup(pos) {
|
||
const s = searcherFor(pos.size, pos.variant ?? 'standard');
|
||
const me = s.load(pos.board, pos.turn);
|
||
s.clearTT();
|
||
return { s, me };
|
||
}
|
||
|
||
/** Best move with exact solving near the end. */
|
||
function deepBest(s, me, { ms, maxDepth, solve, solveMs }) {
|
||
if (solve && s.ne <= solve) {
|
||
const r = s.solve(me, solveMs);
|
||
if (r) return { i: r.i, score: r.score, exact: true, depth: r.depth };
|
||
s.clearTT();
|
||
}
|
||
const r = s.think(me, { ms, maxDepth });
|
||
return r ? { i: r.i, score: r.score, exact: false, depth: r.depth } : null;
|
||
}
|
||
|
||
export function rankMoves(pos, { depth = 4, ms = 300 } = {}) {
|
||
const { s, me } = setup(pos);
|
||
return s.rankAll(me, { depth, ms }).map((r) => ({ sq: s.sqOf[r.i], score: r.score }));
|
||
}
|
||
|
||
export function hint(pos, { ms = 700, solve = 14, solveMs = 2200 } = {}) {
|
||
const { s, me } = setup(pos);
|
||
const r = deepBest(s, me, { ms, maxDepth: 30, solve, solveMs });
|
||
return r ? { sq: s.sqOf[r.i], score: r.score, exact: r.exact, depth: r.depth } : null;
|
||
}
|
||
|
||
export function chooseMove(pos, skill, { line = null, rnd = Math.random } = {}) {
|
||
const prof = profileFor(skill);
|
||
const legal = movesFor(pos.board, pos.size, pos.turn);
|
||
if (!legal.length) return null;
|
||
if (legal.length === 1) return { sq: legal[0].sq, score: 0, book: false, exact: false };
|
||
// book
|
||
if (line && pos.size === 8 && (pos.variant ?? 'standard') === 'standard' && rnd() < prof.book) {
|
||
const replies = bookReplies(line).map((n) => parseSq(n, 8)).filter((sq) => legal.some((m) => m.sq === sq));
|
||
if (replies.length) return { sq: replies[Math.floor(rnd() * replies.length)], score: 0, book: true, exact: false };
|
||
}
|
||
const { s, me } = setup(pos);
|
||
// perfect endgame
|
||
if (prof.solve && s.ne <= prof.solve) {
|
||
const r = s.solve(me, prof.solveMs);
|
||
if (r) return { sq: s.sqOf[r.i], score: r.score, book: false, exact: true };
|
||
s.clearTT();
|
||
}
|
||
if (prof.blunder && rnd() < prof.blunder) {
|
||
const m = legal[Math.floor(rnd() * legal.length)];
|
||
return { sq: m.sq, score: 0, book: false, exact: false };
|
||
}
|
||
if (!prof.noise && prof.style === 'sound') {
|
||
const r = s.think(me, { ms: prof.ms, maxDepth: prof.depth });
|
||
return { sq: s.sqOf[r.i], score: r.score, book: false, exact: false };
|
||
}
|
||
const ranked = s.rankAll(me, { depth: prof.depth, ms: prof.ms });
|
||
let best = null, bestV = -INF;
|
||
for (const r of ranked) {
|
||
const sq = s.sqOf[r.i];
|
||
let v = r.score + (rnd() * 2 - 1) * prof.noise;
|
||
if (prof.style === 'greedy') v += flipsFor(pos.board, pos.size, sq, pos.turn).length * 40;
|
||
else if (prof.style === 'edgy' && isEdge(sq, pos.size) && cCorner(sq, pos.size) < 0) v += 70;
|
||
if (Math.abs(r.score) >= WIN) v = r.score; // never throw away a forced result
|
||
if (v > bestV) { bestV = v; best = { sq, score: r.score }; }
|
||
}
|
||
return { ...best, book: false, exact: false };
|
||
}
|
||
|
||
/**
|
||
* Post-game review. positions: [{ i, board, turn, played }] (the human's
|
||
* decisions). Returns each with the best move and the loss in hundredths of
|
||
* a disc (0 when the move played was best).
|
||
*/
|
||
export function review(positions, { ms = 140, depth = 6, size, variant } = {}) {
|
||
const out = [];
|
||
for (const p of positions) {
|
||
const pos = { size, variant, board: p.board, turn: p.turn };
|
||
const legal = movesFor(p.board, size, p.turn);
|
||
if (legal.length < 2) continue;
|
||
const { s, me } = setup(pos);
|
||
let ranked = null, exact = false;
|
||
if (s.ne <= 12) {
|
||
s.abort = false; s.nodes = 0; s.deadline = Date.now() + ms * 4;
|
||
const r = s.rankAt(me, s.ne);
|
||
s.abort = false;
|
||
if (r) { ranked = r; exact = true; }
|
||
}
|
||
if (!ranked) ranked = s.rankAll(me, { depth, ms });
|
||
const best = ranked[0];
|
||
const mine = ranked.find((r) => s.sqOf[r.i] === p.played);
|
||
if (!best || !mine) continue;
|
||
out.push({ i: p.i, best: s.sqOf[best.i], played: p.played, loss: best.score - mine.score, bestScore: best.score, playedScore: mine.score, exact });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// ── words for the Master ───────────────────────────────────────────────────
|
||
|
||
function after(pos, sq) {
|
||
const b = pos.board.slice();
|
||
const f = flipsFor(b, pos.size, sq, pos.turn);
|
||
b[sq] = pos.turn;
|
||
for (const x of f) b[x] = pos.turn;
|
||
return { board: b, flips: f };
|
||
}
|
||
|
||
function cornersOpenTo(board, size, color) {
|
||
return movesFor(board, size, color).filter((m) => isCorner(m.sq, size)).length;
|
||
}
|
||
|
||
export function exactMargin(score) {
|
||
if (score >= WIN) return Math.round((score - WIN) / 10);
|
||
if (score <= -WIN) return Math.round((score + WIN) / 10);
|
||
return 0;
|
||
}
|
||
|
||
/** A short verb phrase for why sq is good ("takes a corner"). */
|
||
export function describeIdea(pos, sq, res = {}) {
|
||
const anti = pos.variant === 'anti';
|
||
const opp = other(pos.turn);
|
||
if (res.exact) {
|
||
const m = exactMargin(res.score);
|
||
if (res.score >= WIN) return `wins by ${m} disc${m === 1 ? '' : 's'} with perfect play from here`;
|
||
if (res.score === 0) return 'holds a draw with perfect play';
|
||
return `keeps the loss to ${-m} disc${m === -1 ? '' : 's'}, the best that's left`;
|
||
}
|
||
const { board, flips } = after(pos, sq);
|
||
const theirMoves = movesFor(board, pos.size, opp);
|
||
const om = theirMoves.length;
|
||
if (!anti && isCorner(sq, pos.size)) return 'takes a corner, and a corner can never be flipped back';
|
||
if (om === 0) return 'leaves them no move at all, so they have to pass';
|
||
const before = cornersOpenTo(pos.board, pos.size, opp);
|
||
const nowOpen = theirMoves.filter((m) => isCorner(m.sq, pos.size)).length;
|
||
if (!anti && before > 0 && nowOpen === 0) return 'takes away the corner they were threatening';
|
||
if (om <= 3) return `leaves them only ${om} move${om === 1 ? '' : 's'}`;
|
||
if (anti) {
|
||
if (flips.length <= 2) return `turns over just ${flips.length} disc${flips.length === 1 ? '' : 's'}, which keeps your count low`;
|
||
return 'keeps you off the corners and edges for now';
|
||
}
|
||
if (flips.length <= 2 && !isEdge(sq, pos.size)) return `is a quiet move: it flips only ${flips.length} disc${flips.length === 1 ? '' : 's'} and opens nothing up for them`;
|
||
if (isEdge(sq, pos.size) && cCorner(sq, pos.size) < 0) return 'takes a safe edge square';
|
||
return `keeps your options open and limits theirs to ${om}`;
|
||
}
|
||
|
||
/** What was wrong with `played` compared with `best` (past tense). */
|
||
export function describeMistake(pos, played, best) {
|
||
const opp = other(pos.turn);
|
||
const anti = pos.variant === 'anti';
|
||
const a = after(pos, played).board, b = after(pos, best).board;
|
||
if (!anti) {
|
||
const ca = cornersOpenTo(a, pos.size, opp), cb = cornersOpenTo(b, pos.size, opp);
|
||
if (ca > cb) return 'it gave them a corner';
|
||
const xc = xCorner(played, pos.size);
|
||
if (xc >= 0 && pos.board[xc] === null) return 'it took an X-square next to an empty corner';
|
||
} else if (isCorner(played, pos.size)) return 'it took a corner, and in Anti-Othello that disc is yours forever';
|
||
const ma = movesFor(a, pos.size, opp).length, mb = movesFor(b, pos.size, opp).length;
|
||
if (ma - mb >= 3) return `it gave them ${ma} replies instead of ${mb}`;
|
||
const fa = flipsFor(pos.board, pos.size, played, pos.turn).length, fb = flipsFor(pos.board, pos.size, best, pos.turn).length;
|
||
if (!anti && fa - fb >= 4) return `it grabbed ${fa} discs, and big flips open doors for the other side`;
|
||
return 'it let them take the initiative';
|
||
}
|
||
|
||
/** Does playing sq let the opponent into a corner they couldn't reach before? */
|
||
export function givesCorner(pos, sq) {
|
||
if (pos.variant === 'anti') return false;
|
||
const opp = other(pos.turn);
|
||
const before = cornersOpenTo(pos.board, pos.size, opp);
|
||
const nowOpen = cornersOpenTo(after(pos, sq).board, pos.size, opp);
|
||
return nowOpen > before;
|
||
}
|
||
|
||
|
||
// ── for tools/verifyOthello.js ─────────────────────────────────────────────
|
||
|
||
/** Perft on the engine's own make/unmake (a pass counts as a move). */
|
||
export function perft(pos, depth) {
|
||
const { s, me } = setup(pos);
|
||
const walk = (side, d, passed, ply) => {
|
||
if (d === 0) return 1;
|
||
const n = s.gen(side, ply);
|
||
if (n === 0) {
|
||
if (passed) return 1;
|
||
s.pass();
|
||
const v = walk(3 - side, d - 1, true, ply + 1);
|
||
s.pass();
|
||
return v;
|
||
}
|
||
let total = 0;
|
||
const base = ply * s.N;
|
||
for (let j = 0; j < n; j++) {
|
||
const i = s.moveBuf[base + j];
|
||
s.make(i, side);
|
||
total += walk(3 - side, d - 1, false, ply + 1);
|
||
s.unmake(i, side);
|
||
}
|
||
return total;
|
||
};
|
||
return walk(me, depth, false, 0);
|
||
}
|
||
|
||
/** The engine's view of a position: legal squares, and the board after each. */
|
||
export function engineView(pos) {
|
||
const { s, me } = setup(pos);
|
||
const n = s.gen(me, 0);
|
||
const out = [];
|
||
const lo = s.hLo, hi = s.hHi;
|
||
for (let j = 0; j < n; j++) {
|
||
const i = s.moveBuf[j];
|
||
s.make(i, me);
|
||
const board = [];
|
||
for (let q = 0; q < s.N; q++) { const v = s.b[s.cells[q]]; board.push(v === 1 ? 'black' : v === 2 ? 'white' : null); }
|
||
s.unmake(i, me);
|
||
out.push({ sq: s.sqOf[i], board });
|
||
}
|
||
return { moves: out.sort((a, b) => a.sq - b.sq), hashRestored: s.hLo === lo && s.hHi === hi };
|
||
}
|
||
|
||
/** Exact solve score (null on timeout). */
|
||
export function solveExact(pos, ms = 5000) {
|
||
const { s, me } = setup(pos);
|
||
if (!s.gen(me, 0)) return null;
|
||
const r = s.solve(me, ms);
|
||
return r ? { sq: s.sqOf[r.i], score: r.score } : null;
|
||
}
|