Rework Sudoku as "Sunday Paper Café" with canvas art and full play flow

- Add SudokuArt.js: bake all café-themed textures (table, paper, grid, notepad, watch, eraser, clippings) to canvases at runtime; no image assets
- Rewrite SudokuGame.js around the new layout: start page with edition cards and daily puzzle, play screen with cell/digit-first input, keyboard controls, undo/redo, hints, pause flap, win ceremony + solved clipping, autosave/resume, stats and daily streak tracking
- Expand SudokuLogic.js with pure helpers (geometry, conflicts, completed units, history, save validation, daily streak) shared by the scene and the verify tool
- Replace the old generator with a technique-tiered engine: bitmask backtracking solution counting, logic-solver grading (naked/hidden singles, locked candidates, pairs/triples, X-Wing/Swordfish/XY-Wing), seeded deterministic generation for the Daily edition
- Add seed query param to /words/sudoku/start route
- Add tools/verifySudoku.js: headless test suite covering generator correctness and uniqueness, solver soundness, board helpers, hints, undo/redo, save/resume, daily streaks, layout invariants, art bake against a strict fake 2D context, and stubbed-Phaser scene smoke runs
This commit is contained in:
Brian Fertig 2026-11-26 09:44:16 -07:00
parent 9c35504760
commit da558f2df9
No known key found for this signature in database
6 changed files with 3358 additions and 593 deletions

View File

