From 9c35504760858279ec20b44950753e84ee759b88 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Thu, 26 Nov 2026 08:45:58 -0700 Subject: [PATCH] Rework Tectonic into a Field Geologist's Notebook experience - Replace the flat graph-paper UI with a baked-canvas notebook: desk scene, watercolour cage plates with inked outlines, specimen tags, and a survey certificate win screen (TectonicArt.js). - Add keyboard play (arrows/WASD cursor, 1-5, Backspace, Ctrl+Z/Y), undo/redo, pause overlay, toasts, a first-run field guide, and per-cage completion feedback with a seismograph strip. - Support resuming an in-progress survey from localStorage plus a Daily Survey (seeded generation, streaks, best-time tracking). - Extract shared rules into TectonicLogic.js (cage tracing/inset/colouring, history, save validation, daily helpers) and make the puzzle generator accept a seed for deterministic boards. - Add tools/verifyTectonic.js covering the generator, logic, layout, art bake, and a stubbed-Phaser scene smoke run. --- src/games/tectonic/TectonicArt.js | 741 ++++++++++++ src/games/tectonic/TectonicGame.js | 1719 +++++++++++++++++++-------- src/games/tectonic/TectonicLogic.js | 311 ++++- src/words/tectonicEngine.js | 63 +- src/words/wordRouter.js | 6 +- tools/verifyTectonic.js | 539 +++++++++ 6 files changed, 2837 insertions(+), 542 deletions(-) create mode 100644 src/games/tectonic/TectonicArt.js create mode 100644 tools/verifyTectonic.js diff --git a/src/games/tectonic/TectonicArt.js b/src/games/tectonic/TectonicArt.js new file mode 100644 index 0000000..d3fab6d --- /dev/null +++ b/src/games/tectonic/TectonicArt.js @@ -0,0 +1,741 @@ +// Tectonic art — the Field Geologist's Notebook, baked to canvases (no image files). +// +// tectonic-desk 1920×1080: weathered oak field desk, a topo map sheet +// peeking out, the open notebook (graph-paper pages, gutter +// shadow, stitched spine, ribbon, coffee ring), the lamp +// pool and the props (rock specimens + geode, hand lens, +// brass compass, pencil stub, quartz point) +// tectonic-cover leather cover that swings open off the right page +// tectonic-tag-1..5 manila specimen tags for the number selector +// tectonic-eraser the eraser +// tectonic-card ruled index card (start screen) +// tectonic-cert the Survey Certificate +// per puzzle bakeCage() → one watercolour plate + inked outline per cage +// +// Also exports the layout constants and PaperButton (a pencil-sketched button). + +import * as Phaser from 'phaser'; +import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { traceCage, insetLoop } from './TectonicLogic.js'; + +// ── Layout ──────────────────────────────────────────────────────────────────── +export const W = 1920, H = 1080; +export const BOOK = { x: 186, y: 50, w: 1548, h: 988 }; +export const LEFT = { x: 204, y: 64, w: 754, h: 958 }; +export const RIGHT = { x: 962, y: 64, w: 754, h: 958 }; +export const SPINE_X = 960; +export const LCX = LEFT.x + LEFT.w / 2; // 581 +export const RCX = RIGHT.x + RIGHT.w / 2; // 1339 +export const CELL = 84; +export const GRID_W = 8 * CELL; // 672 +export const GRID_X = Math.round(LCX - GRID_W / 2); // 245 +export const GRID_Y = 244; +export const PITCH = 28; // graph paper = CELL / 3, aligned to the grid +export const CAGE_PAD = 10; // texture margin around a cage plate + +// Earth tones for the cage plates (strata). +export const TONES = [ + { name: 'sandstone', fill: '#d9a35b', ink: 0xb07a35 }, + { name: 'slate', fill: '#6f8fa8', ink: 0x4f6f88 }, + { name: 'moss', fill: '#8ea65a', ink: 0x66803a }, + { name: 'clay', fill: '#c97a5d', ink: 0xa0553c }, + { name: 'ochre', fill: '#d8c056', ink: 0xa89130 }, + { name: 'heather', fill: '#a58bb5', ink: 0x7c6290 }, +]; +export const TAG_TONES = ['#c97a5d', '#d9a35b', '#8ea65a', '#6f8fa8', '#a58bb5']; + +export const INK = '#26313d'; +export const INK_N = 0x26313d; +export const PENCIL = '#6d7580'; +export const PENCIL_N = 0x6d7580; +export const BLUE_INK = '#1f5f9e'; +export const RED_PENCIL = 0xb8402f; + +let seed = 7; +const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }; +const jit = (a) => (rnd() - 0.5) * 2 * a; + +// ── Desk ───────────────────────────────────────────────────────────────────── +function desk(ctx) { + const g = ctx.createLinearGradient(0, 0, W, H); + g.addColorStop(0, '#6d4b2d'); g.addColorStop(0.5, '#5a3c23'); g.addColorStop(1, '#3d2714'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + // planks + const PLANK = 216; + for (let y = 0; y < H; y += PLANK) { + const tone = rnd() * 0.12; + ctx.fillStyle = `rgba(${rnd() < 0.5 ? '0,0,0' : '255,210,160'},${tone * 0.6})`; + ctx.fillRect(0, y, W, PLANK); + for (let i = 0; i < 70; i++) { + const gy = y + rnd() * PLANK, x0 = rnd() * W, len = 300 + rnd() * 1100; + ctx.strokeStyle = rnd() < 0.55 ? `rgba(30,15,5,${0.10 + rnd() * 0.14})` : `rgba(230,180,120,${0.04 + rnd() * 0.06})`; + ctx.lineWidth = 0.8 + rnd() * 2.2; + ctx.beginPath(); + ctx.moveTo(x0, gy); + ctx.bezierCurveTo(x0 + len * 0.3, gy + jit(8), x0 + len * 0.7, gy + jit(8), x0 + len, gy + jit(5)); + ctx.stroke(); + } + // seam + ctx.fillStyle = 'rgba(15,8,2,0.55)'; + ctx.fillRect(0, y + PLANK - 3, W, 3); + ctx.fillStyle = 'rgba(255,220,170,0.07)'; + ctx.fillRect(0, y + PLANK, W, 2); + // nail heads at plank ends + for (const nx of [36, W - 36]) { + ctx.fillStyle = 'rgba(20,12,6,0.7)'; + ctx.beginPath(); ctx.arc(nx, y + PLANK / 2, 5, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(200,170,130,0.25)'; + ctx.beginPath(); ctx.arc(nx - 1.5, y + PLANK / 2 - 1.5, 2, 0, Math.PI * 2); ctx.fill(); + } + } + // dents and scratches from field use + for (let i = 0; i < 60; i++) { + const x = rnd() * W, y = rnd() * H, a = rnd() * Math.PI, l = 8 + rnd() * 40; + ctx.strokeStyle = `rgba(${rnd() < 0.5 ? '20,10,4' : '220,180,130'},${0.08 + rnd() * 0.1})`; + ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l); ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 200, 16); + ctx.fillRect(0, 0, W, H); +} + +// A topographic survey sheet, mostly under the notebook. +function topoMap(ctx) { + ctx.save(); + ctx.translate(120, 760); + ctx.rotate(-0.16); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 18; ctx.shadowOffsetY = 6; + ctx.fillStyle = '#e8dcbc'; + ctx.fillRect(-260, -180, 620, 520); + ctx.shadowColor = 'transparent'; + ctx.save(); + ctx.beginPath(); ctx.rect(-260, -180, 620, 520); ctx.clip(); + // grid + ctx.strokeStyle = 'rgba(80,110,140,0.25)'; ctx.lineWidth = 1; + for (let x = -260; x < 360; x += 62) { ctx.beginPath(); ctx.moveTo(x, -180); ctx.lineTo(x, 340); ctx.stroke(); } + for (let y = -180; y < 340; y += 62) { ctx.beginPath(); ctx.moveTo(-260, y); ctx.lineTo(360, y); ctx.stroke(); } + // contours around two hills + for (const [hx, hy, rings] of [[-40, 60, 11], [230, -60, 7]]) { + for (let k = 1; k <= rings; k++) { + ctx.strokeStyle = k % 5 === 0 ? 'rgba(130,80,40,0.65)' : 'rgba(150,100,50,0.38)'; + ctx.lineWidth = k % 5 === 0 ? 1.8 : 1; + ctx.beginPath(); + for (let t = 0; t <= 64; t++) { + const a = (t / 64) * Math.PI * 2; + const rad = k * 17 * (1 + 0.16 * Math.sin(a * 3 + k * 0.7) + 0.08 * Math.cos(a * 5 + hx)); + const x = hx + Math.cos(a) * rad * 1.3, y = hy + Math.sin(a) * rad; + t ? ctx.lineTo(x, y) : ctx.moveTo(x, y); + } + ctx.closePath(); ctx.stroke(); + } + } + // a river + ctx.strokeStyle = 'rgba(60,110,170,0.55)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.moveTo(-260, 250); + ctx.bezierCurveTo(-120, 200, 40, 300, 140, 220); ctx.bezierCurveTo(220, 160, 300, 240, 360, 200); + ctx.stroke(); + // fold creases + ctx.strokeStyle = 'rgba(0,0,0,0.12)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(50, -180); ctx.lineTo(50, 340); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,255,255,0.25)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(52, -180); ctx.lineTo(52, 340); ctx.stroke(); + ctx.fillStyle = noisePattern(ctx, 120, 22); + ctx.fillRect(-260, -180, 620, 520); + ctx.restore(); + ctx.restore(); +} + +function notebook(ctx) { + const { x, y, w, h } = BOOK; + // drop shadow + cover board + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 40; ctx.shadowOffsetY = 14; + ctx.fillStyle = '#34402f'; + rr(ctx, x, y, w, h, 20); ctx.fill(); + ctx.restore(); + // leather grain + worn edge + ctx.save(); + rr(ctx, x, y, w, h, 20); ctx.clip(); + const lg = ctx.createLinearGradient(x, y, x + w, y + h); + lg.addColorStop(0, '#46553c'); lg.addColorStop(1, '#27301f'); + ctx.fillStyle = lg; ctx.fillRect(x, y, w, h); + ctx.fillStyle = noisePattern(ctx, 90, 40); ctx.fillRect(x, y, w, h); + ctx.strokeStyle = 'rgba(200,190,140,0.18)'; ctx.lineWidth = 2; + rr(ctx, x + 3, y + 3, w - 6, h - 6, 18); ctx.stroke(); + ctx.restore(); + + // page block edges (stacked sheets on the outer and bottom edges) + for (let i = 4; i >= 1; i--) { + ctx.fillStyle = i % 2 ? '#e7e0cf' : '#d9d1bd'; + rr(ctx, LEFT.x - i * 1.6, LEFT.y + i * 1.2, LEFT.w + i * 1.6, LEFT.h + i * 1.4, 6); ctx.fill(); + rr(ctx, RIGHT.x, RIGHT.y + i * 1.2, RIGHT.w + i * 1.6, RIGHT.h + i * 1.4, 6); ctx.fill(); + } + + for (const [P, side] of [[LEFT, 'L'], [RIGHT, 'R']]) { + ctx.save(); + rr(ctx, P.x, P.y, P.w, P.h, 6); ctx.clip(); + ctx.fillStyle = '#fbf8ee'; ctx.fillRect(P.x, P.y, P.w, P.h); + // graph paper (aligned to the puzzle grid on the left page) + const ox = GRID_X % PITCH, oy = GRID_Y % PITCH; + for (let gx = ox; gx < W; gx += PITCH) { + if (gx < P.x || gx > P.x + P.w) continue; + const major = Math.round((gx - GRID_X) / PITCH) % 3 === 0; + ctx.strokeStyle = major ? 'rgba(110,160,205,0.42)' : 'rgba(130,175,215,0.26)'; + ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(gx + 0.5, P.y); ctx.lineTo(gx + 0.5, P.y + P.h); ctx.stroke(); + } + for (let gy = oy; gy < H; gy += PITCH) { + if (gy < P.y || gy > P.y + P.h) continue; + const major = Math.round((gy - GRID_Y) / PITCH) % 3 === 0; + ctx.strokeStyle = major ? 'rgba(110,160,205,0.42)' : 'rgba(130,175,215,0.26)'; + ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(P.x, gy + 0.5); ctx.lineTo(P.x + P.w, gy + 0.5); ctx.stroke(); + } + // printed header band + ctx.fillStyle = 'rgba(251,248,238,0.92)'; + ctx.fillRect(P.x, P.y, P.w, 34); + ctx.strokeStyle = 'rgba(190,70,60,0.5)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(P.x, P.y + 34); ctx.lineTo(P.x + P.w, P.y + 34); ctx.stroke(); + // gutter shadow + outer page curl + const gut = side === 'L' + ? ctx.createLinearGradient(P.x + P.w, 0, P.x + P.w - 90, 0) + : ctx.createLinearGradient(P.x, 0, P.x + 90, 0); + gut.addColorStop(0, 'rgba(70,55,30,0.34)'); gut.addColorStop(0.35, 'rgba(70,55,30,0.10)'); gut.addColorStop(1, 'rgba(70,55,30,0)'); + ctx.fillStyle = gut; ctx.fillRect(P.x, P.y, P.w, P.h); + const curl = side === 'L' + ? ctx.createLinearGradient(P.x, 0, P.x + 40, 0) + : ctx.createLinearGradient(P.x + P.w, 0, P.x + P.w - 40, 0); + curl.addColorStop(0, 'rgba(120,100,60,0.16)'); curl.addColorStop(1, 'rgba(120,100,60,0)'); + ctx.fillStyle = curl; ctx.fillRect(P.x, P.y, P.w, P.h); + // paper tooth + light foxing + ctx.fillStyle = noisePattern(ctx, 140, 12); ctx.fillRect(P.x, P.y, P.w, P.h); + for (let i = 0; i < 14; i++) { + const fx = P.x + rnd() * P.w, fy = P.y + rnd() * P.h, fr = 2 + rnd() * 6; + ctx.fillStyle = `rgba(160,120,60,${0.04 + rnd() * 0.05})`; + ctx.beginPath(); ctx.arc(fx, fy, fr, 0, Math.PI * 2); ctx.fill(); + } + ctx.restore(); + } + + // spine: binding thread through the gutter + ctx.fillStyle = 'rgba(40,30,15,0.35)'; + ctx.fillRect(SPINE_X - 2, LEFT.y, 4, LEFT.h); + for (let sy = LEFT.y + 40; sy < LEFT.y + LEFT.h - 30; sy += 64) { + ctx.strokeStyle = 'rgba(235,225,195,0.9)'; ctx.lineWidth = 2.4; + ctx.beginPath(); ctx.moveTo(SPINE_X, sy); ctx.lineTo(SPINE_X, sy + 22); ctx.stroke(); + ctx.fillStyle = 'rgba(40,30,15,0.6)'; + ctx.beginPath(); ctx.arc(SPINE_X, sy - 2, 1.8, 0, Math.PI * 2); ctx.arc(SPINE_X, sy + 24, 1.8, 0, Math.PI * 2); ctx.fill(); + } + + // ribbon bookmark draped over the bottom of the right page + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.35)'; ctx.shadowBlur = 6; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; + ctx.fillStyle = '#9c2f2a'; + ctx.beginPath(); + ctx.moveTo(SPINE_X + 6, RIGHT.y + RIGHT.h - 220); + ctx.bezierCurveTo(SPINE_X + 30, RIGHT.y + RIGHT.h - 120, SPINE_X + 14, RIGHT.y + RIGHT.h - 40, SPINE_X + 40, BOOK.y + BOOK.h + 34); + ctx.lineTo(SPINE_X + 52, BOOK.y + BOOK.h + 22); + ctx.lineTo(SPINE_X + 66, BOOK.y + BOOK.h + 36); + ctx.bezierCurveTo(SPINE_X + 40, RIGHT.y + RIGHT.h - 40, SPINE_X + 54, RIGHT.y + RIGHT.h - 120, SPINE_X + 30, RIGHT.y + RIGHT.h - 220); + ctx.closePath(); ctx.fill(); + ctx.restore(); + + // faint coffee ring on the right page + ctx.save(); + ctx.translate(RIGHT.x + RIGHT.w - 120, RIGHT.y + 140); + for (let k = 0; k < 3; k++) { + ctx.strokeStyle = `rgba(130,80,30,${0.10 - k * 0.025})`; + ctx.lineWidth = 5 - k * 1.4; + ctx.beginPath(); ctx.ellipse(jit(2), jit(2), 62 + k * 2, 58 + k * 2, 0.3, 0.2, Math.PI * 1.85); ctx.stroke(); + } + ctx.restore(); +} + +// ── Props ───────────────────────────────────────────────────────────────────── +function rock(ctx, cx, cy, rad, base, dark, facets = 7) { + const pts = []; + for (let i = 0; i < facets; i++) { + const a = (i / facets) * Math.PI * 2 + jit(0.2); + const r = rad * (0.78 + rnd() * 0.3); + pts.push([cx + Math.cos(a) * r * 1.15, cy + Math.sin(a) * r * 0.85]); + } + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 16; ctx.shadowOffsetX = 6; ctx.shadowOffsetY = 8; + ctx.fillStyle = base; + ctx.beginPath(); pts.forEach(([x, y], i) => i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)); ctx.closePath(); ctx.fill(); + ctx.restore(); + // facets lit from the lamp (upper left) + for (let i = 0; i < pts.length; i++) { + const a = pts[i], b = pts[(i + 1) % pts.length]; + const mid = Math.atan2((a[1] + b[1]) / 2 - cy, (a[0] + b[0]) / 2 - cx); + const lit = Math.cos(mid + 2.3); + ctx.fillStyle = lit > 0 ? `rgba(255,240,210,${0.22 * lit})` : `rgba(0,0,0,${-0.32 * lit})`; + ctx.beginPath(); ctx.moveTo(cx + jit(rad * 0.15), cy + jit(rad * 0.15)); ctx.lineTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.closePath(); ctx.fill(); + } + // strata bands + ctx.save(); + ctx.beginPath(); pts.forEach(([x, y], i) => i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)); ctx.closePath(); ctx.clip(); + for (let k = -3; k <= 3; k++) { + ctx.strokeStyle = dark; ctx.globalAlpha = 0.35; ctx.lineWidth = 2 + rnd() * 3; + ctx.beginPath(); ctx.moveTo(cx - rad * 1.4, cy + k * rad * 0.28 - rad * 0.3); + ctx.quadraticCurveTo(cx, cy + k * rad * 0.28 + jit(rad * 0.2), cx + rad * 1.4, cy + k * rad * 0.28 + rad * 0.3); + ctx.stroke(); + } + ctx.globalAlpha = 1; + ctx.fillStyle = noisePattern(ctx, 60, 50); ctx.fillRect(cx - rad * 2, cy - rad * 2, rad * 4, rad * 4); + ctx.restore(); +} + +function geode(ctx, cx, cy, rad) { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 14; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 7; + ctx.fillStyle = '#7b6f62'; + ctx.beginPath(); ctx.ellipse(cx, cy, rad * 1.1, rad * 0.9, 0.3, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + ctx.fillStyle = '#ddd6cb'; + ctx.beginPath(); ctx.ellipse(cx, cy, rad * 0.9, rad * 0.72, 0.3, 0, Math.PI * 2); ctx.fill(); + const g = ctx.createRadialGradient(cx - rad * 0.2, cy - rad * 0.2, 2, cx, cy, rad * 0.75); + g.addColorStop(0, '#f3e6ff'); g.addColorStop(0.4, '#a77bd0'); g.addColorStop(1, '#4c2a6d'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(cx, cy, rad * 0.76, rad * 0.6, 0.3, 0, Math.PI * 2); ctx.fill(); + // crystal points + for (let i = 0; i < 26; i++) { + const a = rnd() * Math.PI * 2, d = rnd() * rad * 0.6; + const x = cx + Math.cos(a) * d * 1.1, y = cy + Math.sin(a) * d * 0.85, s = 3 + rnd() * 6; + ctx.fillStyle = `rgba(255,245,255,${0.25 + rnd() * 0.5})`; + ctx.beginPath(); ctx.moveTo(x, y - s); ctx.lineTo(x + s * 0.6, y); ctx.lineTo(x, y + s * 0.5); ctx.lineTo(x - s * 0.6, y); ctx.closePath(); ctx.fill(); + } +} + +function handLens(ctx, cx, cy) { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 16; ctx.shadowOffsetX = 7; ctx.shadowOffsetY = 9; + // handle + ctx.save(); ctx.translate(cx, cy); ctx.rotate(0.75); + ctx.fillStyle = '#3b2616'; rr(ctx, 54, -11, 130, 22, 10); ctx.fill(); + ctx.restore(); + // brass rim + ctx.fillStyle = '#b8913f'; + ctx.beginPath(); ctx.arc(cx, cy, 62, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + const rim = ctx.createLinearGradient(cx - 60, cy - 60, cx + 60, cy + 60); + rim.addColorStop(0, '#f0d591'); rim.addColorStop(0.5, '#a57a2c'); rim.addColorStop(1, '#6b4a15'); + ctx.strokeStyle = rim; ctx.lineWidth = 10; + ctx.beginPath(); ctx.arc(cx, cy, 56, 0, Math.PI * 2); ctx.stroke(); + // glass: magnified wood grain + highlight + const gl = ctx.createRadialGradient(cx - 18, cy - 20, 4, cx, cy, 52); + gl.addColorStop(0, 'rgba(255,255,255,0.32)'); gl.addColorStop(0.5, 'rgba(190,220,230,0.10)'); gl.addColorStop(1, 'rgba(20,40,50,0.28)'); + ctx.fillStyle = gl; + ctx.beginPath(); ctx.arc(cx, cy, 51, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.arc(cx, cy, 40, Math.PI * 1.1, Math.PI * 1.45); ctx.stroke(); +} + +function compass(ctx, cx, cy) { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 18; ctx.shadowOffsetX = 7; ctx.shadowOffsetY = 9; + ctx.fillStyle = '#9c7a35'; + ctx.beginPath(); ctx.arc(cx, cy, 92, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + const rim = ctx.createLinearGradient(cx - 90, cy - 90, cx + 90, cy + 90); + rim.addColorStop(0, '#f2d895'); rim.addColorStop(0.5, '#b08a3c'); rim.addColorStop(1, '#5e4214'); + ctx.fillStyle = rim; + ctx.beginPath(); ctx.arc(cx, cy, 90, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#efe6cf'; + ctx.beginPath(); ctx.arc(cx, cy, 72, 0, Math.PI * 2); ctx.fill(); + // degree ticks + for (let i = 0; i < 72; i++) { + const a = (i / 72) * Math.PI * 2, l = i % 9 === 0 ? 12 : 6; + ctx.strokeStyle = 'rgba(40,30,20,0.7)'; ctx.lineWidth = i % 9 === 0 ? 2 : 1; + ctx.beginPath(); ctx.moveTo(cx + Math.cos(a) * 70, cy + Math.sin(a) * 70); + ctx.lineTo(cx + Math.cos(a) * (70 - l), cy + Math.sin(a) * (70 - l)); ctx.stroke(); + } + // rose + ctx.fillStyle = 'rgba(40,30,20,0.18)'; + for (let i = 0; i < 4; i++) { + const a = i * Math.PI / 2 + Math.PI / 4; + ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(a - 0.2) * 30, cy + Math.sin(a - 0.2) * 30); + ctx.lineTo(cx + Math.cos(a) * 44, cy + Math.sin(a) * 44); ctx.closePath(); ctx.fill(); + } + // needle + const na = -0.5; + ctx.fillStyle = '#b8352a'; + ctx.beginPath(); ctx.moveTo(cx + Math.cos(na) * 56, cy + Math.sin(na) * 56); + ctx.lineTo(cx + Math.cos(na + Math.PI / 2) * 7, cy + Math.sin(na + Math.PI / 2) * 7); + ctx.lineTo(cx + Math.cos(na - Math.PI / 2) * 7, cy + Math.sin(na - Math.PI / 2) * 7); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#3a4048'; + ctx.beginPath(); ctx.moveTo(cx - Math.cos(na) * 56, cy - Math.sin(na) * 56); + ctx.lineTo(cx + Math.cos(na + Math.PI / 2) * 7, cy + Math.sin(na + Math.PI / 2) * 7); + ctx.lineTo(cx + Math.cos(na - Math.PI / 2) * 7, cy + Math.sin(na - Math.PI / 2) * 7); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#d8b86a'; + ctx.beginPath(); ctx.arc(cx, cy, 6, 0, Math.PI * 2); ctx.fill(); + // glass glare + ctx.strokeStyle = 'rgba(255,255,255,0.5)'; ctx.lineWidth = 4; + ctx.beginPath(); ctx.arc(cx, cy, 60, Math.PI * 1.05, Math.PI * 1.4); ctx.stroke(); +} + +function pencil(ctx, x, y, angle, len) { + ctx.save(); + ctx.translate(x, y); ctx.rotate(angle); + ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 10; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 6; + ctx.fillStyle = '#d9a52c'; ctx.fillRect(0, -9, len, 18); + ctx.shadowColor = 'transparent'; + ctx.fillStyle = 'rgba(255,240,180,0.45)'; ctx.fillRect(0, -9, len, 5); + ctx.fillStyle = 'rgba(120,80,10,0.35)'; ctx.fillRect(0, 4, len, 5); + // sharpened end + ctx.fillStyle = '#e8c79a'; + ctx.beginPath(); ctx.moveTo(len, -9); ctx.lineTo(len + 34, 0); ctx.lineTo(len, 9); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#2b2b2b'; + ctx.beginPath(); ctx.moveTo(len + 24, -3); ctx.lineTo(len + 34, 0); ctx.lineTo(len + 24, 3); ctx.closePath(); ctx.fill(); + // ferrule + eraser + ctx.fillStyle = '#b9b9b0'; ctx.fillRect(-22, -9.5, 22, 19); + ctx.fillStyle = 'rgba(0,0,0,0.25)'; for (let i = -18; i < 0; i += 5) ctx.fillRect(i, -9.5, 1.5, 19); + ctx.fillStyle = '#d98a8a'; rr(ctx, -40, -9, 20, 18, 4); ctx.fill(); + ctx.restore(); +} + +function quartz(ctx, cx, cy) { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 12; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 6; + ctx.translate(cx, cy); ctx.rotate(-0.5); + ctx.fillStyle = 'rgba(235,240,245,0.92)'; + ctx.beginPath(); ctx.moveTo(-18, 40); ctx.lineTo(-20, -20); ctx.lineTo(0, -52); ctx.lineTo(20, -20); ctx.lineTo(18, 40); ctx.closePath(); ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.fillStyle = 'rgba(160,180,200,0.5)'; + ctx.beginPath(); ctx.moveTo(0, -52); ctx.lineTo(20, -20); ctx.lineTo(18, 40); ctx.lineTo(4, 40); ctx.lineTo(4, -18); ctx.closePath(); ctx.fill(); + ctx.strokeStyle = 'rgba(255,255,255,0.8)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(-14, 34); ctx.lineTo(-15, -18); ctx.lineTo(0, -46); ctx.stroke(); + ctx.restore(); +} + +function lamp(ctx) { + ctx.save(); + ctx.globalCompositeOperation = 'lighter'; + const g = ctx.createRadialGradient(700, 240, 40, 760, 420, 1250); + g.addColorStop(0, 'rgba(255,214,150,0.20)'); g.addColorStop(0.45, 'rgba(255,190,120,0.07)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); + ctx.restore(); + const v = ctx.createRadialGradient(W / 2, H / 2, 420, W / 2, H / 2, 1180); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(8,4,0,0.62)'); + ctx.fillStyle = v; ctx.fillRect(0, 0, W, H); +} + +function bakeDesk(scene) { + seed = 7; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + desk(ctx); + topoMap(ctx); + rock(ctx, 92, 150, 52, '#8a7f73', '#4e463e'); + rock(ctx, 126, 300, 38, '#b0794f', '#6a3f22', 6); + geode(ctx, 86, 450, 48); + notebook(ctx); + handLens(ctx, 92, 930); + compass(ctx, 1838, 150); + pencil(ctx, 1790, 900, -1.38, 330); + quartz(ctx, 1846, 990); + rock(ctx, 1840, 400, 40, '#5f6b70', '#2c3438', 8); + lamp(ctx); + scene.textures.addCanvas('tectonic-desk', c); +} + +// ── Cover ──────────────────────────────────────────────────────────────────── +function bakeCover(scene) { + seed = 21; + const cw = RIGHT.w + 18, ch = BOOK.h; + const c = canvas(cw, ch); + const ctx = c.getContext('2d'); + const lg = ctx.createLinearGradient(0, 0, cw, ch); + lg.addColorStop(0, '#4c5c40'); lg.addColorStop(1, '#2a3322'); + ctx.fillStyle = lg; rr(ctx, 0, 0, cw, ch, 20); ctx.fill(); + ctx.fillStyle = noisePattern(ctx, 90, 46); rr(ctx, 0, 0, cw, ch, 20); ctx.fill(); + // spine hinge shading + const hg = ctx.createLinearGradient(0, 0, 60, 0); + hg.addColorStop(0, 'rgba(0,0,0,0.45)'); hg.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = hg; ctx.fillRect(0, 0, 60, ch); + // blind-tooled frame + ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 3; + rr(ctx, 46, 40, cw - 92, ch - 80, 12); ctx.stroke(); + ctx.strokeStyle = 'rgba(210,200,150,0.22)'; ctx.lineWidth = 1.5; + rr(ctx, 50, 44, cw - 100, ch - 88, 10); ctx.stroke(); + // paper label + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.4)'; ctx.shadowBlur = 8; ctx.shadowOffsetY = 3; + ctx.fillStyle = '#efe5c8'; rr(ctx, cw / 2 - 230, 240, 460, 240, 8); ctx.fill(); + ctx.restore(); + ctx.strokeStyle = 'rgba(120,60,40,0.6)'; ctx.lineWidth = 2; + rr(ctx, cw / 2 - 218, 252, 436, 216, 6); ctx.stroke(); + // elastic band + ctx.fillStyle = 'rgba(20,20,20,0.85)'; ctx.fillRect(cw - 120, 0, 22, ch); + ctx.fillStyle = 'rgba(255,255,255,0.08)'; ctx.fillRect(cw - 116, 0, 4, ch); + scene.textures.addCanvas('tectonic-cover', c); +} + +// ── Tags, eraser, card, certificate ────────────────────────────────────────── +export const TAG_W = 108, TAG_H = 132; + +function bakeTag(scene, key, tone) { + const pad = 8; + const c = canvas(TAG_W + pad * 2, TAG_H + pad * 2 + 24); + const ctx = c.getContext('2d'); + const x = pad, y = pad + 24, w = TAG_W, h = TAG_H; + // string loop + ctx.strokeStyle = '#8b7355'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(x + w / 2, y + 18); ctx.bezierCurveTo(x + w / 2 - 20, y - 20, x + w / 2 + 26, y - 26, x + w / 2 + 6, y + 18); ctx.stroke(); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.3)'; ctx.shadowBlur = 6; ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 3; + ctx.fillStyle = '#ead9b0'; + ctx.beginPath(); + ctx.moveTo(x + 22, y); ctx.lineTo(x + w - 22, y); ctx.lineTo(x + w, y + 22); + ctx.lineTo(x + w, y + h - 6); ctx.quadraticCurveTo(x + w, y + h, x + w - 6, y + h); + ctx.lineTo(x + 6, y + h); ctx.quadraticCurveTo(x, y + h, x, y + h - 6); + ctx.lineTo(x, y + 22); ctx.closePath(); ctx.fill(); + ctx.restore(); + ctx.save(); + ctx.clip(); + ctx.fillStyle = tone; ctx.globalAlpha = 0.85; ctx.fillRect(x, y + h - 26, w, 26); + ctx.globalAlpha = 1; + ctx.strokeStyle = 'rgba(120,90,50,0.35)'; ctx.lineWidth = 1; + for (let ly = y + 40; ly < y + h - 30; ly += 16) { ctx.beginPath(); ctx.moveTo(x + 10, ly); ctx.lineTo(x + w - 10, ly); ctx.stroke(); } + ctx.fillStyle = noisePattern(ctx, 60, 22); ctx.fillRect(x, y, w, h); + ctx.restore(); + // reinforced hole + ctx.fillStyle = '#c9b48a'; ctx.beginPath(); ctx.arc(x + w / 2, y + 16, 9, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#5a3c23'; ctx.beginPath(); ctx.arc(x + w / 2, y + 16, 4.5, 0, Math.PI * 2); ctx.fill(); + scene.textures.addCanvas(key, c); +} + +function bakeEraser(scene) { + const c = canvas(150, 90); + const ctx = c.getContext('2d'); + ctx.translate(75, 45); ctx.rotate(-0.12); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.35)'; ctx.shadowBlur = 8; ctx.shadowOffsetX = 3; ctx.shadowOffsetY = 4; + ctx.fillStyle = '#e9a3a1'; rr(ctx, -60, -24, 120, 48, 9); ctx.fill(); + ctx.restore(); + ctx.fillStyle = '#3d6fa8'; ctx.fillRect(-10, -25, 66, 50); + ctx.fillStyle = 'rgba(255,255,255,0.18)'; ctx.fillRect(-10, -25, 66, 8); + ctx.fillStyle = 'rgba(255,255,255,0.3)'; rr(ctx, -56, -20, 40, 8, 4); ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.06)'; rr(ctx, -60, 10, 50, 14, 6); ctx.fill(); + scene.textures.addCanvas('tectonic-eraser', c); +} + +export const CARD_W = 640, CARD_H = 132; +function bakeCard(scene) { + const c = canvas(CARD_W + 24, CARD_H + 24); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.3)'; ctx.shadowBlur = 10; ctx.shadowOffsetY = 4; + ctx.fillStyle = '#fffdf6'; ctx.fillRect(12, 10, CARD_W, CARD_H); + ctx.restore(); + ctx.strokeStyle = 'rgba(200,70,60,0.55)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(12, 42); ctx.lineTo(12 + CARD_W, 42); ctx.stroke(); + ctx.strokeStyle = 'rgba(110,160,205,0.35)'; ctx.lineWidth = 1; + for (let ly = 68; ly < 10 + CARD_H; ly += 24) { ctx.beginPath(); ctx.moveTo(12, ly); ctx.lineTo(12 + CARD_W, ly); ctx.stroke(); } + ctx.fillStyle = noisePattern(ctx, 80, 10); ctx.fillRect(12, 10, CARD_W, CARD_H); + scene.textures.addCanvas('tectonic-card', c); +} + +export const CERT_W = 940, CERT_H = 640; +function bakeCert(scene) { + seed = 33; + const c = canvas(CERT_W + 40, CERT_H + 40); + const ctx = c.getContext('2d'); + const x = 20, y = 20, w = CERT_W, h = CERT_H; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 24; ctx.shadowOffsetY = 10; + ctx.fillStyle = '#f3e8c9'; ctx.fillRect(x, y, w, h); + ctx.restore(); + const g = ctx.createRadialGradient(x + w / 2, y + h / 2, 100, x + w / 2, y + h / 2, w * 0.7); + g.addColorStop(0, 'rgba(255,250,235,0.6)'); g.addColorStop(1, 'rgba(160,120,60,0.22)'); + ctx.fillStyle = g; ctx.fillRect(x, y, w, h); + // double rule border + guilloche wave + ctx.strokeStyle = '#6a4a2a'; ctx.lineWidth = 3; ctx.strokeRect(x + 22, y + 22, w - 44, h - 44); + ctx.lineWidth = 1; ctx.strokeRect(x + 32, y + 32, w - 64, h - 64); + ctx.strokeStyle = 'rgba(106,74,42,0.45)'; + for (const [x0, y0, x1, y1] of [[x + 40, y + 27, x + w - 40, y + 27], [x + 40, y + h - 27, x + w - 40, y + h - 27]]) { + ctx.beginPath(); + for (let t = 0; t <= 1; t += 0.004) { + const px = x0 + (x1 - x0) * t, py = y0 + Math.sin(t * 160) * 3; + t ? ctx.lineTo(px, py) : ctx.moveTo(px, py); + } + ctx.stroke(); + } + // corner strata blocks + for (const [cx, cy] of [[x + 32, y + 32], [x + w - 32, y + 32], [x + 32, y + h - 32], [x + w - 32, y + h - 32]]) { + TONES.slice(0, 4).forEach((t, i) => { + ctx.fillStyle = t.fill; ctx.globalAlpha = 0.7; + ctx.fillRect(cx - 14, cy - 14 + i * 7, 28, 7); + }); + ctx.globalAlpha = 1; + ctx.strokeStyle = '#6a4a2a'; ctx.lineWidth = 1.5; ctx.strokeRect(cx - 14, cy - 14, 28, 28); + } + // seismograph band under the title + ctx.strokeStyle = 'rgba(106,74,42,0.5)'; ctx.lineWidth = 1.5; + ctx.beginPath(); + for (let px = x + 120; px <= x + w - 120; px += 3) { + const t = (px - x - 120) / (w - 240); + const amp = Math.exp(-Math.pow((t - 0.5) * 6, 2)) * 22 + 2; + const py = y + 190 + Math.sin(px * 0.9) * amp * (0.5 + rnd() * 0.5); + px === x + 120 ? ctx.moveTo(px, py) : ctx.lineTo(px, py); + } + ctx.stroke(); + ctx.fillStyle = noisePattern(ctx, 120, 18); ctx.fillRect(x, y, w, h); + scene.textures.addCanvas('tectonic-cert', c); +} + +export function prepareTectonicArt(scene) { + if (!scene.textures.exists('tectonic-desk')) bakeDesk(scene); + if (!scene.textures.exists('tectonic-cover')) bakeCover(scene); + for (let n = 1; n <= 5; n++) + if (!scene.textures.exists(`tectonic-tag-${n}`)) bakeTag(scene, `tectonic-tag-${n}`, TAG_TONES[n - 1]); + if (!scene.textures.exists('tectonic-eraser')) bakeEraser(scene); + if (!scene.textures.exists('tectonic-card')) bakeCard(scene); + if (!scene.textures.exists('tectonic-cert')) bakeCert(scene); +} + +// ── Cage plates (per puzzle) ────────────────────────────────────────────────── +// Bakes two textures for one cage: `${key}-fill` (watercolour wash, shown at +// partial alpha so it can deepen on completion) and `${key}-ink` (the inked +// outline, inset so neighbouring plates read as separate pieces with a fault +// line of paper between them). Returns { x, y } — the top-left screen position +// of both images — or null if the cage outline can't be traced. +export function bakeCage(scene, key, cells, tone, cageSeed = 1) { + const loop = traceCage(cells); + if (!loop || loop.length < 4) return null; + const minC = Math.min(...cells.map(p => p.c)), minR = Math.min(...cells.map(p => p.r)); + const maxC = Math.max(...cells.map(p => p.c)), maxR = Math.max(...cells.map(p => p.r)); + const tw = (maxC - minC + 1) * CELL + CAGE_PAD * 2, th = (maxR - minR + 1) * CELL + CAGE_PAD * 2; + const toPx = ([gx, gy]) => [(gx - minC) * CELL + CAGE_PAD, (gy - minR) * CELL + CAGE_PAD]; + + let s = (cageSeed * 7919 + 13) % 2147483647 || 1; + const r = () => { s = (s * 16807) % 2147483647; return s / 2147483647; }; + + const INSET = 4.5; + const pts = insetLoop(loop, INSET / CELL).map(toPx); + + // wobbly path: subdivide each edge and jitter, keep corners slightly rounded + const wobble = (amp) => { + const out = []; + for (let i = 0; i < pts.length; i++) { + const a = pts[i], b = pts[(i + 1) % pts.length]; + const len = Math.hypot(b[0] - a[0], b[1] - a[1]); + const steps = Math.max(2, Math.round(len / 22)); + for (let k = 0; k < steps; k++) { + const t = k / steps; + const nx = -(b[1] - a[1]) / len, ny = (b[0] - a[0]) / len; + const j = k === 0 ? 0 : (r() - 0.5) * 2 * amp; + out.push([a[0] + (b[0] - a[0]) * t + nx * j, a[1] + (b[1] - a[1]) * t + ny * j]); + } + } + return out; + }; + const path = (ctx, p) => { + ctx.beginPath(); + p.forEach(([x, y], i) => i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)); + ctx.closePath(); + }; + + // fill: layered watercolour wash with darker pooled edges + const fc = canvas(tw, th); + const f = fc.getContext('2d'); + f.save(); + path(f, pts); f.clip(); + f.fillStyle = tone.fill; + for (let k = 0; k < 3; k++) { + f.globalAlpha = 0.22; + path(f, wobble(3)); f.fill(); + } + // granulation blooms + for (let k = 0; k < cells.length * 6; k++) { + const cell = cells[Math.floor(r() * cells.length)]; + const bx = (cell.c - minC) * CELL + CAGE_PAD + r() * CELL, by = (cell.r - minR) * CELL + CAGE_PAD + r() * CELL; + const br = 10 + r() * 26; + const bg = f.createRadialGradient(bx, by, 1, bx, by, br); + bg.addColorStop(0, tone.fill); bg.addColorStop(1, 'rgba(0,0,0,0)'); + f.globalAlpha = 0.14 + r() * 0.12; + f.fillStyle = bg; + f.fillRect(bx - br, by - br, br * 2, br * 2); + } + f.globalAlpha = 0.45; + f.strokeStyle = tone.fill; f.lineWidth = 9; f.lineJoin = 'round'; + path(f, pts); f.stroke(); + f.globalAlpha = 1; + f.fillStyle = noisePattern(f, 64, 26); f.fillRect(0, 0, tw, th); + f.restore(); + scene.textures.addCanvas(`${key}-fill`, fc); + + // ink: a pen line that varies a little in weight + const ic = canvas(tw, th); + const ik = ic.getContext('2d'); + ik.lineJoin = 'round'; ik.lineCap = 'round'; + ik.strokeStyle = 'rgba(38,49,61,0.92)'; ik.lineWidth = 3.4; + path(ik, wobble(0.7)); ik.stroke(); + ik.strokeStyle = 'rgba(38,49,61,0.28)'; ik.lineWidth = 1.2; + path(ik, wobble(1.1)); ik.stroke(); + scene.textures.addCanvas(`${key}-ink`, ic); + + return { x: GRID_X + minC * CELL - CAGE_PAD, y: GRID_Y + minR * CELL - CAGE_PAD, w: tw, h: th }; +} + +export function removeCageTextures(scene, keys) { + for (const k of keys) { + for (const suffix of ['-fill', '-ink']) { + if (scene.textures.exists(k + suffix)) scene.textures.remove(k + suffix); + } + } +} + +// ── PaperButton ────────────────────────────────────────────────────────────── +// A pencil-sketched label on the page. Container centred on (x, y); children are +// centred too (a Container's hit area is always centred on its position). +export class PaperButton extends Phaser.GameObjects.Container { + constructor(scene, x, y, label, onClick, { width = 200, height = 54, fontSize = 30, accent = false, fill = 0xf2e7c9 } = {}) { + super(scene, x, y); + this.w = width; this.h = height; this.accent = accent; this.fillCol = fill; + this.enabled = true; + this.gfx = scene.add.graphics(); + this.text = scene.add.text(0, 1, label, { + fontFamily: 'YummyCupcakes', fontSize: `${fontSize}px`, color: INK, + }).setOrigin(0.5); + const maxW = width - 18; + if (this.text.width > maxW) this.text.setFontSize(Math.max(14, Math.floor(fontSize * maxW / this.text.width))); + this.add([this.gfx, this.text]); + this.setSize(width, height); + this.setInteractive({ useHandCursor: true }); + this.hover = false; + 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); + } + + draw() { + const g = this.gfx, w = this.w, h = this.h; + g.clear(); + g.fillStyle(0x000000, 0.16); + g.fillRoundedRect(-w / 2 + 3, -h / 2 + 4, w, h, 10); + g.fillStyle(this.hover && this.enabled ? 0xe9d39c : this.fillCol, 1); + g.fillRoundedRect(-w / 2, -h / 2, w, h, 10); + g.lineStyle(2.2, this.accent ? RED_PENCIL : INK_N, 0.85); + g.strokeRoundedRect(-w / 2, -h / 2, w, h, 10); + g.lineStyle(1, this.accent ? RED_PENCIL : INK_N, 0.3); + g.strokeRoundedRect(-w / 2 + 2, -h / 2 - 1, w - 1, h + 1, 11); + } + + setLabel(t) { this.text.setText(t); return this; } + + setEnabled(on) { + this.enabled = on; + this.setAlpha(on ? 1 : 0.42); + if (this.input) this.input.cursor = on ? 'pointer' : 'default'; + this.draw(); + return this; + } +} diff --git a/src/games/tectonic/TectonicGame.js b/src/games/tectonic/TectonicGame.js index 7b98ad6..6271444 100644 --- a/src/games/tectonic/TectonicGame.js +++ b/src/games/tectonic/TectonicGame.js @@ -1,645 +1,1334 @@ +// Tectonic (Suguru) — "Field Geologist's Notebook". +// +// The puzzle lives on the left page of a field notebook lying open on a desk: +// each cage is a watercolour "plate" with an inked outline and a size badge. +// The right page holds the field notes (timer, mistakes, hints), the specimen +// tags 1–5 + eraser, undo/redo, hint, pause and the page buttons. +// +// Input: pick a tag then tap cells (number-first), or tap a cell then a tag / +// press 1–5 (cell-first). Arrows/WASD move the cursor, Backspace/Delete/0 +// erase, Ctrl+Z / Ctrl+Y undo/redo, H hint, P pause, Esc clears the selection. +// +// Feedback follows the original rules: Easy checks each entry immediately; +// Medium/Hard check once every cell is filled, then switch to immediate checks. +// Games autosave to localStorage; stats per difficulty + the Daily Survey. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { api } from '../../services/api.js'; -import { Button } from '../../ui/Button.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { HINT_LIMITS, DIFFICULTY_SCORES, isBoardComplete, getHintCell } from './TectonicLogic.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; +import { loadStats, recordGame, formatTime } from '../../ui/solitaire/SolitaireStats.js'; +import { + N, HINT_LIMITS, DIFF_LABELS, calcScore, isBoardComplete, getHintCell, + cageMeta, cageStatus, colourCages, traceCage, insetLoop, + makeHistory, pushEdit, pushMarker, canUndo, canRedo, undoEdit, redoEdit, + SAVE_KEY, serialiseSave, parseSave, + DAILY_KEY, DAILY_DIFFICULTY, todayString, dailySeed, updateDaily, dailyStreakNow, blankDaily, +} from './TectonicLogic.js'; +import { + W, H, BOOK, LEFT, RIGHT, SPINE_X, LCX, RCX, CELL, GRID_W, GRID_X, GRID_Y, + TONES, INK, INK_N, PENCIL, BLUE_INK, RED_PENCIL, TAG_H, CARD_W, CARD_H, + prepareTectonicArt, bakeCage, removeCageTextures, PaperButton, +} from './TectonicArt.js'; -// ── Palette (graph-paper notebook) ───────────────────────────────────────────── -const PAPER = 0xFCFEFF; // bright graph-paper white -const PAPER_EDGE = 0xD9E4EC; -const GRAPH_BLUE = 0x9DC4E6; // fine printed grid lines -const CELL_BLUE = 0x6FA3CF; // puzzle cell separators -const REGION_INK = 0x223547; // bold cage outlines -const INK = '#21303f'; // given numbers (ink) -const INK_N = 0x21303f; -const FADED = '#8aa6bd'; -const TITLE_BLUE = '#27506e'; -const RED_MARK = 0xc0392b; -const PLAYER_INK = '#1c6fb0'; // player-entered numbers (blue pen) - -const DEPTH = { - bg: 0, paper: 1, graph: 2, cell: 3, cellLines: 4, region: 5, - number: 6, selector: 7, hit: 10, ui: 20, overlay: 40, +const D = { + desk: 0, page: 2, gridLines: 4, cages: 10, hover: 14, cursor: 16, hit: 20, + ui: 30, flap: 40, toast: 45, cover: 55, modal: 60, cert: 80, }; -// ── Layout ────────────────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; +const HEADER_Y = LEFT.y + 17; // inside the printed header band +const TAG_Y = 392; // centre of a tag's body +const TAG_PITCH = 128; +const ERASER_Y = 548; +const HINT_Y = 652; +const PAGE_BTN_Y = 968; +const SEISMO_Y = 986; +const SEISMO_X0 = GRID_X + 14, SEISMO_X1 = GRID_X + GRID_W - 14; +const GUIDE_SEEN_KEY = 'tectonic-guide-seen'; -// Paper sheet -const PX = 60, PY = 40, PW = 1800, PH = 1000; -const GRAPH_PITCH = 45; +const GIVEN_COLOR = INK; +const HINT_COLOR = '#8a6a1c'; +const TITLE_BLUE = '#27506e'; -// Grid (8×8, centered in the left panel) -const N = 8; -const CELL = 90; -const GRID_W = N * CELL; // 720 -const GRID_H = N * CELL; // 720 -const TITLE_CX = 540; // centre of the left panel -const GRID_X = TITLE_CX - GRID_W / 2; // 180 -const GRID_Y = 200; +const DEMO_REGIONS = [[4, 2, 2, 2, 2], [4, 2, 0, 1, 1], [4, 4, 0, 1, 1], [3, 3, 3, 1, 5], [3, 3, 5, 5, 5]]; +const DEMO_SOLUTION = [[1, 3, 1, 4, 2], [2, 5, 2, 3, 1], [3, 4, 1, 4, 2], [1, 2, 3, 5, 1], [4, 5, 4, 2, 3]]; +const DEMO_SHOWN = [[1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 1, 1], [1, 0, 1, 0, 1]]; -// Right-panel number selector (1–5 + eraser) -const NUM_X = 1440; -const NUM_START_Y = 282; -const NUM_STEP = 108; -const ERASER_CY = NUM_START_Y + 5 * NUM_STEP + 6; // below the "5" -const HINT_BTN_Y = ERASER_CY + 86; -const BTN_Y = PY + PH - 48; +let puzzleCounter = 0; // unique cage texture keys across restarts -const DIFF_LABELS = { easy: 'Easy', medium: 'Medium', hard: 'Hard' }; +const storage = () => { try { return globalThis.localStorage ?? null; } catch { return null; } }; +const readJSON = (k) => { try { return JSON.parse(storage()?.getItem(k) || 'null'); } catch { return null; } }; +const writeJSON = (k, v) => { try { storage()?.setItem(k, JSON.stringify(v)); } catch { /* private/full */ } }; + +const cellCX = (c) => GRID_X + c * CELL + CELL / 2; +const cellCY = (r) => GRID_Y + r * CELL + CELL / 2; export default class TectonicGame extends Phaser.Scene { constructor() { super('TectonicGame'); } init(data) { - this._initData = { ...data }; - this.gameDef = data.game; + this._initData = { ...data }; + delete this._initData.next; + this.next = data.next ?? null; + this.gameDef = data.game; - this.grid = null; - this.solution = null; - this.regions = null; - this.regionSize = null; // 2D: size of the region each cell belongs to - this.neededFor = null; // neededFor[v] = how many regions hold value v - this.difficulty = ''; - this.selectedNum = 1; - this.hintsLeft = null; - this.hintsUsed = 0; - this.gameEnded = false; - this.hoveredCell = null; + this.mode = 'start'; // start | loading | play | won + this.startObjs = []; + this.modal = null; + this.coverBusy = false; + this.paused = false; + this.flap = null; + this.toastObj = null; - this.givenCells = []; - this.cellState = []; // 0=empty, 1=correct, 2=wrong - this.cellBgObjs = []; - this.cellTextObjs = []; - this.cellHitObjs = []; + this.grid = null; this.solution = null; this.regions = null; this.givens = null; + this.hinted = new Set(); + this.difficulty = 'medium'; + this.daily = null; + this.surveyNo = 0; + this.cellState = null; + this.history = makeHistory(); + this.elapsed = 0; + this.timerOn = false; + this.hintsLeft = 0; this.hintsUsed = 0; this.mistakes = 0; + this.revealed = false; + this.moves = 0; + this.gameEnded = false; + this.winPending = false; + this.hintPending = false; - this.numCircleGfx = null; - this.numStrikeGfx = null; - this.numTextObjs = {}; - this.numHitObjs = {}; - this.hintBtn = null; - this.startObjs = []; - this.revealed = false; + this.cursor = null; + this.armed = null; // null | 0 (eraser) | 1..5 + this.hover = null; + + this.cageKeys = []; + this.cageObjs = new Map(); // id → { cont, fill, wash, ink, badge, cells, slot } + this.cageDone = new Set(); + this.seismoAmp = new Map(); // id → 0..1 + this.seismoBurst = 0; + this.cellText = []; + this.tags = {}; + this._lastSecond = -1; } - async create() { + create() { + prepareTectonicArt(this); const music = this.cache.json.get('music'); if (music?.tracks) new MusicPlayer(this, music.tracks); - this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(DEPTH.bg); + this.add.image(0, 0, 'tectonic-desk').setOrigin(0).setDepth(D.desk); - await this.showStartPanel(); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this._onBlur = () => { if (this.mode === 'play' && this.timerOn && !this.paused && !this.gameEnded) this.setPaused(true); }; + this.game.events.on('blur', this._onBlur); + this.game.events.on('hidden', this._onBlur); + this.events.once('shutdown', () => this.onShutdown()); + + const next = this.next; + if (next?.resume) { + const save = parseSave(storage()?.getItem(SAVE_KEY)); + if (save) { this.beginFromSave(save); return; } + } + if (next?.difficulty) { this.startGame(next.difficulty, { daily: next.daily ?? null }); return; } + this.showStart({ cover: !next }); } - // ── Start panel ─────────────────────────────────────────────────────────────── + onShutdown() { + this.saveGame(); + this.game.events.off('blur', this._onBlur); + this.game.events.off('hidden', this._onBlur); + removeCageTextures(this, this.cageKeys); + this.cageKeys = []; + } - async showStartPanel() { - const cx = CX, cy = CY; + restartWith(next) { + this.scene.restart({ ...this._initData, next }); + } - const sheet = this.add.graphics().setDepth(DEPTH.paper); - sheet.postFX.addShadow(0, 6, 0.02, 1.2, 0x000000, 10, 0.6); - sheet.fillStyle(PAPER, 1); - sheet.fillRoundedRect(cx - 600, cy - 320, 1200, 640, 18); - sheet.lineStyle(3, PAPER_EDGE, 1); - sheet.strokeRoundedRect(cx - 600, cy - 320, 1200, 640, 18); - this.startObjs.push(sheet); + leave() { + this.saveGame(); + this.scene.start('GameMenu'); + } - // graph lines inside the start sheet - const g = this.add.graphics().setDepth(DEPTH.graph); - g.lineStyle(1, GRAPH_BLUE, 0.4); - for (let x = cx - 600 + GRAPH_PITCH; x < cx + 600; x += GRAPH_PITCH) - g.lineBetween(x, cy - 320, x, cy + 320); - for (let y = cy - 320 + GRAPH_PITCH; y < cy + 320; y += GRAPH_PITCH) - g.lineBetween(cx - 600, y, cx + 600, y); - this.startObjs.push(g); + // ── Start screen ──────────────────────────────────────────────────────────── - this.startObjs.push( - this.add.text(cx, cy - 226, 'Tectonic', { - fontFamily: 'YummyCupcakes', fontSize: '104px', color: TITLE_BLUE, - }).setOrigin(0.5).setDepth(DEPTH.ui), - ); + showStart({ cover = false } = {}) { + this.mode = 'start'; + const add = (o) => { this.startObjs.push(o); return o; }; + const save = parseSave(storage()?.getItem(SAVE_KEY)); + const today = todayString(); - this.startObjs.push( - this.add.text(cx, cy - 118, 'Fill each cage 1–N · no touching twins', { - fontFamily: 'YummyCupcakes', fontSize: '34px', color: '#5a7a92', - }).setOrigin(0.5).setDepth(DEPTH.ui), - ); + // left page: title, a sample plate map, guide + leave + add(this.add.text(LEFT.x + 24, HEADER_Y, 'FIELD NOTEBOOK · VOL. VIII', { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(0, 0.5).setDepth(D.ui).setAlpha(0.8)); + add(this.add.text(LCX, 196, 'Tectonic', { + fontFamily: 'YummyCupcakes', fontSize: '128px', color: TITLE_BLUE, + }).setOrigin(0.5).setDepth(D.ui)); + add(this.add.text(LCX, 290, 'A field survey of number plates', { + fontFamily: 'YummyCupcakes', fontSize: '36px', color: PENCIL, + }).setOrigin(0.5).setDepth(D.ui)); + this.drawDemoBoard(add); + add(this.add.text(LCX, 842, 'Each plate of N cells holds 1 to N.\nTouching cells never match, not even corner to corner.', { + fontFamily: 'YummyCupcakes', fontSize: '27px', color: INK, align: 'center', lineSpacing: 6, + }).setOrigin(0.5).setDepth(D.ui)); + add(new PaperButton(this, LCX - 130, PAGE_BTN_Y, 'Field guide', () => this.openGuide(), { width: 220 }).setDepth(D.ui)); + add(new PaperButton(this, LCX + 130, PAGE_BTN_Y, 'Leave', () => this.scene.start('GameMenu'), { width: 220 }).setDepth(D.ui)); - this.startObjs.push( - this.add.text(cx, cy - 44, 'Choose difficulty', { - fontFamily: 'YummyCupcakes', fontSize: '44px', color: INK, - }).setOrigin(0.5).setDepth(DEPTH.ui), - ); + // right page: survey site cards + add(this.add.text(RIGHT.x + RIGHT.w - 24, HEADER_Y, today, { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(1, 0.5).setDepth(D.ui).setAlpha(0.8)); + add(this.add.text(RCX, 140, 'Choose a survey site', { + fontFamily: 'YummyCupcakes', fontSize: '54px', color: INK, + }).setOrigin(0.5).setDepth(D.ui)); - const diffs = [['Easy', 'easy'], ['Medium', 'medium'], ['Hard', 'hard']]; - diffs.forEach(([label, id], i) => { - const b = new Button(this, cx + (i - 1) * 260, cy + 70, label, - () => this.startGame(id), { width: 230, height: 70, fontSize: 26 }); - b.setDepth(DEPTH.ui); - this.startObjs.push(b); + const dailyRec = readJSON(DAILY_KEY) ?? blankDaily(); + const dailyTime = dailyRec.solved?.[today]; + const statLine = (mode) => { + const s = loadStats('tectonic', mode); + if (!s.played) return 'No surveys yet'; + return `Solved ${s.won} · Best ${formatTime(s.bestTime)} · Streak ${s.streak}`; + }; + + const cards = []; + if (save) { + const givenFlat = save.givens.flat(); + const empties = givenFlat.filter(g => !g).length; + const filled = save.grid.flat().filter((v, i) => v && !givenFlat[i]).length; + const label = save.daily ? `Daily Survey (${save.daily})` : `${DIFF_LABELS[save.difficulty]} site`; + cards.push({ title: 'Resume survey', tone: '#b8402f', desc: `${label} · No. ${save.surveyNo || '—'}`, + stats: `${formatTime(save.elapsed)} on the clock · ${filled} / ${empties} cells written`, + go: () => this.restartWith({ resume: true }) }); + } + cards.push({ title: 'Daily Survey', tone: TONES[5].fill, desc: 'One plate map for everyone today (Medium rules)', + stats: `Day streak ${dailyStreakNow(dailyRec, today)} · Today: ${dailyTime != null ? `solved in ${formatTime(dailyTime)}` : 'not yet surveyed'}`, + go: () => this.pickSite(DAILY_DIFFICULTY, today, save) }); + cards.push({ title: 'Easy site', tone: TONES[2].fill, desc: '30 givens · unlimited hints · checked as you write', + stats: statLine('easy'), go: () => this.pickSite('easy', null, save) }); + cards.push({ title: 'Medium site', tone: TONES[0].fill, desc: '24 givens · 5 hints · checked once the map is full', + stats: statLine('medium'), go: () => this.pickSite('medium', null, save) }); + cards.push({ title: 'Hard site', tone: TONES[3].fill, desc: '18 givens · no hints · checked once the map is full', + stats: statLine('hard'), go: () => this.pickSite('hard', null, save) }); + + const pitch = cards.length > 4 ? 150 : 166; + const y0 = cards.length > 4 ? 262 : 290; + cards.forEach((spec, i) => this.makeCard(add, RCX, y0 + i * pitch, spec, i)); + + if (cover) this.playCover(); + else this.maybeFirstGuide(); + } + + drawDemoBoard(add) { + const cell = 64, n = 5; + const x0 = LCX - (cell * n) / 2, y0 = 368; + const meta = cageMeta(DEMO_REGIONS); + const colours = colourCages(DEMO_REGIONS, TONES.length); + const g = add(this.add.graphics().setDepth(D.cages)); + for (const [id, cells] of meta.cages) { + const tone = Phaser.Display.Color.HexStringToColor(TONES[colours.get(id)].fill).color; + g.fillStyle(tone, 0.32); + for (const { r, c } of cells) g.fillRect(x0 + c * cell, y0 + r * cell, cell, cell); + } + g.lineStyle(3, INK_N, 0.9); + for (const cells of meta.cages.values()) { + const loop = insetLoop(traceCage(cells), 3 / cell); + g.strokePoints(loop.map(([x, y]) => ({ x: x0 + x * cell, y: y0 + y * cell })), true, true); + } + for (let r = 0; r < n; r++) + for (let c = 0; c < n; c++) { + if (!DEMO_SHOWN[r][c]) continue; + add(this.add.text(x0 + c * cell + cell / 2, y0 + r * cell + cell / 2 + 1, String(DEMO_SOLUTION[r][c]), { + fontFamily: r % 2 ? 'YummyCupcakes' : 'Righteous', fontSize: r % 2 ? '40px' : '34px', color: r % 2 ? BLUE_INK : INK, + }).setOrigin(0.5).setDepth(D.cages + 1)); + } + add(this.add.text(x0 + n * cell + 26, y0 + 30, 'fig. 1', { + fontFamily: 'YummyCupcakes', fontSize: '24px', color: PENCIL, + }).setOrigin(0, 0.5).setDepth(D.ui).setAngle(-6)); + } + + makeCard(add, x, y, spec, i) { + const cont = add(this.add.container(x, y).setDepth(D.ui)); + const img = this.add.image(0, 0, 'tectonic-card'); + const band = this.add.graphics(); + band.fillStyle(Phaser.Display.Color.HexStringToColor(spec.tone).color, 0.85); + band.fillRect(-CARD_W / 2, -CARD_H / 2 - 2, 16, CARD_H); + const title = this.add.text(-CARD_W / 2 + 36, -CARD_H / 2 + 18, spec.title, { + fontFamily: 'YummyCupcakes', fontSize: '40px', color: INK, + }).setOrigin(0, 0.5); + const desc = this.add.text(-CARD_W / 2 + 38, 8, spec.desc, { + fontFamily: 'YummyCupcakes', fontSize: '24px', color: BLUE_INK, + }).setOrigin(0, 0.5); + const stats = this.add.text(-CARD_W / 2 + 38, 40, spec.stats, { + fontFamily: 'YummyCupcakes', fontSize: '22px', color: PENCIL, + }).setOrigin(0, 0.5); + cont.add([img, band, title, desc, stats]); + cont.setAngle(i % 2 ? 0.6 : -0.5); + cont.setSize(CARD_W, CARD_H); + cont.setInteractive({ useHandCursor: true }); + cont.on('pointerover', () => this.tweens.add({ targets: cont, y: y - 5, angle: 0, duration: 120 })); + cont.on('pointerout', () => this.tweens.add({ targets: cont, y, angle: i % 2 ? 0.6 : -0.5, duration: 160 })); + cont.on('pointerup', () => { + if (this.coverBusy || this.modal || this.mode !== 'start') return; + playSound(this, SFX.UI_PICK); + spec.go(); }); - - const leave = new Button(this, cx, cy + 210, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 200, height: 50, fontSize: 22 }); - leave.setDepth(DEPTH.ui); - this.startObjs.push(leave); } - destroyStart() { - this.startObjs.forEach(o => o.destroy()); - this.startObjs = []; + playCover() { + this.coverBusy = true; + const cont = this.add.container(SPINE_X, BOOK.y).setDepth(D.cover); + const img = this.add.image(0, 0, 'tectonic-cover').setOrigin(0, 0); + const cw = img.width; + const t1 = this.add.text(cw / 2, 330, 'FIELD NOTEBOOK', { + fontFamily: 'Righteous', fontSize: '34px', color: '#5a3a26', + }).setOrigin(0.5); + const t2 = this.add.text(cw / 2, 396, 'Tectonic Plate Surveys', { + fontFamily: 'YummyCupcakes', fontSize: '44px', color: '#27324a', + }).setOrigin(0.5); + cont.add([img, t1, t2]); + this.time.delayedCall(420, () => { + playSound(this, SFX.UI_FLIP); + this.tweens.add({ + targets: cont, scaleX: 0, duration: 620, ease: 'Cubic.easeIn', + onComplete: () => { cont.destroy(); this.coverBusy = false; this.maybeFirstGuide(); }, + }); + }); } - // ── Game start ──────────────────────────────────────────────────────────────── + maybeFirstGuide() { + if (storage()?.getItem(GUIDE_SEEN_KEY)) return; + this.time.delayedCall(200, () => { if (!this.modal) this.openGuide(); }); + } - async startGame(difficulty) { - this.destroyStart(); - playSound(this, SFX.PIECE_CLICK); - - let data; - try { - data = await api.get(`/words/tectonic/start?difficulty=${difficulty}`); - } catch (err) { - console.error('[tectonic] failed to fetch puzzle:', err); - await this.showStartPanel(); + // Choosing a site when a save exists abandons it (counted as played, not won). + pickSite(difficulty, daily, save) { + if (save && daily && save.daily === daily) { this.restartWith({ resume: true }); return; } + if (save && save.moves > 0) { + this.confirm('Start a new survey?', `Your saved ${save.daily ? 'Daily Survey' : `${DIFF_LABELS[save.difficulty]} site`} will be abandoned.`, + 'Abandon it', () => { this.abandonSave(save); this.restartWith({ difficulty, daily }); }); return; } + storage()?.removeItem(SAVE_KEY); + this.restartWith({ difficulty, daily }); + } - this.grid = data.grid.map(row => [...row]); - this.solution = data.solution; - this.regions = data.regions; - this.difficulty = difficulty; - this.selectedNum = 1; - this.hintsLeft = HINT_LIMITS[difficulty] ?? 0; - this.hintsUsed = 0; - this.gameEnded = false; - this.hoveredCell = null; - this.revealed = false; + abandonSave(save) { + recordGame('tectonic', { won: false, time: save.elapsed, moves: save.moves, mode: save.daily ? 'daily' : save.difficulty }); + storage()?.removeItem(SAVE_KEY); + } - this.computeRegionMeta(); + // ── Game start ───────────────────────────────────────────────────────────── - this.givenCells = this.grid.map(row => row.map(v => v !== 0)); - this.cellState = Array.from({ length: N }, () => Array(N).fill(0)); + async startGame(difficulty, { daily = null } = {}) { + this.mode = 'loading'; + const loading = this.add.text(LCX, GRID_Y + GRID_W / 2, 'Surveying the site…', { + fontFamily: 'YummyCupcakes', fontSize: '48px', color: PENCIL, + }).setOrigin(0.5).setDepth(D.ui); + const seedQ = daily ? `&seed=${dailySeed(daily)}` : ''; + let data; + try { + data = await api.get(`/words/tectonic/start?difficulty=${difficulty}${seedQ}`); + } catch (err) { + console.error('[tectonic] failed to fetch puzzle:', err); + loading.destroy(); + this.showStart(); + return; + } + if (!this.sys.isActive()) return; + loading.destroy(); - this.buildPaper(); - this.buildTitle(); - this.buildCellLines(); - this.buildRegionBorders(); - this.buildCells(); - this.buildSelector(); - if (this.hintsLeft > 0) this.buildHintBtn(); + this.difficulty = difficulty; + this.daily = daily; + this.grid = data.grid.map(row => [...row]); + this.solution = data.solution; + this.regions = data.regions; + this.givens = this.grid.map(row => row.map(v => v !== 0)); + this.cellState = Array.from({ length: N }, () => Array(N).fill(0)); + this.hintsLeft = HINT_LIMITS[difficulty] ?? 0; + this.surveyNo = daily ? 1000 + (dailySeed(daily) % 9000) : 1000 + Math.floor(Math.random() * 9000); + this.buildPlay(); + } + + beginFromSave(s) { + this.difficulty = s.difficulty; + this.daily = s.daily; + this.grid = s.grid; this.solution = s.solution; this.regions = s.regions; this.givens = s.givens; + this.hinted = new Set((s.hinted ?? []).filter(k => typeof k === 'string')); + this.cellState = s.cellState; + this.history = s.history; + this.elapsed = s.elapsed; + this.hintsLeft = s.hintsLeft; this.hintsUsed = s.hintsUsed; this.mistakes = s.mistakes; + this.revealed = s.revealed; + this.moves = s.moves; + this.surveyNo = s.surveyNo || 1000 + Math.floor(Math.random() * 9000); + this.timerOn = this.moves > 0; + this.buildPlay(); + this.toast('Welcome back. Survey resumed.'); + } + + // ── Play screen ──────────────────────────────────────────────────────────── + + buildPlay() { + this.mode = 'play'; + this.meta = cageMeta(this.regions); + this.buildHeader(); + this.buildBoard(); + this.buildNotes(); + this.buildTags(); this.buildControls(); - this.refreshSelector(); - this.updateCompletedNums(); + this.refreshAll(); } - // Region size per cell + how many regions contain each value 1..5. - computeRegionMeta() { - const counts = {}; - for (let r = 0; r < N; r++) - for (let c = 0; c < N; c++) { - const id = this.regions[r][c]; - counts[id] = (counts[id] || 0) + 1; - } - this.regionSize = this.regions.map(row => row.map(id => counts[id])); - this.neededFor = [0, 0, 0, 0, 0, 0]; - for (const id in counts) { - const size = counts[id]; - for (let v = 1; v <= size; v++) this.neededFor[v]++; - } + buildHeader() { + this.add.text(LEFT.x + 24, HEADER_Y, `SURVEY No. ${this.surveyNo}`, { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(0, 0.5).setDepth(D.ui).setAlpha(0.85); + this.add.text(LEFT.x + LEFT.w - 24, HEADER_Y, + this.daily ? `DAILY SURVEY · ${this.daily}` : `SITE: ${DIFF_LABELS[this.difficulty].toUpperCase()}`, { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(1, 0.5).setDepth(D.ui).setAlpha(0.85); + this.add.text(LCX, 138, 'Tectonic', { + fontFamily: 'YummyCupcakes', fontSize: '76px', color: TITLE_BLUE, + }).setOrigin(0.5).setDepth(D.ui); + const givens = this.givens.flat().filter(Boolean).length - this.hinted.size; + this.add.text(LCX, 194, `8 × 8 · ${this.meta.cages.size} plates · ${givens} givens`, { + fontFamily: 'YummyCupcakes', fontSize: '26px', color: PENCIL, + }).setOrigin(0.5).setDepth(D.ui); } - // ── Paper & graph lines ───────────────────────────────────────────────────── - - buildPaper() { - const g = this.add.graphics().setDepth(DEPTH.paper); - g.postFX.addShadow(0, 8, 0.02, 1.2, 0x000000, 14, 0.55); - g.fillStyle(PAPER, 1); - g.fillRoundedRect(PX, PY, PW, PH, 16); - g.lineStyle(2, PAPER_EDGE, 1); - g.strokeRoundedRect(PX, PY, PW, PH, 16); - - // Printed graph-paper grid across the whole sheet. - const gl = this.add.graphics().setDepth(DEPTH.graph); - gl.lineStyle(1, GRAPH_BLUE, 0.45); - for (let x = PX + GRAPH_PITCH; x < PX + PW; x += GRAPH_PITCH) - gl.lineBetween(x, PY + 6, x, PY + PH - 6); - for (let y = PY + GRAPH_PITCH; y < PY + PH; y += GRAPH_PITCH) - gl.lineBetween(PX + 6, y, PX + PW - 6, y); - } - - buildTitle() { - const titleTxt = this.add.text(TITLE_CX, 116, 'Tectonic', { - fontFamily: 'YummyCupcakes', fontSize: '84px', color: TITLE_BLUE, - }).setOrigin(0.5).setDepth(DEPTH.ui); - - this.add.text(titleTxt.x + titleTxt.width / 2 + 24, titleTxt.y + 14, - DIFF_LABELS[this.difficulty] ?? this.difficulty, { - fontFamily: 'YummyCupcakes', fontSize: '36px', color: FADED, - }).setOrigin(0, 0.5).setDepth(DEPTH.ui); - } - - // ── Grid lines & cage borders ──────────────────────────────────────────────── - - buildCellLines() { - const gfx = this.add.graphics().setDepth(DEPTH.cellLines); - gfx.lineStyle(1.5, CELL_BLUE, 0.5); + buildBoard() { + // pencilled cell grid + outer frame + const gl = this.add.graphics().setDepth(D.gridLines); + gl.lineStyle(1.2, 0x6f9fca, 0.45); for (let i = 1; i < N; i++) { - gfx.lineBetween(GRID_X + i * CELL, GRID_Y, GRID_X + i * CELL, GRID_Y + GRID_H); - gfx.lineBetween(GRID_X, GRID_Y + i * CELL, GRID_X + GRID_W, GRID_Y + i * CELL); + gl.lineBetween(GRID_X + i * CELL, GRID_Y, GRID_X + i * CELL, GRID_Y + GRID_W); + gl.lineBetween(GRID_X, GRID_Y + i * CELL, GRID_X + GRID_W, GRID_Y + i * CELL); + } + gl.lineStyle(2, INK_N, 0.35); + gl.strokeRect(GRID_X - 6, GRID_Y - 6, GRID_W + 12, GRID_W + 12); + // row/column survey marks + for (let i = 0; i < N; i++) { + this.add.text(GRID_X - 22, cellCY(i), String.fromCharCode(65 + i), { + fontFamily: 'Righteous', fontSize: '15px', color: PENCIL, + }).setOrigin(0.5).setDepth(D.gridLines).setAlpha(0.6); + this.add.text(cellCX(i), GRID_Y - 22, String(i + 1), { + fontFamily: 'Righteous', fontSize: '15px', color: PENCIL, + }).setOrigin(0.5).setDepth(D.gridLines).setAlpha(0.6); } - } - buildRegionBorders() { - const gfx = this.add.graphics().setDepth(DEPTH.region); - gfx.lineStyle(5, REGION_INK, 0.92); - - const idAt = (r, c) => (r < 0 || r >= N || c < 0 || c >= N) ? -1 : this.regions[r][c]; - - for (let r = 0; r < N; r++) { - for (let c = 0; c < N; c++) { - const id = this.regions[r][c]; - const x = GRID_X + c * CELL; - const y = GRID_Y + r * CELL; - if (idAt(r - 1, c) !== id) gfx.lineBetween(x, y, x + CELL, y); - if (idAt(r, c - 1) !== id) gfx.lineBetween(x, y, x, y + CELL); - if (idAt(r + 1, c) !== id) gfx.lineBetween(x, y + CELL, x + CELL, y + CELL); - if (idAt(r, c + 1) !== id) gfx.lineBetween(x + CELL, y, x + CELL, y + CELL); + // cage plates + const colours = colourCages(this.regions, TONES.length); + const pid = ++puzzleCounter; + const order = [...this.meta.cages.entries()] + .map(([id, cells]) => ({ id, cells, cx: cells.reduce((s, p) => s + p.c, 0) / cells.length })) + .sort((a, b) => a.cx - b.cx); + this.cellText = Array.from({ length: N }, () => Array(N).fill(null)); + order.forEach(({ id, cells }, slot) => { + const key = `tectonic-cage-${pid}-${id}`; + const tone = TONES[colours.get(id)]; + const pos = bakeCage(this, key, cells, tone, id + pid * 31); + this.cageKeys.push(key); + const cont = this.add.container(0, 0).setDepth(D.cages); + const fill = pos ? this.add.image(pos.x, pos.y, `${key}-fill`).setOrigin(0).setAlpha(0.6) : null; + const wash = this.add.graphics(); + const ink = pos ? this.add.image(pos.x, pos.y, `${key}-ink`).setOrigin(0) : null; + const first = cells[0]; + const badge = this.add.text(GRID_X + first.c * CELL + 11, GRID_Y + first.r * CELL + 9, String(cells.length), { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(0, 0).setAlpha(0.85); + const kids = [fill, wash, ink, badge].filter(Boolean); + for (const { r, c } of cells) { + const t = this.add.text(cellCX(c), cellCY(r) + 2, '', { + fontFamily: 'YummyCupcakes', fontSize: '56px', color: BLUE_INK, + }).setOrigin(0.5); + this.cellText[r][c] = t; + kids.push(t); } + cont.add(kids); + this.cageObjs.set(id, { cont, fill, wash, ink, badge, cells, slot, tone }); + }); + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) this.renderCellText(r, c); + + this.hoverGfx = this.add.graphics().setDepth(D.hover); + this.cursorGfx = this.add.graphics().setDepth(D.cursor); + + const zone = this.add.zone(GRID_X + GRID_W / 2, GRID_Y + GRID_W / 2, GRID_W, GRID_W) + .setDepth(D.hit).setInteractive({ useHandCursor: true }); + const cellAt = (p) => { + const c = Math.floor((p.worldX - GRID_X) / CELL), r = Math.floor((p.worldY - GRID_Y) / CELL); + return r >= 0 && r < N && c >= 0 && c < N ? { r, c } : null; + }; + zone.on('pointermove', (p) => { + const h = cellAt(p); + if (h?.r !== this.hover?.r || h?.c !== this.hover?.c) { this.hover = h; this.drawHover(); } + }); + zone.on('pointerout', () => { this.hover = null; this.drawHover(); }); + zone.on('pointerdown', (p) => { const h = cellAt(p); if (h) this.onCellPointer(h.r, h.c); }); + + // seismograph strip: plates surveyed + this.seismoLabel = this.add.text(GRID_X, 944, '', { + fontFamily: 'YummyCupcakes', fontSize: '24px', color: PENCIL, + }).setOrigin(0, 0.5).setDepth(D.ui); + this.seismoGfx = this.add.graphics().setDepth(D.ui); + let s = 99; + this.seismoNoise = Array.from({ length: 400 }, () => { s = (s * 16807) % 2147483647; return s / 2147483647 - 0.5; }); + } + + renderCellText(r, c) { + const t = this.cellText[r][c]; + if (!t) return; + const v = this.grid[r][c]; + t.setText(v ? String(v) : ''); + if (this.givens[r][c]) { + const hinted = this.hinted.has(`${r},${c}`); + t.setFontFamily('Righteous').setFontSize(46).setColor(hinted ? HINT_COLOR : GIVEN_COLOR); + } else { + t.setFontFamily('YummyCupcakes').setFontSize(56).setColor(BLUE_INK); } } - // ── Cells ───────────────────────────────────────────────────────────────────── + buildNotes() { + this.add.text(RIGHT.x + 56, HEADER_Y, 'FIELD NOTES', { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(0, 0.5).setDepth(D.ui).setAlpha(0.85); + this.add.text(RIGHT.x + RIGHT.w - 24, HEADER_Y, todayString(), { + fontFamily: 'Righteous', fontSize: '16px', color: PENCIL, + }).setOrigin(1, 0.5).setDepth(D.ui).setAlpha(0.85); - buildCells() { - this.cellBgObjs = []; - this.cellTextObjs = []; - this.cellHitObjs = []; + const box = this.add.graphics().setDepth(D.ui); + this.statTexts = {}; + [['time', 'Time', -232], ['mistakes', 'Mistakes', 0], ['hints', 'Hints used', 232]].forEach(([k, label, dx]) => { + const x = RCX + dx; + box.lineStyle(2, INK_N, 0.5); + box.strokeRoundedRect(x - 100, 114, 200, 104, 10); + box.lineStyle(1, INK_N, 0.18); + box.strokeRoundedRect(x - 98, 112, 199, 107, 11); + this.add.text(x, 136, label, { + fontFamily: 'YummyCupcakes', fontSize: '24px', color: PENCIL, + }).setOrigin(0.5).setDepth(D.ui); + this.statTexts[k] = this.add.text(x, 182, '', { + fontFamily: 'YummyCupcakes', fontSize: '54px', color: INK, + }).setOrigin(0.5).setDepth(D.ui); + }); + this.add.text(RCX, 268, 'Specimen tags', { + fontFamily: 'YummyCupcakes', fontSize: '30px', color: INK, + }).setOrigin(0.5).setDepth(D.ui); - for (let r = 0; r < N; r++) { - this.cellBgObjs.push([]); - this.cellTextObjs.push([]); - this.cellHitObjs.push([]); + const rule = this.isChecking() + ? 'Easy site: every entry is checked as you write.' + : `${this.daily ? 'Daily Survey' : `${DIFF_LABELS[this.difficulty]} site`}: checked once every cell is written.`; + this.add.text(RCX, 790, + 'Pick a tag, then tap cells, or tap a cell, then a tag.\n' + + 'Keys: arrows move · 1–5 write · Backspace erases\n' + + 'Ctrl+Z undo · Ctrl+Y redo · H hint · P pause', { + fontFamily: 'YummyCupcakes', fontSize: '25px', color: PENCIL, align: 'center', lineSpacing: 8, + }).setOrigin(0.5).setDepth(D.ui); + this.ruleText = this.add.text(RCX, 880, rule, { + fontFamily: 'YummyCupcakes', fontSize: '25px', color: BLUE_INK, align: 'center', + }).setOrigin(0.5).setDepth(D.ui); + } - for (let c = 0; c < N; c++) { - const cx = GRID_X + c * CELL + CELL / 2; - const cy = GRID_Y + r * CELL + CELL / 2; - const given = this.givenCells[r][c]; - const val = this.grid[r][c]; + buildTags() { + this.selGfx = this.add.graphics().setDepth(D.ui + 2); + this.strikeGfx = this.add.graphics().setDepth(D.ui + 3); + for (let n = 1; n <= 5; n++) { + const x = RCX + (n - 3) * TAG_PITCH; + const img = this.add.image(x, TAG_Y, `tectonic-tag-${n}`).setOrigin(0.5, 98 / 172).setDepth(D.ui); + const txt = this.add.text(x, TAG_Y - 6, String(n), { + fontFamily: 'Righteous', fontSize: '62px', color: INK, + }).setOrigin(0.5).setDepth(D.ui + 1); + const zone = this.add.zone(x, TAG_Y, 116, TAG_H + 10).setDepth(D.hit).setInteractive({ useHandCursor: true }); + zone.on('pointerover', () => this.tweens.add({ targets: [img, txt], angle: n % 2 ? 3 : -3, duration: 100 })); + zone.on('pointerout', () => this.tweens.add({ targets: [img, txt], angle: 0, duration: 140 })); + zone.on('pointerup', () => this.onTagPointer(n)); + this.tags[n] = { img, txt, zone, x }; + } + const eimg = this.add.image(RCX, ERASER_Y, 'tectonic-eraser').setDepth(D.ui); + const ezone = this.add.zone(RCX, ERASER_Y, 150, 90).setDepth(D.hit).setInteractive({ useHandCursor: true }); + ezone.on('pointerover', () => this.tweens.add({ targets: eimg, angle: 4, duration: 100 })); + ezone.on('pointerout', () => this.tweens.add({ targets: eimg, angle: 0, duration: 140 })); + ezone.on('pointerup', () => this.onTagPointer(0)); + this.tags[0] = { img: eimg, zone: ezone, x: RCX }; + } - const bg = this.add.graphics().setDepth(DEPTH.cell); - this.cellBgObjs[r].push(bg); + buildControls() { + this.undoBtn = new PaperButton(this, RCX - 220, ERASER_Y, 'Undo', () => this.doUndo(), { width: 170 }).setDepth(D.ui); + this.redoBtn = new PaperButton(this, RCX + 220, ERASER_Y, 'Redo', () => this.doRedo(), { width: 170 }).setDepth(D.ui); + this.hintBtn = new PaperButton(this, RCX - 136, HINT_Y, 'Hint', () => this.useHint(), { width: 250 }).setDepth(D.ui); + this.pauseBtn = new PaperButton(this, RCX + 136, HINT_Y, 'Pause', () => this.setPaused(!this.paused), { width: 250 }).setDepth(D.ui); + new PaperButton(this, RCX - 232, PAGE_BTN_Y, 'Field guide', () => this.openGuide(), { width: 196 }).setDepth(D.ui); + new PaperButton(this, RCX, PAGE_BTN_Y, 'New survey', () => this.newSurvey(), { width: 210, accent: true }).setDepth(D.ui); + new PaperButton(this, RCX + 232, PAGE_BTN_Y, 'Leave', () => this.leave(), { width: 196 }).setDepth(D.ui); + } - const txt = this.add.text(cx, cy, given ? String(val) : '', { - fontFamily: given ? 'Righteous' : 'YummyCupcakes', - fontSize: given ? '46px' : '50px', - color: given ? INK : PLAYER_INK, - }).setOrigin(0.5).setDepth(DEPTH.number); - this.cellTextObjs[r].push(txt); + // ── Rendering ─────────────────────────────────────────────────────────────── - if (given) { - this.cellHitObjs[r].push(null); - } else { - const hit = this.add.rectangle(cx, cy, CELL - 2, CELL - 2, 0xffffff, 0.001) - .setDepth(DEPTH.hit) - .setInteractive({ useHandCursor: true }); - hit.on('pointerover', () => this.onCellHover(r, c, true)); - hit.on('pointerout', () => this.onCellHover(r, c, false)); - hit.on('pointerdown', () => this.onCellClick(r, c)); - this.cellHitObjs[r].push(hit); + refreshAll() { + for (const id of this.meta.cages.keys()) this.drawWash(id); + this.recomputeCageDone(false); + this.refreshSelector(); + this.refreshButtons(); + this.refreshStats(); + this.drawCursor(); + this.drawSeismo(); + } + + isChecking() { return this.difficulty === 'easy' || this.revealed; } + + drawWash(id) { + const o = this.cageObjs.get(id); + if (!o) return; + const g = o.wash; + g.clear(); + for (const { r, c } of o.cells) { + const st = this.cellState[r][c]; + if (!st) continue; + const x = GRID_X + c * CELL + 7, y = GRID_Y + r * CELL + 7, s = CELL - 14; + if (st === 1) { + g.fillStyle(0x3c8a4e, 0.16); + g.fillRoundedRect(x, y, s, s, 8); + } else { + g.fillStyle(RED_PENCIL, 0.10); + g.fillRoundedRect(x, y, s, s, 8); + g.lineStyle(1.6, RED_PENCIL, 0.5); + for (let t = 12; t < s * 2; t += 12) { + const ax = x + Math.max(0, t - s), ay = y + Math.min(t, s); + const bx = x + Math.min(t, s), by = y + Math.max(0, t - s); + g.lineBetween(ax, ay, bx, by); } } } } - // ── Number selector ─────────────────────────────────────────────────────────── + drawHover() { + const g = this.hoverGfx; + if (!g) return; + g.clear(); + if (!this.hover || this.mode !== 'play' || this.paused) return; + const { r, c } = this.hover; + g.fillStyle(INK_N, this.givens[r][c] ? 0.03 : 0.07); + g.fillRoundedRect(GRID_X + c * CELL + 5, GRID_Y + r * CELL + 5, CELL - 10, CELL - 10, 8); + } - buildSelector() { - this.numCircleGfx = this.add.graphics().setDepth(DEPTH.selector); - this.numStrikeGfx = this.add.graphics().setDepth(DEPTH.selector + 2); - this.numHitObjs = {}; - this.numTextObjs = {}; - - for (let n = 1; n <= 5; n++) { - const ny = NUM_START_Y + (n - 1) * NUM_STEP; - - const numTxt = this.add.text(NUM_X, ny, String(n), { - fontFamily: '"Julius Sans One"', fontSize: '74px', color: INK, - }).setOrigin(0.5).setDepth(DEPTH.number + 1); - this.numTextObjs[n] = numTxt; - - const hit = this.add.rectangle(NUM_X, ny, 220, NUM_STEP - 4, 0xffffff, 0.001) - .setDepth(DEPTH.hit + 1) - .setInteractive({ useHandCursor: true }); - hit.on('pointerdown', () => this.selectNum(n)); - this.numHitObjs[n] = hit; - } - - // Eraser × - this.add.text(NUM_X, ERASER_CY, '×', { - fontFamily: '"Julius Sans One"', fontSize: '60px', color: FADED, - }).setOrigin(0.5).setDepth(DEPTH.number + 1); - - const eraserHit = this.add.rectangle(NUM_X, ERASER_CY, 220, NUM_STEP - 4, 0xffffff, 0.001) - .setDepth(DEPTH.hit + 1) - .setInteractive({ useHandCursor: true }); - eraserHit.on('pointerdown', () => this.selectNum(0)); - this.numHitObjs[0] = eraserHit; + drawCursor(offsetX = 0) { + const g = this.cursorGfx; + if (!g) return; + g.clear(); + if (!this.cursor || this.gameEnded) return; + const { r, c } = this.cursor; + const x = GRID_X + c * CELL + 6 + offsetX, y = GRID_Y + r * CELL + 6, s = CELL - 12; + g.lineStyle(3.2, RED_PENCIL, 0.9); + g.strokeRoundedRect(x, y, s, s, 10); + g.lineStyle(1.4, RED_PENCIL, 0.35); + g.strokeRoundedRect(x - 2, y + 1, s + 3, s - 1, 12); } refreshSelector() { - const gfx = this.numCircleGfx; - if (!gfx) return; - gfx.clear(); + const g = this.selGfx, sg = this.strikeGfx; + if (!g) return; + g.clear(); sg.clear(); + const maxV = this.cursor && !this.givens[this.cursor.r][this.cursor.c] + ? this.meta.sizeAt[this.cursor.r][this.cursor.c] : 5; + const counts = [0, 0, 0, 0, 0, 0]; + for (const row of this.grid) for (const v of row) if (v) counts[v]++; + for (let n = 1; n <= 5; n++) { + const t = this.tags[n]; + const used = counts[n] >= this.meta.neededFor[n]; + const out = n > maxV; + t.img.setAlpha(out ? 0.35 : 1); + t.txt.setAlpha(out ? 0.35 : 1).setColor(used ? '#9aa6b2' : INK); + if (used) { + sg.lineStyle(3.2, 0x6d7580, 0.85); + sg.lineBetween(t.x - 30, TAG_Y - 2, t.x + 30, TAG_Y - 12); + } + } + if (this.armed != null) { + const t = this.tags[this.armed]; + const cy = this.armed === 0 ? ERASER_Y : TAG_Y; + const rx = this.armed === 0 ? 92 : 70, ry = this.armed === 0 ? 56 : 86; + g.lineStyle(3.4, RED_PENCIL, 0.88); + g.strokeEllipse(t.x, cy, rx * 2, ry * 2); + g.lineStyle(1.8, RED_PENCIL, 0.3); + g.strokeEllipse(t.x + 4, cy - 3, rx * 2 + 8, ry * 2 + 6); + } + } - let cy; - if (this.selectedNum >= 1 && this.selectedNum <= 5) { - cy = NUM_START_Y + (this.selectedNum - 1) * NUM_STEP; - } else if (this.selectedNum === 0) { - cy = ERASER_CY; + refreshButtons() { + this.undoBtn?.setEnabled(!this.gameEnded && canUndo(this.history)); + this.redoBtn?.setEnabled(!this.gameEnded && canRedo(this.history)); + if (this.hintBtn) { + const finite = Number.isFinite(this.hintsLeft); + this.hintBtn.setLabel(this.hintsLeft === 0 && this.hintsUsed === 0 && finite ? 'No hints here' + : finite ? `Hint (${this.hintsLeft} left)` : 'Hint'); + this.hintBtn.setEnabled(!this.gameEnded && this.hintsLeft > 0); + } + this.pauseBtn?.setLabel(this.paused ? 'Resume' : 'Pause').setEnabled(!this.gameEnded); + } + + refreshStats() { + if (!this.statTexts) return; + this.statTexts.time.setText(formatTime(this.elapsed)); + this.statTexts.mistakes.setText(String(this.mistakes)); + this.statTexts.hints.setText(String(this.hintsUsed)); + } + + drawSeismo() { + const g = this.seismoGfx; + if (!g) return; + g.clear(); + const total = this.meta.cages.size; + this.seismoLabel.setText(`Plates surveyed ${this.cageDone.size} / ${total}`); + const slots = [...this.cageObjs.values()].map(o => o.slot); + const span = SEISMO_X1 - SEISMO_X0; + const slotX = (slot) => SEISMO_X0 + 40 + (slot / Math.max(1, slots.length - 1)) * (span - 80); + const spikes = []; + for (const [id, o] of this.cageObjs) { + const a = this.seismoAmp.get(id) ?? 0; + if (a > 0.001) spikes.push([slotX(o.slot), a]); + } + g.lineStyle(1, 0x6f9fca, 0.5); + g.lineBetween(SEISMO_X0, SEISMO_Y, SEISMO_X1, SEISMO_Y); + g.lineStyle(2, INK_N, 0.8); + g.beginPath(); + let k = 0; + for (let x = SEISMO_X0; x <= SEISMO_X1; x += 2, k++) { + let y = SEISMO_Y + this.seismoNoise[k % this.seismoNoise.length] * 2.2; + for (const [sx, a] of spikes) { + const d = (x - sx) / 11; + y += a * 22 * Math.exp(-d * d) * Math.sin(x * 0.9); + } + if (this.seismoBurst > 0) { + const d = (x - (SEISMO_X0 + SEISMO_X1) / 2) / (span * 0.28); + y += this.seismoBurst * 30 * Math.exp(-d * d) * Math.sin(x * 0.55 + k); + } + if (x === SEISMO_X0) g.moveTo(x, y); else g.lineTo(x, y); + } + g.strokePath(); + } + + // ── Input ────────────────────────────────────────────────────────────────── + + blocked() { return this.mode !== 'play' || this.gameEnded || this.winPending || this.hintPending || this.paused || !!this.modal; } + + onCellPointer(r, c) { + if (this.blocked()) return; + if (this.armed != null) { + this.cursor = { r, c }; + if (!this.givens[r][c]) { + if (this.armed === 0 || this.grid[r][c] === this.armed) this.writeCell(r, c, 0); + else this.writeCell(r, c, this.armed); + } else playSound(this, SFX.PIECE_CLICK); + } else if (this.cursor?.r === r && this.cursor?.c === c) { + this.cursor = null; + playSound(this, SFX.PIECE_CLICK); } else { + this.cursor = { r, c }; + playSound(this, SFX.PIECE_CLICK); + } + this.drawCursor(); + this.refreshSelector(); + } + + onTagPointer(n) { + if (this.blocked()) return; + if (this.armed === n) { + this.armed = null; + playSound(this, SFX.PIECE_CLICK); + } else if (this.armed != null) { + this.armed = n; + playSound(this, SFX.PIECE_CLICK); + } else if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) { + this.writeCell(this.cursor.r, this.cursor.c, n); + } else { + this.armed = n; + playSound(this, SFX.PIECE_CLICK); + } + this.refreshSelector(); + } + + onKey(e) { + const k = e.key; + if (this.modal) { + if (k === 'Escape') this.modal.close?.(); return; } - this.drawHandCircle(gfx, NUM_X, cy); - } - - drawHandCircle(gfx, cx, cy) { - gfx.lineStyle(3, RED_MARK, 0.88); - gfx.strokeEllipse(cx, cy, 92, 80); - gfx.lineStyle(2, RED_MARK, 0.28); - gfx.strokeEllipse(cx + 3, cy - 2, 96, 84); - } - - updateCompletedNums() { - const gfx = this.numStrikeGfx; - if (!gfx) return; - gfx.clear(); - - for (let n = 1; n <= 5; n++) { - let count = 0; - for (let r = 0; r < N; r++) - for (let c = 0; c < N; c++) - if (this.grid[r][c] === n) count++; - - const txt = this.numTextObjs[n]; - if (!txt) continue; - - if (count >= this.neededFor[n]) { - txt.setColor('#9bb0c2'); - const ny = NUM_START_Y + (n - 1) * NUM_STEP; - gfx.lineStyle(3, 0x7a92a6, 0.8); - gfx.lineBetween(NUM_X - 38, ny - 6, NUM_X + 38, ny - 6); - } else { - txt.setColor(INK); + if (this.mode !== 'play' || this.gameEnded) return; + const ctrl = e.ctrlKey || e.metaKey; + const lower = k.length === 1 ? k.toLowerCase() : k; + if (ctrl && lower === 'z') { e.preventDefault?.(); e.shiftKey ? this.doRedo() : this.doUndo(); return; } + if (ctrl && lower === 'y') { e.preventDefault?.(); this.doRedo(); return; } + if (ctrl) return; + if (lower === 'p') { this.setPaused(!this.paused); return; } + if (this.paused) return; + if (k === 'Escape') { + if (this.cursor || this.armed != null) { this.cursor = null; this.armed = null; this.drawCursor(); this.refreshSelector(); } + else this.setPaused(true); + return; + } + if (lower === 'h') { this.useHint(); return; } + const moves = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1], w: [-1, 0], s: [1, 0], a: [0, -1], d: [0, 1] }; + if (moves[lower]) { + e.preventDefault?.(); + if (!this.cursor) this.cursor = this.firstEmpty() ?? { r: 0, c: 0 }; + else { + const [dr, dc] = moves[lower]; + this.cursor = { r: (this.cursor.r + dr + N) % N, c: (this.cursor.c + dc + N) % N }; } + this.drawCursor(); + this.refreshSelector(); + return; + } + if (/^[1-5]$/.test(k)) { + const v = Number(k); + if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) this.writeCell(this.cursor.r, this.cursor.c, v); + else if (!this.cursor) { this.armed = v; playSound(this, SFX.PIECE_CLICK); this.refreshSelector(); } + return; + } + if (k === 'Backspace' || k === 'Delete' || k === '0') { + e.preventDefault?.(); + if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) this.writeCell(this.cursor.r, this.cursor.c, 0); } } - // ── Hint button ─────────────────────────────────────────────────────────────── - - buildHintBtn() { - const isLimited = isFinite(this.hintsLeft); - const label = isLimited ? `Hint (${this.hintsLeft} left)` : 'Hint'; - - this.hintBtn = new Button(this, NUM_X, HINT_BTN_Y, label, - () => this.useHint(), { width: 240, height: 56, fontSize: 22 }); - this.hintBtn.setDepth(DEPTH.ui); + firstEmpty() { + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!this.grid[r][c]) return { r, c }; + return null; } - updateHintBtn() { - if (!this.hintBtn) return; - const isLimited = isFinite(this.hintsLeft); - this.hintBtn.setLabel(isLimited ? `Hint (${this.hintsLeft} left)` : 'Hint'); - if (this.hintsLeft === 0) this.hintBtn.setEnabled(false); + // ── Editing ──────────────────────────────────────────────────────────────── + + // A player write (v = 0 erases). Validates, records history, evaluates. + writeCell(r, c, v) { + if (this.blocked() || this.givens[r][c]) return; + const size = this.meta.sizeAt[r][c]; + if (v > size) { this.rejectValue(r, c, size); return; } + const from = this.grid[r][c]; + if (from === v) return; + pushEdit(this.history, { r, c, from, to: v }); + this.moves++; + this.timerOn = true; + this.applyCell(r, c, v, { anim: true, countMistake: true }); } - // ── Controls ────────────────────────────────────────────────────────────────── - - buildControls() { - new Button(this, PX + 160, BTN_Y, 'New puzzle', - () => this.scene.restart(this._initData), - { variant: 'ghost', width: 230, height: 50, fontSize: 22 }).setDepth(DEPTH.ui); - - new Button(this, PX + PW - 130, BTN_Y, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 200, height: 50, fontSize: 22 }).setDepth(DEPTH.ui); - } - - // ── Input ───────────────────────────────────────────────────────────────────── - - selectNum(num) { - this.selectedNum = num; - this.refreshSelector(); - playSound(this, SFX.PIECE_CLICK); - } - - onCellHover(r, c, entering) { - this.hoveredCell = entering ? { r, c } : null; - this.drawCellBg(r, c, entering); - } - - onCellClick(r, c) { - if (this.gameEnded || this.givenCells[r][c]) return; - playSound(this, SFX.PIECE_CLICK); - - if (this.selectedNum === 0) { - this.clearCell(r, c); - } else if (this.grid[r][c] === this.selectedNum) { - this.clearCell(r, c); - } else { - this.placeNum(r, c, this.selectedNum); + rejectValue(r, c, size) { + playSoundEx(this, SFX.CLICK, { rate: 0.6, volume: 0.6 }); + const o = this.cageObjs.get(this.regions[r][c]); + if (o?.badge) { + o.badge.setColor('#b8402f').setScale(1.4); + this.tweens.add({ targets: o.badge, scale: 1, duration: 420, ease: 'Back.easeOut', onComplete: () => o.badge.setColor(PENCIL) }); } + const shake = { x: 0 }; + this.tweens.add({ + targets: shake, x: 1, duration: 280, + onUpdate: () => this.drawCursor(Math.sin(shake.x * Math.PI * 6) * 5 * (1 - shake.x)), + onComplete: () => this.drawCursor(), + }); + this.toast(`That plate has ${size} cell${size > 1 ? 's' : ''}, so it only holds 1–${size}.`, 2000); } - placeNum(r, c, num) { - this.grid[r][c] = num; - this.cellTextObjs[r][c].setText(String(num)); - - const hovered = this.hoveredCell?.r === r && this.hoveredCell?.c === c; - - if (this.isEasyMode() || this.revealed) { - const correct = (num === this.solution[r][c]); - this.cellState[r][c] = correct ? 1 : 2; - this.drawCellBg(r, c, hovered); - - if (correct && isBoardComplete(this.grid, this.solution)) { - this.time.delayedCall(300, () => this.handleWin()); + // Set a cell's value and run the feedback rules. Used by writes, undo/redo + // and hints. + applyCell(r, c, v, { anim = false, countMistake = false } = {}) { + const from = this.grid[r][c]; + this.grid[r][c] = v; + this.renderCellText(r, c); + const t = this.cellText[r][c]; + if (anim && t) { + if (v) { + playSoundEx(this, SFX.PENCIL_WRITE, { rate: 0.9 + Math.random() * 0.25, volume: 0.7 }); + t.setScale(1.35).setAlpha(0).setAngle(-8); + this.tweens.add({ targets: t, scale: 1, alpha: 1, angle: 0, duration: 220, ease: 'Back.easeOut' }); + } else if (from) { + playSoundEx(this, SFX.UI_PICK, { rate: 0.7, volume: 0.6 }); + this.smudge(r, c); } + } + + if (!v || this.givens[r][c]) { + this.cellState[r][c] = 0; + } else if (this.isChecking()) { + const ok = v === this.solution[r][c]; + this.cellState[r][c] = ok ? 1 : 2; + if (!ok && countMistake) this.mistakes++; } else { this.cellState[r][c] = 0; - this.drawCellBg(r, c, hovered); - - if (this.isAllFilled()) { - this.time.delayedCall(200, () => this.revealAll()); - } } + this.drawWash(this.regions[r][c]); + this.recomputeCageDone(true); + this.refreshSelector(); + this.refreshButtons(); + this.refreshStats(); - this.updateCompletedNums(); + if (isBoardComplete(this.grid, this.solution)) { + if (!this.isChecking()) this.revealAll(true); + this.winPending = true; // locks input until the ceremony + this.time.delayedCall(360, () => this.handleWin()); + } else if (!this.isChecking() && this.allFilled()) { + this.time.delayedCall(220, () => { if (!this.revealed && this.allFilled()) this.revealAll(false); }); + } + this.saveGame(); } - isEasyMode() { - return this.difficulty === 'easy'; - } - - isAllFilled() { - for (let r = 0; r < N; r++) - for (let c = 0; c < N; c++) - if (!this.givenCells[r][c] && this.grid[r][c] === 0) return false; + allFilled() { + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!this.grid[r][c]) return false; return true; } - revealAll() { + // Medium/Hard: the map is full, so check it. From here on entries are + // checked immediately. + revealAll(silent) { + if (this.gameEnded) return; this.revealed = true; - let allCorrect = true; - - for (let r = 0; r < N; r++) { + let wrong = 0; + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) { - if (this.givenCells[r][c]) continue; - const correct = this.grid[r][c] === this.solution[r][c]; - if (!correct) allCorrect = false; - this.cellState[r][c] = correct ? 1 : 2; - this.drawCellBg(r, c, false); + if (this.givens[r][c]) continue; + const ok = this.grid[r][c] === this.solution[r][c]; + this.cellState[r][c] = ok ? 1 : 2; + if (!ok) wrong++; + } + this.mistakes += wrong; + for (const id of this.meta.cages.keys()) this.drawWash(id); + this.recomputeCageDone(!silent); + this.refreshStats(); + this.ruleText?.setText('Map checked: every entry is now checked as you write.'); + if (wrong && !silent) { + playSoundEx(this, SFX.CLICK, { rate: 0.5 }); + this.toast(`${wrong} cell${wrong > 1 ? "s don't" : " doesn't"} fit. They're hatched in red.`, 3200); + } + this.saveGame(); + } + + smudge(r, c) { + const g = this.add.graphics().setDepth(D.hover); + g.fillStyle(0x8a8f96, 0.28); + g.fillEllipse(0, 0, 46, 26); + g.fillStyle(0x8a8f96, 0.16); + g.fillEllipse(8, 4, 40, 18); + g.setPosition(cellCX(c), cellCY(r) + 2).setAngle(-12); + this.tweens.add({ targets: g, alpha: 0, scaleX: 1.5, duration: 520, ease: 'Sine.easeOut', onComplete: () => g.destroy() }); + } + + // A cage is "surveyed" when it holds 1..N (and, when entries are being + // checked, every cell is right). Newly surveyed cages get the flourish. + recomputeCageDone(flourish) { + const checking = this.isChecking(); + for (const [id, o] of this.cageObjs) { + const full = cageStatus(this.grid, o.cells) === 'full'; + const done = full && (!checking || o.cells.every(({ r, c }) => this.grid[r][c] === this.solution[r][c])); + const was = this.cageDone.has(id); + if (done && !was) { + this.cageDone.add(id); + if (flourish) { + playSoundEx(this, SFX.UI_CHIME, { volume: 0.55, rate: 0.95 + o.slot * 0.02 }); + if (o.fill) this.tweens.add({ targets: o.fill, alpha: 1, duration: 420, ease: 'Sine.easeOut' }); + this.tweenSeismo(id, 1); + for (const { r, c } of o.cells) { + const t = this.cellText[r][c]; + if (t) this.tweens.add({ targets: t, scale: 1.18, duration: 140, yoyo: true, delay: 40 }); + } + } else { + o.fill?.setAlpha(1); + this.seismoAmp.set(id, 1); + } + } else if (!done && was) { + this.cageDone.delete(id); + if (o.fill) this.tweens.add({ targets: o.fill, alpha: 0.6, duration: 260 }); + this.tweenSeismo(id, 0); } } - - this.updateCompletedNums(); - - if (allCorrect) { - this.time.delayedCall(300, () => this.handleWin()); - } + this.drawSeismo(); } - clearCell(r, c) { - if (this.givenCells[r][c]) return; - this.grid[r][c] = 0; - this.cellTextObjs[r][c].setText(''); - this.cellState[r][c] = 0; - const hovered = this.hoveredCell?.r === r && this.hoveredCell?.c === c; - this.drawCellBg(r, c, hovered); - this.updateCompletedNums(); + tweenSeismo(id, to) { + const p = { a: this.seismoAmp.get(id) ?? 0 }; + this.tweens.add({ + targets: p, a: to, duration: to ? 700 : 300, ease: to ? 'Elastic.easeOut' : 'Sine.easeIn', + onUpdate: () => { this.seismoAmp.set(id, p.a); this.drawSeismo(); }, + }); } - drawCellBg(r, c, isHovered) { - const bg = this.cellBgObjs[r][c]; - if (!bg) return; - bg.clear(); - - const x = GRID_X + c * CELL + 1; - const y = GRID_Y + r * CELL + 1; - const sz = CELL - 2; - - const state = this.cellState[r][c]; - - if (state === 1) { - bg.fillStyle(0x3c8a4e, isHovered ? 0.30 : 0.20); - bg.fillRect(x, y, sz, sz); - } else if (state === 2) { - bg.fillStyle(0xb03a2e, isHovered ? 0.27 : 0.16); - bg.fillRect(x, y, sz, sz); - } else if (isHovered) { - bg.fillStyle(INK_N, 0.07); - bg.fillRect(x, y, sz, sz); - } + doUndo() { + if (this.blocked()) return; + const e = undoEdit(this.history); + if (!e) return; + this.moves++; + this.cursor = { r: e.r, c: e.c }; + this.applyCell(e.r, e.c, e.from, { anim: true }); + this.drawCursor(); } - // ── Hint ────────────────────────────────────────────────────────────────────── + doRedo() { + if (this.blocked()) return; + const e = redoEdit(this.history); + if (!e) return; + this.moves++; + this.cursor = { r: e.r, c: e.c }; + this.applyCell(e.r, e.c, e.to, { anim: true }); + this.drawCursor(); + } + + // ── Hints ────────────────────────────────────────────────────────────────── useHint() { - if (this.gameEnded) return; - if (isFinite(this.hintsLeft) && this.hintsLeft <= 0) return; - - const cell = getHintCell(this.grid); + if (this.blocked() || this.hintsLeft <= 0 || this.hintPending) return; + const cell = getHintCell(this.grid, this.solution, this.givens); if (!cell) return; - const { r, c } = cell; + this.hintPending = true; + this.timerOn = true; + if (Number.isFinite(this.hintsLeft)) this.hintsLeft--; + this.hintsUsed++; + this.moves++; + playSound(this, SFX.UI_ACTIVATE); - const bg = this.cellBgObjs[r][c]; - bg.clear(); - bg.fillStyle(0xd4a017, 0.5); - bg.fillRect(GRID_X + c * CELL + 1, GRID_Y + r * CELL + 1, CELL - 2, CELL - 2); + const glow = this.add.graphics().setDepth(D.cursor); + glow.fillStyle(0xd4a017, 0.45); + glow.fillRoundedRect(GRID_X + c * CELL + 5, GRID_Y + r * CELL + 5, CELL - 10, CELL - 10, 10); + this.tweens.add({ targets: glow, alpha: 0.2, duration: 220, yoyo: true, repeat: 1 }); + if (cell.fix) this.toast('That entry was wrong. The hint corrected it.', 2400); - this.time.delayedCall(550, () => { - this.grid[r][c] = this.solution[r][c]; - this.cellTextObjs[r][c].setText(String(this.solution[r][c])); - this.cellState[r][c] = 1; - this.drawCellBg(r, c, false); - this.updateCompletedNums(); - - if (isBoardComplete(this.grid, this.solution)) { - this.time.delayedCall(200, () => this.handleWin()); - } + this.time.delayedCall(520, () => { + glow.destroy(); + this.hintPending = false; + if (this.gameEnded || !this.sys.isActive()) return; + this.givens[r][c] = true; + this.hinted.add(`${r},${c}`); + pushMarker(this.history); + this.applyCell(r, c, this.solution[r][c], { anim: true }); }); + this.refreshButtons(); + this.refreshStats(); + } - if (isFinite(this.hintsLeft)) { - this.hintsLeft--; - this.hintsUsed++; - this.updateHintBtn(); + // ── Timer + pause ────────────────────────────────────────────────────────── + + update(_t, delta) { + if (this.mode !== 'play' || !this.timerOn || this.paused || this.gameEnded || this.modal) return; + if (typeof document !== 'undefined' && document.hidden) return; + this.elapsed += delta; + const sec = Math.floor(this.elapsed / 1000); + if (sec !== this._lastSecond) { + this._lastSecond = sec; + this.statTexts?.time.setText(formatTime(this.elapsed)); } } - // ── Win ─────────────────────────────────────────────────────────────────────── + setPaused(on) { + if (this.mode !== 'play' || this.gameEnded || this.paused === on) return; + this.paused = on; + playSound(this, SFX.UI_FLIP); + if (on) { + const x = GRID_X - 26, y = GRID_Y - 30, w = GRID_W + 52, h = GRID_W + 60; + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.18); g.fillRect(x + 6, y + 8, w, h); + g.fillStyle(0xf6efdc, 1); g.fillRect(x, y, w, h); + g.lineStyle(1, 0x8ab3d8, 0.35); + for (let ly = y + 40; ly < y + h; ly += 34) g.lineBetween(x + 10, ly, x + w - 10, ly); + g.lineStyle(1.5, 0xc0504a, 0.45); g.lineBetween(x + 70, y, x + 70, y + h); + g.lineStyle(2, INK_N, 0.3); g.strokeRect(x, y, w, h); + const t1 = this.add.text(LCX, GRID_Y + GRID_W / 2 - 40, 'Survey paused', { + fontFamily: 'YummyCupcakes', fontSize: '72px', color: TITLE_BLUE, + }).setOrigin(0.5); + const t2 = this.add.text(LCX, GRID_Y + GRID_W / 2 + 34, 'Tap the page or press P to carry on', { + fontFamily: 'YummyCupcakes', fontSize: '32px', color: PENCIL, + }).setOrigin(0.5); + const cont = this.add.container(0, 0, [g, t1, t2]).setDepth(D.flap); + const zone = this.add.zone(x + w / 2, y + h / 2, w, h).setDepth(D.flap + 1).setInteractive({ useHandCursor: true }); + zone.on('pointerup', () => this.setPaused(false)); + cont.y = -40; cont.alpha = 0; + this.tweens.add({ targets: cont, y: 0, alpha: 1, duration: 260, ease: 'Cubic.easeOut' }); + this.flap = { cont, zone }; + this.drawHover(); + this.saveGame(); + } else if (this.flap) { + const { cont, zone } = this.flap; + this.flap = null; + zone.destroy(); + this.tweens.add({ targets: cont, y: -40, alpha: 0, duration: 200, onComplete: () => cont.destroy() }); + } + this.refreshButtons(); + } + + // ── New survey / save ────────────────────────────────────────────────────── + + newSurvey() { + if (this.modal) return; + const go = () => this.daily ? this.restartWith({ start: true }) : this.restartWith({ difficulty: this.difficulty }); + if (this.mode === 'play' && !this.gameEnded && this.moves > 0) { + this.confirm('Abandon this survey?', 'Your progress on this plate map will be lost.', 'Abandon it', () => { + recordGame('tectonic', { won: false, time: Math.round(this.elapsed), moves: this.moves, mode: this.statsMode() }); + storage()?.removeItem(SAVE_KEY); + this.moves = 0; // nothing left to save on shutdown + go(); + }); + return; + } + if (!this.gameEnded) storage()?.removeItem(SAVE_KEY); + go(); + } + + statsMode() { return this.daily ? 'daily' : this.difficulty; } + + saveGame() { + if (this.mode !== 'play' || this.gameEnded || this.moves <= 0 || !this.grid) return; + try { + storage()?.setItem(SAVE_KEY, serialiseSave({ + difficulty: this.difficulty, daily: this.daily, + grid: this.grid, solution: this.solution, regions: this.regions, givens: this.givens, + cellState: this.cellState, history: this.history, elapsed: this.elapsed, + hintsLeft: this.hintsLeft, hintsUsed: this.hintsUsed, mistakes: this.mistakes, + revealed: this.revealed, moves: this.moves, surveyNo: this.surveyNo, + hinted: [...this.hinted], + })); + } catch { /* storage full or unavailable */ } + } + + // ── Win ──────────────────────────────────────────────────────────────────── handleWin() { if (this.gameEnded) return; this.gameEnded = true; - this.recordResult(); - this.showWin(); - } + this.timerOn = false; + this.cursor = null; this.armed = null; + this.drawCursor(); this.drawHover(); this.refreshSelector(); this.refreshButtons(); + storage()?.removeItem(SAVE_KEY); - showWin() { - const cx = CX, cy = CY; - - this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.42) - .setDepth(DEPTH.overlay); - - const panel = this.add.graphics().setDepth(DEPTH.overlay + 1); - panel.postFX.addShadow(0, 6, 0.02, 1.2, 0x000000, 10, 0.55); - panel.fillStyle(PAPER, 1); - panel.fillRoundedRect(cx - 460, cy - 230, 920, 460, 18); - panel.lineStyle(3, PAPER_EDGE, 1); - panel.strokeRoundedRect(cx - 460, cy - 230, 920, 460, 18); - - this.add.text(cx, cy - 130, 'Puzzle Solved!', { - fontFamily: 'YummyCupcakes', fontSize: '88px', color: '#3c8a4e', - }).setOrigin(0.5).setDepth(DEPTH.overlay + 2); - - const diffLabel = DIFF_LABELS[this.difficulty] ?? this.difficulty; - const score = this.calcScore(); - - this.add.text(cx, cy - 26, `${diffLabel} · ${score} pts`, { - fontFamily: 'YummyCupcakes', fontSize: '44px', color: TITLE_BLUE, - }).setOrigin(0.5).setDepth(DEPTH.overlay + 2); - - if (this.hintsUsed > 0) { - this.add.text(cx, cy + 28, `${this.hintsUsed} hint${this.hintsUsed > 1 ? 's' : ''} used`, { - fontFamily: 'YummyCupcakes', fontSize: '32px', color: FADED, - }).setOrigin(0.5).setDepth(DEPTH.overlay + 2); + const time = Math.round(this.elapsed); + const { stats, newBest } = recordGame('tectonic', { + won: true, time, moves: this.moves, mode: this.statsMode(), + extra: { hints: this.hintsUsed, mistakes: this.mistakes }, + }); + let daily = null; + if (this.daily) { + const res = updateDaily(readJSON(DAILY_KEY), this.daily, todayString(), time); + writeJSON(DAILY_KEY, res.rec); + daily = res; } + const score = calcScore(this.difficulty, this.hintsUsed); + api.post('/history/single-player', { slug: 'tectonic', score, opponentScores: [], result: 'win' }).catch(() => {}); - new Button(this, cx - 175, cy + 130, 'New puzzle', - () => this.scene.restart(this._initData), - { width: 280, height: 58, fontSize: 26 }).setDepth(DEPTH.overlay + 3); - - new Button(this, cx + 175, cy + 130, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 280, height: 58, fontSize: 26 }).setDepth(DEPTH.overlay + 3); + this.plateShift(); + this.time.delayedCall(1700, () => this.showCertificate({ time, score, stats, newBest, daily })); } - calcScore() { - const base = DIFFICULTY_SCORES[this.difficulty] ?? 10; - const hintPenalty = this.difficulty === 'medium' ? this.hintsUsed * 4 : 0; - return Math.max(0, base - hintPenalty); - } - - async recordResult() { - try { - await api.post('/history/single-player', { - slug: 'tectonic', score: this.calcScore(), opponentScores: [], result: 'win', + // Cages lift and settle in a ripple from left to right, with a rumble. + plateShift() { + playSoundEx(this, SFX.DICE_ROLL, { rate: 0.45, volume: 0.5 }); + for (const o of this.cageObjs.values()) { + const delay = o.slot * 60; + const dx = (o.slot % 2 ? 1 : -1) * (2 + (o.slot % 3)); + this.tweens.add({ + targets: o.cont, y: -12, x: dx, duration: 200, delay, ease: 'Sine.easeOut', + onComplete: () => this.tweens.add({ targets: o.cont, y: 0, x: 0, duration: 460, ease: 'Bounce.easeOut' }), }); - } catch { /* best effort */ } + if (o.fill) this.tweens.add({ targets: o.fill, alpha: 1, duration: 300, delay }); + } + const p = { b: 0 }; + this.tweens.add({ + targets: p, b: 1, duration: 500, delay: 200, yoyo: true, hold: 300, ease: 'Sine.easeInOut', + onUpdate: () => { this.seismoBurst = p.b; this.drawSeismo(); }, + }); + } + + showCertificate({ time, score, stats, newBest, daily }) { + if (!this.sys.isActive()) return; + playSound(this, SFX.VICTORY_SHORT); + const objs = []; + const dim = this.add.rectangle(W / 2, H / 2, W, H, 0x0a0602, 0.5).setDepth(D.cert).setInteractive(); + dim.alpha = 0; + this.tweens.add({ targets: dim, alpha: 1, duration: 300 }); + objs.push(dim); + + const cont = this.add.container(W / 2, H / 2).setDepth(D.cert + 1); + const cert = this.add.image(0, 0, 'tectonic-cert'); + const oy = -cert.height / 2; // texture top + const txt = (x, y, s, size, color, font = 'YummyCupcakes') => + this.add.text(x, y, s, { fontFamily: font, fontSize: `${size}px`, color, align: 'center' }).setOrigin(0.5); + const site = this.daily ? `Daily Survey of ${this.daily}` : `${DIFF_LABELS[this.difficulty]} site`; + const kids = [ + cert, + txt(0, oy + 112, 'Certificate of Survey', 72, '#4a3420'), + txt(0, oy + 278, `This certifies that plate map No. ${this.surveyNo}`, 32, '#5a4630'), + txt(0, oy + 318, `(${site}) was surveyed in full.`, 32, '#5a4630'), + ]; + [['Time', formatTime(time)], ['Mistakes', String(this.mistakes)], ['Hints', String(this.hintsUsed)], ['Score', `${score} pts`]] + .forEach(([label, value], i) => { + const x = -330 + i * 220; + kids.push(txt(x, oy + 390, label, 24, '#7a6450')); + kids.push(txt(x, oy + 432, value, 44, '#2f3b4a')); + }); + let note; + if (daily) note = `Daily streak: ${daily.streak} day${daily.streak === 1 ? '' : 's'}${daily.newBestTime ? ' · new best for today!' : ''}`; + else if (newBest.time) note = 'A new best time for this site!'; + else if (stats.won === 1) note = 'Your first survey at this site.'; + else note = `Best ${formatTime(stats.bestTime)} · Streak ${stats.streak}${newBest.streak ? ' (a new record!)' : ''}`; + kids.push(txt(0, oy + 498, note, 30, newBest.time || daily?.newBestTime ? '#a0402f' : '#5a4630')); + cont.add(kids); + cont.y = H + 400; cont.angle = -4; + this.tweens.add({ targets: cont, y: H / 2 - 30, angle: -1, duration: 520, ease: 'Back.easeOut' }); + objs.push(cont); + + // stamp + this.time.delayedCall(700, () => { + if (!this.sys.isActive()) return; + const stamp = this.add.container(W / 2 + 320, H / 2 - 170).setDepth(D.cert + 3); + const sg = this.add.graphics(); + sg.lineStyle(5, 0xb3352a, 0.85); sg.strokeRoundedRect(-150, -42, 300, 84, 12); + sg.lineStyle(2, 0xb3352a, 0.6); sg.strokeRoundedRect(-140, -33, 280, 66, 9); + const st = this.add.text(0, 2, 'SURVEYED', { fontFamily: 'Righteous', fontSize: '50px', color: '#b3352a' }).setOrigin(0.5).setAlpha(0.9); + stamp.add([sg, st]); + stamp.setAngle(-14).setScale(2.4).setAlpha(0); + this.tweens.add({ + targets: stamp, scale: 1, alpha: 0.88, duration: 220, ease: 'Quad.easeIn', + onComplete: () => { playSound(this, SFX.KART_THUMP); this.cameras.main.shake(120, 0.003); }, + }); + objs.push(stamp); + }); + + const by = H / 2 - 30 + 250; + this.time.delayedCall(560, () => { + if (!this.sys.isActive()) return; + const again = this.daily + ? new PaperButton(this, W / 2 - 150, by, 'Back to sites', () => this.restartWith({ start: true }), { width: 250, accent: true }) + : new PaperButton(this, W / 2 - 150, by, 'New survey', () => this.restartWith({ difficulty: this.difficulty }), { width: 250, accent: true }); + const lv = new PaperButton(this, W / 2 + 150, by, 'Leave', () => this.scene.start('GameMenu'), { width: 250 }); + again.setDepth(D.cert + 2); lv.setDepth(D.cert + 2); + }); + } + + // ── Modals + toast ───────────────────────────────────────────────────────── + + openModal(build) { + if (this.modal) return null; + const objs = []; + const dim = this.add.rectangle(W / 2, H / 2, W, H, 0x0a0602, 0.55).setDepth(D.modal).setInteractive(); + objs.push(dim); + const modal = { objs, close: () => { + for (const o of objs) o.destroy(); + if (this.modal === modal) this.modal = null; + } }; + this.modal = modal; + build(objs, modal); + return modal; + } + + confirm(title, body, yesLabel, onYes) { + this.openModal((objs, modal) => { + const g = this.add.graphics().setDepth(D.modal + 1); + const x = W / 2 - 380, y = H / 2 - 170; + g.fillStyle(0x000000, 0.25); g.fillRect(x + 8, y + 10, 760, 340); + g.fillStyle(0xfbf8ee, 1); g.fillRect(x, y, 760, 340); + g.lineStyle(1, 0x8ab3d8, 0.35); + for (let ly = y + 60; ly < y + 340; ly += 32) g.lineBetween(x + 14, ly, x + 746, ly); + g.lineStyle(2, INK_N, 0.45); g.strokeRect(x, y, 760, 340); + objs.push(g); + objs.push(this.add.text(W / 2, y + 74, title, { + fontFamily: 'YummyCupcakes', fontSize: '54px', color: INK, + }).setOrigin(0.5).setDepth(D.modal + 2)); + objs.push(this.add.text(W / 2, y + 150, body, { + fontFamily: 'YummyCupcakes', fontSize: '30px', color: PENCIL, align: 'center', wordWrap: { width: 660 }, + }).setOrigin(0.5).setDepth(D.modal + 2)); + objs.push(new PaperButton(this, W / 2 - 150, y + 260, yesLabel, () => { modal.close(); onYes(); }, { width: 250, accent: true }).setDepth(D.modal + 2)); + objs.push(new PaperButton(this, W / 2 + 150, y + 260, 'Keep going', () => modal.close(), { width: 250 }).setDepth(D.modal + 2)); + }); + } + + openGuide() { + if (this.modal) return; + playSound(this, SFX.UI_FLIP); + this.openModal((objs, modal) => { + const add = (o) => { objs.push(o.setDepth?.(D.modal + 2) ?? o); return o; }; + const x = W / 2 - 560, y = H / 2 - 370, w = 1120, h = 740; + const g = this.add.graphics().setDepth(D.modal + 1); + g.fillStyle(0x000000, 0.28); g.fillRect(x + 10, y + 12, w, h); + g.fillStyle(0xfbf8ee, 1); g.fillRect(x, y, w, h); + g.lineStyle(1, 0x8ab3d8, 0.28); + for (let gx = x + 28; gx < x + w; gx += 28) g.lineBetween(gx, y, gx, y + h); + for (let gy = y + 28; gy < y + h; gy += 28) g.lineBetween(x, gy, x + w, gy); + g.lineStyle(2, INK_N, 0.45); g.strokeRect(x, y, w, h); + objs.push(g); + add(this.add.text(W / 2, y + 66, 'Field Guide', { fontFamily: 'YummyCupcakes', fontSize: '72px', color: TITLE_BLUE }).setOrigin(0.5)); + + const cell = 64; + const ig = this.add.graphics().setDepth(D.modal + 2); + objs.push(ig); + const plate = (cells, ox, oy, toneIdx) => { + const tone = Phaser.Display.Color.HexStringToColor(TONES[toneIdx].fill).color; + ig.fillStyle(tone, 0.35); + for (const { r, c } of cells) ig.fillRect(ox + c * cell, oy + r * cell, cell, cell); + ig.lineStyle(3, INK_N, 0.9); + const loop = insetLoop(traceCage(cells), 3 / cell); + ig.strokePoints(loop.map(([lx, ly]) => ({ x: ox + lx * cell, y: oy + ly * cell })), true, true); + add(this.add.text(ox + cells[0].c * cell + 8, oy + cells[0].r * cell + 6, String(cells.length), { + fontFamily: 'Righteous', fontSize: '15px', color: PENCIL, + })); + }; + const num = (ox, oy, r, c, v, given = true, color = null) => add(this.add.text(ox + c * cell + cell / 2, oy + r * cell + cell / 2 + 1, String(v), { + fontFamily: given ? 'Righteous' : 'YummyCupcakes', fontSize: given ? '36px' : '44px', color: color ?? (given ? INK : BLUE_INK), + }).setOrigin(0.5)); + + // fig. 1: plates hold 1..N + const ax = x + 120, ay = y + 170; + plate([{ r: 0, c: 0 }, { r: 1, c: 0 }, { r: 2, c: 0 }, { r: 2, c: 1 }], ax, ay, 0); + [[0, 0, 2], [1, 0, 4], [2, 0, 1], [2, 1, 3]].forEach(([r, c, v]) => num(ax, ay, r, c, v, false)); + plate([{ r: 0, c: 3 }, { r: 1, c: 3 }], ax, ay, 1); + num(ax, ay, 0, 3, 1, false); num(ax, ay, 1, 3, 2, false); + plate([{ r: 2, c: 4 }], ax, ay, 2); + num(ax, ay, 2, 4, 1, false); + add(this.add.text(x + 290, y + 400, 'fig. 1: a plate of N cells holds\neach number from 1 to N exactly once.', { + fontFamily: 'YummyCupcakes', fontSize: '28px', color: INK, align: 'center', lineSpacing: 4, + }).setOrigin(0.5, 0)); + + // fig. 2: touching twins + const bx = x + 700, by = y + 170; + ig.fillStyle(RED_PENCIL, 0.10); + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) if (r !== 1 || c !== 1) ig.fillRect(bx + c * cell, by + r * cell, cell, cell); + ig.lineStyle(1.5, 0x6f9fca, 0.7); + for (let i = 0; i <= 3; i++) { + ig.lineBetween(bx + i * cell, by, bx + i * cell, by + 3 * cell); + ig.lineBetween(bx, by + i * cell, bx + 3 * cell, by + i * cell); + } + num(bx, by, 1, 1, 3); + num(bx, by, 0, 2, 3, false); + num(bx, by, 2, 0, 2, false); + ig.lineStyle(4, RED_PENCIL, 0.9); + ig.lineBetween(bx + 2 * cell + 14, by + 14, bx + 3 * cell - 14, by + cell - 14); + ig.lineBetween(bx + 3 * cell - 14, by + 14, bx + 2 * cell + 14, by + cell - 14); + add(this.add.text(bx + 1.5 * cell, y + 400, 'fig. 2: touching cells never match,\nnot even corner to corner.', { + fontFamily: 'YummyCupcakes', fontSize: '28px', color: INK, align: 'center', lineSpacing: 4, + }).setOrigin(0.5, 0)); + + add(this.add.text(W / 2, y + 540, + 'Pick a specimen tag, then tap cells, or tap a cell, then a tag (or type 1–5).\n' + + 'Arrows move · Backspace erases · Ctrl+Z / Ctrl+Y undo and redo · H hint · P pause\n' + + 'Your survey saves itself. Leave any time and resume it from the start page.', { + fontFamily: 'YummyCupcakes', fontSize: '27px', color: PENCIL, align: 'center', lineSpacing: 8, + }).setOrigin(0.5)); + const closeModal = modal.close; + modal.close = () => { storage()?.setItem(GUIDE_SEEN_KEY, '1'); closeModal(); }; + add(new PaperButton(this, W / 2, y + h - 66, 'Got it', () => modal.close(), { width: 230, accent: true })); + }); + } + + toast(text, ms = 2600) { + if (this.toastObj) { this.tweens.killTweensOf(this.toastObj); this.toastObj.destroy(); } + const cont = this.add.container(RCX, 836).setDepth(D.toast); + const t = this.add.text(0, 0, text, { + fontFamily: 'YummyCupcakes', fontSize: '28px', color: '#3d3420', align: 'center', wordWrap: { width: 500 }, + }).setOrigin(0.5); + const w = Math.max(360, t.width + 60), h = t.height + 46; + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.2); g.fillRect(-w / 2 + 5, -h / 2 + 6, w, h); + g.fillStyle(0xf7e58a, 1); g.fillRect(-w / 2, -h / 2, w, h); + g.fillStyle(0xe9d16a, 1); g.fillRect(-w / 2, -h / 2, w, 14); + cont.add([g, t]); + cont.setAngle(-1.5).setAlpha(0).setScale(0.9); + this.toastObj = cont; + this.tweens.add({ targets: cont, alpha: 1, scale: 1, duration: 180, ease: 'Back.easeOut' }); + this.tweens.add({ + targets: cont, alpha: 0, delay: ms, duration: 400, + onComplete: () => { if (this.toastObj === cont) this.toastObj = null; cont.destroy(); }, + }); } } diff --git a/src/games/tectonic/TectonicLogic.js b/src/games/tectonic/TectonicLogic.js index 6d6aefb..7e23b65 100644 --- a/src/games/tectonic/TectonicLogic.js +++ b/src/games/tectonic/TectonicLogic.js @@ -1,3 +1,18 @@ +// Tectonic — pure helpers (no Phaser). Shared by the scene and tools/verifyTectonic.js. +// +// rules/score HINT_LIMITS, DIFFICULTY_SCORES, calcScore, isBoardComplete +// hints getHintCell(grid, solution, givens) — fixes a wrong entry first +// cages cageMeta, cageStatus, cageAdjacency, colourCages, traceCage, insetLoop +// history makeHistory, pushEdit, pushMarker, undoEdit, redoEdit +// save serialiseSave, parseSave +// daily dailySeed, prevDate, updateDaily, dailyStreakNow +// +// Grids are 8×8 arrays of ints; `givens` is an 8×8 array of booleans. + +import { dateSeed, localDateString } from '../dotlink/DotLinkLogic.js'; + +export const N = 8; + export const HINT_LIMITS = { easy: Infinity, medium: 5, @@ -10,6 +25,14 @@ export const DIFFICULTY_SCORES = { hard: 90, }; +export const DIFF_LABELS = { easy: 'Easy', medium: 'Medium', hard: 'Hard' }; + +export function calcScore(difficulty, hintsUsed) { + const base = DIFFICULTY_SCORES[difficulty] ?? 10; + const hintPenalty = difficulty === 'medium' ? hintsUsed * 4 : 0; + return Math.max(0, base - hintPenalty); +} + export function isBoardComplete(grid, solution) { for (let r = 0; r < grid.length; r++) for (let c = 0; c < grid[r].length; c++) @@ -17,12 +40,286 @@ export function isBoardComplete(grid, solution) { return true; } -// Returns a random empty cell that still needs filling, or null. -export function getHintCell(grid) { - const empties = []; +// The cell a hint should fix: a wrong player entry first (so a full board with +// mistakes still gets help), otherwise a random empty cell. null when solved. +export function getHintCell(grid, solution, givens = null, rng = Math.random) { + const wrong = [], empties = []; for (let r = 0; r < grid.length; r++) - for (let c = 0; c < grid[r].length; c++) - if (grid[r][c] === 0) empties.push({ r, c }); - if (empties.length === 0) return null; - return empties[Math.floor(Math.random() * empties.length)]; + for (let c = 0; c < grid[r].length; c++) { + if (givens?.[r]?.[c]) continue; + const v = grid[r][c]; + if (v === 0) empties.push({ r, c }); + else if (v !== solution[r][c]) wrong.push({ r, c }); + } + const pool = wrong.length ? wrong : empties; + if (!pool.length) return null; + return { ...pool[Math.floor(rng() * pool.length)], fix: wrong.length > 0 }; +} + +// ── Cages ───────────────────────────────────────────────────────────────────── + +// { cages: Map id → [{r,c}…] (row-major order), sizeAt: 8×8, neededFor: [0..5] } +// neededFor[v] = how many cages hold the value v (cages of size ≥ v). +export function cageMeta(regions) { + const cages = new Map(); + for (let r = 0; r < regions.length; r++) + for (let c = 0; c < regions[r].length; c++) { + const id = regions[r][c]; + if (!cages.has(id)) cages.set(id, []); + cages.get(id).push({ r, c }); + } + const sizeAt = regions.map(row => row.map(id => cages.get(id).length)); + const neededFor = [0, 0, 0, 0, 0, 0]; + for (const cells of cages.values()) + for (let v = 1; v <= Math.min(5, cells.length); v++) neededFor[v]++; + return { cages, sizeAt, neededFor }; +} + +// 'empty' | 'partial' | 'full' (holds exactly 1..N) | 'broken' (full, but not 1..N) +export function cageStatus(grid, cells) { + let filled = 0; + const seen = new Set(); + for (const { r, c } of cells) { + const v = grid[r][c]; + if (v) { filled++; seen.add(v); } + } + if (filled === 0) return 'empty'; + if (filled < cells.length) return 'partial'; + for (let v = 1; v <= cells.length; v++) if (!seen.has(v)) return 'broken'; + return 'full'; +} + +// { ortho: Map id → Set(id), diag: Map id → Set(id) } — cages sharing an edge, +// and cages that only touch at a corner. +export function cageAdjacency(regions) { + const ortho = new Map(), diag = new Map(); + const add = (m, a, b) => { + if (!m.has(a)) m.set(a, new Set()); + if (!m.has(b)) m.set(b, new Set()); + m.get(a).add(b); m.get(b).add(a); + }; + const R = regions.length, C = regions[0].length; + for (let r = 0; r < R; r++) + for (let c = 0; c < C; c++) { + const id = regions[r][c]; + if (!ortho.has(id)) ortho.set(id, new Set()); + if (!diag.has(id)) diag.set(id, new Set()); + for (const [dr, dc, m] of [[0, 1, ortho], [1, 0, ortho], [1, 1, diag], [1, -1, diag]]) { + const nr = r + dr, nc = c + dc; + if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue; + const o = regions[nr][nc]; + if (o !== id) add(m, id, o); + } + } + for (const [id, set] of diag) for (const o of ortho.get(id)) set.delete(o); + return { ortho, diag }; +} + +// DSATUR colouring: cages sharing an edge never share a colour; cages that only +// touch at a corner avoid it when possible. Returns Map id → colour index. +export function colourCages(regions, nColours = 6) { + const { ortho, diag } = cageAdjacency(regions); + const ids = [...ortho.keys()]; + const colour = new Map(); + while (colour.size < ids.length) { + let pick = null, bestSat = -1, bestDeg = -1; + for (const id of ids) { + if (colour.has(id)) continue; + const sat = new Set([...ortho.get(id)].filter(o => colour.has(o)).map(o => colour.get(o))).size; + const deg = ortho.get(id).size; + if (sat > bestSat || (sat === bestSat && deg > bestDeg) || (sat === bestSat && deg === bestDeg && id < pick)) { + pick = id; bestSat = sat; bestDeg = deg; + } + } + const hard = new Set([...ortho.get(pick)].filter(o => colour.has(o)).map(o => colour.get(o))); + const soft = new Set([...diag.get(pick)].filter(o => colour.has(o)).map(o => colour.get(o))); + let chosen = -1; + for (let k = 0; k < nColours && chosen < 0; k++) if (!hard.has(k) && !soft.has(k)) chosen = k; + for (let k = 0; k < nColours && chosen < 0; k++) if (!hard.has(k)) chosen = k; + if (chosen < 0) chosen = (pick % nColours + nColours) % nColours; // >nColours-chromatic: can't happen on a planar map with 6 + colour.set(pick, chosen); + } + return colour; +} + +// Trace a cage's outline as a closed loop of grid-corner vertices [x, y] +// (x = column, y = row), clockwise on screen, collinear points removed. +// Cages of ≤5 cells can't enclose a hole, so there is exactly one loop. +export function traceCage(cells) { + const key = (r, c) => `${r},${c}`; + const inCage = new Set(cells.map(({ r, c }) => key(r, c))); + const out = new Map(); // "x,y" → [x2, y2] + for (const { r, c } of cells) { + if (!inCage.has(key(r - 1, c))) out.set(`${c},${r}`, [c + 1, r]); // top → + if (!inCage.has(key(r, c + 1))) out.set(`${c + 1},${r}`, [c + 1, r + 1]); // right ↓ + if (!inCage.has(key(r + 1, c))) out.set(`${c + 1},${r + 1}`, [c, r + 1]); // bottom ← + if (!inCage.has(key(r, c - 1))) out.set(`${c},${r + 1}`, [c, r]); // left ↑ + } + if (!out.size) return []; + const startKey = out.keys().next().value; + const loop = []; + let k = startKey, guard = 0; + do { + const [x, y] = k.split(',').map(Number); + loop.push([x, y]); + const nxt = out.get(k); + if (!nxt) return null; // open path — malformed cage + k = `${nxt[0]},${nxt[1]}`; + if (++guard > 400) return null; + } while (k !== startKey); + if (loop.length !== out.size) return null; // more than one loop + // drop collinear vertices + const n = loop.length; + return loop.filter((p, i) => { + const a = loop[(i + n - 1) % n], b = loop[(i + 1) % n]; + return !((a[0] === p[0] && p[0] === b[0]) || (a[1] === p[1] && p[1] === b[1])); + }); +} + +// Offset a clockwise (screen) rectilinear loop inward by d (in the loop's units). +// For a clockwise loop on screen (y down) the interior lies to the right of +// each edge, i.e. inward normal of (dx, dy) is (-dy, dx). +export function insetLoop(loop, d) { + const n = loop.length; + return loop.map((p, i) => { + const a = loop[(i + n - 1) % n], b = loop[(i + 1) % n]; + const e1 = [Math.sign(p[0] - a[0]), Math.sign(p[1] - a[1])]; + const e2 = [Math.sign(b[0] - p[0]), Math.sign(b[1] - p[1])]; + const n1 = [-e1[1], e1[0]], n2 = [-e2[1], e2[0]]; + return [p[0] + d * (n1[0] + n2[0]), p[1] + d * (n1[1] + n2[1])]; + }); +} + +// ── Undo / redo ─────────────────────────────────────────────────────────────── +// Entries are { r, c, from, to } edits or { marker: 'hint' } barriers: undo +// never steps back past a hint. + +export function makeHistory() { return { undo: [], redo: [] }; } + +export function pushEdit(h, edit) { + h.undo.push({ r: edit.r, c: edit.c, from: edit.from, to: edit.to }); + h.redo.length = 0; + if (h.undo.length > 500) h.undo.splice(0, h.undo.length - 500); +} + +export function pushMarker(h) { + h.undo.push({ marker: 'hint' }); + h.redo.length = 0; +} + +export function canUndo(h) { return h.undo.length > 0 && !h.undo[h.undo.length - 1].marker; } +export function canRedo(h) { return h.redo.length > 0; } + +// Returns the edit to reverse (apply grid[r][c] = from), or null. +export function undoEdit(h) { + if (!canUndo(h)) return null; + const e = h.undo.pop(); + h.redo.push(e); + return e; +} + +// Returns the edit to re-apply (apply grid[r][c] = to), or null. +export function redoEdit(h) { + if (!h.redo.length) return null; + const e = h.redo.pop(); + h.undo.push(e); + return e; +} + +// ── Save / resume ───────────────────────────────────────────────────────────── + +export const SAVE_KEY = 'tectonic-save'; +const SAVE_VERSION = 1; + +export function serialiseSave(s) { + return JSON.stringify({ + v: SAVE_VERSION, + difficulty: s.difficulty, + daily: s.daily ?? null, + grid: s.grid, solution: s.solution, regions: s.regions, givens: s.givens, + cellState: s.cellState, + history: s.history, + elapsed: Math.round(s.elapsed ?? 0), + hintsLeft: Number.isFinite(s.hintsLeft) ? s.hintsLeft : null, + hintsUsed: s.hintsUsed ?? 0, + mistakes: s.mistakes ?? 0, + revealed: !!s.revealed, + moves: s.moves ?? 0, + surveyNo: s.surveyNo ?? 0, + hinted: Array.isArray(s.hinted) ? s.hinted : [], + savedAt: s.savedAt ?? Date.now(), + }); +} + +const isGrid = (g, ok) => Array.isArray(g) && g.length === N && + g.every(row => Array.isArray(row) && row.length === N && row.every(ok)); +const isDigit = (max) => (v) => Number.isInteger(v) && v >= 0 && v <= max; + +// 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) return null; + if (!['easy', 'medium', 'hard'].includes(s.difficulty)) return null; + if (!isGrid(s.grid, isDigit(5)) || !isGrid(s.solution, (v) => Number.isInteger(v) && v >= 1 && v <= 5)) return null; + if (!isGrid(s.regions, (v) => Number.isInteger(v) && v >= 0)) return null; + if (!isGrid(s.givens, (v) => typeof v === 'boolean')) return null; + if (!isGrid(s.cellState, isDigit(2))) return null; + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) + if (s.givens[r][c] && s.grid[r][c] !== s.solution[r][c]) return null; + const { sizeAt } = cageMeta(s.regions); + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) + if (s.solution[r][c] > sizeAt[r][c] || s.grid[r][c] > sizeAt[r][c]) return null; + if (isBoardComplete(s.grid, s.solution)) return null; // already solved: nothing to resume + const h = s.history; + if (!h || !Array.isArray(h.undo) || !Array.isArray(h.redo)) s.history = makeHistory(); + s.hintsLeft = s.hintsLeft == null ? Infinity : s.hintsLeft; + s.hinted = Array.isArray(s.hinted) ? s.hinted.filter(k => typeof k === 'string' && /^[0-7],[0-7]$/.test(k)) : []; + if (s.daily != null && !/^\d{4}-\d{2}-\d{2}$/.test(s.daily)) s.daily = null; + return s; +} + +// ── Daily Survey ────────────────────────────────────────────────────────────── + +export const DAILY_KEY = 'tectonic-daily'; +export const DAILY_DIFFICULTY = 'medium'; + +export function todayString(d = new Date()) { return localDateString(d); } + +export function dailySeed(date) { return dateSeed(`tectonic:${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 Survey solve for `date` (the puzzle's date) on `today`. Only a +// same-day solve moves the streak; re-solving keeps the faster time. +// Returns { rec, newBestTime, streak }. +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); + } + // keep the last 60 solves + 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; } diff --git a/src/words/tectonicEngine.js b/src/words/tectonicEngine.js index f1ae71a..d65fc2c 100644 --- a/src/words/tectonicEngine.js +++ b/src/words/tectonicEngine.js @@ -6,7 +6,7 @@ // • No two cells that touch orthogonally OR diagonally (king-move / 8-way) // may hold the same number. // -// generatePuzzle(difficulty) → { grid, solution, regions, difficulty } +// generatePuzzle(difficulty, { seed? }) → { grid, solution, regions, difficulty } // grid : 8×8, 0 = empty cell the player must fill // solution : 8×8 fully-solved board // regions : 8×8 of integer region IDs (which cage each cell belongs to) @@ -32,9 +32,25 @@ const KING = [ [1, -1], [1, 0], [1, 1], ]; +// The generator's only randomness. generatePuzzle swaps in a seeded RNG for the +// duration of a seeded call (the Daily Survey) and restores it afterwards. +let rand = Math.random; + +// mulberry32, the same as DotLinkLogic.makeRng (kept local so the engine stays +// dependency-free). +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; + }; +} + function shuffle(arr) { for (let i = arr.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); + const j = Math.floor(rand() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; @@ -293,25 +309,36 @@ function toGrid(flat) { return out; } -export function generatePuzzle(difficulty) { +// generatePuzzle(difficulty, { seed }) — with a numeric seed the result is +// fully deterministic (same seed → same board), so generation is bounded by an +// attempt count instead of the wall-clock deadline used for random boards. +export function generatePuzzle(difficulty, { seed = null } = {}) { const target = GIVENS[difficulty] ?? GIVENS.medium; - const deadline = Date.now() + 3000; + const seeded = seed != null && Number.isFinite(Number(seed)); + const prevRand = rand; + if (seeded) rand = makeRng(Number(seed)); + try { + const deadline = seeded ? Infinity : Date.now() + 3000; + const MAX_BUILDS = 60; - let best = null; - while (Date.now() < deadline) { - const built = buildSolved(deadline); - if (!built) break; - const { regions, tables, sol } = built; - const { given, givens } = dig(sol, tables, target); + let best = null; + for (let builds = 0; seeded ? builds < MAX_BUILDS : Date.now() < deadline; builds++) { + const built = buildSolved(deadline); + if (!built) break; + const { regions, tables, sol } = built; + const { given, givens } = dig(sol, tables, target); - if (givens <= target) { - return { grid: toGrid(given), solution: toGrid(sol), regions, difficulty }; - } - if (!best || givens < best.givens) { - best = { grid: toGrid(given), solution: toGrid(sol), regions, givens }; + if (givens <= target) { + return { grid: toGrid(given), solution: toGrid(sol), regions, difficulty }; + } + if (!best || givens < best.givens) { + best = { grid: toGrid(given), solution: toGrid(sol), regions, givens }; + } } + + if (!best) throw new Error('tectonic: failed to generate a board'); + return { grid: best.grid, solution: best.solution, regions: best.regions, difficulty }; + } finally { + rand = prevRand; } - - if (!best) throw new Error('tectonic: failed to generate a board'); - return { grid: best.grid, solution: best.solution, regions: best.regions, difficulty }; } diff --git a/src/words/wordRouter.js b/src/words/wordRouter.js index cb7f48e..0525970 100644 --- a/src/words/wordRouter.js +++ b/src/words/wordRouter.js @@ -521,11 +521,13 @@ router.get('/sudoku/start', (req, res) => { res.json(sudokuGenerate(difficulty)); }); -// GET /api/words/tectonic/start?difficulty=easy|medium|hard +// GET /api/words/tectonic/start?difficulty=easy|medium|hard[&seed=uint32] +// A seed makes the board deterministic (the Daily Survey). router.get('/tectonic/start', (req, res) => { const VALID = ['easy', 'medium', 'hard']; const difficulty = VALID.includes(req.query.difficulty) ? req.query.difficulty : 'medium'; - res.json(tectonicGenerate(difficulty)); + const seed = req.query.seed != null && /^\d+$/.test(String(req.query.seed)) ? Number(req.query.seed) : null; + res.json(tectonicGenerate(difficulty, { seed })); }); // ── Dispatch ────────────────────────────────────────────────────────────────── diff --git a/tools/verifyTectonic.js b/tools/verifyTectonic.js new file mode 100644 index 0000000..eb9e4b9 --- /dev/null +++ b/tools/verifyTectonic.js @@ -0,0 +1,539 @@ +#!/usr/bin/env node +// verifyTectonic.js — headless checks for the Field Geologist's Notebook +// Tectonic: the generator (valid, unique, on-target givens, seeded +// determinism), cage helpers (outline tracing, inset, map colouring), hints, +// undo/redo, save/resume validation, Daily Survey streaks, the notebook layout, +// and a stubbed-Phaser smoke run of the scene's play flow. +// Usage: node tools/verifyTectonic.js [--quick] + +import { generatePuzzle } from '../src/words/tectonicEngine.js'; +import { + N, calcScore, isBoardComplete, getHintCell, cageMeta, cageStatus, cageAdjacency, colourCages, + traceCage, insetLoop, makeHistory, pushEdit, pushMarker, canUndo, canRedo, undoEdit, redoEdit, + serialiseSave, parseSave, dailySeed, prevDate, updateDaily, dailyStreakNow, blankDaily, +} from '../src/games/tectonic/TectonicLogic.js'; +import { + W, H, BOOK, LEFT, RIGHT, LCX, RCX, CELL, GRID_W, GRID_X, GRID_Y, PITCH, TONES, TAG_W, TAG_H, CARD_W, CARD_H, CERT_W, CERT_H, +} from '../src/games/tectonic/TectonicArt.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 clone = (g) => g.map(r => [...r]); +const KING = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]; + +function validSolution(sol, regions) { + const { cages } = cageMeta(regions); + for (const cells of cages.values()) { + if (cells.length < 1 || cells.length > 5) return 'cage size'; + const vals = cells.map(({ r, c }) => sol[r][c]).sort(); + for (let i = 0; i < vals.length; i++) if (vals[i] !== i + 1) return 'cage values'; + } + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) + for (const [dr, dc] of KING) { + const nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < N && nc >= 0 && nc < N && sol[nr][nc] === sol[r][c]) return `twins at ${r},${c}`; + } + return null; +} + +// Independent solution counter (MRV backtracking, stops at `limit`). +function countSolutions(grid, regions, limit = 2) { + const g = clone(grid); + const { cages, sizeAt } = cageMeta(regions); + const mates = regions.map((row, r) => row.map((id, c) => cages.get(id).filter(p => p.r !== r || p.c !== c))); + const okAt = (r, c, v) => { + for (const [dr, dc] of KING) { + const nr = r + dr, nc = c + dc; + if (nr >= 0 && nr < N && nc >= 0 && nc < N && g[nr][nc] === v) return false; + } + for (const p of mates[r][c]) if (g[p.r][p.c] === v) return false; + return true; + }; + let count = 0, nodes = 0; + const rec = () => { + if (++nodes > 2e6) return; + let best = null, bestC = null; + for (let r = 0; r < N; r++) + for (let c = 0; c < N; c++) { + if (g[r][c]) continue; + const cands = []; + for (let v = 1; v <= sizeAt[r][c]; v++) if (okAt(r, c, v)) cands.push(v); + if (!best || cands.length < bestC.length) { best = { r, c }; bestC = cands; if (cands.length <= 1) break; } + } + if (!best) { count++; return; } + for (const v of bestC) { + g[best.r][best.c] = v; + rec(); + g[best.r][best.c] = 0; + if (count >= limit) return; + } + }; + rec(); + return nodes > 2e6 ? -1 : count; +} + +const TARGET = { easy: 30, medium: 24, hard: 18 }; +const puzzles = []; + +// ── Generator ──────────────────────────────────────────────────────────────── +section('Generator'); +{ + const per = QUICK ? 3 : 8; + for (const d of ['easy', 'medium', 'hard']) { + let worst = 0; + for (let i = 0; i < per; i++) { + const t0 = Date.now(); + const p = generatePuzzle(d); + worst = Math.max(worst, Date.now() - t0); + puzzles.push(p); + const bad = validSolution(p.solution, p.regions); + ok(`${d}#${i} solution valid`, !bad, bad); + let givens = 0, mismatch = 0; + for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (p.grid[r][c]) { givens++; if (p.grid[r][c] !== p.solution[r][c]) mismatch++; } + ok(`${d}#${i} givens agree with the solution`, mismatch === 0); + ok(`${d}#${i} hits the givens target`, givens === TARGET[d], `${givens}`); + const n = countSolutions(p.grid, p.regions); + ok(`${d}#${i} unique solution`, n === 1, `count=${n}`); + } + ok(`${d} generation under 1.5s`, worst < 1500, `${worst}ms`); + } +} + +section('Seeded generation'); +{ + for (const d of ['easy', 'medium', 'hard']) { + const a = generatePuzzle(d, { seed: 4242 }), b = generatePuzzle(d, { seed: 4242 }); + ok(`${d}: same seed → same board`, JSON.stringify(a) === JSON.stringify(b)); + const c = generatePuzzle(d, { seed: 4243 }); + ok(`${d}: different seed → different board`, JSON.stringify(a) !== JSON.stringify(c)); + ok(`${d}: seeded board valid + unique`, !validSolution(a.solution, a.regions) && countSolutions(a.grid, a.regions) === 1); + } + const r1 = generatePuzzle('medium'), r2 = generatePuzzle('medium'); + ok('unseeded boards still vary after seeded calls', JSON.stringify(r1) !== JSON.stringify(r2)); + ok('daily seeds differ by date', dailySeed('2026-11-26') !== dailySeed('2026-11-27')); + ok('daily seed is stable', dailySeed('2026-11-26') === dailySeed('2026-11-26')); + const da = generatePuzzle('medium', { seed: dailySeed('2026-11-26') }); + const db = generatePuzzle('medium', { seed: dailySeed('2026-11-27') }); + ok('consecutive daily boards differ', JSON.stringify(da.regions) !== JSON.stringify(db.regions)); +} + +// ── Cages ───────────────────────────────────────────────────────────────────── +section('Cage helpers'); +{ + let traced = 0, colouredOk = true, maxColour = 0, diagClash = 0, diagPairs = 0; + for (const p of puzzles) { + const { cages, sizeAt, neededFor } = cageMeta(p.regions); + const expectNeeded = [0, 0, 0, 0, 0, 0]; + for (const cells of cages.values()) for (let v = 1; v <= cells.length; v++) expectNeeded[v]++; + ok('neededFor matches cage sizes', JSON.stringify(neededFor) === JSON.stringify(expectNeeded)); + ok('sizeAt consistent', p.regions.every((row, r) => row.every((id, c) => sizeAt[r][c] === cages.get(id).length))); + + for (const cells of cages.values()) { + const loop = traceCage(cells); + if (!loop) { ok('cage traces to one closed loop', false); continue; } + traced++; + const axis = loop.every((pt, i) => { const q = loop[(i + 1) % loop.length]; return pt[0] === q[0] || pt[1] === q[1]; }); + ok('outline edges axis-aligned', axis); + ok('outline has ≥4 corners, even count', loop.length >= 4 && loop.length % 2 === 0, `${loop.length}`); + let area = 0; + for (let i = 0; i < loop.length; i++) { const a = loop[i], b = loop[(i + 1) % loop.length]; area += a[0] * b[1] - b[0] * a[1]; } + ok('outline area = cell count, clockwise on screen', area / 2 === cells.length, `${area / 2} vs ${cells.length}`); + const inner = insetLoop(loop, 0.06); + const inCells = (x, y) => cells.some(({ r, c }) => x > c && x < c + 1 && y > r && y < r + 1); + ok('inset outline stays inside the cage', inner.every(([x, y]) => inCells(x, y))); + } + const col = colourCages(p.regions, TONES.length); + const { ortho, diag } = cageAdjacency(p.regions); + for (const [id, set] of ortho) { + maxColour = Math.max(maxColour, col.get(id)); + for (const o of set) if (col.get(o) === col.get(id)) colouredOk = false; + } + for (const [id, set] of diag) for (const o of set) { diagPairs++; if (col.get(o) === col.get(id)) diagClash++; } + } + ok('every cage traced', traced > 0); + ok('edge-touching cages never share a tone', colouredOk); + ok(`tones fit the palette (max ${maxColour})`, maxColour < TONES.length); + ok('corner-touching cages mostly differ too', diagClash <= diagPairs * 0.1, `${diagClash}/${diagPairs}`); + + const L = [{ r: 0, c: 0 }, { r: 1, c: 0 }, { r: 1, c: 1 }]; + ok('L-tromino traces 6 corners', traceCage(L)?.length === 6); + ok('single cell traces 4 corners', traceCage([{ r: 3, c: 3 }])?.length === 4); + const g = [[1, 2, 0], [0, 0, 0]]; + ok('cageStatus partial', cageStatus(g, [{ r: 0, c: 0 }, { r: 0, c: 1 }, { r: 0, c: 2 }]) === 'partial'); + ok('cageStatus full', cageStatus([[2, 1]], [{ r: 0, c: 0 }, { r: 0, c: 1 }]) === 'full'); + ok('cageStatus broken', cageStatus([[2, 2]], [{ r: 0, c: 0 }, { r: 0, c: 1 }]) === 'broken'); + ok('cageStatus empty', cageStatus([[0, 0]], [{ r: 0, c: 0 }, { r: 0, c: 1 }]) === 'empty'); +} + +// ── Hints + scoring ─────────────────────────────────────────────────────────── +section('Hints'); +{ + const p = puzzles[0]; + const givens = p.grid.map(row => row.map(v => v !== 0)); + const g = clone(p.grid); + let empties = 0; + for (let i = 0; i < 50; i++) { + const h = getHintCell(g, p.solution, givens); + if (h && !givens[h.r][h.c] && g[h.r][h.c] === 0 && !h.fix) empties++; + } + ok('hint picks an empty, non-given cell', empties === 50); + // full board with one mistake: the old hint did nothing here + const full = clone(p.solution); + let wr = -1, wc = -1; + outer: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!givens[r][c]) { wr = r; wc = c; break outer; } + full[wr][wc] = full[wr][wc] === 1 ? 2 : 1; + const h = getHintCell(full, p.solution, givens); + ok('hint fixes a wrong entry on a full board', h && h.r === wr && h.c === wc && h.fix === true); + const part = clone(p.grid); + part[wr][wc] = p.solution[wr][wc] === 1 ? 2 : 1; + let fixFirst = true; + for (let i = 0; i < 20; i++) { const x = getHintCell(part, p.solution, givens); if (x.r !== wr || x.c !== wc) fixFirst = false; } + ok('wrong entries are fixed before empties are filled', fixFirst); + ok('no hint on a solved board', getHintCell(clone(p.solution), p.solution, givens) === null); + ok('isBoardComplete', isBoardComplete(p.solution, p.solution) && !isBoardComplete(p.grid, p.solution)); + ok('scores', calcScore('easy', 9) === 20 && calcScore('medium', 2) === 42 && calcScore('hard', 0) === 90 && calcScore('medium', 99) === 0); +} + +// ── Undo / redo ─────────────────────────────────────────────────────────────── +section('Undo / redo'); +{ + const h = makeHistory(); + const g = [[0, 0]]; + const apply = (e, dir) => { g[e.r][e.c] = dir === 'undo' ? e.from : e.to; }; + const edit = (c, to) => { const e = { r: 0, c, from: g[0][c], to }; pushEdit(h, e); g[0][c] = to; }; + edit(0, 1); edit(1, 2); edit(0, 3); + ok('three edits undoable', canUndo(h) && !canRedo(h)); + apply(undoEdit(h), 'undo'); + ok('undo restores the previous value', g[0][0] === 1); + apply(undoEdit(h), 'undo'); apply(undoEdit(h), 'undo'); + ok('undo all the way back', g[0][0] === 0 && g[0][1] === 0 && !canUndo(h)); + ok('nothing left to undo returns null', undoEdit(h) === null); + apply(redoEdit(h), 'redo'); apply(redoEdit(h), 'redo'); + ok('redo replays in order', g[0][0] === 1 && g[0][1] === 2 && canRedo(h)); + edit(1, 4); + ok('a new edit clears redo', !canRedo(h)); + pushMarker(h); + ok('a hint marker blocks undo', !canUndo(h) && undoEdit(h) === null); + edit(0, 2); + ok('edits after a hint are undoable…', canUndo(h)); + apply(undoEdit(h), 'undo'); + ok('…but only back to the hint', !canUndo(h) && g[0][0] === 1); + const big = makeHistory(); + for (let i = 0; i < 700; i++) pushEdit(big, { r: 0, c: 0, from: 0, to: 1 }); + ok('history capped at 500', big.undo.length === 500); + ok('history survives JSON', (() => { const j = JSON.parse(JSON.stringify(h)); return j.undo.length === h.undo.length && j.undo.at(-1).marker === 'hint' && j.redo.at(-1).r === 0; })()); +} + +// ── Save / resume ───────────────────────────────────────────────────────────── +section('Save / resume'); +{ + const p = puzzles[1]; + const givens = p.grid.map(row => row.map(v => v !== 0)); + const grid = clone(p.grid); + let er = -1, ec = -1; + outer: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!givens[r][c]) { er = r; ec = c; break outer; } + grid[er][ec] = p.solution[er][ec]; + const history = makeHistory(); pushEdit(history, { r: er, c: ec, from: 0, to: grid[er][ec] }); + const base = { + difficulty: 'medium', daily: '2026-11-26', grid, solution: p.solution, regions: p.regions, givens, + cellState: grid.map(row => row.map(() => 0)), history, elapsed: 61234.6, hintsLeft: 4, hintsUsed: 1, + mistakes: 2, revealed: false, moves: 7, surveyNo: 4321, hinted: ['0,0', 'bogus'], + }; + const s = parseSave(serialiseSave(base)); + ok('round-trips', s && s.difficulty === 'medium' && s.daily === '2026-11-26' && JSON.stringify(s.grid) === JSON.stringify(grid)); + ok('keeps clock, hints, mistakes, moves', s.elapsed === 61235 && s.hintsLeft === 4 && s.hintsUsed === 1 && s.mistakes === 2 && s.moves === 7); + ok('keeps history', s.history.undo.length === 1 && s.history.undo[0].to === grid[er][ec]); + ok('filters bad hinted keys', JSON.stringify(s.hinted) === '["0,0"]'); + ok('Infinity hints survive', parseSave(serialiseSave({ ...base, difficulty: 'easy', hintsLeft: Infinity })).hintsLeft === Infinity); + ok('zero hints stay zero', parseSave(serialiseSave({ ...base, difficulty: 'hard', hintsLeft: 0 })).hintsLeft === 0); + ok('missing → null', parseSave(null) === null && parseSave('') === null); + ok('garbage JSON → null', parseSave('{oops') === null); + ok('wrong version → null', parseSave(JSON.stringify({ ...JSON.parse(serialiseSave(base)), v: 99 })) === null); + ok('bad difficulty → null', parseSave(serialiseSave({ ...base, difficulty: 'insane' })) === null); + const tampered = clone(grid); + outer2: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (givens[r][c]) { tampered[r][c] = tampered[r][c] === 1 ? 2 : 1; break outer2; } + ok('tampered given → null', parseSave(serialiseSave({ ...base, grid: tampered })) === null); + const tooBig = clone(grid); + const { sizeAt } = cageMeta(p.regions); + outer3: for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!givens[r][c] && sizeAt[r][c] < 5) { tooBig[r][c] = 5; break outer3; } + ok('value above cage size → null', parseSave(serialiseSave({ ...base, grid: tooBig })) === null); + ok('short grid → null', parseSave(serialiseSave({ ...base, grid: grid.slice(1) })) === null); + ok('solved board → nothing to resume', parseSave(serialiseSave({ ...base, grid: clone(p.solution) })) === null); + ok('bad daily date dropped', parseSave(serialiseSave({ ...base, daily: 'yesterday' })).daily === null); + ok('missing history rebuilt', parseSave(JSON.stringify({ ...JSON.parse(serialiseSave(base)), history: null })).history.undo.length === 0); +} + +// ── Daily Survey ────────────────────────────────────────────────────────────── +section('Daily Survey'); +{ + ok('prevDate', prevDate('2026-11-26') === '2026-11-25' && prevDate('2026-12-01') === '2026-11-30' && prevDate('2027-01-01') === '2026-12-31' && prevDate('2028-03-01') === '2028-02-29'); + let r = updateDaily(null, '2026-11-20', '2026-11-20', 300000); + ok('first solve starts a streak', r.streak === 1 && r.rec.solved['2026-11-20'] === 300000 && !r.newBestTime); + r = updateDaily(r.rec, '2026-11-21', '2026-11-21', 250000); + ok('next day extends it', r.streak === 2 && r.rec.bestStreak === 2); + r = updateDaily(r.rec, '2026-11-21', '2026-11-21', 200000); + ok('re-solving today keeps the streak, keeps the faster time', r.streak === 2 && r.rec.solved['2026-11-21'] === 200000 && r.newBestTime); + const slower = updateDaily(r.rec, '2026-11-21', '2026-11-21', 900000); + ok('a slower re-solve keeps the old time', slower.rec.solved['2026-11-21'] === 200000 && !slower.newBestTime); + ok('streak alive the day after', dailyStreakNow(r.rec, '2026-11-22') === 2); + ok('streak dead two days later', dailyStreakNow(r.rec, '2026-11-23') === 0); + const old = updateDaily(r.rec, '2026-11-18', '2026-11-22', 100000); + ok('solving an old daily does not move the streak', old.rec.lastDate === '2026-11-21' && old.rec.streak === 2 && old.rec.solved['2026-11-18'] === 100000); + r = updateDaily(r.rec, '2026-11-24', '2026-11-24', 280000); + ok('a missed day restarts at 1', r.streak === 1 && r.rec.bestStreak === 2); + ok('blank record', dailyStreakNow(blankDaily(), '2026-11-24') === 0 && dailyStreakNow(null, '2026-11-24') === 0); + let rec = null; + for (let i = 0; i < 80; i++) { + const d = new Date(2026, 0, 1 + i); + const ds = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + rec = updateDaily(rec, ds, ds, 1000 + i).rec; + } + ok('long streak counted', rec.streak === 80 && rec.bestStreak === 80); + ok('solve history trimmed to 60', Object.keys(rec.solved).length === 60); +} + +// ── Layout ──────────────────────────────────────────────────────────────────── +section('Layout'); +{ + const inside = (P, x0, y0, x1, y1) => x0 >= P.x && x1 <= P.x + P.w && y0 >= P.y && y1 <= P.y + P.h; + ok('notebook on the desk', BOOK.x >= 0 && BOOK.y >= 0 && BOOK.x + BOOK.w <= W && BOOK.y + BOOK.h <= H); + ok('pages inside the cover', inside(BOOK, LEFT.x, LEFT.y, LEFT.x + LEFT.w, LEFT.y + LEFT.h) && inside(BOOK, RIGHT.x, RIGHT.y, RIGHT.x + RIGHT.w, RIGHT.y + RIGHT.h)); + ok('grid on the left page with room for row labels', inside(LEFT, GRID_X - 34, GRID_Y - 34, GRID_X + GRID_W + 6, GRID_Y + GRID_W + 6)); + ok('grid centred on the left page', Math.abs(GRID_X + GRID_W / 2 - LCX) <= 1); + ok('graph paper aligns with the cells', CELL % PITCH === 0); + ok('tags row fits the right page', inside(RIGHT, RCX - 2 * 128 - TAG_W / 2, 392 - 98, RCX + 2 * 128 + TAG_W / 2, 392 + TAG_H / 2 + 10)); + ok('page buttons fit the right page', inside(RIGHT, RCX - 232 - 98, 968 - 27, RCX + 232 + 98, 968 + 27)); + ok('start cards fit the right page', inside(RIGHT, RCX - CARD_W / 2, 262 - CARD_H / 2, RCX + CARD_W / 2, 262 + 4 * 150 + CARD_H / 2)); + ok('seismograph strip fits under the grid', GRID_Y + GRID_W + 6 < 944 - 12 && 986 + 34 <= LEFT.y + LEFT.h); + ok('certificate fits the screen', CERT_W + 40 <= W && CERT_H + 40 <= H); +} + +// ── Art bake (strict fake 2D context) ──────────────────────────────────────── +// No canvas in Node, so run every bake against a fake context that throws where +// a real one would: bad colour stops, negative radii, non-finite coordinates. +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 'fillRect': case 'strokeRect': case 'rect': return (...a) => check(fin(...a), 'rect'); + 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}`); + t[k] = v; return true; + }, + }); + const prevDoc = globalThis.document; + globalThis.document = { createElement: () => { const ctx = makeCtx(); return { width: 0, height: 0, getContext: () => ctx }; } }; + const added = new Map(); + const scene = { textures: { exists: (k) => added.has(k), addCanvas: (k, c) => { added.set(k, c); return {}; }, remove: (k) => added.delete(k) } }; + try { + const art = await import('../src/games/tectonic/TectonicArt.js'); + art.prepareTectonicArt(scene); + for (const k of ['tectonic-desk', 'tectonic-cover', 'tectonic-tag-1', 'tectonic-tag-5', 'tectonic-eraser', 'tectonic-card', 'tectonic-cert']) + ok(`baked ${k}`, added.has(k)); + const size = added.size; + art.prepareTectonicArt(scene); + ok('baking twice reuses the textures', added.size === size); + let cagesBaked = 0, inBounds = true; + for (const p of puzzles.slice(0, 4)) { + const { cages } = cageMeta(p.regions); + const col = colourCages(p.regions, TONES.length); + for (const [id, cells] of cages) { + const pos = art.bakeCage(scene, `t-${cagesBaked}`, cells, TONES[col.get(id)], id + 1); + if (pos) cagesBaked++; + if (!pos || pos.x < GRID_X - 12 || pos.y < GRID_Y - 12 || pos.x + pos.w > GRID_X + GRID_W + 12 || pos.y + pos.h > GRID_Y + GRID_W + 12) inBounds = false; + } + } + ok('every cage plate bakes', cagesBaked > 40, `${cagesBaked}`); + ok('cage plates sit on the grid', inBounds); + art.removeCageTextures(scene, ['t-0']); + ok('cage textures can be removed', !added.has('t-0-fill') && !added.has('t-0-ink')); + } catch (err) { + ok('art bake threw', false, err.stack); + } + ok('canvas calls all valid', errors.length === 0, [...new Set(errors)].slice(0, 6).join('; ')); + globalThis.document = prevDoc; +} + +// ── Scene smoke run (stubbed Phaser) ────────────────────────────────────────── +section('Scene smoke run'); +{ + // A do-anything stub: every property is a callable stub; calls return the stub. + const mk = () => { + const fn = function () { return proxy; }; + const proxy = new Proxy(fn, { + get(t, k) { + if (k === Symbol.toPrimitive) return () => 0; + if (k === 'then') return undefined; + if (k in t && typeof k === 'symbol') return t[k]; + return proxy; + }, + apply() { return proxy; }, + set() { return true; }, + }); + return proxy; + }; + const store = new Map(); + globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) }; + const { default: TectonicGame } = await import('../src/games/tectonic/TectonicGame.js'); + const sc = Object.create(TectonicGame.prototype); + const stub = mk(); + const delayed = []; + 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: () => {} }, + }); + const flush = () => { while (delayed.length) delayed.shift()(); }; + // Render-only methods are stubbed so the run exercises the rules/flow code. + for (const m of ['buildHeader', 'buildBoard', 'buildNotes', 'buildTags', 'buildControls', 'drawWash', 'drawHover', 'drawCursor', + 'refreshSelector', 'refreshButtons', 'refreshStats', 'drawSeismo', 'smudge', 'toast', 'plateShift', 'showCertificate', 'rejectValue']) + sc[m] = function () { this._calls = (this._calls ?? 0) + 1; }; + const p = generatePuzzle('medium', { seed: 77 }); + const boot = (difficulty) => { + sc.init({ game: { slug: 'tectonic' } }); + sc.difficulty = difficulty; + sc.grid = clone(p.grid); sc.solution = p.solution; sc.regions = p.regions; + sc.givens = p.grid.map(row => row.map(v => v !== 0)); + sc.cellState = Array.from({ length: N }, () => Array(N).fill(0)); + sc.hintsLeft = difficulty === 'easy' ? Infinity : difficulty === 'medium' ? 5 : 0; + sc.surveyNo = 1234; + sc.meta = cageMeta(sc.regions); + sc.mode = 'play'; + sc.cageObjs = new Map([...sc.meta.cages.entries()].map(([id, cells], slot) => [id, { cells, slot, fill: null }])); + sc.cellText = Array.from({ length: N }, () => Array(N).fill(null)); + sc.refreshAll(); + }; + const empties = () => { const out = []; for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!p.grid[r][c]) out.push({ r, c }); return out; }; + + try { + // Medium: fill with one wrong entry → reveal counts it; fix it → win. + boot('medium'); + const cells = empties(); + const bad = cells[0]; + const badV = p.solution[bad.r][bad.c] === 1 ? 2 : 1; + sc.onCellPointer(bad.r, bad.c); + ok('cell-first: tapping a cell selects it', sc.cursor?.r === bad.r && sc.cursor?.c === bad.c && sc.armed == null); + sc.onTagPointer(badV); + ok('cell-first: tapping a tag writes it', sc.grid[bad.r][bad.c] === badV && sc.armed == null); + ok('timer starts on the first entry', sc.timerOn === true); + ok('medium: no feedback before the map is full', sc.cellState[bad.r][bad.c] === 0 && sc.mistakes === 0); + for (const { r, c } of cells.slice(1)) { sc.cursor = { r, c }; sc.writeCell(r, c, p.solution[r][c]); } + flush(); + ok('full map triggers the check', sc.revealed === true && sc.cellState[bad.r][bad.c] === 2 && sc.mistakes === 1); + ok('no win with a mistake on the map', !sc.gameEnded); + const saved = parseSave(globalThis.localStorage.getItem('tectonic-save')); + ok('progress autosaved', saved && saved.revealed === true && saved.moves === cells.length); + sc.doUndo(); + ok('undo after reveal reverts the last entry', sc.grid[cells.at(-1).r][cells.at(-1).c] === 0); + sc.doRedo(); + sc.writeCell(bad.r, bad.c, p.solution[bad.r][bad.c]); + flush(); + ok('fixing the last mistake wins', sc.gameEnded === true); + ok('win clears the save', globalThis.localStorage.getItem('tectonic-save') === null); + const stats = JSON.parse(globalThis.localStorage.getItem('solitaire-stats-tectonic') || '{}'); + ok('win recorded under medium', stats.medium?.won === 1); + sc.writeCell(bad.r, bad.c, 0); + ok('no edits after the win', sc.grid[bad.r][bad.c] === p.solution[bad.r][bad.c]); + + // Easy: immediate checks + mistakes; number-first input; cage size guard. + boot('easy'); + const e = empties(); + sc.onTagPointer(5); + ok('number-first: a tag with no cell selected arms it', sc.armed === 5); + const small = e.find(({ r, c }) => sc.meta.sizeAt[r][c] < 5); + let rejected = 0; + sc.rejectValue = () => { rejected++; }; + sc.onCellPointer(small.r, small.c); + ok('value above cage size is refused', sc.grid[small.r][small.c] === 0 && rejected === 1); + const t = e[0]; + const wrong = [1, 2, 3, 4, 5].find(v => v !== p.solution[t.r][t.c] && v <= sc.meta.sizeAt[t.r][t.c]); + sc.armed = wrong; + sc.onCellPointer(t.r, t.c); + ok('easy: a wrong entry is marked and counted', sc.cellState[t.r][t.c] === 2 && sc.mistakes === 1); + sc.onCellPointer(t.r, t.c); + ok('armed tag on the same value erases', sc.grid[t.r][t.c] === 0); + sc.armed = p.solution[t.r][t.c]; + sc.onCellPointer(t.r, t.c); + ok('easy: a right entry is marked right', sc.cellState[t.r][t.c] === 1 && sc.mistakes === 1); + sc.onTagPointer(sc.armed); + ok('tapping the armed tag disarms it', sc.armed == null); + + // Keyboard + sc.cursor = null; + sc.onKey({ key: 'ArrowRight', preventDefault() {} }); + ok('arrows place the cursor on the first empty cell', sc.cursor && sc.grid[sc.cursor.r][sc.cursor.c] === 0); + const k0 = { ...sc.cursor }; + sc.onKey({ key: String(p.solution[k0.r][k0.c]), preventDefault() {} }); + ok('digit keys write at the cursor', sc.grid[k0.r][k0.c] === p.solution[k0.r][k0.c]); + sc.onKey({ key: 'Backspace', preventDefault() {} }); + ok('Backspace erases', sc.grid[k0.r][k0.c] === 0); + sc.onKey({ key: 'z', ctrlKey: true, preventDefault() {} }); + ok('Ctrl+Z undoes', sc.grid[k0.r][k0.c] === p.solution[k0.r][k0.c]); + sc.onKey({ key: 'y', ctrlKey: true, preventDefault() {} }); + ok('Ctrl+Y redoes', sc.grid[k0.r][k0.c] === 0); + sc.onKey({ key: 'ArrowUp', preventDefault() {} }); + ok('cursor wraps around the edge', sc.cursor.r === (k0.r + N - 1) % N && sc.cursor.c === k0.c); + + // Hints lock the cell and block undo past them. + sc.setPaused = TectonicGame.prototype.setPaused; + const hintsBefore = sc.hintsUsed; + sc.useHint(); + flush(); + const hinted = [...sc.hinted][0]?.split(',').map(Number); + ok('hint fills a cell with the answer and locks it', hinted && sc.grid[hinted[0]][hinted[1]] === p.solution[hinted[0]][hinted[1]] && sc.givens[hinted[0]][hinted[1]]); + ok('hint counted', sc.hintsUsed === hintsBefore + 1); + ok('undo cannot step back past a hint', !canUndo(sc.history)); + + // Hard: no hints at all. + boot('hard'); + sc.useHint(); + flush(); + ok('hard: hint does nothing', sc.hintsUsed === 0 && sc.hinted.size === 0); + + // Pause blocks input and the clock. + boot('easy'); + sc.add = stub; + sc.setPaused(true); + const c0 = empties()[0]; + sc.cursor = c0; + sc.writeCell = TectonicGame.prototype.writeCell; + sc.onTagPointer(1); + ok('paused: tags do nothing', sc.grid[c0.r][c0.c] === 0); + sc.timerOn = true; sc.elapsed = 0; + sc.update(0, 1000); + ok('paused: clock stops', sc.elapsed === 0); + sc.setPaused(false); + sc.update(0, 1000); + ok('resumed: clock runs', sc.elapsed === 1000); + } catch (err) { + ok('scene smoke run threw', false, err.stack); + } +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);