fertig-classic-games/tools/verifyChess.js

366 lines
20 KiB
JavaScript

#!/usr/bin/env node
// verifyChess.js — headless checks for Chess ("The Stone Tables"):
// • perft: the standard start, Kiwipete and the usual tricky positions,
// plus Chess960 positions — node counts must match the published numbers
// • rules on hand-built positions: castling rights, en passant (incl. the
// pinned-pawn case), promotion, stalemate, insufficient material,
// threefold repetition, the fifty-move rule, flag-fall material
// • Chess960: all 960 starts are valid; castling lands king/rook correctly
// • notation: SAN / UCI round-trip for every legal move of many positions,
// FEN round-trip, PGN export
// • the opening book: every line + name is legal; names resolve
// • puzzles: every puzzle replays legally; the first solving move is the
// engine's clear choice; daily puzzle is deterministic; ladder + rating
// • the engine: each skill moves legally inside its budget; finds mates;
// SEE and describeIdea sanity; the worker message handler
// • self-play soak: games end cleanly; skill ladder (mirrored colours)
// • layout: HUD rectangles on screen and clear of the board and each other
// Usage: node tools/verifyChess.js [--quick]
import * as L from '../src/games/chess/ChessLogic.js';
import * as AI from '../src/games/chess/ChessAI.js';
import { checkBook, openingName, bookMoves } from '../src/games/chess/ChessBook.js';
import { PUZZLES, dailyPuzzle, nextLadderPuzzle, ratePuzzle, dailyStreak, dateKey } from '../src/games/chess/ChessPuzzles.js';
import { handle } from '../src/games/chess/ChessEngine.js';
import * as LY from '../src/games/chess/ChessLayout.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 sans = (g) => g.moves().map((m) => m.san).sort();
// ── perft ────────────────────────────────────────────────────────────────────
section('perft');
const PERFT = [
['start', L.START_FEN, [20, 400, 8902, 197281, 4865609]],
['kiwipete', 'r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1', [48, 2039, 97862, 4085603]],
['pos3', '8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1', [14, 191, 2812, 43238, 674624]],
['pos4', 'r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1', [6, 264, 9467, 422333]],
['pos5', 'rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8', [44, 1486, 62379, 2103487]],
['960-a', 'bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9', [21, 528, 12189, 326672]],
['960-b', '2nnrbkr/p1qppppp/8/1ppb4/6PP/3PP3/PPP2P2/BQNNRBKR w HEhe - 1 9', [21, 807, 18002, 667366]],
['960-c', 'b1q1rrkb/pppppppp/3nn3/8/P7/1PPP4/4PPPP/BQNNRKRB w GE - 1 9', [20, 479, 10471, 273318]],
];
for (const [name, fen, exp] of PERFT) {
const p = L.fromFen(fen);
const depth = QUICK ? Math.min(exp.length, 3) : exp.length;
for (let d = 1; d <= depth; d++) {
const n = L.perft(p, d);
ok(`perft ${name} d${d}`, n === exp[d - 1], `${n} ≠ ${exp[d - 1]}`);
}
ok(`${name}: hash restored after perft`, (() => { const q = L.fromFen(fen); return q.lo === p.lo && q.hi === p.hi; })());
}
// ── rules ────────────────────────────────────────────────────────────────────
section('rules');
{
const g = new L.Chess();
ok('20 opening moves', g.moves().length === 20);
ok('white to move', g.turn === 'w');
g.move('e4');
ok('turn passes', g.turn === 'b' && g.ply === 1);
ok('history has SAN', g.history[0].san === 'e4' && g.history[0].uci === 'e2e4');
ok('no phantom en passant after e4', g.fen().split(' ')[3] === '-', g.fen());
}
{
// castling both ways, and losing the right
const g = new L.Chess('r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1');
ok('O-O and O-O-O available', sans(g).includes('O-O') && sans(g).includes('O-O-O'), sans(g).join(' '));
g.move('O-O');
ok('king g1, rook f1', g.at(62)?.type === 'k' && g.at(61)?.type === 'r' && !g.at(63), g.fen());
ok('white castling rights gone', !/[KQ]/.test(g.fen().split(' ')[2]), g.fen());
const h = new L.Chess('r3k2r/1pppppp1/8/8/8/8/1PPPPPP1/R3K2R w KQkq - 0 1');
h.move('Ra2'); h.move('Rb8');
ok('rook move drops only that side', h.fen().split(' ')[2] === 'Kk', h.fen());
}
{
// can't castle out of / through check
const g = new L.Chess('4k3/8/8/8/8/8/5r2/R3K2R w KQ - 0 1');
ok('no O-O through an attacked f1', !sans(g).includes('O-O'), sans(g).join(' '));
ok('O-O-O still fine', sans(g).includes('O-O-O'));
const c = new L.Chess('4k3/8/8/8/8/8/4r3/R3K2R w KQ - 0 1');
ok('no castling out of check', !sans(c).some((s) => s.startsWith('O-O')));
}
{
// en passant, including the horizontally pinned case
const g = new L.Chess('4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 2');
ok('exd6 e.p. legal', sans(g).includes('exd6'), sans(g).join(' '));
g.move('exd6');
ok('captured pawn removed', !g.at(L.to64(L.parseSq('d5'))));
const pin = new L.Chess('8/8/8/K2pP2r/8/8/8/7k w - d6 0 2');
ok('pinned e.p. illegal', !sans(pin).includes('exd6'), sans(pin).join(' '));
}
{
// promotion options
const g = new L.Chess('8/4P3/8/8/8/8/8/k6K w - - 0 1');
const pr = g.moves().filter((m) => m.promo);
ok('four promotions', pr.length === 4 && ['q', 'r', 'b', 'n'].every((t) => pr.some((m) => m.promo === t)));
g.move('e8=Q');
ok('queen on e8', g.at(4)?.type === 'q');
ok('promotion SAN', g.history[0].san === 'e8=Q');
}
{
const st = new L.Chess('7k/5Q2/6K1/8/8/8/8/8 b - - 0 1');
ok('stalemate', st.status()?.reason === 'stalemate' && st.status()?.winner === 'draw');
const cm = new L.Chess('7k/6Q1/6K1/8/8/8/8/8 b - - 0 1');
ok('checkmate', cm.status()?.reason === 'checkmate' && cm.status()?.winner === 'w');
ok('K v K draw', new L.Chess('8/8/8/4k3/8/8/8/4K3 w - - 0 1').status()?.reason === 'material');
ok('K+N v K draw', new L.Chess('8/8/8/4k3/8/8/8/3NK3 w - - 0 1').status()?.reason === 'material');
ok('K+B v K+B same colour draw', new L.Chess('8/8/3b4/4k3/8/8/8/2B1K3 w - - 0 1').status()?.reason === 'material');
ok('K+B v K+B opposite colours plays on', !new L.Chess('8/8/2b5/4k3/8/8/8/2B1K3 w - - 0 1').status());
ok('K+R v K plays on', !new L.Chess('8/8/8/4k3/8/8/8/R3K3 w - - 0 1').status());
}
{
// threefold repetition by shuffling knights
const g = new L.Chess();
for (const m of ['Nf3', 'Nf6', 'Ng1', 'Ng8', 'Nf3', 'Nf6', 'Ng1']) g.move(m);
ok('not yet a draw', !g.status());
g.move('Ng8');
ok('threefold', g.status()?.reason === 'repetition', JSON.stringify(g.status()));
const f = new L.Chess('8/8/8/4k3/8/8/8/R3K3 w - - 99 80');
f.move('Ra2');
ok('fifty-move rule', f.status()?.reason === 'fifty');
}
{
ok('canMate: lone king can\'t', !L.canMate(L.fromFen('8/8/8/4k3/8/8/8/R3K3 w - - 0 1'), L.BLACK));
ok('canMate: rook can', L.canMate(L.fromFen('8/8/8/4k3/8/8/8/R3K3 w - - 0 1'), L.WHITE));
}
// ── Chess960 ─────────────────────────────────────────────────────────────────
section('chess960');
{
let good = 0;
const seen = new Set();
for (let n = 0; n < 960; n++) {
const r = L.back960(n).join('');
seen.add(r);
const bi = [...r].map((c, i) => (c === 'b' ? i : -1)).filter((i) => i >= 0);
const ro = [...r].map((c, i) => (c === 'r' ? i : -1)).filter((i) => i >= 0);
const k = r.indexOf('k');
if (bi.length === 2 && (bi[0] + bi[1]) % 2 === 1 && ro.length === 2 && ro[0] < k && k < ro[1] && r.split('q').length === 2 && r.split('n').length === 3) good++;
if (n % 97 === 0) {
const g = new L.Chess(L.fen960(n));
if (g.moves().length < 18) good -= 1000;
}
}
ok('all 960 back ranks valid', good === 960, `${good}`);
ok('960 distinct', seen.size === 960);
ok('518 is the standard setup', L.back960(518).join('') === 'rnbqkbnr');
}
{
// king already on g1 castles by moving only the rook
const g = new L.Chess('1r4kr/8/8/8/8/8/8/1R4KR w HBhb - 0 1');
const c = g.moves().find((m) => m.castle === 'K');
ok('960 O-O with king on g1 exists', !!c, sans(g).join(' '));
g.move(c);
ok('960 O-O: king g1, rook f1', g.at(62)?.type === 'k' && g.at(61)?.type === 'r' && !g.at(63), g.fen());
const q = new L.Chess('1r4kr/8/8/8/8/8/8/1R4KR w HBhb - 0 1');
const cq = q.moves().find((m) => m.castle === 'Q');
ok('960 O-O-O exists', !!cq);
q.move(cq);
ok('960 O-O-O: king c1, rook d1', q.at(58)?.type === 'k' && q.at(59)?.type === 'r' && !q.at(57) && !q.at(62), q.fen());
ok('960 castling uci is king→rook', cq.uci === 'g1b1', cq.uci);
// rook blocked by the king's path
const b = new L.Chess('8/8/8/8/8/8/8/RK4k1 w A - 0 1');
ok('960 queen-side with rook a1, king b1', b.moves().some((m) => m.castle === 'Q'), sans(b).join(' '));
}
// ── notation ─────────────────────────────────────────────────────────────────
section('notation');
{
const rng = mulberry32(7);
let bad = 0, checked = 0;
for (let gi = 0; gi < (QUICK ? 6 : 20); gi++) {
const g = new L.Chess(gi % 4 === 3 ? L.fen960(Math.floor(rng() * 960)) : L.START_FEN);
for (let ply = 0; ply < 80 && !g.status(); ply++) {
const ms = g.moves();
for (const m of ms) {
checked++;
if (L.fromSan(g.pos, m.san) !== m.m) bad++;
if (L.fromUci(g.pos, m.uci) !== m.m) bad++;
}
const fen = g.fen();
if (L.toFen(L.fromFen(fen)) !== fen) bad += 1000;
g.move(ms[Math.floor(rng() * ms.length)]);
}
}
ok(`SAN/UCI/FEN round-trip (${checked} moves)`, bad === 0, `${bad} bad`);
const g = new L.Chess('7k/8/8/8/8/8/8/R3R2K w - - 0 1');
ok('rook disambiguation', sans(g).includes('Rad1') && sans(g).includes('Red1'), sans(g).join(' '));
const n = new L.Chess('7k/8/8/8/8/2N5/8/2N4K w - - 0 1');
ok('knight rank disambiguation', sans(n).includes('N1e2') && sans(n).includes('N3e2'), sans(n).join(' '));
const mate = new L.Chess('6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1');
ok('mate suffix', mate.moves().some((m) => m.san === 'Rd8#'));
const pg = new L.Chess();
['e4', 'e5', 'Nf3', 'Nc6'].forEach((m) => pg.move(m));
const pgn = pg.pgn({ white: 'A', black: 'B' });
ok('PGN movetext', pgn.includes('1. e4 e5 2. Nf3 Nc6 *'), pgn);
const p960 = new L.Chess(L.fen960(100));
p960.move(p960.moves()[0]);
ok('PGN 960 tags', /Variant "Chess960"/.test(p960.pgn()) && /FEN "/.test(p960.pgn()));
}
// ── opening book ─────────────────────────────────────────────────────────────
section('book');
{
const bad = checkBook().filter((x) => !x.ok);
ok('all book lines and names legal', bad.length === 0, bad.map((b) => `${b.line} @${b.at}`).join('; '));
const g = new L.Chess();
ok('book has replies at the start', bookMoves(g).length >= 4);
['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'a6'].forEach((m) => g.move(m));
ok('Najdorf named', openingName(g) === 'Sicilian, Najdorf', openingName(g));
const t = new L.Chess();
['c4', 'e6', 'Nc3', 'Nf6', 'd4', 'Bb4'].forEach((m) => t.move(m));
ok('transposition finds Nimzo', openingName(t) === 'Nimzo-Indian Defence', openingName(t));
ok('960 has no book', bookMoves(new L.Chess(L.fen960(3))).length === 0);
}
// ── puzzles ──────────────────────────────────────────────────────────────────
section('puzzles');
{
ok('puzzles exist', PUZZLES.length >= 40, `${PUZZLES.length}`);
ok('ids unique', new Set(PUZZLES.map((p) => p.id)).size === PUZZLES.length);
let bad = [];
for (const p of PUZZLES) {
const g = new L.Chess(p.fen);
const moves = p.moves.split(' ');
for (const u of moves) { if (!g.move(u)) { bad.push(`${p.id} ${u}`); break; } }
if (moves.length < 2 || moves.length % 2 !== 0) bad.push(`${p.id} length ${moves.length}`);
}
ok('every puzzle replays legally', bad.length === 0, bad.slice(0, 5).join('; '));
const sample = QUICK ? PUZZLES.filter((_, i) => i % 6 === 0) : PUZZLES;
const notBest = [];
for (const p of sample) {
const g = new L.Chess(p.fen);
const moves = p.moves.split(' ');
g.move(moves[0]);
const r = AI.analyze(g.pos, { ms: 700, margin: 300 });
const top = L.toUci(g.pos, r[0].m);
const mateTie = AI.mateIn(r[0].score) > 0 && r[1] && AI.mateIn(r[1].score) === AI.mateIn(r[0].score);
if (top !== moves[1] && !mateTie) notBest.push(`${p.id} engine ${top} vs ${moves[1]}`);
}
ok(`solution is the engine's choice (${sample.length})`, notBest.length <= Math.ceil(sample.length * 0.05), notBest.slice(0, 5).join('; '));
const d1 = dailyPuzzle(new Date(2026, 11, 1)), d1b = dailyPuzzle(new Date(2026, 11, 1)), d2 = dailyPuzzle(new Date(2026, 11, 2));
ok('daily deterministic', d1.puzzle.id === d1b.puzzle.id && d1.number === d1b.number);
ok('daily changes day to day', d1.puzzle.id !== d2.puzzle.id && d2.number === d1.number + 1);
ok('date key', dateKey(new Date(2026, 0, 5)) === '2026-01-05');
const st = { rating: 1000, solved: {}, failed: {}, streak: 0, best: 0, played: 0, daily: {} };
const pz = nextLadderPuzzle(st, mulberry32(3));
ok('ladder picks near rating', Math.abs(pz.rating - 1000) <= 600, `${pz.rating}`);
const up = ratePuzzle(st, { id: 'x', rating: 1200 }, 'solved');
ok('solving a harder puzzle gains', up > 20 && st.rating === 1000 + up && st.streak === 1);
const down = ratePuzzle(st, { id: 'y', rating: 800 }, 'failed');
ok('failing an easier puzzle loses', down < -20 && st.streak === 0);
ok('assisted is neutral', ratePuzzle(st, { id: 'z', rating: 900 }, 'assisted') === 0);
st.daily = { '2026-11-29': 'solved', '2026-11-30': 'solved', '2026-12-01': 'solved' };
ok('daily streak', dailyStreak(st, new Date(2026, 11, 1)) === 3 && dailyStreak(st, new Date(2026, 11, 2)) === 3);
}
// ── engine ───────────────────────────────────────────────────────────────────
section('engine');
{
const g = new L.Chess('r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq - 4 4');
for (let s = 1; s <= 5; s++) {
const t0 = Date.now();
const r = AI.chooseMove(g, s, { rng: mulberry32(s) });
const dt = Date.now() - t0;
ok(`skill ${s} legal`, g.moves().some((m) => m.m === r.m));
ok(`skill ${s} in budget`, dt <= AI.PROFILES[s].ms * 1.6 + 150, `${dt}ms`);
}
const mate1 = AI.bestMove(g.pos, { ms: 500 });
ok('finds Qxf7#', L.toUci(g.pos, mate1.m) === 'h5f7' && AI.mateIn(mate1.score) === 1);
const m2 = L.fromFen('r2qkb1r/pp2nppp/3p4/2pNN1B1/2BnP3/3P4/PPP2PPP/R2bK2R w KQkq - 1 1');
const r2 = AI.bestMove(m2, { ms: 1500 });
ok('finds mate in 2', AI.mateIn(r2.score) === 2, `${L.toUci(m2, r2.m)} ${r2.score}`);
const hang = L.fromFen('4k3/8/8/3q4/8/8/3R4/4K3 w - - 0 1');
const rh = AI.bestMove(hang, { ms: 400 });
ok('takes a hanging queen', L.toUci(hang, rh.m) === 'd2d5');
const s1 = L.fromFen('4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1');
ok('SEE: pawn takes defended-nothing pawn = +100', AI.see(s1, L.fromUci(s1, 'e4d5')) === 100);
const s2 = L.fromFen('4k3/2p5/3p4/8/8/8/3Q4/4K3 w - - 0 1');
ok('SEE: queen takes defended pawn < 0', AI.see(s2, L.fromUci(s2, 'd2d6')) < 0);
const fk = L.fromFen('r3k3/8/8/1N6/8/8/8/4K3 w - - 0 1');
ok('describeIdea: knight fork', /forks the king and rook/.test(AI.describeIdea(fk, L.fromUci(fk, 'b5c7'), 400)), AI.describeIdea(fk, L.fromUci(fk, 'b5c7'), 400));
// the worker message handler
const rec = { startFen: L.START_FEN, moves: ['e2e4', 'e7e5'] };
const mv = handle('move', { rec, skill: 3, ms: 150 });
ok('handle move', mv && typeof mv.uci === 'string' && mv.uci.length >= 4);
const best = handle('best', { rec, ms: 150 });
ok('handle best', best && best.san && best.idea && Array.isArray(best.pv));
const an = handle('analyze', { rec, ms: 150, margin: 200 });
ok('handle analyze', Array.isArray(an) && an.length === 29 && an[0].idea, `${an?.length}`);
const ev = handle('eval', { rec: { startFen: '7k/6Q1/6K1/8/8/8/8/8 b - - 0 1', moves: [] }, ms: 50 });
ok('handle eval on mate', ev.cp > 20000);
ok('clock budget shrinks with time', AI.clockBudget(5, 10000, 0, 40) < AI.clockBudget(5, 300000, 0, 40));
ok('draw decision sane', AI.drawDecision(-300, 60, 4).accept && !AI.drawDecision(300, 60, 4).accept && !AI.drawDecision(-300, 4, 4).accept);
ok('resign only when lost', AI.shouldResign([-1200, -1300, -1500], 4) && !AI.shouldResign([-1200, -200, -1500], 4) && !AI.shouldResign([-1200, -1300, -1500], 2));
}
// ── self-play ────────────────────────────────────────────────────────────────
section('self-play');
function play(sw, sb, ms, rng, fen = L.START_FEN) {
const g = new L.Chess(fen);
while (!g.status() && g.ply < 220) {
const c = AI.chooseMove(g, g.turn === 'w' ? sw : sb, { ms, rng });
if (!c || !g.move(c.m)) return { bad: true, g };
let kings = 0;
for (const p of g.board64()) if (p?.type === 'k') kings++;
if (kings !== 2) return { bad: true, g };
}
return { g, r: g.result ?? { winner: 'draw', reason: 'cap' } };
}
{
const rng = mulberry32(11);
let bad = 0;
const N = QUICK ? 3 : 8;
for (let i = 0; i < N; i++) {
const r = play(1 + (i % 5), 1 + ((i * 3) % 5), 40, rng, i % 3 === 2 ? L.fen960(Math.floor(rng() * 960)) : L.START_FEN);
if (r.bad) bad++;
}
ok(`soak: ${N} games clean`, bad === 0);
}
{
const rng = mulberry32(5);
let hi = 0, lo = 0;
const N = QUICK ? 2 : 6;
for (let i = 0; i < N; i++) {
const strongWhite = i % 2 === 0;
const r = play(strongWhite ? 5 : 2, strongWhite ? 2 : 5, 80, rng);
const w = r.r?.winner;
if ((w === 'w' && strongWhite) || (w === 'b' && !strongWhite)) hi++;
else if (w && w !== 'draw') lo++;
}
ok(`skill 5 beats skill 2 (${hi}-${lo})`, hi > lo);
}
// ── layout ───────────────────────────────────────────────────────────────────
section('layout');
{
const R = LY.HUD_RECTS();
const board = LY.BOARD_RECT;
const hit = (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`, !hit(r, board), JSON.stringify(r));
}
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]} / ${keys[j]} don't overlap`, !hit(R[keys[i]], R[keys[j]]));
}
}
ok('square mapping round-trips', [0, 7, 36, 63].every((s) => {
const p = LY.squareXY(s, false), q = LY.squareXY(s, true);
return LY.sqAt(p.x, p.y, false) === s && LY.sqAt(q.x, q.y, true) === s;
}));
ok('a8 top-left when White is at the bottom', LY.squareXY(0, false).x < LY.BCX && LY.squareXY(0, false).y < LY.BCY);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);