Rename Scrabble to Wordsmith and rebuild the game as a Reading Room table

- New baked-canvas art (ScrabbleArt), HUD (score sheet, tile tracker, seats, preview tag), dialogs, end screen with coach review, Web Audio SFX, and layout constants replace the old flat Phaser scene
- Split rules into a JSON-safe state machine in ScrabbleLogic (seeded RNG for resumable saves) plus challenge-rule modes (friendly / double / five-point)
- Rewrite the move engine: anchor-based generator with incremental scoring, skill-tiered vocabularies, leave-value equity, plausible phonies, and challenge judgement; add hint, judge, two-letter, and AI-challenge routes
- Add a verifier (tools/verifyWordsmith.js) that soaks full games, checks the generator against a brute-force reference, runs a skill ladder, and validates layout overlap
This commit is contained in:
Brian Fertig 2026-11-26 12:33:07 -07:00
parent 0a421a3392
commit 14f098e3f1
No known key found for this signature in database
18 changed files with 4631 additions and 1029 deletions

Binary file not shown.

Binary file not shown.

View File

@ -625,7 +625,10 @@
"citySheet": "mayan",
"bio": "Mystical Powers and a knack for games.",
"voice": "Antonio Bandaras",
"convo": [],
"convo": [
"brad",
"jerry"
],
"speech": {
"intro": [
"balam-intro-01",

View File

@ -50,7 +50,7 @@ registerGame({ slug: 'dominion', name: 'Dominion', category: 'cards', cardGame:
registerGame({ slug: 'checkers', name: 'Checkers', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 20, defaultPlayfield: 'cherry' });
registerGame({ slug: 'chess', name: 'Chess', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 21, defaultPlayfield: 'dark' });
registerGame({ slug: 'wordle', name: 'Wordle Race', category: 'word', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 22 });
registerGame({ slug: 'scrabble', name: 'Scrabble', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 23 });
registerGame({ slug: 'scrabble', name: 'Wordsmith', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 23 });
registerGame({ slug: 'ghost', name: 'Ghost', category: 'word', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 24 });
registerGame({ slug: 'wordladder', name: 'Word Ladder', category: 'word', minPlayers: 1, maxPlayers: 2, minOpponents: 0, maxOpponents: 1, iconFrame: 25 });
registerGame({ slug: 'wordsearch', name: 'Word Search', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 26 });

View File

@ -1,30 +1,51 @@
// Thin client wrapper around the server move generator. The heavy lifting (the
// dictionary trie + anchor/cross-check search) lives in server/words/scrabbleEngine.js;
// here we just ship the board + rack and pace the AI so turns feel deliberate.
// Wordsmith AI client: thin wrappers over the in-browser word routes
// (src/words/scrabbleEngine.js does the work) plus opponent pacing.
import { api } from '../../services/api.js';
import { aiTiming } from '../../ui/cardtable/AITiming.js';
// Ask the server for this AI's move. Resolves to:
// { type:'play', placements, score, word } | { type:'exchange', tiles } | { type:'pass' }
export async function requestAIMove({ board, rack, skill, firstMove, bagCount }) {
// → { type:'play', placements, score, word, words, phony } | { type:'exchange', tiles } | { type:'pass' }
export async function requestAIMove(args) {
try {
return await api.post('/words/scrabble/ai-move', { board, rack, skill, firstMove, bagCount });
return await api.post('/words/scrabble/ai-move', args);
} catch (err) {
console.error('[scrabble] ai-move request failed:', err);
console.error('[wordsmith] ai-move request failed:', err);
return { type: 'pass' };
}
}
// "Thinking" pause before the AI commits, in ms. Stronger players act faster.
const THINK_DELAY = {
1: [2200, 3600],
2: [1800, 3000],
3: [1400, 2400],
4: [1000, 1800],
5: [700, 1300],
};
export function nextThinkDelay(skill) {
const [min, max] = THINK_DELAY[skill] ?? THINK_DELAY[3];
return min + Math.random() * (max - min);
export async function requestHint(args) {
try {
return (await api.post('/words/scrabble/hint', args)).moves ?? [];
} catch { return []; }
}
export async function judgeWords(words) {
try {
return await api.post('/words/scrabble/judge', { words });
} catch { return { results: words.map(word => ({ word, valid: true })), valid: true }; }
}
export async function aiChallenges(words, skill, score) {
try {
return !!(await api.post('/words/scrabble/ai-challenge', { words, skill, score })).challenge;
} catch { return false; }
}
export async function twoLetterList() {
try { return (await api.get('/words/scrabble/two-letter')).words ?? []; } catch { return []; }
}
// "Thinking" pause before an AI commits. Weaker players mull longer; the table
// pace (relaxed / normal / fast) scales everything.
const THINK = { 1: [2000, 3200], 2: [1700, 2800], 3: [1300, 2200], 4: [1000, 1700], 5: [800, 1300] };
export function nextThinkDelay(skill, pace = 1) {
const [min, max] = THINK[skill] ?? THINK[3];
return (min + Math.random() * (max - min)) * pace;
}
/** Per-tile pacing for laying a play down (ms). */
export function layTiming(skill, pace = 1) {
const t = aiTiming(skill, pace, { think: 500, between: 240, reach: 170, carry: 230, hesitate: 220 });
return { perTile: Math.max(150, Math.min(420, t.carry)), settle: 260 * pace };
}

View File

@ -0,0 +1,725 @@
// Wordsmith art — the Reading Room, baked to canvases (no image files).
//
// wsm-room 1920×1080 oak library table, bookshelf band, lamp pool
// wsm-board-<l>-<p> the walnut-framed board (labels full|short, patterns 0|1)
// wsm-tile-0…7 maple tile faces, each a different grain
// wsm-back a tile back (opponent racks)
// wsm-rack the felt-lined rack in front of you
// wsm-orack an opponent's rack, seen from behind
// wsm-bag the velvet drawstring bag
// wsm-dict the dictionary on the table
// wsm-sheet-<n> the clipboard score sheet for n players
// wsm-track the tile-tracker card
// wsm-card the reference card / modal paper
// wsm-seat, wsm-hplate leather seat plates
//
// Premium squares use an original palette (green leather, ochre, plum, teal),
// not the familiar commercial colours. Also exports makeTile and LibButton.
import * as Phaser from 'phaser';
import { canvas, rr, noisePattern, ensureLeatherPanel } from '../../ui/casino/CasinoArt.js';
import { BOARD_SIZE, PREMIUM, CENTER, LETTER_VALUES, BLANK } from './ScrabbleTiles.js';
import {
W, H, SHELF_H, SQ, GRID, FRAME, BOARD, BOARD_PX, RACK, SHEET, TRACKER, BAG, DICT, SEAT, HUMAN,
} from './ScrabbleLayout.js';
export const SERIF = 'Georgia, "Times New Roman", "Liberation Serif", "DejaVu Serif", serif';
export const SANS = '"Trebuchet MS", Verdana, "DejaVu Sans", Arial, sans-serif';
export const HAND = '"YummyCupcakes", "Comic Sans MS", cursive';
export const INK = '#2b1e12';
export const INK_N = 0x2b1e12;
export const PENCIL = '#4a4f58';
export const GOLD = '#e2c378';
export const GOLD_N = 0xe2c378;
export const CREAM = '#f4ead2';
export const RED_INK = '#9b2f25';
export const GREEN_N = 0x28503f;
export const PREMIUM_STYLE = {
TW: { fill: '#28503f', dark: '#173126', ink: '#ecd38a', full: ['TRIPLE', 'WORD'], short: '3W', name: 'Triple word' },
DW: { fill: '#b9733a', dark: '#7d4a22', ink: '#fff1d8', full: ['DOUBLE', 'WORD'], short: '2W', name: 'Double word' },
TL: { fill: '#5a3a68', dark: '#3a2445', ink: '#f2e4f6', full: ['TRIPLE', 'LETTER'], short: '3L', name: 'Triple letter' },
DL: { fill: '#6e9c97', dark: '#4a6f6a', ink: '#f6fffd', full: ['DOUBLE', 'LETTER'], short: '2L', name: 'Double letter' },
};
export const TILE_PX = 64;
export const GRAINS = 8;
let seed = 1;
const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
const jit = (a) => (rnd() - 0.5) * 2 * a;
const font = (px, weight = '', family = SERIF) => `${weight ? `${weight} ` : ''}${px}px ${family}`;
// ── Painters ──────────────────────────────────────────────────────────────────
function woodGrain(ctx, x, y, w, h, { base = ['#7a4e2c', '#5e3a1f'], line = 'rgba(40,20,8,', lines = 40, alpha = 0.18, vertical = false } = {}) {
const g = vertical ? ctx.createLinearGradient(x, y, x + w, y) : ctx.createLinearGradient(x, y, x, y + h);
g.addColorStop(0, base[0]);
g.addColorStop(1, base[1]);
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
ctx.save();
ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
for (let i = 0; i < lines; i++) {
ctx.strokeStyle = `${line}${(alpha * (0.4 + rnd() * 0.8)).toFixed(3)})`;
ctx.lineWidth = 0.6 + rnd() * 1.6;
ctx.beginPath();
if (vertical) {
const x0 = x + rnd() * w, amp = 2 + rnd() * 6, f = 0.004 + rnd() * 0.01, ph = rnd() * 6;
for (let yy = y; yy <= y + h; yy += 8) ctx.lineTo(x0 + Math.sin(yy * f + ph) * amp, yy);
} else {
const y0 = y + rnd() * h, amp = 2 + rnd() * 6, f = 0.004 + rnd() * 0.01, ph = rnd() * 6;
for (let xx = x; xx <= x + w; xx += 8) ctx.lineTo(xx, y0 + Math.sin(xx * f + ph) * amp);
}
ctx.stroke();
}
// a knot or two
for (let k = 0; k < Math.max(1, Math.round(w * h / 400000)); k++) {
const kx = x + rnd() * w, ky = y + rnd() * h;
for (let i = 0; i < 6; i++) {
ctx.strokeStyle = `${line}${(alpha * 0.7).toFixed(3)})`;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.ellipse(kx, ky, 4 + i * 5, 2 + i * 2, 0, 0, Math.PI * 2);
ctx.stroke();
}
}
ctx.fillStyle = noisePattern(ctx, 128, 14);
ctx.fillRect(x, y, w, h);
ctx.restore();
}
function bakeRoom(scene) {
seed = 4242;
const c = canvas(W, H);
const ctx = c.getContext('2d');
// Oak table planks
const plankH = 136;
for (let y = SHELF_H - 10, i = 0; y < H; y += plankH, i++) {
const tone = i % 2 ? ['#6f4728', '#5a3820'] : ['#77502e', '#603d22'];
woodGrain(ctx, 0, y, W, plankH, { base: tone, lines: 60, alpha: 0.2 });
ctx.fillStyle = 'rgba(20,10,4,0.55)';
ctx.fillRect(0, y, W, 2);
ctx.fillStyle = 'rgba(255,220,170,0.06)';
ctx.fillRect(0, y + 2, W, 1);
// butt joints
for (let k = 0; k < 2; k++) {
const jx = ((i * 577 + k * 911) % W);
ctx.fillStyle = 'rgba(20,10,4,0.4)';
ctx.fillRect(jx, y, 2, plankH);
}
}
// Bookshelf band
woodGrain(ctx, 0, 0, W, SHELF_H, { base: ['#2a1a10', '#1b100a'], lines: 20, alpha: 0.25 });
const SPINES = ['#5b1f24', '#28402f', '#2b3550', '#6b4a22', '#4a2238', '#3a3a2a', '#7a2e1f', '#1f3a3e', '#5e5132'];
for (let x = 6; x < W - 6;) {
const w = 14 + Math.floor(rnd() * 22), h = 38 + Math.floor(rnd() * 18);
if (x > 760 && x < 1160) { x += w; continue; } // the title plaque sits here
const col = SPINES[Math.floor(rnd() * SPINES.length)];
const lean = rnd() < 0.06 ? 3 : 0;
ctx.save();
ctx.translate(x, SHELF_H - 6);
ctx.rotate(lean * Math.PI / 180);
const g = ctx.createLinearGradient(0, 0, w, 0);
g.addColorStop(0, 'rgba(0,0,0,0.35)');
g.addColorStop(0.3, col);
g.addColorStop(0.7, col);
g.addColorStop(1, 'rgba(0,0,0,0.45)');
ctx.fillStyle = col;
ctx.fillRect(0, -h, w - 1, h);
ctx.fillStyle = g;
ctx.fillRect(0, -h, w - 1, h);
ctx.fillStyle = 'rgba(226,195,120,0.55)';
ctx.fillRect(1, -h + 6, w - 3, 1.5);
ctx.fillRect(1, -h + 9, w - 3, 1);
ctx.fillRect(1, -10, w - 3, 1.5);
if (w > 22 && rnd() < 0.5) { ctx.fillStyle = 'rgba(226,195,120,0.45)'; ctx.fillRect(w / 2 - 4, -h / 2 - 5, 7, 10); }
ctx.restore();
x += w + (rnd() < 0.1 ? 6 : 0);
}
// shelf lip
ctx.fillStyle = '#3e2615';
ctx.fillRect(0, SHELF_H - 6, W, 8);
ctx.fillStyle = 'rgba(255,220,170,0.18)';
ctx.fillRect(0, SHELF_H - 6, W, 1.5);
const sh = ctx.createLinearGradient(0, SHELF_H + 2, 0, SHELF_H + 40);
sh.addColorStop(0, 'rgba(0,0,0,0.55)');
sh.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = sh;
ctx.fillRect(0, SHELF_H + 2, W, 38);
// Title plaque
const px = 790, pw = 340, py = 6, ph = 52;
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 8; ctx.shadowOffsetY = 3;
rr(ctx, px, py, pw, ph, 8);
const bg = ctx.createLinearGradient(0, py, 0, py + ph);
bg.addColorStop(0, '#d9b968'); bg.addColorStop(0.5, '#b88d3c'); bg.addColorStop(1, '#8a6526');
ctx.fillStyle = bg; ctx.fill();
ctx.restore();
rr(ctx, px + 5, py + 5, pw - 10, ph - 10, 5);
ctx.strokeStyle = 'rgba(60,36,10,0.7)'; ctx.lineWidth = 1.5; ctx.stroke();
for (const sx of [px + 14, px + pw - 14]) {
ctx.fillStyle = '#6e4e1c'; ctx.beginPath(); ctx.arc(sx, py + ph / 2, 4, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(255,240,200,0.6)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(sx - 2.5, py + ph / 2); ctx.lineTo(sx + 2.5, py + ph / 2); ctx.stroke();
}
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = font(30, 'bold');
ctx.fillStyle = 'rgba(255,245,215,0.5)';
ctx.fillText('W O R D S M I T H', px + pw / 2, py + ph / 2 + 2);
ctx.fillStyle = '#3a2410';
ctx.fillText('W O R D S M I T H', px + pw / 2, py + ph / 2 + 1);
// Lamp pool + vignette
const lamp = ctx.createRadialGradient(BOARD.cx, BOARD.cy, 80, BOARD.cx, BOARD.cy, 1100);
lamp.addColorStop(0, 'rgba(255,214,150,0.26)');
lamp.addColorStop(0.45, 'rgba(255,214,150,0.08)');
lamp.addColorStop(1, 'rgba(255,214,150,0)');
ctx.fillStyle = lamp; ctx.fillRect(0, 0, W, H);
const vig = ctx.createRadialGradient(BOARD.cx, BOARD.cy, 420, BOARD.cx, BOARD.cy, 1250);
vig.addColorStop(0, 'rgba(0,0,0,0)');
vig.addColorStop(1, 'rgba(0,0,0,0.62)');
ctx.fillStyle = vig; ctx.fillRect(0, 0, W, H);
// Soft contact shadows under the furniture that sits on the table
const soft = (x, y, w, h, a = 0.4, r = 14) => {
ctx.save(); ctx.shadowColor = `rgba(0,0,0,${a})`; ctx.shadowBlur = 22; ctx.shadowOffsetY = 8;
ctx.fillStyle = `rgba(0,0,0,${a * 0.6})`; rr(ctx, x, y, w, h, r); ctx.fill(); ctx.restore();
};
soft(SHEET.x - 10, SHEET.y - 10, SHEET.w + 20, SHEET.h + 22, 0.45);
soft(TRACKER.x + 4, TRACKER.y + 4, TRACKER.w - 8, TRACKER.h - 8, 0.35);
soft(RACK.cx - RACK.w / 2, RACK.cy - RACK.h / 2 + 10, RACK.w, RACK.h - 10, 0.5);
soft(DICT.x - DICT.w / 2 + 4, DICT.y - DICT.h / 2 + 4, DICT.w - 8, DICT.h - 8, 0.5);
// Pencil lying by the score sheet
ctx.save();
ctx.translate(SHEET.x - 30, SHEET.y + SHEET.h - 40);
ctx.rotate(-1.2);
ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(4, 6, 170, 12);
ctx.fillStyle = '#d8a634'; ctx.fillRect(0, 0, 150, 12);
ctx.fillStyle = 'rgba(255,255,255,0.25)'; ctx.fillRect(0, 2, 150, 2);
ctx.fillStyle = '#b9b2a2'; ctx.fillRect(150, 0, 12, 12);
ctx.fillStyle = '#c56a6a'; ctx.fillRect(162, 0, 12, 12);
ctx.fillStyle = '#e7cfa2'; ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(-18, 6); ctx.lineTo(0, 12); ctx.fill();
ctx.fillStyle = '#333'; ctx.beginPath(); ctx.moveTo(-12, 4); ctx.lineTo(-18, 6); ctx.lineTo(-12, 8); ctx.fill();
ctx.restore();
scene.textures.addCanvas('wsm-room', c);
}
const BOARD_PAD = 26; // shadow margin around the board texture
function bakeBoard(scene, key, { labels = 'full', patterns = false } = {}) {
seed = 777;
const S = BOARD_PX + BOARD_PAD * 2;
const c = canvas(S, S);
const ctx = c.getContext('2d');
const o = BOARD_PAD;
// drop shadow
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 26; ctx.shadowOffsetY = 10;
rr(ctx, o, o, BOARD_PX, BOARD_PX, 16);
ctx.fillStyle = '#2a170c'; ctx.fill();
ctx.restore();
// walnut frame
ctx.save();
rr(ctx, o, o, BOARD_PX, BOARD_PX, 16); ctx.clip();
woodGrain(ctx, o, o, BOARD_PX, BOARD_PX, { base: ['#4a2c18', '#2f1b0e'], lines: 90, alpha: 0.3 });
ctx.restore();
rr(ctx, o + 1, o + 1, BOARD_PX - 2, BOARD_PX - 2, 15);
ctx.strokeStyle = 'rgba(255,220,170,0.22)'; ctx.lineWidth = 2; ctx.stroke();
rr(ctx, o + FRAME - 6, o + FRAME - 6, GRID + 12, GRID + 12, 6);
ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.lineWidth = 3; ctx.stroke();
ctx.strokeStyle = 'rgba(226,195,120,0.5)'; ctx.lineWidth = 1; ctx.stroke();
// brass corner caps
for (const [cx, cy, a] of [[o, o, 0], [o + BOARD_PX, o, 1], [o + BOARD_PX, o + BOARD_PX, 2], [o, o + BOARD_PX, 3]]) {
ctx.save();
ctx.translate(cx, cy); ctx.rotate(a * Math.PI / 2);
const g = ctx.createLinearGradient(0, 0, 40, 40);
g.addColorStop(0, '#f0d58a'); g.addColorStop(0.5, '#b88d3c'); g.addColorStop(1, '#7a5520');
ctx.fillStyle = g;
ctx.beginPath(); ctx.moveTo(4, 4); ctx.lineTo(44, 4); ctx.quadraticCurveTo(20, 10, 10, 20); ctx.quadraticCurveTo(6, 30, 4, 44); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#6e4e1c'; ctx.beginPath(); ctx.arc(13, 13, 2.6, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
// grid bed
const gx = o + FRAME, gy = o + FRAME;
ctx.fillStyle = '#7c6446';
ctx.fillRect(gx, gy, GRID, GRID);
for (let r = 0; r < BOARD_SIZE; r++) {
for (let col = 0; col < BOARD_SIZE; col++) {
const x = gx + col * SQ, y = gy + r * SQ;
const prem = PREMIUM[r][col];
const st = PREMIUM_STYLE[prem.label];
const inset = 2.5;
const wx = x + inset, wy = y + inset, ww = SQ - inset * 2;
// the well
if (st) {
const g = ctx.createLinearGradient(wx, wy, wx + ww, wy + ww);
g.addColorStop(0, st.dark); g.addColorStop(0.25, st.fill); g.addColorStop(1, st.fill);
ctx.fillStyle = g;
} else {
const g = ctx.createLinearGradient(wx, wy, wx + ww, wy + ww);
g.addColorStop(0, '#cdbb93'); g.addColorStop(0.3, '#e3d4ae'); g.addColorStop(1, '#e8dab7');
ctx.fillStyle = g;
}
ctx.fillRect(wx, wy, ww, ww);
ctx.fillStyle = noisePattern(ctx, 64, st ? 18 : 10);
ctx.fillRect(wx, wy, ww, ww);
// inner shadow (the well is recessed below the ridges)
ctx.fillStyle = 'rgba(0,0,0,0.28)';
ctx.fillRect(wx, wy, ww, 2); ctx.fillRect(wx, wy, 2, ww);
ctx.fillStyle = 'rgba(255,245,220,0.18)';
ctx.fillRect(wx, wy + ww - 1, ww, 1); ctx.fillRect(wx + ww - 1, wy, 1, ww);
if (st) {
// tooled border
ctx.strokeStyle = 'rgba(236,211,138,0.45)'; ctx.lineWidth = 0.8;
ctx.strokeRect(wx + 3.5, wy + 3.5, ww - 7, ww - 7);
if (patterns) {
ctx.save(); ctx.beginPath(); ctx.rect(wx + 4, wy + 4, ww - 8, ww - 8); ctx.clip();
ctx.strokeStyle = 'rgba(255,255,255,0.16)'; ctx.lineWidth = 1;
const word = prem.wordMult > 1, step = prem.label[0] === 'T' ? 6 : 9;
if (word) for (let k = -ww; k < ww * 2; k += step) { ctx.beginPath(); ctx.moveTo(wx + k, wy); ctx.lineTo(wx + k - ww, wy + ww); ctx.stroke(); }
else for (let yy = wy + 5; yy < wy + ww; yy += step) for (let xx = wx + 5; xx < wx + ww; xx += step) { ctx.fillStyle = 'rgba(255,255,255,0.2)'; ctx.fillRect(xx, yy, 1.6, 1.6); }
ctx.restore();
}
const isCenter = r === CENTER && col === CENTER;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
if (isCenter) {
drawFleuron(ctx, x + SQ / 2, y + SQ / 2, 15, st.ink);
} else if (labels === 'short') {
ctx.font = font(17, 'bold', SANS);
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.fillText(st.short, x + SQ / 2, y + SQ / 2 + 1.5);
ctx.fillStyle = st.ink;
ctx.fillText(st.short, x + SQ / 2, y + SQ / 2);
} else {
ctx.font = font(9.5, 'bold', SANS);
ctx.fillStyle = st.ink;
ctx.fillText(st.full[0], x + SQ / 2, y + SQ / 2 - 6);
ctx.fillText(st.full[1], x + SQ / 2, y + SQ / 2 + 6);
}
}
}
}
// raised ridges between the wells
for (let i = 0; i <= BOARD_SIZE; i++) {
const p = i * SQ;
ctx.fillStyle = 'rgba(255,236,200,0.16)';
ctx.fillRect(gx + p - 1.5, gy, 1, GRID);
ctx.fillRect(gx, gy + p - 1.5, GRID, 1);
}
scene.textures.addCanvas(key, c);
}
function drawFleuron(ctx, x, y, r, color) {
ctx.save();
ctx.translate(x, y);
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.beginPath();
for (let i = 0; i < 16; i++) {
const a = (i / 16) * Math.PI * 2 - Math.PI / 2, rr2 = i % 2 ? r * 0.42 : (i % 4 ? r * 0.7 : r);
ctx.lineTo(Math.cos(a) * rr2 + 1, Math.sin(a) * rr2 + 1.5);
}
ctx.closePath(); ctx.fill();
ctx.fillStyle = color;
ctx.beginPath();
for (let i = 0; i < 16; i++) {
const a = (i / 16) * Math.PI * 2 - Math.PI / 2, rr2 = i % 2 ? r * 0.42 : (i % 4 ? r * 0.7 : r);
ctx.lineTo(Math.cos(a) * rr2, Math.sin(a) * rr2);
}
ctx.closePath(); ctx.fill();
ctx.fillStyle = '#b9733a';
ctx.beginPath(); ctx.arc(0, 0, r * 0.2, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
function bakeTiles(scene) {
for (let g = 0; g < GRAINS; g++) {
seed = 1000 + g * 97;
const S = TILE_PX;
const c = canvas(S, S);
const ctx = c.getContext('2d');
rr(ctx, 1, 1, S - 2, S - 2, 7);
ctx.save(); ctx.clip();
const tones = [['#f0dba8', '#e1c48a'], ['#ecd49d', '#dcbd82'], ['#f2dfb0', '#e3c891'], ['#e9cf96', '#d8b87c']];
woodGrain(ctx, 0, 0, S, S, { base: tones[g % tones.length], line: 'rgba(120,80,30,', lines: 9 + (g % 3) * 3, alpha: 0.16 + (g % 4) * 0.03, vertical: g % 2 === 1 });
// bevel
const hl = ctx.createLinearGradient(0, 0, S, S);
hl.addColorStop(0, 'rgba(255,250,235,0.55)');
hl.addColorStop(0.18, 'rgba(255,250,235,0)');
hl.addColorStop(0.82, 'rgba(90,55,20,0)');
hl.addColorStop(1, 'rgba(90,55,20,0.45)');
ctx.fillStyle = hl; ctx.fillRect(0, 0, S, S);
ctx.restore();
rr(ctx, 1, 1, S - 2, S - 2, 7);
ctx.strokeStyle = 'rgba(110,70,30,0.55)'; ctx.lineWidth = 1.5; ctx.stroke();
rr(ctx, 3.5, 3.5, S - 7, S - 7, 5);
ctx.strokeStyle = 'rgba(255,250,232,0.35)'; ctx.lineWidth = 1; ctx.stroke();
scene.textures.addCanvas(`wsm-tile-${g}`, c);
}
// tile back
seed = 555;
const c = canvas(40, 40);
const ctx = c.getContext('2d');
rr(ctx, 1, 1, 38, 38, 5); ctx.save(); ctx.clip();
woodGrain(ctx, 0, 0, 40, 40, { base: ['#c9a36a', '#a8814c'], line: 'rgba(80,50,20,', lines: 8, alpha: 0.2 });
ctx.restore();
rr(ctx, 1, 1, 38, 38, 5); ctx.strokeStyle = 'rgba(70,40,15,0.6)'; ctx.lineWidth = 1.2; ctx.stroke();
scene.textures.addCanvas('wsm-back', c);
// soft tile shadow
const s = canvas(84, 84);
const sx = s.getContext('2d');
sx.shadowColor = 'rgba(0,0,0,0.75)'; sx.shadowBlur = 8;
sx.fillStyle = 'rgba(0,0,0,0.55)';
rr(sx, 12, 12, 60, 60, 8); sx.fill();
scene.textures.addCanvas('wsm-tshadow', s);
}
function bakeRack(scene) {
seed = 31;
const w = RACK.w, h = RACK.h;
const c = canvas(w, h + 10);
const ctx = c.getContext('2d');
// back lip
rr(ctx, 6, 4, w - 12, 30, 8); ctx.save(); ctx.clip();
woodGrain(ctx, 0, 0, w, 40, { base: ['#4e301a', '#3a2212'], lines: 18, alpha: 0.3 });
ctx.restore();
// felt groove
const fg = ctx.createLinearGradient(0, 26, 0, h - 26);
fg.addColorStop(0, '#173126'); fg.addColorStop(1, '#244a39');
ctx.fillStyle = fg;
ctx.fillRect(10, 26, w - 20, h - 46);
ctx.fillStyle = noisePattern(ctx, 64, 24);
ctx.fillRect(10, 26, w - 20, h - 46);
// front lip (closest to you)
rr(ctx, 0, h - 30, w, 34, 10); ctx.save(); ctx.clip();
woodGrain(ctx, 0, h - 30, w, 40, { base: ['#8a5b33', '#5c3a1e'], lines: 16, alpha: 0.28 });
ctx.restore();
rr(ctx, 0, h - 30, w, 34, 10);
ctx.strokeStyle = 'rgba(255,226,180,0.25)'; ctx.lineWidth = 1.5; ctx.stroke();
ctx.fillStyle = 'rgba(255,226,180,0.18)'; ctx.fillRect(12, h - 28, w - 24, 2);
// brass name plate
const g = ctx.createLinearGradient(0, h - 22, 0, h - 6);
g.addColorStop(0, '#e6c97c'); g.addColorStop(1, '#9a7230');
ctx.fillStyle = g; rr(ctx, w / 2 - 46, h - 22, 92, 15, 3); ctx.fill();
scene.textures.addCanvas('wsm-rack', c);
// opponent rack, from behind: the back of the bar with tile backs peeking over
const ow = 300, oh = 46;
const o = canvas(ow, oh);
const ox = o.getContext('2d');
rr(ox, 0, 16, ow, 28, 7); ox.save(); ox.clip();
woodGrain(ox, 0, 16, ow, 30, { base: ['#7a4f2c', '#4f311a'], lines: 12, alpha: 0.3 });
ox.restore();
rr(ox, 0, 16, ow, 28, 7); ox.strokeStyle = 'rgba(255,226,180,0.2)'; ox.lineWidth = 1.2; ox.stroke();
scene.textures.addCanvas('wsm-orack', o);
}
function bakeBag(scene) {
seed = 88;
const w = BAG.w, h = BAG.h;
const c = canvas(w, h);
const ctx = c.getContext('2d');
const cx = w / 2;
const body = () => {
ctx.beginPath();
ctx.moveTo(cx - 26, 40);
ctx.bezierCurveTo(cx - 76, 60, cx - 74, h - 20, cx - 30, h - 12);
ctx.quadraticCurveTo(cx, h - 4, cx + 30, h - 12);
ctx.bezierCurveTo(cx + 74, h - 20, cx + 76, 60, cx + 26, 40);
ctx.closePath();
};
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 8;
body();
const g = ctx.createRadialGradient(cx - 18, 80, 10, cx, 100, 90);
g.addColorStop(0, '#8a2f3e'); g.addColorStop(0.6, '#5b1f2a'); g.addColorStop(1, '#2e0e15');
ctx.fillStyle = g; ctx.fill();
ctx.restore();
ctx.save(); body(); ctx.clip();
ctx.fillStyle = noisePattern(ctx, 64, 16); ctx.fillRect(0, 0, w, h);
ctx.restore();
// velvet folds
ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 2;
for (const dx of [-30, -12, 8, 26]) { ctx.beginPath(); ctx.moveTo(cx + dx * 0.4, 46); ctx.quadraticCurveTo(cx + dx, 100, cx + dx * 0.8, h - 16); ctx.stroke(); }
ctx.strokeStyle = 'rgba(255,180,190,0.12)'; ctx.lineWidth = 3;
for (const dx of [-21, 0, 17]) { ctx.beginPath(); ctx.moveTo(cx + dx * 0.4, 48); ctx.quadraticCurveTo(cx + dx, 100, cx + dx * 0.8, h - 18); ctx.stroke(); }
// gathered neck + ruffle
ctx.fillStyle = '#4a1822';
ctx.beginPath(); ctx.ellipse(cx, 40, 28, 9, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#6e2633';
for (let i = 0; i < 7; i++) { ctx.beginPath(); ctx.ellipse(cx - 24 + i * 8, 24 + (i % 2) * 3, 6, 14, (i - 3) * 0.15, 0, Math.PI * 2); ctx.fill(); }
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.beginPath(); ctx.ellipse(cx, 18, 18, 5, 0, 0, Math.PI * 2); ctx.fill();
// gold cord + tassels
ctx.strokeStyle = '#d9b25a'; ctx.lineWidth = 4;
ctx.beginPath(); ctx.ellipse(cx, 40, 30, 9, 0, 0.1, Math.PI - 0.1); ctx.stroke();
ctx.strokeStyle = '#a5792c'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.ellipse(cx, 41, 30, 9, 0, 0.1, Math.PI - 0.1); ctx.stroke();
for (const [dx, len] of [[18, 34], [26, 28]]) {
ctx.strokeStyle = '#d9b25a'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.moveTo(cx + 10, 48); ctx.quadraticCurveTo(cx + dx, 60, cx + dx + 2, 48 + len); ctx.stroke();
ctx.fillStyle = '#c79d45';
ctx.beginPath(); ctx.moveTo(cx + dx - 3, 48 + len); ctx.lineTo(cx + dx + 7, 48 + len); ctx.lineTo(cx + dx + 4, 62 + len); ctx.lineTo(cx + dx, 62 + len); ctx.fill();
}
scene.textures.addCanvas('wsm-bag', c);
}
function bakeDict(scene) {
seed = 99;
const w = DICT.w, h = DICT.h;
const c = canvas(w, h);
const ctx = c.getContext('2d');
// page block (right + bottom edges)
ctx.fillStyle = '#efe4c8';
rr(ctx, 10, 12, w - 14, h - 16, 6); ctx.fill();
ctx.strokeStyle = 'rgba(120,100,70,0.35)'; ctx.lineWidth = 0.6;
for (let y = 16; y < h - 6; y += 2.2) { ctx.beginPath(); ctx.moveTo(w - 12, y); ctx.lineTo(w - 4, y); ctx.stroke(); }
for (let x = 14; x < w - 6; x += 2.2) { ctx.beginPath(); ctx.moveTo(x, h - 12); ctx.lineTo(x, h - 4); ctx.stroke(); }
// cover
rr(ctx, 2, 2, w - 16, h - 16, 6);
ctx.save(); ctx.clip();
const g = ctx.createLinearGradient(0, 0, w, h);
g.addColorStop(0, '#5a2a1c'); g.addColorStop(1, '#2e140c');
ctx.fillStyle = g; ctx.fillRect(0, 0, w, h);
ctx.fillStyle = noisePattern(ctx, 128, 26); ctx.fillRect(0, 0, w, h);
// spine band
ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(2, 2, 20, h);
ctx.fillStyle = 'rgba(255,220,170,0.08)'; ctx.fillRect(22, 2, 2, h);
ctx.restore();
ctx.strokeStyle = 'rgba(226,195,120,0.7)'; ctx.lineWidth = 1.5;
rr(ctx, 30, 10, w - 52, h - 32, 4); ctx.stroke();
rr(ctx, 34, 14, w - 60, h - 40, 3); ctx.lineWidth = 0.8; ctx.stroke();
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = GOLD;
ctx.font = font(15, 'bold');
ctx.fillText('DICTIONARY', 30 + (w - 52) / 2, h / 2 - 16);
ctx.font = font(10, 'italic');
ctx.fillText('of the English Language', 30 + (w - 52) / 2, h / 2 + 2);
drawFleuron(ctx, 30 + (w - 52) / 2, h / 2 + 24, 7, GOLD);
scene.textures.addCanvas('wsm-dict', c);
}
function paper(ctx, x, y, w, h, { tone = ['#f7efd9', '#efe3c4'], r = 4 } = {}) {
rr(ctx, x, y, w, h, r);
const g = ctx.createLinearGradient(x, y, x, y + h);
g.addColorStop(0, tone[0]); g.addColorStop(1, tone[1]);
ctx.fillStyle = g; ctx.fill();
ctx.save(); ctx.clip();
ctx.fillStyle = noisePattern(ctx, 128, 10); ctx.fillRect(x, y, w, h);
ctx.restore();
}
export const SHEET_GEOM = { headY: 74, namesY: 112, rowY0: 140, rowH: 27, footH: 58, padX: 22 };
function bakeSheet(scene, n) {
seed = 321 + n;
const { w, h } = SHEET;
const c = canvas(w, h);
const ctx = c.getContext('2d');
// clipboard
rr(ctx, 0, 0, w, h, 14); ctx.save(); ctx.clip();
woodGrain(ctx, 0, 0, w, h, { base: ['#8d6236', '#6b4523'], lines: 40, alpha: 0.24, vertical: true });
ctx.restore();
rr(ctx, 0, 0, w, h, 14); ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 2; ctx.stroke();
// paper
const px = 14, py = 30, pw = w - 28, ph = h - 44;
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.35)'; ctx.shadowBlur = 6; ctx.shadowOffsetY = 2;
paper(ctx, px, py, pw, ph); ctx.restore();
paper(ctx, px, py, pw, ph);
// header
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = RED_INK; ctx.font = font(22, 'bold');
ctx.fillText('SCORE SHEET', w / 2, SHEET_GEOM.headY - 8);
ctx.fillStyle = '#7a6f5e'; ctx.font = font(11, 'italic');
ctx.fillText('word · points · running total', w / 2, SHEET_GEOM.headY + 12);
// columns
const { padX, rowY0, rowH, namesY, footH } = SHEET_GEOM;
const colW = (pw - padX * 2) / n;
ctx.strokeStyle = 'rgba(70,110,160,0.35)'; ctx.lineWidth = 1;
for (let y = rowY0; y < h - footH; y += rowH) { ctx.beginPath(); ctx.moveTo(px + 8, y); ctx.lineTo(px + pw - 8, y); ctx.stroke(); }
ctx.strokeStyle = 'rgba(155,47,37,0.55)'; ctx.lineWidth = 1.4;
for (let i = 1; i < n; i++) { const x = px + padX + colW * i; ctx.beginPath(); ctx.moveTo(x, namesY - 16); ctx.lineTo(x, h - footH + 4); ctx.stroke(); }
ctx.beginPath(); ctx.moveTo(px + 8, rowY0 - 2); ctx.lineTo(px + pw - 8, rowY0 - 2); ctx.stroke();
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(px + 8, h - footH + 6); ctx.lineTo(px + pw - 8, h - footH + 6); ctx.stroke();
ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(px + 8, h - footH + 10); ctx.lineTo(px + pw - 8, h - footH + 10); ctx.stroke();
// clip
const cg = ctx.createLinearGradient(0, 4, 0, 46);
cg.addColorStop(0, '#e9e6df'); cg.addColorStop(0.5, '#a8a39a'); cg.addColorStop(1, '#6e6a63');
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 6; ctx.shadowOffsetY = 3;
ctx.fillStyle = cg; rr(ctx, w / 2 - 70, 6, 140, 34, 8); ctx.fill(); ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,0.5)'; ctx.fillRect(w / 2 - 60, 10, 120, 2);
ctx.fillStyle = '#56524c'; ctx.beginPath(); ctx.arc(w / 2, 22, 5, 0, Math.PI * 2); ctx.fill();
scene.textures.addCanvas(`wsm-sheet-${n}`, c);
}
function bakeCards(scene) {
seed = 61;
{
const { w, h } = TRACKER;
const c = canvas(w, h);
const ctx = c.getContext('2d');
paper(ctx, 2, 2, w - 4, h - 4, { tone: ['#f3ead2', '#e6d8b6'], r: 6 });
ctx.strokeStyle = 'rgba(155,47,37,0.45)'; ctx.lineWidth = 1;
rr(ctx, 8, 8, w - 16, h - 16, 4); ctx.stroke();
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillStyle = RED_INK; ctx.font = font(15, 'bold');
ctx.fillText('TILE TRACKER', 20, 24);
scene.textures.addCanvas('wsm-track', c);
}
{
const w = 900, h = 640;
const c = canvas(w, h);
const ctx = c.getContext('2d');
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 24; ctx.shadowOffsetY = 10;
paper(ctx, 12, 12, w - 24, h - 24, { r: 10 }); ctx.restore();
paper(ctx, 12, 12, w - 24, h - 24, { r: 10 });
ctx.strokeStyle = 'rgba(155,47,37,0.5)'; ctx.lineWidth = 1.5;
rr(ctx, 24, 24, w - 48, h - 48, 6); ctx.stroke();
ctx.lineWidth = 0.8; rr(ctx, 29, 29, w - 58, h - 58, 4); ctx.stroke();
scene.textures.addCanvas('wsm-card', c);
}
ensureLeatherPanel(scene, 'wsm-seat', SEAT.w, SEAT.h, { radius: 14 });
ensureLeatherPanel(scene, 'wsm-hplate', HUMAN.w, HUMAN.h, { radius: 14 });
}
/** Bake everything the scene needs (idempotent). */
export function ensureWordsmithArt(scene, { labels = 'full', patterns = false, players = 2 } = {}) {
if (!scene.textures.exists('wsm-room')) bakeRoom(scene);
if (!scene.textures.exists('wsm-tile-0')) bakeTiles(scene);
if (!scene.textures.exists('wsm-rack')) bakeRack(scene);
if (!scene.textures.exists('wsm-bag')) bakeBag(scene);
if (!scene.textures.exists('wsm-dict')) bakeDict(scene);
if (!scene.textures.exists('wsm-track')) bakeCards(scene);
if (!scene.textures.exists(`wsm-sheet-${players}`)) bakeSheet(scene, players);
const key = boardKey(labels, patterns);
if (!scene.textures.exists(key)) bakeBoard(scene, key, { labels, patterns });
if (!scene.textures.exists('wsm-dot')) {
const g = scene.make.graphics({ add: false });
g.fillStyle(0xffffff, 1); g.fillCircle(6, 6, 6);
g.generateTexture('wsm-dot', 12, 12); g.destroy();
}
if (!scene.textures.exists('wsm-glow')) {
const c = canvas(128, 128);
const ctx = c.getContext('2d');
const gr = ctx.createRadialGradient(64, 64, 4, 64, 64, 62);
gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.4, 'rgba(255,255,255,0.45)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gr; ctx.fillRect(0, 0, 128, 128);
scene.textures.addCanvas('wsm-glow', c);
}
return key;
}
export function boardKey(labels, patterns) { return `wsm-board-${labels}-${patterns ? 1 : 0}`; }
export const BOARD_TEX_SIZE = BOARD_PX + BOARD_PAD * 2;
// ── Tiles ─────────────────────────────────────────────────────────────────────
/**
* A wooden tile: container [shadow, face, letter, value]. `size` in px.
* token: 'A'…'Z' or '_' (blank); `letter` is the blank's chosen letter (pencilled).
* opts: { grain, letter, shadow }
*/
export function makeTile(scene, token, size, { grain = null, letter = null, shadow = true } = {}) {
const c = scene.add.container(0, 0);
const k = size / TILE_PX;
const g = grain ?? Math.floor(Math.random() * GRAINS);
if (shadow) {
const sh = scene.add.image(2 * k, 4 * k, 'wsm-tshadow').setScale(k).setAlpha(0.55);
c.add(sh); c._shadow = sh;
}
const face = scene.add.image(0, 0, `wsm-tile-${g}`).setScale(k);
c.add(face); c._face = face;
const isBlank = token === BLANK;
const L = isBlank ? (letter ?? '') : token;
if (L) {
const txt = scene.add.text(isBlank ? 0 : -3 * k, (isBlank ? 1 : -1) * k, L, isBlank
? { fontFamily: HAND, fontSize: `${Math.round(size * 0.62)}px`, color: PENCIL }
: { fontFamily: SERIF, fontSize: `${Math.round(size * 0.58)}px`, color: INK, fontStyle: 'bold' }).setOrigin(0.5);
if (!isBlank) txt.setShadow(0, Math.max(1, k * 1.4), 'rgba(255,248,226,0.75)', 0, false, true);
else txt.setAlpha(0.85);
c.add(txt); c._letter = txt;
}
if (!isBlank) {
const v = LETTER_VALUES[token] ?? 0;
const vt = scene.add.text(size * 0.36, size * 0.32, String(v), {
fontFamily: SANS, fontSize: `${Math.max(9, Math.round(size * 0.22))}px`, color: INK, fontStyle: 'bold',
}).setOrigin(1, 1);
c.add(vt); c._value = vt;
}
c._token = token;
c._size = size;
c.setSize(size, size);
return c;
}
/** Re-letter a blank tile (pencil). */
export function pencilBlank(scene, tile, letter) {
if (tile._letter) { tile._letter.setText(letter); return; }
const txt = scene.add.text(0, 1, letter, { fontFamily: HAND, fontSize: `${Math.round(tile._size * 0.62)}px`, color: PENCIL }).setOrigin(0.5).setAlpha(0.85);
tile.add(txt); tile._letter = txt;
}
// ── Buttons ───────────────────────────────────────────────────────────────────
/** A tooled-leather library button. variant: 'leather' | 'oak' | 'brass'. */
export class LibButton extends Phaser.GameObjects.Container {
constructor(scene, x, y, label, onClick, { width = 132, height = 44, fontSize = 18, variant = 'leather', hotkey = null } = {}) {
super(scene, x, y);
this.w = width; this.h = height; this.variant = variant;
this.enabled = true; this.hover = false; this.lit = false;
this.gfx = scene.add.graphics();
const color = variant === 'oak' ? INK : variant === 'brass' ? '#2b1a08' : CREAM;
this.text = scene.add.text(0, hotkey ? -5 : 0, label, { fontFamily: SERIF, fontSize: `${fontSize}px`, color, fontStyle: 'bold' }).setOrigin(0.5);
this.base = fontSize;
this.add([this.gfx, this.text]);
if (hotkey) {
this.key = scene.add.text(0, 12, hotkey, { fontFamily: SANS, fontSize: '10px', color }).setOrigin(0.5).setAlpha(0.6);
this.add(this.key);
}
this.fit();
this.setSize(width, height);
this.setInteractive({ useHandCursor: true });
this.draw();
this.on('pointerover', () => { this.hover = true; this.draw(); });
this.on('pointerout', () => { this.hover = false; this.draw(); this.gfx.y = 0; });
this.on('pointerdown', () => { if (this.enabled) this.gfx.y = 2; });
this.on('pointerup', () => { this.gfx.y = 0; if (this.enabled) onClick?.(); });
scene.add.existing(this);
}
fit() {
const maxW = this.w - 18;
this.text.setFontSize(this.base);
if (this.text.width > maxW) this.text.setFontSize(Math.max(11, Math.floor(this.base * maxW / this.text.width)));
}
draw() {
const g = this.gfx, w = this.w, h = this.h;
g.clear();
g.fillStyle(0x000000, 0.35);
g.fillRoundedRect(-w / 2 + 2, -h / 2 + 4, w, h, 8);
const hot = this.hover && this.enabled;
const pal = {
leather: [hot ? 0x346650 : 0x28503f, 0x173126],
oak: [hot ? 0xf3e6c4 : 0xe8d6a8, 0xb89a62],
brass: [hot ? 0xf0d58a : 0xd6b260, 0x8a6526],
}[this.variant];
g.fillStyle(pal[1], 1);
g.fillRoundedRect(-w / 2, -h / 2 + 2, w, h, 8);
g.fillStyle(pal[0], 1);
g.fillRoundedRect(-w / 2, -h / 2, w, h - 2, 8);
g.lineStyle(1.2, this.variant === 'leather' ? GOLD_N : 0x6e4e1c, this.lit ? 1 : 0.6);
g.strokeRoundedRect(-w / 2 + 4, -h / 2 + 4, w - 8, h - 10, 5);
if (this.lit) {
g.lineStyle(2.5, 0xffe9a8, 0.9);
g.strokeRoundedRect(-w / 2 - 2, -h / 2 - 2, w + 4, h + 2, 9);
}
}
setLabel(t) { this.text.setText(t); this.fit(); return this; }
setLit(on) { this.lit = !!on; this.draw(); return this; }
setEnabled(on) {
this.enabled = !!on;
this.setAlpha(on ? 1 : 0.42);
if (this.input) this.input.cursor = on ? 'pointer' : 'default';
this.draw();
return this;
}
}

View File

@ -0,0 +1,227 @@
// Wordsmith dialogs — every modal is a paper card on a dimmed table:
// blank picker, settings, Word Judge, reference card, pause menu, confirm,
// statistics, resume prompt. Portrait videos are hidden while one is open.
import { TextInput } from '../../ui/TextInput.js';
import { LETTER_DISTRIBUTION, LETTER_VALUES, BLANK } from './ScrabbleTiles.js';
import { RULES } from './ScrabbleLogic.js';
import { W, H } from './ScrabbleLayout.js';
import { LibButton, makeTile, SERIF, INK, RED_INK } from './ScrabbleArt.js';
import { DEPTH } from './ScrabbleHud.js';
import { judgeWords } from './ScrabbleAI.js';
export const SETTINGS_KEY = 'scrabble-settings';
export const DEFAULT_SETTINGS = {
rule: 'friendly', clock: 0, coach: 'hints', preview: true, tracker: true,
turntable: true, labels: 'full', patterns: false, pace: 'normal',
};
export function loadSettings() {
try { return { ...DEFAULT_SETTINGS, ...(JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') || {}) }; } catch { return { ...DEFAULT_SETTINGS }; }
}
export function saveSettings(s) { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(s)); } catch { /* private mode */ } }
/** A modal card. Returns { root, add, close, cx, cy, w, h }. */
export function openModal(scene, { w = 640, h = 420, title = '', onClose = null, closeOnDim = true } = {}) {
scene.closeModal?.();
const root = scene.add.container(0, 0).setDepth(DEPTH.modal);
const dim = scene.add.rectangle(W / 2, H / 2, W, H, 0x000000, 0.55).setInteractive();
root.add(dim);
const card = scene.add.image(W / 2, H / 2, 'wsm-card').setDisplaySize(w, h);
root.add(card);
const cx = W / 2, cy = H / 2;
if (title) root.add(scene.add.text(cx, cy - h / 2 + 52, title, { fontFamily: SERIF, fontSize: '30px', color: RED_INK, fontStyle: 'bold' }).setOrigin(0.5));
const extras = [];
const m = {
root, cx, cy, w, h,
add: (o) => { root.add(o); return o; },
track: (o) => { extras.push(o); return o; },
close: () => {
if (m.closed) return;
m.closed = true;
extras.forEach(o => o.destroy?.());
root.destroy();
if (scene.modal === m) scene.modal = null;
scene.seats?.setVideos(true);
onClose?.();
},
};
if (closeOnDim) dim.on('pointerup', () => m.close());
scene.seats?.setVideos(false);
scene.modal = m;
return m;
}
function btn(scene, m, x, y, label, fn, opts = {}) {
const b = new LibButton(scene, x, y, label, fn, { width: 170, height: 46, ...opts });
m.add(b);
return b;
}
// ── Blank picker ─────────────────────────────────────────────────────────────
export function openBlankPicker(scene, onPick) {
let picked = false;
const m = openModal(scene, { w: 640, h: 470, title: 'Name the blank', closeOnDim: false, onClose: () => { if (!picked) onPick(null); } });
m.add(scene.add.text(m.cx, m.cy - m.h / 2 + 88, 'It scores nothing, but it can be any letter.', { fontFamily: SERIF, fontSize: '16px', color: '#5a4a32', fontStyle: 'italic' }).setOrigin(0.5));
const L = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const cols = 9, cell = 58, gx = m.cx - ((cols - 1) * cell) / 2, gy = m.cy - 76;
[...L].forEach((ch, i) => {
const t = makeTile(scene, ch, 50, { shadow: true, grain: i % 8 });
t._value?.setVisible(false);
t.setPosition(gx + (i % cols) * cell, gy + Math.floor(i / cols) * cell);
t.setInteractive({ useHandCursor: true });
t.on('pointerover', () => t.setScale(1.1));
t.on('pointerout', () => t.setScale(1));
t.on('pointerup', () => { picked = true; m.close(); onPick(ch); });
m.add(t);
});
m.add(scene.add.text(m.cx, m.cy + 122, 'or type a letter', { fontFamily: SERIF, fontSize: '14px', color: '#7a6f5e' }).setOrigin(0.5));
btn(scene, m, m.cx, m.cy + m.h / 2 - 56, 'Cancel', () => m.close(), { variant: 'oak' });
const onKey = (e) => {
const k = e.key.toUpperCase();
if (/^[A-Z]$/.test(k)) { picked = true; m.close(); onPick(k); }
else if (e.key === 'Escape') m.close();
};
scene.input.keyboard.on('keydown', onKey);
m.track({ destroy: () => scene.input.keyboard.off('keydown', onKey) });
return m;
}
// ── Settings ─────────────────────────────────────────────────────────────────
const OPTIONS = [
{ key: 'rule', label: 'Word rule', values: ['friendly', 'double', 'five'], names: { friendly: 'Friendly (auto-check)', double: 'Double challenge', five: '5-point challenge' }, next: true },
{ key: 'clock', label: 'Tournament clock', values: [0, 25, 15, 10], names: { 0: 'Off', 25: '25 min each', 15: '15 min each', 10: '10 min each' }, next: true },
{ key: 'coach', label: 'Coach', values: ['hints', 'practice', 'off'], names: { hints: '3 hints a game', practice: 'Practice (unlimited, top 3)', off: 'Off' } },
{ key: 'preview', label: 'Score preview', values: [true, false], names: { true: 'On', false: 'Off' } },
{ key: 'tracker', label: 'Tile tracker', values: [true, false], names: { true: 'Shown', false: 'Hidden' } },
{ key: 'turntable', label: 'Turntable turns to the player', values: [true, false], names: { true: 'On', false: 'Off' } },
{ key: 'labels', label: 'Square labels', values: ['full', 'short'], names: { full: 'TRIPLE WORD', short: '3W · 2L' } },
{ key: 'patterns', label: 'Colour-blind patterns', values: [false, true], names: { false: 'Off', true: 'On' } },
{ key: 'pace', label: 'Opponent pace', values: ['relaxed', 'normal', 'fast'], names: { relaxed: 'Relaxed', normal: 'Normal', fast: 'Brisk' } },
];
export function openSettings(scene, settings, onChange, { live = {} } = {}) {
const m = openModal(scene, { w: 820, h: 640, title: 'Table Settings' });
const x0 = m.cx - 330, y0 = m.cy - 200;
OPTIONS.forEach((o, i) => {
const y = y0 + i * 44;
m.add(scene.add.text(x0, y, o.label, { fontFamily: SERIF, fontSize: '19px', color: INK }).setOrigin(0, 0.5));
const b = new LibButton(scene, x0 + 520, y, o.names[settings[o.key]], () => {
const idx = o.values.indexOf(settings[o.key]);
settings[o.key] = o.values[(idx + 1) % o.values.length];
b.setLabel(o.names[settings[o.key]]);
saveSettings(settings);
onChange?.(o.key, settings[o.key]);
note.setText(noteText());
}, { width: 290, height: 36, fontSize: 16, variant: 'oak' });
m.add(b);
});
const noteText = () => {
const pend = OPTIONS.filter(o => o.next && live[o.key] !== undefined && live[o.key] !== settings[o.key]).map(o => o.label.toLowerCase());
return pend.length ? `The ${pend.join(' and ')} change${pend.length > 1 ? '' : 's'} with the next game.` : RULES[settings.rule].blurb;
};
const note = m.add(scene.add.text(m.cx, y0 + OPTIONS.length * 44 + 10, noteText(), { fontFamily: SERIF, fontSize: '15px', color: '#5a4a32', fontStyle: 'italic', wordWrap: { width: 680 }, align: 'center' }).setOrigin(0.5, 0));
btn(scene, m, m.cx, m.cy + m.h / 2 - 50, 'Done', () => m.close());
return m;
}
// ── Word Judge ───────────────────────────────────────────────────────────────
export function openWordJudge(scene, { disabled = false } = {}) {
const m = openModal(scene, { w: 640, h: 440, title: 'Word Judge' });
if (disabled) {
m.add(scene.add.text(m.cx, m.cy - 10, 'The judge is closed while a play can still be challenged.', { fontFamily: SERIF, fontSize: '18px', color: INK, wordWrap: { width: 520 }, align: 'center' }).setOrigin(0.5));
btn(scene, m, m.cx, m.cy + m.h / 2 - 56, 'Close', () => m.close());
return m;
}
m.add(scene.add.text(m.cx, m.cy - 110, 'Type one or more words. The judge says only "acceptable" or not.', { fontFamily: SERIF, fontSize: '15px', color: '#5a4a32', fontStyle: 'italic' }).setOrigin(0.5));
const input = m.track(new TextInput(scene, m.cx, m.cy - 54, { width: 440, height: 48, placeholder: 'e.g. QUIXOTE ZAX', maxLength: 64 }));
input.el.style.fontSize = '22px';
input.el.style.textTransform = 'uppercase';
input.el.style.textAlign = 'center';
setTimeout(() => input.el.focus(), 30);
const verdict = m.add(scene.add.text(m.cx, m.cy + 34, '', { fontFamily: SERIF, fontSize: '22px', color: INK, align: 'center', wordWrap: { width: 540 } }).setOrigin(0.5));
const go = async () => {
const words = String(input.el.value || '').toUpperCase().split(/[^A-Z]+/).filter(Boolean).slice(0, 8);
if (!words.length) return;
scene.sfx?.pageFlip();
const res = await judgeWords(words);
if (m.closed) return;
verdict.setText(res.valid ? `✓ ${words.join(', ')} ${words.length > 1 ? 'are' : 'is'} acceptable` : `✗ not acceptable`);
verdict.setColor(res.valid ? '#2f6a3a' : RED_INK);
};
input.el.addEventListener('keydown', (e) => { if (e.key === 'Enter') go(); if (e.key === 'Escape') m.close(); e.stopPropagation(); });
btn(scene, m, m.cx - 100, m.cy + m.h / 2 - 56, 'Judge', go);
btn(scene, m, m.cx + 100, m.cy + m.h / 2 - 56, 'Close', () => m.close(), { variant: 'oak' });
return m;
}
// ── Reference card ───────────────────────────────────────────────────────────
export function openReferenceCard(scene, twoLetter) {
const m = openModal(scene, { w: 900, h: 640, title: 'Reference Card' });
const left = m.cx - 400;
m.add(scene.add.text(left + 20, m.cy - 230, 'TWO-LETTER WORDS', { fontFamily: SERIF, fontSize: '16px', color: RED_INK, fontStyle: 'bold' }).setOrigin(0, 0.5));
const per = 9;
twoLetter.forEach((w, i) => {
const col = Math.floor(i / 12), row = i % 12;
if (col >= per) return;
m.add(scene.add.text(left + 20 + col * 52, m.cy - 196 + row * 26, w, { fontFamily: SERIF, fontSize: '17px', color: INK, fontStyle: 'bold' }).setOrigin(0, 0.5));
});
const rx = m.cx + 90;
m.add(scene.add.text(rx, m.cy - 230, 'THE 100 TILES (count × points)', { fontFamily: SERIF, fontSize: '16px', color: RED_INK, fontStyle: 'bold' }).setOrigin(0, 0.5));
const tokens = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ', BLANK];
tokens.forEach((t, i) => {
const col = Math.floor(i / 10), row = i % 10;
const label = `${t === BLANK ? '?' : t} ${LETTER_DISTRIBUTION[t]}×${LETTER_VALUES[t]}`;
m.add(scene.add.text(rx + col * 106, m.cy - 196 + row * 28, label, { fontFamily: SERIF, fontSize: '17px', color: INK }).setOrigin(0, 0.5));
});
m.add(scene.add.text(m.cx, m.cy + 140, [
'All seven tiles in one play: +50. Premium squares count only on the turn they are covered.',
'Exchanges need 7+ tiles in the bag. Six scoreless turns in a row end the game.',
'At the end, each rack is docked its value; the player who went out gains the others’ total.',
].join('\n'), { fontFamily: SERIF, fontSize: '14px', color: '#5a4a32', align: 'center', lineSpacing: 6 }).setOrigin(0.5));
btn(scene, m, m.cx, m.cy + m.h / 2 - 50, 'Close', () => m.close(), { variant: 'oak' });
return m;
}
// ── Pause menu / confirm / stats ──────────────────────────────────────────────
export function openMenu(scene, items, { title = 'Paused', onClose = null } = {}) {
const h = 170 + items.length * 62;
const m = openModal(scene, { w: 460, h, title, onClose });
items.forEach((it, i) => {
btn(scene, m, m.cx, m.cy - h / 2 + 120 + i * 62, it.label, () => { m.close(); it.fn(); }, { width: 300, height: 48, variant: i === 0 ? 'leather' : 'oak' });
});
return m;
}
export function confirmDialog(scene, title, body, yes, onYes, { no = 'Cancel', onNo = null } = {}) {
const m = openModal(scene, { w: 620, h: 320, title, onClose: null });
m.add(scene.add.text(m.cx, m.cy - 20, body, { fontFamily: SERIF, fontSize: '18px', color: INK, align: 'center', wordWrap: { width: 520 } }).setOrigin(0.5));
btn(scene, m, m.cx - 110, m.cy + 100, yes, () => { m.close(); onYes?.(); });
btn(scene, m, m.cx + 110, m.cy + 100, no, () => { m.close(); onNo?.(); }, { variant: 'oak' });
return m;
}
export function openStats(scene, s, extra) {
const m = openModal(scene, { w: 620, h: 480, title: 'Your Record' });
const rows = [
['Games played', s.played],
['Games won', `${s.won}${s.played ? ` (${Math.round(100 * s.won / s.played)}%)` : ''}`],
['Current streak', s.streak],
['High game', s.bests?.highGame ?? '—'],
['Best single play', extra.bestWord ? `${extra.bestWord.word} ${extra.bestWord.score}` : '—'],
['Bingos', s.counts?.bingos ?? 0],
['Average score', s.played ? Math.round((s.counts?.points ?? 0) / s.played) : '—'],
];
rows.forEach(([k, v], i) => {
const y = m.cy - 130 + i * 38;
m.add(scene.add.text(m.cx - 220, y, k, { fontFamily: SERIF, fontSize: '19px', color: INK }).setOrigin(0, 0.5));
m.add(scene.add.text(m.cx + 220, y, String(v), { fontFamily: SERIF, fontSize: '19px', color: RED_INK, fontStyle: 'bold' }).setOrigin(1, 0.5));
});
btn(scene, m, m.cx, m.cy + m.h / 2 - 50, 'Close', () => m.close(), { variant: 'oak' });
return m;
}

View File

@ -0,0 +1,93 @@
// Wordsmith end screen: the final tally (rack penalties, the out bonus,
// overtime), standings, and the coach's post-game review of your turns.
import { BLANK } from './ScrabbleTiles.js';
import { W, H } from './ScrabbleLayout.js';
import { LibButton, SERIF, INK, RED_INK } from './ScrabbleArt.js';
import { DEPTH } from './ScrabbleHud.js';
const GREEN_INK = '#2f6a3a';
/**
* review: [{ word, score, best:{word,score}|null, type }] for the human's turns.
* actions: { again, leave, onView }
*/
export function showEndScreen(scene, state, review, { again, leave }) {
const root = scene.add.container(0, 0).setDepth(DEPTH.end);
const dim = scene.add.rectangle(W / 2, H / 2, W, H, 0x000000, 0.5).setInteractive();
root.add(dim);
const PW = 1180, PH = 760, cx = W / 2, cy = H / 2;
root.add(scene.add.image(cx, cy, 'wsm-card').setDisplaySize(PW, PH));
const end = state.end;
const winners = end.winners;
const won = winners.includes(0);
const tie = winners.length > 1;
const title = tie ? (won ? 'A shared victory!' : 'A tie at the top') : won ? 'You win!' : `${state.players[winners[0]].name} wins`;
root.add(scene.add.text(cx, cy - PH / 2 + 62, title, { fontFamily: SERIF, fontSize: '44px', color: won ? GREEN_INK : RED_INK, fontStyle: 'bold' }).setOrigin(0.5));
const why = end.reason === 'out'
? `${end.outSeat === 0 ? 'You' : state.players[end.outSeat].name} went out.`
: 'Six scoreless turns in a row: the game is over.';
root.add(scene.add.text(cx, cy - PH / 2 + 106, why, { fontFamily: SERIF, fontSize: '17px', color: '#5a4a32', fontStyle: 'italic' }).setOrigin(0.5));
// Standings with the end-of-game adjustments.
const lx = cx - PW / 2 + 70;
root.add(scene.add.text(lx, cy - 230, 'FINAL TALLY', { fontFamily: SERIF, fontSize: '16px', color: RED_INK, fontStyle: 'bold' }).setOrigin(0, 0.5));
end.order.forEach((seat, i) => {
const p = state.players[seat];
const y = cy - 186 + i * 58;
const adjs = state.log.filter(e => e.seat === seat && ['rack', 'out', 'clock'].includes(e.type));
const adjText = adjs.map(e => e.type === 'rack' ? `rack ${e.tiles.map(t => t === BLANK ? '?' : t).join('')} ${e.score}` : e.type === 'out' ? `out +${e.score}` : `overtime ${e.score}`).join(' · ');
const isW = winners.includes(seat);
root.add(scene.add.text(lx, y, `${i + 1}. ${p.name}`, { fontFamily: SERIF, fontSize: '26px', color: isW ? GREEN_INK : INK, fontStyle: 'bold' }).setOrigin(0, 0.5));
root.add(scene.add.text(lx + 470, y, String(p.score), { fontFamily: SERIF, fontSize: '30px', color: isW ? GREEN_INK : INK, fontStyle: 'bold' }).setOrigin(1, 0.5));
const sub = [adjText, p.bingos ? `${p.bingos} bingo${p.bingos > 1 ? 's' : ''}` : '', p.best ? `best ${p.best.word} ${p.best.score}` : ''].filter(Boolean).join(' · ');
root.add(scene.add.text(lx + 30, y + 22, sub, { fontFamily: SERIF, fontSize: '13px', color: '#7a6f5e' }).setOrigin(0, 0.5));
});
// Coach's review.
const rx = cx + 40;
root.add(scene.add.text(rx, cy - 230, "THE COACH'S REVIEW", { fontFamily: SERIF, fontSize: '16px', color: RED_INK, fontStyle: 'bold' }).setOrigin(0, 0.5));
const plays = review.filter(r => r.type === 'play' && r.best);
if (!plays.length) {
root.add(scene.add.text(rx, cy - 190, 'No plays to review this time.', { fontFamily: SERIF, fontSize: '16px', color: '#5a4a32', fontStyle: 'italic' }).setOrigin(0, 0.5));
} else {
const yours = plays.reduce((s, r) => s + r.score, 0);
const bests = plays.reduce((s, r) => s + Math.max(r.score, r.best.score), 0);
const found = plays.filter(r => r.score >= r.best.score).length;
root.add(scene.add.text(rx, cy - 196, `Found the top play ${found} of ${plays.length} times · ${Math.round(100 * yours / Math.max(1, bests))}% of the available points`, { fontFamily: SERIF, fontSize: '15px', color: INK }).setOrigin(0, 0.5));
// the biggest misses
const misses = plays.map((r, i) => ({ ...r, i, gap: r.best.score - r.score })).filter(r => r.gap > 0).sort((a, b) => b.gap - a.gap).slice(0, 7);
if (!misses.length) {
root.add(scene.add.text(rx, cy - 160, 'Every play was the highest scorer available. Superb.', { fontFamily: SERIF, fontSize: '16px', color: GREEN_INK, fontStyle: 'italic' }).setOrigin(0, 0.5));
}
misses.forEach((r, k) => {
const y = cy - 156 + k * 44;
root.add(scene.add.text(rx, y, `Turn ${r.i + 1}: you played ${r.word || '—'} for ${r.score}`, { fontFamily: SERIF, fontSize: '15px', color: INK }).setOrigin(0, 0.5));
root.add(scene.add.text(rx + 18, y + 18, `best was ${r.best.word} for ${r.best.score} (+${r.gap})`, { fontFamily: SERIF, fontSize: '14px', color: GREEN_INK, fontStyle: 'italic' }).setOrigin(0, 0.5));
});
}
const by = cy + PH / 2 - 62;
const objs = [];
const view = new LibButton(scene, cx - 250, by, 'View board', () => {
root.setVisible(false);
scene.seats?.setVideos(true);
const back = new LibButton(scene, W / 2, 856, 'Back to results', () => { back.destroy(); root.setVisible(true); scene.seats?.setVideos(false); }, { width: 220, height: 44 });
back.setDepth(DEPTH.end);
objs.push(back);
}, { width: 200, height: 52, variant: 'oak' });
const play = new LibButton(scene, cx, by, 'Play again', again, { width: 220, height: 52 });
const out = new LibButton(scene, cx + 250, by, 'Leave', leave, { width: 200, height: 52, variant: 'oak' });
root.add([view, play, out]);
scene.seats?.setVideos(false);
// a few gold flecks for a win
if (won) {
const fx = scene.add.particles(cx, cy - PH / 2 + 62, 'wsm-dot', {
speed: { min: 60, max: 260 }, lifespan: 1400, scale: { start: 0.6, end: 0 }, alpha: { start: 1, end: 0 },
quantity: 2, frequency: 40, angle: { min: 200, max: 340 }, gravityY: 180, tint: [0xe2c378, 0xfff2c8, 0x9fd18b],
}).setDepth(DEPTH.end + 1);
scene.time.delayedCall(2400, () => { fx.stop(); scene.time.delayedCall(1500, () => fx.destroy()); });
}
return { root, destroy: () => { root.destroy(); objs.forEach(o => o.destroy()); } };
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,336 @@
// Wordsmith HUD — the clipboard score sheet, tile tracker, seat plates, the
// play-preview tag and the hover tip. Scene-side (Phaser), state comes in from
// ScrabbleLogic's plain `state`.
import { LETTER_DISTRIBUTION, BLANK } from './ScrabbleTiles.js';
import { SHEET, TRACKER, SEAT, HUMAN, seatRect, BAG } from './ScrabbleLayout.js';
import { SHEET_GEOM, SERIF, SANS, HAND, INK, CREAM, GOLD, RED_INK, PENCIL, GOLD_N } from './ScrabbleArt.js';
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
export const DEPTH = { room: 0, board: 5, furniture: 8, hud: 12, rack: 20, fly: 40, drag: 60, tip: 70, modal: 80, end: 90 };
const PENCIL_BLUE = '#2f4a78';
const fmtClock = (ms) => {
if (ms == null) return '';
const neg = ms < 0;
const t = Math.ceil(Math.abs(ms) / 1000);
return `${neg ? '−' : ''}${Math.floor(t / 60)}:${String(t % 60).padStart(2, '0')}`;
};
export { fmtClock };
// ── Score sheet ───────────────────────────────────────────────────────────────
export class ScoreSheet {
constructor(scene, state, { onRowClick } = {}) {
this.scene = scene;
this.n = state.players.length;
this.onRowClick = onRowClick;
this.img = scene.add.image(SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, `wsm-sheet-${this.n}`).setDepth(DEPTH.furniture);
const pw = SHEET.w - 28;
this.colW = (pw - SHEET_GEOM.padX * 2) / this.n;
this.x0 = SHEET.x + 14 + SHEET_GEOM.padX;
this.maxRows = Math.floor((SHEET.h - SHEET_GEOM.footH - SHEET_GEOM.rowY0) / SHEET_GEOM.rowH);
this.names = state.players.map((p, i) => scene.add.text(this.colX(i) + this.colW / 2, SHEET.y + SHEET_GEOM.namesY, short(p.name, this.n > 2 ? 9 : 14), {
fontFamily: SERIF, fontSize: this.n > 3 ? '15px' : '18px', color: RED_INK, fontStyle: 'bold',
}).setOrigin(0.5).setDepth(DEPTH.hud));
this.totals = state.players.map((_, i) => scene.add.text(this.colX(i) + this.colW / 2, SHEET.y + SHEET.h - SHEET_GEOM.footH / 2 + 4, '0', {
fontFamily: HAND, fontSize: '32px', color: PENCIL_BLUE,
}).setOrigin(0.5).setDepth(DEPTH.hud));
this.cells = [];
this.strikes = scene.add.graphics().setDepth(DEPTH.hud + 1);
this.marker = scene.add.graphics().setDepth(DEPTH.hud - 1);
this.zones = [];
}
colX(i) { return this.x0 + i * this.colW; }
render(state, { activeSeat = null } = {}) {
for (const c of this.cells) c.destroy();
for (const z of this.zones) z.destroy();
this.cells = []; this.zones = [];
this.strikes.clear();
this.marker.clear();
// Group log entries into per-player columns; each turn is one row.
const cols = state.players.map(() => []);
for (const e of state.log) cols[e.seat].push(e);
const rows = Math.max(1, ...cols.map(c => c.length));
const first = Math.max(0, rows - this.maxRows);
const s = this.scene;
cols.forEach((col, seat) => {
col.slice(first).forEach((e, r) => {
const y = SHEET.y + SHEET_GEOM.rowY0 + r * SHEET_GEOM.rowH + SHEET_GEOM.rowH / 2;
const x = this.colX(seat);
const { label, pts, color, strike } = entryText(e);
const fs = this.n > 3 ? 15 : this.n > 2 ? 17 : 19;
const lt = s.add.text(x + 5, y, label, { fontFamily: HAND, fontSize: `${fs}px`, color }).setOrigin(0, 0.5).setDepth(DEPTH.hud);
const maxL = this.colW - (this.n > 2 ? 34 : 70);
if (lt.width > maxL) lt.setScale(maxL / lt.width, 1);
this.cells.push(lt);
if (strike) {
this.strikes.lineStyle(1.6, 0x9b2f25, 0.8);
this.strikes.lineBetween(x + 3, y + 1, x + 7 + lt.displayWidth, y - 1);
}
if (pts != null) {
this.cells.push(s.add.text(x + this.colW - 5, y - (this.n > 2 ? 0 : 0), pts, {
fontFamily: HAND, fontSize: `${fs}px`, color,
}).setOrigin(1, 0.5).setDepth(DEPTH.hud));
}
if (this.n <= 2 && e.total != null && (e.type === 'play' || e.type === 'phony')) {
this.cells.push(s.add.text(x + this.colW - 46, y, String(e.total), {
fontFamily: HAND, fontSize: '14px', color: '#8a8270',
}).setOrigin(1, 0.5).setDepth(DEPTH.hud));
}
if (e.type === 'play' && this.onRowClick) {
const z = s.add.zone(x + this.colW / 2, y, this.colW - 4, SHEET_GEOM.rowH - 2).setInteractive({ useHandCursor: true }).setDepth(DEPTH.hud + 2);
z.on('pointerup', () => this.onRowClick(e));
this.zones.push(z);
}
});
});
state.players.forEach((p, i) => this.totals[i].setText(String(p.score)));
if (activeSeat != null && !state.over) {
const x = this.colX(activeSeat);
this.marker.fillStyle(GOLD_N, 0.22);
this.marker.fillRoundedRect(x + 2, SHEET.y + SHEET_GEOM.namesY - 15, this.colW - 4, 30, 6);
}
if (first > 0) {
this.cells.push(s.add.text(SHEET.x + SHEET.w / 2, SHEET.y + SHEET_GEOM.rowY0 - 10, `… ${first} earlier rounds`, {
fontFamily: SERIF, fontSize: '11px', color: '#8a8270', fontStyle: 'italic',
}).setOrigin(0.5).setDepth(DEPTH.hud));
}
}
bump(seat) {
const t = this.totals[seat];
if (t) this.scene.tweens.add({ targets: t, scale: { from: 1.35, to: 1 }, duration: 260, ease: 'Back.easeOut' });
}
destroy() { [this.img, ...this.names, ...this.totals, ...this.cells, ...this.zones, this.strikes, this.marker].forEach(o => o?.destroy()); }
}
function short(name, max) { return name.length > max ? `${name.slice(0, max - 1)}…` : name; }
function entryText(e) {
switch (e.type) {
case 'play': return { label: e.word + (e.bingo ? ' ★' : ''), pts: String(e.score), color: e.bingo ? RED_INK : PENCIL_BLUE };
case 'phony': return { label: e.word, pts: '0', color: '#7a6f5e', strike: true };
case 'exchange': return { label: `swap ${e.count}`, pts: '—', color: '#7a6f5e' };
case 'pass': return { label: 'pass', pts: '—', color: '#7a6f5e' };
case 'lost': return { label: 'lost turn', pts: '—', color: '#7a6f5e' };
case 'bonus': return { label: 'challenge', pts: `+${e.score}`, color: '#3d6b3a' };
case 'rack': return { label: `rack ${e.tiles.map(t => (t === BLANK ? '?' : t)).join('')}`, pts: String(e.score), color: RED_INK };
case 'out': return { label: 'went out', pts: `+${e.score}`, color: '#3d6b3a' };
case 'clock': return { label: 'overtime', pts: String(e.score), color: RED_INK };
default: return { label: e.type, pts: null, color: PENCIL };
}
}
// ── Tile tracker ──────────────────────────────────────────────────────────────
const TRACK_ORDER = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ', BLANK];
export class TileTracker {
constructor(scene) {
this.scene = scene;
this.img = scene.add.image(TRACKER.x + TRACKER.w / 2, TRACKER.y + TRACKER.h / 2, 'wsm-track').setDepth(DEPTH.furniture);
this.letters = [];
this.g = scene.add.graphics().setDepth(DEPTH.hud + 1);
// Flow-layout all 100 tiles, grouped by letter.
const x0 = TRACKER.x + 22, x1 = TRACKER.x + TRACKER.w - 18, cw = 12.2, lh = 29;
let x = x0, y = TRACKER.y + 60;
for (const t of TRACK_ORDER) {
const n = LETTER_DISTRIBUTION[t];
if (x + n * cw > x1) { x = x0; y += lh; }
const group = [];
for (let i = 0; i < n; i++) {
const txt = scene.add.text(x + i * cw, y, t === BLANK ? '?' : t, { fontFamily: SERIF, fontSize: '16px', color: INK, fontStyle: 'bold' })
.setOrigin(0, 0.5).setDepth(DEPTH.hud);
group.push(txt);
}
this.letters.push({ t, group });
x += n * cw + 8;
}
this.summary = scene.add.text(TRACKER.x + 20, TRACKER.y + TRACKER.h - 26, '', { fontFamily: SERIF, fontSize: '14px', color: '#5a4a32', fontStyle: 'italic' })
.setOrigin(0, 0.5).setDepth(DEPTH.hud);
this.head = scene.add.text(TRACKER.x + TRACKER.w - 20, TRACKER.y + 24, '', { fontFamily: SERIF, fontSize: '13px', color: '#7a6f5e' })
.setOrigin(1, 0.5).setDepth(DEPTH.hud);
}
/** unseen: { token: count }, bag: tiles in the bag, oppTiles: tiles on other racks */
render(unseen, bag, oppTiles) {
this.g.clear();
let vow = 0, con = 0, total = 0;
for (const { t, group } of this.letters) {
const left = Math.max(0, unseen[t] ?? 0);
total += left;
if (t !== BLANK) { if ('AEIOU'.includes(t)) vow += left; else con += left; }
group.forEach((txt, i) => {
const gone = i >= left;
txt.setColor(gone ? '#b5a88c' : INK).setAlpha(gone ? 0.75 : 1);
if (gone) {
this.g.lineStyle(1.5, 0x4a4f58, 0.7);
this.g.lineBetween(txt.x - 1, txt.y + 5, txt.x + txt.width + 1, txt.y - 6);
}
});
}
this.summary.setText(`Unseen ${total}: ${vow} vowels · ${con} consonants · ${unseen[BLANK] ?? 0} blank${(unseen[BLANK] ?? 0) === 1 ? '' : 's'}`);
this.head.setText(`bag ${bag} · other racks ${oppTiles}`);
}
setVisible(v) {
[this.img, this.g, this.summary, this.head, ...this.letters.flatMap(l => l.group)].forEach(o => o.setVisible(v));
}
destroy() { [this.img, this.g, this.summary, this.head, ...this.letters.flatMap(l => l.group)].forEach(o => o.destroy()); }
}
// ── Seats ─────────────────────────────────────────────────────────────────────
export class Seats {
/** opps: the opponent objects from the room (portrait data), by seat-1 */
constructor(scene, state, opps) {
this.scene = scene;
this.plates = [];
state.players.forEach((p, seat) => {
if (seat === 0) { this.plates.push(this.humanPlate(p)); return; }
this.plates.push(this.oppPlate(p, seat, opps[seat - 1]));
});
}
oppPlate(p, seat, opp) {
const s = this.scene, R = seatRect(seat - 1);
const o = { seat, rect: R, objs: [] };
const add = (x) => { o.objs.push(x); return x; };
add(s.add.image(R.x + R.w / 2, R.y + R.h / 2, 'wsm-seat').setDepth(DEPTH.furniture));
o.ring = add(s.add.graphics().setDepth(DEPTH.furniture + 1));
o.portrait = createOpponentPortrait(s, opp ?? { name: p.name }, R.x + 70, R.y + 70, 50, DEPTH.hud);
add(s.add.text(R.x + 136, R.y + 30, short(p.name, 16), { fontFamily: SERIF, fontSize: '22px', color: CREAM, fontStyle: 'bold' }).setOrigin(0, 0.5).setDepth(DEPTH.hud));
add(s.add.text(R.x + 136, R.y + 58, '★'.repeat(p.skill) + '☆'.repeat(5 - p.skill), { fontFamily: SANS, fontSize: '15px', color: GOLD }).setOrigin(0, 0.5).setDepth(DEPTH.hud));
o.score = add(s.add.text(R.x + R.w - 22, R.y + 40, '0', { fontFamily: SERIF, fontSize: '40px', color: GOLD, fontStyle: 'bold' }).setOrigin(1, 0.5).setDepth(DEPTH.hud));
o.clock = add(s.add.text(R.x + R.w - 22, R.y + 80, '', { fontFamily: SANS, fontSize: '16px', color: CREAM }).setOrigin(1, 0.5).setDepth(DEPTH.hud));
o.think = add(s.add.text(R.x + 136, R.y + 86, '', { fontFamily: SERIF, fontSize: '15px', color: '#e9d9b0', fontStyle: 'italic' }).setOrigin(0, 0.5).setDepth(DEPTH.hud));
o.rackX = R.x + 136; o.rackY = R.y + R.h - 34;
add(s.add.image(o.rackX + 150, o.rackY + 4, 'wsm-orack').setDepth(DEPTH.hud + 1));
o.backs = [];
for (let i = 0; i < 7; i++) {
const b = s.add.image(o.rackX + 26 + i * 41, o.rackY - 6, 'wsm-back').setDepth(DEPTH.hud);
o.backs.push(b); o.objs.push(b);
}
return o;
}
humanPlate(p) {
const s = this.scene, R = HUMAN;
const o = { seat: 0, rect: R, objs: [] };
const add = (x) => { o.objs.push(x); return x; };
add(s.add.image(R.x + R.w / 2, R.y + R.h / 2, 'wsm-hplate').setDepth(DEPTH.furniture));
o.ring = add(s.add.graphics().setDepth(DEPTH.furniture + 1));
o.portrait = createPlayerPortrait(s, R.x + 66, R.y + 66, 46, DEPTH.hud, 'ScrabbleGame');
add(s.add.text(R.x + 128, R.y + 34, short(p.name, 14), { fontFamily: SERIF, fontSize: '22px', color: CREAM, fontStyle: 'bold' }).setOrigin(0, 0.5).setDepth(DEPTH.hud));
o.score = add(s.add.text(R.x + R.w - 20, R.y + 44, '0', { fontFamily: SERIF, fontSize: '42px', color: GOLD, fontStyle: 'bold' }).setOrigin(1, 0.5).setDepth(DEPTH.hud));
o.clock = add(s.add.text(R.x + R.w - 20, R.y + 86, '', { fontFamily: SANS, fontSize: '16px', color: CREAM }).setOrigin(1, 0.5).setDepth(DEPTH.hud));
o.think = add(s.add.text(R.x + 128, R.y + 66, '', { fontFamily: SERIF, fontSize: '15px', color: '#e9d9b0', fontStyle: 'italic' }).setOrigin(0, 0.5).setDepth(DEPTH.hud));
o.info = add(s.add.text(R.x + 22, R.y + R.h - 30, '', { fontFamily: SERIF, fontSize: '14px', color: '#cdbf9c' }).setOrigin(0, 0.5).setDepth(DEPTH.hud));
return o;
}
update(state, { active = null, hints = null } = {}) {
for (const o of this.plates) {
const p = state.players[o.seat];
o.score.setText(String(p.score));
o.clock.setText(p.timeLeft == null ? '' : `⏱ ${fmtClock(p.timeLeft)}`).setColor(p.timeLeft != null && p.timeLeft < 0 ? '#ff8f7a' : p.timeLeft != null && p.timeLeft < 60000 ? '#ffd27a' : CREAM);
if (o.backs) o.backs.forEach((b, i) => b.setVisible(i < p.rack.length));
o.ring.clear();
if (o.seat === active && !state.over) {
o.ring.lineStyle(3, GOLD_N, 0.95);
o.ring.strokeRoundedRect(o.rect.x - 3, o.rect.y - 3, o.rect.w + 6, o.rect.h + 6, 16);
o.ring.lineStyle(8, GOLD_N, 0.18);
o.ring.strokeRoundedRect(o.rect.x - 7, o.rect.y - 7, o.rect.w + 14, o.rect.h + 14, 20);
}
if (o.info) {
const bits = [];
if (p.bingos) bits.push(`${p.bingos} bingo${p.bingos > 1 ? 's' : ''}`);
if (p.best) bits.push(`best ${p.best.word} ${p.best.score}`);
if (hints != null) bits.push(hints === Infinity ? 'coach: practice' : `${hints} hint${hints === 1 ? '' : 's'} left`);
o.info.setText(bits.join(' · '));
}
}
}
plate(seat) { return this.plates[seat]; }
setThinking(seat, text) { this.plates[seat]?.think.setText(text ?? ''); }
portrait(seat) { return this.plates[seat]?.portrait; }
setVideos(visible) { for (const o of this.plates) o.portrait?.setVideoVisible?.(visible); }
/** World point of a seat's rack (where tiles leave from / return to). */
rackPoint(seat, i = 3) {
const o = this.plates[seat];
if (!o?.backs) return { x: 960, y: 932 };
return { x: o.backs[Math.min(6, i)].x, y: o.backs[0].y };
}
destroy() { for (const o of this.plates) { o.portrait?.destroy?.(); o.objs.forEach(x => x.destroy()); } }
}
// ── Preview tag + hover tip ───────────────────────────────────────────────────
export class PreviewTag {
constructor(scene) {
this.scene = scene;
this.c = scene.add.container(0, 0).setDepth(DEPTH.tip - 2).setVisible(false);
this.g = scene.add.graphics();
this.score = scene.add.text(0, -9, '', { fontFamily: SERIF, fontSize: '24px', color: INK, fontStyle: 'bold' }).setOrigin(0.5);
this.words = scene.add.text(0, 14, '', { fontFamily: SERIF, fontSize: '12px', color: '#5a4a32' }).setOrigin(0.5);
this.c.add([this.g, this.score, this.words]);
}
show(x, y, score, words, tone = 'ok') {
this.score.setText(`+${score}`);
const w = words.join(' · ');
this.words.setText(w.length > 34 ? `${w.slice(0, 33)}…` : w);
const ww = Math.max(70, this.score.width + 24, this.words.width + 20), hh = 52;
const fill = tone === 'bad' ? 0xf1c9bd : tone === 'unknown' ? 0xf0e6cc : 0xf6ecd0;
const edge = tone === 'bad' ? 0x9b2f25 : tone === 'unknown' ? 0x7a6f5e : 0x3d6b3a;
this.g.clear();
this.g.fillStyle(0x000000, 0.3); this.g.fillRoundedRect(-ww / 2 + 2, -hh / 2 + 4, ww, hh, 8);
this.g.fillStyle(fill, 1); this.g.fillRoundedRect(-ww / 2, -hh / 2, ww, hh, 8);
this.g.lineStyle(2, edge, 0.9); this.g.strokeRoundedRect(-ww / 2 + 3, -hh / 2 + 3, ww - 6, hh - 6, 6);
this.score.setColor(tone === 'bad' ? '#9b2f25' : INK);
this.c.setPosition(Math.max(ww / 2 + 4, Math.min(1916 - ww / 2, x)), Math.max(hh / 2 + 70, y)).setVisible(true);
}
hide() { this.c.setVisible(false); }
}
export class HoverTip {
constructor(scene) {
this.c = scene.add.container(0, 0).setDepth(DEPTH.tip).setVisible(false);
this.g = scene.add.graphics();
this.t = scene.add.text(0, 0, '', { fontFamily: SERIF, fontSize: '15px', color: CREAM, align: 'center', lineSpacing: 2 }).setOrigin(0.5);
this.c.add([this.g, this.t]);
}
show(x, y, text) {
if (this._last === text && this.c.visible) { this.c.setPosition(this.clampX(x), y); return; }
this._last = text;
this.t.setText(text);
const w = this.t.width + 22, h = this.t.height + 14;
this.w = w;
this.g.clear();
this.g.fillStyle(0x140c06, 0.92); this.g.fillRoundedRect(-w / 2, -h / 2, w, h, 7);
this.g.lineStyle(1, GOLD_N, 0.6); this.g.strokeRoundedRect(-w / 2, -h / 2, w, h, 7);
this.c.setPosition(this.clampX(x), y).setVisible(true);
}
clampX(x) { const w = this.w ?? 100; return Math.max(w / 2 + 4, Math.min(1916 - w / 2, x)); }
hide() { this.c.setVisible(false); this._last = null; }
}
/** The tiles-left tag hanging from the bag. */
export function bagTag(scene) {
const t = scene.add.text(BAG.x, BAG.y + BAG.h / 2 + 4, '', { fontFamily: SERIF, fontSize: '16px', color: CREAM, fontStyle: 'bold', backgroundColor: '#2b1a10', padding: { x: 8, y: 3 } })
.setOrigin(0.5).setDepth(DEPTH.hud);
return t;
}
export { SEAT };

View File

@ -0,0 +1,107 @@
// Wordsmith layout — pure geometry (no Phaser) so the verifier can check it.
//
// ┌──────── bookshelf band: title plaque · rule/clock note · top buttons ────────┐
// │ opponent seats │ │ score sheet │
// │ (portrait, │ the board (15×15) │ (one column a player,│
// │ score, clock, │ on its turntable │ a row a round) │
// │ rack backs) │ │ │
// │ tile tracker │ status line │ │
// │ human plate │ [btns] [ your rack ] [btns][PLAY] │ bag dictionary │
// └──────────────────────────────────────────────────────────────────────────────┘
import { BOARD_SIZE } from './ScrabbleTiles.js';
export const W = 1920, H = 1080;
export const SHELF_H = 64;
export const SQ = 48;
export const GRID = SQ * BOARD_SIZE; // 720
export const FRAME = 22;
export const BOARD = { cx: 960, cy: 452 };
export const GRID_X0 = BOARD.cx - GRID / 2; // 600
export const GRID_Y0 = BOARD.cy - GRID / 2; // 92
export const BOARD_PX = GRID + FRAME * 2; // 764 (board texture)
export const STATUS_Y = 856;
export const RACK = { cx: 960, cy: 932, tile: 58, gap: 5, w: 480, h: 96 };
export const RACK_TILE_Y = RACK.cy - 6;
export const BTN_W = 132, BTN_H = 44;
export const BUTTONS = {
recall: { x: 500, y: 908 },
shuffle: { x: 642, y: 908 },
sort: { x: 500, y: 960 },
hint: { x: 642, y: 960 },
exchange: { x: 1278, y: 908 },
pass: { x: 1420, y: 908 },
play: { x: 1349, y: 960, w: 274 },
};
export const TOP_BUTTONS = { y: 32, w: 104, h: 40, xs: [1488, 1602, 1716, 1830], keys: ['rules', 'card', 'settings', 'menu'] };
export const TITLE = { x: 960, y: 32 };
export const NOTE = { x: 34, y: 32 };
export const SEAT = { x: 28, w: 520, h: 168, y0: 84, gap: 12 };
export const seatRect = (i) => ({ x: SEAT.x, y: SEAT.y0 + i * (SEAT.h + SEAT.gap), w: SEAT.w, h: SEAT.h });
export const TRACKER = { x: 28, y: 628, w: 520, h: 236 };
export const HUMAN = { x: 28, y: 880, w: 390, h: 176 };
export const SHEET = { x: 1372, y: 76, w: 520, h: 694 };
export const BAG = { x: 1588, y: 926, w: 150, h: 160 };
export const DICT = { x: 1790, y: 936, w: 186, h: 136 };
/** Board square → centre in world space (turntable at rest). */
export function squareCenter(row, col) {
return { x: GRID_X0 + col * SQ + SQ / 2, y: GRID_Y0 + row * SQ + SQ / 2 };
}
/** …and in board-local space (origin at the board centre). */
export function squareLocal(row, col) {
return { x: (col - (BOARD_SIZE - 1) / 2) * SQ, y: (row - (BOARD_SIZE - 1) / 2) * SQ };
}
/** Board-local point → square, or null. */
export function squareAtLocal(x, y) {
const col = Math.floor((x + GRID / 2) / SQ), row = Math.floor((y + GRID / 2) / SQ);
if (row < 0 || col < 0 || row >= BOARD_SIZE || col >= BOARD_SIZE) return null;
return { row, col };
}
export function rackSlotX(i, n = 7) {
const span = n * RACK.tile + (n - 1) * RACK.gap;
return RACK.cx - span / 2 + RACK.tile / 2 + i * (RACK.tile + RACK.gap);
}
export function rackIndexAt(x, n) {
const span = n * RACK.tile + (n - 1) * RACK.gap;
const i = Math.round((x - (RACK.cx - span / 2 + RACK.tile / 2)) / (RACK.tile + RACK.gap));
return Math.max(0, Math.min(Math.max(0, n - 1), i));
}
export function inRackZone(x, y) {
return y > GRID_Y0 + GRID + 10 && Math.abs(x - RACK.cx) < RACK.w / 2 + 70;
}
// Turntable lean toward the active seat (degrees). Human sits at the bottom.
export function seatLean(seatIndexOnScreen, human) {
if (human) return 0;
return [2.6, 3.4, 4.2][seatIndexOnScreen] ?? 3;
}
/** Every fixed HUD rect, for the verifier's overlap checks. */
export function hudFurniture() {
const r = (name, x, y, w, h, overlapOk = []) => ({ name, x, y, w, h, overlapOk });
const c = (name, cx, cy, w, h, ok) => r(name, cx - w / 2, cy - h / 2, w, h, ok);
const out = [
r('board', BOARD.cx - BOARD_PX / 2, BOARD.cy - BOARD_PX / 2, BOARD_PX, BOARD_PX),
c('rack', RACK.cx, RACK.cy, RACK.w, RACK.h),
c('status', BOARD.cx, STATUS_Y, 700, 26),
r('tracker', TRACKER.x, TRACKER.y, TRACKER.w, TRACKER.h),
r('human', HUMAN.x, HUMAN.y, HUMAN.w, HUMAN.h),
r('sheet', SHEET.x, SHEET.y, SHEET.w, SHEET.h),
c('bag', BAG.x, BAG.y, BAG.w, BAG.h),
c('dict', DICT.x, DICT.y, DICT.w, DICT.h),
c('title', TITLE.x, TITLE.y, 360, 52),
];
for (let i = 0; i < 3; i++) { const s = seatRect(i); out.push(r(`seat${i}`, s.x, s.y, s.w, s.h)); }
for (const [k, b] of Object.entries(BUTTONS)) out.push(c(`btn-${k}`, b.x, b.y, b.w ?? BTN_W, BTN_H));
TOP_BUTTONS.xs.forEach((x, i) => out.push(c(`top-${TOP_BUTTONS.keys[i]}`, x, TOP_BUTTONS.y, TOP_BUTTONS.w, TOP_BUTTONS.h)));
return out;
}

View File

@ -1,9 +1,13 @@
// Pure Scrabble rules: board model, tile bag, move legality, word extraction,
// and scoring. No Phaser, no DOM, no network. The scene owns the mutable game
// state (board, bag, racks, scores) and calls these helpers.
// Wordsmith (slug `scrabble`) rules. Pure: no Phaser, no DOM, no network.
//
// Board model: board[row][col] is null (empty) or { letter:'A', blank:false }.
// Placement: { row, col, letter, blank } — a tentative tile the player dragged.
// The bottom half of this file is the game state machine: a plain, JSON-safe
// `state` object (seeded RNG included, so a saved game resumes exactly) moved
// along by createGame / submitPlay / acceptPending / challengePending /
// exchangeTiles / passTurn. The scene renders it; the verifier soaks it.
//
// Board model: board[row][col] is null (empty) or { letter:'A', blank:false,
// seat, move } (seat/move: who played it, on which log entry).
// Placement: { row, col, letter, blank } — a tile being played.
import {
BOARD_SIZE, RACK_SIZE, BLANK, LETTER_VALUES, LETTER_DISTRIBUTION,
@ -177,3 +181,347 @@ export function scoreMove(board, placements) {
if (placements.length === RACK_SIZE) total += 50;
return total;
}
// ── Game state machine ────────────────────────────────────────────────────────
export const RULES = {
friendly: { label: 'Friendly', blurb: 'Words are checked as you play. A wrong word just bounces back.' },
double: { label: 'Double challenge', blurb: 'Anyone may try any word. A phony that is challenged comes off; a wrong challenge loses the challenger their next turn.' },
five: { label: '5-point challenge', blurb: 'Anyone may try any word. A phony that is challenged comes off; a wrong challenge gives the player 5 points.' },
};
export const SCORELESS_LIMIT = 6;
export const OVERTIME_PENALTY = 10; // points per started overtime minute
export const MIN_BAG_TO_EXCHANGE = RACK_SIZE;
// Seeded PRNG kept inside the state so saves resume identically.
export function nextRandom(state) {
let a = (state.rng = (state.rng + 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;
}
// Draw one tile at random from the bag (a hand reaching in).
function drawOne(state) {
if (!state.bag.length) return null;
const i = Math.floor(nextRandom(state) * state.bag.length);
return state.bag.splice(i, 1)[0];
}
function drawN(state, n) {
const out = [];
for (let k = 0; k < n && state.bag.length; k++) out.push(drawOne(state));
return out;
}
// Rank for the opening draw: a blank beats everything, then A … Z.
export function drawRank(token) {
return token === BLANK ? -1 : token.charCodeAt(0) - 65;
}
/**
* players: [{ name, kind:'human'|'ai', skill?, id? }]
* opts: { seed, rule:'friendly'|'double'|'five', clockMin: 0 (off) | minutes }
*/
export function createGame(players, { seed = (Math.random() * 2 ** 32) >>> 0, rule = 'friendly', clockMin = 0 } = {}) {
const state = {
v: 1,
seed: seed >>> 0,
rng: seed >>> 0,
rule: RULES[rule] ? rule : 'friendly',
clockMs: clockMin > 0 ? clockMin * 60000 : 0,
board: createEmptyBoard(),
bag: createBag(),
players: players.map((p, i) => ({
seat: i,
name: p.name ?? `Player ${i + 1}`,
kind: p.kind ?? 'ai',
skill: p.skill ?? 3,
id: p.id ?? null,
rack: [],
score: 0,
timeLeft: clockMin > 0 ? clockMin * 60000 : null,
skipNext: false,
bingos: 0,
best: null, // { word, score }
plays: 0,
})),
firstDraw: [], // rounds of [{ seat, token }]
firstSeat: 0,
turn: 0,
moveNo: 0,
scoreless: 0,
log: [],
pending: null,
over: false,
end: null,
};
drawForFirst(state);
// Deal seven each, starting with the first player.
const n = state.players.length;
for (let k = 0; k < n; k++) {
const p = state.players[(state.firstSeat + k) % n];
p.rack = drawN(state, RACK_SIZE);
}
state.turn = state.firstSeat;
return state;
}
// Everyone draws a tile; nearest to A goes first (blank beats all). Ties redraw.
function drawForFirst(state) {
let contenders = state.players.map(p => p.seat);
for (let round = 0; round < 20 && contenders.length > 1; round++) {
const draws = contenders.map(seat => ({ seat, token: drawOne(state) }));
state.firstDraw.push(draws);
for (const d of draws) state.bag.push(d.token); // tiles go back in the bag
const best = Math.min(...draws.map(d => drawRank(d.token)));
contenders = draws.filter(d => drawRank(d.token) === best).map(d => d.seat);
}
state.firstSeat = contenders[0];
}
export function current(state) { return state.players[state.turn]; }
export function isFirstMove(state) { return isBoardEmpty(state.board); }
export function canExchange(state) { return state.bag.length >= MIN_BAG_TO_EXCHANGE; }
// Main (longest-axis) word string for a set of placements.
export function mainWordOf(words) {
if (!words?.length) return '';
return words[0].word ?? words[0];
}
/** Geometry + scoring check for a play on the current board. */
export function checkPlay(state, placements) {
const res = validateMove(state.board, placements, { firstMove: isFirstMove(state) });
if (!res.ok) return res;
const score = scoreMove(state.board, placements);
return { ok: true, words: res.words.map(w => w.word), wordCells: res.words, score, bingo: placements.length === RACK_SIZE };
}
function tokenFor(p) { return p.blank ? BLANK : p.letter; }
function removeFromRack(rack, tokens) {
const r = rack.slice();
for (const t of tokens) {
const i = r.indexOf(t);
if (i === -1) return null;
r.splice(i, 1);
}
return r;
}
function pushLog(state, entry) {
const e = { n: state.log.length, moveNo: state.moveNo, ...entry };
state.log.push(e);
return e;
}
/**
* Put a play on the board. Friendly rule: commits at once. Challenge rules: the
* tiles sit on the board as `state.pending` until acceptPending/challengePending.
* Returns { ok, error?, pending?, entry? }. Word validity is the caller's job
* under the friendly rule (the scene checks the dictionary first).
*/
export function submitPlay(state, seat, placements, extra = {}) {
if (state.over) return { ok: false, error: 'The game is over.' };
if (state.pending) return { ok: false, error: 'A play is waiting to be accepted.' };
if (seat !== state.turn) return { ok: false, error: 'Not your turn.' };
const p = state.players[seat];
const chk = checkPlay(state, placements);
if (!chk.ok) return chk;
const rack = removeFromRack(p.rack, placements.map(tokenFor));
if (!rack) return { ok: false, error: 'Those tiles are not on the rack.' };
p.rack = rack;
const move = state.log.length;
for (const pl of placements) state.board[pl.row][pl.col] = { letter: pl.letter, blank: !!pl.blank, seat, move };
state.pending = {
seat, placements: placements.map(x => ({ ...x })), words: chk.words, score: chk.score,
bingo: chk.bingo, move, extra,
};
if (state.rule === 'friendly') return { ok: true, pending: false, ...acceptPending(state) };
return { ok: true, pending: true };
}
/** The pending play stands: score it, draw replacements, move on. */
export function acceptPending(state, { penaltyBonus = 0, challengedBy = null } = {}) {
const pd = state.pending;
if (!pd) return { ok: false };
const p = state.players[pd.seat];
const total = pd.score + penaltyBonus;
p.score += pd.score;
p.plays++;
if (pd.bingo) p.bingos++;
const main = pd.words[0] ?? '';
if (!p.best || pd.score > p.best.score) p.best = { word: main, score: pd.score };
const drawn = drawN(state, RACK_SIZE - p.rack.length);
p.rack.push(...drawn);
state.scoreless = pd.score > 0 ? 0 : state.scoreless + 1;
state.pending = null;
const entry = pushLog(state, {
seat: pd.seat, type: 'play', word: main, words: pd.words, score: pd.score,
placements: pd.placements, bingo: pd.bingo, drew: drawn.length, total: p.score,
challengedBy, ...pd.extra,
});
if (penaltyBonus) {
p.score += penaltyBonus;
pushLog(state, { seat: pd.seat, type: 'bonus', score: penaltyBonus, total: p.score, challengedBy, note: 'challenge bonus' });
}
state.moveNo++;
if (p.rack.length === 0 && state.bag.length === 0) { endGame(state, 'out', pd.seat); return { ok: true, entry, drawn, over: true }; }
advance(state);
return { ok: true, entry, drawn, over: state.over };
}
/**
* `challenger` disputes the pending play. `isValid(word)` is the dictionary.
* → { ok, phony:boolean, invalid:[words], entry }
*/
export function challengePending(state, challenger, isValid) {
const pd = state.pending;
if (!pd) return { ok: false };
const invalid = pd.words.filter(w => !isValid(w));
if (invalid.length) {
// Phony: the tiles come back, the turn scores nothing.
const p = state.players[pd.seat];
for (const pl of pd.placements) state.board[pl.row][pl.col] = null;
p.rack.push(...pd.placements.map(tokenFor));
state.pending = null;
state.scoreless++;
const entry = pushLog(state, {
seat: pd.seat, type: 'phony', word: pd.words[0], words: pd.words, invalid, score: 0,
placements: pd.placements, total: p.score, challengedBy: challenger,
});
state.moveNo++;
advance(state);
return { ok: true, phony: true, invalid, entry };
}
// The play is good: the challenger pays.
if (state.rule === 'five') {
const r = acceptPending(state, { penaltyBonus: 5, challengedBy: challenger });
return { ok: true, phony: false, invalid: [], entry: r.entry };
}
state.players[challenger].skipNext = true;
const r = acceptPending(state, { challengedBy: challenger });
return { ok: true, phony: false, invalid: [], entry: r.entry };
}
export function exchangeTiles(state, seat, tokens) {
if (state.over || state.pending || seat !== state.turn) return { ok: false, error: 'Not your turn.' };
if (!canExchange(state)) return { ok: false, error: `Exchanges need at least ${MIN_BAG_TO_EXCHANGE} tiles in the bag.` };
if (!tokens.length) return { ok: false, error: 'Choose at least one tile.' };
const p = state.players[seat];
const rack = removeFromRack(p.rack, tokens);
if (!rack) return { ok: false, error: 'Those tiles are not on the rack.' };
const drawn = drawN(state, tokens.length); // draw first, then return the old ones
p.rack = [...rack, ...drawn];
state.bag.push(...tokens);
state.scoreless++;
const entry = pushLog(state, { seat, type: 'exchange', count: tokens.length, tiles: tokens.slice(), score: 0, total: p.score });
state.moveNo++;
advance(state);
return { ok: true, drawn, entry };
}
export function passTurn(state, seat) {
if (state.over || state.pending || seat !== state.turn) return { ok: false, error: 'Not your turn.' };
state.scoreless++;
const entry = pushLog(state, { seat, type: 'pass', score: 0, total: state.players[seat].score });
state.moveNo++;
advance(state);
return { ok: true, entry };
}
function advance(state) {
if (state.over) return;
if (state.scoreless >= SCORELESS_LIMIT) { endGame(state, 'scoreless'); return; }
const n = state.players.length;
state.turn = (state.turn + 1) % n;
// A player who lost a challenge sits this turn out.
for (let guard = 0; guard < n * 2 && state.players[state.turn].skipNext; guard++) {
const p = state.players[state.turn];
p.skipNext = false;
state.scoreless++;
pushLog(state, { seat: p.seat, type: 'lost', score: 0, total: p.score });
state.moveNo++;
if (state.scoreless >= SCORELESS_LIMIT) { endGame(state, 'scoreless'); return; }
state.turn = (state.turn + 1) % n;
}
}
/** Spend `ms` of `seat`'s clock (tournament clock only). */
export function spendClock(state, seat, ms) {
const p = state.players[seat];
if (p?.timeLeft == null || state.over) return;
p.timeLeft -= ms;
}
export function overtimePenalty(timeLeft) {
if (timeLeft == null || timeLeft >= 0) return 0;
return Math.ceil(-timeLeft / 60000) * OVERTIME_PENALTY;
}
/** Finish: rack penalties, the out bonus, overtime, ranking. */
export function endGame(state, reason, outSeat = null) {
if (state.over) return state.end;
const adj = state.players.map(() => 0);
let bonus = 0;
for (const p of state.players) {
if (p.seat === outSeat) continue;
const v = rackValue(p.rack);
if (v) {
adj[p.seat] -= v;
bonus += v;
p.score -= v;
pushLog(state, { seat: p.seat, type: 'rack', score: -v, tiles: p.rack.slice(), total: p.score });
}
}
if (outSeat != null && bonus) {
const o = state.players[outSeat];
o.score += bonus;
adj[outSeat] += bonus;
pushLog(state, { seat: outSeat, type: 'out', score: bonus, total: o.score });
}
for (const p of state.players) {
const pen = overtimePenalty(p.timeLeft);
if (pen) {
p.score -= pen;
adj[p.seat] -= pen;
pushLog(state, { seat: p.seat, type: 'clock', score: -pen, total: p.score });
}
}
const order = state.players.slice().sort((a, b) => b.score - a.score).map(p => p.seat);
const top = state.players[order[0]].score;
const winners = order.filter(s => state.players[s].score === top);
state.over = true;
state.end = { reason, outSeat, adj, order, winners };
return state.end;
}
/** Tiles `seat` hasn't seen: the bag plus every other rack. { token: count } */
export function unseenFor(state, seat) {
const left = { ...LETTER_DISTRIBUTION };
for (const row of state.board) for (const c of row) if (c) left[c.blank ? BLANK : c.letter]--;
for (const t of state.players[seat].rack) left[t]--;
return left;
}
export function unseenCount(state, seat) {
return Object.values(unseenFor(state, seat)).reduce((a, b) => a + b, 0);
}
/** Every tile accounted for? (bag + racks + board === the full set) */
export function tileCensus(state) {
const c = {};
const add = (t) => { c[t] = (c[t] ?? 0) + 1; };
state.bag.forEach(add);
state.players.forEach(p => p.rack.forEach(add));
for (const row of state.board) for (const cell of row) if (cell) add(cell.blank ? BLANK : cell.letter);
for (const [t, n] of Object.entries(LETTER_DISTRIBUTION)) if ((c[t] ?? 0) !== n) return { ok: false, token: t, have: c[t] ?? 0, want: n };
return { ok: true };
}
/** A serialisable board for the AI (letters + blank flags only). */
export function plainBoard(board) {
return board.map(row => row.map(cell => (cell ? { letter: cell.letter, blank: !!cell.blank } : null)));
}

View File

@ -0,0 +1,142 @@
// Wordsmith sounds — small Web Audio synths (no files). Silent when muted or
// without Web Audio.
//
// clack(scene, k) a wooden tile set down on the board (k 0..1 = weight)
// rackTap(scene) a tile nudged along the rack
// rattle(scene) the rack shuffled
// rustle(scene) a hand in the velvet bag
// pencil(scene, len) the score written on the sheet
// pageFlip(scene) the dictionary consulted
// bingoChime(scene) seven tiles out
// thunk(scene) a play that bounced (not a word / not legal)
// tick(scene) the tournament clock in its last minute
function ctxOf(scene) {
const sm = scene?.sound;
if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null;
return sm.context;
}
const noiseCache = new WeakMap();
function noise(ac) {
if (noiseCache.has(ac)) return noiseCache.get(ac);
const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ac, buf);
return buf;
}
function out(scene, ac, gain) {
const sm = scene.sound;
const node = sm.masterVolumeNode ?? sm.destination ?? null;
const g = ac.createGain();
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
g.connect(node ?? ac.destination);
return g;
}
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003 } = {}) {
const o = ac.createOscillator(); o.type = type;
o.frequency.setValueAtTime(f, t0);
if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d);
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(a, t0 + attack);
g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03);
}
function hiss(ac, dest, t0, f, vol = 1, d = 0.03, q = 3, type = 'bandpass') {
const n = ac.createBufferSource(); n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.value = f; bp.Q.value = q;
const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02);
}
const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } };
const semi = (f, n) => f * Math.pow(2, n / 12);
export function clack(scene, k = 0.6) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.16 + k * 0.1), t = ac.currentTime + 0.002;
const f = 900 + Math.random() * 500;
tone(ac, dest, t, f, { type: 'triangle', a: 0.9, d: 0.05, glide: 0.7 });
tone(ac, dest, t, f * 2.3, { type: 'sine', a: 0.3, d: 0.03 });
hiss(ac, dest, t, 2600 + Math.random() * 800, 0.9, 0.035, 2.2);
tone(ac, dest, t + 0.004, 180 + Math.random() * 40, { type: 'sine', a: 0.5 * k, d: 0.07 });
});
}
export function rackTap(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.08), t = ac.currentTime + 0.002;
tone(ac, dest, t, 1500 + Math.random() * 300, { type: 'triangle', a: 0.7, d: 0.03 });
hiss(ac, dest, t, 3400, 0.6, 0.02, 3);
});
}
export function rattle(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.1), t = ac.currentTime + 0.003;
for (let i = 0; i < 9; i++) {
const tt = t + i * 0.028 + Math.random() * 0.012;
tone(ac, dest, tt, 1100 + Math.random() * 900, { type: 'triangle', a: 0.5, d: 0.025 });
hiss(ac, dest, tt, 3000 + Math.random() * 1500, 0.5, 0.018, 3);
}
});
}
export function rustle(scene, ms = 380) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.12), t = ac.currentTime + 0.003;
const n = Math.max(4, Math.round(ms / 45));
for (let i = 0; i < n; i++) hiss(ac, dest, t + i * (ms / 1000 / n) + Math.random() * 0.02, 900 + Math.random() * 1600, 0.5 + Math.random() * 0.4, 0.07, 0.9, 'bandpass');
// tiles knocking inside
for (let i = 0; i < 3; i++) tone(ac, dest, t + 0.05 + Math.random() * ms / 1000, 700 + Math.random() * 500, { type: 'triangle', a: 0.25, d: 0.03 });
});
}
export function pencil(scene, len = 3) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003;
for (let i = 0; i < Math.min(9, len + 2); i++) hiss(ac, dest, t + i * 0.06 + Math.random() * 0.02, 3600 + Math.random() * 1200, 0.8, 0.045, 2.2);
});
}
export function pageFlip(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.12), t = ac.currentTime + 0.003;
for (let i = 0; i < 3; i++) hiss(ac, dest, t + i * 0.09, 1800 - i * 300, 0.8, 0.16, 0.7, 'bandpass');
hiss(ac, dest, t + 0.3, 900, 0.6, 0.08, 0.8, 'lowpass');
});
}
export function bingoChime(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.13), t = ac.currentTime + 0.01;
[0, 4, 7, 12, 16].forEach((n, i) => {
tone(ac, dest, t + i * 0.08, semi(523.25, n), { type: 'sine', a: 0.8, d: 0.9 });
tone(ac, dest, t + i * 0.08, semi(523.25, n + 12), { type: 'sine', a: 0.18, d: 0.5 });
});
});
}
export function thunk(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.14), t = ac.currentTime + 0.003;
tone(ac, dest, t, 150, { type: 'sine', a: 0.9, d: 0.16, glide: 0.7 });
tone(ac, dest, t + 0.09, 120, { type: 'sine', a: 0.7, d: 0.18, glide: 0.7 });
});
}
export function tick(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.002;
tone(ac, dest, t, 2400, { type: 'square', a: 0.3, d: 0.012 });
});
}

