Rewrite Zahtzee as a game-night dice table with expert AI

- Replace the flat panel UI with baked art: plank room, felt tray, keeper ledge, leather cup, clipboard score pad, and opponent seats
- Add YatziSolver (exact expected-value turn solver) and rework YatziAI into a 5-level skill ladder plus a Coach readout with chase odds
- Generalize Dice3D.planTrayThrow from two dice to N dice with configurable spread/aim
- Split game code into YatziLayout, YatziArt, YatziTray, YatziPad, YatziDialogs, and YatziEndScreen; update YatziGame to drive them
- Extend YatziLogic with Joker modes, per-player stats, upper-par meter, rankings, and a commit log
- Add a tutorial (tutorial.md), enable it in the game registry, and add tools/verifyYatzi.js for headless rule/solver/AI/layout checks
This commit is contained in:
Brian Fertig 2026-11-25 11:43:45 -07:00
parent 01372c1c62
commit 98b4dfdb8e
No known key found for this signature in database
14 changed files with 3034 additions and 892 deletions

View File

@ -31,7 +31,7 @@ registerGame({ slug: 'backgammon', name: 'Backgammon', category: 'tabletop', min
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 });
registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 4 }); registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 4 });
registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 }); registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 });
registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 }); registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 });
registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 }); registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 });

View File

