363 lines
18 KiB
JavaScript
363 lines
18 KiB
JavaScript
#!/usr/bin/env node
|
||
// verifyOthello.js: headless checks for Othello ("Kissa Kuro-Shiro"):
|
||
// • perft from the start position (published counts), on both the rules
|
||
// module and the engine's make/unmake, for 6×6, 8×8 and 10×10
|
||
// • the engine agrees with OthelloLogic on legal moves and resulting boards
|
||
// across thousands of random positions; Zobrist hash restored
|
||
// • rules: passes recorded, game end, wipeout, Anti-Othello winner, stable
|
||
// discs, the disc supply, notation round-trip, replay (boardAfter)
|
||
// • the book: every line legal; names found in all four orientations;
|
||
// replies mapped back correctly; opening card lines play out
|
||
// • the endgame solver matches brute-force minimax on small positions
|
||
// • skills: each moves legally inside its time budget; the ladder holds
|
||
// (stronger beats weaker over mirrored pairs of games)
|
||
// • describeIdea / describeMistake / review produce sensible output
|
||
// • layout: HUD rectangles on screen and clear of the board and each other
|
||
// Usage: node tools/verifyOthello.js [--quick]
|
||
|
||
import * as L from '../src/games/othello/OthelloLogic.js';
|
||
import * as AI from '../src/games/othello/OthelloAI.js';
|
||
import { LINES, openingName, bookReplies, openingCard } from '../src/games/othello/OthelloBook.js';
|
||
import { handle } from '../src/games/othello/OthelloEngine.js';
|
||
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
||
|
||
const QUICK = process.argv.includes('--quick');
|
||
let pass = 0, fail = 0;
|
||
function ok(label, cond, detail = '') {
|
||
if (cond) pass++;
|
||
else { console.error(` ✗ ${label}${detail ? ` (${detail})` : ''}`); fail++; }
|
||
}
|
||
const section = (n) => console.log(`\n${n}`);
|
||
const posOf = (gs) => ({ size: gs.size, variant: gs.variant, board: gs.board, turn: gs.turn });
|
||
|
||
// ── perft ────────────────────────────────────────────────────────────────────
|
||
section('perft');
|
||
function perftLogic(board, size, turn, d, passed = false) {
|
||
if (d === 0) return 1;
|
||
const moves = L.movesFor(board, size, turn);
|
||
if (!moves.length) {
|
||
if (passed) return 1;
|
||
return perftLogic(board, size, L.other(turn), d - 1, true);
|
||
}
|
||
let t = 0;
|
||
for (const m of moves) {
|
||
const b = board.slice();
|
||
b[m.sq] = turn;
|
||
for (const f of m.flips) b[f] = turn;
|
||
t += perftLogic(b, size, L.other(turn), d - 1, false);
|
||
}
|
||
return t;
|
||
}
|
||
{
|
||
const EXP8 = [4, 12, 56, 244, 1396, 8200, 55092, 390216, 3005288];
|
||
const g = L.createGame({ size: 8 });
|
||
const dl = QUICK ? 6 : 8, de = QUICK ? 7 : 9;
|
||
for (let d = 1; d <= dl; d++) ok(`logic perft 8×8 d${d}`, perftLogic(g.board, 8, L.BLACK, d) === EXP8[d - 1]);
|
||
for (let d = 1; d <= de; d++) {
|
||
const n = AI.perft(posOf(g), d);
|
||
ok(`engine perft 8×8 d${d}`, n === EXP8[d - 1], `${n} ≠ ${EXP8[d - 1]}`);
|
||
}
|
||
for (const size of [6, 10]) {
|
||
const gg = L.createGame({ size });
|
||
for (let d = 1; d <= 6; d++) {
|
||
const a = perftLogic(gg.board, size, L.BLACK, d), b = AI.perft(posOf(gg), d);
|
||
ok(`perft ${size}×${size} d${d}: logic = engine`, a === b, `${a} vs ${b}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ── engine vs rules on random positions ──────────────────────────────────────
|
||
section('engine agrees with the rules');
|
||
{
|
||
const rnd = mulberry32(7);
|
||
let positions = 0, mismatches = 0, hashBad = 0;
|
||
const games = QUICK ? 40 : 160;
|
||
for (const size of [6, 8, 10]) {
|
||
for (let gi = 0; gi < games / 2; gi++) {
|
||
let gs = L.createGame({ size, variant: gi % 2 ? 'anti' : 'standard' });
|
||
while (gs.phase === 'playing') {
|
||
const legal = L.legalMoves(gs);
|
||
const view = AI.engineView(posOf(gs));
|
||
positions++;
|
||
if (!view.hashRestored) hashBad++;
|
||
const a = legal.map((m) => m.sq).sort((x, y) => x - y), b = view.moves.map((m) => m.sq);
|
||
if (a.join() !== b.join()) mismatches++;
|
||
else {
|
||
for (const m of view.moves) {
|
||
const ref = L.applyMove(gs, m.sq).board;
|
||
if (ref.join() !== m.board.join()) { mismatches++; break; }
|
||
}
|
||
}
|
||
gs = L.applyMove(gs, legal[Math.floor(rnd() * legal.length)].sq);
|
||
}
|
||
}
|
||
}
|
||
ok(`legal moves and boards match on ${positions} positions`, mismatches === 0, `${mismatches} mismatches`);
|
||
ok('hash restored after every make/unmake', hashBad === 0, `${hashBad}`);
|
||
}
|
||
|
||
// ── rules ────────────────────────────────────────────────────────────────────
|
||
section('rules');
|
||
{
|
||
const g = L.createGame({ size: 8 });
|
||
ok('start: black to move, 4 legal', g.turn === 'black' && L.legalMoves(g).length === 4);
|
||
ok('f5 is legal first move', L.legalMoves(g).some((m) => L.notate(m.sq, 8) === 'f5'));
|
||
for (let sq = 0; sq < 64; sq++) ok(`notation round-trip ${sq}`, L.parseSq(L.notate(sq, 8), 8) === sq);
|
||
ok('notation a1 top-left, h8 bottom-right', L.notate(0, 8) === 'a1' && L.notate(63, 8) === 'h8');
|
||
ok('10×10 notation j10', L.notate(99, 10) === 'j10' && L.parseSq('j10', 10) === 99);
|
||
let w = L.createGame({ size: 8 });
|
||
for (const n of ['f5', 'f6', 'e6', 'f4', 'e3', 'c5', 'g5', 'g3', 'g4', 'f3', 'd6', 'e7', 'd3', 'e2', 'f2', 'c4']) {
|
||
if (w.phase !== 'playing') break;
|
||
const sq = L.parseSq(n, 8);
|
||
if (!L.legalMoves(w).some((m) => m.sq === sq)) break;
|
||
w = L.applyMove(w, sq);
|
||
}
|
||
ok('random line plays without errors', w.history.length > 0);
|
||
// a hand-built pass position: white has no move, black does
|
||
{
|
||
const b = Array(64).fill(null);
|
||
b[0] = 'black'; b[1] = 'white'; b[9] = 'white';
|
||
// black at a1, white b1 & b2; black to move can play c1 (flips b1) or c3 (flips b2)
|
||
const gs = { ...L.createGame({ size: 8 }), board: b, start: b.slice() };
|
||
const after = L.applyMove(gs, L.parseSq('c1', 8));
|
||
// now white has b2 only; white cannot move (needs black beyond) → pass recorded or game over
|
||
ok('pass or end handled after a move', after.history.length >= 1);
|
||
const last = after.history[after.history.length - 1];
|
||
ok('white has no reply: a pass is recorded and black moves again', last.pass && last.color === 'white' && after.turn === 'black');
|
||
}
|
||
// a full board ends the game; anti flips the winner
|
||
{
|
||
const b = Array(64).fill('black'); b[63] = null; b[62] = 'white';
|
||
const gs = { ...L.createGame({ size: 8 }), board: b, start: b.slice() };
|
||
const legal = L.legalMoves(gs);
|
||
ok('one move left for black', legal.length === 1 && legal[0].sq === 63);
|
||
const end = L.applyMove(gs, 63);
|
||
ok('board full → game over, black wins', end.phase === 'game_over' && end.winner === 'black' && end.endReason === 'wipeout');
|
||
const anti = L.applyMove({ ...gs, variant: 'anti' }, 63);
|
||
ok('Anti-Othello: same board, white wins', anti.winner === 'white');
|
||
}
|
||
// stable discs
|
||
{
|
||
const b = Array(64).fill(null);
|
||
b[0] = 'black'; b[1] = 'black'; b[8] = 'black'; b[27] = 'white';
|
||
const st = L.stableDiscs(b, 8);
|
||
ok('corner + edge-run discs are stable', st.includes(0) && st.includes(1) && st.includes(8));
|
||
ok('a centre disc is not stable', !st.includes(27));
|
||
const full = Array(64).fill('white');
|
||
ok('full board: everything stable', L.stableDiscs(full, 8).length === 64);
|
||
}
|
||
// supply
|
||
{
|
||
const g2 = L.applyMove(L.createGame({ size: 8 }), L.parseSq('f5', 8));
|
||
const s = L.supply(g2);
|
||
ok('supply 30 each, black 29 after one move', s.each === 30 && s.black === 29 && s.white === 30);
|
||
}
|
||
// replay
|
||
{
|
||
const rnd = mulberry32(3);
|
||
let gs = L.createGame({ size: 8 });
|
||
while (gs.phase === 'playing') { const m = L.legalMoves(gs); gs = L.applyMove(gs, m[Math.floor(rnd() * m.length)].sq); }
|
||
ok('boardAfter(all) = final board', L.boardAfter(gs, gs.history.length).join() === gs.board.join());
|
||
const tr = L.discTrace(gs);
|
||
const c = L.counts(gs);
|
||
ok('disc trace ends at the final difference', tr[tr.length - 1] === c.black - c.white && tr.length === gs.history.length + 1);
|
||
ok('resign', L.resign(gs, 'black').winner === 'white');
|
||
}
|
||
}
|
||
|
||
// ── book ─────────────────────────────────────────────────────────────────────
|
||
section('book');
|
||
{
|
||
for (const l of LINES) {
|
||
let gs = L.createGame({ size: 8 });
|
||
let legal = true;
|
||
for (const n of l.list) {
|
||
const sq = L.parseSq(n, 8);
|
||
if (gs.phase !== 'playing' || !L.legalMoves(gs).some((m) => m.sq === sq)) { legal = false; break; }
|
||
gs = L.applyMove(gs, sq);
|
||
}
|
||
ok(`book line legal: ${l.name}`, legal);
|
||
ok(`openingName finds ${l.name}`, openingName(l.list) === l.name, openingName(l.list));
|
||
}
|
||
const rnd = mulberry32(11);
|
||
for (let i = 0; i < 40; i++) {
|
||
const card = openingCard(rnd);
|
||
let gs = L.createGame({ size: 8 });
|
||
let legal = true;
|
||
for (const n of card.moves) {
|
||
const sq = L.parseSq(n, 8);
|
||
if (!L.legalMoves(gs).some((m) => m.sq === sq)) { legal = false; break; }
|
||
gs = L.applyMove(gs, sq, { book: true });
|
||
}
|
||
ok(`opening card ${card.name} (${card.moves[0]}) plays out`, legal);
|
||
ok(`mirrored card still named ${card.name}`, openingName(card.moves) === card.name, openingName(card.moves));
|
||
}
|
||
ok('replies from the start are the four first moves', bookReplies([]).length === 4);
|
||
ok('after f5 the book knows d6, f6, f4', ['d6', 'f6', 'f4'].every((m) => bookReplies(['f5']).includes(m)));
|
||
ok('after c4 the replies are mirrored (c3 = d6 mirrored)', bookReplies(['c4']).includes('e3'));
|
||
ok('unknown line → no replies', bookReplies(['f5', 'd6', 'c3', 'd3', 'c4', 'f4', 'c5', 'b3', 'c2', 'a1']).length === 0);
|
||
}
|
||
|
||
// ── endgame solver vs brute force ────────────────────────────────────────────
|
||
section('endgame solver');
|
||
function brute(board, size, turn, variant, passed = false) {
|
||
const moves = L.movesFor(board, size, turn);
|
||
if (!moves.length) {
|
||
if (passed) {
|
||
const c = L.countsOf(board);
|
||
let d = turn === 'black' ? c.black - c.white : c.white - c.black;
|
||
if (variant === 'anti') d = -d;
|
||
return d > 0 ? AI.WIN + d * 10 : d < 0 ? -AI.WIN + d * 10 : 0;
|
||
}
|
||
return -brute(board, size, L.other(turn), variant, true);
|
||
}
|
||
let best = -Infinity;
|
||
for (const m of moves) {
|
||
const b = board.slice(); b[m.sq] = turn; for (const f of m.flips) b[f] = turn;
|
||
best = Math.max(best, -brute(b, size, L.other(turn), variant, false));
|
||
}
|
||
return best;
|
||
}
|
||
{
|
||
const rnd = mulberry32(99);
|
||
const N = QUICK ? 12 : 40;
|
||
let tested = 0;
|
||
for (let i = 0; i < N * 3 && tested < N; i++) {
|
||
const size = i % 3 === 0 ? 6 : 8;
|
||
const variant = i % 4 === 3 ? 'anti' : 'standard';
|
||
let gs = L.createGame({ size, variant });
|
||
const stopAt = 7 + Math.floor(rnd() * 3);
|
||
while (gs.phase === 'playing' && L.counts(gs).empty > stopAt) { const m = L.legalMoves(gs); gs = L.applyMove(gs, m[Math.floor(rnd() * m.length)].sq); }
|
||
if (gs.phase !== 'playing') continue;
|
||
tested++;
|
||
const ref = brute(gs.board, size, gs.turn, variant);
|
||
const got = AI.solveExact(posOf(gs));
|
||
ok(`solve ${size}×${size} ${variant} (${L.counts(gs).empty} empty)`, got && got.score === ref, `${got?.score} vs ${ref}`);
|
||
// the solver's move really achieves that score
|
||
if (got) {
|
||
const after = L.applyMove(gs, got.sq);
|
||
const v = after.phase === 'game_over'
|
||
? (() => { const c = L.counts(after); let d = gs.turn === 'black' ? c.black - c.white : c.white - c.black; if (variant === 'anti') d = -d; return d > 0 ? AI.WIN + d * 10 : d < 0 ? -AI.WIN + d * 10 : 0; })()
|
||
: (after.turn === gs.turn ? brute(after.board, size, after.turn, variant) : -brute(after.board, size, after.turn, variant));
|
||
ok(' …and its move achieves it', v === ref, `${v} vs ${ref}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ── skills: legality, timing, ladder ─────────────────────────────────────────
|
||
section('skills');
|
||
function playGame(skillBlack, skillWhite, { size = 8, variant = 'standard', rnd, timing } = {}) {
|
||
let gs = L.createGame({ size, variant });
|
||
const line = [];
|
||
while (gs.phase === 'playing') {
|
||
const skill = gs.turn === 'black' ? skillBlack : skillWhite;
|
||
const t0 = Date.now();
|
||
const r = AI.chooseMove(posOf(gs), skill, { line: line.slice(), rnd });
|
||
const dt = Date.now() - t0;
|
||
timing?.(skill, dt, L.counts(gs).empty);
|
||
if (!r || !L.legalMoves(gs).some((m) => m.sq === r.sq)) return { error: true, gs };
|
||
line.push(L.notate(r.sq, size));
|
||
gs = L.applyMove(gs, r.sq);
|
||
}
|
||
return { gs };
|
||
}
|
||
{
|
||
const rnd = mulberry32(5);
|
||
const worst = {};
|
||
const timing = (skill, dt) => { worst[skill] = Math.max(worst[skill] ?? 0, dt); };
|
||
for (const size of [6, 8, 10]) {
|
||
for (const skill of [1, 2, 3, 4, 5]) {
|
||
if (QUICK && size !== 8 && skill > 3) continue;
|
||
const r = playGame(skill, 3, { size, rnd, timing });
|
||
ok(`skill ${skill} on ${size}×${size}: legal game to the end`, !r.error);
|
||
}
|
||
}
|
||
const BUDGET = { 1: 300, 2: 500, 3: 1100, 4: 2200, 5: 4500 };
|
||
for (const [s, t] of Object.entries(worst)) ok(`skill ${s} worst think ${t} ms within ${BUDGET[s]} ms`, t <= BUDGET[s]);
|
||
console.log(' worst think times (ms):', worst);
|
||
|
||
const ladder = QUICK ? [[1, 3, 4], [3, 5, 2]] : [[1, 3, 6], [2, 4, 6], [3, 5, 4], [1, 5, 4]];
|
||
for (const [lo, hi, pairs] of ladder) {
|
||
let hiScore = 0, games = 0;
|
||
for (let p = 0; p < pairs; p++) {
|
||
for (const hiBlack of [true, false]) {
|
||
const r = playGame(hiBlack ? hi : lo, hiBlack ? lo : hi, { rnd });
|
||
const w = r.gs.winner;
|
||
const hiColor = hiBlack ? 'black' : 'white';
|
||
hiScore += w === 'draw' ? 0.5 : w === hiColor ? 1 : 0;
|
||
games++;
|
||
}
|
||
}
|
||
console.log(` skill ${hi} vs ${lo}: ${hiScore}/${games}`);
|
||
ok(`skill ${hi} beats skill ${lo} most of the time`, hiScore / games >= 0.7, `${hiScore}/${games}`);
|
||
}
|
||
}
|
||
|
||
// ── coach words, review, worker handler ──────────────────────────────────────
|
||
section('coach & review');
|
||
{
|
||
// corner available → describeIdea says so
|
||
const b = Array(64).fill(null);
|
||
b[9] = 'white'; b[18] = 'black'; b[27] = 'black';
|
||
const pos = { size: 8, variant: 'standard', board: b, turn: 'black' };
|
||
ok('a1 legal here', L.flipsFor(b, 8, 0, 'black').length === 1);
|
||
ok('describeIdea: corner', /corner/.test(AI.describeIdea(pos, 0, {})));
|
||
ok('describeIdea: exact win', /wins by 4 discs/.test(AI.describeIdea(pos, 0, { exact: true, score: AI.WIN + 40 })));
|
||
const g = L.applyMove(L.createGame({ size: 8 }), L.parseSq('f5', 8));
|
||
const h = handle('hint', { pos: posOf(g), ms: 200 });
|
||
ok('worker hint returns a legal move', h && L.legalMoves(g).some((m) => m.sq === h.sq));
|
||
const r = handle('rank', { pos: posOf(g), depth: 3, ms: 200 });
|
||
ok('worker rank lists every move', r.length === L.legalMoves(g).length);
|
||
const mv = handle('move', { pos: posOf(g), skill: 5, line: ['f5'] });
|
||
ok('skill 5 plays from the book after f5', mv.book && ['d6', 'f6', 'f4'].includes(L.notate(mv.sq, 8)));
|
||
// review: replay a game and review black's decisions
|
||
const rnd = mulberry32(21);
|
||
let gs = L.createGame({ size: 8 });
|
||
const positions = [];
|
||
while (gs.phase === 'playing') {
|
||
const m = L.legalMoves(gs);
|
||
const pick = m[Math.floor(rnd() * m.length)].sq;
|
||
if (gs.turn === 'black') positions.push({ i: gs.history.length, board: gs.board.slice(), turn: 'black', played: pick });
|
||
gs = L.applyMove(gs, pick);
|
||
}
|
||
const t0 = Date.now();
|
||
const rev = handle('review', { size: 8, variant: 'standard', positions, ms: 60 });
|
||
ok(`review of ${positions.length} moves in ${Date.now() - t0} ms`, Array.isArray(rev) && rev.length > 0 && Date.now() - t0 < 15000);
|
||
ok('review losses are ≥ 0', rev.every((x) => x.loss >= 0));
|
||
const worst = rev.slice().sort((a, b2) => b2.loss - a.loss)[0];
|
||
const at = positions.find((p) => p.i === worst.i);
|
||
const why = AI.describeMistake({ size: 8, variant: 'standard', board: at.board, turn: 'black' }, worst.played, worst.best);
|
||
ok('describeMistake gives words', typeof why === 'string' && why.length > 5, why);
|
||
console.log(` worst random move: ${L.notate(worst.played, 8)} (best ${L.notate(worst.best, 8)}): ${why}`);
|
||
}
|
||
|
||
// ── layout ───────────────────────────────────────────────────────────────────
|
||
section('layout');
|
||
try {
|
||
const LY = await import('../src/games/othello/OthelloLayout.js');
|
||
const R = LY.HUD_RECTS();
|
||
const board = LY.BOARD_RECT;
|
||
const inter = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
||
for (const [k, r] of Object.entries(R)) {
|
||
ok(`${k} on screen`, r.x >= 0 && r.y >= 0 && r.x + r.w <= LY.W && r.y + r.h <= LY.H, JSON.stringify(r));
|
||
ok(`${k} clear of the board`, !inter(r, board));
|
||
}
|
||
const keys = Object.keys(R);
|
||
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) {
|
||
ok(`${keys[i]} clear of ${keys[j]}`, !inter(R[keys[i]], R[keys[j]]));
|
||
}
|
||
for (const size of [6, 8, 10]) {
|
||
const g = LY.geom(size);
|
||
for (let sq = 0; sq < size * size; sq++) {
|
||
const { x, y } = LY.squareXY(sq, size);
|
||
if (LY.cellAt(x, y, size) !== sq) { ok(`cellAt(squareXY) ${size}×${size} sq ${sq}`, false); break; }
|
||
}
|
||
ok(`${size}×${size} board fills the felt`, Math.abs(g.SQ * size - LY.BOARD) < 1e-6);
|
||
}
|
||
} catch (e) {
|
||
ok('layout module loads', false, e.message);
|
||
}
|
||
|
||
console.log(`\n${pass} passed, ${fail} failed`);
|
||
process.exit(fail ? 1 : 0);
|