From 7a3205799b726f1559643ac8cbbe021740bbce63 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Tue, 24 Nov 2026 09:18:11 -0700 Subject: [PATCH] Overhaul craps with full table art, 3D dice, expanded bets, and AI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add perspective-projected craps tub: baked felt layout, padded rail, diamond-pyramid walls, house bank, dice bowl, ON/OFF puck (CrapsArt.js) - True 3D die rendering and physics-lite throw that relabels the cube to match the rolled face (CrapsDice.js) - Table geometry module with zones, seats, bet lanes, hit-testing shared by art and input (CrapsTable.js) - Expand rules: Buy/Lay/Big/Hardways and all one-roll props; 3-4-5× odds caps, barred 12s, called-on working, contract bets, come-bet travel, plain-English payout explanations (CrapsLogic.js) - Rewrite the scene: shared casino dock, per-seat chip stacks in the rail, felt click-through hit-testing, learner hints, roll-history board, results card, speed/felt settings (CrapsGame.js) - AI profiles gain hardway/prop/lay appetite and injectable RNG for deterministic verification (CrapsAI.js) - Add headless verifier: 36-combo resolution tables, exact Markov house edges, chip-conservation AI soak, geometry and dice-throw checks (tools/verifyCraps.js) --- src/games/craps/CrapsAI.js | 100 +- src/games/craps/CrapsArt.js | 699 +++++++++ src/games/craps/CrapsDice.js | 334 +++++ src/games/craps/CrapsGame.js | 2661 +++++++++++++++++++++------------ src/games/craps/CrapsLogic.js | 620 ++++++-- src/games/craps/CrapsTable.js | 313 ++++ tools/verifyCraps.js | 598 ++++++++ 7 files changed, 4227 insertions(+), 1098 deletions(-) create mode 100644 src/games/craps/CrapsArt.js create mode 100644 src/games/craps/CrapsDice.js create mode 100644 src/games/craps/CrapsTable.js create mode 100644 tools/verifyCraps.js diff --git a/src/games/craps/CrapsAI.js b/src/games/craps/CrapsAI.js index 30c9e12..373dcd5 100644 --- a/src/games/craps/CrapsAI.js +++ b/src/games/craps/CrapsAI.js @@ -4,26 +4,36 @@ // shapes what they bet and how big. Functions return plain bet specs / odds // requests; the scene applies them through CrapsLogic (which guards affordability). -import { BET, POINT_NUMBERS, legalBetTypes, oddsEligibleBets, maxOddsFor } from './CrapsLogic.js'; +import { + BET, POINT_NUMBERS, HARD_NUMBERS, legalBetTypes, oddsEligibleBets, maxOddsFor, +} from './CrapsLogic.js'; const PROFILES = { // unitPct: flat-bet size as a fraction of bankroll - // oddsMult: odds as a multiple of the flat bet - // fieldChance: probability of tossing a field bet on a come-out - // place: which numbers they like to place during the point phase - // dontChance: probability of betting the Don't side instead of Pass - conservative: { unitPct: 0.03, oddsMult: 1, fieldChance: 0.10, place: [], dontChance: 0.18, comeChance: 0.10 }, - balanced: { unitPct: 0.05, oddsMult: 2, fieldChance: 0.25, place: [6, 8], dontChance: 0.10, comeChance: 0.25 }, - aggressive: { unitPct: 0.08, oddsMult: 3, fieldChance: 0.55, place: [6, 8, 5, 9], dontChance: 0.05, comeChance: 0.45 }, - gambler: { unitPct: 0.11, oddsMult: 3, fieldChance: 0.80, place: [6, 8, 4, 10],dontChance: 0.00, comeChance: 0.60 }, + // oddsMult: odds as a multiple of the flat bet (capped at the table's 3-4-5×) + // fieldChance: chance of a field flyer on a roll + // place: numbers they like to place during the point phase + // dontChance: chance of betting the Don't side instead of Pass + // comeChance / maxCome: come-bet appetite (and how many working at once) + // hardChance: chance of backing the point (and 6/8) the hard way + // propChance: chance of a one-roll proposition flyer (C&E / Yo / Any craps) + // layChance: chance of laying the 4 or 10 (dark-side players only) + conservative: { unitPct: 0.03, oddsMult: 1, fieldChance: 0.05, place: [], dontChance: 0.35, comeChance: 0.10, maxCome: 1, hardChance: 0, propChance: 0, layChance: 0.4 }, + balanced: { unitPct: 0.05, oddsMult: 2, fieldChance: 0.12, place: [6, 8], dontChance: 0.10, comeChance: 0.30, maxCome: 2, hardChance: 0.12, propChance: 0.05, layChance: 0 }, + aggressive: { unitPct: 0.08, oddsMult: 5, fieldChance: 0.30, place: [6, 8, 5, 9], dontChance: 0.05, comeChance: 0.45, maxCome: 2, hardChance: 0.30, propChance: 0.15, layChance: 0 }, + gambler: { unitPct: 0.11, oddsMult: 5, fieldChance: 0.45, place: [6, 8, 4, 10], dontChance: 0.00, comeChance: 0.55, maxCome: 3, hardChance: 0.50, propChance: 0.35, layChance: 0 }, }; const PROFILE_KEYS = Object.keys(PROFILES); -function profileFor(player) { +export function profileName(player) { const name = player.name ?? player.avatar?.id ?? 'bot'; let h = 0; for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0; - return PROFILES[PROFILE_KEYS[h % PROFILE_KEYS.length]]; + return PROFILE_KEYS[h % PROFILE_KEYS.length]; +} + +function profileFor(player) { + return PROFILES[profileName(player)]; } const snap = (n, step) => Math.max(step, Math.round(n / step) * step); @@ -38,45 +48,56 @@ function placeSize(player, prof, number) { return Math.min(120, snap(player.chips * prof.unitPct, step)); } -// Flat bets to open for the current phase. Returns an array of bet specs. -export function chooseBets(player, state) { +// Flat bets to open for the next roll. Returns an array of bet specs. +// `rng` is injectable so the verify soak is deterministic. +export function chooseBets(player, state, rng = Math.random) { const prof = profileFor(player); const legal = legalBetTypes(state); const specs = []; let budget = player.chips; const afford = (amt) => amt > 0 && amt <= budget; + const push = (spec) => { if (afford(spec.amount)) { specs.push(spec); budget -= spec.amount; } }; + const has = (type, number = null) => player.bets.some((b) => b.type === type && (number == null || b.number === number)); + const unit = unitFor(player, prof); if (state.point === null) { - // Come-out: take a line bet, maybe a field flyer. - const unit = unitFor(player, prof); - const hasLine = player.bets.some((b) => b.type === BET.PASS || b.type === BET.DONT_PASS); - if (!hasLine && afford(unit)) { - const dont = Math.random() < prof.dontChance && legal.has(BET.DONT_PASS); - specs.push({ type: dont ? BET.DONT_PASS : BET.PASS, amount: unit }); - budget -= unit; + // Come-out: a line bet, maybe a flyer. + const hasLine = has(BET.PASS) || has(BET.DONT_PASS); + if (!hasLine && legal.has(BET.PASS)) { + const dont = rng() < prof.dontChance; + push({ type: dont ? BET.DONT_PASS : BET.PASS, amount: unit }); } - if (Math.random() < prof.fieldChance) { - const f = snap(unit / 2, 5); - if (afford(f)) { specs.push({ type: BET.FIELD, amount: f }); budget -= f; } - } - } else { - // Point phase: maybe a come bet, plus favourite place numbers. - if (Math.random() < prof.comeChance) { - const unit = unitFor(player, prof); - if (afford(unit)) { specs.push({ type: BET.COME, amount: unit }); budget -= unit; } - } - const placed = new Set(player.bets.filter((b) => b.type === BET.PLACE).map((b) => b.number)); - for (const num of prof.place) { - if (placed.has(num) || num === state.point) continue; - if (!POINT_NUMBERS.includes(num)) continue; - const amt = placeSize(player, prof, num); - if (afford(amt)) { specs.push({ type: BET.PLACE, number: num, amount: amt }); budget -= amt; } + if (rng() < prof.fieldChance) push({ type: BET.FIELD, amount: snap(unit / 2, 5) }); + if (rng() < prof.propChance) push({ type: rng() < 0.6 ? BET.CE : BET.YO, amount: rng() < 0.5 ? 2 : 5 }); + return specs; + } + + // Point phase. + const comeCount = player.bets.filter((b) => b.type === BET.COME || b.type === BET.DONT_COME).length; + const dark = has(BET.DONT_PASS); + if (comeCount < prof.maxCome && rng() < prof.comeChance) { + push({ type: dark ? BET.DONT_COME : BET.COME, amount: unit }); + } + if (dark && rng() < prof.layChance) { + for (const n of [4, 10]) { + if (n !== state.point && !has(BET.LAY, n)) { push({ type: BET.LAY, number: n, amount: snap(unit * 2, 20) }); break; } } } + const comeNums = new Set(player.bets.map((b) => b.comePoint).filter((n) => n != null)); + for (const num of prof.place) { + if (has(BET.PLACE, num) || num === state.point || comeNums.has(num)) continue; + if (!POINT_NUMBERS.includes(num)) continue; + push({ type: BET.PLACE, number: num, amount: placeSize(player, prof, num) }); + } + if (HARD_NUMBERS.includes(state.point) && !has(BET.HARD, state.point) && rng() < prof.hardChance) { + push({ type: BET.HARD, number: state.point, amount: 5 }); + } + if (rng() < prof.fieldChance * 0.5) push({ type: BET.FIELD, amount: snap(unit / 2, 5) }); + if (rng() < prof.propChance * 0.4) push({ type: BET.ANY_CRAPS, amount: 1 + Math.floor(rng() * 5) }); return specs; } -// Odds to lay behind eligible line/come bets. Returns [{ betId, amount }]. +// Odds behind eligible line/come bets that don't have them yet. Returns [{ betId, amount }]. export function chooseOdds(player, state) { const prof = profileFor(player); if (prof.oddsMult <= 0) return []; @@ -84,8 +105,9 @@ export function chooseOdds(player, state) { let budget = player.chips; for (const bet of oddsEligibleBets(player, state)) { if (bet.oddsAmount > 0) continue; - const want = Math.min(bet.amount * prof.oddsMult, maxOddsFor(bet)); - const amt = snap(want, 5); + const cap = maxOddsFor(bet, state); + const want = Math.min(bet.amount * prof.oddsMult, cap); + const amt = Math.min(cap, snap(want, 5)); if (amt > 0 && amt <= budget) { out.push({ betId: bet.id, amount: amt }); budget -= amt; } } return out; diff --git a/src/games/craps/CrapsArt.js b/src/games/craps/CrapsArt.js new file mode 100644 index 0000000..cde4e9a --- /dev/null +++ b/src/games/craps/CrapsArt.js @@ -0,0 +1,699 @@ +// Craps table art — one end of a casino craps tub baked once into 'craps-table': +// floor shadow, padded rail with a wooden chip groove, the sunken felt with the +// full betting layout, proposition box and C&E circles, diamond-pyramid rubber +// on the inner walls, the house bank set into the far rail, and the stickman's +// dice bowl. Also bakes the ON/OFF puck. +// +// All positions come from CrapsTable.js so the art lines up with hit-testing +// and chip placement. + +import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { CHIP_DEFS } from '../../ui/CasinoChips.js'; +import { + P, VIEW, TUB, lift, tubOutline, ZONES, ROWS, BOX_NUMS, boxU, END_U, LAYOUT_U1, PASS_SIDE, + PROP, LANDING, BANK, BOWL, LANES, SLOT_ORDER, rectCenter, +} from './CrapsTable.js'; + +const W = 1920, H = 1080; +export const FELTS = { green: '#0d5a2e', blue: '#123c78', red: '#6a1020' }; +const LINE = 'rgba(244,236,214,0.88)'; +const LINE_SOFT = 'rgba(244,236,214,0.45)'; +const WHITE = '#f4ecd6'; +const RED = '#d8392b'; +const GOLD = '#e8c15a'; +const SERIF = 'Georgia, "Times New Roman", serif'; +const SANS = '"Julius Sans One", sans-serif'; +const LEATHER_DARK = '#0f0806', LEATHER_MID = '#2c1a12', LEATHER_HI = '#5e3e2b'; + +export async function prepareCrapsArt(scene, felt = 'green') { + await prepareCasinoArt(scene); + const key = `craps-table-${felt}`; + if (!scene.textures.exists(key)) bakeTable(scene, key, FELTS[felt] ?? FELTS.green); + if (!scene.textures.exists('craps-puck-on')) bakePuck(scene, 'craps-puck-on', true); + if (!scene.textures.exists('craps-puck-off')) bakePuck(scene, 'craps-puck-off', false); + return key; +} + +// ── Small projection helpers ───────────────────────────────────────────────── +const toScreen = (pts, h = 0) => pts.map(p => lift(p.u, p.v, h)); + +function rectPts(r) { + return [P.project(r.u0, r.v0), P.project(r.u1, r.v0), P.project(r.u1, r.v1), P.project(r.u0, r.v1)]; +} + +function strokeRect(ctx, r, color = LINE, width = 2.4) { + poly(ctx, rectPts(r)); + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); +} + +function fillRect(ctx, r, color) { + poly(ctx, rectPts(r)); + ctx.fillStyle = color; + ctx.fill(); +} + +// Text lying flat on the felt at (u, v): sized in px at s = 1. +function feltText(ctx, u, v, text, size, color, { + font = SERIF, bold = true, rot = 0, spacing = 0, alpha = 1, maxW = null, shadow = true, +} = {}) { + const p = P.project(u, v); + ctx.save(); + ctx.globalAlpha = alpha; + ctx.translate(p.x, p.y); + ctx.scale(p.s, p.s * VIEW.squash); + ctx.rotate(rot); + ctx.font = `${bold ? 'bold ' : ''}${size}px ${font}`; + if (spacing) ctx.letterSpacing = `${spacing}px`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + if (shadow) { + ctx.shadowColor = 'rgba(0,0,0,0.4)'; + ctx.shadowBlur = 2; + ctx.shadowOffsetY = 1; + } + ctx.fillStyle = color; + if (maxW) { + const w = ctx.measureText(text).width; + if (w > maxW) ctx.scale(maxW / w, 1); + } + ctx.fillText(text, 0, 0); + ctx.restore(); +} + +const PIPS = { + 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]], +}; + +// A small die printed on the felt. +function feltDie(ctx, u, v, size, face, { body = '#f4ecd6', pip = '#1a1208', alpha = 1 } = {}) { + const p = P.project(u, v); + ctx.save(); + ctx.globalAlpha = alpha; + ctx.translate(p.x, p.y); + ctx.scale(p.s, p.s * VIEW.squash); + rr(ctx, -size / 2, -size / 2, size, size, size * 0.2); + ctx.fillStyle = body; + ctx.fill(); + ctx.lineWidth = 1.2; + ctx.strokeStyle = 'rgba(0,0,0,0.5)'; + ctx.stroke(); + ctx.fillStyle = pip; + for (const [x, y] of PIPS[face]) { + ctx.beginPath(); + ctx.arc(x * size * 0.27, y * size * 0.27, size * 0.1, 0, Math.PI * 2); + ctx.fill(); + } + ctx.restore(); +} + +// Text printed up a band that runs along v at a fixed u (reading bottom → top, +// i.e. from v1 toward v0). Each letter sits on the projected centre line with +// its baseline along the band and its uprights along the felt's u direction, so +// the lettering leans with the perspective instead of standing straight up. +function feltTextUpBand(ctx, u, v0, v1, text, size, color, { font = SERIF, bold = true, spacing = 0, alpha = 1 } = {}) { + ctx.save(); + ctx.globalAlpha = alpha; + ctx.font = `${bold ? 'bold ' : ''}${size}px ${font}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = color; + ctx.shadowColor = 'rgba(0,0,0,0.4)'; + ctx.shadowBlur = 2; + ctx.shadowOffsetY = 1; + const q = VIEW.squash; + const chars = [...text]; + const widths = chars.map((ch) => (ctx.measureText(ch).width + spacing) * q); + const total = widths.reduce((a, b) => a + b, 0) - spacing * q; + const DV = 0.0005; + // Walk `px` felt-pixels (screen distance ÷ local scale) along the band; dir −1 = up the screen. + const walk = (v, px, dir) => { + let rem = px; + while (rem > 1e-6) { + const a = P.project(u, v), b = P.project(u, v + dir * DV); + const d = Math.hypot(b.x - a.x, b.y - a.y) / a.s; + if (d >= rem) { v += dir * DV * (rem / d); rem = 0; } else { v += dir * DV; rem -= d; } + } + return v; + }; + let v = walk((v0 + v1) / 2, total / 2, +1); // start below the centre + chars.forEach((ch, i) => { + const mid = walk(v, widths[i] / 2, -1); + v = walk(v, widths[i], -1); + if (ch === ' ') return; + const p = P.project(u, mid); + const up = P.project(u, mid - DV), dn = P.project(u, mid + DV); + const tl = Math.hypot(up.x - dn.x, up.y - dn.y); + const tx = (up.x - dn.x) / tl, ty = (up.y - dn.y) / tl; // reading direction + const r0 = P.project(u - 0.001, mid), r1 = P.project(u + 0.001, mid); + const rl = Math.hypot(r1.x - r0.x, r1.y - r0.y); + const rx = (r1.x - r0.x) / rl, ry = (r1.y - r0.y) / rl; // glyph "down" = toward +u + const k = p.s; + ctx.save(); + ctx.transform(tx * k * q, ty * k * q, rx * k, ry * k, p.x, p.y); + ctx.fillText(ch, 0, 0); + ctx.restore(); + }); + ctx.restore(); +} + +function dicePair(ctx, u, v, size, a, b, opts) { + const p = P.project(u, v); + const du = (size * 0.62) / (VIEW.halfW * p.s); + feltDie(ctx, u - du, v, size, a, opts); + feltDie(ctx, u + du, v, size, b, opts); +} + +// ── Table ──────────────────────────────────────────────────────────────────── +function bakeTable(scene, key, felt) { + const c = canvas(W, H); + const ctx = c.getContext('2d'); + drawFloorShadow(ctx); + drawRailFace(ctx); + drawFelt(ctx, felt); + drawWalls(ctx); + drawRailTop(ctx); + drawBank(ctx); + drawBowl(ctx); + scene.textures.addCanvas(key, c); +} + +function outlineScreen(d, h, extraDown = 0) { + return tubOutline(d, 14, 40).map(p => { + const q = lift(p.u, p.v, h); + return { x: q.x, y: q.y + extraDown * q.s, s: q.s }; + }); +} + +function drawFloorShadow(ctx) { + const OFF = 6000; + const pts = outlineScreen(TUB.RW, TUB.H, TUB.FACE + 10); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.75)'; + ctx.shadowBlur = 70; + ctx.shadowOffsetX = OFF; + ctx.shadowOffsetY = 30; + poly(ctx, pts.map(p => ({ x: p.x - OFF, y: p.y }))); + ctx.fillStyle = '#000'; + ctx.fill(); + ctx.restore(); +} + +// The rail's outer side (visible below the near rail and around the end). +function drawRailFace(ctx) { + const top = outlineScreen(TUB.RW, TUB.H); + ctx.save(); + poly(ctx, top.map(p => ({ x: p.x, y: p.y + TUB.FACE * p.s }))); + ctx.fillStyle = '#2a170c'; + ctx.fill(); + for (let i = 0; i <= 14; i++) { + const f = i / 14; + poly(ctx, top.map(p => ({ x: p.x, y: p.y + TUB.FACE * p.s * f }))); + ctx.lineWidth = 4; + ctx.strokeStyle = mix('#7a4520', '#2a170c', Math.min(1, f * 1.2)); + ctx.stroke(); + } + // brass kick-rail line + poly(ctx, top.map(p => ({ x: p.x, y: p.y + TUB.FACE * p.s * 0.78 }))); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(214,174,90,0.55)'; + ctx.stroke(); + ctx.restore(); +} + +function drawFelt(ctx, felt) { + const feltPts = outlineScreen(0, 0); + ctx.save(); + poly(ctx, feltPts); + ctx.clip(); + ctx.fillStyle = felt; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 256, 22); + ctx.fillRect(0, 0, W, H); + + drawLayout(ctx, felt); + drawProps(ctx, felt); + drawLanding(ctx); + + // overhead lamp + vignette toward the walls + const c = P.project(-0.1, 0.5); + const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1000); + lamp.addColorStop(0, 'rgba(255,246,205,0.18)'); + lamp.addColorStop(0.5, 'rgba(255,246,205,0.06)'); + lamp.addColorStop(1, 'rgba(255,246,205,0)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); + const vig = ctx.createRadialGradient(c.x, c.y, 420, c.x, c.y, 1150); + vig.addColorStop(0, 'rgba(0,0,0,0)'); + vig.addColorStop(1, 'rgba(0,0,0,0.45)'); + ctx.fillStyle = vig; + ctx.fillRect(0, 0, W, H); + // contact shadow along the walls + for (let i = 0; i < 9; i++) { + poly(ctx, toScreen(tubOutline(-i * 0.006, 14, 40))); + ctx.lineWidth = 5; + ctx.strokeStyle = `rgba(0,0,0,${0.3 * (1 - i / 9)})`; + ctx.stroke(); + } + ctx.restore(); +} + +// ── Betting end ────────────────────────────────────────────────────────────── +function drawLayout(ctx, felt) { + const Z = (k) => ZONES[k].rects[0]; + + // Number boxes + for (const n of BOX_NUMS) { + const { u0, u1 } = boxU(n); + const um = (u0 + u1) / 2; + strokeRect(ctx, { u0, u1, v0: ROWS.lay[0], v1: ROWS.buy[1] }, LINE, 2.6); + strokeRect(ctx, { u0, u1, v0: ROWS.lay[1], v1: ROWS.main[1] }, LINE_SOFT, 1.4); + const label = n === 6 ? 'SIX' : n === 9 ? 'NINE' : String(n); + feltText(ctx, um, 0.15, label, n === 6 || n === 9 ? 34 : 50, WHITE, { maxW: 120 }); + feltText(ctx, um, ROWS.lay[0] + 0.028, 'LAY', 13, LINE_SOFT, { font: SANS, bold: false, spacing: 2 }); + const pays = n === 6 || n === 8 ? '7 TO 6' : n === 5 || n === 9 ? '7 TO 5' : '9 TO 5'; + feltText(ctx, um, 0.225, pays, 12, GOLD, { font: SANS, bold: false, alpha: 0.8 }); + feltText(ctx, um, (ROWS.buy[0] + ROWS.buy[1]) / 2, 'BUY', 13, LINE_SOFT, { font: SANS, bold: false, spacing: 2 }); + } + + // Don't Come bar + { + const r = Z('dontcome'); + strokeRect(ctx, r, LINE, 2.6); + const um = (r.u0 + r.u1) / 2; + feltText(ctx, um, 0.08, "DON'T", 17, WHITE); + feltText(ctx, um, 0.125, 'COME', 17, WHITE); + feltText(ctx, um, 0.17, 'BAR', 14, WHITE, { font: SANS }); + dicePair(ctx, um, 0.215, 15, 6, 6); + } + + // Come + { + const r = Z('come'); + strokeRect(ctx, r, LINE, 2.6); + const c = rectCenter(r); + feltText(ctx, c.u, c.v - 0.012, 'COME', 64, RED, { spacing: 14 }); + } + + // Field + { + const r = Z('field'); + strokeRect(ctx, r, LINE, 2.6); + const nums = [2, 3, 4, 9, 10, 11, 12]; + const u0 = r.u0 + 0.16, u1 = r.u1 - 0.05; + const vm = r.v0 + (r.v1 - r.v0) * 0.36; + feltText(ctx, r.u0 + 0.075, vm + 0.012, 'FIELD', 30, GOLD, { spacing: 3 }); + nums.forEach((n, i) => { + const u = u0 + ((i + 0.5) / nums.length) * (u1 - u0); + if (n === 2 || n === 12) { + const p = P.project(u, vm); + ctx.save(); + ctx.translate(p.x, p.y); + ctx.scale(p.s, p.s * VIEW.squash); + ctx.beginPath(); + ctx.arc(0, 0, 25, 0, Math.PI * 2); + ctx.lineWidth = 2.4; + ctx.strokeStyle = GOLD; + ctx.stroke(); + ctx.restore(); + feltText(ctx, u, vm + 0.004, String(n), 30, WHITE); + feltText(ctx, u, vm + 0.058, n === 2 ? 'PAYS DOUBLE' : 'PAYS TRIPLE', 11, GOLD, { font: SANS, bold: false }); + } else { + feltText(ctx, u, vm + 0.004, String(n), 34, WHITE); + if (i < nums.length - 1) feltText(ctx, u + (u1 - u0) / nums.length / 2, vm, '•', 18, GOLD); + } + }); + } + + // Big 6 / 8 + for (const [k, n] of [['big6', 6], ['big8', 8]]) { + const r = Z(k); + strokeRect(ctx, r, LINE, 2.6); + const c = rectCenter(r); + feltText(ctx, c.u, c.v - 0.018, String(n), 54, RED); + feltText(ctx, c.u, r.v0 + 0.02, 'BIG', 12, WHITE, { font: SANS, bold: false }); + } + + // Don't Pass bar + { + const r = Z('dontpass'); + strokeRect(ctx, r, LINE, 2.6); + const c = rectCenter(r); + feltText(ctx, c.u - 0.06, c.v, "DON'T PASS BAR", 24, WHITE, { spacing: 3 }); + dicePair(ctx, c.u + 0.24, c.v, 18, 6, 6); + } + + // Pass line — bottom band + the band up the end, drawn as one L + { + const b = ZONES.pass.rects[0], sd = ZONES.pass.rects[1]; + const pts = [ + P.project(sd.u0, sd.v0), P.project(sd.u1, sd.v0), P.project(sd.u1, b.v0), + P.project(b.u1, b.v0), P.project(b.u1, b.v1), P.project(b.u0, b.v1), + ]; + poly(ctx, pts); + ctx.lineWidth = 3; + ctx.strokeStyle = LINE; + ctx.stroke(); + const c = rectCenter(b); + feltText(ctx, c.u - 0.03, c.v - 0.012, 'PASS LINE', 56, WHITE, { spacing: 8 }); + // up the end + feltTextUpBand(ctx, (sd.u0 + sd.u1) / 2, sd.v0, b.v0, 'PASS LINE', 34, WHITE, { spacing: 6 }); + } + + // Odds strip behind the line (subtle) + { + const r = ZONES.odds.rects[0]; + const pts = [P.project(r.u0, r.v0), P.project(r.u1, r.v0)]; + ctx.save(); + ctx.setLineDash([10, 8]); + poly(ctx, pts, false); + ctx.lineWidth = 1.4; + ctx.strokeStyle = LINE_SOFT; + ctx.stroke(); + ctx.restore(); + for (const u of [r.u0 + 0.12, (r.u0 + r.u1) / 2, r.u1 - 0.12]) { + feltText(ctx, u, (r.v0 + r.v1) / 2 + 0.006, 'ODDS', 14, LINE_SOFT, { font: SANS, bold: false, spacing: 4 }); + } + } + + void felt; +} + +// ── Proposition box ────────────────────────────────────────────────────────── +function drawProps(ctx, felt) { + const outer = { u0: PROP.u0, u1: PROP.u1, v0: PROP.v0, v1: PROP.v1 }; + fillRect(ctx, outer, 'rgba(0,0,0,0.12)'); + strokeRect(ctx, outer, GOLD, 3); + const Z = (k) => ZONES[k].rects[0]; + + // Any seven + { + const r = Z('any7'); + strokeRect(ctx, r, LINE, 2); + const c = rectCenter(r); + feltText(ctx, c.u, c.v, 'SEVEN 4 TO 1', 22, RED, { maxW: 200 }); + } + // Hardways + const HW = { hard6: [3, 3, '9 TO 1'], hard10: [5, 5, '7 TO 1'], hard8: [4, 4, '9 TO 1'], hard4: [2, 2, '7 TO 1'] }; + for (const [k, [a, b, pays]] of Object.entries(HW)) { + const r = Z(k); + strokeRect(ctx, r, LINE, 2); + const c = rectCenter(r); + dicePair(ctx, c.u, c.v - 0.025, 22, a, b, { body: '#c41f2a', pip: '#fbf3df' }); + feltText(ctx, c.u, c.v + 0.04, pays, 15, WHITE, { font: SANS }); + } + // One-roll row + const ONE = { acedeuce: [1, 2, '15 TO 1'], aces: [1, 1, '30 TO 1'], boxcars: [6, 6, '30 TO 1'], yo: [5, 6, '15 TO 1'] }; + for (const [k, [a, b, pays]] of Object.entries(ONE)) { + const r = Z(k); + strokeRect(ctx, r, LINE, 2); + const c = rectCenter(r); + dicePair(ctx, c.u, c.v - 0.025, 15, a, b, { body: '#c41f2a', pip: '#fbf3df' }); + feltText(ctx, c.u, c.v + 0.032, pays, 11, WHITE, { font: SANS }); + } + // Horn + { + const r = Z('horn'); + strokeRect(ctx, r, LINE, 2); + const c = rectCenter(r); + feltText(ctx, c.u - 0.07, c.v, 'HORN', 22, GOLD, { spacing: 4 }); + feltText(ctx, c.u + 0.07, c.v, '2 · 3 · 11 · 12', 15, WHITE, { font: SANS }); + } + // Any craps + { + const r = Z('anycraps'); + strokeRect(ctx, r, LINE, 2); + const c = rectCenter(r); + feltText(ctx, c.u, c.v, 'ANY CRAPS 7 TO 1', 22, RED, { maxW: 220 }); + } + // C & E circles — one per seat position, top to bottom + { + const r = Z('ce'); + strokeRect(ctx, r, LINE, 2); + const L = LANES.ce; + for (let i = 0; i < SLOT_ORDER.length; i++) { + const v = L.v0 + ((i + 0.5) / SLOT_ORDER.length) * (L.v1 - L.v0); + const p = P.project(L.u, v); + ctx.save(); + ctx.translate(p.x, p.y); + ctx.scale(p.s, p.s * VIEW.squash); + const rad = 17; + ctx.beginPath(); ctx.arc(0, 0, rad, Math.PI, 0); ctx.closePath(); + ctx.fillStyle = 'rgba(244,236,214,0.9)'; ctx.fill(); + ctx.beginPath(); ctx.arc(0, 0, rad, 0, Math.PI); ctx.closePath(); + ctx.fillStyle = RED; ctx.fill(); + ctx.beginPath(); ctx.arc(0, 0, rad, 0, Math.PI * 2); + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke(); + ctx.font = `bold 13px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#7a1010'; ctx.fillText('C', 0, -7); + ctx.fillStyle = '#fbf3df'; ctx.fillText('E', 0, 8); + ctx.restore(); + } + } + void felt; +} + +// ── Landing area ───────────────────────────────────────────────────────────── +function drawLanding(ctx) { + const c = { u: (LANDING.u0 + LANDING.u1) / 2, v: (LANDING.v0 + LANDING.v1) / 2 }; + feltTextUpBand(ctx, c.u, LANDING.v0, LANDING.v1, '♦ C R A P S ♦', 38, GOLD, { alpha: 0.22, spacing: 6 }); +} + +// ── Walls with diamond-pyramid rubber ──────────────────────────────────────── +function drawWalls(ctx) { + const base = tubOutline(0, 18, 60); + const n = base.length; + for (let i = 0; i < n; i++) { + const a = base[i], b = base[(i + 1) % n]; + // inner face normal (pointing into the tub) — skip faces turned away + const nu = -(b.v - a.v), nv = b.u - a.u; // left normal of a clockwise outline points inward + const facing = nv > 1e-6 || Math.abs(nu) > 1e-6 && nv >= -1e-6; + if (!facing) continue; + const A0 = lift(a.u, a.v, 0), B0 = lift(b.u, b.v, 0); + const A1 = lift(a.u, a.v, TUB.H), B1 = lift(b.u, b.v, TUB.H); + // padded rubber base + poly(ctx, [A0, B0, B1, A1]); + ctx.fillStyle = '#17110d'; + ctx.fill(); + ctx.lineWidth = 0.6; + ctx.strokeStyle = '#17110d'; + ctx.stroke(); + // pyramids: two rows of diamonds per segment + const rows = 2; + for (let r = 0; r < rows; r++) { + const t0 = r / rows, t1 = (r + 1) / rows; + const q = [ + mixPt(A0, A1, t0), mixPt(B0, B1, t0), mixPt(B0, B1, t1), mixPt(A0, A1, t1), + ]; + const apex = mixPt(mixPt(q[0], q[2], 0.5), mixPt(q[1], q[3], 0.5), 0.5); + apex.y -= 1.2; + const faces = [ + [q[3], q[2], apex, '#4a3a2e'], // top facet (lit) + [q[0], q[3], apex, '#2a2019'], + [q[2], q[1], apex, '#231a14'], + [q[1], q[0], apex, '#120c09'], // bottom facet (shadow) + ]; + for (const [p1, p2, p3, col] of faces) { + ctx.beginPath(); + ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.lineTo(p3.x, p3.y); ctx.closePath(); + ctx.fillStyle = col; + ctx.fill(); + } + } + } + // seam where wall meets felt + poly(ctx, toScreen(base)); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; + ctx.stroke(); +} + +function mixPt(a, b, t) { return { x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t) }; } + +// ── Rail top: padded leather lip, wooden chip groove, padded outer roll ────── +function bandPath(ctx, d0, d1) { + const outer = toScreen(tubOutline(d1, 14, 40), TUB.H); + const inner = toScreen(tubOutline(d0, 14, 40), TUB.H); + ctx.beginPath(); + outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + ctx.closePath(); + inner.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + ctx.closePath(); +} + +function ring(ctx, d, width, color) { + poly(ctx, toScreen(tubOutline(d, 14, 40), TUB.H)); + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); +} + +function padColor(f) { + const ridge = Math.max(0, Math.cos((f - 0.45) * Math.PI)); + return ridge > 0.7 ? mix(LEATHER_MID, LEATHER_HI, (ridge - 0.7) / 0.3) : mix(LEATHER_DARK, LEATHER_MID, Math.min(1, ridge * 1.4)); +} + +export const GROOVE = { d0: 0.3, d1: 0.72 }; // fraction of the rail width + +function drawRailTop(ctx) { + const RW = TUB.RW; + const g0 = RW * GROOVE.d0, g1 = RW * GROOVE.d1; + // inner padded lip + ctx.save(); + bandPath(ctx, 0, g0); + ctx.fillStyle = LEATHER_MID; + ctx.fill('evenodd'); + ctx.clip('evenodd'); + for (let i = 0; i <= 10; i++) ring(ctx, lerp(0, g0, i / 10), 3, padColor(i / 10)); + ctx.fillStyle = noisePattern(ctx, 128, 24); + ctx.fillRect(0, 0, W, H); + ctx.restore(); + // wooden groove + ctx.save(); + bandPath(ctx, g0, g1); + ctx.fillStyle = '#6b3b18'; + ctx.fill('evenodd'); + ctx.clip('evenodd'); + for (let i = 0; i <= 12; i++) { + const f = i / 12; + ring(ctx, lerp(g0, g1, f), 3, mix('#3a1e0a', '#8a5426', Math.sin(f * Math.PI) * 0.9)); + } + ctx.fillStyle = noisePattern(ctx, 128, 18); + ctx.fillRect(0, 0, W, H); + ctx.restore(); + ring(ctx, g0, 1.5, 'rgba(0,0,0,0.6)'); + ring(ctx, g1, 1.2, 'rgba(255,210,150,0.25)'); + // outer padded roll + ctx.save(); + bandPath(ctx, g1, RW); + ctx.fillStyle = LEATHER_MID; + ctx.fill('evenodd'); + ctx.clip('evenodd'); + for (let i = 0; i <= 14; i++) ring(ctx, lerp(g1, RW, i / 14), 3, padColor(i / 14)); + ctx.fillStyle = noisePattern(ctx, 128, 26); + ctx.fillRect(0, 0, W, H); + ctx.setLineDash([7, 5]); + ring(ctx, lerp(g1, RW, 0.5), 1.4, 'rgba(214,174,120,0.4)'); + ctx.setLineDash([]); + ctx.restore(); + ring(ctx, RW, 2, 'rgba(0,0,0,0.75)'); + ring(ctx, 0, 1.5, 'rgba(0,0,0,0.6)'); +} + +// House bank: chips racked in the far rail. +function drawBank(ctx) { + const d = TUB.RW * (GROOVE.d0 + GROOVE.d1) / 2; + const a = lift(BANK.u0, -d, TUB.H), b = lift(BANK.u1, -d, TUB.H); + const h = 22 * a.s; + rr(ctx, a.x - 8, a.y - h / 2 - 5, b.x - a.x + 16, h + 10, 6); + ctx.fillStyle = '#120c08'; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(214,174,120,0.6)'; + ctx.stroke(); + const cols = [1, 5, 5, 25, 25, 25, 50, 100, 100, 100, 50, 25, 25, 25, 5, 5, 1]; + const cw = (b.x - a.x) / cols.length; + cols.forEach((den, i) => { + const def = CHIP_DEFS[den]; + const x0 = a.x + i * cw + 1.5; + for (let k = 0; k < 7; k++) { + ctx.fillStyle = k % 2 ? def.base : mix(def.base, '#000000', 0.22); + ctx.fillRect(x0, a.y - h / 2 + (k * h) / 7, cw - 3, h / 7 + 0.5); + } + ctx.fillStyle = 'rgba(255,255,255,0.18)'; + ctx.fillRect(x0, a.y - h / 2, (cw - 3) * 0.35, h); + }); + // brass plate + const m = { x: (a.x + b.x) / 2, y: a.y - h / 2 - 22 }; + rr(ctx, m.x - 70, m.y - 11, 140, 22, 5); + const g = ctx.createLinearGradient(0, m.y - 11, 0, m.y + 11); + g.addColorStop(0, '#f0d78a'); g.addColorStop(1, '#9a7428'); + ctx.fillStyle = g; + ctx.fill(); + ctx.font = `bold 11px ${SANS}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#2a1a06'; + ctx.fillText('TABLE MIN $1 · MAX $500', m.x, m.y + 1); +} + +// The stickman's dice bowl at the far rail. +function drawBowl(ctx) { + const p = lift(BOWL.u, -TUB.RW * 0.5, TUB.H); + const rx = 40 * p.s, ry = 15 * p.s; + ctx.save(); + ctx.beginPath(); + ctx.ellipse(p.x, p.y + 4, rx + 3, ry + 5, 0, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.fill(); + const g = ctx.createLinearGradient(p.x - rx, 0, p.x + rx, 0); + g.addColorStop(0, '#3b2414'); g.addColorStop(0.5, '#8b5a30'); g.addColorStop(1, '#2a180c'); + ctx.beginPath(); + ctx.ellipse(p.x, p.y, rx, ry, 0, 0, Math.PI * 2); + ctx.fillStyle = g; + ctx.fill(); + ctx.beginPath(); + ctx.ellipse(p.x, p.y - 1, rx * 0.78, ry * 0.7, 0, 0, Math.PI * 2); + ctx.fillStyle = '#1a0f08'; + ctx.fill(); + // a few spare dice in the bowl + const dice = [[-14, -2], [2, 1], [15, -3]]; + for (const [dx, dy] of dice) { + const s = 10 * p.s; + rr(ctx, p.x + dx * p.s - s / 2, p.y + dy * p.s - s / 2, s, s * 0.8, 2); + ctx.fillStyle = '#c41f2a'; + ctx.fill(); + ctx.fillStyle = '#fbf3df'; + ctx.beginPath(); ctx.arc(p.x + dx * p.s, p.y + dy * p.s - 0.5, 1.3, 0, Math.PI * 2); ctx.fill(); + } + ctx.restore(); +} + +// ── ON / OFF puck: a thick tilted disc ─────────────────────────────────────── +export const PUCK = { w: 128, h: 76, rx: 56, ry: 24, t: 14 }; + +function bakePuck(scene, key, on) { + const { w, h, rx, ry, t } = PUCK; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + const cx = w / 2, yT = ry + 3, yB = yT + t; + // edge + ctx.beginPath(); + ctx.moveTo(cx - rx, yT); + ctx.lineTo(cx - rx, yB); + ctx.ellipse(cx, yB, rx, ry, 0, Math.PI, 0, true); + ctx.lineTo(cx + rx, yT); + ctx.closePath(); + const eg = ctx.createLinearGradient(cx - rx, 0, cx + rx, 0); + const edge = on ? ['#9a9a9a', '#f4f4f4', '#7a7a7a'] : ['#050505', '#3a3a3a', '#030303']; + eg.addColorStop(0, edge[0]); eg.addColorStop(0.35, edge[1]); eg.addColorStop(1, edge[2]); + ctx.fillStyle = eg; + ctx.fill(); + // top + ctx.beginPath(); + ctx.ellipse(cx, yT, rx, ry, 0, 0, Math.PI * 2); + const tg = ctx.createRadialGradient(cx - rx * 0.3, yT - ry * 0.4, 2, cx, yT, rx); + if (on) { tg.addColorStop(0, '#ffffff'); tg.addColorStop(1, '#d8d8d2'); } else { tg.addColorStop(0, '#2e2e2e'); tg.addColorStop(1, '#0a0a0a'); } + ctx.fillStyle = tg; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = on ? '#1d6b2c' : '#7a7a7a'; + ctx.beginPath(); + ctx.ellipse(cx, yT, rx * 0.86, ry * 0.86, 0, 0, Math.PI * 2); + ctx.stroke(); + ctx.save(); + ctx.translate(cx, yT + 1); + ctx.scale(1, ry / rx * 1.25); + ctx.font = `bold 34px ${SANS}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = on ? '#1d6b2c' : '#f4ecd6'; + ctx.fillText(on ? 'ON' : 'OFF', 0, 0); + ctx.restore(); + scene.textures.addCanvas(key, c); +} diff --git a/src/games/craps/CrapsDice.js b/src/games/craps/CrapsDice.js new file mode 100644 index 0000000..b3ff556 --- /dev/null +++ b/src/games/craps/CrapsDice.js @@ -0,0 +1,334 @@ +// Craps dice — true 3D cubes drawn live (Graphics) and a physics-lite throw. +// +// The roll's result is decided first by the game RNG. simulateThrow() then flies +// a canonical die (gravity, felt bounces, the pyramid wall, sliding friction, +// tumble), snaps it flat, and finally relabels the die (a fixed cube rotation +// applied in the die's own frame) so the face that ends up on top carries the +// rolled number. Outcomes stay fair; the animation just agrees with them. +// +// Phaser-free apart from the Graphics objects handed in by the scene, so the +// simulation can be verified under Node. + +import { P, lift, WALL_U, LANDING, NEAR_VISIBLE_V, VIEW } from './CrapsTable.js'; + +// ── Tuning ─────────────────────────────────────────────────────────────────── +export const DIE = { size: 30 }; // edge length, px at s = 1 +const UX = VIEW.halfW; // px per u-unit at s = 1 +const VY = VIEW.halfW * (4 / 3); // px per v-unit (the felt is 4 ft deep, half-length 3 ft) +const SIN_E = 0.7, COS_E = 0.71; // camera elevation used to draw the cubes +const G = 2600; // gravity, px/s² +const DT = 1 / 240; +const LIGHT = norm([-0.35, 0.45, 0.82]); + +// Local face normals and the pips on them (opposite faces add to 7). +const FACES = [ + { n: [0, 0, 1], label: 1, e1: [1, 0, 0], e2: [0, 1, 0] }, + { n: [0, 0, -1], label: 6, e1: [1, 0, 0], e2: [0, -1, 0] }, + { n: [0, 1, 0], label: 2, e1: [1, 0, 0], e2: [0, 0, 1] }, + { n: [0, -1, 0], label: 5, e1: [-1, 0, 0], e2: [0, 0, 1] }, + { n: [1, 0, 0], label: 3, e1: [0, 1, 0], e2: [0, 0, 1] }, + { n: [-1, 0, 0], label: 4, e1: [0, -1, 0], e2: [0, 0, 1] }, +]; +const PIPS = { + 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]], +}; + +// ── Vector / quaternion helpers ────────────────────────────────────────────── +function norm(v) { const l = Math.hypot(...v) || 1; return v.map(x => x / l); } +const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + +export function qmul(a, b) { + return [ + a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2], + a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1], + a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0], + ]; +} +function qnorm(q) { const l = Math.hypot(...q) || 1; return q.map(x => x / l); } +export function qaxis(axis, ang) { + const a = norm(axis), s = Math.sin(ang / 2); + return [Math.cos(ang / 2), a[0] * s, a[1] * s, a[2] * s]; +} +export function qrot(q, v) { + const [w, x, y, z] = q; + const ix = w * v[0] + y * v[2] - z * v[1]; + const iy = w * v[1] + z * v[0] - x * v[2]; + const iz = w * v[2] + x * v[1] - y * v[0]; + const iw = -x * v[0] - y * v[1] - z * v[2]; + return [ + ix * w + iw * -x + iy * -z - iz * -y, + iy * w + iw * -y + iz * -x - ix * -z, + iz * w + iw * -z + ix * -y - iy * -x, + ]; +} +function qslerp(a, b, t) { + let d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + if (d < 0) { b = b.map(x => -x); d = -d; } + if (d > 0.9995) return qnorm(a.map((x, i) => x + (b[i] - x) * t)); + const th = Math.acos(d), s = Math.sin(th); + const wa = Math.sin((1 - t) * th) / s, wb = Math.sin(t * th) / s; + return a.map((x, i) => x * wa + b[i] * wb); +} +function randomQ(rng) { + const u1 = rng(), u2 = rng(), u3 = rng(); + return [ + Math.sqrt(1 - u1) * Math.sin(2 * Math.PI * u2), Math.sqrt(1 - u1) * Math.cos(2 * Math.PI * u2), + Math.sqrt(u1) * Math.sin(2 * Math.PI * u3), Math.sqrt(u1) * Math.cos(2 * Math.PI * u3), + ]; +} + +// Rotate q so the local axis nearest world-up points exactly up (keeps the yaw). +function snapFlat(q) { + let best = null; + for (const f of FACES) { + const w = qrot(q, f.n); + if (!best || w[2] > best.w[2]) best = { w, f }; + } + const up = [0, 0, 1]; + const ax = cross(best.w, up); + const l = Math.hypot(...ax); + if (l < 1e-9) return q; + return qnorm(qmul(qaxis(ax, Math.acos(Math.min(1, dot(best.w, up)))), q)); +} + +// The label on top for an orientation. +export function topFace(q) { + let best = null; + for (const f of FACES) { + const z = qrot(q, f.n)[2]; + if (!best || z > best.z) best = { z, label: f.label }; + } + return best.label; +} + +// Cube rotation (die frame) that moves the face labelled `target` onto local axis `a`. +function relabel(target, a) { + const t = FACES.find(f => f.label === target).n; + const d = dot(t, a); + if (d > 0.999) return [1, 0, 0, 0]; + if (d < -0.999) { + const perp = Math.abs(t[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + return qaxis(cross(t, perp), Math.PI); + } + return qaxis(cross(t, a), Math.PI / 2); +} + +// ── Simulation ─────────────────────────────────────────────────────────────── +// origin {u, v, h}; returns { frames: [{u, v, h, q}], u, v } at 120 fps. +function flyOne(origin, rng, aimV) { + const half = DIE.size / 2; + const wallX = WALL_U * UX - half; + const farY = 0.03 * VY + half, nearY = (NEAR_VISIBLE_V - 0.03) * VY - half; // the real near wall + let X = origin.u * UX, Y = origin.v * VY, Z = origin.h; + const TX = wallX, TY = aimV * VY; + const dist = Math.hypot(TX - X, TY - Y); + const tf = Math.max(0.35, (dist / 1500) * (0.85 + rng() * 0.3)); + let vx = (TX - X) / tf, vy = (TY - Y) / tf; + const zArrive = 25 + rng() * 40; + let vz = (zArrive - Z + 0.5 * G * tf * tf) / tf; + let q = randomQ(rng); + let w = norm([rng() - 0.5, rng() - 0.5, rng() - 0.5]).map(x => x * (16 + rng() * 12)); + const frames = []; + let t = 0, grounded = false, hitWall = false, step = 0; + const push = () => frames.push({ u: X / UX, v: Y / VY, h: Z, q }); + push(); + while (t < 3.4) { + // integrate + vz -= grounded ? 0 : G * DT; + X += vx * DT; Y += vy * DT; Z += vz * DT; + const wl = Math.hypot(...w); + if (wl > 1e-6) q = qnorm(qmul(qaxis(w, wl * DT), q)); + // felt + if (Z <= 0 && !grounded) { + Z = 0; + if (hitWall && Math.abs(vz) < 140) { vz = 0; grounded = true; } + else if (!hitWall) { + // a short throw skips along the felt — it still has to reach the wall + vz = Math.max(260, -vz * 0.5); + vx *= 0.92; vy *= 0.92; + w = w.map(x => x * 0.7 + (rng() - 0.5) * 12); + } else { + vz = -vz * 0.36; + vx *= 0.7; vy *= 0.7; + w = w.map(x => x * 0.55 + (rng() - 0.5) * 14); + } + } + if (grounded) { + Z = 0; + const sp = Math.hypot(vx, vy); + const dec = Math.min(sp, 1700 * DT); + if (sp > 0) { vx -= (vx / sp) * dec; vy -= (vy / sp) * dec; } + w = w.map(x => x * 0.965); + } + // walls + if (X >= wallX) { + X = wallX; vx = -Math.abs(vx) * 0.28; vy += (rng() - 0.5) * 420; vz += 120 + rng() * 160; + grounded = false; hitWall = true; + w = w.map(x => x * 0.6 + (rng() - 0.5) * 22); + } + if (X <= (-0.97 * UX + half)) { X = -0.97 * UX + half; vx = Math.abs(vx) * 0.5; } + if (Y <= farY) { Y = farY; vy = Math.abs(vy) * 0.5; } + if (Y >= nearY) { Y = nearY; vy = -Math.abs(vy) * 0.5; } + t += DT; + if (++step % 2 === 0) push(); + if (grounded && hitWall && Math.hypot(vx, vy) < 18 && Math.hypot(...w) < 4) break; + } + // settle flat over ~0.16 s with a little slide + const q0 = q, qf = snapFlat(q); + const n = 20; + for (let i = 1; i <= n; i++) { + const k = i / n, e = 1 - (1 - k) * (1 - k); + X += vx * DT * 2 * (1 - k); Y += vy * DT * 2 * (1 - k); + frames.push({ u: X / UX, v: Y / VY, h: Math.sin(k * Math.PI) * 2.5, q: qslerp(q0, qf, e) }); + } + return { frames, u: X / UX, v: Y / VY, hitWall, q: qf }; +} + +// Plan a throw of both dice from `origin` landing on `faces` [a, b]. +export function simulateThrow(origin, faces, rng = Math.random) { + const out = []; + let tries = 0; + for (let i = 0; i < 2; i++) { + let best = null; + for (let k = 0; k < 40; k++) { + tries++; + const aim = 0.16 + rng() * 0.36; // the upper part of the wall, so dice settle above the results card + const o = { u: origin.u, v: origin.v + (i ? 0.02 : -0.02), h: origin.h }; + const fly = flyOne(o, rng, aim); + const inLanding = fly.u >= LANDING.u0 - 0.04 && fly.u <= LANDING.u1 && fly.v >= LANDING.v0 && fly.v <= LANDING.v1; + const sep = i ? Math.hypot((fly.u - out[0].u) * UX, (fly.v - out[0].v) * VY) : Infinity; + const okSep = sep >= DIE.size * 1.5; + const score = (inLanding ? 2 : 0) + (okSep ? 1 : 0) + (fly.hitWall ? 2 : 0); + if (!best || score > best.score) best = { ...fly, score }; + if (score === 5) break; + } + // Relabel so the face that lands on top shows the rolled number. + const up = qrot([best.q[0], -best.q[1], -best.q[2], -best.q[3]], [0, 0, 1]).map(Math.round); + best.Q = relabel(faces[i], up); + best.frames = best.frames.map(f => ({ ...f, q: qmul(f.q, best.Q) })); + best.top = topFace(best.frames[best.frames.length - 1].q); + out.push(best); + } + // pad the shorter path so both finish together + const len = Math.max(out[0].frames.length, out[1].frames.length); + for (const d of out) while (d.frames.length < len) d.frames.push(d.frames[d.frames.length - 1]); + return { dice: out, duration: (len - 1) / 120, tries }; +} + +// A resting orientation showing `face` on top with a given yaw. +export function restingQ(face, yaw = 0) { + const base = relabel(face, [0, 0, 1]); + return qmul(qaxis([0, 0, 1], yaw), base); +} + +// ── Rendering ──────────────────────────────────────────────────────────────── +const BODY = [196, 28, 40]; + +function shadeHex(rgb, k) { + const c = rgb.map(x => Math.max(0, Math.min(255, Math.round(x * k)))); + return (c[0] << 16) | (c[1] << 8) | c[2]; +} + +export class Die3D { + constructor(scene, depth) { + this.scene = scene; + this.shadow = scene.add.graphics().setDepth(depth - 0.5); + this.g = scene.add.graphics().setDepth(depth); + this.state = { u: 0, v: 0, h: 0, q: [1, 0, 0, 0] }; + this.scale = 1; + this.glow = 0; + this.visible = true; + } + + setVisible(v) { this.visible = v; this.g.setVisible(v); this.shadow.setVisible(v); return this; } + + set(u, v, h, q) { Object.assign(this.state, { u, v, h, q }); this.draw(); return this; } + + screenCenter() { + const { u, v, h } = this.state; + const p = P.project(u, v); + const half = DIE.size / 2; + return { x: p.x, y: p.y - (h + half) * COS_E * p.s * this.scale, s: p.s }; + } + + draw() { + const g = this.g, sh = this.shadow; + g.clear(); sh.clear(); + if (!this.visible) return; + const { u, v, h, q } = this.state; + const p = lift(u, v, 0); + const s = p.s * this.scale; + const half = DIE.size / 2; + const hc = h + half; + const proj = (w) => ({ x: p.x + s * w[0], y: p.y + s * (w[1] * SIN_E - (hc + w[2]) * COS_E) }); + + // shadow on the felt + const fade = Math.max(0.12, 0.42 - h / 500); + sh.fillStyle(0x000000, fade); + sh.fillEllipse(p.x + 4 * s + h * 0.04, p.y + 3 * s, DIE.size * 1.25 * s, DIE.size * 0.75 * s); + + if (this.glow > 0) { + g.lineStyle(3, 0xf5d020, this.glow); + g.strokeEllipse(p.x, p.y + 2 * s, DIE.size * 1.7 * s, DIE.size * 1.0 * s); + } + + const cam = [0, SIN_E, COS_E]; + for (const f of FACES) { + const n = qrot(q, f.n); + const facing = dot(n, cam); + if (facing <= 0.02) continue; + const e1 = qrot(q, f.e1), e2 = qrot(q, f.e2); + const c = n.map(x => x * half); + const corner = (a, b) => proj([ + c[0] + (e1[0] * a + e2[0] * b) * half, + c[1] + (e1[1] * a + e2[1] * b) * half, + c[2] + (e1[2] * a + e2[2] * b) * half, + ]); + // slightly chamfered square + const k = 0.82; + const pts = [ + corner(-k, -1), corner(k, -1), corner(1, -k), corner(1, k), + corner(k, 1), corner(-k, 1), corner(-1, k), corner(-1, -k), + ]; + const lit = 0.5 + 0.55 * Math.max(0, dot(n, LIGHT)); + g.fillStyle(shadeHex(BODY, lit), 0.97); + g.fillPoints(pts, true); + g.lineStyle(1, shadeHex(BODY, lit * 0.55), 0.9); + g.strokePoints(pts, true); + // gloss on the top-lit face + if (n[2] > 0.6) { + g.fillStyle(0xffffff, 0.08 + 0.1 * n[2]); + g.fillPoints([corner(-0.75, 0.2), corner(-0.2, 0.75), corner(-0.75, 0.75)], true); + } + // pips + const pipA = Math.min(1, facing * 2.4); + g.fillStyle(0xfdf6e6, 0.95 * pipA); + for (const [a, b] of PIPS[f.label]) { + const ring = []; + for (let i = 0; i < 8; i++) { + const t = (i / 8) * Math.PI * 2; + ring.push(corner(a * 0.52 + Math.cos(t) * 0.17, b * 0.52 + Math.sin(t) * 0.17)); + } + g.fillPoints(ring, true); + } + } + } + + destroy() { this.g.destroy(); this.shadow.destroy(); } +} + +// Play a planned throw on two Die3D objects. `progress` 0…1 drives the frames. +export function poseFromPlan(plan, i, progress) { + const fr = plan.dice[i].frames; + const f = Math.min(fr.length - 1, Math.max(0, progress * (fr.length - 1))); + const a = fr[Math.floor(f)], b = fr[Math.ceil(f)]; + const t = f - Math.floor(f); + return { + u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t, h: a.h + (b.h - a.h) * t, + q: t < 0.5 ? a.q : b.q, + }; +} diff --git a/src/games/craps/CrapsGame.js b/src/games/craps/CrapsGame.js index cadc7a9..ba14950 100644 --- a/src/games/craps/CrapsGame.js +++ b/src/games/craps/CrapsGame.js @@ -2,1049 +2,1872 @@ import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { Modal } from '../../ui/Modal.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { Tooltip } from '../../ui/Tooltip.js'; +import { createOpponentPortrait } from '../../ui/Portrait.js'; import { api } from '../../services/api.js'; import { auth } from '../../services/auth.js'; import { playSound, playChipBet, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { makeChipStack, throwChip, SLICE_RY, SLICE_T, SLICE_H, FACE } from '../../ui/CasinoChips.js'; +import { CasinoDock } from '../../ui/casino/CasinoDock.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; import { - BET, POINT_NUMBERS, CHIP_AMOUNTS, - createInitialState, placeBet, addOdds, refundBets, rollDice, resolveRoll, - clearLastDeltas, legalBetTypes, oddsEligibleBets, totalAtRisk, getNetResult, + BET, POINT_NUMBERS, HARD_NUMBERS, CHIP_AMOUNTS, NUMBERED, + createInitialState, placeBet, addOdds, oddsRoom, reduceBet, setWorking, refundBets, + rollDice, resolveRoll, clearLastDeltas, legalBetTypes, isLegalBet, oddsEligibleBets, totalAtRisk, + getNetResult, isContract, canToggleWorking, isWorking, maxOddsFor, oddsNumber, + placeWin, trueOddsWin, layOddsWin, vig, paysLabel, houseEdge, stickCall, + cloneState, explainPayout, explainMove, betLabel, } from './CrapsLogic.js'; import { chooseBets, chooseOdds } from './CrapsAI.js'; +import { + P, TUB, DOCK, ZONES, SLOT_ORDER, STACK, BOARD, CALL, BOWL, RESULT, zoneKeyFor, + seatNames, railPose, seatPortrait, throwOrigin, laneForBet, laneSpot, oddsOffset, + hitZone, rectOutline, bankPose, puckOnUV, puckOffUV, offerSpot, lift, +} from './CrapsTable.js'; +import { prepareCrapsArt, PUCK, FELTS } from './CrapsArt.js'; +import { Die3D, simulateThrow, poseFromPlan, restingQ, DIE } from './CrapsDice.js'; -// ─── Layout ────────────────────────────────────────────────────────────────-- -const CX = GAME_WIDTH / 2; // 960 -const DIE_SIZE = 76; -const TABLE = { x: 220, y: 110, w: 1480, h: 610 }; -const LAND = { x: 1555, y: 218 }; // upper-right open area, right of come and number boxes - -const NUM_TO_BOX = { 4: 0, 5: 1, 6: 2, 8: 3, 9: 4, 10: 5 }; -const BOX_NUMS = [4, 5, 6, 8, 9, 10]; - -// Seat slots (x) for up to 7 players — human centred, opponents fanned out. -const SEAT_X = [960, 700, 1220, 440, 1480, 200, 1740]; -const SEAT_Y = 838; -const PORTRAIT_R = 46; - -const CHIP_COLORS = { 5: 0xe05c5c, 25: 0x5cb85c, 50: 0x4a90d9, 100: 0x2c2c2c }; - -// Per-player identity colors: seat 0 (human) is gold, opponents get distinct hues. -const SEAT_COLORS = [0xd4a017, 0x4aa3df, 0xe06c75, 0x5cb85c, 0xb07cd6, 0xe09a3c, 0x3cc6c0]; -const hexStr = (n) => `#${n.toString(16).padStart(6, '0')}`; +// ─── Layout / tuning ────────────────────────────────────────────────────────── +// Geometry lives in CrapsTable.js, art in CrapsArt.js, dice in CrapsDice.js and +// rules in CrapsLogic.js. This file is flow, input and animation. +const CX = GAME_WIDTH / 2; +const CY = GAME_HEIGHT / 2; +const DOCK_Y = DOCK.y + DOCK.h / 2; +const TABLE_MAX = 500; +const AI_WAIT_MS = 12000; // an opponent shooter rolls after this long… +const AI_NUDGE_MS = 6000; // …or at least this long after your last bet +const SPEEDS = { normal: 1, fast: 1.8, instant: 4 }; +const SPEED_LABEL = { normal: 'Speed: Normal', fast: 'Speed: Fast', instant: 'Speed: Instant' }; +const FELT_ORDER = Object.keys(FELTS); const D = { - bg: -1, felt: 0, zone: 1, zoneLabel: 2, betChip: 6, puck: 8, - portrait: 20, shooterRing: 21, dice: 30, fx: 40, ui: 50, prompt: 55, modal: 60, + bg: -2, playfield: -1, table: 0, input: 1, feltHi: 2, puck: 8, stacks: 10, lammer: 13, offer: 16, + hints: 12.5, result: 12.7, dice: 20, flying: 24, badges: 30, dock: 40, ui: 42, dockUi: 44, prompt: 48, modal: 60, }; -// 3×3 pip layout per die face. -const PIP_POS = { - 1: [[0, 0]], - 2: [[-1, -1], [1, 1]], - 3: [[-1, -1], [0, 0], [1, 1]], - 4: [[-1, -1], [1, -1], [-1, 1], [1, 1]], - 5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]], - 6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]], +// Seat identity colours (marker rings under opponents' chips, portrait rings). +const SEAT_COLORS = [0xd4a017, 0x4aa3df, 0xe06c75, 0x5cb85c, 0xb07cd6, 0xe09a3c, 0x3cc6c0]; +const hexStr = (n) => `#${n.toString(16).padStart(6, '0')}`; +const money = (n) => `$${Math.round(n).toLocaleString()}`; + +const HELP = { + pass: 'Bet with the shooter. Come-out: 7 or 11 wins, 2·3·12 loses. Any other number becomes the point — win if it repeats before a 7.', + dontpass: "Bet against the shooter. Come-out: 2 or 3 wins, 7 or 11 loses, 12 is barred (no action — the bet stays). Then win if a 7 comes before the point.", + come: 'Like a Pass Line bet made after the point is set. 7/11 wins, 2·3·12 loses; any other number becomes this bet\'s own point.', + dontcome: "Like Don't Pass, made after the point is set. 2/3 wins, 7/11 loses, 12 is barred (the bet stays); then win if a 7 beats its number.", + field: 'One roll. Wins on 2·3·4·9·10·11·12 (2 pays double, 12 triple). Loses on 5·6·7·8.', + odds: 'Free odds behind your line bet — paid at true odds, no house edge. Up to 3× on 4/10, 4× on 5/9, 5× on 6/8 (lay up to 6× on the Don\'t).', + place: 'Wins whenever the number rolls before a 7. Stays up after a win. Off on the come-out unless you turn it on.', + buy: 'Like a Place bet but paid at true odds, less a 5% commission on wins. Best in multiples of $20.', + lay: 'Bets a 7 rolls before the number. Paid at true odds less 5% of the win. Always working.', + big: 'Wins if the number rolls before a 7. Pays even money — a Place bet on the same number pays more.', + hard: 'Wins if the number rolls as a pair (the hard way) before a 7 or the easy way. Off on the come-out.', + any7: 'One roll: wins on any 7.', + anycraps: 'One roll: wins on 2, 3 or 12.', + yo: 'One roll: wins on 11.', + aces: 'One roll: wins on 2 (snake eyes).', + acedeuce: 'One roll: wins on 3.', + boxcars: 'One roll: wins on 12.', + ce: 'One roll, split between Craps and Eleven: 2·3·12 pays 3 to 1, 11 pays 7 to 1.', + horn: 'One roll, split four ways on 2·3·11·12: 2 or 12 pays 27 to 4, 3 or 11 pays 3 to 1.', }; -// ─── Bet-zone help text ────────────────────────────────────────────────────-- -const ZONE_INFO = { - pass: { title: 'PASS LINE', desc: 'Bet with the shooter. Win on 7 or 11 on the come-out roll. Lose on 2, 3, or 12 (craps). Once a point is set, win if that point rolls again before a 7.' }, - dontpass: { title: "DON'T PASS BAR", desc: "Bet against the shooter. Win on 2 or 3; push on 12. Lose on 7 or 11. After a point is set, win when 7 rolls before the point. One of the lowest house-edge bets on the table." }, - come: { title: 'COME', desc: 'Placed after a point is set — works exactly like the Pass Line from that moment. Win on 7 or 11; lose on 2, 3, or 12. Any other number becomes your personal come point; win when it repeats before a 7.' }, - dontcome: { title: "DON'T COME", desc: "Placed after a point is set — mirrors the Don't Pass. Lose on 7 or 11; win on 2 or 3 (12 pushes). Once your come point is established, you win if a 7 rolls first." }, - field: { title: 'FIELD', desc: 'A one-roll bet resolved on every throw. Win on 2, 3, 4, 9, 10, 11, or 12. Lose on 5, 6, 7, or 8. A 2 pays double; 12 pays triple. High action — wins or loses immediately.' }, - box4: { title: 'PLACE 4', desc: 'Win if a 4 rolls before a 7. Pays 9 to 5. Available any time after a point is set. You can take this bet down between rolls whenever you like.' }, - box5: { title: 'PLACE 5', desc: 'Win if a 5 rolls before a 7. Pays 7 to 5. A flexible standing bet — leave it up as long as you choose.' }, - box6: { title: 'PLACE 6', desc: 'Win if a 6 rolls before a 7. Pays 7 to 6. The 6 is the second most common number after 7, giving this bet a strong win rate.' }, - box8: { title: 'PLACE 8', desc: 'Win if an 8 rolls before a 7. Pays 7 to 6. Rolls just as often as the 6 — considered one of the best place bets on the table.' }, - box9: { title: 'PLACE 9', desc: 'Win if a 9 rolls before a 7. Pays 7 to 5. Solid mid-table bet with moderate odds.' }, - box10: { title: 'PLACE 10', desc: 'Win if a 10 rolls before a 7. Pays 9 to 5. Identical odds to the 4 — both roll four ways out of 36.' }, +const HINT_TAGS = { + pass: 'BEST BET · 1.41% EDGE', dontpass: 'BEST BET · 1.36% EDGE', odds: 'FREE ODDS · 0% EDGE', + come: 'LIKE PASS · 1.41% EDGE', place6: 'PLACE 6 · 1.52%', place8: 'PLACE 8 · 1.52%', }; +const TYPE_NAME = { + pass: 'Pass Line', dontpass: "Don't Pass", come: 'Come', dontcome: "Don't Come", field: 'Field', + place: 'Place', buy: 'Buy', lay: 'Lay', big: 'Big', hard: 'Hard', any7: 'Any Seven', anycraps: 'Any Craps', + yo: 'Yo-Eleven', aces: 'Aces', acedeuce: 'Ace-Deuce', boxcars: 'Boxcars', ce: 'C & E', horn: 'Horn', +}; + +function betName(b) { + const base = TYPE_NAME[b.type] ?? b.type; + if (b.number != null) return `${base} ${b.number}`; + if (b.comePoint != null) return `${base} on ${b.comePoint}`; + return base; +} + +function store(key, fallback) { + try { return localStorage.getItem(key) ?? fallback; } catch { return fallback; } +} +function save(key, value) { + try { localStorage.setItem(key, value); } catch { /* private mode */ } +} + export default class CrapsGame extends Phaser.Scene { constructor() { super('CrapsGame'); } init(data) { this.gameDef = data.game; - this.opponents = data.opponents ?? []; + this.opponents = (data.opponents ?? []).slice(0, 6); this.playfield = data.playfield ?? null; - } - - async create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); this.gs = null; - this.animating = false; - this.selectedChip = 25; - this.zones = {}; // key → { rect:{x,y,w,h}, center:{x,y}, type, number, label } - this.zoneGfx = null; - this.humanChipObjs = []; - this.aiWagerObjs = {}; // seat → { container } - this.aiBetObjs = []; // chips on the felt for AI bets - this.seatJitter = Array.from({ length: 7 }, () => ({ dx: (Math.random() - 0.5) * 18, dy: (Math.random() - 0.5) * 8 })); + this.phase = 'load'; // load | bet | rolling | settle | over + this.selectedChip = 5; + this.stackObjs = new Map(); // `${pi}:${betId}:${part}` → container + this.railObjs = {}; // pi → [containers] this.portraits = []; - this.chipBtns = []; - this.startingChips = 2000; - this.hoverTimer = null; - this.tooltipW = 0; - this.tooltipH = 0; - - this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); - this.buildPlayfield(); - this.buildTitle(); - this.defineZones(); - this.buildTable(); - this.buildPuck(); - this.buildDice(); - this.buildChipTray(); - this.buildButtons(); - - new Button(this, 110, GAME_HEIGHT - 48, 'Leave', () => this.leave(), { - variant: 'ghost', width: 150, fontSize: 20, - }).setDepth(D.ui); - - this.buildTooltip(); - this.input.on('pointermove', (ptr) => this.onPointerMove(ptr)); - - await this.loadChips(); - this.gs = createInitialState(this.opponents, this.startingChips, auth.user?.username ?? 'You'); - this.buildPortraits(); - this.updateShooterIndicator(); - this.beginComeOut(); + this.plates = {}; + this.undo = []; // human actions this betting window + this.lastSnapshot = []; // human re-placeable bets at the last roll + this.pressBtns = []; + this.lammers = []; // { x, y, r, betId } + this.history = []; + this.hover = null; + this.decor = []; + this.offerDice = []; + this.chosen = []; + this.needsPick = true; + this.aiTimer = null; + this.aiDeadline = 0; + this.speed = store('craps-speed', 'normal'); + this.hints = store('craps-hints', 'off') === 'on'; + this.hintTags = new Map(); // zone key → floating label + this.felt = store('craps-felt', 'green'); + if (!FELTS[this.felt]) this.felt = 'green'; } - // ── Background ───────────────────────────────────────────────────────────── + // ── Lifecycle ─────────────────────────────────────────────────────────────── + async create() { + new MusicPlayer(this, this.cache.json.get('music').tracks); + this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); + this.buildPlayfield(); + this.events.once('shutdown', () => { + this.input.setDefaultCursor('default'); + for (const p of this.portraits) p?.destroy?.(); + }); + + const key = await prepareCrapsArt(this, this.felt); + if (!this.sys.isActive()) return; + this.tableImg = this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.feltHi = this.add.graphics().setDepth(D.feltHi); + this.hintG = this.add.graphics().setDepth(D.hints); + this.resultG = this.add.graphics().setDepth(D.result); + this.resultTags = []; + this.resultFx = null; + + this.applySpeed(); + this.buildPuck(); + this.buildDice(); + this.buildDock(); + this.buildTopButtons(); + this.buildBoard(); + this.buildResultCard(); + this.tooltip = new Tooltip(this, { depth: 70 }); + this.buildFeltInput(); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + + const chips = await this.loadChips(); + if (!this.sys.isActive()) return; + this.gs = createInitialState(this.opponents, chips, auth.user?.username ?? 'You'); + this.startingChips = chips; + this.seatOf = seatNames(this.opponents.length); + this.buildSeats(); + this.renderAllRails(); + this.updateShooter(); + this.placeIdleDice(); + this.say('Welcome to the table — new shooter coming out!'); + this.startBetting(); + } + + update() { + this.drawHints(); + this.drawResultFx(); + if (this.phase === 'bet' && this.aiTimer && this.gs) { + const left = Math.max(0, Math.ceil((this.aiDeadline - this.game.loop.time) / 1000)); + const lbl = `Ready (${left})`; + if (this.rollBtn.text.text !== lbl) this.rollBtn.setLabel(lbl); + } + } + + wait(ms) { return new Promise((res) => this.time.delayedCall(ms, res)); } + + tweenP(cfg) { + return new Promise((res) => this.tweens.add({ ...cfg, onComplete: (...a) => { cfg.onComplete?.(...a); res(); } })); + } + + alive() { return this.sys.isActive(); } + + applySpeed() { + const k = SPEEDS[this.speed] ?? 1; + this.tweens.timeScale = k; + this.time.timeScale = k; + } + + // ── Scenery ──────────────────────────────────────────────────────────────── buildPlayfield() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg + 1); + this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.playfield); } } - buildTitle() { - this.add.text(CX, 52, 'Craps', { - fontFamily: 'Caesar', fontSize: '50px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - this.statusText = this.add.text(CX, 96, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.ui); - } - - // ── Bet zones ────────────────────────────────────────────────────────────── - defineZones() { - const add = (key, type, number, label, x, y, w, h, sub) => { - this.zones[key] = { type, number, label, sub, rect: { x, y, w, h }, center: { x: x + w / 2, y: y + h / 2 } }; - }; - - // Top: point/place number boxes - const boxW = 150, boxH = 90, gap = 14; - const totalW = BOX_NUMS.length * boxW + (BOX_NUMS.length - 1) * gap; - const startX = CX - totalW / 2; - const boxY = 150; - BOX_NUMS.forEach((n, i) => { - const lbl = n === 6 ? 'SIX' : n === 9 ? 'NINE' : String(n); - const payout = (n === 4 || n === 10) ? 'PAYS 9 TO 5' - : (n === 5 || n === 9) ? 'PAYS 7 TO 5' : 'PAYS 7 TO 6'; - add(`box${n}`, BET.PLACE, n, lbl, startX + i * (boxW + gap), boxY, boxW, boxH); - this.zones[`box${n}`].payout = payout; - }); - this._boxY = boxY; this._boxH = boxH; - - // Don't Come (left of the boxes) - add('dontcome', BET.DONT_COME, null, "DON'T\nCOME", TABLE.x + 24, boxY, startX - TABLE.x - 44, boxH * 2 + 14); - this.zones.dontcome.barText = 'BAR 12'; - - // Come - add('come', BET.COME, null, 'COME', startX, 268, totalW, 88); - - // Field - add('field', BET.FIELD, null, 'FIELD', TABLE.x + 60, 372, TABLE.w - 120, 86, - '2 pays double · 12 pays triple'); - this.zones.field.fieldNums = [2, 3, 4, 9, 10, 11, 12]; - - // Don't Pass bar - add('dontpass', BET.DONT_PASS, null, "DON'T PASS", TABLE.x + 140, 476, TABLE.w - 280, 60); - this.zones.dontpass.barText = 'BAR 12'; - - // Pass line - add('pass', BET.PASS, null, 'PASS LINE', TABLE.x + 100, 552, TABLE.w - 200, 76); - } - - buildTable() { - const g = this.add.graphics().setDepth(D.felt); - g.fillStyle(0x14532d, 0.92); - g.fillRoundedRect(TABLE.x, TABLE.y, TABLE.w, TABLE.h, 26); - g.lineStyle(8, COLORS.accent, 0.9); - g.strokeRoundedRect(TABLE.x, TABLE.y, TABLE.w, TABLE.h, 26); - g.lineStyle(2, 0x3c8a52, 0.6); - g.strokeRoundedRect(TABLE.x + 12, TABLE.y + 12, TABLE.w - 24, TABLE.h - 24, 20); - - this.zoneGfx = this.add.graphics().setDepth(D.zone); - this.drawZones(); - - for (const [key, z] of Object.entries(this.zones)) { - const { w, h } = z.rect; - const zone = this.add.zone(z.center.x, z.center.y, w, h).setDepth(D.zone + 1); - zone.setInteractive({ useHandCursor: true }); - zone.on('pointerover', () => this.hoverZone(key, true)); - zone.on('pointerout', () => this.hoverZone(key, false)); - zone.on('pointerup', () => this.onZoneClick(key)); - - this._renderZoneLabel(key, z); - } - } - - _renderZoneLabel(key, z) { - if (z.number != null) return this._renderNumberBox(z); - if (key === 'field') return this._renderFieldZone(z); - if (key === 'dontpass') return this._renderDontZone(z, 21, 9); - if (key === 'dontcome') return this._renderDontComeZone(z); - if (key === 'pass') return this._renderLineZone(z, 'PASS LINE', 34); - if (key === 'come') return this._renderLineZone(z, 'COME', 32); - } - - _renderNumberBox(z) { - this.add.text(z.center.x, z.center.y - 16, z.label, { - fontFamily: 'Caesar', fontSize: '38px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - this.add.text(z.center.x, z.center.y + 24, z.payout, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } - - _renderLineZone(z, text, fontSize) { - this.add.text(z.center.x, z.center.y, text, { - fontFamily: 'Caesar', fontSize: `${fontSize}px`, color: COLORS.textHex, - letterSpacing: 14, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } - - _renderDontZone(z, fontSize, ls) { - this.add.text(z.center.x, z.center.y - 11, "DON'T PASS", { - fontFamily: 'Caesar', fontSize: `${fontSize}px`, color: COLORS.textHex, - letterSpacing: ls, - }).setOrigin(0.5).setDepth(D.zoneLabel); - this.add.text(z.center.x, z.center.y + 17, z.barText, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } - - _renderDontComeZone(z) { - this.add.text(z.center.x, z.center.y - 44, "DON'T", { - fontFamily: 'Caesar', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - this.add.text(z.center.x, z.center.y, 'COME', { - fontFamily: 'Caesar', fontSize: '18px', color: COLORS.textHex, - letterSpacing: 8, - }).setOrigin(0.5).setDepth(D.zoneLabel); - this.add.text(z.center.x, z.center.y + 44, z.barText, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } - - _renderFieldZone(z) { - // "FIELD" label left-anchored - this.add.text(z.rect.x + 55, z.center.y, 'FIELD', { - fontFamily: 'Caesar', fontSize: '20px', color: COLORS.textHex, - letterSpacing: 6, - }).setOrigin(0.5).setDepth(D.zoneLabel); - - // Vertical separator - const sep = this.add.graphics().setDepth(D.zoneLabel); - sep.lineStyle(1, COLORS.accent, 0.35); - sep.lineBetween(z.rect.x + 100, z.rect.y + 8, z.rect.x + 100, z.rect.y + z.rect.h - 8); - - // 7 number tokens, evenly spaced from x=430 to x=1630, step=200 - const fieldNums = z.fieldNums; - const startX = 430, step = 200; - fieldNums.forEach((n, i) => { - const nx = startX + i * step; - const ny = z.center.y; - if (n === 2 || n === 12) { - const cg = this.add.graphics().setDepth(D.zoneLabel); - cg.fillStyle(COLORS.accent, 0.85); - cg.fillCircle(nx, ny, 22); - cg.lineStyle(2, COLORS.gold, 1); - cg.strokeCircle(nx, ny, 22); - this.add.text(nx, ny, String(n), { - fontFamily: 'Caesar', fontSize: n === 12 ? '22px' : '22px', - color: COLORS.textDarkHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } else { - const fs = (n === 10 || n === 11) ? '24px' : '28px'; - this.add.text(nx, ny, String(n), { - fontFamily: 'Caesar', fontSize: fs, color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } - }); - - // Sub-text at bottom of zone - this.add.text(z.center.x, z.rect.y + z.rect.h - 10, z.sub, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.zoneLabel); - } - - drawZones(hoverKey = null) { - const g = this.zoneGfx; - g.clear(); - const legal = this.gs ? legalBetTypes(this.gs) : new Set(); - for (const [key, z] of Object.entries(this.zones)) { - const { x, y, w, h } = z.rect; - const isLegal = !this.gs || legal.has(z.type); - const isDont = key === 'dontpass' || key === 'dontcome'; - g.fillStyle(0x0c2e19, isLegal ? 0.5 : 0.18); - g.fillRoundedRect(x, y, w, h, 10); - const strokeColor = (key === hoverKey && isLegal) ? COLORS.gold - : isDont ? 0x8b2020 : 0x3c8a52; - const strokeAlpha = isLegal ? 0.9 : 0.4; - const strokeW = (key === hoverKey && isLegal) ? 4 : 2; - g.lineStyle(strokeW, strokeColor, strokeAlpha); - g.strokeRoundedRect(x, y, w, h, 10); - if (z.number != null) { - g.fillStyle(COLORS.accent, isLegal ? 0.55 : 0.2); - g.fillRect(x + 10, y, w - 20, 4); - } - } - } - - hoverZone(key, on) { - if (this.animating) { this.drawZones(null); this.hideTooltip(); return; } - this.drawZones(on ? key : null); - if (on) { - const delay = 500 + Math.random() * 250; - this.hoverTimer = this.time.delayedCall(delay, () => this.showTooltip(key)); - } else { - if (this.hoverTimer) { this.hoverTimer.remove(); this.hoverTimer = null; } - this.hideTooltip(); - } - } - - // ── Hover-intent tooltip ──────────────────────────────────────────────────- - buildTooltip() { - const bg = this.add.graphics(); - const title = this.add.text(0, 0, '', { - fontFamily: 'Caesar', fontSize: '30px', color: COLORS.goldHex, - }); - const desc = this.add.text(0, 0, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - wordWrap: { width: 480 }, lineSpacing: 4, - }); - this.tooltip = this.add.container(0, 0, [bg, title, desc]).setDepth(D.prompt + 10).setVisible(false); - this.tooltipBg = bg; - this.tooltipTitle = title; - this.tooltipDesc = desc; - } - - showTooltip(key) { - const info = ZONE_INFO[key]; - if (!info) return; - const PAD_X = 22, PAD_Y = 18, GAP = 10, TOTAL_W = 524; - this.tooltipTitle.setText(info.title); - this.tooltipDesc.setText(info.desc); - const titleH = this.tooltipTitle.height; - const descH = this.tooltipDesc.height; - const TOTAL_H = PAD_Y + titleH + GAP + descH + PAD_Y; - this.tooltipTitle.setPosition(PAD_X, PAD_Y); - this.tooltipDesc.setPosition(PAD_X, PAD_Y + titleH + GAP); - this.tooltipBg.clear(); - this.tooltipBg.fillStyle(0x071a0e, 0.96); - this.tooltipBg.fillRoundedRect(0, 0, TOTAL_W, TOTAL_H, 14); - this.tooltipBg.lineStyle(3, COLORS.gold, 1); - this.tooltipBg.strokeRoundedRect(0, 0, TOTAL_W, TOTAL_H, 14); - this.tooltipW = TOTAL_W; - this.tooltipH = TOTAL_H; - const ptr = this.input.activePointer; - this.positionTooltip(ptr.x, ptr.y); - this.tooltip.setVisible(true); - } - - positionTooltip(px, py) { - const OFF = 22, MARGIN = 10; - let tx = px + OFF; - let ty = py + OFF; - if (tx + this.tooltipW > GAME_WIDTH - MARGIN) tx = px - this.tooltipW - OFF; - if (ty + this.tooltipH > GAME_HEIGHT - MARGIN) ty = py - this.tooltipH - OFF; - if (tx < MARGIN) tx = MARGIN; - if (ty < MARGIN) ty = MARGIN; - this.tooltip.setPosition(tx, ty); - } - - hideTooltip() { - this.tooltip?.setVisible(false); - } - - onPointerMove(ptr) { - if (this.tooltip?.visible) this.positionTooltip(ptr.x, ptr.y); - } - - // ── Puck (ON / OFF) ──────────────────────────────────────────────────────-- buildPuck() { - this.puckOff = { x: TABLE.x + 70, y: 470 }; - this.puck = this.add.container(this.puckOff.x, this.puckOff.y).setDepth(D.puck); - const g = this.add.graphics(); - this.puck.add(g); - this.puckGfx = g; - this.puckText = this.add.text(0, 0, 'OFF', { - fontFamily: 'Caesar', fontSize: '18px', color: '#1a1208', - }).setOrigin(0.5); - this.puck.add(this.puckText); - this.drawPuck(false); + const off = puckOffUV(); + const p = P.project(off.u, off.v); + this.puck = this.add.image(p.x, p.y, 'craps-puck-off') + .setOrigin(0.5, (PUCK.ry + 3 + PUCK.t) / PUCK.h) + .setScale(0.46 * p.s) + .setDepth(D.puck); + this.puckOn = false; } - drawPuck(on) { - const g = this.puckGfx; - g.clear(); - g.fillStyle(on ? 0xffffff : 0x1a1208, 1); - g.fillCircle(0, 0, 26); - g.lineStyle(4, on ? 0x2e7d32 : 0x000000, 1); - g.strokeCircle(0, 0, 26); - this.puckText.setText(on ? 'ON' : 'OFF'); - this.puckText.setColor(on ? '#2e7d32' : '#f2ead8'); - } - - movePuck(point) { - if (point == null) { - this.drawPuck(false); - this.tweens.add({ targets: this.puck, x: this.puckOff.x, y: this.puckOff.y, duration: 300, ease: 'Quad.Out' }); - } else { - const i = NUM_TO_BOX[point]; - const z = this.zones[`box${point}`]; - this.drawPuck(true); - this.tweens.add({ targets: this.puck, x: z.center.x, y: this.zones[`box${point}`].rect.y - 14, duration: 360, ease: 'Back.Out' }); + async movePuck(point) { + const on = point != null; + const uv = on ? puckOnUV(point) : puckOffUV(); + const p = P.project(uv.u, uv.v); + const k = 0.46 * p.s; + if (on !== this.puckOn) { + await this.tweenP({ targets: this.puck, scaleY: 0, y: this.puck.y - 18, duration: 140, ease: 'Sine.easeIn' }); + this.puck.setTexture(on ? 'craps-puck-on' : 'craps-puck-off'); + this.puckOn = on; } + await this.tweenP({ targets: this.puck, x: p.x, y: p.y, scaleX: k, scaleY: k, duration: 380, ease: 'Back.easeOut' }); } - // ── Dice ─────────────────────────────────────────────────────────────────── buildDice() { - this.diceGfx = [this.add.graphics(), this.add.graphics()]; - this.diceGfx.forEach((g) => { g.setDepth(D.dice); g.setVisible(false); }); + this.dice = [new Die3D(this, D.dice), new Die3D(this, D.dice)]; + for (let i = 0; i < 5; i++) this.offerDice.push(new Die3D(this, D.offer).setVisible(false)); } - drawDieFace(g, face) { - const s = DIE_SIZE, h = s / 2, r = s * 0.18; - g.clear(); - g.fillStyle(0xf2ead8, 1); - g.fillRoundedRect(-h, -h, s, s, r); - g.lineStyle(3, 0x1a1208, 0.3); - g.strokeRoundedRect(-h, -h, s, s, r); - g.fillStyle(0x1a1208, 1); - const off = s * 0.28, pr = s * 0.085; - for (const [px, py] of PIP_POS[face]) g.fillCircle(px * off, py * off, pr); + // Dice resting at the shooter's spot (start of the game / after a seven-out). + placeIdleDice() { + const o = this.shooterOrigin(); + this.dice.forEach((d, i) => d.set(o.u + (i ? 0.035 : -0.035), o.v, 0, restingQ(1 + Math.floor(Math.random() * 6), Math.random() * 6))); + if (this.gs.shooterIndex === 0) this.dice.forEach((d) => d.setVisible(false)); } - animateThrow(finalDice) { - playSound(this, SFX.DICE_ROLL); - const ox = SEAT_X[this.gs.shooterIndex]; - const oy = SEAT_Y - 60; - return Promise.all(this.diceGfx.map((g, i) => - this.throwOneDie(g, finalDice[i], ox + (i ? 44 : -44), oy, i))); + shooterOrigin() { + const pi = this.gs.shooterIndex; + if (pi === 0) return { ...offerSpot(2), h: 4 }; + const o = throwOrigin(this.seatOf[pi]); + return { u: o.u, v: Math.min(0.92, Math.max(0.06, o.v)), h: 0 }; } - throwOneDie(g, face, ox, oy, idx) { - return new Promise((resolve) => { - const rnd6 = () => 1 + Math.floor(Math.random() * 6); - g.setVisible(true).setPosition(ox, oy).setScale(0.55).setAngle(Math.random() * 360); - this.drawDieFace(g, rnd6()); - - const wallX = TABLE.x + TABLE.w - 38 + (Math.random() * 24 - 12); // upper-right corner wall - const wallY = TABLE.y + 44 + Math.random() * 22; - const landX = LAND.x + (idx ? 50 : -50) + (Math.random() * 14 - 7); - const landY = LAND.y + (Math.random() * 24 - 12); - const outMs = 320 + idx * 28; - const backMs = 540 + idx * 44; - - const cycler = this.time.addEvent({ delay: 55, loop: true, callback: () => this.drawDieFace(g, rnd6()) }); - - this.tweens.chain({ targets: g, tweens: [ - { x: wallX, duration: outMs, ease: 'Quad.Out' }, - { x: landX, duration: backMs, ease: 'Quad.Out' }, - ] }); - this.tweens.chain({ targets: g, tweens: [ - { y: wallY, duration: outMs, ease: 'Quad.Out' }, - { y: landY, duration: backMs, ease: 'Bounce.Out' }, - ] }); - this.tweens.add({ targets: g, scale: 1, duration: outMs, ease: 'Quad.Out' }); - this.tweens.add({ targets: g, angle: g.angle + 720 + Math.random() * 360, duration: outMs + backMs, ease: 'Quad.Out' }); - - this.time.delayedCall(outMs + backMs, () => { - cycler.remove(); - this.drawDieFace(g, face); - const upright = Math.round(g.angle / 90) * 90 + (Math.random() * 14 - 7); - this.tweens.add({ - targets: g, angle: upright, duration: 140, ease: 'Back.Out', - onComplete: () => this.tweens.add({ - targets: g, scaleX: { from: 1.14, to: 1 }, scaleY: { from: 0.88, to: 1 }, - duration: 130, onComplete: resolve, - }), - }); - }); + // ── Dock ─────────────────────────────────────────────────────────────────── + buildDock() { + this.dock = new CasinoDock(this, { + sceneName: 'CrapsGame', + portrait: { x: 160, y: 1013, r: 50 }, + depth: { dock: D.dock, ui: D.ui, dockUi: D.dockUi, prompt: D.prompt }, + chipAmounts: CHIP_AMOUNTS, chipX0: 452, chipDX: 74, chipSize: 64, + betPillX: 806, + keys: { + bet: '1–5 chip · click a bet to add · right-click to take down · Space roll / ready · Z undo · R rebet · O max odds · C clear', + }, + canChip: (amt) => this.gs && amt <= this.gs.players[0].chips, + onChip: (amt) => this.selectChip(amt), }); - } + this.portraits[0] = this.dock.portrait; + this.dock.betPill.setFontSize(18).setLineSpacing(6); - // ── Chip tray ────────────────────────────────────────────────────────────── - buildChipTray() { - const y = GAME_HEIGHT - 78; - const startX = CX - 240; - this.add.text(startX - 70, y, 'Chip', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); + this.chipRing = this.add.graphics().setDepth(D.dockUi + 2); + this.dock.addToGroup('bet', this.chipRing); - CHIP_AMOUNTS.forEach((amt, i) => { - const x = startX + i * 86; - const c = this.add.container(x, y).setDepth(D.ui); - const g = this.add.graphics(); - g.fillStyle(CHIP_COLORS[amt], 1); g.fillCircle(0, 0, 30); - g.lineStyle(3, 0xffffff, 0.45); g.strokeCircle(0, 0, 30); - const t = this.add.text(0, 0, `$${amt}`, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5); - c.add([g, t]); - c.setInteractive(new Phaser.Geom.Circle(0, 0, 30), Phaser.Geom.Circle.Contains); - c.on('pointerup', () => this.selectChip(amt)); - this.chipBtns.push({ amt, container: c }); - }); - - this.chipRing = this.add.graphics().setDepth(D.ui + 1); - this.balanceText = this.add.text(startX + 4 * 86 + 30, y, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui); - this.selectChip(25); + const ghost = { height: 46, fontSize: 17, variant: 'ghost' }; + this.undoBtn = new Button(this, 1035, DOCK_Y, 'Undo', () => this.onUndo(), { ...ghost, width: 90 }); + this.clearBtn = new Button(this, 1135, DOCK_Y, 'Clear', () => this.onClear(), { ...ghost, width: 90 }); + this.rebetBtn = new Button(this, 1240, DOCK_Y, 'Rebet', () => this.onRebet(), { ...ghost, width: 100 }); + this.acrossBtn = new Button(this, 1348, DOCK_Y - 26, 'Across', () => this.onAcross(false), { ...ghost, width: 96, height: 40, fontSize: 15 }); + this.insideBtn = new Button(this, 1348, DOCK_Y + 22, 'Inside', () => this.onAcross(true), { ...ghost, width: 96, height: 40, fontSize: 15 }); + this.oddsBtn = new Button(this, 1470, DOCK_Y, 'Max Odds', () => this.onMaxOdds(), { ...ghost, width: 128 }); + this.rollBtn = new Button(this, 1700, DOCK_Y, 'Roll Dice', () => this.onRollButton(), { width: 250, height: 60, fontSize: 24 }); + const btns = [this.undoBtn, this.clearBtn, this.rebetBtn, this.acrossBtn, this.insideBtn, this.oddsBtn, this.rollBtn]; + btns.forEach((b) => b.setDepth(D.dockUi)); + this.dock.addToGroup('bet', ...btns); + this.dock.setMode('bet'); + this.selectChip(this.selectedChip); } selectChip(amt) { this.selectedChip = amt; - const hit = this.chipBtns.find((c) => c.amt === amt); + const c = this.dock.chipButton(amt); this.chipRing.clear(); - if (hit) { + if (c) { this.chipRing.lineStyle(4, COLORS.gold, 1); - this.chipRing.strokeCircle(hit.container.x, hit.container.y, 35); + this.chipRing.strokeCircle(c.img.x, DOCK_Y, 37); + } + this.dock.hidePrompts(); + if (this.hover) this.refreshHover(); + } + + buildTopButtons() { + const opts = { variant: 'ghost', width: 150, height: 42, fontSize: 16 }; + new Button(this, 90, 40, 'Leave', () => this.leave(), { ...opts, fontSize: 19 }).setDepth(D.ui); + this.speedBtn = new Button(this, 90, 92, SPEED_LABEL[this.speed], () => this.cycleSpeed(), opts).setDepth(D.ui); + this.hintBtn = new Button(this, 90, 144, this.hints ? 'Hints: On' : 'Hints: Off', () => this.toggleHints(), opts).setDepth(D.ui); + this.feltBtn = new Button(this, 90, 196, `Felt: ${this.felt[0].toUpperCase()}${this.felt.slice(1)}`, () => this.cycleFelt(), opts).setDepth(D.ui); + } + + cycleSpeed() { + const order = Object.keys(SPEEDS); + this.speed = order[(order.indexOf(this.speed) + 1) % order.length]; + save('craps-speed', this.speed); + this.speedBtn.setLabel(SPEED_LABEL[this.speed]); + this.applySpeed(); + } + + toggleHints() { + this.hints = !this.hints; + save('craps-hints', this.hints ? 'on' : 'off'); + this.hintBtn.setLabel(this.hints ? 'Hints: On' : 'Hints: Off'); + if (this.hints) this.startIdlePrompt(); + else this.dock.hidePrompts(); + this.drawFeltHighlights(); + } + + async cycleFelt() { + this.felt = FELT_ORDER[(FELT_ORDER.indexOf(this.felt) + 1) % FELT_ORDER.length]; + save('craps-felt', this.felt); + this.feltBtn.setLabel(`Felt: ${this.felt[0].toUpperCase()}${this.felt.slice(1)}`); + const key = await prepareCrapsArt(this, this.felt); + if (this.alive()) this.tableImg.setTexture(key); + } + + // ── Roll-history board ───────────────────────────────────────────────────── + buildBoard() { + ensureLeatherPanel(this, 'craps-board', BOARD.w, BOARD.h, { radius: 14 }); + this.add.image(BOARD.x, BOARD.y, 'craps-board').setOrigin(0, 0).setDepth(D.ui); + this.boardG = this.add.graphics().setDepth(D.ui + 1); + const txt = (x, y, size, color, origin = 0) => this.add.text(x, y, '', { + fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, + }).setOrigin(origin, 0.5).setDepth(D.ui + 2); + this.boardTitle = txt(BOARD.x + 14, BOARD.y + 18, 13, '#d9b45a').setText('ROLL HISTORY'); + this.boardPoint = txt(BOARD.x + BOARD.w - 14, BOARD.y + 18, 13, '#f2ead8', 1); + this.boardShooter = txt(BOARD.x + 14, BOARD.y + BOARD.h - 20, 14, '#f2ead8'); + this.boardRolls = txt(BOARD.x + BOARD.w - 14, BOARD.y + BOARD.h - 20, 14, '#d9b45a', 1); + this.boardCells = []; + for (let i = 0; i < 16; i++) { + const col = i % 8, row = Math.floor(i / 8); + const x = BOARD.x + 22 + col * ((BOARD.w - 44) / 7), y = BOARD.y + 52 + row * 40; + this.boardCells.push(this.add.text(x, y, '', { + fontFamily: 'Righteous, "Julius Sans One"', fontSize: '19px', color: '#f2ead8', + }).setOrigin(0.5).setDepth(D.ui + 2)); } } - // ── Buttons ──────────────────────────────────────────────────────────────── - buildButtons() { - const y = GAME_HEIGHT - 78; - this.clearBtn = new Button(this, CX + 420, y, 'Clear', () => this.onClear(), { - width: 130, height: 56, fontSize: 20, variant: 'ghost', - }); - this.clearBtn.setDepth(D.ui); - this.oddsBtn = new Button(this, CX + 580, y, 'Take Odds', () => this.onTakeOdds(), { - width: 170, height: 56, fontSize: 20, variant: 'ghost', - }); - this.oddsBtn.setDepth(D.ui); - this.shootBtn = new Button(this, CX + 760, y, 'Shoot', () => this.onShoot(), { - width: 180, height: 64, fontSize: 26, - }); - this.shootBtn.setDepth(D.ui); - } - - // ── Portraits ────────────────────────────────────────────────────────────── - buildPortraits() { - for (let i = 0; i < this.gs.players.length; i++) { - const x = SEAT_X[i]; - const p = this.gs.players[i]; - const seatColor = SEAT_COLORS[i % SEAT_COLORS.length]; - let ctrl; - if (i === 0) ctrl = createPlayerPortrait(this, x, SEAT_Y, PORTRAIT_R, D.portrait, 'CrapsGame'); - else ctrl = createOpponentPortrait(this, p.avatar, x, SEAT_Y, PORTRAIT_R, D.portrait); - this.portraits.push(ctrl); - - const ring = this.add.graphics().setDepth(D.portrait + 1); - ring.lineStyle(4, seatColor, 1); - ring.strokeCircle(x, SEAT_Y, PORTRAIT_R + 5); - - const shortName = p.name.length > 10 ? p.name.slice(0, 9) + '…' : p.name; - this.add.text(x, SEAT_Y + PORTRAIT_R + 16, shortName, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: hexStr(seatColor), - }).setOrigin(0.5).setDepth(D.ui); - } - this.shooterRingGfx = this.add.graphics().setDepth(D.shooterRing); - this.renderAiWagers(); - this.renderAiBets(); - this.updateBalances(); - } - - updateShooterIndicator() { - const g = this.shooterRingGfx; - if (!g) return; + drawBoard() { + const g = this.boardG; g.clear(); - const x = SEAT_X[this.gs.shooterIndex]; - g.lineStyle(4, COLORS.gold, 1); - g.strokeCircle(x, SEAT_Y, PORTRAIT_R + 7); - } - - // ── Render human bets on the layout ──────────────────────────────────────-- - betTokenPos(bet) { - switch (bet.type) { - case BET.PASS: return { x: this.zones.pass.center.x - 220, y: this.zones.pass.center.y }; - case BET.DONT_PASS: return { x: this.zones.dontpass.center.x - 180, y: this.zones.dontpass.center.y }; - case BET.FIELD: return { x: this.zones.field.rect.x + 70, y: this.zones.field.center.y }; - case BET.PLACE: return this.boxChipPos(bet.number, 0); - case BET.COME: - return bet.comePoint == null - ? { x: this.zones.come.center.x - 260, y: this.zones.come.center.y } - : this.boxChipPos(bet.comePoint, 1); - case BET.DONT_COME: - return bet.comePoint == null - ? { x: this.zones.dontcome.center.x, y: this.zones.dontcome.center.y + 30 } - : this.boxChipPos(bet.comePoint, 2); - default: return { x: CX, y: LAND.y }; + g.fillStyle(0x050403, 1); + g.fillRoundedRect(BOARD.x + 8, BOARD.y + 32, BOARD.w - 16, 86, 6); + const recent = this.history.slice(-16).reverse(); + this.boardCells.forEach((t, i) => { + const h = recent[i]; + if (!h) { t.setText(''); return; } + const color = h.total === 7 ? (h.sevenOut ? '#ff5a4a' : '#ff8a7a') + : h.pointMade ? '#ffd700' : [2, 3, 12].includes(h.total) ? '#7fb8ff' : '#f2ead8'; + t.setText(String(h.total)).setColor(color).setAlpha(i === 0 ? 1 : 0.85 - i * 0.03); + if (h.pointEstablished || h.pointMade) { + g.lineStyle(2, h.pointMade ? 0xffd700 : 0xf2ead8, 0.9); + g.strokeCircle(t.x, t.y, 13); + } + if (h.hard) { + g.fillStyle(0xd23a2e, 1); + g.fillCircle(t.x + 11, t.y - 11, 3); + } + }); + const gs = this.gs; + this.boardPoint.setText(gs.point ? `POINT ${gs.point}` : 'COME-OUT'); + const shooter = gs.players[gs.shooterIndex]; + const hot = gs.shooterRolls >= 10; + this.boardShooter.setText(`Shooter: ${shooter.name.length > 12 ? shooter.name.slice(0, 11) + '…' : shooter.name}`); + this.boardRolls.setText(`${hot ? 'HOT · ' : ''}Roll ${gs.shooterRolls + 1}`).setColor(hot ? '#ff9a3c' : '#d9b45a'); + if (hot) { + g.lineStyle(3, 0xff9a3c, 0.55 + 0.25 * Math.sin(this.time.now / 300)); + g.strokeRoundedRect(BOARD.x + 2, BOARD.y + 2, BOARD.w - 4, BOARD.h - 4, 13); } } - boxChipPos(number, slot) { - const z = this.zones[`box${number}`]; - const offs = [{ dx: -40, dy: 24 }, { dx: 0, dy: 24 }, { dx: 40, dy: 24 }]; - const o = offs[slot] ?? offs[0]; - return { x: z.center.x + o.dx, y: z.rect.y + z.rect.h + 4 + o.dy }; + // ── Seats ────────────────────────────────────────────────────────────────── + buildSeats() { + for (let pi = 1; pi < this.gs.players.length; pi++) { + const seat = this.seatOf[pi]; + const pt = seatPortrait(seat); + const color = SEAT_COLORS[pi % SEAT_COLORS.length]; + this.portraits[pi] = createOpponentPortrait(this, this.opponents[pi - 1], pt.x, pt.y, pt.r, D.ui); + const ring = this.add.graphics().setDepth(D.ui + 3); + ring.lineStyle(3, color, 1); + ring.strokeCircle(pt.x, pt.y, pt.r + 4); + const below = seat === 'E'; + const tx = below ? pt.x : pt.x + pt.r + 12; + const ty = below ? pt.y + pt.r + 24 : pt.y; + const name = this.add.text(tx, ty - 11, this.gs.players[pi].name, { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: hexStr(color), + }).setOrigin(below ? 0.5 : 0, 0.5).setDepth(D.ui + 2); + const chips = this.add.text(tx, ty + 10, '', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f2ead8', + }).setOrigin(below ? 0.5 : 0, 0.5).setDepth(D.ui + 2); + const bg = this.add.graphics().setDepth(D.ui + 1); + this.plates[pi] = { name, chips, bg, below, pt }; + } + this.shooterRing = this.add.graphics().setDepth(D.ui + 4); + this.shooterTag = this.add.text(0, 0, 'SHOOTER', { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#1a1208', backgroundColor: '#f5d020', + padding: { x: 5, y: 2 }, + }).setOrigin(0.5).setDepth(D.ui + 5); + this.updatePlates(); } - renderHumanBets() { - for (const o of this.humanChipObjs) o.destroy(); - this.humanChipObjs = []; + updatePlates() { + for (const [pi, pl] of Object.entries(this.plates)) { + const p = this.gs.players[pi]; + pl.chips.setText(money(p.chips)); + const w = Math.max(pl.name.width, pl.chips.width) + 16; + pl.bg.clear(); + pl.bg.fillStyle(0x000000, 0.62); + if (pl.below) pl.bg.fillRoundedRect(pl.name.x - w / 2, pl.name.y - 12, w, 46, 6); + else pl.bg.fillRoundedRect(pl.name.x - 8, pl.name.y - 12, w, 46, 6); + } const human = this.gs.players[0]; - for (const bet of human.bets) { - const pos = this.betTokenPos(bet); - const label = bet.oddsAmount > 0 ? `$${bet.amount}+${bet.oddsAmount}` : `$${bet.amount}`; - this.humanChipObjs.push(this.makeChipToken(pos.x, pos.y, label, this.selectedChipColorFor(bet.amount))); + this.dock.balanceTxt.setText(money(human.chips)); + this.dock.nameTxt.setText(human.name); + const onTable = totalAtRisk(human); + const last = human.lastDelta; + this.dock.betPill.setText(`ON TABLE ${money(onTable)}\nLAST ROLL ${last > 0 ? '+' : last < 0 ? '−' : ''}${money(Math.abs(last))}`) + .setColor(last > 0 ? '#9be07a' : last < 0 ? '#ff9a8a' : COLORS.textHex); + } + + updateShooter() { + const pi = this.gs.shooterIndex; + const pt = pi === 0 ? { x: 160, y: 1013, r: 50 } : seatPortrait(this.seatOf[pi]); + const g = this.shooterRing; + g.clear(); + g.lineStyle(4, 0xf5d020, 1); + g.strokeCircle(pt.x, pt.y, pt.r + 9); + this.shooterTag.setPosition(pt.x, pt.y - pt.r - 10); + this.tweens.killTweensOf(g); + g.setAlpha(1); + this.tweens.add({ targets: g, alpha: 0.45, duration: 700, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + } + + // ── Rail chips (each player's bankroll, racked in the groove) ────────────── + railColumns(amount) { + const cols = []; + let rest = Math.floor(amount); + for (const d of [100, 25, 5, 1]) { + let n = Math.floor(rest / d); + if (d === 1) n = Math.min(n, 10); + rest -= n * d; + while (n > 0 && cols.length < 6) { const k = Math.min(10, n); cols.push({ d, n: k }); n -= k; } } + return cols; } - selectedChipColorFor(amount) { - if (amount >= 100) return CHIP_COLORS[100]; - if (amount >= 50) return CHIP_COLORS[50]; - if (amount >= 25) return CHIP_COLORS[25]; - return CHIP_COLORS[5]; - } - - makeChipToken(x, y, label, color) { - const c = this.add.container(x, y).setDepth(D.betChip); - const g = this.add.graphics(); - g.fillStyle(color, 1); g.fillCircle(0, 0, 19); - g.lineStyle(3, 0xffffff, 0.5); g.strokeCircle(0, 0, 19); - const t = this.add.text(0, 0, label, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5); - c.add([g, t]); + makeColumn(x, y, denom, count, size, depth) { + const c = this.add.container(x, y).setDepth(depth); + const k = size / FACE; + const sh = this.add.graphics(); + sh.fillStyle(0x000000, 0.4); + sh.fillEllipse(size * 0.06, size * 0.05, size * 1.1, SLICE_RY * 2 * k * 1.1); + c.add(sh); + for (let i = 0; i < count; i++) { + c.add(this.add.image(0, -i * SLICE_T * k, `chip-slice-${denom}`) + .setOrigin(0.5, (SLICE_RY + 2 + SLICE_T) / SLICE_H).setScale(k)); + } return c; } - renderAiWagers() { - for (let i = 1; i < this.gs.players.length; i++) { - if (this.aiWagerObjs[i]) { this.aiWagerObjs[i].destroy(); delete this.aiWagerObjs[i]; } - const risk = totalAtRisk(this.gs.players[i]); - if (risk <= 0) continue; - const x = SEAT_X[i]; - this.aiWagerObjs[i] = this.makeChipToken(x, SEAT_Y - PORTRAIT_R - 18, `$${risk}`, SEAT_COLORS[i % SEAT_COLORS.length]); + renderRail(pi) { + for (const o of this.railObjs[pi] ?? []) o.destroy(); + const seat = this.seatOf[pi]; + const cols = this.railColumns(this.gs.players[pi].chips); + const step = 0.033; + this.railObjs[pi] = cols.map((col, i) => { + const off = (i - (cols.length - 1) / 2) * step * (seat === 'E' ? 1.3 : 1); + const p = railPose(seat, off); + return this.makeColumn(p.x, p.y + 4 * p.s, col.d, col.n, 36 * p.s, D.stacks - 1 + p.y / 10000); + }); + } + + renderAllRails() { + for (let pi = 0; pi < this.gs.players.length; pi++) this.renderRail(pi); + this.updatePlates(); + } + + railSource(pi) { return railPose(this.seatOf[pi]); } + + // ── Bet stacks ───────────────────────────────────────────────────────────── + // Where every bet stack belongs right now. + layoutBets() { + const byLane = new Map(); + this.gs.players.forEach((p, pi) => p.bets.forEach((b) => { + const lane = laneForBet(b); + if (!lane) return; + if (!byLane.has(lane)) byLane.set(lane, []); + byLane.get(lane).push({ pi, b }); + })); + const out = new Map(); + for (const [lane, list] of byLane) { + list.sort((a, c) => SLOT_ORDER.indexOf(this.seatOf[a.pi]) - SLOT_ORDER.indexOf(this.seatOf[c.pi])); + list.forEach(({ pi, b }, index) => { + const seat = this.seatOf[pi]; + const spot = laneSpot(lane, { seat, index, count: list.length }); + const p = P.project(spot.u, spot.v); + const size = (pi === 0 ? STACK.human : STACK.ai) * p.s; + out.set(`${pi}:${b.id}:flat`, { pi, bet: b, part: 'flat', amount: b.amount, x: p.x, y: p.y, s: p.s, size }); + if (b.oddsAmount > 0) { + let q; + if (lane === 'pass') { + const o = laneSpot('odds', { seat }); + q = P.project(o.u, o.v); + } else if (lane === 'dontpass') { + q = P.project(spot.u + 0.04, spot.v); + } else { + const off = oddsOffset(lane); + q = P.project(spot.u + off.du, spot.v + off.dv); + } + out.set(`${pi}:${b.id}:odds`, { pi, bet: b, part: 'odds', amount: b.oddsAmount, x: q.x, y: q.y - 2, s: q.s, size: size * 0.92 }); + } + }); + } + return out; + } + + makeBetStack(m) { + const human = m.pi === 0; + const st = makeChipStack(this, m.x, m.y, m.amount, { + size: m.size, depth: D.stacks + m.y / 10000, seed: m.amount + m.pi * 7, label: human, maxChips: 12, + }); + st.chipSize = m.size; + if (!human) { + const ring = this.add.graphics(); + ring.lineStyle(2.5, SEAT_COLORS[m.pi % SEAT_COLORS.length], 0.95); + ring.strokeEllipse(0, 0, m.size * 1.18, SLICE_RY * 2 * (m.size / FACE) * 1.3); + st.addAt(ring, 1); + } else if (m.part === 'odds') { + const t = this.add.text(0, m.size * 0.42, 'ODDS', { + fontFamily: '"Julius Sans One"', fontSize: '10px', color: '#f5d020', fontStyle: 'bold', + stroke: '#000000', strokeThickness: 3, + }).setOrigin(0.5); + st.add(t); + } + st._meta = { amount: m.amount, x: m.x, y: m.y }; + return st; + } + + // Bring the felt in line with the state. New opponent stacks fly in from + // their rail; moved stacks (come bets travelling, flow lanes re-spacing) slide. + renderBets({ animate = true } = {}) { + const want = this.layoutBets(); + for (const [key, st] of this.stackObjs) { + if (!want.has(key)) { this.tweens.killTweensOf(st); st.destroy(); this.stackObjs.delete(key); } + } + let flyIdx = 0; + for (const [key, m] of want) { + const st = this.stackObjs.get(key); + if (st && st._meta.amount === m.amount) { + if (Math.abs(st._meta.x - m.x) > 0.5 || Math.abs(st._meta.y - m.y) > 0.5) { + st._meta.x = m.x; st._meta.y = m.y; + st.setDepth(D.stacks + m.y / 10000); + if (animate) this.tweens.add({ targets: st, x: m.x, y: m.y, duration: 420, ease: 'Cubic.easeInOut' }); + else st.setPosition(m.x, m.y); + } + continue; + } + const from = st ? { x: st.x, y: st.y } : null; + st?.destroy(); + const nst = this.makeBetStack(m); + this.stackObjs.set(key, nst); + if (!animate) continue; + if (from && (Math.abs(from.x - m.x) > 0.5 || Math.abs(from.y - m.y) > 0.5)) { + nst.setPosition(from.x, from.y); + this.tweens.add({ targets: nst, x: m.x, y: m.y, duration: 420, ease: 'Cubic.easeInOut' }); + } else if (!from && m.pi !== 0) { + const src = this.railSource(m.pi); + nst.setPosition(src.x, src.y).setAlpha(0).setScale(0.8); + this.tweens.add({ + targets: nst, x: m.x, y: m.y, alpha: 1, scale: 1, duration: 420, delay: flyIdx++ * 45, ease: 'Cubic.easeOut', + }); + } + } + this.renderLammers(); + // a Press offer goes away with its bet (taken down / undone) + const live = new Set(this.gs.players[0].bets.map((b) => b.id)); + this.pressBtns = this.pressBtns.filter((b) => (live.has(b.betId) ? true : (b.destroy(), false))); + } + + // ON/OFF markers on your Place / Buy / Hardway bets during the come-out. + renderLammers() { + for (const l of this.lammers) l.obj.destroy(); + this.lammers = []; + if (!this.gs || this.gs.point !== null) return; + for (const b of this.gs.players[0].bets) { + if (!canToggleWorking(b, this.gs)) continue; + const st = this.stackObjs.get(`0:${b.id}:flat`); + if (!st) continue; + const on = isWorking(b, this.gs); + const r = Math.max(9, st.chipSize * 0.26); + const x = st._meta.x - st.chipSize * 0.62, y = st._meta.y - st.chipSize * 0.32; + const c = this.add.container(x, y).setDepth(D.lammer); + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.4); g.fillEllipse(1, 3, r * 2.1, r * 1.3); + g.fillStyle(on ? 0xf4f4ee : 0x111111, 1); g.fillEllipse(0, 0, r * 2, r * 1.25); + g.lineStyle(1.5, on ? 0x1d6b2c : 0x9a9a9a, 1); g.strokeEllipse(0, 0, r * 2, r * 1.25); + const t = this.add.text(0, 0, on ? 'ON' : 'OFF', { + fontFamily: '"Julius Sans One"', fontSize: `${Math.round(r * 0.78)}px`, color: on ? '#1d6b2c' : '#f4ecd6', fontStyle: 'bold', + }).setOrigin(0.5); + c.add([g, t]); + this.lammers.push({ x, y, r: r * 1.1, betId: b.id, obj: c }); } } - betZoneKey(bet) { - switch (bet.type) { - case BET.PASS: return 'pass'; - case BET.DONT_PASS: return 'dontpass'; - case BET.FIELD: return 'field'; - case BET.PLACE: return `box${bet.number}-place`; - case BET.COME: return bet.comePoint == null ? 'come' : `box${bet.comePoint}-come`; - case BET.DONT_COME: return bet.comePoint == null ? 'dontcome' : `box${bet.comePoint}-dontcome`; + // ── Felt input ───────────────────────────────────────────────────────────── + buildFeltInput() { + this.input.mouse?.disableContextMenu(); + const zone = this.add.zone(CX, CY, GAME_WIDTH, GAME_HEIGHT).setDepth(D.input).setInteractive(); + zone.on('pointermove', (p) => this.onFeltMove(p)); + zone.on('pointerout', () => this.setHover(null)); + zone.on('pointerdown', (p) => this.onFeltDown(p)); + zone.on('pointerup', (p) => this.onFeltUp(p)); + } + + // What is under the pointer: a lammer, an offered die, a stack, or a zone. + pick(x, y) { + if (y >= DOCK.y) return null; + for (const l of this.lammers) { + if (Math.hypot(x - l.x, (y - l.y) * 1.4) <= l.r) return { kind: 'lammer', betId: l.betId }; + } + if (this.phase === 'bet' && this.gs?.shooterIndex === 0) { + for (let i = 0; i < this.offerDice.length; i++) { + const d = this.offerDice[i]; + if (!d.visible) continue; + const c = d.screenCenter(); + if (Math.hypot(x - c.x, y - c.y) <= DIE.size * c.s * 0.9) return { kind: 'die', index: i }; + } + } + let best = null; + for (const [key, st] of this.stackObjs) { + const sz = st.chipSize; + const cy = st.y + (st.stackTopY ?? -sz * 0.3) * 0.5; + const d = Math.hypot((x - st.x) / (sz * 0.6), (y - cy) / (sz * 0.55 + Math.abs(st.stackTopY ?? 0) * 0.5)); + if (d <= 1 && (!best || st.depth > best.st.depth)) best = { key, st }; + } + if (best) { + const [pi, betId, part] = best.key.split(':'); + const bet = this.gs.players[+pi].bets.find((b) => b.id === +betId); + if (bet) return { kind: 'stack', pi: +pi, bet, part, key: best.key, zoneKey: hitZone(x, y) }; + } + const z = hitZone(x, y); + return z ? { kind: 'zone', key: z } : null; + } + + onFeltMove(p) { + this.setHover(this.pick(p.worldX, p.worldY)); + } + + sameHover(a, b) { + if (!a || !b) return a === b; + return a.kind === b.kind && a.key === b.key && a.betId === b.betId && a.index === b.index; + } + + setHover(h) { + if (this.sameHover(h, this.hover)) return; + this.hover = h; + this.refreshHover(); + } + + refreshHover() { + const h = this.hover; + const betting = this.phase === 'bet'; + const zoneKey = this.hoverZoneKey(h); + const clickable = h && betting && (h.kind === 'stack' && h.pi === 0 ? true : h.kind === 'stack' || h.kind === 'zone' + ? !!zoneKey && this.zoneActionable(zoneKey) : true); + this.input.setDefaultCursor(clickable ? 'pointer' : 'default'); + this.drawFeltHighlights(); + this.hoverTimer?.remove(); + this.tooltip.hide(); + if (!h || h.kind === 'die') return; + this.hoverTimer = this.time.delayedCall(320, () => { + const content = this.tooltipFor(h); + if (!content || !this.sameHover(h, this.hover)) return; + this.tooltip.setContent(content); + const ptr = this.input.activePointer; + this.tooltip._reposition(ptr.x, ptr.y); + this.tooltip.container.setVisible(true); + }); + } + + // ── Learner hints ───────────────────────────────────────────────────────── + // Which low-edge bets to point at right now (skipping ones you already have). + hintKeys() { + const gs = this.gs; + if (!this.hints || !gs || this.phase !== 'bet') return []; + const mine = gs.players[0].bets; + const has = (type, n = null) => mine.some((b) => b.type === type && (n == null || b.number === n)); + const keys = []; + if (gs.point === null) { + if (!has(BET.PASS) && !has(BET.DONT_PASS)) keys.push('pass', 'dontpass'); + } else { + const lb = this.humanLineBet(); + if (lb && oddsRoom(gs, 0, lb.id) > 0) keys.push('odds'); + const comes = mine.filter((b) => b.type === BET.COME).length; + if (comes < 2) keys.push('come'); + for (const n of [6, 8]) if (gs.point !== n && !has(BET.PLACE, n) && !has(BET.BUY, n)) keys.push(`place${n}`); + } + return keys; + } + + // Table-space outline of a zone (the Pass Line is one L, not two boxes). + zoneOutlineUV(key) { + if (key === 'pass') { + const [b, sd] = ZONES.pass.rects; + return [ + { u: sd.u0, v: sd.v0 }, { u: sd.u1, v: sd.v0 }, { u: sd.u1, v: b.v0 }, + { u: b.u1, v: b.v0 }, { u: b.u1, v: b.v1 }, { u: b.u0, v: b.v1 }, + ]; + } + const r = ZONES[key].rects[0]; + return [{ u: r.u0, v: r.v0 }, { u: r.u1, v: r.v0 }, { u: r.u1, v: r.v1 }, { u: r.u0, v: r.v1 }]; + } + + // An outline floating above a zone: it bobs, glows, casts a shadow on the felt + // and has sparks running around its edge. Returns the lifted outline + bob. + floatOutline(g, key, color, now, i, { alpha = 1, sparkSpeed = 0.32 } = {}) { + const bob = (Math.sin(now * 2.6 + i * 0.9) + 1) / 2; // 0…1 + const h = 7 + 9 * bob; // px above the felt + const uv = this.zoneOutlineUV(key); + const flat = uv.map((p) => P.project(p.u, p.v)); + const up = uv.map((p) => lift(p.u, p.v, h)); + g.lineStyle(7, 0x000000, (0.22 + 0.1 * (1 - bob)) * alpha); + g.strokePoints(flat, true); + g.fillStyle(color, (0.05 + 0.07 * bob) * alpha); + g.fillPoints(up, true); + g.lineStyle(16, color, (0.08 + 0.06 * bob) * alpha); g.strokePoints(up, true); + g.lineStyle(9, color, (0.16 + 0.1 * bob) * alpha); g.strokePoints(up, true); + g.lineStyle(3.5, color, 0.95 * alpha); g.strokePoints(up, true); + g.lineStyle(1.2, 0xffffff, 0.85 * alpha); g.strokePoints(up, true); + const segs = up.map((a, j) => { + const b = up[(j + 1) % up.length]; + return { a, b, len: Math.hypot(b.x - a.x, b.y - a.y) }; + }); + const per = segs.reduce((acc, sgm) => acc + sgm.len, 0); + for (const off of [0, 0.5]) { + let d = ((now * sparkSpeed + off + i * 0.17) % 1) * per; + for (const sgm of segs) { + if (d > sgm.len) { d -= sgm.len; continue; } + const t = d / sgm.len; + const x = sgm.a.x + (sgm.b.x - sgm.a.x) * t, y = sgm.a.y + (sgm.b.y - sgm.a.y) * t; + g.fillStyle(color, 0.35 * alpha); g.fillCircle(x, y, 9); + g.fillStyle(0xffffff, 0.95 * alpha); g.fillCircle(x, y, 3.5); + break; + } + } + return { up, bob }; + } + + // Where a zone's floating tag goes (the Pass Line's sits over its long band). + tagAnchor(key, up, bob) { + if (key === 'pass') return { x: (up[2].x + up[3].x) / 2, y: up[3].y - 6 - 4 * bob }; + const top = up.reduce((m, p) => (p.y < m.y ? p : m), up[0]); + return { x: up.reduce((a, p) => a + p.x, 0) / up.length, y: top.y - 6 - 4 * bob }; + } + + // Bright cyan outlines on the low-edge bets, each with a little tag. + drawHints() { + const g = this.hintG; + if (!g) return; + const keys = this.hintKeys(); + const sig = keys.join(); + if (sig !== this.hintSig) { + this.hintSig = sig; + for (const [k, t] of this.hintTags) if (!keys.includes(k)) { t.destroy(); this.hintTags.delete(k); } + for (const k of keys) { + if (this.hintTags.has(k)) continue; + const t = this.add.text(0, 0, HINT_TAGS[k] ?? 'GOOD BET', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#06262b', fontStyle: 'bold', + backgroundColor: '#7ff6ff', padding: { x: 7, y: 3 }, + }).setOrigin(0.5, 1).setDepth(D.hints + 0.1); + this.hintTags.set(k, t); + } + } + g.clear(); + if (!keys.length) return; + const now = this.game.loop.time / 1000; + keys.forEach((key, i) => { + const { up, bob } = this.floatOutline(g, key, 0x3ff0ff, now, i); + const tag = this.hintTags.get(key); + if (tag) { const a = this.tagAnchor(key, up, bob); tag.setPosition(a.x, a.y); } + }); + } + + // ── Roll results on the felt ────────────────────────────────────────────── + // Every zone's fate on this roll, found by resolving a probe bet on each one + // against the same dice and point (so it is exactly what the rules pay). + zoneOutcomes(state) { + const probe = cloneState(state); + probe.players = [{ name: 'probe', isAI: true, chips: 1e9, bets: [], lastDelta: 0 }]; + const keyOf = new Map(); + let id = 1; + for (const z of Object.values(ZONES)) { + if (z.key === 'odds') continue; + if ((z.type === BET.COME || z.type === BET.DONT_COME) && state.point === null) continue; + probe.players[0].bets.push({ id, type: z.type, number: z.number ?? null, comePoint: null, amount: 12, oddsAmount: 0, onComeOut: false }); + keyOf.set(id++, z.key); + } + const out = new Map(); + for (const p of resolveRoll(probe).payouts) out.set(keyOf.get(p.betId), p.result); + return out; + } + + // The felt zone a resolved bet was sitting in. + zoneForPayout(p) { + if (p.betType === BET.COME) return p.number != null ? `place${p.number}` : 'come'; + if (p.betType === BET.DONT_COME) return p.number != null ? `lay${p.number}` : 'dontcome'; + return zoneKeyFor(p.betType, p.number); + } + + // Gold floating outlines on everything that pays this roll, a red flash on + // zones where someone's chips just lost, and "+$X" tags on your winners. + showRollFx(outcomes, res) { + this.clearRollFx(); + const wins = [...outcomes].filter(([, r]) => r === 'win').map(([k]) => k); + const losses = [...new Set(res.payouts.filter((p) => p.result === 'lose').map((p) => this.zoneForPayout(p)).filter(Boolean))]; + const mine = new Map(); + for (const p of res.payouts) { + if (p.playerIndex !== 0 || p.result !== 'win') continue; + const k = this.zoneForPayout(p); + if (k) mine.set(k, (mine.get(k) ?? 0) + p.delta); + } + for (const k of mine.keys()) if (!wins.includes(k)) wins.push(k); + const tags = new Map(); + for (const [k, amt] of mine) { + tags.set(k, this.add.text(0, 0, `YOU WIN +${money(amt)}`, { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#2a1a00', fontStyle: 'bold', + backgroundColor: '#ffd34d', padding: { x: 8, y: 4 }, + }).setOrigin(0.5, 1).setDepth(D.result + 0.1)); + } + this.resultTags = [...tags.values()]; + this.resultFx = { wins, losses, tags, start: this.game.loop.time, dur: 3800 / (SPEEDS[this.speed] ?? 1) }; + } + + clearRollFx() { + this.resultTags.forEach((t) => t.destroy()); + this.resultTags = []; + this.resultFx = null; + this.resultG?.clear(); + } + + drawResultFx() { + const fx = this.resultFx; + const g = this.resultG; + if (!fx || !g) return; + const el = this.game.loop.time - fx.start; + if (el > fx.dur) { this.clearRollFx(); return; } + const fadeIn = Math.min(1, el / 180), fadeOut = Math.min(1, (fx.dur - el) / 600); + const a = fadeIn * fadeOut; + const now = this.game.loop.time / 1000; + g.clear(); + // losers: a red wash that drains away + const lossA = a * Math.max(0, 1 - el / (fx.dur * 0.6)); + for (const k of fx.losses) { + for (const r of ZONES[k].rects) { + const pts = rectOutline(r); + g.fillStyle(0xff2a2a, 0.26 * lossA); g.fillPoints(pts, true); + g.lineStyle(3, 0xff5a4a, 0.9 * lossA); g.strokePoints(pts, true); + } + } + fx.wins.forEach((k, i) => { + const { up, bob } = this.floatOutline(g, k, 0xffc933, now, i, { alpha: a, sparkSpeed: 0.55 }); + const tag = fx.tags.get(k); + if (tag) { const p = this.tagAnchor(k, up, bob); tag.setPosition(p.x, p.y - 4).setAlpha(a); } + }); + } + + // The zone a hover acts on: the zone itself, or the zone under an opponent's stack. + hoverZoneKey(h) { + if (!h) return null; + if (h.kind === 'zone') return h.key; + if (h.kind === 'stack' && h.pi !== 0) return h.zoneKey ?? null; + return null; + } + + zoneActionable(key) { + const z = ZONES[key]; + if (key === 'odds') return this.humanLineBet() != null; + return legalBetTypes(this.gs).has(z.type); + } + + humanLineBet() { + const gs = this.gs; + if (!gs || gs.point === null) return null; + return gs.players[0].bets.find((b) => b.type === BET.PASS || b.type === BET.DONT_PASS) ?? null; + } + + winPreview(type, number, amt) { + switch (type) { + case BET.PASS: case BET.DONT_PASS: case BET.COME: case BET.DONT_COME: case BET.FIELD: case BET.BIG: return amt; + case BET.PLACE: return placeWin(amt, number); + case BET.BUY: return trueOddsWin(amt, number) - vig(amt); + case BET.LAY: { const w = layOddsWin(amt, number); return w - Math.min(w, vig(w)); } + case BET.HARD: return amt * (number === 4 || number === 10 ? 7 : 9); + case BET.ANY7: return amt * 4; + case BET.ANY_CRAPS: return amt * 7; + case BET.YO: case BET.ACE_DEUCE: return amt * 15; + case BET.ACES: case BET.BOXCARS: return amt * 30; default: return null; } } - drawAiChip(x, y, playerIndex, label, name) { - const color = SEAT_COLORS[playerIndex % SEAT_COLORS.length]; - const c = this.add.container(x, y).setDepth(D.betChip); - const g = this.add.graphics(); - g.fillStyle(color, 1); g.fillCircle(0, 0, 16); - g.lineStyle(3, 0xffffff, 0.5); g.strokeCircle(0, 0, 16); - const t = this.add.text(0, 0, label, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5); - const n = this.add.text(0, 24, name, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: hexStr(color), fontStyle: 'bold', - stroke: '#000000', strokeThickness: 2, - }).setOrigin(0.5); - c.add([g, t, n]); - return c; - } - - // Place a chip in the left/right side of a zone, skirting the center text. - chipSidePos(z, zoneKey, i, n, pi) { - // Approximate widths of each zone's center text label. - const avoidW = { pass: 250, dontpass: 310, field: 550, come: 200, dontcome: 60 }[zoneKey] ?? 240; - const margin = 28; - const jitter = this.seatJitter[pi % this.seatJitter.length]; - const leftBound = z.rect.x + margin; - const rightBound = z.rect.x + z.rect.w - margin; - const leftEnd = z.center.x - avoidW / 2; - const rightStart = z.center.x + avoidW / 2; - const leftW = Math.max(0, leftEnd - leftBound); - const rightW = Math.max(0, rightBound - rightStart); - - let x; - if (leftW <= 0 && rightW <= 0) { - // Narrow zone with no side room — fall back to even spread. - x = leftBound + ((i + 1) / (n + 1)) * (rightBound - leftBound) + jitter.dx * 0.5; - } else { - // Alternate chips left/right so they spread across both sides. - const leftCount = Math.ceil(n / 2); - const rightCount = Math.floor(n / 2); - if (i % 2 === 0) { - const si = i / 2; - x = leftBound + (si + 1) * (leftW / (leftCount + 1)) + jitter.dx * 0.6; + tooltipFor(h) { + const gs = this.gs; + if (h.kind === 'lammer') { + const b = gs.players[0].bets.find((x) => x.id === h.betId); + if (!b) return null; + return { + title: `${betName(b)} — ${isWorking(b, gs) ? 'ON' : 'OFF'}`, + lines: [{ text: `${isWorking(b, gs) ? 'Working' : 'Not working'} for the come-out roll. Click to turn it ${isWorking(b, gs) ? 'off' : 'on'}.` }], + }; + } + if (h.kind === 'stack') { + const p = gs.players[h.pi]; + const b = h.bet; + const lines = []; + if (h.part === 'odds') { + lines.push({ text: `Odds ${money(b.oddsAmount)} behind ${money(b.amount)} — paid at true odds.` }); } else { - const si = (i - 1) / 2; - x = rightStart + (si + 1) * (rightW / (Math.max(rightCount, 1) + 1)) + jitter.dx * 0.6; + lines.push({ text: `${money(b.amount)}${b.oddsAmount ? ` + ${money(b.oddsAmount)} odds` : ''} · pays ${paysLabel(b.type, b.number ?? b.comePoint)}` }); } - } - x = Math.max(leftBound, Math.min(rightBound, x)); - return { x, y: z.center.y + jitter.dy }; - } - - renderAiBets(animate = false) { - for (const o of this.aiBetObjs) o.destroy(); - this.aiBetObjs = []; - - const groups = new Map(); - for (let pi = 1; pi < this.gs.players.length; pi++) { - for (const bet of this.gs.players[pi].bets) { - const key = this.betZoneKey(bet); - if (!key) continue; - if (!groups.has(key)) groups.set(key, []); - groups.get(key).push({ pi, bet }); + if (h.pi === 0 && this.phase === 'bet') { + const n = oddsNumber(b, gs); + if (h.part === 'odds') lines.push({ text: 'Click to add odds · right-click to take the odds down', color: '#d9b45a' }); + else if (n != null) { + const room = maxOddsFor(b, gs) - b.oddsAmount; + lines.push({ text: room > 0 ? `Click to add odds (room for ${money(room)})` : 'Odds are at the maximum', color: '#d9b45a' }); + } else lines.push({ text: 'Click to add a chip', color: '#d9b45a' }); + lines.push(isContract(b, gs) && h.part === 'flat' + ? { text: 'Contract bet — it stays until it resolves', color: '#ff9a8a' } + : { text: 'Right-click to take it down', color: '#9be07a' }); + if (canToggleWorking(b, gs)) lines.push({ text: `${isWorking(b, gs) ? 'ON' : 'OFF'} for the come-out`, color: '#c9c2b0' }); } + return { title: `${h.pi === 0 ? 'Your' : `${p.name}'s`} ${betName(b)}`, titleColor: hexStr(SEAT_COLORS[h.pi % SEAT_COLORS.length]), lines }; } - - for (const [key, entries] of groups.entries()) { - const n = entries.length; - if (key.includes('-')) { - const [boxPart, slotType] = key.split('-'); - const number = parseInt(boxPart.slice(3)); - const slot = slotType === 'place' ? 0 : slotType === 'come' ? 1 : 2; - const base = this.boxChipPos(number, slot); - entries.forEach((e, idx) => { - const dx = n > 1 ? (idx - (n - 1) / 2) * 22 : 0; - const finalX = base.x + dx; - const finalY = base.y; - const label = `$${e.bet.amount}`; - const shortN = this.gs.players[e.pi] - ? (this.gs.players[e.pi].name.length > 6 ? this.gs.players[e.pi].name.slice(0, 5) + '…' : this.gs.players[e.pi].name) - : ''; - const chip = this.drawAiChip(finalX, finalY, e.pi, label, shortN); - if (animate) this.animateChipFromSeat(chip, e.pi, finalX, finalY, idx); - this.aiBetObjs.push(chip); - }); - } else { - const z = this.zones[key]; - if (!z) continue; - entries.forEach((e, idx) => { - const { x: finalX, y: finalY } = this.chipSidePos(z, key, idx, n, e.pi); - const label = `$${e.bet.amount}`; - const shortN = this.gs.players[e.pi] - ? (this.gs.players[e.pi].name.length > 6 ? this.gs.players[e.pi].name.slice(0, 5) + '…' : this.gs.players[e.pi].name) - : ''; - const chip = this.drawAiChip(finalX, finalY, e.pi, label, shortN); - if (animate) this.animateChipFromSeat(chip, e.pi, finalX, finalY, idx); - this.aiBetObjs.push(chip); - }); - } + const z = ZONES[h.key]; + const lines = [{ text: HELP[z.type] ?? '' }]; + if (h.key === 'odds') { + const lb = this.humanLineBet(); + if (lb) { + const room = maxOddsFor(lb, gs) - lb.oddsAmount; + const win = lb.type === BET.PASS ? trueOddsWin(this.selectedChip, gs.point) : layOddsWin(this.selectedChip, gs.point); + lines.push({ text: `Your ${betName(lb)}: room for ${money(room)} more odds · a ${money(this.selectedChip)} chip wins ${money(win)}`, color: '#d9b45a' }); + } else lines.push({ text: 'Make a Pass or Don\'t Pass bet first; odds open once a point is set.', color: '#c9c2b0' }); + return { title: 'Odds', lines }; } - } - - animateChipFromSeat(chip, pi, finalX, finalY, betIdx) { - const delay = (pi - 1) * 90 + betIdx * 35; - chip.setPosition(SEAT_X[pi] ?? CX, SEAT_Y).setAlpha(0).setScale(0.4); - if (betIdx === 0) this.time.delayedCall(delay, () => playChipBet(this)); - this.tweens.add({ - targets: chip, x: finalX, y: finalY, - alpha: 1, scaleX: 1, scaleY: 1, - duration: 400, ease: 'Quad.Out', delay, - }); - } - - updateBalances() { - const human = this.gs.players[0]; - this.balanceText.setText(`Balance $${human.chips.toLocaleString()}`); - } - - // ── Human betting ────────────────────────────────────────────────────────-- - bettingEnabled() { - return !!this.gs && !this.animating && this.gs.phase !== 'gameover'; - } - - onZoneClick(key) { - if (!this.bettingEnabled()) return; - const z = this.zones[key]; - if (!legalBetTypes(this.gs).has(z.type)) { - this.setStatus(this.notAvailableMsg(z.type)); - return; - } - const amt = this.selectedChip; - if (amt > this.gs.players[0].chips) { this.setStatus('Not enough chips for that bet.'); return; } - const before = this.gs.players[0].chips; - this.gs = placeBet(this.gs, 0, { type: z.type, number: z.number, amount: amt }); - if (this.gs.players[0].chips === before) return; // placement rejected - playChipBet(this); - this.renderHumanBets(); - this.updateBalances(); - this.refreshControls(); + const pays = paysLabel(z.type, z.number); + const edge = houseEdge(z.type, z.number); + lines.push({ text: `Pays ${pays}${edge != null ? ` · house edge ${edge}%` : ''}`, color: '#f5d020' }); + const win = this.winPreview(z.type, z.number, this.selectedChip); + if (win != null) lines.push({ text: `A ${money(this.selectedChip)} chip wins ${money(win)}`, color: '#9be07a' }); + if (!legalBetTypes(gs).has(z.type)) lines.push({ text: this.notAvailableMsg(z.type), color: '#ff9a8a' }); + return { title: z.name, lines }; } notAvailableMsg(type) { - if (type === BET.PASS || type === BET.DONT_PASS) return 'Pass / Don\'t Pass only on the come-out.'; - if (type === BET.COME || type === BET.DONT_COME) return 'Come bets only after a point is set.'; + if (type === BET.PASS || type === BET.DONT_PASS) return "Pass / Don't Pass are made on the come-out roll."; + if (type === BET.COME || type === BET.DONT_COME) return 'Come bets open once a point is set.'; return 'That bet is not available right now.'; } - onClear() { - if (!this.bettingEnabled() || this.gs.point !== null) return; - this.gs = refundBets(this.gs, 0); - this.renderHumanBets(); - this.updateBalances(); + // Hover outline, illegal-zone dimming and learner hints. + drawFeltHighlights() { + const g = this.feltHi; + g.clear(); + if (!this.gs || this.phase !== 'bet') return; + const legal = legalBetTypes(this.gs); + const polyOf = (r) => rectOutline(r); + const fill = (key, color, alpha) => { + for (const r of ZONES[key].rects) { g.fillStyle(color, alpha); g.fillPoints(polyOf(r), true); } + }; + const stroke = (key, color, alpha, w) => { + for (const r of ZONES[key].rects) { g.lineStyle(w, color, alpha); g.strokePoints(polyOf(r), true); } + }; + for (const z of Object.values(ZONES)) { + if (z.key === 'odds') continue; + if (!legal.has(z.type)) fill(z.key, 0x000000, 0.28); + } + const hk = this.hoverZoneKey(this.hover); + if (hk && this.zoneActionable(hk)) { + fill(hk, 0xf5d020, 0.12); + stroke(hk, 0xf5d020, 0.95, 3); + } + } + + onFeltDown(p) { + if (!this.gs) return; + let h = this.pick(p.worldX, p.worldY); + this.dragStart = null; + const right = p.rightButtonDown() || p.event?.shiftKey; + if (this.phase !== 'bet' || !h) return; + if (h.kind === 'die') { + if (this.chosen.length === 2 && this.chosen.includes(h.index)) { + this.dragStart = { x: p.worldX, y: p.worldY, t: this.time.now }; + return; + } + this.pickDie(h.index); + return; + } + if (h.kind === 'stack' && h.pi !== 0) { + if (!h.zoneKey) return; + h = { kind: 'zone', key: h.zoneKey }; + } + if (right) { this.takeDown(h); return; } + if (h.kind === 'lammer') { this.toggleWorking(h.betId); return; } + if (h.kind === 'stack') { + const n = oddsNumber(h.bet, this.gs); + if (n != null) this.addHumanOdds(h.bet.id, this.selectedChip); + else this.addHumanBet(h.bet.type, h.bet.number); + return; + } + if (h.kind === 'zone') { + if (h.key === 'odds') { + const lb = this.humanLineBet(); + if (lb) this.addHumanOdds(lb.id, this.selectedChip); + else this.flashStatus("Make a Pass or Don't Pass bet first — odds open once a point is set."); + return; + } + const z = ZONES[h.key]; + this.addHumanBet(z.type, z.number); + } + } + + onFeltUp(p) { + const s = this.dragStart; + this.dragStart = null; + if (!s || this.phase !== 'bet') return; + const dx = p.worldX - s.x, dy = p.worldY - s.y; + if (Math.hypot(dx, dy) > 36) this.onRoll(); + } + + // ── Human betting ────────────────────────────────────────────────────────── + canAct() { return this.phase === 'bet' && !!this.gs; } + + addHumanBet(type, number = null, amount = this.selectedChip, { quiet = false, from = null } = {}) { + if (!this.canAct()) return false; + const gs = this.gs; + const human = gs.players[0]; + if (!NUMBERED[type]) number = null; + if (!isLegalBet(gs, type, number)) { + if (!quiet) this.flashStatus(this.notAvailableMsg(type)); + return false; + } + const existing = human.bets.find((b) => b.type === type && (b.number ?? null) === (number ?? null) && b.comePoint == null); + const room = TABLE_MAX - (existing?.amount ?? 0); + const amt = Math.min(amount, room, human.chips); + if (amt <= 0) { + if (!quiet) this.flashStatus(room <= 0 ? `Table maximum is ${money(TABLE_MAX)} per bet.` : 'Not enough chips.'); + return false; + } + const before = gs; + this.gs = placeBet(gs, 0, { type, number, amount: amt }); + if (this.gs === before) return false; + const bet = this.gs.players[0].bets.find((b) => b.type === type && (b.number ?? null) === (number ?? null) && b.comePoint == null); + this.undo.push({ betId: bet.id, part: 'flat', amount: amt }); + this.afterHumanBet(bet, 'flat', amt, from); + return true; + } + + addHumanOdds(betId, amount) { + if (!this.canAct()) return false; + const room = oddsRoom(this.gs, 0, betId); + if (room <= 0) { this.flashStatus('Odds are at the maximum for that bet.'); return false; } + const before = this.gs.players[0].bets.find((b) => b.id === betId).oddsAmount; + this.gs = addOdds(this.gs, 0, betId, amount); + const bet = this.gs.players[0].bets.find((b) => b.id === betId); + const added = bet.oddsAmount - before; + if (added <= 0) return false; + this.undo.push({ betId, part: 'odds', amount: added }); + this.afterHumanBet(bet, 'odds', added); + return true; + } + + afterHumanBet(bet, part, amount, from = null) { + const want = this.layoutBets().get(`0:${bet.id}:${part}`); + const btn = this.dock.chipButton(this.selectedChip); + const src = from ?? (btn ? { x: btn.img.x, y: btn.img.y } : this.dock.sourcePos()); + const denom = CHIP_AMOUNTS.includes(amount) ? amount : [100, 50, 25, 5, 1].find((d) => d <= amount) ?? 1; + if (want) { + throwChip(this, denom, src, { x: want.x, y: want.y, s: want.s }, { + size: STACK.human, depth: D.flying, sound: () => playChipBet(this), + }).then(() => { if (this.alive()) this.renderBets(); }); + } + this.dock.hidePrompts(); + this.renderRail(0); + this.updatePlates(); + this.refreshControls(); + this.nudgeAiTimer(); + if (this.hover) this.refreshHover(); + } + + takeDown(h) { + const gs = this.gs; + let bet = null, part = 'flat'; + if (h.kind === 'stack' && h.pi === 0) { bet = h.bet; part = h.part; } + else if (h.kind === 'zone') { + const z = ZONES[h.key]; + if (h.key === 'odds') { bet = this.humanLineBet(); part = 'odds'; } + else bet = gs.players[0].bets.find((b) => b.type === z.type && (b.number ?? null) === (z.number ?? null) && b.comePoint == null); + } + if (!bet) return; + if (part === 'flat' && isContract(bet, gs)) { this.flashStatus('That is a contract bet — it stays up until it wins or loses.'); return; } + const key = `0:${bet.id}:${part}`; + const st = this.stackObjs.get(key); + const next = reduceBet(gs, 0, bet.id, { part }); + if (next === gs) return; + this.gs = next; + this.undo = this.undo.filter((u) => u.betId !== bet.id || (part === 'odds' && u.part === 'flat')); + if (st) { + this.stackObjs.delete(key); + const dst = this.railSource(0); + this.tweens.add({ targets: st, x: dst.x, y: dst.y, scale: 0.6, alpha: 0, duration: 380, ease: 'Cubic.easeIn', onComplete: () => st.destroy() }); + } + playSound(this, SFX.CHIP_BET); + this.renderBets(); + this.renderRail(0); + this.updatePlates(); + this.refreshControls(); + this.setHover(null); + } + + toggleWorking(betId) { + const b = this.gs.players[0].bets.find((x) => x.id === betId); + if (!b) return; + this.gs = setWorking(this.gs, 0, betId, !isWorking(b, this.gs)); + playSound(this, SFX.PIECE_CLICK); + this.renderLammers(); + if (this.hover) this.refreshHover(); + } + + onUndo() { + if (!this.canAct() || !this.undo.length) return; + const u = this.undo.pop(); + const next = reduceBet(this.gs, 0, u.betId, { part: u.part, amount: u.amount }); + if (next === this.gs) return; + this.gs = next; + playSound(this, SFX.CHIP_BET); + this.renderBets(); + this.renderRail(0); + this.updatePlates(); this.refreshControls(); } - onTakeOdds() { - if (!this.bettingEnabled() || this.gs.point === null) return; - const eligible = oddsEligibleBets(this.gs.players[0], this.gs); - if (eligible.length === 0) { this.setStatus('No line bet to back with odds.'); return; } - const target = eligible.find((b) => b.type === BET.PASS || b.type === BET.DONT_PASS) ?? eligible[0]; - const before = this.gs.players[0].chips; - this.gs = addOdds(this.gs, 0, target.id, this.selectedChip); - if (this.gs.players[0].chips === before) { this.setStatus('Odds maxed out (3× the line).'); return; } - playChipBet(this); - this.renderHumanBets(); - this.updateBalances(); + onClear() { + if (!this.canAct() || !this.undo.length) return; + while (this.undo.length) { + const u = this.undo.pop(); + this.gs = reduceBet(this.gs, 0, u.betId, { part: u.part, amount: u.amount }); + } + playSound(this, SFX.CHIP_BET); + this.renderBets(); + this.renderRail(0); + this.updatePlates(); this.refreshControls(); } + // Bets you had at the last roll that are gone now (and legal again). + rebetPlan() { + const gs = this.gs; + if (!gs) return []; + const human = gs.players[0]; + const out = []; + for (const s of this.lastSnapshot) { + const have = human.bets.find((b) => b.type === s.type && (b.number ?? null) === (s.number ?? null) && b.comePoint == null); + const missing = s.amount - (have?.amount ?? 0); + if (missing > 0 && isLegalBet(gs, s.type, s.number)) out.push({ ...s, amount: missing }); + } + return out; + } + + onRebet() { + if (!this.canAct()) return; + let placed = 0; + for (const s of this.rebetPlan()) { + if (s.amount > this.gs.players[0].chips) break; + if (this.addHumanBet(s.type, s.number, s.amount, { quiet: true })) placed++; + } + if (!placed) this.flashStatus('Nothing to rebet.'); + } + + onAcross(inside) { + if (!this.canAct()) return; + const nums = inside ? [5, 6, 8, 9] : POINT_NUMBERS; + const unit = Math.max(5, Math.round(this.selectedChip / 5) * 5); + let placed = 0; + for (const n of nums) { + if (this.gs.players[0].bets.some((b) => b.type === BET.PLACE && b.number === n)) continue; + const amt = n === 6 || n === 8 ? (unit / 5) * 6 : unit; + if (amt > this.gs.players[0].chips) break; + if (this.addHumanBet(BET.PLACE, n, amt, { quiet: true })) placed++; + } + if (!placed) this.flashStatus(inside ? 'Already covering the inside numbers.' : 'Already covering every number.'); + } + + onMaxOdds() { + if (!this.canAct()) return; + let added = 0; + for (const b of oddsEligibleBets(this.gs.players[0], this.gs)) { + const room = oddsRoom(this.gs, 0, b.id); + if (room > 0 && this.addHumanOdds(b.id, room)) added++; + } + if (!added) this.flashStatus('No odds to add — take a line or come bet first.'); + } + refreshControls() { - const canBet = this.bettingEnabled(); - this.shootBtn.setEnabled(canBet); - this.clearBtn.setEnabled(canBet && this.gs.point === null && this.gs.players[0].bets.length > 0); - const eligible = canBet && this.gs.point !== null && oddsEligibleBets(this.gs.players[0], this.gs).length > 0; - this.oddsBtn.setEnabled(eligible); - this.drawZones(); + if (!this.gs) return; + const betting = this.canAct(); + const human = this.gs.players[0]; + this.undoBtn.setEnabled(betting && this.undo.length > 0); + this.clearBtn.setEnabled(betting && this.undo.length > 0); + const rb = betting ? this.rebetPlan() : []; + const rbTotal = rb.reduce((a, s) => a + s.amount, 0); + this.rebetBtn.setEnabled(rb.length > 0 && rbTotal <= human.chips); + this.rebetBtn.setLabel(rb.length ? `Rebet ${money(rbTotal)}` : 'Rebet'); + this.acrossBtn.setEnabled(betting && human.chips >= 5); + this.insideBtn.setEnabled(betting && human.chips >= 5); + const oddsOk = betting && oddsEligibleBets(human, this.gs).some((b) => oddsRoom(this.gs, 0, b.id) > 0); + this.oddsBtn.setEnabled(oddsOk); + this.dock.setChipStates((amt) => amt <= human.chips); + if (this.gs.shooterIndex === 0) { + this.rollBtn.setLabel(this.chosen.length === 2 ? 'Roll Dice' : 'Pick 2 Dice'); + this.rollBtn.setEnabled(betting); + } else { + this.rollBtn.setEnabled(betting); + } + this.drawFeltHighlights(); + } + + flashStatus(msg) { + this.say(msg, '#ffcf9a', 1800); + } + + // ── Stickman / banners ───────────────────────────────────────────────────── + say(text, color = '#f7ecd0', hold = 2600) { + this.callObj?.destroy(); + const c = this.add.container(CALL.x, CALL.y).setDepth(D.badges).setAlpha(0); + const t = this.add.text(0, 0, text, { + fontFamily: '"Julius Sans One"', fontSize: '22px', color, + }).setOrigin(0.5); + if (t.width > CALL.maxW - 56) t.setScale((CALL.maxW - 56) / t.width); + const w = Math.min(CALL.maxW, t.width * t.scaleX + 56); + const bg = this.add.graphics(); + bg.fillStyle(0x0b0806, 0.86); + bg.fillRoundedRect(-w / 2, -22, w, 44, 22); + bg.lineStyle(2, COLORS.accent, 0.8); + bg.strokeRoundedRect(-w / 2, -22, w, 44, 22); + c.add([bg, t]); + this.callObj = c; + this.tweens.add({ targets: c, alpha: 1, duration: 180 }); + this.tweens.add({ + targets: c, alpha: 0, delay: hold, duration: 400, + onComplete: () => { if (this.callObj === c) this.callObj = null; c.destroy(); }, + }); + } + + popTotal(total, hard) { + const [a, b] = this.dice.map((d) => d.screenCenter()); + const x = (a.x + b.x) / 2, y = Math.min(a.y, b.y) - 48; + const t = this.add.text(x, y, String(total), { + fontFamily: 'Righteous, "Julius Sans One"', fontSize: '64px', color: total === 7 ? '#ff6a5a' : '#ffe27a', + stroke: '#000000', strokeThickness: 7, + }).setOrigin(0.5).setDepth(D.badges).setScale(0.4).setAlpha(0); + const objs = [t]; + if (hard && HARD_NUMBERS.includes(total)) { + objs.push(this.add.text(x, y + 42, 'HARD WAY', { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#ffffff', fontStyle: 'bold', + stroke: '#a01010', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.badges).setAlpha(0)); + } + this.tweens.add({ targets: objs, alpha: 1, scale: 1, duration: 260, ease: 'Back.easeOut' }); + this.tweens.add({ + targets: objs, alpha: 0, y: '-=26', delay: 1500, duration: 420, onComplete: () => objs.forEach((o) => o.destroy()), + }); + } + + floatText(x, y, label, color, size = 24) { + const t = this.add.text(x, y, label, { + fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, fontStyle: 'bold', + stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.badges); + this.tweens.add({ targets: t, y: y - 40, alpha: 0, duration: 1300, ease: 'Quad.easeOut', onComplete: () => t.destroy() }); } // ── Round flow ───────────────────────────────────────────────────────────── - beginComeOut() { - this.gs = clearLastDeltas(this.gs); - this.aiBet(false); - this.setStatus(this.gs.shooterIndex === 0 - ? 'Come-out roll — place your bets, then Shoot.' - : `Come-out roll — ${this.gs.players[this.gs.shooterIndex].name} is shooting. Place your bets.`); - this.renderHumanBets(); - this.renderAiWagers(); - this.updateBalances(); - this.refreshControls(); - } + startBetting() { + if (!this.alive() || this.phase === 'over') return; + this.phase = 'bet'; + this.undo = []; + this.dock.setMode('bet'); + this.selectChip(this.selectedChip); + this.aiBets(); + this.renderBets(); + this.showPressButtons(); + this.drawBoard(); + if (this.card?.filled) this.card.title.setText('LAST ROLL'); - aiBet(pointPhase) { - for (let i = 1; i < this.gs.players.length; i++) { - const specs = chooseBets(this.gs.players[i], this.gs); - for (const spec of specs) this.gs = placeBet(this.gs, i, spec); - if (pointPhase) { - for (const o of chooseOdds(this.gs.players[i], this.gs)) this.gs = addOdds(this.gs, i, o.betId, o.amount); - } + if (this.gs.shooterIndex === 0) { + this.clearAiTimer(); + if (this.needsPick) this.offerFive(); + else this.returnDiceToHuman(); + } else { + this.hideOffer(); + this.startAiTimer(); } - this.renderAiWagers(); - this.renderAiBets(true); + this.refreshControls(); + this.updatePlates(); + this.startIdlePrompt(); } - onShoot() { - if (!this.bettingEnabled()) return; - this.animating = true; + // The "pick a chip…" nudge (pulsing chips + banner) is a hint too, so it only + // runs with Hints on. + startIdlePrompt() { + if (!this.hints || this.phase !== 'bet' || this.gs.players[0].bets.length) return; + this.dock.startPrompts(() => (this.gs.point === null + ? 'Pick a chip, then click PASS LINE (or any bet) on the felt' + : 'Point is on — try Come, Place 6 / 8, or Odds behind your line'), () => this.undo.length === 0); + } + + aiBets() { + for (let pi = 1; pi < this.gs.players.length; pi++) { + const p = this.gs.players[pi]; + for (const spec of chooseBets(p, this.gs)) { + const have = this.gs.players[pi].bets.find((b) => b.type === spec.type && (b.number ?? null) === (spec.number ?? null) && b.comePoint == null); + if ((have?.amount ?? 0) + spec.amount > TABLE_MAX) continue; + this.gs = placeBet(this.gs, pi, spec); + } + if (this.gs.point !== null) { + for (const o of chooseOdds(this.gs.players[pi], this.gs)) this.gs = addOdds(this.gs, pi, o.betId, o.amount); + } + this.renderRail(pi); + } + this.time.delayedCall(120, () => playChipBet(this)); + } + + startAiTimer() { + this.clearAiTimer(); + this.aiDeadline = this.game.loop.time + AI_WAIT_MS; + this.aiTimer = this.time.addEvent({ delay: 200, loop: true, callback: () => { + if (this.phase === 'bet' && this.game.loop.time >= this.aiDeadline) this.onRoll(); + } }); + const name = this.gs.players[this.gs.shooterIndex].name; + this.say(`${name} has the dice — place your bets`, '#f7ecd0', 2200); + } + + nudgeAiTimer() { + if (this.aiTimer) this.aiDeadline = Math.max(this.aiDeadline, this.game.loop.time + AI_NUDGE_MS); + } + + clearAiTimer() { + this.aiTimer?.remove(); + this.aiTimer = null; + } + + onRollButton() { + if (!this.canAct()) return; + if (this.gs.shooterIndex === 0 && this.chosen.length < 2) { + this.autoPick(); + return; + } + this.onRoll(); + } + + // Stickman pushes five dice to a new human shooter. + offerFive() { + this.chosen = []; + this.dice.forEach((d) => d.setVisible(false)); + this.offerDice.forEach((d, i) => { + const spot = offerSpot(i); + const q = restingQ(1 + Math.floor(Math.random() * 6), Math.random() * 6); + d.glow = 0; + d.setVisible(true).set(BOWL.u - 0.02 * i, 0.04, TUB.H, q); + const prox = { t: 0 }; + this.tweens.add({ + targets: prox, t: 1, duration: 520, delay: i * 60, ease: 'Cubic.easeOut', + onUpdate: () => d.set( + Phaser.Math.Linear(BOWL.u - 0.02 * i, spot.u, prox.t), + Phaser.Math.Linear(0.04, spot.v, prox.t), + TUB.H * (1 - prox.t) + Math.sin(prox.t * Math.PI) * 30, + q, + ), + }); + }); + this.say('New shooter — pick two dice', '#f7ecd0', 2400); + } + + autoPick() { + const order = [1, 3, 0, 2, 4].filter((i) => !this.chosen.includes(i)); + while (this.chosen.length < 2) this.pickDie(order.shift(), { quiet: true }); + } + + pickDie(i, { quiet = false } = {}) { + if (this.chosen.includes(i)) { + this.chosen = this.chosen.filter((x) => x !== i); + const d = this.offerDice[i]; + d.glow = 0; + d.set(d.state.u, d.state.v, 0, d.state.q); + this.refreshControls(); + return; + } + if (this.chosen.length >= 2) return; + this.chosen.push(i); + const d = this.offerDice[i]; + d.glow = 0.9; + d.set(d.state.u, d.state.v, 5, d.state.q); + if (!quiet) playSound(this, SFX.PIECE_CLICK); + if (this.chosen.length === 2) { + // the other three go back to the bowl + this.offerDice.forEach((od, k) => { + if (this.chosen.includes(k)) return; + const from = { ...od.state }; + const prox = { t: 0 }; + this.tweens.add({ + targets: prox, t: 1, duration: 420, ease: 'Cubic.easeIn', + onUpdate: () => od.set( + Phaser.Math.Linear(from.u, BOWL.u, prox.t), Phaser.Math.Linear(from.v, 0.04, prox.t), + TUB.H * prox.t, from.q, + ), + onComplete: () => od.setVisible(false), + }); + }); + this.needsPick = false; + if (!quiet) this.say('Shooter\'s ready — roll when you are (Space, Roll, or flick the dice)', '#f7ecd0', 2600); + } this.refreshControls(); - this.setStatus('Rolling…'); - this.gs = clearLastDeltas(this.gs); - this.gs = rollDice(this.gs); - const finalDice = [...this.gs.dice]; - this.animateThrow(finalDice).then(() => { - const res = resolveRoll(this.gs); - this.gs = res.state; - this.handleResolution(res); + } + + hideOffer() { + this.offerDice.forEach((d) => { d.glow = 0; d.setVisible(false); }); + } + + // After a roll, the stickman sends your two dice back. + returnDiceToHuman() { + this.chosen = [1, 3]; + this.offerDice.forEach((d) => d.setVisible(false)); + this.dice.forEach((d, i) => { + const spot = offerSpot(i ? 3 : 1); + const od = this.offerDice[i ? 3 : 1]; + const from = { ...d.state }; + if (!d.visible) { od.setVisible(true).set(spot.u, spot.v, 0, from.q); return; } + const prox = { t: 0 }; + this.tweens.add({ + targets: prox, t: 1, duration: 500, ease: 'Cubic.easeInOut', + onUpdate: () => d.set(Phaser.Math.Linear(from.u, spot.u, prox.t), Phaser.Math.Linear(from.v, spot.v, prox.t), 0, from.q), + onComplete: () => { + d.setVisible(false); + od.glow = 0; + od.setVisible(true).set(spot.u, spot.v, 0, from.q); + }, + }); }); } - handleResolution(res) { - const total = res.total; + async onRoll() { + if (!this.canAct()) return; + if (this.gs.shooterIndex === 0 && this.chosen.length < 2) { this.autoPick(); } + this.clearAiTimer(); + this.phase = 'rolling'; + this.setHover(null); + this.clearPressButtons(); + this.dock.setMode('wait', 'Dice are out — no more bets'); + this.drawFeltHighlights(); + this.lastSnapshot = this.gs.players[0].bets + .filter((b) => b.comePoint == null && !(b.type === BET.PASS && this.gs.point !== null)) + .map((b) => ({ type: b.type, number: b.number, amount: b.amount })); - // Move puck for point changes. - if (res.pointEstablished) this.movePuck(res.pointEstablished); - else if (res.newComeOut) this.movePuck(null); - - // Chip animations fire immediately for all players. - for (let i = 0; i < this.gs.players.length; i++) { - const delta = this.gs.players[i].lastDelta; - if (delta > 0) this.animateChips(i, true, delta); - else if (delta < 0) this.animateChips(i, false, -delta); + const shooter = this.gs.shooterIndex; + let origin; + if (shooter === 0) { + const a = this.offerDice[this.chosen[0]].state, b = this.offerDice[this.chosen[1]].state; + origin = { u: (a.u + b.u) / 2, v: (a.v + b.v) / 2, h: 40 }; + this.hideOffer(); + } else { + const o = throwOrigin(this.seatOf[shooter]); + origin = { ...o }; + this.say(`${this.gs.players[shooter].name} is rolling…`, '#f7ecd0', 1400); } - this.setStatus(this.outcomeMessage(res, total)); - this.renderHumanBets(); - this.renderAiWagers(); - this.renderAiBets(); - this.updateBalances(); + + const prevPoint = this.gs.point; + this.clearRollFx(); + this.gs = clearLastDeltas(rollDice(this.gs)); + const unmoved = new Set(this.gs.players[0].bets.filter((b) => (b.type === BET.COME || b.type === BET.DONT_COME) && b.comePoint == null).map((b) => b.id)); + this.resultCardRolling(); + const faces = [...this.gs.dice]; + await this.throwDice(origin, faces); + if (!this.alive()) return; + + const outcomes = this.zoneOutcomes(this.gs); + const res = resolveRoll(this.gs); + this.gs = res.state; + this.showRollFx(outcomes, res); + this.fillResultCard(res, prevPoint, faces, unmoved); + this.history.push({ + total: res.total, hard: res.hard, sevenOut: res.sevenOut, pointMade: res.pointMade, + pointEstablished: res.pointEstablished, + }); + this.popTotal(res.total, res.hard); + const call = stickCall(res, prevPoint); + this.say(call, res.sevenOut ? '#ff9a8a' : res.pointMade ? '#ffe27a' : '#f7ecd0', 2600); + if (res.pointEstablished || res.newComeOut) this.movePuck(this.gs.point); + this.drawBoard(); + + this.phase = 'settle'; + await this.settle(res); + if (!this.alive()) return; this.persistChips(); + this.reactions(res); - // Win/lose badges + emotions play sequentially left to right. - this.showRollResults(); - - this.time.delayedCall(1400, () => { - this.animating = false; - this.diceGfx.forEach((g) => g.setVisible(true)); // leave dice resting on the felt - - if (this.checkGameOver()) return; - - if (res.sevenOut) { - this.updateShooterIndicator(); - this.beginComeOut(); - } else if (res.pointMade) { - this.beginComeOut(); - } else if (res.pointEstablished) { - this.aiBet(true); // opponents back the point once - this.setStatus(`Point is ${res.pointEstablished}. Add bets or Shoot.`); - this.renderAiWagers(); - this.updateBalances(); - this.refreshControls(); - } else { - // No-decision roll during the point. - this.setStatus(`Point is ${this.gs.point}. Add bets or Shoot.`); - this.refreshControls(); - } - }); - } - - outcomeMessage(res, total) { if (res.sevenOut) { - const next = this.gs.players[this.gs.shooterIndex].name; - return `Seven out! Dice pass to ${next}.`; + this.updateShooter(); + this.needsPick = this.gs.shooterIndex === 0; + const nxt = this.gs.players[this.gs.shooterIndex]; + await this.wait(500); + this.say(`New shooter: ${this.gs.shooterIndex === 0 ? 'you!' : nxt.name}`, '#f7ecd0', 2000); + if (this.gs.shooterIndex !== 0) this.dice.forEach((d) => this.slideDiceTo(d, this.shooterOrigin())); + } else if (this.gs.shooterIndex !== 0) { + this.dice.forEach((d, i) => this.slideDiceTo(d, this.shooterOrigin(), i)); } - if (res.pointMade) return `${total} — Point made! Pass line wins.`; - if (res.pointEstablished) return `Point is ${res.pointEstablished}.`; - if (this.gs.point === null) { - if (total === 7 || total === 11) return `${total} — a natural! Pass wins.`; - if (total === 2 || total === 3 || total === 12) return `${total} — craps.`; - } - return `Rolled ${total}.`; + if (this.checkGameOver()) return; + await this.wait(350); + this.startBetting(); } - // ── Win / lose result badges (sequential left → right) ──────────────────── - showRollResults() { - const entries = this.gs.players - .map((p, i) => ({ i, delta: p.lastDelta })) - .filter(e => e.delta !== 0) - .sort((a, b) => SEAT_X[a.i] - SEAT_X[b.i]); - - entries.forEach(({ i, delta }, idx) => { - this.time.delayedCall(idx * 420, () => { - this.portraits[i]?.playEmotion?.(delta > 0 ? 'happy' : 'upset'); - this.animatePlayerResult(i, delta); - }); + slideDiceTo(d, o, i = 0) { + const from = { ...d.state }; + const tu = o.u + (i ? 0.035 : -0.035), tv = o.v; + const prox = { t: 0 }; + this.tweens.add({ + targets: prox, t: 1, duration: 600, delay: 400, ease: 'Cubic.easeInOut', + onUpdate: () => d.set(Phaser.Math.Linear(from.u, tu, prox.t), Phaser.Math.Linear(from.v, tv, prox.t), 0, from.q), }); } - animatePlayerResult(pi, delta) { - const isWin = delta > 0; - const x = SEAT_X[pi]; - const textY = SEAT_Y - PORTRAIT_R - 58; - - const badge = this.add.text(x, textY, isWin ? 'Win!' : 'Lose', { - fontFamily: '"Julius Sans One"', - fontSize: isWin ? '52px' : '44px', - color: isWin ? '#f5d020' : '#e05c5c', - fontStyle: 'bold', - stroke: '#000000', strokeThickness: 5, - shadow: isWin ? { offsetX: 0, offsetY: 0, color: '#f5d020', blur: 24, fill: true } : undefined, - }).setOrigin(0.5).setAlpha(0).setScale(1.4).setDepth(D.modal); - - this.tweens.add({ targets: badge, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.Out' }); - - playSound(this, isWin ? SFX.CASINO_WIN : SFX.CASINO_LOSE); - if (isWin) this.animateFireworks(x, textY); - - this.time.delayedCall(isWin ? 1200 : 900, () => { - this.tweens.add({ - targets: badge, alpha: 0, y: textY - 30, - duration: 350, ease: 'Power2', - onComplete: () => badge.destroy(), - }); + throwDice(origin, faces) { + const plan = simulateThrow(origin, faces); + this.dice.forEach((d) => { d.glow = 0; d.setVisible(true); }); + playSound(this, SFX.DICE_ROLL); + if (this.speed === 'instant') { + this.dice.forEach((d, i) => { const p = poseFromPlan(plan, i, 1); d.set(p.u, p.v, p.h, p.q); }); + return this.wait(150); + } + const prox = { t: 0 }; + return this.tweenP({ + targets: prox, t: 1, duration: plan.duration * 1000, ease: 'Linear', + onUpdate: () => this.dice.forEach((d, i) => { const p = poseFromPlan(plan, i, prox.t); d.set(p.u, p.v, p.h, p.q); }), }); } - animateFireworks(cx, cy) { - const palette = [0xf5d020, 0xff8c00, 0x5cb85c, 0x4a90d9, 0xff69b4, 0xffffff, 0x00e5ff]; - for (let burst = 0; burst < 3; burst++) { - this.time.delayedCall(burst * 380, () => { - if (!this.scene.isActive('CrapsGame')) return; - const bx = cx + (Math.random() - 0.5) * 140; - const by = cy - 10 + (Math.random() - 0.5) * 80; - for (let i = 0; i < 10; i++) { - const angle = (i / 10) * Math.PI * 2 + Math.random() * 0.3; - const dist = 65 + Math.random() * 65; - const color = palette[Math.floor(Math.random() * palette.length)]; - const dot = this.add.graphics().setDepth(D.modal + 5); - dot.fillStyle(color, 1); - dot.fillCircle(0, 0, 4 + Math.random() * 3); - dot.x = bx; dot.y = by; - this.tweens.add({ - targets: dot, - x: bx + Math.cos(angle) * dist, - y: by + Math.sin(angle) * dist, - alpha: 0, scaleX: 0.1, scaleY: 0.1, - duration: 700 + Math.random() * 400, - delay: Math.random() * 100, - ease: 'Power2', - onComplete: () => dot.destroy(), - }); - } + // ── Settlement choreography ──────────────────────────────────────────────── + takeStack(key) { + const st = this.stackObjs.get(key); + if (st) this.stackObjs.delete(key); + return st; + } + + async settle(res) { + const bank = bankPose(); + const sweep = (st, delay) => st && this.tweens.add({ + targets: st, x: bank.x + (Math.random() - 0.5) * 120, y: bank.y, scale: 0.6, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 520, delay, ease: 'Cubic.easeInOut', + onComplete: () => st.destroy(), + }); + const toRail = (objs, pi, delay = 0) => { + const dst = this.railSource(pi); + return this.tweenP({ + targets: objs, x: dst.x, y: dst.y, scale: 0.55, alpha: { value: 0, ease: 'Expo.easeIn' }, + duration: 520, delay, ease: 'Cubic.easeIn', + }).then(() => objs.forEach((o) => o.destroy())); + }; + + this.lastWins = res.payouts + .filter((p) => p.playerIndex === 0 && p.kept && [BET.PLACE, BET.BUY, BET.HARD, BET.BIG].includes(p.betType)) + .map((p) => p.betId); + const losers = res.payouts.filter((p) => p.result === 'lose'); + const pushes = res.payouts.filter((p) => p.result === 'push'); + const winners = res.payouts.filter((p) => p.result === 'win'); + + // 1. take the losers + if (losers.length) { + losers.forEach((p, i) => { + sweep(this.takeStack(`${p.playerIndex}:${p.betId}:flat`), i * 25); + const odds = this.takeStack(`${p.playerIndex}:${p.betId}:odds`); + if (p.refund > 0 && odds) toRail([odds], p.playerIndex, 200); + else sweep(odds, i * 25); }); + playSound(this, SFX.CHIP_BET); + await this.wait(560); + } + // 2. pushes go home + if (pushes.length) { + await Promise.all(pushes.map((p) => { + const objs = [this.takeStack(`${p.playerIndex}:${p.betId}:flat`), this.takeStack(`${p.playerIndex}:${p.betId}:odds`)].filter(Boolean); + return objs.length ? toRail(objs, p.playerIndex) : null; + })); + } + // 3. pay the winners + if (winners.length) { + const human = winners.filter((p) => p.playerIndex === 0); + await Promise.all(winners.map((p, i) => this.payWinner(p, i * 70, bank, toRail))); + const humanWin = human.reduce((a, p) => a + p.delta, 0); + if (humanWin > 0) playSound(this, SFX.CASINO_WIN); + } + // 4. come bets travel to their numbers; everything else re-syncs + if (res.moves.length) playSound(this, SFX.CHIP_BET); + this.renderBets(); + await this.wait(res.moves.length ? 460 : 60); + this.renderAllRails(); + const net = this.gs.players[0].lastDelta; + if (net !== 0) { + const b = this.dock.balanceTxt; + this.floatText(b.x + 80, b.y - 36, `${net > 0 ? '+' : '−'}${money(Math.abs(net))}`, net > 0 ? '#9be07a' : '#ff8a7a', 26); + if (net < 0 && !winners.some((p) => p.playerIndex === 0)) playSound(this, SFX.CASINO_LOSE); } } - // ── Chip win/loss animation (aggregated per player) ───────────────────────── - animateChips(playerIndex, toPlayer, amount) { - const seatX = SEAT_X[playerIndex]; - const count = Math.min(7, Math.max(2, Math.ceil(amount / 50))); - for (let i = 0; i < count; i++) { - const chip = this.add.graphics().setDepth(D.fx); - const color = toPlayer ? CHIP_COLORS[25] : CHIP_COLORS[100]; - chip.fillStyle(color, 1); chip.fillCircle(0, 0, 13); - chip.lineStyle(2, 0xffffff, 0.4); chip.strokeCircle(0, 0, 13); - const fromX = toPlayer ? LAND.x : seatX; - const fromY = toPlayer ? LAND.y : SEAT_Y; - const toX = toPlayer ? seatX : LAND.x; - const toY = toPlayer ? SEAT_Y : LAND.y; - chip.setPosition(fromX + (Math.random() * 40 - 20), fromY + (Math.random() * 20 - 10)); - this.tweens.add({ - targets: chip, x: toX + (Math.random() * 30 - 15), y: toY + (Math.random() * 20 - 10), - duration: 420 + i * 45, ease: 'Quad.InOut', onComplete: () => chip.destroy(), - }); + async payWinner(p, delay, bank, toRail) { + const flatKey = `${p.playerIndex}:${p.betId}:flat`; + const base = p.kept ? this.stackObjs.get(flatKey) : this.takeStack(flatKey); + const odds = p.kept ? null : this.takeStack(`${p.playerIndex}:${p.betId}:odds`); + const ref = base ?? odds; + if (!ref) return; + const size = ref.chipSize ?? 40; + const human = p.playerIndex === 0; + const gross = p.winnings; + let pay = makeChipStack(this, bank.x, bank.y, gross, { size, depth: D.flying, seed: gross + 3, label: human, maxChips: 12 }); + pay.setScale(0.75).setAlpha(0); + const px = ref.x + size * 1.05, py = ref.y + 2; + await this.tweenP({ targets: pay, x: px, y: py, scale: 1, alpha: 1, duration: 460, delay, ease: 'Cubic.easeOut' }); + playChipBet(this); + if (human) this.floatText(px, py - size, `+${money(p.winnings - p.commission)}`, '#9be07a', 20); + if (p.commission > 0) { + await this.wait(300); + pay.destroy(); + pay = makeChipStack(this, px, py, gross - p.commission, { size, depth: D.flying, seed: gross + 5, label: human, maxChips: 12 }); + const cut = makeChipStack(this, px, py - 4, p.commission, { size: size * 0.85, depth: D.flying + 1, label: false }); + const t = this.add.text(px, py - size * 0.9, '−5% vig', { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#ff8a80', fontStyle: 'bold', stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.badges); + this.tweens.add({ targets: t, y: t.y - 28, alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 1100, onComplete: () => t.destroy() }); + await this.tweenP({ targets: cut, x: bank.x, y: bank.y, scale: 0.6, alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 520 }); + cut.destroy(); } - if (toPlayer) this.floatText(seatX, SEAT_Y - PORTRAIT_R - 40, `+$${amount}`, '#5cb85c'); - else this.floatText(seatX, SEAT_Y - PORTRAIT_R - 40, `-$${amount}`, '#e05c5c'); + await this.wait(380); + const objs = [pay]; + if (!p.kept) { if (base) objs.push(base); if (odds) objs.push(odds); } + await toRail(objs, p.playerIndex); } - floatText(x, y, label, color) { - const t = this.add.text(x, y, label, { - fontFamily: '"Julius Sans One"', fontSize: '26px', color, fontStyle: 'bold', + reactions(res) { + const rows = this.gs.players.map((p, pi) => ({ pi, d: p.lastDelta })).filter((r) => r.pi > 0 && r.d !== 0); + rows.forEach(({ pi, d }, i) => { + this.time.delayedCall(i * 180, () => { + this.portraits[pi]?.playEmotion?.(d > 0 ? 'happy' : 'upset'); + const pt = seatPortrait(this.seatOf[pi]); + this.floatText(pt.x, pt.y - pt.r - 8, `${d > 0 ? '+' : '−'}${money(Math.abs(d))}`, d > 0 ? '#9be07a' : '#ff8a7a', 18); + }); + }); + if (res.pointMade) this.time.delayedCall(200, () => playSound(this, SFX.CASINO_WIN)); + } + + // "Press" offers on your Place / Buy / Hard / Big bets that just won. + showPressButtons() { + this.clearPressButtons(); + const last = this.lastWins ?? []; + for (const id of last) { + const b = this.gs.players[0].bets.find((x) => x.id === id); + const st = this.stackObjs.get(`0:${id}:flat`); + if (!b || !st) continue; + const add = b.type === BET.PLACE && (b.number === 6 || b.number === 8) ? Math.ceil(b.amount / 6) * 6 : b.amount; + if (add > this.gs.players[0].chips || b.amount + add > TABLE_MAX) continue; + const btn = new Button(this, st.x, st.y + 26, `PRESS +${money(add)}`, () => { + if (this.addHumanBet(b.type, b.number, add, { quiet: true })) { btn.destroy(); this.pressBtns = this.pressBtns.filter((x) => x !== btn); } + }, { width: 104, height: 26, fontSize: 12, variant: 'ghost' }).setDepth(D.badges); + btn.betId = id; + this.pressBtns.push(btn); + } + } + + clearPressButtons() { + this.pressBtns.forEach((b) => b.destroy()); + this.pressBtns = []; + } + + + // ── Results card (lower right) ──────────────────────────────────────────── + buildResultCard() { + const { x, y, w, h } = RESULT; + ensureLeatherPanel(this, 'craps-result', w, h, { radius: 16 }); + this.add.image(x, y, 'craps-result').setOrigin(0, 0).setDepth(D.ui).setAlpha(0.96); + const title = this.add.text(x + 16, y + 18, 'THIS ROLL', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#d9b45a', + }).setOrigin(0, 0.5).setDepth(D.ui + 2); + const sub = this.add.text(x + w - 16, y + 18, '', { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#c9c2b0', + }).setOrigin(1, 0.5).setDepth(D.ui + 2); + this.card = { title, sub, objs: [], filled: false }; + this.cardMessage('Place a bet and roll —\nyour results show up here.'); + } + + clearCardBody() { + for (const o of this.card.objs) { this.tweens.killTweensOf(o); o.destroy(); } + this.card.objs = []; + } + + cardMessage(text) { + this.clearCardBody(); + const { x, y, w, h } = RESULT; + const t = this.add.text(x + w / 2, y + h / 2, text, { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#c9c2b0', align: 'center', lineSpacing: 6, + }).setOrigin(0.5).setDepth(D.ui + 2); + this.card.objs.push(t); + } + + resultCardRolling() { + this.card.title.setText('THIS ROLL'); + this.card.sub.setText(''); + this.card.filled = false; + this.cardMessage('Dice are out…'); + } + + drawDieIcon(g, cx, cy, size, face) { + const r = size * 0.18; + g.fillStyle(0x000000, 0.35); g.fillRoundedRect(cx - size / 2 + 2, cy - size / 2 + 3, size, size, r); + g.fillStyle(0xc41f2a, 1); g.fillRoundedRect(cx - size / 2, cy - size / 2, size, size, r); + g.lineStyle(1.5, 0x7a0d14, 1); g.strokeRoundedRect(cx - size / 2, cy - size / 2, size, size, r); + const PIP = { 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]] }; + g.fillStyle(0xfdf6e6, 1); + for (const [a, b] of PIP[face]) g.fillCircle(cx + a * size * 0.27, cy + b * size * 0.27, size * 0.09); + } + + // What the roll did to *your* bets, and why. + fillResultCard(res, prevPoint, dice, unmoved) { + const card = this.card; + this.clearCardBody(); + card.filled = true; + card.title.setText('THIS ROLL'); + const { x, y, w, h } = RESULT; + const add = (o) => { card.objs.push(o); return o; }; + const human = this.gs.players[0]; + + // dice + total + the call + const g = add(this.add.graphics().setDepth(D.ui + 2)); + this.drawDieIcon(g, x + 34, y + 62, 34, dice[0]); + this.drawDieIcon(g, x + 76, y + 62, 34, dice[1]); + add(this.add.text(x + 106, y + 62, String(res.total), { + fontFamily: 'Righteous, "Julius Sans One"', fontSize: '44px', color: res.total === 7 ? '#ff6a5a' : '#ffe27a', stroke: '#000000', strokeThickness: 4, - }).setOrigin(0.5).setDepth(D.fx + 1); - this.tweens.add({ targets: t, y: y - 36, alpha: 0, duration: 1200, ease: 'Quad.Out', onComplete: () => t.destroy() }); + }).setOrigin(0, 0.5).setDepth(D.ui + 2)); + const what = res.sevenOut ? 'SEVEN-OUT' : res.pointMade ? `POINT ${res.total} MADE` + : res.pointEstablished ? `POINT IS ${res.total}` : prevPoint === null && [7, 11].includes(res.total) ? 'NATURAL' + : prevPoint === null && [2, 3, 12].includes(res.total) ? 'CRAPS' : res.hard && HARD_NUMBERS.includes(res.total) ? `HARD ${res.total}` : ''; + add(this.add.text(x + 166, y + 50, what, { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: res.sevenOut ? '#ff9a8a' : '#f7ecd0', fontStyle: 'bold', + }).setOrigin(0, 0.5).setDepth(D.ui + 2)); + add(this.add.text(x + 166, y + 72, prevPoint === null ? 'come-out roll' : `point was ${prevPoint}`, { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#c9c2b0', + }).setOrigin(0, 0.5).setDepth(D.ui + 2)); + card.sub.setText(`Roll ${this.history.length}`); + const rule = add(this.add.graphics().setDepth(D.ui + 2)); + rule.lineStyle(1, 0xd9b45a, 0.45); + rule.lineBetween(x + 14, y + 96, x + w - 14, y + 96); + + // one row per decision on your bets (biggest first), then come bets that moved + const rows = res.payouts + .filter((p) => p.playerIndex === 0) + .sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || b.amount - a.amount) + .map((p) => ({ + kind: p.result, + name: betLabel(p.betType, p.number), + why: explainPayout(p, { dice, prevPoint, unmoved: unmoved.has(p.betId) }), + amt: p.delta, + })); + for (const m of res.moves.filter((m) => m.playerIndex === 0)) { + rows.push({ kind: 'move', name: betLabel(m.type), why: explainMove(m), amt: null }); + } + const top = y + 108, bottom = y + h - 62; + let ry = top, shown = 0; + rows.forEach((r, i) => { + if (ry + 40 > bottom) return; + const color = r.kind === 'win' ? '#9be07a' : r.kind === 'lose' ? '#ff8a7a' : '#9ad4ff'; + const icon = r.kind === 'win' ? '✓' : r.kind === 'lose' ? '✗' : r.kind === 'move' ? '→' : '='; + const objs = [ + this.add.text(x + 20, ry + 10, icon, { fontFamily: '"Julius Sans One"', fontSize: '18px', color, fontStyle: 'bold' }).setOrigin(0.5), + this.add.text(x + 38, ry + 10, r.name, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#f7ecd0', fontStyle: 'bold' }).setOrigin(0, 0.5), + this.add.text(x + w - 16, ry + 10, r.amt == null ? '' : `${r.amt > 0 ? '+' : r.amt < 0 ? '−' : ''}${money(Math.abs(r.amt))}`, { + fontFamily: '"Julius Sans One"', fontSize: '15px', color, fontStyle: 'bold', + }).setOrigin(1, 0.5), + this.add.text(x + 38, ry + 28, r.why, { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#c9c2b0', wordWrap: { width: w - 56 }, + }).setOrigin(0, 0.5), + ]; + const why = objs[3]; + if (why.height > 18) why.setFontSize(11); + objs.forEach((o) => { o.setDepth(D.ui + 2).setAlpha(0); add(o); }); + this.tweens.add({ targets: objs, alpha: 1, duration: 220, delay: 120 + i * 110 }); + ry += 42; + shown++; + }); + if (shown < rows.length) { + add(this.add.text(x + w / 2, ry + 6, `+ ${rows.length - shown} more`, { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#c9c2b0', + }).setOrigin(0.5, 0).setDepth(D.ui + 2)); + } + if (!rows.length) { + const working = human.bets.length; + add(this.add.text(x + w / 2, top + 40, working + ? `No decision on your bets.\n${working} bet${working > 1 ? 's' : ''} still working (${money(totalAtRisk(human))}).` + : 'You had no bets on this roll.', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#c9c2b0', align: 'center', lineSpacing: 6, + }).setOrigin(0.5, 0).setDepth(D.ui + 2)); + } + + // net for the roll, counting up, and the bankroll + const net = human.lastDelta; + const rule2 = add(this.add.graphics().setDepth(D.ui + 2)); + rule2.lineStyle(1, 0xd9b45a, 0.45); + rule2.lineBetween(x + 14, y + h - 56, x + w - 14, y + h - 56); + add(this.add.text(x + 16, y + h - 30, 'NET', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#d9b45a', + }).setOrigin(0, 0.5).setDepth(D.ui + 2)); + const netTxt = add(this.add.text(x + 62, y + h - 30, '', { + fontFamily: 'Righteous, "Julius Sans One"', fontSize: '28px', + color: net > 0 ? '#9be07a' : net < 0 ? '#ff8a7a' : '#f7ecd0', stroke: '#000000', strokeThickness: 3, + }).setOrigin(0, 0.5).setDepth(D.ui + 2)); + const fmt = (v) => (net === 0 && rows.length === 0 ? '—' : `${v > 0 ? '+' : v < 0 ? '−' : ''}${money(Math.abs(v))}`); + const counter = { v: 0 }; + netTxt.setText(fmt(0)); + this.tweens.add({ + targets: counter, v: net, duration: 700, delay: 150 + Math.min(rows.length, 6) * 110, ease: 'Cubic.easeOut', + onUpdate: () => netTxt.setText(fmt(Math.round(counter.v))), + onComplete: () => netTxt.setText(fmt(net)), + }); + add(this.add.text(x + w - 16, y + h - 30, `Bankroll ${money(human.chips)}`, { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#c9c2b0', + }).setOrigin(1, 0.5).setDepth(D.ui + 2)); } - setStatus(msg) { this.statusText.setText(msg); } + // ── Keyboard ─────────────────────────────────────────────────────────────── + onKey(e) { + if (!this.gs || this.phase !== 'bet') return; + const k = (e.key ?? '').toLowerCase(); + if (k === ' ' || k === 'enter') { e.preventDefault?.(); this.onRoll(); } + else if (['1', '2', '3', '4', '5'].includes(k)) this.selectChip(CHIP_AMOUNTS[Number(k) - 1]); + else if (k === 'z' || k === 'backspace') this.onUndo(); + else if (k === 'r') this.onRebet(); + else if (k === 'o') this.onMaxOdds(); + else if (k === 'c' || k === 'escape') this.onClear(); + else if (k === 'h') this.toggleHints(); + } - // ── Persistence & game over ───────────────────────────────────────────────── + // ── Persistence & game over ──────────────────────────────────────────────── async loadChips() { try { const { profile } = await api.get('/profile'); - this.startingChips = profile?.chips ?? 2000; - } catch { this.startingChips = 2000; } + return profile?.chips ?? 2000; + } catch { return 2000; } } async persistChips() { @@ -1056,8 +1879,9 @@ export default class CrapsGame extends Phaser.Scene { checkGameOver() { const human = this.gs.players[0]; if (human.chips > 0 || totalAtRisk(human) > 0) return false; - this.gs.phase = 'gameover'; - this.refreshControls(); + this.phase = 'over'; + this.clearAiTimer(); + this.dock.setMode('wait', 'Out of chips'); this.postHistory(); new Modal(this, 'Out of chips! Visit your profile to request a reset.', { autoCloseMs: 4200 }); this.time.delayedCall(4400, () => this.scene.start('GameMenu')); @@ -1066,25 +1890,24 @@ export default class CrapsGame extends Phaser.Scene { async postHistory() { const human = this.gs.players[0]; - const result = getNetResult(human, this.startingChips); try { await api.post('/history/single-player', { slug: 'craps', - score: human.chips, - opponentScores: this.gs.players.slice(1).map((p) => p.chips), - result, + score: human.chips + totalAtRisk(human), + opponentScores: this.gs.players.slice(1).map((p) => p.chips + totalAtRisk(p)), + result: getNetResult(human, this.startingChips), }); } catch { /* ignore */ } } leave() { - if (this.gs && this.gs.phase !== 'gameover') { - // Only resolved deltas are ever posted to the server, so refunding the - // un-resolved stakes locally makes the bankroll match the server balance - // (no extra post needed). postHistory then records the true final equity. - this.gs = refundBets(this.gs, 0); + if (this.gs && this.phase !== 'over') { + // Only resolved deltas are ever posted to the server, so returning every + // un-resolved stake locally makes the bankroll match the server balance. + this.gs = refundBets(this.gs, 0, { force: true }); this.postHistory(); } this.scene.start('GameMenu'); } } + diff --git a/src/games/craps/CrapsLogic.js b/src/games/craps/CrapsLogic.js index f2eb8a9..a563d75 100644 --- a/src/games/craps/CrapsLogic.js +++ b/src/games/craps/CrapsLogic.js @@ -1,28 +1,64 @@ -// Pure Craps rules. No Phaser dependency. +// Pure Craps rules. No Phaser dependency (verify scripts import this under Node). // -// Scope: Pass Line, Don't Pass (bar 12), Field, Place (4·5·6·8·9·10), -// Come / Don't Come, and free Odds behind Pass/Don't and Come/Don't Come. +// Bets: +// Line Pass / Don't Pass (bar 12), Come / Don't Come, with free odds +// behind them (3-4-5× on the right side, 6× flat-equivalent laid) +// Numbers Place (4·5·6·8·9·10), Buy (true odds, 5% vig on wins), +// Lay (true odds against, 5% of the win), Big 6 / Big 8 +// Hardways Hard 4·6·8·10 (off on the come-out unless called on) +// One-roll Field (2 double, 12 triple), Any 7, Any Craps, Yo-11, Aces, +// Ace-Deuce, Boxcars, C&E, Horn // -// A "round" is one shooter sequence. The shooter rolls a come-out; if a point -// is set the game enters the point phase and the shooter keeps rolling until -// the point repeats (pass wins) or a 7 shows (seven-out → shooter rotates). +// A "round" is one shooter sequence: a come-out roll, then (if a point is set) +// rolls until the point repeats (pass wins) or a 7 shows (seven-out → the dice +// move to the next player). // // State is treated as immutable: every mutating helper returns a fresh object. export const POINT_NUMBERS = [4, 5, 6, 8, 9, 10]; +export const HARD_NUMBERS = [4, 6, 8, 10]; -// Bet types and where they live on the layout. export const BET = { PASS: 'pass', DONT_PASS: 'dontpass', - FIELD: 'field', - PLACE: 'place', COME: 'come', DONT_COME: 'dontcome', + FIELD: 'field', + PLACE: 'place', + BUY: 'buy', + LAY: 'lay', + BIG: 'big', // number 6 or 8 + HARD: 'hard', // number 4, 6, 8 or 10 + ANY7: 'any7', + ANY_CRAPS: 'anycraps', + YO: 'yo', + ACES: 'aces', + ACE_DEUCE: 'acedeuce', + BOXCARS: 'boxcars', + CE: 'ce', + HORN: 'horn', }; +// Bets that carry a number (and which numbers are valid). +export const NUMBERED = { + [BET.PLACE]: POINT_NUMBERS, + [BET.BUY]: POINT_NUMBERS, + [BET.LAY]: POINT_NUMBERS, + [BET.BIG]: [6, 8], + [BET.HARD]: HARD_NUMBERS, +}; + +export const ONE_ROLL = new Set([ + BET.FIELD, BET.ANY7, BET.ANY_CRAPS, BET.YO, BET.ACES, BET.ACE_DEUCE, BET.BOXCARS, BET.CE, BET.HORN, +]); + +// Bets that are "off" on the come-out roll unless the player calls them on. +const OFF_ON_COMEOUT = new Set([BET.PLACE, BET.BUY, BET.HARD]); + // Chip denominations offered in the UI. -export const CHIP_AMOUNTS = [5, 25, 50, 100]; +export const CHIP_AMOUNTS = [1, 5, 25, 50, 100]; + +export const VIG = 0.05; // ─── Setup ─────────────────────────────────────────────────────────────────── @@ -41,10 +77,11 @@ export function createInitialState(opponents = [], humanChips = 2000, humanName return { players, shooterIndex: 0, - phase: 'betting', // betting → comeout → point → (betting | gameover) + phase: 'comeout', // comeout | point | gameover point: null, dice: [1, 1], rollCount: 0, + shooterRolls: 0, // rolls by the current shooter (resets on seven-out) _nextBetId: 1, }; } @@ -53,89 +90,184 @@ export function cloneState(state) { return JSON.parse(JSON.stringify(state)); } -// ─── Bet placement ─────────────────────────────────────────────────────────-- +// ─── Queries ───────────────────────────────────────────────────────────────── -// Which base bet types may be opened right now. +// Which bet types may be opened right now. export function legalBetTypes(state) { - const out = new Set([BET.FIELD, BET.PLACE]); + const out = new Set(Object.values(BET)); if (state.point === null) { - out.add(BET.PASS); - out.add(BET.DONT_PASS); + out.delete(BET.COME); + out.delete(BET.DONT_COME); } else { - out.add(BET.COME); - out.add(BET.DONT_COME); + out.delete(BET.PASS); + out.delete(BET.DONT_PASS); } return out; } +export function isLegalBet(state, type, number = null) { + if (!legalBetTypes(state).has(type)) return false; + if (NUMBERED[type]) return NUMBERED[type].includes(number); + return number == null; +} + +// The number a line/come bet's odds are tied to (null until established). +export function oddsNumber(bet, state) { + if (bet.type === BET.PASS || bet.type === BET.DONT_PASS) return state.point; + if (bet.type === BET.COME || bet.type === BET.DONT_COME) return bet.comePoint ?? null; + return null; +} + // A line/come bet that can still receive odds (point/come-point established). export function oddsEligibleBets(player, state) { - return player.bets.filter((b) => { - if (b.type === BET.PASS || b.type === BET.DONT_PASS) return state.point !== null; - if (b.type === BET.COME || b.type === BET.DONT_COME) return b.comePoint != null; - return false; - }); + return player.bets.filter((b) => oddsNumber(b, state) != null); } -export function maxOddsFor(bet) { - // Keep it simple: allow up to 3× the flat bet behind the line. - return bet.amount * 3; +// 3-4-5× odds behind the line; laid odds capped so the win is at most 6× the flat. +export function oddsMultiple(number) { + if (number === 4 || number === 10) return 3; + if (number === 5 || number === 9) return 4; + if (number === 6 || number === 8) return 5; + return 0; } -// Place a flat bet. Stake is removed from the player's bankroll immediately. +export function maxOddsFor(bet, state) { + const n = oddsNumber(bet, state); + if (n == null) return 0; + const dont = bet.type === BET.DONT_PASS || bet.type === BET.DONT_COME; + return dont ? bet.amount * 6 : bet.amount * oddsMultiple(n); +} + +// Is this bet live for the next roll? +export function isWorking(bet, state) { + if (state.point === null && OFF_ON_COMEOUT.has(bet.type)) return !!bet.onComeOut; + return true; +} + +// Contract bets may not be taken down: Pass once a point is set, and a Come bet +// once it has travelled to its number. +export function isContract(bet, state) { + if (bet.type === BET.PASS) return state.point !== null; + if (bet.type === BET.COME) return bet.comePoint != null; + return false; +} + +export function canToggleWorking(bet, state) { + return state.point === null && OFF_ON_COMEOUT.has(bet.type); +} + +// ─── Bet placement ─────────────────────────────────────────────────────────── + +function findMatch(bets, type, number) { + return bets.find((b) => b.type === type && (b.number ?? null) === (number ?? null) && b.comePoint == null); +} + +// Place (or add to) a flat bet. The stake leaves the bankroll immediately. +// Returns the same state object when the placement is rejected. export function placeBet(state, playerIndex, { type, number = null, amount }) { const player = state.players[playerIndex]; - if (amount <= 0 || amount > player.chips) return state; - if (!legalBetTypes(state).has(type)) return state; - if (type === BET.PLACE && !POINT_NUMBERS.includes(number)) return state; + amount = Math.floor(amount); + if (!(amount > 0) || amount > player.chips) return state; + if (!NUMBERED[type]) number = null; + if (!isLegalBet(state, type, number)) return state; const s = cloneState(state); const p = s.players[playerIndex]; - - // Stack onto an existing matching flat bet rather than duplicating it. - const existing = p.bets.find((b) => - b.type === type && - (type === BET.PLACE ? b.number === number : b.comePoint == null && b.number == null)); - if (existing && type !== BET.COME && type !== BET.DONT_COME) { + const existing = findMatch(p.bets, type, number); + if (existing) { existing.amount += amount; } else { p.bets.push({ id: s._nextBetId++, type, - number: type === BET.PLACE ? number : null, + number, comePoint: null, amount, oddsAmount: 0, - // Place bets sit "off" during a come-out; everything else is working. - working: type === BET.PLACE ? state.point !== null : true, + onComeOut: false, }); } p.chips -= amount; return s; } -// Add odds behind an eligible line/come bet. +// Add odds behind an eligible line/come bet (clamped to the cap and bankroll). export function addOdds(state, playerIndex, betId, amount) { + const bet = state.players[playerIndex].bets.find((b) => b.id === betId); + if (!bet) return state; + const cap = maxOddsFor(bet, state) - bet.oddsAmount; + const add = Math.min(Math.floor(amount), cap, state.players[playerIndex].chips); + if (add <= 0) return state; const s = cloneState(state); const p = s.players[playerIndex]; - const bet = p.bets.find((b) => b.id === betId); - if (!bet) return state; - const cap = maxOddsFor(bet) - bet.oddsAmount; - const add = Math.min(amount, cap, p.chips); - if (add <= 0) return state; - bet.oddsAmount += add; + const b = p.bets.find((x) => x.id === betId); + b.oddsAmount += add; p.chips -= add; return s; } -// Return un-resolved stakes to the bankroll (only sensible during a betting -// window). Used by "Clear" and when leaving the table. -export function refundBets(state, playerIndex, predicate = () => true) { +// Odds that would be added by "max odds" for this bet. +export function oddsRoom(state, playerIndex, betId) { + const p = state.players[playerIndex]; + const bet = p.bets.find((b) => b.id === betId); + if (!bet) return 0; + return Math.max(0, Math.min(maxOddsFor(bet, state) - bet.oddsAmount, p.chips)); +} + +// Take `amount` (default: all) off a bet's flat stake or odds. Contract flats +// can't come down. Removing the whole flat also returns its odds. +export function reduceBet(state, playerIndex, betId, { part = 'flat', amount = Infinity } = {}) { + const bet = state.players[playerIndex].bets.find((b) => b.id === betId); + if (!bet) return state; + if (part === 'odds') { + const take = Math.min(bet.oddsAmount, Math.floor(amount)); + if (take <= 0) return state; + const s = cloneState(state); + const p = s.players[playerIndex]; + p.bets.find((b) => b.id === betId).oddsAmount -= take; + p.chips += take; + return s; + } + if (isContract(bet, state)) return state; + const take = Math.min(bet.amount, Math.floor(amount)); + if (take <= 0) return state; + const s = cloneState(state); + const p = s.players[playerIndex]; + const b = p.bets.find((x) => x.id === betId); + if (take >= b.amount) { + p.chips += b.amount + b.oddsAmount; + p.bets = p.bets.filter((x) => x.id !== betId); + } else { + b.amount -= take; + p.chips += take; + const excess = b.oddsAmount - maxOddsFor(b, s); + if (excess > 0) { b.oddsAmount -= excess; p.chips += excess; } + } + return s; +} + +export function removeBet(state, playerIndex, betId) { + return reduceBet(state, playerIndex, betId, { part: 'flat' }); +} + +// Call a Place / Buy / Hardway bet on (or off) for the come-out roll. +export function setWorking(state, playerIndex, betId, on) { + const bet = state.players[playerIndex].bets.find((b) => b.id === betId); + if (!bet || !canToggleWorking(bet, state)) return state; + const s = cloneState(state); + s.players[playerIndex].bets.find((b) => b.id === betId).onComeOut = !!on; + return s; +} + +// Return every removable stake to the bankroll (Clear, and leaving the table). +// Contract bets stay unless `force` (leaving refunds everything, since only +// resolved deltas are ever posted to the server). +export function refundBets(state, playerIndex, { force = false, predicate = () => true } = {}) { const s = cloneState(state); const p = s.players[playerIndex]; const kept = []; for (const b of p.bets) { - if (predicate(b)) p.chips += b.amount + b.oddsAmount; + if (predicate(b) && (force || !isContract(b, state))) p.chips += b.amount + b.oddsAmount; else kept.push(b); } p.bets = kept; @@ -144,9 +276,9 @@ export function refundBets(state, playerIndex, predicate = () => true) { // ─── Dice ──────────────────────────────────────────────────────────────────── -export function rollDice(state) { +export function rollDice(state, rng = Math.random) { const s = cloneState(state); - s.dice = [1 + Math.floor(Math.random() * 6), 1 + Math.floor(Math.random() * 6)]; + s.dice = [1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)]; s.rollCount += 1; return s; } @@ -158,50 +290,96 @@ export function setDice(state, dice) { return s; } -// ─── Payout tables (return winnings only, not the returned stake) ───────────── +// ─── Payout tables (winnings only, not the returned stake) ─────────────────── -function floor(n) { return Math.floor(n); } +const floor = Math.floor; -function passOddsWin(amount, number) { - if (number === 4 || number === 10) return amount * 2; // 2:1 - if (number === 5 || number === 9) return floor(amount * 3 / 2); // 3:2 - if (number === 6 || number === 8) return floor(amount * 6 / 5); // 6:5 +// True odds for the right side (point → pays X to Y). +export function trueOddsWin(amount, number) { + if (number === 4 || number === 10) return amount * 2; // 2:1 + if (number === 5 || number === 9) return floor((amount * 3) / 2); // 3:2 + if (number === 6 || number === 8) return floor((amount * 6) / 5); // 6:5 return 0; } -function dontOddsWin(amount, number) { - if (number === 4 || number === 10) return floor(amount / 2); // 1:2 - if (number === 5 || number === 9) return floor(amount * 2 / 3); // 2:3 - if (number === 6 || number === 8) return floor(amount * 5 / 6); // 5:6 +// True odds laid against a number. +export function layOddsWin(amount, number) { + if (number === 4 || number === 10) return floor(amount / 2); // 1:2 + if (number === 5 || number === 9) return floor((amount * 2) / 3); // 2:3 + if (number === 6 || number === 8) return floor((amount * 5) / 6); // 5:6 return 0; } -function placeWin(amount, number) { - if (number === 4 || number === 10) return floor(amount * 9 / 5); - if (number === 5 || number === 9) return floor(amount * 7 / 5); - if (number === 6 || number === 8) return floor(amount * 7 / 6); +export function placeWin(amount, number) { + if (number === 4 || number === 10) return floor((amount * 9) / 5); + if (number === 5 || number === 9) return floor((amount * 7) / 5); + if (number === 6 || number === 8) return floor((amount * 7) / 6); return 0; } -function fieldWin(amount, total) { - if (total === 2) return amount * 2; // 2 pays double - if (total === 12) return amount * 3; // 12 pays triple - return amount; // 3,4,9,10,11 pay 1:1 +export function vig(amount) { + return Math.max(1, floor(amount * VIG)); } -// ─── Resolution ────────────────────────────────────────────────────────────-- +// Payout ratios shown on the layout / tooltips. +export const PAYS = { + [BET.PASS]: '1 to 1', [BET.DONT_PASS]: '1 to 1', [BET.COME]: '1 to 1', [BET.DONT_COME]: '1 to 1', + [BET.FIELD]: '1 to 1 · 2 pays 2× · 12 pays 3×', + [BET.BIG]: '1 to 1', + [BET.ANY7]: '4 to 1', [BET.ANY_CRAPS]: '7 to 1', [BET.YO]: '15 to 1', + [BET.ACES]: '30 to 1', [BET.ACE_DEUCE]: '15 to 1', [BET.BOXCARS]: '30 to 1', + [BET.CE]: 'Craps 3 to 1 · 11 pays 7 to 1', [BET.HORN]: '2/12 pay 27 to 4 · 3/11 pay 3 to 1', +}; + +export function paysLabel(type, number) { + if (type === BET.PLACE) return number === 6 || number === 8 ? '7 to 6' : number === 5 || number === 9 ? '7 to 5' : '9 to 5'; + if (type === BET.BUY) return `${number === 6 || number === 8 ? '6 to 5' : number === 5 || number === 9 ? '3 to 2' : '2 to 1'} · 5% vig on wins`; + if (type === BET.LAY) return `${number === 6 || number === 8 ? '5 to 6' : number === 5 || number === 9 ? '2 to 3' : '1 to 2'} · 5% vig on wins`; + if (type === BET.HARD) return number === 4 || number === 10 ? '7 to 1' : '9 to 1'; + return PAYS[type] ?? ''; +} + +// House edge (per bet, as a %) for tooltips — verified exactly in tools/verifyCraps.js. +export function houseEdge(type, number) { + switch (type) { + case BET.PASS: case BET.COME: return 1.41; + case BET.DONT_PASS: case BET.DONT_COME: return 1.4; // per decision (a barred 12 is no action) + case BET.FIELD: return 2.78; + case BET.PLACE: return number === 6 || number === 8 ? 1.52 : number === 5 || number === 9 ? 4.0 : 6.67; + // Buy / Lay quoted at their natural sizes ($20 buys, lays that win $20). + case BET.BUY: return number === 6 || number === 8 ? 2.27 : number === 5 || number === 9 ? 2.0 : 1.67; + case BET.LAY: return number === 6 || number === 8 ? 1.82 : number === 5 || number === 9 ? 2.0 : 1.67; + case BET.BIG: return 9.09; + case BET.HARD: return number === 6 || number === 8 ? 9.09 : 11.11; + case BET.ANY7: return 16.67; + case BET.ANY_CRAPS: case BET.YO: case BET.ACE_DEUCE: case BET.CE: return 11.11; + case BET.ACES: case BET.BOXCARS: return 13.89; + case BET.HORN: return 12.5; + default: return null; + } +} + +// ─── Resolution ────────────────────────────────────────────────────────────── // Resolve every bet against the dice already set on `state`. -// Returns { state, total, payouts, pointEstablished, pointMade, sevenOut, newComeOut }. +// Returns { state, total, hard, payouts, moves, pointEstablished, pointMade, sevenOut, newComeOut }. // -// payouts entry: { playerIndex, betType, number, result, amount, delta } -// result ∈ 'win' | 'lose' | 'push'; delta is the net bankroll change for the bet. +// payouts entry: { playerIndex, betId, betType, number, result, amount, winnings, +// commission, refund, kept, delta } +// result ∈ 'win' | 'lose' | 'push'; amount = stake at risk; delta = net bankroll change. +// kept = the bet stays on the felt after a win (Place, Buy, Lay, Big, Hard). +// moves entry: { playerIndex, betId, type, to } — a Come / Don't Come bet +// travelling to its number. export function resolveRoll(state) { const s = cloneState(state); - const total = s.dice[0] + s.dice[1]; + const [d1, d2] = s.dice; + const total = d1 + d2; + const hard = d1 === d2; const point = s.point; const isComeOut = point === null; const payouts = []; + const moves = []; + const ctx = { total, hard, point, isComeOut, state }; let pointEstablished = null; let pointMade = false; @@ -212,30 +390,42 @@ export function resolveRoll(state) { const kept = []; for (const bet of p.bets) { - const resolved = resolveBet(bet, { total, point, isComeOut }); - if (resolved.result === 'open') { - // Bet survives (possibly mutated, e.g. a come bet that travelled). - kept.push(resolved.bet ?? bet); + const r = resolveBet(bet, ctx); + if (r.result === 'open') { + const nb = r.bet ?? bet; + // A Come / Don't Come bet travelling to its number. (An older come bet on + // that number always resolves on this same roll — "off and on" — and + // placeBet keeps one unmoved come bet per player, so no twins can exist.) + if (nb.comePoint != null && bet.comePoint == null) { + moves.push({ playerIndex: pi, betId: bet.id, type: bet.type, to: nb.comePoint }); + } + kept.push(nb); continue; } - // Credit returned stake + winnings; delta is net of the staked amount. const stake = bet.amount + bet.oddsAmount; + const winnings = r.winnings ?? 0; + const commission = r.commission ?? 0; let credited = 0; - if (resolved.result === 'win') credited = stake + resolved.winnings; - else if (resolved.result === 'push') credited = stake; + if (r.result === 'win') credited = (r.keep ? 0 : stake) + winnings - commission; + else if (r.result === 'push') credited = stake; + else credited = r.refund ?? 0; p.chips += credited; - const delta = credited - stake; + const delta = r.keep ? winnings - commission : credited - stake; p.lastDelta += delta; payouts.push({ playerIndex: pi, + betId: bet.id, betType: bet.type, number: bet.number ?? bet.comePoint ?? null, - result: resolved.result, + result: r.result, amount: stake, + winnings, + commission, + refund: r.result === 'lose' ? (r.refund ?? 0) : 0, + kept: !!r.keep, delta, }); - // A winning Place bet stays up and working; everything else clears. - if (resolved.keep) kept.push(resolved.bet ?? bet); + if (r.keep) kept.push(bet); } p.bets = kept; } @@ -246,10 +436,6 @@ export function resolveRoll(state) { pointEstablished = total; s.point = total; s.phase = 'point'; - // Place bets switch on once a point exists. - for (const p of s.players) for (const b of p.bets) { - if (b.type === BET.PLACE) b.working = true; - } } else { s.phase = 'comeout'; } @@ -257,36 +443,38 @@ export function resolveRoll(state) { pointMade = true; s.point = null; s.phase = 'comeout'; - for (const p of s.players) for (const b of p.bets) { - if (b.type === BET.PLACE) b.working = false; - } } else if (total === 7) { sevenOut = true; s.point = null; s.phase = 'comeout'; - for (const p of s.players) for (const b of p.bets) { - if (b.type === BET.PLACE) b.working = false; - } } + // Called-on flags only last for a come-out. + if (s.point !== null) for (const p of s.players) for (const b of p.bets) b.onComeOut = false; + s.shooterRolls += 1; const newComeOut = pointMade || sevenOut; if (sevenOut) { s.shooterIndex = (s.shooterIndex + 1) % s.players.length; + s.shooterRolls = 0; } - return { state: s, total, payouts, pointEstablished, pointMade, sevenOut, newComeOut }; + return { state: s, total, hard, payouts, moves, pointEstablished, pointMade, sevenOut, newComeOut }; } // Resolve a single bet. Returns one of: -// { result:'open', bet } — unresolved (bet may have mutated) -// { result:'win', winnings, keep } — paid; keep=true leaves it on the felt -// { result:'lose' } | { result:'push' } -function resolveBet(bet, { total, point, isComeOut }) { +// { result:'open', bet? } unresolved (bet may have mutated) +// { result:'win', winnings, commission?, keep? } paid; keep → stays on the felt +// { result:'lose', refund? } refund = odds that were off +// { result:'push' } +function resolveBet(bet, { total, hard, point, isComeOut, state }) { + const n = bet.number; + if (!isWorking(bet, state)) return { result: 'open' }; + switch (bet.type) { case BET.FIELD: { - if ([2, 3, 4, 9, 10, 11, 12].includes(total)) { - return { result: 'win', winnings: fieldWin(bet.amount, total) }; - } + if (total === 2) return { result: 'win', winnings: bet.amount * 2 }; + if (total === 12) return { result: 'win', winnings: bet.amount * 3 }; + if ([3, 4, 9, 10, 11].includes(total)) return { result: 'win', winnings: bet.amount }; return { result: 'lose' }; } @@ -294,12 +482,9 @@ function resolveBet(bet, { total, point, isComeOut }) { if (isComeOut) { if (total === 7 || total === 11) return { result: 'win', winnings: bet.amount }; if (total === 2 || total === 3 || total === 12) return { result: 'lose' }; - return { result: 'open' }; // point established, ride it - } - if (total === point) { - const winnings = bet.amount + passOddsWin(bet.oddsAmount, point); - return { result: 'win', winnings }; + return { result: 'open' }; } + if (total === point) return { result: 'win', winnings: bet.amount + trueOddsWin(bet.oddsAmount, point) }; if (total === 7) return { result: 'lose' }; return { result: 'open' }; } @@ -307,56 +492,98 @@ function resolveBet(bet, { total, point, isComeOut }) { case BET.DONT_PASS: { if (isComeOut) { if (total === 2 || total === 3) return { result: 'win', winnings: bet.amount }; - if (total === 12) return { result: 'push' }; // bar 12 + if (total === 12) return { result: 'open' }; // barred: no action, the bet stands if (total === 7 || total === 11) return { result: 'lose' }; return { result: 'open' }; } - if (total === 7) { - const winnings = bet.amount + dontOddsWin(bet.oddsAmount, point); - return { result: 'win', winnings }; - } + if (total === 7) return { result: 'win', winnings: bet.amount + layOddsWin(bet.oddsAmount, point) }; if (total === point) return { result: 'lose' }; return { result: 'open' }; } - case BET.PLACE: { - if (!bet.working) return { result: 'open' }; - if (total === bet.number) { - return { result: 'win', winnings: placeWin(bet.amount, bet.number), keep: true }; - } - if (total === 7) return { result: 'lose' }; - return { result: 'open' }; - } - case BET.COME: case BET.DONT_COME: { - const isDont = bet.type === BET.DONT_COME; + const dont = bet.type === BET.DONT_COME; if (bet.comePoint == null) { - // This roll is the come bet's own come-out. - if (total === 7 || total === 11) return isDont ? { result: 'lose' } : { result: 'win', winnings: bet.amount }; - if (total === 2 || total === 3) return isDont ? { result: 'win', winnings: bet.amount } : { result: 'lose' }; - if (total === 12) return isDont ? { result: 'push' } : { result: 'lose' }; - // Travels to its number. + if (total === 7 || total === 11) return dont ? { result: 'lose' } : { result: 'win', winnings: bet.amount }; + if (total === 2 || total === 3) return dont ? { result: 'win', winnings: bet.amount } : { result: 'lose' }; + if (total === 12) return dont ? { result: 'open' } : { result: 'lose' }; // barred 12 stands return { result: 'open', bet: { ...bet, comePoint: total } }; } - // Come point established. - if (total === bet.comePoint) { - if (isDont) return { result: 'lose' }; - return { result: 'win', winnings: bet.amount + passOddsWin(bet.oddsAmount, bet.comePoint) }; - } - if (total === 7) { - if (isDont) return { result: 'win', winnings: bet.amount + dontOddsWin(bet.oddsAmount, bet.comePoint) }; - return { result: 'lose' }; + const cp = bet.comePoint; + if (!dont) { + // Come odds are off on the come-out roll: returned, not paid or lost. + const oddsOn = !isComeOut; + if (total === cp) { + return { result: 'win', winnings: bet.amount + (oddsOn ? trueOddsWin(bet.oddsAmount, cp) : 0) }; + } + if (total === 7) return { result: 'lose', refund: oddsOn ? 0 : bet.oddsAmount }; + return { result: 'open' }; } + if (total === 7) return { result: 'win', winnings: bet.amount + layOddsWin(bet.oddsAmount, cp) }; + if (total === cp) return { result: 'lose' }; return { result: 'open' }; } + case BET.PLACE: { + if (total === n) return { result: 'win', winnings: placeWin(bet.amount, n), keep: true }; + if (total === 7) return { result: 'lose' }; + return { result: 'open' }; + } + + case BET.BUY: { + if (total === n) return { result: 'win', winnings: trueOddsWin(bet.amount, n), commission: vig(bet.amount), keep: true }; + if (total === 7) return { result: 'lose' }; + return { result: 'open' }; + } + + case BET.LAY: { + if (total === 7) { + const w = layOddsWin(bet.amount, n); + return { result: 'win', winnings: w, commission: Math.min(w, vig(w)), keep: true }; + } + if (total === n) return { result: 'lose' }; + return { result: 'open' }; + } + + case BET.BIG: { + if (total === n) return { result: 'win', winnings: bet.amount, keep: true }; + if (total === 7) return { result: 'lose' }; + return { result: 'open' }; + } + + case BET.HARD: { + if (total === n && hard) { + return { result: 'win', winnings: bet.amount * (n === 4 || n === 10 ? 7 : 9), keep: true }; + } + if (total === 7 || total === n) return { result: 'lose' }; + return { result: 'open' }; + } + + case BET.ANY7: return total === 7 ? { result: 'win', winnings: bet.amount * 4 } : { result: 'lose' }; + case BET.ANY_CRAPS: + return [2, 3, 12].includes(total) ? { result: 'win', winnings: bet.amount * 7 } : { result: 'lose' }; + case BET.YO: return total === 11 ? { result: 'win', winnings: bet.amount * 15 } : { result: 'lose' }; + case BET.ACES: return total === 2 ? { result: 'win', winnings: bet.amount * 30 } : { result: 'lose' }; + case BET.ACE_DEUCE: return total === 3 ? { result: 'win', winnings: bet.amount * 15 } : { result: 'lose' }; + case BET.BOXCARS: return total === 12 ? { result: 'win', winnings: bet.amount * 30 } : { result: 'lose' }; + case BET.CE: { + if ([2, 3, 12].includes(total)) return { result: 'win', winnings: bet.amount * 3 }; + if (total === 11) return { result: 'win', winnings: bet.amount * 7 }; + return { result: 'lose' }; + } + case BET.HORN: { + if (total === 2 || total === 12) return { result: 'win', winnings: floor((bet.amount * 27) / 4) }; + if (total === 3 || total === 11) return { result: 'win', winnings: bet.amount * 3 }; + return { result: 'lose' }; + } + default: return { result: 'open' }; } } -// ─── Round / table helpers ─────────────────────────────────────────────────-- +// ─── Round / table helpers ─────────────────────────────────────────────────── export function clearLastDeltas(state) { const s = cloneState(state); @@ -374,7 +601,120 @@ export function hasActiveBets(player) { // Human net result vs. the chips they walked in with, for match history. export function getNetResult(player, startingChips) { - if (player.chips > startingChips) return 'win'; - if (player.chips < startingChips) return 'loss'; + const equity = player.chips + totalAtRisk(player); + if (equity > startingChips) return 'win'; + if (equity < startingChips) return 'loss'; return 'draw'; } + +// Stickman's call for a roll (flavour text). +export function stickCall(res, prevPoint) { + const { total, hard } = res; + const easyHard = POINT_NUMBERS.includes(total) && total !== 5 && total !== 9 + ? (hard ? `Hard ${total}!` : `Easy ${total}`) : null; + if (res.sevenOut) return 'Seven out — line away, pay the don\'ts!'; + if (res.pointMade) return `${hard && HARD_NUMBERS.includes(total) ? `Hard ${total}` : total}, winner! Pay the line`; + if (res.pointEstablished) { + const base = total === 6 ? 'Six' : total === 8 ? 'Eight' : total === 9 ? 'Nine' : total === 10 ? 'Ten' : total === 4 ? 'Four' : 'Five'; + return `${easyHard ?? base} — the point is ${total}, mark it!`; + } + if (prevPoint === null) { + if (total === 7) return 'Seven, winner on the pass line!'; + if (total === 11) return 'Yo-leven! Front line winner!'; + if (total === 2) return 'Aces — craps! Line away'; + if (total === 3) return 'Ace-deuce, craps three'; + if (total === 12) return 'Boxcars! Craps — bar the don\'ts'; + } + if (total === 11) return 'Yo-leven!'; + if (total === 2) return 'Aces, snake eyes!'; + if (total === 3) return 'Three craps three'; + if (total === 12) return 'Midnight — boxcars!'; + if (easyHard) return easyHard; + if (total === 5) return 'Five, no field five'; + if (total === 9) return 'Nine, centre field'; + return `${total}`; +} + +// ─── Plain-English results ─────────────────────────────────────────────────── + +const PROP_NAME = { + [BET.FIELD]: 'Field', [BET.ANY7]: 'Any Seven', [BET.ANY_CRAPS]: 'Any Craps', [BET.YO]: 'Yo-Eleven', + [BET.ACES]: 'Aces', [BET.ACE_DEUCE]: 'Ace-Deuce', [BET.BOXCARS]: 'Boxcars', [BET.CE]: 'C & E', [BET.HORN]: 'Horn', +}; + +// Display name for a resolved bet (payout entry) or a live bet. +export function betLabel(type, number = null, comePoint = null) { + switch (type) { + case BET.PASS: return 'Pass Line'; + case BET.DONT_PASS: return "Don't Pass"; + case BET.COME: return comePoint ?? number ? `Come on ${comePoint ?? number}` : 'Come'; + case BET.DONT_COME: return comePoint ?? number ? `Don't Come on ${comePoint ?? number}` : "Don't Come"; + case BET.PLACE: return `Place ${number}`; + case BET.BUY: return `Buy ${number}`; + case BET.LAY: return `Lay ${number}`; + case BET.BIG: return `Big ${number}`; + case BET.HARD: return `Hard ${number}`; + default: return PROP_NAME[type] ?? type; + } +} + +// Why a bet won or lost on this roll. `ctx` = { dice: [a, b], prevPoint, unmoved } +// where unmoved = it was a Come / Don't Come bet still in its own come-out. +export function explainPayout(p, { dice, prevPoint, unmoved = false }) { + const t = dice[0] + dice[1]; + const n = p.number; + const win = p.result === 'win'; + const sevenOut = prevPoint !== null && t === 7; + const seven = sevenOut ? 'Seven-out' : 'A 7 rolled'; + let why; + if (p.result === 'push') why = 'Push — stake returned'; + else switch (p.betType) { + case BET.FIELD: + why = !win ? `${t} isn't a Field number` : t === 2 ? '2 in the Field pays double' : t === 12 ? '12 in the Field pays triple' : `${t} is a Field number`; + break; + case BET.PASS: + if (prevPoint === null) why = win ? `Natural ${t} on the come-out` : `Craps ${t} on the come-out`; + else why = win ? `Point ${prevPoint} made` : 'Seven-out before the point'; + break; + case BET.DONT_PASS: + if (prevPoint === null) why = win ? `Craps ${t} — the Don't wins` : `Natural ${t} beats the Don't`; + else why = win ? 'Seven-out — the Don\'t wins' : `Point ${prevPoint} made`; + break; + case BET.COME: + if (unmoved) why = win ? `Natural ${t} on the Come` : `Craps ${t} on the Come`; + else why = win ? `${n} rolled again` : `${seven} before the ${n}`; + break; + case BET.DONT_COME: + if (unmoved) why = win ? `Craps ${t} — the Don't Come wins` : `Natural ${t} beats the Don't Come`; + else why = win ? `7 before the ${n}` : `The ${n} rolled`; + break; + case BET.PLACE: case BET.BUY: case BET.BIG: + why = win ? `The ${n} rolled` : `${seven} before the ${n}`; + break; + case BET.LAY: + why = win ? `7 before the ${n}` : `The ${n} rolled`; + break; + case BET.HARD: + if (win) why = `Hard ${n} — ${n / 2} and ${n / 2}`; + else why = t === 7 ? seven : `${n} came easy (${dice[0]}-${dice[1]})`; + break; + case BET.ANY7: why = win ? 'Seven!' : `${t} — no seven`; break; + case BET.ANY_CRAPS: why = win ? `Craps ${t}` : `${t} — no 2, 3 or 12`; break; + case BET.YO: why = win ? 'Yo-eleven!' : `${t} — no 11`; break; + case BET.ACES: why = win ? 'Snake eyes!' : `${t} — no 2`; break; + case BET.ACE_DEUCE: why = win ? 'Ace-deuce!' : `${t} — no 3`; break; + case BET.BOXCARS: why = win ? 'Boxcars!' : `${t} — no 12`; break; + case BET.CE: why = !win ? `${t} — no craps or 11` : t === 11 ? '11 pays 7 to 1' : `Craps ${t} pays 3 to 1`; break; + case BET.HORN: why = win ? `${t} on the Horn` : `${t} — no 2, 3, 11 or 12`; break; + default: why = win ? 'Winner' : 'Loser'; + } + const extra = []; + if (win && p.kept) extra.push('stays up'); + if (p.commission > 0) extra.push(`$${p.commission} vig`); + if (p.refund > 0) extra.push('odds returned (off on the come-out)'); + return extra.length ? `${why} · ${extra.join(' · ')}` : why; +} + +export function explainMove(m) { + return m.type === BET.DONT_COME ? `Moves behind the ${m.to}` : `Moves to the ${m.to}`; +} diff --git a/src/games/craps/CrapsTable.js b/src/games/craps/CrapsTable.js new file mode 100644 index 0000000..22d9d2c --- /dev/null +++ b/src/games/craps/CrapsTable.js @@ -0,0 +1,313 @@ +// Craps table geometry — Phaser-free so tools/verifyCraps.js can import it. +// +// One end of a craps tub seen from the near rail, through the shared casino +// perspective camera (makeProjection). Table space: +// u left/right, −1 (the curved end, left) … +1 (the pyramid wall, right) +// v depth, 0 = far wall … 1 = near wall (the player's rail) +// The felt is the rounded rectangle u∈[−1,1], v∈[0,1] sunk TUB.H px below the +// padded rail. Everything lying on the felt goes through P.project(u, v); things +// raised off it (rail, flying dice) through lift(u, v, h). +// +// Left ~60% of the felt is the betting end (number boxes, Come, Field, Don't +// Pass, Pass Line wrapping the end); the centre strip is the proposition box; +// the right end is open felt where the dice land against the pyramid wall. + +import { makeProjection, DOCK } from '../../ui/casino/CasinoGeometry.js'; + +export { DOCK }; + +export const VIEW = { cx: 960, yFar: 172, yNear: 812, sFar: 0.72, halfW: 795, squash: 0.9 }; +export const P = makeProjection(VIEW); + +export const TUB = { + H: 46, // wall height (px at s = 1): the felt sits this far below the rail top + RW: 0.085, // padded rail width (table units) + FACE: 30, // rail's outer face (px at s = 1) + CR: 0.1, // felt corner radius (table units) +}; + +// Raised points are nearer the camera, so they also spread out from the centre +// line a little — that is what makes the side walls and the end rail read as 3D. +export const LIFT_SPREAD = 0.0011; +export function lift(u, v, h) { + const p = P.project(u, v); + return { x: VIEW.cx + (p.x - VIEW.cx) * (1 + h * LIFT_SPREAD), y: p.y - h * p.s, s: p.s }; +} + +// Rounded-rectangle outline of the tub offset `d` outward (table units), clockwise +// from the top-left corner. Returned as table-space points. +export function tubOutline(d = 0, perCorner = 10, perSide = 24) { + const r = TUB.CR + d; + const u0 = -1 - d, u1 = 1 + d, v0 = -d, v1 = 1 + d; + const pts = []; + const corner = (cu, cv, a0) => { + for (let i = 0; i <= perCorner; i++) { + const a = (a0 + (90 * i) / perCorner) * (Math.PI / 180); + pts.push({ u: cu + Math.cos(a) * r, v: cv + Math.sin(a) * r }); + } + }; + const side = (a, b) => { + for (let i = 1; i < perSide; i++) { + const t = i / perSide; + pts.push({ u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t }); + } + }; + corner(u0 + r, v0 + r, 180); // top-left + side({ u: u0 + r, v: v0 }, { u: u1 - r, v: v0 }); + corner(u1 - r, v0 + r, 270); // top-right + side({ u: u1, v: v0 + r }, { u: u1, v: v1 - r }); + corner(u1 - r, v1 - r, 0); // bottom-right + side({ u: u1 - r, v: v1 }, { u: u0 + r, v: v1 }); + corner(u0 + r, v1 - r, 90); // bottom-left + side({ u: u0, v: v1 - r }, { u: u0, v: v0 + r }); + return pts; +} + +export function inTub(u, v, d = 0) { + const r = TUB.CR + d; + if (u < -1 - d || u > 1 + d || v < -d || v > 1 + d) return false; + const cu = Math.max(-1 + TUB.CR, Math.min(1 - TUB.CR, u)); + const cv = Math.max(TUB.CR, Math.min(1 - TUB.CR, v)); + return Math.hypot(u - cu, v - cv) <= r + 1e-9; +} + +// Visible felt ends where the near rail's top edge occludes it. +export const NEAR_VISIBLE_V = (() => { + const y = lift(0, 1, TUB.H).y; + return P.unproject(VIEW.cx, y).v; +})(); + +// ── Layout ─────────────────────────────────────────────────────────────────── +const BOX_U0 = -0.66, BOX_W = 0.16; +export const BOX_NUMS = [4, 5, 6, 8, 9, 10]; +export const ROWS = { + lay: [0.035, 0.09], main: [0.09, 0.28], buy: [0.28, 0.335], + come: [0.355, 0.47], field: [0.49, 0.625], dontpass: [0.645, 0.715], + pass: [0.735, 0.865], odds: [0.875, 0.94], +}; +export const END_U = [-0.86, -0.685]; // Don't Come box + Big 6/8 column +export const LAYOUT_U1 = BOX_U0 + 6 * BOX_W; // 0.30: right edge of the betting end +export const PASS_SIDE = { u0: -0.975, u1: -0.875, v0: 0.05 }; +export const PROP = { u0: 0.345, u1: 0.67, v0: 0.05, v1: 0.79, ceU1: 0.395 }; +// Dice settle in the upper two-thirds of the open end; the lower right is the results card. +export const LANDING = { u0: 0.71, u1: 0.95, v0: 0.08, v1: 0.66 }; +export const WALL_U = 0.985; // dice bounce off the pyramid wall here +export const OFFER = { u0: 0.4, u1: 0.64, v: 0.885 }; // stickman pushes the dice here + +export function boxU(n) { + const i = BOX_NUMS.indexOf(n); + return { u0: BOX_U0 + i * BOX_W, u1: BOX_U0 + (i + 1) * BOX_W }; +} + +const R = (u0, u1, v0, v1) => ({ u0, u1, v0, v1 }); + +// Prop-box cells +const PU0 = PROP.ceU1 + 0.005; +const PW = PROP.u1 - PU0; +const PROP_ROWS = { + any7: [0.05, 0.14], hardA: [0.15, 0.31], hardB: [0.31, 0.47], one: [0.48, 0.6], horn: [0.61, 0.69], craps: [0.7, 0.79], +}; + +// Every clickable zone: key → { type, number, rects, name } +// (types match CrapsLogic BET values). +export const ZONES = {}; +function zone(key, type, number, name, ...rects) { ZONES[key] = { key, type, number, name, rects }; } + +zone('pass', 'pass', null, 'Pass Line', + R(PASS_SIDE.u0, LAYOUT_U1, ROWS.pass[0], ROWS.pass[1]), + R(PASS_SIDE.u0, PASS_SIDE.u1, PASS_SIDE.v0, ROWS.pass[0])); +zone('odds', 'odds', null, 'Odds', R(PASS_SIDE.u1, LAYOUT_U1, ROWS.odds[0], ROWS.odds[1])); +zone('dontpass', 'dontpass', null, "Don't Pass Bar", R(END_U[0], LAYOUT_U1, ROWS.dontpass[0], ROWS.dontpass[1])); +zone('dontcome', 'dontcome', null, "Don't Come Bar", R(END_U[0], END_U[1], ROWS.lay[0], ROWS.buy[1])); +zone('come', 'come', null, 'Come', R(BOX_U0, LAYOUT_U1, ROWS.come[0], ROWS.come[1])); +zone('field', 'field', null, 'Field', R(BOX_U0, LAYOUT_U1, ROWS.field[0], ROWS.field[1])); +zone('big6', 'big', 6, 'Big 6', R(END_U[0], END_U[1], ROWS.come[0], (ROWS.come[0] + ROWS.field[1]) / 2)); +zone('big8', 'big', 8, 'Big 8', R(END_U[0], END_U[1], (ROWS.come[0] + ROWS.field[1]) / 2, ROWS.field[1])); +for (const n of BOX_NUMS) { + const { u0, u1 } = boxU(n); + zone(`lay${n}`, 'lay', n, `Lay ${n}`, R(u0, u1, ROWS.lay[0], ROWS.lay[1])); + zone(`place${n}`, 'place', n, `Place ${n}`, R(u0, u1, ROWS.main[0], ROWS.main[1])); + zone(`buy${n}`, 'buy', n, `Buy ${n}`, R(u0, u1, ROWS.buy[0], ROWS.buy[1])); +} +zone('any7', 'any7', null, 'Any Seven', R(PU0, PROP.u1, ...PROP_ROWS.any7)); +zone('hard6', 'hard', 6, 'Hard 6', R(PU0, PU0 + PW / 2, ...PROP_ROWS.hardA)); +zone('hard10', 'hard', 10, 'Hard 10', R(PU0 + PW / 2, PROP.u1, ...PROP_ROWS.hardA)); +zone('hard8', 'hard', 8, 'Hard 8', R(PU0, PU0 + PW / 2, ...PROP_ROWS.hardB)); +zone('hard4', 'hard', 4, 'Hard 4', R(PU0 + PW / 2, PROP.u1, ...PROP_ROWS.hardB)); +['acedeuce', 'aces', 'boxcars', 'yo'].forEach((k, i) => { + const names = { acedeuce: 'Ace-Deuce', aces: 'Aces', boxcars: 'Boxcars', yo: 'Yo-Eleven' }; + zone(k, k, null, names[k], R(PU0 + (PW * i) / 4, PU0 + (PW * (i + 1)) / 4, ...PROP_ROWS.one)); +}); +zone('horn', 'horn', null, 'Horn', R(PU0, PROP.u1, ...PROP_ROWS.horn)); +zone('anycraps', 'anycraps', null, 'Any Craps', R(PU0, PROP.u1, ...PROP_ROWS.craps)); +zone('ce', 'ce', null, 'C & E', R(PROP.u0, PROP.ceU1, PROP.v0, PROP.v1)); + +export function rectCenter(r) { return { u: (r.u0 + r.u1) / 2, v: (r.v0 + r.v1) / 2 }; } + +export function hitZoneUV(u, v) { + for (const z of Object.values(ZONES)) { + for (const r of z.rects) if (u >= r.u0 && u <= r.u1 && v >= r.v0 && v <= r.v1) return z.key; + } + return null; +} + +export function hitZone(x, y) { + const { u, v } = P.unproject(x, y); + return hitZoneUV(u, v); +} + +// Screen outline of a table-space rect (for highlights). +export function rectOutline(r) { + return [P.project(r.u0, r.v0), P.project(r.u1, r.v0), P.project(r.u1, r.v1), P.project(r.u0, r.v1)]; +} + +export function zoneKeyFor(type, number) { + for (const z of Object.values(ZONES)) if (z.type === type && (z.number ?? null) === (number ?? null)) return z.key; + return null; +} + +// ── Seats ──────────────────────────────────────────────────────────────────── +// Seven places around the rail. The human stands at the near rail; opponents +// fill FILL_ORDER. `slot` is the left-to-right order used for seat-fixed spots +// on the long lanes (Pass, Field, Come, ...), so each player's chips sit +// roughly in front of where they stand. +export const SEATS = { + H: { side: 'near', u: -0.18 }, + N2: { side: 'near', u: -0.56 }, + N1: { side: 'near', u: -0.88 }, + E: { side: 'end', v: 0.42 }, + F3: { side: 'far', u: -0.78 }, + F2: { side: 'far', u: -0.45 }, + F1: { side: 'far', u: -0.12 }, +}; +export const FILL_ORDER = ['N2', 'F2', 'E', 'F1', 'N1', 'F3']; +export const SLOT_ORDER = ['E', 'N1', 'F3', 'N2', 'F2', 'H', 'F1']; + +// Player index → seat name for a table of n opponents. +export function seatNames(nOpp) { + return ['H', ...FILL_ORDER.slice(0, Math.min(6, nOpp))]; +} + +// Table-space point in the middle of the rail's chip groove for a seat. +export function railUV(name, offset = 0) { + const s = SEATS[name]; + const d = TUB.RW * 0.5; + if (s.side === 'near') return { u: s.u + offset, v: 1 + d }; + if (s.side === 'far') return { u: s.u + offset, v: -d }; + return { u: -1 - d, v: s.v + offset }; +} + +// Where a seat's chips sit in the rail (screen, raised to the rail top). +export function railPose(name, offset = 0) { + const { u, v } = railUV(name, offset); + return lift(u, v, TUB.H); +} + +// Portrait placement (screen) — beside the rail, outside the tub. +export function seatPortrait(name) { + const s = SEATS[name]; + if (s.side === 'near') { + const p = lift(s.u, 1 + TUB.RW, TUB.H); + return { x: p.x + 70, y: p.y + TUB.FACE * p.s + 12, r: 32 }; + } + if (s.side === 'far') { + const p = lift(s.u, -TUB.RW, TUB.H); + return { x: p.x, y: p.y - 40, r: 32 }; + } + const p = lift(-1 - TUB.RW, s.v, TUB.H); + return { x: p.x - 48, y: p.y - 8, r: 34 }; +} + +// Where a shooter releases the dice (table space, above the rail). +export function throwOrigin(name) { + const s = SEATS[name]; + if (s.side === 'near') return { u: s.u + 0.05, v: 0.96, h: TUB.H + 30 }; + if (s.side === 'far') return { u: s.u + 0.05, v: 0.04, h: TUB.H + 30 }; + return { u: -0.96, v: s.v, h: TUB.H + 30 }; +} + +// ── Bet spots ──────────────────────────────────────────────────────────────── +// A lane is where stacks for one kind of bet are laid out: +// 'slots' — one fixed spot per seat (long lanes), ordered by SLOT_ORDER +// 'flow' — stacks share a cell, spread left-to-right in seat order +export const LANES = { + pass: { kind: 'slots', u0: PASS_SIDE.u1 + 0.02, u1: LAYOUT_U1 - 0.02, v: 0.81 }, + odds: { kind: 'slots', u0: PASS_SIDE.u1 + 0.02, u1: LAYOUT_U1 - 0.02, v: 0.912 }, + dontpass: { kind: 'slots', u0: END_U[0] + 0.03, u1: LAYOUT_U1 - 0.03, v: 0.695 }, + come: { kind: 'slots', u0: BOX_U0 + 0.03, u1: LAYOUT_U1 - 0.03, v: 0.445 }, + field: { kind: 'slots', u0: BOX_U0 + 0.03, u1: LAYOUT_U1 - 0.03, v: 0.6 }, + ce: { kind: 'vslots', u: (PROP.u0 + PROP.ceU1) / 2, v0: PROP.v0 + 0.05, v1: PROP.v1 - 0.04 }, + dontcome: { kind: 'flow', u0: END_U[0] + 0.02, u1: END_U[1] - 0.02, v: 0.29 }, +}; +for (const n of BOX_NUMS) { + const { u0, u1 } = boxU(n); + LANES[`place${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.195 }; + LANES[`comept${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.255 }; + LANES[`buy${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.318 }; + LANES[`lay${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.07 }; +} +for (const k of ['big6', 'big8', 'hard4', 'hard6', 'hard8', 'hard10', 'any7', 'acedeuce', 'aces', 'boxcars', 'yo', 'horn', 'anycraps']) { + const r = ZONES[k].rects[0]; + LANES[k] = { kind: 'flow', u0: r.u0 + 0.025, u1: r.u1 - 0.025, v: r.v0 + (r.v1 - r.v0) * 0.66 }; +} + +// Lane key for a bet (types match CrapsLogic BET values). +export function laneForBet(bet) { + switch (bet.type) { + case 'pass': return 'pass'; + case 'dontpass': return 'dontpass'; + case 'come': return bet.comePoint == null ? 'come' : `comept${bet.comePoint}`; + case 'dontcome': return bet.comePoint == null ? 'dontcome' : `lay${bet.comePoint}`; + case 'field': return 'field'; + case 'place': return `place${bet.number}`; + case 'buy': return `buy${bet.number}`; + case 'lay': return `lay${bet.number}`; + case 'big': return `big${bet.number}`; + case 'hard': return `hard${bet.number}`; + default: return LANES[bet.type] ? bet.type : null; + } +} + +// Table-space spot for a stack in `lane`: seat-fixed lanes use the seat's slot; +// flow lanes use the stack's index among the `count` stacks sharing the lane. +export function laneSpot(laneKey, { seat = 'H', index = 0, count = 1 } = {}) { + const L = LANES[laneKey]; + const slot = SLOT_ORDER.indexOf(seat); + if (L.kind === 'slots') { + return { u: L.u0 + ((slot + 0.5) / SLOT_ORDER.length) * (L.u1 - L.u0), v: L.v }; + } + if (L.kind === 'vslots') { + return { u: L.u, v: L.v0 + ((slot + 0.5) / SLOT_ORDER.length) * (L.v1 - L.v0) }; + } + const w = L.u1 - L.u0; + const step = count > 1 ? Math.min(0.06, w / (count - 1)) : 0; + return { u: (L.u0 + L.u1) / 2 + (index - (count - 1) / 2) * step, v: L.v }; +} + +// Where odds go for a line / come bet relative to its flat stack (table units). +export function oddsOffset(laneKey) { + if (laneKey === 'pass') return null; // behind the line: the 'odds' lane + return { du: 0.03, dv: -0.012 }; +} + +// ── Furniture ──────────────────────────────────────────────────────────────── +export const BANK = { u0: 0.36, u1: 0.68 }; // house chip rack in the far rail +export function bankPose() { return lift((BANK.u0 + BANK.u1) / 2, -TUB.RW * 0.5, TUB.H); } +export const BOWL = { u: 0.84 }; // stickman's dice bowl (far rail) +export function bowlPose() { return lift(BOWL.u, -TUB.RW * 0.5, TUB.H); } + +export function puckOffUV() { return { u: (END_U[0] + END_U[1]) / 2, v: 0.12 }; } +export function puckOnUV(n) { const { u0, u1 } = boxU(n); return { u: (u0 + u1) / 2, v: 0.125 }; } + +export function offerSpot(i, n = 5) { + return { u: OFFER.u0 + ((i + 0.5) / n) * (OFFER.u1 - OFFER.u0), v: OFFER.v }; +} + +// Roll-history board (screen rect, top-right) and the stickman's call line. +// Below the music widget (buttons + track name fill the top ~76px on the right). +export const BOARD = { x: 1670, y: 88, w: 238, h: 150 }; +export const CALL = { x: 1330, y: 40, maxW: 500 }; +export const STACK = { human: 50, ai: 42 }; // chip-stack diameter at s = 1 + +// "This roll" results card, lower right (over the near corner of the open end). +export const RESULT = { x: 1560, y: 566, w: 348, h: 374 }; diff --git a/tools/verifyCraps.js b/tools/verifyCraps.js new file mode 100644 index 0000000..9b9a27d --- /dev/null +++ b/tools/verifyCraps.js @@ -0,0 +1,598 @@ +#!/usr/bin/env node +// verifyCraps.js — headless checks for Craps: every bet against all 36 dice +// combos, exact house edges (Markov solve over resolveRoll itself), odds caps, +// take-down / working rules, a seeded AI soak for chip conservation, and the +// table geometry (zones, per-seat bet spots, rail stacks). + +import { readFileSync } from 'node:fs'; +import { + BET, POINT_NUMBERS, HARD_NUMBERS, NUMBERED, ONE_ROLL, + createInitialState, placeBet, addOdds, reduceBet, removeBet, setWorking, refundBets, + setDice, rollDice, resolveRoll, clearLastDeltas, totalAtRisk, maxOddsFor, oddsRoom, + isContract, isWorking, houseEdge, paysLabel, stickCall, explainPayout, explainMove, betLabel, +} from '../src/games/craps/CrapsLogic.js'; +import { chooseBets, chooseOdds } from '../src/games/craps/CrapsAI.js'; +import { + P, VIEW, TUB, ZONES, LANES, SEATS, SLOT_ORDER, FILL_ORDER, seatNames, laneSpot, laneForBet, hitZoneUV, inTub, + NEAR_VISIBLE_V, railUV, railPose, seatPortrait, throwOrigin, LANDING, BOARD, DOCK, offerSpot, OFFER, PROP, CALL, + puckOnUV, puckOffUV, BOX_NUMS, zoneKeyFor, lift, RESULT, +} from '../src/games/craps/CrapsTable.js'; +import { simulateThrow, topFace, restingQ, DIE } from '../src/games/craps/CrapsDice.js'; + +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps; + +function mulberry32(seed) { + return function () { + seed |= 0; seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const ALL_DICE = []; +for (let a = 1; a <= 6; a++) for (let b = 1; b <= 6; b++) ALL_DICE.push([a, b]); + +// A one-player table with the bankroll large enough for anything. +function table(point = null, chips = 100000) { + const s = createInitialState([], chips, 'T'); + s.point = point; + s.phase = point === null ? 'comeout' : 'point'; + return s; +} + +function withBet(point, spec, { comePoint = null, odds = 0, onComeOut = false } = {}) { + const line = spec.type === BET.PASS || spec.type === BET.DONT_PASS; + const come = spec.type === BET.COME || spec.type === BET.DONT_COME; + let s = table(line ? null : come ? 6 : (point === 'cp' ? 6 : point)); + s = placeBet(s, 0, spec); + const b = s.players[0].bets[0]; + if (!b) throw new Error(`withBet: rejected ${JSON.stringify(spec)}`); + if (comePoint != null) b.comePoint = comePoint; + b.oddsAmount = odds; + s.players[0].chips -= odds; + b.onComeOut = onComeOut; + if (point !== 'cp') s.point = point; + s.phase = s.point === null ? 'comeout' : 'point'; + return s; +} + +// One roll with a single bet: returns { delta, result, kept, open, next }. +function oneRoll(state, dice) { + const r = resolveRoll(setDice(state, dice)); + const pay = r.payouts.find((p) => p.playerIndex === 0); + return { r, pay, next: r.state }; +} + +// Exact expected value (per decision) of the player's single bet, by value +// iteration over the Markov chain that resolveRoll itself defines. +function exactEV(start) { + const key = (s) => JSON.stringify([s.point, s.players[0].bets.map((b) => [b.comePoint, b.amount, b.oddsAmount, b.onComeOut])]); + const states = new Map(); + const queue = [start]; + states.set(key(start), { s: start, edges: null, v: 0 }); + while (queue.length) { + const s = queue.shift(); + const node = states.get(key(s)); + node.edges = []; + for (const d of ALL_DICE) { + const { pay, next } = oneRoll(s, d); + if (pay) { node.edges.push({ p: 1 / 36, delta: pay.delta }); continue; } + next.players[0].lastDelta = 0; + const k = key(next); + if (!states.has(k)) { states.set(k, { s: next, edges: null, v: 0 }); queue.push(next); } + node.edges.push({ p: 1 / 36, to: k }); + } + } + for (let it = 0; it < 4000; it++) { + let change = 0; + for (const node of states.values()) { + let v = 0; + for (const e of node.edges) v += e.p * (e.to ? states.get(e.to).v : e.delta); + change = Math.max(change, Math.abs(v - node.v)); + node.v = v; + } + if (change < 1e-13) break; + } + return states.get(key(start)).v; +} + +const edgeOf = (s) => -exactEV(s) / (s.players[0].bets[0].amount + s.players[0].bets[0].oddsAmount) * 100; + +// ── 1. Every bet × all 36 rolls against a hand-written table ───────────────── +section('Single-roll resolution (36 combos per bet)'); +{ + // expected(total, hard, isComeOut) → ['win', winnings] | ['lose'] | ['push'] | ['open'] + const W = (w) => ['win', w]; + const L = ['lose'], O = ['open'], Pu = ['push']; + const cases = [ + { name: 'Field $10', spec: { type: BET.FIELD, amount: 10 }, point: null, + exp: (t) => (t === 2 ? W(20) : t === 12 ? W(30) : [3, 4, 9, 10, 11].includes(t) ? W(10) : L) }, + { name: 'Pass $10 come-out', spec: { type: BET.PASS, amount: 10 }, point: null, + exp: (t) => (t === 7 || t === 11 ? W(10) : [2, 3, 12].includes(t) ? L : O) }, + { name: "Don't Pass $10 come-out", spec: { type: BET.DONT_PASS, amount: 10 }, point: null, + exp: (t) => (t === 2 || t === 3 ? W(10) : t === 7 || t === 11 ? L : O) }, // 12 barred: stands + { name: 'Any 7 $5', spec: { type: BET.ANY7, amount: 5 }, point: 6, exp: (t) => (t === 7 ? W(20) : L) }, + { name: 'Any Craps $5', spec: { type: BET.ANY_CRAPS, amount: 5 }, point: 6, exp: (t) => ([2, 3, 12].includes(t) ? W(35) : L) }, + { name: 'Yo $5', spec: { type: BET.YO, amount: 5 }, point: null, exp: (t) => (t === 11 ? W(75) : L) }, + { name: 'Aces $5', spec: { type: BET.ACES, amount: 5 }, point: null, exp: (t) => (t === 2 ? W(150) : L) }, + { name: 'Ace-Deuce $5', spec: { type: BET.ACE_DEUCE, amount: 5 }, point: null, exp: (t) => (t === 3 ? W(75) : L) }, + { name: 'Boxcars $5', spec: { type: BET.BOXCARS, amount: 5 }, point: null, exp: (t) => (t === 12 ? W(150) : L) }, + { name: 'C&E $2', spec: { type: BET.CE, amount: 2 }, point: null, exp: (t) => ([2, 3, 12].includes(t) ? W(6) : t === 11 ? W(14) : L) }, + { name: 'Horn $4', spec: { type: BET.HORN, amount: 4 }, point: null, exp: (t) => (t === 2 || t === 12 ? W(27) : t === 3 || t === 11 ? W(12) : L) }, + { name: 'Big 6 $10', spec: { type: BET.BIG, number: 6, amount: 10 }, point: 5, exp: (t) => (t === 6 ? W(10) : t === 7 ? L : O) }, + { name: 'Hard 8 $5 (point)', spec: { type: BET.HARD, number: 8, amount: 5 }, point: 5, + exp: (t, h) => (t === 8 && h ? W(45) : t === 8 || t === 7 ? L : O) }, + { name: 'Hard 4 $5 (point)', spec: { type: BET.HARD, number: 4, amount: 5 }, point: 5, + exp: (t, h) => (t === 4 && h ? W(35) : t === 4 || t === 7 ? L : O) }, + { name: 'Hard 6 $5 (come-out, off)', spec: { type: BET.HARD, number: 6, amount: 5 }, point: null, exp: () => O }, + { name: 'Place 6 $12 (point)', spec: { type: BET.PLACE, number: 6, amount: 12 }, point: 5, exp: (t) => (t === 6 ? W(14) : t === 7 ? L : O) }, + { name: 'Place 4 $10 (point)', spec: { type: BET.PLACE, number: 4, amount: 10 }, point: 5, exp: (t) => (t === 4 ? W(18) : t === 7 ? L : O) }, + { name: 'Place 9 $10 (point)', spec: { type: BET.PLACE, number: 9, amount: 10 }, point: 5, exp: (t) => (t === 9 ? W(14) : t === 7 ? L : O) }, + { name: 'Place 8 $6 (come-out, off)', spec: { type: BET.PLACE, number: 8, amount: 6 }, point: null, exp: () => O }, + { name: 'Buy 10 $20', spec: { type: BET.BUY, number: 10, amount: 20 }, point: 5, exp: (t) => (t === 10 ? W(40) : t === 7 ? L : O) }, + { name: 'Lay 4 $40', spec: { type: BET.LAY, number: 4, amount: 40 }, point: null, exp: (t) => (t === 7 ? W(20) : t === 4 ? L : O) }, + ]; + for (const c of cases) { + const s0 = placeBet(table(c.point), 0, c.spec); + ok(`${c.name}: placed`, s0.players[0].bets.length === 1); + let bad = 0; + for (const d of ALL_DICE) { + const t = d[0] + d[1], h = d[0] === d[1]; + const [res, w] = c.exp(t, h); + const { pay } = oneRoll(s0, d); + const got = pay ? pay.result : 'open'; + if (got !== res || (res === 'win' && pay.winnings !== w)) { + bad++; + if (bad < 3) ok(`${c.name} on ${d.join('-')}`, false, `expected ${res}${w ? ' ' + w : ''}, got ${got}${pay ? ' ' + pay.winnings : ''}`); + } + } + ok(`${c.name}: all 36 combos`, bad === 0); + } + + // Commissions + { + const s0 = placeBet(table(5), 0, { type: BET.BUY, number: 4, amount: 20 }); + const { pay } = oneRoll(s0, [2, 2]); + ok('Buy 4 $20: pays 40 less $1 vig', pay.winnings === 40 && pay.commission === 1 && pay.delta === 39 && pay.kept); + const s1 = placeBet(table(5), 0, { type: BET.LAY, number: 10, amount: 40 }); + const r1 = oneRoll(s1, [3, 4]).pay; + ok('Lay 10 $40: wins 20 less $1 vig', r1.winnings === 20 && r1.commission === 1 && r1.delta === 19 && r1.kept); + } + // Pass / Don't on the point, with odds + for (const n of POINT_NUMBERS) { + const mult = n === 4 || n === 10 ? 3 : n === 5 || n === 9 ? 4 : 5; + let s = placeBet(table(null), 0, { type: BET.PASS, amount: 10 }); + s.point = n; s.phase = 'point'; + const b = s.players[0].bets[0]; + ok(`Pass on ${n}: odds cap is ${mult}×`, maxOddsFor(b, s) === 10 * mult); + s = addOdds(s, 0, b.id, 10000); + ok(`Pass on ${n}: addOdds clamps to the cap`, s.players[0].bets[0].oddsAmount === 10 * mult); + const odds = 10 * mult; + const trueW = n === 4 || n === 10 ? odds * 2 : n === 5 || n === 9 ? odds * 3 / 2 : odds * 6 / 5; + const hit = oneRoll(s, n === 4 ? [2, 2] : n === 10 ? [5, 5] : [1, n - 1]).pay; + ok(`Pass on ${n} + max odds: point made pays flat + true odds`, hit.result === 'win' && hit.winnings === 10 + trueW, `${hit.winnings}`); + const seven = oneRoll(s, [3, 4]).pay; + ok(`Pass on ${n} + odds: seven-out loses everything`, seven.result === 'lose' && seven.delta === -(10 + odds)); + + let d = placeBet(table(null), 0, { type: BET.DONT_PASS, amount: 10 }); + d.point = n; d.phase = 'point'; + const db = d.players[0].bets[0]; + ok(`Don't on ${n}: lay cap is 6× flat`, maxOddsFor(db, d) === 60); + d = addOdds(d, 0, db.id, 60); + const layW = n === 4 || n === 10 ? 30 : n === 5 || n === 9 ? 40 : 50; + const dw = oneRoll(d, [3, 4]).pay; + ok(`Don't on ${n} + 6× lay: seven pays flat + ${layW} (max win = 6× flat)`, dw.result === 'win' && dw.winnings === 10 + layW); + } + // A barred 12 is no action: the Don't bet stays exactly where it is. + { + const dp = placeBet(table(null), 0, { type: BET.DONT_PASS, amount: 10 }); + const r = resolveRoll(setDice(dp, [6, 6])); + ok("Don't Pass on a come-out 12 stays up, untouched", r.payouts.length === 0 && r.state.players[0].bets.length === 1 + && r.state.players[0].bets[0].amount === 10 && r.state.players[0].chips === dp.players[0].chips); + const dc = placeBet(table(8), 0, { type: BET.DONT_COME, amount: 10 }); + const r2 = resolveRoll(setDice(dc, [6, 6])); + ok("Don't Come on a 12 stays in the Don't Come box", r2.payouts.length === 0 && r2.state.players[0].bets[0].comePoint == null); + } + // Come bets travel, then win / lose; come odds off on the come-out. + { + let s = placeBet(table(5), 0, { type: BET.COME, amount: 10 }); + const r = resolveRoll(setDice(s, [4, 4])); + ok('Come on 8: travels', r.moves.length === 1 && r.moves[0].to === 8 && r.state.players[0].bets[0].comePoint === 8); + s = r.state; + const cb = s.players[0].bets[0]; + ok('Come on 8: is a contract bet', isContract(cb, s)); + ok('Come on 8: cannot be taken down', removeBet(s, 0, cb.id) === s); + s = addOdds(s, 0, cb.id, 50); + ok('Come on 8: takes 5× odds', s.players[0].bets[0].oddsAmount === 50); + const win = oneRoll(s, [5, 3]).pay; + ok('Come 8 hits: flat + 6:5 odds', win.result === 'win' && win.winnings === 10 + 60); + // come-out: odds off + const co = { ...s, point: null, phase: 'comeout' }; + const lose7 = oneRoll(co, [3, 4]).pay; + ok('Come 8 on a come-out 7: flat loses, odds returned', lose7.result === 'lose' && lose7.refund === 50 && lose7.delta === -10); + const hit8 = oneRoll(co, [4, 4]).pay; + ok('Come 8 hits on the come-out: flat paid, odds returned unpaid', hit8.result === 'win' && hit8.winnings === 10 && hit8.delta === 10); + // Don't Come + let dc = placeBet(table(5), 0, { type: BET.DONT_COME, amount: 10 }); + dc = resolveRoll(setDice(dc, [2, 2])).state; + const dcb = dc.players[0].bets[0]; + ok("Don't Come travels to 4", dcb.comePoint === 4 && !isContract(dcb, dc)); + ok("Don't Come lay cap 6×", maxOddsFor(dcb, dc) === 60); + ok("Don't Come can be taken down", removeBet(dc, 0, dcb.id).players[0].bets.length === 0); + } +} + +// ── 2. Exact house edges ───────────────────────────────────────────────────── +section('Exact house edges (Markov solve)'); +{ + const E = [ + ['Pass', withBet(null, { type: BET.PASS, amount: 10 }), 7 / 495 * 100], + // per decision: a barred 12 is no action, so the bet simply stands + ["Don't Pass", withBet(null, { type: BET.DONT_PASS, amount: 10 }), 108 / 7700 * 100], + ['Come', withBet('cp', { type: BET.COME, amount: 10 }), 7 / 495 * 100], + ["Don't Come", withBet('cp', { type: BET.DONT_COME, amount: 10 }), 108 / 7700 * 100], + ['Field', withBet(null, { type: BET.FIELD, amount: 10 }), 100 / 36], + ['Place 6 $6', withBet(5, { type: BET.PLACE, number: 6, amount: 6 }), 100 / 66], + ['Place 5 $5', withBet(6, { type: BET.PLACE, number: 5, amount: 5 }), 4], + ['Place 4 $5', withBet(6, { type: BET.PLACE, number: 4, amount: 5 }), 100 / 15], + ['Place 8 $6 from the come-out', withBet(null, { type: BET.PLACE, number: 8, amount: 6 }), 100 / 66], + ['Buy 4 $20', withBet(6, { type: BET.BUY, number: 4, amount: 20 }), 5 / 3], + ['Buy 5 $20', withBet(6, { type: BET.BUY, number: 5, amount: 20 }), 2], + ['Buy 6 $20', withBet(5, { type: BET.BUY, number: 6, amount: 20 }), 25 / 11], + ['Lay 4 $40', withBet(6, { type: BET.LAY, number: 4, amount: 40 }), 5 / 3], + ['Lay 5 $30', withBet(6, { type: BET.LAY, number: 5, amount: 30 }), 2], + ['Lay 6 $30', withBet(5, { type: BET.LAY, number: 6, amount: 30 }), 20 / 11], + ['Big 6', withBet(5, { type: BET.BIG, number: 6, amount: 10 }), 100 / 11], + ['Hard 6', withBet(5, { type: BET.HARD, number: 6, amount: 5 }), 100 / 11], + ['Hard 4', withBet(5, { type: BET.HARD, number: 4, amount: 5 }), 100 / 9], + ['Hard 10 from the come-out', withBet(null, { type: BET.HARD, number: 10, amount: 5 }), 100 / 9], + ['Any 7', withBet(null, { type: BET.ANY7, amount: 5 }), 100 / 6], + ['Any Craps', withBet(null, { type: BET.ANY_CRAPS, amount: 5 }), 100 / 9], + ['Yo', withBet(null, { type: BET.YO, amount: 5 }), 100 / 9], + ['Aces', withBet(null, { type: BET.ACES, amount: 5 }), 500 / 36], + ['Ace-Deuce', withBet(null, { type: BET.ACE_DEUCE, amount: 5 }), 100 / 9], + ['Boxcars', withBet(null, { type: BET.BOXCARS, amount: 5 }), 500 / 36], + ['C&E $2', withBet(null, { type: BET.CE, amount: 2 }), 100 / 9], + ['Horn $4', withBet(null, { type: BET.HORN, amount: 4 }), 12.5], + ]; + for (const [name, s, want] of E) { + const got = edgeOf(s); + ok(`${name}: edge ${want.toFixed(3)}%`, near(got, want, 1e-6), `got ${got.toFixed(6)}%`); + const b = s.players[0].bets[0]; + const shown = houseEdge(b.type, b.number); + ok(`${name}: tooltip edge ${shown}% matches to 2dp`, shown != null && Math.abs(shown - want) < 0.006, `exact ${want.toFixed(4)}`); + } + // Odds are free: adding max odds to a Pass/Come on any point leaves EV unchanged. + for (const n of POINT_NUMBERS) { + const mult = n === 4 || n === 10 ? 3 : n === 5 || n === 9 ? 4 : 5; + const flat = withBet(n, { type: BET.PASS, amount: 10 }); + const odds = withBet(n, { type: BET.PASS, amount: 10 }, { odds: 10 * mult }); + ok(`Pass odds on ${n} are zero-edge`, near(exactEV(flat), exactEV(odds), 1e-9)); + const dflat = withBet(n, { type: BET.DONT_PASS, amount: 10 }); + const dodds = withBet(n, { type: BET.DONT_PASS, amount: 10 }, { odds: 60 }); + ok(`Lay odds on ${n} are zero-edge`, near(exactEV(dflat), exactEV(dodds), 1e-9)); + } +} + +// ── 3. Placement, take-downs, working ──────────────────────────────────────── +section('Placement / take-down / working rules'); +{ + let s = table(null, 100); + ok('Come is illegal on the come-out', placeBet(s, 0, { type: BET.COME, amount: 5 }) === s); + ok('Place needs a point number', placeBet(s, 0, { type: BET.PLACE, number: 7, amount: 5 }) === s); + ok('Hard needs 4/6/8/10', placeBet(s, 0, { type: BET.HARD, number: 5, amount: 5 }) === s); + ok('Big only 6/8', placeBet(s, 0, { type: BET.BIG, number: 4, amount: 5 }) === s); + ok('Cannot bet more than the bankroll', placeBet(s, 0, { type: BET.FIELD, amount: 101 }) === s); + s = placeBet(s, 0, { type: BET.PASS, amount: 10 }); + s = placeBet(s, 0, { type: BET.PASS, amount: 5 }); + ok('Repeat chips stack onto the same bet', s.players[0].bets.length === 1 && s.players[0].bets[0].amount === 15); + ok('Bankroll debited', s.players[0].chips === 85); + const pb = s.players[0].bets[0]; + ok('Pass is not contract before the point', !isContract(pb, s)); + const part = reduceBet(s, 0, pb.id, { amount: 5 }); + ok('Undo a chip: reduceBet partial', part.players[0].bets[0].amount === 10 && part.players[0].chips === 90); + const off = removeBet(s, 0, pb.id); + ok('Pass can come down on the come-out', off.players[0].bets.length === 0 && off.players[0].chips === 100); + + // Place bets: off on come-out, can be called on. + let p = placeBet(table(null, 100), 0, { type: BET.PLACE, number: 6, amount: 12 }); + const plb = p.players[0].bets[0]; + ok('Place is off on the come-out', !isWorking(plb, p)); + p = setWorking(p, 0, plb.id, true); + ok('Place called on for the come-out', isWorking(p.players[0].bets[0], p)); + const hit = oneRoll(p, [3, 3]).pay; + ok('Called-on Place 6 wins on a come-out 6', hit && hit.result === 'win' && hit.winnings === 14); + const after = oneRoll(p, [3, 3]).next; + ok('A point resets the called-on flag', after.point === 6 && after.players[0].bets[0].onComeOut === false); + ok('Winning place stays up, stake not returned', after.players[0].chips === 100 - 12 + 14 && after.players[0].bets[0].amount === 12); + const pt = table(5, 100); + const pp = placeBet(pt, 0, { type: BET.PLACE, number: 6, amount: 12 }); + ok('setWorking only during the come-out', setWorking(pp, 0, pp.players[0].bets[0].id, false) === pp); + + // Contract Pass after the point. + let c = placeBet(table(null, 100), 0, { type: BET.PASS, amount: 10 }); + c = resolveRoll(setDice(c, [2, 2])).state; + const cb = c.players[0].bets[0]; + ok('Pass is contract once the point is set', isContract(cb, c) && removeBet(c, 0, cb.id) === c); + c = addOdds(c, 0, cb.id, 30); + ok('oddsRoom is 0 at the cap', oddsRoom(c, 0, cb.id) === 0); + const oddsOff = reduceBet(c, 0, cb.id, { part: 'odds' }); + ok('Odds can always come down', oddsOff.players[0].bets[0].oddsAmount === 0 && oddsOff.players[0].chips === c.players[0].chips + 30); + const cleared = refundBets(c, 0); + ok('Clear leaves contract bets', cleared.players[0].bets.length === 1); + const left = refundBets(c, 0, { force: true }); + ok('Leaving refunds everything', left.players[0].bets.length === 0 && left.players[0].chips === 100); + // Shrinking a Don't flat trims laid odds above the new cap. + let dd = placeBet(table(null, 500), 0, { type: BET.DONT_PASS, amount: 20 }); + dd = resolveRoll(setDice(dd, [2, 2])).state; + const ddb = dd.players[0].bets[0]; + dd = addOdds(dd, 0, ddb.id, 120); + const dd2 = reduceBet(dd, 0, ddb.id, { amount: 10 }); + ok("Shrinking a Don't flat returns excess odds", dd2.players[0].bets[0].oddsAmount === 60 && dd2.players[0].chips === dd.players[0].chips + 10 + 60); + + // Stickman always has something to say. + let calls = 0; + for (const point of [null, 4, 6, 9]) { + for (const d of ALL_DICE) { + const r = resolveRoll(setDice(table(point), d)); + if (typeof stickCall(r, point) === 'string' && stickCall(r, point).length > 0) calls++; + } + } + ok('stickCall covers every roll', calls === 4 * 36); + + // Every decision on every bet gets a plain-English reason and a name. + let explained = 0, blank = 0; + for (const point of [null, 4, 5, 6, 8, 9, 10]) { + for (const z of Object.values(ZONES)) { + if (z.type === 'odds') continue; + const s0 = table(point); + s0.players[0].bets.push({ id: 1, type: z.type, number: z.number ?? null, comePoint: null, amount: 20, oddsAmount: 0, onComeOut: true }); + const moved = table(point); + if (z.type === BET.COME || z.type === BET.DONT_COME) moved.players[0].bets.push({ id: 2, type: z.type, number: null, comePoint: 6, amount: 20, oddsAmount: 20, onComeOut: false }); + for (const d of ALL_DICE) { + for (const [st, unmoved] of [[s0, true], [moved, false]]) { + const r = resolveRoll(setDice(st, d)); + for (const p of r.payouts) { + const why = explainPayout(p, { dice: d, prevPoint: point, unmoved: unmoved && p.betId === 1 }); + const name = betLabel(p.betType, p.number); + if (!why || !name || /undefined|null|NaN/.test(why + name)) { blank++; if (blank < 4) ok(`explain ${p.betType} ${d}`, false, `${name}: ${why}`); } + else explained++; + } + for (const m of r.moves) if (!explainMove(m).includes(String(m.to))) blank++; + } + } + } + } + ok(`every decision explained (${explained})`, blank === 0 && explained > 3000, `${blank} blank`); + const ex = (type, number, result, dice, prevPoint, extra = {}) => explainPayout({ betType: type, number, result, commission: 0, refund: 0, kept: false, ...extra }, { dice, prevPoint, ...extra }); + ok('Field loss says why', ex(BET.FIELD, null, 'lose', [5, 3], 6) === "8 isn't a Field number"); + ok('Hard way lost to the easy way', ex(BET.HARD, 8, 'lose', [5, 3], 6) === '8 came easy (5-3)'); + ok('Seven-out named', ex(BET.PLACE, 6, 'lose', [3, 4], 9) === 'Seven-out before the 6'); + ok('Point made named', ex(BET.PASS, null, 'win', [4, 2], 6) === 'Point 6 made'); + ok('Come natural on its own come-out', ex(BET.COME, null, 'win', [5, 6], 8, { unmoved: true }) === 'Natural 11 on the Come'); + ok('Buy vig noted', ex(BET.BUY, 4, 'win', [2, 2], 8, { commission: 1, kept: true }) === 'The 4 rolled · stays up · $1 vig'); + ok('Come odds returned noted', ex(BET.COME, 8, 'lose', [3, 4], null, { refund: 40 }).includes('odds returned')); + for (const type of Object.values(BET)) { + const nums = NUMBERED[type] ?? [null]; + for (const n of nums) ok(`${type}${n ?? ''} has a pays label`, paysLabel(type, n).length > 0); + } +} + +// ── 4. Seeded AI soak: chip conservation ───────────────────────────────────── +section('AI soak (chip conservation, 6 bots × 20k rolls)'); +{ + const rng = mulberry32(20261124); + // names chosen so all four AI personalities play + const opps = ['ava', 'ben', 'cara', 'eli', 'ivy', 'kai'].map((id) => ({ id, name: id })); + let s = createInitialState(opps, 2000, 'Human'); + s.players[0].isAI = true; + let violations = 0, rolls = 0, sevenOuts = 0, points = 0, propHits = 0; + const seen = new Set(); + for (let i = 0; i < 20000; i++) { + for (let pi = 0; pi < s.players.length; pi++) { + if (s.players[pi].chips + totalAtRisk(s.players[pi]) < 50) s.players[pi].chips += 2000; // rebuy + for (const spec of chooseBets(s.players[pi], s, rng)) s = placeBet(s, pi, spec); + for (const o of chooseOdds(s.players[pi], s)) s = addOdds(s, pi, o.betId, o.amount); + } + for (const p of s.players) for (const b of p.bets) { + seen.add(b.type); + if (b.amount <= 0 || b.oddsAmount < 0 || b.oddsAmount > Math.max(0, maxOddsFor(b, s))) violations++; + } + const before = s.players.map((p) => p.chips + totalAtRisk(p)); + s = clearLastDeltas(rollDice(s, rng)); + const r = resolveRoll(s); + s = r.state; + rolls++; + if (r.sevenOut) sevenOuts++; + if (r.pointEstablished) points++; + propHits += r.payouts.filter((p) => ONE_ROLL.has(p.betType) && p.result === 'win').length; + s.players.forEach((p, pi) => { + const after = p.chips + totalAtRisk(p); + if (after - before[pi] !== p.lastDelta) violations++; + if (p.chips < 0) violations++; + }); + } + ok('no conservation / cap violations', violations === 0, `${violations}`); + ok('shooter rotated', sevenOuts > 1000, `${sevenOuts}`); + ok('points were set', points > 2000, `${points}`); + ok('props got hit', propHits > 50, `${propHits}`); + for (const t of [BET.PASS, BET.DONT_PASS, BET.COME, BET.DONT_COME, BET.FIELD, BET.PLACE, BET.HARD, BET.LAY, BET.CE, BET.YO, BET.ANY_CRAPS]) { + ok(`AI uses ${t}`, seen.has(t)); + } +} + +// ── 5. Source lint ─────────────────────────────────────────────────────────── +section('Source lint'); +{ + const logic = readFileSync(new URL('../src/games/craps/CrapsLogic.js', import.meta.url), 'utf8'); + ok('logic is Phaser-free', !/from 'phaser'/.test(logic)); + for (const f of ['CrapsTable.js', 'CrapsDice.js', 'CrapsAI.js']) { + const src = readFileSync(new URL(`../src/games/craps/${f}`, import.meta.url), 'utf8'); + ok(`${f} is Phaser-free`, !/from 'phaser'/.test(src)); + } + const game = readFileSync(new URL('../src/games/craps/CrapsGame.js', import.meta.url), 'utf8'); + ok('no hand-built Rectangle hit areas', !/new Phaser\.Geom\.Rectangle\(/.test(game)); + ok('no setInteractive on containers', !/add\.container\([^)]*\)[^;]*setInteractive/.test(game)); + ok('felt clicks go through table-space hit-testing', /hitZone\(x, y\)/.test(game)); + ok('uses the shared dock + chip stacks', /new CasinoDock\(/.test(game) && /makeChipStack\(/.test(game)); +} + + +// ── 6. Table geometry ──────────────────────────────────────────────────────── +section('Table geometry'); +{ + const inRect = (pt, r, eps = 1e-9) => pt.u >= r.u0 - eps && pt.u <= r.u1 + eps && pt.v >= r.v0 - eps && pt.v <= r.v1 + eps; + const all = Object.values(ZONES).flatMap((z) => z.rects.map((r) => ({ key: z.key, r }))); + for (const { key, r } of all) { + const corners = [[r.u0, r.v0], [r.u1, r.v0], [r.u0, r.v1], [r.u1, r.v1]]; + ok(`${key}: on the felt`, corners.every(([u, v]) => inTub(u, v))); + ok(`${key}: not hidden under the near rail`, r.v1 <= NEAR_VISIBLE_V); + const c = { u: (r.u0 + r.u1) / 2, v: (r.v0 + r.v1) / 2 }; + ok(`${key}: centre hit-tests to itself`, hitZoneUV(c.u, c.v) === key, hitZoneUV(c.u, c.v)); + const a = P.project(r.u0, r.v0), b = P.project(r.u1, r.v1); + ok(`${key}: big enough to click (≥ 24px)`, Math.abs(b.x - a.x) >= 24 && Math.abs(b.y - a.y) >= 20, `${(b.x - a.x).toFixed(0)}×${(b.y - a.y).toFixed(0)}`); + } + let overlaps = 0; + for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) { + const A = all[i].r, B = all[j].r; + const ou = Math.min(A.u1, B.u1) - Math.max(A.u0, B.u0), ov = Math.min(A.v1, B.v1) - Math.max(A.v0, B.v0); + if (ou > 1e-6 && ov > 1e-6 && all[i].key !== all[j].key) { overlaps++; ok(`${all[i].key} ∩ ${all[j].key}`, false); } + } + ok('no two zones overlap', overlaps === 0); + // Every bet type maps to a zone the player can click. + for (const type of Object.values(BET)) { + for (const n of NUMBERED[type] ?? [null]) ok(`${type}${n ?? ''} has a zone`, !!zoneKeyFor(type, n)); + } + + // Lane spots sit inside their zone, for every seat / crowding. + const laneZone = (k) => { + if (k.startsWith('comept')) return ZONES[`place${k.slice(6)}`]; + return ZONES[k]; + }; + for (const [k, L] of Object.entries(LANES)) { + const z = laneZone(k); + ok(`lane ${k} has a zone`, !!z); + if (!z) continue; + const pts = []; + if (L.kind === 'flow') for (let n = 1; n <= 7; n++) for (let i = 0; i < n; i++) pts.push(laneSpot(k, { index: i, count: n })); + else for (const seat of SLOT_ORDER) pts.push(laneSpot(k, { seat })); + ok(`lane ${k}: every spot inside ${z.key}`, pts.every((p) => z.rects.some((r) => inRect(p, r)))); + } + // Seat-fixed lanes give each seat its own spot. + for (const k of ['pass', 'field', 'come', 'dontpass', 'odds', 'ce']) { + const keys = new Set(SLOT_ORDER.map((seat) => JSON.stringify(laneSpot(k, { seat })))); + ok(`lane ${k}: 7 distinct seat spots`, keys.size === 7); + } + // Bets → lanes + const sample = [ + { type: 'pass' }, { type: 'dontpass' }, { type: 'come' }, { type: 'come', comePoint: 9 }, { type: 'dontcome' }, + { type: 'dontcome', comePoint: 4 }, { type: 'field' }, { type: 'place', number: 6 }, { type: 'buy', number: 10 }, + { type: 'lay', number: 5 }, { type: 'big', number: 8 }, { type: 'hard', number: 4 }, { type: 'any7' }, { type: 'horn' }, + { type: 'ce' }, { type: 'yo' }, { type: 'aces' }, { type: 'acedeuce' }, { type: 'boxcars' }, { type: 'anycraps' }, + ]; + for (const b of sample) ok(`${b.type}${b.number ?? b.comePoint ?? ''} has a lane`, !!LANES[laneForBet(b)]); + + // Seats + ok('seat names: human first, fill order after', seatNames(6).join() === ['H', ...FILL_ORDER].join()); + const portraits = seatNames(6).slice(1).map((n) => ({ n, ...seatPortrait(n) })); + for (const p of portraits) { + ok(`${p.n}: portrait on screen`, p.x - p.r >= 0 && p.x + p.r <= 1920 && p.y - p.r >= 0); + ok(`${p.n}: portrait clear of the dock`, p.y + p.r + 22 <= DOCK.y, `${p.y + p.r}`); + ok(`${p.n}: portrait clear of the history board`, p.x + p.r < BOARD.x || p.y - p.r > BOARD.y + BOARD.h); + ok(`${p.n}: portrait clear of the Leave button`, !(p.x - p.r < 160 && p.y - p.r < 72)); + } + for (let i = 0; i < portraits.length; i++) for (let j = i + 1; j < portraits.length; j++) { + const a = portraits[i], b = portraits[j]; + ok(`${a.n}/${b.n}: portraits don't overlap`, Math.hypot(a.x - b.x, a.y - b.y) > a.r + b.r + 60); + } + for (const n of Object.keys(SEATS)) { + const { u, v } = railUV(n); + ok(`${n}: chips sit on the rail, not the felt`, !inTub(u, v) && inTub(u, v, TUB.RW)); + const r = railPose(n); + ok(`${n}: rail stack on screen`, r.x > 20 && r.x < 1900 && r.y > 60 && r.y < DOCK.y); + const o = throwOrigin(n); + ok(`${n}: throw starts over the felt`, inTub(o.u, o.v)); + } + // Furniture + for (let i = 0; i < 5; i++) { + const o = offerSpot(i); + ok(`offer die ${i} on visible felt, below the prop box`, inTub(o.u, o.v) && o.v <= NEAR_VISIBLE_V && o.v > PROP.v1 && !hitZoneUV(o.u, o.v)); + } + for (const n of BOX_NUMS) ok(`puck ON spot inside place${n}`, ZONES[`place${n}`].rects.some((r) => inRect(puckOnUV(n), r))); + ok('puck OFF spot inside the Don\'t Come box', ZONES.dontcome.rects.some((r) => inRect(puckOffUV(), r))); + ok('board on screen', BOARD.x + BOARD.w <= 1920 && BOARD.y >= 0); + { + const inCard = (p, pad = 0) => p.x > RESULT.x - pad && p.x < RESULT.x + RESULT.w + pad && p.y > RESULT.y - pad && p.y < RESULT.y + RESULT.h + pad; + ok('results card on screen, above the dock', RESULT.x + RESULT.w <= 1920 && RESULT.y + RESULT.h <= DOCK.y - 4); + ok('results card clear of the history board', RESULT.y > BOARD.y + BOARD.h); + const L = LANDING; + ok('landing area clear of the results card', [[L.u0, L.v0], [L.u1, L.v0], [L.u1, L.v1], [L.u0, L.v1]].every(([u, v]) => !inCard(P.project(u, v)))); + for (const z of Object.values(ZONES)) for (const r of z.rects) { + ok(`${z.key} clear of the results card`, [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]].every(([u, v]) => !inCard(P.project(u, v)))); + } + for (let i = 0; i < 5; i++) ok(`offer die ${i} clear of the results card`, !inCard(P.project(offerSpot(i).u, offerSpot(i).v), 24)); + for (const n of seatNames(6).slice(1)) { const p = seatPortrait(n); ok(`${n} portrait clear of the results card`, !inCard(p, p.r)); } + } + ok('board below the music player (top ~76px on the right)', BOARD.y >= 80); + { + // right rail's outer edge where the board's bottom-left corner sits + let near = null; + for (let v = -0.1; v <= 1.1; v += 0.001) { + const p = lift(1 + TUB.RW, v, TUB.H); + if (!near || Math.abs(p.y - (BOARD.y + BOARD.h)) < Math.abs(near.y - (BOARD.y + BOARD.h))) near = p; + } + ok('board clear of the right rail', BOARD.x - near.x >= 8, `${(BOARD.x - near.x).toFixed(0)}px`); + } + { + const c0 = CALL.x - CALL.maxW / 2, c1 = CALL.x + CALL.maxW / 2; + ok('stickman banner clear of the history board', c1 < BOARD.x); + for (const n of ['F1', 'F2', 'F3']) { + const p = seatPortrait(n); + const plateEnd = p.x + p.r + 12 + 120; // name / bankroll plate to the right + ok(`stickman banner clear of ${n}'s plate`, plateEnd < c0 || p.x - p.r > c1, `${plateEnd.toFixed(0)} vs ${c0}`); + } + } + ok('landing area on the felt', inTub(LANDING.u0, LANDING.v0) && inTub(LANDING.u1, LANDING.v1)); +} + +// ── 7. Dice throws ─────────────────────────────────────────────────────────── +section('Dice throws (300 seeded throws)'); +{ + const rng = mulberry32(777); + let wrongFace = 0, outside = 0, close = 0, noWall = 0, maxDur = 0, maxTries = 0, underCard = 0; + for (let i = 0; i < 300; i++) { + const seat = seatNames(6)[i % 7]; + const faces = [1 + (i % 6), 1 + ((i * 5 + 2) % 6)]; + const plan = simulateThrow(throwOrigin(seat), faces, rng); + maxDur = Math.max(maxDur, plan.duration); + maxTries = Math.max(maxTries, plan.tries); + plan.dice.forEach((d, k) => { + const last = d.frames[d.frames.length - 1]; + if (topFace(last.q) !== faces[k]) wrongFace++; + if (!(last.u >= LANDING.u0 - 0.04 && last.u <= LANDING.u1 && last.v >= LANDING.v0 && last.v <= LANDING.v1)) outside++; + const sp = P.project(last.u, last.v); + if (sp.x > RESULT.x - 24 && sp.y > RESULT.y - 12) underCard++; + if (!d.hitWall) noWall++; + if (!d.frames.every((f) => inTub(f.u, f.v) && f.h >= 0 && Number.isFinite(f.u))) outside++; + }); + const [a, b] = plan.dice.map((d) => d.frames[d.frames.length - 1]); + if (Math.hypot((a.u - b.u) * VIEW.halfW, (a.v - b.v) * VIEW.halfW * 4 / 3) < DIE.size * 1.2) close++; + } + ok('every die lands showing the rolled number', wrongFace === 0, `${wrongFace}`); + ok('dice stay in the tub and land in the landing area', outside === 0, `${outside}`); + ok('every die hits the back wall', noWall === 0, `${noWall}`); + ok('no die comes to rest under the results card', underCard === 0, `${underCard}`); + ok('dice never come to rest on top of each other', close === 0, `${close}`); + ok('throws last under 3.6 s', maxDur < 3.6, maxDur.toFixed(2)); + for (let f = 1; f <= 6; f++) ok(`restingQ shows ${f}`, topFace(restingQ(f, f * 0.7)) === f); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);