@ -0,0 +1,767 @@
// Sudoku art — the Sunday Paper Café, baked to canvases (no image files).
//
// sudoku-table 1920×1080: marble café table in window light, the back
// section of the paper peeking out, croissant plate, pencil,
// sugar packets, the coffee cup + saucer
// sudoku-paper the front page (masthead, rules, section band), placed at PAPER
// sudoku-print the printed puzzle: header rules, the 9×9 grid, the side
// column with filler copy and a small ad (play screen only)
// sudoku-notepad café guest-check pad that holds the number pad
// sudoku-eraser pink eraser (the erase button)
// sudoku-watch wristwatch (the timer face; hands are drawn by the scene)
// sudoku-steam soft wisp for the coffee steam
// sudoku-card newsprint clipping for the start-page editions
// sudoku-clipping the cut-out "Solved" clipping with a push pin
// sudoku-flap the folded-over page shown while paused
//
// Also exports the layout constants and NewsButton (a paper-slip button).
import * as Phaser from 'phaser';
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
// ── Layout ────────────────────────────────────────────────────────────────────
export const W = 1920, H = 1080;
export const PAPER = { x: 262, y: 24, w: 1000, h: 1032 };
export const PAPER_CX = PAPER.x + PAPER.w / 2; // 762
export const CELL = 80;
export const GRID_W = 9 * CELL; // 720
export const GRID_X = PAPER.x + 52; // 314
export const GRID_Y = 308;
export const SIDE = { x: GRID_X + GRID_W + 34, w: 160 }; // side column 1068..1228
export const SIDE_CX = SIDE.x + SIDE.w / 2; // 1148
export const TITLE_Y = 98;
export const DATELINE_Y = 172;
export const BAND_Y = 216;
export const HEADER_Y = 274;
export const PRINT = { x: GRID_X - 16, y: 248, w: PAPER.x + PAPER.w - 24 - (GRID_X - 16), h: 1044 - 248 };
export const RCX = 1592; // centre of the table area right of the paper
export const WATCH = { x: 1412, y: 150, r: 78 };
export const CUP = { x: 1772, y: 156 };
export const PAD = { x: RCX - 220, y: 298, w: 440, h: 584 };
export const PAD_PITCH = 124;
export const PAD_ROW0 = 476; // centre y of digits 1–3
export const ERASER_Y = 830;
export const BTN_Y1 = 934, BTN_Y2 = 1010;
export const CARD_W = 880, CARD_H = 96;
export const CLIP_W = 860, CLIP_H = 600;
export const FLAP = { x: GRID_X - 26, y: GRID_Y - 26, w: GRID_W + 52, h: GRID_W + 52 };
export const SERIF = 'Georgia, "Times New Roman", "Liberation Serif", "DejaVu Serif", serif';
export const INK = '#1f1d1a';
export const INK_N = 0x1f1d1a;
export const GRAPHITE = '#3d4046';
export const GRAPHITE_N = 0x3d4046;
export const FADED = '#6e675c';
export const RED_INK = '#b3352a';
export const RED_INK_N = 0xb3352a;
export const HIGHLIGHT_N = 0xf3d35a; // highlighter yellow
export const NEWSPRINT = '#efe9da';
let seed = 11;
const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
const jit = (a) => (rnd() - 0.5) * 2 * a;
const font = (px, weight = '') => `${weight ? `${weight} ` : ''}${px}px ${SERIF}`;
// Grey bars standing in for body copy.
function greek(ctx, x, y, w, h, { line = 12, alpha = 0.32, indentEvery = 7 } = {}) {
let k = 0;
for (let ly = y; ly < y + h - 4; ly += line, k++) {
const last = k % indentEvery === indentEvery - 1;
const indent = k % indentEvery === 0 ? 12 : 0;
const len = last ? w * (0.35 + rnd() * 0.4) : w - indent - rnd() * 6;
ctx.fillStyle = `rgba(40,36,30,${alpha * (0.75 + rnd() * 0.25)})`;
let px = x + indent;
while (px < x + indent + len) {
const word = 8 + rnd() * 26;
ctx.fillRect(px, ly, Math.min(word, x + indent + len - px), 4);
px += word + 4;
}
}
}
// ── Table ────────────────────────────────────────────────────────────────────
function marble(ctx) {
const g = ctx.createLinearGradient(0, 0, W, H);
g.addColorStop(0, '#f1ede6'); g.addColorStop(0.55, '#e6e1d8'); g.addColorStop(1, '#d6d0c5');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
// cloudy patches
for (let i = 0; i < 40; i++) {
const x = rnd() * W, y = rnd() * H, r = 80 + rnd() * 260;
const cg = ctx.createRadialGradient(x, y, 1, x, y, r);
cg.addColorStop(0, `rgba(${rnd() < 0.5 ? '150,145,138' : '255,255,252'},${0.06 + rnd() * 0.08})`);
cg.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = cg;
ctx.fillRect(x - r, y - r, r * 2, r * 2);
}
// veins: long wandering strokes with fine branches
for (let v = 0; v < 14; v++) {
let x = rnd() * W, y = rnd() * H;
let a = rnd() * Math.PI * 2;
const dark = rnd() < 0.7;
ctx.strokeStyle = dark ? `rgba(110,104,98,${0.16 + rnd() * 0.18})` : `rgba(190,170,140,${0.18 + rnd() * 0.14})`;
ctx.lineWidth = 0.8 + rnd() * 2.4;
ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(x, y);
const steps = 40 + Math.floor(rnd() * 60);
for (let s = 0; s < steps; s++) {
a += jit(0.45);
x += Math.cos(a) * 18; y += Math.sin(a) * 18;
ctx.lineTo(x, y);
if (rnd() < 0.08) {
ctx.stroke();
ctx.save();
ctx.lineWidth = 0.6;
ctx.beginPath(); ctx.moveTo(x, y);
let bx = x, by = y, ba = a + jit(1.2);
for (let t = 0; t < 10; t++) { ba += jit(0.5); bx += Math.cos(ba) * 12; by += Math.sin(ba) * 12; ctx.lineTo(bx, by); }
ctx.stroke();
ctx.restore();
ctx.beginPath(); ctx.moveTo(x, y);
}
}
ctx.stroke();
}
ctx.fillStyle = noisePattern(ctx, 180, 10);
ctx.fillRect(0, 0, W, H);
}
// Late-morning sun through a café window: bright shafts with mullion shadows.
function windowLight(ctx) {
ctx.save();
ctx.globalCompositeOperation = 'source-over';
const shaft = (x0, w, alpha) => {
ctx.fillStyle = `rgba(255,236,190,${alpha})`;
ctx.beginPath();
ctx.moveTo(x0, 0); ctx.lineTo(x0 + w, 0);
ctx.lineTo(x0 + w - 520, H); ctx.lineTo(x0 - 520, H);
ctx.closePath(); ctx.fill();
};
shaft(1180, 360, 0.11);
shaft(1600, 300, 0.09);
shaft(2000, 320, 0.08);
// mullion shadows between the panes
ctx.fillStyle = 'rgba(60,50,40,0.05)';
for (const x0 of [1550, 1930]) {
ctx.beginPath();
ctx.moveTo(x0, 0); ctx.lineTo(x0 + 40, 0); ctx.lineTo(x0 - 480, H); ctx.lineTo(x0 - 520, H);
ctx.closePath(); ctx.fill();
}
// vignette
const vg = ctx.createRadialGradient(W * 0.55, H * 0.45, 300, W * 0.55, H * 0.45, W * 0.75);
vg.addColorStop(0, 'rgba(0,0,0,0)'); vg.addColorStop(1, 'rgba(40,30,20,0.32)');
ctx.fillStyle = vg;
ctx.fillRect(0, 0, W, H);
ctx.restore();
}
// The back section of the paper, folded, sticking out from under the front page.
function backSection(ctx) {
ctx.save();
ctx.translate(PAPER.x + 470, PAPER.y + 530);
ctx.rotate(-0.045);
ctx.shadowColor = 'rgba(0,0,0,0.28)'; ctx.shadowBlur = 16; ctx.shadowOffsetX = -4; ctx.shadowOffsetY = 6;
ctx.fillStyle = '#e8e1cf';
ctx.fillRect(-590, -500, 1000, 1000);
ctx.shadowColor = 'transparent';
ctx.save();
ctx.beginPath(); ctx.rect(-590, -500, 1000, 1000); ctx.clip();
for (let col = 0; col < 2; col++) greek(ctx, -575 + col * 64, -470, 56, 940, { line: 11, alpha: 0.22 });
ctx.fillStyle = 'rgba(40,36,30,0.55)';
ctx.fillRect(-575, -490, 120, 8);
ctx.fillStyle = noisePattern(ctx, 90, 14); ctx.fillRect(-590, -500, 1000, 1000);
ctx.restore();
ctx.restore();
}
function pencil(ctx, x, y, angle, len = 380) {
ctx.save();
ctx.translate(x, y); ctx.rotate(angle);
ctx.shadowColor = 'rgba(0,0,0,0.35)'; ctx.shadowBlur = 8; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 6;
ctx.fillStyle = '#e8b830';
ctx.fillRect(-len / 2, -11, len - 60, 22);
ctx.shadowColor = 'transparent';
// facets
ctx.fillStyle = 'rgba(255,240,170,0.55)'; ctx.fillRect(-len / 2, -11, len - 60, 6);
ctx.fillStyle = 'rgba(150,100,10,0.35)'; ctx.fillRect(-len / 2, 5, len - 60, 6);
// ferrule + eraser
ctx.fillStyle = '#b9b3a6'; ctx.fillRect(-len / 2 - 26, -11, 26, 22);
ctx.strokeStyle = 'rgba(90,84,76,0.6)'; ctx.lineWidth = 1.5;
for (let k = 0; k < 4; k++) { ctx.beginPath(); ctx.moveTo(-len / 2 - 22 + k * 6, -11); ctx.lineTo(-len / 2 - 22 + k * 6, 11); ctx.stroke(); }
ctx.fillStyle = '#e48c8c'; rr(ctx, -len / 2 - 52, -11, 28, 22, 6); ctx.fill();
// sharpened cone + lead
const tip = len / 2 - 60;
ctx.fillStyle = '#e9cfa1';
ctx.beginPath(); ctx.moveTo(tip, -11); ctx.lineTo(tip + 50, -2); ctx.lineTo(tip + 50, 2); ctx.lineTo(tip, 11); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#3a3a3e';
ctx.beginPath(); ctx.moveTo(tip + 36, -3.6); ctx.lineTo(tip + 60, 0); ctx.lineTo(tip + 36, 3.6); ctx.closePath(); ctx.fill();
ctx.restore();
}
function croissantPlate(ctx, x, y) {
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.3)'; ctx.shadowBlur = 22; ctx.shadowOffsetX = 6; ctx.shadowOffsetY = 10;
ctx.fillStyle = '#f8f6f1';
ctx.beginPath(); ctx.arc(x, y, 158, 0, Math.PI * 2); ctx.fill();
ctx.restore();
const pg = ctx.createRadialGradient(x - 30, y - 30, 20, x, y, 158);
pg.addColorStop(0, '#ffffff'); pg.addColorStop(0.75, '#efece4'); pg.addColorStop(1, '#d9d4c8');
ctx.fillStyle = pg;
ctx.beginPath(); ctx.arc(x, y, 156, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(30,90,120,0.55)'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.arc(x, y, 142, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(0,0,0,0.06)'; ctx.lineWidth = 8;
ctx.beginPath(); ctx.arc(x, y, 104, 0, Math.PI * 2); ctx.stroke();
// croissant: overlapping crescent segments
ctx.save();
ctx.translate(x + 6, y - 4); ctx.rotate(-0.5);
ctx.shadowColor = 'rgba(80,40,0,0.35)'; ctx.shadowBlur = 10; ctx.shadowOffsetY = 5;
const segs = 7;
for (let k = 0; k < segs; k++) {
const t = k / (segs - 1);
const a = Math.PI * (0.15 + 0.7 * t);
const sx = Math.cos(a) * 70, sy = -Math.sin(a) * 70 + 40;
const size = 18 + Math.sin(t * Math.PI) * 26;
const sg = ctx.createRadialGradient(sx - size * 0.3, sy - size * 0.4, 2, sx, sy, size);
sg.addColorStop(0, '#f0c070'); sg.addColorStop(0.6, '#c8843a'); sg.addColorStop(1, '#8e5420');
ctx.fillStyle = sg;
ctx.beginPath(); ctx.ellipse(sx, sy, size, size * 0.8, a, 0, Math.PI * 2); ctx.fill();
}
ctx.shadowColor = 'transparent';
ctx.strokeStyle = 'rgba(110,60,20,0.45)'; ctx.lineWidth = 2;
for (let k = 1; k < segs; k++) {
const t = (k - 0.5) / (segs - 1);
const a = Math.PI * (0.15 + 0.7 * t);
const sx = Math.cos(a) * 70, sy = -Math.sin(a) * 70 + 40;
ctx.beginPath(); ctx.arc(sx, sy, 16 + Math.sin(t * Math.PI) * 18, a + 1.2, a + 2.0); ctx.stroke();
}
ctx.restore();
// crumbs
for (let i = 0; i < 26; i++) {
const a = rnd() * Math.PI * 2, d = 60 + rnd() * 80;
ctx.fillStyle = `rgba(${170 + Math.floor(rnd() * 40)},${110 + Math.floor(rnd() * 30)},50,0.8)`;
ctx.beginPath(); ctx.arc(x + Math.cos(a) * d, y + Math.sin(a) * d, 1 + rnd() * 2.5, 0, Math.PI * 2); ctx.fill();
}
}
function coffeeCup(ctx, x, y) {
// saucer
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.32)'; ctx.shadowBlur = 20; ctx.shadowOffsetX = 6; ctx.shadowOffsetY = 10;
ctx.fillStyle = '#f6f4ef';
ctx.beginPath(); ctx.arc(x, y, 128, 0, Math.PI * 2); ctx.fill();
ctx.restore();
const sg = ctx.createRadialGradient(x - 30, y - 30, 10, x, y, 128);
sg.addColorStop(0, '#ffffff'); sg.addColorStop(0.8, '#ebe7de'); sg.addColorStop(1, '#d3cdc0');
ctx.fillStyle = sg;
ctx.beginPath(); ctx.arc(x, y, 126, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(30,90,120,0.5)'; ctx.lineWidth = 2.5;
ctx.beginPath(); ctx.arc(x, y, 116, 0, Math.PI * 2); ctx.stroke();
// spoon on the saucer
ctx.save();
ctx.translate(x + 30, y + 80); ctx.rotate(-0.35);
ctx.shadowColor = 'rgba(0,0,0,0.25)'; ctx.shadowBlur = 4; ctx.shadowOffsetY = 2;
const spg = ctx.createLinearGradient(-60, -6, -60, 6);
spg.addColorStop(0, '#e4e6ea'); spg.addColorStop(1, '#9ba0a8');
ctx.fillStyle = spg;
rr(ctx, -70, -5, 110, 10, 5); ctx.fill();
ctx.beginPath(); ctx.ellipse(52, 0, 20, 13, 0, 0, Math.PI * 2); ctx.fill();
ctx.restore();
// handle
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.25)'; ctx.shadowBlur = 6; ctx.shadowOffsetY = 3;
ctx.strokeStyle = '#f3f0ea'; ctx.lineWidth = 16; ctx.lineCap = 'round';
ctx.beginPath(); ctx.arc(x - 96, y + 6, 26, Math.PI * 0.55, Math.PI * 1.45); ctx.stroke();
ctx.restore();
// cup
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.3)'; ctx.shadowBlur = 14; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 6;
ctx.fillStyle = '#fbfaf7';
ctx.beginPath(); ctx.arc(x, y, 80, 0, Math.PI * 2); ctx.fill();
ctx.restore();
ctx.strokeStyle = 'rgba(30,90,120,0.55)'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.arc(x, y, 76, 0, Math.PI * 2); ctx.stroke();
// coffee with crema + latte-art heart
const cg = ctx.createRadialGradient(x - 14, y - 16, 4, x, y, 66);
cg.addColorStop(0, '#9a6236'); cg.addColorStop(0.7, '#6b3d1d'); cg.addColorStop(1, '#3e2210');
ctx.fillStyle = cg;
ctx.beginPath(); ctx.arc(x, y, 66, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(245,225,195,0.85)';
ctx.beginPath();
ctx.moveTo(x, y + 30);
ctx.bezierCurveTo(x - 46, y + 2, x - 34, y - 38, x, y - 16);
ctx.bezierCurveTo(x + 34, y - 38, x + 46, y + 2, x, y + 30);
ctx.closePath(); ctx.fill();
ctx.strokeStyle = 'rgba(120,70,35,0.6)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x, y - 30); ctx.lineTo(x, y + 34); ctx.stroke();
// rim highlight
ctx.strokeStyle = 'rgba(255,255,255,0.7)'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.arc(x, y, 72, Math.PI * 1.1, Math.PI * 1.6); ctx.stroke();
}
function sugarPackets(ctx) {
for (const [x, y, a, tone] of [[1866, 372, 0.4, '#f2efe6'], [1834, 404, -0.2, '#e4a8a0']]) {
ctx.save();
ctx.translate(x, y); ctx.rotate(a);
ctx.shadowColor = 'rgba(0,0,0,0.25)'; ctx.shadowBlur = 5; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 3;
ctx.fillStyle = tone; ctx.fillRect(-40, -22, 80, 44);
ctx.shadowColor = 'transparent';
ctx.strokeStyle = 'rgba(0,0,0,0.12)'; ctx.lineWidth = 1;
for (const ex of [-40, 40]) for (let k = -20; k <= 20; k += 4) { ctx.beginPath(); ctx.moveTo(ex, k); ctx.lineTo(ex + (ex < 0 ? 4 : -4), k + 2); ctx.stroke(); }
ctx.fillStyle = 'rgba(80,60,40,0.55)'; ctx.font = font(12, 'bold');
ctx.textAlign = 'center'; ctx.fillText('SUCRE', 0, 4);
ctx.restore();
}
}
function bakeTable(scene) {
seed = 11;
const c = canvas(W, H);
const ctx = c.getContext('2d');
marble(ctx);
windowLight(ctx);
backSection(ctx);
croissantPlate(ctx, 92, 900);
pencil(ctx, 132, 440, -1.36);
sugarPackets(ctx);
coffeeCup(ctx, CUP.x, CUP.y);
scene.textures.addCanvas('sudoku-table', c);
}
// ── Front page ───────────────────────────────────────────────────────────────
const PAD_PX = 20; // shadow margin around paper-like bakes
function newsprint(ctx, x, y, w, h, { tone = NEWSPRINT, noise = 16 } = {}) {
ctx.fillStyle = tone;
ctx.fillRect(x, y, w, h);
const g = ctx.createRadialGradient(x + w / 2, y + h / 2, Math.min(w, h) * 0.3, x + w / 2, y + h / 2, Math.max(w, h) * 0.75);
g.addColorStop(0, 'rgba(255,252,240,0.25)'); g.addColorStop(1, 'rgba(170,140,90,0.2)');
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
// fibres
for (let i = 0; i < (w * h) / 900; i++) {
const fx = x + rnd() * w, fy = y + rnd() * h, a = rnd() * Math.PI;
ctx.strokeStyle = `rgba(120,100,70,${0.05 + rnd() * 0.06})`;
ctx.lineWidth = 0.6;
ctx.beginPath(); ctx.moveTo(fx, fy); ctx.lineTo(fx + Math.cos(a) * 6, fy + Math.sin(a) * 6); ctx.stroke();
}
ctx.fillStyle = noisePattern(ctx, 96, noise);
ctx.fillRect(x, y, w, h);
}
function bakePaper(scene) {
seed = 21;
const c = canvas(PAPER.w + PAD_PX * 2, PAPER.h + PAD_PX * 2);
const ctx = c.getContext('2d');
const x = PAD_PX, y = PAD_PX, w = PAPER.w, h = PAPER.h;
ctx.save();
ctx.shadowColor = 'rgba(30,20,10,0.38)'; ctx.shadowBlur = 18; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 8;
ctx.fillStyle = NEWSPRINT; ctx.fillRect(x, y, w, h);
ctx.restore();
newsprint(ctx, x, y, w, h);
// horizontal fold crease, lit from the window side
const fy = y + h * 0.53;
const fg = ctx.createLinearGradient(0, fy - 10, 0, fy + 10);
fg.addColorStop(0, 'rgba(0,0,0,0)'); fg.addColorStop(0.48, 'rgba(70,55,35,0.10)');
fg.addColorStop(0.52, 'rgba(255,255,245,0.20)'); fg.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = fg; ctx.fillRect(x, fy - 10, w, 20);
const ox = x - PAPER.x, oy = y - PAPER.y; // page → canvas offset
const L = PAPER.x + 30 + ox, R = PAPER.x + PAPER.w - 30 + ox;
ctx.fillStyle = INK; ctx.strokeStyle = INK;
// ears
ctx.lineWidth = 1.2;
ctx.strokeRect(L, PAPER.y + 34 + oy, 150, 66);
ctx.strokeRect(R - 150, PAPER.y + 34 + oy, 150, 66);
ctx.textAlign = 'center';
ctx.font = font(13, 'bold');
ctx.fillText('LATE CITY', L + 75, PAPER.y + 58 + oy);
ctx.fillText('EDITION', L + 75, PAPER.y + 76 + oy);
ctx.font = font(11);
ctx.fillText('Puzzles inside', L + 75, PAPER.y + 92 + oy);
ctx.font = font(13, 'bold');
ctx.fillText('WEATHER', R - 75, PAPER.y + 56 + oy);
ctx.font = font(12);
ctx.fillText('Bright and mild', R - 75, PAPER.y + 74 + oy);
ctx.fillText('High 18° Low 9°', R - 75, PAPER.y + 90 + oy);
// nameplate
ctx.font = font(78, 'bold');
ctx.fillText('The Sunday Courier', PAPER_CX + ox, TITLE_Y + 26 + oy);
// rules: double above the dateline, single below
ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(L, 146 + oy); ctx.lineTo(R, 146 + oy); ctx.stroke();
ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(L, 152 + oy); ctx.lineTo(R, 152 + oy); ctx.stroke();
ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(L, 190 + oy); ctx.lineTo(R, 190 + oy); ctx.stroke();
// section band
ctx.fillStyle = '#23201b';
ctx.fillRect(L, BAND_Y - 18 + oy, R - L, 36);
ctx.fillStyle = 'rgba(239,233,218,0.95)';
ctx.font = font(18, 'bold');
const band = 'P U Z Z L E S · G A M E S · P A S T I M E S';
ctx.fillText(band, PAPER_CX + ox, BAND_Y + 6 + oy);
// ink rub along the band
ctx.fillStyle = noisePattern(ctx, 64, 40);
ctx.fillRect(L, BAND_Y - 18 + oy, R - L, 36);
scene.textures.addCanvas('sudoku-paper', c);
}
// The printed puzzle area (play screen).
function bakePrint(scene) {
seed = 31;
const c = canvas(PRINT.w, PRINT.h);
const ctx = c.getContext('2d');
const ox = -PRINT.x, oy = -PRINT.y;
ctx.strokeStyle = INK; ctx.fillStyle = INK;
// header rule under "SUDOKU"
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(GRID_X + ox, HEADER_Y + 18 + oy); ctx.lineTo(SIDE.x + SIDE.w + ox, HEADER_Y + 18 + oy); ctx.stroke();
// grid: thin cell lines, heavier box lines, a heavy frame. Each line is printed
// twice with a hair of offset so the ink looks pressed rather than drawn.
const line = (x0, y0, x1, y1, wdt, a) => {
for (let pass = 0; pass < 2; pass++) {
ctx.strokeStyle = `rgba(31,29,26,${pass ? a * 0.35 : a})`;
ctx.lineWidth = pass ? wdt + 1.2 : wdt;
const d = pass ? 0.4 : 0;
ctx.beginPath(); ctx.moveTo(x0 + ox + d, y0 + oy + d); ctx.lineTo(x1 + ox + d, y1 + oy + d); ctx.stroke();
}
};
for (let i = 1; i < 9; i++) {
if (i % 3 === 0) continue;
line(GRID_X + i * CELL, GRID_Y, GRID_X + i * CELL, GRID_Y + GRID_W, 1.1, 0.55);
line(GRID_X, GRID_Y + i * CELL, GRID_X + GRID_W, GRID_Y + i * CELL, 1.1, 0.55);
}
for (const i of [3, 6]) {
line(GRID_X + i * CELL, GRID_Y, GRID_X + i * CELL, GRID_Y + GRID_W, 3, 0.92);
line(GRID_X, GRID_Y + i * CELL, GRID_X + GRID_W, GRID_Y + i * CELL, 3, 0.92);
}
ctx.strokeStyle = 'rgba(31,29,26,0.95)'; ctx.lineWidth = 4.5;
ctx.strokeRect(GRID_X + ox, GRID_Y + oy, GRID_W, GRID_W);
// side column: rule, filler copy and a small ad
ctx.strokeStyle = 'rgba(31,29,26,0.55)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(SIDE.x - 17 + ox, GRID_Y + oy); ctx.lineTo(SIDE.x - 17 + ox, GRID_Y + GRID_W + oy); ctx.stroke();
ctx.beginPath(); ctx.moveTo(SIDE.x + ox, 640 + oy); ctx.lineTo(SIDE.x + SIDE.w + ox, 640 + oy); ctx.stroke();
ctx.fillStyle = INK; ctx.font = font(15, 'bold'); ctx.textAlign = 'left';
ctx.fillText('Around Town', SIDE.x + ox, 664 + oy);
greek(ctx, SIDE.x + ox, 678 + oy, SIDE.w, 210, { line: 11, alpha: 0.3 });
const ay = 900;
ctx.strokeStyle = 'rgba(31,29,26,0.8)'; ctx.lineWidth = 2;
ctx.strokeRect(SIDE.x + ox, ay + oy, SIDE.w, GRID_Y + GRID_W - ay);
ctx.lineWidth = 0.8; ctx.strokeRect(SIDE.x + 4 + ox, ay + 4 + oy, SIDE.w - 8, GRID_Y + GRID_W - ay - 8);
ctx.textAlign = 'center'; ctx.fillStyle = INK;
ctx.font = font(17, 'bold italic'); ctx.fillText('Café du Coin', SIDE_CX + ox, ay + 32 + oy);
ctx.font = font(12); ctx.fillText('Fresh croissants', SIDE_CX + ox, ay + 56 + oy);
ctx.fillText('every morning', SIDE_CX + ox, ay + 72 + oy);
ctx.font = font(12, 'italic'); ctx.fillText('— since 1931 —', SIDE_CX + ox, ay + 100 + oy);
scene.textures.addCanvas('sudoku-print', c);
}
// ── Notepad, eraser, watch, steam ────────────────────────────────────────────
function bakeNotepad(scene) {
seed = 41;
const c = canvas(PAD.w + PAD_PX * 2, PAD.h + PAD_PX * 2);
const ctx = c.getContext('2d');
const x = PAD_PX, y = PAD_PX, w = PAD.w, h = PAD.h;
// the torn top edge
const tornTop = () => {
ctx.beginPath();
ctx.moveTo(x, y + 8);
for (let px = x; px <= x + w; px += 9) ctx.lineTo(px, y + 4 + rnd() * 7);
ctx.lineTo(x + w, y + h); ctx.lineTo(x, y + h); ctx.closePath();
};
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.3)'; ctx.shadowBlur = 14; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 7;
ctx.fillStyle = '#eef3e4';
tornTop(); ctx.fill();
ctx.restore();
ctx.save();
tornTop(); ctx.clip();
ctx.fillStyle = '#eef3e4'; ctx.fillRect(x, y, w, h);
// header block
ctx.fillStyle = 'rgba(46,110,80,0.92)';
ctx.font = font(24, 'bold'); ctx.textAlign = 'left';
ctx.fillText('GUEST CHECK', x + 24, y + 46);
ctx.font = font(13); ctx.textAlign = 'right';
ctx.fillText('TABLE 9', x + w - 24, y + 34);
ctx.fillText('No. 0981', x + w - 24, y + 52);
ctx.strokeStyle = 'rgba(46,110,80,0.75)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x + 16, y + 64); ctx.lineTo(x + w - 16, y + 64); ctx.stroke();
ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(x + 16, y + 68); ctx.lineTo(x + w - 16, y + 68); ctx.stroke();
// ruled lines + a price column
ctx.strokeStyle = 'rgba(46,110,80,0.28)'; ctx.lineWidth = 1;
for (let ly = y + 108; ly < y + h - 10; ly += 31) { ctx.beginPath(); ctx.moveTo(x + 12, ly); ctx.lineTo(x + w - 12, ly); ctx.stroke(); }
ctx.strokeStyle = 'rgba(190,70,60,0.35)';
ctx.beginPath(); ctx.moveTo(x + w - 70, y + 72); ctx.lineTo(x + w - 70, y + h); ctx.stroke();
ctx.fillStyle = noisePattern(ctx, 80, 12); ctx.fillRect(x, y, w, h);
ctx.restore();
scene.textures.addCanvas('sudoku-notepad', c);
}
function bakeEraser(scene) {
const c = canvas(170, 100);
const ctx = c.getContext('2d');
ctx.translate(85, 50); ctx.rotate(-0.1);
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.35)'; ctx.shadowBlur = 8; ctx.shadowOffsetX = 3; ctx.shadowOffsetY = 4;
ctx.fillStyle = '#ec9ea4';
ctx.beginPath();
ctx.moveTo(-66, -22); ctx.lineTo(58, -22); ctx.lineTo(70, 0); ctx.lineTo(58, 22); ctx.lineTo(-66, 22);
ctx.quadraticCurveTo(-72, 0, -66, -22); ctx.closePath(); ctx.fill();
ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,0.32)'; rr(ctx, -60, -18, 100, 8, 4); ctx.fill();
ctx.fillStyle = 'rgba(120,40,50,0.5)'; ctx.font = font(13, 'bold'); ctx.textAlign = 'center';
ctx.fillText('ERASER', -4, 6);
ctx.fillStyle = 'rgba(80,80,80,0.12)'; rr(ctx, 30, 6, 34, 12, 5); ctx.fill();
scene.textures.addCanvas('sudoku-eraser', c);
}
function bakeWatch(scene) {
const cw = 220, ch = 340;
const c = canvas(cw, ch);
const ctx = c.getContext('2d');
const x = cw / 2, y = ch / 2, r = WATCH.r;
// leather strap (top and bottom halves)
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.3)'; ctx.shadowBlur = 10; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 6;
const sg = ctx.createLinearGradient(x - 40, 0, x + 40, 0);
sg.addColorStop(0, '#5b3518'); sg.addColorStop(0.5, '#7a4a24'); sg.addColorStop(1, '#5b3518');
ctx.fillStyle = sg;
rr(ctx, x - 38, 8, 76, ch - 16, 14); ctx.fill();
ctx.restore();
ctx.strokeStyle = 'rgba(240,210,170,0.45)'; ctx.lineWidth = 1.2; ctx.setLineDash?.([5, 4]);
for (const dx of [-30, 30]) { ctx.beginPath(); ctx.moveTo(x + dx, 16); ctx.lineTo(x + dx, ch - 16); ctx.stroke(); }
ctx.setLineDash?.([]);
ctx.fillStyle = 'rgba(30,15,5,0.6)';
for (let k = 0; k < 3; k++) { ctx.beginPath(); ctx.arc(x, ch - 40 - k * 22, 4, 0, Math.PI * 2); ctx.fill(); }
// case
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.4)'; ctx.shadowBlur = 12; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 6;
const cg = ctx.createLinearGradient(x - r, y - r, x + r, y + r);
cg.addColorStop(0, '#f4f1ea'); cg.addColorStop(0.5, '#b8b2a4'); cg.addColorStop(1, '#7d776b');
ctx.fillStyle = cg;
ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
ctx.restore();
// crown
ctx.fillStyle = '#a49d8e'; rr(ctx, x + r - 2, y - 9, 14, 18, 3); ctx.fill();
// face
const fg = ctx.createRadialGradient(x - 18, y - 22, 6, x, y, r - 10);
fg.addColorStop(0, '#fffdf5'); fg.addColorStop(1, '#e9e2cf');
ctx.fillStyle = fg;
ctx.beginPath(); ctx.arc(x, y, r - 10, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(40,36,30,0.85)'; ctx.lineCap = 'round';
for (let k = 0; k < 60; k++) {
const a = (k / 60) * Math.PI * 2;
const big = k % 5 === 0;
const r0 = r - (big ? 24 : 18), r1 = r - 14;
ctx.lineWidth = big ? 3 : 1;
ctx.beginPath(); ctx.moveTo(x + Math.sin(a) * r0, y - Math.cos(a) * r0); ctx.lineTo(x + Math.sin(a) * r1, y - Math.cos(a) * r1); ctx.stroke();
}
ctx.fillStyle = 'rgba(40,36,30,0.85)'; ctx.font = font(12, 'bold'); ctx.textAlign = 'center';
ctx.fillText('COURIER', x, y - 22);
// date-window style readout box (the scene writes the elapsed time in it)
ctx.fillStyle = '#f8f4e8'; ctx.strokeStyle = 'rgba(40,36,30,0.5)'; ctx.lineWidth = 1.2;
rr(ctx, x - 34, y + 14, 68, 26, 4); ctx.fill(); ctx.stroke();
// glass glare
ctx.fillStyle = 'rgba(255,255,255,0.22)';
ctx.beginPath(); ctx.ellipse(x - 20, y - 26, 34, 16, -0.6, 0, Math.PI * 2); ctx.fill();
scene.textures.addCanvas('sudoku-watch', c);
}
function bakeSteam(scene) {
const c = canvas(96, 96);
const ctx = c.getContext('2d');
const g = ctx.createRadialGradient(48, 48, 2, 48, 48, 46);
g.addColorStop(0, 'rgba(255,255,255,0.55)'); g.addColorStop(0.5, 'rgba(255,255,255,0.2)'); g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, 96, 96);
scene.textures.addCanvas('sudoku-steam', c);
}
// ── Clippings ────────────────────────────────────────────────────────────────
// A scissor-cut rectangle: edges wander a pixel or two.
function cutPath(ctx, x, y, w, h, amp = 1.6) {
ctx.beginPath();
ctx.moveTo(x + jit(amp), y + jit(amp));
for (let px = x + 14; px < x + w; px += 14) ctx.lineTo(px, y + jit(amp));
ctx.lineTo(x + w + jit(amp), y + jit(amp));
for (let py = y + 14; py < y + h; py += 14) ctx.lineTo(x + w + jit(amp), py);
ctx.lineTo(x + w + jit(amp), y + h + jit(amp));
for (let px = x + w - 14; px > x; px -= 14) ctx.lineTo(px, y + h + jit(amp));
ctx.lineTo(x + jit(amp), y + h + jit(amp));
for (let py = y + h - 14; py > y; py -= 14) ctx.lineTo(x + jit(amp), py);
ctx.closePath();
}
function bakeCard(scene) {
seed = 51;
const c = canvas(CARD_W + 24, CARD_H + 24);
const ctx = c.getContext('2d');
const x = 12, y = 10;
ctx.save();
ctx.shadowColor = 'rgba(30,20,10,0.32)'; ctx.shadowBlur = 9; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 4;
ctx.fillStyle = '#f3eee1';
cutPath(ctx, x, y, CARD_W, CARD_H); ctx.fill();
ctx.restore();
ctx.save();
cutPath(ctx, x, y, CARD_W, CARD_H); ctx.clip();
newsprint(ctx, x, y, CARD_W, CARD_H, { tone: '#f3eee1', noise: 12 });
ctx.strokeStyle = 'rgba(31,29,26,0.6)'; ctx.lineWidth = 1;
ctx.strokeRect(x + 7, y + 7, CARD_W - 14, CARD_H - 14);
// a tiny printed sudoku thumbnail at the left
const tx = x + 22, ty = y + 18, ts = 60;
ctx.strokeStyle = 'rgba(31,29,26,0.75)'; ctx.lineWidth = 2; ctx.strokeRect(tx, ty, ts, ts);
ctx.lineWidth = 0.6;
for (let k = 1; k < 9; k++) {
ctx.lineWidth = k % 3 ? 0.5 : 1.4;
ctx.beginPath(); ctx.moveTo(tx + (k * ts) / 9, ty); ctx.lineTo(tx + (k * ts) / 9, ty + ts); ctx.stroke();
ctx.beginPath(); ctx.moveTo(tx, ty + (k * ts) / 9); ctx.lineTo(tx + ts, ty + (k * ts) / 9); ctx.stroke();
}
ctx.fillStyle = 'rgba(31,29,26,0.55)';
for (let k = 0; k < 22; k++) {
const cx = Math.floor(rnd() * 9), cy = Math.floor(rnd() * 9);
ctx.fillRect(tx + cx * ts / 9 + 2.2, ty + cy * ts / 9 + 1.8, 2.4, 3.2);
}
ctx.restore();
scene.textures.addCanvas('sudoku-card', c);
}
function bakeClipping(scene) {
seed = 61;
const c = canvas(CLIP_W + 40, CLIP_H + 60);
const ctx = c.getContext('2d');
const x = 20, y = 40, w = CLIP_W, h = CLIP_H;
ctx.save();
ctx.shadowColor = 'rgba(20,10,0,0.5)'; ctx.shadowBlur = 24; ctx.shadowOffsetX = 6; ctx.shadowOffsetY = 12;
ctx.fillStyle = NEWSPRINT;
cutPath(ctx, x, y, w, h, 2.2); ctx.fill();
ctx.restore();
ctx.save();
cutPath(ctx, x, y, w, h, 2.2); ctx.clip();
newsprint(ctx, x, y, w, h);
ctx.strokeStyle = INK; ctx.fillStyle = INK;
ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(x + 40, y + 52); ctx.lineTo(x + w - 40, y + 52); ctx.stroke();
ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(x + 40, y + 58); ctx.lineTo(x + w - 40, y + 58); ctx.stroke();
ctx.font = font(15, 'bold'); ctx.textAlign = 'center';
ctx.fillText('T H E S U N D A Y C O U R I E R · P U Z Z L E S', x + w / 2, y + 40);
ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(x + 40, y + 236); ctx.lineTo(x + w - 40, y + 236); ctx.stroke();
ctx.beginPath(); ctx.moveTo(x + 40, y + 380); ctx.lineTo(x + w - 40, y + 380); ctx.stroke();
// column copy along the bottom
for (let k = 0; k < 4; k++) greek(ctx, x + 40 + k * 200, y + 470, 180, 110, { line: 11, alpha: 0.26 });
ctx.restore();
// push pin
const px = x + w / 2, py = y + 4;
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 6; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 7;
const pg = ctx.createRadialGradient(px - 6, py - 6, 2, px, py, 18);
pg.addColorStop(0, '#ff8a7a'); pg.addColorStop(0.6, '#c8302a'); pg.addColorStop(1, '#7c1410');
ctx.fillStyle = pg;
ctx.beginPath(); ctx.arc(px, py, 18, 0, Math.PI * 2); ctx.fill();
ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,0.55)';
ctx.beginPath(); ctx.arc(px - 6, py - 6, 5, 0, Math.PI * 2); ctx.fill();
scene.textures.addCanvas('sudoku-clipping', c);
}
function bakeFlap(scene) {
seed = 71;
const c = canvas(FLAP.w + 24, FLAP.h + 24);
const ctx = c.getContext('2d');
const x = 6, y = 4, w = FLAP.w, h = FLAP.h;
ctx.save();
ctx.shadowColor = 'rgba(30,20,10,0.4)'; ctx.shadowBlur = 14; ctx.shadowOffsetY = 8;
ctx.fillStyle = '#e9e2cf'; ctx.fillRect(x, y, w, h);
ctx.restore();
newsprint(ctx, x, y, w, h, { tone: '#e9e2cf' });
// fold shading at the top edge
const fg = ctx.createLinearGradient(0, y, 0, y + 50);
fg.addColorStop(0, 'rgba(60,45,25,0.25)'); fg.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = fg; ctx.fillRect(x, y, w, 50);
// the back page: three columns of copy around a headline box
for (let k = 0; k < 3; k++) {
const cx = x + 30 + k * ((w - 60) / 3);
greek(ctx, cx, y + 70, (w - 60) / 3 - 22, 150, { line: 12, alpha: 0.24 });
greek(ctx, cx, y + h - 230, (w - 60) / 3 - 22, 200, { line: 12, alpha: 0.24 });
}
ctx.strokeStyle = 'rgba(31,29,26,0.7)'; ctx.lineWidth = 2;
ctx.strokeRect(x + 30, y + 250, w - 60, h - 520);
ctx.lineWidth = 0.8; ctx.strokeRect(x + 36, y + 256, w - 72, h - 532);
scene.textures.addCanvas('sudoku-flap', c);
}
export function prepareSudokuArt(scene) {
if (!scene.textures.exists('sudoku-table')) bakeTable(scene);
if (!scene.textures.exists('sudoku-paper')) bakePaper(scene);
if (!scene.textures.exists('sudoku-print')) bakePrint(scene);
if (!scene.textures.exists('sudoku-notepad')) bakeNotepad(scene);
if (!scene.textures.exists('sudoku-eraser')) bakeEraser(scene);
if (!scene.textures.exists('sudoku-watch')) bakeWatch(scene);
if (!scene.textures.exists('sudoku-steam')) bakeSteam(scene);
if (!scene.textures.exists('sudoku-card')) bakeCard(scene);
if (!scene.textures.exists('sudoku-clipping')) bakeClipping(scene);
if (!scene.textures.exists('sudoku-flap')) bakeFlap(scene);
}
export const PAPER_TEX_PAD = PAD_PX;
// ── NewsButton ───────────────────────────────────────────────────────────────
// A small slip of card stock with a printed label. Container centred on (x, y);
// children are centred too (a Container's hit area is always centred on it).
export class NewsButton extends Phaser.GameObjects.Container {
constructor(scene, x, y, label, onClick, { width = 190, height = 54, fontSize = 22, accent = false } = {}) {
super(scene, x, y);
this.w = width; this.h = height; this.accent = accent;
this.enabled = true;
this.gfx = scene.add.graphics();
this.text = scene.add.text(0, 1, label, {
fontFamily: SERIF, fontSize: `${fontSize}px`, color: accent ? RED_INK : INK, fontStyle: 'bold',
}).setOrigin(0.5);
this.baseSize = fontSize;
this.fit();
this.add([this.gfx, this.text]);
this.setSize(width, height);
this.setInteractive({ useHandCursor: true });
this.hover = false;
this.draw();
this.on('pointerover', () => { this.hover = true; this.draw(); });
this.on('pointerout', () => { this.hover = false; this.draw(); this.gfx.y = 0; this.text.y = 1; });
this.on('pointerdown', () => { if (this.enabled) { this.gfx.y = 2; this.text.y = 3; } });
this.on('pointerup', () => {
this.gfx.y = 0; this.text.y = 1;
if (this.enabled) onClick?.();
});
scene.add.existing(this);
}
fit() {
const maxW = this.w - 18;
this.text.setFontSize(this.baseSize);
if (this.text.width > maxW) this.text.setFontSize(Math.max(13, Math.floor(this.baseSize * maxW / this.text.width)));
}
draw() {
const g = this.gfx, w = this.w, h = this.h;
g.clear();
g.fillStyle(0x000000, 0.18);
g.fillRect(-w / 2 + 3, -h / 2 + 4, w, h);
g.fillStyle(this.hover && this.enabled ? 0xfff4cf : 0xf6f1e4, 1);
g.fillRect(-w / 2, -h / 2, w, h);
g.lineStyle(2, this.accent ? RED_INK_N : INK_N, 0.9);
g.strokeRect(-w / 2 + 4, -h / 2 + 4, w - 8, h - 8);
g.lineStyle(1, this.accent ? RED_INK_N : INK_N, 0.4);
g.strokeRect(-w / 2 + 7, -h / 2 + 7, w - 14, h - 14);
}
setLabel(t) { this.text.setText(t); this.fit(); return this; }
setEnabled(on) {
this.enabled = on;
this.setAlpha(on ? 1 : 0.45);
if (this.input) this.input.cursor = on ? 'pointer' : 'default';
this.draw();
return this;
}
}
// Five stars (filled to `n`) as text.
export const stars = (n) => '★'.repeat(n) + '☆'.repeat(5 - n);

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,20 @@
// Sudoku — pure helpers (no Phaser). Shared by the scene and tools/verifySudoku.js.
//
// rules/score HINT_LIMITS, DIFFICULTY_SCORES, DIFF_LABELS, EDITION, calcScore, isBoardComplete
// geometry boxOf, peers, unitCells
// board findConflicts, digitCounts, completedUnits
// hints getHintCell(grid, solution, givens) — fixes a wrong entry first
// history makeHistory, pushEdit, pushMarker, undoEdit, redoEdit
// save serialiseSave, parseSave
// daily dailySeed, prevDate, updateDaily, dailyStreakNow
//
// Grids are 9×9 arrays of ints (0 = empty); `givens` is a 9×9 array of booleans.
import { dateSeed, localDateString } from '../dotlink/DotLinkLogic.js';
export const N = 9;
export const DIFFS = ['very-easy', 'easy', 'regular', 'hard', 'brutal'];
export const HINT_LIMITS = {
'very-easy': Infinity,
'easy': Infinity,
@ -14,19 +31,270 @@ export const DIFFICULTY_SCORES = {
'brutal': 100,
};
export const DIFF_LABELS = {
'very-easy': 'Very Easy', 'easy': 'Easy', 'regular': 'Regular', 'hard': 'Hard', 'brutal': 'Brutal',
};
// Newspaper convention: puzzles get harder through the week.
export const EDITION = {
'very-easy': { day: 'Monday', stars: 1 },
'easy': { day: 'Tuesday', stars: 2 },
'regular': { day: 'Wednesday', stars: 3 },
'hard': { day: 'Friday', stars: 4 },
'brutal': { day: 'Saturday', stars: 5 },
};
// Very Easy + Easy check every entry as it's written and show rule conflicts.
export const isEasyTier = (difficulty) => difficulty === 'very-easy' || difficulty === 'easy';
export function calcScore(difficulty, hintsUsed) {
const base = DIFFICULTY_SCORES[difficulty] ?? 10;
const hintPenalty = difficulty === 'regular' ? hintsUsed * 4 : 0;
return Math.max(0, base - hintPenalty);
}
export function isBoardComplete(grid, solution) {
for (let r = 0; r < 9; r++)
for (let c = 0; c < 9; c++)
for (let r = 0; r < N; r++)
for (let c = 0; c < N; c++)
if (grid[r][c] !== solution[r][c]) return false;
return true;
}
// Returns a random empty cell that should be filled per the solution, or null.
export function getHintCell(grid, solution) {
const empties = [];
for (let r = 0; r < 9; r++)
for (let c = 0; c < 9; c++)
if (grid[r][c] === 0) empties.push({ r, c });
if (empties.length === 0) return null;
return empties[Math.floor(Math.random() * empties.length)];
// ── Geometry ──────────────────────────────────────────────────────────────────
export const boxOf = (r, c) => Math.floor(r / 3) * 3 + Math.floor(c / 3);
// The 20 cells sharing a row, column or box with (r, c).
export function peers(r, c) {
const out = [];
const b = boxOf(r, c);
for (let rr = 0; rr < N; rr++)
for (let cc = 0; cc < N; cc++)
if ((rr !== r || cc !== c) && (rr === r || cc === c || boxOf(rr, cc) === b)) out.push({ r: rr, c: cc });
return out;
}
// Cells of a unit: type 'row' | 'col' | 'box', index 0–8.
export function unitCells(type, index) {
const out = [];
for (let k = 0; k < N; k++) {
if (type === 'row') out.push({ r: index, c: k });
else if (type === 'col') out.push({ r: k, c: index });
else out.push({ r: Math.floor(index / 3) * 3 + Math.floor(k / 3), c: (index % 3) * 3 + (k % 3) });
}
return out;
}
const ALL_UNITS = ['row', 'col', 'box'].flatMap(type => Array.from({ length: N }, (_, index) => ({ type, index })));
// ── Board state ───────────────────────────────────────────────────────────────
// Cells that repeat a digit within a row, column or box (by the rules, not the
// stored solution). Returns a Set of "r,c" keys.
export function findConflicts(grid) {
const out = new Set();
for (const { type, index } of ALL_UNITS) {
const seen = new Map();
for (const { r, c } of unitCells(type, index)) {
const v = grid[r][c];
if (!v) continue;
if (!seen.has(v)) seen.set(v, []);
seen.get(v).push(`${r},${c}`);
}
for (const keys of seen.values()) if (keys.length > 1) for (const k of keys) out.add(k);
}
return out;
}
// counts[d] = how many cells hold d (index 0 unused).
export function digitCounts(grid) {
const counts = Array(10).fill(0);
for (const row of grid) for (const v of row) if (v) counts[v]++;
return counts;
}
// Units holding all nine digits. With `solution`, each cell must also match it
// (used once entries are being checked, so a finished unit is a correct one).
// Returns [{ type, index, key }].
export function completedUnits(grid, solution = null) {
const out = [];
for (const { type, index } of ALL_UNITS) {
const cells = unitCells(type, index);
let mask = 0, ok = true;
for (const { r, c } of cells) {
const v = grid[r][c];
if (!v || (solution && v !== solution[r][c])) { ok = false; break; }
mask |= 1 << v;
}
if (ok && mask === 0x3fe) out.push({ type, index, key: `${type}${index}` });
}
return out;
}
// The cell a hint should fix: a wrong player entry first (so a full board with
// mistakes still gets help), otherwise a random empty cell. null when solved.
export function getHintCell(grid, solution, givens = null, rng = Math.random) {
const wrong = [], empties = [];
for (let r = 0; r < N; r++)
for (let c = 0; c < N; c++) {
if (givens?.[r]?.[c]) continue;
const v = grid[r][c];
if (v === 0) empties.push({ r, c });
else if (v !== solution[r][c]) wrong.push({ r, c });
}
const pool = wrong.length ? wrong : empties;
if (!pool.length) return null;
return { ...pool[Math.floor(rng() * pool.length)], fix: wrong.length > 0 };
}
// ── History ───────────────────────────────────────────────────────────────────
// A hint pushes a marker: undo never steps back past a hint.
export function makeHistory() { return { undo: [], redo: [] }; }
export function pushEdit(h, edit) {
h.undo.push({ r: edit.r, c: edit.c, from: edit.from, to: edit.to });
h.redo.length = 0;
if (h.undo.length > 500) h.undo.splice(0, h.undo.length - 500);
}
export function pushMarker(h) {
h.undo.push({ marker: 'hint' });
h.redo.length = 0;
}
export function canUndo(h) { return h.undo.length > 0 && !h.undo[h.undo.length - 1].marker; }
export function canRedo(h) { return h.redo.length > 0; }
// Returns the edit to reverse (apply grid[r][c] = from), or null.
export function undoEdit(h) {
if (!canUndo(h)) return null;
const e = h.undo.pop();
h.redo.push(e);
return e;
}
// Returns the edit to re-apply (apply grid[r][c] = to), or null.
export function redoEdit(h) {
if (!h.redo.length) return null;
const e = h.redo.pop();
h.undo.push(e);
return e;
}
// ── Save / resume ─────────────────────────────────────────────────────────────
export const SAVE_KEY = 'sudoku-save';
const SAVE_VERSION = 1;
export function serialiseSave(s) {
return JSON.stringify({
v: SAVE_VERSION,
difficulty: s.difficulty,
daily: s.daily ?? null,
grid: s.grid, solution: s.solution, givens: s.givens,
cellState: s.cellState,
history: s.history,
elapsed: Math.round(s.elapsed ?? 0),
hintsLeft: Number.isFinite(s.hintsLeft) ? s.hintsLeft : null,
hintsUsed: s.hintsUsed ?? 0,
mistakes: s.mistakes ?? 0,
revealed: !!s.revealed,
moves: s.moves ?? 0,
puzzleNo: s.puzzleNo ?? 0,
tier: s.tier ?? null,
hinted: Array.isArray(s.hinted) ? s.hinted : [],
savedAt: s.savedAt ?? Date.now(),
});
}
const isGrid = (g, ok) => Array.isArray(g) && g.length === N &&
g.every(row => Array.isArray(row) && row.length === N && row.every(ok));
const isDigit = (max) => (v) => Number.isInteger(v) && v >= 0 && v <= max;
// The stored solution must itself be a valid Sudoku.
function validSolution(sol) {
for (let k = 0; k < N; k++) {
for (const type of ['row', 'col', 'box']) {
let mask = 0;
for (const { r, c } of unitCells(type, k)) mask |= 1 << sol[r][c];
if (mask !== 0x3fe) return false;
}
}
return true;
}
// Returns the save object, or null when the JSON is missing, corrupt, from a
// different version, or internally inconsistent.
export function parseSave(json) {
if (!json) return null;
let s;
try { s = JSON.parse(json); } catch { return null; }
if (!s || s.v !== SAVE_VERSION) return null;
if (!DIFFS.includes(s.difficulty)) return null;
if (!isGrid(s.grid, isDigit(9)) || !isGrid(s.solution, (v) => Number.isInteger(v) && v >= 1 && v <= 9)) return null;
if (!validSolution(s.solution)) return null;
if (!isGrid(s.givens, (v) => typeof v === 'boolean')) return null;
if (!isGrid(s.cellState, isDigit(2))) return null;
for (let r = 0; r < N; r++)
for (let c = 0; c < N; c++)
if (s.givens[r][c] && s.grid[r][c] !== s.solution[r][c]) return null;
if (isBoardComplete(s.grid, s.solution)) return null; // already solved: nothing to resume
const h = s.history;
if (!h || !Array.isArray(h.undo) || !Array.isArray(h.redo)) s.history = makeHistory();
s.hintsLeft = s.hintsLeft == null ? Infinity : s.hintsLeft;
s.hinted = Array.isArray(s.hinted) ? s.hinted.filter(k => typeof k === 'string' && /^[0-8],[0-8]$/.test(k)) : [];
if (s.daily != null && !/^\d{4}-\d{2}-\d{2}$/.test(s.daily)) s.daily = null;
if (!Number.isFinite(s.elapsed) || s.elapsed < 0) s.elapsed = 0;
return s;
}
// ── Daily ─────────────────────────────────────────────────────────────────────
export const DAILY_KEY = 'sudoku-daily';
export const DAILY_DIFFICULTY = 'regular';
export function todayString(d = new Date()) { return localDateString(d); }
export function dailySeed(date) { return dateSeed(`sudoku:${date}`); }
export function prevDate(date) {
const [y, m, d] = date.split('-').map(Number);
return localDateString(new Date(y, m - 1, d - 1));
}
export function blankDaily() { return { lastDate: null, streak: 0, bestStreak: 0, solved: {} }; }
// Record a Daily solve for `date` (the puzzle's date) on `today`. Only a
// same-day solve moves the streak; re-solving keeps the faster time.
// Returns { rec, newBestTime, streak }.
export function updateDaily(rec, date, today, timeMs) {
const r = { ...blankDaily(), ...(rec ?? {}), solved: { ...(rec?.solved ?? {}) } };
const old = r.solved[date];
const newBestTime = old != null && timeMs < old;
if (old == null || timeMs < old) r.solved[date] = timeMs;
if (date === today && r.lastDate !== today) {
r.streak = r.lastDate === prevDate(today) ? r.streak + 1 : 1;
r.lastDate = today;
r.bestStreak = Math.max(r.bestStreak, r.streak);
}
// keep the last 60 solves
const keys = Object.keys(r.solved).sort();
for (const k of keys.slice(0, Math.max(0, keys.length - 60))) delete r.solved[k];
return { rec: r, newBestTime, streak: dailyStreakNow(r, today) };
}
// The streak still alive today: solved today or yesterday keeps it.
export function dailyStreakNow(rec, today) {
if (!rec?.lastDate) return 0;
return rec.lastDate === today || rec.lastDate === prevDate(today) ? rec.streak : 0;
}
// "SUNDAY, NOVEMBER 26, 2026" for a YYYY-MM-DD string.
export function longDate(date) {
const [y, m, d] = date.split('-').map(Number);
const dt = new Date(y, m - 1, d);
const days = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
const months = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'];
return `${days[dt.getDay()]}, ${months[m - 1]} ${d}, ${y}`;
}

View File

@ -1,97 +1,439 @@
function isValid(grid, row, col, num) {
for (let c = 0; c < 9; c++) if (grid[row][c] === num) return false;
for (let r = 0; r < 9; r++) if (grid[r][col] === num) return false;
const br = Math.floor(row / 3) * 3;
const bc = Math.floor(col / 3) * 3;
for (let r = br; r < br + 3; r++)
for (let c = bc; c < bc + 3; c++)
if (grid[r][c] === num) return false;
return true;
// Sudoku puzzle engine — generation, solution counting and technique grading.
//
// generatePuzzle(difficulty, { seed? }) → { grid, solution, difficulty, tier, givens, seed }
// countSolutions(grid, limit = 2) → number of solutions found (stops at limit)
// gradePuzzle(grid, maxTier = 5) → { solved, tier, grid, candidates } — tier is the
// hardest technique the logic solver needed (1–5);
// solved=false when it gets stuck
//
// Grids are 9×9 arrays of ints (0 = empty).
//
// Technique tiers (the solver always applies the easiest one that makes progress):
// 1 naked single · 2 hidden single · 3 locked candidates (pointing / claiming)
// 4 naked + hidden pairs and triples · 5 X-Wing, Swordfish, XY-Wing
//
// Every technique is a sound deduction, so a board the logic solver finishes has
// exactly one solution. Hole digging keeps a removal only while the board stays
// logic-solvable within the target tier; countSolutions double-checks the result.
export const TECHNIQUES = {
1: 'Naked single',
2: 'Hidden single',
3: 'Locked candidates',
4: 'Pairs and triples',
5: 'X-Wing, Swordfish, XY-Wing',
};
// tier = the hardest technique the puzzle must need; band = allowed givens.
export const DIFFICULTY_SPEC = {
'very-easy': { tier: 1, min: 44, max: 50 },
'easy': { tier: 2, min: 34, max: 40 },
'regular': { tier: 3, min: 28, max: 33 },
'hard': { tier: 4, min: 24, max: 28 },
'brutal': { tier: 5, min: 22, max: 26 },
};
// ── Geometry ──────────────────────────────────────────────────────────────────
const ROW_OF = new Int8Array(81), COL_OF = new Int8Array(81), BOX_OF = new Int8Array(81);
const UNITS = []; // 27 × 9 cell indexes: rows 0–8, cols 9–17, boxes 18–26
const PEERS = []; // 81 × 20
const POP = new Int8Array(512);
const LOW_DIGIT = new Int8Array(512); // digit (1–9) of the lowest set bit
for (let i = 0; i < 81; i++) {
ROW_OF[i] = (i / 9) | 0; COL_OF[i] = i % 9;
BOX_OF[i] = ((ROW_OF[i] / 3) | 0) * 3 + ((COL_OF[i] / 3) | 0);
}
for (let r = 0; r < 9; r++) UNITS.push(Array.from({ length: 9 }, (_, c) => r * 9 + c));
for (let c = 0; c < 9; c++) UNITS.push(Array.from({ length: 9 }, (_, r) => r * 9 + c));
for (let b = 0; b < 9; b++) {
const r0 = ((b / 3) | 0) * 3, c0 = (b % 3) * 3;
const u = [];
for (let r = r0; r < r0 + 3; r++) for (let c = c0; c < c0 + 3; c++) u.push(r * 9 + c);
UNITS.push(u);
}
for (let i = 0; i < 81; i++) {
const s = new Set();
for (const u of [UNITS[ROW_OF[i]], UNITS[9 + COL_OF[i]], UNITS[18 + BOX_OF[i]]]) for (const j of u) if (j !== i) s.add(j);
PEERS.push([...s]);
}
for (let m = 1; m < 512; m++) {
POP[m] = POP[m >> 1] + (m & 1);
let d = 0; while (!(m & (1 << d))) d++;
LOW_DIGIT[m] = d + 1;
}
const ALL = 0x1ff;
const bit = (d) => 1 << (d - 1);
const sees = (a, b) => a !== b && (ROW_OF[a] === ROW_OF[b] || COL_OF[a] === COL_OF[b] || BOX_OF[a] === BOX_OF[b]);
// ── Randomness ────────────────────────────────────────────────────────────────
// The generator's only randomness. generatePuzzle swaps in a seeded RNG for the
// duration of a seeded call (the Daily) and restores it afterwards.
let rand = Math.random;
function makeRng(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const j = Math.floor(rand() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
function fillBox(grid, startRow, startCol) {
const nums = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]);
let idx = 0;
for (let r = startRow; r < startRow + 3; r++)
for (let c = startCol; c < startCol + 3; c++)
grid[r][c] = nums[idx++];
const flatten = (grid) => { const a = new Int8Array(81); for (let i = 0; i < 81; i++) a[i] = grid[ROW_OF[i]][COL_OF[i]] | 0; return a; };
const unflatten = (a) => Array.from({ length: 9 }, (_, r) => Array.from({ length: 9 }, (_, c) => a[r * 9 + c]));
// ── Solution grid ─────────────────────────────────────────────────────────────
function generateSolution() {
const g = new Int8Array(81);
const rows = new Int16Array(9), cols = new Int16Array(9), boxes = new Int16Array(9);
const order = Array.from({ length: 81 }, (_, i) => i);
const fill = (k) => {
if (k === 81) return true;
const i = order[k];
const free = ALL & ~(rows[ROW_OF[i]] | cols[COL_OF[i]] | boxes[BOX_OF[i]]);
const digits = [];
for (let d = 1; d <= 9; d++) if (free & bit(d)) digits.push(d);
for (const d of shuffle(digits)) {
const b = bit(d);
g[i] = d; rows[ROW_OF[i]] |= b; cols[COL_OF[i]] |= b; boxes[BOX_OF[i]] |= b;
if (fill(k + 1)) return true;
rows[ROW_OF[i]] &= ~b; cols[COL_OF[i]] &= ~b; boxes[BOX_OF[i]] &= ~b;
}
g[i] = 0;
return false;
};
fill(0);
return g;
}
function solve(grid) {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
if (grid[r][c] === 0) {
for (const num of shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9])) {
if (isValid(grid, r, c, num)) {
grid[r][c] = num;
if (solve(grid)) return true;
grid[r][c] = 0;
}
}
return false;
}
}
// ── Solution counting (MRV bitmask backtracking) ──────────────────────────────
function countFlat(src, limit) {
const g = Int8Array.from(src);
const rows = new Int16Array(9), cols = new Int16Array(9), boxes = new Int16Array(9);
for (let i = 0; i < 81; i++) {
const d = g[i];
if (!d) continue;
const b = bit(d);
if ((rows[ROW_OF[i]] | cols[COL_OF[i]] | boxes[BOX_OF[i]]) & b) return 0; // already broken
rows[ROW_OF[i]] |= b; cols[COL_OF[i]] |= b; boxes[BOX_OF[i]] |= b;
}
let count = 0;
const rec = () => {
let best = -1, bestFree = 0, bestN = 10;
for (let i = 0; i < 81; i++) {
if (g[i]) continue;
const free = ALL & ~(rows[ROW_OF[i]] | cols[COL_OF[i]] | boxes[BOX_OF[i]]);
const n = POP[free];
if (n < bestN) { best = i; bestFree = free; bestN = n; if (n <= 1) break; }
}
if (best < 0) { count++; return; }
let m = bestFree;
while (m) {
const b = m & -m; m &= m - 1;
const d = LOW_DIGIT[b];
g[best] = d; rows[ROW_OF[best]] |= b; cols[COL_OF[best]] |= b; boxes[BOX_OF[best]] |= b;
rec();
rows[ROW_OF[best]] &= ~b; cols[COL_OF[best]] &= ~b; boxes[BOX_OF[best]] &= ~b;
g[best] = 0;
if (count >= limit) return;
}
};
rec();
return count;
}
export function countSolutions(grid, limit = 2) {
return countFlat(flatten(grid), limit);
}
// ── Logic solver / grader ─────────────────────────────────────────────────────
function makeState(flat) {
const vals = new Int8Array(81), cand = new Uint16Array(81).fill(ALL);
const st = { vals, cand, empty: 81, broken: false };
for (let i = 0; i < 81; i++) if (flat[i]) place(st, i, flat[i]);
return st;
}
function place(st, i, d) {
if (st.vals[i]) return;
const b = bit(d);
if (!(st.cand[i] & b)) { st.broken = true; return; }
st.vals[i] = d; st.cand[i] = 0; st.empty--;
for (const p of PEERS[i]) {
if (st.vals[p] === d) st.broken = true;
st.cand[p] &= ~b;
}
}
// Remove `mask` from cell i's candidates; true when something was removed.
function elim(st, i, mask) {
if (st.vals[i] || !(st.cand[i] & mask)) return false;
st.cand[i] &= ~mask;
if (!st.cand[i]) st.broken = true;
return true;
}
function generateSolution() {
const grid = Array.from({ length: 9 }, () => Array(9).fill(0));
// Seed diagonal boxes first (no inter-box constraints) for faster solve
fillBox(grid, 0, 0);
fillBox(grid, 3, 3);
fillBox(grid, 6, 6);
solve(grid);
return grid;
}
function cloneGrid(g) {
return g.map(row => [...row]);
}
function countGivens(grid) {
return grid.flat().filter(v => v !== 0).length;
}
const GIVENS = {
'very-easy': 50,
'easy': 36,
'regular': 28,
'hard': 24,
'brutal': 18,
};
function digHoles(solution, targetGivens) {
const grid = cloneGrid(solution);
const positions = [];
for (let r = 0; r < 9; r++)
for (let c = 0; c < 9; c++)
positions.push([r, c]);
shuffle(positions);
for (const [r, c] of positions) {
if (countGivens(grid) <= targetGivens) break;
const mr = 8 - r, mc = 8 - c;
if (grid[r][c] === 0 && grid[mr][mc] === 0) continue;
grid[r][c] = 0;
if (r !== mr || c !== mc) grid[mr][mc] = 0;
function nakedSingles(st) {
let hit = false;
for (let i = 0; i < 81; i++) {
if (!st.vals[i] && POP[st.cand[i]] === 1) { place(st, i, LOW_DIGIT[st.cand[i]]); hit = true; }
}
return grid;
return hit;
}
export function generatePuzzle(difficulty) {
const target = GIVENS[difficulty] ?? 28;
const solution = generateSolution();
const grid = digHoles(solution, target);
return { grid, solution, difficulty };
function hiddenSingles(st) {
let hit = false;
for (const u of UNITS) {
for (let d = 1; d <= 9; d++) {
const b = bit(d);
let at = -1, n = 0, placed = false;
for (const i of u) {
if (st.vals[i] === d) { placed = true; break; }
if (st.cand[i] & b) { at = i; n++; }
}
if (!placed && n === 1) { place(st, at, d); hit = true; }
}
}
return hit;
}
function lockedCandidates(st) {
let hit = false;
// pointing: inside a box, a digit confined to one row/col clears the rest of that line
for (let b = 0; b < 9; b++) {
const box = UNITS[18 + b];
for (let d = 1; d <= 9; d++) {
const m = bit(d);
const cells = box.filter(i => st.cand[i] & m);
if (cells.length < 2) continue;
const r = ROW_OF[cells[0]], c = COL_OF[cells[0]];
if (cells.every(i => ROW_OF[i] === r)) for (const j of UNITS[r]) if (BOX_OF[j] !== b && elim(st, j, m)) hit = true;
if (cells.every(i => COL_OF[i] === c)) for (const j of UNITS[9 + c]) if (BOX_OF[j] !== b && elim(st, j, m)) hit = true;
}
}
// claiming: inside a line, a digit confined to one box clears the rest of that box
for (let u = 0; u < 18; u++) {
const line = UNITS[u];
for (let d = 1; d <= 9; d++) {
const m = bit(d);
const cells = line.filter(i => st.cand[i] & m);
if (cells.length < 2) continue;
const bx = BOX_OF[cells[0]];
if (!cells.every(i => BOX_OF[i] === bx)) continue;
for (const j of UNITS[18 + bx]) if (!line.includes(j) && elim(st, j, m)) hit = true;
}
}
return hit;
}
function combos(arr, k, start = 0, acc = [], out = []) {
if (acc.length === k) { out.push([...acc]); return out; }
for (let i = start; i < arr.length; i++) { acc.push(arr[i]); combos(arr, k, i + 1, acc, out); acc.pop(); }
return out;
}
function subsets(st) {
let hit = false;
for (const k of [2, 3]) {
for (const u of UNITS) {
const open = u.filter(i => !st.vals[i]);
if (open.length <= k) continue;
// naked: k cells whose candidates together are exactly k digits
for (const set of combos(open.filter(i => POP[st.cand[i]] <= k), k)) {
let m = 0;
for (const i of set) m |= st.cand[i];
if (POP[m] !== k) continue;
for (const j of open) if (!set.includes(j) && elim(st, j, m)) hit = true;
}
// hidden: k digits that only fit in the same k cells
const digits = [];
for (let d = 1; d <= 9; d++) {
const b = bit(d);
const n = open.filter(i => st.cand[i] & b).length;
if (n >= 1 && n <= k) digits.push(d);
}
for (const ds of combos(digits, k)) {
let dm = 0;
for (const d of ds) dm |= bit(d);
const cells = open.filter(i => st.cand[i] & dm);
if (cells.length !== k) continue;
for (const i of cells) if (elim(st, i, ALL & ~dm)) hit = true;
}
if (hit) return true;
}
}
return hit;
}
// X-Wing (size 2) and Swordfish (size 3), both orientations.
function fish(st) {
for (const size of [2, 3]) {
for (let d = 1; d <= 9; d++) {
const m = bit(d);
for (const byRow of [true, false]) {
const lines = [];
for (let a = 0; a < 9; a++) {
let pos = 0;
for (let b = 0; b < 9; b++) {
const i = byRow ? a * 9 + b : b * 9 + a;
if (st.cand[i] & m) pos |= 1 << b;
}
const n = POP[pos];
if (n >= 2 && n <= size) lines.push({ a, pos });
}
for (const set of combos(lines, size)) {
let cover = 0;
for (const l of set) cover |= l.pos;
if (POP[cover] !== size) continue;
let hit = false;
const base = new Set(set.map(l => l.a));
for (let b = 0; b < 9; b++) {
if (!(cover & (1 << b))) continue;
for (let a = 0; a < 9; a++) {
if (base.has(a)) continue;
if (elim(st, byRow ? a * 9 + b : b * 9 + a, m)) hit = true;
}
}
if (hit) return true;
}
}
}
}
return false;
}
function xyWing(st) {
const bivalue = [];
for (let i = 0; i < 81; i++) if (!st.vals[i] && POP[st.cand[i]] === 2) bivalue.push(i);
for (const pivot of bivalue) {
const pm = st.cand[pivot];
const wings = bivalue.filter(w => sees(pivot, w) && POP[st.cand[w] & pm] === 1);
for (let x = 0; x < wings.length; x++) {
for (let y = x + 1; y < wings.length; y++) {
const a = wings[x], b = wings[y];
const ma = st.cand[a], mb = st.cand[b];
if ((ma & pm) === (mb & pm)) continue; // must share different pivot digits
const z = (ma & ~pm);
if (POP[z] !== 1 || (mb & ~pm) !== z) continue; // and the same outside digit z
let hit = false;
for (let i = 0; i < 81; i++) {
if (i === a || i === b || i === pivot || st.vals[i]) continue;
if (sees(i, a) && sees(i, b) && elim(st, i, z)) hit = true;
}
if (hit) return true;
}
}
}
return false;
}
const TIERS = [
[1, nakedSingles],
[2, hiddenSingles],
[3, lockedCandidates],
[4, subsets],
[5, fish],
[5, xyWing],
];
// Solve with the easiest technique that works at each step. `maxTier` stops the
// solver from trying harder techniques (used while digging holes).
function gradeFlat(flat, maxTier = 5, keepState = false) {
const st = makeState(flat);
const done = (solved, tier) => (keepState ? { solved, tier, st } : { solved, tier });
if (st.broken) return done(false, 0);
let tier = 0;
while (st.empty > 0) {
let progressed = false;
for (const [t, fn] of TIERS) {
if (t > maxTier) break;
if (fn(st)) { tier = Math.max(tier, t); progressed = true; break; }
}
if (st.broken || !progressed) return done(false, tier);
}
return done(true, tier);
}
// gradePuzzle(grid, maxTier = 5) → { solved, tier, grid, candidates }
// grid the values the solver placed (9×9)
// candidates 9×9 arrays of the digits still possible in each empty cell
// (the last two let tools/verifySudoku.js check every deduction is sound).
export function gradePuzzle(grid, maxTier = 5) {
const { solved, tier, st } = gradeFlat(flatten(grid), maxTier, true);
const candidates = unflatten(Array.from(st.cand, (m) => {
const ds = [];
for (let d = 1; d <= 9; d++) if (m & bit(d)) ds.push(d);
return ds;
}));
return { solved, tier, grid: unflatten(st.vals), candidates };
}
// ── Hole digging ──────────────────────────────────────────────────────────────
// 180° symmetric pairs (the centre cell pairs with itself).
const PAIRS = [];
for (let i = 0; i <= 40; i++) PAIRS.push(i === 40 ? [40] : [i, 80 - i]);
function dig(solution, spec) {
const g = Int8Array.from(solution);
let givens = 81;
for (const pair of shuffle(PAIRS.map(p => p))) {
if (givens - pair.length < spec.min) continue;
for (const i of pair) g[i] = 0;
const res = gradeFlat(g, spec.tier);
if (res.solved) givens -= pair.length;
else for (const i of pair) g[i] = solution[i];
}
const res = gradeFlat(g, spec.tier);
return { grid: g, givens, tier: res.solved ? res.tier : 0 };
}
const MAX_SEEDED_ATTEMPTS = 220;
// generatePuzzle(difficulty, { seed }) — with a numeric seed the result is fully
// deterministic (same seed → same board), so generation is bounded by an attempt
// count instead of the wall clock.
export function generatePuzzle(difficulty, { seed = null } = {}) {
const spec = DIFFICULTY_SPEC[difficulty] ?? DIFFICULTY_SPEC.regular;
const seeded = seed != null && Number.isFinite(Number(seed));
const prevRand = rand;
if (seeded) rand = makeRng(Number(seed));
try {
const deadline = seeded ? Infinity : Date.now() + 2200;
let best = null;
const better = (a, b) => !b || a.tier > b.tier || (a.tier === b.tier && a.givens < b.givens);
for (let attempt = 0; seeded ? attempt < MAX_SEEDED_ATTEMPTS : Date.now() < deadline; attempt++) {
const solution = generateSolution();
const p = dig(solution, spec);
if (!p.tier) continue;
const cand = { ...p, solution };
const inBand = p.givens >= spec.min && p.givens <= spec.max;
if (inBand && p.tier === spec.tier) { best = cand; break; }
if (inBand && better(cand, best)) best = cand;
else if (!best) best = cand;
}
if (!best) { // unreachable in practice: tier-1 digging always succeeds
const solution = generateSolution();
best = { ...dig(solution, DIFFICULTY_SPEC['very-easy']), solution };
}
return {
grid: unflatten(best.grid),
solution: unflatten(best.solution),
difficulty: DIFFICULTY_SPEC[difficulty] ? difficulty : 'regular',
tier: best.tier,
givens: best.givens,
seed: seeded ? Number(seed) >>> 0 : null,
};
} finally {
rand = prevRand;
}
}

View File

@ -514,11 +514,13 @@ router.get('/wordsearch/themes', (_req, res) => {
res.json({ themes: wordSearchThemes() });
});
// GET /api/words/sudoku/start?difficulty=very-easy|easy|regular|hard|brutal
// GET /api/words/sudoku/start?difficulty=very-easy|easy|regular|hard|brutal[&seed=uint32]
// A seed makes the board deterministic (the Daily edition).
router.get('/sudoku/start', (req, res) => {
const VALID = ['very-easy', 'easy', 'regular', 'hard', 'brutal'];
const difficulty = VALID.includes(req.query.difficulty) ? req.query.difficulty : 'regular';
res.json(sudokuGenerate(difficulty));
const seed = req.query.seed != null && /^\d+$/.test(String(req.query.seed)) ? Number(req.query.seed) : null;
res.json(sudokuGenerate(difficulty, { seed }));
});
// GET /api/words/tectonic/start?difficulty=easy|medium|hard[&seed=uint32]

704
tools/verifySudoku.js Normal file
View File

@ -0,0 +1,704 @@
#!/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);