Rewrite chess as 'The Stone Tables' with puzzles, timing, and park theme

- Replace the basic alpha-beta AI with a negamax engine (iterative
  deepening, transposition table, SEE quiescence, null-move pruning,
  LMR, reverse futility) run in a Web Worker so the scene stays alive
- Rework ChessLogic to a 0x88 board with make/unmake, Zobrist hashing,
  Chess960, threefold/fifty-move rules, and full SAN/UCI/FEN/PGN I/O
- Add a procedurally baked "city park at dusk" art pipeline (board,
  pieces, fountain, pigeons, string lights) with no image assets
- Build out the full game surface: setup card (colour, clock, 960),
  pause menu, promotion picker, end screen with eval graph and replay,
  score sheet, analog clock, evaluation bar, and character dialogue
- Introduce a puzzle ladder (Elo-rated, near your skill) and a daily
  puzzle with streak tracking; 223 tactics generated by self-play
- Add Web Audio synth SFX (clacks, captures, check, promotion, flag)
  plus ambient park sound (wind, fountain, pigeons, a distant busker)
- Ship tools/verifyChess.js (perft, rules, 960, notation, book,
  puzzles, engine, self-play, layout) and tools/genChessPuzzles.js
  for regenerating the puzzle set
This commit is contained in:
Brian Fertig 2026-12-01 19:00:54 -07:00
parent 50078661d2
commit 8b1e77b0aa
19 changed files with 6913 additions and 950 deletions

View File

