Rework backgammon into a full seaside kafeneio experience

- Rewrite the AI with a skill 1–5 ladder: pip-equivalent evaluator with shot counting, primes and blot risk; exact one-sided bear-off table (54k positions) for race play; optional 2-ply lookahead at skill 5; cube double/take decisions with Crawford and dead-cube handling
- Add a procedural art set (olive-wood tavli case, bone/walnut checkers, dice cups, doubling cube, tea glass, komboloi) and a layout module driving every screen rect, including a mirrored home-board option
- Rebuild the scene around the new modules: persistent checker registry with stable ids and animated moves, 3D dice throws planned from real rolls, leather cup shake/throw, HUD plates/slate/ledger, pause menu, cube offer slip, end screen with stats and pip-race chart, Web Audio clacks/slams and looping sea waves
- Expand the rules engine: opening roll, maximum-dice/higher-die enforcement, bar entry and dancing, overshoot bear-off, gammons/backgammons, Jacoby, matches to N with Crawford, per-player stats and move log
- Enable opponent skill selection for backgammon in the opponent scene
- Rewrite the tutorial to match the new table, controls and cube/match features
- Add tools/verifyBackgammon.js covering rules, turn generation vs brute force, bear-off table sanity, AI soak and layout bounds
This commit is contained in:
Brian Fertig 2026-11-25 12:44:57 -07:00
parent 98b4dfdb8e
commit 43ca22b63a
No known key found for this signature in database
16 changed files with 4826 additions and 1138 deletions

View File

@ -27,7 +27,7 @@ export function getGame(slug) {
} }
// Built-in catalog so the menu has something to show. // Built-in catalog so the menu has something to show.
registerGame({ slug: 'backgammon', name: 'Backgammon', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 0, defaultPlayfield: 'dark' }); registerGame({ slug: 'backgammon', name: 'Backgammon', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 0 });
registerGame({ slug: 'parchisi', name: 'Parchisi', category: 'tabletop', minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, hasTutorial: true, iconFrame: 1 }); registerGame({ slug: 'parchisi', name: 'Parchisi', category: 'tabletop', minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, hasTutorial: true, iconFrame: 1 });
registerGame({ slug: 'blackjack', name: 'Blackjack', category: 'casino', cardGame: true, minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 2 }); registerGame({ slug: 'blackjack', name: 'Blackjack', category: 'casino', cardGame: true, minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 2 });
registerGame({ slug: 'holdem', name: "Texas Hold 'Em", category: 'casino', cardGame: true, minPlayers: 2, maxPlayers: 8, minOpponents: 3, maxOpponents: 7, iconFrame: 3 }); registerGame({ slug: 'holdem', name: "Texas Hold 'Em", category: 'casino', cardGame: true, minPlayers: 2, maxPlayers: 8, minOpponents: 3, maxOpponents: 7, iconFrame: 3 });

View File

