From 60021f197b47f0aaa69a5e43d8018666e731ef06 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Mon, 30 Nov 2026 21:00:45 -0700 Subject: [PATCH] Rework Farkel as a ski-lodge table with exact-solver AI and house rules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace the heuristic opponent with a skill ladder (1–5) built on an exact one-turn Markov solver; skills 4–5 pick keeps by expected value and handle final-round reach, catch-up pressure, and piggyback offers. - Add house rules (target, entry minimum, three-Farkle penalty, two triplets, doubling kinds, piggyback) with a settings dialog and normalized state; the engine now scores each throw independently instead of combining set-aside dice. - Rebuild the table art as Gerome's Ski Lodge: baked textures for room, tray, rail, cup, seats, clipboard score pad, chalkboard scoring card, risk gauge, frost and sprites, plus a 3D dice tray with shake-and-pour throws. - Add coach advice, turn log, pause menu, end screen with stats/chart and personal bests, autosave/resume, and keyboard controls. - Ship tools/verifyFarkel.js to check scoring, odds, solver, AI legality, skill ladder, and layout overlaps; update the tutorial accordingly. --- src/games/farkel/FarkelAI.js | 197 ++- src/games/farkel/FarkelArt.js | 593 +++++++++ src/games/farkel/FarkelData.js | 100 +- src/games/farkel/FarkelDialogs.js | 193 +++ src/games/farkel/FarkelEndScreen.js | 123 ++ src/games/farkel/FarkelGame.js | 1845 ++++++++++++++++----------- src/games/farkel/FarkelLayout.js | 161 +++ src/games/farkel/FarkelLogic.js | 451 ++++--- src/games/farkel/FarkelPad.js | 185 +++ src/games/farkel/FarkelSolver.js | 193 +++ src/games/farkel/FarkelTray.js | 389 ++++++ src/games/farkel/tutorial.md | 46 +- tools/verifyFarkel.js | 314 +++++ 13 files changed, 3797 insertions(+), 993 deletions(-) create mode 100644 src/games/farkel/FarkelArt.js create mode 100644 src/games/farkel/FarkelDialogs.js create mode 100644 src/games/farkel/FarkelEndScreen.js create mode 100644 src/games/farkel/FarkelLayout.js create mode 100644 src/games/farkel/FarkelPad.js create mode 100644 src/games/farkel/FarkelSolver.js create mode 100644 src/games/farkel/FarkelTray.js create mode 100644 tools/verifyFarkel.js diff --git a/src/games/farkel/FarkelAI.js b/src/games/farkel/FarkelAI.js index 21a92e3..4199625 100644 --- a/src/games/farkel/FarkelAI.js +++ b/src/games/farkel/FarkelAI.js @@ -1,55 +1,166 @@ -// Farkel — heuristic opponent. No Phaser, no timers, no state mutation. After a -// roll the AI always takes the greedy best-scoring set (FarkelLogic.bestScoring); -// the only real decision is reroll vs. bank, made with an expected-value model -// over the standard Farkle odds, shaded by a 1-5 skill profile for human-like -// pacing and the occasional greedy blunder. +// Farkel — opponents and the Coach. No Phaser, no timers, no state mutation. +// +// skill 5 exact solver (FarkelSolver) for both the keep and bank/roll, plus +// endgame awareness: the final-round chase maximises P(beat leader), +// and it pushes harder when an opponent is about to close the game +// skill 4 solver keeps (occasionally greedy) and solver banking with slips +// on close calls +// skill 3 greedy keeps, sensible bank thresholds by dice left +// skill 2 greedy keeps, a timid or reckless personality with noise +// skill 1 greedy keeps, banks as soon as it's nervous +// +// Every skill obeys the hard rules of the table: it never banks below the +// entry minimum and never banks short of the leader in the final round. -import { WIN_TARGET, ON_BOARD_MIN } from './FarkelData.js'; +import { DICE } from './FarkelData.js'; +import { bestScoring, finalRoundNeed, bankAllowed, currentPlayer } from './FarkelLogic.js'; +import { pointsSolver, reachSolver, rankKeeps, farkleChance } from './FarkelSolver.js'; -// Probability a roll of N dice scores nothing (standard Farkle figures). -const FARKLE_PROB = { 1: 0.667, 2: 0.444, 3: 0.278, 4: 0.157, 5: 0.077, 6: 0.023 }; -// Rough expected points added by scoring dice in a roll of N. -const AVG_GAIN = { 1: 25, 2: 50, 3: 75, 4: 113, 5: 150, 6: 200 }; +const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3))); -const SKILL_PROFILES = { - 1: { greed: 1.6, noise: 0.5, delay: [700, 1200] }, - 2: { greed: 1.3, noise: 0.35, delay: [650, 1100] }, - 3: { greed: 1.1, noise: 0.2, delay: [600, 1000] }, - 4: { greed: 1.0, noise: 0.1, delay: [520, 900] }, - 5: { greed: 1.0, noise: 0.0, delay: [440, 820] }, +const THRESH = { + 3: { 6: Infinity, 5: 3000, 4: 1050, 3: 450, 2: 250, 1: 350 }, + timid: { 6: Infinity, 5: 1000, 4: 500, 3: 300, 2: 250, 1: 200 }, + reckless: { 6: Infinity, 5: 3000, 4: 2000, 3: 1000, 2: 600, 1: 500 }, }; -function profileFor(skill) { - return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; + +// Reading of the scoreboard for the current player: which solver to use. +export function situation(state) { + const me = currentPlayer(state); + const rules = state.rules; + let need = finalRoundNeed(state); + if (need > 0) { + if (!me.onBoard) need = Math.max(need, rules.entry); + return { mode: 'reach', need, solver: reachSolver(rules, need) }; + } + const entry = me.onBoard ? 0 : rules.entry; + return { mode: 'points', need: 0, minBank: entry, solver: pointsSolver(rules, entry) }; } +// Expert endgame shading for skill 5: when an opponent is close to triggering +// the final round and we're well behind, demand a bigger turn before banking. +function catchUpMinBank(state) { + const me = currentPlayer(state); + const target = state.rules.target; + let opp = 0; + state.players.forEach((p) => { if (p.seat !== me.seat) opp = Math.max(opp, p.score); }); + if (opp < target * 0.8) return 0; + const deficit = opp - me.score; + if (deficit <= 1000) return 0; + return Math.min(2000, Math.round((deficit * 0.3) / 50) * 50); +} + +function personality(state, seat) { + // stable per seat and game: odd seats are reckless, even seats timid + return (seat + state.players.length) % 2 ? 'reckless' : 'timid'; +} + +// Decide what to keep from the current throw and whether to bank afterwards. +// Returns { keep: indices into turn.rolled, bank: boolean }. +export function planDecision(state, skill = 3, rng = Math.random) { + const sk = clampSkill(skill); + const me = currentPlayer(state); + const t = state.turn; + const rules = state.rules; + const rolled = t.rolled; + const sit = situation(state); + + // ── which dice to keep ── + let keep; + if (sk >= 4 || (sk === 3 && sit.mode === 'reach')) { + let solver = sit.solver; + if (sk === 5 && sit.mode === 'points') { + const mb = Math.max(sit.minBank, catchUpMinBank(state)); + if (mb > sit.minBank) solver = pointsSolver(rules, mb); + } + const ranked = rankKeeps(rolled, t.kept, rules, solver); + keep = ranked[0]; + if (sk === 4 && rng() < 0.1) { + const g = bestScoring(rolled, rules); + keep = ranked.find((k) => k.indices.join() === g.indices.join()) ?? keep; + } + keep = { indices: keep.indices, points: keep.points, solver }; + } else { + const g = bestScoring(rolled, rules); + keep = { indices: g.indices, points: g.points, solver: sit.solver }; + } + + const total = t.kept + keep.points; + const left = rolled.length - keep.indices.length || DICE; + const allowed = bankAllowed(state, total); + + // ── hard rules every skill respects ── + if (!allowed) return { keep: keep.indices, bank: false }; + if (sit.mode === 'reach') return { keep: keep.indices, bank: total >= sit.need }; + if (!state.finalRound && me.score + total >= rules.target) return { keep: keep.indices, bank: true }; + + // ── bank or roll ── + let bank; + if (sk >= 4) { + const s = keep.solver; + const bv = s.bankValue(total), rv = s.rollValue(total, left); + bank = bv >= rv; + if (sk === 4 && Math.abs(bv - rv) < Math.max(40, total * 0.06) && rng() < 0.35) bank = !bank; + if (bv === -Infinity) bank = false; + } else if (sk === 3) { + bank = total >= THRESH[3][left]; + } else if (sk === 2) { + const th = THRESH[personality(state, me.seat)][left]; + bank = total >= th * (0.55 + rng() * 0.9); + } else { + // skill 1: jittery — banks when few dice are left, sometimes on a whim + bank = left <= 3 ? rng() < 0.75 : left <= 4 ? rng() < 0.3 : false; + if (left <= 2 && total < 150) bank = rng() < 0.5; + } + return { keep: keep.indices, bank }; +} + +// Should this player take the piggyback offer? +export function wantsPiggyback(state, skill = 3) { + const o = state.piggyOffer; + if (!o) return false; + const sk = clampSkill(skill); + if (sk <= 2) return o.available >= 3 || o.kept >= 1000; + const { solver } = situation(state); + return solver.rollValue(o.kept, o.available) > solver.rollValue(0, DICE); +} + +// Human-like thinking time per skill. +const DELAY = { 1: [700, 1200], 2: [650, 1100], 3: [600, 1000], 4: [520, 900], 5: [440, 820] }; export function nextThinkDelay(skill) { - const [lo, hi] = profileFor(skill).delay; + const [lo, hi] = DELAY[clampSkill(skill)]; return lo + Math.random() * (hi - lo); } -// Decide whether to reroll the remaining dice (true) or bank (false). Called -// after the AI has already set aside its scoring dice for the current roll. -export function decideReroll(state, skill = 3) { - const prof = profileFor(skill); +// ── Coach ──────────────────────────────────────────────────────────────────── +// Advice for the human on the current throw: the expert keep, plus what the +// chosen (or expert) keep is worth if banked vs rolled on. +export function coachAdvice(state, selection = null) { const t = state.turn; - const me = state.players[state.current]; - - // Below the on-board minimum, banking would score nothing — so the kept total - // is worthless until it reaches 500. Always push on (there's nothing to lose). - if (!me.onBoard && t.kept < ON_BOARD_MIN) return true; - - // If banking now wins the game, take it. - if (me.score + t.kept >= WIN_TARGET) return false; - - const prob = FARKLE_PROB[t.available] ?? 0.5; - const gain = (AVG_GAIN[t.available] ?? 50) * prof.greed; - let ev = (1 - prob) * gain - prob * t.kept; - ev += (Math.random() * 2 - 1) * prof.noise * 100; - - // If an opponent is on the brink, gamble harder to keep pace. - let oppMax = 0; - state.players.forEach((p) => { if (p.seat !== me.seat && p.score > oppMax) oppMax = p.score; }); - if (oppMax >= WIN_TARGET * 0.8 && me.score + t.kept < oppMax) ev += 150; - - return ev > 0; + const rules = state.rules; + const sit = situation(state); + const ranked = rankKeeps(t.rolled, t.kept, rules, sit.solver); + if (!ranked.length) return null; + const best = ranked[0]; + let mine = null; + if (selection && selection.length) { + const key = selection.map((i) => t.rolled[i]).sort().join(''); + mine = ranked.find((k) => k.indices.map((i) => t.rolled[i]).sort().join('') === key) ?? null; + } + const k = mine ?? best; + const canBankK = bankAllowed(state, k.total) && (sit.mode !== 'reach' || k.total >= sit.need); + return { + mode: sit.mode, + need: sit.need, + best, + mine, + total: k.total, + left: k.left, + rollValue: k.roll, + bankValue: canBankK ? (sit.mode === 'reach' ? 1 : k.total) : null, + recommend: canBankK && k.bank >= k.roll ? 'bank' : 'roll', + farkle: farkleChance(rules, k.left), + // how much the selection gives up against the expert keep (points mode) + regret: mine ? best.value - mine.value : 0, + }; } diff --git a/src/games/farkel/FarkelArt.js b/src/games/farkel/FarkelArt.js new file mode 100644 index 0000000..d474e14 --- /dev/null +++ b/src/games/farkel/FarkelArt.js @@ -0,0 +1,593 @@ +// FarkelArt.js — baked canvas textures for Gerome's Ski Lodge. +// +// farkel-room dark knotty-pine table, buffalo-plaid runner, fireside glow, +// cold window light and frosted corners +// farkel-vignette glow + vignette overlay for a chosen playfield "tablecloth" +// farkel-tray pine dice tray with an evergreen felt well + snowflake crest +// farkel-rail the "set aside" shelf under the tray +// farkel-cup leather dice cup with a sheepskin cuff +// farkel-seat an opponent's wooden place-card +// farkel-pad-N clipboard + ruled score sheet for N players +// farkel-card framed chalkboard for the scoring table +// farkel-thermo wooden plaque + glass tube for the Farkle-risk gauge +// farkel-frost frost sheet laid over the tray on a Farkle +// farkel-hand a soft ghost hand (tinted per opponent) +// farkel-spark / farkel-flake / farkel-ember small particles + +import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + W, H, TRAY, TRAY_FELT, TRAY_WALL, RAIL, RAIL_TOP_H, RAIL_START_X, CUP, SEAT, BOARD, CLIP, PAPER, + PAD_TITLE, PAD_HEAD, PAD_GRID, PAD_MARGIN, PAD_ROW_H, PAD_ROWS, padColX, CARD, CARD_INNER, THERMO, +} from './FarkelLayout.js'; + +export const PAD_PX = 26; // shadow margin baked around tray / rail / board +export const INK = ['#22304f', '#9c2121', '#1d6a3c', '#6a3591']; +export const INK_HEX = [0x22304f, 0x9c2121, 0x1d6a3c, 0x6a3591]; +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'; +export const CHALK = '#f1eee2'; +export const ICE = 0x9fd8ff; +export const EMBER = 0xff9a3c; + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); +} + +function shade(hex, k) { + const n = parseInt(hex.slice(1), 16); + const c = [n >> 16, (n >> 8) & 255, n & 255].map((v) => Math.max(0, Math.min(255, Math.round(v * k)))); + return `rgb(${c[0]},${c[1]},${c[2]})`; +} + +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(); +} + +// ── wood ───────────────────────────────────────────────────────────────────── +function grain(ctx, x, y, w, h, { tone = 'rgba(40,20,8,0.22)', lines = 14, wave = 3, knots = 0.7 } = {}) { + 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(); + } + // knotty pine: dark knots with rings + const nk = w > 300 ? (Math.random() < knots ? 1 + Math.floor(Math.random() * 2) : 0) : 0; + for (let k = 0; k < nk; k++) { + const kx = x + Math.random() * w, ky = y + h * (0.25 + Math.random() * 0.5); + const kg = ctx.createRadialGradient(kx, ky, 1, kx, ky, 12); + kg.addColorStop(0, 'rgba(40,18,6,0.85)'); kg.addColorStop(1, 'rgba(40,18,6,0)'); + ctx.fillStyle = kg; + ctx.beginPath(); ctx.ellipse(kx, ky, 14, 7, 0, 0, Math.PI * 2); ctx.fill(); + for (let r = 4; r < 22; r += 4) { + 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 = ['#5a3a20', '#4e321c', '#634024', '#553620'] } = {}) { + 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.08)); g.addColorStop(1, shade(base, 0.88)); + ctx.fillStyle = g; + ctx.fillRect(x, py, w, ph); + grain(ctx, x, py, w, ph, { lines: 20, knots: 0.9 }); + ctx.fillStyle = 'rgba(15,6,2,0.6)'; + ctx.fillRect(x, py + ph - 3, w, 3); + ctx.fillStyle = 'rgba(255,220,170,0.07)'; + ctx.fillRect(x, py, w, 1.5); + const jx = x + ((i * 617) % Math.max(1, w - 200)) + 100; + ctx.fillStyle = 'rgba(15,6,2,0.45)'; + ctx.fillRect(jx, py, 2, ph); + // square-head nails at the joint + ctx.fillStyle = 'rgba(30,26,22,0.8)'; + ctx.fillRect(jx - 9, py + 14, 4, 4); ctx.fillRect(jx + 7, py + ph - 20, 4, 4); + } +} + +// Red/black buffalo plaid with a fringe on the short ends. +function plaid(ctx, x, y, w, h) { + ctx.save(); + rr(ctx, x, y, w, h, 8); ctx.clip(); + ctx.fillStyle = '#8e1a1a'; ctx.fillRect(x, y, w, h); + const S = 54; + ctx.fillStyle = 'rgba(12,8,8,0.62)'; + for (let xx = x; xx < x + w; xx += S * 2) ctx.fillRect(xx, y, S, h); + ctx.fillStyle = 'rgba(12,8,8,0.55)'; + for (let yy = y; yy < y + h; yy += S * 2) ctx.fillRect(x, yy, w, S); + // woven texture: fine diagonal twill + ctx.strokeStyle = 'rgba(0,0,0,0.12)'; ctx.lineWidth = 1; + for (let d = -h; d < w; d += 5) { ctx.beginPath(); ctx.moveTo(x + d, y); ctx.lineTo(x + d + h, y + h); ctx.stroke(); } + ctx.fillStyle = noisePattern(ctx, 96, 30); ctx.fillRect(x, y, w, h); + // soft fold shadows + const fg = ctx.createLinearGradient(0, y, 0, y + h); + fg.addColorStop(0, 'rgba(0,0,0,0.25)'); fg.addColorStop(0.08, 'rgba(0,0,0,0)'); fg.addColorStop(0.92, 'rgba(0,0,0,0)'); fg.addColorStop(1, 'rgba(0,0,0,0.3)'); + ctx.fillStyle = fg; ctx.fillRect(x, y, w, h); + ctx.restore(); + // fringe + ctx.strokeStyle = 'rgba(120,24,24,0.9)'; ctx.lineWidth = 2; + for (const ex of [x, x + w]) { + const dir = ex === x ? -1 : 1; + for (let yy = y + 6; yy < y + h - 4; yy += 7) { + ctx.beginPath(); ctx.moveTo(ex, yy); ctx.lineTo(ex + dir * (10 + Math.random() * 6), yy + (Math.random() - 0.5) * 4); ctx.stroke(); + } + } +} + +function glow(ctx, cx, cy, r, rgb, alpha) { + const g = ctx.createRadialGradient(cx, cy, 10, cx, cy, r); + g.addColorStop(0, `rgba(${rgb},${alpha})`); + g.addColorStop(0.6, `rgba(${rgb},${alpha * 0.35})`); + g.addColorStop(1, `rgba(${rgb},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); +} + +// Frost crystals creeping in from a corner (cx, cy) towards (dx, dy). +function frostCorner(ctx, cx, cy, dx, dy, reach = 260) { + ctx.save(); + const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, reach); + g.addColorStop(0, 'rgba(225,240,255,0.32)'); g.addColorStop(1, 'rgba(225,240,255,0)'); + ctx.fillStyle = g; ctx.fillRect(cx - reach, cy - reach, reach * 2, reach * 2); + ctx.strokeStyle = 'rgba(235,246,255,0.35)'; + const branch = (x, y, ang, len, depth) => { + if (depth <= 0 || len < 6) return; + const x2 = x + Math.cos(ang) * len, y2 = y + Math.sin(ang) * len; + ctx.lineWidth = Math.max(0.5, depth * 0.45); + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x2, y2); ctx.stroke(); + const n = 2 + Math.floor(Math.random() * 2); + for (let i = 0; i < n; i++) { + const t = 0.3 + Math.random() * 0.6; + branch(x + (x2 - x) * t, y + (y2 - y) * t, ang + (Math.random() < 0.5 ? -1 : 1) * (0.5 + Math.random() * 0.5), len * 0.45, depth - 1); + } + branch(x2, y2, ang + (Math.random() - 0.5) * 0.4, len * 0.7, depth - 1); + }; + const base = Math.atan2(dy, dx); + for (let i = 0; i < 7; i++) branch(cx, cy, base + (i - 3) * 0.24, reach * (0.35 + Math.random() * 0.25), 5); + ctx.restore(); +} + +function bakeRoom(scene) { + const c = canvas(W, H), ctx = c.getContext('2d'); + planks(ctx, 0, 0, W, H, { plankH: 128 }); + ctx.fillStyle = noisePattern(ctx, 128, 26); + ctx.fillRect(0, 0, W, H); + // plaid runner under the tray, rail and the HUD + dropShadow(ctx, () => { ctx.fillStyle = '#5a1010'; rr(ctx, 26, 166, 1168, 660, 8); ctx.fill(); }, { blur: 16, dy: 6, alpha: 0.5 }); + plaid(ctx, 26, 166, 1168, 660); + // fireside: warm glow from the lower left; window: cold light from the upper right + glow(ctx, -80, H + 60, 1100, '255,150,70', 0.42); + glow(ctx, TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, 820, '255,214,150', 0.2); + glow(ctx, W + 80, -60, 900, '170,205,255', 0.22); + vignette(ctx, 0.62); + frostCorner(ctx, W, 0, -1, 1, 300); + frostCorner(ctx, 0, 0, 1, 1, 220); + addCanvas(scene, 'farkel-room', c); + + const v = canvas(W, H), vx = v.getContext('2d'); + glow(vx, -80, H + 60, 1100, '255,150,70', 0.3); + glow(vx, W + 80, -60, 900, '170,205,255', 0.16); + vignette(vx, 0.55); + frostCorner(vx, W, 0, -1, 1, 260); + addCanvas(scene, 'farkel-vignette', v); +} + +// ── tray ───────────────────────────────────────────────────────────────────── +function snowflake(ctx, cx, cy, r, { lw = 3, color = 'rgba(255,255,255,0.08)' } = {}) { + ctx.save(); + ctx.translate(cx, cy); + ctx.strokeStyle = color; ctx.lineWidth = lw; ctx.lineCap = 'round'; + for (let k = 0; k < 6; k++) { + ctx.rotate(Math.PI / 3); + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, -r); ctx.stroke(); + for (const t of [0.45, 0.72]) { + const b = r * (1 - t) * 0.6; + ctx.beginPath(); ctx.moveTo(0, -r * t); ctx.lineTo(-b, -r * t - b); ctx.moveTo(0, -r * t); ctx.lineTo(b, -r * t - b); ctx.stroke(); + } + } + 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, 24); ctx.fillStyle = '#3a2412'; ctx.fill(); }, { blur: 30, dy: 16, alpha: 0.7 }); + // log-cabin frame: honey pine + ctx.save(); rr(ctx, x, y, w, h, 24); ctx.clip(); + const g = ctx.createLinearGradient(0, y, 0, y + h); + g.addColorStop(0, '#a8743e'); g.addColorStop(0.5, '#8a5a2c'); g.addColorStop(1, '#6e4520'); + ctx.fillStyle = g; ctx.fillRect(x, y, w, h); + grain(ctx, x, y, w, h, { lines: 46, tone: 'rgba(60,30,10,0.32)', knots: 1 }); + ctx.restore(); + ctx.strokeStyle = 'rgba(255,226,170,0.4)'; ctx.lineWidth = 2; + rr(ctx, x + 2, y + 2, w - 4, h - 4, 22); ctx.stroke(); + // felt well — deep evergreen + 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, '#2c6448'); fg.addColorStop(1, '#123726'); + ctx.fillStyle = fg; ctx.fillRect(fx, fy, fw, fh); + ctx.fillStyle = noisePattern(ctx, 96, 40); ctx.fillRect(fx, fy, fw, fh); + // crest: snowflake + lodge name, pressed into the felt + snowflake(ctx, fx + fw / 2, fy + fh * 0.5, 120, { lw: 6, color: 'rgba(0,0,0,0.12)' }); + snowflake(ctx, fx + fw / 2 - 1, fy + fh * 0.5 - 2, 120, { lw: 4, color: 'rgba(220,255,235,0.07)' }); + ctx.font = `30px ${DISPLAY_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(0,0,0,0.16)'; ctx.fillText("GEROME'S LODGE", fx + fw / 2 + 1, fy + fh * 0.5 + 168); + ctx.fillStyle = 'rgba(220,255,235,0.09)'; ctx.fillText("GEROME'S LODGE", fx + fw / 2, fy + fh * 0.5 + 166); + ctx.font = `14px ${PRINT_FONT}`; + ctx.fillStyle = 'rgba(220,255,235,0.08)'; ctx.fillText('· FARKLE · EST. ON A POWDER DAY ·', fx + fw / 2, fy + fh * 0.5 + 196); + // the far wall's inner face and inner shadows + const wallG = ctx.createLinearGradient(0, fy, 0, fy + 26); + wallG.addColorStop(0, '#4a2c12'); wallG.addColorStop(1, 'rgba(74,44,18,0)'); + ctx.fillStyle = wallG; ctx.fillRect(fx, fy, fw, 26); + for (const [x0, x1, a] of [[fx, fx + 22, 0.45], [fx + fw, fx + fw - 22, 0.35]]) { + const s = ctx.createLinearGradient(x0, 0, x1, 0); + s.addColorStop(0, `rgba(0,0,0,${a})`); s.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = s; ctx.fillRect(Math.min(x0, x1), 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(); + // iron corner brackets + for (const [cx, cy, sx, sy] of [[x + 6, y + 6, 1, 1], [x + w - 6, y + 6, -1, 1], [x + 6, y + h - 6, 1, -1], [x + w - 6, y + h - 6, -1, -1]]) { + ctx.fillStyle = '#2b2622'; + ctx.beginPath(); + ctx.moveTo(cx, cy); ctx.lineTo(cx + sx * 46, cy); ctx.lineTo(cx + sx * 46, cy + sy * 10); + ctx.lineTo(cx + sx * 10, cy + sy * 10); ctx.lineTo(cx + sx * 10, cy + sy * 46); ctx.lineTo(cx, cy + sy * 46); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#8a8178'; + for (const [a, b] of [[30, 5], [5, 30]]) { ctx.beginPath(); ctx.arc(cx + sx * a, cy + sy * b, 2.5, 0, Math.PI * 2); ctx.fill(); } + } + addCanvas(scene, 'farkel-tray', c); +} + +// ── set-aside rail ─────────────────────────────────────────────────────────── +function bakeRail(scene) { + const P = PAD_PX; + const c = canvas(RAIL.w + P * 2, RAIL.h + P * 2), ctx = c.getContext('2d'); + const x = P, y = P, w = RAIL.w, h = RAIL.h; + const topH = RAIL_TOP_H; + dropShadow(ctx, () => { rr(ctx, x, y, w, h, 14); ctx.fillStyle = '#2e1a0b'; ctx.fill(); }, { blur: 22, dy: 12, alpha: 0.6 }); + ctx.save(); rr(ctx, x, y, w, h, 14); ctx.clip(); + const tg = ctx.createLinearGradient(0, y, 0, y + topH); + tg.addColorStop(0, '#a26c38'); tg.addColorStop(1, '#84542a'); + ctx.fillStyle = tg; ctx.fillRect(x, y, w, topH); + grain(ctx, x, y, w, topH, { lines: 16 }); + // felt groove where kept dice sit + const gx = RAIL_START_X - RAIL.x + P - 10; + ctx.save(); + rr(ctx, gx, y + 12, w - (gx - x) - 16, topH - 22, 12); + const sg = ctx.createLinearGradient(0, y + 12, 0, y + topH - 10); + sg.addColorStop(0, '#0f2c1d'); sg.addColorStop(1, '#1d5135'); + ctx.fillStyle = sg; ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 2; ctx.stroke(); + ctx.restore(); + // front face + const fg = ctx.createLinearGradient(0, y + topH, 0, y + h); + fg.addColorStop(0, '#5c3417'); fg.addColorStop(1, '#3a200d'); + 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(); + // engraved label at the left of the shelf top + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.font = `20px ${DISPLAY_FONT}`; + const lx = x + (RAIL_START_X - RAIL.x) / 2 - 6; + ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.fillText('SET ASIDE', lx + 1, y + 22); + ctx.fillStyle = '#f1d6a6'; ctx.fillText('SET ASIDE', lx, y + 21); + ctx.font = `italic 13px ${SERIF}`; + ctx.fillStyle = 'rgba(240,214,166,0.7)'; ctx.fillText('this turn, by throw', lx, y + 42); + addCanvas(scene, 'farkel-rail', 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 + 18, bot = P + ch - 10; + const lt = P + 6, rt = P + cw - 6; + const lb = P + 16, rb = P + cw - 16; + ctx.fillStyle = 'rgba(0,0,0,0.45)'; + ctx.beginPath(); ctx.ellipse(P + cw / 2 + 8, bot + 2, cw * 0.42, 12, 0, 0, Math.PI * 2); ctx.fill(); + ctx.save(); + ctx.beginPath(); + ctx.moveTo(lt, top); ctx.lineTo(rt, top); ctx.lineTo(rb, bot); + ctx.ellipse(P + cw / 2, bot, (rb - lb) / 2, 10, 0, 0, Math.PI, false); + ctx.lineTo(lt, top); ctx.closePath(); + const g = ctx.createLinearGradient(lt, 0, rt, 0); + g.addColorStop(0, '#2a140a'); g.addColorStop(0.3, '#6b3a1e'); g.addColorStop(0.55, '#52290f'); g.addColorStop(1, '#1f0e06'); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 50); ctx.fillRect(0, 0, c.width, c.height); + // a red/black plaid band + const by = bot - 46; + ctx.fillStyle = '#8e1a1a'; ctx.fillRect(0, by, c.width, 22); + ctx.fillStyle = 'rgba(10,6,6,0.6)'; + for (let xx = 0; xx < c.width; xx += 16) ctx.fillRect(xx, by, 8, 22); + ctx.fillRect(0, by + 7, c.width, 8); + ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.fillRect(0, by - 2, c.width, 2); ctx.fillRect(0, by + 22, c.width, 2); + // embossed snowflake badge + snowflake(ctx, P + cw / 2, (top + by) / 2 + 12, 20, { lw: 2.5, color: 'rgba(255,214,160,0.4)' }); + ctx.restore(); + // sheepskin cuff around the mouth + ctx.save(); + for (let i = 0; i < 70; i++) { + const a = (i / 70) * Math.PI * 2; + const rx = (rt - lt) / 2 + 4, ry = 17; + const px = P + cw / 2 + Math.cos(a) * rx, py = top + 4 + Math.sin(a) * ry; + ctx.fillStyle = `rgba(${236 + Math.random() * 14},${228 + Math.random() * 14},${212 + Math.random() * 14},1)`; + ctx.beginPath(); ctx.arc(px, py, 7 + Math.random() * 3, 0, Math.PI * 2); ctx.fill(); + } + ctx.restore(); + ctx.beginPath(); ctx.ellipse(P + cw / 2, top + 2, (rt - lt) / 2 - 8, 10, 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(); + addCanvas(scene, 'farkel-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(66,38,18,0.94)'); g.addColorStop(1, 'rgba(38,20,9,0.94)'); + 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)' }); + // plaid strip along the bottom + ctx.fillStyle = '#7a1717'; ctx.fillRect(P, P + SEAT.h - 10, SEAT.w, 10); + ctx.fillStyle = 'rgba(10,6,6,0.6)'; + for (let xx = P; xx < P + SEAT.w; xx += 14) ctx.fillRect(xx, P + SEAT.h - 10, 7, 10); + 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, 'farkel-seat', c); +} + +// ── score pad ──────────────────────────────────────────────────────────────── +export function padKey(n) { return `farkel-pad-${n}`; } + +function bakePad(scene, n, target) { + const key = `${padKey(n)}-${target}`; + 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; + dropShadow(ctx, () => { rr(ctx, X(BOARD.x), Y(BOARD.y), BOARD.w, BOARD.h, 22); ctx.fillStyle = '#6a4a2c'; 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, '#7e5634'); bg.addColorStop(0.5, '#966a42'); bg.addColorStop(1, '#74502e'); + 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 + 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 = '#f8f3e2'; 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 + ctx.textBaseline = 'middle'; ctx.textAlign = 'left'; + ctx.font = `44px ${DISPLAY_FONT}`; + ctx.fillStyle = '#8e1a1a'; + ctx.fillText('FARKLE', X(PAD_TITLE.x), Y(PAD_TITLE.y)); + ctx.font = `15px ${PRINT_FONT}`; + ctx.fillStyle = '#6f5d45'; + ctx.fillText(`GEROME'S LODGE · FIRST TO ${target.toLocaleString('en-US')}`, X(PAD_TITLE.x) + 196, Y(PAD_TITLE.y) + 4); + snowflake(ctx, X(PAPER.x + PAPER.w - 46), Y(PAD_TITLE.y), 20, { lw: 2.5, color: 'rgba(70,110,170,0.55)' }); + // header band + ruled lines + const gx0 = X(PAD_GRID.x), gw = PAD_GRID.w; + ctx.fillStyle = 'rgba(34,48,79,0.06)'; ctx.fillRect(gx0, Y(PAD_HEAD.y), gw, PAD_HEAD.h); + ctx.fillStyle = '#22304f'; ctx.fillRect(gx0, Y(PAD_HEAD.y + PAD_HEAD.h) - 2, gw, 2); + ctx.font = `13px ${PRINT_FONT}`; ctx.fillStyle = '#6f5d45'; ctx.textAlign = 'center'; + ctx.fillText('TURN', gx0 + PAD_MARGIN / 2, Y(PAD_HEAD.y + PAD_HEAD.h / 2)); + const rowsTop = PAD_HEAD.y + PAD_HEAD.h; + ctx.fillStyle = 'rgba(70,95,150,0.35)'; + for (let r = 1; r <= PAD_ROWS; r++) ctx.fillRect(gx0, Y(rowsTop + r * PAD_ROW_H) - 1, gw, 1); + // red margin + column rules + const bottom = Y(rowsTop + PAD_ROWS * PAD_ROW_H); + ctx.fillStyle = 'rgba(179,38,30,0.6)'; + ctx.fillRect(gx0 + PAD_MARGIN - 1, Y(PAD_HEAD.y), 2, bottom - Y(PAD_HEAD.y)); + ctx.fillStyle = 'rgba(70,95,150,0.35)'; + for (let p = 1; p < n; p++) ctx.fillRect(X(padColX(p, n)), Y(PAD_HEAD.y), 1, bottom - Y(PAD_HEAD.y)); + 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 + 12, 80, 20, 10); ctx.fillStyle = 'rgba(60,64,70,0.55)'; ctx.fill(); + for (const rx of [cx + 24, cx + CLIP.w - 24]) { + const rg = ctx.createRadialGradient(rx - 2, cy + CLIP.h - 22, 1, rx, cy + CLIP.h - 20, 8); + rg.addColorStop(0, '#ffffff'); rg.addColorStop(1, '#6a7178'); + ctx.fillStyle = rg; ctx.beginPath(); ctx.arc(rx, cy + CLIP.h - 20, 7, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, key, c); + return { key, x: ox, y: oy }; +} + +// ── scoring chalkboard ─────────────────────────────────────────────────────── +function bakeCard(scene) { + const P = PAD_PX; + const c = canvas(CARD.w + P * 2, CARD.h + P * 2), ctx = c.getContext('2d'); + const x = P, y = P, w = CARD.w, h = CARD.h; + dropShadow(ctx, () => { rr(ctx, x, y, w, h, 16); ctx.fillStyle = '#3a2412'; ctx.fill(); }, { blur: 24, dy: 12, alpha: 0.6 }); + ctx.save(); rr(ctx, x, y, w, h, 16); ctx.clip(); + const fg = ctx.createLinearGradient(0, y, 0, y + h); + fg.addColorStop(0, '#9a6a38'); fg.addColorStop(1, '#6e4520'); + ctx.fillStyle = fg; ctx.fillRect(x, y, w, h); + grain(ctx, x, y, w, h, { lines: 30, tone: 'rgba(50,25,8,0.3)' }); + ctx.restore(); + const ix = CARD_INNER.x - CARD.x + P, iy = CARD_INNER.y - CARD.y + P, iw = CARD_INNER.w, ih = CARD_INNER.h; + ctx.save(); rr(ctx, ix, iy, iw, ih, 6); ctx.clip(); + const bg = ctx.createRadialGradient(ix + iw / 2, iy + ih / 2, 40, ix + iw / 2, iy + ih / 2, iw * 0.7); + bg.addColorStop(0, '#2f3a34'); bg.addColorStop(1, '#1c2420'); + ctx.fillStyle = bg; ctx.fillRect(ix, iy, iw, ih); + ctx.fillStyle = noisePattern(ctx, 96, 22); ctx.fillRect(ix, iy, iw, ih); + // old chalk smudges + for (let i = 0; i < 14; i++) { + const sx = ix + Math.random() * iw, sy = iy + Math.random() * ih; + const sg = ctx.createRadialGradient(sx, sy, 2, sx, sy, 40 + Math.random() * 60); + sg.addColorStop(0, 'rgba(255,255,255,0.05)'); sg.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = sg; ctx.fillRect(ix, iy, iw, ih); + } + ctx.restore(); + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; ctx.lineWidth = 3; + rr(ctx, ix, iy, iw, ih, 6); ctx.stroke(); + // chalk ledge with a stub of chalk + ctx.fillStyle = '#5a3818'; ctx.fillRect(ix + 20, iy + ih + 4, iw - 40, 10); + ctx.fillStyle = '#f4f1e6'; rr(ctx, ix + iw - 110, iy + ih + 1, 34, 9, 4); ctx.fill(); + addCanvas(scene, 'farkel-card', c); +} + +// ── risk thermometer ───────────────────────────────────────────────────────── +export const THERMO_TUBE = { x: THERMO.x + THERMO.w / 2, top: THERMO.y + 58, bottom: THERMO.y + THERMO.h - 46, w: 14, bulb: 17 }; +function bakeThermo(scene) { + const P = 12; + const c = canvas(THERMO.w + P * 2, THERMO.h + P * 2), ctx = c.getContext('2d'); + const x = P, y = P, w = THERMO.w, h = THERMO.h; + dropShadow(ctx, () => { rr(ctx, x, y, w, h, 30); ctx.fillStyle = '#5a3818'; ctx.fill(); }, { blur: 14, dy: 6, alpha: 0.55 }); + ctx.save(); rr(ctx, x, y, w, h, 30); ctx.clip(); + const g = ctx.createLinearGradient(x, 0, x + w, 0); + g.addColorStop(0, '#6e4520'); g.addColorStop(0.5, '#9a6a38'); g.addColorStop(1, '#6e4520'); + ctx.fillStyle = g; ctx.fillRect(x, y, w, h); + grain(ctx, x, y, w, h, { lines: 8, tone: 'rgba(40,20,6,0.3)', knots: 0 }); + ctx.restore(); + ctx.strokeStyle = 'rgba(255,226,170,0.35)'; ctx.lineWidth = 1.5; rr(ctx, x + 3, y + 3, w - 6, h - 6, 27); ctx.stroke(); + const tx = THERMO_TUBE.x - THERMO.x + P, tt = THERMO_TUBE.top - THERMO.y + P, tb = THERMO_TUBE.bottom - THERMO.y + P; + // snowflake cap + snowflake(ctx, tx, y + 24, 13, { lw: 2.5, color: 'rgba(230,244,255,0.85)' }); + // glass tube + bulb + ctx.fillStyle = 'rgba(235,245,255,0.85)'; + rr(ctx, tx - THERMO_TUBE.w / 2 - 3, tt - 6, THERMO_TUBE.w + 6, tb - tt + 10, 10); ctx.fill(); + ctx.beginPath(); ctx.arc(tx, tb + 10, THERMO_TUBE.bulb + 3, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(40,30,30,0.85)'; + rr(ctx, tx - THERMO_TUBE.w / 2, tt - 3, THERMO_TUBE.w, tb - tt + 6, 7); ctx.fill(); + // tick marks (0–70 %) + ctx.strokeStyle = '#f1d6a6'; ctx.fillStyle = '#f1d6a6'; + ctx.font = `10px ${PRINT_FONT}`; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; + for (let p = 0; p <= 70; p += 10) { + const ty = tb - (p / 70) * (tb - tt); + ctx.lineWidth = p % 20 === 0 ? 2 : 1; + ctx.beginPath(); ctx.moveTo(tx + 11, ty); ctx.lineTo(tx + (p % 20 === 0 ? 20 : 16), ty); ctx.stroke(); + } + addCanvas(scene, 'farkel-thermo', c); +} + +// ── frost sheet for a Farkle ───────────────────────────────────────────────── +function bakeFrost(scene) { + const c = canvas(TRAY_FELT.w, TRAY_FELT.h), ctx = c.getContext('2d'); + const w = TRAY_FELT.w, h = TRAY_FELT.h; + ctx.save(); rr(ctx, 0, 0, w, h, 14); ctx.clip(); + const g = ctx.createRadialGradient(w / 2, h / 2, 40, w / 2, h / 2, w * 0.7); + g.addColorStop(0, 'rgba(170,215,255,0.18)'); g.addColorStop(1, 'rgba(210,235,255,0.55)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + frostCorner(ctx, 0, 0, 1, 1, 340); + frostCorner(ctx, w, 0, -1, 1, 340); + frostCorner(ctx, 0, h, 1, -1, 300); + frostCorner(ctx, w, h, -1, -1, 300); + ctx.restore(); + addCanvas(scene, 'farkel-frost', c); +} + +// ── small sprites ──────────────────────────────────────────────────────────── +function bakeSprites(scene) { + const c = canvas(72, 84), ctx = c.getContext('2d'); + ctx.fillStyle = '#ffffff'; + ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 2; + ctx.beginPath(); + rr(ctx, 14, 34, 44, 40, 16); ctx.fill(); ctx.stroke(); + for (const [hx, hy, hh] of [[14, 10, 34], [26, 4, 38], [38, 6, 36], [50, 14, 30]]) { + rr(ctx, hx, hy, 11, hh, 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, 'farkel-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, 'farkel-spark', s); + + const e = canvas(20, 20), ex = e.getContext('2d'); + const eg = ex.createRadialGradient(10, 10, 0, 10, 10, 10); + eg.addColorStop(0, 'rgba(255,250,220,1)'); eg.addColorStop(0.3, 'rgba(255,170,70,0.9)'); eg.addColorStop(1, 'rgba(255,90,20,0)'); + ex.fillStyle = eg; ex.fillRect(0, 0, 20, 20); + addCanvas(scene, 'farkel-ember', e); + + const f = canvas(40, 40), fx = f.getContext('2d'); + snowflake(fx, 20, 20, 17, { lw: 2.4, color: 'rgba(255,255,255,0.95)' }); + addCanvas(scene, 'farkel-flake', f); + + // knit toque (leader's hat) + const t = canvas(44, 44), tx = t.getContext('2d'); + tx.fillStyle = '#b3261e'; + tx.beginPath(); tx.moveTo(8, 34); tx.quadraticCurveTo(10, 10, 22, 10); tx.quadraticCurveTo(34, 10, 36, 34); tx.closePath(); tx.fill(); + tx.strokeStyle = 'rgba(255,255,255,0.35)'; tx.lineWidth = 1.5; + for (let xx = 12; xx < 34; xx += 5) { tx.beginPath(); tx.moveTo(xx, 16); tx.lineTo(xx, 32); tx.stroke(); } + tx.fillStyle = '#f4f1e6'; rr(tx, 5, 30, 34, 9, 4); tx.fill(); + tx.beginPath(); tx.arc(22, 8, 6, 0, Math.PI * 2); tx.fill(); + addCanvas(scene, 'farkel-hat', t); +} + +// ── entry point ────────────────────────────────────────────────────────────── +let baked = false; +export async function prepareFarkelArt(scene, nPlayers, target) { + 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('farkel-room')) { + bakeRoom(scene); bakeTray(scene); bakeRail(scene); bakeCup(scene); bakeSeat(scene); + bakeCard(scene); bakeThermo(scene); bakeFrost(scene); bakeSprites(scene); + baked = true; + } + return bakePad(scene, nPlayers, target); +} diff --git a/src/games/farkel/FarkelData.js b/src/games/farkel/FarkelData.js index 8d2f025..eaed7dc 100644 --- a/src/games/farkel/FarkelData.js +++ b/src/games/farkel/FarkelData.js @@ -1,38 +1,72 @@ -// Farkel — static catalog. No Phaser, no game state. Constants, the die-pip -// layout (ported from Yatzi), player colours, and the scoring-reference rows -// shown in the info panel. +// Farkel — static catalog. No Phaser, no game state: dice count, the default +// table rules, house-rule options and the scoring-reference rows. export const DICE = 6; -export const WIN_TARGET = 10000; // first to 10k triggers a final round -export const ON_BOARD_MIN = 500; // single-turn total needed to start banking +export const WIN_TARGET = 10000; // default: first to 10k triggers one final round +export const ON_BOARD_MIN = 500; // default single-turn total needed to start banking +export const THREE_FARKLE_PENALTY = 1000; -// 3x3 pip layout (col, row offsets in {-1, 0, 1}) per face. Mirrors Yatzi. -export 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]], -}; +// Every rule the engine understands. Saved settings are merged over this. +export const DEFAULT_RULES = Object.freeze({ + target: WIN_TARGET, // 5000 | 10000 | 15000 + entry: ON_BOARD_MIN, // 0 | 350 | 500 | 1000 + threeFarkle: false, // three Farkles in a row costs 1,000 + twoTriplets: false, // two three-of-a-kinds in one roll = 2,500 + doubling: false, // 4/5/6 of a kind = triple ×2 / ×4 / ×8 (instead of 1k/2k/3k) + piggyback: false, // the next player may take over the leftover dice + total +}); -// Seat colours (shared visual language with the other tabletop games). -export const PLAYER_COLORS = [0xd0473a, 0x4a90d9, 0x49a25a, 0xe2b53c]; -export const PLAYER_COLOR_HEX = ['#d0473a', '#4a90d9', '#49a25a', '#e2b53c']; +export const TARGET_OPTIONS = [5000, 10000, 15000]; +export const ENTRY_OPTIONS = [0, 350, 500, 1000]; -// Ordered rows for the "Scoring" reference panel. -export const SCORING_REFERENCE = [ - { label: 'Single 1', value: '100' }, - { label: 'Single 5', value: '50' }, - { label: 'Three 1s', value: '1000' }, - { label: 'Three 2s', value: '200' }, - { label: 'Three 3s', value: '300' }, - { label: 'Three 4s', value: '400' }, - { label: 'Three 5s', value: '500' }, - { label: 'Three 6s', value: '600' }, - { label: 'Four of a kind', value: '1000' }, - { label: 'Five of a kind', value: '2000' }, - { label: 'Six of a kind', value: '3000' }, - { label: 'Straight 1-6', value: '1500' }, - { label: 'Three pairs', value: '1500' }, -]; +export function normalizeRules(r = {}) { + const out = { ...DEFAULT_RULES, ...r }; + if (!TARGET_OPTIONS.includes(out.target)) out.target = WIN_TARGET; + if (!ENTRY_OPTIONS.includes(out.entry)) out.entry = ON_BOARD_MIN; + for (const k of ['threeFarkle', 'twoTriplets', 'doubling', 'piggyback']) out[k] = !!out[k]; + return out; +} + +// Exact chance that a throw of N dice scores nothing (standard combos). The +// house rules only add combos inside rolls that already score, so these hold. +// tools/verifyFarkel.js re-derives every entry by enumeration. +export const FARKLE_ODDS = Object.freeze({ + 1: 4 / 6, 2: 16 / 36, 3: 60 / 216, 4: 204 / 1296, 5: 600 / 7776, 6: 1080 / 46656, +}); + +// Seat colours (pencil inks on the score pad, seat accents). +export const PLAYER_COLORS = [0x22304f, 0x9c2121, 0x1d6a3c, 0x7a3fa0]; +export const PLAYER_COLOR_HEX = ['#22304f', '#9c2121', '#1d6a3c', '#7a3fa0']; + +const fmt = (n) => n.toLocaleString('en-US'); + +// Rows for the scoring card. `key` matches the part keys from scoreParts(). +export function scoringReference(rules = DEFAULT_RULES) { + const r = normalizeRules(rules); + const rows = [ + { key: 'single1', label: 'Each 1', value: '100' }, + { key: 'single5', label: 'Each 5', value: '50' }, + { key: 'three1', label: 'Three 1s', value: '1,000' }, + { key: 'three2', label: 'Three 2s', value: '200' }, + { key: 'three3', label: 'Three 3s', value: '300' }, + { key: 'three4', label: 'Three 4s', value: '400' }, + { key: 'three5', label: 'Three 5s', value: '500' }, + { key: 'three6', label: 'Three 6s', value: '600' }, + ]; + if (r.doubling) { + rows.push({ key: 'four', label: 'Four of a kind', value: 'triple ×2' }); + rows.push({ key: 'five', label: 'Five of a kind', value: 'triple ×4' }); + rows.push({ key: 'six', label: 'Six of a kind', value: 'triple ×8' }); + } else { + rows.push({ key: 'four', label: 'Four of a kind', value: fmt(1000) }); + rows.push({ key: 'five', label: 'Five of a kind', value: fmt(2000) }); + rows.push({ key: 'six', label: 'Six of a kind', value: fmt(3000) }); + } + rows.push({ key: 'straight', label: 'Straight 1–6', value: fmt(1500) }); + rows.push({ key: 'pairs', label: 'Three pairs*', value: fmt(1500) }); + if (r.twoTriplets) rows.push({ key: 'triplets', label: 'Two triplets', value: fmt(2500) }); + return rows; +} + +// Back-compat for anything that imported the old constant. +export const SCORING_REFERENCE = scoringReference(DEFAULT_RULES); diff --git a/src/games/farkel/FarkelDialogs.js b/src/games/farkel/FarkelDialogs.js new file mode 100644 index 0000000..85dce89 --- /dev/null +++ b/src/games/farkel/FarkelDialogs.js @@ -0,0 +1,193 @@ +// FarkelDialogs.js — lodge pop-ups: a cream card in a pine frame with a plaid +// band. Each opener returns { close() } and swallows clicks beneath it. +// +// openPauseMenu resume · table settings · house rules · log · rules · new · leave +// openRulesDialog target / entry / house rules (take effect in a new game) +// openLogDialog the turn-by-turn ledger +// confirmBox yes / no (also used for resume-or-new) + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { DISPLAY_FONT, SERIF, PRINT_FONT, INK } from './FarkelArt.js'; +import { TARGET_OPTIONS, ENTRY_OPTIONS } from './FarkelData.js'; +import { describeLog, fmtPts } from './FarkelLogic.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(0x7a4e26, 1).fillRoundedRect(x, y, w, h, 14); + g.lineStyle(2, 0xe6c088, 0.7).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 11); + g.fillStyle(0xf8f3e2, 1).fillRoundedRect(x + 12, y + 12, w - 24, h - 24, 8); + // plaid band under the title + g.fillStyle(0x8e1a1a, 1).fillRect(x + 12, y + 70, w - 24, 8); + g.fillStyle(0x140a0a, 0.6); + for (let xx = x + 12; xx < x + w - 12; xx += 16) g.fillRect(xx, y + 70, 8, 8); + 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: '#8e1a1a', 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, onHouseRules, onLog, onRules, onNewGame, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 540, h = 780; + 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, "Gerome's Lodge", 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]); + }], + [() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)], + [() => `Scoring-dice hints: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)], + [() => `Smart pick (whole combos): ${onOff(settings.smartPick)}`, () => onChange('smartPick', !settings.smartPick)], + [() => `Coach (best keep + odds): ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)], + ['House Rules…', () => { hRef.close(); onHouseRules(); }], + ['Turn Log', () => { hRef.close(); onLog(); }], + ['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 + 116 + i * 54, text, () => { + fn(); + if (typeof label === 'function') btn.setLabel(label()); + }, { width: 440, height: 46, fontSize: 17, bg: bg ?? 0x5a3820 }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 40, 'Keys: Space shake & throw · 1–6 pick dice · R roll · B bank · A best keep · C clear · P piggyback · L log · Esc menu', { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: w - 70 }, + }).setOrigin(0.5).setDepth(depth + 1)); + hRef = handle(objs, onClose); + return hRef; +} + +// House rules. Edits a copy; onApply(rules) is called with the result. +export function openRulesDialog(scene, { rules, depth, inGame, onApply, onClose }) { + const r = { ...rules }; + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 600, h = 690; + 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, 'House Rules', depth + 1)); + const cx = x + w / 2; + let hRef = null; + const cycle = (list, v) => list[(list.indexOf(v) + 1) % list.length]; + const rows = [ + [() => `Play to: ${fmtPts(r.target)}`, () => { r.target = cycle(TARGET_OPTIONS, r.target); }, 'First to reach it triggers one final round.'], + [() => `Get on the board: ${r.entry ? fmtPts(r.entry) : 'no minimum'}`, () => { r.entry = cycle(ENTRY_OPTIONS, r.entry); }, 'Points needed in one turn before your first bank.'], + [() => `Three-Farkle penalty: ${onOff(r.threeFarkle)}`, () => { r.threeFarkle = !r.threeFarkle; }, 'A third Farkle in a row costs 1,000.'], + [() => `Two triplets = 2,500: ${onOff(r.twoTriplets)}`, () => { r.twoTriplets = !r.twoTriplets; }, 'Two three-of-a-kinds in one throw.'], + [() => `Doubling kinds: ${onOff(r.doubling)}`, () => { r.doubling = !r.doubling; }, '4/5/6 of a kind = the triple ×2 / ×4 / ×8.'], + [() => `Piggyback: ${onOff(r.piggyback)}`, () => { r.piggyback = !r.piggyback; }, "Ride the last player's leftover dice and total."], + ]; + rows.forEach(([label, fn, hint], i) => { + const by = y + 120 + i * 76; + const btn = new Button(scene, cx, by, label(), () => { fn(); btn.setLabel(label()); }, { + width: 470, height: 46, fontSize: 17, bg: 0x5a3820, + }).setDepth(depth + 2); + objs.push(btn); + objs.push(scene.add.text(cx, by + 32, hint, { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#6f5d45', + }).setOrigin(0.5).setDepth(depth + 1)); + }); + const note = inGame ? 'Rule changes start a new game.' : ''; + if (note) { + objs.push(scene.add.text(cx, y + h - 102, note, { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#8e1a1a' }) + .setOrigin(0.5).setDepth(depth + 1)); + } + objs.push(new Button(scene, cx - 120, y + h - 54, inGame ? 'Apply & New Game' : 'Apply', () => { hRef.close(); onApply?.(r); }, { + width: 220, height: 48, fontSize: 18, bg: 0x22304f, + }).setDepth(depth + 2)); + objs.push(new Button(scene, cx + 120, y + h - 54, 'Cancel', () => hRef.close(), { + width: 220, height: 48, fontSize: 18, bg: 0x5a3820, + }).setDepth(depth + 2)); + hRef = handle(objs, onClose); + return hRef; +} + +// The turn log, newest at the bottom; scrolls with the wheel or the arrows. +export function openLogDialog(scene, { gs, depth, onClose }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 900, h = 820; + 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, 'Turn Log', depth + 1)); + const entries = gs.log.filter((e) => e.kind !== 'roll' || e.farkle); + const LINES = 24, LH = 25; + let top = Math.max(0, entries.length - LINES); + const texts = []; + for (let i = 0; i < LINES; i++) { + texts.push(scene.add.text(x + 44, y + 98 + i * LH, '', { + fontFamily: SERIF, fontSize: '17px', color: '#2b2418', + }).setDepth(depth + 1)); + } + objs.push(...texts); + const turnTag = scene.add.text(x + w - 40, y + 42, '', { fontFamily: PRINT_FONT, fontSize: '13px', color: '#6f5d45' }).setOrigin(1, 0.5).setDepth(depth + 1); + objs.push(turnTag); + const draw = () => { + for (let i = 0; i < LINES; i++) { + const e = entries[top + i]; + if (!e) { texts[i].setText(''); continue; } + const bank = e.kind === 'bank', far = e.kind === 'farkle' || (e.kind === 'roll' && e.farkle); + texts[i].setText(`${String(e.turn).padStart(3, ' ')} ${describeLog(gs, e)}`) + .setColor(far ? '#9c2121' : bank ? INK[e.seat] ?? '#2b2418' : '#2b2418') + .setFontStyle(bank ? 'bold' : 'normal'); + } + turnTag.setText(entries.length ? `${top + 1}–${Math.min(entries.length, top + LINES)} of ${entries.length}` : 'Nothing yet'); + }; + draw(); + const scroll = (d) => { top = Math.max(0, Math.min(Math.max(0, entries.length - LINES), top + d)); draw(); }; + const wheel = (_p, _o, _dx, dy) => scroll(dy > 0 ? 3 : -3); + scene.input.on('wheel', wheel); + let hRef = null; + objs.push(new Button(scene, x + w - 70, y + 120, '▲', () => scroll(-LINES + 2), { width: 60, height: 44, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w - 70, y + h - 140, '▼', () => scroll(LINES - 2), { width: 60, height: 44, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2, y + h - 52, 'Close', () => hRef.close(), { width: 220, height: 48, fontSize: 18, bg: 0x22304f }).setDepth(depth + 2)); + hRef = handle(objs, () => { scene.input.off('wheel', wheel); onClose?.(); }); + return hRef; +} + +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 540, h = 270; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 42, heading, depth + 1, 24)); + objs.push(scene.add.text(x + w / 2, y + 134, 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 - 122, y + h - 50, yes, () => { hRef.close(); onYes?.(); }, { width: 214, height: 46, fontSize: 18, bg: 0x7a2a1a }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 122, y + h - 50, no, () => { hRef.close(); onNo?.(); }, { width: 214, height: 46, fontSize: 18, bg: 0x22304f }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} diff --git a/src/games/farkel/FarkelEndScreen.js b/src/games/farkel/FarkelEndScreen.js new file mode 100644 index 0000000..83c5503 --- /dev/null +++ b/src/games/farkel/FarkelEndScreen.js @@ -0,0 +1,123 @@ +// FarkelEndScreen.js — the after-game card over the dice tray: final standings, +// per-player stats, a score-over-turns chart and the human's personal bests. + +import { Button } from '../../ui/Button.js'; +import { fmtPts } from './FarkelLogic.js'; +import { INK, INK_HEX, DISPLAY_FONT, PRINT_FONT, SERIF, HAND_FONT } from './FarkelArt.js'; +import { frame } from './FarkelDialogs.js'; + +const BEST_KEY = 'farkel-best'; + +// Records the human's best final score and biggest single turn. +export function recordPersonalBest(score, bestTurn) { + let prev = null; + try { prev = JSON.parse(localStorage.getItem(BEST_KEY) || 'null'); } catch (_) { prev = null; } + const today = new Date().toISOString().slice(0, 10); + const next = { + score: Math.max(prev?.score ?? 0, score), + scoreDate: score > (prev?.score ?? -1) ? today : prev?.scoreDate ?? today, + turn: Math.max(prev?.turn ?? 0, bestTurn), + turnDate: bestTurn > (prev?.turn ?? -1) ? today : prev?.turnDate ?? today, + }; + try { localStorage.setItem(BEST_KEY, JSON.stringify(next)); } catch (_) { /* private mode */ } + return { prev, next, newScore: !prev || score > prev.score, newTurn: !prev || bestTurn > (prev.turn ?? 0) }; +} + +export function openEndScreen(scene, { gs, ranks, depth, best, onPlayAgain, onMenu }) { + const objs = []; + const n = gs.players.length; + const w = 1060, rowsH = n * 58; + const chartH = 190; + const h = 150 + rowsH + chartH + 150; + const x = 60 + (1100 - w) / 2, y = Math.max(16, 540 - h / 2); + const shade = scene.add.rectangle(590, 540, 1180, 1080, 0x000000, 0.5).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 the lodge!' : `${gs.players[winner].name} wins`; + objs.push(scene.add.text(x + w / 2, y + 42, head, { fontFamily: DISPLAY_FONT, fontSize: '34px', color: '#8e1a1a' }).setOrigin(0.5).setDepth(depth + 1)); + + const cols = [ + { k: 'rank', x: x + 50, label: '', o: 0.5 }, + { k: 'name', x: x + 96, label: 'PLAYER', o: 0 }, + { k: 'total', x: x + 420, label: 'FINAL', o: 0.5 }, + { k: 'best', x: x + 560, label: 'BEST TURN', o: 0.5 }, + { k: 'avg', x: x + 690, label: 'AVG BANK', o: 0.5 }, + { k: 'hot', x: x + 820, label: 'HOT DICE', o: 0.5 }, + { k: 'far', x: x + 950, label: 'FARKLES', o: 0.5 }, + ]; + const hy = y + 104; + cols.forEach((c) => { + if (!c.label) return; + objs.push(scene.add.text(c.x, hy, c.label, { fontFamily: PRINT_FONT, fontSize: '13px', color: '#6f5d45' }).setOrigin(c.o, 0.5).setDepth(depth + 1)); + }); + order.forEach((p, row) => { + const pl = gs.players[p]; + const st = pl.stats; + const ry = hy + 40 + row * 58; + const ink = INK[p]; + const txt = (c, s, opts = {}) => { + const o = scene.add.text(c.x, ry, s, { fontFamily: HAND_FONT, fontSize: '27px', color: ink, ...opts }).setOrigin(c.o, 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 - 29, w - 60, 1); + objs.push(g); + } + txt(cols[0], ['1st', '2nd', '3rd', '4th'][ranks[p] - 1], { color: ranks[p] === 1 ? '#8e1a1a' : '#6f5d45', fontSize: '23px' }); + txt(cols[1], pl.name.length > 16 ? pl.name.slice(0, 15) + '…' : pl.name); + txt(cols[2], fmtPts(pl.score), { fontSize: '34px' }); + txt(cols[3], st.bestTurn ? fmtPts(st.bestTurn) : '—'); + txt(cols[4], st.banks ? fmtPts(Math.round(st.bankTotal / st.banks / 10) * 10) : '—'); + txt(cols[5], String(st.hotDice)); + txt(cols[6], `${st.farkles}${st.penalties ? ` (−${st.penalties})` : ''}`); + }); + + // score-over-turns chart + const cx0 = x + 90, cy0 = hy + 40 + rowsH, cw = w - 160, ch = chartH - 30; + const g = scene.add.graphics().setDepth(depth + 1); + objs.push(g); + const maxTurns = Math.max(2, ...gs.players.map((p) => p.stats.history.length)); + const maxScore = Math.max(gs.rules.target, ...gs.players.map((p) => p.score)) * 1.05; + const X = (k) => cx0 + (k / (maxTurns - 1)) * cw; + const Y = (v) => cy0 + ch - (Math.max(0, v) / maxScore) * ch; + g.lineStyle(1, 0x6f5d45, 0.5).strokeRect(cx0, cy0, cw, ch); + // target line (dashed) + const ty = Y(gs.rules.target); + g.lineStyle(2, 0x8e1a1a, 0.6); + for (let xx = cx0; xx < cx0 + cw; xx += 18) g.lineBetween(xx, ty, Math.min(cx0 + cw, xx + 10), ty); + objs.push(scene.add.text(cx0 - 8, ty, fmtPts(gs.rules.target), { fontFamily: PRINT_FONT, fontSize: '12px', color: '#8e1a1a' }).setOrigin(1, 0.5).setDepth(depth + 1)); + objs.push(scene.add.text(cx0 - 8, cy0 + ch, '0', { fontFamily: PRINT_FONT, fontSize: '12px', color: '#6f5d45' }).setOrigin(1, 0.5).setDepth(depth + 1)); + objs.push(scene.add.text(cx0 + cw, cy0 + ch + 14, `turn ${maxTurns - 1}`, { fontFamily: PRINT_FONT, fontSize: '12px', color: '#6f5d45' }).setOrigin(1, 0.5).setDepth(depth + 1)); + gs.players.forEach((pl, p) => { + const hist = pl.stats.history; + g.lineStyle(3, INK_HEX[p], 0.9); + g.beginPath(); + hist.forEach((v, k) => { if (k === 0) g.moveTo(X(k), Y(v)); else g.lineTo(X(k), Y(v)); }); + g.strokePath(); + g.fillStyle(INK_HEX[p], 1).fillCircle(X(hist.length - 1), Y(hist[hist.length - 1]), 4); + }); + + const fy = y + h - 104; + const me = gs.players[0]; + const bits = []; + if (best.newScore && best.prev) bits.push(`New best score! ${fmtPts(me.score)} beats ${fmtPts(best.prev.score)}.`); + else bits.push(`Best score: ${fmtPts(best.next.score)}.`); + if (best.newTurn && best.prev && me.stats.bestTurn) bits.push(`New biggest turn: ${fmtPts(me.stats.bestTurn)}!`); + else bits.push(`Biggest turn ever: ${fmtPts(best.next.turn)}.`); + objs.push(scene.add.text(x + w / 2, fy, bits.join(' · '), { + fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: (best.newScore || best.newTurn) && best.prev ? '#8e1a1a' : '#5a4428', + }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(new Button(scene, x + w / 2 - 140, y + h - 52, 'Rematch', 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)); + + 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/farkel/FarkelGame.js b/src/games/farkel/FarkelGame.js index af0147e..e6afa67 100644 --- a/src/games/farkel/FarkelGame.js +++ b/src/games/farkel/FarkelGame.js @@ -1,828 +1,1177 @@ +// FarkelGame.js — Farkle at Gerome's Ski Lodge: a felt dice tray with six real +// 3D dice, a sheepskin-cuffed cup you shake, a "set aside" rail, a clipboard +// score ledger and a chalkboard of scores. +// +// FarkelLogic rules (pure, JSON state) FarkelAI / FarkelSolver opponents 1–5 + Coach +// FarkelLayout every rect (Phaser-free) FarkelArt baked textures +// FarkelTray dice, rail, cup FarkelPad the score ledger +// FarkelDialogs menu / rules / log FarkelEndScreen 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 { playSound, SFX } from '../../ui/Sounds.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { DICE, PIP_POS, PLAYER_COLOR_HEX, SCORING_REFERENCE, ON_BOARD_MIN } from './FarkelData.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { aiTiming, clampSkill, PACE } from '../../ui/cardtable/AITiming.js'; +import { DICE, DEFAULT_RULES, FARKLE_ODDS, normalizeRules, scoringReference } from './FarkelData.js'; +import * as L from './FarkelLogic.js'; +import { planDecision, wantsPiggyback, coachAdvice } from './FarkelAI.js'; import { - createInitialState, rollDice, applySetAside, bank, farkleTurn, - scoreSelection, bestScoring, breakdownScoring, isGameOver, getWinners, -} from './FarkelLogic.js'; -import { decideReroll, nextThinkDelay } from './FarkelAI.js'; + seatParts, TRAY, TRAY_FELT, RAIL_LABEL_Y, RAIL_CHIP, HUMAN_PORTRAIT, HUMAN_NAME, HUMAN_SCORE, HUMAN_HAT, + CUP_MOUTH, THERMO, TURN_TOTAL, STATUS, SUBLINE, TICKER, BTN_BIG, BTN_SMALL, ROLL_BTN, BANK_BTN, BEST_BTN, + CLEAR_BTN, LOG_BTN, MENU_BTN, BANNER, FINAL_RIBBON, PIGGY, CARD, CARD_INNER, CARD_ROW_H, CARD_COLS, + CARD_ROWS_TOP, PAD_ROWS, padColX, padColW, padRowY, PAD_ROW_H, railSlots, humanOrigin, seatOrigin, +} from './FarkelLayout.js'; +import { + prepareFarkelArt, PAD_PX, SEAT_TINT, HAND_FONT, DISPLAY_FONT, PRINT_FONT, SERIF, CHALK, ICE, EMBER, + THERMO_TUBE, +} from './FarkelArt.js'; +import { FarkelTray, FarkelCup } from './FarkelTray.js'; +import { FarkelPad } from './FarkelPad.js'; +import { openPauseMenu, openRulesDialog, openLogDialog, confirmBox } from './FarkelDialogs.js'; +import { openEndScreen, recordPersonalBest } from './FarkelEndScreen.js'; -// ─── Layout ─────────────────────────────────────────────────────────────── -const PORTRAIT_X = 90; -const PORTRAIT_R = 46; -const PORTRAIT_TOP = 210; -const PORTRAIT_GAP = 132; - -const TRAY_CX = 620; -const TRAY_CY = 600; -const TRAY_W = 760; -const TRAY_H = 280; - -const DIE = 96; -const DIE_GAP = 18; -const DICE_ROW_W = DICE * DIE + (DICE - 1) * DIE_GAP; -const DICE_LEFT = TRAY_CX - DICE_ROW_W / 2 + DIE / 2; - -const SHELF_Y = TRAY_CY - TRAY_H / 2 - 64; -const SDIE = 46; -const SDIE_GAP = 12; - -// Right-hand panels -const SCORE_X = 1080; // scoring reference panel -const SCORE_W = 360; -const PAPER_X = 1480; // scratch-paper score sheet -const PAPER_W = 400; -const PANEL_TOP = 110; - -const DEPTH = { - bg: -1, panel: 0, paper: 1, grid: 2, text: 3, - die: 10, dieSel: 11, ui: 20, toast: 60, modal: 70, +const HUMAN = 0; +const SETTINGS_KEY = 'farkel-settings'; +const SAVE_KEY = 'farkel-save-v1'; +const DEFAULT_SETTINGS = { + pace: 'normal', skipAI: false, hints: true, smartPick: true, coach: false, rules: { ...DEFAULT_RULES }, }; +const D = { + bg: 0, seat: 5, tray: 10, cup: 30, hud: 40, pad: 50, card: 50, fx: 80, banner: 85, end: 95, modal: 110, +}; +const fmt = L.fmtPts; -// ─── Display helper ──────────────────────────────────────────────────────────── -function fmtPts(n) { - return n >= 1000 ? `${Math.floor(n / 1000)},${String(n % 1000).padStart(3, '0')}` : String(n); +const SPEECH = { + farkle: ['Farkle! Ugh.', 'Nothing. Nada.', 'Wiped out!', 'Ice under the powder…', 'Yard sale!'], + bigBank: ["I'll take that!", 'Pencil it in!', 'Sweet line.', 'Banked!'], + bank: ["That'll do.", 'Banking.', 'Safe run.', 'Into the lodge.'], + push: ['Let it ride!', 'One more run…', 'Sending it!', 'Come on…'], + hot: ['HOT DICE!', 'All six! Again!', 'Powder day!'], + react: ['No way!', 'Lucky roll!', 'Show-off.', 'Oh, come on!'], + console: ['Ouch.', 'Tough break.', 'Brr.'], + piggy: ["I'll ride that!", "Don't mind if I do.", 'Piggyback!'], + fresh: ['Fresh dice for me.', 'Clean slate.'], + chase: ['Gotta catch you…', 'All or nothing!'], +}; +const pick = (arr) => arr[Math.floor(Math.random() * arr.length)]; + +function loadSettings() { + let s; + try { s = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { s = { ...DEFAULT_SETTINGS }; } + s.rules = normalizeRules(s.rules); + return s; } export default class FarkelGame extends Phaser.Scene { constructor() { super('FarkelGame'); } init(data) { - this.gameDef = data.game; + this.initData = data; + this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; - - this.humanSeat = 0; - this.busy = false; - this.gameOverShown = false; - - this.dieEls = []; // [{ g, hit, cx, cy }] - this.selected = new Set(); // indices into turn.rolled - this.scratchRows = []; // [{ name, score, star }] - this.portraitCtrls = []; + this.ended = false; + this.busy = true; + this.modal = null; + this.selected = new Set(); + this.shaking = false; + this.skipTurn = false; + this.aiTimer = null; + this.bubbles = {}; + this.railLabels = []; + this.settings = loadSettings(); } - create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* optional */ } - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(DEPTH.bg); - this.buildBackground(); + get k() { return PACE[this.settings.pace] ?? 1; } + get aiFast() { return !!this.settings.skipAI || this.skipTurn; } + + create() { + try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch (_) { /* optional */ } + this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x1a0f08).setDepth(-2); - // Players: human seat 0 (skill 5), then AI opponents. const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); const names = []; const skills = {}; for (let seat = 0; seat < playerCount; seat++) { - if (seat === this.humanSeat) { - names.push(auth.user?.username ?? 'You'); - skills[seat] = 5; - } else { + if (seat === HUMAN) { names.push(auth.user?.username ?? 'You'); skills[seat] = 5; } + else { const opp = this.opponents[seat - 1]; - names.push(opp?.name ?? `Player ${seat + 1}`); - skills[seat] = Math.max(1, Math.min(5, opp?.skill ?? 3)); + names.push(opp?.name ?? opp?.id ?? `Player ${seat + 1}`); + skills[seat] = clampSkill(opp?.skill ?? 3); } } - this.gs = createInitialState({ playerCount, names, skills }); + this.n = playerCount; + const save = this.readSave(); + if (this.initData.resume && save) { + this.gs = save.gs; + } else { + this.gs = L.createInitialState({ playerCount, names, skills, rules: this.settings.rules }); + } + this.pendingSave = !this.initData.resume && !this.initData.fresh ? save : null; - this.buildHeader(); - - this.buildTray(); - this.buildDice(); - this.buildShelf(); - this.buildExplainPanel(); - this.buildScoringPanel(); - this.buildScratchPaper(); - this.buildButtons(); - this.buildPortraits(); - - new Button(this, 80, GAME_HEIGHT - 50, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 140, fontSize: 20, + prepareFarkelArt(this, this.n, this.gs.rules.target).then((padOrigin) => { + if (!this.sys.isActive()) return; + this.padOrigin = padOrigin; + this.build(); + if (this.pendingSave) this.offerResume(this.pendingSave); + else this.time.delayedCall(450, () => this.nextTurn()); }); - - this.render(); - this.advance(); } - // ── static chrome ────────────────────────────────────────────────────────── - buildBackground() { + // ── 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); + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg); + this.add.image(0, 0, 'farkel-vignette').setOrigin(0).setDepth(D.bg + 1); + } else { + this.add.image(0, 0, 'farkel-room').setOrigin(0).setDepth(D.bg); } - } + this.buildFire(); + this.buildSeats(); + this.tray = new FarkelTray(this, D.tray, { + onDieClick: (i, ev) => this.onDieClick(i, ev), + onDieHover: (i, on) => this.onDieHover(i, on), + }).build(); + this.frost = this.add.image(TRAY_FELT.x, TRAY_FELT.y, 'farkel-frost').setOrigin(0).setDepth(D.tray + 6).setAlpha(0); + this.cup = new FarkelCup(this, D.cup, { onPress: () => this.beginShake() }).build(); + this.pad = new FarkelPad(this, { players: this.gs.players, depth: D.pad, origin: this.padOrigin }).build(); + this.buildCard(); + this.buildThermo(); + this.buildHud(); + this.buildRibbon(); - buildHeader() { - const titleText = this.add.text(TRAY_CX, 56, 'Farkle', { - fontFamily: 'Righteous', fontSize: '60px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.panel + 1); - this.statusText = this.add.text(TRAY_CX, 128, '', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(DEPTH.panel + 2); + this.tray.layoutState(this.gs.turn); + this.pad.syncFromState(this.gs, { leader: L.leaderSeat(this.gs) }); - // Fixed-size panel (wide enough for longest status messages) - const pw = 680; - const ph = 160; - const panel = this.add.graphics().setDepth(DEPTH.panel + 1); - panel.fillStyle(0x000000, 0.75); - panel.fillRoundedRect(TRAY_CX - pw / 2, 10, pw, ph, 12); - panel.lineStyle(3, COLORS.accent, 1); - panel.strokeRoundedRect(TRAY_CX - pw / 2, 10, pw, ph, 12); - this.headerPanel = panel; - this.headerTitle = titleText; - } - - buildTray() { - // Felt throwing area. - const g = this.add.graphics().setDepth(DEPTH.panel); - g.fillStyle(0x14532d, 1); - g.fillRoundedRect(TRAY_CX - TRAY_W / 2, TRAY_CY - TRAY_H / 2, TRAY_W, TRAY_H, 24); - g.lineStyle(4, COLORS.accent, 1); - g.strokeRoundedRect(TRAY_CX - TRAY_W / 2, TRAY_CY - TRAY_H / 2, TRAY_W, TRAY_H, 24); - - this.turnTotalText = this.add.text(TRAY_CX, TRAY_CY + TRAY_H / 2 + 28, '', { - fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex, - }).setOrigin(0.5); - } - - buildDice() { - for (let i = 0; i < DICE; i++) { - const x = DICE_LEFT + i * (DIE + DIE_GAP); - const y = TRAY_CY; - const g = this.add.graphics().setDepth(DEPTH.die); - const c = this.add.container(x, y, [g]).setDepth(DEPTH.die); - const hit = this.add.zone(x, y, DIE, DIE).setOrigin(0.5).setDepth(DEPTH.dieSel); - hit.setInteractive({ useHandCursor: true }); - hit.on('pointerdown', () => this.onDieClick(i)); - this.dieEls.push({ g, hit, cx: x, cy: y, c }); - } - } - - buildShelf() { - this.shelfGfx = this.add.graphics().setDepth(DEPTH.die); - - // Background panel for the shelf area - const shelfLeft = TRAY_CX - TRAY_W / 2 + 4; - const shelfW = DICE * (SDIE + SDIE_GAP) + 12; - const shelfH = SDIE + 70; - const shelfX = shelfLeft; - const shelfY = SHELF_Y - SDIE / 2 - 46; - const shelfPanel = this.add.graphics().setDepth(DEPTH.die - 1); - shelfPanel.fillStyle(0x000000, 0.55); - shelfPanel.fillRoundedRect(shelfX, shelfY, shelfW, shelfH, 8); - shelfPanel.lineStyle(2, COLORS.accent, 0.6); - shelfPanel.strokeRoundedRect(shelfX, shelfY, shelfW, shelfH, 8); - this.shelfPanel = shelfPanel; - - // Text on top of panel - this.add.text(TRAY_CX - TRAY_W / 2 + 20, SHELF_Y - SDIE / 2 - 24, 'Set aside this turn', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.die); - } - - buildExplainPanel() { - const shelfLeft = TRAY_CX - TRAY_W / 2 + 4; - const shelfW = DICE * (SDIE + SDIE_GAP) + 12; - const shelfH = SDIE + 70; - const shelfY = SHELF_Y - SDIE / 2 - 46; - - const ex = shelfLeft + shelfW + 10; - const ew = TRAY_CX + TRAY_W / 2 - ex - 4; - const ey = shelfY; - const eh = shelfH; - - const bg = this.add.graphics().setDepth(DEPTH.die - 1); - bg.fillStyle(0x000000, 0.55); - bg.fillRoundedRect(ex, ey, ew, eh, 8); - bg.lineStyle(2, COLORS.accent, 0.6); - bg.strokeRoundedRect(ex, ey, ew, eh, 8); - - this.add.text(ex + 14, ey + 16, 'If you bank:', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.accentHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.die); - - this._explainBounds = { ex, ew, ey, eh }; - this._explainLines = []; - for (let i = 0; i < 4; i++) { - this._explainLines.push( - this.add.text(ex + 14, ey + 34 + i * 20, '', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, - }).setOrigin(0, 0).setDepth(DEPTH.die), - ); - } - } - - buildScoringPanel() { - const rows = SCORING_REFERENCE.length; - const rowH = 40; - const h = 64 + rows * rowH + 16; - this.add.rectangle(SCORE_X + SCORE_W / 2, PANEL_TOP + h / 2, SCORE_W, h, COLORS.panel) - .setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.panel); - this.add.text(SCORE_X + SCORE_W / 2, PANEL_TOP + 34, 'Scoring', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.text); - - let y = PANEL_TOP + 76; - for (const row of SCORING_REFERENCE) { - this.add.text(SCORE_X + 22, y, row.label, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.text); - this.add.text(SCORE_X + SCORE_W - 22, y, row.value, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(1, 0.5).setDepth(DEPTH.text); - y += rowH; - } - } - - buildScratchPaper() { - const N = this.gs.players.length; - const headH = 70; - const rowH = 96; - const h = headH + N * rowH + 24; - const top = PANEL_TOP; - - // Paper sheet. - const g = this.add.graphics().setDepth(DEPTH.paper); - g.fillStyle(0xf3ecd2, 1); - g.fillRoundedRect(PAPER_X, top, PAPER_W, h, 10); - g.lineStyle(2, 0xbfae82, 1); - g.strokeRoundedRect(PAPER_X, top, PAPER_W, h, 10); - // Ruled lines + red margin. - g.lineStyle(1, 0x9bb7d4, 0.5); - for (let ly = top + headH; ly < top + h - 10; ly += 32) { - g.beginPath(); g.moveTo(PAPER_X + 12, ly); g.lineTo(PAPER_X + PAPER_W - 12, ly); g.strokePath(); - } - g.lineStyle(2, 0xcf6b5e, 0.7); - g.beginPath(); g.moveTo(PAPER_X + 56, top + 10); g.lineTo(PAPER_X + 56, top + h - 10); g.strokePath(); - - this.add.text(PAPER_X + PAPER_W / 2, top + 36, 'Score Pad', { - fontFamily: 'YummyCupcakes', fontSize: '40px', color: '#2a2418', - }).setOrigin(0.5).setDepth(DEPTH.text); - - let y = top + headH + 30; - for (let seat = 0; seat < N; seat++) { - const colorHex = PLAYER_COLOR_HEX[seat] ?? '#2a2418'; - const name = this.add.text(PAPER_X + 72, y, this.gs.players[seat].name, { - fontFamily: 'YummyCupcakes', fontSize: '34px', color: colorHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.text); - const star = this.add.text(PAPER_X + 70, y - 34, '★', { - fontFamily: 'YummyCupcakes', fontSize: '24px', color: '#d4a017', - }).setOrigin(0, 0.5).setDepth(DEPTH.text).setVisible(false); - const score = this.add.text(PAPER_X + PAPER_W - 22, y, '0', { - fontFamily: 'YummyCupcakes', fontSize: '40px', color: '#2a2418', - }).setOrigin(1, 0.5).setDepth(DEPTH.text); - this.scratchRows.push({ name, score, star, y }); - y += rowH; - } - this.scratchUnderline = this.add.graphics().setDepth(DEPTH.grid); - this._paperTop = top; - this._paperHeadH = headH; - this._paperRowH = rowH; - } - - buildButtons() { - const y = TRAY_CY + TRAY_H / 2 + 86; - this.rollBtn = new Button(this, TRAY_CX - 220, y, 'Roll', () => this.onRoll(), { width: 220, fontSize: 26 }); - this.scoreAllBtn = new Button(this, TRAY_CX, y, 'Score All', () => this.onScoreAll(), { width: 200, fontSize: 24, variant: 'ghost' }); - this.bankBtn = new Button(this, TRAY_CX + 220, y, 'Bank', () => this.onBank(), { width: 220, fontSize: 26 }); - } - - buildPortraits() { - const N = this.gs.players.length; - for (let seat = 0; seat < N; seat++) { - const py = PORTRAIT_TOP + seat * PORTRAIT_GAP; - const ring = this.add.graphics().setDepth(DEPTH.ui); - let ctrl; - if (seat === this.humanSeat) { - ctrl = createPlayerPortrait(this, PORTRAIT_X, py, PORTRAIT_R, DEPTH.ui, 'FarkelGame'); - } else { - const opp = this.opponents[seat - 1] ?? { id: 'bot', spriteIndex: 0 }; - ctrl = createOpponentPortrait(this, opp, PORTRAIT_X, py, PORTRAIT_R, DEPTH.ui); + this.input.on('pointerup', () => this.releaseShake()); + this.input.on('pointerdown', (ptr) => { + // click the tray during an opponent's turn to hurry it along + if (this.gs.current !== HUMAN && !this.ended && !this.modal + && ptr.x >= TRAY.x && ptr.x <= TRAY.x + TRAY.w && ptr.y >= TRAY.y && ptr.y <= TRAY.y + TRAY.h + 150) { + if (!this.skipTurn) { this.skipTurn = true; this.flashSub('Hurrying along…'); } } - this.portraitCtrls.push({ ring, controller: ctrl, x: PORTRAIT_X, y: py }); - this.add.text(PORTRAIT_X, py + PORTRAIT_R + 16, this.gs.players[seat].name, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, - }).setOrigin(0.5); + }); + 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(); + } + + // A soft, flickering fireside glow from the lower-left corner. + buildFire() { + const g = this.add.graphics({ x: -40, y: GAME_HEIGHT + 40 }).setDepth(D.bg + 2).setBlendMode(Phaser.BlendModes.ADD); + for (let i = 8; i >= 1; i--) g.fillStyle(0xff8a3a, 0.018 * (9 - i)).fillCircle(0, 0, 70 * i); + this.tweens.add({ targets: g, alpha: { from: 0.75, to: 1 }, duration: 380, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.time.addEvent({ delay: 1700, loop: true, callback: () => g.setScale(0.96 + Math.random() * 0.08) }); + } + + buildSeats() { + const nOpp = this.n - 1; + this.seats = []; + this.portraits = []; + 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, 'FarkelGame'); + const nm = this.gs.players[HUMAN].name; + this.add.text(HUMAN_NAME.x, HUMAN_NAME.y, nm.length > 12 ? nm.slice(0, 11) + '…' : nm, { + fontFamily: HAND_FONT, fontSize: '24px', color: '#f3e6c4', + }).setOrigin(0.5).setDepth(D.hud); + this.humanScore = this.add.text(HUMAN_SCORE.x, HUMAN_SCORE.y, '', { + fontFamily: HAND_FONT, fontSize: '26px', color: '#ffd98a', + }).setOrigin(0.5).setDepth(D.hud); + this.humanHat = this.add.image(HUMAN_HAT.x, HUMAN_HAT.y, 'farkel-hat').setDepth(D.hud + 3).setAngle(-14).setVisible(false); + + 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, 'farkel-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.score.x, s.score.y, '0', { + fontFamily: HAND_FONT, fontSize: '30px', color: Phaser.Display.Color.IntegerToColor(SEAT_TINT[p]).rgba, + }).setOrigin(0, 0.5).setDepth(D.seat + 1); + const line = this.add.text(s.line.x, s.line.y, '', { + fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#e8d3a6', + }).setOrigin(0, 0.5).setDepth(D.seat + 1); + const sk = this.gs.players[p].skill; + this.add.text(s.rect.x + s.rect.w - 14, s.name.y, '●'.repeat(sk) + '○'.repeat(5 - sk), { + fontFamily: SERIF, fontSize: '12px', color: '#d6aa60', + }).setOrigin(1, 0.5).setDepth(D.seat + 1); + const hat = this.add.image(s.portrait.x + 34, s.portrait.y - 44, 'farkel-hat').setDepth(D.seat + 4).setAngle(14).setVisible(false); + this.seats[p] = { ...s, ring, score, line, hat }; } } - // ── rendering ──────────────────────────────────────────────────────────────── - render() { - this.renderDice(); - this.renderShelf(); - this.renderScratch(); - this.updatePortraitRing(); - this.updateStatus(); - this.updateTurnTotal(); - this.updateControls(); - this.updateExplainPanel(); + buildCard() { + this.add.image(CARD.x - PAD_PX, CARD.y - PAD_PX, 'farkel-card').setOrigin(0).setDepth(D.card); + const r = this.gs.rules; + this.add.text(CARD_INNER.x + CARD_INNER.w / 2, CARD_INNER.y + 26, 'LODGE SCORING', { + fontFamily: HAND_FONT, fontSize: '32px', color: CHALK, + }).setOrigin(0.5).setDepth(D.card + 2).setAlpha(0.92); + this.cardHl = this.add.graphics().setDepth(D.card + 1); + const rows = scoringReference(r); + const perCol = Math.ceil(rows.length / 2); + this.cardRows = rows.map((row, i) => { + const col = CARD_COLS[i < perCol ? 0 : 1]; + const y = CARD_ROWS_TOP + (i % perCol) * CARD_ROW_H; + const a = this.add.text(col.x, y, row.label, { fontFamily: HAND_FONT, fontSize: '24px', color: CHALK }).setOrigin(0, 0.5).setDepth(D.card + 2).setAlpha(0.85); + const b = this.add.text(col.x + col.w, y, row.value, { fontFamily: HAND_FONT, fontSize: '24px', color: '#ffe9a6' }).setOrigin(1, 0.5).setDepth(D.card + 2).setAlpha(0.9); + return { ...row, x: col.x, w: col.w, y, a, b }; + }); + const notes = [`to ${fmt(r.target)}`, r.entry ? `${fmt(r.entry)} to get on` : 'no entry minimum']; + if (r.threeFarkle) notes.push('3 Farkles −1,000'); + if (r.piggyback) notes.push('piggyback'); + this.add.text(CARD_INNER.x + CARD_INNER.w / 2, CARD_INNER.y + CARD_INNER.h - 18, `* incl. 4 of a kind + a pair · ${notes.join(' · ')}`, { + fontFamily: HAND_FONT, fontSize: '17px', color: CHALK, + }).setOrigin(0.5).setDepth(D.card + 2).setAlpha(0.6); } - drawDie(g, x, y, size, face, { selected = false, locked = false } = {}) { + buildThermo() { + this.add.image(THERMO.x - 12, THERMO.y - 12, 'farkel-thermo').setOrigin(0).setDepth(D.hud); + this.thermoG = this.add.graphics().setDepth(D.hud + 1); + this.thermoText = this.add.text(THERMO.x + THERMO.w / 2, THERMO.y + 46, '', { + fontFamily: PRINT_FONT, fontSize: '13px', color: '#fff2d6', + }).setOrigin(0.5).setDepth(D.hud + 2); + this.thermoShown = 0; + } + + buildHud() { + this.turnTotalText = this.add.text(TURN_TOTAL.x, TURN_TOTAL.y, '', { + fontFamily: DISPLAY_FONT, fontSize: '40px', color: '#ffd98a', stroke: '#2a1408', strokeThickness: 6, + }).setOrigin(0.5).setDepth(D.hud); + this.statusText = this.add.text(STATUS.x, STATUS.y, '', { + fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#f3e6c4', stroke: '#1a0c04', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.hud); + this.subText = this.add.text(SUBLINE.x, SUBLINE.y, '', { + fontFamily: SERIF, fontSize: '17px', color: '#f0dcb0', align: 'center', wordWrap: { width: STATUS.w }, + stroke: '#1a0c04', strokeThickness: 3, + }).setOrigin(0.5, 0).setDepth(D.hud); + this.tickerText = this.add.text(TICKER.x, TICKER.y, '', { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#d8c4a0', align: 'center', + stroke: '#1a0c04', strokeThickness: 3, + }).setOrigin(0.5).setDepth(D.hud); + + const big = { width: BTN_BIG.w, height: BTN_BIG.h, fontSize: 19 }; + const small = { width: BTN_SMALL.w, height: BTN_SMALL.h, fontSize: 15 }; + this.rollBtn = new Button(this, ROLL_BTN.x, ROLL_BTN.y, 'Roll', () => this.onRollButton(), { ...big, bg: 0x1d5135 }).setDepth(D.hud); + this.bankBtn = new Button(this, BANK_BTN.x, BANK_BTN.y, 'Bank', () => this.onBank(), { ...big, bg: 0x8e1a1a }).setDepth(D.hud); + this.bestBtn = new Button(this, BEST_BTN.x, BEST_BTN.y, 'Best (A)', () => this.onBest(), { ...small, bg: 0x5a3820 }).setDepth(D.hud); + this.clearBtn = new Button(this, CLEAR_BTN.x, CLEAR_BTN.y, 'Clear (C)', () => this.onClear(), { ...small, bg: 0x5a3820 }).setDepth(D.hud); + this.logBtn = new Button(this, LOG_BTN.x, LOG_BTN.y, 'Log (L)', () => this.openLog(), { ...small, bg: 0x3a2412 }).setDepth(D.hud); + this.menuBtn = new Button(this, MENU_BTN.x, MENU_BTN.y, 'Menu', () => this.openMenu(), { ...small, bg: 0x3a2412 }).setDepth(D.hud); + + this.railChip = this.add.text(RAIL_CHIP.x, RAIL_LABEL_Y, '', { + fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#ffd98a', align: 'center', + }).setOrigin(0.5).setDepth(D.tray + 4); + } + + buildRibbon() { + const R = FINAL_RIBBON; + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.35).fillRect(-R.w / 2 + 4, -R.h / 2 + 5, R.w, R.h); + g.fillStyle(0x8e1a1a, 1).fillRect(-R.w / 2, -R.h / 2, R.w, R.h); + g.fillTriangle(-R.w / 2 - 26, -R.h / 2, -R.w / 2, -R.h / 2, -R.w / 2, R.h / 2); + g.fillTriangle(-R.w / 2 - 26, R.h / 2, -R.w / 2, -R.h / 2, -R.w / 2, R.h / 2); + g.fillTriangle(R.w / 2 + 26, -R.h / 2, R.w / 2, -R.h / 2, R.w / 2, R.h / 2); + g.fillTriangle(R.w / 2 + 26, R.h / 2, R.w / 2, -R.h / 2, R.w / 2, R.h / 2); + g.lineStyle(2, 0xffd98a, 0.8).strokeRect(-R.w / 2 + 4, -R.h / 2 + 4, R.w - 8, R.h - 8); + this.ribbonText = this.add.text(0, 0, '', { fontFamily: DISPLAY_FONT, fontSize: '20px', color: '#fff2d6' }).setOrigin(0.5); + this.ribbon = this.add.container(R.x, R.y, [g, this.ribbonText]).setDepth(D.banner - 1).setVisible(false); + } + + // ── HUD refresh ───────────────────────────────────────────────────────────── + refreshHud() { + if (!this.tray) return; + const gs = this.gs; + const over = L.isGameOver(gs); + const leader = L.leaderSeat(gs); + const t = gs.turn; + for (let p = 1; p < this.n; p++) { + const s = this.seats[p]; + const pl = gs.players[p]; + s.ring.clear(); + const cur = p === gs.current && !over; + if (cur) { + 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(fmt(pl.score)); + s.hat.setVisible(leader === p); + let line = pl.onBoard ? 'on the board ✓' : `needs ${fmt(gs.rules.entry)} to get on`; + if (gs.rules.entry === 0) line = ''; + if (cur && !this.bubbles[p]) line = t.kept > 0 ? `this turn: ${fmt(t.kept)}` : 'rolling…'; + if (gs.rules.threeFarkle && pl.farkleStreak > 0 && !cur) line = `${'F '.repeat(pl.farkleStreak).trim()} · ${line}`; + s.line.setText(this.bubbles[p] ? '' : line); + } + this.humanRing.clear(); + if (gs.current === HUMAN && !over) { + this.humanRing.lineStyle(4, 0xf5d020, 1).strokeCircle(HUMAN_PORTRAIT.x, HUMAN_PORTRAIT.y, HUMAN_PORTRAIT.r + 6); + } + const me = gs.players[HUMAN]; + this.humanScore.setText(`${fmt(me.score)}${me.onBoard || !gs.rules.entry ? '' : ' ·'}`); + this.humanHat.setVisible(leader === HUMAN); + this.pad.setActive(over ? null : gs.current); + this.refreshTurnView(); + this.refreshRibbon(); + const lines = gs.log.filter((e) => e.kind !== 'roll').slice(-2).map((e) => L.describeLog(gs, e)); + this.tickerText.setText(lines.join('\n')); + this.refreshControls(); + } + + // Everything that follows the current selection: turn total, rail, chalk + // highlights, risk gauge, ledger preview. + refreshTurnView() { + const gs = this.gs; + const t = gs.turn; + const over = L.isGameOver(gs); + const sel = this.selectionInfo(); + let txt = ''; + if (!over && (t.kept > 0 || sel.valid)) { + txt = `TURN ${fmt(t.kept)}`; + if (sel.valid) txt += ` +${fmt(sel.points)}`; + } + this.turnTotalText.setText(txt); + this.pad.setPreview(over ? null : gs.current, t.kept + (sel.valid ? sel.points : 0)); + // rail chip: points carried from earlier cycles (hot dice) or a piggyback + const cyc = t.groups.filter((g) => g.cycle === t.cycle); + const carried = t.kept - cyc.reduce((s, g) => s + g.points, 0); + if (!over && carried > 0 && this.railCarry !== false) { + const label = t.piggy && t.cycle === 0 ? 'PIGGYBACK' : `HOT DICE ×${t.cycle}`; + this.railChip.setText(`${label}\n+${fmt(carried)}`).setVisible(true); + } else this.railChip.setVisible(false); + // chalk highlights + const keys = new Set((sel.valid ? sel.parts : []).map((p) => p.key)); + this.cardHl.clear(); + for (const row of this.cardRows) { + const on = keys.has(row.key); + row.a.setAlpha(on ? 1 : 0.85).setColor(on ? '#ffe36a' : CHALK); + if (on) { + this.cardHl.lineStyle(2, 0xffe36a, 0.85).strokeRoundedRect(row.x - 10, row.y - CARD_ROW_H / 2 + 3, row.w + 20, CARD_ROW_H - 6, 8); + this.cardHl.fillStyle(0xffe36a, 0.08).fillRoundedRect(row.x - 10, row.y - CARD_ROW_H / 2 + 3, row.w + 20, CARD_ROW_H - 6, 8); + } + } + // risk gauge + let n = null; + if (!over) { + if (gs.phase === 'awaitRoll' || gs.phase === 'awaitDecision') n = t.available; + else if (gs.phase === 'awaitPick' && sel.valid) n = t.rolled.length - this.selected.size || DICE; + } + this.setThermo(n); + } + + setThermo(n) { + const target = n ? FARKLE_ODDS[n] : 0; + if (this.thermoTween) this.thermoTween.stop(); + const prox = { v: this.thermoShown }; + this.thermoTween = this.tweens.add({ + targets: prox, v: target, duration: 380, ease: 'Cubic.Out', + onUpdate: () => { this.thermoShown = prox.v; this.drawThermo(); }, + }); + this.thermoText.setText(n ? `${Math.round(target * 100)}%` : '—'); + this.thermoDice = n; + } + drawThermo() { + const g = this.thermoG; + const T = THERMO_TUBE; + const v = Math.min(0.7, this.thermoShown); + const k = v / 0.7; + const col = Phaser.Display.Color.Interpolate.ColorWithColor( + Phaser.Display.Color.ValueToColor(0x58b4ff), Phaser.Display.Color.ValueToColor(0xe0332a), 100, Math.round(k * 100)); + const c = Phaser.Display.Color.GetColor(col.r, col.g, col.b); g.clear(); - this.paintDie(g, x, y, size, face, { selected, locked }); + g.fillStyle(c, 1).fillCircle(T.x, T.bottom + 10, T.bulb); + const top = T.bottom - k * (T.bottom - T.top); + g.fillRoundedRect(T.x - T.w / 2 + 3, top, T.w - 6, T.bottom + 10 - top, 4); + g.fillStyle(0xffffff, 0.35).fillCircle(T.x - 5, T.bottom + 4, 4); } - paintDie(g, x, y, size, face, { selected = false, locked = false } = {}) { - const half = size / 2; - const r = size * 0.14; - g.fillStyle(locked ? 0xe6dcc2 : 0xf2ead8, 1); - g.fillRoundedRect(x - half, y - half, size, size, r); - let bc = COLORS.muted, bw = 2; - if (selected) { bc = COLORS.gold; bw = 5; } - else if (locked) { bc = COLORS.accent; bw = 2; } - g.lineStyle(bw, bc, 1); - g.strokeRoundedRect(x - half, y - half, size, size, r); - g.fillStyle(0x1a1208, 1); - const pipR = Math.max(4, size * 0.094); - const off = size * 0.28; - for (const [cx, cy] of (PIP_POS[face] ?? [])) { - g.fillCircle(x + cx * off, y + cy * off, pipR); + refreshRibbon() { + const gs = this.gs; + if (!gs.finalRound || L.isGameOver(gs)) { this.ribbon.setVisible(false); return; } + const need = L.finalRoundNeed(gs); + const cur = gs.players[gs.current]; + let txt; + if (gs.current === HUMAN) txt = need > 0 ? `FINAL ROUND · you need ${fmt(need)} this turn` : 'FINAL ROUND · you lead — bank anything to stay ahead'; + else txt = need > 0 ? `FINAL ROUND · ${cur.name} needs ${fmt(need)}` : `FINAL ROUND · ${cur.name} leads`; + this.ribbonText.setText(txt); + this.ribbon.setVisible(true); + } + + refreshControls() { + if (!this.rollBtn) return; + const gs = this.gs; + const human = gs.current === HUMAN && !this.busy && !this.ended && !this.modal && !L.isGameOver(gs); + const sel = this.selectionInfo(); + const t = gs.turn; + let rollOn = false, bankOn = false, rollLabel = 'Roll', bankLabel = 'Bank'; + if (gs.phase === 'awaitRoll') { + rollOn = human; + rollLabel = `Roll ${t.available} ${t.available === 1 ? 'die' : 'dice'} (R)`; + } else if (gs.phase === 'awaitPick') { + const left = t.rolled.length - this.selected.size; + rollOn = human && sel.valid; + rollLabel = sel.valid ? (left === 0 ? 'HOT DICE! Roll 6 (R)' : `Keep & roll ${left} (R)`) : 'Pick dice to keep'; + const total = t.kept + (sel.valid ? sel.points : 0); + const allowed = sel.valid && L.bankAllowed(gs, total); + bankOn = human && allowed; + if (sel.valid && !allowed && !gs.players[gs.current].onBoard) bankLabel = `Need ${fmt(gs.rules.entry)} to bank`; + else if (sel.valid) bankLabel = `Bank ${fmt(total)} (B)`; + } + this.rollBtn.setEnabled(rollOn); this.rollBtn.setLabel(rollLabel); + this.bankBtn.setEnabled(bankOn); this.bankBtn.setLabel(bankLabel); + this.bestBtn.setEnabled(human && gs.phase === 'awaitPick'); + this.clearBtn.setEnabled(human && gs.phase === 'awaitPick' && this.selected.size > 0); + this.logBtn.setEnabled(!this.modal); + this.menuBtn.setEnabled(!this.modal && !this.shaking); + this.cup.setEnabled(human && this.canShake()); + } + + setStatus(main, sub = '') { + this.statusText.setScale(1).setText(main); + if (this.statusText.width > STATUS.w) this.statusText.setScale(STATUS.w / this.statusText.width); + this.subText.setText(sub); + } + flashSub(text) { + const prev = this.subText.text; + this.subText.setText(text); + this.time.delayedCall(1200, () => { if (this.subText.text === text) this.subText.setText(prev); }); + } + + // ── selection ─────────────────────────────────────────────────────────────── + selectionInfo() { + const t = this.gs.turn; + if (this.gs.phase !== 'awaitPick' || !this.selected.size) return { valid: false, points: 0, parts: [] }; + const vals = [...this.selected].map((i) => t.rolled[i]); + return L.scoreParts(vals, this.gs.rules); + } + + onDieClick(i, ev) { + if (this.busy || this.ended || this.modal || this.gs.current !== HUMAN || this.gs.phase !== 'awaitPick') return; + if (i >= this.gs.turn.rolled.length) return; + if (this.selected.has(i)) this.selected.delete(i); + else if (this.settings.smartPick && !ev?.shiftKey) { + L.smartGroup(this.gs.turn.rolled, i, this.gs.rules).forEach((k) => this.selected.add(k)); + } else this.selected.add(i); + playSoundEx(this, SFX.PIECE_CLICK, { volume: 0.5, rate: 1.2 }); + this.refreshPick(); + } + + onDieHover(i, on) { + if (!this.tray || this.gs.current !== HUMAN) return; + this.tray.setDecor({ hover: on ? i : -1 }); + } + + onBest() { + if (this.busy || this.ended || this.modal || this.gs.current !== HUMAN || this.gs.phase !== 'awaitPick') return; + this.selected = new Set(L.bestScoring(this.gs.turn.rolled, this.gs.rules).indices); + playSoundEx(this, SFX.PIECE_CLICK, { volume: 0.5, rate: 1.2 }); + this.refreshPick(); + } + + onClear() { + if (this.busy || this.ended || this.modal || this.gs.current !== HUMAN || !this.selected.size) return; + this.selected.clear(); + playSoundEx(this, SFX.PIECE_CLICK, { volume: 0.4, rate: 0.9 }); + this.refreshPick(); + } + + // Human picking: decorate dice and explain the selection. + refreshPick() { + const gs = this.gs; + const t = gs.turn; + const human = gs.current === HUMAN; + const hints = human && this.settings.hints ? L.scoringMask(t.rolled, gs.rules) : null; + let coach = null; + let main, sub; + const sel = this.selectionInfo(); + if (human) { + const adv = this.settings.coach ? coachAdvice(gs, [...this.selected]) : null; + if (adv) coach = adv.best.indices; + if (!this.selected.size) { + main = 'Pick dice to keep'; + sub = this.settings.smartPick + ? 'Click a die to take its whole combo (Shift-click for one die), or press Best.' + : 'Click the scoring dice (or 1–6) you want to set aside, or press Best.'; + } else if (!sel.valid) { + main = "Those dice don't all score"; + sub = 'Every kept die must be part of a combo from this throw.'; + } else { + const left = t.rolled.length - this.selected.size; + const total = t.kept + sel.points; + main = `+${fmt(sel.points)} · ${sel.parts.map((p) => p.label).join(' + ')}`; + sub = left === 0 ? `Hot dice! Turn total ${fmt(total)} — roll all six again, or bank.` + : `Turn total ${fmt(total)} · ${left} ${left === 1 ? 'die' : 'dice'} left (${Math.round(FARKLE_ODDS[left] * 100)}% Farkle risk)`; + if (!L.bankAllowed(gs, total)) sub += ` · need ${fmt(gs.rules.entry)} to get on the board`; + } + const need = L.finalRoundNeed(gs); + if (need > 0 && sel.valid && t.kept + sel.points < need) sub = `Final round: ${fmt(need - t.kept - sel.points)} more needed before banking can win.`; + if (adv) { + const keep = adv.best.indices.map((i) => t.rolled[i]).join('·'); + const verdict = adv.mode === 'reach' + ? `${Math.round(adv.rollValue * 100)}% to make it if you roll on` + : adv.recommend === 'bank' ? `bank ${fmt(adv.total)}` : `roll on (worth ≈ ${fmt(Math.round(adv.rollValue / 10) * 10)})`; + const mine = adv.mine && adv.regret > 1 ? ' · the blue dice play better' : ''; + sub = `Coach: keep ${keep}, then ${verdict}${mine}`; + } + this.setStatus(main, sub); + } + this.tray.setDecor({ selected: new Set(this.selected), hints, coach }); + this.refreshHud(); + } + + // ── turn flow ─────────────────────────────────────────────────────────────── + nextTurn() { + if (this.ended) return; + if (L.isGameOver(this.gs)) { this.finishGame(); return; } + this.saveGame(); + this.selected.clear(); + this.skipTurn = false; + this.railCarry = true; + this.tray.clearDecor(); + this.tray.layoutState(this.gs.turn); + this.updateRailLabels([]); + this.pad.syncFromState(this.gs, { leader: L.leaderSeat(this.gs) }); + this.refreshHud(); + if (this.gs.players[this.gs.current].isAI) this.aiTurn(); + else this.humanTurnStart(); + } + + humanTurnStart() { + this.busy = false; + this.tray.setEnabled(false); + const gs = this.gs; + const me = gs.players[HUMAN]; + let sub = 'Shake the cup (press and hold it, or Space) or press Roll.'; + if (!me.onBoard && gs.rules.entry) sub = `You need ${fmt(gs.rules.entry)} in one turn to get on the board. ${sub}`; + this.setStatus('Your turn', sub); + if (gs.piggyOffer) this.showPiggy(); + this.refreshHud(); + } + + canShake() { + const gs = this.gs; + if (this.ended || this.busy || this.modal || this.shaking || gs.current !== HUMAN) return false; + return gs.phase === 'awaitRoll' || (gs.phase === 'awaitPick' && this.selectionInfo().valid); + } + + beginShake() { + if (!this.canShake()) return; + this.shaking = true; + this.busy = true; + this.hidePiggy(); + this.tray.setEnabled(false); + this.refreshControls(); + const commit = this.gs.phase === 'awaitPick' ? this.commitSelection(HUMAN) : Promise.resolve(); + this.prepThrow = commit.then(() => (this.ended ? null : this.tray.scoopTray(CUP_MOUTH, 220))); + this.cup.startShake(); + this.setStatus('Shaking…', 'Let go to throw.'); + } + + async releaseShake() { + if (!this.shaking) return; + this.shaking = false; + const extra = Math.max(0, 320 - this.cup.shakeTime()); + await Promise.all([this.prepThrow, this.wait(extra)]); + if (this.ended) return; + await this.cup.pour(); + await this.doThrow(humanOrigin(), { fast: false, speed: 1 }); + if (this.ended) return; + await this.afterThrow(HUMAN); + } + + onRollButton() { + if (!this.canShake()) return; + this.beginShake(); + this.time.delayedCall(420, () => this.releaseShake()); + } + + // RNG first: roll in the engine, then animate the dice onto those faces. + async doThrow(origin, { fast, speed }) { + L.rollDice(this.gs, Math.random); + this.tray.setDecor({ dimAll: false, selected: new Set(), hints: null, coach: null }); + this.refreshHud(); + await this.tray.throwDice(this.gs.turn.rolled.slice(), origin, { fast, speed }); + } + + // After any throw: Farkle, or a flourish for a big throw. + async afterThrow(p) { + if (this.ended) return; + if (this.gs.phase === 'farkled') { await this.farkle(p); return; } + this.throwFlourish(p); + if (p === HUMAN) { + this.busy = false; + this.selected.clear(); + this.tray.setEnabled(true); + this.refreshPick(); } } - // Catan-style dice throw animation - animateDice(values) { - return new Promise((resolve) => { - playSound(this, SFX.DICE_ROLL); + throwFlourish(p) { + const rolled = this.gs.turn.rolled; + const best = L.scoreParts(rolled, this.gs.rules); + let label = null, color = 0xffd98a; + const whole = best.valid && best.parts.length === 1 && best.parts[0].count === 6 ? best.parts[0] : null; + if (whole) { label = `${whole.label}!`; color = 0x9fe0ff; } + else { + const c = L.countsOf(rolled); + const big = [1, 2, 3, 4, 5, 6].find((v) => c[v] >= 4); + if (big) label = `${['', '', '', '', 'Four', 'Five', 'Six'][c[big]]} ${big}s!`; + else if (c[1] >= 3) label = 'Three 1s!'; + } + if (!label) return; + this.flourish(label, color); + this.tray.rollHop(26, 340); + if (p === HUMAN) this.reactOthers(SPEECH.react, 0.4); + else if (Math.random() < 0.5) this.say(p, pick(['Look at that!', 'Oh yeah!', 'Read it and weep!'])); + } - const n = values.length; // only animate the dice actually being rolled - const landX = this.dieEls.slice(0, n).map((el) => el.cx); - const landY = TRAY_CY; - const startX = TRAY_CX; - const startY = TRAY_CY + 120; - const arcY = TRAY_CY - 200; + // Commit the selection: dice slide to the rail; hot dice celebrate and come back. + commitSelection(p) { + const gs = this.gs; + const idx = [...this.selected]; + const before = gs.turn.cycle; + const res = L.applySetAside(gs, idx); + this.selected.clear(); + if (!res) return Promise.resolve(); + const groups = gs.turn.groups.filter((g) => g.cycle === before); + const sizes = groups.map((g) => g.dice.length); + this.railCarry = !res.hot; + this.refreshHud(); + const fast = p !== HUMAN && this.aiFast; + return (async () => { + await this.tray.keepToRail(idx, sizes, fast ? 120 : 300); + if (this.ended) return; + this.updateRailLabels(groups); + if (res.hot) await this.hotDice(p); + this.railCarry = true; + this.refreshHud(); + })(); + } - // Hide unused dice containers - for (let i = n; i < DICE; i++) this.dieEls[i].c.setVisible(false); - - // Move rolling dice to throw origin, small, random angle - for (let i = 0; i < n; i++) { - const el = this.dieEls[i]; - el.c.setVisible(true).setAlpha(0.25).setScale(0.35).setAngle(Phaser.Math.Between(0, 359)) - .setPosition(startX + (i - (n - 1) / 2) * 18, startY); - this.drawDie(el.g, 0, 0, DIE, Phaser.Math.Between(1, 6)); - } - - // Cycle random faces while airborne - let cyclerStopped = false; - const cycler = this.time.addEvent({ - delay: 55, loop: true, - callback: () => { - for (let i = 0; i < n; i++) { - this.drawDie(this.dieEls[i].g, 0, 0, DIE, Phaser.Math.Between(1, 6)); - } - }, - }); - const stopCycler = () => { if (!cyclerStopped) { cyclerStopped = true; cycler.remove(); } }; - - let settled = 0; - for (let i = 0; i < n; i++) { - const el = this.dieEls[i]; - const lx = landX[i] + (Math.random() * 10 - 5); - const ly = landY + (Math.random() * 10 - 5); - const outMs = 320 + i * 28; - const backMs = 460 + i * 40; - const totalMs = outMs + backMs; - - // X flies straight to landing; Y arcs up then bounces down - this.tweens.add({ targets: el.c, x: lx, duration: totalMs, ease: 'Quad.Out' }); - this.tweens.chain({ - targets: el.c, tweens: [ - { y: arcY, duration: outMs, ease: 'Quad.Out' }, - { y: ly, duration: backMs, ease: 'Bounce.Out' }, - ] - }); - // Scale up as die approaches - this.tweens.add({ targets: el.c, scale: 1, duration: outMs + backMs * 0.55, ease: 'Quad.Out' }); - // Spin - this.tweens.add({ - targets: el.c, - angle: el.c.angle + 540 + Math.random() * 180, - duration: totalMs, - ease: 'Quad.Out', - }); - - this.time.delayedCall(totalMs, () => { - stopCycler(); - this.drawDie(el.g, 0, 0, DIE, values[i]); - // Snap to nearest upright angle with a small wiggle - const upright = Math.round(el.c.angle / 90) * 90 + (Math.random() * 10 - 5); - this.tweens.add({ - targets: el.c, angle: upright, duration: 120, ease: 'Back.Out', - onComplete: () => { - el.c.setAlpha(1); - settled++; - if (settled === n) { - // Little squash-bounce on last die - for (let j = 0; j < n; j++) - this.tweens.add({ targets: this.dieEls[j].c, scaleX: 1.12, scaleY: 0.88, duration: 80, yoyo: true }); - this.time.delayedCall(160, resolve); - } - }, - }); - }); - } + updateRailLabels(groups) { + this.railLabels.forEach((o) => o.destroy()); + this.railLabels = []; + if (!groups.length) return; + const { labels } = railSlots(groups.map((g) => g.dice.length)); + groups.forEach((g, k) => { + const l = labels[k]; + const name = g.parts.map((pt) => pt.label.replace('Straight 1–6', 'Straight')).join(' + '); + const t1 = this.add.text(l.x, RAIL_LABEL_Y - 9, name, { + fontFamily: HAND_FONT, fontSize: g.dice.length > 1 ? '17px' : '15px', color: '#f6e7c8', + }).setOrigin(0.5).setDepth(D.tray + 4); + const t2 = this.add.text(l.x, RAIL_LABEL_Y + 13, `+${fmt(g.points)}`, { + fontFamily: DISPLAY_FONT, fontSize: '15px', color: '#ffd98a', + }).setOrigin(0.5).setDepth(D.tray + 4); + if (t1.width > l.w) t1.setScale(l.w / t1.width); + this.railLabels.push(t1, t2); }); } - renderDice() { - const rolled = this.gs.turn.rolled; - for (let i = 0; i < DICE; i++) { - const el = this.dieEls[i]; - if (i < rolled.length) { - this.drawDie(el.g, 0, 0, DIE, rolled[i], { selected: this.selected.has(i) }); - el.hit.setInteractive({ useHandCursor: true }); - } else { - el.g.clear(); - el.hit.disableInteractive(); - } - } + async hotDice(p) { + const fast = p !== HUMAN && this.aiFast; + playSound(this, SFX.VICTORY_SHORT); + this.banner('HOT DICE!', EMBER, 1.05); + this.embers(); + if (p !== HUMAN) this.say(p, pick(SPEECH.hot)); + else this.reactOthers(SPEECH.react, 0.5); + await this.tray.railHop(40, fast ? 220 : 420); + await this.wait(fast ? 120 : 380); + const target = p === HUMAN ? CUP_MOUTH : { x: this.seats[p].portrait.x, y: this.seats[p].portrait.y + 120 }; + this.updateRailLabels([]); + await this.tray.scoopAll(target, fast ? 160 : 280); } - renderShelf() { - const g = this.shelfGfx; - g.clear(); - const dice = this.gs.turn.setAsideDice; - const startX = TRAY_CX - TRAY_W / 2 + SDIE / 2 + 24; - for (let i = 0; i < dice.length; i++) { - const x = startX + i * (SDIE + SDIE_GAP); - this.paintDie(g, x, SHELF_Y, SDIE, dice[i], { locked: true }); - } - } - - renderScratch() { - const cur = this.gs.current; - for (let seat = 0; seat < this.scratchRows.length; seat++) { - const p = this.gs.players[seat]; - const row = this.scratchRows[seat]; - if (seat === cur && !isGameOver(this.gs)) { - // selectionScore() returns the combined cycle score (setAsideDice + selection). - // Adding priorKept gives the full prospective bank total in every phase. - const preview = (this.gs.turn.priorKept ?? 0) + this.selectionScore(); - row.score.setText(preview > 0 ? `${p.score} +${preview}` : String(p.score)); - } else { - row.score.setText(String(p.score)); - } - row.star.setVisible(p.onBoard); - } - // Underline the active player's row. - const u = this.scratchUnderline; - u.clear(); - if (isGameOver(this.gs)) return; - const row = this.scratchRows[cur]; - u.lineStyle(3, 0xcf6b5e, 0.9); - u.beginPath(); - u.moveTo(PAPER_X + 70, row.y + 24); - u.lineTo(PAPER_X + PAPER_W - 18, row.y + 24); - u.strokePath(); - } - - updatePortraitRing() { - for (let i = 0; i < this.portraitCtrls.length; i++) { - const { ring, x, y } = this.portraitCtrls[i]; - ring.clear(); - if (i === this.gs.current && !isGameOver(this.gs)) { - ring.lineStyle(4, COLORS.gold, 1); - ring.strokeCircle(x, y, PORTRAIT_R + 6); - } - } - } - - updateStatus() { + onBank() { const gs = this.gs; - if (isGameOver(gs)) { this.statusText.setText('Game over'); return; } - const cur = gs.players[gs.current]; - if (cur.isAI) { this.statusText.setText(`${cur.name} is rolling…`); return; } - - if (gs.phase === 'awaitRoll') { - this.statusText.setText(cur.onBoard ? 'Your turn — roll the dice' : 'Your turn — reach 500 to get on the board'); - } else if (gs.phase === 'awaitPick') { - const score = this.selectionScore(); - if (this.selected.size === 0) this.statusText.setText('Select scoring dice to set aside'); - else if (score > 0) this.statusText.setText(`Selection: +${score}`); - else this.statusText.setText('That selection has non-scoring dice'); - } else { - this.statusText.setText('Roll again or bank'); - } - } - - updateTurnTotal() { - const gs = this.gs; - const preview = (gs.turn.priorKept ?? 0) + this.selectionScore(); - this.turnTotalText.setText(preview > 0 ? `Turn total: ${preview}` : ''); - } - - updateExplainPanel() { - const gs = this.gs; - const p = gs.players[gs.current]; - const priorKept = gs.turn.priorKept ?? 0; - - // Combined set: already set-aside dice + pending selection (if any) - const combined = [ - ...gs.turn.setAsideDice, - ...(gs.phase === 'awaitPick' ? this.selectionValues() : []), - ]; - const groups = breakdownScoring(combined); - const cycleScore = groups.reduce((s, g) => s + g.points, 0); - const totalKept = priorKept + cycleScore; - const bankOk = p.onBoard || totalKept >= ON_BOARD_MIN; - - if (groups.length === 0 && priorKept === 0) { - this._explainLines.forEach((t) => t.setText('')); + if (this.busy || this.ended || this.modal || gs.current !== HUMAN || gs.phase !== 'awaitPick') return; + const sel = this.selectionInfo(); + if (!sel.valid || !L.bankAllowed(gs, gs.turn.kept + sel.points)) return; + const need = L.finalRoundNeed(gs); + if (need > 0 && gs.turn.kept + sel.points < need) { + this.confirmThen('Bank short?', `You need ${fmt(need)} to beat the leader in the final round. Banking ${fmt(gs.turn.kept + sel.points)} can't win.`, () => this.doHumanBank(), 'Bank anyway'); return; } - - // Gold = preview (selection pending), white = committed - const inPreview = gs.phase === 'awaitPick' && this.selected.size > 0 && this.selectionScore() > 0; - const detailColor = inPreview ? COLORS.goldHex : COLORS.textHex; - - let li = 0; - const maxDetail = this._explainLines.length - 1; // reserve last line for total - - if (priorKept > 0 && li < maxDetail) { - this._explainLines[li++].setText(`Prior rolls = ${fmtPts(priorKept)}`).setColor(COLORS.textHex); - } - - for (const g of groups) { - if (li >= maxDetail) break; - this._explainLines[li++].setText(`${g.label} = ${fmtPts(g.points)}`).setColor(detailColor); - } - - // Show total when there are multiple content lines, or when "need 500" applies - const contentLines = (priorKept > 0 ? 1 : 0) + groups.length; - if (totalKept > 0 && (contentLines > 1 || !bankOk) && li < this._explainLines.length) { - const note = bankOk ? '' : ' (need 500)'; - this._explainLines[li++] - .setText(`Total = ${fmtPts(totalKept)}${note}`) - .setColor(bankOk ? COLORS.accentHex : COLORS.dangerHex); - } - - for (let i = li; i < this._explainLines.length; i++) this._explainLines[i].setText(''); + this.doHumanBank(); } - updateControls() { + async doHumanBank() { + this.busy = true; + this.hidePiggy(); + this.tray.setEnabled(false); + this.refreshControls(); + await this.commitSelection(HUMAN); + if (this.ended) return; + await this.bankTurn(HUMAN); + } + + // Bank the turn total: the number flies into the ledger. + async bankTurn(p) { const gs = this.gs; - const human = !gs.players[gs.current].isAI && !isGameOver(gs) && !this.busy; - const validSel = this.selected.size > 0 && this.selectionValid(); - - const canRoll = human && (gs.phase === 'awaitRoll' || (gs.phase === 'awaitPick' && validSel)); - const canBank = human && gs.phase === 'awaitPick' && validSel; - const canScoreAll = human && gs.phase === 'awaitPick'; - - this.rollBtn?.setEnabled(canRoll); - this.rollBtn?.setLabel(gs.phase === 'awaitPick' ? 'Set Aside & Roll' : 'Roll'); - this.bankBtn?.setEnabled(canBank); - this.scoreAllBtn?.setEnabled(canScoreAll); - } - - // ── selection helpers ───────────────────────────────────────────────────────── - selectionValues() { return [...this.selected].map((i) => this.gs.turn.rolled[i]); } - - // Returns the combined score of all set-aside dice this cycle plus the current - // selection. This IS the value that would become turn.kept if committed. - selectionScore() { - const combined = [...this.gs.turn.setAsideDice, ...this.selectionValues()]; - if (combined.length === 0) return 0; - const r = scoreSelection(combined); - return r.valid ? r.points : 0; - } - - // A selection is valid when the combined set (set-aside + selection) all score. - selectionValid() { - const values = this.selectionValues(); - if (values.length === 0) return false; - return scoreSelection([...this.gs.turn.setAsideDice, ...values]).valid; - } - - // ── input ────────────────────────────────────────────────────────────────────── - onDieClick(i) { - if (this.busy || !this.isHumanTurn() || this.gs.phase !== 'awaitPick') return; - if (i >= this.gs.turn.rolled.length) return; - if (this.selected.has(i)) this.selected.delete(i); else this.selected.add(i); - playSound(this, SFX.PIECE_CLICK); - this.render(); - } - - onScoreAll() { - if (this.busy || !this.isHumanTurn() || this.gs.phase !== 'awaitPick') return; - const { indices } = bestScoring(this.gs.turn.rolled, this.gs.turn.setAsideDice); - this.selected = new Set(indices); - playSound(this, SFX.PIECE_CLICK); - this.render(); - } - - async onRoll() { - if (this.busy || !this.isHumanTurn()) return; - if (this.gs.phase === 'awaitPick' && !this.commitSelection()) return; - if (this.gs.phase === 'gameover') return; - await this.rollAnimated(); - await this.afterRoll(); - } - - async onBank() { - if (this.busy || !this.isHumanTurn()) return; - if (this.gs.phase === 'awaitPick' && !this.commitSelection()) return; - if (this.gs.phase !== 'awaitDecision') return; - const seat = this.gs.current; - const { bankable } = bank(this.gs); - playSound(this, SFX.PENCIL_WRITE); - if (bankable > 0) { - await this.animateBank(seat, bankable); - this.gs.players[seat].score += bankable; + const fast = p !== HUMAN && this.aiFast; + const total = gs.turn.kept; + const historyLen = gs.players[p].stats.history.length; + const res = L.bank(gs); + if (!res) { this.nextTurn(); return; } + this.pad.setPreview(null, 0); + // fly the total to the ledger cell + const row = Math.min(PAD_ROWS - 1, Math.max(0, historyLen - 1 - (this.pad.start ?? 0))); + const to = { x: padColX(p, this.n) + padColW(this.n) - 50, y: padRowY(row) + PAD_ROW_H / 2 }; + const fly = this.add.text(TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, `+${fmt(total)}`, { + fontFamily: DISPLAY_FONT, fontSize: '76px', color: '#ffd98a', stroke: '#2a1408', strokeThickness: 10, + }).setOrigin(0.5).setDepth(D.fx).setScale(0.4); + playSound(this, total >= 1000 ? SFX.CASINO_WIN : SFX.COINS); + await this.tweenTo(fly, { scale: 1 }, fast ? 160 : 300, 'Back.Out'); + await this.wait(fast ? 120 : 420); + await this.tweenTo(fly, { x: to.x, y: to.y, scale: 0.35, alpha: 0.4 }, fast ? 320 : 620, 'Cubic.InOut'); + fly.destroy(); + if (this.ended) return; + this.pad.syncFromState(gs, { leader: L.leaderSeat(gs) }); + await this.pad.animateLatest(p, { speed: fast ? 0.4 : 1 }); + // reactions + if (p !== HUMAN) { + if (total >= 1500) { this.say(p, pick(SPEECH.bigBank)); this.portraits[p]?.playEmotion?.('happy'); } + else if (Math.random() < 0.3) this.say(p, pick(SPEECH.bank)); + } else if (total >= 1500) { + this.flourish(`Big run! +${fmt(total)}`, 0xffd98a, 0.9); + this.reactOthers(SPEECH.react, 0.6, 'upset'); } - this.render(); - this.advance(); + const fin = gs.log[gs.log.length - 1]; + if (fin?.kind === 'final' && fin.seat === p) { + this.banner('FINAL ROUND!', 0xff6b5a, 0.95); + playSound(this, SFX.VICTORY_SHORT); + } + const next = gs.current; + const target = next === HUMAN || !this.seats[next] ? CUP_MOUTH : { x: this.seats[next].portrait.x, y: this.seats[next].portrait.y + 120 }; + this.updateRailLabels([]); + await this.tray.scoopAll(target, fast ? 160 : 300); + await this.wait(p === HUMAN ? 150 : 300 * this.k * (fast ? 0.3 : 1)); + if (this.ended) return; + this.nextTurn(); } - commitSelection() { - const idx = [...this.selected]; - if (idx.length === 0) return false; - if (!this.selectionValid()) return false; - applySetAside(this.gs, idx); - this.selected.clear(); - return true; - } - - // ── turn driver ────────────────────────────────────────────────────────────── - isHumanTurn() { return !this.gs.players[this.gs.current].isAI && !isGameOver(this.gs); } - - advance() { - this.render(); - if (isGameOver(this.gs)) { this.showGameOver(); return; } - if (this.isHumanTurn()) { this.updateControls(); return; } - this.aiTurn(); - } - - async rollAnimated() { + // A Farkle: frost sweeps the tray, the turn total is lost. + async farkle(p) { + const gs = this.gs; + const fast = p !== HUMAN && this.aiFast; this.busy = true; - this.updateControls(); - rollDice(this.gs); - const values = this.gs.turn.rolled; - await this.animateDice(values); - this.render(); - this.busy = false; - } - - async afterRoll() { - if (this.gs.phase === 'farkled') { - await this.farkleFx(); - farkleTurn(this.gs); - this.advance(); - } else { - this.advance(); - } - } - - async aiTurn() { - this.busy = true; - this.updateControls(); - const skill = this.gs.players[this.gs.current].skill; - - while (true) { - await this.delay(nextThinkDelay(skill)); - await this.rollAnimated(); - if (this.gs.phase === 'farkled') { - await this.farkleFx(); - const seat = this.gs.current; - farkleTurn(this.gs); - this.portraitCtrls[seat]?.controller?.playEmotion?.('upset'); - break; - } - const best = bestScoring(this.gs.turn.rolled, this.gs.turn.setAsideDice); - this.selected = new Set(best.indices); - this.render(); - await this.delay(480); - applySetAside(this.gs, best.indices); - this.selected.clear(); - this.render(); - await this.delay(360); - if (decideReroll(this.gs, skill)) continue; - const seat = this.gs.current; - const { bankable } = bank(this.gs); - playSound(this, SFX.PENCIL_WRITE); - if (bankable > 0) { - await this.animateBank(seat, bankable); - this.gs.players[seat].score += bankable; - } - if (this.gs.players[seat].score >= 1000) { - this.portraitCtrls[seat]?.controller?.playEmotion?.('happy'); - } - break; - } - - this.busy = false; - this.render(); - this.advance(); - } - - // ── effects ────────────────────────────────────────────────────────────────── - farkleFx() { + this.tray.setEnabled(false); + const lost = gs.turn.kept; playSound(this, SFX.CASINO_LOSE); - const toast = this.add.text(TRAY_CX, TRAY_CY, 'FARKLE!', { - fontFamily: 'Righteous', fontSize: '72px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(DEPTH.toast).setAngle(-8); - this.tweens.add({ targets: toast, scale: { from: 0.6, to: 1.1 }, duration: 260, ease: 'Back.Out' }); - return new Promise((resolve) => { - this.time.delayedCall(1100, () => { - this.tweens.add({ - targets: toast, alpha: 0, duration: 250, - onComplete: () => { toast.destroy(); resolve(); }, - }); - }); - }); - } - - animateBank(seat, banked) { - return new Promise((resolve) => { - playSound(this, SFX.CASINO_WIN); - const row = this.scratchRows[seat]; - const destX = PAPER_X + PAPER_W - 22; - const destY = row.y; - - // Create floating text at dice area - const label = this.add.text(TRAY_CX, TRAY_CY, `+${banked}`, { - fontFamily: 'Righteous', fontSize: '80px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.toast); - - // Hold for 1 second - this.time.delayedCall(1000, () => { - // Animate to score pad - this.tweens.add({ - targets: label, - x: destX, - y: destY, - scale: 0.5, - duration: 1000, - ease: 'Cubic.Out', - onComplete: () => { - label.destroy(); - resolve(); - }, - }); - }); - }); - } - - // ── game over ────────────────────────────────────────────────────────────────── - showGameOver() { - if (this.gameOverShown) return; - this.gameOverShown = true; - playSound(this, SFX.VICTORY_SHORT); - this.postHistory().catch(() => {}); - - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.65) - .setInteractive().setDepth(DEPTH.modal); - - const N = this.gs.players.length; - const panelW = 720; - const panelH = 220 + N * 56; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - this.add.rectangle(cx, cy, panelW, panelH, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(DEPTH.modal); - this.add.text(cx, cy - panelH / 2 + 48, 'Final Scores', { - fontFamily: 'Righteous', fontSize: '42px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.modal); - - const winners = new Set(getWinners(this.gs)); - const order = [...this.gs.players].sort((a, b) => b.score - a.score); - let rowY = cy - panelH / 2 + 110; - for (const p of order) { - const isWin = winners.has(p.seat); - const color = isWin ? COLORS.goldHex : COLORS.textHex; - this.add.text(cx - panelW / 2 + 40, rowY, `${isWin ? '★ ' : ' '}${p.name}`, { - fontFamily: 'Righteous', fontSize: '24px', color, - }).setOrigin(0, 0.5).setDepth(DEPTH.modal); - this.add.text(cx + panelW / 2 - 40, rowY, String(p.score), { - fontFamily: 'Righteous', fontSize: '28px', color, - }).setOrigin(1, 0.5).setDepth(DEPTH.modal); - rowY += 52; + this.tray.setDecor({ dimAll: true, selected: new Set(), hints: null, coach: null }); + this.frost.setAlpha(0); + this.tweens.add({ targets: this.frost, alpha: 0.95, duration: fast ? 160 : 420, ease: 'Quad.Out' }); + this.snowfall(fast ? 18 : 40); + this.banner('FARKLE!', ICE, 1.1); + this.cameras.main.shake(180, 0.003); + if (lost > 0) this.turnTotalText.setText(`TURN ${fmt(lost)} ✗`).setColor('#9fd8ff'); + if (p !== HUMAN) { this.say(p, pick(SPEECH.farkle)); this.portraits[p]?.playEmotion?.('upset'); } + else if (lost >= 500) this.reactOthers(SPEECH.console, 0.6); + await this.wait(fast ? 500 : 1300); + if (this.ended) return; + const { penalty } = L.farkleTurn(gs); + this.turnTotalText.setColor('#ffd98a'); + this.pad.setPreview(null, 0); + this.pad.syncFromState(gs, { leader: L.leaderSeat(gs) }); + await this.pad.animateLatest(p, { speed: fast ? 0.4 : 1 }); + if (penalty) { + this.banner(`Three Farkles! −${fmt(penalty)}`, 0xff6b5a, 0.8); + playSound(this, SFX.CASINO_LOSE); + await this.wait(fast ? 300 : 900); } + const next = gs.current; + const target = next === HUMAN || !this.seats[next] ? CUP_MOUTH : { x: this.seats[next].portrait.x, y: this.seats[next].portrait.y + 120 }; + this.updateRailLabels([]); + this.tweens.add({ targets: this.frost, alpha: 0, duration: 500, delay: 200 }); + await this.tray.scoopAll(target, fast ? 160 : 300); + this.tray.setDecor({ dimAll: false }); + await this.wait(fast ? 120 : 300); + if (this.ended) return; + this.nextTurn(); + } - new Button(this, cx, cy + panelH / 2 - 48, 'Back to Menu', - () => this.scene.start('GameMenu'), { width: 280, fontSize: 24 }, - ).setDepth(DEPTH.modal); + // ── piggyback offer ───────────────────────────────────────────────────────── + showPiggy() { + this.hidePiggy(); + const o = this.gs.piggyOffer; + if (!o) return; + const from = this.gs.players[o.from]?.name ?? 'the last player'; + const g = this.add.graphics().setDepth(D.banner - 2); + g.fillStyle(0x000000, 0.55).fillRoundedRect(PIGGY.x - 330, PIGGY.y - 92, 660, 184, 16); + g.lineStyle(2, 0xffd98a, 0.8).strokeRoundedRect(PIGGY.x - 330, PIGGY.y - 92, 660, 184, 16); + const t = this.add.text(PIGGY.x, PIGGY.y - 56, `Piggyback on ${from}?`, { + fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#ffd98a', + }).setOrigin(0.5).setDepth(D.banner - 1); + const s = this.add.text(PIGGY.x, PIGGY.y - 22, `Take their ${fmt(o.kept)} and roll their ${o.available} leftover ${o.available === 1 ? 'die' : 'dice'} — a Farkle loses it all.`, { + fontFamily: SERIF, fontSize: '16px', color: '#f0dcb0', + }).setOrigin(0.5).setDepth(D.banner - 1); + const a = new Button(this, PIGGY.x - 150, PIGGY.y + 42, `Piggyback (P)`, () => this.onPiggy(), { width: 260, height: 50, fontSize: 18, bg: 0x8e1a1a }).setDepth(D.banner); + const b = new Button(this, PIGGY.x + 150, PIGGY.y + 42, 'Fresh 6 dice (R)', () => { this.hidePiggy(); this.onRollButton(); }, { width: 260, height: 50, fontSize: 18, bg: 0x1d5135 }).setDepth(D.banner); + this.piggyObjs = [g, t, s, a, b]; + } + hidePiggy() { (this.piggyObjs ?? []).forEach((o) => o.destroy()); this.piggyObjs = null; } + + onPiggy() { + if (this.busy || this.modal || this.gs.current !== HUMAN || !this.gs.piggyOffer) return; + if (!L.takePiggyback(this.gs)) return; + this.hidePiggy(); + playSound(this, SFX.COINS); + this.setStatus('Piggybacking!', `Turn total ${fmt(this.gs.turn.kept)} — roll your ${this.gs.turn.available} dice.`); + this.refreshHud(); + } + + // ── opponents ─────────────────────────────────────────────────────────────── + aiTurn() { + const p = this.gs.current; + this.busy = true; + this.tray.setEnabled(false); + const t = aiTiming(this.gs.players[p].skill, this.k); + const name = this.gs.players[p].name; + const need = L.finalRoundNeed(this.gs); + this.setStatus(`${name}'s turn`, need > 0 ? `${name} needs ${fmt(need)} to take the lead. (Click the tray to hurry.)` : `${name} reaches for the dice… (click the tray to hurry)`); + if (need > 0 && Math.random() < 0.6) this.say(p, pick(SPEECH.chase)); + this.refreshHud(); + this.aiTimer = this.time.delayedCall(t.think * (this.aiFast ? 0.4 : 1), () => { + this.aiTimer = null; + this.runAI(p, t).catch((e) => console.error('Farkle AI turn failed', e)); + }); + } + + async runAI(p, t) { + const gs = this.gs; + const f = () => (this.aiFast ? 0.25 : 1); + const name = gs.players[p].name; + const skill = gs.players[p].skill; + if (gs.piggyOffer) { + if (wantsPiggyback(gs, skill)) { + L.takePiggyback(gs); + this.say(p, pick(SPEECH.piggy)); + playSound(this, SFX.COINS); + this.refreshHud(); + await this.wait(500 * f()); + } else if (Math.random() < 0.4) this.say(p, pick(SPEECH.fresh)); + } + for (let guard = 0; guard < 60; guard++) { + if (this.ended) return; + await this.aiThrow(p); + if (this.ended) return; + if (gs.phase === 'farkled') { await this.farkle(p); return; } + this.throwFlourish(p); + await this.wait(t.think * f()); + if (this.ended) return; + let d = planDecision(gs, skill); + if (!L.scoreSelection(d.keep.map((i) => gs.turn.rolled[i]), gs.rules).valid) { + d = { keep: L.bestScoring(gs.turn.rolled, gs.rules).indices, bank: false }; + } + // show the pick + this.selected = new Set(d.keep); + const sel = this.selectionInfo(); + this.tray.setDecor({ selected: new Set(this.selected), hints: null, coach: null }); + this.setStatus(`${name} keeps ${d.keep.map((i) => gs.turn.rolled[i]).join('·')}`, `+${fmt(sel.points)} · ${sel.parts.map((x) => x.label).join(' + ')}`); + this.refreshHud(); + await this.wait((380 + t.hesitate) * f()); + if (this.ended) return; + await this.commitSelection(p); + if (this.ended) return; + // a hot-dice cycle must roll again (planDecision may still bank — that's allowed) + if (d.bank && L.canBank(gs)) { + if (gs.turn.kept < 1500 && Math.random() < 0.25) this.say(p, pick(SPEECH.bank)); + this.setStatus(`${name} banks ${fmt(gs.turn.kept)}`, ''); + await this.wait(t.hesitate * f()); + await this.bankTurn(p); + return; + } + if (Math.random() < 0.22) this.say(p, pick(SPEECH.push)); + this.setStatus(`${name} rolls on`, `Turn total ${fmt(gs.turn.kept)} · ${gs.turn.available} ${gs.turn.available === 1 ? 'die' : 'dice'}`); + await this.wait(t.between * f()); + } + } + + async aiThrow(p) { + const seat = this.seats[p]; + const fast = this.aiFast; + const from = { x: seat.portrait.x, y: seat.portrait.y + 120 }; + if (!fast) { + await this.tray.scoopTray(from, 240 * this.k); + 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); + } + } else { + await this.tray.scoopTray(from, 0); + } + if (this.ended) return; + await this.doThrow(seatOrigin(seat.portrait.x), { fast, speed: 1 }); + } + + // ── flourishes ────────────────────────────────────────────────────────────── + 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), 'farkel-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() }); + } + } + + 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: '#1a0c04', 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 : 1300, duration: 420, onComplete: () => { c.destroy(); if (this.bannerObj === c) this.bannerObj = null; } }); + } + + embers(count = 46) { + for (let i = 0; i < count; i++) { + const x = TRAY.x + 200 + Math.random() * (TRAY.w - 400); + const e = this.add.image(x, TRAY.y + TRAY.h + 60 + Math.random() * 40, 'farkel-ember') + .setDepth(D.fx).setBlendMode(Phaser.BlendModes.ADD).setScale(0.6 + Math.random() * 1.2); + this.tweens.add({ + targets: e, y: TRAY.y + 40 + Math.random() * 200, x: x + Phaser.Math.Between(-80, 80), alpha: 0, + duration: 900 + Math.random() * 900, ease: 'Sine.Out', onComplete: () => e.destroy(), + }); + } + } + + snowfall(count = 40, area = TRAY) { + for (let i = 0; i < count; i++) { + const x = area.x + Math.random() * area.w; + const s = this.add.image(x, area.y - 20 - Math.random() * 80, 'farkel-flake') + .setDepth(D.fx).setAlpha(0.9).setScale(0.35 + Math.random() * 0.6).setRotation(Math.random() * 3); + this.tweens.add({ + targets: s, y: area.y + area.h * (0.4 + Math.random() * 0.6), x: x + Phaser.Math.Between(-60, 60), + rotation: s.rotation + Phaser.Math.FloatBetween(-3, 3), alpha: 0, + duration: 1300 + Math.random() * 1100, ease: 'Sine.In', onComplete: () => s.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: '16px', 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(36, t.height + 16); + 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); + const c = this.add.container(0, 0, [g, t]).setDepth(D.seat + 6).setAlpha(0); + this.bubbles[p] = c; + this.refreshHud(); + 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]; if (!this.ended) this.refreshHud(); } + }, + }); + } + + 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)); + if (p === this.gs.current) return; + this.time.delayedCall(450, () => { + this.say(p, pick(lines)); + if (emotion) this.portraits[p]?.playEmotion?.(emotion); + }); + } + + // ── input ─────────────────────────────────────────────────────────────────── + onKey(e, down) { + if (this.ended) return; + const key = e.key; + if (key === ' ' || e.code === 'Space') { + e.preventDefault?.(); + if (this.gs.current !== HUMAN) { if (down && !this.skipTurn) { this.skipTurn = true; this.flashSub('Hurrying along…'); } return; } + 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 <= '6') { this.onDieClick(Number(key) - 1, { shiftKey: e.shiftKey }); return; } + const k = key.toLowerCase(); + if (k === 'r') this.onRollButton(); + else if (k === 'b') this.onBank(); + else if (k === 'a') this.onBest(); + else if (k === 'c' || k === 'u') this.onClear(); + else if (k === 'p') this.onPiggy(); + else if (k === 'l') this.openLog(); + } + + // ── menu / modals ─────────────────────────────────────────────────────────── + hidePortraits() { this.portraits.forEach((c) => c?.setVideoVisible?.(false)); } + showPortraits() { this.portraits.forEach((c) => c?.setVideoVisible?.(true)); } + + 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), + onHouseRules: () => this.openHouseRules(), + onLog: () => this.openLog(), + onRules: () => new TutorialModal(this.gameDef).open(), + onNewGame: () => this.confirmThen('New game?', 'Abandon this game and start a fresh score sheet?', () => this.restartFresh()), + onLeave: () => this.confirmThen('Leave the lodge?', 'Your game is saved at the start of each turn — you can resume it next time.', () => this.scene.start('GameMenu'), 'Leave'), + onClose: () => { this.modal = null; this.showPortraits(); this.refreshControls(); }, + }); + this.refreshControls(); + } + + openHouseRules() { + if (this.ended) return; + this.hidePortraits(); + this.modal = openRulesDialog(this, { + rules: this.settings.rules, depth: D.modal, inGame: true, + onApply: (r) => { + this.settings.rules = normalizeRules(r); + this.saveSettings(); + this.modal = null; + this.restartFresh(); + }, + onClose: () => { if (this.modal) { this.modal = null; this.showPortraits(); this.refreshControls(); } }, + }); + } + + openLog() { + if (this.modal || this.ended) return; + this.hidePortraits(); + this.modal = openLogDialog(this, { + gs: this.gs, depth: D.modal, + onClose: () => { this.modal = null; this.showPortraits(); this.refreshControls(); }, + }); + this.refreshControls(); + } + + confirmThen(heading, text, onYes, yes = 'Yes') { + this.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, yes, depth: D.modal + 5, + onYes: () => { this.modal = null; this.showPortraits(); onYes(); this.refreshControls(); }, + onNo: () => { this.modal = null; this.showPortraits(); this.refreshControls(); }, + }); + this.refreshControls(); + } + + closeModal() { this.modal?.close?.(); this.modal = null; this.showPortraits(); this.refreshControls(); } + + changeSetting(key, value) { + this.settings[key] = value; + this.saveSettings(); + if (this.gs.current === HUMAN && this.gs.phase === 'awaitPick' && !this.busy) this.refreshPick(); + this.refreshHud(); + } + + saveSettings() { + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + } + + restartFresh() { + this.clearSave(); + this.scene.restart({ ...this.initData, resume: false, fresh: true }); + } + + // ── autosave ──────────────────────────────────────────────────────────────── + signature() { + return JSON.stringify({ n: Math.max(2, Math.min(4, 1 + this.opponents.length)), opp: this.opponents.map((o) => o?.id ?? o?.name ?? '?') }); + } + readSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || s.sig !== this.signature() || s.gs?.version !== 2 || s.gs.phase === 'gameover') return null; + if (s.gs.players?.length !== Math.max(2, Math.min(4, 1 + this.opponents.length))) return null; + return s; + } catch (_) { return null; } + } + saveGame() { + if (L.isGameOver(this.gs)) { this.clearSave(); return; } + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ v: 1, sig: this.signature(), gs: this.gs, savedAt: Date.now() })); + } catch (_) { /* storage full / private mode */ } + } + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + offerResume(save) { + const me = save.gs.players[HUMAN]; + const when = new Date(save.savedAt).toLocaleDateString(); + this.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Resume your game?', + text: `A game from ${when} is still on the table — turn ${save.gs.turnNo}, you have ${fmt(me.score)} (to ${fmt(save.gs.rules.target)}).`, + yes: 'Resume', no: 'New Game', depth: D.modal + 5, + onYes: () => { this.modal = null; this.scene.restart({ ...this.initData, resume: true }); }, + onNo: () => { this.modal = null; this.showPortraits(); this.clearSave(); this.time.delayedCall(250, () => this.nextTurn()); }, + }); + } + + // ── end of game ───────────────────────────────────────────────────────────── + async finishGame() { + if (this.ended) return; + this.ended = true; + this.busy = true; + this.clearSave(); + this.cup.setEnabled(false); + this.tray.setEnabled(false); + this.hidePiggy(); + this.refreshHud(); + this.refreshControls(); + const gs = this.gs; + const ranks = L.rankings(gs); + const me = gs.players[HUMAN]; + const best = recordPersonalBest(me.score, me.stats.bestTurn); + this.postHistory().catch(() => {}); + if (ranks[HUMAN] === 1) { playSound(this, SFX.VICTORY_SHORT); this.snowfall(120, { x: 0, y: 0, w: 1180, h: 1080 }); this.embers(60); } + 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: ${fmt(me.score)}`); + await this.wait(1100); + this.hidePortraits(); + openEndScreen(this, { + gs, ranks, depth: D.end, best, + onPlayAgain: () => this.scene.restart({ ...this.initData, resume: false, fresh: true }), + onMenu: () => this.scene.start('GameMenu'), + }); } async postHistory() { const totals = this.gs.players.map((p) => p.score); - const winners = new Set(getWinners(this.gs)); + const winners = new Set(L.getWinners(this.gs)); let result; - if (winners.has(this.humanSeat) && winners.size === 1) result = 'win'; - else if (winners.has(this.humanSeat)) result = 'draw'; + 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: 'farkel', - score: totals[this.humanSeat], - opponentScores: totals.filter((_, i) => i !== this.humanSeat), - result, + slug: 'farkel', score: totals[HUMAN], opponentScores: totals.slice(1), result, }); } - 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/farkel/FarkelLayout.js b/src/games/farkel/FarkelLayout.js new file mode 100644 index 0000000..8645584 --- /dev/null +++ b/src/games/farkel/FarkelLayout.js @@ -0,0 +1,161 @@ +// FarkelLayout.js — every screen rect for Gerome's Ski Lodge Farkle table, plus +// the dice-tray projection. Phaser-free (tools/verifyFarkel.js checks overlaps). +// +// ┌ opponent seats (top) ─────────────────────┐ ┌ clipboard score pad ──┐ +// │ felt dice tray │ │ (one row per turn) │ +// │ "set aside" rail (kept dice, by throw) │ ├ chalkboard scoring ───┤ +// └ you · cup · risk gauge · status · buttons ┘ └───────────────────────┘ + +export const W = 1920; +export const H = 1080; + +// ── Seats ──────────────────────────────────────────────────────────────────── +export const SEAT = { w: 360, h: 150, y: 12, 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 + 70, y: r.y + 75, r: 52 }, + name: { x: r.x + 140, y: r.y + 32 }, + score: { x: r.x + 140, y: r.y + 70 }, + line: { x: r.x + 140, y: r.y + 108 }, + hat: { x: r.x + 112, y: r.y + 26 }, + bubble: { x: r.x + 138, y: r.y + 86, w: 214, h: 58 }, + }; +} + +// ── Dice tray ──────────────────────────────────────────────────────────────── +export const TRAY = { x: 60, y: 176, w: 1100, h: 470 }; +export const TRAY_WALL = 26; +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 = 64; + +// One shared ground plane for the tray, the rail 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 }; +} + +// Where n dice rest after a throw (tidied into a row). +const COL_GAP = 134; +export function columnU(i, n) { return TRAY_FELT.w / 2 + (i - (n - 1) / 2) * COL_GAP; } +export const REST_V = TRAY_WORLD.h * 0.56; + +// ── Set-aside rail ─────────────────────────────────────────────────────────── +export const RAIL = { x: 60, y: 656, w: 1100, h: 150 }; +export const RAIL_TOP_H = 84; // the shelf top; the rest is the front face +export const RAIL_GROUND_Y = 702; // where a kept die sits +export const RAIL_V = toWorld(0, RAIL_GROUND_Y).v; +export const RAIL_LABEL_Y = RAIL.y + RAIL_TOP_H + (RAIL.h - RAIL_TOP_H) / 2; +export const RAIL_START_X = RAIL.x + 250; // left of this: the engraved "SET ASIDE" +const RAIL_STEP = 86, RAIL_GROUP_GAP = 40; + +// Slots for the kept dice of this cycle, grouped by throw. sizes = dice per +// group. Returns { us: [u per die], labels: [{ x, w }] per group }. +export function railSlots(sizes) { + const us = []; + const labels = []; + let x = RAIL_START_X + RAIL_STEP / 2; + sizes.forEach((n, g) => { + if (g > 0) x += RAIL_GROUP_GAP; + const x0 = x; + for (let i = 0; i < n; i++) { us.push(x - TRAY_FELT.x); x += RAIL_STEP; } + labels.push({ x: (x0 + x - RAIL_STEP) / 2, w: n * RAIL_STEP + RAIL_GROUP_GAP - 12 }); + }); + return { us, labels }; +} +export function railU(k, groups = 6) { + const sizes = Array.from({ length: groups }, () => 1); + return railSlots(sizes).us[k]; +} +export const RAIL_CHIP = { x: RAIL.x + 128, y: RAIL.y + RAIL_TOP_H / 2 + 2 }; // hot-dice carry chip + +// ── Bottom rail (you) ──────────────────────────────────────────────────────── +export const HUMAN_PORTRAIT = { x: 92, y: 912, r: 56 }; +export const HUMAN_NAME = { x: 92, y: 994 }; +export const HUMAN_SCORE = { x: 92, y: 1034 }; +export const HUMAN_HAT = { x: 52, y: 860 }; +export const CUP = { x: 262, y: 940, w: 130, h: 160 }; // centre +export const CUP_MOUTH = { x: CUP.x, y: CUP.y - CUP.h / 2 + 18 }; +export const THERMO = { x: 346, y: 826, w: 70, h: 236 }; +export const TURN_TOTAL = { x: 660, y: 852 }; +export const STATUS = { x: 660, y: 906, w: 430 }; +export const SUBLINE = { x: 660, y: 948 }; +export const TICKER = { x: 660, y: 1044 }; +export const BTN_BIG = { w: 236, h: 54 }; +export const BTN_SMALL = { w: 112, h: 42 }; +export const ROLL_BTN = { x: 1040, y: 852 }; +export const BANK_BTN = { x: 1040, y: 914 }; +export const BEST_BTN = { x: 978, y: 976 }; +export const CLEAR_BTN = { x: 1102, y: 976 }; +export const LOG_BTN = { x: 978, y: 1030 }; +export const MENU_BTN = { x: 1102, y: 1030 }; +export const BANNER = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + TRAY.h * 0.44 }; +export const FINAL_RIBBON = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + 8, w: 640, h: 40 }; +export const PIGGY = { x: TRAY.x + TRAY.w / 2, y: TRAY.y + TRAY.h * 0.5 }; + +// Throw origins in tray-world coordinates. +export function humanOrigin() { + return { u: CUP.x - TRAY_FELT.x + 40, v: TRAY_WORLD.h + 70, h: 130 }; +} +export function seatOrigin(portraitX) { + return { u: portraitX - TRAY_FELT.x, v: -90, h: 110 }; +} + +// ── Score pad (clipboard) ──────────────────────────────────────────────────── +export const BOARD = { x: 1186, y: 12, w: 716, h: 640 }; +export const CLIP = { x: BOARD.x + BOARD.w / 2 - 110, y: 0, w: 220, h: 70 }; +export const PAPER = { x: BOARD.x + 22, y: 56, w: BOARD.w - 44, h: 580 }; +export const PAD_TITLE = { x: PAPER.x + 30, y: PAPER.y + 50 }; +export const PAD_HEAD = { y: PAPER.y + 98, h: 52 }; +export const PAD_MARGIN = 54; // turn numbers left of the red line +export const PAD_ROW_H = 34; +export const PAD_ROWS = Math.floor((PAPER.y + PAPER.h - 12 - (PAD_HEAD.y + PAD_HEAD.h)) / PAD_ROW_H); +export const PAD_GRID = { x: PAPER.x + 12, y: PAD_HEAD.y, w: PAPER.w - 24 }; +export function padColW(n) { return (PAD_GRID.w - PAD_MARGIN) / n; } +export function padColX(p, n) { return PAD_GRID.x + PAD_MARGIN + p * padColW(n); } +export function padRowY(r) { return PAD_HEAD.y + PAD_HEAD.h + r * PAD_ROW_H; } // top of visible row r + +// ── Scoring chalkboard ─────────────────────────────────────────────────────── +export const CARD = { x: 1186, y: 666, w: 716, h: 402 }; +export const CARD_INNER = { x: CARD.x + 26, y: CARD.y + 26, w: CARD.w - 52, h: CARD.h - 52 }; +export const CARD_ROW_H = 38; +export const CARD_COLS = [ + { x: CARD_INNER.x + 18, w: CARD_INNER.w / 2 - 30 }, + { x: CARD_INNER.x + CARD_INNER.w / 2 + 12, w: CARD_INNER.w / 2 - 30 }, +]; +export const CARD_ROWS_TOP = CARD_INNER.y + 62; + +// ── 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: 'rail', ...RAIL }); + 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({ name: 'humanText', x: 20, y: HUMAN_NAME.y - 16, w: 150, h: HUMAN_SCORE.y + 18 - (HUMAN_NAME.y - 16) }); + f.push(c('cup', CUP, CUP.w, CUP.h)); + f.push({ name: 'thermo', x: THERMO.x, y: THERMO.y, w: THERMO.w, h: THERMO.h }); + f.push({ name: 'status', x: STATUS.x - STATUS.w / 2, y: TURN_TOTAL.y - 26, w: STATUS.w, h: TICKER.y + 30 - (TURN_TOTAL.y - 26) }); + f.push(c('roll', ROLL_BTN, BTN_BIG.w, BTN_BIG.h)); + f.push(c('bank', BANK_BTN, BTN_BIG.w, BTN_BIG.h)); + f.push(c('best', BEST_BTN, BTN_SMALL.w, BTN_SMALL.h)); + f.push(c('clear', CLEAR_BTN, BTN_SMALL.w, BTN_SMALL.h)); + f.push(c('log', LOG_BTN, BTN_SMALL.w, BTN_SMALL.h)); + f.push(c('menu', MENU_BTN, BTN_SMALL.w, BTN_SMALL.h)); + f.push({ name: 'board', ...BOARD }); + f.push({ name: 'card', ...CARD }); + 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; diff --git a/src/games/farkel/FarkelLogic.js b/src/games/farkel/FarkelLogic.js index 8c23539..e132c30 100644 --- a/src/games/farkel/FarkelLogic.js +++ b/src/games/farkel/FarkelLogic.js @@ -1,117 +1,167 @@ -// Farkel — pure game engine. No Phaser, no timers. Deterministic given a seed so -// the AI self-play test is reproducible and lookahead is side-effect free. +// Farkel — pure game engine. No Phaser, no timers, JSON-serialisable state (the +// scene autosaves it). Every random draw comes from an injected rng. // -// Scoring rules (confirmed): single 1 = 100, single 5 = 50; three-of-a-kind = -// face×100 (three 1s = 1000); four = 1000, five = 2000, six = 3000; straight -// 1-6 = 1500; three pairs = 1500. Hot dice: set aside all six and roll again, -// keeping the turn total. Must bank 500+ in one turn before any points count. +// Standard rules: each throw is scored ON ITS OWN — dice set aside from an +// earlier throw never combine with a later one. Single 1 = 100, single 5 = 50; +// three-of-a-kind = face×100 (three 1s = 1,000); four / five / six of a kind = +// 1,000 / 2,000 / 3,000; straight 1–6 = 1,500; three pairs (incl. four of a kind +// + a pair) = 1,500. Hot dice: once all six are set aside, roll all six again +// and keep the turn total. A turn must reach `entry` (default 500) before a +// player's first bank. First to `target` triggers one final round. +// +// House rules (state.rules): threeFarkle (−1,000 on a third Farkle in a row), +// twoTriplets (2,500), doubling (N-of-a-kind = triple ×2/×4/×8), piggyback +// (the next player may take over the leftover dice and turn total). -import { DICE, WIN_TARGET, ON_BOARD_MIN } from './FarkelData.js'; +import { DICE, DEFAULT_RULES, THREE_FARKLE_PENALTY, normalizeRules } from './FarkelData.js'; -// ── seeded RNG (mulberry32) ────────────────────────────────────────────────── -function mulberry32(seed) { - let a = seed >>> 0; - return function () { - a |= 0; a = (a + 0x6d2b79f5) | 0; - let t = Math.imul(a ^ (a >>> 15), 1 | a); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} +const LOG_CAP = 400; +const NUM = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six']; -// ── scoring helpers ────────────────────────────────────────────────────────── -function countsOf(dice) { +// ── scoring ────────────────────────────────────────────────────────────────── +export function countsOf(dice) { const c = [0, 0, 0, 0, 0, 0, 0]; for (const v of dice) c[v]++; return c; } -// Value of an N-of-a-kind (n >= 3) of face v. -function nKindValue(v, n) { - if (n === 3) return v === 1 ? 1000 : v * 100; - if (n === 4) return 1000; - if (n === 5) return 2000; - return 3000; // n === 6 +export function tripleValue(v) { return v === 1 ? 1000 : v * 100; } + +// Value of N (≥3) of a kind of face v. +export function nKindValue(v, n, rules = DEFAULT_RULES) { + if (n === 3) return tripleValue(v); + if (rules.doubling) return tripleValue(v) * 2 ** (n - 3); + return n === 4 ? 1000 : n === 5 ? 2000 : 3000; } -// For c (>=3) dice of face v, the best of "flat N-of-a-kind" vs -// "three-of-a-kind + the rest as singles" (only ever better for 1s/5s). -function bestGroupValue(v, c) { - const flat = nKindValue(v, c); - let alt = -1; - if (v === 1) alt = 1000 + (c - 3) * 100; - else if (v === 5) alt = 500 + (c - 3) * 50; - return Math.max(flat, alt); +function kindPart(v, n, rules) { + const key = n === 3 ? `three${v}` : n === 4 ? 'four' : n === 5 ? 'five' : 'six'; + return { key, label: `${NUM[n]} ${v}s`, points: nKindValue(v, n, rules), count: n, face: v }; +} +function singlesPart(v, n) { + return { key: `single${v}`, label: n === 1 ? `Single ${v}` : `${NUM[n]} ${v}s`, points: n * (v === 1 ? 100 : 50), count: n, face: v }; } -// Score a chosen multiset of dice, requiring that EVERY die contributes to a -// combo. Returns { valid, points }. -export function scoreSelection(dice) { - if (!dice || dice.length === 0) return { valid: false, points: 0 }; +// Score one throw's chosen dice. Every die must belong to a combo. +// Returns { valid, points, parts: [{ key, label, points, count, face? }] }. +export function scoreParts(dice, rules = DEFAULT_RULES) { + if (!dice || dice.length === 0) return { valid: false, points: 0, parts: [] }; const counts = countsOf(dice); - const total = dice.length; - let best = null; - const note = (p) => { best = best === null ? p : Math.max(best, p); }; + const cands = []; - // Whole-set six-dice patterns. - if (total === 6) { - if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] === 1)) note(1500); // straight - if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] % 2 === 0)) note(1500); // three pairs + if (dice.length === 6) { + if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] === 1)) { + cands.push([{ key: 'straight', label: 'Straight 1–6', points: 1500, count: 6 }]); + } + if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] % 2 === 0)) { + cands.push([{ key: 'pairs', label: 'Three Pairs', points: 1500, count: 6 }]); + } + if (rules.twoTriplets && counts.filter((c) => c === 3).length === 2) { + cands.push([{ key: 'triplets', label: 'Two Triplets', points: 2500, count: 6 }]); + } } - // Greedy decomposition — valid only if no die is left non-scoring. - let g = 0, ok = true; - for (let v = 1; v <= 6; v++) { + // Combos face by face (the only other way every die can score). + const parts = []; + let ok = true; + for (let v = 1; v <= 6 && ok; v++) { const c = counts[v]; if (c === 0) continue; - if (c >= 3) { g += bestGroupValue(v, c); } - else if (v === 1) g += c * 100; - else if (v === 5) g += c * 50; - else { ok = false; } + if (c >= 3) { + const flat = kindPart(v, c, rules); + // three of a kind plus the extras as singles (only ever an option for 1s/5s) + if ((v === 1 || v === 5) && c > 3) { + const alt = [kindPart(v, 3, rules), singlesPart(v, c - 3)]; + if (alt[0].points + alt[1].points > flat.points) { parts.push(...alt); continue; } + } + parts.push(flat); + } else if (v === 1 || v === 5) { + parts.push(singlesPart(v, c)); + } else ok = false; } - if (ok) note(g); + if (ok) cands.push(parts); - if (best === null) return { valid: false, points: 0 }; - return { valid: true, points: best }; + if (!cands.length) return { valid: false, points: 0, parts: [] }; + let best = null, bestPts = -1; + for (const p of cands) { + const pts = p.reduce((s, x) => s + x.points, 0); + if (pts > bestPts) { best = p; bestPts = pts; } + } + return { valid: true, points: bestPts, parts: best }; } -// Find the best subset of `dice` (rolled) to set aside given already set-aside -// dice from this turn. Brute-forces all 2^n subsets — feasible for n ≤ 6 (63 -// iterations). Returns the indices of rolled dice and the resulting combined score. -export function bestScoring(dice, setAsideDice = []) { - const n = dice.length; - let bestPts = 0; - let bestIndices = []; - for (let mask = 1; mask < (1 << n); mask++) { - const subset = []; - const indices = []; - for (let i = 0; i < n; i++) { - if (mask & (1 << i)) { subset.push(dice[i]); indices.push(i); } - } - const res = scoreSelection([...setAsideDice, ...subset]); - if (res.valid && res.points > bestPts) { - bestPts = res.points; - bestIndices = indices; - } - } - return { indices: bestIndices, points: bestPts }; +export function scoreSelection(dice, rules = DEFAULT_RULES) { + const r = scoreParts(dice, rules); + return { valid: r.valid, points: r.points }; +} +export function breakdownScoring(dice, rules = DEFAULT_RULES) { + return scoreParts(dice, rules).parts.map(({ label, points, key }) => ({ label, points, key })); } -// A roll is NOT a farkle if any subset of the rolled dice, when combined with -// already set-aside dice from this turn, produces a valid scoring set. -export function hasScoring(dice, setAsideDice = []) { - const n = dice.length; +function subsets(n) { + const out = []; for (let mask = 1; mask < (1 << n); mask++) { - const subset = []; - for (let i = 0; i < n; i++) if (mask & (1 << i)) subset.push(dice[i]); - if (scoreSelection([...setAsideDice, ...subset]).valid) return true; + const idx = []; + for (let i = 0; i < n; i++) if (mask & (1 << i)) idx.push(i); + out.push(idx); } + return out; +} +const SUBSETS = Array.from({ length: DICE + 1 }, (_, n) => subsets(n)); + +// The best set of dice to keep from one throw. Ties prefer using every die (hot +// dice), then keeping fewer dice. Returns { indices, points } (points 0 = none). +export function bestScoring(rolled, rules = DEFAULT_RULES) { + let best = { indices: [], points: 0 }; + for (const idx of SUBSETS[rolled.length]) { + const r = scoreSelection(idx.map((i) => rolled[i]), rules); + if (!r.valid) continue; + const allUsed = idx.length === rolled.length; + const bestAll = best.indices.length === rolled.length; + const better = r.points > best.points + || (r.points === best.points && ((allUsed && !bestAll) || (allUsed === bestAll && idx.length < best.indices.length))); + if (better) best = { indices: idx, points: r.points }; + } + return best; +} + +// Does this throw score at all? (Earlier set-aside dice never count.) +export function hasScoring(rolled, rules = DEFAULT_RULES) { + const c = countsOf(rolled); + if (c[1] || c[5]) return true; + for (let v = 2; v <= 6; v++) if (c[v] >= 3) return true; + if (rolled.length === 6) return scoreSelection(rolled, rules).valid; return false; } +// Which dice can take part in some scoring keep (for the hint glow). +export function scoringMask(rolled, rules = DEFAULT_RULES) { + const mask = rolled.map(() => false); + for (const idx of SUBSETS[rolled.length]) { + if (!scoreSelection(idx.map((i) => rolled[i]), rules).valid) continue; + for (const i of idx) mask[i] = true; + } + return mask; +} + +// Smart pick: the natural combo a click on die i belongs to. +export function smartGroup(rolled, i, rules = DEFAULT_RULES) { + const v = rolled[i]; + if (rolled.length === 6) { + const whole = scoreParts(rolled, rules); + if (whole.valid && whole.parts.length === 1 && whole.parts[0].count === 6) return rolled.map((_, k) => k); + } + const same = rolled.map((x, k) => (x === v ? k : -1)).filter((k) => k >= 0); + if (same.length >= 3) return same; + return [i]; +} + // ── state ──────────────────────────────────────────────────────────────────── -export function createInitialState({ playerCount = 4, names = [], skills = {}, seed } = {}) { - const rng = mulberry32((seed ?? (Date.now() & 0x7fffffff)) | 0); +function freshStats() { + return { turns: 0, banks: 0, bankTotal: 0, bestTurn: 0, farkles: 0, hotDice: 0, penalties: 0, piggybacks: 0, history: [0] }; +} + +export function createInitialState({ playerCount = 4, names = [], skills = {}, rules = {} } = {}) { const players = []; for (let seat = 0; seat < playerCount; seat++) { players.push({ @@ -121,115 +171,186 @@ export function createInitialState({ playerCount = 4, names = [], skills = {}, s onBoard: false, skill: skills[seat] ?? 3, isAI: seat !== 0, + farkleStreak: 0, + stats: freshStats(), }); } const state = { + version: 2, + rules: normalizeRules(rules), players, current: 0, + turnNo: 1, phase: 'awaitRoll', // awaitRoll | awaitPick | awaitDecision | farkled | gameover - winner: null, winners: [], + winner: null, finalRound: false, finalFrom: null, - _rng: rng, + piggyOffer: null, // { kept, available, from } when the piggyback rule offers one + log: [], + turn: null, }; resetTurn(state); return state; } function resetTurn(state) { - state.turn = { rolled: [], available: DICE, kept: 0, priorKept: 0, setAsideDice: [], hotDice: false }; + state.turn = { rolled: [], available: DICE, kept: 0, groups: [], cycle: 0, rolls: 0, hotDice: false, piggy: false, lastKeep: null }; state.phase = 'awaitRoll'; } -export function cloneState(s) { - const rngState = s._rng; // functions don't clone; lookahead must not roll dice - const copy = JSON.parse(JSON.stringify({ ...s, _rng: undefined })); - copy._rng = rngState; - return copy; +export function cloneState(s) { return JSON.parse(JSON.stringify(s)); } + +function log(state, entry) { + state.log.push({ turn: state.turnNo, seat: state.current, ...entry }); + if (state.log.length > LOG_CAP) state.log.splice(0, state.log.length - LOG_CAP); } -// Roll the available dice into turn.rolled. Sets phase to awaitPick, or farkled -// when no subset of the rolled dice (combined with already set-aside dice) scores. -export function rollDice(state) { +export const currentPlayer = (s) => s.players[s.current]; + +// Can the current player legally bank `total` this turn? +export function bankAllowed(state, total = state.turn.kept) { + const p = currentPlayer(state); + return total > 0 && (p.onBoard || total >= state.rules.entry); +} +export function canBank(state) { + return state.phase === 'awaitDecision' && bankAllowed(state); +} + +// Points the current player still needs this turn to beat the leader in the +// final round (0 when not chasing). +export function finalRoundNeed(state) { + if (!state.finalRound) return 0; + const me = currentPlayer(state); + let lead = -Infinity; + state.players.forEach((p) => { if (p.seat !== me.seat) lead = Math.max(lead, p.score); }); + return me.score > lead ? 0 : lead - me.score + 50; +} + +// ── actions ────────────────────────────────────────────────────────────────── +export function canRoll(state) { + return state.phase === 'awaitRoll' || state.phase === 'awaitDecision'; +} + +// Throw the available dice. Phase → awaitPick, or farkled if nothing scores. +export function rollDice(state, rng = Math.random) { + if (!canRoll(state)) return state; const t = state.turn; - const rng = state._rng; + if (state.piggyOffer && t.rolls === 0 && !t.piggy) state.piggyOffer = null; // declined const out = []; for (let i = 0; i < t.available; i++) out.push(1 + Math.floor(rng() * 6)); t.rolled = out; + t.rolls++; t.hotDice = false; - state.phase = hasScoring(out, t.setAsideDice) ? 'awaitPick' : 'farkled'; + state.phase = hasScoring(out, state.rules) ? 'awaitPick' : 'farkled'; + log(state, { kind: 'roll', dice: out.slice(), farkle: state.phase === 'farkled' }); return state; } -// Set aside the dice at the given indices (into turn.rolled). The turn score is -// always the combined value of ALL set-aside dice this cycle (not a running sum), -// so extending the set can unlock higher N-of-a-kind bonuses. Triggers hot dice -// when all available dice have been used. Returns true on a valid selection. -export function applySetAside(state, indices) { +// Take the piggyback offer (before the first roll of the turn). +export function takePiggyback(state) { + const o = state.piggyOffer; const t = state.turn; - const values = indices.map((i) => t.rolled[i]); - const combined = [...t.setAsideDice, ...values]; - const res = scoreSelection(combined); - if (!res.valid) return false; - - t.setAsideDice.push(...values); - t.available -= values.length; - t.rolled = []; - - if (t.available === 0) { - // Hot dice — carry this cycle's score into priorKept, then reset for new cycle. - t.priorKept += res.points; - t.kept = t.priorKept; - t.available = DICE; - t.setAsideDice = []; - t.hotDice = true; - } else { - t.kept = t.priorKept + res.points; - } - - state.phase = 'awaitDecision'; + if (!o || state.phase !== 'awaitRoll' || t.rolls > 0) return false; + t.kept = o.kept; + t.available = o.available; + t.piggy = true; + state.piggyOffer = null; + currentPlayer(state).stats.piggybacks++; + log(state, { kind: 'piggy', points: o.kept, available: o.available, from: o.from }); return true; } -// Bank the turn total (subject to the on-board minimum) and pass play. -// Returns { bankable, scoreBefore, scoreAfter } so the caller can -// handle score updates (e.g. for animations). Does NOT mutate state.score. -export function bank(state) { - const p = state.players[state.current]; +// Set aside the dice at `indices` (into turn.rolled). They must all score as +// one throw's combo. Hot dice when no dice remain. Returns the scored result +// or null on an invalid selection. +export function applySetAside(state, indices) { + if (state.phase !== 'awaitPick') return null; const t = state.turn; - const bankable = (p.onBoard || t.kept >= ON_BOARD_MIN) ? t.kept : 0; - const scoreBefore = p.score; - const scoreAfter = scoreBefore + bankable; - if (bankable > 0) p.onBoard = true; - advanceTurn(state); - return { bankable, scoreBefore, scoreAfter }; + const uniq = [...new Set(indices)].filter((i) => i >= 0 && i < t.rolled.length); + if (!uniq.length) return null; + const values = uniq.map((i) => t.rolled[i]); + const res = scoreParts(values, state.rules); + if (!res.valid) return null; + + t.kept += res.points; + t.groups.push({ dice: values, points: res.points, parts: res.parts, cycle: t.cycle }); + t.available -= values.length; + t.rolled = []; + t.lastKeep = { dice: values, points: res.points }; + let hot = false; + if (t.available === 0) { + hot = true; + t.available = DICE; + t.cycle++; + t.hotDice = true; + currentPlayer(state).stats.hotDice++; + } + state.phase = 'awaitDecision'; + log(state, { kind: 'keep', dice: values, points: res.points, total: t.kept, hot, label: res.parts.map((p) => p.label).join(' + ') }); + return { points: res.points, parts: res.parts, hot, total: t.kept }; } -// Forfeit the turn total and pass play. +// Bank the turn total and pass play. Returns { banked, total } or null. +export function bank(state) { + if (!canBank(state)) return null; + const p = currentPlayer(state); + const t = state.turn; + const banked = t.kept; + p.score += banked; + p.onBoard = true; + p.farkleStreak = 0; + p.stats.banks++; + p.stats.bankTotal += banked; + p.stats.bestTurn = Math.max(p.stats.bestTurn, banked); + log(state, { kind: 'bank', points: banked, score: p.score }); + const offer = state.rules.piggyback ? { kept: t.kept, available: t.available, from: p.seat } : null; + endTurn(state, offer); + return { banked, total: p.score }; +} + +// Lose the turn total after a Farkle. Returns { penalty }. export function farkleTurn(state) { - advanceTurn(state); - return state; + if (state.phase !== 'farkled') return { penalty: 0 }; + const p = currentPlayer(state); + p.stats.farkles++; + p.farkleStreak++; + let penalty = 0; + if (state.rules.threeFarkle && p.farkleStreak >= 3) { + penalty = Math.min(THREE_FARKLE_PENALTY, p.score); + p.score -= penalty; + p.farkleStreak = 0; + p.stats.penalties++; + } + log(state, { kind: 'farkle', lost: state.turn.kept, penalty, score: p.score }); + endTurn(state, null); + return { penalty }; } -function advanceTurn(state) { +function endTurn(state, offer) { const N = state.players.length; - const p = state.players[state.current]; + const p = currentPlayer(state); + p.stats.turns++; + p.stats.history.push(p.score); - if (!state.finalRound && p.score >= WIN_TARGET) { + if (!state.finalRound && p.score >= state.rules.target) { state.finalRound = true; state.finalFrom = state.current; + log(state, { kind: 'final', score: p.score }); } - state.current = (state.current + 1) % N; + if (state.current === 0) state.turnNo++; if (state.finalRound && state.current === state.finalFrom) { state.phase = 'gameover'; + state.piggyOffer = null; + state.turn.rolled = []; state.winners = computeWinners(state); state.winner = state.winners[0] ?? null; return; } resetTurn(state); + state.piggyOffer = offer && offer.kept > 0 ? offer : null; } function computeWinners(state) { @@ -241,28 +362,30 @@ function computeWinners(state) { export function isGameOver(state) { return state.phase === 'gameover'; } export function getWinners(state) { return state.winners; } -// ── display helper ─────────────────────────────────────────────────────────── -// Returns an array of { label, points } describing the scoring groups in `dice`. -export function breakdownScoring(dice) { - if (!dice || dice.length === 0) return []; - const total = dice.length; - const counts = countsOf(dice); - if (total === 6) { - if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] === 1)) return [{ label: 'Straight 1–6', points: 1500 }]; - if ([1, 2, 3, 4, 5, 6].every((v) => counts[v] % 2 === 0)) return [{ label: 'Three Pairs', points: 1500 }]; - } - const K = ['', '', '', 'Three', 'Four', 'Five', 'Six']; - const groups = []; - for (let v = 1; v <= 6; v++) { - const n = counts[v]; - if (n === 0) continue; - if (n >= 3) { - groups.push({ label: `${K[n]} ${v}s`, points: bestGroupValue(v, n) }); - } else if (v === 1) { - groups.push({ label: n === 1 ? 'Single 1' : 'Two 1s', points: n * 100 }); - } else if (v === 5) { - groups.push({ label: n === 1 ? 'Single 5' : 'Two 5s', points: n * 50 }); - } - } - return groups; +// 1-based standing per seat (ties share a rank). +export function rankings(state) { + return state.players.map((p) => 1 + state.players.filter((q) => q.score > p.score).length); +} + +export function leaderSeat(state) { + let best = null; + for (const p of state.players) if (p.score > 0 && (!best || p.score > best.score)) best = p; + if (!best) return null; + return state.players.filter((p) => p.score === best.score).length > 1 ? null : best.seat; +} + +export function fmtPts(n) { return Math.round(n).toLocaleString('en-US'); } + +// One human-readable line per log entry. +export function describeLog(state, e) { + const name = state.players[e.seat]?.name ?? '?'; + switch (e.kind) { + case 'roll': return e.farkle ? `${name} threw ${e.dice.join(' ')} — FARKLE` : `${name} threw ${e.dice.join(' ')}`; + case 'keep': return `${name} kept ${e.dice.join(' ')} (${e.label}) +${fmtPts(e.points)} → ${fmtPts(e.total)}${e.hot ? ' · HOT DICE' : ''}`; + case 'bank': return `${name} banked ${fmtPts(e.points)} → ${fmtPts(e.score)}`; + case 'farkle': return `${name} lost ${fmtPts(e.lost)}${e.penalty ? ` and paid the ${fmtPts(e.penalty)} three-Farkle penalty` : ''}`; + case 'piggy': return `${name} piggybacked ${fmtPts(e.points)} with ${e.available} dice`; + case 'final': return `${name} reached ${fmtPts(e.score)} — final round!`; + default: return ''; + } } diff --git a/src/games/farkel/FarkelPad.js b/src/games/farkel/FarkelPad.js new file mode 100644 index 0000000..2997ffe --- /dev/null +++ b/src/games/farkel/FarkelPad.js @@ -0,0 +1,185 @@ +// FarkelPad.js — the clipboard score sheet. One ruled row per turn, one column +// per player. Each banked turn is pencilled as a new running total (with the +// turn's points beside it) and the previous total gets struck through; a +// Farkle is a red "F". The sheet scrolls once the game outgrows the paper. + +import { playSoundEx, SFX } from '../../ui/Sounds.js'; +import { + PAD_HEAD, PAD_MARGIN, PAD_ROW_H, PAD_ROWS, PAD_GRID, padColW, padColX, padRowY, +} from './FarkelLayout.js'; +import { INK, INK_HEX, HAND_FONT, PRINT_FONT } from './FarkelArt.js'; +import { fmtPts } from './FarkelLogic.js'; + +const RED = '#b3261e'; + +export class FarkelPad { + constructor(scene, { players, depth, origin }) { + this.scene = scene; + this.n = players.length; + this.depth = depth; + this.origin = origin; + this.names = players.map((p) => p.name); + this.cells = []; + this.preview = null; + this.active = null; + } + + build() { + const s = this.scene; + s.add.image(this.origin.x, this.origin.y, this.origin.key).setOrigin(0).setDepth(this.depth); + this.hl = s.add.graphics().setDepth(this.depth + 1); + this.head = []; + for (let p = 0; p < this.n; p++) { + const x = padColX(p, this.n), w = padColW(this.n); + const max = Math.max(4, Math.floor(w / 15)); + const nm = this.names[p].length > max ? `${this.names[p].slice(0, max - 1)}…` : this.names[p]; + const name = s.add.text(x + w / 2, PAD_HEAD.y + PAD_HEAD.h / 2 - 2, nm, { + fontFamily: HAND_FONT, fontSize: this.n > 3 ? '24px' : '28px', color: INK[p], + }).setOrigin(0.5).setDepth(this.depth + 3); + const check = s.add.text(x + w - 12, PAD_HEAD.y + 14, '✓', { + fontFamily: HAND_FONT, fontSize: '22px', color: '#1d6a3c', + }).setOrigin(0.5).setDepth(this.depth + 3).setVisible(false); + const hat = s.add.image(x + 16, PAD_HEAD.y + 16, 'farkel-hat').setScale(0.6).setDepth(this.depth + 3).setVisible(false).setAngle(-12); + this.head.push({ name, check, hat }); + } + this.layer = s.add.container(0, 0).setDepth(this.depth + 2); + return this; + } + + // Highlighter band down the active player's column. + setActive(seat) { + this.active = seat; + const g = this.hl; + g.clear(); + if (seat === null || seat === undefined) return; + const x = padColX(seat, this.n), w = padColW(this.n); + g.fillStyle(0xfff07a, 0.28).fillRect(x + 3, PAD_HEAD.y + 4, w - 6, PAD_HEAD.h + PAD_ROWS * PAD_ROW_H - 8); + g.lineStyle(2, INK_HEX[seat], 0.7).lineBetween(x + 14, PAD_HEAD.y + PAD_HEAD.h - 8, x + w - 14, PAD_HEAD.y + PAD_HEAD.h - 8); + } + + // Rebuild every visible row from the game state. + syncFromState(gs, { leader = null } = {}) { + this.gs = gs; + this.layer.removeAll(true); + this.cells = gs.players.map(() => ({})); + const s = this.scene; + const turnsDone = gs.players.map((p) => p.stats.history.length - 1); + const rowsNeeded = Math.max(1, ...turnsDone.map((t, p) => t + (p === gs.current && gs.phase !== 'gameover' ? 1 : 0))); + const start = Math.max(0, rowsNeeded - PAD_ROWS); + this.start = start; + + for (let r = 0; r < Math.min(PAD_ROWS, rowsNeeded); r++) { + const turn = start + r + 1; + const y = padRowY(r) + PAD_ROW_H / 2; + this.layer.add(s.add.text(PAD_GRID.x + PAD_MARGIN / 2, y + 1, String(turn), { + fontFamily: PRINT_FONT, fontSize: '13px', color: '#8a7a60', + }).setOrigin(0.5)); + } + if (start > 0) { + this.layer.add(s.add.text(PAD_GRID.x + PAD_MARGIN / 2, PAD_HEAD.y + PAD_HEAD.h + 4, '⋮', { + fontFamily: PRINT_FONT, fontSize: '12px', color: '#8a7a60', + }).setOrigin(0.5, 0)); + } + + gs.players.forEach((pl, p) => { + const h = pl.stats.history; + const x = padColX(p, this.n), w = padColW(this.n); + // index of the latest turn that changed the total (that total stays unstruck) + let latest = 0; + for (let k = 1; k < h.length; k++) if (h[k] !== h[k - 1]) latest = k; + for (let k = Math.max(1, start + 1); k < h.length; k++) { + const r = k - 1 - start; + if (r < 0 || r >= PAD_ROWS) continue; + const y = padRowY(r) + PAD_ROW_H / 2; + const delta = h[k] - h[k - 1]; + const objs = []; + if (delta > 0) { + const plus = s.add.text(x + 10, y + 3, `+${fmtPts(delta)}`, { + fontFamily: HAND_FONT, fontSize: '16px', color: INK[p], + }).setOrigin(0, 0.5).setAlpha(0.6); + this.layer.add(plus); + objs.push(plus); + const tot = s.add.text(x + w - 10, y, fmtPts(h[k]), { + fontFamily: HAND_FONT, fontSize: '27px', color: INK[p], + }).setOrigin(1, 0.5); + this.layer.add(tot); + objs.push(tot); + if (k !== latest) objs.push(this.strike(tot, p)); + } else { + const f = s.add.text(x + 14, y, 'F', { fontFamily: HAND_FONT, fontSize: '26px', color: RED }).setOrigin(0, 0.5).setAngle(-6); + this.layer.add(f); + objs.push(f); + if (delta < 0) { + const pen = s.add.text(x + 36, y + 2, `−${fmtPts(-delta)}`, { fontFamily: HAND_FONT, fontSize: '17px', color: RED }).setOrigin(0, 0.5); + const tot = s.add.text(x + w - 10, y, fmtPts(h[k]), { fontFamily: HAND_FONT, fontSize: '27px', color: INK[p] }).setOrigin(1, 0.5); + this.layer.add([pen, tot]); + objs.push(pen, tot); + if (k !== latest) objs.push(this.strike(tot, p)); + } + } + this.cells[p][k] = objs; + } + // header marks + this.head[p].check.setVisible(pl.onBoard); + this.head[p].hat.setVisible(leader === p); + }); + this.drawPreview(); + } + + strike(textObj, p) { + const g = this.scene.add.graphics(); + const b = textObj.getBounds(); + g.lineStyle(2, INK_HEX[p], 0.75); + g.beginPath(); + g.moveTo(b.x - 3, b.centerY + 2); + g.lineTo(b.right + 3, b.centerY - 1); + g.strokePath(); + this.layer.add(g); + return g; + } + + // Animate the newest cell of `seat` being pencilled in (call after syncFromState). + async animateLatest(seat, { speed = 1 } = {}) { + const h = this.gs.players[seat].stats.history; + const objs = this.cells[seat][h.length - 1]; + if (!objs) return; + const s = this.scene; + playSoundEx(s, SFX.PENCIL_WRITE, { volume: 0.6 }); + objs.forEach((o) => { o.__a = o.alpha; o.setAlpha(0); }); + await new Promise((res) => { + objs.forEach((o, i) => s.tweens.add({ + targets: o, alpha: o.__a ?? 1, duration: 260 * speed, delay: i * 90 * speed, + onComplete: i === objs.length - 1 ? res : undefined, + })); + }); + // strike the previous total in the column, if it's visible + let prev = null; + for (let k = h.length - 2; k >= 1; k--) { + if (h[k] !== h[k - 1]) { prev = this.cells[seat][k]; break; } + } + const line = prev?.find((o) => o.type === 'Graphics'); + if (line && h[h.length - 1] !== h[h.length - 2]) { + line.setAlpha(0); + await new Promise((res) => s.tweens.add({ targets: line, alpha: 1, duration: 200 * speed, onComplete: res })); + } + } + + // Ghost pencil "+650" in the current row while a turn is running. + setPreview(seat, points) { + this.preview = points > 0 && seat !== null ? { seat, points } : null; + this.drawPreview(); + } + drawPreview() { + this.previewText?.destroy(); + this.previewText = null; + if (!this.preview || !this.gs) return; + const { seat, points } = this.preview; + const k = this.gs.players[seat].stats.history.length; // the row being played + const r = k - 1 - (this.start ?? 0); + if (r < 0 || r >= PAD_ROWS) return; + const x = padColX(seat, this.n), w = padColW(this.n); + this.previewText = this.scene.add.text(x + w / 2, padRowY(r) + PAD_ROW_H / 2, `+${fmtPts(points)}?`, { + fontFamily: HAND_FONT, fontSize: '22px', color: '#7d7466', + }).setOrigin(0.5).setAlpha(0.65).setDepth(this.depth + 3); + } +} diff --git a/src/games/farkel/FarkelSolver.js b/src/games/farkel/FarkelSolver.js new file mode 100644 index 0000000..8d55d7c --- /dev/null +++ b/src/games/farkel/FarkelSolver.js @@ -0,0 +1,193 @@ +// FarkelSolver.js — exact one-turn Farkle policy. Phaser-free, no state. +// +// A turn is a Markov decision process over (turn total t, dice left n). After a +// scoring throw you choose which combo to keep (→ t + points, n − used, or six +// fresh dice on hot dice), then bank or roll on. Because every keep strictly +// raises t, values can be filled from the largest total downward in one sweep. +// +// pointsSolver(rules, minBank) maximise expected banked points; banking is +// only allowed at t ≥ minBank (the entry rule) +// reachSolver(rules, need) maximise P(turn total ≥ need) — the final +// round chase, where anything less loses +// +// Totals are multiples of 50 up to T_MAX; beyond it the solver simply banks. + +import { DICE } from './FarkelData.js'; +import { scoreSelection, countsOf } from './FarkelLogic.js'; + +export const STEP = 50; +export const T_MAX = 20000; +const TI = T_MAX / STEP; + +const rulesKey = (r) => `${r.doubling ? 1 : 0}${r.twoTriplets ? 1 : 0}`; + +// ── throw outcomes ─────────────────────────────────────────────────────────── +// For n dice: every multiset of faces with its probability and, per number of +// dice used, the best points any valid keep of that size scores. +function multisets(n) { + const out = []; + const rec = (start, left, acc) => { + if (left === 0) { out.push(acc.slice()); return; } + for (let v = start; v <= 6; v++) { acc.push(v); rec(v, left - 1, acc); acc.pop(); } + }; + rec(1, n, []); + return out; +} +const FACT = [1, 1, 2, 6, 24, 120, 720]; +function multisetProb(dice) { + const c = countsOf(dice); + let ways = FACT[dice.length]; + for (let v = 1; v <= 6; v++) ways /= FACT[c[v]]; + return ways / 6 ** dice.length; +} +// All sub-multisets of a multiset (as count vectors → dice arrays). +function subMultisets(dice) { + const c = countsOf(dice); + const out = []; + const rec = (v, acc) => { + if (v > 6) { if (acc.length) out.push(acc.slice()); return; } + for (let k = 0; k <= c[v]; k++) { + for (let i = 0; i < k; i++) acc.push(v); + rec(v + 1, acc); + for (let i = 0; i < k; i++) acc.pop(); + } + }; + rec(1, []); + return out; +} + +const OUTCOME_CACHE = new Map(); +export function outcomes(rules) { + const key = rulesKey(rules); + if (OUTCOME_CACHE.has(key)) return OUTCOME_CACHE.get(key); + const byN = [null]; + for (let n = 1; n <= DICE; n++) { + const list = []; + let pFarkle = 0; + for (const ms of multisets(n)) { + const p = multisetProb(ms); + const best = new Map(); // used → points + for (const sub of subMultisets(ms)) { + const r = scoreSelection(sub, rules); + if (!r.valid) continue; + if ((best.get(sub.length) ?? -1) < r.points) best.set(sub.length, r.points); + } + if (!best.size) { pFarkle += p; continue; } + const opts = [...best].map(([used, pts]) => ({ used, pts, ti: pts / STEP, next: n - used || DICE })); + list.push({ p, opts }); + } + byN.push({ list, pFarkle }); + } + OUTCOME_CACHE.set(key, byN); + return byN; +} + +// ── generic sweep ──────────────────────────────────────────────────────────── +// bankV(ti) → value of banking at total ti*STEP (−Infinity when not allowed). +// stopAt(ti) → true if the state is terminal (value = bankV, no rolling). +function sweep(rules, bankV, stopAt) { + const outs = outcomes(rules); + const R = Array.from({ length: DICE + 1 }, () => new Float64Array(TI + 1)); + const V = Array.from({ length: DICE + 1 }, () => new Float64Array(TI + 1)); + const val = (ti, n) => (ti > TI ? Math.max(0, bankV(ti)) : V[n][ti]); + for (let ti = TI; ti >= 0; ti--) { + for (let n = 1; n <= DICE; n++) { + const b = bankV(ti); + if (ti === TI || stopAt(ti)) { R[n][ti] = Math.max(0, b); V[n][ti] = Math.max(0, b); continue; } + let r = 0; + for (const o of outs[n].list) { + let m = 0; + for (const op of o.opts) { const x = val(ti + op.ti, op.next); if (x > m) m = x; } + r += o.p * m; + } + R[n][ti] = r; + V[n][ti] = Math.max(r, b); + } + } + return { R, V }; +} + +function wrap(rules, tables, bankV, kind, param) { + const ti = (t) => Math.min(TI + 1, Math.round(t / STEP)); + return { + kind, param, + // value of rolling n dice holding total t + rollValue(t, n) { const i = ti(t); return i > TI ? Math.max(0, bankV(i)) : tables.R[n][i]; }, + // value of banking at t (−Infinity when not allowed) + bankValue(t) { return bankV(ti(t)); }, + // best of the two + value(t, n) { const i = ti(t); return i > TI ? Math.max(0, bankV(i)) : tables.V[n][i]; }, + shouldBank(t, n) { + const b = bankV(ti(t)); + return b > -Infinity && b >= this.rollValue(t, n); + }, + }; +} + +const SOLVER_CACHE = new Map(); +function cached(key, make) { + if (SOLVER_CACHE.has(key)) { + const v = SOLVER_CACHE.get(key); + SOLVER_CACHE.delete(key); SOLVER_CACHE.set(key, v); // LRU touch + return v; + } + const v = make(); + SOLVER_CACHE.set(key, v); + if (SOLVER_CACHE.size > 24) SOLVER_CACHE.delete(SOLVER_CACHE.keys().next().value); + return v; +} + +export function pointsSolver(rules, minBank = 0) { + const mb = Math.max(0, Math.ceil(minBank / STEP)); + return cached(`p:${rulesKey(rules)}:${mb}`, () => { + const bankV = (ti) => (ti >= Math.max(1, mb) ? ti * STEP : -Infinity); + const tables = sweep(rules, bankV, () => false); + return wrap(rules, tables, bankV, 'points', mb * STEP); + }); +} + +export function reachSolver(rules, need) { + const nd = Math.max(1, Math.ceil(need / STEP)); + return cached(`r:${rulesKey(rules)}:${nd}`, () => { + const bankV = (ti) => (ti >= nd ? 1 : -Infinity); + const tables = sweep(rules, bankV, (ti) => ti >= nd); + return wrap(rules, tables, bankV, 'reach', nd * STEP); + }); +} + +// ── policy over a concrete throw ───────────────────────────────────────────── +const SUBS = []; +for (let n = 0; n <= DICE; n++) { + const list = []; + for (let mask = 1; mask < (1 << n); mask++) { + const idx = []; + for (let i = 0; i < n; i++) if (mask & (1 << i)) idx.push(i); + list.push(idx); + } + SUBS.push(list); +} + +// Every distinct scoring keep of a throw, valued by `solver` from total t. +export function rankKeeps(rolled, t, rules, solver) { + const seen = new Map(); + for (const idx of SUBS[rolled.length]) { + const dice = idx.map((i) => rolled[i]); + const r = scoreSelection(dice, rules); + if (!r.valid) continue; + const key = dice.slice().sort().join(''); + if (seen.has(key)) continue; + const t2 = t + r.points; + const left = rolled.length - idx.length || DICE; + const roll = solver.rollValue(t2, left); + const bankV = solver.bankValue(t2); + seen.set(key, { indices: idx, points: r.points, total: t2, left, roll, bank: bankV, value: Math.max(roll, bankV) }); + } + return [...seen.values()].sort((a, b) => b.value - a.value || b.points - a.points); +} + +export function bestKeep(rolled, t, rules, solver) { + return rankKeeps(rolled, t, rules, solver)[0] ?? null; +} + +// Chance a throw of n dice scores nothing (from the enumeration). +export function farkleChance(rules, n) { return outcomes(rules)[n].pFarkle; } diff --git a/src/games/farkel/FarkelTray.js b/src/games/farkel/FarkelTray.js new file mode 100644 index 0000000..81d1a82 --- /dev/null +++ b/src/games/farkel/FarkelTray.js @@ -0,0 +1,389 @@ +// FarkelTray.js — the felt dice tray, the "set aside" rail and the leather cup, +// with six real 3D dice (src/ui/dice/Dice3D.js). +// +// Fairness: the engine rolls first (FarkelLogic.rollDice); throwDice() then +// plays a planned boxed throw whose dice are relabelled to land on exactly +// those faces. The animation never decides a result. +// +// The six Die3D objects are a pool. Dice kept this cycle sit on the rail in +// throw order (grouped); every other die is "in the tray" — idle, or the +// current throw, tidied into a centred row where rolled[i] is column i. + +import { Die3D, planTrayThrow, poseFromPlan, restingQ, qslerp } from '../../ui/dice/Dice3D.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; +import { DICE } from './FarkelData.js'; +import { + TRAY, RAIL, TRAY_WORLD, DIE_SIZE, REST_V, RAIL_V, CUP, columnU, railSlots, ground, toWorld, +} from './FarkelLayout.js'; +import { PAD_PX } from './FarkelArt.js'; + +const BODY = [246, 240, 224]; +const PIP = 0x1b1410; +const YAW = [0.1, -0.08, 0.05, -0.13, 0.09, -0.04]; +const lerp = (a, b, t) => a + (b - a) * t; +const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2); +const LIFT = 16; + +export class FarkelTray { + constructor(scene, depth, { onDieClick, onDieHover } = {}) { + this.scene = scene; + this.depth = depth; + this.onDieClick = onDieClick; + this.onDieHover = onDieHover; + this.poses = []; + this.enabled = false; + this.railDice = []; // die indices on the rail, in order + this.rollMap = []; // rolled index → die index + this.decor = { selected: new Set(), hints: null, coach: null, hover: -1, dimAll: false }; + } + + build() { + const s = this.scene; + s.add.image(TRAY.x - PAD_PX, TRAY.y - PAD_PX, 'farkel-tray').setOrigin(0).setDepth(this.depth); + s.add.image(RAIL.x - PAD_PX, RAIL.y - PAD_PX, 'farkel-rail').setOrigin(0).setDepth(this.depth + 1); + this.dice = Array.from({ length: DICE }, () => 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((_, d) => { + const z = s.add.zone(0, 0, 92, 92).setDepth(this.depth + 8); + z.on('pointerdown', (ptr) => { + const i = this.rollMap.indexOf(d); + if (this.enabled && i >= 0) this.onDieClick?.(i, ptr?.event); + }); + z.on('pointerover', () => { const i = this.rollMap.indexOf(d); if (this.enabled && i >= 0) this.onDieHover?.(i, true); }); + z.on('pointerout', () => { const i = this.rollMap.indexOf(d); if (i >= 0) this.onDieHover?.(i, false); }); + return z; + }); + for (let d = 0; d < DICE; d++) { + this.poses[d] = { u: columnU(d, DICE), v: REST_V, h: 0, q: restingQ(d + 1, YAW[d]), face: d + 1, spot: 'tray', alpha: 1 }; + this.apply(d); + } + return this; + } + + // ── pose helpers ─────────────────────────────────────────────────────────── + apply(d) { + const p = this.poses[d]; + const die = this.dice[d]; + die.g.setAlpha(p.alpha); + die.shadow.setAlpha(p.alpha); + die.set(p.u, p.v, p.h, p.q); + } + trayDice() { return this.dice.map((_, d) => d).filter((d) => !this.railDice.includes(d)); } + + // Put everything at rest instantly from a turn: this cycle's kept groups on + // the rail, the rest in the tray (showing `turn.rolled` when there is a throw). + layoutState(turn) { + const groups = (turn?.groups ?? []).filter((g) => g.cycle === turn.cycle); + const faces = groups.flatMap((g) => g.dice); + const { us } = railSlots(groups.map((g) => g.dice.length)); + this.railDice = faces.map((_, k) => k); + faces.forEach((f, k) => { + Object.assign(this.poses[k], { u: us[k], v: RAIL_V, h: 0, q: restingQ(f, YAW[k]), face: f, spot: 'rail', alpha: 1 }); + this.dice[k].setVisible(true); + this.apply(k); + }); + const tray = this.trayDice(); + const rolled = turn?.rolled ?? []; + this.rollMap = rolled.length ? tray.slice(0, rolled.length) : []; + tray.forEach((d, i) => { + if (i >= rolled.length) { + // not thrown yet: the dice are in the cup + Object.assign(this.poses[d], { u: columnU(i, tray.length), v: REST_V, h: 0, spot: 'cup', alpha: 0 }); + this.dice[d].glow = 0; + this.dice[d].setVisible(false); + return; + } + const face = rolled[i]; + Object.assign(this.poses[d], { u: columnU(i, rolled.length), v: REST_V, h: 0, q: restingQ(face, YAW[d]), face, spot: 'tray', alpha: 1 }); + this.dice[d].setVisible(true); + this.apply(d); + }); + this.refreshDecor(); + this.syncZones(); + } + + tweenDie(d, to, dur, { arc = 0, alphaTo = null, q = null } = {}) { + const p = this.poses[d]; + const from = { u: p.u, v: p.v, h: p.h, q: p.q, alpha: p.alpha }; + const qTo = q ?? p.q; + if (dur <= 0) { + Object.assign(p, { u: to.u, v: to.v, h: to.h ?? 0, q: qTo }); + if (alphaTo !== null) p.alpha = alphaTo; + this.apply(d); + return Promise.resolve(); + } + const prox = { t: 0 }; + return new Promise((resolve) => { + this.scene.tweens.add({ + targets: prox, t: 1, duration: dur, ease: 'Linear', + onUpdate: () => { + const t = easeInOut(prox.t); + p.u = lerp(from.u, to.u, t); + p.v = lerp(from.v, to.v, t); + p.h = lerp(from.h, to.h ?? 0, t) + arc * Math.sin(Math.PI * prox.t); + p.q = qslerp(from.q, qTo, t); + if (alphaTo !== null) p.alpha = lerp(from.alpha, alphaTo, t); + this.apply(d); + }, + onComplete: () => resolve(), + }); + }); + } + + // Gather dice into the cup (or towards a seat) and hide them. + async scoop(dice, target, dur = 260) { + if (!dice.length) return; + const w = toWorld(target.x, target.y); + await Promise.all(dice.map((d, k) => new Promise((res) => { + this.scene.time.delayedCall(k * 30, async () => { + this.poses[d].spot = 'cup'; + this.dice[d].glow = 0; + await this.tweenDie(d, { u: w.u, v: w.v + 30, h: 90 }, dur, { arc: 30, alphaTo: 0 }); + this.dice[d].setVisible(false); + res(); + }); + }))); + } + async scoopTray(target, dur) { + this.rollMap = []; + await this.scoop(this.trayDice(), target, dur); + } + async scoopAll(target, dur) { + this.rollMap = []; + const all = this.dice.map((_, d) => d).filter((d) => this.dice[d].visible); + this.railDice = []; + await this.scoop(all, target, dur); + } + + // Throw the tray dice so they land on `faces`, then tidy them into a row. + async throwDice(faces, origin, { speed = 1, fast = false } = {}) { + const s = this.scene; + const tray = this.trayDice(); + const dice = tray.slice(0, faces.length); + this.rollMap = []; + this.decor.selected = new Set(); + if (fast) { + dice.forEach((d, i) => { + Object.assign(this.poses[d], { u: columnU(i, faces.length), v: REST_V, h: 0, q: restingQ(faces[i], YAW[d]), face: faces[i], spot: 'tray', alpha: 1 }); + this.dice[d].setVisible(true); + this.apply(d); + }); + playSoundEx(s, SFX.DICE_ROLL, { volume: 0.5 }); + this.rollMap = dice.slice(); + this.refreshDecor(); + this.syncZones(); + return; + } + const plan = planTrayThrow(TRAY_WORLD, origin, faces, Math.random, DIE_SIZE, { + spread: faces.length > 4 ? 1.9 : 1.5, sep: 1.4, aim: { u0: 0.22, u1: 0.78, v0: 0.28, v1: 0.72 }, + }); + playSound(s, SFX.DICE_ROLL); + dice.forEach((d, i) => { + Object.assign(this.poses[d], { face: faces[i], spot: 'tray', alpha: 1 }); + this.dice[d].glow = 0; + this.dice[d].setVisible(true); + }); + const step = (t) => dice.forEach((d, i) => { + const p = poseFromPlan(plan, i, t); + Object.assign(this.poses[d], { u: p.u, v: p.v, h: p.h, q: p.q }); + this.apply(d); + }); + step(0); + const prox = { t: 0 }; + let clacks = 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); + // a couple of wooden clacks as dice hit the felt + if (clacks < 3 && prox.t > 0.3 + clacks * 0.18) { + clacks++; + playSoundEx(s, SFX.PIECE_CLICK, { volume: 0.22, rate: 1.1 + Math.random() * 0.5 }); + } + }, + onComplete: () => { step(1); resolve(); }, + }); + }); + await new Promise((resolve) => { + const sq = { k: 1.1 }; + s.tweens.add({ + targets: sq, k: 1, duration: 150, ease: 'Back.Out', + onUpdate: () => dice.forEach((d) => { this.dice[d].scale = sq.k; this.dice[d].draw(); }), + onComplete: () => { dice.forEach((d) => { this.dice[d].scale = 1; this.dice[d].draw(); }); resolve(); }, + }); + }); + await this.wait(120 * speed); + await Promise.all(dice.map((d, i) => this.tweenDie(d, { u: columnU(i, faces.length), v: REST_V, h: 0 }, 300 * speed, { + q: restingQ(faces[i], YAW[d]), + }))); + this.rollMap = dice.slice(); + this.refreshDecor(); + this.syncZones(); + } + + // Slide the kept dice (indices into the current throw) onto the rail. + // `sizes` = dice per group this cycle INCLUDING the new group. + async keepToRail(indices, sizes, dur = 300) { + const moving = indices.map((i) => this.rollMap[i]).filter((d) => d !== undefined); + const { us } = railSlots(sizes); + const base = this.railDice.length; + this.railDice.push(...moving); + this.rollMap = []; + this.decor.selected = new Set(); + this.decor.hints = null; + this.decor.coach = null; + const jobs = moving.map((d, k) => new Promise((res) => { + this.scene.time.delayedCall(dur > 0 ? k * 60 : 0, async () => { + this.poses[d].spot = 'rail'; + this.dice[d].glow = 0; + this.poses[d].alpha = 1; + await this.tweenDie(d, { u: us[base + k], v: RAIL_V, h: 0 }, dur, { arc: dur > 0 ? 70 : 0, q: restingQ(this.poses[d].face, YAW[d]) }); + if (dur > 0) playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.32, rate: 1.15 + Math.random() * 0.3 }); + res(); + }); + })); + await Promise.all(jobs); + this.refreshDecor(); + this.syncZones(); + } + + // Little celebratory hops (hot dice, a straight…). + async hop(dice, height = 46, dur = 420) { + await Promise.all(dice.map((d, k) => new Promise((res) => { + this.scene.time.delayedCall(k * 60, async () => { + const p = this.poses[d]; + await this.tweenDie(d, { u: p.u, v: p.v, h: 0 }, dur, { arc: height }); + res(); + }); + }))); + } + railHop(height, dur) { return this.hop(this.railDice.slice(), height, dur); } + rollHop(height, dur) { return this.hop(this.rollMap.slice(), height, dur); } + + wait(ms) { return new Promise((r) => this.scene.time.delayedCall(Math.max(0, ms), r)); } + + // ── decoration: selection lift, hint glow, coach glow, hover ─────────────── + setDecor(patch) { Object.assign(this.decor, patch); this.refreshDecor(); } + clearDecor() { this.decor = { selected: new Set(), hints: null, coach: null, hover: -1, dimAll: false }; this.refreshDecor(); } + + refreshDecor() { + const { selected, hints, coach, hover, dimAll } = this.decor; + for (let d = 0; d < DICE; d++) { + const die = this.dice[d]; + const p = this.poses[d]; + if (p.spot === 'cup') continue; + const i = this.rollMap.indexOf(d); + let glow = 0, color = 0xf5d020, alpha = 1, lift = 0; + if (i >= 0) { + if (selected.has(i)) { glow = 1; color = 0xf5d020; lift = LIFT; } + else if (coach && coach.includes(i)) { glow = 0.85; color = 0x7fd6ff; } + else if (hover === i) { glow = 0.7; color = 0xffffff; } + else if (hints) { glow = hints[i] ? 0.32 : 0; color = 0xfff3c0; alpha = hints[i] ? 1 : 0.62; } + } + if (dimAll && p.spot === 'tray') alpha = 0.45; + die.glow = glow; + die.opts.glowColor = color; + if (p.alpha !== alpha) p.alpha = alpha; + if (p.spot === 'tray' && p.h !== lift && !this.lifting?.has(d)) this.liftTo(d, lift); + else this.apply(d); + } + } + + liftTo(d, h) { + this.lifting ??= new Set(); + this.lifting.add(d); + const p = this.poses[d]; + this.tweenDie(d, { u: p.u, v: p.v, h }, 110).then(() => { + this.lifting.delete(d); + this.syncZones(); + }); + } + + // ── input ────────────────────────────────────────────────────────────────── + setEnabled(on) { + this.enabled = !!on; + this.zones.forEach((z) => (on ? z.setInteractive({ useHandCursor: true }) : z.disableInteractive())); + if (!on && this.decor.hover >= 0) this.setDecor({ hover: -1 }); + } + syncZones() { + this.dice.forEach((die, d) => { + const c = die.screenCenter(); + this.zones[d].setPosition(c.x, c.y); + }); + } + screenOfRoll(i) { + const d = this.rollMap[i]; + return d === undefined ? null : this.dice[d].screenCenter(); + } +} + +// ── the leather cup ────────────────────────────────────────────────────────── +export class FarkelCup { + 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); + this.img = s.add.image(CUP.x, CUP.y + CUP.h / 2 - 4, 'farkel-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.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; + } + 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.5, x: this.home.x + 34, y: this.home.y - 52, 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/farkel/tutorial.md b/src/games/farkel/tutorial.md index 7a537f4..9f375ac 100644 --- a/src/games/farkel/tutorial.md +++ b/src/games/farkel/tutorial.md @@ -32,9 +32,11 @@ If there's NOTHING — no 1s, no 5s, no three-of-a-kinds, nothing — that's a * ### Step 2: Set Aside Your Scoring Dice -You MUST set aside at least one scoring die each roll. Click the dice you want to keep and they'll lock in. Check the scoring chart below — it tells you exactly what each combination is worth. +You MUST set aside at least one scoring die each roll. Click the dice you want to keep — they pop up with a gold glow — and the chalkboard on the right lights up the combo you've made. Press **Best** if you just want the biggest score from the throw. -The dice you set aside are done for this turn. The ones you didn't pick? Those are still live. You can keep rolling them. +The dice you set aside slide onto the **Set Aside** rail under the tray, grouped by throw, and they're done for this turn. The ones you didn't pick? Those are still live. You can keep rolling them. + +**One throw at a time, my friend.** Every throw scores on its own. Dice you set aside earlier NEVER team up with dice from a later throw. Got three 2s last throw and a lone 2 this throw? That lone 2 is worth nothing — it's not four of a kind. A 1 and a 5 on the rail plus a 2-3-4-6 on the next throw? That's not a straight. That's a Farkle. Brutal. Fair. Mountain law. ### Step 3: Roll Again or Bank @@ -46,6 +48,17 @@ Now the real decision. The moment of truth. The top of the cliff. More dice = more scoring combinations. Fewer dice = higher Farkle risk. When you're down to one or two dice, you're basically pointing your skis straight down a sheet of ice and hoping for the best. Thrilling? Yes. Recommended? Debatable. +Check the **thermometer** next to the cup — it shows the exact chance that your next throw scores nothing: + +| Dice you'd roll | Farkle chance | +|---|---| +| 6 | 2% | +| 5 | 8% | +| 4 | 16% | +| 3 | 28% | +| 2 | 44% | +| 1 | 67% | + ### Hot Dice — The Mountain Calls! Here's the best rule in the entire game: if you manage to set aside ALL SIX DICE in a single turn, you get **Hot Dice**. You pick up all six dice and roll again, keeping every point you've built up so far. @@ -70,7 +83,7 @@ Hot Dice is like hitting a perfect powder stash, ripping through it top to botto | Straight (1-2-3-4-5-6) | 1,500 | | Three pairs | 1,500 | -Note: a straight and three pairs use all six dice at once — the game will recognize them automatically. +Note: a straight and three pairs use all six dice from ONE throw — the game will recognize them automatically. Four of a kind plus a pair counts as three pairs (1,500). ## Gerome's Mountain Wisdom (Tips) @@ -86,15 +99,38 @@ Note: a straight and three pairs use all six dice at once — the game will reco **6. Three 1s is the jackpot.** That's 1,000 points from three dice in one shot. It's like dropping off a cliff and landing in bottomless pow — it doesn't get better than that moment. +## House Rules + +Every lodge has its own rules, and ours are in **Menu → House Rules**. Changing them starts a fresh game. + +- **Play to** 5,000, 10,000 or 15,000. +- **Get on the board** with 0, 350, 500 or 1,000 in one turn. +- **Three-Farkle penalty** — Farkle three turns in a row and it costs you 1,000. Ouch. +- **Two triplets = 2,500** — two three-of-a-kinds in one throw. +- **Doubling kinds** — four of a kind is the triple ×2, five is ×4, six is ×8. Six 1s = 8,000. Gerome has seen it ONCE. +- **Piggyback** — when the player before you banks, you can take over their leftover dice AND their turn total. Roll a score and it's all yours. Farkle and it's gone. Pure backcountry. + +## Your Table at the Lodge + +- **Shake the cup:** press and hold the cup (or hold Space), then let go to throw. Or just hit **Roll**. +- **Score pad:** every banked turn gets pencilled in as your new total, the old one gets crossed out, and a Farkle is a big red **F**. The ✓ means that player is on the board; the red toque marks the leader. +- **Hints:** dice that can score glow softly and the duds dim. Turn it off in the Menu if you like it raw. +- **Smart pick:** clicking a die grabs its whole combo (all three 4s, the whole straight). Shift-click takes just that one die. +- **Coach:** switch it on in the Menu and I'll glow the best keep in blue and tell you whether rolling on beats banking. Straight from the math. No ego. +- **Turn Log:** press **Log** (or L) to see every throw, keep, bank and Farkle. +- **Your game saves** at the start of every turn. Leave the lodge and you can pick it back up later. + +**Keys:** Space shake & throw · 1–6 pick dice · R roll · B bank · A best keep · C clear · P piggyback · L log · Esc menu. During someone else's turn, click the tray (or tap Space) to hurry them along. + ## When the Final Round Hits The first player to cross 10,000 triggers the **final round** — everyone else gets one last turn to beat that score. No sudden death. Everyone gets their shot. -This is where Farkle turns into a chase scene. Trailing by 800 points with one turn left? That's your moment. Roll big. Bank nothing until you know you've got enough. This is Gerome's favorite part of the game, honestly. Pure mountain energy. All or nothing. +This is where Farkle turns into a chase scene. Trailing by 800 points with one turn left? That's your moment. Roll big. Bank nothing until you know you've got enough — the red ribbon over the tray tells you exactly how much you need. This is Gerome's favorite part of the game, honestly. Pure mountain energy. All or nothing. ## A Note on the AI Opponents -The computer players are smart. They've read the odds. They know when to bank and when to push. I won't lie to you — they'll Farkle sometimes, and when they do, it's extremely satisfying. But they'll also rip off a 3,000-point turn right when you think you've got it locked up. +The computer players range from first-day-on-skis (skill 1) to ski patrol (skill 5). The top ones have done the math on every single throw — which dice to keep, when to bank, and exactly how hard to chase in the final round. I won't lie to you — they'll Farkle sometimes, and when they do, it's extremely satisfying. But they'll also rip off a 3,000-point turn right when you think you've got it locked up. Treat them like the locals at a powder day. Respectful. A little competitive. Always slightly better at reading the mountain than you'd like. diff --git a/tools/verifyFarkel.js b/tools/verifyFarkel.js new file mode 100644 index 0000000..40f6007 --- /dev/null +++ b/tools/verifyFarkel.js @@ -0,0 +1,314 @@ +#!/usr/bin/env node +// verifyFarkel.js — headless checks for Farkle: +// • scoring table (standard + every house rule), parts/labels +// • per-roll scoring: dice from different throws never combine (regressions) +// • farkle odds by enumeration, hot dice, entry minimum, bank gating +// • final round, three-Farkle penalty, piggyback, rankings, autosave JSON +// • solver: odds, textbook keeps, monotone values, reach solver +// • AI: never banks below entry or short of the final-round leader; +// seeded self-play terminates; skill ladder 1 < 2 < 3 < 4 < 5 +// • screen layout: furniture on screen, no overlaps (when present) +// Usage: node tools/verifyFarkel.js [--quick] + +import * as L from '../src/games/farkel/FarkelLogic.js'; +import { DEFAULT_RULES, FARKLE_ODDS, normalizeRules, scoringReference } from '../src/games/farkel/FarkelData.js'; +import { pointsSolver, reachSolver, bestKeep, rankKeeps, farkleChance } from '../src/games/farkel/FarkelSolver.js'; +import { planDecision, wantsPiggyback, coachAdvice } from '../src/games/farkel/FarkelAI.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +const R = (o = {}) => normalizeRules(o); + +// ── scoring ────────────────────────────────────────────────────────────────── +section('Scoring'); +{ + const T = [ + [[1], 100], [[5], 50], [[1, 1], 200], [[5, 5], 100], [[1, 5], 150], + [[1, 1, 1], 1000], [[2, 2, 2], 200], [[3, 3, 3], 300], [[4, 4, 4], 400], [[5, 5, 5], 500], [[6, 6, 6], 600], + [[2, 2, 2, 2], 1000], [[3, 3, 3, 3, 3], 2000], [[4, 4, 4, 4, 4, 4], 3000], + [[1, 1, 1, 1], 1100], [[5, 5, 5, 5], 1000], [[1, 1, 1, 1, 1, 1], 3000], + [[1, 2, 3, 4, 5, 6], 1500], [[2, 2, 3, 3, 4, 4], 1500], [[2, 2, 2, 2, 3, 3], 1500], + [[2, 2, 2, 3, 3, 3], 500], [[1, 1, 1, 5, 5, 5], 1500], [[2, 2, 2, 1], 300], [[3, 3, 3, 5, 5], 400], + ]; + for (const [d, pts] of T) { + const r = L.scoreSelection(d); + ok(`score ${d.join('')} = ${pts}`, r.valid && r.points === pts, JSON.stringify(r)); + } + for (const d of [[2], [1, 2], [2, 2], [3, 4], [1, 1, 6], [2, 3, 4, 5, 6]]) { + ok(`invalid ${d.join('')}`, !L.scoreSelection(d).valid); + } + // house rules + ok('two triplets 2500', L.scoreSelection([2, 2, 2, 3, 3, 3], R({ twoTriplets: true })).points === 2500); + ok('two triplets beats 1s+5s triples', L.scoreSelection([1, 1, 1, 5, 5, 5], R({ twoTriplets: true })).points === 2500); + const dbl = R({ doubling: true }); + ok('doubling four 2s = 400', L.scoreSelection([2, 2, 2, 2], dbl).points === 400); + ok('doubling five 3s = 1200', L.scoreSelection([3, 3, 3, 3, 3], dbl).points === 1200); + ok('doubling six 1s = 8000', L.scoreSelection([1, 1, 1, 1, 1, 1], dbl).points === 8000); + ok('doubling four 2s + pair = three pairs 1500', L.scoreSelection([2, 2, 2, 2, 3, 3], dbl).points === 1500); + // parts + reference keys line up + const keys = new Set(scoringReference(R({ twoTriplets: true })).map((r) => r.key)); + for (const d of [[1], [5, 5], [1, 1, 1], [6, 6, 6], [2, 2, 2, 2], [4, 4, 4, 4, 4], [3, 3, 3, 3, 3, 3], [1, 2, 3, 4, 5, 6], [2, 2, 4, 4, 6, 6], [2, 2, 2, 3, 3, 3]]) { + const p = L.scoreParts(d, R({ twoTriplets: true })); + ok(`parts of ${d.join('')} are reference rows`, p.parts.every((x) => keys.has(x.key)), p.parts.map((x) => x.key).join()); + ok(`parts of ${d.join('')} sum`, p.parts.reduce((s, x) => s + x.points, 0) === p.points); + } + ok('best keep 1,5,2,3,4,6 → straight', L.bestScoring([1, 5, 2, 3, 4, 6]).points === 1500); + ok('best keep prefers hot dice on ties', L.bestScoring([5, 5, 5, 1, 1, 1]).indices.length === 6); + ok('smart group triple', L.smartGroup([2, 4, 2, 6, 2, 3], 2).join() === '0,2,4'); + ok('smart group straight', L.smartGroup([1, 2, 3, 4, 5, 6], 3).length === 6); + ok('smart group single 1', L.smartGroup([1, 2, 3, 4, 4, 6], 0).join() === '0'); + ok('scoring mask', L.scoringMask([1, 2, 3, 5, 6, 6]).join() === 'true,false,false,true,false,false'); +} + +// ── per-roll scoring regressions (the old engine combined throws) ──────────── +section('Per-roll scoring'); +{ + const s = L.createInitialState({ playerCount: 2 }); + // set aside 1 and 5, then throw 2,3,4,6 — a Farkle, not a straight + s.phase = 'awaitPick'; s.turn.rolled = [1, 5, 2, 2, 3, 6]; + L.applySetAside(s, [0, 1]); + ok('kept 150', s.turn.kept === 150 && s.turn.available === 4); + ok('2,3,4,6 after 1,5 is a Farkle', !L.hasScoring([2, 3, 4, 6])); + // set aside 2,2,2 then throw a single 2 — no four of a kind + const s2 = L.createInitialState({ playerCount: 2 }); + s2.phase = 'awaitPick'; s2.turn.rolled = [2, 2, 2, 3, 4, 6]; + L.applySetAside(s2, [0, 1, 2]); + ok('three 2s = 200', s2.turn.kept === 200); + ok('a lone 2 later does not score', !L.hasScoring([2, 3, 4])); + s2.phase = 'awaitPick'; s2.turn.rolled = [2, 1, 3]; + ok('cannot add a 2 to an old triple', L.applySetAside(s2, [0]) === null); + ok('the 1 still scores', L.applySetAside(s2, [1])?.points === 100 && s2.turn.kept === 300); + // set aside 1,1 then 3,3,4,4 — not three pairs + ok('3,3,4,4 alone does not score', !L.hasScoring([3, 3, 4, 4])); +} + +// ── odds ───────────────────────────────────────────────────────────────────── +section('Farkle odds'); +{ + for (let n = 1; n <= 6; n++) { + let farkles = 0, total = 6 ** n; + for (let k = 0; k < total; k++) { + const d = []; let x = k; + for (let i = 0; i < n; i++) { d.push(1 + (x % 6)); x = Math.floor(x / 6); } + if (!L.hasScoring(d)) farkles++; + } + ok(`${n}-die farkle odds`, Math.abs(farkles / total - FARKLE_ODDS[n]) < 1e-12, `${farkles}/${total}`); + ok(`${n}-die solver odds`, Math.abs(farkleChance(DEFAULT_RULES, n) - FARKLE_ODDS[n]) < 1e-12); + } +} + +// ── turn flow ──────────────────────────────────────────────────────────────── +section('Turn flow'); +{ + const s = L.createInitialState({ playerCount: 3, names: ['A', 'B', 'C'] }); + ok('starts awaitRoll', s.phase === 'awaitRoll' && s.turn.available === 6); + ok('cannot bank before rolling', L.bank(s) === null); + s.phase = 'awaitPick'; s.turn.rolled = [1, 1, 1, 5, 5, 5]; + const hot = L.applySetAside(s, [0, 1, 2, 3, 4, 5]); + ok('hot dice', hot.hot && s.turn.available === 6 && s.turn.kept === 1500 && s.players[0].stats.hotDice === 1); + ok('hot dice groups keep cycle', s.turn.groups[0].cycle === 0 && s.turn.cycle === 1); + ok('bank allowed ≥ entry', L.canBank(s)); + const b = L.bank(s); + ok('banked 1500', b.banked === 1500 && s.players[0].score === 1500 && s.players[0].onBoard); + ok('next player', s.current === 1 && s.phase === 'awaitRoll' && s.turn.kept === 0); + // entry gating + s.phase = 'awaitPick'; s.turn.rolled = [1, 5, 2, 3, 4, 4]; + L.applySetAside(s, [0, 1]); + ok('150 < entry: bank blocked', !L.canBank(s) && L.bank(s) === null); + ok('rolling on is allowed', L.canRoll(s)); + // farkle + s.phase = 'farkled'; + L.farkleTurn(s); + ok('farkle passes', s.current === 2 && s.players[1].stats.farkles === 1 && s.players[1].farkleStreak === 1); + // entry 0 + const z = L.createInitialState({ playerCount: 2, rules: { entry: 0 } }); + z.phase = 'awaitPick'; z.turn.rolled = [5, 2, 3, 4, 6, 6]; + L.applySetAside(z, [0]); + ok('entry 0 allows a 50 bank', L.canBank(z)); + // seeded rolls + const a = L.createInitialState({ playerCount: 2 }); + const c = L.createInitialState({ playerCount: 2 }); + L.rollDice(a, mulberry32(7)); L.rollDice(c, mulberry32(7)); + ok('seeded roll repeatable', a.turn.rolled.join() === c.turn.rolled.join()); + ok('state is JSON-safe', JSON.stringify(L.cloneState(a)) === JSON.stringify(a)); +} + +section('Final round'); +{ + const s = L.createInitialState({ playerCount: 3, names: ['A', 'B', 'C'] }); + s.players.forEach((p) => { p.onBoard = true; }); + s.players[0].score = 9800; + s.phase = 'awaitPick'; s.turn.rolled = [1, 1, 1, 2, 3, 4]; + L.applySetAside(s, [0, 1, 2]); + L.bank(s); + ok('final round triggered', s.finalRound && s.finalFrom === 0 && s.players[0].score === 10800); + ok('B needs 10,850 − score', L.finalRoundNeed(s) === 10800 - s.players[1].score + 50); + s.phase = 'farkled'; L.farkleTurn(s); + ok('C still to play', s.phase === 'awaitRoll' && s.current === 2); + s.players[2].score = 11000; + ok('C leads: needs nothing', L.finalRoundNeed(s) === 0); + s.phase = 'farkled'; L.farkleTurn(s); + ok('game over after the lap', L.isGameOver(s) && s.winners.join() === '2'); + ok('rankings', L.rankings(s).join() === '2,3,1'); +} + +section('House rules'); +{ + const s = L.createInitialState({ playerCount: 2, rules: { threeFarkle: true } }); + s.players[0].score = 700; s.players[0].onBoard = true; + for (let k = 0; k < 3; k++) { + s.current = 0; s.phase = 'farkled'; + const r = L.farkleTurn(s); + if (k < 2) ok(`farkle ${k + 1}: no penalty`, r.penalty === 0); + else ok('third farkle costs up to 1,000', r.penalty === 700 && s.players[0].score === 0 && s.players[0].farkleStreak === 0); + } + // piggyback + const p = L.createInitialState({ playerCount: 2, rules: { piggyback: true } }); + p.phase = 'awaitPick'; p.turn.rolled = [1, 1, 1, 2, 3, 4]; + L.applySetAside(p, [0, 1, 2]); + L.bank(p); + ok('piggyback offered', p.piggyOffer && p.piggyOffer.kept === 1000 && p.piggyOffer.available === 3); + ok('take piggyback', L.takePiggyback(p) && p.turn.kept === 1000 && p.turn.available === 3 && !L.canBank(p)); + const q = L.createInitialState({ playerCount: 2, rules: { piggyback: true } }); + q.phase = 'awaitPick'; q.turn.rolled = [1, 1, 1, 2, 3, 4]; + L.applySetAside(q, [0, 1, 2]); L.bank(q); + L.rollDice(q, mulberry32(3)); + ok('rolling fresh declines the offer', q.piggyOffer === null && q.turn.kept === 0 && q.turn.rolls === 1); + ok('piggy AI decision is boolean', typeof wantsPiggyback(p, 5) === 'boolean'); + ok('rules normalise', normalizeRules({ target: 123, entry: 7 }).target === 10000 && normalizeRules({ entry: 7 }).entry === 500); +} + +// ── solver ─────────────────────────────────────────────────────────────────── +section('Solver'); +{ + const s0 = pointsSolver(DEFAULT_RULES, 0); + const e = s0.rollValue(0, 6); + ok('expected turn ≈ 590', e > 560 && e < 620, e.toFixed(1)); + const s5 = pointsSolver(DEFAULT_RULES, 500); + ok('entry rule lowers the value', s5.rollValue(0, 6) < e); + ok('never bank with 6 dice at 1000', !s0.shouldBank(1000, 6)); + ok('bank 2 dice at 600', s0.shouldBank(600, 2)); + ok('roll 3 dice at 200', !s0.shouldBank(200, 3)); + ok('roll 4 dice at 500', !s0.shouldBank(500, 4)); + ok('bank below entry impossible', !s5.shouldBank(300, 1)); + let mono = true; + for (let n = 1; n <= 6; n++) for (let t = 50; t <= 5000; t += 50) if (s0.value(t, n) + 1e-9 < s0.value(t - 50, n)) mono = false; + ok('value monotone in total', mono); + const k1 = bestKeep([1, 5, 2, 3, 4, 4], 0, DEFAULT_RULES, s0); + ok('textbook: keep a lone 1 from 1,5,…', k1.indices.length === 1 && k1.points === 100); + const k2 = bestKeep([1, 2, 3, 4, 5, 6], 0, DEFAULT_RULES, s0); + ok('keep a straight', k2.points === 1500); + const r = reachSolver(DEFAULT_RULES, 1000); + const p = r.rollValue(0, 6); + ok('reach 1000 probability sane', p > 0.25 && p < 0.6, p.toFixed(3)); + ok('reach is monotone in need', reachSolver(DEFAULT_RULES, 2000).rollValue(0, 6) < p); + ok('ranked keeps sorted', rankKeeps([1, 1, 5, 2, 3, 6], 0, DEFAULT_RULES, s0).every((k, i, a) => !i || a[i - 1].value >= k.value)); + const st = L.createInitialState({ playerCount: 2 }); + st.phase = 'awaitPick'; st.turn.rolled = [1, 5, 2, 3, 4, 4]; + const adv = coachAdvice(st, [0, 1]); + ok('coach flags a 1+5 keep as worse than the lone 1', adv && adv.regret > 0 && adv.best.points === 100); +} + +// ── AI play ────────────────────────────────────────────────────────────────── +function playTurn(s, skill, rng, checks) { + for (let guard = 0; guard < 200; guard++) { + if (s.piggyOffer && s.turn.rolls === 0 && wantsPiggyback(s, skill)) L.takePiggyback(s); + L.rollDice(s, rng); + if (s.phase === 'farkled') { L.farkleTurn(s); return 0; } + const me = s.players[s.current]; + const need = L.finalRoundNeed(s); + const d = planDecision(s, skill, rng); + const res = L.applySetAside(s, d.keep); + if (!res) { checks.badKeep++; return 0; } + if (d.bank) { + const leadBefore = Math.max(...s.players.filter((p) => p !== me).map((p) => p.score)); + const wasFinal = s.finalRound; + const b = L.bank(s); + if (!b) { checks.badBank++; return 0; } + if (wasFinal && need > 0 && me.score <= leadBefore) checks.finalShort++; + return b.banked; + } + } + checks.stuck++; + return 0; +} + +section('AI self-play'); +{ + const rng = mulberry32(12345); + const checks = { badKeep: 0, badBank: 0, finalShort: 0, stuck: 0 }; + const GAMES = QUICK ? 120 : 600; + let turns = 0, maxTurns = 0, belowTarget = 0; + const ruleSets = [{}, { entry: 0 }, { entry: 1000, target: 5000 }, { threeFarkle: true, piggyback: true }, { doubling: true, twoTriplets: true, target: 15000 }]; + for (let g = 0; g < GAMES; g++) { + const n = 2 + (g % 3); + const skills = {}; + for (let i = 0; i < n; i++) skills[i] = 1 + Math.floor(rng() * 5); + const s = L.createInitialState({ playerCount: n, skills, rules: ruleSets[g % ruleSets.length] }); + let k = 0; + while (!L.isGameOver(s) && k < 3000) { playTurn(s, s.players[s.current].skill, rng, checks); k++; } + turns += k; maxTurns = Math.max(maxTurns, k); + ok(`game ${g} finished`, L.isGameOver(s), `${k} turns`); + if (Math.max(...s.players.map((p) => p.score)) < s.rules.target) belowTarget++; + ok(`game ${g} winners hold the max`, s.winners.every((w) => s.players[w].score === Math.max(...s.players.map((p) => p.score)))); + } + ok('every keep was legal', checks.badKeep === 0, String(checks.badKeep)); + ok('never banked illegally (entry)', checks.badBank === 0, String(checks.badBank)); + ok('never banked short of the final-round leader', checks.finalShort === 0, String(checks.finalShort)); + ok('no stuck turns', checks.stuck === 0); + ok('winner always reached the target', belowTarget === 0, String(belowTarget)); + console.log(` ${GAMES} games · avg ${(turns / GAMES).toFixed(1)} turns · max ${maxTurns}`); +} + +section('Skill ladder'); +{ + const N = QUICK ? 30000 : 120000; + const avg = []; + for (let sk = 1; sk <= 5; sk++) { + const rng = mulberry32(900 + sk); + const checks = { badKeep: 0, badBank: 0, finalShort: 0, stuck: 0 }; + let sum = 0; + for (let i = 0; i < N; i++) { + const s = L.createInitialState({ playerCount: 2, skills: { 0: sk } }); + s.players[0].onBoard = true; + sum += playTurn(s, sk, rng, checks); + } + avg[sk] = sum / N; + } + console.log(` points/turn: ${avg.slice(1).map((a, i) => `${i + 1}:${a.toFixed(0)}`).join(' ')}`); + for (let sk = 2; sk <= 5; sk++) ok(`skill ${sk} > skill ${sk - 1}`, avg[sk] > avg[sk - 1] + 5, `${avg[sk].toFixed(1)} vs ${avg[sk - 1].toFixed(1)}`); + const opt = pointsSolver(DEFAULT_RULES, 0).rollValue(0, 6); + ok('skill 5 matches the solver', Math.abs(avg[5] - opt) < opt * 0.03, `${avg[5].toFixed(1)} vs ${opt.toFixed(1)}`); +} + +// ── layout (optional until the scene modules exist) ───────────────────────── +section('Layout'); +try { + const Y = await import('../src/games/farkel/FarkelLayout.js'); + for (let nOpp = 1; nOpp <= 3; nOpp++) { + const f = Y.hudFurniture(nOpp); + for (const r of f) 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++) { + if (Y.ALLOWED_OVERLAPS?.has(`${f[i].name}|${f[j].name}`)) continue; + ok(`${f[i].name} ∩ ${f[j].name} (${nOpp} opp)`, !Y.rectsOverlap(f[i], f[j])); + } + } + // six dice fit across the tray and the rail + for (let n = 1; n <= 6; n++) { + const xs = Array.from({ length: n }, (_, i) => Y.columnU(i, n)); + ok(`${n} columns inside the felt`, xs.every((u) => u > Y.DIE_SIZE && u < Y.TRAY_FELT.w - Y.DIE_SIZE)); + } + for (let k = 0; k < 6; k++) ok(`rail slot ${k} on the rail`, Y.railU(k, 6, 3) > 0 && Y.TRAY_FELT.x + Y.railU(k, 6, 3) < Y.RAIL.x + Y.RAIL.w); +} catch (e) { + if (e.code === 'ERR_MODULE_NOT_FOUND') console.log(' (layout module not present — skipped)'); + else { ok('layout module loads', false, e.message); } +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);