Redesign word search as "The Rail Edition" puzzle book

- Replace the plain grid UI with a train-carriage scene: baked carriage art, scrolling window view (clouds/far/mid/near/poles), tunnel dips, rail-bed audio, and a spiral-bound book with cover, contents page, and page-turn animation
- Add 15 themed chapters (space through castles) with per-chapter inks, fun-fact words, and secret-message phrases; the generator now packs words so leftover cells spell the message instead of random filler letters
- Introduce four ticket classes (Local/Express/Intercity/Sleeper), a seeded "Today's Route" daily with streak tracking, autosave/resume, hints, scoring, and stats per class and chapter
- Add Web Audio synths for pencil ticks, highlighter swipes, train whistle, letter pings, and the carriage rumble/clack bed (no audio files)
- Extend the server route to accept an optional seed and return ink, message, facts, and seed; move theme data to a shared module
- Add tools/verifyWordSearch.js covering chapter data, generator correctness/perf, selection machine, save/resume validation, daily streaks, layout, art bakes, and a stubbed-Phaser play-through
- Add new opponent convo speech files (juliet-croc/nadia/smasher, michael-bernie) and wire convo entries into opponents.json
This commit is contained in:
Brian Fertig 2026-11-26 11:21:04 -07:00
parent 5f2930c1e1
commit 0a421a3392
No known key found for this signature in database
13 changed files with 4338 additions and 497 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -548,7 +548,8 @@
"voice": "Djed Spence",
"convo": [
"terry",
"victor"
"victor",
"bernie"
],
"speech": {
"intro": [
@ -586,6 +587,11 @@
"citySheet": "classic",
"bio": "Let's take a break on a warm summer day to spend time playing games!",
"voice": "Street Fighter 6 - Crimson Viper",
"convo": [
"croc",
"nadia",
"smasher"
],
"speech": {
"intro": [
"juliet-intro-01",
@ -618,6 +624,8 @@
"startingTechs": [],
"citySheet": "mayan",
"bio": "Mystical Powers and a knack for games.",
"voice": "Antonio Bandaras",
"convo": [],
"speech": {
"intro": [
"balam-intro-01",

View File

@ -0,0 +1,955 @@
// Word Search art — the Rail Edition puzzle book on a train's tray table,
// baked to canvases (no image files).
//
// ws-carriage 1920×1080: tray table, the carriage wall and window frame
// (the glass is cut out so the scenery shows through)
// ws-sky the view's sky (static)
// ws-clouds / ws-far / ws-mid / ws-near / ws-poles
// seamless horizontal strips that scroll past the window
// ws-glass reflections over the window
// ws-spread the open spiral-bound book (two pages)
// ws-cover the closed book's cloth cover (right-hand half)
// ws-leaf one loose page, for page turns and the pause flap
// ws-ticket the punched ticket that shows chapter, class, time, hints
// ws-card a ticket card on the contents page
// ws-postcard the fun-fact postcard
// ws-summary the big ticket shown when a chapter is complete
// ws-cup / ws-steam / ws-pencil
// ws-doodle-<chapter> a small ink sketch for each chapter
//
// Also exports the layout constants and BookButton (a ticket-stub button).
import * as Phaser from 'phaser';
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
import { THEMES, CHAPTER_ORDER } from '../../words/wordSearchThemes.js';
// ── Layout ────────────────────────────────────────────────────────────────────
export const W = 1920, H = 1080;
export const BOOK = { x: 36, y: 40, w: 1440, h: 1004 };
export const SPINE_X = BOOK.x + BOOK.w / 2; // 756
export const GUTTER = 18; // half the ring gap
export const LEFT_PAGE = { x: BOOK.x, y: BOOK.y, w: BOOK.w / 2 - GUTTER, h: BOOK.h }; // 36..738
export const RIGHT_PAGE = { x: SPINE_X + GUTTER, y: BOOK.y, w: BOOK.w / 2 - GUTTER, h: BOOK.h }; // 774..1476
export const BOOK_PAD = 24; // shadow margin in book bakes
export const GRID_BOX = { x: 67, y: 168, w: 640, h: 640 };
export const LEFT_CX = LEFT_PAGE.x + LEFT_PAGE.w / 2; // 387
export const HEAD_Y = 96;
export const SUBHEAD_Y = 134;
export const MSG_BOX = { x: 70, y: 836, w: 634, h: 176 };
export const RIGHT_L = RIGHT_PAGE.x + 38; // 812
export const RIGHT_R = RIGHT_PAGE.x + RIGHT_PAGE.w - 34; // 1442
export const RIGHT_CX = RIGHT_PAGE.x + RIGHT_PAGE.w / 2; // 1125
export const TITLE_Y = 108;
export const LIST_BOX = { x: RIGHT_L, y: 228, w: RIGHT_R - RIGHT_L, h: 740 };
export const DOODLE = { x: RIGHT_R - 62, y: 120, size: 150 };
export const FOOT_Y = BOOK.y + BOOK.h - 30;
export const WINDOW = { x: 1522, y: 34, w: 368, h: 300 };
export const SILL_Y = WINDOW.y + WINDOW.h; // 334
export const TABLE_Y = 360;
export const CUP = { x: 1842, y: 470 };
export const TICKET = { x: 1640, y: 470, w: 240, h: 140 }; // centre
export const FACT = { x: 1708, y: 670, w: 392, h: 196 }; // centre
export const BTN = { xs: [1610, 1806], ys: [830, 906], w: 180, h: 60 };
export const SMALL_BTN = { xs: [1610, 1806], y: 986, w: 180, h: 46 };
export const SERIF = 'Georgia, "Times New Roman", "Liberation Serif", "DejaVu Serif", serif';
export const SANS = '"Trebuchet MS", Verdana, "DejaVu Sans", Arial, sans-serif';
export const INK = '#2a241c';
export const INK_N = 0x2a241c;
export const FADED = '#7a6f5e';
export const FADED_N = 0x7a6f5e;
export const GRAPHITE_N = 0x4a4d54;
export const RED_INK = '#a8322a';
export const RED_INK_N = 0xa8322a;
export const PAPER = '#f6f0df';
export const TICKET_INK = '#7b2f22';
export const TICKET_INK_N = 0x7b2f22;
// Highlighter pens, used in turn for found words.
export const HIGHLIGHTERS = [0xf5dd3c, 0xf59ac0, 0x96dc72, 0x86c8f0, 0xf6ad55, 0xc2a2ee];
let seed = 7;
const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
const jit = (a) => (rnd() - 0.5) * 2 * a;
const font = (px, weight = '', family = SERIF) => `${weight ? `${weight} ` : ''}${px}px ${family}`;
const hexA = (hex, a) => {
const n = parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
};
export const inkNum = (hex) => parseInt(String(hex).slice(1), 16);
// ── Carriage: tray table, wall, window frame ──────────────────────────────────
function woodGrain(ctx, x, y, w, h, base = ['#8b5a36', '#6d4427']) {
const g = ctx.createLinearGradient(0, y, 0, y + h);
g.addColorStop(0, base[0]); g.addColorStop(1, base[1]);
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
// long grain lines, gently wandering
for (let i = 0; i < 150; i++) {
let ly = y + rnd() * h;
const dark = rnd() < 0.6;
ctx.strokeStyle = dark ? `rgba(60,34,18,${0.08 + rnd() * 0.14})` : `rgba(200,150,100,${0.05 + rnd() * 0.08})`;
ctx.lineWidth = 0.6 + rnd() * 2.2;
ctx.beginPath();
ctx.moveTo(x, ly);
const amp = 2 + rnd() * 6, f = 0.002 + rnd() * 0.006, ph = rnd() * 6;
for (let px = x; px <= x + w; px += 24) {
ctx.lineTo(px, ly + Math.sin(px * f + ph) * amp);
}
ctx.stroke();
}
// a few knots
for (let k = 0; k < 5; k++) {
const kx = x + rnd() * w, ky = y + rnd() * h;
for (let r = 4; r < 34; r += 5) {
ctx.strokeStyle = `rgba(55,30,15,${0.16 - r * 0.004})`;
ctx.lineWidth = 1;
ctx.beginPath(); ctx.ellipse(kx, ky, r * 2.4, r * 0.7, 0, 0, Math.PI * 2); ctx.stroke();
}
}
ctx.fillStyle = noisePattern(ctx, 128, 14);
ctx.fillRect(x, y, w, h);
}
function bakeCarriage(scene) {
seed = 11;
const c = canvas(W, H);
const ctx = c.getContext('2d');
// the wall behind the table (only the top right shows past the book)
const wg = ctx.createLinearGradient(0, 0, 0, TABLE_Y);
wg.addColorStop(0, '#e6dcc0'); wg.addColorStop(1, '#d3c7a6');
ctx.fillStyle = wg;
ctx.fillRect(0, 0, W, TABLE_Y);
ctx.fillStyle = noisePattern(ctx, 96, 10);
ctx.fillRect(0, 0, W, TABLE_Y);
// fine pinstripe of the wall covering
for (let x = 0; x < W; x += 14) {
ctx.fillStyle = 'rgba(150,130,90,0.08)';
ctx.fillRect(x, 0, 2, TABLE_Y);
}
// the window: a deep rounded frame, rubber seal, then the cut-out glass
const { x: wx, y: wy, w: ww, h: wh } = WINDOW;
ctx.save();
ctx.shadowColor = 'rgba(40,30,15,0.35)'; ctx.shadowBlur = 14; ctx.shadowOffsetY = 4;
ctx.fillStyle = '#b9b3a6';
rr(ctx, wx - 22, wy - 20, ww + 44, wh + 34, 34); ctx.fill();
ctx.restore();
const fg = ctx.createLinearGradient(wx - 22, 0, wx + ww + 22, 0);
fg.addColorStop(0, '#d8d3c8'); fg.addColorStop(0.5, '#c4bfb2'); fg.addColorStop(1, '#a9a396');
ctx.fillStyle = fg;
rr(ctx, wx - 22, wy - 20, ww + 44, wh + 34, 34); ctx.fill();
ctx.fillStyle = '#2b2a28';
rr(ctx, wx - 7, wy - 7, ww + 14, wh + 14, 28); ctx.fill();
// the sill the window sits on
const sg = ctx.createLinearGradient(0, SILL_Y, 0, TABLE_Y);
sg.addColorStop(0, '#9a7048'); sg.addColorStop(1, '#6e4a2c');
ctx.fillStyle = sg;
ctx.fillRect(wx - 40, SILL_Y + 6, ww + 80, TABLE_Y - SILL_Y - 6);
ctx.fillStyle = 'rgba(255,230,190,0.25)';
ctx.fillRect(wx - 40, SILL_Y + 6, ww + 80, 3);
// the curtain, tied back at the left of the window
ctx.save();
const cx0 = wx - 44, cw = 46;
const cg = ctx.createLinearGradient(cx0, 0, cx0 + cw, 0);
cg.addColorStop(0, '#5a1f24'); cg.addColorStop(0.35, '#8a3038'); cg.addColorStop(0.7, '#6a242b'); cg.addColorStop(1, '#4a181c');
ctx.fillStyle = cg;
ctx.beginPath();
ctx.moveTo(cx0, 0); ctx.lineTo(cx0 + cw, 0);
ctx.quadraticCurveTo(cx0 + cw - 18, 170, cx0 + cw - 10, 230);
ctx.quadraticCurveTo(cx0 + cw + 6, 300, cx0 + cw - 4, SILL_Y + 4);
ctx.lineTo(cx0 - 6, SILL_Y + 4);
ctx.quadraticCurveTo(cx0 + 4, 300, cx0 + 6, 230);
ctx.closePath(); ctx.fill();
for (let k = 1; k < 4; k++) {
ctx.strokeStyle = 'rgba(30,8,10,0.35)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(cx0 + k * 11, 0); ctx.quadraticCurveTo(cx0 + k * 9, 160, cx0 + 14 + k * 4, 228); ctx.stroke();
}
ctx.fillStyle = '#c8a24a';
rr(ctx, cx0 - 4, 218, cw + 8, 16, 6); ctx.fill();
ctx.restore();
// luggage-rack shadow along the very top
const lg = ctx.createLinearGradient(0, 0, 0, 26);
lg.addColorStop(0, 'rgba(30,20,10,0.35)'); lg.addColorStop(1, 'rgba(30,20,10,0)');
ctx.fillStyle = lg; ctx.fillRect(0, 0, W, 26);
// the tray table
woodGrain(ctx, 0, TABLE_Y, W, H - TABLE_Y);
// far edge where the table meets the wall
const eg = ctx.createLinearGradient(0, TABLE_Y - 4, 0, TABLE_Y + 18);
eg.addColorStop(0, 'rgba(255,225,180,0.35)'); eg.addColorStop(0.3, 'rgba(60,35,18,0.45)'); eg.addColorStop(1, 'rgba(60,35,18,0)');
ctx.fillStyle = eg; ctx.fillRect(0, TABLE_Y - 4, W, 22);
// window light falling across the table from the right
const lightG = ctx.createRadialGradient(1760, 420, 40, 1700, 520, 900);
lightG.addColorStop(0, 'rgba(255,236,190,0.30)'); lightG.addColorStop(1, 'rgba(255,236,190,0)');
ctx.fillStyle = lightG; ctx.fillRect(0, TABLE_Y, W, H - TABLE_Y);
// vignette
const vg = ctx.createRadialGradient(W * 0.5, H * 0.55, 300, W * 0.5, H * 0.55, 1250);
vg.addColorStop(0, 'rgba(0,0,0,0)'); vg.addColorStop(1, 'rgba(20,10,4,0.55)');
ctx.fillStyle = vg; ctx.fillRect(0, 0, W, H);
// cut the glass out so the scenery layers show through
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = '#000000';
rr(ctx, wx, wy, ww, wh, 22); ctx.fill();
ctx.restore();
scene.textures.addCanvas('ws-carriage', c);
}
// ── The view from the window ─────────────────────────────────────────────────
export const STRIP_W = WINDOW.w * 2; // seamless strips are twice the window wide
// A periodic ridge line across the strip: sum of sines with whole periods.
function ridge(x, terms) {
let y = 0;
for (const [k, a, ph] of terms) y += a * Math.sin((x / STRIP_W) * Math.PI * 2 * k + ph);
return y;
}
function bakeSky(scene) {
const c = canvas(WINDOW.w, WINDOW.h);
const ctx = c.getContext('2d');
const g = ctx.createLinearGradient(0, 0, 0, WINDOW.h);
g.addColorStop(0, '#7fa9cf'); g.addColorStop(0.55, '#c9d9df'); g.addColorStop(0.75, '#f2dcb4'); g.addColorStop(1, '#f6caa0');
ctx.fillStyle = g; ctx.fillRect(0, 0, WINDOW.w, WINDOW.h);
const sun = ctx.createRadialGradient(WINDOW.w * 0.72, WINDOW.h * 0.5, 4, WINDOW.w * 0.72, WINDOW.h * 0.5, 160);
sun.addColorStop(0, 'rgba(255,248,220,0.95)'); sun.addColorStop(0.12, 'rgba(255,236,190,0.7)'); sun.addColorStop(1, 'rgba(255,220,160,0)');
ctx.fillStyle = sun; ctx.fillRect(0, 0, WINDOW.w, WINDOW.h);
scene.textures.addCanvas('ws-sky', c);
}
function bakeClouds(scene) {
seed = 41;
const c = canvas(STRIP_W, WINDOW.h);
const ctx = c.getContext('2d');
for (let i = 0; i < 9; i++) {
const cx = rnd() * STRIP_W, cy = 30 + rnd() * 90, s = 0.6 + rnd() * 0.9;
for (const off of [-STRIP_W, 0, STRIP_W]) {
for (let p = 0; p < 6; p++) {
const px = cx + off + (p - 2.5) * 22 * s + jit(6), py = cy + jit(6) * s;
const r = (20 + rnd() * 18) * s;
const g = ctx.createRadialGradient(px, py, 1, px, py, r);
g.addColorStop(0, 'rgba(255,255,255,0.75)'); g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g; ctx.fillRect(px - r, py - r, r * 2, r * 2);
}
}
}
scene.textures.addCanvas('ws-clouds', c);
}
function fillRidge(ctx, base, terms, colTop, colBot) {
const h = WINDOW.h;
ctx.beginPath();
ctx.moveTo(0, h);
for (let x = 0; x <= STRIP_W; x += 4) ctx.lineTo(x, base + ridge(x, terms));
ctx.lineTo(STRIP_W, h);
ctx.closePath();
const g = ctx.createLinearGradient(0, base - 40, 0, h);
g.addColorStop(0, colTop); g.addColorStop(1, colBot);
ctx.fillStyle = g; ctx.fill();
}
function bakeFar(scene) {
const c = canvas(STRIP_W, WINDOW.h);
const ctx = c.getContext('2d');
fillRidge(ctx, 170, [[2, 18, 0.4], [5, 9, 1.3], [11, 4, 2.2]], '#93a7bd', '#b9c3c4');
fillRidge(ctx, 196, [[3, 12, 2.0], [7, 6, 0.3], [13, 3, 1.1]], '#8ea58f', '#a9b59a');
scene.textures.addCanvas('ws-far', c);
}
// trees drawn across the seam so the strip tiles
function tree(ctx, x, y, s, col) {
for (const off of [-STRIP_W, 0, STRIP_W]) {
const tx = x + off;
if (tx < -60 || tx > STRIP_W + 60) continue;
ctx.fillStyle = 'rgba(60,40,20,0.8)';
ctx.fillRect(tx - 2 * s, y - 8 * s, 4 * s, 10 * s);
ctx.fillStyle = col;
ctx.beginPath(); ctx.arc(tx, y - 16 * s, 11 * s, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(tx - 7 * s, y - 11 * s, 8 * s, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(tx + 7 * s, y - 11 * s, 8 * s, 0, Math.PI * 2); ctx.fill();
}
}
function cottage(ctx, x, y, s) {
for (const off of [-STRIP_W, 0, STRIP_W]) {
const tx = x + off;
if (tx < -60 || tx > STRIP_W + 60) continue;
ctx.fillStyle = '#efe6d2'; ctx.fillRect(tx - 12 * s, y - 12 * s, 24 * s, 12 * s);
ctx.fillStyle = '#9a4b38';
ctx.beginPath(); ctx.moveTo(tx - 15 * s, y - 12 * s); ctx.lineTo(tx, y - 22 * s); ctx.lineTo(tx + 15 * s, y - 12 * s); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#4a5a6a'; ctx.fillRect(tx - 7 * s, y - 9 * s, 4 * s, 4 * s); ctx.fillRect(tx + 3 * s, y - 9 * s, 4 * s, 4 * s);
}
}
function bakeMid(scene) {
seed = 53;
const c = canvas(STRIP_W, WINDOW.h);
const ctx = c.getContext('2d');
const terms = [[2, 10, 1.7], [4, 7, 0.2], [9, 3, 2.9]];
fillRidge(ctx, 216, terms, '#a8c06e', '#7f9f4e');
// hedgerows and field lines
for (let k = 0; k < 4; k++) {
const by = 232 + k * 16;
ctx.strokeStyle = `rgba(60,90,40,${0.45 - k * 0.06})`; ctx.lineWidth = 3 - k * 0.4;
ctx.beginPath();
for (let x = 0; x <= STRIP_W; x += 6) {
const y = by + ridge(x, terms) * (0.6 - k * 0.1) + Math.sin(x / STRIP_W * Math.PI * 2 * (6 + k)) * 2;
if (x === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
ctx.stroke();
}
// golden field patches
for (let i = 0; i < 6; i++) {
const px = rnd() * STRIP_W, py = 236 + rnd() * 30;
for (const off of [-STRIP_W, 0, STRIP_W]) {
ctx.fillStyle = 'rgba(214,190,96,0.45)';
ctx.beginPath(); ctx.ellipse(px + off, py, 40 + rnd() * 30, 6, 0, 0, Math.PI * 2); ctx.fill();
}
}
for (let i = 0; i < 16; i++) {
const tx = rnd() * STRIP_W;
tree(ctx, tx, 214 + ridge(tx, terms) + 6 + rnd() * 6, 0.7 + rnd() * 0.4, rnd() < 0.5 ? '#4f7a38' : '#5f8a40');
}
for (let i = 0; i < 3; i++) {
const hx = rnd() * STRIP_W;
cottage(ctx, hx, 222 + ridge(hx, terms) + 4, 0.8 + rnd() * 0.3);
}
scene.textures.addCanvas('ws-mid', c);
}
function bakeNear(scene) {
seed = 67;
const c = canvas(STRIP_W, WINDOW.h);
const ctx = c.getContext('2d');
const terms = [[3, 8, 0.9], [8, 5, 2.4], [17, 2, 0.5]];
fillRidge(ctx, 270, terms, '#5d8a3a', '#3e6a28');
// trackside bushes
for (let i = 0; i < 26; i++) {
const bx = rnd() * STRIP_W, s = 0.9 + rnd() * 1.1;
for (const off of [-STRIP_W, 0, STRIP_W]) {
ctx.fillStyle = rnd() < 0.5 ? '#3f6e2a' : '#4a7a30';
ctx.beginPath(); ctx.arc(bx + off, 278 + ridge(bx, terms) * 0.5, 14 * s, Math.PI, 0); ctx.fill();
}
}
// the ballast verge right under the window
const bg = ctx.createLinearGradient(0, WINDOW.h - 26, 0, WINDOW.h);
bg.addColorStop(0, '#7d7366'); bg.addColorStop(1, '#5d554a');
ctx.fillStyle = bg; ctx.fillRect(0, WINDOW.h - 24, STRIP_W, 24);
ctx.fillStyle = noisePattern(ctx, 48, 60);
ctx.fillRect(0, WINDOW.h - 24, STRIP_W, 24);
scene.textures.addCanvas('ws-near', c);
}
// One telegraph pole per strip, wires sagging pole to pole across the seam.
function bakePoles(scene) {
const c = canvas(STRIP_W, WINDOW.h);
const ctx = c.getContext('2d');
const px = STRIP_W * 0.5, top = 40;
ctx.strokeStyle = 'rgba(30,24,20,0.75)'; ctx.lineWidth = 1.4;
for (const wy of [top + 14, top + 28]) {
for (const [x0, x1] of [[px - STRIP_W, px], [px, px + STRIP_W]]) {
ctx.beginPath(); ctx.moveTo(x0, wy);
ctx.quadraticCurveTo((x0 + x1) / 2, wy + 46, x1, wy);
ctx.stroke();
}
}
ctx.fillStyle = '#3b2c20';
ctx.fillRect(px - 5, top, 10, WINDOW.h - top);
ctx.fillRect(px - 26, top + 10, 52, 6);
ctx.fillRect(px - 22, top + 24, 44, 5);
ctx.fillStyle = '#d8d4c8';
for (const ix of [-22, -10, 10, 22]) ctx.fillRect(px + ix - 2, top + 5, 4, 6);
scene.textures.addCanvas('ws-poles', c);
}
function bakeGlass(scene) {
const c = canvas(WINDOW.w, WINDOW.h);
const ctx = c.getContext('2d');
ctx.save();
rr(ctx, 0, 0, WINDOW.w, WINDOW.h, 22); ctx.clip();
for (const [x, w, a] of [[40, 70, 0.09], [130, 22, 0.07], [250, 110, 0.05]]) {
ctx.fillStyle = `rgba(255,255,255,${a})`;
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x + w, 0); ctx.lineTo(x + w - 160, WINDOW.h); ctx.lineTo(x - 160, WINDOW.h); ctx.closePath(); ctx.fill();
}
const eg = ctx.createRadialGradient(WINDOW.w / 2, WINDOW.h / 2, WINDOW.h * 0.3, WINDOW.w / 2, WINDOW.h / 2, WINDOW.w * 0.75);
eg.addColorStop(0, 'rgba(0,0,0,0)'); eg.addColorStop(1, 'rgba(20,20,30,0.28)');
ctx.fillStyle = eg; ctx.fillRect(0, 0, WINDOW.w, WINDOW.h);
ctx.restore();
scene.textures.addCanvas('ws-glass', c);
}
// ── The book ─────────────────────────────────────────────────────────────────
function pageFill(ctx, x, y, w, h, gutterSide) {
ctx.fillStyle = PAPER;
ctx.fillRect(x, y, w, h);
const g = ctx.createRadialGradient(x + w / 2, y + h / 2, Math.min(w, h) * 0.3, x + w / 2, y + h / 2, Math.max(w, h) * 0.72);
g.addColorStop(0, 'rgba(255,252,240,0.3)'); g.addColorStop(1, 'rgba(180,150,100,0.16)');
ctx.fillStyle = g; ctx.fillRect(x, y, w, h);
for (let i = 0; i < (w * h) / 1100; i++) {
const fx = x + rnd() * w, fy = y + rnd() * h, a = rnd() * Math.PI;
ctx.strokeStyle = `rgba(130,110,80,${0.04 + rnd() * 0.05})`; ctx.lineWidth = 0.6;
ctx.beginPath(); ctx.moveTo(fx, fy); ctx.lineTo(fx + Math.cos(a) * 5, fy + Math.sin(a) * 5); ctx.stroke();
}
ctx.fillStyle = noisePattern(ctx, 96, 12);
ctx.fillRect(x, y, w, h);
// the curve of the page down into the binding
if (gutterSide) {
const gx = gutterSide === 'right' ? x + w : x;
const gg = ctx.createLinearGradient(gx, 0, gutterSide === 'right' ? gx - 70 : gx + 70, 0);
gg.addColorStop(0, 'rgba(90,70,40,0.30)'); gg.addColorStop(1, 'rgba(90,70,40,0)');
ctx.fillStyle = gg;
ctx.fillRect(gutterSide === 'right' ? gx - 70 : gx, y, 70, h);
}
// printed page border
ctx.strokeStyle = 'rgba(42,36,28,0.35)'; ctx.lineWidth = 1.2;
ctx.strokeRect(x + 16, y + 16, w - 32, h - 32);
ctx.strokeStyle = 'rgba(42,36,28,0.18)'; ctx.lineWidth = 0.8;
ctx.strokeRect(x + 21, y + 21, w - 42, h - 42);
}
// Holes punched along a page edge + the wire coils through them.
function spiral(ctx, sx, y0, y1, { coils = true } = {}) {
for (let y = y0; y <= y1; y += 34) {
for (const hx of [sx - GUTTER - 10, sx + GUTTER + 10]) {
ctx.fillStyle = 'rgba(40,30,20,0.85)';
ctx.beginPath(); ctx.ellipse(hx, y, 5, 4, 0, 0, Math.PI * 2); ctx.fill();
}
if (!coils) continue;
const g = ctx.createLinearGradient(0, y - 6, 0, y + 6);
g.addColorStop(0, '#f2f2f0'); g.addColorStop(0.5, '#9fa3a8'); g.addColorStop(1, '#5c6066');
ctx.strokeStyle = g; ctx.lineWidth = 4; ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(sx - GUTTER - 10, y + 1);
ctx.bezierCurveTo(sx - 10, y - 16, sx + 10, y - 16, sx + GUTTER + 10, y + 1);
ctx.stroke();
ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(sx - GUTTER - 6, y - 2);
ctx.bezierCurveTo(sx - 8, y - 15, sx + 8, y - 15, sx + GUTTER + 6, y - 2);
ctx.stroke();
}
}
function bakeSpread(scene) {
seed = 23;
const P = BOOK_PAD;
const c = canvas(BOOK.w + P * 2, BOOK.h + P * 2);
const ctx = c.getContext('2d');
const ox = P - BOOK.x, oy = P - BOOK.y;
ctx.save();
ctx.shadowColor = 'rgba(20,10,4,0.5)'; ctx.shadowBlur = 20; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 10;
ctx.fillStyle = '#d8cfb8';
ctx.fillRect(LEFT_PAGE.x + ox, BOOK.y + oy, LEFT_PAGE.w, BOOK.h);
ctx.fillRect(RIGHT_PAGE.x + ox, BOOK.y + oy, RIGHT_PAGE.w, BOOK.h);
ctx.restore();
// stacked page edges peeking out at the outer sides and bottom
for (let k = 4; k >= 1; k--) {
ctx.fillStyle = k % 2 ? '#e7dfca' : '#d9d0b8';
ctx.fillRect(LEFT_PAGE.x + ox - k * 1.5, BOOK.y + oy + k, LEFT_PAGE.w, BOOK.h);
ctx.fillRect(RIGHT_PAGE.x + ox + k * 1.5, BOOK.y + oy + k, RIGHT_PAGE.w, BOOK.h);
}
pageFill(ctx, LEFT_PAGE.x + ox, BOOK.y + oy, LEFT_PAGE.w, BOOK.h, 'right');
pageFill(ctx, RIGHT_PAGE.x + ox, BOOK.y + oy, RIGHT_PAGE.w, BOOK.h, 'left');
spiral(ctx, SPINE_X + ox, BOOK.y + oy + 30, BOOK.y + oy + BOOK.h - 30);
scene.textures.addCanvas('ws-spread', c);
}
function bakeLeaf(scene) {
seed = 29;
const c = canvas(LEFT_PAGE.w, BOOK.h);
const ctx = c.getContext('2d');
pageFill(ctx, 0, 0, LEFT_PAGE.w, BOOK.h, null);
scene.textures.addCanvas('ws-leaf', c);
}
// The little steam engine on the cover and tickets.
function locomotive(ctx, x, y, s, col, { lw = 3 } = {}) {
ctx.save();
ctx.translate(x, y); ctx.scale(s, s);
ctx.strokeStyle = col; ctx.lineWidth = lw / s; ctx.lineJoin = 'round'; ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(-60, 10); ctx.lineTo(-60, -26); ctx.lineTo(-30, -26); ctx.lineTo(-30, -10); // cab
ctx.moveTo(-66, -30); ctx.lineTo(-24, -30); // cab roof
ctx.moveTo(-30, -10); ctx.lineTo(40, -10); ctx.quadraticCurveTo(52, -10, 52, 2); ctx.lineTo(52, 10); // boiler
ctx.lineTo(-60, 10);
ctx.moveTo(26, -10); ctx.lineTo(24, -32); ctx.lineTo(36, -32); ctx.lineTo(34, -10); // chimney
ctx.moveTo(52, 10); ctx.lineTo(64, 18); // cow-catcher
ctx.stroke();
for (const [wx, r] of [[-44, 12], [-14, 9], [12, 9], [38, 9]]) {
ctx.beginPath(); ctx.arc(wx, 18, r, 0, Math.PI * 2); ctx.stroke();
}
ctx.beginPath(); ctx.moveTo(-44, 18); ctx.lineTo(38, 18); ctx.stroke();
// puffs
for (const [px, py, r] of [[34, -44, 7], [44, -56, 9], [58, -66, 11]]) {
ctx.beginPath(); ctx.arc(px, py, r, 0, Math.PI * 2); ctx.stroke();
}
ctx.restore();
}
function bakeCover(scene) {
seed = 31;
const P = BOOK_PAD;
const cw = RIGHT_PAGE.w + GUTTER, ch = BOOK.h;
const c = canvas(cw + P * 2, ch + P * 2);
const ctx = c.getContext('2d');
const x = P, y = P;
ctx.save();
ctx.shadowColor = 'rgba(20,10,4,0.55)'; ctx.shadowBlur = 22; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 12;
ctx.fillStyle = '#26402f';
rr(ctx, x, y, cw, ch, 10); ctx.fill();
ctx.restore();
const g = ctx.createLinearGradient(x, y, x + cw, y + ch);
g.addColorStop(0, '#2f4d39'); g.addColorStop(0.6, '#294533'); g.addColorStop(1, '#1f3628');
ctx.fillStyle = g;
rr(ctx, x, y, cw, ch, 10); ctx.fill();
// cloth weave
ctx.save();
rr(ctx, x, y, cw, ch, 10); ctx.clip();
for (let yy = y; yy < y + ch; yy += 3) { ctx.fillStyle = `rgba(255,255,255,${0.02 + rnd() * 0.025})`; ctx.fillRect(x, yy, cw, 1); }
for (let xx = x; xx < x + cw; xx += 3) { ctx.fillStyle = `rgba(0,0,0,${0.03 + rnd() * 0.03})`; ctx.fillRect(xx, y, 1, ch); }
ctx.fillStyle = noisePattern(ctx, 96, 22);
ctx.fillRect(x, y, cw, ch);
// worn corners
for (const [cx, cy] of [[x + cw, y], [x + cw, y + ch]]) {
const wg = ctx.createRadialGradient(cx, cy, 2, cx, cy, 90);
wg.addColorStop(0, 'rgba(210,200,170,0.25)'); wg.addColorStop(1, 'rgba(210,200,170,0)');
ctx.fillStyle = wg; ctx.fillRect(cx - 90, cy - 90, 180, 180);
}
ctx.restore();
// gold-blocked border + title
const gold = '#d9b65c';
const L = x + 66, R = x + cw - 40, T = y + 50, B = y + ch - 50;
ctx.strokeStyle = gold; ctx.lineWidth = 3; ctx.strokeRect(L, T, R - L, B - T);
ctx.lineWidth = 1.2; ctx.strokeRect(L + 9, T + 9, R - L - 18, B - T - 18);
for (const [cx, cy] of [[L + 9, T + 9], [R - 9, T + 9], [L + 9, B - 9], [R - 9, B - 9]]) {
ctx.fillStyle = gold; ctx.beginPath(); ctx.arc(cx, cy, 5, 0, Math.PI * 2); ctx.fill();
}
const mid = (L + R) / 2;
ctx.fillStyle = gold; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = font(28, 'bold'); ctx.fillText('THE RAIL EDITION', mid, T + 96);
ctx.font = font(96, 'bold'); ctx.fillText('WORD', mid, T + 230);
ctx.fillText('SEARCH', mid, T + 334);
ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(mid - 160, T + 404); ctx.lineTo(mid + 160, T + 404); ctx.stroke();
locomotive(ctx, mid, T + 520, 1.9, gold);
ctx.font = font(26, 'italic'); ctx.fillText('Fifteen chapters of hidden words', mid, B - 150);
ctx.font = font(22); ctx.fillText('for the long way round', mid, B - 112);
ctx.font = font(18, 'bold'); ctx.fillText('LOCAL · EXPRESS · INTERCITY · SLEEPER', mid, B - 56);
// the spiral holes along the binding edge
spiral(ctx, x - GUTTER + 2, y + 30, y + ch - 30, { coils: false });
for (let yy = y + 30; yy <= y + ch - 30; yy += 34) {
const gg = ctx.createLinearGradient(0, yy - 6, 0, yy + 6);
gg.addColorStop(0, '#f2f2f0'); gg.addColorStop(0.5, '#9fa3a8'); gg.addColorStop(1, '#5c6066');
ctx.strokeStyle = gg; ctx.lineWidth = 4; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(x + 2, yy + 3); ctx.bezierCurveTo(x - 10, yy - 12, x + 24, yy - 14, x + 30, yy + 1); ctx.stroke();
}
scene.textures.addCanvas('ws-cover', c);
}
// ── Tickets, postcard, summary ───────────────────────────────────────────────
function cardStock(ctx, x, y, w, h, tone = '#f1e4c2') {
ctx.fillStyle = tone;
rr(ctx, x, y, w, h, 8); ctx.fill();
ctx.save();
rr(ctx, x, y, w, h, 8); ctx.clip();
const g = ctx.createLinearGradient(x, y, x + w, y + h);
g.addColorStop(0, 'rgba(255,255,255,0.22)'); g.addColorStop(1, 'rgba(150,110,60,0.14)');
ctx.fillStyle = g; ctx.fillRect(x, y, w, h);
ctx.fillStyle = noisePattern(ctx, 64, 16);
ctx.fillRect(x, y, w, h);
// guilloche-ish fine wave pattern
ctx.strokeStyle = 'rgba(123,47,34,0.07)'; ctx.lineWidth = 0.8;
for (let k = 0; k < h; k += 7) {
ctx.beginPath();
for (let px = 0; px <= w; px += 6) {
const py = y + k + Math.sin(px / 18 + k) * 3;
if (px === 0) ctx.moveTo(x + px, py); else ctx.lineTo(x + px, py);
}
ctx.stroke();
}
ctx.restore();
}
function perforation(ctx, x, y0, y1) {
ctx.fillStyle = 'rgba(60,40,20,0.55)';
for (let y = y0 + 6; y < y1 - 4; y += 9) { ctx.beginPath(); ctx.arc(x, y, 1.8, 0, Math.PI * 2); ctx.fill(); }
}
function bakeTicket(scene) {
seed = 61;
const P = 12, { w, h } = TICKET;
const c = canvas(w + P * 2, h + P * 2);
const ctx = c.getContext('2d');
ctx.save();
ctx.shadowColor = 'rgba(20,10,4,0.4)'; ctx.shadowBlur = 8; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 4;
ctx.fillStyle = '#f1e4c2'; rr(ctx, P, P, w, h, 8); ctx.fill();
ctx.restore();
cardStock(ctx, P, P, w, h);
ctx.strokeStyle = TICKET_INK; ctx.lineWidth = 2; rr(ctx, P + 6, P + 6, w - 12, h - 12, 5); ctx.stroke();
ctx.fillStyle = TICKET_INK; ctx.fillRect(P + 6, P + 6, w - 12, 26);
ctx.fillStyle = '#f4e9cc'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = font(15, 'bold'); ctx.fillText('PUZZLE EXPRESS · ADMIT ONE', P + w / 2, P + 19);
perforation(ctx, P + w - 52, P + 34, P + h - 6);
// the conductor's punch
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath(); ctx.arc(P + w - 26, P + h - 30, 8, 0, Math.PI * 2); ctx.fill();
ctx.restore();
scene.textures.addCanvas('ws-ticket', c);
}
export const CARD = { w: 620, h: 104 };
function bakeCard(scene) {
seed = 63;
const P = 10, { w, h } = CARD;
const c = canvas(w + P * 2, h + P * 2);
const ctx = c.getContext('2d');
ctx.save();
ctx.shadowColor = 'rgba(20,10,4,0.3)'; ctx.shadowBlur = 6; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 3;
ctx.fillStyle = '#f1e4c2'; rr(ctx, P, P, w, h, 8); ctx.fill();
ctx.restore();
cardStock(ctx, P, P, w, h);
ctx.fillStyle = 'rgba(123,47,34,0.10)';
ctx.fillRect(P, P, 118, h);
ctx.strokeStyle = TICKET_INK; ctx.lineWidth = 1.6; rr(ctx, P + 5, P + 5, w - 10, h - 10, 5); ctx.stroke();
perforation(ctx, P + 118, P + 2, P + h - 2);
scene.textures.addCanvas('ws-card', c);
}
function bakePostcard(scene) {
seed = 71;
const P = 12, { w, h } = FACT;
const c = canvas(w + P * 2, h + P * 2);
const ctx = c.getContext('2d');
ctx.save();
ctx.shadowColor = 'rgba(20,10,4,0.4)'; ctx.shadowBlur = 10; ctx.shadowOffsetX = 3; ctx.shadowOffsetY = 5;
ctx.fillStyle = '#fbf7ec'; ctx.fillRect(P, P, w, h);
ctx.restore();
ctx.fillStyle = noisePattern(ctx, 64, 10); ctx.fillRect(P, P, w, h);
// airmail-ish striped edge
for (let x = 0; x < w; x += 22) {
ctx.fillStyle = (x / 22) % 2 ? 'rgba(168,50,42,0.75)' : 'rgba(44,74,138,0.75)';
ctx.beginPath(); ctx.moveTo(P + x, P); ctx.lineTo(P + x + 11, P); ctx.lineTo(P + x + 5, P + 7); ctx.lineTo(P + x - 6, P + 7); ctx.closePath(); ctx.fill();
}
// stamp
const sx = P + w - 74, sy = P + 18, sw = 56, sh = 64;
ctx.fillStyle = '#efe4c4'; ctx.fillRect(sx, sy, sw, sh);
ctx.fillStyle = '#fbf7ec';
for (let k = 0; k <= sw; k += 8) { ctx.beginPath(); ctx.arc(sx + k, sy, 3, 0, Math.PI * 2); ctx.arc(sx + k, sy + sh, 3, 0, Math.PI * 2); ctx.fill(); }
for (let k = 0; k <= sh; k += 8) { ctx.beginPath(); ctx.arc(sx, sy + k, 3, 0, Math.PI * 2); ctx.arc(sx + sw, sy + k, 3, 0, Math.PI * 2); ctx.fill(); }
ctx.fillStyle = '#8a3a2c'; ctx.fillRect(sx + 6, sy + 6, sw - 12, sh - 12);
locomotive(ctx, sx + sw / 2, sy + sh / 2 + 4, 0.28, '#f1e4c2', { lw: 1.4 });
// postmark rings
ctx.strokeStyle = 'rgba(40,40,60,0.35)'; ctx.lineWidth = 1.4;
ctx.beginPath(); ctx.arc(sx - 12, sy + 36, 24, 0, Math.PI * 2); ctx.stroke();
ctx.beginPath(); ctx.arc(sx - 12, sy + 36, 18, 0, Math.PI * 2); ctx.stroke();
for (let k = 0; k < 4; k++) {
ctx.beginPath(); ctx.moveTo(sx - 120, sy + 22 + k * 9);
for (let px = 0; px <= 80; px += 10) ctx.lineTo(sx - 120 + px, sy + 22 + k * 9 + Math.sin(px / 8) * 2);
ctx.stroke();
}
scene.textures.addCanvas('ws-postcard', c);
}
export const SUMMARY = { w: 780, h: 560 };
function bakeSummary(scene) {
seed = 81;
const P = 18, { w, h } = SUMMARY;
const c = canvas(w + P * 2, h + P * 2);
const ctx = c.getContext('2d');
ctx.save();
ctx.shadowColor = 'rgba(10,5,2,0.5)'; ctx.shadowBlur = 18; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 10;
ctx.fillStyle = '#f1e4c2'; rr(ctx, P, P, w, h, 14); ctx.fill();
ctx.restore();
cardStock(ctx, P, P, w, h);
ctx.strokeStyle = TICKET_INK; ctx.lineWidth = 3; rr(ctx, P + 12, P + 12, w - 24, h - 24, 9); ctx.stroke();
ctx.lineWidth = 1; rr(ctx, P + 18, P + 18, w - 36, h - 36, 7); ctx.stroke();
ctx.fillStyle = TICKET_INK; ctx.fillRect(P + 18, P + 18, w - 36, 46);
ctx.fillStyle = '#f4e9cc'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = font(22, 'bold'); ctx.fillText('THE PUZZLE EXPRESS · JOURNEY COMPLETE', P + w / 2, P + 42);
perforation(ctx, P + w - 150, P + 66, P + h - 20);
locomotive(ctx, P + w - 76, P + h - 92, 0.62, 'rgba(123,47,34,0.55)', { lw: 2 });
scene.textures.addCanvas('ws-summary', c);
}
// ── Props ────────────────────────────────────────────────────────────────────
function bakeCup(scene) {
const S = 150, c = canvas(S, S), ctx = c.getContext('2d');
const cx = S / 2 - 6, cy = S / 2;
ctx.save();
ctx.shadowColor = 'rgba(20,10,4,0.45)'; ctx.shadowBlur = 10; ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 6;
ctx.fillStyle = '#f4f1ea'; ctx.beginPath(); ctx.arc(cx, cy, 62, 0, Math.PI * 2); ctx.fill();
ctx.restore();
const sg = ctx.createRadialGradient(cx - 14, cy - 14, 10, cx, cy, 64);
sg.addColorStop(0, '#ffffff'); sg.addColorStop(1, '#d9d4ca');
ctx.fillStyle = sg; ctx.beginPath(); ctx.arc(cx, cy, 62, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(138,47,47,0.55)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(cx, cy, 55, 0, Math.PI * 2); ctx.stroke();
// handle
ctx.strokeStyle = '#e9e5dc'; ctx.lineWidth = 10; ctx.lineCap = 'round';
ctx.beginPath(); ctx.arc(cx + 50, cy + 2, 13, -1.2, 1.4); ctx.stroke();
ctx.fillStyle = '#efebe3'; ctx.beginPath(); ctx.arc(cx, cy, 44, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(120,110,95,0.4)'; ctx.lineWidth = 2; ctx.stroke();
const cg = ctx.createRadialGradient(cx - 8, cy - 8, 4, cx, cy, 38);
cg.addColorStop(0, '#8a5a32'); cg.addColorStop(0.7, '#5a3418'); cg.addColorStop(1, '#3e220e');
ctx.fillStyle = cg; ctx.beginPath(); ctx.arc(cx, cy, 37, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,240,210,0.25)'; ctx.beginPath(); ctx.ellipse(cx - 12, cy - 14, 12, 6, -0.6, 0, Math.PI * 2); ctx.fill();
scene.textures.addCanvas('ws-cup', c);
}
function bakeSteam(scene) {
const c = canvas(96, 96);
const ctx = c.getContext('2d');
const g = ctx.createRadialGradient(48, 48, 2, 48, 48, 46);
g.addColorStop(0, 'rgba(255,255,255,0.55)'); g.addColorStop(0.5, 'rgba(255,255,255,0.2)'); g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, 96, 96);
scene.textures.addCanvas('ws-steam', c);
}
// Pencil, drawn upright with the tip at the bottom centre.
export const PENCIL = { w: 26, h: 210 };
function bakePencil(scene) {
const { w, h } = PENCIL;
const c = canvas(w, h), ctx = c.getContext('2d');
const cx = w / 2;
// eraser + ferrule
ctx.fillStyle = '#e88a8a'; rr(ctx, cx - 10, 0, 20, 22, 5); ctx.fill();
const fg = ctx.createLinearGradient(cx - 10, 0, cx + 10, 0);
fg.addColorStop(0, '#9c9a8c'); fg.addColorStop(0.5, '#e6e2d2'); fg.addColorStop(1, '#8a887a');
ctx.fillStyle = fg; ctx.fillRect(cx - 10, 18, 20, 18);
// hexagonal body: three lit facets
const body = [['#d9a520', -10, -3.5], ['#f4c63a', -3.5, 3.5], ['#c08e14', 3.5, 10]];
for (const [col, a, b] of body) { ctx.fillStyle = col; ctx.fillRect(cx + a, 36, b - a, h - 90); }
// sharpened wood + graphite
ctx.fillStyle = '#e8c79a';
ctx.beginPath(); ctx.moveTo(cx - 10, h - 54); ctx.lineTo(cx + 10, h - 54); ctx.lineTo(cx + 2.6, h - 10); ctx.lineTo(cx - 2.6, h - 10); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#3a3a40';
ctx.beginPath(); ctx.moveTo(cx - 2.6, h - 12); ctx.lineTo(cx + 2.6, h - 12); ctx.lineTo(cx, h); ctx.closePath(); ctx.fill();
scene.textures.addCanvas('ws-pencil', c);
}
// ── Chapter doodles ──────────────────────────────────────────────────────────
// Small ink sketches in each chapter's colour, a light wash under the lines.
const DOODLES = {
space(ctx, s) {
ctx.beginPath(); ctx.arc(0, 0, 30 * s, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.ellipse(0, 0, 58 * s, 16 * s, -0.35, 0.1, Math.PI - 0.1, true); ctx.stroke();
for (const [x, y, r] of [[-50, -42, 6], [46, -48, 4], [52, 40, 5], [-44, 46, 3]]) star(ctx, x * s, y * s, r * s);
},
animals(ctx, s) {
ctx.beginPath(); ctx.ellipse(0, 18 * s, 26 * s, 22 * s, 0, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
for (const [x, y] of [[-34, -16], [-12, -36], [12, -36], [34, -16]]) {
ctx.beginPath(); ctx.ellipse(x * s, y * s, 10 * s, 13 * s, x * 0.01, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
}
},
food(ctx, s) {
// a pizza slice
ctx.beginPath(); ctx.moveTo(0, 50 * s); ctx.lineTo(-40 * s, -36 * s); ctx.quadraticCurveTo(0, -56 * s, 40 * s, -36 * s); ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-36 * s, -28 * s); ctx.quadraticCurveTo(0, -46 * s, 36 * s, -28 * s); ctx.stroke();
for (const [x, y] of [[-10, -18], [12, -10], [0, 14], [-16, 4]]) { ctx.beginPath(); ctx.arc(x * s, y * s, 6 * s, 0, Math.PI * 2); ctx.stroke(); }
},
ocean(ctx, s) {
ctx.beginPath(); ctx.ellipse(-6 * s, -6 * s, 34 * s, 18 * s, 0, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(26 * s, -6 * s); ctx.lineTo(48 * s, -24 * s); ctx.lineTo(48 * s, 12 * s); ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.arc(-24 * s, -10 * s, 3 * s, 0, Math.PI * 2); ctx.stroke();
for (let k = 0; k < 2; k++) {
ctx.beginPath();
for (let x = -56; x <= 56; x += 4) { const y = 38 + k * 14 + Math.sin(x / 9) * 5; if (x === -56) ctx.moveTo(x * s, y * s); else ctx.lineTo(x * s, y * s); }
ctx.stroke();
}
},
sports(ctx, s) {
ctx.beginPath(); ctx.arc(0, 0, 46 * s, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
const pent = (cx, cy, r) => { ctx.beginPath(); for (let i = 0; i < 5; i++) { const a = -Math.PI / 2 + i * Math.PI * 2 / 5; const px = cx + Math.cos(a) * r, py = cy + Math.sin(a) * r; if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); } ctx.closePath(); ctx.stroke(); };
pent(0, 0, 14 * s);
for (let i = 0; i < 5; i++) {
const a = -Math.PI / 2 + i * Math.PI * 2 / 5;
ctx.beginPath(); ctx.moveTo(Math.cos(a) * 14 * s, Math.sin(a) * 14 * s); ctx.lineTo(Math.cos(a) * 46 * s, Math.sin(a) * 46 * s); ctx.stroke();
}
},
music(ctx, s) {
for (const x of [-22, 22]) { ctx.beginPath(); ctx.ellipse(x * s, 32 * s, 14 * s, 10 * s, -0.4, 0, Math.PI * 2); ctx.wash(); ctx.stroke(); }
ctx.beginPath(); ctx.moveTo(-9 * s, 30 * s); ctx.lineTo(-9 * s, -40 * s); ctx.lineTo(35 * s, -52 * s); ctx.lineTo(35 * s, 30 * s); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-9 * s, -26 * s); ctx.lineTo(35 * s, -38 * s); ctx.stroke();
},
weather(ctx, s) {
ctx.beginPath();
ctx.arc(-22 * s, 0, 20 * s, Math.PI * 0.5, Math.PI * 1.5);
ctx.arc(0, -16 * s, 24 * s, Math.PI, Math.PI * 1.9);
ctx.arc(28 * s, -2 * s, 18 * s, Math.PI * 1.4, Math.PI * 0.5);
ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(4 * s, 22 * s); ctx.lineTo(-8 * s, 42 * s); ctx.lineTo(6 * s, 42 * s); ctx.lineTo(-6 * s, 62 * s); ctx.stroke();
for (const x of [-30, 26]) { ctx.beginPath(); ctx.moveTo(x * s, 28 * s); ctx.lineTo((x - 6) * s, 44 * s); ctx.stroke(); }
},
garden(ctx, s) {
for (let i = 0; i < 6; i++) {
const a = i * Math.PI / 3;
ctx.beginPath(); ctx.ellipse(Math.cos(a) * 18 * s, -22 * s + Math.sin(a) * 18 * s, 13 * s, 8 * s, a, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
}
ctx.beginPath(); ctx.arc(0, -22 * s, 8 * s, 0, Math.PI * 2); ctx.stroke();
ctx.beginPath(); ctx.moveTo(0, -12 * s); ctx.quadraticCurveTo(6 * s, 20 * s, 0, 56 * s); ctx.stroke();
ctx.beginPath(); ctx.ellipse(-16 * s, 30 * s, 16 * s, 6 * s, 0.6, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
},
railway(ctx, s) { locomotiveDoodle(ctx, s); },
dinosaurs(ctx, s) {
ctx.beginPath();
ctx.moveTo(-60 * s, 20 * s);
ctx.quadraticCurveTo(-30 * s, -4 * s, -4 * s, 0);
ctx.quadraticCurveTo(14 * s, -40 * s, 36 * s, -48 * s);
ctx.quadraticCurveTo(48 * s, -52 * s, 50 * s, -42 * s);
ctx.quadraticCurveTo(36 * s, -36 * s, 28 * s, -10 * s);
ctx.quadraticCurveTo(26 * s, 22 * s, 10 * s, 26 * s);
ctx.quadraticCurveTo(-24 * s, 30 * s, -60 * s, 20 * s);
ctx.wash(); ctx.stroke();
for (const x of [-14, 0, 14]) { ctx.beginPath(); ctx.moveTo(x * s, 24 * s); ctx.lineTo(x * s, 50 * s); ctx.stroke(); }
},
birds(ctx, s) {
for (const [x, y, k] of [[-22, -18, 1], [20, -36, 0.7], [30, 16, 0.85]]) {
ctx.beginPath();
ctx.moveTo((x - 24 * k) * s, y * s);
ctx.quadraticCurveTo((x - 10 * k) * s, (y - 16 * k) * s, x * s, (y + 2) * s);
ctx.quadraticCurveTo((x + 10 * k) * s, (y - 16 * k) * s, (x + 24 * k) * s, y * s);
ctx.stroke();
}
ctx.beginPath(); ctx.moveTo(-56 * s, 46 * s); ctx.quadraticCurveTo(0, 36 * s, 56 * s, 50 * s); ctx.stroke();
},
insects(ctx, s) {
ctx.beginPath(); ctx.ellipse(0, 8 * s, 22 * s, 30 * s, 0, 0, Math.PI * 2); ctx.wash(); ctx.stroke();
for (const y of [0, 14, 28]) { ctx.beginPath(); ctx.moveTo(-20 * s, y * s); ctx.lineTo(20 * s, y * s); ctx.stroke(); }
for (const x of [-1, 1]) { ctx.beginPath(); ctx.ellipse(x * 26 * s, -16 * s, 20 * s, 12 * s, x * 0.6, 0, Math.PI * 2); ctx.wash(); ctx.stroke(); }
ctx.beginPath(); ctx.arc(0, -28 * s, 10 * s, 0, Math.PI * 2); ctx.stroke();
for (const x of [-1, 1]) { ctx.beginPath(); ctx.moveTo(x * 4 * s, -36 * s); ctx.quadraticCurveTo(x * 10 * s, -54 * s, x * 18 * s, -56 * s); ctx.stroke(); }
},
camping(ctx, s) {
ctx.beginPath(); ctx.moveTo(-50 * s, 40 * s); ctx.lineTo(-8 * s, -34 * s); ctx.lineTo(34 * s, 40 * s); ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-8 * s, -34 * s); ctx.lineTo(-8 * s, 40 * s); ctx.moveTo(-8 * s, 40 * s); ctx.lineTo(-22 * s, 12 * s); ctx.stroke();
ctx.beginPath(); ctx.moveTo(42 * s, 40 * s); ctx.lineTo(52 * s, -10 * s); ctx.lineTo(62 * s, 40 * s); ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-60 * s, 40 * s); ctx.lineTo(66 * s, 40 * s); ctx.stroke();
},
baking(ctx, s) {
ctx.beginPath(); ctx.moveTo(-30 * s, 0); ctx.lineTo(-22 * s, 48 * s); ctx.lineTo(22 * s, 48 * s); ctx.lineTo(30 * s, 0); ctx.closePath(); ctx.wash(); ctx.stroke();
for (const x of [-12, 0, 12]) { ctx.beginPath(); ctx.moveTo(x * s, 2 * s); ctx.lineTo(x * 0.8 * s, 46 * s); ctx.stroke(); }
ctx.beginPath();
ctx.arc(-18 * s, -4 * s, 16 * s, Math.PI * 0.6, Math.PI * 1.6);
ctx.arc(0, -20 * s, 20 * s, Math.PI * 1.1, Math.PI * 1.9);
ctx.arc(18 * s, -4 * s, 16 * s, Math.PI * 1.4, Math.PI * 0.4);
ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.arc(0, -46 * s, 6 * s, 0, Math.PI * 2); ctx.stroke();
},
castles(ctx, s) {
ctx.beginPath();
ctx.moveTo(-40 * s, 50 * s); ctx.lineTo(-40 * s, -20 * s);
for (let i = 0; i < 4; i++) {
const x = -40 + i * 20;
ctx.lineTo(x * s, -30 * s); ctx.lineTo((x + 10) * s, -30 * s); ctx.lineTo((x + 10) * s, -20 * s); ctx.lineTo((x + 20) * s, -20 * s);
}
ctx.lineTo(40 * s, 50 * s); ctx.closePath(); ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-12 * s, 50 * s); ctx.lineTo(-12 * s, 22 * s); ctx.arc(0, 22 * s, 12 * s, Math.PI, 0); ctx.lineTo(12 * s, 50 * s); ctx.stroke();
ctx.beginPath(); ctx.moveTo(0, -30 * s); ctx.lineTo(0, -60 * s); ctx.lineTo(22 * s, -53 * s); ctx.lineTo(0, -46 * s); ctx.stroke();
},
};
function star(ctx, x, y, r) {
ctx.beginPath();
ctx.moveTo(x - r, y); ctx.lineTo(x + r, y);
ctx.moveTo(x, y - r); ctx.lineTo(x, y + r);
ctx.stroke();
}
function locomotiveDoodle(ctx, s) {
ctx.beginPath();
ctx.moveTo(-50 * s, 20 * s); ctx.lineTo(-50 * s, -20 * s); ctx.lineTo(-24 * s, -20 * s); ctx.lineTo(-24 * s, -6 * s);
ctx.lineTo(34 * s, -6 * s); ctx.quadraticCurveTo(44 * s, -6 * s, 44 * s, 6 * s); ctx.lineTo(44 * s, 20 * s); ctx.closePath();
ctx.wash(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(18 * s, -6 * s); ctx.lineTo(16 * s, -26 * s); ctx.lineTo(28 * s, -26 * s); ctx.lineTo(26 * s, -6 * s); ctx.stroke();
for (const [x, r] of [[-36, 10], [-8, 8], [18, 8]]) { ctx.beginPath(); ctx.arc(x * s, 26 * s, r * s, 0, Math.PI * 2); ctx.stroke(); }
for (const [x, y, r] of [[28, -36, 6], [38, -46, 8], [52, -54, 10]]) { ctx.beginPath(); ctx.arc(x * s, y * s, r * s, 0, Math.PI * 2); ctx.stroke(); }
}
function bakeDoodle(scene, id) {
const S = DOODLE.size, c = canvas(S, S), ctx = c.getContext('2d');
const ink = THEMES[id].ink;
ctx.translate(S / 2, S / 2);
ctx.lineWidth = 3; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
ctx.strokeStyle = ink;
ctx.wash = () => { ctx.fillStyle = hexA(ink, 0.16); ctx.fill(); };
(DOODLES[id] ?? DOODLES.railway)(ctx, 1);
delete ctx.wash;
scene.textures.addCanvas(`ws-doodle-${id}`, c);
}
export function prepareWordSearchArt(scene) {
const bakes = [
['ws-carriage', bakeCarriage], ['ws-sky', bakeSky], ['ws-clouds', bakeClouds], ['ws-far', bakeFar],
['ws-mid', bakeMid], ['ws-near', bakeNear], ['ws-poles', bakePoles], ['ws-glass', bakeGlass],
['ws-spread', bakeSpread], ['ws-leaf', bakeLeaf], ['ws-cover', bakeCover], ['ws-ticket', bakeTicket],
['ws-card', bakeCard], ['ws-postcard', bakePostcard], ['ws-summary', bakeSummary], ['ws-cup', bakeCup],
['ws-steam', bakeSteam], ['ws-pencil', bakePencil],
];
for (const [key, fn] of bakes) if (!scene.textures.exists(key)) fn(scene);
for (const id of CHAPTER_ORDER) if (!scene.textures.exists(`ws-doodle-${id}`)) bakeDoodle(scene, id);
}
// ── BookButton ───────────────────────────────────────────────────────────────
// A ticket stub with a perforated left edge and a printed label. Container is
// centred on (x, y); children are centred too (a Container's hit area is always
// centred on it).
export class BookButton extends Phaser.GameObjects.Container {
constructor(scene, x, y, label, onClick, { width = 180, height = 56, fontSize = 22, accent = false } = {}) {
super(scene, x, y);
this.w = width; this.h = height; this.accent = accent;
this.enabled = true;
this.hover = false;
this.gfx = scene.add.graphics();
this.text = scene.add.text(6, 1, label, {
fontFamily: SERIF, fontSize: `${fontSize}px`, color: accent ? '#f6ecd2' : TICKET_INK, fontStyle: 'bold',
}).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 - 34;
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;
g.clear();
g.fillStyle(0x000000, 0.22);
g.fillRoundedRect(-w / 2 + 3, -h / 2 + 4, w, h, 6);
const base = this.accent ? TICKET_INK_N : 0xf1e4c2;
const lit = this.accent ? 0x92402f : 0xfaf0d2;
g.fillStyle(this.hover && this.enabled ? lit : base, 1);
g.fillRoundedRect(-w / 2, -h / 2, w, h, 6);
g.lineStyle(1.6, this.accent ? 0xf1e4c2 : TICKET_INK_N, 0.85);
g.strokeRoundedRect(-w / 2 + 4, -h / 2 + 4, w - 8, h - 8, 4);
// stub perforation
g.fillStyle(this.accent ? 0xf1e4c2 : TICKET_INK_N, 0.55);
for (let y = -h / 2 + 9; y < h / 2 - 6; y += 8) g.fillCircle(-w / 2 + 22, y, 1.5);
}
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;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,31 @@
// Pure helpers for Word Search selection — no Phaser, easy to reason about/test.
// Pure helpers for Word Search: no Phaser, shared by the scene and
// tools/verifyWordSearch.js.
//
// snapSelection / lettersAt / matchWord line snapping + word matching
// selectionStep drag-or-click-click selection machine
// wordCells / leftoverCells / pickHint grid geometry + hints
// serialiseSave / parseSave autosave (`wordsearch-save`)
// daily helpers Today's Route (`wordsearch-daily`)
import { dateSeed, localDateString } from '../dotlink/DotLinkLogic.js';
export const DIFFS = ['easy', 'medium', 'hard', 'expert'];
export const DIFF_LABELS = { easy: 'Easy', medium: 'Medium', hard: 'Hard', expert: 'Expert' };
// Each difficulty is a class of ticket on the line.
export const TICKET = {
easy: { cls: 'Local Line', size: 10, dirs: 'Words run across and down' },
medium: { cls: 'Express', size: 12, dirs: 'Across, down and diagonally' },
hard: { cls: 'Intercity', size: 14, dirs: 'Any direction, even backwards' },
expert: { cls: 'Overnight Sleeper', size: 16, dirs: 'Any direction, even backwards' },
};
export const HINT_LIMITS = { easy: 5, medium: 3, hard: 2, expert: 1 };
const BASE_SCORE = { easy: 100, medium: 200, hard: 350, expert: 500 };
export function calcScore(difficulty, wordCount, hintsUsed) {
return Math.max(10, (BASE_SCORE[difficulty] ?? 100) + wordCount * 5 - hintsUsed * 25);
}
// ── Line selection ───────────────────────────────────────────────────────────
// All 8 directions as [rowDelta, colDelta]. Selection always snaps to one of
// these regardless of difficulty; matchWord checks both orientations, so a word
@ -37,7 +64,7 @@ export function snapSelection(size, br, bc, tr, tc, allowedDirs = DIRECTIONS) {
if (proj <= 0) continue; // wrong way — skip
const maxN = maxStepsInBounds(size, br, bc, dr, dc);
const n = Math.max(1, Math.min(Math.round(proj), maxN));
if (n < 1) continue;
if (n < 1 || maxN < 1) continue;
// Landing point if we step n times; error vs. the actual target.
const lr = br + dr * n;
@ -75,3 +102,187 @@ export function matchWord(letters, words) {
if (words.includes(rev)) return rev;
return null;
}
// ── Selection machine ────────────────────────────────────────────────────────
// Works for both drag (press on the first letter, release on the last) and
// click-click (click the first letter, then the last).
//
// state { anchor: {r,c} | null, dragging: bool, moved: bool }
// event { type: 'down' | 'move' | 'up' | 'cancel', cell: {r,c} | null, inGrid: bool }
// `cell` is the pointer's cell clamped into the grid; inGrid says
// whether the pointer is actually over the grid.
// result { state, action: 'none' | 'anchor' | 'preview' | 'hold' | 'commit' | 'cancel', target }
export const idleSelection = () => ({ anchor: null, dragging: false, moved: false });
const sameCell = (a, b) => !!a && !!b && a.r === b.r && a.c === b.c;
export function selectionStep(state, ev) {
const s = state ?? idleSelection();
const cell = ev.cell ?? null;
switch (ev.type) {
case 'cancel':
return { state: idleSelection(), action: s.anchor ? 'cancel' : 'none', target: null };
case 'down': {
if (!s.anchor) {
if (!ev.inGrid || !cell) return { state: s, action: 'none', target: null };
return { state: { anchor: { ...cell }, dragging: true, moved: false }, action: 'anchor', target: cell };
}
// second press of a click-click: tapping the anchor again cancels it
if (sameCell(cell, s.anchor)) return { state: idleSelection(), action: 'cancel', target: null };
if (!cell) return { state: idleSelection(), action: 'cancel', target: null };
return { state: idleSelection(), action: 'commit', target: cell };
}
case 'move': {
if (!s.anchor || !cell) return { state: s, action: 'none', target: null };
const moved = s.moved || (s.dragging && !sameCell(cell, s.anchor));
return { state: { ...s, moved }, action: 'preview', target: cell };
}
case 'up': {
if (!s.anchor || !s.dragging) return { state: s, action: 'none', target: null };
if (s.moved && cell && !sameCell(cell, s.anchor)) return { state: idleSelection(), action: 'commit', target: cell };
// released where it started: keep the anchor and wait for a second click
return { state: { anchor: s.anchor, dragging: false, moved: false }, action: 'hold', target: s.anchor };
}
default:
return { state: s, action: 'none', target: null };
}
}
// ── Grid geometry ────────────────────────────────────────────────────────────
export function wordCells(p) {
const out = [];
for (let i = 0; i < p.word.length; i++) out.push([p.row + p.dir[0] * i, p.col + p.dir[1] * i]);
return out;
}
// Cells no hidden word uses, in reading order (they spell the secret message).
export function leftoverCells(size, placements) {
const used = new Set();
for (const p of placements) for (const [r, c] of wordCells(p)) used.add(r * size + c);
const out = [];
for (let r = 0; r < size; r++) for (let c = 0; c < size; c++) if (!used.has(r * size + c)) out.push([r, c]);
return out;
}
// The message split into words of slots, for the blank lines under the grid.
export function messageWords(message) {
return message.split(/\s+/).map(w => w.replace(/[^A-Z]/g, '')).filter(Boolean);
}
// A hint pencils a ring round the first letter of an unfound, unhinted word.
export function pickHint(placements, found, hinted, rng = Math.random) {
const open = placements.filter(p => !found.has(p.word) && !hinted.has(p.word));
if (!open.length) return null;
const p = open[Math.floor(rng() * open.length)];
return { word: p.word, r: p.row, c: p.col };
}
// ── Save / resume ────────────────────────────────────────────────────────────
export const SAVE_KEY = 'wordsearch-save';
const SAVE_VERSION = 1;
export function serialiseSave(s) {
const p = s.puzzle;
return JSON.stringify({
v: SAVE_VERSION,
difficulty: s.difficulty,
daily: s.daily ?? null,
puzzle: {
difficulty: p.difficulty, theme: p.theme, themeLabel: p.themeLabel, ink: p.ink, size: p.size,
words: p.words, placements: p.placements, grid: p.grid, message: p.message, seed: p.seed ?? null,
},
found: s.found,
hinted: s.hinted ?? [],
hintsLeft: s.hintsLeft ?? 0,
hintsUsed: s.hintsUsed ?? 0,
elapsed: Math.round(s.elapsed ?? 0),
puzzleNo: s.puzzleNo ?? 0,
savedAt: s.savedAt ?? Date.now(),
});
}
const isStrArr = (a) => Array.isArray(a) && a.every(x => typeof x === 'string');
// Returns the save object, or null when the JSON is missing, corrupt, from a
// different version, or internally inconsistent.
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 !== 'object') return null;
const size = p.size;
if (!Number.isInteger(size) || size < 5 || size > 20) return null;
if (!Array.isArray(p.grid) || p.grid.length !== size || !p.grid.every(r => typeof r === 'string' && /^[A-Z]+$/.test(r) && r.length === size)) return null;
if (!isStrArr(p.words) || !p.words.length || !Array.isArray(p.placements) || p.placements.length !== p.words.length) return null;
for (const pl of p.placements) {
if (!pl || typeof pl.word !== 'string' || !p.words.includes(pl.word)) return null;
if (!Array.isArray(pl.dir) || pl.dir.length !== 2 || !pl.dir.every(d => d === -1 || d === 0 || d === 1) || (pl.dir[0] === 0 && pl.dir[1] === 0)) return null;
const cells = wordCells(pl);
if (!cells.every(([r, c]) => r >= 0 && c >= 0 && r < size && c < size)) return null;
if (cells.map(([r, c]) => p.grid[r][c]).join('') !== pl.word) return null;
}
if (new Set(p.placements.map(pl => pl.word)).size !== p.words.length) return null;
if (typeof p.message !== 'string') return null;
const left = leftoverCells(size, p.placements).map(([r, c]) => p.grid[r][c]).join('');
if (left !== p.message.replace(/[^A-Z]/g, '')) return null;
if (!isStrArr(s.found) || !s.found.every(w => p.words.includes(w))) return null;
s.found = [...new Set(s.found)];
if (s.found.length >= p.words.length) return null; // already solved
s.hinted = isStrArr(s.hinted) ? s.hinted.filter(w => p.words.includes(w)) : [];
if (!Number.isFinite(s.elapsed) || s.elapsed < 0) s.elapsed = 0;
if (!Number.isInteger(s.hintsLeft) || s.hintsLeft < 0) s.hintsLeft = 0;
if (!Number.isInteger(s.hintsUsed) || s.hintsUsed < 0) s.hintsUsed = 0;
if (s.daily != null && !/^\d{4}-\d{2}-\d{2}$/.test(s.daily)) s.daily = null;
return s;
}
// ── Daily: Today's Route ─────────────────────────────────────────────────────
export const DAILY_KEY = 'wordsearch-daily';
export const DAILY_DIFFICULTY = 'medium';
export function todayString(d = new Date()) { return localDateString(d); }
export function dailySeed(date) { return dateSeed(`wordsearch:${date}`); }
export function prevDate(date) {
const [y, m, d] = date.split('-').map(Number);
return localDateString(new Date(y, m - 1, d - 1));
}
export function blankDaily() { return { lastDate: null, streak: 0, bestStreak: 0, solved: {} }; }
// Record a Daily solve for `date` (the puzzle's date) on `today`. Only a
// same-day solve moves the streak; re-solving keeps the faster time.
export function updateDaily(rec, date, today, timeMs) {
const r = { ...blankDaily(), ...(rec ?? {}), solved: { ...(rec?.solved ?? {}) } };
const old = r.solved[date];
const newBestTime = old != null && timeMs < old;
if (old == null || timeMs < old) r.solved[date] = timeMs;
if (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.solved).sort();
for (const k of keys.slice(0, Math.max(0, keys.length - 60))) delete r.solved[k];
return { rec: r, newBestTime, streak: dailyStreakNow(r, today) };
}
// The streak still alive today: solved 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 26 November" for a YYYY-MM-DD string.
export function shortDate(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()]} ${d} ${months[m - 1]}`;
}

View File

@ -0,0 +1,157 @@
// WordSearchSound.js — small Web Audio synths for the Rail Edition. No audio
// files; silent without Web Audio or when the game is muted.
//
// RailBed the carriage: a low rumble plus clack-clack at the rail joints
// pencilTick(scene) the pencil touching the page
// highlighterSwipe(scene) a felt-tip squeak along a found word
// whistle(scene) a distant two-tone train whistle
// letterPing(scene, i) a soft rising ping as message letters land
function ctxOf(scene) {
const sm = scene?.sound;
if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null;
return sm.context;
}
const noiseCache = new WeakMap();
function noise(ac) {
if (noiseCache.has(ac)) return noiseCache.get(ac);
const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ac, buf);
return buf;
}
function out(scene, ac, gain) {
const sm = scene.sound;
const node = sm.masterVolumeNode ?? sm.destination ?? null;
const g = ac.createGain();
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
g.connect(node ?? ac.destination);
return g;
}
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003 } = {}) {
const o = ac.createOscillator(); o.type = type;
o.frequency.setValueAtTime(f, t0);
if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d);
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(a, t0 + attack);
g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03);
}
function hiss(ac, dest, t0, f, vol = 1, d = 0.03, q = 3, type = 'bandpass') {
const n = ac.createBufferSource(); n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.value = f; bp.Q.value = q;
const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02);
}
const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } };
const semi = (f, n) => f * Math.pow(2, n / 12);
export function pencilTick(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003;
hiss(ac, dest, t, 3800, 0.8, 0.035, 2.5);
});
}
export function highlighterSwipe(scene, len = 5) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.005;
const d = 0.12 + Math.min(12, len) * 0.025;
hiss(ac, dest, t, 2400, 0.9, d, 1.6);
tone(ac, dest, t, 1800, { type: 'triangle', a: 0.08, d, glide: 1.25, attack: 0.02 });
});
}
export function letterPing(scene, i = 0) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.025), t = ac.currentTime + 0.004;
const scale = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24];
tone(ac, dest, t, semi(659.25, scale[i % scale.length]), { a: 0.7, d: 0.35 });
});
}
export function whistle(scene, { vol = 0.05 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.02;
for (const [f, a] of [[466.16, 0.6], [554.37, 0.5], [698.46, 0.32]]) {
const o = ac.createOscillator(); o.type = 'sawtooth';
o.frequency.setValueAtTime(f * 0.96, t);
o.frequency.linearRampToValueAtTime(f, t + 0.18);
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 1500;
const g = ac.createGain();
g.gain.setValueAtTime(0, t);
g.gain.linearRampToValueAtTime(a, t + 0.12);
g.gain.setValueAtTime(a, t + 0.7);
g.gain.linearRampToValueAtTime(0, t + 1.25);
o.connect(lp); lp.connect(g); g.connect(dest);
o.start(t); o.stop(t + 1.3);
}
hiss(ac, dest, t, 2200, 0.25, 1.1, 0.8);
});
}
/** The carriage: filtered rumble with a clack-clack every so often. */
export class RailBed {
constructor(scene, { vol = 0.03 } = {}) {
this.scene = scene; this.vol = vol; this.nodes = null; this.timer = null;
this.onClack = null; // called on each pair of clacks (the scene bumps the camera)
}
start() {
if (this.nodes) return;
const ac = ctxOf(this.scene); if (!ac) return;
safe(() => {
const dest = out(this.scene, ac, 0);
const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true;
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 190;
const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 35;
src.connect(hp); hp.connect(lp); lp.connect(dest);
src.start();
dest.gain.linearRampToValueAtTime(this.vol, ac.currentTime + 2.5);
this.nodes = { src, dest, lp };
});
const clack = () => {
this.timer = setTimeout(clack, 1700 + Math.random() * 900);
const a2 = ctxOf(this.scene); if (!a2 || !this.nodes) return;
safe(() => {
const d2 = out(this.scene, a2, this.vol * 1.4), t = a2.currentTime + 0.01;
for (const dt of [0, 0.16]) {
hiss(a2, d2, t + dt, 420, 1, 0.07, 1.2);
tone(a2, d2, t + dt, 90, { a: 0.5, d: 0.09, glide: 0.7 });
}
});
this.onClack?.();
};
if (this.nodes) this.timer = setTimeout(clack, 900);
}
// In a tunnel the rumble gets louder and boomier.
setTunnel(on) {
const n = this.nodes; if (!n) return;
safe(() => {
const ac = n.src.context, t = ac.currentTime;
n.dest.gain.cancelScheduledValues(t);
n.dest.gain.setValueAtTime(n.dest.gain.value, t);
n.dest.gain.linearRampToValueAtTime(on ? this.vol * 2.2 : this.vol, t + 0.5);
n.lp.frequency.setValueAtTime(n.lp.frequency.value, t);
n.lp.frequency.linearRampToValueAtTime(on ? 320 : 190, t + 0.5);
});
}
stop() {
clearTimeout(this.timer); this.timer = null;
const n = this.nodes; this.nodes = null;
if (!n) return;
safe(() => {
const ac = n.src.context;
n.dest.gain.cancelScheduledValues(ac.currentTime);
n.dest.gain.setValueAtTime(n.dest.gain.value, ac.currentTime);
n.dest.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6);
n.src.stop(ac.currentTime + 0.7);
});
}
setOn(on) { if (on) this.start(); else this.stop(); }
}

View File

@ -505,15 +505,18 @@ router.get('/hangman/start', (req, res) => {
// ── Word Search ──────────────────────────────────────────────────────────────
// GET /api/words/wordsearch/start?difficulty=easy|medium|hard&theme=random|space|...
// Returns a generated puzzle: { difficulty, theme, themeLabel, size, words, placements, grid }.
// GET /api/words/wordsearch/start?difficulty=easy|medium|hard|expert&theme=random|space|...[&seed=uint32]
// Returns a generated puzzle: { difficulty, theme, themeLabel, ink, size, words,
// placements, grid, message, messageLetters, facts, seed }. A seed makes it
// deterministic (Today's Route; with theme=random the chapter is seeded too).
router.get('/wordsearch/start', (req, res) => {
const difficulty = String(req.query.difficulty ?? 'medium').toLowerCase();
const theme = req.query.theme ? String(req.query.theme).toLowerCase() : 'random';
res.json(wordSearchGenerate({ difficulty, theme }));
const seed = req.query.seed != null && /^\d+$/.test(String(req.query.seed)) ? Number(req.query.seed) : null;
res.json(wordSearchGenerate({ difficulty, theme, seed }));
});
// GET /api/words/wordsearch/themes — list of { id, label } for the start panel.
// GET /api/words/wordsearch/themes — list of { id, label, ink, chapter } for the contents page.
router.get('/wordsearch/themes', (_req, res) => {
res.json({ themes: wordSearchThemes() });
});

View File

@ -1,179 +1,256 @@
// Server-side Word Search puzzle generator.
// Word Search generator — the Rail Edition puzzle book.
//
// A puzzle is a square letter grid with a set of theme words hidden inside it,
// placed along straight lines in one of 8 directions. Difficulty controls grid
// size, how many words are hidden, and which directions are allowed (harder
// puzzles add diagonals and backwards placement).
// generatePuzzle({ difficulty, theme, seed }) →
// { difficulty, theme, themeLabel, ink, size, words, placements, grid,
// message, messageLetters, facts, seed }
//
// Self-contained: theme word lists live here, no dependency on the ENABLE list.
// A puzzle is a square grid with a chapter's words hidden along straight lines.
// The grid is packed (crossings preferred) until the cells no word uses — read
// left→right, top→bottom — number exactly the letters of a secret message;
// those leftover cells then spell it. So there are no random filler letters.
//
// Every listed word occurs exactly once in the finished grid (any of the 8
// directions, either way round), no listed word contains another, and only the
// difficulty's directions are used.
//
// With a numeric seed the result is fully deterministic (the Daily): the module
// `rand` is swapped for a seeded RNG for the duration of the call and the search
// is bounded by an attempt count rather than the clock.
const A = 'A'.charCodeAt(0);
import { THEMES, CHAPTER_ORDER, JOURNEY_MESSAGES, messageLetters } from './wordSearchThemes.js';
// [rowDelta, colDelta] for each direction.
const DIR = {
E: [0, 1],
W: [0, -1],
S: [1, 0],
N: [-1, 0],
SE: [1, 1],
SW: [1, -1],
NE: [-1, 1],
NW: [-1, -1],
// [rowDelta, colDelta]
const E = [0, 1], S = [1, 0], SE = [1, 1], NE = [-1, 1];
const W = [0, -1], N = [-1, 0], SW = [1, -1], NW = [-1, -1];
export const ALL_DIRS = [E, S, SE, NE, W, N, SW, NW];
// band = allowed leftover (message) length; words = how many words to hide.
export const DIFFICULTY = {
easy: { id: 'easy', size: 10, dirs: [E, S], band: [14, 30], words: [9, 13], maxLen: 10 },
medium: { id: 'medium', size: 12, dirs: [E, S, SE, NE], band: [18, 42], words: [12, 18], maxLen: 12 },
hard: { id: 'hard', size: 14, dirs: ALL_DIRS, band: [26, 56], words: [16, 26], maxLen: 12 },
expert: { id: 'expert', size: 16, dirs: ALL_DIRS, band: [40, 80], words: [22, 36], maxLen: 12 },
};
export const DIFFICULTIES = Object.keys(DIFFICULTY);
const DIFFICULTY = {
easy: { id: 'easy', size: 10, count: 8, dirs: [DIR.E, DIR.S] },
medium: { id: 'medium', size: 12, count: 10, dirs: [DIR.E, DIR.S, DIR.SE, DIR.NE] },
hard: { id: 'hard', size: 14, count: 12, dirs: [DIR.E, DIR.S, DIR.SE, DIR.NE, DIR.W, DIR.N, DIR.SW, DIR.NW] },
};
const MAX_SEEDED_ATTEMPTS = 400;
const DEADLINE_MS = 1500;
// Curated themes. Each entry: display label + uppercase A–Z words (3–9 letters).
const THEMES = {
space: {
label: 'Space',
words: ['COMET', 'PLANET', 'ROCKET', 'GALAXY', 'ORBIT', 'NEBULA', 'METEOR',
'SOLAR', 'COSMOS', 'SATURN', 'VENUS', 'PLUTO', 'GRAVITY', 'ASTEROID',
'MARS', 'MOON'],
},
animals: {
label: 'Animals',
words: ['TIGER', 'ELEPHANT', 'GIRAFFE', 'MONKEY', 'ZEBRA', 'KANGAROO',
'PENGUIN', 'DOLPHIN', 'LEOPARD', 'PANDA', 'RABBIT', 'FALCON',
'OTTER', 'BEAVER', 'COBRA', 'WALRUS'],
},
food: {
label: 'Food',
words: ['PIZZA', 'BURGER', 'PASTA', 'SALAD', 'CHEESE', 'TOMATO', 'BANANA',
'COOKIE', 'WAFFLE', 'PRETZEL', 'MUFFIN', 'NOODLE', 'PEPPER',
'CARROT', 'YOGURT', 'PANCAKE'],
},
ocean: {
label: 'Ocean',
words: ['CORAL', 'SHARK', 'WHALE', 'OCTOPUS', 'DOLPHIN', 'LOBSTER',
'STARFISH', 'SEAWEED', 'JELLYFISH', 'URCHIN', 'OYSTER', 'MARLIN',
'SHRIMP', 'ANCHOR', 'LAGOON', 'CURRENT'],
},
sports: {
label: 'Sports',
words: ['SOCCER', 'TENNIS', 'HOCKEY', 'BOXING', 'RUGBY', 'SKIING',
'CYCLING', 'ARCHERY', 'BOWLING', 'CRICKET', 'DIVING', 'FENCING',
'KARATE', 'ROWING', 'SAILING', 'SURFING'],
},
music: {
label: 'Music',
words: ['GUITAR', 'PIANO', 'VIOLIN', 'DRUMS', 'TRUMPET', 'FLUTE', 'CELLO',
'HARP', 'BANJO', 'MELODY', 'RHYTHM', 'TEMPO', 'CHORD', 'OCTAVE',
'SONATA', 'BALLAD'],
},
};
// The generator's only randomness (swapped for a seeded RNG during seeded calls).
let rand = Math.random;
function randomFrom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
function makeRng(seed) {
let a = seed >>> 0;
return () => {
a |= 0; a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const pick = (arr) => arr[Math.floor(rand() * arr.length)];
function shuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const j = Math.floor(rand() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const reverse = (w) => [...w].reverse().join('');
const clash = (a, b) => a.includes(b) || b.includes(a) || a.includes(reverse(b)) || b.includes(reverse(a));
function resolveDifficulty(id) {
return DIFFICULTY[String(id).toLowerCase()] ?? DIFFICULTY.medium;
return DIFFICULTY[String(id ?? '').toLowerCase()] ?? DIFFICULTY.medium;
}
function resolveTheme(id) {
const key = String(id).toLowerCase();
if (key === 'random' || !THEMES[key]) {
const keys = Object.keys(THEMES);
const pick = randomFrom(keys);
return { key: pick, ...THEMES[pick] };
}
return { key, ...THEMES[key] };
const key = String(id ?? 'random').toLowerCase();
if (THEMES[key]) return key;
return pick(CHAPTER_ORDER);
}
// Try to place `word` into `grid` along one of `dirs`. Accepts a placement when
// every target cell is empty or already holds the matching letter (crossings).
// Returns { row, col, dir } on success, or null after exhausting attempts.
function tryPlace(grid, word, dirs, size, attempts = 150) {
for (let a = 0; a < attempts; a++) {
const [dr, dc] = randomFrom(dirs);
const len = word.length;
// Valid start range so the whole word stays in bounds.
const rowMin = dr < 0 ? (len - 1) : 0;
const rowMax = dr > 0 ? (size - len) : (size - 1);
const colMin = dc < 0 ? (len - 1) : 0;
const colMax = dc > 0 ? (size - len) : (size - 1);
if (rowMin > rowMax || colMin > colMax) continue;
const row = rowMin + Math.floor(Math.random() * (rowMax - rowMin + 1));
const col = colMin + Math.floor(Math.random() * (colMax - colMin + 1));
let ok = true;
for (let i = 0; i < len; i++) {
const r = row + dr * i;
const c = col + dc * i;
const cur = grid[r][c];
if (cur !== '' && cur !== word[i]) { ok = false; break; }
}
if (!ok) continue;
for (let i = 0; i < len; i++) {
grid[row + dr * i][col + dc * i] = word[i];
}
return { row, col, dir: [dr, dc] };
// Group message phrases by letter count.
function byLength(list) {
const m = new Map();
for (const text of list) {
const n = messageLetters(text).length;
if (!m.has(n)) m.set(n, []);
m.get(n).push(text);
}
return null;
return m;
}
// Build a single puzzle. Returns the grid as an array of row strings plus the
// list of words actually placed and their placements.
export function generatePuzzle({ difficulty, theme } = {}) {
const cfg = resolveDifficulty(difficulty);
const themeInfo = resolveTheme(theme ?? 'random');
const { size, count, dirs } = cfg;
// Candidate words that fit the grid, longest first so the hard ones place
// before the grid fills up.
const candidates = shuffle(themeInfo.words.filter(w => w.length <= size))
.sort((x, y) => y.length - x.length);
const grid = Array.from({ length: size }, () => Array(size).fill(''));
const placedWords = [];
const placements = [];
for (const word of candidates) {
if (placedWords.length >= count) break;
const placed = tryPlace(grid, word, dirs, size);
if (placed) {
placedWords.push(word);
placements.push({ word, row: placed.row, col: placed.col, dir: placed.dir });
}
}
// Fill the remaining empties with random letters.
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
if (grid[r][c] === '') {
grid[r][c] = String.fromCharCode(A + Math.floor(Math.random() * 26));
// Every legal placement of `word` (each adds at least one new cell).
function placementsFor(grid, size, word, dirs) {
const out = [];
const L = word.length;
for (const [dr, dc] of dirs) {
const rMin = dr < 0 ? L - 1 : 0, rMax = dr > 0 ? size - L : size - 1;
const cMin = dc < 0 ? L - 1 : 0, cMax = dc > 0 ? size - L : size - 1;
for (let r = rMin; r <= rMax; r++) {
for (let c = cMin; c <= cMax; c++) {
let fresh = 0, ok = true;
for (let i = 0; i < L; i++) {
const g = grid[r + dr * i][c + dc * i];
if (g === '') fresh++;
else if (g !== word[i]) { ok = false; break; }
}
if (ok && fresh > 0) out.push({ row: r, col: c, dir: [dr, dc], fresh });
}
}
}
return out;
}
return {
difficulty: cfg.id,
theme: themeInfo.key,
themeLabel: themeInfo.label,
size,
words: placedWords,
placements,
grid: grid.map(row => row.join('')),
// How many distinct times `word` appears in the grid (all 8 directions, either
// way round; a palindrome found both ways in the same cells counts once).
export function countOccurrences(rows, word) {
const size = rows.length;
const L = word.length;
const seen = new Set();
const targets = [word, reverse(word)];
for (const [dr, dc] of ALL_DIRS) {
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
const er = r + dr * (L - 1), ec = c + dc * (L - 1);
if (er < 0 || er >= size || ec < 0 || ec >= size) continue;
let s = '';
for (let i = 0; i < L; i++) s += rows[r + dr * i][c + dc * i];
if (targets.includes(s)) {
const a = `${r},${c}`, b = `${er},${ec}`;
seen.add(a < b ? `${a}|${b}` : `${b}|${a}`);
}
}
}
}
return seen.size;
}
// One packing attempt. Returns the finished puzzle core or null.
function attempt(cfg, themeKey, themeLens, journeyLens) {
const { size, dirs, band: [lo, hi], words: [wMin, wMax], maxLen } = cfg;
const theme = THEMES[themeKey];
const grid = Array.from({ length: size }, () => Array(size).fill(''));
let empty = size * size;
const placed = [];
// Longest words first (they're hardest to fit), with some jitter for variety.
let pool = shuffle(Object.keys(theme.words).filter(w => w.length <= Math.min(size, maxLen)))
.map(w => ({ w, k: w.length + rand() * 3 }))
.sort((a, b) => b.k - a.k)
.map(o => o.w);
const apply = (word, p) => {
for (let i = 0; i < word.length; i++) grid[p.row + p.dir[0] * i][p.col + p.dir[1] * i] = word[i];
empty -= p.fresh;
placed.push({ word, row: p.row, col: p.col, dir: p.dir });
pool = pool.filter(w => w !== word && !clash(w, word));
};
const fits = (n) => n >= lo && n <= hi;
for (;;) {
if (placed.length >= wMin - 1 && empty <= hi + 12) {
// Try to land the leftover count exactly on a message length with one
// more word. Chapter phrases always; the journey phrases only once the
// grid is nearly out of room or words.
const lastChance = placed.length + 3 >= wMax || empty - lo < 8 || pool.length < 4;
for (const lens of lastChance ? [themeLens, journeyLens] : [themeLens]) {
const options = [];
for (const word of pool) {
for (const p of placementsFor(grid, size, word, dirs)) {
const left = empty - p.fresh;
if (fits(left) && lens.has(left)) options.push({ word, p, left });
}
}
if (options.length && placed.length + 1 >= wMin && placed.length + 1 <= wMax) {
const o = pick(options);
apply(o.word, o.p);
return { grid, placed, lens };
}
}
if (placed.length >= wMin && fits(empty)) {
if (themeLens.has(empty)) return { grid, placed, lens: themeLens };
if (lastChance && journeyLens.has(empty)) return { grid, placed, lens: journeyLens };
}
}
if (placed.length >= wMax || empty < lo || !pool.length) return null;
// An ordinary step: the first word in the pool that fits, at a placement
// that reuses as many letters as possible (with a little randomness).
let done = false;
while (pool.length && !done) {
const word = pool[0];
const ps = placementsFor(grid, size, word, dirs);
if (!ps.length) { pool.shift(); continue; }
let best = null, bestScore = Infinity;
for (const p of ps) {
const score = p.fresh + rand() * 2.2;
if (score < bestScore) { bestScore = score; best = p; }
}
apply(word, best);
done = true;
}
if (!done) return null;
}
}
export function generatePuzzle({ difficulty, theme, seed = null } = {}) {
const seeded = seed != null && Number.isFinite(Number(seed));
const prevRand = rand;
if (seeded) rand = makeRng(Number(seed));
try {
const cfg = resolveDifficulty(difficulty);
const themeKey = resolveTheme(theme);
const info = THEMES[themeKey];
const themeMsgs = byLength(info.messages);
const journeyMsgs = byLength(JOURNEY_MESSAGES);
const themeLens = new Set(themeMsgs.keys());
const journeyLens = new Set(journeyMsgs.keys());
const deadline = seeded ? Infinity : Date.now() + DEADLINE_MS;
for (let n = 0; seeded ? n < MAX_SEEDED_ATTEMPTS : (n < 40 || Date.now() < deadline); n++) {
const res = attempt(cfg, themeKey, themeLens, journeyLens);
if (!res) continue;
const { grid, placed } = res;
// leftover cells in reading order
const leftover = [];
for (let r = 0; r < cfg.size; r++) for (let c = 0; c < cfg.size; c++) if (grid[r][c] === '') leftover.push([r, c]);
const msgs = (res.lens === themeLens ? themeMsgs : journeyMsgs).get(leftover.length);
if (!msgs) continue;
const message = pick(msgs);
const letters = messageLetters(message);
leftover.forEach(([r, c], i) => { grid[r][c] = letters[i]; });
const rows = grid.map(row => row.join(''));
if (!placed.every(p => countOccurrences(rows, p.word) === 1)) continue;
const words = placed.map(p => p.word).sort();
const facts = {};
for (const w of words) facts[w] = info.words[w];
return {
difficulty: cfg.id,
theme: themeKey,
themeLabel: info.label,
ink: info.ink,
size: cfg.size,
words,
placements: placed,
grid: rows,
message,
messageLetters: letters,
facts,
seed: seeded ? Number(seed) : null,
};
}
throw new Error(`wordsearch: could not build a ${cfg.id} ${themeKey} puzzle`);
} finally {
rand = prevRand;
}
}
export function listThemes() {
return Object.entries(THEMES).map(([id, t]) => ({ id, label: t.label }));
return CHAPTER_ORDER.map((id, i) => ({ id, label: THEMES[id].label, ink: THEMES[id].ink, chapter: i + 1 }));
}

View File

@ -0,0 +1,961 @@
// Word Search — the chapters of the Rail Edition puzzle book.
//
// Pure data, shared by the generator (src/words/wordSearchEngine.js), the scene
// (fun-fact cards, chapter inks) and tools/verifyWordSearch.js.
//
// Each chapter:
// label the chapter name printed in the book
// ink the chapter's accent ink (title, tab, doodle)
// words { WORD: 'one-line fun fact' }: uppercase A–Z, 3–12 letters
// messages secret-message phrases (A–Z and spaces). The leftover letters of a
// finished grid, read left→right and top→bottom, spell one of them.
//
// JOURNEY_MESSAGES are general train-trip phrases the generator falls back on
// when no chapter phrase has the exact leftover length.
export const CHAPTER_ORDER = [
'space', 'animals', 'food', 'ocean', 'sports', 'music', 'weather', 'garden',
'railway', 'dinosaurs', 'birds', 'insects', 'camping', 'baking', 'castles',
];
export const THEMES = {
space: {
label: 'Space',
ink: '#2c4a8a',
words: {
COMET: "A comet's tail always points away from the Sun, pushed by the solar wind.",
PLANET: "The word planet comes from the Greek for 'wanderer'.",
ROCKET: 'A rocket works in empty space because it pushes against its own exhaust.',
GALAXY: 'Our galaxy, the Milky Way, is roughly 100,000 light-years across.',
ORBIT: 'The International Space Station orbits Earth about every 90 minutes.',
NEBULA: 'A nebula is a vast cloud of gas and dust where new stars are born.',
METEOR: 'A meteor is the streak of light from a space rock burning up in our air.',
SOLAR: 'Sunlight takes about eight minutes to reach Earth.',
COSMOS: "Cosmos comes from a Greek word meaning 'order'.",
SATURN: 'Saturn is so light for its size that it would float in a big enough bathtub.',
VENUS: 'Venus spins backwards compared with most planets, so its Sun rises in the west.',
PLUTO: 'Pluto was reclassified as a dwarf planet in 2006.',
GRAVITY: 'On the Moon you would weigh about one sixth of what you weigh on Earth.',
ASTEROID: 'Most asteroids orbit the Sun in a belt between Mars and Jupiter.',
MARS: 'Mars looks red because its dust is rich in iron oxide, or rust.',
MOON: 'The Moon drifts away from Earth by about 3.8 cm every year.',
JUPITER: 'Jupiter is so big that all the other planets could fit inside it.',
MERCURY: 'Mercury is the closest planet to the Sun and the smallest of the eight.',
NEPTUNE: 'Neptune has the fastest winds in the solar system, over 2,000 km/h.',
URANUS: 'Uranus rolls around the Sun on its side, tilted about 98 degrees.',
EARTH: 'Earth is the only planet in our solar system not named after a god.',
ECLIPSE: 'A total solar eclipse can last at most about seven and a half minutes.',
CRATER: "The Moon's craters last for ages because it has no wind or rain to wear them down.",
ASTRONAUT: "Astronaut comes from Greek words meaning 'star sailor'.",
TELESCOPE: "Galileo turned a telescope to the sky in 1609 and spotted Jupiter's moons.",
SHUTTLE: "NASA's Space Shuttle flew 135 missions between 1981 and 2011.",
LAUNCH: "Rockets often launch eastward to borrow speed from Earth's spin.",
QUASAR: 'Quasars are blazing galaxy cores powered by giant black holes.',
PULSAR: 'A pulsar is a spinning neutron star that sweeps out beams like a lighthouse.',
LUNAR: 'Twelve astronauts walked on the lunar surface between 1969 and 1972.',
SUNSPOT: "Sunspots look dark only because they're cooler than the rest of the Sun.",
AURORA: 'Auroras glow when particles from the Sun hit gases high in our atmosphere.',
ROVER: "NASA's Opportunity rover was planned for 90 days and worked for nearly 15 years.",
CAPSULE: 'Apollo crews rode home in a cone-shaped capsule that splashed down in the sea.',
COSMONAUT: 'Yuri Gagarin, a Soviet cosmonaut, became the first person in space in 1961.',
SATELLITE: 'Sputnik 1, launched in 1957, was the first artificial satellite.',
STARDUST: 'Much of the iron in your blood was made inside long-dead stars.',
ORION: "Orion's Belt is three bright stars in an almost straight line.",
ZENITH: 'The zenith is the point in the sky directly above your head.',
EQUINOX: 'At an equinox, day and night are nearly equal all over the world.',
SUPERNOVA: 'A supernova can briefly outshine its entire galaxy.',
SPACEWALK: 'Alexei Leonov made the first spacewalk in 1965.',
COUNTDOWN: 'Launch countdowns include planned holds so the crew can make final checks.',
TITAN: "Titan, Saturn's largest moon, has lakes of liquid methane.",
},
messages: [
'REACH FOR THE STARS',
'THE SKY IS NOT THE LIMIT',
'KEEP LOOKING UP AT THE NIGHT SKY',
'EVERY ATOM IN YOUR BODY WAS MADE IN A STAR',
'A DAY ON VENUS LASTS LONGER THAN ITS WHOLE YEAR',
'SUNLIGHT TAKES ABOUT EIGHT MINUTES TO REACH THE EARTH',
'LIGHT FROM THE SUN TAKES ABOUT EIGHT MINUTES TO TRAVEL ALL THE WAY TO EARTH',
'THE FOOTPRINTS LEFT ON THE MOON COULD LAST FOR MILLIONS OF YEARS BECAUSE THERE IS NO WIND',
],
},
animals: {
label: 'Animals',
ink: '#8a5a2b',
words: {
TIGER: 'No two tigers have the same stripes, and the stripes go right down to the skin.',
ELEPHANT: 'Elephants can recognise themselves in a mirror.',
GIRAFFE: "A giraffe's tongue can be about 50 cm long.",
MONKEY: 'Howler monkeys can be heard several kilometres away.',
ZEBRA: 'Scientists think zebra stripes help keep biting flies away.',
KANGAROO: 'A newborn kangaroo is about the size of a jellybean.',
PENGUIN: 'Emperor penguins can dive deeper than 500 metres.',
LEOPARD: 'Leopards often haul their prey up into trees to keep it safe.',
PANDA: 'A giant panda can spend 10 to 16 hours a day eating bamboo.',
RABBIT: "A rabbit's teeth never stop growing.",
OTTER: "Sea otters sometimes hold paws while they sleep so they don't drift apart.",
BEAVER: "A beaver's front teeth are orange because of iron in the enamel.",
COBRA: 'A king cobra can raise a third of its body off the ground.',
WALRUS: 'Walruses use their tusks to haul themselves out of the water.',
CHEETAH: 'The cheetah is the fastest land animal, reaching about 110 km/h in short bursts.',
GORILLA: 'Gorillas share roughly 98 percent of their DNA with humans.',
HIPPO: 'Hippos ooze an oily red fluid that works like sunscreen.',
RHINO: "A rhino's horn is made of keratin, the same stuff as your fingernails.",
CAMEL: "A camel's hump stores fat, not water.",
KOALA: 'Koalas can sleep up to 20 hours a day.',
SLOTH: 'Sloths are so slow that algae can grow on their fur.',
LION: "A lion's roar can be heard about 8 km away.",
WOLF: 'Wolves live in family groups called packs.',
MOOSE: 'A bull moose can grow antlers up to about 1.8 metres across.',
BADGER: 'A group of badgers is called a cete.',
FERRET: 'Ferrets sleep around 14 to 18 hours a day.',
HEDGEHOG: 'A hedgehog has around 5,000 to 7,000 spines.',
SQUIRREL: 'Squirrels forget where they buried many nuts, which helps plant new trees.',
CHIPMUNK: 'A chipmunk can stuff its cheek pouches to three times the size of its head.',
JAGUAR: 'Jaguars have one of the strongest bites of any big cat.',
PANTHER: 'A black panther is usually a leopard or jaguar with dark fur.',
LEMUR: 'Wild lemurs are found only on Madagascar and a few nearby islands.',
LLAMA: 'Llamas hum to communicate with each other.',
ALPACA: 'Alpacas were bred in the Andes for their soft fleece.',
MEERKAT: 'Meerkats take turns standing guard while the rest of the group forages.',
ARMADILLO: 'Nine-banded armadillos almost always give birth to identical quadruplets.',
PORCUPINE: "A porcupine can't shoot its quills, but they come loose very easily.",
RACCOON: 'Raccoons often dunk their food in water before eating it.',
WOMBAT: 'Wombats produce cube-shaped droppings.',
PLATYPUS: 'The platypus is a mammal that lays eggs.',
OCELOT: 'Ocelots are good swimmers, unlike many other cats.',
COYOTE: 'Coyotes can run at about 65 km/h.',
BISON: 'The American bison is the heaviest land animal in North America.',
GAZELLE: "Gazelles leap straight up, called stotting, to show predators they're fit.",
},
messages: [
'THE WILD IS CALLING',
'EVERY CREATURE HAS ITS PLACE',
'ELEPHANTS NEVER FORGET A FRIEND',
'THE HEART OF A SHRIMP IS IN ITS HEAD',
'A GROUP OF FLAMINGOS IS CALLED A FLAMBOYANCE',
'SEA OTTERS HOLD HANDS SO THEY DO NOT DRIFT APART',
'A GROUP OF OWLS IS CALLED A PARLIAMENT AND A GROUP OF CROWS IS A MURDER',
'SOME ANIMALS SLEEP STANDING UP WHILE OTHERS SLEEP WITH ONE EYE OPEN AND HALF THEIR BRAIN AWAKE',
],
},
food: {
label: 'Food',
ink: '#b5462e',
words: {
PIZZA: 'Pizza Margherita is said to be named after a queen of Italy.',
BURGER: 'Hamburgers are named after the German city of Hamburg.',
PASTA: 'Italy has hundreds of different pasta shapes.',
SALAD: 'Salad comes from the Latin word for salt.',
CHEESE: 'It takes about 10 litres of milk to make 1 kg of hard cheese.',
TOMATO: 'Botanically, a tomato is a fruit.',
BANANA: 'Botanically speaking, bananas are berries.',
WAFFLE: 'Waffle irons leave a grid that holds little pools of syrup.',
NOODLE: 'Noodles have been eaten in China for at least 4,000 years.',
PEPPER: 'Black pepper was once so prized it was traded like money.',
CARROT: 'The first cultivated carrots were purple and yellow, not orange.',
YOGURT: 'Yogurt is milk thickened by friendly bacteria.',
PANCAKE: 'Pancake Day falls on the day before Lent begins.',
TACO: 'In Mexico, tacos are usually served on small soft corn tortillas.',
SUSHI: 'Sushi refers to the vinegared rice, not the raw fish.',
BAGEL: 'Bagels are boiled before they are baked, giving them a chewy crust.',
CURRY: 'Curry is a broad name for many spiced dishes across South Asia and beyond.',
DUMPLING: 'Almost every cuisine in the world has its own kind of dumpling.',
BURRITO: "Burrito means 'little donkey' in Spanish.",
NACHOS: "Nachos are named after Ignacio 'Nacho' Anaya, who first made them in 1943.",
OMELETTE: 'An omelette is beaten eggs cooked flat in a pan, then folded.',
AVOCADO: "Avocados only ripen after they're picked from the tree.",
POPCORN: 'Popcorn pops when the water inside each kernel turns to steam.',
BROCCOLI: 'Broccoli is a cluster of flower buds, picked before they bloom.',
POTATO: 'Potatoes were first grown in the Andes of South America.',
GARLIC: 'Garlic is a close cousin of onions, leeks and chives.',
ONION: 'Cutting an onion releases a gas that makes your eyes water.',
LEMON: 'A lemon tree can carry blossom and fruit at the same time.',
MANGO: 'The mango is the national fruit of India.',
PEANUT: "Peanuts aren't nuts at all; they're legumes, like peas.",
WALNUT: 'A walnut kernel looks a bit like a tiny brain.',
HONEY: 'Honey kept sealed can last for thousands of years.',
BUTTER: 'It takes about 20 litres of milk to make 1 kg of butter.',
SAUSAGE: 'The word sausage comes from the Latin for salted.',
RISOTTO: 'Risotto rice is stirred to release starch, which makes it creamy.',
LASAGNA: 'Lasagna is one of the oldest known kinds of pasta.',
RAMEN: 'Instant ramen was invented in Japan in 1958.',
SPINACH: 'Spinach shrinks to a fraction of its size when cooked.',
OATMEAL: 'Oats were grown as animal feed long before they became a breakfast.',
CHUTNEY: 'Chutney comes from the Hindi word chatni.',
PAELLA: 'Paella is named after the wide, shallow pan it is cooked in.',
KEBAB: 'Shish kebab means skewered meat in Turkish.',
FALAFEL: 'Falafel is made from ground chickpeas or fava beans.',
GRAVY: 'Gravy is made from the juices that drip from cooking meat.',
},
messages: [
'DINNER IS SERVED',
'SAVE ROOM FOR DESSERT',
'AN APPLE A DAY KEEPS THE DOCTOR AWAY',
'THE WAY TO A HEART IS THROUGH THE STOMACH',
'HONEY NEVER SPOILS IF YOU KEEP IT SEALED',
'THE WORLD EATS BILLIONS OF NOODLES EVERY SINGLE YEAR',
'TOMATOES AND POTATOES BOTH CAME TO EUROPE FROM THE AMERICAS',
'PEANUTS ARE NOT NUTS AND STRAWBERRIES ARE NOT BERRIES BUT BANANAS AND AVOCADOS ARE',
],
},
ocean: {
label: 'Ocean',
ink: '#1f6f8b',
words: {
CORAL: 'Coral reefs cover under one percent of the seabed but shelter about a quarter of sea life.',
SHARK: 'Sharks have been around for longer than trees.',
WHALE: 'The blue whale is the largest animal known to have ever lived.',
OCTOPUS: 'An octopus has three hearts and blue blood.',
DOLPHIN: 'Dolphins sleep with only half of their brain at a time.',
LOBSTER: 'Lobsters taste with their legs.',
STARFISH: 'A starfish can regrow a lost arm.',
SEAWEED: 'Kelp, a seaweed, can grow up to half a metre in a single day.',
JELLYFISH: 'Jellyfish have no brain, heart or bones.',
URCHIN: 'Sea urchins move on hundreds of tiny tube feet.',
OYSTER: 'An adult oyster can filter around 190 litres of water a day.',
MARLIN: 'Marlins are among the fastest fish in the sea.',
SHRIMP: 'Pistol shrimp snap their claws so fast the bubble pops louder than a gunshot.',
ANCHOR: 'Ships used stone anchors long before iron ones.',
LAGOON: 'A lagoon is shallow water cut off from the sea by a reef or sandbar.',
CURRENT: 'The Gulf Stream carries warm water across the Atlantic toward Europe.',
TIDE: 'Tides are mostly caused by the pull of the Moon.',
WAVE: 'Most ocean waves are made by the wind blowing across the water.',
REEF: 'The Great Barrier Reef is the largest structure built by living things.',
SEAHORSE: 'Male seahorses carry the eggs and give birth to the young.',
SQUID: 'Colossal squid have eyes as big as dinner plates.',
CRAB: 'Crabs walk sideways because of the way their legs bend.',
CLAM: 'Some giant clams live for more than 100 years.',
MANATEE: 'Manatees are distant relatives of elephants.',
NARWHAL: "A narwhal's tusk is actually a long spiral tooth.",
ORCA: 'Orcas are the largest members of the dolphin family.',
PLANKTON: 'Tiny ocean plankton make a large share of the oxygen we breathe.',
TRENCH: 'The Mariana Trench is deeper than Mount Everest is tall.',
ABYSS: 'The abyssal zone is cold and pitch dark, 3,000 to 6,000 metres down.',
BARNACLE: 'Barnacles glue themselves head-first to rocks and ships.',
PEARL: 'A pearl forms when an oyster coats an irritant in layers of nacre.',
TURTLE: 'Sea turtles return to the beach where they hatched to lay their eggs.',
STINGRAY: 'Stingrays are flat cousins of sharks.',
EEL: 'European eels swim thousands of kilometres to the Sargasso Sea to spawn.',
TUNA: 'Bluefin tuna can keep their bodies warmer than the water around them.',
SALMON: 'Salmon swim back up the river where they were born to spawn.',
SARDINE: 'Sardines swim in huge shoals for safety in numbers.',
SEAL: 'Seals slow their heartbeat to save oxygen on long dives.',
KRILL: 'Krill are tiny shrimp-like animals that feed the great whales.',
SURF: 'Surfing was a part of Hawaiian life centuries ago.',
BUOY: 'Buoys mark safe channels and hidden dangers for ships.',
ISLAND: 'Some islands are the tops of underwater volcanoes.',
LIGHTHOUSE: 'The Lighthouse of Alexandria was one of the Seven Wonders of the Ancient World.',
DRIFTWOOD: 'Driftwood can float across whole oceans before it washes ashore.',
},
messages: [
'SAIL AWAY WITH THE TIDE',
'THE SEA IS FULL OF SECRETS',
'LIFE IS BETTER AT THE BEACH',
'THE BLUE WHALE HAS A HEART AS BIG AS A SMALL CAR',
'WE HAVE EXPLORED ONLY A TINY PART OF THE DEEP SEA',
'THE OCEAN COVERS MORE THAN SEVENTY PERCENT OF OUR PLANET',
'A BLUE WHALE CAN BE HEARD BY OTHER WHALES HUNDREDS OF KILOMETRES AWAY',
'THE OCEAN HOLDS MOUNTAINS VALLEYS AND CANYONS THAT NO PERSON HAS EVER SEEN WITH THEIR OWN EYES',
],
},
sports: {
label: 'Sports',
ink: '#2e7a3c',
words: {
SOCCER: "Soccer is the world's most popular sport, with billions of fans.",
TENNIS: 'Tennis scores of 15, 30 and 40 may come from the quarters of a clock face.',
HOCKEY: 'Ice hockey pucks are frozen before games so they bounce less.',
BOXING: 'Boxing rings are square, despite the name.',
RUGBY: 'Rugby is named after Rugby School in England.',
SKIING: 'People have used skis to travel over snow for thousands of years.',
CYCLING: 'The Tour de France covers about 3,500 km in three weeks.',
ARCHERY: 'Olympic archers shoot at a target 70 metres away.',
BOWLING: 'A perfect game in ten-pin bowling is 300 points: twelve strikes in a row.',
CRICKET: 'A Test cricket match can last five days.',
DIVING: 'Divers hit the water at around 55 km/h from the 10 metre platform.',
FENCING: 'Fencing has been part of every modern Olympic Games.',
KARATE: "Karate means 'empty hand' in Japanese.",
ROWING: 'Rowers face backwards, the opposite way to where the boat is going.',
SAILING: 'Some sailboats can sail faster than the wind that pushes them.',
SURFING: 'Surfing made its Olympic debut at the Tokyo 2020 Games.',
GOLF: 'Golf balls have dimples to help them fly farther.',
BASEBALL: 'A baseball is held together by 108 double stitches.',
FOOTBALL: 'In most of the world, football means the game Americans call soccer.',
BASKETBALL: 'Basketball was invented in 1891 using peach baskets as hoops.',
VOLLEYBALL: 'Volleyball was invented in 1895 as a gentler game than basketball.',
BADMINTON: 'A badminton shuttlecock can leave the racket at more than 400 km/h.',
JUDO: "Judo means 'the gentle way' in Japanese.",
POLO: 'Polo is one of the oldest team sports, first played in ancient Persia.',
LACROSSE: 'Lacrosse was first played by Indigenous peoples of North America.',
SQUASH: 'Squash balls have to be warmed up before they bounce properly.',
CURLING: 'Most Olympic curling stones are cut from granite from one Scottish island.',
SKATING: 'The earliest ice skates had blades made from animal bones.',
SPRINT: 'Top sprinters reach their fastest speed about 60 metres into a 100 metre race.',
MARATHON: 'The marathon distance was fixed at 42.195 km after the 1908 London Olympics.',
JAVELIN: 'The javelin was redesigned in 1986 after throws went dangerously far.',
HURDLES: 'Hurdles are built to tip over if a runner clips them.',
DISCUS: 'The discus throw was an event at the ancient Greek Olympics.',
TRIATHLON: 'A triathlon combines swimming, cycling and running.',
WRESTLING: 'Wrestling is one of the oldest sports, shown in ancient cave paintings.',
GYMNAST: 'Gymnasts use chalk on their hands to keep a dry grip.',
REFEREE: 'A football referee can run more than 10 km in a single match.',
TROPHY: 'The Stanley Cup has the names of winning players engraved on it.',
MEDAL: 'Olympic gold medals are mostly silver with a coating of gold.',
STADIUM: 'The word stadium comes from an ancient Greek footrace of about 180 metres.',
GOAL: 'Football goals had no nets until the 1890s.',
PADDLE: 'Kayakers use a double-bladed paddle; canoeists usually use a single blade.',
SLALOM: "Slalom comes from Norwegian words for a 'sloping track'.",
CANOE: 'Canoe comes from a Caribbean word for a dug-out boat.',
},
messages: [
'PLAY FAIR AND HAVE FUN',
'PRACTICE MAKES PERFECT',
'TEAMWORK MAKES THE DREAM WORK',
'EVERY CHAMPION WAS ONCE A BEGINNER',
'IT IS NOT WHETHER YOU WIN OR LOSE BUT HOW YOU PLAY',
'THE FIRST MODERN OLYMPIC GAMES WERE HELD IN ATHENS',
'A GOLF BALL HAS AROUND THREE HUNDRED TO FIVE HUNDRED DIMPLES',
'THE FIVE OLYMPIC RINGS STAND FOR CONTINENTS JOINED TOGETHER IN FRIENDLY COMPETITION',
],
},
music: {
label: 'Music',
ink: '#7a3d8f',
words: {
GUITAR: 'Most guitars have six strings, but twelve-string guitars double them up.',
PIANO: 'A standard piano has 88 keys: 52 white and 36 black.',
VIOLIN: 'A violin is made from more than 70 separate pieces of wood.',
DRUMS: 'Drums are among the oldest instruments and were used to send signals over long distances.',
TRUMPET: "Trumpets found in Tutankhamun's tomb are over 3,000 years old.",
FLUTE: 'Flutes carved from bird bone are among the oldest instruments ever found.',
CELLO: 'A cellist plays seated, holding the cello between the knees.',
HARP: 'A concert harp has 47 strings and seven pedals.',
BANJO: 'The banjo grew from instruments brought to the Americas by enslaved West Africans.',
MELODY: 'A melody is a run of notes heard as a single tune.',
RHYTHM: 'Rhythm is one of the longest everyday English words with no vowel except Y.',
TEMPO: 'Tempo markings are often in Italian, like allegro for fast.',
CHORD: 'A chord is three or more notes played at the same time.',
OCTAVE: 'A note an octave higher vibrates exactly twice as fast.',
SONATA: "Sonata comes from the Italian for 'sounded', meaning played rather than sung.",
BALLAD: 'Ballads began as songs that told a story.',
ORCHESTRA: 'Orchestras usually tune to an A played by the oboe.',
SYMPHONY: 'Beethoven was almost completely deaf when he wrote his Ninth Symphony.',
OPERA: "Opera means 'works' in Italian.",
TUBA: 'A tuba has about 5.5 metres of tubing coiled up inside.',
CLARINET: 'A clarinet uses a single reed that vibrates against the mouthpiece.',
OBOE: 'The oboe uses a double reed: two thin blades of cane that vibrate together.',
BASSOON: "Unrolled, a bassoon's tube would be about 2.5 metres long.",
SAXOPHONE: 'Adolphe Sax invented the saxophone in the 1840s.',
TROMBONE: 'The trombone changes pitch with a sliding tube instead of valves.',
UKULELE: "Ukulele is often said to mean 'jumping flea' in Hawaiian.",
ACCORDION: 'An accordion makes sound by squeezing air past metal reeds.',
XYLOPHONE: "Xylophone comes from the Greek for 'wood sound'.",
HARMONICA: 'The harmonica is one of the best-selling instruments in the world.',
CONDUCTOR: "The conductor's baton became common in the 1800s.",
CHOIR: "Singing together in a choir can bring the singers' heartbeats into step.",
LYRICS: 'The word lyrics comes from the lyre, a harp-like instrument of ancient Greece.',
CHORUS: 'In ancient Greek plays, the chorus sang and commented on the action.',
CONCERT: 'Some of the first concerts with paid tickets were held in London in the 1670s.',
ENCORE: "Encore is French for 'again'.",
TENOR: 'The tenor is usually the highest common male singing voice.',
SOPRANO: 'The soprano is the highest singing voice.',
JAZZ: 'Jazz grew up in New Orleans in the early 1900s.',
BLUES: 'The blues grew from the work songs and spirituals of the American South.',
REGGAE: 'Reggae began in Jamaica in the late 1960s.',
FIDDLE: 'A fiddle and a violin are the same instrument, played in different styles.',
MANDOLIN: 'A mandolin has eight strings tuned in four pairs.',
CYMBAL: 'Some cymbal makers have guarded their metal recipes for centuries.',
METRONOME: 'A metronome ticks a steady beat to help musicians keep time.',
},
messages: [
'THE SHOW MUST GO ON',
'FACE THE MUSIC AND DANCE',
'MUSIC IS THE UNIVERSAL LANGUAGE',
'STRIKE UP THE BAND AND SING ALONG',
'A PIANO HAS EIGHTY EIGHT KEYS FROM LOW TO HIGH',
'MOZART WROTE HIS FIRST PIECES OF MUSIC WHEN HE WAS ONLY FIVE',
'MOZART WROTE HIS FIRST PIECES OF MUSIC WHEN HE WAS ONLY FIVE YEARS OLD',
'BEETHOVEN KEPT COMPOSING MUSIC EVEN AFTER HE HAD LOST NEARLY ALL OF HIS HEARING',
],
},
weather: {
label: 'Weather',
ink: '#4a6a86',
words: {
RAINBOW: 'You can only see a rainbow when the Sun is behind you.',
SNOWFLAKE: 'Most snowflakes have six sides because of the way water molecules link up.',
THUNDER: 'Thunder is the boom of air heated suddenly by lightning.',
LIGHTNING: 'A bolt of lightning can be about five times hotter than the surface of the Sun.',
CLOUD: 'A puffy cumulus cloud can weigh as much as 100 elephants.',
STORM: 'At any moment, around 2,000 thunderstorms are rumbling somewhere on Earth.',
TORNADO: 'The strongest tornadoes have winds of over 300 km/h.',
HURRICANE: 'Hurricanes, typhoons and cyclones are the same kind of storm in different oceans.',
BLIZZARD: 'A blizzard needs strong wind and blowing snow, not just a heavy snowfall.',
DRIZZLE: 'Drizzle drops are less than half a millimetre across.',
FOG: 'Fog is simply a cloud that touches the ground.',
MIST: 'Mist is thinner than fog; you can see more than a kilometre through it.',
HAIL: "Hailstones grow in layers as they're tossed up and down inside a storm cloud.",
SLEET: 'Sleet is rain that freezes into ice pellets before it lands.',
FROST: 'Frost forms when water vapour freezes straight onto cold surfaces.',
BREEZE: 'A sea breeze blows onto the land on sunny days as the ground warms up.',
GALE: 'On the Beaufort scale, a gale blows at about 62 to 88 km/h.',
MONSOON: "Monsoon comes from the Arabic word for 'season'.",
CYCLONE: 'Cyclones spin anticlockwise north of the equator and clockwise south of it.',
TYPHOON: 'Typhoon is the name for a hurricane in the northwest Pacific.',
DROUGHT: 'A drought is a long stretch of unusually dry weather.',
HUMIDITY: 'High humidity makes hot days feel hotter because sweat dries slowly.',
ICICLE: 'Icicles grow when meltwater drips and refreezes in cold air.',
PUDDLE: 'A still puddle reflects the sky like a small mirror on the ground.',
UMBRELLA: 'Umbrella comes from the Latin umbra, meaning shade.',
FORECAST: 'The first public weather forecasts were printed in The Times in 1861.',
CLIMATE: 'Weather is what happens today; climate is the pattern over decades.',
SUNSHINE: 'Yuma, Arizona, is often called the sunniest place on Earth.',
HEATWAVE: 'Heatwaves are among the deadliest kinds of extreme weather.',
THERMOMETER: 'Galileo built one of the first devices for showing changes in temperature.',
BAROMETER: 'A falling barometer often means stormy weather is on the way.',
DEW: 'Dew forms when the air cools overnight and its water vapour condenses.',
TEMPEST: "Shakespeare's play The Tempest opens with a storm at sea.",
OVERCAST: 'An overcast sky is completely covered by cloud.',
SQUALL: 'A squall is a sudden, sharp rise in wind speed.',
FLURRY: 'A flurry is a light, brief shower of snow.',
SOLSTICE: 'The summer solstice is the longest day of the year.',
SMOG: 'Smog is a blend of the words smoke and fog.',
CIRRUS: 'Cirrus clouds are thin wisps made of ice crystals high in the sky.',
CUMULUS: "Cumulus means 'heap' in Latin, after its piled-up shape.",
STRATUS: 'Stratus clouds form flat grey layers that can cover the whole sky.',
NIMBUS: 'Nimbus is Latin for cloud, and marks the clouds that bring rain.',
WEATHERVANE: 'A weathervane points into the wind, showing where it is coming from.',
WINDCHILL: 'Wind chill is how cold it feels when the wind strips heat from your skin.',
},
messages: [
'SUNSHINE AFTER THE RAIN',
'IT IS RAINING CATS AND DOGS',
'EVERY CLOUD HAS A SILVER LINING',
'RED SKY AT NIGHT SHEPHERDS DELIGHT',
'NO TWO SNOWFLAKES ARE EXACTLY ALIKE',
'WHATEVER THE WEATHER WE WILL WEATHER IT TOGETHER',
'LIGHTNING STRIKES SOMEWHERE ON EARTH ABOUT FORTY TIMES EVERY SECOND',
'COUNT THE SECONDS BETWEEN LIGHTNING AND THUNDER TO TELL HOW FAR AWAY THE STORM IS',
],
},
garden: {
label: 'Garden',
ink: '#4f7a2a',
words: {
ROSE: 'Fossils show that roses have been around for over 30 million years.',
TULIP: 'In 1630s Holland, a single tulip bulb could sell for more than a house.',
DAISY: "Daisy comes from 'day's eye', because the flower opens at dawn.",
SUNFLOWER: 'Young sunflowers turn to follow the Sun across the sky.',
LAVENDER: 'Lavender has been used to scent baths since Roman times.',
DAFFODIL: 'Daffodil sap can make other flowers in the same vase wilt.',
ORCHID: 'Orchids are one of the largest plant families, with over 25,000 species.',
LILY: 'Lilies are poisonous to cats, even the pollen.',
POPPY: 'Poppy seeds can lie in the soil for years, waiting for the ground to be dug.',
VIOLET: 'Sugared violets were a favourite treat in Victorian times.',
PANSY: "Pansy comes from the French pensée, meaning 'thought'.",
MARIGOLD: 'Gardeners plant marigolds to help keep pests away from vegetables.',
BLUEBELL: "Around half of the world's bluebells grow in Britain.",
BUTTERCUP: 'Holding a buttercup under your chin is an old game said to show if you like butter.',
DANDELION: 'Every part of a dandelion is edible, from the flower to the root.',
IVY: 'Ivy climbs walls using tiny root-like hairs that cling to the surface.',
FERN: "Ferns don't make seeds; they spread by spores.",
LICHEN: 'A lichen is a fungus and an alga living together as a single partnership.',
HEDGE: 'Some hedgerows in England are over 700 years old.',
TROWEL: 'A trowel is a small hand tool for digging and planting.',
RAKE: 'A pile of raked leaves makes good compost and a cosy home for hedgehogs.',
WHEELBARROW: 'Wheelbarrows were used in ancient China nearly 2,000 years ago.',
GREENHOUSE: 'Glass lets sunlight into a greenhouse but traps much of the warmth.',
COMPOST: 'Earthworms help turn kitchen scraps into rich compost.',
SEEDLING: 'Seedlings lean toward the light, a habit called phototropism.',
BULB: "A bulb is an underground store of food that feeds next year's flower.",
PETAL: 'Some petals have patterns that only bees can see.',
POLLEN: 'Bees carry pollen home in little baskets on their back legs.',
THORN: 'Rose thorns are really prickles, not true thorns.',
SOIL: 'A spoonful of healthy soil holds more living things than there are people on Earth.',
MULCH: 'Mulch keeps soil moist and stops weeds from sprouting.',
BLOSSOM: 'Japan celebrates cherry blossom season with picnics called hanami.',
TOPIARY: 'Topiary is the art of clipping shrubs into shapes.',
TRELLIS: 'A trellis gives climbing plants a framework to grow up.',
SCARECROW: 'Scarecrows have guarded crops for thousands of years.',
GNOME: 'Garden gnomes first became popular in 19th-century Germany.',
PEONY: 'A peony can keep flowering in the same spot for decades.',
HYACINTH: 'Hyacinths are named after Hyacinthus, a figure from Greek myth.',
GERANIUM: 'Geranium comes from the Greek word for crane, after its beak-shaped seed pods.',
CROCUS: "Saffron, the world's priciest spice, comes from a crocus flower.",
MAGNOLIA: 'Magnolias are so ancient that they evolved before bees and are pollinated by beetles.',
WISTERIA: 'A famous wisteria in Japan spreads over half an acre.',
HONEYSUCKLE: 'Honeysuckle smells strongest in the evening, to attract moths.',
FOXGLOVE: 'Foxglove is the source of digitalis, a heart medicine.',
},
messages: [
'STOP AND SMELL THE ROSES',
'BLOOM WHERE YOU ARE PLANTED',
'APRIL SHOWERS BRING MAY FLOWERS',
'A GARDEN IS A FRIEND YOU CAN VISIT ANY TIME',
'TO PLANT A GARDEN IS TO BELIEVE IN TOMORROW',
'BEES VISIT MILLIONS OF FLOWERS TO MAKE A SINGLE JAR OF HONEY',
'A SUNFLOWER CAN GROW TALLER THAN A GIRAFFE WHEN THE SOIL AND SUN ARE JUST RIGHT',
'THE BEST TIME TO PLANT A TREE WAS TWENTY YEARS AGO AND THE SECOND BEST TIME IS TODAY',
],
},
railway: {
label: 'Railway',
ink: '#8a2f2f',
words: {
LOCOMOTIVE: "Stephenson's Rocket won the Rainhill locomotive trials in 1829.",
CARRIAGE: 'Early railway carriages were built like stagecoaches on rails.',
STATION: "Tokyo's Shinjuku is often called the busiest railway station in the world.",
PLATFORM: 'Some of the longest railway platforms in the world are over a kilometre long.',
TICKET: "Thomas Edmondson's printed card tickets were used for well over a century.",
CONDUCTOR: 'The conductor checks tickets and looks after the passengers.',
SIGNAL: 'Railway signals once used coloured lamps that burned oil.',
TUNNEL: 'The Gotthard Base Tunnel in Switzerland runs for 57 km.',
VIADUCT: 'A viaduct carries a railway across a valley on a row of arches.',
BRIDGE: "Scotland's Forth Bridge is a World Heritage Site.",
CABOOSE: 'A caboose gave the crew a place to watch the train from the back.',
FREIGHT: 'Some freight trains stretch more than 3 km long.',
EXPRESS: 'An express train skips the smaller stations along the line.',
WHISTLE: 'Engine drivers used whistle codes to signal to the crew and the stations.',
BOILER: "A steam locomotive's boiler turns water into high-pressure steam.",
PISTON: 'Steam pushes the pistons, and the pistons turn the driving wheels.',
STEAM: 'Water expands about 1,600 times when it turns to steam.',
DIESEL: 'Diesel engines are named after Rudolf Diesel, who patented his design in 1892.',
ENGINE: 'Railway enthusiasts often know engines by their numbers.',
TRACK: 'Standard gauge track is 1,435 mm between the rails.',
SLEEPER: 'In Britain the beams under the rails are called sleepers; in America, ties.',
JUNCTION: "Clapham Junction in London is one of Europe's busiest stations.",
TIMETABLE: 'Railway timetables helped bring standard time zones into use.',
CROSSING: 'Level crossings let roads cross railway lines at the same height.',
GAUGE: 'Track gauge is the distance between the two rails.',
COUPLING: 'Couplings join railway wagons together.',
TENDER: 'A tender is the wagon behind a steam engine that carries its coal and water.',
FIREMAN: "A steam engine's fireman shovelled coal into the firebox.",
DRIVER: 'In Britain the person at the controls is the driver; in America, the engineer.',
PORTER: "Station porters carried passengers' luggage to and from the trains.",
LUGGAGE: 'Some early trains carried luggage on the carriage roofs.',
SUITCASE: 'Suitcases with wheels only caught on in the 1970s.',
DEPOT: 'Engines are cleaned and repaired at the depot.',
TERMINUS: 'A terminus is a station at the very end of a line.',
SIDING: 'A siding is a short track off the main line where trains can wait.',
TURNTABLE: 'A turntable spins a locomotive round to face the other way.',
BUFFER: 'Buffers at the end of the track stop trains from running off the line.',
LANTERN: 'Guards waved lanterns to signal to the driver after dark.',
PASSENGER: 'The first public railway to carry passengers by steam opened in England in 1825.',
JOURNEY: 'The Trans-Siberian journey from Moscow to Vladivostok takes about a week.',
MONORAIL: 'The Wuppertal monorail in Germany has been running since 1901.',
FUNICULAR: 'A funicular hauls two cars up a slope, one balancing the other.',
CARGO: 'Trains move cargo using far less fuel per tonne than lorries.',
SEMAPHORE: 'Semaphore signals use a swinging arm to tell drivers to stop or go.',
},
messages: [
'PLEASE MIND THE GAP',
'NEXT STOP THE END OF THE LINE',
'ALL ABOARD THE PUZZLE EXPRESS',
'THE JOURNEY IS THE DESTINATION',
'SIT BACK AND WATCH THE COUNTRYSIDE ROLL BY',
'STEAM TRAINS NEED COAL AND WATER AND A HARD WORKING FIREMAN',
'THE FIRST STEAM RAILWAY FOR PASSENGERS OPENED IN ENGLAND IN EIGHTEEN TWENTY FIVE',
'RAILWAYS HELPED THE WORLD AGREE ON TIME ZONES SO THE TRAINS COULD RUN ON SCHEDULE',
],
},
dinosaurs: {
label: 'Dinosaurs',
ink: '#6b6b2a',
words: {
TYRANNOSAUR: 'Tyrannosaurus rex had teeth about as long as bananas.',
TRICERATOPS: 'Triceratops had a bony frill and three horns on its face.',
STEGOSAURUS: 'Stegosaurus had a brain roughly the size of a walnut.',
VELOCIRAPTOR: 'The real Velociraptor was about the size of a turkey, and it had feathers.',
DIPLODOCUS: 'Diplodocus may have cracked its long tail like a whip.',
ALLOSAURUS: 'Allosaurus was a top predator of the late Jurassic in North America.',
IGUANODON: 'Iguanodon had a spiky thumb that was once mistaken for a horn on its nose.',
SPINOSAURUS: 'Spinosaurus had a tall sail on its back and hunted fish.',
PTEROSAUR: 'Pterosaurs were flying reptiles, close cousins of the dinosaurs.',
MOSASAUR: 'Mosasaurs were huge sea-going lizards that lived alongside the dinosaurs.',
PLESIOSAUR: 'Plesiosaurs swam with four big flippers, like underwater wings.',
ANKYLOSAUR: 'Ankylosaurs had bony armour and a heavy club at the end of the tail.',
APATOSAURUS: 'Some Apatosaurus fossils were once labelled Brontosaurus.',
MAIASAURA: "Maiasaura means 'good mother lizard'; fossils show it cared for its young.",
OVIRAPTOR: "Oviraptor means 'egg thief', but it was probably guarding its own eggs.",
TITANOSAUR: 'Titanosaurs were among the largest animals ever to walk on land.',
GALLIMIMUS: 'Gallimimus looked a bit like a giant ostrich and was a fast runner.',
HADROSAUR: 'Duck-billed hadrosaurs had hundreds of teeth for grinding plants.',
FOSSIL: "Fossil comes from the Latin for 'dug up'.",
AMBER: 'Amber is fossilised tree resin that can trap insects for millions of years.',
SKELETON: 'Sue, one of the most complete T. rex skeletons ever found, is in a Chicago museum.',
JURASSIC: 'The Jurassic period is named after the Jura Mountains in Europe.',
TRIASSIC: 'The first dinosaurs appeared in the Triassic, about 230 million years ago.',
CRETACEOUS: 'The Cretaceous ended 66 million years ago with a huge mass extinction.',
EXTINCT: 'Birds are the only dinosaurs that did not go extinct.',
CARNIVORE: 'Meat-eating dinosaurs walked on two legs.',
HERBIVORE: 'The biggest dinosaurs of all were plant eaters.',
CLAW: 'Therizinosaurus had claws nearly a metre long.',
NEST: 'Some dinosaurs laid their eggs in neat rings in the nest.',
EGG: 'The largest dinosaur eggs were about the size of a football.',
MUSEUM: "London's Natural History Museum once displayed a famous Diplodocus cast called Dippy.",
EXCAVATE: 'Fossil hunters excavate bones with brushes and dental picks.',
MAMMOTH: 'Woolly mammoths were still alive when the Egyptian pyramids were built.',
PREDATOR: 'Many predators had forward-facing eyes to help them judge distance.',
PREHISTORIC: 'Prehistoric means from the time before anything was written down.',
ASTEROID: 'The asteroid that ended the age of dinosaurs struck near Mexico.',
FEATHER: 'Many dinosaurs had feathers, long before birds took to the air.',
COPROLITE: 'A coprolite is fossilised dung, and it shows what dinosaurs ate.',
FOOTPRINT: 'Fossil footprints reveal how fast some dinosaurs walked.',
PANGAEA: 'When the first dinosaurs appeared, the continents were joined as Pangaea.',
TOOTH: 'Dinosaurs replaced their lost teeth throughout their lives.',
VOLCANO: 'Huge volcanic eruptions in India may have helped end the dinosaurs.',
SAUROPOD: 'Sauropods were long-necked giants that stripped leaves from the treetops.',
SEDIMENT: 'Most fossils formed when bones were buried in mud or sand.',
},
messages: [
'DIG DEEP AND DISCOVER',
'BIRDS ARE LIVING DINOSAURS',
'BONES TELL ANCIENT STORIES',
'FOSSILS ARE NATURES TIME CAPSULES',
'THE BIGGEST DINOSAURS WERE LONGER THAN THREE BUSES',
'A TYRANNOSAUR LIVED CLOSER IN TIME TO US THAN TO A STEGOSAURUS',
'DINOSAURS RULED THE EARTH FOR MORE THAN ONE HUNDRED AND SIXTY MILLION YEARS',
'FOSSIL HUNTERS USE BRUSHES AND PICKS TO UNCOVER BONES THAT HAVE WAITED MILLIONS OF YEARS',
],
},
birds: {
label: 'Birds',
ink: '#3a6f6f',
words: {
ROBIN: 'American and European robins are different birds that share a red breast.',
SPARROW: 'House sparrows have followed people around the world for thousands of years.',
EAGLE: "An eagle's eyesight is about four to five times sharper than ours.",
OWL: 'An owl can turn its head about 270 degrees.',
FALCON: 'A diving peregrine falcon can top 300 km/h, the fastest animal on Earth.',
HAWK: 'Hawks hunt by day, while most owls hunt at night.',
PARROT: 'Some parrots can live for more than 80 years.',
PENGUIN: "Penguins can't fly in the air, but they fly underwater with their flippers.",
OSTRICH: 'The ostrich lays the largest egg of any living bird.',
FLAMINGO: 'Flamingos are pink because of pigments in the shrimp and algae they eat.',
PEACOCK: 'Only male peafowl, the peacocks, have the dazzling tail train.',
PELICAN: "A pelican's throat pouch can hold about three times more than its stomach.",
TOUCAN: "A toucan's huge bill is light, and it helps the bird shed heat.",
HUMMINGBIRD: 'Hummingbirds are the only birds that can fly backwards.',
WOODPECKER: 'A woodpecker can peck up to 20 times a second.',
KINGFISHER: "Japan's bullet train nose was redesigned to copy the kingfisher's beak.",
SWALLOW: 'Swallows migrate thousands of kilometres between Europe and Africa every year.',
SWAN: 'Swans often pair up with one partner for life.',
HERON: 'Herons stand perfectly still in shallow water, waiting to spear fish.',
STORK: 'White storks return to the same rooftop nests year after year.',
PUFFIN: 'A puffin can carry a dozen or more small fish in its beak at once.',
ALBATROSS: 'The wandering albatross has the longest wingspan of any living bird, up to 3.5 metres.',
GULL: 'Gulls can drink seawater; special glands remove the salt.',
CROW: 'Crows can recognise individual human faces.',
RAVEN: 'Ravens can solve puzzles and even plan ahead.',
MAGPIE: 'Magpies can recognise themselves in a mirror.',
CARDINAL: 'The northern cardinal is the state bird of seven US states.',
FINCH: "Darwin's finches helped him work out how species change over time.",
WREN: 'The tiny wren has a remarkably loud song for its size.',
PIGEON: 'Homing pigeons can find their way home from hundreds of kilometres away.',
DOVE: 'Doves and pigeons belong to the same bird family.',
CANARY: 'Miners once took canaries underground to warn them of dangerous gas.',
CUCKOO: "Some cuckoos lay their eggs in other birds' nests.",
KIWI: 'The kiwi has nostrils at the very tip of its long bill.',
EMU: "Emus can run at about 50 km/h, but they can't fly.",
VULTURE: 'Vultures help keep the land clean by eating carrion.',
CONDOR: 'The Andean condor can soar for hours without flapping its wings.',
KESTREL: 'Kestrels hover in place while they scan the ground for mice.',
NIGHTINGALE: 'Nightingales are famous for singing at night as well as by day.',
LARK: 'Skylarks sing while they hover high above the fields.',
STARLING: 'Starlings gather in huge swirling flocks called murmurations.',
GOOSE: 'Geese fly in a V shape to save energy on long journeys.',
CRANE: 'Cranes perform leaping dances to court their mates.',
HORNBILL: 'Female hornbills seal themselves inside tree holes while they nest.',
},
messages: [
'WATCH THE BIRDIE',
'AS FREE AS A BIRD IN FLIGHT',
'SPREAD YOUR WINGS AND FLY',
'THE EARLY BIRD CATCHES THE WORM',
'BIRDS OF A FEATHER FLOCK TOGETHER',
'ARCTIC TERNS FLY FROM POLE TO POLE EVERY YEAR',
'A HUMMINGBIRD HEART CAN BEAT OVER ONE THOUSAND TIMES A MINUTE',
'OWLS CANNOT MOVE THEIR EYES SO THEY TURN THEIR WHOLE HEADS INSTEAD',
'THE OSTRICH HAS THE LARGEST EYES OF ANY LAND ANIMAL AND EACH ONE IS BIGGER THAN ITS BRAIN',
],
},
insects: {
label: 'Insects',
ink: '#7a5a1a',
words: {
BUMBLEBEE: 'Bumblebees can fly in cool weather because they shiver to warm up.',
BEETLE: 'About one in every four known animal species is a beetle.',
BUTTERFLY: 'Butterflies taste with their feet.',
MOTH: 'Some moths have no mouths and never eat as adults.',
DRAGONFLY: 'Dragonflies catch more than 90 percent of the prey they chase.',
LADYBUG: 'A single ladybug can eat thousands of aphids in its lifetime.',
GRASSHOPPER: 'Grasshoppers have ears on their bellies.',
CATERPILLAR: 'A caterpillar has thousands of muscles; you have about 650.',
MOSQUITO: 'Only female mosquitoes bite; they need blood to make their eggs.',
FIREFLY: 'Fireflies make cold light with almost no wasted heat.',
WASP: 'Paper wasps chew wood into pulp to build their nests.',
HORNET: 'Hornets are the largest kind of social wasp.',
TERMITE: 'Some termite mounds are taller than a giraffe.',
FLEA: 'A flea can jump about 100 times its own body length.',
MANTIS: 'A praying mantis can turn its head 180 degrees.',
CICADA: 'Some cicadas spend 17 years underground before they come out.',
APHID: 'Some aphids are born already pregnant.',
WEEVIL: 'Weevils are beetles with long snouts.',
EARWIG: "Despite the old tale, earwigs don't crawl into people's ears.",
LOCUST: 'A locust swarm can contain billions of insects.',
COCKROACH: 'A cockroach can live for about a week without its head.',
LARVA: 'A larva is the young stage of an insect, like a caterpillar or a grub.',
PUPA: 'Inside a pupa, a larva rebuilds its body into an adult.',
COCOON: 'A silkworm cocoon is spun from a single thread up to a kilometre long.',
CHRYSALIS: "A butterfly's chrysalis is its hard pupa case, not a silk cocoon.",
NECTAR: 'Bees turn flower nectar into honey.',
HIVE: 'A busy beehive can hold tens of thousands of bees.',
COLONY: 'Leafcutter ant colonies farm fungus on the leaves they collect.',
THORAX: "An insect's legs and wings are all attached to its thorax.",
ABDOMEN: 'Insects breathe through tiny holes along their abdomen.',
WING: 'A honeybee beats its wings about 200 times a second.',
GNAT: 'Gnats often gather in dancing clouds on summer evenings.',
MIDGE: "Scotland's Highland midges are famous for biting walkers in summer.",
SCARAB: 'Ancient Egyptians saw the dung-rolling scarab as a symbol of the Sun.',
SILKWORM: 'Silk has been made from silkworm cocoons in China for thousands of years.',
KATYDID: 'Katydids are named after the sound of their song.',
HOVERFLY: 'Hoverflies look like wasps, but they are harmless.',
MAYFLY: 'Some adult mayflies live for only a few hours.',
DAMSELFLY: "Damselflies fold their wings along their backs at rest; dragonflies don't.",
SWARM: 'Honeybees swarm when a colony splits to start a new home.',
POLLINATE: "Insects pollinate most of the world's flowering plants.",
MONARCH: 'Monarch butterflies migrate up to 4,000 km to Mexico each autumn.',
HONEYCOMB: 'Bees build hexagonal honeycomb from wax they make in their own bodies.',
EXOSKELETON: 'Insects wear their skeleton on the outside: an exoskeleton.',
},
messages: [
'SNUG AS A BUG IN A RUG',
'AS BUSY AS A BUMBLEBEE',
'BUTTERFLIES TASTE WITH THEIR FEET',
'THE WORLD IS ALIVE WITH TINY WONDERS',
'ANTS CAN LIFT MANY TIMES THEIR OWN WEIGHT',
'THERE ARE MORE INSECTS ON EARTH THAN ANY OTHER KIND OF ANIMAL',
'A BEE MUST VISIT ABOUT TWO MILLION FLOWERS TO MAKE HALF A KILO OF HONEY',
'FIREFLIES FLASH THEIR LIGHTS IN PATTERNS TO FIND EACH OTHER ON WARM SUMMER EVENINGS',
],
},
camping: {
label: 'Camping',
ink: '#3f5f2a',
words: {
TENT: 'The first tents were made from animal skins stretched over poles.',
CAMPFIRE: 'Always drown a campfire with water and stir the ashes before you leave.',
LANTERN: 'Early camping lanterns burned oil or kerosene.',
COMPASS: 'A compass needle points to magnetic north, not the North Pole itself.',
BACKPACK: 'Hikers pack the heaviest gear close to their back for balance.',
HAMMOCK: 'Hammocks were used in Central and South America long before Europeans arrived.',
TRAIL: 'The Appalachian Trail runs about 3,500 km from Georgia to Maine.',
HIKING: 'Hiking uphill burns far more energy than walking on the flat.',
CANOE: 'Indigenous peoples of North America built canoes from birch bark.',
KAYAK: 'Kayaks were first built by Arctic peoples from driftwood and seal skin.',
MARSHMALLOW: 'Marshmallows were once made from the root of the marsh mallow plant.',
FLASHLIGHT: 'Early flashlights could only shine in short flashes, hence the name.',
MAP: 'Topographic maps show the shape of the land with contour lines.',
FOREST: "Forests cover about a third of Earth's land.",
CABIN: 'Log cabins were built from logs notched to lock together at the corners.',
LAKE: "Lake Baikal in Siberia holds about a fifth of Earth's fresh surface water.",
RIVER: 'The Amazon carries more water than any other river.',
MOUNTAIN: 'Mount Everest grows a few millimetres taller every year.',
SUMMIT: 'The summit is the highest point of a mountain.',
CANYON: 'The Grand Canyon is about 1.8 km deep in places.',
VALLEY: 'Many valleys were carved out by rivers or glaciers.',
MEADOW: 'Mountain meadows burst into wildflowers in early summer.',
WATERFALL: "Angel Falls in Venezuela is the world's tallest waterfall, at 979 metres.",
BINOCULARS: 'Binoculars are two small telescopes joined side by side.',
THERMOS: 'A vacuum flask keeps drinks hot because heat cannot cross the vacuum easily.',
KINDLING: 'Kindling is the small dry wood that gets a fire going.',
FIREWOOD: 'Dry, seasoned firewood burns hotter and with less smoke.',
MATCHES: 'Safety matches only light when struck on the strip on their box.',
HATCHET: 'A hatchet is a small axe for chopping kindling.',
TARP: 'A tarp strung over camp keeps the rain off.',
SKILLET: 'A cast-iron skillet can last for generations.',
CANTEEN: 'Canteens were once made from wood, leather or gourds.',
RANGER: 'Park rangers protect wildlife and help visitors stay safe.',
BEAR: 'Bears can smell food from far away, so campers lock it up at night.',
PINECONE: "Pinecones close up in wet weather and open again when it's dry.",
ACORN: 'A mighty oak can grow from a single acorn.',
CAMPSITE: 'Pitch your tent on higher ground so the rain drains away.',
FISHING: 'Fishing hooks have been found that are over 20,000 years old.',
WILDERNESS: 'Leave No Trace means leaving the wilderness just as you found it.',
GEYSER: 'Old Faithful in Yellowstone erupts roughly every hour and a half.',
BOULDER: 'Glaciers can carry boulders far from where they started.',
CREEK: 'A creek is a small stream, often feeding a larger river.',
BONFIRE: "Bonfire comes from 'bone fire', from a time when bones were burned.",
STARGAZING: 'Far from city lights, you can see thousands of stars with the naked eye.',
},
messages: [
'HAPPY TRAILS TO YOU',
'THE MOUNTAINS ARE CALLING',
'SLEEP UNDER A SKY FULL OF STARS',
'LIFE IS BETTER AROUND A CAMPFIRE',
'TAKE ONLY PHOTOS AND LEAVE ONLY FOOTPRINTS',
'THE BEST VIEWS COME AFTER THE HARDEST CLIMBS',
'ALWAYS PACK A MAP AND A COMPASS AND PLENTY OF WATER AND A WARM JACKET',
'STORE YOUR FOOD SAFELY AT NIGHT SO CURIOUS BEARS AND RACCOONS STAY OUT OF YOUR CAMP',
],
},
baking: {
label: 'Baking',
ink: '#a0522d',
words: {
CUPCAKE: 'Cupcakes were once baked in teacups, which may be how they got their name.',
COOKIE: 'The chocolate chip cookie was invented in the 1930s at the Toll House Inn.',
MUFFIN: 'American muffins are quick breads; English muffins are griddled yeast rolls.',
CROISSANT: "Croissant is French for 'crescent', after its curved shape.",
PRETZEL: "A pretzel's twist is said to look like arms folded in prayer.",
SCONE: 'Whether jam or cream goes first on a scone is hotly debated in Britain.',
BAGEL: 'Boiling bagels before baking gives them their chewy crust.',
BISCUIT: "Biscuit comes from the Latin for 'twice cooked'.",
BROWNIE: 'Brownies are said to have been created at a Chicago hotel in 1893.',
DOUGHNUT: 'The hole helps a doughnut cook evenly all the way through.',
PIE: 'Medieval pie crusts were often tough cases, called coffins, not meant to be eaten.',
TART: 'A tart has a pastry base but usually no pastry lid.',
ECLAIR: "Eclair is French for 'flash of lightning', perhaps because it's eaten so fast.",
MACARON: 'French macarons are made from almond flour, egg whites and sugar.',
CHEESECAKE: 'The ancient Greeks served a kind of cheesecake to athletes at the Olympics.',
FLOUR: 'Flour and flower were once the same word in English.',
SUGAR: "Sugar was once so costly that it was called 'white gold'.",
YEAST: 'Yeast is a living fungus whose bubbles of gas make bread rise.',
BUTTER: 'Cold butter makes flaky pastry because it melts into steamy pockets in the oven.',
OVEN: "Pompeii's bakeries still have their stone ovens, nearly 2,000 years on.",
WHISK: 'Whisking traps tiny air bubbles that make eggs and cream fluffy.',
SPATULA: 'Spatula comes from the Latin for a small flat blade.',
APRON: "An apron was once 'a napron', until people heard the n in the wrong place.",
KNEAD: 'Kneading dough builds gluten, which makes bread stretchy and strong.',
FROSTING: 'Frosting and icing are often the same thing, depending on where you live.',
ICING: 'Royal icing sets rock hard and is used to decorate fancy cakes.',
SPRINKLES: 'In the Netherlands, chocolate sprinkles called hagelslag are eaten on toast.',
VANILLA: 'Vanilla comes from the seed pod of an orchid.',
CINNAMON: 'Cinnamon is the dried inner bark of a tree.',
NUTMEG: 'Nutmeg was once worth more than its weight in gold.',
GINGERBREAD: 'Gingerbread houses became popular in Germany after the tale of Hansel and Gretel.',
SOURDOUGH: 'A sourdough starter can be kept alive for decades.',
BAGUETTE: 'French law sets out what may go into a traditional baguette.',
STRUDEL: 'Good strudel pastry is rolled so thin you could read a newspaper through it.',
SOUFFLE: "Soufflé is French for 'puffed up'.",
MERINGUE: 'Meringue is just egg whites and sugar whisked into stiff peaks.',
PASTRY: 'Puff pastry can have hundreds of thin layers of butter and dough.',
CUSTARD: 'Custard is thickened with eggs, or with cornflour in custard powder.',
CARAMEL: 'Caramel is sugar heated until it melts and turns golden brown.',
CHOCOLATE: 'Chocolate comes from cacao beans, which grow in pods on trees.',
CRUMPET: 'Crumpets get their holes from bubbles rising as they cook on a griddle.',
BRIOCHE: 'Brioche is a rich bread made with lots of eggs and butter.',
PRALINE: 'Pralines are named after a French diplomat whose cook created them.',
SHORTBREAD: "Shortbread is called 'short' because the butter keeps it crumbly.",
},
messages: [
'KEEP CALM AND BAKE ON',
'HOME IS WHERE THE OVEN IS',
'BAKE THE WORLD A BETTER PLACE',
'LIFE IS SHORT SO EAT DESSERT FIRST',
'A PINCH OF SALT MAKES SWEET THINGS TASTE SWEETER',
'BREAD HAS BEEN BAKED FOR MORE THAN TEN THOUSAND YEARS',
'THE SMELL OF FRESH BREAD BAKING IN THE OVEN IS ONE OF LIFES SIMPLE JOYS',
'ALWAYS PREHEAT THE OVEN AND LET YOUR CAKE COOL BEFORE YOU SPREAD THE FROSTING ON TOP',
],
},
castles: {
label: 'Castles',
ink: '#5a4a7a',
words: {
CASTLE: 'Windsor Castle is the oldest and largest occupied castle in the world.',
KNIGHT: "A knight's training could begin at about seven years old, as a page.",
KING: "Louis XIV of France reigned for 72 years, longer than any other European king.",
QUEEN: 'In chess, the queen is the most powerful piece on the board.',
PRINCESS: "Princess comes from the Latin princeps, meaning 'first'.",
MOAT: 'Many castle moats were dry ditches rather than water-filled.',
DRAWBRIDGE: 'A drawbridge was raised on chains to seal off the castle gate.',
TOWER: 'Round towers were harder to knock down than square ones.',
TURRET: 'A turret is a small tower built onto a larger wall or tower.',
DUNGEON: "Dungeon comes from the French donjon, the castle's great tower.",
ARMOR: 'A full suit of plate armor weighed about 20 to 25 kg, spread across the body.',
SHIELD: 'Coats of arms on shields helped tell knights apart in battle.',
SWORD: 'A medieval sword usually weighed only about 1 to 1.5 kg.',
LANCE: 'Jousting knights charged with long wooden lances designed to shatter.',
BANNER: 'Banners showed where a lord stood on a crowded battlefield.',
CROWN: 'The Imperial State Crown is set with nearly 3,000 diamonds.',
THRONE: 'Throne comes from the Greek thronos, a raised seat.',
JESTER: 'Jesters could sometimes mock the king and get away with it.',
SQUIRE: 'A squire served a knight while training to become one.',
DRAGON: 'Dragons appear in the myths of cultures all around the world.',
WIZARD: 'Wizard comes from an old word for a wise person.',
RAMPART: 'Ramparts were broad defensive walls topped with walkways.',
PORTCULLIS: 'A portcullis is a heavy grille that drops down to block the gate.',
BATTLEMENT: 'The gaps in a battlement are called crenels; the raised parts are merlons.',
CATAPULT: 'Catapults hurled rocks, fire and worse over castle walls.',
TREBUCHET: 'A trebuchet used a heavy counterweight to fling huge stones.',
ARCHER: 'A skilled longbowman could loose about ten arrows a minute.',
CROSSBOW: 'A crossbow was easier to learn than a longbow but slower to reload.',
HELMET: "A knight's visor had slits so he could see and breathe.",
GAUNTLET: 'Throwing down a gauntlet was a challenge to a duel.',
BANQUET: 'Medieval banquets could include roast peacock served in its feathers.',
HERALD: 'Heralds carried messages and kept track of coats of arms.',
CHAPEL: 'Most castles had their own chapel for daily prayers.',
COURTYARD: 'The courtyard, or bailey, held stables, workshops and kitchens.',
GATEHOUSE: 'The gatehouse was often the most heavily defended part of a castle.',
FORTRESS: 'Masada, a fortress on a desert mountain top, overlooks the Dead Sea.',
SIEGE: 'Some castle sieges dragged on for months, until the food ran out.',
MINSTREL: 'Minstrels travelled from castle to castle singing songs and telling tales.',
DUKE: 'In Britain, a duke is the highest rank of nobility below the royal family.',
BARON: 'In 1215, English barons forced King John to agree to Magna Carta.',
TAPESTRY: 'Tapestries helped keep draughty castle walls a little warmer.',
GOBLET: 'Wealthy lords drank from goblets of silver or pewter.',
TORCH: 'Castles were lit by torches, candles and fires after dark.',
MANOR: "A lord's manor included his house, his farmland and the village around it.",
},
messages: [
'LONG LIVE THE KING',
'A KNIGHT IN SHINING ARMOR',
'HEAVY IS THE HEAD THAT WEARS THE CROWN',
'RAISE THE DRAWBRIDGE AND GUARD THE GATE',
'THE TOWER OF LONDON HAS BEEN GUARDED BY RAVENS FOR CENTURIES',
'SOME CASTLES HAD SECRET PASSAGES HIDDEN BEHIND THEIR THICK STONE WALLS',
'BUILDING A STONE CASTLE COULD TAKE TEN YEARS AND THOUSANDS OF WORKERS HAULING ROCK BY HAND',
'A KNIGHT TRAINED FOR YEARS AS A PAGE AND THEN AS A SQUIRE BEFORE HE COULD EARN HIS SPURS',
],
},
};
// Fallback phrases about the trip itself, for any chapter.
export const JOURNEY_MESSAGES = [
'ENJOY THE RIDE',
'TICKETS PLEASE',
'WISH YOU WERE HERE',
'NEXT STOP PUZZLE TOWN',
'THE JOURNEY IS HALF THE FUN',
'ENJOY THE VIEW FROM THE WINDOW',
'WELL DONE YOU FOUND EVERY WORD',
'A GOOD PUZZLE MAKES THE MILES FLY BY',
'SIT BACK RELAX AND ENJOY THE JOURNEY',
'THANK YOU FOR RIDING THE PUZZLE EXPRESS TODAY',
'KEEP YOUR EYES PEELED FOR THE NEXT STATION ON THE LINE',
'THE FIELDS ROLL BY AS THE TRAIN RATTLES ON TOWARD THE COAST',
'PLEASE KEEP YOUR TICKET HANDY AND ENJOY THE REST OF THE JOURNEY',
'THE TRAIN WHISTLES THROUGH THE VALLEY WHILE YOU CIRCLE ONE LAST HIDDEN WORD',
'FROM THE CITY TO THE SEASIDE EVERY STOP ON THIS LINE HAS A NEW PUZZLE WAITING',
'LOOK OUT OF THE WINDOW AT THE HILLS AND FIELDS THEN COME BACK TO THE BOOK FOR ONE MORE PUZZLE',
'WHEN THE TEA TROLLEY COMES ROUND ORDER A CUP AND TURN THE PAGE TO THE NEXT CHAPTER OF THE BOOK',
];
// Letters only: the leftover cells spell this.
export const messageLetters = (m) => m.replace(/[^A-Z]/g, '');

567
tools/verifyWordSearch.js Normal file
View File

@ -0,0 +1,567 @@
#!/usr/bin/env node
// verifyWordSearch.js — headless checks for the Rail Edition Word Search: the
// chapter data, the generator (every word exactly once by an independent
// scanner, allowed directions only, no word inside another, the leftover
// letters spell the secret message, seeded determinism, speed), the selection
// machine (drag and click-click), hints, save/resume validation, daily streaks,
// the book layout, art bakes against a strict fake 2D context, and a
// stubbed-Phaser play-through of the scene.
// Usage: node tools/verifyWordSearch.js [--quick]
import { generatePuzzle, DIFFICULTY, DIFFICULTIES, listThemes } from '../src/words/wordSearchEngine.js';
import { THEMES, CHAPTER_ORDER, JOURNEY_MESSAGES, messageLetters } from '../src/words/wordSearchThemes.js';
import {
DIFFS, TICKET as CLASS, HINT_LIMITS, calcScore, snapSelection, lettersAt, matchWord, idleSelection, selectionStep,
wordCells, leftoverCells, messageWords, pickHint, serialiseSave, parseSave,
dailySeed, prevDate, updateDaily, dailyStreakNow, blankDaily, shortDate,
} from '../src/games/wordsearch/WordSearchLogic.js';
import {
W, H, BOOK, LEFT_PAGE, RIGHT_PAGE, GRID_BOX, MSG_BOX, LIST_BOX, FOOT_Y, WINDOW, CUP, TICKET, FACT, BTN, SMALL_BTN,
CARD, SUMMARY, DOODLE, RIGHT_CX,
} from '../src/games/wordsearch/WordSearchArt.js';
const QUICK = process.argv.includes('--quick');
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 rev = (w) => [...w].reverse().join('');
const DIR8 = [[0, 1], [1, 0], [1, 1], [-1, 1], [0, -1], [-1, 0], [1, -1], [-1, -1]];
// Independent scanner: distinct cell-runs (either direction) spelling `word`.
function occurrences(rows, word) {
const n = rows.length, L = word.length, found = new Set();
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) for (const [dr, dc] of DIR8) {
let s = '';
for (let i = 0; i < L; i++) {
const rr = r + dr * i, cc = c + dc * i;
if (rr < 0 || cc < 0 || rr >= n || cc >= n) { s = null; break; }
s += rows[rr][cc];
}
if (s === word) {
const a = `${r},${c}`, b = `${r + dr * (L - 1)},${c + dc * (L - 1)}`;
found.add([a, b].sort().join('|'));
}
}
return found.size;
}
// ── Chapter data ──────────────────────────────────────────────────────────────
section('Chapter data');
{
ok('15 chapters in order', CHAPTER_ORDER.length === 15 && CHAPTER_ORDER.every(id => THEMES[id]));
ok('listThemes matches the chapter order', listThemes().map(t => t.id).join() === CHAPTER_ORDER.join());
const allMsgs = new Set();
for (const id of CHAPTER_ORDER) {
const t = THEMES[id];
const words = Object.keys(t.words);
ok(`${id}: label + ink`, typeof t.label === 'string' && /^#[0-9a-f]{6}$/i.test(t.ink));
ok(`${id}: at least 40 words`, words.length >= 40, String(words.length));
ok(`${id}: words are A–Z, 3–12 letters`, words.every(w => /^[A-Z]{3,12}$/.test(w)), words.filter(w => !/^[A-Z]{3,12}$/.test(w)).join());
ok(`${id}: every word has a fact`, words.every(w => typeof t.words[w] === 'string' && t.words[w].length > 15 && t.words[w].length < 120),
words.filter(w => !(t.words[w]?.length > 15 && t.words[w].length < 120)).join());
const clashes = [];
for (const a of words) for (const b of words) if (a !== b && (b.includes(a) || b.includes(rev(a)))) clashes.push(`${a}<${b}`);
ok(`${id}: no word hides inside another`, clashes.length === 0, clashes.join());
ok(`${id}: 6+ messages`, t.messages.length >= 6);
ok(`${id}: messages are A–Z words`, t.messages.every(m => /^[A-Z]+( [A-Z]+)*$/.test(m)), t.messages.filter(m => !/^[A-Z]+( [A-Z]+)*$/.test(m)).join(' | '));
const lens = t.messages.map(m => messageLetters(m).length);
ok(`${id}: messages span short to long`, Math.min(...lens) <= 20 && Math.max(...lens) >= 60, lens.join());
for (const m of t.messages) allMsgs.add(m);
}
ok('journey messages are A–Z words', JOURNEY_MESSAGES.every(m => /^[A-Z]+( [A-Z]+)*$/.test(m)));
ok('no duplicate messages', allMsgs.size === CHAPTER_ORDER.reduce((n, id) => n + THEMES[id].messages.length, 0));
}
// ── Generator ────────────────────────────────────────────────────────────────
section('Generator');
const samples = [];
{
const seedsPer = QUICK ? 3 : 10;
const times = {};
for (const d of DIFFICULTIES) {
times[d] = [];
const cfg = DIFFICULTY[d];
const dirKeys = new Set(cfg.dirs.map(x => x.join()));
for (const theme of CHAPTER_ORDER) {
for (let k = 0; k < seedsPer; k++) {
const seed = 1000 + k * 7717 + theme.length * 31;
const t0 = performance.now();
let p;
try { p = generatePuzzle({ difficulty: d, theme, seed }); } catch (err) { ok(`${d}/${theme}/${seed} generates`, false, err.message); continue; }
times[d].push(performance.now() - t0);
samples.push(p);
const tag = `${d}/${theme}/${seed}`;
const errs = [];
if (p.difficulty !== d || p.theme !== theme || p.size !== cfg.size) errs.push('header');
if (p.grid.length !== cfg.size || !p.grid.every(r => r.length === cfg.size && /^[A-Z]+$/.test(r))) errs.push('grid shape');
if (p.words.length < cfg.words[0] || p.words.length > cfg.words[1]) errs.push(`word count ${p.words.length}`);
if ([...p.words].sort().join() !== p.words.join()) errs.push('list not alphabetical');
if (new Set(p.words).size !== p.words.length) errs.push('duplicate words');
if (!p.words.every(w => THEMES[theme].words[w] && p.facts[w] === THEMES[theme].words[w])) errs.push('facts');
for (const pl of p.placements) {
if (!dirKeys.has(pl.dir.join())) errs.push(`dir ${pl.dir} for ${pl.word}`);
if (wordCells(pl).map(([r, c]) => p.grid[r]?.[c]).join('') !== pl.word) errs.push(`placement ${pl.word}`);
if (pl.word.length > Math.min(cfg.size, cfg.maxLen)) errs.push(`too long ${pl.word}`);
}
// the 8-direction scan already reads both ways round
for (const w of p.words) { const n = occurrences(p.grid, w); if (n !== 1) errs.push(`${w}×${n}`); }
for (const a of p.words) for (const b of p.words) if (a !== b && (b.includes(a) || b.includes(rev(a)))) errs.push(`${a} in ${b}`);
const left = leftoverCells(p.size, p.placements);
const msgLen = p.messageLetters.length;
if (left.map(([r, c]) => p.grid[r][c]).join('') !== p.messageLetters) errs.push('leftovers ≠ message');
if (messageLetters(p.message) !== p.messageLetters) errs.push('messageLetters');
if (msgLen < cfg.band[0] || msgLen > cfg.band[1]) errs.push(`message length ${msgLen}`);
if (!THEMES[theme].messages.includes(p.message) && !JOURNEY_MESSAGES.includes(p.message)) errs.push('message source');
ok(tag, errs.length === 0, errs.slice(0, 5).join('; '));
}
}
}
for (const d of DIFFICULTIES) {
const t = [...times[d]].sort((a, b) => a - b);
const p95 = t[Math.floor(t.length * 0.95)] ?? 0;
ok(`${d}: p95 generation under 150 ms`, p95 < 150, `${p95.toFixed(1)} ms`);
console.log(` ${d}: p50 ${t[t.length >> 1]?.toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${t.at(-1)?.toFixed(1)} ms`);
}
const chapterMsgShare = samples.filter(p => THEMES[p.theme].messages.includes(p.message)).length / samples.length;
ok('most messages come from the chapter', chapterMsgShare > 0.75, chapterMsgShare.toFixed(2));
console.log(` chapter messages: ${(chapterMsgShare * 100).toFixed(0)}%`);
}
section('Seeded generation');
{
const a = generatePuzzle({ difficulty: 'hard', theme: 'ocean', seed: 42 });
const b = generatePuzzle({ difficulty: 'hard', theme: 'ocean', seed: 42 });
ok('same seed → same puzzle', JSON.stringify(a) === JSON.stringify(b));
const c = generatePuzzle({ difficulty: 'hard', theme: 'ocean', seed: 43 });
ok('different seed → different puzzle', a.grid.join() !== c.grid.join());
const d1 = generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed('2026-11-26') });
const d2 = generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed('2026-11-26') });
ok('daily: random chapter is seeded too', d1.theme === d2.theme && d1.grid.join() === d2.grid.join());
const chapters = new Set();
for (let k = 0; k < 40; k++) chapters.add(generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed(`2026-12-${k}`) }).theme);
ok('daily chapters vary from day to day', chapters.size >= 8, String(chapters.size));
ok('seed is reported', a.seed === 42);
const u = generatePuzzle({ difficulty: 'expert', theme: 'baking' });
ok('unseeded expert works', u.size === 16 && u.seed === null);
ok('unknown difficulty falls back to medium', generatePuzzle({ difficulty: 'nope', theme: 'space', seed: 1 }).difficulty === 'medium');
ok('unknown theme falls back to a chapter', CHAPTER_ORDER.includes(generatePuzzle({ difficulty: 'easy', theme: 'zzz', seed: 1 }).theme));
ok('Math.random untouched after seeded calls', typeof Math.random() === 'number');
}
// ── Selection ─────────────────────────────────────────────────────────────────
section('Selection');
{
ok('snap: same cell', snapSelection(10, 3, 3, 3, 3).cells.length === 1);
ok('snap: across', snapSelection(10, 2, 1, 2, 6).cells.map(c => c.join()).join(' ') === '2,1 2,2 2,3 2,4 2,5 2,6');
ok('snap: diagonal', snapSelection(10, 0, 0, 3, 3).cells.length === 4 && snapSelection(10, 0, 0, 3, 3).dir.join() === '1,1');
ok('snap: near-diagonal snaps to diagonal', snapSelection(10, 0, 0, 4, 3).dir.join() === '1,1');
ok('snap: backwards', snapSelection(10, 5, 5, 5, 1).dir.join() === '0,-1');
let inBounds = true;
for (let size = 6; size <= 16; size += 5)
for (let br = 0; br < size; br++) for (let bc = 0; bc < size; bc++)
for (const [tr, tc] of [[0, 0], [0, size - 1], [size - 1, 0], [size - 1, size - 1], [br, size - 1], [size - 1, bc], [Math.floor(size / 2), 0]]) {
for (const [r, c] of snapSelection(size, br, bc, tr, tc).cells) if (r < 0 || c < 0 || r >= size || c >= size) inBounds = false;
}
ok('snap never leaves the grid', inBounds);
ok('lettersAt', lettersAt(['ABC', 'DEF', 'GHI'], [[0, 0], [1, 1], [2, 2]]) === 'AEI');
ok('matchWord forward', matchWord('CAT', ['DOG', 'CAT']) === 'CAT');
ok('matchWord backward', matchWord('TAC', ['DOG', 'CAT']) === 'CAT');
ok('matchWord miss', matchWord('COW', ['DOG', 'CAT']) === null);
const run = (events) => {
let s = idleSelection(); const acts = [];
for (const e of events) { const r = selectionStep(s, e); s = r.state; acts.push(r.action + (r.target ? `@${r.target.r},${r.target.c}` : '')); }
return { s, acts };
};
const A = { r: 2, c: 2 }, B = { r: 2, c: 6 };
let res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'move', cell: { r: 2, c: 4 } }, { type: 'move', cell: B }, { type: 'up', cell: B }]);
ok('drag: anchor → preview → commit on release', res.acts.join() === 'anchor@2,2,preview@2,4,preview@2,6,commit@2,6' && !res.s.anchor, res.acts.join());
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'up', cell: A }, { type: 'move', cell: B }, { type: 'down', cell: B, inGrid: true }]);
ok('click-click: hold then commit on the second click', res.acts.join() === 'anchor@2,2,hold@2,2,preview@2,6,commit@2,6' && !res.s.anchor, res.acts.join());
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'up', cell: A }, { type: 'down', cell: A, inGrid: true }]);
ok('clicking the anchor again cancels', res.acts.at(-1) === 'cancel' && !res.s.anchor);
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'move', cell: B }, { type: 'move', cell: A }, { type: 'up', cell: A }]);
ok('drag back to the start keeps the anchor (click-click)', res.acts.at(-1) === 'hold@2,2' && res.s.anchor?.c === 2);
res = run([{ type: 'down', cell: A, inGrid: false }]);
ok('pressing outside the grid does nothing', res.acts[0] === 'none' && !res.s.anchor);
res = run([{ type: 'down', cell: A, inGrid: true }, { type: 'cancel' }]);
ok('cancel clears', res.acts.at(-1) === 'cancel' && !res.s.anchor);
res = run([{ type: 'up', cell: A }, { type: 'move', cell: A }]);
ok('stray up / move with no anchor', res.acts.join() === 'none,none');
}
// ── Geometry + hints + score ──────────────────────────────────────────────────
section('Hints and helpers');
{
const p = samples.find(s => s.difficulty === 'medium');
ok('wordCells spells each word', p.placements.every(pl => wordCells(pl).map(([r, c]) => p.grid[r][c]).join('') === pl.word));
ok('messageWords drops spaces only', messageWords('THE SKY IS').join('|') === 'THE|SKY|IS' && messageWords(p.message).join('') === p.messageLetters);
const found = new Set(p.words.slice(0, 3));
const hinted = new Set([p.words[3]]);
let good = true;
for (let k = 0; k < 50; k++) {
const h = pickHint(p.placements, found, hinted);
const pl = p.placements.find(q => q.word === h.word);
if (!h || found.has(h.word) || hinted.has(h.word) || pl.row !== h.r || pl.col !== h.c) good = false;
}
ok('hint: an unfound, unhinted word, ringed at its first letter', good);
ok('hint: none left → null', pickHint(p.placements, new Set(p.words), new Set()) === null);
ok('hint limits', DIFFS.every(d => Number.isInteger(HINT_LIMITS[d]) && HINT_LIMITS[d] >= 1));
ok('score: harder pays more', calcScore('expert', 30, 0) > calcScore('hard', 20, 0) && calcScore('hard', 20, 0) > calcScore('easy', 10, 0));
ok('score: hints cost, floor 10', calcScore('easy', 10, 1) < calcScore('easy', 10, 0) && calcScore('easy', 1, 99) === 10);
ok('ticket classes', DIFFS.every(d => CLASS[d]?.cls && CLASS[d].size === DIFFICULTY[d].size));
}
// ── Save / resume ────────────────────────────────────────────────────────────
section('Save / resume');
{
const p = samples.find(s => s.difficulty === 'hard');
const base = { difficulty: 'hard', daily: null, puzzle: p, found: p.words.slice(0, 4), hinted: [p.words[6]], hintsLeft: 1, hintsUsed: 1, elapsed: 65432.4, puzzleNo: 4321 };
const json = serialiseSave(base);
const s = parseSave(json);
ok('round trip', s && s.found.join() === base.found.join() && s.hinted[0] === p.words[6] && s.elapsed === 65432 && s.puzzleNo === 4321);
ok('round trip keeps the message', s.puzzle.message === p.message && s.puzzle.grid.join() === p.grid.join());
ok('facts are not stored', !('facts' in JSON.parse(json).puzzle));
const mut = (f) => { const o = JSON.parse(json); f(o); return parseSave(JSON.stringify(o)); };
ok('rejects junk', parseSave('nope') === null && parseSave(null) === null && parseSave('{}') === null);
ok('rejects other versions', mut(o => { o.v = 99; }) === null);
ok('rejects a bad difficulty', mut(o => { o.difficulty = 'insane'; }) === null);
ok('rejects a tampered grid', mut(o => { const r = o.puzzle.grid[0]; o.puzzle.grid[0] = (r[0] === 'A' ? 'B' : 'A') + r.slice(1); }) === null);
ok('rejects a placement off the grid', mut(o => { o.puzzle.placements[0].row = 99; }) === null);
ok('rejects a wrong message', mut(o => { o.puzzle.message = 'NOT THE MESSAGE'; }) === null);
ok('rejects unknown found words', mut(o => { o.found.push('ZZZZ'); }) === null);
ok('rejects a finished puzzle', mut(o => { o.found = [...o.puzzle.words]; }) === null);
ok('repairs bad counters', (() => { const r = mut(o => { o.elapsed = -5; o.hintsLeft = 'x'; o.daily = 'tuesday'; }); return r && r.elapsed === 0 && r.hintsLeft === 0 && r.daily === null; })());
ok('dedupes found words', mut(o => { o.found = [o.found[0], o.found[0]]; })?.found.length === 1);
}
// ── Daily ─────────────────────────────────────────────────────────────────────
section('Daily');
{
ok('dailySeed is stable + per date', dailySeed('2026-11-26') === dailySeed('2026-11-26') && dailySeed('2026-11-26') !== dailySeed('2026-11-27'));
ok('prevDate crosses months', prevDate('2026-12-01') === '2026-11-30' && prevDate('2027-01-01') === '2026-12-31');
let r = updateDaily(blankDaily(), '2026-11-25', '2026-11-25', 90000);
ok('first solve starts a streak', r.streak === 1 && r.rec.solved['2026-11-25'] === 90000);
r = updateDaily(r.rec, '2026-11-26', '2026-11-26', 80000);
ok('next day extends it', r.streak === 2 && r.rec.bestStreak === 2);
r = updateDaily(r.rec, '2026-11-26', '2026-11-26', 70000);
ok('re-solving keeps the streak + faster time', r.streak === 2 && r.newBestTime && r.rec.solved['2026-11-26'] === 70000);
ok('streak alive tomorrow, gone after', dailyStreakNow(r.rec, '2026-11-27') === 2 && dailyStreakNow(r.rec, '2026-11-28') === 0);
r = updateDaily(r.rec, '2026-11-29', '2026-11-29', 50000);
ok('a gap resets to 1', r.streak === 1 && r.rec.bestStreak === 2);
ok('shortDate', shortDate('2026-11-26') === 'Thursday 26 November');
}
// ── Layout ────────────────────────────────────────────────────────────────────
section('Layout');
{
const inside = (a, b) => a.x >= b.x && a.y >= b.y && a.x + a.w <= b.x + b.w && a.y + a.h <= b.y + b.h;
const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
const centred = (o) => ({ x: o.x - o.w / 2, y: o.y - o.h / 2, w: o.w, h: o.h });
ok('the book fits the screen', inside(BOOK, { x: 0, y: 0, w: W, h: H }));
ok('grid box sits on the left page', inside(GRID_BOX, { x: LEFT_PAGE.x + 20, y: LEFT_PAGE.y, w: LEFT_PAGE.w - 40, h: LEFT_PAGE.h }));
ok('message box below the grid, on the page', MSG_BOX.y > GRID_BOX.y + GRID_BOX.h + 10 && inside(MSG_BOX, LEFT_PAGE));
ok('word list on the right page', inside(LIST_BOX, RIGHT_PAGE) && LIST_BOX.y + LIST_BOX.h < FOOT_Y);
ok('doodle on the right page', inside(centred({ x: DOODLE.x, y: DOODLE.y, w: DOODLE.size, h: DOODLE.size }), RIGHT_PAGE));
for (const d of DIFFICULTIES) {
const size = DIFFICULTY[d].size, cell = Math.min(64, Math.floor(GRID_BOX.w / size));
ok(`${d}: grid fits, cells ≥ 38 px`, cell * size <= GRID_BOX.w && cell * size <= GRID_BOX.h && cell >= 38, `cell ${cell}`);
const maxWords = DIFFICULTY[d].words[1];
const cols = maxWords > 24 ? 3 : 2, rows = Math.ceil(maxWords / cols);
const lineH = Math.min(58, Math.floor(LIST_BOX.h / rows));
ok(`${d}: ${maxWords} words fit the list (${cols} columns)`, rows * lineH <= LIST_BOX.h && lineH >= 40);
}
const { layoutBlanks } = await import('../src/games/wordsearch/WordSearchGame.js');
const allMsgs = [...CHAPTER_ORDER.flatMap(id => THEMES[id].messages), ...JOURNEY_MESSAGES];
let worst = 0, okBlanks = true;
for (const m of allMsgs) {
const L = layoutBlanks(messageWords(m), MSG_BOX.w);
const bottom = MSG_BOX.y + 40 + (L.lines - 1) * L.lineH + L.font;
worst = Math.max(worst, bottom);
const right = Math.max(...L.slots.map(s => s.x + L.pitch));
if (L.slots.length !== messageLetters(m).length || right > MSG_BOX.w || bottom > FOOT_Y - 6 || L.pitch < 16) okBlanks = false;
}
ok('every message lays out under the grid', okBlanks, `lowest ${worst}`);
const props = { window: WINDOW, cup: centred({ x: CUP.x, y: CUP.y, w: 140, h: 140 }), ticket: centred(TICKET), fact: centred(FACT) };
BTN.xs.forEach((x, i) => BTN.ys.forEach((y, j) => { props[`btn${i}${j}`] = centred({ x, y, w: BTN.w, h: BTN.h }); }));
SMALL_BTN.xs.forEach((x, i) => { props[`small${i}`] = centred({ x, y: SMALL_BTN.y, w: SMALL_BTN.w, h: SMALL_BTN.h }); });
const keys = Object.keys(props);
for (const k of keys) {
ok(`${k} clears the book`, props[k].x >= BOOK.x + BOOK.w + 8, `${props[k].x}`);
ok(`${k} on screen`, inside(props[k], { x: 0, y: 0, w: W, h: H }));
}
const clashes = [];
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) {
if (keys[i] === 'cup' && keys[j] === 'ticket') continue;
if (overlap(props[keys[i]], props[keys[j]])) clashes.push(`${keys[i]}/${keys[j]}`);
}
ok('right-column props do not overlap', clashes.length === 0, clashes.join());
ok('cup clear of the ticket', CUP.x - 60 > TICKET.x + TICKET.w / 2);
ok('contents cards fit the right page', CARD.w < RIGHT_PAGE.w - 40 && RIGHT_CX - CARD.w / 2 > RIGHT_PAGE.x);
ok('summary fits the screen', SUMMARY.w < W && SUMMARY.h + 140 < 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': case 'clearRect': return (...a) => check(fin(...a), 'rect');
case 'fillText': return (s, x, y) => check(typeof s === 'string' && fin(x, y), 'text');
case 'translate': case 'scale': return (...a) => check(fin(...a), k);
default: return () => {};
}
},
set(t, k, v) {
if ((k === 'fillStyle' || k === 'strokeStyle' || k === 'shadowColor') && typeof v === 'string') check(colourOk(v), `${k} ${v}`);
if (k === 'lineWidth' || k === 'globalAlpha' || k === 'shadowBlur') check(Number.isFinite(v) && v >= 0, `${k} ${v}`);
if (k === 'font') check(/^(bold |italic |bold italic )?\d+px /.test(v), `font ${v}`);
if (k === 'globalCompositeOperation') check(['source-over', 'destination-out', 'multiply', 'lighter'].includes(v), `composite ${v}`);
t[k] = v; return true;
},
});
const prevDoc = globalThis.document;
const sizes = [];
globalThis.document = { createElement: () => { const ctx = makeCtx(); const c = { width: 0, height: 0, getContext: () => ctx }; sizes.push(c); return c; } };
const added = new Map();
const scene = { textures: { exists: (k) => added.has(k), addCanvas: (k, c) => { added.set(k, c); return {}; }, remove: (k) => added.delete(k) } };
try {
const art = await import('../src/games/wordsearch/WordSearchArt.js');
art.prepareWordSearchArt(scene);
for (const k of ['ws-carriage', 'ws-sky', 'ws-clouds', 'ws-far', 'ws-mid', 'ws-near', 'ws-poles', 'ws-glass', 'ws-spread',
'ws-leaf', 'ws-cover', 'ws-ticket', 'ws-card', 'ws-postcard', 'ws-summary', 'ws-cup', 'ws-steam', 'ws-pencil'])
ok(`baked ${k}`, added.has(k));
ok('a doodle for every chapter', CHAPTER_ORDER.every(id => added.has(`ws-doodle-${id}`)));
ok('scenery strips are twice the window wide', ['ws-clouds', 'ws-far', 'ws-mid', 'ws-near', 'ws-poles'].every(k => added.get(k).width === WINDOW.w * 2 && added.get(k).height === WINDOW.h));
ok('carriage is full screen', added.get('ws-carriage').width === W && added.get('ws-carriage').height === H);
ok('leaf matches a page', added.get('ws-leaf').width === LEFT_PAGE.w && added.get('ws-leaf').height === BOOK.h && LEFT_PAGE.w === RIGHT_PAGE.w);
const size = added.size;
art.prepareWordSearchArt(scene);
ok('baking twice reuses the textures', added.size === size);
ok('inkNum', art.inkNum('#2c4a8a') === 0x2c4a8a);
} 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 play-through (stubbed Phaser) ──────────────────────────────────────
const mkStub = (dims = 0) => {
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 === 'width' || k === 'height') && dims) return dims;
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) };
const Art = await import('../src/games/wordsearch/WordSearchArt.js');
if (!Art.BookButton.prototype.destroy) Art.BookButton.prototype.destroy = function () {};
const { default: WordSearchGame } = await import('../src/games/wordsearch/WordSearchGame.js');
function makeScene(dims = 0) {
const stub = mkStub(dims);
const delayed = [];
const sc = Object.create(WordSearchGame.prototype);
Object.assign(sc, {
add: stub, tweens: stub, sound: stub, cameras: stub, textures: stub, input: stub, events: stub, game: stub, cache: stub,
sys: { isActive: () => true },
time: { delayedCall: (ms, f) => { delayed.push(f); return stub; } },
scene: { restart: () => {}, start: () => {} },
});
sc.flush = () => { let n = 0; while (delayed.length && n++ < 2000) delayed.shift()(); };
sc.init({ game: { slug: 'wordsearch' } });
sc.previewGfx = stub; sc.pencil = stub; sc.bookImg = stub;
return sc;
}
const boot = (sc, p, { difficulty = p.difficulty, daily = null } = {}) => {
sc.difficulty = difficulty; sc.daily = daily; sc.puzzle = p;
sc.hintsLeft = HINT_LIMITS[difficulty]; sc.puzzleNo = 2468;
sc.buildPlay();
};
const pointAt = (sc, r, c) => { const { x, y } = sc.cellCenter(r, c); return { worldX: x, worldY: y, rightButtonDown: () => false }; };
section('Scene play-through');
{
const sc = makeScene();
let ceremonies = 0, summaries = 0;
sc.winCeremony = (done) => { ceremonies++; done(); };
sc.showSummary = () => { summaries++; };
sc.showFact = () => {};
const p = generatePuzzle({ difficulty: 'hard', theme: 'railway', seed: 99 });
try {
boot(sc, p);
ok('play page: grid geometry', sc.size === 14 && sc.cell === Math.floor(640 / 14) && sc.mode === 'play');
ok('letters laid out', sc.letterText.length === 14 && sc.letterText.every(r => r.length === 14));
ok('a blank per message letter', sc.blankSlots.length === p.messageLetters.length);
ok('word list entries', Object.keys(sc.wordEntries).length === p.words.length);
// a wrong line: nothing found
const pl0 = p.placements[0];
const cells0 = wordCells(pl0);
sc.onPointerDown(pointAt(sc, cells0[0][0], cells0[0][1]), []);
ok('timer starts on the first press', sc.timerOn === true);
sc.onPointerUp(pointAt(sc, cells0[0][0], cells0[0][1]));
ok('a press-release on one letter waits for a second click', !!sc.sel.anchor);
sc.onPointerDown(pointAt(sc, cells0[0][0], cells0[0][1]), []);
ok('clicking it again cancels', !sc.sel.anchor && sc.found.size === 0);
// find everything: alternate drag (forwards) and click-click (backwards)
p.placements.forEach((pl, i) => {
if (sc.found.size === p.words.length - 1 && i === p.placements.length - 1) {
// save mid-way check before the last word
const saved = parseSave(globalThis.localStorage.getItem('wordsearch-save'));
ok('progress autosaved', saved && saved.found.length === p.words.length - 1 && saved.puzzleNo === 2468);
}
const cells = wordCells(pl);
const a = cells[0], b = cells.at(-1);
if (i % 2 === 0) {
sc.onPointerDown(pointAt(sc, a[0], a[1]), []);
sc.onPointerMove(pointAt(sc, b[0], b[1]));
sc.onPointerUp(pointAt(sc, b[0], b[1]));
} else {
sc.onPointerDown(pointAt(sc, b[0], b[1]), []);
sc.onPointerUp(pointAt(sc, b[0], b[1]));
sc.onPointerMove(pointAt(sc, a[0], a[1]));
sc.onPointerDown(pointAt(sc, a[0], a[1]), []);
}
});
ok('every word found by drag and click-click', sc.found.size === p.words.length, `${sc.found.size}/${p.words.length}`);
ok('the win fires once with its ceremony', sc.gameEnded && ceremonies === 1 && summaries === 1);
ok('win clears the save', globalThis.localStorage.getItem('wordsearch-save') === null);
const stats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch') || '{}');
ok('win recorded under hard', stats.hard?.won === 1);
ok('chapter count bumped', stats.chapters?.counts?.railway === 1);
sc.handleWin();
ok('handleWin is idempotent', JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch')).hard.won === 1);
sc.onPointerDown(pointAt(sc, 0, 0), []);
ok('no selection after the win', !sc.sel.anchor);
} catch (err) {
ok('play-through threw', false, err.stack.split('\n').slice(0, 4).join(' | '));
}
// hints, pause, saving and resuming
try {
const q = generatePuzzle({ difficulty: 'easy', theme: 'garden', seed: 5 });
const s2 = makeScene();
s2.showFact = () => {};
s2.toast = () => {};
boot(s2, q);
s2.useHint();
ok('hint: used + ringed', s2.hintsUsed === 1 && s2.hintsLeft === HINT_LIMITS.easy - 1 && s2.hinted.size === 1);
const hintedWord = [...s2.hinted.keys()][0];
const pl = q.placements.find(x => x.word === hintedWord);
s2.acceptWord(pl.word, wordCells(pl));
ok('finding a hinted word clears its ring', s2.hinted.get(hintedWord) === null);
for (let k = 0; k < 10; k++) s2.useHint();
ok('hints stop at the limit', s2.hintsLeft === 0 && s2.hintsUsed === HINT_LIMITS.easy);
s2.setPaused(true);
ok('pause blocks selection', s2.paused && !s2.canSelect());
s2.onPointerDown(pointAt(s2, 0, 0), []);
ok('no anchor while paused', !s2.sel.anchor);
s2.setPaused(false);
s2.elapsed = 12345;
s2.saveGame();
const saved = parseSave(globalThis.localStorage.getItem('wordsearch-save'));
ok('save holds found + hints', saved && saved.found.includes(hintedWord) && saved.hintsUsed === HINT_LIMITS.easy && saved.hintsLeft === 0);
const s3 = makeScene();
s3.toast = () => {};
s3.beginFromSave(saved);
ok('resume restores found words', s3.found.size === saved.found.length && s3.found.has(hintedWord));
ok('resume restores hint rings for unfound words', [...s3.hinted.keys()].every(w => !s3.found.has(w)) && s3.hinted.size === saved.hinted.length);
ok('resume restores the clock + facts', s3.elapsed === 12345 && s3.timerOn && s3.puzzle.facts[hintedWord] === THEMES.garden.words[hintedWord]);
// abandoning via New puzzle
let restarted = null;
s3.scene.restart = (d) => { restarted = d; };
s3.confirm = (t, b, y, yes) => yes();
s3.newPuzzle();
ok('abandon → contents, save gone, counted as played', restarted?.next?.contents && globalThis.localStorage.getItem('wordsearch-save') === null
&& JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch')).easy.played === 1);
} catch (err) {
ok('hint/save run threw', false, err.stack.split('\n').slice(0, 4).join(' | '));
}
// daily
try {
const today = (await import('../src/games/wordsearch/WordSearchLogic.js')).todayString();
const dp = generatePuzzle({ difficulty: 'medium', theme: 'random', seed: dailySeed(today) });
const s4 = makeScene();
s4.winCeremony = (done) => done();
s4.showSummary = () => {};
s4.showFact = () => {};
boot(s4, dp, { difficulty: 'medium', daily: today });
for (const pl of dp.placements) s4.acceptWord(pl.word, wordCells(pl));
const rec = JSON.parse(globalThis.localStorage.getItem('wordsearch-daily') || 'null');
ok('daily solve recorded with a streak', rec?.solved?.[today] != null && rec.streak === 1);
const dstats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-wordsearch') || '{}');
ok('daily stats under their own mode', dstats.daily?.won === 1);
} catch (err) {
ok('daily run threw', false, err.stack.split('\n').slice(0, 4).join(' | '));
}
}
// ── Render paths (stubbed Phaser with real-ish sizes) ────────────────────────
section('Render paths');
{
const sc = makeScene(100);
const step = (name, f) => { try { f(); ok(name, true); } catch (err) { ok(name, false, err.stack.split('\n').slice(0, 3).join(' | ')); } };
globalThis.localStorage.removeItem('wordsearch-save');
step('carriage + ticket', () => { sc.buildCarriage(); sc.refreshTicket(); });
step('cover', () => { sc.showCover(); });
step('contents', () => { sc.showContents(); sc.selectedTheme = 'music'; sc.drawChapterHl(); });
const p = generatePuzzle({ difficulty: 'expert', theme: 'castles', seed: 3 });
step('expert play page', () => boot(sc, p));
step('preview + deny', () => {
const pl = p.placements[0]; const cells = wordCells(pl);
sc.dispatchSel({ type: 'down', cell: { r: cells[0][0], c: cells[0][1] }, inGrid: true });
sc.dispatchSel({ type: 'move', cell: { r: cells[0][0], c: cells[0][1] + 1 } });
sc.commitSelection([cells[0], [cells[0][0], cells[0][1]]]);
});
step('find + fact postcard', () => { const pl = p.placements[1]; sc.acceptWord(pl.word, wordCells(pl)); sc.showFact(pl.word, { hover: true }); sc.hideFact(); });
step('hint ring', () => sc.useHint());
step('pause + resume', () => { sc.setPaused(true); sc.setPaused(false); });
step('tunnel + rail bump', () => { sc.enterTunnel(); sc.flush(); sc.railBump(); });
step('update tick', () => { sc.strips = { far: { tilePositionX: 0 } }; sc.update(0, 16); });
step('guide modal', () => { sc.openGuide(); sc.modal.close(); });
step('confirm modal', () => { sc.confirm('t', 'b', 'y', () => {}); sc.modal.close(); });
step('toast', () => sc.toast('hello'));
step('contents with a resume card', () => { sc.saveGame(); sc.mode = 'contents'; sc.showContents(); sc.mode = 'play'; });
step('win ceremony → summary', () => {
sc.mode = 'play'; sc.gameEnded = false;
for (const pl of p.placements) sc.acceptWord(pl.word, wordCells(pl));
sc.flush();
if (!sc.gameEnded) throw new Error('did not win');
});
step('summary for a daily', () => { sc.daily = '2026-11-26'; sc.showSummary({ time: 1000, score: 10, stats: { won: 2, bestTime: 900, streak: 1 }, newBest: {}, daily: { streak: 3, newBestTime: true } }); });
globalThis.localStorage.removeItem('wordsearch-save');
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);