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.
This commit is contained in:
parent
d341746a8e
commit
9c35504760
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 ──────────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
Loading…
Reference in New Issue