365 lines
23 KiB
JavaScript
365 lines
23 KiB
JavaScript
#!/usr/bin/env node
|
||
// verifyBoggle.js — headless checks for Boggle:
|
||
// • scoring table, min-length rule, duplicate cancelling on/off
|
||
// • revealPlan: shown totals == committed round scores (the old overflow bug)
|
||
// • adjacency / paths / findPath (Qu, preferring the current path) / typing
|
||
// • engine: seeded determinism, 4×4 + 5×5 dice sets, solver vs an independent
|
||
// prefix-set reference, every solution path valid and spelling its word
|
||
// • familiarity tiers spot-checks
|
||
// • review groups, summaries, hints, practice goal, daily streaks, saves
|
||
// • AI: schedules valid, target word counts per skill, skill ladder (mirrored boards)
|
||
// • screen layout: furniture on screen, no overlaps (0–3 rivals, both sizes)
|
||
// Usage: node tools/verifyBoggle.js [--quick] [--ladder]
|
||
|
||
import fs from 'fs';
|
||
import path from 'path';
|
||
import { fileURLToPath } from 'url';
|
||
import * as E from '../src/words/boggleEngine.js';
|
||
import * as L from '../src/games/boggle/BoggleLogic.js';
|
||
import { scheduleFinds, familyMap, stemOf } from '../src/games/boggle/BoggleAI.js';
|
||
import * as Y from '../src/games/boggle/BoggleLayout.js';
|
||
|
||
const QUICK = process.argv.includes('--quick');
|
||
const LADDER = process.argv.includes('--ladder');
|
||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||
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}`);
|
||
|
||
// ── dictionary ─────────────────────────────────────────────────────────────
|
||
const t0 = Date.now();
|
||
const read = (f) => fs.readFileSync(path.join(ROOT, 'data/wordlists', f), 'utf8');
|
||
const enable = read('enable1.txt').split('\n').map((w) => w.trim().toUpperCase()).filter((w) => w.length >= 3 && w.length <= 16 && /^[A-Z]+$/.test(w));
|
||
E.initBoggleDictionary(enable);
|
||
E.initBoggleCommonWords(read('common.txt').split('\n'), read('spellingbee-answers.txt'));
|
||
const DICT = new Set(enable);
|
||
console.log(`dictionary: ${enable.length} words (${Date.now() - t0} ms)`);
|
||
|
||
// ── scoring ────────────────────────────────────────────────────────────────
|
||
section('Scoring');
|
||
{
|
||
const T = [['CAT', 1], ['CATS', 1], ['CATER', 2], ['CATERS', 3], ['CRATERS', 5], ['SCATTERS', 11], ['QUEST', 2], ['QUESTION', 11]];
|
||
for (const [w, p] of T) ok(`score ${w} = ${p}`, L.scoreWord(w) === p, String(L.scoreWord(w)));
|
||
ok('2-letter scores 0', L.scoreWord('AT') === 0);
|
||
ok('minLen 4: 3-letter scores 0', L.scoreWord('CAT', 4) === 0 && L.scoreWord('CATS', 4) === 1);
|
||
const sheets = [{ found: ['CAT', 'CATER', 'DOG'] }, { found: ['cat', 'RATE'] }, { found: ['CATER', 'TOP', 'cat'] }];
|
||
const on = L.resolveRound(sheets, { dupCancel: true });
|
||
ok('dup cancel: p0 = DOG only', on[0].roundScore === 1, JSON.stringify(on[0]));
|
||
ok('dup cancel: p1 = RATE', on[1].roundScore === 1);
|
||
ok('dup cancel: p2 = TOP', on[2].roundScore === 1);
|
||
ok('sharedWith lists the other finders', JSON.stringify(on[0].words.find((w) => w.word === 'CAT').sharedWith) === '[1,2]');
|
||
ok('unique/shared counts', on[0].unique === 1 && on[0].shared === 2);
|
||
const off = L.resolveRound(sheets, { dupCancel: false });
|
||
ok('dup off: p0 = 1+2+1', off[0].roundScore === 4, String(off[0].roundScore));
|
||
ok('dup off: nothing marked dup', off.every((r) => r.words.every((w) => !w.dup)));
|
||
const min4 = L.resolveRound(sheets, { minLen: 4, dupCancel: false });
|
||
ok('minLen 4 in resolveRound', min4[0].roundScore === 2, String(min4[0].roundScore));
|
||
|
||
// reveal plan totals == round scores, even for very long sheets
|
||
const big = (n, tag) => Array.from({ length: n }, (_, i) => `${tag}${String.fromCharCode(65 + (i % 26))}${String.fromCharCode(65 + Math.floor(i / 26))}XYZ`.slice(0, 4 + (i % 6)));
|
||
const sheets2 = [{ found: [...big(80, 'A'), 'SHARED', 'BOTH'] }, { found: [...big(45, 'B'), 'SHARED'] }, { found: ['BOTH', 'SHARED', ...big(5, 'C')] }];
|
||
for (const dup of [true, false]) {
|
||
const res = L.resolveRound(sheets2, { dupCancel: dup });
|
||
const plan = L.revealPlan(res);
|
||
const sums = res.map(() => 0);
|
||
for (const st of plan.steps) for (const e of st.entries) sums[e.player] += e.score;
|
||
ok(`revealPlan sums == roundScore (dup ${dup})`, sums.every((s, i) => s === res[i].roundScore), `${sums} vs ${res.map((r) => r.roundScore)}`);
|
||
ok(`revealPlan rows == word counts (dup ${dup})`, plan.rows.every((r, i) => r === res[i].words.length));
|
||
const shared = plan.steps.find((s) => s.word === 'SHARED');
|
||
ok(`shared word revealed on one beat for all (dup ${dup})`, shared && shared.entries.length === 3);
|
||
}
|
||
ok('revealPlan longest first', (() => { const p = L.revealPlan(L.resolveRound(sheets)); return p.steps.every((s, i) => i === 0 || p.steps[i - 1].word.length >= s.word.length); })());
|
||
}
|
||
|
||
// ── paths & typing ─────────────────────────────────────────────────────────
|
||
section('Paths & typing');
|
||
{
|
||
ok('adjacent diag', L.areAdjacent([0, 0], [1, 1]));
|
||
ok('not adjacent self', !L.areAdjacent([1, 1], [1, 1]));
|
||
ok('not adjacent 2 away', !L.areAdjacent([0, 0], [0, 2]));
|
||
ok('valid path', L.isValidPath([[0, 0], [0, 1], [1, 2]]));
|
||
ok('invalid repeat', !L.isValidPath([[0, 0], [0, 1], [0, 0]]));
|
||
ok('invalid jump', !L.isValidPath([[0, 0], [2, 2]]));
|
||
const B = [
|
||
['Qu', 'E', 'S', 'T'],
|
||
['A', 'R', 'T', 'E'],
|
||
['C', 'A', 'T', 'S'],
|
||
['D', 'O', 'G', 'E'],
|
||
];
|
||
const q = L.findPath(B, 'QUEST');
|
||
ok('findPath QUEST via Qu', q && L.pathWord(B, q) === 'QUEST' && q.length === 4, JSON.stringify(q));
|
||
ok('findPath missing → null', L.findPath(B, 'ZEBRA') === null);
|
||
ok('findPath half a Qu → null', L.findPath(B, 'Q') === null);
|
||
ok('findPath empty → []', Array.isArray(L.findPath(B, '')) && L.findPath(B, '').length === 0);
|
||
// two T's after CA: (2,2) and (1,2)… prefer the path we already have
|
||
const first = L.findPath(B, 'CAT');
|
||
const alt = [[2, 0], [2, 1], [1, 2]];
|
||
ok('alt CAT path is valid', L.isValidPath(alt) && L.pathWord(B, alt) === 'CAT');
|
||
const ext = L.findPath(B, 'CATE', alt);
|
||
ok('prefers extending the current path', ext && ext[2][0] === 1 && ext[2][1] === 2, JSON.stringify(ext));
|
||
const ext2 = L.findPath(B, 'CATS', first);
|
||
ok('extends the first path too', ext2 && JSON.stringify(ext2.slice(0, 3)) === JSON.stringify(first), JSON.stringify([first, ext2]));
|
||
let t = L.typeLetter('', 'q');
|
||
ok('Q types QU', t.word === 'QU' && t.lastWasQ);
|
||
t = L.typeLetter(t.word, 'u', t.lastWasQ);
|
||
ok('U after Q swallowed', t.word === 'QU' && !t.lastWasQ);
|
||
t = L.typeLetter(t.word, 'u', t.lastWasQ);
|
||
ok('second U kept', t.word === 'QUU');
|
||
ok('non-letter ignored', L.typeLetter('AB', '1').word === 'AB');
|
||
ok('backspace removes QU as a unit', L.backspace('QU') === '' && L.backspace('SQU') === 'S' && L.backspace('CAT') === 'CA');
|
||
const valid = new Set(['CAT', 'CATS']);
|
||
ok('reject short', L.rejectReason('CA', { minLen: 3, found: new Set(), valid }) === 'short');
|
||
ok('reject already', L.rejectReason('CAT', { minLen: 3, found: new Set(['CAT']), valid }) === 'already');
|
||
ok('reject notWord', L.rejectReason('CTA', { minLen: 3, found: new Set(), valid }) === 'notWord');
|
||
ok('reject off board', L.rejectReason('CAT', { minLen: 3, found: new Set(), valid, onBoard: false }) === 'notOnBoard');
|
||
ok('accept', L.rejectReason('CATS', { minLen: 3, found: new Set(['CAT']), valid }) === null);
|
||
}
|
||
|
||
// ── engine ─────────────────────────────────────────────────────────────────
|
||
section('Engine');
|
||
// Independent reference solver: prefix Set + plain DFS (no trie).
|
||
const PREFIX = new Set();
|
||
for (const w of enable) for (let i = 1; i <= w.length; i++) PREFIX.add(w.slice(0, i));
|
||
function refSolve(grid) {
|
||
const n = grid.length, out = new Set();
|
||
const used = Array.from({ length: n }, () => new Array(n).fill(false));
|
||
const go = (r, c, s) => {
|
||
const w = s + grid[r][c].toUpperCase();
|
||
if (!PREFIX.has(w)) return;
|
||
if (w.length >= 3 && DICT.has(w)) out.add(w);
|
||
used[r][c] = true;
|
||
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
|
||
const nr = r + dr, nc = c + dc;
|
||
if ((dr || dc) && nr >= 0 && nc >= 0 && nr < n && nc < n && !used[nr][nc]) go(nr, nc, w);
|
||
}
|
||
used[r][c] = false;
|
||
};
|
||
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) go(r, c, '');
|
||
return out;
|
||
}
|
||
// Can the board's faces be assigned to distinct dice of the set? (bipartite matching)
|
||
function facesFromDice(board, dice) {
|
||
const faces = board.flat().map((t) => (t === 'Qu' ? 'Q' : t));
|
||
if (faces.length !== dice.length) return false;
|
||
const match = new Array(dice.length).fill(-1);
|
||
const tryFace = (f, seen) => {
|
||
for (let d = 0; d < dice.length; d++) {
|
||
if (seen[d] || !dice[d].includes(faces[f])) continue;
|
||
seen[d] = true;
|
||
if (match[d] < 0 || tryFace(match[d], seen)) { match[d] = f; return true; }
|
||
}
|
||
return false;
|
||
};
|
||
return faces.every((_, f) => tryFace(f, new Array(dice.length).fill(false)));
|
||
}
|
||
{
|
||
const N = QUICK ? 12 : 60;
|
||
let mism = 0, bad = 0, dice = 0, sizes = 0, totalWords = { 4: 0, 5: 0 }, ms = 0;
|
||
for (const size of [4, 5]) {
|
||
for (let i = 0; i < N; i++) {
|
||
const tt = Date.now();
|
||
const g = E.generateBoard({ size, seed: 9000 + i });
|
||
ms += Date.now() - tt;
|
||
if (g.board.length !== size || g.board.some((row) => row.length !== size)) sizes++;
|
||
if (!facesFromDice(g.board, size === 5 ? E.DICE_5 : E.DICE_4)) dice++;
|
||
const ref = refSolve(g.board);
|
||
const got = new Set(g.solutions.map((s) => s.word));
|
||
if (ref.size !== got.size || [...ref].some((w) => !got.has(w))) mism++;
|
||
for (const s of g.solutions) {
|
||
if (!L.isValidPath(s.path) || L.pathWord(g.board, s.path) !== s.word || ![1, 2, 3].includes(s.tier)) bad++;
|
||
}
|
||
totalWords[size] += got.size;
|
||
}
|
||
}
|
||
ok('boards are N×N', sizes === 0, String(sizes));
|
||
ok('faces come from distinct dice of the right set', dice === 0, String(dice));
|
||
ok('solver == reference word set', mism === 0, `${mism} boards differ`);
|
||
ok('every solution path valid + spells its word + has a tier', bad === 0, String(bad));
|
||
console.log(` avg words: 4×4 ${(totalWords[4] / N).toFixed(0)}, 5×5 ${(totalWords[5] / N).toFixed(0)} · ${(ms / (2 * N)).toFixed(1)} ms/board`);
|
||
ok('generation under 25 ms/board', ms / (2 * N) < 25);
|
||
const a = E.generateBoard({ size: 4, seed: 42 }), b = E.generateBoard({ size: 4, seed: 42 });
|
||
ok('seeded boards are deterministic', JSON.stringify(a.board) === JSON.stringify(b.board) && a.seed === 42);
|
||
const c = E.generateBoard({ size: 4, seed: 43 });
|
||
ok('different seeds differ', JSON.stringify(a.board) !== JSON.stringify(c.board));
|
||
ok('unseeded board reports its seed', Number.isInteger(E.generateBoard({ size: 4 }).seed));
|
||
// quality floor
|
||
let thin = 0;
|
||
for (let i = 0; i < N; i++) { const g = E.generateBoard({ size: 4, seed: 500 + i }); if (g.solutions.filter((s) => s.tier <= 2).length < 20) thin++; }
|
||
ok('few thin boards (<20 common words)', thin <= Math.ceil(N * 0.05), String(thin));
|
||
// Qu boards
|
||
let quSeen = 0, quBad = 0;
|
||
for (let i = 0; i < 400 && quSeen < 6; i++) {
|
||
const g = E.generateBoard({ size: 4, seed: 70000 + i });
|
||
if (!g.board.flat().includes('Qu')) continue;
|
||
quSeen++;
|
||
for (const s of g.solutions.filter((x) => x.word.includes('Q'))) if (!s.word.includes('QU')) quBad++;
|
||
for (const s of g.solutions) { const p = L.findPath(g.board, s.word); if (!p || L.pathWord(g.board, p) !== s.word) quBad++; }
|
||
}
|
||
ok('found Qu boards to test', quSeen > 0);
|
||
ok('Qu words solve + findPath round-trips', quBad === 0, String(quBad));
|
||
}
|
||
|
||
// ── tiers ──────────────────────────────────────────────────────────────────
|
||
section('Tiers');
|
||
{
|
||
for (const w of ['BEE', 'TUB', 'CAT', 'HOUSE', 'TABLES', 'RATED', 'QUEST']) ok(`${w} is everyday`, E.wordTier(w) === 1, String(E.wordTier(w)));
|
||
for (const w of ['ETUI', 'ZOEAE', 'AENEUS', 'FUB']) ok(`${w} is obscure`, E.wordTier(w) === 3, String(E.wordTier(w)));
|
||
ok('non-word → tier 3', E.wordTier('XQZT') === 3);
|
||
ok('isWord', E.isWord('cater') && !E.isWord('catx'));
|
||
}
|
||
|
||
// ── review, summary, hints, goals ─────────────────────────────────────────
|
||
section('Review & practice');
|
||
{
|
||
const g = E.generateBoard({ size: 4, seed: 7 });
|
||
const mine = new Set(g.solutions.filter((s) => s.tier === 1).slice(0, 6).map((s) => s.word));
|
||
const foundBy = new Map([...mine].map((w) => [w, [0]]));
|
||
const groups = L.reviewGroups(g.solutions, foundBy, { minLen: 3 });
|
||
const listed = groups.flatMap((gr) => gr.items.map((i) => i.word));
|
||
ok('review lists every solution once', listed.length === g.solutions.length && new Set(listed).size === listed.length);
|
||
ok('obscure group last and only tier 3', (() => { const o = groups.filter((x) => x.obscure); return o.length <= 1 && (!o.length || (groups[groups.length - 1].obscure && o[0].items.every((i) => i.tier === 3))); })());
|
||
ok('common groups longest first', groups.filter((x) => !x.obscure).every((gr, i, arr) => i === 0 || arr[i - 1].len > gr.len));
|
||
ok('found-by carried', groups.flatMap((x) => x.items).filter((i) => i.by.includes(0)).length === mine.size);
|
||
const g4 = L.reviewGroups(g.solutions, new Map(), { minLen: 4 });
|
||
ok('minLen 4 review drops 3-letter words', g4.flatMap((x) => x.items).every((i) => i.word.length >= 4));
|
||
const sum = L.roundSummary(g.solutions, mine, { minLen: 3 });
|
||
ok('summary counts', sum.total === g.solutions.length && sum.found === mine.size && sum.foundCommon === mine.size);
|
||
ok('summary max score', sum.maxScore === L.sheetScore(g.solutions.map((s) => s.word)));
|
||
ok('summary longest', sum.longest.length === Math.max(...g.solutions.map((s) => s.word.length)));
|
||
const goal = L.practiceGoal(g.solutions, 3);
|
||
const common = g.solutions.filter((s) => s.tier <= 2).length;
|
||
ok('practice goal ≈ 25% of common', goal === Math.max(5, Math.round(common * 0.25)), `${goal} of ${common}`);
|
||
const h = L.pickHint(g.solutions, mine, { minLen: 3, rng: () => 0.3 });
|
||
ok('hint is an unfound common word', h && !mine.has(h.word) && E.wordTier(h.word) <= 2);
|
||
ok('hint prefix is its first two dice', h && L.pathWord(g.board, h.path.slice(0, 2)) === h.prefix, h && `${h.prefix} ${h.word}`);
|
||
const all = new Set(g.solutions.map((s) => s.word));
|
||
ok('no hint when everything is found', L.pickHint(g.solutions, all, {}) === null);
|
||
ok('counts by length', JSON.stringify(L.countsByLength(['CAT', 'DOGS', 'TABLES', 'ABCDEFGHIJ'])) === JSON.stringify({ 3: 1, 4: 1, 6: 1, 8: 1 }));
|
||
}
|
||
|
||
// ── match state, saves, daily ─────────────────────────────────────────────
|
||
section('Match, saves & daily');
|
||
{
|
||
const players = [{ id: 'player', name: 'You', isHuman: true }, { id: 'a', name: 'Ann', skill: 3 }, { id: 'b', name: 'Bob', skill: 5 }];
|
||
const m = L.createMatch({ mode: 'match', rules: { rounds: 3, size: 5 }, players });
|
||
ok('rules normalized', m.rules.size === 5 && m.rules.rounds === 3 && m.rules.timerMs === 180000);
|
||
const res = L.resolveRound([{ found: ['CATER', 'DOG'] }, { found: ['DOG', 'TOP'] }, { found: [] }], m.rules);
|
||
L.commitRound(m, res, [['CATER', 'DOG'], ['DOG', 'TOP'], []]);
|
||
ok('commit adds totals', m.totals.player === res[0].roundScore && m.totals.a === res[1].roundScore);
|
||
ok('history best words', m.history[0].best.player === 'CATER');
|
||
ok('not over after 1 of 3', !L.isMatchOver(m));
|
||
m.round = 2;
|
||
const sig = JSON.stringify({ opp: ['a', 'b'] });
|
||
const raw = L.serialiseSave(m, sig);
|
||
const back = L.parseSave(raw, sig);
|
||
ok('save round-trips', back && JSON.stringify(back.match) === JSON.stringify(m));
|
||
ok('save rejects another table', L.parseSave(raw, JSON.stringify({ opp: ['a'] })) === null);
|
||
ok('save rejects junk', L.parseSave('{oops', sig) === null && L.parseSave(null, sig) === null);
|
||
L.commitRound(m, res, [['CATER', 'DOG'], ['DOG', 'TOP'], []]);
|
||
L.commitRound(m, res, [['CATER', 'DOG'], ['DOG', 'TOP'], []]);
|
||
ok('over after 3 of 3', L.isMatchOver(m));
|
||
ok('finished match not resumable', L.parseSave(L.serialiseSave(m, sig), sig) === null);
|
||
ok('match result', ['win', 'draw', 'loss'].includes(L.matchResult(m)));
|
||
ok('standings sorted', (() => { const s = L.standings(m); return s.every((p, i) => i === 0 || m.totals[s[i - 1].id] >= m.totals[p.id]); })());
|
||
const tie = L.createMatch({ mode: 'match', rules: {}, players });
|
||
ok('all-zero match is a draw', L.matchResult(tie) === 'draw');
|
||
ok('normalize bad timer', L.normalizeRules({ timerMs: 12345 }).timerMs === 180000);
|
||
ok('normalize untimed', L.normalizeRules({ timerMs: 0 }).timerMs === 0);
|
||
// daily
|
||
let d = L.blankDaily();
|
||
d = L.updateDaily(d, '2026-11-28', { score: 10 });
|
||
d = L.updateDaily(d, '2026-11-29', { score: 12 });
|
||
ok('streak grows day by day', d.streak === 2 && d.bestStreak === 2);
|
||
const same = L.updateDaily(d, '2026-11-29', { score: 99 });
|
||
ok('one attempt per day', same.results['2026-11-29'].score === 12 && same.streak === 2);
|
||
d = L.updateDaily(d, '2026-12-02', { score: 5 });
|
||
ok('gap resets streak', d.streak === 1 && d.bestStreak === 2);
|
||
ok('streak shown today/yesterday only', L.dailyStreakNow(d, '2026-12-03') === 1 && L.dailyStreakNow(d, '2026-12-05') === 0);
|
||
ok('daily seed stable + date-specific', L.dailySeed('2026-11-30') === L.dailySeed('2026-11-30') && L.dailySeed('2026-11-30') !== L.dailySeed('2026-12-01'));
|
||
ok('fmtClock', L.fmtClock(180000) === '3:00' && L.fmtClock(9001) === '0:10' && L.fmtClock(0) === '0:00');
|
||
}
|
||
|
||
// ── AI ─────────────────────────────────────────────────────────────────────
|
||
section('AI');
|
||
{
|
||
ok('stem groups inflections', stemOf('RATES') === stemOf('RATE') && stemOf('RATED') === stemOf('RATE') && stemOf('RATER') === stemOf('RATE') && stemOf('CATS') === 'CAT', ['RATE', 'RATES', 'RATED', 'CATS'].map(stemOf).join());
|
||
const fam = familyMap(['RATE', 'RATES', 'TEAR', 'DOG']);
|
||
ok('families: suffix + anagram', fam.get('RATE').includes('RATES') && fam.get('RATE').includes('TEAR') && fam.get('DOG').length === 0);
|
||
|
||
const N = QUICK ? 40 : LADDER ? 400 : 160;
|
||
const boards = Array.from({ length: N }, (_, i) => E.generateBoard({ size: 4, seed: 30000 + i }));
|
||
const stats = {};
|
||
let badSched = 0;
|
||
const mul = (seed) => () => { seed = (seed + 0x6d2b79f5) >>> 0; let t = seed; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||
const finds = {};
|
||
for (let s = 1; s <= 5; s++) {
|
||
stats[s] = { words: 0, pts: 0, obscure: 0, short: 0 };
|
||
finds[s] = boards.map((g, i) => {
|
||
const sched = scheduleFinds(g.solutions, s, 180000, { minLen: 3, rng: mul(i * 7 + s * 1000003) });
|
||
const valid = new Set(g.solutions.map((x) => x.word));
|
||
if (sched.some((x, k) => !valid.has(x.word) || x.atMs < 0 || x.atMs > 180000 || (k && sched[k - 1].atMs > x.atMs))) badSched++;
|
||
if (new Set(sched.map((x) => x.word)).size !== sched.length) badSched++;
|
||
stats[s].words += sched.length;
|
||
stats[s].pts += L.sheetScore(sched.map((x) => x.word));
|
||
stats[s].obscure += sched.filter((x) => E.wordTier(x.word) === 3).length;
|
||
return sched.map((x) => x.word);
|
||
});
|
||
}
|
||
ok('schedules valid, sorted, unique, inside the round', badSched === 0, String(badSched));
|
||
const TARGET = { 1: [5, 13], 2: [9, 18], 3: [14, 26], 4: [20, 36], 5: [28, 50] };
|
||
for (let s = 1; s <= 5; s++) {
|
||
const w = stats[s].words / N;
|
||
console.log(` skill ${s}: ${w.toFixed(1)} words · ${(stats[s].pts / N).toFixed(1)} pts · ${(stats[s].obscure / N).toFixed(1)} obscure`);
|
||
ok(`skill ${s} words in ${TARGET[s]}`, w >= TARGET[s][0] && w <= TARGET[s][1], w.toFixed(1));
|
||
}
|
||
ok('skill 1 finds no obscure words', stats[1].obscure === 0);
|
||
// ladder on mirrored boards (duplicates cancel)
|
||
for (let s = 2; s <= 5; s++) {
|
||
let win = 0;
|
||
for (let i = 0; i < N; i++) {
|
||
const r = L.resolveRound([{ found: finds[s][i] }, { found: finds[s - 1][i] }]);
|
||
win += r[0].roundScore > r[1].roundScore ? 1 : r[0].roundScore === r[1].roundScore ? 0.5 : 0;
|
||
}
|
||
const pct = (win / N) * 100;
|
||
console.log(` ${s} beats ${s - 1}: ${pct.toFixed(0)}%`);
|
||
ok(`ladder ${s} > ${s - 1} (≥70%)`, pct >= 70, pct.toFixed(0));
|
||
}
|
||
// shorter rounds find fewer words; dup cancelling actually happens
|
||
const short = boards.slice(0, 30).reduce((a, g, i) => a + scheduleFinds(g.solutions, 3, 60000, { rng: mul(i + 5) }).length, 0) / 30;
|
||
ok('1-minute rounds find fewer words', short < stats[3].words / N * 0.7, short.toFixed(1));
|
||
let sharedCount = 0;
|
||
for (let i = 0; i < N; i++) sharedCount += L.resolveRound([{ found: finds[3][i] }, { found: finds[4][i] }])[0].shared;
|
||
ok('rivals share some words (cancelling matters)', sharedCount / N >= 3, (sharedCount / N).toFixed(1));
|
||
ok('no AI for empty / untimed', scheduleFinds([], 3, 180000).length === 0 && scheduleFinds(boards[0].solutions, 3, 0).length === 0);
|
||
const min4 = scheduleFinds(boards[0].solutions, 5, 180000, { minLen: 4 });
|
||
ok('AI respects min length', min4.every((x) => x.word.length >= 4));
|
||
}
|
||
|
||
// ── layout ─────────────────────────────────────────────────────────────────
|
||
section('Layout');
|
||
{
|
||
for (const size of [4, 5]) {
|
||
for (let n = 0; n <= 3; n++) {
|
||
const f = Y.furniture(n, size);
|
||
const off = f.filter((r) => r.x < 0 || r.y < 0 || r.x + r.w > Y.W || r.y + r.h > Y.H);
|
||
ok(`on screen (size ${size}, ${n} rivals)`, off.length === 0, off.map((r) => r.name).join());
|
||
const clash = [];
|
||
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) if (Y.overlaps(f[i], f[j])) clash.push(`${f[i].name}/${f[j].name}`);
|
||
ok(`no overlaps (size ${size}, ${n} rivals)`, clash.length === 0, clash.join(' '));
|
||
}
|
||
const g = Y.trayGeom(size);
|
||
const c00 = g.center(0, 0), cnn = g.center(g.n - 1, g.n - 1);
|
||
ok(`tray ${size}: dice inside the frame`, c00.x - g.cube / 2 >= g.rect.x + g.frame && cnn.x + g.cube / 2 <= g.rect.x + g.rect.w - g.frame);
|
||
}
|
||
const cols = Y.scoreColumns(4);
|
||
ok('score columns fit 4 players', cols[0].x >= 0 && cols[3].x + cols[3].w <= Y.W);
|
||
ok('pad rows fit the pad', Y.PAD_LIST.y + Y.PAD_LIST.rows * Y.PAD_LIST.rowH <= Y.PAD_FOOT_Y - 10);
|
||
ok('controls fit between tray and screen bottom', Y.CONTROLS_Y + 28 <= Y.H && Y.CONTROLS_Y - 28 > Y.trayGeom(5).rect.y + Y.trayGeom(5).rect.h);
|
||
}
|
||
|
||
console.log(`\n${pass} passed, ${fail} failed`);
|
||
process.exit(fail ? 1 : 0);
|