View File

@ -1,6 +1,6 @@
// Standard English Scrabble tile data and the 15×15 premium-square layout.
// Pure data + tiny helpers — no Phaser, no DOM. The server mirrors the values
// and layout it needs in server/words/scrabbleEngine.js.
// Wordsmith (slug `scrabble`) tile data: the standard 100-tile English set and
// the 15×15 premium-square layout. Pure data + tiny helpers, no Phaser or DOM.
// The move engine (src/words/scrabbleEngine.js) imports these directly.
export const BOARD_SIZE = 15;
export const CENTER = 7; // center square (0-indexed) — first move must cover it
@ -29,7 +29,7 @@ export function tileValue(letter, isBlank = false) {
}
// ── Premium-square layout ────────────────────────────────────────────────────
// Compact, human-verifiable map (symmetric standard Scrabble board):
// Compact, human-verifiable map (the standard symmetric layout):
// 3 = triple word 2 = double word t = triple letter d = double letter
// The center (7,7) is a double word and is rendered with a star.
const LAYOUT = [

View File

@ -0,0 +1,127 @@
# Wordsmith: A Tutorial by Edith
*Good evening, and welcome to the Reading Room. I'm Edith. I've kept the stacks here for thirty-one years, and on Thursday nights, once the last patron has gone, the staff pull this board out under the green lamp. I'll warn you now: the dictionary on the table is not decoration. Sit down, draw a tile, and I'll show you how it all works.*
---
## What Is This Game?
Wordsmith is the classic crossword tile game for **2–4 players**. Everyone keeps seven lettered tiles on a rack. On your turn you lay tiles on the 15×15 board to make words that link up with the words already there, crossword-style. Each tile carries a point value in its corner, and the coloured squares multiply your score.
When the bag is empty and someone plays their last tile, the game ends. Highest score wins.
---
## Setting Up
- **The bag** holds 100 wooden tiles: 98 letters and **2 blanks**. A blank can stand for any letter but scores nothing.
- **Who goes first:** everyone draws one tile. Whoever is closest to **A** starts (a blank beats everything), and the tiles go back in the bag. Ties draw again.
- Everyone then draws **seven tiles** onto their rack.
---
## Your Turn
You do one of three things:
1. **Play a word.** Place tiles in a **single row or a single column**, with no gaps (tiles already on the board can fill the gaps). Every string of two or more touching letters must be a real word, across and down.
2. **Exchange tiles.** Throw back any number of tiles and draw replacements. You can only do this if **at least 7 tiles** are left in the bag, and it uses your turn.
3. **Pass.** You score nothing and keep your rack.
**The first word** must cover the **star** in the centre. Every later word must touch a tile that's already on the board.
After you play, draw back up to seven tiles from the bag.
---
## Scoring
Add up the values of every letter in each word you formed, then apply the coloured squares:
| Square | What it does |
|---|---|
| **Double letter** (teal) | that tile's value ×2 |
| **Triple letter** (plum) | that tile's value ×3 |
| **Double word** (ochre, and the centre star) | the whole word ×2 |
| **Triple word** (green leather) | the whole word ×3 |
- Premium squares count **only on the turn a tile is first placed on them**. After that, they're ordinary.
- If one tile sits on a premium square and forms two words (one across, one down), the premium counts **for both words**.
- Letter multipliers are applied before word multipliers.
- **Bingo!** Play all seven tiles in one turn and you get a **50-point bonus**.
*A little librarian's secret: the best players don't hunt for long words. They hunt for the triple-letter square next to a vowel, and they keep an S or a blank in reserve.*
---
## Placing Tiles
There are two ways to put tiles down. Use whichever feels natural.
- **Drag** a tile from your rack onto a square. Drag it back to the rack, or to another square, to change your mind. You can also drag tiles along the rack to rearrange them.
- **Click and type:** click an empty square and an arrow appears. Click the same square again to switch between across and down. Then just type your letters; the arrow hops over tiles already on the board.
- **Backspace** takes back the last tile.
- **Enter** plays the word.
- **Esc** recalls everything.
- **Space** shuffles your rack.
- If you type a letter you don't have but you hold a blank, the blank becomes that letter. Type **?** to choose a blank on purpose.
While you build a play, a little paper tag shows the **score** and **every word** you'd make. With the Friendly rule, the tag turns red if a word isn't in the dictionary.
**Blanks** stay blank on the board, with their letter pencilled in, just as you'd do at a real table.
---
## The Word Rules
You'll find these in **Settings**. They take effect from your next game.
- **Friendly (the default).** The dictionary checks every play as you make it. If a word isn't acceptable, your tiles simply bounce back and you can try again.
- **Double challenge.** Any word may be played, even a made-up one (a *phony*). After each play, the other players may **challenge**.
- If a word is a phony, the tiles come off the board and the player scores nothing for the turn.
- If every word is good, the **challenger loses their next turn**.
- **5-point challenge.** Like double challenge, but a challenge that fails gives the player **5 bonus points** instead of costing the challenger a turn.
When an opponent plays under a challenge rule, you get a few seconds to choose **Accept** or **Challenge!** (Enter or C). My dear colleagues bluff now and then, especially the newer ones. The sharpest of them will happily challenge *you*, too.
---
## Ending the Game
The game ends when:
- **the bag is empty and a player uses their last tile**, or
- there have been **six scoreless turns in a row** (passes, exchanges, plays that were challenged off).
Then the tally:
- Each player **loses the value of the tiles left on their rack**.
- If someone went out, they **gain the total** of everyone else's leftovers.
- With the tournament clock on, each player loses **10 points for every minute** they went over time.
---
## The Table and Its Helpers
- **Score sheet (right).** Every turn is pencilled in: the word, its points and a running total. Click a row to see that word flash on the board.
- **Tile tracker (left).** The tournament player's secret weapon: every tile you've seen is crossed off, so what's left is in the bag or on your opponents' racks.
- **The bag.** It sags as it empties, and the tag tells you how many tiles remain.
- **The dictionary.** Click it to open the **Word Judge**: type any words and it tells you whether they're acceptable. (It's closed while a challenge is pending.)
- **Card (top).** The two-letter word list and the tile distribution. Every serious player knows the twos.
- **Hint / Coach.** Shows the coach's favourite play as glowing ghost tiles; click one to use it. "3 hints a game" is the default. **Practice** mode is unlimited and lists the top three plays.
- **The coach's review.** At the end of the game, the coach shows where you could have scored more: "you played X for 24, the best was Y for 71."
- **Turntable.** The board turns a few degrees toward whoever is playing. You can switch this off in Settings.
- **Tournament clock.** Optional: 25, 15 or 10 minutes each.
---
## The Opponents
Skill changes how my colleagues play, not how lucky they are:
- **★ / ★★:** casual players. They know everyday words, see only part of the board, and like short words.
- **★★★:** a club player. They know the two- and three-letter lists and think a little about which tiles they keep.
- **★★★★:** a strong club player. They know the whole dictionary and value their rack, though now and then they miss a spot.
- **★★★★★:** an expert. They see everything, keep balanced racks, and read the endgame. You'll need your best.
*Now then. The lamp's on, the tea's poured, and I believe it's your draw.*

