From da558f2df93d4c3d56d9f166c0c5954b3d7e2db2 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Thu, 26 Nov 2026 09:44:16 -0700 Subject: [PATCH] =?UTF-8?q?Rework=20Sudoku=20as=20"Sunday=20Paper=20Caf?= =?UTF-8?q?=C3=A9"=20with=20canvas=20art=20and=20full=20play=20flow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- src/games/sudoku/SudokuArt.js | 767 ++++++++++++++ src/games/sudoku/SudokuGame.js | 1688 ++++++++++++++++++++++--------- src/games/sudoku/SudokuLogic.js | 288 +++++- src/words/sudokuEngine.js | 498 +++++++-- src/words/wordRouter.js | 6 +- tools/verifySudoku.js | 704 +++++++++++++ 6 files changed, 3358 insertions(+), 593 deletions(-) create mode 100644 src/games/sudoku/SudokuArt.js create mode 100644 tools/verifySudoku.js diff --git a/src/games/sudoku/SudokuArt.js b/src/games/sudoku/SudokuArt.js new file mode 100644 index 0000000..958d9a9 --- /dev/null +++ b/src/games/sudoku/SudokuArt.js @@ -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); diff --git a/src/games/sudoku/SudokuGame.js b/src/games/sudoku/SudokuGame.js index 169639e..508100e 100644 --- a/src/games/sudoku/SudokuGame.js +++ b/src/games/sudoku/SudokuGame.js @@ -1,629 +1,1311 @@ +// Sudoku — "Sunday Paper Café". +// +// The puzzle is printed on the front page of The Sunday Courier, lying on a +// marble café table with a coffee, a croissant and a pencil. Entries are pencilled +// in; the café guest-check pad holds the number pad (1–9 + eraser); the wristwatch +// is the timer. The start page lists the week's editions (Monday = Very Easy … +// Saturday = Brutal) plus Today's Edition, a seeded daily puzzle. +// +// Input: tap a cell then a pad digit / type 1–9 (cell-first), or pick a pad digit +// with no cell selected and tap cells (digit-first). Arrows/WASD move, Backspace/ +// Delete/0 erase, Ctrl+Z / Ctrl+Y undo/redo, H hint, P pause, Esc clears. +// +// Highlights on every difficulty: the selected cell's row, column and box, and +// every copy of the focused digit. Rule conflicts are circled on Very Easy and +// Easy only. Very Easy/Easy check entries as they're written; Regular and up +// check once the grid is full, then switch to immediate checks. +// Games autosave to localStorage; stats per edition + the daily streak. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { api } from '../../services/api.js'; -import { Button } from '../../ui/Button.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { HINT_LIMITS, DIFFICULTY_SCORES, isBoardComplete, getHintCell } from './SudokuLogic.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; +import { loadStats, recordGame, formatTime } from '../../ui/solitaire/SolitaireStats.js'; +import { + N, HINT_LIMITS, DIFF_LABELS, EDITION, isEasyTier, calcScore, isBoardComplete, getHintCell, + boxOf, findConflicts, digitCounts, completedUnits, unitCells, + makeHistory, pushEdit, pushMarker, canUndo, canRedo, undoEdit, redoEdit, + SAVE_KEY, serialiseSave, parseSave, + DAILY_KEY, DAILY_DIFFICULTY, todayString, dailySeed, updateDaily, dailyStreakNow, blankDaily, longDate, +} from './SudokuLogic.js'; +import { + W, H, PAPER, PAPER_CX, CELL, GRID_W, GRID_X, GRID_Y, SIDE, DATELINE_Y, HEADER_Y, PRINT, + RCX, WATCH, CUP, PAD, PAD_PITCH, PAD_ROW0, ERASER_Y, BTN_Y1, BTN_Y2, CARD_W, CARD_H, CLIP_H, FLAP, + SERIF, INK, INK_N, GRAPHITE, GRAPHITE_N, FADED, RED_INK, RED_INK_N, HIGHLIGHT_N, PAPER_TEX_PAD, + prepareSudokuArt, NewsButton, stars, +} from './SudokuArt.js'; -// ── Palette ─────────────────────────────────────────────────────────────────── -const PAPER = 0xFFF8F0; -const PAPER_EDGE = 0xE8D8C0; -const INK = '#3a2a18'; -const INK_N = 0x3a2a18; -const FADED = '#b09a7a'; -const TITLE_BROWN = '#5c3a1e'; -const RED_CIRCLE = 0xc0392b; -const SPIRAL_CLR = 0x8a7060; -const PLAYER_INK = '#1e4d7a'; // slightly blue-tinted ink for player entries - -const DEPTH = { - bg: 0, paper: 1, lines: 2, cell: 3, gridLines: 4, - number: 5, selector: 6, hit: 10, ui: 20, overlay: 40, +const D = { + table: 0, paper: 2, print: 3, hl: 4, state: 5, smudge: 6, hover: 7, digits: 8, conflicts: 9, cursor: 10, + props: 12, hit: 20, pad: 24, ui: 30, flap: 40, toast: 45, modal: 60, win: 80, }; -// ── Layout ──────────────────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; - -// Paper sheet -const PX = 60, PY = 40, PW = 1800, PH = 1000; - -// Grid (9×9, centered in left panel) -const CELL = 82; -const GRID_X = 171; // 540 − 9×82/2 = 540 − 369 -const GRID_Y = 170; -const GRID_W = 9 * CELL; // 738 -const GRID_H = 9 * CELL; // 738 - -// Red margin line -const MARGIN_X = 1020; -const TITLE_CX = 540; // center of left panel: (60+1020)/2 - -// Right-panel number selector -const NUM_X = 1440; // center of right panel: (1020+1860)/2 -const NUM_START_Y = 163; // y-center of number "1" -const NUM_STEP = 82; // vertical spacing (= CELL, aligns with grid rows) -const ERASER_CY = NUM_START_Y + 9 * NUM_STEP + 6; // 163 + 738 + 6 = 907 -const HINT_BTN_Y = ERASER_CY + 56; // 963 -const BTN_Y = PY + PH - 48; // 992 - -const DIFF_LABELS = { - 'very-easy': 'Very Easy', 'easy': 'Easy', 'regular': 'Regular', - 'hard': 'Hard', 'brutal': 'Brutal', +const GUIDE_SEEN_KEY = 'sudoku-guide-seen'; +const HINT_COLOR = '#7a4a12'; +const DESC = { + 'very-easy': '44+ givens · singles only · unlimited hints · checked as you write', + 'easy': '34+ givens · hidden singles · unlimited hints · checked as you write', + 'regular': 'Locked candidates · 5 hints · checked when the grid is full', + 'hard': 'Pairs and triples · no hints · checked when the grid is full', + 'brutal': 'X-Wings and XY-Wings · no hints · checked when the grid is full', }; +const storage = () => { try { return globalThis.localStorage ?? null; } catch { return null; } }; +const readJSON = (k) => { try { return JSON.parse(storage()?.getItem(k) || 'null'); } catch { return null; } }; +const writeJSON = (k, v) => { try { storage()?.setItem(k, JSON.stringify(v)); } catch { /* private/full */ } }; + +const cellCX = (c) => GRID_X + c * CELL + CELL / 2; +const cellCY = (r) => GRID_Y + r * CELL + CELL / 2; +const padXY = (n) => ({ x: RCX + (((n - 1) % 3) - 1) * PAD_PITCH, y: PAD_ROW0 + Math.floor((n - 1) / 3) * PAD_PITCH }); + +function unitRect({ type, index }) { + if (type === 'row') return { x: GRID_X, y: GRID_Y + index * CELL, w: GRID_W, h: CELL }; + if (type === 'col') return { x: GRID_X + index * CELL, y: GRID_Y, w: CELL, h: GRID_W }; + return { x: GRID_X + (index % 3) * 3 * CELL, y: GRID_Y + Math.floor(index / 3) * 3 * CELL, w: 3 * CELL, h: 3 * CELL }; +} + export default class SudokuGame extends Phaser.Scene { constructor() { super('SudokuGame'); } init(data) { - this._initData = { ...data }; - this.gameDef = data.game; + this._initData = { ...data }; + delete this._initData.next; + this.next = data.next ?? null; + this.gameDef = data.game; - this.grid = null; - this.solution = null; - this.difficulty = ''; - this.selectedNum = 1; - this.hintsLeft = null; - this.hintsUsed = 0; - this.gameEnded = false; - this.hoveredCell = null; + this.mode = 'start'; // start | loading | play + this.startObjs = []; + this.modal = null; + this.introBusy = false; + this.paused = false; + this.flap = null; + this.toastObj = null; - this.givenCells = []; - this.cellState = []; // 0=empty, 1=correct, 2=wrong - this.cellBgObjs = []; - this.cellTextObjs = []; - this.cellHitObjs = []; + this.grid = null; this.solution = null; this.givens = null; + this.hinted = new Set(); + this.difficulty = 'regular'; + this.daily = null; + this.puzzleNo = 0; + this.tier = null; + this.cellState = null; + this.history = makeHistory(); + this.elapsed = 0; + this.timerOn = false; + this.hintsLeft = 0; this.hintsUsed = 0; this.mistakes = 0; + this.revealed = false; + this.moves = 0; + this.gameEnded = false; + this.winPending = false; + this.hintPending = false; - this.numCircleGfx = null; - this.numStrikeGfx = null; - this.numTextObjs = {}; - this.numHitObjs = {}; - this.hintBtn = null; - this.startObjs = []; - this.revealed = false; + this.cursor = null; + this.armed = null; // null | 0 (eraser) | 1..9 + this.hover = null; + + this.cellText = []; + this.tilt = Array.from({ length: N }, () => Array.from({ length: N }, () => (Math.random() - 0.5) * 8)); + this.unitsDone = new Set(); + this.digitsDone = new Set(); + this.padCells = {}; + this.strikeProgress = {}; + this._lastSecond = -1; } - async create() { + create() { + prepareSudokuArt(this); const music = this.cache.json.get('music'); if (music?.tracks) new MusicPlayer(this, music.tracks); - this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(DEPTH.bg); + this.add.image(0, 0, 'sudoku-table').setOrigin(0).setDepth(D.table); + this.paperImg = this.add.image(PAPER.x - PAPER_TEX_PAD, PAPER.y - PAPER_TEX_PAD, 'sudoku-paper').setOrigin(0).setDepth(D.paper); + this.buildProps(); - await this.showStartPanel(); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this._onBlur = () => { if (this.mode === 'play' && this.timerOn && !this.paused && !this.gameEnded) this.setPaused(true); }; + this.game.events.on('blur', this._onBlur); + this.game.events.on('hidden', this._onBlur); + this.events.once('shutdown', () => this.onShutdown()); + + const next = this.next; + if (next?.resume) { + const save = parseSave(storage()?.getItem(SAVE_KEY)); + if (save) { this.beginFromSave(save); return; } + } + if (next?.difficulty) { this.startGame(next.difficulty, { daily: next.daily ?? null }); return; } + this.showStart({ intro: !next }); } - // ── Start panel ─────────────────────────────────────────────────────────────── + onShutdown() { + this.saveGame(); + this.game.events.off('blur', this._onBlur); + this.game.events.off('hidden', this._onBlur); + } - async showStartPanel() { - const cx = CX, cy = CY; + restartWith(next) { + this.scene.restart({ ...this._initData, next }); + } - const sheet = this.add.graphics().setDepth(DEPTH.paper); - sheet.postFX.addShadow(0, 6, 0.02, 1.2, 0x000000, 10, 0.6); - sheet.fillStyle(PAPER, 1); - sheet.fillRoundedRect(cx - 600, cy - 310, 1200, 620, 18); - sheet.lineStyle(3, PAPER_EDGE, 1); - sheet.strokeRoundedRect(cx - 600, cy - 310, 1200, 620, 18); - this.startObjs.push(sheet); + leave() { + this.saveGame(); + this.scene.start('GameMenu'); + } - this.startObjs.push( - this.add.text(cx, cy - 220, 'Sudoku', { - fontFamily: 'YummyCupcakes', fontSize: '100px', color: TITLE_BROWN, - }).setOrigin(0.5).setDepth(DEPTH.ui), - ); + // ── Table props (both screens) ────────────────────────────────────────────── - this.startObjs.push( - this.add.text(cx, cy - 114, 'Choose difficulty', { - fontFamily: 'YummyCupcakes', fontSize: '46px', color: INK, - }).setOrigin(0.5).setDepth(DEPTH.ui), - ); + buildProps() { + // coffee steam: a few soft wisps rising and fading on a loop + for (let k = 0; k < 4; k++) { + const wisp = this.add.image(CUP.x, CUP.y, 'sudoku-steam').setDepth(D.props).setAlpha(0); + const p = { t: 0 }; + const drift = (k % 2 ? 1 : -1) * (10 + k * 6); + this.tweens.add({ + targets: p, t: 1, duration: 3200, delay: k * 800, repeat: -1, + onUpdate: () => { + const t = p.t; + wisp.setPosition(CUP.x + Math.sin(t * Math.PI * 1.5 + k) * drift, CUP.y - 10 - t * 150); + wisp.setScale(0.6 + t * 1.3); + wisp.setAlpha(Math.sin(t * Math.PI) * 0.42); + }, + }); + } + // the wristwatch timer + this.add.image(WATCH.x, WATCH.y, 'sudoku-watch').setDepth(D.props); + this.watchHands = this.add.graphics().setDepth(D.props + 1); + this.watchText = this.add.text(WATCH.x, WATCH.y + 27, '', { + fontFamily: 'Righteous', fontSize: '17px', color: INK, + }).setOrigin(0.5).setDepth(D.props + 1); + this.drawWatch(); + } - const diffs = [ - ['Very Easy', 'very-easy'], - ['Easy', 'easy'], - ['Regular', 'regular'], - ['Hard', 'hard'], - ['Brutal', 'brutal'], - ]; - diffs.forEach(([label, id], i) => { - const b = new Button(this, cx + (i - 2) * 230, cy + 10, label, - () => this.startGame(id), { width: 200, height: 62, fontSize: 22 }); - b.setDepth(DEPTH.ui); - this.startObjs.push(b); + // Start page: the wall-clock time. Play: elapsed minutes + seconds. + drawWatch() { + const g = this.watchHands; + if (!g) return; + g.clear(); + const hand = (angle, len, width, color, alpha = 1) => { + g.lineStyle(width, color, alpha); + g.lineBetween(WATCH.x - Math.sin(angle) * 8, WATCH.y + Math.cos(angle) * 8, + WATCH.x + Math.sin(angle) * len, WATCH.y - Math.cos(angle) * len); + }; + if (this.mode === 'play') { + const sec = this.elapsed / 1000; + hand(((sec / 60) % 60) / 60 * Math.PI * 2, 46, 4, INK_N); + hand((Math.floor(sec) % 60) / 60 * Math.PI * 2, 56, 1.6, RED_INK_N); + this.watchText.setText(formatTime(this.elapsed)); + } else { + const now = new Date(); + const m = now.getMinutes() + now.getSeconds() / 60; + hand(((now.getHours() % 12) + m / 60) / 12 * Math.PI * 2, 34, 5, INK_N); + hand(m / 60 * Math.PI * 2, 50, 3.4, INK_N); + this.watchText.setText(''); + } + g.fillStyle(INK_N, 1); g.fillCircle(WATCH.x, WATCH.y, 4.5); + g.fillStyle(RED_INK_N, 1); g.fillCircle(WATCH.x, WATCH.y, 2); + } + + // ── Start screen ──────────────────────────────────────────────────────────── + + showStart({ intro = false } = {}) { + this.mode = 'start'; + if (intro) { + this.introBusy = true; + this.paperImg.setPosition(PAPER.x - PAPER_TEX_PAD + 40, H + 60).setAngle(5); + playSound(this, SFX.UI_FLIP); + this.tweens.add({ + targets: this.paperImg, x: PAPER.x - PAPER_TEX_PAD, y: PAPER.y - PAPER_TEX_PAD, angle: 0, + duration: 620, ease: 'Cubic.easeOut', + onComplete: () => { this.introBusy = false; this.buildStart(); this.maybeFirstGuide(); }, + }); + return; + } + this.buildStart(); + } + + buildStart() { + const add = (o) => { this.startObjs.push(o); return o; }; + const save = parseSave(storage()?.getItem(SAVE_KEY)); + const today = todayString(); + + add(this.add.text(PAPER_CX, DATELINE_Y, `${longDate(today)} · PUZZLES & PASTIMES · ONE DOLLAR`, { + fontFamily: SERIF, fontSize: '15px', color: INK, fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.ui)); + add(this.add.text(PAPER_CX, HEADER_Y, "This Week's Sudoku", { + fontFamily: SERIF, fontSize: '40px', color: INK, fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.ui)); + const rule = add(this.add.graphics().setDepth(D.ui)); + rule.lineStyle(1.2, INK_N, 0.7); + rule.lineBetween(PAPER.x + 60, HEADER_Y + 28, PAPER.x + PAPER.w - 60, HEADER_Y + 28); + + const dailyRec = readJSON(DAILY_KEY) ?? blankDaily(); + const dailyTime = dailyRec.solved?.[today]; + const statLine = (mode) => { + const s = loadStats('sudoku', mode); + if (!s.played) return 'Not yet attempted'; + return `Solved ${s.won} · Best ${formatTime(s.bestTime)} · Streak ${s.streak}`; + }; + + const cards = []; + if (save) { + const givenFlat = save.givens.flat(); + const empties = givenFlat.filter(g => !g).length; + const filled = save.grid.flat().filter((v, i) => v && !givenFlat[i]).length; + const label = save.daily ? `Today's Edition (${save.daily})` : `${EDITION[save.difficulty].day} · ${DIFF_LABELS[save.difficulty]}`; + cards.push({ title: 'Resume your puzzle', stars: EDITION[save.difficulty].stars, accent: true, + desc: `${label} · No. ${save.puzzleNo || '—'}`, + stats: `${formatTime(save.elapsed)} on the watch · ${filled} / ${empties} cells pencilled in`, + go: () => this.restartWith({ resume: true }) }); + } + cards.push({ title: "Today's Edition", stars: EDITION[DAILY_DIFFICULTY].stars, + desc: 'One puzzle for everyone today · Wednesday rules', + stats: `Day streak ${dailyStreakNow(dailyRec, today)} · Today: ${dailyTime != null ? `solved in ${formatTime(dailyTime)}` : 'not yet solved'}`, + go: () => this.pickEdition(DAILY_DIFFICULTY, today, save) }); + for (const d of ['very-easy', 'easy', 'regular', 'hard', 'brutal']) { + cards.push({ title: `${EDITION[d].day} · ${DIFF_LABELS[d]}`, stars: EDITION[d].stars, + desc: DESC[d], stats: statLine(d), go: () => this.pickEdition(d, null, save) }); + } + + const pitch = cards.length > 6 ? 104 : 114; + const y0 = cards.length > 6 ? 350 : 356; + cards.forEach((spec, i) => this.makeCard(add, PAPER_CX, y0 + i * pitch, spec, i)); + + // the guest-check pad: today's order, plus how-to + leave + add(this.add.image(PAD.x - PAPER_TEX_PAD, PAD.y - PAPER_TEX_PAD, 'sudoku-notepad').setOrigin(0).setDepth(D.pad)); + add(this.add.text(PAD.x + 40, PAD.y + 104, + '1 café crème\n1 croissant\n1 sudoku, in pencil\n\n\n thank you!', { + fontFamily: 'YummyCupcakes', fontSize: '38px', color: GRAPHITE, lineSpacing: 0, + }).setOrigin(0, 0).setDepth(D.pad + 1).setAngle(-1.5)); + add(this.add.text(PAD.x + PAD.w - 40, PAD.y + 112, '3.40\n2.80\n—', { + fontFamily: 'YummyCupcakes', fontSize: '34px', color: GRAPHITE, align: 'right', lineSpacing: 6, + }).setOrigin(1, 0).setDepth(D.pad + 1).setAngle(-1.5)); + add(new NewsButton(this, RCX - 110, BTN_Y2, 'How to play', () => this.openGuide(), { width: 200 }).setDepth(D.ui)); + add(new NewsButton(this, RCX + 110, BTN_Y2, 'Leave', () => this.scene.start('GameMenu'), { width: 200 }).setDepth(D.ui)); + } + + makeCard(add, x, y, spec, i) { + const cont = add(this.add.container(x, y).setDepth(D.ui)); + const img = this.add.image(0, 0, 'sudoku-card'); + const left = -CARD_W / 2 + 100; + const title = this.add.text(left, -22, spec.title, { + fontFamily: SERIF, fontSize: '28px', color: spec.accent ? RED_INK : INK, fontStyle: 'bold', + }).setOrigin(0, 0.5); + const st = this.add.text(CARD_W / 2 - 30, -22, stars(spec.stars), { + fontFamily: SERIF, fontSize: '22px', color: RED_INK, + }).setOrigin(1, 0.5); + const desc = this.add.text(left, 7, spec.desc, { + fontFamily: SERIF, fontSize: '17px', color: INK, fontStyle: 'italic', + }).setOrigin(0, 0.5); + const stats = this.add.text(left, 31, spec.stats, { + fontFamily: SERIF, fontSize: '16px', color: FADED, + }).setOrigin(0, 0.5); + cont.add([img, title, st, desc, stats]); + const tiltA = i % 2 ? 0.35 : -0.3; + cont.setAngle(tiltA); + cont.setSize(CARD_W, CARD_H); + cont.setInteractive({ useHandCursor: true }); + cont.on('pointerover', () => this.tweens.add({ targets: cont, x: x + 6, angle: 0, duration: 120 })); + cont.on('pointerout', () => this.tweens.add({ targets: cont, x, angle: tiltA, duration: 160 })); + cont.on('pointerup', () => { + if (this.introBusy || this.modal || this.mode !== 'start') return; + playSound(this, SFX.UI_PICK); + spec.go(); }); - - const leave = new Button(this, cx, cy + 140, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 200, height: 50, fontSize: 22 }); - leave.setDepth(DEPTH.ui); - this.startObjs.push(leave); } - destroyStart() { - this.startObjs.forEach(o => o.destroy()); - this.startObjs = []; + maybeFirstGuide() { + if (storage()?.getItem(GUIDE_SEEN_KEY)) return; + this.time.delayedCall(200, () => { if (!this.modal) this.openGuide(); }); } - // ── Game start ──────────────────────────────────────────────────────────────── + // Choosing an edition when a save exists abandons it (counted as played, not won). + pickEdition(difficulty, daily, save) { + if (save && daily && save.daily === daily) { this.restartWith({ resume: true }); return; } + if (save && save.moves > 0) { + const what = save.daily ? "Today's Edition" : `${EDITION[save.difficulty].day}'s puzzle`; + this.confirm('Start a new puzzle?', `Your saved ${what} will be abandoned.`, + 'Abandon it', () => { this.abandonSave(save); this.restartWith({ difficulty, daily }); }); + return; + } + storage()?.removeItem(SAVE_KEY); + this.restartWith({ difficulty, daily }); + } - async startGame(difficulty) { - this.destroyStart(); - playSound(this, SFX.PIECE_CLICK); + abandonSave(save) { + recordGame('sudoku', { won: false, time: save.elapsed, moves: save.moves, mode: save.daily ? 'daily' : save.difficulty }); + storage()?.removeItem(SAVE_KEY); + } + // ── Game start ───────────────────────────────────────────────────────────── + + async startGame(difficulty, { daily = null } = {}) { + this.mode = 'loading'; + const loading = this.add.text(PAPER_CX, GRID_Y + GRID_W / 2, 'Fetching the morning paper…', { + fontFamily: SERIF, fontSize: '36px', color: FADED, fontStyle: 'italic', + }).setOrigin(0.5).setDepth(D.ui); + // let the loading line render before the (synchronous) generator runs + await new Promise((res) => this.time.delayedCall(40, res)); + const seedQ = daily ? `&seed=${dailySeed(daily)}` : ''; let data; try { - data = await api.get(`/words/sudoku/start?difficulty=${difficulty}`); + data = await api.get(`/words/sudoku/start?difficulty=${difficulty}${seedQ}`); } catch (err) { console.error('[sudoku] failed to fetch puzzle:', err); - await this.showStartPanel(); + loading.destroy(); + this.showStart(); return; } + if (!this.sys.isActive()) return; + loading.destroy(); - this.grid = data.grid.map(row => [...row]); - this.solution = data.solution; - this.difficulty = difficulty; - this.selectedNum = 1; - this.hintsLeft = HINT_LIMITS[difficulty] ?? 0; - this.hintsUsed = 0; - this.gameEnded = false; - this.hoveredCell = null; + this.difficulty = difficulty; + this.daily = daily; + this.grid = data.grid.map(row => [...row]); + this.solution = data.solution; + this.tier = data.tier ?? null; + this.givens = this.grid.map(row => row.map(v => v !== 0)); + this.cellState = Array.from({ length: N }, () => Array(N).fill(0)); + this.hintsLeft = HINT_LIMITS[difficulty] ?? 0; + this.puzzleNo = daily ? 1000 + (dailySeed(daily) % 9000) : 1000 + Math.floor(Math.random() * 9000); + this.buildPlay(); + } - this.givenCells = this.grid.map(row => row.map(v => v !== 0)); - this.cellState = Array.from({ length: 9 }, () => Array(9).fill(0)); - this.revealed = false; + beginFromSave(s) { + this.difficulty = s.difficulty; + this.daily = s.daily; + this.grid = s.grid; this.solution = s.solution; this.givens = s.givens; + this.hinted = new Set(s.hinted ?? []); + this.cellState = s.cellState; + this.history = s.history; + this.elapsed = s.elapsed; + this.hintsLeft = s.hintsLeft; this.hintsUsed = s.hintsUsed; this.mistakes = s.mistakes; + this.revealed = s.revealed; + this.moves = s.moves; + this.tier = s.tier ?? null; + this.puzzleNo = s.puzzleNo || 1000 + Math.floor(Math.random() * 9000); + this.timerOn = this.moves > 0; + this.buildPlay(); + this.toast('Welcome back. Your puzzle is where you left it.'); + } - this.buildPaper(); - this.buildRuledLines(); - this.buildMarginLine(); - this.buildTitle(); - this.buildGrid(); - this.buildSelector(); - if (this.hintsLeft > 0) this.buildHintBtn(); + // ── Play screen ──────────────────────────────────────────────────────────── + + buildPlay() { + this.mode = 'play'; + this.buildHeader(); + this.buildBoard(); + this.buildSide(); + this.buildPad(); this.buildControls(); - this.refreshSelector(); - this.updateCompletedNums(); + this.refreshAll(); } - // ── Paper & notebook decoration ─────────────────────────────────────────────── - - buildPaper() { - const g = this.add.graphics().setDepth(DEPTH.paper); - g.postFX.addShadow(0, 8, 0.02, 1.2, 0x000000, 14, 0.55); - g.fillStyle(PAPER, 1); - g.fillRoundedRect(PX, PY, PW, PH, 16); - g.lineStyle(2, PAPER_EDGE, 1); - g.strokeRoundedRect(PX, PY, PW, PH, 16); - - // Spiral binding — top only - const spiralG = this.add.graphics().setDepth(DEPTH.paper + 1); - const spiralCnt = 32; - const step = PW / (spiralCnt + 1); - for (let i = 1; i <= spiralCnt; i++) { - const sx = PX + step * i; - const sy = PY + 40; - spiralG.fillStyle(SPIRAL_CLR, 0.75); - spiralG.fillCircle(sx, sy, 18); - spiralG.fillStyle(0x000000, 1); - spiralG.fillCircle(sx, sy, 12); - } + editionLabel() { + return this.daily ? "Today's Edition" : `${EDITION[this.difficulty].day} · ${DIFF_LABELS[this.difficulty]}`; } - buildRuledLines() { - const g = this.add.graphics().setDepth(DEPTH.lines); - g.lineStyle(1, 0xbcd0e0, 0.35); - for (let y = PY + 150; y < PY + PH - 30; y += 44) { - g.lineBetween(PX + 30, y, PX + PW - 30, y); - } + buildHeader() { + const date = this.daily ?? todayString(); + this.add.text(PAPER_CX, DATELINE_Y, `${longDate(date)} · PUZZLE No. ${this.puzzleNo} · ONE DOLLAR`, { + fontFamily: SERIF, fontSize: '15px', color: INK, fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.ui); + this.add.image(PRINT.x, PRINT.y, 'sudoku-print').setOrigin(0).setDepth(D.print); + this.add.text(GRID_X, HEADER_Y - 2, 'SUDOKU', { + fontFamily: SERIF, fontSize: '40px', color: INK, fontStyle: 'bold', + }).setOrigin(0, 0.5).setDepth(D.ui); + this.add.text(SIDE.x + SIDE.w, HEADER_Y + 2, + `${this.editionLabel()}${this.daily ? ` · ${DIFF_LABELS[this.difficulty]}` : ''} ${stars(EDITION[this.difficulty].stars)}`, { + fontFamily: SERIF, fontSize: '20px', color: INK, fontStyle: 'italic', + }).setOrigin(1, 0.5).setDepth(D.ui); } - buildMarginLine() { - const g = this.add.graphics().setDepth(DEPTH.lines); - g.lineStyle(2, RED_CIRCLE, 0.52); - g.lineBetween(MARGIN_X, PY + 10, MARGIN_X, PY + PH - 10); - } + buildBoard() { + this.hlGfx = this.add.graphics().setDepth(D.hl); + this.stateGfx = this.add.graphics().setDepth(D.state); + this.smudgeGfx = this.add.graphics().setDepth(D.smudge); + this.hoverGfx = this.add.graphics().setDepth(D.hover); + this.conflictGfx = this.add.graphics().setDepth(D.conflicts); + this.cursorGfx = this.add.graphics().setDepth(D.cursor); - buildTitle() { - const titleTxt = this.add.text(TITLE_CX, 132, 'Sudoku', { - fontFamily: 'YummyCupcakes', fontSize: '84px', color: TITLE_BROWN, - }).setOrigin(0.5).setDepth(DEPTH.ui); - - this.add.text(titleTxt.x + titleTxt.width / 2 + 24, titleTxt.y + 14, - DIFF_LABELS[this.difficulty] ?? this.difficulty, { - fontFamily: 'YummyCupcakes', fontSize: '36px', color: FADED, - }).setOrigin(0, 0.5).setDepth(DEPTH.ui); - } - - // ── Grid ────────────────────────────────────────────────────────────────────── - - buildGrid() { - const gfx = this.add.graphics().setDepth(DEPTH.gridLines); - - // Faint cell dividers - gfx.lineStyle(1, INK_N, 0.18); - for (let i = 1; i <= 8; i++) { - if (i % 3 === 0) continue; - gfx.lineBetween(GRID_X + i * CELL, GRID_Y, GRID_X + i * CELL, GRID_Y + GRID_H); - gfx.lineBetween(GRID_X, GRID_Y + i * CELL, GRID_X + GRID_W, GRID_Y + i * CELL); - } - - // Box dividers - gfx.lineStyle(3, INK_N, 0.58); - for (let i = 1; i <= 2; i++) { - gfx.lineBetween(GRID_X + i * 3 * CELL, GRID_Y, GRID_X + i * 3 * CELL, GRID_Y + GRID_H); - gfx.lineBetween(GRID_X, GRID_Y + i * 3 * CELL, GRID_X + GRID_W, GRID_Y + i * 3 * CELL); - } - - // Outer border - gfx.lineStyle(4, INK_N, 0.78); - gfx.strokeRect(GRID_X, GRID_Y, GRID_W, GRID_H); - - this.cellBgObjs = []; - this.cellTextObjs = []; - this.cellHitObjs = []; - - for (let r = 0; r < 9; r++) { - this.cellBgObjs.push([]); - this.cellTextObjs.push([]); - this.cellHitObjs.push([]); - - for (let c = 0; c < 9; c++) { - const cx = GRID_X + c * CELL + CELL / 2; - const cy = GRID_Y + r * CELL + CELL / 2; - const given = this.givenCells[r][c]; - const val = this.grid[r][c]; - - const bg = this.add.graphics().setDepth(DEPTH.cell); - this.cellBgObjs[r].push(bg); - - const txt = this.add.text(cx, cy, given ? String(val) : '', { - fontFamily: given ? 'Righteous' : 'YummyCupcakes', - fontSize: given ? '40px' : '46px', - color: given ? INK : PLAYER_INK, - }).setOrigin(0.5).setDepth(DEPTH.number); - this.cellTextObjs[r].push(txt); - - if (given) { - this.cellHitObjs[r].push(null); - } else { - const hit = this.add.rectangle(cx, cy, CELL - 2, CELL - 2, 0xffffff, 0.001) - .setDepth(DEPTH.hit) - .setInteractive({ useHandCursor: true }); - hit.on('pointerover', () => this.onCellHover(r, c, true)); - hit.on('pointerout', () => this.onCellHover(r, c, false)); - hit.on('pointerdown', () => this.onCellClick(r, c)); - this.cellHitObjs[r].push(hit); - } + this.cellText = Array.from({ length: N }, () => Array(N).fill(null)); + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) { + this.cellText[r][c] = this.add.text(cellCX(c), cellCY(r) + 2, '', { + fontFamily: 'YummyCupcakes', fontSize: '56px', color: GRAPHITE, + }).setOrigin(0.5).setDepth(D.digits); + this.renderCellText(r, c); } - } + + const zone = this.add.zone(GRID_X + GRID_W / 2, GRID_Y + GRID_W / 2, GRID_W, GRID_W) + .setDepth(D.hit).setInteractive({ useHandCursor: true }); + const cellAt = (p) => { + const c = Math.floor((p.worldX - GRID_X) / CELL), r = Math.floor((p.worldY - GRID_Y) / CELL); + return r >= 0 && r < N && c >= 0 && c < N ? { r, c } : null; + }; + zone.on('pointermove', (p) => { + const h = cellAt(p); + if (h?.r !== this.hover?.r || h?.c !== this.hover?.c) { this.hover = h; this.drawHover(); } + }); + zone.on('pointerout', () => { this.hover = null; this.drawHover(); }); + zone.on('pointerdown', (p) => { const h = cellAt(p); if (h) this.onCellPointer(h.r, h.c); }); } - // ── Number selector ─────────────────────────────────────────────────────────── - - buildSelector() { - this.numCircleGfx = this.add.graphics().setDepth(DEPTH.selector); - this.numStrikeGfx = this.add.graphics().setDepth(DEPTH.selector + 2); - this.numHitObjs = {}; - this.numTextObjs = {}; - - for (let n = 1; n <= 9; n++) { - const ny = NUM_START_Y + (n - 1) * NUM_STEP; - - const numTxt = this.add.text(NUM_X, ny, String(n), { - fontFamily: '"Julius Sans One"', fontSize: '70px', color: INK, - }).setOrigin(0.5).setDepth(DEPTH.number + 1); - this.numTextObjs[n] = numTxt; - - const hit = this.add.rectangle(NUM_X, ny, 210, NUM_STEP - 4, 0xffffff, 0.001) - .setDepth(DEPTH.hit + 1) - .setInteractive({ useHandCursor: true }); - hit.on('pointerdown', () => this.selectNum(n)); - this.numHitObjs[n] = hit; - } - - // Eraser × - this.add.text(NUM_X, ERASER_CY, '×', { - fontFamily: '"Julius Sans One"', fontSize: '56px', color: FADED, - }).setOrigin(0.5).setDepth(DEPTH.number + 1); - - const eraserHit = this.add.rectangle(NUM_X, ERASER_CY, 210, NUM_STEP - 4, 0xffffff, 0.001) - .setDepth(DEPTH.hit + 1) - .setInteractive({ useHandCursor: true }); - eraserHit.on('pointerdown', () => this.selectNum(0)); - this.numHitObjs[0] = eraserHit; - } - - refreshSelector() { - const gfx = this.numCircleGfx; - if (!gfx) return; - gfx.clear(); - - let cy; - if (this.selectedNum >= 1 && this.selectedNum <= 9) { - cy = NUM_START_Y + (this.selectedNum - 1) * NUM_STEP; - } else if (this.selectedNum === 0) { - cy = ERASER_CY; + renderCellText(r, c) { + const t = this.cellText[r]?.[c]; + if (!t) return; + const v = this.grid[r][c]; + t.setText(v ? String(v) : ''); + if (this.givens[r][c]) { + const hinted = this.hinted.has(`${r},${c}`); + t.setFontFamily(SERIF).setFontStyle('bold').setFontSize(46).setColor(hinted ? HINT_COLOR : INK).setAngle(0); } else { - return; + t.setFontFamily('YummyCupcakes').setFontStyle('').setFontSize(58).setColor(GRAPHITE).setAngle(this.tilt[r][c]); } - this.drawHandCircle(gfx, NUM_X, cy); } - drawHandCircle(gfx, cx, cy) { - // Two slightly-offset ellipses for a hand-drawn wobble - gfx.lineStyle(3, RED_CIRCLE, 0.88); - gfx.strokeEllipse(cx, cy, 88, 78); - gfx.lineStyle(2, RED_CIRCLE, 0.28); - gfx.strokeEllipse(cx + 3, cy - 2, 92, 82); + buildSide() { + const x = SIDE.x, w = SIDE.w; + const head = (y, s) => this.add.text(x, y, s, { fontFamily: SERIF, fontSize: '15px', color: INK, fontStyle: 'bold' }).setOrigin(0, 0.5).setDepth(D.ui); + const body = (y, s, color = INK) => this.add.text(x, y, s, { + fontFamily: SERIF, fontSize: '15px', color, wordWrap: { width: w }, lineSpacing: 3, + }).setOrigin(0, 0).setDepth(D.ui); + head(GRID_Y + 10, 'HOW TO PLAY'); + body(GRID_Y + 26, 'Fill the grid so every row, every column and every 3×3 box holds the numbers 1 to 9 exactly once.'); + head(GRID_Y + 158, 'THIS PUZZLE'); + const givens = this.givens.flat().filter(Boolean).length - this.hinted.size; + const hints = Number.isFinite(this.hintsLeft) ? (HINT_LIMITS[this.difficulty] ? `${HINT_LIMITS[this.difficulty]} hints` : 'No hints') : 'Unlimited hints'; + body(GRID_Y + 174, `${givens} givens\n${hints}\nNo. ${this.puzzleNo}`); + head(GRID_Y + 254, 'CHECKING'); + this.ruleText = body(GRID_Y + 270, this.ruleLine(), RED_INK); } - updateCompletedNums() { - const gfx = this.numStrikeGfx; - if (!gfx) return; - gfx.clear(); + ruleLine() { + if (isEasyTier(this.difficulty)) return 'Every entry is checked as you write. Clashes are circled.'; + if (this.revealed) return 'Grid checked. Entries are now checked as you write.'; + return 'Checked once every square is filled in.'; + } + buildPad() { + this.add.image(PAD.x - PAPER_TEX_PAD, PAD.y - PAPER_TEX_PAD, 'sudoku-notepad').setOrigin(0).setDepth(D.pad); + this.statText = this.add.text(PAD.x + 26, PAD.y + 100, '', { + fontFamily: 'YummyCupcakes', fontSize: '30px', color: GRAPHITE, + }).setOrigin(0, 0.5).setDepth(D.pad + 1).setAngle(-1); + this.padSel = this.add.graphics().setDepth(D.pad + 3); + this.padStrike = this.add.graphics().setDepth(D.pad + 4); for (let n = 1; n <= 9; n++) { - let count = 0; - for (let r = 0; r < 9; r++) - for (let c = 0; c < 9; c++) - if (this.grid[r][c] === n) count++; - - const txt = this.numTextObjs[n]; - if (!txt) continue; - - if (count === 9) { - txt.setColor('#b0a090'); - const ny = NUM_START_Y + (n - 1) * NUM_STEP; - gfx.lineStyle(3, 0x8a7a6a, 0.8); - gfx.lineBetween(NUM_X - 36, ny - 6, NUM_X + 36, ny - 6); - } else { - txt.setColor(INK); - } + const { x, y } = padXY(n); + const txt = this.add.text(x, y - 8, String(n), { + fontFamily: 'YummyCupcakes', fontSize: '80px', color: GRAPHITE, + }).setOrigin(0.5).setDepth(D.pad + 2).setAngle((n % 3 - 1) * 2); + const tally = this.add.text(x, y + 42, '', { + fontFamily: SERIF, fontSize: '15px', color: FADED, fontStyle: 'italic', + }).setOrigin(0.5).setDepth(D.pad + 2); + const zone = this.add.zone(x, y, PAD_PITCH - 8, PAD_PITCH - 8).setDepth(D.hit).setInteractive({ useHandCursor: true }); + zone.on('pointerover', () => this.tweens.add({ targets: txt, scale: 1.12, duration: 100 })); + zone.on('pointerout', () => this.tweens.add({ targets: txt, scale: 1, duration: 140 })); + zone.on('pointerup', () => this.onPadPointer(n)); + this.padCells[n] = { txt, tally, zone, x, y }; } + const eimg = this.add.image(RCX, ERASER_Y, 'sudoku-eraser').setDepth(D.pad + 2); + const ezone = this.add.zone(RCX, ERASER_Y, 170, 90).setDepth(D.hit).setInteractive({ useHandCursor: true }); + ezone.on('pointerover', () => this.tweens.add({ targets: eimg, angle: 4, duration: 100 })); + ezone.on('pointerout', () => this.tweens.add({ targets: eimg, angle: 0, duration: 140 })); + ezone.on('pointerup', () => this.onPadPointer(0)); + this.padCells[0] = { img: eimg, zone: ezone, x: RCX, y: ERASER_Y }; } - // ── Hint button ─────────────────────────────────────────────────────────────── - - buildHintBtn() { - const isLimited = isFinite(this.hintsLeft); - const label = isLimited ? `Hint (${this.hintsLeft} left)` : 'Hint'; - - this.hintBtn = new Button(this, NUM_X, HINT_BTN_Y, label, - () => this.useHint(), { width: 230, height: 54, fontSize: 22 }); - this.hintBtn.setDepth(DEPTH.ui); - } - - updateHintBtn() { - if (!this.hintBtn) return; - const isLimited = isFinite(this.hintsLeft); - this.hintBtn.setLabel(isLimited ? `Hint (${this.hintsLeft} left)` : 'Hint'); - if (this.hintsLeft === 0) this.hintBtn.setEnabled(false); - } - - // ── Controls ────────────────────────────────────────────────────────────────── - buildControls() { - new Button(this, PX + 160, BTN_Y, 'New puzzle', - () => this.scene.restart(this._initData), - { variant: 'ghost', width: 230, height: 50, fontSize: 22 }).setDepth(DEPTH.ui); - - new Button(this, PX + PW - 130, BTN_Y, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 200, height: 50, fontSize: 22 }).setDepth(DEPTH.ui); + const bw = 140, bp = 150; + this.undoBtn = new NewsButton(this, RCX - 1.5 * bp, BTN_Y1, 'Undo', () => this.doUndo(), { width: bw }).setDepth(D.ui); + this.redoBtn = new NewsButton(this, RCX - 0.5 * bp, BTN_Y1, 'Redo', () => this.doRedo(), { width: bw }).setDepth(D.ui); + this.hintBtn = new NewsButton(this, RCX + 0.5 * bp, BTN_Y1, 'Hint', () => this.useHint(), { width: bw }).setDepth(D.ui); + this.pauseBtn = new NewsButton(this, RCX + 1.5 * bp, BTN_Y1, 'Pause', () => this.setPaused(!this.paused), { width: bw }).setDepth(D.ui); + new NewsButton(this, RCX - 210, BTN_Y2, 'How to play', () => this.openGuide(), { width: 196 }).setDepth(D.ui); + new NewsButton(this, RCX, BTN_Y2, 'New puzzle', () => this.newPuzzle(), { width: 196, accent: true }).setDepth(D.ui); + new NewsButton(this, RCX + 210, BTN_Y2, 'Leave', () => this.leave(), { width: 196 }).setDepth(D.ui); } - // ── Input ───────────────────────────────────────────────────────────────────── + // ── Rendering ─────────────────────────────────────────────────────────────── - selectNum(num) { - this.selectedNum = num; - this.refreshSelector(); - playSound(this, SFX.PIECE_CLICK); + refreshAll() { + this.drawState(); + this.recomputeUnits(false); + this.refreshPad(false); + this.refreshButtons(); + this.refreshStats(); + this.refreshFocus(); + this.drawConflicts(); + this.drawWatch(); } - onCellHover(r, c, entering) { - this.hoveredCell = entering ? { r, c } : null; - this.drawCellBg(r, c, entering); + isChecking() { return isEasyTier(this.difficulty) || this.revealed; } + showsConflicts() { return isEasyTier(this.difficulty); } + + refreshFocus() { + this.drawHighlights(); + this.drawCursor(); } - onCellClick(r, c) { - if (this.gameEnded || this.givenCells[r][c]) return; - playSound(this, SFX.PIECE_CLICK); + drawState() { + const g = this.stateGfx; + if (!g) return; + g.clear(); + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) { + const st = this.cellState[r][c]; + if (!st) continue; + const x = GRID_X + c * CELL + 4, y = GRID_Y + r * CELL + 4, s = CELL - 8; + if (st === 1) { + g.fillStyle(0x3c8a4e, 0.09); + g.fillRect(x, y, s, s); + } else { + g.fillStyle(RED_INK_N, 0.09); + g.fillRect(x, y, s, s); + g.lineStyle(1.4, RED_INK_N, 0.42); + for (let t = 11; t < s * 2; t += 11) { + const ax = x + Math.max(0, t - s), ay = y + Math.min(t, s); + const bx = x + Math.min(t, s), by = y + Math.max(0, t - s); + g.lineBetween(ax, ay, bx, by); + } + } + } + } - if (this.selectedNum === 0) { - this.clearCell(r, c); - } else if (this.grid[r][c] === this.selectedNum) { - this.clearCell(r, c); - } else { - this.placeNum(r, c, this.selectedNum); + // The digit everything else lights up for: the digit picked on the pad, else + // the cursor cell's value. + focusDigit() { + if (this.armed >= 1) return this.armed; + if (this.cursor) { + const v = this.grid[this.cursor.r][this.cursor.c]; + if (v) return v; + } + return 0; + } + + drawHighlights() { + const g = this.hlGfx; + if (!g) return; + g.clear(); + if (this.mode !== 'play' || this.gameEnded || this.paused) return; + if (this.cursor) { + const { r, c } = this.cursor; + const b = boxOf(r, c); + g.fillStyle(0x5a7fa6, 0.085); + for (let rr = 0; rr < N; rr++) + for (let cc = 0; cc < N; cc++) + if (rr === r || cc === c || boxOf(rr, cc) === b) g.fillRect(GRID_X + cc * CELL, GRID_Y + rr * CELL, CELL, CELL); + g.fillStyle(0x5a7fa6, 0.12); + g.fillRect(GRID_X + c * CELL, GRID_Y + r * CELL, CELL, CELL); + } + const d = this.focusDigit(); + if (d) { + // highlighter strokes: slightly uneven bars over each matching digit + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) { + if (this.grid[r][c] !== d) continue; + const x = GRID_X + c * CELL, y = GRID_Y + r * CELL; + g.fillStyle(HIGHLIGHT_N, 0.5); + g.fillRoundedRect(x + 7, y + 12, CELL - 14, CELL - 22, 6); + g.fillStyle(HIGHLIGHT_N, 0.22); + g.fillRoundedRect(x + 4, y + 16, CELL - 8, CELL - 30, 6); + } } } - placeNum(r, c, num) { - this.grid[r][c] = num; - this.cellTextObjs[r][c].setText(String(num)); + drawConflicts() { + const g = this.conflictGfx; + if (!g) return; + g.clear(); + if (!this.showsConflicts() || this.gameEnded) return; + for (const key of findConflicts(this.grid)) { + const [r, c] = key.split(',').map(Number); + const x = cellCX(c), y = cellCY(r) + 2; + g.lineStyle(2.8, RED_INK_N, 0.85); + g.strokeEllipse(x, y, 58, 62); + g.lineStyle(1.4, RED_INK_N, 0.35); + g.strokeEllipse(x + 2, y - 2, 64, 64); + } + } - const hovered = this.hoveredCell?.r === r && this.hoveredCell?.c === c; + drawHover() { + const g = this.hoverGfx; + if (!g) return; + g.clear(); + if (!this.hover || this.mode !== 'play' || this.paused || this.gameEnded) return; + const { r, c } = this.hover; + g.fillStyle(INK_N, this.givens[r][c] ? 0.03 : 0.07); + g.fillRect(GRID_X + c * CELL + 3, GRID_Y + r * CELL + 3, CELL - 6, CELL - 6); + } - if (this.isEasyMode() || this.revealed) { - const correct = (num === this.solution[r][c]); - this.cellState[r][c] = correct ? 1 : 2; - this.drawCellBg(r, c, hovered); + drawCursor(offsetX = 0) { + const g = this.cursorGfx; + if (!g) return; + g.clear(); + if (!this.cursor || this.gameEnded || this.paused) return; + const { r, c } = this.cursor; + const x = GRID_X + c * CELL + 5 + offsetX, y = GRID_Y + r * CELL + 5, s = CELL - 10; + g.lineStyle(3.2, RED_INK_N, 0.9); + g.strokeRoundedRect(x, y, s, s, 8); + g.lineStyle(1.3, RED_INK_N, 0.35); + g.strokeRoundedRect(x - 2, y + 1, s + 3, s - 1, 10); + } - if (correct && isBoardComplete(this.grid, this.solution)) { - this.time.delayedCall(300, () => this.handleWin()); + // Pad: remaining tallies, struck-off digits, the armed ring. + refreshPad(animate = true) { + if (!this.padSel) return; + const counts = digitCounts(this.grid); + for (let n = 1; n <= 9; n++) { + const p = this.padCells[n]; + const left = 9 - counts[n]; + const done = counts[n] >= 9; + p.tally.setText(done ? (counts[n] > 9 ? 'too many!' : 'all placed') : `${left} left`); + p.tally.setColor(counts[n] > 9 ? RED_INK : FADED); + p.txt.setColor(done ? '#9a958c' : GRAPHITE); + const was = this.digitsDone.has(n); + if (done && !was) { + this.digitsDone.add(n); + if (animate) { + const o = { t: 0 }; + this.strikeProgress[n] = 0; + this.tweens.add({ targets: o, t: 1, duration: 260, ease: 'Sine.easeOut', onUpdate: () => { this.strikeProgress[n] = o.t; this.drawPadStrikes(); } }); + playSoundEx(this, SFX.PENCIL_WRITE, { rate: 1.4, volume: 0.5 }); + } else this.strikeProgress[n] = 1; + } else if (!done && was) { + this.digitsDone.delete(n); + this.strikeProgress[n] = 0; } + } + this.drawPadStrikes(); + const g = this.padSel; + g.clear(); + if (this.armed != null) { + const p = this.padCells[this.armed]; + const rx = this.armed === 0 ? 96 : 50, ry = this.armed === 0 ? 50 : 54; + g.lineStyle(3.2, RED_INK_N, 0.88); + g.strokeEllipse(p.x, p.y - (this.armed ? 6 : 0), rx * 2, ry * 2); + g.lineStyle(1.6, RED_INK_N, 0.3); + g.strokeEllipse(p.x + 4, p.y - (this.armed ? 9 : 3), rx * 2 + 8, ry * 2 + 6); + } + } + + drawPadStrikes() { + const g = this.padStrike; + if (!g) return; + g.clear(); + for (let n = 1; n <= 9; n++) { + const t = this.strikeProgress[n] ?? 0; + if (t <= 0) continue; + const { x, y } = this.padCells[n]; + const x0 = x - 34, y0 = y - 2, x1 = x + 34, y1 = y - 18; + g.lineStyle(3.4, GRAPHITE_N, 0.85); + g.lineBetween(x0, y0, x0 + (x1 - x0) * t, y0 + (y1 - y0) * t); + } + } + + refreshButtons() { + this.undoBtn?.setEnabled(!this.gameEnded && canUndo(this.history)); + this.redoBtn?.setEnabled(!this.gameEnded && canRedo(this.history)); + if (this.hintBtn) { + const finite = Number.isFinite(this.hintsLeft); + this.hintBtn.setLabel(finite && this.hintsLeft === 0 && this.hintsUsed === 0 ? 'No hints' + : finite ? `Hint (${this.hintsLeft})` : 'Hint'); + this.hintBtn.setEnabled(!this.gameEnded && this.hintsLeft > 0); + } + this.pauseBtn?.setLabel(this.paused ? 'Resume' : 'Pause').setEnabled(!this.gameEnded); + } + + refreshStats() { + this.statText?.setText(`Mistakes ${this.mistakes} Hints ${this.hintsUsed}`); + this.drawWatch(); + } + + // ── Input ────────────────────────────────────────────────────────────────── + + blocked() { return this.mode !== 'play' || this.gameEnded || this.winPending || this.hintPending || this.paused || !!this.modal; } + + onCellPointer(r, c) { + if (this.blocked()) return; + if (this.givens[r][c]) { + // A printed number picks that digit on the pad (digit-first from here on); + // tapping the same one again lets go of it. + const v = this.grid[r][c]; + if (this.armed === v && this.cursor?.r === r && this.cursor?.c === c) { + this.armed = null; + this.cursor = null; + } else { + this.armed = v; + this.cursor = { r, c }; + } + playSound(this, SFX.PIECE_CLICK); + } else if (this.armed != null) { + this.cursor = { r, c }; + if (this.armed === 0 || this.grid[r][c] === this.armed) this.writeCell(r, c, 0); + else this.writeCell(r, c, this.armed); + } else if (this.cursor?.r === r && this.cursor?.c === c) { + this.cursor = null; + playSound(this, SFX.PIECE_CLICK); + } else { + this.cursor = { r, c }; + playSound(this, SFX.PIECE_CLICK); + } + this.refreshFocus(); + this.refreshPad(); + } + + onPadPointer(n) { + if (this.blocked()) return; + if (this.armed === n) { + this.armed = null; + playSound(this, SFX.PIECE_CLICK); + } else if (this.armed != null) { + this.armed = n; + playSound(this, SFX.PIECE_CLICK); + } else if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) { + this.writeCell(this.cursor.r, this.cursor.c, n); + } else { + this.armed = n; + playSound(this, SFX.PIECE_CLICK); + } + this.refreshPad(); + this.refreshFocus(); + } + + onKey(e) { + const k = e.key; + if (this.modal) { + if (k === 'Escape') this.modal.close?.(); + return; + } + if (this.mode !== 'play' || this.gameEnded) return; + const ctrl = e.ctrlKey || e.metaKey; + const lower = k.length === 1 ? k.toLowerCase() : k; + if (ctrl && lower === 'z') { e.preventDefault?.(); e.shiftKey ? this.doRedo() : this.doUndo(); return; } + if (ctrl && lower === 'y') { e.preventDefault?.(); this.doRedo(); return; } + if (ctrl) return; + if (lower === 'p') { this.setPaused(!this.paused); return; } + if (this.paused) return; + if (k === 'Escape') { + if (this.cursor || this.armed != null) { this.cursor = null; this.armed = null; this.refreshFocus(); this.refreshPad(); } + else this.setPaused(true); + return; + } + if (lower === 'h') { this.useHint(); return; } + const moves = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1], w: [-1, 0], s: [1, 0], a: [0, -1], d: [0, 1] }; + if (moves[lower]) { + e.preventDefault?.(); + if (this.blocked()) return; + if (!this.cursor) this.cursor = this.firstEmpty() ?? { r: 0, c: 0 }; + else { + const [dr, dc] = moves[lower]; + this.cursor = { r: (this.cursor.r + dr + N) % N, c: (this.cursor.c + dc + N) % N }; + } + this.refreshFocus(); + return; + } + if (/^[1-9]$/.test(k)) { + if (this.blocked()) return; + const v = Number(k); + if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) this.writeCell(this.cursor.r, this.cursor.c, v); + else if (!this.cursor) { this.armed = this.armed === v ? null : v; playSound(this, SFX.PIECE_CLICK); this.refreshPad(); } + this.refreshFocus(); + return; + } + if (k === 'Backspace' || k === 'Delete' || k === '0') { + e.preventDefault?.(); + if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) this.writeCell(this.cursor.r, this.cursor.c, 0); + } + } + + firstEmpty() { + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!this.grid[r][c]) return { r, c }; + return null; + } + + // ── Editing ──────────────────────────────────────────────────────────────── + + // A player write (v = 0 erases). Records history, then evaluates. + writeCell(r, c, v) { + if (this.blocked() || this.givens[r][c]) return; + const from = this.grid[r][c]; + if (from === v) return; + pushEdit(this.history, { r, c, from, to: v }); + this.moves++; + this.timerOn = true; + this.applyCell(r, c, v, { anim: true, countMistake: true }); + } + + // Set a cell's value and run the feedback rules. Used by writes, undo/redo and hints. + applyCell(r, c, v, { anim = false, countMistake = false } = {}) { + const from = this.grid[r][c]; + this.grid[r][c] = v; + if (v && !this.givens[r][c]) this.tilt[r][c] = (Math.random() - 0.5) * 8; + this.renderCellText(r, c); + const t = this.cellText[r]?.[c]; + if (anim && t) { + if (v) { + playSoundEx(this, SFX.PENCIL_WRITE, { rate: 0.9 + Math.random() * 0.25, volume: 0.7 }); + const angle = t.angle; + t.setScale(1.3).setAlpha(0).setAngle(angle - 8); + this.tweens.add({ targets: t, scale: 1, alpha: 1, angle, duration: 200, ease: 'Back.easeOut' }); + } else if (from) { + playSoundEx(this, SFX.UI_PICK, { rate: 0.7, volume: 0.6 }); + this.smudge(r, c); + } + } + + if (!v || this.givens[r][c]) { + this.cellState[r][c] = 0; + } else if (this.isChecking()) { + const ok = v === this.solution[r][c]; + this.cellState[r][c] = ok ? 1 : 2; + if (!ok && countMistake) this.mistakes++; } else { - // No per-cell feedback — wait until all cells are filled this.cellState[r][c] = 0; - this.drawCellBg(r, c, hovered); - - if (this.isAllFilled()) { - this.time.delayedCall(200, () => this.revealAll()); - } } + this.drawState(); + this.drawConflicts(); + this.recomputeUnits(anim); + this.refreshPad(anim); + this.refreshFocus(); + this.refreshButtons(); + this.refreshStats(); - this.updateCompletedNums(); + if (isBoardComplete(this.grid, this.solution)) { + if (!this.isChecking()) this.revealAll(true); + this.winPending = true; // locks input until the ceremony + this.time.delayedCall(360, () => this.handleWin()); + } else if (!this.isChecking() && this.allFilled()) { + this.time.delayedCall(220, () => { if (!this.revealed && this.allFilled()) this.revealAll(false); }); + } + this.saveGame(); } - isEasyMode() { - return this.difficulty === 'very-easy' || this.difficulty === 'easy'; - } - - isAllFilled() { - for (let r = 0; r < 9; r++) - for (let c = 0; c < 9; c++) - if (!this.givenCells[r][c] && this.grid[r][c] === 0) return false; + allFilled() { + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!this.grid[r][c]) return false; return true; } - revealAll() { + // Regular and up: the grid is full, so check it. From here on entries are + // checked immediately. + revealAll(silent) { + if (this.gameEnded) return; this.revealed = true; - let allCorrect = true; - - for (let r = 0; r < 9; r++) { - for (let c = 0; c < 9; c++) { - if (this.givenCells[r][c]) continue; - const correct = this.grid[r][c] === this.solution[r][c]; - if (!correct) allCorrect = false; - this.cellState[r][c] = correct ? 1 : 2; - this.drawCellBg(r, c, false); + let wrong = 0; + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) { + if (this.givens[r][c]) continue; + const ok = this.grid[r][c] === this.solution[r][c]; + this.cellState[r][c] = ok ? 1 : 2; + if (!ok) wrong++; } + this.mistakes += wrong; + this.drawState(); + this.recomputeUnits(!silent); + this.refreshStats(); + this.ruleText?.setText(this.ruleLine()); + if (wrong && !silent) { + playSoundEx(this, SFX.CLICK, { rate: 0.5 }); + this.toast(`${wrong} square${wrong > 1 ? "s don't" : " doesn't"} fit. They're hatched in red.`, 3200); } + this.saveGame(); + } - this.updateCompletedNums(); + smudge(r, c) { + const x = cellCX(c), y = cellCY(r) + 2; + // a faint graphite ghost stays behind… + this.smudgeGfx?.fillStyle(0x6a6d72, 0.05); + this.smudgeGfx?.fillEllipse(x + (Math.random() - 0.5) * 6, y, 42, 24); + // …and the rubbing itself fades out + const g = this.add.graphics().setDepth(D.hover); + g.fillStyle(0x8a8f96, 0.28); + g.fillEllipse(0, 0, 46, 26); + g.fillStyle(0x8a8f96, 0.16); + g.fillEllipse(8, 4, 40, 18); + g.setPosition(x, y).setAngle(-12); + this.tweens.add({ targets: g, alpha: 0, scaleX: 1.5, duration: 520, ease: 'Sine.easeOut', onComplete: () => g.destroy() }); + } - if (allCorrect) { - this.time.delayedCall(300, () => this.handleWin()); + // Rows, columns and boxes holding 1–9 (and, once checking, correct) get a + // short shimmer when they're finished. + recomputeUnits(flourish) { + const now = completedUnits(this.grid, this.isChecking() ? this.solution : null); + const keys = new Set(now.map(u => u.key)); + const fresh = now.filter(u => !this.unitsDone.has(u.key)); + this.unitsDone = keys; + if (flourish && fresh.length && !isBoardComplete(this.grid, this.solution)) { + fresh.forEach((u, i) => this.unitFlourish(u, i)); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.5, rate: 0.95 + Math.min(fresh.length, 3) * 0.05 }); } } - clearCell(r, c) { - if (this.givenCells[r][c]) return; - this.grid[r][c] = 0; - this.cellTextObjs[r][c].setText(''); - this.cellState[r][c] = 0; - const hovered = this.hoveredCell?.r === r && this.hoveredCell?.c === c; - this.drawCellBg(r, c, hovered); - this.updateCompletedNums(); + unitFlourish(u, i = 0) { + const { x, y, w, h } = unitRect(u); + const g = this.add.graphics().setDepth(D.hl); + const band = { t: 0 }; + const horizontal = u.type !== 'col'; + this.tweens.add({ + targets: band, t: 1, duration: 520, delay: i * 90, ease: 'Sine.easeInOut', + onUpdate: () => { + g.clear(); + const a = Math.sin(band.t * Math.PI); + g.fillStyle(0xfff1b0, 0.32 * a); + g.fillRect(x, y, w, h); + // a bright gleam sweeping along the unit + g.fillStyle(0xffffff, 0.45 * a); + if (horizontal) g.fillRect(x + band.t * w - 30, y, 60, h); + else g.fillRect(x, y + band.t * h - 30, w, 60); + }, + onComplete: () => g.destroy(), + }); + unitCells(u.type, u.index).forEach(({ r, c }, k) => { + const t = this.cellText[r]?.[c]; + if (t) this.tweens.add({ targets: t, scale: 1.16, duration: 120, yoyo: true, delay: i * 90 + k * 30 }); + }); } - drawCellBg(r, c, isHovered) { - const bg = this.cellBgObjs[r][c]; - if (!bg) return; - bg.clear(); - - const x = GRID_X + c * CELL + 1; - const y = GRID_Y + r * CELL + 1; - const sz = CELL - 2; - - const state = this.cellState[r][c]; - - if (state === 1) { - bg.fillStyle(0x3c8a4e, isHovered ? 0.28 : 0.18); - bg.fillRect(x, y, sz, sz); - } else if (state === 2) { - bg.fillStyle(0xb03a2e, isHovered ? 0.25 : 0.14); - bg.fillRect(x, y, sz, sz); - } else if (isHovered) { - bg.fillStyle(INK_N, 0.07); - bg.fillRect(x, y, sz, sz); - } + doUndo() { + if (this.blocked()) return; + const e = undoEdit(this.history); + if (!e) return; + this.moves++; + this.cursor = { r: e.r, c: e.c }; + this.applyCell(e.r, e.c, e.from, { anim: true }); } - // ── Hint ────────────────────────────────────────────────────────────────────── + doRedo() { + if (this.blocked()) return; + const e = redoEdit(this.history); + if (!e) return; + this.moves++; + this.cursor = { r: e.r, c: e.c }; + this.applyCell(e.r, e.c, e.to, { anim: true }); + } + + // ── Hints ────────────────────────────────────────────────────────────────── useHint() { - if (this.gameEnded) return; - if (isFinite(this.hintsLeft) && this.hintsLeft <= 0) return; - - const cell = getHintCell(this.grid, this.solution); + if (this.blocked() || this.hintsLeft <= 0 || this.hintPending) return; + const cell = getHintCell(this.grid, this.solution, this.givens); if (!cell) return; - const { r, c } = cell; + this.hintPending = true; + this.timerOn = true; + if (Number.isFinite(this.hintsLeft)) this.hintsLeft--; + this.hintsUsed++; + this.moves++; + playSound(this, SFX.UI_ACTIVATE); - // Temporarily show gold flash - const bg = this.cellBgObjs[r][c]; - bg.clear(); - bg.fillStyle(0xd4a017, 0.5); - bg.fillRect(GRID_X + c * CELL + 1, GRID_Y + r * CELL + 1, CELL - 2, CELL - 2); + const glow = this.add.graphics().setDepth(D.cursor); + glow.fillStyle(HIGHLIGHT_N, 0.6); + glow.fillRect(GRID_X + c * CELL + 4, GRID_Y + r * CELL + 4, CELL - 8, CELL - 8); + this.tweens.add({ targets: glow, alpha: 0.25, duration: 220, yoyo: true, repeat: 1 }); + if (cell.fix) this.toast('That entry was wrong. The hint corrected it.', 2400); - this.time.delayedCall(550, () => { - this.grid[r][c] = this.solution[r][c]; - this.cellTextObjs[r][c].setText(String(this.solution[r][c])); - this.cellState[r][c] = 1; - this.drawCellBg(r, c, false); - this.updateCompletedNums(); - - if (isBoardComplete(this.grid, this.solution)) { - this.time.delayedCall(200, () => this.handleWin()); - } + this.time.delayedCall(520, () => { + glow.destroy(); + this.hintPending = false; + if (this.gameEnded || !this.sys.isActive()) return; + this.givens[r][c] = true; + this.hinted.add(`${r},${c}`); + pushMarker(this.history); + this.cursor = { r, c }; + this.applyCell(r, c, this.solution[r][c], { anim: true }); }); + this.refreshButtons(); + this.refreshStats(); + } - if (isFinite(this.hintsLeft)) { - this.hintsLeft--; - this.hintsUsed++; - this.updateHintBtn(); + // ── Timer + pause ────────────────────────────────────────────────────────── + + update(_t, delta) { + if (this.mode !== 'play') { + if (this.mode === 'start' && Math.floor(Date.now() / 1000) !== this._lastSecond) { + this._lastSecond = Math.floor(Date.now() / 1000); + this.drawWatch(); + } + return; + } + if (!this.timerOn || this.paused || this.gameEnded || this.modal) return; + if (typeof document !== 'undefined' && document.hidden) return; + this.elapsed += delta; + const sec = Math.floor(this.elapsed / 1000); + if (sec !== this._lastSecond) { + this._lastSecond = sec; + this.drawWatch(); } } - // ── Win ─────────────────────────────────────────────────────────────────────── + setPaused(on) { + if (this.mode !== 'play' || this.gameEnded || this.paused === on) return; + this.paused = on; + playSound(this, SFX.UI_FLIP); + if (on) { + // the top half of the page folds down over the puzzle + const cont = this.add.container(0, FLAP.y).setDepth(D.flap); + const img = this.add.image(FLAP.x - 6, -4, 'sudoku-flap').setOrigin(0); + const cx = FLAP.x + FLAP.w / 2; + const t1 = this.add.text(cx, FLAP.h / 2 - 50, 'INTERMISSION', { + fontFamily: SERIF, fontSize: '58px', color: INK, fontStyle: 'bold', + }).setOrigin(0.5); + const t2 = this.add.text(cx, FLAP.h / 2 + 12, 'Back after the break', { + fontFamily: SERIF, fontSize: '30px', color: INK, fontStyle: 'italic', + }).setOrigin(0.5); + const t3 = this.add.text(cx, FLAP.h / 2 + 62, 'Tap the page or press P to carry on. The watch is stopped.', { + fontFamily: SERIF, fontSize: '19px', color: FADED, + }).setOrigin(0.5); + cont.add([img, t1, t2, t3]); + const zone = this.add.zone(cx, FLAP.y + FLAP.h / 2, FLAP.w, FLAP.h).setDepth(D.flap + 1).setInteractive({ useHandCursor: true }); + zone.on('pointerup', () => this.setPaused(false)); + cont.scaleY = 0.02; + this.tweens.add({ targets: cont, scaleY: 1, duration: 320, ease: 'Cubic.easeOut' }); + this.flap = { cont, zone }; + this.drawHover(); + this.refreshFocus(); + this.saveGame(); + } else if (this.flap) { + const { cont, zone } = this.flap; + this.flap = null; + zone.destroy(); + this.tweens.add({ targets: cont, scaleY: 0.02, duration: 240, ease: 'Cubic.easeIn', onComplete: () => cont.destroy() }); + this.refreshFocus(); + } + this.refreshButtons(); + } + + // ── New puzzle / save ────────────────────────────────────────────────────── + + newPuzzle() { + if (this.modal) return; + const go = () => this.daily ? this.restartWith({ start: true }) : this.restartWith({ difficulty: this.difficulty }); + if (this.mode === 'play' && !this.gameEnded && this.moves > 0) { + this.confirm('Abandon this puzzle?', 'Your pencil marks on this grid will be lost.', 'Abandon it', () => { + recordGame('sudoku', { won: false, time: Math.round(this.elapsed), moves: this.moves, mode: this.statsMode() }); + storage()?.removeItem(SAVE_KEY); + this.moves = 0; // nothing left to save on shutdown + go(); + }); + return; + } + if (!this.gameEnded) storage()?.removeItem(SAVE_KEY); + go(); + } + + statsMode() { return this.daily ? 'daily' : this.difficulty; } + + saveGame() { + if (this.mode !== 'play' || this.gameEnded || this.moves <= 0 || !this.grid) return; + try { + storage()?.setItem(SAVE_KEY, serialiseSave({ + difficulty: this.difficulty, daily: this.daily, + grid: this.grid, solution: this.solution, givens: this.givens, + cellState: this.cellState, history: this.history, elapsed: this.elapsed, + hintsLeft: this.hintsLeft, hintsUsed: this.hintsUsed, mistakes: this.mistakes, + revealed: this.revealed, moves: this.moves, puzzleNo: this.puzzleNo, tier: this.tier, + hinted: [...this.hinted], + })); + } catch { /* storage full or unavailable */ } + } + + // ── Win ──────────────────────────────────────────────────────────────────── handleWin() { if (this.gameEnded) return; this.gameEnded = true; - this.recordResult(); - this.showWin(); - } + this.timerOn = false; + this.cursor = null; this.armed = null; + this.refreshFocus(); this.drawHover(); this.drawConflicts(); this.refreshPad(); this.refreshButtons(); + storage()?.removeItem(SAVE_KEY); - showWin() { - const cx = CX, cy = CY; - - this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.42) - .setDepth(DEPTH.overlay); - - const panel = this.add.graphics().setDepth(DEPTH.overlay + 1); - panel.postFX.addShadow(0, 6, 0.02, 1.2, 0x000000, 10, 0.55); - panel.fillStyle(PAPER, 1); - panel.fillRoundedRect(cx - 460, cy - 230, 920, 460, 18); - panel.lineStyle(3, PAPER_EDGE, 1); - panel.strokeRoundedRect(cx - 460, cy - 230, 920, 460, 18); - - this.add.text(cx, cy - 130, 'Puzzle Solved!', { - fontFamily: 'YummyCupcakes', fontSize: '88px', color: '#3c8a4e', - }).setOrigin(0.5).setDepth(DEPTH.overlay + 2); - - const diffLabel = DIFF_LABELS[this.difficulty] ?? this.difficulty; - const score = this.calcScore(); - - this.add.text(cx, cy - 26, `${diffLabel} · ${score} pts`, { - fontFamily: 'YummyCupcakes', fontSize: '44px', color: TITLE_BROWN, - }).setOrigin(0.5).setDepth(DEPTH.overlay + 2); - - if (this.hintsUsed > 0) { - this.add.text(cx, cy + 28, `${this.hintsUsed} hint${this.hintsUsed > 1 ? 's' : ''} used`, { - fontFamily: 'YummyCupcakes', fontSize: '32px', color: FADED, - }).setOrigin(0.5).setDepth(DEPTH.overlay + 2); + const time = Math.round(this.elapsed); + const { stats, newBest } = recordGame('sudoku', { + won: true, time, moves: this.moves, mode: this.statsMode(), + extra: { hints: this.hintsUsed, mistakes: this.mistakes }, + }); + let daily = null; + if (this.daily) { + const res = updateDaily(readJSON(DAILY_KEY), this.daily, todayString(), time); + writeJSON(DAILY_KEY, res.rec); + daily = res; } + const score = calcScore(this.difficulty, this.hintsUsed); + api.post('/history/single-player', { slug: 'sudoku', score, opponentScores: [], result: 'win' }).catch(() => {}); - new Button(this, cx - 175, cy + 130, 'New puzzle', - () => this.scene.restart(this._initData), - { width: 280, height: 58, fontSize: 26 }).setDepth(DEPTH.overlay + 3); - - new Button(this, cx + 175, cy + 130, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 280, height: 58, fontSize: 26 }).setDepth(DEPTH.overlay + 3); + this.winCeremony(); + this.time.delayedCall(1900, () => this.showClipping({ time, score, stats, newBest, daily })); } - calcScore() { - const base = DIFFICULTY_SCORES[this.difficulty] ?? 10; - const hintPenalty = this.difficulty === 'regular' ? this.hintsUsed * 4 : 0; - return Math.max(0, base - hintPenalty); - } - - async recordResult() { - try { - await api.post('/history/single-player', { - slug: 'sudoku', score: this.calcScore(), opponentScores: [], result: 'win', + // Digits pop in a diagonal wave, then the SOLVED stamp lands on the grid. + winCeremony() { + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) { + const t = this.cellText[r]?.[c]; + if (t) this.tweens.add({ targets: t, scale: 1.25, duration: 140, yoyo: true, delay: (r + c) * 38 }); + } + playSoundEx(this, SFX.UI_CHIME, { volume: 0.6, rate: 1.1 }); + this.time.delayedCall(800, () => { + if (!this.sys.isActive()) return; + const stamp = this.add.container(GRID_X + GRID_W / 2, GRID_Y + GRID_W / 2).setDepth(D.flap - 1); + const sg = this.add.graphics(); + sg.lineStyle(7, RED_INK_N, 0.82); sg.strokeRoundedRect(-230, -70, 460, 140, 14); + sg.lineStyle(2.5, RED_INK_N, 0.6); sg.strokeRoundedRect(-216, -56, 432, 112, 10); + const st = this.add.text(0, 2, 'SOLVED', { fontFamily: 'Righteous', fontSize: '92px', color: RED_INK }).setOrigin(0.5).setAlpha(0.88); + stamp.add([sg, st]); + stamp.setAngle(-12).setScale(2.6).setAlpha(0); + this.tweens.add({ + targets: stamp, scale: 1, alpha: 0.86, duration: 220, ease: 'Quad.easeIn', + onComplete: () => { playSound(this, SFX.KART_THUMP); this.cameras.main.shake(130, 0.004); }, }); - } catch { /* best effort */ } + }); + } + + showClipping({ time, score, stats, newBest, daily }) { + if (!this.sys.isActive()) return; + playSound(this, SFX.VICTORY_SHORT); + const dim = this.add.rectangle(W / 2, H / 2, W, H, 0x1a120a, 0.45).setDepth(D.win).setInteractive(); + dim.alpha = 0; + this.tweens.add({ targets: dim, alpha: 1, duration: 300 }); + + const cy = H / 2 - 50; + const cont = this.add.container(W / 2, cy).setDepth(D.win + 1); + const clip = this.add.image(0, 0, 'sudoku-clipping'); + const top = -clip.height / 2 + 40; // the clipping's top edge inside the texture + const txt = (x, y, s, size, color = INK, style = '') => + this.add.text(x, y, s, { fontFamily: SERIF, fontSize: `${size}px`, color, fontStyle: style, align: 'center' }).setOrigin(0.5); + const edition = this.daily ? `Today's Edition (${this.daily}) · ${DIFF_LABELS[this.difficulty]}` : this.editionLabel(); + const kids = [ + clip, + txt(0, top + 130, 'Puzzle Solved!', 72, INK, 'bold'), + txt(0, top + 200, `${edition} · Puzzle No. ${this.puzzleNo}`, 24, INK, 'italic'), + ]; + [['TIME', formatTime(time)], ['MISTAKES', String(this.mistakes)], ['HINTS', String(this.hintsUsed)], ['SCORE', `${score} pts`]] + .forEach(([label, value], i) => { + const x = -300 + i * 200; + kids.push(txt(x, top + 272, label, 16, FADED, 'bold')); + kids.push(txt(x, top + 320, value, 44, INK, 'bold')); + }); + let note; + if (daily) note = `Day streak: ${daily.streak} day${daily.streak === 1 ? '' : 's'}${daily.newBestTime ? ' · a new best for today!' : ''}`; + else if (newBest.time) note = `A new best time for ${EDITION[this.difficulty].day}'s puzzle!`; + else if (stats.won === 1) note = `Your first ${EDITION[this.difficulty].day} puzzle solved.`; + else note = `Best ${formatTime(stats.bestTime)} · Streak ${stats.streak}${newBest.streak ? ' (a new record!)' : ''}`; + kids.push(txt(0, top + 420, note, 28, newBest.time || daily?.newBestTime ? RED_INK : INK, 'italic')); + cont.add(kids); + cont.y = H + 420; cont.angle = 5; + this.tweens.add({ targets: cont, y: cy, angle: -1.2, duration: 560, ease: 'Back.easeOut' }); + + const by = cy + CLIP_H / 2 + 50; + this.time.delayedCall(600, () => { + if (!this.sys.isActive()) return; + const again = this.daily + ? new NewsButton(this, W / 2 - 150, by, "Back to the paper", () => this.restartWith({ start: true }), { width: 260, height: 58, accent: true }) + : new NewsButton(this, W / 2 - 150, by, 'Another puzzle', () => this.restartWith({ difficulty: this.difficulty }), { width: 260, height: 58, accent: true }); + const lv = new NewsButton(this, W / 2 + 150, by, 'Leave', () => this.scene.start('GameMenu'), { width: 260, height: 58 }); + again.setDepth(D.win + 2); lv.setDepth(D.win + 2); + }); + } + + // ── Modals + toast ───────────────────────────────────────────────────────── + + openModal(build) { + if (this.modal) return null; + const objs = []; + const dim = this.add.rectangle(W / 2, H / 2, W, H, 0x1a120a, 0.55).setDepth(D.modal).setInteractive(); + objs.push(dim); + const modal = { objs, close: () => { + for (const o of objs) o.destroy(); + if (this.modal === modal) this.modal = null; + } }; + this.modal = modal; + build(objs, modal); + return modal; + } + + newsPanel(x, y, w, h) { + const g = this.add.graphics().setDepth(D.modal + 1); + g.fillStyle(0x000000, 0.25); g.fillRect(x + 8, y + 10, w, h); + g.fillStyle(0xf1ebdc, 1); g.fillRect(x, y, w, h); + g.lineStyle(2.5, INK_N, 0.85); g.strokeRect(x + 14, y + 14, w - 28, h - 28); + g.lineStyle(1, INK_N, 0.5); g.strokeRect(x + 20, y + 20, w - 40, h - 40); + return g; + } + + confirm(title, body, yesLabel, onYes) { + this.openModal((objs, modal) => { + const x = W / 2 - 380, y = H / 2 - 170; + objs.push(this.newsPanel(x, y, 760, 340)); + objs.push(this.add.text(W / 2, y + 82, title, { + fontFamily: SERIF, fontSize: '44px', color: INK, fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.modal + 2)); + objs.push(this.add.text(W / 2, y + 152, body, { + fontFamily: SERIF, fontSize: '24px', color: INK, fontStyle: 'italic', align: 'center', wordWrap: { width: 640 }, + }).setOrigin(0.5).setDepth(D.modal + 2)); + objs.push(new NewsButton(this, W / 2 - 150, y + 256, yesLabel, () => { modal.close(); onYes(); }, { width: 250, accent: true }).setDepth(D.modal + 2)); + objs.push(new NewsButton(this, W / 2 + 150, y + 256, 'Keep going', () => modal.close(), { width: 250 }).setDepth(D.modal + 2)); + }); + } + + openGuide() { + if (this.modal) return; + playSound(this, SFX.UI_FLIP); + this.openModal((objs, modal) => { + const add = (o) => { objs.push(o.setDepth?.(D.modal + 2) ?? o); return o; }; + const x = W / 2 - 580, y = H / 2 - 380, w = 1160, h = 760; + objs.push(this.newsPanel(x, y, w, h)); + add(this.add.text(W / 2, y + 74, 'How to Play Sudoku', { fontFamily: SERIF, fontSize: '54px', color: INK, fontStyle: 'bold' }).setOrigin(0.5)); + const rg = add(this.add.graphics()); + rg.lineStyle(1.2, INK_N, 0.7); rg.lineBetween(x + 60, y + 116, x + w - 60, y + 116); + + // three small figures: a row, a column, a box + const cell = 24, size = cell * 9; + const figs = [ + { label: 'fig. 1 Every row', shade: (r) => r === 4 }, + { label: 'fig. 2 Every column', shade: (r, c) => c === 4 }, + { label: 'fig. 3 Every 3×3 box', shade: (r, c) => boxOf(r, c) === 4 }, + ]; + const ig = add(this.add.graphics()); + figs.forEach((f, k) => { + const fx = x + 110 + k * 340, fy = y + 156; + ig.fillStyle(HIGHLIGHT_N, 0.55); + for (let r = 0; r < 9; r++) for (let c = 0; c < 9; c++) if (f.shade(r, c)) ig.fillRect(fx + c * cell, fy + r * cell, cell, cell); + for (let i = 0; i <= 9; i++) { + ig.lineStyle(i % 3 ? 0.8 : 2.2, INK_N, i % 3 ? 0.45 : 0.9); + ig.lineBetween(fx + i * cell, fy, fx + i * cell, fy + size); + ig.lineBetween(fx, fy + i * cell, fx + size, fy + i * cell); + } + add(this.add.text(fx + size / 2, fy + size + 26, `${f.label}\nholds 1 to 9 exactly once.`, { + fontFamily: SERIF, fontSize: '20px', color: INK, fontStyle: 'italic', align: 'center', lineSpacing: 3, + }).setOrigin(0.5, 0)); + }); + + add(this.add.text(W / 2, y + 520, + 'Tap a square, then a number on the guest check (or type 1–9). You can also pick a number first and tap squares.\n' + + 'Arrows move · Backspace erases · Ctrl+Z / Ctrl+Y undo and redo · H hint · P pause\n' + + "Monday and Tuesday check entries as you write and circle clashes in red. Later editions check the grid once it's full.\n" + + 'Your puzzle saves itself. Leave any time and resume it from the front page.', { + fontFamily: SERIF, fontSize: '19px', color: INK, align: 'center', lineSpacing: 10, wordWrap: { width: w - 120 }, + }).setOrigin(0.5)); + const closeModal = modal.close; + modal.close = () => { storage()?.setItem(GUIDE_SEEN_KEY, '1'); closeModal(); }; + add(new NewsButton(this, W / 2, y + h - 74, 'Got it', () => modal.close(), { width: 230, accent: true })); + }); + } + + toast(text, ms = 2600) { + if (this.toastObj) { this.tweens.killTweensOf(this.toastObj); this.toastObj.destroy(); } + const cont = this.add.container(RCX, PAD.y + 40).setDepth(D.toast); + const t = this.add.text(0, 0, text, { + fontFamily: 'YummyCupcakes', fontSize: '28px', color: '#3d3420', align: 'center', wordWrap: { width: 440 }, + }).setOrigin(0.5); + const w = Math.max(340, t.width + 60), h = t.height + 46; + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.2); g.fillRect(-w / 2 + 5, -h / 2 + 6, w, h); + g.fillStyle(0xf7e58a, 1); g.fillRect(-w / 2, -h / 2, w, h); + g.fillStyle(0xe9d16a, 1); g.fillRect(-w / 2, -h / 2, w, 14); + cont.add([g, t]); + cont.setAngle(-1.5).setAlpha(0).setScale(0.9); + this.toastObj = cont; + this.tweens.add({ targets: cont, alpha: 1, scale: 1, duration: 180, ease: 'Back.easeOut' }); + this.tweens.add({ + targets: cont, alpha: 0, delay: ms, duration: 400, + onComplete: () => { if (this.toastObj === cont) this.toastObj = null; cont.destroy(); }, + }); } } diff --git a/src/games/sudoku/SudokuLogic.js b/src/games/sudoku/SudokuLogic.js index 4806ce4..8ba0ef3 100644 --- a/src/games/sudoku/SudokuLogic.js +++ b/src/games/sudoku/SudokuLogic.js @@ -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}`; } diff --git a/src/words/sudokuEngine.js b/src/words/sudokuEngine.js index 7932360..4147376 100644 --- a/src/words/sudokuEngine.js +++ b/src/words/sudokuEngine.js @@ -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; + } } diff --git a/src/words/wordRouter.js b/src/words/wordRouter.js index 0525970..0d02c69 100644 --- a/src/words/wordRouter.js +++ b/src/words/wordRouter.js @@ -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] diff --git a/tools/verifySudoku.js b/tools/verifySudoku.js new file mode 100644 index 0000000..a6bb80d --- /dev/null +++ b/tools/verifySudoku.js @@ -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);