fertig-classic-games/tools/verifySudoku.js

705 lines
40 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
// verifySudoku.js — headless checks for the Sunday Paper Café Sudoku: the
// generator (valid, unique by an independent counter, on-target technique tier
// and givens band, seeded determinism, speed), the logic solver's soundness,
// board helpers (conflicts, tallies, finished units), hints, undo/redo,
// save/resume validation, daily streaks, the café layout, art bakes against a
// strict fake 2D context, and a stubbed-Phaser smoke run of the play flow.
// Usage: node tools/verifySudoku.js [--quick]
import { generatePuzzle, countSolutions, gradePuzzle, DIFFICULTY_SPEC } from '../src/words/sudokuEngine.js';
import {
N, DIFFS, calcScore, isBoardComplete, getHintCell, boxOf, peers, unitCells, findConflicts, digitCounts, completedUnits,
makeHistory, pushEdit, pushMarker, canUndo, canRedo, undoEdit, redoEdit, isEasyTier,
serialiseSave, parseSave, dailySeed, prevDate, updateDaily, dailyStreakNow, blankDaily, longDate, EDITION,
} from '../src/games/sudoku/SudokuLogic.js';
import {
W, H, PAPER, CELL, GRID_W, GRID_X, GRID_Y, SIDE, PRINT, RCX, WATCH, CUP, PAD, PAD_PITCH, PAD_ROW0, ERASER_Y,
BTN_Y1, BTN_Y2, CARD_W, CARD_H, CLIP_W, CLIP_H, FLAP, HEADER_Y,
} from '../src/games/sudoku/SudokuArt.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 clone = (g) => g.map(r => [...r]);
function validSolution(sol) {
for (let k = 0; k < 9; k++) {
for (const type of ['row', 'col', 'box']) {
const vals = unitCells(type, k).map(({ r, c }) => sol[r][c]).sort();
if (vals.join('') !== '123456789') return `${type} ${k}`;
}
}
return null;
}
// Independent solution counter: plain backtracking over the first empty cell,
// checking the rules directly (no bitmasks, nothing shared with the engine).
function naiveCount(grid, limit = 2) {
const g = clone(grid);
const fits = (r, c, v) => {
for (let k = 0; k < 9; k++) if (g[r][k] === v || g[k][c] === v) return false;
const r0 = Math.floor(r / 3) * 3, c0 = Math.floor(c / 3) * 3;
for (let rr = r0; rr < r0 + 3; rr++) for (let cc = c0; cc < c0 + 3; cc++) if (g[rr][cc] === v) return false;
return true;
};
let count = 0, nodes = 0;
const rec = () => {
if (++nodes > 3e6) return;
let er = -1, ec = -1, best = null;
for (let r = 0; r < 9 && best?.length !== 0; r++)
for (let c = 0; c < 9; c++) {
if (g[r][c]) continue;
const cands = [];
for (let v = 1; v <= 9; v++) if (fits(r, c, v)) cands.push(v);
if (!best || cands.length < best.length) { best = cands; er = r; ec = c; if (cands.length <= 1) break; }
}
if (er < 0) { count++; return; }
for (const v of best) {
g[er][ec] = v;
rec();
g[er][ec] = 0;
if (count >= limit) return;
}
};
rec();
return nodes > 3e6 ? -1 : count;
}
const puzzles = {};
// ── Generator ────────────────────────────────────────────────────────────────
section('Generator');
{
const per = QUICK ? 3 : 10;
for (const d of DIFFS) {
const spec = DIFFICULTY_SPEC[d];
const times = [];
puzzles[d] = [];
for (let i = 0; i < per; i++) {
const t0 = Date.now();
const p = generatePuzzle(d);
times.push(Date.now() - t0);
puzzles[d].push(p);
const bad = validSolution(p.solution);
ok(`${d}#${i} solution valid`, !bad, bad);
let givens = 0, mismatch = 0;
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (p.grid[r][c]) { givens++; if (p.grid[r][c] !== p.solution[r][c]) mismatch++; }
ok(`${d}#${i} givens agree with the solution`, mismatch === 0);
ok(`${d}#${i} reported givens`, givens === p.givens, `${givens} vs ${p.givens}`);
ok(`${d}#${i} givens in band ${spec.min}–${spec.max}`, givens >= spec.min && givens <= spec.max, `${givens}`);
let sym = true;
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!!p.grid[r][c] !== !!p.grid[8 - r][8 - c]) sym = false;
ok(`${d}#${i} 180° symmetric`, sym);
ok(`${d}#${i} unique (independent counter)`, naiveCount(p.grid) === 1);
ok(`${d}#${i} unique (engine counter)`, countSolutions(p.grid) === 1);
const g = gradePuzzle(p.grid);
ok(`${d}#${i} grade = tier ${spec.tier}`, g.solved && g.tier === spec.tier && p.tier === spec.tier, `tier ${g.tier}, reported ${p.tier}`);
ok(`${d}#${i} solver reaches the stored solution`, JSON.stringify(g.grid) === JSON.stringify(p.solution));
if (spec.tier > 1) ok(`${d}#${i} not solvable with easier techniques`, !gradePuzzle(p.grid, spec.tier - 1).solved);
}
times.sort((a, b) => a - b);
const p95 = times[Math.min(times.length - 1, Math.floor(times.length * 0.95))];
console.log(` ${d}: median ${times[Math.floor(times.length / 2)]}ms, p95 ${p95}ms, max ${times.at(-1)}ms`);
ok(`${d} generation p95 under 3s`, p95 < 3000, `${p95}ms`);
}
}
section('Seeded generation');
{
for (const d of DIFFS) {
const a = generatePuzzle(d, { seed: 4242 }), b = generatePuzzle(d, { seed: 4242 });
ok(`${d}: same seed → same board`, JSON.stringify(a) === JSON.stringify(b));
const c = generatePuzzle(d, { seed: 4243 });
ok(`${d}: different seed → different board`, JSON.stringify(a.grid) !== JSON.stringify(c.grid));
ok(`${d}: seeded board valid, unique, on tier`, !validSolution(a.solution) && naiveCount(a.grid) === 1 && a.tier === DIFFICULTY_SPEC[d].tier);
}
const r1 = generatePuzzle('regular'), r2 = generatePuzzle('regular');
ok('unseeded boards still vary after seeded calls', JSON.stringify(r1.grid) !== JSON.stringify(r2.grid));
ok('daily seeds differ by date', dailySeed('2026-11-26') !== dailySeed('2026-11-27'));
ok('daily seed is stable', dailySeed('2026-11-26') === dailySeed('2026-11-26'));
const da = generatePuzzle('regular', { seed: dailySeed('2026-11-26') });
const db = generatePuzzle('regular', { seed: dailySeed('2026-11-27') });
ok('consecutive daily boards differ', JSON.stringify(da.grid) !== JSON.stringify(db.grid));
ok('bad difficulty falls back to regular', generatePuzzle('nightmare').difficulty === 'regular');
}
// ── Solver soundness ─────────────────────────────────────────────────────────
// Dig random unique boards with no tier limit (many need techniques beyond the
// solver's), run the solver to where it stops, and check it never placed a
// wrong digit or eliminated the true one. This exercises every technique.
section('Solver soundness');
{
const base = puzzles.brutal.concat(puzzles.hard);
let stuck = 0, solved = 0, wrongPlace = 0, wrongElim = 0;
const boards = QUICK ? 30 : 120;
let k = 0;
for (let b = 0; b < boards; b++) {
const sol = base[b % base.length].solution;
const g = clone(sol);
const cells = [];
for (let i = 0; i < 81; i++) cells.push(i);
let s = 1234 + b * 7919;
const rnd = () => { s = (s * 16807) % 2147483647; return s / 2147483647; };
for (let i = cells.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [cells[i], cells[j]] = [cells[j], cells[i]]; }
for (const i of cells) {
const r = Math.floor(i / 9), c = i % 9, v = g[r][c];
g[r][c] = 0;
if (countSolutions(g) !== 1) g[r][c] = v;
}
const res = gradePuzzle(g);
if (res.solved) solved++; else stuck++;
for (let r = 0; r < N; r++)
for (let c = 0; c < N; c++) {
const v = res.grid[r][c];
if (v && v !== sol[r][c]) wrongPlace++;
if (!v && !res.candidates[r][c].includes(sol[r][c])) wrongElim++;
}
k++;
}
console.log(` ${k} minimal boards: ${solved} solved by logic, ${stuck} stuck`);
ok('no wrong placements', wrongPlace === 0, `${wrongPlace}`);
ok('no true digit ever eliminated', wrongElim === 0, `${wrongElim}`);
ok('some minimal boards need more than the solver knows (tests partial runs)', stuck > 0);
// fixtures
const p = puzzles.regular[0];
const oneGap = clone(p.solution); oneGap[4][4] = 0;
ok('one missing digit: tier 1', gradePuzzle(oneGap).tier === 1 && gradePuzzle(oneGap).solved);
const empty = Array.from({ length: 9 }, () => Array(9).fill(0));
ok('empty grid: not solvable by logic', !gradePuzzle(empty).solved);
ok('empty grid: many solutions', countSolutions(empty) === 2);
const broken = clone(p.solution); broken[0][0] = broken[0][1]; broken[5][5] = 0;
ok('broken grid: no solutions', countSolutions(broken) === 0 && !gradePuzzle(broken).solved);
const twoWay = clone(p.solution);
// a deadly rectangle: find two rows/cols in one band forming a swap
let found = false;
outer: for (let r1 = 0; r1 < 9; r1++) for (let r2 = r1 + 1; r2 < 9; r2++) {
if (Math.floor(r1 / 3) !== Math.floor(r2 / 3)) continue;
for (let c1 = 0; c1 < 9; c1++) for (let c2 = c1 + 1; c2 < 9; c2++) {
const s = p.solution;
if (s[r1][c1] === s[r2][c2] && s[r1][c2] === s[r2][c1]) {
twoWay[r1][c1] = twoWay[r1][c2] = twoWay[r2][c1] = twoWay[r2][c2] = 0;
found = true; break outer;
}
}
}
if (found) ok('deadly rectangle: two solutions, not logic-solvable', countSolutions(twoWay) === 2 && !gradePuzzle(twoWay).solved);
}
// ── Board helpers ────────────────────────────────────────────────────────────
section('Board helpers');
{
ok('20 peers per cell', peers(4, 4).length === 20 && peers(0, 8).length === 20);
ok('peers exclude the cell', !peers(2, 3).some(p => p.r === 2 && p.c === 3));
ok('boxOf', boxOf(0, 0) === 0 && boxOf(4, 4) === 4 && boxOf(8, 8) === 8 && boxOf(2, 6) === 2 && boxOf(6, 2) === 6);
ok('unitCells box 5', JSON.stringify(unitCells('box', 5)[0]) === '{"r":3,"c":6}' && unitCells('box', 5).length === 9);
const p = puzzles.easy[0];
ok('no conflicts in a puzzle or a solution', findConflicts(p.grid).size === 0 && findConflicts(p.solution).size === 0);
const g = clone(p.grid);
let er = -1, ec = -1;
outer: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!g[r][c]) { er = r; ec = c; break outer; }
// duplicate a digit already in this row
const rowVal = g[er].find(v => v);
g[er][ec] = rowVal;
const conf = findConflicts(g);
const other = g[er].findIndex((v, c) => v === rowVal && c !== ec);
ok('row clash marks both cells', conf.has(`${er},${ec}`) && conf.has(`${er},${other}`));
ok('only clashing cells are marked', [...conf].every(k => { const [r, c] = k.split(',').map(Number); return g[r][c] === rowVal; }));
const counts = digitCounts(p.solution);
ok('digitCounts on a solution', counts.slice(1).every(n => n === 9) && counts[0] === 0);
ok('completedUnits: solution has all 27', completedUnits(p.solution).length === 27 && completedUnits(p.solution, p.solution).length === 27);
const almost = clone(p.solution); almost[0][0] = 0;
ok('completedUnits: a gap removes its row, column and box', completedUnits(almost).length === 24);
const swapped = clone(p.solution);
[swapped[0][0], swapped[0][1]] = [swapped[0][1], swapped[0][0]];
const loose = completedUnits(swapped).map(u => u.key);
const strict = completedUnits(swapped, p.solution).map(u => u.key);
ok('completedUnits: a swapped pair still "fills" row 0 without the solution…', loose.includes('row0'));
ok('…but not with it', !strict.includes('row0'));
ok('easy tiers', isEasyTier('very-easy') && isEasyTier('easy') && !isEasyTier('regular') && !isEasyTier('brutal'));
ok('editions run Mon → Sat', EDITION['very-easy'].day === 'Monday' && EDITION.brutal.day === 'Saturday' && EDITION.hard.stars === 4);
ok('longDate', longDate('2026-11-26') === 'THURSDAY, NOVEMBER 26, 2026');
}
// ── Hints + scoring ───────────────────────────────────────────────────────────
section('Hints');
{
const p = puzzles.regular[1];
const givens = p.grid.map(row => row.map(v => v !== 0));
const g = clone(p.grid);
let empties = 0;
for (let i = 0; i < 50; i++) {
const h = getHintCell(g, p.solution, givens);
if (h && !givens[h.r][h.c] && g[h.r][h.c] === 0 && !h.fix) empties++;
}
ok('hint picks an empty, non-given cell', empties === 50);
const full = clone(p.solution);
let wr = -1, wc = -1;
outer: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!givens[r][c]) { wr = r; wc = c; break outer; }
full[wr][wc] = full[wr][wc] === 1 ? 2 : 1;
const h = getHintCell(full, p.solution, givens);
ok('hint fixes a wrong entry on a full board', h && h.r === wr && h.c === wc && h.fix === true);
const part = clone(p.grid);
part[wr][wc] = p.solution[wr][wc] === 1 ? 2 : 1;
let fixFirst = true;
for (let i = 0; i < 20; i++) { const x = getHintCell(part, p.solution, givens); if (x.r !== wr || x.c !== wc) fixFirst = false; }
ok('wrong entries are fixed before empties are filled', fixFirst);
ok('no hint on a solved board', getHintCell(clone(p.solution), p.solution, givens) === null);
ok('isBoardComplete', isBoardComplete(p.solution, p.solution) && !isBoardComplete(p.grid, p.solution));
ok('scores', calcScore('very-easy', 9) === 10 && calcScore('regular', 2) === 32 && calcScore('brutal', 0) === 100 && calcScore('regular', 99) === 0);
}
// ── Undo / redo ───────────────────────────────────────────────────────────────
section('Undo / redo');
{
const h = makeHistory();
const g = [[0, 0]];
const apply = (e, dir) => { g[e.r][e.c] = dir === 'undo' ? e.from : e.to; };
const edit = (c, to) => { const e = { r: 0, c, from: g[0][c], to }; pushEdit(h, e); g[0][c] = to; };
edit(0, 1); edit(1, 2); edit(0, 3);
ok('three edits undoable', canUndo(h) && !canRedo(h));
apply(undoEdit(h), 'undo');
ok('undo restores the previous value', g[0][0] === 1);
apply(undoEdit(h), 'undo'); apply(undoEdit(h), 'undo');
ok('undo all the way back', g[0][0] === 0 && g[0][1] === 0 && !canUndo(h));
ok('nothing left to undo returns null', undoEdit(h) === null);
apply(redoEdit(h), 'redo'); apply(redoEdit(h), 'redo');
ok('redo replays in order', g[0][0] === 1 && g[0][1] === 2 && canRedo(h));
edit(1, 4);
ok('a new edit clears redo', !canRedo(h));
pushMarker(h);
ok('a hint marker blocks undo', !canUndo(h) && undoEdit(h) === null);
edit(0, 2);
apply(undoEdit(h), 'undo');
ok('edits after a hint undo only back to the hint', !canUndo(h) && g[0][0] === 1);
const big = makeHistory();
for (let i = 0; i < 700; i++) pushEdit(big, { r: 0, c: 0, from: 0, to: 1 });
ok('history capped at 500', big.undo.length === 500);
}
// ── Save / resume ─────────────────────────────────────────────────────────────
section('Save / resume');
{
const p = puzzles.regular[2];
const givens = p.grid.map(row => row.map(v => v !== 0));
const grid = clone(p.grid);
let er = -1, ec = -1;
outer: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!givens[r][c]) { er = r; ec = c; break outer; }
grid[er][ec] = p.solution[er][ec];
const history = makeHistory(); pushEdit(history, { r: er, c: ec, from: 0, to: grid[er][ec] });
const base = {
difficulty: 'regular', daily: '2026-11-26', grid, solution: p.solution, givens,
cellState: grid.map(row => row.map(() => 0)), history, elapsed: 61234.6, hintsLeft: 4, hintsUsed: 1,
mistakes: 2, revealed: false, moves: 7, puzzleNo: 4321, tier: 3, hinted: ['0,0', '9,9', 'bogus'],
};
const s = parseSave(serialiseSave(base));
ok('round-trips', s && s.difficulty === 'regular' && s.daily === '2026-11-26' && JSON.stringify(s.grid) === JSON.stringify(grid));
ok('keeps clock, hints, mistakes, moves, number, tier', s.elapsed === 61235 && s.hintsLeft === 4 && s.hintsUsed === 1 && s.mistakes === 2 && s.moves === 7 && s.puzzleNo === 4321 && s.tier === 3);
ok('keeps history', s.history.undo.length === 1 && s.history.undo[0].to === grid[er][ec]);
ok('filters bad hinted keys', JSON.stringify(s.hinted) === '["0,0"]');
ok('Infinity hints survive', parseSave(serialiseSave({ ...base, difficulty: 'easy', hintsLeft: Infinity })).hintsLeft === Infinity);
ok('zero hints stay zero', parseSave(serialiseSave({ ...base, difficulty: 'hard', hintsLeft: 0 })).hintsLeft === 0);
ok('every difficulty accepted', DIFFS.every(d => parseSave(serialiseSave({ ...base, difficulty: d }))?.difficulty === d));
ok('missing → null', parseSave(null) === null && parseSave('') === null);
ok('garbage JSON → null', parseSave('{oops') === null);
ok('wrong version → null', parseSave(JSON.stringify({ ...JSON.parse(serialiseSave(base)), v: 99 })) === null);
ok('bad difficulty → null', parseSave(serialiseSave({ ...base, difficulty: 'medium' })) === null);
const tampered = clone(grid);
outer2: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (givens[r][c]) { tampered[r][c] = tampered[r][c] === 1 ? 2 : 1; break outer2; }
ok('tampered given → null', parseSave(serialiseSave({ ...base, grid: tampered })) === null);
const badSol = clone(p.solution); [badSol[0][0], badSol[0][1]] = [badSol[0][1], badSol[0][0]];
ok('invalid stored solution → null', parseSave(serialiseSave({ ...base, solution: badSol, givens: givens.map(r => r.map(() => false)) })) === null);
const ten = clone(grid); ten[er][ec] = 10;
ok('digit out of range → null', parseSave(serialiseSave({ ...base, grid: ten })) === null);
ok('short grid → null', parseSave(serialiseSave({ ...base, grid: grid.slice(1) })) === null);
ok('solved board → nothing to resume', parseSave(serialiseSave({ ...base, grid: clone(p.solution) })) === null);
ok('bad daily date dropped', parseSave(serialiseSave({ ...base, daily: 'yesterday' })).daily === null);
ok('missing history rebuilt', parseSave(JSON.stringify({ ...JSON.parse(serialiseSave(base)), history: null })).history.undo.length === 0);
}
// ── Daily ─────────────────────────────────────────────────────────────────────
section('Daily');
{
ok('prevDate', prevDate('2026-11-26') === '2026-11-25' && prevDate('2026-12-01') === '2026-11-30' && prevDate('2027-01-01') === '2026-12-31' && prevDate('2028-03-01') === '2028-02-29');
let r = updateDaily(null, '2026-11-20', '2026-11-20', 300000);
ok('first solve starts a streak', r.streak === 1 && r.rec.solved['2026-11-20'] === 300000 && !r.newBestTime);
r = updateDaily(r.rec, '2026-11-21', '2026-11-21', 250000);
ok('next day extends it', r.streak === 2 && r.rec.bestStreak === 2);
r = updateDaily(r.rec, '2026-11-21', '2026-11-21', 200000);
ok('re-solving today keeps the streak, keeps the faster time', r.streak === 2 && r.rec.solved['2026-11-21'] === 200000 && r.newBestTime);
ok('streak alive the day after', dailyStreakNow(r.rec, '2026-11-22') === 2);
ok('streak dead two days later', dailyStreakNow(r.rec, '2026-11-23') === 0);
r = updateDaily(r.rec, '2026-11-24', '2026-11-24', 280000);
ok('a missed day restarts at 1', r.streak === 1 && r.rec.bestStreak === 2);
ok('blank record', dailyStreakNow(blankDaily(), '2026-11-24') === 0 && dailyStreakNow(null, '2026-11-24') === 0);
}
// ── Layout ────────────────────────────────────────────────────────────────────
section('Layout');
{
const inside = (P, x0, y0, x1, y1) => x0 >= P.x && x1 <= P.x + P.w && y0 >= P.y && y1 <= P.y + P.h;
const SCREEN = { x: 0, y: 0, w: W, h: H };
ok('paper on the table', inside(SCREEN, PAPER.x, PAPER.y, PAPER.x + PAPER.w, PAPER.y + PAPER.h));
ok('grid on the paper', inside(PAPER, GRID_X - 10, GRID_Y - 10, GRID_X + GRID_W + 10, GRID_Y + GRID_W + 10));
ok('grid below the header', GRID_Y - HEADER_Y >= 30);
ok('side column on the paper, clear of the grid', SIDE.x > GRID_X + GRID_W + 16 && SIDE.x + SIDE.w <= PAPER.x + PAPER.w - 20);
ok('print overlay on the paper', inside(PAPER, PRINT.x, PRINT.y, PRINT.x + PRINT.w, PRINT.y + PRINT.h));
ok('pause flap covers the grid and stays on the paper', FLAP.x <= GRID_X && FLAP.y <= GRID_Y && FLAP.x + FLAP.w >= GRID_X + GRID_W && FLAP.y + FLAP.h >= GRID_Y + GRID_W && inside(PAPER, FLAP.x, FLAP.y, FLAP.x + FLAP.w, FLAP.y + FLAP.h));
ok('pad right of the paper, on screen', PAD.x > PAPER.x + PAPER.w && inside(SCREEN, PAD.x, PAD.y, PAD.x + PAD.w, PAD.y + PAD.h));
const pad = { x: PAD.x, y: PAD.y + 70, w: PAD.w, h: PAD.h - 70 }; // below the printed header
ok('pad digits fit under the pad header', inside(pad, RCX - PAD_PITCH - 58, PAD_ROW0 - 58, RCX + PAD_PITCH + 58, PAD_ROW0 + 2 * PAD_PITCH + 58));
ok('eraser on the pad, below the digits', ERASER_Y - 45 > PAD_ROW0 + 2 * PAD_PITCH + 50 && ERASER_Y + 45 <= PAD.y + PAD.h);
ok('stat line clears the digits', PAD.y + 100 + 18 < PAD_ROW0 - 58);
const row1 = [RCX - 225 - 70, RCX + 225 + 70], row2 = [RCX - 210 - 98, RCX + 210 + 98];
ok('button rows right of the paper and on screen', row1[0] > PAPER.x + PAPER.w && row2[0] > PAPER.x + PAPER.w && row1[1] < W && row2[1] < W);
ok('button rows below the pad and on screen', BTN_Y1 - 27 > PAD.y + PAD.h && BTN_Y2 + 27 < H && BTN_Y2 - BTN_Y1 >= 60);
ok('watch face above the pad, on screen', WATCH.y + WATCH.r < PAD.y && WATCH.x - WATCH.r > PAPER.x + PAPER.w);
ok('cup clear of the watch', Math.hypot(CUP.x - WATCH.x, CUP.y - WATCH.y) > WATCH.r + 128);
ok('seven start cards fit the paper', inside(PAPER, 762 - CARD_W / 2, 350 - CARD_H / 2, 762 + CARD_W / 2, 350 + 6 * 104 + CARD_H / 2));
ok('six start cards fit the paper', inside(PAPER, 762 - CARD_W / 2, 356 - CARD_H / 2, 762 + CARD_W / 2, 356 + 5 * 114 + CARD_H / 2));
ok('clipping + buttons fit the screen', CLIP_W + 40 <= W && H / 2 - 50 - (CLIP_H + 60) / 2 >= 0 && H / 2 - 50 + CLIP_H / 2 + 50 + 29 <= H);
ok('cells are a whole pixel size', Number.isInteger(CELL) && GRID_W === 9 * CELL);
}
// ── Art bake (strict fake 2D context) ────────────────────────────────────────
section('Art bake');
{
const colourOk = (c) => typeof c === 'string' && /^(#[0-9a-f]{3,8}|rgba?\([^)]*\)|transparent)$/i.test(c.trim());
const fin = (...a) => a.every(Number.isFinite);
const errors = [];
const check = (cond, what) => { if (!cond) errors.push(what); };
const gradient = () => ({ addColorStop: (o, c) => { check(o >= 0 && o <= 1, `stop offset ${o}`); check(colourOk(c), `stop colour ${c}`); } });
const makeCtx = () => new Proxy({}, {
get(t, k) {
if (k in t) return t[k];
switch (k) {
case 'createLinearGradient': return (...a) => { check(fin(...a), 'linear gradient coords'); return gradient(); };
case 'createRadialGradient': return (x0, y0, r0, x1, y1, r1) => { check(fin(x0, y0, r0, x1, y1, r1) && r0 >= 0 && r1 >= 0, 'radial gradient'); return gradient(); };
case 'createPattern': return () => ({ pattern: true });
case 'createImageData': return (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) });
case 'arc': return (x, y, r) => check(fin(x, y, r) && r >= 0, `arc r=${r}`);
case 'ellipse': return (x, y, rx, ry) => check(fin(x, y, rx, ry) && rx >= 0 && ry >= 0, `ellipse ${rx},${ry}`);
case 'moveTo': case 'lineTo': return (x, y) => check(fin(x, y), 'path point');
case 'quadraticCurveTo': case 'bezierCurveTo': return (...a) => check(fin(...a), 'curve point');
case 'fillRect': case 'strokeRect': case 'rect': return (...a) => check(fin(...a), 'rect');
case 'fillText': return (s, x, y) => check(typeof s === 'string' && fin(x, y), 'text');
default: return () => {};
}
},
set(t, k, v) {
if ((k === 'fillStyle' || k === 'strokeStyle' || k === 'shadowColor') && typeof v === 'string') check(colourOk(v), `${k} ${v}`);
if (k === 'lineWidth' || k === 'globalAlpha' || k === 'shadowBlur') check(Number.isFinite(v) && v >= 0, `${k} ${v}`);
if (k === 'font') check(/^(bold |italic |bold italic )?\d+px /.test(v), `font ${v}`);
t[k] = v; return true;
},
});
const prevDoc = globalThis.document;
globalThis.document = { createElement: () => { const ctx = makeCtx(); return { width: 0, height: 0, getContext: () => ctx }; } };
const added = new Map();
const scene = { textures: { exists: (k) => added.has(k), addCanvas: (k, c) => { added.set(k, c); return {}; }, remove: (k) => added.delete(k) } };
try {
const art = await import('../src/games/sudoku/SudokuArt.js');
art.prepareSudokuArt(scene);
for (const k of ['sudoku-table', 'sudoku-paper', 'sudoku-print', 'sudoku-notepad', 'sudoku-eraser', 'sudoku-watch',
'sudoku-steam', 'sudoku-card', 'sudoku-clipping', 'sudoku-flap'])
ok(`baked ${k}`, added.has(k));
const size = added.size;
art.prepareSudokuArt(scene);
ok('baking twice reuses the textures', added.size === size);
ok('stars()', art.stars(3) === '★★★☆☆');
} catch (err) {
ok('art bake threw', false, err.stack);
}
ok('canvas calls all valid', errors.length === 0, [...new Set(errors)].slice(0, 6).join('; '));
globalThis.document = prevDoc;
}
// ── Scene smoke run (stubbed Phaser) ──────────────────────────────────────────
section('Scene smoke run');
{
const mk = () => {
const fn = function () { return proxy; };
const proxy = new Proxy(fn, {
get(t, k) {
if (k === Symbol.toPrimitive) return () => 0;
if (k === 'then') return undefined;
if (k in t && typeof k === 'symbol') return t[k];
return proxy;
},
apply() { return proxy; },
set() { return true; },
});
return proxy;
};
const store = new Map();
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
const { default: SudokuGame } = await import('../src/games/sudoku/SudokuGame.js');
const sc = Object.create(SudokuGame.prototype);
const stub = mk();
const delayed = [];
Object.assign(sc, {
add: stub, tweens: stub, sound: stub, cameras: stub, textures: stub, input: stub, events: stub, game: stub, cache: stub,
sys: { isActive: () => true },
time: { delayedCall: (ms, f) => { delayed.push(f); return stub; } },
scene: { restart: () => {}, start: () => {} },
});
const flush = () => { while (delayed.length) delayed.shift()(); };
let flourishes = 0, ceremonies = 0;
for (const m of ['buildHeader', 'buildBoard', 'buildSide', 'buildPad', 'buildControls', 'buildProps', 'drawState', 'drawHighlights',
'drawConflicts', 'drawHover', 'drawCursor', 'refreshPad', 'drawPadStrikes', 'refreshButtons', 'refreshStats', 'drawWatch',
'smudge', 'toast', 'showClipping'])
sc[m] = function () {};
sc.unitFlourish = () => { flourishes++; };
sc.winCeremony = () => { ceremonies++; };
const p = generatePuzzle('regular', { seed: 77 });
const pe = generatePuzzle('easy', { seed: 78 });
const boot = (difficulty, puz = p, daily = null) => {
sc.init({ game: { slug: 'sudoku' } });
sc.difficulty = difficulty;
sc.daily = daily;
sc.grid = clone(puz.grid); sc.solution = puz.solution;
sc.givens = puz.grid.map(row => row.map(v => v !== 0));
sc.cellState = Array.from({ length: N }, () => Array(N).fill(0));
sc.hintsLeft = { 'very-easy': Infinity, easy: Infinity, regular: 5, hard: 0, brutal: 0 }[difficulty];
sc.puzzleNo = 1234;
sc.mode = 'play';
sc.refreshAll();
sc._puz = puz;
};
const empties = (puz) => { const out = []; for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!puz.grid[r][c]) out.push({ r, c }); return out; };
try {
// Regular: fill with one wrong entry → the full grid is checked; fix it → win.
boot('regular');
const cells = empties(p);
const bad = cells[0];
const badV = p.solution[bad.r][bad.c] % 9 + 1;
sc.onCellPointer(bad.r, bad.c);
ok('cell-first: tapping a cell selects it', sc.cursor?.r === bad.r && sc.cursor?.c === bad.c && sc.armed == null);
ok('focus digit follows the cursor cell', sc.focusDigit() === 0);
sc.onPadPointer(badV);
ok('cell-first: tapping a pad digit writes it', sc.grid[bad.r][bad.c] === badV && sc.armed == null);
ok('focus digit = the value under the cursor', sc.focusDigit() === badV);
ok('timer starts on the first entry', sc.timerOn === true);
ok('regular: no feedback before the grid is full', sc.cellState[bad.r][bad.c] === 0 && sc.mistakes === 0);
ok('regular: no conflict marks', !sc.showsConflicts());
flourishes = 0;
for (const { r, c } of cells.slice(1)) { sc.cursor = { r, c }; sc.writeCell(r, c, p.solution[r][c]); }
ok('finished rows/columns/boxes flourish', flourishes > 0);
flush();
ok('full grid triggers the check', sc.revealed === true && sc.cellState[bad.r][bad.c] === 2 && sc.mistakes === 1);
ok('no win with a mistake on the grid', !sc.gameEnded);
const saved = parseSave(globalThis.localStorage.getItem('sudoku-save'));
ok('progress autosaved', saved && saved.revealed === true && saved.moves === cells.length && saved.puzzleNo === 1234);
sc.doUndo();
ok('undo after the check reverts the last entry', sc.grid[cells.at(-1).r][cells.at(-1).c] === 0);
sc.doRedo();
sc.writeCell(bad.r, bad.c, p.solution[bad.r][bad.c]);
flush();
ok('fixing the last mistake wins', sc.gameEnded === true && ceremonies === 1);
ok('win clears the save', globalThis.localStorage.getItem('sudoku-save') === null);
const stats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-sudoku') || '{}');
ok('win recorded under regular', stats.regular?.won === 1);
sc.writeCell(bad.r, bad.c, 0);
ok('no edits after the win', sc.grid[bad.r][bad.c] === p.solution[bad.r][bad.c]);
sc.handleWin();
ok('the win fires once', ceremonies === 1 && JSON.parse(globalThis.localStorage.getItem('solitaire-stats-sudoku')).regular.won === 1);
// Easy: immediate checks + mistakes; digit-first input.
boot('easy', pe);
const e = empties(pe);
ok('easy: conflict marks on', sc.showsConflicts() && sc.isChecking());
sc.onPadPointer(5);
ok('digit-first: a pad digit with no cell selected arms it', sc.armed === 5);
ok('armed digit is the focus digit', sc.focusDigit() === 5);
{
const g0 = (() => { for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (pe.grid[r][c] && pe.grid[r][c] !== 5) return { r, c }; })();
sc.cursor = g0;
ok('the pad digit outranks the value under the cursor', sc.focusDigit() === 5);
sc.cursor = null;
}
const t = e[0];
const wrong = p.solution[t.r][t.c] === 0 ? 1 : (pe.solution[t.r][t.c] % 9) + 1;
sc.armed = wrong;
sc.onCellPointer(t.r, t.c);
ok('easy: a wrong entry is marked and counted', sc.cellState[t.r][t.c] === 2 && sc.mistakes === 1);
sc.onCellPointer(t.r, t.c);
ok('armed digit on the same value erases', sc.grid[t.r][t.c] === 0);
sc.armed = pe.solution[t.r][t.c];
sc.onCellPointer(t.r, t.c);
ok('easy: a right entry is marked right', sc.cellState[t.r][t.c] === 1 && sc.mistakes === 1);
sc.onPadPointer(sc.armed);
ok('tapping the armed digit disarms it', sc.armed == null);
const given = (() => { for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (pe.grid[r][c]) return { r, c }; })();
sc.armed = (pe.grid[given.r][given.c] % 9) + 1;
sc.onCellPointer(given.r, given.c);
ok('givens cannot be overwritten', sc.grid[given.r][given.c] === pe.grid[given.r][given.c]);
ok('tapping a given picks its digit on the pad', sc.armed === pe.grid[given.r][given.c]);
sc.armed = null; sc.cursor = null;
sc.onCellPointer(given.r, given.c);
ok('…with nothing armed too', sc.armed === pe.grid[given.r][given.c] && sc.focusDigit() === sc.armed);
const target = e.find(({ r, c }) => !sc.grid[r][c] && pe.solution[r][c] === sc.armed) ?? e.find(({ r, c }) => !sc.grid[r][c]);
const picked = sc.armed;
sc.onCellPointer(target.r, target.c);
ok('…then tapping an empty square writes it', sc.grid[target.r][target.c] === picked);
sc.writeCell(target.r, target.c, 0);
sc.onCellPointer(given.r, given.c); sc.onCellPointer(given.r, given.c);
ok('tapping the same given twice lets go of it', sc.armed == null && sc.cursor == null);
sc.armed = null;
// Keyboard
sc.cursor = null;
sc.onKey({ key: 'ArrowRight', preventDefault() {} });
ok('arrows place the cursor on the first empty cell', sc.cursor && sc.grid[sc.cursor.r][sc.cursor.c] === 0);
const k0 = { ...sc.cursor };
sc.onKey({ key: String(pe.solution[k0.r][k0.c]), preventDefault() {} });
ok('digit keys write at the cursor', sc.grid[k0.r][k0.c] === pe.solution[k0.r][k0.c]);
sc.onKey({ key: 'Backspace', preventDefault() {} });
ok('Backspace erases', sc.grid[k0.r][k0.c] === 0);
sc.onKey({ key: 'z', ctrlKey: true, preventDefault() {} });
ok('Ctrl+Z undoes', sc.grid[k0.r][k0.c] === pe.solution[k0.r][k0.c]);
sc.onKey({ key: 'y', ctrlKey: true, preventDefault() {} });
ok('Ctrl+Y redoes', sc.grid[k0.r][k0.c] === 0);
sc.onKey({ key: 'ArrowUp', preventDefault() {} });
ok('cursor wraps around the edge', sc.cursor.r === (k0.r + N - 1) % N && sc.cursor.c === k0.c);
sc.onKey({ key: 'Escape', preventDefault() {} });
ok('Esc clears the selection', sc.cursor == null);
sc.onKey({ key: '7', preventDefault() {} });
ok('a digit key with no cursor arms it', sc.armed === 7);
sc.onKey({ key: '7', preventDefault() {} });
ok('…and again disarms it', sc.armed == null);
// Hints lock the cell and block undo past them.
const hintsBefore = sc.hintsUsed;
sc.useHint();
flush();
const hinted = [...sc.hinted][0]?.split(',').map(Number);
ok('hint fills a cell with the answer and locks it', hinted && sc.grid[hinted[0]][hinted[1]] === pe.solution[hinted[0]][hinted[1]] && sc.givens[hinted[0]][hinted[1]]);
ok('hint counted', sc.hintsUsed === hintsBefore + 1);
ok('undo cannot step back past a hint', !canUndo(sc.history));
// Hard + Brutal: no hints at all.
for (const d of ['hard', 'brutal']) {
boot(d);
sc.useHint();
flush();
ok(`${d}: hint does nothing`, sc.hintsUsed === 0 && sc.hinted.size === 0);
}
// Pause blocks input and the clock.
boot('easy', pe);
sc.setPaused(true);
const c0 = empties(pe)[0];
sc.cursor = c0;
sc.onPadPointer(1);
ok('paused: the pad does nothing', sc.grid[c0.r][c0.c] === 0);
sc.onKey({ key: '1', preventDefault() {} });
ok('paused: digit keys do nothing', sc.grid[c0.r][c0.c] === 0);
sc.timerOn = true; sc.elapsed = 0;
sc.update(0, 1000);
ok('paused: the watch stops', sc.elapsed === 0);
sc.setPaused(false);
sc.update(0, 1000);
ok('resumed: the watch runs', sc.elapsed === 1000);
// Daily: a win records the streak.
store.clear();
const today = (await import('../src/games/sudoku/SudokuLogic.js')).todayString();
boot('regular', p, today);
for (const { r, c } of empties(p)) { sc.cursor = { r, c }; sc.writeCell(r, c, p.solution[r][c]); }
flush();
const rec = JSON.parse(globalThis.localStorage.getItem('sudoku-daily') || 'null');
ok('daily win records the day + streak', sc.gameEnded && rec?.solved?.[today] != null && rec.streak === 1);
const dstats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-sudoku') || '{}');
ok('daily stats kept apart from Wednesday', dstats.daily?.won === 1 && !dstats.regular);
} catch (err) {
ok('scene smoke run threw', false, err.stack);
}
}
// ── Render paths (real drawing code, stubbed Phaser) ─────────────────────────
// The smoke run above stubs the renderers; this one runs them for real against
// a do-anything `add`/`tweens` so typos and bad references surface.
section('Render paths');
{
const mk = () => {
const fn = function () { return proxy; };
const proxy = new Proxy(fn, {
get(t, k) {
if (k === Symbol.toPrimitive) return () => 0;
if (k === 'then') return undefined;
if (k === 'width' || k === 'height') return 100;
if (k in t && typeof k === 'symbol') return t[k];
return proxy;
},
apply() { return proxy; },
set() { return true; },
});
return proxy;
};
const Art = await import('../src/games/sudoku/SudokuArt.js');
// the Node phaser stand-in's Container has no destroy()
if (!Art.NewsButton.prototype.destroy) Art.NewsButton.prototype.destroy = function () {};
const { default: SudokuGame } = await import('../src/games/sudoku/SudokuGame.js');
const stub = mk();
const delayed = [];
const sc = Object.create(SudokuGame.prototype);
Object.assign(sc, {
add: stub, tweens: stub, sound: stub, cameras: stub, textures: stub, input: stub, events: stub, game: stub, cache: stub,
sys: { isActive: () => true },
time: { delayedCall: (ms, f) => { delayed.push(f); return stub; } },
scene: { restart: () => {}, start: () => {} },
});
const flush = () => { let n = 0; while (delayed.length && n++ < 200) delayed.shift()(); };
const step = (name, f) => { try { f(); ok(name, true); } catch (err) { ok(name, false, err.stack.split('\n').slice(0, 3).join(' | ')); } };
globalThis.localStorage.removeItem('sudoku-save');
const boot = (difficulty, puz) => {
sc.init({ game: { slug: 'sudoku' } });
sc.difficulty = difficulty;
sc.grid = clone(puz.grid); sc.solution = puz.solution;
sc.givens = puz.grid.map(r => r.map(v => v !== 0)); sc.cellState = puz.grid.map(r => r.map(() => 0));
sc.hintsLeft = { 'very-easy': Infinity, easy: Infinity, regular: 5, hard: 0, brutal: 0 }[difficulty];
sc.puzzleNo = 4444;
};
const p = generatePuzzle('easy', { seed: 5 });
const empt = []; for (let r = 0; r < 9; r++) for (let c = 0; c < 9; c++) if (!p.grid[r][c]) empt.push({ r, c });
sc.init({ game: { slug: 'sudoku' } });
step('props + watch', () => { sc.buildProps(); sc.drawWatch(); });
step('start page', () => sc.buildStart());
boot('easy', p);
step('play page', () => sc.buildPlay());
step('select, write a clash, conflicts', () => { const { r, c } = empt[0]; sc.onCellPointer(r, c); sc.onPadPointer(p.grid[r].find(v => v)); sc.drawConflicts(); });
step('erase', () => sc.onKey({ key: 'Backspace', preventDefault() {} }));
step('armed digit + eraser rings', () => { sc.cursor = null; sc.onPadPointer(0); sc.onPadPointer(3); sc.onPadPointer(3); });
step('pause + resume', () => { sc.timerOn = true; sc.setPaused(true); sc.setPaused(false); });
step('hint', () => { sc.useHint(); flush(); });
step('guide modal', () => { sc.openGuide(); sc.modal.close(); });
step('confirm modal', () => { sc.confirm('t', 'b', 'y', () => {}); sc.modal.close(); });
step('toast', () => sc.toast('hello'));
step('start page with a resume card', () => { sc.saveGame(); sc.mode = 'start'; sc.buildStart(); sc.mode = 'play'; });
step('finish → ceremony → clipping', () => {
for (const { r, c } of empt) if (sc.grid[r][c] !== p.solution[r][c]) { sc.cursor = { r, c }; sc.writeCell(r, c, p.solution[r][c]); }
flush();
if (!sc.gameEnded) throw new Error('did not win');
});
const q = generatePuzzle('regular', { seed: 9 });
boot('regular', q);
step('regular: fill with a mistake → checked grid', () => {
sc.mode = 'play'; sc.buildPlay();
const e = []; for (let r = 0; r < 9; r++) for (let c = 0; c < 9; c++) if (!q.grid[r][c]) e.push({ r, c });
sc.writeCell(e[0].r, e[0].c, q.solution[e[0].r][e[0].c] % 9 + 1);
for (const { r, c } of e.slice(1)) sc.writeCell(r, c, q.solution[r][c]);
flush();
if (!sc.revealed || sc.mistakes !== 1) throw new Error('no check');
});
globalThis.localStorage.removeItem('sudoku-save');
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);