diff --git a/assets/speech/convo/balam-brad.mp3 b/assets/speech/convo/balam-brad.mp3 new file mode 100644 index 0000000..5809792 Binary files /dev/null and b/assets/speech/convo/balam-brad.mp3 differ diff --git a/assets/speech/convo/balam-jerry.mp3 b/assets/speech/convo/balam-jerry.mp3 new file mode 100644 index 0000000..effa6a2 Binary files /dev/null and b/assets/speech/convo/balam-jerry.mp3 differ diff --git a/data/opponents.json b/data/opponents.json index f0332df..9c8e0d5 100644 --- a/data/opponents.json +++ b/data/opponents.json @@ -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", diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index b58ca3e..62ef1fc 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -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 }); diff --git a/src/games/scrabble/ScrabbleAI.js b/src/games/scrabble/ScrabbleAI.js index e215849..45afd47 100644 --- a/src/games/scrabble/ScrabbleAI.js +++ b/src/games/scrabble/ScrabbleAI.js @@ -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 }; } diff --git a/src/games/scrabble/ScrabbleArt.js b/src/games/scrabble/ScrabbleArt.js new file mode 100644 index 0000000..242f821 --- /dev/null +++ b/src/games/scrabble/ScrabbleArt.js @@ -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--

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- 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; + } +} diff --git a/src/games/scrabble/ScrabbleDialogs.js b/src/games/scrabble/ScrabbleDialogs.js new file mode 100644 index 0000000..da6ef0d --- /dev/null +++ b/src/games/scrabble/ScrabbleDialogs.js @@ -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; +} + diff --git a/src/games/scrabble/ScrabbleEndScreen.js b/src/games/scrabble/ScrabbleEndScreen.js new file mode 100644 index 0000000..34a7207 --- /dev/null +++ b/src/games/scrabble/ScrabbleEndScreen.js @@ -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()); } }; +} + diff --git a/src/games/scrabble/ScrabbleGame.js b/src/games/scrabble/ScrabbleGame.js index 2db6099..92db427 100644 --- a/src/games/scrabble/ScrabbleGame.js +++ b/src/games/scrabble/ScrabbleGame.js @@ -1,46 +1,42 @@ +// Wordsmith (slug `scrabble`) — the crossword tile game in a Reading Room. +// +// The rules live in ScrabbleLogic's JSON-safe `state`; this scene renders it and +// drives turns. Input: drag tiles (rack ↔ board, rack reorder), or click a +// square and type (arrow shows direction; Backspace, Enter, Esc, Space). AI +// opponents think, then lay tiles from their racks one by one. Challenge rules +// put a play on hold for a challenge window; the dictionary on the table is the +// referee (and, clicked, the Word Judge). + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { api } from '../../services/api.js'; import { auth } from '../../services/auth.js'; -import { Button } from '../../ui/Button.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { loadStats, recordGame, recordBest, bumpCount } from '../../ui/solitaire/SolitaireStats.js'; +import { PACE } from '../../ui/cardtable/AITiming.js'; +import { isValidWord } from '../../words/scrabbleEngine.js'; +import { BLANK, RACK_SIZE, PREMIUM, BOARD_SIZE } from './ScrabbleTiles.js'; +import * as LG from './ScrabbleLogic.js'; +import * as L from './ScrabbleLayout.js'; import { - createEmptyBoard, createBag, shuffle, drawTiles, isBoardEmpty, - applyPlacements, rackValue, validateMove, scoreMove, -} from './ScrabbleLogic.js'; -import { - BOARD_SIZE, RACK_SIZE, BLANK, LETTER_VALUES, premiumAt, isCenter, -} from './ScrabbleTiles.js'; -import { requestAIMove, nextThinkDelay } from './ScrabbleAI.js'; + ensureWordsmithArt, boardKey, makeTile, LibButton, + SERIF, CREAM, GOLD_N, PREMIUM_STYLE, GRAINS, +} from './ScrabbleArt.js'; +import * as SFX from './ScrabbleSound.js'; +import { ScoreSheet, TileTracker, Seats, PreviewTag, HoverTip, bagTag, DEPTH } from './ScrabbleHud.js'; +import * as DLG from './ScrabbleDialogs.js'; +import { showEndScreen } from './ScrabbleEndScreen.js'; +import { requestAIMove, requestHint, aiChallenges, twoLetterList, nextThinkDelay, layTiming } from './ScrabbleAI.js'; -// ── Layout ───────────────────────────────────────────────────────────────────── -const SQ = 50; // board square size -const BOARD_PX = SQ * BOARD_SIZE; // 750 -const BOARD_X0 = Math.round(GAME_WIDTH / 2 - BOARD_PX / 2); // 585 -const BOARD_Y0 = 90; -const RACK_TILE = 56; -const RACK_GAP = 6; -const RACK_Y = 915; -const STATUS_Y = 968; -const CONTROLS_Y = 1014; +const SLUG = 'scrabble'; +const SAVE_KEY = 'scrabble-save'; +const BEST_WORD_KEY = 'scrabble-best-word'; +const BOARD_TILE = L.SQ - 4; +const HINTS_PER_GAME = 3; +const VOWELS = 'AEIOU'; -const NOTE_X = 1360, NOTE_W = 540, NOTE_Y = 90, NOTE_H = 750; -const OPP_X0 = 60, OPP_X1 = 565; // left column bounds - -const DEPTH = { bg: 0, board: 1, grid: 2, panel: 4, tile: 6, tentative: 7, ui: 12, drag: 60, modal: 90, victory: 100 }; - -// Premium-square palette + label color -const PREM_STYLE = { - TW: { fill: 0xcf4b3e, text: '#ffffff' }, - DW: { fill: 0xe39aa0, text: '#3a2417' }, - TL: { fill: 0x2f6fb0, text: '#ffffff' }, - DL: { fill: 0x8fc1e3, text: '#23323f' }, - '': { fill: 0xbfa97e, text: '#5a4a28' }, -}; -const GRID_LINE = 0x6b5d3e; -const TILE_FILL = 0xf2e3b3, TILE_FILL_TENT = 0xfff0c0, TILE_STROKE = 0xb89b5e, TILE_INK = '#2a1f0c'; +let nextId = 1; +const newEntry = (token) => ({ id: nextId++, token, grain: Math.floor(Math.random() * GRAINS) }); export default class ScrabbleGame extends Phaser.Scene { constructor() { super('ScrabbleGame'); } @@ -48,886 +44,1335 @@ export default class ScrabbleGame extends Phaser.Scene { init(data) { this._initData = { ...data }; this.gameDef = data.game; - this.opponents = data.opponents ?? []; - - this.board = createEmptyBoard(); - this.bag = shuffle(createBag()); - - this.players = [ - { type: 'human', name: auth.user?.username ?? 'You', rack: [], score: 0, portrait: null }, - ...this.opponents.map(o => ({ - type: 'ai', name: o.name ?? 'CPU', skill: o.skill ?? 3, opp: o, rack: [], score: 0, portrait: null, - })), - ]; - this.turnIndex = 0; - this.tentative = []; // [{ row, col, token, letter, blank, obj }] - this.boardObjs = {}; // 'r,c' -> committed tile container - this.rackObjs = []; // rack tile containers (human) - this.oppFaceObjs = []; // per-opponent array of face-down tile containers - this.scorelessTurns = 0; - this.animating = false; - this.gameOver = false; + this.opponents = (data.opponents ?? []).slice(0, 3); + this.fresh = !!data.fresh; + this.gen = (this.gen ?? 0) + 1; + this.state = null; + this.hand = []; + this.tentative = []; + this.typed = []; + this.rackObjs = new Map(); + this.boardTiles = new Map(); + this.squareGrain = new Map(); + this.ghosts = []; + this.cursor = null; this.exchangeMode = false; this.exchangeSel = new Set(); - this.blankPicking = false; + this.press = null; + this.drag = null; + this.busy = true; + this.modal = null; + this.paused = false; + this.sortMode = 0; + this.seenLog = 0; + this.endUI = null; + this.challengeUI = null; } create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildParticleTexture(); - this.buildBackground(); + this.settings = DLG.loadSettings(); + this.sfx = SFX; + this.pace = PACE[this.settings.pace] ?? 1; + new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); + const players = 1 + this.opponents.length; + ensureWordsmithArt(this, { labels: this.settings.labels, patterns: this.settings.patterns, players }); + this.add.image(L.W / 2, L.H / 2, 'wsm-room').setDepth(DEPTH.room); + this.events.once('shutdown', () => this.teardown()); + this.boot(); + } + + async boot() { + const gen = this.gen; + this.twoLetter = await twoLetterList(); // also makes sure the dictionary is loaded + if (!this.alive(gen)) return; + const save = this.fresh ? null : loadSave(); + if (save && sameTable(save, this.opponents)) { + DLG.confirmDialog(this, 'Resume your game?', `You left a game in progress (move ${save.state.moveNo + 1}, you ${save.state.players[0].score} – ${save.state.players.slice(1).map(p => p.score).join(' – ')}).`, + 'Resume', () => this.startGame(save.state, { save }), { no: 'New game', onNo: () => { clearSave(); this.startGame(this.newState(), { fresh: true }); } }); + return; + } + this.startGame(this.newState(), { fresh: true }); + } + + newState() { + const players = [ + { name: auth.user?.username ?? 'You', kind: 'human', skill: 5 }, + ...this.opponents.map(o => ({ name: o.name ?? 'Opponent', kind: 'ai', skill: Math.max(1, Math.min(5, o.skill ?? 3)), id: o.id ?? null })), + ]; + return LG.createGame(players, { rule: this.settings.rule, clockMin: Number(this.settings.clock) || 0 }); + } + + // ── Build ────────────────────────────────────────────────────────────────── + + startGame(state, { fresh = false, save = null } = {}) { + this.state = state; + this.hintsLeft = save?.hintsLeft ?? (this.settings.coach === 'practice' ? Infinity : HINTS_PER_GAME); + if (this.settings.coach === 'off') this.hintsLeft = 0; this.buildBoard(); - this.buildOpponents(); - this.buildNotepad(); - this.buildRackTray(); - this.buildStatus(); - this.buildControls(); - this.setupDrag(); - - // Deal racks - for (const p of this.players) p.rack = drawTiles(this.bag, RACK_SIZE); - this.renderRack(); - this.renderOpponentRacks(); - this.updateNotepad(); - this.highlightActive(); - - this.beginTurn(); - } - - // ── Build: scenery ─────────────────────────────────────────────────────────── - - buildParticleTexture() { - if (this.textures.exists('scrabbleParticle')) return; - const g = this.make.graphics({ add: false }); - g.fillStyle(0xffffff, 1); - g.fillCircle(5, 5, 5); - g.generateTexture('scrabbleParticle', 10, 10); - g.destroy(); - } - - buildBackground() { - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(DEPTH.bg); - this.add.text(GAME_WIDTH / 2, 44, 'SCRABBLE', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); + this.seats = new Seats(this, state, this.opponents); + this.sheet = new ScoreSheet(this, state, { onRowClick: (e) => this.flashEntry(e) }); + this.tracker = new TileTracker(this); + this.tracker.setVisible(this.settings.tracker); + this.buildRack(); + this.buildButtons(); + this.buildProps(); + this.preview = new PreviewTag(this); + this.tip = new HoverTip(this); + this.status = this.add.text(L.BOARD.cx, L.STATUS_Y, '', { fontFamily: SERIF, fontSize: '19px', color: CREAM, fontStyle: 'italic' }).setOrigin(0.5).setDepth(DEPTH.hud); + this.status.setShadow(0, 2, 'rgba(0,0,0,0.8)', 4); + this.note = this.add.text(L.NOTE.x, L.NOTE.y, '', { fontFamily: SERIF, fontSize: '15px', color: '#e9d9b0' }).setOrigin(0, 0.5).setDepth(DEPTH.hud); + this.setupInput(); + // Hand: keep a saved order when resuming. + const rack = state.players[0].rack.slice(); + const order = save?.handOrder ?? null; + if (order && sameMultiset(order, rack)) this.hand = order.map(newEntry); + else this.hand = rack.map(newEntry); + this.seenLog = state.log.length; + this.renderAll(); + if (fresh) this.openingCeremony().then(() => this.beginTurn()); + else this.beginTurn(); } buildBoard() { - // backing frame - const frame = this.add.graphics().setDepth(DEPTH.board); - frame.fillStyle(0x3a3327, 1); - frame.fillRoundedRect(BOARD_X0 - 10, BOARD_Y0 - 10, BOARD_PX + 20, BOARD_PX + 20, 10); + this.boardC = this.add.container(L.BOARD.cx, L.BOARD.cy).setDepth(DEPTH.board); + this.boardImg = this.add.image(0, 0, boardKey(this.settings.labels, this.settings.patterns)); + this.lastG = this.add.graphics(); + this.boardC.add([this.boardImg, this.lastG]); + this.cursorG = this.add.graphics(); + this.boardC.add(this.cursorG); + } - const g = this.add.graphics().setDepth(DEPTH.grid); - for (let r = 0; r < BOARD_SIZE; r++) { - for (let c = 0; c < BOARD_SIZE; c++) { - const prem = premiumAt(r, c); - const style = PREM_STYLE[prem.label] ?? PREM_STYLE['']; - const x = BOARD_X0 + c * SQ; - const y = BOARD_Y0 + r * SQ; - g.fillStyle(style.fill, 1); - g.fillRect(x + 1, y + 1, SQ - 2, SQ - 2); - g.lineStyle(1, GRID_LINE, 0.8); - g.strokeRect(x + 1, y + 1, SQ - 2, SQ - 2); + rebakeBoard() { + const key = boardKey(this.settings.labels, this.settings.patterns); + ensureWordsmithArt(this, { labels: this.settings.labels, patterns: this.settings.patterns, players: this.state.players.length }); + this.boardImg.setTexture(key); + } - if (isCenter(r, c)) { - this.add.text(x + SQ / 2, y + SQ / 2, '★', { - fontFamily: 'Righteous', fontSize: '26px', color: '#3a2417', - }).setOrigin(0.5).setDepth(DEPTH.grid); - } else if (prem.label) { - this.add.text(x + SQ / 2, y + SQ / 2, prem.label, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: style.text, - }).setOrigin(0.5).setDepth(DEPTH.grid); + buildRack() { + this.rackImg = this.add.image(L.RACK.cx, L.RACK.cy + 5, 'wsm-rack').setDepth(DEPTH.furniture + 1); + this.rackName = this.add.text(L.RACK.cx, L.RACK.cy + 34, '', { fontFamily: SERIF, fontSize: '11px', color: '#3a2410', fontStyle: 'bold' }) + .setOrigin(0.5).setDepth(DEPTH.furniture + 2).setText((this.state.players[0].name || 'YOU').toUpperCase().slice(0, 12)); + } + + buildButtons() { + const B = L.BUTTONS, mk = (k, label, fn, o = {}) => { + const b = new LibButton(this, B[k].x, B[k].y, label, fn, { width: B[k].w ?? L.BTN_W, height: L.BTN_H, fontSize: 17, ...o }); + b.setDepth(DEPTH.hud); + return b; + }; + this.btn = { + recall: mk('recall', 'Recall', () => this.onRecall(), { variant: 'oak', hotkey: 'Esc' }), + shuffle: mk('shuffle', 'Shuffle', () => this.onShuffle(), { variant: 'oak', hotkey: 'Space' }), + sort: mk('sort', 'Sort A–Z', () => this.onSort(), { variant: 'oak' }), + hint: mk('hint', 'Hint', () => this.onHint(), { variant: 'brass' }), + exchange: mk('exchange', 'Exchange', () => this.onExchange(), { variant: 'oak' }), + pass: mk('pass', 'Pass', () => this.onPass(), { variant: 'oak' }), + play: mk('play', 'PLAY WORD', () => this.onPlay(), { fontSize: 21, hotkey: 'Enter' }), + }; + const T = L.TOP_BUTTONS; + const top = { + rules: ['Rules', () => this.openRules()], + card: ['Card', () => DLG.openReferenceCard(this, this.twoLetter ?? [])], + settings: ['Settings', () => this.openSettings()], + menu: ['Menu', () => this.openPause()], + }; + T.keys.forEach((k, i) => { + const b = new LibButton(this, T.xs[i], T.y, top[k][0], top[k][1], { width: T.w, height: T.h, fontSize: 16, variant: k === 'menu' ? 'leather' : 'oak' }); + b.setDepth(DEPTH.hud); + }); + } + + buildProps() { + this.bag = this.add.image(L.BAG.x, L.BAG.y, 'wsm-bag').setDepth(DEPTH.furniture + 2).setInteractive({ useHandCursor: true }); + this.bag.setOrigin(0.5, 1).setY(L.BAG.y + L.BAG.h / 2); + this.bagTag = bagTag(this); + this.bag.on('pointerup', () => { SFX.rustle(this, 220); this.wobbleBag(); }); + this.dict = this.add.image(L.DICT.x, L.DICT.y, 'wsm-dict').setDepth(DEPTH.furniture + 2).setInteractive({ useHandCursor: true }).setAngle(-4); + this.dict.on('pointerup', () => { if (!this.modal) DLG.openWordJudge(this, { disabled: !!this.state?.pending }); }); + } + + // ── Render ───────────────────────────────────────────────────────────────── + + renderAll() { + const s = this.state; + this.renderBoard(); + this.renderRack(); + this.seats.update(s, { active: s.over ? null : s.turn, hints: this.settings.coach === 'off' ? null : this.hintsLeft }); + this.sheet.render(s, { activeSeat: s.turn }); + const unseen = LG.unseenFor(s, 0); + const opp = s.players.slice(1).reduce((n, p) => n + p.rack.length, 0); + this.tracker.render(unseen, s.bag.length, opp); + this.bagTag.setText(`${s.bag.length} in the bag`); + const full = Math.max(0.12, s.bag.length / 86); + this.bag.setScale(0.82 + 0.18 * full, 0.7 + 0.3 * full); + const clock = s.clockMs ? `${Math.round(s.clockMs / 60000)}-minute clock` : 'no clock'; + this.note.setText(`${LG.RULES[s.rule].label} · ${clock} · move ${s.moveNo + 1}`); + this.renderLastMove(); + this.updateControls(); + } + + renderBoard() { + const b = this.state.board; + const live = new Set(); + for (let r = 0; r < BOARD_SIZE; r++) for (let c = 0; c < BOARD_SIZE; c++) { + const cell = b[r][c]; + if (!cell) continue; + const k = `${r},${c}`; + live.add(k); + const have = this.boardTiles.get(k); + if (have && have._letterIs === cell.letter && have._blankIs === cell.blank) continue; + have?.destroy(); + if (!this.squareGrain.has(k)) this.squareGrain.set(k, Math.floor(Math.random() * GRAINS)); + const t = makeTile(this, cell.blank ? BLANK : cell.letter, BOARD_TILE, { grain: this.squareGrain.get(k), letter: cell.letter }); + const p = L.squareLocal(r, c); + t.setPosition(p.x, p.y).setAngle((Math.random() - 0.5) * 3); + t._letterIs = cell.letter; t._blankIs = cell.blank; + this.boardC.add(t); + this.boardTiles.set(k, t); + } + for (const [k, t] of this.boardTiles) if (!live.has(k)) { t.destroy(); this.boardTiles.delete(k); } + // keep tentative tiles, ghosts and the cursor on top + for (const t of this.tentative) this.boardC.bringToTop(t.obj); + for (const g of this.ghosts) this.boardC.bringToTop(g); + this.boardC.bringToTop(this.cursorG); + } + + renderLastMove() { + this.lastG.clear(); + const last = [...this.state.log].reverse().find(e => e.type === 'play' || e.type === 'phony'); + const pend = this.state.pending; + const pls = pend ? pend.placements : last?.type === 'play' ? last.placements : null; + if (!pls) return; + const color = pend ? 0xf2a65a : GOLD_N; + for (const p of pls) { + const q = L.squareLocal(p.row, p.col); + this.lastG.fillStyle(color, 0.55); + this.lastG.fillRoundedRect(q.x - L.SQ / 2 + 0.5, q.y - L.SQ / 2 + 0.5, L.SQ - 1, L.SQ - 1, 6); + } + } + + renderRack({ animate = true } = {}) { + const n = this.hand.length; + const live = new Set(); + this.hand.forEach((h, i) => { + live.add(h.id); + let o = this.rackObjs.get(h.id); + if (!o) { + o = makeTile(this, h.token, L.RACK.tile, { grain: h.grain }); + o.setDepth(DEPTH.rack).setPosition(L.rackSlotX(i, n), L.RACK_TILE_Y); + o.setInteractive({ useHandCursor: true }); + o._entry = h; + this.rackObjs.set(h.id, o); + } + if (this.drag?.obj === o) return; + const sel = this.exchangeMode && this.exchangeSel.has(h.id); + const tx = L.rackSlotX(i, n), ty = L.RACK_TILE_Y - (sel ? 16 : 0); + o._homeX = tx; o._homeY = ty; + if (animate) this.tweens.add({ targets: o, x: tx, y: ty, duration: 150, ease: 'Cubic.easeOut' }); + else o.setPosition(tx, ty); + o.setAlpha(this.exchangeMode && !sel ? 0.75 : 1); + }); + for (const [id, o] of this.rackObjs) if (!live.has(id) && this.drag?.obj !== o) { o.destroy(); this.rackObjs.delete(id); } + } + + updateControls() { + const s = this.state; + const mine = this.humanCanAct(); + const ex = this.exchangeMode; + const b = this.btn; + b.play.setLabel(ex ? `SWAP ${this.exchangeSel.size || ''}`.trim() : 'PLAY WORD').setEnabled(mine && (ex ? this.exchangeSel.size > 0 : this.tentative.length > 0)); + b.play.setLit(mine && !ex && this.tentative.length > 0); + b.recall.setLabel(ex ? 'Cancel' : 'Recall').setEnabled(mine && (ex || this.tentative.length > 0)); + b.shuffle.setEnabled(mine && !ex); + b.sort.setEnabled(mine && !ex); + b.exchange.setEnabled(mine && !ex && LG.canExchange(s)); + b.pass.setEnabled(mine && !ex); + const coach = this.settings.coach; + b.hint.setVisible(coach !== 'off'); + b.hint.setLabel(coach === 'practice' ? 'Coach' : `Hint (${this.hintsLeft})`).setEnabled(mine && !ex && this.hintsLeft > 0); + } + + // ── Turn flow ────────────────────────────────────────────────────────────── + + async beginTurn() { + const gen = this.gen; + const s = this.state; + this.announceSkips(); + if (s.over) { this.finish(); return; } + this.writeSave(); + this.renderAll(); + const seat = s.turn; + this.lean(seat); + if (seat === 0) { + this.busy = false; + const opener = LG.isFirstMove(s) ? 'Your opening play must cover the star in the centre.' : 'Your turn. Drag tiles, or click a square and type.'; + this.setStatus(opener); + this.updateControls(); + return; + } + this.busy = true; + this.updateControls(); + await this.aiTurn(seat); + if (!this.alive(gen)) return; + this.beginTurn(); + } + + announceSkips() { + const s = this.state; + for (let i = this.seenLog; i < s.log.length; i++) { + const e = s.log[i]; + if (e.type === 'lost') { + this.setStatus(e.seat === 0 ? 'You lose this turn (the challenge failed).' : `${s.players[e.seat].name} loses a turn.`); + this.seats.plate(e.seat) && this.floatAt(this.seatPoint(e.seat), 'turn lost', '#ffb38a'); + } + } + this.seenLog = s.log.length; + } + + lean(seat) { + if (!this.boardC) return; + const to = this.settings.turntable && seat !== 0 && !this.state.over ? L.seatLean(seat - 1, false) : 0; + this.tweens.add({ targets: this.boardC, angle: to, duration: 700, ease: 'Sine.easeInOut' }); + } + + async aiTurn(seat) { + const gen = this.gen; + const s = this.state; + const p = s.players[seat]; + this.seats.setThinking(seat, 'thinking…'); + this.setStatus(`${p.name} is thinking…`); + const n = s.players.length; + const oppRacks = s.bag.length === 0 && n === 2 ? [s.players[1 - seat].rack.slice()] : null; + const [move] = await Promise.all([ + requestAIMove({ + board: LG.plainBoard(s.board), rack: p.rack.slice(), skill: p.skill, firstMove: LG.isFirstMove(s), + bagCount: s.bag.length, rule: s.rule, oppRacks, + }), + this.wait(nextThinkDelay(p.skill, this.pace)), + ]); + if (!this.alive(gen)) return; + this.seats.setThinking(seat, ''); + if (move?.type === 'play' && move.placements?.length) { + const chk = LG.checkPlay(s, move.placements); + if (chk.ok) { + await this.layTiles(seat, move.placements); + if (!this.alive(gen)) return; + const r = LG.submitPlay(s, seat, move.placements); + this.flyers?.forEach(f => f.destroy()); + this.flyers = []; + if (r.ok) { + this.renderAll(); + if (r.pending) await this.resolvePending(); + else this.afterCommit(r.entry); + return; } } } - } - - buildOpponents() { - const ai = this.players.filter(p => p.type === 'ai'); - const top = BOARD_Y0, bottom = BOARD_Y0 + BOARD_PX; - const slotH = (bottom - top) / ai.length; - const blockCx = (OPP_X0 + OPP_X1) / 2; - - ai.forEach((p, i) => { - const cy = Math.round(top + slotH * i + slotH / 2); - const R = ai.length <= 2 ? 50 : 44; - - const bg = this.add.rectangle(blockCx, cy, OPP_X1 - OPP_X0, slotH - 16, COLORS.panel, 0.55) - .setStrokeStyle(2, 0x2a2a2c).setDepth(DEPTH.panel); - p._blockBg = bg; - - const px = OPP_X0 + R + 16; - p.portrait = createOpponentPortrait(this, p.opp, px, cy, R, DEPTH.ui); - - const infoX = px + R + 22; - this.add.text(infoX, cy - R + 6, p.name, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0).setDepth(DEPTH.ui); - - this.add.text(infoX, cy - R + 36, `Skill ${p.skill}`, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setOrigin(0, 0).setDepth(DEPTH.ui); - - p._faceY = cy + 6; - p._faceX = infoX; - p._thinkText = this.add.text(infoX, cy + R - 16, '', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.accentHex, - }).setOrigin(0, 0).setDepth(DEPTH.ui); - }); - } - - buildNotepad() { - const g = this.add.graphics().setDepth(DEPTH.panel); - g.fillStyle(0xf5efdc, 1); - g.fillRoundedRect(NOTE_X, NOTE_Y, NOTE_W, NOTE_H, 8); - // ruled lines - g.lineStyle(1, 0xbcd0e0, 0.9); - for (let y = NOTE_Y + 96; y < NOTE_Y + NOTE_H - 10; y += 40) { - g.lineBetween(NOTE_X + 24, y, NOTE_X + NOTE_W - 18, y); - } - // red margin - g.lineStyle(2, 0xd98a8a, 0.9); - g.lineBetween(NOTE_X + 56, NOTE_Y + 12, NOTE_X + 56, NOTE_Y + NOTE_H - 12); - - this.add.text(NOTE_X + NOTE_W / 2, NOTE_Y + 40, 'Score Pad', { - fontFamily: 'YummyCupcakes', fontSize: '56px', color: '#b03a2e', - }).setOrigin(0.5).setDepth(DEPTH.ui); - - // Per-player score lines - this.noteScoreObjs = []; - const startY = NOTE_Y + 120; - this.players.forEach((p, i) => { - const y = startY + i * 64; - const nameText = this.add.text(NOTE_X + 72, y, p.name, { - fontFamily: 'YummyCupcakes', fontSize: '40px', color: '#27408b', - }).setOrigin(0, 0.5).setDepth(DEPTH.ui); - const scoreText = this.add.text(NOTE_X + NOTE_W - 40, y, '0', { - fontFamily: 'YummyCupcakes', fontSize: '40px', color: '#27408b', - }).setOrigin(1, 0.5).setDepth(DEPTH.ui); - this.noteScoreObjs.push({ nameText, scoreText }); - }); - - this.noteBagText = this.add.text(NOTE_X + 72, NOTE_Y + NOTE_H - 80, '', { - fontFamily: 'YummyCupcakes', fontSize: '34px', color: '#5a6b3a', - }).setOrigin(0, 0.5).setDepth(DEPTH.ui); - - this.noteLastText = this.add.text(NOTE_X + 72, NOTE_Y + NOTE_H - 38, '', { - fontFamily: 'YummyCupcakes', fontSize: '30px', color: '#7a5a2a', - }).setOrigin(0, 0.5).setDepth(DEPTH.ui); - } - - buildRackTray() { - const w = RACK_SIZE * RACK_TILE + (RACK_SIZE - 1) * RACK_GAP + 28; - this.rackTrayBg = this.add.rectangle(GAME_WIDTH / 2, RACK_Y, w, RACK_TILE + 24, 0x3a2b16, 1) - .setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.panel); - } - - buildStatus() { - this.statusText = this.add.text(GAME_WIDTH / 2, STATUS_Y, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - } - - buildControls() { - const labels = [ - ['Recall', () => this.recallAll()], - ['Shuffle', () => this.shuffleRack()], - ['Exchange', () => this.onExchangeButton()], - ['Pass', () => this.onPassButton()], - ['Play', () => this.onPlayButton()], - ]; - const bw = 150, gap = 12; - const total = labels.length * bw + (labels.length - 1) * gap; - let x = GAME_WIDTH / 2 - total / 2 + bw / 2; - this.btn = {}; - for (const [label, fn] of labels) { - const b = new Button(this, x, CONTROLS_Y, label, fn, { width: bw, height: 44, fontSize: 18 }); - b.setDepth(DEPTH.ui); - this.btn[label.toLowerCase()] = b; - x += bw + gap; - } - new Button(this, GAME_WIDTH - 96, GAME_HEIGHT - 28, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 150, height: 40, fontSize: 18, - }).setDepth(DEPTH.ui); - } - - // ── Tile rendering ─────────────────────────────────────────────────────────── - - makeTile(size, letter, value, { tentative = false, faceDown = false } = {}) { - const c = this.add.container(0, 0); - const g = this.add.graphics(); - const half = size / 2; - if (faceDown) { - g.fillStyle(COLORS.panel, 1); - g.fillRoundedRect(-half, -half, size, size, 6); - g.lineStyle(2, COLORS.accent, 0.8); - g.strokeRoundedRect(-half, -half, size, size, 6); - c.add(g); - c.add(this.add.text(0, 0, '✦', { - fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.4)}px`, color: COLORS.accentHex, - }).setOrigin(0.5)); - return c; - } - g.fillStyle(tentative ? TILE_FILL_TENT : TILE_FILL, 1); - g.fillRoundedRect(-half, -half, size, size, 6); - g.lineStyle(2, tentative ? COLORS.gold : TILE_STROKE, 1); - g.strokeRoundedRect(-half, -half, size, size, 6); - c.add(g); - if (letter) { - c.add(this.add.text(-2, -2, letter, { - fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.52)}px`, color: TILE_INK, - }).setOrigin(0.5)); - } - if (value > 0) { - c.add(this.add.text(half - 6, half - 5, String(value), { - fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.24)}px`, color: TILE_INK, - }).setOrigin(1, 1)); - } - return c; - } - - squareCenter(row, col) { - return { x: BOARD_X0 + col * SQ + SQ / 2, y: BOARD_Y0 + row * SQ + SQ / 2 }; - } - - // ── Rack (human) ───────────────────────────────────────────────────────────── - - // Shared tray geometry: x of slot 0's center, and center-to-center slot pitch. - rackLayout() { - const w = RACK_SIZE * RACK_TILE + (RACK_SIZE - 1) * RACK_GAP; - return { startX: GAME_WIDTH / 2 - w / 2 + RACK_TILE / 2, slot: RACK_TILE + RACK_GAP }; - } - - renderRack() { - for (const o of this.rackObjs) o.destroy(); - this.rackObjs = []; - this._dragInsertIndex = null; - const rack = this.players[0].rack; - const { startX, slot } = this.rackLayout(); - rack.forEach((token, i) => { - const x = startX + i * slot; - const letter = token === BLANK ? '' : token; - const value = token === BLANK ? 0 : (LETTER_VALUES[token] ?? 0); - const tile = this.makeTile(RACK_TILE, letter, value); - tile.setPosition(x, RACK_Y).setDepth(DEPTH.tile); - tile._token = token; - tile._rackIndex = i; - tile._homeX = x; - tile._homeY = RACK_Y; - tile.setSize(RACK_TILE, RACK_TILE); - // A Container's displayOrigin is width*0.5, which Phaser adds to the hit - // test, so the auto-generated Rectangle(0,0,w,h) lands centered. Passing a - // manual (-w/2,-h/2,w,h) rect double-shifts it up-left — don't. - tile.setInteractive({ useHandCursor: true }); - this.input.setDraggable(tile); - tile.on('pointerup', () => { if (this.exchangeMode) this.toggleExchangeSel(tile); }); - this.rackObjs.push(tile); - }); - this.refreshExchangeVisuals(); - } - - setupDrag() { - this.input.on('dragstart', (_p, obj) => { - if (!this.canHumanAct() || this.exchangeMode || obj._rackIndex === undefined) return; - obj.setDepth(DEPTH.drag); - obj._dragging = true; - obj._fromIndex = obj._rackIndex; - this._dragInsertIndex = obj._fromIndex; - }); - this.input.on('drag', (_p, obj, dx, dy) => { - if (!obj._dragging) return; - obj.setPosition(dx, dy); - const sq = this.squareAt(obj.x, obj.y); - if (sq && this.squareFree(sq.row, sq.col)) { - // Pointer is over a free board square — close any tray gap we opened. - this.clearRackGap(obj); - } else if (this.inRackZone(obj.y)) { - // Tray-reorder mode — slide neighbours aside to reveal the drop slot. - this.updateRackGap(obj, this.rackInsertIndexAt(obj.x)); - } else { - // Dead zone (e.g. over an occupied square) — no gap. - this.clearRackGap(obj); - } - }); - this.input.on('dragend', (_p, obj) => { - if (!obj._dragging) return; - obj._dragging = false; - const insert = this._dragInsertIndex; - const sq = this.squareAt(obj.x, obj.y); - if (sq && this.squareFree(sq.row, sq.col)) { - // Defer: placeTentative rebuilds the rack and destroys this very tile, - // so let Phaser finish dispatching dragend first. - obj.setVisible(false); - const token = obj._token, row = sq.row, col = sq.col; - this.time.delayedCall(0, () => this.placeTentative(token, row, col)); - } else if (this.inRackZone(obj.y) && insert !== null && insert !== obj._fromIndex) { - this.reorderRack(obj._fromIndex, insert); - } else { - // No move — snap the dragged tile home and close the gap. - obj.setDepth(DEPTH.tile); - this.clearRackGap(obj); - this.tweens.add({ targets: obj, x: obj._homeX, y: obj._homeY, duration: 140, ease: 'Back.easeOut' }); - } - }); - } - - // True when y is below the board, i.e. in the tray region (not over the grid). - inRackZone(y) { - return y > BOARD_Y0 + BOARD_PX; - } - - // Which rack slot would the dragged tile land on, given its current x. - rackInsertIndexAt(x) { - const { startX, slot } = this.rackLayout(); - const max = this.players[0].rack.length - 1; - const i = Math.round((x - startX) / slot); - return Math.max(0, Math.min(max, i)); - } - - // Lay out every non-dragged tile, leaving slot `insertIndex` empty for the drop. - updateRackGap(draggedObj, insertIndex) { - this._dragInsertIndex = insertIndex; - const { startX, slot } = this.rackLayout(); - // Tiles in their natural rack order, excluding the one being dragged. - const others = this.rackObjs.filter(t => t !== draggedObj); - let s = 0; - for (const tile of others) { - if (s === insertIndex) s++; // reserve the gap slot - const tx = startX + s * slot; - if (tile._homeX !== tx) { // only retween when the target changes - tile._homeX = tx; - this.tweens.add({ targets: tile, x: tx, duration: 120, ease: 'Cubic.easeOut' }); - } - s++; - } - } - - // Restore all non-dragged tiles to their natural slots (gap closed). - clearRackGap(draggedObj) { - if (this._dragInsertIndex === null) return; - this._dragInsertIndex = null; - const { startX, slot } = this.rackLayout(); - for (const tile of this.rackObjs) { - if (tile === draggedObj) continue; - const tx = startX + tile._rackIndex * slot; - if (tile._homeX !== tx) { - tile._homeX = tx; - this.tweens.add({ targets: tile, x: tx, duration: 120, ease: 'Cubic.easeOut' }); + if (move?.type === 'exchange' && LG.canExchange(s)) { + const count = move.tiles.length; + await this.tilesToBag(this.seats.rackPoint(seat), count); + const r = LG.exchangeTiles(s, seat, move.tiles); + if (r.ok) { + this.setStatus(`${p.name} exchanges ${count} tile${count > 1 ? 's' : ''}.`); + await this.tilesFromBag(this.seats.rackPoint(seat), count); + this.sheet.render(s); + return; } } + LG.passTurn(s, seat); + this.setStatus(`${p.name} passes.`); + this.floatAt(this.seatPoint(seat), 'pass', '#e9d9b0'); + await this.wait(500); } - reorderRack(fromIndex, toIndex) { - const rack = this.players[0].rack; - const [tok] = rack.splice(fromIndex, 1); - // `toIndex` is the desired final-array slot for the tile; updateRackGap laid the - // remaining tiles out around that slot, so insert directly there. - rack.splice(toIndex, 0, tok); - playSound(this, SFX.PIECE_CLICK); - this.renderRack(); - } - - squareAt(x, y) { - const col = Math.floor((x - BOARD_X0) / SQ); - const row = Math.floor((y - BOARD_Y0) / SQ); - if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) return null; - return { row, col }; - } - - squareFree(row, col) { - if (this.board[row][col]) return false; - return !this.tentative.some(t => t.row === row && t.col === col); - } - - placeTentative(token, row, col) { - const finalize = (letter) => { - // remove one matching token from rack - const rack = this.players[0].rack; - const idx = rack.indexOf(token); - if (idx !== -1) rack.splice(idx, 1); - - const blank = token === BLANK; - const { x, y } = this.squareCenter(row, col); - const obj = this.makeTile(SQ - 4, letter, blank ? 0 : (LETTER_VALUES[letter] ?? 0), { tentative: true }); - obj.setPosition(x, y).setDepth(DEPTH.tentative); - obj.setSize(SQ, SQ); - obj.setInteractive({ useHandCursor: true }); - const t = { row, col, token, letter, blank, obj }; - obj.on('pointerup', () => { if (this.canHumanAct() && !this.exchangeMode) this.recallTentative(t); }); - this.tentative.push(t); - playSound(this, SFX.PIECE_CLICK); - this.renderRack(); - this.clearStatus(); - }; - - if (token === BLANK) { - this.openBlankPicker((letter) => { - if (letter) finalize(letter); - else this.renderRack(); // cancelled — snap back - }); - } else { - finalize(token); + // Tiles travel from the AI's rack to the board, one at a time. + async layTiles(seat, placements) { + const p = this.state.players[seat]; + const { perTile, settle } = layTiming(p.skill, this.pace); + const from = this.seats.rackPoint(seat); + this.flyers = []; + const order = placements.slice().sort((a, b) => a.row - b.row || a.col - b.col); + for (const pl of order) { + const to = this.squareWorld(pl.row, pl.col); + const t = makeTile(this, pl.blank ? BLANK : pl.letter, 30, { letter: pl.letter }); + t.setPosition(from.x, from.y).setDepth(DEPTH.fly); + this.flyers.push(t); + this.tweens.add({ targets: t, x: to.x, y: to.y, scale: BOARD_TILE / 30, angle: this.boardC.angle, duration: perTile, ease: 'Cubic.easeOut' }); + await this.wait(perTile * 0.85); + SFX.clack(this, 0.5); + this.seats.plate(seat).backs?.[Math.max(0, p.rack.length - this.flyers.length)]?.setVisible(false); } + await this.wait(settle); } - recallTentative(t) { - this.players[0].rack.push(t.token); - t.obj.destroy(); - this.tentative = this.tentative.filter(x => x !== t); - this.renderRack(); + // After a play stands (friendly, or accepted / survived a challenge). + afterCommit(entry) { + const s = this.state; + if (!entry) { this.renderAll(); return; } + const seat = entry.seat; + this.renderAll(); + SFX.pencil(this, entry.word?.length ?? 3); + this.sheet.bump(seat); + if (entry.type === 'play') { + const at = this.wordCentre(entry.placements); + this.floatAt(at, `+${entry.score}`, '#fff1c2', 34); + const txt = entry.words.length > 1 ? `${entry.word} (+${entry.words.length - 1} more)` : entry.word; + this.setStatus(`${seat === 0 ? 'You' : s.players[seat].name} played ${txt} for ${entry.score}.`); + if (entry.bingo) this.bingo(seat); + else if (seat !== 0 && entry.score >= 40) this.seats.portrait(seat)?.playEmotion?.('happy'); + } + // replacement tiles + if (entry.drew) { + if (seat === 0) this.syncHand({ fromBag: true }); + else this.tilesFromBag(this.seats.rackPoint(seat), entry.drew); + } + this.seenLog = s.log.length; + } + + // ── Challenges ───────────────────────────────────────────────────────────── + + async resolvePending() { + const gen = this.gen; + const s = this.state; + const pd = s.pending; + if (!pd) return; + const n = s.players.length; + // Opponents (other than the player) consider it in seat order; the human last. + for (let k = 1; k < n; k++) { + const seat = (pd.seat + k) % n; + if (seat === 0) continue; + await this.wait(250 * this.pace); + if (!this.alive(gen)) return; + if (await aiChallenges(pd.words, s.players[seat].skill, pd.score)) { await this.doChallenge(seat); return; } + } + if (pd.seat !== 0) { + const choice = await this.humanChallengeWindow(pd); + if (!this.alive(gen)) return; + if (choice === 'challenge') { await this.doChallenge(0); return; } + } + const r = LG.acceptPending(s); + this.afterCommit(r.entry); + } + + humanChallengeWindow(pd) { + return new Promise((resolve) => { + const who = this.state.players[pd.seat].name; + const secs = Math.round(7 * this.pace); + let left = secs; + this.setStatus(`${who} played ${pd.words[0]} for ${pd.score}. Accept, or challenge?`); + const accept = new LibButton(this, L.BOARD.cx - 300, L.STATUS_Y, `Accept (${left})`, () => done('accept'), { width: 170, height: 40, fontSize: 17, variant: 'oak', hotkey: 'Enter' }).setDepth(DEPTH.tip); + const chal = new LibButton(this, L.BOARD.cx + 300, L.STATUS_Y, 'Challenge!', () => done('challenge'), { width: 170, height: 40, fontSize: 17, hotkey: 'C' }).setDepth(DEPTH.tip); + const timer = this.time.addEvent({ delay: 1000, repeat: secs - 1, callback: () => { left--; accept.setLabel(`Accept (${left})`); if (left <= 0) done('accept'); } }); + const key = (e) => { if (this.modal) return; if (e.key === 'Enter') done('accept'); else if (e.key.toLowerCase() === 'c') done('challenge'); }; + this.input.keyboard.on('keydown', key); + let finished = false; + const done = (v) => { + if (finished) return; + finished = true; + timer.remove(); + this.input.keyboard.off('keydown', key); + accept.destroy(); chal.destroy(); + this.challengeUI = null; + resolve(v); + }; + this.challengeUI = { done }; + }); + } + + async doChallenge(challenger) { + const gen = this.gen; + const s = this.state; + const pd = s.pending; + const name = challenger === 0 ? 'You' : s.players[challenger].name; + this.setStatus(`${name} challenge${challenger === 0 ? '' : 's'} ${pd.words.join(', ')}…`); + this.floatAt(this.seatPoint(challenger), 'Challenge!', '#ffd27a', 26); + // the dictionary is consulted + SFX.pageFlip(this); + this.tweens.add({ targets: this.dict, y: L.DICT.y - 22, angle: 0, scale: 1.12, duration: 300, yoyo: true, hold: 600, ease: 'Sine.easeInOut', onComplete: () => this.dict.setAngle(-4) }); + await this.wait(1200 * this.pace); + if (!this.alive(gen)) return; + const player = pd.seat; + const res = LG.challengePending(s, challenger, isValidWord); + if (res.phony) { + SFX.thunk(this); + this.setStatus(`${res.invalid.join(', ')} ${res.invalid.length > 1 ? 'are' : 'is'} not acceptable. The tiles come off.`); + this.stamp('PHONY', '#c4492f'); + if (player !== 0) this.seats.portrait(player)?.playEmotion?.('upset'); + else if (challenger !== 0) this.seats.portrait(challenger)?.playEmotion?.('happy'); + // tiles return to the player's rack + const back = player === 0 ? { x: L.RACK.cx, y: L.RACK_TILE_Y } : this.seats.rackPoint(player); + const fly = []; + for (const pl of pd.placements) { + const from = this.squareWorld(pl.row, pl.col); + const t = makeTile(this, pl.blank ? BLANK : pl.letter, BOARD_TILE, { letter: pl.blank ? pl.letter : null }); + t.setPosition(from.x, from.y).setDepth(DEPTH.fly); + fly.push(t); + this.tweens.add({ targets: t, x: back.x, y: back.y, scale: player === 0 ? 1.2 : 0.6, alpha: player === 0 ? 1 : 0.2, duration: 420, ease: 'Cubic.easeIn' }); + } + this.renderAll(); + await this.wait(460); + fly.forEach(f => f.destroy()); + if (player === 0) this.syncHand({ fromBag: false }); + this.sheet.render(s); + this.seenLog = s.log.length; + await this.wait(700 * this.pace); + return; + } + SFX.bingoChime(this); + const bonus = s.rule === 'five'; + this.setStatus(`${pd.words.join(', ')} ${pd.words.length > 1 ? 'are' : 'is'} good! ${bonus ? `+5 to ${player === 0 ? 'you' : s.players[player].name}.` : `${name} lose${challenger === 0 ? '' : 's'} the next turn.`}`); + this.stamp('GOOD WORD', '#5f9e62'); + if (challenger !== 0) this.seats.portrait(challenger)?.playEmotion?.('upset'); + const entry = s.log.slice().reverse().find(e => e.type === 'play'); + this.afterCommit(entry); + await this.wait(900 * this.pace); + } + + // ── Human actions ────────────────────────────────────────────────────────── + + humanCanAct() { + const s = this.state; + return !!s && !s.over && !this.busy && !this.modal && !this.paused && s.turn === 0 && !s.pending; + } + + async onPlay() { + if (!this.humanCanAct()) return; + if (this.exchangeMode) { this.confirmExchange(); return; } + if (!this.tentative.length) { this.setStatus('Put some tiles on the board first.'); return; } + const s = this.state; + const placements = this.tentative.map(t => ({ row: t.row, col: t.col, letter: t.letter, blank: t.token === BLANK })); + const chk = LG.checkPlay(s, placements); + if (!chk.ok) { this.bounce(chk.error); return; } + if (s.rule === 'friendly') { + const bad = chk.words.filter(w => !isValidWord(w)); + if (bad.length) { this.bounce(`${bad.join(', ')} ${bad.length > 1 ? "aren't" : "isn't"} in the dictionary.`); return; } + } + const gen = this.gen; + this.busy = true; + this.updateControls(); + this.clearGhosts(); + this.clearCursor(); + // The coach notes the best play available, for the post-game review. + let best = null; + if (this.settings.coach !== 'off') { + const top = await requestHint({ board: LG.plainBoard(s.board), rack: s.players[0].rack.slice(), firstMove: LG.isFirstMove(s), bagCount: s.bag.length, n: 1, by: 'score' }); + if (top[0]) best = { word: top[0].word, score: top[0].score }; + if (!this.alive(gen)) return; + } + for (const t of this.tentative) this.squareGrain.set(`${t.row},${t.col}`, t.grain); + const r = LG.submitPlay(s, 0, placements, { best }); + if (!r.ok) { this.busy = false; this.bounce(r.error); return; } + for (const t of this.tentative) t.obj.destroy(); + this.tentative = []; + this.typed = []; + this.preview.hide(); + SFX.clack(this, 0.4); + this.renderAll(); + if (r.pending) await this.resolvePending(); + else this.afterCommit(r.entry); + if (!this.alive(gen)) return; + await this.wait(500 * this.pace); + if (!this.alive(gen)) return; + this.beginTurn(); + } + + bounce(msg) { + SFX.thunk(this); + this.setStatus(msg); + const objs = this.tentative.map(t => t.obj); + const xs = objs.map(o => o.x); + this.tweens.add({ targets: objs, x: '+=5', duration: 45, yoyo: true, repeat: 3, onComplete: () => objs.forEach((o, i) => { o.x = xs[i]; }) }); + } + + onRecall() { + if (!this.humanCanAct()) return; + if (this.exchangeMode) { this.cancelExchange(); return; } + this.recallAll(); } recallAll() { - if (!this.canHumanAct()) return; - if (this.exchangeMode) { this.cancelExchange(); return; } - for (const t of this.tentative) { - this.players[0].rack.push(t.token); - t.obj.destroy(); - } - this.tentative = []; + for (const t of this.tentative.slice()) this.recallTentative(t, { render: false }); + this.typed = []; + this.renderRack(); + this.updatePreview(); + this.updateControls(); + } + + onShuffle() { + if (!this.humanCanAct() || this.exchangeMode) return; + LG.shuffle(this.hand); + SFX.rattle(this); this.renderRack(); } - shuffleRack() { - if (!this.canHumanAct() || this.exchangeMode) return; - shuffle(this.players[0].rack); + onSort() { + if (!this.humanCanAct() || this.exchangeMode) return; + this.sortMode = (this.sortMode + 1) % 2; + const key = (h) => (h.token === BLANK ? 'ZZ' : h.token); + if (this.sortMode === 1) this.hand.sort((a, b) => key(a).localeCompare(key(b))); + else this.hand.sort((a, b) => (VOWELS.includes(b.token) - VOWELS.includes(a.token)) || key(a).localeCompare(key(b))); + this.btn.sort.setLabel(this.sortMode === 1 ? 'Vowels first' : 'Sort A–Z'); + SFX.rattle(this); this.renderRack(); - playSound(this, SFX.PIECE_CLICK); } - // ── Blank picker ───────────────────────────────────────────────────────────── - - openBlankPicker(onPick) { - this.blankPicking = true; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - const objs = []; - objs.push(this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55).setDepth(DEPTH.modal).setInteractive()); - objs.push(this.add.rectangle(cx, cy, 520, 360, COLORS.panel, 1).setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.modal + 1)); - objs.push(this.add.text(cx, cy - 150, 'Choose a letter for the blank', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.modal + 2)); - - const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); - const cols = 7, cell = 60, gx = cx - (cols * cell) / 2 + cell / 2, gy = cy - 88; - const cleanup = (pick) => { for (const o of objs) o.destroy(); this.blankPicking = false; onPick(pick); }; - letters.forEach((L, i) => { - const r = Math.floor(i / cols), c = i % cols; - const x = gx + c * cell, y = gy + r * cell; - const box = this.add.rectangle(x, y, cell - 8, cell - 8, 0x2a2a2c, 1).setStrokeStyle(1, COLORS.accent) - .setDepth(DEPTH.modal + 2).setInteractive({ useHandCursor: true }); - const txt = this.add.text(x, y, L, { fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex }) - .setOrigin(0.5).setDepth(DEPTH.modal + 3); - box.on('pointerover', () => box.setFillStyle(COLORS.gold)); - box.on('pointerout', () => box.setFillStyle(0x2a2a2c)); - box.on('pointerup', () => cleanup(L)); - objs.push(box, txt); - }); - const cancel = new Button(this, cx, cy + 142, 'Cancel', () => cleanup(null), { variant: 'ghost', width: 160, height: 40, fontSize: 18 }); - cancel.setDepth(DEPTH.modal + 3); - objs.push(cancel); - } - - // ── Play a move (human) ────────────────────────────────────────────────────── - - async onPlayButton() { - if (!this.canHumanAct()) return; - if (this.exchangeMode) { this.confirmExchange(); return; } - if (!this.tentative.length) { this.flashStatus('Drag tiles onto the board first.'); return; } - - const placements = this.tentative.map(t => ({ row: t.row, col: t.col, letter: t.letter, blank: t.blank })); - const firstMove = isBoardEmpty(this.board); - const res = validateMove(this.board, placements, { firstMove }); - if (!res.ok) { this.flashStatus(res.error); this.shakeTentative(); return; } - - this.animating = true; - let check; - try { - check = await api.post('/words/scrabble/validate', { words: res.words.map(w => w.word) }); - } catch { - check = { valid: true, invalid: [] }; // network failure → allow (best effort) - } - this.animating = false; - if (!check.valid) { - this.flashStatus(`Not a word: ${check.invalid.join(', ')}`); - this.shakeTentative(); - return; - } - - const score = scoreMove(this.board, placements); - this.commitMove(this.players[0], placements, res.words, score); - } - - commitMove(player, placements, words, score, alreadyApplied = false) { - if (!alreadyApplied) { - // commit to board model and turn tentative tiles into committed ones - this.board = applyPlacements(this.board, placements); - for (const t of this.tentative) t.obj.destroy(); - this.tentative = []; - for (const p of placements) this.renderCommittedTile(p.row, p.col); - } - - player.score += score; - this.scorelessTurns = score > 0 ? 0 : this.scorelessTurns + 1; - - const best = words.slice().sort((a, b) => b.word.length - a.word.length)[0]; - this.noteLastText.setText(`${player.name}: ${best?.word ?? ''} +${score}`); - playSound(this, SFX.PENCIL_WRITE); - - // refill from bag - const need = RACK_SIZE - player.rack.length; - if (need > 0) player.rack.push(...drawTiles(this.bag, need)); - - if (player.type === 'human') this.renderRack(); - this.renderOpponentRacks(); - this.updateNotepad(); - this.bumpScore(this.players.indexOf(player)); - - if (player.rack.length === 0) { this.endGame(player); return; } - this.advanceTurn(); - } - - renderCommittedTile(row, col) { - const cell = this.board[row][col]; - const { x, y } = this.squareCenter(row, col); - const value = cell.blank ? 0 : (LETTER_VALUES[cell.letter] ?? 0); - const obj = this.makeTile(SQ - 4, cell.letter, value); - obj.setPosition(x, y).setDepth(DEPTH.tile); - this.boardObjs[`${row},${col}`] = obj; - this.tweens.add({ targets: obj, scale: { from: 1.25, to: 1 }, duration: 160, ease: 'Back.easeOut' }); - } - - shakeTentative() { - const objs = this.tentative.map(t => t.obj); - if (!objs.length) return; - const homeX = objs.map(o => o.x); - this.tweens.add({ - targets: objs, x: '+=6', duration: 50, yoyo: true, repeat: 3, - onComplete: () => objs.forEach((o, i) => { o.x = homeX[i]; }), + onPass() { + if (!this.humanCanAct()) return; + const sc = this.state.scoreless; + const warn = sc >= LG.SCORELESS_LIMIT - 1 ? '\nThat would be the sixth scoreless turn in a row, which ends the game.' : ''; + DLG.confirmDialog(this, 'Pass this turn?', `You'll score nothing and keep your tiles.${warn}`, 'Pass', () => { + this.recallAll(); + LG.passTurn(this.state, 0); + this.setStatus('You pass.'); + this.busy = true; + this.wait(350).then(() => this.beginTurn()); }); } - // ── Exchange ───────────────────────────────────────────────────────────────── - - onExchangeButton() { - if (!this.canHumanAct()) return; - if (this.exchangeMode) { this.confirmExchange(); return; } - if (this.tentative.length) { this.flashStatus('Recall your tiles before exchanging.'); return; } - if (this.bag.length < 1) { this.flashStatus('No tiles left to exchange.'); return; } + onExchange() { + if (!this.humanCanAct()) return; + if (!LG.canExchange(this.state)) { this.setStatus(`Exchanges need at least ${LG.MIN_BAG_TO_EXCHANGE} tiles in the bag.`); return; } + this.recallAll(); this.exchangeMode = true; this.exchangeSel.clear(); - this.flashStatus('Select tiles to swap, then press Swap.'); + this.setStatus('Click the tiles to throw back, then press Swap. (Exchanging uses your turn.)'); + this.renderRack(); this.updateControls(); - this.refreshExchangeVisuals(); - } - - toggleExchangeSel(tile) { - const i = tile._rackIndex; - if (this.exchangeSel.has(i)) this.exchangeSel.delete(i); - else this.exchangeSel.add(i); - this.refreshExchangeVisuals(); - } - - refreshExchangeVisuals() { - this.rackObjs.forEach(o => { - const sel = this.exchangeMode && this.exchangeSel.has(o._rackIndex); - o.setY(sel ? RACK_Y - 14 : RACK_Y); - o.setAlpha(this.exchangeMode && !sel ? 0.7 : 1); - }); } cancelExchange() { this.exchangeMode = false; this.exchangeSel.clear(); - this.updateControls(); + this.setStatus(''); this.renderRack(); - this.clearStatus(); + this.updateControls(); } - confirmExchange() { - const rack = this.players[0].rack; - const idxs = [...this.exchangeSel].sort((a, b) => b - a); - if (!idxs.length) { this.flashStatus('Select at least one tile.'); return; } - const returned = []; - for (const i of idxs) returned.push(rack.splice(i, 1)[0]); - const drawn = drawTiles(this.bag, returned.length); - rack.push(...drawn); - this.bag.push(...returned); - shuffle(this.bag); - + async confirmExchange() { + const gen = this.gen; + const ids = [...this.exchangeSel]; + if (!ids.length) return; + const entries = this.hand.filter(h => ids.includes(h.id)); + const tokens = entries.map(h => h.token); + this.busy = true; this.exchangeMode = false; this.exchangeSel.clear(); - this.scorelessTurns += 1; this.updateControls(); - this.renderRack(); - this.updateNotepad(); - playSound(this, SFX.CARD_SHUFFLE); - this.flashStatus('Tiles exchanged.'); - this.advanceTurn(); - } - - onPassButton() { - if (!this.canHumanAct()) return; - if (this.exchangeMode) { this.cancelExchange(); return; } - this.recallAll(); - this.scorelessTurns += 1; - this.flashStatus('You passed.'); - this.advanceTurn(); - } - - updateControls() { - if (this.exchangeMode) { - this.btn.play.setLabel('Swap'); - this.btn.recall.setLabel('Cancel'); - this.btn.shuffle.setEnabled(false); - this.btn.exchange.setEnabled(false); - this.btn.pass.setEnabled(false); - } else { - this.btn.play.setLabel('Play'); - this.btn.recall.setLabel('Recall'); - this.btn.shuffle.setEnabled(true); - this.btn.exchange.setEnabled(true); - this.btn.pass.setEnabled(true); + // the tiles go into the bag + for (const h of entries) { + const o = this.rackObjs.get(h.id); + if (o) this.tweens.add({ targets: o, x: this.bag.x, y: this.bag.y - L.BAG.h * 0.55, scale: 0.4, alpha: 0, duration: 380, ease: 'Cubic.easeIn' }); } - } - - setControlsEnabled(on) { - for (const k of Object.keys(this.btn)) this.btn[k].setEnabled(on); - if (on) this.updateControls(); - } - - // ── Turn loop ──────────────────────────────────────────────────────────────── - - beginTurn() { - if (this.gameOver) return; - this.highlightActive(); - const player = this.players[this.turnIndex]; - if (player.type === 'human') { - this.setControlsEnabled(true); - this.flashStatus('Your turn — build a word.'); - } else { - this.setControlsEnabled(false); - this.runAITurn(player); - } - } - - advanceTurn() { - if (this.gameOver) return; - if (this.scorelessTurns >= 6) { this.endGame(null); return; } - this.turnIndex = (this.turnIndex + 1) % this.players.length; + SFX.rustle(this, 420); + this.wobbleBag(); + await this.wait(420); + if (!this.alive(gen)) return; + for (const h of entries) { this.rackObjs.get(h.id)?.destroy(); this.rackObjs.delete(h.id); } + this.hand = this.hand.filter(h => !ids.includes(h.id)); + const r = LG.exchangeTiles(this.state, 0, tokens); + if (!r.ok) { this.setStatus(r.error); this.syncHand({ fromBag: false }); this.busy = false; this.updateControls(); return; } + this.setStatus(`You exchange ${tokens.length} tile${tokens.length > 1 ? 's' : ''}.`); + this.syncHand({ fromBag: true }); + this.sheet.render(this.state); + await this.wait(700); + if (!this.alive(gen)) return; this.beginTurn(); } - async runAITurn(player) { - this.animating = true; - player._thinkText?.setText('thinking…'); - const delay = nextThinkDelay(player.skill); + async onHint() { + if (!this.humanCanAct() || this.hintsLeft <= 0) return; + const gen = this.gen; + const s = this.state; + this.recallAll(); + const practice = this.settings.coach === 'practice'; + this.busy = true; + const moves = await requestHint({ board: LG.plainBoard(s.board), rack: s.players[0].rack.slice(), firstMove: LG.isFirstMove(s), bagCount: s.bag.length, n: practice ? 3 : 1, by: 'equity' }); + if (!this.alive(gen)) return; + this.busy = false; + if (!moves.length) { + this.setStatus(LG.canExchange(s) ? 'The coach sees no play at all. Exchanging is your best option.' : 'The coach sees no play. You will have to pass.'); + this.updateControls(); + return; + } + if (!practice) this.hintsLeft--; + this.showHints(moves); + this.renderAll(); + } - const move = await requestAIMove({ - board: this.serializeBoard(), - rack: player.rack.slice(), - skill: player.skill, - firstMove: isBoardEmpty(this.board), - bagCount: this.bag.length, - }); + showHints(moves) { + this.clearGhosts(); + const first = moves[0]; + this.showGhost(first); + const lines = moves.map((m, i) => `${i + 1}. ${m.word} for ${m.score}${m.leave.length ? `, keeping ${m.leave.map(t => (t === BLANK ? '?' : t)).join('')}` : ''}`); + this.setStatus(`Coach: ${lines.join(' ')} (click a ghost tile to use it)`); + this.hintMoves = moves; + } - await this.delay(delay); - player._thinkText?.setText(''); - this.animating = false; - if (this.gameOver) return; + showGhost(m) { + for (const g of this.ghosts) g.destroy(); + this.ghosts = []; + for (const p of m.placements) { + const g = makeTile(this, p.blank ? BLANK : p.letter, BOARD_TILE, { letter: p.letter, shadow: false }); + const q = L.squareLocal(p.row, p.col); + g.setPosition(q.x, q.y).setAlpha(0.55); + const ring = this.add.graphics(); + ring.lineStyle(2, GOLD_N, 1); + ring.strokeRoundedRect(-BOARD_TILE / 2, -BOARD_TILE / 2, BOARD_TILE, BOARD_TILE, 6); + g.add(ring); + this.boardC.add(g); + this.ghosts.push(g); + this.tweens.add({ targets: g, alpha: 0.85, duration: 600, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + } + this.ghostMove = m; + } - if (move.type === 'play' && Array.isArray(move.placements) && move.placements.length) { - const firstMove = isBoardEmpty(this.board); - const res = validateMove(this.board, move.placements, { firstMove }); - if (res.ok) { - const score = scoreMove(this.board, move.placements); // board still pre-move - await this.animateAIPlacements(move.placements); // applies board + renders tiles - player.portrait?.playEmotion('happy'); - this.commitMove(player, move.placements, res.words, score, true); + clearGhosts() { + for (const g of this.ghosts) g.destroy(); + this.ghosts = []; + this.ghostMove = null; + } + + useGhost() { + const m = this.ghostMove; + if (!m) return; + this.clearGhosts(); + this.recallAll(); + for (const p of m.placements) { + const tok = p.blank ? BLANK : p.letter; + const h = this.hand.find(x => x.token === tok); + if (!h) continue; + this.placeEntry(h, p.row, p.col, p.blank ? p.letter : null, { render: false }); + } + this.renderRack(); + this.updatePreview(); + this.updateControls(); + } + + // ── Tentative tiles ──────────────────────────────────────────────────────── + + squareFree(row, col) { + return !this.state.board[row][col] && !this.tentative.some(t => t.row === row && t.col === col); + } + + /** Move a hand entry onto the board (asks for a blank's letter unless given). */ + placeEntry(h, row, col, blankLetter = null, { render = true, typed = false } = {}) { + if (!this.squareFree(row, col)) return false; + if (h.token === BLANK && !blankLetter) { + DLG.openBlankPicker(this, (letter) => { + if (letter) this.placeEntry(h, row, col, letter, { render: true, typed }); + else this.renderRack(); + }); + return false; + } + this.hand = this.hand.filter(x => x.id !== h.id); + const o = this.rackObjs.get(h.id); + if (o) { o.destroy(); this.rackObjs.delete(h.id); } + const letter = h.token === BLANK ? blankLetter : h.token; + const obj = makeTile(this, h.token, BOARD_TILE, { grain: h.grain, letter }); + const q = L.squareLocal(row, col); + obj.setPosition(q.x, q.y); + this.boardC.add(obj); + this.tweens.add({ targets: obj, scale: { from: 1.18, to: 1 }, duration: 140, ease: 'Back.easeOut' }); + const t = { row, col, token: h.token, letter, grain: h.grain, id: h.id, obj }; + this.tentative.push(t); + if (typed) this.typed.push(t); + this.boardC.bringToTop(this.cursorG); + SFX.clack(this, 0.45); + this.clearGhosts(); + if (render) { this.renderRack(); this.updatePreview(); this.updateControls(); } + return true; + } + + recallTentative(t, { render = true, index = null } = {}) { + t.obj.destroy(); + this.tentative = this.tentative.filter(x => x !== t); + this.typed = this.typed.filter(x => x !== t); + const entry = { id: t.id, token: t.token, grain: t.grain }; + if (index == null) this.hand.push(entry); else this.hand.splice(index, 0, entry); + if (render) { this.renderRack(); this.updatePreview(); this.updateControls(); } + } + + updatePreview() { + if (!this.settings.preview || !this.tentative.length || this.state.turn !== 0) { this.preview.hide(); return; } + const placements = this.tentative.map(t => ({ row: t.row, col: t.col, letter: t.letter, blank: t.token === BLANK })); + const chk = LG.checkPlay(this.state, placements); + if (!chk.ok) { this.preview.hide(); return; } + let tone = 'unknown'; + if (this.state.rule === 'friendly') tone = chk.words.every(w => isValidWord(w)) ? 'ok' : 'bad'; + const top = placements.reduce((a, b) => (b.row < a.row || (b.row === a.row && b.col < a.col) ? b : a)); + const at = this.squareWorld(top.row, top.col); + this.preview.show(at.x, at.y - 52, chk.score, chk.words, tone); + } + + // Keep the hand in step with the state's rack (after draws / returns). + syncHand({ fromBag = false } = {}) { + const rack = this.state.players[0].rack.slice(); + for (const t of this.tentative) { const i = rack.indexOf(t.token); if (i >= 0) rack.splice(i, 1); } + const keep = []; + for (const h of this.hand) { const i = rack.indexOf(h.token); if (i >= 0) { rack.splice(i, 1); keep.push(h); } } + const added = rack.map(newEntry); + this.hand = keep.concat(added); + for (const [id, o] of this.rackObjs) if (!this.hand.some(h => h.id === id)) { o.destroy(); this.rackObjs.delete(id); } + this.renderRack({ animate: true }); + if (fromBag && added.length) { + SFX.rustle(this, 160 + added.length * 60); + this.wobbleBag(); + added.forEach((h, i) => { + const o = this.rackObjs.get(h.id); + if (!o) return; + const tx = o._homeX, ty = o._homeY; + this.tweens.killTweensOf(o); + o.setPosition(this.bag.x, this.bag.y - L.BAG.h * 0.6).setScale(0.4).setAlpha(0); + this.tweens.add({ targets: o, x: tx, y: ty, scale: 1, alpha: 1, duration: 420, delay: i * 110, ease: 'Cubic.easeOut', onComplete: () => SFX.rackTap(this) }); + }); + } + } + + // ── Input ────────────────────────────────────────────────────────────────── + + setupInput() { + this.input.on('pointerdown', (p, over) => this.onDown(p, over)); + this.input.on('pointermove', (p) => this.onMove(p)); + this.input.on('pointerup', (p) => this.onUp(p)); + this.onKey = (e) => this.handleKey(e); + this.input.keyboard.on('keydown', this.onKey); + } + + boardSquareAt(x, y) { + const lp = this.boardC.pointToContainer({ x, y }); + return L.squareAtLocal(lp.x, lp.y); + } + + onDown(p, over) { + if (this.modal || this.endUI) return; + const rackObj = over.find(o => o._entry && this.rackObjs.get(o._entry.id) === o); + if (rackObj) { this.press = { kind: 'rack', obj: rackObj, entry: rackObj._entry, x0: p.x, y0: p.y }; return; } + const sq = this.boardSquareAt(p.x, p.y); + if (!sq) return; + const t = this.tentative.find(x => x.row === sq.row && x.col === sq.col); + if (t) { this.press = { kind: 'board', t, x0: p.x, y0: p.y }; return; } + if (this.ghosts.length && this.ghostMove?.placements.some(g => g.row === sq.row && g.col === sq.col)) { this.press = { kind: 'ghost', x0: p.x, y0: p.y }; return; } + this.press = { kind: 'square', sq, x0: p.x, y0: p.y }; + } + + onMove(p) { + if (this.press && !this.drag && Math.hypot(p.x - this.press.x0, p.y - this.press.y0) > 7) this.startDrag(p); + if (this.drag) { + this.drag.obj.setPosition(p.x, p.y - 6); + if (L.inRackZone(p.x, p.y)) this.rackGap(L.rackIndexAt(p.x, this.hand.length + 1)); + else this.rackGap(null); + this.tip.hide(); + return; + } + this.hover(p); + } + + startDrag(p) { + const pr = this.press; + if (!this.humanCanAct() || this.exchangeMode || pr.kind === 'square' || pr.kind === 'ghost') { this.press = null; return; } + if (pr.kind === 'rack') { + const idx = this.hand.indexOf(pr.entry); + this.hand.splice(idx, 1); + pr.obj.setDepth(DEPTH.drag).setScale(1.08); + this.tweens.killTweensOf(pr.obj); + this.drag = { obj: pr.obj, entry: pr.entry, from: 'rack', index: idx }; + this.rackObjs.delete(pr.entry.id); + this.renderRack(); + } else if (pr.kind === 'board') { + const t = pr.t; + t.obj.destroy(); + this.tentative = this.tentative.filter(x => x !== t); + this.typed = this.typed.filter(x => x !== t); + const entry = { id: t.id, token: t.token, grain: t.grain }; + const obj = makeTile(this, t.token, L.RACK.tile, { grain: t.grain, letter: t.token === BLANK ? t.letter : null }); + obj.setPosition(p.x, p.y).setDepth(DEPTH.drag).setScale(1.08); + this.drag = { obj, entry, from: 'board', home: { row: t.row, col: t.col }, letter: t.letter }; + this.updatePreview(); + } + this.press = null; + this.clearCursor(); + } + + rackGap(index) { + if (index === this.gapIndex) return; + this.gapIndex = index; + const n = this.hand.length + (index == null ? 0 : 1); + let slot = 0; + for (const h of this.hand) { + if (slot === index) slot++; + const o = this.rackObjs.get(h.id); + if (o) this.tweens.add({ targets: o, x: L.rackSlotX(slot, n), duration: 110, ease: 'Cubic.easeOut' }); + slot++; + } + } + + onUp(p) { + const pr = this.press; + this.press = null; + if (this.drag) { this.endDrag(p); return; } + if (!pr || this.modal || this.endUI) return; + if (pr.kind === 'rack') { + if (!this.humanCanAct()) return; + if (this.exchangeMode) { + const id = pr.entry.id; + if (this.exchangeSel.has(id)) this.exchangeSel.delete(id); else this.exchangeSel.add(id); + SFX.rackTap(this); + this.renderRack(); + this.updateControls(); + return; + } + // click a rack tile with a typing cursor → place it there + if (this.cursor) { this.typeEntry(pr.entry); return; } + SFX.rackTap(this); + this.tweens.add({ targets: pr.obj, y: pr.obj._homeY - 8, duration: 90, yoyo: true }); + this.setStatus('Drag a tile to the board, or click a square first and then type or click tiles.'); + } else if (pr.kind === 'board') { + if (!this.humanCanAct()) return; + this.recallTentative(pr.t); + SFX.rackTap(this); + } else if (pr.kind === 'ghost') { + if (this.humanCanAct()) this.useGhost(); + } else if (pr.kind === 'square') { + if (!this.humanCanAct() || this.exchangeMode) return; + const { row, col } = pr.sq; + if (!this.squareFree(row, col)) return; + if (this.cursor && this.cursor.row === row && this.cursor.col === col) this.cursor.dir = this.cursor.dir === 'across' ? 'down' : 'across'; + else this.cursor = { row, col, dir: this.cursor?.dir ?? this.guessDir(row, col) }; + this.drawCursor(); + } + } + + endDrag(p) { + const d = this.drag; + this.drag = null; + this.gapIndex = null; + const sq = this.boardSquareAt(p.x, p.y); + const entry = d.entry; + const objDone = () => d.obj.destroy(); + if (sq && this.squareFree(sq.row, sq.col) && this.humanCanAct()) { + objDone(); + // Back into the hand first: placeEntry takes it out again, and a cancelled + // blank picker leaves it safely on the rack. + this.hand.splice(Math.min(d.index ?? this.hand.length, this.hand.length), 0, entry); + if (!this.placeEntry(entry, sq.row, sq.col, entry.token === BLANK ? (d.letter ?? null) : null)) this.renderRack(); + return; + } + if (L.inRackZone(p.x, p.y) || d.from === 'rack' || !this.humanCanAct()) { + const idx = L.inRackZone(p.x, p.y) ? L.rackIndexAt(p.x, this.hand.length + 1) : (d.index ?? this.hand.length); + this.hand.splice(Math.min(idx, this.hand.length), 0, entry); + if (d.from === 'rack') { + d.obj.setDepth(DEPTH.rack).setScale(1); + this.rackObjs.set(entry.id, d.obj); + d.obj._entry = entry; + } else objDone(); + SFX.rackTap(this); + this.renderRack(); + this.updatePreview(); + this.updateControls(); + return; + } + // dropped somewhere else: a board tile goes back to its square + objDone(); + if (d.from === 'board' && this.squareFree(d.home.row, d.home.col)) this.placeEntry(entry, d.home.row, d.home.col, d.letter); + else { this.hand.push(entry); this.renderRack(); this.updatePreview(); this.updateControls(); } + } + + hover(p) { + if (!this.state || this.modal || this.endUI) { this.tip?.hide(); return; } + const sq = this.boardSquareAt(p.x, p.y); + if (sq) { + const cell = this.state.board[sq.row][sq.col]; + if (cell) { + const e = this.state.log[cell.move]; + const who = cell.seat === 0 ? 'You' : this.state.players[cell.seat]?.name; + const text = e && e.type === 'play' ? `${e.word}${cell.blank ? ' (blank as ' + cell.letter + ')' : ''}\n${who} · ${e.score} points` : `${who}${cell.blank ? ' · blank as ' + cell.letter : ''}`; + this.tip.show(p.x, p.y - 46, text); + return; + } + const prem = PREMIUM[sq.row][sq.col]; + if (prem.label && !this.tentative.some(t => t.row === sq.row && t.col === sq.col)) { + const st = PREMIUM_STYLE[prem.label]; + const centre = sq.row === 7 && sq.col === 7; + this.tip.show(p.x, p.y - 40, centre ? 'Centre star · double word\nThe first play must cover it' : `${st.name} score`); return; } } + const inR = (r) => Math.abs(p.x - r.x) < r.w / 2 && Math.abs(p.y - r.y) < r.h / 2; + if (inR(L.BAG)) { this.tip.show(p.x, p.y - 50, `${this.state.bag.length} tiles in the bag`); return; } + if (inR(L.DICT)) { this.tip.show(p.x, p.y - 50, 'The dictionary · Word Judge'); return; } + this.tip.hide(); + } - if (move.type === 'exchange' && this.bag.length >= 1) { - this.aiExchange(player, move.tiles ?? []); + // ── Typing ───────────────────────────────────────────────────────────────── + + guessDir(row, col) { + // Continue the line the tentative tiles already form, else read the board. + if (this.tentative.length >= 1) { + const t = this.tentative[0]; + if (this.tentative.every(x => x.row === t.row) && t.row === row) return 'across'; + if (this.tentative.every(x => x.col === t.col) && t.col === col) return 'down'; + } + const b = this.state.board; + const h = !!(b[row]?.[col - 1] || b[row]?.[col + 1]); + const v = !!(b[row - 1]?.[col] || b[row + 1]?.[col]); + return v && !h ? 'down' : 'across'; + } + + drawCursor() { + const g = this.cursorG; + g.clear(); + if (!this.cursor || !this.humanCanAct()) return; + const q = L.squareLocal(this.cursor.row, this.cursor.col); + g.lineStyle(3, 0xfff1c2, 1); + g.strokeRoundedRect(q.x - L.SQ / 2 + 2, q.y - L.SQ / 2 + 2, L.SQ - 4, L.SQ - 4, 6); + g.fillStyle(0xfff1c2, 1); + if (this.cursor.dir === 'across') g.fillTriangle(q.x - 7, q.y - 10, q.x - 7, q.y + 10, q.x + 11, q.y); + else g.fillTriangle(q.x - 10, q.y - 7, q.x + 10, q.y - 7, q.x, q.y + 11); + this.boardC.bringToTop(g); + } + + clearCursor() { this.cursor = null; this.cursorG?.clear(); } + + advanceCursor() { + const c = this.cursor; + if (!c) return; + let { row, col } = c; + do { + if (c.dir === 'across') col++; else row++; + } while (row < BOARD_SIZE && col < BOARD_SIZE && !this.squareFree(row, col)); + if (row >= BOARD_SIZE || col >= BOARD_SIZE) this.clearCursor(); + else { this.cursor = { row, col, dir: c.dir }; this.drawCursor(); } + } + + typeEntry(h, blankLetter = null) { + if (!this.cursor) return; + const { row, col } = this.cursor; + if (h.token === BLANK && !blankLetter) { + const cur = this.cursor; + DLG.openBlankPicker(this, (letter) => { + if (!letter) return; + this.cursor = cur; + if (this.placeEntry(h, row, col, letter, { typed: true })) this.advanceCursor(); + }); return; } - - // pass - this.scorelessTurns += 1; - this.noteLastText.setText(`${player.name}: passed`); - this.advanceTurn(); + if (this.placeEntry(h, row, col, blankLetter, { typed: true })) this.advanceCursor(); } - aiExchange(player, tiles) { - const returned = []; - for (const tok of tiles) { - const idx = player.rack.indexOf(tok); - if (idx !== -1) returned.push(player.rack.splice(idx, 1)[0]); - } - if (returned.length) { - player.rack.push(...drawTiles(this.bag, returned.length)); - this.bag.push(...returned); - shuffle(this.bag); - } - this.scorelessTurns += 1; - this.noteLastText.setText(`${player.name}: exchanged ${returned.length}`); - this.renderOpponentRacks(); - this.updateNotepad(); - playSound(this, SFX.CARD_SHUFFLE); - this.advanceTurn(); - } - - animateAIPlacements(placements) { - return new Promise(resolve => { - // commit to board model up front so renderCommittedTile reads letters - this.board = applyPlacements(this.board, placements); - placements.forEach((p, i) => { - this.time.delayedCall(i * 160, () => { - this.renderCommittedTile(p.row, p.col); - playSound(this, SFX.PIECE_CLICK); - if (i === placements.length - 1) this.time.delayedCall(220, resolve); - }); - }); - }); - } - - // ── Opponent face-down racks + active highlight ──────────────────────────────── - - renderOpponentRacks() { - for (const arr of this.oppFaceObjs) for (const o of arr) o.destroy(); - this.oppFaceObjs = []; - const ai = this.players.filter(p => p.type === 'ai'); - ai.forEach((p) => { - const arr = []; - const size = 26, gap = 4; - p.rack.forEach((_, i) => { - const tile = this.makeTile(size, '', 0, { faceDown: true }); - tile.setPosition(p._faceX + size / 2 + i * (size + gap), p._faceY).setDepth(DEPTH.ui); - arr.push(tile); - }); - this.oppFaceObjs.push(arr); - }); - } - - highlightActive() { - const active = this.players[this.turnIndex]; - for (const p of this.players) { - if (p._blockBg) { - const on = p === active; - p._blockBg.setStrokeStyle(on ? 3 : 2, on ? COLORS.accent : 0x2a2a2c); - p._blockBg.setFillStyle(COLORS.panel, on ? 0.8 : 0.55); + handleKey(e) { + if (this.modal || this.endUI || this.challengeUI) return; + if (!this.humanCanAct()) return; + const k = e.key; + if (k === 'Enter') { this.onPlay(); return; } + if (k === 'Escape') { if (this.cursor) this.clearCursor(); else this.onRecall(); return; } + if (k === ' ') { this.onShuffle(); e.preventDefault?.(); return; } + if (this.exchangeMode) return; + if (k === 'Backspace') { + const t = this.typed.pop() ?? this.tentative[this.tentative.length - 1]; + if (t) { + const dir = this.cursor?.dir ?? this.guessDir(t.row, t.col); + this.recallTentative(t); + this.cursor = { row: t.row, col: t.col, dir }; + this.drawCursor(); } + return; } - const humanActive = active.type === 'human'; - this.rackTrayBg?.setStrokeStyle(3, humanActive ? COLORS.accent : 0x6b5d3e); - } - - // ── Notepad / status ────────────────────────────────────────────────────────── - - updateNotepad() { - this.players.forEach((p, i) => this.noteScoreObjs[i]?.scoreText.setText(String(p.score))); - this.noteBagText.setText(`Tiles in bag: ${this.bag.length}`); - } - - bumpScore(i) { - const obj = this.noteScoreObjs[i]?.scoreText; - if (obj) this.tweens.add({ targets: obj, scale: { from: 1.4, to: 1 }, duration: 220, ease: 'Back.easeOut' }); - } - - flashStatus(msg) { - this.statusText.setText(msg); - if (this._statusTimer) this._statusTimer.remove(); - this._statusTimer = this.time.delayedCall(2600, () => this.statusText.setText('')); - } - - clearStatus() { this.statusText.setText(''); } - - // ── Game over ────────────────────────────────────────────────────────────────── - - endGame(outPlayer) { - if (this.gameOver) return; - this.gameOver = true; - this.setControlsEnabled(false); - - // Final rack-penalty scoring - let bonus = 0; - for (const p of this.players) { - const v = rackValue(p.rack); - if (p !== outPlayer) { p.score -= v; bonus += v; } + if (k.startsWith('Arrow') && this.cursor) { + const d = { ArrowLeft: [0, -1, 'across'], ArrowRight: [0, 1, 'across'], ArrowUp: [-1, 0, 'down'], ArrowDown: [1, 0, 'down'] }[k]; + const r = Math.max(0, Math.min(14, this.cursor.row + d[0])), c = Math.max(0, Math.min(14, this.cursor.col + d[1])); + this.cursor = { row: r, col: c, dir: d[2] }; + this.drawCursor(); + return; + } + if (/^[a-zA-Z?]$/.test(k)) { + if (!this.cursor) { + // keep typing after the last tile if the line is obvious + const last = this.tentative[this.tentative.length - 1]; + if (!last) { this.setStatus('Click a square to start typing there.'); return; } + this.cursor = { row: last.row, col: last.col, dir: this.guessDir(last.row, last.col) }; + this.advanceCursor(); + if (!this.cursor) return; + } + const L2 = k.toUpperCase(); + if (L2 === '?') { const b = this.hand.find(h => h.token === BLANK); if (b) this.typeEntry(b); return; } + const h = this.hand.find(x => x.token === L2); + if (h) { this.typeEntry(h); return; } + const b = this.hand.find(x => x.token === BLANK); + if (b) { this.typeEntry(b, L2); return; } + SFX.thunk(this); + this.setStatus(`No ${L2} on your rack.`); } - if (outPlayer) outPlayer.score += bonus; - this.updateNotepad(); - - const winner = this.players.slice().sort((a, b) => b.score - a.score)[0]; - const humanWon = winner.type === 'human'; - this.recordResult(humanWon); - this.time.delayedCall(700, () => this.showVictoryScreen(winner, humanWon)); } - showVictoryScreen(winner, humanWon) { - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - const PW = 760, PH = 520; + // ── Animations / effects ─────────────────────────────────────────────────── - const fw = this.add.particles(cx, cy, 'scrabbleParticle', { - speed: { min: 80, max: 460 }, lifespan: 1400, scale: { start: 1.2, end: 0 }, alpha: { start: 1, end: 0 }, - quantity: 3, frequency: 35, angle: { min: 0, max: 360 }, - tint: [0xffd700, 0xff6644, 0xffffff, 0x44aaff, 0xff44aa, 0x88ff44], - emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(-GAME_WIDTH / 2, -GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT) }, - }).setDepth(DEPTH.victory - 1); - this.time.delayedCall(3200, () => { fw.stop(); this.time.delayedCall(1400, () => fw.destroy()); }); + squareWorld(row, col) { + const q = L.squareLocal(row, col); + const m = this.boardC.getWorldTransformMatrix(); + return { x: m.getX(q.x, q.y), y: m.getY(q.x, q.y) }; + } - this.add.rectangle(cx, cy, PW, PH, 0x0a0e14, 0.95).setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.victory); - this.add.text(cx, cy - PH / 2 + 56, humanWon ? 'You Win!' : `${winner.name} Wins!`, { - fontFamily: 'Righteous', fontSize: '46px', color: humanWon ? '#ffd700' : COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.victory + 1); + wordCentre(placements) { + const pts = placements.map(p => this.squareWorld(p.row, p.col)); + return { x: pts.reduce((s, p) => s + p.x, 0) / pts.length, y: pts.reduce((s, p) => s + p.y, 0) / pts.length }; + } - // final standings, sorted - const sorted = this.players.slice().sort((a, b) => b.score - a.score); - sorted.forEach((p, i) => { - const y = cy - 120 + i * 56; - this.add.text(cx - PW / 2 + 80, y, `${i + 1}. ${p.name}`, { - fontFamily: 'YummyCupcakes', fontSize: '38px', color: p === winner ? '#ffd700' : COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.victory + 1); - this.add.text(cx + PW / 2 - 80, y, String(p.score), { - fontFamily: 'YummyCupcakes', fontSize: '38px', color: p === winner ? '#ffd700' : COLORS.textHex, - }).setOrigin(1, 0.5).setDepth(DEPTH.victory + 1); + seatPoint(seat) { + if (seat === 0) return { x: L.HUMAN.x + L.HUMAN.w / 2, y: L.HUMAN.y + 20 }; + const r = L.seatRect(seat - 1); + return { x: r.x + r.w / 2, y: r.y + 30 }; + } + + floatAt(at, text, color = CREAM, size = 28) { + const t = this.add.text(at.x, at.y, text, { fontFamily: SERIF, fontSize: `${size}px`, color, fontStyle: 'bold' }).setOrigin(0.5).setDepth(DEPTH.tip); + t.setShadow(0, 3, 'rgba(0,0,0,0.85)', 6); + this.tweens.add({ targets: t, y: at.y - 56, alpha: { from: 1, to: 0 }, duration: 1300, ease: 'Sine.easeOut', onComplete: () => t.destroy() }); + } + + stamp(text, color) { + const t = this.add.text(L.BOARD.cx, L.BOARD.cy, text, { fontFamily: SERIF, fontSize: '84px', color, fontStyle: 'bold' }).setOrigin(0.5).setDepth(DEPTH.tip).setAngle(-8).setAlpha(0); + t.setStroke('#1a0f08', 8); + this.tweens.add({ targets: t, alpha: 1, scale: { from: 1.8, to: 1 }, duration: 260, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, delay: 1300, duration: 400, onComplete: () => t.destroy() }); + } + + bingo(seat) { + SFX.bingoChime(this); + this.stamp('BINGO! +50', '#e2c378'); + const fx = this.add.particles(L.BOARD.cx, L.BOARD.cy, 'wsm-dot', { + speed: { min: 120, max: 420 }, lifespan: 1100, scale: { start: 0.7, end: 0 }, alpha: { start: 1, end: 0 }, + quantity: 40, emitting: false, tint: [0xe2c378, 0xfff2c8, 0xb9733a], + }).setDepth(DEPTH.tip - 1); + fx.explode(60); + this.time.delayedCall(1400, () => fx.destroy()); + if (seat === 0) this.state.players.slice(1).forEach((_, i) => this.seats.portrait(i + 1)?.playEmotion?.('upset')); + else this.seats.portrait(seat)?.playEmotion?.('happy'); + } + + wobbleBag() { + this.tweens.add({ targets: this.bag, angle: { from: -5, to: 5 }, duration: 90, yoyo: true, repeat: 2, onComplete: () => this.bag.setAngle(0) }); + } + + async tilesToBag(from, n) { + for (let i = 0; i < n; i++) { + const t = this.add.image(from.x, from.y, 'wsm-back').setDepth(DEPTH.fly); + this.tweens.add({ targets: t, x: this.bag.x, y: this.bag.y - L.BAG.h * 0.55, scale: 0.5, alpha: 0, duration: 360, delay: i * 70, ease: 'Cubic.easeIn', onComplete: () => t.destroy() }); + } + SFX.rustle(this, 300); + this.wobbleBag(); + await this.wait(360 + n * 70); + } + + async tilesFromBag(to, n) { + for (let i = 0; i < n; i++) { + const t = this.add.image(this.bag.x, this.bag.y - L.BAG.h * 0.55, 'wsm-back').setDepth(DEPTH.fly).setScale(0.5).setAlpha(0); + this.tweens.add({ targets: t, x: to.x, y: to.y, scale: 1, alpha: 1, duration: 380, delay: i * 80, ease: 'Cubic.easeOut', onComplete: () => t.destroy() }); + } + if (n) { SFX.rustle(this, 140 + n * 50); this.wobbleBag(); } + await this.wait(380 + n * 80); + this.seats.update(this.state, { active: this.state.turn, hints: this.settings.coach === 'off' ? null : this.hintsLeft }); + } + + flashEntry(e) { + if (!e.placements) return; + const g = this.add.graphics(); + this.boardC.add(g); + for (const p of e.placements) { + const q = L.squareLocal(p.row, p.col); + g.lineStyle(4, 0xfff1c2, 1); + g.strokeRoundedRect(q.x - L.SQ / 2 + 1, q.y - L.SQ / 2 + 1, L.SQ - 2, L.SQ - 2, 6); + } + this.tweens.add({ targets: g, alpha: { from: 1, to: 0 }, duration: 500, yoyo: true, repeat: 2, onComplete: () => g.destroy() }); + const who = e.seat === 0 ? 'You' : this.state.players[e.seat].name; + this.setStatus(`${who}: ${e.words.join(', ')} for ${e.score}${e.bingo ? ' (bingo)' : ''}.`); + } + + // The opening draw: everyone draws a tile, nearest to A starts, then the deal. + async openingCeremony() { + const gen = this.gen; + const s = this.state; + this.busy = true; + // hide what's about to be dealt + for (const o of this.rackObjs.values()) o.setVisible(false); + this.seats.plates.forEach(o => o.backs?.forEach(b => b.setVisible(false))); + this.setStatus('Drawing for first play: closest to A goes first (a blank beats them all).'); + for (const round of s.firstDraw) { + const shown = []; + for (const d of round) { + const at = d.seat === 0 ? { x: L.HUMAN.x + L.HUMAN.w - 60, y: L.HUMAN.y + 120 } : (() => { const r = L.seatRect(d.seat - 1); return { x: r.x + r.w - 60, y: r.y + r.h - 40 }; })(); + const t = makeTile(this, d.token, 50, { letter: d.token === BLANK ? '?' : null }); + t.setPosition(this.bag.x, this.bag.y - 80).setDepth(DEPTH.fly).setScale(0.4); + this.tweens.add({ targets: t, x: at.x, y: at.y, scale: 1, duration: 420, ease: 'Cubic.easeOut' }); + shown.push(t); + SFX.rustle(this, 160); + await this.wait(220); + if (!this.alive(gen)) return; + } + await this.wait(1100); + if (!this.alive(gen)) return; + for (const t of shown) this.tweens.add({ targets: t, x: this.bag.x, y: this.bag.y - 80, scale: 0.3, alpha: 0, duration: 320, ease: 'Cubic.easeIn', onComplete: () => t.destroy() }); + await this.wait(340); + } + const first = s.firstSeat; + this.setStatus(first === 0 ? 'You drew closest to A, so you go first.' : `${s.players[first].name} drew closest to A and goes first.`); + this.floatAt(this.seatPoint(first), 'plays first', '#fff1c2', 24); + await this.wait(600); + // the deal + this.seats.plates.forEach(o => o.backs?.forEach(b => b.setVisible(false))); + const objs = [...this.rackObjs.values()]; + objs.forEach((o, i) => { + const tx = o._homeX, ty = o._homeY; + o.setVisible(true).setPosition(this.bag.x, this.bag.y - 80).setScale(0.4).setAlpha(0); + this.tweens.add({ targets: o, x: tx, y: ty, scale: 1, alpha: 1, duration: 420, delay: i * 90, ease: 'Cubic.easeOut', onComplete: () => SFX.rackTap(this) }); }); - - const btnsY = cy + PH / 2 - 56; - new Button(this, cx - 130, btnsY, 'Play Again', () => this.scene.restart({ ...this._initData }), { - width: 230, height: 52, fontSize: 22, - }).setDepth(DEPTH.victory + 1); - new Button(this, cx + 130, btnsY, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 230, height: 52, fontSize: 22, - }).setDepth(DEPTH.victory + 1); + for (let seat = 1; seat < s.players.length; seat++) this.tilesFromBag(this.seats.rackPoint(seat), RACK_SIZE); + SFX.rustle(this, 700); + await this.wait(1100); + if (!this.alive(gen)) return; + this.renderAll(); } - async recordResult(humanWon) { - try { - const opponentScores = this.players.filter(p => p.type === 'ai').map(p => Math.max(0, p.score)); - await api.post('/history/single-player', { - slug: 'scrabble', - score: Math.max(0, this.players[0].score), - opponentScores, - result: humanWon ? 'win' : 'loss', + // ── Menus ────────────────────────────────────────────────────────────────── + + openRules() { new TutorialModal(this.gameDef ?? { slug: SLUG }).open(); } + + openSettings() { + const live = { rule: this.state.rule, clock: this.state.clockMs ? Math.round(this.state.clockMs / 60000) : 0 }; + DLG.openSettings(this, this.settings, (key) => { + if (key === 'labels' || key === 'patterns') this.rebakeBoard(); + if (key === 'tracker') this.tracker.setVisible(this.settings.tracker); + if (key === 'pace') this.pace = PACE[this.settings.pace] ?? 1; + if (key === 'coach') { + this.hintsLeft = this.settings.coach === 'practice' ? Infinity : this.settings.coach === 'off' ? 0 : Math.min(HINTS_PER_GAME, Number.isFinite(this.hintsLeft) ? this.hintsLeft : HINTS_PER_GAME); + this.clearGhosts(); + } + if (key === 'preview') this.updatePreview(); + if (key === 'turntable') this.lean(this.state.turn); + this.renderAll(); + }, { live }); + } + + openPause() { + if (this.modal) return; + this.paused = true; + this.time.paused = true; + this.tweens.pauseAll(); + const resume = () => { this.paused = false; this.time.paused = false; this.tweens.resumeAll(); }; + DLG.openMenu(this, [ + { label: 'Resume', fn: () => {} }, + { label: 'Word Judge', fn: () => DLG.openWordJudge(this, { disabled: !!this.state.pending }) }, + { label: 'Your record', fn: () => DLG.openStats(this, loadStats(SLUG), { bestWord: loadBestWord() }) }, + { label: 'New game', fn: () => DLG.confirmDialog(this, 'Start a new game?', 'This game will count as a loss.', 'New game', () => { this.recordEnd(false, true); clearSave(); this.scene.restart({ ...this._initData, fresh: true }); }) }, + { label: 'Leave the table', fn: () => { this.writeSave(); this.scene.start('GameMenu'); } }, + ], { title: 'Paused', onClose: resume }); + } + + closeModal() { this.modal?.close(); } + + // ── End ──────────────────────────────────────────────────────────────────── + + finish() { + if (this.endUI) return; + this.busy = true; + this.clearCursor(); + this.lean(0); + this.renderAll(); + const s = this.state; + const won = s.end.winners.includes(0) && s.end.winners.length === 1; + this.recordEnd(won); + clearSave(); + const review = s.log.filter(e => e.seat === 0 && e.type === 'play').map(e => ({ type: 'play', word: e.word, score: e.score, best: e.best ?? null })); + if (won) this.seats.plates.slice(1).forEach(o => o.portrait?.playEmotion?.('upset')); + else this.seats.portrait(s.end.winners[0])?.playEmotion?.('happy'); + this.time.delayedCall(900, () => { + if (!this.sys.isActive()) return; + this.endUI = showEndScreen(this, s, review, { + again: () => this.scene.restart({ ...this._initData, fresh: true }), + leave: () => this.scene.start('GameMenu'), }); - } catch { /* best effort */ } + }); } - // ── Utility ──────────────────────────────────────────────────────────────────── - - serializeBoard() { - return this.board.map(row => row.map(cell => (cell ? { letter: cell.letter, blank: !!cell.blank } : null))); + recordEnd(won, forfeit = false) { + if (this._recorded) return; + this._recorded = true; + const s = this.state; + if (!s) return; + const me = s.players[0]; + try { + recordGame(SLUG, { won, extra: { score: me.score, opp: s.players.slice(1).map(p => p.score), forfeit } }); + if (!forfeit) { + recordBest(SLUG, 'highGame', me.score, { lower: false }); + bumpCount(SLUG, 'points', { n: Math.max(0, me.score) }); + if (me.bingos) bumpCount(SLUG, 'bingos', { n: me.bingos }); + const bw = loadBestWord(); + if (me.best && (!bw || me.best.score > bw.score)) localStorage.setItem(BEST_WORD_KEY, JSON.stringify(me.best)); + } + } catch { /* storage is best effort */ } + api.post('/history/single-player', { + slug: SLUG, + score: Math.max(0, me.score), + opponentScores: s.players.slice(1).map(p => Math.max(0, p.score)), + result: won ? 'win' : 'loss', + }).catch(() => {}); } - canHumanAct() { - return !this.gameOver && !this.animating && !this.blankPicking && this.players[this.turnIndex]?.type === 'human'; + // ── Save / clock / util ──────────────────────────────────────────────────── + + writeSave() { + const s = this.state; + if (!s || s.over || s.pending) return; + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ + v: 1, opps: this.opponents.map(o => o.id ?? o.name), state: s, + hintsLeft: Number.isFinite(this.hintsLeft) ? this.hintsLeft : -1, + handOrder: this.hand.map(h => h.token).concat(this.tentative.map(t => t.token)), + })); + } catch { /* full */ } } - delay(ms) { return new Promise(resolve => this.time.delayedCall(ms, resolve)); } + update(_t, dt) { + const s = this.state; + if (!s || s.over || this.paused || !s.clockMs || s.pending || this.endUI) return; + const p = s.players[s.turn]; + const before = p.timeLeft; + LG.spendClock(s, s.turn, dt); + this._clockAcc = (this._clockAcc ?? 0) + dt; + if (this._clockAcc > 250) { + this._clockAcc = 0; + this.seats.update(s, { active: s.turn, hints: this.settings.coach === 'off' ? null : this.hintsLeft }); + } + if (s.turn === 0 && p.timeLeft < 60000 && p.timeLeft > -600000 && Math.floor(before / 1000) !== Math.floor(p.timeLeft / 1000)) SFX.tick(this); + if (before >= 0 && p.timeLeft < 0) this.setStatus(`${s.turn === 0 ? 'Your' : `${p.name}'s`} clock has run out: −10 points for every minute over.`); + } - shutdown() { - for (const p of this.players) p.portrait?.destroy?.(); + setStatus(t) { this.status?.setText(t ?? ''); } + wait(ms) { return new Promise(res => this.time.delayedCall(Math.max(0, ms), res)); } + alive(gen) { return this.sys.isActive() && gen === this.gen; } + + teardown() { + this.gen++; + if (this.onKey) this.input.keyboard?.off('keydown', this.onKey); + this.seats?.destroy(); + this.modal?.close(); } } + +// ── Save helpers ────────────────────────────────────────────────────────────── + +function loadSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || !s.state || s.state.over) return null; + if (s.hintsLeft === -1) s.hintsLeft = Infinity; + return s; + } catch { return null; } +} +function clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch { /* ignore */ } } +function sameTable(save, opps) { + const ids = opps.map(o => o.id ?? o.name); + return save.opps?.length === ids.length && save.opps.every((x, i) => x === ids[i]); +} +function sameMultiset(a, b) { return a.length === b.length && a.slice().sort().join() === b.slice().sort().join(); } +function loadBestWord() { try { return JSON.parse(localStorage.getItem(BEST_WORD_KEY) || 'null'); } catch { return null; } } + diff --git a/src/games/scrabble/ScrabbleHud.js b/src/games/scrabble/ScrabbleHud.js new file mode 100644 index 0000000..212247e --- /dev/null +++ b/src/games/scrabble/ScrabbleHud.js @@ -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 }; diff --git a/src/games/scrabble/ScrabbleLayout.js b/src/games/scrabble/ScrabbleLayout.js new file mode 100644 index 0000000..ce66462 --- /dev/null +++ b/src/games/scrabble/ScrabbleLayout.js @@ -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; +} diff --git a/src/games/scrabble/ScrabbleLogic.js b/src/games/scrabble/ScrabbleLogic.js index f8447e9..d4e7354 100644 --- a/src/games/scrabble/ScrabbleLogic.js +++ b/src/games/scrabble/ScrabbleLogic.js @@ -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))); +} diff --git a/src/games/scrabble/ScrabbleSound.js b/src/games/scrabble/ScrabbleSound.js new file mode 100644 index 0000000..7b8ed8e --- /dev/null +++ b/src/games/scrabble/ScrabbleSound.js @@ -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 }); + }); +} diff --git a/src/games/scrabble/ScrabbleTiles.js b/src/games/scrabble/ScrabbleTiles.js index c82c8fe..8d08f28 100644 --- a/src/games/scrabble/ScrabbleTiles.js +++ b/src/games/scrabble/ScrabbleTiles.js @@ -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 = [ diff --git a/src/games/scrabble/tutorial.md b/src/games/scrabble/tutorial.md new file mode 100644 index 0000000..5b65c5b --- /dev/null +++ b/src/games/scrabble/tutorial.md @@ -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.* diff --git a/src/words/scrabbleEngine.js b/src/words/scrabbleEngine.js index 70fa957..bd5db62 100644 --- a/src/words/scrabbleEngine.js +++ b/src/words/scrabbleEngine.js @@ -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()); - } - - 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); + 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; + } + } + 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; + }; + if (reach(true) && !reach(false)) n++; + } + 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, }; - 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)) }; +// 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 { type: 'pass' }; + 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)); } diff --git a/src/words/wordRouter.js b/src/words/wordRouter.js index 585d80c..c268ed0 100644 --- a/src/words/wordRouter.js +++ b/src/words/wordRouter.js @@ -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? } diff --git a/tools/verifyWordsmith.js b/tools/verifyWordsmith.js new file mode 100644 index 0000000..71ef26a --- /dev/null +++ b/tools/verifyWordsmith.js @@ -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))); +}