fertig-classic-games/tools/verifyGo.js

500 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// verifyGo.js: headless checks for Go ("Unkai-ji, the Temple Above the
// Clouds"):
// • rules: notation, star and handicap points, captures, suicide, simple
// ko and positional superko, passes into scoring, resign, replay/rewind
// • scoring: territory (Japanese) and area (Chinese) on hand-built boards,
// dead stones, prisoners, komi, jigo
// • the fast board agrees with GoLogic on legality and on the board after
// every move, across random games on all three sizes
// • the engine: legal moves only, never fills its own true eyes, passes
// once the board is settled, finds captures and escapes; the skill
// ladder holds (stronger beats weaker over colour-swapped games)
// • dead-stone estimation on settled boards; review output
// • tsumego: the solver on classic shapes; every shipped puzzle is legal,
// solvable and has a unique first move
// • SGF: write → parse round-trip, handicap/setup stones, comments
// • layout: HUD rectangles on screen and clear of the board and each other
// Usage: node tools/verifyGo.js [--quick]
import * as L from '../src/games/go/GoLogic.js';
import * as AI from '../src/games/go/GoAI.js';
import * as T from '../src/games/go/GoTsumego.js';
import * as PZ from '../src/games/go/GoPuzzles.js';
import { toSgf, parseSgf } from '../src/games/go/GoSgf.js';
import { hounLine, opponentLine } from '../src/games/go/GoTalk.js';
import { HUD_RECTS, W, H, pointAt, pointXY } from '../src/games/go/GoLayout.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}`);
function mulberry32(seed) {
let a = (seed >>> 0) || 1;
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;
};
}
/** Build a board from rows of '.', 'X' (black), 'O' (white). */
function boardFrom(rows) {
const size = rows.length;
const b = [];
for (const row of rows) for (const ch of row.replace(/\s/g, '')) b.push(ch === 'X' ? L.BLACK : ch === 'O' ? L.WHITE : null);
return { size, board: b };
}
function gameFrom(rows, { turn = L.BLACK, rules = 'japanese', komi = 6.5, captures = null } = {}) {
const { size, board } = boardFrom(rows);
const gs = L.createGame({ size, rules, komi, setup: { black: board.map((v, i) => (v === L.BLACK ? i : -1)).filter((i) => i >= 0), white: board.map((v, i) => (v === L.WHITE ? i : -1)).filter((i) => i >= 0) }, turn });
if (captures) gs.captures = { ...captures };
return gs;
}
const P = (n, size) => L.parseSq(n, size);
// ── rules ────────────────────────────────────────────────────────────────────
section('rules');
{
for (const size of L.SIZES) {
let rt = true;
for (let sq = 0; sq < size * size; sq++) if (L.parseSq(L.notate(sq, size), size) !== sq) rt = false;
ok(`notation round-trip ${size}×${size}`, rt);
}
ok('A9 is the top-left of 9×9, J1 bottom-right', L.notate(0, 9) === 'A9' && L.notate(80, 9) === 'J1');
ok('no I column', !L.COLS.includes('I') && L.notate(8, 19) === 'J19');
ok('9×9 has five star points', L.starPoints(9).length === 5);
ok('19×19 has nine star points incl. tengen', L.starPoints(19).length === 9 && L.starPoints(19).includes(P('K10', 19)));
for (const size of L.SIZES) {
for (let n = 2; n <= 9; n++) {
const pts = L.handicapPoints(size, n);
ok(`handicap ${n} on ${size}: ${n} distinct points`, pts.length === n && new Set(pts).size === n);
}
}
ok('handicap 2 on 19 is D4 + Q16', ['Q16', 'D4'].every((x) => L.handicapPoints(19, 2).includes(P(x, 19))));
const h = L.createGame({ size: 19, handicap: 4 });
ok('handicap game: white to move, komi 0.5', h.turn === L.WHITE && h.komi === 0.5 && h.board.filter(Boolean).length === 4);
// a capture in the middle
let g = gameFrom([
'.........',
'.........',
'....X....',
'...XO....',
'....X....',
'.........',
'.........',
'.........',
'.........',
]);
const t = L.tryMove(g, P('F6', 9));
ok('capture: one white stone taken', t.ok && t.captured.length === 1 && t.captured[0] === P('E6', 9));
g = L.play(g, P('F6', 9));
ok('capture: prisoners counted, point empty', g.captures.black === 1 && g.board[P('E6', 9)] === null);
ok('capture of a single stone sets no ko here', g.ko === -1);
// suicide
const s = gameFrom([
'.X.......',
'X........',
'.........', '.........', '.........', '.........', '.........', '.........', '.........',
], { turn: L.WHITE });
ok('suicide is illegal', L.tryMove(s, P('A9', 9)).reason === 'suicide');
ok('the suicide point is not a legal move', !L.legalMoves(s).includes(P('A9', 9)));
// ko
let k = gameFrom([
'.........',
'...XO....',
'..X.XO...',
'...XO....',
'.........', '.........', '.........', '.........', '.........',
], { turn: L.WHITE });
const before = k.board.slice();
k = L.play(k, P('D7', 9)); // white takes at D7, capturing E7
ok('ko: white captures one stone', k && k.captures.white === 1 && k.board[P('E7', 9)] === null);
ok('ko: the ko point is marked', k.ko === P('E7', 9));
ok('ko: black may not retake at once', L.tryMove(k, P('E7', 9)).reason === 'ko');
k = L.play(k, P('A1', 9)); // a ko threat
k = L.play(k, P('A2', 9)); // answered
ok('ko: after an exchange black may retake', L.tryMove(k, P('E7', 9)).ok);
k = L.play(k, P('E7', 9));
ok('ko: retaking captures the white stone', k.board[P('D7', 9)] === null);
ok('position keys recorded for superko', k.seen.length === k.history.length + 1);
ok('setup board restored by replay', L.boardAfter(k, 0).join() === before.join());
ok('rewind gives the same board', L.rewind(k, k.history.length).board.join() === k.board.join());
// positional superko: a position that repeats without being a simple ko
{
const base = gameFrom([
'.........', '.........', '.........', '.........', '.........', '.........', '.........', '.........', '.........',
]);
// play a stone, pass dance can't repeat a position; check seen-lookup directly
let q = L.play(base, P('E5', 9));
const forged = { ...q, seen: q.seen.concat([L.hashKey(L.zobristOf([...q.board.slice(0, P('A1', 9)), L.WHITE, ...q.board.slice(P('A1', 9) + 1)]))]) };
ok('superko: a repeated whole-board position is refused', L.tryMove(forged, P('A1', 9)).reason === 'superko');
}
// passes and the end
let p = L.createGame({ size: 9 });
p = L.pass(p);
ok('one pass: still playing, white to move', p.phase === 'playing' && p.turn === L.WHITE && p.passes === 1);
p = L.play(p, P('E5', 9));
ok('a move resets the pass count', p.passes === 0);
p = L.pass(L.pass(p));
ok('two passes in a row: scoring', p.phase === 'scoring');
ok('no legal moves while scoring', L.legalMoves(p).length === 0);
const r = L.resumePlay(p);
ok('resume play returns to playing', r.phase === 'playing' && r.passes === 0);
const rg = L.resign(L.createGame({ size: 9 }), L.BLACK);
ok('resign: the other side wins', rg.phase === 'over' && rg.winner === L.WHITE && L.resultString(rg) === 'W+R');
}
// ── scoring ──────────────────────────────────────────────────────────────────
section('scoring');
{
// a split board: black owns columns A–D, white F–J, the E column is the wall
const rows = [];
for (let i = 0; i < 9; i++) rows.push('...XO....');
const gj = gameFrom(rows, { komi: 6.5 });
const sj = L.scoreGame(gj, []);
ok('territory: black 27 points', sj.territory.black === 27, `${sj.territory.black}`);
ok('territory: white 36 points', sj.territory.white === 36, `${sj.territory.white}`);
ok('Japanese: B 27 · W 42.5', sj.black === 27 && sj.white === 42.5, `${sj.black} ${sj.white}`);
const gc = gameFrom(rows, { rules: 'chinese', komi: 7.5 });
const sc = L.scoreGame(gc, []);
ok('Chinese: B 36 · W 52.5', sc.black === 36 && sc.white === 52.5, `${sc.black} ${sc.white}`);
ok('winner white, margin 15.5 (Japanese)', sj.winner === L.WHITE && sj.margin === 15.5);
// a dead white stone inside black's area
const rows2 = rows.slice();
rows2[4] = '.O.XO....';
const gd = gameFrom(rows2, { komi: 6.5 });
const alive = L.scoreGame(gd, []);
ok('an unremoved invader spoils the territory', alive.territory.black < 27);
const dead = [P('B5', 9)];
const sd = L.scoreGame(gd, dead);
ok('dead stone removed: black territory back to 27', sd.territory.black === 27);
ok('dead stone counts as a prisoner (Japanese)', sd.prisoners.black === 1 && sd.black === 28);
const gdc = gameFrom(rows2, { rules: 'chinese', komi: 7.5 });
ok('Chinese: dead stone just becomes black area', L.scoreGame(gdc, dead).black === 36);
// toggling dead marks the whole chain
const rows3 = rows.slice();
rows3[4] = '.OO.XO....'.slice(0, 9);
const gt = gameFrom(['.OO.X....', ...rows.slice(1)]);
const td = L.toggleDead(gt, [], P('B9', 9));
ok('toggleDead marks the whole chain', td.length === 2 && td.includes(P('C9', 9)));
ok('toggleDead again clears it', L.toggleDead(gt, td, P('C9', 9)).length === 0);
// jigo
const gz = gameFrom(Array(9).fill('...X.O...'), { komi: 0 });
const fz = L.finish(gz, []);
ok('equal score with no komi: jigo', fz.winner === 'draw' && L.resultString(fz) === '0');
const fw = L.finish(gj, []);
ok('result string W+15.5', L.resultString(fw) === 'W+15.5');
}
// ── the fast board vs the rules ──────────────────────────────────────────────
section('engine board agrees with the rules');
{
const { fromPos, geo } = AI._internals;
const rnd = mulberry32(11);
let positions = 0, legalBad = 0, boardBad = 0, koBad = 0;
const games = QUICK ? 6 : 24;
for (const size of L.SIZES) {
const gg = geo(size);
for (let gi = 0; gi < games; gi++) {
let gs = L.createGame({ size, handicap: gi % 3 === 0 ? 3 : 0 });
const maxMoves = size * size * (size === 19 ? 1 : 2);
while (gs.phase === 'playing' && gs.history.length < maxMoves) {
const b = fromPos(AI.posOf(gs));
positions++;
// legality: the fast board ignores only superko
for (let sq = 0; sq < size * size; sq++) {
const t = L.tryMove(gs, sq);
const fast = b.legal(gg.toIdx[sq], b.turn);
const ref = t.ok || t.reason === 'superko';
if (fast !== ref) { legalBad++; break; }
}
const legal = L.legalMoves(gs);
// prefer non-eye-filling moves so games last
const good = legal.filter((sq) => !L.eyeLike(gs.board, size, sq, gs.turn));
if (!good.length || rnd() < 0.02) { gs = L.pass(gs); continue; }
const sq = good[Math.floor(rnd() * good.length)];
const next = L.play(gs, sq);
b.play(gg.toIdx[sq]);
const fb = Array(size * size).fill(null);
for (const p of gg.pts) { const c = b.color[p]; if (c === 1) fb[gg.toSq[p]] = L.BLACK; else if (c === 2) fb[gg.toSq[p]] = L.WHITE; }
if (fb.join() !== next.board.join()) boardBad++;
const fk = b.ko ? gg.toSq[b.ko] : -1;
if (fk !== next.ko) koBad++;
gs = next;
}
}
}
ok(`legality matches on ${positions} positions`, legalBad === 0, `${legalBad} mismatches`);
ok('boards match after every move', boardBad === 0, `${boardBad}`);
ok('ko point matches', koBad === 0, `${koBad}`);
}
// ── the engine ───────────────────────────────────────────────────────────────
section('engine: legal, eyes, passing, tactics');
{
// legal moves only, on random positions of every size
const rnd = mulberry32(99);
let bad = 0, tried = 0;
for (const size of L.SIZES) {
for (let g = 0; g < (QUICK ? 2 : 4); g++) {
let gs = L.createGame({ size });
const n = Math.floor(rnd() * size * size * 0.5);
for (let i = 0; i < n; i++) {
const legal = L.legalMoves(gs).filter((sq) => !L.eyeLike(gs.board, size, sq, gs.turn));
if (!legal.length) break;
gs = L.play(gs, legal[Math.floor(rnd() * legal.length)]);
}
const r = AI.chooseMove(AI.posOf(gs), 1 + (g % 3), { seed: 7 + g, scale: 0.08 });
tried++;
if (r.sq >= 0 && !L.isLegal(gs, r.sq)) bad++;
}
}
ok(`the engine plays legal moves (${tried} positions)`, bad === 0, `${bad} illegal`);
// a finished board: two eyes for every group, nothing left to play
const fin = [
'XXXXOOOOO',
'X.XXOO.OO',
'XXXXOOOOO',
'XXXXOOOOO',
'XX.XOOO.O',
'XXXXOOOOO',
'XXXXOOOOO',
'X.XXOO.OO',
'XXXXOOOOO',
];
const eyesB = [P('B8', 9), P('C5', 9), P('B2', 9)];
{
const gs = gameFrom(fin, { turn: L.BLACK, komi: 0.5 });
gs.history.push({ color: L.WHITE, sq: -1, pass: true, captured: [], n: 'pass' });
gs.passes = 1;
const r = AI.chooseMove(AI.posOf(gs), 3, { seed: 3, scale: 0.4 });
ok('never fills its own true eye on a finished board', !eyesB.includes(r.sq), `played ${L.notate(r.sq, 9)}`);
ok('passes (or resigns) when nothing is left', r.sq === -1 || r.resign);
}
{
const gs = gameFrom(fin, { turn: L.WHITE, komi: 0.5 });
gs.history.push({ color: L.BLACK, sq: -1, pass: true, captured: [], n: 'pass' });
gs.passes = 1;
const r = AI.chooseMove(AI.posOf(gs), 4, { seed: 4, scale: 0.4 });
ok('passes back when settled and ahead', r.sq === -1 && !r.resign, `played ${r.sq >= 0 ? L.notate(r.sq, 9) : 'resign'}`);
}
{
const gs = gameFrom([
'.........',
'.........',
'...OOO...',
'..OXXXO..',
'..OXXX...',
'...OOO...',
'.........',
'.........',
'.........',
], { turn: L.WHITE });
const r = AI.chooseMove(AI.posOf(gs), 4, { seed: 5, scale: 0.3 });
ok('captures six stones in atari', r.sq === P('G5', 9), `played ${L.notate(r.sq, 9)}`);
}
{
const gs = gameFrom([
'.........',
'.........',
'.........',
'....OO...',
'...OXX...',
'....OO...',
'.........',
'.........',
'.........',
], { turn: L.BLACK });
const r = AI.analyse(AI.posOf(gs), { playouts: 3000, ms: 800, seed: 6 });
ok('runs two stones out of atari', r.best === P('G5', 9), `best ${L.notate(r.best, 9)}`);
}
}
section('engine: dead stones and review');
{
const gs = gameFrom([
'....XO...',
'.O..XO...',
'....XO...',
'....XO...',
'....XO.X.',
'....XO...',
'....XO...',
'....XO...',
'....XO...',
], { komi: 6.5 });
const r = AI.estimateDead(AI.posOf(gs), { playouts: 3000, ms: 1500, seed: 11 });
ok('a lone invader in black\'s area is dead', r.dead.includes(P('B8', 9)), `dead ${r.dead.map((s) => L.notate(s, 9)).join(' ')}`);
ok('a lone invader in white\'s area is dead', r.dead.includes(P('H5', 9)));
ok('the walls are alive', !r.dead.some((s) => [P('E5', 9), P('F5', 9)].includes(s)));
const sc = L.scoreGame(gs, r.dead);
ok('the count after removing them is right (B 36+1 · W 27+1+6.5)', sc.black === 37 && sc.white === 34.5, `${sc.black}–${sc.white}`);
// review output
let g2 = L.createGame({ size: 9 });
for (const n of ['E5', 'C3', 'G7']) g2 = L.play(g2, P(n, 9));
const list = [0, 1, 2, 3].map((n) => {
const pos = L.positionAfter(g2, n);
return { size: 9, board: pos.board, turn: n % 2 ? L.WHITE : L.BLACK, komi: 6.5, rules: 'japanese', ko: -1, last: null, last2: null, passes: 0, captures: pos.captures, forbidden: [], moveNo: n };
});
const rev = AI.reviewPositions(list, { playouts: 300, ms: 150, seed: 2 });
ok('review: one answer per position', rev.length === 4 && rev.every((x) => x && Number.isFinite(x.lead) && x.winrate >= 0 && x.winrate <= 1));
ok('review: best moves are empty points', rev.every((x, i) => x.best < 0 || !list[i].board[x.best]));
}
if (!QUICK) {
section('engine: skill ladder and time budgets');
const playOut = (skB, skW, seed, scale) => {
let gs = L.createGame({ size: 9, komi: 6.5 });
for (let i = 0; i < 160 && gs.phase === 'playing'; i++) {
const sk = gs.turn === L.BLACK ? skB : skW;
const r = AI.chooseMove(AI.posOf(gs), sk, { seed: seed + i, scale });
if (r.resign) return L.other(gs.turn);
gs = r.sq < 0 ? L.pass(gs) : (L.play(gs, r.sq) ?? L.pass(gs));
}
const d = AI.estimateDead(AI.posOf(gs), { playouts: 3000, ms: 1200, seed });
return L.scoreGame(gs, d.dead).winner;
};
let strong = 0;
const games = 2;
for (let g = 0; g < games; g++) {
const strongBlack = g % 2 === 0;
const w = playOut(strongBlack ? 5 : 1, strongBlack ? 1 : 5, 100 + g * 1000, 0.15);
if (w === (strongBlack ? L.BLACK : L.WHITE)) strong++;
}
ok(`skill 5 beats skill 1 (${strong}/${games}, colours swapped)`, strong === games);
for (const size of [9, 19]) {
let gs = L.createGame({ size });
for (const n of size === 9 ? ['E5', 'C3'] : ['Q16', 'D4', 'Q4']) gs = L.play(gs, P(n, size));
for (const sk of [1, 3, 5]) {
const t0 = Date.now();
AI.chooseMove(AI.posOf(gs), sk, { seed: 1 });
const ms = Date.now() - t0;
const budget = AI.SKILL[sk].ms * ({ 9: 1, 13: 1.25, 19: 1.5 }[size]);
ok(`skill ${sk} on ${size}×${size} within its time budget (${ms} ms of ${Math.round(budget)})`, ms <= budget * 1.25 + 150);
}
}
}
// ── tsumego ──────────────────────────────────────────────────────────────────
section('tsumego: shipped problems');
{
const ids = new Set(PZ.PUZZLES.map((p) => p.id));
ok(`${PZ.PUZZLES.length} problems, ids unique`, ids.size === PZ.PUZZLES.length && PZ.PUZZLES.length >= 150);
ok('kill and live problems both present', PZ.PUZZLES.some((p) => p.goal === 'kill') && PZ.PUZZLES.some((p) => p.goal === 'live'));
ok('ratings sorted within 600–1900', PZ.PUZZLES.every((p, i) => p.rating >= 600 && p.rating <= 1900 && (i === 0 || p.rating >= PZ.PUZZLES[i - 1].rating)));
const sample = QUICK ? PZ.PUZZLES.filter((_, i) => i % 7 === 0) : PZ.PUZZLES;
let badSetup = 0, notUnique = 0, badLine = 0, badSym = 0, aborted = 0;
for (const p of sample) {
const raw = PZ.puzzleSetup(p, { sym: false });
const st = PZ.puzzleSetup(p);
// stones don't overlap, the first move is an empty point in the region
const nB = p.b.length / 2, nW = p.w.length / 2;
const cnt = L.counts(st.board);
if (cnt.black !== nB || cnt.white !== nW || st.board[st.first] || !st.region.includes(st.first)) badSetup++;
const prob = PZ.toProb(st, st.board, L.BLACK);
const w = T.winningMoves(prob, { maxNodes: 400000 });
if (w.aborted) aborted++;
const real = w.moves.filter((m) => m !== T.PASS);
if (real.length !== 1 || real[0] !== st.first || w.passWins) notUnique++;
// the symmetry is a true symmetry: the unmapped problem has the unmapped answer
const w0 = T.winningMoves(PZ.toProb(raw, raw.board, L.BLACK), { maxNodes: 400000 }).moves.filter((m) => m !== T.PASS);
if (w0.length !== 1 || w0[0] !== raw.first) badSym++;
// the main line is playable and Black still wins at its end
let pr = prob, okLine = true;
for (const sq of st.line) { pr = T.play(pr, sq); if (!pr) { okLine = false; break; } }
if (okLine && !T.terminal(pr) && !T.wins(pr, L.BLACK, { maxNodes: 400000 })) okLine = false;
if (!okLine) badLine++;
}
ok(`setups sound (${sample.length} checked)`, badSetup === 0, `${badSetup}`);
ok('each has exactly one winning first move, and passing loses', notUnique === 0, `${notUnique}`);
ok('the board symmetry keeps the answer', badSym === 0, `${badSym}`);
ok('every main line is legal and ends won for Black', badLine === 0, `${badLine}`);
ok('the solver finished every search', aborted === 0, `${aborted}`);
// ladder and daily picks
const stt = { rating: 800, solved: {}, failed: {}, streak: 0, best: 0, played: 0, daily: {} };
const pick = PZ.nextLadderPuzzle(stt, mulberry32(1));
ok('the ladder picks near your rating', Math.abs(pick.rating - 800) < 400);
const d1 = PZ.dailyPuzzle(new Date(2026, 11, 1)), d2 = PZ.dailyPuzzle(new Date(2026, 11, 2));
ok('the daily problem changes by the day', d1.puzzle.id !== d2.puzzle.id && d2.number === d1.number + 1);
const before = stt.rating;
PZ.ratePuzzle(stt, pick, 'solved');
ok('solving raises the rating', stt.rating > before && stt.solved[pick.id]);
stt.daily[PZ.dateKey(new Date(2026, 11, 1))] = 'solved';
stt.daily[PZ.dateKey(new Date(2026, 11, 2))] = 'solved';
ok('the daily streak counts consecutive days', PZ.dailyStreak(stt, new Date(2026, 11, 2)) === 2 && PZ.dailyStreak(stt, new Date(2026, 11, 3)) === 2 && PZ.dailyStreak(stt, new Date(2026, 11, 4)) === 0);
}
// ── SGF ──────────────────────────────────────────────────────────────────────
section('SGF');
{
const rnd = mulberry32(5);
let gs = L.createGame({ size: 13, handicap: 3, rules: 'chinese' });
for (let i = 0; i < 60; i++) {
const legal = L.legalMoves(gs).filter((sq) => !L.eyeLike(gs.board, 13, sq, gs.turn));
if (!legal.length || rnd() < 0.03) { gs = L.pass(gs); if (gs.phase !== 'playing') break; continue; }
gs = L.play(gs, legal[Math.floor(rnd() * legal.length)]);
}
if (gs.phase === 'playing') gs = L.pass(L.pass(gs));
gs = L.finish(gs, []);
const text = toSgf(gs, { black: 'Hōun [the monk]', white: 'Jun' });
const { gs: back, info } = parseSgf(text);
ok('round trip: size, komi, rules, handicap', back.size === 13 && back.komi === gs.komi && back.rules === 'chinese' && back.handicap === 3);
ok('round trip: setup stones', back.setup.black.join() === gs.setup.black.join());
ok('round trip: every move', back.history.length === gs.history.length && back.history.every((h, i) => h.sq === gs.history[i].sq && h.color === gs.history[i].color));
ok('round trip: final board', back.board.join() === gs.board.join());
ok('round trip: names with brackets escaped', info.black === 'Hōun [the monk]' && info.white === 'Jun');
ok('round trip: result', info.result === L.resultString(gs), `${info.result} vs ${L.resultString(gs)}`);
const hand = parseSgf('(;GM[1]FF[4]SZ[9]KM[6.5]PB[A]PW[B]RE[W+R];B[ee]C[a \\] bracket];W[cc](;B[gg];W[gc])(;B[cg]))');
ok('main line follows the first variation', hand.gs.history.map((h) => h.n).join(' ') === 'E5 C7 G3 G7', hand.gs.history.map((h) => h.n).join(' '));
ok('comments with escaped brackets', hand.info.comments[0] === 'a ] bracket');
ok('a resignation result is kept', hand.gs.winner === L.WHITE && hand.gs.endReason === 'resign');
let threw = false;
try { parseSgf('(;GM[1]SZ[7];B[aa])'); } catch (_) { threw = true; }
ok('odd board sizes are refused', threw);
const passes = parseSgf('(;SZ[9];B[];W[tt];B[ee])');
ok('B[] and tt are passes, and play can go on after them', passes.gs.history[0].pass && passes.gs.history[1].pass && passes.gs.history[2].n === 'E5' && passes.gs.phase === 'playing');
}
// ── words and layout ─────────────────────────────────────────────────────────
section('talk and layout');
{
const kinds = ['welcome', 'handicap', 'humanCapture', 'atariYou', 'ko', 'aiPass', 'scoring', 'hint', 'warnSelfAtari', 'dispute', 'puzzleKill', 'proverb', 'byoyomi'];
let leftover = 0;
for (const k of kinds) for (let i = 0; i < 20; i++) {
const l = hounLine(k, { n: 3, move: 'D4', name: 'Jun', reason: 'claims a corner', s: 30 });
if (l && /[{}]/.test(l)) leftover++;
}
ok('Hōun\'s lines fill every blank', leftover === 0, `${leftover}`);
ok('every tier has a greeting', ['novice', 'regular', 'master'].every((t) => opponentLine('greet', t)));
const R = HUD_RECTS();
const names = Object.keys(R);
ok('every HUD rectangle on screen', names.every((n) => R[n].x >= 0 && R[n].y >= 0 && R[n].x + R[n].w <= W && R[n].y + R[n].h <= H), names.filter((n) => !(R[n].x >= 0 && R[n].y >= 0 && R[n].x + R[n].w <= W && R[n].y + R[n].h <= H)).join(' '));
const hit = [];
for (let i = 0; i < names.length; i++) for (let j = i + 1; j < names.length; j++) {
const a = R[names[i]], b = R[names[j]];
if (a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h) hit.push(`${names[i]}/${names[j]}`);
}
ok('no two HUD rectangles overlap', hit.length === 0, hit.join(' '));
let round = true;
for (const size of L.SIZES) for (let sq = 0; sq < size * size; sq++) { const p = pointXY(sq, size); if (pointAt(p.x, p.y, size) !== sq) round = false; }
ok('point ↔ screen round trip on every size', round);
}
// @@END-OF-SECTIONS@@
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);