545 lines
30 KiB
JavaScript
545 lines
30 KiB
JavaScript
#!/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 mistake takes the count back', sc.mistakes === 0);
|
|
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.doUndo();
|
|
ok('undoing a mistake takes the count back', sc.grid[t.r][t.c] === 0 && sc.mistakes === 0);
|
|
sc.doRedo();
|
|
ok('redo brings the mistake back', sc.grid[t.r][t.c] === wrong && 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.mistakes === 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 === 0);
|
|
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);
|