fertig-classic-games/tools/verifySpellingBee.js

427 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

#!/usr/bin/env node
// verifySpellingBee.js — headless checks for "The Apiary" Spelling Bee: the
// curated answer list, the puzzle catalogue (every hive has an answer pangram,
// answer counts inside each mode's band, answers/bonus split, seeded Daily
// determinism), the goal tuning (how many words Genius takes per mode), rank
// ladder + the difficulty-aware rankFor fix, word checking, hints, saves, the
// Daily streak, layout, art bakes against a strict fake 2D context, and a
// stubbed-Phaser smoke run of the play flow (find → Genius → Queen Bee).
// Usage: node tools/verifySpellingBee.js [--quick] [--samples]
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
initSpellingBeeDictionary, generatePuzzle, catalogueStats, DIFFICULTY, scoreWord as engineScore,
} from '../src/words/spellingBeeEngine.js';
import {
GOAL, MODES, DIFFS, isPangram, scoreWord, checkWord, geniusScore, buildTiers, rankFor, wordsToGo,
hintGrid, twoLetterStarts, pickNudge, nudgeText, serialiseSave, parseSave,
dailySeed, prevDate, updateDaily, dailyStreakNow, blankDaily, longDate,
} from '../src/games/spellingbee/SpellingBeeLogic.js';
import {
W, H, HIVE, HEX_R, HEX_D, INPUT_Y, FEEDBACK_Y, CONTROLS_Y, JAR, LEDGER, LEDGER_LIST, LEDGER_BONUS_Y, CARD, OVERLAY_CARD,
} from '../src/games/spellingbee/SpellingBeeArt.js';
const QUICK = process.argv.includes('--quick');
const SAMPLES = process.argv.includes('--samples');
const DRAWS = QUICK ? 150 : 600;
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 q = (a, ps = [0.1, 0.5, 0.9]) => { const s = [...a].sort((x, y) => x - y); return ps.map((p) => s[Math.floor(p * (s.length - 1))]); };
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const LISTS = path.join(__dirname, '../data/wordlists');
const enableRaw = fs.readFileSync(path.join(LISTS, 'enable1.txt'), 'utf8');
const enable = new Set(enableRaw.split('\n').map((w) => w.trim().toUpperCase()).filter(Boolean));
const answersRaw = fs.readFileSync(path.join(LISTS, 'spellingbee-answers.txt'), 'utf8');
const denyRaw = fs.readFileSync(path.join(LISTS, 'spellingbee-deny.txt'), 'utf8');
// ── Answer list ───────────────────────────────────────────────────────────────
section('Answer list');
const tierOf = new Map();
{
let badLine = 0, notEnable = 0, notBee = 0;
for (const line of answersRaw.split('\n')) {
if (!line.trim()) continue;
const [w, t] = line.split('\t');
if (!/^[A-Z]+$/.test(w) || !['core', 'familiar'].includes(t)) { badLine++; continue; }
if (!enable.has(w)) notEnable++;
if (w.length < 4 || w.includes('S') || new Set(w).size > 7) notBee++;
tierOf.set(w, t);
}
ok('every line is WORD<TAB>core|familiar', badLine === 0, `${badLine} bad lines`);
ok('every answer is an ENABLE word', notEnable === 0, `${notEnable} not in ENABLE`);
ok('every answer can appear in a hive', notBee === 0, `${notBee} ineligible`);
const core = [...tierOf.values()].filter((t) => t === 'core').length;
ok('a healthy list (core ≥ 8k, total ≥ 12k)', core >= 8000 && tierOf.size >= 12000, `${core} core / ${tierOf.size}`);
const deny = new Set(denyRaw.split('\n').map((l) => l.replace(/#.*/, '')).join(' ').split(/\s+/).filter(Boolean));
const leaked = [...deny].filter((w) => tierOf.has(w));
ok('no denied word is an answer', leaked.length === 0, leaked.slice(0, 8).join(' '));
for (const w of ['ALAN', 'ANNA', 'DONNA', 'APOLLO', 'GLORIA', 'FRANKLIN']) ok(`name "${w}" is not an answer`, !tierOf.has(w));
for (const w of ['APPLE', 'GARDEN', 'MOTHER', 'BREAD', 'HONEY', 'BEACH']) ok(`everyday "${w}" is core`, tierOf.get(w) === 'core');
}
// ── Engine / catalogue ────────────────────────────────────────────────────────
section('Engine & catalogue');
const stats = initSpellingBeeDictionary(enableRaw.split('\n'), answersRaw);
const t0 = Date.now();
const cat = catalogueStats();
const catMs = Date.now() - t0;
console.log(` dictionary ${stats.words} words, ${stats.answers} answers, ${stats.pangramSets} pangram sets; pools ${JSON.stringify(cat.pools)} (${catMs} ms)`);
ok('catalogue builds quickly (< 1.5 s)', catMs < 1500, `${catMs} ms`);
for (const d of DIFFS) ok(`${d}: pool has ≥ 500 hives`, cat.pools[d] >= 500, String(cat.pools[d]));
ok('engine and client agree on modes', DIFFS.every((d) => DIFFICULTY[d] && MODES[d] && GOAL[d]));
const byDiff = {};
for (const d of DIFFS) {
const spec = DIFFICULTY[d];
const list = [];
let probs = [];
for (let i = 0; i < DRAWS; i++) {
const p = generatePuzzle(d);
list.push(p);
const letters = new Set(p.letters);
if (p.letters.length !== 7 || letters.size !== 7) probs.push('letters');
if (p.letters.includes('S')) probs.push('S');
if (p.outer.length !== 6 || p.outer.includes(p.center) || !p.outer.every((l) => letters.has(l))) probs.push('outer');
if (!p.pangrams.length) probs.push('no answer pangram');
if (p.answers.length < spec.answers[0] || p.answers.length > spec.answers[1]) probs.push(`band ${p.answers.length}`);
const all = [...p.answers, ...p.bonus];
if (new Set(all).size !== all.length) probs.push('answers∩bonus');
for (const w of all) {
if (!enable.has(w)) { probs.push(`not ENABLE ${w}`); break; }
if (!w.includes(p.center) || [...w].some((c) => !letters.has(c)) || w.length < 4) { probs.push(`invalid ${w}`); break; }
}
for (const w of p.answers) {
const t = tierOf.get(w);
if (!t || (spec.tier === 0 && t !== 'core')) { probs.push(`tier ${w}`); break; }
}
if (p.maxScore !== p.answers.reduce((s, w) => s + scoreWord(w), 0)) probs.push('maxScore');
if (p.answers.some((w) => engineScore(w, new Set(w).size === 7) !== scoreWord(w))) probs.push('score mismatch');
if (p.validWords.length !== all.length) probs.push('validWords');
if ((p.letters.includes('Q') && !p.letters.includes('U'))) probs.push('Q without U');
}
probs = [...new Set(probs)];
ok(`${d}: ${DRAWS} hives all well-formed`, probs.length === 0, probs.slice(0, 6).join('; '));
byDiff[d] = list;
}
{
const a = generatePuzzle('normal', { seed: 12345 });
const b = generatePuzzle('normal', { seed: 12345 });
const c = generatePuzzle('normal', { seed: 12346 });
ok('same seed → same hive', a.id === b.id && a.outer.join('') === b.outer.join('') && a.answers.join() === b.answers.join());
ok('different seeds → (almost always) different hives', a.id !== c.id || a.outer.join('') !== c.outer.join(''));
const ids = new Set();
for (let d = 1; d <= 60; d++) ids.add(generatePuzzle('normal', { seed: dailySeed(`2026-12-${String(d % 31 + 1).padStart(2, '0')}`) + d }).id);
ok('daily seeds spread over many hives', ids.size >= 50, `${ids.size}/60 distinct`);
}
// ── Goal tuning ───────────────────────────────────────────────────────────────
section('Goal tuning (words needed for Genius)');
const TARGET = { easy: [8, 13], normal: [16, 25], hard: [30, 42] };
{
const rows = [];
for (const d of DIFFS) {
const rnd = [], shortFirst = [], answers = [], bonus = [];
for (const p of byDiff[d]) {
const pts = p.answers.map(scoreWord);
const goal = geniusScore(p.maxScore, d);
let acc = 0;
for (let k = 0; k < 4; k++) {
const o = [...pts].sort(() => Math.random() - 0.5);
let s = 0, n = 0; while (s < goal) s += o[n++]; acc += n;
}
rnd.push(Math.round(acc / 4));
const o = [...pts].sort((a, b) => a - b);
let s = 0, n = 0; while (s < goal) s += o[n++];
shortFirst.push(n);
answers.push(p.answers.length);
bonus.push(p.bonus.length);
}
const [r10, r50, r90] = q(rnd), [s10, s50, s90] = q(shortFirst);
rows.push(` ${d.padEnd(6)} answers ${q(answers).join('/')} bonus ${q(bonus).join('/')} Genius ${Math.round(GOAL[d] * 100)}% → words (random order) ${r10}/${r50}/${r90}, (short words first) ${s10}/${s50}/${s90}`);
const mid = (r50 + s50) / 2;
ok(`${d}: typical words-to-Genius in ${TARGET[d].join('–')}`, mid >= TARGET[d][0] && mid <= TARGET[d][1], `mid ${mid}`);
}
console.log(rows.join('\n'));
console.log(' (before this overhaul: answers were every ENABLE word; only ~1/3 were common words and the pangram was a common word in < 10% of hives)');
const med = (d) => q(byDiff[d].map((p) => p.answers.length))[1];
ok('harder modes have more words to find', med('easy') < med('normal') && med('normal') < med('hard'));
}
if (SAMPLES || QUICK) {
section('Sample hives');
for (const d of DIFFS) for (const p of byDiff[d].slice(0, SAMPLES ? 5 : 1)) {
console.log(` ${d} ${p.center}/${p.letters.join('')} pangram ${p.pangrams.join(',')} ${p.answers.length} answers: ${p.answers.join(' ')}`);
}
}
// ── Ranks ─────────────────────────────────────────────────────────────────────
section('Ranks');
{
for (const d of DIFFS) {
const t = buildTiers(200, d);
ok(`${d}: thresholds rise`, t.every((x, i) => i === 0 || x.threshold >= t[i - 1].threshold) && t[0].threshold === 0);
ok(`${d}: Genius threshold = goal`, t.at(-1).threshold === geniusScore(200, d) && t.at(-1).name === 'Genius');
}
ok('Genius line moves with difficulty', geniusScore(200, 'easy') < geniusScore(200, 'normal') && geniusScore(200, 'normal') < geniusScore(200, 'hard'));
const g = geniusScore(200, 'easy');
ok('rankFor respects difficulty (the old bug)', rankFor(g, 200, 'easy').isGenius && !rankFor(g, 200, 'hard').isGenius);
ok('rankFor below Genius', !rankFor(g - 1, 200, 'easy').isGenius && rankFor(g - 1, 200, 'easy').next?.name === 'Genius');
ok('rankFor at zero = Beginner', rankFor(0, 200, 'normal').current.name === 'Beginner');
const ans = ['ABLE', 'TABLE', 'BLEAT', 'BALLET'];
ok('wordsToGo = 0 once there', wordsToGo(50, 40, ans, new Set()) === 0);
ok('wordsToGo estimates', wordsToGo(0, 10, ans, new Set()) >= 1 && wordsToGo(0, 10, ans, new Set()) <= 4);
}
// ── Scoring & checking ────────────────────────────────────────────────────────
section('Scoring & word check');
{
ok('4 letters = 1', scoreWord('ABLE') === 1);
ok('5 letters = 5', scoreWord('TABLE') === 5);
ok('pangram +7', isPangram('PLAYTIME') === false && isPangram('BETRAYAL') && scoreWord('BETRAYAL') === 8 + 7);
const st = { center: 'A', letters: ['A', 'B', 'L', 'E', 'T', 'R', 'Y'], answers: new Set(['TABLE', 'BETRAY']), bonus: new Set(['ABLER']), found: new Set(['BETRAY']) };
ok('too short', checkWord('TAB', st).reason === 'Too short');
ok('bad letters', checkWord('TABLES', st).reason === 'Bad letters');
ok('missing center', checkWord('BYTE', st).reason === 'Missing center letter');
ok('already found', checkWord('betray', st).reason === 'Already found' && checkWord('BETRAY', st).tone === 'muted');
ok('not in list', checkWord('BLART', st).reason === 'Not in word list');
const a = checkWord('TABLE', st), b = checkWord('ABLER', st);
ok('answer accepted', a.ok && a.kind === 'answer' && a.pts === 5);
ok('bonus accepted', b.ok && b.kind === 'bonus' && b.pts === 5);
}
// ── Hints ─────────────────────────────────────────────────────────────────────
section('Hints');
{
const p = byDiff.normal[0];
const found = new Set(p.answers.slice(0, 5));
const left = p.answers.length - 5;
const g = hintGrid(p.answers, found);
ok('grid total = remaining answers', g.total === left && g.rows.reduce((s, r) => s + r.total, 0) === left);
ok('grid column totals add up', Object.values(g.colTotals).reduce((a, b) => a + b, 0) === left);
ok('grid rows are letters of the hive', g.rows.every((r) => p.letters.includes(r.letter)));
ok('two-letter starts add up', twoLetterStarts(p.answers, found).reduce((s, x) => s + x.n, 0) === left);
const n1 = pickNudge(p.answers, found, []);
ok('first nudge prefers a pangram', isPangram(n1) || p.pangrams.every((w) => found.has(w)));
const n2 = pickNudge(p.answers, found, [n1]);
ok('nudges don\'t repeat', n2 && n2 !== n1 && !found.has(n2));
ok('nudge text', nudgeText('TABLE') === 'TA···');
ok('nothing to nudge when all found', pickNudge(['ABLE'], new Set(['ABLE'])) === null);
}
// ── Saves ─────────────────────────────────────────────────────────────────────
section('Saves');
{
const p = byDiff.hard[0];
const found = new Set([p.answers[0], p.answers[1], ...(p.bonus.length ? [p.bonus[0]] : [])]);
const json = serialiseSave({ difficulty: 'hard', daily: '2026-11-26', puzzle: p, found, nudged: [p.answers[2]], hintsUsed: 2, geniusAt: null });
const s = parseSave(json);
ok('round trip', s && s.difficulty === 'hard' && s.daily === '2026-11-26' && s.found.size === found.size && s.hintsUsed === 2);
ok('score recomputed from found words', s.score === [...found].reduce((t, w) => t + scoreWord(w), 0));
ok('maxScore recomputed', s.puzzle.maxScore === p.maxScore);
ok('outer order kept', s.puzzle.outer.join('') === p.outer.join(''));
ok('corrupt json → null', parseSave('{nope') === null && parseSave(null) === null);
ok('wrong version → null', parseSave(JSON.stringify({ ...JSON.parse(json), v: 99 })) === null);
ok('tampered letters → null', parseSave(JSON.stringify({ ...JSON.parse(json), puzzle: { ...JSON.parse(json).puzzle, center: 'S' } })) === null);
const done = serialiseSave({ difficulty: 'hard', puzzle: p, found: new Set(p.answers) });
ok('finished hive → nothing to resume', parseSave(done) === null);
const junk = JSON.parse(json); junk.found.push('ZZZZ');
ok('unknown found words dropped', parseSave(JSON.stringify(junk)).found.size === found.size);
}
// ── Daily ─────────────────────────────────────────────────────────────────────
section('Daily Hive');
{
ok('prevDate across a month', prevDate('2026-12-01') === '2026-11-30');
ok('seed is stable', dailySeed('2026-11-26') === dailySeed('2026-11-26') && dailySeed('2026-11-26') !== dailySeed('2026-11-27'));
let r = blankDaily();
({ rec: r } = updateDaily(r, '2026-11-24', '2026-11-24', { score: 20, rank: 'Nice' }));
ok('progress without Genius keeps streak at 0', r.streak === 0 && r.best['2026-11-24'].score === 20);
({ rec: r } = updateDaily(r, '2026-11-24', '2026-11-24', { score: 90, rank: 'Genius', genius: true }));
({ rec: r } = updateDaily(r, '2026-11-25', '2026-11-25', { score: 80, rank: 'Genius', genius: true }));
ok('consecutive Genius days build a streak', r.streak === 2 && dailyStreakNow(r, '2026-11-26') === 2);
ok('streak lapses after a missed day', dailyStreakNow(r, '2026-11-27') === 0);
({ rec: r } = updateDaily(r, '2026-11-25', '2026-11-25', { score: 60, rank: 'Great' }));
ok('best score is kept', r.best['2026-11-25'].score === 80);
({ rec: r } = updateDaily(r, '2026-11-20', '2026-11-25', { score: 99, rank: 'Genius', genius: true }));
ok('an old Daily doesn\'t move the streak', r.streak === 2);
ok('longDate', longDate('2026-11-26') === 'Thursday, November 26');
}
// ── Layout ────────────────────────────────────────────────────────────────────
section('Layout');
{
const half = HEX_R * Math.sqrt(3) / 2;
const hiveTop = HIVE.y - HEX_D * Math.sin(Math.PI / 3) - HEX_R;
const hiveBottom = HIVE.y + HEX_D * Math.sin(Math.PI / 3) + HEX_R;
const hiveLeft = HIVE.x - HEX_D - half, hiveRight = HIVE.x + HEX_D + half;
ok('cells sit flush (spacing ≥ 2 × apothem)', HEX_D >= HEX_R * Math.sqrt(3));
ok('input line clears the hive', INPUT_Y + 36 < hiveTop && FEEDBACK_Y + 30 < INPUT_Y - 30);
ok('controls clear the hive', CONTROLS_Y - 30 > hiveBottom);
ok('jar + tick labels clear the hive', JAR.x + JAR.w / 2 + 90 < hiveLeft);
ok('hive clears the ledger', hiveRight + 40 < LEDGER.x);
ok('ledger fits the screen', LEDGER.x + LEDGER.w <= W && LEDGER.y + LEDGER.h <= H - 60);
ok('ledger list fits ≥ 65 words in 4 columns', Math.floor(LEDGER_LIST.h / 30) * 4 >= 65);
ok('ledger list ends above Rare finds', LEDGER_LIST.y + LEDGER_LIST.h <= LEDGER_BONUS_Y);
ok('cards fit the screen', CARD.w < W && CARD.h < H && OVERLAY_CARD.w < W && OVERLAY_CARD.h < 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': return (...a) => check(fin(...a), 'rect');
case 'drawImage': return (img, ...a) => check(img && fin(...a), 'drawImage');
default: return () => {};
}
},
set(t, k, v) {
if ((k === 'fillStyle' || k === 'strokeStyle') && typeof v === 'string') check(colourOk(v), `${k} ${v}`);
if (k === 'lineWidth' || k === 'globalAlpha') check(Number.isFinite(v) && v >= 0, `${k} ${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) || k === 'spellingbee-bg',
addCanvas: (k, c) => { added.set(k, c); return {}; },
get: () => ({ getSourceImage: () => ({ width: 1920, height: 1080 }) }),
} };
try {
const art = await import('../src/games/spellingbee/SpellingBeeArt.js');
art.prepareBeeArt(scene);
for (const k of ['bee-cell', 'bee-cell-center', 'bee-cell-shadow', 'bee-body', 'bee-wing', 'bee-jar', 'bee-ledger',
'bee-card', 'bee-overlay-card', 'bee-vignette', 'bee-glow', 'bee-drip'])
ok(`baked ${k}`, added.has(k));
const size = added.size;
art.prepareBeeArt(scene);
ok('baking twice reuses the textures', added.size === size);
ok('soft backdrop bakes', art.bakeSoftBackdrop(scene, 'spellingbee-bg') === 'bee-bg-soft' && added.has('bee-bg-soft'));
} 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) };
try {
const { default: Game } = await import('../src/games/spellingbee/SpellingBeeGame.js');
const sc = Object.create(Game.prototype);
const stub = mk();
const delayed = [];
Object.assign(sc, {
add: stub, make: stub, tweens: stub, sound: stub, cameras: stub, textures: stub, input: stub, events: stub, cache: stub, load: stub,
sys: { isActive: () => true },
time: { now: 0, delayedCall: (ms, f) => { delayed.push(f); return stub; } },
scene: { restart: () => {}, start: () => {} },
});
const flush = () => { while (delayed.length) delayed.shift()(); };
let geniusShown = 0, queenShown = 0;
for (const m of ['buildHeader', 'buildJar', 'buildHive', 'buildInput', 'buildControls', 'buildLedger', 'buildBees',
'renderInput', 'feedback', 'pangramFx', 'swarm', 'shakeInput', 'scatterBees', 'rankUp', 'flashLedgerWord', 'animatePress',
'drawTicks', 'refreshLedger', 'addAnswerToLedger'])
sc[m] = function () {};
sc.showGenius = () => { geniusShown++; };
sc.showQueenBee = () => { queenShown++; sc.mode = 'done'; };
sc.postHistory = () => {};
sc.inputChars = [];
sc.cells = [];
for (const k of ['rankText', 'scoreText', 'nextText', 'crown']) sc[k] = stub;
const p = generatePuzzle('easy', { seed: 4242 });
sc.init({ game: { slug: 'spellingbee' } });
sc.beginHive({ difficulty: 'easy', daily: null, puzzle: p, found: new Set(), score: 0, nudged: [], hintsUsed: 0, geniusAt: null });
const type = (w) => { for (const c of w) sc.typeLetter(c); sc.submitWord(); flush(); };
type('ZZZZ');
ok('a bad word scores nothing', sc.score === 0 && sc.found.size === 0);
if (p.bonus.length) {
type(p.bonus[0]);
ok('a bonus word scores but isn\'t an answer', sc.found.has(p.bonus[0]) && sc.score === scoreWord(p.bonus[0]));
}
const before = sc.score;
type(p.answers[0]);
ok('an answer scores', sc.score === before + scoreWord(p.answers[0]));
const saved = parseSave(store.get('spellingbee-save'));
ok('progress autosaved', saved && saved.found.has(p.answers[0]) && saved.puzzle.id === p.id);
type(p.answers[0]);
ok('a repeat scores nothing', sc.score === before + scoreWord(p.answers[0]));
// Find answers (shortest first) until Genius.
const order = [...p.answers].sort((a, b) => scoreWord(a) - scoreWord(b));
for (const w of order) { if (sc.geniusAt != null) break; type(w); }
ok('Genius fires once, at the goal', geniusShown === 1 && sc.score >= geniusScore(p.maxScore, 'easy'));
const stats = JSON.parse(store.get('solitaire-stats-spellingbee') || '{}');
ok('Genius recorded as a win under easy', stats.easy?.won === 1 && stats.easy?.played === 1);
ok('save keeps going after Genius', parseSave(store.get('spellingbee-save'))?.geniusAt != null);
for (const w of order) if (!sc.found.has(w)) type(w);
ok('Queen Bee when every answer is found', queenShown === 1 && sc.queen === true);
ok('Queen Bee clears the save', !store.has('spellingbee-save'));
const st2 = JSON.parse(store.get('solitaire-stats-spellingbee'));
ok('one hive = one game in the stats', st2.easy.played === 1 && st2.easy.counts?.queen === 1);
ok('no Genius fired twice', geniusShown === 1);
// A hive closed before Genius counts as a loss.
store.clear();
const p2 = generatePuzzle('hard', { seed: 99 });
sc.init({ game: { slug: 'spellingbee' } });
sc.inputChars = []; sc.cells = [];
for (const k of ['rankText', 'scoreText', 'nextText', 'crown']) sc[k] = stub;
sc.showReveal = () => {};
sc.beginHive({ difficulty: 'hard', daily: '2026-11-26', puzzle: p2, found: new Set(), score: 0, nudged: [], hintsUsed: 0, geniusAt: null });
type(p2.answers[0]);
ok('daily progress recorded', JSON.parse(store.get('spellingbee-daily')).best['2026-11-26']?.score === scoreWord(p2.answers[0]));
sc.closeHive();
const st3 = JSON.parse(store.get('solitaire-stats-spellingbee'));
ok('closing early = a loss', st3.hard.played === 1 && st3.hard.won === 0 && !store.has('spellingbee-save'));
} catch (err) {
ok('scene smoke run threw', false, err.stack);
}
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);