@ -1,139 +1,233 @@
// Heuristic Yatzi AI. Stateless functions consumed by YatziGame. // Zahtzee opponents, skill 1–5. Phaser-free.
// //
// `chooseDiceToHold(dice, scorecard, rollsRemaining)` → 5-bool hold mask // planTurn(scorecard, bonusCount, skill, rng) → a turn planner:
// `chooseCategory(dice, scorecard)` → category slug // .chooseHold(dice, held, rollsRemaining) → 5-bool hold mask
// `shouldKeepRolling(holdMask, rollsRemaining)` → boolean // .shouldStop(mask) → true when nothing would be re-rolled
// .chooseCategory(dice) → category slug
// boxUtility / expertAdvice — shared with the Coach readout.
//
// The ladder:
// 5 exact one-turn expected-value play (YatziSolver) over a utility that
// prices each box's future worth and the upper-bonus chances
// 4 the same solver, but planning only one throw ahead (and the odd slip)
// 3 pattern heuristic for dice, expert box choice
// 2 pattern heuristic with the odd slip, greedy raw-points boxes
// 1 pattern heuristic with frequent slips, greedy boxes, stands pat early
import { import {
UPPER, legalCategories, scoreForCommit, isYahtzee, UPPER, CATEGORIES, legalCategories, scoreForCommit, jokerStatus,
isYahtzee, isFullHouse, isSmallStraight, isLargeStraight, diceCounts,
UPPER_BONUS, UPPER_BONUS_AT, YAHTZEE_BONUS,
} from './YatziLogic.js'; } from './YatziLogic.js';
import { solveTurn, rankKeeps, maskForKeep, chaseOdds } from './YatziSolver.js';
export function chooseDiceToHold(dice, scorecard, rollsRemaining) { // Average score each box yields under optimal solitaire play — what a box is
const open = (c) => scorecard[c] === null; // "worth" while it stays open. Scoring into a box gives up this future value.
const counts = {}; export const BOX_WORTH = {
for (const d of dice) counts[d] = (counts[d] || 0) + 1; ones: 1.88, twos: 5.28, threes: 8.57, fours: 12.16, fives: 15.69, sixes: 19.19,
threeOfKind: 21.66, fourOfKind: 13.10, fullHouse: 22.59, smallStraight: 29.46,
largeStraight: 32.71, yahtzee: 19.5, chance: 22.01,
};
const UPPER_MEAN = [0, 1.88, 5.28, 8.57, 12.16, 15.69, 19.19];
const UPPER_SD = [0, 1.1, 2.2, 3.2, 4.2, 5.2, 6.2];
// Yahtzee in hand — always hold all (Joker rules let us score it somewhere) // Rough chance of reaching 63 from `sub` with `openFaces` still to fill.
if (isYahtzee(dice)) return [true, true, true, true, true]; export function bonusChance(sub, openFaces) {
const need = UPPER_BONUS_AT - sub;
const face4 = faceWithCount(counts, 4); if (need <= 0) return 1;
const face3 = faceWithCount(counts, 3); if (openFaces.length === 0) return 0;
const pairs = Object.entries(counts).filter(([, c]) => c >= 2).map(([f]) => Number(f)); let mean = 0, varSum = 0, max = 0;
for (const f of openFaces) { mean += UPPER_MEAN[f]; varSum += UPPER_SD[f] ** 2; max += 5 * f; }
// 4-of-a-kind: hold the four; reroll the spare hunting Yahtzee if (need > max) return 0;
if (face4 !== null && (open('yahtzee') || open('fourOfKind') || open('threeOfKind'))) { const z = (mean - need) / Math.sqrt(varSum + 4);
return dice.map((d) => d === face4); return 1 / (1 + Math.exp(-1.7 * z));
}
// Full house in hand
if (face3 !== null && pairs.some((p) => p !== face3) && open('fullHouse')) {
return [true, true, true, true, true];
}
// Large straight in hand (5 in a row)
if (hasLargeStraight(dice) && open('largeStraight')) {
return [true, true, true, true, true];
}
// Small straight in hand (4 in a row) — hold those 4, reroll the dupe
const smallStraightHold = holdForSmallStraight(dice);
if (smallStraightHold && (open('smallStraight') || open('largeStraight'))) {
return smallStraightHold;
}
// 3-of-a-kind in hand
if (face3 !== null) {
if (open('threeOfKind') || open('fourOfKind') || open('yahtzee') || open(UPPER[face3 - 1])) {
return dice.map((d) => d === face3);
}
}
// 4-in-a-row distinct values — chase a straight if slots open
const run = longestConsecutive(dice);
if (run.length >= 4 && (open('largeStraight') || open('smallStraight'))) {
return maskMatchingValues(dice, run);
}
// 3-in-a-row + open straight goals — keep the run
if (run.length === 3 && rollsRemaining >= 1 && (open('largeStraight') || open('smallStraight'))) {
return maskMatchingValues(dice, run);
}
// Highest pair toward upper / 3-of-a-kind
if (pairs.length > 0) {
const bestPair = Math.max(...pairs);
if (open(UPPER[bestPair - 1]) || open('threeOfKind') || open('fourOfKind') || open('yahtzee')) {
return dice.map((d) => d === bestPair);
}
}
// Nothing matched: keep individual high pips whose upper slot is open
const held = [false, false, false, false, false];
for (let i = 0; i < 5; i++) {
const f = dice[i];
if (f >= 4 && open(UPPER[f - 1])) held[i] = true;
}
return held;
} }
// AI decides to stop early if every die is held (further rolls do nothing). function upperState(scorecard) {
export function shouldKeepRolling(holdMask, rollsRemaining) { let sub = 0;
if (rollsRemaining <= 0) return false; const open = [];
return holdMask.some((h) => !h); UPPER.forEach((c, i) => { if (scorecard[c] === null) open.push(i + 1); else sub += scorecard[c]; });
return { sub, open };
} }
// Pick the category to commit to. Best score wins; ties resolved by // Utility of placing `dice` into `cat`. `mode` 'expert' prices future value
// sacrificing the cheapest slot first. // and bonus chances; 'raw' just counts points this turn (+ a bonus crossed now).
export function chooseCategory(dice, scorecard) { export function boxUtility(dice, cat, scorecard, mode = 'expert') {
const s = scoreForCommit(dice, cat, scorecard);
if (s === null) return -Infinity;
const j = jokerStatus(dice, scorecard);
let u = s + (j.bonus ? YAHTZEE_BONUS : 0);
const fi = UPPER.indexOf(cat);
const { sub, open } = upperState(scorecard);
if (mode === 'raw') {
if (fi >= 0 && sub < UPPER_BONUS_AT && sub + s >= UPPER_BONUS_AT) u += UPPER_BONUS;
return u;
}
const openCount = CATEGORIES.filter((c) => scorecard[c] === null).length;
if (openCount > 1) u -= BOX_WORTH[cat];
if (fi >= 0) {
const face = fi + 1;
const before = bonusChance(sub, open);
const after = bonusChance(sub + s, open.filter((f) => f !== face));
u += UPPER_BONUS * 1.2 * (after - before);
}
// Scratching the Zahtzee box forfeits every future +100.
if (cat === 'yahtzee' && s === 0 && openCount > 1) u -= 4 + 0.6 * openCount;
return u;
}
export function bestCategory(dice, scorecard, mode = 'expert') {
const legal = legalCategories(dice, scorecard);
let best = null, bestU = -Infinity;
for (const c of legal) {
const u = boxUtility(dice, c, scorecard, mode);
if (u > bestU || (u === bestU && sacrificeRank(c) < sacrificeRank(best))) { best = c; bestU = u; }
}
return best;
}
function finalUtility(scorecard, mode) {
return (dice) => {
const legal = legalCategories(dice, scorecard);
let best = -Infinity;
for (const c of legal) { const u = boxUtility(dice, c, scorecard, mode); if (u > best) best = u; }
return best;
};
}
const solverCache = new Map();
function solverFor(scorecard, mode) {
const key = mode + '|' + CATEGORIES.map((c) => scorecard[c] ?? '_').join(',');
let sol = solverCache.get(key);
if (!sol) {
if (solverCache.size > 200) solverCache.clear();
sol = solveTurn(finalUtility(scorecard, mode));
solverCache.set(key, sol);
}
return sol;
}
// ── The Coach ────────────────────────────────────────────────────────────────
// Expert keep for these dice plus the odds of the open patterns if chased.
const PATTERNS = [
{ cat: 'yahtzee', label: 'Zahtzee', test: isYahtzee },
{ cat: 'largeStraight', label: 'Lg. Straight', test: isLargeStraight },
{ cat: 'smallStraight', label: 'Sm. Straight', test: isSmallStraight },
{ cat: 'fullHouse', label: 'Full House', test: (d) => isFullHouse(d) },
{ cat: 'fourOfKind', label: '4 of a Kind', test: (d) => diceCounts(d).some((v) => v >= 4) },
];
export function expertAdvice(dice, held, scorecard, rollsRemaining) {
const sol = solverFor(scorecard, 'expert');
const ranked = rankKeeps(sol, dice, rollsRemaining);
const best = ranked[0];
const mask = maskForKeep(dice, best.dice, held);
const odds = [];
for (const p of PATTERNS) {
const open = scorecard[p.cat] === null || (p.cat === 'yahtzee' && scorecard.yahtzee === 50);
if (!open) continue;
if (p.test(dice)) continue; // already made
odds.push({ cat: p.cat, label: p.label, p: chaseOdds(p.cat, p.test, dice, rollsRemaining) });
}
odds.sort((a, b) => b.p - a.p);
return { mask, keep: best.dice, stop: best.dice.length === 5, value: best.value, odds };
}
// ── Opponent turns ───────────────────────────────────────────────────────────
export function planTurn(scorecard, bonusCount, skill = 3, rng = Math.random) {
const k = Math.max(1, Math.min(5, Math.round(skill)));
const blunder = { 1: 0.35, 2: 0.15, 3: 0 }[k] ?? 0;
return {
skill: k,
chooseHold(dice, held, rollsRemaining) {
if (k >= 4) {
// Skill 4 plays the same solver but only ever plans one throw ahead.
const horizon = k === 5 ? rollsRemaining : 1;
const ranked = rankKeeps(solverFor(scorecard, 'expert'), dice, horizon);
const slip = k === 4 && ranked.length > 1 && rng() < 0.1;
return maskForKeep(dice, ranked[slip ? 1 : 0].dice, held);
}
let mask = heuristicHold(dice, scorecard, rollsRemaining);
if (blunder && rng() < blunder) {
const i = Math.floor(rng() * 5);
mask = mask.slice(); mask[i] = !mask[i];
}
// A careless player sometimes just stands pat on the second roll.
if (k === 1 && rollsRemaining === 1 && rng() < 0.2) mask = [true, true, true, true, true];
return mask;
},
shouldStop(mask) {
return mask.every(Boolean);
},
chooseCategory(dice) {
if (k <= 2) return greedyCategory(dice, scorecard);
return bestCategory(dice, scorecard, 'expert');
},
};
}
// Best raw score; ties broken by sacrificing the cheapest box.
function greedyCategory(dice, scorecard) {
const legal = legalCategories(dice, scorecard); const legal = legalCategories(dice, scorecard);
if (legal.length === 0) return null; if (legal.length === 0) return null;
const scored = legal.map((c) => ({ c, v: scoreForCommit(dice, c, scorecard) ?? 0 })); const scored = legal.map((c) => ({ c, v: scoreForCommit(dice, c, scorecard) ?? 0 }));
scored.sort((a, b) => { scored.sort((a, b) => (b.v - a.v) || (sacrificeRank(a.c) - sacrificeRank(b.c)));
if (b.v !== a.v) return b.v - a.v;
return sacrificeRank(a.c) - sacrificeRank(b.c);
});
return scored[0].c; return scored[0].c;
} }
// Lower rank = cheaper to zero out when no slot scores positive
const SACRIFICE_ORDER = [ const SACRIFICE_ORDER = [
'ones', 'twos', 'threes', 'ones', 'twos', 'threes', 'fourOfKind', 'threeOfKind', 'fours', 'fives',
'fourOfKind', 'threeOfKind', 'fullHouse', 'smallStraight', 'sixes', 'largeStraight', 'chance', 'yahtzee',
'fours', 'fives',
'fullHouse', 'smallStraight',
'sixes',
'largeStraight', 'chance', 'yahtzee',
]; ];
function sacrificeRank(category) { function sacrificeRank(category) {
const i = SACRIFICE_ORDER.indexOf(category); const i = SACRIFICE_ORDER.indexOf(category);
return i === -1 ? 99 : i; return i === -1 ? 99 : i;
} }
// ── Helpers ───────────────────────────────────────────────────────────────── // ── Pattern heuristic (skills 1–2) ───────────────────────────────────────────
function heuristicHold(dice, scorecard, rollsRemaining) {
const open = (c) => scorecard[c] === null;
const counts = diceCounts(dice);
if (isYahtzee(dice)) return [true, true, true, true, true];
function faceWithCount(counts, n) { const faceWith = (n) => { for (let f = 6; f >= 1; f--) if (counts[f] >= n) return f; return null; };
for (const [f, c] of Object.entries(counts)) { const face4 = faceWith(4);
if (c >= n) return Number(f); const face3 = faceWith(3);
const pairs = [1, 2, 3, 4, 5, 6].filter((f) => counts[f] >= 2);
if (face4 !== null && (open('yahtzee') || open('fourOfKind') || open('threeOfKind') || open(UPPER[face4 - 1]))) {
return dice.map((d) => d === face4);
} }
return null; if (isFullHouse(dice) && open('fullHouse')) return [true, true, true, true, true];
} if (isLargeStraight(dice) && open('largeStraight')) return [true, true, true, true, true];
const ss = holdForSmallStraight(dice);
function hasLargeStraight(dice) { if (ss && (open('smallStraight') || open('largeStraight'))) {
const s = new Set(dice); return open('largeStraight') ? ss : [true, true, true, true, true];
return [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]].some((seq) => seq.every((n) => s.has(n))); }
if (face3 !== null && (open('threeOfKind') || open('fourOfKind') || open('yahtzee') || open(UPPER[face3 - 1]))) {
return dice.map((d) => d === face3);
}
const run = longestConsecutive(dice);
if (run.length >= 3 && rollsRemaining >= 1 && (open('largeStraight') || open('smallStraight'))) {
return maskMatchingValues(dice, run);
}
if (pairs.length > 0) {
const bestPair = Math.max(...pairs);
if (open(UPPER[bestPair - 1]) || open('threeOfKind') || open('fourOfKind') || open('yahtzee')) {
return dice.map((d) => d === bestPair);
}
}
return dice.map((f) => f >= 5 && open(UPPER[f - 1]));
} }
function holdForSmallStraight(dice) { function holdForSmallStraight(dice) {
const s = new Set(dice); const s = new Set(dice);
for (const seq of [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]) { for (const seq of [[3, 4, 5, 6], [2, 3, 4, 5], [1, 2, 3, 4]]) {
if (seq.every((n) => s.has(n))) { if (seq.every((n) => s.has(n))) return maskMatchingValues(dice, seq);
return maskMatchingValues(dice, seq);
}
} }
return null; return null;
} }
// Build a hold mask that picks one die per target value (in order).
function maskMatchingValues(dice, targets) { function maskMatchingValues(dice, targets) {
const need = {}; const need = {};
for (const t of targets) need[t] = (need[t] ?? 0) + 1; for (const t of targets) need[t] = (need[t] ?? 0) + 1;
@ -144,16 +238,34 @@ function maskMatchingValues(dice, targets) {
return mask; return mask;
} }
// Longest run of consecutive distinct values in dice.
function longestConsecutive(dice) { function longestConsecutive(dice) {
const unique = [...new Set(dice)].sort((a, b) => a - b); const unique = [...new Set(dice)].sort((a, b) => a - b);
if (unique.length === 0) return []; let best = [unique[0]], cur = [unique[0]];
let best = [unique[0]];
let cur = [unique[0]];
for (let i = 1; i < unique.length; i++) { for (let i = 1; i < unique.length; i++) {
if (unique[i] === unique[i - 1] + 1) cur.push(unique[i]); if (unique[i] === unique[i - 1] + 1) cur.push(unique[i]); else cur = [unique[i]];
else cur = [unique[i]];
if (cur.length > best.length) best = [...cur]; if (cur.length > best.length) best = [...cur];
} }
return best; return best;
} }
// What the AI is chasing with this hold — feeds the table talk.
export function describeKeep(dice, mask) {
const kept = dice.filter((_, i) => mask[i]);
if (kept.length === 0) return { kind: 'fresh' };
if (kept.length === 5) return { kind: 'stand' };
const c = diceCounts(kept);
const top = [1, 2, 3, 4, 5, 6].reduce((a, f) => (c[f] > c[a] ? f : a), 1);
if (c[top] >= 2 && kept.every((d) => d === top)) return { kind: 'set', face: top, n: c[top] };
const uniq = new Set(kept);
if (uniq.size === kept.length && kept.length >= 3) {
const s = [...uniq].sort((a, b) => a - b);
if (s[s.length - 1] - s[0] <= 4) return { kind: 'straight' };
}
if (kept.length === 4 && isFullHouseDraw(c)) return { kind: 'house' };
return { kind: 'mixed' };
}
function isFullHouseDraw(c) {
const v = c.filter((x) => x > 0).sort();
return v.length === 2 && v[0] === 2 && v[1] === 2;
}

448
src/games/yatzi/YatziArt.js Normal file
View File

@ -0,0 +1,448 @@
// YatziArt.js — baked canvas textures for the Zahtzee game-night table.
//
// yatzi-room warm plank kitchen table, lamp pool over the tray, vignette
// yatzi-vignette lamp + vignette overlay for a chosen playfield "tablecloth"
// yatzi-tray walnut dice tray with a green felt well
// yatzi-ledge the keeper ledge: shelf with five numbered slots
// yatzi-cup a stitched leather dice cup
// yatzi-seat an opponent's wooden place-card
// yatzi-pad-N clipboard + printed score sheet for N players
// yatzi-hand a soft ghost hand (tinted per opponent)
// yatzi-spark a small soft spark for flourishes
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
import {
W, H, TRAY, TRAY_FELT, TRAY_WALL, LEDGE, COLUMN_X, CUP, SEAT, BOARD, CLIP, PAPER,
PAD_TITLE, GRID, LABEL_W, PAD_ROWS, colX,
} from './YatziLayout.js';
import { CATEGORY_LABELS, CATEGORY_HINTS } from './YatziLogic.js';
export const PAD_PX = 26; // shadow margin baked around tray / ledge / board
export const INK = ['#22304f', '#9c2121', '#1d6a3c', '#5a2a86'];
export const INK_HEX = [0x22304f, 0x9c2121, 0x1d6a3c, 0x5a2a86];
export const SEAT_TINT = [0x4f86c6, 0xd0533f, 0x3f9d66, 0x9364c9];
export const HAND_FONT = 'YummyCupcakes, "Comic Sans MS", cursive';
export const PRINT_FONT = '"Julius Sans One", Georgia, serif';
export const DISPLAY_FONT = 'Righteous, Georgia, serif';
export const SERIF = 'Georgia, "Times New Roman", serif';
function addCanvas(scene, key, c) {
if (scene.textures.exists(key)) scene.textures.remove(key);
scene.textures.addCanvas(key, c);
}
// ── wood ──────────────────────────────────────────────────────────────────────
function grain(ctx, x, y, w, h, { tone = 'rgba(40,20,8,0.22)', lines = 14, wave = 3 } = {}) {
ctx.save();
ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
ctx.strokeStyle = tone;
for (let i = 0; i < lines; i++) {
const yy = y + Math.random() * h;
const amp = wave * (0.4 + Math.random());
const f = 0.004 + Math.random() * 0.01;
const ph = Math.random() * 6;
ctx.lineWidth = 0.6 + Math.random() * 1.4;
ctx.beginPath();
for (let xx = x; xx <= x + w; xx += 8) {
const yv = yy + Math.sin(xx * f + ph) * amp + Math.sin(xx * f * 3.1 + ph) * amp * 0.3;
if (xx === x) ctx.moveTo(xx, yv); else ctx.lineTo(xx, yv);
}
ctx.stroke();
}
// a knot or two
if (w > 300 && Math.random() < 0.7) {
const kx = x + Math.random() * w, ky = y + h * (0.3 + Math.random() * 0.4);
for (let r = 3; r < 16; r += 3) {
ctx.lineWidth = 1;
ctx.beginPath(); ctx.ellipse(kx, ky, r * 2.2, r * 0.7, 0, 0, Math.PI * 2); ctx.stroke();
}
}
ctx.restore();
}
function planks(ctx, x, y, w, h, { plankH = 120, tones = ['#7a4a26', '#6e4122', '#83502a', '#744624'] } = {}) {
let i = 0;
for (let py = y; py < y + h; py += plankH, i++) {
const ph = Math.min(plankH, y + h - py);
const g = ctx.createLinearGradient(0, py, 0, py + ph);
const base = tones[i % tones.length];
g.addColorStop(0, base); g.addColorStop(0.5, shade(base, 1.06)); g.addColorStop(1, shade(base, 0.9));
ctx.fillStyle = g;
ctx.fillRect(x, py, w, ph);
grain(ctx, x, py, w, ph, { lines: 18 });
ctx.fillStyle = 'rgba(20,8,2,0.55)';
ctx.fillRect(x, py + ph - 2, w, 2);
ctx.fillStyle = 'rgba(255,220,170,0.08)';
ctx.fillRect(x, py, w, 1.5);
// staggered butt joints
const jx = x + ((i * 617) % Math.max(1, w - 200)) + 100;
ctx.fillStyle = 'rgba(20,8,2,0.45)';
ctx.fillRect(jx, py, 2, ph);
}
}
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]})`;
}
function lamp(ctx, cx, cy, r, alpha = 0.28) {
const g = ctx.createRadialGradient(cx, cy, 10, cx, cy, r);
g.addColorStop(0, `rgba(255,214,150,${alpha})`);
g.addColorStop(0.6, `rgba(255,190,120,${alpha * 0.35})`);
g.addColorStop(1, 'rgba(255,190,120,0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
function vignette(ctx, k = 0.6) {
const g = ctx.createRadialGradient(W * 0.42, H * 0.48, H * 0.35, W * 0.5, H * 0.5, H * 1.05);
g.addColorStop(0, 'rgba(0,0,0,0)');
g.addColorStop(1, `rgba(0,0,0,${k})`);
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
function bakeRoom(scene) {
const c = canvas(W, H), ctx = c.getContext('2d');
planks(ctx, 0, 0, W, H, { plankH: 135 });
ctx.fillStyle = noisePattern(ctx, 128, 26);
ctx.fillRect(0, 0, W, H);
lamp(ctx, TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, 900, 0.3);
lamp(ctx, BOARD.x + BOARD.w / 2, H * 0.45, 600, 0.12);
vignette(ctx, 0.62);
addCanvas(scene, 'yatzi-room', c);
const v = canvas(W, H), vx = v.getContext('2d');
lamp(vx, TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, 900, 0.18);
vignette(vx, 0.55);
addCanvas(scene, 'yatzi-vignette', v);
}
// ── tray ──────────────────────────────────────────────────────────────────────
function dropShadow(ctx, fn, { blur = 22, dy = 10, alpha = 0.55 } = {}) {
ctx.save();
ctx.shadowColor = `rgba(0,0,0,${alpha})`;
ctx.shadowBlur = blur; ctx.shadowOffsetY = dy;
fn();
ctx.restore();
}
function bakeTray(scene) {
const P = PAD_PX;
const c = canvas(TRAY.w + P * 2, TRAY.h + P * 2), ctx = c.getContext('2d');
const x = P, y = P, w = TRAY.w, h = TRAY.h;
dropShadow(ctx, () => { rr(ctx, x, y, w, h, 26); ctx.fillStyle = '#4a2b14'; ctx.fill(); }, { blur: 30, dy: 16, alpha: 0.65 });
// frame wood
ctx.save(); rr(ctx, x, y, w, h, 26); ctx.clip();
const g = ctx.createLinearGradient(0, y, 0, y + h);
g.addColorStop(0, '#7b4a24'); g.addColorStop(0.5, '#5e3519'); g.addColorStop(1, '#4b2912');
ctx.fillStyle = g; ctx.fillRect(x, y, w, h);
grain(ctx, x, y, w, h, { lines: 40, tone: 'rgba(25,10,3,0.3)' });
ctx.restore();
// rim highlight
ctx.strokeStyle = 'rgba(255,214,160,0.35)'; ctx.lineWidth = 2;
rr(ctx, x + 2, y + 2, w - 4, h - 4, 24); ctx.stroke();
// felt well
const fx = P + TRAY_WALL, fy = P + TRAY_WALL, fw = TRAY_FELT.w, fh = TRAY_FELT.h;
ctx.save(); rr(ctx, fx, fy, fw, fh, 14); ctx.clip();
const fg = ctx.createRadialGradient(fx + fw / 2, fy + fh * 0.45, 40, fx + fw / 2, fy + fh / 2, fw * 0.62);
fg.addColorStop(0, '#2f7a4f'); fg.addColorStop(1, '#174a2e');
ctx.fillStyle = fg; ctx.fillRect(fx, fy, fw, fh);
ctx.fillStyle = noisePattern(ctx, 96, 40); ctx.fillRect(fx, fy, fw, fh);
// the far wall's inner face (seen at an angle) and inner shadows
const wallG = ctx.createLinearGradient(0, fy, 0, fy + 26);
wallG.addColorStop(0, '#3e2210'); wallG.addColorStop(1, 'rgba(62,34,16,0)');
ctx.fillStyle = wallG; ctx.fillRect(fx, fy, fw, 26);
const ls = ctx.createLinearGradient(fx, 0, fx + 22, 0);
ls.addColorStop(0, 'rgba(0,0,0,0.45)'); ls.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = ls; ctx.fillRect(fx, fy, 22, fh);
const rs = ctx.createLinearGradient(fx + fw, 0, fx + fw - 22, 0);
rs.addColorStop(0, 'rgba(0,0,0,0.35)'); rs.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = rs; ctx.fillRect(fx + fw - 22, fy, 22, fh);
const bs = ctx.createLinearGradient(0, fy + fh, 0, fy + fh - 14);
bs.addColorStop(0, 'rgba(0,0,0,0.3)'); bs.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = bs; ctx.fillRect(fx, fy + fh - 14, fw, 14);
ctx.restore();
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 2;
rr(ctx, fx, fy, fw, fh, 14); ctx.stroke();
// brass corner caps
for (const [cx, cy] of [[x + 16, y + 16], [x + w - 16, y + 16], [x + 16, y + h - 16], [x + w - 16, y + h - 16]]) {
const bg = ctx.createRadialGradient(cx - 3, cy - 3, 1, cx, cy, 9);
bg.addColorStop(0, '#fff1b8'); bg.addColorStop(1, '#a67c2c');
ctx.fillStyle = bg; ctx.beginPath(); ctx.arc(cx, cy, 7, 0, Math.PI * 2); ctx.fill();
}
addCanvas(scene, 'yatzi-tray', c);
}
// ── keeper ledge ─────────────────────────────────────────────────────────────
function bakeLedge(scene) {
const P = PAD_PX;
const c = canvas(LEDGE.w + P * 2, LEDGE.h + P * 2), ctx = c.getContext('2d');
const x = P, y = P, w = LEDGE.w, h = LEDGE.h;
const topH = 66;
dropShadow(ctx, () => { rr(ctx, x, y, w, h, 14); ctx.fillStyle = '#3a200d'; ctx.fill(); }, { blur: 22, dy: 12, alpha: 0.6 });
// shelf top
ctx.save(); rr(ctx, x, y, w, h, 14); ctx.clip();
const tg = ctx.createLinearGradient(0, y, 0, y + topH);
tg.addColorStop(0, '#9a6232'); tg.addColorStop(1, '#7d4c25');
ctx.fillStyle = tg; ctx.fillRect(x, y, w, topH);
grain(ctx, x, y, w, topH, { lines: 14 });
// front face
const fg = ctx.createLinearGradient(0, y + topH, 0, y + h);
fg.addColorStop(0, '#5c3417'); fg.addColorStop(1, '#3f230f');
ctx.fillStyle = fg; ctx.fillRect(x, y + topH, w, h - topH);
grain(ctx, x, y + topH, w, h - topH, { lines: 10, tone: 'rgba(15,6,2,0.35)' });
ctx.fillStyle = 'rgba(255,220,170,0.25)'; ctx.fillRect(x, y + topH, w, 2);
ctx.restore();
// felt slots + engraved key numbers
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
COLUMN_X.forEach((sx, i) => {
const cx = sx - LEDGE.x + P;
const cy = y + topH * 0.62;
ctx.save();
ctx.beginPath(); ctx.ellipse(cx, cy, 60, 20, 0, 0, Math.PI * 2);
const sg = ctx.createRadialGradient(cx, cy - 4, 4, cx, cy, 60);
sg.addColorStop(0, '#1d5636'); sg.addColorStop(1, '#0f3020');
ctx.fillStyle = sg; ctx.fill();
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 2; ctx.stroke();
ctx.restore();
ctx.font = 'bold 22px Georgia, serif';
ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fillText(String(i + 1), cx + 1, y + topH + (h - topH) / 2 + 2);
ctx.fillStyle = '#d9b27a'; ctx.fillText(String(i + 1), cx, y + topH + (h - topH) / 2);
});
ctx.font = 'italic 15px Georgia, serif';
ctx.fillStyle = 'rgba(240,210,160,0.6)';
ctx.textAlign = 'left';
ctx.fillText('KEEPERS', x + 16, y + topH + (h - topH) / 2);
addCanvas(scene, 'yatzi-ledge', c);
}
// ── dice cup ─────────────────────────────────────────────────────────────────
function bakeCup(scene) {
const P = 14;
const cw = CUP.w, ch = 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; // mouth (wider)
const lb = P + 18, rb = P + cw - 18; // base
// shadow
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();
// body
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, '#3a1c0d'); g.addColorStop(0.3, '#7a3a1a'); g.addColorStop(0.55, '#5c2a12'); g.addColorStop(1, '#2a1208');
ctx.fillStyle = g; ctx.fill();
ctx.clip();
ctx.fillStyle = noisePattern(ctx, 64, 50); ctx.fillRect(0, 0, c.width, c.height);
// stitched bands — each follows the front half of an ellipse whose depth
// eases from the mouth's (ry 16) to the base's (ry 10), like the cup's
// cross-section at that height. Stitches are spaced evenly in angle, so they
// foreshorten and crowd together as they wrap round the sides.
const cxm = P + cw / 2;
const ring = (yy) => {
const f = (yy - top) / (bot - top);
return { hw: ((rt - lt) / 2) * (1 - f) + ((rb - lb) / 2) * f + 2, ry: 16 * (1 - f) + 10 * f };
};
const arcPt = (yy, r, th) => ({ x: cxm + r.hw * Math.cos(th), y: yy + r.ry * Math.sin(th) });
for (const yy of [top + 26, bot - 22]) {
const r = ring(yy);
// the darker leather band: the region between two curved edges
ctx.beginPath();
for (let i = 0; i <= 40; i++) { const p = arcPt(yy - 9, r, Math.PI * (1 - i / 40)); if (i) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); }
for (let i = 0; i <= 40; i++) { const p = arcPt(yy + 9, r, Math.PI * (i / 40)); ctx.lineTo(p.x, p.y); }
ctx.closePath();
ctx.fillStyle = 'rgba(0,0,0,0.28)'; ctx.fill();
// two rows of stitches
const N = 26;
for (const off of [-5, 5]) {
for (let k = 0; k < N; k++) {
const a0 = Math.PI * (k + 0.2) / N, a1 = Math.PI * (k + 0.75) / N;
const p0 = arcPt(yy + off, r, a0), p1 = arcPt(yy + off, r, a1);
const face = Math.sin((a0 + a1) / 2); // 1 facing us, → 0 at the sides
ctx.lineCap = 'round';
ctx.lineWidth = 1 + 1.4 * face;
ctx.strokeStyle = `rgba(20,8,2,${0.45 * face})`; // stitch shadow
ctx.beginPath(); ctx.moveTo(p0.x + 0.8, p0.y + 1.2); ctx.lineTo(p1.x + 0.8, p1.y + 1.2); ctx.stroke();
ctx.strokeStyle = `rgba(233,201,143,${0.35 + 0.65 * face})`;
ctx.beginPath(); ctx.moveTo(p0.x, p0.y); ctx.lineTo(p1.x, p1.y); ctx.stroke();
}
}
ctx.lineCap = 'butt';
}
// embossed die badge
ctx.strokeStyle = 'rgba(255,210,150,0.35)'; ctx.lineWidth = 2;
rr(ctx, P + cw / 2 - 20, (top + bot) / 2 - 20, 40, 40, 8); ctx.stroke();
ctx.fillStyle = 'rgba(255,210,150,0.35)';
for (const [a, b] of [[-1, -1], [1, 1], [0, 0], [1, -1], [-1, 1]]) {
ctx.beginPath(); ctx.arc(P + cw / 2 + a * 10, (top + bot) / 2 + b * 10, 3.5, 0, Math.PI * 2); ctx.fill();
}
ctx.restore();
// mouth
ctx.beginPath(); ctx.ellipse(P + cw / 2, top, (rt - lt) / 2, 16, 0, 0, Math.PI * 2);
ctx.fillStyle = '#6b3417'; ctx.fill();
ctx.beginPath(); ctx.ellipse(P + cw / 2, top + 2, (rt - lt) / 2 - 8, 11, 0, 0, Math.PI * 2);
const ig = ctx.createLinearGradient(0, top - 10, 0, top + 12);
ig.addColorStop(0, '#0d0503'); ig.addColorStop(1, '#2a140a');
ctx.fillStyle = ig; ctx.fill();
ctx.strokeStyle = 'rgba(255,220,170,0.35)'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.ellipse(P + cw / 2, top, (rt - lt) / 2, 16, 0, Math.PI * 1.05, Math.PI * 1.95); ctx.stroke();
addCanvas(scene, 'yatzi-cup', c);
}
// ── seat place-card ──────────────────────────────────────────────────────────
function bakeSeat(scene) {
const P = 16;
const c = canvas(SEAT.w + P * 2, SEAT.h + P * 2), ctx = c.getContext('2d');
dropShadow(ctx, () => { rr(ctx, P, P, SEAT.w, SEAT.h, 18); ctx.fillStyle = '#2b170b'; ctx.fill(); }, { blur: 18, dy: 8, alpha: 0.55 });
ctx.save(); rr(ctx, P, P, SEAT.w, SEAT.h, 18); ctx.clip();
const g = ctx.createLinearGradient(0, P, 0, P + SEAT.h);
g.addColorStop(0, 'rgba(58,32,15,0.92)'); g.addColorStop(1, 'rgba(36,19,8,0.92)');
ctx.fillStyle = g; ctx.fillRect(P, P, SEAT.w, SEAT.h);
grain(ctx, P, P, SEAT.w, SEAT.h, { lines: 12, tone: 'rgba(0,0,0,0.25)' });
ctx.restore();
ctx.strokeStyle = 'rgba(214,170,96,0.55)'; ctx.lineWidth = 2;
rr(ctx, P + 4, P + 4, SEAT.w - 8, SEAT.h - 8, 15); ctx.stroke();
addCanvas(scene, 'yatzi-seat', c);
}
// ── score pad ────────────────────────────────────────────────────────────────
export function padKey(n) { return `yatzi-pad-${n}`; }
function bakePad(scene, n) {
const key = padKey(n);
const P = PAD_PX;
const ox = BOARD.x - P, oy = Math.min(BOARD.y, CLIP.y) - P;
if (scene.textures.exists(key)) return { key, x: ox, y: oy };
const c = canvas(BOARD.w + P * 2, BOARD.h + (BOARD.y - CLIP.y) + P * 2), ctx = c.getContext('2d');
const X = (x) => x - ox, Y = (y) => y - oy;
// board
dropShadow(ctx, () => { rr(ctx, X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h, 22); ctx.fillStyle = '#7a5532'; ctx.fill(); }, { blur: 30, dy: 14, alpha: 0.6 });
ctx.save(); rr(ctx, X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h, 22); ctx.clip();
const bg = ctx.createLinearGradient(X(BOARD.x), 0, X(BOARD.x + BOARD.w), 0);
bg.addColorStop(0, '#8a6038'); bg.addColorStop(0.5, '#a0744a'); bg.addColorStop(1, '#80562f');
ctx.fillStyle = bg; ctx.fillRect(X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h);
ctx.fillStyle = noisePattern(ctx, 128, 40); ctx.fillRect(X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h);
ctx.restore();
// paper (a slightly lifted sheet with a second sheet peeking underneath)
dropShadow(ctx, () => { ctx.fillStyle = '#e9e1c8'; ctx.fillRect(X(PAPER.x) + 6, Y(PAPER.y) + 6, PAPER.w, PAPER.h); }, { blur: 6, dy: 2, alpha: 0.3 });
dropShadow(ctx, () => { ctx.fillStyle = '#f8f2df'; ctx.fillRect(X(PAPER.x), Y(PAPER.y), PAPER.w, PAPER.h); }, { blur: 10, dy: 3, alpha: 0.35 });
ctx.save(); ctx.beginPath(); ctx.rect(X(PAPER.x), Y(PAPER.y), PAPER.w, PAPER.h); ctx.clip();
ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(X(PAPER.x), Y(PAPER.y), PAPER.w, PAPER.h);
// title band
ctx.fillStyle = '#b3261e';
ctx.fillRect(X(PAPER.x), Y(PAPER.y) + 22, PAPER.w, 6);
ctx.fillRect(X(PAPER.x), Y(PAPER.y) + 98, PAPER.w, 3);
ctx.font = `46px ${DISPLAY_FONT}`;
ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
ctx.fillStyle = '#b3261e';
ctx.fillText('ZAHTZEE', X(PAD_TITLE.x), Y(PAD_TITLE.y));
ctx.font = `15px ${PRINT_FONT}`;
ctx.fillStyle = '#6f5d45';
ctx.fillText('OFFICIAL SCORE CARD', X(PAD_TITLE.x) + 228, Y(PAD_TITLE.y) + 4);
const gx0 = X(GRID.x), gx1 = X(GRID.x + GRID.w);
for (const row of PAD_ROWS) {
const ry = Y(row.y);
if (row.kind === 'gap') {
ctx.fillStyle = '#b3261e'; ctx.fillRect(gx0, ry + row.h / 2 - 1.5, GRID.w, 3);
continue;
}
if (row.kind === 'sum') { ctx.fillStyle = 'rgba(214,190,120,0.22)'; ctx.fillRect(gx0, ry, GRID.w, row.h); }
if (row.kind === 'grand') { ctx.fillStyle = 'rgba(179,38,30,0.1)'; ctx.fillRect(gx0, ry, GRID.w, row.h); }
if (row.kind === 'head') { ctx.fillStyle = 'rgba(34,48,79,0.06)'; ctx.fillRect(gx0, ry, GRID.w, row.h); }
// label
ctx.textAlign = 'left';
if (row.kind === 'cat') {
ctx.font = `19px ${PRINT_FONT}`; ctx.fillStyle = '#2b2418';
ctx.fillText(CATEGORY_LABELS[row.key], gx0 + 12, ry + row.h / 2 - 7);
ctx.font = `italic 12px ${SERIF}`; ctx.fillStyle = '#8a7a60';
ctx.fillText(CATEGORY_HINTS[row.key], gx0 + 12, ry + row.h / 2 + 12);
} else if (row.kind === 'grand') {
ctx.font = `24px ${DISPLAY_FONT}`; ctx.fillStyle = '#b3261e';
ctx.fillText(row.label, gx0 + 12, ry + row.h / 2 + 1);
} else if (row.kind === 'head') {
ctx.font = `14px ${PRINT_FONT}`; ctx.fillStyle = '#6f5d45';
ctx.fillText('PLAYER', gx0 + 12, ry + row.h / 2);
} else {
ctx.font = `italic 15px ${SERIF}`; ctx.fillStyle = '#5c4c34';
ctx.fillText(row.label, gx0 + 12, ry + row.h / 2 + 1);
}
// rule under the row
ctx.fillStyle = row.kind === 'head' ? '#22304f' : 'rgba(70,95,150,0.35)';
ctx.fillRect(gx0, ry + row.h - 1, GRID.w, row.kind === 'head' ? 2 : 1);
}
// column lines
const top = Y(PAD_ROWS[0].y), bottom = Y(PAD_ROWS[PAD_ROWS.length - 1].y + PAD_ROWS[PAD_ROWS.length - 1].h);
ctx.fillStyle = 'rgba(179,38,30,0.55)';
ctx.fillRect(gx0 + LABEL_W - 1, top, 2, bottom - top);
ctx.fillStyle = 'rgba(70,95,150,0.35)';
for (let p = 1; p < n; p++) ctx.fillRect(X(colX(p, n)), top, 1, bottom - top);
ctx.strokeStyle = 'rgba(34,48,79,0.6)'; ctx.lineWidth = 1.5;
ctx.strokeRect(gx0, top, gx1 - gx0, bottom - top);
ctx.restore();
// clip
const cx = X(CLIP.x), cy = Y(CLIP.y);
dropShadow(ctx, () => { rr(ctx, cx, cy, CLIP.w, CLIP.h, 16); ctx.fillStyle = '#9aa1a8'; ctx.fill(); }, { blur: 12, dy: 6, alpha: 0.5 });
const mg = ctx.createLinearGradient(0, cy, 0, cy + CLIP.h);
mg.addColorStop(0, '#eef1f3'); mg.addColorStop(0.45, '#a9b0b7'); mg.addColorStop(0.55, '#c9ced3'); mg.addColorStop(1, '#7c838a');
rr(ctx, cx, cy, CLIP.w, CLIP.h, 16); ctx.fillStyle = mg; ctx.fill();
ctx.strokeStyle = 'rgba(40,44,48,0.6)'; ctx.lineWidth = 1.5; ctx.stroke();
rr(ctx, cx + CLIP.w / 2 - 40, cy + 14, 80, 22, 11); ctx.fillStyle = 'rgba(60,64,70,0.55)'; ctx.fill();
for (const rx of [cx + 26, cx + CLIP.w - 26]) {
const rg = ctx.createRadialGradient(rx - 2, cy + CLIP.h - 24, 1, rx, cy + CLIP.h - 22, 8);
rg.addColorStop(0, '#ffffff'); rg.addColorStop(1, '#6a7178');
ctx.fillStyle = rg; ctx.beginPath(); ctx.arc(rx, cy + CLIP.h - 22, 7, 0, Math.PI * 2); ctx.fill();
}
addCanvas(scene, key, c);
return { key, x: ox, y: oy };
}
// ── small sprites ────────────────────────────────────────────────────────────
function bakeHand(scene) {
const c = canvas(72, 84), ctx = c.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 2;
// palm + fingers (a relaxed reaching hand, fingertips at the top)
ctx.beginPath();
rr(ctx, 14, 34, 44, 40, 16); ctx.fill(); ctx.stroke();
for (const [x, y, h] of [[14, 10, 34], [26, 4, 38], [38, 6, 36], [50, 14, 30]]) {
rr(ctx, x, y, 11, h, 5.5); ctx.fill(); ctx.stroke();
}
ctx.save(); ctx.translate(12, 56); ctx.rotate(-0.7);
rr(ctx, -6, -18, 12, 26, 6); ctx.fill(); ctx.stroke();
ctx.restore();
addCanvas(scene, 'yatzi-hand', c);
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.35, 'rgba(255,240,190,0.8)'); g.addColorStop(1, 'rgba(255,220,120,0)');
sx.fillStyle = g; sx.fillRect(0, 0, 32, 32);
addCanvas(scene, 'yatzi-spark', s);
}
// ── entry point ──────────────────────────────────────────────────────────────
let baked = false;
export async function prepareYatziArt(scene, nPlayers) {
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('yatzi-room')) {
bakeRoom(scene); bakeTray(scene); bakeLedge(scene); bakeCup(scene); bakeSeat(scene); bakeHand(scene);
baked = true;
}
return bakePad(scene, nPlayers);
}

View File

@ -0,0 +1,100 @@
// YatziDialogs.js — game-night pop-ups: a recipe-card on a walnut frame.
// Each opener returns { close() } and swallows clicks beneath it.
//
// openPauseMenu resume · opponent pace · hints · coach · undo · sort · skip · rules · new · leave
// confirmBox yes / no
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { DISPLAY_FONT, SERIF } from './YatziArt.js';
export function frame(scene, x, y, w, h, depth) {
const g = scene.add.graphics().setDepth(depth);
g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 4, y + 8, w, h, 14);
g.fillStyle(0x4a2b14, 1).fillRoundedRect(x, y, w, h, 14);
g.lineStyle(2, 0xd6aa60, 0.8).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 11);
g.fillStyle(0xf8f2df, 1).fillRoundedRect(x + 12, y + 12, w - 24, h - 24, 8);
g.fillStyle(0xb3261e, 1).fillRect(x + 12, y + 70, w - 24, 3);
return g;
}
export function blocker(scene, depth, alpha = 0) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, alpha)
.setDepth(depth).setInteractive();
}
export function title(scene, x, y, text, depth, size = 28) {
return scene.add.text(x, y, text, { fontFamily: DISPLAY_FONT, fontSize: `${size}px`, color: '#b3261e', 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' };
export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose }) {
const objs = [blocker(scene, depth - 1, 0.5)];
const w = 520, h = 760;
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 + 42, 'Game Night', depth + 1));
const cx = x + w / 2;
let hRef = null;
const rows = [
['Resume', () => hRef.close(), 0x22304f],
[() => `Opponent speed: ${PACE_LABEL[settings.pace]}`, () => {
const order = ['relaxed', 'normal', 'fast'];
onChange('pace', order[(order.indexOf(settings.pace) + 1) % order.length]);
}],
[() => `Score previews: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)],
[() => `Coach (odds + best keep): ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)],
[() => `Undo last score: ${onOff(settings.undo)}`, () => onChange('undo', !settings.undo)],
[() => `Sort dice after a roll: ${onOff(settings.sort)}`, () => onChange('sort', !settings.sort)],
[() => `Confirm scratches: ${onOff(settings.confirmScratch)}`, () => onChange('confirmScratch', !settings.confirmScratch)],
[() => `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 * 54, text, () => {
fn();
if (typeof label === 'function') btn.setLabel(label());
}, { width: 420, height: 46, fontSize: 17, bg: bg ?? 0x5a3820 }).setDepth(depth + 2);
objs.push(btn);
});
objs.push(scene.add.text(cx, y + h - 36, 'Keys: Space shake & roll · 1–5 keep a die · Enter score the glowing box · Z undo · Esc menu', {
fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#5a4428', 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 = 520, h = 260;
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 + 42, heading, depth + 1, 24));
objs.push(scene.add.text(x + w / 2, y + 128, text, {
fontFamily: SERIF, fontSize: '17px', color: '#2b2418', align: 'center', wordWrap: { width: w - 70 },
}).setOrigin(0.5).setDepth(depth + 1));
let hRef = null;
objs.push(new Button(scene, x + w / 2 - 116, y + h - 50, yes, () => { hRef.close(); onYes?.(); }, { width: 204, height: 46, fontSize: 18, bg: 0x7a2a1a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 116, y + h - 50, no, () => { hRef.close(); onNo?.(); }, { width: 204, height: 46, fontSize: 18, bg: 0x22304f }).setDepth(depth + 2));
hRef = handle(objs);
return hRef;
}

View File

@ -0,0 +1,93 @@
// YatziEndScreen.js — the after-game card over the dice tray: final standings,
// a few stats per player, and the human's personal best (localStorage).
import { Button } from '../../ui/Button.js';
import { CATEGORY_LABELS, computeTotals } from './YatziLogic.js';
import { TRAY } from './YatziLayout.js';
import { INK, DISPLAY_FONT, PRINT_FONT, SERIF, HAND_FONT } from './YatziArt.js';
import { frame } from './YatziDialogs.js';
const BEST_KEY = 'yatzi-best';
export function recordPersonalBest(score) {
let prev = null;
try { prev = JSON.parse(localStorage.getItem(BEST_KEY) || 'null'); } catch (_) { prev = null; }
const isNew = !prev || score > prev.score;
if (isNew) {
try { localStorage.setItem(BEST_KEY, JSON.stringify({ score, date: new Date().toISOString().slice(0, 10) })); } catch (_) { /* private mode */ }
}
return { prev, isNew };
}
export function openEndScreen(scene, { gs, ranks, depth, best, onPlayAgain, onMenu }) {
const objs = [];
const n = gs.players.length;
const w = 980, h = 190 + n * 74 + 70;
const x = TRAY.x + (TRAY.w - w) / 2, y = Math.max(20, TRAY.y + (TRAY.h - h) / 2 + 40);
const shade = scene.add.rectangle(590, 540, 1180, 1080, 0x000000, 0.45).setDepth(depth - 1).setInteractive();
objs.push(shade, frame(scene, x, y, w, h, depth));
const order = gs.players.map((_, i) => i).sort((a, b) => ranks[a] - ranks[b]);
const winner = order[0];
const human = ranks[0] === 1;
const tie = ranks.filter((r) => r === 1).length > 1;
const head = tie ? (human ? 'A tie at the top!' : 'A shared win') : human ? 'You win!' : `${gs.players[winner].name} wins`;
objs.push(scene.add.text(x + w / 2, y + 42, head, { fontFamily: DISPLAY_FONT, fontSize: '34px', color: '#b3261e' }).setOrigin(0.5).setDepth(depth + 1));
const cols = [
{ k: 'rank', x: x + 46, label: '' },
{ k: 'name', x: x + 96, label: 'PLAYER' },
{ k: 'total', x: x + 380, label: 'TOTAL' },
{ k: 'bonus', x: x + 490, label: 'UPPER BONUS' },
{ k: 'z', x: x + 630, label: 'ZAHTZEES' },
{ k: 'best', x: x + 740, label: 'BEST TURN' },
{ k: 'scr', x: x + w - 50, label: 'SCRATCHES' },
];
const hy = y + 100;
cols.forEach((c) => {
if (!c.label) return;
const o = c.k === 'name' ? 0 : c.k === 'scr' ? 1 : 0;
objs.push(scene.add.text(c.x, hy, c.label, { fontFamily: PRINT_FONT, fontSize: '13px', color: '#6f5d45' }).setOrigin(o, 0.5).setDepth(depth + 1));
});
order.forEach((p, row) => {
const pl = gs.players[p];
const t = computeTotals(pl);
const ry = hy + 44 + row * 74;
const ink = INK[p];
const txt = (cx, s, opts = {}, ox = 0) => {
const o = scene.add.text(cx, ry, s, { fontFamily: HAND_FONT, fontSize: '28px', color: ink, ...opts }).setOrigin(ox, 0.5).setDepth(depth + 1);
objs.push(o);
return o;
};
if (row > 0) {
const g = scene.add.graphics().setDepth(depth + 1);
g.fillStyle(0x465f96, 0.25).fillRect(x + 30, ry - 37, w - 60, 1);
objs.push(g);
}
txt(cols[0].x, ['1st', '2nd', '3rd', '4th'][ranks[p] - 1], { color: ranks[p] === 1 ? '#b3261e' : '#6f5d45', fontSize: '24px' }, 0.5);
txt(cols[1].x, pl.name.length > 14 ? pl.name.slice(0, 13) + '…' : pl.name);
txt(cols[2].x, String(t.grand), { fontSize: '36px' }, 0.5);
txt(cols[3].x, t.upperBonus ? '✓ +35' : '—', {}, 0);
txt(cols[4].x, String(pl.stats.yahtzees), {}, 0.5);
const b = pl.stats.bestTurn;
txt(cols[5].x, b ? `${b.value} · ${CATEGORY_LABELS[b.category]}` : '—', { fontSize: '22px' }, 0);
txt(cols[6].x, String(pl.stats.scratches), {}, 1);
});
const fy = y + h - 104;
const human0 = computeTotals(gs.players[0]).grand;
const bestLine = best.isNew
? (best.prev ? `New personal best! ${human0} beats your old ${best.prev.score}.` : `Personal best set: ${human0}.`)
: `Your personal best: ${best.prev.score} (${best.prev.date}).`;
objs.push(scene.add.text(x + w / 2, fy, bestLine, {
fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: best.isNew ? '#b3261e' : '#5a4428',
}).setOrigin(0.5).setDepth(depth + 1));
objs.push(new Button(scene, x + w / 2 - 140, y + h - 52, 'Play Again', onPlayAgain, { width: 240, height: 50, fontSize: 20, bg: 0x22304f }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 140, y + h - 52, 'Back to Menu', onMenu, { width: 240, height: 50, fontSize: 20, bg: 0x5a3820 }).setDepth(depth + 2));
// drop in
objs.forEach((o) => { if (o !== shade && o.y !== undefined) o.y -= 30; if (o.setAlpha) o.setAlpha(0); });
scene.tweens.add({ targets: objs.filter((o) => o !== shade), y: '+=30', alpha: 1, duration: 380, ease: 'Back.Out' });
shade.setAlpha(0);
scene.tweens.add({ targets: shade, alpha: 1, duration: 300 });
return { close: () => objs.forEach((o) => o.destroy()) };
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,146 @@
// YatziLayout.js — every screen rect for the Zahtzee game-night table, plus the
// dice-tray projection. Phaser-free (tools/verifyYatzi.js checks overlaps).
//
// ┌ opponent seats (top rail) ───────────────┐ ┌ clipboard score pad ┐
// │ felt dice tray │ │ │
// │ keeper ledge (one slot per die column) │ │ │
// └ you · dice cup · rolls · status · menu ──┘ └─────────────────────┘
import { UPPER, LOWER } from './YatziLogic.js';
export const W = 1920;
export const H = 1080;
// ── Seats ────────────────────────────────────────────────────────────────────
export const SEAT = { w: 360, h: 172, y: 14, gap: 15, left: 40, span: 1120 };
export function seatRect(k, nOpp) {
const total = nOpp * SEAT.w + (nOpp - 1) * SEAT.gap;
const x0 = SEAT.left + (SEAT.span - total) / 2;
return { x: x0 + k * (SEAT.w + SEAT.gap), y: SEAT.y, w: SEAT.w, h: SEAT.h };
}
export function seatParts(k, nOpp) {
const r = seatRect(k, nOpp);
return {
rect: r,
portrait: { x: r.x + 76, y: r.y + 86, r: 58 },
name: { x: r.x + 152, y: r.y + 40 },
score: { x: r.x + 152, y: r.y + 76 },
bubble: { x: r.x + 146, y: r.y + 100, w: 204, h: 62 },
};
}
// ── Dice tray ────────────────────────────────────────────────────────────────
export const TRAY = { x: 60, y: 202, w: 1100, h: 516 };
export const TRAY_WALL = 28;
export const TRAY_FELT = { x: TRAY.x + TRAY_WALL, y: TRAY.y + TRAY_WALL, w: TRAY.w - TRAY_WALL * 2, h: TRAY.h - TRAY_WALL * 2 };
export const TRAY_CAM = { sin: 0.62, cos: 0.785 };
export const TRAY_WORLD = { w: TRAY_FELT.w, h: TRAY_FELT.h / TRAY_CAM.sin };
export const DIE_SIZE = 70;
// One shared ground plane for the tray, the ledge and everything between.
export function ground(u, v) {
return { x: TRAY_FELT.x + u, y: TRAY_FELT.y + v * TRAY_CAM.sin, s: 1 };
}
export function toWorld(x, y) {
return { u: x - TRAY_FELT.x, v: (y - TRAY_FELT.y) / TRAY_CAM.sin };
}
// The five die columns (key 1–5): same x in the tray and on the ledge.
export const COLUMN_U = [0, 1, 2, 3, 4].map((i) => TRAY_FELT.w * (0.18 + i * 0.16));
export const COLUMN_X = COLUMN_U.map((u) => TRAY_FELT.x + u);
export const REST_V = TRAY_WORLD.h * 0.56;
// ── Keeper ledge ─────────────────────────────────────────────────────────────
export const LEDGE = { x: 150, y: 728, w: 920, h: 124 };
export const LEDGE_GROUND_Y = 770; // where a kept die sits (the felt slots)
export const LEDGE_V = toWorld(0, LEDGE_GROUND_Y).v;
// ── Bottom rail ──────────────────────────────────────────────────────────────
export const HUMAN_PORTRAIT = { x: 92, y: 956, r: 58 };
export const HUMAN_NAME = { x: 92, y: 1044 };
export const CUP = { x: 300, y: 962, w: 150, h: 176 }; // centre
export const CUP_MOUTH = { x: CUP.x, y: CUP.y - CUP.h / 2 + 18 };
export const PIPS = { x: 424, y: 930, gap: 36, r: 13 };
export const PIPS_LABEL = { x: 460, y: 966 };
export const STATUS = { x: 780, w: 440, y: 896 };
export const SUBLINE = { x: 780, y: 936 };
export const TICKER = { x: 780, y: 976 };
export const METER = { x: 780, y: 1018 };
export const BTN = { w: 134, h: 46 };
export const UNDO_BTN = { x: 1088, y: 920 };
export const MENU_BTN = { x: 1088, y: 986 };
export const BANNER = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + TRAY.h * 0.42 };
// Throw origins in tray-world coordinates.
export function humanOrigin() {
const w = toWorld(CUP_MOUTH.x, CUP_MOUTH.y + 40); // straight out of the cup's mouth
return { u: w.u, v: w.v, h: 70 };
}
export function seatOrigin(portraitX) {
return { u: portraitX - TRAY_FELT.x, v: -90, h: 110 };
}
// ── Score pad (clipboard) ────────────────────────────────────────────────────
export const BOARD = { x: 1186, y: 14, w: 716, h: 1054 };
export const CLIP = { x: BOARD.x + BOARD.w / 2 - 120, y: 2, w: 240, h: 84 };
export const PAPER = { x: BOARD.x + 24, y: 70, w: BOARD.w - 48, h: 980 };
export const PAD_TITLE = { x: PAPER.x + 36, y: PAPER.y + 66 };
export const PAD_ROUND = { x: PAPER.x + PAPER.w - 30, y: PAPER.y + 70 };
export const GRID = { x: PAPER.x + 16, y: PAPER.y + 112, w: PAPER.w - 32 };
export const LABEL_W = 236;
const ROW_H = 44, SUM_H = 40, HEAD_H = 56, GRAND_H = 54, GAP_H = 14;
// Rows top → bottom. kind: head | cat | sum | gap | grand
export const PAD_ROWS = (() => {
const rows = [];
let y = GRID.y;
const push = (key, kind, h, label) => { rows.push({ key, kind, y, h, label }); y += h; };
push('head', 'head', HEAD_H, 'Player');
for (const c of UPPER) push(c, 'cat', ROW_H);
push('upperTotal', 'sum', SUM_H, 'Upper Total');
push('upperBonus', 'sum', SUM_H, 'Bonus · 63+ = 35');
push('gap', 'gap', GAP_H);
for (const c of LOWER) push(c, 'cat', ROW_H);
push('yahtzeeBonus', 'sum', SUM_H, 'Zahtzee Bonus · 100 each');
push('grand', 'grand', GRAND_H, 'GRAND TOTAL');
return rows;
})();
export const PAD_BOTTOM = PAD_ROWS[PAD_ROWS.length - 1].y + GRAND_H;
export const rowOf = (key) => PAD_ROWS.find((r) => r.key === key);
export function colW(n) { return (GRID.w - LABEL_W) / n; }
export function colX(p, n) { return GRID.x + LABEL_W + p * colW(n); }
export function cellRect(p, key, n) {
const r = rowOf(key);
return { x: colX(p, n), y: r.y, w: colW(n), h: r.h };
}
export function cellCenter(p, key, n) {
const c = cellRect(p, key, n);
return { x: c.x + c.w / 2, y: c.y + c.h / 2 };
}
// The clickable strip for the human's box: label + their cell.
export function rowHit(key, n) {
const r = rowOf(key);
return { x: GRID.x, y: r.y, w: LABEL_W + colW(n), h: r.h };
}
// ── Checks ───────────────────────────────────────────────────────────────────
export function hudFurniture(nOpp) {
const f = [];
for (let k = 0; k < nOpp; k++) f.push({ name: `seat${k}`, ...seatRect(k, nOpp) });
f.push({ name: 'tray', ...TRAY });
f.push({ name: 'ledge', ...LEDGE });
const c = (name, o, w, h) => ({ name, x: o.x - w / 2, y: o.y - h / 2, w, h });
f.push(c('portrait', HUMAN_PORTRAIT, HUMAN_PORTRAIT.r * 2, HUMAN_PORTRAIT.r * 2));
f.push(c('cup', CUP, CUP.w, CUP.h));
f.push({ name: 'pips', x: PIPS.x - PIPS.r, y: PIPS.y - PIPS.r, w: PIPS.gap * 2 + PIPS.r * 2, h: 50 });
f.push({ name: 'status', x: STATUS.x - STATUS.w / 2, y: STATUS.y - 20, w: STATUS.w, h: METER.y + 14 - (STATUS.y - 20) });
f.push(c('undo', UNDO_BTN, BTN.w, BTN.h));
f.push(c('menu', MENU_BTN, BTN.w, BTN.h));
f.push({ name: 'board', ...BOARD });
return f;
}
export const rectsOverlap = (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;
export const onScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H;
export const inside = (a, b) => a.x >= b.x && a.y >= b.y && a.x + a.w <= b.x + b.w && a.y + a.h <= b.y + b.h;

View File

@ -1,42 +1,53 @@
// Pure Yahtzee rules. No Phaser dependency. // Pure Zahtzee (Yahtzee) rules. No Phaser dependency — verified under Node by
// tools/verifyYatzi.js.
// //
// Categories (13): // Categories (13):
// Upper: ones, twos, threes, fours, fives, sixes (sum of those faces) // Upper: ones … sixes (sum of those faces)
// Lower: threeOfKind, fourOfKind, fullHouse(25), smallStraight(30), // Lower: threeOfKind, fourOfKind (sum of all dice), fullHouse (25),
// largeStraight(40), yahtzee(50), chance(sum) // smallStraight (30), largeStraight (40), yahtzee (50), chance (sum)
// //
// Scoring extras: // Scoring extras:
// - Upper bonus: +35 if upper subtotal ≥ 63 // - Upper bonus: +35 if the upper subtotal reaches 63 (three of each face).
// - Yahtzee bonus: +100 per subsequent Yahtzee after the first scored 50, // - Zahtzee bonus: +100 for every further Zahtzee once the box holds 50.
// with Joker placement rules: // - Joker rules (official, "forced"), whenever a Zahtzee is rolled and the
// 1. If matching upper section is empty, must use it (scores face×5). // Zahtzee box is already filled (with 50 or a scratched 0):
// 2. Else any lower section: fullHouse=25, smallStraight=30, // 1. the matching upper box must be used if it is open;
// largeStraight=40 even when pattern doesn't strictly match; // 2. otherwise any open LOWER box, where Full House / Small Straight /
// threeOfKind / fourOfKind / chance score sum of dice. // Large Straight score their full value and 3K / 4K / Chance the sum;
// 3. Else any upper section may be zeroed. // 3. only if the lower section is full may an upper box be scratched.
// If yahtzee slot was already zeroed (player scored 0 there earlier), // The +100 bonus is earned only if the Zahtzee box holds 50.
// Joker placement still applies but no +100 bonus accrues. //
// Every roll takes an injectable rng (default Math.random), so whole games can
// be replayed from a seed.
export const UPPER = ['ones', 'twos', 'threes', 'fours', 'fives', 'sixes']; export const UPPER = ['ones', 'twos', 'threes', 'fours', 'fives', 'sixes'];
export const LOWER = ['threeOfKind', 'fourOfKind', 'fullHouse', 'smallStraight', 'largeStraight', 'yahtzee', 'chance']; export const LOWER = ['threeOfKind', 'fourOfKind', 'fullHouse', 'smallStraight', 'largeStraight', 'yahtzee', 'chance'];
export const CATEGORIES = [...UPPER, ...LOWER]; export const CATEGORIES = [...UPPER, ...LOWER];
export const TURNS = CATEGORIES.length; // 13 rounds
export const UPPER_BONUS_AT = 63;
export const UPPER_BONUS = 35;
export const YAHTZEE_BONUS = 100;
export const CATEGORY_LABELS = { export const CATEGORY_LABELS = {
ones: 'Aces', ones: 'Aces', twos: 'Twos', threes: 'Threes', fours: 'Fours', fives: 'Fives', sixes: 'Sixes',
twos: 'Twos', threeOfKind: '3 of a Kind', fourOfKind: '4 of a Kind', fullHouse: 'Full House',
threes: 'Threes', smallStraight: 'Sm. Straight', largeStraight: 'Lg. Straight', yahtzee: 'Zahtzee', chance: 'Chance',
fours: 'Fours',
fives: 'Fives',
sixes: 'Sixes',
threeOfKind: '3 of a Kind',
fourOfKind: '4 of a Kind',
fullHouse: 'Full House',
smallStraight: 'Sm. Straight',
largeStraight: 'Lg. Straight',
yahtzee: 'Zahtzee',
chance: 'Chance',
}; };
// The "how to score" column printed on the pad.
export const CATEGORY_HINTS = {
ones: 'count aces', twos: 'count twos', threes: 'count threes',
fours: 'count fours', fives: 'count fives', sixes: 'count sixes',
threeOfKind: 'sum of all dice', fourOfKind: 'sum of all dice', fullHouse: 'score 25',
smallStraight: 'run of 4 · 30', largeStraight: 'run of 5 · 40', yahtzee: '5 alike · 50', chance: 'sum of all dice',
};
export const FACE_WORDS = { 1: 'Aces', 2: 'Twos', 3: 'Threes', 4: 'Fours', 5: 'Fives', 6: 'Sixes' };
export function emptyStats() {
return { yahtzees: 0, scratches: 0, bestTurn: null, rolls: 0, jokers: 0 };
}
export function createInitialState({ playerNames }) { export function createInitialState({ playerNames }) {
const players = playerNames.map((p) => ({ const players = playerNames.map((p) => ({
name: p.name, name: p.name,
@ -44,15 +55,18 @@ export function createInitialState({ playerNames }) {
avatar: p.avatar ?? null, avatar: p.avatar ?? null,
scorecard: Object.fromEntries(CATEGORIES.map((c) => [c, null])), scorecard: Object.fromEntries(CATEGORIES.map((c) => [c, null])),
yahtzeeBonusCount: 0, yahtzeeBonusCount: 0,
stats: emptyStats(),
})); }));
return { return {
players, players,
current: 0, current: 0,
dice: [1, 1, 1, 1, 1], dice: [1, 2, 3, 4, 5],
held: [false, false, false, false, false], held: [false, false, false, false, false],
rollsRemaining: 3, rollsRemaining: 3,
phase: 'preroll', // preroll → rolling → scoring → gameover phase: 'preroll', // preroll → rolling → scoring → gameover
lastBonusGained: false, // transient flag set when last commitScore awarded a Yahtzee bonus lastBonusGained: false, // set when the last commitScore awarded a Zahtzee bonus
lastCommit: null, // { player, category, value, bonus, upperBonusEarned }
log: [],
}; };
} }
@ -62,15 +76,16 @@ export function cloneState(state) {
// ─── Dice ────────────────────────────────────────────────────────────────── // ─── Dice ──────────────────────────────────────────────────────────────────
export function rollDice(state) { export function rollDice(state, rng = Math.random) {
if (state.rollsRemaining <= 0) return state; if (state.rollsRemaining <= 0 || state.phase === 'gameover') return state;
const s = cloneState(state); const s = cloneState(state);
for (let i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
if (!s.held[i]) s.dice[i] = Math.ceil(Math.random() * 6); if (!s.held[i]) s.dice[i] = 1 + Math.floor(rng() * 6);
} }
s.rollsRemaining -= 1; s.rollsRemaining -= 1;
s.phase = s.rollsRemaining > 0 ? 'rolling' : 'scoring'; s.phase = s.rollsRemaining > 0 ? 'rolling' : 'scoring';
s.lastBonusGained = false; s.lastBonusGained = false;
s.players[s.current].stats.rolls += 1;
return s; return s;
} }
@ -80,45 +95,66 @@ export function setDice(state, dice) {
return s; return s;
} }
// Re-order the dice that were just rolled (the unheld positions) into
// ascending order. Held dice keep their positions. Purely cosmetic — it never
// changes a score — but it makes straights and sets easy to read.
export function sortUnheld(state) {
const idx = [0, 1, 2, 3, 4].filter((i) => !state.held[i]);
const vals = idx.map((i) => state.dice[i]).sort((a, b) => a - b);
const s = cloneState(state);
idx.forEach((i, k) => { s.dice[i] = vals[k]; });
return s;
}
export function canHold(state) {
return state.phase === 'rolling';
}
export function toggleHold(state, idx) { export function toggleHold(state, idx) {
if (state.phase === 'preroll' || state.phase === 'gameover') return state; if (!canHold(state)) return state;
if (state.rollsRemaining <= 0) return state; // no point holding once all rolls used
const s = cloneState(state); const s = cloneState(state);
s.held[idx] = !s.held[idx]; s.held[idx] = !s.held[idx];
return s; return s;
} }
export function setHeld(state, mask) {
if (!canHold(state)) return state;
const s = cloneState(state);
s.held = mask.map(Boolean);
return s;
}
// ─── Scoring primitives ──────────────────────────────────────────────────── // ─── Scoring primitives ────────────────────────────────────────────────────
const sumDice = (dice) => dice.reduce((a, b) => a + b, 0); export const sumDice = (dice) => dice.reduce((a, b) => a + b, 0);
function diceCounts(dice) { export function diceCounts(dice) {
const c = {}; const c = [0, 0, 0, 0, 0, 0, 0];
for (const d of dice) c[d] = (c[d] || 0) + 1; for (const d of dice) c[d]++;
return c; return c;
} }
function nOfAKind(dice, n) { function nOfAKind(dice, n) {
return Object.values(diceCounts(dice)).some((v) => v >= n); return diceCounts(dice).some((v) => v >= n);
} }
function isFullHouse(dice) { export function isFullHouse(dice) {
const c = Object.values(diceCounts(dice)).sort((a, b) => a - b); const c = diceCounts(dice).filter((v) => v > 0).sort((a, b) => a - b);
return c.length === 2 && c[0] === 2 && c[1] === 3; return c.length === 2 && c[0] === 2 && c[1] === 3;
} }
function isSmallStraight(dice) { export function isSmallStraight(dice) {
const s = new Set(dice); const s = new Set(dice);
return [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]].some((seq) => seq.every((n) => s.has(n))); return [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]].some((seq) => seq.every((n) => s.has(n)));
} }
function isLargeStraight(dice) { export function isLargeStraight(dice) {
const s = new Set(dice); const s = new Set(dice);
return [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]].some((seq) => seq.every((n) => s.has(n))); return [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]].some((seq) => seq.every((n) => s.has(n)));
} }
export function isYahtzee(dice) { export function isYahtzee(dice) {
return new Set(dice).size === 1; return dice.length === 5 && new Set(dice).size === 1;
} }
// Base (non-Joker) score for a category given dice. // Base (non-Joker) score for a category given dice.
@ -141,43 +177,45 @@ export function baseScore(dice, category) {
} }
} }
// Whether Joker rules apply to this roll. // Whether Joker rules apply to this roll, and whether it earns the +100.
function jokerStatus(dice, scorecard) { export function jokerStatus(dice, scorecard) {
if (!isYahtzee(dice)) return { applies: false, bonus: false }; if (!isYahtzee(dice)) return { applies: false, bonus: false };
if (scorecard.yahtzee === 50) return { applies: true, bonus: true }; if (scorecard.yahtzee === 50) return { applies: true, bonus: true };
if (scorecard.yahtzee === 0) return { applies: true, bonus: false }; if (scorecard.yahtzee === 0) return { applies: true, bonus: false };
return { applies: false, bonus: false }; return { applies: false, bonus: false };
} }
// What the Joker forces this turn: 'upper' (the matching upper box),
// 'lower' (any open lower box), 'scratch' (lower full — zero an upper box),
// or null when no Joker applies.
export function jokerMode(dice, scorecard) {
if (!jokerStatus(dice, scorecard).applies) return null;
if (scorecard[UPPER[dice[0] - 1]] === null) return 'upper';
if (LOWER.some((c) => scorecard[c] === null)) return 'lower';
return 'scratch';
}
// Categories that are legal placements for these dice + scorecard. // Categories that are legal placements for these dice + scorecard.
export function legalCategories(dice, scorecard) { export function legalCategories(dice, scorecard) {
const open = CATEGORIES.filter((c) => scorecard[c] === null); const open = CATEGORIES.filter((c) => scorecard[c] === null);
if (open.length === 0) return []; if (open.length === 0) return [];
const j = jokerStatus(dice, scorecard); const mode = jokerMode(dice, scorecard);
if (!j.applies) return open; if (mode === null) return open;
if (mode === 'upper') return [UPPER[dice[0] - 1]];
const face = dice[0]; if (mode === 'lower') return LOWER.filter((c) => scorecard[c] === null);
const matchingUpper = UPPER[face - 1]; return UPPER.filter((c) => scorecard[c] === null);
// Rule 1: matching upper must be used first if still empty.
if (scorecard[matchingUpper] === null) {
return [matchingUpper];
}
// Rule 2: any open category may be used (lower-section Jokers + upper zeroes).
return open;
} }
// Compute committed value for a category, honoring Joker substitutions. // Committed value for a category, honouring Joker substitutions.
// Returns null if placement is illegal. // Returns null if the placement is illegal.
export function scoreForCommit(dice, category, scorecard) { export function scoreForCommit(dice, category, scorecard) {
if (scorecard[category] !== null) return null; if (scorecard[category] !== null && scorecard[category] !== undefined) return null;
const legal = legalCategories(dice, scorecard); const legal = legalCategories(dice, scorecard);
if (!legal.includes(category)) return null; if (!legal.includes(category)) return null;
const j = jokerStatus(dice, scorecard); const j = jokerStatus(dice, scorecard);
if (!j.applies) return baseScore(dice, category); if (!j.applies) return baseScore(dice, category);
// Joker substitution: lower-section specials score their face values
// even if dice don't strictly match the pattern.
switch (category) { switch (category) {
case 'fullHouse': return 25; case 'fullHouse': return 25;
case 'smallStraight': return 30; case 'smallStraight': return 30;
@ -185,12 +223,11 @@ export function scoreForCommit(dice, category, scorecard) {
case 'threeOfKind': case 'threeOfKind':
case 'fourOfKind': case 'fourOfKind':
case 'chance': return sumDice(dice); case 'chance': return sumDice(dice);
case 'yahtzee': return 50; // unreachable: already filled when Joker applies default: return baseScore(dice, category); // upper: face × count (0 when scratching)
default: return baseScore(dice, category); // upper: face * count (zero unless matching upper used)
} }
} }
// Commit current dice to a category; advances turn. Pure — returns new state. // Commit the current dice to a category and advance the turn. Pure.
export function commitScore(state, category) { export function commitScore(state, category) {
if (state.phase !== 'rolling' && state.phase !== 'scoring') return state; if (state.phase !== 'rolling' && state.phase !== 'scoring') return state;
const player = state.players[state.current]; const player = state.players[state.current];
@ -200,6 +237,7 @@ export function commitScore(state, category) {
const s = cloneState(state); const s = cloneState(state);
const cur = s.players[s.current]; const cur = s.players[s.current];
const j = jokerStatus(s.dice, cur.scorecard); const j = jokerStatus(s.dice, cur.scorecard);
const upperBefore = computeTotals(cur).upperBonus;
cur.scorecard[category] = value; cur.scorecard[category] = value;
s.lastBonusGained = false; s.lastBonusGained = false;
@ -207,16 +245,23 @@ export function commitScore(state, category) {
cur.yahtzeeBonusCount += 1; cur.yahtzeeBonusCount += 1;
s.lastBonusGained = true; s.lastBonusGained = true;
} }
if (j.applies) cur.stats.jokers += 1;
if (isYahtzee(s.dice)) cur.stats.yahtzees += 1;
if (value === 0) cur.stats.scratches += 1;
const turnValue = value + (j.bonus ? YAHTZEE_BONUS : 0);
if (!cur.stats.bestTurn || turnValue > cur.stats.bestTurn.value) {
cur.stats.bestTurn = { value: turnValue, category };
}
const upperBonusEarned = !upperBefore && computeTotals(cur).upperBonus > 0;
s.lastCommit = { player: s.current, category, value, bonus: j.bonus, joker: j.applies, upperBonusEarned, dice: [...s.dice] };
s.log.push(`${cur.name}: ${value === 0 ? 'scratched' : value + ' in'} ${CATEGORY_LABELS[category]}${j.bonus ? ' (+100 bonus)' : ''}`);
s.held = [false, false, false, false, false];
if (isGameOver(s)) { if (isGameOver(s)) {
s.phase = 'gameover'; s.phase = 'gameover';
return s; return s;
} }
// Advance turn
s.current = (s.current + 1) % s.players.length; s.current = (s.current + 1) % s.players.length;
s.dice = [1, 1, 1, 1, 1];
s.held = [false, false, false, false, false];
s.rollsRemaining = 3; s.rollsRemaining = 3;
s.phase = 'preroll'; s.phase = 'preroll';
return s; return s;
@ -226,18 +271,48 @@ export function isGameOver(state) {
return state.players.every((p) => CATEGORIES.every((c) => p.scorecard[c] !== null)); return state.players.every((p) => CATEGORIES.every((c) => p.scorecard[c] !== null));
} }
export function filledCount(player) {
return CATEGORIES.filter((c) => player.scorecard[c] !== null).length;
}
// 1-based round number (13 rounds). After the last commit it reads 13.
export function roundOf(state) {
return Math.min(TURNS, Math.min(...state.players.map(filledCount)) + 1);
}
export function computeTotals(player) { export function computeTotals(player) {
const upperSubtotal = UPPER.reduce((a, c) => a + (player.scorecard[c] ?? 0), 0); const upperSubtotal = UPPER.reduce((a, c) => a + (player.scorecard[c] ?? 0), 0);
const upperBonus = upperSubtotal >= 63 ? 35 : 0; const upperBonus = upperSubtotal >= UPPER_BONUS_AT ? UPPER_BONUS : 0;
const lowerSubtotal = LOWER.reduce((a, c) => a + (player.scorecard[c] ?? 0), 0); const lowerSubtotal = LOWER.reduce((a, c) => a + (player.scorecard[c] ?? 0), 0);
const yahtzeeBonus = player.yahtzeeBonusCount * 100; const yahtzeeBonus = player.yahtzeeBonusCount * YAHTZEE_BONUS;
const grand = upperSubtotal + upperBonus + lowerSubtotal + yahtzeeBonus; const grand = upperSubtotal + upperBonus + lowerSubtotal + yahtzeeBonus;
return { upperSubtotal, upperBonus, lowerSubtotal, yahtzeeBonus, grand }; return { upperSubtotal, upperBonus, lowerSubtotal, yahtzeeBonus, grand };
} }
// Returns array of player indices with max grand total (ties supported). // Upper-bonus progress against par (three of each face = exactly 63).
// par how far ahead (+) or behind (−) of three-of-each on the filled boxes
// need points still needed for the bonus (0 once earned)
// alive whether the bonus is still reachable with five of each open face
export function upperPar(player) {
let par = 0, sub = 0, maxLeft = 0;
UPPER.forEach((c, i) => {
const v = player.scorecard[c];
if (v === null) maxLeft += 5 * (i + 1);
else { par += v - 3 * (i + 1); sub += v; }
});
const need = Math.max(0, UPPER_BONUS_AT - sub);
return { par, sub, need, earned: sub >= UPPER_BONUS_AT, alive: need <= maxLeft, done: UPPER.every((c) => player.scorecard[c] !== null) };
}
// Array of player indices with the highest grand total (ties supported).
export function getWinners(state) { export function getWinners(state) {
const totals = state.players.map((p, i) => ({ idx: i, total: computeTotals(p).grand })); const totals = state.players.map((p, i) => ({ idx: i, total: computeTotals(p).grand }));
const max = Math.max(...totals.map((t) => t.total)); const max = Math.max(...totals.map((t) => t.total));
return totals.filter((t) => t.total === max).map((t) => t.idx); return totals.filter((t) => t.total === max).map((t) => t.idx);
} }
// Standard competition ranking (1, 2, 2, 4) by grand total.
export function rankings(state) {
const totals = state.players.map((p) => computeTotals(p).grand);
return totals.map((t) => 1 + totals.filter((o) => o > t).length);
}

305
src/games/yatzi/YatziPad.js Normal file
View File

@ -0,0 +1,305 @@
// YatziPad.js — the clipboard score pad. Each player writes in their own ink.
//
// write(p, cat, value) pencils a score in (a scratch gets a struck line)
// showPreviews(map, best) ghost values in the human's open boxes
// refreshTotals(p, …) running totals, par note, bonus stamps
// tally(…) the end-of-game add-up ceremony
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
import { CATEGORIES, UPPER, computeTotals, upperPar } from './YatziLogic.js';
import {
PAD_ROWS, PAD_ROUND, cellRect, cellCenter, rowHit, colX, colW, rowOf,
} from './YatziLayout.js';
import { INK, INK_HEX, HAND_FONT, PRINT_FONT, SERIF, padKey } from './YatziArt.js';
const SUM_KEYS = ['upperTotal', 'upperBonus', 'yahtzeeBonus', 'grand'];
export class YatziPad {
constructor(scene, { players, depth, origin, onCell, onHover }) {
this.scene = scene;
this.players = players; // [{ name }]
this.n = players.length;
this.depth = depth;
this.origin = origin; // baked texture position
this.onCell = onCell;
this.onHover = onHover;
this.cells = {}; // `${p}-${key}` → Text
this.scratches = {}; // `${p}-${key}` → Graphics
this.previews = {}; // cat → Text (human column)
this.stamps = {}; // `${p}-upperBonus` → Container
this.rowZones = {}; // cat → Zone (human row strip)
this.enabled = false;
}
build() {
const s = this.scene, n = this.n, D = this.depth;
s.add.image(this.origin.x, this.origin.y, padKey(n)).setOrigin(0).setDepth(D);
this.activeG = s.add.graphics().setDepth(D + 1);
this.hoverG = s.add.graphics().setDepth(D + 1);
this.bestG = s.add.graphics().setDepth(D + 1);
const head = rowOf('head');
const nameSize = n >= 4 ? 24 : 28;
this.names = this.players.map((pl, p) => {
const c = cellCenter(p, 'head', n);
const max = n >= 4 ? 7 : 9;
const short = pl.name.length > max ? pl.name.slice(0, max - 1) + '…' : pl.name;
return s.add.text(c.x, head.y + head.h / 2, short, {
fontFamily: HAND_FONT, fontSize: `${nameSize}px`, color: INK[p],
}).setOrigin(0.5).setDepth(D + 3);
});
for (const row of PAD_ROWS) {
if (row.kind === 'head' || row.kind === 'gap') continue;
for (let p = 0; p < n; p++) {
const c = cellCenter(p, row.key, n);
const size = row.kind === 'grand' ? 34 : row.kind === 'sum' ? 24 : 28;
const t = s.add.text(c.x, c.y + 1, '', {
fontFamily: HAND_FONT, fontSize: `${size}px`, color: INK[p],
}).setOrigin(0.5).setDepth(D + 3);
this.cells[`${p}-${row.key}`] = t;
}
if (row.kind === 'cat') {
const c = cellCenter(0, row.key, n);
this.previews[row.key] = s.add.text(c.x, c.y + 1, '', {
fontFamily: HAND_FONT, fontSize: '26px', color: '#8f8a80',
}).setOrigin(0.5).setAlpha(0.75).setDepth(D + 2);
const hr = rowHit(row.key, n);
const z = s.add.zone(hr.x, hr.y, hr.w, hr.h).setOrigin(0).setDepth(D + 6);
z.on('pointerdown', () => { if (this.enabled) this.onCell?.(row.key); });
z.on('pointerover', () => { if (this.enabled) this.onHover?.(row.key); });
z.on('pointerout', () => this.onHover?.(null));
this.rowZones[row.key] = z;
}
}
// small par notes beside the upper totals
this.parNotes = this.players.map((_, p) => {
const r = cellRect(p, 'upperTotal', n);
return s.add.text(r.x + r.w - 6, r.y + 5, '', {
fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#7a6a50',
}).setOrigin(1, 0).setDepth(D + 3);
});
this.roundText = s.add.text(PAD_ROUND.x, PAD_ROUND.y, '', {
fontFamily: PRINT_FONT, fontSize: '17px', color: '#6f5d45',
}).setOrigin(1, 0.5).setDepth(D + 3);
return this;
}
zoneRows() { return Object.entries(this.rowZones).map(([key, zone]) => ({ key, zone })); }
setEnabled(on) {
this.enabled = !!on;
this.zoneRows().forEach((r) => (on ? r.zone.setInteractive({ useHandCursor: true }) : r.zone.disableInteractive()));
if (!on) this.hover(null);
}
// Only the given categories respond to the pointer.
setClickable(cats) {
const set = new Set(cats);
this.zoneRows().forEach((r) => {
if (this.enabled && set.has(r.key)) r.zone.setInteractive({ useHandCursor: true });
else r.zone.disableInteractive();
});
}
setRound(k, total) { this.roundText.setText(`ROUND ${k} OF ${total}`); }
setActive(p) {
const g = this.activeG;
g.clear();
if (p === null || p === undefined) return;
const top = rowOf('head'), last = PAD_ROWS[PAD_ROWS.length - 1];
const x = colX(p, this.n), w = colW(this.n);
g.fillStyle(0xfff3a0, 0.32).fillRect(x + 1, top.y + 1, w - 2, last.y + last.h - top.y - 2);
g.fillStyle(INK_HEX[p], 0.85).fillRect(x + 8, top.y + top.h - 8, w - 16, 3);
this.names.forEach((t, i) => t.setScale(i === p ? 1.08 : 1));
}
hover(cat) {
const g = this.hoverG;
g.clear();
if (!cat) return;
const r = cellRect(0, cat, this.n);
const hr = rowHit(cat, this.n);
g.fillStyle(0x22304f, 0.06).fillRect(hr.x, hr.y + 1, hr.w, hr.h - 2);
g.lineStyle(2, 0x22304f, 0.75);
// a slightly wobbly pencil box
g.beginPath();
g.moveTo(r.x + 4, r.y + 4); g.lineTo(r.x + r.w - 3, r.y + 5);
g.lineTo(r.x + r.w - 5, r.y + r.h - 4); g.lineTo(r.x + 5, r.y + r.h - 3);
g.closePath(); g.strokePath();
const t = this.previews[cat];
if (t?.text) t.setScale(1.15).setAlpha(1);
}
// ── previews ─────────────────────────────────────────────────────────────
showPreviews(map, best) {
for (const cat of CATEGORIES) {
const t = this.previews[cat];
if (cat in map) {
const v = map[cat];
t.setText(v === 0 ? '0' : String(v)).setColor(v === 0 ? '#b88a80' : '#7d7a72').setAlpha(0.75).setScale(1);
} else t.setText('');
}
this.bestG.clear();
if (best) {
const r = cellRect(0, best, this.n);
this.bestG.fillStyle(0xffd75a, 0.35).fillRoundedRect(r.x + 3, r.y + 3, r.w - 6, r.h - 6, 8);
this.bestG.lineStyle(2, 0xd4a017, 0.8).strokeRoundedRect(r.x + 3, r.y + 3, r.w - 6, r.h - 6, 8);
}
}
clearPreviews() {
for (const cat of CATEGORIES) this.previews[cat].setText('');
this.bestG.clear();
this.hover(null);
}
restorePreviewScale() {
for (const cat of CATEGORIES) { const t = this.previews[cat]; if (t.text) t.setScale(1).setAlpha(0.75); }
}
// ── writing ──────────────────────────────────────────────────────────────
// Pencil a value into a cell. Resolves when the stroke is done.
write(p, key, value, { animate = true, speed = 1 } = {}) {
const t = this.cells[`${p}-${key}`];
const isScratch = value === 0 && CATEGORIES.includes(key);
if (isScratch) return this.scratch(p, key, { animate, speed });
t.setText(String(value)).setAlpha(1);
if (!animate) { t.setCrop(); return Promise.resolve(); }
playSoundEx(this.scene, SFX.PENCIL_WRITE, { volume: 0.7 });
const w = t.width, h = t.height;
const prox = { k: 0 };
t.setCrop(0, 0, 0, h);
return new Promise((res) => {
this.scene.tweens.add({
targets: prox, k: 1, duration: 320 * speed, ease: 'Sine.Out',
onUpdate: () => t.setCrop(0, 0, w * prox.k, h),
onComplete: () => { t.setCrop(); res(); },
});
});
}
scratch(p, key, { animate = true, speed = 1 } = {}) {
const id = `${p}-${key}`;
this.cells[id].setText('');
this.scratches[id]?.destroy();
const r = cellRect(p, key, this.n);
const g = this.scene.add.graphics().setDepth(this.depth + 3);
this.scratches[id] = g;
const x0 = r.x + 12, x1 = r.x + r.w - 12, y0 = r.y + r.h / 2 + 5, y1 = r.y + r.h / 2 - 5;
const draw = (k) => {
g.clear();
g.lineStyle(3, INK_HEX[p], 0.85);
g.beginPath(); g.moveTo(x0, y0); g.lineTo(x0 + (x1 - x0) * k, y0 + (y1 - y0) * k); g.strokePath();
};
if (!animate) { draw(1); return Promise.resolve(); }
playSoundEx(this.scene, SFX.PENCIL_WRITE, { volume: 0.6, rate: 1.3 });
const prox = { k: 0 };
return new Promise((res) => {
this.scene.tweens.add({
targets: prox, k: 1, duration: 240 * speed, ease: 'Quad.Out',
onUpdate: () => draw(prox.k), onComplete: () => { draw(1); res(); },
});
});
}
flashCell(p, key, color = 0xffd75a) {
const r = cellRect(p, key, this.n);
const g = this.scene.add.graphics().setDepth(this.depth + 2);
g.fillStyle(color, 0.55).fillRoundedRect(r.x + 3, r.y + 3, r.w - 6, r.h - 6, 8);
this.scene.tweens.add({ targets: g, alpha: { from: 1, to: 0 }, duration: 700, onComplete: () => g.destroy() });
}
// Running totals (light pencil), par note, bonus stamp.
refreshTotals(p, player, { animate = false, final = false } = {}) {
const t = computeTotals(player);
const par = upperPar(player);
const set = (key, v, alpha = 1) => this.cells[`${p}-${key}`].setText(v === null ? '' : String(v)).setAlpha(alpha);
const anyUpper = UPPER.some((c) => player.scorecard[c] !== null);
set('upperTotal', anyUpper ? t.upperSubtotal : null, final || par.done ? 1 : 0.6);
if (t.upperBonus) {
if (!this.stamps[`${p}-upperBonus`]) this.stamp(p, 'upperBonus', '+35', { animate });
this.cells[`${p}-upperBonus`].setText('');
} else if (par.done || !par.alive) {
set('upperBonus', 0, 1);
} else set('upperBonus', null);
set('yahtzeeBonus', t.yahtzeeBonus ? t.yahtzeeBonus : null, 1);
set('grand', t.grand || null, final ? 1 : 0.45);
// par note: "+4" / "−6" against three-of-each, or "need 12"
const note = this.parNotes[p];
if (!anyUpper || par.earned || par.done) note.setText('');
else if (!par.alive) note.setText('no bonus').setColor('#9c2121');
else note.setText(par.par >= 0 ? `+${par.par} par` : `−${-par.par} par`).setColor(par.par >= 0 ? '#1d6a3c' : '#9c2121');
}
stamp(p, key, label, { animate = true } = {}) {
const s = this.scene;
const c = cellCenter(p, key, this.n);
const g = s.add.graphics();
g.lineStyle(3, 0xb3261e, 0.85).strokeCircle(0, 0, 17);
g.lineStyle(1.5, 0xb3261e, 0.6).strokeCircle(0, 0, 13);
const tx = s.add.text(0, 0, label, { fontFamily: '"Righteous", Georgia', fontSize: '14px', color: '#b3261e' }).setOrigin(0.5);
const ct = s.add.container(c.x, c.y, [g, tx]).setDepth(this.depth + 4).setRotation(-0.2);
this.stamps[`${p}-${key}`] = ct;
if (!animate) return Promise.resolve();
ct.setScale(2.6).setAlpha(0);
return new Promise((res) => {
s.tweens.add({
targets: ct, scale: 1, alpha: 0.95, duration: 260, ease: 'Quad.In',
onComplete: () => { playSoundEx(s, SFX.PIECE_CLICK, { volume: 0.8, rate: 0.6 }); s.cameras.main.shake(90, 0.002); res(); },
});
});
}
clearStamp(p, key) {
const id = `${p}-${key}`;
this.stamps[id]?.destroy();
delete this.stamps[id];
}
// Rebuild everything from state without animation (after an undo).
syncFromState(gs) {
for (let p = 0; p < this.n; p++) {
const pl = gs.players[p];
for (const cat of CATEGORIES) {
const id = `${p}-${cat}`;
const v = pl.scorecard[cat];
this.scratches[id]?.destroy(); delete this.scratches[id];
this.cells[id].setCrop();
if (v === null) this.cells[id].setText('');
else this.write(p, cat, v, { animate: false });
}
if (!computeTotals(pl).upperBonus) this.clearStamp(p, 'upperBonus');
this.refreshTotals(p, pl);
}
}
// ── end-of-game add-up ───────────────────────────────────────────────────
async tally(gs, ranks, wait) {
const s = this.scene;
for (let p = 0; p < this.n; p++) {
this.setActive(p);
const pl = gs.players[p];
this.refreshTotals(p, pl, { animate: true, final: false });
await this.write(p, 'upperTotal', computeTotals(pl).upperSubtotal);
await wait(160);
const grand = this.cells[`${p}-grand`];
grand.setText('');
await this.write(p, 'grand', computeTotals(pl).grand);
// ring the total
const r = cellRect(p, 'grand', this.n);
const g = s.add.graphics().setDepth(this.depth + 4);
g.lineStyle(2.5, INK_HEX[p], 0.85);
g.strokeEllipse(r.x + r.w / 2, r.y + r.h / 2, Math.min(r.w - 8, 92), r.h - 10);
// rank in the header corner
const head = cellRect(p, 'head', this.n);
const label = ['1st', '2nd', '3rd', '4th'][ranks[p] - 1];
const rt = s.add.text(head.x + head.w - 6, head.y + 4, label, {
fontFamily: HAND_FONT, fontSize: '18px', color: ranks[p] === 1 ? '#b3261e' : INK[p],
}).setOrigin(1, 0).setDepth(this.depth + 4);
if (ranks[p] === 1) rt.setFontSize(22);
await wait(260);
}
this.setActive(null);
playSound(s, SFX.PENCIL_WRITE);
}
}

View File

@ -0,0 +1,152 @@
// Exact single-turn expected-value solver for Zahtzee. Phaser-free.
//
// A turn is a small Markov decision problem: after each roll you choose which
// dice to keep (a sub-multiset of the roll), and after the last roll (or
// whenever you stop) you choose a box. With dice treated as multisets there
// are only 252 five-dice rolls and 462 keeps, so the whole turn solves exactly
// in a few milliseconds:
//
// V0(roll) = best box utility for that roll
// W_n(keep) = Σ P(outcome) · V_n(keep ∪ outcome) (re-rolling the rest)
// V_n+1(roll)= max over keeps ⊆ roll of W_n(keep)
//
// The box utility is supplied by the caller (YatziAI.js) so the same machinery
// drives the expert opponent, weaker heuristics, the Coach's "best keep" hint
// and the "odds if you chase it" readout (utility = 1 if a pattern is made).
const FACT = [1, 1, 2, 6, 24, 120];
// counts[1..6] → integer key (base 6)
const keyOf = (counts) => {
let k = 0;
for (let f = 6; f >= 1; f--) k = k * 6 + counts[f];
return k;
};
function enumerate(n) {
const out = [];
const counts = [0, 0, 0, 0, 0, 0, 0];
const rec = (face, left) => {
if (face === 6) {
counts[6] = left;
const c = counts.slice();
let p = FACT[n];
for (let f = 1; f <= 6; f++) p /= FACT[c[f]];
out.push({ counts: c, key: keyOf(c), p: p / 6 ** n, size: n });
counts[6] = 0;
return;
}
for (let k = 0; k <= left; k++) { counts[face] = k; rec(face + 1, left - k); }
counts[face] = 0;
};
rec(1, n);
return out;
}
const countsToDice = (c) => {
const d = [];
for (let f = 1; f <= 6; f++) for (let k = 0; k < c[f]; k++) d.push(f);
return d;
};
// ── Tables (built once) ──────────────────────────────────────────────────────
export const ROLLS = enumerate(5); // 252
const ROLL_INDEX = new Map(ROLLS.map((r, i) => [r.key, i]));
ROLLS.forEach((r) => { r.dice = countsToDice(r.counts); });
export const KEEPS = []; // 462 (sizes 0…5)
for (let n = 0; n <= 5; n++) for (const m of enumerate(n)) KEEPS.push({ counts: m.counts, key: m.key, size: n });
const KEEP_INDEX = new Map(KEEPS.map((k, i) => [k.key, i]));
// For every keep: the rolls it can turn into, with probabilities.
const OUTCOMES_BY_N = [0, 1, 2, 3, 4, 5].map((n) => enumerate(n));
const TRANS = KEEPS.map((k) => {
const outs = OUTCOMES_BY_N[5 - k.size];
return outs.map((o) => {
const c = k.counts.map((x, f) => x + o.counts[f]);
return { r: ROLL_INDEX.get(keyOf(c)), p: o.p };
});
});
// For every roll: the distinct keeps (sub-multisets) it allows.
const SUBKEEPS = ROLLS.map((r) => {
const seen = new Set();
const list = [];
for (let mask = 0; mask < 32; mask++) {
const c = [0, 0, 0, 0, 0, 0, 0];
for (let i = 0; i < 5; i++) if (mask & (1 << i)) c[r.dice[i]]++;
const k = KEEP_INDEX.get(keyOf(c));
if (!seen.has(k)) { seen.add(k); list.push(k); }
}
return list;
});
export function rollIndex(dice) {
const c = [0, 0, 0, 0, 0, 0, 0];
for (const d of dice) c[d]++;
return ROLL_INDEX.get(keyOf(c));
}
export function keepDice(keepIdx) { return countsToDice(KEEPS[keepIdx].counts); }
// ── Solve ────────────────────────────────────────────────────────────────────
// utility(dice) → number (the best box value for a final roll).
// Returns { V: [V0, V1, V2], W: [W0, W1] } where W[n] is indexed by keep and is
// the value of keeping that multiset with n+1 rolls still to come… precisely:
// W[n][k] = expected V[n] after re-rolling the dice not in k.
export function solveTurn(utility) {
const V0 = ROLLS.map((r) => utility(r.dice));
const V = [V0];
const W = [];
for (let n = 0; n < 2; n++) {
const Vn = V[n];
const Wn = TRANS.map((t) => {
let e = 0;
for (const { r, p } of t) e += p * Vn[r];
return e;
});
W.push(Wn);
V.push(ROLLS.map((_, ri) => {
let best = -Infinity;
for (const k of SUBKEEPS[ri]) if (Wn[k] > best) best = Wn[k];
return best;
}));
}
return { V, W };
}
// The keeps for these dice ranked best first, given `rollsRemaining` (1 or 2).
// Each entry: { keep, dice (kept values), value }.
export function rankKeeps(solution, dice, rollsRemaining) {
const n = Math.max(1, Math.min(2, rollsRemaining)) - 1;
const Wn = solution.W[n];
const ri = rollIndex(dice);
return SUBKEEPS[ri]
.map((k) => ({ keep: k, dice: keepDice(k), value: Wn[k] }))
.sort((a, b) => b.value - a.value || b.dice.length - a.dice.length);
}
// Turn a kept multiset into a hold mask over dice positions, preferring dice
// that are already held so nothing visibly shuffles.
export function maskForKeep(dice, keptValues, heldNow = [false, false, false, false, false]) {
const need = [0, 0, 0, 0, 0, 0, 0];
for (const v of keptValues) need[v]++;
const mask = [false, false, false, false, false];
for (const pass of [true, false]) {
for (let i = 0; i < 5; i++) {
if (mask[i] || !!heldNow[i] !== pass) continue;
if (need[dice[i]] > 0) { mask[i] = true; need[dice[i]]--; }
}
}
return mask;
}
// Probability of finishing with a roll that satisfies `test`, when chasing it
// optimally from `dice` with `rollsRemaining` rolls left.
const patternCache = new Map();
export function chaseOdds(name, test, dice, rollsRemaining) {
let sol = patternCache.get(name);
if (!sol) { sol = solveTurn((d) => (test(d) ? 1 : 0)); patternCache.set(name, sol); }
const r = Math.max(0, Math.min(2, rollsRemaining));
return sol.V[r][rollIndex(dice)];
}

View File

@ -0,0 +1,302 @@
// YatziTray.js — the felt dice tray, the keeper ledge and the leather cup, with
// five real 3D dice (src/ui/dice/Dice3D.js).
//
// Fairness: the engine rolls first (YatziLogic.rollDice); throwDice() then
// plays a planned boxed throw whose dice are relabelled to land on exactly
// those faces. The animation never decides a result.
//
// Every die has a fixed column (key 1–5). It rests in its column in the tray,
// and when kept it slides straight down onto the ledge slot below.
import { Die3D, planTrayThrow, poseFromPlan, restingQ, qslerp } from '../../ui/dice/Dice3D.js';
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
import {
TRAY, LEDGE, TRAY_WORLD, DIE_SIZE, COLUMN_U, REST_V, LEDGE_V, CUP, ground, toWorld,
} from './YatziLayout.js';
import { PAD_PX } from './YatziArt.js';
const BODY = [244, 238, 222];
const PIP = 0x15151c;
const YAW = [0.12, -0.08, 0.05, -0.14, 0.09];
const lerp = (a, b, t) => a + (b - a) * t;
const ease = (t) => 1 - (1 - t) * (1 - t);
const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
export class YatziTray {
constructor(scene, depth, { onDieClick, onDieHover } = {}) {
this.scene = scene;
this.depth = depth;
this.onDieClick = onDieClick;
this.onDieHover = onDieHover;
this.poses = [];
this.enabled = false;
}
build() {
const s = this.scene;
s.add.image(TRAY.x - PAD_PX, TRAY.y - PAD_PX, 'yatzi-tray').setOrigin(0).setDepth(this.depth);
s.add.image(LEDGE.x - PAD_PX, LEDGE.y - PAD_PX, 'yatzi-ledge').setOrigin(0).setDepth(this.depth + 1);
this.dice = [0, 1, 2, 3, 4].map(() => new Die3D(s, this.depth + 3, {
size: DIE_SIZE, body: BODY, pip: PIP, sin: 0.62, cos: 0.785, ground, glowColor: 0xf5d020,
}));
this.zones = this.dice.map((_, i) => {
const z = s.add.zone(0, 0, 100, 100).setDepth(this.depth + 8);
z.on('pointerdown', () => { if (this.enabled) this.onDieClick?.(i); });
z.on('pointerover', () => { if (this.enabled) this.onDieHover?.(i, true); });
z.on('pointerout', () => this.onDieHover?.(i, false));
return z;
});
for (let i = 0; i < 5; i++) {
this.poses[i] = { u: COLUMN_U[i], v: REST_V, h: 0, q: restingQ(i + 1, YAW[i]), face: i + 1, spot: 'tray', alpha: 1 };
this.apply(i);
}
return this;
}
// ── pose helpers ───────────────────────────────────────────────────────────
apply(i) {
const p = this.poses[i];
const d = this.dice[i];
d.setDepth(this.depth + 3 + p.v * 0.0004 + (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);
}
restFor(i, spot) {
return spot === 'ledge' ? { u: COLUMN_U[i], v: LEDGE_V } : { u: COLUMN_U[i], v: REST_V };
}
// Put every die at rest instantly: faces[i] up, in the tray or on the ledge.
layout(faces, held) {
for (let i = 0; i < 5; i++) {
const spot = held[i] ? 'ledge' : 'tray';
const r = this.restFor(i, spot);
Object.assign(this.poses[i], { ...r, h: 0, q: restingQ(faces[i], YAW[i]), face: faces[i], spot, alpha: this.dim ? 0.55 : 1 });
this.dice[i].setVisible(true);
this.apply(i);
}
this.syncZones();
}
setDim(on) {
this.dim = !!on;
for (let i = 0; i < 5; i++) {
if (this.poses[i].spot === 'cup') continue;
this.poses[i].alpha = on ? 0.55 : 1;
this.apply(i);
}
}
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;
const prox = { t: 0 };
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();
}
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(); },
});
});
}
// Slide a die between its tray column and its ledge slot.
async moveTo(i, spot, dur = 260) {
const r = this.restFor(i, spot);
this.poses[i].spot = spot;
await this.tweenDie(i, { ...r, h: 0 }, dur, { arc: dur > 0 ? 46 : 0, q: restingQ(this.poses[i].face, YAW[i]) });
if (dur > 0) playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.35, rate: 1.2 + Math.random() * 0.3 });
this.syncZones();
}
// Gather dice into the cup (or towards an opponent's seat) and hide them.
async scoop(indices, target, dur = 260) {
if (!indices.length) return;
const w = toWorld(target.x, target.y);
this.setGlowAll(0);
await Promise.all(indices.map((i, k) => new Promise((res) => {
this.scene.time.delayedCall(k * 35, async () => {
this.poses[i].spot = 'cup';
await this.tweenDie(i, { u: w.u, v: w.v + 30, h: 90 }, dur, { arc: 30, alphaTo: 0 });
this.dice[i].setVisible(false);
res();
});
})));
}
// Throw the given dice so they land on `faces` (one per index), then tidy
// them into their columns. `speed` scales the flight; `fast` skips it.
async throwDice(indices, faces, origin, { speed = 1, fast = false } = {}) {
if (!indices.length) return;
const s = this.scene;
if (fast) {
indices.forEach((i, k) => {
Object.assign(this.poses[i], { ...this.restFor(i, 'tray'), h: 0, q: restingQ(faces[k], YAW[i]), face: faces[k], spot: 'tray', alpha: 1 });
this.dice[i].setVisible(true);
this.apply(i);
});
playSoundEx(s, SFX.DICE_ROLL, { volume: 0.5 });
this.syncZones();
return;
}
const plan = planTrayThrow(TRAY_WORLD, origin, faces, Math.random, DIE_SIZE, {
spread: 1.6, sep: 1.45, aim: { u0: 0.25, u1: 0.75, v0: 0.3, v1: 0.72 },
});
playSound(s, SFX.DICE_ROLL);
indices.forEach((i, k) => {
Object.assign(this.poses[i], { face: faces[k], spot: 'tray', alpha: 1 });
this.dice[i].setVisible(true);
});
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(650, plan.duration * 1000) * speed, ease: 'Linear',
onUpdate: () => step(prox.t),
onComplete: () => { step(1); resolve(); },
});
});
// settle squash
await new Promise((resolve) => {
const sq = { k: 1.1 };
s.tweens.add({
targets: sq, k: 1, duration: 150, ease: 'Back.Out',
onUpdate: () => indices.forEach((i) => { this.dice[i].scale = sq.k; this.dice[i].draw(); }),
onComplete: () => { indices.forEach((i) => { this.dice[i].scale = 1; this.dice[i].draw(); }); resolve(); },
});
});
await this.wait(140 * speed);
// tidy into columns
await Promise.all(indices.map((i, k) => this.tweenDie(i, { ...this.restFor(i, 'tray'), h: 0 }, 300 * speed, {
q: restingQ(faces[k], YAW[i]),
})));
this.syncZones();
}
// Little celebratory hops (a Zahtzee, a straight…).
async hop(indices, height = 46, dur = 420) {
await Promise.all(indices.map((i, k) => new Promise((res) => {
this.scene.time.delayedCall(k * 70, async () => {
const p = this.poses[i];
await this.tweenDie(i, { u: p.u, v: p.v, h: 0 }, dur, { arc: height });
res();
});
})));
}
wait(ms) { return new Promise((r) => this.scene.time.delayedCall(Math.max(0, ms), r)); }
// ── glow / input ───────────────────────────────────────────────────────────
setGlow(i, amount, color = 0xf5d020) {
const d = this.dice[i];
d.glow = amount;
d.opts.glowColor = color;
d.draw();
}
setGlowAll(amount, color) { for (let i = 0; i < 5; i++) this.setGlow(i, amount, color); }
setEnabled(on) {
this.enabled = !!on;
this.zones.forEach((z) => (on ? z.setInteractive({ useHandCursor: true }) : z.disableInteractive()));
if (!on) this.zones.forEach((_, i) => this.onDieHover?.(i, false));
}
syncZones() {
this.dice.forEach((d, i) => {
const c = d.screenCenter();
this.zones[i].setPosition(c.x, c.y);
});
}
screenOf(i) { return this.dice[i].screenCenter(); }
}
// ── the leather cup ──────────────────────────────────────────────────────────
export class YatziCup {
constructor(scene, depth, { onPress } = {}) {
this.scene = scene;
this.depth = depth;
this.onPress = onPress;
this.enabled = false;
}
build() {
const s = this.scene;
this.glow = s.add.graphics().setDepth(this.depth - 1);
this.glow.fillStyle(0xf5d020, 0.22).fillEllipse(CUP.x, CUP.y + CUP.h / 2 - 12, CUP.w * 1.25, 40);
this.glow.lineStyle(3, 0xf5d020, 0.8).strokeEllipse(CUP.x, CUP.y + CUP.h / 2 - 12, CUP.w * 1.1, 32);
this.glow.setAlpha(0);
// pivot near the base so shakes and tilts look held
this.img = s.add.image(CUP.x, CUP.y + CUP.h / 2 - 4, 'yatzi-cup').setOrigin(0.5, 1 - 18 / (CUP.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; }
// Tip the cup towards the tray, then set it back down.
async pour() {
this.stopShake();
const s = this.scene;
await new Promise((res) => s.tweens.add({
targets: this.img, rotation: 0.55, x: this.home.x + 40, y: this.home.y - 46, 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);
}
}

View File

@ -0,0 +1,80 @@
# Zahtzee: A Tutorial by Aunt Dot
*Pull up a chair, hon. Every Friday for thirty years this kitchen table has had a dice cup on it, and I've lost track of how many score pads we've filled. Here's how the game goes.*
---
## What Is This Game?
Zahtzee is a dice game for **2–4 players**. Each player gets a column on the score pad with **13 boxes**. The game lasts **13 rounds**, and every round you fill exactly one box. When everyone's column is full, the highest **Grand Total** wins.
---
## Your Turn
1. **Shake the cup.** Press and hold the leather cup (or hold **Space**), then let go to throw. A quick click works too.
2. **Keep what you like.** Click a die (or press **1–5**) to move it onto the **keeper ledge** below the tray. Kept dice stay put. Click one again to put it back in the tray.
3. **Roll again**, up to **three throws** in all. The three pips beside the cup show how many throws you have left.
4. **Score it.** Click one open box in your column on the pad. You can score after any throw; you don't have to use all three.
If nothing fits, you still have to fill a box, so you **scratch** one by taking a zero there. Pick a box you weren't counting on.
---
## The Upper Section
| Box | Scores |
|---|---|
| Aces – Sixes | Add up only the dice showing that number |
If your upper boxes add up to **63 or more**, you get a **35-point bonus**. 63 is exactly three of each number, so it's called **par**. The pad notes how far ahead (+) or behind (−) par you are, and the line under the cup tells you how much you still need.
---
## The Lower Section
| Box | You need | Scores |
|---|---|---|
| 3 of a Kind | three alike | sum of all five dice |
| 4 of a Kind | four alike | sum of all five dice |
| Full House | three alike + a pair | 25 |
| Sm. Straight | four in a row | 30 |
| Lg. Straight | five in a row | 40 |
| Zahtzee | five alike | 50 |
| Chance | anything | sum of all five dice |
---
## Extra Zahtzees and the Joker
Rolled another Zahtzee after you've already scored 50 in the Zahtzee box? You get a **+100 bonus chip**, and the roll becomes a **Joker**:
1. If the matching upper box is open (five 4s → Fours), it **must** go there.
2. Otherwise it goes in any open **lower** box, and it scores in full there. Full House scores 25, Small Straight 30, and Large Straight 40, even though the dice don't form those patterns.
3. Only if the lower section is full do you scratch an open upper box.
If you scratched your Zahtzee box earlier, the Joker rules still apply, but you get no +100.
---
## Helpers
Open **Menu** to change these:
- **Score previews:** shows in pencil what each open box would score, and lights up the best box. Press **Enter** to score the lit box.
- **Coach:** marks the dice an expert would keep in blue, and gives your odds of making each pattern you could chase.
- **Undo last score:** take back your last box (or **Z**) before the next player rolls.
- **Sort dice after a roll:** lines up freshly rolled dice from low to high.
- **Confirm scratches:** double-checks before you zero a big box.
- **Opponent speed / Skip opponent animations:** for when you'd rather not wait.
---
## Aunt Dot's Tips
- **Chase the bonus early.** Three 6s in Sixes is worth more than it looks once you count the 35.
- **Chance is your safety net.** Keep it open for a bad roll late in the game.
- **Aces make the best scratch.** If you have to throw a zero away, put it there.
- **Large Straight is the hardest box to fill on purpose.** If you roll one, take it.
*Now go shake that cup.*

View File

@ -204,22 +204,33 @@ function flyTray(tray, size, origin, aim, rng) {
return { frames, u: X, v: Y, q: qf, hitWall }; return { frames, u: X, v: Y, q: qf, hitWall };
} }
// Plan a throw of both dice into a rectangular tray landing on `faces` [a, b]. // Plan a throw of N dice into a rectangular tray landing on `faces` (one per
// Returns { dice: [{frames, u, v, top}], duration } — frames are at 120 fps. // die; Catan passes two). Returns { dice: [{frames, u, v, top}], duration } —
export function planTrayThrow(tray, origin, faces, rng = Math.random, size = 30) { // frames are at 120 fps. opts.spread widens the aim fan for many dice;
// opts.aim { u0, u1, v0, v1 } (fractions of the tray) bounds where dice aim.
// With two dice and no opts the RNG draws and maths match the original
// two-die planner exactly.
export function planTrayThrow(tray, origin, faces, rng = Math.random, size = 30, opts = {}) {
const n = faces.length;
const mid = (n - 1) / 2;
const spread = opts.spread ?? 1;
const aimBox = opts.aim ?? { u0: 0.3, u1: 0.7, v0: 0.3, v1: 0.7 };
const sepMin = size * (opts.sep ?? 1.6);
const out = []; const out = [];
for (let i = 0; i < 2; i++) { for (let i = 0; i < n; i++) {
const off = n === 1 ? 0 : (i - mid) / mid; // −1 … +1 (±1 for two dice)
let best = null; let best = null;
for (let k = 0; k < 40; k++) { for (let k = 0; k < 40; k++) {
const aim = { const aim = {
u: tray.w * (0.3 + rng() * 0.4) + (i ? 1 : -1) * size * 0.9, u: tray.w * (aimBox.u0 + rng() * (aimBox.u1 - aimBox.u0)) + off * size * 0.9 * spread,
v: tray.h * (0.3 + rng() * 0.4), v: tray.h * (aimBox.v0 + rng() * (aimBox.v1 - aimBox.v0)),
}; };
const o = { u: origin.u + (i ? 1 : -1) * size * 0.4, v: origin.v, h: origin.h }; const o = { u: origin.u + off * size * 0.4 * spread, v: origin.v, h: origin.h };
const fly = flyTray(tray, size, o, aim, rng); const fly = flyTray(tray, size, o, aim, rng);
const inside = fly.u >= size / 2 && fly.u <= tray.w - size / 2 && fly.v >= size / 2 && fly.v <= tray.h - size / 2; const inside = fly.u >= size / 2 && fly.u <= tray.w - size / 2 && fly.v >= size / 2 && fly.v <= tray.h - size / 2;
const sep = i ? Math.hypot(fly.u - out[0].u, fly.v - out[0].v) : Infinity; let sep = Infinity;
const okSep = sep >= size * 1.6; for (const d of out) sep = Math.min(sep, Math.hypot(fly.u - d.u, fly.v - d.v));
const okSep = sep >= sepMin;
const score = (inside ? 2 : 0) + (okSep ? 2 : 0); const score = (inside ? 2 : 0) + (okSep ? 2 : 0);
if (!best || score > best.score) best = { ...fly, score }; if (!best || score > best.score) best = { ...fly, score };
if (score === 4) break; if (score === 4) break;
@ -227,7 +238,7 @@ export function planTrayThrow(tray, origin, faces, rng = Math.random, size = 30)
relabelFlight(best, faces[i]); relabelFlight(best, faces[i]);
out.push(best); out.push(best);
} }
const len = Math.max(out[0].frames.length, out[1].frames.length); const len = Math.max(1, ...out.map((d) => d.frames.length));
for (const d of out) while (d.frames.length < len) d.frames.push(d.frames[d.frames.length - 1]); for (const d of out) while (d.frames.length < len) d.frames.push(d.frames[d.frames.length - 1]);
return { dice: out, duration: (len - 1) / 120 }; return { dice: out, duration: (len - 1) / 120 };
} }

311
tools/verifyYatzi.js Normal file
View File

@ -0,0 +1,311 @@
#!/usr/bin/env node
// verifyYatzi.js — headless checks for Zahtzee:
// • scoring table, forced Joker rules, +100 bonus, commit bookkeeping/stats
// • seeded rolls, held dice untouched, sortUnheld keeps the multiset
// • upper par / bonus meter, rounds, rankings
// • solver: transition probabilities sum to 1, the known 4.6% Zahtzee odds,
// expert keeps on textbook positions
// • AI soak: every game finishes legally; 2–4 player tables; skill ladder
// strictly ordered by average score (1 < 2 < 3 < 4 < 5)
// • N-die tray throws land on the rolled faces, inside the felt, apart
// • screen layout: furniture on screen, no overlaps, pad rows on the paper
// Usage: node tools/verifyYatzi.js [--quick]
import * as L from '../src/games/yatzi/YatziLogic.js';
import { planTurn, expertAdvice, bestCategory, bonusChance } from '../src/games/yatzi/YatziAI.js';
import { ROLLS, KEEPS, solveTurn, rankKeeps, chaseOdds, maskForKeep } from '../src/games/yatzi/YatziSolver.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
import { planTrayThrow, topFace } from '../src/ui/dice/Dice3D.js';
import * as Y from '../src/games/yatzi/YatziLayout.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;
function card(fill = {}) {
const sc = Object.fromEntries(L.CATEGORIES.map((c) => [c, null]));
return Object.assign(sc, fill);
}
function stateWith(dice, fill = {}, extra = {}) {
const s = L.createInitialState({ playerNames: [{ name: 'A' }, { name: 'B', isAI: true }] });
s.dice = dice; s.phase = 'rolling'; s.rollsRemaining = 1;
Object.assign(s.players[0].scorecard, fill);
Object.assign(s.players[0], extra);
return s;
}
// ── scoring ─────────────────────────────────────────────────────────────────────
section('Scoring');
{
const T = [
[[1, 1, 1, 2, 3], 'ones', 3], [[6, 6, 2, 6, 1], 'sixes', 18], [[2, 3, 4, 5, 6], 'fives', 5],
[[3, 3, 3, 4, 5], 'threeOfKind', 18], [[3, 3, 4, 4, 5], 'threeOfKind', 0],
[[2, 2, 2, 2, 6], 'fourOfKind', 14], [[2, 2, 2, 6, 6], 'fourOfKind', 0],
[[2, 2, 3, 3, 3], 'fullHouse', 25], [[2, 2, 2, 2, 2], 'fullHouse', 0], [[2, 2, 3, 3, 4], 'fullHouse', 0],
[[1, 2, 3, 4, 6], 'smallStraight', 30], [[3, 4, 5, 6, 6], 'smallStraight', 30], [[1, 2, 3, 5, 6], 'smallStraight', 0],
[[2, 3, 4, 5, 6], 'largeStraight', 40], [[1, 2, 3, 4, 6], 'largeStraight', 0],
[[4, 4, 4, 4, 4], 'yahtzee', 50], [[4, 4, 4, 4, 3], 'yahtzee', 0], [[6, 5, 4, 3, 1], 'chance', 19],
];
for (const [d, c, v] of T) ok(`${c} ${d.join('')} = ${v}`, L.baseScore(d, c) === v, `got ${L.baseScore(d, c)}`);
ok('all 13 boxes open on a fresh card', L.legalCategories([1, 2, 3, 4, 6], card()).length === 13);
ok('a filled box is not legal', !L.legalCategories([1, 2, 3, 4, 6], card({ chance: 16 })).includes('chance'));
ok('scoreForCommit returns null for a filled box', L.scoreForCommit([1, 1, 1, 1, 1], 'ones', card({ ones: 3 })) === null);
}
// ── Joker ────────────────────────────────────────────────────────────────────────
section('Joker rules (forced)');
{
const five4 = [4, 4, 4, 4, 4];
ok('first Zahtzee: no Joker, any box', L.jokerMode(five4, card()) === null && L.legalCategories(five4, card()).length === 13);
const z50 = card({ yahtzee: 50 });
ok('matching upper open → forced there', JSON.stringify(L.legalCategories(five4, z50)) === '["fours"]');
ok('forced upper scores 20', L.scoreForCommit(five4, 'fours', z50) === 20);
ok('other boxes illegal while upper is open', L.scoreForCommit(five4, 'chance', z50) === null);
const z50f = card({ yahtzee: 50, fours: 12 });
const legal = L.legalCategories(five4, z50f);
ok('upper filled → only open lower boxes', legal.length === 6 && legal.every((c) => L.LOWER.includes(c)), legal.join(','));
ok('upper zero NOT allowed while lower is open (the old bug)', !legal.includes('ones'));
ok('Joker Full House = 25', L.scoreForCommit(five4, 'fullHouse', z50f) === 25);
ok('Joker Sm. Straight = 30', L.scoreForCommit(five4, 'smallStraight', z50f) === 30);
ok('Joker Lg. Straight = 40', L.scoreForCommit(five4, 'largeStraight', z50f) === 40);
ok('Joker 4 of a Kind = sum', L.scoreForCommit(five4, 'fourOfKind', z50f) === 20);
const lowerFull = card({ yahtzee: 50, fours: 12, threeOfKind: 20, fourOfKind: 20, fullHouse: 25, smallStraight: 30, largeStraight: 40, chance: 22 });
const l2 = L.legalCategories(five4, lowerFull);
ok('lower full → scratch an open upper box', L.jokerMode(five4, lowerFull) === 'scratch' && l2.length === 5 && l2.every((c) => L.UPPER.includes(c)));
ok('the scratch scores 0', L.scoreForCommit(five4, 'sixes', lowerFull) === 0);
let s = stateWith(five4, { yahtzee: 50, fours: 12 });
s = L.commitScore(s, 'largeStraight');
ok('+100 bonus awarded with 50 in the box', s.players[0].yahtzeeBonusCount === 1 && s.lastBonusGained && s.lastCommit.bonus);
ok('bonus counted in the totals', L.computeTotals(s.players[0]).yahtzeeBonus === 100);
let s0 = stateWith(five4, { yahtzee: 0, fours: 12 });
ok('scratched Zahtzee box: Joker still forced to lower', L.jokerMode(five4, s0.players[0].scorecard) === 'lower');
s0 = L.commitScore(s0, 'fullHouse');
ok('…but no +100', s0.players[0].yahtzeeBonusCount === 0 && s0.players[0].scorecard.fullHouse === 25);
}
// ── commit / turn flow ──────────────────────────────────────────────────────────
section('Commit and turn flow');
{
let s = stateWith([6, 6, 6, 2, 2]);
const t = L.commitScore(s, 'fullHouse');
ok('commit writes the box', t.players[0].scorecard.fullHouse === 25);
ok('turn passes to the next player', t.current === 1 && t.rollsRemaining === 3 && t.phase === 'preroll');
ok('holds reset', t.held.every((h) => !h));
ok('lastCommit recorded', t.lastCommit.category === 'fullHouse' && t.lastCommit.value === 25 && t.lastCommit.player === 0);
ok('best turn stat', t.players[0].stats.bestTurn.value === 25);
ok('illegal commit is a no-op', L.commitScore(t, 'chance') === t);
ok('log line written', t.log.length === 1 && t.log[0].includes('Full House'));
const sc = L.commitScore(stateWith([1, 2, 3, 5, 6]), 'yahtzee');
ok('scratch counted', sc.players[0].stats.scratches === 1 && sc.players[0].scorecard.yahtzee === 0);
const ub = L.commitScore(stateWith([6, 6, 6, 6, 1], { ones: 3, twos: 6, threes: 9, fours: 12, fives: 15 }), 'sixes');
ok('upper bonus flagged on the commit that earns it', ub.lastCommit.upperBonusEarned && L.computeTotals(ub.players[0]).upperBonus === 35);
ok('toggleHold only while rolling', L.toggleHold(L.createInitialState({ playerNames: [{ name: 'A' }] }), 0).held[0] === false);
}
// ── rolling ─────────────────────────────────────────────────────────────────────
section('Rolling');
{
const base = L.createInitialState({ playerNames: [{ name: 'A' }] });
const a = L.rollDice(base, mulberry32(7)), b = L.rollDice(base, mulberry32(7));
ok('seeded rolls repeat', JSON.stringify(a.dice) === JSON.stringify(b.dice));
ok('roll uses one throw', a.rollsRemaining === 2 && a.phase === 'rolling');
let h = L.setHeld(a, [true, false, true, false, false]);
const r2 = L.rollDice(h, mulberry32(99));
ok('held dice untouched', r2.dice[0] === a.dice[0] && r2.dice[2] === a.dice[2]);
let all = true, sortedOk = true;
const rng = mulberry32(3);
for (let i = 0; i < 2000; i++) {
let s = L.rollDice(base, rng);
s.dice.forEach((d) => { if (d < 1 || d > 6 || !Number.isInteger(d)) all = false; });
s = L.setHeld(s, [rng() < 0.5, rng() < 0.5, rng() < 0.5, rng() < 0.5, rng() < 0.5]);
const r = L.rollDice(s, rng);
const srt = L.sortUnheld(r);
const idx = [0, 1, 2, 3, 4].filter((k) => !r.held[k]);
const before = idx.map((k) => r.dice[k]).sort().join();
const after = idx.map((k) => srt.dice[k]);
if (after.join() !== before) sortedOk = false;
if (r.held.some((hh, k) => hh && srt.dice[k] !== r.dice[k])) sortedOk = false;
}
ok('dice are always 1–6', all);
ok('sortUnheld sorts only the rolled dice and keeps the multiset', sortedOk);
const done = { ...a, rollsRemaining: 0, phase: 'scoring' };
ok('no fourth roll', L.rollDice(done) === done);
}
// ── par / rounds / ranks ────────────────────────────────────────────────────────
section('Par, rounds and rankings');
{
const p = { scorecard: card({ ones: 3, sixes: 24 }), yahtzeeBonusCount: 0 };
const par = L.upperPar(p);
ok('par counts against three-of-each', par.par === 6 && par.sub === 27 && par.need === 36 && par.alive);
const dead = L.upperPar({ scorecard: card({ ones: 0, twos: 0, threes: 0, fours: 0, fives: 5 }) });
ok('bonus out of reach detected', !dead.alive && dead.need === 58);
ok('bonusChance is 1 once earned, 0 when impossible', bonusChance(63, [1]) === 1 && bonusChance(0, [1]) === 0);
const s = L.createInitialState({ playerNames: [{ name: 'A' }, { name: 'B' }, { name: 'C' }] });
ok('round 1 at the start', L.roundOf(s) === 1);
s.players.forEach((pl, i) => { pl.scorecard.chance = [20, 25, 20][i]; });
ok('round 2 after everyone scores once', L.roundOf(s) === 2);
ok('ties share a rank', JSON.stringify(L.rankings(s)) === '[2,1,2]');
}
// ── solver ──────────────────────────────────────────────────────────────────────
section('Solver');
{
ok('252 rolls, 462 keeps', ROLLS.length === 252 && KEEPS.length === 462);
ok('roll probabilities sum to 1', near(ROLLS.reduce((a, r) => a + r.p, 0), 1, 1e-9));
const sol = solveTurn((d) => (L.isYahtzee(d) ? 1 : 0));
const p3 = ROLLS.reduce((a, r, i) => a + r.p * sol.V[2][i], 0);
ok('Zahtzee in three throws ≈ 4.60% (known value 4.6029%)', near(p3, 0.046029, 0.00005), (p3 * 100).toFixed(4) + '%');
const ls = chaseOdds('ls', L.isLargeStraight, [2, 3, 4, 5, 5], 2);
ok('open-ended four-run with two throws ≈ 55.6% for a Large Straight', near(ls, 1 - (2 / 3) ** 2, 1e-9), ls.toFixed(4));
const adv = expertAdvice([5, 5, 5, 5, 5], [false, false, false, false, false], card(), 2);
ok('expert stands on a Zahtzee', adv.stop);
const adv2 = expertAdvice([6, 6, 6, 2, 1], [false, false, false, false, false], card(), 2);
ok('expert keeps three sixes from 6-6-6-2-1', adv2.keep.join() === '6,6,6', adv2.keep.join());
const adv3 = expertAdvice([2, 3, 4, 5, 5], [false, false, false, false, false], card(), 1);
ok('expert keeps the 2-3-4-5 run with one throw left', adv3.keep.join() === '2,3,4,5', adv3.keep.join());
ok('best box for 2-2-3-3-3 is Full House on a fresh card', bestCategory([2, 2, 3, 3, 3], card()) === 'fullHouse');
ok('expert scratches Aces, not Zahtzee, with junk', bestCategory([2, 3, 4, 6, 6], card({
twos: 6, threes: 9, fours: 12, fives: 15, sixes: 18, threeOfKind: 20, fourOfKind: 20, fullHouse: 25,
smallStraight: 30, largeStraight: 40, chance: 22,
})) === 'ones');
const m = maskForKeep([3, 5, 3, 1, 3], [3, 3], [false, false, true, false, true]);
ok('maskForKeep prefers dice already held', m[2] && m[4] && !m[0]);
const ranked = rankKeeps(solveTurn((d) => L.sumDice(d)), [1, 1, 6, 6, 2], 1);
ok('rankKeeps best-first', ranked.every((r, i) => i === 0 || r.value <= ranked[i - 1].value));
ok('keep the sixes when maximising the sum', ranked[0].dice.join() === '6,6', ranked[0].dice.join());
}
// ── AI soak ─────────────────────────────────────────────────────────────────────
function playGame(skills, seed) {
const rng = mulberry32(seed);
let s = L.createInitialState({ playerNames: skills.map((k, i) => ({ name: `P${i}`, isAI: true })) });
let turns = 0, illegal = 0;
while (s.phase !== 'gameover') {
if (++turns > 13 * skills.length + 1) return { stuck: true };
const p = s.players[s.current];
const plan = planTurn(p.scorecard, p.yahtzeeBonusCount, skills[s.current], rng);
s = L.rollDice(s, rng);
while (s.rollsRemaining > 0) {
const m = plan.chooseHold(s.dice, s.held, s.rollsRemaining);
if (plan.shouldStop(m)) break;
s = L.setHeld(s, m);
s = L.rollDice(s, rng);
}
const cat = plan.chooseCategory(s.dice);
if (!L.legalCategories(s.dice, s.players[s.current].scorecard).includes(cat)) illegal++;
const next = L.commitScore(s, cat);
if (next === s) return { stuck: true };
s = next;
}
return { s, illegal, turns };
}
section('AI soak');
{
let stuck = 0, illegal = 0, filled = true, sums = true;
const games = QUICK ? 40 : 160;
for (let g = 0; g < games; g++) {
const n = 2 + (g % 3);
const skills = Array.from({ length: n }, (_, i) => 1 + ((g + i * 2) % 5));
const r = playGame(skills, 500 + g);
if (r.stuck) { stuck++; continue; }
illegal += r.illegal;
for (const pl of r.s.players) {
if (!L.CATEGORIES.every((c) => pl.scorecard[c] !== null)) filled = false;
const t = L.computeTotals(pl);
if (t.grand !== t.upperSubtotal + t.upperBonus + t.lowerSubtotal + t.yahtzeeBonus) sums = false;
}
if (L.roundOf(r.s) !== 13) filled = false;
}
ok(`${games} mixed 2–4 player games finish`, stuck === 0, `${stuck} stuck`);
ok('every AI box choice was legal', illegal === 0, `${illegal} illegal`);
ok('every column ends with all 13 boxes filled', filled);
ok('grand totals add up', sums);
}
section('Skill ladder');
{
const N = QUICK ? 120 : 500;
const avg = {};
const skills = QUICK ? [1, 3, 5] : [1, 2, 3, 4, 5];
for (const k of skills) {
let sum = 0;
for (let g = 0; g < N; g++) sum += L.computeTotals(playGame([k], 9000 + g).s.players[0]).grand;
avg[k] = sum / N;
}
console.log(' averages: ' + skills.map((k) => `${k}=${avg[k].toFixed(1)}`).join(' '));
for (let i = 1; i < skills.length; i++) {
ok(`skill ${skills[i]} out-scores skill ${skills[i - 1]}`, avg[skills[i]] > avg[skills[i - 1]], `${avg[skills[i]].toFixed(1)} vs ${avg[skills[i - 1]].toFixed(1)}`);
}
if (avg[5]) ok('expert averages 235+', avg[5] >= 235, avg[5].toFixed(1));
}
// ── throws ──────────────────────────────────────────────────────────────────────
section('Dice throws (N-die tray)');
{
const rng = mulberry32(42);
let faces = true, inside = true, apart = 0, total = 0;
const S = Y.DIE_SIZE;
const throws = QUICK ? 120 : 400;
for (let t = 0; t < throws; t++) {
const n = 1 + (t % 5);
const want = Array.from({ length: n }, () => 1 + Math.floor(rng() * 6));
const origin = t % 2 ? Y.humanOrigin() : Y.seatOrigin(200 + (t % 3) * 375);
const plan = planTrayThrow(Y.TRAY_WORLD, origin, want, rng, S, { spread: 1.6, sep: 1.45, aim: { u0: 0.25, u1: 0.75, v0: 0.3, v1: 0.72 } });
plan.dice.forEach((d, i) => {
const last = d.frames[d.frames.length - 1];
if (topFace(last.q) !== want[i]) faces = false;
if (last.u < S / 2 - 1 || last.u > Y.TRAY_WORLD.w - S / 2 + 1 || last.v < S / 2 - 1 || last.v > Y.TRAY_WORLD.h - S / 2 + 1) inside = false;
});
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
total++;
if (Math.hypot(plan.dice[i].u - plan.dice[j].u, plan.dice[i].v - plan.dice[j].v) >= S * 1.05) apart++;
}
}
ok('every die lands on the rolled face', faces);
ok('every die rests inside the felt', inside);
ok('≥ 97% of die pairs rest apart', total === 0 || apart / total >= 0.97, `${((100 * apart) / total).toFixed(1)}%`);
const two = planTrayThrow({ w: 300, h: 300 }, { u: 150, v: 360, h: 60 }, [3, 4], mulberry32(1), 30);
ok('two-die planner still returns two dice (Catan)', two.dice.length === 2 && two.dice.every((d, i) => d.top === [3, 4][i]));
}
// ── layout ──────────────────────────────────────────────────────────────────────
section('Screen layout');
{
for (let nOpp = 1; nOpp <= 3; nOpp++) {
const f = Y.hudFurniture(nOpp);
f.forEach((r) => ok(`${r.name} on screen (${nOpp} opp)`, Y.onScreen(r), JSON.stringify(r)));
for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) {
ok(`${f[i].name} / ${f[j].name} don't overlap (${nOpp} opp)`, !Y.rectsOverlap(f[i], f[j]));
}
for (let k = 0; k < nOpp; k++) {
const s = Y.seatParts(k, nOpp);
ok(`seat ${k} bubble inside its seat`, Y.inside(s.bubble, s.rect));
ok(`seat ${k} portrait inside its seat`, s.portrait.x - s.portrait.r >= s.rect.x && s.portrait.y + s.portrait.r <= s.rect.y + s.rect.h);
}
}
ok('pad rows end on the paper', Y.PAD_BOTTOM <= Y.PAPER.y + Y.PAPER.h - 10, String(Y.PAD_BOTTOM));
ok('paper inside the board', Y.inside(Y.PAPER, Y.BOARD));
for (let n = 2; n <= 4; n++) {
ok(`pad columns fit (${n} players)`, Y.colX(n - 1, n) + Y.colW(n) <= Y.GRID.x + Y.GRID.w + 0.01 && Y.colW(n) >= 90);
}
Y.COLUMN_X.forEach((x, i) => {
ok(`die column ${i + 1} inside the felt`, x - Y.DIE_SIZE / 2 >= Y.TRAY_FELT.x && x + Y.DIE_SIZE / 2 <= Y.TRAY_FELT.x + Y.TRAY_FELT.w);
ok(`ledge slot ${i + 1} on the ledge`, x - 60 >= Y.LEDGE.x && x + 60 <= Y.LEDGE.x + Y.LEDGE.w);
});
const rest = Y.ground(Y.COLUMN_U[0], Y.REST_V);
ok('tray rest row inside the felt', rest.y > Y.TRAY_FELT.y + 40 && rest.y < Y.TRAY_FELT.y + Y.TRAY_FELT.h - 10);
const ledge = Y.ground(0, Y.LEDGE_V);
ok('ledge ground on the ledge top', ledge.y > Y.LEDGE.y && ledge.y < Y.LEDGE.y + 70);
ok('cup mouth below the tray', Y.CUP_MOUTH.y > Y.TRAY.y + Y.TRAY.h);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);