@ -1,95 +1,427 @@
// BackgammonAI.js — skill 1–5 checker play and cube decisions. Phaser-free.
//
// Everything works on mover-perspective Int8Array boards (see BackgammonLogic).
// evaluate(me, op) = P(me wins) with op ON ROLL, i.e. right after I moved.
//
// race (no contact) bear-off table when both sides are home (exact
// one-sided expected rolls + variance), else a pip race
// formula with the on-roll edge.
// contact a pip-equivalent score: pips, made points (by value),
// primes in front of trapped checkers, shot-counted blot
// risk (how many of the 36 rolls hit each blot, honouring
// blocks, combination paths and the bar), checkers on the
// bar against the closed home board, stacking — then a
// logistic to a probability.
//
// Skill ladder
// 5 full evaluator + 2-ply: the top 8 candidates are re-scored against every
// one of the opponent's 21 rolls and their best reply (≈61% vs skill 4)
// 4 full evaluator, 1-ply
// 3 simple evaluator (no shot counting, pip-only races)
// 2 simple evaluator + noise
// 1 simple evaluator + heavy noise + occasional loose plays
import { import {
cloneState, getValidMoves, applyMove, computePipCount, WHITE, BLACK, other, boardsFor, enumerateTurns, toIdx, pipP, canBearOffP,
} from './BackgammonLogic.js'; } from './BackgammonLogic.js';
import * as Bearoff from './BackgammonBearoff.js';
// Returns an ordered array of moves for the AI (Black) to execute. // ── tuning ───────────────────────────────────────────────────────────────────
export function chooseMoves(state) { export const TUNE = {
const sequences = generateSequences(state); K: 13, // pip-equivalent score → logistic scale
if (sequences.length === 0) return []; onRoll: 5, // pips the side on roll is worth in contact
prime: [0, 0, 1, 3, 6.5, 11, 17],
trappedBonus: 0.3,
blotBase: 4,
blotPerPip: 0.55,
blotHome: 1.6, // extra cost per opponent home point made
oppBlotW: 0.22,
barBase: 3,
barHome: 0.95,
stack: 1.1,
backStuck: 0.45,
pvScale: 1,
primeScale: 1,
};
// value of a made point by its own point index (0 = ace … 23 = 24-point)
const PV = [
1.0, 2.2, 3.4, 5.0, 7.0, 6.0, // home board: 1…6
5.5, 3.6, 2.4, 2.0, 1.6, 1.4, // outer: bar(7) … 12
1.6, 1.0, 1.0, 1.0, 1.0, 1.2, // 13 (mid) … 18
3.0, 4.2, 3.6, 2.6, 1.6, 1.0, // anchors in the opponent's home: 19…24
];
const PV_SIMPLE = [
0.5, 1.5, 2.5, 3.5, 4.5, 4.0,
3.5, 2.5, 1.5, 1.0, 1.0, 1.0,
1.0, 0.5, 0.5, 0.5, 0.5, 0.5,
1.5, 2.0, 2.0, 1.5, 1.0, 0.5,
];
const ROLLS = [];
for (let a = 1; a <= 6; a++) for (let b = a; b <= 6; b++) ROLLS.push({ a, b, w: a === b ? 1 : 2 });
export { ROLLS };
const logistic = (x) => 1 / (1 + Math.exp(-x));
const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
// ── helpers ──────────────────────────────────────────────────────────────────
export function hasContact(me, op) {
let mMax = -1, oMax = -1;
for (let i = 24; i >= 0; i--) if (me[i]) { mMax = i; break; }
for (let i = 24; i >= 0; i--) if (op[i]) { oMax = i; break; }
if (mMax < 0 || oMax < 0) return false;
return mMax + oMax >= 24;
}
function homeClosed(b) {
let n = 0;
for (let i = 0; i < 6; i++) if (b[i] >= 2) n++;
return n;
}
// Shots the opponent (op, on roll) has at my blots. Returns
// { union, per: Float32Array(24) } in roll counts out of 36.
const perBuf = new Float32Array(24);
const hitBuf = new Uint8Array(24);
export function shotInfo(me, op) {
const per = perBuf; per.fill(0);
let blotCount = 0;
for (let i = 0; i < 24; i++) if (me[i] === 1) blotCount++;
if (!blotCount) return { union: 0, per, blots: 0 };
// op-perspective helpers: target t (op index) holds my blot when me[23 − t] === 1
const open = (t) => t >= 0 && t <= 23 && me[23 - t] < 2;
const blotAt = (t) => t >= 0 && t <= 23 && me[23 - t] === 1;
const srcs = [];
for (let j = 0; j < 24; j++) if (op[j]) srcs.push(j);
const bar = op[24];
let union = 0;
for (const { a, b, w } of ROLLS) {
hitBuf.fill(0);
let any = false;
const mark = (t) => { if (blotAt(t)) { hitBuf[23 - t] = 1; any = true; } };
if (a === b) {
const d = a;
if (bar > 0) {
const e = 24 - d;
if (open(e)) {
mark(e);
const left = 4 - Math.min(bar, 4);
// the entered checker (and, with one on the bar, any other checker) continues
let t = e;
for (let k = 0; k < left; k++) { t -= d; if (!open(t)) break; mark(t); }
if (bar === 1) {
for (const j of srcs) {
let tt = j;
for (let k = 0; k < 3; k++) { tt -= d; if (!open(tt)) break; mark(tt); }
}
}
}
} else {
for (const j of srcs) {
let t = j;
for (let k = 0; k < 4; k++) { t -= d; if (!open(t)) break; mark(t); }
}
}
} else if (bar >= 2) {
if (open(24 - a)) mark(24 - a);
if (open(24 - b)) mark(24 - b);
} else if (bar === 1) {
for (const [x, y] of [[a, b], [b, a]]) {
const e = 24 - x;
if (!open(e)) continue;
mark(e);
if (open(e - y)) mark(e - y);
for (const j of srcs) if (open(j - y)) mark(j - y);
}
} else {
for (const j of srcs) {
mark(j - a); mark(j - b);
if ((open(j - a) || open(j - b)) && open(j - a - b)) mark(j - a - b);
}
}
if (any) {
union += w;
for (let i = 0; i < 24; i++) if (hitBuf[i]) per[i] += w;
}
}
return { union, per, blots: blotCount };
}
function primeValue(me, op) {
let best = 0;
let i = 0;
while (i < 24) {
if (me[i] < 2) { i++; continue; }
let j = i;
while (j + 1 < 24 && me[j + 1] >= 2) j++;
const L = j - i + 1;
if (L >= 2) {
// op checkers behind the run: my coordinate k = 23 − jop < i (bar counts)
let trapped = op[24];
for (let jo = 0; jo < 24; jo++) if (op[jo] && 23 - jo < i) trapped += op[jo];
const base = TUNE.prime[Math.min(6, L)];
const v = trapped ? base * (1 + TUNE.trappedBonus * Math.min(3, trapped)) : base * 0.25;
if (v > best) best = v;
}
i = j + 1;
}
return best;
}
// ── race ─────────────────────────────────────────────────────────────────────
const MU = 8.1667;
function raceProb(me, op, useTable) {
if (me[25] === 15) return 1;
if (op[25] === 15) return 0;
if (useTable && canBearOffP(me) && canBearOffP(op) && Bearoff.ready()) {
const p = Bearoff.raceWinProb([me[0], me[1], me[2], me[3], me[4], me[5]], [op[0], op[1], op[2], op[3], op[4], op[5]]);
if (p !== null) return p;
}
const pm = pipP(me), po = pipP(op);
const waste = (b) => (b[0] * 1.6 + b[1] * 0.9 + b[2] * 0.4) * (canBearOffP(b) ? 1 : 0.4);
const em = (pm + waste(me)) / MU, eo = (po + waste(op)) / MU;
const sd = Math.max(0.4, Math.sqrt(0.0339 * (pm + po)));
return Bearoff.phi((-0.5 - (em - eo)) / sd);
}
// ── evaluation ───────────────────────────────────────────────────────────────
// mode: 'full' | 'simple'
export function evaluate(me, op, mode = 'full') {
if (me[25] === 15) return 1;
if (op[25] === 15) return 0;
if (!hasContact(me, op)) return raceProb(me, op, mode === 'full');
return logistic(contactScore(me, op, mode) / TUNE.K);
}
export function contactScore(me, op, mode = 'full') {
const T = TUNE;
let s = pipP(op) - pipP(me) - T.onRoll;
const pv = mode === 'full' ? PV : PV_SIMPLE;
const pvk = mode === 'full' ? T.pvScale : 1;
for (let i = 0; i < 24; i++) {
if (me[i] >= 2) s += pv[i] * pvk;
if (op[i] >= 2) s -= pv[i] * pvk;
}
const hcMe = homeClosed(me), hcOp = homeClosed(op);
s += T.barBase * op[24] + T.barHome * hcMe * hcMe * op[24] * 0.5;
s -= T.barBase * me[24] + T.barHome * hcOp * hcOp * me[24] * 0.5;
if (mode === 'full') {
s += (primeValue(me, op) - primeValue(op, me)) * T.primeScale;
// my blots, op to roll: real risk
const sh = shotInfo(me, op);
if (sh.blots) {
let risk = 0, maxR = 0;
for (let i = 0; i < 24; i++) {
if (!sh.per[i]) continue;
const cost = T.blotBase + T.blotPerPip * (24 - i) + T.blotHome * hcOp;
const r = (sh.per[i] / 36) * cost;
risk += r;
if (r > maxR) maxR = r;
}
s -= maxR + (risk - maxR) * 0.45;
}
// op's blots: they move first, so worth much less
const sh2 = shotInfo(op, me);
if (sh2.blots) {
let risk = 0;
for (let i = 0; i < 24; i++) {
if (!sh2.per[i]) continue;
risk += (sh2.per[i] / 36) * (T.blotBase + T.blotPerPip * (24 - i) + T.blotHome * hcMe);
}
s += risk * T.oppBlotW;
}
for (let i = 0; i < 24; i++) {
if (me[i] > 4) s -= (me[i] - 4) * T.stack;
if (op[i] > 4) s += (op[i] - 4) * T.stack;
}
// back checkers versus a strong home board
let backMe = me[24], backOp = op[24];
for (let i = 18; i < 24; i++) { backMe += me[i]; backOp += op[i]; }
s -= backMe * hcOp * T.backStuck * 0.4;
s += backOp * hcMe * T.backStuck * 0.4;
} else {
// simple: flat blot penalty where an enemy checker is behind it
let opBack = -1;
for (let j = 24; j >= 0; j--) if (op[j]) { opBack = 23 - j; break; } // lowest my-coordinate of an op checker
for (let i = 0; i < 24; i++) if (me[i] === 1 && opBack < i) s -= i < 6 ? 5 : 3;
let meBack = -1;
for (let j = 24; j >= 0; j--) if (me[j]) { meBack = 23 - j; break; }
for (let i = 0; i < 24; i++) if (op[i] === 1 && meBack < i) s += 1;
}
return s;
}
// P(player wins) when it is player's turn to roll (before rolling).
export function winProbOnRoll(state, player, mode = 'full') {
const { me, op } = boardsFor(state, player);
return 1 - evaluate(op, me, mode);
}
// ── turn choice ──────────────────────────────────────────────────────────────
export const SKILL = {
1: { mode: 'simple', noise: 0.09, loose: 0.25 },
2: { mode: 'simple', noise: 0.045, loose: 0.08 },
3: { mode: 'simple', noise: 0.012, loose: 0 },
4: { mode: 'full', noise: 0, loose: 0 },
5: { mode: 'full', noise: 0, loose: 0, ply2: 8, budgetMs: 450 },
};
function gauss(rng) {
const u = Math.max(1e-9, rng()), v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function seqToMoves(player, seq) {
return seq.map(([from, to, die, hit]) => ({
from: from === 24 ? 'bar' : toIdx(player, from),
to: to < 0 ? 'off' : toIdx(player, to),
dieUsed: die,
hit: !!hit,
}));
}
// 2-ply: average over the opponent's 21 rolls of (1 − their best reply).
function twoPly(meB, opB) {
if (!hasContact(meB, opB)) return evaluate(meB, opB, 'full');
let sum = 0;
for (const { a, b, w } of ROLLS) {
const dice = a === b ? [a, a, a, a] : [a, b];
const replies = enumerateTurns(opB, meB, dice);
let best = 0;
for (const r of replies) {
const v = evaluate(r.me, r.op, 'full');
if (v > best) best = v;
if (best > 0.999) break;
}
sum += w * (1 - best);
}
return sum / 36;
}
/** Choose a full turn. Returns { moves, value, turns } (value = P(win) after it). */
export function chooseTurn(state, skill = 3, rng = Math.random) {
const player = state.currentPlayer;
const { me, op } = boardsFor(state, player);
const turns = enumerateTurns(me, op, state.movesLeft);
if (turns.length <= 1) {
const t = turns[0];
return { moves: t ? seqToMoves(player, t.seq) : [], value: t ? evaluate(t.me, t.op) : 0.5, turns: turns.length };
}
const prof = SKILL[Math.max(1, Math.min(5, Math.round(skill)))];
const scored = turns.map((t) => ({ t, v: evaluate(t.me, t.op, prof.mode) }));
if (prof.noise) for (const x of scored) x.v += gauss(rng) * prof.noise;
scored.sort((x, y) => y.v - x.v);
let pick = scored[0];
if (prof.loose && rng() < prof.loose) {
const k = Math.max(1, Math.ceil(scored.length * 0.5));
pick = scored[Math.floor(rng() * k)];
}
if (prof.ply2 && scored.length > 1) {
// candidates in 1-ply order; stop early past the time budget (slow devices)
const top = scored.slice(0, prof.ply2);
const t0 = now();
let best = null; let best = null;
let bestScore = -Infinity; for (const x of top) {
for (const seq of sequences) { const v = twoPly(x.t.me, x.t.op);
const score = evaluateState(seq.finalState, 'black'); if (!best || v > best.v2) best = { ...x, v2: v };
if (score > bestScore) { bestScore = score; best = seq; } if (prof.budgetMs && now() - t0 > prof.budgetMs) break;
} }
return best ? best.moves : []; pick = best;
}
return { moves: seqToMoves(player, pick.t.seq), value: pick.v2 ?? pick.v, turns: turns.length };
} }
function generateSequences(state, depth = 0) { // ── cube ─────────────────────────────────────────────────────────────────────
if (depth > 6) return [{ moves: [], finalState: state }]; const CUBE_NOISE = { 1: 0.16, 2: 0.1, 3: 0.06, 4: 0.03, 5: 0 };
const validMoves = getValidMoves(state); function postCrawfordTrailer(match, player) {
if (validMoves.length === 0 || state.movesLeft.length === 0) { if (!match || match.length <= 0 || !match.hadCrawford || match.crawford) return false;
return [{ moves: [], finalState: state }]; const opp = other(player);
return match.score[opp] === match.length - 1 && match.score[player] < match.length - 1;
} }
const results = []; /** Should `player` (on roll, cube available) offer a double? */
const seenBoards = new Set(); export function shouldDouble(state, player, skill = 3, match = null, rng = Math.random) {
if (!state.cubeEnabled) return false;
for (const move of validMoves) { if (match && match.length > 0) {
const next = applyMove(state, move); if (match.score[player] + state.cube.value >= match.length) return false; // dead cube: winning already wins the match
// If applyMove ended the turn, no further moves are possible in this sequence if (postCrawfordTrailer(match, player)) return true;
const finished = next.currentPlayer !== state.currentPlayer || next.phase !== 'move'; if (match.score[other(player)] === match.length - 1) return false;
if (finished) {
results.push({ moves: [move], finalState: next });
} else {
const subSeqs = generateSequences(next, depth + 1);
for (const sub of subSeqs) {
const key = boardHash(sub.finalState);
if (!seenBoards.has(key)) {
seenBoards.add(key);
results.push({ moves: [move, ...sub.moves], finalState: sub.finalState });
}
}
} }
const mode = skill >= 4 ? 'full' : 'simple';
const p = winProbOnRoll(state, player, mode) + gauss(rng) * (CUBE_NOISE[skill] ?? 0.05);
if (skill <= 1 && rng() < 0.5) return false; // a timid beginner
// too good to double: play on for the gammon (gammons count unless Jacoby with a centred cube)
const gammonsCount = !(state.jacoby && state.cube.value === 1);
const tooGood = p > 0.9 && gammonsCount && gammonThreat(state, player);
return p >= 0.7 && !tooGood;
} }
return results.length > 0 ? results : [{ moves: [], finalState: state }]; /** Should `taker` accept a double offered by the other player? */
export function shouldTake(state, taker, skill = 3, match = null, rng = Math.random) {
const offerer = other(taker);
if (match && match.length > 0) {
if (match.score[offerer] + state.cube.value >= match.length) return true; // dropping loses the match anyway
if (postCrawfordTrailer(match, offerer)) return true;
}
const mode = skill >= 4 ? 'full' : 'simple';
const pTaker = 1 - winProbOnRoll(state, offerer, mode) + gauss(rng) * (CUBE_NOISE[skill] ?? 0.05);
return pTaker >= 0.25;
} }
function boardHash(state) { function gammonThreat(state, player) {
return state.points.map((p) => `${p.color?.[0] ?? '-'}${p.count}`).join('') + const { me, op } = boardsFor(state, player);
`|b${state.bar.black}w${state.bar.white}`; if (op[25] > 0) return false;
// opponent still has 3+ checkers back in my home board / on the bar and trails badly
let back = op[24];
for (let i = 18; i < 24; i++) back += op[i];
return back >= 3 && pipP(op) - pipP(me) > 50;
} }
function evaluateState(state, player) { // ── coaching ─────────────────────────────────────────────────────────────────
const opp = player === 'white' ? 'black' : 'white'; const pointName = (i) => (i === 6 ? 'bar point' : `${i + 1}-point`);
let score = 0;
// Pip count advantage /** Plain-English reason for a turn played from `state`. */
const ownPips = computePipCount(state, player); export function explainTurn(state, moves) {
const oppPips = computePipCount(state, opp); const player = state.currentPlayer;
score += (oppPips - ownPips) * 1.5; const before = boardsFor(state, player);
let me = before.me.slice(), op = before.op.slice();
// Borne off bonus let hits = 0, off = 0, entered = 0;
score += state.borneOff[player] * 25; for (const m of moves) {
score -= state.borneOff[opp] * 25; const from = m.from === 'bar' ? 24 : (player === WHITE ? m.from : 23 - m.from);
const to = m.to === 'off' ? -1 : (player === WHITE ? m.to : 23 - m.to);
// Opponent checkers on bar (we sent them there) if (from === 24) entered++;
score += state.bar[opp] * 20; if (to < 0) off++;
me[from]--;
// Own blots (lone exposed checkers) if (to >= 0) { me[to]++; const j = 23 - to; if (op[j] === 1) { op[j] = 0; op[24]++; hits++; } }
for (let i = 0; i < 24; i++) { else me[25]++;
const pt = state.points[i];
if (pt.color === player && pt.count === 1) score -= 8;
if (pt.color === player && pt.count >= 2) {
// Home board anchors
const inHome = player === 'white' ? (i <= 5) : (i >= 18);
if (inHome) score += 10;
} }
const bits = [];
if (hits) bits.push(hits > 1 ? `hits ${hits} blots` : 'hits a blot');
if (entered) bits.push(entered > 1 ? `enters ${entered} from the bar` : 'enters from the bar');
const made = [];
for (let i = 0; i < 24; i++) if (me[i] >= 2 && before.me[i] < 2) made.push(i);
if (made.length) {
const named = made.filter((i) => i <= 6 || i >= 18).map((i) => (i >= 18 ? `an anchor on the ${i + 1}-point` : `your ${pointName(i)}`));
if (named.length) bits.push(`makes ${named.slice(0, 2).join(' and ')}`);
else bits.push(made.length > 1 ? `makes ${made.length} points` : 'makes a point');
}
if (off) bits.push(off > 1 ? `bears off ${off}` : 'bears one off');
if (hasContact(me, op)) {
const sh = shotInfo(me, op);
if (!sh.blots || !sh.union) bits.push('leaves no shots');
else bits.push(`leaves ${sh.union} shot${sh.union === 1 ? '' : 's'} (${Math.round((sh.union / 36) * 100)}%)`);
} else if (!bits.length) bits.push('races safely home');
let s = bits.join(' · ');
return s.charAt(0).toUpperCase() + s.slice(1);
} }
// Prime bonus — runs of 3+ consecutive blocked points /** Best turn from the current position (skill-5 search) plus its reason. */
let run = 0; export function hint(state) {
for (let i = 0; i < 24; i++) { const r = chooseTurn(state, 5, () => 0.5);
if (state.points[i].color === player && state.points[i].count >= 2) { return { moves: r.moves, reason: r.moves.length ? explainTurn(state, r.moves) : 'No legal move', value: r.value };
run++;
if (run >= 3) score += 15;
} else {
run = 0;
}
} }
return score; export { Bearoff };
}

View File

@ -0,0 +1,764 @@
// BackgammonArt.js — baked canvas textures for "Tavli at the seaside kafeneio".
// All procedural: no image files.
//
// bg-room sun-warmed, blue-painted café table (worn to the wood),
// tea glass + saucer, komboloi beads over the table edge
// bg-vignette sun + vignette overlay for a chosen playfield tablecloth
// bg-props tea glass, beads and leaves alone (drawn over a playfield)
// bg-case the open olive-wood tavli case: Greek-key inlay, mother-of-
// pearl rosettes, teal leather fields, bone/oxblood points,
// hinge with brass knuckles, grooved bear-off tray
// bg-chk-<c> turned checkers (white = bone, black = walnut)
// bg-edge-<c> a borne-off checker standing on edge in the tray
// bg-chk-shadow soft contact shadow
// bg-glow soft gold ring (selection / movable)
// bg-cup-<c> stitched leather dice cups (honey for you, oxblood for them)
// bg-cube-<v> doubling-cube faces 64 / 2 / 4 / 8 / 16 / 32
// bg-plate a whitewashed board with blue trim (player plates)
// bg-slate the café chalk slate
// bg-ledger a waiter's order pad (move ledger)
// bg-slip a torn paper slip (cube offers)
// bg-dapple drifting vine-leaf shadows
// bg-spark / bg-steam
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
import {
W, H, CASE, FRAME, FY, FH, PW, PH, CR, HALF_W, BAR_W, TRAY_W, MID_Y,
OPP_PLATE, SLATE, TEA, LEDGER, BEADS, AI_CUP,
} from './BackgammonLayout.js';
export const DISPLAY_FONT = 'Righteous, Georgia, serif';
export const SERIF = 'Georgia, "Times New Roman", serif';
export const HAND_FONT = 'YummyCupcakes, "Comic Sans MS", cursive';
export const PRINT_FONT = '"Julius Sans One", Georgia, serif';
export const CASE_PAD = 34;
export const CUBE_VALUES = [64, 2, 4, 8, 16, 32];
export const CHK = { size: CR * 2 + 14, edgeW: CR * 2 + 8, edgeH: 13 };
export const INK = { white: '#2a3f66', black: '#7a2420' };
export const TINT = { white: 0xe9dcc0, black: 0x5a3422 };
function addCanvas(scene, key, c) {
if (scene.textures.exists(key)) scene.textures.remove(key);
scene.textures.addCanvas(key, c);
}
function shade(hex, k) {
const n = parseInt(hex.slice(1), 16);
const c = [n >> 16, (n >> 8) & 255, n & 255].map((v) => Math.max(0, Math.min(255, Math.round(v * k))));
return `rgb(${c[0]},${c[1]},${c[2]})`;
}
// seeded so the room looks the same every visit
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 grain(ctx, rnd, x, y, w, h, { tone = 'rgba(60,32,10,0.22)', lines = 14, wave = 3, vertical = false } = {}) {
ctx.save();
ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
ctx.strokeStyle = tone;
const L = vertical ? h : w;
const S = vertical ? w : h;
for (let i = 0; i < lines; i++) {
const o = rnd() * S;
const amp = wave * (0.4 + rnd());
const f = 0.004 + rnd() * 0.012;
const ph = rnd() * 6;
ctx.lineWidth = 0.6 + rnd() * 1.6;
ctx.beginPath();
for (let t = 0; t <= L; t += 6) {
const d = o + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.1 + 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();
}
// Olive wood: pale honey with bold dark swirls.
function oliveWood(ctx, rnd, x, y, w, h, vertical = false) {
const g = vertical ? ctx.createLinearGradient(x, 0, x + w, 0) : ctx.createLinearGradient(0, y, 0, y + h);
g.addColorStop(0, '#c89a5c'); g.addColorStop(0.5, '#d9b277'); g.addColorStop(1, '#b8874a');
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
grain(ctx, rnd, x, y, w, h, { tone: 'rgba(92,52,18,0.30)', lines: Math.max(6, (vertical ? w : h) / 3), wave: 6, vertical });
grain(ctx, rnd, x, y, w, h, { tone: 'rgba(60,30,8,0.45)', lines: Math.max(2, (vertical ? w : h) / 14), wave: 14, vertical });
ctx.fillStyle = noisePattern(ctx, 64, 22);
ctx.fillRect(x, y, w, h);
}
function dropShadow(ctx, fn, { blur = 26, dx = 10, dy = 14, alpha = 0.5 } = {}) {
ctx.save();
ctx.shadowColor = `rgba(10,20,30,${alpha})`;
ctx.shadowBlur = blur; ctx.shadowOffsetX = dx; ctx.shadowOffsetY = dy;
fn();
ctx.restore();
}
// ── room ─────────────────────────────────────────────────────────────────────
function paintTable(ctx, rnd, w, h) {
// planks of wood under worn Aegean-blue paint
const plankH = 120;
const tones = ['#8a6238', '#7d5732', '#94693d', '#83603a'];
for (let py = 0, i = 0; py < h; py += plankH, i++) {
const ph = Math.min(plankH, h - py);
ctx.fillStyle = tones[i % tones.length];
ctx.fillRect(0, py, w, ph);
grain(ctx, rnd, 0, py, w, ph, { lines: 20, tone: 'rgba(50,28,8,0.3)' });
}
const paint = canvas(w, h), pc = paint.getContext('2d');
const pg = pc.createLinearGradient(0, 0, w, h);
pg.addColorStop(0, '#5b9ccc'); pg.addColorStop(0.55, '#4a87b8'); pg.addColorStop(1, '#3d76a6');
pc.fillStyle = pg;
pc.fillRect(0, 0, w, h);
// brush streaks
for (let i = 0; i < 260; i++) {
pc.strokeStyle = rnd() < 0.5 ? 'rgba(255,255,255,0.05)' : 'rgba(10,40,70,0.06)';
pc.lineWidth = 2 + rnd() * 6;
const y = rnd() * h;
pc.beginPath(); pc.moveTo(rnd() * w, y); pc.lineTo(rnd() * w, y + (rnd() - 0.5) * 6); pc.stroke();
}
// wear: chipped patches showing the wood (and white undercoat at the rim)
pc.globalCompositeOperation = 'destination-out';
for (let i = 0; i < 110; i++) {
const x = rnd() * w, y = rnd() * h;
const r = 6 + rnd() * 34;
pc.fillStyle = `rgba(0,0,0,${0.5 + rnd() * 0.5})`;
pc.beginPath();
for (let k = 0; k < 9; k++) {
const a = (k / 9) * Math.PI * 2, rr2 = r * (0.5 + rnd() * 0.7);
const px = x + Math.cos(a) * rr2 * 1.8, py = y + Math.sin(a) * rr2 * 0.6;
if (k) pc.lineTo(px, py); else pc.moveTo(px, py);
}
pc.closePath(); pc.fill();
}
// plank edges rub through most
for (let py = plankH; py < h; py += plankH) {
for (let x = 0; x < w; x += 18) {
if (rnd() < 0.55) { pc.fillStyle = `rgba(0,0,0,${0.4 + rnd() * 0.6})`; pc.fillRect(x, py - 3 - rnd() * 4, 12 + rnd() * 26, 5 + rnd() * 6); }
}
}
pc.globalCompositeOperation = 'source-over';
ctx.drawImage(paint, 0, 0);
// plank seams
for (let py = plankH; py < h; py += plankH) {
ctx.fillStyle = 'rgba(20,20,30,0.55)'; ctx.fillRect(0, py - 1, w, 3);
ctx.fillStyle = 'rgba(255,255,255,0.08)'; ctx.fillRect(0, py + 2, w, 1);
}
ctx.fillStyle = noisePattern(ctx, 96, 26);
ctx.fillRect(0, 0, w, h);
}
function sunAndVignette(ctx, w, h) {
const g = ctx.createRadialGradient(w * 0.32, h * 0.1, 40, w * 0.4, h * 0.3, w * 0.85);
g.addColorStop(0, 'rgba(255,232,170,0.28)');
g.addColorStop(0.5, 'rgba(255,214,140,0.08)');
g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, w, h);
const v = ctx.createRadialGradient(w / 2, h / 2, h * 0.45, w / 2, h / 2, h * 1.05);
v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(8,16,28,0.55)');
ctx.fillStyle = v; ctx.fillRect(0, 0, w, h);
}
function teaGlass(ctx, cx, cy) {
// saucer (white with a blue rim) seen from above, slight perspective
dropShadow(ctx, () => {
ctx.fillStyle = '#f4f1ea';
ctx.beginPath(); ctx.ellipse(cx, cy, 64, 46, 0, 0, Math.PI * 2); ctx.fill();
}, { blur: 14, dx: 6, dy: 8, alpha: 0.45 });
ctx.strokeStyle = '#2f5f9a'; ctx.lineWidth = 4;
ctx.beginPath(); ctx.ellipse(cx, cy, 58, 41, 0, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(47,95,154,0.5)'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.ellipse(cx, cy, 50, 35, 0, 0, Math.PI * 2); ctx.stroke();
// two sugar cubes
for (const [dx, dy, a] of [[-40, 14, 0.3], [-26, 24, -0.2]]) {
ctx.save(); ctx.translate(cx + dx, cy + dy); ctx.rotate(a);
ctx.fillStyle = '#fffdf6'; ctx.fillRect(-7, -7, 14, 14);
ctx.fillStyle = 'rgba(0,0,0,0.12)'; ctx.fillRect(-7, 4, 14, 3);
ctx.restore();
}
// tulip tea glass: base ring, amber tea, rim highlight
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.beginPath(); ctx.ellipse(cx + 12, cy - 2, 28, 22, 0, 0, Math.PI * 2); ctx.fill();
const tea = ctx.createRadialGradient(cx + 2, cy - 10, 4, cx + 8, cy - 6, 30);
tea.addColorStop(0, '#e2902c'); tea.addColorStop(0.6, '#b05a14'); tea.addColorStop(1, '#6e2f08');
ctx.fillStyle = tea;
ctx.beginPath(); ctx.ellipse(cx + 8, cy - 8, 27, 21, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(255,255,255,0.75)'; ctx.lineWidth = 2.5;
ctx.beginPath(); ctx.ellipse(cx + 8, cy - 8, 29, 23, 0, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(255,255,255,0.5)'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.ellipse(cx + 8, cy - 8, 22, 16, 0, Math.PI * 1.1, Math.PI * 1.55); ctx.stroke();
// a spoon resting on the saucer
ctx.save(); ctx.translate(cx + 44, cy + 16); ctx.rotate(-0.5);
ctx.fillStyle = '#c9ccd2';
ctx.beginPath(); ctx.ellipse(0, 0, 9, 6, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillRect(6, -1.5, 34, 3);
ctx.fillStyle = 'rgba(255,255,255,0.6)'; ctx.fillRect(8, -1.5, 28, 1);
ctx.restore();
}
function komboloi(ctx, rnd, x0, y0, w) {
// a loop of amber beads draped over the table edge, tassel hanging off
const beads = [];
const n = 19;
for (let i = 0; i < n; i++) {
const t = i / (n - 1);
beads.push({ x: x0 + 20 + t * (w - 70), y: y0 + 8 + Math.sin(t * Math.PI) * 22 + (rnd() - 0.5) * 3 });
}
ctx.strokeStyle = 'rgba(60,20,8,0.8)'; ctx.lineWidth = 1.5;
ctx.beginPath(); beads.forEach((b, i) => (i ? ctx.lineTo(b.x, b.y) : ctx.moveTo(b.x, b.y))); ctx.stroke();
for (const b of beads) {
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.beginPath(); ctx.arc(b.x + 3, b.y + 4, 8, 0, Math.PI * 2); ctx.fill();
const g = ctx.createRadialGradient(b.x - 3, b.y - 3, 1, b.x, b.y, 9);
g.addColorStop(0, '#ffd27a'); g.addColorStop(0.5, '#d98a1e'); g.addColorStop(1, '#8a4208');
ctx.fillStyle = g;
ctx.beginPath(); ctx.arc(b.x, b.y, 8, 0, Math.PI * 2); ctx.fill();
}
// shield bead + tassel
const e = beads[beads.length - 1];
ctx.fillStyle = '#c9a24a';
ctx.beginPath(); ctx.ellipse(e.x + 22, e.y + 4, 9, 6, 0.4, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#7a1e18'; ctx.lineWidth = 1.6;
for (let k = 0; k < 9; k++) {
ctx.beginPath(); ctx.moveTo(e.x + 28, e.y + 8);
ctx.quadraticCurveTo(e.x + 40 + k, e.y + 20, e.x + 34 + k * 2.4, e.y + 40);
ctx.stroke();
}
}
function bakeRoom(scene) {
const rnd = seeded(91);
const c = canvas(W, H), ctx = c.getContext('2d');
paintTable(ctx, rnd, W, H);
teaGlass(ctx, TEA.x + TEA.w / 2, TEA.y + TEA.h / 2);
komboloi(ctx, rnd, BEADS.x, BEADS.y, BEADS.w);
// a few fallen olive leaves
for (const [x, y, a] of [[1660, 640, 0.6], [1890, 820, -0.4], [300, 1060, 1.2], [14, 520, -1.0]]) leaf(ctx, x, y, a, 1);
sunAndVignette(ctx, W, H);
addCanvas(scene, 'bg-room', c);
const v = canvas(W, H), vx = v.getContext('2d');
sunAndVignette(vx, W, H);
addCanvas(scene, 'bg-vignette', v);
// the props alone, for when a chosen playfield is the tablecloth
const p = canvas(W, H), px = p.getContext('2d');
const r2 = seeded(91);
teaGlass(px, TEA.x + TEA.w / 2, TEA.y + TEA.h / 2);
komboloi(px, r2, BEADS.x, BEADS.y, BEADS.w);
for (const [x, y, a] of [[1660, 640, 0.6], [1890, 820, -0.4], [300, 1060, 1.2], [14, 520, -1.0]]) leaf(px, x, y, a, 1);
addCanvas(scene, 'bg-props', p);
}
function leaf(ctx, x, y, a, alpha = 1, len = 26) {
ctx.save(); ctx.translate(x, y); ctx.rotate(a);
ctx.globalAlpha = alpha;
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.beginPath(); ctx.ellipse(3, 4, len, len * 0.28, 0, 0, Math.PI * 2); ctx.fill();
const g = ctx.createLinearGradient(0, -8, 0, 8);
g.addColorStop(0, '#7c8a4a'); g.addColorStop(1, '#4f5c2c');
ctx.fillStyle = g;
ctx.beginPath(); ctx.ellipse(0, 0, len, len * 0.28, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(220,230,180,0.5)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(-len, 0); ctx.lineTo(len, 0); ctx.stroke();
ctx.restore();
}
// ── the case ─────────────────────────────────────────────────────────────────
function greekKey(ctx, x, y, w, h, vertical) {
// a running meander in bone on a walnut strip
ctx.fillStyle = '#3a2210';
ctx.fillRect(x, y, w, h);
ctx.strokeStyle = '#ead9b4';
ctx.lineWidth = 1.6;
const u = vertical ? w : h; // module size
const s = u - 3;
const L = vertical ? h : w;
ctx.beginPath();
for (let t = 0; t + u <= L; t += u) {
// one meander unit drawn in local coords (along, across)
const pts = [[0, s], [0, 1.5], [s * 0.8, 1.5], [s * 0.8, s * 0.65], [s * 0.35, s * 0.65], [s * 0.35, s * 0.4], [s * 0.55, s * 0.4]];
pts.forEach(([a, b], i) => {
const px = vertical ? x + 1.5 + b : x + t + a + 1;
const py = vertical ? y + t + a + 1 : y + 1.5 + b;
if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py);
});
}
ctx.stroke();
}
function rosette(ctx, cx, cy, r) {
const g = ctx.createRadialGradient(cx - r * 0.3, cy - r * 0.3, 1, cx, cy, r);
g.addColorStop(0, '#ffffff'); g.addColorStop(0.35, '#dfe9f2'); g.addColorStop(0.6, '#f2dfe8'); g.addColorStop(0.8, '#d6efe4'); g.addColorStop(1, '#b9c6cf');
for (let k = 0; k < 8; k++) {
const a = (k / 8) * Math.PI * 2;
ctx.save(); ctx.translate(cx, cy); ctx.rotate(a);
ctx.fillStyle = g;
ctx.beginPath(); ctx.ellipse(r * 0.5, 0, r * 0.5, r * 0.2, 0, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
ctx.fillStyle = '#c9a24a';
ctx.beginPath(); ctx.arc(cx, cy, r * 0.18, 0, Math.PI * 2); ctx.fill();
}
function leather(ctx, x, y, w, h) {
const g = ctx.createLinearGradient(0, y, 0, y + h);
g.addColorStop(0, '#1d4b47'); g.addColorStop(0.5, '#215550'); g.addColorStop(1, '#1a4440');
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
ctx.fillStyle = noisePattern(ctx, 80, 34);
ctx.fillRect(x, y, w, h);
// stitched border
ctx.save();
ctx.setLineDash([7, 6]);
ctx.strokeStyle = 'rgba(230,214,170,0.45)'; ctx.lineWidth = 1.5;
ctx.strokeRect(x + 7, y + 7, w - 14, h - 14);
ctx.restore();
// inner bevel
ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 4;
ctx.strokeRect(x + 2, y + 2, w - 4, h - 4);
}
function point(ctx, ax, bx, baseY, tipY, light) {
const cx = (ax + bx) / 2;
const base = light ? '#ecdfc0' : '#7d2a22';
const g = ctx.createLinearGradient(0, baseY, 0, tipY);
g.addColorStop(0, light ? '#efe3c6' : '#86302a');
g.addColorStop(1, light ? '#cfbd94' : '#5a1c16');
ctx.fillStyle = g;
ctx.beginPath(); ctx.moveTo(ax + 2, baseY); ctx.lineTo(bx - 2, baseY); ctx.lineTo(cx, tipY); ctx.closePath(); ctx.fill();
// inlay grain
ctx.save(); ctx.clip();
ctx.strokeStyle = light ? 'rgba(120,90,40,0.18)' : 'rgba(0,0,0,0.22)';
ctx.lineWidth = 1;
for (let k = 0; k < 7; k++) {
const xx = ax + 8 + k * ((bx - ax - 16) / 6);
ctx.beginPath(); ctx.moveTo(xx, baseY); ctx.lineTo(cx + (xx - cx) * 0.1, tipY); ctx.stroke();
}
ctx.restore();
// stringing: a fine inset line in the contrasting wood
const inset = 7;
const dir = tipY < baseY ? -1 : 1;
ctx.strokeStyle = light ? 'rgba(90,40,20,0.55)' : 'rgba(240,222,180,0.6)';
ctx.lineWidth = 1.2;
ctx.beginPath();
ctx.moveTo(ax + inset, baseY + dir * 4);
ctx.lineTo(bx - inset, baseY + dir * 4);
ctx.lineTo(cx, tipY - dir * 16);
ctx.closePath(); ctx.stroke();
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(ax + 2, baseY); ctx.lineTo(cx, tipY); ctx.lineTo(bx - 2, baseY); ctx.stroke();
void base;
}
function brassPlate(ctx, x, y, w, h) {
const g = ctx.createLinearGradient(x, y, x + w, y + h);
g.addColorStop(0, '#f3d98a'); g.addColorStop(0.5, '#c79a3a'); g.addColorStop(1, '#8e6a22');
ctx.fillStyle = g;
rr(ctx, x, y, w, h, 3); ctx.fill();
ctx.strokeStyle = 'rgba(60,40,10,0.7)'; ctx.lineWidth = 1; ctx.stroke();
}
function screw(ctx, x, y) {
ctx.fillStyle = '#7a5a1c';
ctx.beginPath(); ctx.arc(x, y, 2.6, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#f6e3a8'; ctx.lineWidth = 0.8;
ctx.beginPath(); ctx.moveTo(x - 2, y); ctx.lineTo(x + 2, y); ctx.stroke();
}
function bakeCase(scene) {
const rnd = seeded(7);
const P = CASE_PAD;
const c = canvas(CASE.w + P * 2, CASE.h + P * 2), ctx = c.getContext('2d');
const X = (x) => x - CASE.x + P, Y = (y) => y - CASE.y + P;
const x0 = P, y0 = P, w = CASE.w, h = CASE.h;
dropShadow(ctx, () => { ctx.fillStyle = '#6b4a22'; rr(ctx, x0, y0, w, h, 14); ctx.fill(); }, { blur: 34, dx: 14, dy: 20, alpha: 0.6 });
ctx.save(); rr(ctx, x0, y0, w, h, 14); ctx.clip();
oliveWood(ctx, rnd, x0, y0, w, h);
ctx.restore();
// outer bevel
ctx.strokeStyle = 'rgba(255,240,200,0.35)'; ctx.lineWidth = 2; rr(ctx, x0 + 2, y0 + 2, w - 4, h - 4, 12); ctx.stroke();
ctx.strokeStyle = 'rgba(40,20,5,0.6)'; ctx.lineWidth = 2; rr(ctx, x0 + 1, y0 + 1, w - 2, h - 2, 13); ctx.stroke();
const leftX = CASE.x + FRAME, barX = leftX + HALF_W, rightX = barX + BAR_W, trayX = rightX + HALF_W + FRAME;
// Greek-key bands along the outer frame (top and bottom), between the rails
const band = 12;
greekKey(ctx, X(leftX), Y(CASE.y) + (FRAME - band) / 2, HALF_W * 2 + BAR_W, band, false);
greekKey(ctx, X(leftX), Y(CASE.y + CASE.h - FRAME) + (FRAME - band) / 2, HALF_W * 2 + BAR_W, band, false);
// rosettes at the four frame corners
for (const [x, y] of [[CASE.x + FRAME / 2, CASE.y + FRAME / 2], [CASE.x + CASE.w - FRAME / 2, CASE.y + FRAME / 2], [CASE.x + FRAME / 2, CASE.y + CASE.h - FRAME / 2], [CASE.x + CASE.w - FRAME / 2, CASE.y + CASE.h - FRAME / 2]]) {
rosette(ctx, X(x), Y(y), 12);
}
// brass corner guards
for (const [x, y, sx, sy] of [[x0, y0, 1, 1], [x0 + w, y0, -1, 1], [x0, y0 + h, 1, -1], [x0 + w, y0 + h, -1, -1]]) {
ctx.save(); ctx.translate(x, y); ctx.scale(sx, sy);
const g = ctx.createLinearGradient(0, 0, 40, 40);
g.addColorStop(0, '#f3d98a'); g.addColorStop(1, '#8e6a22');
ctx.fillStyle = g;
ctx.beginPath(); ctx.moveTo(0, 14); ctx.quadraticCurveTo(0, 0, 14, 0); ctx.lineTo(44, 0); ctx.lineTo(44, 7); ctx.lineTo(7, 7); ctx.lineTo(7, 44); ctx.lineTo(0, 44); ctx.closePath(); ctx.fill();
screw(ctx, 24, 3.5); screw(ctx, 3.5, 24);
ctx.restore();
}
// fields (recessed leather)
for (const fx of [leftX, rightX]) {
dropShadow(ctx, () => { ctx.fillStyle = '#123'; ctx.fillRect(X(fx), Y(FY), HALF_W, FH); }, { blur: 10, dx: 0, dy: 3, alpha: 0.7 });
leather(ctx, X(fx), Y(FY), HALF_W, FH);
}
// points
for (let half = 0; half < 2; half++) {
const fx = half === 0 ? leftX : rightX;
for (let col = 0; col < 6; col++) {
const ax = X(fx + col * PW), bx = ax + PW;
// top row starts light at the left of each half, bottom row starts dark
point(ctx, ax, bx, Y(FY), Y(FY + PH), col % 2 === 0);
point(ctx, ax, bx, Y(FY + FH), Y(FY + FH - PH), col % 2 === 1);
}
}
// the hinge / bar: olive wood with a centre seam and brass knuckles
ctx.save(); ctx.beginPath(); ctx.rect(X(barX), Y(FY), BAR_W, FH); ctx.clip();
oliveWood(ctx, rnd, X(barX), Y(FY), BAR_W, FH, true);
ctx.restore();
ctx.fillStyle = 'rgba(30,15,5,0.65)'; ctx.fillRect(X(barX + BAR_W / 2) - 1.5, Y(FY), 3, FH);
ctx.fillStyle = 'rgba(255,235,190,0.25)'; ctx.fillRect(X(barX + BAR_W / 2) + 1.5, Y(FY), 1, FH);
for (const yy of [FY + FH * 0.33, FY + FH * 0.67]) {
brassPlate(ctx, X(barX + BAR_W / 2) - 9, Y(yy) - 34, 18, 68);
for (let k = -2; k <= 2; k++) { ctx.fillStyle = 'rgba(80,55,15,0.6)'; ctx.fillRect(X(barX + BAR_W / 2) - 9, Y(yy) + k * 13, 18, 1.2); }
}
ctx.strokeStyle = 'rgba(30,15,5,0.55)'; ctx.lineWidth = 2;
ctx.strokeRect(X(barX), Y(FY), BAR_W, FH);
// bear-off tray: a grooved well with a divider
const tx = X(trayX), tw = TRAY_W;
dropShadow(ctx, () => { ctx.fillStyle = '#221'; ctx.fillRect(tx, Y(FY), tw, FH); }, { blur: 10, dx: 0, dy: 3, alpha: 0.7 });
const tg = ctx.createLinearGradient(tx, 0, tx + tw, 0);
tg.addColorStop(0, '#5a3a1c'); tg.addColorStop(0.5, '#6e4824'); tg.addColorStop(1, '#4e3218');
ctx.fillStyle = tg; ctx.fillRect(tx, Y(FY), tw, FH);
grain(ctx, rnd, tx, Y(FY), tw, FH, { vertical: true, lines: 14, tone: 'rgba(20,10,2,0.35)', wave: 4 });
for (let yy = FY + 6; yy < FY + FH; yy += 14) {
ctx.fillStyle = 'rgba(0,0,0,0.25)'; ctx.fillRect(tx + 8, Y(yy), tw - 16, 1.5);
ctx.fillStyle = 'rgba(255,220,170,0.08)'; ctx.fillRect(tx + 8, Y(yy) + 1.5, tw - 16, 1);
}
ctx.save(); ctx.beginPath(); ctx.rect(tx - 2, Y(MID_Y) - 15, tw + 4, 30); ctx.clip();
oliveWood(ctx, rnd, tx - 2, Y(MID_Y) - 15, tw + 4, 30);
ctx.restore();
rosette(ctx, tx + tw / 2, Y(MID_Y), 10);
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 3; ctx.strokeRect(tx + 1, Y(FY) + 1, tw - 2, FH - 2);
// the small rail between the field and the tray
ctx.fillStyle = 'rgba(40,20,5,0.35)'; ctx.fillRect(X(rightX + HALF_W), Y(FY), 2, FH);
addCanvas(scene, 'bg-case', c);
}
// ── checkers ─────────────────────────────────────────────────────────────────
function bakeCheckers(scene) {
const S = CHK.size, cx = S / 2, cy = S / 2 - 2, R = CR;
for (const color of ['white', 'black']) {
const c = canvas(S, S + 6), ctx = c.getContext('2d');
const face = color === 'white'
? ['#fbf3df', '#eadbb7', '#cdb88b']
: ['#6b4630', '#3e2618', '#22140b'];
// edge band (thickness, seen just below the face)
ctx.fillStyle = color === 'white' ? '#b49f72' : '#150b05';
ctx.beginPath(); ctx.arc(cx, cy + 5, R, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = color === 'white' ? 'rgba(255,255,255,0.25)' : 'rgba(255,200,150,0.12)';
ctx.fillRect(cx - R, cy + 2, R * 2, 1);
// face
const g = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R);
g.addColorStop(0, face[0]); g.addColorStop(0.6, face[1]); g.addColorStop(1, face[2]);
ctx.fillStyle = g;
ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill();
// turned lathe rings
for (const [k, a] of [[0.86, 0.35], [0.62, 0.3], [0.34, 0.25]]) {
ctx.strokeStyle = color === 'white' ? `rgba(120,95,50,${a})` : `rgba(0,0,0,${a + 0.15})`;
ctx.lineWidth = 1.6;
ctx.beginPath(); ctx.arc(cx, cy, R * k, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = color === 'white' ? 'rgba(255,255,255,0.55)' : 'rgba(255,210,170,0.16)';
ctx.lineWidth = 1;
ctx.beginPath(); ctx.arc(cx, cy + 1.2, R * k, Math.PI * 0.15, Math.PI * 0.85); ctx.stroke();
}
// centre inlay
const ig = ctx.createRadialGradient(cx - 2, cy - 2, 0.5, cx, cy, 7);
if (color === 'white') { ig.addColorStop(0, '#ffffff'); ig.addColorStop(0.5, '#d9e6ef'); ig.addColorStop(1, '#a9b8c4'); }
else { ig.addColorStop(0, '#fbe6a8'); ig.addColorStop(0.6, '#c99a3a'); ig.addColorStop(1, '#7a5a1c'); }
ctx.fillStyle = ig;
ctx.beginPath(); ctx.arc(cx, cy, 6.5, 0, Math.PI * 2); ctx.fill();
// gloss
const gl = ctx.createLinearGradient(cx - R, cy - R, cx, cy);
gl.addColorStop(0, color === 'white' ? 'rgba(255,255,255,0.55)' : 'rgba(255,220,190,0.28)');
gl.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gl;
ctx.beginPath(); ctx.ellipse(cx - R * 0.32, cy - R * 0.38, R * 0.55, R * 0.3, -0.6, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = color === 'white' ? 'rgba(90,70,30,0.55)' : 'rgba(0,0,0,0.75)';
ctx.lineWidth = 1.2;
ctx.beginPath(); ctx.arc(cx, cy, R - 0.5, 0, Math.PI * 2); ctx.stroke();
addCanvas(scene, `bg-chk-${color}`, c);
// standing on edge in the tray
const e = canvas(CHK.edgeW + 6, CHK.edgeH + 6), ex = e.getContext('2d');
ex.fillStyle = 'rgba(0,0,0,0.4)'; rr(ex, 4, 5, CHK.edgeW, CHK.edgeH, 5); ex.fill();
const eg = ex.createLinearGradient(0, 2, 0, 2 + CHK.edgeH);
eg.addColorStop(0, face[0]); eg.addColorStop(0.5, face[1]); eg.addColorStop(1, face[2]);
ex.fillStyle = eg; rr(ex, 2, 2, CHK.edgeW, CHK.edgeH, 5); ex.fill();
ex.strokeStyle = color === 'white' ? 'rgba(110,85,40,0.45)' : 'rgba(0,0,0,0.6)'; ex.lineWidth = 1;
for (const yy of [5, 2 + CHK.edgeH - 3]) { ex.beginPath(); ex.moveTo(6, yy); ex.lineTo(CHK.edgeW - 2, yy); ex.stroke(); }
rr(ex, 2, 2, CHK.edgeW, CHK.edgeH, 5); ex.stroke();
addCanvas(scene, `bg-edge-${color}`, e);
}
// contact shadow
const s = canvas(S + 20, S + 20), sx = s.getContext('2d');
const sg = sx.createRadialGradient((S + 20) / 2, (S + 20) / 2, R * 0.6, (S + 20) / 2, (S + 20) / 2, R + 10);
sg.addColorStop(0, 'rgba(0,0,0,0.55)'); sg.addColorStop(1, 'rgba(0,0,0,0)');
sx.fillStyle = sg; sx.fillRect(0, 0, S + 20, S + 20);
addCanvas(scene, 'bg-chk-shadow', s);
// selection glow ring
const gS = S + 30, gc = canvas(gS, gS), gx = gc.getContext('2d');
const gg = gx.createRadialGradient(gS / 2, gS / 2, R - 2, gS / 2, gS / 2, R + 14);
gg.addColorStop(0, 'rgba(255,214,90,0)'); gg.addColorStop(0.3, 'rgba(255,214,90,0.95)'); gg.addColorStop(1, 'rgba(255,214,90,0)');
gx.fillStyle = gg; gx.fillRect(0, 0, gS, gS);
addCanvas(scene, 'bg-glow', gc);
}
// ── cups ─────────────────────────────────────────────────────────────────────
function bakeCup(scene, key, tones) {
const P = 14;
const cw = AI_CUP.w, ch = AI_CUP.h;
const c = canvas(cw + P * 2, ch + P * 2), ctx = c.getContext('2d');
const top = P + 16, bot = P + ch - 10;
const lt = P + 6, rt = P + cw - 6, lb = P + 18, rb = P + cw - 18;
ctx.fillStyle = 'rgba(0,0,0,0.45)';
ctx.beginPath(); ctx.ellipse(P + cw / 2 + 8, bot + 2, cw * 0.42, 12, 0, 0, Math.PI * 2); ctx.fill();
ctx.save();
ctx.beginPath();
ctx.moveTo(lt, top); ctx.lineTo(rt, top); ctx.lineTo(rb, bot);
ctx.ellipse(P + cw / 2, bot, (rb - lb) / 2, 10, 0, 0, Math.PI, false);
ctx.lineTo(lt, top); ctx.closePath();
const g = ctx.createLinearGradient(lt, 0, rt, 0);
g.addColorStop(0, tones[0]); g.addColorStop(0.3, tones[1]); g.addColorStop(0.55, tones[2]); g.addColorStop(1, tones[3]);
ctx.fillStyle = g; ctx.fill();
ctx.clip();
ctx.fillStyle = noisePattern(ctx, 64, 50); ctx.fillRect(0, 0, c.width, c.height);
const cxm = P + cw / 2;
for (const yy of [top + 24, bot - 22]) {
const f = (yy - top) / (bot - top);
const hw = ((rt - lt) / 2) * (1 - f) + ((rb - lb) / 2) * f + 2, ry = 16 * (1 - f) + 10 * f;
ctx.fillStyle = 'rgba(0,0,0,0.25)';
ctx.beginPath(); ctx.ellipse(cxm, yy, hw, ry + 8, 0, 0, Math.PI); ctx.ellipse(cxm, yy - 14, hw, ry, 0, Math.PI, 0, true); ctx.fill();
const N = 22;
for (let k = 0; k < N; k++) {
const a0 = Math.PI * (k + 0.2) / N, a1 = Math.PI * (k + 0.75) / N;
const face = Math.sin((a0 + a1) / 2);
ctx.strokeStyle = `rgba(240,214,160,${0.3 + 0.6 * face})`;
ctx.lineWidth = 1 + 1.2 * face;
ctx.beginPath();
ctx.moveTo(cxm + hw * Math.cos(a0), yy - 4 + ry * Math.sin(a0));
ctx.lineTo(cxm + hw * Math.cos(a1), yy - 4 + ry * Math.sin(a1));
ctx.stroke();
}
}
// embossed meander square
ctx.strokeStyle = 'rgba(255,220,160,0.35)'; ctx.lineWidth = 2;
rr(ctx, cxm - 18, (top + bot) / 2 - 16, 36, 36, 6); ctx.stroke();
ctx.beginPath(); ctx.moveTo(cxm - 10, (top + bot) / 2 + 12); ctx.lineTo(cxm - 10, (top + bot) / 2 - 8); ctx.lineTo(cxm + 10, (top + bot) / 2 - 8); ctx.lineTo(cxm + 10, (top + bot) / 2 + 4); ctx.lineTo(cxm - 2, (top + bot) / 2 + 4); ctx.stroke();
ctx.restore();
// mouth
ctx.fillStyle = '#1a0b04';
ctx.beginPath(); ctx.ellipse(cxm, top, (rt - lt) / 2, 16, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = tones[1]; ctx.lineWidth = 5;
ctx.beginPath(); ctx.ellipse(cxm, top, (rt - lt) / 2 - 2, 14, 0, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(255,230,190,0.35)'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.ellipse(cxm, top - 1, (rt - lt) / 2 - 2, 14, 0, Math.PI * 1.05, Math.PI * 1.95); ctx.stroke();
addCanvas(scene, key, c);
}
// ── doubling cube ────────────────────────────────────────────────────────────
function bakeCube(scene) {
const S = 64;
for (const v of CUBE_VALUES) {
const c = canvas(S + 12, S + 18), ctx = c.getContext('2d');
ctx.fillStyle = 'rgba(0,0,0,0.4)'; rr(ctx, 8, 12, S, S, 10); ctx.fill();
ctx.fillStyle = '#a99a78'; rr(ctx, 4, 10, S, S, 10); ctx.fill(); // side
const g = ctx.createLinearGradient(4, 4, 4 + S, 4 + S);
g.addColorStop(0, '#fffaf0'); g.addColorStop(1, '#e2d6bb');
ctx.fillStyle = g; rr(ctx, 4, 4, S, S, 10); ctx.fill(); // top face
ctx.strokeStyle = 'rgba(90,70,30,0.5)'; ctx.lineWidth = 1.5; rr(ctx, 4, 4, S, S, 10); ctx.stroke();
ctx.strokeStyle = 'rgba(122,36,32,0.6)'; ctx.lineWidth = 1.2; rr(ctx, 10, 10, S - 12, S - 12, 6); ctx.stroke();
ctx.fillStyle = '#7a2420';
ctx.font = `bold ${v >= 10 ? 30 : 36}px Georgia, serif`;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(String(v), 4 + S / 2, 4 + S / 2 + 2);
addCanvas(scene, `bg-cube-${v}`, c);
}
}
// ── HUD pieces ───────────────────────────────────────────────────────────────
function bakePlate(scene) {
const rnd = seeded(33);
const w = OPP_PLATE.w, h = OPP_PLATE.h, P = 16;
const c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
dropShadow(ctx, () => { ctx.fillStyle = '#f2ede2'; rr(ctx, P, P, w, h, 14); ctx.fill(); }, { blur: 18, dx: 6, dy: 10, alpha: 0.5 });
ctx.save(); rr(ctx, P, P, w, h, 14); ctx.clip();
ctx.fillStyle = '#efe9dc'; ctx.fillRect(P, P, w, h);
grain(ctx, rnd, P, P, w, h, { tone: 'rgba(120,100,70,0.16)', lines: 30, wave: 3 });
ctx.fillStyle = noisePattern(ctx, 64, 18); ctx.fillRect(P, P, w, h);
ctx.restore();
ctx.strokeStyle = '#2f6ea6'; ctx.lineWidth = 7; rr(ctx, P + 6, P + 6, w - 12, h - 12, 10); ctx.stroke();
ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1; rr(ctx, P + 11, P + 11, w - 22, h - 22, 7); ctx.stroke();
for (const [x, y] of [[P + 18, P + 18], [P + w - 18, P + 18], [P + 18, P + h - 18], [P + w - 18, P + h - 18]]) {
ctx.fillStyle = '#b8902e'; ctx.beginPath(); ctx.arc(x, y, 4, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,240,190,0.8)'; ctx.beginPath(); ctx.arc(x - 1, y - 1, 1.5, 0, Math.PI * 2); ctx.fill();
}
addCanvas(scene, 'bg-plate', c);
}
function bakeSlate(scene) {
const rnd = seeded(5);
const w = SLATE.w, h = SLATE.h, P = 16;
const c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
dropShadow(ctx, () => { ctx.fillStyle = '#6b4a22'; rr(ctx, P, P, w, h, 10); ctx.fill(); }, { blur: 18, dx: 6, dy: 10, alpha: 0.5 });
ctx.save(); rr(ctx, P, P, w, h, 10); ctx.clip();
oliveWood(ctx, rnd, P, P, w, h);
ctx.restore();
const ix = P + 14, iy = P + 14, iw = w - 28, ih = h - 28;
const g = ctx.createLinearGradient(ix, iy, ix + iw, iy + ih);
g.addColorStop(0, '#2c3433'); g.addColorStop(1, '#1f2625');
ctx.fillStyle = g; ctx.fillRect(ix, iy, iw, ih);
ctx.fillStyle = noisePattern(ctx, 64, 30); ctx.fillRect(ix, iy, iw, ih);
// old chalk smudges
for (let i = 0; i < 16; i++) {
ctx.fillStyle = `rgba(230,230,220,${0.02 + rnd() * 0.04})`;
ctx.beginPath(); ctx.ellipse(ix + rnd() * iw, iy + rnd() * ih, 20 + rnd() * 50, 6 + rnd() * 14, rnd() * 3, 0, Math.PI * 2); ctx.fill();
}
ctx.strokeStyle = 'rgba(0,0,0,0.55)'; ctx.lineWidth = 3; ctx.strokeRect(ix, iy, iw, ih);
addCanvas(scene, 'bg-slate', c);
}
function bakeLedger(scene) {
const w = LEDGER.w, h = LEDGER.h, P = 14;
const c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
dropShadow(ctx, () => { ctx.fillStyle = '#fbf8ef'; ctx.fillRect(P, P, w, h); }, { blur: 16, dx: 6, dy: 9, alpha: 0.45 });
ctx.fillStyle = '#fbf8ef'; ctx.fillRect(P, P, w, h);
ctx.fillStyle = noisePattern(ctx, 64, 12); ctx.fillRect(P, P, w, h);
// blue binding band with a title
ctx.fillStyle = '#2f6ea6'; ctx.fillRect(P, P, w, 40);
ctx.fillStyle = 'rgba(255,255,255,0.15)'; ctx.fillRect(P, P + 36, w, 2);
ctx.fillStyle = '#f6f2e6'; ctx.font = 'bold 18px Georgia, serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('ΤΑΒΛΙ · moves', P + w / 2, P + 20);
for (let y = P + 64; y < P + h - 6; y += 26) {
ctx.strokeStyle = 'rgba(47,110,166,0.28)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(P + 8, y); ctx.lineTo(P + w - 8, y); ctx.stroke();
}
ctx.strokeStyle = 'rgba(190,60,60,0.35)';
ctx.beginPath(); ctx.moveTo(P + 44, P + 42); ctx.lineTo(P + 44, P + h); ctx.stroke();
// torn top edge
ctx.fillStyle = 'rgba(0,0,0,0.12)';
for (let x = P; x < P + w; x += 8) ctx.fillRect(x, P + 40, 4, 2);
addCanvas(scene, 'bg-ledger', c);
}
function bakeSlip(scene) {
const rnd = seeded(11);
const w = 520, h = 300, P = 18;
const c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
const pts = [];
for (let x = 0; x <= w; x += 10) pts.push([P + x, P + (rnd() - 0.5) * 5]);
for (let y = 0; y <= h; y += 10) pts.push([P + w + (rnd() - 0.5) * 5, P + y]);
for (let x = w; x >= 0; x -= 10) pts.push([P + x, P + h + (rnd() - 0.5) * 6]);
for (let y = h; y >= 0; y -= 10) pts.push([P + (rnd() - 0.5) * 5, P + y]);
const path = () => { ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); };
dropShadow(ctx, () => { ctx.fillStyle = '#fbf6e8'; path(); ctx.fill(); }, { blur: 20, dx: 8, dy: 12, alpha: 0.55 });
ctx.save(); path(); ctx.clip();
const g = ctx.createLinearGradient(0, P, 0, P + h);
g.addColorStop(0, '#fdf9ee'); g.addColorStop(1, '#efe6cf');
ctx.fillStyle = g; ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(0, 0, c.width, c.height);
ctx.restore();
ctx.strokeStyle = 'rgba(47,110,166,0.5)'; ctx.lineWidth = 2;
ctx.strokeRect(P + 14, P + 14, w - 28, h - 28);
addCanvas(scene, 'bg-slip', c);
}
function bakeDapple(scene) {
const rnd = seeded(2024);
// painted at half resolution (it is blurred anyway) and shown at 2×
const w = 2400, h = 1500;
const c = canvas(w / 2, h / 2), ctx = c.getContext('2d');
ctx.scale(0.5, 0.5);
try { ctx.filter = 'blur(7px)'; } catch (_) { /* older canvas */ }
// clusters of vine leaves (dark) with sunny gaps
for (let k = 0; k < 46; k++) {
const cx = rnd() * w, cy = rnd() * h;
const n = 6 + Math.floor(rnd() * 10);
for (let i = 0; i < n; i++) {
const x = cx + (rnd() - 0.5) * 260, y = cy + (rnd() - 0.5) * 200;
const r = 26 + rnd() * 46;
ctx.fillStyle = `rgba(8,26,20,${0.35 + rnd() * 0.35})`;
ctx.save(); ctx.translate(x, y); ctx.rotate(rnd() * Math.PI);
// a five-lobed vine leaf
ctx.beginPath();
for (let a = 0; a <= 40; a++) {
const t = (a / 40) * Math.PI * 2;
const lobe = 0.72 + 0.28 * Math.abs(Math.cos(t * 2.5));
const px = Math.cos(t) * r * lobe, py = Math.sin(t) * r * lobe * 0.9;
if (a) ctx.lineTo(px, py); else ctx.moveTo(px, py);
}
ctx.closePath(); ctx.fill();
ctx.restore();
}
// a tendril
ctx.strokeStyle = 'rgba(8,26,20,0.4)'; ctx.lineWidth = 5;
ctx.beginPath(); ctx.moveTo(cx, cy);
ctx.bezierCurveTo(cx + 60, cy - 90, cx + 160, cy + 40, cx + 230, cy - 40);
ctx.stroke();
}
try { ctx.filter = 'none'; } catch (_) { /* older canvas */ }
addCanvas(scene, 'bg-dapple', c);
}
function bakeBits(scene) {
const s = canvas(32, 32), sx = s.getContext('2d');
const g = sx.createRadialGradient(16, 16, 0, 16, 16, 16);
g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.4, 'rgba(255,240,200,0.7)'); g.addColorStop(1, 'rgba(255,240,200,0)');
sx.fillStyle = g; sx.fillRect(0, 0, 32, 32);
addCanvas(scene, 'bg-spark', s);
const st = canvas(64, 64), tx = st.getContext('2d');
const g2 = tx.createRadialGradient(32, 32, 0, 32, 32, 32);
g2.addColorStop(0, 'rgba(255,255,255,0.55)'); g2.addColorStop(1, 'rgba(255,255,255,0)');
tx.fillStyle = g2; tx.fillRect(0, 0, 64, 64);
addCanvas(scene, 'bg-steam', st);
}
let baked = false;
export async function prepareBackgammonArt(scene) {
try {
if (document.fonts?.load) {
await Promise.race([
Promise.all([
document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"'),
document.fonts.load('30px YummyCupcakes'),
]),
new Promise((res) => setTimeout(res, 1200)),
]);
}
} catch (_) { /* fall back to Georgia */ }
if (!baked || !scene.textures.exists('bg-room')) {
bakeRoom(scene); bakeCase(scene); bakeCheckers(scene);
bakeCup(scene, 'bg-cup-white', ['#5a3412', '#b07a3a', '#8e5c26', '#4a2a0e']);
bakeCup(scene, 'bg-cup-black', ['#3a0e0c', '#8a2a24', '#6a1c18', '#2a0806']);
bakeCube(scene); bakePlate(scene); bakeSlate(scene); bakeLedger(scene); bakeSlip(scene);
bakeDapple(scene); bakeBits(scene);
baked = true;
}
}
export { shade };

View File

@ -0,0 +1,177 @@
// BackgammonBearoff.js — exact one-sided bear-off table. Phaser-free.
//
// For every arrangement of ≤ 15 checkers on the six home points (C(21,6) =
// 54,264 positions) it stores the expected number of rolls to bear everything
// off under rolls-minimising play, and the second moment, so a two-sided race
// can be turned into a win probability.
//
// Built by DP in pip order (children always have fewer pips). Every
// (position, die) single-step child list is precomputed into flat Int32Arrays,
// then h_k(pos, d) = best E after k more moves of die d drives non-doubles
// (two orders) and doubles (four moves). The build can run in slices
// (buildStep) so the scene never stalls; ready() says when it's done.
//
// expectedRolls(counts[6]) → { e, m2 } | null (null until built)
// raceWinProb(meHome, opHome) → P(me wins) with op ON ROLL
const N_POINTS = 6;
const MAXC = 15;
let positions = null; // Int32Array of packed keys, in pip order
let indexOf = null; // Map packed → index
let E = null, M2 = null;
let H = null, HM = null; // h_k tables: [(pos*6 + d-1)*3 + (k-1)]
let cursor = 0;
let total = 0;
const pack = (c) => c[0] | (c[1] << 4) | (c[2] << 8) | (c[3] << 12) | (c[4] << 16) | (c[5] << 20);
const unpack = (k, out) => { for (let i = 0; i < 6; i++) out[i] = (k >> (i * 4)) & 15; return out; };
function enumeratePositions() {
const list = [];
const c = [0, 0, 0, 0, 0, 0];
const rec = (i, left) => {
if (i === N_POINTS) { list.push({ key: pack(c), pips: c.reduce((a, n, j) => a + n * (j + 1), 0) }); return; }
for (let n = 0; n <= left; n++) { c[i] = n; rec(i + 1, left - n); }
c[i] = 0;
};
rec(0, MAXC);
list.sort((a, b) => a.pips - b.pips);
return list;
}
function init() {
const list = enumeratePositions();
total = list.length;
positions = new Int32Array(total);
indexOf = new Map();
list.forEach((p, i) => { positions[i] = p.key; indexOf.set(p.key, i); });
E = new Float32Array(total);
M2 = new Float32Array(total);
H = new Float32Array(total * 18);
HM = new Float32Array(total * 18);
cursor = 0;
}
const tmp = [0, 0, 0, 0, 0, 0];
const tmp2 = [0, 0, 0, 0, 0, 0];
// Children of position c for one die: indices.
function childrenOf(c, die, out) {
out.length = 0;
let hi = -1;
for (let i = 5; i >= 0; i--) if (c[i]) { hi = i; break; }
if (hi < 0) return out;
for (let i = 0; i < 6; i++) {
if (!c[i]) continue;
const to = i - die;
if (to < -1 && i !== hi) continue;
for (let j = 0; j < 6; j++) tmp2[j] = c[j];
tmp2[i]--;
if (to >= 0) tmp2[to]++;
out.push(indexOf.get(pack(tmp2)));
}
return out;
}
const kids = [];
function processOne(idx) {
const c = unpack(positions[idx], tmp);
let empty = true;
for (let i = 0; i < 6; i++) if (c[i]) { empty = false; break; }
if (empty) {
E[idx] = 0; M2[idx] = 0;
for (let q = 0; q < 18; q++) { H[idx * 18 + q] = 0; HM[idx * 18 + q] = 0; }
return;
}
// per-die child lists (reused below)
const lists = [];
for (let d = 1; d <= 6; d++) lists.push(childrenOf(c, d, []).slice());
// expected rolls for this position: average over 36 rolls of best play
let e = 0, m2 = 0;
for (let a = 1; a <= 6; a++) {
for (let b = a; b <= 6; b++) {
let best = Infinity, bestM = 0;
if (a === b) {
// four moves: first step here, then h_3 on the child
for (const ch of lists[a - 1]) {
const v = H[(ch * 6 + a - 1) * 3 + 2], vm = HM[(ch * 6 + a - 1) * 3 + 2];
if (v < best) { best = v; bestM = vm; }
}
} else {
for (const ch of lists[a - 1]) {
const v = H[(ch * 6 + b - 1) * 3], vm = HM[(ch * 6 + b - 1) * 3];
if (v < best) { best = v; bestM = vm; }
}
for (const ch of lists[b - 1]) {
const v = H[(ch * 6 + a - 1) * 3], vm = HM[(ch * 6 + a - 1) * 3];
if (v < best) { best = v; bestM = vm; }
}
}
const w = a === b ? 1 : 2;
e += w * (1 + best);
m2 += w * (1 + 2 * best + bestM);
}
}
E[idx] = e / 36;
M2[idx] = m2 / 36;
// h_k(this, d): best (E, M2) after k more single moves of die d from here.
for (let d = 1; d <= 6; d++) {
const base = (idx * 6 + d - 1) * 3;
let b1 = Infinity, m1 = 0;
for (const ch of lists[d - 1]) if (E[ch] < b1) { b1 = E[ch]; m1 = M2[ch]; }
H[base] = b1; HM[base] = m1;
for (let k = 2; k <= 3; k++) {
let bk = Infinity, mk = 0;
for (const ch of lists[d - 1]) {
const v = H[(ch * 6 + d - 1) * 3 + (k - 2)];
if (v < bk) { bk = v; mk = HM[(ch * 6 + d - 1) * 3 + (k - 2)]; }
}
H[base + k - 1] = bk; HM[base + k - 1] = mk;
}
}
}
/** Build up to `budget` positions; returns true when the table is complete. */
export function buildStep(budget = 4000) {
if (!positions) init();
const end = Math.min(total, cursor + budget);
for (; cursor < end; cursor++) processOne(cursor);
return cursor >= total;
}
export function buildAll() { while (!buildStep(1e6)); }
export function ready() { return !!positions && cursor >= total; }
export function size() { return total || enumeratePositions().length; }
export function expectedRolls(counts) {
if (!ready()) return null;
for (let i = 0; i < 6; i++) if (counts[i] > MAXC) return null;
const idx = indexOf.get(pack(counts));
if (idx === undefined) return null;
return { e: E[idx], m2: M2[idx] };
}
// Standard normal CDF.
export function phi(x) {
const t = 1 / (1 + 0.2316419 * Math.abs(x));
const d = 0.3989423 * Math.exp(-x * x / 2);
const p = d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274))));
return x > 0 ? 1 - p : p;
}
// P(me wins) when both sides are bearing off and op is on roll. Uses the
// normal approximation to the difference of the two roll-count distributions.
export function raceWinProb(meHome, opHome) {
const a = expectedRolls(meHome), b = expectedRolls(opHome);
if (!a || !b) return null;
if (a.e === 0) return 1;
if (b.e === 0) return 0;
const va = Math.max(0, a.m2 - a.e * a.e), vb = Math.max(0, b.m2 - b.e * b.e);
const sd = Math.max(0.35, Math.sqrt(va + vb));
// op wins if N_op ≤ N_me (op rolls first): P(me) = P(N_me − N_op ≤ −1)
return phi((-0.5 - (a.e - b.e)) / sd);
}

View File

@ -0,0 +1,231 @@
// BackgammonCheckers.js — the 30 checkers as persistent sprites with stable ids.
//
// Every checker is a shadow Image + a face Image (never a Container, so depth
// works). `sync(state)` assigns ids to locations so nothing that stays put
// moves: a location that shrinks releases its TOP checkers, a location that
// grows takes freed ones. A single move therefore always relocates exactly the
// checker the scene animated (the top of the source stack), and an undo just
// slides the changed checkers back.
//
// Locations: 'p<idx>' (a point), 'bar', 'off'.
import { CR } from './BackgammonLayout.js';
import { clack, slam } from './BackgammonSound.js';
const lerp = (a, b, t) => a + (b - a) * t;
const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
export const locKey = (where) => (where === 'bar' ? 'bar' : where === 'off' ? 'off' : `p${where}`);
export class CheckerSet {
constructor(scene, layout, depth) {
this.scene = scene;
this.L = layout;
this.depth = depth;
this.items = []; // id → item
this.lists = { white: new Map(), black: new Map() }; // key → [ids bottom→top]
}
build() {
const s = this.scene;
for (let id = 0; id < 30; id++) {
const color = id < 15 ? 'white' : 'black';
const shadow = s.add.image(0, 0, 'bg-chk-shadow').setDepth(this.depth - 0.5).setAlpha(0.7);
const img = s.add.image(0, 0, `bg-chk-${color}`).setDepth(this.depth);
this.items.push({ id, color, img, shadow, x: 0, y: 0, h: 0, edge: false, key: null, slot: 0, tier: 0, busy: false });
}
return this;
}
// ── placement maths ─────────────────────────────────────────────────────────
countsOf(state, color) {
const m = new Map();
for (let idx = 0; idx < 24; idx++) {
const pt = state.points[idx];
if (pt.color === color && pt.count) m.set(`p${idx}`, pt.count);
}
if (state.bar[color]) m.set('bar', state.bar[color]);
if (state.borneOff[color]) m.set('off', state.borneOff[color]);
return m;
}
slotFor(color, key, s, count) {
if (key === 'bar') return { ...this.L.barPos(color, s, count), edge: false };
if (key === 'off') return { ...this.L.offPos(color, s), tier: s, edge: true };
const p = this.L.slotPos(Number(key.slice(1)), s);
return { ...p, edge: false };
}
depthFor(it) {
if (it.edge) return this.depth + 0.2 + it.slot * 0.001;
return this.depth + it.tier * 0.1 + it.slot * 0.001 + (it.key === 'bar' ? 0.05 : 0);
}
// Re-assign ids to match `state`. Returns [{ it, to }] for checkers whose
// target changed.
assign(state) {
const changes = [];
for (const color of ['white', 'black']) {
const lists = this.lists[color];
const counts = this.countsOf(state, color);
const freed = [];
const ids = this.items.filter((it) => it.color === color).map((it) => it.id);
if (!this.assigned) {
// first time: hand out in order
let k = 0;
lists.clear();
for (const [key, n] of counts) lists.set(key, ids.slice(k, (k += n)));
} else {
for (const [key, list] of lists) {
const want = counts.get(key) ?? 0;
while (list.length > want) freed.push(list.pop());
if (!list.length) lists.delete(key);
}
for (const [key, n] of counts) {
const list = lists.get(key) ?? [];
while (list.length < n && freed.length) list.push(freed.shift());
lists.set(key, list);
}
}
for (const [key, list] of lists) {
list.forEach((id, s) => {
const it = this.items[id];
const to = this.slotFor(color, key, s, list.length);
if (it.key !== key || it.slot !== s || Math.abs(it.x - to.x) > 0.5 || Math.abs(it.y - to.y) > 0.5 || it.edge !== to.edge) {
changes.push({ it, to, key, s });
}
});
}
}
this.assigned = true;
return changes;
}
// Snap or slide every checker to its place for `state`.
sync(state, { dur = 0 } = {}) {
const changes = this.assign(state);
const jobs = [];
for (const { it, to, key, s } of changes) {
it.key = key; it.slot = s; it.tier = to.tier ?? 0;
if (dur <= 0 || it.busy) { this.place(it, to.x, to.y, 0, to.edge); continue; }
jobs.push(this.slide(it, to, dur));
}
return Promise.all(jobs);
}
place(it, x, y, h = 0, edge = it.edge) {
it.x = x; it.y = y; it.h = h;
if (edge !== it.edge) {
it.edge = edge;
it.img.setTexture(edge ? `bg-edge-${it.color}` : `bg-chk-${it.color}`);
}
const lift = h / 60;
it.img.setPosition(x, y - h * 0.55);
it.img.setScale(1 + lift * 0.12);
it.shadow.setPosition(x + 4 + h * 0.18, y + 6 + h * 0.3);
it.shadow.setScale(1 + lift * 0.25);
it.shadow.setAlpha(edge ? 0 : Math.max(0.2, 0.7 - lift * 0.25));
if (!it.flying) {
const d = this.depthFor(it);
it.img.setDepth(d); it.shadow.setDepth(d - 0.05);
}
}
slide(it, to, dur) {
const from = { x: it.x, y: it.y };
const p = { t: 0 };
return new Promise((res) => {
this.scene.tweens.add({
targets: p, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const k = easeInOut(p.t);
this.place(it, lerp(from.x, to.x, k), lerp(from.y, to.y, k), Math.sin(Math.PI * p.t) * 10, p.t > 0.5 ? to.edge : it.edge);
},
onComplete: () => { this.place(it, to.x, to.y, 0, to.edge); res(); },
});
});
}
// ── queries ─────────────────────────────────────────────────────────────────
topOf(color, where) {
const list = this.lists[color].get(locKey(where));
return list?.length ? this.items[list[list.length - 1]] : null;
}
itemsAt(color, where) {
return (this.lists[color].get(locKey(where)) ?? []).map((id) => this.items[id]);
}
// Where the next checker of `color` lands on `where` once state is `after`.
landingFor(after, color, where) {
const key = locKey(where);
const counts = this.countsOf(after, color);
const n = counts.get(key) ?? 1;
return this.slotFor(color, key, n - 1, n);
}
// ── animated moves ──────────────────────────────────────────────────────────
// Arc one checker from where it is to `to` ({x, y, edge}); hops with a little
// lift, lands with a squash and a clack. opts.spin for hits.
fly(it, to, { dur = 420, height = 70, spin = 0, sound = true, stack = 0, slamIt = false } = {}) {
const from = { x: it.x, y: it.y };
it.flying = true; it.busy = true;
it.img.setDepth(this.depth + 30); it.shadow.setDepth(this.depth + 29.5);
const p = { t: 0 };
return new Promise((res) => {
this.scene.tweens.add({
targets: p, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const k = easeInOut(p.t);
this.place(it, lerp(from.x, to.x, k), lerp(from.y, to.y, k), Math.sin(Math.PI * p.t) * height, p.t > 0.6 ? to.edge : it.edge);
if (spin) it.img.setRotation(spin * p.t * Math.PI * 2);
},
onComplete: () => {
it.img.setRotation(0);
this.place(it, to.x, to.y, 0, to.edge);
if (sound) (slamIt ? slam : clack)(this.scene, { stack });
// squash on landing
const sq = { k: 0 };
this.scene.tweens.add({
targets: sq, k: 1, duration: 120, ease: 'Linear',
onUpdate: () => { const v = Math.sin(Math.PI * sq.k) * 0.08; it.img.setScale(1 + v, 1 - v); },
onComplete: () => {
it.img.setScale(1);
it.flying = false; it.busy = false;
const d = this.depthFor(it);
it.img.setDepth(d); it.shadow.setDepth(d - 0.05);
res();
},
});
},
});
});
}
// Lift / drop the top checker of a selected point.
setLifted(it, on) {
if (!it || it.edge) return;
if (on) {
it.lifted = true;
it.flying = true;
it.img.setDepth(this.depth + 28); it.shadow.setDepth(this.depth + 27.5);
this.place(it, it.x, it.y, 16);
} else if (it.lifted) {
it.lifted = false;
it.flying = false;
this.place(it, it.x, it.y, 0);
}
}
// Drag: follow the pointer.
dragTo(it, x, y) {
it.flying = true;
it.img.setDepth(this.depth + 30); it.shadow.setDepth(this.depth + 29.5);
it.img.setPosition(x, y - 10);
it.img.setScale(1.12);
it.shadow.setPosition(x + 14, y + 16).setScale(1.25).setAlpha(0.35);
}
allItems() { return this.items; }
}
export { CR };

View File

@ -0,0 +1,155 @@
// BackgammonDialogs.js — café pop-ups: a whitewashed card with a blue rim, and
// the torn paper slip the cube is offered on. Each opener returns { close() }
// and swallows clicks beneath it.
//
// openPauseMenu resume · settings · rules · new game · leave
// confirmBox yes / no
// openCubeOffer "Nikos turns the cube to 4" — Take / Drop (+ coach line)
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { DISPLAY_FONT, SERIF, HAND_FONT } from './BackgammonArt.js';
const BLUE = 0x2f6ea6;
export function frame(scene, x, y, w, h, depth) {
const g = scene.add.graphics().setDepth(depth);
g.fillStyle(0x000000, 0.4).fillRoundedRect(x + 6, y + 10, w, h, 16);
g.fillStyle(0xf6f2e8, 1).fillRoundedRect(x, y, w, h, 16);
g.lineStyle(8, BLUE, 1).strokeRoundedRect(x + 8, y + 8, w - 16, h - 16, 11);
g.lineStyle(1.5, 0xffffff, 0.8).strokeRoundedRect(x + 15, y + 15, w - 30, h - 30, 8);
g.fillStyle(BLUE, 0.9).fillRect(x + 30, y + 74, w - 60, 2);
return g;
}
export function blocker(scene, depth, alpha = 0) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x06121c, alpha)
.setDepth(depth).setInteractive();
}
export function title(scene, x, y, text, depth, size = 30, color = '#2f6ea6') {
return scene.add.text(x, y, text, { fontFamily: DISPLAY_FONT, fontSize: `${size}px`, color, align: 'center' })
.setOrigin(0.5).setDepth(depth);
}
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_LABEL = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' };
const MATCH_LABEL = (n) => (n ? `Match to ${n}` : 'Single game');
export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose }) {
const objs = [blocker(scene, depth - 1, 0.5)];
const w = 600, h = 960;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(title(scene, x + w / 2, y + 44, 'Kafeneio', depth + 1));
const cx = x + w / 2;
let hRef = null;
const cycle = (key, order) => onChange(key, order[(order.indexOf(settings[key]) + 1) % order.length]);
const rows = [
['Resume', () => hRef.close(), 0x22445f],
[() => `Opponent speed: ${PACE_LABEL[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])],
[() => `Confirm each turn (Done / tap dice): ${onOff(settings.confirm)}`, () => onChange('confirm', !settings.confirm)],
[() => `Auto-roll when no cube decision: ${onOff(settings.autoRoll)}`, () => onChange('autoRoll', !settings.autoRoll)],
[() => `Auto-play forced moves: ${onOff(settings.autoForced)}`, () => onChange('autoForced', !settings.autoForced)],
[() => `Hover previews: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)],
[() => `Pip counts: ${onOff(settings.pips)}`, () => onChange('pips', !settings.pips)],
[() => `Doubling cube (next game): ${onOff(settings.cube)}`, () => onChange('cube', !settings.cube)],
[() => `Length (next match): ${MATCH_LABEL(settings.match)}`, () => cycle('match', [0, 3, 5, 7])],
[() => `Jacoby rule, single games: ${onOff(settings.jacoby)}`, () => onChange('jacoby', !settings.jacoby)],
[() => `Home board (next game): ${settings.mirror ? 'Left' : 'Right'}`, () => onChange('mirror', !settings.mirror)],
[() => `Slam on hits: ${onOff(settings.slam)} · Sea: ${onOff(settings.waves)}`, () => {
// cycle: both on → slam off → both off → sea only… keeps one row
const s = settings.slam, wv = settings.waves;
if (s && wv) onChange('slam', false);
else if (!s && wv) onChange('waves', false);
else if (!s && !wv) onChange('slam', true);
else onChange('waves', true);
}],
[() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)],
['How to Play', () => onRules()],
['New Game', () => { hRef.close(); onNewGame(); }, 0x6a4a1a],
['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a2a1a],
];
rows.forEach(([label, fn, bg], i) => {
const text = typeof label === 'function' ? label() : label;
const btn = new Button(scene, cx, y + 112 + i * 50, text, () => {
fn();
if (typeof label === 'function') btn.setLabel(label());
}, { width: 520, height: 42, fontSize: 16, bg: bg ?? 0x2f5577 }).setDepth(depth + 2);
objs.push(btn);
});
objs.push(scene.add.text(cx, y + h - 34, 'Keys: Space roll / done · Z undo · H hint · D double · Esc menu', {
fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#3a4a5a', align: 'center', wordWrap: { width: w - 60 },
}).setOrigin(0.5).setDepth(depth + 1));
hRef = handle(objs, onClose);
return hRef;
}
export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) {
const objs = [blocker(scene, depth - 1, 0.5)];
const w = 540, h = 270;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(title(scene, x + w / 2, y + 44, heading, depth + 1, 26));
objs.push(scene.add.text(x + w / 2, y + 134, text, {
fontFamily: SERIF, fontSize: '18px', color: '#22303c', align: 'center', wordWrap: { width: w - 80 },
}).setOrigin(0.5).setDepth(depth + 1));
let hRef = null;
objs.push(new Button(scene, x + w / 2 - 118, y + h - 52, yes, () => { hRef.close(); onYes?.(); }, { width: 210, height: 46, fontSize: 18, bg: 0x7a2a1a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 118, y + h - 52, no, () => { hRef.close(); onNo?.(); }, { width: 210, height: 46, fontSize: 18, bg: 0x22445f }).setDepth(depth + 2));
hRef = handle(objs);
return hRef;
}
// The cube offer, written on a torn slip. `advice` is an optional coach line.
export function openCubeOffer(scene, { name, value, stake, depth, advice, onTake, onDrop }) {
const objs = [blocker(scene, depth - 1, 0.35)];
const w = 520, h = 300;
const x = GAME_WIDTH / 2 - w / 2 + 60, y = GAME_HEIGHT / 2 - h / 2 - 30;
const slip = scene.add.image(x - 18, y - 18, 'bg-slip').setOrigin(0).setDepth(depth).setRotation(-0.02);
objs.push(slip);
objs.push(scene.add.text(x + w / 2, y + 58, `${name} turns the cube`, {
fontFamily: HAND_FONT, fontSize: '36px', color: '#7a2420',
}).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 112, `“Double? We play for ${value}.”`, {
fontFamily: HAND_FONT, fontSize: '30px', color: '#22303c',
}).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 158, `Take to keep playing for ${value} (and own the cube).\nDrop to concede ${stake} point${stake === 1 ? '' : 's'} now.`, {
fontFamily: SERIF, fontSize: '16px', color: '#3a4a5a', align: 'center',
}).setOrigin(0.5).setDepth(depth + 1));
if (advice) {
objs.push(scene.add.text(x + w / 2, y + 200, advice, {
fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#2f6ea6', align: 'center', wordWrap: { width: w - 60 },
}).setOrigin(0.5).setDepth(depth + 1));
}
let hRef = null;
objs.push(new Button(scene, x + w / 2 - 112, y + h - 46, 'Take', () => { hRef.close(); onTake?.(); }, { width: 196, height: 46, fontSize: 20, bg: 0x2f6e3a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 112, y + h - 46, 'Drop', () => { hRef.close(); onDrop?.(); }, { width: 196, height: 46, fontSize: 20, bg: 0x7a2a1a }).setDepth(depth + 2));
hRef = handle(objs);
hRef.keys = { take: onTake, drop: onDrop };
return hRef;
}
// A short-lived note card (e.g. "Crawford game: no doubling").
export function toast(scene, text, { depth, x = GAME_WIDTH / 2, y = 120, ms = 2200 } = {}) {
const t = scene.add.text(x, y, text, {
fontFamily: SERIF, fontSize: '20px', color: '#22303c', backgroundColor: '#f6f2e8',
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;
}

View File

@ -0,0 +1,115 @@
// BackgammonEndScreen.js — after each game: who won and how (single / gammon /
// backgammon / dropped cube), the points and match tally, a stats table for
// both players and a pip-race chart across the game.
import { Button } from '../../ui/Button.js';
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { DISPLAY_FONT, SERIF, PRINT_FONT, HAND_FONT, INK } from './BackgammonArt.js';
import { frame } from './BackgammonDialogs.js';
const KIND = {
single: 'a single game',
gammon: 'a GAMMON',
backgammon: 'a BACKGAMMON',
drop: 'a dropped double',
};
const EXPECTED_PIPS = 8.1667;
export function resultLine(result, names) {
const who = result.winner === 'white' ? 'You' : names.black;
const pts = `${result.points} point${result.points === 1 ? '' : 's'}`;
if (result.kind === 'drop') return `${who} win${result.winner === 'white' ? '' : 's'} ${pts} — the double was dropped`;
const parts = [];
if (result.multiplier > 1) parts.push(result.kind === 'gammon' ? 'gammon ×2' : 'backgammon ×3');
if (result.cube > 1) parts.push(`cube ${result.cube}`);
const why = parts.length ? ` (${parts.join(' · ')})` : '';
const waived = result.jacobyWaived ? ' — Jacoby: gammon not counted, cube never turned' : '';
return `${who} win${result.winner === 'white' ? '' : 's'} ${pts}${why}${waived}`;
}
export function openEndScreen(scene, { gs, match, names, depth, onNext, onPlayAgain, onMenu }) {
const objs = [];
const w = 980, h = 760;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x06121c, 0.45).setDepth(depth - 1).setInteractive());
objs.push(frame(scene, x, y, w, h, depth));
const r = gs.result;
const humanWon = r.winner === 'white';
const matchOver = match.over;
let head;
if (matchOver && match.length > 0) head = humanWon ? 'You win the match!' : `${names.black} wins the match`;
else head = humanWon ? `You win ${KIND[r.kind]}!` : `${names.black} wins ${KIND[r.kind]}`;
objs.push(scene.add.text(x + w / 2, y + 44, head, { fontFamily: DISPLAY_FONT, fontSize: '34px', color: humanWon ? '#2f6e3a' : '#7a2420' }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 100, resultLine(r, names), { fontFamily: SERIF, fontSize: '19px', color: '#22303c' }).setOrigin(0.5).setDepth(depth + 1));
const tally = match.length > 0
? `Match to ${match.length}: You ${match.score.white} · ${names.black} ${match.score.black}${match.crawford && !matchOver ? ' — next game is the Crawford game' : ''}`
: `Tonight's points: You ${match.score.white} · ${names.black} ${match.score.black}`;
objs.push(scene.add.text(x + w / 2, y + 132, tally, { fontFamily: HAND_FONT, fontSize: '24px', color: '#2f6ea6' }).setOrigin(0.5).setDepth(depth + 1));
// stats table
const rows = [
['Rolls', (s) => s.rolls],
['Pips rolled (per roll)', (s) => `${s.pips} (${s.rolls ? (s.pips / s.rolls).toFixed(2) : '—'})`],
['Doubles rolled', (s) => s.doubles],
['Checkers hit', (s) => s.hits],
['Times hit', (s) => s.hitTaken],
['Turns starting on the bar', (s) => s.barTurns],
['Danced (could not enter)', (s) => s.dances],
['Pips wasted bearing off', (s) => s.pipsWasted],
['Doubles offered', (s) => s.doublesOffered],
];
const tx = x + 60, ty = y + 178;
objs.push(scene.add.text(tx + 300, ty, 'YOU', { fontFamily: PRINT_FONT, fontSize: '14px', color: INK.white }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(tx + 400, ty, names.black.toUpperCase().slice(0, 10), { fontFamily: PRINT_FONT, fontSize: '14px', color: INK.black }).setOrigin(0.5).setDepth(depth + 1));
rows.forEach(([label, fn], i) => {
const yy = ty + 32 + i * 30;
objs.push(scene.add.text(tx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#3a4a5a' }).setOrigin(0, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(tx + 300, yy, String(fn(gs.stats.white)), { fontFamily: SERIF, fontSize: '16px', color: INK.white }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(tx + 400, yy, String(fn(gs.stats.black)), { fontFamily: SERIF, fontSize: '16px', color: INK.black }).setOrigin(0.5).setDepth(depth + 1));
});
const luck = (s) => (s.rolls ? s.pips / s.rolls - EXPECTED_PIPS : 0);
const lw = luck(gs.stats.white), lb = luck(gs.stats.black);
const dl = lw - lb;
const luckLine = Math.abs(dl) < 0.4 ? 'The dice were even-handed.'
: dl > 0 ? `The dice favoured you by ${dl.toFixed(1)} pips a roll.` : `The dice favoured ${names.black} by ${(-dl).toFixed(1)} pips a roll.`;
objs.push(scene.add.text(tx, ty + 32 + rows.length * 30 + 8, `${luckLine} (Average is ${EXPECTED_PIPS.toFixed(2)}.)`, {
fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#2f6ea6',
}).setOrigin(0, 0.5).setDepth(depth + 1));
// pip race chart
const cx0 = x + 540, cy0 = y + 196, cw = 380, ch = 300;
const g = scene.add.graphics().setDepth(depth + 1);
objs.push(g);
g.fillStyle(0xffffff, 0.6).fillRect(cx0, cy0, cw, ch);
g.lineStyle(1, 0x2f6ea6, 0.25);
for (let k = 1; k < 4; k++) g.lineBetween(cx0, cy0 + (ch * k) / 4, cx0 + cw, cy0 + (ch * k) / 4);
g.lineStyle(1.5, 0x22303c, 0.6).strokeRect(cx0, cy0, cw, ch);
const hist = gs.pipHistory;
const maxP = Math.max(170, ...hist.map((p) => Math.max(p.white, p.black)));
const n = Math.max(2, hist.length);
const px = (i) => cx0 + (i / (n - 1)) * cw;
const py = (v) => cy0 + ch - (v / maxP) * ch;
for (const [color, hex] of [['white', 0x2a3f66], ['black', 0x7a2420]]) {
g.lineStyle(3, hex, 0.95);
g.beginPath();
hist.forEach((p, i) => (i ? g.lineTo(px(i), py(p[color])) : g.moveTo(px(i), py(p[color]))));
g.strokePath();
}
objs.push(scene.add.text(cx0 + cw / 2, cy0 - 14, 'Pips left, turn by turn', { fontFamily: PRINT_FONT, fontSize: '13px', color: '#3a4a5a' }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(cx0 + 4, cy0 + ch + 16, '— you', { fontFamily: SERIF, fontSize: '14px', color: INK.white }).setOrigin(0, 0.5).setDepth(depth + 1));
objs.push(scene.add.text(cx0 + 90, cy0 + ch + 16, `— ${names.black}`, { fontFamily: SERIF, fontSize: '14px', color: INK.black }).setOrigin(0, 0.5).setDepth(depth + 1));
// buttons
const by = y + h - 62;
if (!matchOver) {
objs.push(new Button(scene, x + w / 2 - 130, by, 'Next Game', () => { close(); onNext(); }, { width: 230, height: 50, fontSize: 20, bg: 0x2f6e3a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 130, by, 'Leave Table', () => { close(); onMenu(); }, { width: 230, height: 50, fontSize: 20, bg: 0x22445f }).setDepth(depth + 2));
} else {
objs.push(new Button(scene, x + w / 2 - 130, by, match.length > 0 ? 'New Match' : 'Play Again', () => { close(); onPlayAgain(); }, { width: 230, height: 50, fontSize: 20, bg: 0x2f6e3a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 130, by, 'Leave Table', () => { close(); onMenu(); }, { width: 230, height: 50, fontSize: 20, bg: 0x22445f }).setDepth(depth + 2));
}
let closed = false;
function close() { if (closed) return; closed = true; objs.forEach((o) => o.destroy()); }
return { close, objs };
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,190 @@
// BackgammonHud.js — everything around the case: the two café-board plates
// (portraits, names, pip counts), the chalk slate (match score, cube, race bar,
// status), the waiter's-pad move ledger, the button stack and speech bubbles.
import { Button } from '../../ui/Button.js';
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
import {
OPP_PLATE, HUMAN_PLATE, OPP_PARTS, HUMAN_PARTS, SLATE, LEDGER, MENU_BTN, BTN, BUTTONS,
} from './BackgammonLayout.js';
import { DISPLAY_FONT, SERIF, HAND_FONT, PRINT_FONT, INK } from './BackgammonArt.js';
const CHALK = '#ecebe4';
const CHALK_DIM = '#a9b0aa';
export class Hud {
constructor(scene, depth, { names, skill, opponent, onButton, onMenu }) {
this.scene = scene;
this.depth = depth;
this.names = names; // { white, black }
this.skill = skill;
this.opponent = opponent;
this.onButton = onButton;
this.onMenu = onMenu;
this.buttons = {};
this.bubble = null;
}
build() {
const s = this.scene, D = this.depth;
// plates
s.add.image(OPP_PLATE.x - 16, OPP_PLATE.y - 16, 'bg-plate').setOrigin(0).setDepth(D);
s.add.image(HUMAN_PLATE.x - 16, HUMAN_PLATE.y - 16, 'bg-plate').setOrigin(0).setDepth(D);
this.rings = { white: s.add.graphics().setDepth(D + 1), black: s.add.graphics().setDepth(D + 1) };
const op = OPP_PARTS.portrait, hp = HUMAN_PARTS.portrait;
this.portraits = {
black: createOpponentPortrait(s, this.opponent ?? { id: 'bot', spriteIndex: 0 }, op.x, op.y, op.r, D + 2),
white: createPlayerPortrait(s, hp.x, hp.y, hp.r, D + 2, 'Backgammon'),
};
const nm = (n) => (n.length > 16 ? n.slice(0, 15) + '…' : n);
s.add.text(OPP_PARTS.name.x, OPP_PARTS.name.y, nm(this.names.black), { fontFamily: DISPLAY_FONT, fontSize: '24px', color: '#22303c' }).setOrigin(0.5).setDepth(D + 1);
s.add.text(OPP_PARTS.skill.x, OPP_PARTS.skill.y, '●'.repeat(this.skill) + '○'.repeat(5 - this.skill), { fontFamily: SERIF, fontSize: '14px', color: '#2f6ea6' }).setOrigin(0.5).setDepth(D + 1);
s.add.text(HUMAN_PARTS.name.x, HUMAN_PARTS.name.y, nm(this.names.white), { fontFamily: DISPLAY_FONT, fontSize: '24px', color: '#22303c' }).setOrigin(0.5).setDepth(D + 1);
this.pipText = {
black: s.add.text(OPP_PARTS.pips.x, OPP_PARTS.pips.y, '', { fontFamily: PRINT_FONT, fontSize: '16px', color: '#5a4a32' }).setOrigin(0.5).setDepth(D + 1),
white: s.add.text(HUMAN_PARTS.pips.x, HUMAN_PARTS.pips.y, '', { fontFamily: PRINT_FONT, fontSize: '16px', color: '#5a4a32' }).setOrigin(0.5).setDepth(D + 1),
};
this.chk = {
black: s.add.image(OPP_PARTS.pips.x - 92, OPP_PARTS.pips.y, 'bg-chk-black').setScale(0.3).setDepth(D + 1),
white: s.add.image(HUMAN_PARTS.pips.x - 92, HUMAN_PARTS.pips.y, 'bg-chk-white').setScale(0.3).setDepth(D + 1),
};
// slate
s.add.image(SLATE.x - 16, SLATE.y - 16, 'bg-slate').setOrigin(0).setDepth(D);
const sx = SLATE.x + SLATE.w / 2;
this.slate = {
head: s.add.text(sx, SLATE.y + 40, '', { fontFamily: HAND_FONT, fontSize: '26px', color: CHALK }).setOrigin(0.5).setDepth(D + 1),
score: s.add.text(sx, SLATE.y + 74, '', { fontFamily: HAND_FONT, fontSize: '22px', color: CHALK, align: 'center' }).setOrigin(0.5).setDepth(D + 1),
cube: s.add.text(sx, SLATE.y + 106, '', { fontFamily: HAND_FONT, fontSize: '19px', color: CHALK_DIM }).setOrigin(0.5).setDepth(D + 1),
race: s.add.graphics().setDepth(D + 1),
raceText: s.add.text(sx, SLATE.y + 158, '', { fontFamily: HAND_FONT, fontSize: '17px', color: CHALK_DIM }).setOrigin(0.5).setDepth(D + 1),
status: s.add.text(sx, SLATE.y + 206, '', { fontFamily: HAND_FONT, fontSize: '25px', color: '#ffe9a8', align: 'center', wordWrap: { width: SLATE.w - 40 } }).setOrigin(0.5).setDepth(D + 1),
sub: s.add.text(sx, SLATE.y + 254, '', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: CHALK_DIM, align: 'center', wordWrap: { width: SLATE.w - 44 } }).setOrigin(0.5).setDepth(D + 1),
};
// ledger
s.add.image(LEDGER.x - 14, LEDGER.y - 14, 'bg-ledger').setOrigin(0).setDepth(D);
this.ledgerLines = [];
for (let i = 0; i < 11; i++) {
this.ledgerLines.push(s.add.text(LEDGER.x + 10, LEDGER.y + 62 + i * 26, '', {
fontFamily: HAND_FONT, fontSize: '17px', color: '#22303c',
}).setOrigin(0, 0.5).setDepth(D + 1));
}
// buttons
const label = { double: 'Double (D)', hint: 'Hint (H)', undo: 'Undo (Z)', done: 'Done (Space)' };
const bg = { double: 0x7a2420, hint: 0x2f5577, undo: 0x6a4a1a, done: 0x2f6e3a };
BUTTONS.forEach((k, i) => {
this.buttons[k] = new Button(s, BTN.x, BTN.y0 + i * BTN.gap, label[k], () => this.onButton(k), {
width: BTN.w, height: BTN.h, fontSize: 17, bg: bg[k],
}).setDepth(D + 3);
this.buttons[k].setEnabled(false);
});
this.menuBtn = new Button(s, MENU_BTN.x, MENU_BTN.y, 'Menu (Esc)', () => this.onMenu(), {
width: MENU_BTN.w, height: MENU_BTN.h, fontSize: 17, bg: 0x22445f,
}).setDepth(D + 3);
return this;
}
setButton(k, enabled, labelText) {
const b = this.buttons[k];
if (!b) return;
b.setEnabled(!!enabled);
if (labelText) b.setLabel(labelText);
}
setActive(color) {
for (const c of ['white', 'black']) {
const g = this.rings[c];
g.clear();
if (c !== color) continue;
const P = c === 'white' ? HUMAN_PLATE : OPP_PLATE;
const pp = c === 'white' ? HUMAN_PARTS.portrait : OPP_PARTS.portrait;
g.lineStyle(5, 0xf5c542, 1).strokeRoundedRect(P.x - 4, P.y - 4, P.w + 8, P.h + 8, 16);
g.lineStyle(4, 0xf5c542, 1).strokeCircle(pp.x, pp.y, pp.r + 6);
}
}
setPips(w, b, show = true) {
this.pipText.white.setText(show ? `${w} pips` : '');
this.pipText.black.setText(show ? `${b} pips` : '');
this.chk.white.setVisible(show); this.chk.black.setVisible(show);
// race bar on the slate: who leads and by how much
const g = this.slate.race;
g.clear();
const x0 = SLATE.x + 30, x1 = SLATE.x + SLATE.w - 30, y = SLATE.y + 136;
g.lineStyle(2, 0xecebe4, 0.5).lineBetween(x0, y, x1, y);
if (!show) { this.slate.raceText.setText(''); return; }
const diff = b - w; // > 0: you lead
const k = Math.max(-1, Math.min(1, diff / 60));
const mid = (x0 + x1) / 2;
g.lineStyle(6, diff >= 0 ? 0xbfe3a8 : 0xf0a18e, 0.9).lineBetween(mid, y, mid + k * (x1 - x0) / 2, y);
g.fillStyle(0xecebe4, 1).fillCircle(mid, y, 3);
this.slate.raceText.setText(diff === 0 ? 'Race: dead even' : diff > 0 ? `Race: you lead by ${diff}` : `Race: ${this.names.black} leads by ${-diff}`);
}
setMatch(match, cube, crawford, cubeEnabled) {
const sl = this.slate;
if (match.length > 0) {
sl.head.setText(`Match to ${match.length}`);
sl.score.setText(`You ${match.score.white} · ${this.short(this.names.black)} ${match.score.black}`);
} else {
sl.head.setText('Single game');
sl.score.setText(match.games.length ? `Tonight: You ${match.score.white} · ${this.short(this.names.black)} ${match.score.black}` : 'Bear off all fifteen');
}
let c;
if (crawford) c = 'Crawford game — no doubling';
else if (!cubeEnabled) c = 'Doubling cube off';
else if (cube.value === 1) c = 'Cube in the middle';
else c = `Cube at ${cube.value} · ${cube.owner === 'white' ? 'yours' : `${this.short(this.names.black)}'s`}`;
sl.cube.setText(c);
}
short(n) { return n.length > 9 ? n.slice(0, 8) + '…' : n; }
setStatus(main, sub = '') {
this.slate.status.setText(main);
this.slate.sub.setText(sub);
}
setLedger(log) {
const lines = log.slice(-this.ledgerLines.length);
this.ledgerLines.forEach((t, i) => {
const e = lines[i];
if (!e) { t.setText(''); return; }
const who = e.player === 'white' ? 'You' : this.short(this.names.black);
const dice = e.dice ? ` ${e.dice[0]}-${e.dice[1]}` : '';
t.setText(`${who}${dice} ${e.text}`).setColor(INK[e.player] ?? '#22303c');
// keep long lines inside the pad
t.setFontSize(t.text.length > 24 ? 14 : 17);
});
}
say(text, dur = 2400) {
const s = this.scene;
this.bubble?.destroy();
const b = OPP_PARTS.bubble;
const t = s.add.text(b.x + 16, b.y + b.h / 2, text, {
fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#22303c', wordWrap: { width: b.w - 28 },
}).setOrigin(0, 0.5);
const w = b.w, h = Math.max(42, t.height + 20);
t.setPosition(b.x + w / 2, b.y + 8 + h / 2).setOrigin(0.5).setAlign('center');
const g = s.add.graphics();
const y0 = b.y + 8;
g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, y0 + 4, w, h, 12);
g.fillStyle(0xfbf8ef, 1).fillRoundedRect(b.x, y0, w, h, 12);
g.lineStyle(2, 0x7a2420, 1).strokeRoundedRect(b.x, y0, w, h, 12);
// tail pointing up at the portrait
g.fillStyle(0xfbf8ef, 1).fillTriangle(b.x + w / 2 - 10, y0 + 1, b.x + w / 2 + 10, y0 + 1, b.x + w / 2, y0 - 14);
g.lineStyle(2, 0x7a2420, 1).lineBetween(b.x + w / 2 - 10, y0, b.x + w / 2, y0 - 14).lineBetween(b.x + w / 2 + 10, y0, b.x + w / 2, y0 - 14);
const c = s.add.container(0, 0, [g, t]).setDepth(this.depth + 6).setAlpha(0);
this.bubble = c;
s.tweens.add({ targets: c, alpha: 1, duration: 160 });
s.tweens.add({ targets: c, alpha: 0, delay: dur, duration: 300, onComplete: () => { c.destroy(); if (this.bubble === c) this.bubble = null; } });
}
emotion(color, e) { this.portraits[color]?.playEmotion?.(e); }
hidePortraits() { Object.values(this.portraits).forEach((p) => p?.setVideoVisible?.(false)); }
showPortraits() { Object.values(this.portraits).forEach((p) => p?.setVideoVisible?.(true)); }
}

View File

@ -0,0 +1,201 @@
// BackgammonLayout.js — every screen rect for the seaside tavli table, plus the
// board geometry (points, stacks, bar, bear-off tray, dice fields, cube).
// Phaser-free (tools/verifyBackgammon.js checks overlaps and bounds).
//
// ┌ opponent ┐ ┌──────────── olive-wood case ─────────────┬tray┐ ┌ menu ─────┐
// │ plate │ │ 13 … 18 │bar│ 19 … 24 │ ▭▭ │ │ their cup │
// │ slate │ │ │ ⧈ │ │ │ │ ledger │
// │ tea │ │ 12 … 7 │ │ 6 … 1 (your home) │ ▭▭ │ │ buttons │
// │ you │ └─────────┴───┴────────────────────────────┴────┘ │ your cup │
//
// `mirror` puts your home board (and the tray) on the left instead.
export const W = 1920;
export const H = 1080;
// ── The case ────────────────────────────────────────────────────────────────
export const CASE = { x: 316, y: 40, w: 1326, h: 1000 };
export const FRAME = 30;
export const FY = CASE.y + FRAME; // field top (70)
export const FH = CASE.h - FRAME * 2; // field height (940)
export const PW = 88; // point width
export const PH = 396; // triangle height
export const CR = 38; // checker radius
export const HALF_W = PW * 6; // 528
export const BAR_W = 76;
export const TRAY_W = 104;
export const MID_Y = FY + FH / 2; // 540
export const CASE_CX = CASE.x + CASE.w / 2; // 979
export const DIE_SIZE = 52;
export const TIERS = [5, 4, 3, 2, 1]; // pyramid stacking: 15 checkers max
// un-mirrored x extents
const LEFT_X = CASE.x + FRAME; // 346
const BAR_X = LEFT_X + HALF_W; // 874
const RIGHT_X = BAR_X + BAR_W; // 950
const TRAY_X = RIGHT_X + HALF_W + FRAME; // 1508
// ── HUD furniture (never mirrored) ───────────────────────────────────────────
export const OPP_PLATE = { x: 24, y: 36, w: 268, h: 268 };
export const SLATE = { x: 24, y: 330, w: 268, h: 300 };
export const TEA = { x: 72, y: 648, w: 150, h: 112 }; // tea glass + saucer prop
export const HUMAN_PLATE = { x: 24, y: 776, w: 268, h: 268 };
export const MENU_BTN = { x: 1782, y: 34, w: 200, h: 44 };
export const AI_CUP = { x: 1782, y: 168, w: 120, h: 150 }; // centre
export const LEDGER = { x: 1664, y: 262, w: 236, h: 352 };
export const BTN = { x: 1782, w: 220, h: 46, y0: 652, gap: 56 };
export const HUMAN_CUP = { x: 1782, y: 952, w: 120, h: 150 }; // centre
export const BEADS = { x: 560, y: 1040, w: 300, h: 40 }; // komboloi draped over the table edge
export const BANNER = { x: CASE_CX, y: MID_Y - 40 };
export const OPP_PARTS = {
portrait: { x: OPP_PLATE.x + OPP_PLATE.w / 2, y: OPP_PLATE.y + 100, r: 70 },
name: { x: OPP_PLATE.x + OPP_PLATE.w / 2, y: OPP_PLATE.y + 192 },
skill: { x: OPP_PLATE.x + OPP_PLATE.w / 2, y: OPP_PLATE.y + 218 },
pips: { x: OPP_PLATE.x + OPP_PLATE.w / 2, y: OPP_PLATE.y + 246 },
// speech bubble hangs under the plate (over the slate's top) so it never hides the board
bubble: { x: OPP_PLATE.x + 8, y: OPP_PLATE.y + OPP_PLATE.h + 6, w: OPP_PLATE.w - 16, h: 66 },
};
export const HUMAN_PARTS = {
pips: { x: HUMAN_PLATE.x + HUMAN_PLATE.w / 2, y: HUMAN_PLATE.y + 24 },
name: { x: HUMAN_PLATE.x + HUMAN_PLATE.w / 2, y: HUMAN_PLATE.y + 54 },
portrait: { x: HUMAN_PLATE.x + HUMAN_PLATE.w / 2, y: HUMAN_PLATE.y + 164, r: 70 },
};
export function buttonRect(i) {
return { x: BTN.x - BTN.w / 2, y: BTN.y0 + i * BTN.gap - BTN.h / 2, w: BTN.w, h: BTN.h };
}
export const BUTTONS = ['double', 'hint', 'undo', 'done'];
export function hudFurniture() {
return {
case: CASE,
oppPlate: OPP_PLATE,
slate: SLATE,
tea: TEA,
humanPlate: HUMAN_PLATE,
menu: { x: MENU_BTN.x - MENU_BTN.w / 2, y: MENU_BTN.y - MENU_BTN.h / 2, w: MENU_BTN.w, h: MENU_BTN.h },
aiCup: { x: AI_CUP.x - AI_CUP.w / 2, y: AI_CUP.y - AI_CUP.h / 2, w: AI_CUP.w, h: AI_CUP.h },
ledger: LEDGER,
...Object.fromEntries(BUTTONS.map((k, i) => [`btn_${k}`, buttonRect(i)])),
humanCup: { x: HUMAN_CUP.x - HUMAN_CUP.w / 2, y: HUMAN_CUP.y - HUMAN_CUP.h / 2, w: HUMAN_CUP.w, h: HUMAN_CUP.h },
};
}
// ── Board geometry ───────────────────────────────────────────────────────────
export function makeLayout(mirror = false) {
const mx = (x) => (mirror ? 2 * CASE_CX - x : x);
const rectX = (x, w) => (mirror ? 2 * CASE_CX - x - w : x);
// Column of a point (0 = leftmost) within its half, before mirroring.
function pointCol(idx) {
if (idx < 6) return { right: true, col: 5 - idx }; // 1–6: bottom right, 1 at the far right
if (idx < 12) return { right: false, col: 11 - idx }; // 7–12: bottom left
if (idx < 18) return { right: false, col: idx - 12 }; // 13–18: top left
return { right: true, col: idx - 18 }; // 19–24: top right
}
function pointX(idx) {
const { right, col } = pointCol(idx);
return mx((right ? RIGHT_X : LEFT_X) + col * PW + PW / 2);
}
const isBottom = (idx) => idx < 12;
const edgeY = (idx) => (isBottom(idx) ? FY + FH : FY);
// Triangle drawing coords (left base x, right base x, tip y, base y).
function triangle(idx) {
const cx = pointX(idx);
return { ax: cx - PW / 2, bx: cx + PW / 2, tipY: isBottom(idx) ? FY + FH - PH : FY + PH, baseY: edgeY(idx) };
}
// Click / hover zone for a point: its whole half-column.
function pointZone(idx) {
const cx = pointX(idx);
return isBottom(idx)
? { x: cx - PW / 2, y: MID_Y + 4, w: PW, h: FH / 2 - 4 }
: { x: cx - PW / 2, y: FY, w: PW, h: FH / 2 - 4 };
}
// Stack slot s (0 = against the rail) as a pyramid of tiers.
function stackSlot(s) {
let t = 0, k = s;
while (t < TIERS.length - 1 && k >= TIERS[t]) { k -= TIERS[t]; t++; }
return { tier: t, k };
}
function slotPos(idx, s) {
const { tier, k } = stackSlot(s);
const dir = isBottom(idx) ? -1 : 1;
const off = CR + tier * CR + k * CR * 2;
return { x: pointX(idx), y: edgeY(idx) + dir * off, tier };
}
const barX = mx(BAR_X + BAR_W / 2);
// White (you) sit below the hinge's middle, Black above.
function barPos(color, s, count) {
// compress long queues so they never reach the cube parked at the rail end
const sp = count > 1 ? Math.min(CR * 2, 252 / (count - 1)) : CR * 2;
const y = color === 'white' ? MID_Y + 100 + s * sp : MID_Y - 100 - s * sp;
return { x: barX, y, tier: s };
}
const barZone = { x: barX - BAR_W / 2, y: FY, w: BAR_W, h: FH };
const trayX = mx(TRAY_X + TRAY_W / 2);
const OFF_STEP = 14;
// Borne-off checkers stand on edge, stacked from the tray's outer end inwards.
function offPos(color, s) {
return color === 'white'
? { x: trayX, y: FY + FH - 12 - s * OFF_STEP }
: { x: trayX, y: FY + 12 + s * OFF_STEP };
}
const trayZone = (color) => (color === 'white'
? { x: trayX - TRAY_W / 2, y: MID_Y + 15, w: TRAY_W, h: FH / 2 - 15 }
: { x: trayX - TRAY_W / 2, y: FY, w: TRAY_W, h: FH / 2 - 15 });
function cubePos(owner) {
if (owner === 'white') return { x: barX, y: FY + FH - 48 };
if (owner === 'black') return { x: barX, y: FY + 48 };
return { x: barX, y: MID_Y };
}
// Dice fields: you throw into your home-side half, the opponent into theirs.
const homeField = { x: rectX(RIGHT_X, HALF_W), y: FY, w: HALF_W, h: FH };
const outerField = { x: rectX(LEFT_X, HALF_W), y: FY, w: HALF_W, h: FH };
const field = (who) => (who === 'white' ? homeField : outerField);
const TRAY_WORLD = { w: HALF_W, h: FH };
const groundFor = (who) => {
const f = field(who);
return (u, v) => ({ x: f.x + u, y: f.y + v, s: 1 });
};
const toFieldWorld = (who, x, y) => {
const f = field(who);
return { u: x - f.x, v: y - f.y };
};
// where dice settle after a throw (2 or 4 of them), in field-world coords
function diceRest(n) {
const us = n === 4 ? [0.2, 0.4, 0.6, 0.8] : n === 1 ? [0.5] : [0.38, 0.62];
return us.map((u) => ({ u: HALF_W * u, v: FH / 2 }));
}
function throwOrigin(who) {
// you throw from the near (bottom) rail on your cup's side; they from the far rail
if (who === 'white') return { u: mirror ? HALF_W * 0.15 : HALF_W * 0.85, v: FH * 0.9, h: 150 };
return { u: mirror ? HALF_W * 0.75 : HALF_W * 0.25, v: FH * 0.1, h: 150 };
}
// Inverse: which point / bar / tray is under (x, y)?
function hitTest(x, y) {
const inR = (r) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
if (inR(barZone)) return 'bar';
if (inR(trayZone('white')) || inR(trayZone('black'))) return 'off';
for (let idx = 0; idx < 24; idx++) if (inR(pointZone(idx))) return idx;
return null;
}
return {
mirror, mx, pointX, isBottom, edgeY, triangle, pointZone, stackSlot, slotPos,
barX, barPos, barZone, trayX, offPos, trayZone, cubePos,
field, TRAY_WORLD, groundFor, toFieldWorld, diceRest, throwOrigin, hitTest,
};
}
// Point label shown on the rail, from your (White's) side: idx + 1.
export const pointLabel = (idx) => String(idx + 1);

View File

@ -1,28 +1,61 @@
// Pure game logic — no Phaser dependency. // BackgammonLogic.js — pure backgammon rules. No Phaser dependency.
// Convention: point indices 0–23 (0 = point 1, White's home ace-point). //
// White moves high→low (23→0), bears off past index 0. // State convention (unchanged from v1 so saved notes and the tutorial agree):
// Black moves low→high (0→23), bears off past index 23. // point indices 0–23; index 0 = White's 1-point (the human plays White).
// White home board: indices 0–5. Black home board: indices 18–23. // White moves 23 → 0 and bears off past 0 (home board 0–5).
// Black moves 0 → 23 and bears off past 23 (home board 18–23).
//
// The move generator works in "mover perspective": two Int8Array(26) boards
// me / op where i = 0 is that side's ace point, 23 its 24-point, 24 its bar and
// 25 its borne-off tray. My point k is the opponent's point 23 − k.
//
// Rules implemented: opening roll (higher die starts and plays both dice),
// maximum-dice rule (play both dice if possible, the higher one if only one can
// be played; as many of a double as possible), bar entry, bearing off with
// overshoot, hits, the doubling cube (offer / take / drop, owner, Crawford via
// options), gammons and backgammons, Jacoby (money games only, optional), and
// matches to N points.
export function createInitialState() { export const WHITE = 'white';
export const BLACK = 'black';
export const other = (p) => (p === WHITE ? BLACK : WHITE);
export const CHECKERS = 15;
export const MAX_CUBE = 64;
// ── State ────────────────────────────────────────────────────────────────────
function freshStats() {
return { rolls: 0, pips: 0, doubles: 0, hits: 0, hitTaken: 0, barTurns: 0, dances: 0, doublesOffered: 0, pipsWasted: 0 };
}
export function createInitialState(opts = {}) {
const points = Array.from({ length: 24 }, () => ({ color: null, count: 0 })); const points = Array.from({ length: 24 }, () => ({ color: null, count: 0 }));
points[23] = { color: 'white', count: 2 }; points[23] = { color: WHITE, count: 2 };
points[12] = { color: 'white', count: 5 }; points[12] = { color: WHITE, count: 5 };
points[7] = { color: 'white', count: 3 }; points[7] = { color: WHITE, count: 3 };
points[5] = { color: 'white', count: 5 }; points[5] = { color: WHITE, count: 5 };
points[0] = { color: 'black', count: 2 }; points[0] = { color: BLACK, count: 2 };
points[11] = { color: 'black', count: 5 }; points[11] = { color: BLACK, count: 5 };
points[16] = { color: 'black', count: 3 }; points[16] = { color: BLACK, count: 3 };
points[18] = { color: 'black', count: 5 }; points[18] = { color: BLACK, count: 5 };
return { return {
points, points,
bar: { white: 0, black: 0 }, bar: { white: 0, black: 0 },
borneOff: { white: 0, black: 0 }, borneOff: { white: 0, black: 0 },
dice: null, dice: null,
movesLeft: [], movesLeft: [],
currentPlayer: 'white', currentPlayer: WHITE,
phase: 'roll', phase: 'opening', // opening | roll | double | move | game_over
opening: null, // { white, black } faces of the last opening throw
winner: null, winner: null,
result: null, // { winner, kind, multiplier, cube, points }
cube: { value: 1, owner: null },
pendingDouble: null, // the player who offered
cubeEnabled: opts.cubeEnabled ?? true,
jacoby: !!opts.jacoby,
turn: 0,
stats: { white: freshStats(), black: freshStats() },
pipHistory: [{ white: 167, black: 167 }],
log: [],
}; };
} }
@ -30,10 +63,291 @@ export function cloneState(state) {
return JSON.parse(JSON.stringify(state)); return JSON.parse(JSON.stringify(state));
} }
export function rollDice(state) { // ── Perspective boards ───────────────────────────────────────────────────────
const d1 = Math.ceil(Math.random() * 6); // idx ↔ own point: White's own point i is idx i; Black's own point i is idx 23 − i.
const d2 = Math.ceil(Math.random() * 6); export const toIdx = (player, i) => (player === WHITE ? i : 23 - i);
return rollSpecificDice(state, d1, d2); export const toOwn = (player, idx) => (player === WHITE ? idx : 23 - idx);
export function boardOf(state, player) {
const b = new Int8Array(26);
for (let i = 0; i < 24; i++) {
const pt = state.points[toIdx(player, i)];
if (pt.color === player) b[i] = pt.count;
}
b[24] = state.bar[player];
b[25] = state.borneOff[player];
return b;
}
export function boardsFor(state, player) {
return { me: boardOf(state, player), op: boardOf(state, other(player)) };
}
// Write perspective boards back into a state's points / bar / off.
function writeBoards(s, player, me, op) {
const opp = other(player);
for (let idx = 0; idx < 24; idx++) s.points[idx] = { color: null, count: 0 };
for (let i = 0; i < 24; i++) {
if (me[i]) s.points[toIdx(player, i)] = { color: player, count: me[i] };
if (op[i]) s.points[toIdx(opp, i)] = { color: opp, count: op[i] };
}
s.bar[player] = me[24]; s.bar[opp] = op[24];
s.borneOff[player] = me[25]; s.borneOff[opp] = op[25];
}
export function canBearOffP(me) {
for (let i = 6; i <= 24; i++) if (me[i]) return false;
return true;
}
// Single-die moves in perspective. Calls push(from, to, hit) where from is
// 0..24 (24 = bar) and to is 0..23 or −1 (borne off).
export function forEachStep(me, op, die, push) {
if (me[24] > 0) {
const to = 24 - die;
const o = op[23 - to];
if (o < 2) push(24, to, o === 1);
return;
}
const bear = canBearOffP(me);
for (let i = 23; i >= 0; i--) {
if (!me[i]) continue;
const to = i - die;
if (to >= 0) {
const o = op[23 - to];
if (o < 2) push(i, to, o === 1);
} else if (bear) {
if (to === -1) push(i, -1, false);
else {
let higher = false;
for (let k = i + 1; k < 6; k++) if (me[k]) { higher = true; break; }
if (!higher) push(i, -1, false);
}
}
}
}
// Mutating single step on perspective boards.
export function stepP(me, op, from, to) {
me[from]--;
if (to < 0) { me[25]++; return false; }
me[to]++;
const j = 23 - to;
if (op[j] === 1) { op[j] = 0; op[24]++; return true; }
return false;
}
export function posKey(me, op) {
return String.fromCharCode.apply(null, me) + String.fromCharCode.apply(null, op);
}
// Every legal complete turn for remaining dice `dice` (array of 1–4 values),
// obeying the maximum-dice and higher-die rules, de-duplicated by the final
// position. Each result: { seq: [[from, to, die, hit], …], me, op }.
export function enumerateTurns(me, op, dice) {
const leaves = [];
const seen = new Map();
let maxUsed = 0;
const isDouble = dice.length > 1 && dice.every((d) => d === dice[0]);
const record = (m, o, seq) => {
const used = seq.length;
if (used < maxUsed) return;
const key = posKey(m, o);
if (used > maxUsed) { maxUsed = used; leaves.length = 0; seen.clear(); }
if (seen.has(key)) return;
seen.set(key, true);
leaves.push({ seq, me: m, op: o, key });
};
if (isDouble) {
const d = dice[0];
const n = dice.length;
const rec = (m, o, seq, lastFrom) => {
if (seq.length === n) { record(m, o, seq); return; }
let any = false;
forEachStep(m, o, d, (from, to, hit) => {
if (from > lastFrom) return; // canonical order: non-increasing sources
any = true;
const m2 = m.slice(), o2 = o.slice();
stepP(m2, o2, from, to);
rec(m2, o2, seq.concat([[from, to, d, hit]]), from);
});
if (!any) record(m, o, seq);
};
rec(me, op, [], 24);
} else {
const orders = dice.length === 2 ? [[dice[0], dice[1]], [dice[1], dice[0]]] : [dice.slice()];
for (const order of orders) {
const rec = (m, o, seq, k) => {
if (k === order.length) { record(m, o, seq); return; }
let any = false;
forEachStep(m, o, order[k], (from, to, hit) => {
any = true;
const m2 = m.slice(), o2 = o.slice();
stepP(m2, o2, from, to);
rec(m2, o2, seq.concat([[from, to, order[k], hit]]), k + 1);
});
if (!any) {
// this die can't be played now; maybe the remaining one can
if (k === 0 && order.length === 2) {
let any2 = false;
forEachStep(m, o, order[1], (from, to, hit) => {
any2 = true;
const m2 = m.slice(), o2 = o.slice();
stepP(m2, o2, from, to);
record(m2, o2, seq.concat([[from, to, order[1], hit]]));
});
if (!any2) record(m, o, seq);
} else record(m, o, seq);
}
};
rec(me, op, [], 0);
}
// higher-die rule: only one die playable (and the dice differ) → the higher
if (maxUsed === 1 && dice.length === 2 && dice[0] !== dice[1]) {
const hi = Math.max(dice[0], dice[1]);
if (leaves.some((l) => l.seq[0][2] === hi)) {
const keep = leaves.filter((l) => l.seq[0][2] === hi);
leaves.length = 0; leaves.push(...keep);
}
}
}
if (!leaves.length) leaves.push({ seq: [], me: me.slice(), op: op.slice(), key: posKey(me, op) });
return leaves;
}
// ── State-level moves ────────────────────────────────────────────────────────
// A move: { from: idx | 'bar', to: idx | 'off', dieUsed, hit }
function toStateMove(player, [from, to, die, hit]) {
return {
from: from === 24 ? 'bar' : toIdx(player, from),
to: to < 0 ? 'off' : toIdx(player, to),
dieUsed: die,
hit: !!hit,
};
}
const turnCache = new WeakMap();
// All maximal turns for the current roll from the current position.
export function legalTurns(state) {
if (state.phase !== 'move' || !state.movesLeft.length) return [];
if (turnCache.has(state)) return turnCache.get(state);
const player = state.currentPlayer;
const { me, op } = boardsFor(state, player);
const turns = enumerateTurns(me, op, state.movesLeft).map((t) => ({
moves: t.seq.map((m) => toStateMove(player, m)),
key: t.key,
}));
turnCache.set(state, turns);
return turns;
}
const moveCache = new WeakMap();
// Legal single moves right now: every step after which the rest of the roll
// can still be played to the maximum (and, when only one die can be played at
// all, the higher die if it can be). Checked step by step rather than taken
// from the de-duplicated turns, so every ordering of a legal turn is offered.
export function getValidMoves(state) {
if (moveCache.has(state)) return moveCache.get(state);
const out = [];
const turns = legalTurns(state);
const maxLen = turns.length ? turns[0].moves.length : 0;
if (maxLen > 0) {
const player = state.currentPlayer;
const { me, op } = boardsFor(state, player);
const dice = state.movesLeft;
const distinct = [...new Set(dice)];
// with one playable die out of two different ones, the turns already say which
const onlyDie = maxLen === 1 && dice.length === 2 && dice[0] !== dice[1] ? turns[0].moves[0].dieUsed : null;
const seen = new Set();
for (const d of distinct) {
if (onlyDie !== null && d !== onlyDie) continue;
const rest = dice.slice();
rest.splice(rest.indexOf(d), 1);
forEachStep(me, op, d, (from, to, hit) => {
const k = `${from}|${to}|${d}`;
if (seen.has(k)) return;
seen.add(k);
let can = 1;
if (rest.length) {
const m2 = me.slice(), o2 = op.slice();
stepP(m2, o2, from, to);
can += enumerateTurns(m2, o2, rest)[0].seq.length;
}
if (can === maxLen) out.push(toStateMove(player, [from, to, d, hit]));
});
}
}
moveCache.set(state, out);
return out;
}
export function hasAnyMove(state) {
return getValidMoves(state).length > 0;
}
// The player has nothing more to play this roll.
export function turnDone(state) {
return state.phase === 'move' && (state.movesLeft.length === 0 || getValidMoves(state).length === 0);
}
// Same-checker paths from `from` (combined moves): [{ to, moves: [...] }] for
// each distinct landing reachable by moving only that checker, every step legal.
export function checkerPaths(state, from) {
const out = [];
const seen = new Set();
const rec = (s, at, chain) => {
if (s.phase !== 'move') return;
for (const m of getValidMoves(s)) {
if (m.from !== at) continue;
const next = chain.concat([m]);
const key = `${m.to}|${next.length}`;
if (!seen.has(key)) {
seen.add(key);
out.push({ to: m.to, moves: next });
}
if (m.to !== 'off') {
const s2 = applyMove(s, m);
if (s2.phase === 'move' && s2.movesLeft.length) rec(s2, m.to, next);
}
}
};
rec(state, from, []);
// keep the shortest chain for each destination
const best = new Map();
for (const p of out) {
const cur = best.get(p.to);
if (!cur || p.moves.length < cur.moves.length) best.set(p.to, p);
}
return [...best.values()];
}
// ── Dice ─────────────────────────────────────────────────────────────────────
const d6 = (rng) => 1 + Math.floor(rng() * 6);
export function rollOpening(state, rng = Math.random) {
return openingWith(state, d6(rng), d6(rng));
}
export function openingWith(state, w, b) {
const s = cloneState(state);
s.opening = { white: w, black: b };
if (w === b) { s.phase = 'opening'; return s; }
const starter = w > b ? WHITE : BLACK;
s.currentPlayer = starter;
s.dice = starter === WHITE ? [w, b] : [b, w];
s.movesLeft = [w, b];
s.phase = 'move';
s.turn = 1;
noteRoll(s, starter, s.dice);
return s;
}
export function rollDice(state, rng = Math.random) {
return rollSpecificDice(state, d6(rng), d6(rng));
} }
export function rollSpecificDice(state, d1, d2) { export function rollSpecificDice(state, d1, d2) {
@ -41,179 +355,221 @@ export function rollSpecificDice(state, d1, d2) {
s.dice = [d1, d2]; s.dice = [d1, d2];
s.movesLeft = d1 === d2 ? [d1, d1, d1, d1] : [d1, d2]; s.movesLeft = d1 === d2 ? [d1, d1, d1, d1] : [d1, d2];
s.phase = 'move'; s.phase = 'move';
s.turn = (s.turn || 0) + 1;
noteRoll(s, s.currentPlayer, s.dice);
if (!getValidMoves(s).length && s.bar[s.currentPlayer] > 0) s.stats[s.currentPlayer].dances++;
return s;
}
function noteRoll(s, player, [a, b]) {
const st = s.stats[player];
st.rolls++;
st.pips += a === b ? 4 * a : a + b;
if (a === b) st.doubles++;
if (s.bar[player] > 0) st.barTurns++;
}
// ── Applying moves ───────────────────────────────────────────────────────────
// Applies one move and consumes its die. Does NOT end the turn (the human may
// still undo); call endTurn() once turnDone(). Ends the game when the last
// checker is borne off.
export function applyMove(state, move) {
const s = cloneState(state);
const player = s.currentPlayer;
const opp = other(player);
if (move.from === 'bar') s.bar[player] = Math.max(0, s.bar[player] - 1);
else {
const pt = s.points[move.from];
pt.count--;
if (pt.count <= 0) { pt.count = 0; pt.color = null; }
}
if (move.to === 'off') {
s.borneOff[player]++;
const own = toOwn(player, move.from);
s.stats[player].pipsWasted += Math.max(0, move.dieUsed - (own + 1));
} else {
const pt = s.points[move.to];
if (pt.color === opp && pt.count === 1) {
pt.count = 0; pt.color = null;
s.bar[opp]++;
s.stats[player].hits++;
s.stats[opp].hitTaken++;
}
pt.color = player;
pt.count++;
}
const di = s.movesLeft.indexOf(move.dieUsed);
if (di !== -1) s.movesLeft.splice(di, 1);
if (s.borneOff[player] >= CHECKERS) finishGame(s, player);
return s; return s;
} }
export function endTurn(state) { export function endTurn(state) {
const s = cloneState(state); const s = cloneState(state);
s.currentPlayer = s.currentPlayer === 'white' ? 'black' : 'white'; if (s.phase === 'game_over') return s;
s.pipHistory.push({ white: computePipCount(s, WHITE), black: computePipCount(s, BLACK) });
s.currentPlayer = other(s.currentPlayer);
s.dice = null; s.dice = null;
s.movesLeft = []; s.movesLeft = [];
s.phase = 'roll'; s.phase = 'roll';
return s; return s;
} }
export function allCheckersInHome(state, player) { // ── Doubling cube ────────────────────────────────────────────────────────────
if (state.bar[player] > 0) return false; export function canDouble(state, player = state.currentPlayer) {
const [homeMin, homeMax] = player === 'white' ? [0, 5] : [18, 23]; return state.cubeEnabled && state.phase === 'roll' && state.currentPlayer === player
for (let i = 0; i < 24; i++) { && (state.cube.owner === null || state.cube.owner === player) && state.cube.value < MAX_CUBE;
if (i < homeMin || i > homeMax) {
if (state.points[i].color === player && state.points[i].count > 0) return false;
}
}
return true;
} }
// Furthest checker from the bear-off edge (by index): export function offerDouble(state) {
// White: highest index in 0–5 (index 5 = 6 pips away) if (!canDouble(state)) return state;
// Black: lowest index in 18–23 (index 18 = 6 pips away) const s = cloneState(state);
function furthestHomeChecker(state, player) { s.pendingDouble = s.currentPlayer;
const { points } = state; s.phase = 'double';
if (player === 'white') { s.stats[s.currentPlayer].doublesOffered++;
for (let i = 5; i >= 0; i--) { return s;
if (points[i].color === 'white' && points[i].count > 0) return i;
}
} else {
for (let i = 18; i <= 23; i++) {
if (points[i].color === 'black' && points[i].count > 0) return i;
}
}
return -1;
} }
export function getValidMoves(state) { export function takeDouble(state) {
const { currentPlayer: player, movesLeft, points, bar } = state; if (state.phase !== 'double') return state;
const opp = player === 'white' ? 'black' : 'white'; const s = cloneState(state);
const uniqueDice = [...new Set(movesLeft)]; s.cube.value *= 2;
const inBearOff = allCheckersInHome(state, player); s.cube.owner = other(s.pendingDouble);
const moves = []; s.pendingDouble = null;
s.phase = 'roll';
const isBlocked = (idx) => points[idx]?.color === opp && points[idx].count >= 2; return s;
const isHit = (idx) => points[idx]?.color === opp && points[idx].count === 1;
// Bar entry takes priority — only these moves if bar has checkers
if (bar[player] > 0) {
for (const die of uniqueDice) {
// White enters opposite side: die 1 → index 23, die 6 → index 18
// Black enters near side: die 1 → index 0, die 6 → index 5
const entryIdx = player === 'white' ? (24 - die) : (die - 1);
if (!isBlocked(entryIdx)) {
moves.push({ from: 'bar', to: entryIdx, dieUsed: die, hit: isHit(entryIdx) });
}
}
return dedup(moves);
} }
for (const die of uniqueDice) { export function dropDouble(state) {
for (let i = 0; i < 24; i++) { if (state.phase !== 'double') return state;
if (points[i].color !== player || points[i].count === 0) continue; const s = cloneState(state);
const winner = s.pendingDouble;
if (player === 'white') { s.pendingDouble = null;
const dest = i - die; s.winner = winner;
if (dest >= 0) {
if (!isBlocked(dest)) moves.push({ from: i, to: dest, dieUsed: die, hit: isHit(dest) });
} else if (inBearOff) {
if (dest === -1) {
// Exact bear-off (die == i + 1)
moves.push({ from: i, to: 'off', dieUsed: die, hit: false });
} else {
// Overshoot — only the furthest checker may be borne off
if (furthestHomeChecker(state, 'white') === i) {
moves.push({ from: i, to: 'off', dieUsed: die, hit: false });
}
}
}
} else {
const dest = i + die;
if (dest <= 23) {
if (!isBlocked(dest)) moves.push({ from: i, to: dest, dieUsed: die, hit: isHit(dest) });
} else if (inBearOff) {
if (dest === 24) {
// Exact bear-off (die == 24 - i)
moves.push({ from: i, to: 'off', dieUsed: die, hit: false });
} else {
// Overshoot
if (furthestHomeChecker(state, 'black') === i) {
moves.push({ from: i, to: 'off', dieUsed: die, hit: false });
}
}
}
}
}
}
return dedup(moves);
}
function dedup(moves) {
const seen = new Set();
return moves.filter((m) => {
const key = `${m.from}|${m.to}|${m.dieUsed}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
export function applyMove(state, move) {
let s = cloneState(state);
const player = s.currentPlayer;
const opp = player === 'white' ? 'black' : 'white';
// Remove from source
if (move.from === 'bar') {
s.bar[player] = Math.max(0, s.bar[player] - 1);
} else {
s.points[move.from].count--;
if (s.points[move.from].count === 0) s.points[move.from].color = null;
}
// Handle hit — send opponent blot to bar
if (move.hit && move.to !== 'off') {
s.points[move.to].count = 0;
s.points[move.to].color = null;
s.bar[opp]++;
}
// Place on destination
if (move.to === 'off') {
s.borneOff[player]++;
} else {
s.points[move.to].color = player;
s.points[move.to].count++;
}
// Consume the die
const dieIdx = s.movesLeft.indexOf(move.dieUsed);
if (dieIdx !== -1) s.movesLeft.splice(dieIdx, 1);
// Win check
if (s.borneOff[player] >= 15) {
s.winner = player;
s.phase = 'game_over'; s.phase = 'game_over';
s.result = { winner, kind: 'drop', multiplier: 1, cube: s.cube.value, points: s.cube.value };
return s; return s;
} }
// Auto-end turn if no dice remain or no legal moves remain // ── Game end ─────────────────────────────────────────────────────────────────
if (s.movesLeft.length === 0 || getValidMoves(s).length === 0) { export function gammonKind(state, winner) {
s = endTurn(s); const loser = other(winner);
if (state.borneOff[loser] > 0) return 'single';
if (state.bar[loser] > 0) return 'backgammon';
// any loser checker in the winner's home board
for (let i = 0; i < 6; i++) {
const pt = state.points[toIdx(winner, i)];
if (pt.color === loser && pt.count > 0) return 'backgammon';
}
return 'gammon';
} }
function finishGame(s, winner) {
s.winner = winner;
s.phase = 'game_over';
let kind = gammonKind(s, winner);
if (s.jacoby && s.cube.value === 1 && kind !== 'single') kind = 'single';
const multiplier = kind === 'backgammon' ? 3 : kind === 'gammon' ? 2 : 1;
s.result = { winner, kind, multiplier, cube: s.cube.value, points: s.cube.value * multiplier, jacobyWaived: s.jacoby && s.cube.value === 1 && gammonKind(s, winner) !== 'single' };
s.pipHistory.push({ white: computePipCount(s, WHITE), black: computePipCount(s, BLACK) });
}
// Resign / concede helper used by tests (not exposed in the UI).
export function resign(state, loser, kind = 'single') {
const s = cloneState(state);
const winner = other(loser);
const multiplier = kind === 'backgammon' ? 3 : kind === 'gammon' ? 2 : 1;
s.winner = winner; s.phase = 'game_over';
s.result = { winner, kind, multiplier, cube: s.cube.value, points: s.cube.value * multiplier };
return s; return s;
} }
export function hasAnyMove(state) {
return getValidMoves(state).length > 0;
}
export function computePipCount(state, player) { export function computePipCount(state, player) {
let pips = 0; let pips = 0;
for (let i = 0; i < 24; i++) { for (let idx = 0; idx < 24; idx++) {
const pt = state.points[i]; const pt = state.points[idx];
if (pt.color !== player || pt.count === 0) continue; if (pt.color !== player || pt.count === 0) continue;
const dist = player === 'white' ? (i + 1) : (24 - i); pips += (toOwn(player, idx) + 1) * pt.count;
pips += dist * pt.count;
} }
pips += state.bar[player] * 25; return pips + state.bar[player] * 25;
return pips; }
export function pipP(me) {
let p = me[24] * 25;
for (let i = 0; i < 24; i++) p += me[i] * (i + 1);
return p;
}
// Checker conservation (for tests and debug asserts).
export function checkerTotals(state) {
const t = { white: state.bar.white + state.borneOff.white, black: state.bar.black + state.borneOff.black };
for (const pt of state.points) if (pt.color) t[pt.color] += pt.count;
return t;
}
// ── Notation ─────────────────────────────────────────────────────────────────
// "13/7 8/7*" style, from the mover's own point numbers.
export function moveText(player, m) {
const f = m.from === 'bar' ? 'bar' : String(toOwn(player, m.from) + 1);
const t = m.to === 'off' ? 'off' : String(toOwn(player, m.to) + 1);
return `${f}/${t}${m.hit ? '*' : ''}`;
}
export function turnText(player, moves) {
if (!moves.length) return '(no move)';
const counts = new Map();
for (const m of moves) {
const k = moveText(player, m);
counts.set(k, (counts.get(k) ?? 0) + 1);
}
return [...counts].map(([k, n]) => (n > 1 ? `${k}(${n})` : k)).join(' ');
}
export function logTurn(state, player, dice, moves) {
const s = cloneState(state);
s.log.push({ player, dice: dice ? dice.slice() : null, text: turnText(player, moves) });
if (s.log.length > 200) s.log.splice(0, s.log.length - 200);
return s;
}
export function logEvent(state, player, text) {
const s = cloneState(state);
s.log.push({ player, dice: null, text });
if (s.log.length > 200) s.log.splice(0, s.log.length - 200);
return s;
}
// ── Matches ──────────────────────────────────────────────────────────────────
// length 0 = a single (money-style) game.
export function createMatch(length = 0) {
return { length, score: { white: 0, black: 0 }, crawford: false, hadCrawford: false, games: [], over: false, winner: null };
}
export function recordGame(match, result) {
const m = JSON.parse(JSON.stringify(match));
m.games.push({ winner: result.winner, points: result.points, kind: result.kind, crawford: m.crawford });
m.score[result.winner] += result.points;
const wasCrawford = m.crawford;
m.crawford = false;
if (m.length <= 0) { m.over = true; m.winner = result.winner; return m; }
if (m.score[result.winner] >= m.length) { m.over = true; m.winner = result.winner; return m; }
if (!m.hadCrawford && !wasCrawford) {
const atMatchPoint = [WHITE, BLACK].filter((p) => m.score[p] === m.length - 1);
if (atMatchPoint.length === 1) { m.crawford = true; m.hadCrawford = true; }
}
return m;
}
// Options for the next game of a match.
export function gameOptions(match, { cube = true, jacoby = false } = {}) {
return { cubeEnabled: cube && !match.crawford, jacoby: jacoby && match.length <= 0 };
}
export function matchLabel(match) {
if (match.length <= 0) return 'Single game';
return `Match to ${match.length}`;
} }

View File

@ -0,0 +1,173 @@
// BackgammonSound.js — tiny Web Audio synths for a wooden tavli case. No audio
// files; silently does nothing without Web Audio or when the game is muted.
//
// clack(scene, { stack }) a checker set down (higher stacks ring a touch higher)
// slam(scene) the tavli slam: a hit, or a proud last move
// tap(scene) a light pick-up tick
// skitter(scene, { n }) dice skittering on leather
// bell(scene) a soft bell when the bear-off begins
// cubeTurn(scene) the cube being turned
// Waves looped sea-swell ambience (start / stop / setOn)
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 * 1.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;
}
// A wooden knock: a low body thump + a band-passed click.
function knock(ac, dest, t0, { freq = 950, vol = 1, body = 0.8, decay = 0.07 } = {}) {
const o = ac.createOscillator();
o.type = 'triangle';
o.frequency.setValueAtTime(freq, t0);
o.frequency.exponentialRampToValueAtTime(freq * 0.6, t0 + decay);
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(vol * 0.7, t0 + 0.002);
g.gain.exponentialRampToValueAtTime(0.0005, t0 + decay);
o.connect(g); g.connect(dest);
o.start(t0); o.stop(t0 + decay + 0.02);
const b = ac.createOscillator();
b.type = 'sine';
b.frequency.setValueAtTime(170, t0);
b.frequency.exponentialRampToValueAtTime(90, t0 + 0.09);
const bg = ac.createGain();
bg.gain.setValueAtTime(vol * body, t0);
bg.gain.exponentialRampToValueAtTime(0.0005, t0 + 0.1);
b.connect(bg); bg.connect(dest);
b.start(t0); b.stop(t0 + 0.12);
const n = ac.createBufferSource();
n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = freq * 2.2; bp.Q.value = 1.2;
const ng = ac.createGain();
ng.gain.setValueAtTime(vol * 0.9, t0);
ng.gain.exponentialRampToValueAtTime(0.0005, t0 + 0.025);
n.connect(bp); bp.connect(ng); ng.connect(dest);
n.start(t0, Math.random() * 0.8); n.stop(t0 + 0.04);
}
export function clack(scene, { stack = 0, vol = 0.12 } = {}) {
const ac = ctxOf(scene);
if (!ac) return;
try {
knock(ac, out(scene, ac, vol), ac.currentTime + 0.004, { freq: 880 + stack * 45 + Math.random() * 120, body: 0.55 });
} catch (_) { /* audio is decoration */ }
}
export function slam(scene, { vol = 0.22 } = {}) {
const ac = ctxOf(scene);
if (!ac) return;
try {
const dest = out(scene, ac, vol);
const t0 = ac.currentTime + 0.004;
knock(ac, dest, t0, { freq: 620, body: 1.3, decay: 0.12 });
knock(ac, dest, t0 + 0.05, { freq: 1100, vol: 0.35, body: 0.2 });
} catch (_) { /* audio is decoration */ }
}
export function tap(scene, { vol = 0.05 } = {}) {
const ac = ctxOf(scene);
if (!ac) return;
try { knock(ac, out(scene, ac, vol), ac.currentTime + 0.003, { freq: 1500, body: 0.1, decay: 0.03 }); } catch (_) { /* decoration */ }
}
export function skitter(scene, { n = 5, vol = 0.07 } = {}) {
const ac = ctxOf(scene);
if (!ac) return;
try {
const dest = out(scene, ac, vol);
let t = ac.currentTime + 0.01;
for (let k = 0; k < n; k++) {
knock(ac, dest, t, { freq: 1800 + Math.random() * 900, vol: 1 - k / (n + 1), body: 0.15, decay: 0.03 });
t += 0.05 + k * 0.025 + Math.random() * 0.02;
}
} catch (_) { /* decoration */ }
}
export function bell(scene, { vol = 0.06 } = {}) {
const ac = ctxOf(scene);
if (!ac) return;
try {
const dest = out(scene, ac, vol);
const t0 = ac.currentTime + 0.01;
for (const [f, a, d] of [[880, 1, 1.6], [1320, 0.5, 1.1], [2210, 0.25, 0.7], [440, 0.4, 1.8]]) {
const o = ac.createOscillator(); o.type = 'sine'; o.frequency.value = f;
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(a, t0 + 0.01);
g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
o.connect(g); g.connect(dest);
o.start(t0); o.stop(t0 + d + 0.05);
}
} catch (_) { /* decoration */ }
}
export function cubeTurn(scene) {
const ac = ctxOf(scene);
if (!ac) return;
try {
const dest = out(scene, ac, 0.1);
const t0 = ac.currentTime + 0.005;
knock(ac, dest, t0, { freq: 1300, body: 0.3, decay: 0.05 });
knock(ac, dest, t0 + 0.12, { freq: 1050, body: 0.5, decay: 0.06 });
} catch (_) { /* decoration */ }
}
// Looping sea swell: brown-ish noise through a low-pass whose gain breathes.
export class Waves {
constructor(scene) { this.scene = scene; this.nodes = null; }
start(vol = 0.035) {
const ac = ctxOf(this.scene);
if (!ac || this.nodes) return;
try {
const src = ac.createBufferSource();
src.buffer = noise(ac);
src.loop = true;
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 420;
const g = ac.createGain(); g.gain.value = 0;
const lfo = ac.createOscillator(); lfo.type = 'sine'; lfo.frequency.value = 0.085;
const depth = ac.createGain(); depth.gain.value = vol * 0.7;
const base = out(this.scene, ac, 1);
lfo.connect(depth); depth.connect(g.gain);
g.gain.setValueAtTime(0, ac.currentTime);
g.gain.linearRampToValueAtTime(vol, ac.currentTime + 3);
src.connect(lp); lp.connect(g); g.connect(base);
src.start(); lfo.start();
this.nodes = { src, lfo, g, base };
} catch (_) { this.nodes = null; }
}
stop() {
if (!this.nodes) return;
try {
const ac = this.nodes.src.context;
this.nodes.g.gain.cancelScheduledValues(ac.currentTime);
this.nodes.g.gain.setValueAtTime(this.nodes.g.gain.value, ac.currentTime);
this.nodes.g.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6);
const n = this.nodes;
setTimeout(() => { try { n.src.stop(); n.lfo.stop(); n.base.disconnect(); } catch (_) { /* gone */ } }, 700);
} catch (_) { /* gone */ }
this.nodes = null;
}
setOn(on) { if (on) this.start(); else this.stop(); }
}

View File

@ -0,0 +1,423 @@
// BackgammonTray.js — real 3D dice thrown onto the board, the two leather cups
// and the doubling cube.
//
// Fairness: the engine rolls first (BackgammonLogic.rollDice); a throw is then
// planned with planTrayThrow (src/ui/dice/Dice3D.js) and relabelled so each
// die lands on exactly the rolled face. The animation never decides a result.
//
// Dice land in the roller's own half of the board, as at a real table: yours
// in your home-side half, the opponent's in theirs. Doubles add two ghost dice
// so all four moves can be counted off.
import { Die3D, planTrayThrow, poseFromPlan, restingQ, qslerp } from '../../ui/dice/Dice3D.js';
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
import { DIE_SIZE, FY, FH } from './BackgammonLayout.js';
import { CUBE_VALUES } from './BackgammonArt.js';
import { skitter, cubeTurn } from './BackgammonSound.js';
const BODY = { white: [244, 236, 214], black: [128, 30, 28] };
const PIP = { white: 0x1c1410, black: 0xf6ecd2 };
const YAW = [0.14, -0.1, 0.06, -0.16];
const lerp = (a, b, t) => a + (b - a) * t;
const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
export class BoardDice {
constructor(scene, layout, depth, { onClick, onHover } = {}) {
this.scene = scene;
this.L = layout;
this.depth = depth;
this.onClick = onClick;
this.onHover = onHover;
this.poses = [];
this.faces = [1, 1, 1, 1];
this.who = 'white';
this.enabled = false;
this.count = 0;
}
build() {
const s = this.scene;
this.dice = [0, 1, 2, 3].map(() => new Die3D(s, this.depth, {
size: DIE_SIZE, body: BODY.white, pip: PIP.white, sin: 0.86, cos: 0.5, ground: this.L.groundFor('white'),
}));
this.zones = this.dice.map((_, i) => {
const z = s.add.zone(0, 0, DIE_SIZE + 14, DIE_SIZE + 14).setDepth(this.depth + 5);
z.on('pointerdown', () => { if (this.enabled) this.onClick?.(i); });
z.on('pointerover', () => { if (this.enabled) this.onHover?.(i, true); });
z.on('pointerout', () => this.onHover?.(i, false));
return z;
});
for (let i = 0; i < 4; i++) {
this.poses[i] = { u: 0, v: 0, h: 0, q: restingQ(1, YAW[i]), alpha: 1 };
this.dice[i].setVisible(false);
}
return this;
}
setStyle(i, who) {
const d = this.dice[i];
d.opts.body = BODY[who]; d.opts.pip = PIP[who];
d.opts.ground = this.L.groundFor(who);
}
apply(i) {
const p = this.poses[i];
const d = this.dice[i];
d.setDepth(this.depth + p.v * 0.0002 + (p.h > 4 ? 0.3 : 0));
d.g.setAlpha(p.alpha); d.shadow.setAlpha(p.alpha);
d.set(p.u, p.v, p.h, p.q);
}
hideAll() {
this.count = 0;
for (let i = 0; i < 4; i++) { this.dice[i].setVisible(false); this.zones[i].disableInteractive(); }
}
tweenDie(i, to, dur, { arc = 0, alphaTo = null, q = null } = {}) {
const p = this.poses[i];
const from = { u: p.u, v: p.v, h: p.h, q: p.q, alpha: p.alpha };
const qTo = q ?? p.q;
if (dur <= 0) {
Object.assign(p, { u: to.u, v: to.v, h: to.h ?? 0, q: qTo });
if (alphaTo !== null) p.alpha = alphaTo;
this.apply(i);
return Promise.resolve();
}
const prox = { t: 0 };
return new Promise((resolve) => {
this.scene.tweens.add({
targets: prox, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const t = easeInOut(prox.t);
p.u = lerp(from.u, to.u, t); p.v = lerp(from.v, to.v, t);
p.h = lerp(from.h, to.h ?? 0, t) + arc * Math.sin(Math.PI * prox.t);
p.q = qslerp(from.q, qTo, t);
if (alphaTo !== null) p.alpha = lerp(from.alpha, alphaTo, t);
this.apply(i);
},
onComplete: resolve,
});
});
}
async playThrow(indices, who, faces, { speed = 1, fast = false, aim } = {}) {
const s = this.scene;
indices.forEach((i) => { this.setStyle(i, who); this.dice[i].setVisible(true); this.poses[i].alpha = 1; });
if (fast) {
const rest = this.L.diceRest(indices.length);
indices.forEach((i, k) => {
Object.assign(this.poses[i], { ...rest[k], h: 0, q: restingQ(faces[k], YAW[i]) });
this.apply(i);
});
return;
}
const plan = planTrayThrow(this.L.TRAY_WORLD, this.L.throwOrigin(who), faces, Math.random, DIE_SIZE, {
spread: 1.4, sep: 1.6, aim: aim ?? { u0: 0.22, u1: 0.78, v0: 0.42, v1: 0.58 },
});
playSound(s, SFX.DICE_ROLL);
s.time.delayedCall(Math.max(120, plan.duration * 600 * speed), () => skitter(s, { n: 4 }));
const step = (t) => indices.forEach((i, k) => {
const p = poseFromPlan(plan, k, t);
Object.assign(this.poses[i], { u: p.u, v: p.v, h: p.h, q: p.q });
this.apply(i);
});
step(0);
const prox = { t: 0 };
await new Promise((resolve) => {
s.tweens.add({
targets: prox, t: 1, duration: Math.max(620, plan.duration * 1000) * speed, ease: 'Linear',
onUpdate: () => step(prox.t), onComplete: () => { step(1); resolve(); },
});
});
await this.wait(120 * speed);
}
// Tidy dice into their resting row (n = 1, 2 or 4).
async tidy(indices, faces, dur = 260) {
const rest = this.L.diceRest(indices.length);
await Promise.all(indices.map((i, k) => this.tweenDie(i, { ...rest[k], h: 0 }, dur, { q: restingQ(faces[k], YAW[i]) })));
this.syncZones();
}
// Opening throw: one die each, into each player's own half.
async throwOpening(wFace, bFace, { speed = 1, fast = false } = {}) {
this.hideAll();
const one = { u0: 0.4, u1: 0.6, v0: 0.44, v1: 0.56 };
await Promise.all([
this.playThrow([0], 'white', [wFace], { speed, fast, aim: one }),
this.playThrow([1], 'black', [bFace], { speed, fast, aim: one }),
]);
const mid = { u: this.L.TRAY_WORLD.w / 2, v: FH / 2 };
await Promise.all([
this.tweenDie(0, { ...mid, h: 0 }, fast ? 0 : 240, { q: restingQ(wFace, YAW[0]) }),
this.tweenDie(1, { ...mid, h: 0 }, fast ? 0 : 240, { q: restingQ(bFace, YAW[1]) }),
]);
this.faces = [wFace, bFace, 1, 1];
this.count = 2;
this.syncZones();
}
// Move die i onto another half's ground without moving it on screen.
rebase(i, who) {
const from = this.dice[i].opts.ground(0, 0);
this.dice[i].opts.ground = this.L.groundFor(who);
const to = this.dice[i].opts.ground(0, 0);
this.poses[i].u += from.x - to.x;
this.poses[i].v += from.y - to.y;
this.apply(i);
}
// After the opening: carry the loser's die across into the starter's half.
// The loser's die keeps its colour — the starter plays both numbers.
async gatherOpening(starter, dice, { fast = false } = {}) {
const loserIdx = starter === 'white' ? 1 : 0;
const winnerIdx = 1 - loserIdx;
this.rebase(loserIdx, starter);
this.who = starter;
const rest = this.L.diceRest(2);
await Promise.all([
this.tweenDie(winnerIdx, { ...rest[0], h: 0 }, fast ? 0 : 300, { q: restingQ(dice[0], YAW[0]) }),
this.tweenDie(loserIdx, { ...rest[1], h: 0 }, fast ? 0 : 480, { arc: fast ? 0 : 70, q: restingQ(dice[1], YAW[1]) }),
]);
if (winnerIdx !== 0) this.swapDice(0, 1);
this.faces = [dice[0], dice[1], 1, 1];
this.count = 2;
this.syncZones();
}
swapDice(a, b) {
[this.dice[a], this.dice[b]] = [this.dice[b], this.dice[a]];
[this.poses[a], this.poses[b]] = [this.poses[b], this.poses[a]];
}
// A normal roll: two dice into `who`'s half; doubles grow two ghost dice.
async throwRoll(who, d1, d2, { speed = 1, fast = false } = {}) {
this.hideAll();
this.who = who;
await this.playThrow([0, 1], who, [d1, d2], { speed, fast });
if (d1 === d2) {
const rest = this.L.diceRest(4);
for (const i of [2, 3]) {
this.setStyle(i, who);
Object.assign(this.poses[i], { ...rest[i], h: 40, q: restingQ(d1, YAW[i]), alpha: 0 });
this.dice[i].setVisible(true);
this.apply(i);
}
await Promise.all([
this.tweenDie(0, { ...rest[0], h: 0 }, fast ? 0 : 260, { q: restingQ(d1, YAW[0]) }),
this.tweenDie(1, { ...rest[1], h: 0 }, fast ? 0 : 260, { q: restingQ(d1, YAW[1]) }),
this.tweenDie(2, { ...rest[2], h: 0 }, fast ? 0 : 260, { alphaTo: 0.92 }),
this.tweenDie(3, { ...rest[3], h: 0 }, fast ? 0 : 300, { alphaTo: 0.92 }),
]);
if (!fast) playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.3, rate: 1.5 });
this.faces = [d1, d1, d1, d1];
this.count = 4;
} else {
await this.tidy([0, 1], [d1, d2], fast ? 0 : 260);
this.faces = [d1, d2, 1, 1];
this.count = 2;
}
this.syncZones();
}
// Dim the dice already played. Non-doubles: by value; doubles: by count.
setUsage(movesLeft) {
if (!this.count) return;
const used = [false, false, false, false];
if (this.count === 4) {
const n = 4 - movesLeft.length;
for (let i = 0; i < n; i++) used[i] = true;
} else {
const left = movesLeft.slice();
for (let i = 0; i < 2; i++) {
const k = left.indexOf(this.faces[i]);
if (k >= 0) left.splice(k, 1); else used[i] = true;
}
}
for (let i = 0; i < this.count; i++) {
const target = used[i] ? 0.38 : (this.count === 4 && i >= 2 ? 0.92 : 1);
if (Math.abs(this.poses[i].alpha - target) > 0.01) this.tweenDie(i, { u: this.poses[i].u, v: this.poses[i].v, h: 0 }, 160, { alphaTo: target });
}
this.used = used;
}
// Sweep the dice off (end of turn).
async clear({ fast = false } = {}) {
if (!this.count) return;
const n = this.count;
await Promise.all([...Array(n).keys()].map((i) => this.tweenDie(i, { u: this.poses[i].u, v: this.poses[i].v - 20, h: 30 }, fast ? 0 : 220, { alphaTo: 0 })));
this.hideAll();
}
setGlow(amount, color = 0xf5d020) {
for (let i = 0; i < this.count; i++) { this.dice[i].glow = amount; this.dice[i].opts.glowColor = color; this.dice[i].draw(); }
}
glowDie(i, amount, color = 0xf5d020) {
if (i >= this.count) return;
this.dice[i].glow = amount; this.dice[i].opts.glowColor = color; this.dice[i].draw();
}
setEnabled(on) {
this.enabled = !!on;
this.zones.forEach((z, i) => ((on && i < this.count) ? z.setInteractive({ useHandCursor: true }) : z.disableInteractive()));
}
syncZones() {
this.dice.forEach((d, i) => { const c = d.screenCenter(); this.zones[i].setPosition(c.x, c.y); });
this.setEnabled(this.enabled);
}
valueOf(i) { return this.faces[i]; }
wait(ms) { return new Promise((r) => this.scene.time.delayedCall(Math.max(0, ms), r)); }
}
// ── leather cups ─────────────────────────────────────────────────────────────
export class DiceCup {
constructor(scene, depth, rect, key, { onPress } = {}) {
this.scene = scene;
this.depth = depth;
this.rect = rect;
this.key = key;
this.onPress = onPress;
this.enabled = false;
}
build() {
const s = this.scene, R = this.rect;
this.glow = s.add.graphics().setDepth(this.depth - 1);
this.glow.fillStyle(0xf5d020, 0.22).fillEllipse(R.x, R.y + R.h / 2 - 12, R.w * 1.3, 40);
this.glow.lineStyle(3, 0xf5d020, 0.85).strokeEllipse(R.x, R.y + R.h / 2 - 12, R.w * 1.15, 32);
this.glow.setAlpha(0);
this.img = s.add.image(R.x, R.y + R.h / 2 - 4, this.key).setOrigin(0.5, 1 - 18 / (R.h + 28)).setDepth(this.depth);
this.home = { x: this.img.x, y: this.img.y };
this.img.setInteractive({ useHandCursor: true });
this.img.on('pointerdown', () => { if (this.enabled) this.onPress?.(); });
this.img.on('pointerover', () => { if (this.enabled) this.img.setScale(1.04); });
this.img.on('pointerout', () => this.img.setScale(1));
this.pulse = s.tweens.add({ targets: this.glow, alpha: { from: 0.25, to: 0.95 }, duration: 750, yoyo: true, repeat: -1, paused: true });
return this;
}
setEnabled(on) {
this.enabled = !!on;
if (on) { if (this.pulse.isPaused()) this.pulse.resume(); }
else { this.pulse.pause(); this.glow.setAlpha(0); this.img.setScale(1); }
}
startShake() {
const s = this.scene;
this.stopShake();
this.shaking = true;
this.shakeT = 0;
this.shakeTimer = s.time.addEvent({
delay: 16, loop: true, callback: () => {
this.shakeT += 16;
const k = Math.min(1, this.shakeT / 400);
this.img.rotation = Math.sin(this.shakeT / 38) * (0.12 + 0.1 * k);
this.img.x = this.home.x + Math.sin(this.shakeT / 55) * 6 * k;
this.img.y = this.home.y - 10 - Math.abs(Math.sin(this.shakeT / 45)) * 10 * k;
},
});
this.rattle = s.time.addEvent({
delay: 95, loop: true, callback: () => playSoundEx(s, SFX.PIECE_CLICK, { volume: 0.16 + Math.random() * 0.14, rate: 1.4 + Math.random() * 0.8 }),
});
}
stopShake() {
this.shakeTimer?.remove(); this.shakeTimer = null;
this.rattle?.remove(); this.rattle = null;
this.shaking = false;
}
shakeTime() { return this.shakeT ?? 0; }
async pour(dir = -1) {
this.stopShake();
const s = this.scene;
await new Promise((res) => s.tweens.add({
targets: this.img, rotation: 0.6 * dir, x: this.home.x + 40 * dir, y: this.home.y - 40, duration: 140, ease: 'Quad.Out', onComplete: res,
}));
s.tweens.add({ targets: this.img, rotation: 0, x: this.home.x, y: this.home.y, duration: 380, delay: 160, ease: 'Back.Out' });
}
reset() { this.stopShake(); this.img.setRotation(0).setPosition(this.home.x, this.home.y); }
}
// ── the doubling cube ────────────────────────────────────────────────────────
export class DoublingCube {
constructor(scene, layout, depth, { onClick } = {}) {
this.scene = scene;
this.L = layout;
this.depth = depth;
this.onClick = onClick;
this.value = 1;
this.owner = null;
}
build() {
const s = this.scene;
const p = this.L.cubePos(null);
this.ring = s.add.graphics().setDepth(this.depth - 0.1);
this.img = s.add.image(p.x, p.y, 'bg-cube-64').setDepth(this.depth);
this.img.setInteractive({ useHandCursor: true });
this.img.on('pointerdown', () => this.onClick?.());
this.pulse = s.tweens.add({ targets: this.ring, alpha: { from: 0.3, to: 1 }, duration: 700, yoyo: true, repeat: -1, paused: true });
this.ring.setAlpha(0);
return this;
}
face(v) { return `bg-cube-${CUBE_VALUES.includes(v) ? v : 64}`; }
setVisible(on) { this.img.setVisible(on); this.ring.setVisible(on); }
// Jump straight to a value and owner.
snap(value, owner) {
this.value = value; this.owner = owner;
const p = this.L.cubePos(owner);
this.img.setTexture(this.face(value === 1 ? 64 : value)).setPosition(p.x, p.y).setScale(1).setRotation(0);
this.drawRing();
}
drawRing() {
this.ring.clear();
this.ring.lineStyle(4, 0xf5d020, 1).strokeRoundedRect(this.img.x - 40, this.img.y - 40, 80, 80, 14);
}
setGlow(on) {
this.drawRing();
if (on) { this.ring.setAlpha(0.8); if (this.pulse.isPaused()) this.pulse.resume(); }
else { this.pulse.pause(); this.ring.setAlpha(0); }
}
// Lift the cube and wobble it towards the taker (an offer).
async offer(offerer) {
this.setGlow(false);
const p = this.L.cubePos(null);
const dy = offerer === 'white' ? -1 : 1;
cubeTurn(this.scene);
await this.tween({ x: p.x, y: p.y + dy * 60, scale: 1.35, rotation: 0.25 * dy }, 320, 'Back.Out');
this.wobble = this.scene.tweens.add({ targets: this.img, rotation: { from: 0.18 * dy, to: -0.18 * dy }, duration: 420, yoyo: true, repeat: -1, ease: 'Sine.InOut' });
}
// Taken: tumble to the doubled face and slide to the new owner.
async take(value, owner) {
this.wobble?.stop(); this.wobble = null;
const s = this.scene;
const p = this.L.cubePos(owner);
cubeTurn(s);
await this.tween({ scaleX: 0.08, rotation: 0.6 }, 140, 'Quad.In');
this.img.setTexture(this.face(value));
await this.tween({ scaleX: 1.35, rotation: 0 }, 160, 'Quad.Out');
await this.tween({ x: p.x, y: p.y, scale: 1 }, 380, 'Cubic.InOut');
this.value = value; this.owner = owner;
this.drawRing();
}
// Dropped: the cube falls back to the middle.
async settle() {
this.wobble?.stop(); this.wobble = null;
const p = this.L.cubePos(this.owner);
await this.tween({ x: p.x, y: p.y, scale: 1, rotation: 0 }, 260, 'Quad.Out');
}
tween(props, duration, ease = 'Quad.InOut') {
return new Promise((r) => this.scene.tweens.add({ targets: this.img, ...props, duration, ease, onComplete: r }));
}
}
export { FY };

View File

@ -18,88 +18,112 @@ I like to think of it as a very polite argument about who gets to go first.
## The Setup ## The Setup
When the game starts, your checkers are arranged just so on the board: We're playing at a little café table by the sea today, dear—Harold always said backgammon tastes better with salt air. The board is an old olive-wood **tavli** case, opened flat, with the hinge running down the middle.
- **White checkers** start at the bottom of the board and move toward the top-left corner, heading home. - **You play the bone-white checkers.** Your **home board** is the bottom-right quarter (points 1 to 6), right next to the little tray where your checkers go when you bear them off. (There's a setting to put your home on the left if you're left-handed like my sister Martha.)
- **Black checkers** start at the top and move toward the bottom-right corner, heading home. - **Your opponent plays the dark walnut checkers.** Their home board is the top-right quarter.
- The little numbers on the wooden rail are the points, counted from **your** side: 1 is your far-right corner, 24 is the top-right corner where your two back checkers start.
Each player has checkers in four places at the start. It looks like a nice little pattern, doesn't it? Like the checkerboard quilt my sister Martha made me in 1973. Though hers had squares, not triangles. You move your checkers *down* the numbers—from 24 toward 1—around the board in a horseshoe, and then off into the tray. Your opponent travels the other way round. It looks like a nice little pattern, doesn't it? Like the checkerboard quilt Martha made me in 1973. Though hers had squares, not triangles.
The board has **24 points** (those little triangles). You move your checkers around the board in a circle, and your "home" board is where you want to end up. Think of it like coming home for dinner—everyone wants to get to the table!
## How to Play—Step by Step, Now That I've Checked the Cookies ## How to Play—Step by Step, Now That I've Checked the Cookies
### Step 1: Roll the Dice ### Step 1: The Opening Roll
At the beginning of your turn, you roll two dice. The computer does it for you, which is nice because my arthritis makes it rather difficult to shake the dice cup properly. Harold always accused me of rigging the dice. I told him, Harold, I am rigging nothing, I am merely… enthusiastic about probability! To start, you each throw **one die**. Whoever throws higher goes first—and plays **both** of those numbers as their first move. If you tie, you both throw again. Very civilised. Harold and I used to argue about who went first, so this would have saved us a great deal of bother.
- If you roll the **same number on both dice** (called "doubles"), you get to roll **four times** instead of two! It's like getting four chances instead of two. Very lucky, very nice. ### Step 2: Shake the Cup and Roll
- If you roll different numbers, like a 3 and a 5, you get to make **two moves**—one for the 3 and one for the 5.
### Step 2: Move Your Checkers On your turn, **press and hold your leather cup** (bottom right) to give it a good shake—listen to it rattle!—then let go, and the dice tumble out onto your side of the board. You can hold the **Space bar** instead if your wrists are like mine.
Now the fun part! You use the numbers on your dice to move your checkers around the board. - Roll **different numbers**, say a 3 and a 5, and you make two moves: one of 3 and one of 5. One checker can make both moves, or two checkers can make one each.
- Roll **doubles**—the same number on both dice—and you get to move that number **four times**! Two extra little dice pop up so you can count them off.
- **You must use both dice if you possibly can.** If only one of them can be played, you must play the **larger** one if that's possible. The game knows these rules and only lets you make legal moves, so don't fret.
**Where do you move?** ### Step 3: Moving Your Checkers
- If you're **White**, you move your checkers from the high numbers toward the low numbers (from point 23 down to point 0). Think of it like walking down the stairs at home—going from the top floor to the ground floor.
- If you're **Black**, you move from the low numbers toward the high numbers (from point 0 up to point 23). Like climbing up the stairs to the bedroom.
![Backgammon Moves](assets/images/tutorial-images/backgammon-01.png) ![Backgammon Moves](assets/images/tutorial-images/backgammon-01.png)
The checkers you're allowed to move have a soft golden glow. You can:
- **Click** a checker to pick it up—little circles show where it can land, marked with the dice it uses (like "5" or "3+5"). Click a circle to move there.
- **Drag** it there, if you prefer. Drop it somewhere silly and it just hops back to you.
- **Double-click** a checker to send it as far as it can legally go with your dice.
- Hover over a **die** to see which checkers can use that number.
Changed your mind? **Undo (Z)** takes back your last move—as many times as you like—until you press **Done (Space)** or tap the dice. Harold would never have let me do that.
**The basic rules of moving:** **The basic rules of moving:**
1. **You can move to an empty spot** — no problem at all! Just go on in. 1. **You can move to an empty spot** — no problem at all! Just go on in.
2. **You can move to a spot with your own checkers** — they're all friends, they don't mind. 2. **You can move to a spot with your own checkers** — they're all friends, they don't mind.
3. **You can move to a spot with just ONE of the opponent's checkers** — and when you do, you **hit** them! Their checker goes to the "bar" (the middle of the board). It's like saying "Excuse me, but I was here first!" and sending them to the waiting area. 3. **You can move to a spot with just ONE of the opponent's checkers** (a "blot") — and when you do, you **hit** them! Their checker goes up onto the hinge in the middle—the **bar**. The circles turn red when a move hits. In the cafés they *slam* the checker down when they hit. Very dramatic. I usually apologise.
4. **You CANNOT move to a spot with TWO or more of the opponent's checkers** — that spot is "blocked" or "made." It's like the neighbor's house with the two big dogs barking. You don't go there. 4. **You CANNOT move to a spot with TWO or more of the opponent's checkers** — that point is "made." It's like the neighbour's house with the two big dogs barking. You don't go there.
### Step 3: The Bar ### Step 4: The Bar
If your checker gets hit, it goes to the **bar**—that's the middle strip on the board. Before you can move any of your other checkers, you **must** get your checker off the bar and back onto the board. If your checker gets hit, it waits on the bar. Before you can move anything else, you **must** bring it back in—into your **opponent's home board** (the top-right quarter, points 24 down to 19). A roll of 1 enters on point 24, a 6 on point 19, and so on. If every point you could enter on is made, you "dance"—you can't move at all this turn. It's like being sent to the principal's office and waiting for the teacher to say you can come back to class.
To get back on: ### Step 5: Bearing Off
- **White** enters on the opponent's home board (the top-right area, points 18–23)
- **Black** enters on the opponent's home board (the bottom-left area, points 0–5)
You use the die to figure out where to land. It's like being sent to the principal's office and then having to wait until the teacher says you can come back to class. When **all fifteen** of your checkers are in your home board, you can start **bearing them off** into the tray, where they stand up on their edges in a neat little row. This is the best part, really. It's like clearing the dinner table after everyone's had their fill.
### Step 4: Bearing Off - Roll the number of the point a checker is on, and you can bear it off. Roll a 4 with a checker on your 4-point—off it goes!
- If you roll **higher** than your highest checker—say a 6 when your highest checker is on the 3-point—you may bear off that highest checker.
- If a checker gets hit while you're bearing off, it has to come all the way back round before you can bear off any more. Ouch.
When **all fifteen** of your checkers are in your home board, you can start **bearing them off**—that means removing them from the board entirely. This is the best part, really. It's like clearing the dinner table after everyone's had their fill. ### Step 6: Winning—and Winning Big
**How bearing off works:** The first player to bear off all fifteen checkers wins! *Huzzah!* But there's more, dear:
- Roll a die that matches the point your checker is on, and you can remove it. For example, if you roll a 4 and you have a checker on point 4 (for White), you bear it off! - A normal win is worth **1 point**.
- If you don't have a checker on the exact point the die shows, you can move a checker from a **higher-numbered** point instead. Like, if you roll a 6 but your highest checker is on point 3, you can bear that one off using the 6. - If your opponent hasn't borne off a single checker, it's a **gammon**—worth **2 points**.
- You can only bear off if all your checkers are home. No sneaky bear-offs from outside the home board, dear. - If they haven't borne off any *and* still have a checker on the bar or in your home board, it's a **backgammon**—worth **3 points**! Harold got one of those against the vicar once. He was insufferable for a week.
### Step 5: Winning ## The Doubling Cube
The first player to bear off **all fifteen** of their checkers wins the game! *Huzzah!* Everyone claps. Well, I clap. Harold pretends not to notice but he's really quite pleased. That big ivory cube on the hinge, with 64 on top, is the **doubling cube**. It's what makes backgammon so delicious.
- **Before you roll**, if you think you're winning, you may **offer a double** (the Double button, or press **D**). Your opponent then either **takes**—and you play on for twice as many points, and *they* now own the cube—or **drops**, and loses right there for the current stakes.
- Only the cube's owner may double next (the cube sits on their side of the hinge). In the middle, either player may.
- The computer will offer you doubles too! A torn little slip of paper appears and asks: Take or Drop? A good rule of thumb: **take if you think you'll win at least one game in four**. With hints switched on, the Coach tells you your chances.
- You can switch the cube off in the menu if you'd rather keep things simple.
## Matches
In the menu you can choose a **match** to 3, 5 or 7 points, playing game after game until someone gets there. When one player is one point away from winning, the next game is the **Crawford game**—nobody may double in it. (It's named after a gentleman called Crawford, not after my neighbour's dog, though the dog is also called Crawford.)
There's also the **Jacoby rule** for single games: gammons only count if somebody has turned the cube. It stops people dawdling for a gammon.
## The Coach and Other Comforts
- **Hint (H)** shows the move the cleverest computer would make, with arrows and a little reason—"makes your 5-point · leaves no shots." Before you roll, it tells you whether it's a good moment to double.
- The **slate** on the left shows the match score, where the cube is, and who leads the race (that's the **pip count**—how far everyone still has to travel).
- The **order pad** on the right writes down every move in proper backgammon shorthand. "13/7 8/7*" means one checker from 13 to 7 and another from 8 to 7, and the little star means somebody got hit.
- The menu (**Esc**) lets you slow the opponent down, auto-roll, auto-play forced moves, skip the confirm step, turn off the sea and the slamming, and more.
## A Few Helpful Tips from Ethel's Kitchen ## A Few Helpful Tips from Ethel's Kitchen
1. **Get your checkers home early!** Don't just bounce around the board forever. You want them all in your home board so you can start bearing off. It's like getting all the groceries into the kitchen before you start cooking. 1. **Make points in your home board**, especially your 5-point and 6-point. A row of made points—a **prime**—is like a garden fence. Nothing gets past.
2. **Don't leave single checkers (blots) lying around!** If the opponent can hit you, they will. It's like leaving your front door unlocked. Sure, nobody *should* break in, but why take the chance? 2. **Don't leave single checkers (blots) lying around!** If the opponent can hit you, they will. It's like leaving your front door unlocked.
3. **Doubles are wonderful!** Four moves from one roll is a huge advantage. If you roll doubles, try to use all four moves if you can. 3. **Look at the race.** If you're well ahead in pips, run for home and avoid contact. If you're behind, hang back and hope for a shot.
4. **The bar is your worst enemy.** Getting hit and having to go to the bar means you lose your turn getting back in. It's like tripping on the stairs—embarrassing and time-consuming. 4. **Doubles are wonderful!** Four moves from one roll is a huge advantage. Use all four if you can.
5. **Sometimes you just can't move.** If all your possible moves are blocked, you have to wait. It's like being stuck in traffic. Annoying, but it'll pass. 5. **Don't be afraid of the cube.** A take at 25% feels scary, but in the long run it's right more often than not. Harold took everything. Harold also lost a great deal. Find a middle path, dear.
## A Note About the Computer Opponent ## A Note About the Computer Opponent
The computer plays as the opponent, and it's rather clever, I must say. It doesn't give up easily. Sometimes I think it's judging me. It doesn't have eyes, but it *feels* like it's judging me. Your opponent sits across the table with their own leather cup, and they're rather clever—how clever depends on the **skill** you pick for them when you choose your opponent, from 1 (happy-go-lucky) to 5 (looks ahead at every roll you might throw back). They'll chat a little, too, especially when they hit you. Don't take it personally.
When it's the computer's turn, just wait patiently. It makes its moves rather quickly, which is good, because I get rather distracted. I was telling you about the cookies, weren't I? They're chocolate chip with a hint of sea salt. Harold's favorite.
## Troubleshooting (Because Things Go Wrong, Even in Games) ## Troubleshooting (Because Things Go Wrong, Even in Games)
- **I can't move my checker!** Make sure you've rolled the dice first, and check if the destination is blocked (two or more opponent checkers). Also, if you have a checker on the bar, you must move it first before moving anything else. - **I can't move my checker!** Make sure you've rolled first. Only glowing checkers can move—if you have a checker on the bar, that one must come in first.
- **I don't see where to move!** Click on a checker you want to move, and the game should show you where you can go. If nothing happens, maybe that checker can't move with the dice you rolled. - **It won't let me play the move I want!** Remember: you must use both dice if you can, and the larger one if you can only use one. Sometimes that forbids a move that looks perfectly nice.
- **The game won't let me bear off!** You can only bear off when ALL fifteen checkers are in your home board. If even one is outside, you have to move it home first. - **Nothing happens after my moves!** Press **Done** (or Space, or tap the dice) to finish your turn—or switch off "Confirm each turn" in the menu.
- **The game won't let me bear off!** All fifteen checkers must be in your home board first. Even one straggler keeps the tray shut.
--- ---
@ -107,6 +131,6 @@ Oh! The timer! *Ethel rushes toward the kitchen, nearly trips over the cat, and
There you go, dear. Chocolate chip cookies. With sea salt. Harold would've loved this game, you know. He played backgammon for forty years. Said the dice were like life—you never know what you're gonna get. There you go, dear. Chocolate chip cookies. With sea salt. Harold would've loved this game, you know. He played backgammon for forty years. Said the dice were like life—you never know what you're gonna get.
Now, want to play a round? I'll go first. I always go first. It's my house, after all. And my oven timer. Now, want to play a round? I'd go first—it's my house, after all, and my oven timer—but there's the opening roll now, so I suppose it's only fair.
*Bon appétit and good luck, dear!* 🍪🎲 *Bon appétit and good luck, dear!* 🍪🎲

View File

@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
// Skill control: pips always show the level; the +/- buttons appear only // Skill control: pips always show the level; the +/- buttons appear only
// when this opponent is selected. Enabled for games with a 1–5 AI skill. // when this opponent is selected. Enabled for games with a 1–5 AI skill.
if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride'].includes(this.gameDef.slug)) { if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride', 'backgammon'].includes(this.gameDef.slug)) {
bio.style.webkitLineClamp = '1'; bio.style.webkitLineClamp = '1';
const skillRow = document.createElement('div'); const skillRow = document.createElement('div');

503
tools/verifyBackgammon.js Normal file
View File

@ -0,0 +1,503 @@
#!/usr/bin/env node
// verifyBackgammon.js — headless checks for Backgammon ("Tavli at the kafeneio"):
// • rules on hand-built positions: maximum-dice and higher-die rules, bar
// entry and dancing, bearing off (exact, overshoot, blocked by a higher
// checker), hits, the opening roll, gammon / backgammon, the cube (offer,
// take, drop, ownership, 64 cap), Jacoby, matches + Crawford, notation
// • turn generation = an unrestricted brute force on positions from real games
// • bear-off table: exact small values, monotone in checkers, race odds sane
// • AI soak: all-AI games with the cube finish legally; every AI turn is one
// of the legal maximal turns; checkers always 15 a side
// • skill ladder with mirrored seeds (same dice, seats swapped)
// • dice throws land on the rolled faces inside the roller's half
// • layout: furniture on screen and apart, stacks inside their points,
// tray / bar / cube placements, hit-testing, mirror symmetry
// • checker registry: a move relocates exactly the top checker
// Usage: node tools/verifyBackgammon.js [--quick]
import * as L from '../src/games/backgammon/BackgammonLogic.js';
import * as AI from '../src/games/backgammon/BackgammonAI.js';
import * as Bearoff from '../src/games/backgammon/BackgammonBearoff.js';
import * as Lay from '../src/games/backgammon/BackgammonLayout.js';
import { CheckerSet } from '../src/games/backgammon/BackgammonCheckers.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
import { planTrayThrow, topFace } from '../src/ui/dice/Dice3D.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 near = (a, b, eps) => Math.abs(a - b) <= eps;
// Build a state: white / black = { idx: count }, plus bar / off.
function pos({ white = {}, black = {}, bar = {}, off = {}, dice = null, player = 'white', opts = {} }) {
const s = L.createInitialState(opts);
for (let i = 0; i < 24; i++) s.points[i] = { color: null, count: 0 };
for (const [i, n] of Object.entries(white)) s.points[i] = { color: 'white', count: n };
for (const [i, n] of Object.entries(black)) s.points[i] = { color: 'black', count: n };
s.bar = { white: bar.white ?? 0, black: bar.black ?? 0 };
const placed = (c) => Object.values(c === 'white' ? white : black).reduce((a, b) => a + b, 0) + s.bar[c];
s.borneOff = { white: off.white ?? 15 - placed('white'), black: off.black ?? 15 - placed('black') };
s.currentPlayer = player;
s.phase = 'roll';
if (dice) {
s.dice = dice.slice();
s.movesLeft = dice[0] === dice[1] ? [dice[0], dice[0], dice[0], dice[0]] : dice.slice();
s.phase = 'move';
}
return s;
}
const mv = (m) => `${m.from}>${m.to}/${m.dieUsed}`;
// ── rules ────────────────────────────────────────────────────────────────────
section('Rules');
{
const s0 = L.createInitialState();
ok('15 checkers a side at the start', L.checkerTotals(s0).white === 15 && L.checkerTotals(s0).black === 15);
ok('pip counts start at 167', L.computePipCount(s0, 'white') === 167 && L.computePipCount(s0, 'black') === 167);
ok('a fresh game begins with the opening roll', s0.phase === 'opening');
// opening roll
const tie = L.openingWith(s0, 4, 4);
ok('opening tie stays in the opening', tie.phase === 'opening' && tie.opening.white === 4);
const ow = L.openingWith(s0, 5, 2);
ok('higher opening die starts and plays both numbers', ow.currentPlayer === 'white' && ow.dice[0] === 5 && ow.dice[1] === 2 && ow.phase === 'move' && ow.movesLeft.length === 2);
const ob = L.openingWith(s0, 1, 6);
ok('black can start too, dice reordered for the starter', ob.currentPlayer === 'black' && ob.dice[0] === 6 && ob.dice[1] === 1);
ok('opening roll counts in the starter\'s stats', ob.stats.black.rolls === 1 && ob.stats.black.pips === 7 && ob.stats.white.rolls === 0);
// maximum dice: both must be used when possible
{
// single checker on 10 (point 11): 10-6=4 blocked, 10-1=9 open, 9-6=3 open → must play 1 then 6
const s = pos({ white: { 10: 1, 0: 14 }, black: { 4: 2, 23: 13 }, dice: [6, 1] });
const turns = L.legalTurns(s);
ok('max-dice: every legal turn uses both dice', turns.length > 0 && turns.every((t) => t.moves.length === 2), JSON.stringify(turns.map((t) => t.moves.map(mv))));
const v = L.getValidMoves(s).map(mv);
ok('max-dice: the only first step is the 1 that unlocks the 6', v.length === 1 && v[0] === '10>9/1', v.join(','));
}
{
// only one die can be played → it must be the higher one
const s = pos({ white: { 20: 1, 0: 14 }, black: { 11: 2, 23: 13 }, dice: [6, 3] });
const v = L.getValidMoves(s).map(mv);
ok('higher-die rule: forced to play the 6', v.length === 1 && v[0] === '20>14/6', v.join(','));
const s2 = pos({ white: { 20: 1, 0: 14 }, black: { 14: 2, 11: 2, 23: 11 }, dice: [6, 3] });
const v2 = L.getValidMoves(s2).map(mv);
ok('higher-die rule: the 3 is fine when the 6 cannot be played at all', v2.length === 1 && v2[0] === '20>17/3', v2.join(','));
}
{
// doubles: play as many as possible
const s = pos({ white: { 12: 1 }, black: { 0: 2, 23: 13 }, dice: [4, 4] });
const turns = L.legalTurns(s);
ok('doubles: blocked after two steps → turns use exactly two 4s', turns.length === 1 && turns[0].moves.length === 2, JSON.stringify(turns.map((t) => t.moves.map(mv))));
const s1 = pos({ white: { 12: 1, 0: 14 }, black: { 4: 2, 23: 13 }, dice: [4, 4] });
ok('doubles: only one 4 playable → a one-move turn', L.legalTurns(s1).every((t) => t.moves.length === 1));
}
// bar entry
{
const s = pos({ white: { 5: 14 }, bar: { white: 1 }, black: { 18: 2, 19: 2, 0: 11 }, player: 'white' });
const r = L.rollSpecificDice(s, 6, 5);
ok('dance: both entry points made → no move', !L.hasAnyMove(r) && L.turnDone(r));
ok('dance is counted in the stats', r.stats.white.dances === 1 && r.stats.white.barTurns === 1);
const r2 = L.rollSpecificDice(s, 6, 3);
const v = L.getValidMoves(r2).map(mv);
ok('bar first: only the entering move is legal', v.length === 1 && v[0] === 'bar>21/3', v.join(','));
const b = pos({ black: { 18: 14 }, bar: { black: 1 }, white: { 5: 15 }, player: 'black' });
const rb = L.rollSpecificDice(b, 2, 2);
ok('black enters on White\'s home board (a 2 → point 2)', L.getValidMoves(rb).some((m) => m.from === 'bar' && m.to === 1));
}
// hits
{
const s = pos({ white: { 8: 2, 5: 13 }, black: { 3: 1, 23: 14 }, dice: [5, 2] });
const m = L.getValidMoves(s).find((x) => x.from === 8 && x.to === 3);
ok('landing on a lone checker is a hit', m && m.hit);
const a = L.applyMove(s, m);
ok('the hit checker goes to the bar', a.bar.black === 1 && a.points[3].color === 'white' && a.points[3].count === 1);
ok('hit stats', a.stats.white.hits === 1 && a.stats.black.hitTaken === 1);
ok('applyMove consumes exactly the die', a.movesLeft.length === 1 && a.movesLeft[0] === 2);
ok('the turn is not over until both dice are used', !L.turnDone(a));
const b2 = L.applyMove(a, L.getValidMoves(a)[0]);
ok('turnDone once the dice are spent; endTurn passes the dice', L.turnDone(b2) && L.endTurn(b2).currentPlayer === 'black' && L.endTurn(b2).phase === 'roll');
}
// bearing off
{
const s = pos({ white: { 2: 1, 4: 1 }, black: { 23: 15 }, dice: [6, 1] });
const v = L.getValidMoves(s).map(mv);
ok('overshoot: the 6 bears off the highest checker only', v.includes('4>off/6') && !v.includes('2>off/6'), v.join(','));
ok('every ordering is offered (2>1 then 4>off reaches the same place as the reverse)', v.includes('4>3/1') && v.includes('2>1/1'), v.join(','));
const s2 = pos({ white: { 7: 1, 3: 1 }, black: { 23: 15 }, dice: [4, 2] });
ok('no bearing off while a checker is outside home', L.getValidMoves(s2).every((m) => m.to !== 'off'));
const s3 = pos({ white: { 0: 1 }, black: { 23: 15 }, dice: [3, 1] });
const end = L.applyMove(s3, L.getValidMoves(s3).find((m) => m.dieUsed === 3));
ok('bearing off the last checker ends the game (higher die)', end.phase === 'game_over' && end.winner === 'white');
ok('wasted pips are counted', end.stats.white.pipsWasted === 2);
}
// gammons
{
const g = pos({ white: { 0: 1 }, black: { 10: 15 }, dice: [1, 2] });
const gm = L.applyMove(g, L.getValidMoves(g).find((m) => m.to === 'off'));
ok('gammon when the loser bore off nothing', gm.result.kind === 'gammon' && gm.result.points === 2);
const bg = pos({ white: { 0: 1 }, black: { 3: 1, 10: 14 }, dice: [1, 2] });
const bgm = L.applyMove(bg, L.getValidMoves(bg).find((m) => m.to === 'off'));
ok('backgammon when a loser checker is in the winner\'s home', bgm.result.kind === 'backgammon' && bgm.result.points === 3);
const bb = pos({ white: { 0: 1 }, black: { 10: 14 }, bar: { black: 1 }, dice: [1, 2] });
ok('backgammon when a loser checker is on the bar', L.applyMove(bb, L.getValidMoves(bb).find((m) => m.to === 'off')).result.kind === 'backgammon');
const sg = pos({ white: { 0: 1 }, black: { 20: 14 }, off: { black: 1 }, dice: [1, 2] });
ok('single game once the loser has borne one off', L.applyMove(sg, L.getValidMoves(sg).find((m) => m.to === 'off')).result.kind === 'single');
const jg = pos({ white: { 0: 1 }, black: { 10: 15 }, dice: [1, 2], opts: { jacoby: true } });
const jr = L.applyMove(jg, L.getValidMoves(jg).find((m) => m.to === 'off')).result;
ok('Jacoby: no gammon with a centred cube', jr.kind === 'single' && jr.points === 1 && jr.jacobyWaived);
const jc = pos({ white: { 0: 1 }, black: { 10: 15 }, dice: [1, 2], opts: { jacoby: true } });
jc.cube = { value: 2, owner: 'white' };
const jcr = L.applyMove(jc, L.getValidMoves(jc).find((m) => m.to === 'off')).result;
ok('Jacoby: the gammon counts once the cube is turned (2 × 2)', jcr.kind === 'gammon' && jcr.points === 4);
}
// the cube
{
let s = pos({ white: { 5: 15 }, black: { 18: 15 } });
ok('either player may double from the centre', L.canDouble(s, 'white') && !L.canDouble(s, 'black'));
s = L.offerDouble(s);
ok('offer → phase double, offerer remembered', s.phase === 'double' && s.pendingDouble === 'white');
const t = L.takeDouble(s);
ok('take → cube 2 owned by the taker; offerer still rolls', t.cube.value === 2 && t.cube.owner === 'black' && t.phase === 'roll' && t.currentPlayer === 'white');
ok('the cube owner alone may redouble', !L.canDouble(t, 'white') && L.canDouble({ ...t, currentPlayer: 'black' }, 'black'));
const d = L.dropDouble(s);
ok('drop → offerer wins the current stake', d.phase === 'game_over' && d.winner === 'white' && d.result.kind === 'drop' && d.result.points === 1);
const big = { ...pos({ white: { 5: 15 }, black: { 18: 15 } }), cube: { value: 64, owner: 'white' } };
ok('no doubling past 64', !L.canDouble(big, 'white'));
const off = pos({ white: { 5: 15 }, black: { 18: 15 }, opts: { cubeEnabled: false } });
ok('no doubling with the cube switched off', !L.canDouble(off, 'white'));
}
// matches
{
let m = L.createMatch(5);
m = L.recordGame(m, { winner: 'white', points: 2, kind: 'gammon' });
ok('match score adds the points', m.score.white === 2 && !m.over);
m = L.recordGame(m, { winner: 'white', points: 2, kind: 'gammon' });
ok('reaching match point → the next game is Crawford', m.score.white === 4 && m.crawford);
ok('Crawford game: cube disabled', L.gameOptions(m, { cube: true }).cubeEnabled === false);
m = L.recordGame(m, { winner: 'black', points: 1, kind: 'single' });
ok('after Crawford the cube is back', !m.crawford && m.hadCrawford && L.gameOptions(m, { cube: true }).cubeEnabled);
m = L.recordGame(m, { winner: 'black', points: 4, kind: 'drop' });
ok('no second Crawford game', !m.crawford);
m = L.recordGame(m, { winner: 'white', points: 1, kind: 'single' });
ok('match over at the target', m.over && m.winner === 'white');
const one = L.recordGame(L.createMatch(0), { winner: 'black', points: 2, kind: 'gammon' });
ok('a single game is over at once', one.over && one.winner === 'black' && one.score.black === 2);
ok('Jacoby only applies to single games', L.gameOptions(L.createMatch(5), { jacoby: true }).jacoby === false && L.gameOptions(L.createMatch(0), { jacoby: true }).jacoby === true);
}
// notation
{
ok('notation from the mover\'s side', L.moveText('white', { from: 12, to: 6, hit: true }) === '13/7*' && L.moveText('black', { from: 0, to: 6, hit: false }) === '24/18');
ok('repeated moves collapse', L.turnText('white', [{ from: 12, to: 8 }, { from: 12, to: 8 }]) === '13/9(2)');
ok('bar / off notation', L.moveText('white', { from: 'bar', to: 20 }) === 'bar/21' && L.moveText('white', { from: 2, to: 'off' }) === '3/off');
}
// combined (same-checker) paths
{
const s = L.openingWith(L.createInitialState(), 6, 5);
const paths = L.checkerPaths(s, 23);
ok('checkerPaths: 6-5 runner goes to 18 or (lover\'s leap) 13; their 6-point blocks the 5', [17, 12].every((t) => paths.some((p) => p.to === t)) && !paths.some((p) => p.to === 18), paths.map((p) => p.to).join(','));
ok('checkerPaths: 11 uses two dice', paths.find((p) => p.to === 12)?.moves.length === 2);
}
}
// ── turn generation vs brute force ───────────────────────────────────────────
section('Turn generation');
{
function brute(me, op, dice) {
const res = new Map();
let max = 0;
const rec = (m, o, rem, seq) => {
let any = false;
for (const d of [...new Set(rem)]) {
L.forEachStep(m, o, d, (f, to) => {
any = true;
const m2 = m.slice(), o2 = o.slice();
L.stepP(m2, o2, f, to);
const r = rem.slice(); r.splice(r.indexOf(d), 1);
rec(m2, o2, r, seq.concat([d]));
});
}
if (!any) {
if (seq.length > max) { max = seq.length; res.clear(); }
if (seq.length === max) { const k = L.posKey(m, o); if (!res.has(k)) res.set(k, seq); }
}
};
rec(me, op, dice, []);
let keys = [...res.keys()];
if (max === 1 && dice.length === 2 && dice[0] !== dice[1]) {
const hi = Math.max(...dice);
if ([...res.values()].some((q) => q[0] === hi)) keys = keys.filter((k) => res.get(k)[0] === hi);
}
return new Set(keys);
}
const rng = mulberry32(77);
let checked = 0, bad = 0;
for (let g = 0; g < (QUICK ? 15 : 60); g++) {
let s = L.rollOpening(L.createInitialState(), rng);
while (s.phase === 'opening') s = L.rollOpening(s, rng);
let guard = 0;
while (s.phase !== 'game_over' && guard++ < 500) {
if (s.phase === 'roll') s = L.rollDice(s, rng);
const { me, op } = L.boardsFor(s, s.currentPlayer);
const A = new Set(L.enumerateTurns(me, op, s.movesLeft).map((t) => t.key));
const B = brute(me, op, s.movesLeft);
checked++;
if (A.size !== B.size || [...A].some((k) => !B.has(k))) bad++;
const turns = L.legalTurns(s);
const t = turns[Math.floor(rng() * turns.length)];
for (const m of t.moves) { s = L.applyMove(s, m); if (s.phase === 'game_over') break; }
if (s.phase !== 'game_over') s = L.endTurn(s);
}
}
ok(`enumerateTurns matches brute force on ${checked} positions`, bad === 0, `${bad} mismatches`);
}
// ── bear-off table ───────────────────────────────────────────────────────────
section('Bear-off table');
{
const t0 = Date.now();
let steps = 0;
while (!Bearoff.buildStep(5000)) steps++;
ok('table builds in slices', steps > 3 && Bearoff.ready(), `steps ${steps}`);
ok(`54,264 positions (built in ${Date.now() - t0} ms)`, Bearoff.size() === 54264);
const E = (c) => Bearoff.expectedRolls(c).e;
ok('1 checker on the ace: exactly 1 roll', near(E([1, 0, 0, 0, 0, 0]), 1, 1e-6));
ok('2 checkers on the ace: exactly 1 roll', near(E([2, 0, 0, 0, 0, 0]), 1, 1e-6));
ok('1 checker on the 6-point: 1.25 rolls (9 of 36 rolls fall short)', near(E([0, 0, 0, 0, 0, 1]), 1.25, 1e-5));
ok('4 on the ace: 1 + 30/36 (only doubles do it at once)', near(E([4, 0, 0, 0, 0, 0]), 1 + 30 / 36, 1e-5));
const rng = mulberry32(5);
let mono = true;
for (let k = 0; k < 400; k++) {
const c = [0, 0, 0, 0, 0, 0];
const n = 1 + Math.floor(rng() * 13);
for (let i = 0; i < n; i++) c[Math.floor(rng() * 6)]++;
const j = Math.floor(rng() * 6);
const c2 = c.slice(); c2[j]++;
if (E(c2) + 1e-6 < E(c)) mono = false;
}
ok('adding a checker never makes the bear-off faster', mono);
const p = Bearoff.raceWinProb([0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 0]);
ok('a short bear-off beats a long one, even off roll', p > 0.9, `p=${p}`);
const sym = Bearoff.raceWinProb([2, 2, 2, 2, 2, 2], [2, 2, 2, 2, 2, 2]);
ok('equal bear-offs: the side on roll is the favourite', sym < 0.5 && sym > 0.15, `p=${sym}`);
}
// ── AI ───────────────────────────────────────────────────────────────────────
section('AI');
AI.SKILL[5].budgetMs = 0; // deterministic searches in tests
function playGame(skW, skB, seed, { cube = false, check = false } = {}) {
const dice = mulberry32(seed), noise = mulberry32(seed * 7 + 1);
let s = L.createInitialState({ cubeEnabled: cube });
while (s.phase === 'opening') s = L.rollOpening(s, dice);
let guard = 0, legalBad = 0, consBad = 0, dbl = 0;
while (s.phase !== 'game_over' && guard++ < 1500) {
if (s.phase === 'roll') {
const p = s.currentPlayer, sk = p === 'white' ? skW : skB;
if (cube && L.canDouble(s, p) && AI.shouldDouble(s, p, sk, null, noise)) {
dbl++;
s = L.offerDouble(s);
s = AI.shouldTake(s, L.other(p), p === 'white' ? skB : skW, null, noise) ? L.takeDouble(s) : L.dropDouble(s);
if (s.phase === 'game_over') break;
}
s = L.rollDice(s, dice);
}
const sk = s.currentPlayer === 'white' ? skW : skB;
const r = AI.chooseTurn(s, sk, noise);
if (check) {
const { me, op } = L.boardsFor(s, s.currentPlayer);
const keys = new Set(L.enumerateTurns(me, op, s.movesLeft).map((t) => t.key));
let t = s;
for (const m of r.moves) t = L.applyMove(t, m);
const after = L.boardsFor({ ...t, phase: 'move' }, s.currentPlayer);
if (!keys.has(L.posKey(after.me, after.op))) legalBad++;
}
for (const m of r.moves) { s = L.applyMove(s, m); if (s.phase === 'game_over') break; }
if (s.phase !== 'game_over') {
if (!L.turnDone(s)) legalBad++;
s = L.endTurn(s);
}
const tot = L.checkerTotals(s);
if (tot.white !== 15 || tot.black !== 15) consBad++;
}
return { winner: s.winner, result: s.result, guard, legalBad, consBad, dbl };
}
{
const N = QUICK ? 40 : 240;
let fin = 0, legal = 0, cons = 0, cubeGames = 0, drops = 0, kinds = { single: 0, gammon: 0, backgammon: 0, drop: 0 };
for (let g = 0; g < N; g++) {
const r = playGame(1 + (g % 5), 1 + ((g * 3) % 5), 300 + g, { cube: true, check: g % 4 === 0 });
if (r.winner && r.guard < 1500) fin++;
legal += r.legalBad; cons += r.consBad;
if (r.dbl) cubeGames++;
if (r.result?.kind === 'drop') drops++;
kinds[r.result?.kind ?? 'single']++;
}
ok(`${N} all-AI games with the cube all finish`, fin === N, `${fin}/${N}`);
ok('every AI turn is a legal maximal turn and ends the roll', legal === 0, `${legal} bad`);
ok('checkers conserved (15 a side) throughout', cons === 0);
ok('the AIs use the cube', cubeGames > N * 0.2, `${cubeGames} games with a double, ${drops} drops`);
ok('gammons happen but are not the norm', kinds.gammon + kinds.backgammon > 0 && kinds.gammon + kinds.backgammon < N * 0.5, JSON.stringify(kinds));
// cube judgement on clear positions
const crush = pos({ white: { 0: 3, 1: 3, 2: 3, 3: 3, 4: 3 }, black: { 18: 3, 19: 3, 20: 3, 21: 3, 22: 3 }, off: { white: 0, black: 0 } });
// white needs ~45 pips, black ~75 → white is a huge favourite
ok('skill 5 doubles a big race lead', AI.shouldDouble(crush, 'white', 5, null, () => 0.5));
const even = L.createInitialState();
even.phase = 'roll';
ok('skill 5 does not double the opening position', !AI.shouldDouble(even, 'white', 5, null, () => 0.5));
ok('skill 5 takes from the opening position', AI.shouldTake(L.offerDouble(even), 'black', 5, null, () => 0.5));
const hopeless = pos({ white: { 0: 2 }, black: { 0: 0, 12: 15 }, off: { white: 13 } });
ok('skill 5 drops a hopeless race', !AI.shouldTake(L.offerDouble(hopeless), 'black', 5, null, () => 0.5));
const m5 = L.createMatch(5); m5.score = { white: 4, black: 2 };
ok('dead cube: no double when a win already takes the match', !AI.shouldDouble(crush, 'white', 5, m5, () => 0.5));
// hint / explain
const op = L.openingWith(L.createInitialState(), 3, 1);
const h = AI.hint(op);
ok('hint for 3-1 opening makes the 5-point (8/5 6/5)', L.turnText('white', h.moves) === '8/5 6/5' || L.turnText('white', h.moves) === '6/5 8/5', L.turnText('white', h.moves));
ok('hint reason names the 5-point', /5-point/.test(h.reason), h.reason);
const op2 = L.openingWith(L.createInitialState(), 6, 1);
ok('hint for 6-1 opening makes the bar point (13/7 8/7)', /13\/7/.test(L.turnText('white', AI.hint(op2).moves)) && /8\/7/.test(L.turnText('white', AI.hint(op2).moves)), L.turnText('white', AI.hint(op2).moves));
}
section('Skill ladder (mirrored seeds)');
{
const pairs = (a, b, n, off) => {
let w = 0;
for (let i = 0; i < n; i++) {
if (playGame(a, b, 9000 + off + i).winner === 'white') w++;
if (playGame(b, a, 9000 + off + i).winner === 'black') w++;
}
return w / (2 * n);
};
const n = QUICK ? 30 : 150;
for (const [a, b] of [[2, 1], [3, 2], [4, 3]]) {
const r = pairs(a, b, n, a * 1000);
console.log(` skill ${a} vs ${b}: ${(r * 100).toFixed(1)}% over ${2 * n} games`);
ok(`skill ${a} beats skill ${b}`, r > (QUICK ? 0.5 : 0.55), `${(r * 100).toFixed(1)}%`);
}
const n5 = QUICK ? 8 : 60;
const t0 = Date.now();
const r5 = pairs(5, 4, n5, 5000);
console.log(` skill 5 vs 4: ${(r5 * 100).toFixed(1)}% over ${2 * n5} games (${((Date.now() - t0) / 1000).toFixed(0)} s)`);
if (!QUICK) ok('skill 5 beats skill 4', r5 > 0.55, `${(r5 * 100).toFixed(1)}%`);
// search time for one skill-5 decision in a busy middle game
const busy = L.rollSpecificDice({ ...L.createInitialState(), phase: 'roll' }, 3, 3);
const t1 = Date.now();
AI.chooseTurn(busy, 5, () => 0.5);
const dt = Date.now() - t1;
ok('a skill-5 decision on a double takes under 1.5 s (node)', dt < 1500, `${dt} ms`);
}
// ── dice ─────────────────────────────────────────────────────────────────────
section('Dice throws');
{
const lay = Lay.makeLayout(false);
const rng = mulberry32(3);
let badFace = 0, outside = 0, close = 0;
for (let k = 0; k < (QUICK ? 40 : 200); k++) {
const who = k % 2 ? 'white' : 'black';
const faces = [1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)];
const plan = planTrayThrow(lay.TRAY_WORLD, lay.throwOrigin(who), faces, rng, Lay.DIE_SIZE, { spread: 1.4, sep: 1.6, aim: { u0: 0.22, u1: 0.78, v0: 0.42, v1: 0.58 } });
plan.dice.forEach((d, i) => {
const last = d.frames[d.frames.length - 1];
if (topFace(last.q) !== faces[i]) badFace++;
if (last.u < Lay.DIE_SIZE / 2 - 1 || last.u > lay.TRAY_WORLD.w - Lay.DIE_SIZE / 2 + 1 || last.v < 0 || last.v > lay.TRAY_WORLD.h) outside++;
});
if (Math.hypot(plan.dice[0].u - plan.dice[1].u, plan.dice[0].v - plan.dice[1].v) < Lay.DIE_SIZE * 0.9) close++;
}
ok('every throw lands on the rolled faces', badFace === 0, `${badFace}`);
ok('dice stay inside the roller\'s half', outside === 0, `${outside}`);
ok('dice rarely land on top of each other', close <= 2, `${close}`);
const rest4 = lay.diceRest(4);
ok('four resting dice fit inside the half, apart', rest4.every((r) => r.u > Lay.DIE_SIZE && r.u < lay.TRAY_WORLD.w - Lay.DIE_SIZE) && rest4[1].u - rest4[0].u > Lay.DIE_SIZE * 1.5);
}
// ── layout ───────────────────────────────────────────────────────────────────
section('Layout');
{
const F = Lay.hudFurniture();
const inScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= Lay.W && r.y + r.h <= Lay.H;
for (const [k, r] of Object.entries(F)) ok(`${k} on screen`, inScreen(r), JSON.stringify(r));
const keys = Object.keys(F);
const overlap = (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;
let ov = [];
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) if (overlap(F[keys[i]], F[keys[j]])) ov.push(`${keys[i]}×${keys[j]}`);
ok('HUD furniture never overlaps', ov.length === 0, ov.join(', '));
ok('opponent speech bubble stays clear of the case', !overlap(Lay.OPP_PARTS.bubble, Lay.CASE) && inScreen(Lay.OPP_PARTS.bubble));
for (const mirror of [false, true]) {
const lay = Lay.makeLayout(mirror);
const tag = mirror ? ' (mirrored)' : '';
const xs = [...Array(24).keys()].map((i) => lay.pointX(i));
ok(`24 distinct point columns${tag}`, new Set(xs.map((x, i) => `${x}|${i < 12}`)).size === 24);
// point 1 next to the tray, point 12 / 13 at the far side
ok(`your 1-point sits beside the tray${tag}`, Math.abs(lay.pointX(0) - lay.trayX) < Math.abs(lay.pointX(11) - lay.trayX));
let stackOk = true, zoneOk = true;
for (let idx = 0; idx < 24; idx++) {
const z = lay.pointZone(idx);
for (let s = 0; s < 15; s++) {
const p = lay.slotPos(idx, s);
const inField = p.y - Lay.CR >= Lay.FY - 1 && p.y + Lay.CR <= Lay.FY + Lay.FH + 1;
const inTri = idx < 12 ? p.y - Lay.CR >= Lay.FY + Lay.FH - Lay.PH - 2 : p.y + Lay.CR <= Lay.FY + Lay.PH + 2;
if (!inField || !inTri || Math.abs(p.x - lay.pointX(idx)) > 0.01) stackOk = false;
if (lay.hitTest(p.x, p.y) !== idx) zoneOk = false;
}
if (z.w !== Lay.PW) zoneOk = false;
}
ok(`15-checker pyramids stay inside their triangle${tag}`, stackOk);
ok(`every stack slot hit-tests to its own point${tag}`, zoneOk);
ok(`pyramid tiers: 5 + 4 + 3 + 2 + 1${tag}`, lay.stackSlot(4).tier === 0 && lay.stackSlot(5).tier === 1 && lay.stackSlot(14).tier === 4);
const off = [...Array(15).keys()].map((s) => lay.offPos('white', s));
const offB = [...Array(15).keys()].map((s) => lay.offPos('black', s));
ok(`15 borne-off checkers fit in each half of the tray${tag}`, off.every((p) => p.y > Lay.MID_Y + 15 && p.y < Lay.FY + Lay.FH) && offB.every((p) => p.y < Lay.MID_Y - 15 && p.y > Lay.FY));
ok(`tray hit-test${tag}`, lay.hitTest(off[3].x, off[3].y) === 'off' && lay.hitTest(offB[3].x, offB[3].y) === 'off');
const bar = [...Array(6).keys()].map((s) => lay.barPos('white', s, 6));
const cubeW = lay.cubePos('white'), cubeC = lay.cubePos(null);
ok(`bar checkers clear the cube${tag}`, bar.every((p) => Math.abs(p.y - cubeW.y) >= Lay.CR + 32 && Math.abs(p.y - cubeC.y) >= Lay.CR + 32));
ok(`bar hit-test${tag}`, lay.hitTest(bar[0].x, bar[0].y) === 'bar');
ok(`throw origins inside the case span${tag}`, ['white', 'black'].every((w) => { const o = lay.throwOrigin(w); return o.u > 0 && o.u < lay.TRAY_WORLD.w; }));
}
const a = Lay.makeLayout(false), b = Lay.makeLayout(true);
ok('mirroring is a reflection about the case centre', [...Array(24).keys()].every((i) => Math.abs(a.pointX(i) + b.pointX(i) - 2 * Lay.CASE_CX) < 0.01) && Math.abs(a.trayX + b.trayX - 2 * Lay.CASE_CX) < 0.01);
}
// ── checker registry ─────────────────────────────────────────────────────────
section('Checker registry');
{
const img = () => ({ setDepth() { return this; }, setAlpha() { return this; }, setTexture() { return this; }, setPosition() { return this; }, setScale() { return this; }, setRotation() { return this; } });
const scene = { add: { image: () => img() }, tweens: { add() {} } };
const cs = new CheckerSet(scene, Lay.makeLayout(false), 10).build();
let s = L.openingWith(L.createInitialState(), 6, 5);
cs.sync(s);
const where = () => cs.items.map((it) => `${it.key}#${it.slot}`);
const ok15 = () => ['white', 'black'].every((c) => [...cs.lists[c].values()].reduce((a, l) => a + l.length, 0) === 15);
ok('initial assignment: 15 a side', ok15());
const rng = mulberry32(9);
let stable = true, conserved = true;
for (let t = 0; t < 400 && s.phase !== 'game_over'; t++) {
if (s.phase === 'roll') s = L.rollDice(s, rng);
const moves = L.getValidMoves(s);
if (!moves.length) { s = L.endTurn(s); continue; }
const m = moves[Math.floor(rng() * moves.length)];
const mover = cs.topOf(s.currentPlayer, m.from);
const victim = m.hit ? cs.topOf(L.other(s.currentPlayer), m.to) : null;
const before = where();
s = L.applyMove(s, m);
cs.sync(s);
const after = where();
const changed = after.map((w, i) => (w !== before[i] ? i : -1)).filter((i) => i >= 0);
const allowed = new Set([mover?.id, victim?.id]);
if (!changed.every((i) => allowed.has(i)) || (mover && cs.items[mover.id].key === `${before[mover.id].split('#')[0]}` && m.from !== m.to)) stable = false;
if (!ok15()) conserved = false;
if (L.turnDone(s) && s.phase !== 'game_over') s = L.endTurn(s);
}
ok('a move relocates only the moving checker (and a hit victim)', stable);
ok('registry conserves 15 a side', conserved);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);