View File

@ -1,199 +1,684 @@
// Scrabble dictionary + AI move generator (runs in the browser).
// Wordsmith (slug `scrabble`) dictionary + move engine. Pure JS: no Phaser, no DOM.
//
// Scoring/extraction is imported from the SAME pure modules the game scene uses
// (no Phaser/DOM deps there) so the AI ranks moves exactly as the client scores
// them. Move generation is a line-scan DFS over a trie: for every line and every
// legal word-start we walk the trie, consuming board tiles or placing rack tiles
// (with cross-checks), recording each terminal word that connects to the board.
// Move generation is the classic anchor-based search (Appel & Jacobson): for every
// row (and every column, via a transposed view) we find the empty squares that
// touch a tile, the "anchors". From each anchor we grow a left part over the empty,
// non-anchor squares before it, then extend right through the anchor, placing
// rack tiles where the cross-checks allow and reading board tiles as we pass.
// Scoring is done incrementally during the search, so there's no board copying.
//
// Each move comes back as
// { placements:[{row,col,letter,blank}], score, word, words:[main, ...cross], leave:[tokens], dir }
//
// The AI layers equity (score + rack-leave value), defence, endgame lookahead,
// skill-limited vocabulary, limited "vision" and noise on top of the generator.
// Challenge-rule games also get plausible phonies and challenge judgement.
import { scoreMove } from '../games/scrabble/ScrabbleLogic.js';
import { BOARD_SIZE, RACK_SIZE, BLANK, CENTER } from '../games/scrabble/ScrabbleTiles.js';
import { BOARD_SIZE, RACK_SIZE, BLANK, CENTER, LETTER_VALUES, PREMIUM } from '../games/scrabble/ScrabbleTiles.js';
let TRIE = null;
let WORD_SET = null;
const N = BOARD_SIZE;
const ALL = (1 << 26) - 1;
const LETTER = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));
const VOWELS = new Set(['A', 'E', 'I', 'O', 'U']);
const VAL = new Int8Array(26);
for (let i = 0; i < 26; i++) VAL[i] = LETTER_VALUES[String.fromCharCode(65 + i)] ?? 0;
// ── Dictionaries ──────────────────────────────────────────────────────────────
function newNode() { return { c: Object.create(null), t: false }; }
function popcnt(x) {
x -= (x >>> 1) & 0x55555555;
x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
return (((x + (x >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;
}
// Compact node: t = terminal, m = 26-bit child-letter mask, n = children in letter order.
function compact(node) {
const keys = Object.keys(node.c).sort();
let m = 0;
const n = new Array(keys.length);
keys.forEach((k, i) => { m |= 1 << (k.charCodeAt(0) - 65); n[i] = compact(node.c[k]); });
return { t: node.t, m, n };
}
/** Child of compact `node` for letter index `li` (0–25), or null. */
export function child(node, li) {
const bit = 1 << li;
if (!(node.m & bit)) return null;
return node.n[popcnt(node.m & (bit - 1))];
}
function walk(node, str) {
for (let i = 0; i < str.length && node; i++) node = child(node, str.charCodeAt(i) - 65);
return node;
}
export function buildTrie(words) {
const root = newNode();
for (const w of words) {
let node = root;
for (let i = 0; i < w.length; i++) {
const ch = w[i];
node = node.c[ch] || (node.c[ch] = newNode());
}
node.t = true;
}
return compact(root);
}
const DICT = {
full: null, // { set, trie }
commonRanked: null, // string[], frequency order, ENABLE-valid
tiers: new Map(), // tier → { set, trie }
phony: new Map(), // tier → { set, trie } (tier words + plausible phonies)
};
export function initScrabbleDictionary(words) {
WORD_SET = words instanceof Set ? words : new Set(words);
TRIE = { children: Object.create(null), terminal: false };
for (const w of WORD_SET) {
let node = TRIE;
for (const ch of w) {
node = node.children[ch] || (node.children[ch] = { children: Object.create(null), terminal: false });
}
node.terminal = true;
const set = words instanceof Set ? words : new Set(words);
DICT.full = { set, trie: buildTrie(set) };
DICT.tiers.clear();
DICT.phony.clear();
}
// Frequency-ordered common words (data/wordlists/common.txt). Optional: without it
// every tier falls back to the full list.
export function initScrabbleCommonWords(words) {
if (!DICT.full) return { common: 0 };
const seen = new Set();
DICT.commonRanked = [];
for (const raw of words) {
const w = String(raw).trim().toUpperCase();
if (w.length >= 2 && w.length <= 15 && DICT.full.set.has(w) && !seen.has(w)) { seen.add(w); DICT.commonRanked.push(w); }
}
DICT.tiers.clear();
DICT.phony.clear();
return { common: DICT.commonRanked.length };
}
export function isValidWord(word) {
return WORD_SET?.has(word) ?? false;
return DICT.full?.set.has(String(word).toUpperCase()) ?? false;
}
export function dictionaryReady() {
return TRIE !== null;
export function dictionaryReady() { return DICT.full !== null; }
export function twoLetterWords() {
if (!DICT.full) return [];
return [...DICT.full.set].filter(w => w.length === 2).sort();
}
// ── Helpers ───────────────────────────────────────────────────────────────────
// The inflections a casual player knows once they know the stem.
function inflections(w) {
const out = [w + 'S', w + 'ES', w + 'D', w + 'ED', w + 'ER', w + 'ERS', w + 'EST', w + 'LY', w + 'ING', w + 'INGS'];
if (w.endsWith('E')) out.push(w.slice(0, -1) + 'ING', w.slice(0, -1) + 'INGS');
if (w.endsWith('Y')) out.push(w.slice(0, -1) + 'IES', w.slice(0, -1) + 'IED', w.slice(0, -1) + 'IER', w.slice(0, -1) + 'IEST');
return out;
}
const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
// common.txt has no two-letter words, so the everyday ones are listed here.
const EVERYDAY_TWOS = {
1: 'AH AM AN AS AT BE BY DO GO HE HI IF IN IS IT ME MY NO OF OH ON OR OX SO TO UP US WE',
2: 'AD AX HA HM ID LA LO MA MU NU OD OE OP OW OY PA PE PI RE TA TI UH UM YA YE YO',
};
// Skill vocabulary tiers:
// 1 the ~5,000 most common words (+ their inflections)
// 2 all ~16k common words (+ inflections)
// 3 tier 2 + every 2- and 3-letter word (a club player who learnt the lists)
// 4 the full ENABLE list
export function tierFor(skill) {
const s = Number(skill) || 3;
return s <= 1 ? 1 : s === 2 ? 2 : s === 3 ? 3 : 4;
}
function tierDict(tier) {
if (!DICT.full) return null;
if (tier >= 4 || !DICT.commonRanked) return DICT.full;
if (DICT.tiers.has(tier)) return DICT.tiers.get(tier);
const full = DICT.full.set;
const base = tier === 1 ? DICT.commonRanked.slice(0, 5000) : DICT.commonRanked;
const set = new Set();
for (const w of base) {
set.add(w);
for (const f of inflections(w)) if (full.has(f)) set.add(f);
}
for (const t of tier === 1 ? [1] : [1, 2]) for (const w of EVERYDAY_TWOS[t].split(' ')) if (full.has(w)) set.add(w);
if (tier >= 3) for (const w of full) if (w.length <= 3) set.add(w);
const d = { set, trie: buildTrie(set) };
DICT.tiers.set(tier, d);
return d;
}
// Plausible non-words a casual player might try: a common stem with a regular
// inflection or prefix it doesn't actually take (FUNNIED, RESLEEP, UNSTRONG,
// WINDLESS…), built with real English spelling rules so they *look* right.
const CONS_Y = /[^AEIOU]Y$/;
const SIBILANT = /(S|X|Z|CH|SH)$/;
const INFLECTED = /(S|ED|ING|LY|EST)$/;
const FUNCTION_WORDS = new Set(('THAT THIS WITH FROM HAVE WERE BEEN THEY THEM THEIR WHAT WHEN WHERE WHICH WHILE WHOM WHOSE ' +
'WOULD COULD SHOULD MIGHT MUST SHALL THERE THESE THOSE ABOUT ABOVE AFTER AGAIN ALSO INTO JUST LIKE MORE MOST MUCH ONLY ' +
'OVER SOME SUCH THAN THEN VERY WELL WILL YOUR YOURS EACH EVEN EVER HERE ONCE UPON UNTIL UNLESS BEING DOES DONE SAID ' +
'BOTH EITHER NEITHER OTHER ANOTHER AMONG BEFORE BEHIND BELOW BESIDE BETWEEN BEYOND DURING EXCEPT SINCE THOUGH THROUGH ' +
'TOWARD TOWARDS UNDER WITHIN WITHOUT ALMOST ALREADY ALWAYS NEVER OFTEN PERHAPS QUITE RATHER SOON STILL TODAY YESTERDAY ' +
'TOMORROW HIMSELF HERSELF ITSELF MYSELF OURSELVES THEMSELVES EVERY EVERYONE SOMEONE ANYONE NOTHING SOMETHING ANYTHING ' +
'EVERYTHING WHETHER INDEED ENOUGH MANY FEW SEVERAL').split(' '));
function plausibleForms(w) {
const out = [];
const cy = CONS_Y.test(w);
const stemY = cy ? w.slice(0, -1) + 'I' : w;
out.push(SIBILANT.test(w) ? w + 'ES' : cy ? stemY + 'ES' : w + 'S');
if (w.endsWith('E')) out.push(w + 'D', w + 'R', w.slice(0, -1) + 'ING');
else out.push(stemY + 'ED', stemY + 'ER', w + 'ING');
out.push(stemY + 'NESS', w + 'LESS', 'RE' + w, 'UN' + w);
return out;
}
function phonyDict(tier) {
if (!DICT.full) return null;
if (DICT.phony.has(tier)) return DICT.phony.get(tier);
const base = tierDict(tier);
const full = DICT.full.set;
const stems = (DICT.commonRanked ?? []).slice(0, tier === 1 ? 3000 : 8000)
.filter(w => w.length >= 4 && w.length <= 8 && !INFLECTED.test(w) && !FUNCTION_WORDS.has(w));
const set = new Set(base.set);
let added = 0;
for (const w of stems) {
for (const p of plausibleForms(w)) {
if (p.length > 15 || full.has(p) || set.has(p)) continue;
set.add(p);
added++;
}
if (added > 30000) break;
}
const d = { set, trie: buildTrie(set), phonies: added };
DICT.phony.set(tier, d);
return d;
}
export function vocabularyFor(skill) { return tierDict(tierFor(skill))?.set ?? null; }
// ── Generator ─────────────────────────────────────────────────────────────────
function rackCounts(rack) {
const counts = Object.create(null);
for (const t of rack) counts[t] = (counts[t] ?? 0) + 1;
return counts;
const cnt = new Int8Array(27);
for (const t of rack) {
if (t === BLANK) cnt[26]++;
else { const i = t.charCodeAt(0) - 65; if (i >= 0 && i < 26) cnt[i]++; }
}
return cnt;
}
// Take a tile for letter L, preferring a real tile over a blank. Mutates counts.
function takeTile(counts, L) {
if (counts[L] > 0) { counts[L]--; return { token: L, blank: false }; }
if (counts[BLANK] > 0) { counts[BLANK]--; return { token: BLANK, blank: true }; }
return null;
}
function giveTile(counts, t) { counts[t.token]++; }
// Perpendicular word constraint at an empty square. null = no constraint
// (no tiles above/below); otherwise a Set of letters that complete a valid
// cross word. An empty Set means nothing legal can be placed here.
function crossCheckSet(board, r, c, cdr, cdc, cache) {
const key = `${r},${c},${cdr},${cdc}`;
if (cache.has(key)) return cache.get(key);
let pre = '';
let 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 result;
if (!pre && !suf) {
result = null;
} else {
result = new Set();
for (const L of LETTERS) if (WORD_SET.has(pre + L + suf)) result.add(L);
}
cache.set(key, result);
return result;
function countsToTokens(cnt) {
const out = [];
for (let i = 0; i < 26; i++) for (let k = 0; k < cnt[i]; k++) out.push(String.fromCharCode(65 + i));
for (let k = 0; k < cnt[26]; k++) out.push(BLANK);
return out;
}
// DFS from (R,C) along (mdr,mdc); cross axis (cdr,cdc). Records every terminal,
// board-connected word that places ≥1 new tile.
function dfs(ctx, R, C, node, placed, usedExisting, touchedCross) {
const { board, counts, mdr, mdc, cdr, cdc, firstMove, moves, cache } = ctx;
const inBounds = R >= 0 && C >= 0 && R < BOARD_SIZE && C < BOARD_SIZE;
const cell = inBounds ? board[R][C] : undefined;
if (inBounds && cell) { // read an existing tile
const child = node.children[cell.letter];
if (child) dfs(ctx, R + mdr, C + mdc, child, placed, true, touchedCross);
return;
// Precompute per-line data for one orientation. `get(r,c)` → cell|null in that
// orientation; row r is the line, c runs along it; the cross axis is r±1.
function lineInfo(get, r, trie) {
const cells = new Array(N), blanks = new Array(N);
const mask = new Int32Array(N), csum = new Int16Array(N), hasCross = new Uint8Array(N), anchor = new Uint8Array(N);
const pre = new Array(N), suf = new Array(N);
for (let c = 0; c < N; c++) {
const cell = get(r, c);
cells[c] = cell ? cell.letter : null;
blanks[c] = cell ? !!cell.blank : false;
}
// square is empty or off-board → the word may end here
if (node.terminal && placed.length > 0) {
const connected = firstMove
? placed.some(p => p.row === CENTER && p.col === CENTER)
: (usedExisting || touchedCross);
if (connected) moves.push(placed.slice());
for (let c = 0; c < N; c++) {
if (cells[c]) continue;
const up = get(r - 1, c), dn = get(r + 1, c);
anchor[c] = (up || dn || (c > 0 && cells[c - 1]) || (c < N - 1 && cells[c + 1])) ? 1 : 0;
if (!up && !dn) { mask[c] = ALL; continue; }
let p = '', s = '', sum = 0, rr = r - 1;
while (get(rr, c)) { const x = get(rr, c); p = x.letter + p; if (!x.blank) sum += VAL[x.letter.charCodeAt(0) - 65]; rr--; }
rr = r + 1;
while (get(rr, c)) { const x = get(rr, c); s += x.letter; if (!x.blank) sum += VAL[x.letter.charCodeAt(0) - 65]; rr++; }
hasCross[c] = 1; csum[c] = sum; pre[c] = p; suf[c] = s;
const node = walk(trie, p);
let m = 0;
if (node) {
let bits = node.m, i = 0;
while (bits) {
const low = bits & -bits; bits ^= low;
const n2 = walk(node.n[i++], s);
if (n2 && n2.t) m |= low;
}
if (!inBounds) return; // cannot place past the edge
const cc = crossCheckSet(board, R, C, cdr, cdc, cache);
for (const L in node.children) {
if (cc && !cc.has(L)) continue;
const tile = takeTile(counts, L);
if (!tile) continue;
placed.push({ row: R, col: C, letter: L, blank: tile.blank });
dfs(ctx, R + mdr, C + mdc, node.children[L], placed, usedExisting, touchedCross || cc !== null);
placed.pop();
giveTile(counts, tile);
}
mask[c] = m;
}
return { cells, blanks, mask, csum, hasCross, anchor, pre, suf };
}
function scanLine(ctx, startList) {
for (const [sr, sc] of startList) {
const lr = sr - ctx.mdr, lc = sc - ctx.mdc;
if (ctx.board[lr]?.[lc]) continue; // mid-word start → skip (covered by an earlier start)
dfs(ctx, sr, sc, TRIE, [], false, false);
}
}
function generateMoves(board, rack, firstMove) {
const counts = rackCounts(rack);
const cache = new Map();
/**
* Every legal move for `rack` on `board`.
* opts: { firstMove, trie (default full), vision (0..1 share of anchors examined),
* rng, maxLen (longest main word considered) }
*/
export function generateMoves(board, rack, opts = {}) {
const trie = opts.trie ?? DICT.full?.trie;
if (!trie) return [];
const firstMove = opts.firstMove ?? !board.some(row => row.some(Boolean));
const vision = opts.vision ?? 1;
const rng = opts.rng ?? Math.random;
const maxLen = opts.maxLen ?? N;
const cnt = rackCounts(rack);
const rackN = rack.length;
const moves = [];
const directions = firstMove
? [
{ mdr: 0, mdc: 1, cdr: 1, cdc: 0, line: Array.from({ length: BOARD_SIZE }, (_, c) => [CENTER, c]) },
{ mdr: 1, mdc: 0, cdr: 0, cdc: 1, line: Array.from({ length: BOARD_SIZE }, (_, r) => [r, CENTER]) },
]
: buildFullScanDirections();
const across = (r, c) => (r >= 0 && r < N && c >= 0 && c < N ? board[r][c] : null);
const down = (r, c) => (r >= 0 && r < N && c >= 0 && c < N ? board[c][r] : null);
const orients = firstMove ? [[across, false]] : [[across, false], [down, true]];
for (const d of directions) {
const ctx = { board, counts, mdr: d.mdr, mdc: d.mdc, cdr: d.cdr, cdc: d.cdc, firstMove, moves, cache };
scanLine(ctx, d.line);
for (const [get, transposed] of orients) {
for (let r = 0; r < N; r++) {
if (firstMove && r !== CENTER) continue;
const L = lineInfo(get, r, trie);
if (firstMove) { L.anchor.fill(0); L.anchor[CENTER] = 1; }
const prem = (c) => (transposed ? PREMIUM[c][r] : PREMIUM[r][c]);
const work = L.cells.slice();
const placed = []; // [{ col, li, blank }]
let mainSum = 0, mainMult = 1, crossTotal = 0;
let anchorCol = 0, startCol = 0;
const record = (endCol) => {
const len = endCol - startCol;
if (len < 2 || len > maxLen) return;
// A lone tile that also makes a word along the other axis is found by that scan.
if (transposed && placed.length === 1) {
const c = placed[0].col;
if (across(c, r - 1) || across(c, r + 1)) return; // board[c][r±1]: its across neighbours
}
let score = mainSum * mainMult + crossTotal;
if (placed.length === RACK_SIZE) score += 50;
const word = work.slice(startCol, endCol).join('');
const words = [word];
const placements = new Array(placed.length);
for (let i = 0; i < placed.length; i++) {
const p = placed[i];
const letter = LETTER[p.li];
if (L.hasCross[p.col]) words.push(L.pre[p.col] + letter + L.suf[p.col]);
placements[i] = transposed
? { row: p.col, col: r, letter, blank: p.blank }
: { row: r, col: p.col, letter, blank: p.blank };
}
moves.push({ placements, score, word, words, leave: countsToTokens(cnt), dir: transposed ? 'down' : 'across' });
};
// Rack availability as a letter mask (bit set while cnt[li] > 0).
let rackMask = 0;
for (let i = 0; i < 26; i++) if (cnt[i] > 0) rackMask |= 1 << i;
const avail = () => (cnt[26] > 0 ? ALL : rackMask);
// Use a blank only for a letter the rack doesn't hold: a blank standing in
// for a letter we have is never better (same or lower score, worse leave).
const take = (li) => {
if (cnt[li] > 0) { if (--cnt[li] === 0) rackMask &= ~(1 << li); return 0; }
if (cnt[26] > 0) { cnt[26]--; return 1; }
return -1;
};
const give = (li, blank) => {
if (blank) cnt[26]++;
else if (cnt[li]++ === 0) rackMask |= 1 << li;
};
const extend = (node, col) => {
if (col < N && L.cells[col]) {
const li = L.cells[col].charCodeAt(0) - 65;
const nx = child(node, li);
if (!nx) return;
const v = L.blanks[col] ? 0 : VAL[li];
mainSum += v;
extend(nx, col + 1);
mainSum -= v;
return;
}
if (node.t && col > anchorCol) record(col);
if (col >= N || placed.length >= rackN) return;
let bits = node.m & L.mask[col] & avail();
if (!bits) return;
const pm = prem(col);
while (bits) {
const low = bits & -bits; bits ^= low;
const li = 31 - Math.clz32(low);
const blank = take(li);
if (blank < 0) continue;
const v = blank ? 0 : VAL[li];
const lv = v * pm.letterMult;
mainSum += lv; mainMult *= pm.wordMult;
const cross = L.hasCross[col] ? (L.csum[col] + lv) * pm.wordMult : 0;
crossTotal += cross;
work[col] = LETTER[li];
placed.push({ col, li, blank: blank === 1 });
extend(node.n[popcnt(node.m & (low - 1))], col + 1);
placed.pop();
work[col] = null;
crossTotal -= cross;
mainSum -= lv; mainMult /= pm.wordMult;
give(li, blank === 1);
}
};
// Left part over empty non-anchor squares; `part` holds {li, blank} in order.
const part = [];
const leftPart = (node, limit) => {
// place the current left part at anchorCol-len..anchorCol-1 and extend
const len = part.length;
startCol = anchorCol - len;
let s = 0, wm = 1;
for (let i = 0; i < len; i++) {
const col = startCol + i, p = part[i], pm = prem(col);
s += (p.blank ? 0 : VAL[p.li]) * pm.letterMult; wm *= pm.wordMult;
work[col] = LETTER[p.li];
placed.push({ col, li: p.li, blank: p.blank });
}
mainSum += s; mainMult *= wm;
extend(node, anchorCol);
mainSum -= s; mainMult /= wm;
for (let i = 0; i < len; i++) { placed.pop(); work[startCol + i] = null; }
if (limit <= 0) return;
let bits = node.m & avail();
while (bits) {
const low = bits & -bits; bits ^= low;
const li = 31 - Math.clz32(low);
const blank = take(li);
if (blank < 0) continue;
part.push({ li, blank: blank === 1 });
leftPart(node.n[popcnt(node.m & (low - 1))], limit - 1);
part.pop();
give(li, blank === 1);
}
};
for (let a = 0; a < N; a++) {
if (!L.anchor[a]) continue;
if (vision < 1 && rng() > vision) continue;
anchorCol = a;
if (a > 0 && L.cells[a - 1]) {
// Prefix already on the board: read it, then extend from the anchor.
let s = a - 1;
while (s > 0 && L.cells[s - 1]) s--;
let node = trie, sum = 0;
for (let c = s; c < a && node; c++) {
const li = L.cells[c].charCodeAt(0) - 65;
node = child(node, li);
if (!L.blanks[c]) sum += VAL[li];
}
if (!node) continue;
startCol = s;
mainSum = sum; mainMult = 1; crossTotal = 0;
extend(node, a);
mainSum = 0;
} else {
let limit = 0;
for (let c = a - 1; c >= 0 && !L.cells[c] && !L.anchor[c]; c--) limit++;
limit = Math.min(limit, rackN - 1);
mainSum = 0; mainMult = 1; crossTotal = 0;
leftPart(trie, limit);
}
}
}
}
return moves;
}
function buildFullScanDirections() {
const across = { mdr: 0, mdc: 1, cdr: 1, cdc: 0, line: [] };
const down = { mdr: 1, mdc: 0, cdr: 0, cdc: 1, line: [] };
for (let r = 0; r < BOARD_SIZE; r++) for (let c = 0; c < BOARD_SIZE; c++) {
across.line.push([r, c]);
down.line.push([c, r]);
// ── Leave + equity ────────────────────────────────────────────────────────────
const TILE_LEAVE = {
[BLANK]: 25, S: 8, Z: 4, X: 3.5, E: 3.5, H: 1.5, R: 1.5, A: 1, C: 1, M: 0.5, D: 0.5, N: 0.5, T: 0.5,
L: 0, P: -0.5, Y: -0.5, K: -1, J: -2, I: -1.5, O: -1.5, G: -2, B: -2, F: -2, W: -3.5, U: -4, V: -5.5, Q: -7,
};
export function leaveValue(tokens) {
if (!tokens.length) return 0;
let v = 0, vow = 0, con = 0;
const seen = Object.create(null);
for (const t of tokens) {
v += TILE_LEAVE[t] ?? 0;
seen[t] = (seen[t] ?? 0) + 1;
if (t === BLANK) continue;
if (VOWELS.has(t)) vow++; else con++;
}
return [across, down];
for (const t in seen) {
const k = seen[t];
if (k < 2 || t === BLANK) continue;
const per = t === 'S' ? 2 : VOWELS.has(t) ? 4 : 3;
v -= per * (k - 1) * (k > 2 ? 1.4 : 1);
}
const n = vow + con;
if (n > 0) {
const ideal = n * 0.42;
v -= 2.5 * Math.pow(Math.abs(vow - ideal), 1.4);
if (n >= 3 && vow === 0) v -= 3;
if (n >= 3 && con === 0) v -= 4;
}
if (seen.Q && seen.U) v += 5;
return v;
}
// ── Public: choose a move for an AI player ─────────────────────────────────────
// board: 15×15 of null | { letter, blank }. rack: array of tokens ('A'…'Z','_').
// Returns { type:'play', placements, score, word } | { type:'exchange', tiles }
// | { type:'pass' }.
export function chooseMove({ board, rack, skill = 3, firstMove, bagCount = 0 }) {
if (!TRIE) return { type: 'pass' };
const rawMoves = generateMoves(board, rack, firstMove);
if (!rawMoves.length) return fallbackMove(rack, bagCount);
const scored = rawMoves
.map(placements => ({ placements, score: scoreMove(board, placements) }))
.filter(m => m.score > 0)
.sort((a, b) => b.score - a.score);
if (!scored.length) return fallbackMove(rack, bagCount);
const pick = scored[pickIndex(scored.length, skill)];
return { type: 'play', placements: pick.placements, score: pick.score, word: longestWord(pick.placements) };
export function rackValue(tokens) {
return tokens.reduce((s, t) => s + (t === BLANK ? 0 : (LETTER_VALUES[t] ?? 0)), 0);
}
// Map skill 1–5 onto a slice of the score-ranked move list (0 = best).
function pickIndex(n, skill) {
const ranges = {
5: [0, Math.min(1, n - 1)],
4: [0, Math.max(0, Math.ceil(n * 0.10) - 1)],
3: [Math.floor(n * 0.15), Math.ceil(n * 0.45)],
2: [Math.floor(n * 0.45), Math.ceil(n * 0.75)],
1: [Math.floor(n * 0.70), n - 1],
const TW_SQUARES = [];
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (PREMIUM[r][c].wordMult === 3) TW_SQUARES.push([r, c]);
// How many still-empty triple-word squares this move brings within reach (a tile
// within 3 squares in a straight, clear line) that weren't already in reach.
export function twExposure(board, placements) {
const placedAt = new Set(placements.map(p => p.row * N + p.col));
const filled = (r, c, withMove) => !!board[r]?.[c] || (withMove && placedAt.has(r * N + c));
let n = 0;
for (const [tr, tc] of TW_SQUARES) {
if (board[tr][tc] || placedAt.has(tr * N + tc)) continue;
const reach = (withMove) => {
for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
for (let k = 1; k <= 3; k++) {
const r = tr + dr * k, c = tc + dc * k;
if (r < 0 || c < 0 || r >= N || c >= N) break;
if (filled(r, c, withMove)) return true;
}
}
return false;
};
const [lo, hi] = ranges[skill] ?? ranges[3];
const a = Math.max(0, Math.min(lo, n - 1));
const b = Math.max(a, Math.min(hi, n - 1));
return a + Math.floor(Math.random() * (b - a + 1));
}
function longestWord(placements) {
// The display word: rebuild the main line from the placements alone is enough
// for a label; the client recomputes the authoritative words when applying.
return placements.map(p => p.letter).join('');
}
// No legal play: exchange when the bag can support it, otherwise pass.
function fallbackMove(rack, bagCount) {
if (bagCount >= RACK_SIZE) {
return { type: 'exchange', tiles: rack.slice(0, Math.min(rack.length, bagCount)) };
if (reach(true) && !reach(false)) n++;
}
return { type: 'pass' };
return n;
}
// ── Skill profiles ────────────────────────────────────────────────────────────
// Tuned with mirrored-seed self-play (tools/verifyWordsmith.js --ladder). Average
// self-play scores ≈ 226 / 280 / 354 / 410 / 418. Notes from tuning:
// - the leave term is worth ~30 points a game over pure greedy (67% head to head);
// - the simple TW-exposure "defence" penalty cost ~12 points, so it is off (0);
// - a sampled one-reply lookahead was neutral within noise, so it isn't used.
// Skill 4 is a strong club player who now and then misses a spot (vision, noise);
// skill 5 sees the whole board and looks ahead in the endgame.
export const PROFILES = {
1: { vision: 0.45, maxLen: 5, leaveW: 0, noise: 7, defense: 0, smartExchange: false, phony: 0.6, endgame: 0 },
2: { vision: 0.65, maxLen: 6, leaveW: 0.3, noise: 4.5, defense: 0, smartExchange: false, phony: 0.35, endgame: 0 },
3: { vision: 0.85, maxLen: 8, leaveW: 0.65, noise: 2.5, defense: 0, smartExchange: true, phony: 0.15, endgame: 1 },
4: { vision: 0.88, maxLen: 15, leaveW: 0.8, noise: 2.5, defense: 0, smartExchange: true, phony: 0, endgame: 1 },
5: { vision: 1, maxLen: 15, leaveW: 1, noise: 0, defense: 0, smartExchange: true, phony: 0, endgame: 2 },
};
// Chance the AI challenges a word that really is a phony / one it merely doesn't know.
const DETECT = { 1: 0.35, 2: 0.55, 3: 0.8, 4: 0.95, 5: 1 };
const DOUBT = { 1: 0.12, 2: 0.08, 3: 0.04, 4: 0, 5: 0 };
function gauss(rng) {
let u = 0, v = 0;
while (u === 0) u = rng();
while (v === 0) v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function applyTemp(board, placements) {
const b = board.map(row => row.slice());
for (const p of placements) b[p.row][p.col] = { letter: p.letter, blank: !!p.blank };
return b;
}
function bestScore(board, rack) {
let best = 0;
for (const m of generateMoves(board, rack, { firstMove: false })) if (m.score > best) best = m.score;
return best;
}
// Equity of a move for the given profile + situation.
function equity(m, ctx) {
const { profile, bagCount, board } = ctx;
let eq = m.score;
if (bagCount > 0) {
const w = profile.leaveW * (bagCount >= 7 ? 1 : 0.35 + 0.65 * bagCount / 7);
eq += w * leaveValue(m.leave);
if (profile.defense) eq -= profile.defense * 4 * twExposure(board, m.placements);
} else if (profile.endgame) {
const out = m.leave.length === 0;
eq += out ? 2 * (ctx.oppRackGuess ?? 10) : -1.2 * rackValue(m.leave);
}
return eq;
}
// Best tiles to keep for an exchange: the subset with the best leave.
export function bestKeep(rack) {
const n = rack.length;
let best = { keep: [], value: leaveValue([]) };
const seen = new Set();
for (let mask = 0; mask < (1 << n); mask++) {
const keep = [];
for (let i = 0; i < n; i++) if (mask & (1 << i)) keep.push(rack[i]);
if (keep.length === n) continue;
const key = keep.slice().sort().join('');
if (seen.has(key)) continue;
seen.add(key);
const v = leaveValue(keep);
if (v > best.value) best = { keep, value: v };
}
const left = rack.slice();
for (const t of best.keep) left.splice(left.indexOf(t), 1);
return { keep: best.keep, toss: left, value: best.value };
}
function exchangeMove(rack, profile, rng) {
if (profile.smartExchange) {
const { toss } = bestKeep(rack);
if (toss.length) return { type: 'exchange', tiles: toss };
}
// casual: keep blanks and S, toss the rest (or a random handful)
const toss = rack.filter(t => t !== BLANK && t !== 'S');
if (!toss.length) return { type: 'exchange', tiles: rack.slice(0, Math.max(1, rack.length - 1)) };
const k = Math.max(2, Math.min(toss.length, 3 + Math.floor(rng() * 5)));
return { type: 'exchange', tiles: toss.slice(0, k) };
}
/**
* Choose the AI's move.
* { board, rack, skill, firstMove, bagCount, rule ('friendly'|'double'|'five'),
* oppRacks (known exact racks when bag is empty & 1 opponent: [tokens]),
* oppRackGuess, rng }
* → { type:'play', placements, score, word, words, phony } | { type:'exchange', tiles } | { type:'pass' }
*/
export function chooseMove(args) {
const {
board, rack, skill = 3, firstMove = false, bagCount = 0, rule = 'friendly',
oppRacks = null, rng = Math.random,
} = args;
if (!DICT.full || !rack?.length) return { type: 'pass' };
const sk = Math.max(1, Math.min(5, Number(skill) || 3));
const profile = PROFILES[sk];
const tier = tierFor(sk);
const usePhony = rule !== 'friendly' && profile.phony > 0 && DICT.commonRanked && rng() < profile.phony;
const dict = usePhony ? phonyDict(tier) : tierDict(tier);
let moves = generateMoves(board, rack, { firstMove, trie: dict.trie, vision: profile.vision, rng, maxLen: profile.maxLen });
// A narrow view that finds nothing gets a second, full look (players do find *something*).
if (!moves.length && profile.vision < 1) moves = generateMoves(board, rack, { firstMove, trie: dict.trie, rng, maxLen: profile.maxLen });
if (!moves.length && profile.maxLen < N) moves = generateMoves(board, rack, { firstMove, trie: dict.trie, rng });
if (usePhony) {
for (const m of moves) m.phony = m.words.some(w => !DICT.full.set.has(w));
// Only bluff when the phony looks at least about as good as the honest best.
const honest = moves.filter(m => !m.phony);
const bestHonest = honest.reduce((b, m) => Math.max(b, m.score), 0);
moves = moves.filter(m => !m.phony || m.score >= bestHonest - 2);
}
const oppRackGuess = oppRacks?.length ? rackValue(oppRacks[0]) : 10;
const ctx = { profile, bagCount, board, oppRackGuess };
let best = null, bestEq = -Infinity;
if (moves.length) {
let scored = moves.map(m => ({ m, eq: equity(m, ctx) }));
// Endgame lookahead (skill 5, bag empty, one opponent with a known rack).
if (profile.endgame >= 2 && bagCount === 0 && oppRacks?.length === 1) {
scored.sort((a, b) => b.eq - a.eq);
const oppRack = oppRacks[0];
const oppVal = rackValue(oppRack);
scored = scored.slice(0, 14).map(({ m }) => {
const out = m.leave.length === 0;
if (out) return { m, eq: m.score + 2 * oppVal };
const after = applyTemp(board, m.placements);
const reply = generateMoves(after, oppRack, { firstMove: false });
let r = 0, oppOut = false;
for (const x of reply) { if (x.score > r) r = x.score; if (x.leave.length === 0) oppOut = true; }
const mine = rackValue(m.leave);
return { m, eq: m.score - r - (oppOut ? 2 * mine : mine) };
});
}
for (const s of scored) {
const e = s.eq + (profile.noise ? gauss(rng) * profile.noise : 0);
if (e > bestEq) { bestEq = e; best = s.m; }
}
}
// Exchange instead of a poor play (stronger players only, bag permitting).
if (bagCount >= RACK_SIZE && profile.smartExchange) {
const keep = bestKeep(rack);
const exEq = profile.leaveW * keep.value - 1;
if (!best || exEq > bestEq + 3) return { type: 'exchange', tiles: keep.toss.length ? keep.toss : rack.slice() };
}
if (!best) return bagCount >= RACK_SIZE ? exchangeMove(rack, profile, rng) : { type: 'pass' };
let placements = best.placements;
// Opening plays: the board is symmetric, so half the time play it down instead.
if (firstMove && rng() < 0.5) placements = placements.map(p => ({ ...p, row: p.col, col: p.row }));
return {
type: 'play', placements, score: best.score, word: best.word, words: best.words,
phony: !!best.phony,
};
}
// Hints / post-game review: the top `n` moves by raw score or by equity.
export function topMoves({ board, rack, firstMove = false, n = 3, by = 'equity', bagCount = 50 }) {
if (!DICT.full) return [];
const moves = generateMoves(board, rack, { firstMove });
const ctx = { profile: PROFILES[5], bagCount, board, oppRackGuess: 10 };
const keyed = moves.map(m => ({ ...m, equity: equity(m, ctx) }));
keyed.sort(by === 'score' ? (a, b) => b.score - a.score || b.equity - a.equity : (a, b) => b.equity - a.equity || b.score - a.score);
// drop duplicates that differ only by which blank/real tile — keep distinct words+positions
const out = [], seen = new Set();
for (const m of keyed) {
const key = m.placements.map(p => `${p.row},${p.col},${p.letter}`).sort().join('|');
if (seen.has(key)) continue;
seen.add(key);
out.push(m);
if (out.length >= n) break;
}
return out;
}
// Would an AI of `skill` challenge a play forming `words`?
export function aiWouldChallenge({ words, skill = 3, score = 0, rng = Math.random }) {
if (!DICT.full) return false;
const sk = Math.max(1, Math.min(5, Number(skill) || 3));
const phony = words.some(w => !DICT.full.set.has(w));
if (phony) return rng() < DETECT[sk];
const vocab = tierDict(tierFor(sk)).set;
const unknown = words.some(w => !vocab.has(w));
if (!unknown) return false;
return rng() < DOUBT[sk] * (score >= 30 ? 1.5 : 1);
}
export function invalidWords(words) {
return words.filter(w => !isValidWord(w));
}

View File

@ -2,7 +2,10 @@
// same engines, same response shapes — but the dictionaries are fetched once in
// the browser (see initWords) instead of read from disk, and routing happens via
// `handle(method, subpath, query, body)` instead of Express.
import { initScrabbleDictionary, isValidWord, chooseMove } from './scrabbleEngine.js';
import {
initScrabbleDictionary, initScrabbleCommonWords, isValidWord, chooseMove,
topMoves as scrabbleTopMoves, aiWouldChallenge, twoLetterWords,
} from './scrabbleEngine.js';
import { initGhostDictionary, initGhostCommonWords, judge as ghostJudge, chooseLetter as ghostChooseLetter, suggestWords as ghostSuggestWords } from './ghostEngine.js';
import {
initWordLadderDictionary,
@ -138,7 +141,7 @@ function loadWordLists(raw, commonRaw, crosswordBank, beeAnswersRaw = null) {
allWords.filter(w => w.length >= 2 && w.length <= 15 && /^[A-Z]+$/.test(w)),
);
initScrabbleDictionary(scrabbleWords);
console.log(`[words] loaded ${scrabbleWords.size} Scrabble words (2–15 letters)`);
console.log(`[words] loaded ${scrabbleWords.size} Wordsmith words (2–15 letters)`);
// Ghost dictionary: every ENABLE word of length >= 4 (shorter words don't count).
const ghostWords = allWords.filter(w => w.length >= 4 && /^[A-Z]+$/.test(w));
@ -174,6 +177,8 @@ function loadWordLists(raw, commonRaw, crosswordBank, beeAnswersRaw = null) {
// targets recognizable words instead of obscure ENABLE entries.
if (commonRaw) {
const commonWords = commonRaw.split('\n').map(w => w.trim().toUpperCase()).filter(Boolean);
const scrabbleCommon = initScrabbleCommonWords(commonWords);
console.log(`[words] loaded ${scrabbleCommon.common} Wordsmith common words for AI vocabulary tiers`);
const commonStats = initKiitosCommonWords(commonWords);
console.log(`[words] loaded ${commonStats.common} Kiitos common words for AI targeting`);
const common3 = commonWords.filter(w => /^[A-Z]{3}$/.test(w));
@ -296,10 +301,10 @@ router.post('/scrabble/validate', (req, res) => {
res.json({ valid: invalid.length === 0, invalid });
});
// POST /api/words/scrabble/ai-move { board, rack, skill, firstMove, bagCount }
// POST /api/words/scrabble/ai-move { board, rack, skill, firstMove, bagCount, rule, oppRacks }
// Returns the AI's chosen move: a play, an exchange, or a pass.
router.post('/scrabble/ai-move', (req, res) => {
const { board, rack, skill, firstMove, bagCount } = req.body ?? {};
const { board, rack, skill, firstMove, bagCount, rule, oppRacks } = req.body ?? {};
if (!Array.isArray(board) || !Array.isArray(rack)) {
return res.status(400).json({ error: 'board and rack are required' });
}
@ -309,10 +314,46 @@ router.post('/scrabble/ai-move', (req, res) => {
skill: Number(skill) || 3,
firstMove: !!firstMove,
bagCount: Number(bagCount) || 0,
rule: rule || 'friendly',
oppRacks: Array.isArray(oppRacks) ? oppRacks : null,
});
res.json(move);
});
// POST /api/words/scrabble/hint { board, rack, firstMove, bagCount, n, by }
// The coach: the top n plays (by equity unless by:'score').
router.post('/scrabble/hint', (req, res) => {
const { board, rack, firstMove, bagCount, n, by } = req.body ?? {};
if (!Array.isArray(board) || !Array.isArray(rack)) {
return res.status(400).json({ error: 'board and rack are required' });
}
const moves = scrabbleTopMoves({
board, rack, firstMove: !!firstMove, bagCount: Number(bagCount) || 0,
n: Math.max(1, Math.min(10, Number(n) || 3)), by: by === 'score' ? 'score' : 'equity',
});
res.json({ moves: moves.map(m => ({ placements: m.placements, score: m.score, word: m.word, words: m.words, leave: m.leave, equity: m.equity })) });
});
// POST /api/words/scrabble/judge { words: string[] } — the Word Judge
router.post('/scrabble/judge', (req, res) => {
const words = Array.isArray(req.body?.words) ? req.body.words : [];
const results = words.map(w => String(w).trim().toUpperCase()).filter(Boolean)
.map(word => ({ word, valid: isValidWord(word) }));
res.json({ results, valid: results.every(r => r.valid) });
});
// POST /api/words/scrabble/ai-challenge { words, skill, score }
// Would this AI challenge a play forming these words?
router.post('/scrabble/ai-challenge', (req, res) => {
const words = Array.isArray(req.body?.words) ? req.body.words.map(w => String(w).toUpperCase()) : [];
res.json({ challenge: aiWouldChallenge({ words, skill: Number(req.body?.skill) || 3, score: Number(req.body?.score) || 0 }) });
});
// GET /api/words/scrabble/two-letter — the reference card list
router.get('/scrabble/two-letter', (_req, res) => {
res.json({ words: twoLetterWords() });
});
// ── Kiitos ────────────────────────────────────────────────────────────────────
// POST /api/words/kiitos/validate { word, minLen?, prefix? }

502
tools/verifyWordsmith.js Normal file
View File

@ -0,0 +1,502 @@
// 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)));
}