fertig-classic-games/src/games/tectonic/TectonicGame.js

1335 lines
59 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Tectonic (Suguru) — "Field Geologist's Notebook".
//
// The puzzle lives on the left page of a field notebook lying open on a desk:
// each cage is a watercolour "plate" with an inked outline and a size badge.
// The right page holds the field notes (timer, mistakes, hints), the specimen
// tags 1–5 + eraser, undo/redo, hint, pause and the page buttons.
//
// Input: pick a tag then tap cells (number-first), or tap a cell then a tag /
// press 1–5 (cell-first). Arrows/WASD move the cursor, Backspace/Delete/0
// erase, Ctrl+Z / Ctrl+Y undo/redo, H hint, P pause, Esc clears the selection.
//
// Feedback follows the original rules: Easy checks each entry immediately;
// Medium/Hard check once every cell is filled, then switch to immediate checks.
// Games autosave to localStorage; stats per difficulty + the Daily Survey.
import * as Phaser from 'phaser';
import { api } from '../../services/api.js';
import { MusicPlayer } from '../../ui/MusicPlayer.js';
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
import { loadStats, recordGame, formatTime } from '../../ui/solitaire/SolitaireStats.js';
import {
N, HINT_LIMITS, DIFF_LABELS, calcScore, isBoardComplete, getHintCell,
cageMeta, cageStatus, colourCages, traceCage, insetLoop,
makeHistory, pushEdit, pushMarker, canUndo, canRedo, undoEdit, redoEdit,
SAVE_KEY, serialiseSave, parseSave,
DAILY_KEY, DAILY_DIFFICULTY, todayString, dailySeed, updateDaily, dailyStreakNow, blankDaily,
} from './TectonicLogic.js';
import {
W, H, BOOK, LEFT, RIGHT, SPINE_X, LCX, RCX, CELL, GRID_W, GRID_X, GRID_Y,
TONES, INK, INK_N, PENCIL, BLUE_INK, RED_PENCIL, TAG_H, CARD_W, CARD_H,
prepareTectonicArt, bakeCage, removeCageTextures, PaperButton,
} from './TectonicArt.js';
const D = {
desk: 0, page: 2, gridLines: 4, cages: 10, hover: 14, cursor: 16, hit: 20,
ui: 30, flap: 40, toast: 45, cover: 55, modal: 60, cert: 80,
};
const HEADER_Y = LEFT.y + 17; // inside the printed header band
const TAG_Y = 392; // centre of a tag's body
const TAG_PITCH = 128;
const ERASER_Y = 548;
const HINT_Y = 652;
const PAGE_BTN_Y = 968;
const SEISMO_Y = 986;
const SEISMO_X0 = GRID_X + 14, SEISMO_X1 = GRID_X + GRID_W - 14;
const GUIDE_SEEN_KEY = 'tectonic-guide-seen';
const GIVEN_COLOR = INK;
const HINT_COLOR = '#8a6a1c';
const TITLE_BLUE = '#27506e';
const DEMO_REGIONS = [[4, 2, 2, 2, 2], [4, 2, 0, 1, 1], [4, 4, 0, 1, 1], [3, 3, 3, 1, 5], [3, 3, 5, 5, 5]];
const DEMO_SOLUTION = [[1, 3, 1, 4, 2], [2, 5, 2, 3, 1], [3, 4, 1, 4, 2], [1, 2, 3, 5, 1], [4, 5, 4, 2, 3]];
const DEMO_SHOWN = [[1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 1, 1], [1, 0, 1, 0, 1]];
let puzzleCounter = 0; // unique cage texture keys across restarts
const storage = () => { try { return globalThis.localStorage ?? null; } catch { return null; } };
const readJSON = (k) => { try { return JSON.parse(storage()?.getItem(k) || 'null'); } catch { return null; } };
const writeJSON = (k, v) => { try { storage()?.setItem(k, JSON.stringify(v)); } catch { /* private/full */ } };
const cellCX = (c) => GRID_X + c * CELL + CELL / 2;
const cellCY = (r) => GRID_Y + r * CELL + CELL / 2;
export default class TectonicGame extends Phaser.Scene {
constructor() { super('TectonicGame'); }
init(data) {
this._initData = { ...data };
delete this._initData.next;
this.next = data.next ?? null;
this.gameDef = data.game;
this.mode = 'start'; // start | loading | play | won
this.startObjs = [];
this.modal = null;
this.coverBusy = false;
this.paused = false;
this.flap = null;
this.toastObj = null;
this.grid = null; this.solution = null; this.regions = null; this.givens = null;
this.hinted = new Set();
this.difficulty = 'medium';
this.daily = null;
this.surveyNo = 0;
this.cellState = null;
this.history = makeHistory();
this.elapsed = 0;
this.timerOn = false;
this.hintsLeft = 0; this.hintsUsed = 0; this.mistakes = 0;
this.revealed = false;
this.moves = 0;
this.gameEnded = false;
this.winPending = false;
this.hintPending = false;
this.cursor = null;
this.armed = null; // null | 0 (eraser) | 1..5
this.hover = null;
this.cageKeys = [];
this.cageObjs = new Map(); // id → { cont, fill, wash, ink, badge, cells, slot }
this.cageDone = new Set();
this.seismoAmp = new Map(); // id → 0..1
this.seismoBurst = 0;
this.cellText = [];
this.tags = {};
this._lastSecond = -1;
}
create() {
prepareTectonicArt(this);
const music = this.cache.json.get('music');
if (music?.tracks) new MusicPlayer(this, music.tracks);
this.add.image(0, 0, 'tectonic-desk').setOrigin(0).setDepth(D.desk);
this.input.keyboard?.on('keydown', (e) => this.onKey(e));
this._onBlur = () => { if (this.mode === 'play' && this.timerOn && !this.paused && !this.gameEnded) this.setPaused(true); };
this.game.events.on('blur', this._onBlur);
this.game.events.on('hidden', this._onBlur);
this.events.once('shutdown', () => this.onShutdown());
const next = this.next;
if (next?.resume) {
const save = parseSave(storage()?.getItem(SAVE_KEY));
if (save) { this.beginFromSave(save); return; }
}
if (next?.difficulty) { this.startGame(next.difficulty, { daily: next.daily ?? null }); return; }
this.showStart({ cover: !next });
}
onShutdown() {
this.saveGame();
this.game.events.off('blur', this._onBlur);
this.game.events.off('hidden', this._onBlur);
removeCageTextures(this, this.cageKeys);
this.cageKeys = [];
}
restartWith(next) {
this.scene.restart({ ...this._initData, next });
}
leave() {
this.saveGame();
this.scene.start('GameMenu');
}
// ── Start screen ────────────────────────────────────────────────────────────
showStart({ cover = false } = {}) {
this.mode = 'start';
const add = (o) => { this.startObjs.push(o); return o; };
const save = parseSave(storage()?.getItem(SAVE_KEY));
const today = todayString();
// left page: title, a sample plate map, guide + leave
add(this.add.text(LEFT.x + 24, HEADER_Y, 'FIELD NOTEBOOK · VOL. VIII', {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(0, 0.5).setDepth(D.ui).setAlpha(0.8));
add(this.add.text(LCX, 196, 'Tectonic', {
fontFamily: 'YummyCupcakes', fontSize: '128px', color: TITLE_BLUE,
}).setOrigin(0.5).setDepth(D.ui));
add(this.add.text(LCX, 290, 'A field survey of number plates', {
fontFamily: 'YummyCupcakes', fontSize: '36px', color: PENCIL,
}).setOrigin(0.5).setDepth(D.ui));
this.drawDemoBoard(add);
add(this.add.text(LCX, 842, 'Each plate of N cells holds 1 to N.\nTouching cells never match, not even corner to corner.', {
fontFamily: 'YummyCupcakes', fontSize: '27px', color: INK, align: 'center', lineSpacing: 6,
}).setOrigin(0.5).setDepth(D.ui));
add(new PaperButton(this, LCX - 130, PAGE_BTN_Y, 'Field guide', () => this.openGuide(), { width: 220 }).setDepth(D.ui));
add(new PaperButton(this, LCX + 130, PAGE_BTN_Y, 'Leave', () => this.scene.start('GameMenu'), { width: 220 }).setDepth(D.ui));
// right page: survey site cards
add(this.add.text(RIGHT.x + RIGHT.w - 24, HEADER_Y, today, {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(1, 0.5).setDepth(D.ui).setAlpha(0.8));
add(this.add.text(RCX, 140, 'Choose a survey site', {
fontFamily: 'YummyCupcakes', fontSize: '54px', color: INK,
}).setOrigin(0.5).setDepth(D.ui));
const dailyRec = readJSON(DAILY_KEY) ?? blankDaily();
const dailyTime = dailyRec.solved?.[today];
const statLine = (mode) => {
const s = loadStats('tectonic', mode);
if (!s.played) return 'No surveys yet';
return `Solved ${s.won} · Best ${formatTime(s.bestTime)} · Streak ${s.streak}`;
};
const cards = [];
if (save) {
const givenFlat = save.givens.flat();
const empties = givenFlat.filter(g => !g).length;
const filled = save.grid.flat().filter((v, i) => v && !givenFlat[i]).length;
const label = save.daily ? `Daily Survey (${save.daily})` : `${DIFF_LABELS[save.difficulty]} site`;
cards.push({ title: 'Resume survey', tone: '#b8402f', desc: `${label} · No. ${save.surveyNo || '—'}`,
stats: `${formatTime(save.elapsed)} on the clock · ${filled} / ${empties} cells written`,
go: () => this.restartWith({ resume: true }) });
}
cards.push({ title: 'Daily Survey', tone: TONES[5].fill, desc: 'One plate map for everyone today (Medium rules)',
stats: `Day streak ${dailyStreakNow(dailyRec, today)} · Today: ${dailyTime != null ? `solved in ${formatTime(dailyTime)}` : 'not yet surveyed'}`,
go: () => this.pickSite(DAILY_DIFFICULTY, today, save) });
cards.push({ title: 'Easy site', tone: TONES[2].fill, desc: '30 givens · unlimited hints · checked as you write',
stats: statLine('easy'), go: () => this.pickSite('easy', null, save) });
cards.push({ title: 'Medium site', tone: TONES[0].fill, desc: '24 givens · 5 hints · checked once the map is full',
stats: statLine('medium'), go: () => this.pickSite('medium', null, save) });
cards.push({ title: 'Hard site', tone: TONES[3].fill, desc: '18 givens · no hints · checked once the map is full',
stats: statLine('hard'), go: () => this.pickSite('hard', null, save) });
const pitch = cards.length > 4 ? 150 : 166;
const y0 = cards.length > 4 ? 262 : 290;
cards.forEach((spec, i) => this.makeCard(add, RCX, y0 + i * pitch, spec, i));
if (cover) this.playCover();
else this.maybeFirstGuide();
}
drawDemoBoard(add) {
const cell = 64, n = 5;
const x0 = LCX - (cell * n) / 2, y0 = 368;
const meta = cageMeta(DEMO_REGIONS);
const colours = colourCages(DEMO_REGIONS, TONES.length);
const g = add(this.add.graphics().setDepth(D.cages));
for (const [id, cells] of meta.cages) {
const tone = Phaser.Display.Color.HexStringToColor(TONES[colours.get(id)].fill).color;
g.fillStyle(tone, 0.32);
for (const { r, c } of cells) g.fillRect(x0 + c * cell, y0 + r * cell, cell, cell);
}
g.lineStyle(3, INK_N, 0.9);
for (const cells of meta.cages.values()) {
const loop = insetLoop(traceCage(cells), 3 / cell);
g.strokePoints(loop.map(([x, y]) => ({ x: x0 + x * cell, y: y0 + y * cell })), true, true);
}
for (let r = 0; r < n; r++)
for (let c = 0; c < n; c++) {
if (!DEMO_SHOWN[r][c]) continue;
add(this.add.text(x0 + c * cell + cell / 2, y0 + r * cell + cell / 2 + 1, String(DEMO_SOLUTION[r][c]), {
fontFamily: r % 2 ? 'YummyCupcakes' : 'Righteous', fontSize: r % 2 ? '40px' : '34px', color: r % 2 ? BLUE_INK : INK,
}).setOrigin(0.5).setDepth(D.cages + 1));
}
add(this.add.text(x0 + n * cell + 26, y0 + 30, 'fig. 1', {
fontFamily: 'YummyCupcakes', fontSize: '24px', color: PENCIL,
}).setOrigin(0, 0.5).setDepth(D.ui).setAngle(-6));
}
makeCard(add, x, y, spec, i) {
const cont = add(this.add.container(x, y).setDepth(D.ui));
const img = this.add.image(0, 0, 'tectonic-card');
const band = this.add.graphics();
band.fillStyle(Phaser.Display.Color.HexStringToColor(spec.tone).color, 0.85);
band.fillRect(-CARD_W / 2, -CARD_H / 2 - 2, 16, CARD_H);
const title = this.add.text(-CARD_W / 2 + 36, -CARD_H / 2 + 18, spec.title, {
fontFamily: 'YummyCupcakes', fontSize: '40px', color: INK,
}).setOrigin(0, 0.5);
const desc = this.add.text(-CARD_W / 2 + 38, 8, spec.desc, {
fontFamily: 'YummyCupcakes', fontSize: '24px', color: BLUE_INK,
}).setOrigin(0, 0.5);
const stats = this.add.text(-CARD_W / 2 + 38, 40, spec.stats, {
fontFamily: 'YummyCupcakes', fontSize: '22px', color: PENCIL,
}).setOrigin(0, 0.5);
cont.add([img, band, title, desc, stats]);
cont.setAngle(i % 2 ? 0.6 : -0.5);
cont.setSize(CARD_W, CARD_H);
cont.setInteractive({ useHandCursor: true });
cont.on('pointerover', () => this.tweens.add({ targets: cont, y: y - 5, angle: 0, duration: 120 }));
cont.on('pointerout', () => this.tweens.add({ targets: cont, y, angle: i % 2 ? 0.6 : -0.5, duration: 160 }));
cont.on('pointerup', () => {
if (this.coverBusy || this.modal || this.mode !== 'start') return;
playSound(this, SFX.UI_PICK);
spec.go();
});
}
playCover() {
this.coverBusy = true;
const cont = this.add.container(SPINE_X, BOOK.y).setDepth(D.cover);
const img = this.add.image(0, 0, 'tectonic-cover').setOrigin(0, 0);
const cw = img.width;
const t1 = this.add.text(cw / 2, 330, 'FIELD NOTEBOOK', {
fontFamily: 'Righteous', fontSize: '34px', color: '#5a3a26',
}).setOrigin(0.5);
const t2 = this.add.text(cw / 2, 396, 'Tectonic Plate Surveys', {
fontFamily: 'YummyCupcakes', fontSize: '44px', color: '#27324a',
}).setOrigin(0.5);
cont.add([img, t1, t2]);
this.time.delayedCall(420, () => {
playSound(this, SFX.UI_FLIP);
this.tweens.add({
targets: cont, scaleX: 0, duration: 620, ease: 'Cubic.easeIn',
onComplete: () => { cont.destroy(); this.coverBusy = false; this.maybeFirstGuide(); },
});
});
}
maybeFirstGuide() {
if (storage()?.getItem(GUIDE_SEEN_KEY)) return;
this.time.delayedCall(200, () => { if (!this.modal) this.openGuide(); });
}
// Choosing a site when a save exists abandons it (counted as played, not won).
pickSite(difficulty, daily, save) {
if (save && daily && save.daily === daily) { this.restartWith({ resume: true }); return; }
if (save && save.moves > 0) {
this.confirm('Start a new survey?', `Your saved ${save.daily ? 'Daily Survey' : `${DIFF_LABELS[save.difficulty]} site`} will be abandoned.`,
'Abandon it', () => { this.abandonSave(save); this.restartWith({ difficulty, daily }); });
return;
}
storage()?.removeItem(SAVE_KEY);
this.restartWith({ difficulty, daily });
}
abandonSave(save) {
recordGame('tectonic', { won: false, time: save.elapsed, moves: save.moves, mode: save.daily ? 'daily' : save.difficulty });
storage()?.removeItem(SAVE_KEY);
}
// ── Game start ─────────────────────────────────────────────────────────────
async startGame(difficulty, { daily = null } = {}) {
this.mode = 'loading';
const loading = this.add.text(LCX, GRID_Y + GRID_W / 2, 'Surveying the site…', {
fontFamily: 'YummyCupcakes', fontSize: '48px', color: PENCIL,
}).setOrigin(0.5).setDepth(D.ui);
const seedQ = daily ? `&seed=${dailySeed(daily)}` : '';
let data;
try {
data = await api.get(`/words/tectonic/start?difficulty=${difficulty}${seedQ}`);
} catch (err) {
console.error('[tectonic] failed to fetch puzzle:', err);
loading.destroy();
this.showStart();
return;
}
if (!this.sys.isActive()) return;
loading.destroy();
this.difficulty = difficulty;
this.daily = daily;
this.grid = data.grid.map(row => [...row]);
this.solution = data.solution;
this.regions = data.regions;
this.givens = this.grid.map(row => row.map(v => v !== 0));
this.cellState = Array.from({ length: N }, () => Array(N).fill(0));
this.hintsLeft = HINT_LIMITS[difficulty] ?? 0;
this.surveyNo = daily ? 1000 + (dailySeed(daily) % 9000) : 1000 + Math.floor(Math.random() * 9000);
this.buildPlay();
}
beginFromSave(s) {
this.difficulty = s.difficulty;
this.daily = s.daily;
this.grid = s.grid; this.solution = s.solution; this.regions = s.regions; this.givens = s.givens;
this.hinted = new Set((s.hinted ?? []).filter(k => typeof k === 'string'));
this.cellState = s.cellState;
this.history = s.history;
this.elapsed = s.elapsed;
this.hintsLeft = s.hintsLeft; this.hintsUsed = s.hintsUsed; this.mistakes = s.mistakes;
this.revealed = s.revealed;
this.moves = s.moves;
this.surveyNo = s.surveyNo || 1000 + Math.floor(Math.random() * 9000);
this.timerOn = this.moves > 0;
this.buildPlay();
this.toast('Welcome back. Survey resumed.');
}
// ── Play screen ────────────────────────────────────────────────────────────
buildPlay() {
this.mode = 'play';
this.meta = cageMeta(this.regions);
this.buildHeader();
this.buildBoard();
this.buildNotes();
this.buildTags();
this.buildControls();
this.refreshAll();
}
buildHeader() {
this.add.text(LEFT.x + 24, HEADER_Y, `SURVEY No. ${this.surveyNo}`, {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(0, 0.5).setDepth(D.ui).setAlpha(0.85);
this.add.text(LEFT.x + LEFT.w - 24, HEADER_Y,
this.daily ? `DAILY SURVEY · ${this.daily}` : `SITE: ${DIFF_LABELS[this.difficulty].toUpperCase()}`, {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(1, 0.5).setDepth(D.ui).setAlpha(0.85);
this.add.text(LCX, 138, 'Tectonic', {
fontFamily: 'YummyCupcakes', fontSize: '76px', color: TITLE_BLUE,
}).setOrigin(0.5).setDepth(D.ui);
const givens = this.givens.flat().filter(Boolean).length - this.hinted.size;
this.add.text(LCX, 194, `8 × 8 · ${this.meta.cages.size} plates · ${givens} givens`, {
fontFamily: 'YummyCupcakes', fontSize: '26px', color: PENCIL,
}).setOrigin(0.5).setDepth(D.ui);
}
buildBoard() {
// pencilled cell grid + outer frame
const gl = this.add.graphics().setDepth(D.gridLines);
gl.lineStyle(1.2, 0x6f9fca, 0.45);
for (let i = 1; i < N; i++) {
gl.lineBetween(GRID_X + i * CELL, GRID_Y, GRID_X + i * CELL, GRID_Y + GRID_W);
gl.lineBetween(GRID_X, GRID_Y + i * CELL, GRID_X + GRID_W, GRID_Y + i * CELL);
}
gl.lineStyle(2, INK_N, 0.35);
gl.strokeRect(GRID_X - 6, GRID_Y - 6, GRID_W + 12, GRID_W + 12);
// row/column survey marks
for (let i = 0; i < N; i++) {
this.add.text(GRID_X - 22, cellCY(i), String.fromCharCode(65 + i), {
fontFamily: 'Righteous', fontSize: '15px', color: PENCIL,
}).setOrigin(0.5).setDepth(D.gridLines).setAlpha(0.6);
this.add.text(cellCX(i), GRID_Y - 22, String(i + 1), {
fontFamily: 'Righteous', fontSize: '15px', color: PENCIL,
}).setOrigin(0.5).setDepth(D.gridLines).setAlpha(0.6);
}
// cage plates
const colours = colourCages(this.regions, TONES.length);
const pid = ++puzzleCounter;
const order = [...this.meta.cages.entries()]
.map(([id, cells]) => ({ id, cells, cx: cells.reduce((s, p) => s + p.c, 0) / cells.length }))
.sort((a, b) => a.cx - b.cx);
this.cellText = Array.from({ length: N }, () => Array(N).fill(null));
order.forEach(({ id, cells }, slot) => {
const key = `tectonic-cage-${pid}-${id}`;
const tone = TONES[colours.get(id)];
const pos = bakeCage(this, key, cells, tone, id + pid * 31);
this.cageKeys.push(key);
const cont = this.add.container(0, 0).setDepth(D.cages);
const fill = pos ? this.add.image(pos.x, pos.y, `${key}-fill`).setOrigin(0).setAlpha(0.6) : null;
const wash = this.add.graphics();
const ink = pos ? this.add.image(pos.x, pos.y, `${key}-ink`).setOrigin(0) : null;
const first = cells[0];
const badge = this.add.text(GRID_X + first.c * CELL + 11, GRID_Y + first.r * CELL + 9, String(cells.length), {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(0, 0).setAlpha(0.85);
const kids = [fill, wash, ink, badge].filter(Boolean);
for (const { r, c } of cells) {
const t = this.add.text(cellCX(c), cellCY(r) + 2, '', {
fontFamily: 'YummyCupcakes', fontSize: '56px', color: BLUE_INK,
}).setOrigin(0.5);
this.cellText[r][c] = t;
kids.push(t);
}
cont.add(kids);
this.cageObjs.set(id, { cont, fill, wash, ink, badge, cells, slot, tone });
});
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) this.renderCellText(r, c);
this.hoverGfx = this.add.graphics().setDepth(D.hover);
this.cursorGfx = this.add.graphics().setDepth(D.cursor);
const zone = this.add.zone(GRID_X + GRID_W / 2, GRID_Y + GRID_W / 2, GRID_W, GRID_W)
.setDepth(D.hit).setInteractive({ useHandCursor: true });
const cellAt = (p) => {
const c = Math.floor((p.worldX - GRID_X) / CELL), r = Math.floor((p.worldY - GRID_Y) / CELL);
return r >= 0 && r < N && c >= 0 && c < N ? { r, c } : null;
};
zone.on('pointermove', (p) => {
const h = cellAt(p);
if (h?.r !== this.hover?.r || h?.c !== this.hover?.c) { this.hover = h; this.drawHover(); }
});
zone.on('pointerout', () => { this.hover = null; this.drawHover(); });
zone.on('pointerdown', (p) => { const h = cellAt(p); if (h) this.onCellPointer(h.r, h.c); });
// seismograph strip: plates surveyed
this.seismoLabel = this.add.text(GRID_X, 944, '', {
fontFamily: 'YummyCupcakes', fontSize: '24px', color: PENCIL,
}).setOrigin(0, 0.5).setDepth(D.ui);
this.seismoGfx = this.add.graphics().setDepth(D.ui);
let s = 99;
this.seismoNoise = Array.from({ length: 400 }, () => { s = (s * 16807) % 2147483647; return s / 2147483647 - 0.5; });
}
renderCellText(r, c) {
const t = this.cellText[r][c];
if (!t) return;
const v = this.grid[r][c];
t.setText(v ? String(v) : '');
if (this.givens[r][c]) {
const hinted = this.hinted.has(`${r},${c}`);
t.setFontFamily('Righteous').setFontSize(46).setColor(hinted ? HINT_COLOR : GIVEN_COLOR);
} else {
t.setFontFamily('YummyCupcakes').setFontSize(56).setColor(BLUE_INK);
}
}
buildNotes() {
this.add.text(RIGHT.x + 56, HEADER_Y, 'FIELD NOTES', {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(0, 0.5).setDepth(D.ui).setAlpha(0.85);
this.add.text(RIGHT.x + RIGHT.w - 24, HEADER_Y, todayString(), {
fontFamily: 'Righteous', fontSize: '16px', color: PENCIL,
}).setOrigin(1, 0.5).setDepth(D.ui).setAlpha(0.85);
const box = this.add.graphics().setDepth(D.ui);
this.statTexts = {};
[['time', 'Time', -232], ['mistakes', 'Mistakes', 0], ['hints', 'Hints used', 232]].forEach(([k, label, dx]) => {
const x = RCX + dx;
box.lineStyle(2, INK_N, 0.5);
box.strokeRoundedRect(x - 100, 114, 200, 104, 10);
box.lineStyle(1, INK_N, 0.18);
box.strokeRoundedRect(x - 98, 112, 199, 107, 11);
this.add.text(x, 136, label, {
fontFamily: 'YummyCupcakes', fontSize: '24px', color: PENCIL,
}).setOrigin(0.5).setDepth(D.ui);
this.statTexts[k] = this.add.text(x, 182, '', {
fontFamily: 'YummyCupcakes', fontSize: '54px', color: INK,
}).setOrigin(0.5).setDepth(D.ui);
});
this.add.text(RCX, 268, 'Specimen tags', {
fontFamily: 'YummyCupcakes', fontSize: '30px', color: INK,
}).setOrigin(0.5).setDepth(D.ui);
const rule = this.isChecking()
? 'Easy site: every entry is checked as you write.'
: `${this.daily ? 'Daily Survey' : `${DIFF_LABELS[this.difficulty]} site`}: checked once every cell is written.`;
this.add.text(RCX, 790,
'Pick a tag, then tap cells, or tap a cell, then a tag.\n' +
'Keys: arrows move · 1–5 write · Backspace erases\n' +
'Ctrl+Z undo · Ctrl+Y redo · H hint · P pause', {
fontFamily: 'YummyCupcakes', fontSize: '25px', color: PENCIL, align: 'center', lineSpacing: 8,
}).setOrigin(0.5).setDepth(D.ui);
this.ruleText = this.add.text(RCX, 880, rule, {
fontFamily: 'YummyCupcakes', fontSize: '25px', color: BLUE_INK, align: 'center',
}).setOrigin(0.5).setDepth(D.ui);
}
buildTags() {
this.selGfx = this.add.graphics().setDepth(D.ui + 2);
this.strikeGfx = this.add.graphics().setDepth(D.ui + 3);
for (let n = 1; n <= 5; n++) {
const x = RCX + (n - 3) * TAG_PITCH;
const img = this.add.image(x, TAG_Y, `tectonic-tag-${n}`).setOrigin(0.5, 98 / 172).setDepth(D.ui);
const txt = this.add.text(x, TAG_Y - 6, String(n), {
fontFamily: 'Righteous', fontSize: '62px', color: INK,
}).setOrigin(0.5).setDepth(D.ui + 1);
const zone = this.add.zone(x, TAG_Y, 116, TAG_H + 10).setDepth(D.hit).setInteractive({ useHandCursor: true });
zone.on('pointerover', () => this.tweens.add({ targets: [img, txt], angle: n % 2 ? 3 : -3, duration: 100 }));
zone.on('pointerout', () => this.tweens.add({ targets: [img, txt], angle: 0, duration: 140 }));
zone.on('pointerup', () => this.onTagPointer(n));
this.tags[n] = { img, txt, zone, x };
}
const eimg = this.add.image(RCX, ERASER_Y, 'tectonic-eraser').setDepth(D.ui);
const ezone = this.add.zone(RCX, ERASER_Y, 150, 90).setDepth(D.hit).setInteractive({ useHandCursor: true });
ezone.on('pointerover', () => this.tweens.add({ targets: eimg, angle: 4, duration: 100 }));
ezone.on('pointerout', () => this.tweens.add({ targets: eimg, angle: 0, duration: 140 }));
ezone.on('pointerup', () => this.onTagPointer(0));
this.tags[0] = { img: eimg, zone: ezone, x: RCX };
}
buildControls() {
this.undoBtn = new PaperButton(this, RCX - 220, ERASER_Y, 'Undo', () => this.doUndo(), { width: 170 }).setDepth(D.ui);
this.redoBtn = new PaperButton(this, RCX + 220, ERASER_Y, 'Redo', () => this.doRedo(), { width: 170 }).setDepth(D.ui);
this.hintBtn = new PaperButton(this, RCX - 136, HINT_Y, 'Hint', () => this.useHint(), { width: 250 }).setDepth(D.ui);
this.pauseBtn = new PaperButton(this, RCX + 136, HINT_Y, 'Pause', () => this.setPaused(!this.paused), { width: 250 }).setDepth(D.ui);
new PaperButton(this, RCX - 232, PAGE_BTN_Y, 'Field guide', () => this.openGuide(), { width: 196 }).setDepth(D.ui);
new PaperButton(this, RCX, PAGE_BTN_Y, 'New survey', () => this.newSurvey(), { width: 210, accent: true }).setDepth(D.ui);
new PaperButton(this, RCX + 232, PAGE_BTN_Y, 'Leave', () => this.leave(), { width: 196 }).setDepth(D.ui);
}
// ── Rendering ───────────────────────────────────────────────────────────────
refreshAll() {
for (const id of this.meta.cages.keys()) this.drawWash(id);
this.recomputeCageDone(false);
this.refreshSelector();
this.refreshButtons();
this.refreshStats();
this.drawCursor();
this.drawSeismo();
}
isChecking() { return this.difficulty === 'easy' || this.revealed; }
drawWash(id) {
const o = this.cageObjs.get(id);
if (!o) return;
const g = o.wash;
g.clear();
for (const { r, c } of o.cells) {
const st = this.cellState[r][c];
if (!st) continue;
const x = GRID_X + c * CELL + 7, y = GRID_Y + r * CELL + 7, s = CELL - 14;
if (st === 1) {
g.fillStyle(0x3c8a4e, 0.16);
g.fillRoundedRect(x, y, s, s, 8);
} else {
g.fillStyle(RED_PENCIL, 0.10);
g.fillRoundedRect(x, y, s, s, 8);
g.lineStyle(1.6, RED_PENCIL, 0.5);
for (let t = 12; t < s * 2; t += 12) {
const ax = x + Math.max(0, t - s), ay = y + Math.min(t, s);
const bx = x + Math.min(t, s), by = y + Math.max(0, t - s);
g.lineBetween(ax, ay, bx, by);
}
}
}
}
drawHover() {
const g = this.hoverGfx;
if (!g) return;
g.clear();
if (!this.hover || this.mode !== 'play' || this.paused) return;
const { r, c } = this.hover;
g.fillStyle(INK_N, this.givens[r][c] ? 0.03 : 0.07);
g.fillRoundedRect(GRID_X + c * CELL + 5, GRID_Y + r * CELL + 5, CELL - 10, CELL - 10, 8);
}
drawCursor(offsetX = 0) {
const g = this.cursorGfx;
if (!g) return;
g.clear();
if (!this.cursor || this.gameEnded) return;
const { r, c } = this.cursor;
const x = GRID_X + c * CELL + 6 + offsetX, y = GRID_Y + r * CELL + 6, s = CELL - 12;
g.lineStyle(3.2, RED_PENCIL, 0.9);
g.strokeRoundedRect(x, y, s, s, 10);
g.lineStyle(1.4, RED_PENCIL, 0.35);
g.strokeRoundedRect(x - 2, y + 1, s + 3, s - 1, 12);
}
refreshSelector() {
const g = this.selGfx, sg = this.strikeGfx;
if (!g) return;
g.clear(); sg.clear();
const maxV = this.cursor && !this.givens[this.cursor.r][this.cursor.c]
? this.meta.sizeAt[this.cursor.r][this.cursor.c] : 5;
const counts = [0, 0, 0, 0, 0, 0];
for (const row of this.grid) for (const v of row) if (v) counts[v]++;
for (let n = 1; n <= 5; n++) {
const t = this.tags[n];
const used = counts[n] >= this.meta.neededFor[n];
const out = n > maxV;
t.img.setAlpha(out ? 0.35 : 1);
t.txt.setAlpha(out ? 0.35 : 1).setColor(used ? '#9aa6b2' : INK);
if (used) {
sg.lineStyle(3.2, 0x6d7580, 0.85);
sg.lineBetween(t.x - 30, TAG_Y - 2, t.x + 30, TAG_Y - 12);
}
}
if (this.armed != null) {
const t = this.tags[this.armed];
const cy = this.armed === 0 ? ERASER_Y : TAG_Y;
const rx = this.armed === 0 ? 92 : 70, ry = this.armed === 0 ? 56 : 86;
g.lineStyle(3.4, RED_PENCIL, 0.88);
g.strokeEllipse(t.x, cy, rx * 2, ry * 2);
g.lineStyle(1.8, RED_PENCIL, 0.3);
g.strokeEllipse(t.x + 4, cy - 3, rx * 2 + 8, ry * 2 + 6);
}
}
refreshButtons() {
this.undoBtn?.setEnabled(!this.gameEnded && canUndo(this.history));
this.redoBtn?.setEnabled(!this.gameEnded && canRedo(this.history));
if (this.hintBtn) {
const finite = Number.isFinite(this.hintsLeft);
this.hintBtn.setLabel(this.hintsLeft === 0 && this.hintsUsed === 0 && finite ? 'No hints here'
: finite ? `Hint (${this.hintsLeft} left)` : 'Hint');
this.hintBtn.setEnabled(!this.gameEnded && this.hintsLeft > 0);
}
this.pauseBtn?.setLabel(this.paused ? 'Resume' : 'Pause').setEnabled(!this.gameEnded);
}
refreshStats() {
if (!this.statTexts) return;
this.statTexts.time.setText(formatTime(this.elapsed));
this.statTexts.mistakes.setText(String(this.mistakes));
this.statTexts.hints.setText(String(this.hintsUsed));
}
drawSeismo() {
const g = this.seismoGfx;
if (!g) return;
g.clear();
const total = this.meta.cages.size;
this.seismoLabel.setText(`Plates surveyed ${this.cageDone.size} / ${total}`);
const slots = [...this.cageObjs.values()].map(o => o.slot);
const span = SEISMO_X1 - SEISMO_X0;
const slotX = (slot) => SEISMO_X0 + 40 + (slot / Math.max(1, slots.length - 1)) * (span - 80);
const spikes = [];
for (const [id, o] of this.cageObjs) {
const a = this.seismoAmp.get(id) ?? 0;
if (a > 0.001) spikes.push([slotX(o.slot), a]);
}
g.lineStyle(1, 0x6f9fca, 0.5);
g.lineBetween(SEISMO_X0, SEISMO_Y, SEISMO_X1, SEISMO_Y);
g.lineStyle(2, INK_N, 0.8);
g.beginPath();
let k = 0;
for (let x = SEISMO_X0; x <= SEISMO_X1; x += 2, k++) {
let y = SEISMO_Y + this.seismoNoise[k % this.seismoNoise.length] * 2.2;
for (const [sx, a] of spikes) {
const d = (x - sx) / 11;
y += a * 22 * Math.exp(-d * d) * Math.sin(x * 0.9);
}
if (this.seismoBurst > 0) {
const d = (x - (SEISMO_X0 + SEISMO_X1) / 2) / (span * 0.28);
y += this.seismoBurst * 30 * Math.exp(-d * d) * Math.sin(x * 0.55 + k);
}
if (x === SEISMO_X0) g.moveTo(x, y); else g.lineTo(x, y);
}
g.strokePath();
}
// ── Input ──────────────────────────────────────────────────────────────────
blocked() { return this.mode !== 'play' || this.gameEnded || this.winPending || this.hintPending || this.paused || !!this.modal; }
onCellPointer(r, c) {
if (this.blocked()) return;
if (this.armed != null) {
this.cursor = { r, c };
if (!this.givens[r][c]) {
if (this.armed === 0 || this.grid[r][c] === this.armed) this.writeCell(r, c, 0);
else this.writeCell(r, c, this.armed);
} else playSound(this, SFX.PIECE_CLICK);
} else if (this.cursor?.r === r && this.cursor?.c === c) {
this.cursor = null;
playSound(this, SFX.PIECE_CLICK);
} else {
this.cursor = { r, c };
playSound(this, SFX.PIECE_CLICK);
}
this.drawCursor();
this.refreshSelector();
}
onTagPointer(n) {
if (this.blocked()) return;
if (this.armed === n) {
this.armed = null;
playSound(this, SFX.PIECE_CLICK);
} else if (this.armed != null) {
this.armed = n;
playSound(this, SFX.PIECE_CLICK);
} else if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) {
this.writeCell(this.cursor.r, this.cursor.c, n);
} else {
this.armed = n;
playSound(this, SFX.PIECE_CLICK);
}
this.refreshSelector();
}
onKey(e) {
const k = e.key;
if (this.modal) {
if (k === 'Escape') this.modal.close?.();
return;
}
if (this.mode !== 'play' || this.gameEnded) return;
const ctrl = e.ctrlKey || e.metaKey;
const lower = k.length === 1 ? k.toLowerCase() : k;
if (ctrl && lower === 'z') { e.preventDefault?.(); e.shiftKey ? this.doRedo() : this.doUndo(); return; }
if (ctrl && lower === 'y') { e.preventDefault?.(); this.doRedo(); return; }
if (ctrl) return;
if (lower === 'p') { this.setPaused(!this.paused); return; }
if (this.paused) return;
if (k === 'Escape') {
if (this.cursor || this.armed != null) { this.cursor = null; this.armed = null; this.drawCursor(); this.refreshSelector(); }
else this.setPaused(true);
return;
}
if (lower === 'h') { this.useHint(); return; }
const moves = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1], w: [-1, 0], s: [1, 0], a: [0, -1], d: [0, 1] };
if (moves[lower]) {
e.preventDefault?.();
if (!this.cursor) this.cursor = this.firstEmpty() ?? { r: 0, c: 0 };
else {
const [dr, dc] = moves[lower];
this.cursor = { r: (this.cursor.r + dr + N) % N, c: (this.cursor.c + dc + N) % N };
}
this.drawCursor();
this.refreshSelector();
return;
}
if (/^[1-5]$/.test(k)) {
const v = Number(k);
if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) this.writeCell(this.cursor.r, this.cursor.c, v);
else if (!this.cursor) { this.armed = v; playSound(this, SFX.PIECE_CLICK); this.refreshSelector(); }
return;
}
if (k === 'Backspace' || k === 'Delete' || k === '0') {
e.preventDefault?.();
if (this.cursor && !this.givens[this.cursor.r][this.cursor.c]) this.writeCell(this.cursor.r, this.cursor.c, 0);
}
}
firstEmpty() {
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!this.grid[r][c]) return { r, c };
return null;
}
// ── Editing ────────────────────────────────────────────────────────────────
// A player write (v = 0 erases). Validates, records history, evaluates.
writeCell(r, c, v) {
if (this.blocked() || this.givens[r][c]) return;
const size = this.meta.sizeAt[r][c];
if (v > size) { this.rejectValue(r, c, size); return; }
const from = this.grid[r][c];
if (from === v) return;
pushEdit(this.history, { r, c, from, to: v });
this.moves++;
this.timerOn = true;
this.applyCell(r, c, v, { anim: true, countMistake: true });
}
rejectValue(r, c, size) {
playSoundEx(this, SFX.CLICK, { rate: 0.6, volume: 0.6 });
const o = this.cageObjs.get(this.regions[r][c]);
if (o?.badge) {
o.badge.setColor('#b8402f').setScale(1.4);
this.tweens.add({ targets: o.badge, scale: 1, duration: 420, ease: 'Back.easeOut', onComplete: () => o.badge.setColor(PENCIL) });
}
const shake = { x: 0 };
this.tweens.add({
targets: shake, x: 1, duration: 280,
onUpdate: () => this.drawCursor(Math.sin(shake.x * Math.PI * 6) * 5 * (1 - shake.x)),
onComplete: () => this.drawCursor(),
});
this.toast(`That plate has ${size} cell${size > 1 ? 's' : ''}, so it only holds 1–${size}.`, 2000);
}
// Set a cell's value and run the feedback rules. Used by writes, undo/redo
// and hints.
applyCell(r, c, v, { anim = false, countMistake = false } = {}) {
const from = this.grid[r][c];
this.grid[r][c] = v;
this.renderCellText(r, c);
const t = this.cellText[r][c];
if (anim && t) {
if (v) {
playSoundEx(this, SFX.PENCIL_WRITE, { rate: 0.9 + Math.random() * 0.25, volume: 0.7 });
t.setScale(1.35).setAlpha(0).setAngle(-8);
this.tweens.add({ targets: t, scale: 1, alpha: 1, angle: 0, duration: 220, ease: 'Back.easeOut' });
} else if (from) {
playSoundEx(this, SFX.UI_PICK, { rate: 0.7, volume: 0.6 });
this.smudge(r, c);
}
}
if (!v || this.givens[r][c]) {
this.cellState[r][c] = 0;
} else if (this.isChecking()) {
const ok = v === this.solution[r][c];
this.cellState[r][c] = ok ? 1 : 2;
if (!ok && countMistake) this.mistakes++;
} else {
this.cellState[r][c] = 0;
}
this.drawWash(this.regions[r][c]);
this.recomputeCageDone(true);
this.refreshSelector();
this.refreshButtons();
this.refreshStats();
if (isBoardComplete(this.grid, this.solution)) {
if (!this.isChecking()) this.revealAll(true);
this.winPending = true; // locks input until the ceremony
this.time.delayedCall(360, () => this.handleWin());
} else if (!this.isChecking() && this.allFilled()) {
this.time.delayedCall(220, () => { if (!this.revealed && this.allFilled()) this.revealAll(false); });
}
this.saveGame();
}
allFilled() {
for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (!this.grid[r][c]) return false;
return true;
}
// Medium/Hard: the map is full, so check it. From here on entries are
// checked immediately.
revealAll(silent) {
if (this.gameEnded) return;
this.revealed = true;
let wrong = 0;
for (let r = 0; r < N; r++)
for (let c = 0; c < N; c++) {
if (this.givens[r][c]) continue;
const ok = this.grid[r][c] === this.solution[r][c];
this.cellState[r][c] = ok ? 1 : 2;
if (!ok) wrong++;
}
this.mistakes += wrong;
for (const id of this.meta.cages.keys()) this.drawWash(id);
this.recomputeCageDone(!silent);
this.refreshStats();
this.ruleText?.setText('Map checked: every entry is now checked as you write.');
if (wrong && !silent) {
playSoundEx(this, SFX.CLICK, { rate: 0.5 });
this.toast(`${wrong} cell${wrong > 1 ? "s don't" : " doesn't"} fit. They're hatched in red.`, 3200);
}
this.saveGame();
}
smudge(r, c) {
const g = this.add.graphics().setDepth(D.hover);
g.fillStyle(0x8a8f96, 0.28);
g.fillEllipse(0, 0, 46, 26);
g.fillStyle(0x8a8f96, 0.16);
g.fillEllipse(8, 4, 40, 18);
g.setPosition(cellCX(c), cellCY(r) + 2).setAngle(-12);
this.tweens.add({ targets: g, alpha: 0, scaleX: 1.5, duration: 520, ease: 'Sine.easeOut', onComplete: () => g.destroy() });
}
// A cage is "surveyed" when it holds 1..N (and, when entries are being
// checked, every cell is right). Newly surveyed cages get the flourish.
recomputeCageDone(flourish) {
const checking = this.isChecking();
for (const [id, o] of this.cageObjs) {
const full = cageStatus(this.grid, o.cells) === 'full';
const done = full && (!checking || o.cells.every(({ r, c }) => this.grid[r][c] === this.solution[r][c]));
const was = this.cageDone.has(id);
if (done && !was) {
this.cageDone.add(id);
if (flourish) {
playSoundEx(this, SFX.UI_CHIME, { volume: 0.55, rate: 0.95 + o.slot * 0.02 });
if (o.fill) this.tweens.add({ targets: o.fill, alpha: 1, duration: 420, ease: 'Sine.easeOut' });
this.tweenSeismo(id, 1);
for (const { r, c } of o.cells) {
const t = this.cellText[r][c];
if (t) this.tweens.add({ targets: t, scale: 1.18, duration: 140, yoyo: true, delay: 40 });
}
} else {
o.fill?.setAlpha(1);
this.seismoAmp.set(id, 1);
}
} else if (!done && was) {
this.cageDone.delete(id);
if (o.fill) this.tweens.add({ targets: o.fill, alpha: 0.6, duration: 260 });
this.tweenSeismo(id, 0);
}
}
this.drawSeismo();
}
tweenSeismo(id, to) {
const p = { a: this.seismoAmp.get(id) ?? 0 };
this.tweens.add({
targets: p, a: to, duration: to ? 700 : 300, ease: to ? 'Elastic.easeOut' : 'Sine.easeIn',
onUpdate: () => { this.seismoAmp.set(id, p.a); this.drawSeismo(); },
});
}
doUndo() {
if (this.blocked()) return;
const e = undoEdit(this.history);
if (!e) return;
this.moves++;
this.cursor = { r: e.r, c: e.c };
this.applyCell(e.r, e.c, e.from, { anim: true });
this.drawCursor();
}
doRedo() {
if (this.blocked()) return;
const e = redoEdit(this.history);
if (!e) return;
this.moves++;
this.cursor = { r: e.r, c: e.c };
this.applyCell(e.r, e.c, e.to, { anim: true });
this.drawCursor();
}
// ── Hints ──────────────────────────────────────────────────────────────────
useHint() {
if (this.blocked() || this.hintsLeft <= 0 || this.hintPending) return;
const cell = getHintCell(this.grid, this.solution, this.givens);
if (!cell) return;
const { r, c } = cell;
this.hintPending = true;
this.timerOn = true;
if (Number.isFinite(this.hintsLeft)) this.hintsLeft--;
this.hintsUsed++;
this.moves++;
playSound(this, SFX.UI_ACTIVATE);
const glow = this.add.graphics().setDepth(D.cursor);
glow.fillStyle(0xd4a017, 0.45);
glow.fillRoundedRect(GRID_X + c * CELL + 5, GRID_Y + r * CELL + 5, CELL - 10, CELL - 10, 10);
this.tweens.add({ targets: glow, alpha: 0.2, duration: 220, yoyo: true, repeat: 1 });
if (cell.fix) this.toast('That entry was wrong. The hint corrected it.', 2400);
this.time.delayedCall(520, () => {
glow.destroy();
this.hintPending = false;
if (this.gameEnded || !this.sys.isActive()) return;
this.givens[r][c] = true;
this.hinted.add(`${r},${c}`);
pushMarker(this.history);
this.applyCell(r, c, this.solution[r][c], { anim: true });
});
this.refreshButtons();
this.refreshStats();
}
// ── Timer + pause ──────────────────────────────────────────────────────────
update(_t, delta) {
if (this.mode !== 'play' || !this.timerOn || this.paused || this.gameEnded || this.modal) return;
if (typeof document !== 'undefined' && document.hidden) return;
this.elapsed += delta;
const sec = Math.floor(this.elapsed / 1000);
if (sec !== this._lastSecond) {
this._lastSecond = sec;
this.statTexts?.time.setText(formatTime(this.elapsed));
}
}
setPaused(on) {
if (this.mode !== 'play' || this.gameEnded || this.paused === on) return;
this.paused = on;
playSound(this, SFX.UI_FLIP);
if (on) {
const x = GRID_X - 26, y = GRID_Y - 30, w = GRID_W + 52, h = GRID_W + 60;
const g = this.add.graphics();
g.fillStyle(0x000000, 0.18); g.fillRect(x + 6, y + 8, w, h);
g.fillStyle(0xf6efdc, 1); g.fillRect(x, y, w, h);
g.lineStyle(1, 0x8ab3d8, 0.35);
for (let ly = y + 40; ly < y + h; ly += 34) g.lineBetween(x + 10, ly, x + w - 10, ly);
g.lineStyle(1.5, 0xc0504a, 0.45); g.lineBetween(x + 70, y, x + 70, y + h);
g.lineStyle(2, INK_N, 0.3); g.strokeRect(x, y, w, h);
const t1 = this.add.text(LCX, GRID_Y + GRID_W / 2 - 40, 'Survey paused', {
fontFamily: 'YummyCupcakes', fontSize: '72px', color: TITLE_BLUE,
}).setOrigin(0.5);
const t2 = this.add.text(LCX, GRID_Y + GRID_W / 2 + 34, 'Tap the page or press P to carry on', {
fontFamily: 'YummyCupcakes', fontSize: '32px', color: PENCIL,
}).setOrigin(0.5);
const cont = this.add.container(0, 0, [g, t1, t2]).setDepth(D.flap);
const zone = this.add.zone(x + w / 2, y + h / 2, w, h).setDepth(D.flap + 1).setInteractive({ useHandCursor: true });
zone.on('pointerup', () => this.setPaused(false));
cont.y = -40; cont.alpha = 0;
this.tweens.add({ targets: cont, y: 0, alpha: 1, duration: 260, ease: 'Cubic.easeOut' });
this.flap = { cont, zone };
this.drawHover();
this.saveGame();
} else if (this.flap) {
const { cont, zone } = this.flap;
this.flap = null;
zone.destroy();
this.tweens.add({ targets: cont, y: -40, alpha: 0, duration: 200, onComplete: () => cont.destroy() });
}
this.refreshButtons();
}
// ── New survey / save ──────────────────────────────────────────────────────
newSurvey() {
if (this.modal) return;
const go = () => this.daily ? this.restartWith({ start: true }) : this.restartWith({ difficulty: this.difficulty });
if (this.mode === 'play' && !this.gameEnded && this.moves > 0) {
this.confirm('Abandon this survey?', 'Your progress on this plate map will be lost.', 'Abandon it', () => {
recordGame('tectonic', { won: false, time: Math.round(this.elapsed), moves: this.moves, mode: this.statsMode() });
storage()?.removeItem(SAVE_KEY);
this.moves = 0; // nothing left to save on shutdown
go();
});
return;
}
if (!this.gameEnded) storage()?.removeItem(SAVE_KEY);
go();
}
statsMode() { return this.daily ? 'daily' : this.difficulty; }
saveGame() {
if (this.mode !== 'play' || this.gameEnded || this.moves <= 0 || !this.grid) return;
try {
storage()?.setItem(SAVE_KEY, serialiseSave({
difficulty: this.difficulty, daily: this.daily,
grid: this.grid, solution: this.solution, regions: this.regions, givens: this.givens,
cellState: this.cellState, history: this.history, elapsed: this.elapsed,
hintsLeft: this.hintsLeft, hintsUsed: this.hintsUsed, mistakes: this.mistakes,
revealed: this.revealed, moves: this.moves, surveyNo: this.surveyNo,
hinted: [...this.hinted],
}));
} catch { /* storage full or unavailable */ }
}
// ── Win ────────────────────────────────────────────────────────────────────
handleWin() {
if (this.gameEnded) return;
this.gameEnded = true;
this.timerOn = false;
this.cursor = null; this.armed = null;
this.drawCursor(); this.drawHover(); this.refreshSelector(); this.refreshButtons();
storage()?.removeItem(SAVE_KEY);
const time = Math.round(this.elapsed);
const { stats, newBest } = recordGame('tectonic', {
won: true, time, moves: this.moves, mode: this.statsMode(),
extra: { hints: this.hintsUsed, mistakes: this.mistakes },
});
let daily = null;
if (this.daily) {
const res = updateDaily(readJSON(DAILY_KEY), this.daily, todayString(), time);
writeJSON(DAILY_KEY, res.rec);
daily = res;
}
const score = calcScore(this.difficulty, this.hintsUsed);
api.post('/history/single-player', { slug: 'tectonic', score, opponentScores: [], result: 'win' }).catch(() => {});
this.plateShift();
this.time.delayedCall(1700, () => this.showCertificate({ time, score, stats, newBest, daily }));
}
// Cages lift and settle in a ripple from left to right, with a rumble.
plateShift() {
playSoundEx(this, SFX.DICE_ROLL, { rate: 0.45, volume: 0.5 });
for (const o of this.cageObjs.values()) {
const delay = o.slot * 60;
const dx = (o.slot % 2 ? 1 : -1) * (2 + (o.slot % 3));
this.tweens.add({
targets: o.cont, y: -12, x: dx, duration: 200, delay, ease: 'Sine.easeOut',
onComplete: () => this.tweens.add({ targets: o.cont, y: 0, x: 0, duration: 460, ease: 'Bounce.easeOut' }),
});
if (o.fill) this.tweens.add({ targets: o.fill, alpha: 1, duration: 300, delay });
}
const p = { b: 0 };
this.tweens.add({
targets: p, b: 1, duration: 500, delay: 200, yoyo: true, hold: 300, ease: 'Sine.easeInOut',
onUpdate: () => { this.seismoBurst = p.b; this.drawSeismo(); },
});
}
showCertificate({ time, score, stats, newBest, daily }) {
if (!this.sys.isActive()) return;
playSound(this, SFX.VICTORY_SHORT);
const objs = [];
const dim = this.add.rectangle(W / 2, H / 2, W, H, 0x0a0602, 0.5).setDepth(D.cert).setInteractive();
dim.alpha = 0;
this.tweens.add({ targets: dim, alpha: 1, duration: 300 });
objs.push(dim);
const cont = this.add.container(W / 2, H / 2).setDepth(D.cert + 1);
const cert = this.add.image(0, 0, 'tectonic-cert');
const oy = -cert.height / 2; // texture top
const txt = (x, y, s, size, color, font = 'YummyCupcakes') =>
this.add.text(x, y, s, { fontFamily: font, fontSize: `${size}px`, color, align: 'center' }).setOrigin(0.5);
const site = this.daily ? `Daily Survey of ${this.daily}` : `${DIFF_LABELS[this.difficulty]} site`;
const kids = [
cert,
txt(0, oy + 112, 'Certificate of Survey', 72, '#4a3420'),
txt(0, oy + 278, `This certifies that plate map No. ${this.surveyNo}`, 32, '#5a4630'),
txt(0, oy + 318, `(${site}) was surveyed in full.`, 32, '#5a4630'),
];
[['Time', formatTime(time)], ['Mistakes', String(this.mistakes)], ['Hints', String(this.hintsUsed)], ['Score', `${score} pts`]]
.forEach(([label, value], i) => {
const x = -330 + i * 220;
kids.push(txt(x, oy + 390, label, 24, '#7a6450'));
kids.push(txt(x, oy + 432, value, 44, '#2f3b4a'));
});
let note;
if (daily) note = `Daily streak: ${daily.streak} day${daily.streak === 1 ? '' : 's'}${daily.newBestTime ? ' · new best for today!' : ''}`;
else if (newBest.time) note = 'A new best time for this site!';
else if (stats.won === 1) note = 'Your first survey at this site.';
else note = `Best ${formatTime(stats.bestTime)} · Streak ${stats.streak}${newBest.streak ? ' (a new record!)' : ''}`;
kids.push(txt(0, oy + 498, note, 30, newBest.time || daily?.newBestTime ? '#a0402f' : '#5a4630'));
cont.add(kids);
cont.y = H + 400; cont.angle = -4;
this.tweens.add({ targets: cont, y: H / 2 - 30, angle: -1, duration: 520, ease: 'Back.easeOut' });
objs.push(cont);
// stamp
this.time.delayedCall(700, () => {
if (!this.sys.isActive()) return;
const stamp = this.add.container(W / 2 + 320, H / 2 - 170).setDepth(D.cert + 3);
const sg = this.add.graphics();
sg.lineStyle(5, 0xb3352a, 0.85); sg.strokeRoundedRect(-150, -42, 300, 84, 12);
sg.lineStyle(2, 0xb3352a, 0.6); sg.strokeRoundedRect(-140, -33, 280, 66, 9);
const st = this.add.text(0, 2, 'SURVEYED', { fontFamily: 'Righteous', fontSize: '50px', color: '#b3352a' }).setOrigin(0.5).setAlpha(0.9);
stamp.add([sg, st]);
stamp.setAngle(-14).setScale(2.4).setAlpha(0);
this.tweens.add({
targets: stamp, scale: 1, alpha: 0.88, duration: 220, ease: 'Quad.easeIn',
onComplete: () => { playSound(this, SFX.KART_THUMP); this.cameras.main.shake(120, 0.003); },
});
objs.push(stamp);
});
const by = H / 2 - 30 + 250;
this.time.delayedCall(560, () => {
if (!this.sys.isActive()) return;
const again = this.daily
? new PaperButton(this, W / 2 - 150, by, 'Back to sites', () => this.restartWith({ start: true }), { width: 250, accent: true })
: new PaperButton(this, W / 2 - 150, by, 'New survey', () => this.restartWith({ difficulty: this.difficulty }), { width: 250, accent: true });
const lv = new PaperButton(this, W / 2 + 150, by, 'Leave', () => this.scene.start('GameMenu'), { width: 250 });
again.setDepth(D.cert + 2); lv.setDepth(D.cert + 2);
});
}
// ── Modals + toast ─────────────────────────────────────────────────────────
openModal(build) {
if (this.modal) return null;
const objs = [];
const dim = this.add.rectangle(W / 2, H / 2, W, H, 0x0a0602, 0.55).setDepth(D.modal).setInteractive();
objs.push(dim);
const modal = { objs, close: () => {
for (const o of objs) o.destroy();
if (this.modal === modal) this.modal = null;
} };
this.modal = modal;
build(objs, modal);
return modal;
}
confirm(title, body, yesLabel, onYes) {
this.openModal((objs, modal) => {
const g = this.add.graphics().setDepth(D.modal + 1);
const x = W / 2 - 380, y = H / 2 - 170;
g.fillStyle(0x000000, 0.25); g.fillRect(x + 8, y + 10, 760, 340);
g.fillStyle(0xfbf8ee, 1); g.fillRect(x, y, 760, 340);
g.lineStyle(1, 0x8ab3d8, 0.35);
for (let ly = y + 60; ly < y + 340; ly += 32) g.lineBetween(x + 14, ly, x + 746, ly);
g.lineStyle(2, INK_N, 0.45); g.strokeRect(x, y, 760, 340);
objs.push(g);
objs.push(this.add.text(W / 2, y + 74, title, {
fontFamily: 'YummyCupcakes', fontSize: '54px', color: INK,
}).setOrigin(0.5).setDepth(D.modal + 2));
objs.push(this.add.text(W / 2, y + 150, body, {
fontFamily: 'YummyCupcakes', fontSize: '30px', color: PENCIL, align: 'center', wordWrap: { width: 660 },
}).setOrigin(0.5).setDepth(D.modal + 2));
objs.push(new PaperButton(this, W / 2 - 150, y + 260, yesLabel, () => { modal.close(); onYes(); }, { width: 250, accent: true }).setDepth(D.modal + 2));
objs.push(new PaperButton(this, W / 2 + 150, y + 260, 'Keep going', () => modal.close(), { width: 250 }).setDepth(D.modal + 2));
});
}
openGuide() {
if (this.modal) return;
playSound(this, SFX.UI_FLIP);
this.openModal((objs, modal) => {
const add = (o) => { objs.push(o.setDepth?.(D.modal + 2) ?? o); return o; };
const x = W / 2 - 560, y = H / 2 - 370, w = 1120, h = 740;
const g = this.add.graphics().setDepth(D.modal + 1);
g.fillStyle(0x000000, 0.28); g.fillRect(x + 10, y + 12, w, h);
g.fillStyle(0xfbf8ee, 1); g.fillRect(x, y, w, h);
g.lineStyle(1, 0x8ab3d8, 0.28);
for (let gx = x + 28; gx < x + w; gx += 28) g.lineBetween(gx, y, gx, y + h);
for (let gy = y + 28; gy < y + h; gy += 28) g.lineBetween(x, gy, x + w, gy);
g.lineStyle(2, INK_N, 0.45); g.strokeRect(x, y, w, h);
objs.push(g);
add(this.add.text(W / 2, y + 66, 'Field Guide', { fontFamily: 'YummyCupcakes', fontSize: '72px', color: TITLE_BLUE }).setOrigin(0.5));
const cell = 64;
const ig = this.add.graphics().setDepth(D.modal + 2);
objs.push(ig);
const plate = (cells, ox, oy, toneIdx) => {
const tone = Phaser.Display.Color.HexStringToColor(TONES[toneIdx].fill).color;
ig.fillStyle(tone, 0.35);
for (const { r, c } of cells) ig.fillRect(ox + c * cell, oy + r * cell, cell, cell);
ig.lineStyle(3, INK_N, 0.9);
const loop = insetLoop(traceCage(cells), 3 / cell);
ig.strokePoints(loop.map(([lx, ly]) => ({ x: ox + lx * cell, y: oy + ly * cell })), true, true);
add(this.add.text(ox + cells[0].c * cell + 8, oy + cells[0].r * cell + 6, String(cells.length), {
fontFamily: 'Righteous', fontSize: '15px', color: PENCIL,
}));
};
const num = (ox, oy, r, c, v, given = true, color = null) => add(this.add.text(ox + c * cell + cell / 2, oy + r * cell + cell / 2 + 1, String(v), {
fontFamily: given ? 'Righteous' : 'YummyCupcakes', fontSize: given ? '36px' : '44px', color: color ?? (given ? INK : BLUE_INK),
}).setOrigin(0.5));
// fig. 1: plates hold 1..N
const ax = x + 120, ay = y + 170;
plate([{ r: 0, c: 0 }, { r: 1, c: 0 }, { r: 2, c: 0 }, { r: 2, c: 1 }], ax, ay, 0);
[[0, 0, 2], [1, 0, 4], [2, 0, 1], [2, 1, 3]].forEach(([r, c, v]) => num(ax, ay, r, c, v, false));
plate([{ r: 0, c: 3 }, { r: 1, c: 3 }], ax, ay, 1);
num(ax, ay, 0, 3, 1, false); num(ax, ay, 1, 3, 2, false);
plate([{ r: 2, c: 4 }], ax, ay, 2);
num(ax, ay, 2, 4, 1, false);
add(this.add.text(x + 290, y + 400, 'fig. 1: a plate of N cells holds\neach number from 1 to N exactly once.', {
fontFamily: 'YummyCupcakes', fontSize: '28px', color: INK, align: 'center', lineSpacing: 4,
}).setOrigin(0.5, 0));
// fig. 2: touching twins
const bx = x + 700, by = y + 170;
ig.fillStyle(RED_PENCIL, 0.10);
for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) if (r !== 1 || c !== 1) ig.fillRect(bx + c * cell, by + r * cell, cell, cell);
ig.lineStyle(1.5, 0x6f9fca, 0.7);
for (let i = 0; i <= 3; i++) {
ig.lineBetween(bx + i * cell, by, bx + i * cell, by + 3 * cell);
ig.lineBetween(bx, by + i * cell, bx + 3 * cell, by + i * cell);
}
num(bx, by, 1, 1, 3);
num(bx, by, 0, 2, 3, false);
num(bx, by, 2, 0, 2, false);
ig.lineStyle(4, RED_PENCIL, 0.9);
ig.lineBetween(bx + 2 * cell + 14, by + 14, bx + 3 * cell - 14, by + cell - 14);
ig.lineBetween(bx + 3 * cell - 14, by + 14, bx + 2 * cell + 14, by + cell - 14);
add(this.add.text(bx + 1.5 * cell, y + 400, 'fig. 2: touching cells never match,\nnot even corner to corner.', {
fontFamily: 'YummyCupcakes', fontSize: '28px', color: INK, align: 'center', lineSpacing: 4,
}).setOrigin(0.5, 0));
add(this.add.text(W / 2, y + 540,
'Pick a specimen tag, then tap cells, or tap a cell, then a tag (or type 1–5).\n' +
'Arrows move · Backspace erases · Ctrl+Z / Ctrl+Y undo and redo · H hint · P pause\n' +
'Your survey saves itself. Leave any time and resume it from the start page.', {
fontFamily: 'YummyCupcakes', fontSize: '27px', color: PENCIL, align: 'center', lineSpacing: 8,
}).setOrigin(0.5));
const closeModal = modal.close;
modal.close = () => { storage()?.setItem(GUIDE_SEEN_KEY, '1'); closeModal(); };
add(new PaperButton(this, W / 2, y + h - 66, 'Got it', () => modal.close(), { width: 230, accent: true }));
});
}
toast(text, ms = 2600) {
if (this.toastObj) { this.tweens.killTweensOf(this.toastObj); this.toastObj.destroy(); }
const cont = this.add.container(RCX, 836).setDepth(D.toast);
const t = this.add.text(0, 0, text, {
fontFamily: 'YummyCupcakes', fontSize: '28px', color: '#3d3420', align: 'center', wordWrap: { width: 500 },
}).setOrigin(0.5);
const w = Math.max(360, t.width + 60), h = t.height + 46;
const g = this.add.graphics();
g.fillStyle(0x000000, 0.2); g.fillRect(-w / 2 + 5, -h / 2 + 6, w, h);
g.fillStyle(0xf7e58a, 1); g.fillRect(-w / 2, -h / 2, w, h);
g.fillStyle(0xe9d16a, 1); g.fillRect(-w / 2, -h / 2, w, 14);
cont.add([g, t]);
cont.setAngle(-1.5).setAlpha(0).setScale(0.9);
this.toastObj = cont;
this.tweens.add({ targets: cont, alpha: 1, scale: 1, duration: 180, ease: 'Back.easeOut' });
this.tweens.add({
targets: cont, alpha: 0, delay: ms, duration: 400,
onComplete: () => { if (this.toastObj === cont) this.toastObj = null; cont.destroy(); },
});
}
}