// Wordsmith (slug `scrabble`) verifier — rules, generator, soak, skill ladder, layout. // // node tools/verifyWordsmith.js full run (soak 160 games + ladder) // node tools/verifyWordsmith.js --quick fast subset (no ladder) // node tools/verifyWordsmith.js --ladder ladder only, more pairs // // The generator is checked against a slow brute-force reference (the original // whole-board trie DFS) on boards grown from real AI games: same move set, same // scores, every move legal and every word in the dictionary. import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const E = await import(path.join(ROOT, 'src/words/scrabbleEngine.js')); const LG = await import(path.join(ROOT, 'src/games/scrabble/ScrabbleLogic.js')); const T = await import(path.join(ROOT, 'src/games/scrabble/ScrabbleTiles.js')); let LAYOUT = null; try { LAYOUT = await import(path.join(ROOT, 'src/games/scrabble/ScrabbleLayout.js')); } catch { /* optional until built */ } const args = new Set(process.argv.slice(2)); const QUICK = args.has('--quick'); const LADDER_ONLY = args.has('--ladder'); let pass = 0, fail = 0; const fails = []; function check(cond, msg) { if (cond) pass++; else { fail++; fails.push(msg); if (fails.length < 40) console.log(' ✗', msg); } } function section(name) { console.log(`\n── ${name}`); } // ── Dictionary ──────────────────────────────────────────────────────────────── const words = fs.readFileSync(path.join(ROOT, 'data/wordlists/enable1.txt'), 'utf8') .split(/\s+/).map(w => w.trim().toUpperCase()).filter(w => /^[A-Z]{2,15}$/.test(w)); const WORDS = new Set(words); E.initScrabbleDictionary(WORDS); const common = fs.readFileSync(path.join(ROOT, 'data/wordlists/common.txt'), 'utf8').split(/\s+/); const cs = E.initScrabbleCommonWords(common); const isValid = (w) => WORDS.has(w); const rngOf = (seed) => { let a = seed >>> 0 || 1; 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; }; }; const place = (s, r, c, dir = 'across', blanks = []) => [...s].map((ch, i) => ({ row: dir === 'down' ? r + i : r, col: dir === 'across' ? c + i : c, letter: ch, blank: blanks.includes(i), })); if (!LADDER_ONLY) { // ── Tiles + board ─────────────────────────────────────────────────────────── section('tiles + premium layout'); const total = Object.values(T.LETTER_DISTRIBUTION).reduce((a, b) => a + b, 0); check(total === 100, `bag has ${total} tiles (want 100)`); check(T.LETTER_DISTRIBUTION[T.BLANK] === 2, 'two blanks'); const pts = Object.entries(T.LETTER_DISTRIBUTION).reduce((s, [t, n]) => s + n * (T.LETTER_VALUES[t] ?? 0), 0); check(pts === 187, `face value of the set is ${pts} (want 187)`); const count = { TW: 0, DW: 0, TL: 0, DL: 0 }; let sym = true; for (let r = 0; r < 15; r++) for (let c = 0; c < 15; c++) { const p = T.PREMIUM[r][c]; if (p.label) count[p.label]++; for (const [rr, cc] of [[c, r], [14 - r, c], [r, 14 - c]]) if (T.PREMIUM[rr][cc].label !== p.label) sym = false; } check(sym, 'premium layout symmetric (both mirrors + transpose)'); check(count.TW === 8 && count.DW === 17 && count.TL === 12 && count.DL === 24, `premium counts ${JSON.stringify(count)}`); check(T.PREMIUM[7][7].label === 'DW', 'centre is a double word'); // ── Scoring ───────────────────────────────────────────────────────────────── section('scoring'); const B0 = LG.createEmptyBoard(); check(LG.scoreMove(B0, place('CAT', 7, 6)) === 10, 'CAT over the centre = 10'); check(LG.scoreMove(B0, place('CAT', 7, 6, 'across', [0])) === 4, 'blank C scores 0 → 4'); const seven = place('RETAINS', 7, 4); check(LG.scoreMove(B0, seven) === 2 * 7 + 50, `RETAINS opening = 64 (got ${LG.scoreMove(B0, seven)})`); let B1 = LG.applyPlacements(B0, place('CAT', 7, 6)); check(LG.scoreMove(B1, [{ row: 7, col: 9, letter: 'S', blank: false }]) === 6, 'CATS hook: premium under old tiles not re-used (6)'); let B2 = LG.applyPlacements(B0, place('HE', 7, 7)); const ah = LG.scoreMove(B2, [{ row: 6, col: 7, letter: 'A', blank: false }]); check(ah === 5, `AH (A on plain square + H) = 5 (got ${ah})`); // parallel play forming two words const par = LG.scoreMove(B2, [{ row: 8, col: 7, letter: 'O', blank: false }, { row: 8, col: 8, letter: 'X', blank: false }]); // words: OX across (row 8: (8,7)='.'? row 8 '..d...d.d...d..' → col 6 d, col 8 d) O plain, X on DL → 1+16 = 17 // HO down: H4 + O1 = 5 ; EX down: E1 + X(8*2)=17 → total 39 check(par === 39, `parallel OX under HE = 39 (got ${par})`); // ── Move legality ─────────────────────────────────────────────────────────── section('move legality'); const v = (b, pl, first) => LG.validateMove(b, pl, { firstMove: first }); check(!v(B0, place('CAT', 0, 0), true).ok, 'opening must cover the centre'); check(!v(B0, [{ row: 7, col: 7, letter: 'A' }, { row: 8, col: 8, letter: 'B' }], true).ok, 'tiles in one line'); check(!v(B0, [{ row: 7, col: 6, letter: 'A' }, { row: 7, col: 8, letter: 'B' }], true).ok, 'no gaps'); check(v(B1, [{ row: 7, col: 9, letter: 'S' }], false).ok, 'hook connects'); check(!v(B1, place('DOG', 0, 0), false).ok, 'later plays must connect'); check(v(B1, [{ row: 7, col: 5, letter: 'S' }, { row: 7, col: 9, letter: 'S' }], false).ok === true, 'existing tiles bridge a gap'); // ── State machine ────────────────────────────────────────────────────────── section('state machine'); const mk = (rule = 'friendly', seed = 7, n = 2) => LG.createGame( Array.from({ length: n }, (_, i) => ({ name: `P${i}`, kind: i ? 'ai' : 'human', skill: 3 })), { seed, rule }); { const s = mk(); check(s.players.every(p => p.rack.length === 7), 'dealt 7 each'); check(s.bag.length === 86, `bag after deal = 86 (got ${s.bag.length})`); check(LG.tileCensus(s).ok, 'census after deal'); const draws = s.firstDraw.at(-1); const best = Math.min(...draws.map(d => LG.drawRank(d.token))); check(draws.find(d => d.seat === s.firstSeat) && LG.drawRank(draws.find(d => d.seat === s.firstSeat).token) === best, 'nearest-to-A draws first'); check(s.turn === s.firstSeat, 'first drawer starts'); } { // Ties redraw; blank beats A. let blankWins = 0, n = 0; for (let seed = 1; seed < 400; seed++) { const s = mk('friendly', seed, 3); const firstRound = s.firstDraw[0]; if (firstRound.some(d => d.token === T.BLANK) && firstRound.filter(d => d.token === T.BLANK).length === 1) { n++; if (firstRound.find(d => d.token === T.BLANK).seat === s.firstSeat) blankWins++; } if (s.firstDraw.length > 1) { const r0 = s.firstDraw[0]; const b = Math.min(...r0.map(d => LG.drawRank(d.token))); check(r0.filter(d => LG.drawRank(d.token) === b).length > 1, 'redraw only on a tie'); } } check(n > 0 && blankWins === n, `a lone blank always wins the draw (${blankWins}/${n})`); } { // Exchange gating. const s = mk(); const seat = s.turn; s.bag.splice(6); const res = LG.exchangeTiles(s, seat, [s.players[seat].rack[0]]); check(!res.ok, 'exchange refused with 6 in bag'); } { const s = mk(); const seat = s.turn; const before = s.players[seat].rack.slice(); const res = LG.exchangeTiles(s, seat, before.slice(0, 3)); check(res.ok && s.players[seat].rack.length === 7 && s.bag.length === 86 && LG.tileCensus(s).ok, 'exchange 3 keeps counts'); check(s.turn !== seat && s.scoreless === 1, 'exchange ends the turn, scoreless'); } { // Six scoreless turns end the game, each rack docked. const s = mk(); for (let i = 0; i < 6; i++) LG.passTurn(s, s.turn); check(s.over && s.end.reason === 'scoreless', 'six scoreless turns end the game'); check(s.players.every(p => p.score === -LG.rackValue(p.rack)), 'scoreless end docks every rack'); } // Rig a board/rack for challenge tests. const rig = (rule) => { const s = mk(rule, 11); const seat = s.turn; s.bag.push(...s.players[seat].rack); s.players[seat].rack = ['C', 'A', 'T', 'Z', 'Q', 'X', 'J']; for (const t of s.players[seat].rack) s.bag.splice(s.bag.indexOf(t), 1); return { s, seat, other: (seat + 1) % 2 }; }; { const { s, seat } = rig('friendly'); const r = LG.submitPlay(s, seat, place('CAT', 7, 6)); check(r.ok && !r.pending && s.players[seat].score === 10 && s.players[seat].rack.length === 7, 'friendly play commits + draws'); check(LG.tileCensus(s).ok, 'census after play'); } { const { s, seat, other } = rig('double'); const r = LG.submitPlay(s, seat, place('ZAT', 7, 6)); check(r.ok && r.pending, 'challenge rule: play is pending'); const c = LG.challengePending(s, other, isValid); check(c.phony && s.players[seat].rack.length === 7 && LG.isBoardEmpty(s.board) && s.players[seat].score === 0, 'phony comes off, tiles back on rack'); check(s.turn === other && LG.tileCensus(s).ok, 'phony loses the turn; census ok'); } { const { s, seat, other } = rig('double'); LG.submitPlay(s, seat, place('CAT', 7, 6)); const c = LG.challengePending(s, other, isValid); check(!c.phony && s.players[seat].score === 10, 'valid play stands'); check(s.turn === seat && s.log.some(e => e.type === 'lost' && e.seat === other), 'double: failed challenger loses their turn'); } { const { s, seat, other } = rig('five'); LG.submitPlay(s, seat, place('CAT', 7, 6)); LG.challengePending(s, other, isValid); check(s.players[seat].score === 15 && s.turn === other, 'five-point: +5 to the player, challenger keeps turn'); } { // Going out: bag empty, rack empty → bonus = others' racks. const s = mk('friendly', 5); const seat = s.turn, other = (seat + 1) % 2; s.bag.length = 0; s.players[seat].rack = ['C', 'A', 'T']; s.players[other].rack = ['Q', 'Z']; LG.submitPlay(s, seat, place('CAT', 7, 6)); check(s.over && s.end.reason === 'out' && s.end.outSeat === seat, 'going out ends the game'); check(s.players[seat].score === 10 + 20 && s.players[other].score === -20, `out bonus +20 / rack −20 (${s.players[seat].score}/${s.players[other].score})`); } check(LG.overtimePenalty(-1) === 10 && LG.overtimePenalty(-60000) === 10 && LG.overtimePenalty(-60001) === 20 && LG.overtimePenalty(5) === 0, 'overtime: −10 per started minute'); { const s = mk(); const u = LG.unseenFor(s, 0); const n = Object.values(u).reduce((a, b) => a + b, 0); check(n === 93, `unseen at start = 93 (got ${n})`); } // ── Generator vs reference ────────────────────────────────────────────────── section('generator vs brute-force reference'); const REF = buildRefTrie(WORDS); const boards = growBoards(QUICK ? 6 : 16); let compared = 0, slow = 0; const timing = { 0: [], 1: [], 2: [] }; const R = rngOf(99); for (const b of boards) { for (let k = 0; k < (QUICK ? 2 : 3); k++) { const rack = randomRack(R, k === 2 ? 2 : k === 1 ? 1 : 0); const firstMove = LG.isBoardEmpty(b); const t0 = performance.now(); let mine = E.generateMoves(b, rack, { firstMove }); // Openings are generated across only (the board is symmetric); mirror them for the reference. if (firstMove) mine = mine.concat(mine.map(m => ({ ...m, placements: m.placements.map(p => ({ ...p, row: p.col, col: p.row })) }))); timing[rack.filter(t => t === T.BLANK).length].push(performance.now() - t0); const ref = refGenerate(REF, b, rack, firstMove); const key = (pl) => pl.map(p => `${p.row},${p.col},${p.letter},${p.blank ? 1 : 0}`).sort().join('|'); const A = new Map(mine.map(m => [key(m.placements), m.score])); const Bm = new Map(); for (const pl of ref) Bm.set(key(pl), LG.scoreMove(b, pl)); let missing = 0, extra = 0, wrong = 0; for (const [k2, sc] of Bm) { if (!A.has(k2)) missing++; else if (A.get(k2) !== sc) wrong++; } for (const k2 of A.keys()) if (!Bm.has(k2)) extra++; check(!missing && !extra && !wrong, `rack ${rack.join('')}: missing ${missing}, extra ${extra}, wrong score ${wrong} (of ${Bm.size})`); // every generated move legal, words valid, words list right let bad = 0; for (const m of mine) { const res = LG.validateMove(b, m.placements, { firstMove }); if (!res.ok || !res.words.every(w => WORDS.has(w.word))) bad++; else if (res.words.map(w => w.word).sort().join() !== m.words.slice().sort().join()) bad++; } check(bad === 0, `rack ${rack.join('')}: ${bad} illegal/mismatched moves`); compared++; } } const avg = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0); console.log(` compared ${compared} positions; avg ms by blanks: 0→${avg(timing[0]).toFixed(1)} 1→${avg(timing[1]).toFixed(1)} 2→${avg(timing[2]).toFixed(1)}`); check(avg(timing[0]) < 40, `plain-rack generation under 40 ms (avg ${avg(timing[0]).toFixed(1)})`); check(Math.max(0, ...timing[2]) < 600, `two-blank worst case under 600 ms (${Math.max(0, ...timing[2]).toFixed(0)})`); // ── Engine features ───────────────────────────────────────────────────────── section('engine features'); check(cs.common > 10000, `common words loaded (${cs.common})`); check(E.leaveValue(['_', 'S']) > E.leaveValue(['Q', 'V']), 'leave: ?S beats QV'); check(E.leaveValue(['E', 'R', 'S']) > E.leaveValue(['I', 'I', 'U']), 'leave: ERS beats IIU'); const bk = E.bestKeep(['Q', 'V', 'V', 'U', 'I', 'S', 'E']); check(bk.keep.includes('S') && !bk.keep.includes('V'), `bestKeep keeps S, tosses V (${bk.keep.join('')})`); const v1 = E.vocabularyFor(1), v3 = E.vocabularyFor(3), v5 = E.vocabularyFor(5); check(v1.size < v3.size && v3.size < v5.size, `vocab tiers grow (${v1.size} < ${v3.size} < ${v5.size})`); check(!v1.has('XU') && v3.has('XU') && v5.has('XU') && v1.has('OF'), 'XU unknown at skill 1, known at 3+; OF known everywhere'); check([...v1].every(w => WORDS.has(w)), 'tier words are all valid'); check(E.twoLetterWords().length === 96 || E.twoLetterWords().length > 80, `two-letter list (${E.twoLetterWords().length})`); let ph = 0; for (let i = 0; i < 40; i++) if (E.aiWouldChallenge({ words: ['ZOQX'], skill: 5 })) ph++; check(ph === 40, 'skill 5 always challenges a phony'); let fc = 0; for (let i = 0; i < 40; i++) if (E.aiWouldChallenge({ words: ['CAT'], skill: 1 })) fc++; check(fc === 0, 'nobody challenges a common word'); const hint = E.topMoves({ board: LG.createEmptyBoard(), rack: ['C', 'A', 'T', 'S', 'E', 'R', 'O'], firstMove: true, n: 3 }); check(hint.length === 3 && hint[0].score >= 50, `hint finds the opening bingo (${hint[0]?.word} ${hint[0]?.score})`); { // Opening plays sometimes go down (board symmetry). let downs = 0; for (let i = 0; i < 30; i++) { const m = E.chooseMove({ board: LG.createEmptyBoard(), rack: ['C', 'A', 'T', 'S', 'E', 'R', 'O'], skill: 5, firstMove: true, bagCount: 86, rng: rngOf(i + 1) }); if (m.placements.every(p => p.col === m.placements[0].col) && m.placements.length > 1) downs++; check(LG.validateMove(LG.createEmptyBoard(), m.placements, { firstMove: true }).ok, 'opening move legal'); } check(downs > 3 && downs < 27, `openings vary across/down (${downs}/30 down)`); } // ── Soak ──────────────────────────────────────────────────────────────────── section('AI soak'); const games = QUICK ? 24 : 160; let ended = 0, stalls = 0, censusBad = 0, sumBad = 0, illegal = 0, moves = 0, bingos = 0, phonies = 0, challenges = 0; const reasons = {}; const t0 = performance.now(); let worst = 0; for (let g = 0; g < games; g++) { const n = 2 + (g % 3); const rule = ['friendly', 'double', 'five'][g % 3 === 0 ? 0 : (g >> 1) % 3]; const skills = Array.from({ length: n }, (_, i) => 1 + ((g * 7 + i * 3) % 5)); const out = playGame({ seed: 1000 + g, skills, rule, onMove: (ms) => { worst = Math.max(worst, ms); } }); if (out.stalled) stalls++; if (out.state.over) ended++; reasons[out.state.end?.reason ?? 'none'] = (reasons[out.state.end?.reason ?? 'none'] ?? 0) + 1; censusBad += out.censusBad; illegal += out.illegal; moves += out.moves; bingos += out.state.players.reduce((s, p) => s + p.bingos, 0); phonies += out.phonies; challenges += out.challenges; // scores == sum of the log for (const p of out.state.players) { const sum = out.state.log.filter(e => e.seat === p.seat).reduce((s, e) => s + (e.type === 'phony' ? 0 : e.score ?? 0), 0); if (sum !== p.score) sumBad++; } } const secs = (performance.now() - t0) / 1000; console.log(` ${games} games, ${moves} turns in ${secs.toFixed(1)}s; ends ${JSON.stringify(reasons)}; bingos ${bingos}; phonies ${phonies}; challenges ${challenges}; slowest AI turn ${worst.toFixed(0)} ms`); check(ended === games, `every game finished (${ended}/${games})`); check(stalls === 0, `no stalls (${stalls})`); check(censusBad === 0, `tile census always 100 (${censusBad} bad)`); check(sumBad === 0, `scores match the log (${sumBad} bad)`); check(illegal === 0, `AI never proposed an illegal play (${illegal})`); check(worst < 1500, `slowest AI turn under 1.5 s (${worst.toFixed(0)} ms)`); check(bingos > 0, 'bingos happen'); } // ── Ladder ──────────────────────────────────────────────────────────────────── if (!QUICK) { section('skill ladder (mirrored seeds, 2 players)'); const pairs = LADDER_ONLY ? 60 : 24; for (let k = 2; k <= 5; k++) { let wins = 0, games = 0, margin = 0; for (let i = 0; i < pairs; i++) { for (const swap of [false, true]) { const skills = swap ? [k - 1, k] : [k, k - 1]; const out = playGame({ seed: 5000 + k * 1000 + i, skills, rule: 'friendly' }); const hi = swap ? 1 : 0; const a = out.state.players[hi].score, b = out.state.players[1 - hi].score; if (a > b) wins++; else if (a === b) wins += 0.5; margin += a - b; games++; } } const pct = (100 * wins / games).toFixed(0); console.log(` skill ${k} vs ${k - 1}: ${pct}% (avg margin ${(margin / games).toFixed(0)})`); check(wins / games > 0.55, `skill ${k} beats ${k - 1} (${pct}%)`); } } // ── Layout ──────────────────────────────────────────────────────────────────── if (!LADDER_ONLY && LAYOUT?.hudFurniture) { section('layout'); const rects = LAYOUT.hudFurniture(); for (let i = 0; i < rects.length; i++) { const a = rects[i]; check(a.x >= 0 && a.y >= 0 && a.x + a.w <= 1920 && a.y + a.h <= 1080, `${a.name} on screen`); for (let j = i + 1; j < rects.length; j++) { const b = rects[j]; if (a.overlapOk?.includes(b.name) || b.overlapOk?.includes(a.name)) continue; const hit = a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; check(!hit, `${a.name} overlaps ${b.name}`); } } } console.log(`\n${fail ? '✗' : '✓'} ${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0); // ── Helpers ─────────────────────────────────────────────────────────────────── function randomRack(R, blanks) { const bag = LG.createBag().filter(t => t !== T.BLANK); const r = []; for (let i = 0; i < blanks; i++) r.push(T.BLANK); while (r.length < 7) r.push(bag.splice(Math.floor(R() * bag.length), 1)[0]); return r; } // Grow realistic boards from a few AI games, snapshotting at various depths. function growBoards(n) { const out = [LG.createEmptyBoard()]; for (let g = 0; out.length < n; g++) { const res = playGame({ seed: 300 + g, skills: [4, 5], rule: 'friendly', snapshots: [3, 8, 14, 20] }); out.push(...res.snaps); } return out.slice(0, n); } // Play one AI-only game through the real state machine. function playGame({ seed, skills, rule = 'friendly', snapshots = [], onMove = null }) { const R = rngOf(seed * 7 + 3); const st = LG.createGame(skills.map((s, i) => ({ name: `AI${i}`, kind: 'ai', skill: s })), { seed, rule }); let censusBad = 0, illegal = 0, moves = 0, stalled = false, phonies = 0, challenges = 0; const snaps = []; for (let turn = 0; !st.over; turn++) { if (turn > 400) { stalled = true; break; } const p = st.players[st.turn]; const n = st.players.length; const oppRacks = st.bag.length === 0 && n === 2 ? [st.players[(st.turn + 1) % 2].rack.slice()] : null; const t0 = performance.now(); const m = E.chooseMove({ board: LG.plainBoard(st.board), rack: p.rack.slice(), skill: p.skill, firstMove: LG.isFirstMove(st), bagCount: st.bag.length, rule: st.rule, oppRacks, rng: R, }); onMove?.(performance.now() - t0); moves++; if (m.type === 'play') { const r = LG.submitPlay(st, st.turn, m.placements); if (!r.ok) { illegal++; LG.passTurn(st, st.turn); continue; } if (m.phony) phonies++; if (r.pending) { // Each other player may challenge (first one who wants to). const words = st.pending.words; let challenger = null; for (let k = 1; k < n && challenger == null; k++) { const seat = (st.pending.seat + k) % n; if (E.aiWouldChallenge({ words, skill: st.players[seat].skill, score: st.pending.score, rng: R })) challenger = seat; } if (challenger != null) { challenges++; LG.challengePending(st, challenger, isValid); } else LG.acceptPending(st); } else if (rule === 'friendly' && !m.words.every(w => WORDS.has(w))) illegal++; } else if (m.type === 'exchange') { const r = LG.exchangeTiles(st, st.turn, m.tiles); if (!r.ok) LG.passTurn(st, st.turn); } else { LG.passTurn(st, st.turn); } if (!LG.tileCensus(st).ok) censusBad++; if (snapshots.includes(moves) && !st.over) snaps.push(LG.plainBoard(st.board)); } return { state: st, censusBad, illegal, moves, stalled, snaps, phonies, challenges }; } // The original whole-board DFS, kept here as the reference implementation. function buildRefTrie(set) { const root = { children: Object.create(null), terminal: false }; for (const w of set) { let node = root; for (const ch of w) node = node.children[ch] || (node.children[ch] = { children: Object.create(null), terminal: false }); node.terminal = true; } return root; } function refGenerate(TRIE, board, rack, firstMove) { const LET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); const counts = Object.create(null); for (const t of rack) counts[t] = (counts[t] ?? 0) + 1; const take = (L) => { if (counts[L] > 0) { counts[L]--; return { token: L, blank: false }; } if (counts[T.BLANK] > 0) { counts[T.BLANK]--; return { token: T.BLANK, blank: true }; } return null; }; const give = (t) => { counts[t.token]++; }; const cache = new Map(); const cross = (r, c, cdr, cdc) => { const key = `${r},${c},${cdr}`; if (cache.has(key)) return cache.get(key); let pre = '', rr = r - cdr, cc = c - cdc; while (board[rr]?.[cc]) { pre = board[rr][cc].letter + pre; rr -= cdr; cc -= cdc; } let suf = ''; rr = r + cdr; cc = c + cdc; while (board[rr]?.[cc]) { suf += board[rr][cc].letter; rr += cdr; cc += cdc; } let res = null; if (pre || suf) { res = new Set(); for (const L of LET) if (WORDS.has(pre + L + suf)) res.add(L); } cache.set(key, res); return res; }; const moves = []; const seen = new Set(); const dfs = (R0, C0, node, placed, usedExisting, touched, mdr, mdc, cdr, cdc) => { const inB = R0 >= 0 && C0 >= 0 && R0 < 15 && C0 < 15; const cell = inB ? board[R0][C0] : undefined; if (inB && cell) { const ch = node.children[cell.letter]; if (ch) dfs(R0 + mdr, C0 + mdc, ch, placed, true, touched, mdr, mdc, cdr, cdc); return; } if (node.terminal && placed.length > 0) { const ok = firstMove ? placed.some(p => p.row === 7 && p.col === 7) : (usedExisting || touched); if (ok) { const k = placed.map(p => `${p.row},${p.col},${p.letter},${p.blank ? 1 : 0}`).sort().join('|'); // the main word must be ≥2 letters; single tiles are legal only if they form a word const res = LG.validateMove(board, placed, { firstMove }); if (!seen.has(k) && res.ok) { seen.add(k); moves.push(placed.slice()); } } } if (!inB) return; const cc = cross(R0, C0, cdr, cdc); for (const L in node.children) { if (cc && !cc.has(L)) continue; const t = take(L); if (!t) continue; placed.push({ row: R0, col: C0, letter: L, blank: t.blank }); dfs(R0 + mdr, C0 + mdc, node.children[L], placed, usedExisting, touched || cc !== null, mdr, mdc, cdr, cdc); placed.pop(); give(t); } }; for (let r = 0; r < 15; r++) for (let c = 0; c < 15; c++) { if (!board[r][c - 1]) dfs(r, c, TRIE, [], false, false, 0, 1, 1, 0); if (!board[r - 1]?.[c]) dfs(r, c, TRIE, [], false, false, 1, 0, 0, 1); } // Every word formed must be valid (the ref only cross-checks placed tiles). return moves.filter(pl => LG.validateMove(board, pl, { firstMove }).words.every(w => WORDS.has(w.word))); }