Rework Boggle into a full game-night experience with solo modes and AI rework
- Add 70s family-den art (baked textures), layout, tray/pad/seats/review/dialog modules - Support 4x4 and 5x5 boards, untimed practice, hints, daily board, and match saves/resume - Rework AI with vocabulary tiers, spotting hazards, word-family boosts, and pencil time - Tag dictionary words with familiarity tiers; seed board generation for the Daily Board - Add scoring sheet reveal, board review, end screen with personal records, and a tutorial - Register Boggle as playable solo (minPlayers 1) with hasTutorial - Add headless verification tool covering logic, engine, AI, and layout
This commit is contained in:
parent
1afdd75a61
commit
d53171cccb
|
|
@ -61,7 +61,7 @@ registerGame({ slug: 'go', name: 'Go', category: 'tabletop', minPlayers: 2, maxP
|
|||
registerGame({ slug: 'battleship', name: 'Battleship', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 31 });
|
||||
registerGame({ slug: 'mastermind', name: 'Mastermind', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 32 });
|
||||
registerGame({ slug: 'connect4', name: 'Connect 4', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 33 });
|
||||
registerGame({ slug: 'boggle', name: 'Boggle', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 34 });
|
||||
registerGame({ slug: 'boggle', name: 'Boggle', category: 'word', minPlayers: 1, maxPlayers: 4, minOpponents: 0, maxOpponents: 3, hasTutorial: true, iconFrame: 34 });
|
||||
registerGame({ slug: 'oldmaid', name: 'Old Maid', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 35 });
|
||||
registerGame({ slug: 'blokus', name: 'Blokus', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 36 });
|
||||
registerGame({ slug: 'spellingbee', name: 'Spelling Bee', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 37 });
|
||||
|
|
|
|||
|
|
@ -1,60 +1,116 @@
|
|||
// Boggle AI — no Phaser. Given the board solution set, produce a time-ordered
|
||||
// schedule of words an opponent "finds" during the round. Higher skill finds more
|
||||
// words and weights longer/rarer words more heavily.
|
||||
// Boggle AI — no Phaser. From the board's solution set, produce a time-ordered
|
||||
// schedule of the words an opponent "finds" during the round.
|
||||
//
|
||||
// The model is serial, like a person with one pencil:
|
||||
// 1. Vocabulary — does this player know the word at all? Chance by skill and
|
||||
// familiarity tier (1 everyday · 2 familiar · 3 obscure ENABLE-only).
|
||||
// 2. Spotting — every known, unfound word has a hazard 1 / (scale × difficulty);
|
||||
// difficulty grows with length and obscurity. The next find arrives after an
|
||||
// exponential wait at the summed rate (a Gillespie step), and which word it
|
||||
// is follows the hazards — so easy words go first and the pace slows as the
|
||||
// board's easy pickings run out. Natural bursts and lulls fall out of it.
|
||||
// 3. Writing — each find costs pencil time that grows with its length.
|
||||
// 4. Word families — a find makes its relatives on the board (RATE → RATES,
|
||||
// RATED, TEAR) much easier to spot for the next several seconds.
|
||||
|
||||
// Per-skill profile:
|
||||
// fraction — share of the solution set the AI ultimately finds
|
||||
// lengthBias — exponent applied to word length when weighting picks
|
||||
// (higher => strongly prefers longer words)
|
||||
const SKILL = {
|
||||
1: { fraction: 0.02, lengthBias: 0.4 },
|
||||
2: { fraction: 0.03, lengthBias: 0.8 },
|
||||
3: { fraction: 0.06, lengthBias: 1.3 },
|
||||
4: { fraction: 0.10, lengthBias: 1.9 },
|
||||
5: { fraction: 0.15, lengthBias: 2.6 },
|
||||
// know[tier1, tier2, tier3] scale (s) write (s/word base) family boost
|
||||
1: { know: [0.80, 0.18, 0.00], scale: 520, write: 2.6, family: 5 },
|
||||
2: { know: [0.88, 0.40, 0.02], scale: 330, write: 2.2, family: 6 },
|
||||
3: { know: [0.94, 0.65, 0.07], scale: 220, write: 1.9, family: 7 },
|
||||
4: { know: [0.97, 0.82, 0.20], scale: 150, write: 1.6, family: 8 },
|
||||
5: { know: [0.99, 0.94, 0.40], scale: 105, write: 1.35, family: 9 },
|
||||
};
|
||||
|
||||
function profile(skill) {
|
||||
return SKILL[Math.max(1, Math.min(5, skill | 0))] ?? SKILL[3];
|
||||
const LEAD_MS = 2500; // nobody writes a word in the first couple of seconds
|
||||
|
||||
export function profile(skill) {
|
||||
return SKILL[Math.max(1, Math.min(5, Math.round(skill) || 3))];
|
||||
}
|
||||
|
||||
// Weighted sampling without replacement.
|
||||
function pickWeighted(pool, weights, count) {
|
||||
const chosen = [];
|
||||
const idx = pool.map((_, i) => i);
|
||||
const w = [...weights];
|
||||
for (let k = 0; k < count && idx.length; k++) {
|
||||
let total = 0;
|
||||
for (const i of idx) total += w[i];
|
||||
let roll = Math.random() * total;
|
||||
let pickPos = 0;
|
||||
for (let p = 0; p < idx.length; p++) {
|
||||
roll -= w[idx[p]];
|
||||
if (roll <= 0) { pickPos = p; break; }
|
||||
}
|
||||
chosen.push(pool[idx[pickPos]]);
|
||||
idx.splice(pickPos, 1);
|
||||
// Relative difficulty of spotting a word (1 = an everyday 3-letter word).
|
||||
export function difficulty(word, tier = 2) {
|
||||
let d = 1 + 0.55 * Math.max(0, word.length - 3) + 0.04 * Math.max(0, word.length - 5) ** 2;
|
||||
d *= tier <= 1 ? 1 : tier === 2 ? 1.35 : 1.8;
|
||||
if (word.includes('QU')) d *= 1.15;
|
||||
return d;
|
||||
}
|
||||
|
||||
const SUFFIXES = ['INGS', 'ING', 'IEST', 'IER', 'IES', 'IED', 'EST', 'ERS', 'ER', 'ED', 'ES', 'LY', 'S', 'D', 'Y'];
|
||||
|
||||
// A rough stem so inflections group together: RATE, RATES, RATED, RATER → RAT.
|
||||
export function stemOf(word) {
|
||||
let w = word;
|
||||
for (const s of SUFFIXES) {
|
||||
if (w.length - s.length >= 3 && w.endsWith(s)) { w = w.slice(0, -s.length); break; }
|
||||
}
|
||||
return chosen;
|
||||
if (w.length >= 4 && w.endsWith('E')) w = w.slice(0, -1);
|
||||
return w;
|
||||
}
|
||||
|
||||
// solutions: [{ word, path }] (path unused by the AI but kept for parity)
|
||||
// Returns: [{ atMs, word }] sorted ascending by atMs.
|
||||
export function scheduleFinds(solutions, skill, durationMs) {
|
||||
if (!solutions?.length) return [];
|
||||
const { fraction, lengthBias } = profile(skill);
|
||||
|
||||
const words = solutions.map((s) => s.word);
|
||||
const weights = words.map((w) => Math.pow(w.length, lengthBias));
|
||||
const target = Math.max(1, Math.round(words.length * fraction));
|
||||
|
||||
const picks = pickWeighted(words, weights, target);
|
||||
|
||||
// Spread finds across the middle ~90% of the round with jitter so the count
|
||||
// ticks up naturally rather than all at once.
|
||||
const lead = durationMs * 0.05;
|
||||
const span = durationMs * 0.9;
|
||||
return picks
|
||||
.map((word) => ({ word, atMs: lead + Math.random() * span }))
|
||||
.sort((a, b) => a.atMs - b.atMs);
|
||||
// word → [related words on this board]
|
||||
export function familyMap(words) {
|
||||
const groups = new Map();
|
||||
const add = (key, w) => { if (!groups.has(key)) groups.set(key, []); groups.get(key).push(w); };
|
||||
for (const w of words) {
|
||||
add('s:' + stemOf(w), w);
|
||||
if (w.length >= 4 && w.length <= 7) add('a:' + [...w].sort().join(''), w);
|
||||
}
|
||||
const fam = new Map(words.map((w) => [w, new Set()]));
|
||||
for (const list of groups.values()) {
|
||||
if (list.length < 2) continue;
|
||||
for (const a of list) for (const b of list) if (a !== b) fam.get(a).add(b);
|
||||
}
|
||||
return new Map([...fam].map(([k, v]) => [k, [...v]]));
|
||||
}
|
||||
|
||||
const FAMILY_WINDOW_MS = 9000;
|
||||
|
||||
// solutions: [{ word, path, tier }]
|
||||
// Returns: [{ atMs, word }] sorted ascending by atMs (only finds inside the round).
|
||||
export function scheduleFinds(solutions, skill, durationMs, { minLen = 3, rng = Math.random } = {}) {
|
||||
if (!solutions?.length || !(durationMs > 0)) return [];
|
||||
const p = profile(skill);
|
||||
const pool = solutions.filter((s) => s.word.length >= minLen);
|
||||
const known = pool.filter((s) => rng() < p.know[Math.max(1, Math.min(3, s.tier ?? 2)) - 1]);
|
||||
if (!known.length) return [];
|
||||
|
||||
const base = known.map((s) => 1 / (p.scale * difficulty(s.word, s.tier ?? 2))); // per second
|
||||
const idx = new Map(known.map((s, i) => [s.word, i]));
|
||||
const fam = familyMap(known.map((s) => s.word));
|
||||
const boostUntil = new Float64Array(known.length); // ms
|
||||
const done = new Uint8Array(known.length);
|
||||
const exp = () => -Math.log(1 - rng() * 0.999999);
|
||||
|
||||
const out = [];
|
||||
const end = durationMs * 0.985;
|
||||
let t = LEAD_MS;
|
||||
for (let n = 0; n < known.length; n++) {
|
||||
let H = 0;
|
||||
const h = new Float64Array(known.length);
|
||||
for (let i = 0; i < known.length; i++) {
|
||||
if (done[i]) continue;
|
||||
h[i] = base[i] * (boostUntil[i] > t ? p.family : 1);
|
||||
H += h[i];
|
||||
}
|
||||
if (H <= 0) break;
|
||||
t += (exp() / H) * 1000;
|
||||
if (t > end) break;
|
||||
let roll = rng() * H, pick = -1;
|
||||
for (let i = 0; i < known.length; i++) {
|
||||
if (done[i]) continue;
|
||||
roll -= h[i];
|
||||
if (roll <= 0) { pick = i; break; }
|
||||
}
|
||||
if (pick < 0) { for (let i = known.length - 1; i >= 0; i--) if (!done[i]) { pick = i; break; } }
|
||||
done[pick] = 1;
|
||||
const word = known[pick].word;
|
||||
out.push({ atMs: Math.round(t), word });
|
||||
for (const rel of fam.get(word) ?? []) {
|
||||
const j = idx.get(rel);
|
||||
if (j != null && !done[j]) boostUntil[j] = t + FAMILY_WINDOW_MS;
|
||||
}
|
||||
t += (p.write * (0.75 + 0.5 * rng()) + 0.12 * word.length) * 1000; // pencil time
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,417 @@
|
|||
// BoggleArt.js — baked canvas textures for the 70s family-den game night.
|
||||
// Top-down: a teak coffee table on a burnt-orange shag rug, a woven runner under
|
||||
// the dice tray, warm lamp light pooling over the play area.
|
||||
//
|
||||
// boggle-room rug + teak table + runner + mug + candy dish + lamp light + vignette
|
||||
// boggle-glow extra warm lamp glow (pulsed in the last ten seconds)
|
||||
// boggle-sign wooden title plaque with 70s stripes
|
||||
// boggle-seat a rival's place card
|
||||
// boggle-practice the practice/daily score card
|
||||
// boggle-pad yellow legal pad
|
||||
// boggle-tray-N walnut tray with N×N recesses (N = 4 | 5)
|
||||
// boggle-die-N ivory die body (bevel, side faces, sheen) for size N
|
||||
// boggle-die-glow-N gold selection glow for size N
|
||||
// boggle-lid-N clear plastic dome lid for size N
|
||||
// boggle-spark small particle
|
||||
|
||||
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
|
||||
import {
|
||||
W, H, TABLE, SIGN, SEAT_W, SEAT_H, PRACTICE, PAD, PAD_BINDING, PAD_LIST, PAD_MARGIN_X, PAD_COUNTS_Y,
|
||||
TRAY_C, trayGeom,
|
||||
} from './BoggleLayout.js';
|
||||
|
||||
export const DISPLAY_FONT = 'Righteous, Georgia, serif';
|
||||
export const HAND_FONT = 'YummyCupcakes, "Comic Sans MS", cursive';
|
||||
export const PRINT_FONT = '"Julius Sans One", Georgia, serif';
|
||||
export const SERIF = 'Georgia, "Times New Roman", serif';
|
||||
|
||||
// 70s palette
|
||||
export const ORANGE = 0xd0652a, ORANGE_HEX = '#d0652a';
|
||||
export const MUSTARD = 0xd9a63a, MUSTARD_HEX = '#d9a63a';
|
||||
export const AVOCADO = 0x7d8a3a, AVOCADO_HEX = '#7d8a3a';
|
||||
export const BROWN = 0x5a3820, BROWN_HEX = '#5a3820';
|
||||
export const CREAM = 0xf6ecd2, CREAM_HEX = '#f6ecd2';
|
||||
export const INK_HEX = '#1f3a78'; // ballpoint blue
|
||||
export const PENCIL_HEX = '#3b3430';
|
||||
export const RED_HEX = '#b8321f';
|
||||
export const GOLD = 0xf3c04a;
|
||||
export const SEAT_TINT = [0xd0652a, 0x7d8a3a, 0xb8862b];
|
||||
export const DIE_INK = '#3a2414';
|
||||
|
||||
export const PAD_PX = 24; // shadow margin baked around tray / pad / cards
|
||||
|
||||
function addCanvas(scene, key, c) {
|
||||
if (scene.textures.exists(key)) scene.textures.remove(key);
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
|
||||
function dropShadow(ctx, fn, { blur = 22, dy = 10, alpha = 0.5 } = {}) {
|
||||
ctx.save();
|
||||
ctx.shadowColor = `rgba(0,0,0,${alpha})`;
|
||||
ctx.shadowBlur = blur; ctx.shadowOffsetY = dy;
|
||||
fn();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// Wood grain streaks inside a rect (horizontal by default).
|
||||
function grain(ctx, x, y, w, h, { tone = 'rgba(40,18,6,0.22)', lines = 40, wave = 3, vertical = false } = {}) {
|
||||
ctx.save();
|
||||
ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
|
||||
ctx.strokeStyle = tone;
|
||||
const len = vertical ? h : w, across = vertical ? w : h;
|
||||
for (let i = 0; i < lines; i++) {
|
||||
const off = Math.random() * across;
|
||||
const amp = wave * (0.4 + Math.random());
|
||||
const f = 0.003 + Math.random() * 0.008;
|
||||
const ph = Math.random() * 6;
|
||||
ctx.lineWidth = 0.6 + Math.random() * 1.6;
|
||||
ctx.beginPath();
|
||||
for (let t = 0; t <= len; t += 10) {
|
||||
const o = off + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.3 + ph) * amp * 0.35;
|
||||
const px = vertical ? x + o : x + t, py = vertical ? y + t : y + o;
|
||||
if (t === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// ── room ────────────────────────────────────────────────────────────────────
|
||||
function bakeRoom(scene) {
|
||||
const c = canvas(W, H);
|
||||
const ctx = c.getContext('2d');
|
||||
|
||||
// shag rug: burnt orange with dense fibre flecks
|
||||
ctx.fillStyle = '#8a3c16';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
const fib = ['#a44a1c', '#6e2c0e', '#c0612a', '#7a3412', '#b85a24'];
|
||||
for (let i = 0; i < 26000; i++) {
|
||||
const x = Math.random() * W, y = Math.random() * H;
|
||||
ctx.strokeStyle = fib[i % fib.length];
|
||||
ctx.lineWidth = 1 + Math.random() * 1.6;
|
||||
ctx.beginPath(); ctx.moveTo(x, y);
|
||||
ctx.lineTo(x + (Math.random() - 0.5) * 7, y + (Math.random() - 0.5) * 7);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// teak coffee table
|
||||
const t = TABLE;
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#6b3d1c'; rr(ctx, t.x, t.y, t.w, t.h, 34); ctx.fill(); }, { blur: 30, dy: 12, alpha: 0.6 });
|
||||
const tg = ctx.createLinearGradient(0, t.y, 0, t.y + t.h);
|
||||
tg.addColorStop(0, '#8e5a2e'); tg.addColorStop(0.5, '#7d4c25'); tg.addColorStop(1, '#6a3d1c');
|
||||
ctx.fillStyle = tg; rr(ctx, t.x + 8, t.y + 8, t.w - 16, t.h - 16, 28); ctx.fill();
|
||||
// teak planks (long, horizontal), with fine grain
|
||||
ctx.save(); rr(ctx, t.x + 8, t.y + 8, t.w - 16, t.h - 16, 28); ctx.clip();
|
||||
const plank = 132;
|
||||
for (let y = t.y + 8; y < t.y + t.h; y += plank) {
|
||||
ctx.fillStyle = `rgba(${Math.random() < 0.5 ? '255,220,170' : '40,16,4'},${0.03 + Math.random() * 0.05})`;
|
||||
ctx.fillRect(t.x, y, t.w, plank);
|
||||
grain(ctx, t.x, y, t.w, plank, { lines: 22, wave: 2.5 });
|
||||
ctx.fillStyle = 'rgba(30,12,2,0.45)'; ctx.fillRect(t.x, y, t.w, 2);
|
||||
}
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 18); ctx.fillRect(t.x, t.y, t.w, t.h);
|
||||
ctx.restore();
|
||||
// rim highlight
|
||||
ctx.strokeStyle = 'rgba(255,214,160,0.25)'; ctx.lineWidth = 3;
|
||||
rr(ctx, t.x + 10, t.y + 10, t.w - 20, t.h - 20, 27); ctx.stroke();
|
||||
|
||||
// woven runner under the tray: mustard / orange / brown stripes with fringe
|
||||
const ry0 = 150, ry1 = H - 120, rx0 = 470, rx1 = 1214;
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#c98d2c'; ctx.fillRect(rx0, ry0, rx1 - rx0, ry1 - ry0); }, { blur: 14, dy: 5, alpha: 0.35 });
|
||||
const stripes = ['#d9a63a', '#c26126', '#5a3820', '#d9a63a', '#7d8a3a', '#d9a63a', '#c26126'];
|
||||
const sw = (rx1 - rx0) / 23;
|
||||
for (let i = 0; i < 23; i++) {
|
||||
ctx.fillStyle = stripes[i % stripes.length];
|
||||
ctx.fillRect(rx0 + i * sw, ry0, sw + 0.5, ry1 - ry0);
|
||||
}
|
||||
// weave texture
|
||||
ctx.save(); ctx.beginPath(); ctx.rect(rx0, ry0, rx1 - rx0, ry1 - ry0); ctx.clip();
|
||||
for (let y = ry0; y < ry1; y += 6) {
|
||||
ctx.fillStyle = `rgba(0,0,0,${y % 12 ? 0.07 : 0.13})`;
|
||||
ctx.fillRect(rx0, y, rx1 - rx0, 3);
|
||||
}
|
||||
ctx.fillStyle = noisePattern(ctx, 96, 30); ctx.fillRect(rx0, ry0, rx1 - rx0, ry1 - ry0);
|
||||
ctx.restore();
|
||||
// fringe
|
||||
ctx.strokeStyle = '#e3c27a'; ctx.lineWidth = 2;
|
||||
for (let x = rx0 + 3; x < rx1; x += 7) {
|
||||
for (const [y, d] of [[ry0, -1], [ry1, 1]]) {
|
||||
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + (Math.random() - 0.5) * 4, y + d * (12 + Math.random() * 6)); ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
// coffee mug (orange with a daisy) bottom-left of the pad
|
||||
const mx = 1222, my = 978;
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#d0652a'; ctx.beginPath(); ctx.arc(mx, my, 40, 0, Math.PI * 2); ctx.fill(); }, { blur: 14, dy: 6, alpha: 0.5 });
|
||||
ctx.fillStyle = '#d0652a'; ctx.beginPath(); ctx.ellipse(mx + 44, my + 4, 15, 10, 0.3, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = '#7d4c25'; ctx.beginPath(); ctx.ellipse(mx + 44, my + 4, 8, 4, 0.3, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = '#e88a4a'; ctx.beginPath(); ctx.arc(mx, my, 34, 0, Math.PI * 2); ctx.fill();
|
||||
const cg = ctx.createRadialGradient(mx - 6, my - 6, 2, mx, my, 30);
|
||||
cg.addColorStop(0, '#5a3418'); cg.addColorStop(1, '#2a1406');
|
||||
ctx.fillStyle = cg; ctx.beginPath(); ctx.arc(mx, my, 29, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = 'rgba(255,235,200,0.35)'; ctx.beginPath(); ctx.ellipse(mx - 9, my - 10, 9, 4, -0.6, 0, Math.PI * 2); ctx.fill();
|
||||
// a coffee ring stain on the teak
|
||||
ctx.strokeStyle = 'rgba(40,18,4,0.25)'; ctx.lineWidth = 3;
|
||||
ctx.beginPath(); ctx.arc(1250, 120, 36, 0.4, Math.PI * 1.8); ctx.stroke();
|
||||
|
||||
// candy dish (avocado glass) bottom-left under the seats
|
||||
const dx = 470, dy = 1006;
|
||||
dropShadow(ctx, () => { ctx.fillStyle = 'rgba(125,138,58,0.9)'; ctx.beginPath(); ctx.ellipse(dx, dy, 56, 38, 0, 0, Math.PI * 2); ctx.fill(); }, { blur: 12, dy: 5, alpha: 0.45 });
|
||||
ctx.fillStyle = 'rgba(160,176,80,0.75)'; ctx.beginPath(); ctx.ellipse(dx, dy, 46, 30, 0, 0, Math.PI * 2); ctx.fill();
|
||||
const candy = ['#e0442a', '#f2c84a', '#3f8ad0', '#f0eada', '#8a3fb0'];
|
||||
for (let i = 0; i < 14; i++) {
|
||||
ctx.fillStyle = candy[i % candy.length];
|
||||
ctx.beginPath(); ctx.arc(dx + (Math.random() - 0.5) * 60, dy + (Math.random() - 0.5) * 36, 7, 0, Math.PI * 2); ctx.fill();
|
||||
}
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.35)'; ctx.beginPath(); ctx.ellipse(dx - 20, dy - 16, 16, 5, -0.3, 0, Math.PI * 2); ctx.fill();
|
||||
|
||||
// lamp light: warm pool over the tray, dark corners
|
||||
const lg = ctx.createRadialGradient(TRAY_C.x - 60, TRAY_C.y - 160, 60, TRAY_C.x, TRAY_C.y, 1150);
|
||||
lg.addColorStop(0, 'rgba(255,214,140,0.30)');
|
||||
lg.addColorStop(0.45, 'rgba(255,190,110,0.10)');
|
||||
lg.addColorStop(1, 'rgba(0,0,0,0)');
|
||||
ctx.fillStyle = lg; ctx.fillRect(0, 0, W, H);
|
||||
const vg = ctx.createRadialGradient(W / 2, H / 2, 420, W / 2, H / 2, 1180);
|
||||
vg.addColorStop(0, 'rgba(0,0,0,0)'); vg.addColorStop(1, 'rgba(10,4,0,0.55)');
|
||||
ctx.fillStyle = vg; ctx.fillRect(0, 0, W, H);
|
||||
addCanvas(scene, 'boggle-room', c);
|
||||
}
|
||||
|
||||
function bakeGlow(scene) {
|
||||
const c = canvas(1200, 1200);
|
||||
const ctx = c.getContext('2d');
|
||||
const g = ctx.createRadialGradient(600, 600, 40, 600, 600, 600);
|
||||
g.addColorStop(0, 'rgba(255,190,110,0.55)');
|
||||
g.addColorStop(0.5, 'rgba(255,150,70,0.18)');
|
||||
g.addColorStop(1, 'rgba(255,120,40,0)');
|
||||
ctx.fillStyle = g; ctx.fillRect(0, 0, 1200, 1200);
|
||||
addCanvas(scene, 'boggle-glow', c);
|
||||
}
|
||||
|
||||
// ── title plaque ────────────────────────────────────────────────────────────
|
||||
function bakeSign(scene) {
|
||||
const w = SIGN.w, h = SIGN.h, P = PAD_PX;
|
||||
const c = canvas(w + P * 2, h + P * 2);
|
||||
const ctx = c.getContext('2d');
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#4a2a12'; rr(ctx, P, P, w, h, 22); ctx.fill(); }, { blur: 18, dy: 8 });
|
||||
const g = ctx.createLinearGradient(0, P, 0, P + h);
|
||||
g.addColorStop(0, '#6e4422'); g.addColorStop(1, '#4a2a12');
|
||||
ctx.fillStyle = g; rr(ctx, P + 6, P + 6, w - 12, h - 12, 18); ctx.fill();
|
||||
grain(ctx, P + 6, P + 6, w - 12, h - 12, { lines: 14, wave: 2 });
|
||||
// three-colour 70s swoosh along the bottom
|
||||
const cols = ['#d9a63a', '#d0652a', '#a33a1c'];
|
||||
ctx.save(); rr(ctx, P + 6, P + 6, w - 12, h - 12, 18); ctx.clip();
|
||||
cols.forEach((col, i) => {
|
||||
ctx.strokeStyle = col; ctx.lineWidth = 9;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(P - 10, P + h - 44 + i * 11);
|
||||
ctx.bezierCurveTo(P + w * 0.3, P + h - 70 + i * 11, P + w * 0.6, P + h - 12 + i * 11, P + w + 10, P + h - 46 + i * 11);
|
||||
ctx.stroke();
|
||||
});
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(255,220,170,0.35)'; ctx.lineWidth = 2;
|
||||
rr(ctx, P + 11, P + 11, w - 22, h - 22, 14); ctx.stroke();
|
||||
// brass screws
|
||||
for (const [x, y] of [[P + 22, P + 22], [P + w - 22, P + 22], [P + 22, P + h - 22], [P + w - 22, P + h - 22]]) {
|
||||
const sg = ctx.createRadialGradient(x - 2, y - 2, 1, x, y, 6);
|
||||
sg.addColorStop(0, '#fff1c0'); sg.addColorStop(1, '#8a6a20');
|
||||
ctx.fillStyle = sg; ctx.beginPath(); ctx.arc(x, y, 5.5, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(60,40,10,0.7)'; ctx.lineWidth = 1.2;
|
||||
ctx.beginPath(); ctx.moveTo(x - 3.5, y); ctx.lineTo(x + 3.5, y); ctx.stroke();
|
||||
}
|
||||
addCanvas(scene, 'boggle-sign', c);
|
||||
}
|
||||
|
||||
// ── cards ───────────────────────────────────────────────────────────────────
|
||||
function bakeCard(scene, key, w, h) {
|
||||
const P = PAD_PX;
|
||||
const c = canvas(w + P * 2, h + P * 2);
|
||||
const ctx = c.getContext('2d');
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#f3e6c6'; rr(ctx, P, P, w, h, 14); ctx.fill(); }, { blur: 16, dy: 7, alpha: 0.5 });
|
||||
const g = ctx.createLinearGradient(0, P, 0, P + h);
|
||||
g.addColorStop(0, '#fbf3de'); g.addColorStop(1, '#efe1bd');
|
||||
ctx.fillStyle = g; rr(ctx, P, P, w, h, 14); ctx.fill();
|
||||
ctx.save(); rr(ctx, P, P, w, h, 14); ctx.clip();
|
||||
// stripes on the left edge
|
||||
['#d9a63a', '#d0652a', '#a33a1c'].forEach((col, i) => { ctx.fillStyle = col; ctx.fillRect(P + i * 8, P, 8, h); });
|
||||
ctx.fillStyle = noisePattern(ctx, 64, 16); ctx.fillRect(P, P, w, h);
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(90,56,32,0.35)'; ctx.lineWidth = 1.5; rr(ctx, P + 0.5, P + 0.5, w - 1, h - 1, 14); ctx.stroke();
|
||||
addCanvas(scene, key, c);
|
||||
}
|
||||
|
||||
// ── legal pad ───────────────────────────────────────────────────────────────
|
||||
function bakePad(scene) {
|
||||
const w = PAD.w, h = PAD.h, P = PAD_PX;
|
||||
const c = canvas(w + P * 2, h + P * 2);
|
||||
const ctx = c.getContext('2d');
|
||||
// sheets underneath, slightly fanned
|
||||
ctx.save(); ctx.translate(P + w / 2, P + h / 2); ctx.rotate(0.012);
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#e8d77a'; ctx.fillRect(-w / 2 + 4, -h / 2 + 10, w, h); }, { blur: 18, dy: 8 });
|
||||
ctx.restore();
|
||||
ctx.fillStyle = '#f6e98e'; ctx.fillRect(P, P, w, h);
|
||||
const pg = ctx.createLinearGradient(P, 0, P + w, 0);
|
||||
pg.addColorStop(0, 'rgba(0,0,0,0.04)'); pg.addColorStop(0.5, 'rgba(255,255,255,0.05)'); pg.addColorStop(1, 'rgba(0,0,0,0.06)');
|
||||
ctx.fillStyle = pg; ctx.fillRect(P, P, w, h);
|
||||
ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(P, P, w, h);
|
||||
// blue rules
|
||||
ctx.strokeStyle = 'rgba(70,120,190,0.45)'; ctx.lineWidth = 1.2;
|
||||
for (let y = PAD_LIST.y - PAD.y + 14; y < h - 60; y += PAD_LIST.rowH) {
|
||||
ctx.beginPath(); ctx.moveTo(P + 6, P + y); ctx.lineTo(P + w - 6, P + y); ctx.stroke();
|
||||
}
|
||||
// header rule
|
||||
ctx.strokeStyle = 'rgba(70,120,190,0.6)'; ctx.lineWidth = 1.6;
|
||||
ctx.beginPath(); ctx.moveTo(P + 6, P + PAD_COUNTS_Y - PAD.y + 26); ctx.lineTo(P + w - 6, P + PAD_COUNTS_Y - PAD.y + 26); ctx.stroke();
|
||||
// red double margin
|
||||
ctx.strokeStyle = 'rgba(200,60,50,0.65)'; ctx.lineWidth = 1.4;
|
||||
for (const dx of [0, 5]) {
|
||||
ctx.beginPath(); ctx.moveTo(P + PAD_MARGIN_X - PAD.x + dx, P + PAD_BINDING); ctx.lineTo(P + PAD_MARGIN_X - PAD.x + dx, P + h); ctx.stroke();
|
||||
}
|
||||
// binding strip
|
||||
const bg = ctx.createLinearGradient(0, P, 0, P + PAD_BINDING);
|
||||
bg.addColorStop(0, '#7a2a1a'); bg.addColorStop(1, '#4e180c');
|
||||
ctx.fillStyle = bg; ctx.fillRect(P - 2, P - 2, w + 4, PAD_BINDING);
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.10)'; ctx.fillRect(P - 2, P + 6, w + 4, 3);
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.25)'; ctx.fillRect(P - 2, P + PAD_BINDING - 4, w + 4, 4);
|
||||
// staples
|
||||
for (const x of [P + 90, P + w / 2, P + w - 90]) {
|
||||
ctx.fillStyle = '#d8d8d8'; ctx.fillRect(x - 16, P + 26, 32, 4);
|
||||
ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(x - 16, P + 30, 32, 2);
|
||||
}
|
||||
addCanvas(scene, 'boggle-pad', c);
|
||||
}
|
||||
|
||||
// ── tray ────────────────────────────────────────────────────────────────────
|
||||
function bakeTray(scene, n) {
|
||||
const g = trayGeom(n);
|
||||
const P = PAD_PX, o = g.outer;
|
||||
const c = canvas(o + P * 2, o + P * 2);
|
||||
const ctx = c.getContext('2d');
|
||||
dropShadow(ctx, () => { ctx.fillStyle = '#3a1e0c'; rr(ctx, P, P, o, o, 30); ctx.fill(); }, { blur: 26, dy: 12, alpha: 0.6 });
|
||||
// walnut rim
|
||||
const wg = ctx.createLinearGradient(P, P, P + o, P + o);
|
||||
wg.addColorStop(0, '#6a3f1e'); wg.addColorStop(1, '#3e2210');
|
||||
ctx.fillStyle = wg; rr(ctx, P, P, o, o, 30); ctx.fill();
|
||||
grain(ctx, P, P, o, o, { lines: 30, wave: 3, tone: 'rgba(20,8,2,0.3)' });
|
||||
ctx.strokeStyle = 'rgba(255,210,150,0.3)'; ctx.lineWidth = 2; rr(ctx, P + 4, P + 4, o - 8, o - 8, 27); ctx.stroke();
|
||||
// inner well — mustard plastic
|
||||
const f = g.frame, wellSz = o - f * 2;
|
||||
const mg = ctx.createLinearGradient(0, P + f, 0, P + f + wellSz);
|
||||
mg.addColorStop(0, '#b8842a'); mg.addColorStop(1, '#a37022');
|
||||
ctx.fillStyle = mg; rr(ctx, P + f, P + f, wellSz, wellSz, 16); ctx.fill();
|
||||
// inner shadow on the well
|
||||
ctx.save(); rr(ctx, P + f, P + f, wellSz, wellSz, 16); ctx.clip();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 18; ctx.shadowOffsetY = 6;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.lineWidth = 12; rr(ctx, P + f - 6, P + f - 6, wellSz + 12, wellSz + 12, 20); ctx.stroke();
|
||||
ctx.restore();
|
||||
// recesses
|
||||
const off = P + o / 2;
|
||||
for (let r = 0; r < g.n; r++) for (let col = 0; col < g.n; col++) {
|
||||
const p = g.local(r, col);
|
||||
const s = g.cube + 8;
|
||||
const x = off + p.x - s / 2, y = off + p.y - s / 2;
|
||||
ctx.fillStyle = 'rgba(60,34,8,0.55)'; rr(ctx, x, y, s, s, 14); ctx.fill();
|
||||
ctx.save(); rr(ctx, x, y, s, s, 14); ctx.clip();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 10; ctx.shadowOffsetY = 4;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.7)'; ctx.lineWidth = 8; rr(ctx, x - 4, y - 4, s + 8, s + 8, 16); ctx.stroke();
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(255,220,150,0.18)'; ctx.lineWidth = 1.5; rr(ctx, x + 1, y + 1, s - 2, s - 2, 13); ctx.stroke();
|
||||
}
|
||||
addCanvas(scene, `boggle-tray-${n}`, c);
|
||||
}
|
||||
|
||||
// ── dice ────────────────────────────────────────────────────────────────────
|
||||
// The body is drawn lit from the top-left: side faces peek out bottom/right.
|
||||
function bakeDie(scene, n) {
|
||||
const g = trayGeom(n);
|
||||
const s = g.cube, P = 16;
|
||||
const c = canvas(s + P * 2, s + P * 2);
|
||||
const ctx = c.getContext('2d');
|
||||
const R = s * 0.16;
|
||||
// contact shadow
|
||||
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 12; ctx.shadowOffsetX = 3; ctx.shadowOffsetY = 6;
|
||||
ctx.fillStyle = '#c9b48a'; rr(ctx, P, P, s, s, R); ctx.fill(); ctx.restore();
|
||||
// side faces (darker ivory)
|
||||
ctx.fillStyle = '#bfa77a'; rr(ctx, P + 2, P + 4, s - 2, s - 4, R); ctx.fill();
|
||||
// top face
|
||||
const top = s - 10;
|
||||
const tg = ctx.createLinearGradient(P, P, P + top, P + top);
|
||||
tg.addColorStop(0, '#fffaf0'); tg.addColorStop(0.55, '#f4e8cc'); tg.addColorStop(1, '#e6d4ae');
|
||||
ctx.fillStyle = tg; rr(ctx, P, P, top, top, R * 0.85); ctx.fill();
|
||||
// worn texture
|
||||
ctx.save(); rr(ctx, P, P, top, top, R * 0.85); ctx.clip();
|
||||
ctx.fillStyle = noisePattern(ctx, 64, 22); ctx.fillRect(P, P, top, top);
|
||||
for (let i = 0; i < 6; i++) {
|
||||
ctx.strokeStyle = `rgba(120,90,50,${0.05 + Math.random() * 0.06})`; ctx.lineWidth = 1;
|
||||
const x = P + Math.random() * top, y = P + Math.random() * top;
|
||||
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + (Math.random() - 0.5) * 30, y + (Math.random() - 0.5) * 30); ctx.stroke();
|
||||
}
|
||||
// sheen
|
||||
const sg = ctx.createRadialGradient(P + top * 0.3, P + top * 0.25, 2, P + top * 0.3, P + top * 0.25, top * 0.7);
|
||||
sg.addColorStop(0, 'rgba(255,255,255,0.55)'); sg.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = sg; ctx.fillRect(P, P, top, top);
|
||||
ctx.restore();
|
||||
ctx.strokeStyle = 'rgba(120,92,52,0.55)'; ctx.lineWidth = 1.5; rr(ctx, P + 0.5, P + 0.5, top - 1, top - 1, R * 0.85); ctx.stroke();
|
||||
addCanvas(scene, `boggle-die-${n}`, c);
|
||||
|
||||
// selection glow
|
||||
const gc = canvas(s + P * 2 + 20, s + P * 2 + 20);
|
||||
const gx = gc.getContext('2d');
|
||||
gx.shadowColor = 'rgba(255,200,60,1)'; gx.shadowBlur = 22;
|
||||
gx.strokeStyle = 'rgba(255,205,80,0.95)'; gx.lineWidth = 7;
|
||||
rr(gx, P + 10 - 2, P + 10 - 2, top + 4, top + 4, R);
|
||||
gx.stroke();
|
||||
gx.shadowBlur = 0;
|
||||
gx.fillStyle = 'rgba(255,210,90,0.20)'; rr(gx, P + 10, P + 10, top, top, R * 0.85); gx.fill();
|
||||
addCanvas(scene, `boggle-die-glow-${n}`, gc);
|
||||
}
|
||||
|
||||
function bakeLid(scene, n) {
|
||||
const g = trayGeom(n);
|
||||
const o = g.outer + 24;
|
||||
const c = canvas(o, o);
|
||||
const ctx = c.getContext('2d');
|
||||
const R = 46;
|
||||
// body: faint blue-white tint, more opaque at the rim
|
||||
const bg = ctx.createRadialGradient(o * 0.4, o * 0.35, o * 0.1, o / 2, o / 2, o * 0.72);
|
||||
bg.addColorStop(0, 'rgba(235,245,255,0.10)');
|
||||
bg.addColorStop(0.75, 'rgba(210,230,245,0.18)');
|
||||
bg.addColorStop(1, 'rgba(190,215,235,0.42)');
|
||||
ctx.fillStyle = bg; rr(ctx, 4, 4, o - 8, o - 8, R); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(240,250,255,0.75)'; ctx.lineWidth = 4; rr(ctx, 4, 4, o - 8, o - 8, R); ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(140,170,200,0.5)'; ctx.lineWidth = 2; rr(ctx, 14, 14, o - 28, o - 28, R - 8); ctx.stroke();
|
||||
// highlights
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.55)'; ctx.lineWidth = 10; ctx.lineCap = 'round';
|
||||
ctx.beginPath(); ctx.arc(o * 0.42, o * 0.42, o * 0.33, Math.PI * 1.08, Math.PI * 1.42); ctx.stroke();
|
||||
ctx.lineWidth = 5;
|
||||
ctx.beginPath(); ctx.arc(o * 0.42, o * 0.42, o * 0.27, Math.PI * 1.12, Math.PI * 1.3); ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.25)'; ctx.lineWidth = 6;
|
||||
ctx.beginPath(); ctx.arc(o * 0.58, o * 0.6, o * 0.36, Math.PI * 0.1, Math.PI * 0.35); ctx.stroke();
|
||||
addCanvas(scene, `boggle-lid-${n}`, c);
|
||||
}
|
||||
|
||||
function bakeSpark(scene) {
|
||||
const c = canvas(24, 24);
|
||||
const ctx = c.getContext('2d');
|
||||
const g = ctx.createRadialGradient(12, 12, 0, 12, 12, 12);
|
||||
g.addColorStop(0, 'rgba(255,250,220,1)'); g.addColorStop(0.4, 'rgba(255,200,90,0.8)'); g.addColorStop(1, 'rgba(255,160,40,0)');
|
||||
ctx.fillStyle = g; ctx.fillRect(0, 0, 24, 24);
|
||||
addCanvas(scene, 'boggle-spark', c);
|
||||
}
|
||||
|
||||
// Bake everything (idempotent across scene restarts: the room keeps its random
|
||||
// grain once made, everything else is cheap).
|
||||
export function prepareBoggleArt(scene) {
|
||||
if (!scene.textures.exists('boggle-room')) bakeRoom(scene);
|
||||
if (!scene.textures.exists('boggle-glow')) bakeGlow(scene);
|
||||
if (!scene.textures.exists('boggle-sign')) bakeSign(scene);
|
||||
if (!scene.textures.exists('boggle-seat')) bakeCard(scene, 'boggle-seat', SEAT_W, SEAT_H);
|
||||
if (!scene.textures.exists('boggle-practice')) bakeCard(scene, 'boggle-practice', PRACTICE.w, PRACTICE.h);
|
||||
if (!scene.textures.exists('boggle-pad')) bakePad(scene);
|
||||
if (!scene.textures.exists('boggle-spark')) bakeSpark(scene);
|
||||
for (const n of [4, 5]) {
|
||||
if (!scene.textures.exists(`boggle-tray-${n}`)) bakeTray(scene, n);
|
||||
if (!scene.textures.exists(`boggle-die-${n}`)) bakeDie(scene, n);
|
||||
if (!scene.textures.exists(`boggle-lid-${n}`)) bakeLid(scene, n);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,284 @@
|
|||
// BoggleDialogs.js — den pop-ups: a cream card in a teak frame with a
|
||||
// three-colour 70s stripe. Each opener returns { close() } and swallows clicks
|
||||
// beneath it.
|
||||
//
|
||||
// openSetup match setup (timer · rounds · board · shortest word · shared words)
|
||||
// or solo setup (Practice / Daily Board)
|
||||
// openPauseMenu resume · table settings · how to play · new · leave
|
||||
// openBetween standings between rounds
|
||||
// confirmBox yes / no
|
||||
|
||||
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
|
||||
import { Button } from '../../ui/Button.js';
|
||||
import { playSound, SFX } from '../../ui/Sounds.js';
|
||||
import { DISPLAY_FONT, SERIF, HAND_FONT, BROWN_HEX, RED_HEX, PENCIL_HEX } from './BoggleArt.js';
|
||||
import { TIMER_OPTIONS, ROUND_OPTIONS, UNTIMED, longDate } from './BoggleLogic.js';
|
||||
|
||||
const BTN = 0x5a3820, BTN_GO = 0xb3501f, BTN_ALT = 0x3f4a1c;
|
||||
|
||||
export function frame(scene, x, y, w, h, depth) {
|
||||
const g = scene.add.graphics().setDepth(depth);
|
||||
g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 5, y + 10, w, h, 18);
|
||||
g.fillStyle(0x6a3f1e, 1).fillRoundedRect(x, y, w, h, 18);
|
||||
g.lineStyle(2, 0xe8c090, 0.55).strokeRoundedRect(x + 5, y + 5, w - 10, h - 10, 14);
|
||||
g.fillStyle(0xf8f0da, 1).fillRoundedRect(x + 14, y + 14, w - 28, h - 28, 10);
|
||||
const band = [0xd9a63a, 0xd0652a, 0xa33a1c];
|
||||
band.forEach((c, i) => g.fillStyle(c, 1).fillRect(x + 14, y + 78 + i * 6, w - 28, 6));
|
||||
return g;
|
||||
}
|
||||
|
||||
export function blocker(scene, depth, alpha = 0) {
|
||||
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, alpha)
|
||||
.setDepth(depth).setInteractive();
|
||||
}
|
||||
|
||||
export function title(scene, x, y, text, depth, size = 34) {
|
||||
return scene.add.text(x, y, text, { fontFamily: DISPLAY_FONT, fontSize: `${size}px`, color: BROWN_HEX, align: 'center' })
|
||||
.setOrigin(0.5).setDepth(depth);
|
||||
}
|
||||
|
||||
export function handle(objs, onClose) {
|
||||
let closed = false;
|
||||
return {
|
||||
objs,
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
objs.forEach((o) => o?.destroy?.());
|
||||
onClose?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function button(scene, x, y, label, fn, depth, { w = 240, h = 52, size = 20, bg = BTN } = {}) {
|
||||
return new Button(scene, x, y, label, fn, { width: w, height: h, fontSize: size, bg }).setDepth(depth);
|
||||
}
|
||||
|
||||
// A labelled row of mutually exclusive chips. opts: [{ label, value }].
|
||||
function chipRow(scene, objs, { x, y, w, label, opts, get, set, depth, chipW = null }) {
|
||||
objs.push(scene.add.text(x, y, label, { fontFamily: SERIF, fontSize: '19px', color: PENCIL_HEX, fontStyle: 'italic' })
|
||||
.setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
const x0 = x + 200;
|
||||
const avail = w - 200;
|
||||
const cw = chipW ?? Math.min(150, Math.floor((avail - (opts.length - 1) * 10) / opts.length));
|
||||
const chips = opts.map((o, i) => {
|
||||
const cx = x0 + i * (cw + 10) + cw / 2;
|
||||
const g = scene.add.graphics().setDepth(depth + 1);
|
||||
const t = scene.add.text(cx, y, o.label, { fontFamily: DISPLAY_FONT, fontSize: '19px', color: BROWN_HEX }).setOrigin(0.5).setDepth(depth + 2);
|
||||
const hit = scene.add.rectangle(cx, y, cw, 42, 0xffffff, 0.001).setDepth(depth + 3).setInteractive({ useHandCursor: true });
|
||||
hit.on('pointerdown', () => { set(o.value); playSound(scene, SFX.PIECE_CLICK); draw(); });
|
||||
objs.push(g, t, hit);
|
||||
return { o, g, t, cx };
|
||||
});
|
||||
const draw = () => {
|
||||
for (const c of chips) {
|
||||
const on = c.o.value === get();
|
||||
c.g.clear();
|
||||
c.g.fillStyle(on ? 0xc2551f : 0xffffff, on ? 1 : 0.55).fillRoundedRect(c.cx - cw / 2, y - 21, cw, 42, 21);
|
||||
c.g.lineStyle(2, on ? 0x7a2a10 : 0xa08060, 0.9).strokeRoundedRect(c.cx - cw / 2, y - 21, cw, 42, 21);
|
||||
c.t.setColor(on ? '#fff6e6' : BROWN_HEX);
|
||||
}
|
||||
};
|
||||
draw();
|
||||
return draw;
|
||||
}
|
||||
|
||||
// ── setup ───────────────────────────────────────────────────────────────────
|
||||
// solo: { mode, practice: {...rules, hints}, daily: { today, played, streak } }
|
||||
export function openSetup(scene, { solo, rules, rivals = [], soloState = null, depth, onStart, onHelp, onLeave, onClose }) {
|
||||
const r = { ...rules };
|
||||
const st = soloState ? { mode: soloState.mode, hints: soloState.hints } : null;
|
||||
const objs = [blocker(scene, depth - 1, 0.55)];
|
||||
const w = 960, h = solo ? 720 : 700;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
const cx = x + w / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, cx, y + 48, solo ? 'Boggle — Solo' : 'Boggle — Game Night', depth + 1));
|
||||
let hRef = null;
|
||||
|
||||
const rowX = x + 80, rowW = w - 160;
|
||||
const dynamic = [];
|
||||
const clearDynamic = () => { dynamic.forEach((o) => o.destroy()); dynamic.length = 0; };
|
||||
|
||||
const buildRules = (y0, { timed = true, untimed = false, rounds = true, dup = true, hints = false }) => {
|
||||
let yy = y0;
|
||||
const timerOpts = TIMER_OPTIONS.map((t) => ({ label: t.label, value: t.ms }));
|
||||
if (untimed) timerOpts.push({ label: 'Untimed', value: UNTIMED });
|
||||
if (timed) { chipRow(scene, dynamic, { x: rowX, y: yy, w: rowW, label: 'Round length', opts: timerOpts, get: () => r.timerMs, set: (v) => { r.timerMs = v; }, depth }); yy += 66; }
|
||||
if (rounds) { chipRow(scene, dynamic, { x: rowX, y: yy, w: rowW, label: 'Rounds', opts: ROUND_OPTIONS.map((n) => ({ label: `${n}`, value: n })), get: () => r.rounds, set: (v) => { r.rounds = v; }, depth, chipW: 110 }); yy += 66; }
|
||||
const drawMin = [];
|
||||
chipRow(scene, dynamic, {
|
||||
x: rowX, y: yy, w: rowW, label: 'Board', depth, chipW: 220,
|
||||
opts: [{ label: 'Classic 4 × 4', value: 4 }, { label: 'Big 5 × 5', value: 5 }],
|
||||
get: () => r.size, set: (v) => { r.size = v; r.minLen = v === 5 ? 4 : 3; drawMin[0]?.(); },
|
||||
});
|
||||
yy += 66;
|
||||
drawMin[0] = chipRow(scene, dynamic, {
|
||||
x: rowX, y: yy, w: rowW, label: 'Shortest word', depth, chipW: 160,
|
||||
opts: [{ label: '3 letters', value: 3 }, { label: '4 letters', value: 4 }],
|
||||
get: () => r.minLen, set: (v) => { r.minLen = v; },
|
||||
});
|
||||
yy += 66;
|
||||
if (dup) {
|
||||
chipRow(scene, dynamic, {
|
||||
x: rowX, y: yy, w: rowW, label: 'Shared words', depth, chipW: 220,
|
||||
opts: [{ label: 'Cancel out', value: true }, { label: 'Still score', value: false }],
|
||||
get: () => r.dupCancel, set: (v) => { r.dupCancel = v; },
|
||||
});
|
||||
yy += 66;
|
||||
}
|
||||
if (hints) {
|
||||
chipRow(scene, dynamic, {
|
||||
x: rowX, y: yy, w: rowW, label: 'Hints', depth, chipW: 160,
|
||||
opts: [{ label: 'On', value: true }, { label: 'Off', value: false }],
|
||||
get: () => st.hints, set: (v) => { st.hints = v; },
|
||||
});
|
||||
yy += 66;
|
||||
}
|
||||
return yy;
|
||||
};
|
||||
|
||||
const startBtn = button(scene, cx - 250, y + h - 64, 'Start', () => {
|
||||
if (solo && st.mode === 'daily' && soloState.daily.played) return;
|
||||
hRef.close();
|
||||
onStart(solo ? { mode: st.mode, rules: r, hints: st.hints } : { mode: 'match', rules: r });
|
||||
}, depth + 2, { w: 250, h: 56, size: 22, bg: BTN_GO });
|
||||
objs.push(startBtn);
|
||||
objs.push(button(scene, cx + 10, y + h - 64, 'How to Play', () => onHelp?.(), depth + 2, { w: 220, h: 56, size: 20, bg: BTN_ALT }));
|
||||
objs.push(button(scene, cx + 250, y + h - 64, 'Leave', () => { hRef.close(); onLeave?.(); }, depth + 2, { w: 200, h: 56, size: 20, bg: BTN }));
|
||||
|
||||
if (!solo) {
|
||||
const names = rivals.map((p) => `${p.name} (skill ${p.skill ?? 3})`).join(' · ');
|
||||
objs.push(scene.add.text(cx, y + 128, `Tonight at the table: ${names}`, {
|
||||
fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: PENCIL_HEX, align: 'center', wordWrap: { width: w - 120 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
buildRules(y + 196, {});
|
||||
objs.push(scene.add.text(cx, y + h - 128, 'Words found by two or more players are crossed off every sheet when "Cancel out" is on.', {
|
||||
fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: PENCIL_HEX, align: 'center', wordWrap: { width: w - 140 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
} else {
|
||||
const modeY = y + 140;
|
||||
const drawSolo = () => {
|
||||
clearDynamic();
|
||||
if (st.mode === 'practice') {
|
||||
r.rounds = 1;
|
||||
buildRules(modeY + 76, { untimed: true, rounds: false, dup: false, hints: true });
|
||||
const tip = scene.add.text(cx, y + h - 136, 'Practice goal: find a quarter of the board\'s common words. Untimed boards end when you press Finish.', {
|
||||
fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: PENCIL_HEX, align: 'center', wordWrap: { width: w - 140 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
dynamic.push(tip);
|
||||
startBtn.setEnabled(true).setLabel('Start');
|
||||
} else {
|
||||
const d = soloState.daily;
|
||||
const lines = [
|
||||
`${longDate(d.today)}`,
|
||||
'Everyone gets the same board today — one attempt.',
|
||||
'Classic 4 × 4 · 3 minutes · 3-letter words count',
|
||||
'',
|
||||
d.played ? `Today: ${d.played.score} pts · ${d.played.words} words · ${d.played.commonPct}% of common words` : 'Not played yet today.',
|
||||
`Daily streak: ${d.streak}${d.bestStreak ? ` (best ${d.bestStreak})` : ''}`,
|
||||
];
|
||||
const t = scene.add.text(cx, modeY + 210, lines.join('\n'), {
|
||||
fontFamily: SERIF, fontSize: '21px', color: '#2b2418', align: 'center', lineSpacing: 8,
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
dynamic.push(t);
|
||||
if (d.played) startBtn.setEnabled(false).setLabel('Come back tomorrow');
|
||||
else startBtn.setEnabled(true).setLabel("Play Today's Board");
|
||||
}
|
||||
};
|
||||
chipRow(scene, objs, {
|
||||
x: rowX, y: modeY, w: rowW, label: 'Mode', depth, chipW: 220,
|
||||
opts: [{ label: 'Practice', value: 'practice' }, { label: 'Daily Board', value: 'daily' }],
|
||||
get: () => st.mode, set: (v) => { st.mode = v; drawSolo(); },
|
||||
});
|
||||
drawSolo();
|
||||
}
|
||||
|
||||
hRef = handle(objs, () => { clearDynamic(); onClose?.(); });
|
||||
return hRef;
|
||||
}
|
||||
|
||||
// ── pause menu ──────────────────────────────────────────────────────────────
|
||||
const onOff = (v) => (v ? 'On' : 'Off');
|
||||
|
||||
export function openPauseMenu(scene, { settings, depth, midRound, onChange, onHelp, onNew, onLeave, onClose }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 560, h = 680;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
const cx = x + w / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, cx, y + 48, midRound ? 'Paused' : 'Game Night', depth + 1));
|
||||
let hRef = null;
|
||||
const rows = [
|
||||
['Resume', () => hRef.close(), BTN_GO],
|
||||
[() => `Upright letters: ${onOff(settings.upright)}`, () => onChange('upright', !settings.upright)],
|
||||
[() => `Release to submit (drag): ${onOff(settings.releaseSubmit)}`, () => onChange('releaseSubmit', !settings.releaseSubmit)],
|
||||
[() => `Rival pencil sounds: ${onOff(settings.rivalSounds)}`, () => onChange('rivalSounds', !settings.rivalSounds)],
|
||||
[() => `Last-ten-seconds tick: ${onOff(settings.tick)}`, () => onChange('tick', !settings.tick)],
|
||||
['How to Play', () => onHelp?.(), BTN_ALT],
|
||||
['New Game', () => { onNew(); hRef.close(); }, 0x6a4a1a],
|
||||
['Leave the Den', () => { onLeave(); hRef.close(); }, 0x7a2a1a],
|
||||
];
|
||||
rows.forEach(([label, fn, bg], i) => {
|
||||
const text = typeof label === 'function' ? label() : label;
|
||||
const btn = new Button(scene, cx, y + 136 + i * 58, text, () => {
|
||||
fn();
|
||||
if (typeof label === 'function') btn.setLabel(label());
|
||||
}, { width: 460, height: 48, fontSize: 18, bg: bg ?? BTN }).setDepth(depth + 2);
|
||||
objs.push(btn);
|
||||
});
|
||||
objs.push(scene.add.text(cx, y + h - 46, 'Keys: type letters · Enter submit · Backspace · Esc clear / pause · Space shake', {
|
||||
fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: w - 70 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
hRef = handle(objs, onClose);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
// ── between rounds ──────────────────────────────────────────────────────────
|
||||
export function openBetween(scene, { match, depth, onNext, onMenu }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.55)];
|
||||
const n = match.players.length;
|
||||
const rounds = match.history.length;
|
||||
const w = 900, h = 330 + n * 58;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
const cx = x + w / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, cx, y + 48, `After Round ${rounds} of ${match.rules.rounds}`, depth + 1));
|
||||
const colX = (k) => x + 380 + k * 110;
|
||||
for (let k = 0; k < rounds; k++) {
|
||||
objs.push(scene.add.text(colX(k), y + 132, `R${k + 1}`, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: PENCIL_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
}
|
||||
objs.push(scene.add.text(x + w - 90, y + 132, 'Total', { fontFamily: DISPLAY_FONT, fontSize: '20px', color: PENCIL_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
const order = [...match.players].sort((a, b) => match.totals[b.id] - match.totals[a.id]);
|
||||
order.forEach((p, i) => {
|
||||
const yy = y + 182 + i * 58;
|
||||
objs.push(scene.add.text(x + 70, yy, `${i + 1}. ${p.name}`, {
|
||||
fontFamily: HAND_FONT, fontSize: '36px', color: p.isHuman ? RED_HEX : '#2b2418',
|
||||
}).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
match.history.forEach((hh, k) => {
|
||||
objs.push(scene.add.text(colX(k), yy, String(hh.scores[p.id] ?? 0), { fontFamily: HAND_FONT, fontSize: '32px', color: '#2b2418' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
});
|
||||
objs.push(scene.add.text(x + w - 90, yy, String(match.totals[p.id]), { fontFamily: DISPLAY_FONT, fontSize: '30px', color: BROWN_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
});
|
||||
let hRef = null;
|
||||
objs.push(button(scene, cx - 140, y + h - 60, `Round ${rounds + 1}`, () => { hRef.close(); onNext(); }, depth + 2, { w: 250, h: 56, size: 22, bg: BTN_GO }));
|
||||
objs.push(button(scene, cx + 140, y + h - 60, 'Menu', () => onMenu(), depth + 2, { w: 200, h: 56, size: 20 }));
|
||||
hRef = handle(objs);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.5)];
|
||||
const w = 580, h = 290;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, x + w / 2, y + 48, heading, depth + 1, 28));
|
||||
objs.push(scene.add.text(x + w / 2, y + 150, text, {
|
||||
fontFamily: SERIF, fontSize: '18px', color: '#2b2418', align: 'center', wordWrap: { width: w - 80 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
let hRef = null;
|
||||
objs.push(button(scene, x + w / 2 - 130, y + h - 52, yes, () => { hRef.close(); onYes?.(); }, depth + 2, { w: 230, h: 48, size: 18, bg: 0x7a2a1a }));
|
||||
objs.push(button(scene, x + w / 2 + 130, y + h - 52, no, () => { hRef.close(); onNo?.(); }, depth + 2, { w: 230, h: 48, size: 18 }));
|
||||
hRef = handle(objs);
|
||||
return hRef;
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
// BoggleEndScreen.js — the after-match card: final standings with a round-by-
|
||||
// round table, each player's best word, and the player's personal records.
|
||||
//
|
||||
// Records live in localStorage `boggle-records`:
|
||||
// { bestRound, bestRoundWords, longestWord, mostWords, bestMatch }
|
||||
|
||||
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
|
||||
import { DISPLAY_FONT, HAND_FONT, SERIF, BROWN_HEX, RED_HEX, PENCIL_HEX } from './BoggleArt.js';
|
||||
import { frame, blocker, title, handle, button } from './BoggleDialogs.js';
|
||||
import { standings, longestWord } from './BoggleLogic.js';
|
||||
|
||||
export const RECORDS_KEY = 'boggle-records';
|
||||
|
||||
export function loadRecords() {
|
||||
try { return { bestRound: 0, longestWord: '', mostWords: 0, bestMatch: 0, ...JSON.parse(localStorage.getItem(RECORDS_KEY) || '{}') }; }
|
||||
catch (_) { return { bestRound: 0, longestWord: '', mostWords: 0, bestMatch: 0 }; }
|
||||
}
|
||||
|
||||
// Update records from one finished round; returns the list of new-record labels.
|
||||
export function noteRound(roundScore, words, { minLen = 3 } = {}) {
|
||||
const r = loadRecords();
|
||||
const out = [];
|
||||
const lw = longestWord(words.filter((w) => w.length >= minLen));
|
||||
if (roundScore > r.bestRound) { if (r.bestRound) out.push(`New best round: ${roundScore} pts`); r.bestRound = roundScore; }
|
||||
if (words.length > r.mostWords) { if (r.mostWords) out.push(`Most words: ${words.length}`); r.mostWords = words.length; }
|
||||
if (lw.length > (r.longestWord?.length ?? 0)) { if (r.longestWord) out.push(`Longest word ever: ${lw}`); r.longestWord = lw; }
|
||||
try { localStorage.setItem(RECORDS_KEY, JSON.stringify(r)); } catch (_) { /* private mode */ }
|
||||
return out;
|
||||
}
|
||||
|
||||
export function noteMatch(total) {
|
||||
const r = loadRecords();
|
||||
let beat = false;
|
||||
if (total > r.bestMatch) { beat = r.bestMatch > 0; r.bestMatch = total; }
|
||||
try { localStorage.setItem(RECORDS_KEY, JSON.stringify(r)); } catch (_) { /* */ }
|
||||
return beat;
|
||||
}
|
||||
|
||||
export function openEndScreen(scene, { match, result, newRecords = [], depth, onReview, onPlayAgain, onMenu }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.62)];
|
||||
const n = match.players.length;
|
||||
const rounds = match.history.length;
|
||||
const w = 1180, h = 420 + n * 62;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
const cx = x + w / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
const st = standings(match);
|
||||
const head = result === 'win' ? 'You win the night!' : result === 'draw' ? "It's a tie!" : `${st[0].name} takes the night`;
|
||||
objs.push(title(scene, cx, y + 48, head, depth + 1, 38));
|
||||
|
||||
const colX = (k) => x + 400 + k * 84;
|
||||
for (let k = 0; k < rounds; k++) {
|
||||
objs.push(scene.add.text(colX(k), y + 132, `R${k + 1}`, { fontFamily: DISPLAY_FONT, fontSize: '19px', color: PENCIL_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
}
|
||||
const totX = x + 400 + rounds * 84 + 30;
|
||||
objs.push(scene.add.text(totX, y + 132, 'Total', { fontFamily: DISPLAY_FONT, fontSize: '19px', color: PENCIL_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(x + w - 140, y + 132, 'Best word', { fontFamily: DISPLAY_FONT, fontSize: '19px', color: PENCIL_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
st.forEach((p, i) => {
|
||||
const yy = y + 186 + i * 62;
|
||||
objs.push(scene.add.text(x + 60, yy, `${i + 1}. ${p.name}`, {
|
||||
fontFamily: HAND_FONT, fontSize: '38px', color: p.isHuman ? RED_HEX : '#2b2418',
|
||||
}).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
match.history.forEach((hh, k) => {
|
||||
objs.push(scene.add.text(colX(k), yy, String(hh.scores[p.id] ?? 0), { fontFamily: HAND_FONT, fontSize: '32px', color: '#2b2418' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
});
|
||||
objs.push(scene.add.text(totX, yy, String(match.totals[p.id]), { fontFamily: DISPLAY_FONT, fontSize: '30px', color: BROWN_HEX }).setOrigin(0.5).setDepth(depth + 1));
|
||||
const best = match.history.map((hh) => hh.best[p.id] ?? '').reduce((a, b) => (b.length > a.length ? b : a), '');
|
||||
objs.push(scene.add.text(x + w - 140, yy, best ? best.toLowerCase() : '—', { fontFamily: HAND_FONT, fontSize: '30px', color: '#2b2418' }).setOrigin(0.5).setDepth(depth + 1));
|
||||
});
|
||||
|
||||
if (newRecords.length) {
|
||||
objs.push(scene.add.text(cx, y + h - 132, newRecords.join(' · '), {
|
||||
fontFamily: HAND_FONT, fontSize: '30px', color: RED_HEX, align: 'center', wordWrap: { width: w - 120 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1).setAngle(-1));
|
||||
} else {
|
||||
objs.push(scene.add.text(cx, y + h - 132, 'Pencils down, popcorn up. Same time next week?', {
|
||||
fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: PENCIL_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
}
|
||||
|
||||
let hRef = null;
|
||||
objs.push(button(scene, cx - 290, y + h - 62, 'Last Board', () => onReview?.(), depth + 2, { w: 230, h: 54, size: 19, bg: 0x3f4a1c }));
|
||||
objs.push(button(scene, cx, y + h - 62, 'Play Again', () => { hRef.close(); onPlayAgain(); }, depth + 2, { w: 250, h: 54, size: 20, bg: 0xb3501f }));
|
||||
objs.push(button(scene, cx + 290, y + h - 62, 'Menu', () => { hRef.close(); onMenu(); }, depth + 2, { w: 200, h: 54, size: 19 }));
|
||||
hRef = handle(objs);
|
||||
hRef.hide = (v) => objs.forEach((o) => o?.setVisible?.(!v));
|
||||
return hRef;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,118 @@
|
|||
// BoggleLayout.js — every rect on the den table, Phaser-free so the verify tool
|
||||
// can check it. Screen is 1920 × 1080.
|
||||
//
|
||||
// left column SIGN · rival SEATS (1–3) or the PRACTICE card · MENU_BTN
|
||||
// centre column HOURGLASS + CLOCK + ROUND_TAG · WORD banner · TRAY · FEEDBACK · CONTROLS
|
||||
// right column the yellow legal PAD
|
||||
|
||||
export const W = 1920, H = 1080;
|
||||
|
||||
export const TABLE = { x: 18, y: 16, w: W - 36, h: H - 32 };
|
||||
|
||||
export const SIGN = { x: 36, y: 30, w: 368, h: 148 };
|
||||
|
||||
export const SEAT_W = 368, SEAT_H = 226, SEAT_GAP = 22, SEAT_X = 36, SEAT_Y = 202;
|
||||
export function seatRect(i) {
|
||||
return { x: SEAT_X, y: SEAT_Y + i * (SEAT_H + SEAT_GAP), w: SEAT_W, h: SEAT_H };
|
||||
}
|
||||
export function seatParts(i) {
|
||||
const r = seatRect(i);
|
||||
return {
|
||||
rect: r,
|
||||
portrait: { x: r.x + 74, y: r.y + 84, r: 54 },
|
||||
name: { x: r.x + 146, y: r.y + 44 },
|
||||
pips: { x: r.x + 152, y: r.y + 82 },
|
||||
count: { x: r.x + r.w - 26, y: r.y + 78 },
|
||||
countLabel: { x: r.x + r.w - 26, y: r.y + 120 },
|
||||
scribble: { x: r.x + 22, y: r.y + 152, w: r.w - 44, h: 56 },
|
||||
bubble: { x: r.x + r.w - 24, y: r.y + 4, w: 250, h: 64 },
|
||||
};
|
||||
}
|
||||
|
||||
export const PRACTICE = { x: 36, y: 202, w: 368, h: 700 };
|
||||
|
||||
export const MENU_BTN = { x: 120, y: 1012, w: 168, h: 50 };
|
||||
export const HELP_BTN = { x: 314, y: 1012, w: 168, h: 50 };
|
||||
|
||||
// ── centre column ───────────────────────────────────────────────────────────
|
||||
export const CX = 842;
|
||||
export const HOURGLASS = { x: 662, y: 106, hw: 30, hh: 54 };
|
||||
export const CLOCK = { x: 712, y: 108 };
|
||||
export const ROUND_TAG = { x: 1236, y: 92 };
|
||||
export const MODE_TAG = { x: 1236, y: 130 };
|
||||
export const WORD = { x: CX, y: 216, w: 760, h: 70 };
|
||||
export const TRAY_C = { x: CX, y: 604 };
|
||||
export const FEEDBACK = { x: CX, y: 964 };
|
||||
export const CONTROLS_Y = 1024;
|
||||
|
||||
// Tray geometry per board size: die size, gap, the wooden frame around them.
|
||||
export function trayGeom(size = 4) {
|
||||
const n = size === 5 ? 5 : 4;
|
||||
const cube = n === 5 ? 100 : 124;
|
||||
const gap = n === 5 ? 12 : 14;
|
||||
const span = n * cube + (n - 1) * gap;
|
||||
const well = 26; // felt/plastic margin inside the frame
|
||||
const frame = 30; // wooden rim
|
||||
const outer = span + 2 * (well + frame);
|
||||
const ox = TRAY_C.x - span / 2, oy = TRAY_C.y - span / 2;
|
||||
return {
|
||||
n, cube, gap, span, well, frame, outer,
|
||||
rect: { x: TRAY_C.x - outer / 2, y: TRAY_C.y - outer / 2, w: outer, h: outer },
|
||||
origin: { x: ox, y: oy },
|
||||
center: (r, c) => ({ x: ox + c * (cube + gap) + cube / 2, y: oy + r * (cube + gap) + cube / 2 }),
|
||||
// local (relative to tray centre)
|
||||
local: (r, c) => ({ x: -span / 2 + c * (cube + gap) + cube / 2, y: -span / 2 + r * (cube + gap) + cube / 2 }),
|
||||
};
|
||||
}
|
||||
|
||||
export function controlSlots(count, width = 210, gap = 22) {
|
||||
const total = count * width + (count - 1) * gap;
|
||||
const x0 = CX - total / 2 + width / 2;
|
||||
return Array.from({ length: count }, (_, i) => ({ x: x0 + i * (width + gap), y: CONTROLS_Y, w: width, h: 56 }));
|
||||
}
|
||||
|
||||
// ── right column: the legal pad ─────────────────────────────────────────────
|
||||
export const PAD = { x: 1282, y: 26, w: 606, h: 1028 };
|
||||
export const PAD_BINDING = 64;
|
||||
export const PAD_TITLE = { x: PAD.x + PAD.w / 2 + 20, y: PAD.y + 112 };
|
||||
export const PAD_SCORE = { x: PAD.x + PAD.w - 40, y: PAD.y + 112 };
|
||||
export const PAD_COUNTS_Y = PAD.y + 172;
|
||||
export const PAD_MARGIN_X = PAD.x + 70;
|
||||
export const PAD_LIST = { x: PAD.x + 82, y: PAD.y + 222, w: PAD.w - 112, rowH: 34, rows: 22, cols: 3 };
|
||||
export const PAD_FOOT_Y = PAD.y + PAD.h - 34;
|
||||
|
||||
// ── overlays ────────────────────────────────────────────────────────────────
|
||||
export const SCORE_TOP = 150;
|
||||
export const SCORE_ROWS = 20;
|
||||
export function scoreColumns(n) {
|
||||
const colW = Math.min(430, Math.floor((W - 160) / n));
|
||||
const total = colW * n;
|
||||
const x0 = (W - total) / 2;
|
||||
return Array.from({ length: n }, (_, i) => ({ x: x0 + i * colW + 10, y: SCORE_TOP, w: colW - 20, h: 820 }));
|
||||
}
|
||||
|
||||
export const REVIEW_LIST = { x: PAD.x, y: PAD.y, w: PAD.w, h: PAD.h };
|
||||
export const REVIEW_SIDE = { x: 36, y: 202, w: 368, h: 700 };
|
||||
|
||||
// Rect overlap helper for verify.
|
||||
export function overlaps(a, b) {
|
||||
return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
||||
}
|
||||
|
||||
// The furniture that must stay apart during play, for `n` rivals (0 = solo).
|
||||
export function furniture(n, size = 4) {
|
||||
const t = trayGeom(size);
|
||||
const out = [
|
||||
{ name: 'sign', ...SIGN },
|
||||
{ name: 'tray', ...t.rect },
|
||||
{ name: 'pad', ...PAD },
|
||||
{ name: 'word', x: WORD.x - WORD.w / 2, y: WORD.y - WORD.h / 2, w: WORD.w, h: WORD.h },
|
||||
{ name: 'clock', x: HOURGLASS.x - HOURGLASS.hw - 12, y: HOURGLASS.y - HOURGLASS.hh - 14, w: 300, h: (HOURGLASS.hh + 14) * 2 },
|
||||
{ name: 'menu', x: MENU_BTN.x - MENU_BTN.w / 2, y: MENU_BTN.y - MENU_BTN.h / 2, w: MENU_BTN.w, h: MENU_BTN.h },
|
||||
{ name: 'help', x: HELP_BTN.x - HELP_BTN.w / 2, y: HELP_BTN.y - HELP_BTN.h / 2, w: HELP_BTN.w, h: HELP_BTN.h },
|
||||
];
|
||||
controlSlots(3).forEach((s, i) => out.push({ name: `ctl${i}`, x: s.x - s.w / 2, y: s.y - s.h / 2, w: s.w, h: s.h }));
|
||||
if (n === 0) out.push({ name: 'practice', ...PRACTICE });
|
||||
for (let i = 0; i < n; i++) out.push({ name: `seat${i}`, ...seatRect(i) });
|
||||
return out;
|
||||
}
|
||||
|
|
@ -1,10 +1,54 @@
|
|||
// Pure Boggle logic — no Phaser, no network. Unit-testable.
|
||||
// Pure Boggle logic — no Phaser, no network. Unit-testable (tools/verifyBoggle.js).
|
||||
//
|
||||
// rules normalizeRules / DEFAULT_RULES / TIMER_OPTIONS / ROUND_OPTIONS
|
||||
// scoring scoreWord(word, minLen) · resolveRound(sheets, rules) · revealPlan(results)
|
||||
// board paths areAdjacent · isValidPath · pathWord · findPath(board, word, prefer)
|
||||
// typing typeLetter(word, ch) · backspace(word)
|
||||
// review reviewGroups(solutions, found, opts) · roundSummary(...)
|
||||
// match state createMatch / commitRound / standings / serialise + parse saves
|
||||
// daily todayString / dailySeed / longDate
|
||||
|
||||
// Classic Boggle scoring by letter count. Because solution words store "Qu" as the
|
||||
// two letters Q + U, word.length already counts Qu as two letters automatically.
|
||||
export function scoreWord(word) {
|
||||
const n = word.length;
|
||||
if (n < 3) return 0;
|
||||
import { dateSeed, localDateString } from '../dotlink/DotLinkLogic.js';
|
||||
|
||||
// ── Rules ────────────────────────────────────────────────────────────────────
|
||||
export const TIMER_OPTIONS = [
|
||||
{ label: '1 min', ms: 60000 },
|
||||
{ label: '2 min', ms: 120000 },
|
||||
{ label: '3 min', ms: 180000 },
|
||||
{ label: '4 min', ms: 240000 },
|
||||
];
|
||||
export const UNTIMED = 0;
|
||||
export const ROUND_OPTIONS = [1, 3, 5];
|
||||
|
||||
export const DEFAULT_RULES = {
|
||||
size: 4, // 4 (classic) or 5 (Big)
|
||||
minLen: 3, // shortest scoring word (Big boards default to 4)
|
||||
timerMs: 180000, // 0 = untimed (practice only)
|
||||
rounds: 3,
|
||||
dupCancel: true, // words found by 2+ players score nothing
|
||||
};
|
||||
|
||||
export const DAILY_RULES = { size: 4, minLen: 3, timerMs: 180000, rounds: 1, dupCancel: true };
|
||||
|
||||
export function normalizeRules(r = {}) {
|
||||
const out = { ...DEFAULT_RULES, ...(r ?? {}) };
|
||||
out.size = out.size === 5 ? 5 : 4;
|
||||
out.minLen = out.minLen === 4 ? 4 : 3;
|
||||
out.timerMs = Number(out.timerMs) || 0;
|
||||
if (out.timerMs && !TIMER_OPTIONS.some((t) => t.ms === out.timerMs)) out.timerMs = DEFAULT_RULES.timerMs;
|
||||
out.rounds = ROUND_OPTIONS.includes(out.rounds) ? out.rounds : DEFAULT_RULES.rounds;
|
||||
out.dupCancel = out.dupCancel !== false;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Scoring ──────────────────────────────────────────────────────────────────
|
||||
// Classic table by letter count; "Qu" counts as two letters (solution words
|
||||
// store it as Q + U, so word.length already does). Words below minLen score 0.
|
||||
export const SCORE_TABLE = [[3, 1], [4, 1], [5, 2], [6, 3], [7, 5], [8, 11]];
|
||||
|
||||
export function scoreWord(word, minLen = 3) {
|
||||
const n = String(word).length;
|
||||
if (n < Math.max(3, minLen)) return 0;
|
||||
if (n <= 4) return 1;
|
||||
if (n === 5) return 2;
|
||||
if (n === 6) return 3;
|
||||
|
|
@ -12,15 +56,71 @@ export function scoreWord(word) {
|
|||
return 11; // 8+
|
||||
}
|
||||
|
||||
// Two board cells are adjacent if they differ by at most one row and one column
|
||||
// (8-neighbour), and are not the same cell.
|
||||
export function sheetScore(words, minLen = 3) {
|
||||
let s = 0;
|
||||
for (const w of words) s += scoreWord(w, minLen);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Each player's found words → scored, with the duplicate rule applied when
|
||||
// rules.dupCancel is on. Returns results aligned with `sheets`:
|
||||
// [{ words: [{ word, score, dup, sharedWith: [playerIdx] }], roundScore, unique, shared }]
|
||||
export function resolveRound(sheets, rules = {}) {
|
||||
const { minLen = 3, dupCancel = true } = rules;
|
||||
const owners = new Map(); // word → [playerIdx]
|
||||
const lists = sheets.map((s, pi) => {
|
||||
const arr = [...new Set([...(s.found ?? [])].map((w) => String(w).toUpperCase()))];
|
||||
for (const w of arr) {
|
||||
if (!owners.has(w)) owners.set(w, []);
|
||||
owners.get(w).push(pi);
|
||||
}
|
||||
return arr;
|
||||
});
|
||||
|
||||
return lists.map((arr, pi) => {
|
||||
let roundScore = 0, unique = 0, shared = 0;
|
||||
const words = arr
|
||||
.sort((a, b) => b.length - a.length || a.localeCompare(b))
|
||||
.map((word) => {
|
||||
const sharedWith = owners.get(word).filter((x) => x !== pi);
|
||||
const dup = dupCancel && sharedWith.length > 0;
|
||||
const score = dup ? 0 : scoreWord(word, minLen);
|
||||
roundScore += score;
|
||||
if (sharedWith.length) shared++; else unique++;
|
||||
return { word, score, dup, sharedWith };
|
||||
});
|
||||
return { words, roundScore, unique, shared };
|
||||
});
|
||||
}
|
||||
|
||||
// The order the scoring sheet reveals words: every distinct word once (longest
|
||||
// first), so a shared word is struck in every column on the same beat.
|
||||
// → { steps: [{ word, entries: [{ player, score, dup, row }] }], rows: [count per player] }
|
||||
// Summing entry scores per player always equals that player's roundScore.
|
||||
export function revealPlan(results) {
|
||||
const byWord = new Map();
|
||||
results.forEach((res, pi) => {
|
||||
for (const e of res.words) {
|
||||
if (!byWord.has(e.word)) byWord.set(e.word, []);
|
||||
byWord.get(e.word).push({ player: pi, score: e.score, dup: e.dup });
|
||||
}
|
||||
});
|
||||
const words = [...byWord.keys()].sort((a, b) => b.length - a.length || a.localeCompare(b));
|
||||
const rows = results.map(() => 0);
|
||||
const steps = words.map((word) => ({
|
||||
word,
|
||||
entries: byWord.get(word).map((e) => ({ ...e, row: rows[e.player]++ })),
|
||||
}));
|
||||
return { steps, rows };
|
||||
}
|
||||
|
||||
// ── Board paths ──────────────────────────────────────────────────────────────
|
||||
export function areAdjacent(a, b) {
|
||||
const dr = Math.abs(a[0] - b[0]);
|
||||
const dc = Math.abs(a[1] - b[1]);
|
||||
return (dr <= 1 && dc <= 1) && !(dr === 0 && dc === 0);
|
||||
}
|
||||
|
||||
// A path is valid if every step is to an adjacent cell and no cell repeats.
|
||||
export function isValidPath(path) {
|
||||
const seen = new Set();
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
|
|
@ -32,29 +132,246 @@ export function isValidPath(path) {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Given each player's found words, apply the classic duplicate rule: any word
|
||||
// found by 2+ players scores 0 for everyone. Returns per-player scored results in
|
||||
// the same order as `sheets`.
|
||||
// sheets: [{ found: Iterable<string> }]
|
||||
// => [{ words: [{ word, score, dup }], roundScore }]
|
||||
export function resolveRound(sheets) {
|
||||
const counts = new Map();
|
||||
const lists = sheets.map((s) => {
|
||||
const arr = [...new Set([...s.found].map((w) => w.toUpperCase()))];
|
||||
for (const w of arr) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||
return arr;
|
||||
});
|
||||
|
||||
return lists.map((arr) => {
|
||||
let roundScore = 0;
|
||||
const words = arr
|
||||
.sort((a, b) => b.length - a.length || a.localeCompare(b))
|
||||
.map((word) => {
|
||||
const dup = (counts.get(word) ?? 0) >= 2;
|
||||
const score = dup ? 0 : scoreWord(word);
|
||||
roundScore += score;
|
||||
return { word, score, dup };
|
||||
});
|
||||
return { words, roundScore };
|
||||
});
|
||||
export function pathWord(board, path) {
|
||||
return path.map(([r, c]) => String(board[r][c]).toUpperCase()).join('');
|
||||
}
|
||||
|
||||
// A path spelling `word` (uppercase; "QU" matches the Qu face), or null.
|
||||
// `prefer` (the current path) is tried first, so typing one more letter extends
|
||||
// the highlighted path instead of jumping to a different copy of the prefix.
|
||||
export function findPath(board, word, prefer = []) {
|
||||
const w = String(word).toUpperCase();
|
||||
if (!w) return [];
|
||||
const n = board.length;
|
||||
const used = Array.from({ length: n }, () => new Array(n).fill(false));
|
||||
const path = [];
|
||||
const prefKey = prefer.map(([r, c]) => r * 16 + c);
|
||||
|
||||
const order = (cands, depth) => {
|
||||
const want = prefKey[depth];
|
||||
if (want == null) return cands;
|
||||
return cands.sort((a, b) => ((b[0] * 16 + b[1]) === want) - ((a[0] * 16 + a[1]) === want));
|
||||
};
|
||||
|
||||
const dfs = (r, c, i) => {
|
||||
const tok = String(board[r][c]).toUpperCase();
|
||||
if (w.substr(i, tok.length) !== tok) return false;
|
||||
used[r][c] = true;
|
||||
path.push([r, c]);
|
||||
const j = i + tok.length;
|
||||
if (j === w.length) return true;
|
||||
const next = [];
|
||||
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
|
||||
if (!dr && !dc) continue;
|
||||
const nr = r + dr, nc = c + dc;
|
||||
if (nr < 0 || nc < 0 || nr >= n || nc >= n || used[nr][nc]) continue;
|
||||
next.push([nr, nc]);
|
||||
}
|
||||
for (const [nr, nc] of order(next, path.length)) if (dfs(nr, nc, j)) return true;
|
||||
used[r][c] = false;
|
||||
path.pop();
|
||||
return false;
|
||||
};
|
||||
|
||||
const starts = [];
|
||||
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) starts.push([r, c]);
|
||||
for (const [r, c] of order(starts, 0)) if (dfs(r, c, 0)) return path.map((p) => [p[0], p[1]]);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Keyboard entry: Q types "QU" (there is no bare Q face); a U typed straight
|
||||
// after that Q is swallowed so typing Q-U-E-S-T also works.
|
||||
export function typeLetter(word, ch, lastWasQ = false) {
|
||||
const c = String(ch).toUpperCase();
|
||||
if (!/^[A-Z]$/.test(c)) return { word, lastWasQ };
|
||||
if (c === 'U' && lastWasQ) return { word, lastWasQ: false };
|
||||
if (c === 'Q') return { word: word + 'QU', lastWasQ: true };
|
||||
return { word: word + c, lastWasQ: false };
|
||||
}
|
||||
|
||||
export function backspace(word) {
|
||||
if (!word) return '';
|
||||
if (word.endsWith('QU')) return word.slice(0, -2);
|
||||
return word.slice(0, -1);
|
||||
}
|
||||
|
||||
// Why a word can't be submitted (null when it can).
|
||||
export function rejectReason(word, { minLen = 3, found, valid, onBoard = true }) {
|
||||
if (!word) return 'empty';
|
||||
if (!onBoard) return 'notOnBoard';
|
||||
if (word.length < minLen) return 'short';
|
||||
if (found?.has(word)) return 'already';
|
||||
if (!valid?.has(word)) return 'notWord';
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Review ───────────────────────────────────────────────────────────────────
|
||||
// Solutions grouped for the board review: common words (tiers 1–2) by length
|
||||
// (longest first), then the obscure tier-3 words. Each item knows who found it.
|
||||
// foundBy: Map<word, [playerIdx]>
|
||||
export function reviewGroups(solutions, foundBy, { minLen = 3 } = {}) {
|
||||
const items = solutions
|
||||
.filter((s) => s.word.length >= minLen)
|
||||
.map((s) => ({ word: s.word, path: s.path, tier: s.tier ?? 2, by: foundBy.get(s.word) ?? [] }));
|
||||
const groups = [];
|
||||
const common = items.filter((i) => i.tier <= 2);
|
||||
const lens = [...new Set(common.map((i) => i.word.length))].sort((a, b) => b - a);
|
||||
for (const len of lens) {
|
||||
groups.push({
|
||||
label: `${len} letters`, len, obscure: false,
|
||||
items: common.filter((i) => i.word.length === len).sort((a, b) => a.word.localeCompare(b.word)),
|
||||
});
|
||||
}
|
||||
const obscure = items.filter((i) => i.tier > 2)
|
||||
.sort((a, b) => b.word.length - a.word.length || a.word.localeCompare(b.word));
|
||||
if (obscure.length) groups.push({ label: 'Obscure', obscure: true, items: obscure });
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function roundSummary(solutions, playerFound, { minLen = 3 } = {}) {
|
||||
const sols = solutions.filter((s) => s.word.length >= minLen);
|
||||
const common = sols.filter((s) => (s.tier ?? 2) <= 2);
|
||||
const foundCommon = common.filter((s) => playerFound.has(s.word)).length;
|
||||
const best = [...sols].sort((a, b) => b.word.length - a.word.length || a.word.localeCompare(b.word))[0] ?? null;
|
||||
return {
|
||||
total: sols.length, found: sols.filter((s) => playerFound.has(s.word)).length,
|
||||
common: common.length, foundCommon,
|
||||
commonPct: common.length ? Math.round((foundCommon / common.length) * 100) : 0,
|
||||
maxScore: sheetScore(sols.map((s) => s.word), minLen),
|
||||
longest: best?.word ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
export function countsByLength(words) {
|
||||
const out = {};
|
||||
for (const w of words) { const k = Math.min(8, w.length); out[k] = (out[k] ?? 0) + 1; }
|
||||
return out;
|
||||
}
|
||||
|
||||
export function longestWord(words) {
|
||||
let best = '';
|
||||
for (const w of words) if (w.length > best.length || (w.length === best.length && w < best)) best = w;
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── Practice goals ───────────────────────────────────────────────────────────
|
||||
export const PRACTICE_GOAL = 0.25; // share of the board's common words
|
||||
|
||||
export function practiceGoal(solutions, minLen = 3) {
|
||||
const common = solutions.filter((s) => s.word.length >= minLen && (s.tier ?? 2) <= 2).length;
|
||||
return Math.max(5, Math.round(common * PRACTICE_GOAL));
|
||||
}
|
||||
|
||||
// A hint: the first two letters of an unfound common word (longest first among
|
||||
// a few random picks, so hints stay useful). Returns { word, path, prefix } | null.
|
||||
export function pickHint(solutions, found, { minLen = 3, rng = Math.random, avoid = new Set() } = {}) {
|
||||
const pool = solutions.filter((s) => s.word.length >= minLen && (s.tier ?? 2) <= 2 && !found.has(s.word) && !avoid.has(s.word));
|
||||
if (!pool.length) return null;
|
||||
const sample = [];
|
||||
for (let i = 0; i < 4; i++) sample.push(pool[Math.floor(rng() * pool.length)]);
|
||||
sample.sort((a, b) => b.word.length - a.word.length);
|
||||
const s = sample[0];
|
||||
const toks = s.word.match(/QU|[A-Z]/g) ?? [];
|
||||
return { word: s.word, path: s.path, prefix: toks.slice(0, 2).join('') };
|
||||
}
|
||||
|
||||
// ── Match state (JSON-safe; autosaved between rounds) ─────────────────────────
|
||||
// players: [{ id, name, isHuman, skill?, spriteIndex? }]
|
||||
export function createMatch({ mode = 'match', rules, players, daily = null }) {
|
||||
const r = normalizeRules(rules);
|
||||
return {
|
||||
version: 1, mode, daily, rules: r,
|
||||
players: players.map((p) => ({ id: p.id, name: p.name, isHuman: !!p.isHuman, skill: p.skill ?? null, spriteIndex: p.spriteIndex ?? 0 })),
|
||||
round: 1, totals: Object.fromEntries(players.map((p) => [p.id, 0])),
|
||||
history: [], // [{ round, scores: {id: pts}, words: {id: count}, best: {id: word} }]
|
||||
};
|
||||
}
|
||||
|
||||
export function commitRound(match, results, foundLists) {
|
||||
const scores = {}, words = {}, best = {};
|
||||
match.players.forEach((p, i) => {
|
||||
scores[p.id] = results[i].roundScore;
|
||||
words[p.id] = foundLists[i].length;
|
||||
best[p.id] = longestWord(foundLists[i]);
|
||||
match.totals[p.id] += results[i].roundScore;
|
||||
});
|
||||
match.history.push({ round: match.round, scores, words, best });
|
||||
return match;
|
||||
}
|
||||
|
||||
export function isMatchOver(match) {
|
||||
return match.history.length >= match.rules.rounds;
|
||||
}
|
||||
|
||||
export function standings(match) {
|
||||
return [...match.players].sort((a, b) => match.totals[b.id] - match.totals[a.id]);
|
||||
}
|
||||
|
||||
// 'win' | 'draw' | 'loss' for the human.
|
||||
export function matchResult(match) {
|
||||
const st = standings(match);
|
||||
const top = match.totals[st[0].id];
|
||||
const human = match.players.find((p) => p.isHuman);
|
||||
if (match.totals[human.id] !== top) return 'loss';
|
||||
return st.filter((p) => match.totals[p.id] === top).length > 1 ? 'draw' : 'win';
|
||||
}
|
||||
|
||||
export const SAVE_KEY = 'boggle-save-v1';
|
||||
|
||||
export function serialiseSave(match, sig) {
|
||||
return JSON.stringify({ v: 1, sig, match, savedAt: Date.now() });
|
||||
}
|
||||
|
||||
export function parseSave(raw, sig) {
|
||||
try {
|
||||
const s = JSON.parse(raw || 'null');
|
||||
if (!s || s.v !== 1 || s.sig !== sig || s.match?.version !== 1) return null;
|
||||
if (isMatchOver(s.match)) return null;
|
||||
s.match.rules = normalizeRules(s.match.rules);
|
||||
return s;
|
||||
} catch (_) { return null; }
|
||||
}
|
||||
|
||||
// ── Daily Board ──────────────────────────────────────────────────────────────
|
||||
export const DAILY_KEY = 'boggle-daily';
|
||||
export function todayString(d = new Date()) { return localDateString(d); }
|
||||
export function dailySeed(date) { return dateSeed(`boggle:${date}`); }
|
||||
|
||||
export function longDate(date) {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
const dt = new Date(y, m - 1, d);
|
||||
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
||||
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
return `${days[dt.getDay()]}, ${months[m - 1]} ${d}`;
|
||||
}
|
||||
|
||||
function prevDate(date) {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return localDateString(new Date(y, m - 1, d - 1));
|
||||
}
|
||||
|
||||
// daily: { lastDate, streak, bestStreak, results: { [date]: { score, words, commonPct, longest } } }
|
||||
export function blankDaily() { return { lastDate: null, streak: 0, bestStreak: 0, results: {} }; }
|
||||
|
||||
export function updateDaily(daily, date, result) {
|
||||
const d = { ...blankDaily(), ...(daily ?? {}) };
|
||||
d.results = { ...(d.results ?? {}) };
|
||||
if (d.results[date]) return d; // one attempt per day
|
||||
d.results[date] = result;
|
||||
d.streak = d.lastDate === prevDate(date) ? d.streak + 1 : 1;
|
||||
d.bestStreak = Math.max(d.bestStreak, d.streak);
|
||||
d.lastDate = date;
|
||||
const keys = Object.keys(d.results).sort();
|
||||
while (keys.length > 60) delete d.results[keys.shift()];
|
||||
return d;
|
||||
}
|
||||
|
||||
export function dailyStreakNow(daily, today) {
|
||||
if (!daily?.lastDate) return 0;
|
||||
return daily.lastDate === today || daily.lastDate === prevDate(today) ? daily.streak : 0;
|
||||
}
|
||||
|
||||
export function fmtClock(ms) {
|
||||
const s = Math.max(0, Math.ceil(ms / 1000));
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,144 @@
|
|||
// BogglePad.js — the player's yellow legal pad: found words in ballpoint, a
|
||||
// running score, counts by length, and a scrolling list (wheel / arrows) so a
|
||||
// big round never runs off the paper.
|
||||
//
|
||||
// addWord(word, pts) writes it in (auto-scrolls to the newest line)
|
||||
// pulse(word) scrolls to an existing word and wiggles it ("already found")
|
||||
// setScoreLabel(text) header right side
|
||||
// reset()
|
||||
|
||||
import { PAD, PAD_TITLE, PAD_SCORE, PAD_COUNTS_Y, PAD_LIST, PAD_FOOT_Y } from './BoggleLayout.js';
|
||||
import { HAND_FONT, INK_HEX, RED_HEX, PENCIL_HEX, SERIF, PAD_PX } from './BoggleArt.js';
|
||||
import { countsByLength } from './BoggleLogic.js';
|
||||
|
||||
export class BogglePad {
|
||||
constructor(scene, depth, { title = 'Your Words' } = {}) {
|
||||
this.scene = scene;
|
||||
this.depth = depth;
|
||||
this.words = [];
|
||||
this.scores = [];
|
||||
this.top = 0; // first visible row
|
||||
const objs = [];
|
||||
this.objs = objs;
|
||||
objs.push(scene.add.image(PAD.x - PAD_PX, PAD.y - PAD_PX, 'boggle-pad').setOrigin(0).setDepth(depth));
|
||||
this.title = scene.add.text(PAD_TITLE.x - 150, PAD_TITLE.y, title, {
|
||||
fontFamily: HAND_FONT, fontSize: '50px', color: RED_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1).setAngle(-1.5);
|
||||
this.score = scene.add.text(PAD_SCORE.x, PAD_SCORE.y + 4, '0 pts', {
|
||||
fontFamily: HAND_FONT, fontSize: '40px', color: INK_HEX,
|
||||
}).setOrigin(1, 0.5).setDepth(depth + 1);
|
||||
this.counts = scene.add.text(PAD.x + PAD.w / 2 + 20, PAD_COUNTS_Y, '', {
|
||||
fontFamily: SERIF, fontSize: '19px', color: PENCIL_HEX, fontStyle: 'italic',
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
objs.push(this.title, this.score, this.counts);
|
||||
|
||||
const { x, y, w, rowH, rows, cols } = PAD_LIST;
|
||||
this.colW = w / cols;
|
||||
this.slots = [];
|
||||
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
|
||||
const sx = x + c * this.colW, sy = y + r * rowH;
|
||||
const word = scene.add.text(sx, sy, '', { fontFamily: HAND_FONT, fontSize: '28px', color: INK_HEX })
|
||||
.setOrigin(0, 0.5).setDepth(depth + 1);
|
||||
const pts = scene.add.text(sx, sy - 8, '', { fontFamily: SERIF, fontSize: '14px', color: PENCIL_HEX })
|
||||
.setOrigin(0, 0.5).setDepth(depth + 1);
|
||||
this.slots.push({ word, pts });
|
||||
objs.push(word, pts);
|
||||
}
|
||||
|
||||
this.foot = scene.add.text(PAD.x + 86, PAD_FOOT_Y, '', {
|
||||
fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: PENCIL_HEX,
|
||||
}).setOrigin(0, 0.5).setDepth(depth + 1);
|
||||
this.more = scene.add.text(PAD.x + PAD.w - 40, PAD_FOOT_Y, '', {
|
||||
fontFamily: SERIF, fontSize: '18px', color: PENCIL_HEX,
|
||||
}).setOrigin(1, 0.5).setDepth(depth + 1).setInteractive({ useHandCursor: true });
|
||||
this.more.on('pointerdown', () => this.scroll(this.top + rows >= this.totalRows() ? -9999 : rows - 2));
|
||||
objs.push(this.foot, this.more);
|
||||
|
||||
this.onWheel = (p, _o, _dx, dy) => {
|
||||
if (p.worldX < PAD.x || p.worldX > PAD.x + PAD.w || p.worldY < PAD.y || p.worldY > PAD.y + PAD.h) return;
|
||||
this.scroll(dy > 0 ? 2 : -2);
|
||||
};
|
||||
scene.input.on('wheel', this.onWheel);
|
||||
this.redraw();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.scene.input.off('wheel', this.onWheel);
|
||||
this.objs.forEach((o) => o.destroy());
|
||||
}
|
||||
|
||||
setVisible(v) { this.objs.forEach((o) => o.setVisible(v)); }
|
||||
|
||||
totalRows() { return Math.ceil(this.words.length / PAD_LIST.cols); }
|
||||
|
||||
scroll(d) {
|
||||
const max = Math.max(0, this.totalRows() - PAD_LIST.rows);
|
||||
this.top = Math.max(0, Math.min(max, this.top + d));
|
||||
this.redraw();
|
||||
}
|
||||
|
||||
reset() { this.words = []; this.scores = []; this.top = 0; this.redraw(); this.setScoreLabel('0 pts'); }
|
||||
|
||||
setScoreLabel(t) { this.score.setText(t); }
|
||||
|
||||
slotFor(i) {
|
||||
const row = Math.floor(i / PAD_LIST.cols) - this.top;
|
||||
if (row < 0 || row >= PAD_LIST.rows) return null;
|
||||
return this.slots[row * PAD_LIST.cols + (i % PAD_LIST.cols)];
|
||||
}
|
||||
|
||||
redraw() {
|
||||
this.slots.forEach((s) => { s.word.setText('').setScale(1).setAlpha(1); s.pts.setText(''); });
|
||||
for (let i = 0; i < this.words.length; i++) {
|
||||
const s = this.slotFor(i);
|
||||
if (!s) continue;
|
||||
const w = this.words[i];
|
||||
s.word.setText(w.toLowerCase()).setFontSize(w.length > 9 ? '22px' : w.length > 7 ? '25px' : '28px');
|
||||
s.word.setAngle(((w.charCodeAt(0) * 7 + w.length * 13) % 5 - 2) * 0.4);
|
||||
s.pts.setText(String(this.scores[i])).setX(s.word.x + Math.min(this.colW - 18, s.word.width + 4));
|
||||
}
|
||||
const c = countsByLength(this.words);
|
||||
const parts = [3, 4, 5, 6, 7, 8].map((k) => `${k === 8 ? '8+' : k}: ${c[k] ?? 0}`);
|
||||
this.counts.setText(parts.join(' '));
|
||||
const n = this.words.length;
|
||||
this.foot.setText(n ? `${n} word${n === 1 ? '' : 's'}` : 'Trace or type a word to begin');
|
||||
const rows = this.totalRows();
|
||||
if (rows > PAD_LIST.rows) {
|
||||
const atEnd = this.top + PAD_LIST.rows >= rows;
|
||||
this.more.setText(atEnd ? '▲ back to top' : `▼ more (${rows - this.top - PAD_LIST.rows} rows)`);
|
||||
} else this.more.setText('');
|
||||
}
|
||||
|
||||
addWord(word, pts) {
|
||||
this.words.push(word);
|
||||
this.scores.push(pts);
|
||||
const max = Math.max(0, this.totalRows() - PAD_LIST.rows);
|
||||
this.top = max;
|
||||
this.redraw();
|
||||
const s = this.slotFor(this.words.length - 1);
|
||||
if (s) {
|
||||
const full = s.word.width;
|
||||
s.word.setCrop(0, 0, 0, s.word.height);
|
||||
const st = { w: 0 };
|
||||
this.scene.tweens.add({
|
||||
targets: st, w: full + 4, duration: 120 + word.length * 45, ease: 'Linear',
|
||||
onUpdate: () => s.word.setCrop(0, 0, st.w, s.word.height),
|
||||
onComplete: () => s.word.setCrop(),
|
||||
});
|
||||
s.pts.setAlpha(0);
|
||||
this.scene.tweens.add({ targets: s.pts, alpha: 1, delay: 120 + word.length * 45, duration: 150 });
|
||||
}
|
||||
}
|
||||
|
||||
pulse(word) {
|
||||
const i = this.words.indexOf(word);
|
||||
if (i < 0) return;
|
||||
const row = Math.floor(i / PAD_LIST.cols);
|
||||
if (row < this.top || row >= this.top + PAD_LIST.rows) { this.top = Math.max(0, row - 2); this.redraw(); }
|
||||
const s = this.slotFor(i);
|
||||
if (!s) return;
|
||||
this.scene.tweens.add({ targets: s.word, scale: { from: 1.35, to: 1 }, duration: 380, ease: 'Back.Out' });
|
||||
s.word.setColor('#b8321f');
|
||||
this.scene.time.delayedCall(700, () => s.word.setColor(INK_HEX));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,328 @@
|
|||
// BoggleReview.js — after the sand runs out.
|
||||
//
|
||||
// openScoring every player's sheet side by side. Words are read out longest
|
||||
// first, one distinct word per beat, so a word two players both
|
||||
// found is struck off every sheet at the same moment (with a red
|
||||
// connector flashing between the copies). Columns scroll — no
|
||||
// word is ever hidden — and each header's total is exactly the
|
||||
// round score that gets committed.
|
||||
// openBoardReview every word on the board, grouped by length, obscure words
|
||||
// last; click one to watch its path traced on the dice.
|
||||
// openSoloSummary practice / daily result card.
|
||||
|
||||
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
|
||||
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
|
||||
import { scoreColumns, SCORE_ROWS, REVIEW_LIST, REVIEW_SIDE, PAD_LIST, PAD_COUNTS_Y } from './BoggleLayout.js';
|
||||
import {
|
||||
DISPLAY_FONT, HAND_FONT, SERIF, INK_HEX, RED_HEX, PENCIL_HEX, BROWN_HEX, SEAT_TINT, PAD_PX,
|
||||
} from './BoggleArt.js';
|
||||
import { frame, blocker, title, handle, button } from './BoggleDialogs.js';
|
||||
import { revealPlan } from './BoggleLogic.js';
|
||||
|
||||
const ROW_H = 34;
|
||||
const BTN_GO = 0xb3501f, BTN_ALT = 0x3f4a1c, BTN = 0x5a3820;
|
||||
|
||||
// ── scoring sheet ───────────────────────────────────────────────────────────
|
||||
export function openScoring(scene, { round, rounds, players, results, depth, onReview, onContinue, continueLabel = 'Continue' }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.68)];
|
||||
objs.push(scene.add.text(GAME_WIDTH / 2, 72, rounds > 1 ? `Round ${round} of ${rounds} — Scoring` : 'Scoring', {
|
||||
fontFamily: HAND_FONT, fontSize: '66px', color: '#fff3d6',
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
|
||||
const plan = revealPlan(results);
|
||||
const cols = scoreColumns(players.length).map((rect, pi) => {
|
||||
const p = players[pi];
|
||||
const g = scene.add.graphics().setDepth(depth);
|
||||
// header card
|
||||
g.fillStyle(0x000000, 0.35).fillRoundedRect(rect.x + 4, rect.y + 6, rect.w, 76, 12);
|
||||
g.fillStyle(p.isHuman ? 0xb3501f : 0x5a3820, 1).fillRoundedRect(rect.x, rect.y, rect.w, 76, 12);
|
||||
g.fillStyle(p.isHuman ? 0xd9a63a : SEAT_TINT[(pi - 1 + 3) % 3], 1).fillRect(rect.x + 10, rect.y + 70, rect.w - 20, 4);
|
||||
// legal-pad sheet
|
||||
const sy = rect.y + 88, sh = rect.h - 88;
|
||||
g.fillStyle(0x000000, 0.3).fillRect(rect.x + 5, sy + 6, rect.w, sh);
|
||||
g.fillStyle(0xf6e98e, 1).fillRect(rect.x, sy, rect.w, sh);
|
||||
g.lineStyle(1, 0x4678be, 0.4);
|
||||
for (let ly = sy + 30 + ROW_H / 2; ly < sy + sh - 6; ly += ROW_H) g.lineBetween(rect.x + 4, ly, rect.x + rect.w - 4, ly);
|
||||
g.lineStyle(1.3, 0xc83c32, 0.55).lineBetween(rect.x + 34, sy, rect.x + 34, sy + sh);
|
||||
objs.push(g);
|
||||
objs.push(scene.add.text(rect.x + rect.w / 2, rect.y + 24, p.name, {
|
||||
fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#fff6e6',
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
const total = scene.add.text(rect.x + rect.w / 2, rect.y + 54, '0 pts', {
|
||||
fontFamily: DISPLAY_FONT, fontSize: '22px', color: '#ffe3a0',
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
objs.push(total);
|
||||
const slots = [];
|
||||
for (let i = 0; i < SCORE_ROWS; i++) {
|
||||
const yy = sy + 30 + i * ROW_H;
|
||||
const word = scene.add.text(rect.x + 46, yy, '', { fontFamily: HAND_FONT, fontSize: '27px', color: INK_HEX }).setOrigin(0, 0.5).setDepth(depth + 1);
|
||||
const pts = scene.add.text(rect.x + rect.w - 16, yy, '', { fontFamily: HAND_FONT, fontSize: '26px', color: PENCIL_HEX }).setOrigin(1, 0.5).setDepth(depth + 1);
|
||||
const strike = scene.add.graphics().setDepth(depth + 2);
|
||||
slots.push({ word, pts, strike, y: yy });
|
||||
objs.push(word, pts, strike);
|
||||
}
|
||||
const foot = scene.add.text(rect.x + rect.w / 2, sy + sh - 18, '', {
|
||||
fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: PENCIL_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
objs.push(foot);
|
||||
return { rect, slots, total, foot, shown: [], running: 0, top: 0, follow: true };
|
||||
});
|
||||
|
||||
const drawCol = (col) => {
|
||||
if (col.follow) col.top = Math.max(0, col.shown.length - SCORE_ROWS);
|
||||
col.slots.forEach((s, i) => {
|
||||
const e = col.shown[col.top + i];
|
||||
s.strike.clear();
|
||||
if (!e) { s.word.setText(''); s.pts.setText(''); return; }
|
||||
s.word.setText(e.word.toLowerCase()).setColor(e.dup ? '#8a7f70' : INK_HEX);
|
||||
s.pts.setText(e.dup ? '—' : e.score ? `+${e.score}` : '0').setColor(e.dup ? '#b8321f' : PENCIL_HEX);
|
||||
if (e.dup) {
|
||||
s.strike.lineStyle(3, 0xc0301f, 0.9);
|
||||
s.strike.lineBetween(s.word.x - 4, s.y + 1, s.word.x + s.word.width + 4, s.y - 2);
|
||||
}
|
||||
});
|
||||
const more = col.shown.length - col.top - SCORE_ROWS;
|
||||
const scrolled = col.top > 0;
|
||||
col.foot.setText(more > 0 ? `▼ ${more} more` : scrolled ? `▲ ${col.top} above` : '');
|
||||
};
|
||||
|
||||
// reveal
|
||||
let stepIdx = 0, timer = null, done = false;
|
||||
const flashes = [];
|
||||
const reveal = (step, animate) => {
|
||||
for (const e of step.entries) {
|
||||
const col = cols[e.player];
|
||||
col.shown.push({ word: step.word, score: e.score, dup: e.dup });
|
||||
col.running += e.score;
|
||||
col.total.setText(`${col.running} pts`);
|
||||
if (animate) drawCol(col);
|
||||
}
|
||||
if (!animate) return;
|
||||
const dup = step.entries.some((e) => e.dup);
|
||||
if (dup) {
|
||||
playSoundEx(scene, SFX.PIECE_CLICK, { rate: 0.7 });
|
||||
// connector between the copies
|
||||
const pts = step.entries.map((e) => {
|
||||
const col = cols[e.player];
|
||||
const row = col.shown.length - 1 - col.top;
|
||||
const s = col.slots[Math.max(0, Math.min(SCORE_ROWS - 1, row))];
|
||||
return { x: s.word.x + s.word.width / 2, y: s.y };
|
||||
});
|
||||
const g = scene.add.graphics().setDepth(depth + 3);
|
||||
g.lineStyle(3, 0xd8452e, 0.75);
|
||||
for (let i = 1; i < pts.length; i++) g.lineBetween(pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y);
|
||||
pts.forEach((p) => g.fillStyle(0xd8452e, 0.9).fillCircle(p.x, p.y, 5));
|
||||
flashes.push(g);
|
||||
scene.tweens.add({ targets: g, alpha: 0, delay: 380, duration: 320, onComplete: () => g.destroy() });
|
||||
} else {
|
||||
playSoundEx(scene, SFX.PENCIL_WRITE, { volume: 0.35, rate: 1 + Math.random() * 0.2 });
|
||||
step.entries.forEach((e) => scene.tweens.add({ targets: cols[e.player].total, scale: { from: 1.25, to: 1 }, duration: 140 }));
|
||||
}
|
||||
return dup;
|
||||
};
|
||||
const next = () => {
|
||||
if (stepIdx >= plan.steps.length) { finish(); return; }
|
||||
const dup = reveal(plan.steps[stepIdx++], true);
|
||||
timer = scene.time.delayedCall(dup ? 420 : 90, next);
|
||||
};
|
||||
const afterButtons = [];
|
||||
const finish = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
timer?.remove();
|
||||
while (stepIdx < plan.steps.length) reveal(plan.steps[stepIdx++], false);
|
||||
cols.forEach((col, pi) => {
|
||||
// the header shows exactly the committed round score
|
||||
col.running = results[pi].roundScore;
|
||||
col.total.setText(`${col.running} pts`);
|
||||
col.follow = false;
|
||||
col.top = 0;
|
||||
drawCol(col);
|
||||
const r = results[pi];
|
||||
col.foot.setText(`${r.unique} unique · ${r.shared} shared${col.shown.length > SCORE_ROWS ? ' · scroll for more' : ''}`);
|
||||
});
|
||||
skip.destroy();
|
||||
afterButtons.push(button(scene, GAME_WIDTH / 2 - 150, GAME_HEIGHT - 60, 'Board Review', () => onReview?.(), depth + 4, { w: 250, h: 56, size: 20, bg: BTN_ALT }));
|
||||
afterButtons.push(button(scene, GAME_WIDTH / 2 + 150, GAME_HEIGHT - 60, continueLabel, () => hRef.close(onContinue), depth + 4, { w: 250, h: 56, size: 20, bg: BTN_GO }));
|
||||
objs.push(...afterButtons);
|
||||
playSound(scene, SFX.UI_CHIME);
|
||||
};
|
||||
const skip = button(scene, GAME_WIDTH / 2, GAME_HEIGHT - 60, 'Skip', () => finish(), depth + 4, { w: 200, h: 52, size: 20 });
|
||||
objs.push(skip);
|
||||
|
||||
const wheel = (p, _o, _dx, dy) => {
|
||||
if (!done) return;
|
||||
for (const col of cols) {
|
||||
const r = col.rect;
|
||||
if (p.worldX < r.x || p.worldX > r.x + r.w || p.worldY < r.y || p.worldY > r.y + r.h) continue;
|
||||
const max = Math.max(0, col.shown.length - SCORE_ROWS);
|
||||
col.top = Math.max(0, Math.min(max, col.top + (dy > 0 ? 3 : -3)));
|
||||
drawCol(col);
|
||||
}
|
||||
};
|
||||
scene.input.on('wheel', wheel);
|
||||
|
||||
const hRef = {
|
||||
objs,
|
||||
close(cb) {
|
||||
timer?.remove();
|
||||
scene.input.off('wheel', wheel);
|
||||
flashes.forEach((f) => f.destroy());
|
||||
objs.forEach((o) => o?.destroy?.());
|
||||
cb?.();
|
||||
},
|
||||
hide(v) { objs.forEach((o) => o?.setVisible?.(!v)); },
|
||||
finish,
|
||||
get done() { return done; },
|
||||
};
|
||||
scene.time.delayedCall(450, next);
|
||||
return hRef;
|
||||
}
|
||||
|
||||
// ── board review ────────────────────────────────────────────────────────────
|
||||
// groups: reviewGroups(...) · summary: roundSummary(...) · players: match players
|
||||
export function openBoardReview(scene, { tray, groups, summary, players, score = null, depth, onClose }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.72)];
|
||||
tray.setDepth(depth + 1);
|
||||
tray.setEnabled(false);
|
||||
tray.setPath([]);
|
||||
|
||||
// left: summary card
|
||||
const S = REVIEW_SIDE;
|
||||
objs.push(frame(scene, S.x, S.y, S.w, S.h, depth));
|
||||
objs.push(title(scene, S.x + S.w / 2, S.y + 48, 'Board Review', depth + 1, 30));
|
||||
const lines = [
|
||||
`You found ${summary.found} of ${summary.total} words`,
|
||||
`Common words: ${summary.foundCommon} of ${summary.common} (${summary.commonPct}%)`,
|
||||
score != null ? `Your score: ${score} pts` : null,
|
||||
`Every word on the board: ${summary.maxScore} pts`,
|
||||
summary.longest ? `Longest word: ${summary.longest}` : null,
|
||||
].filter(Boolean);
|
||||
objs.push(scene.add.text(S.x + 40, S.y + 130, lines.join('\n'), {
|
||||
fontFamily: SERIF, fontSize: '19px', color: '#2b2418', lineSpacing: 12, wordWrap: { width: S.w - 70 },
|
||||
}).setDepth(depth + 1));
|
||||
const rivals = players.filter((p) => !p.isHuman);
|
||||
const legend = [
|
||||
'✓ word — you found it',
|
||||
...(rivals.length ? ['word (A) — a rival found it'] : []),
|
||||
'word — missed',
|
||||
'Click any word to trace it on the dice.',
|
||||
];
|
||||
objs.push(scene.add.text(S.x + 40, S.y + 420, legend.join('\n'), {
|
||||
fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: PENCIL_HEX, lineSpacing: 10, wordWrap: { width: S.w - 70 },
|
||||
}).setDepth(depth + 1));
|
||||
const initials = new Map(players.map((p, i) => [i, (p.name || '?')[0].toUpperCase()]));
|
||||
|
||||
// right: list on a legal pad
|
||||
const L = REVIEW_LIST;
|
||||
objs.push(scene.add.image(L.x - PAD_PX, L.y - PAD_PX, 'boggle-pad').setOrigin(0).setDepth(depth));
|
||||
objs.push(scene.add.text(L.x + L.w / 2 + 20, L.y + 112, 'Every word on the board', {
|
||||
fontFamily: HAND_FONT, fontSize: '42px', color: RED_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
objs.push(scene.add.text(L.x + L.w / 2 + 20, PAD_COUNTS_Y, 'click a word to trace it on the dice', {
|
||||
fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: PENCIL_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
|
||||
const COLS = 3, ROWS = 22, RH = 34;
|
||||
const lx = L.x + 82, ly = PAD_LIST.y, colW = (L.w - 112) / COLS;
|
||||
const rows = [];
|
||||
for (const gr of groups) {
|
||||
rows.push({ head: `${gr.label} (${gr.items.length})`, obscure: gr.obscure });
|
||||
for (let i = 0; i < gr.items.length; i += COLS) rows.push({ items: gr.items.slice(i, i + COLS), obscure: gr.obscure });
|
||||
}
|
||||
let top = 0;
|
||||
let selected = null;
|
||||
const slots = [];
|
||||
for (let r = 0; r < ROWS; r++) {
|
||||
const y = ly + r * RH;
|
||||
const head = scene.add.text(lx - 10, y, '', { fontFamily: DISPLAY_FONT, fontSize: '19px', color: BROWN_HEX }).setOrigin(0, 0.5).setDepth(depth + 1);
|
||||
const words = [];
|
||||
for (let c = 0; c < COLS; c++) {
|
||||
const t = scene.add.text(lx + c * colW, y, '', { fontFamily: HAND_FONT, fontSize: '25px', color: '#2b2418' })
|
||||
.setOrigin(0, 0.5).setDepth(depth + 1).setInteractive({ useHandCursor: true });
|
||||
t.on('pointerdown', () => {
|
||||
if (!t._item) return;
|
||||
selected = t._item.word;
|
||||
tray.playPath(t._item.path, 'hint');
|
||||
draw();
|
||||
});
|
||||
t.on('pointerover', () => { if (t._item) t.setScale(1.08); });
|
||||
t.on('pointerout', () => t.setScale(1));
|
||||
words.push(t);
|
||||
}
|
||||
slots.push({ head, words });
|
||||
objs.push(head, ...words);
|
||||
}
|
||||
const foot = scene.add.text(L.x + L.w - 40, L.y + L.h - 34, '', { fontFamily: SERIF, fontSize: '17px', color: PENCIL_HEX })
|
||||
.setOrigin(1, 0.5).setDepth(depth + 1).setInteractive({ useHandCursor: true });
|
||||
foot.on('pointerdown', () => { top = top + ROWS >= rows.length ? 0 : Math.min(rows.length - ROWS, top + ROWS - 2); draw(); });
|
||||
objs.push(foot);
|
||||
|
||||
function draw() {
|
||||
slots.forEach((s, i) => {
|
||||
const row = rows[top + i];
|
||||
s.head.setText('');
|
||||
s.words.forEach((t) => { t.setText(''); t._item = null; });
|
||||
if (!row) return;
|
||||
if (row.head) { s.head.setText(row.head).setColor(row.obscure ? '#8a7f70' : BROWN_HEX); return; }
|
||||
row.items.forEach((it, c) => {
|
||||
const t = s.words[c];
|
||||
const mine = it.by.includes(0);
|
||||
const others = it.by.filter((x) => x !== 0).map((x) => initials.get(x)).join('');
|
||||
let txt = it.word.toLowerCase();
|
||||
if (mine) txt = `✓ ${txt}`;
|
||||
else if (others) txt = `${txt} (${others})`;
|
||||
t._item = it;
|
||||
t.setText(txt)
|
||||
.setFontSize(txt.length > 13 ? '20px' : '25px')
|
||||
.setColor(it.word === selected ? '#c2551f' : mine ? INK_HEX : others ? '#6f6656' : row.obscure ? '#9a8f80' : '#2b2418')
|
||||
.setFontStyle(row.obscure && !mine ? 'italic' : 'normal');
|
||||
});
|
||||
});
|
||||
foot.setText(rows.length > ROWS ? (top + ROWS >= rows.length ? '▲ back to top' : `▼ more (${rows.length - top - ROWS} rows)`) : '');
|
||||
}
|
||||
draw();
|
||||
|
||||
const wheel = (p, _o, _dx, dy) => {
|
||||
if (p.worldX < L.x) return;
|
||||
top = Math.max(0, Math.min(Math.max(0, rows.length - ROWS), top + (dy > 0 ? 3 : -3)));
|
||||
draw();
|
||||
};
|
||||
scene.input.on('wheel', wheel);
|
||||
|
||||
let hRef = null;
|
||||
objs.push(button(scene, S.x + S.w / 2, S.y + S.h - 60, 'Done', () => hRef.close(), depth + 2, { w: 220, h: 52, size: 20, bg: BTN_GO }));
|
||||
hRef = handle(objs, () => {
|
||||
scene.input.off('wheel', wheel);
|
||||
tray.stopPlay?.();
|
||||
tray.setPath([]);
|
||||
tray.resetDepth();
|
||||
onClose?.();
|
||||
});
|
||||
return hRef;
|
||||
}
|
||||
|
||||
// ── solo result card ────────────────────────────────────────────────────────
|
||||
export function openSoloSummary(scene, { heading, lines, records = [], depth, onReview, onAgain, againLabel = 'New Board', onMenu }) {
|
||||
const objs = [blocker(scene, depth - 1, 0.55)];
|
||||
const w = 780, h = 560;
|
||||
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
|
||||
const cx = x + w / 2;
|
||||
objs.push(frame(scene, x, y, w, h, depth));
|
||||
objs.push(title(scene, cx, y + 48, heading, depth + 1, 34));
|
||||
objs.push(scene.add.text(cx, y + 220, lines.join('\n'), {
|
||||
fontFamily: SERIF, fontSize: '22px', color: '#2b2418', align: 'center', lineSpacing: 10,
|
||||
}).setOrigin(0.5).setDepth(depth + 1));
|
||||
if (records.length) {
|
||||
objs.push(scene.add.text(cx, y + 352, records.join(' · '), {
|
||||
fontFamily: HAND_FONT, fontSize: '30px', color: RED_HEX, align: 'center', wordWrap: { width: w - 80 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1).setAngle(-1.5));
|
||||
}
|
||||
let hRef = null;
|
||||
objs.push(button(scene, cx - 250, y + h - 64, 'Board Review', () => onReview?.(), depth + 2, { w: 230, h: 54, size: 19, bg: BTN_ALT }));
|
||||
if (onAgain) objs.push(button(scene, cx, y + h - 64, againLabel, () => { hRef.close(); onAgain(); }, depth + 2, { w: 230, h: 54, size: 19, bg: BTN_GO }));
|
||||
objs.push(button(scene, cx + 250, y + h - 64, 'Menu', () => { hRef.close(); onMenu(); }, depth + 2, { w: 200, h: 54, size: 19, bg: BTN }));
|
||||
hRef = handle(objs);
|
||||
hRef.hide = (v) => objs.forEach((o) => o?.setVisible?.(!v));
|
||||
return hRef;
|
||||
}
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
// BoggleSeats.js — the rivals round the coffee table (left column), and the
|
||||
// practice / daily card that takes their place when you play solo.
|
||||
//
|
||||
// BoggleSeats portrait · name · skill pips · word count · a little pad that
|
||||
// fills with pencil scribbles as they write · speech bubbles
|
||||
// PracticeCard goal meter, words left by length (hints), streak / date lines
|
||||
|
||||
import { createOpponentPortrait } from '../../ui/Portrait.js';
|
||||
import { playSoundEx, SFX } from '../../ui/Sounds.js';
|
||||
import { seatParts, PRACTICE } from './BoggleLayout.js';
|
||||
import {
|
||||
PAD_PX, DISPLAY_FONT, HAND_FONT, SERIF, BROWN_HEX, SEAT_TINT, ORANGE, MUSTARD, AVOCADO, PENCIL_HEX, INK_HEX,
|
||||
} from './BoggleArt.js';
|
||||
|
||||
export class BoggleSeats {
|
||||
constructor(scene, rivals, depth, { sounds = () => true } = {}) {
|
||||
this.scene = scene;
|
||||
this.depth = depth;
|
||||
this.sounds = sounds;
|
||||
this.seats = new Map();
|
||||
this.portraits = [];
|
||||
this.lastScratch = 0;
|
||||
rivals.forEach((p, i) => {
|
||||
const s = seatParts(i);
|
||||
const objs = [];
|
||||
objs.push(scene.add.image(s.rect.x - PAD_PX, s.rect.y - PAD_PX, 'boggle-seat').setOrigin(0).setDepth(depth));
|
||||
const ring = scene.add.graphics().setDepth(depth + 1);
|
||||
ring.fillStyle(SEAT_TINT[i % SEAT_TINT.length], 1).fillCircle(s.portrait.x, s.portrait.y, s.portrait.r + 6);
|
||||
objs.push(ring);
|
||||
const portrait = createOpponentPortrait(scene, p, s.portrait.x, s.portrait.y, s.portrait.r, depth + 2);
|
||||
this.portraits.push(portrait);
|
||||
objs.push(scene.add.text(s.name.x, s.name.y, p.name, {
|
||||
fontFamily: DISPLAY_FONT, fontSize: '27px', color: BROWN_HEX,
|
||||
}).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
const pips = scene.add.graphics().setDepth(depth + 1);
|
||||
for (let k = 0; k < 5; k++) {
|
||||
const on = k < (p.skill ?? 3);
|
||||
pips.fillStyle(on ? ORANGE : 0x000000, on ? 1 : 0.15).fillCircle(s.pips.x + k * 20, s.pips.y, 7);
|
||||
pips.lineStyle(1.5, 0x8a4a1a, 0.8).strokeCircle(s.pips.x + k * 20, s.pips.y, 7);
|
||||
}
|
||||
objs.push(pips);
|
||||
const count = scene.add.text(s.count.x, s.count.y, '0', {
|
||||
fontFamily: DISPLAY_FONT, fontSize: '54px', color: '#c2551f',
|
||||
}).setOrigin(1, 0.5).setDepth(depth + 1);
|
||||
const label = scene.add.text(s.countLabel.x, s.countLabel.y, 'words', {
|
||||
fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: PENCIL_HEX,
|
||||
}).setOrigin(1, 0.5).setDepth(depth + 1);
|
||||
objs.push(count, label);
|
||||
// the little pad they scribble on
|
||||
const sc = s.scribble;
|
||||
const padG = scene.add.graphics().setDepth(depth + 1);
|
||||
padG.fillStyle(0xf6e98e, 1).fillRect(sc.x, sc.y, sc.w, sc.h);
|
||||
padG.lineStyle(1, 0x4678be, 0.35);
|
||||
for (let yy = sc.y + 14; yy < sc.y + sc.h; yy += 14) padG.lineBetween(sc.x, yy, sc.x + sc.w, yy);
|
||||
padG.fillStyle(0x7a2a1a, 1).fillRect(sc.x, sc.y - 6, sc.w, 7);
|
||||
objs.push(padG);
|
||||
const scrib = scene.add.graphics().setDepth(depth + 2);
|
||||
const pencil = scene.add.container(sc.x + 20, sc.y + 12).setDepth(depth + 3);
|
||||
const pg = scene.add.graphics();
|
||||
pg.fillStyle(0xf0b030, 1).fillRect(-3, -34, 7, 30);
|
||||
pg.fillStyle(0xe8b88a, 1).fillTriangle(-3, -4, 4, -4, 0.5, 6);
|
||||
pg.fillStyle(0x333333, 1).fillTriangle(-1, 2, 2, 2, 0.5, 6);
|
||||
pg.fillStyle(0xe06080, 1).fillRect(-3, -40, 7, 6);
|
||||
pencil.add(pg);
|
||||
pencil.setAngle(28);
|
||||
objs.push(scrib, pencil);
|
||||
this.seats.set(p.id, { idx: i, parts: s, objs, count, scrib, pencil, marks: 0, bubble: null });
|
||||
});
|
||||
}
|
||||
|
||||
destroy() {
|
||||
for (const seat of this.seats.values()) { seat.objs.forEach((o) => o.destroy()); seat.bubble?.destroy(); }
|
||||
this.portraits.forEach((p) => p?.destroy?.());
|
||||
}
|
||||
|
||||
hidePortraits() { this.portraits.forEach((p) => p?.setVideoVisible?.(false)); }
|
||||
showPortraits() { this.portraits.forEach((p) => p?.setVideoVisible?.(true)); }
|
||||
emotion(id, e) { const s = this.seats.get(id); if (s) this.portraits[s.idx]?.playEmotion?.(e); }
|
||||
|
||||
resetRound() {
|
||||
for (const seat of this.seats.values()) {
|
||||
seat.count.setText('0');
|
||||
seat.scrib.clear();
|
||||
seat.marks = 0;
|
||||
const sc = seat.parts.scribble;
|
||||
seat.pencil.setPosition(sc.x + 20, sc.y + 12);
|
||||
}
|
||||
}
|
||||
|
||||
// A rival wrote a word: count bumps, pencil scribbles a squiggle.
|
||||
bump(id, count, wordLen = 4) {
|
||||
const seat = this.seats.get(id);
|
||||
if (!seat) return;
|
||||
seat.count.setText(String(count));
|
||||
this.scene.tweens.add({ targets: seat.count, scale: { from: 1.35, to: 1 }, duration: 220, ease: 'Back.Out' });
|
||||
const sc = seat.parts.scribble;
|
||||
const perRow = 6, rows = 3;
|
||||
const k = seat.marks++ % (perRow * rows);
|
||||
if (k === 0 && seat.marks > 1) seat.scrib.clear(); // fresh page
|
||||
const mx = sc.x + 8 + (k % perRow) * ((sc.w - 16) / perRow), my = sc.y + 10 + Math.floor(k / perRow) * 16;
|
||||
const w = Math.min((sc.w - 16) / perRow - 6, 14 + wordLen * 4);
|
||||
const g = seat.scrib;
|
||||
g.lineStyle(1.6, 0x3b3430, 0.8);
|
||||
g.beginPath();
|
||||
g.moveTo(mx, my);
|
||||
for (let x = 0; x <= w; x += 3) g.lineTo(mx + x, my + Math.sin(x * 0.9 + k) * 3.2);
|
||||
g.strokePath();
|
||||
this.scene.tweens.add({
|
||||
targets: seat.pencil, x: mx + w, y: my + 2, angle: { from: 22, to: 34 }, duration: 260, ease: 'Sine.InOut',
|
||||
});
|
||||
const now = this.scene.time.now;
|
||||
if (this.sounds() && now - this.lastScratch > 450) {
|
||||
this.lastScratch = now;
|
||||
playSoundEx(this.scene, SFX.PENCIL_WRITE, { volume: 0.18, rate: 1.1 + Math.random() * 0.3 });
|
||||
}
|
||||
}
|
||||
|
||||
say(id, text, dur = 2600) {
|
||||
const seat = this.seats.get(id);
|
||||
if (!seat) return;
|
||||
seat.bubble?.destroy();
|
||||
const b = seat.parts.bubble;
|
||||
const t = this.scene.add.text(b.x + 26, b.y + b.h / 2, text, {
|
||||
fontFamily: HAND_FONT, fontSize: '28px', color: '#2b2418', wordWrap: { width: b.w - 40 },
|
||||
}).setOrigin(0, 0.5);
|
||||
const w = Math.min(b.w + 60, t.width + 44), h = Math.max(54, t.height + 18);
|
||||
const g = this.scene.add.graphics();
|
||||
g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + (b.h - h) / 2 + 5, w, h, 16);
|
||||
g.fillStyle(0xfbf5e4, 1).fillRoundedRect(b.x, b.y + (b.h - h) / 2, w, h, 16);
|
||||
g.lineStyle(3, SEAT_TINT[seat.idx % SEAT_TINT.length], 1).strokeRoundedRect(b.x, b.y + (b.h - h) / 2, w, h, 16);
|
||||
g.fillStyle(0xfbf5e4, 1).fillTriangle(b.x + 2, b.y + b.h / 2 - 8, b.x + 2, b.y + b.h / 2 + 8, b.x - 14, b.y + b.h / 2 + 14);
|
||||
const c = this.scene.add.container(0, 0, [g, t]).setDepth(this.depth + 20).setAlpha(0);
|
||||
seat.bubble = c;
|
||||
this.scene.tweens.add({ targets: c, alpha: 1, duration: 160 });
|
||||
this.scene.tweens.add({
|
||||
targets: c, alpha: 0, delay: dur, duration: 300,
|
||||
onComplete: () => { c.destroy(); if (seat.bubble === c) seat.bubble = null; },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── practice / daily card ───────────────────────────────────────────────────
|
||||
export class PracticeCard {
|
||||
constructor(scene, depth) {
|
||||
this.scene = scene;
|
||||
const P = PRACTICE;
|
||||
const objs = [];
|
||||
this.objs = objs;
|
||||
objs.push(scene.add.image(P.x - PAD_PX, P.y - PAD_PX, 'boggle-practice').setOrigin(0).setDepth(depth));
|
||||
this.heading = scene.add.text(P.x + P.w / 2 + 12, P.y + 46, 'Practice', {
|
||||
fontFamily: DISPLAY_FONT, fontSize: '34px', color: BROWN_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
this.sub = scene.add.text(P.x + P.w / 2 + 12, P.y + 86, '', {
|
||||
fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: PENCIL_HEX, align: 'center', wordWrap: { width: P.w - 60 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
this.meter = scene.add.graphics().setDepth(depth + 1);
|
||||
this.meterLabel = scene.add.text(P.x + P.w / 2 + 12, P.y + 176, '', {
|
||||
fontFamily: HAND_FONT, fontSize: '30px', color: INK_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
this.leftHead = scene.add.text(P.x + P.w / 2 + 12, P.y + 236, '', {
|
||||
fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: PENCIL_HEX,
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
this.leftRows = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
this.leftRows.push(scene.add.text(P.x + 64, P.y + 276 + i * 38, '', {
|
||||
fontFamily: HAND_FONT, fontSize: '27px', color: '#2b2418',
|
||||
}).setOrigin(0, 0.5).setDepth(depth + 1));
|
||||
}
|
||||
this.note = scene.add.text(P.x + P.w / 2 + 12, P.y + P.h - 120, '', {
|
||||
fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: PENCIL_HEX, align: 'center', wordWrap: { width: P.w - 64 },
|
||||
}).setOrigin(0.5).setDepth(depth + 1);
|
||||
objs.push(this.heading, this.sub, this.meter, this.meterLabel, this.leftHead, ...this.leftRows, this.note);
|
||||
}
|
||||
|
||||
destroy() { this.objs.forEach((o) => o.destroy()); }
|
||||
setVisible(v) { this.objs.forEach((o) => o.setVisible(v)); }
|
||||
|
||||
setHeading(h, sub = '') { this.heading.setText(h); this.sub.setText(sub); }
|
||||
setNote(t) { this.note.setText(t); }
|
||||
|
||||
// found/goal meter
|
||||
setProgress(found, goal) {
|
||||
const P = PRACTICE;
|
||||
const x = P.x + 50, y = P.y + 128, w = P.w - 76, h = 18;
|
||||
const f = goal ? Math.min(1, found / goal) : 0;
|
||||
this.meter.clear();
|
||||
this.meter.fillStyle(0x000000, 0.12).fillRoundedRect(x, y, w, h, 9);
|
||||
if (f > 0) this.meter.fillStyle(f >= 1 ? AVOCADO : MUSTARD, 1).fillRoundedRect(x, y, Math.max(h, w * f), h, 9);
|
||||
this.meter.lineStyle(1.5, 0x8a4a1a, 0.6).strokeRoundedRect(x, y, w, h, 9);
|
||||
this.meterLabel.setText(goal ? `${found} / ${goal} common words${f >= 1 ? ' ✓' : ''}` : `${found} words`);
|
||||
}
|
||||
|
||||
// remaining common words by length (hints on), or null to hide
|
||||
setRemaining(map) {
|
||||
if (!map) { this.leftHead.setText(''); this.leftRows.forEach((t) => t.setText('')); return; }
|
||||
this.leftHead.setText('Common words still hiding');
|
||||
const keys = [3, 4, 5, 6, 7, 8];
|
||||
keys.forEach((k, i) => {
|
||||
const n = map[k] ?? 0;
|
||||
this.leftRows[i].setText(`${k === 8 ? '8+' : k} letters: ${n === 0 ? '—' : n}`).setAlpha(n ? 1 : 0.45);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,359 @@
|
|||
// BoggleTray.js — the walnut tray, its letter dice, the dome lid and the
|
||||
// tracing input. Everything lives in one root Container (so overlays can lift
|
||||
// the whole tray above a dim by changing a single depth).
|
||||
//
|
||||
// shake(board, rots) lid drops · tray rattles · dice tumble and settle · lid lifts
|
||||
// setPath(path, state) highlight + glowing trace ('ok' | 'bad' | 'hint')
|
||||
// popPath(path) found-word pop along the path
|
||||
// playPath(path) animated trace for the board review
|
||||
// setCovered(bool) pause cover (hides the letters)
|
||||
//
|
||||
// Pointer gestures (handled here, reported through callbacks):
|
||||
// press a die start / extend / backtrack to it / start a new word
|
||||
// drag across dice extend; dragging back onto the previous die undoes it
|
||||
// release after a drag onRelease(true) → the game may submit
|
||||
// tap the last die onTapLast() → the game removes it
|
||||
|
||||
import * as Phaser from 'phaser';
|
||||
import { trayGeom, TRAY_C } from './BoggleLayout.js';
|
||||
import { DISPLAY_FONT, DIE_INK } from './BoggleArt.js';
|
||||
import { areAdjacent } from './BoggleLogic.js';
|
||||
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
|
||||
|
||||
const UNDERLINE = new Set(['M', 'W', 'N', 'Z']);
|
||||
const LINE_OK = 0xffc84a, LINE_BAD = 0xd8452e, LINE_HINT = 0x7fd0ff;
|
||||
|
||||
export class BoggleTray {
|
||||
constructor(scene, size, depth, cb = {}) {
|
||||
this.scene = scene;
|
||||
this.cb = cb;
|
||||
this.g = trayGeom(size);
|
||||
this.n = this.g.n;
|
||||
this.enabled = false;
|
||||
this.gesture = null;
|
||||
this.path = [];
|
||||
this.board = null;
|
||||
|
||||
const root = scene.add.container(TRAY_C.x, TRAY_C.y).setDepth(depth);
|
||||
this.root = root;
|
||||
this.baseDepth = depth;
|
||||
|
||||
this.trayImg = scene.add.image(0, 0, `boggle-tray-${this.n}`);
|
||||
root.add(this.trayImg);
|
||||
|
||||
this.dice = [];
|
||||
for (let r = 0; r < this.n; r++) {
|
||||
this.dice[r] = [];
|
||||
for (let c = 0; c < this.n; c++) {
|
||||
const p = this.g.local(r, c);
|
||||
const die = scene.add.container(p.x, p.y);
|
||||
const glow = scene.add.image(0, 0, `boggle-die-glow-${this.n}`).setVisible(false);
|
||||
const body = scene.add.image(0, 0, `boggle-die-${this.n}`);
|
||||
const face = scene.add.container(-5, -5); // top-face centre (body is drawn top-left lit)
|
||||
const letter = scene.add.text(0, 0, '', {
|
||||
fontFamily: DISPLAY_FONT, fontSize: `${Math.round(this.g.cube * 0.5)}px`, color: DIE_INK,
|
||||
}).setOrigin(0.5);
|
||||
letter.setShadow(0, 2, 'rgba(255,255,255,0.75)', 0, false, true);
|
||||
const under = scene.add.graphics();
|
||||
face.add([letter, under]);
|
||||
die.add([glow, body, face]);
|
||||
die._glow = glow; die._body = body; die._face = face; die._letter = letter; die._under = under;
|
||||
die._home = { x: p.x, y: p.y };
|
||||
root.add(die);
|
||||
this.dice[r][c] = die;
|
||||
}
|
||||
}
|
||||
|
||||
this.lineGfx = scene.add.graphics();
|
||||
root.add(this.lineGfx);
|
||||
|
||||
this.cover = scene.add.container(0, 0).setVisible(false);
|
||||
const cg = scene.add.graphics();
|
||||
cg.fillStyle(0x2a1608, 0.94).fillRoundedRect(-this.g.span / 2 - 14, -this.g.span / 2 - 14, this.g.span + 28, this.g.span + 28, 18);
|
||||
const ct = scene.add.text(0, -20, 'Paused', { fontFamily: DISPLAY_FONT, fontSize: '64px', color: '#f3c04a' }).setOrigin(0.5);
|
||||
const cs = scene.add.text(0, 44, 'The board is hidden while the clock is stopped.', {
|
||||
fontFamily: 'Georgia, serif', fontSize: '20px', fontStyle: 'italic', color: '#f6ecd2',
|
||||
}).setOrigin(0.5);
|
||||
this.cover.add([cg, ct, cs]);
|
||||
root.add(this.cover);
|
||||
|
||||
this.lid = scene.add.image(0, 0, `boggle-lid-${this.n}`).setVisible(false);
|
||||
root.add(this.lid);
|
||||
|
||||
// one interactive zone over the dice; hit tests are done by geometry
|
||||
const span = this.g.span + 20;
|
||||
this.zone = scene.add.zone(TRAY_C.x, TRAY_C.y, span, span).setDepth(depth + 1).setInteractive({ useHandCursor: true });
|
||||
this.onDown = (p) => this.pointerDown(p);
|
||||
this.onMove = (p) => this.pointerMove(p);
|
||||
this.onUp = () => this.pointerUp();
|
||||
this.zone.on('pointerdown', this.onDown);
|
||||
scene.input.on('pointermove', this.onMove);
|
||||
scene.input.on('pointerup', this.onUp);
|
||||
scene.input.on('pointerupoutside', this.onUp);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.scene.input.off('pointermove', this.onMove);
|
||||
this.scene.input.off('pointerup', this.onUp);
|
||||
this.scene.input.off('pointerupoutside', this.onUp);
|
||||
this.zone.destroy();
|
||||
this.root.destroy();
|
||||
}
|
||||
|
||||
setDepth(d) { this.root.setDepth(d); this.zone.setDepth(d + 1); }
|
||||
resetDepth() { this.setDepth(this.baseDepth); }
|
||||
|
||||
setEnabled(on) {
|
||||
this.enabled = !!on;
|
||||
if (!on) this.gesture = null;
|
||||
this.zone.input.cursor = on ? 'pointer' : 'default';
|
||||
}
|
||||
|
||||
// ── letters ───────────────────────────────────────────────────────────────
|
||||
setFace(r, c, token, rot = 0) {
|
||||
const d = this.dice[r][c];
|
||||
const t = String(token ?? '');
|
||||
const qu = t.length > 1;
|
||||
d._letter.setText(t).setFontSize(Math.round(this.g.cube * (qu ? 0.4 : 0.5)));
|
||||
d._face.angle = rot;
|
||||
d._under.clear();
|
||||
if (UNDERLINE.has(t)) {
|
||||
const w = this.g.cube * 0.26;
|
||||
d._under.lineStyle(Math.max(3, this.g.cube * 0.035), 0x3a2414, 1);
|
||||
d._under.lineBetween(-w / 2, this.g.cube * 0.25, w / 2, this.g.cube * 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
setBoard(board, rots = null, tilts = null) {
|
||||
this.board = board;
|
||||
for (let r = 0; r < this.n; r++) for (let c = 0; c < this.n; c++) {
|
||||
this.setFace(r, c, board[r][c], rots ? rots[r][c] : 0);
|
||||
const d = this.dice[r][c];
|
||||
d.angle = tilts ? tilts[r][c].a : 0;
|
||||
d.x = d._home.x + (tilts ? tilts[r][c].dx : 0);
|
||||
d.y = d._home.y + (tilts ? tilts[r][c].dy : 0);
|
||||
d.setScale(1).setAlpha(1);
|
||||
}
|
||||
}
|
||||
|
||||
setRotations(rots) {
|
||||
if (!this.board) return;
|
||||
for (let r = 0; r < this.n; r++) for (let c = 0; c < this.n; c++) this.dice[r][c]._face.angle = rots ? rots[r][c] : 0;
|
||||
}
|
||||
|
||||
setBlank() {
|
||||
this.board = null;
|
||||
for (let r = 0; r < this.n; r++) for (let c = 0; c < this.n; c++) this.setFace(r, c, '');
|
||||
this.setPath([]);
|
||||
}
|
||||
|
||||
showLid(on) { this.lid.setVisible(on).setAlpha(on ? 1 : 0).setScale(1).setY(0); }
|
||||
|
||||
setCovered(on) {
|
||||
this.cover.setVisible(on);
|
||||
for (const row of this.dice) for (const d of row) d.setVisible(!on);
|
||||
this.lineGfx.setVisible(!on);
|
||||
}
|
||||
|
||||
// ── shake & settle ──────────────────────────────────────────────────────────
|
||||
// Resolves once the dice are settled and the lid is off.
|
||||
shake(board, rots, tilts) {
|
||||
const scene = this.scene;
|
||||
return new Promise((resolve) => {
|
||||
this.setPath([]);
|
||||
const lid = this.lid;
|
||||
lid.setVisible(true).setAlpha(0).setScale(1.12).setY(-30);
|
||||
scene.tweens.add({ targets: lid, alpha: 1, scale: 1, y: 0, duration: 260, ease: 'Quad.Out' });
|
||||
playSound(scene, SFX.DICE_ROLL);
|
||||
|
||||
const letters = 'AEIOUBCDFGHKLMNPRSTWY';
|
||||
const rand = () => letters[Math.floor(Math.random() * letters.length)];
|
||||
const all = this.dice.flat();
|
||||
// tumble: dice jitter, spin and blur through random letters
|
||||
const tumble = scene.time.addEvent({
|
||||
delay: 55, repeat: 20, callback: () => {
|
||||
for (const d of all) {
|
||||
d._letter.setText(rand()).setFontSize(Math.round(this.g.cube * 0.5));
|
||||
d._under.clear();
|
||||
d._face.angle = Math.floor(Math.random() * 4) * 90;
|
||||
d.x = d._home.x + Phaser.Math.Between(-12, 12);
|
||||
d.y = d._home.y + Phaser.Math.Between(-12, 12);
|
||||
d.angle = Phaser.Math.Between(-25, 25);
|
||||
d.setAlpha(0.82);
|
||||
}
|
||||
},
|
||||
});
|
||||
// tray rattle + camera shake
|
||||
scene.tweens.add({ targets: this.root, x: TRAY_C.x + 7, duration: 45, yoyo: true, repeat: 11, ease: 'Sine.InOut' });
|
||||
scene.tweens.add({ targets: this.root, y: TRAY_C.y - 5, duration: 60, yoyo: true, repeat: 8, ease: 'Sine.InOut' });
|
||||
scene.cameras.main.shake(900, 0.0035);
|
||||
playSoundEx(scene, SFX.DICE_ROLL, { rate: 0.85, volume: 0.8, delay: 0.35 });
|
||||
|
||||
scene.time.delayedCall(1180, () => {
|
||||
tumble.remove();
|
||||
this.root.setPosition(TRAY_C.x, TRAY_C.y);
|
||||
this.board = board;
|
||||
let i = 0;
|
||||
for (let r = 0; r < this.n; r++) for (let c = 0; c < this.n; c++) {
|
||||
const d = this.dice[r][c];
|
||||
this.setFace(r, c, board[r][c], rots[r][c]);
|
||||
d.setAlpha(1);
|
||||
const t = tilts[r][c];
|
||||
scene.tweens.add({
|
||||
targets: d, x: d._home.x + t.dx, y: d._home.y + t.dy, angle: t.a,
|
||||
duration: 240 + (i++ % 5) * 30, ease: 'Back.Out',
|
||||
});
|
||||
}
|
||||
playSound(scene, SFX.PIECE_CLICK);
|
||||
scene.time.delayedCall(320, () => {
|
||||
scene.tweens.add({
|
||||
targets: lid, alpha: 0, y: -60, scale: 1.08, duration: 380, ease: 'Quad.In',
|
||||
onComplete: () => { lid.setVisible(false); resolve(); },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ── selection drawing ───────────────────────────────────────────────────────
|
||||
setPath(path, state = 'ok') {
|
||||
this.path = path;
|
||||
const sel = new Set(path.map(([r, c]) => r * 8 + c));
|
||||
for (let r = 0; r < this.n; r++) for (let c = 0; c < this.n; c++) {
|
||||
const d = this.dice[r][c];
|
||||
const on = sel.has(r * 8 + c);
|
||||
d._glow.setVisible(on);
|
||||
d._glow.setTint(state === 'bad' ? 0xff7a5a : state === 'hint' ? 0x9fdcff : 0xffffff);
|
||||
d._body.setTint(on ? (state === 'bad' ? 0xffd8cc : 0xfff0c8) : 0xffffff);
|
||||
d.setScale(on ? 0.97 : 1);
|
||||
}
|
||||
this.drawLine(path, state);
|
||||
}
|
||||
|
||||
drawLine(path, state = 'ok', g = this.lineGfx) {
|
||||
g.clear();
|
||||
if (!path.length) return;
|
||||
const col = state === 'bad' ? LINE_BAD : state === 'hint' ? LINE_HINT : LINE_OK;
|
||||
const pts = path.map(([r, c]) => { const d = this.dice[r][c]; return { x: d.x - 5, y: d.y - 5 }; });
|
||||
// glow underlay + core
|
||||
for (const [w, a] of [[26, 0.16], [16, 0.32], [8, 0.9]]) {
|
||||
g.lineStyle(w, col, a);
|
||||
for (let i = 1; i < pts.length; i++) g.lineBetween(pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y);
|
||||
}
|
||||
pts.forEach((p, i) => {
|
||||
const last = i === pts.length - 1;
|
||||
g.fillStyle(col, 0.3).fillCircle(p.x, p.y, last ? 22 : 15);
|
||||
g.fillStyle(last ? 0xffffff : col, 1).fillCircle(p.x, p.y, last ? 11 : 8);
|
||||
});
|
||||
}
|
||||
|
||||
popPath(path) {
|
||||
path.forEach(([r, c], i) => {
|
||||
const d = this.dice[r][c];
|
||||
this.scene.tweens.add({
|
||||
targets: d, scale: { from: 1, to: 1.12 }, duration: 110, delay: i * 45, yoyo: true, ease: 'Quad.Out',
|
||||
});
|
||||
this.scene.time.delayedCall(i * 45, () => this.sparkAt(d.x, d.y));
|
||||
});
|
||||
}
|
||||
|
||||
sparkAt(x, y) {
|
||||
const s = this.scene.add.image(TRAY_C.x + x, TRAY_C.y + y, 'boggle-spark').setDepth(this.root.depth + 2).setBlendMode('ADD');
|
||||
this.scene.tweens.add({ targets: s, scale: { from: 1.6, to: 3.4 }, alpha: { from: 1, to: 0 }, duration: 380, onComplete: () => s.destroy() });
|
||||
}
|
||||
|
||||
// Animated trace (board review). Returns a cancel function.
|
||||
playPath(path, state = 'hint') {
|
||||
this.stopPlay?.();
|
||||
let i = 0, alive = true;
|
||||
this.setPath([], state);
|
||||
const step = () => {
|
||||
if (!alive) return;
|
||||
i++;
|
||||
this.setPath(path.slice(0, i), state);
|
||||
playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.5, rate: 1 + i * 0.05 });
|
||||
if (i < path.length) ev = this.scene.time.delayedCall(170, step);
|
||||
};
|
||||
let ev = this.scene.time.delayedCall(60, step);
|
||||
this.stopPlay = () => { alive = false; ev?.remove(); this.stopPlay = null; };
|
||||
return this.stopPlay;
|
||||
}
|
||||
|
||||
// brief highlight of a few dice (hints)
|
||||
flashCells(cells, ms = 1600) {
|
||||
this.setPath(cells, 'hint');
|
||||
this.scene.time.delayedCall(ms, () => { if (this.path === cells) this.setPath([]); });
|
||||
}
|
||||
|
||||
// ── pointer gestures ────────────────────────────────────────────────────────
|
||||
cellAt(p, inner = 0.5) {
|
||||
const lx = p.worldX - TRAY_C.x, ly = p.worldY - TRAY_C.y;
|
||||
const { cube, gap, span, n } = this.g;
|
||||
const step = cube + gap;
|
||||
const c = Math.floor((lx + span / 2 + gap / 2) / step), r = Math.floor((ly + span / 2 + gap / 2) / step);
|
||||
if (r < 0 || c < 0 || r >= n || c >= n) return null;
|
||||
const ctr = this.g.local(r, c);
|
||||
const dx = lx - ctr.x, dy = ly - ctr.y;
|
||||
if (inner < 0.5) { if (Math.hypot(dx, dy) > cube * inner) return null; }
|
||||
else if (Math.abs(dx) > step / 2 || Math.abs(dy) > step / 2) return null;
|
||||
return [r, c];
|
||||
}
|
||||
|
||||
pointerDown(p) {
|
||||
if (!this.enabled) return;
|
||||
const cell = this.cellAt(p);
|
||||
if (!cell) return;
|
||||
const path = this.cb.getPath?.() ?? [];
|
||||
const idx = path.findIndex(([r, c]) => r === cell[0] && c === cell[1]);
|
||||
let next;
|
||||
const g = { moved: false, wasLast: false };
|
||||
if (!path.length) next = [cell];
|
||||
else if (idx === path.length - 1) { next = path; g.wasLast = true; }
|
||||
else if (idx >= 0) next = path.slice(0, idx + 1);
|
||||
else if (areAdjacent(path[path.length - 1], cell)) next = [...path, cell];
|
||||
else next = [cell];
|
||||
this.gesture = g;
|
||||
if (next !== path) { this.cb.onPath?.(next); playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.6, rate: 1 + next.length * 0.04 }); }
|
||||
}
|
||||
|
||||
pointerMove(p) {
|
||||
if (!this.enabled || !this.gesture || !p.isDown) return;
|
||||
const cell = this.cellAt(p, 0.38);
|
||||
if (!cell) return;
|
||||
const path = this.cb.getPath?.() ?? [];
|
||||
if (!path.length) return;
|
||||
const last = path[path.length - 1];
|
||||
if (last[0] === cell[0] && last[1] === cell[1]) return;
|
||||
let next = null;
|
||||
const prev = path[path.length - 2];
|
||||
if (prev && prev[0] === cell[0] && prev[1] === cell[1]) next = path.slice(0, -1);
|
||||
else if (!path.some(([r, c]) => r === cell[0] && c === cell[1]) && areAdjacent(last, cell)) next = [...path, cell];
|
||||
if (!next) return;
|
||||
this.gesture.moved = true;
|
||||
this.gesture.wasLast = false;
|
||||
this.cb.onPath?.(next);
|
||||
playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.6, rate: 1 + next.length * 0.04 });
|
||||
}
|
||||
|
||||
pointerUp() {
|
||||
const g = this.gesture;
|
||||
this.gesture = null;
|
||||
if (!g || !this.enabled) return;
|
||||
if (g.moved) this.cb.onRelease?.();
|
||||
else if (g.wasLast) this.cb.onTapLast?.();
|
||||
}
|
||||
}
|
||||
|
||||
// Per-die rotations (multiples of 90°) and small resting tilts/offsets.
|
||||
export function randomRests(n, upright = false, rng = Math.random) {
|
||||
const rots = [], tilts = [];
|
||||
for (let r = 0; r < n; r++) {
|
||||
rots.push([]); tilts.push([]);
|
||||
for (let c = 0; c < n; c++) {
|
||||
rots[r].push(upright ? 0 : Math.floor(rng() * 4) * 90);
|
||||
tilts[r].push({ a: (rng() - 0.5) * 7, dx: (rng() - 0.5) * 6, dy: (rng() - 0.5) * 6 });
|
||||
}
|
||||
}
|
||||
return { rots, tilts };
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
# Come On In — It's Boggle Night!
|
||||
|
||||
*By Aunt Doreen — hostess, fondue champion, keeper of the sand timer*
|
||||
|
||||
---
|
||||
|
||||
Well, hello there, sugar! Shoes off, that shag carpet was just raked. Grab a cream soda, take a pillow, and pull up to the coffee table. Every Friday night in this den we turn the lamp down, put the hi-fi on low, and play **Boggle** until somebody storms off over whether "ETUI" is a word. (It is. Look it up. I did.)
|
||||
|
||||
Let me show you how my game night works.
|
||||
|
||||
## The Goal
|
||||
|
||||
A tray of letter dice gets shaken up under a clear dome. When the lid comes off, you've got until the sand runs out to find as many words as you can hidden in the grid. Longer words are worth more. After the timer, everyone compares sheets, and any word that **two or more of us** found gets crossed off everybody's list. So the trick isn't just finding words — it's finding the words nobody else spots.
|
||||
|
||||
## Shake the Tray
|
||||
|
||||
Every round starts with the lid on and the dice in a jumble. Press **Shake the Tray** (or the **Space** bar) and give it a good rattle. The dice tumble, settle into their little pockets, the lid lifts off, and I flip the sand timer. Go!
|
||||
|
||||
The letters sit nice and upright so they're easy to read. If you want it like the real thing — letters facing every which way as the dice land — open the **Menu** and turn **Upright letters** off. M, W, N and Z have a little line under them so you can tell an M from a W upside down.
|
||||
|
||||
## Making a Word
|
||||
|
||||
A word is a chain of dice where each letter **touches the one before it** — up, down, sideways, or corner-to-corner. Two rules:
|
||||
|
||||
- You **can't use the same die twice** in one word.
|
||||
- Words need at least **3 letters** (4 on the Big board, or if you choose that rule).
|
||||
|
||||
The Q die always reads **Qu**, and it counts as two letters. So QUEST is five letters long and you only trace four dice. Isn't that a treat?
|
||||
|
||||
### Three ways to spell it out
|
||||
|
||||
1. **Drag** across the dice. When you let go, your word is submitted. Drag back onto the die you just left to take it back.
|
||||
2. **Click** dice one at a time, then press **Submit**. Click the last die again to undo it, click an earlier die to back up to it, or click a die that isn't touching to start a fresh word.
|
||||
3. **Type it!** Just start typing on the keyboard. The game finds the word's path on the board and lights it up — if the letters aren't connected, the word turns red. Press **Enter** to submit, **Backspace** to fix a letter, **Esc** to clear. Typing **Q** gives you **Qu** automatically.
|
||||
|
||||
Good words get written on your yellow legal pad in ballpoint. Try one you already have and the pad wiggles it at you so you know.
|
||||
|
||||
## Scoring
|
||||
|
||||
| Word length | Points |
|
||||
|---|---|
|
||||
| 3 or 4 letters | 1 |
|
||||
| 5 letters | 2 |
|
||||
| 6 letters | 3 |
|
||||
| 7 letters | 5 |
|
||||
| 8 or more | 11 |
|
||||
|
||||
That's not a typo, honey — **eight letters is eleven points**. One big word can win a whole round.
|
||||
|
||||
When the sand runs out — *Pencils down!* — the sheets get read out loud, longest words first. If two players both wrote a word, it's struck off **every** sheet at the same moment and nobody scores it. You can turn that off in setup ("Shared words: Still score") if you'd rather be friendly about it.
|
||||
|
||||
## Game Night (with rivals)
|
||||
|
||||
Pick one to three opponents before you sit down. You'll choose:
|
||||
|
||||
- **Round length** — 1, 2, 3 or 4 minutes
|
||||
- **Rounds** — 1, 3 or 5 (scores add up across the match)
|
||||
- **Board** — Classic 4 × 4, or the Big 5 × 5 with a 4-letter minimum
|
||||
- **Shortest word** — 3 or 4 letters
|
||||
- **Shared words** — cancel out, or still score
|
||||
|
||||
Watch your rivals' place cards: the little pencil scribbles every time they write a word, and the big number tells you how many they've got. They won't show you their words until scoring, of course — I raised them right. Easier opponents stick to everyday words; the sharp ones know the odd dictionary words too, and they write faster.
|
||||
|
||||
Your match saves itself between rounds, so if the phone rings you can come back later and pick up where you left off.
|
||||
|
||||
## Playing Solo
|
||||
|
||||
Choose no opponents and you get two ways to play:
|
||||
|
||||
- **Practice** — your pick of timer (including **Untimed**), board size and word length. The goal is to find a quarter of the board's common words. With **Hints** on, the card on the left counts how many common words are still hiding at each length, and the **Hint** button lights up the first two dice of a word you've missed.
|
||||
- **Daily Board** — the same board for everyone today. Classic rules, three minutes, one try. Come back each day to keep your streak going!
|
||||
|
||||
## Board Review
|
||||
|
||||
After every round, press **Board Review** to see every word that was on the board, grouped by length. Common words come first; the weird dictionary ones are tucked under **Obscure** so they don't make you feel bad. Words you found have a check, rival finds show their initial, and clicking any word traces it right there on the dice. That's where you learn to see "STRIPE" hiding next to "PRIEST."
|
||||
|
||||
## Doreen's Tips
|
||||
|
||||
- **Hunt the endings.** Found RATE? Look for RATES, RATED, RATER — and TEAR, made from the same letters.
|
||||
- **Find S, E, D and R** first. They turn one word into three.
|
||||
- **Go long when you can.** One 7-letter word beats five little ones.
|
||||
- **Short words get cancelled.** Everybody spots CAT. Not everybody spots CATER.
|
||||
- **Watch the clock.** In the last ten seconds the timer ticks and the lamp starts glowing. Get your last words down!
|
||||
|
||||
## Handy Keys
|
||||
|
||||
- **Space** — shake the tray
|
||||
- **Letters** — type a word
|
||||
- **Enter** — submit
|
||||
- **Backspace** — remove a letter
|
||||
- **Esc** — clear the word (press again to pause — the board hides while you're paused, no peeking!)
|
||||
|
||||
Now scoot over and let's see what you've got. And keep your elbows off my coffee table — that's genuine teak.
|
||||
|
|
@ -1,19 +1,48 @@
|
|||
// Boggle engine: dictionary trie, dice rolling, and board solving.
|
||||
// Pure logic — no Express. Initialized once at server start from the ENABLE list.
|
||||
// Boggle engine: dictionary trie, seeded dice rolling, board solving and word
|
||||
// familiarity tiers. Pure logic — no Phaser. Initialized once from the ENABLE list
|
||||
// (initBoggleDictionary) and, when available, the frequency list
|
||||
// (initBoggleCommonWords).
|
||||
//
|
||||
// generateBoard({ size, seed }) → { board, size, seed, solutions:[{ word, path, tier }] }
|
||||
// rollBoard(size, rng) → size×size grid of face tokens ('Qu' for the Q face)
|
||||
// solveBoard(grid) → [{ word, path, tier }]
|
||||
// wordTier(word) → 1 everyday · 2 familiar · 3 obscure (ENABLE only)
|
||||
|
||||
// Standard 16-die Boggle set. The Q die face is treated as the token "Qu".
|
||||
const DICE = [
|
||||
// Classic 16-die set (4×4). The Q face is treated as the token "Qu".
|
||||
export const DICE_4 = [
|
||||
'AAEEGN', 'ABBJOO', 'ACHOPS', 'AFFKPS',
|
||||
'AOOTTW', 'CIMOTU', 'DEILRX', 'DELRVY',
|
||||
'DISTTY', 'EEGHNW', 'EEINSU', 'EHRTVW',
|
||||
'EIOSST', 'ELRTTY', 'HIMNQU', 'HLNNRZ',
|
||||
];
|
||||
|
||||
const MIN_LEN = 3; // minimum scoring word length
|
||||
// 25-die "Big" set (5×5).
|
||||
export const DICE_5 = [
|
||||
'AAAFRS', 'AAEEEE', 'AAFIRS', 'ADENNN', 'AEEEEM',
|
||||
'AEEGMU', 'AEGMNN', 'AFIRSY', 'BJKQXZ', 'CCENST',
|
||||
'CEIILT', 'CEILPT', 'CEIPST', 'DDHNOT', 'DHHLOR',
|
||||
'DHLNOR', 'DHLNOR', 'EIIITT', 'EMOTTT', 'ENSSSU',
|
||||
'FIPRSY', 'GORRVW', 'IPRRRY', 'NOOTUW', 'OOOTTU',
|
||||
];
|
||||
|
||||
export const DICE = DICE_4; // back-compat
|
||||
|
||||
const MIN_LEN = 3; // the shortest word the solver reports (rules may raise it)
|
||||
|
||||
// ── Seeded RNG ──────────────────────────────────────────────────────────────────
|
||||
export function makeRng(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;
|
||||
};
|
||||
}
|
||||
|
||||
// ── Trie ──────────────────────────────────────────────────────────────────────
|
||||
// Node: { word: boolean, kids: Map<char, node> }. Used for fast prefix pruning
|
||||
// during the board DFS while keeping memory far below a full prefix Set.
|
||||
// Node: { word: boolean, kids: Map<char, node> }.
|
||||
|
||||
let root = null;
|
||||
|
||||
|
|
@ -23,9 +52,10 @@ function makeNode() {
|
|||
|
||||
export function initBoggleDictionary(words) {
|
||||
root = makeNode();
|
||||
tiers = new Map();
|
||||
for (const raw of words) {
|
||||
const w = String(raw).toUpperCase();
|
||||
if (w.length < MIN_LEN || w.length > 16 || !/^[A-Z]+$/.test(w)) continue;
|
||||
if (w.length < MIN_LEN || w.length > 25 || !/^[A-Z]+$/.test(w)) continue;
|
||||
let node = root;
|
||||
for (const ch of w) {
|
||||
let next = node.kids.get(ch);
|
||||
|
|
@ -37,26 +67,117 @@ export function initBoggleDictionary(words) {
|
|||
return root;
|
||||
}
|
||||
|
||||
export function dictionaryReady() { return root !== null; }
|
||||
|
||||
export function isWord(word) {
|
||||
if (!root) return false;
|
||||
let n = root;
|
||||
for (const ch of String(word).toUpperCase()) {
|
||||
n = n.kids.get(ch);
|
||||
if (!n) return false;
|
||||
}
|
||||
return n.word;
|
||||
}
|
||||
|
||||
// ── Familiarity tiers ─────────────────────────────────────────────────────────
|
||||
// common.txt is frequency-ordered. The first TIER1_SIZE entries (and their
|
||||
// inflections) are "everyday" words, the rest "familiar"; anything else in
|
||||
// ENABLE is "obscure". Without common.txt every word is tier 2.
|
||||
|
||||
const TIER1_SIZE = 5000;
|
||||
let tiers = new Map(); // word → 1 | 2
|
||||
let tiersLoaded = false;
|
||||
|
||||
// The inflections a casual player knows once they know the stem.
|
||||
function inflections(w) {
|
||||
const out = [w + 'S', w + 'D', w + 'ED', w + 'ER', w + 'ERS', w + 'EST', w + 'LY', w + 'ING', w + 'INGS'];
|
||||
if (/(S|X|Z|CH|SH|O)$/.test(w)) out.push(w + 'ES');
|
||||
if (w.endsWith('E')) out.push(w.slice(0, -1) + 'ING', w.slice(0, -1) + 'INGS', w + 'R', w + 'RS', w + 'ST');
|
||||
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');
|
||||
// doubled final consonant (STOP → STOPPED, RUN → RUNNING)
|
||||
if (/[^AEIOU][AEIOU][BDGLMNPRT]$/.test(w)) {
|
||||
const d = w + w[w.length - 1];
|
||||
out.push(d + 'ED', d + 'ING', d + 'ER', d + 'ERS');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// common.txt is crossword-tuned and keeps very few short words, so the everyday
|
||||
// three-letter words a casual player spots are listed here (all in ENABLE).
|
||||
const EVERYDAY_THREES = `ACE ACT ADD ADO AGE AGO AID AIL AIM AIR ALE ALL AND ANT ANY APE APT ARC ARE ARK ARM
|
||||
ART ASH ASK ATE AWE AWL AXE BAD BAG BAN BAR BAT BAY BED BEE BEG BET BIB BID BIG BIN BIT BOA BOB BOG BOO BOW
|
||||
BOX BOY BRA BUD BUG BUM BUN BUS BUT BUY BYE CAB CAN CAP CAR CAT COB COD COG CON COO COP COT COW COY CRY CUB
|
||||
CUD CUE CUP CUR CUT DAB DAD DAM DAY DEN DEW DID DIE DIG DIM DIN DIP DOE DOG DON DOT DRY DUB DUD DUE DUG DYE
|
||||
EAR EAT EBB EEL EGG EGO ELF ELK ELM EMU END ERA ERR EVE EWE EYE FAD FAN FAR FAT FAX FED FEE FEW FIB FIG FIN
|
||||
FIR FIT FIX FLU FLY FOE FOG FOR FOX FRY FUN FUR GAB GAG GAL GAP GAS GEL GEM GET GIG GIN GNU GOB GOD GOT GUM
|
||||
GUN GUT GUY GYM HAD HAM HAS HAT HAY HEM HEN HER HEW HEY HID HIM HIP HIS HIT HOB HOE HOG HOP HOT HOW HUB HUE
|
||||
HUG HUM HUT ICE ICY ILL IMP INK INN ION IRE IRK ITS IVY JAB JAM JAR JAW JAY JET JIG JOB JOG JOT JOY JUG KEG
|
||||
KEN KEY KID KIN KIT LAB LAD LAG LAP LAW LAX LAY LED LEG LET LID LIE LIP LIT LOB LOG LOT LOW MAD MAN MAP MAT
|
||||
MAY MEN MET MID MIX MOB MOM MOP MOW MUD MUG MUM NAB NAG NAP NET NEW NIB NIL NIP NIT NOD NOR NOT NOW NUN NUT
|
||||
OAF OAK OAR OAT ODD ODE OFF OFT OIL OLD ONE OPT ORB ORE OUR OUT OVA OWE OWL OWN PAD PAL PAN PAT PAW PAY PEA
|
||||
PEG PEN PEP PER PET PEW PIE PIG PIN PIT PLY POD POP POT POW PRO PRY PUB PUG PUN PUP PUS PUT RAG RAM RAN RAP
|
||||
RAT RAW RAY RED REF RIB RID RIG RIM RIP ROB ROD ROE ROT ROW RUB RUG RUM RUN RUT RYE SAC SAD SAG SAP SAT SAW
|
||||
SAY SEA SEE SET SEW SHE SHY SIN SIP SIR SIS SIT SIX SKI SKY SLY SOB SOD SON SOP SOT SOW SOY SPA SPY STY SUB
|
||||
SUE SUM SUN SUP TAB TAD TAG TAN TAP TAR TAT TAX TEA TEE TEN THE THY TIC TIE TIN TIP TOE TOG TON TOO TOP TOT
|
||||
TOW TOY TRY TUB TUG TUX TWO URN USE VAN VAT VET VIA VIE VOW WAD WAG WAR WAS WAX WAY WEB WED WEE WET WHO WHY
|
||||
WIG WIN WIT WOE WOK WON WOO WOW YAK YAM YAP YAW YEA YES YET YEW YOU ZAP ZIG ZIP ZIT ZOO`;
|
||||
|
||||
// words: common.txt (frequency-ordered). curatedRaw: optional
|
||||
// spellingbee-answers.txt ("WORD<TAB>core|familiar") — a hand-checked list that
|
||||
// fills in everyday words common.txt's crossword cutoffs left out.
|
||||
export function initBoggleCommonWords(words, curatedRaw = null) {
|
||||
if (!root) return { common: 0 };
|
||||
tiers = new Map();
|
||||
const put = (x, t) => { if (isWord(x) && (tiers.get(x) ?? 9) > t) tiers.set(x, t); };
|
||||
const withInflections = (w, t) => { put(w, t); for (const f of inflections(w)) put(f, t); };
|
||||
for (const w of EVERYDAY_THREES.split(/\s+/)) if (w) withInflections(w, 1);
|
||||
if (curatedRaw) {
|
||||
for (const line of String(curatedRaw).split('\n')) {
|
||||
const [w, kind] = line.trim().toUpperCase().split(/\s+/);
|
||||
if (w && /^[A-Z]+$/.test(w)) withInflections(w, kind === 'CORE' ? 1 : 2);
|
||||
}
|
||||
}
|
||||
const ranked = [];
|
||||
const seen = new Set();
|
||||
for (const raw of words) {
|
||||
const w = String(raw).trim().toUpperCase();
|
||||
if (!/^[A-Z]+$/.test(w) || seen.has(w)) continue;
|
||||
seen.add(w);
|
||||
ranked.push(w);
|
||||
}
|
||||
ranked.forEach((w, i) => withInflections(w, i < TIER1_SIZE ? 1 : 2));
|
||||
tiersLoaded = true;
|
||||
return { common: tiers.size };
|
||||
}
|
||||
|
||||
export function wordTier(word) {
|
||||
const w = String(word).toUpperCase();
|
||||
if (!tiersLoaded) return 2;
|
||||
return tiers.get(w) ?? 3;
|
||||
}
|
||||
|
||||
// ── Board rolling ───────────────────────────────────────────────────────────────
|
||||
|
||||
function shuffle(arr) {
|
||||
function shuffle(arr, rng) {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
const j = Math.floor(rng() * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
// Returns a 4×4 grid (array of 4 rows, each 4 face tokens). Each cell is a single
|
||||
// uppercase letter, except the Q die which yields the token "Qu".
|
||||
export function rollBoard() {
|
||||
const dice = shuffle([...DICE]);
|
||||
// Returns a size×size grid (array of rows of face tokens). Each cell is a single
|
||||
// uppercase letter, except the Q face which yields the token "Qu".
|
||||
export function rollBoard(size = 4, rng = Math.random) {
|
||||
const set = size === 5 ? DICE_5 : DICE_4;
|
||||
const n = size === 5 ? 5 : 4;
|
||||
const dice = shuffle([...set], rng);
|
||||
const faces = dice.map((die) => {
|
||||
const ch = die[Math.floor(Math.random() * die.length)];
|
||||
const ch = die[Math.floor(rng() * die.length)];
|
||||
return ch === 'Q' ? 'Qu' : ch;
|
||||
});
|
||||
const grid = [];
|
||||
for (let r = 0; r < 4; r++) grid.push(faces.slice(r * 4, r * 4 + 4));
|
||||
for (let r = 0; r < n; r++) grid.push(faces.slice(r * n, r * n + n));
|
||||
return grid;
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +190,6 @@ const NEIGHBORS = [
|
|||
];
|
||||
|
||||
// Walk a trie down every character of a face token (handles the two-letter "Qu").
|
||||
// Returns the resulting node, or null if the prefix leaves the trie.
|
||||
function stepNode(node, token) {
|
||||
let n = node;
|
||||
for (const ch of token.toUpperCase()) {
|
||||
|
|
@ -79,39 +199,63 @@ function stepNode(node, token) {
|
|||
return n;
|
||||
}
|
||||
|
||||
// Returns every valid word (length >= 3) found on the board, each with one
|
||||
// representative path: [{ word, path: [[r,c], ...] }]. De-duped by word.
|
||||
// Every valid word (length >= 3) on the board, each with one representative path
|
||||
// and its familiarity tier: [{ word, path: [[r,c], ...], tier }]. De-duped by word.
|
||||
export function solveBoard(grid) {
|
||||
if (!root) return [];
|
||||
const size = grid.length;
|
||||
const found = new Map(); // word -> path
|
||||
const visited = Array.from({ length: size }, () => new Array(size).fill(false));
|
||||
const path = [];
|
||||
|
||||
const dfs = (r, c, node, word, path) => {
|
||||
const dfs = (r, c, node, word) => {
|
||||
const next = stepNode(node, grid[r][c]);
|
||||
if (!next) return;
|
||||
const nextWord = word + grid[r][c].toUpperCase();
|
||||
const nextPath = [...path, [r, c]];
|
||||
path.push([r, c]);
|
||||
|
||||
if (next.word && nextWord.length >= MIN_LEN && !found.has(nextWord)) {
|
||||
found.set(nextWord, nextPath);
|
||||
found.set(nextWord, path.map((p) => [p[0], p[1]]));
|
||||
}
|
||||
|
||||
visited[r][c] = true;
|
||||
for (const [dr, dc] of NEIGHBORS) {
|
||||
const nr = r + dr, nc = c + dc;
|
||||
if (nr < 0 || nc < 0 || nr >= size || nc >= size) continue;
|
||||
if (visited[nr][nc]) continue;
|
||||
dfs(nr, nc, next, nextWord, nextPath);
|
||||
if (next.kids.size) {
|
||||
for (const [dr, dc] of NEIGHBORS) {
|
||||
const nr = r + dr, nc = c + dc;
|
||||
if (nr < 0 || nc < 0 || nr >= size || nc >= size) continue;
|
||||
if (visited[nr][nc]) continue;
|
||||
dfs(nr, nc, next, nextWord);
|
||||
}
|
||||
}
|
||||
visited[r][c] = false;
|
||||
path.pop();
|
||||
};
|
||||
|
||||
for (let r = 0; r < size; r++) {
|
||||
for (let c = 0; c < size; c++) {
|
||||
dfs(r, c, root, '', []);
|
||||
dfs(r, c, root, '');
|
||||
}
|
||||
}
|
||||
|
||||
return [...found.entries()].map(([word, path]) => ({ word, path }));
|
||||
return [...found.entries()].map(([word, p]) => ({ word, path: p, tier: wordTier(word) }));
|
||||
}
|
||||
|
||||
// ── Board generation ─────────────────────────────────────────────────────────────
|
||||
// Rerolls (deterministically, from the same seeded stream) boards that are too
|
||||
// thin to be fun: fewer than MIN_GOOD everyday/familiar words of 3+ letters.
|
||||
const MIN_GOOD = { 4: 35, 5: 80 };
|
||||
|
||||
export function generateBoard({ size = 4, seed = null } = {}) {
|
||||
const n = size === 5 ? 5 : 4;
|
||||
const s = seed == null ? (Math.floor(Math.random() * 0xffffffff) >>> 0) : (seed >>> 0);
|
||||
const rng = makeRng(s);
|
||||
let best = null;
|
||||
for (let attempt = 0; attempt < 24; attempt++) {
|
||||
const board = rollBoard(n, rng);
|
||||
const solutions = solveBoard(board);
|
||||
const good = solutions.filter((x) => x.tier <= 2).length;
|
||||
if (!best || good > best.good) best = { board, solutions, good };
|
||||
if (good >= MIN_GOOD[n]) break;
|
||||
}
|
||||
return { board: best.board, size: n, seed: s, solutions: best.solutions };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import {
|
|||
} from './wordSearchEngine.js';
|
||||
import { generatePuzzle as sudokuGenerate } from './sudokuEngine.js';
|
||||
import { generatePuzzle as tectonicGenerate } from './tectonicEngine.js';
|
||||
import { initBoggleDictionary, rollBoard, solveBoard } from './boggleEngine.js';
|
||||
import { initBoggleDictionary, initBoggleCommonWords, generateBoard as boggleGenerate } from './boggleEngine.js';
|
||||
import { initSpellingBeeDictionary, generatePuzzle as spellingBeeGenerate } from './spellingBeeEngine.js';
|
||||
import { initMiniCrosswordPuzzles, getPuzzle as miniCrosswordGet } from './miniCrosswordEngine.js';
|
||||
import {
|
||||
|
|
@ -185,6 +185,8 @@ function loadWordLists(raw, commonRaw, crosswordBank, beeAnswersRaw = null) {
|
|||
const common4 = commonWords.filter(w => /^[A-Z]{4}$/.test(w));
|
||||
ladderInitCommon(common3, common4);
|
||||
console.log(`[words] loaded Word Ladder common words (${common3.length} 3-letter, ${common4.length} 4-letter)`);
|
||||
const boggleCommon = initBoggleCommonWords(commonWords, beeAnswersRaw);
|
||||
console.log(`[words] tagged ${boggleCommon.common} Boggle everyday/familiar words`);
|
||||
const ghostCommon = commonWords.filter(w => w.length >= 4 && /^[A-Z]+$/.test(w));
|
||||
initGhostCommonWords(ghostCommon);
|
||||
console.log(`[words] loaded ${ghostCommon.length} Ghost common words for skill ≤3 AI targeting`);
|
||||
|
|
@ -256,13 +258,15 @@ router.post('/wordle/validate', (req, res) => {
|
|||
|
||||
// ── Boggle ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
// GET /api/words/boggle/start
|
||||
// Rolls a fresh 4×4 board and returns it with the full solution set (every valid
|
||||
// word and one representative path). The client validates player words and drives
|
||||
// the AI from this set — no per-word round trips needed.
|
||||
router.get('/boggle/start', (_req, res) => {
|
||||
const board = rollBoard();
|
||||
res.json({ board, solutions: solveBoard(board) });
|
||||
// GET /api/words/boggle/start[?size=4|5][&seed=uint32]
|
||||
// Rolls a board (deterministic when seeded — the Daily Board) and returns it with
|
||||
// the full solution set: every valid word, one representative path and its
|
||||
// familiarity tier (1 everyday · 2 familiar · 3 obscure). The client validates
|
||||
// player words and drives the AI from this set — no per-word round trips.
|
||||
router.get('/boggle/start', (req, res) => {
|
||||
const size = String(req.query?.size) === '5' ? 5 : 4;
|
||||
const seed = req.query?.seed != null && /^\d+$/.test(String(req.query.seed)) ? Number(req.query.seed) : null;
|
||||
res.json(boggleGenerate({ size, seed }));
|
||||
});
|
||||
|
||||
// ── Spelling Bee ────────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -0,0 +1,364 @@
|
|||
#!/usr/bin/env node
|
||||
// verifyBoggle.js — headless checks for Boggle:
|
||||
// • scoring table, min-length rule, duplicate cancelling on/off
|
||||
// • revealPlan: shown totals == committed round scores (the old overflow bug)
|
||||
// • adjacency / paths / findPath (Qu, preferring the current path) / typing
|
||||
// • engine: seeded determinism, 4×4 + 5×5 dice sets, solver vs an independent
|
||||
// prefix-set reference, every solution path valid and spelling its word
|
||||
// • familiarity tiers spot-checks
|
||||
// • review groups, summaries, hints, practice goal, daily streaks, saves
|
||||
// • AI: schedules valid, target word counts per skill, skill ladder (mirrored boards)
|
||||
// • screen layout: furniture on screen, no overlaps (0–3 rivals, both sizes)
|
||||
// Usage: node tools/verifyBoggle.js [--quick] [--ladder]
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import * as E from '../src/words/boggleEngine.js';
|
||||
import * as L from '../src/games/boggle/BoggleLogic.js';
|
||||
import { scheduleFinds, familyMap, stemOf } from '../src/games/boggle/BoggleAI.js';
|
||||
import * as Y from '../src/games/boggle/BoggleLayout.js';
|
||||
|
||||
const QUICK = process.argv.includes('--quick');
|
||||
const LADDER = process.argv.includes('--ladder');
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
let pass = 0, fail = 0;
|
||||
function ok(label, cond, detail = '') {
|
||||
if (cond) pass++;
|
||||
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
|
||||
}
|
||||
const section = (n) => console.log(`\n${n}`);
|
||||
|
||||
// ── dictionary ─────────────────────────────────────────────────────────────
|
||||
const t0 = Date.now();
|
||||
const read = (f) => fs.readFileSync(path.join(ROOT, 'data/wordlists', f), 'utf8');
|
||||
const enable = read('enable1.txt').split('\n').map((w) => w.trim().toUpperCase()).filter((w) => w.length >= 3 && w.length <= 16 && /^[A-Z]+$/.test(w));
|
||||
E.initBoggleDictionary(enable);
|
||||
E.initBoggleCommonWords(read('common.txt').split('\n'), read('spellingbee-answers.txt'));
|
||||
const DICT = new Set(enable);
|
||||
console.log(`dictionary: ${enable.length} words (${Date.now() - t0} ms)`);
|
||||
|
||||
// ── scoring ────────────────────────────────────────────────────────────────
|
||||
section('Scoring');
|
||||
{
|
||||
const T = [['CAT', 1], ['CATS', 1], ['CATER', 2], ['CATERS', 3], ['CRATERS', 5], ['SCATTERS', 11], ['QUEST', 2], ['QUESTION', 11]];
|
||||
for (const [w, p] of T) ok(`score ${w} = ${p}`, L.scoreWord(w) === p, String(L.scoreWord(w)));
|
||||
ok('2-letter scores 0', L.scoreWord('AT') === 0);
|
||||
ok('minLen 4: 3-letter scores 0', L.scoreWord('CAT', 4) === 0 && L.scoreWord('CATS', 4) === 1);
|
||||
const sheets = [{ found: ['CAT', 'CATER', 'DOG'] }, { found: ['cat', 'RATE'] }, { found: ['CATER', 'TOP', 'cat'] }];
|
||||
const on = L.resolveRound(sheets, { dupCancel: true });
|
||||
ok('dup cancel: p0 = DOG only', on[0].roundScore === 1, JSON.stringify(on[0]));
|
||||
ok('dup cancel: p1 = RATE', on[1].roundScore === 1);
|
||||
ok('dup cancel: p2 = TOP', on[2].roundScore === 1);
|
||||
ok('sharedWith lists the other finders', JSON.stringify(on[0].words.find((w) => w.word === 'CAT').sharedWith) === '[1,2]');
|
||||
ok('unique/shared counts', on[0].unique === 1 && on[0].shared === 2);
|
||||
const off = L.resolveRound(sheets, { dupCancel: false });
|
||||
ok('dup off: p0 = 1+2+1', off[0].roundScore === 4, String(off[0].roundScore));
|
||||
ok('dup off: nothing marked dup', off.every((r) => r.words.every((w) => !w.dup)));
|
||||
const min4 = L.resolveRound(sheets, { minLen: 4, dupCancel: false });
|
||||
ok('minLen 4 in resolveRound', min4[0].roundScore === 2, String(min4[0].roundScore));
|
||||
|
||||
// reveal plan totals == round scores, even for very long sheets
|
||||
const big = (n, tag) => Array.from({ length: n }, (_, i) => `${tag}${String.fromCharCode(65 + (i % 26))}${String.fromCharCode(65 + Math.floor(i / 26))}XYZ`.slice(0, 4 + (i % 6)));
|
||||
const sheets2 = [{ found: [...big(80, 'A'), 'SHARED', 'BOTH'] }, { found: [...big(45, 'B'), 'SHARED'] }, { found: ['BOTH', 'SHARED', ...big(5, 'C')] }];
|
||||
for (const dup of [true, false]) {
|
||||
const res = L.resolveRound(sheets2, { dupCancel: dup });
|
||||
const plan = L.revealPlan(res);
|
||||
const sums = res.map(() => 0);
|
||||
for (const st of plan.steps) for (const e of st.entries) sums[e.player] += e.score;
|
||||
ok(`revealPlan sums == roundScore (dup ${dup})`, sums.every((s, i) => s === res[i].roundScore), `${sums} vs ${res.map((r) => r.roundScore)}`);
|
||||
ok(`revealPlan rows == word counts (dup ${dup})`, plan.rows.every((r, i) => r === res[i].words.length));
|
||||
const shared = plan.steps.find((s) => s.word === 'SHARED');
|
||||
ok(`shared word revealed on one beat for all (dup ${dup})`, shared && shared.entries.length === 3);
|
||||
}
|
||||
ok('revealPlan longest first', (() => { const p = L.revealPlan(L.resolveRound(sheets)); return p.steps.every((s, i) => i === 0 || p.steps[i - 1].word.length >= s.word.length); })());
|
||||
}
|
||||
|
||||
// ── paths & typing ─────────────────────────────────────────────────────────
|
||||
section('Paths & typing');
|
||||
{
|
||||
ok('adjacent diag', L.areAdjacent([0, 0], [1, 1]));
|
||||
ok('not adjacent self', !L.areAdjacent([1, 1], [1, 1]));
|
||||
ok('not adjacent 2 away', !L.areAdjacent([0, 0], [0, 2]));
|
||||
ok('valid path', L.isValidPath([[0, 0], [0, 1], [1, 2]]));
|
||||
ok('invalid repeat', !L.isValidPath([[0, 0], [0, 1], [0, 0]]));
|
||||
ok('invalid jump', !L.isValidPath([[0, 0], [2, 2]]));
|
||||
const B = [
|
||||
['Qu', 'E', 'S', 'T'],
|
||||
['A', 'R', 'T', 'E'],
|
||||
['C', 'A', 'T', 'S'],
|
||||
['D', 'O', 'G', 'E'],
|
||||
];
|
||||
const q = L.findPath(B, 'QUEST');
|
||||
ok('findPath QUEST via Qu', q && L.pathWord(B, q) === 'QUEST' && q.length === 4, JSON.stringify(q));
|
||||
ok('findPath missing → null', L.findPath(B, 'ZEBRA') === null);
|
||||
ok('findPath half a Qu → null', L.findPath(B, 'Q') === null);
|
||||
ok('findPath empty → []', Array.isArray(L.findPath(B, '')) && L.findPath(B, '').length === 0);
|
||||
// two T's after CA: (2,2) and (1,2)… prefer the path we already have
|
||||
const first = L.findPath(B, 'CAT');
|
||||
const alt = [[2, 0], [2, 1], [1, 2]];
|
||||
ok('alt CAT path is valid', L.isValidPath(alt) && L.pathWord(B, alt) === 'CAT');
|
||||
const ext = L.findPath(B, 'CATE', alt);
|
||||
ok('prefers extending the current path', ext && ext[2][0] === 1 && ext[2][1] === 2, JSON.stringify(ext));
|
||||
const ext2 = L.findPath(B, 'CATS', first);
|
||||
ok('extends the first path too', ext2 && JSON.stringify(ext2.slice(0, 3)) === JSON.stringify(first), JSON.stringify([first, ext2]));
|
||||
let t = L.typeLetter('', 'q');
|
||||
ok('Q types QU', t.word === 'QU' && t.lastWasQ);
|
||||
t = L.typeLetter(t.word, 'u', t.lastWasQ);
|
||||
ok('U after Q swallowed', t.word === 'QU' && !t.lastWasQ);
|
||||
t = L.typeLetter(t.word, 'u', t.lastWasQ);
|
||||
ok('second U kept', t.word === 'QUU');
|
||||
ok('non-letter ignored', L.typeLetter('AB', '1').word === 'AB');
|
||||
ok('backspace removes QU as a unit', L.backspace('QU') === '' && L.backspace('SQU') === 'S' && L.backspace('CAT') === 'CA');
|
||||
const valid = new Set(['CAT', 'CATS']);
|
||||
ok('reject short', L.rejectReason('CA', { minLen: 3, found: new Set(), valid }) === 'short');
|
||||
ok('reject already', L.rejectReason('CAT', { minLen: 3, found: new Set(['CAT']), valid }) === 'already');
|
||||
ok('reject notWord', L.rejectReason('CTA', { minLen: 3, found: new Set(), valid }) === 'notWord');
|
||||
ok('reject off board', L.rejectReason('CAT', { minLen: 3, found: new Set(), valid, onBoard: false }) === 'notOnBoard');
|
||||
ok('accept', L.rejectReason('CATS', { minLen: 3, found: new Set(['CAT']), valid }) === null);
|
||||
}
|
||||
|
||||
// ── engine ─────────────────────────────────────────────────────────────────
|
||||
section('Engine');
|
||||
// Independent reference solver: prefix Set + plain DFS (no trie).
|
||||
const PREFIX = new Set();
|
||||
for (const w of enable) for (let i = 1; i <= w.length; i++) PREFIX.add(w.slice(0, i));
|
||||
function refSolve(grid) {
|
||||
const n = grid.length, out = new Set();
|
||||
const used = Array.from({ length: n }, () => new Array(n).fill(false));
|
||||
const go = (r, c, s) => {
|
||||
const w = s + grid[r][c].toUpperCase();
|
||||
if (!PREFIX.has(w)) return;
|
||||
if (w.length >= 3 && DICT.has(w)) out.add(w);
|
||||
used[r][c] = true;
|
||||
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
|
||||
const nr = r + dr, nc = c + dc;
|
||||
if ((dr || dc) && nr >= 0 && nc >= 0 && nr < n && nc < n && !used[nr][nc]) go(nr, nc, w);
|
||||
}
|
||||
used[r][c] = false;
|
||||
};
|
||||
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) go(r, c, '');
|
||||
return out;
|
||||
}
|
||||
// Can the board's faces be assigned to distinct dice of the set? (bipartite matching)
|
||||
function facesFromDice(board, dice) {
|
||||
const faces = board.flat().map((t) => (t === 'Qu' ? 'Q' : t));
|
||||
if (faces.length !== dice.length) return false;
|
||||
const match = new Array(dice.length).fill(-1);
|
||||
const tryFace = (f, seen) => {
|
||||
for (let d = 0; d < dice.length; d++) {
|
||||
if (seen[d] || !dice[d].includes(faces[f])) continue;
|
||||
seen[d] = true;
|
||||
if (match[d] < 0 || tryFace(match[d], seen)) { match[d] = f; return true; }
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return faces.every((_, f) => tryFace(f, new Array(dice.length).fill(false)));
|
||||
}
|
||||
{
|
||||
const N = QUICK ? 12 : 60;
|
||||
let mism = 0, bad = 0, dice = 0, sizes = 0, totalWords = { 4: 0, 5: 0 }, ms = 0;
|
||||
for (const size of [4, 5]) {
|
||||
for (let i = 0; i < N; i++) {
|
||||
const tt = Date.now();
|
||||
const g = E.generateBoard({ size, seed: 9000 + i });
|
||||
ms += Date.now() - tt;
|
||||
if (g.board.length !== size || g.board.some((row) => row.length !== size)) sizes++;
|
||||
if (!facesFromDice(g.board, size === 5 ? E.DICE_5 : E.DICE_4)) dice++;
|
||||
const ref = refSolve(g.board);
|
||||
const got = new Set(g.solutions.map((s) => s.word));
|
||||
if (ref.size !== got.size || [...ref].some((w) => !got.has(w))) mism++;
|
||||
for (const s of g.solutions) {
|
||||
if (!L.isValidPath(s.path) || L.pathWord(g.board, s.path) !== s.word || ![1, 2, 3].includes(s.tier)) bad++;
|
||||
}
|
||||
totalWords[size] += got.size;
|
||||
}
|
||||
}
|
||||
ok('boards are N×N', sizes === 0, String(sizes));
|
||||
ok('faces come from distinct dice of the right set', dice === 0, String(dice));
|
||||
ok('solver == reference word set', mism === 0, `${mism} boards differ`);
|
||||
ok('every solution path valid + spells its word + has a tier', bad === 0, String(bad));
|
||||
console.log(` avg words: 4×4 ${(totalWords[4] / N).toFixed(0)}, 5×5 ${(totalWords[5] / N).toFixed(0)} · ${(ms / (2 * N)).toFixed(1)} ms/board`);
|
||||
ok('generation under 25 ms/board', ms / (2 * N) < 25);
|
||||
const a = E.generateBoard({ size: 4, seed: 42 }), b = E.generateBoard({ size: 4, seed: 42 });
|
||||
ok('seeded boards are deterministic', JSON.stringify(a.board) === JSON.stringify(b.board) && a.seed === 42);
|
||||
const c = E.generateBoard({ size: 4, seed: 43 });
|
||||
ok('different seeds differ', JSON.stringify(a.board) !== JSON.stringify(c.board));
|
||||
ok('unseeded board reports its seed', Number.isInteger(E.generateBoard({ size: 4 }).seed));
|
||||
// quality floor
|
||||
let thin = 0;
|
||||
for (let i = 0; i < N; i++) { const g = E.generateBoard({ size: 4, seed: 500 + i }); if (g.solutions.filter((s) => s.tier <= 2).length < 20) thin++; }
|
||||
ok('few thin boards (<20 common words)', thin <= Math.ceil(N * 0.05), String(thin));
|
||||
// Qu boards
|
||||
let quSeen = 0, quBad = 0;
|
||||
for (let i = 0; i < 400 && quSeen < 6; i++) {
|
||||
const g = E.generateBoard({ size: 4, seed: 70000 + i });
|
||||
if (!g.board.flat().includes('Qu')) continue;
|
||||
quSeen++;
|
||||
for (const s of g.solutions.filter((x) => x.word.includes('Q'))) if (!s.word.includes('QU')) quBad++;
|
||||
for (const s of g.solutions) { const p = L.findPath(g.board, s.word); if (!p || L.pathWord(g.board, p) !== s.word) quBad++; }
|
||||
}
|
||||
ok('found Qu boards to test', quSeen > 0);
|
||||
ok('Qu words solve + findPath round-trips', quBad === 0, String(quBad));
|
||||
}
|
||||
|
||||
// ── tiers ──────────────────────────────────────────────────────────────────
|
||||
section('Tiers');
|
||||
{
|
||||
for (const w of ['BEE', 'TUB', 'CAT', 'HOUSE', 'TABLES', 'RATED', 'QUEST']) ok(`${w} is everyday`, E.wordTier(w) === 1, String(E.wordTier(w)));
|
||||
for (const w of ['ETUI', 'ZOEAE', 'AENEUS', 'FUB']) ok(`${w} is obscure`, E.wordTier(w) === 3, String(E.wordTier(w)));
|
||||
ok('non-word → tier 3', E.wordTier('XQZT') === 3);
|
||||
ok('isWord', E.isWord('cater') && !E.isWord('catx'));
|
||||
}
|
||||
|
||||
// ── review, summary, hints, goals ─────────────────────────────────────────
|
||||
section('Review & practice');
|
||||
{
|
||||
const g = E.generateBoard({ size: 4, seed: 7 });
|
||||
const mine = new Set(g.solutions.filter((s) => s.tier === 1).slice(0, 6).map((s) => s.word));
|
||||
const foundBy = new Map([...mine].map((w) => [w, [0]]));
|
||||
const groups = L.reviewGroups(g.solutions, foundBy, { minLen: 3 });
|
||||
const listed = groups.flatMap((gr) => gr.items.map((i) => i.word));
|
||||
ok('review lists every solution once', listed.length === g.solutions.length && new Set(listed).size === listed.length);
|
||||
ok('obscure group last and only tier 3', (() => { const o = groups.filter((x) => x.obscure); return o.length <= 1 && (!o.length || (groups[groups.length - 1].obscure && o[0].items.every((i) => i.tier === 3))); })());
|
||||
ok('common groups longest first', groups.filter((x) => !x.obscure).every((gr, i, arr) => i === 0 || arr[i - 1].len > gr.len));
|
||||
ok('found-by carried', groups.flatMap((x) => x.items).filter((i) => i.by.includes(0)).length === mine.size);
|
||||
const g4 = L.reviewGroups(g.solutions, new Map(), { minLen: 4 });
|
||||
ok('minLen 4 review drops 3-letter words', g4.flatMap((x) => x.items).every((i) => i.word.length >= 4));
|
||||
const sum = L.roundSummary(g.solutions, mine, { minLen: 3 });
|
||||
ok('summary counts', sum.total === g.solutions.length && sum.found === mine.size && sum.foundCommon === mine.size);
|
||||
ok('summary max score', sum.maxScore === L.sheetScore(g.solutions.map((s) => s.word)));
|
||||
ok('summary longest', sum.longest.length === Math.max(...g.solutions.map((s) => s.word.length)));
|
||||
const goal = L.practiceGoal(g.solutions, 3);
|
||||
const common = g.solutions.filter((s) => s.tier <= 2).length;
|
||||
ok('practice goal ≈ 25% of common', goal === Math.max(5, Math.round(common * 0.25)), `${goal} of ${common}`);
|
||||
const h = L.pickHint(g.solutions, mine, { minLen: 3, rng: () => 0.3 });
|
||||
ok('hint is an unfound common word', h && !mine.has(h.word) && E.wordTier(h.word) <= 2);
|
||||
ok('hint prefix is its first two dice', h && L.pathWord(g.board, h.path.slice(0, 2)) === h.prefix, h && `${h.prefix} ${h.word}`);
|
||||
const all = new Set(g.solutions.map((s) => s.word));
|
||||
ok('no hint when everything is found', L.pickHint(g.solutions, all, {}) === null);
|
||||
ok('counts by length', JSON.stringify(L.countsByLength(['CAT', 'DOGS', 'TABLES', 'ABCDEFGHIJ'])) === JSON.stringify({ 3: 1, 4: 1, 6: 1, 8: 1 }));
|
||||
}
|
||||
|
||||
// ── match state, saves, daily ─────────────────────────────────────────────
|
||||
section('Match, saves & daily');
|
||||
{
|
||||
const players = [{ id: 'player', name: 'You', isHuman: true }, { id: 'a', name: 'Ann', skill: 3 }, { id: 'b', name: 'Bob', skill: 5 }];
|
||||
const m = L.createMatch({ mode: 'match', rules: { rounds: 3, size: 5 }, players });
|
||||
ok('rules normalized', m.rules.size === 5 && m.rules.rounds === 3 && m.rules.timerMs === 180000);
|
||||
const res = L.resolveRound([{ found: ['CATER', 'DOG'] }, { found: ['DOG', 'TOP'] }, { found: [] }], m.rules);
|
||||
L.commitRound(m, res, [['CATER', 'DOG'], ['DOG', 'TOP'], []]);
|
||||
ok('commit adds totals', m.totals.player === res[0].roundScore && m.totals.a === res[1].roundScore);
|
||||
ok('history best words', m.history[0].best.player === 'CATER');
|
||||
ok('not over after 1 of 3', !L.isMatchOver(m));
|
||||
m.round = 2;
|
||||
const sig = JSON.stringify({ opp: ['a', 'b'] });
|
||||
const raw = L.serialiseSave(m, sig);
|
||||
const back = L.parseSave(raw, sig);
|
||||
ok('save round-trips', back && JSON.stringify(back.match) === JSON.stringify(m));
|
||||
ok('save rejects another table', L.parseSave(raw, JSON.stringify({ opp: ['a'] })) === null);
|
||||
ok('save rejects junk', L.parseSave('{oops', sig) === null && L.parseSave(null, sig) === null);
|
||||
L.commitRound(m, res, [['CATER', 'DOG'], ['DOG', 'TOP'], []]);
|
||||
L.commitRound(m, res, [['CATER', 'DOG'], ['DOG', 'TOP'], []]);
|
||||
ok('over after 3 of 3', L.isMatchOver(m));
|
||||
ok('finished match not resumable', L.parseSave(L.serialiseSave(m, sig), sig) === null);
|
||||
ok('match result', ['win', 'draw', 'loss'].includes(L.matchResult(m)));
|
||||
ok('standings sorted', (() => { const s = L.standings(m); return s.every((p, i) => i === 0 || m.totals[s[i - 1].id] >= m.totals[p.id]); })());
|
||||
const tie = L.createMatch({ mode: 'match', rules: {}, players });
|
||||
ok('all-zero match is a draw', L.matchResult(tie) === 'draw');
|
||||
ok('normalize bad timer', L.normalizeRules({ timerMs: 12345 }).timerMs === 180000);
|
||||
ok('normalize untimed', L.normalizeRules({ timerMs: 0 }).timerMs === 0);
|
||||
// daily
|
||||
let d = L.blankDaily();
|
||||
d = L.updateDaily(d, '2026-11-28', { score: 10 });
|
||||
d = L.updateDaily(d, '2026-11-29', { score: 12 });
|
||||
ok('streak grows day by day', d.streak === 2 && d.bestStreak === 2);
|
||||
const same = L.updateDaily(d, '2026-11-29', { score: 99 });
|
||||
ok('one attempt per day', same.results['2026-11-29'].score === 12 && same.streak === 2);
|
||||
d = L.updateDaily(d, '2026-12-02', { score: 5 });
|
||||
ok('gap resets streak', d.streak === 1 && d.bestStreak === 2);
|
||||
ok('streak shown today/yesterday only', L.dailyStreakNow(d, '2026-12-03') === 1 && L.dailyStreakNow(d, '2026-12-05') === 0);
|
||||
ok('daily seed stable + date-specific', L.dailySeed('2026-11-30') === L.dailySeed('2026-11-30') && L.dailySeed('2026-11-30') !== L.dailySeed('2026-12-01'));
|
||||
ok('fmtClock', L.fmtClock(180000) === '3:00' && L.fmtClock(9001) === '0:10' && L.fmtClock(0) === '0:00');
|
||||
}
|
||||
|
||||
// ── AI ─────────────────────────────────────────────────────────────────────
|
||||
section('AI');
|
||||
{
|
||||
ok('stem groups inflections', stemOf('RATES') === stemOf('RATE') && stemOf('RATED') === stemOf('RATE') && stemOf('RATER') === stemOf('RATE') && stemOf('CATS') === 'CAT', ['RATE', 'RATES', 'RATED', 'CATS'].map(stemOf).join());
|
||||
const fam = familyMap(['RATE', 'RATES', 'TEAR', 'DOG']);
|
||||
ok('families: suffix + anagram', fam.get('RATE').includes('RATES') && fam.get('RATE').includes('TEAR') && fam.get('DOG').length === 0);
|
||||
|
||||
const N = QUICK ? 40 : LADDER ? 400 : 160;
|
||||
const boards = Array.from({ length: N }, (_, i) => E.generateBoard({ size: 4, seed: 30000 + i }));
|
||||
const stats = {};
|
||||
let badSched = 0;
|
||||
const mul = (seed) => () => { seed = (seed + 0x6d2b79f5) >>> 0; let t = seed; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||||
const finds = {};
|
||||
for (let s = 1; s <= 5; s++) {
|
||||
stats[s] = { words: 0, pts: 0, obscure: 0, short: 0 };
|
||||
finds[s] = boards.map((g, i) => {
|
||||
const sched = scheduleFinds(g.solutions, s, 180000, { minLen: 3, rng: mul(i * 7 + s * 1000003) });
|
||||
const valid = new Set(g.solutions.map((x) => x.word));
|
||||
if (sched.some((x, k) => !valid.has(x.word) || x.atMs < 0 || x.atMs > 180000 || (k && sched[k - 1].atMs > x.atMs))) badSched++;
|
||||
if (new Set(sched.map((x) => x.word)).size !== sched.length) badSched++;
|
||||
stats[s].words += sched.length;
|
||||
stats[s].pts += L.sheetScore(sched.map((x) => x.word));
|
||||
stats[s].obscure += sched.filter((x) => E.wordTier(x.word) === 3).length;
|
||||
return sched.map((x) => x.word);
|
||||
});
|
||||
}
|
||||
ok('schedules valid, sorted, unique, inside the round', badSched === 0, String(badSched));
|
||||
const TARGET = { 1: [5, 13], 2: [9, 18], 3: [14, 26], 4: [20, 36], 5: [28, 50] };
|
||||
for (let s = 1; s <= 5; s++) {
|
||||
const w = stats[s].words / N;
|
||||
console.log(` skill ${s}: ${w.toFixed(1)} words · ${(stats[s].pts / N).toFixed(1)} pts · ${(stats[s].obscure / N).toFixed(1)} obscure`);
|
||||
ok(`skill ${s} words in ${TARGET[s]}`, w >= TARGET[s][0] && w <= TARGET[s][1], w.toFixed(1));
|
||||
}
|
||||
ok('skill 1 finds no obscure words', stats[1].obscure === 0);
|
||||
// ladder on mirrored boards (duplicates cancel)
|
||||
for (let s = 2; s <= 5; s++) {
|
||||
let win = 0;
|
||||
for (let i = 0; i < N; i++) {
|
||||
const r = L.resolveRound([{ found: finds[s][i] }, { found: finds[s - 1][i] }]);
|
||||
win += r[0].roundScore > r[1].roundScore ? 1 : r[0].roundScore === r[1].roundScore ? 0.5 : 0;
|
||||
}
|
||||
const pct = (win / N) * 100;
|
||||
console.log(` ${s} beats ${s - 1}: ${pct.toFixed(0)}%`);
|
||||
ok(`ladder ${s} > ${s - 1} (≥70%)`, pct >= 70, pct.toFixed(0));
|
||||
}
|
||||
// shorter rounds find fewer words; dup cancelling actually happens
|
||||
const short = boards.slice(0, 30).reduce((a, g, i) => a + scheduleFinds(g.solutions, 3, 60000, { rng: mul(i + 5) }).length, 0) / 30;
|
||||
ok('1-minute rounds find fewer words', short < stats[3].words / N * 0.7, short.toFixed(1));
|
||||
let sharedCount = 0;
|
||||
for (let i = 0; i < N; i++) sharedCount += L.resolveRound([{ found: finds[3][i] }, { found: finds[4][i] }])[0].shared;
|
||||
ok('rivals share some words (cancelling matters)', sharedCount / N >= 3, (sharedCount / N).toFixed(1));
|
||||
ok('no AI for empty / untimed', scheduleFinds([], 3, 180000).length === 0 && scheduleFinds(boards[0].solutions, 3, 0).length === 0);
|
||||
const min4 = scheduleFinds(boards[0].solutions, 5, 180000, { minLen: 4 });
|
||||
ok('AI respects min length', min4.every((x) => x.word.length >= 4));
|
||||
}
|
||||
|
||||
// ── layout ─────────────────────────────────────────────────────────────────
|
||||
section('Layout');
|
||||
{
|
||||
for (const size of [4, 5]) {
|
||||
for (let n = 0; n <= 3; n++) {
|
||||
const f = Y.furniture(n, size);
|
||||
const off = f.filter((r) => r.x < 0 || r.y < 0 || r.x + r.w > Y.W || r.y + r.h > Y.H);
|
||||
ok(`on screen (size ${size}, ${n} rivals)`, off.length === 0, off.map((r) => r.name).join());
|
||||
const clash = [];
|
||||
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) if (Y.overlaps(f[i], f[j])) clash.push(`${f[i].name}/${f[j].name}`);
|
||||
ok(`no overlaps (size ${size}, ${n} rivals)`, clash.length === 0, clash.join(' '));
|
||||
}
|
||||
const g = Y.trayGeom(size);
|
||||
const c00 = g.center(0, 0), cnn = g.center(g.n - 1, g.n - 1);
|
||||
ok(`tray ${size}: dice inside the frame`, c00.x - g.cube / 2 >= g.rect.x + g.frame && cnn.x + g.cube / 2 <= g.rect.x + g.rect.w - g.frame);
|
||||
}
|
||||
const cols = Y.scoreColumns(4);
|
||||
ok('score columns fit 4 players', cols[0].x >= 0 && cols[3].x + cols[3].w <= Y.W);
|
||||
ok('pad rows fit the pad', Y.PAD_LIST.y + Y.PAD_LIST.rows * Y.PAD_LIST.rowH <= Y.PAD_FOOT_Y - 10);
|
||||
ok('controls fit between tray and screen bottom', Y.CONTROLS_Y + 28 <= Y.H && Y.CONTROLS_Y - 28 > Y.trayGeom(5).rect.y + Y.trayGeom(5).rect.h);
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
Loading…
Reference in New Issue