fertig-classic-games/tools/verifyWordSearch.js

568 lines
35 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

#!/usr/bin/env node
// verifyWordSearch.js — headless checks for the Rail Edition Word Search: the
// chapter data, the generator (every word exactly once by an independent
// scanner, allowed directions only, no word inside another, the leftover
// letters spell the secret message, seeded determinism, speed), the selection
// machine (drag and click-click), hints, save/resume validation, daily streaks,
// the book layout, art bakes against a strict fake 2D context, and a
// stubbed-Phaser play-through of the scene.
// Usage: node tools/verifyWordSearch.js [--quick]
import { generatePuzzle, DIFFICULTY, DIFFICULTIES, listThemes } from '../src/words/wordSearchEngine.js';
import { THEMES, CHAPTER_ORDER, JOURNEY_MESSAGES, messageLetters } from '../src/words/wordSearchThemes.js';
import {
DIFFS, TICKET as CLASS, HINT_LIMITS, calcScore, snapSelection, lettersAt, matchWord, idleSelection, selectionStep,
wordCells, leftoverCells, messageWords, pickHint, serialiseSave, parseSave,
dailySeed, prevDate, updateDaily, dailyStreakNow, blankDaily, shortDate,
} from '../src/games/wordsearch/WordSearchLogic.js';
import {
W, H, BOOK, LEFT_PAGE, RIGHT_PAGE, GRID_BOX, MSG_BOX, LIST_BOX, FOOT_Y, WINDOW, CUP, TICKET, FACT, BTN, SMALL_BTN,
CARD, SUMMARY, DOODLE, RIGHT_CX,
} from '../src/games/wordsearch/WordSearchArt.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 rev = (w) => [...w].reverse().join('');
const DIR8 = [[0, 1], [1, 0], [1, 1], [-1, 1], [0, -1], [-1, 0], [1, -1], [-1, -1]];
// Independent scanner: distinct cell-runs (either direction) spelling `word`.
function occurrences(rows, word) {
const n = rows.length, L = word.length, found = new Set();
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) for (const [dr, dc] of DIR8) {
let s = '';
for (let i = 0; i < L; i++) {
const rr = r + dr * i, cc = c + dc * i;
if (rr < 0 || cc < 0 || rr >= n || cc >= n) { s = null; break; }
s += rows[rr][cc];
}
if (s === word) {
const a = `${r},${c}`, b = `${r + dr * (L - 1)},${c + dc * (L - 1)}`;
found.add([a, b].sort().join('|'));
}
}
return found.size;
}
// ── Chapter data ──────────────────────────────────────────────────────────────
section('Chapter data');
{
ok('15 chapters in order', CHAPTER_ORDER.length === 15 && CHAPTER_ORDER.every(id => THEMES[id]));
ok('listThemes matches the chapter order', listThemes().map(t => t.id).join() === CHAPTER_ORDER.join());
const allMsgs = new Set();
for (const id of CHAPTER_ORDER) {
const t = THEMES[id];
const words = Object.keys(t.words);
ok(`${id}: label + ink`, typeof t.label === 'string' && /^#[0-9a-f]{6}$/i.test(t.ink));
ok(`${id}: at least 40 words`, words.length >= 40, String(words.length));
ok(`${id}: words are A–Z, 3–12 letters`, words.every(w => /^[A-Z]{3,12}$/.test(w)), words.filter(w => !/^[A-Z]{3,12}$/.test(w)).join());
ok(`${id}: every word has a fact`, words.every(w => typeof t.words[w] === 'string' && t.words[w].length > 15 && t.words[w].length < 120),
words.filter(w => !(t.words[w]?.length > 15 && t.words[w].length < 120)).join());
const clashes = [];
for (const a of words) for (const b of words) if (a !== b && (b.includes(a) || b.includes(rev(a)))) clashes.push(`${a}<${b}`);
ok(`${id}: no word hides inside another`, clashes.length === 0, clashes.join());
ok(`${id}: 6+ messages`, t.messages.length >= 6);
ok(`${id}: messages are A–Z words`, t.messages.every(m => /^[A-Z]+( [A-Z]+)*$/.test(m)), t.messages.filter(m => !/^[A-Z]+( [A-Z]+)*$/.test(m)).join(' | '));
const lens = t.messages.map(m => messageLetters(m).length);
ok(`${id}: messages span short to long`, Math.min(...lens) <= 20 && Math.max(...lens) >= 60, lens.join());
for (const m of t.messages) allMsgs.add(m);
}
ok('journey messages are A–Z words', JOURNEY_MESSAGES.every(m => /^[A-Z]+( [A-Z]+)*$/.test(m)));
ok('no duplicate messages', allMsgs.size === CHAPTER_ORDER.reduce((n, id) => n + THEMES[id].messages.length, 0));
}
// ── Generator ────────────────────────────────────────────────────────────────
section('Generator');
const samples = [];
{
const seedsPer = QUICK ? 3 : 10;
const times = {};
for (const d of DIFFICULTIES) {
times[d] = [];
const cfg = DIFFICULTY[d];
const dirKeys = new Set(cfg.dirs.map(x => x.join()));
for (const theme of CHAPTER_ORDER) {
for (let k = 0; k < seedsPer; k++) {
const seed = 1000 + k * 7717 + theme.length * 31;
const t0 = performance.now();
let p;
try { p = generatePuzzle({ difficulty: d, theme, seed }); } catch (err) { ok(`${d}/${theme}/${seed} generates`, false, err.message); continue; }
times[d].push(performance.now() - t0);
samples.push(p);
const tag = `${d}/${theme}/${seed}`;
const errs = [];
if (p.difficulty !== d || p.theme !== theme || p.size !== cfg.size) errs.push('header');
if (p.grid.length !== cfg.size || !p.grid.every(r => r.length === cfg.size && /^[A-Z]+$/.test(r))) errs.push('grid shape');
if (p.words.length < cfg.words[0] || p.words.length > cfg.words[1]) errs.push(`word count ${p.words.length}`);
if ([...p.words].sort().join() !== p.words.join()) errs.push('list not alphabetical');
if (new Set(p.words).size !== p.words.length) errs.push('duplicate words');
if (!p.words.every(w => THEMES[theme].words[w] && p.facts[w] === THEMES[theme].words[w])) errs.push('facts');
for (const pl of p.placements) {
if (!dirKeys.has(pl.dir.join())) errs.push(`dir ${pl.dir} for ${pl.word}`);
if (wordCells(pl).map(([r, c]) => p.grid[r]?.[c]).join('') !== pl.word) errs.push(`placement ${pl.word}`);
if (pl.word.length > Math.min(cfg.size, cfg.maxLen)) errs.push(`too long ${pl.word}`);
}
// the 8-direction scan already reads both ways round
for (const w of p.words) { const n = occurrences(p.grid, w); if (n !== 1) errs.push(`${w}×${n}`); }
for (const a of p.words) for (const b of p.words) if (a !== b && (b.includes(a) || b.includes(rev(a)))) errs.push(`${a} in ${b}`);
const left = leftoverCells(p.size, p.placements);
const msgLen = p.messageLetters.length;
if (left.map(([r, c]) => p.grid[r][c]).join('') !== p.messageLetters) errs.push('leftovers ≠ message');
if (messageLetters(p.message) !== p.messageLetters) errs.push('messageLetters');
if (msgLen < cfg.band[0] || msgLen > cfg.band[1]) errs.push(`message length ${msgLen}`);
if (!THEMES[theme].messages.includes(p.message) && !JOURNEY_MESSAGES.includes(p.message)) errs.push('message source');
ok(tag, errs.length === 0, errs.slice(0, 5).join('; '));
}
}
}
for (const d of DIFFICULTIES) {
const t = [...times[d]].sort((a, b) => a - b);
const p95 = t[Math.floor(t.length * 0.95)] ?? 0;
ok(`${d}: p95 generation under 150 ms`, p95 < 150, `${p95.toFixed(1)} ms`);
console.log(` ${d}: p50 ${t[t.length >> 1]?.toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${t.at(-1)?.toFixed(1)} ms`);
}
const chapterMsgShare = samples.filter(p => THEMES[p.theme].messages.includes(p.message)).length / samples.length;
ok('most messages come from the chapter', chapterMsgShare > 0.75, chapterMsgShare.toFixed(2));
console.log(` chapter messages: ${(chapterMsgShare * 100).toFixed(0)}%`);
}
section('Seeded generation');
{
const a = generatePuzzle({ difficulty: 'hard', theme: 'ocean', seed: 42 });
const b = generatePuzzle({ difficulty: 'hard', theme: 'ocean', seed: 42 });
ok('same seed → same puzzle', JSON.stringify(a) === JSON.stringify(b));
const c = generatePuzzle({ difficulty: 'hard', theme: 'ocean', seed: 43 });
ok('different seed → different puzzle', a.grid.join() !== c.grid.join());
const d1 = generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed('2026-11-26') });
const d2 = generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed('2026-11-26') });
ok('daily: random chapter is seeded too', d1.theme === d2.theme && d1.grid.join() === d2.grid.join());
const chapters = new Set();
for (let k = 0; k < 40; k++) chapters.add(generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed(`2026-12-${k}`) }).theme);
ok('daily chapters vary from day to day', chapters.size >= 8, String(chapters.size));
ok('seed is reported', a.seed === 42);
const u = generatePuzzle({ difficulty: 'expert', theme: 'baking' });
ok('unseeded expert works', u.size === 16 && u.seed === null);
ok('unknown difficulty falls back to medium', generatePuzzle({ difficulty: 'nope', theme: 'space', seed: 1 }).difficulty === 'medium');
ok('unknown theme falls back to a chapter', CHAPTER_ORDER.includes(generatePuzzle({ difficulty: 'easy', theme: 'zzz', seed: 1 }).theme));
ok('Math.random untouched after seeded calls', typeof Math.random() === 'number');
}
// ── Selection ─────────────────────────────────────────────────────────────────
section('Selection');
{
ok('snap: same cell', snapSelection(10, 3, 3, 3, 3).cells.length === 1);
ok('snap: across', snapSelection(10, 2, 1, 2, 6).cells.map(c => c.join()).join(' ') === '2,1 2,2 2,3 2,4 2,5 2,6');
ok('snap: diagonal', snapSelection(10, 0, 0, 3, 3).cells.length === 4 && snapSelection(10, 0, 0, 3, 3).dir.join() === '1,1');
ok('snap: near-diagonal snaps to diagonal', snapSelection(10, 0, 0, 4, 3).dir.join() === '1,1');
ok('snap: backwards', snapSelection(10, 5, 5, 5, 1).dir.join() === '0,-1');
let inBounds = true;
for (let size = 6; size <= 16; size += 5)
for (let br = 0; br < size; br++) for (let bc = 0; bc < size; bc++)
for (const [tr, tc] of [[0, 0], [0, size - 1], [size - 1, 0], [size - 1, size - 1], [br, size - 1], [size - 1, bc], [Math.floor(size / 2), 0]]) {
for (const [r, c] of snapSelection(size, br, bc, tr, tc).cells) if (r < 0 || c < 0 || r >= size || c >= size) inBounds = false;
}
ok('snap never leaves the grid', inBounds);
ok('lettersAt', lettersAt(['ABC', 'DEF', 'GHI'], [[0, 0], [1, 1], [2, 2]]) === 'AEI');
ok('matchWord forward', matchWord('CAT', ['DOG', 'CAT']) === 'CAT');
ok('matchWord backward', matchWord('TAC', ['DOG', 'CAT']) === 'CAT');
ok('matchWord miss', matchWord('COW', ['DOG', 'CAT']) === null);
const run = (events) => {
let s = idleSelection(); const acts = [];
for (const e of events) { const r = selectionStep(s, e); s = r.state; acts.push(r.action + (r.target ? `@${r.target.r},${r.target.c}` : '')); }
return { s, acts };
};
const A = { r: 2, c: 2 }, B = { r: 2, c: 6 };
let res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'move', cell: { r: 2, c: 4 } }, { type: 'move', cell: B }, { type: 'up', cell: B }]);
ok('drag: anchor → preview → commit on release', res.acts.join() === 'anchor@2,2,preview@2,4,preview@2,6,commit@2,6' && !res.s.anchor, res.acts.join());
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'up', cell: A }, { type: 'move', cell: B }, { type: 'down', cell: B, inGrid: true }]);
ok('click-click: hold then commit on the second click', res.acts.join() === 'anchor@2,2,hold@2,2,preview@2,6,commit@2,6' && !res.s.anchor, res.acts.join());
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'up', cell: A }, { type: 'down', cell: A, inGrid: true }]);
ok('clicking the anchor again cancels', res.acts.at(-1) === 'cancel' && !res.s.anchor);
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'move', cell: B }, { type: 'move', cell: A }, { type: 'up', cell: A }]);
ok('drag back to the start keeps the anchor (click-click)', res.acts.at(-1) === 'hold@2,2' && res.s.anchor?.c === 2);
res = run([{ type: 'down', cell: A, inGrid: false }]);
ok('pressing outside the grid does nothing', res.acts[0] === 'none' && !res.s.anchor);
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'cancel' }]);
ok('cancel clears', res.acts.at(-1) === 'cancel' && !res.s.anchor);
res = run([{ type: 'up', cell: A }, { type: 'move', cell: A }]);
ok('stray up / move with no anchor', res.acts.join() === 'none,none');
}
// ── Geometry + hints + score ──────────────────────────────────────────────────
section('Hints and helpers');
{
const p = samples.find(s => s.difficulty === 'medium');
ok('wordCells spells each word', p.placements.every(pl => wordCells(pl).map(([r, c]) => p.grid[r][c]).join('') === pl.word));
ok('messageWords drops spaces only', messageWords('THE SKY IS').join('|') === 'THE|SKY|IS' && messageWords(p.message).join('') === p.messageLetters);
const found = new Set(p.words.slice(0, 3));
const hinted = new Set([p.words[3]]);
let good = true;
for (let k = 0; k < 50; k++) {
const h = pickHint(p.placements, found, hinted);
const pl = p.placements.find(q => q.word === h.word);
if (!h || found.has(h.word) || hinted.has(h.word) || pl.row !== h.r || pl.col !== h.c) good = false;
}
ok('hint: an unfound, unhinted word, ringed at its first letter', good);
ok('hint: none left → null', pickHint(p.placements, new Set(p.words), new Set()) === null);
ok('hint limits', DIFFS.every(d => Number.isInteger(HINT_LIMITS[d]) && HINT_LIMITS[d] >= 1));
ok('score: harder pays more', calcScore('expert', 30, 0) > calcScore('hard', 20, 0) && calcScore('hard', 20, 0) > calcScore('easy', 10, 0));
ok('score: hints cost, floor 10', calcScore('easy', 10, 1) < calcScore('easy', 10, 0) && calcScore('easy', 1, 99) === 10);
ok('ticket classes', DIFFS.every(d => CLASS[d]?.cls && CLASS[d].size === DIFFICULTY[d].size));
}
// ── Save / resume ────────────────────────────────────────────────────────────
section('Save / resume');
{
const p = samples.find(s => s.difficulty === 'hard');
const base = { difficulty: 'hard', daily: null, puzzle: p, found: p.words.slice(0, 4), hinted: [p.words[6]], hintsLeft: 1, hintsUsed: 1, elapsed: 65432.4, puzzleNo: 4321 };
const json = serialiseSave(base);
const s = parseSave(json);
ok('round trip', s && s.found.join() === base.found.join() && s.hinted[0] === p.words[6] && s.elapsed === 65432 && s.puzzleNo === 4321);
ok('round trip keeps the message', s.puzzle.message === p.message && s.puzzle.grid.join() === p.grid.join());
ok('facts are not stored', !('facts' in JSON.parse(json).puzzle));
const mut = (f) => { const o = JSON.parse(json); f(o); return parseSave(JSON.stringify(o)); };
ok('rejects junk', parseSave('nope') === null && parseSave(null) === null && parseSave('{}') === null);
ok('rejects other versions', mut(o => { o.v = 99; }) === null);
ok('rejects a bad difficulty', mut(o => { o.difficulty = 'insane'; }) === null);
ok('rejects a tampered grid', mut(o => { const r = o.puzzle.grid[0]; o.puzzle.grid[0] = (r[0] === 'A' ? 'B' : 'A') + r.slice(1); }) === null);
ok('rejects a placement off the grid', mut(o => { o.puzzle.placements[0].row = 99; }) === null);
ok('rejects a wrong message', mut(o => { o.puzzle.message = 'NOT THE MESSAGE'; }) === null);
ok('rejects unknown found words', mut(o => { o.found.push('ZZZZ'); }) === null);
ok('rejects a finished puzzle', mut(o => { o.found = [...o.puzzle.words]; }) === null);
ok('repairs bad counters', (() => { const r = mut(o => { o.elapsed = -5; o.hintsLeft = 'x'; o.daily = 'tuesday'; }); return r && r.elapsed === 0 && r.hintsLeft === 0 && r.daily === null; })());
ok('dedupes found words', mut(o => { o.found = [o.found[0], o.found[0]]; })?.found.length === 1);
}
// ── Daily ─────────────────────────────────────────────────────────────────────
section('Daily');
{
ok('dailySeed is stable + per date', dailySeed('2026-11-26') === dailySeed('2026-11-26') && dailySeed('2026-11-26') !== dailySeed('2026-11-27'));
ok('prevDate crosses months', prevDate('2026-12-01') === '2026-11-30' && prevDate('2027-01-01') === '2026-12-31');
let r = updateDaily(blankDaily(), '2026-11-25', '2026-11-25', 90000);
ok('first solve starts a streak', r.streak === 1 && r.rec.solved['2026-11-25'] === 90000);
r = updateDaily(r.rec, '2026-11-26', '2026-11-26', 80000);
ok('next day extends it', r.streak === 2 && r.rec.bestStreak === 2);
r = updateDaily(r.rec, '2026-11-26', '2026-11-26', 70000);
ok('re-solving keeps the streak + faster time', r.streak === 2 && r.newBestTime && r.rec.solved['2026-11-26'] === 70000);
ok('streak alive tomorrow, gone after', dailyStreakNow(r.rec, '2026-11-27') === 2 && dailyStreakNow(r.rec, '2026-11-28') === 0);
r = updateDaily(r.rec, '2026-11-29', '2026-11-29', 50000);
ok('a gap resets to 1', r.streak === 1 && r.rec.bestStreak === 2);
ok('shortDate', shortDate('2026-11-26') === 'Thursday 26 November');
}
// ── Layout ────────────────────────────────────────────────────────────────────
section('Layout');
{
const inside = (a, b) => a.x >= b.x && a.y >= b.y && a.x + a.w <= b.x + b.w && a.y + a.h <= b.y + b.h;
const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
const centred = (o) => ({ x: o.x - o.w / 2, y: o.y - o.h / 2, w: o.w, h: o.h });
ok('the book fits the screen', inside(BOOK, { x: 0, y: 0, w: W, h: H }));
ok('grid box sits on the left page', inside(GRID_BOX, { x: LEFT_PAGE.x + 20, y: LEFT_PAGE.y, w: LEFT_PAGE.w - 40, h: LEFT_PAGE.h }));
ok('message box below the grid, on the page', MSG_BOX.y > GRID_BOX.y + GRID_BOX.h + 10 && inside(MSG_BOX, LEFT_PAGE));
ok('word list on the right page', inside(LIST_BOX, RIGHT_PAGE) && LIST_BOX.y + LIST_BOX.h < FOOT_Y);
ok('doodle on the right page', inside(centred({ x: DOODLE.x, y: DOODLE.y, w: DOODLE.size, h: DOODLE.size }), RIGHT_PAGE));
for (const d of DIFFICULTIES) {
const size = DIFFICULTY[d].size, cell = Math.min(64, Math.floor(GRID_BOX.w / size));
ok(`${d}: grid fits, cells ≥ 38 px`, cell * size <= GRID_BOX.w && cell * size <= GRID_BOX.h && cell >= 38, `cell ${cell}`);
const maxWords = DIFFICULTY[d].words[1];
const cols = maxWords > 24 ? 3 : 2, rows = Math.ceil(maxWords / cols);
const lineH = Math.min(58, Math.floor(LIST_BOX.h / rows));
ok(`${d}: ${maxWords} words fit the list (${cols} columns)`, rows * lineH <= LIST_BOX.h && lineH >= 40);
}
const { layoutBlanks } = await import('../src/games/wordsearch/WordSearchGame.js');
const allMsgs = [...CHAPTER_ORDER.flatMap(id => THEMES[id].messages), ...JOURNEY_MESSAGES];
let worst = 0, okBlanks = true;
for (const m of allMsgs) {
const L = layoutBlanks(messageWords(m), MSG_BOX.w);
const bottom = MSG_BOX.y + 40 + (L.lines - 1) * L.lineH + L.font;
worst = Math.max(worst, bottom);
const right = Math.max(...L.slots.map(s => s.x + L.pitch));
if (L.slots.length !== messageLetters(m).length || right > MSG_BOX.w || bottom > FOOT_Y - 6 || L.pitch < 16) okBlanks = false;
}
ok('every message lays out under the grid', okBlanks, `lowest ${worst}`);
const props = { window: WINDOW, cup: centred({ x: CUP.x, y: CUP.y, w: 140, h: 140 }), ticket: centred(TICKET), fact: centred(FACT) };
BTN.xs.forEach((x, i) => BTN.ys.forEach((y, j) => { props[`btn${i}${j}`] = centred({ x, y, w: BTN.w, h: BTN.h }); }));
SMALL_BTN.xs.forEach((x, i) => { props[`small${i}`] = centred({ x, y: SMALL_BTN.y, w: SMALL_BTN.w, h: SMALL_BTN.h }); });
const keys = Object.keys(props);
for (const k of keys) {
ok(`${k} clears the book`, props[k].x >= BOOK.x + BOOK.w + 8, `${props[k].x}`);
ok(`${k} on screen`, inside(props[k], { x: 0, y: 0, w: W, h: H }));
}
const clashes = [];
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) {
if (keys[i] === 'cup' && keys[j] === 'ticket') continue;
if (overlap(props[keys[i]], props[keys[j]])) clashes.push(`${keys[i]}/${keys[j]}`);
}
ok('right-column props do not overlap', clashes.length === 0, clashes.join());
ok('cup clear of the ticket', CUP.x - 60 > TICKET.x + TICKET.w / 2);
ok('contents cards fit the right page', CARD.w < RIGHT_PAGE.w - 40 && RIGHT_CX - CARD.w / 2 > RIGHT_PAGE.x);
ok('summary fits the screen', SUMMARY.w < W && SUMMARY.h + 140 < H);
}
// ── 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': case 'clearRect': return (...a) => check(fin(...a), 'rect');
case 'fillText': return (s, x, y) => check(typeof s === 'string' && fin(x, y), 'text');
case 'translate': case 'scale': return (...a) => check(fin(...a), k);
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}`);
if (k === 'globalCompositeOperation') check(['source-over', 'destination-out', 'multiply', 'lighter'].includes(v), `composite ${v}`);
t[k] = v; return true;
},
});
const prevDoc = globalThis.document;
const sizes = [];
globalThis.document = { createElement: () => { const ctx = makeCtx(); const c = { width: 0, height: 0, getContext: () => ctx }; sizes.push(c); return c; } };
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/wordsearch/WordSearchArt.js');
art.prepareWordSearchArt(scene);
for (const k of ['ws-carriage', 'ws-sky', 'ws-clouds', 'ws-far', 'ws-mid', 'ws-near', 'ws-poles', 'ws-glass', 'ws-spread',
'ws-leaf', 'ws-cover', 'ws-ticket', 'ws-card', 'ws-postcard', 'ws-summary', 'ws-cup', 'ws-steam', 'ws-pencil'])
ok(`baked ${k}`, added.has(k));
ok('a doodle for every chapter', CHAPTER_ORDER.every(id => added.has(`ws-doodle-${id}`)));
ok('scenery strips are twice the window wide', ['ws-clouds', 'ws-far', 'ws-mid', 'ws-near', 'ws-poles'].every(k => added.get(k).width === WINDOW.w * 2 && added.get(k).height === WINDOW.h));
ok('carriage is full screen', added.get('ws-carriage').width === W && added.get('ws-carriage').height === H);
ok('leaf matches a page', added.get('ws-leaf').width === LEFT_PAGE.w && added.get('ws-leaf').height === BOOK.h && LEFT_PAGE.w === RIGHT_PAGE.w);
const size = added.size;
art.prepareWordSearchArt(scene);
ok('baking twice reuses the textures', added.size === size);
ok('inkNum', art.inkNum('#2c4a8a') === 0x2c4a8a);
} 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 play-through (stubbed Phaser) ──────────────────────────────────────
const mkStub = (dims = 0) => {
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') && dims) return dims;
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 Art = await import('../src/games/wordsearch/WordSearchArt.js');
if (!Art.BookButton.prototype.destroy) Art.BookButton.prototype.destroy = function () {};
const { default: WordSearchGame } = await import('../src/games/wordsearch/WordSearchGame.js');
function makeScene(dims = 0) {
const stub = mkStub(dims);
const delayed = [];
const sc = Object.create(WordSearchGame.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: () => {} },
});
sc.flush = () => { let n = 0; while (delayed.length && n++ < 2000) delayed.shift()(); };
sc.init({ game: { slug: 'wordsearch' } });
sc.previewGfx = stub; sc.pencil = stub; sc.bookImg = stub;
return sc;
}
const boot = (sc, p, { difficulty = p.difficulty, daily = null } = {}) => {
sc.difficulty = difficulty; sc.daily = daily; sc.puzzle = p;
sc.hintsLeft = HINT_LIMITS[difficulty]; sc.puzzleNo = 2468;
sc.buildPlay();
};
const pointAt = (sc, r, c) => { const { x, y } = sc.cellCenter(r, c); return { worldX: x, worldY: y, rightButtonDown: () => false }; };
section('Scene play-through');
{
const sc = makeScene();
let ceremonies = 0, summaries = 0;
sc.winCeremony = (done) => { ceremonies++; done(); };
sc.showSummary = () => { summaries++; };
sc.showFact = () => {};
const p = generatePuzzle({ difficulty: 'hard', theme: 'railway', seed: 99 });
try {
boot(sc, p);
ok('play page: grid geometry', sc.size === 14 && sc.cell === Math.floor(640 / 14) && sc.mode === 'play');
ok('letters laid out', sc.letterText.length === 14 && sc.letterText.every(r => r.length === 14));
ok('a blank per message letter', sc.blankSlots.length === p.messageLetters.length);
ok('word list entries', Object.keys(sc.wordEntries).length === p.words.length);
// a wrong line: nothing found
const pl0 = p.placements[0];
const cells0 = wordCells(pl0);
sc.onPointerDown(pointAt(sc, cells0[0][0], cells0[0][1]), []);
ok('timer starts on the first press', sc.timerOn === true);
sc.onPointerUp(pointAt(sc, cells0[0][0], cells0[0][1]));
ok('a press-release on one letter waits for a second click', !!sc.sel.anchor);
sc.onPointerDown(pointAt(sc, cells0[0][0], cells0[0][1]), []);
ok('clicking it again cancels', !sc.sel.anchor && sc.found.size === 0);
// find everything: alternate drag (forwards) and click-click (backwards)
p.placements.forEach((pl, i) => {
if (sc.found.size === p.words.length - 1 && i === p.placements.length - 1) {
// save mid-way check before the last word
const saved = parseSave(globalThis.localStorage.getItem('wordsearch-save'));
ok('progress autosaved', saved && saved.found.length === p.words.length - 1 && saved.puzzleNo === 2468);
}
const cells = wordCells(pl);
const a = cells[0], b = cells.at(-1);
if (i % 2 === 0) {
sc.onPointerDown(pointAt(sc, a[0], a[1]), []);
sc.onPointerMove(pointAt(sc, b[0], b[1]));
sc.onPointerUp(pointAt(sc, b[0], b[1]));
} else {
sc.onPointerDown(pointAt(sc, b[0], b[1]), []);
sc.onPointerUp(pointAt(sc, b[0], b[1]));
sc.onPointerMove(pointAt(sc, a[0], a[1]));
sc.onPointerDown(pointAt(sc, a[0], a[1]), []);
}
});
ok('every word found by drag and click-click', sc.found.size === p.words.length, `${sc.found.size}/${p.words.length}`);
ok('the win fires once with its ceremony', sc.gameEnded && ceremonies === 1 && summaries === 1);
ok('win clears the save', globalThis.localStorage.getItem('wordsearch-save') === null);
const stats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch') || '{}');
ok('win recorded under hard', stats.hard?.won === 1);
ok('chapter count bumped', stats.chapters?.counts?.railway === 1);
sc.handleWin();
ok('handleWin is idempotent', JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch')).hard.won === 1);
sc.onPointerDown(pointAt(sc, 0, 0), []);
ok('no selection after the win', !sc.sel.anchor);
} catch (err) {
ok('play-through threw', false, err.stack.split('\n').slice(0, 4).join(' | '));
}
// hints, pause, saving and resuming
try {
const q = generatePuzzle({ difficulty: 'easy', theme: 'garden', seed: 5 });
const s2 = makeScene();
s2.showFact = () => {};
s2.toast = () => {};
boot(s2, q);
s2.useHint();
ok('hint: used + ringed', s2.hintsUsed === 1 && s2.hintsLeft === HINT_LIMITS.easy - 1 && s2.hinted.size === 1);
const hintedWord = [...s2.hinted.keys()][0];
const pl = q.placements.find(x => x.word === hintedWord);
s2.acceptWord(pl.word, wordCells(pl));
ok('finding a hinted word clears its ring', s2.hinted.get(hintedWord) === null);
for (let k = 0; k < 10; k++) s2.useHint();
ok('hints stop at the limit', s2.hintsLeft === 0 && s2.hintsUsed === HINT_LIMITS.easy);
s2.setPaused(true);
ok('pause blocks selection', s2.paused && !s2.canSelect());
s2.onPointerDown(pointAt(s2, 0, 0), []);
ok('no anchor while paused', !s2.sel.anchor);
s2.setPaused(false);
s2.elapsed = 12345;
s2.saveGame();
const saved = parseSave(globalThis.localStorage.getItem('wordsearch-save'));
ok('save holds found + hints', saved && saved.found.includes(hintedWord) && saved.hintsUsed === HINT_LIMITS.easy && saved.hintsLeft === 0);
const s3 = makeScene();
s3.toast = () => {};
s3.beginFromSave(saved);
ok('resume restores found words', s3.found.size === saved.found.length && s3.found.has(hintedWord));
ok('resume restores hint rings for unfound words', [...s3.hinted.keys()].every(w => !s3.found.has(w)) && s3.hinted.size === saved.hinted.length);
ok('resume restores the clock + facts', s3.elapsed === 12345 && s3.timerOn && s3.puzzle.facts[hintedWord] === THEMES.garden.words[hintedWord]);
// abandoning via New puzzle
let restarted = null;
s3.scene.restart = (d) => { restarted = d; };
s3.confirm = (t, b, y, yes) => yes();
s3.newPuzzle();
ok('abandon → contents, save gone, counted as played', restarted?.next?.contents && globalThis.localStorage.getItem('wordsearch-save') === null
&& JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch')).easy.played === 1);
} catch (err) {
ok('hint/save run threw', false, err.stack.split('\n').slice(0, 4).join(' | '));
}
// daily
try {
const today = (await import('../src/games/wordsearch/WordSearchLogic.js')).todayString();
const dp = generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed(today) });
const s4 = makeScene();
s4.winCeremony = (done) => done();
s4.showSummary = () => {};
s4.showFact = () => {};
boot(s4, dp, { difficulty: 'medium', daily: today });
for (const pl of dp.placements) s4.acceptWord(pl.word, wordCells(pl));
const rec = JSON.parse(globalThis.localStorage.getItem('wordsearch-daily') || 'null');
ok('daily solve recorded with a streak', rec?.solved?.[today] != null && rec.streak === 1);
const dstats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch') || '{}');
ok('daily stats under their own mode', dstats.daily?.won === 1);
} catch (err) {
ok('daily run threw', false, err.stack.split('\n').slice(0, 4).join(' | '));
}
}
// ── Render paths (stubbed Phaser with real-ish sizes) ────────────────────────
section('Render paths');
{
const sc = makeScene(100);
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('wordsearch-save');
step('carriage + ticket', () => { sc.buildCarriage(); sc.refreshTicket(); });
step('cover', () => { sc.showCover(); });
step('contents', () => { sc.showContents(); sc.selectedTheme = 'music'; sc.drawChapterHl(); });
const p = generatePuzzle({ difficulty: 'expert', theme: 'castles', seed: 3 });
step('expert play page', () => boot(sc, p));
step('preview + deny', () => {
const pl = p.placements[0]; const cells = wordCells(pl);
sc.dispatchSel({ type: 'down', cell: { r: cells[0][0], c: cells[0][1] }, inGrid: true });
sc.dispatchSel({ type: 'move', cell: { r: cells[0][0], c: cells[0][1] + 1 } });
sc.commitSelection([cells[0], [cells[0][0], cells[0][1]]]);
});
step('find + fact postcard', () => { const pl = p.placements[1]; sc.acceptWord(pl.word, wordCells(pl)); sc.showFact(pl.word, { hover: true }); sc.hideFact(); });
step('hint ring', () => sc.useHint());
step('pause + resume', () => { sc.setPaused(true); sc.setPaused(false); });
step('tunnel + rail bump', () => { sc.enterTunnel(); sc.flush(); sc.railBump(); });
step('update tick', () => { sc.strips = { far: { tilePositionX: 0 } }; sc.update(0, 16); });
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('contents with a resume card', () => { sc.saveGame(); sc.mode = 'contents'; sc.showContents(); sc.mode = 'play'; });
step('win ceremony → summary', () => {
sc.mode = 'play'; sc.gameEnded = false;
for (const pl of p.placements) sc.acceptWord(pl.word, wordCells(pl));
sc.flush();
if (!sc.gameEnded) throw new Error('did not win');
});
step('summary for a daily', () => { sc.daily = '2026-11-26'; sc.showSummary({ time: 1000, score: 10, stats: { won: 2, bestTime: 900, streak: 1 }, newBest: {}, daily: { streak: 3, newBestTime: true } }); });
globalThis.localStorage.removeItem('wordsearch-save');
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);