@ -1,173 +1,670 @@
// Chess AI — alpha-beta minimax with piece-square tables and a Nerts-style
// 1..5 skill model.
// • depth — search depth in plies (capped for browser responsiveness)
// • blunder — chance to ignore the best move and play a random legal one
// • noise — random value added to root move scores (flattens decisions)
// • delay — "thinking" pause (ms range) before moving, for natural pacing
// Captures are searched first so alpha-beta prunes hard at the higher depths.
// ChessAI.js — the engine behind every opponent at the Stone Tables.
//
// Negamax / principal-variation search on ChessLogic's 0x88 position with
// make/unmake; iterative deepening inside a time budget; a transposition
// table; quiescence search with static exchange (SEE) pruning; killer and
// history move ordering; null-move pruning, late-move reductions, reverse
// futility pruning and check extensions; a tapered evaluation (material,
// piece-square tables, pawn structure, passed pawns, king shelter, mobility,
// bishop pair, rooks on open files, mop-up for won endgames).
//
// Skill 1..5 shapes the time/depth budget, scoring noise, and how often the
// opponent "slips" to a weaker candidate — so a rookie hangs pieces and a
// shark plays like a strong club player (~1800–2000 at the top).
//
// API
// chooseMove(game, skill, { ms, rng }) → { m, score, book, opening }
// bestMove(pos, { ms, depth }) → { m, score, depth, pv }
// analyze(pos, { ms, depth, margin }) → [{ m, score }] best first
// evaluateWhite(pos, { ms }) → centipawns from White's side
// describeIdea(pos, m, score) → a short plain-English reason
// wantsDraw / drawDecision / shouldResign → the opponent's table manners
import {
getLegalMoves, applyMoveRaw, isKingAttacked, SIZE,
} from './ChessLogic.js';
import * as L from './ChessLogic.js';
import { bookMoves } from './ChessBook.js';
const SKILL_PROFILES = {
1: { depth: 1, blunder: 0.45, noise: 90, delay: [900, 1500] },
2: { depth: 2, blunder: 0.30, noise: 55, delay: [800, 1300] },
3: { depth: 2, blunder: 0.15, noise: 30, delay: [700, 1100] },
4: { depth: 3, blunder: 0.05, noise: 12, delay: [550, 950] },
5: { depth: 4, blunder: 0.00, noise: 0, delay: [450, 850] },
const { P, N, B, R, Q, K, WHITE, BLACK } = L;
export const MATE = 30000;
const MATE_BOUND = MATE - 512;
const INF = 32000;
export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
export const PROFILES = {
1: { ms: 120, depth: 2, noise: 150, slip: 0.30, topN: 6, wild: 0.08, bookPly: 4 },
2: { ms: 220, depth: 3, noise: 70, slip: 0.16, topN: 4, wild: 0.02, bookPly: 6 },
3: { ms: 450, depth: 5, noise: 32, slip: 0.07, topN: 3, wild: 0, bookPly: 10 },
4: { ms: 900, depth: 8, noise: 12, slip: 0.025, topN: 2, wild: 0, bookPly: 16 },
5: { ms: 1500, depth: 64, noise: 0, slip: 0, topN: 1, wild: 0, bookPly: 24 },
};
export const profileOf = (skill) => PROFILES[clampSkill(skill)];
const VALUE = { p: 100, n: 320, b: 330, r: 500, q: 900, k: 0 };
const MATE = 1000000;
// ── evaluation ─────────────────────────────────────────────────────────────
const MG_VAL = [0, 90, 320, 335, 480, 950, 0];
const EG_VAL = [0, 115, 300, 320, 530, 980, 0];
const PHASE_W = [0, 0, 1, 1, 2, 4, 0];
const PST = {
p: [
[0, 0, 0, 0, 0, 0, 0, 0],
[50, 50, 50, 50, 50, 50, 50, 50],
[10, 10, 20, 30, 30, 20, 10, 10],
[5, 5, 10, 25, 25, 10, 5, 5],
[0, 0, 0, 20, 20, 0, 0, 0],
[5, -5, -10, 0, 0, -10, -5, 5],
[5, 10, 10, -20, -20, 10, 10, 5],
[0, 0, 0, 0, 0, 0, 0, 0],
],
n: [
[-50, -40, -30, -30, -30, -30, -40, -50],
[-40, -20, 0, 0, 0, 0, -20, -40],
[-30, 0, 10, 15, 15, 10, 0, -30],
[-30, 5, 15, 20, 20, 15, 5, -30],
[-30, 0, 15, 20, 20, 15, 0, -30],
[-30, 5, 10, 15, 15, 10, 5, -30],
[-40, -20, 0, 5, 5, 0, -20, -40],
[-50, -40, -30, -30, -30, -30, -40, -50],
],
b: [
[-20, -10, -10, -10, -10, -10, -10, -20],
[-10, 0, 0, 0, 0, 0, 0, -10],
[-10, 0, 5, 10, 10, 5, 0, -10],
[-10, 5, 5, 10, 10, 5, 5, -10],
[-10, 0, 10, 10, 10, 10, 0, -10],
[-10, 10, 10, 10, 10, 10, 10, -10],
[-10, 5, 0, 0, 0, 0, 5, -10],
[-20, -10, -10, -10, -10, -10, -10, -20],
],
r: [
[0, 0, 0, 0, 0, 0, 0, 0],
[5, 10, 10, 10, 10, 10, 10, 5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[0, 0, 0, 5, 5, 0, 0, 0],
],
q: [
[-20, -10, -10, -5, -5, -10, -10, -20],
[-10, 0, 0, 0, 0, 0, 0, -10],
[-10, 0, 5, 5, 5, 5, 0, -10],
[-5, 0, 5, 5, 5, 5, 0, -5],
[0, 0, 5, 5, 5, 5, 0, -5],
[-10, 5, 5, 5, 5, 5, 0, -10],
[-10, 0, 5, 0, 0, 0, 0, -10],
[-20, -10, -10, -5, -5, -10, -10, -20],
],
k: [
[-30, -40, -40, -50, -50, -40, -40, -30],
[-30, -40, -40, -50, -50, -40, -40, -30],
[-30, -40, -40, -50, -50, -40, -40, -30],
[-30, -40, -40, -50, -50, -40, -40, -30],
[-20, -30, -30, -40, -40, -30, -30, -20],
[-10, -20, -20, -20, -20, -20, -20, -10],
[20, 20, 0, 0, 0, 0, 20, 20],
[20, 30, 10, 0, 0, 10, 30, 20],
],
// tables from White's point of view, row 0 = rank 8
const T = (rows) => {
const t = new Int16Array(128);
for (let r = 0; r < 8; r++) for (let f = 0; f < 8; f++) t[r * 16 + f] = rows[r][f];
return t;
};
const PST_MG = [null,
T([[0, 0, 0, 0, 0, 0, 0, 0], [50, 50, 50, 50, 50, 50, 50, 50], [10, 10, 20, 30, 30, 20, 10, 10], [5, 5, 10, 25, 25, 10, 5, 5],
[0, 0, 0, 22, 22, 0, 0, 0], [5, -5, -10, 2, 2, -10, -5, 5], [5, 10, 10, -22, -22, 10, 10, 5], [0, 0, 0, 0, 0, 0, 0, 0]]),
T([[-50, -40, -30, -30, -30, -30, -40, -50], [-40, -20, 0, 0, 0, 0, -20, -40], [-30, 0, 10, 15, 15, 10, 0, -30], [-30, 5, 15, 20, 20, 15, 5, -30],
[-30, 0, 15, 20, 20, 15, 0, -30], [-30, 5, 10, 15, 15, 10, 5, -30], [-40, -20, 0, 5, 5, 0, -20, -40], [-50, -35, -30, -30, -30, -30, -35, -50]]),
T([[-20, -10, -10, -10, -10, -10, -10, -20], [-10, 0, 0, 0, 0, 0, 0, -10], [-10, 0, 5, 10, 10, 5, 0, -10], [-10, 5, 5, 10, 10, 5, 5, -10],
[-10, 0, 10, 10, 10, 10, 0, -10], [-10, 10, 10, 10, 10, 10, 10, -10], [-10, 8, 0, 0, 0, 0, 8, -10], [-20, -10, -12, -10, -10, -12, -10, -20]]),
T([[0, 0, 0, 0, 0, 0, 0, 0], [5, 10, 10, 10, 10, 10, 10, 5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [0, 0, 0, 5, 5, 3, 0, 0]]),
T([[-20, -10, -10, -5, -5, -10, -10, -20], [-10, 0, 0, 0, 0, 0, 0, -10], [-10, 0, 5, 5, 5, 5, 0, -10], [-5, 0, 5, 5, 5, 5, 0, -5],
[0, 0, 5, 5, 5, 5, 0, -5], [-10, 5, 5, 5, 5, 5, 0, -10], [-10, 0, 5, 0, 0, 0, 0, -10], [-20, -10, -10, -5, -5, -10, -10, -20]]),
T([[-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30],
[-20, -30, -30, -40, -40, -30, -30, -20], [-10, -20, -20, -20, -20, -20, -20, -10], [20, 20, -5, -5, -5, -5, 20, 20], [20, 30, 10, 0, 0, 10, 30, 20]]),
];
const PST_EG = [null,
T([[0, 0, 0, 0, 0, 0, 0, 0], [80, 80, 80, 80, 80, 80, 80, 80], [50, 50, 50, 50, 50, 50, 50, 50], [30, 30, 30, 30, 30, 30, 30, 30],
[15, 15, 15, 15, 15, 15, 15, 15], [5, 5, 5, 5, 5, 5, 5, 5], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]),
PST_MG[2], PST_MG[3],
T([[0, 0, 0, 0, 0, 0, 0, 0], [5, 5, 5, 5, 5, 5, 5, 5], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]),
PST_MG[5],
T([[-50, -40, -30, -20, -20, -30, -40, -50], [-30, -20, -10, 0, 0, -10, -20, -30], [-30, -10, 20, 30, 30, 20, -10, -30], [-30, -10, 30, 40, 40, 30, -10, -30],
[-30, -10, 30, 40, 40, 30, -10, -30], [-30, -10, 20, 30, 30, 20, -10, -30], [-30, -30, 0, 0, 0, 0, -30, -30], [-50, -30, -30, -30, -30, -30, -30, -50]]),
];
const PASS_MG = [0, 5, 10, 15, 25, 40, 60, 0];
const PASS_EG = [0, 10, 20, 35, 60, 100, 150, 0];
const KN_D = [-33, -31, -18, -14, 14, 18, 31, 33];
const BI_D = [-17, -15, 15, 17];
const RO_D = [-16, -1, 1, 16];
function profileFor(skill) {
return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3];
const wMax = new Int8Array(10), bMin = new Int8Array(10), wCnt = new Int8Array(10), bCnt = new Int8Array(10);
/** Static evaluation from the side to move's point of view. */
export function evaluate(pos) {
const b = pos.b;
let mg = 0, eg = 0, phase = 0;
let wb = 0, bb = 0, wMat = 0, bMat = 0, wPieces = 0, bPieces = 0;
wMax.fill(-1); bMin.fill(8); wCnt.fill(0); bCnt.fill(0);
// pass 1: pawns per file
for (let s = 0; s < 128; s++) {
if (s & 0x88) { s += 7; continue; }
const p = b[s];
if ((p & 7) !== P) continue;
const f = (s & 7) + 1, r = s >> 4;
if (p === P) { wCnt[f]++; if (r > wMax[f]) wMax[f] = r; } else { bCnt[f]++; if (r < bMin[f]) bMin[f] = r; }
}
for (let s = 0; s < 128; s++) {
if (s & 0x88) { s += 7; continue; }
const p = b[s];
if (!p) continue;
const t = p & 7, white = p < 8;
const r = s >> 4, f = s & 7;
const idx = white ? s : ((7 - r) << 4) | f;
let m = MG_VAL[t] + PST_MG[t][idx], e = EG_VAL[t] + PST_EG[t][idx];
phase += PHASE_W[t];
if (t === P) {
const F = f + 1;
if (white) {
if (wCnt[F] > 1) { m -= 10; e -= 18; }
if (!wCnt[F - 1] && !wCnt[F + 1]) { m -= 12; e -= 14; }
if (bMin[F - 1] >= r && bMin[F] >= r && bMin[F + 1] >= r) { const rr = 7 - r; m += PASS_MG[rr]; e += PASS_EG[rr]; }
} else {
if (bCnt[F] > 1) { m -= 10; e -= 18; }
if (!bCnt[F - 1] && !bCnt[F + 1]) { m -= 12; e -= 14; }
if (wMax[F - 1] <= r && wMax[F] <= r && wMax[F + 1] <= r) { const rr = r; m += PASS_MG[rr]; e += PASS_EG[rr]; }
}
} else if (t === N) {
let mob = 0;
for (let i = 0; i < 8; i++) { const d = s + KN_D[i]; if (!(d & 0x88)) { const q = b[d]; if (!q || (q < 8) !== white) mob++; } }
m += (mob - 4) * 4; e += (mob - 4) * 4;
} else if (t === B || t === R || t === Q) {
if (t === B) { if (white) wb++; else bb++; }
const D = t === B ? BI_D : RO_D;
let mob = 0;
if (t !== Q) {
for (let i = 0; i < 4; i++) {
const dd = D[i];
let d = s + dd;
while (!(d & 0x88)) { const q = b[d]; if (!q) mob++; else { if ((q < 8) !== white) mob++; break; } d += dd; }
}
if (t === B) { m += (mob - 6) * 4; e += (mob - 6) * 5; } else { m += (mob - 6) * 2; e += (mob - 6) * 4; }
}
if (t === R) {
const F = f + 1;
const own = white ? wCnt[F] : bCnt[F], opp = white ? bCnt[F] : wCnt[F];
if (!own) { if (!opp) { m += 22; e += 10; } else { m += 10; e += 5; } }
if ((white && r === 1) || (!white && r === 6)) { m += 10; e += 18; }
}
} else if (t === K) {
// pawn shelter in front of a castled-looking king
const dir = white ? -16 : 16;
let sh = 0;
for (let df = -1; df <= 1; df++) {
const c = s + dir + df;
if (c & 0x88) continue;
if (b[c] === (white ? P : P | 8)) sh += 12;
else if (!((c + dir) & 0x88) && b[c + dir] === (white ? P : P | 8)) sh += 6;
else sh -= 8;
}
m += sh;
}
if (t !== P && t !== K) { if (white) { wMat += MG_VAL[t]; wPieces++; } else { bMat += MG_VAL[t]; bPieces++; } }
if (white) { mg += m; eg += e; } else { mg -= m; eg -= e; }
}
if (wb >= 2) { mg += 30; eg += 45; }
if (bb >= 2) { mg -= 30; eg -= 45; }
if (phase > 24) phase = 24;
let score = Math.round((mg * phase + eg * (24 - phase)) / 24);
// mop-up: drive a lone king to the edge and walk ours over
const diff = wMat - bMat;
if (phase <= 8 && Math.abs(diff) >= 300) {
const strong = diff > 0 ? WHITE : BLACK;
const weakK = pos.kings[strong ^ 1], strongK = pos.kings[strong];
const wr = weakK >> 4, wf = weakK & 7, sr = strongK >> 4, sf = strongK & 7;
const centre = Math.max(3 - wr, wr - 4) + Math.max(3 - wf, wf - 4);
const dist = Math.abs(wr - sr) + Math.abs(wf - sf);
const bonus = centre * 12 + (14 - dist) * 5;
score += strong === WHITE ? bonus : -bonus;
}
// a minor piece up with no pawns can't win
if (!wCnt.some((x) => x) && wMat - bMat < 400 && wMat <= 335 + 0 && score > 0) score >>= 3;
if (!bCnt.some((x) => x) && bMat - wMat < 400 && bMat <= 335 && score < 0) score >>= 3;
void wPieces; void bPieces;
score += pos.side === WHITE ? 10 : -10;
return pos.side === WHITE ? score : -score;
}
export function nextThinkDelay(skill) {
const [lo, hi] = profileFor(skill).delay;
return lo + Math.random() * (hi - lo);
// ── static exchange evaluation ─────────────────────────────────────────────
const SEE_VAL = [0, 100, 320, 330, 500, 900, 20000];
function leastAttacker(pos, sq, side) {
const att = L.attackersOf(pos, sq, side);
let best = -1, bv = 1e9;
for (const s of att) { const v = SEE_VAL[pos.b[s] & 7]; if (v < bv) { bv = v; best = s; } }
return best;
}
/** Material balance (for the mover) of the capture sequence on the move's target. */
export function see(pos, m) {
const from = m & 127, to = (m >> 7) & 127, fl = (m >> 17) & 15, promo = (m >> 14) & 7;
if (fl & L.F_CASTLE) return 0;
const b = pos.b;
const saved = [];
const set = (s, v) => { saved.push(s, b[s]); b[s] = v; };
let side = pos.side;
const gain = [SEE_VAL[(fl & L.F_EP) ? P : (b[to] & 7)]];
const mover = b[from];
let onSq = promo || (mover & 7);
if (fl & L.F_EP) set(to + (side === WHITE ? 16 : -16), 0);
set(to, promo ? (promo | (side << 3)) : mover);
set(from, 0);
let d = 0;
for (;;) {
side ^= 1;
const a = leastAttacker(pos, to, side);
if (a < 0) break;
d++;
gain[d] = SEE_VAL[onSq] - gain[d - 1];
if (Math.max(-gain[d - 1], gain[d]) < 0) break;
onSq = b[a] & 7;
set(to, b[a]);
set(a, 0);
}
while (d > 0) { gain[d - 1] = -Math.max(-gain[d - 1], gain[d]); d--; }
for (let i = saved.length - 2; i >= 0; i -= 2) b[saved[i]] = saved[i + 1];
return gain[0];
}
// Static evaluation from `aiColor`'s perspective (positive = good for AI).
function evaluate(board, aiColor) {
let score = 0; // white's perspective
for (let r = 0; r < SIZE; r++) {
for (let c = 0; c < SIZE; c++) {
const p = board[r][c];
if (!p) continue;
const table = PST[p.type];
const pst = p.color === 'white' ? table[r][c] : table[SIZE - 1 - r][c];
const v = VALUE[p.type] + pst;
score += p.color === 'white' ? v : -v;
// ── transposition table ────────────────────────────────────────────────────
const TT_BITS = 20, TT_SIZE = 1 << TT_BITS, TT_MASK = TT_SIZE - 1;
const ttKey = new Int32Array(TT_SIZE), ttMove = new Int32Array(TT_SIZE), ttScore = new Int16Array(TT_SIZE);
const ttDepth = new Int8Array(TT_SIZE), ttFlag = new Uint8Array(TT_SIZE);
const EXACT = 1, LOWER = 2, UPPER = 3;
export function clearTT() { ttKey.fill(0); ttMove.fill(0); ttFlag.fill(0); }
function ttStore(pos, depth, score, flag, move, ply) {
const i = pos.lo & TT_MASK;
if (ttFlag[i] && ttKey[i] === pos.hi && ttDepth[i] > depth && flag !== EXACT) return;
if (score > MATE_BOUND) score += ply; else if (score < -MATE_BOUND) score -= ply;
ttKey[i] = pos.hi; ttMove[i] = move; ttScore[i] = score; ttDepth[i] = depth; ttFlag[i] = flag;
}
// ── search ─────────────────────────────────────────────────────────────────
class Searcher {
constructor(pos, { ms = 1000, depth = 64, rootFilter = null } = {}) {
this.pos = pos;
this.deadline = Date.now() + ms;
this.maxDepth = depth;
this.nodes = 0;
this.stop = false;
this.killers = new Int32Array(256);
this.history = new Int32Array(16 * 128);
this.rootFilter = rootFilter;
}
timeUp() {
if ((++this.nodes & 1023) === 0 && Date.now() > this.deadline) this.stop = true;
return this.stop;
}
isDraw(ply) {
const pos = this.pos;
if (pos.half >= 100) return true;
const Lh = pos.histLo.length;
const lim = Math.max(0, Lh - pos.half);
for (let i = Lh - 2; i >= lim; i -= 2) {
if (pos.histLo[i] === pos.lo && pos.histHi[i] === pos.hi) return true;
}
void ply;
return L.insufficientMaterial(pos);
}
scoreMoves(moves, ttm, ply) {
const b = this.pos.b;
const scores = new Int32Array(moves.length);
const k0 = this.killers[ply * 2], k1 = this.killers[ply * 2 + 1];
for (let i = 0; i < moves.length; i++) {
const m = moves[i];
if (m === ttm) { scores[i] = 2e9; continue; }
const fl = (m >> 17) & 15, to = (m >> 7) & 127, from = m & 127;
const promo = (m >> 14) & 7;
if (fl & L.F_CAP) {
const v = (fl & L.F_EP) ? P : (b[to] & 7);
scores[i] = 1e8 + SEE_VAL[v] * 10 - SEE_VAL[b[from] & 7] / 10 + (promo === Q ? 5e6 : 0);
} else if (promo) scores[i] = promo === Q ? 9e7 : -1e6;
else if (m === k0) scores[i] = 8e7;
else if (m === k1) scores[i] = 7e7;
else scores[i] = this.history[b[from] * 128 + to];
}
return scores;
}
qsearch(alpha, beta, ply) {
if (this.timeUp()) return 0;
const pos = this.pos;
const stand = evaluate(pos);
if (stand >= beta) return stand;
if (stand > alpha) alpha = stand;
if (ply > 60) return stand;
const moves = L.genMoves(pos, [], true);
const scores = this.scoreMoves(moves, 0, Math.min(ply, 127));
for (let i = 0; i < moves.length; i++) {
let bi = i;
for (let j = i + 1; j < moves.length; j++) if (scores[j] > scores[bi]) bi = j;
const m = moves[bi]; moves[bi] = moves[i]; moves[i] = m;
const sc = scores[bi]; scores[bi] = scores[i]; scores[i] = sc;
const fl = (m >> 17) & 15, promo = (m >> 14) & 7;
if (fl & L.F_CAP && !promo) {
const v = (fl & L.F_EP) ? P : (pos.b[(m >> 7) & 127] & 7);
if (stand + SEE_VAL[v] + 200 < alpha) continue; // delta pruning
if (see(pos, m) < 0) continue; // losing capture
} else if (promo && promo !== Q) continue;
if (!L.makeMove(pos, m)) continue;
const s = -this.qsearch(-beta, -alpha, ply + 1);
L.unmakeMove(pos);
if (this.stop) return 0;
if (s > alpha) { alpha = s; if (s >= beta) return s; }
}
return alpha;
}
search(depth, alpha, beta, ply, nullOk = true) {
const pos = this.pos;
if (this.timeUp()) return 0;
if (ply > 0) {
if (this.isDraw(ply)) return 0;
// mate-distance pruning
const ma = -MATE + ply, mb = MATE - ply - 1;
if (ma > alpha) alpha = ma;
if (mb < beta) beta = mb;
if (alpha >= beta) return alpha;
}
const inCheck = pos.inCheck();
if (inCheck && ply < 60) depth++;
if (depth <= 0) return this.qsearch(alpha, beta, ply);
const pv = beta - alpha > 1;
// transposition table
const ti = pos.lo & TT_MASK;
let ttm = 0;
if (ttFlag[ti] && ttKey[ti] === pos.hi) {
ttm = ttMove[ti];
if (ply > 0 && ttDepth[ti] >= depth && !pv) {
let s = ttScore[ti];
if (s > MATE_BOUND) s -= ply; else if (s < -MATE_BOUND) s += ply;
const f = ttFlag[ti];
if (f === EXACT || (f === LOWER && s >= beta) || (f === UPPER && s <= alpha)) return s;
}
}
let staticEval = 0;
if (!pv && !inCheck) {
staticEval = evaluate(pos);
// reverse futility
if (depth <= 3 && staticEval - 110 * depth >= beta && Math.abs(beta) < MATE_BOUND) return staticEval;
// null move
if (nullOk && depth >= 3 && staticEval >= beta && this.hasPieces(pos.side)) {
const r = depth >= 6 ? 3 : 2;
L.makeNull(pos);
const s = -this.search(depth - 1 - r, -beta, -beta + 1, ply + 1, false);
L.unmakeNull(pos);
if (this.stop) return 0;
if (s >= beta) return Math.abs(s) > MATE_BOUND ? beta : s;
}
}
const moves = L.genMoves(pos, []);
let filter = null;
if (ply === 0 && this.rootFilter) filter = this.rootFilter;
const scores = this.scoreMoves(moves, ttm, ply);
let legal = 0, best = -INF, bestMove = 0;
const a0 = alpha;
for (let i = 0; i < moves.length; i++) {
let bi = i;
for (let j = i + 1; j < moves.length; j++) if (scores[j] > scores[bi]) bi = j;
const m = moves[bi]; moves[bi] = moves[i]; moves[i] = m;
const sc = scores[bi]; scores[bi] = scores[i]; scores[i] = sc;
if (filter && !filter.has(m)) continue;
const fl = (m >> 17) & 15;
const quiet = !(fl & L.F_CAP) && !((m >> 14) & 7);
// futility at the frontier for quiet moves
if (!pv && !inCheck && quiet && depth === 1 && legal > 0 && staticEval + 150 < alpha) {
if (!L.makeMove(pos, m)) continue;
const gc = pos.inCheck();
L.unmakeMove(pos);
if (!gc) { legal++; continue; }
}
if (!L.makeMove(pos, m)) continue;
legal++;
const givesCheck = pos.inCheck();
let s;
if (legal === 1) s = -this.search(depth - 1, -beta, -alpha, ply + 1);
else {
let red = 0;
if (depth >= 3 && legal > 3 && quiet && !inCheck && !givesCheck && m !== this.killers[ply * 2] && m !== this.killers[ply * 2 + 1]) {
red = 1 + (legal > 8 ? 1 : 0) + (depth >= 8 && legal > 16 ? 1 : 0);
if (pv) red = Math.max(0, red - 1);
}
s = -this.search(depth - 1 - red, -alpha - 1, -alpha, ply + 1);
if (!this.stop && s > alpha && red) s = -this.search(depth - 1, -alpha - 1, -alpha, ply + 1);
if (!this.stop && s > alpha && s < beta) s = -this.search(depth - 1, -beta, -alpha, ply + 1);
}
L.unmakeMove(pos);
if (this.stop) return 0;
if (ply === 0 && this.rootScores) this.rootScores.set(m, s);
if (s > best) {
best = s; bestMove = m;
if (s > alpha) {
alpha = s;
if (ply === 0) { this.rootBest = m; this.rootBestScore = s; }
if (s >= beta) {
if (quiet) {
if (this.killers[ply * 2] !== m) { this.killers[ply * 2 + 1] = this.killers[ply * 2]; this.killers[ply * 2] = m; }
const hi = pos.b[m & 127] * 128 + ((m >> 7) & 127);
this.history[hi] += depth * depth;
if (this.history[hi] > 1e6) for (let k = 0; k < this.history.length; k++) this.history[k] >>= 1;
}
break;
}
}
}
}
if (!legal) return inCheck ? -MATE + ply : 0;
ttStore(pos, depth, best, best >= beta ? LOWER : best > a0 ? EXACT : UPPER, bestMove, ply);
return best;
}
hasPieces(side) {
const b = this.pos.b;
for (let s = 0; s < 128; s++) {
if (s & 0x88) { s += 7; continue; }
const p = b[s];
if (p && (p >> 3) === side) { const t = p & 7; if (t !== P && t !== K) return true; }
}
return false;
}
pv(first, n = 8) {
const pos = this.pos;
const line = [];
let m = first;
let made = 0;
while (m && line.length < n) {
const legal = L.legalMoves(pos);
if (!legal.includes(m)) break;
line.push(m);
L.makeMove(pos, m); made++;
const i = pos.lo & TT_MASK;
m = ttFlag[i] && ttKey[i] === pos.hi ? ttMove[i] : 0;
}
while (made--) L.unmakeMove(pos);
return line;
}
}
/** Iterative deepening; returns { m, score, depth, pv, nodes }. */
export function bestMove(pos, { ms = 1000, depth = 64, minDepth = 1 } = {}) {
const p = pos.clone();
const S = new Searcher(p, { ms, depth });
const legal = L.legalMoves(p);
if (!legal.length) return { m: 0, score: p.inCheck() ? -MATE : 0, depth: 0, pv: [], nodes: 0 };
let best = legal[0], bestScore = 0, done = 0;
let prev = 0;
for (let d = 1; d <= depth; d++) {
S.rootBest = 0;
let s;
if (d >= 4 && Math.abs(prev) < MATE_BOUND) {
let lo = prev - 40, hi = prev + 40;
s = S.search(d, lo, hi, 0);
if (!S.stop && (s <= lo || s >= hi)) { S.rootBest = 0; s = S.search(d, -INF, INF, 0); }
} else s = S.search(d, -INF, INF, 0);
if (S.stop && d > minDepth) {
// a partial iteration that already found a better move is still usable
if (S.rootBest && S.rootBestScore > bestScore && done) { best = S.rootBest; bestScore = S.rootBestScore; }
break;
}
if (S.rootBest) { best = S.rootBest; bestScore = s; }
prev = s; done = d;
if (Math.abs(s) > MATE_BOUND && d > 2 && MATE - Math.abs(s) <= d) break;
if (legal.length === 1 && d >= 2) break;
if (S.stop) { S.stop = false; S.deadline = 0; break; }
}
return { m: best, score: bestScore, depth: done, pv: S.pv(best), nodes: S.nodes };
}
/**
* Scores for every root move (best first). Moves within `margin` of the best
* are scored exactly; the rest are known to be at least `margin` worse.
*/
export function analyze(pos, { ms = 500, depth = 64, margin = 250 } = {}) {
const p = pos.clone();
const legal = L.legalMoves(p);
if (!legal.length) return [];
const S = new Searcher(p, { ms, depth });
let result = legal.map((m) => ({ m, score: 0 }));
for (let d = 1; d <= depth; d++) {
const order = result.map((r) => r.m);
const scores = new Map();
let best = -INF;
let complete = true;
for (const m of order) {
L.makeMove(p, m);
const lo = best === -INF ? -INF : best - margin;
const s = -S.search(d - 1, -INF, -lo, 1);
L.unmakeMove(p);
if (S.stop) { complete = false; break; }
scores.set(m, s);
if (s > best) best = s;
}
if (!complete && d > 1) break;
if (scores.size) {
result = order.map((m) => ({ m, score: scores.has(m) ? scores.get(m) : -INF })).sort((a, b) => b.score - a.score);
}
if (!complete) break;
if (Math.abs(result[0].score) > MATE_BOUND && d > 2) break;
}
return result;
}
/** Centipawns from White's point of view after a short search. */
export function evaluateWhite(pos, { ms = 120, depth = 64 } = {}) {
const r = bestMove(pos, { ms, depth });
let s = r.score;
if (!r.m) s = pos.inCheck() ? -MATE : 0;
return pos.side === WHITE ? s : -s;
}
export function mateIn(score) {
if (Math.abs(score) <= MATE_BOUND) return 0;
const plies = MATE - Math.abs(score);
return Math.sign(score) * Math.ceil(plies / 2);
}
// ── choosing a move at a skill level ───────────────────────────────────────
/**
* game: a ChessLogic.Chess. Returns { m, score, book, rich }.
* opts.ms overrides the profile's thinking budget (for clocks).
*/
export function chooseMove(game, skill, { ms = null, rng = Math.random } = {}) {
const prof = profileOf(skill);
const pos = game.pos;
const legal = L.legalMoves(pos);
if (!legal.length) return null;
// the book
if (game.startFen === L.START_FEN && game.ply < prof.bookPly) {
const opts = bookMoves(game);
if (opts.length && rng() < (skill >= 2 ? 0.95 : 0.6)) {
const total = opts.reduce((a, o) => a + o.w, 0);
let x = rng() * total;
for (const o of opts) { x -= o.w; if (x <= 0) return { m: o.m, score: 0, book: true }; }
return { m: opts[0].m, score: 0, book: true };
}
}
return aiColor === 'white' ? score : -score;
}
// Captures first (most-valuable-victim heuristic) for better pruning.
function orderMoves(board, moves) {
return moves
.map((m) => {
let s = 0;
if (m.capture) s += 10 * VALUE[board[m.capture[0]][m.capture[1]].type] - VALUE[m.piece];
if (m.promotion) s += VALUE[m.promotion];
return { m, s };
})
.sort((a, b) => b.s - a.s)
.map((x) => x.m);
}
function search(state, depth, alpha, beta, aiColor) {
const moves = getLegalMoves(state);
if (moves.length === 0) {
if (isKingAttacked(state.board, state.turn)) {
// Side to move is checkmated. Prefer faster mates via the depth bonus.
return state.turn === aiColor ? -(MATE + depth) : (MATE + depth);
const budget = ms ?? prof.ms;
// the occasional wild move (rookies)
if (prof.wild && rng() < prof.wild) {
return { m: legal[Math.floor(rng() * legal.length)], score: 0, book: false, wild: true };
}
if (prof.topN === 1) {
const r = bestMove(pos, { ms: budget, depth: prof.depth });
return { m: r.m, score: r.score, book: false, depth: r.depth };
}
const ranked = analyze(pos, { ms: budget, depth: prof.depth, margin: Math.max(80, prof.noise * 3) });
// never miss a forced mate or walk into one when there's a sane choice
const bestS = ranked[0].score;
if (bestS > MATE_BOUND && skill >= 3) return { m: ranked[0].m, score: bestS, book: false };
let pool = ranked.slice(0, prof.topN).filter((r) => r.score > -MATE_BOUND || r === ranked[0]);
if (!pool.length) pool = [ranked[0]];
let pick;
if (rng() < prof.slip && pool.length > 1) {
pick = pool[1 + Math.floor(rng() * (pool.length - 1))];
} else {
let bestV = -Infinity;
for (const r of pool) {
const v = r.score + (rng() * 2 - 1) * prof.noise;
if (v > bestV) { bestV = v; pick = r; }
}
return 0; // stalemate
}
if (depth <= 0) return evaluate(state.board, aiColor);
return { m: pick.m, score: pick.score, book: false };
}
const ordered = orderMoves(state.board, moves);
if (state.turn === aiColor) {
let value = -Infinity;
for (const m of ordered) {
value = Math.max(value, search(applyMoveRaw(state, m), depth - 1, alpha, beta, aiColor));
alpha = Math.max(alpha, value);
if (alpha >= beta) break;
/** Thinking budget under a clock: a slice of what's left plus most of the increment. */
export function clockBudget(skill, remainingMs, incMs, ply) {
const prof = profileOf(skill);
if (remainingMs == null) return prof.ms;
const movesLeft = Math.max(18, 40 - Math.floor(ply / 2) * 0.5);
const slice = remainingMs / movesLeft + incMs * 0.75;
return Math.max(60, Math.min(prof.ms, slice, remainingMs * 0.25));
}
// ── table manners ──────────────────────────────────────────────────────────
/** Would the AI (whose last search said `score`, from its side) offer a draw? */
export function wantsDraw(score, ply, skill) {
if (ply < 60) return false;
const k = clampSkill(skill);
return Math.abs(score) <= 25 + (5 - k) * 10;
}
/** Response to your draw offer. score = the AI's view of the position. */
export function drawDecision(score, ply, skill) {
if (ply < 20) return { accept: false, why: 'early' };
const k = clampSkill(skill);
if (score <= -150) return { accept: true, why: 'worse' };
if (score <= 40 - k * 5 && ply >= 50) return { accept: true, why: 'level' };
return { accept: false, why: score > 150 ? 'better' : 'play' };
}
/** Resign when hopelessly lost for a few moves running (skill 3+ only). */
export function shouldResign(history, skill) {
if (clampSkill(skill) < 3 || history.length < 3) return false;
return history.slice(-3).every((s) => s <= -1100);
}
// ── explaining a move ──────────────────────────────────────────────────────
const NAME = ['', 'pawn', 'knight', 'bishop', 'rook', 'queen', 'king'];
/** A short reason ("forks the king and rook") for a move, given the search score from the mover's side. */
export function describeIdea(pos, m, score = 0) {
const p = pos.clone();
const from = m & 127, to = (m >> 7) & 127, fl = (m >> 17) & 15, promo = (m >> 14) & 7;
const us = p.side;
const piece = p.b[from] & 7;
const victim = (fl & L.F_EP) ? P : (p.b[to] & 7);
const mate = mateIn(score);
if (!L.makeMove(p, m)) return 'keeps things steady';
try {
if (!L.hasLegalMove(p) && p.inCheck()) return 'is checkmate';
if (mate > 0) return `forces mate in ${mate}`;
if (promo) return `promotes to a ${NAME[promo]}`;
if (fl & L.F_CASTLE) return 'tucks the king away and connects the rooks';
// what does the moved piece attack now?
const ks = (fl & L.F_CASTLE) ? -1 : to;
const targets = [];
if (ks >= 0) {
for (let s = 0; s < 128; s++) {
if (s & 0x88) { s += 7; continue; }
const q = p.b[s];
if (!q || (q >> 3) === us) continue;
const atk = L.attackersOf(p, s, us);
if (atk.includes(ks)) targets.push(q & 7);
}
}
return value;
const big = targets.filter((t) => t === K || SEE_VAL[t] > SEE_VAL[piece] || t === R || t === Q).sort((a, b) => SEE_VAL[b] - SEE_VAL[a]);
if (big.length >= 2) return `forks the ${NAME[big[0]]} and ${NAME[big[1]]}`;
if (victim) {
if (score >= 150) return `wins the ${NAME[victim]}`;
return `takes the ${NAME[victim]}`;
}
if (p.inCheck()) return score >= 200 ? 'checks, and the attack keeps rolling' : 'gives check';
if (score >= 250) return 'sets up a winning threat';
// did it rescue a piece that was hanging?
L.unmakeMove(p);
const wasAttacked = L.isAttacked(p, from, us ^ 1) && piece !== P && piece !== K;
L.makeMove(p, m);
if (wasAttacked) return `gets the ${NAME[piece]} out of trouble`;
const row = from >> 4, home = us === WHITE ? 7 : 0;
if ((piece === N || piece === B) && row === home) return `develops the ${NAME[piece]}`;
const tf = to & 7, tr = to >> 4;
if (piece === P && tf >= 2 && tf <= 5 && tr >= 2 && tr <= 5) return 'grabs space in the centre';
if (targets.length) return `puts pressure on the ${NAME[targets.sort((a, b) => SEE_VAL[b] - SEE_VAL[a])[0]]}`;
return 'improves the position';
} finally {
// p is a clone — nothing to restore
}
let value = Infinity;
for (const m of ordered) {
value = Math.min(value, search(applyMoveRaw(state, m), depth - 1, alpha, beta, aiColor));
beta = Math.min(beta, value);
if (beta <= alpha) break;
}
return value;
}
// Return the chosen move object for `aiColor`, or null if none.
export function chooseMove(state, aiColor, skill) {
const prof = profileFor(skill);
const moves = getLegalMoves(state);
if (moves.length === 0) return null;
if (Math.random() < prof.blunder) {
return moves[Math.floor(Math.random() * moves.length)];
/** Is the moved piece left hanging (a cheap "you're dropping material" test)? */
export function dropsMaterial(pos, m) {
const p = pos.clone();
if (!L.makeMove(p, m)) return 0;
// best capture reply by SEE
const caps = L.genMoves(p, [], true);
let worst = 0;
for (const c of caps) {
if (!(((c >> 17) & 15) & L.F_CAP)) continue;
const v = see(p, c);
if (v > worst) {
if (!L.makeMove(p, c)) continue;
L.unmakeMove(p);
worst = v;
}
}
const ordered = orderMoves(state.board, moves);
let best = null;
let bestScore = -Infinity;
for (const m of ordered) {
const val = search(applyMoveRaw(state, m), prof.depth - 1, -Infinity, Infinity, aiColor)
+ (Math.random() * 2 - 1) * prof.noise;
if (val > bestScore) { bestScore = val; best = m; }
}
return best ?? moves[0];
return worst;
}

909
src/games/chess/ChessArt.js Normal file
View File

@ -0,0 +1,909 @@
// ChessArt.js — baked canvas textures for the Stone Tables, a city park at
// dusk. All procedural: no image files.
//
// cs-park the whole scene: a dusk sky, the skyline with its first
// lit windows, autumn trees, the paved plaza, a fountain,
// a far table with two regulars, lamp posts, the granite
// table the board sits on
// cs-table the granite table alone (over a chosen playfield)
// cs-vignette dusk vignette alone
// cs-lights string lights strung across the top (faded in at night)
// cs-board-<theme> stone (inlaid marble) · walnut · green (tournament vinyl)
// cs-<style>-<c><t> pieces: style carved | bold; c w|b; t p n b r q k (2× bake)
// cs-pigeon-<0..4> walk, walk, peck, flap up, flap down
// cs-clock, cs-clock-btn the chess clock case + plunger
// cs-plate, cs-plate-glow, cs-chalk, cs-sheet, cs-slate
// cs-shadow, cs-glow, cs-ring, cs-dot, cs-cap, cs-spark, cs-dust, cs-drop,
// cs-leaf-<0..3>, cs-lamp-glow, cs-check
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
import {
W, H, BX, BY, BOARD, FRAME, BOARD_TEX, SQ, PLATE, STATUS, LOG, RIBBON, TABLE, FOUNTAIN, PARK, CLOCK, CLOCK_FACES,
} from './ChessLayout.js';
export const DISPLAY_FONT = '"Julius Sans One", Georgia, serif';
export const SERIF = 'Georgia, "Times New Roman", serif';
export const BOLD_FONT = 'Righteous, Georgia, serif';
export const CHALK = '"Julius Sans One", Georgia, serif';
export const RES = 2;
export const PIECE_BOX = 100; // logical piece box (one square)
export const PIECE_TEX = (PIECE_BOX + 16) * RES;
export const BOARD_THEMES = ['stone', 'walnut', 'green'];
export const PIECE_STYLES = ['carved', 'bold'];
function addCanvas(scene, key, c) {
if (scene.textures.exists(key)) scene.textures.remove(key);
scene.textures.addCanvas(key, c);
}
function seeded(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shadowed(ctx, fn, { blur = 24, dx = 8, dy = 14, alpha = 0.55 } = {}) {
ctx.save();
ctx.shadowColor = `rgba(0,0,0,${alpha})`;
ctx.shadowBlur = blur; ctx.shadowOffsetX = dx; ctx.shadowOffsetY = dy;
fn();
ctx.restore();
}
function grain(ctx, rnd, x, y, w, h, { tone = 'rgba(20,8,2,0.35)', lines = 30, wave = 5, vertical = false } = {}) {
ctx.save();
ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
ctx.strokeStyle = tone;
const Lx = vertical ? h : w, S = vertical ? w : h;
for (let i = 0; i < lines; i++) {
const o = rnd() * S, amp = wave * (0.4 + rnd()), f = 0.003 + rnd() * 0.01, ph = rnd() * 6;
ctx.lineWidth = 0.6 + rnd() * 1.6;
ctx.beginPath();
for (let t = 0; t <= Lx; t += 8) {
const d = o + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.3 + ph) * amp * 0.3;
const px = vertical ? x + d : x + t, py = vertical ? y + t : y + d;
if (t === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
}
ctx.stroke();
}
ctx.restore();
}
function speckle(ctx, rnd, x, y, w, h, n, colors, rmax = 1.6) {
for (let i = 0; i < n; i++) {
ctx.fillStyle = colors[Math.floor(rnd() * colors.length)];
const r = 0.4 + rnd() * rmax;
ctx.beginPath(); ctx.arc(x + rnd() * w, y + rnd() * h, r, 0, Math.PI * 2); ctx.fill();
}
}
function brass(ctx, x0, y0, x1, y1) {
const g = ctx.createLinearGradient(x0, y0, x1, y1);
g.addColorStop(0, '#f6dc9a'); g.addColorStop(0.4, '#b98a34'); g.addColorStop(0.65, '#ecc878'); g.addColorStop(1, '#7a5418');
return g;
}
// ── the park ───────────────────────────────────────────────────────────────
const HORIZON = 452;
function sky(ctx, rnd) {
const g = ctx.createLinearGradient(0, 0, 0, HORIZON);
g.addColorStop(0, '#141a3e'); g.addColorStop(0.35, '#3a2c5e'); g.addColorStop(0.62, '#8a4a6a');
g.addColorStop(0.82, '#e07a4a'); g.addColorStop(1, '#f4b060');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, HORIZON + 40);
// the low sun behind the towers
const sun = ctx.createRadialGradient(1280, HORIZON - 40, 10, 1280, HORIZON - 40, 520);
sun.addColorStop(0, 'rgba(255,230,160,0.85)'); sun.addColorStop(0.18, 'rgba(255,190,110,0.45)'); sun.addColorStop(1, 'rgba(255,150,90,0)');
ctx.fillStyle = sun; ctx.fillRect(0, 0, W, HORIZON + 40);
// a few early stars
for (let i = 0; i < 70; i++) {
const x = rnd() * W, y = rnd() * 180;
ctx.fillStyle = `rgba(255,255,240,${0.15 + rnd() * 0.5})`;
ctx.fillRect(x, y, rnd() < 0.15 ? 2 : 1, rnd() < 0.15 ? 2 : 1);
}
// long clouds lit from below
for (let i = 0; i < 9; i++) {
const cx = rnd() * W, cy = 120 + rnd() * 220, w = 240 + rnd() * 420, h = 10 + rnd() * 18;
ctx.save();
ctx.translate(cx, cy);
for (let k = 0; k < 6; k++) {
const ox = (rnd() - 0.5) * w * 0.7, oy = (rnd() - 0.5) * h;
const cg = ctx.createRadialGradient(ox, oy, 0, ox, oy, w * 0.35);
const warm = cy > 260;
cg.addColorStop(0, warm ? 'rgba(255,170,120,0.30)' : 'rgba(200,140,180,0.22)');
cg.addColorStop(1, 'rgba(200,140,180,0)');
ctx.fillStyle = cg;
ctx.save(); ctx.scale(1, h / (w * 0.35)); ctx.beginPath(); ctx.arc(ox, oy * (w * 0.35) / h, w * 0.35, 0, Math.PI * 2); ctx.fill(); ctx.restore();
}
ctx.restore();
}
}
function skyline(ctx, rnd) {
// far layer
let x = -20;
while (x < W) {
const bw = 40 + rnd() * 90, bh = 70 + rnd() * 170;
ctx.fillStyle = '#4a3456';
ctx.fillRect(x, HORIZON - bh, bw, bh);
x += bw + rnd() * 6;
}
// near layer with windows
x = -30;
while (x < W) {
const bw = 60 + rnd() * 120, bh = 120 + rnd() * 230;
const top = HORIZON - bh;
const g = ctx.createLinearGradient(x, 0, x + bw, 0);
g.addColorStop(0, '#2a1e3c'); g.addColorStop(1, '#1c142a');
ctx.fillStyle = g;
ctx.fillRect(x, top, bw, bh);
if (rnd() < 0.3) { ctx.fillRect(x + bw * 0.45, top - 30, 3, 30); ctx.fillStyle = 'rgba(255,80,80,0.9)'; ctx.fillRect(x + bw * 0.45 - 1, top - 32, 5, 4); }
// a sunset edge on the west faces
ctx.fillStyle = 'rgba(255,170,110,0.16)'; ctx.fillRect(x + bw - 4, top, 4, bh);
for (let wy = top + 10; wy < HORIZON - 10; wy += 16) {
for (let wx = x + 7; wx < x + bw - 9; wx += 12) {
const r = rnd();
if (r < 0.2) { ctx.fillStyle = rnd() < 0.6 ? 'rgba(255,214,140,0.85)' : 'rgba(255,240,200,0.7)'; ctx.fillRect(wx, wy, 5, 8); }
else if (r < 0.32) { ctx.fillStyle = 'rgba(120,140,200,0.18)'; ctx.fillRect(wx, wy, 5, 8); }
}
}
x += bw + 2 + rnd() * 10;
}
}
function tree(ctx, rnd, x, y, size, palette) {
// trunk
ctx.fillStyle = '#2a1a14';
ctx.beginPath();
ctx.moveTo(x - size * 0.06, y); ctx.lineTo(x - size * 0.03, y - size * 0.7); ctx.lineTo(x + size * 0.03, y - size * 0.7); ctx.lineTo(x + size * 0.07, y);
ctx.closePath(); ctx.fill();
// crown of leaf clusters, darker at the bottom
for (let i = 0; i < 26; i++) {
const a = rnd() * Math.PI * 2, d = rnd() * size * 0.42;
const cx = x + Math.cos(a) * d * 1.15, cy = y - size * 0.85 + Math.sin(a) * d * 0.8;
const r = size * (0.12 + rnd() * 0.14);
const col = palette[Math.floor(rnd() * palette.length)];
const g = ctx.createRadialGradient(cx - r * 0.3, cy - r * 0.4, r * 0.1, cx, cy, r);
g.addColorStop(0, col[0]); g.addColorStop(1, col[1]);
ctx.fillStyle = g;
ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill();
}
// leaf speckles catching the last light
speckle(ctx, rnd, x - size * 0.5, y - size * 1.25, size, size * 0.8, 60, ['rgba(255,170,80,0.45)', 'rgba(255,210,120,0.35)', 'rgba(200,80,40,0.4)']);
}
const AUTUMN = [
['#a8542a', '#4a2010'], ['#c88a32', '#5a3410'], ['#8a2a1e', '#3a0e0a'], ['#5a6a2a', '#202a10'], ['#b8662a', '#4a2410'],
];
function trees(ctx, rnd) {
// back row, hazy
for (let x = -40; x < W + 40; x += 70 + rnd() * 40) tree(ctx, rnd, x, HORIZON + 30 + rnd() * 20, 150 + rnd() * 70, [['#5a3a4a', '#2a1c2a'], ['#6a4040', '#2a1a22']]);
ctx.fillStyle = 'rgba(120,70,100,0.25)'; ctx.fillRect(0, 300, W, HORIZON - 200);
// front row, autumn colours
for (let x = -60; x < W + 60; x += 150 + rnd() * 90) tree(ctx, rnd, x, HORIZON + 80 + rnd() * 30, 220 + rnd() * 90, AUTUMN);
}
function plaza(ctx, rnd) {
const y0 = HORIZON + 60;
const g = ctx.createLinearGradient(0, y0, 0, H);
g.addColorStop(0, '#5a4a52'); g.addColorStop(1, '#2a2228');
ctx.fillStyle = g; ctx.fillRect(0, y0, W, H - y0);
// pavers in perspective, vanishing at the centre of the board
const vx = W / 2;
ctx.strokeStyle = 'rgba(20,14,20,0.45)'; ctx.lineWidth = 1.5;
for (let r = 0; r < 26; r++) {
const t = r / 26, y = y0 + (H - y0) * t * t;
ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke();
}
for (let i = -40; i <= 40; i++) {
ctx.beginPath(); ctx.moveTo(vx + i * 30, y0); ctx.lineTo(vx + i * 150, H); ctx.stroke();
}
speckle(ctx, rnd, 0, y0, W, H - y0, 1600, ['rgba(255,255,255,0.05)', 'rgba(0,0,0,0.12)'], 1.4);
// fallen leaves on the pavement
for (let i = 0; i < 260; i++) {
const x = rnd() * W, y = y0 + 20 + rnd() * (H - y0 - 20);
const col = ['#a8542a', '#c88a32', '#8a2a1e', '#d0a040'][Math.floor(rnd() * 4)];
ctx.save(); ctx.translate(x, y); ctx.rotate(rnd() * 6);
ctx.fillStyle = col; ctx.globalAlpha = 0.45 + rnd() * 0.4;
ctx.beginPath(); ctx.ellipse(0, 0, 5 + rnd() * 4, 2.5 + rnd() * 2, 0, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
// warm light from the lamp spilling across the plaza
const lg = ctx.createRadialGradient(PARK.x + 60, HORIZON + 200, 10, PARK.x + 60, HORIZON + 200, 420);
lg.addColorStop(0, 'rgba(255,200,120,0.28)'); lg.addColorStop(1, 'rgba(255,200,120,0)');
ctx.fillStyle = lg; ctx.fillRect(0, y0, W, H - y0);
}
function lampPost(ctx, x, y, h) {
ctx.fillStyle = '#121016';
ctx.fillRect(x - 3, y - h, 6, h);
ctx.fillRect(x - 9, y - 10, 18, 10);
ctx.fillRect(x - 6, y - h * 0.35, 12, 4);
// lantern
ctx.beginPath(); ctx.moveTo(x - 12, y - h - 2); ctx.lineTo(x + 12, y - h - 2); ctx.lineTo(x + 8, y - h - 30); ctx.lineTo(x - 8, y - h - 30); ctx.closePath(); ctx.fill();
ctx.fillStyle = 'rgba(255,220,150,0.95)'; ctx.fillRect(x - 6, y - h - 26, 12, 20);
ctx.fillStyle = '#121016'; ctx.beginPath(); ctx.moveTo(x - 14, y - h - 30); ctx.lineTo(x + 14, y - h - 30); ctx.lineTo(x, y - h - 42); ctx.closePath(); ctx.fill();
const g = ctx.createRadialGradient(x, y - h - 16, 2, x, y - h - 16, 90);
g.addColorStop(0, 'rgba(255,220,150,0.6)'); g.addColorStop(1, 'rgba(255,220,150,0)');
ctx.fillStyle = g; ctx.fillRect(x - 90, y - h - 106, 180, 180);
}
function fountain(ctx) {
const { x, y } = FOUNTAIN;
// basin
shadowed(ctx, () => {
ctx.fillStyle = '#6a6470'; ctx.beginPath(); ctx.ellipse(x, y + 70, 150, 40, 0, 0, Math.PI * 2); ctx.fill();
}, { blur: 16, dx: 0, dy: 8, alpha: 0.5 });
ctx.fillStyle = '#7a7480'; ctx.beginPath(); ctx.ellipse(x, y + 60, 150, 38, 0, 0, Math.PI * 2); ctx.fill();
const wg = ctx.createLinearGradient(0, y + 40, 0, y + 80);
wg.addColorStop(0, '#3a5a7a'); wg.addColorStop(1, '#1a2a44');
ctx.fillStyle = wg; ctx.beginPath(); ctx.ellipse(x, y + 58, 134, 28, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(255,200,140,0.35)'; ctx.lineWidth = 2;
for (let i = 0; i < 4; i++) { ctx.beginPath(); ctx.ellipse(x, y + 58, 30 + i * 26, 6 + i * 5, 0, Math.PI * 1.1, Math.PI * 1.9); ctx.stroke(); }
// pedestal and bowl
ctx.fillStyle = '#8a8490';
ctx.beginPath(); ctx.moveTo(x - 14, y + 58); ctx.lineTo(x - 8, y - 10); ctx.lineTo(x + 8, y - 10); ctx.lineTo(x + 14, y + 58); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#9a94a0'; ctx.beginPath(); ctx.ellipse(x, y - 12, 56, 13, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#3a5a7a'; ctx.beginPath(); ctx.ellipse(x, y - 14, 46, 9, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#8a8490'; ctx.fillRect(x - 4, y - 46, 8, 34);
ctx.fillStyle = 'rgba(255,190,120,0.25)'; ctx.fillRect(x - 4, y - 46, 3, 34);
}
function farTable(ctx, x, y) {
// a distant stone table with two regulars hunched over it
ctx.fillStyle = '#4a4450'; ctx.fillRect(x - 34, y - 26, 68, 10);
ctx.fillStyle = '#3a3440'; ctx.fillRect(x - 10, y - 16, 20, 26);
ctx.fillStyle = '#1a1620';
const person = (px, dir) => {
ctx.beginPath(); ctx.arc(px, y - 52, 9, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.moveTo(px - 13, y + 8); ctx.quadraticCurveTo(px - 15 * dir, y - 30, px + 4 * dir, y - 44); ctx.lineTo(px + 12 * dir, y - 30); ctx.lineTo(px + 14, y + 8); ctx.closePath(); ctx.fill();
};
person(x - 46, 1); person(x + 46, -1);
ctx.fillStyle = '#2a2430'; ctx.fillRect(x - 64, y - 4, 30, 8); ctx.fillRect(x + 34, y - 4, 30, 8);
}
function graniteSlab(ctx, rnd, x, y, w, h) {
shadowed(ctx, () => { ctx.fillStyle = '#3a3640'; rr(ctx, x, y, w, h, 18); ctx.fill(); }, { blur: 40, dx: 0, dy: 26, alpha: 0.7 });
const g = ctx.createLinearGradient(x, y, x + w, y + h);
g.addColorStop(0, '#77727c'); g.addColorStop(0.5, '#605a66'); g.addColorStop(1, '#4a4450');
ctx.fillStyle = g; rr(ctx, x, y, w, h, 18); ctx.fill();
ctx.save(); rr(ctx, x, y, w, h, 18); ctx.clip();
speckle(ctx, rnd, x, y, w, h, Math.floor(w * h / 90), ['rgba(20,18,24,0.5)', 'rgba(230,226,236,0.35)', 'rgba(140,120,110,0.35)', 'rgba(0,0,0,0.3)'], 1.8);
// weathering and a chalk tally somebody scratched in a corner
for (let i = 0; i < 6; i++) {
const cx = x + rnd() * w, cy = y + rnd() * h, r = 60 + rnd() * 160;
const sg = ctx.createRadialGradient(cx, cy, 0, cx, cy, r);
sg.addColorStop(0, 'rgba(30,26,34,0.18)'); sg.addColorStop(1, 'rgba(30,26,34,0)');
ctx.fillStyle = sg; ctx.fillRect(cx - r, cy - r, r * 2, r * 2);
}
ctx.strokeStyle = 'rgba(240,236,220,0.35)'; ctx.lineWidth = 2;
const tx = x + w - 86, ty = y + h - 28;
for (let i = 0; i < 4; i++) { ctx.beginPath(); ctx.moveTo(tx + i * 9, ty - 14); ctx.lineTo(tx + i * 9 + 2, ty + 2); ctx.stroke(); }
ctx.beginPath(); ctx.moveTo(tx - 4, ty - 2); ctx.lineTo(tx + 32, ty - 10); ctx.stroke();
ctx.restore();
// bevelled edge
ctx.strokeStyle = 'rgba(255,240,230,0.22)'; ctx.lineWidth = 3; rr(ctx, x + 3, y + 3, w - 6, h - 6, 16); ctx.stroke();
ctx.strokeStyle = 'rgba(0,0,0,0.4)'; ctx.lineWidth = 2; rr(ctx, x + 1, y + 1, w - 2, h - 2, 17); ctx.stroke();
}
function vignette(ctx) {
const g = ctx.createRadialGradient(W / 2, H * 0.55, H * 0.35, W / 2, H * 0.55, H * 1.05);
g.addColorStop(0, 'rgba(10,6,20,0)'); g.addColorStop(1, 'rgba(10,6,20,0.62)');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
}
function bakePark(scene) {
const rnd = seeded(1846);
{
const c = canvas(W, H), ctx = c.getContext('2d');
sky(ctx, rnd);
skyline(ctx, rnd);
trees(ctx, rnd);
plaza(ctx, rnd);
lampPost(ctx, 96, 760, 300);
lampPost(ctx, 1890, 760, 300);
farTable(ctx, 400, 690);
fountain(ctx);
graniteSlab(ctx, rnd, TABLE.x, TABLE.y, TABLE.w, TABLE.h);
vignette(ctx);
ctx.fillStyle = noisePattern(ctx, 96, 10); ctx.fillRect(0, 0, W, H);
addCanvas(scene, 'cs-park', c);
}
{
const c = canvas(W, H), ctx = c.getContext('2d');
graniteSlab(ctx, seeded(7), TABLE.x, TABLE.y, TABLE.w, TABLE.h);
addCanvas(scene, 'cs-table', c);
}
{
const c = canvas(W, H), ctx = c.getContext('2d');
vignette(ctx);
addCanvas(scene, 'cs-vignette', c);
}
{
// string lights: two sagging strands across the top of the park
const c = canvas(W, 190), ctx = c.getContext('2d');
const strand = (y0, sag, phase) => {
const pts = [];
for (let x = -20; x <= W + 20; x += 4) {
const span = 480, t = ((x + phase) % span) / span;
pts.push([x, y0 + Math.sin(Math.PI * t) * sag]);
}
ctx.strokeStyle = 'rgba(20,16,24,0.9)'; ctx.lineWidth = 2;
ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.stroke();
for (let i = 6; i < pts.length; i += 12) {
const [x, y] = pts[i];
const g = ctx.createRadialGradient(x, y + 6, 0, x, y + 6, 18);
g.addColorStop(0, 'rgba(255,220,150,0.9)'); g.addColorStop(0.3, 'rgba(255,200,120,0.35)'); g.addColorStop(1, 'rgba(255,200,120,0)');
ctx.fillStyle = g; ctx.fillRect(x - 18, y - 12, 36, 36);
ctx.fillStyle = '#fff4d8'; ctx.beginPath(); ctx.ellipse(x, y + 6, 3, 4.5, 0, 0, Math.PI * 2); ctx.fill();
}
};
strand(18, 60, 0);
strand(70, 48, 240);
addCanvas(scene, 'cs-lights', c);
}
}
// ── boards ─────────────────────────────────────────────────────────────────
const BOARD_PAD = 20;
export const BOARD_POS = { x: BX - FRAME - BOARD_PAD, y: BY - FRAME - BOARD_PAD };
function marbleSquare(ctx, rnd, x, y, s, base, veins, dark) {
const g = ctx.createLinearGradient(x, y, x + s, y + s);
g.addColorStop(0, base[0]); g.addColorStop(1, base[1]);
ctx.fillStyle = g; ctx.fillRect(x, y, s, s);
ctx.save(); ctx.beginPath(); ctx.rect(x, y, s, s); ctx.clip();
for (let i = 0; i < 4; i++) {
ctx.strokeStyle = veins[Math.floor(rnd() * veins.length)];
ctx.lineWidth = 0.6 + rnd() * 2.2;
ctx.beginPath();
let px = x + rnd() * s, py = y - 10;
ctx.moveTo(px, py);
for (let k = 0; k < 6; k++) {
const nx = px + (rnd() - 0.5) * 60, ny = py + s / 4 + rnd() * 10;
ctx.quadraticCurveTo(px + (rnd() - 0.5) * 50, (py + ny) / 2, nx, ny);
px = nx; py = ny;
}
ctx.stroke();
}
speckle(ctx, rnd, x, y, s, s, 70, dark ? ['rgba(255,255,255,0.08)', 'rgba(0,0,0,0.2)'] : ['rgba(120,100,70,0.12)', 'rgba(255,255,255,0.25)'], 1.2);
ctx.restore();
}
function woodSquare(ctx, rnd, x, y, s, base, tone, vertical) {
const g = ctx.createLinearGradient(x, y, vertical ? x + s : x, vertical ? y : y + s);
g.addColorStop(0, base[0]); g.addColorStop(1, base[1]);
ctx.fillStyle = g; ctx.fillRect(x, y, s, s);
grain(ctx, rnd, x, y, s, s, { tone, lines: 14, wave: 3, vertical });
}
function frameAround(ctx, rnd, x, y, w, h, theme) {
const F = FRAME;
shadowed(ctx, () => { ctx.fillStyle = '#000'; rr(ctx, x, y, w, h, 14); ctx.fill(); }, { blur: 18, dx: 0, dy: 10, alpha: 0.6 });
if (theme === 'walnut') {
const g = ctx.createLinearGradient(x, y, x + w, y + h);
g.addColorStop(0, '#5a3418'); g.addColorStop(1, '#2a160a');
ctx.fillStyle = g; rr(ctx, x, y, w, h, 14); ctx.fill();
grain(ctx, rnd, x, y, w, h, { tone: 'rgba(10,4,0,0.4)', lines: 50, wave: 4 });
ctx.strokeStyle = brass(ctx, x, y, x + w, y + h); ctx.lineWidth = 3; rr(ctx, x + F - 8, y + F - 8, w - 2 * F + 16, h - 2 * F + 16, 4); ctx.stroke();
} else if (theme === 'green') {
ctx.fillStyle = '#e8e4d0'; rr(ctx, x, y, w, h, 10); ctx.fill();
ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 2; rr(ctx, x + 6, y + 6, w - 12, h - 12, 8); ctx.stroke();
speckle(ctx, rnd, x, y, w, h, 1500, ['rgba(0,0,0,0.04)', 'rgba(255,255,255,0.2)'], 1);
} else {
// granite surround with a chamfer and an inlaid brass line
const g = ctx.createLinearGradient(x, y, x + w, y + h);
g.addColorStop(0, '#5a5560'); g.addColorStop(1, '#38333e');
ctx.fillStyle = g; rr(ctx, x, y, w, h, 14); ctx.fill();
ctx.save(); rr(ctx, x, y, w, h, 14); ctx.clip();
speckle(ctx, rnd, x, y, w, h, 3800, ['rgba(20,18,24,0.55)', 'rgba(230,226,236,0.3)', 'rgba(150,120,100,0.3)'], 1.6);
ctx.restore();
ctx.strokeStyle = 'rgba(255,250,240,0.2)'; ctx.lineWidth = 3; rr(ctx, x + 4, y + 4, w - 8, h - 8, 12); ctx.stroke();
ctx.strokeStyle = brass(ctx, x, y, x + w, y + h); ctx.lineWidth = 2.5; rr(ctx, x + F - 10, y + F - 10, w - 2 * F + 20, h - 2 * F + 20, 3); ctx.stroke();
}
// inner lip
ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.fillRect(x + F - 4, y + F - 4, w - 2 * F + 8, h - 2 * F + 8);
}
function bakeBoard(scene, theme) {
const rnd = seeded(theme.length * 977);
const S = BOARD_TEX + BOARD_PAD * 2;
const c = canvas(S, S), ctx = c.getContext('2d');
const x0 = BOARD_PAD, y0 = BOARD_PAD;
frameAround(ctx, rnd, x0, y0, BOARD_TEX, BOARD_TEX, theme);
const ox = x0 + FRAME, oy = y0 + FRAME;
for (let r = 0; r < 8; r++) {
for (let f = 0; f < 8; f++) {
const dark = (r + f) % 2 === 1;
const x = ox + f * SQ, y = oy + r * SQ;
if (theme === 'stone') {
if (dark) marbleSquare(ctx, rnd, x, y, SQ, ['#3c5a4a', '#24392e'], ['rgba(170,210,180,0.22)', 'rgba(10,20,14,0.4)', 'rgba(220,240,220,0.12)'], true);
else marbleSquare(ctx, rnd, x, y, SQ, ['#ece2cc', '#d8cbb0'], ['rgba(150,120,90,0.25)', 'rgba(110,90,70,0.18)', 'rgba(255,255,255,0.5)'], false);
} else if (theme === 'walnut') {
if (dark) woodSquare(ctx, rnd, x, y, SQ, ['#7a4a26', '#5a3218'], 'rgba(20,8,0,0.35)', (r + f) % 4 === 1);
else woodSquare(ctx, rnd, x, y, SQ, ['#e8c88e', '#d4ae72'], 'rgba(120,70,20,0.25)', (r + f) % 4 === 0);
} else {
ctx.fillStyle = dark ? '#6f9a52' : '#eeeed2'; ctx.fillRect(x, y, SQ, SQ);
speckle(ctx, rnd, x, y, SQ, SQ, 40, ['rgba(0,0,0,0.04)', 'rgba(255,255,255,0.12)'], 1);
}
}
}
// gloss: a soft sheen from the lamp, and edge wear
const sh = ctx.createLinearGradient(ox, oy, ox + BOARD, oy + BOARD);
sh.addColorStop(0, 'rgba(255,240,210,0.10)'); sh.addColorStop(0.5, 'rgba(255,240,210,0)'); sh.addColorStop(1, 'rgba(0,0,0,0.12)');
ctx.fillStyle = sh; ctx.fillRect(ox, oy, BOARD, BOARD);
if (theme === 'stone') {
// a few hairline cracks and grout lines between the inlays
ctx.strokeStyle = 'rgba(30,24,20,0.35)'; ctx.lineWidth = 1;
for (let i = 1; i < 8; i++) {
ctx.beginPath(); ctx.moveTo(ox + i * SQ, oy); ctx.lineTo(ox + i * SQ, oy + BOARD); ctx.stroke();
ctx.beginPath(); ctx.moveTo(ox, oy + i * SQ); ctx.lineTo(ox + BOARD, oy + i * SQ); ctx.stroke();
}
ctx.strokeStyle = 'rgba(20,14,10,0.3)';
for (let i = 0; i < 3; i++) {
let px = ox + rnd() * BOARD, py = oy + rnd() * BOARD;
ctx.beginPath(); ctx.moveTo(px, py);
for (let k = 0; k < 5; k++) { px += (rnd() - 0.5) * 40; py += (rnd() - 0.5) * 40; ctx.lineTo(px, py); }
ctx.stroke();
}
}
addCanvas(scene, `cs-board-${theme}`, c);
}
// ── pieces ─────────────────────────────────────────────────────────────────
// Each piece is built from stacked parts (base, body, collar, head…), each
// filled with a cylindrical gradient and outlined, so it reads as carved.
const PAL = {
carved: {
w: { stops: ['#fffaf0', '#f2e6cc', '#d4c09a', '#a89068'], ol: '#3a2a16', hi: 'rgba(255,255,255,0.75)', rim: null, detail: '#5a4226' },
b: { stops: ['#5a5464', '#2e2a34', '#1a171e', '#0a090c'], ol: '#000000', hi: 'rgba(200,190,230,0.45)', rim: 'rgba(170,160,190,0.55)', detail: '#9a90b0' },
},
bold: {
w: { stops: ['#ffffff', '#ffffff', '#f4f4f4', '#e4e4e4'], ol: '#000000', hi: null, rim: null, detail: '#000000', width: 4.5 },
b: { stops: ['#202020', '#161616', '#101010', '#080808'], ol: '#000000', hi: null, rim: 'rgba(255,255,255,0.95)', detail: '#ffffff', width: 4.5 },
},
};
function partFill(ctx, pal, x0, x1) {
const g = ctx.createLinearGradient(x0, 0, x1, 0);
const s = pal.stops;
g.addColorStop(0, s[1]); g.addColorStop(0.22, s[0]); g.addColorStop(0.55, s[2]); g.addColorStop(1, s[3]);
return g;
}
function part(ctx, pal, path, x0, x1) {
ctx.beginPath(); path(ctx);
ctx.fillStyle = partFill(ctx, pal, x0, x1); ctx.fill();
if (pal.hi) {
ctx.save(); ctx.beginPath(); path(ctx); ctx.clip();
const hx = x0 + (x1 - x0) * 0.24;
const hg = ctx.createLinearGradient(hx - 4, 0, hx + 5, 0);
hg.addColorStop(0, 'rgba(255,255,255,0)'); hg.addColorStop(0.5, pal.hi); hg.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = hg; ctx.fillRect(hx - 4, -200, 9, 400);
ctx.restore();
}
ctx.beginPath(); path(ctx);
ctx.strokeStyle = pal.ol; ctx.lineWidth = pal.width ?? 2.4; ctx.lineJoin = 'round'; ctx.stroke();
if (pal.rim) {
ctx.save(); ctx.beginPath(); path(ctx); ctx.clip();
ctx.beginPath(); path(ctx);
ctx.strokeStyle = pal.rim; ctx.lineWidth = (pal.width ?? 2.4) * 0.9; ctx.stroke();
ctx.restore();
}
}
const rrect = (x, y, w, h, r) => (ctx) => rr(ctx, x, y, w, h, r);
const circ = (x, y, r) => (ctx) => ctx.arc(x, y, r, 0, Math.PI * 2);
const polyP = (pts) => (ctx) => { ctx.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i][0], pts[i][1]); ctx.closePath(); };
const flare = (wBot, wTop, yBot, yTop, pinch = 0.55) => (ctx) => {
// a concave-sided column: wide at the bottom, waisted, narrower at the top
ctx.moveTo(-wBot, yBot);
ctx.quadraticCurveTo(-wTop * pinch - (wBot - wTop) * 0.05, (yBot + yTop) / 2 + (yBot - yTop) * 0.12, -wTop, yTop);
ctx.lineTo(wTop, yTop);
ctx.quadraticCurveTo(wTop * pinch + (wBot - wTop) * 0.05, (yBot + yTop) / 2 + (yBot - yTop) * 0.12, wBot, yBot);
ctx.closePath();
};
function base(ctx, pal, w = 34) {
part(ctx, pal, rrect(-w, 84, w * 2, 9, 4), -w, w);
part(ctx, pal, rrect(-w + 6, 78, (w - 6) * 2, 7, 3), -w + 6, w - 6);
}
const PIECES = {
p(ctx, pal) {
base(ctx, pal, 28);
part(ctx, pal, flare(20, 9, 79, 50), -20, 20);
part(ctx, pal, rrect(-16, 45, 32, 7, 3), -16, 16);
part(ctx, pal, circ(0, 32, 14), -14, 14);
},
r(ctx, pal) {
base(ctx, pal, 32);
part(ctx, pal, flare(25, 17, 79, 40, 0.85), -25, 25);
part(ctx, pal, rrect(-23, 34, 46, 8, 2), -23, 23);
part(ctx, pal, polyP([[-24, 35], [-24, 12], [-14, 12], [-14, 20], [-5, 20], [-5, 12], [5, 12], [5, 20], [14, 20], [14, 12], [24, 12], [24, 35]]), -24, 24);
ctx.strokeStyle = pal.detail; ctx.lineWidth = 1.5; ctx.globalAlpha = 0.6;
ctx.beginPath(); ctx.moveTo(-18, 30); ctx.lineTo(18, 30); ctx.stroke();
ctx.globalAlpha = 1;
},
n(ctx, pal) {
base(ctx, pal, 32);
const head = (c) => {
c.moveTo(-22, 79);
c.quadraticCurveTo(-23, 62, -10, 52);
c.quadraticCurveTo(-20, 50, -29, 46);
c.quadraticCurveTo(-36, 41, -31, 33);
c.quadraticCurveTo(-23, 23, -13, 15);
c.lineTo(-9, 5);
c.lineTo(-4, 0);
c.lineTo(1, 9);
c.quadraticCurveTo(19, 14, 24, 36);
c.quadraticCurveTo(29, 60, 24, 79);
c.closePath();
};
part(ctx, pal, head, -32, 26);
// mane, eye, nostril, mouth
ctx.strokeStyle = pal.detail; ctx.lineCap = 'round';
ctx.lineWidth = 2; ctx.globalAlpha = 0.75;
for (let i = 0; i < 6; i++) {
const t = i / 6;
const x = 6 + t * 16, y = 14 + t * 54;
ctx.beginPath(); ctx.moveTo(x, y); ctx.quadraticCurveTo(x - 6, y + 4, x - 4, y + 10); ctx.stroke();
}
ctx.globalAlpha = 1;
ctx.fillStyle = pal.detail;
ctx.beginPath(); ctx.ellipse(-11, 25, 3, 2.2, -0.4, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.ellipse(-27, 37, 1.8, 1.4, 0, 0, Math.PI * 2); ctx.fill();
ctx.lineWidth = 1.6; ctx.beginPath(); ctx.moveTo(-30, 43); ctx.lineTo(-22, 44); ctx.stroke();
},
b(ctx, pal) {
base(ctx, pal, 30);
part(ctx, pal, flare(21, 9, 79, 47), -21, 21);
part(ctx, pal, rrect(-16, 43, 32, 6, 3), -16, 16);
part(ctx, pal, rrect(-12, 38, 24, 6, 3), -12, 12);
const mitre = (c) => {
c.moveTo(0, 8);
c.bezierCurveTo(-11, 15, -17, 26, -10, 39);
c.lineTo(10, 39);
c.bezierCurveTo(17, 26, 11, 15, 0, 8);
c.closePath();
};
part(ctx, pal, mitre, -15, 15);
ctx.strokeStyle = pal.ol; ctx.lineWidth = 3; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(5, 17); ctx.lineTo(-5, 29); ctx.stroke();
if (pal.rim) { ctx.strokeStyle = pal.detail; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(5, 17); ctx.lineTo(-5, 29); ctx.stroke(); }
part(ctx, pal, circ(0, 6, 5), -5, 5);
},
q(ctx, pal) {
base(ctx, pal, 33);
part(ctx, pal, flare(23, 10, 79, 40), -23, 23);
part(ctx, pal, rrect(-17, 35, 34, 7, 3), -17, 17);
part(ctx, pal, polyP([[-17, 36], [-24, 13], [-14, 25], [-12, 10], [-5, 24], [0, 7], [5, 24], [12, 10], [14, 25], [24, 13], [17, 36]]), -24, 24);
for (const [x, y, r] of [[-24, 11, 4], [-12, 8, 4], [0, 5, 4.5], [12, 8, 4], [24, 11, 4]]) part(ctx, pal, circ(x, y, r), x - r, x + r);
},
k(ctx, pal) {
base(ctx, pal, 34);
part(ctx, pal, flare(24, 11, 79, 38), -24, 24);
part(ctx, pal, rrect(-18, 33, 36, 7, 3), -18, 18);
const cup = (c) => {
c.moveTo(-18, 34);
c.bezierCurveTo(-24, 28, -24, 18, -12, 17);
c.lineTo(12, 17);
c.bezierCurveTo(24, 18, 24, 28, 18, 34);
c.closePath();
};
part(ctx, pal, cup, -22, 22);
part(ctx, pal, polyP([[-3.5, -2], [3.5, -2], [3.5, 3], [9, 3], [9, 9], [3.5, 9], [3.5, 17], [-3.5, 17], [-3.5, 9], [-9, 9], [-9, 3], [-3.5, 3]]), -9, 9);
},
};
function bakePieces(scene) {
for (const style of PIECE_STYLES) {
for (const col of ['w', 'b']) {
for (const t of ['p', 'n', 'b', 'r', 'q', 'k']) {
const c = canvas(PIECE_TEX, PIECE_TEX), ctx = c.getContext('2d');
ctx.translate(PIECE_TEX / 2, (8 + 2) * RES);
const k = RES * 0.86;
ctx.scale(k, k);
ctx.translate(0, 4);
PIECES[t](ctx, PAL[style][col]);
addCanvas(scene, `cs-${style}-${col}${t}`, c);
}
}
}
// the soft contact shadow under each piece
const S = PIECE_TEX, c = canvas(S, S / 2), ctx = c.getContext('2d');
ctx.save(); ctx.translate(S / 2, S / 4); ctx.scale(1, 0.3);
const g = ctx.createRadialGradient(0, 0, 0, 0, 0, S * 0.34);
g.addColorStop(0, 'rgba(0,0,0,0.7)'); g.addColorStop(0.6, 'rgba(0,0,0,0.35)'); g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, S * 0.34, 0, Math.PI * 2); ctx.fill();
ctx.restore();
addCanvas(scene, 'cs-shadow', c);
}
// ── pigeons ───────────────────────────────────────────────────────────────
function bakePigeons(scene) {
const FW = 64 * RES, FH = 52 * RES;
const draw = (ctx, f) => {
ctx.save(); ctx.scale(RES, RES);
const bodyCol = '#7a8090', dark = '#4a4e5c', light = '#a8aebc';
const legs = f === 0 ? [[-5, 4], [3, -3]] : f === 1 ? [[-2, 0], [1, 0]] : [[-3, 0], [3, 0]];
// legs
ctx.strokeStyle = '#d06a6a'; ctx.lineWidth = 1.6;
if (f < 3) for (const [a, bb] of legs) { ctx.beginPath(); ctx.moveTo(30 + a * 0.3, 38); ctx.lineTo(30 + a, 46); ctx.lineTo(30 + a + 3, 46); ctx.stroke(); void bb; }
// tail
ctx.fillStyle = dark;
ctx.beginPath(); ctx.moveTo(44, 30); ctx.lineTo(58, 26); ctx.lineTo(58, 32); ctx.lineTo(44, 36); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#2a2c36'; ctx.fillRect(55, 26, 3, 6);
// body
const bg = ctx.createLinearGradient(0, 20, 0, 42);
bg.addColorStop(0, light); bg.addColorStop(1, bodyCol);
ctx.fillStyle = bg;
ctx.beginPath(); ctx.ellipse(34, 32, 15, 9, f === 2 ? 0.35 : 0.08, 0, Math.PI * 2); ctx.fill();
// head + neck sheen
const hx = f === 2 ? 20 : f === 1 ? 19 : 22, hy = f === 2 ? 36 : 21;
ctx.fillStyle = '#5a7a6a';
ctx.beginPath(); ctx.ellipse((hx + 30) / 2, (hy + 28) / 2, 7, 6, 0.4, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(160,90,170,0.6)';
ctx.beginPath(); ctx.ellipse((hx + 30) / 2 + 1, (hy + 28) / 2 + 2, 5, 3.5, 0.4, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#6a7080';
ctx.beginPath(); ctx.arc(hx, hy, 5.5, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#e8a040'; ctx.beginPath(); ctx.arc(hx - 1.6, hy - 1.2, 1.4, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#111'; ctx.beginPath(); ctx.arc(hx - 1.8, hy - 1.2, 0.6, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#3a3030'; ctx.beginPath(); ctx.moveTo(hx - 5, hy); ctx.lineTo(hx - 9, hy + 1.5); ctx.lineTo(hx - 5, hy + 2); ctx.closePath(); ctx.fill();
// wings
ctx.fillStyle = '#8a90a0';
if (f === 3) { ctx.beginPath(); ctx.moveTo(30, 28); ctx.quadraticCurveTo(36, 2, 52, 4); ctx.quadraticCurveTo(44, 18, 42, 30); ctx.closePath(); ctx.fill(); }
else if (f === 4) { ctx.beginPath(); ctx.moveTo(30, 32); ctx.quadraticCurveTo(38, 50, 54, 50); ctx.quadraticCurveTo(46, 38, 42, 31); ctx.closePath(); ctx.fill(); }
else {
ctx.beginPath(); ctx.ellipse(38, 30, 10, 6, 0.1, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#3a3c48'; ctx.lineWidth = 1.6;
ctx.beginPath(); ctx.moveTo(34, 28); ctx.lineTo(40, 33); ctx.stroke();
ctx.beginPath(); ctx.moveTo(38, 27); ctx.lineTo(44, 32); ctx.stroke();
}
ctx.restore();
};
for (let f = 0; f < 5; f++) {
const c = canvas(FW, FH), ctx = c.getContext('2d');
draw(ctx, f);
addCanvas(scene, `cs-pigeon-${f}`, c);
}
}
// ── the chess clock ───────────────────────────────────────────────────────
function bakeClock(scene) {
const { w, h } = CLOCK, pad = 24;
const c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(33);
const x = pad, y = pad;
// wooden case, slightly trapezoidal
shadowed(ctx, () => {
ctx.fillStyle = '#2a160a';
ctx.beginPath(); ctx.moveTo(x + 10, y + 34); ctx.lineTo(x + w - 10, y + 34); ctx.lineTo(x + w, y + h); ctx.lineTo(x, y + h); ctx.closePath(); ctx.fill();
}, { blur: 22, dx: 6, dy: 14, alpha: 0.7 });
const g = ctx.createLinearGradient(0, y + 34, 0, y + h);
g.addColorStop(0, '#7a4a24'); g.addColorStop(1, '#4a2a12');
ctx.fillStyle = g;
ctx.beginPath(); ctx.moveTo(x + 10, y + 34); ctx.lineTo(x + w - 10, y + 34); ctx.lineTo(x + w, y + h); ctx.lineTo(x, y + h); ctx.closePath(); ctx.fill();
grain(ctx, rnd, x, y + 34, w, h - 34, { tone: 'rgba(20,8,0,0.3)', lines: 22, wave: 2 });
ctx.fillStyle = 'rgba(255,220,170,0.18)'; ctx.fillRect(x + 10, y + 34, w - 20, 3);
// top deck where the plungers sit
ctx.fillStyle = '#3a2010'; ctx.fillRect(x + 10, y + 26, w - 20, 10);
// brand plate
ctx.fillStyle = brass(ctx, x + w / 2 - 40, y + h - 26, x + w / 2 + 40, y + h - 12);
rr(ctx, x + w / 2 - 44, y + h - 28, 88, 16, 3); ctx.fill();
ctx.fillStyle = '#3a2408'; ctx.font = `bold 10px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('STONE TABLES', x + w / 2, y + h - 20);
// the two faces
for (const F of CLOCK_FACES) {
const fx = F.x - CLOCK.x + pad, fy = F.y - CLOCK.y + pad, R = F.r;
ctx.fillStyle = brass(ctx, fx - R - 6, fy - R - 6, fx + R + 6, fy + R + 6);
ctx.beginPath(); ctx.arc(fx, fy, R + 6, 0, Math.PI * 2); ctx.fill();
const fg = ctx.createRadialGradient(fx - 14, fy - 18, 4, fx, fy, R);
fg.addColorStop(0, '#fffdf4'); fg.addColorStop(1, '#e6dcc4');
ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(fx, fy, R, 0, Math.PI * 2); ctx.fill();
// the red sector before twelve, where the flag hangs
ctx.fillStyle = 'rgba(200,40,30,0.16)';
ctx.beginPath(); ctx.moveTo(fx, fy); ctx.arc(fx, fy, R - 2, -Math.PI / 2 - Math.PI / 6, -Math.PI / 2); ctx.closePath(); ctx.fill();
ctx.strokeStyle = '#2a2018';
for (let i = 0; i < 60; i++) {
const a = (i / 60) * Math.PI * 2 - Math.PI / 2;
const r0 = i % 5 === 0 ? R - 10 : R - 5;
ctx.lineWidth = i % 5 === 0 ? 2.2 : 1;
ctx.beginPath(); ctx.moveTo(fx + Math.cos(a) * r0, fy + Math.sin(a) * r0); ctx.lineTo(fx + Math.cos(a) * (R - 2), fy + Math.sin(a) * (R - 2)); ctx.stroke();
}
ctx.fillStyle = '#2a2018'; ctx.font = `bold 13px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
for (let i = 1; i <= 12; i++) {
const a = (i / 12) * Math.PI * 2 - Math.PI / 2;
ctx.fillText(String(i), fx + Math.cos(a) * (R - 20), fy + Math.sin(a) * (R - 20));
}
// glass glint
ctx.fillStyle = 'rgba(255,255,255,0.22)';
ctx.beginPath(); ctx.ellipse(fx - R * 0.35, fy - R * 0.45, R * 0.45, R * 0.18, -0.6, 0, Math.PI * 2); ctx.fill();
}
addCanvas(scene, 'cs-clock', c);
{
const bc = canvas(84, 40), bx = bc.getContext('2d');
const gg = bx.createLinearGradient(0, 0, 84, 0);
gg.addColorStop(0, '#2a2a30'); gg.addColorStop(0.3, '#8a8a96'); gg.addColorStop(0.6, '#4a4a54'); gg.addColorStop(1, '#1a1a20');
bx.fillStyle = gg; rr(bx, 6, 8, 72, 26, 8); bx.fill();
bx.fillStyle = 'rgba(255,255,255,0.3)'; rr(bx, 12, 10, 60, 5, 3); bx.fill();
bx.fillStyle = '#16161a'; bx.fillRect(36, 30, 12, 10);
addCanvas(scene, 'cs-clock-btn', bc);
}
}
// ── HUD furniture ──────────────────────────────────────────────────────────
function bakePlate(scene) {
const pad = 14, w = PLATE.w, h = PLATE.h;
{
// a slatted park-bench back, painted green, iron brackets at the ends
const c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(5);
shadowed(ctx, () => { ctx.fillStyle = '#10140e'; rr(ctx, pad, pad, w, h, 10); ctx.fill(); }, { blur: 14, dx: 5, dy: 8, alpha: 0.65 });
const slats = 5, sh = (h - 8) / slats;
for (let i = 0; i < slats; i++) {
const sy = pad + 4 + i * sh;
const g = ctx.createLinearGradient(0, sy, 0, sy + sh);
g.addColorStop(0, '#3e5a3a'); g.addColorStop(1, '#263a24');
ctx.fillStyle = g; rr(ctx, pad + 2, sy + 1, w - 4, sh - 3, 5); ctx.fill();
grain(ctx, rnd, pad + 2, sy + 1, w - 4, sh - 3, { tone: 'rgba(10,20,8,0.4)', lines: 5, wave: 1.5 });
// chipped paint showing the wood
for (let k = 0; k < 5; k++) {
ctx.fillStyle = 'rgba(140,100,60,0.45)';
ctx.beginPath(); ctx.ellipse(pad + 10 + rnd() * (w - 20), sy + 4 + rnd() * (sh - 10), 2 + rnd() * 6, 1 + rnd() * 2, 0, 0, Math.PI * 2); ctx.fill();
}
ctx.fillStyle = 'rgba(255,255,255,0.08)'; ctx.fillRect(pad + 6, sy + 2, w - 12, 2);
}
// iron end brackets with bolts
for (const bx of [pad - 2, pad + w - 16]) {
ctx.fillStyle = '#16181c'; rr(ctx, bx, pad - 4, 18, h + 8, 5); ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.12)'; ctx.fillRect(bx + 3, pad, 2, h);
for (let i = 0; i < 5; i++) { ctx.fillStyle = '#4a4e56'; ctx.beginPath(); ctx.arc(bx + 9, pad + 4 + sh * (i + 0.5), 3, 0, Math.PI * 2); ctx.fill(); }
}
addCanvas(scene, 'cs-plate', c);
}
{
const P = 40, c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
ctx.shadowColor = 'rgba(255,210,130,1)'; ctx.shadowBlur = 30;
ctx.strokeStyle = 'rgba(255,220,140,0.95)'; ctx.lineWidth = 5; rr(ctx, P, P, w, h, 10); ctx.stroke();
addCanvas(scene, 'cs-plate-glow', c);
}
}
function bakeChalkboard(scene) {
const { w, h } = STATUS, pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(41);
shadowed(ctx, () => { ctx.fillStyle = '#3a2412'; rr(ctx, pad, pad, w, h, 8); ctx.fill(); }, { blur: 16, dx: 5, dy: 9, alpha: 0.6 });
const fg = ctx.createLinearGradient(0, pad, 0, pad + h);
fg.addColorStop(0, '#6a4224'); fg.addColorStop(1, '#3e2410');
ctx.fillStyle = fg; rr(ctx, pad, pad, w, h, 8); ctx.fill();
grain(ctx, rnd, pad, pad, w, h, { tone: 'rgba(20,8,0,0.35)', lines: 16, wave: 2 });
const bx = pad + 12, by = pad + 12, bw = w - 24, bh = h - 24;
const bg = ctx.createLinearGradient(bx, by, bx + bw, by + bh);
bg.addColorStop(0, '#2c3a34'); bg.addColorStop(1, '#1c2824');
ctx.fillStyle = bg; ctx.fillRect(bx, by, bw, bh);
// old smudged chalk
for (let i = 0; i < 16; i++) {
const x = bx + rnd() * bw, y = by + rnd() * bh, r = 20 + rnd() * 60;
const sg = ctx.createRadialGradient(x, y, 0, x, y, r);
sg.addColorStop(0, 'rgba(230,236,230,0.07)'); sg.addColorStop(1, 'rgba(230,236,230,0)');
ctx.fillStyle = sg; ctx.fillRect(x - r, y - r, r * 2, r * 2);
}
ctx.fillStyle = noisePattern(ctx, 64, 12); ctx.fillRect(bx, by, bw, bh);
// a stub of chalk on the ledge
ctx.fillStyle = '#f4f0e8'; rr(ctx, pad + w - 70, pad + h - 9, 26, 6, 3); ctx.fill();
addCanvas(scene, 'cs-chalk', c);
}
function bakeSheet(scene) {
// a spiral-bound score sheet
const { w, h } = LOG, pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(77);
shadowed(ctx, () => { ctx.fillStyle = '#f2ecdc'; rr(ctx, pad, pad, w, h, 4); ctx.fill(); }, { blur: 16, dx: 5, dy: 9, alpha: 0.6 });
const paper = ctx.createLinearGradient(0, pad, 0, pad + h);
paper.addColorStop(0, '#f8f4e8'); paper.addColorStop(1, '#e8e0cc');
ctx.fillStyle = paper; rr(ctx, pad, pad, w, h, 4); ctx.fill();
ctx.save(); rr(ctx, pad, pad, w, h, 4); ctx.clip();
ctx.fillStyle = '#2a4a3a'; ctx.fillRect(pad, pad, w, 58);
ctx.strokeStyle = 'rgba(70,110,170,0.3)'; ctx.lineWidth = 1;
for (let y = pad + 98; y < pad + h - 8; y += 31) { ctx.beginPath(); ctx.moveTo(pad + 8, y); ctx.lineTo(pad + w - 8, y); ctx.stroke(); }
ctx.strokeStyle = 'rgba(190,50,40,0.35)';
ctx.beginPath(); ctx.moveTo(pad + 62, pad + 58); ctx.lineTo(pad + 62, pad + h); ctx.stroke();
ctx.beginPath(); ctx.moveTo(pad + 62 + (w - 62) / 2, pad + 58); ctx.lineTo(pad + 62 + (w - 62) / 2, pad + h); ctx.stroke();
for (let i = 0; i < 12; i++) {
const x = pad + rnd() * w, y = pad + 60 + rnd() * (h - 60), r = 2 + rnd() * 7;
ctx.fillStyle = `rgba(150,110,50,${0.03 + rnd() * 0.05})`; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
}
ctx.fillStyle = noisePattern(ctx, 64, 12); ctx.fillRect(pad, pad, w, h);
ctx.restore();
// spiral rings
for (let x = pad + 24; x < pad + w - 10; x += 22) {
ctx.fillStyle = '#1a1a1e'; ctx.beginPath(); ctx.arc(x, pad + 4, 3.5, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#9aa0aa'; ctx.lineWidth = 2.5; ctx.beginPath(); ctx.arc(x, pad - 2, 6, Math.PI * 0.15, Math.PI * 0.95); ctx.stroke();
}
addCanvas(scene, 'cs-sheet', c);
}
function bakeSlate(scene) {
const { w, h } = RIBBON, pad = 12, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(12);
shadowed(ctx, () => { ctx.fillStyle = '#16141a'; rr(ctx, pad, pad, w, h, 10); ctx.fill(); }, { blur: 14, dx: 3, dy: 7, alpha: 0.6 });
const g = ctx.createLinearGradient(0, pad, 0, pad + h);
g.addColorStop(0, '#34323c'); g.addColorStop(1, '#1e1c24');
ctx.fillStyle = g; rr(ctx, pad, pad, w, h, 10); ctx.fill();
speckle(ctx, rnd, pad, pad, w, h, 600, ['rgba(255,255,255,0.05)', 'rgba(0,0,0,0.2)'], 1.2);
ctx.setLineDash([6, 5]); ctx.strokeStyle = 'rgba(230,220,200,0.3)'; ctx.lineWidth = 1.5; rr(ctx, pad + 6, pad + 6, w - 12, h - 12, 7); ctx.stroke(); ctx.setLineDash([]);
// Marcus's badge: a knight on a brass disc
const bx = pad + 40, by = pad + h / 2;
ctx.fillStyle = brass(ctx, bx - 24, by - 24, bx + 24, by + 24); ctx.beginPath(); ctx.arc(bx, by, 24, 0, Math.PI * 2); ctx.fill();
ctx.save(); ctx.translate(bx + 2, by - 1); ctx.scale(0.4, 0.4); ctx.translate(0, -44);
PIECES.n(ctx, { stops: ['#4a2e10', '#3a2408', '#2a1a06', '#1a1004'], ol: '#1a1004', hi: null, rim: null, detail: '#d8b060', width: 2 });
ctx.restore();
addCanvas(scene, 'cs-slate', c);
}
function bakeBits(scene) {
const radial = (key, S, stops) => {
const c = canvas(S, S), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2);
stops.forEach(([o, col]) => g.addColorStop(o, col));
ctx.fillStyle = g; ctx.fillRect(0, 0, S, S);
addCanvas(scene, key, c);
};
radial('cs-glow', 128, [[0, 'rgba(255,226,140,0.9)'], [0.45, 'rgba(255,200,90,0.45)'], [1, 'rgba(255,190,80,0)']]);
radial('cs-check', 160, [[0, 'rgba(255,60,40,0.95)'], [0.45, 'rgba(230,40,30,0.55)'], [1, 'rgba(200,20,20,0)']]);
radial('cs-spark', 24, [[0, 'rgba(255,255,255,1)'], [0.35, 'rgba(255,240,200,0.8)'], [1, 'rgba(255,220,150,0)']]);
radial('cs-dust', 64, [[0, 'rgba(220,210,200,0.55)'], [1, 'rgba(220,210,200,0)']]);
radial('cs-lamp-glow', 360, [[0, 'rgba(255,214,140,0.55)'], [0.4, 'rgba(255,200,120,0.2)'], [1, 'rgba(255,200,120,0)']]);
radial('cs-drop', 12, [[0, 'rgba(220,240,255,0.95)'], [1, 'rgba(160,200,240,0)']]);
{
const S = 96, c = canvas(S, S), ctx = c.getContext('2d');
ctx.strokeStyle = 'rgba(255,224,130,1)'; ctx.lineWidth = 5;
ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 5, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 10, 0, Math.PI * 2); ctx.stroke();
addCanvas(scene, 'cs-ring', c);
}
{
const S = 40, c = canvas(S, S), ctx = c.getContext('2d');
ctx.fillStyle = 'rgba(20,20,20,0.9)'; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 4, 0, Math.PI * 2); ctx.fill();
addCanvas(scene, 'cs-dot', c);
}
{
// capture marker: a ring hugging the square's corners
const S = 100, c = canvas(S, S), ctx = c.getContext('2d');
ctx.fillStyle = 'rgba(20,20,20,1)';
ctx.beginPath(); ctx.rect(0, 0, S, S); ctx.arc(S / 2, S / 2, S / 2 - 2, 0, Math.PI * 2, true); ctx.fill();
addCanvas(scene, 'cs-cap', c);
}
const leafCols = ['#c0602a', '#d8a040', '#9a2a1e', '#8a7a2a'];
leafCols.forEach((col, i) => {
const c = canvas(28, 18), ctx = c.getContext('2d');
ctx.fillStyle = col;
ctx.beginPath(); ctx.moveTo(2, 9); ctx.quadraticCurveTo(14, -2, 26, 9); ctx.quadraticCurveTo(14, 20, 2, 9); ctx.fill();
ctx.strokeStyle = 'rgba(60,20,10,0.6)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(2, 9); ctx.lineTo(26, 9); ctx.stroke();
addCanvas(scene, `cs-leaf-${i}`, c);
});
}
let baked = false;
export async function prepareChessArt(scene) {
try {
if (document.fonts?.load) {
await Promise.race([
Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]),
new Promise((res) => setTimeout(res, 1200)),
]);
}
} catch (_) { /* fall back to Georgia */ }
if (!baked || !scene.textures.exists('cs-park')) {
bakePark(scene);
for (const t of BOARD_THEMES) bakeBoard(scene, t);
bakePieces(scene); bakePigeons(scene); bakeClock(scene);
bakePlate(scene); bakeChalkboard(scene); bakeSheet(scene); bakeSlate(scene); bakeBits(scene);
baked = true;
}
}
export const pieceKey = (style, color, type) => `cs-${style}-${color}${type}`;

View File

@ -0,0 +1,201 @@
// ChessBook.js — Marcus's opening book. A few dozen main lines (in SAN) the
// park regulars actually play, and the names that go with them. Positions
// are matched by FEN (no clocks), so transpositions still find the book and
// still get named. Used only for games from the standard start.
//
// bookMoves(game) → [{ m, uci, w }] candidate book replies here
// openingName(game) → the most specific name the game has reached, or null
//
// tools/verifyChess.js checks every line and every name is legal.
import { Chess, START_FEN, toFen, fromSan, makeMove, toUci } from './ChessLogic.js';
export const LINES = [
// ── open games ──
['e4 e5 Nf3 Nc6 Bc4 Bc5 c3 Nf6 d3 d6 O-O O-O', 3],
['e4 e5 Nf3 Nc6 Bc4 Bc5 b4 Bxb4 c3 Ba5 d4 exd4 O-O', 1],
['e4 e5 Nf3 Nc6 Bc4 Nf6 d3 Be7 O-O O-O Re1 d6', 2],
['e4 e5 Nf3 Nc6 Bb5 a6 Ba4 Nf6 O-O Be7 Re1 b5 Bb3 d6 c3 O-O', 3],
['e4 e5 Nf3 Nc6 Bb5 Nf6 O-O Nxe4 d4 Nd6 Bxc6 dxc6 dxe5 Nf5', 2],
['e4 e5 Nf3 Nc6 d4 exd4 Nxd4 Nf6 Nxc6 bxc6 e5 Qe7', 2],
['e4 e5 Nf3 Nf6 Nxe5 d6 Nf3 Nxe4 d4 d5 Bd3', 1],
['e4 e5 Nf3 Nc6 Nc3 Nf6 Bb5 Bb4 O-O O-O d3 d6', 1],
['e4 e5 f4 exf4 Nf3 g5 h4 g4 Ne5', 1],
['e4 e5 Nc3 Nf6 f4 d5 fxe5 Nxe4 Nf3', 1],
['e4 e5 Nf3 d6 d4 Nf6 Nc3 Nbd7 Bc4 Be7 O-O O-O', 1],
// ── Sicilian ──
['e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6 Be3 e5 Nb3 Be6', 3],
['e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 g6 Be3 Bg7 f3 O-O Qd2 Nc6', 2],
['e4 c5 Nf3 Nc6 d4 cxd4 Nxd4 Nf6 Nc3 e5 Ndb5 d6', 2],
['e4 c5 Nf3 e6 d4 cxd4 Nxd4 a6 Bd3 Nf6 O-O Qc7', 2],
['e4 c5 c3 Nf6 e5 Nd5 d4 cxd4 Nf3 Nc6', 1],
['e4 c5 d4 cxd4 c3 dxc3 Nxc3 Nc6 Nf3 d6 Bc4 e6', 1],
// ── other replies to 1.e4 ──
['e4 e6 d4 d5 Nc3 Nf6 Bg5 Be7 e5 Nfd7 Bxe7 Qxe7', 2],
['e4 e6 d4 d5 e5 c5 c3 Nc6 Nf3 Qb6', 2],
['e4 e6 d4 d5 Nc3 Bb4 e5 c5 a3 Bxc3+ bxc3 Ne7', 1],
['e4 c6 d4 d5 Nc3 dxe4 Nxe4 Bf5 Ng3 Bg6 h4 h6 Nf3 Nd7', 2],
['e4 c6 d4 d5 e5 Bf5 Nf3 e6 Be2 c5', 2],
['e4 d6 d4 Nf6 Nc3 g6 Nf3 Bg7 Be2 O-O O-O', 1],
['e4 d5 exd5 Qxd5 Nc3 Qa5 d4 Nf6 Nf3 c6 Bc4 Bf5', 1],
['e4 Nf6 e5 Nd5 d4 d6 Nf3 Bg4 Be2 e6', 1],
['e4 g6 d4 Bg7 Nc3 d6 Be3 a6 Qd2 b5', 1],
// ── closed games ──
['d4 d5 c4 e6 Nc3 Nf6 Bg5 Be7 e3 O-O Nf3 Nbd7', 3],
['d4 d5 c4 e6 Nc3 Nf6 cxd5 exd5 Bg5 Be7 e3 c6', 1],
['d4 d5 c4 dxc4 Nf3 Nf6 e3 e6 Bxc4 c5 O-O a6', 2],
['d4 d5 c4 c6 Nf3 Nf6 Nc3 dxc4 a4 Bf5 e3 e6 Bxc4 Bb4', 2],
['d4 d5 Bf4 Nf6 e3 e6 Nf3 c5 c3 Nc6 Nbd2 Bd6', 2],
['d4 Nf6 c4 g6 Nc3 Bg7 e4 d6 Nf3 O-O Be2 e5 O-O Nc6', 3],
['d4 Nf6 c4 e6 Nc3 Bb4 e3 O-O Bd3 d5 Nf3 c5', 2],
['d4 Nf6 c4 e6 Nf3 b6 g3 Bb7 Bg2 Be7 O-O O-O', 1],
['d4 Nf6 c4 g6 Nc3 d5 cxd5 Nxd5 e4 Nxc3 bxc3 Bg7', 2],
['d4 Nf6 c4 c5 d5 e6 Nc3 exd5 cxd5 d6 e4 g6', 1],
['d4 Nf6 c4 e6 g3 d5 Bg2 Be7 Nf3 O-O O-O dxc4', 1],
['d4 f5 g3 Nf6 Bg2 e6 Nf3 Be7 O-O O-O c4 d6', 1],
['d4 Nf6 Bg5 Ne4 Bf4 c5 f3 Qa5+ c3 Nf6', 1],
// ── flank openings ──
['c4 e5 Nc3 Nf6 g3 d5 cxd5 Nxd5 Bg2 Nb6', 2],
['c4 c5 Nc3 Nc6 g3 g6 Bg2 Bg7 Nf3 e6', 1],
['Nf3 d5 c4 e6 g3 Nf6 Bg2 Be7 O-O O-O', 1],
['Nf3 d5 g3 Nf6 Bg2 c6 O-O Bg4 d3 Nbd7', 1],
['f4 d5 Nf3 Nf6 e3 g6 b3 Bg7 Bb2 O-O', 1],
];
export const NAMES = [
['e4', 'King\'s Pawn Opening'],
['e4 e5', 'Open Game'],
['e4 e5 Nf3 Nc6 Bc4', 'Italian Game'],
['e4 e5 Nf3 Nc6 Bc4 Bc5', 'Giuoco Piano'],
['e4 e5 Nf3 Nc6 Bc4 Bc5 b4', 'Evans Gambit'],
['e4 e5 Nf3 Nc6 Bc4 Nf6', 'Two Knights Defence'],
['e4 e5 Nf3 Nc6 Bb5', 'Ruy Lopez'],
['e4 e5 Nf3 Nc6 Bb5 a6', 'Ruy Lopez, Morphy Defence'],
['e4 e5 Nf3 Nc6 Bb5 Nf6', 'Ruy Lopez, Berlin Defence'],
['e4 e5 Nf3 Nc6 d4', 'Scotch Game'],
['e4 e5 Nf3 Nf6', 'Petrov\'s Defence'],
['e4 e5 Nf3 Nc6 Nc3 Nf6', 'Four Knights Game'],
['e4 e5 f4', 'King\'s Gambit'],
['e4 e5 f4 exf4', 'King\'s Gambit Accepted'],
['e4 e5 Nc3', 'Vienna Game'],
['e4 e5 Nf3 d6', 'Philidor Defence'],
['e4 c5', 'Sicilian Defence'],
['e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6', 'Sicilian, Najdorf'],
['e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 g6', 'Sicilian, Dragon'],
['e4 c5 Nf3 Nc6 d4 cxd4 Nxd4 Nf6 Nc3 e5', 'Sicilian, Sveshnikov'],
['e4 c5 Nf3 e6 d4 cxd4 Nxd4 a6', 'Sicilian, Kan'],
['e4 c5 c3', 'Sicilian, Alapin'],
['e4 c5 d4 cxd4 c3', 'Smith–Morra Gambit'],
['e4 e6', 'French Defence'],
['e4 e6 d4 d5 e5', 'French, Advance'],
['e4 e6 d4 d5 Nc3 Bb4', 'French, Winawer'],
['e4 e6 d4 d5 Nc3 Nf6', 'French, Classical'],
['e4 c6', 'Caro–Kann Defence'],
['e4 c6 d4 d5 e5', 'Caro–Kann, Advance'],
['e4 d6', 'Pirc Defence'],
['e4 d5', 'Scandinavian Defence'],
['e4 Nf6', 'Alekhine\'s Defence'],
['e4 g6', 'Modern Defence'],
['d4', 'Queen\'s Pawn Opening'],
['d4 d5 c4', 'Queen\'s Gambit'],
['d4 d5 c4 e6', 'Queen\'s Gambit Declined'],
['d4 d5 c4 e6 Nc3 Nf6 cxd5', 'QGD, Exchange Variation'],
['d4 d5 c4 dxc4', 'Queen\'s Gambit Accepted'],
['d4 d5 c4 c6', 'Slav Defence'],
['d4 d5 Bf4', 'London System'],
['d4 Nf6', 'Indian Defence'],
['d4 Nf6 c4 g6 Nc3 Bg7', 'King\'s Indian Defence'],
['d4 Nf6 c4 g6 Nc3 d5', 'Grünfeld Defence'],
['d4 Nf6 c4 e6 Nc3 Bb4', 'Nimzo-Indian Defence'],
['d4 Nf6 c4 e6 Nf3 b6', 'Queen\'s Indian Defence'],
['d4 Nf6 c4 c5 d5', 'Benoni Defence'],
['d4 Nf6 c4 e6 g3', 'Catalan Opening'],
['d4 Nf6 Bg5', 'Trompowsky Attack'],
['d4 f5', 'Dutch Defence'],
['c4', 'English Opening'],
['c4 c5', 'English, Symmetrical'],
['Nf3', 'Réti Opening'],
['Nf3 d5 g3', 'King\'s Indian Attack'],
['f4', 'Bird\'s Opening'],
];
const key = (pos) => toFen(pos, { clocks: false });
let BOOK = null; // fen → Map(uci → weight)
let NAMEMAP = null; // fen → { name, depth }
function build() {
BOOK = new Map();
NAMEMAP = new Map();
for (const [line, w] of LINES) {
const g = new Chess(START_FEN);
for (const san of line.split(' ')) {
const m = fromSan(g.pos, san);
if (!m) break;
const k = key(g.pos);
const uci = toUci(g.pos, m);
if (!BOOK.has(k)) BOOK.set(k, new Map());
const mp = BOOK.get(k);
mp.set(uci, (mp.get(uci) ?? 0) + w);
makeMove(g.pos, m);
}
}
for (const [line, name] of NAMES) {
const g = new Chess(START_FEN);
let okAll = true;
const sans = line.split(' ');
for (const san of sans) {
const m = fromSan(g.pos, san);
if (!m) { okAll = false; break; }
makeMove(g.pos, m);
}
if (okAll) NAMEMAP.set(key(g.pos), { name, depth: sans.length });
}
}
/** Book replies in the game's current position. */
export function bookMoves(game) {
if (!BOOK) build();
if (game.startFen !== START_FEN) return [];
const mp = BOOK.get(key(game.pos));
if (!mp) return [];
const out = [];
for (const [uci, w] of mp) {
const g2 = game.pos;
const m = game.moves().find((r) => r.uci === uci)?.m;
if (m) out.push({ m, uci, w });
void g2;
}
return out;
}
/** The most specific opening name reached so far (null if none). */
export function openingName(game) {
if (!NAMEMAP) build();
if (game.startFen !== START_FEN) return null;
const g = new Chess(START_FEN);
let best = null;
const limit = Math.min(game.history.length, 24);
for (let i = 0; i < limit; i++) {
makeMove(g.pos, game.history[i].m);
const hit = NAMEMAP.get(key(g.pos));
if (hit && (!best || hit.depth >= best.depth)) best = hit;
}
return best?.name ?? null;
}
/** For the verifier: [{ line, ok, at }] for every book line + name. */
export function checkBook() {
const out = [];
for (const [line] of [...LINES, ...NAMES]) {
const g = new Chess(START_FEN);
let at = -1;
line.split(' ').forEach((san, i) => {
if (at >= 0) return;
const m = fromSan(g.pos, san);
if (!m) at = i; else makeMove(g.pos, m);
});
out.push({ line, ok: at < 0, at });
}
return out;
}

View File

@ -0,0 +1,221 @@
// ChessDialogs.js — pop-ups at the Stone Tables: a cream card in a
// park-bench green frame with an iron trim. Each opener returns
// { close() } and swallows clicks beneath.
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { DISPLAY_FONT, SERIF, pieceKey } from './ChessArt.js';
import { fmtClock } from './ChessHud.js';
const INK = '#1e2a1a';
const BTN_BG = 0x2a3a24;
export const TIME_CONTROLS = [
{ id: 'none', name: 'Untimed', base: 0, inc: 0, blurb: 'No clock. Take all the time you want; take-backs allowed.' },
{ id: 'blitz', name: 'Blitz 5 + 0', base: 5 * 60000, inc: 0, blurb: 'Five minutes each, no increment. Park rules: the clock is the clock.' },
{ id: 'rapid', name: 'Rapid 10 + 5', base: 10 * 60000, inc: 5000, blurb: 'Ten minutes each, plus five seconds every move.' },
{ id: 'classical', name: 'Classical 30 + 0', base: 30 * 60000, inc: 0, blurb: 'Half an hour each. Room to think.' },
];
export const tcOf = (id) => TIME_CONTROLS.find((t) => t.id === id) ?? TIME_CONTROLS[0];
export function frame(scene, x, y, w, h, depth) {
const g = scene.add.graphics().setDepth(depth);
g.fillStyle(0x000000, 0.5).fillRoundedRect(x + 6, y + 10, w, h, 14);
g.fillStyle(0x2a3a24, 1).fillRoundedRect(x, y, w, h, 14);
g.lineStyle(3, 0x16181c, 1).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 12);
g.lineStyle(2, 0xd8b060, 0.9).strokeRoundedRect(x + 9, y + 9, w - 18, h - 18, 9);
g.fillStyle(0xf6f0de, 1).fillRoundedRect(x + 16, y + 16, w - 32, h - 32, 6);
// a band of fallen-leaf colours along the top
const cols = [0xa8542a, 0xc88a32, 0x8a2a1e, 0x5a6a2a];
for (let i = 0; i < w - 32; i += 22) g.fillStyle(cols[(i / 22) % cols.length], 1).fillRect(x + 16 + i, y + 16, Math.min(22, w - 32 - i), 6);
g.lineStyle(1.5, 0x6a7a5a, 0.5).strokeRoundedRect(x + 24, y + 30, w - 48, h - 54, 4);
return g;
}
export function blocker(scene, depth, alpha = 0) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x05040a, alpha).setDepth(depth).setInteractive();
}
export function handle(objs, onClose) {
let closed = false;
return { objs, close() { if (closed) return; closed = true; objs.forEach((o) => o?.destroy?.()); onClose?.(); } };
}
const onOff = (v) => (v ? 'On' : 'Off');
const PACE = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' };
const THEME = { stone: 'Inlaid stone', walnut: 'Walnut', green: 'Tournament green' };
const STYLE = { carved: 'Carved Staunton', bold: 'Bold (high contrast)' };
export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose, puzzle = false }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 640, h = 900;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(scene.add.text(x + w / 2, y + 64, 'The Stone Tables', { fontFamily: DISPLAY_FONT, fontSize: '32px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
const cx = x + w / 2;
let hRef = null;
const cycle = (k, order) => onChange(k, order[(order.indexOf(settings[k]) + 1) % order.length]);
const rows = [
['Resume', () => hRef.close(), 0x2a4a6a],
[() => `Board: ${THEME[settings.board]}`, () => cycle('board', ['stone', 'walnut', 'green'])],
[() => `Pieces: ${STYLE[settings.pieces]}`, () => cycle('pieces', ['carved', 'bold'])],
[() => `Opponent speed: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])],
[() => `Show legal moves: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)],
[() => `Marcus warns before a blunder: ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)],
[() => `Evaluation bar: ${onOff(settings.evalBar)}`, () => onChange('evalBar', !settings.evalBar)],
[() => `Premoves while they think: ${onOff(settings.premove)}`, () => onChange('premove', !settings.premove)],
[() => `Always promote to a queen: ${onOff(settings.autoQueen)}`, () => onChange('autoQueen', !settings.autoQueen)],
[() => `Board coordinates: ${onOff(settings.coords)}`, () => onChange('coords', !settings.coords)],
[() => `Park sounds: ${onOff(settings.ambience)}`, () => onChange('ambience', !settings.ambience)],
['How to Play', () => onRules()],
[puzzle ? 'Back to the Setup Card…' : 'New Game…', () => { hRef.close(); onNewGame(); }, 0x6a4a1a],
['Leave the Park', () => { hRef.close(); onLeave(); }, 0x7a1a14],
];
rows.forEach(([label, fn, bg], i) => {
const text = typeof label === 'function' ? label() : label;
const btn = new Button(scene, cx, y + 120 + i * 52, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, {
width: 560, height: 44, fontSize: 16, bg: bg ?? BTN_BG,
}).setDepth(depth + 2);
objs.push(btn);
});
objs.push(scene.add.text(cx, y + h - 50, 'Click or drag a piece · Z undo · H hint · F flip board · ← → step through moves\nArrows + Enter to play with the keyboard · Esc menu', {
fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#3a4a2a', align: 'center',
}).setOrigin(0.5).setDepth(depth + 1));
hRef = handle(objs, onClose);
return hRef;
}
/**
* The setup card. prefs = { mode, color, tc, c960 }.
* extra = { puzzleRating, dailyDone, dailyStreak, week: [{label, state, today}], record }
*/
export function openSetup(scene, { prefs, depth, opponentName, skill, extra = {}, onStart, onLeave }) {
const objs = [blocker(scene, depth - 1, 0.6)];
const w = 800, h = 760;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
const p = { ...prefs };
const cx = x + w / 2;
objs.push(scene.add.text(cx, y + 66, 'Table Nine', { fontFamily: DISPLAY_FONT, fontSize: '36px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(cx, y + 104, 'The park at dusk. Marcus is holding your bench.', { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#4a5a3a' }).setOrigin(0.5).setDepth(depth + 1));
// mode tabs
const modes = [
['play', `Play ${opponentName.length > 12 ? opponentName.split(' ')[0] : opponentName}`],
['ladder', 'Puzzle Ladder'],
['daily', extra.dailyDone ? 'Daily Puzzle ✓' : 'Daily Puzzle'],
];
const tabs = modes.map(([id, label], i) => {
const b = new Button(scene, cx - 250 + i * 250, y + 162, label, () => { p.mode = id; refresh(); }, { width: 236, height: 50, fontSize: 18, bg: BTN_BG }).setDepth(depth + 2);
objs.push(b);
return { id, b };
});
const panel = [];
const clearPanel = () => { panel.forEach((o) => o.destroy()); panel.length = 0; };
const labelX = x + 80, ctlX = x + 500;
const rowY = (i) => y + 252 + i * 76;
const cyc = (list, v) => list[(list.indexOf(v) + 1) % list.length];
const addRow = (i, title, get, fn) => {
panel.push(scene.add.text(labelX, rowY(i), title, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 1));
const btn = new Button(scene, ctlX, rowY(i), get(), () => { fn(); refresh(); }, { width: 340, height: 46, fontSize: 18, bg: BTN_BG }).setDepth(depth + 2);
panel.push(btn);
};
const blurb = scene.add.text(cx, y + 580, '', { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#3a4a2a', align: 'center', wordWrap: { width: w - 140 }, lineSpacing: 4 })
.setOrigin(0.5).setDepth(depth + 1);
objs.push(blurb);
let startBtn = null;
function refresh() {
tabs.forEach(({ id, b }) => b.setActive?.(id === p.mode));
clearPanel();
if (p.mode === 'play') {
addRow(0, 'Your colour', () => (p.color === 'random' ? 'Flip a coin' : p.color === 'w' ? 'White (moves first)' : 'Black'), () => { p.color = cyc(['w', 'b', 'random'], p.color); });
addRow(1, 'Clock', () => tcOf(p.tc).name, () => { p.tc = cyc(TIME_CONTROLS.map((t) => t.id), p.tc); });
addRow(2, 'Starting position', () => (p.c960 ? 'Chess960 (random)' : 'Standard'), () => { p.c960 = !p.c960; });
let b = `${tcOf(p.tc).blurb}`;
if (p.c960) b += ' Chess960: the back rank is shuffled (bishops on opposite colours, king between the rooks). No opening book for anybody.';
b += `\n${opponentName} plays at skill ${skill} of 5.`;
if (extra.record) b += ` Your record: ${extra.record.w} won · ${extra.record.d} drawn · ${extra.record.l} lost.`;
blurb.setText(b);
startBtn?.setLabel('Set \'Em Up');
} else if (p.mode === 'ladder') {
panel.push(scene.add.text(cx, rowY(0) + 10, `Your puzzle rating: ${extra.puzzleRating ?? 1000}`, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
panel.push(scene.add.text(cx, rowY(1) + 6, `${extra.solved ?? 0} solved · best streak ${extra.bestStreak ?? 0} · ${extra.total ?? 0} in Marcus's notebook`, { fontFamily: SERIF, fontSize: '18px', color: '#3a4a2a' }).setOrigin(0.5).setDepth(depth + 1));
blurb.setText('Tactics from real games played at these tables. Each one has a single best move: find it. Solve to climb, miss to drop. Hints and the solution are there when you need them, but they don\'t count.');
startBtn?.setLabel('Open the Notebook');
} else {
const wk = extra.week ?? [];
panel.push(scene.add.text(cx, rowY(0) - 6, `Daily Puzzle #${extra.dailyNumber ?? 1}`, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
wk.forEach((d, i) => {
const bx = cx - 3 * 70 + i * 70, by = rowY(1) + 6;
const g = scene.add.graphics().setDepth(depth + 1);
const col = d.state === 'solved' ? 0x3a7a3a : d.state === 'failed' ? 0x9a3a2a : 0xd8d0b8;
g.fillStyle(col, 1).fillRoundedRect(bx - 26, by - 26, 52, 52, 8);
if (d.today) g.lineStyle(3, 0xd8a030, 1).strokeRoundedRect(bx - 28, by - 28, 56, 56, 9);
panel.push(g);
panel.push(scene.add.text(bx, by - 8, d.label, { fontFamily: DISPLAY_FONT, fontSize: '15px', color: d.state ? '#fff8e8' : '#4a4a3a' }).setOrigin(0.5).setDepth(depth + 2));
panel.push(scene.add.text(bx, by + 12, d.state === 'solved' ? '✓' : d.state === 'failed' ? '✗' : '', { fontFamily: SERIF, fontSize: '18px', color: '#fff8e8' }).setOrigin(0.5).setDepth(depth + 2));
});
panel.push(scene.add.text(cx, rowY(2) + 10, `Streak: ${extra.dailyStreak ?? 0} day${extra.dailyStreak === 1 ? '' : 's'}`, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: '#5a3a12' }).setOrigin(0.5).setDepth(depth + 1));
blurb.setText(extra.dailyDone
? 'You\'ve already played today\'s puzzle. You can look at it again for practice; it won\'t change your streak. A new one shows up at midnight.'
: 'One puzzle a day, the same one for everybody in the park. Get it right on the first try to keep your streak going.');
startBtn?.setLabel(extra.dailyDone ? 'Look Again' : 'Today\'s Puzzle');
}
}
let hRef = null;
startBtn = new Button(scene, cx - 140, y + h - 66, 'Set \'Em Up', () => { hRef.close(); onStart(p); }, { width: 250, height: 52, fontSize: 20, bg: 0x1f6a3a }).setDepth(depth + 2);
objs.push(startBtn);
objs.push(new Button(scene, cx + 140, y + h - 66, 'Leave', () => { hRef.close(); onLeave(); }, { width: 250, height: 52, fontSize: 20, bg: 0x7a1a14 }).setDepth(depth + 2));
refresh();
hRef = handle(objs, clearPanel);
return hRef;
}
export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 580, h = 300;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(scene.add.text(x + w / 2, y + 68, heading, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 140, text, { fontFamily: SERIF, fontSize: '18px', color: '#2a2a1a', align: 'center', wordWrap: { width: w - 90 } }).setOrigin(0.5).setDepth(depth + 1));
let hRef = null;
objs.push(new Button(scene, x + w / 2 - 128, y + h - 62, yes, () => { hRef.close(); onYes?.(); }, { width: 226, height: 46, fontSize: 18, bg: 0x7a1a14 }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 128, y + h - 62, no, () => { hRef.close(); onNo?.(); }, { width: 226, height: 46, fontSize: 18, bg: 0x2a4a6a }).setDepth(depth + 2));
hRef = handle(objs);
return hRef;
}
export function toast(scene, text, { depth, x = GAME_WIDTH / 2, y = 960, ms = 2200 } = {}) {
const t = scene.add.text(x, y, text, { fontFamily: SERIF, fontSize: '20px', color: '#1e2a1a', backgroundColor: '#f6f0de', padding: { x: 18, y: 10 } })
.setOrigin(0.5).setDepth(depth).setAlpha(0);
scene.tweens.add({ targets: t, alpha: 1, duration: 200 });
scene.tweens.add({ targets: t, alpha: 0, delay: ms, duration: 400, onComplete: () => t.destroy() });
return t;
}
/**
* The promotion picker: a column of four pieces dropping from the
* promotion square (toward the centre of the board). onPick('q'|'r'|'b'|'n'), onCancel().
*/
export function openPromotion(scene, { x, y, down, color, style, depth, onPick, onCancel }) {
const objs = [];
const shade = scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x05040a, 0.35).setDepth(depth - 1).setInteractive();
objs.push(shade);
let hRef = null;
shade.on('pointerdown', () => { hRef.close(); onCancel?.(); });
['q', 'n', 'r', 'b'].forEach((t, i) => {
const yy = y + (down ? 1 : -1) * i * 100;
const bg = scene.add.rectangle(x, yy, 96, 96, 0xf6f0de, 0.96).setStrokeStyle(3, 0x2a3a24).setDepth(depth).setInteractive({ useHandCursor: true });
const im = scene.add.image(x, yy, pieceKey(style, color, t)).setScale(0.45).setDepth(depth + 1);
bg.on('pointerover', () => { bg.setFillStyle(0xf0d890, 1); im.setScale(0.5); });
bg.on('pointerout', () => { bg.setFillStyle(0xf6f0de, 0.96); im.setScale(0.45); });
bg.on('pointerdown', () => { hRef.close(); onPick(t); });
objs.push(bg, im);
});
hRef = handle(objs);
return hRef;
}
export { fmtClock };

View File

@ -0,0 +1,234 @@
// ChessEndScreen.js — after the game: the result and why, the opening, a few
// stats, Marcus's review (an evaluation graph that fills in as the engine
// goes over the game, and how many blunders / mistakes / inaccuracies each
// side made), your record against this opponent, a replay board you can step
// through, and a Copy PGN button.
import { Button } from '../../ui/Button.js';
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { DISPLAY_FONT, SERIF, pieceKey } from './ChessArt.js';
import { frame, blocker, handle, toast } from './ChessDialogs.js';
export const REASON = {
checkmate: 'checkmate',
stalemate: 'stalemate: no legal move, but not in check',
material: 'neither side has enough material to mate',
repetition: 'the same position came up three times',
fifty: 'fifty moves without a capture or a pawn move',
agreed: 'both players agreed',
resign: 'resignation',
timeout: 'the flag fell',
timeoutDraw: 'the flag fell, but the other side couldn\'t mate',
};
export function resultLine(gs, humanColor, oppName) {
const r = gs.result;
if (!r) return { title: 'Game in progress', good: null, why: '' };
if (r.winner === 'draw') return { title: r.reason === 'stalemate' ? 'Stalemate: a draw' : 'A draw', good: null, why: `Drawn by ${REASON[r.reason] ?? r.reason}.` };
const won = r.winner === humanColor;
let why = REASON[r.reason] ?? r.reason;
if (r.reason === 'resign') why = won ? `${oppName} resigned` : 'you resigned';
else if (r.reason === 'timeout') why = won ? `${oppName}'s flag fell` : 'your flag fell';
else if (r.reason === 'checkmate') why = won ? 'checkmate. You delivered it' : 'checkmate';
return { title: won ? 'You win!' : `${oppName} wins`, good: won, why: `${why.charAt(0).toUpperCase()}${why.slice(1)}.` };
}
function stats(gs, color) {
const mine = gs.history.filter((h) => h.color === color);
return {
moves: mine.length,
captures: mine.filter((h) => h.captured).length,
checks: mine.filter((h) => h.check).length,
castled: mine.some((h) => h.castle) ? (mine.find((h) => h.castle).castle === 'K' ? 'O-O' : 'O-O-O') : '—',
promos: mine.filter((h) => h.promo).length,
};
}
/** Classify each move from the White-POV evals before/after it. */
export function classify(gs, evals) {
const out = { w: { blunder: 0, mistake: 0, inaccuracy: 0, acc: 0, n: 0 }, b: { blunder: 0, mistake: 0, inaccuracy: 0, acc: 0, n: 0 } };
const cap = (v) => Math.max(-1500, Math.min(1500, v));
for (let i = 0; i < gs.history.length; i++) {
if (evals[i] == null || evals[i + 1] == null) continue;
const c = gs.history[i].color;
const sign = c === 'w' ? 1 : -1;
const before = cap(evals[i]) * sign, after = cap(evals[i + 1]) * sign;
const loss = Math.max(0, before - after);
const o = out[c];
o.n++;
// win-probability style accuracy
const wp = (cp) => 1 / (1 + Math.exp(-cp / 250));
o.acc += Math.max(0, 100 - 100 * Math.max(0, wp(before) - wp(after)) * 1.6);
if (before > 800 && after > 500) continue; // still winning comfortably — no fuss
if (loss >= 300) o.blunder++; else if (loss >= 120) o.mistake++; else if (loss >= 50) o.inaccuracy++;
}
for (const c of ['w', 'b']) out[c].accuracy = out[c].n ? Math.round(out[c].acc / out[c].n) : null;
return out;
}
export function openEndScreen(scene, { gs, humanColor, oppName, record, opening, style, depth, pgn, onPlayAgain, onMenu }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 1280, h = 840;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
const add = (o) => { objs.push(o); return o; };
const D1 = depth + 1;
const r = resultLine(gs, humanColor, oppName);
const color = r.good === null ? '#1e2a1a' : r.good ? '#1f6a3a' : '#8e1c16';
add(scene.add.text(x + w / 2, y + 68, r.title, { fontFamily: DISPLAY_FONT, fontSize: '40px', color }).setOrigin(0.5).setDepth(D1));
const sub = `${r.why}${opening ? ` · ${opening}` : ''}${gs.chess960 ? ' · Chess960' : ''}`;
add(scene.add.text(x + w / 2, y + 112, sub, { fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: '#3a4a2a' }).setOrigin(0.5).setDepth(D1));
// left: stats table
const lx = x + 70;
let ly = y + 168;
const g = add(scene.add.graphics().setDepth(D1));
add(scene.add.text(lx, ly, 'THE GAME', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#3a4a2a' }).setOrigin(0, 0.5).setDepth(D1));
ly += 30;
const oppColor = humanColor === 'w' ? 'b' : 'w';
const you = stats(gs, humanColor), them = stats(gs, oppColor);
const rows = [
['Moves', you.moves, them.moves],
['Captures', you.captures, them.captures],
['Checks', you.checks, them.checks],
['Castled', you.castled, them.castled],
];
const c1 = lx + 280, c2 = lx + 420;
add(scene.add.text(c1, ly, 'YOU', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#1e2a1a' }).setOrigin(0.5).setDepth(D1));
add(scene.add.text(c2, ly, oppName.toUpperCase().slice(0, 12), { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#1e2a1a' }).setOrigin(0.5).setDepth(D1));
const rowTexts = [];
const putRow = (i, label, a, b) => {
const yy = ly + 30 + i * 28;
if (i % 2 === 0) g.fillStyle(0x3a4a2a, 0.08).fillRect(lx - 10, yy - 13, 500, 26);
const t = [
add(scene.add.text(lx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#2a3a1a' }).setOrigin(0, 0.5).setDepth(D1)),
add(scene.add.text(c1, yy, String(a), { fontFamily: SERIF, fontSize: '16px', color: '#1a1a10' }).setOrigin(0.5).setDepth(D1)),
add(scene.add.text(c2, yy, String(b), { fontFamily: SERIF, fontSize: '16px', color: '#1a1a10' }).setOrigin(0.5).setDepth(D1)),
];
rowTexts.push(t);
return t;
};
rows.forEach((rw, i) => putRow(i, ...rw));
const reviewRows = [
putRow(rows.length, 'Accuracy', '…', '…'),
putRow(rows.length + 1, 'Blunders', '…', '…'),
putRow(rows.length + 2, 'Mistakes', '…', '…'),
putRow(rows.length + 3, 'Inaccuracies', '…', '…'),
];
ly += 30 + (rows.length + 4) * 28 + 26;
// the evaluation graph
const sw = 500, sh = 130, sx = lx - 10, sy = ly;
const graphTitle = add(scene.add.text(lx, sy - 4, 'MARCUS IS GOING OVER THE GAME…', { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#3a4a2a' }).setOrigin(0, 1).setDepth(D1));
const gg = add(scene.add.graphics().setDepth(D1));
const marker = add(scene.add.graphics().setDepth(D1 + 1));
const drawGraph = (evals) => {
gg.clear();
gg.fillStyle(0x1a1a20, 1).fillRect(sx, sy + 6, sw, sh);
const n = gs.history.length;
const mid = sy + 6 + sh / 2;
const pts = [];
for (let i = 0; i <= n; i++) {
if (evals[i] == null) break;
const v = 0.5 + 0.5 * Math.tanh(evals[i] / 450);
pts.push({ x: sx + (n ? (i / n) * sw : 0), y: sy + 6 + sh - v * sh });
}
if (pts.length > 1) {
gg.fillStyle(0xf2ecdc, 1);
gg.beginPath(); gg.moveTo(pts[0].x, sy + 6 + sh);
pts.forEach((p) => gg.lineTo(p.x, p.y));
gg.lineTo(pts[pts.length - 1].x, sy + 6 + sh); gg.closePath(); gg.fillPath();
}
gg.lineStyle(1, 0xd8b060, 0.7).lineBetween(sx, mid, sx + sw, mid);
};
drawGraph([]);
ly = sy + sh + 34;
if (record) {
add(scene.add.text(lx, ly, `Your record against ${oppName}: ${record.w} won · ${record.d} drawn · ${record.l} lost`, { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#2a3a1a' }).setOrigin(0, 0.5).setDepth(D1));
}
// right: replay board
const RS = 50, rx = x + w - 70 - RS * 8, ry = y + 172;
add(scene.add.text(rx + RS * 4, ry - 22, 'REPLAY', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#3a4a2a' }).setOrigin(0.5).setDepth(D1));
const bg = add(scene.add.graphics().setDepth(D1));
for (let rr2 = 0; rr2 < 8; rr2++) {
for (let c = 0; c < 8; c++) bg.fillStyle((rr2 + c) % 2 ? 0x3c5a4a : 0xece2cc, 1).fillRect(rx + c * RS, ry + rr2 * RS, RS, RS);
}
bg.lineStyle(4, 0x2a3a24, 1).strokeRect(rx - 2, ry - 2, RS * 8 + 4, RS * 8 + 4);
const hl = add(scene.add.graphics().setDepth(D1 + 0.5));
let pieceImgs = [];
const flipped = humanColor === 'b';
const label = add(scene.add.text(rx + RS * 4, ry + RS * 8 + 28, '', { fontFamily: SERIF, fontSize: '17px', color: '#1a1a10' }).setOrigin(0.5).setDepth(D1));
let n = gs.history.length;
let evalsNow = [];
const sqXY = (sq) => {
const r0 = sq >> 3, c0 = sq & 7;
const vr = flipped ? 7 - r0 : r0, vc = flipped ? 7 - c0 : c0;
return { x: rx + vc * RS + RS / 2, y: ry + vr * RS + RS / 2 };
};
const draw = () => {
pieceImgs.forEach((o) => o.destroy());
pieceImgs = [];
hl.clear();
const pos = gs.after(n);
const last = n > 0 ? gs.history[n - 1] : null;
if (last) {
for (const sq of [last.from, last.to]) {
const p = sqXY(sq);
hl.fillStyle(0xf0c040, 0.45).fillRect(p.x - RS / 2, p.y - RS / 2, RS, RS);
}
}
pos.board64().forEach((p, sq) => {
if (!p) return;
const q = sqXY(sq);
const im = scene.add.image(q.x, q.y - 2, pieceKey(style, p.color, p.type)).setScale(RS / 232 * 1.02).setDepth(D1 + 1);
pieceImgs.push(im);
});
const mv = last ? `${Math.ceil(n / 2)}${last.color === 'w' ? '.' : '…'} ${last.san}` : 'Starting position';
const ev = evalsNow[n];
label.setText(`Move ${n} of ${gs.history.length}: ${mv}${ev != null ? ` (${ev >= 0 ? '+' : ''}${(Math.max(-99, Math.min(99, ev / 100))).toFixed(1)})` : ''}`);
marker.clear();
const nn = gs.history.length;
if (nn) { const mx = sx + (n / nn) * sw; marker.lineStyle(2, 0xc0281c, 0.9).lineBetween(mx, sy + 6, mx, sy + 6 + sh); }
};
draw();
const by = ry + RS * 8 + 74;
const step = (d) => { n = Math.max(0, Math.min(gs.history.length, n + d)); draw(); };
add(new Button(scene, rx + RS * 4 - 165, by, '|◀', () => { n = 0; draw(); }, { width: 70, height: 42, fontSize: 18, bg: 0x2a3a24 }).setDepth(D1 + 1));
add(new Button(scene, rx + RS * 4 - 80, by, '◀', () => step(-1), { width: 80, height: 42, fontSize: 18, bg: 0x2a3a24 }).setDepth(D1 + 1));
add(new Button(scene, rx + RS * 4 + 10, by, '▶', () => step(1), { width: 80, height: 42, fontSize: 18, bg: 0x2a3a24 }).setDepth(D1 + 1));
add(new Button(scene, rx + RS * 4 + 95, by, '▶|', () => { n = gs.history.length; draw(); }, { width: 70, height: 42, fontSize: 18, bg: 0x2a3a24 }).setDepth(D1 + 1));
const keys = (e) => { if (e.key === 'ArrowLeft') step(-1); else if (e.key === 'ArrowRight') step(1); };
scene.input.keyboard?.on('keydown', keys);
// clicking the graph jumps the replay there
const gz = add(scene.add.zone(sx + sw / 2, sy + 6 + sh / 2, sw, sh).setInteractive({ useHandCursor: true }).setDepth(D1 + 2));
gz.on('pointerdown', (p) => { n = Math.round(((p.x - sx) / sw) * gs.history.length); step(0); });
const bty = y + h - 64;
let hRef = null;
add(new Button(scene, x + w / 2 - 290, bty, 'Play Again', () => { hRef.close(); onPlayAgain(); }, { width: 250, height: 52, fontSize: 20, bg: 0x1f6a3a }).setDepth(D1 + 1));
add(new Button(scene, x + w / 2, bty, 'Copy PGN', () => {
const text = pgn();
const done = () => toast(scene, 'PGN copied. Paste it into any chess site to study.', { depth: depth + 20, y: bty - 70 });
try { navigator.clipboard.writeText(text).then(done, () => toast(scene, 'Couldn\'t reach the clipboard.', { depth: depth + 20, y: bty - 70 })); } catch (_) { /* no clipboard */ }
}, { width: 250, height: 52, fontSize: 20, bg: 0x2a4a6a }).setDepth(D1 + 1));
add(new Button(scene, x + w / 2 + 290, bty, 'Leave the Park', () => { hRef.close(); onMenu(); }, { width: 250, height: 52, fontSize: 20, bg: 0x7a1a14 }).setDepth(D1 + 1));
hRef = handle(objs, () => { pieceImgs.forEach((o) => o.destroy()); scene.input.keyboard?.off('keydown', keys); });
hRef.setAnalysis = (evals, done) => {
evalsNow = evals;
drawGraph(evals);
if (done) {
graphTitle.setText('EVALUATION (WHITE ABOVE THE LINE) · CLICK TO JUMP');
const cl = classify(gs, evals);
const a = cl[humanColor], b = cl[oppColor];
const set = (row, va, vb) => { row[1].setText(String(va)); row[2].setText(String(vb)); };
set(reviewRows[0], a.accuracy != null ? `${a.accuracy}%` : '—', b.accuracy != null ? `${b.accuracy}%` : '—');
set(reviewRows[1], a.blunder, b.blunder);
set(reviewRows[2], a.mistake, b.mistake);
set(reviewRows[3], a.inaccuracy, b.inaccuracy);
}
draw();
};
return hRef;
}

View File

@ -0,0 +1,113 @@
// ChessEngine.js — runs ChessAI off the main thread so the park keeps moving
// (pigeons, clock hands, the busker) while an opponent thinks.
//
// handle(kind, payload) the actual work (shared by the worker and the
// synchronous fallback)
// class Engine main-thread client: request(kind, payload) →
// Promise. Uses a module Worker (ChessWorker.js);
// if that can't start, runs the same code inline.
//
// Kinds (payload always carries `rec`: { startFen, moves: [uci…] }):
// move { skill, ms } → { uci, score, book }
// best { ms } → { uci, san, score, idea, pv: [san…] }
// analyze { ms, margin, top } → [{ uci, san, score }] best first
// eval { ms } → { cp } (White's point of view)
// drops { uci } → { loss } material the move hangs (SEE)
import * as L from './ChessLogic.js';
import * as AI from './ChessAI.js';
export function handle(kind, p) {
const g = L.Chess.fromRecord(p.rec);
const pos = g.pos;
switch (kind) {
case 'move': {
const r = AI.chooseMove(g, p.skill, { ms: p.ms ?? null });
if (!r) return null;
return { uci: L.toUci(pos, r.m), score: r.score, book: !!r.book };
}
case 'best': {
const r = AI.bestMove(pos, { ms: p.ms ?? 600 });
if (!r.m) return null;
const san = L.toSan(pos, r.m);
const idea = AI.describeIdea(pos, r.m, r.score);
const pv = [];
const q = pos.clone();
for (const m of r.pv) { if (!L.legalMoves(q).includes(m)) break; pv.push(L.toSan(q, m)); L.makeMove(q, m); }
return { uci: L.toUci(pos, r.m), san, score: r.score, idea, pv };
}
case 'analyze': {
const ranked = AI.analyze(pos, { ms: p.ms ?? 400, margin: p.margin ?? 300 });
const top = ranked.slice(0, p.top ?? ranked.length);
const legal = L.legalMoves(pos);
return top.map((r, i) => ({
uci: L.toUci(pos, r.m), san: L.toSan(pos, r.m, legal), score: r.score,
idea: i === 0 ? AI.describeIdea(pos, r.m, r.score) : null,
}));
}
case 'eval': {
if (!L.hasLegalMove(pos)) return { cp: pos.inCheck() ? (pos.side === L.WHITE ? -AI.MATE : AI.MATE) : 0, mate: pos.inCheck() };
const r = AI.bestMove(pos, { ms: p.ms ?? 150 });
const cp = pos.side === L.WHITE ? r.score : -r.score;
return { cp, best: r.m ? L.toUci(pos, r.m) : null };
}
case 'drops': {
const m = L.fromUci(pos, p.uci);
return { loss: m ? AI.dropsMaterial(pos, m) : 0 };
}
default: return null;
}
}
export class Engine {
constructor() {
this.seq = 0;
this.pending = new Map();
this.worker = null;
try {
if (typeof Worker !== 'undefined') {
this.worker = new Worker(new URL('./ChessWorker.js', import.meta.url), { type: 'module' });
this.worker.onmessage = (e) => this.settle(e.data);
this.worker.onerror = (e) => { e?.preventDefault?.(); this.fallBack(); };
}
} catch (_) { this.worker = null; }
}
settle({ id, res, err }) {
const job = this.pending.get(id);
if (!job) return;
this.pending.delete(id);
if (err) job.reject(new Error(err)); else job.resolve(res);
}
fallBack() {
// the worker couldn't start (or died): finish everything inline
try { this.worker?.terminate(); } catch (_) { /* */ }
this.worker = null;
for (const [id, job] of this.pending) this.runInline(id, job.kind, job.payload);
}
runInline(id, kind, payload) {
setTimeout(() => {
let res = null, err = null;
try { res = handle(kind, payload); } catch (e) { err = String(e?.message ?? e); }
this.settle({ id, res, err });
}, 0);
}
request(kind, payload) {
const id = ++this.seq;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject, kind, payload });
if (this.worker) {
try { this.worker.postMessage({ id, kind, payload }); } catch (_) { this.fallBack(); }
} else this.runInline(id, kind, payload);
});
}
destroy() {
try { this.worker?.terminate(); } catch (_) { /* */ }
this.worker = null;
this.pending.clear();
}
}

File diff suppressed because it is too large Load Diff

415
src/games/chess/ChessHud.js Normal file
View File

@ -0,0 +1,415 @@
// ChessHud.js — the furniture around the stone table: a bench-slat plaque
// per player (portrait, name, skill, a note, material and clock, their
// colour), capture trays with the material count, the speech bubble, the
// chalkboard status, the spiral score sheet (click a move to look back), the
// buttons, Marcus's slate, the evaluation bar and the analog chess clock.
import { Button } from '../../ui/Button.js';
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
import {
PLATES, PLATE, plateParts, TRAYS, BUBBLE, STATUS, LOG, LOG_ROWS, BUTTONS, BTN, RIBBON, EVAL, CLOCK, CLOCK_FACES,
} from './ChessLayout.js';
import { DISPLAY_FONT, SERIF, CHALK, pieceKey } from './ChessArt.js';
const short = (s, n = 14) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
export const fmtClock = (ms, tenths = false) => {
const neg = ms < 0;
ms = Math.max(0, ms);
const s = Math.floor(ms / 1000);
const base = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
return (neg ? '-' : '') + (tenths && ms < 20000 ? `${base}.${Math.floor((ms % 1000) / 100)}` : base);
};
const VAL = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
const ORDER = { q: 0, r: 1, b: 2, n: 3, p: 4 };
export class Hud {
constructor(scene, depth, { names, skill, opponent, onButton, onReview }) {
this.scene = scene;
this.depth = depth;
this.names = names; // { top, bottom }
this.skill = skill;
this.opponent = opponent;
this.onButton = onButton;
this.onReview = onReview;
this.plates = {};
this.buttons = {};
this.bubble = null;
this.trayObjs = { top: [], bottom: [] };
this.style = 'carved';
this.scroll = null; // null = follow the latest move
this.rowsData = [];
}
build() {
const s = this.scene, D = this.depth;
for (const side of ['top', 'bottom']) {
const P = PLATES[side], parts = plateParts(side);
const glow = s.add.image(P.x - 40, P.y - 40, 'cs-plate-glow').setOrigin(0).setDepth(D - 1).setAlpha(0);
s.add.image(P.x - 14, P.y - 14, 'cs-plate').setOrigin(0).setDepth(D);
const pp = parts.portrait;
const ring = s.add.circle(pp.x, pp.y, pp.r + 5, 0xd8b060, 1).setDepth(D + 1);
const portrait = side === 'bottom'
? createPlayerPortrait(s, pp.x, pp.y, pp.r, D + 2, 'ChessGame')
: createOpponentPortrait(s, this.opponent ?? { id: 'bot', spriteIndex: 0 }, pp.x, pp.y, pp.r, D + 2);
const name = s.add.text(parts.name.x, parts.name.y, short(this.names[side], side === 'top' ? 13 : 16), {
fontFamily: DISPLAY_FONT, fontSize: '22px', color: '#f8f0dc', stroke: '#16200f', strokeThickness: 3,
}).setOrigin(0, 0.5).setDepth(D + 1);
let pips = null;
if (side === 'top') {
const k = this.skill;
pips = s.add.text(parts.skill.x, parts.skill.y, '●'.repeat(k) + '○'.repeat(5 - k), { fontFamily: SERIF, fontSize: '13px', color: '#e8c46a' })
.setOrigin(1, 0.5).setDepth(D + 1);
}
const note = s.add.text(parts.note.x, parts.note.y, '', { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#e8dcb0', stroke: '#16200f', strokeThickness: 2 })
.setOrigin(0, 0.5).setDepth(D + 1);
const line = s.add.text(parts.line.x, parts.line.y, '', { fontFamily: SERIF, fontSize: '16px', color: '#e0d8c0', stroke: '#16200f', strokeThickness: 2 })
.setOrigin(0, 0.5).setDepth(D + 1);
const chip = s.add.image(parts.color.x, parts.color.y, pieceKey('carved', 'w', 'k')).setScale(0.17).setDepth(D + 1).setVisible(false);
const chipText = s.add.text(parts.color.x + 18, parts.color.y, '', { fontFamily: SERIF, fontSize: '15px', color: '#e0d8c0', stroke: '#16200f', strokeThickness: 2 })
.setOrigin(0, 0.5).setDepth(D + 1);
const tally = s.add.text(parts.tally.x, parts.tally.y, '', { fontFamily: DISPLAY_FONT, fontSize: '15px', color: '#f0d890', stroke: '#16200f', strokeThickness: 2 })
.setOrigin(1, 0.5).setDepth(D + 1);
this.plates[side] = { glow, ring, portrait, name, pips, note, line, chip, chipText, tally, active: false };
}
// capture trays: a shallow stone ledge each
for (const side of ['top', 'bottom']) {
const T = TRAYS[side];
const g = s.add.graphics().setDepth(D);
g.fillStyle(0x000000, 0.35).fillRoundedRect(T.x + 2, T.y + 4, T.w, T.h, 10);
g.fillStyle(0x2a2630, 0.85).fillRoundedRect(T.x, T.y, T.w, T.h, 10);
g.lineStyle(1.5, 0xd8c8a0, 0.25).strokeRoundedRect(T.x + 1, T.y + 1, T.w - 2, T.h - 2, 9);
this[`diff_${side}`] = s.add.text(T.x + T.w - 14, T.y + T.h / 2, '', { fontFamily: DISPLAY_FONT, fontSize: '18px', color: '#f0d890' })
.setOrigin(1, 0.5).setDepth(D + 2);
}
// the chalkboard
s.add.image(STATUS.x - 14, STATUS.y - 14, 'cs-chalk').setOrigin(0).setDepth(D);
this.status = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 58, '', {
fontFamily: CHALK, fontSize: '27px', color: '#f4f2ea', align: 'center', wordWrap: { width: STATUS.w - 60 },
shadow: { offsetX: 0, offsetY: 0, color: 'rgba(255,255,255,0.35)', blur: 4, fill: true },
}).setOrigin(0.5).setDepth(D + 1);
this.sub = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 120, '', {
fontFamily: SERIF, fontSize: '16px', color: '#d8e0d4', align: 'center', wordWrap: { width: STATUS.w - 60 }, lineSpacing: 3,
}).setOrigin(0.5).setDepth(D + 1);
// the score sheet
s.add.image(LOG.x - 14, LOG.y - 14, 'cs-sheet').setOrigin(0).setDepth(D);
this.logTitle = s.add.text(LOG.x + 22, LOG.y + 22, 'SCORE SHEET', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#f0e8d0' }).setOrigin(0, 0.5).setDepth(D + 1);
this.logSub = s.add.text(LOG.x + LOG.w - 20, LOG.y + 22, '', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#d8e0c8' }).setOrigin(1, 0.5).setDepth(D + 1);
this.opening = s.add.text(LOG.x + 22, LOG.y + 44, '', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#f0d890' }).setOrigin(0, 0.5).setDepth(D + 1);
const colA = LOG.x + 62 + (LOG.w - 62) / 4, colB = LOG.x + 62 + ((LOG.w - 62) * 3) / 4;
this.colHead = [
s.add.text(colA, LOG.y + 72, 'WHITE', { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#3a2a1a' }).setOrigin(0.5).setDepth(D + 1),
s.add.text(colB, LOG.y + 72, 'BLACK', { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#3a2a1a' }).setOrigin(0.5).setDepth(D + 1),
];
this.rows = [];
this.reviewMark = s.add.rectangle(0, 0, (LOG.w - 62) / 2 - 10, 26, 0xf0c040, 0.35).setDepth(D + 0.5).setVisible(false);
for (let i = 0; i < LOG_ROWS; i++) {
const y = LOG.y + 99 + i * 31;
const row = {
n: s.add.text(LOG.x + 50, y, '', { fontFamily: SERIF, fontSize: '15px', color: '#7a5a3a' }).setOrigin(1, 0.5).setDepth(D + 1),
a: s.add.text(colA, y, '', { fontFamily: SERIF, fontSize: '18px', color: '#1a1a24' }).setOrigin(0.5).setDepth(D + 1),
b: s.add.text(colB, y, '', { fontFamily: SERIF, fontSize: '18px', color: '#1a1a24' }).setOrigin(0.5).setDepth(D + 1),
y,
};
for (const [k, x] of [['a', colA], ['b', colB]]) {
const z = s.add.zone(x, y, (LOG.w - 62) / 2 - 8, 29).setInteractive({ useHandCursor: true }).setDepth(D + 2);
z.on('pointerdown', () => { const ply = row[`${k}Ply`]; if (ply != null) this.onReview?.(ply); });
z.on('pointerover', () => { if (row[`${k}Ply`] != null) row[k].setStyle({ backgroundColor: 'rgba(240,200,80,0.25)' }); });
z.on('pointerout', () => row[k].setStyle({ backgroundColor: null }));
}
this.rows.push(row);
}
this.moreUp = s.add.text(LOG.x + LOG.w - 20, LOG.y + 72, '', { fontFamily: SERIF, fontSize: '13px', color: '#7a5a3a' }).setOrigin(1, 0.5).setDepth(D + 1);
const wheelZone = s.add.zone(LOG.x + LOG.w / 2, LOG.y + LOG.h / 2, LOG.w, LOG.h).setInteractive().setDepth(D + 1.5);
wheelZone.on('wheel', (_p, _dx, dy) => this.scrollBy(dy > 0 ? 1 : -1));
// buttons
const label = { undo: 'Undo (Z)', hint: 'Hint (H)', draw: 'Offer Draw', resign: 'Resign', flip: 'Flip (F)', menu: 'Menu (Esc)' };
const bg = { undo: 0x5a4a1a, hint: 0x2a4a6a, draw: 0x4a4a4a, resign: 0x7a1a14, flip: 0x2a3a24, menu: 0x2a2632 };
for (const [k, b] of Object.entries(BUTTONS)) {
this.buttons[k] = new Button(s, b.x, b.y, label[k], () => this.onButton(k), { width: BTN.w, height: BTN.h, fontSize: 15, bg: bg[k] }).setDepth(D + 3);
if (!['menu', 'flip'].includes(k)) this.buttons[k].setEnabled(false);
}
this.defaultLabels = label;
// Marcus's slate
s.add.image(RIBBON.x - 12, RIBBON.y - 12, 'cs-slate').setOrigin(0).setDepth(D);
this.marcus = s.add.text(RIBBON.x + 84, RIBBON.y + RIBBON.h / 2, '', {
fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: '#f3ecd8', wordWrap: { width: RIBBON.w - 110 },
}).setOrigin(0, 0.5).setDepth(D + 1);
this.buildEval();
this.buildClock();
return this;
}
// ── evaluation bar ────────────────────────────────────────────────────────
buildEval() {
const s = this.scene, D = this.depth;
this.evalBg = s.add.rectangle(EVAL.x + EVAL.w / 2, EVAL.y + EVAL.h / 2, EVAL.w, EVAL.h, 0x1a181e).setStrokeStyle(2, 0x0a0a0c).setDepth(D);
this.evalFill = s.add.rectangle(EVAL.x + EVAL.w / 2, EVAL.y + EVAL.h, EVAL.w - 4, EVAL.h / 2, 0xf2ecdc).setOrigin(0.5, 1).setDepth(D + 1);
this.evalMid = s.add.rectangle(EVAL.x + EVAL.w / 2, EVAL.y + EVAL.h / 2, EVAL.w + 6, 2, 0xd8b060, 0.8).setDepth(D + 2);
this.evalText = s.add.text(EVAL.x + EVAL.w / 2, EVAL.y + EVAL.h - 10, '', { fontFamily: SERIF, fontSize: '11px', color: '#1a1a1a' })
.setOrigin(0.5).setDepth(D + 2).setAngle(-90);
this.evalObjs = [this.evalBg, this.evalFill, this.evalMid, this.evalText];
this.evalFrac = 0.5;
this.showEval(false);
}
showEval(on) { this.evalObjs.forEach((o) => o.setVisible(on)); this.evalOn = on; }
/** cp from White's view; whiteAtBottom decides which end White's share grows from. */
setEval(cp, whiteAtBottom, mate = 0) {
if (!this.evalOn) return;
const frac = mate ? (mate > 0 ? 1 : 0) : 0.5 + 0.5 * Math.tanh(cp / 450);
const s = this.scene;
s.tweens.killTweensOf(this);
s.tweens.add({
targets: this, evalFrac: frac, duration: 500, ease: 'Cubic.Out',
onUpdate: () => {
const h = Math.max(2, (EVAL.h - 4) * this.evalFrac);
if (whiteAtBottom) this.evalFill.setOrigin(0.5, 1).setPosition(EVAL.x + EVAL.w / 2, EVAL.y + EVAL.h - 2);
else this.evalFill.setOrigin(0.5, 0).setPosition(EVAL.x + EVAL.w / 2, EVAL.y + 2);
this.evalFill.height = h;
this.evalFill.setSize(EVAL.w - 4, h);
},
});
const txt = mate ? `M${Math.abs(mate)}` : (Math.abs(cp) < 5 ? '0.0' : (Math.abs(cp) / 100).toFixed(1));
const whiteAhead = mate ? mate > 0 : cp >= 0;
const atBottom = whiteAhead === whiteAtBottom;
this.evalText.setText(txt).setColor(whiteAhead ? '#1a1a1a' : '#f2ecdc')
.setPosition(EVAL.x + EVAL.w / 2, atBottom ? EVAL.y + EVAL.h - 18 : EVAL.y + 18);
}
// ── the chess clock ───────────────────────────────────────────────────────
buildClock() {
const s = this.scene, D = this.depth;
this.clockBody = s.add.image(CLOCK.x - 24, CLOCK.y - 24, 'cs-clock').setOrigin(0).setDepth(D);
this.clockBtns = CLOCK_FACES.map((F) => s.add.image(F.x, CLOCK.y + 14, 'cs-clock-btn').setDepth(D - 0.5));
this.clockHands = s.add.graphics().setDepth(D + 1);
this.clockDigits = CLOCK_FACES.map((F) => s.add.text(F.x, F.y + 26, '', {
fontFamily: '"Courier New", monospace', fontSize: '15px', fontStyle: 'bold', color: '#1a1410', backgroundColor: 'rgba(250,244,228,0.85)', padding: { x: 4, y: 1 },
}).setOrigin(0.5).setDepth(D + 2));
this.clockLabels = CLOCK_FACES.map((F, i) => s.add.text(F.x, CLOCK.y + CLOCK.h - 6, i === 0 ? 'YOU' : short(this.names.top, 10).toUpperCase(), {
fontFamily: DISPLAY_FONT, fontSize: '12px', color: '#f0d8a8',
}).setOrigin(0.5).setDepth(D + 1));
this.clockState = { human: 0, ai: 0, timed: false, running: null, flagged: null };
this.drawClock();
}
setClock(st) { this.clockState = st; this.drawClock(); }
drawClock() {
const g = this.clockHands;
g.clear();
const st = this.clockState;
[st.human, st.ai].forEach((ms, i) => {
const F = CLOCK_FACES[i];
// a timed clock counts down to twelve; an untimed one just counts up from twelve
const mins = st.timed ? 720 - Math.max(0, ms) / 60000 : Math.max(0, ms) / 60000;
const ma = ((mins % 60) / 60) * Math.PI * 2 - Math.PI / 2;
const ha = (((mins / 60) % 12) / 12) * Math.PI * 2 - Math.PI / 2;
const secs = st.timed ? (60 - ((Math.max(0, ms) / 1000) % 60)) % 60 : (Math.max(0, ms) / 1000) % 60;
const sa = (secs / 60) * Math.PI * 2 - Math.PI / 2;
const hand = (a, len, w, col) => {
g.lineStyle(w, col, 1);
g.lineBetween(F.x - Math.cos(a) * 8, F.y - Math.sin(a) * 8, F.x + Math.cos(a) * len, F.y + Math.sin(a) * len);
};
hand(ha, F.r * 0.5, 5, 0x1a1410);
hand(ma, F.r * 0.78, 3.5, 0x1a1410);
if (st.running === (i === 0 ? 'human' : 'ai')) hand(sa, F.r * 0.82, 1.5, 0xc0281c);
g.fillStyle(0x1a1410, 1).fillCircle(F.x, F.y, 4.5);
g.fillStyle(0xd8b060, 1).fillCircle(F.x, F.y, 2);
// the flag: lifted by the minute hand in the last three minutes, falls at zero
if (st.timed) {
const left = Math.max(0, ms);
const fallen = st.flagged === (i === 0 ? 'human' : 'ai') || left <= 0;
const lift = fallen ? 0 : Math.max(0, 1 - left / 180000);
const px = F.x + 10, py = F.y - F.r + 14;
const ang = fallen ? 1.35 : -0.25 - lift * 0.9;
const tip = { x: px + Math.cos(ang - Math.PI / 2) * 0 + Math.sin(ang) * -1, y: py };
void tip;
const cx = Math.cos(ang), sx = Math.sin(ang);
const p = (u, v) => ({ x: px + u * cx - v * sx, y: py + u * sx + v * cx });
const a = p(0, 0), b = p(-14, -4), c = p(-14, 4);
g.fillStyle(0xc0281c, 1).fillTriangle(a.x, a.y, b.x, b.y, c.x, c.y);
g.lineStyle(1, 0x5a0a06, 1).strokeTriangle(a.x, a.y, b.x, b.y, c.x, c.y);
}
const t = this.clockDigits[i];
t.setText(fmtClock(ms, st.timed));
const col = st.timed && ms < 20000 ? '#b01810' : '#1a1410';
if (t.style.color !== col) t.setColor(col);
// plunger: up for the side to move
const up = st.running === (i === 0 ? 'human' : 'ai');
this.clockBtns[i].setY(CLOCK.y + (up ? 6 : 16));
});
}
setStyle(style) { this.style = style; }
/** gs (Chess), ctx: { humanColor, thinking, clocks:{human,ai}, timed, captured:{top,bottom}, opening, reviewPly, puzzle } */
refresh(gs, ctx) {
const sides = { bottom: ctx.humanColor, top: ctx.humanColor === 'w' ? 'b' : 'w' };
const mat = gs.material();
for (const side of ['top', 'bottom']) {
const pl = this.plates[side], col = sides[side];
const active = !gs.result && gs.turn === col && !ctx.idle;
if (active !== pl.active) {
pl.active = active;
this.scene.tweens.killTweensOf(pl.glow);
if (active) {
pl.glow.setAlpha(0.9);
this.scene.tweens.add({ targets: pl.glow, alpha: { from: 0.95, to: 0.45 }, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' });
} else pl.glow.setAlpha(0);
}
let note;
if (ctx.notes?.[side] != null) note = ctx.notes[side];
else if (gs.result || ctx.idle) note = '';
else if (active) note = side === 'bottom' ? (gs.inCheck() ? 'In check!' : 'Your move') : (ctx.thinking ? 'Thinking…' : 'To play');
else note = side === 'bottom' ? 'Waiting' : 'Watching the board';
pl.note.setText(note).setColor(active ? '#ffe0a0' : '#d8ccaa');
if (ctx.lines?.[side] != null) pl.line.setText(ctx.lines[side]);
else {
const ms = side === 'bottom' ? ctx.clocks.human : ctx.clocks.ai;
pl.line.setText(`Material ${mat[col]} ⏱ ${fmtClock(ms, ctx.timed)}`);
}
pl.chip.setTexture(pieceKey(this.style, col, 'k')).setVisible(true);
pl.chipText.setText(col === 'w' ? 'White' : 'Black');
pl.tally.setText(ctx.tally?.[side] ?? '');
pl.ring.setFillStyle(side === 'bottom' ? 0xd8b060 : (col === 'b' ? 0x4a4658 : 0xe8e0c8));
}
this.setTrays(ctx.captured);
this.setLog(gs, ctx);
}
setTrays(captured) {
const s = this.scene;
const worth = (list) => list.reduce((a, t) => a + VAL[t], 0);
const diff = worth(captured.bottom ?? []) - worth(captured.top ?? []);
for (const side of ['top', 'bottom']) {
this.trayObjs[side].forEach((o) => o.destroy());
this.trayObjs[side] = [];
const T = TRAYS[side];
const list = (captured[side] ?? []).slice().sort((a, b) => ORDER[a] - ORDER[b]);
// a captured piece shows in the colour it was (the other side's)
const col = captured.colors?.[side] ?? 'b';
let x = T.x + 22, prev = null;
list.forEach((t, i) => {
if (prev && prev !== t) x += 10;
const im = s.add.image(x, T.y + T.h / 2 - 2, pieceKey(this.style, col, t)).setScale(0.22).setDepth(this.depth + 1 + i * 0.01);
this.trayObjs[side].push(im);
x += 17;
prev = t;
});
const d = side === 'bottom' ? diff : -diff;
this[`diff_${side}`].setText(d > 0 ? `+${d}` : '');
}
}
trayTarget(side, n) {
const T = TRAYS[side];
return { x: Math.min(T.x + T.w - 60, T.x + 22 + n * 19), y: T.y + T.h / 2 - 2 };
}
scrollBy(d) {
const pairs = this.rowsData.length;
const maxStart = Math.max(0, pairs - LOG_ROWS);
const cur = this.scroll ?? maxStart;
const next = Math.max(0, Math.min(maxStart, cur + d));
this.scroll = next >= maxStart ? null : next;
this.paintRows();
}
setLog(gs, ctx = {}) {
const startWhite = gs.startFen.split(' ')[1] !== 'b';
const pairs = [];
gs.history.forEach((h, i) => {
if (h.color === 'w' || !pairs.length) pairs.push({ a: null, b: null, aPly: null, bPly: null });
const last = pairs[pairs.length - 1];
if (h.color === 'w') { last.a = h; last.aPly = i + 1; } else { last.b = h; last.bPly = i + 1; }
});
void startWhite;
this.rowsData = pairs;
this.reviewPly = ctx.reviewPly ?? null;
this.lastPly = gs.history.length;
if (this.reviewPly != null) {
// keep the reviewed move in view
const idx = pairs.findIndex((p) => p.aPly === this.reviewPly || p.bPly === this.reviewPly);
const maxStart = Math.max(0, pairs.length - LOG_ROWS);
if (idx >= 0) {
const cur = this.scroll ?? maxStart;
if (idx < cur) this.scroll = idx;
else if (idx >= cur + LOG_ROWS) this.scroll = Math.min(maxStart, idx - LOG_ROWS + 1);
if (this.scroll >= maxStart) this.scroll = null;
}
}
this.logSub.setText(ctx.logSub ?? (gs.chess960 ? 'Chess960' : ''));
this.opening.setText(ctx.opening ?? '');
this.paintRows();
}
paintRows() {
const pairs = this.rowsData;
const maxStart = Math.max(0, pairs.length - LOG_ROWS);
const start = this.scroll ?? maxStart;
this.moreUp.setText(start > 0 ? `▲ ${start} more` : '');
this.reviewMark.setVisible(false);
this.rows.forEach((r, i) => {
const p = pairs[start + i];
r.aPly = null; r.bPly = null;
if (!p) { r.n.setText(''); r.a.setText(''); r.b.setText(''); return; }
r.n.setText(`${start + i + 1}.`);
for (const [k, h, ply] of [['a', p.a, p.aPly], ['b', p.b, p.bPly]]) {
const t = r[k];
if (!h) { t.setText(k === 'a' && p.b ? '…' : ''); continue; }
r[`${k}Ply`] = ply;
const latest = ply === this.lastPly;
t.setText(h.san).setColor(latest ? '#8a1c10' : '#1a1a24').setFontStyle(latest ? 'bold' : 'normal');
if (ply === this.reviewPly) this.reviewMark.setPosition(t.x, r.y).setVisible(true);
}
});
}
setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); }
setButton(k, on) { this.buttons[k]?.setEnabled(!!on); }
setLabels(map) {
for (const [k, b] of Object.entries(this.buttons)) b.setLabel?.(map?.[k] ?? this.defaultLabels[k]);
}
marcusSays(text, { hold = 7000 } = {}) {
if (!text) return;
const t = this.marcus;
this.scene.tweens.killTweensOf(t);
t.setText(`Marcus: “${text}”`).setAlpha(0);
this.scene.tweens.add({ targets: t, alpha: 1, duration: 220 });
this.scene.tweens.add({ targets: t, alpha: 0.55, delay: hold, duration: 800 });
}
say(text, dur = 2800) {
if (!text) return;
const s = this.scene;
this.bubble?.destroy();
const b = BUBBLE;
const t = s.add.text(b.x + b.w / 2, b.y + b.h / 2, text, {
fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#2a1a10', align: 'center', wordWrap: { width: b.w - 36 },
}).setOrigin(0.5);
const g = s.add.graphics();
g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + 4, b.w, b.h, 12);
g.fillStyle(0xf6f0de, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 12);
g.lineStyle(2, 0x3a4a2a, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 12);
const tx = plateParts('top').portrait.x + 40;
g.fillStyle(0xf6f0de, 1).fillTriangle(tx - 10, b.y + 1, tx + 10, b.y + 1, tx, b.y - 14);
const cont = s.add.container(0, 0, [g, t]).setDepth(this.depth + 8).setAlpha(0);
this.bubble = cont;
s.tweens.add({ targets: cont, alpha: 1, duration: 160 });
s.tweens.add({ targets: cont, alpha: 0, delay: dur, duration: 300, onComplete: () => { cont.destroy(); if (this.bubble === cont) this.bubble = null; } });
}
setNames(top) {
this.names.top = top;
this.plates.top.name.setText(short(top, 13));
this.clockLabels[1].setText(short(top, 10).toUpperCase());
}
emotion(e) { this.plates.top?.portrait?.playEmotion?.(e); }
hidePortraits() { Object.values(this.plates).forEach((p) => p.portrait?.setVideoVisible?.(false)); }
showPortraits() { Object.values(this.plates).forEach((p) => p.portrait?.setVideoVisible?.(true)); }
}
export { PLATE };

View File

@ -0,0 +1,108 @@
// ChessLayout.js — geometry for the Stone Tables (1920 × 1080). No Phaser.
//
// left column opponent's bench plaque · their captures · speech bubble ·
// a gap onto the park (fountain, pigeons) · your captures ·
// your plaque
// centre the board on a granite table, Marcus's slate beneath, an
// optional evaluation bar down the left edge of the board
// right column the chalkboard (status) · the score sheet · buttons · the
// chess clock on the table's corner
export const W = 1920;
export const H = 1080;
export const SQ = 100;
export const BX = 560; // board (playing squares) origin
export const BY = 124;
export const BOARD = SQ * 8; // 800
export const FRAME = 44;
export const BOARD_TEX = BOARD + FRAME * 2; // 888
export const BCX = BX + BOARD / 2; // 960
export const BCY = BY + BOARD / 2; // 524
export const BOARD_RECT = { x: BX - FRAME, y: BY - FRAME, w: BOARD_TEX, h: BOARD_TEX };
export const TABLE = { x: BX - FRAME - 46, y: BY - FRAME - 40, w: BOARD_TEX + 92, h: BOARD_TEX + 86 };
const LX = 30, RX = 1430, CW = 460;
export const PLATE = { w: CW, h: 190 };
export const PLATES = {
top: { x: LX, y: 28 },
bottom: { x: LX, y: 862 },
};
// captured pieces: 'top' = what the opponent took, 'bottom' = what you took
export const TRAYS = {
top: { x: LX + 12, y: 232, w: CW - 24, h: 52 },
bottom: { x: LX + 12, y: 800, w: CW - 24, h: 52 },
};
export const BUBBLE = { x: LX, y: 298, w: CW, h: 84 };
export const PARK = { x: LX, y: 396, w: CW, h: 396 }; // the open view onto the park
export const FOUNTAIN = { x: 250, y: 560 };
export const GROUND = { x0: 52, x1: 468, y0: 690, y1: 784 }; // where the pigeons walk
export const EVAL = { x: 494, y: BY, w: 16, h: BOARD };
export const STATUS = { x: RX, y: 28, w: CW, h: 176 };
export const LOG = { x: RX, y: 224, w: CW, h: 420 };
export const LOG_ROWS = 10;
export const BTN = { w: 146, h: 48 };
export const BUTTON_ROWS = [['undo', 'hint', 'draw'], ['resign', 'flip', 'menu']];
export const BUTTONS = {};
BUTTON_ROWS.forEach((row, ri) => row.forEach((k, ci) => {
BUTTONS[k] = { x: RX + BTN.w / 2 + ci * (BTN.w + 11), y: 688 + ri * 60 };
}));
export const CLOCK = { x: RX + 30, y: 820, w: 400, h: 220 }; // the chess clock case
export const CLOCK_FACES = [
{ x: CLOCK.x + 104, y: CLOCK.y + 118, r: 64 },
{ x: CLOCK.x + CLOCK.w - 104, y: CLOCK.y + 118, r: 64 },
];
export const RIBBON = { x: BX, y: 1000, w: BOARD, h: 64 };
export const BANNER = { x: BCX, y: BCY - 40 };
export function plateParts(side) {
const P = PLATES[side];
return {
portrait: { x: P.x + 94, y: P.y + 96, r: 68 },
name: { x: P.x + 186, y: P.y + 48 },
skill: { x: P.x + PLATE.w - 24, y: P.y + 48 },
note: { x: P.x + 186, y: P.y + 88 },
line: { x: P.x + 186, y: P.y + 124 },
color: { x: P.x + 186 + 12, y: P.y + 156 },
tally: { x: P.x + PLATE.w - 24, y: P.y + 156 },
};
}
/** For the verify harness: every HUD rectangle. */
export function HUD_RECTS() {
const btns = Object.values(BUTTONS);
const bx0 = Math.min(...btns.map((b) => b.x)) - BTN.w / 2, by0 = Math.min(...btns.map((b) => b.y)) - BTN.h / 2;
const bx1 = Math.max(...btns.map((b) => b.x)) + BTN.w / 2, by1 = Math.max(...btns.map((b) => b.y)) + BTN.h / 2;
return {
plateTop: { ...PLATES.top, ...PLATE },
plateBottom: { ...PLATES.bottom, ...PLATE },
trayTop: TRAYS.top,
trayBottom: TRAYS.bottom,
bubble: BUBBLE,
park: PARK,
eval: EVAL,
status: STATUS,
log: LOG,
buttons: { x: bx0, y: by0, w: bx1 - bx0, h: by1 - by0 },
clock: CLOCK,
ribbon: RIBBON,
};
}
/** Screen centre of a square (sq64, row 0 = rank 8) for the view orientation. */
export function squareXY(sq, flipped) {
const r = sq >> 3, c = sq & 7;
const vr = flipped ? 7 - r : r, vc = flipped ? 7 - c : c;
return { x: BX + vc * SQ + SQ / 2, y: BY + vr * SQ + SQ / 2 };
}
/** sq64 under a screen point, or -1. */
export function sqAt(x, y, flipped) {
const vc = Math.floor((x - BX) / SQ), vr = Math.floor((y - BY) / SQ);
if (vc < 0 || vc > 7 || vr < 0 || vr > 7) return -1;
const r = flipped ? 7 - vr : vr, c = flipped ? 7 - vc : vc;
return r * 8 + c;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,127 +1,196 @@
// Custom vector chess pieces drawn with Phaser graphics — no art assets.
// Each piece is a stylized silhouette (fill + dark outline + soft highlight)
// over a drop shadow, tinted ivory for white and charcoal for black.
//
// makePiece(scene, type, color, x, y, size) → Phaser.Container
// ChessPieces.js — the men on the board. Each is a contact shadow + a baked
// carved piece (ChessArt), positioned by square (sq64) and view orientation.
// Moves lift, glide and land with a little dust; knights hop; captured men
// tip over and slide off to the capturer's side; promotion shimmers; a mated
// king topples.
const WHITE = { fill: 0xf2ead2, hi: 0xfffdf3, ol: 0x8a7c52 };
const BLACK = { fill: 0x2b2833, hi: 0x55506a, ol: 0x05040a };
import { squareXY } from './ChessLayout.js';
import { RES, pieceKey } from './ChessArt.js';
function poly(g, pts, pal) {
g.fillStyle(pal.fill, 1);
g.fillPoints(pts, true);
g.lineStyle(2, pal.ol, 1);
g.strokePoints(pts, true);
}
const SCALE = 1 / RES;
const FOOT = 35; // from square centre down to where the base meets the board
function P(s, x, y) { return { x: x * s, y: y * s }; }
export class PieceSet {
constructor(scene, depth, { style = 'carved' } = {}) {
this.scene = scene;
this.depth = depth;
this.style = style;
this.items = new Map(); // sq64 → item
this.flipped = false;
}
function pedestal(g, s, pal) {
g.fillStyle(pal.fill, 1);
g.fillRoundedRect(-0.26 * s, 0.34 * s, 0.52 * s, 0.12 * s, 4);
g.lineStyle(2, pal.ol, 1);
g.strokeRoundedRect(-0.26 * s, 0.34 * s, 0.52 * s, 0.12 * s, 4);
g.fillStyle(pal.fill, 1);
g.fillRoundedRect(-0.20 * s, 0.28 * s, 0.40 * s, 0.07 * s, 3);
g.lineStyle(2, pal.ol, 1);
g.strokeRoundedRect(-0.20 * s, 0.28 * s, 0.40 * s, 0.07 * s, 3);
}
tex(p) { return pieceKey(this.style, p.color, p.type); }
function body(g, s, pal, topW, botW) {
poly(g, [P(s, -topW, 0.02), P(s, topW, 0.02), P(s, botW, 0.30), P(s, -botW, 0.30)], pal);
}
build(board, flipped) {
this.clear();
this.flipped = flipped;
board.forEach((p, sq) => { if (p) this.items.set(sq, this.make(sq, p)); });
return this;
}
function sheen(g, s, pal) {
g.fillStyle(pal.hi, 0.3);
g.fillEllipse(-0.10 * s, 0.02 * s, 0.10 * s, 0.34 * s);
}
make(sq, p) {
const s = this.scene;
const { x, y } = squareXY(sq, this.flipped);
const shadow = s.add.image(x, y + FOOT, 'cs-shadow').setScale(SCALE * 0.9).setAlpha(0.75);
const body = s.add.image(x, y, this.tex(p)).setScale(SCALE);
const it = { sq, p: { ...p }, shadow, body, x, y, lift: 0 };
this.place(it, x, y, 0);
return it;
}
const DRAW = {
p(g, s, pal) {
pedestal(g, s, pal);
body(g, s, pal, 0.10, 0.16);
g.fillStyle(pal.fill, 1); g.fillCircle(0, -0.12 * s, 0.14 * s);
g.lineStyle(2, pal.ol, 1); g.strokeCircle(0, -0.12 * s, 0.14 * s);
g.fillStyle(pal.hi, 0.4); g.fillCircle(-0.04 * s, -0.16 * s, 0.05 * s);
},
clear() {
for (const it of this.items.values()) { it.shadow.destroy(); it.body.destroy(); }
this.items.clear();
}
r(g, s, pal) {
pedestal(g, s, pal);
body(g, s, pal, 0.13, 0.18);
poly(g, [
P(s, -0.20, -0.02), P(s, -0.20, -0.22), P(s, -0.13, -0.22), P(s, -0.13, -0.13),
P(s, -0.05, -0.13), P(s, -0.05, -0.22), P(s, 0.05, -0.22), P(s, 0.05, -0.13),
P(s, 0.13, -0.13), P(s, 0.13, -0.22), P(s, 0.20, -0.22), P(s, 0.20, -0.02),
], pal);
sheen(g, s, pal);
},
get(sq) { return this.items.get(sq); }
all() { return [...this.items.values()]; }
n(g, s, pal) {
pedestal(g, s, pal);
poly(g, [
P(s, -0.18, 0.30), P(s, -0.21, 0.08), P(s, -0.10, -0.08), P(s, -0.17, -0.20),
P(s, -0.06, -0.34), P(s, 0.06, -0.40), P(s, 0.11, -0.30), P(s, 0.21, -0.18),
P(s, 0.23, -0.05), P(s, 0.10, -0.03), P(s, 0.05, 0.05), P(s, 0.12, 0.16),
P(s, 0.18, 0.30),
], pal);
g.fillStyle(pal.ol, 1); g.fillCircle(0.04 * s, -0.22 * s, 0.025 * s); // eye
g.lineStyle(2, pal.ol, 0.7);
g.lineBetween(-0.04 * s, -0.30 * s, -0.10 * s, -0.16 * s); // mane
},
place(it, x, y, lift = it.lift) {
it.x = x; it.y = y; it.lift = lift;
it.body.setPosition(x, y - lift);
it.shadow.setPosition(x + lift * 0.18, y + FOOT + lift * 0.1)
.setScale(SCALE * 0.9 * (1 + lift / 160), SCALE * 0.9 * (1 + lift / 220))
.setAlpha(0.75 - Math.min(0.45, lift / 110));
const d = this.depth + (lift > 0 ? 30 : 0) + y / 2000;
it.body.setDepth(d);
it.shadow.setDepth(this.depth - 1);
}
b(g, s, pal) {
pedestal(g, s, pal);
body(g, s, pal, 0.09, 0.16);
g.fillStyle(pal.fill, 1); g.fillEllipse(0, -0.14 * s, 0.24 * s, 0.34 * s);
g.lineStyle(2, pal.ol, 1); g.strokeEllipse(0, -0.14 * s, 0.24 * s, 0.34 * s);
g.lineStyle(2, pal.ol, 1); g.lineBetween(0.03 * s, -0.30 * s, -0.05 * s, -0.16 * s); // slit
g.fillStyle(pal.fill, 1); g.fillCircle(0, -0.34 * s, 0.05 * s);
g.lineStyle(2, pal.ol, 1); g.strokeCircle(0, -0.34 * s, 0.05 * s);
sheen(g, s, pal);
},
home(sq) { return squareXY(sq, this.flipped); }
q(g, s, pal) {
pedestal(g, s, pal);
body(g, s, pal, 0.11, 0.18);
// crown band
g.fillStyle(pal.fill, 1); g.fillRoundedRect(-0.19 * s, -0.18 * s, 0.38 * s, 0.10 * s, 4);
g.lineStyle(2, pal.ol, 1); g.strokeRoundedRect(-0.19 * s, -0.18 * s, 0.38 * s, 0.10 * s, 4);
// five spikes with balls
const xs = [-0.17, -0.085, 0, 0.085, 0.17];
for (const x of xs) {
poly(g, [P(s, x - 0.045, -0.18), P(s, x + 0.045, -0.18), P(s, x, -0.36)], pal);
g.fillStyle(pal.fill, 1); g.fillCircle(x * s, -0.37 * s, 0.045 * s);
g.lineStyle(2, pal.ol, 1); g.strokeCircle(x * s, -0.37 * s, 0.045 * s);
setFlipped(f) {
this.flipped = f;
for (const it of this.items.values()) { const p = this.home(it.sq); this.place(it, p.x, p.y, 0); }
}
setStyle(style) {
this.style = style;
for (const it of this.items.values()) it.body.setTexture(this.tex(it.p));
}
setVisible(v) { for (const it of this.items.values()) { it.body.setVisible(v); it.shadow.setVisible(v); } }
tween(cfg) { return new Promise((res) => this.scene.tweens.add({ ...cfg, onComplete: res })); }
async liftTo(it, lift, dur = 110) {
if (!it) return;
const o = { l: it.lift };
await this.tween({ targets: o, l: lift, duration: dur, ease: 'Quad.Out', onUpdate: () => this.place(it, it.x, it.y, o.l) });
}
/** Glide (or hop, for a knight) to a square. */
async moveTo(it, sq, { dur = 260, arc = 14 } = {}) {
if (!it) return;
const from = { x: it.x, y: it.y, l: it.lift };
const to = this.home(sq);
const o = { t: 0 };
const dist = Math.hypot(to.x - from.x, to.y - from.y);
const d = dur * (0.75 + Math.min(1, dist / 500) * 0.5);
await this.tween({
targets: o, t: 1, duration: d, ease: 'Cubic.InOut',
onUpdate: () => {
const t = o.t;
const lift = from.l * (1 - t) + Math.sin(Math.PI * t) * arc;
this.place(it, from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t, lift);
},
});
this.place(it, to.x, to.y, 0);
}
async squash(it, amt = 0.08, dur = 110) {
if (!it?.body?.active) return;
await this.tween({ targets: it.body, scaleX: SCALE * (1 + amt), scaleY: SCALE * (1 - amt), duration: dur / 2, yoyo: true, ease: 'Quad.Out' });
it.body.setScale(SCALE);
}
/** A puff of dust where a piece lands. */
dust(x, y, n = 6) {
const s = this.scene;
for (let i = 0; i < n; i++) {
const d = s.add.image(x + (Math.random() - 0.5) * 30, y + FOOT - 2, 'cs-dust').setDepth(this.depth - 0.5).setScale(0.2).setAlpha(0.55);
const a = (i / n) * Math.PI * 2;
s.tweens.add({ targets: d, x: d.x + Math.cos(a) * 28, y: d.y + Math.sin(a) * 8 - 4, scale: 0.55, alpha: 0, duration: 420 + Math.random() * 200, ease: 'Quad.Out', onComplete: () => d.destroy() });
}
sheen(g, s, pal);
},
}
k(g, s, pal) {
pedestal(g, s, pal);
body(g, s, pal, 0.11, 0.18);
// crown band
g.fillStyle(pal.fill, 1); g.fillRoundedRect(-0.18 * s, -0.20 * s, 0.36 * s, 0.10 * s, 4);
g.lineStyle(2, pal.ol, 1); g.strokeRoundedRect(-0.18 * s, -0.20 * s, 0.36 * s, 0.10 * s, 4);
// shoulder bumps
poly(g, [P(s, -0.18, -0.10), P(s, -0.10, -0.20), P(s, -0.02, -0.10)], pal);
poly(g, [P(s, 0.02, -0.10), P(s, 0.10, -0.20), P(s, 0.18, -0.10)], pal);
// cross
g.fillStyle(pal.fill, 1);
g.fillRoundedRect(-0.035 * s, -0.46 * s, 0.07 * s, 0.26 * s, 3);
g.fillRoundedRect(-0.11 * s, -0.40 * s, 0.22 * s, 0.06 * s, 3);
g.lineStyle(2, pal.ol, 1);
g.strokeRoundedRect(-0.035 * s, -0.46 * s, 0.07 * s, 0.26 * s, 3);
g.strokeRoundedRect(-0.11 * s, -0.40 * s, 0.22 * s, 0.06 * s, 3);
sheen(g, s, pal);
},
};
rekey(it, sq) {
this.items.delete(it.sq);
it.sq = sq;
this.items.set(sq, it);
}
export function makePiece(scene, type, color, x, y, size) {
const pal = color === 'white' ? WHITE : BLACK;
const shadow = scene.add.graphics();
shadow.fillStyle(0x000000, 0.28);
shadow.fillEllipse(3, 0.42 * size + 3, 0.56 * size, 0.15 * size);
const g = scene.add.graphics();
(DRAW[type] ?? DRAW.p)(g, size, pal);
return scene.add.container(x, y, [shadow, g]);
/** Remove a piece without animation. */
remove(sq) {
const it = this.items.get(sq);
if (!it) return;
it.body.destroy(); it.shadow.destroy();
this.items.delete(sq);
}
/** Captured: tip over, then slide off toward (tx, ty) shrinking. */
async capture(sq, tx, ty, { dur = 520, delay = 0 } = {}) {
const it = this.items.get(sq);
if (!it) return;
this.items.delete(sq);
const dir = tx < it.x ? -1 : 1;
it.body.setDepth(this.depth + 40);
await this.tween({ targets: it.body, angle: dir * 82, x: it.x + dir * 22, y: it.y + 16, duration: 200, delay, ease: 'Quad.In' });
this.dust(it.x + dir * 30, it.y, 4);
const from = { x: it.body.x, y: it.body.y };
const o = { t: 0 };
await this.tween({
targets: o, t: 1, duration: dur, ease: 'Quad.InOut',
onUpdate: () => {
const t = o.t;
const x = from.x + (tx - from.x) * t, y = from.y + (ty - from.y) * t - Math.sin(Math.PI * t) * 70;
it.body.setPosition(x, y).setScale(SCALE * (1 - 0.6 * t)).setAngle(dir * (82 + t * 100));
it.shadow.setPosition(x, y + FOOT * (1 - t) + Math.sin(Math.PI * t) * 70).setAlpha(0.5 * (1 - t));
},
});
it.body.destroy(); it.shadow.destroy();
}
/** Promotion: the pawn shimmers into the new piece. */
async promote(it, type) {
if (!it) return;
const s = this.scene;
const flash = s.add.image(it.x, it.y - 10, 'cs-glow').setDepth(this.depth + 45).setScale(0.3).setAlpha(0).setBlendMode('ADD');
await this.tween({ targets: flash, alpha: 1, scale: 1.4, duration: 220, ease: 'Quad.Out' });
it.p = { ...it.p, type };
it.body.setTexture(this.tex(it.p));
await this.tween({ targets: flash, alpha: 0, scale: 2, duration: 360, ease: 'Quad.In' });
flash.destroy();
await this.squash(it, 0.12, 160);
}
/** Checkmate: the king rocks, then falls. */
async topple(sq) {
const it = this.items.get(sq);
if (!it) return;
const dir = Math.random() < 0.5 ? -1 : 1;
await this.tween({ targets: it.body, angle: dir * 8, duration: 140, yoyo: true, repeat: 1, ease: 'Sine.InOut' });
await this.tween({ targets: it.body, angle: dir * 92, x: it.x + dir * 30, y: it.y + 18, duration: 620, ease: 'Bounce.Out' });
this.dust(it.x + dir * 36, it.y, 8);
}
/** Bring every piece in, rank by rank, from above the table. */
async dropIn(k = 1, onLand = null) {
const list = this.all().sort((a, b) => (a.y - b.y) || (a.x - b.x));
const jobs = list.map((it, i) => new Promise((res) => {
const { x, y } = it;
this.place(it, x, y, 160);
it.body.setAlpha(0); it.shadow.setAlpha(0);
this.scene.time.delayedCall(i * 22 * k, () => {
it.body.setAlpha(1);
const o = { l: 160 };
this.scene.tweens.add({
targets: o, l: 0, duration: 240, ease: 'Quad.In',
onUpdate: () => this.place(it, x, y, o.l),
onComplete: () => { onLand?.(i); this.squash(it, 0.08, 90).then(res); },
});
});
}));
await Promise.all(jobs);
}
}

View File

@ -0,0 +1,230 @@
// ChessPuzzleData.js — GENERATED by tools/genChessPuzzles.js. Do not edit by hand.
// 223 original tactics mined from engine self-play at the Stone Tables.
// fen: the position before the opponent's last move; moves (UCI): that move,
// then the solution (yours, their reply, yours…). Sorted by rating.
export const PUZZLES = [
{ id: 'st001', fen: '1rb4k/2p3pp/2p5/p4p2/2PP4/P1q5/2P5/K7 w - - 3 34', moves: 'a1a2 c3b2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st002', fen: '1rQ1kbnr/3ppppp/p7/4P3/B7/2N2N2/PPn2PPP/R1BQ1K1R b k - 0 15', moves: 'b8c8 d1d7', rating: 660, themes: 'mateIn1 check' },
{ id: 'st003', fen: '2Q2b2/1p2krq1/pp2p1p1/4P2r/4B3/1P6/P3NPpP/R2R2K1 b - - 3 28', moves: 'g7e5 c8d8', rating: 660, themes: 'mateIn1 check' },
{ id: 'st004', fen: '2Q5/8/4R3/7K/P6P/6P1/1B1k4/8 b - - 2 69', moves: 'd2d3 c8c3', rating: 660, themes: 'mateIn1 check' },
{ id: 'st005', fen: '2r1Q3/8/7R/1NkP2P1/p1P5/P2K3P/5P2/8 b - - 0 51', moves: 'c8e8 h6c6', rating: 660, themes: 'mateIn1 check' },
{ id: 'st006', fen: '3k1bn1/p1Nb1pp1/2n5/2p5/3pPp2/3P1P2/PPP3qr/R1Q2KN1 w - - 2 19', moves: 'f1e1 g2g1', rating: 660, themes: 'mateIn1 hanging check' },
{ id: 'st007', fen: '3N4/7k/7p/6R1/1P2B3/4P3/6PP/7K b - - 2 48', moves: 'h7h8 d8f7', rating: 660, themes: 'mateIn1 check' },
{ id: 'st008', fen: '3r2k1/7p/4p1p1/1P3p1K/1p6/5P1P/6r1/4q3 w - - 0 39', moves: 'h5h6 e1h4', rating: 660, themes: 'mateIn1 check' },
{ id: 'st009', fen: '4r1k1/1b3ppp/p1p5/1pbp4/5p2/1B1P1P2/PP1N1K2/1RB4q w - - 3 33', moves: 'd3d4 c5d4', rating: 660, themes: 'mateIn1 check' },
{ id: 'st010', fen: '4r1kr/pp1bbppp/2n5/3p2P1/nqpP1B2/2N2N1P/1PP2P2/1K1QRB1R w - - 0 23', moves: 'b1a2 b4b2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st011', fen: '5Q2/6k1/5R1p/3P4/2PB4/8/P7/7K b - - 2 39', moves: 'g7h7 f6h6', rating: 660, themes: 'mateIn1 check' },
{ id: 'st012', fen: '5r2/1p4kp/pbp4p/8/5p2/Pb5B/1R4P1/4q2K w - - 0 47', moves: 'h1h2 e1g1', rating: 660, themes: 'mateIn1 check' },
{ id: 'st013', fen: '5r2/1p4kp/pPp1B2p/7b/5p1P/P3b3/R5P1/3q1R1K w - - 0 39', moves: 'f1g1 d1g1', rating: 660, themes: 'mateIn1 hanging check' },
{ id: 'st014', fen: '5r2/pb3kp1/2p2n1p/1p2pB2/8/2Q3PP/Pr3P2/3q2KR w - - 0 29', moves: 'g1h2 b2f2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st015', fen: '6k1/5p2/5p1p/3p4/1P4PK/1r3q1P/6n1/8 w - - 2 59', moves: 'h4h5 f3h3', rating: 660, themes: 'mateIn1 check' },
{ id: 'st016', fen: '6k1/ppp3pp/3p4/3Kq3/8/5r1P/8/8 w - - 6 41', moves: 'd5c4 e5c5', rating: 660, themes: 'mateIn1 check' },
{ id: 'st017', fen: '6k1/Q7/2R5/8/3pp3/3P2PP/5P2/6K1 b - - 4 58', moves: 'e4d3 c6c8', rating: 660, themes: 'mateIn1 check' },
{ id: 'st018', fen: '7k/4Qp2/6p1/1P1BP2p/5P1P/2r3P1/r4K2/8 w - - 0 65', moves: 'f2g1 c3c1', rating: 660, themes: 'mateIn1 check' },
{ id: 'st019', fen: '7k/4R3/5Np1/b7/5PPP/3K4/8/8 b - - 2 51', moves: 'a5b6 e7h7', rating: 660, themes: 'mateIn1 check' },
{ id: 'st020', fen: '7r/Q4k2/R7/2B5/5Kp1/6P1/8/8 b - - 2 63', moves: 'f7g8 a6g6', rating: 660, themes: 'mateIn1 check' },
{ id: 'st021', fen: '8/1k1Q4/8/7R/6p1/4B1P1/1P3P1P/6K1 b - - 4 41', moves: 'b7b8 h5h8', rating: 660, themes: 'mateIn1 check' },
{ id: 'st022', fen: '8/1P5k/7p/8/p3b2P/P1b5/r3p3/5K2 w - - 0 55', moves: 'f1f2 e2e1q', rating: 660, themes: 'mateIn1 promotion check' },
{ id: 'st023', fen: '8/3q3R/1p2k1Q1/p2p4/8/1RP1P3/P4PP1/6K1 b - - 2 48', moves: 'e6e5 f2f4', rating: 660, themes: 'mateIn1 check' },
{ id: 'st024', fen: '8/4Q3/6k1/6R1/1pp2P1P/1P5P/1PP5/6K1 b - - 4 57', moves: 'g6h6 e7g7', rating: 660, themes: 'mateIn1 check' },
{ id: 'st025', fen: '8/5p2/1N6/6p1/k3p1Pp/4P3/1Q3P2/4KB1R b K - 0 38', moves: 'a4a5 b2b5', rating: 660, themes: 'mateIn1 check' },
{ id: 'st026', fen: '8/6k1/7p/8/3bpP2/6PP/r2N4/2r4K w - - 2 47', moves: 'h1g2 a2d2', rating: 660, themes: 'mateIn1 hanging check' },
{ id: 'st027', fen: '8/6pk/7p/8/8/5q2/1R3P2/4r1K1 w - - 2 39', moves: 'g1h2 e1h1', rating: 660, themes: 'mateIn1 check' },
{ id: 'st028', fen: '8/8/1p2b1p1/7p/4n2P/3k4/7q/1K6 w - - 2 63', moves: 'b1c1 h2c2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st029', fen: '8/8/6K1/8/7P/P4Q1k/8/6B1 b - - 8 68', moves: 'h3h4 g1f2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st030', fen: '8/p4k2/2p3p1/8/3r1p2/8/2r5/4K3 w - - 0 47', moves: 'e1f1 d4d1', rating: 660, themes: 'mateIn1 check' },
{ id: 'st031', fen: 'r1b3Q1/ppq5/1nNk4/2b2pBp/3P4/2P5/P4PPP/4R1K1 b - - 2 29', moves: 'b6d7 g8e6', rating: 660, themes: 'mateIn1 check' },
{ id: 'st032', fen: 'r1br3k/pp1p1Bpp/8/6N1/8/3QB3/PPP2PPP/RN2K2R b KQ - 2 14', moves: 'h7h6 d3h7', rating: 660, themes: 'mateIn1 check' },
{ id: 'st033', fen: 'r2qkb1r/pBp2ppp/8/3Pp3/3Knn2/8/PPP1q2P/RN6 w kq e6 0 17', moves: 'd4e5 d8f6', rating: 660, themes: 'mateIn1 check' },
{ id: 'st034', fen: 'r3r1k1/ppp2p2/8/2b3p1/4p1bp/P2P2q1/RP4KN/2B4R w - - 2 26', moves: 'g2f1 g3f2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st035', fen: 'r4rk1/pp4pp/P3p1n1/2ppP3/3P2P1/4nq2/1PP2P1B/R1N2RK1 w - - 2 25', moves: 'a6b7 f3g2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st036', fen: 'r5k1/1p2B2p/2bPp1p1/2p5/p5q1/P2r4/2Pb3P/R5K1 w - - 0 34', moves: 'g1f2 g4g2', rating: 660, themes: 'mateIn1 check' },
{ id: 'st037', fen: 'r5r1/1pp4p/p1k1p3/2N3p1/3P4/1Q2P1BP/PP2BPP1/4K1R1 b - - 0 23', moves: 'b7b5 b3e6', rating: 660, themes: 'mateIn1 check' },
{ id: 'st038', fen: 'r6k/1pp3pp/p2p4/4p3/1Pq1n1bP/P1N1K3/3P2P1/B1Q5 w - - 2 26', moves: 'c1b2 c4d4', rating: 660, themes: 'mateIn1 check' },
{ id: 'st039', fen: 'r7/p4k2/2p3pp/4p1K1/q7/4P2P/2Pr4/8 w - - 0 39', moves: 'g5h6 a4h4', rating: 660, themes: 'mateIn1 check' },
{ id: 'st040', fen: '1k1r3r/pp3ppp/1q2p3/3NRn2/P7/5N1P/1P3PP1/1R1Q2K1 b - - 0 24', moves: 'e6d5 e5f5', rating: 730, themes: 'hanging' },
{ id: 'st041', fen: '2q3k1/1p3pp1/2nNbn1p/1r6/3pP3/3P2P1/2Rb1PBP/Q4RK1 b - - 1 33', moves: 'c8d8 d6b5', rating: 730, themes: 'hanging' },
{ id: 'st042', fen: '2rr2k1/1p3p2/p4b1p/4p1p1/1nBpP3/5P1P/1PPB1KRP/R7 w - - 2 28', moves: 'd2b4 c8c4', rating: 730, themes: 'hanging' },
{ id: 'st043', fen: '3r1rk1/R4ppp/p1q3b1/Ppp3P1/8/4P3/1P2BP1P/R1B3K1 b - - 0 25', moves: 'c6f3 e2f3', rating: 730, themes: 'hanging' },
{ id: 'st044', fen: '3rkb2/1R3p1r/p6p/2p3p1/4n3/3Q4/P1P2PPP/4R1K1 w - - 2 29', moves: 'c2c4 d8d3', rating: 730, themes: 'hanging' },
{ id: 'st045', fen: '5b1k/1p6/p2p4/3npP2/6P1/3K4/PP1N1r2/4R3 b - - 3 34', moves: 'f2f3 d2f3', rating: 730, themes: 'hanging' },
{ id: 'st046', fen: '8/1R6/4k3/7K/P3N3/P6P/1r4r1/8 w - - 3 66', moves: 'e4d6 e6d6', rating: 730, themes: 'hanging' },
{ id: 'st047', fen: '8/2p2p2/7k/p1p3Rp/P2p4/1Pr1n1P1/2BRK2P/3r4 w - - 14 57', moves: 'c2d1 h6g5', rating: 730, themes: 'hanging' },
{ id: 'st048', fen: '8/5R2/6k1/pp1B3r/4p3/PP2P2b/2P5/1K6 w - - 4 48', moves: 'f7f4 h5d5', rating: 730, themes: 'hanging' },
{ id: 'st049', fen: 'r1b2k2/ppppqp1Q/5np1/1Nb1p3/2B1PP2/3P4/PPP3PP/R4RK1 w - - 1 17', moves: 'g1h1 f6h7', rating: 730, themes: 'hanging' },
{ id: 'st050', fen: 'r1bq1rk1/1ppp1ppp/p1nb1n2/1B2p3/4P3/2NP1N2/PPP2PPP/R1BQ1RK1 w - - 0 7', moves: 'c3d5 a6b5', rating: 730, themes: 'hanging' },
{ id: 'st051', fen: 'r1bqk2r/p1ppbppp/2n2n2/1p2p3/N3P3/3P1N2/PPP1QPPP/R1B1KB1R w KQkq - 0 7', moves: 'c1g5 b5a4', rating: 730, themes: 'hanging' },
{ id: 'st052', fen: 'r1bqk2r/pp2bppp/2np1n2/4p3/2B1P3/2N2N2/PPP2PPP/R1BQ1RK1 b kq - 5 8', moves: 'c8f5 e4f5', rating: 730, themes: 'hanging' },
{ id: 'st053', fen: 'r1bqk2r/pppp1Npp/2n2n2/4p3/2B1P3/8/PPPB1PPP/R2QK2R b KQkq - 0 7', moves: 'd8e7 f7h8', rating: 730, themes: 'hanging' },
{ id: 'st054', fen: 'r1bqkb1r/ppp2ppp/3p1n2/3Pp3/3nP3/2N1B3/PPP1NPPP/R2QKB1R b KQkq - 4 6', moves: 'd4b5 c3b5', rating: 730, themes: 'hanging' },
{ id: 'st055', fen: 'r2q2rk/p4p1p/2bb1n1N/8/3P4/2N2p2/PPP2Q1P/R1B2RK1 w - - 2 18', moves: 'c1g5 g8g5', rating: 730, themes: 'hanging check' },
{ id: 'st056', fen: 'r2q3k/pp1N2pp/2p5/2Q5/3P1r2/8/PPP3K1/R3R2q w - - 0 24', moves: 'e1h1 d8d7', rating: 730, themes: 'hanging' },
{ id: 'st057', fen: 'r2qk2r/Npp2ppp/1nb1p3/4P3/8/8/PPP1BQPP/R2K3R w kq - 3 17', moves: 'd1e1 a8a7', rating: 730, themes: 'hanging' },
{ id: 'st058', fen: 'r2qr1k1/p1pn2pp/b3p3/B1pp1p2/3P4/2P3P1/P1P1PPBP/1R1Q1RK1 b - - 1 14', moves: 'a6b5 b1b5', rating: 730, themes: 'hanging' },
{ id: 'st059', fen: 'r3k1nr/ppp2ppp/2n5/1B1p4/1q1pP3/5N2/PPP2PPP/R1Q1K2R w KQkq - 1 10', moves: 'c1d2 b4b5', rating: 730, themes: 'hanging' },
{ id: 'st060', fen: 'r3R1k1/1p1q3p/p6Q/8/3p4/3N4/PP3PPb/2R2K2 b - - 0 28', moves: 'a8e8 h6h2', rating: 730, themes: 'hanging' },
{ id: 'st061', fen: 'r6r/1bpqkppp/p2Pp3/8/3P4/2nB1N2/PP3PPP/R2QK2R b KQ - 0 17', moves: 'c7d6 b2c3', rating: 730, themes: 'hanging' },
{ id: 'st062', fen: 'rn2kb1r/pp2pppp/2p1bn2/q5B1/3Pp3/7Q/PPP2PPP/RN2KBNR w KQkq - 6 7', moves: 'h3c3 a5g5', rating: 730, themes: 'hanging' },
{ id: 'st063', fen: 'rnb1kb1r/pp2nppp/2p1p3/3pP3/3P4/2NB1N2/qPP2PPP/R1BQK2R w KQkq - 0 7', moves: 'd3b5 a2a1', rating: 730, themes: 'hanging' },
{ id: 'st064', fen: 'rnbqk2r/pppnbp1B/6pB/3pP3/3P4/3Q1N2/PPP2PPP/R4RK1 w - - 2 12', moves: 'h7g6 h8h6', rating: 730, themes: 'hanging' },
{ id: 'st065', fen: '1r6/5B2/2r2p1p/P5p1/3k2P1/P6P/3N1P2/2B3K1 w - - 1 58', moves: 'g1h2 c6c1 d2b3 b8b3', rating: 850, themes: 'hanging' },
{ id: 'st066', fen: '2b1R3/8/5p2/1k1B2pp/3B4/8/PR3PPP/6K1 b - - 3 34', moves: 'b5a5 e8c8 f6f5 c8a8', rating: 850, themes: 'mateIn2 hanging' },
{ id: 'st067', fen: '2r5/2P2B2/3k1P2/7P/P7/4PK2/3r4/2R5 b - - 0 56', moves: 'c8b8 c7b8q d6d7 b8c7', rating: 850, themes: 'mateIn2 promotion hanging check' },
{ id: 'st068', fen: '8/1pN1kQ2/4r3/p2p4/3P4/6P1/PPP1P1BP/R4RK1 b - - 0 25', moves: 'e7d8 c7e6 d8c8 f7e8', rating: 850, themes: 'mateIn2 hanging check' },
{ id: 'st069', fen: 'r1b3kr/1ppp1p1p/p1B3pB/4b3/1nPN4/1N6/PP3PPP/R3Q1K1 b - - 0 17', moves: 'd7c6 e1e5 b4d3 e5e8', rating: 850, themes: 'mateIn2 hanging' },
{ id: 'st070', fen: 'r5k1/1p1Q1pp1/3r3p/p1p1p3/P1P1P3/R1BBnn2/1PP4P/3R2K1 w - - 0 24', moves: 'g1f2 e3d1 f2f3 d6d7', rating: 850, themes: 'hanging fork check' },
{ id: 'st071', fen: '1k6/5N2/8/6p1/R7/5P1P/3r2P1/5K2 b - - 6 45', moves: 'd2d1 f1e2', rating: 880, themes: 'advantage' },
{ id: 'st072', fen: '1r2r1k1/1pp2ppp/8/3p1q2/1Q2n1PP/P3P3/1P1n1P2/R1B1K2R b - - 2 22', moves: 'e4d6 g4f5', rating: 880, themes: 'advantage' },
{ id: 'st073', fen: '1r3rk1/Qbq3bp/4p1p1/1N1nN1B1/4PP2/P7/6PP/3R1RK1 b - - 2 26', moves: 'c7b6 a7b6', rating: 880, themes: 'advantage' },
{ id: 'st074', fen: '1r5k/8/2p1B1pp/P1Qnp3/2P4P/5PP1/4q3/5RK1 b - - 0 36', moves: 'e2e3 c5e3', rating: 880, themes: 'advantage' },
{ id: 'st075', fen: '2b2rk1/3p1p2/rp3qp1/2p1n1B1/p1P1nPp1/P2P2P1/1P1Q3P/R4RK1 w - - 0 23', moves: 'd3e4 e5c4', rating: 880, themes: 'advantage' },
{ id: 'st076', fen: '2b4r/r1pk3p/p4b2/4p3/B2nP3/2P2N2/1P3PPP/3R1RK1 b - - 0 23', moves: 'd7e7 c3d4', rating: 880, themes: 'advantage' },
{ id: 'st077', fen: '2k1r3/8/ppp5/2R1Bp2/1P1p3p/3P1P2/2P5/6KB b - - 0 42', moves: 'c8d7 c5c4', rating: 880, themes: 'advantage' },
{ id: 'st078', fen: '2k4r/pp2p2p/1q2p2b/4n3/2p2PB1/2N3B1/PPP3PP/1RK4R w - - 0 19', moves: 'c3d5 b6d6', rating: 880, themes: 'advantage' },
{ id: 'st079', fen: '2k5/p5Bp/2p2p2/4n1p1/1p1r4/1P5P/2R1KPP1/3R4 b - - 3 33', moves: 'd4e4 e2f1', rating: 880, themes: 'advantage' },
{ id: 'st080', fen: '2q2rk1/5rpp/1p1p4/1P1P1R1P/P7/1P2PQN1/5K2/8 w - - 1 44', moves: 'f3e4 f7f5', rating: 880, themes: 'check advantage' },
{ id: 'st081', fen: '2r4k/1r3p1p/1qp1bNp1/p2BPn2/Q6P/P2R4/1PR2PP1/6K1 b - - 0 27', moves: 'b6b5 a4b5', rating: 880, themes: 'advantage' },
{ id: 'st082', fen: '3R4/4P1k1/B6p/7b/5K2/2r4P/8/8 b - - 0 51', moves: 'c3f3 f4e4', rating: 880, themes: 'advantage' },
{ id: 'st083', fen: '3rkb1r/1qp1npp1/p6p/nB6/4P3/2N5/PPP2PPP/R1BQR1K1 b k - 2 14', moves: 'c7c6 b5d3', rating: 880, themes: 'advantage' },
{ id: 'st084', fen: '3rkb1r/pppb1p2/nn4qp/1Q1Pp1P1/2P5/2N3B1/PP2NPP1/R3KB1R w k - 1 17', moves: 'b5b3 a6c5', rating: 880, themes: 'advantage' },
{ id: 'st085', fen: '4k2r/p1p2ppp/1q2p3/2bn4/Pr6/2N2N2/QPbB1PPP/R3K2R w Kk - 2 17', moves: 'c3d5 c5f2', rating: 880, themes: 'check advantage' },
{ id: 'st086', fen: '4q3/2p2kbp/p3r3/3Q1pP1/1P1B4/P5P1/7K/4R3 b - - 0 72', moves: 'g7d4 d5f5', rating: 880, themes: 'fork check' },
{ id: 'st087', fen: '4rrk1/pp2bppp/3pq3/2p1P3/3BP1n1/2NP4/PPP1B1PP/R2QK2R b KQ - 0 16', moves: 'e7h4 g2g3', rating: 880, themes: 'advantage' },
{ id: 'st088', fen: '5r2/1R3pk1/2p4N/p5p1/6P1/6P1/5r1P/R5K1 b - - 4 52', moves: 'f2c2 h6f5', rating: 880, themes: 'check advantage' },
{ id: 'st089', fen: '5r2/2P5/8/5bp1/4p2p/3k3P/5PK1/R7 w - - 9 60', moves: 'a1d1 d3e2', rating: 880, themes: 'advantage' },
{ id: 'st090', fen: '5rk1/2R1Qppp/4P2r/R7/3p4/6PB/5PKP/1q6 b - - 2 35', moves: 'b1e4 g2f1', rating: 880, themes: 'advantage' },
{ id: 'st091', fen: '6k1/1rpp1ppp/3b4/P2N4/1p1Pr1n1/8/1PPK1PP1/R2R4 w - - 2 26', moves: 'f2f3 e4d4', rating: 880, themes: 'check advantage' },
{ id: 'st092', fen: '6k1/5Bp1/3N4/1p5p/p4P1P/Pr6/6P1/6K1 b - - 1 37', moves: 'g8f8 f7b3', rating: 880, themes: 'advantage' },
{ id: 'st093', fen: '7k/8/8/8/4K3/5pR1/2r4p/8 w - - 2 77', moves: 'g3h3 h8g8', rating: 880, themes: 'advantage' },
{ id: 'st094', fen: '7k/q2r2p1/p6p/8/8/8/1pQ3PP/3R3K w - - 0 47', moves: 'c2c8 h8h7', rating: 880, themes: 'advantage' },
{ id: 'st095', fen: '8/8/p4k1P/P2p1pp1/1p1p4/3P2P1/2PK4/8 w - - 1 50', moves: 'h6h7 f6g7', rating: 880, themes: 'advantage' },
{ id: 'st096', fen: '8/8/p7/P2p4/3p4/1P1P1kp1/8/6K1 b - - 0 66', moves: 'g3g2 b3b4', rating: 880, themes: 'advantage' },
{ id: 'st097', fen: 'B2r2k1/5pp1/p1Qq3p/1p6/3p2P1/P7/1PP4P/4R2K b - - 2 27', moves: 'd6f8 a8b7', rating: 880, themes: 'advantage' },
{ id: 'st098', fen: 'Bnbr2k1/p1p2ppp/4p3/qp6/Pb6/1N4P1/4PP1P/3RQRK1 b - - 4 17', moves: 'b8d7 b3a5', rating: 880, themes: 'advantage' },
{ id: 'st099', fen: 'Q1b3k1/1p2npP1/7p/1Nb2P2/3p4/3q2P1/5R1P/4R1K1 b - - 1 46', moves: 'd3b5 f5f6', rating: 880, themes: 'advantage' },
{ id: 'st100', fen: 'r1b1kb1r/1pp1qppp/3p4/2np4/2P5/4QN2/PP2PPPP/RN2KB1R w KQkq - 0 12', moves: 'c4d5 e7e3', rating: 880, themes: 'advantage' },
{ id: 'st101', fen: 'r1b1kb1r/pp1ppppp/1qN2n2/4P3/8/8/PPP2PPP/RNBQKB1R b KQkq - 0 6', moves: 'd7c6 e5f6', rating: 880, themes: 'advantage' },
{ id: 'st102', fen: 'r1bq1k2/pp3Bpp/1npb4/3nr1N1/3QN3/4B3/PPP2PPP/3R1RK1 b - - 6 16', moves: 'c8f5 e4d6', rating: 880, themes: 'advantage' },
{ id: 'st103', fen: 'r2q1b1r/pp2kppp/5p2/1Bp5/3BP3/5b2/PPP2PPP/R2QK2R w KQ - 2 10', moves: 'e1g1 f3d1', rating: 880, themes: 'advantage' },
{ id: 'st104', fen: 'r2r2k1/ppp1qp1p/4pnp1/1P1pN3/3PPP2/1PNQ4/1bP2RPP/R5K1 w - - 1 18', moves: 'a1a4 b2c3', rating: 880, themes: 'advantage' },
{ id: 'st105', fen: 'r3kb1r/ppp2ppp/2npbq2/1N1np3/7P/3PBN2/PPPQPPP1/2KR1B1R b kq - 4 10', moves: 'h7h5 e3g5', rating: 880, themes: 'advantage' },
{ id: 'st106', fen: 'r3kb2/ppp1ppp1/n2q3B/3pNb1p/1P1P3P/P2Q1Nn1/2P1PPP1/2R1KB1R w Kq - 1 16', moves: 'e5g4 f5d3', rating: 880, themes: 'advantage' },
{ id: 'st107', fen: 'r4k2/p1p1pp2/6b1/2p3B1/Q2bP1P1/7B/Pq3P2/2R2K2 w - - 2 24', moves: 'g5h6 f8g8', rating: 880, themes: 'advantage' },
{ id: 'st108', fen: 'r4rk1/3b2pp/2n1p3/1p2q3/1p1pBN2/1Q4P1/P1P2P1P/R3R1K1 b - - 1 24', moves: 'e5c5 f4e6', rating: 880, themes: 'fork' },
{ id: 'st109', fen: 'r5k1/1pr3p1/5p1p/1B1R4/2P5/p7/P2n1n1P/4R1K1 w - - 0 33', moves: 'g1f2 d2c4', rating: 880, themes: 'advantage' },
{ id: 'st110', fen: 'rnb1k2r/pppp1ppp/4pq2/3P4/2P1Q3/2b5/PP2PPPP/R1B1KBNR w KQkq - 0 7', moves: 'c1d2 c3d2', rating: 880, themes: 'check advantage' },
{ id: 'st111', fen: '1r4k1/5p1p/p5p1/7q/4p3/R3P1P1/1p1P1PPK/3R4 w - - 1 32', moves: 'h2g1 h5d1 g1h2 d1h5 h2g1 b2b1q', rating: 970, themes: 'mateIn3 promotion hanging check long' },
{ id: 'st112', fen: '2k5/1p4p1/8/3p1p1p/2bb3P/8/4rNK1/8 w - - 4 40', moves: 'g2g3 e2f2 g3h3 c4f1 h3g3 f5f4', rating: 970, themes: 'mateIn3 hanging long' },
{ id: 'st113', fen: '2Nr1b1r/1P2kppp/p1B1p3/8/8/5N2/PPb2PPK/R1BQ1R2 b - - 2 16', moves: 'e7f6 d1d8 f8e7 d8e7 f6g6 e7g5', rating: 970, themes: 'mateIn3 hanging check long' },
{ id: 'st114', fen: '5k2/1prbbp2/2R1p2p/p3r3/P2PNN2/7P/5PPR/6K1 w - - 0 33', moves: 'f4g6 f7g6 c6c7 e5e4 f2f3 e4d4', rating: 970, themes: 'hanging long' },
{ id: 'st115', fen: '5rk1/1pR3b1/p3N1B1/3Pp3/4p1N1/7P/PP3P2/4K2R b K - 3 26', moves: 'f8f3 c7g7 g8h8 g7h7 h8g8 g4h6', rating: 970, themes: 'mateIn3 hanging check long' },
{ id: 'st116', fen: '7k/3b1p1p/3p4/1p1qp1R1/5P2/7P/r2r2P1/4R1K1 w - - 0 32', moves: 'e1e4 d5e4 f4e5 d2g2 g5g2 e4g2', rating: 970, themes: 'mateIn3 hanging long' },
{ id: 'st117', fen: '8/1pQ3bR/4pk2/8/8/5P2/PN4P1/6K1 b - - 2 40', moves: 'b7b5 c7g7 f6f5 h7h5 f5f4 g7e5', rating: 970, themes: 'mateIn3 hanging check long' },
{ id: 'st118', fen: 'r1b4r/2Q1k1p1/p2p3p/1B1PNp2/1p2n3/4P3/PP3PPP/R3K2R b KQ - 4 21', moves: 'c8d7 c7d7 e7f6 d7f7 f6e5 f7e6', rating: 970, themes: 'mateIn3 hanging check long' },
{ id: 'st119', fen: 'r1k5/ppp2pBp/2n5/8/P6P/2Pq4/2bK1P2/3R4 w - - 3 26', moves: 'd2c1 d3d1 c1b2 d1b1 b2a3 b1b3', rating: 970, themes: 'mateIn3 hanging check long' },
{ id: 'st120', fen: 'r4r2/p4b1k/3R4/1p4Q1/2p3p1/7P/P4PP1/6K1 b - - 1 39', moves: 'f7e6 d6e6 f8f6 e6f6 a8g8 f6h6', rating: 970, themes: 'mateIn3 hanging long' },
{ id: 'st121', fen: '1Q3r2/3R4/5R2/5p2/3k4/6PP/5K2/8 b - - 1 52', moves: 'd4c5 b8b6 c5c4 f6c6', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st122', fen: '1r2r1k1/p1p2p1p/p6p/3pn3/5bb1/P1P5/3N1KPP/R6R w - - 0 24', moves: 'd2b1 e5d3 f2g1 e8e1', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st123', fen: '1R5r/p1p1kPpp/3pp3/2p3B1/8/5Q2/P1r2PPP/4KB1R b K - 5 20', moves: 'e7d7 f1b5 c7c6 f3c6', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st124', fen: '2k1rb1r/ppp4p/1n4p1/3q4/1P1p2n1/3B4/P2Q1P1P/3RK3 w - - 1 21', moves: 'd2e2 f8b4 e1f1 d5h1', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st125', fen: '2r2rk1/pRN3pp/8/2b1n3/8/P2n1P1b/5P1P/5RK1 w - - 1 26', moves: 'f1d1 e5f3 g1h1 d3f2', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st126', fen: '2r3k1/p4p2/6p1/2K1P2p/4q3/P1B5/8/8 w - - 1 36', moves: 'c5b5 e4c4 b5a5 c8c5', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st127', fen: '3k1Q2/7p/3P1p2/p5B1/4P1n1/P1N2N2/1PP2PPP/R3K2R b KQ - 2 25', moves: 'd8d7 f8e7 d7c6 e7c7', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st128', fen: '3r1rk1/pp5p/2p1Q1p1/q3p3/P2bP3/1R4B1/5PPP/1R4K1 b - - 0 25', moves: 'g8h8 b3b7 f8f2 g3f2', rating: 1000, themes: 'advantage' },
{ id: 'st129', fen: '3r2k1/5pp1/2p4p/b3p2b/P1B1P3/7P/1Q3PP1/2q3K1 w - - 0 30', moves: 'b2c1 d8d1 c1d1 h5d1', rating: 1000, themes: 'fork check' },
{ id: 'st130', fen: '3r4/2k2pp1/1pp2B2/p3p2p/2P1P2P/2b2P2/P3K1P1/1R6 b - - 0 23', moves: 'a5a4 f6d8 c7d8 b1b6', rating: 1000, themes: 'check advantage' },
{ id: 'st131', fen: '4R3/2k5/5p2/1q6/8/K2r4/4p3/8 w - - 12 78', moves: 'a3a2 b5b3 a2a1 d3d1', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st132', fen: '4r3/8/1k1R4/4R3/1p1NB3/5P2/2P2K2/8 b - - 5 37', moves: 'b6c7 d4b5 c7c8 e5e8', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st133', fen: '6k1/5p1p/3p2p1/2p1p3/r1PbP3/1r1R1P1P/1P4P1/5K1R w - - 0 45', moves: 'd3b3 a4a1 f1e2 a1h1', rating: 1000, themes: 'check advantage' },
{ id: 'st134', fen: '6k1/6pp/8/3P4/2r2b2/4qB1P/RP2K1P1/7Q w - - 0 44', moves: 'e2f1 c4c1 f3d1 c1d1', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st135', fen: '7r/1p2n3/4b2k/p4p1P/4N3/P3P3/1PP1B3/2K2R2 b - - 0 39', moves: 'f5e4 f1f6 h6g7 f6e6', rating: 1000, themes: 'check advantage' },
{ id: 'st136', fen: '8/1pNRnk2/1p6/5p2/4n1p1/2P4p/P7/6K1 w - - 4 52', moves: 'c7d5 f7e6 d7e7 e6d5', rating: 1000, themes: 'advantage' },
{ id: 'st137', fen: '8/3B1pb1/5k2/1NPR2R1/4p2B/K3P3/5PP1/8 b - - 0 39', moves: 'g7h6 g5g8 h6g5 h4g5', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st138', fen: '8/4k1pp/p7/2p1b3/8/5pn1/r7/2K5 w - - 0 43', moves: 'c1d1 f3f2 d1c1 f2f1q', rating: 1000, themes: 'mateIn2 promotion' },
{ id: 'st139', fen: '8/4R3/7R/1Q1k4/7P/r7/6K1/8 b - - 2 62', moves: 'd5d4 h6d6 d4c3 e7c7', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st140', fen: 'b4k2/p1p3b1/p3PpQ1/P2pP3/8/2N5/1rPN1P1P/4R1K1 b - - 0 28', moves: 'f8g8 e5f6 b2c2 g6g7', rating: 1000, themes: 'mateIn2' },
{ id: 'st141', fen: 'r1b2b2/p3k1p1/1pPP4/8/5Q2/3B2N1/P4Pq1/R3K3 b Q - 0 24', moves: 'e7e8 d3g6 e8d8 f4f8', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st142', fen: 'r1b2r2/pp3p1p/3k4/b5Q1/2B1P3/2P5/PP3PPP/3R1K1R b - - 5 19', moves: 'd6c6 g5d5 c6b6 d5d6', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st143', fen: 'r1kn3r/p1p1Bqpp/2Q2p1P/3p4/3P4/3BPN1P/P4P2/1R3RK1 b - - 0 24', moves: 'd8c6 d3f5 f7e6 f5e6', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st144', fen: 'r1q1r1k1/pR3pp1/P3p2B/2p1P3/2NPp1Q1/8/2P2PPP/4R1K1 b - - 0 22', moves: 'g7g5 g4g5 g8h8 g5g7', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st145', fen: 'r2q1rk1/1p3pNp/p7/n7/1bp1nBb1/2P3Q1/P1P1BPPP/R3K2R w KQ - 0 17', moves: 'g3g4 b4c3 e1f1 c3g7', rating: 1000, themes: 'fork check' },
{ id: 'st146', fen: 'r2q2kr/2pb2p1/p3pn1p/3p4/P1nP4/1Pp4Q/2P1PPPP/1K1R1B1R w - - 0 17', moves: 'b3c4 d8b8 b1a2 b8b2', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st147', fen: 'r2r4/kpR3Q1/p7/3p4/3P3p/P1N4P/1PPN1P2/R5K1 b - - 0 34', moves: 'a7b8 c7b7 b8c8 g7c7', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st148', fen: 'r3k2r/ppNR2pp/2p1p1n1/2N5/P5P1/5P2/1PP4P/R5K1 b - - 2 22', moves: 'e8f8 c5e6 f8g8 d7g7', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st149', fen: 'r3kb1r/pp1qpppp/n2Nbn2/Q2p4/3P4/3BPNB1/PPP2PPP/R4RK1 b - - 10 14', moves: 'e7d6 d3b5 a8c8 b5d7', rating: 1000, themes: 'advantage' },
{ id: 'st150', fen: 'r4r2/1p1n2pp/1n2R3/p4k2/8/2NB1N2/PPP2PPP/2K1R3 b - - 2 19', moves: 'f5g4 h2h3 g4f4 c3e2', rating: 1000, themes: 'mateIn2 check' },
{ id: 'st151', fen: '4k3/1R2rp2/2p4p/8/6P1/p1P4P/5K2/8 w - - 0 70', moves: 'b7b3 e7a7', rating: 1020, themes: 'advantage' },
{ id: 'st152', fen: '8/8/4k1p1/8/4K3/8/8/8 w - - 2 68', moves: 'e4f4 e6f6', rating: 1020, themes: 'advantage' },
{ id: 'st153', fen: 'rn1q1rk1/ppp2ppp/3bb3/3N4/8/4PN2/PP3PPP/R2QKB1R w KQ - 1 11', moves: 'a1c1 e6d5', rating: 1020, themes: 'advantage' },
{ id: 'st154', fen: 'r2q1k1r/1ppN2p1/p1npp2p/2b5/4PB2/5N2/PPQ2PPP/R2R2K1 b - - 1 15', moves: 'd8d7 c2c5', rating: 1030, themes: 'sacrifice advantage' },
{ id: 'st155', fen: '1k4r1/1b3ppp/1N1Bp3/pB1p2R1/2q2P2/P1Q5/1PPK1P2/3R4 b - - 0 35', moves: 'c4c7 d6c7 b8a7 c3a5 b7a6 a5a6', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st156', fen: '1rbqkb1r/ppN2ppp/2np1n2/3Np3/4P3/4B3/PPP1BPPP/R2QK2R b KQk - 3 10', moves: 'e8d7 e2g4 f6g4 d1g4 f7f5 g4f5', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st157', fen: '2b3nr/ppN1kpb1/2np1p1p/4p3/4P3/Q4N2/PP2BPPP/3R1RK1 b - - 1 18', moves: 'e7f8 a3d6 g8e7 d6d8 c6d8 d1d8', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st158', fen: '2r3k1/7p/4Q1p1/p3N3/3P4/8/6PP/5R1K b - - 6 58', moves: 'g8g7 f1f7 g7h6 e6h3 h6g5 e5f3', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st159', fen: '3r4/1qpb1p1p/1p1pr1pk/p7/P1P1P1N1/2QR1P1P/1P2B1P1/R5K1 b - - 7 34', moves: 'h6h5 c3g7 g6g5 g7h7 e6h6 h7h6', rating: 1120, themes: 'mateIn3 long' },
{ id: 'st160', fen: '3r4/4Q3/3kpP2/1p5p/1P1P2r1/P4R2/2P3PP/R5K1 b - - 2 32', moves: 'd6c6 f3c3 c6d5 e7c5 d5e4 c5e5', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st161', fen: '5rk1/1pq1b3/2n4Q/3Bp1p1/p4p2/P1R2N1P/1PP2PP1/3R2K1 b - - 0 38', moves: 'f8f7 h6g6 g8h8 d5f7 c7b6 g6g8', rating: 1120, themes: 'mateIn3 fork check long' },
{ id: 'st162', fen: '5rk1/6pp/2n3p1/1p2p3/2b5/2P4P/1b2pK2/8 w - - 2 41', moves: 'f2g3 e2e1q g3h2 e1f2 h2h1 c4d5', rating: 1120, themes: 'mateIn3 promotion check long' },
{ id: 'st163', fen: '5rk1/p4ppp/3bbn2/2p4P/q1PpPp2/3P1N2/P3BPP1/nr4KR w - - 1 20', moves: 'g1h2 f6g4 h2h3 b1h1 f3h2 h1h2', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st164', fen: '6k1/p6p/6p1/5p2/1p6/8/2r5/4K3 w - - 2 41', moves: 'e1d1 b4b3 d1e1 b3b2 e1d1 b2b1q', rating: 1120, themes: 'mateIn3 promotion long' },
{ id: 'st165', fen: '8/1p3k1p/p1b5/8/4p2P/3r1pQ1/2r2K2/8 w - - 8 67', moves: 'f2f1 d3d1 g3e1 c6b5 f1g1 d1e1', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st166', fen: '8/2p3p1/1P1kbn2/7p/7P/4q3/2K5/8 w - - 3 55', moves: 'c2b2 e3d2 b2b1 c7b6 b1a1 d2a2', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st167', fen: '8/5KPk/5P2/8/8/8/8/8 b - - 2 72', moves: 'h7h6 g7g8q h6h5 g8g3 h5h6 g3g6', rating: 1120, themes: 'mateIn3 promotion long' },
{ id: 'st168', fen: '8/5P2/8/6P1/3Q4/4K2P/kP6/8 b - - 0 51', moves: 'a2b3 f7f8q b3c2 f8f1 c2b3 f1c4', rating: 1120, themes: 'mateIn3 promotion long' },
{ id: 'st169', fen: '8/6rp/8/k4q2/1p6/4K3/8/8 w - - 0 77', moves: 'e3e2 f5e4 e2d2 g7g2 d2d1 e4b1', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st170', fen: '8/8/1pk2K2/8/8/5q2/2p5/8 w - - 2 62', moves: 'f6g7 c2c1q g7g6 c1g1 g6h6 f3h3', rating: 1120, themes: 'mateIn3 promotion long' },
{ id: 'st171', fen: '8/8/2r5/PR1N4/6p1/4K1P1/1P1Q4/2k5 b - - 4 46', moves: 'c1b1 d5c3 c6c3 b2c3 b1a1 d2b2', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st172', fen: 'k6q/2p1p3/p3b3/2p2p2/1BP1p3/P5rr/1P3RN1/1R4K1 w - - 4 47', moves: 'f2f4 h3h1 g1f2 g3g2 f2g2 h8h2', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st173', fen: 'N1bk3r/1p1p1pp1/pQ1Bp1qp/8/6P1/2P5/PP3P1P/R3KB1R b KQ - 2 16', moves: 'd8e8 a8c7 e8d8 c7e6 d8e8 b6d8', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st174', fen: 'r1b5/pppk2p1/4N2p/3Q4/1b1P4/8/PPP2PPP/R3R1K1 b - - 0 25', moves: 'b4d6 e6c5 d7d8 d5g8 d6f8 g8f8', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st175', fen: 'r1bqr1k1/ppp2ppp/3b4/3p3P/3n2P1/3n4/PPP5/R1B2KR1 w - - 0 17', moves: 'c2d3 d8f6 c1f4 f6f4 f1g2 f4f3', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st176', fen: 'r1q2rk1/2ppb2p/npb1pP1p/p7/2PP4/P1NQ1NPP/1P3P2/RB3RK1 b - - 0 18', moves: 'f8f6 d3h7 g8f8 h7h8 f8f7 f3e5', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st177', fen: 'r3k2r/pp3ppp/1np5/5R2/P2P2P1/2NBP1b1/1P5q/R1BQ2K1 w kq - 3 18', moves: 'g1f1 h2h1 f1e2 h1g2 f5f2 g2f2', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st178', fen: 'r7/p3kp2/1pn5/7r/P7/2P2Knb/2P4P/RR3r2 w - - 0 29', moves: 'f3e3 h5e5 e3d3 a8d8 d3c4 h3e6', rating: 1120, themes: 'mateIn3 check long' },
{ id: 'st179', fen: '1R3b1r/5ppp/3p1k2/Q2B2B1/3N3P/3P1P2/P5P1/4K2R b K - 2 29', moves: 'f6e5 b8b4 f7f5 d4c6', rating: 1140, themes: 'mateIn2' },
{ id: 'st180', fen: '1r4k1/1p3ppp/p1p5/4B3/4P3/P2r2Pb/1P2qP1P/2R3K1 w - - 0 29', moves: 'e5c3 e2f3 c3e5 f3g2', rating: 1140, themes: 'mateIn2' },
{ id: 'st181', fen: '4Q3/2Q3p1/p5k1/8/8/8/P1P2PPP/6K1 b - - 2 36', moves: 'g6h6 c7e5 g7g5 e5h8', rating: 1140, themes: 'mateIn2' },
{ id: 'st182', fen: '4r1k1/1p3p1p/1P1p2p1/3b2B1/1p3P2/4P1P1/r4K1P/8 w - - 2 28', moves: 'f2f1 e8c8 h2h4 c8c1', rating: 1140, themes: 'mateIn2' },
{ id: 'st183', fen: '4rBk1/1pp2p2/p4R2/3PP2Q/7P/2N3K1/PPP3P1/R7 b - - 0 22', moves: 'e8e7 h5h6 e7e5 h6g7', rating: 1140, themes: 'mateIn2' },
{ id: 'st184', fen: '6k1/1p6/p4pp1/7p/4P1rP/8/r6K/8 w - - 2 74', moves: 'h2h3 a2g2 e4e5 g4g3', rating: 1140, themes: 'mateIn2' },
{ id: 'st185', fen: '7Q/6K1/8/3Q4/8/8/8/4k3 b - - 0 56', moves: 'e1f1 h8h2 f1e1 d5h1', rating: 1140, themes: 'mateIn2' },
{ id: 'st186', fen: '8/1R3pp1/4p1kr/8/4q3/6P1/5K2/8 w - - 0 47', moves: 'f2g1 e4f3 b7d7 h6h1', rating: 1140, themes: 'mateIn2' },
{ id: 'st187', fen: '8/p7/4k3/6p1/P1R3Pp/3K3P/QPP1R3/8 b - - 1 36', moves: 'e6f6 c4c7 a7a5 a2e6', rating: 1140, themes: 'mateIn2' },
{ id: 'st188', fen: 'r3kb1r/ppp2ppp/5q2/3p4/3K4/3P2P1/PPP2n1P/RNB2BR1 w kq - 1 12', moves: 'd4d5 b7b5 b1c3 a8d8', rating: 1140, themes: 'mateIn2' },
{ id: 'st189', fen: 'r3kb1r/ppp2ppp/3q1n2/4p1N1/3np1P1/P6P/1Pb1PPB1/1RBQK2R w Kkq - 0 11', moves: 'g5f7 d4f3 g2f3 d6d1', rating: 1150, themes: 'mateIn2 sacrifice check' },
{ id: 'st190', fen: '2r2rk1/1p3ppp/pQ2p3/3p3B/8/2p3B1/P4PPP/6K1 w - - 2 25', moves: 'b6b7 c3c2', rating: 1160, themes: 'advantage' },
{ id: 'st191', fen: '8/8/2p5/p1p1k2P/P2p4/1P3p1P/3K4/8 w - - 2 71', moves: 'h5h6 e5f6', rating: 1160, themes: 'advantage' },
{ id: 'st192', fen: 'r3r1k1/1b1q1pp1/p1nb3Q/1p1N4/4R3/P2B1N2/1P3PPP/2R3K1 b - - 0 25', moves: 'd6e5 e4e5', rating: 1170, themes: 'sacrifice advantage' },
{ id: 'st193', fen: '2b4r/Q2k1p1p/3p1p2/2pN4/2p5/8/PP2BPPP/R3K2R b KQ - 2 25', moves: 'd7e6 a7e7 e6d5 e2f3 d5d4 e7d6', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st194', fen: '2k4r/pp3pp1/2q4p/8/2r1RPP1/4p3/P4b1P/7K w - - 0 29', moves: 'h2h3 c4c1 h1g2 c6e4 g2h2 e4h1', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st195', fen: '2r1nrk1/5p2/1Q6/p3P1Np/8/8/PP3PPP/R5KR b - - 0 24', moves: 'c8a8 b6h6 e8f6 e5f6 a8b8 h6g7', rating: 1260, themes: 'mateIn3 long' },
{ id: 'st196', fen: '2r3kb/1R2p2p/1p4p1/3P4/P2P2bP/3q4/1KN5/8 w - - 0 36', moves: 'b2a1 h8d4 c2d4 d3a3 a1b1 c8c1', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st197', fen: '2r5/5Nkp/p4Qp1/2r1P3/1p4P1/7P/PqB4K/8 b - - 3 40', moves: 'g7f8 f7g5 f8g8 f6f7 g8h8 f7h7', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st198', fen: '3b2k1/6pp/p2pb3/4p1P1/8/2P1Bp2/3K1P2/1q6 w - - 0 43', moves: 'g5g6 b1b2 d2d3 e6f5 d3c4 b2b5', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st199', fen: '4k3/p6p/5p2/3P1B2/1p2P3/r5q1/3NK3/8 w - - 2 48', moves: 'd5d6 a3e3 e2d1 e3e1 d1c2 g3c3', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st200', fen: '4Q3/2p2pk1/3p2p1/3P3p/4PP1P/6P1/5q1K/8 w - - 5 45', moves: 'h2h3 f2g1 e8f7 g7f7 f4f5 g1h1', rating: 1260, themes: 'mateIn3 long' },
{ id: 'st201', fen: '6k1/2p5/p6B/P2bPp1p/1bp4P/8/1PK5/7r w - - 2 50', moves: 'b2b3 d5e4 c2b2 h1b1 b2a2 c4b3', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st202', fen: '8/1KR5/5pk1/1q6/4P3/2P5/P1P5/6q1 w - - 1 58', moves: 'b7c8 b5e8 c8b7 g1b1 b7a6 e8a4', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st203', fen: '8/1pR2pk1/p2P4/2N5/2n5/P3Kb2/8/3q4 w - - 8 53', moves: 'e3f2 d1e2 f2g3 e2g2 g3f4 g2g4', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st204', fen: '8/3k4/5QP1/8/4p3/4P1K1/8/8 b - - 2 58', moves: 'd7e8 f6f7 e8d8 g6g7 d8c8 g7g8q', rating: 1260, themes: 'mateIn3 promotion check long' },
{ id: 'st205', fen: '8/4Q1k1/5p2/4pB1p/1p6/5KP1/8/2r5 b - - 0 63', moves: 'g7g8 f5e6 g8h8 e7f8 h8h7 e6f5', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st206', fen: 'r1b2k1N/p1Np2pp/p2P1n2/2p5/Q7/4P3/PP4PP/R1B1K2R b KQ - 0 19', moves: 'a8b8 a4c4 f6d5 c4d5 c8b7 d5f7', rating: 1260, themes: 'mateIn3 long' },
{ id: 'st207', fen: 'r1b4r/p3k3/1p2p3/3NQ3/8/8/PPP1BPPP/R4RK1 b - - 0 24', moves: 'e7f7 e5f6 f7g8 d5e7 g8h7 f6g6', rating: 1260, themes: 'mateIn3 fork check long' },
{ id: 'st208', fen: 'r2q2k1/1ppr1pp1/4b2p/p3P3/P1B5/2n3Q1/2P2PPP/1R4KR w - - 0 23', moves: 'c4b5 d7d1 b1d1 d8d1 b5f1 c3e2', rating: 1260, themes: 'mateIn3 fork check long' },
{ id: 'st209', fen: 'r3k2r/ppp2ppp/3p1q2/2b5/4P3/3P3b/PPP2PPP/1R1K1nR1 w kq - 0 14', moves: 'g2h3 f6f3 d1c1 f3f4 c1d1 f4d2', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st210', fen: 'rnb4r/ppqp1Q2/2pk2p1/7p/2B1PB2/2N5/PPP2PPP/R3K2R b KQ - 3 13', moves: 'd6c5 f4e3 c5b4 a2a3 b4a5 b2b4', rating: 1260, themes: 'mateIn3 check long' },
{ id: 'st211', fen: '3rk2r/ppp2ppp/1q2b3/4P3/8/2QN3P/PPP2PP1/R2R2K1 w k - 10 23', moves: 'c3c5 d8d3 c5b6 d3d1', rating: 1290, themes: 'sacrifice advantage' },
{ id: 'st212', fen: '5rk1/pp1q1p2/2r1pbpp/3p1n2/3P4/PNNQP3/1PR2PPP/2R3K1 b - - 6 22', moves: 'b7b6 c3d5 e6d5 c2c6', rating: 1290, themes: 'sacrifice advantage' },
{ id: 'st213', fen: '2r2rk1/1p3ppp/1p1pn3/4pQ2/1P2P3/3P2P1/q4PBP/2R2RK1 w - - 0 19', moves: 'f2f4 c8c1', rating: 1300, themes: 'advantage' },
{ id: 'st214', fen: '6k1/1r1n1pp1/p2q3p/2p1p3/P1P1P3/3n1PR1/5P1P/1RQ3K1 w - - 2 36', moves: 'c1f1 b7b1', rating: 1300, themes: 'advantage' },
{ id: 'st215', fen: '6k1/1p3ppp/p1p5/P2p1b2/5P2/2Nq1r2/1P3BPP/7K w - - 0 38', moves: 'f2c5 d3f1 c5g1 f3f2 g2g3 f1g2', rating: 1400, themes: 'mateIn3 check long' },
{ id: 'st216', fen: '8/6pk/3p1B1p/5p2/1p6/2r1nK1r/8/8 w - - 0 56', moves: 'f3e2 c3c2 e2d3 g7f6 d3d4 c2d2', rating: 1400, themes: 'mateIn3 check long' },
{ id: 'st217', fen: '8/kp5p/7p/p6P/P5PK/3rp3/4Rr2/8 w - - 6 47', moves: 'e2e1 e3e2 e1e2 f2e2 g4g5 e2e4', rating: 1400, themes: 'mateIn3 long' },
{ id: 'st218', fen: '2k2b1r/B1rb1ppp/1P1p1n2/Q3p3/P3P3/5B2/2P2PPP/R2R2K1 b - - 0 29', moves: 'c7c2 b6b7 c8b7 a5b6 b7a8 b6b8', rating: 1410, themes: 'mateIn3 sacrifice check long' },
{ id: 'st219', fen: '4k3/Q5r1/2p4q/5p1P/2BP1P2/P3PK2/1r6/7R w - - 5 43', moves: 'a7a6 g7g3 f3g3 h6g7 g3f3 g7g4', rating: 1410, themes: 'mateIn3 sacrifice check long' },
{ id: 'st220', fen: '6kr/p4ppp/1p1p4/3p4/q5b1/P5P1/1Pr1n1P1/K3R2R w - - 2 44', moves: 'a1a2 e2c3 a2a1 a4a3 b2a3 c2a2', rating: 1410, themes: 'mateIn3 sacrifice check long' },
{ id: 'st221', fen: 'Q1k5/2p1q3/1p1p1rp1/8/1P2P2N/8/P5PP/1KR4R b - - 2 29', moves: 'c8d7 c1c7 d7c7 h1c1 c7d7 a8c8', rating: 1410, themes: 'mateIn3 sacrifice check long' },
{ id: 'st222', fen: '8/8/8/2kq1pp1/8/5p2/2K5/8 w - - 0 73', moves: 'c2b1 d5d2 b1a1 f3f2 a1b1 f2f1q', rating: 1540, themes: 'mateIn3 promotion long' },
{ id: 'st223', fen: 'r3k2r/pppq1ppp/5n2/b1p1p3/1PBnP1b1/P2P1N2/2P2PPP/R1BQ2KR w kq - 0 12', moves: 'b4a5 g4f3', rating: 1580, themes: 'advantage' },
];

View File

@ -0,0 +1,111 @@
// ChessPuzzles.js — Marcus's notebook: the puzzle ladder and the daily
// puzzle. The puzzles themselves live in ChessPuzzleData.js (generated by
// tools/genChessPuzzles.js from engine self-play).
//
// loadPuzzleState() / savePuzzleState(st)
// nextLadderPuzzle(st, rng) an unsolved puzzle near your rating
// dailyPuzzle(date) { puzzle, number } — the same for everyone that day
// ratePuzzle(st, puzzle, result) Elo-style update ('solved' | 'failed' | 'assisted')
// dailyStreak(st, date) consecutive days solved, ending today or yesterday
// themeLabel(t) 'fork' → 'Fork'
import { PUZZLES } from './ChessPuzzleData.js';
export { PUZZLES };
const KEY = 'chess-puzzles';
const DEFAULT = { rating: 1000, solved: {}, failed: {}, streak: 0, best: 0, played: 0, daily: {} };
export function loadPuzzleState() {
try {
const s = JSON.parse(localStorage.getItem(KEY) || '{}');
return { ...DEFAULT, ...s, solved: { ...(s.solved ?? {}) }, failed: { ...(s.failed ?? {}) }, daily: { ...(s.daily ?? {}) } };
} catch (_) { return { ...DEFAULT, solved: {}, failed: {}, daily: {} }; }
}
export function savePuzzleState(st) {
try { localStorage.setItem(KEY, JSON.stringify(st)); } catch (_) { /* private mode */ }
}
export function dateKey(d = new Date()) {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
function seeded(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
let DAILY_ORDER = null;
function dailyPool() {
const pool = PUZZLES.filter((p) => p.rating >= 800 && p.rating <= 1900);
return pool.length >= 20 ? pool : PUZZLES;
}
/** The day's puzzle: a fixed shuffle of the pool, one per calendar day. */
export function dailyPuzzle(date = new Date()) {
const pool = dailyPool();
if (!DAILY_ORDER || DAILY_ORDER.length !== pool.length) {
const rnd = seeded(20261201);
DAILY_ORDER = pool.map((_, i) => i);
for (let i = DAILY_ORDER.length - 1; i > 0; i--) {
const j = Math.floor(rnd() * (i + 1));
[DAILY_ORDER[i], DAILY_ORDER[j]] = [DAILY_ORDER[j], DAILY_ORDER[i]];
}
}
const day = Math.floor((Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(2026, 0, 1)) / 86400000);
const n = ((day % pool.length) + pool.length) % pool.length;
return { puzzle: pool[DAILY_ORDER[n]], number: day + 1, key: dateKey(date) };
}
export function nextLadderPuzzle(st, rng = Math.random, exclude = null) {
let pool = PUZZLES.filter((p) => !st.solved[p.id] && p.id !== exclude);
if (!pool.length) pool = PUZZLES.filter((p) => p.id !== exclude);
const target = st.rating + (rng() - 0.4) * 160;
const near = pool.slice().sort((a, b) => Math.abs(a.rating - target) - Math.abs(b.rating - target)).slice(0, 8);
return near[Math.floor(rng() * near.length)] ?? PUZZLES[0];
}
/** Update the ladder rating; returns the change. */
export function ratePuzzle(st, puzzle, result) {
if (result === 'assisted') { st.played++; st.streak = 0; return 0; }
const exp = 1 / (1 + Math.pow(10, (puzzle.rating - st.rating) / 400));
const k = st.played < 10 ? 48 : 28;
const score = result === 'solved' ? 1 : 0;
const d = Math.round(k * (score - exp));
st.rating = Math.max(400, Math.min(2800, st.rating + d));
st.played++;
if (result === 'solved') { st.solved[puzzle.id] = true; st.streak++; st.best = Math.max(st.best, st.streak); }
else { st.failed[puzzle.id] = true; st.streak = 0; }
return d;
}
export function dailyStreak(st, date = new Date()) {
let n = 0;
const d = new Date(date);
if (st.daily[dateKey(d)] !== 'solved') d.setDate(d.getDate() - 1);
while (st.daily[dateKey(d)] === 'solved') { n++; d.setDate(d.getDate() - 1); }
return n;
}
/** The last seven days, oldest first: [{ key, label, state }] (state: solved | failed | null). */
export function lastWeek(st, date = new Date()) {
const out = [];
for (let i = 6; i >= 0; i--) {
const d = new Date(date);
d.setDate(d.getDate() - i);
out.push({ key: dateKey(d), label: 'SMTWTFS'[d.getDay()], state: st.daily[dateKey(d)] ?? null, today: i === 0 });
}
return out;
}
const LABEL = {
mateIn1: 'Mate in 1', mateIn2: 'Mate in 2', mateIn3: 'Mate in 3', fork: 'Fork', hanging: 'Hanging piece',
sacrifice: 'Sacrifice', promotion: 'Promotion', advantage: 'Winning material', check: 'Check', long: 'Long line',
};
export const themeLabel = (t) => LABEL[t] ?? t;

View File

@ -0,0 +1,288 @@
// ChessSound.js — Web Audio synths for the Stone Tables. No audio files;
// silent without Web Audio or when muted.
//
// clack(scene, opts) a weighted piece set down on stone
// pick(scene) lifting a piece
// deny(scene) that piece can't go there
// capture(scene) the captured man knocked over and slid off
// castle(scene) king and rook: two quick clacks
// check(scene) a sharp warning ping
// promote(scene) a bright chime
// press(scene) the chess clock's plunger
// tick(scene) / beep(scene) / flag(scene) clock pressure
// chime(scene, good) puzzle solved / missed
// sting(scene, kind) 'win' · 'lose' · 'draw' — a little busker sax line
// Ambience wind in the leaves, far traffic, the fountain,
// pigeons, and now and then the busker by the gate
function ctxOf(scene) {
const sm = scene?.sound;
if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null;
return sm.context;
}
const noiseCache = new WeakMap();
function noise(ac) {
if (noiseCache.has(ac)) return noiseCache.get(ac);
const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ac, buf);
return buf;
}
function out(scene, ac, gain) {
const sm = scene.sound;
const node = sm.masterVolumeNode ?? sm.destination ?? null;
const g = ac.createGain();
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
g.connect(node ?? ac.destination);
return g;
}
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003, vib = 0, vibRate = 5.2 } = {}) {
const o = ac.createOscillator(); o.type = type;
o.frequency.setValueAtTime(f, t0);
if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d);
if (vib) {
const lfo = ac.createOscillator(); lfo.frequency.value = vibRate;
const lg = ac.createGain(); lg.gain.value = f * vib;
lfo.connect(lg); lg.connect(o.frequency); lfo.start(t0); lfo.stop(t0 + d + 0.05);
}
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(a, t0 + attack);
g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03);
}
function hiss(ac, dest, t0, f, vol = 1, d = 0.03, q = 3, type = 'bandpass') {
const n = ac.createBufferSource(); n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.value = f; bp.Q.value = q;
const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02);
}
const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } };
export function clack(scene, { vol = 0.13, heavy = false } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
// a weighted boxwood base on stone: a woody knock and a hard click
tone(ac, dest, t, heavy ? 150 : 190 + Math.random() * 20, { a: 0.9, d: 0.08, glide: 0.65 });
hiss(ac, dest, t, 2600 + Math.random() * 400, 0.9, 0.03, 2.5);
hiss(ac, dest, t + 0.002, 5200, 0.3, 0.012);
});
}
export function pick(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003;
hiss(ac, dest, t, 3400, 0.7, 0.018);
tone(ac, dest, t, 600, { a: 0.25, d: 0.035, glide: 1.3 });
});
}
export function deny(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.08), t = ac.currentTime + 0.003;
tone(ac, dest, t, 150, { a: 0.8, d: 0.12, glide: 0.7 });
hiss(ac, dest, t, 700, 0.5);
});
}
export function capture(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.12), t = ac.currentTime + 0.003;
// knocked over…
tone(ac, dest, t, 210, { a: 0.9, d: 0.07, glide: 0.6 });
hiss(ac, dest, t, 2200, 0.9, 0.03);
tone(ac, dest, t + 0.09, 170, { a: 0.5, d: 0.06, glide: 0.7 });
hiss(ac, dest, t + 0.09, 1800, 0.5, 0.025);
// …and slid off across the granite
hiss(ac, dest, t + 0.2, 1400, 0.25, 0.32, 0.8);
});
}
export function castle(scene) {
clack(scene, { vol: 0.12 });
scene?.time?.delayedCall?.(120, () => clack(scene, { vol: 0.1, heavy: true }));
}
export function check(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.01;
tone(ac, dest, t, 1318, { type: 'triangle', a: 0.6, d: 0.35 });
tone(ac, dest, t + 0.07, 1760, { type: 'triangle', a: 0.45, d: 0.45 });
});
}
export function promote(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.01;
[784, 988, 1175, 1568].forEach((f, i) => tone(ac, dest, t + i * 0.07, f, { type: 'triangle', a: 0.5, d: 0.6 }));
});
}
export function press(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.1), t = ac.currentTime + 0.003;
// the plunger going down, the other one popping up
hiss(ac, dest, t, 1500, 0.9, 0.025, 4);
tone(ac, dest, t, 320, { a: 0.6, d: 0.05, glide: 0.6 });
hiss(ac, dest, t + 0.04, 3200, 0.4, 0.015, 4);
});
}
export function tick(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.03), t = ac.currentTime + 0.003;
hiss(ac, dest, t, 4200, 0.8, 0.012, 6);
});
}
export function beep(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003;
tone(ac, dest, t, 1760, { type: 'square', a: 0.25, d: 0.09 });
});
}
export function flag(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003;
hiss(ac, dest, t, 2600, 0.8, 0.02, 4);
tone(ac, dest, t + 0.02, 880, { type: 'square', a: 0.25, d: 0.12 });
tone(ac, dest, t + 0.16, 880, { type: 'square', a: 0.25, d: 0.12 });
tone(ac, dest, t + 0.3, 660, { type: 'square', a: 0.25, d: 0.3 });
});
}
export function chime(scene, good = true) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.01;
if (good) [659, 784, 1047].forEach((f, i) => tone(ac, dest, t + i * 0.08, f, { type: 'triangle', a: 0.5, d: 0.5 }));
else [392, 330].forEach((f, i) => tone(ac, dest, t + i * 0.12, f, { type: 'triangle', a: 0.5, d: 0.35 }));
});
}
// a soft, breathy alto sax voice
function sax(ac, dest, t0, f, d, a = 0.5) {
const o = ac.createOscillator(); o.type = 'sawtooth';
o.frequency.setValueAtTime(f * 0.985, t0);
o.frequency.linearRampToValueAtTime(f, t0 + 0.06);
const lfo = ac.createOscillator(); lfo.frequency.value = 5.4;
const lg = ac.createGain(); lg.gain.setValueAtTime(0, t0); lg.gain.linearRampToValueAtTime(f * 0.012, t0 + d * 0.6);
lfo.connect(lg); lg.connect(o.frequency);
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.Q.value = 2;
lp.frequency.setValueAtTime(f * 2, t0); lp.frequency.linearRampToValueAtTime(f * 4.5, t0 + 0.08); lp.frequency.linearRampToValueAtTime(f * 2.5, t0 + d);
const g = ac.createGain();
g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(a, t0 + 0.05); g.gain.setValueAtTime(a * 0.85, t0 + d * 0.7); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
o.connect(lp); lp.connect(g); g.connect(dest);
o.start(t0); lfo.start(t0); o.stop(t0 + d + 0.05); lfo.stop(t0 + d + 0.05);
hiss(ac, dest, t0, f * 3, a * 0.08, d * 0.6, 1.2);
}
const NOTE = (n) => 440 * Math.pow(2, (n - 69) / 12);
export function sting(scene, kind = 'win') {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.06), t = ac.currentTime + 0.02;
const play = (notes) => { let at = 0; for (const [n, d] of notes) { if (n) sax(ac, dest, t + at, NOTE(n), d * 0.95); at += d; } };
if (kind === 'win') play([[65, 0.14], [68, 0.14], [70, 0.14], [72, 0.28], [70, 0.14], [72, 0.9]]);
else if (kind === 'lose') play([[67, 0.3], [65, 0.3], [63, 0.3], [62, 1.1]]);
else play([[65, 0.25], [67, 0.25], [65, 0.25], [64, 0.9]]);
});
}
const BUSKER = [
[[62, 0.4], [65, 0.2], [67, 0.2], [69, 0.6], [67, 0.2], [65, 0.6]],
[[69, 0.3], [72, 0.3], [70, 0.2], [69, 0.2], [67, 0.8]],
[[60, 0.2], [63, 0.2], [65, 0.2], [66, 0.2], [67, 0.6], [70, 0.4], [67, 0.8]],
[[74, 0.5], [72, 0.25], [69, 0.25], [67, 0.5], [65, 1.0]],
];
export class Ambience {
constructor(scene) { this.scene = scene; this.on = false; this.timer = null; this.beds = []; }
start() {
if (this.on) return;
this.on = true;
const ac = ctxOf(this.scene);
if (ac) {
safe(() => {
const bed = (lpF, hpF, vol, lfoRate, lfoAmt) => {
const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true;
const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = hpF;
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = lpF;
const g = out(this.scene, ac, 0);
g.gain.setValueAtTime(0, ac.currentTime);
g.gain.linearRampToValueAtTime(vol, ac.currentTime + 3);
const lfo = ac.createOscillator(); lfo.frequency.value = lfoRate;
const lg = ac.createGain(); lg.gain.value = lfoAmt;
lfo.connect(lg); lg.connect(g.gain);
src.connect(hp); hp.connect(lp); lp.connect(g);
src.start(); lfo.start();
this.beds.push({ src, lfo, g });
};
bed(900, 200, 0.012, 0.09, 0.008); // wind in the leaves, gusting
bed(220, 30, 0.02, 0.05, 0.006); // far-off traffic rumble
bed(7000, 2500, 0.004, 0.3, 0.0015); // the fountain's trickle
});
}
const event = () => {
this.timer = setTimeout(event, 5000 + Math.random() * 9000);
const a = ctxOf(this.scene); if (!a) return;
safe(() => {
const t = a.currentTime + 0.02;
const r = Math.random();
if (r < 0.45) {
// a pigeon: hoo-oo-oo
const dest = out(this.scene, a, 0.025);
const f = 300 + Math.random() * 60;
tone(a, dest, t, f, { a: 0.6, d: 0.28, glide: 0.82, attack: 0.05, vib: 0.03, vibRate: 18 });
tone(a, dest, t + 0.32, f * 1.05, { a: 0.5, d: 0.45, glide: 0.75, attack: 0.05, vib: 0.03, vibRate: 18 });
} else if (r < 0.7) {
// the busker by the gate, a long way off
const dest = out(this.scene, a, 0.018);
const lp = a.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 1400; lp.connect(dest);
let at = 0;
for (const [n, d] of BUSKER[Math.floor(Math.random() * BUSKER.length)]) { sax(a, lp, t + at, NOTE(n), d * 0.95, 0.4); at += d; }
} else if (r < 0.85) {
// a car horn two blocks over
const dest = out(this.scene, a, 0.008);
tone(a, dest, t, 392, { type: 'square', a: 0.5, d: 0.18 });
tone(a, dest, t, 494, { type: 'square', a: 0.4, d: 0.18 });
} else {
// wings flutter
const dest = out(this.scene, a, 0.02);
for (let i = 0; i < 8; i++) hiss(a, dest, t + i * 0.05, 900 + Math.random() * 400, 0.6, 0.04, 1.2);
}
});
};
this.timer = setTimeout(event, 2500);
}
stop() {
this.on = false;
clearTimeout(this.timer); this.timer = null;
for (const { src, lfo, g } of this.beds) {
safe(() => {
const ac = src.context;
g.gain.cancelScheduledValues(ac.currentTime);
g.gain.setValueAtTime(g.gain.value, ac.currentTime);
g.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6);
src.stop(ac.currentTime + 0.7); lfo.stop(ac.currentTime + 0.7);
});
}
this.beds = [];
}
setOn(on) { if (on) this.start(); else this.stop(); }
}

View File

@ -0,0 +1,157 @@
// ChessTalk.js — table talk at the Stone Tables. Two voices:
// marcusLine(kind, ctx) Marcus: thirty years hustling five-minute games
// in this park, now he mostly coaches. Cocky,
// warm, full of street wisdom.
// opponentLine(kind, tier) whoever's across the table — needling that
// depends on how good they are:
// 'rookie' (skill 1–2) · 'regular' (3) · 'shark' (4–5)
// Each returns a line or null (some moments only get a remark now and then).
const pick = (a) => a[Math.floor(Math.random() * a.length)];
const fill = (s, ctx = {}) => s.replace(/\{(\w+)\}/g, (_, k) => (ctx[k] ?? ''));
const MARCUS = {
welcome: [
'Pull up a bench. Sun\'s going down, lights are coming on. Best time to play.',
'Table nine\'s open. Set \'em up, I\'ll keep an eye on you.',
'Pigeons are out, the busker\'s warming up. Let\'s see your game.',
'Thirty years at these tables. Show me something I haven\'t seen.',
],
welcomeBack: [
'Board\'s right where you left it. Nobody touched a thing. Pigeons tried.',
'Back for the rest? Sit down, I kept your seat warm.',
],
newGame: ['Shake hands. Fresh board.', 'Next game. Clocks reset, pieces back.'],
chess960: [
'Fischer Random. Back rank\'s shuffled, so forget your openings and just play chess.',
'Nine-sixty. No book, no prep. Castling still works. King and rook land where they would in a normal game.',
],
opening: [
'Ah, the {name}.', 'The {name}. Good choice.', '{name}. I\'ve seen that one a thousand times on this table.',
'That\'s the {name}. Classic.',
],
humanCapture: ['There you go.', 'Clean.', 'Took that one off nice.', null, null, null],
humanBig: ['The {piece}! That\'s a big one.', 'Off goes the {piece}. That\'s the game swinging.', 'Grabbed the {piece}. Don\'t give it back.'],
humanLostPiece: ['Hm.', 'That one stung.', null, null, null],
humanLostBig: ['Your {piece}… ouch.', 'Lost the {piece}. Breathe. Still chess to play.', 'That {piece} was doing work. Regroup.'],
humanCheck: ['Check! Make \'em sweat.', null, null],
inCheck: ['You\'re in check. Deal with that first.', 'Check. King\'s gotta move, block, or take.', null],
humanCastle: ['Castled. King\'s safe, rooks connected. Textbook.', 'Smart. Tuck that king away.', null],
promote: ['New {piece}! Pawn went all the way.', 'Promotion. Now THAT\'s a comeback story.'],
aiPromote: ['They got a pawn through. Watch the new {piece}.', 'Uh-oh. Fresh {piece} on the board.'],
hint: ['Look at {move}. It {reason}.', 'If it were me: {move}. It {reason}.', 'Try {move}. It {reason}.'],
warn: [
'Hold up. Something\'s off with that one.',
'Wait. Look again. That costs you.',
'Easy. You\'re about to give something away.',
],
missed: [
'You had {move} there. It {reason}. Next time.',
'There was a shot: {move}. It {reason}.',
'Don\'t look now, but {move} {reason}.',
],
goodMove: ['That\'s the move!', 'Only move, and you found it. Nice.', 'See? You\'ve got eyes.'],
repetition: ['Same position again. One more time and it\'s a draw.'],
fifty: ['{n} more moves with no capture or pawn move and it\'s a draw.', 'Clock\'s ticking on the fifty-move rule. {n} to go.'],
drawOfferAI: ['They\'re offering a draw. Your call.'],
drawYouAccepted: ['Draw. Shake on it.', 'Half a point each. Fair enough.'],
drawDeclined: ['They want to play it out.', 'No dice. Back to work.'],
resign: ['Tipping your king? Respect. Next one.', 'No shame in it. Set \'em up again.'],
aiResigns: ['They\'re tipping the king. You earned that.', 'That\'s a resignation. Take the point.'],
undo: ['Take-back. Just this once… okay, maybe twice.', 'Rewind. Think it through this time.', null],
lowTime: ['Watch your clock!', 'Clock! Move, move!', 'Under twenty seconds. Trust your gut.'],
flagWin: ['Their flag fell! You win on time.', 'Time! You win on the clock. That counts.'],
flagLoss: ['Your flag fell. In the park, the clock is the clock.', 'Out of time. Gotta move faster in blitz.'],
premove: ['Premove in. Bold.', null, null],
win: [
'That\'s a win! Next round\'s on you.',
'Beautiful. The regulars are gonna hear about that one.',
'Well played. You might have a future at these tables.',
],
loss: [
'Shake it off. Every loss is a lesson.',
'They got you this time. Run it back?',
'Tough one. Look at the replay. It\'s all in there.',
],
draw: ['A draw. Honest result.', 'Neither side budged. Respect.'],
stalemate: ['Stalemate! No legal moves, but no check either. Draw.', 'Stalemate. So close and yet… a draw.'],
// puzzles
puzzleIntro: [
'Here\'s one from my notebook. {side} to move. Find the best line.',
'Sharpen up. {side} to play. There\'s something here.',
'Look close. {side} to move. It\'s not a quiet position.',
],
puzzleMate: ['Mate in {n}. Find it.', 'There\'s a mate in {n} here. Don\'t miss it.'],
puzzleGood: ['Good. Keep going.', 'That\'s it. Now finish it.', 'Right. What\'s next?'],
puzzleSolved: ['Solved! That\'s how you do it.', 'Nailed it.', 'Clean. Next one\'s harder.', 'See? You\'re learning.'],
puzzleWrong: ['Nope. Look again.', 'Not that one. What\'s the forcing move?', 'Close, but no. Checks, captures, threats: look at those first.'],
puzzleFailed: ['Here\'s how it goes. Study it.', 'That\'s the line. Remember it.'],
puzzleHint: ['Look at your {piece}.', 'The {piece} has a job to do.', 'Something with the {piece}.'],
dailyIntro: ['Today\'s puzzle. Same board for everybody in the park.', 'Daily puzzle. One shot at it, just like a real game.'],
dailySolved: ['Daily done! Come back tomorrow, keep the streak alive.', 'That\'s today\'s. Streak\'s growing.'],
dailyAlready: ['You already did today\'s. Here it is again, for practice.'],
};
const OPP = {
rookie: {
greet: ['Hi! I just learned how the horsey moves.', 'Be nice to me, okay?', 'I\'ve been watching videos! …Some of them.'],
capture: ['Ooh, I got one!', 'Is that allowed? Cool!', 'Yoink!'],
lostPiece: ['Hey! I needed that!', 'Wait, it could do that?', 'Oh no.'],
lostBig: ['My queen!! Can I take that back?', 'Nooo, not that one!'],
check: ['Check! …Right? That\'s check?', 'Is that check? I think that\'s check!'],
inCheck: ['Uh oh, where do I go?', 'Um. Hmm.'],
offerDraw: ['Wanna call it a draw? I\'m kinda confused.'],
acceptDraw: ['Okay! A draw is like a tie, right?'],
declineDraw: ['No way, I think I\'m winning!'],
win: ['I won?! I WON!', 'Wait, really? Checkmate? Yes!'],
lose: ['Aw. Good game though!', 'I\'ll get you next time!'],
draw: ['A tie! That\'s like half a win!'],
resign: [],
},
regular: {
greet: ['Good to see you. Let\'s have a game.', 'Clock or no clock, I\'m ready.', 'Same table as always. Let\'s play.'],
capture: ['I\'ll take that.', 'Thank you very much.', 'That\'s mine now.'],
lostPiece: ['Hm. Didn\'t see that.', 'Fair enough.', 'Okay, okay.'],
lostBig: ['Ugh. I left that hanging.', 'That\'s a big mistake on my part.'],
check: ['Check.', 'Check. Your move.'],
inCheck: ['Nice check. Let me think.', 'Hmm.'],
offerDraw: ['I think this one\'s heading for a draw. Shake on it?'],
acceptDraw: ['Sure. Good game.', 'Fair. Half a point each.'],
declineDraw: ['Let\'s keep playing.', 'Not yet. I like my position.'],
win: ['Good game. I had to work for that.', 'That\'s mate. Well fought.'],
lose: ['Well played. You got me.', 'Good game. I\'ll want a rematch.'],
draw: ['Draw. Good game.'],
resign: ['I\'m lost. I resign. Well played.', 'That\'s enough for me. You win.'],
},
shark: {
greet: ['Five bucks says you don\'t last thirty moves.', 'Sit down. Let\'s see if you\'re a player or a tourist.', 'I\'ve hustled this park for twenty years. Your move, friend.'],
capture: ['Free piece. Thank you.', 'You just donated that.', 'Mm. Delicious.'],
lostPiece: ['Calculated.', 'Take it. See what it costs you.', 'A loan. I\'ll collect.'],
lostBig: ['…Okay. Okay. That was good.', 'Lucky. Doesn\'t happen twice.'],
check: ['Check. Feel that?', 'Check. Getting warm in here?'],
inCheck: ['Cute.', 'That doesn\'t scare me.'],
offerDraw: ['It\'s dead level. Want to split it?'],
acceptDraw: ['Fine. Take your half.', 'Smart. Draw.'],
declineDraw: ['A draw? I\'m just getting started.', 'No. Play.'],
win: ['Pay up.', 'That\'s mate. Come back when you\'ve studied.', 'Told you. Thirty moves.'],
lose: ['…Rematch. Now.', 'Hm. You\'re not a tourist.', 'Respect. That doesn\'t happen often.'],
draw: ['Draw. You held on.'],
resign: ['That\'s lost. I resign. Don\'t get used to it.', 'Fine. You win this one.'],
},
};
export const tierOf = (skill) => (skill <= 2 ? 'rookie' : skill >= 4 ? 'shark' : 'regular');
export function marcusLine(kind, ctx = {}) {
const list = MARCUS[kind];
if (!list || !list.length) return null;
const l = pick(list);
return l ? fill(l, ctx) : null;
}
export function opponentLine(kind, tier = 'regular', ctx = {}) {
const list = OPP[tier]?.[kind] ?? OPP.regular[kind];
if (!list || !list.length) return null;
const l = pick(list);
return l ? fill(l, ctx) : null;
}

View File

@ -0,0 +1,11 @@
// ChessWorker.js — the module worker the Stone Tables' engine runs in.
// See ChessEngine.js for the message kinds.
import { handle } from './ChessEngine.js';
self.onmessage = (e) => {
const { id, kind, payload } = e.data ?? {};
let res = null, err = null;
try { res = handle(kind, payload); } catch (ex) { err = String(ex?.message ?? ex); }
self.postMessage({ id, res, err });
};

View File

@ -0,0 +1,95 @@
# Welcome to Chess
*By Marcus: thirty years at the stone tables in the park, five-minute games for five-dollar bills, coaching these days*
---
*Slides a pawn into place and taps the clock*
Sit down, sit down. Sun's going down and the string lights are coming on. That's the best time to play. I've seen every trick on this table, so let me show you how it works.
## The Goal
Each side has **sixteen pieces**: White and Black. You win by **checkmating** the enemy king: attacking it so it can't escape. You never actually take the king. Once it's trapped, the game's over.
## The Board
Sixty-four squares, eight by eight. **White always moves first.** Whatever colour you play sits at the bottom of the screen. Press **F** or the **Flip** button to turn the board around.
Every file has a letter (**a–h**, left to right from White's side), every rank has a number (**1–8**), and every square has a name, like **e4**. That's how moves get written on the score sheet.
## The Pieces
| Piece | Worth | How it moves |
|---|---|---|
| **Pawn** | 1 | One square straight ahead (two from its starting square). Captures one square **diagonally** forward. |
| **Knight** | 3 | An "L": two squares one way, one square sideways. It's the only piece that **jumps over** others. |
| **Bishop** | 3 | Any distance diagonally. Each bishop stays on its colour all game. |
| **Rook** | 5 | Any distance straight along a rank or file. |
| **Queen** | 9 | Any distance in any straight line or diagonal. Your heavy hitter. |
| **King** | Everything | One square in any direction. Never onto a square that's attacked. |
Capture by moving onto an enemy piece's square. It comes off the board and slides over to your side of the table.
## Check, Checkmate, Stalemate
- **Check:** your king is attacked. You *must* get out of it, by moving the king, blocking, or capturing the attacker. The board glows red under a king in check.
- **Checkmate:** in check, with no way out. Game over.
- **Stalemate:** **not** in check, but no legal move at all. That's a **draw**, even if one side is way ahead. Plenty of people have thrown away a win that way on this table.
## The Special Moves
- **Castling:** once per game, the king hops two squares toward a rook and the rook jumps over to the other side. You can't castle if the king or that rook has moved, if anything's in between, if you're in check, or if the king would pass through or land on an attacked square. To castle here, click the king and then its destination (or the rook).
- **En passant:** if an enemy pawn jumps two squares and lands right beside your pawn, you can capture it *as if* it had moved one, but only on your very next move.
- **Promotion:** a pawn that reaches the far rank becomes a queen, rook, bishop or knight. Your choice. Almost always the queen.
## Draws
Besides stalemate, the game is drawn when:
- the **same position comes up three times**,
- **fifty moves** go by on each side with no capture and no pawn move,
- neither side has **enough pieces left to checkmate** (a lone king, a king and one minor piece…),
- or both players **agree**. You can offer from the button, and so can they.
## How to Play Here
| Do this | And this happens |
|---|---|
| **Click a piece** | It lifts. Dots show where it can go, rings show captures. |
| **Click a marked square** | The move is played. |
| **Drag a piece** | Drop it on a marked square instead of clicking. |
| **Right-click** | Cancels a premove. |
| **Arrow keys + Enter** | Play with the keyboard. |
| **← →** | Step back through the game. Or click any move on the score sheet. Esc comes back. |
| **Undo (Z)** | Takes back your last move and their reply. Untimed games only. |
| **Hint (H)** | I'll point at a move and tell you why. |
| **Offer Draw / Resign** | Shake on it, or tip your king. |
**Premoves:** while your opponent is thinking, you can line up your next move. It goes in the moment it's your turn, if it's still legal. Handy in blitz.
## The Setup Card
- **Your colour:** White, Black, or flip a coin.
- **Clock:** Untimed, **Blitz 5+0**, **Rapid 10+5** (five seconds added every move) or **Classical 30+0**. The chess clock on the corner of the table shows both times, and the little red flag rises as your minute hand nears twelve. When your flag falls, you lose. *Unless* your opponent doesn't have enough left to mate, then it's a draw.
- **Starting position:** Standard, or **Chess960**, where the back rank is shuffled (bishops on opposite colours, king somewhere between the rooks). No opening theory, just chess. Castling still puts the king and rook on the same squares as in a normal game.
## Puzzles
My notebook's full of positions from real games played at these tables. Each one has **one best move**. The board shows your opponent's last move first, then it's your turn to find the punishment.
- **Puzzle Ladder:** solve to climb, miss to drop. Puzzles come in around your rating.
- **Daily Puzzle:** the same puzzle for everybody in the park that day. Get it on the first try to keep your **streak** alive.
Stuck? **Hint** points at the piece, press it again for the move, and **Solution** plays the whole line. They just don't count toward your rating.
## Marcus's Rules of Thumb
1. **Control the centre.** Pawns and pieces aimed at e4, d4, e5 and d5 run the game.
2. **Develop.** Knights and bishops out before you go hunting with the queen.
3. **Castle early.** A king in the middle is a target.
4. **Checks, captures, threats.** Before every move, look at those three, for both sides.
5. **Don't leave things hanging.** If I lean in and say *"hold up,"* you're about to give something away. You can turn that off in the menu once you're feeling brave.
6. **When you're ahead, trade pieces. When you're behind, make it messy.**
Now set 'em up. The pigeons are waiting.

198
tools/genChessPuzzles.js Normal file
View File

@ -0,0 +1,198 @@
#!/usr/bin/env node
// genChessPuzzles.js — mines original tactics puzzles for Chess ("The Stone
// Tables") from engine self-play. Nothing is copied from a puzzle site:
// games are played by ChessAI at mixed skills from book openings, and every
// position is screened for a tactic with ONE clearly best first move.
//
// mate puzzles the solver has a unique mate in 1–3 (alternative final
// mating moves are accepted by the game, so only the
// first and middle moves must be unique)
// material puzzles the best move wins ≥ 2 pawns more than any other, from
// a roughly level position, and isn't a simple recapture
//
// Each puzzle is stored Lichess-style: `fen` is the position BEFORE the
// opponent's last move, `moves` = [their move, your move, reply, your move…]
// in UCI, so the board can show how the chance arose.
//
// Usage:
// node tools/genChessPuzzles.js --seed 1 --games 60 --out /tmp/p1.json (one worker)
// node tools/genChessPuzzles.js --seed 11 --games 40 --mates --out /tmp/m11.json (mates only)
// node tools/genChessPuzzles.js --merge /tmp/p*.json (→ ChessPuzzleData.js)
import { writeFileSync, readFileSync } from 'node:fs';
import * as L from '../src/games/chess/ChessLogic.js';
import * as AI from '../src/games/chess/ChessAI.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
const arg = (k, d) => { const i = process.argv.indexOf(k); return i >= 0 ? process.argv[i + 1] : d; };
const MATE_B = AI.MATE - 512;
const MATES_ONLY = process.argv.includes('--mates'); // a mate-hunting run: mates even in won positions
function solverLine(pos, firstM, firstScore) {
// returns [uci…] for solver/opponent alternation, or null if not unique
const p = pos.clone();
const line = [L.toUci(p, firstM)];
const mate = AI.mateIn(firstScore);
L.makeMove(p, firstM);
let solverMoves = 1;
const want = mate > 0 ? mate : 3;
while (solverMoves < want) {
if (!L.hasLegalMove(p)) break;
// opponent's best defence
const rep = AI.bestMove(p, { ms: 500 });
if (!rep.m) break;
const pr = p.clone();
L.makeMove(p, rep.m);
if (!L.hasLegalMove(p)) { // defence can't leave us with nothing to do
return mate > 0 ? null : line;
}
const ranked = AI.analyze(p, { ms: 900, margin: 400 });
const best = ranked[0], second = ranked[1];
if (mate > 0) {
const left = want - solverMoves;
const mi = AI.mateIn(best.score);
if (mi <= 0 || mi > left) return null;
// the final move may have alternatives (any mate is accepted); earlier ones must be unique
if (left > 1 && second && AI.mateIn(second.score) > 0 && AI.mateIn(second.score) <= left) return null;
line.push(L.toUci(pr, rep.m), L.toUci(p, best.m));
L.makeMove(p, best.m);
solverMoves++;
continue;
}
// material: carry on only while the follow-up is clearly unique and cashes in
const fl = L.mFlags(best.m);
const unique = !second || best.score - second.score >= 200;
if (!unique || !(fl & L.F_CAP)) break;
line.push(L.toUci(pr, rep.m), L.toUci(p, best.m));
L.makeMove(p, best.m);
solverMoves++;
}
if (mate > 0 && solverMoves < want) return null;
void firstScore;
return line;
}
function themesOf(pos, line, mate) {
const t = [];
if (mate) t.push(`mateIn${mate}`);
const p = pos.clone();
const m = L.fromUci(p, line[0]);
const fl = L.mFlags(m);
if (L.mPromo(m) || line.some((u) => u.length === 5)) t.push('promotion');
const s = AI.see(p, m);
const victim = (fl & L.F_CAP) ? (fl & L.F_EP ? L.P : p.b[L.mTo(m)] & 7) : 0;
if (fl & L.F_CAP && s >= L.VALUE[victim] - 20 && victim >= L.N) t.push('hanging');
if (s < -50 && !mate) t.push('sacrifice');
if (s < -50 && mate) t.push('sacrifice');
const idea = AI.describeIdea(p, m, 300);
if (idea.startsWith('forks')) t.push('fork');
L.makeMove(p, m);
if (p.inCheck()) t.push('check');
if (!mate && !t.includes('fork') && !t.includes('hanging')) t.push('advantage');
if (line.length >= 5) t.push('long');
return t;
}
function depthToFind(pos, m) {
for (let d = 1; d <= 9; d++) {
const r = AI.bestMove(pos, { ms: 3000, depth: d });
if (r.m === m && (d >= 2 || AI.mateIn(r.score) === 1)) return d;
}
return 10;
}
function worker() {
const seed = +arg('--seed', 1), games = +arg('--games', 40), out = arg('--out', `/tmp/chess-puzzles-${seed}.json`);
const rng = mulberry32(seed * 7919);
const found = [];
const seen = new Set();
for (let gi = 0; gi < games; gi++) {
const g = new L.Chess();
const sw = 1 + Math.floor(rng() * 4), sb = 1 + Math.floor(rng() * 4);
let perGame = 0, cool = 0;
while (!g.status() && g.ply < 160) {
// screen positions after the opening, before each side moves
if (cool > 0) cool--;
else if (g.ply >= 12 && perGame < 2 && g.history.length) {
const pos = g.pos;
const quick = AI.bestMove(pos, { ms: 60 });
const prevM = g.history[g.history.length - 1];
const lastWasCapture = !!prevM.captured;
const qm = AI.mateIn(quick.score);
const promising = (qm > 0 && qm <= 3) || (!MATES_ONLY && quick.score >= 220);
if (promising) {
// level-ish before? (the side to move shouldn't already be miles ahead)
const ranked = AI.analyze(pos, { ms: 1200, margin: 400 });
const best = ranked[0], second = ranked[1];
const mate = AI.mateIn(best.score);
let take = false;
const fl = L.mFlags(best.m);
const recapture = lastWasCapture && (fl & L.F_CAP) && L.to64(L.mTo(best.m)) === prevM.to;
if (recapture) take = false;
else if (mate > 0 && mate <= 3) {
const altMate = second && AI.mateIn(second.score) > 0 && AI.mateIn(second.score) <= mate;
take = !altMate && (MATES_ONLY || !second || second.score <= 900);
} else if (!MATES_ONLY && best.score >= 220 && best.score < MATE_B && second && best.score - second.score >= 220 && second.score <= 120 && second.score >= -350) {
take = true;
}
if (take) {
const line = solverLine(pos, best.m, best.score);
const key = L.toFen(pos, { clocks: false });
if (line && !seen.has(key)) {
seen.add(key);
// the position before the opponent's last move
const before = g.after(g.ply - 1);
const themes = themesOf(pos, line, mate > 0 ? mate : 0);
const d = depthToFind(pos, best.m);
const solverN = Math.ceil(line.length / 2);
let rating = 600 + d * 140 + (solverN - 1) * 120 + (themes.includes('sacrifice') ? 150 : 0) - (themes.includes('hanging') ? 150 : 0);
if (mate === 1) rating = 600 + d * 60;
rating = Math.max(500, Math.min(2300, Math.round(rating / 10) * 10));
found.push({ fen: before.fen(), moves: [prevM.uci, ...line], rating, themes, mate: mate > 0 ? mate : 0 });
perGame++;
cool = 12;
process.stderr.write(`[seed ${seed}] game ${gi} ply ${g.ply}: ${themes.join(',')} r${rating} (${found.length})\n`);
}
}
}
}
const c = AI.chooseMove(g, g.turn === 'w' ? sw : sb, { ms: 80, rng });
if (!c) break;
g.move(c.m);
}
writeFileSync(out, JSON.stringify(found));
}
writeFileSync(out, JSON.stringify(found));
}
function merge(files) {
const all = [];
const seen = new Set();
for (const f of files) {
for (const p of JSON.parse(readFileSync(f, 'utf8'))) {
const k = p.fen.split(' ').slice(0, 4).join(' ') + p.moves[0];
if (seen.has(k)) continue;
seen.add(k);
all.push(p);
}
}
all.sort((a, b) => a.rating - b.rating || a.fen.localeCompare(b.fen));
all.forEach((p, i) => { p.id = `st${String(i + 1).padStart(3, '0')}`; });
const body = all.map((p) => ` { id: '${p.id}', fen: '${p.fen}', moves: '${p.moves.join(' ')}', rating: ${p.rating}, themes: '${p.themes.join(' ')}' },`).join('\n');
const src = `// ChessPuzzleData.js — GENERATED by tools/genChessPuzzles.js. Do not edit by hand.
// ${all.length} original tactics mined from engine self-play at the Stone Tables.
// fen: the position before the opponent's last move; moves (UCI): that move,
// then the solution (yours, their reply, yours…). Sorted by rating.
export const PUZZLES = [
${body}
];
`;
writeFileSync(new URL('../src/games/chess/ChessPuzzleData.js', import.meta.url), src);
const byTheme = {};
for (const p of all) for (const t of p.themes) byTheme[t] = (byTheme[t] ?? 0) + 1;
console.log(`${all.length} puzzles`, byTheme);
}
if (process.argv.includes('--merge')) merge(process.argv.slice(process.argv.indexOf('--merge') + 1));
else worker();

365
tools/verifyChess.js Normal file
View File

@ -0,0 +1,365 @@
#!/usr/bin/env node
// verifyChess.js — headless checks for Chess ("The Stone Tables"):
// • perft: the standard start, Kiwipete and the usual tricky positions,
// plus Chess960 positions — node counts must match the published numbers
// • rules on hand-built positions: castling rights, en passant (incl. the
// pinned-pawn case), promotion, stalemate, insufficient material,
// threefold repetition, the fifty-move rule, flag-fall material
// • Chess960: all 960 starts are valid; castling lands king/rook correctly
// • notation: SAN / UCI round-trip for every legal move of many positions,
// FEN round-trip, PGN export
// • the opening book: every line + name is legal; names resolve
// • puzzles: every puzzle replays legally; the first solving move is the
// engine's clear choice; daily puzzle is deterministic; ladder + rating
// • the engine: each skill moves legally inside its budget; finds mates;
// SEE and describeIdea sanity; the worker message handler
// • self-play soak: games end cleanly; skill ladder (mirrored colours)
// • layout: HUD rectangles on screen and clear of the board and each other
// Usage: node tools/verifyChess.js [--quick]
import * as L from '../src/games/chess/ChessLogic.js';
import * as AI from '../src/games/chess/ChessAI.js';
import { checkBook, openingName, bookMoves } from '../src/games/chess/ChessBook.js';
import { PUZZLES, dailyPuzzle, nextLadderPuzzle, ratePuzzle, dailyStreak, dateKey } from '../src/games/chess/ChessPuzzles.js';
import { handle } from '../src/games/chess/ChessEngine.js';
import * as LY from '../src/games/chess/ChessLayout.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.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 sans = (g) => g.moves().map((m) => m.san).sort();
// ── perft ────────────────────────────────────────────────────────────────────
section('perft');
const PERFT = [
['start', L.START_FEN, [20, 400, 8902, 197281, 4865609]],
['kiwipete', 'r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1', [48, 2039, 97862, 4085603]],
['pos3', '8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1', [14, 191, 2812, 43238, 674624]],
['pos4', 'r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1', [6, 264, 9467, 422333]],
['pos5', 'rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8', [44, 1486, 62379, 2103487]],
['960-a', 'bqnb1rkr/pp3ppp/3ppn2/2p5/5P2/P2P4/NPP1P1PP/BQ1BNRKR w HFhf - 2 9', [21, 528, 12189, 326672]],
['960-b', '2nnrbkr/p1qppppp/8/1ppb4/6PP/3PP3/PPP2P2/BQNNRBKR w HEhe - 1 9', [21, 807, 18002, 667366]],
['960-c', 'b1q1rrkb/pppppppp/3nn3/8/P7/1PPP4/4PPPP/BQNNRKRB w GE - 1 9', [20, 479, 10471, 273318]],
];
for (const [name, fen, exp] of PERFT) {
const p = L.fromFen(fen);
const depth = QUICK ? Math.min(exp.length, 3) : exp.length;
for (let d = 1; d <= depth; d++) {
const n = L.perft(p, d);
ok(`perft ${name} d${d}`, n === exp[d - 1], `${n} ≠ ${exp[d - 1]}`);
}
ok(`${name}: hash restored after perft`, (() => { const q = L.fromFen(fen); return q.lo === p.lo && q.hi === p.hi; })());
}
// ── rules ────────────────────────────────────────────────────────────────────
section('rules');
{
const g = new L.Chess();
ok('20 opening moves', g.moves().length === 20);
ok('white to move', g.turn === 'w');
g.move('e4');
ok('turn passes', g.turn === 'b' && g.ply === 1);
ok('history has SAN', g.history[0].san === 'e4' && g.history[0].uci === 'e2e4');
ok('no phantom en passant after e4', g.fen().split(' ')[3] === '-', g.fen());
}
{
// castling both ways, and losing the right
const g = new L.Chess('r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R w KQkq - 0 1');
ok('O-O and O-O-O available', sans(g).includes('O-O') && sans(g).includes('O-O-O'), sans(g).join(' '));
g.move('O-O');
ok('king g1, rook f1', g.at(62)?.type === 'k' && g.at(61)?.type === 'r' && !g.at(63), g.fen());
ok('white castling rights gone', !/[KQ]/.test(g.fen().split(' ')[2]), g.fen());
const h = new L.Chess('r3k2r/1pppppp1/8/8/8/8/1PPPPPP1/R3K2R w KQkq - 0 1');
h.move('Ra2'); h.move('Rb8');
ok('rook move drops only that side', h.fen().split(' ')[2] === 'Kk', h.fen());
}
{
// can't castle out of / through check
const g = new L.Chess('4k3/8/8/8/8/8/5r2/R3K2R w KQ - 0 1');
ok('no O-O through an attacked f1', !sans(g).includes('O-O'), sans(g).join(' '));
ok('O-O-O still fine', sans(g).includes('O-O-O'));
const c = new L.Chess('4k3/8/8/8/8/8/4r3/R3K2R w KQ - 0 1');
ok('no castling out of check', !sans(c).some((s) => s.startsWith('O-O')));
}
{
// en passant, including the horizontally pinned case
const g = new L.Chess('4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 2');
ok('exd6 e.p. legal', sans(g).includes('exd6'), sans(g).join(' '));
g.move('exd6');
ok('captured pawn removed', !g.at(L.to64(L.parseSq('d5'))));
const pin = new L.Chess('8/8/8/K2pP2r/8/8/8/7k w - d6 0 2');
ok('pinned e.p. illegal', !sans(pin).includes('exd6'), sans(pin).join(' '));
}
{
// promotion options
const g = new L.Chess('8/4P3/8/8/8/8/8/k6K w - - 0 1');
const pr = g.moves().filter((m) => m.promo);
ok('four promotions', pr.length === 4 && ['q', 'r', 'b', 'n'].every((t) => pr.some((m) => m.promo === t)));
g.move('e8=Q');
ok('queen on e8', g.at(4)?.type === 'q');
ok('promotion SAN', g.history[0].san === 'e8=Q');
}
{
const st = new L.Chess('7k/5Q2/6K1/8/8/8/8/8 b - - 0 1');
ok('stalemate', st.status()?.reason === 'stalemate' && st.status()?.winner === 'draw');
const cm = new L.Chess('7k/6Q1/6K1/8/8/8/8/8 b - - 0 1');
ok('checkmate', cm.status()?.reason === 'checkmate' && cm.status()?.winner === 'w');
ok('K v K draw', new L.Chess('8/8/8/4k3/8/8/8/4K3 w - - 0 1').status()?.reason === 'material');
ok('K+N v K draw', new L.Chess('8/8/8/4k3/8/8/8/3NK3 w - - 0 1').status()?.reason === 'material');
ok('K+B v K+B same colour draw', new L.Chess('8/8/3b4/4k3/8/8/8/2B1K3 w - - 0 1').status()?.reason === 'material');
ok('K+B v K+B opposite colours plays on', !new L.Chess('8/8/2b5/4k3/8/8/8/2B1K3 w - - 0 1').status());
ok('K+R v K plays on', !new L.Chess('8/8/8/4k3/8/8/8/R3K3 w - - 0 1').status());
}
{
// threefold repetition by shuffling knights
const g = new L.Chess();
for (const m of ['Nf3', 'Nf6', 'Ng1', 'Ng8', 'Nf3', 'Nf6', 'Ng1']) g.move(m);
ok('not yet a draw', !g.status());
g.move('Ng8');
ok('threefold', g.status()?.reason === 'repetition', JSON.stringify(g.status()));
const f = new L.Chess('8/8/8/4k3/8/8/8/R3K3 w - - 99 80');
f.move('Ra2');
ok('fifty-move rule', f.status()?.reason === 'fifty');
}
{
ok('canMate: lone king can\'t', !L.canMate(L.fromFen('8/8/8/4k3/8/8/8/R3K3 w - - 0 1'), L.BLACK));
ok('canMate: rook can', L.canMate(L.fromFen('8/8/8/4k3/8/8/8/R3K3 w - - 0 1'), L.WHITE));
}
// ── Chess960 ─────────────────────────────────────────────────────────────────
section('chess960');
{
let good = 0;
const seen = new Set();
for (let n = 0; n < 960; n++) {
const r = L.back960(n).join('');
seen.add(r);
const bi = [...r].map((c, i) => (c === 'b' ? i : -1)).filter((i) => i >= 0);
const ro = [...r].map((c, i) => (c === 'r' ? i : -1)).filter((i) => i >= 0);
const k = r.indexOf('k');
if (bi.length === 2 && (bi[0] + bi[1]) % 2 === 1 && ro.length === 2 && ro[0] < k && k < ro[1] && r.split('q').length === 2 && r.split('n').length === 3) good++;
if (n % 97 === 0) {
const g = new L.Chess(L.fen960(n));
if (g.moves().length < 18) good -= 1000;
}
}
ok('all 960 back ranks valid', good === 960, `${good}`);
ok('960 distinct', seen.size === 960);
ok('518 is the standard setup', L.back960(518).join('') === 'rnbqkbnr');
}
{
// king already on g1 castles by moving only the rook
const g = new L.Chess('1r4kr/8/8/8/8/8/8/1R4KR w HBhb - 0 1');
const c = g.moves().find((m) => m.castle === 'K');
ok('960 O-O with king on g1 exists', !!c, sans(g).join(' '));
g.move(c);
ok('960 O-O: king g1, rook f1', g.at(62)?.type === 'k' && g.at(61)?.type === 'r' && !g.at(63), g.fen());
const q = new L.Chess('1r4kr/8/8/8/8/8/8/1R4KR w HBhb - 0 1');
const cq = q.moves().find((m) => m.castle === 'Q');
ok('960 O-O-O exists', !!cq);
q.move(cq);
ok('960 O-O-O: king c1, rook d1', q.at(58)?.type === 'k' && q.at(59)?.type === 'r' && !q.at(57) && !q.at(62), q.fen());
ok('960 castling uci is king→rook', cq.uci === 'g1b1', cq.uci);
// rook blocked by the king's path
const b = new L.Chess('8/8/8/8/8/8/8/RK4k1 w A - 0 1');
ok('960 queen-side with rook a1, king b1', b.moves().some((m) => m.castle === 'Q'), sans(b).join(' '));
}
// ── notation ─────────────────────────────────────────────────────────────────
section('notation');
{
const rng = mulberry32(7);
let bad = 0, checked = 0;
for (let gi = 0; gi < (QUICK ? 6 : 20); gi++) {
const g = new L.Chess(gi % 4 === 3 ? L.fen960(Math.floor(rng() * 960)) : L.START_FEN);
for (let ply = 0; ply < 80 && !g.status(); ply++) {
const ms = g.moves();
for (const m of ms) {
checked++;
if (L.fromSan(g.pos, m.san) !== m.m) bad++;
if (L.fromUci(g.pos, m.uci) !== m.m) bad++;
}
const fen = g.fen();
if (L.toFen(L.fromFen(fen)) !== fen) bad += 1000;
g.move(ms[Math.floor(rng() * ms.length)]);
}
}
ok(`SAN/UCI/FEN round-trip (${checked} moves)`, bad === 0, `${bad} bad`);
const g = new L.Chess('7k/8/8/8/8/8/8/R3R2K w - - 0 1');
ok('rook disambiguation', sans(g).includes('Rad1') && sans(g).includes('Red1'), sans(g).join(' '));
const n = new L.Chess('7k/8/8/8/8/2N5/8/2N4K w - - 0 1');
ok('knight rank disambiguation', sans(n).includes('N1e2') && sans(n).includes('N3e2'), sans(n).join(' '));
const mate = new L.Chess('6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1');
ok('mate suffix', mate.moves().some((m) => m.san === 'Rd8#'));
const pg = new L.Chess();
['e4', 'e5', 'Nf3', 'Nc6'].forEach((m) => pg.move(m));
const pgn = pg.pgn({ white: 'A', black: 'B' });
ok('PGN movetext', pgn.includes('1. e4 e5 2. Nf3 Nc6 *'), pgn);
const p960 = new L.Chess(L.fen960(100));
p960.move(p960.moves()[0]);
ok('PGN 960 tags', /Variant "Chess960"/.test(p960.pgn()) && /FEN "/.test(p960.pgn()));
}
// ── opening book ─────────────────────────────────────────────────────────────
section('book');
{
const bad = checkBook().filter((x) => !x.ok);
ok('all book lines and names legal', bad.length === 0, bad.map((b) => `${b.line} @${b.at}`).join('; '));
const g = new L.Chess();
ok('book has replies at the start', bookMoves(g).length >= 4);
['e4', 'c5', 'Nf3', 'd6', 'd4', 'cxd4', 'Nxd4', 'Nf6', 'Nc3', 'a6'].forEach((m) => g.move(m));
ok('Najdorf named', openingName(g) === 'Sicilian, Najdorf', openingName(g));
const t = new L.Chess();
['c4', 'e6', 'Nc3', 'Nf6', 'd4', 'Bb4'].forEach((m) => t.move(m));
ok('transposition finds Nimzo', openingName(t) === 'Nimzo-Indian Defence', openingName(t));
ok('960 has no book', bookMoves(new L.Chess(L.fen960(3))).length === 0);
}
// ── puzzles ──────────────────────────────────────────────────────────────────
section('puzzles');
{
ok('puzzles exist', PUZZLES.length >= 40, `${PUZZLES.length}`);
ok('ids unique', new Set(PUZZLES.map((p) => p.id)).size === PUZZLES.length);
let bad = [];
for (const p of PUZZLES) {
const g = new L.Chess(p.fen);
const moves = p.moves.split(' ');
for (const u of moves) { if (!g.move(u)) { bad.push(`${p.id} ${u}`); break; } }
if (moves.length < 2 || moves.length % 2 !== 0) bad.push(`${p.id} length ${moves.length}`);
}
ok('every puzzle replays legally', bad.length === 0, bad.slice(0, 5).join('; '));
const sample = QUICK ? PUZZLES.filter((_, i) => i % 6 === 0) : PUZZLES;
const notBest = [];
for (const p of sample) {
const g = new L.Chess(p.fen);
const moves = p.moves.split(' ');
g.move(moves[0]);
const r = AI.analyze(g.pos, { ms: 700, margin: 300 });
const top = L.toUci(g.pos, r[0].m);
const mateTie = AI.mateIn(r[0].score) > 0 && r[1] && AI.mateIn(r[1].score) === AI.mateIn(r[0].score);
if (top !== moves[1] && !mateTie) notBest.push(`${p.id} engine ${top} vs ${moves[1]}`);
}
ok(`solution is the engine's choice (${sample.length})`, notBest.length <= Math.ceil(sample.length * 0.05), notBest.slice(0, 5).join('; '));
const d1 = dailyPuzzle(new Date(2026, 11, 1)), d1b = dailyPuzzle(new Date(2026, 11, 1)), d2 = dailyPuzzle(new Date(2026, 11, 2));
ok('daily deterministic', d1.puzzle.id === d1b.puzzle.id && d1.number === d1b.number);
ok('daily changes day to day', d1.puzzle.id !== d2.puzzle.id && d2.number === d1.number + 1);
ok('date key', dateKey(new Date(2026, 0, 5)) === '2026-01-05');
const st = { rating: 1000, solved: {}, failed: {}, streak: 0, best: 0, played: 0, daily: {} };
const pz = nextLadderPuzzle(st, mulberry32(3));
ok('ladder picks near rating', Math.abs(pz.rating - 1000) <= 600, `${pz.rating}`);
const up = ratePuzzle(st, { id: 'x', rating: 1200 }, 'solved');
ok('solving a harder puzzle gains', up > 20 && st.rating === 1000 + up && st.streak === 1);
const down = ratePuzzle(st, { id: 'y', rating: 800 }, 'failed');
ok('failing an easier puzzle loses', down < -20 && st.streak === 0);
ok('assisted is neutral', ratePuzzle(st, { id: 'z', rating: 900 }, 'assisted') === 0);
st.daily = { '2026-11-29': 'solved', '2026-11-30': 'solved', '2026-12-01': 'solved' };
ok('daily streak', dailyStreak(st, new Date(2026, 11, 1)) === 3 && dailyStreak(st, new Date(2026, 11, 2)) === 3);
}
// ── engine ───────────────────────────────────────────────────────────────────
section('engine');
{
const g = new L.Chess('r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq - 4 4');
for (let s = 1; s <= 5; s++) {
const t0 = Date.now();
const r = AI.chooseMove(g, s, { rng: mulberry32(s) });
const dt = Date.now() - t0;
ok(`skill ${s} legal`, g.moves().some((m) => m.m === r.m));
ok(`skill ${s} in budget`, dt <= AI.PROFILES[s].ms * 1.6 + 150, `${dt}ms`);
}
const mate1 = AI.bestMove(g.pos, { ms: 500 });
ok('finds Qxf7#', L.toUci(g.pos, mate1.m) === 'h5f7' && AI.mateIn(mate1.score) === 1);
const m2 = L.fromFen('r2qkb1r/pp2nppp/3p4/2pNN1B1/2BnP3/3P4/PPP2PPP/R2bK2R w KQkq - 1 1');
const r2 = AI.bestMove(m2, { ms: 1500 });
ok('finds mate in 2', AI.mateIn(r2.score) === 2, `${L.toUci(m2, r2.m)} ${r2.score}`);
const hang = L.fromFen('4k3/8/8/3q4/8/8/3R4/4K3 w - - 0 1');
const rh = AI.bestMove(hang, { ms: 400 });
ok('takes a hanging queen', L.toUci(hang, rh.m) === 'd2d5');
const s1 = L.fromFen('4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1');
ok('SEE: pawn takes defended-nothing pawn = +100', AI.see(s1, L.fromUci(s1, 'e4d5')) === 100);
const s2 = L.fromFen('4k3/2p5/3p4/8/8/8/3Q4/4K3 w - - 0 1');
ok('SEE: queen takes defended pawn < 0', AI.see(s2, L.fromUci(s2, 'd2d6')) < 0);
const fk = L.fromFen('r3k3/8/8/1N6/8/8/8/4K3 w - - 0 1');
ok('describeIdea: knight fork', /forks the king and rook/.test(AI.describeIdea(fk, L.fromUci(fk, 'b5c7'), 400)), AI.describeIdea(fk, L.fromUci(fk, 'b5c7'), 400));
// the worker message handler
const rec = { startFen: L.START_FEN, moves: ['e2e4', 'e7e5'] };
const mv = handle('move', { rec, skill: 3, ms: 150 });
ok('handle move', mv && typeof mv.uci === 'string' && mv.uci.length >= 4);
const best = handle('best', { rec, ms: 150 });
ok('handle best', best && best.san && best.idea && Array.isArray(best.pv));
const an = handle('analyze', { rec, ms: 150, margin: 200 });
ok('handle analyze', Array.isArray(an) && an.length === 29 && an[0].idea, `${an?.length}`);
const ev = handle('eval', { rec: { startFen: '7k/6Q1/6K1/8/8/8/8/8 b - - 0 1', moves: [] }, ms: 50 });
ok('handle eval on mate', ev.cp > 20000);
ok('clock budget shrinks with time', AI.clockBudget(5, 10000, 0, 40) < AI.clockBudget(5, 300000, 0, 40));
ok('draw decision sane', AI.drawDecision(-300, 60, 4).accept && !AI.drawDecision(300, 60, 4).accept && !AI.drawDecision(-300, 4, 4).accept);
ok('resign only when lost', AI.shouldResign([-1200, -1300, -1500], 4) && !AI.shouldResign([-1200, -200, -1500], 4) && !AI.shouldResign([-1200, -1300, -1500], 2));
}
// ── self-play ────────────────────────────────────────────────────────────────
section('self-play');
function play(sw, sb, ms, rng, fen = L.START_FEN) {
const g = new L.Chess(fen);
while (!g.status() && g.ply < 220) {
const c = AI.chooseMove(g, g.turn === 'w' ? sw : sb, { ms, rng });
if (!c || !g.move(c.m)) return { bad: true, g };
let kings = 0;
for (const p of g.board64()) if (p?.type === 'k') kings++;
if (kings !== 2) return { bad: true, g };
}
return { g, r: g.result ?? { winner: 'draw', reason: 'cap' } };
}
{
const rng = mulberry32(11);
let bad = 0;
const N = QUICK ? 3 : 8;
for (let i = 0; i < N; i++) {
const r = play(1 + (i % 5), 1 + ((i * 3) % 5), 40, rng, i % 3 === 2 ? L.fen960(Math.floor(rng() * 960)) : L.START_FEN);
if (r.bad) bad++;
}
ok(`soak: ${N} games clean`, bad === 0);
}
{
const rng = mulberry32(5);
let hi = 0, lo = 0;
const N = QUICK ? 2 : 6;
for (let i = 0; i < N; i++) {
const strongWhite = i % 2 === 0;
const r = play(strongWhite ? 5 : 2, strongWhite ? 2 : 5, 80, rng);
const w = r.r?.winner;
if ((w === 'w' && strongWhite) || (w === 'b' && !strongWhite)) hi++;
else if (w && w !== 'draw') lo++;
}
ok(`skill 5 beats skill 2 (${hi}-${lo})`, hi > lo);
}
// ── layout ───────────────────────────────────────────────────────────────────
section('layout');
{
const R = LY.HUD_RECTS();
const board = LY.BOARD_RECT;
const hit = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
for (const [k, r] of Object.entries(R)) {
ok(`${k} on screen`, r.x >= 0 && r.y >= 0 && r.x + r.w <= LY.W && r.y + r.h <= LY.H, JSON.stringify(r));
ok(`${k} clear of the board`, !hit(r, board), JSON.stringify(r));
}
const keys = Object.keys(R);
for (let i = 0; i < keys.length; i++) {
for (let j = i + 1; j < keys.length; j++) {
ok(`${keys[i]} / ${keys[j]} don't overlap`, !hit(R[keys[i]], R[keys[j]]));
}
}
ok('square mapping round-trips', [0, 7, 36, 63].every((s) => {
const p = LY.squareXY(s, false), q = LY.squareXY(s, true);
return LY.sqAt(p.x, p.y, false) === s && LY.sqAt(q.x, q.y, true) === s;
}));
ok('a8 top-left when White is at the bottom', LY.squareXY(0, false).x < LY.BCX && LY.squareXY(0, false).y < LY.BCY);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);