diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 62c1fe1..0b59130 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -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: '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: '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: '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 }); diff --git a/src/games/yatzi/YatziAI.js b/src/games/yatzi/YatziAI.js index ac935d3..487715f 100644 --- a/src/games/yatzi/YatziAI.js +++ b/src/games/yatzi/YatziAI.js @@ -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 -// `chooseCategory(dice, scorecard)` → category slug -// `shouldKeepRolling(holdMask, rollsRemaining)` → boolean +// planTurn(scorecard, bonusCount, skill, rng) → a turn planner: +// .chooseHold(dice, held, rollsRemaining) → 5-bool hold mask +// .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 { - UPPER, legalCategories, scoreForCommit, isYahtzee, + UPPER, CATEGORIES, legalCategories, scoreForCommit, jokerStatus, + isYahtzee, isFullHouse, isSmallStraight, isLargeStraight, diceCounts, + UPPER_BONUS, UPPER_BONUS_AT, YAHTZEE_BONUS, } from './YatziLogic.js'; +import { solveTurn, rankKeeps, maskForKeep, chaseOdds } from './YatziSolver.js'; -export function chooseDiceToHold(dice, scorecard, rollsRemaining) { - const open = (c) => scorecard[c] === null; - const counts = {}; - for (const d of dice) counts[d] = (counts[d] || 0) + 1; +// Average score each box yields under optimal solitaire play — what a box is +// "worth" while it stays open. Scoring into a box gives up this future value. +export const BOX_WORTH = { + 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) - if (isYahtzee(dice)) return [true, true, true, true, true]; - - const face4 = faceWithCount(counts, 4); - const face3 = faceWithCount(counts, 3); - const pairs = Object.entries(counts).filter(([, c]) => c >= 2).map(([f]) => Number(f)); - - // 4-of-a-kind: hold the four; reroll the spare hunting Yahtzee - if (face4 !== null && (open('yahtzee') || open('fourOfKind') || open('threeOfKind'))) { - return dice.map((d) => d === face4); - } - - // 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; +// Rough chance of reaching 63 from `sub` with `openFaces` still to fill. +export function bonusChance(sub, openFaces) { + const need = UPPER_BONUS_AT - sub; + if (need <= 0) return 1; + if (openFaces.length === 0) return 0; + let mean = 0, varSum = 0, max = 0; + for (const f of openFaces) { mean += UPPER_MEAN[f]; varSum += UPPER_SD[f] ** 2; max += 5 * f; } + if (need > max) return 0; + const z = (mean - need) / Math.sqrt(varSum + 4); + return 1 / (1 + Math.exp(-1.7 * z)); } -// AI decides to stop early if every die is held (further rolls do nothing). -export function shouldKeepRolling(holdMask, rollsRemaining) { - if (rollsRemaining <= 0) return false; - return holdMask.some((h) => !h); +function upperState(scorecard) { + let sub = 0; + const open = []; + 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 -// sacrificing the cheapest slot first. -export function chooseCategory(dice, scorecard) { +// Utility of placing `dice` into `cat`. `mode` 'expert' prices future value +// and bonus chances; 'raw' just counts points this turn (+ a bonus crossed now). +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); if (legal.length === 0) return null; const scored = legal.map((c) => ({ c, v: scoreForCommit(dice, c, scorecard) ?? 0 })); - scored.sort((a, b) => { - if (b.v !== a.v) return b.v - a.v; - return sacrificeRank(a.c) - sacrificeRank(b.c); - }); + scored.sort((a, b) => (b.v - a.v) || (sacrificeRank(a.c) - sacrificeRank(b.c))); return scored[0].c; } -// Lower rank = cheaper to zero out when no slot scores positive const SACRIFICE_ORDER = [ - 'ones', 'twos', 'threes', - 'fourOfKind', 'threeOfKind', - 'fours', 'fives', - 'fullHouse', 'smallStraight', - 'sixes', - 'largeStraight', 'chance', 'yahtzee', + 'ones', 'twos', 'threes', 'fourOfKind', 'threeOfKind', 'fours', 'fives', + 'fullHouse', 'smallStraight', 'sixes', 'largeStraight', 'chance', 'yahtzee', ]; function sacrificeRank(category) { const i = SACRIFICE_ORDER.indexOf(category); 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) { - for (const [f, c] of Object.entries(counts)) { - if (c >= n) return Number(f); + const faceWith = (n) => { for (let f = 6; f >= 1; f--) if (counts[f] >= n) return f; return null; }; + const face4 = faceWith(4); + 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; -} - -function hasLargeStraight(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))); + 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); + if (ss && (open('smallStraight') || open('largeStraight'))) { + return open('largeStraight') ? ss : [true, true, true, true, true]; + } + 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) { const s = new Set(dice); - for (const seq of [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]) { - if (seq.every((n) => s.has(n))) { - return maskMatchingValues(dice, seq); - } + for (const seq of [[3, 4, 5, 6], [2, 3, 4, 5], [1, 2, 3, 4]]) { + if (seq.every((n) => s.has(n))) return maskMatchingValues(dice, seq); } return null; } -// Build a hold mask that picks one die per target value (in order). function maskMatchingValues(dice, targets) { const need = {}; for (const t of targets) need[t] = (need[t] ?? 0) + 1; @@ -144,16 +238,34 @@ function maskMatchingValues(dice, targets) { return mask; } -// Longest run of consecutive distinct values in dice. function longestConsecutive(dice) { const unique = [...new Set(dice)].sort((a, b) => a - b); - if (unique.length === 0) return []; - let best = [unique[0]]; - let cur = [unique[0]]; + let best = [unique[0]], cur = [unique[0]]; for (let i = 1; i < unique.length; i++) { - if (unique[i] === unique[i - 1] + 1) cur.push(unique[i]); - else cur = [unique[i]]; + if (unique[i] === unique[i - 1] + 1) cur.push(unique[i]); else cur = [unique[i]]; if (cur.length > best.length) best = [...cur]; } 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; +} + diff --git a/src/games/yatzi/YatziArt.js b/src/games/yatzi/YatziArt.js new file mode 100644 index 0000000..dbdf7f5 --- /dev/null +++ b/src/games/yatzi/YatziArt.js @@ -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); +} diff --git a/src/games/yatzi/YatziDialogs.js b/src/games/yatzi/YatziDialogs.js new file mode 100644 index 0000000..31847de --- /dev/null +++ b/src/games/yatzi/YatziDialogs.js @@ -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; +} diff --git a/src/games/yatzi/YatziEndScreen.js b/src/games/yatzi/YatziEndScreen.js new file mode 100644 index 0000000..de54a48 --- /dev/null +++ b/src/games/yatzi/YatziEndScreen.js @@ -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()) }; +} diff --git a/src/games/yatzi/YatziGame.js b/src/games/yatzi/YatziGame.js index a49414d..f7ce672 100644 --- a/src/games/yatzi/YatziGame.js +++ b/src/games/yatzi/YatziGame.js @@ -1,765 +1,772 @@ +// YatziGame.js — Zahtzee at the kitchen table: a felt dice tray with five real +// 3D dice, a leather cup you shake, a keeper ledge, and a clipboard score pad. +// +// YatziLogic rules (pure) YatziAI / YatziSolver opponents 1–5 + Coach +// YatziLayout every rect (Phaser-free) YatziArt baked textures +// YatziTray dice, ledge, cup YatziPad the score pad +// YatziDialogs menu / confirm YatziEndScreen the after-game card + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { - CATEGORIES, UPPER, LOWER, CATEGORY_LABELS, - createInitialState, rollDice, toggleHold, commitScore, - computeTotals, baseScore, scoreForCommit, legalCategories, - getWinners, -} from './YatziLogic.js'; -import { chooseDiceToHold, chooseCategory, shouldKeepRolling } from './YatziAI.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { aiTiming, clampSkill, PACE } from '../../ui/cardtable/AITiming.js'; +import * as L from './YatziLogic.js'; +import { planTurn, expertAdvice, bestCategory, describeKeep } from './YatziAI.js'; +import { + seatParts, HUMAN_PORTRAIT, HUMAN_NAME, CUP_MOUTH, PIPS, PIPS_LABEL, STATUS, SUBLINE, TICKER, METER, + BTN, UNDO_BTN, MENU_BTN, BANNER, TRAY, humanOrigin, seatOrigin, cellCenter, ground, +} from './YatziLayout.js'; +import { prepareYatziArt, SEAT_TINT, HAND_FONT, DISPLAY_FONT, PRINT_FONT, SERIF } from './YatziArt.js'; +import { YatziTray, YatziCup } from './YatziTray.js'; +import { YatziPad } from './YatziPad.js'; +import { openPauseMenu, confirmBox } from './YatziDialogs.js'; +import { openEndScreen, recordPersonalBest } from './YatziEndScreen.js'; -// ─── Layout ─────────────────────────────────────────────────────────────── -const LEFT_CX = 480; -const DICE_SIZE = 104; -const DICE_GAP = 22; -const DICE_TOTAL_W = 5 * DICE_SIZE + 4 * DICE_GAP; // 608 -const DICE_LEFT = LEFT_CX - DICE_TOTAL_W / 2; // 176 -const DICE_Y = 480; - -// Scorecard panel on the right half -const SC_X = 980; // left edge of panel -const SC_RIGHT_MARGIN = 40; -const SC_W = GAME_WIDTH - SC_X - SC_RIGHT_MARGIN; // 900 -const SC_CAT_W = 220; -const SC_PLAYERS_W = SC_W - SC_CAT_W; // shared among N player columns -const SC_TOP = 110; -const SC_HEADER_H = 50; -const SC_ROW_H = 42; -const SC_SUMMARY_H = 40; -const SC_GRAND_H = 54; - -// Portrait column -const PORTRAIT_X = 90; -const PORTRAIT_R = 48; -const PORTRAIT_TOP = 200; -const PORTRAIT_GAP = 124; - -const DEPTH = { - bg: -1, panel: 0, grid: 1, cellBg: 2, - cellText: 3, preview: 4, hover: 5, - dieBox: 10, diePip: 11, dieFrame: 12, dieHit: 13, - ui: 20, toast: 50, modal: 60, +const HUMAN = 0; +const SETTINGS_KEY = 'yatzi-settings'; +const DEFAULT_SETTINGS = { + pace: 'normal', hints: true, coach: false, undo: true, sort: true, confirmScratch: true, skipAI: false, }; - -// 3x3 pip layout (col, row offsets in {-1, 0, 1}) per face -const PIP_POS = { - 1: [[0, 0]], - 2: [[-1, -1], [1, 1]], - 3: [[-1, -1], [0, 0], [1, 1]], - 4: [[-1, -1], [1, -1], [-1, 1], [1, 1]], - 5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]], - 6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]], +const D = { + bg: 0, seat: 5, tray: 10, cup: 30, hud: 40, pad: 50, hand: 70, fx: 80, banner: 85, end: 95, modal: 110, }; +const VALUABLE = ['yahtzee', 'largeStraight', 'smallStraight', 'fullHouse']; -const ROW_INDEX = (() => { - // y-offset of each category row from top of its section - const m = {}; - UPPER.forEach((c, i) => { m[c] = i; }); - LOWER.forEach((c, i) => { m[c] = i; }); - return m; -})(); +const SPEECH = { + zahtzee: ['ZAHTZEE!', 'Five of a kind!', "Read 'em and weep!"], + big: ["I'll take that.", 'Not bad at all.', 'Pencil that in!', 'Lovely.'], + scratch: ['Ugh… scratching {cat}.', 'That one hurts.', 'Nothing doing. {cat} goes.'], + set: ['Going for {face}…', 'Come on, {face}!', 'Keeping the {face}.'], + straight: ['Chasing the straight.', 'One more for the run…'], + house: ['Full house, please…', 'Two pair. Fill it in!'], + stand: ["I'll stand.", 'Good enough for me.'], + react: ['No way!', 'Lucky roll!', 'Show-off.', 'Oh, come on!'], + console: ['Ouch.', 'Tough break.'], + bonus: ['Bonus secured!', "That's the 35!"], +}; +const pick = (arr) => arr[Math.floor(Math.random() * arr.length)]; export default class YatziGame extends Phaser.Scene { constructor() { super('YatziGame'); } init(data) { + this.initData = data; this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; - - this.gs = null; - this.animating = false; - this.aiRunning = false; - this.gameOverShown = false; - - this.dieEls = []; // [{ frame: Graphics, face: Graphics, hit: Zone, currentFace }] - this.cellText = {}; // `${pi}-${cat}` → Text - this.cellHit = {}; // `${pi}-${cat}` → Zone - this.cellHoverGfx = null; // single hover highlight rect - this.columnHeaderText = []; // [Text per player] - this.activeColumnGfx = null; - this.summaryRefs = []; // [{ upperSub, upperBonus, lowerSub, yahtzBonus, grand }] - this.portraitCtrls = []; // [{ ring, controller }] - this.rollBtn = null; - this.rollsText = null; - this.statusText = null; - this.toastText = null; + this.ended = false; + this.busy = true; + this.modal = null; + this.undoSnap = null; + this.aiTimer = null; + this.shaking = false; + this.ticker = []; + this.bubbles = {}; + try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } } - async create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(DEPTH.bg); - this.buildPlayfield(); + get k() { return PACE[this.settings.pace] ?? 1; } + get aiFast() { return !!this.settings.skipAI; } - // Compose players: human first, then AI opponents - const playerNames = [ + create() { + new MusicPlayer(this, this.cache.json.get('music').tracks); + this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x1a0f08).setDepth(-2); + + const players = [ { name: auth.user?.username ?? 'You', isAI: false }, ...this.opponents.map((o) => ({ name: o.name ?? o.id ?? 'Bot', isAI: true, avatar: o })), ]; - this.gs = createInitialState({ playerNames }); + this.gs = L.createInitialState({ playerNames: players }); + this.n = players.length; + this.skill = players.map((p, i) => (i === HUMAN ? 5 : clampSkill(this.opponents[i - 1]?.skill ?? 3))); - this.buildLeftPanel(); - this.buildScorecard(); - this.buildDice(); - this.buildButtons(); - this.buildPortraits(); - this.buildHover(); - - new Button(this, 80, GAME_HEIGHT - 50, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 140, fontSize: 20, + prepareYatziArt(this, this.n).then((padOrigin) => { + if (!this.sys.isActive()) return; + this.padOrigin = padOrigin; + this.build(); + this.time.delayedCall(500, () => this.nextTurn()); }); - - this.renderAllDice(); - this.updateScorecard(); - this.updateActiveColumn(); - this.updateControls(); - - this.time.delayedCall(450, () => this.nextTurn()); } - // ─── Playfield background ────────────────────────────────────────────── - buildPlayfield() { + // ── build ─────────────────────────────────────────────────────────────────── + build() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT) - .setDepth(DEPTH.bg + 1); - } - } - - // ─── Left panel (title + status) ────────────────────────────────────── - buildLeftPanel() { - this.add.text(LEFT_CX, 56, 'Zahtzee', { - fontFamily: 'Righteous', fontSize: '60px', color: COLORS.textHex, - }).setOrigin(0.5); - - this.statusText = this.add.text(LEFT_CX, 130, '', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.accentHex, - }).setOrigin(0.5); - - this.rollsText = this.add.text(LEFT_CX, 740, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5); - - this.add.text(LEFT_CX, 800, 'Click a die to hold it between rolls.', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5); - } - - // ─── Scorecard ──────────────────────────────────────────────────────── - buildScorecard() { - const N = this.gs.players.length; - const colW = SC_PLAYERS_W / N; - - // Background panel - const totalH = SC_HEADER_H - + UPPER.length * SC_ROW_H - + SC_SUMMARY_H * 2 - + LOWER.length * SC_ROW_H - + SC_SUMMARY_H * 2 - + SC_GRAND_H; - this.add.rectangle(SC_X + SC_W / 2, SC_TOP + totalH / 2, SC_W + 4, totalH + 4, COLORS.panel) - .setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.panel); - - const grid = this.add.graphics().setDepth(DEPTH.grid); - grid.lineStyle(1, COLORS.muted, 0.4); - - // Header row - let y = SC_TOP; - this.drawRowDivider(grid, y); - this.drawRowDivider(grid, y + SC_HEADER_H); - this.add.text(SC_X + 14, y + SC_HEADER_H / 2, 'Category', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.cellText); - - for (let p = 0; p < N; p++) { - const cx = SC_X + SC_CAT_W + colW * p + colW / 2; - const name = this.gs.players[p].name; - const trimmed = name.length > 10 ? name.slice(0, 9) + '…' : name; - const t = this.add.text(cx, y + SC_HEADER_H / 2, trimmed, { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.cellText); - this.columnHeaderText.push(t); - } - // Vertical lines - grid.beginPath(); - grid.moveTo(SC_X + SC_CAT_W, y); - grid.lineTo(SC_X + SC_CAT_W, y + totalH); - for (let p = 1; p < N; p++) { - const x = SC_X + SC_CAT_W + colW * p; - grid.moveTo(x, y); grid.lineTo(x, y + totalH); - } - grid.strokePath(); - - y += SC_HEADER_H; - - // ─── Upper section ────────────────────────────────────────────── - for (const cat of UPPER) { - this.buildCategoryRow(grid, y, cat, colW, false); - y += SC_ROW_H; - } - // Upper subtotal - this.buildSummaryRow(grid, y, 'Upper subtotal', 'upperSubtotal', colW); - y += SC_SUMMARY_H; - // Upper bonus - this.buildSummaryRow(grid, y, 'Bonus (≥63 → +35)', 'upperBonus', colW); - y += SC_SUMMARY_H; - - // ─── Lower section ────────────────────────────────────────────── - for (const cat of LOWER) { - this.buildCategoryRow(grid, y, cat, colW, true); - y += SC_ROW_H; - } - // Lower subtotal - this.buildSummaryRow(grid, y, 'Lower subtotal', 'lowerSubtotal', colW); - y += SC_SUMMARY_H; - // Yahtzee bonus - this.buildSummaryRow(grid, y, 'Zahtzee bonus', 'yahtzeeBonus', colW); - y += SC_SUMMARY_H; - // Grand total - this.drawRowDivider(grid, y); - this.drawRowDivider(grid, y + SC_GRAND_H); - this.add.text(SC_X + 14, y + SC_GRAND_H / 2, 'GRAND TOTAL', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.goldHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.cellText); - for (let p = 0; p < N; p++) { - const cx = SC_X + SC_CAT_W + colW * p + colW / 2; - const t = this.add.text(cx, y + SC_GRAND_H / 2, '0', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.cellText); - this.summaryRefs[p] = this.summaryRefs[p] ?? {}; - this.summaryRefs[p].grand = t; - } - - // Active column outline (drawn later, updated each turn) - this.activeColumnGfx = this.add.graphics().setDepth(DEPTH.hover); - - this._scLastY = y + SC_GRAND_H; - this._scColW = colW; - this._scN = N; - } - - drawRowDivider(grid, y) { - grid.beginPath(); - grid.moveTo(SC_X, y); - grid.lineTo(SC_X + SC_W, y); - grid.strokePath(); - } - - buildCategoryRow(grid, y, cat, colW, isLower) { - this.drawRowDivider(grid, y); - this.add.text(SC_X + 14, y + SC_ROW_H / 2, CATEGORY_LABELS[cat], { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.cellText); - - for (let p = 0; p < this.gs.players.length; p++) { - const cx = SC_X + SC_CAT_W + colW * p + colW / 2; - const cy = y + SC_ROW_H / 2; - const t = this.add.text(cx, cy, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.cellText); - this.cellText[`${p}-${cat}`] = t; - - // Hit zone for clicking - const cellX = SC_X + SC_CAT_W + colW * p; - const zone = this.add.zone(cellX, y, colW, SC_ROW_H).setOrigin(0, 0).setDepth(DEPTH.cellBg); - zone.setInteractive({ useHandCursor: true }); - zone.on('pointerover', () => this.onCellHover(p, cat, true)); - zone.on('pointerout', () => this.onCellHover(p, cat, false)); - zone.on('pointerdown', () => this.onCellClick(p, cat)); - this.cellHit[`${p}-${cat}`] = zone; - } - } - - buildSummaryRow(grid, y, label, key, colW) { - this.drawRowDivider(grid, y); - this.add.text(SC_X + 14, y + SC_SUMMARY_H / 2, label, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - fontStyle: 'italic', - }).setOrigin(0, 0.5).setDepth(DEPTH.cellText); - - for (let p = 0; p < this.gs.players.length; p++) { - const cx = SC_X + SC_CAT_W + colW * p + colW / 2; - const cy = y + SC_SUMMARY_H / 2; - const t = this.add.text(cx, cy, '0', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.cellText); - this.summaryRefs[p] = this.summaryRefs[p] ?? {}; - this.summaryRefs[p][key] = t; - } - } - - buildHover() { - this.cellHoverGfx = this.add.graphics().setDepth(DEPTH.hover); - } - - // ─── Dice ────────────────────────────────────────────────────────────── - buildDice() { - for (let i = 0; i < 5; i++) { - const x = DICE_LEFT + i * (DICE_SIZE + DICE_GAP) + DICE_SIZE / 2; - const y = DICE_Y; - const container = this.add.container(x, y).setDepth(DEPTH.dieBox); - const frame = this.add.graphics(); - const face = this.add.graphics(); - container.add([frame, face]); - const hit = this.add.zone(x, y, DICE_SIZE, DICE_SIZE).setOrigin(0.5).setDepth(DEPTH.dieHit); - hit.setInteractive({ useHandCursor: true }); - hit.on('pointerdown', () => this.onDieClick(i)); - this.dieEls.push({ frame, face, hit, container, cx: x, cy: y, currentFace: 1 }); - } - } - - renderAllDice() { - for (let i = 0; i < 5; i++) { - this.renderDieFace(i, this.gs.dice[i], this.gs.held[i]); - } - } - - renderDieFace(idx, face, held) { - const el = this.dieEls[idx]; - el.currentFace = face; - const half = DICE_SIZE / 2; - const r = 14; - - // Frame (drawn at container-local coords, center = 0,0) - el.frame.clear(); - const borderColor = held ? COLORS.accent : COLORS.muted; - const borderWidth = held ? 5 : 2; - el.frame.fillStyle(0xf2ead8, 1); - el.frame.fillRoundedRect(-half, -half, DICE_SIZE, DICE_SIZE, r); - el.frame.lineStyle(borderWidth, borderColor, 1); - el.frame.strokeRoundedRect(-half, -half, DICE_SIZE, DICE_SIZE, r); - - // Pips - el.face.clear(); - el.face.fillStyle(0x1a1208, 1); - const pipR = 9; - const off = DICE_SIZE * 0.28; - for (const [px, py] of PIP_POS[face]) { - el.face.fillCircle(px * off, py * off, pipR); - } - } - - onDieClick(idx) { - if (this.animating || this.aiRunning) return; - if (this.gs.players[this.gs.current].isAI) return; - if (this.gs.rollsRemaining === 3 || this.gs.rollsRemaining === 0) return; - this.gs = toggleHold(this.gs, idx); - this.renderDieFace(idx, this.gs.dice[idx], this.gs.held[idx]); - } - - // ─── Buttons ─────────────────────────────────────────────────────────── - buildButtons() { - this.rollBtn = new Button(this, LEFT_CX, 660, 'Roll', () => this.onRollClick(), { width: 240, fontSize: 28 }); - } - - onRollClick() { - if (this.animating || this.aiRunning) return; - if (this.gs.players[this.gs.current].isAI) return; - if (this.gs.rollsRemaining <= 0) return; - this.doRoll(); - } - - async doRoll() { - const next = rollDice(this.gs); - await this.animateRoll(next.dice); - this.gs = next; - this.renderAllDice(); - this.updateScorecard(); - this.updateControls(); - } - - async animateRoll(targetDice) { - playSound(this, SFX.DICE_ROLL); - this.animating = true; - - const promises = []; - for (let i = 0; i < 5; i++) { - if (this.gs.held[i]) continue; - - const el = this.dieEls[i]; - const finalX = el.cx; - const finalY = el.cy; - - const startX = finalX + Phaser.Math.Between(-120, 120); - const startY = 1280; - const landX = finalX + Phaser.Math.Between(-14, 14); - const landY = finalY + Phaser.Math.Between(-14, 14); - const P1x = (startX + landX) / 2 + Phaser.Math.Between(-80, 80); - const P1y = landY - Phaser.Math.Between(380, 520); - - const startRot = Phaser.Math.FloatBetween(-Math.PI * 3, Math.PI * 3); - const endRot = Phaser.Math.FloatBetween(-0.12, 0.12); - - el.container.x = startX; - el.container.y = startY; - el.container.rotation = startRot; - - const progress = { t: 0 }; - const p = new Promise((resolve) => { - this.tweens.add({ - targets: progress, - t: 1, - duration: 700, - delay: i * 70, - ease: 'Cubic.Out', - onUpdate: () => { - const t = progress.t; - const u = 1 - t; - el.container.x = u * u * startX + 2 * u * t * P1x + t * t * landX; - el.container.y = u * u * startY + 2 * u * t * P1y + t * t * landY; - el.container.rotation = startRot + (endRot - startRot) * t; - this.renderDieFace(i, Math.ceil(Math.random() * 6), false); - }, - onComplete: () => { - el.container.x = landX; - el.container.y = landY; - el.container.rotation = endRot; - this.renderDieFace(i, targetDice[i], false); - this.tweens.add({ - targets: el.container, - scaleX: { from: 1.12, to: 1 }, - scaleY: { from: 1.12, to: 1 }, - duration: 110, - ease: 'Quad.Out', - onComplete: resolve, - }); - }, - }); - }); - promises.push(p); - } - - await Promise.all(promises); - this.animating = false; - } - - // ─── Portraits ───────────────────────────────────────────────────────── - buildPortraits() { - const y0 = PORTRAIT_TOP; - // Player (human) - const ring0 = this.add.graphics().setDepth(DEPTH.ui); - const ctrl0 = createPlayerPortrait(this, PORTRAIT_X, y0, PORTRAIT_R, DEPTH.ui, 'YatziGame'); - this.portraitCtrls.push({ ring: ring0, controller: ctrl0, x: PORTRAIT_X, y: y0 }); - this.add.text(PORTRAIT_X, y0 + PORTRAIT_R + 18, this.gs.players[0].name, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5); - - for (let i = 1; i < this.gs.players.length; i++) { - const py = y0 + i * PORTRAIT_GAP; - const ring = this.add.graphics().setDepth(DEPTH.ui); - const opp = this.opponents[i - 1] ?? { id: 'bot', spriteIndex: 0 }; - const ctrl = createOpponentPortrait(this, opp, PORTRAIT_X, py, PORTRAIT_R, DEPTH.ui); - this.portraitCtrls.push({ ring, controller: ctrl, x: PORTRAIT_X, y: py }); - this.add.text(PORTRAIT_X, py + PORTRAIT_R + 18, this.gs.players[i].name, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5); - } - } - - updateActivePortraitRing() { - for (let i = 0; i < this.portraitCtrls.length; i++) { - const { ring, x, y } = this.portraitCtrls[i]; - ring.clear(); - if (i === this.gs.current) { - ring.lineStyle(4, COLORS.gold, 1); - ring.strokeCircle(x, y, PORTRAIT_R + 6); - } - } - } - - // ─── Active column outline ───────────────────────────────────────────── - updateActiveColumn() { - const g = this.activeColumnGfx; - g.clear(); - const colW = this._scColW; - const N = this._scN; - if (this.gs.current >= N) return; - const x = SC_X + SC_CAT_W + colW * this.gs.current; - const y = SC_TOP; - const h = this._scLastY - SC_TOP; - g.lineStyle(4, COLORS.accent, 1); - g.strokeRect(x + 1, y + 1, colW - 2, h - 2); - - // Header color emphasis - for (let p = 0; p < N; p++) { - this.columnHeaderText[p].setColor(p === this.gs.current ? COLORS.accentHex : COLORS.textHex); - } - } - - // ─── Cell hover preview / committed score render ─────────────────────── - updateScorecard() { - const N = this.gs.players.length; - for (let p = 0; p < N; p++) { - const player = this.gs.players[p]; - for (const cat of CATEGORIES) { - const t = this.cellText[`${p}-${cat}`]; - const v = player.scorecard[cat]; - if (v !== null) { - t.setText(String(v)); - t.setColor(COLORS.textHex); - t.setAlpha(1); - } else if (p === this.gs.current && !player.isAI && this.gs.rollsRemaining < 3) { - // Preview score for the human, after the first roll - const legal = legalCategories(this.gs.dice, player.scorecard); - if (legal.includes(cat)) { - const preview = scoreForCommit(this.gs.dice, cat, player.scorecard) ?? 0; - t.setText(String(preview)); - t.setColor(preview > 0 ? COLORS.accentHex : COLORS.mutedHex); - t.setAlpha(0.65); - } else { - t.setText(''); - } - } else { - t.setText(''); - } - } - // Summary rows - const totals = computeTotals(player); - this.summaryRefs[p].upperSubtotal.setText(String(totals.upperSubtotal)); - this.summaryRefs[p].upperBonus.setText(String(totals.upperBonus)); - this.summaryRefs[p].lowerSubtotal.setText(String(totals.lowerSubtotal)); - this.summaryRefs[p].yahtzeeBonus.setText(String(totals.yahtzeeBonus)); - this.summaryRefs[p].grand.setText(String(totals.grand)); - } - } - - onCellHover(p, cat, entering) { - const g = this.cellHoverGfx; - g.clear(); - if (!entering) return; - if (this.animating || this.aiRunning) return; - const cur = this.gs.players[this.gs.current]; - if (p !== this.gs.current || cur.isAI) return; - if (this.gs.rollsRemaining === 3) return; - if (cur.scorecard[cat] !== null) return; - const legal = legalCategories(this.gs.dice, cur.scorecard); - if (!legal.includes(cat)) return; - - const zone = this.cellHit[`${p}-${cat}`]; - g.lineStyle(2, COLORS.gold, 1); - g.strokeRect(zone.x + 2, zone.y + 2, zone.width - 4, zone.height - 4); - } - - onCellClick(p, cat) { - if (this.animating || this.aiRunning) return; - if (this.gameOverShown) return; - const cur = this.gs.players[this.gs.current]; - if (p !== this.gs.current || cur.isAI) return; - if (this.gs.rollsRemaining === 3) return; - if (cur.scorecard[cat] !== null) return; - const legal = legalCategories(this.gs.dice, cur.scorecard); - if (!legal.includes(cat)) return; - - this.commitCategory(cat); - } - - commitCategory(cat) { - const before = this.gs; - const after = commitScore(before, cat); - if (after === before) return; - playSound(this, SFX.PENCIL_WRITE); - this.gs = after; - if (after.lastBonusGained) this.showBonusToast(); - this.cellHoverGfx?.clear(); - this.renderAllDice(); - this.updateScorecard(); - this.updateActiveColumn(); - this.updateControls(); - - if (this.gs.phase === 'gameover') { - this.showGameOverModal(); + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg); + this.add.image(0, 0, 'yatzi-vignette').setOrigin(0).setDepth(D.bg + 1); } else { - this.time.delayedCall(350, () => this.nextTurn()); + this.add.image(0, 0, 'yatzi-room').setOrigin(0).setDepth(D.bg); + } + + this.buildSeats(); + this.tray = new YatziTray(this, D.tray, { + onDieClick: (i) => this.onDieClick(i), + onDieHover: (i, on) => this.onDieHover(i, on), + }).build(); + this.cup = new YatziCup(this, D.cup, { onPress: () => this.beginShake() }).build(); + this.pad = new YatziPad(this, { + players: this.gs.players, depth: D.pad, origin: this.padOrigin, + onCell: (cat) => this.onCellClick(cat), onHover: (cat) => this.onCellHover(cat), + }).build(); + for (let p = 0; p < this.n; p++) this.pad.refreshTotals(p, this.gs.players[p]); + this.buildHud(); + + this.hand = this.add.image(0, 0, 'yatzi-hand').setDepth(D.hand).setAlpha(0).setOrigin(0.5, 0.2); + + this.tray.setDim(true); + this.tray.layout(this.gs.dice, this.gs.held); + this.input.on('pointerup', () => this.releaseShake()); + this.input.keyboard?.on('keydown', (e) => this.onKey(e, true)); + this.input.keyboard?.on('keyup', (e) => this.onKey(e, false)); + this.events.once('shutdown', () => { this.ended = true; this.cup?.stopShake(); }); + this.refreshHud(); + } + + buildSeats() { + const nOpp = this.n - 1; + this.seats = []; + this.portraits = []; + // the human sits at the near edge + this.humanRing = this.add.graphics().setDepth(D.hud); + this.portraits[HUMAN] = createPlayerPortrait(this, HUMAN_PORTRAIT.x, HUMAN_PORTRAIT.y, HUMAN_PORTRAIT.r, D.hud + 1, 'YatziGame'); + this.add.text(HUMAN_NAME.x, HUMAN_NAME.y, this.gs.players[HUMAN].name, { + fontFamily: HAND_FONT, fontSize: '24px', color: '#f3e6c4', + }).setOrigin(0.5).setDepth(D.hud); + + for (let k = 0; k < nOpp; k++) { + const p = k + 1; + const s = seatParts(k, nOpp); + this.add.image(s.rect.x - 16, s.rect.y - 16, 'yatzi-seat').setOrigin(0).setDepth(D.seat); + const ring = this.add.graphics().setDepth(D.seat + 1); + const opp = this.opponents[k] ?? { id: 'bot', spriteIndex: 0 }; + this.portraits[p] = createOpponentPortrait(this, opp, s.portrait.x, s.portrait.y, s.portrait.r, D.seat + 2); + const name = this.gs.players[p].name; + this.add.text(s.name.x, s.name.y, name.length > 12 ? name.slice(0, 11) + '…' : name, { + fontFamily: DISPLAY_FONT, fontSize: '24px', color: '#f3e6c4', + }).setOrigin(0, 0.5).setDepth(D.seat + 1); + const score = this.add.text(s.name.x, s.score.y, '0 pts', { + fontFamily: HAND_FONT, fontSize: '26px', color: Phaser.Display.Color.IntegerToColor(SEAT_TINT[p]).rgba, + }).setOrigin(0, 0.5).setDepth(D.seat + 1); + const sk = this.skill[p]; + this.add.text(s.rect.x + s.rect.w - 16, s.score.y, '●'.repeat(sk) + '○'.repeat(5 - sk), { + fontFamily: SERIF, fontSize: '13px', color: '#d6aa60', + }).setOrigin(1, 0.5).setDepth(D.seat + 1); + this.seats[p] = { ...s, ring, score }; } } - showBonusToast() { - if (this.toastText) this.toastText.destroy(); - this.toastText = this.add.text(LEFT_CX, 380, '+100 Zahtzee Bonus!', { - fontFamily: 'Righteous', fontSize: '32px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.toast); - this.tweens.add({ - targets: this.toastText, alpha: { from: 1, to: 0 }, y: 340, duration: 1600, - onComplete: () => { this.toastText?.destroy(); this.toastText = null; }, - }); + buildHud() { + this.pipsG = this.add.graphics().setDepth(D.hud); + this.add.text(PIPS_LABEL.x, PIPS_LABEL.y, 'ROLLS LEFT', { + fontFamily: PRINT_FONT, fontSize: '13px', color: '#d9c49a', + }).setOrigin(0.5).setDepth(D.hud); + this.statusText = this.add.text(STATUS.x, STATUS.y, '', { + fontFamily: DISPLAY_FONT, fontSize: '28px', color: '#f3e6c4', + }).setOrigin(0.5).setDepth(D.hud); + this.subText = this.add.text(SUBLINE.x, SUBLINE.y, '', { + fontFamily: SERIF, fontSize: '18px', color: '#e8d3a6', align: 'center', wordWrap: { width: STATUS.w }, + }).setOrigin(0.5).setDepth(D.hud); + this.tickerText = this.add.text(TICKER.x, TICKER.y, '', { + fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#bfa98a', align: 'center', + }).setOrigin(0.5).setDepth(D.hud); + this.meterText = this.add.text(METER.x, METER.y, '', { + fontFamily: PRINT_FONT, fontSize: '15px', color: '#d9c49a', + }).setOrigin(0.5).setDepth(D.hud); + this.undoBtn = new Button(this, UNDO_BTN.x, UNDO_BTN.y, 'Undo (Z)', () => this.undo(), { + width: BTN.w, height: BTN.h, fontSize: 17, bg: 0x6a4a1a, + }).setDepth(D.hud).setVisible(false); + this.menuBtn = new Button(this, MENU_BTN.x, MENU_BTN.y, 'Menu', () => this.openMenu(), { + width: BTN.w, height: BTN.h, fontSize: 17, bg: 0x3a2412, + }).setDepth(D.hud); } - // ─── Turn flow ───────────────────────────────────────────────────────── + // ── HUD refresh ───────────────────────────────────────────────────────────── + refreshHud() { + const gs = this.gs; + // roll pips + const g = this.pipsG; + g.clear(); + for (let i = 0; i < 3; i++) { + const x = PIPS.x + i * PIPS.gap, y = PIPS.y; + const filled = gs.phase !== 'gameover' && i < gs.rollsRemaining; + g.fillStyle(0x000000, 0.4).fillCircle(x + 1, y + 2, PIPS.r); + g.fillStyle(filled ? 0xf4ecd8 : 0x3a2a1a, 1).fillCircle(x, y, PIPS.r); + g.lineStyle(2, filled ? 0xd6aa60 : 0x6a5236, 1).strokeCircle(x, y, PIPS.r); + if (filled) { g.fillStyle(0x15151c, 1).fillCircle(x, y, 3.5); } + } + // seat rings + scores + for (let p = 1; p < this.n; p++) { + const s = this.seats[p]; + s.ring.clear(); + if (p === gs.current && gs.phase !== 'gameover') { + s.ring.lineStyle(4, 0xf5d020, 1).strokeRoundedRect(s.rect.x - 3, s.rect.y - 3, s.rect.w + 6, s.rect.h + 6, 20); + s.ring.lineStyle(4, 0xf5d020, 1).strokeCircle(s.portrait.x, s.portrait.y, s.portrait.r + 6); + } + s.score.setText(`${L.computeTotals(gs.players[p]).grand} pts`); + } + this.humanRing.clear(); + if (gs.current === HUMAN && gs.phase !== 'gameover') { + this.humanRing.lineStyle(4, 0xf5d020, 1).strokeCircle(HUMAN_PORTRAIT.x, HUMAN_PORTRAIT.y, HUMAN_PORTRAIT.r + 6); + } + this.pad.setActive(gs.phase === 'gameover' ? null : gs.current); + this.pad.setRound(L.roundOf(gs), L.TURNS); + // upper-bonus meter (yours) + const par = L.upperPar(gs.players[HUMAN]); + let m; + if (par.earned) m = 'Upper bonus earned ✓ +35'; + else if (!par.alive) m = 'Upper bonus is out of reach this game'; + else if (par.sub === 0 && !L.UPPER.some((c) => gs.players[HUMAN].scorecard[c] !== null)) m = 'Upper bonus: 63 needed (three of each face is par)'; + else m = `Upper bonus: ${par.sub} / 63 · ${par.par >= 0 ? '+' : '−'}${Math.abs(par.par)} vs par · need ${par.need}`; + this.meterText.setText(m).setColor(par.earned ? '#9fdc9f' : par.alive ? '#d9c49a' : '#d08a7a'); + this.tickerText.setText(this.ticker.slice(-2).join('\n')); + this.undoBtn.setVisible(!!(this.undoSnap && this.settings.undo && this.aiTimer)); + } + + setStatus(main, sub = '') { + this.statusText.setText(main); + this.subText.setText(sub); + } + + // ── turn flow ─────────────────────────────────────────────────────────────── nextTurn() { - if (this.gs.phase === 'gameover') { - this.showGameOverModal(); + if (this.ended) return; + if (this.gs.phase === 'gameover') { this.finishGame(); return; } + this.tray.setDim(true); + this.refreshHud(); + if (this.gs.players[this.gs.current].isAI) this.aiTurn(); + else this.humanTurnStart(); + } + + humanTurnStart() { + this.busy = false; + this.pad.setEnabled(false); + this.tray.setEnabled(false); + this.cup.setEnabled(true); + this.setStatus('Your turn', 'Shake the cup: press and hold it (or Space), then let go to throw.'); + this.refreshHud(); + } + + canRoll() { + return !this.ended && !this.busy && !this.modal && !this.shaking + && this.gs.current === HUMAN && this.gs.rollsRemaining > 0 && this.gs.phase !== 'gameover' + && !this.gs.held.every(Boolean); + } + + beginShake() { + if (!this.canRoll()) return; + this.shaking = true; + this.busy = true; + this.cup.setEnabled(false); + this.tray.setEnabled(false); + this.pad.setEnabled(false); + this.pad.clearPreviews(); + this.tray.setGlowAll(0); + this.setStatus('Shaking…', 'Let go to throw.'); + const idx = [0, 1, 2, 3, 4].filter((i) => !this.gs.held[i]); + this.scooping = this.tray.scoop(idx, CUP_MOUTH, 220); + this.cup.startShake(); + } + + async releaseShake() { + if (!this.shaking) return; + this.shaking = false; + const minShake = 320; + const extra = Math.max(0, minShake - this.cup.shakeTime()); + await Promise.all([this.scooping, this.wait(extra)]); + if (this.ended) return; + await this.cup.pour(); + await this.doThrow(humanOrigin(), { fast: false, speed: 1 }); + if (this.ended) return; + this.afterRoll(HUMAN); + this.humanDecide(); + } + + // RNG first: roll in the engine, then animate the dice onto those faces. + async doThrow(origin, { fast, speed }) { + const before = this.gs; + let next = L.rollDice(before, Math.random); + if (this.settings.sort) next = L.sortUnheld(next); + const idx = [0, 1, 2, 3, 4].filter((i) => !before.held[i]); + this.tray.setDim(false); + await this.tray.throwDice(idx, idx.map((i) => next.dice[i]), origin, { fast, speed }); + this.gs = next; + this.refreshHud(); + } + + // Flourishes and table talk after any roll. + afterRoll(p) { + const dice = this.gs.dice; + const sc = this.gs.players[p].scorecard; + if (L.isYahtzee(dice)) { + this.celebrateZahtzee(p); + if (p !== HUMAN) { this.say(p, pick(SPEECH.zahtzee)); this.portraits[p]?.playEmotion?.('happy'); } + else this.reactOthers(SPEECH.react, 0.9, 'upset'); + } else if (L.isLargeStraight(dice) && sc.largeStraight === null) { + this.flourish('Large Straight!', 0x6fc3ff); + this.tray.hop([0, 1, 2, 3, 4], 22, 320); + if (p === HUMAN) this.reactOthers(SPEECH.react, 0.35); + } else if (L.isFullHouse(dice) && sc.fullHouse === null) { + this.flourish('Full House!', 0xffb86b); + } else if (L.isSmallStraight(dice) && sc.smallStraight === null && this.gs.rollsRemaining === 0) { + this.flourish('Small Straight', 0x9fdc9f, 0.8); + } + } + + humanDecide() { + if (this.ended) return; + this.busy = false; + const gs = this.gs; + const pl = gs.players[HUMAN]; + const legal = L.legalCategories(gs.dice, pl.scorecard); + this.pad.setEnabled(true); + this.pad.setClickable(legal); + this.tray.setEnabled(gs.rollsRemaining > 0); + this.cup.setEnabled(this.canRoll()); + this.refreshDecideHints(); + } + + refreshDecideHints() { + const gs = this.gs; + if (gs.current !== HUMAN || gs.phase === 'preroll' || gs.phase === 'gameover') return; + const pl = gs.players[HUMAN]; + const legal = L.legalCategories(gs.dice, pl.scorecard); + const best = bestCategory(gs.dice, pl.scorecard, 'expert'); + if (this.settings.hints) { + const map = {}; + for (const c of legal) map[c] = L.scoreForCommit(gs.dice, c, pl.scorecard); + this.pad.showPreviews(map, best); + } else this.pad.clearPreviews(); + this.bestCat = this.settings.hints ? best : null; + + // status, Joker notice, coach + const mode = L.jokerMode(gs.dice, pl.scorecard); + const bonus = L.jokerStatus(gs.dice, pl.scorecard).bonus; + let main = gs.rollsRemaining > 0 ? 'Keep dice or roll again' : 'Pick a box to score'; + let sub = gs.rollsRemaining > 0 + ? 'Click dice (or 1–5) to keep them on the ledge, then shake again. Or score now.' + : 'Click a box in your column of the score pad.'; + if (gs.rollsRemaining > 0 && gs.held.every(Boolean)) sub = 'All five are kept. Release one to roll again, or score now.'; + if (mode) { + main = bonus ? 'Joker! +100 bonus' : 'Joker!'; + sub = mode === 'upper' ? `Your ${L.FACE_WORDS[gs.dice[0]]} box is open, so the Joker must go there.` + : mode === 'lower' ? 'Any open lower box scores in full: Full House 25, straights 30 / 40.' + : 'Your lower section is full, so the Joker scratches an open upper box.'; + } + this.tray.setGlowAll(0); + if (this.settings.coach && gs.rollsRemaining > 0 && !mode) { + const adv = expertAdvice(gs.dice, gs.held, pl.scorecard, gs.rollsRemaining); + adv.mask.forEach((k, i) => { if (k) this.tray.setGlow(i, 0.9, 0x7fd6ff); }); + const keep = adv.stop ? 'stand pat and score' : adv.keep.length ? `keep ${adv.keep.join('·')}` : 'roll all five'; + const odds = adv.odds.filter((o) => o.p >= 0.005).slice(0, 2).map((o) => `${o.label} ${Math.round(o.p * 100)}%`).join(' · '); + sub = `Coach: ${keep}${odds ? ` · if you chase: ${odds}` : ''}`; + } else if (this.settings.coach && best) { + sub = `Coach: ${L.CATEGORY_LABELS[best]} is the best box for this roll.`; + } + this.setStatus(main, sub); + } + + onDieClick(i) { + if (this.busy || this.ended || this.modal || this.gs.current !== HUMAN || !L.canHold(this.gs)) return; + this.gs = L.toggleHold(this.gs, i); + this.tray.moveTo(i, this.gs.held[i] ? 'ledge' : 'tray', 220); + this.onDieHover(i, false); + this.cup.setEnabled(this.canRoll()); + this.refreshDecideHints(); + } + + onDieHover(i, on) { + if (on && this.settings.coach) return; + if (!this.tray) return; + if (on) this.tray.setGlow(i, 0.7, 0xffffff); + else if (!this.settings.coach) this.tray.setGlow(i, 0); + } + + onCellHover(cat) { + if (this.busy) { this.pad.hover(null); return; } + this.pad.restorePreviewScale(); + this.pad.hover(cat); + } + + onCellClick(cat) { + if (this.busy || this.ended || this.modal || this.gs.current !== HUMAN) return; + const pl = this.gs.players[HUMAN]; + const v = L.scoreForCommit(this.gs.dice, cat, pl.scorecard); + if (v === null) return; + if (v === 0 && this.settings.confirmScratch && VALUABLE.includes(cat) && pl.scorecard[cat] === null) { + this.confirmThen(`Scratch ${L.CATEGORY_LABELS[cat]}?`, `This puts a zero in ${L.CATEGORY_LABELS[cat]} for the rest of the game.`, () => this.commitHuman(cat)); return; } - this.updateActiveColumn(); - this.updateActivePortraitRing(); - this.renderAllDice(); - this.updateScorecard(); - this.updateControls(); + this.commitHuman(cat); + } - const cur = this.gs.players[this.gs.current]; - if (cur.isAI) { - this.runAITurn(); + commitHuman(cat) { + this.undoSnap = this.settings.undo ? { gs: this.gs, ticker: this.ticker.slice() } : null; + this.commit(cat); + } + + async commit(cat) { + const p = this.gs.current; + this.busy = true; + this.pad.setEnabled(false); + this.tray.setEnabled(false); + this.cup.setEnabled(false); + this.pad.clearPreviews(); + this.tray.setGlowAll(0); + const before = this.gs; + const after = L.commitScore(before, cat); + if (after === before) { this.busy = false; return; } + this.gs = after; + const lc = after.lastCommit; + const name = after.players[p].name; + const label = L.CATEGORY_LABELS[cat]; + this.ticker.push(lc.value === 0 ? `${name} scratched ${label}` : `${name}: ${lc.value} in ${label}${lc.bonus ? ' · +100 bonus!' : ''}`); + const speed = p !== HUMAN && this.aiFast ? 0.4 : 1; + await this.pad.write(p, cat, lc.value, { speed }); + if (this.ended) return; + if (lc.bonus) await this.flyBonusChip(p); + this.pad.refreshTotals(p, after.players[p], { animate: true }); + this.refreshHud(); + // reactions + if (p !== HUMAN) { + if (lc.value === 0 && Math.random() < 0.7) { + this.say(p, pick(SPEECH.scratch).replace('{cat}', label)); + this.portraits[p]?.playEmotion?.('upset'); + } else if (lc.upperBonusEarned) { + this.say(p, pick(SPEECH.bonus)); + } else if (lc.value >= 30 && !L.isYahtzee(lc.dice) && Math.random() < 0.5) { + this.say(p, pick(SPEECH.big)); + this.portraits[p]?.playEmotion?.('happy'); + } + } else if (lc.value === 0 && VALUABLE.includes(cat)) { + this.reactOthers(SPEECH.console, 0.5); + } + if (lc.upperBonusEarned && p === HUMAN) this.flourish('Upper bonus! +35', 0x9fdc9f, 0.9); + await this.wait(p === HUMAN ? 200 : 380 * this.k * (this.aiFast ? 0.3 : 1)); + if (this.ended) return; + if (this.gs.phase === 'gameover') { this.undoSnap = null; this.finishGame(); return; } + this.nextTurn(); + } + + undoWindow() { return Math.round(1500 * this.k); } + + undo() { + if (!this.undoSnap || !this.settings.undo || !this.aiTimer || this.modal) return; + this.aiTimer.remove(); + this.aiTimer = null; + const snap = this.undoSnap; + this.undoSnap = null; + this.gs = snap.gs; + this.ticker = snap.ticker; + this.pad.syncFromState(this.gs); + this.tray.setDim(false); + this.tray.layout(this.gs.dice, this.gs.held); + playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.5, rate: 0.7 }); + this.refreshHud(); + this.humanDecide(); + } + + // ── opponents ─────────────────────────────────────────────────────────────── + aiTurn() { + const p = this.gs.current; + this.busy = true; + this.cup.setEnabled(false); + this.tray.setEnabled(false); + this.pad.setEnabled(false); + const t = aiTiming(this.skill[p], this.k); + this.setStatus(`${this.gs.players[p].name}'s turn`, `${this.gs.players[p].name} picks up the cup…`); + const delay = this.undoSnap ? Math.max(t.think, this.undoWindow()) : t.think * (this.aiFast ? 0.4 : 1); + this.aiTimer = this.time.delayedCall(delay, () => { + this.aiTimer = null; + this.undoSnap = null; + this.refreshHud(); + this.runAI(p, t).catch((e) => console.error('Zahtzee AI turn failed', e)); + }); + this.refreshHud(); + } + + async runAI(p, t) { + const f = this.aiFast ? 0.25 : 1; + const pl = () => this.gs.players[p]; + const plan = planTurn(pl().scorecard, pl().yahtzeeBonusCount, this.skill[p], Math.random); + await this.aiRoll(p); + if (this.ended) return; + while (this.gs.rollsRemaining > 0) { + await this.wait(t.think * f); + if (this.ended) return; + const mask = plan.chooseHold(this.gs.dice, this.gs.held, this.gs.rollsRemaining); + if (plan.shouldStop(mask)) { + if (Math.random() < 0.4) this.say(p, pick(SPEECH.stand)); + break; + } + await this.aiApplyHolds(p, mask, t, f); + if (this.ended) return; + const what = describeKeep(this.gs.dice, mask); + if (Math.random() < 0.35) { + if (what.kind === 'set') this.say(p, pick(SPEECH.set).replace('{face}', L.FACE_WORDS[what.face].toLowerCase())); + else if (what.kind === 'straight') this.say(p, pick(SPEECH.straight)); + else if (what.kind === 'house') this.say(p, pick(SPEECH.house)); + } + this.setStatus(`${pl().name}'s turn`, `${pl().name} keeps ${this.gs.dice.filter((_, i) => this.gs.held[i]).join('·') || 'nothing'} and shakes again…`); + await this.wait(t.between * f); + await this.aiRoll(p); + if (this.ended) return; + } + await this.wait((t.think + t.hesitate) * f); + if (this.ended) return; + const cat = plan.chooseCategory(this.gs.dice); + this.pad.flashCell(p, cat, SEAT_TINT[p]); + this.setStatus(`${pl().name}'s turn`, `${pl().name} writes in ${L.CATEGORY_LABELS[cat]}.`); + await this.wait(380 * f * this.k); + if (this.ended) return; + await this.commit(cat); + } + + async aiRoll(p) { + const seat = this.seats[p]; + const idx = [0, 1, 2, 3, 4].filter((i) => !this.gs.held[i]); + const fast = this.aiFast; + if (!fast) { + await this.tray.scoop(idx, { x: seat.portrait.x, y: seat.portrait.y + 120 }, 240 * this.k); + // a short rattle from their seat + for (let i = 0; i < 4; i++) { + playSoundEx(this, SFX.PIECE_CLICK, { volume: 0.12 + Math.random() * 0.1, rate: 1.4 + Math.random() * 0.8 }); + await this.wait(80); + } + } + if (this.ended) return; + await this.doThrow(seatOrigin(seat.portrait.x), { fast, speed: 1 }); + if (this.ended) return; + this.afterRoll(p); + } + + // Move the AI's keepers with a ghost hand from their seat. + async aiApplyHolds(p, mask, t, f) { + const changes = [0, 1, 2, 3, 4].filter((i) => !!mask[i] !== !!this.gs.held[i]); + if (!changes.length) return; + const seat = this.seats[p]; + const fast = this.aiFast; + if (!fast) { + this.hand.setTint(SEAT_TINT[p]).setPosition(seat.portrait.x, seat.portrait.y + 60).setAlpha(0).setScale(1); + this.tweens.add({ targets: this.hand, alpha: 0.8, duration: 120 }); + } + for (const i of changes) { + const c = this.tray.screenOf(i); + if (!fast) await this.tweenTo(this.hand, { x: c.x + 10, y: c.y - 6 }, t.reach * f + 90); + if (this.ended) return; + this.gs = L.toggleHold(this.gs, i); + const spot = this.gs.held[i] ? 'ledge' : 'tray'; + if (!fast) { + const rest = this.tray.restFor(i, spot); + const to = ground(rest.u, rest.v); + const move = this.tray.moveTo(i, spot, t.carry * f + 120); + // the hand rides along with the die + this.tweenTo(this.hand, { x: to.x + 10, y: to.y - 40 }, t.carry * f + 120); + await move; + } else { + await this.tray.moveTo(i, spot, 0); + } + } + if (!fast) { + await this.tweenTo(this.hand, { x: seat.portrait.x, y: seat.portrait.y + 60, alpha: 0 }, 260); } } - async runAITurn() { - this.aiRunning = true; - this.updateControls(); - await this.delay(500); + // ── flourishes ────────────────────────────────────────────────────────────── + celebrateZahtzee(p) { + playSound(this, SFX.VICTORY_SHORT); + this.tray.setGlowAll(1, 0xf5d020); + this.tray.hop([0, 1, 2, 3, 4], 60, 460).then(() => { if (!this.ended && !(this.settings.coach && p === HUMAN)) this.tray.setGlowAll(0); }); + this.banner('ZAHTZEE!', 0xf5d020, 1.25); + this.confetti(); + this.cameras.main.shake(220, 0.004); + } - let keepRolling = true; - while (keepRolling && this.gs.rollsRemaining > 0) { - await this.doRoll(); - if (this.gs.rollsRemaining === 0) break; - await this.delay(450); - const mask = chooseDiceToHold( - this.gs.dice, - this.gs.players[this.gs.current].scorecard, - this.gs.rollsRemaining, - ); - // Apply hold mask visibly - for (let i = 0; i < 5; i++) { - if (mask[i] !== this.gs.held[i]) { - this.gs.held[i] = mask[i]; - this.renderDieFace(i, this.gs.dice[i], this.gs.held[i]); - } - } - await this.delay(500); - keepRolling = shouldKeepRolling(mask, this.gs.rollsRemaining); - } - - await this.delay(500); - const cat = chooseCategory( - this.gs.dice, - this.gs.players[this.gs.current].scorecard, - ); - if (cat) { - this.flashCell(this.gs.current, cat); - await this.delay(500); - const aiIdx = this.gs.current; - const scored = scoreForCommit(this.gs.dice, cat, this.gs.players[aiIdx].scorecard) ?? 0; - this.aiRunning = false; - this.commitCategory(cat); - const ctrl = this.portraitCtrls[aiIdx]?.controller; - if (ctrl?.playEmotion) { - if (scored > 30) ctrl.playEmotion('happy'); - else if (scored < 10) ctrl.playEmotion('upset'); - } - } else { - this.aiRunning = false; + flourish(text, color, scale = 1) { + this.banner(text, color, 0.75 * scale, true); + for (let i = 0; i < 12; i++) { + const s = this.add.image(BANNER.x + Phaser.Math.Between(-220, 220), BANNER.y + Phaser.Math.Between(-30, 30), 'yatzi-spark') + .setDepth(D.fx).setTint(color).setBlendMode(Phaser.BlendModes.ADD).setScale(0.5 + Math.random()); + this.tweens.add({ targets: s, y: s.y - 60 - Math.random() * 60, alpha: 0, scale: 0.2, duration: 700 + Math.random() * 400, onComplete: () => s.destroy() }); } } - flashCell(p, cat) { - const zone = this.cellHit[`${p}-${cat}`]; - if (!zone) return; - const flash = this.add.graphics().setDepth(DEPTH.hover); - flash.fillStyle(COLORS.accent, 0.4); - flash.fillRect(zone.x + 2, zone.y + 2, zone.width - 4, zone.height - 4); - this.tweens.add({ - targets: flash, alpha: { from: 0.6, to: 0 }, duration: 450, - onComplete: () => flash.destroy(), + banner(text, color, scale = 1, small = false) { + this.bannerObj?.destroy(); + const hex = Phaser.Display.Color.IntegerToColor(color).rgba; + const t = this.add.text(0, 0, text, { + fontFamily: DISPLAY_FONT, fontSize: small ? '54px' : '96px', color: hex, + stroke: '#2a1408', strokeThickness: small ? 8 : 12, + shadow: { offsetX: 0, offsetY: 6, color: '#000', blur: 14, fill: true }, + }).setOrigin(0.5); + const c = this.add.container(BANNER.x, BANNER.y - 120, [t]).setDepth(D.banner).setScale(scale * 0.4).setAlpha(0); + this.bannerObj = c; + this.tweens.add({ targets: c, y: BANNER.y, scale, alpha: 1, duration: 380, ease: 'Back.Out' }); + this.tweens.add({ targets: c, alpha: 0, y: BANNER.y - 40, delay: small ? 900 : 1500, duration: 420, onComplete: () => { c.destroy(); if (this.bannerObj === c) this.bannerObj = null; } }); + } + + confetti(count = 90) { + const colors = [0xf5d020, 0xd0533f, 0x4f86c6, 0x3f9d66, 0x9364c9, 0xffffff]; + for (let i = 0; i < count; i++) { + const x = TRAY.x + Math.random() * TRAY.w; + const r = this.add.rectangle(x, TRAY.y - 30 - Math.random() * 120, 8 + Math.random() * 6, 4 + Math.random() * 4, pick(colors)) + .setDepth(D.fx).setRotation(Math.random() * 6); + this.tweens.add({ + targets: r, y: TRAY.y + TRAY.h + 80 + Math.random() * 120, x: x + Phaser.Math.Between(-120, 120), + rotation: r.rotation + Phaser.Math.FloatBetween(-8, 8), duration: 1400 + Math.random() * 1200, ease: 'Sine.In', + onComplete: () => r.destroy(), + }); + } + } + + async flyBonusChip(p) { + const to = cellCenter(p, 'yahtzeeBonus', this.n); + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.35).fillCircle(2, 3, 26); + g.fillStyle(0xf5d020, 1).fillCircle(0, 0, 25); + g.lineStyle(3, 0x8a6a10, 1).strokeCircle(0, 0, 25); + const tx = this.add.text(0, 0, '+100', { fontFamily: DISPLAY_FONT, fontSize: '18px', color: '#3a2a08' }).setOrigin(0.5); + const chip = this.add.container(BANNER.x, BANNER.y + 60, [g, tx]).setDepth(D.fx).setScale(0); + playSound(this, SFX.COINS); + await this.tweenTo(chip, { scale: 1.2 }, 200); + await this.tweenTo(chip, { x: to.x, y: to.y, scale: 0.7 }, 520, 'Cubic.InOut'); + chip.destroy(); + } + + // ── speech ────────────────────────────────────────────────────────────────── + say(p, text, dur = 2200) { + if (p === HUMAN || !this.seats[p] || this.ended) return; + this.bubbles[p]?.destroy(); + const b = this.seats[p].bubble; + const t = this.add.text(b.x + 14, b.y + b.h / 2, text, { + fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#2b2418', wordWrap: { width: b.w - 26 }, + }).setOrigin(0, 0.5); + const w = Math.min(b.w, t.width + 28), h = Math.max(40, t.height + 18); + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + (b.h - h) / 2 + 4, w, h, 12); + g.fillStyle(0xfbf5e4, 1).fillRoundedRect(b.x, b.y + (b.h - h) / 2, w, h, 12); + g.lineStyle(2, SEAT_TINT[p], 1).strokeRoundedRect(b.x, b.y + (b.h - h) / 2, w, h, 12); + g.fillStyle(0xfbf5e4, 1).fillTriangle(b.x - 10, b.y + b.h / 2 - 2, b.x + 2, b.y + b.h / 2 - 10, b.x + 2, b.y + b.h / 2 + 6); + const c = this.add.container(0, 0, [g, t]).setDepth(D.seat + 4).setAlpha(0); + this.bubbles[p] = c; + this.tweens.add({ targets: c, alpha: 1, duration: 160 }); + this.tweens.add({ targets: c, alpha: 0, delay: dur, duration: 300, onComplete: () => { c.destroy(); if (this.bubbles[p] === c) delete this.bubbles[p]; } }); + } + + reactOthers(lines, chance = 0.5, emotion = null) { + if (Math.random() > chance || this.n < 2) return; + const p = 1 + Math.floor(Math.random() * (this.n - 1)); + this.time.delayedCall(450, () => { + this.say(p, pick(lines)); + if (emotion) this.portraits[p]?.playEmotion?.(emotion); }); } - // ─── Controls update ─────────────────────────────────────────────────── - updateControls() { - const cur = this.gs.players[this.gs.current]; - const isHuman = !cur.isAI; - const canRoll = isHuman && this.gs.rollsRemaining > 0 && !this.animating && !this.aiRunning && this.gs.phase !== 'gameover'; - this.rollBtn?.setEnabled(canRoll); - this.rollBtn?.setLabel(this.gs.rollsRemaining === 3 ? 'Roll' : 'Re-roll'); - this.rollsText?.setText(this.gs.phase === 'gameover' ? '' : `Rolls remaining: ${this.gs.rollsRemaining}`); - - if (this.gs.phase === 'gameover') { - this.statusText.setText('Game over'); - } else if (cur.isAI) { - this.statusText.setText(`${cur.name}'s turn`); - } else if (this.gs.rollsRemaining === 3) { - this.statusText.setText('Your turn — roll the dice'); - } else if (this.gs.rollsRemaining === 0) { - this.statusText.setText('Pick a category to score'); - } else { - this.statusText.setText('Hold dice or re-roll'); + // ── input ─────────────────────────────────────────────────────────────────── + onKey(e, down) { + if (this.ended) return; + const key = e.key; + if (key === ' ' || e.code === 'Space') { + e.preventDefault?.(); + if (down && !e.repeat) this.beginShake(); + else if (!down) this.releaseShake(); + return; } + if (!down || e.repeat) return; + if (key === 'Escape') { if (this.modal) this.closeModal(); else this.openMenu(); return; } + if (this.modal) return; + if (key >= '1' && key <= '5') { this.onDieClick(Number(key) - 1); return; } + if (key === 'Enter' && this.bestCat && !this.busy && this.gs.current === HUMAN && this.gs.phase !== 'preroll') { this.onCellClick(this.bestCat); return; } + if (key === 'z' || key === 'Z') this.undo(); } - // ─── Game over ───────────────────────────────────────────────────────── - showGameOverModal() { - if (this.gameOverShown) return; - this.gameOverShown = true; + // ── menu / modals ─────────────────────────────────────────────────────────── + hidePortraits() { this.portraits.forEach((c) => c?.setVideoVisible?.(false)); } + showPortraits() { this.portraits.forEach((c) => c?.setVideoVisible?.(true)); } - // Submit to server (silent on failure) + openMenu() { + if (this.modal || this.ended || this.shaking) return; + this.hidePortraits(); + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => new TutorialModal(this.gameDef).open(), + onNewGame: () => this.confirmThen('New game?', 'Abandon this game and start a fresh score pad?', () => this.scene.restart(this.initData)), + onLeave: () => this.confirmThen('Leave the table?', 'This game will be abandoned.', () => this.scene.start('GameMenu')), + onClose: () => { this.modal = null; this.showPortraits(); }, + }); + } + + confirmThen(heading, text, onYes) { + this.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, depth: D.modal + 5, + onYes: () => { this.modal = null; this.showPortraits(); onYes(); }, + onNo: () => { this.modal = null; this.showPortraits(); }, + }); + } + + closeModal() { this.modal?.close?.(); this.modal = null; this.showPortraits(); } + + changeSetting(key, value) { + this.settings[key] = value; + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + if ((key === 'hints' || key === 'coach') && !this.busy && this.gs.current === HUMAN) this.refreshDecideHints(); + this.refreshHud(); + } + + // ── end of game ───────────────────────────────────────────────────────────── + async finishGame() { + if (this.ended) return; + this.ended = true; + this.busy = true; + this.cup.setEnabled(false); + this.tray.setEnabled(false); + this.pad.setEnabled(false); + this.undoBtn.setVisible(false); + this.refreshHud(); + this.setStatus('Game over', 'Adding up the score pad…'); + const ranks = L.rankings(this.gs); + const wait = (ms) => new Promise((r) => this.time.delayedCall(ms, r)); + await this.pad.tally(this.gs, ranks, wait); + const human = L.computeTotals(this.gs.players[HUMAN]).grand; + const best = recordPersonalBest(human); this.postHistory().catch(() => {}); - - const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.65) - .setInteractive().setDepth(DEPTH.modal); - - const panelW = 760; - const N = this.gs.players.length; - const panelH = 220 + N * 60; - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, panelW, panelH, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.modal); - - const cy = GAME_HEIGHT / 2; - this.add.text(GAME_WIDTH / 2, cy - panelH / 2 + 50, 'Final Score', { - fontFamily: 'Righteous', fontSize: '42px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.modal); - - const winners = new Set(getWinners(this.gs)); - let rowY = cy - panelH / 2 + 110; - for (let p = 0; p < N; p++) { - const totals = computeTotals(this.gs.players[p]); - const isWinner = winners.has(p); - const color = isWinner ? COLORS.goldHex : COLORS.textHex; - const prefix = isWinner ? '★ ' : ' '; - this.add.text(GAME_WIDTH / 2 - panelW / 2 + 40, rowY, `${prefix}${this.gs.players[p].name}`, { - fontFamily: 'Righteous', fontSize: '24px', color, - }).setOrigin(0, 0.5).setDepth(DEPTH.modal); - this.add.text(GAME_WIDTH / 2 + panelW / 2 - 40, rowY, String(totals.grand), { - fontFamily: 'Righteous', fontSize: '28px', color, - }).setOrigin(1, 0.5).setDepth(DEPTH.modal); - rowY += 50; - } - - new Button(this, GAME_WIDTH / 2, cy + panelH / 2 - 50, 'Back to Menu', - () => this.scene.start('GameMenu'), - { width: 280, fontSize: 24 }, - ).setDepth(DEPTH.modal); + if (ranks[HUMAN] === 1) { playSound(this, SFX.CASINO_WIN); this.confetti(140); } + else playSound(this, SFX.CASINO_LOSE); + for (let p = 1; p < this.n; p++) this.portraits[p]?.playEmotion?.(ranks[p] === 1 ? 'happy' : 'upset'); + this.setStatus(ranks[HUMAN] === 1 ? 'You win!' : 'Game over', `Final score: ${human}`); + await wait(900); + this.hidePortraits(); + openEndScreen(this, { + gs: this.gs, ranks, depth: D.end, best, + onPlayAgain: () => this.scene.restart(this.initData), + onMenu: () => this.scene.start('GameMenu'), + }); } async postHistory() { - const N = this.gs.players.length; - const totals = this.gs.players.map((p) => computeTotals(p).grand); - const human = totals[0]; - const winners = new Set(getWinners(this.gs)); + const totals = this.gs.players.map((p) => L.computeTotals(p).grand); + const winners = new Set(L.getWinners(this.gs)); let result; - if (N === 1) { - result = 'win'; - } else if (winners.has(0) && winners.size === 1) { - result = 'win'; - } else if (winners.has(0)) { - result = 'draw'; - } else { - result = 'loss'; - } + if (this.n === 1) result = 'win'; + else if (winners.has(HUMAN) && winners.size === 1) result = 'win'; + else if (winners.has(HUMAN)) result = 'draw'; + else result = 'loss'; await api.post('/history/single-player', { - slug: 'yatzi', - score: human, - opponentScores: totals.slice(1), - result, + slug: 'yatzi', score: totals[HUMAN], opponentScores: totals.slice(1), result, }); } - // ─── Utility ─────────────────────────────────────────────────────────── - delay(ms) { - return new Promise((resolve) => this.time.delayedCall(ms, resolve)); + // ── utility ───────────────────────────────────────────────────────────────── + wait(ms) { return new Promise((r) => this.time.delayedCall(Math.max(0, ms), r)); } + tweenTo(target, props, duration, ease = 'Quad.InOut') { + return new Promise((r) => this.tweens.add({ targets: target, ...props, duration, ease, onComplete: r })); } } diff --git a/src/games/yatzi/YatziLayout.js b/src/games/yatzi/YatziLayout.js new file mode 100644 index 0000000..26855b1 --- /dev/null +++ b/src/games/yatzi/YatziLayout.js @@ -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; diff --git a/src/games/yatzi/YatziLogic.js b/src/games/yatzi/YatziLogic.js index 0843294..2a3a5c9 100644 --- a/src/games/yatzi/YatziLogic.js +++ b/src/games/yatzi/YatziLogic.js @@ -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): -// Upper: ones, twos, threes, fours, fives, sixes (sum of those faces) -// Lower: threeOfKind, fourOfKind, fullHouse(25), smallStraight(30), -// largeStraight(40), yahtzee(50), chance(sum) +// Upper: ones … sixes (sum of those faces) +// Lower: threeOfKind, fourOfKind (sum of all dice), fullHouse (25), +// smallStraight (30), largeStraight (40), yahtzee (50), chance (sum) // // Scoring extras: -// - Upper bonus: +35 if upper subtotal ≥ 63 -// - Yahtzee bonus: +100 per subsequent Yahtzee after the first scored 50, -// with Joker placement rules: -// 1. If matching upper section is empty, must use it (scores face×5). -// 2. Else any lower section: fullHouse=25, smallStraight=30, -// largeStraight=40 even when pattern doesn't strictly match; -// threeOfKind / fourOfKind / chance score sum of dice. -// 3. Else any upper section may be zeroed. -// If yahtzee slot was already zeroed (player scored 0 there earlier), -// Joker placement still applies but no +100 bonus accrues. +// - Upper bonus: +35 if the upper subtotal reaches 63 (three of each face). +// - Zahtzee bonus: +100 for every further Zahtzee once the box holds 50. +// - Joker rules (official, "forced"), whenever a Zahtzee is rolled and the +// Zahtzee box is already filled (with 50 or a scratched 0): +// 1. the matching upper box must be used if it is open; +// 2. otherwise any open LOWER box, where Full House / Small Straight / +// Large Straight score their full value and 3K / 4K / Chance the sum; +// 3. only if the lower section is full may an upper box be scratched. +// The +100 bonus is earned only if the Zahtzee box holds 50. +// +// 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 LOWER = ['threeOfKind', 'fourOfKind', 'fullHouse', 'smallStraight', 'largeStraight', 'yahtzee', 'chance']; 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 = { - ones: 'Aces', - twos: 'Twos', - threes: 'Threes', - 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', + ones: 'Aces', twos: 'Twos', threes: 'Threes', 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 }) { const players = playerNames.map((p) => ({ name: p.name, @@ -44,15 +55,18 @@ export function createInitialState({ playerNames }) { avatar: p.avatar ?? null, scorecard: Object.fromEntries(CATEGORIES.map((c) => [c, null])), yahtzeeBonusCount: 0, + stats: emptyStats(), })); return { players, current: 0, - dice: [1, 1, 1, 1, 1], + dice: [1, 2, 3, 4, 5], held: [false, false, false, false, false], rollsRemaining: 3, 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 ────────────────────────────────────────────────────────────────── -export function rollDice(state) { - if (state.rollsRemaining <= 0) return state; +export function rollDice(state, rng = Math.random) { + if (state.rollsRemaining <= 0 || state.phase === 'gameover') return state; const s = cloneState(state); 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.phase = s.rollsRemaining > 0 ? 'rolling' : 'scoring'; s.lastBonusGained = false; + s.players[s.current].stats.rolls += 1; return s; } @@ -80,45 +95,66 @@ export function setDice(state, dice) { 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) { - if (state.phase === 'preroll' || state.phase === 'gameover') return state; - if (state.rollsRemaining <= 0) return state; // no point holding once all rolls used + if (!canHold(state)) return state; const s = cloneState(state); s.held[idx] = !s.held[idx]; 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 ──────────────────────────────────────────────────── -const sumDice = (dice) => dice.reduce((a, b) => a + b, 0); +export const sumDice = (dice) => dice.reduce((a, b) => a + b, 0); -function diceCounts(dice) { - const c = {}; - for (const d of dice) c[d] = (c[d] || 0) + 1; +export function diceCounts(dice) { + const c = [0, 0, 0, 0, 0, 0, 0]; + for (const d of dice) c[d]++; return c; } function nOfAKind(dice, n) { - return Object.values(diceCounts(dice)).some((v) => v >= n); + return diceCounts(dice).some((v) => v >= n); } -function isFullHouse(dice) { - const c = Object.values(diceCounts(dice)).sort((a, b) => a - b); +export function isFullHouse(dice) { + const c = diceCounts(dice).filter((v) => v > 0).sort((a, b) => a - b); return c.length === 2 && c[0] === 2 && c[1] === 3; } -function isSmallStraight(dice) { +export function isSmallStraight(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))); } -function isLargeStraight(dice) { +export function isLargeStraight(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))); } 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. @@ -141,43 +177,45 @@ export function baseScore(dice, category) { } } -// Whether Joker rules apply to this roll. -function jokerStatus(dice, scorecard) { +// Whether Joker rules apply to this roll, and whether it earns the +100. +export function jokerStatus(dice, scorecard) { if (!isYahtzee(dice)) return { applies: false, bonus: false }; if (scorecard.yahtzee === 50) return { applies: true, bonus: true }; if (scorecard.yahtzee === 0) return { applies: true, 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. export function legalCategories(dice, scorecard) { const open = CATEGORIES.filter((c) => scorecard[c] === null); if (open.length === 0) return []; - const j = jokerStatus(dice, scorecard); - if (!j.applies) return open; - - const face = dice[0]; - const matchingUpper = UPPER[face - 1]; - // 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; + const mode = jokerMode(dice, scorecard); + if (mode === null) return open; + if (mode === 'upper') return [UPPER[dice[0] - 1]]; + if (mode === 'lower') return LOWER.filter((c) => scorecard[c] === null); + return UPPER.filter((c) => scorecard[c] === null); } -// Compute committed value for a category, honoring Joker substitutions. -// Returns null if placement is illegal. +// Committed value for a category, honouring Joker substitutions. +// Returns null if the placement is illegal. 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); if (!legal.includes(category)) return null; const j = jokerStatus(dice, scorecard); 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) { case 'fullHouse': return 25; case 'smallStraight': return 30; @@ -185,12 +223,11 @@ export function scoreForCommit(dice, category, scorecard) { case 'threeOfKind': case 'fourOfKind': case 'chance': return sumDice(dice); - case 'yahtzee': return 50; // unreachable: already filled when Joker applies - default: return baseScore(dice, category); // upper: face * count (zero unless matching upper used) + default: return baseScore(dice, category); // upper: face × count (0 when scratching) } } -// 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) { if (state.phase !== 'rolling' && state.phase !== 'scoring') return state; const player = state.players[state.current]; @@ -200,6 +237,7 @@ export function commitScore(state, category) { const s = cloneState(state); const cur = s.players[s.current]; const j = jokerStatus(s.dice, cur.scorecard); + const upperBefore = computeTotals(cur).upperBonus; cur.scorecard[category] = value; s.lastBonusGained = false; @@ -207,16 +245,23 @@ export function commitScore(state, category) { cur.yahtzeeBonusCount += 1; 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)) { s.phase = 'gameover'; return s; } - - // Advance turn 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.phase = 'preroll'; return s; @@ -226,18 +271,48 @@ export function isGameOver(state) { 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) { 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 yahtzeeBonus = player.yahtzeeBonusCount * 100; + const yahtzeeBonus = player.yahtzeeBonusCount * YAHTZEE_BONUS; const grand = upperSubtotal + upperBonus + lowerSubtotal + yahtzeeBonus; 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) { const totals = state.players.map((p, i) => ({ idx: i, total: computeTotals(p).grand })); const max = Math.max(...totals.map((t) => t.total)); 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); +} diff --git a/src/games/yatzi/YatziPad.js b/src/games/yatzi/YatziPad.js new file mode 100644 index 0000000..de2ccef --- /dev/null +++ b/src/games/yatzi/YatziPad.js @@ -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); + } +} diff --git a/src/games/yatzi/YatziSolver.js b/src/games/yatzi/YatziSolver.js new file mode 100644 index 0000000..da47549 --- /dev/null +++ b/src/games/yatzi/YatziSolver.js @@ -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)]; +} diff --git a/src/games/yatzi/YatziTray.js b/src/games/yatzi/YatziTray.js new file mode 100644 index 0000000..7a5debd --- /dev/null +++ b/src/games/yatzi/YatziTray.js @@ -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); + } +} diff --git a/src/games/yatzi/tutorial.md b/src/games/yatzi/tutorial.md new file mode 100644 index 0000000..15b1e01 --- /dev/null +++ b/src/games/yatzi/tutorial.md @@ -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.* diff --git a/src/ui/dice/Dice3D.js b/src/ui/dice/Dice3D.js index 77089e6..0a0b672 100644 --- a/src/ui/dice/Dice3D.js +++ b/src/ui/dice/Dice3D.js @@ -204,22 +204,33 @@ function flyTray(tray, size, origin, aim, rng) { return { frames, u: X, v: Y, q: qf, hitWall }; } -// Plan a throw of both dice into a rectangular tray landing on `faces` [a, b]. -// Returns { dice: [{frames, u, v, top}], duration } — frames are at 120 fps. -export function planTrayThrow(tray, origin, faces, rng = Math.random, size = 30) { +// Plan a throw of N dice into a rectangular tray landing on `faces` (one per +// die; Catan passes two). Returns { dice: [{frames, u, v, top}], duration } — +// 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 = []; - 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; for (let k = 0; k < 40; k++) { const aim = { - u: tray.w * (0.3 + rng() * 0.4) + (i ? 1 : -1) * size * 0.9, - v: tray.h * (0.3 + rng() * 0.4), + u: tray.w * (aimBox.u0 + rng() * (aimBox.u1 - aimBox.u0)) + off * size * 0.9 * spread, + 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 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; - const okSep = sep >= size * 1.6; + let sep = Infinity; + 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); if (!best || score > best.score) best = { ...fly, score }; if (score === 4) break; @@ -227,7 +238,7 @@ export function planTrayThrow(tray, origin, faces, rng = Math.random, size = 30) relabelFlight(best, faces[i]); 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]); return { dice: out, duration: (len - 1) / 120 }; } diff --git a/tools/verifyYatzi.js b/tools/verifyYatzi.js new file mode 100644 index 0000000..58037e1 --- /dev/null +++ b/tools/verifyYatzi.js @@ -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);