Overhaul Spelling Bee with curated answers, Daily Hive, and full art pass
- Introduce a tiered answer list (core/familiar) built from ENABLE + web frequency data; non-answer ENABLE words become "Rare Finds" bonus points instead of counting toward the goal - Rewrite puzzle engine to pre-index words by letter mask, build per-difficulty catalogues with pangram/suffix-share filters, and support seeded generation for a deterministic Daily Hive - Add Daily Hive mode with streak tracking, best-score history, and date-based seeding - Replace the dark felt UI with a baked "Apiary at Golden Hour" art set (honeycomb cells, honey jar rank meter, beekeeper's ledger, animated bees, vignette, synthesized buzz) - Expand SpellingBeeLogic with hint grid, nudge picking, save/parse helpers, and difficulty-aware rank tiers - Add tools/buildBeeWords.js to regenerate the answer list from frequency data with allow/deny overrides, and tools/verifySpellingBee.js as a headless test harness covering engine, logic, layout, art bake, and scene smoke run
This commit is contained in:
parent
da558f2df9
commit
5f2930c1e1
|
|
@ -0,0 +1,6 @@
|
|||
# Spelling Bee — words forced onto the ANSWER list even though the frequency
|
||||
# data missed them. One per line: `WORD` (familiar tier) or `WORD core`.
|
||||
# Must be ENABLE words that can appear in a hive (4+ letters, no S, ≤7 distinct
|
||||
# letters). Rerun `node tools/buildBeeWords.js` after editing.
|
||||
UPROOT
|
||||
POUTING
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,55 @@
|
|||
# Spelling Bee — words that never count as ANSWERS (they're still accepted as
|
||||
# Rare Finds if ENABLE has them). One word per line; `#` starts a comment.
|
||||
# Rerun `node tools/buildBeeWords.js` after editing.
|
||||
|
||||
# ── Names / places whose ENABLE meaning is obscure ─────────────────────────────
|
||||
ABBA ABIGAIL AGGIE ALAMEDA ALAN ALAND ALBA ALEC ALEXANDER ALEXIA ALINE ALMA
|
||||
ALTHEA AMIN AMIR AMRITA ANDROMEDA ANGELICA ANIL ANNA APOLLO APPEL ARGENT ARIEL
|
||||
AXEL BACH BARNY BARRET BAYARD BAZAR BECK BECKET BEDELL BELIER BENEDICT BENNET
|
||||
BENNY BENJAMIN BERG BERLIN BERTHA BETH BETHEL BETTA BILLIE BLAIN BOBBY BOLLING
|
||||
BONITA BONNE BORA BOUTON BOWYER BRAD BRANT BREE BRIT BRITT BROOKING BUFFY BURG
|
||||
BURKE BURNIE BURTON CALLAN CAMPAGNA CANDIDA CARBO CARINA CARL CARLIN CARLING
|
||||
CARMAN CARMEN CARNEY CARR CARTER CATE CATLIN CATTIER CHANG CHAO CHAPMAN CHARLEY
|
||||
CHARLIE CHARRY CHEVY CHICO CICELY CICERO CLARENCE CLARY CLIFT CLINE COBB COBBY
|
||||
CODDING COLIN COLLEEN CONCHA CONN CONNER CONTE CORBY CORNEL CORRIE CORY COTE
|
||||
COUCHER COULTER CULVER CURR CURRAN CURRIE CYPRIAN DAHL DAPHNE DAVY DEVON DEWAR
|
||||
DEXTER DIDO DOMINICK DONA DONNA DOTY DUMA DURNING EMMET ERICA EUGENIA FARO
|
||||
FLETCHER FRANKLIN FREEDMAN FRITZ GABY GALATEA GAULT GEMMA GENET GENEVA
|
||||
GEORGETTE GERMAN GILBERT GLORIA GODDING GOODMAN GRAHAM GRANNIE GURNEY HAKEEM
|
||||
HAKIM HALBERT HENRY HILLER HOGG HOLLAND HONG JACKY JAEGER JAKE JANE JENNY JERRY
|
||||
JILL JOHN JOHNNY JORDAN KANE KATA KELLY KENT KERN KERRY KHAN KRAFT LAIRD LAMBERT
|
||||
LANDAU LANG LANGLEY LAURA LAZAR LEARY LEAVY LENO LEONE LEVIN LEVY LICHT LING
|
||||
LINN LOGAN LORIMER LOTTE LOUIE LOWE LUCE LUNA MACK MADELEINE MADONNA MAGDALEN
|
||||
MAGDALENE MALKIN MAMIE MARC MARCEL MARIA MARTIN MARYJANE MATILDA MATT MAUD MAYA
|
||||
MEDINA MELTON MERLE META MICK MIGNON MIGNONNE MILO MINA MOIRA MOLLIE MONTE
|
||||
MONTEITH MORA MORGAN MORGEN MOROCCO MORT MOTT MULLEN MULLER MUNGO MURPHY MURRY
|
||||
NANCE NANCY NANNIE NAPOLEON NATAL NELLIE NELLY NEMA NETTY NEVE NEWTON NICOL
|
||||
OTTO PANDORA PARKER PATTEN PATTIE PEDRO PEERY PERI PERRON PERRY PETER PHOEBE
|
||||
PILAR POLLACK POLLOCK POMFRET PONCE POULTER PRENTICE PUGH PURI QUINTA QUINTIN
|
||||
RALPH RANCE RAND REGINA REYNARD RHEA RICK RICKEY RIDLEY RITTER RITZ ROBBIN ROLF
|
||||
ROMANO ROMEO ROQUE RUDD RUTH TABER TABOR TAKA TAMMIE TAMMY TELFER TELFORD TERRY
|
||||
THORPE TIFFANY TIMOTHY TOBY TOMMY TONEY TONY TORI TROY TURK TYNE ULTIMA URANIA
|
||||
VAIL VALENCIA VANDYKE VERA VICTORIA VITA WARNER WATERMAN WAUGH WEBER WEINER
|
||||
WELCHER WYNN XENIA YAGER BAILEY BURNIE
|
||||
|
||||
# ── Offensive, vulgar or adult ──────────────────────────────────────────────────
|
||||
ANAL ANUS BITCH BITCHY BONDAGE BONER BOOB BOOBY CLIT COCK COCKY COON CRAP DAGO
|
||||
DICK DICKEY DICKIE DICKY DILDO DYKE FAGGOT FAGGOTRY FART FUCK FUCKER GOOK HOMO
|
||||
HONKY HOOKER HUMP HYMEN JIZZ KIKE KRAUT NIGGER NIGGARD PECKER PENIS PIMP PISS
|
||||
POOP PORN PORNO PRICK PUBIC RAPE RAPER RAPED RAPING RETARD SLUT TURD TWAT
|
||||
VAGINA VULVA WANK WENCH WETBACK WHORE WOP YID BALLING HOOCH BOOZE BOOZER
|
||||
CUNT ORGY
|
||||
|
||||
# ── Web/abbreviation junk that ranks high on frequency lists ────────────────────
|
||||
ACTA AERO ALFA ANON BAHT CAIN COCA COLE DONG DYER EXEC FUJI HAHA HOLT HOWE JEUX
|
||||
KIRK LAMA LIMA LITE METH MOLY MONY NAZI NITE PARA PHAT PLAT POOH PROG TATE TELE
|
||||
THRU YANG YUAN MANA
|
||||
ACYL ARCO BABA BARM BATT BENE BOCK BODE BOGY BUNN BUTE CAKY CAPO CAVY CHEZ CINE
|
||||
COLY CONY COWY DADA DEXY DIDY DOGY DOIT DURA DURO EELY EIDE ELMY EXON EYRE EYRY
|
||||
FICO FILA FLEY FOGY FORA GAPY GELD GIGA GIRO GUID HAUT HELO HOLM HOMY HORA HOYA
|
||||
ILLY JOKY KEMP KINO LAKH LAKY LIMY LINY LIRE LOCA LOGY LORY MAAR MANO MAZY MITY
|
||||
MOPY MUNI MUON NANA NIXY NOME OLDY ORBY PADI PALY PARR PATY PILY PIMA PINY PIPY
|
||||
POCO RIAL RIEL RIMY ROPY ROTA ROTO RULY TAIN TING TODY TOWY TRAD TROP TUFF TUNG
|
||||
TYPY VIDE VINY WADY WANY WICH WINY
|
||||
TITANIA MICRA AMICI MARGE LEGER GLEBE NICOTIANA TITIAN MANHATTAN
|
||||
TITTY LATED RALLYE LINAC VELOCE FACIA DERRY RILEY COCO CALIF AVION
|
||||
|
|
@ -0,0 +1,507 @@
|
|||
// Spelling Bee art — "The Apiary at Golden Hour", baked to canvases (no new
|
||||
// image files; the honeycomb photo backdrop and intro clip are the only assets).
|
||||
//
|
||||
// bee-cell a beeswax comb cell (the six outer letters)
|
||||
// bee-cell-center the honey-glazed center cell
|
||||
// bee-cell-shadow soft drop shadow under a cell
|
||||
// bee-body a little bee (body, stripes, eye) — wings are separate
|
||||
// bee-wing one translucent wing (flapped by scaleY)
|
||||
// bee-jar the glass honey jar (rank meter); honey is drawn under it
|
||||
// bee-ledger the beekeeper's ledger page (found words)
|
||||
// bee-card a parchment card (start screen + overlays)
|
||||
// bee-vignette warm golden-hour vignette over the backdrop
|
||||
// bee-glow soft round glow (pangram light, motes)
|
||||
// bee-drip a honey drop
|
||||
//
|
||||
// Also exports layout constants, the palette, HiveButton (a wax-tag button)
|
||||
// and playBuzz (a short synthesised buzz).
|
||||
|
||||
import * as Phaser from 'phaser';
|
||||
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────────
|
||||
export const W = 1920, H = 1080;
|
||||
export const HIVE = { x: 640, y: 600 };
|
||||
export const HEX_R = 92; // center-to-vertex
|
||||
export const HEX_D = Math.round(HEX_R * Math.sqrt(3)) + 6; // center-to-center (+ wax gap)
|
||||
export const INPUT_Y = 290;
|
||||
export const FEEDBACK_Y = 222;
|
||||
export const CONTROLS_Y = 930;
|
||||
export const JAR = { x: 150, top: 380, w: 168, h: 400 }; // glass body; neck + lid above
|
||||
export const LEDGER = { x: 1140, y: 40, w: 740, h: 960 };
|
||||
export const LEDGER_LIST = { x: LEDGER.x + 56, y: LEDGER.y + 236, w: LEDGER.w - 100, h: 520 };
|
||||
export const LEDGER_BONUS_Y = LEDGER.y + 790;
|
||||
|
||||
// ── Palette ───────────────────────────────────────────────────────────────────
|
||||
export const SERIF = 'Georgia, "Times New Roman", "Liberation Serif", "DejaVu Serif", serif';
|
||||
export const HONEY = 0xf2b632;
|
||||
export const HONEY_DEEP = 0xc77d0e;
|
||||
export const WAX = 0xf6dfa0;
|
||||
export const INK = '#3a2611'; // ledger ink (brown)
|
||||
export const INK_N = 0x3a2611;
|
||||
export const FADED = '#8a6d45';
|
||||
export const GOLD = '#f2c14e';
|
||||
export const CREAM = '#fff4d6';
|
||||
export const GOOD = '#5e9c3c';
|
||||
export const BAD = '#c2452d';
|
||||
export const BAD_N = 0xc2452d;
|
||||
|
||||
function hexPath(ctx, cx, cy, r) {
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const a = (Math.PI / 180) * (60 * i - 90);
|
||||
const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r;
|
||||
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
|
||||
}
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
// ── Cells ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function bakeCell(scene, key, center) {
|
||||
const pad = 10, S = (HEX_R + pad) * 2;
|
||||
const c = canvas(S, S), ctx = c.getContext('2d');
|
||||
const cx = S / 2, cy = S / 2;
|
||||
|
||||
// Rim: a darker wax wall.
|
||||
hexPath(ctx, cx, cy, HEX_R);
|
||||
const rim = ctx.createLinearGradient(0, cy - HEX_R, 0, cy + HEX_R);
|
||||
if (center) { rim.addColorStop(0, '#f7c64a'); rim.addColorStop(1, '#8f5208'); }
|
||||
else { rim.addColorStop(0, '#fbe7b0'); rim.addColorStop(1, '#b88a3a'); }
|
||||
ctx.fillStyle = rim;
|
||||
ctx.fill();
|
||||
|
||||
// Face: inset hex with a radial body.
|
||||
const inner = HEX_R - 9;
|
||||
hexPath(ctx, cx, cy, inner);
|
||||
const face = ctx.createRadialGradient(cx - 18, cy - 26, 6, cx, cy, inner * 1.05);
|
||||
if (center) {
|
||||
face.addColorStop(0, '#ffe08a'); face.addColorStop(0.45, '#f5ad22'); face.addColorStop(1, '#c46f05');
|
||||
} else {
|
||||
face.addColorStop(0, '#fff6da'); face.addColorStop(0.55, '#f4dc9c'); face.addColorStop(1, '#d9b468');
|
||||
}
|
||||
ctx.fillStyle = face;
|
||||
ctx.fill();
|
||||
|
||||
// Faint wax grain.
|
||||
ctx.save();
|
||||
hexPath(ctx, cx, cy, inner);
|
||||
ctx.clip();
|
||||
ctx.fillStyle = noisePattern(ctx, 96, center ? 18 : 26);
|
||||
ctx.fillRect(0, 0, S, S);
|
||||
// Tiny ghost comb pattern on the wax cells only.
|
||||
if (!center) {
|
||||
ctx.strokeStyle = 'rgba(150,105,40,0.10)';
|
||||
ctx.lineWidth = 1.5;
|
||||
for (let gy = -2; gy < 8; gy++) {
|
||||
for (let gx = -2; gx < 8; gx++) {
|
||||
const hx = gx * 26 + (gy % 2) * 13, hy = gy * 22.5;
|
||||
hexPath(ctx, hx, hy, 13);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Inner shadow along the lower edge.
|
||||
const sh = ctx.createLinearGradient(0, cy, 0, cy + inner);
|
||||
sh.addColorStop(0, 'rgba(0,0,0,0)');
|
||||
sh.addColorStop(1, center ? 'rgba(90,40,0,0.35)' : 'rgba(110,70,10,0.25)');
|
||||
ctx.fillStyle = sh;
|
||||
ctx.fillRect(0, cy, S, inner);
|
||||
ctx.restore();
|
||||
|
||||
// Gloss: an arc of light across the top.
|
||||
ctx.save();
|
||||
hexPath(ctx, cx, cy, inner - 4);
|
||||
ctx.clip();
|
||||
const gloss = ctx.createLinearGradient(0, cy - inner, 0, cy - inner * 0.15);
|
||||
gloss.addColorStop(0, `rgba(255,255,255,${center ? 0.55 : 0.45})`);
|
||||
gloss.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = gloss;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(cx - 8, cy - inner * 0.55, inner * 0.8, inner * 0.42, -0.12, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
// Crisp outline.
|
||||
hexPath(ctx, cx, cy, HEX_R - 1);
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = center ? 'rgba(110,55,0,0.85)' : 'rgba(140,100,40,0.8)';
|
||||
ctx.stroke();
|
||||
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
|
||||
function bakeCellShadow(scene) {
|
||||
const S = (HEX_R + 30) * 2;
|
||||
const c = canvas(S, S), ctx = c.getContext('2d');
|
||||
ctx.filter = 'blur(10px)';
|
||||
hexPath(ctx, S / 2, S / 2, HEX_R);
|
||||
ctx.fillStyle = 'rgba(30,14,0,0.55)';
|
||||
ctx.fill();
|
||||
scene.textures.addCanvas('bee-cell-shadow', c);
|
||||
}
|
||||
|
||||
// ── Bee ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
function bakeBee(scene) {
|
||||
// Body, facing right, 64×44.
|
||||
const c = canvas(64, 44), ctx = c.getContext('2d');
|
||||
// Stinger
|
||||
ctx.fillStyle = '#2a1a08';
|
||||
ctx.beginPath(); ctx.moveTo(6, 22); ctx.lineTo(14, 18); ctx.lineTo(14, 26); ctx.closePath(); ctx.fill();
|
||||
// Abdomen with stripes (clipped).
|
||||
ctx.save();
|
||||
ctx.beginPath(); ctx.ellipse(28, 22, 18, 14, 0, 0, Math.PI * 2); ctx.clip();
|
||||
const body = ctx.createRadialGradient(24, 15, 2, 28, 22, 20);
|
||||
body.addColorStop(0, '#ffe27a'); body.addColorStop(1, '#e9a512');
|
||||
ctx.fillStyle = body; ctx.fillRect(0, 0, 64, 44);
|
||||
ctx.fillStyle = '#2b1c0b';
|
||||
for (const x of [17, 27, 37]) ctx.fillRect(x, 0, 5, 44);
|
||||
ctx.restore();
|
||||
// Fuzz outline
|
||||
ctx.strokeStyle = 'rgba(80,50,10,0.6)'; ctx.lineWidth = 1.5;
|
||||
ctx.beginPath(); ctx.ellipse(28, 22, 18, 14, 0, 0, Math.PI * 2); ctx.stroke();
|
||||
// Head
|
||||
ctx.fillStyle = '#2b1c0b';
|
||||
ctx.beginPath(); ctx.arc(50, 21, 9, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.beginPath(); ctx.arc(53, 18, 2.6, 0, Math.PI * 2); ctx.fill();
|
||||
// Antennae
|
||||
ctx.strokeStyle = '#2b1c0b'; ctx.lineWidth = 1.6;
|
||||
ctx.beginPath(); ctx.moveTo(53, 13); ctx.quadraticCurveTo(57, 4, 62, 5); ctx.stroke();
|
||||
ctx.beginPath(); ctx.moveTo(50, 12); ctx.quadraticCurveTo(51, 3, 56, 1); ctx.stroke();
|
||||
scene.textures.addCanvas('bee-body', c);
|
||||
|
||||
// Wing, 34×22, anchored at its left-bottom.
|
||||
const w = canvas(34, 22), wx = w.getContext('2d');
|
||||
wx.fillStyle = 'rgba(235,245,255,0.62)';
|
||||
wx.strokeStyle = 'rgba(120,140,160,0.75)';
|
||||
wx.lineWidth = 1.2;
|
||||
wx.beginPath(); wx.ellipse(17, 11, 16, 9.5, -0.25, 0, Math.PI * 2); wx.fill(); wx.stroke();
|
||||
wx.strokeStyle = 'rgba(120,140,160,0.35)';
|
||||
wx.beginPath(); wx.moveTo(4, 15); wx.lineTo(28, 7); wx.stroke();
|
||||
scene.textures.addCanvas('bee-wing', w);
|
||||
}
|
||||
|
||||
// ── Jar ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
// The jar body's interior rectangle in scene coords (for the honey fill).
|
||||
export function jarInterior(inset = 6) {
|
||||
return { x: JAR.x - JAR.w / 2 + inset, y: JAR.top + inset, w: JAR.w - inset * 2, h: JAR.h - inset * 2, r: 34 - inset };
|
||||
}
|
||||
|
||||
function bakeJar(scene) {
|
||||
const pad = 20, neck = 46, lid = 34;
|
||||
const Wc = JAR.w + pad * 2, Hc = JAR.h + neck + lid + pad * 2;
|
||||
const c = canvas(Wc, Hc), ctx = c.getContext('2d');
|
||||
const bx = pad, by = pad + lid + neck, bw = JAR.w, bh = JAR.h;
|
||||
|
||||
// Lid: wooden cap with a gingham cloth.
|
||||
ctx.fillStyle = '#7a4a1e';
|
||||
rr(ctx, bx + 18, pad + 6, bw - 36, lid, 8); ctx.fill();
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.18)';
|
||||
rr(ctx, bx + 22, pad + 9, bw - 44, 8, 4); ctx.fill();
|
||||
ctx.save();
|
||||
rr(ctx, bx + 4, pad + lid - 2, bw - 8, 26, 10); ctx.clip();
|
||||
ctx.fillStyle = '#f3ead8'; ctx.fillRect(bx, pad + lid - 2, bw, 26);
|
||||
ctx.fillStyle = 'rgba(196,58,42,0.55)';
|
||||
for (let x = bx; x < bx + bw; x += 16) ctx.fillRect(x, pad + lid - 2, 8, 26);
|
||||
for (let y = pad + lid - 2; y < pad + lid + 24; y += 16) ctx.fillRect(bx, y, bw, 8);
|
||||
ctx.restore();
|
||||
// twine
|
||||
ctx.strokeStyle = '#9b7a46'; ctx.lineWidth = 3;
|
||||
ctx.beginPath(); ctx.moveTo(bx + 14, pad + lid + 22); ctx.lineTo(bx + bw - 14, pad + lid + 22); ctx.stroke();
|
||||
|
||||
// Neck + body glass.
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
rr(ctx, bx + 24, pad + lid + 20, bw - 48, neck - 10, 6);
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.10)'; ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.55)'; ctx.lineWidth = 2.5; ctx.stroke();
|
||||
ctx.restore();
|
||||
|
||||
rr(ctx, bx, by, bw, bh, 34);
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.08)'; ctx.fill();
|
||||
ctx.lineWidth = 4; ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.stroke();
|
||||
ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(90,60,20,0.5)';
|
||||
rr(ctx, bx + 3, by + 3, bw - 6, bh - 6, 31); ctx.stroke();
|
||||
|
||||
// Glass highlights.
|
||||
const hl = ctx.createLinearGradient(bx, 0, bx + bw, 0);
|
||||
hl.addColorStop(0, 'rgba(255,255,255,0.0)');
|
||||
hl.addColorStop(0.12, 'rgba(255,255,255,0.42)');
|
||||
hl.addColorStop(0.2, 'rgba(255,255,255,0.0)');
|
||||
hl.addColorStop(0.82, 'rgba(255,255,255,0.0)');
|
||||
hl.addColorStop(0.9, 'rgba(255,255,255,0.22)');
|
||||
hl.addColorStop(1, 'rgba(255,255,255,0.0)');
|
||||
ctx.fillStyle = hl;
|
||||
rr(ctx, bx + 6, by + 10, bw - 12, bh - 20, 28); ctx.fill();
|
||||
|
||||
// Paper label.
|
||||
const ly = by + bh * 0.58, lh = 88;
|
||||
ctx.fillStyle = '#f4e6c4';
|
||||
rr(ctx, bx + 14, ly, bw - 28, lh, 6); ctx.fill();
|
||||
ctx.strokeStyle = 'rgba(90,60,20,0.55)'; ctx.lineWidth = 1.5;
|
||||
rr(ctx, bx + 19, ly + 5, bw - 38, lh - 10, 4); ctx.stroke();
|
||||
|
||||
scene.textures.addCanvas('bee-jar', c);
|
||||
}
|
||||
export const JAR_TEX = { padX: 20, padTop: 20 + 34 + 46 }; // body top-left inside the texture
|
||||
export const JAR_LABEL_Y = JAR.top + JAR.h * 0.58 + 44; // centre of the paper label
|
||||
|
||||
// ── Paper (ledger + cards) ────────────────────────────────────────────────────
|
||||
|
||||
function paperFill(ctx, x, y, w, h, r) {
|
||||
rr(ctx, x, y, w, h, r);
|
||||
const g = ctx.createLinearGradient(x, y, x + w * 0.3, y + h);
|
||||
g.addColorStop(0, '#fbf1d8'); g.addColorStop(1, '#efdcb0');
|
||||
ctx.fillStyle = g; ctx.fill();
|
||||
ctx.save();
|
||||
rr(ctx, x, y, w, h, r); ctx.clip();
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 22);
|
||||
ctx.fillRect(x, y, w, h);
|
||||
// edge darkening
|
||||
const e = ctx.createRadialGradient(x + w / 2, y + h / 2, Math.min(w, h) * 0.35, x + w / 2, y + h / 2, Math.max(w, h) * 0.75);
|
||||
e.addColorStop(0, 'rgba(120,80,20,0)'); e.addColorStop(1, 'rgba(120,80,20,0.22)');
|
||||
ctx.fillStyle = e; ctx.fillRect(x, y, w, h);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function honeyRing(ctx, x, y, r) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = 'rgba(200,130,20,0.16)'; ctx.lineWidth = 7;
|
||||
ctx.beginPath(); ctx.arc(x, y, r, 0.3, Math.PI * 1.85); ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(200,130,20,0.09)'; ctx.lineWidth = 3;
|
||||
ctx.beginPath(); ctx.arc(x + 2, y + 1, r - 6, 0, Math.PI * 2); ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function bakeLedger(scene) {
|
||||
const pad = 18;
|
||||
const c = canvas(LEDGER.w + pad * 2, LEDGER.h + pad * 2), ctx = c.getContext('2d');
|
||||
ctx.filter = 'blur(12px)';
|
||||
ctx.fillStyle = 'rgba(20,10,0,0.55)';
|
||||
rr(ctx, pad + 6, pad + 12, LEDGER.w, LEDGER.h, 14); ctx.fill();
|
||||
ctx.filter = 'none';
|
||||
paperFill(ctx, pad, pad, LEDGER.w, LEDGER.h, 12);
|
||||
|
||||
// Ruled lines for the word list + a red margin.
|
||||
const lx = pad + 40, top = pad + 236 - 18;
|
||||
ctx.strokeStyle = 'rgba(80,120,170,0.18)'; ctx.lineWidth = 1;
|
||||
for (let y = top; y < pad + LEDGER.h - 30; y += 30) {
|
||||
ctx.beginPath(); ctx.moveTo(pad + 16, y); ctx.lineTo(pad + LEDGER.w - 16, y); ctx.stroke();
|
||||
}
|
||||
ctx.strokeStyle = 'rgba(190,60,50,0.35)'; ctx.lineWidth = 1.5;
|
||||
ctx.beginPath(); ctx.moveTo(lx, pad + 16); ctx.lineTo(lx, pad + LEDGER.h - 16); ctx.stroke();
|
||||
|
||||
// Header rule.
|
||||
ctx.strokeStyle = 'rgba(58,38,17,0.6)'; ctx.lineWidth = 2;
|
||||
ctx.beginPath(); ctx.moveTo(pad + 30, pad + 176); ctx.lineTo(pad + LEDGER.w - 30, pad + 176); ctx.stroke();
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath(); ctx.moveTo(pad + 30, pad + 181); ctx.lineTo(pad + LEDGER.w - 30, pad + 181); ctx.stroke();
|
||||
// Rare finds rule.
|
||||
const by = pad + (LEDGER_BONUS_Y - LEDGER.y) - 14;
|
||||
ctx.setLineDash([6, 5]);
|
||||
ctx.strokeStyle = 'rgba(58,38,17,0.45)';
|
||||
ctx.beginPath(); ctx.moveTo(pad + 30, by); ctx.lineTo(pad + LEDGER.w - 30, by); ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
|
||||
honeyRing(ctx, pad + LEDGER.w - 120, pad + LEDGER.h - 120, 54);
|
||||
|
||||
// Washi-tape corners.
|
||||
ctx.fillStyle = 'rgba(242,182,50,0.55)';
|
||||
for (const [x, y, a] of [[pad + 30, pad + 6, -0.5], [pad + LEDGER.w - 30, pad + 6, 0.5]]) {
|
||||
ctx.save(); ctx.translate(x, y); ctx.rotate(a); ctx.fillRect(-40, -12, 80, 24); ctx.restore();
|
||||
}
|
||||
scene.textures.addCanvas('bee-ledger', c);
|
||||
}
|
||||
export const LEDGER_PAD = 18;
|
||||
|
||||
function bakeCard(scene, key, w, h) {
|
||||
const pad = 18;
|
||||
const c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d');
|
||||
ctx.filter = 'blur(12px)';
|
||||
ctx.fillStyle = 'rgba(20,10,0,0.6)';
|
||||
rr(ctx, pad + 6, pad + 12, w, h, 16); ctx.fill();
|
||||
ctx.filter = 'none';
|
||||
paperFill(ctx, pad, pad, w, h, 16);
|
||||
ctx.strokeStyle = 'rgba(160,100,20,0.55)'; ctx.lineWidth = 2;
|
||||
rr(ctx, pad + 12, pad + 12, w - 24, h - 24, 10); ctx.stroke();
|
||||
// little comb motif in the corners
|
||||
ctx.strokeStyle = 'rgba(200,130,20,0.35)'; ctx.lineWidth = 2;
|
||||
for (const [x, y] of [[pad + 38, pad + 38], [pad + w - 38, pad + 38], [pad + 38, pad + h - 38], [pad + w - 38, pad + h - 38]]) {
|
||||
hexPath(ctx, x, y, 12); ctx.stroke();
|
||||
}
|
||||
honeyRing(ctx, pad + w - 90, pad + 90, 40);
|
||||
scene.textures.addCanvas(key, c);
|
||||
}
|
||||
export const CARD = { w: 1120, h: 760 };
|
||||
export const OVERLAY_CARD = { w: 900, h: 640 };
|
||||
|
||||
// ── Atmosphere ────────────────────────────────────────────────────────────────
|
||||
|
||||
function bakeVignette(scene) {
|
||||
const c = canvas(W / 2, H / 2), ctx = c.getContext('2d');
|
||||
const g = ctx.createRadialGradient(W / 4 - 80, H / 4, 80, W / 4, H / 4, W / 2.6);
|
||||
g.addColorStop(0, 'rgba(255,190,90,0.10)');
|
||||
g.addColorStop(0.55, 'rgba(60,25,0,0.25)');
|
||||
g.addColorStop(1, 'rgba(15,6,0,0.82)');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, W / 2, H / 2);
|
||||
scene.textures.addCanvas('bee-vignette', c);
|
||||
}
|
||||
|
||||
function bakeGlow(scene) {
|
||||
const c = canvas(128, 128), ctx = c.getContext('2d');
|
||||
const g = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);
|
||||
g.addColorStop(0, 'rgba(255,236,170,1)');
|
||||
g.addColorStop(0.4, 'rgba(255,200,90,0.45)');
|
||||
g.addColorStop(1, 'rgba(255,180,60,0)');
|
||||
ctx.fillStyle = g; ctx.fillRect(0, 0, 128, 128);
|
||||
scene.textures.addCanvas('bee-glow', c);
|
||||
}
|
||||
|
||||
function bakeDrip(scene) {
|
||||
const c = canvas(20, 28), ctx = c.getContext('2d');
|
||||
const g = ctx.createRadialGradient(8, 18, 1, 10, 18, 10);
|
||||
g.addColorStop(0, '#ffd56a'); g.addColorStop(1, '#c4730a');
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(10, 0);
|
||||
ctx.bezierCurveTo(12, 8, 19, 12, 19, 18);
|
||||
ctx.arc(10, 18, 9, 0, Math.PI);
|
||||
ctx.bezierCurveTo(1, 12, 8, 8, 10, 0);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.7)';
|
||||
ctx.beginPath(); ctx.arc(7, 17, 2.4, 0, Math.PI * 2); ctx.fill();
|
||||
scene.textures.addCanvas('bee-drip', c);
|
||||
}
|
||||
|
||||
export function prepareBeeArt(scene) {
|
||||
if (!scene.textures.exists('bee-cell')) bakeCell(scene, 'bee-cell', false);
|
||||
if (!scene.textures.exists('bee-cell-center')) bakeCell(scene, 'bee-cell-center', true);
|
||||
if (!scene.textures.exists('bee-cell-shadow')) bakeCellShadow(scene);
|
||||
if (!scene.textures.exists('bee-body')) bakeBee(scene);
|
||||
if (!scene.textures.exists('bee-jar')) bakeJar(scene);
|
||||
if (!scene.textures.exists('bee-ledger')) bakeLedger(scene);
|
||||
if (!scene.textures.exists('bee-card')) bakeCard(scene, 'bee-card', CARD.w, CARD.h);
|
||||
if (!scene.textures.exists('bee-overlay-card')) bakeCard(scene, 'bee-overlay-card', OVERLAY_CARD.w, OVERLAY_CARD.h);
|
||||
if (!scene.textures.exists('bee-vignette')) bakeVignette(scene);
|
||||
if (!scene.textures.exists('bee-glow')) bakeGlow(scene);
|
||||
if (!scene.textures.exists('bee-drip')) bakeDrip(scene);
|
||||
}
|
||||
|
||||
// ── HiveButton ────────────────────────────────────────────────────────────────
|
||||
// A beeswax tag with a stamped label. Container centred on (x, y); every child
|
||||
// is centred too (a Container's hit area is always centred on it).
|
||||
export class HiveButton extends Phaser.GameObjects.Container {
|
||||
constructor(scene, x, y, label, onClick, { width = 180, height = 60, fontSize = 24, accent = false, dark = false } = {}) {
|
||||
super(scene, x, y);
|
||||
this.w = width; this.h = height; this.accent = accent; this.dark = dark;
|
||||
this.enabled = true;
|
||||
this.hover = false;
|
||||
this.gfx = scene.add.graphics();
|
||||
this.text = scene.add.text(0, 1, label, {
|
||||
fontFamily: SERIF, fontSize: `${fontSize}px`, fontStyle: 'bold',
|
||||
color: accent ? '#4a2604' : (dark ? CREAM : INK),
|
||||
}).setOrigin(0.5);
|
||||
this.baseSize = fontSize;
|
||||
this.fit();
|
||||
this.add([this.gfx, this.text]);
|
||||
this.setSize(width, height);
|
||||
this.setInteractive({ useHandCursor: true });
|
||||
this.draw();
|
||||
this.on('pointerover', () => { this.hover = true; this.draw(); });
|
||||
this.on('pointerout', () => { this.hover = false; this.draw(); this.gfx.y = 0; this.text.y = 1; });
|
||||
this.on('pointerdown', () => { if (this.enabled) { this.gfx.y = 2; this.text.y = 3; } });
|
||||
this.on('pointerup', () => {
|
||||
this.gfx.y = 0; this.text.y = 1;
|
||||
if (this.enabled) onClick?.();
|
||||
});
|
||||
scene.add.existing(this);
|
||||
}
|
||||
|
||||
fit() {
|
||||
const maxW = this.w - 20;
|
||||
this.text.setFontSize(this.baseSize);
|
||||
if (this.text.width > maxW) this.text.setFontSize(Math.max(12, Math.floor(this.baseSize * maxW / this.text.width)));
|
||||
}
|
||||
|
||||
draw() {
|
||||
const g = this.gfx, w = this.w, h = this.h, r = Math.min(16, h / 2);
|
||||
const lit = this.hover && this.enabled;
|
||||
g.clear();
|
||||
g.fillStyle(0x1a0c00, 0.35);
|
||||
g.fillRoundedRect(-w / 2 + 2, -h / 2 + 5, w, h, r);
|
||||
let fill, edge;
|
||||
if (this.accent) { fill = lit ? 0xffcf55 : HONEY; edge = HONEY_DEEP; }
|
||||
else if (this.dark) { fill = lit ? 0x5a3a18 : 0x3d260e; edge = 0x8a6030; }
|
||||
else { fill = lit ? 0xfff1c8 : WAX; edge = 0xb88a3a; }
|
||||
g.fillStyle(fill, 1);
|
||||
g.fillRoundedRect(-w / 2, -h / 2, w, h, r);
|
||||
g.fillStyle(0xffffff, this.dark ? 0.06 : 0.28);
|
||||
g.fillRoundedRect(-w / 2 + 6, -h / 2 + 4, w - 12, h * 0.36, { tl: r - 4, tr: r - 4, bl: 4, br: 4 });
|
||||
g.lineStyle(2, edge, 1);
|
||||
g.strokeRoundedRect(-w / 2, -h / 2, w, h, r);
|
||||
}
|
||||
|
||||
setLabel(t) { this.text.setText(t); this.fit(); return this; }
|
||||
|
||||
setEnabled(on) {
|
||||
this.enabled = on;
|
||||
this.setAlpha(on ? 1 : 0.45);
|
||||
if (this.input) this.input.cursor = on ? 'pointer' : 'default';
|
||||
this.draw();
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Sound ─────────────────────────────────────────────────────────────────────
|
||||
// A short, soft buzz synthesised with WebAudio (there is no bee clip in the
|
||||
// SFX set). Quietly does nothing under the HTML5 sound manager or when muted.
|
||||
export function playBuzz(scene, { duration = 0.55, pitch = 190, volume = 0.05 } = {}) {
|
||||
try {
|
||||
const sm = scene.sound;
|
||||
const ctx = sm?.context;
|
||||
if (!ctx || sm.mute || ctx.state !== 'running') return;
|
||||
const t = ctx.currentTime;
|
||||
const osc = ctx.createOscillator();
|
||||
osc.type = 'sawtooth';
|
||||
osc.frequency.setValueAtTime(pitch, t);
|
||||
osc.frequency.linearRampToValueAtTime(pitch * 1.18, t + duration * 0.4);
|
||||
osc.frequency.linearRampToValueAtTime(pitch * 0.92, t + duration);
|
||||
const lfo = ctx.createOscillator();
|
||||
lfo.frequency.value = 23;
|
||||
const lfoGain = ctx.createGain();
|
||||
lfoGain.gain.value = 0.35;
|
||||
const amp = ctx.createGain();
|
||||
const v = volume; // sm.destination already applies the master volume/mute
|
||||
amp.gain.setValueAtTime(0, t);
|
||||
amp.gain.linearRampToValueAtTime(v, t + 0.06);
|
||||
amp.gain.setValueAtTime(v, t + duration * 0.7);
|
||||
amp.gain.linearRampToValueAtTime(0, t + duration);
|
||||
const lp = ctx.createBiquadFilter();
|
||||
lp.type = 'lowpass';
|
||||
lp.frequency.value = 900;
|
||||
lfo.connect(lfoGain).connect(amp.gain);
|
||||
osc.connect(lp).connect(amp).connect(sm.destination ?? ctx.destination);
|
||||
osc.start(t); lfo.start(t);
|
||||
osc.stop(t + duration + 0.05); lfo.stop(t + duration + 0.05);
|
||||
} catch { /* audio is a nicety */ }
|
||||
}
|
||||
|
||||
// ── Backdrop ──────────────────────────────────────────────────────────────────
|
||||
// A softened copy of the honeycomb photo, baked once at half resolution (cheap
|
||||
// to blur, and the upscale softens it further) so the busy comb sits behind
|
||||
// the real hive instead of competing with it.
|
||||
export function bakeSoftBackdrop(scene, srcKey) {
|
||||
const key = 'bee-bg-soft';
|
||||
if (scene.textures.exists(key)) return key;
|
||||
if (!scene.textures.exists(srcKey)) return srcKey;
|
||||
const src = scene.textures.get(srcKey).getSourceImage();
|
||||
const c = canvas(W / 2, H / 2), ctx = c.getContext('2d');
|
||||
ctx.filter = 'blur(3px) saturate(1.08)';
|
||||
ctx.drawImage(src, -10, -10, W / 2 + 20, H / 2 + 20); // overdraw so the blur doesn't darken the edges
|
||||
scene.textures.addCanvas(key, c);
|
||||
return key;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,61 +1,255 @@
|
|||
// Spelling Bee logic: scoring and rank tiers. Pure — no Phaser.
|
||||
// Spelling Bee logic — scoring, ranks/goals, hints, saves and the Daily Hive.
|
||||
// Pure — no Phaser (Node-tested by tools/verifySpellingBee.js).
|
||||
//
|
||||
// scoring scoreWord, isPangram, checkWord
|
||||
// ranks GOAL, MODES, buildTiers, rankFor, geniusScore, wordsToGo
|
||||
// hints hintGrid, twoLetterStarts, pickNudge, nudgeText
|
||||
// saves SAVE_KEY, serialiseSave, parseSave
|
||||
// daily DAILY_KEY, DAILY_DIFFICULTY, todayString, dailySeed, blankDaily,
|
||||
// updateDaily, dailyStreakNow, longDate
|
||||
//
|
||||
// The goal is a share of the ANSWER points (the curated words the puzzle was
|
||||
// built from — see src/words/spellingBeeEngine.js). Bonus words (other ENABLE
|
||||
// words that fit) add to your score, so they help, but they're never needed.
|
||||
|
||||
// Rank tiers as a fraction of the puzzle's maximum possible score (NYT scale).
|
||||
// Queen Bee (100%) is intentionally omitted — Genius is the achievable goal.
|
||||
// Genius threshold scales down on easier difficulties so it's actually reachable.
|
||||
import { dateSeed, localDateString } from '../dotlink/DotLinkLogic.js';
|
||||
|
||||
// ── Modes ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Share of the answer points needed for Genius. Tuned with the verify tool so a
|
||||
// typical hive needs roughly 9–12 / 19–24 / 35–40 words.
|
||||
export const GOAL = { easy: 0.32, normal: 0.50, hard: 0.66 };
|
||||
|
||||
export const MODES = {
|
||||
easy: { name: 'Meadow', label: 'Easy', blurb: 'Everyday words, a short list.' },
|
||||
normal: { name: 'Garden', label: 'Normal', blurb: 'A fuller hive of familiar words.' },
|
||||
hard: { name: 'Wild Hive', label: 'Hard', blurb: 'Big hives, longer words, a high bar.' },
|
||||
};
|
||||
export const DIFFS = ['easy', 'normal', 'hard'];
|
||||
|
||||
// Rank ladder as a fraction of the Genius score (NYT-style names). Queen Bee —
|
||||
// every answer found — sits beyond Genius and is tracked separately.
|
||||
const TIER_TABLE = [
|
||||
{ name: 'Beginner', pct: 0.00 },
|
||||
{ name: 'Good Start', pct: 0.02 },
|
||||
{ name: 'Moving Up', pct: 0.05 },
|
||||
{ name: 'Good', pct: 0.08 },
|
||||
{ name: 'Solid', pct: 0.15 },
|
||||
{ name: 'Nice', pct: 0.25 },
|
||||
{ name: 'Great', pct: 0.40 },
|
||||
{ name: 'Amazing', pct: 0.50 },
|
||||
{ name: 'Genius', pct: 0.70 },
|
||||
{ name: 'Beginner', f: 0.00 },
|
||||
{ name: 'Good Start', f: 0.03 },
|
||||
{ name: 'Moving Up', f: 0.07 },
|
||||
{ name: 'Good', f: 0.12 },
|
||||
{ name: 'Solid', f: 0.22 },
|
||||
{ name: 'Nice', f: 0.36 },
|
||||
{ name: 'Great', f: 0.57 },
|
||||
{ name: 'Amazing', f: 0.72 },
|
||||
{ name: 'Genius', f: 1.00 },
|
||||
];
|
||||
|
||||
// Fraction of maxScore required to reach Genius per difficulty.
|
||||
const GENIUS_PCT = { easy: 0.40, normal: 0.55, hard: 0.70 };
|
||||
|
||||
// Number of distinct letters in a word.
|
||||
function distinctCount(word) {
|
||||
return new Set(word.toUpperCase()).size;
|
||||
}
|
||||
// ── Scoring ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// A pangram uses all 7 distinct puzzle letters.
|
||||
export function isPangram(word) {
|
||||
return distinctCount(word) === 7;
|
||||
return new Set(String(word).toUpperCase()).size === 7;
|
||||
}
|
||||
|
||||
// 4-letter word = 1 pt; longer words = 1 pt per letter; pangram earns +7.
|
||||
// 4-letter word = 1 pt; longer words = 1 pt per letter; a pangram earns +7.
|
||||
export function scoreWord(word) {
|
||||
const w = String(word);
|
||||
let s = w.length === 4 ? 1 : w.length;
|
||||
if (isPangram(w)) s += 7;
|
||||
return s;
|
||||
return (w.length === 4 ? 1 : w.length) + (isPangram(w) ? 7 : 0);
|
||||
}
|
||||
|
||||
// Concrete tier thresholds (rounded score needed to reach each tier).
|
||||
// Judge a submitted word. `p` is the puzzle state:
|
||||
// { center, letters[], answers:Set, bonus:Set, found:Set }
|
||||
// → { ok:false, reason, tone } | { ok:true, kind:'answer'|'bonus', pts, pangram }
|
||||
export function checkWord(word, p) {
|
||||
const w = String(word).toUpperCase();
|
||||
if (!w) return { ok: false, reason: '', tone: 'muted' };
|
||||
if (w.length < 4) return { ok: false, reason: 'Too short', tone: 'bad' };
|
||||
if ([...w].some((c) => !p.letters.includes(c))) return { ok: false, reason: 'Bad letters', tone: 'bad' };
|
||||
if (!w.includes(p.center)) return { ok: false, reason: 'Missing center letter', tone: 'bad' };
|
||||
if (p.found.has(w)) return { ok: false, reason: 'Already found', tone: 'muted' };
|
||||
const kind = p.answers.has(w) ? 'answer' : p.bonus.has(w) ? 'bonus' : null;
|
||||
if (!kind) return { ok: false, reason: 'Not in word list', tone: 'bad' };
|
||||
return { ok: true, kind, pts: scoreWord(w), pangram: isPangram(w) };
|
||||
}
|
||||
|
||||
// ── Ranks / goal ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function geniusScore(maxScore, difficulty = 'normal') {
|
||||
return Math.max(1, Math.round((GOAL[difficulty] ?? GOAL.normal) * maxScore));
|
||||
}
|
||||
|
||||
// Concrete thresholds for each rank, ending at Genius.
|
||||
export function buildTiers(maxScore, difficulty = 'normal') {
|
||||
const geniusPct = GENIUS_PCT[difficulty] ?? GENIUS_PCT.normal;
|
||||
const scale = geniusPct / TIER_TABLE[TIER_TABLE.length - 1].pct;
|
||||
return TIER_TABLE.map((t) => ({
|
||||
const g = geniusScore(maxScore, difficulty);
|
||||
return TIER_TABLE.map((t, i) => ({
|
||||
name: t.name,
|
||||
threshold: Math.round(t.pct * scale * maxScore),
|
||||
threshold: i === TIER_TABLE.length - 1 ? g : Math.round(t.f * g),
|
||||
}));
|
||||
}
|
||||
|
||||
// Current tier for a score plus the next tier (null once Genius is reached).
|
||||
export function rankFor(score, maxScore) {
|
||||
const tiers = buildTiers(maxScore);
|
||||
let currentIdx = 0;
|
||||
for (let i = 0; i < tiers.length; i++) {
|
||||
if (score >= tiers[i].threshold) currentIdx = i;
|
||||
// Current rank (and the next one) for a score. Difficulty matters — it moves
|
||||
// the Genius line — so it is always passed through.
|
||||
export function rankFor(score, maxScore, difficulty = 'normal') {
|
||||
const tiers = buildTiers(maxScore, difficulty);
|
||||
let idx = 0;
|
||||
for (let i = 0; i < tiers.length; i++) if (score >= tiers[i].threshold) idx = i;
|
||||
return { index: idx, current: tiers[idx], next: tiers[idx + 1] ?? null, isGenius: idx === tiers.length - 1, tiers };
|
||||
}
|
||||
|
||||
// Rough number of answers still needed to reach `target` points: remaining
|
||||
// points over the average points of the answers you haven't found.
|
||||
export function wordsToGo(score, target, answers, found) {
|
||||
if (score >= target) return 0;
|
||||
const left = answers.filter((w) => !found.has(w));
|
||||
if (!left.length) return 0;
|
||||
const avg = left.reduce((s, w) => s + scoreWord(w), 0) / left.length;
|
||||
return Math.min(left.length, Math.max(1, Math.ceil((target - score) / avg)));
|
||||
}
|
||||
|
||||
// ── Hints ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// The classic hints grid over the answers still missing: rows = first letter,
|
||||
// columns = word length. → { lengths[], rows: [{ letter, counts{len:n}, total }], colTotals{}, total }
|
||||
export function hintGrid(answers, found) {
|
||||
const left = answers.filter((w) => !found.has(w));
|
||||
const lengths = [...new Set(left.map((w) => w.length))].sort((a, b) => a - b);
|
||||
const byLetter = new Map();
|
||||
const colTotals = {};
|
||||
for (const w of left) {
|
||||
const L = w[0];
|
||||
if (!byLetter.has(L)) byLetter.set(L, { letter: L, counts: {}, total: 0 });
|
||||
const r = byLetter.get(L);
|
||||
r.counts[w.length] = (r.counts[w.length] ?? 0) + 1;
|
||||
r.total++;
|
||||
colTotals[w.length] = (colTotals[w.length] ?? 0) + 1;
|
||||
}
|
||||
const rows = [...byLetter.values()].sort((a, b) => a.letter.localeCompare(b.letter));
|
||||
return { lengths, rows, colTotals, total: left.length };
|
||||
}
|
||||
|
||||
// Two-letter starts of the missing answers → [{ pre, n }] alphabetical.
|
||||
export function twoLetterStarts(answers, found) {
|
||||
const m = new Map();
|
||||
for (const w of answers) if (!found.has(w)) m.set(w.slice(0, 2), (m.get(w.slice(0, 2)) ?? 0) + 1);
|
||||
return [...m.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([pre, n]) => ({ pre, n }));
|
||||
}
|
||||
|
||||
// A missing answer to nudge toward: prefers pangrams nobody's found, then the
|
||||
// shortest words (the easiest "oh, of course"). `nudged` = words already nudged.
|
||||
export function pickNudge(answers, found, nudged = [], rng = Math.random) {
|
||||
const pool = answers.filter((w) => !found.has(w) && !nudged.includes(w));
|
||||
if (!pool.length) return null;
|
||||
const pans = pool.filter(isPangram);
|
||||
if (pans.length && !nudged.some(isPangram)) return pans[Math.floor(rng() * pans.length)];
|
||||
const minLen = Math.min(...pool.map((w) => w.length));
|
||||
const short = pool.filter((w) => w.length <= minLen + 1);
|
||||
return short[Math.floor(rng() * short.length)];
|
||||
}
|
||||
|
||||
// "TR·····" — the first two letters and a dot per hidden letter.
|
||||
export function nudgeText(word) {
|
||||
return word.slice(0, 2) + '·'.repeat(Math.max(0, word.length - 2));
|
||||
}
|
||||
|
||||
// ── Saves ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const SAVE_KEY = 'spellingbee-save';
|
||||
const SAVE_VERSION = 1;
|
||||
|
||||
const isWordList = (a) => Array.isArray(a) && a.every((w) => typeof w === 'string' && /^[A-Z]{4,}$/.test(w));
|
||||
|
||||
export function serialiseSave(s) {
|
||||
return JSON.stringify({
|
||||
v: SAVE_VERSION,
|
||||
difficulty: s.difficulty,
|
||||
daily: s.daily ?? null,
|
||||
puzzle: {
|
||||
id: s.puzzle.id, center: s.puzzle.center, outer: s.puzzle.outer, letters: s.puzzle.letters,
|
||||
answers: s.puzzle.answers, bonus: s.puzzle.bonus, maxScore: s.puzzle.maxScore,
|
||||
},
|
||||
found: [...s.found],
|
||||
nudged: s.nudged ?? [],
|
||||
hintsUsed: s.hintsUsed ?? 0,
|
||||
geniusAt: s.geniusAt ?? null,
|
||||
queen: !!s.queen,
|
||||
elapsed: Math.round(s.elapsed ?? 0),
|
||||
savedAt: s.savedAt ?? Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
// The save object (with `found` as a Set and `score` recomputed), or null when
|
||||
// missing, corrupt, from another version, or already finished.
|
||||
export function parseSave(json) {
|
||||
if (!json) return null;
|
||||
let s;
|
||||
try { s = JSON.parse(json); } catch { return null; }
|
||||
if (!s || s.v !== SAVE_VERSION || !DIFFS.includes(s.difficulty)) return null;
|
||||
const p = s.puzzle;
|
||||
if (!p || typeof p.center !== 'string' || !/^[A-Z]$/.test(p.center)) return null;
|
||||
if (!Array.isArray(p.letters) || p.letters.length !== 7 || !p.letters.includes(p.center)) return null;
|
||||
if (!Array.isArray(p.outer) || p.outer.length !== 6 || p.outer.some((l) => !p.letters.includes(l) || l === p.center)) return null;
|
||||
if (!isWordList(p.answers) || !isWordList(p.bonus) || !p.answers.length) return null;
|
||||
if (!isWordList(s.found)) return null;
|
||||
const valid = new Set([...p.answers, ...p.bonus]);
|
||||
const found = new Set(s.found.filter((w) => valid.has(w)));
|
||||
if (s.queen || p.answers.every((w) => found.has(w))) return null; // nothing left to resume
|
||||
if (s.daily != null && !/^\d{4}-\d{2}-\d{2}$/.test(s.daily)) s.daily = null;
|
||||
return {
|
||||
current: tiers[currentIdx],
|
||||
next: tiers[currentIdx + 1] ?? null,
|
||||
isGenius: currentIdx === tiers.length - 1,
|
||||
difficulty: s.difficulty,
|
||||
daily: s.daily ?? null,
|
||||
puzzle: { ...p, maxScore: p.answers.reduce((t, w) => t + scoreWord(w), 0) },
|
||||
found,
|
||||
score: [...found].reduce((t, w) => t + scoreWord(w), 0),
|
||||
nudged: isWordList(s.nudged) ? s.nudged : [],
|
||||
hintsUsed: Number.isInteger(s.hintsUsed) && s.hintsUsed >= 0 ? s.hintsUsed : 0,
|
||||
geniusAt: Number.isFinite(s.geniusAt) ? s.geniusAt : null,
|
||||
queen: false,
|
||||
elapsed: Number.isFinite(s.elapsed) && s.elapsed >= 0 ? s.elapsed : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Daily Hive ────────────────────────────────────────────────────────────────
|
||||
|
||||
export const DAILY_KEY = 'spellingbee-daily';
|
||||
export const DAILY_DIFFICULTY = 'normal';
|
||||
|
||||
export function todayString(d = new Date()) { return localDateString(d); }
|
||||
export function dailySeed(date) { return dateSeed(`spellingbee:${date}`); }
|
||||
|
||||
export function prevDate(date) {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return localDateString(new Date(y, m - 1, d - 1));
|
||||
}
|
||||
|
||||
// best: { [date]: { score, rank, queen } } for the last 60 Daily Hives.
|
||||
export function blankDaily() { return { lastDate: null, streak: 0, bestStreak: 0, best: {} }; }
|
||||
|
||||
// Record progress on the Daily for `date`, played on `today`. Reaching Genius
|
||||
// on the day itself extends the streak. → { rec, streak }
|
||||
export function updateDaily(rec, date, today, { score, rank, genius = false, queen = false }) {
|
||||
const r = { ...blankDaily(), ...(rec ?? {}), best: { ...(rec?.best ?? {}) } };
|
||||
const old = r.best[date];
|
||||
if (!old || score > old.score || (queen && !old.queen)) {
|
||||
r.best[date] = { score: Math.max(score, old?.score ?? 0), rank, queen: queen || !!old?.queen };
|
||||
}
|
||||
if (genius && date === today && r.lastDate !== today) {
|
||||
r.streak = r.lastDate === prevDate(today) ? r.streak + 1 : 1;
|
||||
r.lastDate = today;
|
||||
r.bestStreak = Math.max(r.bestStreak, r.streak);
|
||||
}
|
||||
const keys = Object.keys(r.best).sort();
|
||||
for (const k of keys.slice(0, Math.max(0, keys.length - 60))) delete r.best[k];
|
||||
return { rec: r, streak: dailyStreakNow(r, today) };
|
||||
}
|
||||
|
||||
// The streak still alive today: a Genius today or yesterday keeps it.
|
||||
export function dailyStreakNow(rec, today) {
|
||||
if (!rec?.lastDate) return 0;
|
||||
return rec.lastDate === today || rec.lastDate === prevDate(today) ? rec.streak : 0;
|
||||
}
|
||||
|
||||
// "Thursday, November 26" for a YYYY-MM-DD string.
|
||||
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}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,32 +1,59 @@
|
|||
// Spelling Bee engine: NYT-style honeycomb puzzle generation.
|
||||
// Pure logic — no Express. Initialized once at server start from the ENABLE list.
|
||||
// Spelling Bee engine: honeycomb puzzle generation. Pure logic — no Phaser.
|
||||
//
|
||||
// A puzzle is 7 distinct letters (one "center" required in every word) built
|
||||
// around a pangram (a word using all 7 letters). Valid words are length >= 4,
|
||||
// contain the center letter, and use only the 7 puzzle letters (repeats allowed).
|
||||
// The letter S is excluded (NYT convention) to avoid trivial plurals.
|
||||
// A hive is 7 distinct letters (one "center" required in every word) built
|
||||
// around a pangram (a word using all 7 letters). Words are 4+ letters, contain
|
||||
// the center, and use only the hive's letters (repeats allowed). S never
|
||||
// appears (it would turn every noun into two words).
|
||||
//
|
||||
// Two kinds of word are ACCEPTED:
|
||||
// answers words on the curated list (data/wordlists/spellingbee-answers.txt,
|
||||
// built by tools/buildBeeWords.js) at the difficulty's tier. Only
|
||||
// these count toward the goal / Queen Bee, and `maxScore` is theirs.
|
||||
// bonus every other ENABLE word that fits. Points, a "Rare find!" stamp,
|
||||
// never required — knowing obscure words helps but can't block you.
|
||||
//
|
||||
// Instead of rolling random letter sets and hoping, the engine indexes every
|
||||
// ENABLE word by its letter mask and scores every (pangram set × center)
|
||||
// combination up front by enumerating the 128 submasks of each set. Each
|
||||
// difficulty then draws from its own pre-filtered pool, so every hive has a
|
||||
// known pangram and a sensible number of common answers. A numeric seed makes
|
||||
// the draw deterministic (the Daily Hive).
|
||||
//
|
||||
// initSpellingBeeDictionary(enableWords, answersText) → stats
|
||||
// generatePuzzle(difficulty, { seed? }) → puzzle (see bottom)
|
||||
// catalogueStats() → pool sizes per difficulty (verify tool)
|
||||
|
||||
const MIN_LEN = 4;
|
||||
const A_CODE = 'A'.charCodeAt(0);
|
||||
const A_CODE = 65;
|
||||
const S_BIT = 1 << ('S'.charCodeAt(0) - A_CODE);
|
||||
const Q_BIT = 1 << ('Q'.charCodeAt(0) - A_CODE);
|
||||
const U_BIT = 1 << ('U'.charCodeAt(0) - A_CODE);
|
||||
|
||||
// Difficulty target bands for the valid-word count (smaller pool = harder).
|
||||
const BANDS = {
|
||||
easy: { min: 40, max: 90 },
|
||||
normal: { min: 20, max: 45 },
|
||||
hard: { min: 10, max: 25 },
|
||||
export const TIER = { core: 0, familiar: 1, rare: 2 };
|
||||
|
||||
// Per-difficulty puzzle shape. `tier` = the highest answer tier that counts
|
||||
// (Easy counts only core words; familiar ones become bonus words there).
|
||||
// `answers` = allowed answer-count band. `minAvgLen` pushes Hard toward longer
|
||||
// words. The goal (how much of it you must find) lives in SpellingBeeLogic.
|
||||
export const DIFFICULTY = {
|
||||
easy: { tier: TIER.core, answers: [18, 30], minAvgLen: 0 },
|
||||
normal: { tier: TIER.familiar, answers: [28, 45], minAvgLen: 0 },
|
||||
hard: { tier: TIER.familiar, answers: [40, 65], minAvgLen: 5.4 },
|
||||
};
|
||||
// No suffix may account for more than this share of a hive's answers — an
|
||||
// E/D or I/N/G hive turns into "add -ED to everything".
|
||||
const MAX_SUFFIX_SHARE = 0.34;
|
||||
|
||||
let words = []; // [{ w, mask }] — candidate words (len>=4, no S, <=7 distinct)
|
||||
let pangramMasks = []; // distinct 7-letter masks that have at least one pangram
|
||||
let byMask = new Map(); // letter mask → [{ w, tier }]
|
||||
let pangramSets = []; // 7-letter masks with at least one answer-tier pangram
|
||||
let catalogue = null; // lazily built: { easy: [...], normal: [...], hard: [...] }
|
||||
let dictStats = { words: 0, answers: 0, pangramSets: 0 };
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function wordMask(w) {
|
||||
let mask = 0;
|
||||
for (let i = 0; i < w.length; i++) {
|
||||
mask |= 1 << (w.charCodeAt(i) - A_CODE);
|
||||
}
|
||||
for (let i = 0; i < w.length; i++) mask |= 1 << (w.charCodeAt(i) - A_CODE);
|
||||
return mask;
|
||||
}
|
||||
|
||||
|
|
@ -38,103 +65,194 @@ function popcount(n) {
|
|||
|
||||
function maskLetters(mask) {
|
||||
const letters = [];
|
||||
for (let i = 0; i < 26; i++) {
|
||||
if (mask & (1 << i)) letters.push(String.fromCharCode(A_CODE + i));
|
||||
}
|
||||
for (let i = 0; i < 26; i++) if (mask & (1 << i)) letters.push(String.fromCharCode(A_CODE + i));
|
||||
return letters;
|
||||
}
|
||||
|
||||
function shuffle(arr) {
|
||||
// Mulberry32 — the same generator the Sudoku/Tectonic engines use for seeds.
|
||||
function makeRng(seed) {
|
||||
let a = seed >>> 0;
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
function shuffle(arr, rand) {
|
||||
for (let i = arr.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
const j = Math.floor(rand() * (i + 1));
|
||||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
// Scoring (mirrors the client SpellingBeeLogic): 4 letters = 1 pt; longer words
|
||||
// = 1 pt per letter; pangram (uses all 7 distinct letters) earns a +7 bonus.
|
||||
function scoreWord(w, isPangram) {
|
||||
let s = w.length === 4 ? 1 : w.length;
|
||||
if (isPangram) s += 7;
|
||||
return s;
|
||||
// Scoring (mirrors SpellingBeeLogic.scoreWord): 4 letters = 1 pt; longer words
|
||||
// = 1 pt per letter; a pangram (all 7 letters) earns +7.
|
||||
export function scoreWord(w, isPangram) {
|
||||
return (w.length === 4 ? 1 : w.length) + (isPangram ? 7 : 0);
|
||||
}
|
||||
|
||||
// ── Initialization ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function initSpellingBeeDictionary(rawWords) {
|
||||
words = [];
|
||||
const seenPangram = new Set();
|
||||
pangramMasks = [];
|
||||
|
||||
for (const raw of rawWords) {
|
||||
const w = String(raw).toUpperCase();
|
||||
if (w.length < MIN_LEN || !/^[A-Z]+$/.test(w)) continue;
|
||||
const mask = wordMask(w);
|
||||
if (mask & S_BIT) continue; // S is excluded from puzzles entirely
|
||||
const distinct = popcount(mask);
|
||||
if (distinct > 7) continue; // can never fit a 7-letter puzzle
|
||||
words.push({ w, mask });
|
||||
if (distinct === 7 && !seenPangram.has(mask)) {
|
||||
seenPangram.add(mask);
|
||||
pangramMasks.push(mask);
|
||||
// `enableWords`: the ENABLE list (any case). `answersText`: the curated list,
|
||||
// `WORD<TAB>core|familiar` per line (null → every ENABLE word is an answer,
|
||||
// which keeps the game playable if the file is missing).
|
||||
export function initSpellingBeeDictionary(enableWords, answersText = null) {
|
||||
const tierOf = new Map();
|
||||
if (answersText) {
|
||||
for (const line of String(answersText).split('\n')) {
|
||||
const [w, t] = line.trim().split('\t');
|
||||
if (w) tierOf.set(w.toUpperCase(), t === 'core' ? TIER.core : TIER.familiar);
|
||||
}
|
||||
}
|
||||
return { words: words.length, pangrams: pangramMasks.length };
|
||||
const fallbackTier = tierOf.size ? TIER.rare : TIER.core;
|
||||
|
||||
byMask = new Map();
|
||||
catalogue = null;
|
||||
const pangramTier = new Map(); // 7-letter mask → best (lowest) pangram tier
|
||||
let count = 0, answers = 0;
|
||||
for (const raw of enableWords) {
|
||||
const w = String(raw).trim().toUpperCase();
|
||||
if (w.length < MIN_LEN || !/^[A-Z]+$/.test(w)) continue;
|
||||
const mask = wordMask(w);
|
||||
if (mask & S_BIT) continue;
|
||||
const distinct = popcount(mask);
|
||||
if (distinct > 7) continue;
|
||||
const tier = tierOf.get(w) ?? fallbackTier;
|
||||
let list = byMask.get(mask);
|
||||
if (!list) byMask.set(mask, (list = []));
|
||||
list.push({ w, tier });
|
||||
count++;
|
||||
if (tier < TIER.rare) answers++;
|
||||
if (distinct === 7) pangramTier.set(mask, Math.min(pangramTier.get(mask) ?? TIER.rare, tier));
|
||||
}
|
||||
pangramSets = [...pangramTier.entries()]
|
||||
.filter(([, t]) => t < TIER.rare)
|
||||
.map(([mask, t]) => ({ mask, tier: t }))
|
||||
.sort((a, b) => a.mask - b.mask);
|
||||
dictStats = { words: count, answers, pangramSets: pangramSets.length };
|
||||
return { ...dictStats };
|
||||
}
|
||||
|
||||
// ── Catalogue ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// Every word a hive accepts, split by tier relative to `maxTier`.
|
||||
function collect(puzzleMask, centerBit, maxTier) {
|
||||
const answers = [], bonus = [];
|
||||
for (let s = puzzleMask; s; s = (s - 1) & puzzleMask) {
|
||||
if (!(s & centerBit)) continue;
|
||||
const list = byMask.get(s);
|
||||
if (!list) continue;
|
||||
for (const e of list) (e.tier <= maxTier ? answers : bonus).push(e.w);
|
||||
}
|
||||
return { answers, bonus };
|
||||
}
|
||||
|
||||
// Shape numbers for one hive at one answer tier — cheap enough to run for
|
||||
// every combination (no word lists kept).
|
||||
function measure(puzzleMask, centerBit, maxTier) {
|
||||
let n = 0, pangrams = 0, letters = 0, ed = 0, ing = 0, er = 0;
|
||||
for (let s = puzzleMask; s; s = (s - 1) & puzzleMask) {
|
||||
if (!(s & centerBit)) continue;
|
||||
const list = byMask.get(s);
|
||||
if (!list) continue;
|
||||
for (const e of list) {
|
||||
if (e.tier > maxTier) continue;
|
||||
n++;
|
||||
letters += e.w.length;
|
||||
if (s === puzzleMask) pangrams++;
|
||||
if (e.w.endsWith('ED')) ed++;
|
||||
else if (e.w.endsWith('ING')) ing++;
|
||||
else if (e.w.endsWith('ER')) er++;
|
||||
}
|
||||
}
|
||||
return { n, pangrams, avgLen: n ? letters / n : 0, suffixShare: n ? Math.max(ed, ing, er) / n : 0 };
|
||||
}
|
||||
|
||||
function buildCatalogue() {
|
||||
const pools = { easy: [], normal: [], hard: [] };
|
||||
for (const { mask } of pangramSets) {
|
||||
if ((mask & Q_BIT) && !(mask & U_BIT)) continue; // Q without U is a trap
|
||||
for (let b = 0; b < 26; b++) {
|
||||
const centerBit = 1 << b;
|
||||
if (!(mask & centerBit)) continue;
|
||||
const byTier = {};
|
||||
for (const [diff, spec] of Object.entries(DIFFICULTY)) {
|
||||
const m = byTier[spec.tier] ?? (byTier[spec.tier] = measure(mask, centerBit, spec.tier));
|
||||
if (!m.pangrams) continue; // the pangram must be an answer
|
||||
if (m.n < spec.answers[0] || m.n > spec.answers[1]) continue;
|
||||
if (m.avgLen < spec.minAvgLen) continue;
|
||||
if (m.suffixShare > MAX_SUFFIX_SHARE) continue;
|
||||
pools[diff].push({ mask, centerBit, n: m.n });
|
||||
}
|
||||
}
|
||||
}
|
||||
return pools;
|
||||
}
|
||||
|
||||
function ensureCatalogue() {
|
||||
if (!catalogue) catalogue = buildCatalogue();
|
||||
return catalogue;
|
||||
}
|
||||
|
||||
export function catalogueStats() {
|
||||
const c = ensureCatalogue();
|
||||
return { ...dictStats, pools: Object.fromEntries(Object.entries(c).map(([k, v]) => [k, v.length])) };
|
||||
}
|
||||
|
||||
// ── Puzzle generation ───────────────────────────────────────────────────────────
|
||||
|
||||
function buildPuzzle(puzzleMask, centerBit) {
|
||||
const validWords = [];
|
||||
const pangrams = [];
|
||||
let maxScore = 0;
|
||||
const notMask = ~puzzleMask;
|
||||
for (const { w, mask } of words) {
|
||||
if ((mask & notMask) !== 0) continue; // uses a letter outside the puzzle
|
||||
if ((mask & centerBit) === 0) continue; // missing the center letter
|
||||
const isPangram = mask === puzzleMask; // a <=7-distinct word filling all 7
|
||||
validWords.push(w);
|
||||
if (isPangram) pangrams.push(w);
|
||||
maxScore += scoreWord(w, isPangram);
|
||||
}
|
||||
return { validWords, pangrams, maxScore };
|
||||
}
|
||||
// Returns:
|
||||
// { id, difficulty, seed, center, outer[6], letters[7],
|
||||
// answers[], bonus[], pangrams[] (answer pangrams), bonusPangrams[],
|
||||
// validWords[] (answers ∪ bonus), maxScore (answers only) }
|
||||
export function generatePuzzle(difficulty = 'normal', { seed = null } = {}) {
|
||||
const diff = DIFFICULTY[difficulty] ? difficulty : 'normal';
|
||||
const spec = DIFFICULTY[diff];
|
||||
const empty = { id: '', difficulty: diff, seed, center: '', outer: [], letters: [], answers: [], bonus: [],
|
||||
pangrams: [], bonusPangrams: [], validWords: [], maxScore: 0 };
|
||||
if (!pangramSets.length) return empty;
|
||||
|
||||
export function generatePuzzle(difficulty = 'normal') {
|
||||
const band = BANDS[difficulty] ?? BANDS.normal;
|
||||
if (!pangramMasks.length) {
|
||||
return { center: '', outer: [], letters: [], validWords: [], pangrams: [], maxScore: 0 };
|
||||
const rand = seed != null ? makeRng(seed) : Math.random;
|
||||
const pools = ensureCatalogue();
|
||||
let pool = pools[diff];
|
||||
// A thin or missing word list can empty a band; fall back to the nearest one.
|
||||
if (!pool.length) pool = pools.normal.length ? pools.normal : (pools.easy.length ? pools.easy : pools.hard);
|
||||
let pick;
|
||||
if (pool.length) {
|
||||
pick = pool[Math.floor(rand() * pool.length)];
|
||||
} else {
|
||||
const set = pangramSets[Math.floor(rand() * pangramSets.length)].mask;
|
||||
const bits = maskLetters(set).map((l) => 1 << (l.charCodeAt(0) - A_CODE));
|
||||
pick = { mask: set, centerBit: bits[Math.floor(rand() * bits.length)] };
|
||||
}
|
||||
|
||||
let best = null;
|
||||
for (let attempt = 0; attempt < 40; attempt++) {
|
||||
const puzzleMask = pangramMasks[Math.floor(Math.random() * pangramMasks.length)];
|
||||
const letters = maskLetters(puzzleMask);
|
||||
const center = letters[Math.floor(Math.random() * letters.length)];
|
||||
const centerBit = 1 << (center.charCodeAt(0) - A_CODE);
|
||||
const letters = maskLetters(pick.mask);
|
||||
const center = String.fromCharCode(A_CODE + Math.log2(pick.centerBit));
|
||||
const { answers, bonus } = collect(pick.mask, pick.centerBit, spec.tier);
|
||||
answers.sort();
|
||||
bonus.sort();
|
||||
const isPan = (w) => wordMask(w) === pick.mask;
|
||||
const pangrams = answers.filter(isPan);
|
||||
const bonusPangrams = bonus.filter(isPan);
|
||||
const maxScore = answers.reduce((s, w) => s + scoreWord(w, isPan(w)), 0);
|
||||
const outer = shuffle(letters.filter((l) => l !== center), rand);
|
||||
|
||||
const { validWords, pangrams, maxScore } = buildPuzzle(puzzleMask, centerBit);
|
||||
const candidate = { center, letters, validWords, pangrams, maxScore };
|
||||
|
||||
// Track the best-so-far by closeness to the band midpoint, as a fallback.
|
||||
if (!best || Math.abs(validWords.length - (band.min + band.max) / 2)
|
||||
< Math.abs(best.validWords.length - (band.min + band.max) / 2)) {
|
||||
best = candidate;
|
||||
}
|
||||
if (validWords.length >= band.min && validWords.length <= band.max) {
|
||||
best = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const outer = shuffle(best.letters.filter((l) => l !== best.center));
|
||||
return {
|
||||
center: best.center,
|
||||
id: `${letters.join('')}-${center}`,
|
||||
difficulty: diff,
|
||||
seed,
|
||||
center,
|
||||
outer,
|
||||
letters: best.letters,
|
||||
validWords: best.validWords,
|
||||
pangrams: best.pangrams,
|
||||
maxScore: best.maxScore,
|
||||
letters,
|
||||
answers,
|
||||
bonus,
|
||||
pangrams,
|
||||
bonusPangrams,
|
||||
validWords: [...answers, ...bonus].sort(),
|
||||
maxScore,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ let answerPool = null; // string[] — shuffleable answer list
|
|||
// `raw` is the ENABLE word list text, `commonRaw` the frequency list text (may be
|
||||
// null), `crosswordBank` the parsed minicrossword.json array. All fetched by the
|
||||
// caller (initWords) — this stays synchronous so the engines initialize in order.
|
||||
function loadWordLists(raw, commonRaw, crosswordBank) {
|
||||
function loadWordLists(raw, commonRaw, crosswordBank, beeAnswersRaw = null) {
|
||||
if (allFiveLetterWords) return;
|
||||
|
||||
if (!raw) {
|
||||
|
|
@ -156,9 +156,10 @@ function loadWordLists(raw, commonRaw, crosswordBank) {
|
|||
initBoggleDictionary(boggleWords);
|
||||
console.log(`[words] loaded ${boggleWords.length} Boggle words (3–16 letters)`);
|
||||
|
||||
// Spelling Bee dictionary: ENABLE words of length 4+, no S, ≤7 distinct letters.
|
||||
const beeStats = initSpellingBeeDictionary(allWords);
|
||||
console.log(`[words] loaded ${beeStats.words} Spelling Bee words (${beeStats.pangrams} pangram sets)`);
|
||||
// Spelling Bee dictionary: ENABLE words of length 4+, no S, ≤7 distinct
|
||||
// letters, tiered by the curated answer list (spellingbee-answers.txt).
|
||||
const beeStats = initSpellingBeeDictionary(allWords, beeAnswersRaw);
|
||||
console.log(`[words] loaded ${beeStats.words} Spelling Bee words (${beeStats.answers} answers, ${beeStats.pangramSets} pangram sets)`);
|
||||
|
||||
// Mini Crossword: curated puzzle bank, 5x5/6x6/7x7 by difficulty (independent of the ENABLE list).
|
||||
const crosswordStats = initMiniCrosswordPuzzles(crosswordBank);
|
||||
|
|
@ -210,12 +211,13 @@ let readyPromise = null;
|
|||
export function initWords() {
|
||||
if (readyPromise) return readyPromise;
|
||||
readyPromise = (async () => {
|
||||
const [enableRaw, commonRaw, crosswordBank] = await Promise.all([
|
||||
const [enableRaw, commonRaw, crosswordBank, beeAnswersRaw] = await Promise.all([
|
||||
fetch(dataUrl('wordlists/enable1.txt')).then(r => (r.ok ? r.text() : '')).catch(() => ''),
|
||||
fetch(dataUrl('wordlists/common.txt')).then(r => (r.ok ? r.text() : null)).catch(() => null),
|
||||
fetch(dataUrl('crosswords/minicrossword.json')).then(r => (r.ok ? r.json() : [])).catch(() => []),
|
||||
fetch(dataUrl('wordlists/spellingbee-answers.txt')).then(r => (r.ok ? r.text() : null)).catch(() => null),
|
||||
]);
|
||||
loadWordLists(enableRaw, commonRaw, crosswordBank);
|
||||
loadWordLists(enableRaw, commonRaw, crosswordBank, beeAnswersRaw);
|
||||
})();
|
||||
return readyPromise;
|
||||
}
|
||||
|
|
@ -260,13 +262,15 @@ router.get('/boggle/start', (_req, res) => {
|
|||
|
||||
// ── Spelling Bee ────────────────────────────────────────────────────────────────
|
||||
|
||||
// GET /api/words/spellingbee/start?difficulty=easy|normal|hard
|
||||
// GET /api/words/spellingbee/start?difficulty=easy|normal|hard[&seed=uint32]
|
||||
// Builds a honeycomb puzzle (7 letters incl. a required center) and returns it
|
||||
// with the full valid-word list so the client validates locally.
|
||||
// with its answer + bonus word lists so the client validates locally. A seed
|
||||
// makes the hive deterministic (the Daily Hive).
|
||||
router.get('/spellingbee/start', (req, res) => {
|
||||
const VALID = ['easy', 'normal', 'hard'];
|
||||
const difficulty = VALID.includes(req.query.difficulty) ? req.query.difficulty : 'normal';
|
||||
res.json(spellingBeeGenerate(difficulty));
|
||||
const seed = req.query.seed != null && /^\d+$/.test(String(req.query.seed)) ? Number(req.query.seed) : null;
|
||||
res.json(spellingBeeGenerate(difficulty, { seed }));
|
||||
});
|
||||
|
||||
// ── Mini Crossword ────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -0,0 +1,191 @@
|
|||
// Builds data/wordlists/spellingbee-answers.txt — the curated ANSWER list the
|
||||
// Spelling Bee generator builds puzzles from (see src/words/spellingBeeEngine.js).
|
||||
//
|
||||
// Every ENABLE word that fits a hive is still ACCEPTED in-game; this list only
|
||||
// decides which words COUNT toward the goal (and which pangrams a puzzle may be
|
||||
// built around). Words not on it become "Rare Finds" — bonus points, never
|
||||
// required. Output lines are `WORD<TAB>tier`:
|
||||
// core everyday words (Easy hives use only these)
|
||||
// familiar words most adults know (Normal + Hard add these)
|
||||
//
|
||||
// Tiering is ENABLE ∩ the Norvig web word-frequency list, with length-aware rank
|
||||
// cutoffs, plus an inflection rule: PATTED / RACING / HAPPILY rank low on the web
|
||||
// but their bases (PAT, RACE, HAPPY) are common, so they're promoted. Frequency
|
||||
// lists are web text, so names and junk leak through (GLORIA, FRANKLIN, ANON):
|
||||
// data/wordlists/spellingbee-deny.txt removes them and spellingbee-allow.txt
|
||||
// forces words in (one `WORD` or `WORD core` per line; the deny file takes any
|
||||
// number of words per line). Both are hand-editable — edit, rerun.
|
||||
//
|
||||
// Usage: node tools/buildBeeWords.js [--freq path/to/count_1w.txt]
|
||||
// [--suspects path/to/names.txt ...]
|
||||
// --freq cached copy of https://norvig.com/ngrams/count_1w.txt (otherwise
|
||||
// downloaded to the OS temp dir and cached there)
|
||||
// --suspects print answer words that also appear in the given name lists and
|
||||
// aren't yet in the deny/allow files — review them by hand.
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const LISTS = path.join(__dirname, '../data/wordlists');
|
||||
const ENABLE_PATH = path.join(LISTS, 'enable1.txt');
|
||||
const DENY_PATH = path.join(LISTS, 'spellingbee-deny.txt');
|
||||
const ALLOW_PATH = path.join(LISTS, 'spellingbee-allow.txt');
|
||||
const OUT_PATH = path.join(LISTS, 'spellingbee-answers.txt');
|
||||
const FREQ_URL = 'https://norvig.com/ngrams/count_1w.txt';
|
||||
|
||||
const A_CODE = 65;
|
||||
const S_BIT = 1 << ('S'.charCodeAt(0) - A_CODE);
|
||||
|
||||
// Rank cutoffs (0-based rank in the Norvig list) by word length. Longer words
|
||||
// are naturally rarer on the web, so their bar is looser. 4-letter words are
|
||||
// where web junk concentrates (abbreviations, names), so they're strictest.
|
||||
const CORE_CUTOFF = { 4: 20000, 5: 32000, 6: 42000, 7: 50000, default: 60000 };
|
||||
const FAMILIAR_CUTOFF = { 4: 32000, 5: 60000, 6: 85000, 7: 95000, default: 100000 };
|
||||
// A base word this common promotes its inflections (core base → familiar
|
||||
// inflection; very common base → core inflection).
|
||||
const BASE_CORE = 8000;
|
||||
const BASE_FAMILIAR = 20000;
|
||||
// …and the inflected form must still turn up on the web at least this often.
|
||||
const PROMOTE_MAX_RANK = 200000;
|
||||
|
||||
const cut = (table, len) => table[len] ?? table.default;
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function argValues(flag) {
|
||||
const out = [];
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
if (process.argv[i] === flag) {
|
||||
for (let j = i + 1; j < process.argv.length && !process.argv[j].startsWith('--'); j++) out.push(process.argv[j]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function wordMask(w) {
|
||||
let m = 0;
|
||||
for (let i = 0; i < w.length; i++) m |= 1 << (w.charCodeAt(i) - A_CODE);
|
||||
return m;
|
||||
}
|
||||
function popcount(n) { let c = 0; while (n) { n &= n - 1; c++; } return c; }
|
||||
|
||||
// Bee-eligible: 4+ letters, A–Z only, no S, at most 7 distinct letters.
|
||||
function beeEligible(w) {
|
||||
if (w.length < 4 || !/^[A-Z]+$/.test(w)) return false;
|
||||
const m = wordMask(w);
|
||||
return !(m & S_BIT) && popcount(m) <= 7;
|
||||
}
|
||||
|
||||
// Candidate base words for an inflected form (PATTED → PAT, RACING → RACE,
|
||||
// HAPPILY → HAPPY, BIGGEST → BIG). Returns every plausible base; the caller
|
||||
// keeps the most common one that exists.
|
||||
function baseCandidates(w, enable) {
|
||||
const out = [];
|
||||
// No bare -Y (LINE → LINY) and no -ER agent nouns (HAY → HAYER, HONE → HONER):
|
||||
// both are ENABLE-legal but mostly words nobody says.
|
||||
const SUFFIXES = ['ING', 'ED', 'EST', 'LY', 'IER', 'IEST', 'ILY', 'NESS', 'FUL', 'MENT', 'ABLE'];
|
||||
for (const suf of SUFFIXES) {
|
||||
if (!w.endsWith(suf) || w.length - suf.length < 3) continue;
|
||||
const stem = w.slice(0, -suf.length);
|
||||
// A consonant-vowel-consonant stem would have doubled its last letter
|
||||
// (LAD → LADDED), so when stem+E is a word the base is that (LADED → LADE,
|
||||
// BARED → BARE), never the short stem.
|
||||
if ((suf === 'ED' || suf === 'ING' || suf === 'EST') && /[^AEIOU][AEIOU][^AEIOUWXY]$/.test(stem)
|
||||
&& enable.has(stem + 'E')) {
|
||||
out.push(stem + 'E');
|
||||
continue;
|
||||
}
|
||||
out.push(stem); // jumped → jump
|
||||
out.push(stem + 'E'); // racing → race
|
||||
if (suf.startsWith('I')) out.push(stem + 'Y'); // happier → happy
|
||||
const n = stem.length;
|
||||
if (n >= 3 && stem[n - 1] === stem[n - 2]) out.push(stem.slice(0, -1)); // patted → pat
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readList(file) {
|
||||
if (!fs.existsSync(file)) return [];
|
||||
return fs.readFileSync(file, 'utf8').split('\n')
|
||||
.map((l) => l.replace(/#.*/, '').trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
async function loadFreq() {
|
||||
const given = argValues('--freq')[0];
|
||||
if (given) return fs.readFileSync(given, 'utf8');
|
||||
const cache = path.join(os.tmpdir(), 'count_1w.txt');
|
||||
if (fs.existsSync(cache)) return fs.readFileSync(cache, 'utf8');
|
||||
console.log('Downloading frequency list...');
|
||||
const text = await (await fetch(FREQ_URL, { redirect: 'follow' })).text();
|
||||
fs.writeFileSync(cache, text);
|
||||
return text;
|
||||
}
|
||||
|
||||
// ── main ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
const enable = new Set(
|
||||
fs.readFileSync(ENABLE_PATH, 'utf8').split('\n').map((w) => w.trim().toUpperCase()).filter(Boolean),
|
||||
);
|
||||
const rank = new Map();
|
||||
(await loadFreq()).split('\n').forEach((line, i) => {
|
||||
const w = line.split('\t')[0]?.toUpperCase();
|
||||
if (w && /^[A-Z]+$/.test(w) && !rank.has(w)) rank.set(w, i);
|
||||
});
|
||||
|
||||
const deny = new Set(readList(DENY_PATH).flatMap((l) => l.split(/\s+/)).map((w) => w.toUpperCase()));
|
||||
const allow = new Map();
|
||||
for (const l of readList(ALLOW_PATH)) {
|
||||
const [w, tier] = l.split(/\s+/);
|
||||
allow.set(w.toUpperCase(), tier === 'core' ? 'core' : 'familiar');
|
||||
}
|
||||
|
||||
const tiers = new Map(); // word → 'core' | 'familiar'
|
||||
for (const w of enable) {
|
||||
if (!beeEligible(w) || deny.has(w)) continue;
|
||||
const r = rank.get(w) ?? Infinity;
|
||||
let tier = null;
|
||||
if (r < cut(CORE_CUTOFF, w.length)) tier = 'core';
|
||||
else if (r < cut(FAMILIAR_CUTOFF, w.length)) tier = 'familiar';
|
||||
|
||||
// Promotion needs the word itself to appear somewhere in the web list —
|
||||
// an inflection nobody ever writes (COWY, DOGY) isn't familiar.
|
||||
if (tier !== 'core' && r < PROMOTE_MAX_RANK) {
|
||||
let best = Infinity;
|
||||
for (const b of baseCandidates(w, enable)) {
|
||||
if (b !== w && enable.has(b) && !deny.has(b)) best = Math.min(best, rank.get(b) ?? Infinity);
|
||||
}
|
||||
if (best < BASE_CORE && r < cut(FAMILIAR_CUTOFF, w.length) * 2) tier = 'core';
|
||||
else if (best < BASE_FAMILIAR && !tier) tier = 'familiar';
|
||||
}
|
||||
if (tier) tiers.set(w, tier);
|
||||
}
|
||||
for (const [w, tier] of allow) {
|
||||
if (!enable.has(w)) { console.warn(`allow: ${w} is not in ENABLE — skipped`); continue; }
|
||||
if (!beeEligible(w)) { console.warn(`allow: ${w} can't appear in a hive (S / <4 / >7 letters) — skipped`); continue; }
|
||||
tiers.set(w, tier);
|
||||
}
|
||||
|
||||
const words = [...tiers.keys()].sort();
|
||||
fs.writeFileSync(OUT_PATH, words.map((w) => `${w}\t${tiers.get(w)}`).join('\n') + '\n');
|
||||
const counts = { core: 0, familiar: 0 };
|
||||
for (const t of tiers.values()) counts[t]++;
|
||||
console.log(`Wrote ${words.length} answer words to ${path.relative(process.cwd(), OUT_PATH)}`, counts);
|
||||
|
||||
const nameFiles = argValues('--suspects');
|
||||
if (nameFiles.length) {
|
||||
const names = new Set();
|
||||
for (const f of nameFiles) {
|
||||
for (const n of fs.readFileSync(f, 'utf8').split(/\r?\n/)) if (n.trim()) names.add(n.trim().toUpperCase());
|
||||
}
|
||||
const suspects = words.filter((w) => names.has(w) && !allow.has(w));
|
||||
console.log(`\n${suspects.length} answer words also appear in the name lists (review → deny or allow):`);
|
||||
console.log(suspects.map((w) => `${w}:${tiers.get(w)[0]}${rank.get(w) ?? '-'}`).join(' '));
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
|
|
@ -0,0 +1,426 @@
|
|||
#!/usr/bin/env node
|
||||
// verifySpellingBee.js — headless checks for "The Apiary" Spelling Bee: the
|
||||
// curated answer list, the puzzle catalogue (every hive has an answer pangram,
|
||||
// answer counts inside each mode's band, answers/bonus split, seeded Daily
|
||||
// determinism), the goal tuning (how many words Genius takes per mode), rank
|
||||
// ladder + the difficulty-aware rankFor fix, word checking, hints, saves, the
|
||||
// Daily streak, layout, art bakes against a strict fake 2D context, and a
|
||||
// stubbed-Phaser smoke run of the play flow (find → Genius → Queen Bee).
|
||||
// Usage: node tools/verifySpellingBee.js [--quick] [--samples]
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
initSpellingBeeDictionary, generatePuzzle, catalogueStats, DIFFICULTY, scoreWord as engineScore,
|
||||
} from '../src/words/spellingBeeEngine.js';
|
||||
import {
|
||||
GOAL, MODES, DIFFS, isPangram, scoreWord, checkWord, geniusScore, buildTiers, rankFor, wordsToGo,
|
||||
hintGrid, twoLetterStarts, pickNudge, nudgeText, serialiseSave, parseSave,
|
||||
dailySeed, prevDate, updateDaily, dailyStreakNow, blankDaily, longDate,
|
||||
} from '../src/games/spellingbee/SpellingBeeLogic.js';
|
||||
import {
|
||||
W, H, HIVE, HEX_R, HEX_D, INPUT_Y, FEEDBACK_Y, CONTROLS_Y, JAR, LEDGER, LEDGER_LIST, LEDGER_BONUS_Y, CARD, OVERLAY_CARD,
|
||||
} from '../src/games/spellingbee/SpellingBeeArt.js';
|
||||
|
||||
const QUICK = process.argv.includes('--quick');
|
||||
const SAMPLES = process.argv.includes('--samples');
|
||||
const DRAWS = QUICK ? 150 : 600;
|
||||
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}`);
|
||||
const q = (a, ps = [0.1, 0.5, 0.9]) => { const s = [...a].sort((x, y) => x - y); return ps.map((p) => s[Math.floor(p * (s.length - 1))]); };
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const LISTS = path.join(__dirname, '../data/wordlists');
|
||||
const enableRaw = fs.readFileSync(path.join(LISTS, 'enable1.txt'), 'utf8');
|
||||
const enable = new Set(enableRaw.split('\n').map((w) => w.trim().toUpperCase()).filter(Boolean));
|
||||
const answersRaw = fs.readFileSync(path.join(LISTS, 'spellingbee-answers.txt'), 'utf8');
|
||||
const denyRaw = fs.readFileSync(path.join(LISTS, 'spellingbee-deny.txt'), 'utf8');
|
||||
|
||||
// ── Answer list ───────────────────────────────────────────────────────────────
|
||||
section('Answer list');
|
||||
const tierOf = new Map();
|
||||
{
|
||||
let badLine = 0, notEnable = 0, notBee = 0;
|
||||
for (const line of answersRaw.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
const [w, t] = line.split('\t');
|
||||
if (!/^[A-Z]+$/.test(w) || !['core', 'familiar'].includes(t)) { badLine++; continue; }
|
||||
if (!enable.has(w)) notEnable++;
|
||||
if (w.length < 4 || w.includes('S') || new Set(w).size > 7) notBee++;
|
||||
tierOf.set(w, t);
|
||||
}
|
||||
ok('every line is WORD<TAB>core|familiar', badLine === 0, `${badLine} bad lines`);
|
||||
ok('every answer is an ENABLE word', notEnable === 0, `${notEnable} not in ENABLE`);
|
||||
ok('every answer can appear in a hive', notBee === 0, `${notBee} ineligible`);
|
||||
const core = [...tierOf.values()].filter((t) => t === 'core').length;
|
||||
ok('a healthy list (core ≥ 8k, total ≥ 12k)', core >= 8000 && tierOf.size >= 12000, `${core} core / ${tierOf.size}`);
|
||||
const deny = new Set(denyRaw.split('\n').map((l) => l.replace(/#.*/, '')).join(' ').split(/\s+/).filter(Boolean));
|
||||
const leaked = [...deny].filter((w) => tierOf.has(w));
|
||||
ok('no denied word is an answer', leaked.length === 0, leaked.slice(0, 8).join(' '));
|
||||
for (const w of ['ALAN', 'ANNA', 'DONNA', 'APOLLO', 'GLORIA', 'FRANKLIN']) ok(`name "${w}" is not an answer`, !tierOf.has(w));
|
||||
for (const w of ['APPLE', 'GARDEN', 'MOTHER', 'BREAD', 'HONEY', 'BEACH']) ok(`everyday "${w}" is core`, tierOf.get(w) === 'core');
|
||||
}
|
||||
|
||||
// ── Engine / catalogue ────────────────────────────────────────────────────────
|
||||
section('Engine & catalogue');
|
||||
const stats = initSpellingBeeDictionary(enableRaw.split('\n'), answersRaw);
|
||||
const t0 = Date.now();
|
||||
const cat = catalogueStats();
|
||||
const catMs = Date.now() - t0;
|
||||
console.log(` dictionary ${stats.words} words, ${stats.answers} answers, ${stats.pangramSets} pangram sets; pools ${JSON.stringify(cat.pools)} (${catMs} ms)`);
|
||||
ok('catalogue builds quickly (< 1.5 s)', catMs < 1500, `${catMs} ms`);
|
||||
for (const d of DIFFS) ok(`${d}: pool has ≥ 500 hives`, cat.pools[d] >= 500, String(cat.pools[d]));
|
||||
ok('engine and client agree on modes', DIFFS.every((d) => DIFFICULTY[d] && MODES[d] && GOAL[d]));
|
||||
|
||||
const byDiff = {};
|
||||
for (const d of DIFFS) {
|
||||
const spec = DIFFICULTY[d];
|
||||
const list = [];
|
||||
let probs = [];
|
||||
for (let i = 0; i < DRAWS; i++) {
|
||||
const p = generatePuzzle(d);
|
||||
list.push(p);
|
||||
const letters = new Set(p.letters);
|
||||
if (p.letters.length !== 7 || letters.size !== 7) probs.push('letters');
|
||||
if (p.letters.includes('S')) probs.push('S');
|
||||
if (p.outer.length !== 6 || p.outer.includes(p.center) || !p.outer.every((l) => letters.has(l))) probs.push('outer');
|
||||
if (!p.pangrams.length) probs.push('no answer pangram');
|
||||
if (p.answers.length < spec.answers[0] || p.answers.length > spec.answers[1]) probs.push(`band ${p.answers.length}`);
|
||||
const all = [...p.answers, ...p.bonus];
|
||||
if (new Set(all).size !== all.length) probs.push('answers∩bonus');
|
||||
for (const w of all) {
|
||||
if (!enable.has(w)) { probs.push(`not ENABLE ${w}`); break; }
|
||||
if (!w.includes(p.center) || [...w].some((c) => !letters.has(c)) || w.length < 4) { probs.push(`invalid ${w}`); break; }
|
||||
}
|
||||
for (const w of p.answers) {
|
||||
const t = tierOf.get(w);
|
||||
if (!t || (spec.tier === 0 && t !== 'core')) { probs.push(`tier ${w}`); break; }
|
||||
}
|
||||
if (p.maxScore !== p.answers.reduce((s, w) => s + scoreWord(w), 0)) probs.push('maxScore');
|
||||
if (p.answers.some((w) => engineScore(w, new Set(w).size === 7) !== scoreWord(w))) probs.push('score mismatch');
|
||||
if (p.validWords.length !== all.length) probs.push('validWords');
|
||||
if ((p.letters.includes('Q') && !p.letters.includes('U'))) probs.push('Q without U');
|
||||
}
|
||||
probs = [...new Set(probs)];
|
||||
ok(`${d}: ${DRAWS} hives all well-formed`, probs.length === 0, probs.slice(0, 6).join('; '));
|
||||
byDiff[d] = list;
|
||||
}
|
||||
{
|
||||
const a = generatePuzzle('normal', { seed: 12345 });
|
||||
const b = generatePuzzle('normal', { seed: 12345 });
|
||||
const c = generatePuzzle('normal', { seed: 12346 });
|
||||
ok('same seed → same hive', a.id === b.id && a.outer.join('') === b.outer.join('') && a.answers.join() === b.answers.join());
|
||||
ok('different seeds → (almost always) different hives', a.id !== c.id || a.outer.join('') !== c.outer.join(''));
|
||||
const ids = new Set();
|
||||
for (let d = 1; d <= 60; d++) ids.add(generatePuzzle('normal', { seed: dailySeed(`2026-12-${String(d % 31 + 1).padStart(2, '0')}`) + d }).id);
|
||||
ok('daily seeds spread over many hives', ids.size >= 50, `${ids.size}/60 distinct`);
|
||||
}
|
||||
|
||||
// ── Goal tuning ───────────────────────────────────────────────────────────────
|
||||
section('Goal tuning (words needed for Genius)');
|
||||
const TARGET = { easy: [8, 13], normal: [16, 25], hard: [30, 42] };
|
||||
{
|
||||
const rows = [];
|
||||
for (const d of DIFFS) {
|
||||
const rnd = [], shortFirst = [], answers = [], bonus = [];
|
||||
for (const p of byDiff[d]) {
|
||||
const pts = p.answers.map(scoreWord);
|
||||
const goal = geniusScore(p.maxScore, d);
|
||||
let acc = 0;
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const o = [...pts].sort(() => Math.random() - 0.5);
|
||||
let s = 0, n = 0; while (s < goal) s += o[n++]; acc += n;
|
||||
}
|
||||
rnd.push(Math.round(acc / 4));
|
||||
const o = [...pts].sort((a, b) => a - b);
|
||||
let s = 0, n = 0; while (s < goal) s += o[n++];
|
||||
shortFirst.push(n);
|
||||
answers.push(p.answers.length);
|
||||
bonus.push(p.bonus.length);
|
||||
}
|
||||
const [r10, r50, r90] = q(rnd), [s10, s50, s90] = q(shortFirst);
|
||||
rows.push(` ${d.padEnd(6)} answers ${q(answers).join('/')} bonus ${q(bonus).join('/')} Genius ${Math.round(GOAL[d] * 100)}% → words (random order) ${r10}/${r50}/${r90}, (short words first) ${s10}/${s50}/${s90}`);
|
||||
const mid = (r50 + s50) / 2;
|
||||
ok(`${d}: typical words-to-Genius in ${TARGET[d].join('–')}`, mid >= TARGET[d][0] && mid <= TARGET[d][1], `mid ${mid}`);
|
||||
}
|
||||
console.log(rows.join('\n'));
|
||||
console.log(' (before this overhaul: answers were every ENABLE word; only ~1/3 were common words and the pangram was a common word in < 10% of hives)');
|
||||
const med = (d) => q(byDiff[d].map((p) => p.answers.length))[1];
|
||||
ok('harder modes have more words to find', med('easy') < med('normal') && med('normal') < med('hard'));
|
||||
}
|
||||
|
||||
if (SAMPLES || QUICK) {
|
||||
section('Sample hives');
|
||||
for (const d of DIFFS) for (const p of byDiff[d].slice(0, SAMPLES ? 5 : 1)) {
|
||||
console.log(` ${d} ${p.center}/${p.letters.join('')} pangram ${p.pangrams.join(',')} ${p.answers.length} answers: ${p.answers.join(' ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Ranks ─────────────────────────────────────────────────────────────────────
|
||||
section('Ranks');
|
||||
{
|
||||
for (const d of DIFFS) {
|
||||
const t = buildTiers(200, d);
|
||||
ok(`${d}: thresholds rise`, t.every((x, i) => i === 0 || x.threshold >= t[i - 1].threshold) && t[0].threshold === 0);
|
||||
ok(`${d}: Genius threshold = goal`, t.at(-1).threshold === geniusScore(200, d) && t.at(-1).name === 'Genius');
|
||||
}
|
||||
ok('Genius line moves with difficulty', geniusScore(200, 'easy') < geniusScore(200, 'normal') && geniusScore(200, 'normal') < geniusScore(200, 'hard'));
|
||||
const g = geniusScore(200, 'easy');
|
||||
ok('rankFor respects difficulty (the old bug)', rankFor(g, 200, 'easy').isGenius && !rankFor(g, 200, 'hard').isGenius);
|
||||
ok('rankFor below Genius', !rankFor(g - 1, 200, 'easy').isGenius && rankFor(g - 1, 200, 'easy').next?.name === 'Genius');
|
||||
ok('rankFor at zero = Beginner', rankFor(0, 200, 'normal').current.name === 'Beginner');
|
||||
const ans = ['ABLE', 'TABLE', 'BLEAT', 'BALLET'];
|
||||
ok('wordsToGo = 0 once there', wordsToGo(50, 40, ans, new Set()) === 0);
|
||||
ok('wordsToGo estimates', wordsToGo(0, 10, ans, new Set()) >= 1 && wordsToGo(0, 10, ans, new Set()) <= 4);
|
||||
}
|
||||
|
||||
// ── Scoring & checking ────────────────────────────────────────────────────────
|
||||
section('Scoring & word check');
|
||||
{
|
||||
ok('4 letters = 1', scoreWord('ABLE') === 1);
|
||||
ok('5 letters = 5', scoreWord('TABLE') === 5);
|
||||
ok('pangram +7', isPangram('PLAYTIME') === false && isPangram('BETRAYAL') && scoreWord('BETRAYAL') === 8 + 7);
|
||||
const st = { center: 'A', letters: ['A', 'B', 'L', 'E', 'T', 'R', 'Y'], answers: new Set(['TABLE', 'BETRAY']), bonus: new Set(['ABLER']), found: new Set(['BETRAY']) };
|
||||
ok('too short', checkWord('TAB', st).reason === 'Too short');
|
||||
ok('bad letters', checkWord('TABLES', st).reason === 'Bad letters');
|
||||
ok('missing center', checkWord('BYTE', st).reason === 'Missing center letter');
|
||||
ok('already found', checkWord('betray', st).reason === 'Already found' && checkWord('BETRAY', st).tone === 'muted');
|
||||
ok('not in list', checkWord('BLART', st).reason === 'Not in word list');
|
||||
const a = checkWord('TABLE', st), b = checkWord('ABLER', st);
|
||||
ok('answer accepted', a.ok && a.kind === 'answer' && a.pts === 5);
|
||||
ok('bonus accepted', b.ok && b.kind === 'bonus' && b.pts === 5);
|
||||
}
|
||||
|
||||
// ── Hints ─────────────────────────────────────────────────────────────────────
|
||||
section('Hints');
|
||||
{
|
||||
const p = byDiff.normal[0];
|
||||
const found = new Set(p.answers.slice(0, 5));
|
||||
const left = p.answers.length - 5;
|
||||
const g = hintGrid(p.answers, found);
|
||||
ok('grid total = remaining answers', g.total === left && g.rows.reduce((s, r) => s + r.total, 0) === left);
|
||||
ok('grid column totals add up', Object.values(g.colTotals).reduce((a, b) => a + b, 0) === left);
|
||||
ok('grid rows are letters of the hive', g.rows.every((r) => p.letters.includes(r.letter)));
|
||||
ok('two-letter starts add up', twoLetterStarts(p.answers, found).reduce((s, x) => s + x.n, 0) === left);
|
||||
const n1 = pickNudge(p.answers, found, []);
|
||||
ok('first nudge prefers a pangram', isPangram(n1) || p.pangrams.every((w) => found.has(w)));
|
||||
const n2 = pickNudge(p.answers, found, [n1]);
|
||||
ok('nudges don\'t repeat', n2 && n2 !== n1 && !found.has(n2));
|
||||
ok('nudge text', nudgeText('TABLE') === 'TA···');
|
||||
ok('nothing to nudge when all found', pickNudge(['ABLE'], new Set(['ABLE'])) === null);
|
||||
}
|
||||
|
||||
// ── Saves ─────────────────────────────────────────────────────────────────────
|
||||
section('Saves');
|
||||
{
|
||||
const p = byDiff.hard[0];
|
||||
const found = new Set([p.answers[0], p.answers[1], ...(p.bonus.length ? [p.bonus[0]] : [])]);
|
||||
const json = serialiseSave({ difficulty: 'hard', daily: '2026-11-26', puzzle: p, found, nudged: [p.answers[2]], hintsUsed: 2, geniusAt: null });
|
||||
const s = parseSave(json);
|
||||
ok('round trip', s && s.difficulty === 'hard' && s.daily === '2026-11-26' && s.found.size === found.size && s.hintsUsed === 2);
|
||||
ok('score recomputed from found words', s.score === [...found].reduce((t, w) => t + scoreWord(w), 0));
|
||||
ok('maxScore recomputed', s.puzzle.maxScore === p.maxScore);
|
||||
ok('outer order kept', s.puzzle.outer.join('') === p.outer.join(''));
|
||||
ok('corrupt json → null', parseSave('{nope') === null && parseSave(null) === null);
|
||||
ok('wrong version → null', parseSave(JSON.stringify({ ...JSON.parse(json), v: 99 })) === null);
|
||||
ok('tampered letters → null', parseSave(JSON.stringify({ ...JSON.parse(json), puzzle: { ...JSON.parse(json).puzzle, center: 'S' } })) === null);
|
||||
const done = serialiseSave({ difficulty: 'hard', puzzle: p, found: new Set(p.answers) });
|
||||
ok('finished hive → nothing to resume', parseSave(done) === null);
|
||||
const junk = JSON.parse(json); junk.found.push('ZZZZ');
|
||||
ok('unknown found words dropped', parseSave(JSON.stringify(junk)).found.size === found.size);
|
||||
}
|
||||
|
||||
// ── Daily ─────────────────────────────────────────────────────────────────────
|
||||
section('Daily Hive');
|
||||
{
|
||||
ok('prevDate across a month', prevDate('2026-12-01') === '2026-11-30');
|
||||
ok('seed is stable', dailySeed('2026-11-26') === dailySeed('2026-11-26') && dailySeed('2026-11-26') !== dailySeed('2026-11-27'));
|
||||
let r = blankDaily();
|
||||
({ rec: r } = updateDaily(r, '2026-11-24', '2026-11-24', { score: 20, rank: 'Nice' }));
|
||||
ok('progress without Genius keeps streak at 0', r.streak === 0 && r.best['2026-11-24'].score === 20);
|
||||
({ rec: r } = updateDaily(r, '2026-11-24', '2026-11-24', { score: 90, rank: 'Genius', genius: true }));
|
||||
({ rec: r } = updateDaily(r, '2026-11-25', '2026-11-25', { score: 80, rank: 'Genius', genius: true }));
|
||||
ok('consecutive Genius days build a streak', r.streak === 2 && dailyStreakNow(r, '2026-11-26') === 2);
|
||||
ok('streak lapses after a missed day', dailyStreakNow(r, '2026-11-27') === 0);
|
||||
({ rec: r } = updateDaily(r, '2026-11-25', '2026-11-25', { score: 60, rank: 'Great' }));
|
||||
ok('best score is kept', r.best['2026-11-25'].score === 80);
|
||||
({ rec: r } = updateDaily(r, '2026-11-20', '2026-11-25', { score: 99, rank: 'Genius', genius: true }));
|
||||
ok('an old Daily doesn\'t move the streak', r.streak === 2);
|
||||
ok('longDate', longDate('2026-11-26') === 'Thursday, November 26');
|
||||
}
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────────
|
||||
section('Layout');
|
||||
{
|
||||
const half = HEX_R * Math.sqrt(3) / 2;
|
||||
const hiveTop = HIVE.y - HEX_D * Math.sin(Math.PI / 3) - HEX_R;
|
||||
const hiveBottom = HIVE.y + HEX_D * Math.sin(Math.PI / 3) + HEX_R;
|
||||
const hiveLeft = HIVE.x - HEX_D - half, hiveRight = HIVE.x + HEX_D + half;
|
||||
ok('cells sit flush (spacing ≥ 2 × apothem)', HEX_D >= HEX_R * Math.sqrt(3));
|
||||
ok('input line clears the hive', INPUT_Y + 36 < hiveTop && FEEDBACK_Y + 30 < INPUT_Y - 30);
|
||||
ok('controls clear the hive', CONTROLS_Y - 30 > hiveBottom);
|
||||
ok('jar + tick labels clear the hive', JAR.x + JAR.w / 2 + 90 < hiveLeft);
|
||||
ok('hive clears the ledger', hiveRight + 40 < LEDGER.x);
|
||||
ok('ledger fits the screen', LEDGER.x + LEDGER.w <= W && LEDGER.y + LEDGER.h <= H - 60);
|
||||
ok('ledger list fits ≥ 65 words in 4 columns', Math.floor(LEDGER_LIST.h / 30) * 4 >= 65);
|
||||
ok('ledger list ends above Rare finds', LEDGER_LIST.y + LEDGER_LIST.h <= LEDGER_BONUS_Y);
|
||||
ok('cards fit the screen', CARD.w < W && CARD.h < H && OVERLAY_CARD.w < W && OVERLAY_CARD.h < H);
|
||||
}
|
||||
|
||||
// ── Art bake (strict fake 2D context) ─────────────────────────────────────────
|
||||
section('Art bake');
|
||||
{
|
||||
const colourOk = (c) => typeof c === 'string' && /^(#[0-9a-f]{3,8}|rgba?\([^)]*\)|transparent)$/i.test(c.trim());
|
||||
const fin = (...a) => a.every(Number.isFinite);
|
||||
const errors = [];
|
||||
const check = (cond, what) => { if (!cond) errors.push(what); };
|
||||
const gradient = () => ({ addColorStop: (o, c) => { check(o >= 0 && o <= 1, `stop offset ${o}`); check(colourOk(c), `stop colour ${c}`); } });
|
||||
const makeCtx = () => new Proxy({}, {
|
||||
get(t, k) {
|
||||
if (k in t) return t[k];
|
||||
switch (k) {
|
||||
case 'createLinearGradient': return (...a) => { check(fin(...a), 'linear gradient coords'); return gradient(); };
|
||||
case 'createRadialGradient': return (x0, y0, r0, x1, y1, r1) => { check(fin(x0, y0, r0, x1, y1, r1) && r0 >= 0 && r1 >= 0, 'radial gradient'); return gradient(); };
|
||||
case 'createPattern': return () => ({ pattern: true });
|
||||
case 'createImageData': return (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) });
|
||||
case 'arc': return (x, y, r) => check(fin(x, y, r) && r >= 0, `arc r=${r}`);
|
||||
case 'ellipse': return (x, y, rx, ry) => check(fin(x, y, rx, ry) && rx >= 0 && ry >= 0, `ellipse ${rx},${ry}`);
|
||||
case 'moveTo': case 'lineTo': return (x, y) => check(fin(x, y), 'path point');
|
||||
case 'quadraticCurveTo': case 'bezierCurveTo': return (...a) => check(fin(...a), 'curve point');
|
||||
case 'fillRect': case 'strokeRect': case 'rect': return (...a) => check(fin(...a), 'rect');
|
||||
case 'drawImage': return (img, ...a) => check(img && fin(...a), 'drawImage');
|
||||
default: return () => {};
|
||||
}
|
||||
},
|
||||
set(t, k, v) {
|
||||
if ((k === 'fillStyle' || k === 'strokeStyle') && typeof v === 'string') check(colourOk(v), `${k} ${v}`);
|
||||
if (k === 'lineWidth' || k === 'globalAlpha') check(Number.isFinite(v) && v >= 0, `${k} ${v}`);
|
||||
t[k] = v; return true;
|
||||
},
|
||||
});
|
||||
const prevDoc = globalThis.document;
|
||||
globalThis.document = { createElement: () => { const ctx = makeCtx(); return { width: 0, height: 0, getContext: () => ctx }; } };
|
||||
const added = new Map();
|
||||
const scene = { textures: {
|
||||
exists: (k) => added.has(k) || k === 'spellingbee-bg',
|
||||
addCanvas: (k, c) => { added.set(k, c); return {}; },
|
||||
get: () => ({ getSourceImage: () => ({ width: 1920, height: 1080 }) }),
|
||||
} };
|
||||
try {
|
||||
const art = await import('../src/games/spellingbee/SpellingBeeArt.js');
|
||||
art.prepareBeeArt(scene);
|
||||
for (const k of ['bee-cell', 'bee-cell-center', 'bee-cell-shadow', 'bee-body', 'bee-wing', 'bee-jar', 'bee-ledger',
|
||||
'bee-card', 'bee-overlay-card', 'bee-vignette', 'bee-glow', 'bee-drip'])
|
||||
ok(`baked ${k}`, added.has(k));
|
||||
const size = added.size;
|
||||
art.prepareBeeArt(scene);
|
||||
ok('baking twice reuses the textures', added.size === size);
|
||||
ok('soft backdrop bakes', art.bakeSoftBackdrop(scene, 'spellingbee-bg') === 'bee-bg-soft' && added.has('bee-bg-soft'));
|
||||
} catch (err) {
|
||||
ok('art bake threw', false, err.stack);
|
||||
}
|
||||
ok('canvas calls all valid', errors.length === 0, [...new Set(errors)].slice(0, 6).join('; '));
|
||||
globalThis.document = prevDoc;
|
||||
}
|
||||
|
||||
// ── Scene smoke run (stubbed Phaser) ──────────────────────────────────────────
|
||||
section('Scene smoke run');
|
||||
{
|
||||
const mk = () => {
|
||||
const fn = function () { return proxy; };
|
||||
const proxy = new Proxy(fn, {
|
||||
get(t, k) {
|
||||
if (k === Symbol.toPrimitive) return () => 0;
|
||||
if (k === 'then') return undefined;
|
||||
if (k in t && typeof k === 'symbol') return t[k];
|
||||
return proxy;
|
||||
},
|
||||
apply() { return proxy; },
|
||||
set() { return true; },
|
||||
});
|
||||
return proxy;
|
||||
};
|
||||
const store = new Map();
|
||||
globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) };
|
||||
try {
|
||||
const { default: Game } = await import('../src/games/spellingbee/SpellingBeeGame.js');
|
||||
const sc = Object.create(Game.prototype);
|
||||
const stub = mk();
|
||||
const delayed = [];
|
||||
Object.assign(sc, {
|
||||
add: stub, make: stub, tweens: stub, sound: stub, cameras: stub, textures: stub, input: stub, events: stub, cache: stub, load: stub,
|
||||
sys: { isActive: () => true },
|
||||
time: { now: 0, delayedCall: (ms, f) => { delayed.push(f); return stub; } },
|
||||
scene: { restart: () => {}, start: () => {} },
|
||||
});
|
||||
const flush = () => { while (delayed.length) delayed.shift()(); };
|
||||
let geniusShown = 0, queenShown = 0;
|
||||
for (const m of ['buildHeader', 'buildJar', 'buildHive', 'buildInput', 'buildControls', 'buildLedger', 'buildBees',
|
||||
'renderInput', 'feedback', 'pangramFx', 'swarm', 'shakeInput', 'scatterBees', 'rankUp', 'flashLedgerWord', 'animatePress',
|
||||
'drawTicks', 'refreshLedger', 'addAnswerToLedger'])
|
||||
sc[m] = function () {};
|
||||
sc.showGenius = () => { geniusShown++; };
|
||||
sc.showQueenBee = () => { queenShown++; sc.mode = 'done'; };
|
||||
sc.postHistory = () => {};
|
||||
sc.inputChars = [];
|
||||
sc.cells = [];
|
||||
for (const k of ['rankText', 'scoreText', 'nextText', 'crown']) sc[k] = stub;
|
||||
|
||||
const p = generatePuzzle('easy', { seed: 4242 });
|
||||
sc.init({ game: { slug: 'spellingbee' } });
|
||||
sc.beginHive({ difficulty: 'easy', daily: null, puzzle: p, found: new Set(), score: 0, nudged: [], hintsUsed: 0, geniusAt: null });
|
||||
const type = (w) => { for (const c of w) sc.typeLetter(c); sc.submitWord(); flush(); };
|
||||
|
||||
type('ZZZZ');
|
||||
ok('a bad word scores nothing', sc.score === 0 && sc.found.size === 0);
|
||||
if (p.bonus.length) {
|
||||
type(p.bonus[0]);
|
||||
ok('a bonus word scores but isn\'t an answer', sc.found.has(p.bonus[0]) && sc.score === scoreWord(p.bonus[0]));
|
||||
}
|
||||
const before = sc.score;
|
||||
type(p.answers[0]);
|
||||
ok('an answer scores', sc.score === before + scoreWord(p.answers[0]));
|
||||
const saved = parseSave(store.get('spellingbee-save'));
|
||||
ok('progress autosaved', saved && saved.found.has(p.answers[0]) && saved.puzzle.id === p.id);
|
||||
type(p.answers[0]);
|
||||
ok('a repeat scores nothing', sc.score === before + scoreWord(p.answers[0]));
|
||||
|
||||
// Find answers (shortest first) until Genius.
|
||||
const order = [...p.answers].sort((a, b) => scoreWord(a) - scoreWord(b));
|
||||
for (const w of order) { if (sc.geniusAt != null) break; type(w); }
|
||||
ok('Genius fires once, at the goal', geniusShown === 1 && sc.score >= geniusScore(p.maxScore, 'easy'));
|
||||
const stats = JSON.parse(store.get('solitaire-stats-spellingbee') || '{}');
|
||||
ok('Genius recorded as a win under easy', stats.easy?.won === 1 && stats.easy?.played === 1);
|
||||
ok('save keeps going after Genius', parseSave(store.get('spellingbee-save'))?.geniusAt != null);
|
||||
for (const w of order) if (!sc.found.has(w)) type(w);
|
||||
ok('Queen Bee when every answer is found', queenShown === 1 && sc.queen === true);
|
||||
ok('Queen Bee clears the save', !store.has('spellingbee-save'));
|
||||
const st2 = JSON.parse(store.get('solitaire-stats-spellingbee'));
|
||||
ok('one hive = one game in the stats', st2.easy.played === 1 && st2.easy.counts?.queen === 1);
|
||||
ok('no Genius fired twice', geniusShown === 1);
|
||||
|
||||
// A hive closed before Genius counts as a loss.
|
||||
store.clear();
|
||||
const p2 = generatePuzzle('hard', { seed: 99 });
|
||||
sc.init({ game: { slug: 'spellingbee' } });
|
||||
sc.inputChars = []; sc.cells = [];
|
||||
for (const k of ['rankText', 'scoreText', 'nextText', 'crown']) sc[k] = stub;
|
||||
sc.showReveal = () => {};
|
||||
sc.beginHive({ difficulty: 'hard', daily: '2026-11-26', puzzle: p2, found: new Set(), score: 0, nudged: [], hintsUsed: 0, geniusAt: null });
|
||||
type(p2.answers[0]);
|
||||
ok('daily progress recorded', JSON.parse(store.get('spellingbee-daily')).best['2026-11-26']?.score === scoreWord(p2.answers[0]));
|
||||
sc.closeHive();
|
||||
const st3 = JSON.parse(store.get('solitaire-stats-spellingbee'));
|
||||
ok('closing early = a loss', st3.hard.played === 1 && st3.hard.won === 0 && !store.has('spellingbee-save'));
|
||||
} catch (err) {
|
||||
ok('scene smoke run threw', false, err.stack);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n${pass} passed, ${fail} failed`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
Loading…
Reference in New Issue