From 2d1a673b7e5214dda7d1d0fa28f703853da89f5b Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Tue, 24 Nov 2026 09:59:28 -0700 Subject: [PATCH] Rework roulette into a full 3D table with both wheel variants - Add European single-zero and American double-zero wheels with La Partage and the full set of inside bets (splits, corners, streets, trios, basket) - Rebuild the scene around a perspective-projected felt: baked table art, 3D wheel bowl/head/ball, chip stacks on the layout, and a dealer's rail - Plan each spin physically (track, diamond strikes, fret hops) so the ball lands on the pre-chosen number instead of a tween to a fixed angle - Add AI personalities (grinder, sprinkler, martingale, chaser, sections), late bets, and per-player memory for the Martingale progression - Introduce table limits, call bets/racetrack with neighbour stepper, history board, wheel cam, speed/felt/table toggles, and tooltips with house edges - Extract geometry and rules into Phaser-free modules and add a headless verification suite covering payouts, hit-testing, AI, and the ball planner --- src/games/roulette/RouletteAI.js | 174 ++- src/games/roulette/RouletteArt.js | 780 +++++++++++ src/games/roulette/RouletteBall.js | 289 ++++ src/games/roulette/RouletteGame.js | 1901 +++++++++++++++++++-------- src/games/roulette/RouletteLogic.js | 455 +++++-- src/games/roulette/RouletteTable.js | 414 ++++++ src/games/roulette/RouletteWheel.js | 151 +++ src/ui/CasinoChips.js | 82 +- tools/verifyRoulette.js | 452 +++++++ 9 files changed, 3973 insertions(+), 725 deletions(-) create mode 100644 src/games/roulette/RouletteArt.js create mode 100644 src/games/roulette/RouletteBall.js create mode 100644 src/games/roulette/RouletteTable.js create mode 100644 src/games/roulette/RouletteWheel.js create mode 100644 tools/verifyRoulette.js diff --git a/src/games/roulette/RouletteAI.js b/src/games/roulette/RouletteAI.js index 3e5855c..638b6fc 100644 --- a/src/games/roulette/RouletteAI.js +++ b/src/games/roulette/RouletteAI.js @@ -1,24 +1,30 @@ -// Heuristic Roulette AI. Stateless helpers consumed by RouletteGame. +// Roulette opponents. Stateless helpers plus a small per-player memory object +// the scene keeps (for the Martingale player). Each opponent gets a stable +// personality from a hash of their name. Bets come back as plain specs that the +// scene applies through RouletteLogic.placeBet (which validates legality, +// bankroll and the table limits). // -// Each opponent gets a stable "personality" derived from their name, which -// shapes which bets they favour and how big. chooseBets returns plain bet specs -// the scene applies through RouletteLogic.placeBet (which guards affordability). +// grinder even-money and dozens, small and steady +// sprinkler straight-ups plus the splits/corners around a few lucky numbers +// martingale one even-money bet, doubled after every loss (reset on a win) +// chaser plays the hot numbers off the history board +// sections European call bets (Voisins / Tiers / Orphelins); streets and +// six lines on the American wheel -import { BET } from './RouletteLogic.js'; +import { + BET, EVEN_MONEY, WHEELS, legalInsideBets, callBetSpecs, spotLimit, +} from './RouletteLogic.js'; -const EVEN_MONEY = [BET.RED, BET.BLACK, BET.ODD, BET.EVEN, BET.LOW, BET.HIGH]; +const EVEN = [...EVEN_MONEY]; -const PROFILES = { - // unitPct: flat-bet size as a fraction of bankroll - // evenChance: probability of taking an even-money outside bet - // groupChance: probability of taking a dozen or column (2:1) bet - // straightCount: how many favourite straight-up numbers they sprinkle on - conservative: { unitPct: 0.03, evenChance: 0.92, groupChance: 0.12, straightCount: 0 }, - balanced: { unitPct: 0.05, evenChance: 0.70, groupChance: 0.55, straightCount: 0 }, - aggressive: { unitPct: 0.07, evenChance: 0.45, groupChance: 0.70, straightCount: 1 }, - gambler: { unitPct: 0.10, evenChance: 0.50, groupChance: 0.35, straightCount: 3 }, +export const PERSONALITIES = { + grinder: { unitPct: 0.03 }, + sprinkler: { unitPct: 0.012 }, + martingale: { unitPct: 0.015 }, + chaser: { unitPct: 0.012 }, + sections: { unitPct: 0.01 }, }; -const PROFILE_KEYS = Object.keys(PROFILES); +const KEYS = Object.keys(PERSONALITIES); function hash(str) { let h = 0; @@ -26,26 +32,20 @@ function hash(str) { return h; } -function profileFor(player) { - const name = player.name ?? player.avatar?.id ?? 'bot'; - return PROFILES[PROFILE_KEYS[hash(name) % PROFILE_KEYS.length]]; +export function personalityOf(player) { + return KEYS[hash(player.name ?? player.avatar?.id ?? 'bot') % KEYS.length]; } -const snap = (n, step) => Math.max(step, Math.round(n / step) * step); +const snap = (n, step = 5) => Math.max(step, Math.round(n / step) * step); +const pick = (arr, rng) => arr[Math.floor(rng() * arr.length)]; -function unitFor(player, prof) { - return Math.min(100, snap(player.chips * prof.unitPct, 5)); +function unitFor(player, kind) { + return Math.min(50, snap(player.chips * PERSONALITIES[kind].unitPct, 5)); } -const pick = (arr) => arr[Math.floor(Math.random() * arr.length)]; - -// Deterministic favourite numbers (1–36) for an opponent, so a "gambler" keeps -// chasing the same lucky spots round after round. function luckyNumbers(player, count) { - if (count <= 0) return []; - const seed = hash(player.name ?? player.avatar?.id ?? 'bot'); + let x = hash(player.name ?? 'bot') || 1; const out = []; - let x = seed || 1; while (out.length < count) { x = (x * 1103515245 + 12345) >>> 0; const n = 1 + (x % 36); @@ -54,27 +54,107 @@ function luckyNumbers(player, count) { return out; } -// Bets to place for the current round. Returns an array of bet specs. -export function chooseBets(player, state) { - const prof = profileFor(player); +function insideAround(variant, n, type) { + return legalInsideBets(variant).filter(b => b.type === type && b.numbers.includes(n)); +} + +// Hot numbers off the history (most frequent first). +function hotNumbers(history, count) { + const freq = new Map(); + for (const v of history.slice(-60)) freq.set(v, (freq.get(v) ?? 0) + 1); + return [...freq.entries()].sort((a, b) => b[1] - a[1]).slice(0, count).map(e => e[0]); +} + +/** + * Opening bets for a round. + * ctx = { variant, history: [values], memory: {}, rng } + */ +export function chooseBets(player, ctx) { + const { variant, history = [], memory = {}, rng = Math.random } = ctx; + const kind = personalityOf(player); + const unit = unitFor(player, kind); const specs = []; let budget = player.chips; - const unit = unitFor(player, prof); - const afford = (amt) => amt > 0 && amt <= budget; - const add = (spec) => { if (afford(spec.amount)) { specs.push(spec); budget -= spec.amount; } }; + const add = (spec) => { + const amount = Math.min(spec.amount, spotLimit(spec.type)); + if (amount < 1 || amount > budget) return false; + specs.push({ ...spec, amount }); + budget -= amount; + return true; + }; + const inside = (b, amount) => add({ type: b.type, numbers: b.numbers, amount }); - if (Math.random() < prof.evenChance) { - add({ type: pick(EVEN_MONEY), amount: unit }); + switch (kind) { + case 'grinder': { + add({ type: pick(EVEN, rng), amount: unit }); + if (rng() < 0.5) add({ type: rng() < 0.5 ? BET.DOZEN : BET.COLUMN, number: 1 + Math.floor(rng() * 3), amount: snap(unit * 0.6) }); + break; + } + case 'sprinkler': { + for (const n of luckyNumbers(player, 2)) { + inside({ type: BET.STRAIGHT, numbers: [n] }, unit); + const extra = rng() < 0.5 ? insideAround(variant, n, BET.SPLIT) : insideAround(variant, n, BET.CORNER); + if (extra.length) inside(pick(extra, rng), unit); + } + if (rng() < 0.3) inside({ type: BET.STRAIGHT, numbers: [WHEELS[variant].zeros[0]] }, unit); + break; + } + case 'martingale': { + memory.type ??= pick([BET.RED, BET.BLACK, BET.ODD, BET.EVEN], rng); + memory.base ??= unit; + memory.stake ??= memory.base; + const stake = Math.min(memory.stake, spotLimit(memory.type), budget); + if (stake < memory.stake) memory.stake = memory.base; // busted the progression + add({ type: memory.type, amount: Math.max(memory.base, Math.min(stake, memory.stake)) }); + break; + } + case 'chaser': { + const hot = hotNumbers(history, 3); + const nums = hot.length ? hot : luckyNumbers(player, 3); + for (const n of nums) inside({ type: BET.STRAIGHT, numbers: [n] }, unit); + const col = nums.find(n => typeof n === 'number' && n > 0); + if (col && rng() < 0.6) add({ type: BET.COLUMN, number: ((col - 1) % 3) + 1, amount: unit * 2 }); + break; + } + case 'sections': { + if (variant === 'eu') { + const name = pick(['voisins', 'tiers', 'orphelins', 'zero'], rng); + for (const s of callBetSpecs(variant, name, unit)) add(s); + } else { + const streets = legalInsideBets(variant).filter(b => b.type === BET.STREET || b.type === BET.SIX_LINE); + inside(pick(streets, rng), unit * 2); + add({ type: BET.DOZEN, number: 1 + Math.floor(rng() * 3), amount: unit * 2 }); + } + break; + } + default: break; } - if (Math.random() < prof.groupChance) { - const type = Math.random() < 0.5 ? BET.DOZEN : BET.COLUMN; - add({ type, number: 1 + Math.floor(Math.random() * 3), amount: snap(unit, 5) }); - } - for (const n of luckyNumbers(player, prof.straightCount)) { - add({ type: BET.STRAIGHT, number: n, amount: Math.max(5, snap(unit / 2, 5)) }); - } - // Never sit a round out entirely. - if (specs.length === 0 && afford(unit)) add({ type: pick(EVEN_MONEY), amount: unit }); - + if (specs.length === 0 && budget >= 5) add({ type: pick(EVEN, rng), amount: Math.min(budget, unit) }); return specs; } + +// A chip or two dropped on while the ball is spinning. +export function chooseLateBets(player, ctx) { + const { variant, rng = Math.random } = ctx; + if (rng() > 0.45 || player.chips < 5) return []; + const kind = personalityOf(player); + const unit = Math.min(unitFor(player, kind), player.chips); + if (kind === 'martingale') return []; + const pockets = WHEELS[variant].pockets; + const specs = [{ type: BET.STRAIGHT, numbers: [pick(pockets, rng)], amount: Math.max(1, Math.min(unit, 10)) }]; + if (rng() < 0.3 && player.chips >= unit * 2) { + const splits = legalInsideBets(variant).filter(b => b.type === BET.SPLIT); + const s = pick(splits, rng); + specs.push({ type: s.type, numbers: s.numbers, amount: Math.max(1, Math.min(unit, 10)) }); + } + return specs; +} + +// Update the Martingale memory after a spin. +export function noteResult(player, memory, payouts) { + if (personalityOf(player) !== 'martingale' || !memory.type) return; + const mine = payouts.find(p => p.type === memory.type); + if (!mine) return; + if (mine.result === 'win') memory.stake = memory.base; + else memory.stake = Math.min(spotLimit(memory.type), memory.stake * 2); +} diff --git a/src/games/roulette/RouletteArt.js b/src/games/roulette/RouletteArt.js new file mode 100644 index 0000000..2143a60 --- /dev/null +++ b/src/games/roulette/RouletteArt.js @@ -0,0 +1,780 @@ +// Roulette art — every texture is baked once into a canvas (no image files). +// +// roulette-table-- the full 1920×1080 table: floor shadow, +// padded rail, wooden wheel cabinet, felt +// with the betting layout (+ racetrack on +// the European table), the house chip float +// roulette-head- the rotating wheel head, top-down +// roulette-bowl- the static bowl at screen radius R, drawn +// already in perspective (rim, track, +// incline, diamonds, cabinet side) +// roulette-gloss / -turret static lighting + the chrome spindle +// roulette-ball, roulette-dolly +// +// Table positions come from RouletteTable.js; wheel radii from RouletteBall.js. + +import { prepareCasinoArt, canvas, rr, poly, mix, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { CHIP_DEFS } from '../../ui/CasinoChips.js'; +import { WHEELS, colorOf, numLabel, BET } from './RouletteLogic.js'; +import { GEO, DIAMONDS, bowlHeight } from './RouletteBall.js'; +import { + P, VIEW, RAIL, lift, tableOutline, CABINET_U1, WHEEL, ZERO_U0, GRID_U0, CELL_U, GRID_U1, COL_U1, + GRID_V0, ROW_V, GRID_V1, DOZ_V1, EVEN_V1, EVEN_ORDER, feltBoxes, RT, RT_GEOM, racetrackPoint, + racetrackLines, racetrackSectionCenters, BANK, +} from './RouletteTable.js'; + +const W = 1920, H = 1080; +export const FELTS = { green: '#0d5a2e', blue: '#123c78', red: '#6a1020' }; +const LINE = 'rgba(244,236,214,0.9)'; +const LINE_SOFT = 'rgba(244,236,214,0.45)'; +const CREAM = '#f4ecd6'; +const RED = '#c8202b'; +const BLACK = '#121214'; +const GOLD = '#e8c15a'; +const SERIF = 'Georgia, "Times New Roman", serif'; +const SANS = '"Julius Sans One", sans-serif'; +const POCKET_COLORS = { red: '#b3141f', black: '#151517', green: '#127a3a' }; + +export async function prepareRouletteArt(scene, felt = 'green', variant = 'us') { + await prepareCasinoArt(scene); + const key = `roulette-table-${felt}-${variant}`; + if (!scene.textures.exists(key)) bakeTable(scene, key, FELTS[felt] ?? FELTS.green, variant); + for (const v of Object.keys(WHEELS)) { + if (!scene.textures.exists(`roulette-head-${v}`)) bakeHead(scene, v); + } + if (!scene.textures.exists('roulette-ball')) bakeBall(scene); + if (!scene.textures.exists('roulette-dolly')) bakeDolly(scene); + if (!scene.textures.exists('roulette-turret')) bakeTurret(scene); + if (!scene.textures.exists('roulette-gloss')) bakeGloss(scene); + return key; +} + +// ── Projection helpers ─────────────────────────────────────────────────────── +const toScreen = (pts, h = 0) => pts.map(p => lift(p.u, p.v, h)); +const rectPts = (r) => [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 strokePts(ctx, pts, color = LINE, width = 2.4, close = true) { + poly(ctx, pts, close); + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); +} + +// 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, spacing = 0, alpha = 1, maxW = null, stroke = null, strokeW = 3, shadow = true, rot = 0, +} = {}) { + 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 (maxW) { + const w = ctx.measureText(text).width; + if (w > maxW) ctx.scale(maxW / w, 1); + } + if (shadow) { + ctx.shadowColor = 'rgba(0,0,0,0.45)'; + ctx.shadowBlur = 3; + ctx.shadowOffsetY = 1.5; + } + if (stroke) { + ctx.lineWidth = strokeW; + ctx.strokeStyle = stroke; + ctx.lineJoin = 'round'; + ctx.strokeText(text, 0, 0); + ctx.shadowColor = 'transparent'; + } + ctx.fillStyle = color; + ctx.fillText(text, 0, 0); + ctx.restore(); +} + +// A flat shape (drawn in local px around (0,0)) lying on the felt at (u, v). +function onFelt(ctx, u, v, draw) { + const p = P.project(u, v); + ctx.save(); + ctx.translate(p.x, p.y); + ctx.scale(p.s, p.s * VIEW.squash); + draw(ctx); + ctx.restore(); +} + +function ringPath(ctx, outer, inner) { + ctx.beginPath(); + outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + ctx.closePath(); + [...inner].reverse().forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + ctx.closePath(); +} + +// ── Table ──────────────────────────────────────────────────────────────────── +function bakeTable(scene, key, felt, variant) { + const c = canvas(W, H); + const ctx = c.getContext('2d'); + drawFloorShadow(ctx); + drawRailFace(ctx); + drawFelt(ctx, felt, variant); + drawCabinet(ctx); + drawRail(ctx); + drawBank(ctx); + scene.textures.addCanvas(key, c); +} + +function outlineScreen(d, h, extraDown = 0) { + return tableOutline(d, 14, 44).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(RAIL.W, RAIL.H, RAIL.FACE + 14); + 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(); +} + +function drawRailFace(ctx) { + const top = outlineScreen(RAIL.W, RAIL.H); + ctx.save(); + poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL.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 + RAIL.FACE * p.s * f }))); + ctx.lineWidth = 4; + ctx.strokeStyle = mix('#7a4520', '#2a170c', Math.min(1, f * 1.2)); + ctx.stroke(); + } + poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL.FACE * p.s * 0.78 }))); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(214,174,90,0.55)'; + ctx.stroke(); + ctx.restore(); +} + +function drawFelt(ctx, felt, variant) { + 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, variant); + if (variant === 'eu') drawRacetrack(ctx, felt); + else drawPlacard(ctx); + + const c = P.project(0.25, 0.45); + const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1000); + lamp.addColorStop(0, 'rgba(255,246,205,0.17)'); + lamp.addColorStop(0.5, 'rgba(255,246,205,0.05)'); + 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, 1200); + 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); + for (let i = 0; i < 8; i++) { + poly(ctx, toScreen(tableOutline(-i * 0.006, 14, 44))); + ctx.lineWidth = 5; + ctx.strokeStyle = `rgba(0,0,0,${0.28 * (1 - i / 8)})`; + ctx.stroke(); + } + ctx.restore(); +} + +// ── Betting layout ─────────────────────────────────────────────────────────── +function drawLayout(ctx, felt, variant) { + const boxes = feltBoxes(variant); + const darker = mix(felt, '#000000', 0.18); + + // zero boxes: a slightly richer green so they read as special + for (const b of boxes.filter(b => b.kind === 'num' && (b.n === 0 || b.n === '00'))) { + poly(ctx, rectPts(b)); + ctx.fillStyle = mix(felt, '#1f9a4c', 0.35); + ctx.fill(); + } + // outside boxes: faint inset + for (const b of boxes.filter(b => b.kind === 'out')) { + poly(ctx, rectPts(b)); + ctx.fillStyle = darker; + ctx.globalAlpha = 0.25; + ctx.fill(); + ctx.globalAlpha = 1; + } + + // numbers + for (const b of boxes.filter(b => b.kind === 'num')) { + const u = (b.u0 + b.u1) / 2, v = (b.v0 + b.v1) / 2; + const col = colorOf(b.n); + if (col === 'green') { + feltText(ctx, u, v, numLabel(b.n), b.n === '00' ? 34 : 40, CREAM, { stroke: 'rgba(0,0,0,0.5)', strokeW: 3 }); + continue; + } + // a lacquered oval behind each number + onFelt(ctx, u, v, (g) => { + g.beginPath(); + g.ellipse(0, 0, 25, 31, 0, 0, Math.PI * 2); + const grad = g.createLinearGradient(0, -31, 0, 31); + const base = col === 'red' ? RED : BLACK; + grad.addColorStop(0, mix(base, '#ffffff', 0.18)); + grad.addColorStop(1, mix(base, '#000000', 0.25)); + g.fillStyle = grad; + g.fill(); + g.lineWidth = 1.6; + g.strokeStyle = 'rgba(244,236,214,0.55)'; + g.stroke(); + }); + feltText(ctx, u, v + 0.002, numLabel(b.n), 30, CREAM, { maxW: 40 }); + } + + // grid lines + ctx.lineCap = 'round'; + for (const b of boxes) strokePts(ctx, rectPts(b), LINE, 2.4); + // heavier outline round the whole inside layout + strokePts(ctx, rectPts({ u0: ZERO_U0, u1: COL_U1, v0: GRID_V0, v1: GRID_V1 }), LINE, 3.2); + + // outside lettering + for (const b of boxes.filter(b => b.kind === 'out')) { + const u = (b.u0 + b.u1) / 2, v = (b.v0 + b.v1) / 2; + switch (b.type) { + case BET.COLUMN: feltText(ctx, u, v, '2 to 1', 19, CREAM, { maxW: 64 }); break; + case BET.DOZEN: feltText(ctx, u, v, ['1st 12', '2nd 12', '3rd 12'][b.number - 1], 30, CREAM, { spacing: 2 }); break; + case BET.RED: + case BET.BLACK: + onFelt(ctx, u, v, (g) => { + g.beginPath(); + g.moveTo(0, -27); g.lineTo(46, 0); g.lineTo(0, 27); g.lineTo(-46, 0); g.closePath(); + const base = b.type === BET.RED ? RED : BLACK; + const grad = g.createLinearGradient(0, -27, 0, 27); + grad.addColorStop(0, mix(base, '#ffffff', 0.15)); + grad.addColorStop(1, mix(base, '#000000', 0.3)); + g.fillStyle = grad; + g.fill(); + g.lineWidth = 2; + g.strokeStyle = 'rgba(244,236,214,0.7)'; + g.stroke(); + }); + break; + default: { + const label = { [BET.LOW]: '1 – 18', [BET.EVEN]: 'EVEN', [BET.ODD]: 'ODD', [BET.HIGH]: '19 – 36' }[b.type]; + feltText(ctx, u, v, label, 26, CREAM, { spacing: 2 }); + } + } + } + if (variant === 'eu') { + feltText(ctx, (GRID_U0 + GRID_U1) / 2, EVEN_V1 + 0.045, 'LA PARTAGE · EVEN-MONEY BETS LOSE ONLY HALF ON ZERO', 13, GOLD, { font: SANS, bold: false, spacing: 2, alpha: 0.85 }); + } else { + feltText(ctx, (GRID_U0 + GRID_U1) / 2, EVEN_V1 + 0.045, 'AMERICAN DOUBLE ZERO · INSIDE BETS PAY 35 · 17 · 11 · 8 · 6 · 5 TO 1', 13, GOLD, { font: SANS, bold: false, spacing: 2, alpha: 0.8 }); + } +} + +function drawPlacard(ctx) { + const um = (RT.u0 + RT.u1) / 2; + feltText(ctx, um, 0.085, 'AMERICAN ROULETTE', 40, GOLD, { spacing: 8, alpha: 0.9 }); + feltText(ctx, um, 0.155, 'TABLE LIMITS · $1 MINIMUM · $100 STRAIGHT UP · $1,000 OUTSIDE', 14, CREAM, { font: SANS, bold: false, spacing: 2, alpha: 0.7 }); + // little diamonds either side + for (const du of [-0.38, 0.38]) { + onFelt(ctx, um + du, 0.09, (g) => { + g.beginPath(); g.moveTo(0, -9); g.lineTo(12, 0); g.lineTo(0, 9); g.lineTo(-12, 0); g.closePath(); + g.fillStyle = GOLD; g.globalAlpha = 0.75; g.fill(); + }); + } +} + +// ── Racetrack ──────────────────────────────────────────────────────────────── +function stadiumPts(radius, steps = 160) { + const pts = []; + for (let i = 0; i < steps; i++) { + const d = (i / steps) * RT_GEOM.PER; + const c = racetrackPoint(d, RT_GEOM.RC); + // push from the centre line out to `radius` + pts.push(P.project(c.u + c.nu * (radius - RT_GEOM.RC), c.v + c.nv * (radius - RT_GEOM.RC))); + } + return pts; +} + +function drawRacetrack(ctx, felt) { + const pockets = WHEELS.eu.pockets; + const N = pockets.length; + const step = RT_GEOM.PER / N; + const rOut = RT_GEOM.R, rIn = RT_GEOM.R - RT.band; + // band fill + ringPath(ctx, stadiumPts(rOut), stadiumPts(rIn)); + ctx.fillStyle = mix(felt, '#000000', 0.22); + ctx.fill('evenodd'); + // pocket cells + for (let i = 0; i < N; i++) { + const seg = []; + for (let k = 0; k <= 6; k++) { + const c = racetrackPoint((i - 0.5 + k / 6) * step); + seg.push(P.project(c.u + c.nu * (rOut - RT_GEOM.RC - 0.004), c.v + c.nv * (rOut - RT_GEOM.RC - 0.004))); + } + for (let k = 6; k >= 0; k--) { + const c = racetrackPoint((i - 0.5 + k / 6) * step); + seg.push(P.project(c.u + c.nu * (rIn - RT_GEOM.RC + 0.004), c.v + c.nv * (rIn - RT_GEOM.RC + 0.004))); + } + poly(ctx, seg); + const col = colorOf(pockets[i]); + ctx.fillStyle = col === 'red' ? 'rgba(200,32,43,0.55)' : col === 'black' ? 'rgba(10,10,12,0.6)' : 'rgba(31,154,76,0.7)'; + ctx.fill(); + const m = racetrackPoint(i * step); + feltText(ctx, m.u, m.v + 0.002, numLabel(pockets[i]), 17, CREAM, { font: SERIF, maxW: 26 }); + // divider + const a = racetrackPoint((i + 0.5) * step); + strokePts(ctx, [ + P.project(a.u + a.nu * (rOut - RT_GEOM.RC), a.v + a.nv * (rOut - RT_GEOM.RC)), + P.project(a.u + a.nu * (rIn - RT_GEOM.RC), a.v + a.nv * (rIn - RT_GEOM.RC)), + ], LINE_SOFT, 1.2, false); + } + strokePts(ctx, stadiumPts(rOut), LINE, 2.4); + strokePts(ctx, stadiumPts(rIn), LINE, 1.8); + // section dividers + for (const [t, b] of racetrackLines()) strokePts(ctx, [P.project(t.u, t.v), P.project(b.u, b.v)], LINE, 1.8, false); + for (const s of racetrackSectionCenters()) { + const label = { tiers: 'TIER', orphelins: 'ORPHELINS', voisins: 'VOISINS', zero: 'ZERO' }[s.name]; + feltText(ctx, s.u, s.v, label, s.name === 'zero' ? 14 : 18, GOLD, { font: SANS, bold: false, spacing: 3, maxW: 150 }); + } +} + +// ── Wheel cabinet & rail ───────────────────────────────────────────────────── +function drawCabinet(ctx) { + // The left end of the table is a raised wooden cabinet holding the wheel. + const H0 = 10; + const edge = []; + for (let i = 0; i <= 20; i++) edge.push({ u: CABINET_U1, v: 1 - i / 20 }); + const region = [lift(-1.6, -0.4, H0), lift(CABINET_U1, -0.4, H0), lift(CABINET_U1, 1.4, H0), lift(-1.6, 1.4, H0)]; + const clipTo = () => { poly(ctx, outlineScreen(0, H0)); ctx.clip(); }; + // front face along the cabinet edge (the step up from the felt) + ctx.save(); + clipTo(); + poly(ctx, [...edge.map(p => P.project(p.u, p.v)), ...edge.slice().reverse().map(p => lift(p.u, p.v, H0))]); + ctx.fillStyle = '#3b1f0f'; + ctx.fill(); + ctx.restore(); + ctx.save(); + clipTo(); + poly(ctx, region); + ctx.clip(); + const a = lift(-1, 0, H0), b = lift(CABINET_U1, 1, H0); + const g = ctx.createLinearGradient(a.x, a.y, b.x, b.y); + g.addColorStop(0, '#5a2c12'); + g.addColorStop(0.5, '#7a3e1a'); + g.addColorStop(1, '#4a230e'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + // wood grain + ctx.save(); + ctx.globalAlpha = 0.18; + for (let i = 0; i < 46; i++) { + const v = i / 45; + const pts = []; + for (let k = 0; k <= 24; k++) { + const u = -1.1 + (k / 24) * (CABINET_U1 + 1.1); + pts.push(lift(u, v + Math.sin(k * 0.7 + i * 1.3) * 0.006, H0)); + } + strokePts(ctx, pts, i % 3 ? '#2a1206' : '#a8693a', i % 3 ? 1 : 1.6, false); + } + ctx.globalAlpha = 1; + ctx.fillStyle = noisePattern(ctx, 128, 18); + ctx.fillRect(0, 0, W, H); + // soft shadow where the wheel bowl sits + const wc = lift(WHEEL.u, WHEEL.v, WHEEL.h); + ctx.save(); + ctx.translate(wc.x, wc.y + 34); + ctx.scale(1, WHEEL.tilt); + const sh = ctx.createRadialGradient(0, 0, WHEEL.R * 0.8, 0, 0, WHEEL.R * 1.35); + sh.addColorStop(0, 'rgba(0,0,0,0.65)'); + sh.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = sh; + ctx.beginPath(); ctx.arc(0, 0, WHEEL.R * 1.35, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + ctx.restore(); + ctx.restore(); + // brass strip where cabinet meets felt + strokePts(ctx, edge.map(p => lift(p.u, p.v, H0)), 'rgba(214,174,90,0.85)', 2.4, false); +} + +function drawRail(ctx) { + const inner0 = outlineScreen(0, 0); + const innerTop = outlineScreen(0, RAIL.H); + const outerTop = outlineScreen(RAIL.W, RAIL.H); + // inner wall (felt up to the rail top), visible along the far side + ringPath(ctx, innerTop, inner0); + ctx.fillStyle = '#1c0f08'; + ctx.fill('evenodd'); + // padded leather top + ringPath(ctx, outerTop, innerTop); + const g = ctx.createLinearGradient(0, 150, 0, 900); + g.addColorStop(0, '#2a1a12'); + g.addColorStop(1, '#120a06'); + ctx.fillStyle = g; + ctx.fill('evenodd'); + ctx.save(); + ringPath(ctx, outerTop, innerTop); + ctx.clip('evenodd'); + ctx.fillStyle = noisePattern(ctx, 128, 26); + ctx.fillRect(0, 0, W, H); + // cushion sheen along the middle of the pad + const mid = outlineScreen(RAIL.W * 0.45, RAIL.H + 3); + strokePts(ctx, mid, 'rgba(255,230,200,0.12)', 9); + strokePts(ctx, mid, 'rgba(255,240,220,0.14)', 3); + ctx.restore(); + // stitching + edges + ctx.setLineDash([6, 5]); + strokePts(ctx, outlineScreen(RAIL.W * 0.12, RAIL.H), 'rgba(214,174,120,0.35)', 1.3); + strokePts(ctx, outlineScreen(RAIL.W * 0.86, RAIL.H), 'rgba(214,174,120,0.35)', 1.3); + ctx.setLineDash([]); + strokePts(ctx, innerTop, 'rgba(0,0,0,0.6)', 2); + strokePts(ctx, outerTop, 'rgba(120,80,40,0.8)', 2); +} + +// The dealer's chip float, set into the far rail between the wheel and layout. +function drawBank(ctx) { + const v0 = -RAIL.W * 0.85, v1 = -RAIL.W * 0.15; + const pts = [lift(BANK.u0, v0, RAIL.H), lift(BANK.u1, v0, RAIL.H), lift(BANK.u1, v1, RAIL.H), lift(BANK.u0, v1, RAIL.H)]; + poly(ctx, pts); + ctx.fillStyle = '#0a0604'; + ctx.fill(); + strokePts(ctx, pts, 'rgba(214,174,90,0.8)', 2); + const denoms = [100, 100, 50, 50, 25, 25, 25, 5, 5, 5, 1, 1]; + const n = denoms.length; + denoms.forEach((d, i) => { + const u = BANK.u0 + ((i + 0.5) / n) * (BANK.u1 - BANK.u0); + const p = lift(u, (v0 + v1) / 2, RAIL.H); + const rx = 9.5 * p.s, ry = 4.2 * p.s; + const def = CHIP_DEFS[d]; + for (let k = 0; k < 4; k++) { + const y = p.y + 3 - k * 2.4 * p.s; + ctx.beginPath(); + ctx.ellipse(p.x, y, rx, ry, 0, 0, Math.PI * 2); + ctx.fillStyle = k % 2 ? mix(def.base, '#000000', 0.25) : def.base; + ctx.fill(); + } + ctx.beginPath(); + ctx.ellipse(p.x, p.y + 3 - 3 * 2.4 * p.s, rx * 0.55, ry * 0.55, 0, 0, Math.PI * 2); + ctx.fillStyle = def.insert; + ctx.fill(); + }); +} + +// ── Wheel head (rotating, top-down) ────────────────────────────────────────── +export const HEAD_TEX = 680; +export const HEAD_PX = 330; // texture radius that corresponds to GEO.R_HEAD +const KR = HEAD_PX / GEO.R_HEAD; // texture px per normalised radius unit + +function bakeHead(scene, variant) { + const c = canvas(HEAD_TEX, HEAD_TEX); + const ctx = c.getContext('2d'); + const cx = HEAD_TEX / 2, cy = HEAD_TEX / 2; + const pockets = WHEELS[variant].pockets; + const N = pockets.length; + const step = (Math.PI * 2) / N; + const rNumOut = GEO.R_HEAD * KR, rNumIn = 0.625 * KR; + const rPocketOut = rNumIn, rPocketIn = 0.47 * KR; + const rCone = 0.455 * KR; + + // outer lip + ctx.beginPath(); ctx.arc(cx, cy, rNumOut, 0, Math.PI * 2); + ctx.fillStyle = '#3a1a0a'; ctx.fill(); + + for (let i = 0; i < N; i++) { + const a0 = (i - 0.5) * step, a1 = (i + 0.5) * step; + const col = colorOf(pockets[i]); + const base = POCKET_COLORS[col]; + // number ring segment + ctx.beginPath(); + ctx.arc(cx, cy, rNumOut - 4, a0, a1); + ctx.arc(cx, cy, rNumIn, a1, a0, true); + ctx.closePath(); + ctx.fillStyle = base; + ctx.fill(); + // pocket floor (darker toward the outside — it's a cup) + ctx.beginPath(); + ctx.arc(cx, cy, rPocketOut, a0, a1); + ctx.arc(cx, cy, rPocketIn, a1, a0, true); + ctx.closePath(); + const pg = ctx.createRadialGradient(cx, cy, rPocketIn, cx, cy, rPocketOut); + pg.addColorStop(0, mix(base, '#ffffff', 0.08)); + pg.addColorStop(0.7, base); + pg.addColorStop(1, mix(base, '#000000', 0.55)); + ctx.fillStyle = pg; + ctx.fill(); + // number + const am = i * step; + ctx.save(); + ctx.translate(cx + Math.cos(am) * (rNumIn + rNumOut) / 2, cy + Math.sin(am) * (rNumIn + rNumOut) / 2); + ctx.rotate(am + Math.PI / 2); + ctx.font = `bold ${pockets[i] === '00' ? 15 : 19}px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#f7efd8'; + ctx.fillText(numLabel(pockets[i]), 0, 1); + ctx.restore(); + } + // number-ring rims + ctx.lineWidth = 3; + ctx.strokeStyle = '#d9b45a'; + ctx.beginPath(); ctx.arc(cx, cy, rNumOut - 3, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 2; + ctx.beginPath(); ctx.arc(cx, cy, rNumIn, 0, Math.PI * 2); ctx.stroke(); + // frets (chrome separators between pockets) + for (let i = 0; i < N; i++) { + const a = (i + 0.5) * step; + const x0 = cx + Math.cos(a) * rPocketIn, y0 = cy + Math.sin(a) * rPocketIn; + const x1 = cx + Math.cos(a) * (rNumOut - 4), y1 = cy + Math.sin(a) * (rNumOut - 4); + ctx.lineWidth = 4.5; ctx.strokeStyle = '#6d6a64'; + ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke(); + ctx.lineWidth = 1.6; ctx.strokeStyle = '#f1ede4'; + ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(cx + Math.cos(a) * rPocketOut, cy + Math.sin(a) * rPocketOut); ctx.stroke(); + } + // cone (wooden turret base) + const cg = ctx.createRadialGradient(cx - rCone * 0.3, cy - rCone * 0.3, rCone * 0.1, cx, cy, rCone); + cg.addColorStop(0, '#b06a33'); + cg.addColorStop(0.55, '#7a3e1a'); + cg.addColorStop(1, '#3a1a0a'); + ctx.beginPath(); ctx.arc(cx, cy, rCone, 0, Math.PI * 2); + ctx.fillStyle = cg; ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = '#d9b45a'; + ctx.beginPath(); ctx.arc(cx, cy, rCone, 0, Math.PI * 2); ctx.stroke(); + // decorative inlay ring + 8 spokes + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(232,193,90,0.6)'; + ctx.beginPath(); ctx.arc(cx, cy, rCone * 0.72, 0, Math.PI * 2); ctx.stroke(); + for (let k = 0; k < 8; k++) { + const a = (k / 8) * Math.PI * 2; + ctx.beginPath(); + ctx.moveTo(cx + Math.cos(a) * rCone * 0.2, cy + Math.sin(a) * rCone * 0.2); + ctx.lineTo(cx + Math.cos(a) * rCone * 0.72, cy + Math.sin(a) * rCone * 0.72); + ctx.stroke(); + } + // turret cross arms (chrome), seen from above + for (let k = 0; k < 4; k++) { + const a = (k / 4) * Math.PI * 2 + Math.PI / 4; + const ex = cx + Math.cos(a) * rCone * 0.62, ey = cy + Math.sin(a) * rCone * 0.62; + ctx.lineCap = 'round'; + ctx.lineWidth = 9; ctx.strokeStyle = '#4b4a47'; + ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(ex, ey); ctx.stroke(); + ctx.lineWidth = 5; ctx.strokeStyle = '#d8d5cd'; + ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(ex, ey); ctx.stroke(); + const kg = ctx.createRadialGradient(ex - 3, ey - 3, 1, ex, ey, 10); + kg.addColorStop(0, '#ffffff'); kg.addColorStop(1, '#8a877f'); + ctx.fillStyle = kg; + ctx.beginPath(); ctx.arc(ex, ey, 9, 0, Math.PI * 2); ctx.fill(); + } + scene.textures.addCanvas(`roulette-head-${variant}`, c); +} + +// ── Bowl (static, in perspective) ──────────────────────────────────────────── +// Texture is (2·R·OUT + pad) wide; the wheel centre sits at (cx, cy) inside it. +export const BOWL_OUT = 1.12; // outer edge of the cabinet rim (normalised) +export const BOWL_SIDE = 0.16; // visible height of the cabinet's outer side +export function bowlLayout(R, tilt) { + const k = Math.sqrt(1 - tilt * tilt); + const w = Math.ceil(2 * R * BOWL_OUT + 16); + const top = R * BOWL_OUT * tilt + R * 0.2 * k + 8; + const h = Math.ceil(top + R * BOWL_OUT * tilt + R * BOWL_SIDE + 12); + return { w, h, cx: w / 2, cy: top, k }; +} + +export function ensureBowl(scene, R, tilt) { + const key = `roulette-bowl-${Math.round(R)}-${Math.round(tilt * 100)}`; + if (scene.textures.exists(key)) return key; + const L = bowlLayout(R, tilt); + const c = canvas(L.w, L.h); + const ctx = c.getContext('2d'); + const { cx, cy, k } = L; + const pt = (r, a, h) => ({ x: cx + Math.cos(a) * r * R, y: cy + Math.sin(a) * r * R * tilt - h * R * k }); + const ring = (r, h, steps = 180) => Array.from({ length: steps }, (_, i) => pt(r, (i / steps) * Math.PI * 2, h)); + const hRim = 0.2; + + // cabinet outer side (visible below the near half) + const top = ring(BOWL_OUT, hRim); + const bottom = top.map(p => ({ x: p.x, y: p.y + R * BOWL_SIDE })); + ctx.beginPath(); + for (let i = 0; i <= 90; i++) { const p = top[i % 180]; i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y); } + for (let i = 90; i >= 0; i--) { const p = bottom[i % 180]; ctx.lineTo(p.x, p.y); } + ctx.closePath(); + const sg = ctx.createLinearGradient(cx - R * BOWL_OUT, 0, cx + R * BOWL_OUT, 0); + sg.addColorStop(0, '#2a1206'); sg.addColorStop(0.35, '#6b3415'); sg.addColorStop(0.6, '#4a220c'); sg.addColorStop(1, '#1e0c04'); + ctx.fillStyle = sg; + ctx.fill(); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(214,174,90,0.7)'; + ctx.beginPath(); + for (let i = 0; i <= 90; i++) { const p = bottom[i % 180]; const q = { x: p.x, y: p.y - R * BOWL_SIDE * 0.3 }; i ? ctx.lineTo(q.x, q.y) : ctx.moveTo(q.x, q.y); } + ctx.stroke(); + + // cabinet rim top (wood) + ringPath(ctx, top, ring(1.0, hRim)); + const rg = ctx.createLinearGradient(0, cy - R, 0, cy + R * tilt); + rg.addColorStop(0, '#8a4a20'); rg.addColorStop(1, '#4e240c'); + ctx.fillStyle = rg; + ctx.fill('evenodd'); + ctx.lineWidth = 2; ctx.strokeStyle = '#d9b45a'; + poly(ctx, ring(1.0, hRim)); ctx.stroke(); + poly(ctx, top); ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke(); + + // inner wall from the rim down to the ball track + ringPath(ctx, ring(1.0, hRim), ring(0.945, bowlHeight(0.945))); + ctx.fillStyle = '#2b1306'; + ctx.fill('evenodd'); + + // ball track (polished) + ringPath(ctx, ring(0.945, bowlHeight(0.945)), ring(0.875, bowlHeight(0.875))); + const tg = ctx.createLinearGradient(0, cy - R * tilt, 0, cy + R * tilt); + tg.addColorStop(0, '#c08a55'); tg.addColorStop(0.5, '#8a5428'); tg.addColorStop(1, '#5c3414'); + ctx.fillStyle = tg; + ctx.fill('evenodd'); + + // incline (stator) down to the head + ringPath(ctx, ring(0.875, bowlHeight(0.875)), ring(GEO.R_HEAD - 0.01, 0)); + const ig = ctx.createRadialGradient(cx, cy - R * 0.25 * tilt, R * 0.3, cx, cy, R); + ig.addColorStop(0, '#2a1a10'); ig.addColorStop(0.7, '#3d2414'); ig.addColorStop(1, '#5a3418'); + ctx.fillStyle = ig; + ctx.fill('evenodd'); + ctx.save(); + ringPath(ctx, ring(0.875, bowlHeight(0.875)), ring(GEO.R_HEAD - 0.01, 0)); + ctx.clip('evenodd'); + ctx.fillStyle = noisePattern(ctx, 128, 16); + ctx.fillRect(0, 0, L.w, L.h); + ctx.restore(); + + // diamonds (brass deflectors), alternating orientation + DIAMONDS.forEach((a, i) => { + const r = GEO.R_DIAMOND, h = bowlHeight(r); + const c0 = pt(r, a, h); + const along = i % 2 === 0; + const dr = along ? 0.022 : 0.05, da = along ? 0.06 : 0.025; + const q = [pt(r + dr, a, bowlHeight(r + dr)), pt(r, a + da, h), pt(r - dr, a, bowlHeight(r - dr)), pt(r, a - da, h)]; + const lift2 = R * 0.018 * k; + poly(ctx, q.map(p => ({ x: p.x, y: p.y - lift2 }))); + const dg = ctx.createLinearGradient(c0.x - 8, c0.y - 8, c0.x + 8, c0.y + 8); + dg.addColorStop(0, '#fff3c4'); dg.addColorStop(0.5, '#d9b45a'); dg.addColorStop(1, '#7a5a1a'); + ctx.fillStyle = dg; + ctx.fill(); + ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke(); + }); + // shadow ring under the head's edge + ringPath(ctx, ring(GEO.R_HEAD + 0.035, 0.008), ring(GEO.R_HEAD - 0.01, 0)); + ctx.fillStyle = 'rgba(0,0,0,0.55)'; + ctx.fill('evenodd'); + + scene.textures.addCanvas(key, c); + return key; +} + +// Static lighting over the spinning head: an overhead lamp's highlight that +// stays put while the head turns underneath (sells the 3D). Drawn top-down. +function bakeGloss(scene) { + const c = canvas(HEAD_TEX, HEAD_TEX); + const ctx = c.getContext('2d'); + const cx = HEAD_TEX / 2, cy = HEAD_TEX / 2; + const g = ctx.createRadialGradient(cx - 70, cy - 120, 10, cx - 40, cy - 60, HEAD_PX * 1.05); + g.addColorStop(0, 'rgba(255,250,230,0.34)'); + g.addColorStop(0.35, 'rgba(255,250,230,0.1)'); + g.addColorStop(1, 'rgba(255,250,230,0)'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(cx, cy, HEAD_PX, 0, Math.PI * 2); ctx.fill(); + const sh = ctx.createRadialGradient(cx, cy, HEAD_PX * 0.6, cx, cy + 40, HEAD_PX * 1.02); + sh.addColorStop(0, 'rgba(0,0,0,0)'); + sh.addColorStop(1, 'rgba(0,0,0,0.28)'); + ctx.fillStyle = sh; + ctx.beginPath(); ctx.arc(cx, cy, HEAD_PX, 0, Math.PI * 2); ctx.fill(); + scene.textures.addCanvas('roulette-gloss', c); +} + +// The turret spindle standing up from the cone (static; the arms spin in the head). +export const TURRET = { w: 60, h: 96, footY: 86 }; +function bakeTurret(scene) { + const c = canvas(TURRET.w, TURRET.h); + const ctx = c.getContext('2d'); + const cx = TURRET.w / 2; + // base collar + ctx.beginPath(); ctx.ellipse(cx, TURRET.footY, 22, 9, 0, 0, Math.PI * 2); + ctx.fillStyle = '#5a564f'; ctx.fill(); + ctx.beginPath(); ctx.ellipse(cx, TURRET.footY - 4, 19, 7.5, 0, 0, Math.PI * 2); + ctx.fillStyle = '#c9c5bb'; ctx.fill(); + // post + const pg = ctx.createLinearGradient(cx - 7, 0, cx + 7, 0); + pg.addColorStop(0, '#6d6a64'); pg.addColorStop(0.35, '#ffffff'); pg.addColorStop(0.7, '#a9a59c'); pg.addColorStop(1, '#55524c'); + ctx.fillStyle = pg; + ctx.fillRect(cx - 6, 26, 12, TURRET.footY - 30); + // finial knob + const kg = ctx.createRadialGradient(cx - 5, 15, 2, cx, 20, 15); + kg.addColorStop(0, '#ffffff'); kg.addColorStop(0.5, '#d8d5cd'); kg.addColorStop(1, '#6d6a64'); + ctx.fillStyle = kg; + ctx.beginPath(); ctx.arc(cx, 20, 13, 0, Math.PI * 2); ctx.fill(); + scene.textures.addCanvas('roulette-turret', c); +} + +export const BALL_TEX = 48; +function bakeBall(scene) { + const c = canvas(BALL_TEX, BALL_TEX); + const ctx = c.getContext('2d'); + const r = BALL_TEX / 2 - 2; + const g = ctx.createRadialGradient(BALL_TEX / 2 - r * 0.35, BALL_TEX / 2 - r * 0.4, r * 0.08, BALL_TEX / 2, BALL_TEX / 2, r); + g.addColorStop(0, '#ffffff'); + g.addColorStop(0.35, '#f4f0e6'); + g.addColorStop(0.85, '#b9b2a2'); + g.addColorStop(1, '#7d7668'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(BALL_TEX / 2, BALL_TEX / 2, r, 0, Math.PI * 2); ctx.fill(); + scene.textures.addCanvas('roulette-ball', c); +} + +// The clear acrylic "dolly" the dealer sets on the winning number. +export const DOLLY = { w: 64, h: 96, footY: 82 }; +function bakeDolly(scene) { + const c = canvas(DOLLY.w, DOLLY.h); + const ctx = c.getContext('2d'); + const cx = DOLLY.w / 2, rx = 20, ry = 8; + const yTop = 22, yBot = DOLLY.footY; + // contact shadow + ctx.beginPath(); ctx.ellipse(cx + 3, yBot + 4, rx + 6, ry + 3, 0, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fill(); + // body + ctx.beginPath(); + ctx.moveTo(cx - rx, yTop); ctx.lineTo(cx - rx, yBot); + ctx.ellipse(cx, yBot, rx, ry, 0, Math.PI, 0, true); + ctx.lineTo(cx + rx, yTop); + ctx.closePath(); + const bg = ctx.createLinearGradient(cx - rx, 0, cx + rx, 0); + bg.addColorStop(0, 'rgba(255,255,255,0.55)'); + bg.addColorStop(0.25, 'rgba(255,255,255,0.12)'); + bg.addColorStop(0.7, 'rgba(255,255,255,0.08)'); + bg.addColorStop(1, 'rgba(255,255,255,0.45)'); + ctx.fillStyle = bg; ctx.fill(); + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(255,255,255,0.7)'; ctx.stroke(); + // gold crown on top + ctx.beginPath(); ctx.ellipse(cx, yTop, rx, ry, 0, 0, Math.PI * 2); + const tg = ctx.createLinearGradient(cx - rx, yTop - ry, cx + rx, yTop + ry); + tg.addColorStop(0, '#fff3c4'); tg.addColorStop(0.5, '#e8c15a'); tg.addColorStop(1, '#8a6a1a'); + ctx.fillStyle = tg; ctx.fill(); + ctx.beginPath(); ctx.ellipse(cx, yTop - 1, rx * 0.55, ry * 0.5, 0, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(255,255,255,0.55)'; ctx.fill(); + // highlight streak + ctx.fillStyle = 'rgba(255,255,255,0.6)'; + ctx.fillRect(cx - rx + 4, yTop + 6, 3, yBot - yTop - 8); + scene.textures.addCanvas('roulette-dolly', c); +} + +// Re-exported for the scene's history marquee and hover tags. +export { POCKET_COLORS, CREAM, GOLD, rr }; diff --git a/src/games/roulette/RouletteBall.js b/src/games/roulette/RouletteBall.js new file mode 100644 index 0000000..4af178d --- /dev/null +++ b/src/games/roulette/RouletteBall.js @@ -0,0 +1,289 @@ +// Roulette ball + wheel planner — Phaser-free, deterministic, verified in Node. +// +// The winning number is chosen first (RouletteLogic.spinResult); this module +// works out a physically plausible spin that lands there: +// +// 1. Track — the ball is launched round the bowl's rim track against the +// wheel, slowed by rolling friction + drag. +// 2. Drop — below a critical speed it leaves the track and spirals down the +// bowl incline, possibly striking one of the 8 fixed diamonds. +// 3. Pockets — it reaches the rotating head at relative angle φₑ, hops over a +// few frets (seeded), and settles to ride with the wheel. +// +// Phases 1–2 happen in the bowl's (static) frame and don't depend on the wheel +// at all, so we know exactly when (Tₑ) and where (θₑ) the ball reaches the head. +// When the ball is launched the dealer gives the wheel a fresh push ω₀; the +// wheel's angle at Tₑ is linear in ω₀, so we solve for the ω₀ (inside a natural +// range that spans more than a full turn) that puts the right pocket under the +// ball. Nothing is relabelled or snapped: the motion lands there. +// +// Angles: radians in the wheel plane, +ve = clockwise on screen. The ball runs +// clockwise (+), the wheel head anticlockwise (−). Pocket i of the wheel's +// pocket list sits at head-local angle i·step. Radii are normalised (1 = the +// bowl's outer rim). + +import { WHEELS } from './RouletteLogic.js'; + +export const GEO = { + R_RIM: 1.0, + R_TRACK: 0.915, // ball centre while on the track + R_DIAMOND: 0.80, // diamond deflectors on the incline + R_HEAD: 0.70, // outer edge of the rotating head (number ring) + R_ENTRY: 0.64, // ball reaches the fret ring + R_FRET: 0.605, // top of the pocket separators + R_POCKET: 0.545, // ball resting in a pocket + R_CONE: 0.42, + BALL_R: 0.03, +}; +export const DIAMONDS = Array.from({ length: 8 }, (_, k) => k * Math.PI / 4 + Math.PI / 8); +const DIAMOND_HALF = 0.15; // rad: how close to a diamond the ball must pass to strike it + +// Bowl incline height above the pocket plane (normalised units). +export function bowlHeight(r) { + if (r <= GEO.R_HEAD) return 0; + return (Math.min(r, GEO.R_TRACK) - GEO.R_HEAD) * 0.46; +} + +export const WHEEL_SPEED = { idle: 0.32, min: 1.6, max: 3.5, tau: 14, ramp: 0.6 }; +const DT = 1 / 240; +const TWO_PI = Math.PI * 2; +const wrap = (a) => ((a % TWO_PI) + TWO_PI) % TWO_PI; + +export 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 smooth = (x) => (x <= 0 ? 0 : x >= 1 ? 1 : x * x * (3 - 2 * x)); + +// Wheel push profile: ω_w(t) = idle + (ω₀ − idle)·g(t), g = ramp·decay. +const pushShape = (t) => smooth(t / WHEEL_SPEED.ramp) * Math.exp(-t / WHEEL_SPEED.tau); + +// ∫₀ᵗ g — tabulated once. +const G_MAX = 60; +const G_TABLE = (() => { + const n = Math.ceil(G_MAX / DT) + 1; + const tab = new Float64Array(n); + let acc = 0; + for (let i = 1; i < n; i++) { + const t0 = (i - 1) * DT, t1 = i * DT; + acc += (pushShape(t0) + pushShape(t1)) * 0.5 * DT; + tab[i] = acc; + } + return tab; +})(); +function gIntegral(t) { + if (t <= 0) return 0; + const x = t / DT; + const i = Math.floor(x); + if (i >= G_TABLE.length - 1) return G_TABLE[G_TABLE.length - 1]; + return G_TABLE[i] + (G_TABLE[i + 1] - G_TABLE[i]) * (x - i); +} + +export function wheelSpeedAt(omega0, t, idle = WHEEL_SPEED.idle) { + return idle + (omega0 - idle) * pushShape(t); +} + +// Wheel (head) angle t seconds after the push. The head turns anticlockwise (−). +export function wheelAngleAt(W0, omega0, t, idle = WHEEL_SPEED.idle) { + return W0 - idle * t - (omega0 - idle) * gIntegral(t); +} + +// ── Phases 1–2: the ball in the bowl frame ─────────────────────────────────── +function simulateBowl(rng, launchAngle) { + const track = []; // { t, a, r, h } + let t = 0; + let a = launchAngle; + let w = 13.6 + rng() * 3.2; // rad/s (≈ 2.2–2.7 rev/s) + const wDrop = 5.0 + rng() * 0.8; + const C1 = 0.85, C2 = 0.12; + let wob = rng() * TWO_PI; + while (w > wDrop) { + track.push({ t, a, r: GEO.R_TRACK + Math.sin(wob + t * 9) * 0.004, h: bowlHeight(GEO.R_TRACK) }); + w -= (C1 + C2 * w) * DT; + a += w * DT; + t += DT; + if (t > 20) break; + } + const dropT = t; + + // Spiral down the incline. + let r = GEO.R_TRACK, vr = 0; + let hopUntil = -1, hopStart = 0, hopH = 0; + const hits = []; + while (r > GEO.R_ENTRY) { + const prevR = r; + // gravity down the incline grows as the ball slows (less centripetal support) + vr -= (0.55 + Math.max(0, 9 - w) * 0.09) * DT; + r += vr * DT; + w -= (1.1 + 0.1 * w) * DT; + if (w < 1.2) w = 1.2; + a += w * DT; + t += DT; + if (prevR > GEO.R_DIAMOND && r <= GEO.R_DIAMOND && hits.length < 2) { + let best = Infinity; + for (const d of DIAMONDS) { + const diff = Math.abs(((wrap(a) - d + Math.PI) % TWO_PI + TWO_PI) % TWO_PI - Math.PI); + best = Math.min(best, diff); + } + if (best < DIAMOND_HALF) { + hits.push(t); + vr = 0.18 + rng() * 0.2; // knocked back up the incline + w *= 0.55 + rng() * 0.3; + hopStart = t; hopUntil = t + 0.2 + rng() * 0.08; hopH = 0.045 + rng() * 0.03; + } + } + let h = bowlHeight(r); + if (t < hopUntil) h += hopH * Math.sin(Math.PI * (t - hopStart) / (hopUntil - hopStart)); + track.push({ t, a, r: Math.max(r, GEO.R_ENTRY), h }); + if (t > 30) break; + } + return { track, dropT, entryT: t, entryA: a, entryW: w, hits }; +} + +// ── Phase 3: hops over the frets (head frame) ──────────────────────────────── +function planHops(rng) { + const n = 2 + Math.floor(rng() * 4); // 2–5 hops + const hops = []; + for (let j = 0; j < n; j++) { + let k; + if (j === 0) k = 1 + Math.floor(rng() * 5); + else if (j === 1) k = Math.floor(rng() * 3); + else k = rng() < 0.22 ? -1 : Math.floor(rng() * 2); + const dur = 0.3 * Math.pow(0.8, j) + rng() * 0.06; + const h = 0.075 * Math.pow(0.62, j) + rng() * 0.01; + hops.push({ k, dur, h }); + } + return hops; +} + +/** + * Plan a spin that lands on `target`. + * variant 'us' | 'eu' + * target the winning value (0, '00', 1…36) + * wheelAngle0 the head's angle when the ball is launched + * seed any integer + * launchAngle where the dealer releases the ball (bowl frame), default: far side + */ +export function planSpin({ variant, target, wheelAngle0 = 0, seed = 1, launchAngle = -Math.PI / 2, idle = WHEEL_SPEED.idle }) { + const pockets = WHEELS[variant].pockets; + const N = pockets.length; + const step = TWO_PI / N; + const targetIndex = pockets.indexOf(target); + if (targetIndex < 0) throw new Error(`planSpin: ${target} is not on the ${variant} wheel`); + const rng = mulberry32(seed); + + const bowl = simulateBowl(rng, launchAngle + (rng() - 0.5) * 0.7); + const hops = planHops(rng); + const k = hops.reduce((s, h) => s + h.k, 0); + const Te = bowl.entryT; + + // Relative angle the ball must meet the head at: the pocket k before the target. + const jitter = (rng() - 0.5) * 0.5 * step; + const phiE = (targetIndex - k) * step + jitter; + // wheelAngleAt(W0, ω₀, Te) = θₑ − φₑ (mod 2π), linear in ω₀. + const R = gIntegral(Te); + const base = wheelAngle0 - idle * Te + idle * R; // W(Te) = base − ω₀·R + const need = bowl.entryA - phiE; + // base − ω₀R = need + 2πm → ω₀ = (base − need − 2πm) / R + // Every solution is 2π/R apart; take those in the natural range (there is + // always at least one while R ≥ 2π/(max − min)), else the one nearest the middle. + const cands = []; + let nearest = null; + const mid = (WHEEL_SPEED.min + WHEEL_SPEED.max) / 2; + const m0 = Math.floor((base - need - WHEEL_SPEED.max * R) / TWO_PI) - 2; + for (let m = m0; m < m0 + 12; m++) { + const w0 = (base - need - TWO_PI * m) / R; + if (w0 >= WHEEL_SPEED.min && w0 <= WHEEL_SPEED.max) cands.push(w0); + if (w0 > 0.5 && (nearest == null || Math.abs(w0 - mid) < Math.abs(nearest - mid))) nearest = w0; + } + if (!cands.length) cands.push(nearest); + const omega0 = cands[Math.floor(rng() * cands.length)]; + // Keep the ball's angle continuous (not just equal mod 2π) across the hand-off. + const wTe = wheelAngleAt(wheelAngle0, omega0, Te, idle); + const turn = Math.round((bowl.entryA - (wTe + phiE)) / TWO_PI) * TWO_PI; + + // Head-frame path through the hops. + const segs = []; + let t = Te, phi = phiE + turn, idx = targetIndex - k; + // The ball first rolls onto the fret ring for a beat. + const wRel0 = bowl.entryW + wheelSpeedAt(omega0, Te, idle); + const lead = 0.16; + const phiLead = phi + Math.min(wRel0 * lead * 0.5, step * 0.45); + segs.push({ t0: t, t1: t + lead, p0: phi, p1: phiLead, r0: GEO.R_ENTRY, r1: GEO.R_FRET, h: 0.0, kind: 'roll' }); + t += lead; phi = phiLead; + const hopTs = []; + for (const hop of hops) { + idx += hop.k; + const p1 = turn + idx * step + (hop === hops[hops.length - 1] ? 0 : (rng() - 0.5) * 0.3 * step); + hopTs.push(t); + segs.push({ t0: t, t1: t + hop.dur, p0: phi, p1, r0: GEO.R_FRET, r1: GEO.R_FRET - 0.01, h: hop.h, kind: 'hop' }); + t += hop.dur; phi = p1; + } + // Settle into the pocket. + const settleDur = 0.38; + const finalPhi = turn + targetIndex * step; + segs.push({ t0: t, t1: t + settleDur, p0: phi, p1: finalPhi, r0: GEO.R_FRET - 0.01, r1: GEO.R_POCKET, h: 0.012, kind: 'settle' }); + const settleT = t + settleDur; + + const T = { + noMoreBets: Math.max(1.4, bowl.dropT - 1.6), + drop: bowl.dropT, + entry: Te, + settle: settleT, + end: settleT + 0.4, + }; + + const track = bowl.track; + function sampleTrack(time) { + const x = time / DT; + const i = Math.max(0, Math.min(track.length - 2, Math.floor(x))); + const f = Math.max(0, Math.min(1, x - i)); + const A = track[i], B = track[i + 1]; + return { a: A.a + (B.a - A.a) * f, r: A.r + (B.r - A.r) * f, h: A.h + (B.h - A.h) * f }; + } + + function sample(time) { + const wheel = wheelAngleAt(wheelAngle0, omega0, time, idle); + if (time < Te) { + const s = sampleTrack(time); + return { wheel, ball: { angle: s.a, r: s.r, h: s.h }, phase: time < bowl.dropT ? 'track' : 'drop' }; + } + if (time >= settleT) { + return { wheel, ball: { angle: wheel + finalPhi, r: GEO.R_POCKET, h: 0 }, phase: 'rest' }; + } + const seg = segs.find(s => time < s.t1) ?? segs[segs.length - 1]; + const f = Math.max(0, Math.min(1, (time - seg.t0) / (seg.t1 - seg.t0))); + const e = seg.kind === 'hop' ? f : 1 - Math.pow(1 - f, 2.2); + const p = seg.p0 + (seg.p1 - seg.p0) * e; + let r = seg.r0 + (seg.r1 - seg.r0) * e; + let h = 0; + if (seg.kind === 'hop') { + h = seg.h * Math.sin(Math.PI * f); + r += Math.sin(Math.PI * f) * 0.03; // arcs out over the fret + } else if (seg.kind === 'settle') { + h = seg.h * Math.sin(Math.PI * Math.min(1, f * 1.6)) * (1 - f); + } + return { wheel, ball: { angle: wheel + p, r, h }, phase: seg.kind === 'roll' ? 'drop' : 'hop' }; + } + + return { + variant, target, targetIndex, seed, omega0, idle, wheelAngle0, + T, + diamondHits: bowl.hits, + hopTs, + hops, + sample, + wheelSpeed: (time) => wheelSpeedAt(omega0, time, idle), + // Which pocket is under the ball (head frame) at `time` — for verify. + pocketUnderBall(time) { + const s = sample(time); + const rel = wrap(s.ball.angle - s.wheel); + return pockets[Math.round(rel / step) % N]; + }, + }; +} diff --git a/src/games/roulette/RouletteGame.js b/src/games/roulette/RouletteGame.js index cd70357..96ed93b 100644 --- a/src/games/roulette/RouletteGame.js +++ b/src/games/roulette/RouletteGame.js @@ -2,670 +2,1459 @@ 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 { - POCKETS, GRID_ROWS, CHIP_AMOUNTS, BET, colorOf, betWins, - createInitialState, placeBet, refundBets, clearLastDeltas, - totalAtRisk, hasActiveBets, getNetResult, spin, resolveSpin, + makeChipStack, makeChipColumn, throwChip, ensureColorChip, SLICE_RY, SLICE_H, FACE, +} from '../../ui/CasinoChips.js'; +import { CasinoDock } from '../../ui/casino/CasinoDock.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; +import { + WHEELS, BET, INSIDE, EVEN_MONEY, CHIP_AMOUNTS, PAYOUT, TYPE_NAME, CALL_BETS, + colorOf, numLabel, isZero, normalizeSpec, maxAddable, spotLimit, placeBet, removeBet, refundBets, + setVariant, createInitialState, resolveSpin, spinResult, totalAtRisk, getNetResult, betLabel, + houseEdge, callBetSpecs, callBetNumbers, dealerCall, findBet, } from './RouletteLogic.js'; -import { chooseBets } from './RouletteAI.js'; +import { chooseBets, chooseLateBets, noteResult } from './RouletteAI.js'; +import { + P, DOCK, WHEEL, wheelCenter, hitBet, spotFor, feltBoxes, numberCenter, seatNames, SEATS, SEAT_ORDER, + railPose, seatPortrait, bankPose, BOARD, CALL, CAM, STACK, NEIGHBOUR_UI, racetrackPoint, RT, RT_GEOM, +} from './RouletteTable.js'; +import { prepareRouletteArt, FELTS, DOLLY } from './RouletteArt.js'; +import { planSpin, GEO, WHEEL_SPEED } from './RouletteBall.js'; +import { RouletteWheel } from './RouletteWheel.js'; -// ─── Layout ────────────────────────────────────────────────────────────────-- const CX = GAME_WIDTH / 2; -const WHEEL = { x: 430, y: 415, r: 185 }; - -// Felt geometry (right side of the screen). -const CELL_W = 84, CELL_H = 70; -const GRID_X = 760, GRID_TOP = 205; -const ZERO_X = 706, ZERO_W = 54; -const COL_X = GRID_X + 12 * CELL_W; // "2 to 1" column boxes -const COL_W = 76; -const DOZ_TOP = GRID_TOP + 3 * CELL_H; -const DOZ_H = 58, DOZ_W = (12 * CELL_W) / 3; -const EVEN_TOP = DOZ_TOP + DOZ_H; -const EVEN_H = 58, EVEN_W = (12 * CELL_W) / 6; -const POT = { x: 1280, y: 350 }; // where win/loss chips fly to/from - -// Seat slots 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; - -// Chip-tray denomination colors (shared look with Craps). -const CHIP_COLORS = { 5: 0xe05c5c, 25: 0x5cb85c, 50: 0x4a90d9, 100: 0x2c2c2c }; - -// Per-player chip identity: seat 0 (you) 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')}`; +const CY = GAME_HEIGHT / 2; +const DOCK_Y = DOCK.y + DOCK.h / 2; +const TWO_PI = Math.PI * 2; +const SPEEDS = { normal: 1, fast: 1.7, turbo: 3 }; +const SPEED_LABEL = { normal: 'Speed: Normal', fast: 'Speed: Fast', turbo: 'Speed: Turbo' }; +const FELT_ORDER = Object.keys(FELTS); +const HISTORY_MAX = 100; +const CAM_R = 300, CAM_TILT = 0.62; const D = { - bg: -2, bgImg: -1, feltBg: 0, cell: 1, cellLabel: 2, zone: 3, hover: 4, - betChip: 6, marker: 7, wheelRim: 8, wheel: 9, ball: 12, - portrait: 20, hl: 25, fx: 40, ui: 50, modal: 60, + bg: -2, playfield: -1, table: 0, input: 1, feltHi: 2, result: 2.5, wheel: 4, stacks: 10, ghost: 11.6, dolly: 12, + flying: 24, badges: 30, cam: 33, dock: 40, ui: 42, dockUi: 44, prompt: 48, modal: 60, tooltip: 70, }; -const TWO_PI = Math.PI * 2; -const STEP = TWO_PI / POCKETS.length; +// Seat identity: portrait rings and the opponents' wheel-chip colours. +const SEAT_COLORS = [0xd4a017, 0x3a8fd6, 0xd8495c, 0x45a34f, 0xa06ad6, 0xe58a2c, 0x2fb8b0]; +const hexStr = (n) => `#${n.toString(16).padStart(6, '0')}`; +const money = (n) => `$${Math.round(n).toLocaleString()}`; + +const HELP = { + [BET.STRAIGHT]: 'One number.', + [BET.SPLIT]: 'Two neighbouring numbers — chip on the line between them.', + [BET.STREET]: 'A row of three numbers — chip on the outer line.', + [BET.TRIO]: 'A zero and the two numbers beside it.', + [BET.CORNER]: 'Four numbers that meet at a corner.', + [BET.FIRST_FOUR]: '0, 1, 2 and 3 together.', + [BET.BASKET]: '0, 00, 1, 2 and 3 — the "top line". The worst bet on the table.', + [BET.SIX_LINE]: 'Two rows of three — six numbers.', + [BET.DOZEN]: 'Twelve numbers. Zeros lose.', + [BET.COLUMN]: 'The twelve numbers in that row of the layout. Zeros lose.', +}; +const EVEN_HELP = 'Even money. Zeros lose'; + +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 RouletteGame extends Phaser.Scene { constructor() { super('RouletteGame'); } 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 = {}; - this.betObjs = []; - this.highlightObjs = []; + this.phase = 'load'; // load | bet | spin | locked | result | over + this.selectedChip = 5; + this.stackObjs = new Map(); // `${pi}:${betKey}` → container + this.railObjs = {}; this.portraits = []; - this.chipBtns = []; - this.startingChips = 2000; - - this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); - this.buildPlayfield(); - this.buildTitle(); - this.buildFelt(); - this.buildWheel(); - this.buildChipTray(); - this.buildButtons(); - - new Button(this, 110, GAME_HEIGHT - 48, 'Leave', () => this.leave(), { - variant: 'ghost', width: 150, fontSize: 20, - }).setDepth(D.ui); - - await this.loadChips(); - this.gs = createInitialState(this.opponents, this.startingChips, auth.user?.username ?? 'You'); - this.buildPortraits(); - this.beginRound(); + this.plates = {}; + this.undo = []; // human actions this window: [[{key, amount}]] + this.lastSnapshot = []; // human bets at the last "no more bets" + this.hover = null; + this.ghosts = []; + this.plan = null; + this.spinT = 0; + this.lateBets = []; + this.history = []; + this.aiMem = []; + this.dolly = null; + this.resultFx = []; + this.camVisible = false; + this.variant = store('roulette-table', 'us'); + if (!WHEELS[this.variant]) this.variant = 'us'; + this.felt = store('roulette-felt', 'green'); + if (!FELTS[this.felt]) this.felt = 'green'; + this.speed = store('roulette-speed', 'normal'); + if (!SPEEDS[this.speed]) this.speed = 'normal'; + this.camOn = store('roulette-cam', 'on') === 'on'; + this.hints = store('roulette-hints', 'off') === 'on'; + this.nbK = Math.max(1, Math.min(4, Number(store('roulette-neighbours', '2')) || 2)); } - // ── Background & title ───────────────────────────────────────────────────-- + // ── 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 prepareRouletteArt(this, this.felt, this.variant); + if (!this.alive()) return; + this.tableImg = this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.feltHi = this.add.graphics().setDepth(D.feltHi); + this.resultG = this.add.graphics().setDepth(D.result); + this.cacheBoxes(); + + this.applySpeed(); + this.buildWheel(); + this.buildDock(); + this.buildTopButtons(); + this.buildBoard(); + this.buildCam(); + this.buildNeighbourUI(); + this.tooltip = new Tooltip(this, { depth: D.tooltip }); + this.buildInput(); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + + const chips = await this.loadChips(); + if (!this.alive()) return; + this.startingChips = chips; + this.gs = createInitialState(this.opponents, chips, auth.user?.username ?? 'You', this.variant); + this.seatOf = seatNames(this.opponents.length); + for (let pi = 1; pi < this.gs.players.length; pi++) ensureColorChip(this, `rw${pi}`, hexStr(SEAT_COLORS[pi])); + this.aiMem = this.gs.players.map(() => ({})); + this.loadHistory(); + this.buildSeats(); + this.renderAllRails(); + this.restBallOn(this.history[this.history.length - 1]); + this.drawBoard(); + this.say(`Welcome to the ${WHEELS[this.variant].name} table — place your bets!`); + this.startBetting(); + } + + alive() { return this.sys.isActive(); } + 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(); } })); + } + + get speedK() { return SPEEDS[this.speed] ?? 1; } + + applySpeed() { + this.tweens.timeScale = this.speedK; + this.time.timeScale = this.speedK; + } + + update(time, delta) { + if (!this.wheel) return; + const dt = Math.min(0.1, delta / 1000) * this.speedK; + if (this.plan) { + const t0 = this.spinT; + this.spinT += dt; + const s = this.plan.sample(this.spinT); + this.wheelAngle = s.wheel; + this.showWheel(s.wheel, s.ball); + this.spinEvents(t0, this.spinT); + } else { + this.wheelSpeed += (WHEEL_SPEED.idle - this.wheelSpeed) * Math.min(1, dt * 0.35); + this.wheelAngle -= this.wheelSpeed * dt; + const ball = this.ballRel == null ? null : { angle: this.wheelAngle + this.ballRel, r: GEO.R_POCKET, h: 0 }; + this.showWheel(this.wheelAngle, ball); + } + if (this.phase === 'spin' && this.plan) { + const left = Math.max(0, (this.plan.T.noMoreBets - this.spinT) / this.speedK); + const lbl = `Bets close ${left.toFixed(1)}`; + if (this.spinBtn.text.text !== lbl) this.spinBtn.setLabel(lbl); + } + if (this.resultFx.length) this.drawResultFx(time); + } + + // ── 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.bgImg); + this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.playfield); } } - buildTitle() { - this.add.text(CX, 52, 'Roulette', { - fontFamily: 'Righteous', fontSize: '50px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - this.statusText = this.add.text(CX, 104, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.ui); + // Screen polygons of every printed box, for hover + result highlights. + cacheBoxes() { + this.boxes = feltBoxes(this.variant).map((b) => ({ + ...b, + pts: [P.project(b.u0, b.v0), P.project(b.u1, b.v0), P.project(b.u1, b.v1), P.project(b.u0, b.v1)], + })); + this.numBox = new Map(this.boxes.filter((b) => b.kind === 'num').map((b) => [b.n, b])); } - // ── Betting felt ─────────────────────────────────────────────────────────── - defineZones() { - const add = (key, type, number, x, y, w, h) => { - this.zones[key] = { type, number, rect: { x, y, w, h }, center: { x: x + w / 2, y: y + h / 2 } }; - }; - // Number grid (3 rows × 12 cols). - GRID_ROWS.forEach((row, r) => { - row.forEach((n, c) => add(`n${n}`, BET.STRAIGHT, n, GRID_X + c * CELL_W, GRID_TOP + r * CELL_H, CELL_W, CELL_H)); - }); - // Zeros. - add('n0', BET.STRAIGHT, 0, ZERO_X, GRID_TOP, ZERO_W, CELL_H * 1.5); - add('n00', BET.STRAIGHT, '00', ZERO_X, GRID_TOP + CELL_H * 1.5, ZERO_W, CELL_H * 1.5); - // Column (2 to 1) boxes — top row is column 3, bottom is column 1. - [3, 2, 1].forEach((colNum, r) => add(`col${colNum}`, BET.COLUMN, colNum, COL_X, GRID_TOP + r * CELL_H, COL_W, CELL_H)); - // Dozens. - [1, 2, 3].forEach((k, i) => add(`doz${k}`, BET.DOZEN, k, GRID_X + i * DOZ_W, DOZ_TOP, DOZ_W, DOZ_H)); - // Even-money row. - const ev = [BET.LOW, BET.EVEN, BET.RED, BET.BLACK, BET.ODD, BET.HIGH]; - ev.forEach((type, i) => add(type, type, null, GRID_X + i * EVEN_W, EVEN_TOP, EVEN_W, EVEN_H)); - } - - buildFelt() { - this.defineZones(); - - // Felt panel behind the layout. - const px = ZERO_X - 8, py = GRID_TOP - 10; - const pw = (COL_X + COL_W) - px + 8, ph = (EVEN_TOP + EVEN_H) - py + 8; - const panel = this.add.graphics().setDepth(D.feltBg); - panel.fillStyle(0x14532d, 0.95); - panel.fillRoundedRect(px, py, pw, ph, 18); - panel.lineStyle(6, COLORS.accent, 0.9); - panel.strokeRoundedRect(px, py, pw, ph, 18); - - const g = this.add.graphics().setDepth(D.cell); - const label = (cx, cy, text, size, color, font = '"Julius Sans One"') => - this.add.text(cx, cy, text, { fontFamily: font, fontSize: `${size}px`, color, fontStyle: 'bold', align: 'center' }) - .setOrigin(0.5).setDepth(D.cellLabel); - - const EVEN_LABEL = { [BET.LOW]: '1 to 18', [BET.EVEN]: 'EVEN', [BET.RED]: 'RED', [BET.BLACK]: 'BLACK', [BET.ODD]: 'ODD', [BET.HIGH]: '19 to 36' }; - - for (const [key, z] of Object.entries(this.zones)) { - const { x, y, w, h } = z.rect; - let fill = 0x0c3b21, alpha = 0.6; // default felt cell - if (z.type === BET.STRAIGHT) { - const col = colorOf(z.number); - fill = col === 'green' ? 0x1b7a3d : col === 'red' ? 0xb23636 : 0x1c1c1c; - alpha = 0.95; - } else if (z.type === BET.RED) { fill = 0xb23636; alpha = 0.95; } - else if (z.type === BET.BLACK) { fill = 0x1c1c1c; alpha = 0.95; } - - g.fillStyle(fill, alpha); - g.fillRoundedRect(x + 2, y + 2, w - 4, h - 4, 6); - g.lineStyle(2, COLORS.accent, 0.55); - g.strokeRoundedRect(x + 2, y + 2, w - 4, h - 4, 6); - - if (z.type === BET.STRAIGHT) { - label(z.center.x, z.center.y, z.number === '00' ? '00' : String(z.number), z.number === 0 || z.number === '00' ? 26 : 24, '#ffffff', 'Righteous'); - } else if (z.type === BET.COLUMN) { - label(z.center.x, z.center.y, '2 to 1', 18, COLORS.textHex); - } else if (z.type === BET.DOZEN) { - label(z.center.x, z.center.y, ['1st 12', '2nd 12', '3rd 12'][z.number - 1], 22, COLORS.textHex); - } else { - const txt = EVEN_LABEL[z.type]; - const c = (z.type === BET.RED || z.type === BET.BLACK) ? '#ffffff' : COLORS.textHex; - label(z.center.x, z.center.y, txt, 22, c); - } - - const zone = this.add.zone(z.center.x, z.center.y, w, h).setDepth(D.zone); - 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.hoverG = this.add.graphics().setDepth(D.hover); - } - - hoverZone(key, on) { - this.hoverG.clear(); - if (!on || !this.bettingEnabled()) return; - const z = this.zones[key]; - this.hoverG.lineStyle(4, COLORS.gold, 1); - this.hoverG.strokeRoundedRect(z.rect.x + 2, z.rect.y + 2, z.rect.w - 4, z.rect.h - 4, 6); - } - - // ── Wheel & ball ─────────────────────────────────────────────────────────-- buildWheel() { - const r = WHEEL.r; - this.wheel = this.add.container(WHEEL.x, WHEEL.y).setDepth(D.wheel); - const g = this.add.graphics(); - this.wheel.add(g); - - // Rim. - g.fillStyle(0x2a1d10, 1); g.fillCircle(0, 0, r + 24); - g.lineStyle(6, COLORS.gold, 1); g.strokeCircle(0, 0, r + 24); - - // Pocket wedges. - const dir = (t) => [Math.sin(t) * r, -Math.cos(t) * r]; - for (let i = 0; i < POCKETS.length; i++) { - const col = colorOf(POCKETS[i]); - const fill = col === 'green' ? 0x1b7a3d : col === 'red' ? 0xc0392b : 0x161616; - const a0 = (i - 0.5) * STEP, a1 = (i + 0.5) * STEP; - g.fillStyle(fill, 1); - g.beginPath(); g.moveTo(0, 0); - const seg = 5; - for (let j = 0; j <= seg; j++) { const [dx, dy] = dir(a0 + (a1 - a0) * (j / seg)); g.lineTo(dx, dy); } - g.closePath(); g.fillPath(); - // Pocket separator. - g.lineStyle(1, 0x0a0a0a, 0.7); - const [sx, sy] = dir(a0); g.beginPath(); g.moveTo(0, 0); g.lineTo(sx, sy); g.strokePath(); - } - - // Inner fret ring + hub. - g.lineStyle(3, COLORS.gold, 0.85); g.strokeCircle(0, 0, r * 0.55); - g.fillStyle(0x6b4e1f, 1); g.fillCircle(0, 0, r * 0.30); - g.lineStyle(3, COLORS.gold, 1); g.strokeCircle(0, 0, r * 0.30); - g.fillStyle(0x2a1d10, 1); g.fillCircle(0, 0, r * 0.12); - - // Number labels (children → spin with the wheel). - for (let i = 0; i < POCKETS.length; i++) { - const t = i * STEP; - const lx = Math.sin(t) * r * 0.82, ly = -Math.cos(t) * r * 0.82; - const txt = this.add.text(lx, ly, POCKETS[i] === '00' ? '00' : String(POCKETS[i]), { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5).setRotation(t); - this.wheel.add(txt); - } - - // Decorative top marker (ball deflector). - const marker = this.add.graphics().setDepth(D.marker); - marker.fillStyle(COLORS.gold, 1); - marker.fillTriangle(WHEEL.x - 12, WHEEL.y - r - 26, WHEEL.x + 12, WHEEL.y - r - 26, WHEEL.x, WHEEL.y - r - 6); - - // Ball. - this.ball = this.add.graphics().setDepth(D.ball); - this.ball.fillStyle(0xffffff, 1); this.ball.fillCircle(0, 0, 7); - this.ball.lineStyle(2, 0xcccccc, 0.8); this.ball.strokeCircle(0, 0, 7); - this.ball.setPosition(WHEEL.x, WHEEL.y - r * 0.66); - - // Result readout under the wheel. - this.resultText = this.add.text(WHEEL.x, WHEEL.y + r + 56, '', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - // Glow for the winning pocket (drawn on resolution). - this.pocketGlow = this.add.graphics().setDepth(D.ball - 1); + const c = wheelCenter(); + this.wheel = new RouletteWheel(this, { x: c.x, y: c.y, R: WHEEL.R, tilt: WHEEL.tilt, depth: D.wheel, variant: this.variant }); + this.wheelAngle = Math.random() * TWO_PI; + this.wheelSpeed = WHEEL_SPEED.idle; + this.ballRel = null; } - animateSpin(index) { - playSound(this, SFX.ROULETTE); - return new Promise((resolve) => { - const r = WHEEL.r; - const winT = index * STEP; - const start = this.wheel.rotation; - const end = start + 5 * TWO_PI + Math.random() * TWO_PI; - const DUR = 4200; - - this.tweens.add({ targets: this.wheel, rotation: end, duration: DUR, ease: 'Cubic.easeOut' }); - - const finalAngle = winT + end; // screen angle of the winning pocket at rest - const span = 8 * TWO_PI; // ball orbits the opposite way and decelerates - const rTrack = r * 0.93, rRest = r * 0.66; - const prog = { p: 0 }; - this.ball.setVisible(true); - this.tweens.add({ - targets: prog, p: 1, duration: DUR, ease: 'Quart.easeOut', - onUpdate: () => { - const p = prog.p; - const a = finalAngle + span * (1 - p); - const t = Phaser.Math.Clamp((p - 0.5) / 0.5, 0, 1); - const radius = rTrack - (rTrack - rRest) * (t * t * (3 - 2 * t)); - const hop = p > 0.82 ? Math.sin((p - 0.82) / 0.18 * Math.PI) * -5 : 0; - this.ball.setPosition(WHEEL.x + Math.sin(a) * radius, WHEEL.y - Math.cos(a) * radius + hop); - }, - onComplete: () => { - this.ball.setPosition(WHEEL.x + Math.sin(finalAngle) * rRest, WHEEL.y - Math.cos(finalAngle) * rRest); - resolve(); - }, - }); - }); + showWheel(angle, ball) { + this.wheel.setAngle(angle).setBall(ball); + if (this.camVisible) this.camWheel.setAngle(angle).setBall(ball); } - // ── Chip tray & buttons ──────────────────────────────────────────────────── - 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); + restBallOn(value) { + const i = value == null ? -1 : WHEELS[this.variant].pockets.indexOf(value); + this.ballRel = i < 0 ? null : i * (TWO_PI / WHEELS[this.variant].pockets.length); + } - 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 }); + // ── Dock ─────────────────────────────────────────────────────────────────── + buildDock() { + this.dock = new CasinoDock(this, { + sceneName: 'RouletteGame', + 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 / wheel chip · click to bet (lines & corners for splits) · right-click remove a chip (shift: all) · Space spin · Z undo · R rebet · D double · 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); - 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); + this.chipRing = this.add.graphics().setDepth(D.dockUi + 2); + this.dock.addToGroup('bet', this.chipRing); + + const ghost = { height: 46, fontSize: 17, variant: 'ghost' }; + this.undoBtn = new Button(this, 1050, DOCK_Y, 'Undo', () => this.onUndo(), { ...ghost, width: 90 }); + this.clearBtn = new Button(this, 1150, DOCK_Y, 'Clear', () => this.onClear(), { ...ghost, width: 90 }); + this.rebetBtn = new Button(this, 1275, DOCK_Y, 'Rebet', () => this.onRebet(), { ...ghost, width: 140 }); + this.doubleBtn = new Button(this, 1410, DOCK_Y, 'Double', () => this.onDouble(), { ...ghost, width: 110 }); + this.spinBtn = new Button(this, 1670, DOCK_Y, 'Spin', () => this.onSpin(), { width: 280, height: 60, fontSize: 24 }); + const btns = [this.undoBtn, this.clearBtn, this.rebetBtn, this.doubleBtn, this.spinBtn]; + 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(); } - buildButtons() { - const y = GAME_HEIGHT - 78; - this.clearBtn = new Button(this, CX + 470, y, 'Clear', () => this.onClear(), { - width: 150, height: 56, fontSize: 20, variant: 'ghost', + cycleChip(dir) { + const i = CHIP_AMOUNTS.indexOf(this.selectedChip); + this.selectChip(CHIP_AMOUNTS[(i + dir + CHIP_AMOUNTS.length) % CHIP_AMOUNTS.length]); + } + + 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.tableBtn = new Button(this, 90, 144, this.tableLabel(), () => this.toggleTable(), opts).setDepth(D.ui); + this.feltBtn = new Button(this, 90, 196, this.feltLabel(), () => this.cycleFelt(), opts).setDepth(D.ui); + this.camBtn = new Button(this, 90, 248, this.camOn ? 'Wheel Cam: On' : 'Wheel Cam: Off', () => this.toggleCam(), opts).setDepth(D.ui); + this.hintBtn = new Button(this, 90, 300, this.hints ? 'Hints: On' : 'Hints: Off', () => this.toggleHints(), opts).setDepth(D.ui); + } + + tableLabel() { return this.variant === 'us' ? 'Table: American' : 'Table: European'; } + feltLabel() { return `Felt: ${this.felt[0].toUpperCase()}${this.felt.slice(1)}`; } + + cycleSpeed() { + const order = Object.keys(SPEEDS); + this.speed = order[(order.indexOf(this.speed) + 1) % order.length]; + save('roulette-speed', this.speed); + this.speedBtn.setLabel(SPEED_LABEL[this.speed]); + this.applySpeed(); + } + + toggleCam() { + this.camOn = !this.camOn; + save('roulette-cam', this.camOn ? 'on' : 'off'); + this.camBtn.setLabel(this.camOn ? 'Wheel Cam: On' : 'Wheel Cam: Off'); + if (!this.camOn && this.camVisible) this.hideCam(); + } + + toggleHints() { + this.hints = !this.hints; + save('roulette-hints', this.hints ? 'on' : 'off'); + this.hintBtn.setLabel(this.hints ? 'Hints: On' : 'Hints: Off'); + if (this.hints) this.startIdlePrompt(); + else this.dock.hidePrompts(); + if (this.hover) this.refreshHover(); + } + + async cycleFelt() { + this.felt = FELT_ORDER[(FELT_ORDER.indexOf(this.felt) + 1) % FELT_ORDER.length]; + save('roulette-felt', this.felt); + this.feltBtn.setLabel(this.feltLabel()); + const key = await prepareRouletteArt(this, this.felt, this.variant); + if (this.alive()) this.tableImg.setTexture(key); + } + + async toggleTable() { + if (this.phase !== 'bet') { this.flashStatus('Change tables between spins.'); return; } + this.variant = this.variant === 'us' ? 'eu' : 'us'; + save('roulette-table', this.variant); + this.tableBtn.setLabel(this.tableLabel()); + // everyone picks their chips back up + this.gs = setVariant(this.gs, this.variant); + this.undo = []; + this.lastSnapshot = []; + this.setHover(null); + this.renderBets(); + this.renderAllRails(); + const key = await prepareRouletteArt(this, this.felt, this.variant); + if (!this.alive()) return; + this.tableImg.setTexture(key); + this.cacheBoxes(); + this.wheel.setVariant(this.variant); + this.camWheel.setVariant(this.variant); + this.loadHistory(); + this.restBallOn(this.history[this.history.length - 1]); + this.clearResultFx(); + this.removeDolly(); + this.drawBoard(); + this.layoutNeighbourUI(); + this.say(this.variant === 'eu' + ? 'European single-zero table — La Partage in effect. Racetrack is open.' + : 'American double-zero table.'); + this.aiBets(); + this.renderBets(); + this.refreshControls(); + this.updatePlates(); + } + + // ── History marquee ──────────────────────────────────────────────────────── + loadHistory() { + let h = []; + try { h = JSON.parse(store(`roulette-history-${this.variant}`, '[]')); } catch { h = []; } + const P = WHEELS[this.variant].pockets; + h = Array.isArray(h) ? h.filter((v) => P.includes(v)) : []; + if (!h.length) { + // a live table you just sat down at already has numbers on the board + for (let i = 0; i < 14; i++) h.push(spinResult(this.variant)); + } + this.history = h.slice(-HISTORY_MAX); + } + + pushHistory(value) { + this.history.push(value); + if (this.history.length > HISTORY_MAX) this.history.shift(); + save(`roulette-history-${this.variant}`, JSON.stringify(this.history)); + } + + buildBoard() { + ensureLeatherPanel(this, 'roulette-board', BOARD.w, BOARD.h, { radius: 16 }); + this.add.image(BOARD.x, BOARD.y, 'roulette-board').setOrigin(0, 0).setDepth(D.ui); + this.boardG = this.add.graphics().setDepth(D.ui + 1); + const txt = (x, y, size, color, origin = 0, font = '"Julius Sans One"') => this.add.text(x, y, '', { + fontFamily: font, fontSize: `${size}px`, color, + }).setOrigin(origin, 0.5).setDepth(D.ui + 2); + this.boardTitle = txt(BOARD.x + 16, BOARD.y + 20, 13, '#d9b45a').setText('LAST SPINS'); + this.boardWheel = txt(BOARD.x + BOARD.w - 16, BOARD.y + 20, 13, '#f2ead8', 1); + this.boardTiles = []; + for (let i = 0; i < 16; i++) { + this.boardTiles.push(this.add.text(0, 0, '', { + fontFamily: 'Righteous, "Julius Sans One"', fontSize: '18px', color: '#ffffff', + }).setOrigin(0.5).setDepth(D.ui + 3)); + } + this.boardBars = [0, 1, 2].map((i) => ({ + left: txt(BOARD.x + 16, BOARD.y + 98 + i * 19, 11, '#f2ead8'), + right: txt(BOARD.x + BOARD.w * 0.62 - 6, BOARD.y + 98 + i * 19, 11, '#f2ead8', 1), + })); + this.boardHot = txt(BOARD.x + BOARD.w * 0.64, BOARD.y + 102, 13, '#ff9a5a'); + this.boardCold = txt(BOARD.x + BOARD.w * 0.64, BOARD.y + 132, 13, '#7fb8ff'); + } + + drawBoard() { + const g = this.boardG; + if (!g) return; + g.clear(); + const recent = this.history.slice(-16).reverse(); + const x0 = BOARD.x + 26, dx = (BOARD.w - 52) / 15, yMid = BOARD.y + 52; + const COL = { red: 0xb3141f, black: 0x16161a, green: 0x127a3a }; + this.boardTiles.forEach((t, i) => { + const v = recent[i]; + if (v == null) { t.setText(''); return; } + const col = colorOf(v); + const x = x0 + i * dx; + const y = yMid + (col === 'red' ? -8 : col === 'black' ? 8 : 0); // tower columns: red up, black down + const w = i === 0 ? 34 : 28, h = i === 0 ? 30 : 24; + g.fillStyle(COL[col], i === 0 ? 1 : 0.92 - i * 0.025); + g.fillRoundedRect(x - w / 2, y - h / 2, w, h, 5); + g.lineStyle(i === 0 ? 2 : 1, i === 0 ? 0xf5d020 : 0xf2ead8, i === 0 ? 1 : 0.35); + g.strokeRoundedRect(x - w / 2, y - h / 2, w, h, 5); + t.setPosition(x, y).setText(numLabel(v)).setFontSize(i === 0 ? 19 : 15).setAlpha(i === 0 ? 1 : 0.95 - i * 0.03); }); - this.clearBtn.setDepth(D.ui); - this.spinBtn = new Button(this, CX + 680, y, 'Spin', () => this.onSpin(), { - width: 200, height: 64, fontSize: 26, - }); - this.spinBtn.setDepth(D.ui); - } + this.boardWheel.setText(`${WHEELS[this.variant].name.toUpperCase()} · ${this.history.length} SPINS`); - // ── Portraits ────────────────────────────────────────────────────────────── - buildPortraits() { - for (let i = 0; i < this.gs.players.length; i++) { - const x = SEAT_X[i]; - const p = this.gs.players[i]; - let ctrl; - if (i === 0) ctrl = createPlayerPortrait(this, x, SEAT_Y, PORTRAIT_R, D.portrait, 'RouletteGame'); - else ctrl = createOpponentPortrait(this, p.avatar, x, SEAT_Y, PORTRAIT_R, D.portrait); - this.portraits.push(ctrl); - - // Color swatch ring matching this player's chip identity. - const ring = this.add.graphics().setDepth(D.portrait + 1); - ring.lineStyle(4, SEAT_COLORS[i % SEAT_COLORS.length], 1); - ring.strokeCircle(x, SEAT_Y, PORTRAIT_R + 5); - - this.add.text(x, SEAT_Y + PORTRAIT_R + 16, this.shortName(p.name), { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: hexStr(SEAT_COLORS[i % SEAT_COLORS.length]), - }).setOrigin(0.5).setDepth(D.ui); - } - this.updateBalances(); - } - - shortName(name) { - return name.length > 10 ? name.slice(0, 9) + '…' : name; - } - - // ── Bet rendering (every player's chips, color-coded with names) ───────────-- - zoneKeyForBet(bet) { - switch (bet.type) { - case BET.STRAIGHT: return `n${bet.number}`; - case BET.DOZEN: return `doz${bet.number}`; - case BET.COLUMN: return `col${bet.number}`; - default: return bet.type; - } - } - - renderBets() { - for (const o of this.betObjs) o.destroy(); - this.betObjs = []; - - const groups = new Map(); - for (let pi = 0; pi < this.gs.players.length; pi++) { - for (const bet of this.gs.players[pi].bets) { - const key = this.zoneKeyForBet(bet); - const z = this.zones[key]; - if (!z) continue; - if (!groups.has(key)) groups.set(key, []); - groups.get(key).push({ pi, bet, z }); + // percentage bars + const hs = this.history; + const n = Math.max(1, hs.length); + const count = (f) => hs.filter(f).length; + const red = count((v) => colorOf(v) === 'red'), black = count((v) => colorOf(v) === 'black'), green = n - red - black; + const odd = count((v) => !isZero(v) && v % 2 === 1), even = count((v) => !isZero(v) && v % 2 === 0); + const d1 = count((v) => !isZero(v) && v <= 12), d2 = count((v) => !isZero(v) && v > 12 && v <= 24), d3 = count((v) => !isZero(v) && v > 24); + const bars = [ + { parts: [[red, 0xc0202b], [green, 0x1f9a4c], [black, 0x2a2a30]], l: `RED ${Math.round(red / n * 100)}%`, r: `BLACK ${Math.round(black / n * 100)}%` }, + { parts: [[odd, 0x8a6a2a], [n - odd - even, 0x1f9a4c], [even, 0x4a5a7a]], l: `ODD ${Math.round(odd / n * 100)}%`, r: `EVEN ${Math.round(even / n * 100)}%` }, + { parts: [[d1, 0x6b4a8a], [d2, 0x8a6a2a], [d3, 0x2a6a7a], [n - d1 - d2 - d3, 0x1f9a4c]], l: 'DOZENS', r: `${Math.round(d1 / n * 100)} · ${Math.round(d2 / n * 100)} · ${Math.round(d3 / n * 100)}%` }, + ]; + const bx0 = BOARD.x + 92, bx1 = BOARD.x + BOARD.w * 0.62 - 84; + bars.forEach((b, i) => { + const y = BOARD.y + 92 + i * 19; + let x = bx0; + const tot = b.parts.reduce((a, p) => a + p[0], 0) || 1; + for (const [k, c] of b.parts) { + const w = (bx1 - bx0) * (k / tot); + g.fillStyle(c, 1); + g.fillRect(x, y, w, 12); + x += w; } - } + g.lineStyle(1, 0xf2ead8, 0.25); + g.strokeRect(bx0, y, bx1 - bx0, 12); + this.boardBars[i].left.setText(b.l).setY(y + 6).setX(BOARD.x + 16); + this.boardBars[i].right.setText(b.r).setY(y + 6).setX(BOARD.x + BOARD.w * 0.62 + 2).setOrigin(1, 0.5); + }); + // hot & cold + const freq = new Map(); + for (const v of WHEELS[this.variant].pockets) freq.set(v, 0); + for (const v of hs) freq.set(v, (freq.get(v) ?? 0) + 1); + const sorted = [...freq.entries()].sort((a, b) => b[1] - a[1]); + const hot = sorted.slice(0, 4).map((e) => numLabel(e[0])); + const cold = sorted.slice(-4).reverse().map((e) => numLabel(e[0])); + this.boardHot.setText(`HOT ${hot.join(' · ')}`); + this.boardCold.setText(`COLD ${cold.join(' · ')}`); + } - for (const entries of groups.values()) { - const z = entries[0].z; - const n = entries.length; - const spacing = Math.min(30, Math.max(20, (z.rect.w - 12) / n)); - const nameBelow = z.rect.y < EVEN_TOP - 1; // names below, except bottom rows → above - entries.forEach((e, idx) => { - const x = z.center.x + (idx - (n - 1) / 2) * spacing; - const y = z.center.y - 2; - this.drawBetChip(x, y, e.pi, e.bet.amount, this.shortName(this.gs.players[e.pi].name), nameBelow); + // ── Wheel cam ────────────────────────────────────────────────────────────── + buildCam() { + ensureLeatherPanel(this, 'roulette-cam', CAM.w, CAM.h, { radius: 22, felt: '#15100b' }); + this.camPanel = this.add.image(CAM.x, CAM.y, 'roulette-cam').setOrigin(0, 0).setDepth(D.cam); + const L = this.camLayoutY(); + this.camWheel = new RouletteWheel(this, { x: CAM.x + CAM.w / 2, y: L, R: CAM_R, tilt: CAM_TILT, depth: D.cam + 1, variant: this.variant }); + this.camLabel = this.add.text(CAM.x + 34, CAM.y + 36, '● LIVE · WHEEL CAM', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#ff6a5a', + }).setOrigin(0, 0.5).setDepth(D.cam + 2); + this.camResult = this.add.container(CAM.x + CAM.w - 110, CAM.y + 92).setDepth(D.cam + 2); + this.camParts = [this.camPanel, this.camLabel, this.camResult]; + this.setCamOffset(GAME_WIDTH); + this.camParts.forEach((p) => p.setVisible(false)); + this.camWheel.setVisible(false); + } + + camLayoutY() { + const k = Math.sqrt(1 - CAM_TILT * CAM_TILT); + return CAM.y + 40 + CAM_R * 1.12 * CAM_TILT + CAM_R * 0.2 * k; + } + + setCamOffset(dx) { + this.camDX = dx; + this.camPanel.setX(CAM.x + dx); + this.camLabel.setX(CAM.x + 34 + dx); + this.camResult.setX(CAM.x + CAM.w - 110 + dx); + this.camWheel.setPosition(CAM.x + CAM.w / 2 + dx, this.camLayoutY()); + } + + showCam() { + if (!this.camOn || this.camVisible) return; + this.camVisible = true; + this.camResult.removeAll(true); + this.camParts.forEach((p) => p.setVisible(true)); + this.camWheel.setVariant(this.variant); + this.camWheel.setVisible(true); + this.camWheel.setHighlight(null); + this.setHover(null); + const prox = { dx: GAME_WIDTH - CAM.x }; + this.tweens.killTweensOf(this.camProx ?? {}); + this.camProx = prox; + this.setCamOffset(prox.dx); + this.tweens.add({ targets: prox, dx: 0, duration: 520, ease: 'Cubic.easeOut', onUpdate: () => this.setCamOffset(prox.dx) }); + } + + async hideCam() { + if (!this.camVisible) return; + const prox = { dx: this.camDX }; + this.tweens.killTweensOf(this.camProx ?? {}); + this.camProx = prox; + await this.tweenP({ targets: prox, dx: GAME_WIDTH - CAM.x, duration: 420, ease: 'Cubic.easeIn', onUpdate: () => this.setCamOffset(prox.dx) }); + if (this.camProx !== prox) return; + this.camVisible = false; + this.camParts.forEach((p) => p.setVisible(false)); + this.camWheel.setVisible(false); + } + + // ── Neighbour stepper (European racetrack) ───────────────────────────────── + buildNeighbourUI() { + const p = P.project(NEIGHBOUR_UI.u, NEIGHBOUR_UI.v); + const t = (x, y, s, size, color) => this.add.text(x, y, s, { + fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.ui); + this.nbTitle = t(p.x, p.y - 22, 'NEIGHBOURS', 11, '#e8c15a'); + this.nbVal = t(p.x, p.y + 4, String(this.nbK), 22, '#f4ecd6'); + const btn = (dx, label, d) => { + const b = t(p.x + dx, p.y + 4, label, 22, '#e8c15a').setInteractive({ useHandCursor: true }); + b.on('pointerdown', (ptr) => { ptr.event?.stopPropagation?.(); this.stepNeighbours(d); }); + b.on('pointerover', () => b.setColor('#ffffff')); + b.on('pointerout', () => b.setColor('#e8c15a')); + return b; + }; + this.nbMinus = btn(-30, '−', -1); + this.nbPlus = btn(30, '+', 1); + this.nbParts = [this.nbTitle, this.nbVal, this.nbMinus, this.nbPlus]; + this.layoutNeighbourUI(); + } + + layoutNeighbourUI() { + const on = this.variant === 'eu'; + this.nbParts.forEach((o) => o.setVisible(on)); + this.nbVal.setText(String(this.nbK)); + } + + stepNeighbours(d) { + this.nbK = Math.max(1, Math.min(4, this.nbK + d)); + save('roulette-neighbours', String(this.nbK)); + this.nbVal.setText(String(this.nbK)); + playSound(this, SFX.CHIP_BET); + if (this.hover) this.refreshHover(); + } + + // ── 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 = SEATS[seat].side === 'end'; + 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.updatePlates(); + } + + updatePlates() { + if (!this.gs) return; + 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]; + 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 SPIN ${last > 0 ? '+' : last < 0 ? '−' : ''}${money(Math.abs(last))}`) + .setColor(last > 0 ? '#9be07a' : last < 0 ? '#ff9a8a' : COLORS.textHex); + } + + // ── Rail chips ───────────────────────────────────────────────────────────── + railColumns(pi, amount) { + if (pi !== 0) { + // opponents rack their wheel chips: one column per $200, ten high + const n = Math.min(5, Math.ceil(amount / 200)); + return Array.from({ length: n }, (_, i) => ({ d: `rw${pi}`, n: i === n - 1 ? Math.max(1, Math.ceil((amount % 200 || 200) / 20)) : 10 })); + } + 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; + } + + renderRail(pi) { + for (const o of this.railObjs[pi] ?? []) o.destroy(); + const seat = this.seatOf[pi]; + const cols = this.railColumns(pi, this.gs.players[pi].chips); + const step = SEATS[seat].side === 'end' ? 0.045 : 0.032; + this.railObjs[pi] = cols.map((col, i) => { + const off = (i - (cols.length - 1) / 2) * step; + const p = railPose(seat, off); + return makeChipColumn(this, p.x, p.y + 4 * p.s, col.d, col.n, { size: 34 * p.s, depth: D.stacks - 1 + p.y / 10000, seed: i + pi * 3 }); + }); + } + + 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 ───────────────────────────────────────────────────────────── + layoutBets() { + const byKey = new Map(); + this.gs.players.forEach((p, pi) => p.bets.forEach((b) => { + if (!byKey.has(b.key)) byKey.set(b.key, []); + byKey.get(b.key).push({ pi, b }); + })); + const out = new Map(); + for (const [key, list] of byKey) { + list.sort((a, c) => SEAT_ORDER.indexOf(this.seatOf[a.pi]) - SEAT_ORDER.indexOf(this.seatOf[c.pi])); + const spot = spotFor(list[0].b, this.variant); + if (!spot) continue; + list.forEach(({ pi, b }, index) => { + const du = (index - (list.length - 1) / 2) * 0.026; + const p = P.project(spot.u + du, spot.v - (list.length > 1 ? index * 0.004 : 0)); + const size = (pi === 0 ? STACK.human : STACK.ai) * p.s; + out.set(`${pi}:${key}`, { pi, bet: b, key, amount: b.amount, x: p.x, y: p.y, s: p.s, size }); }); } + return out; } - drawBetChip(x, y, playerIndex, amount, name, nameBelow) { - 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, 15); - g.lineStyle(3, 0xffffff, 0.6); g.strokeCircle(0, 0, 15); - const amt = this.add.text(0, 0, `${amount}`, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5); - const label = this.add.text(0, nameBelow ? 24 : -24, name, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: hexStr(color), fontStyle: 'bold', - stroke: '#000000', strokeThickness: 3, - }).setOrigin(0.5); - c.add([g, amt, label]); - this.betObjs.push(c); + makeBetStack(m) { + let st; + if (m.pi === 0) { + st = makeChipStack(this, m.x, m.y, m.amount, { size: m.size, depth: D.stacks + m.y / 10000, seed: m.amount, label: false, maxChips: 10 }); + } else { + const n = Math.max(1, Math.min(10, Math.ceil(m.amount / 5))); + st = makeChipColumn(this, m.x, m.y, `rw${m.pi}`, n, { size: m.size, depth: D.stacks + m.y / 10000, seed: m.pi * 11 + n }); + } + st.chipSize = m.size; + st._meta = { amount: m.amount, x: m.x, y: m.y, pi: m.pi }; + return st; } - updateBalances() { + // Bring the felt in line with the state. Opponents' new stacks fly in from + // their rail; stacks that disappear (undo / clear / take-down) go home. + renderBets({ animate = true } = {}) { + const want = this.layoutBets(); + for (const [key, st] of this.stackObjs) { + if (want.has(key)) continue; + this.stackObjs.delete(key); + this.tweens.killTweensOf(st); + if (animate && this.gs) { + const dst = this.railSource(st._meta.pi); + this.tweens.add({ targets: st, x: dst.x, y: dst.y, scale: 0.6, alpha: 0, duration: 380, ease: 'Cubic.easeIn', onComplete: () => st.destroy() }); + } else st.destroy(); + } + 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: 300, ease: 'Cubic.easeInOut' }); + else st.setPosition(m.x, m.y); + } + continue; + } + st?.destroy(); + const nst = this.makeBetStack(m); + this.stackObjs.set(key, nst); + if (animate && !st && 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++ * 55, ease: 'Cubic.easeOut', + }); + } + } + } + + // ── Input ────────────────────────────────────────────────────────────────── + buildInput() { + this.input.mouse?.disableContextMenu(); + const zone = this.add.zone(CX, CY, GAME_WIDTH, GAME_HEIGHT).setDepth(D.input).setInteractive(); + zone.on('pointermove', (p) => this.setHover(this.pick(p.worldX, p.worldY))); + zone.on('pointerout', () => this.setHover(null)); + zone.on('pointerdown', (p) => this.onFeltDown(p)); + this.input.on('wheel', (_p, _o, _dx, dy) => { if (dy) this.cycleChip(dy > 0 ? -1 : 1); }); + } + + // What is under the pointer: one of your stacks, a bet spot, or a racetrack call. + pick(x, y) { + if (!this.gs || y >= DOCK.y) return null; + if (this.camVisible && x >= CAM.x + this.camDX && x <= CAM.x + this.camDX + CAM.w && y >= CAM.y && y <= CAM.y + CAM.h) return null; + let best = null; + for (const [key, st] of this.stackObjs) { + if (st._meta.pi !== 0) continue; + const sz = st.chipSize; + const top = st.stackTopY ?? -sz * 0.3; + if (x < st.x - sz * 0.55 || x > st.x + sz * 0.55 || y > st.y + sz * 0.25 || y < st.y + top) continue; + if (!best || st.depth > best.st.depth) best = { key, st }; + } + if (best) { + const bet = findBet(this.gs.players[0], best.key.slice(2)); + if (bet) return { kind: 'bet', type: bet.type, numbers: bet.numbers, number: bet.number, key: bet.key, stack: true }; + } + return hitBet(x, y, this.variant); + } + + sameHover(a, b) { + if (!a || !b) return a === b; + if (a.kind !== b.kind) return false; + if (a.kind === 'bet') return a.key === b.key; + return a.call === b.call && a.number === b.number; + } + + setHover(h) { + if (this.sameHover(h, this.hover)) return; + this.hover = h; + this.refreshHover(); + } + + canBet() { return (this.phase === 'bet' || this.phase === 'spin') && !!this.gs; } + + // Specs a hover/click stands for (one bet, or a whole call bet). + specsFor(h, unit = this.selectedChip) { + if (!h) return []; + if (h.kind === 'bet') return [{ type: h.type, numbers: h.numbers, number: h.number, amount: unit }]; + if (h.kind === 'call') { + if (h.call === 'neighbours') return callBetSpecs(this.variant, 'neighbours', unit, { number: h.number, k: this.nbK }); + return callBetSpecs(this.variant, h.call, unit); + } + return []; + } + + coveredNumbers(h) { + if (!h) return []; + if (h.kind === 'call') { + return h.call === 'neighbours' ? callBetNumbers(this.variant, 'neighbours', { number: h.number, k: this.nbK }) : callBetNumbers(this.variant, h.call); + } + return normalizeSpec(this.variant, h)?.numbers ?? []; + } + + refreshHover() { + const h = this.hover; + const active = h && this.canBet(); + this.input.setDefaultCursor(active ? 'pointer' : 'default'); + this.drawFeltHighlights(); + this.hoverTimer?.remove(); + this.tooltip.hide(); + if (!h || this.phase === 'locked' || this.phase === 'result') return; + this.hoverTimer = this.time.delayedCall(260, () => { + 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); + }); + } + + drawFeltHighlights() { + const g = this.feltHi; + g.clear(); + this.ghosts.forEach((o) => o.destroy()); + this.ghosts = []; + const h = this.hover; + if (!h || !this.canBet()) { this.wheel.setHighlight(this.resultFx.length ? [this.lastValue] : null); return; } + const nums = this.coveredNumbers(h); + const set = new Set(nums); + // the outside box itself + if (h.kind === 'bet' && !INSIDE.has(h.type)) { + const box = this.boxes.find((b) => b.kind === 'out' && b.type === h.type && (b.number ?? null) === (h.number ?? null)); + if (box) this.fillPoly(g, box.pts, 0xf5d020, 0.22, 3); + } + for (const n of set) { + const b = this.numBox.get(n); + if (b) this.fillPoly(g, b.pts, 0xf5d020, h.kind === 'bet' && !INSIDE.has(h.type) ? 0.12 : 0.28, 2); + } + if (this.variant === 'eu') this.drawRacetrackMarks(g, set, h); + this.wheel.setHighlight(nums, 0xf5d020, 0.85); + // ghost chips where they would land + const specs = this.specsFor(h); + for (const s of specs.slice(0, 12)) { + const norm = normalizeSpec(this.variant, s); + if (!norm) continue; + const spot = spotFor(norm, this.variant); + const p = P.project(spot.u, spot.v); + const denom = CHIP_AMOUNTS.includes(this.selectedChip) ? this.selectedChip : 5; + const k = (STACK.human * p.s) / FACE; + const img = this.add.image(p.x, p.y, `chip-slice-${denom}`) + .setOrigin(0.5, (SLICE_RY + 2 + 11) / SLICE_H).setScale(k).setAlpha(0.55).setDepth(D.ghost); + this.ghosts.push(img); + } + } + + fillPoly(g, pts, color, alpha, line) { + g.fillStyle(color, alpha); + g.beginPath(); + pts.forEach((p, i) => (i ? g.lineTo(p.x, p.y) : g.moveTo(p.x, p.y))); + g.closePath(); + g.fillPath(); + if (line) { + g.lineStyle(line, color, 0.9); + g.strokePath(); + } + } + + drawRacetrackMarks(g, set, h) { + const pockets = WHEELS.eu.pockets; + const step = RT_GEOM.PER / pockets.length; + const rOut = RT_GEOM.R - RT_GEOM.RC, rIn = RT_GEOM.R - RT.band - RT_GEOM.RC; + pockets.forEach((v, i) => { + if (!set.has(v)) return; + const pts = []; + for (let k = 0; k <= 4; k++) { + const c = racetrackPoint((i - 0.5 + k / 4) * step); + pts.push(P.project(c.u + c.nu * rOut, c.v + c.nv * rOut)); + } + for (let k = 4; k >= 0; k--) { + const c = racetrackPoint((i - 0.5 + k / 4) * step); + pts.push(P.project(c.u + c.nu * rIn, c.v + c.nv * rIn)); + } + this.fillPoly(g, pts, 0xf5d020, h.kind === 'call' && h.number === v ? 0.55 : 0.3, 1.5); + }); + } + + tooltipFor(h) { + const gs = this.gs; + const unit = this.selectedChip; + const human = gs.players[0]; + if (h.kind === 'call') { + const specs = this.specsFor(h); + const nums = this.coveredNumbers(h); + const chips = specs.reduce((a, s) => a + s.amount, 0) / unit; + const title = h.call === 'neighbours' ? `${numLabel(h.number)} and ${this.nbK} neighbours` : CALL_BETS[h.call].name; + const lines = [ + { text: `${chips} chips × ${money(unit)} = ${money(chips * unit)} · covers ${nums.length} numbers` }, + { text: nums.map(numLabel).join(' '), color: '#d9b45a' }, + ]; + if (h.call === 'neighbours') lines.push({ text: 'Straight-ups on the number and its neighbours on the wheel. Use − / + to change how many.', color: '#c9c2b0' }); + else lines.push({ text: 'A French call bet: a fixed set of chips covering a section of the wheel.', color: '#c9c2b0' }); + if (!this.canBet()) lines.push({ text: 'Bets are closed.', color: '#ff9a8a' }); + return { title, lines }; + } + const norm = normalizeSpec(this.variant, h); + if (!norm) return null; + const lines = []; + const help = INSIDE.has(norm.type) || norm.type === BET.DOZEN || norm.type === BET.COLUMN + ? HELP[norm.type] + : `${EVEN_HELP}${WHEELS[this.variant].partage ? ' half (La Partage).' : '.'}`; + lines.push({ text: help }); + lines.push({ text: `Pays ${PAYOUT[norm.type]} to 1 · covers ${norm.numbers.length} number${norm.numbers.length > 1 ? 's' : ''}`, color: '#f5d020' }); + const mine = findBet(human, norm.key); + const room = maxAddable(gs, 0, norm); + const add = Math.min(unit, room); + if (add > 0) lines.push({ text: `A ${money(add)} chip wins ${money(add * PAYOUT[norm.type])}`, color: '#9be07a' }); + else if (spotLimit(norm.type) - (mine?.amount ?? 0) <= 0) lines.push({ text: `At the table max (${money(spotLimit(norm.type))})`, color: '#ff9a8a' }); + if (mine) lines.push({ text: `Your bet: ${money(mine.amount)} — wins ${money(mine.amount * PAYOUT[norm.type])} · right-click to remove`, color: '#f2ead8' }); + const others = gs.players.slice(1).map((p, i) => ({ p, b: findBet(p, norm.key), pi: i + 1 })).filter((o) => o.b); + if (others.length) lines.push({ text: `Also here: ${others.map((o) => `${o.p.name} ${money(o.b.amount)}`).join(', ')}`, color: '#c9c2b0' }); + if (this.hints) { + const edge = houseEdge(norm, this.variant); + let note = `House edge ${(edge * 100).toFixed(2)}%`; + if (norm.type === BET.BASKET) note += ' — the worst bet on the table'; + else if (this.variant === 'eu' && EVEN_MONEY.has(norm.type)) note += ' — the best bet here, thanks to La Partage'; + else if (this.variant === 'us') note += ' — every American bet but the basket'; + lines.push({ text: note, color: '#e8c15a' }); + lines.push({ text: `Table max ${money(spotLimit(norm.type))} on this spot`, color: '#c9c2b0' }); + } + if (!this.canBet()) lines.push({ text: 'Bets are closed.', color: '#ff9a8a' }); + return { title: betLabel(norm), lines }; + } + + onFeltDown(p) { + if (!this.gs) return; + const h = this.pick(p.worldX, p.worldY); + if (!h || !this.canBet()) return; + const right = p.rightButtonDown(); + if (h.kind === 'bet' && right) { + const all = p.event?.shiftKey; + this.removeHuman(h.key, all ? Infinity : this.selectedChip); + return; + } + if (right) return; + this.addHuman(this.specsFor(h)); + } + + // ── Human betting ────────────────────────────────────────────────────────── + // Place several specs as one action (a call bet, rebet, double). + addHuman(specs, { quiet = false } = {}) { + if (!this.canBet() || !specs.length) return false; const human = this.gs.players[0]; - this.balanceText.setText(`Balance $${human.chips.toLocaleString()}`); + const total = specs.reduce((a, s) => a + s.amount, 0); + if (total > human.chips) { + if (!quiet) this.flashStatus(specs.length > 1 ? `That needs ${money(total)} — you have ${money(human.chips)}.` : 'Not enough chips.'); + return false; + } + const placed = []; + for (const spec of specs) { + const norm = normalizeSpec(this.variant, spec); + if (!norm) continue; + const room = maxAddable(this.gs, 0, norm); + const amt = Math.min(spec.amount, room); + if (amt < 1) { + if (!quiet && specs.length === 1) this.flashStatus(`Table max is ${money(spotLimit(norm.type))} on a ${TYPE_NAME[norm.type].toLowerCase()} bet.`); + continue; + } + if (amt < spec.amount && !quiet && specs.length === 1) this.flashStatus(`Topped up to the ${money(spotLimit(norm.type))} table max.`); + const before = this.gs; + this.gs = placeBet(this.gs, 0, { ...norm, amount: amt }); + if (this.gs === before) continue; + placed.push({ key: norm.key, amount: amt }); + } + if (!placed.length) return false; + this.undo.push(placed); + this.afterHumanBet(placed); + return true; } - // ── Human betting ────────────────────────────────────────────────────────-- - bettingEnabled() { - return !!this.gs && !this.animating && this.gs.phase !== 'gameover'; + afterHumanBet(placed) { + const want = this.layoutBets(); + const btn = this.dock.chipButton(this.selectedChip); + const src = btn ? { x: btn.img.x, y: btn.img.y } : this.dock.sourcePos(); + let pending = 0; + placed.slice(0, 12).forEach((pl, i) => { + const m = want.get(`0:${pl.key}`); + if (!m) return; + pending++; + const denom = [100, 50, 25, 5, 1].find((d) => d <= pl.amount) ?? 1; + throwChip(this, denom, src, { x: m.x, y: m.y, s: m.s }, { + size: STACK.human, depth: D.flying, delay: i * 45, sound: () => playChipBet(this), + }).then(() => { if (this.alive() && --pending === 0) this.renderBets(); }); + }); + if (!pending) this.renderBets(); + this.dock.hidePrompts(); + this.renderRail(0); + this.updatePlates(); + this.refreshControls(); + if (this.hover) this.refreshHover(); } - onZoneClick(key) { - if (!this.bettingEnabled()) return; - const z = this.zones[key]; - 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; - playChipBet(this); + removeHuman(key, amount) { + const bet = findBet(this.gs.players[0], key); + if (!bet) return; + const take = Math.min(bet.amount, amount); + this.gs = removeBet(this.gs, 0, key, take); + // forget that much of this spot from the undo history + let rest = take; + for (let i = this.undo.length - 1; i >= 0 && rest > 0; i--) { + for (const e of this.undo[i]) { + if (e.key !== key || rest <= 0) continue; + const k = Math.min(e.amount, rest); + e.amount -= k; rest -= k; + } + this.undo[i] = this.undo[i].filter((e) => e.amount > 0); + if (!this.undo[i].length) this.undo.splice(i, 1); + } + playSound(this, SFX.CHIP_BET); this.renderBets(); - this.updateBalances(); + this.renderRail(0); + this.updatePlates(); + this.refreshControls(); + this.refreshHover(); + } + + onUndo() { + if (!this.canBet() || !this.undo.length) return; + const action = this.undo.pop(); + for (const e of action) this.gs = removeBet(this.gs, 0, e.key, e.amount); + playSound(this, SFX.CHIP_BET); + this.renderBets(); + this.renderRail(0); + this.updatePlates(); this.refreshControls(); } onClear() { - if (!this.bettingEnabled()) return; + if (!this.canBet() || !this.gs.players[0].bets.length) return; this.gs = refundBets(this.gs, 0); + this.undo = []; + playSound(this, SFX.CHIP_BET); this.renderBets(); - this.updateBalances(); + this.renderRail(0); + this.updatePlates(); this.refreshControls(); } + rebetPlan() { + if (!this.gs || this.gs.players[0].bets.length) return []; + return this.lastSnapshot.filter((s) => normalizeSpec(this.variant, s)); + } + + onRebet() { + if (!this.canBet()) return; + const plan = this.rebetPlan(); + if (!plan.length) { this.flashStatus(this.gs.players[0].bets.length ? 'Rebet puts back last spin\'s bets on an empty layout — try Double.' : 'Nothing to rebet yet.'); return; } + this.addHuman(plan); + } + + onDouble() { + if (!this.canBet()) return; + const bets = this.gs.players[0].bets; + if (!bets.length) { this.flashStatus('Nothing on the layout to double.'); return; } + this.addHuman(bets.map((b) => ({ type: b.type, numbers: b.numbers, number: b.number, amount: b.amount }))); + } + refreshControls() { - const canBet = this.bettingEnabled(); - this.spinBtn.setEnabled(canBet); - this.clearBtn.setEnabled(canBet && hasActiveBets(this.gs.players[0])); + if (!this.gs) return; + const open = this.canBet(); + const human = this.gs.players[0]; + this.undoBtn.setEnabled(open && this.undo.length > 0); + this.clearBtn.setEnabled(open && human.bets.length > 0); + const rb = open ? 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'); + const dbl = totalAtRisk(human); + this.doubleBtn.setEnabled(open && dbl > 0 && dbl <= human.chips); + this.spinBtn.setEnabled(this.phase === 'bet'); + if (this.phase === 'bet') this.spinBtn.setLabel('Spin'); + else if (this.phase === 'locked') this.spinBtn.setLabel('No more bets'); + else if (this.phase === 'result') this.spinBtn.setLabel('Paying…'); + this.dock.setChipStates((amt) => amt <= human.chips); + this.drawFeltHighlights(); + } + + flashStatus(msg) { this.say(msg, '#ffcf9a', 1800); } + + // ── Dealer / 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); + const maxW = 700; + if (t.width > maxW - 56) t.setScale((maxW - 56) / t.width); + const w = Math.min(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(); }, + }); + } + + 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() }); + } + + // A big number disc popping over the wheel (and in the cam). + numberBadge(x, y, value, size = 1, parent = null) { + const col = colorOf(value); + const fill = col === 'red' ? 0xc0202b : col === 'black' ? 0x16161a : 0x1f9a4c; + const c = this.add.container(x, y).setDepth(D.badges); + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.45); g.fillCircle(3, 5, 46 * size); + g.fillStyle(fill, 1); g.fillCircle(0, 0, 44 * size); + g.lineStyle(4 * size, 0xf5d020, 1); g.strokeCircle(0, 0, 44 * size); + const t = this.add.text(0, 2, numLabel(value), { + fontFamily: 'Righteous, "Julius Sans One"', fontSize: `${Math.round(46 * size)}px`, color: '#ffffff', + }).setOrigin(0.5); + c.add([g, t]); + if (parent) { c.setPosition(0, 0); parent.add(c); } + c.setScale(0.3).setAlpha(0); + this.tweens.add({ targets: c, scale: 1, alpha: 1, duration: 320, ease: 'Back.easeOut' }); + return c; + } + + // Short filtered-noise clicks for diamond strikes and fret hops. + tick(vol = 0.25, freq = 2600) { + const sm = this.sound; + const ctx = sm?.context; + if (!ctx || sm.mute || typeof ctx.createBufferSource !== 'function') return; + try { + if (!this._tickBuf) { + const len = Math.floor(ctx.sampleRate * 0.035); + const b = ctx.createBuffer(1, len, ctx.sampleRate); + const d = b.getChannelData(0); + for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, 5); + this._tickBuf = b; + } + const src = ctx.createBufferSource(); + src.buffer = this._tickBuf; + src.playbackRate.value = 0.8 + Math.random() * 0.5; + const f = ctx.createBiquadFilter(); + f.type = 'bandpass'; f.frequency.value = freq; f.Q.value = 2.2; + const gain = ctx.createGain(); + gain.gain.value = vol; + src.connect(f); f.connect(gain); gain.connect(sm.destination ?? ctx.destination); + src.start(); + } catch { /* audio unavailable */ } } // ── Round flow ───────────────────────────────────────────────────────────── - beginRound() { - this.clearHighlights(); - this.gs = clearLastDeltas(this.gs); - this.aiBet(); + 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.updateBalances(); - this.setStatus('Place your bets, then Spin.'); this.refreshControls(); + this.updatePlates(); + this.startIdlePrompt(); + if (this.hover) this.refreshHover(); } - aiBet() { - for (let i = 1; i < this.gs.players.length; i++) { - for (const spec of chooseBets(this.gs.players[i], this.gs)) { - this.gs = placeBet(this.gs, i, spec); + startIdlePrompt() { + if (!this.hints || this.phase !== 'bet' || this.gs.players[0].bets.length) return; + this.dock.startPrompts('Pick a chip, then click a number — or the lines and corners between numbers', () => this.gs.players[0].bets.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, { variant: this.variant, history: this.history, memory: this.aiMem[pi] })) { + this.gs = placeBet(this.gs, pi, spec); } } } onSpin() { - if (!this.bettingEnabled()) return; - this.animating = true; + if (this.phase !== 'bet' || !this.gs) return; + this.phase = 'spin'; + this.removeDolly(); + this.clearResultFx(); + this.dock.hidePrompts(); + this.target = spinResult(this.variant); + this.plan = planSpin({ + variant: this.variant, target: this.target, wheelAngle0: this.wheelAngle, + seed: (Math.random() * 2 ** 31) | 0, launchAngle: -Math.PI / 2, + }); + this.spinT = 0; + this.ballRel = null; + // opponents drop the odd late chip while the ball runs + const tNmb = this.plan.T.noMoreBets; + this.lateBets = []; + for (let pi = 1; pi < this.gs.players.length; pi++) { + this.lateBets.push({ pi, t: 0.4 + Math.random() * Math.max(0.2, tNmb - 0.9) }); + } + this.lateBets.sort((a, b) => a.t - b.t); + this.hopIdx = 0; + this.hitIdx = 0; + playSound(this, SFX.ROULETTE); + this.say('The ball is in play — bets are still open!'); this.refreshControls(); - this.hoverG.clear(); - this.setStatus('No more bets — spinning…'); - - const res = spin(this.gs); - this.gs = res.state; - this.animateSpin(res.index).then(() => { - const out = resolveSpin(this.gs, res.index); - this.gs = out.state; - this.handleResolution(out); - }); } - handleResolution(out) { - const { value, color } = out; + spinEvents(t0, t1) { + const plan = this.plan; + while (this.lateBets.length && this.lateBets[0].t <= t1 && this.phase === 'spin') { + const { pi } = this.lateBets.shift(); + const p = this.gs.players[pi]; + let any = false; + for (const spec of chooseLateBets(p, { variant: this.variant })) { + const before = this.gs; + this.gs = placeBet(this.gs, pi, spec); + if (this.gs !== before) any = true; + } + if (any) { this.renderBets(); this.renderRail(pi); this.updatePlates(); } + } + if (this.phase === 'spin' && t1 >= plan.T.noMoreBets) this.lockBets(); + while (this.hitIdx < plan.diamondHits.length && plan.diamondHits[this.hitIdx] <= t1) { + this.hitIdx++; + this.tick(0.5, 3400); + } + while (this.hopIdx < plan.hopTs.length && plan.hopTs[this.hopIdx] <= t1) { + this.hopIdx++; + this.tick(0.35 - this.hopIdx * 0.04, 2200 + Math.random() * 900); + } + if (t0 < plan.T.settle && t1 >= plan.T.settle) this.tick(0.3, 1500); + if (t1 >= plan.T.end && this.phase === 'locked') this.finishSpin(); + } - this.renderBets(); // bets cleared by resolveSpin → felt clears - 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]); + lockBets() { + this.phase = 'locked'; + this.lastSnapshot = this.gs.players[0].bets.map((b) => ({ type: b.type, numbers: b.numbers, number: b.number, amount: b.amount })); + this.undo = []; + this.say('No more bets!', '#ffe27a', 2000); + this.setHover(null); + this.tooltip.hide(); + this.input.setDefaultCursor('default'); + this.showCam(); + this.refreshControls(); + } - entries.forEach(({ i, delta }, idx) => { - this.time.delayedCall(idx * 420, () => { - this.portraits[i]?.playEmotion?.(delta > 0 ? 'happy' : 'upset'); - this.animatePlayerResult(i, delta); - }); - this.animateChips(i, delta > 0, Math.abs(delta)); - }); + finishSpin() { + const plan = this.plan; + this.plan = null; + this.wheelSpeed = plan.wheelSpeed(this.spinT); + this.restBallOn(this.target); + this.resolveRound(this.target); + } - this.showResult(value, color); - this.highlightWinners(value, color, out.index); - const hd = this.gs.players[0].lastDelta; - const tail = hd > 0 ? `You win $${hd}!` : hd < 0 ? `You lose $${-hd}.` : 'No win this time.'; - this.setStatus(`${this.displayNum(value)} ${color.toUpperCase()} — ${tail}`); - this.updateBalances(); + async resolveRound(value) { + this.phase = 'result'; + this.refreshControls(); + this.lastValue = value; + const out = resolveSpin(this.gs, value); + this.gs = out.state; this.persistChips(); + this.pushHistory(value); + this.drawBoard(); + this.say(dealerCall(value), colorOf(value) === 'red' ? '#ff9a8a' : colorOf(value) === 'green' ? '#9be07a' : '#f7ecd0', 3200); + this.wheel.setHighlight([value], 0xf5d020, 0.9); + if (this.camVisible) { + this.camWheel.setHighlight([value], 0xf5d020, 0.9); + this.numberBadge(0, 0, value, 1.2, this.camResult); + await this.wait(1300); + await this.hideCam(); + } else { + const b = this.numberBadge(this.wheel.x, this.wheel.y - WHEEL.R * 0.95, value, 0.9); + this.time.delayedCall(2600, () => this.tweens.add({ targets: b, alpha: 0, duration: 400, onComplete: () => b.destroy() })); + await this.wait(500); + } + if (!this.alive()) return; + await this.dropDolly(value); + this.showResultFx(value); + await this.settle(out); + if (!this.alive()) return; + this.reactions(out); + for (let pi = 1; pi < this.gs.players.length; pi++) { + noteResult(this.gs.players[pi], this.aiMem[pi], out.payouts.filter((p) => p.playerIndex === pi)); + } + await this.wait(700); + if (!this.alive() || this.checkGameOver()) return; + this.startBetting(); + } - this.time.delayedCall(2000, () => { - this.animating = false; - if (this.checkGameOver()) return; - this.beginRound(); + // ── Dolly & winning-number highlights ───────────────────────────────────── + async dropDolly(value) { + this.removeDolly(); + const c = numberCenter(value, this.variant); + const p = P.project(c.u, c.v); + const d = this.add.image(p.x, p.y - 140, 'roulette-dolly') + .setOrigin(0.5, DOLLY.footY / DOLLY.h).setScale(0.85 * p.s).setDepth(D.dolly + p.y / 10000).setAlpha(0); + this.dolly = d; + await this.tweenP({ targets: d, y: p.y, alpha: 1, duration: 420, ease: 'Bounce.easeOut' }); + playSound(this, SFX.CHIP_BET); + } + + removeDolly() { + const d = this.dolly; + if (!d) return; + this.dolly = null; + this.tweens.add({ targets: d, y: d.y - 60, alpha: 0, duration: 300, ease: 'Cubic.easeIn', onComplete: () => d.destroy() }); + } + + showResultFx(value) { + this.resultFx = this.boxes.filter((b) => (b.kind === 'num' ? b.n === value : normalizeSpec(this.variant, b)?.numbers.includes(value))); + } + + drawResultFx(time) { + const g = this.resultG; + g.clear(); + const a = 0.55 + 0.35 * Math.sin(time / 220); + for (const b of this.resultFx) { + const strong = b.kind === 'num'; + this.fillPoly(g, b.pts, 0xf5d020, (strong ? 0.3 : 0.12) * a, 0); + g.lineStyle(strong ? 4 : 2.5, 0xf5d020, a); + g.beginPath(); + b.pts.forEach((p, i) => (i ? g.lineTo(p.x, p.y) : g.moveTo(p.x, p.y))); + g.closePath(); + g.strokePath(); + } + } + + clearResultFx() { + this.resultFx = []; + this.resultG?.clear(); + this.wheel?.setHighlight(null); + } + + // ── Settlement ───────────────────────────────────────────────────────────── + takeStack(key) { + const st = this.stackObjs.get(key); + if (st) this.stackObjs.delete(key); + return st; + } + + async settle(out) { + const bank = bankPose(); + const sweep = (st, delay) => st && this.tweens.add({ + targets: st, x: bank.x + (Math.random() - 0.5) * 140, y: bank.y, scale: 0.55, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 560, 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())); + }; + const losers = out.payouts.filter((p) => p.result === 'lose'); + const partage = out.payouts.filter((p) => p.result === 'partage'); + const winners = out.payouts.filter((p) => p.result === 'win'); - displayNum(value) { return value === '00' ? '00' : String(value); } - - showResult(value, color) { - const c = color === 'red' ? '#c0392b' : color === 'green' ? '#39c06a' : '#f2ead8'; - this.resultText.setColor(c).setText(`${this.displayNum(value)} ${color.toUpperCase()}`); - } - - // ── Highlights ───────────────────────────────────────────────────────────── - highlightWinners(value, color, index) { - this.clearHighlights(); - - // Felt cells/boxes that win this spin. - for (const z of Object.values(this.zones)) { - if (!betWins({ type: z.type, number: z.number }, value, color)) continue; - const ring = this.add.graphics().setDepth(D.hl); - ring.lineStyle(4, COLORS.gold, 1); - ring.strokeRoundedRect(z.rect.x + 2, z.rect.y + 2, z.rect.w - 4, z.rect.h - 4, 6); - this.tweens.add({ targets: ring, alpha: { from: 1, to: 0.3 }, duration: 520, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); - this.highlightObjs.push(ring); + // 1. the dealer rakes the losers (nearest the wheel first, like a real sweep) + if (losers.length) { + const items = losers.map((p) => this.takeStack(`${p.playerIndex}:${p.key}`)).filter(Boolean) + .sort((a, b) => a.x - b.x); + items.forEach((st, i) => sweep(st, i * 18)); + if (items.length) playSound(this, SFX.CHIP_BET); + await this.wait(Math.min(900, 520 + items.length * 18)); } - - // Glow on the winning pocket. - const a = index * STEP + this.wheel.rotation; - const gx = WHEEL.x + Math.sin(a) * WHEEL.r * 0.66; - const gy = WHEEL.y - Math.cos(a) * WHEEL.r * 0.66; - this.pocketGlow.clear(); - this.pocketGlow.lineStyle(3, COLORS.gold, 1); - this.pocketGlow.strokeCircle(gx, gy, 14); - this.pocketGlow.setAlpha(1); - this.tweens.add({ targets: this.pocketGlow, alpha: { from: 1, to: 0.25 }, duration: 520, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); - } - - clearHighlights() { - for (const o of this.highlightObjs) { - this.tweens.killTweensOf(o); - o.destroy(); + // 2. La Partage: half to the house, half back to the player + if (partage.length) { + await Promise.all(partage.map((p) => { + const st = this.takeStack(`${p.playerIndex}:${p.key}`); + if (!st) return null; + sweep(st, 0); + if (p.credited <= 0) return null; + const half = p.playerIndex === 0 + ? makeChipStack(this, st.x, st.y, p.credited, { size: st.chipSize, depth: D.flying, label: false }) + : makeChipColumn(this, st.x, st.y, `rw${p.playerIndex}`, Math.max(1, Math.min(10, Math.ceil(p.credited / 5))), { size: st.chipSize, depth: D.flying }); + if (p.playerIndex === 0) this.floatText(st.x, st.y - 30, `½ back ${money(p.credited)}`, '#f5d020', 18); + return this.wait(300).then(() => toRail([half], p.playerIndex)); + })); } - this.highlightObjs = []; - if (this.pocketGlow) { this.tweens.killTweensOf(this.pocketGlow); this.pocketGlow.clear(); } + // 3. pay the winners + if (winners.length) { + await Promise.all(winners.map((p, i) => this.payWinner(p, i * 80, bank, toRail))); + } + // anything left over (shouldn't be) goes away + for (const [key, st] of this.stackObjs) { st.destroy(); this.stackObjs.delete(key); } + 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); + } + const humanWins = winners.filter((p) => p.playerIndex === 0); + if (humanWins.length) playSound(this, SFX.CASINO_WIN); + else if (out.payouts.some((p) => p.playerIndex === 0)) playSound(this, SFX.CASINO_LOSE); + if (humanWins.some((p) => p.type === BET.STRAIGHT)) this.bigWin(humanWins.find((p) => p.type === BET.STRAIGHT)); } - // ── Win / lose result badges ─────────────────────────────────────────────── - animatePlayerResult(pi, delta) { - const isWin = delta > 0; - const x = SEAT_X[pi]; - const textY = SEAT_Y - PORTRAIT_R - 58; + async payWinner(p, delay, bank, toRail) { + const base = this.takeStack(`${p.playerIndex}:${p.key}`); + if (!base) return; + const size = base.chipSize ?? 40; + const human = p.playerIndex === 0; + const pay = human + ? makeChipStack(this, bank.x, bank.y, p.winnings, { size, depth: D.flying, seed: p.winnings + 3, label: true, maxChips: 12 }) + : makeChipColumn(this, bank.x, bank.y, `rw${p.playerIndex}`, Math.max(1, Math.min(12, Math.ceil(p.winnings / 5))), { size, depth: D.flying }); + pay.setScale(0.75).setAlpha(0); + const px = base.x + size * 1.05, py = base.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)}`, '#9be07a', 20); + await this.wait(520); + await toRail([pay, base], p.playerIndex); + } - 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(), + reactions(out) { + 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 * 160, () => { + 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); }); }); + const hd = this.gs.players[0].lastDelta; + if (hd > 0) this.portraits[0]?.playEmotion?.('happy'); + else if (hd < 0) this.portraits[0]?.playEmotion?.('upset'); + void out; } - animateFireworks(cx, cy) { + bigWin(p) { + const x = CX + 120, y = 470; + const t = this.add.text(x, y, `STRAIGHT UP!\n${numLabel(p.numbers[0])} pays 35 to 1 · +${money(p.winnings)}`, { + fontFamily: '"Julius Sans One"', fontSize: '44px', color: '#f5d020', fontStyle: 'bold', align: 'center', + stroke: '#000000', strokeThickness: 7, lineSpacing: 8, + shadow: { offsetX: 0, offsetY: 0, color: '#f5d020', blur: 26, fill: true }, + }).setOrigin(0.5).setDepth(D.modal).setScale(1.4).setAlpha(0); + this.tweens.add({ targets: t, alpha: 1, scale: 1, duration: 260, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, y: y - 40, delay: 2200, duration: 500, onComplete: () => t.destroy() }); + this.fireworks(x, y); + } + + fireworks(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('RouletteGame')) 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; + for (let burst = 0; burst < 4; burst++) { + this.time.delayedCall(burst * 340, () => { + if (!this.alive()) return; + const bx = cx + (Math.random() - 0.5) * 420; + const by = cy + (Math.random() - 0.5) * 160; + for (let i = 0; i < 14; i++) { + const angle = (i / 14) * TWO_PI + Math.random() * 0.3; + const dist = 70 + Math.random() * 80; + const dot = this.add.circle(bx, by, 4 + Math.random() * 3, palette[Math.floor(Math.random() * palette.length)]).setDepth(D.modal + 5); 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(), + targets: dot, x: bx + Math.cos(angle) * dist, y: by + Math.sin(angle) * dist, + alpha: 0, scale: 0.1, duration: 700 + Math.random() * 400, ease: 'Power2', onComplete: () => dot.destroy(), }); } }); } } - // ── Win/loss chip animation ──────────────────────────────────────────────── - animateChips(playerIndex, toPlayer, amount) { - const seatX = SEAT_X[playerIndex]; - const count = Math.min(8, Math.max(2, Math.ceil(amount / 50))); - const color = SEAT_COLORS[playerIndex % SEAT_COLORS.length]; - for (let i = 0; i < count; i++) { - const chip = this.add.graphics().setDepth(D.fx); - chip.fillStyle(toPlayer ? color : 0x2c2c2c, 1); chip.fillCircle(0, 0, 12); - chip.lineStyle(2, 0xffffff, 0.45); chip.strokeCircle(0, 0, 12); - const fromX = toPlayer ? POT.x : seatX; - const fromY = toPlayer ? POT.y : SEAT_Y; - const toX = toPlayer ? seatX : POT.x; - const toY = toPlayer ? SEAT_Y : POT.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: 440 + i * 45, ease: 'Quad.InOut', onComplete: () => chip.destroy(), - }); - } - this.floatText(seatX, SEAT_Y - PORTRAIT_R - 40, toPlayer ? `+$${amount}` : `-$${amount}`, toPlayer ? '#5cb85c' : '#e05c5c'); + onKey(e) { + if (!this.gs) return; + const k = (e.key ?? '').toLowerCase(); + if (k === 'h') { this.toggleHints(); return; } + if (['1', '2', '3', '4', '5'].includes(k)) { this.selectChip(CHIP_AMOUNTS[Number(k) - 1]); return; } + if (!this.canBet()) return; + if (k === ' ' || k === 'enter') { e.preventDefault?.(); this.onSpin(); } + else if (k === 'z' || k === 'backspace') this.onUndo(); + else if (k === 'r') this.onRebet(); + else if (k === 'd') this.onDouble(); + else if (k === 'c' || k === 'escape') this.onClear(); } - floatText(x, y, label, color) { - const t = this.add.text(x, y, label, { - fontFamily: '"Julius Sans One"', fontSize: '26px', color, fontStyle: 'bold', - 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() }); - } - - setStatus(msg) { this.statusText.setText(msg); } - - // ── 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() { @@ -677,7 +1466,7 @@ export default class RouletteGame extends Phaser.Scene { checkGameOver() { const human = this.gs.players[0]; if (human.chips > 0 || totalAtRisk(human) > 0) return false; - this.gs.phase = 'gameover'; + this.phase = 'over'; this.refreshControls(); this.postHistory(); new Modal(this, 'Out of chips! Visit your profile to request a reset.', { autoCloseMs: 4200 }); @@ -687,20 +1476,28 @@ export default class RouletteGame 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: 'roulette', - 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') { - this.gs = refundBets(this.gs, 0); + if (this.gs && this.phase !== 'over') { + if (this.plan || this.phase === 'locked') { + // the ball is already rolling: the spin stands + const out = resolveSpin(this.gs, this.target); + this.gs = out.state; + this.pushHistory(this.target); + this.persistChips(); + } else if (this.phase === 'bet' || this.phase === 'spin') { + // only resolved deltas reach the server, so un-resolved stakes just come back + this.gs = refundBets(this.gs, 0); + } this.postHistory(); } this.scene.start('GameMenu'); diff --git a/src/games/roulette/RouletteLogic.js b/src/games/roulette/RouletteLogic.js index d2e936d..b786542 100644 --- a/src/games/roulette/RouletteLogic.js +++ b/src/games/roulette/RouletteLogic.js @@ -1,73 +1,210 @@ -// Pure American-roulette rules. No Phaser dependency. +// Pure roulette rules — no Phaser, so tools/verifyRoulette.js can import it. // -// Scope: a double-zero wheel (0, 00, 1–36) with straight-up bets (35:1) and -// outside bets — Red/Black, Odd/Even, 1-18/19-36 (1:1), Dozens and Columns (2:1). +// Two wheels: +// us American double-zero (0, 00, 1–36) +// eu European single-zero (0, 1–36) with La Partage: when the ball lands on +// 0, even-money bets lose only half. // -// A "round" is one spin: players place bets, the wheel is spun, every bet is -// resolved against the winning pocket and cleared. Players re-bet each round. +// Every bet is a set of numbers. A bet wins when the winning number is in its +// set, and pays a fixed multiple of the stake by type (36/n − 1, except the +// American five-number Basket which pays 6 to 1). Inside bets are validated +// against the full list of legal number sets for the wheel (legalInsideBets), +// which the table geometry and verify script also use. // -// State is treated as immutable: every mutating helper returns a fresh object. +// '00' is a string so it stays distinct from 0. State is treated as immutable: +// every mutating helper returns a fresh object. -// Wheel pocket order, clockwise from 0 (standard American double-zero wheel). -// '00' is stored as a string so it stays distinct from 0. -export const POCKETS = [ - 0, 28, 9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1, '00', - 27, 10, 25, 29, 12, 8, 19, 31, 18, 6, 21, 33, 16, 4, 23, 35, 14, 2, -]; +export const WHEELS = { + us: { + key: 'us', + name: 'American', + pockets: [ + 0, 28, 9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1, '00', + 27, 10, 25, 29, 12, 8, 19, 31, 18, 6, 21, 33, 16, 4, 23, 35, 14, 2, + ], + zeros: [0, '00'], + partage: false, + }, + eu: { + key: 'eu', + name: 'European', + pockets: [ + 0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, + 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26, + ], + zeros: [0], + partage: true, + }, +}; +export const VARIANTS = Object.keys(WHEELS); -// Red numbers; every other 1–36 is black; 0 and 00 are green. export const RED = new Set([1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]); -// Felt number grid, top row to bottom row (each column of three = {3k,3k-1,3k-2}). -// The "2 to 1" box at the right of each row bets on that row (a column bet). -export const GRID_ROWS = [ - [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36], // column 3 (n % 3 === 0) - [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35], // column 2 (n % 3 === 2) - [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34], // column 1 (n % 3 === 1) -]; +export const CHIP_AMOUNTS = [1, 5, 25, 50, 100]; -// Chip denominations offered in the UI (shared with the chip-color map in the scene). -export const CHIP_AMOUNTS = [5, 25, 50, 100]; - -// Bet types and the payout (winnings as a multiple of the stake). export const BET = { - STRAIGHT: 'straight', // a single pocket, incl. 0 / 00 + STRAIGHT: 'straight', + SPLIT: 'split', + STREET: 'street', + TRIO: 'trio', // a zero with two adjacent numbers (0-1-2, 0-2-3, 0-00-2, 00-1-2 …) + CORNER: 'corner', + FIRST_FOUR: 'firstfour', // European 0-1-2-3 + BASKET: 'basket', // American 0-00-1-2-3 ("top line") + SIX_LINE: 'sixline', + DOZEN: 'dozen', // number 1 | 2 | 3 + COLUMN: 'column', // number 1 | 2 | 3 (column 1 = 1, 4, 7 …) RED: 'red', BLACK: 'black', ODD: 'odd', EVEN: 'even', LOW: 'low', // 1–18 HIGH: 'high', // 19–36 - DOZEN: 'dozen', // number = 1 | 2 | 3 - COLUMN: 'column', // number = 1 | 2 | 3 (felt rows bottom→top) }; +const BET_TYPES = new Set(Object.values(BET)); + +export const INSIDE = new Set([ + BET.STRAIGHT, BET.SPLIT, BET.STREET, BET.TRIO, BET.CORNER, BET.FIRST_FOUR, BET.BASKET, BET.SIX_LINE, +]); +export const EVEN_MONEY = new Set([BET.RED, BET.BLACK, BET.ODD, BET.EVEN, BET.LOW, BET.HIGH]); export const PAYOUT = { - [BET.STRAIGHT]: 35, - [BET.DOZEN]: 2, - [BET.COLUMN]: 2, + [BET.STRAIGHT]: 35, [BET.SPLIT]: 17, [BET.STREET]: 11, [BET.TRIO]: 11, + [BET.CORNER]: 8, [BET.FIRST_FOUR]: 8, [BET.BASKET]: 6, [BET.SIX_LINE]: 5, + [BET.DOZEN]: 2, [BET.COLUMN]: 2, [BET.RED]: 1, [BET.BLACK]: 1, [BET.ODD]: 1, [BET.EVEN]: 1, [BET.LOW]: 1, [BET.HIGH]: 1, }; +// Most a single spot can hold (per player). +export const TABLE_LIMITS = { + min: 1, + [BET.STRAIGHT]: 100, [BET.SPLIT]: 200, [BET.STREET]: 300, [BET.TRIO]: 300, + [BET.CORNER]: 400, [BET.FIRST_FOUR]: 400, [BET.BASKET]: 500, [BET.SIX_LINE]: 600, + outside: 1000, +}; + +export const TYPE_NAME = { + [BET.STRAIGHT]: 'Straight up', [BET.SPLIT]: 'Split', [BET.STREET]: 'Street', [BET.TRIO]: 'Trio', + [BET.CORNER]: 'Corner', [BET.FIRST_FOUR]: 'First Four', [BET.BASKET]: 'Basket', [BET.SIX_LINE]: 'Six Line', + [BET.DOZEN]: 'Dozen', [BET.COLUMN]: 'Column', [BET.RED]: 'Red', [BET.BLACK]: 'Black', + [BET.ODD]: 'Odd', [BET.EVEN]: 'Even', [BET.LOW]: '1 to 18', [BET.HIGH]: '19 to 36', +}; + +// ── Numbers ────────────────────────────────────────────────────────────────── export function colorOf(value) { if (value === 0 || value === '00') return 'green'; return RED.has(value) ? 'red' : 'black'; } -function columnOf(n) { - if (typeof n !== 'number' || n < 1) return 0; - const r = n % 3; - return r === 0 ? 3 : r; // {3,6,…}=3, {2,5,…}=2, {1,4,…}=1 +export const isZero = (v) => v === 0 || v === '00'; +export const numLabel = (v) => (v === '00' ? '00' : String(v)); +const sortVal = (v) => (v === '00' ? -1 : v); +export const sortNums = (nums) => [...nums].sort((a, b) => sortVal(a) - sortVal(b)); + +export function pocketIndex(variant, value) { + return WHEELS[variant].pockets.indexOf(value); } -function dozenOf(n) { - if (typeof n !== 'number' || n < 1) return 0; - return Math.ceil(n / 12); // 1–12=1, 13–24=2, 25–36=3 +// The k numbers either side of `value` on the wheel, plus the number itself. +export function neighbours(variant, value, k = 2) { + const P = WHEELS[variant].pockets; + const i = P.indexOf(value); + if (i < 0) return []; + const out = []; + for (let d = -k; d <= k; d++) out.push(P[(i + d + P.length) % P.length]); + return out; } -// ─── Setup ─────────────────────────────────────────────────────────────────── +// Column of the felt grid: column c (0…11) holds 3c+1 (near row), 3c+2, 3c+3 (far row). +export function outsideNumbers(type, n = null) { + const all = Array.from({ length: 36 }, (_, i) => i + 1); + switch (type) { + case BET.RED: return all.filter(v => RED.has(v)); + case BET.BLACK: return all.filter(v => !RED.has(v)); + case BET.ODD: return all.filter(v => v % 2 === 1); + case BET.EVEN: return all.filter(v => v % 2 === 0); + case BET.LOW: return all.filter(v => v <= 18); + case BET.HIGH: return all.filter(v => v >= 19); + case BET.DOZEN: return all.filter(v => Math.ceil(v / 12) === n); + case BET.COLUMN: return all.filter(v => ((v - 1) % 3) + 1 === n); + default: return []; + } +} -export function createInitialState(opponents = [], humanChips = 2000, humanName = 'You') { +// ── Legal inside bets ──────────────────────────────────────────────────────── +// Zero placement on the felt: American has 0 against the far half (3 and the +// upper half of 2) and 00 against the near half (lower 2 and 1); European has a +// single 0 spanning all three rows. +const LEGAL_CACHE = {}; +export function legalInsideBets(variant) { + if (LEGAL_CACHE[variant]) return LEGAL_CACHE[variant]; + const out = []; + const add = (type, numbers) => out.push({ type, numbers: sortNums(numbers) }); + for (const z of WHEELS[variant].zeros) add(BET.STRAIGHT, [z]); + for (let n = 1; n <= 36; n++) add(BET.STRAIGHT, [n]); + for (let n = 1; n <= 33; n++) add(BET.SPLIT, [n, n + 3]); + for (let n = 1; n <= 36; n++) if (n % 3 !== 0) add(BET.SPLIT, [n, n + 1]); + for (let c = 0; c < 12; c++) add(BET.STREET, [3 * c + 1, 3 * c + 2, 3 * c + 3]); + for (let n = 1; n <= 32; n++) if (n % 3 !== 0) add(BET.CORNER, [n, n + 1, n + 3, n + 4]); + for (let c = 0; c < 11; c++) add(BET.SIX_LINE, [3 * c + 1, 3 * c + 2, 3 * c + 3, 3 * c + 4, 3 * c + 5, 3 * c + 6]); + if (variant === 'us') { + add(BET.SPLIT, [0, '00']); + add(BET.SPLIT, [0, 3]); add(BET.SPLIT, [0, 2]); + add(BET.SPLIT, ['00', 2]); add(BET.SPLIT, ['00', 1]); + add(BET.TRIO, [0, 2, 3]); add(BET.TRIO, [0, '00', 2]); add(BET.TRIO, ['00', 1, 2]); + add(BET.BASKET, [0, '00', 1, 2, 3]); + } else { + add(BET.SPLIT, [0, 1]); add(BET.SPLIT, [0, 2]); add(BET.SPLIT, [0, 3]); + add(BET.TRIO, [0, 1, 2]); add(BET.TRIO, [0, 2, 3]); + add(BET.FIRST_FOUR, [0, 1, 2, 3]); + } + LEGAL_CACHE[variant] = out; + return out; +} + +const LEGAL_KEYS = {}; +function legalKeys(variant) { + return (LEGAL_KEYS[variant] ??= new Set(legalInsideBets(variant).map(b => betKey(b.type, b.numbers)))); +} + +export function betKey(type, numbers, n = null) { + if (!INSIDE.has(type)) return n == null ? type : `${type}:${n}`; + return `${type}:${sortNums(numbers).map(numLabel).join('-')}`; +} + +// Normalise a bet spec: fills in `numbers` for outside bets, sorts inside ones. +// Returns null if the spec is not a legal bet on this wheel. +export function normalizeSpec(variant, spec) { + if (!spec || !BET_TYPES.has(spec.type)) return null; + if (INSIDE.has(spec.type)) { + const numbers = sortNums(spec.numbers ?? []); + const key = betKey(spec.type, numbers); + if (!legalKeys(variant).has(key)) return null; + return { type: spec.type, numbers, number: null, key }; + } + const n = (spec.type === BET.DOZEN || spec.type === BET.COLUMN) ? spec.number : null; + if ((spec.type === BET.DOZEN || spec.type === BET.COLUMN) && ![1, 2, 3].includes(n)) return null; + return { type: spec.type, numbers: outsideNumbers(spec.type, n), number: n, key: betKey(spec.type, null, n) }; +} + +export function spotLimit(type) { + return INSIDE.has(type) ? TABLE_LIMITS[type] : TABLE_LIMITS.outside; +} + +export function betLabel(bet) { + const t = bet.type; + if (t === BET.STRAIGHT) return `Straight up ${numLabel(bet.numbers[0])}`; + if (t === BET.DOZEN) return ['1st 12', '2nd 12', '3rd 12'][bet.number - 1]; + if (t === BET.COLUMN) return `Column ${bet.number}`; + if (INSIDE.has(t)) return `${TYPE_NAME[t]} ${bet.numbers.map(numLabel).join('·')}`; + return TYPE_NAME[t]; +} + +export function paysLabel(type) { + return `${PAYOUT[type]} to 1`; +} + +// ── Setup ──────────────────────────────────────────────────────────────────── +export function createInitialState(opponents = [], humanChips = 2000, humanName = 'You', variant = 'us') { const players = [ { name: humanName, isAI: false, avatar: null, chips: humanChips, bets: [], lastDelta: 0 }, ...opponents.map((o) => ({ @@ -79,45 +216,68 @@ export function createInitialState(opponents = [], humanChips = 2000, humanName lastDelta: 0, })), ]; - return { - players, - phase: 'betting', // betting → spinning → betting (or gameover) - lastSpin: null, // { index, value } of the most recent spin - _nextBetId: 1, - }; + return { variant, players, lastSpin: null, _nextBetId: 1 }; } export function cloneState(state) { return JSON.parse(JSON.stringify(state)); } -// ─── Bet placement ─────────────────────────────────────────────────────────-- - -// Stable identity for a bet so repeat clicks stack instead of duplicating. -function betKey(type, number) { - return number == null ? type : `${type}:${number}`; +export function setVariant(state, variant) { + const s = cloneState(state); + for (const p of s.players) { + for (const b of p.bets) p.chips += b.amount; + p.bets = []; + } + s.variant = variant; + return s; } -// Place a flat bet. Stake is removed from the bankroll immediately. -export function placeBet(state, playerIndex, { type, number = null, amount }) { - const player = state.players[playerIndex]; - if (amount <= 0 || amount > player.chips) return state; - if (!Object.values(BET).includes(type)) return state; +// ── Bet placement ──────────────────────────────────────────────────────────── +export function findBet(player, key) { + return player.bets.find(b => b.key === key) ?? null; +} +// How much more can go on this spot right now (bankroll and table max). +export function maxAddable(state, playerIndex, spec) { + const norm = normalizeSpec(state.variant, spec); + if (!norm) return 0; + const p = state.players[playerIndex]; + const have = findBet(p, norm.key)?.amount ?? 0; + return Math.max(0, Math.min(p.chips, spotLimit(norm.type) - have)); +} + +// Place (or add to) a bet. Stake leaves the bankroll immediately. Illegal, +// unaffordable or over-limit bets return the state unchanged. +export function placeBet(state, playerIndex, spec) { + const norm = normalizeSpec(state.variant, spec); + const amount = Math.floor(spec?.amount ?? 0); + if (!norm || amount < TABLE_LIMITS.min) return state; + if (amount > maxAddable(state, playerIndex, spec)) return state; const s = cloneState(state); const p = s.players[playerIndex]; - const key = betKey(type, number); - const existing = p.bets.find((b) => betKey(b.type, b.number) === key); - if (existing) { - existing.amount += amount; - } else { - p.bets.push({ id: s._nextBetId++, type, number: number ?? null, amount }); - } + const existing = findBet(p, norm.key); + if (existing) existing.amount += amount; + else p.bets.push({ id: s._nextBetId++, ...norm, amount }); p.chips -= amount; return s; } -// Return staked chips to the bankroll (only sensible during a betting window). +// Take `amount` (default: all) back off the spot `key`. +export function removeBet(state, playerIndex, key, amount = Infinity) { + const p0 = state.players[playerIndex]; + const bet = findBet(p0, key); + if (!bet) return state; + const s = cloneState(state); + const p = s.players[playerIndex]; + const b = findBet(p, key); + const take = Math.min(b.amount, Math.max(0, Math.floor(amount === Infinity ? b.amount : amount))); + b.amount -= take; + p.chips += take; + if (b.amount <= 0) p.bets = p.bets.filter(x => x !== b); + return s; +} + export function refundBets(state, playerIndex, predicate = () => true) { const s = cloneState(state); const p = s.players[playerIndex]; @@ -130,75 +290,114 @@ export function refundBets(state, playerIndex, predicate = () => true) { return s; } -// ─── Spin & resolution ─────────────────────────────────────────────────────── +// ── Call bets (racetrack) ──────────────────────────────────────────────────── +// Each returns plain specs; a spec with `units: 2` takes two chips. +export const CALL_BETS = { + voisins: { + name: 'Voisins du Zéro', + parts: [ + { type: BET.TRIO, numbers: [0, 2, 3], units: 2 }, + { type: BET.SPLIT, numbers: [4, 7] }, { type: BET.SPLIT, numbers: [12, 15] }, + { type: BET.SPLIT, numbers: [18, 21] }, { type: BET.SPLIT, numbers: [19, 22] }, + { type: BET.SPLIT, numbers: [32, 35] }, + { type: BET.CORNER, numbers: [25, 26, 28, 29], units: 2 }, + ], + }, + tiers: { + name: 'Tiers du Cylindre', + parts: [[5, 8], [10, 11], [13, 16], [23, 24], [27, 30], [33, 36]].map(n => ({ type: BET.SPLIT, numbers: n })), + }, + orphelins: { + name: 'Orphelins', + parts: [ + { type: BET.STRAIGHT, numbers: [1] }, + { type: BET.SPLIT, numbers: [6, 9] }, { type: BET.SPLIT, numbers: [14, 17] }, + { type: BET.SPLIT, numbers: [17, 20] }, { type: BET.SPLIT, numbers: [31, 34] }, + ], + }, + zero: { + name: 'Jeu Zéro', + parts: [ + { type: BET.SPLIT, numbers: [0, 3] }, { type: BET.SPLIT, numbers: [12, 15] }, + { type: BET.STRAIGHT, numbers: [26] }, { type: BET.SPLIT, numbers: [32, 35] }, + ], + }, +}; -export function spin(state) { - const s = cloneState(state); - const index = Math.floor(Math.random() * POCKETS.length); - s.lastSpin = { index, value: POCKETS[index] }; - return { state: s, index, value: POCKETS[index] }; -} - -// Force a specific pocket (testing / scripted demos). -export function setSpin(state, index) { - const s = cloneState(state); - s.lastSpin = { index, value: POCKETS[index] }; - return { state: s, index, value: POCKETS[index] }; -} - -export function betWins(bet, value, color) { - if (color === 'green') return bet.type === BET.STRAIGHT && bet.number === value; - switch (bet.type) { - case BET.STRAIGHT: return bet.number === value; - case BET.RED: return color === 'red'; - case BET.BLACK: return color === 'black'; - case BET.ODD: return value % 2 === 1; - case BET.EVEN: return value % 2 === 0; - case BET.LOW: return value >= 1 && value <= 18; - case BET.HIGH: return value >= 19 && value <= 36; - case BET.DOZEN: return dozenOf(value) === bet.number; - case BET.COLUMN: return columnOf(value) === bet.number; - default: return false; +// Specs for a call bet at `unit` per chip. name: a CALL_BETS key or 'neighbours'. +export function callBetSpecs(variant, name, unit, { number = null, k = 2 } = {}) { + if (name === 'neighbours') { + return neighbours(variant, number, k).map(v => ({ type: BET.STRAIGHT, numbers: [v], amount: unit })); } + const def = CALL_BETS[name]; + if (!def) return []; + return def.parts.map(p => ({ type: p.type, numbers: p.numbers, amount: unit * (p.units ?? 1) })); } -// Resolve every bet against pocket `index`. Clears all bets afterward. -// Returns { state, index, value, color, payouts }. -// payouts entry: { playerIndex, type, number, result:'win'|'lose', amount, delta }. -export function resolveSpin(state, index) { +export function callBetChips(variant, name, opts) { + return callBetSpecs(variant, name, 1, opts).reduce((a, s) => a + s.amount, 0); +} + +export function callBetNumbers(variant, name, opts) { + const set = new Set(); + for (const s of callBetSpecs(variant, name, 1, opts)) for (const n of s.numbers) set.add(n); + return sortNums([...set]); +} + +// ── Spin & resolution ──────────────────────────────────────────────────────── +export function spinResult(variant, rng = Math.random) { + const P = WHEELS[variant].pockets; + return P[Math.floor(rng() * P.length)]; +} + +// What a single bet does on `value`: { result, credited } where credited is +// what goes back to the bankroll (stake + winnings, the partage half, or 0). +export function betOutcome(bet, value, variant) { + if (bet.numbers.includes(value)) { + return { result: 'win', credited: bet.amount * (1 + PAYOUT[bet.type]) }; + } + if (WHEELS[variant].partage && value === 0 && EVEN_MONEY.has(bet.type)) { + return { result: 'partage', credited: Math.floor(bet.amount / 2) }; + } + return { result: 'lose', credited: 0 }; +} + +// Resolve every bet against `value`; all bets leave the felt (winning stakes go +// back with their winnings). payouts entry: +// { playerIndex, betId, key, type, numbers, number, amount, result, credited, winnings, delta } +export function resolveSpin(state, value) { const s = cloneState(state); - const value = POCKETS[index]; + const variant = s.variant; const color = colorOf(value); const payouts = []; - - for (let pi = 0; pi < s.players.length; pi++) { - const p = s.players[pi]; + s.players.forEach((p, pi) => { + p.lastDelta = 0; for (const bet of p.bets) { - const win = betWins(bet, value, color); - const stake = bet.amount; - let delta; - if (win) { - const credited = stake + stake * PAYOUT[bet.type]; - p.chips += credited; - delta = credited - stake; // = winnings - } else { - delta = -stake; // stake was already removed at placement - } + const { result, credited } = betOutcome(bet, value, variant); + p.chips += credited; + const delta = credited - bet.amount; p.lastDelta += delta; - payouts.push({ playerIndex: pi, type: bet.type, number: bet.number, result: win ? 'win' : 'lose', amount: stake, delta }); + payouts.push({ + playerIndex: pi, betId: bet.id, key: bet.key, type: bet.type, numbers: bet.numbers, number: bet.number, + amount: bet.amount, result, credited, winnings: result === 'win' ? credited - bet.amount : 0, delta, + }); } p.bets = []; - } - s.lastSpin = { index, value }; - return { state: s, index, value, color, payouts }; + }); + s.lastSpin = { value, color }; + return { state: s, value, color, payouts }; } -// ─── Round / table helpers ─────────────────────────────────────────────────-- - -export function clearLastDeltas(state) { - const s = cloneState(state); - for (const p of s.players) p.lastDelta = 0; - return s; +// ── Analysis ───────────────────────────────────────────────────────────────── +// Exact house edge of a spec on this wheel, by enumerating every pocket. +export function houseEdge(spec, variant) { + const norm = normalizeSpec(variant, spec); + if (!norm) return null; + const bet = { ...norm, amount: 100 }; + const P = WHEELS[variant].pockets; + let back = 0; + for (const v of P) back += betOutcome(bet, v, variant).credited; + return 1 - back / (P.length * bet.amount); } export function totalAtRisk(player) { @@ -209,9 +408,25 @@ export function hasActiveBets(player) { return player.bets.length > 0; } -// 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'; return 'draw'; } + +// The dealer's call: "Seventeen — black, odd, low". +const WORDS = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', + 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty']; +const TENS = { 2: 'Twenty', 3: 'Thirty' }; +export function numberWords(v) { + if (v === '00') return 'Double Zero'; + if (v <= 20) return WORDS[v]; + const t = Math.floor(v / 10), o = v % 10; + return o ? `${TENS[t]}-${WORDS[o].toLowerCase()}` : TENS[t]; +} + +export function dealerCall(value) { + if (isZero(value)) return `${numberWords(value)} — green`; + const parts = [colorOf(value), value % 2 ? 'odd' : 'even', value <= 18 ? 'low' : 'high']; + return `${numberWords(value)} — ${parts.join(', ')}`; +} diff --git a/src/games/roulette/RouletteTable.js b/src/games/roulette/RouletteTable.js new file mode 100644 index 0000000..278c778 --- /dev/null +++ b/src/games/roulette/RouletteTable.js @@ -0,0 +1,414 @@ +// Roulette table geometry — Phaser-free so tools/verifyRoulette.js can import it. +// +// A long roulette table seen from the players' side through the shared casino +// perspective camera (makeProjection). Table space: +// u left/right, −1 (the wheel end) … +1 (the far right end) +// v depth, 0 = far rail (dealer side) … 1 = near rail (players) +// The wheel sits in a wooden cabinet at the left end; the betting layout fills +// the right two-thirds. Everything on the felt goes through P.project(u, v); +// the padded rail is raised through lift(u, v, h). +// +// Layout bands (far → near): racetrack strip (European only), the 3×12 number +// grid with the zero column on its left and "2 to 1" boxes on its right, the +// dozens row and the even-money row. + +import { makeProjection, DOCK } from '../../ui/casino/CasinoGeometry.js'; +import { BET, WHEELS, legalInsideBets, betKey, sortNums, CALL_BETS } from './RouletteLogic.js'; + +export { DOCK }; + +export const VIEW = { cx: 960, yFar: 222, yNear: 800, sFar: 0.74, halfW: 840, squash: 0.9 }; +export const P = makeProjection(VIEW); + +export const RAIL = { + W: 0.062, // padded rail width (table units) + H: 18, // rail top height above the felt (px at s = 1) + FACE: 30, // rail's outer face (px at s = 1) + CR: 0.14, // table corner radius (table units) +}; + +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 table offset `d` outward (table units). +export function tableOutline(d = 0, perCorner = 10, perSide = 28) { + const r = RAIL.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); + side({ u: u0 + r, v: v0 }, { u: u1 - r, v: v0 }); + corner(u1 - r, v0 + r, 270); + side({ u: u1, v: v0 + r }, { u: u1, v: v1 - r }); + corner(u1 - r, v1 - r, 0); + side({ u: u1 - r, v: v1 }, { u: u0 + r, v: v1 }); + corner(u0 + r, v1 - r, 90); + side({ u: u0, v: v1 - r }, { u: u0, v: v0 + r }); + return pts; +} + +// ── Wheel ──────────────────────────────────────────────────────────────────── +// The cabinet occupies u < CABINET_U1; the wheel is its own 3D object (see +// RouletteWheel.js) centred on the projected (u, v), with a fixed screen radius. +export const CABINET_U1 = -0.5; +export const WHEEL = { u: -0.762, v: 0.5, R: 178, tilt: 0.56, h: 22 }; +export function wheelCenter() { + const p = lift(WHEEL.u, WHEEL.v, WHEEL.h); + return { x: p.x, y: p.y }; +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +export const ZERO_U0 = -0.458; +export const GRID_U0 = -0.38; +export const CELL_U = 0.106; +export const GRID_U1 = GRID_U0 + 12 * CELL_U; // 0.892 +export const COL_U1 = GRID_U1 + 0.08; // "2 to 1" boxes +export const GRID_V0 = 0.215; +export const ROW_V = 0.15; +export const GRID_V1 = GRID_V0 + 3 * ROW_V; // 0.665 +export const DOZ_V1 = GRID_V1 + 0.1; +export const EVEN_V1 = DOZ_V1 + 0.1; +export const SNAP = 0.22; // fraction of a cell that snaps to a line +export const EVEN_ORDER = [BET.LOW, BET.EVEN, BET.RED, BET.BLACK, BET.ODD, BET.HIGH]; + +// Grid cell (column c 0…11, row r 0 = far … 2 = near) → number. +export const numAt = (c, r) => 3 * c + (3 - r); +export const cellOf = (n) => ({ c: Math.floor((n - 1) / 3), r: 2 - ((n - 1) % 3) }); +const ZERO_UM = (ZERO_U0 + GRID_U0) / 2; +const colU = (c) => GRID_U0 + (c + 0.5) * CELL_U; +const rowV = (r) => GRID_V0 + (r + 0.5) * ROW_V; + +// Centre of a number's box on the felt. +export function numberCenter(n, variant) { + if (n === 0) return { u: ZERO_UM, v: variant === 'us' ? GRID_V0 + 0.75 * ROW_V : GRID_V0 + 1.5 * ROW_V }; + if (n === '00') return { u: ZERO_UM, v: GRID_V0 + 2.25 * ROW_V }; + const { c, r } = cellOf(n); + return { u: colU(c), v: rowV(r) }; +} + +// Table-space rects for every box printed on the felt (for art + highlights). +export function feltBoxes(variant) { + const out = []; + for (let n = 1; n <= 36; n++) { + const { c, r } = cellOf(n); + out.push({ kind: 'num', n, u0: GRID_U0 + c * CELL_U, u1: GRID_U0 + (c + 1) * CELL_U, v0: GRID_V0 + r * ROW_V, v1: GRID_V0 + (r + 1) * ROW_V }); + } + if (variant === 'us') { + out.push({ kind: 'num', n: 0, u0: ZERO_U0, u1: GRID_U0, v0: GRID_V0, v1: GRID_V0 + 1.5 * ROW_V }); + out.push({ kind: 'num', n: '00', u0: ZERO_U0, u1: GRID_U0, v0: GRID_V0 + 1.5 * ROW_V, v1: GRID_V1 }); + } else { + out.push({ kind: 'num', n: 0, u0: ZERO_U0, u1: GRID_U0, v0: GRID_V0, v1: GRID_V1 }); + } + for (let k = 1; k <= 3; k++) { + out.push({ kind: 'out', type: BET.COLUMN, number: k, u0: GRID_U1, u1: COL_U1, v0: GRID_V0 + (3 - k) * ROW_V, v1: GRID_V0 + (4 - k) * ROW_V }); + out.push({ kind: 'out', type: BET.DOZEN, number: k, u0: GRID_U0 + (k - 1) * 4 * CELL_U, u1: GRID_U0 + k * 4 * CELL_U, v0: GRID_V1, v1: DOZ_V1 }); + } + EVEN_ORDER.forEach((type, i) => { + out.push({ kind: 'out', type, number: null, u0: GRID_U0 + i * 2 * CELL_U, u1: GRID_U0 + (i + 1) * 2 * CELL_U, v0: DOZ_V1, v1: EVEN_V1 }); + }); + return out; +} + +// ── Chip spots ─────────────────────────────────────────────────────────────── +// Where a bet's chips sit, from its numbers alone (cell centre, shared edge, +// corner, street line …), so the felt can be re-drawn from state. +function insideSpot(type, numbers, variant) { + const nums = sortNums(numbers); + const grid = nums.filter(n => typeof n === 'number' && n > 0); + const hasZ = nums.includes(0) || nums.includes('00'); + const avg = (list) => { + const pts = list.map(n => numberCenter(n, variant)); + return { u: pts.reduce((a, p) => a + p.u, 0) / pts.length, v: pts.reduce((a, p) => a + p.v, 0) / pts.length }; + }; + switch (type) { + case BET.STRAIGHT: return numberCenter(nums[0], variant); + case BET.SPLIT: + if (!hasZ) return avg(nums); + if (grid.length === 0) return { u: ZERO_UM, v: GRID_V0 + 1.5 * ROW_V }; // 0-00 + { + const n = grid[0]; + const { r } = cellOf(n); + let v = rowV(r); + if (variant === 'us' && n === 2) v = GRID_V0 + (nums.includes(0) ? 1.25 : 1.75) * ROW_V; + return { u: GRID_U0, v }; + } + case BET.CORNER: return avg(nums); + case BET.STREET: return { u: colU(cellOf(nums[0]).c), v: GRID_V1 }; + case BET.SIX_LINE: return { u: GRID_U0 + (cellOf(nums[0]).c + 1) * CELL_U, v: GRID_V1 }; + case BET.TRIO: { + if (nums.includes(0) && nums.includes('00')) return { u: GRID_U0, v: GRID_V0 + 1.5 * ROW_V }; + return { u: GRID_U0, v: grid.includes(3) ? GRID_V0 + ROW_V : GRID_V0 + 2 * ROW_V }; + } + case BET.BASKET: + case BET.FIRST_FOUR: return { u: GRID_U0, v: GRID_V1 }; + default: return null; + } +} + +export function outsideSpot(type, number) { + if (type === BET.COLUMN) return { u: (GRID_U1 + COL_U1) / 2, v: rowV(3 - number) }; + if (type === BET.DOZEN) return { u: GRID_U0 + (number - 0.5) * 4 * CELL_U, v: (GRID_V1 + DOZ_V1) / 2 }; + const i = EVEN_ORDER.indexOf(type); + return { u: GRID_U0 + (i + 0.5) * 2 * CELL_U, v: (DOZ_V1 + EVEN_V1) / 2 }; +} + +export function spotFor(bet, variant) { + if (bet.type === BET.COLUMN || bet.type === BET.DOZEN || EVEN_ORDER.includes(bet.type)) return outsideSpot(bet.type, bet.number); + return insideSpot(bet.type, bet.numbers, variant); +} + +// ── Hit-testing ────────────────────────────────────────────────────────────── +const make = (type, numbers) => ({ kind: 'bet', type, numbers: sortNums(numbers), number: null, key: betKey(type, numbers) }); +const out = (type, number = null) => ({ kind: 'bet', type, numbers: null, number, key: betKey(type, null, number) }); + +// Table point → bet spec (or a racetrack hit, or null). +export function hitBetUV(u, v, variant) { + if (variant === 'eu') { + const rt = hitRacetrackUV(u, v); + if (rt) return rt; + } + const S = SNAP; + const sv = S * ROW_V; + const su = S * CELL_U; + // Zero column (away from its edge with the grid). + if (u >= ZERO_U0 && u < GRID_U0 - su && v >= GRID_V0 && v <= GRID_V1) { + if (variant === 'us') { + const mid = GRID_V0 + 1.5 * ROW_V; + if (Math.abs(v - mid) < sv) return make(BET.SPLIT, [0, '00']); + return make(BET.STRAIGHT, [v < mid ? 0 : '00']); + } + return make(BET.STRAIGHT, [0]); + } + // Number grid (including the snap band along its near edge for streets). + if (u >= GRID_U0 - su && u < GRID_U1 && v >= GRID_V0 && v <= GRID_V1 + sv) { + const fx = (u - GRID_U0) / CELL_U; + const fy = (v - GRID_V0) / ROW_V; + const c = Math.max(0, Math.min(11, Math.floor(fx))); + const r = Math.max(0, Math.min(2, Math.floor(fy))); + const fu = fx - c, fv = fy - r; + let xLine = null, yLine = null; + if (fu < S) xLine = c; else if (fu > 1 - S) xLine = c + 1; + if (fy > 3 - S) yLine = 3; + else if (fv < S && r > 0) yLine = r; + else if (fv > 1 - S && r < 2) yLine = r + 1; + if (xLine === 12) xLine = null; // edge with the column boxes + + if (yLine === 3) { // street line + if (xLine === 0) return variant === 'us' ? make(BET.BASKET, [0, '00', 1, 2, 3]) : make(BET.FIRST_FOUR, [0, 1, 2, 3]); + if (xLine != null) return make(BET.SIX_LINE, [...street(xLine - 1), ...street(xLine)]); + return make(BET.STREET, street(c)); + } + if (xLine === 0) { // edge with the zero column + if (variant === 'us') { + if (yLine === 1) return make(BET.TRIO, [0, 2, 3]); + if (yLine === 2) return make(BET.TRIO, ['00', 1, 2]); + if (r === 1) { + if (Math.abs(fv - 0.5) < S) return make(BET.TRIO, [0, '00', 2]); + return make(BET.SPLIT, [fv < 0.5 ? 0 : '00', 2]); + } + return make(BET.SPLIT, [r === 0 ? 0 : '00', numAt(0, r)]); + } + if (yLine === 1) return make(BET.TRIO, [0, 2, 3]); + if (yLine === 2) return make(BET.TRIO, [0, 1, 2]); + return make(BET.SPLIT, [0, numAt(0, r)]); + } + if (xLine != null && yLine != null) { + return make(BET.CORNER, [numAt(xLine - 1, yLine - 1), numAt(xLine, yLine - 1), numAt(xLine - 1, yLine), numAt(xLine, yLine)]); + } + if (xLine != null) return make(BET.SPLIT, [numAt(xLine - 1, r), numAt(xLine, r)]); + if (yLine != null) return make(BET.SPLIT, [numAt(c, yLine - 1), numAt(c, yLine)]); + return make(BET.STRAIGHT, [numAt(c, r)]); + } + // Column boxes. + if (u >= GRID_U1 && u <= COL_U1 && v >= GRID_V0 && v <= GRID_V1) { + return out(BET.COLUMN, 3 - Math.min(2, Math.floor((v - GRID_V0) / ROW_V))); + } + if (u >= GRID_U0 && u <= GRID_U1) { + if (v > GRID_V1 && v <= DOZ_V1) return out(BET.DOZEN, Math.min(3, 1 + Math.floor((u - GRID_U0) / (4 * CELL_U)))); + if (v > DOZ_V1 && v <= EVEN_V1) return out(EVEN_ORDER[Math.min(5, Math.floor((u - GRID_U0) / (2 * CELL_U)))]); + } + return null; +} + +function street(c) { return [3 * c + 1, 3 * c + 2, 3 * c + 3]; } + +export function hitBet(x, y, variant) { + const { u, v } = P.unproject(x, y); + return hitBetUV(u, v, variant); +} + +// Every legal inside bet's spot (for verify + highlights). +export function insideSpots(variant) { + return legalInsideBets(variant).map(b => ({ ...b, key: betKey(b.type, b.numbers), spot: insideSpot(b.type, b.numbers, variant) })); +} + +// ── Racetrack (European call bets) ─────────────────────────────────────────── +// A stadium along the far strip. The numbers run round it in wheel order, +// 0 at the right end, then along the far side leftwards. Inside, four sections: +// Tiers | Orphelins | Voisins | Zéro (left → right). +export const RT = { u0: -0.44, u1: 0.76, v0: 0.035, v1: 0.188, band: 0.046 }; +const RT_R = (RT.v1 - RT.v0) / 2; // outer end radius +const RT_VM = (RT.v0 + RT.v1) / 2; +const RT_RC = RT_R - RT.band / 2; // centre-line radius +const RT_L = (RT.u1 - RT.u0) - 2 * RT_R; // straight length +const RT_CU0 = RT.u0 + RT_R, RT_CU1 = RT.u1 - RT_R; +const RT_PER = 2 * RT_L + 2 * Math.PI * RT_RC; +const RT_N = WHEELS.eu.pockets.length; +export const RT_STEP = RT_PER / RT_N; + +// Point on a ring of radius rc (centre line = RT_RC) at perimeter distance d +// (measured along the centre line), plus its outward normal. +export function racetrackPoint(d, rc = RT_RC) { + d = ((d % RT_PER) + RT_PER) % RT_PER; + const q = Math.PI * RT_RC / 2; + const seg = [q, RT_L, Math.PI * RT_RC, RT_L, q]; + let a; + if (d < seg[0]) { a = -d / RT_RC; return arcPt(RT_CU1, a, rc); } + d -= seg[0]; + if (d < seg[1]) return { u: RT_CU1 - d, v: RT_VM - rc, nu: 0, nv: -1 }; + d -= seg[1]; + if (d < seg[2]) { a = -Math.PI / 2 - d / RT_RC; return arcPt(RT_CU0, a, rc); } + d -= seg[2]; + if (d < seg[3]) return { u: RT_CU0 + d, v: RT_VM + rc, nu: 0, nv: 1 }; + d -= seg[3]; + a = Math.PI / 2 - d / RT_RC; + return arcPt(RT_CU1, a, rc); +} +function arcPt(cu, a, rc) { + return { u: cu + Math.cos(a) * rc, v: RT_VM + Math.sin(a) * rc, nu: Math.cos(a), nv: Math.sin(a) }; +} + +// Perimeter distance (centre line) of the nearest point to (u, v). +function racetrackParam(u, v) { + const q = Math.PI * RT_RC / 2; + if (u > RT_CU1) { + const a = Math.atan2(v - RT_VM, u - RT_CU1); + return a <= 0 ? -a * RT_RC : RT_PER - a * RT_RC; + } + if (u < RT_CU0) { + let a = Math.atan2(v - RT_VM, u - RT_CU0); + if (a > -Math.PI / 2) a -= 2 * Math.PI; // (−3π/2, −π/2] + return q + RT_L + (-Math.PI / 2 - a) * RT_RC; + } + if (v < RT_VM) return q + (RT_CU1 - u); + return q + RT_L + Math.PI * RT_RC + (u - RT_CU0); +} + +// Distance from the stadium's centre segment (negative = inside the end circles' axis). +function stadiumDist(u, v) { + const cu = Math.max(RT_CU0, Math.min(RT_CU1, u)); + return Math.hypot(u - cu, v - RT_VM); +} + +export const RT_SECTIONS = ['tiers', 'orphelins', 'voisins', 'zero']; +// Boundaries: top/bottom pocket indices whose gap the dividing line crosses. +const RT_LINES = [[10.5, 22.5], [7.5, 27.5], [2.5, 32.5]]; +export function racetrackLines() { + const inner = RT_R - RT.band; + return RT_LINES.map(([a, b]) => [racetrackPoint(a * RT_STEP, inner), racetrackPoint(b * RT_STEP, inner)]); +} + +export function hitRacetrackUV(u, v) { + const d = stadiumDist(u, v); + if (d > RT_R) return null; + if (d >= RT_R - RT.band) { + const i = Math.round(racetrackParam(u, v) / RT_STEP) % RT_N; + return { kind: 'call', call: 'neighbours', number: WHEELS.eu.pockets[i], index: i }; + } + const lines = racetrackLines(); + let sec = 0; + for (const [t, b] of lines) { + const k = (v - t.v) / (b.v - t.v); + const ul = t.u + (b.u - t.u) * k; + if (u > ul) sec++; + } + return { kind: 'call', call: RT_SECTIONS[sec] }; +} + +// Section label anchors (centre of each inner region). +export function racetrackSectionCenters() { + const inner = RT_R - RT.band; + const lines = racetrackLines().map(([t, b]) => (t.u + b.u) / 2); + const left = RT.u0 + RT_R * 0.6, right = RT.u1 - RT_R * 0.55; + const xs = [left, ...lines, right]; + return RT_SECTIONS.map((name, i) => ({ name, u: (xs[i] + xs[i + 1]) / 2, v: RT_VM, label: name === 'zero' ? 'ZERO' : CALL_BETS[name].name })); +} + +export function racetrackSegment(i) { + return { + mid: racetrackPoint(i * RT_STEP), + a: racetrackPoint((i - 0.5) * RT_STEP), + b: racetrackPoint((i + 0.5) * RT_STEP), + }; +} + +export const RT_GEOM = { R: RT_R, VM: RT_VM, RC: RT_RC, CU0: RT_CU0, CU1: RT_CU1, PER: RT_PER }; + +// Neighbour stepper (UI drawn by the scene) to the right of the racetrack. +export const NEIGHBOUR_UI = { u: 0.875, v: 0.112 }; + +// ── Seats ──────────────────────────────────────────────────────────────────── +// The human stands at the near rail; opponents fill FILL_ORDER (near rail, then +// the right end). `order` sorts stacks that share a spot left → right. +export const SEATS = { + H: { side: 'near', u: 0.24 }, + N1: { side: 'near', u: -0.38 }, + N2: { side: 'near', u: -0.07 }, + N3: { side: 'near', u: 0.52 }, + N4: { side: 'near', u: 0.79 }, + E1: { side: 'end', v: 0.3 }, + E2: { side: 'end', v: 0.7 }, +}; +export const FILL_ORDER = ['N3', 'N2', 'N4', 'N1', 'E2', 'E1']; +export const SEAT_ORDER = ['N1', 'N2', 'H', 'N3', 'N4', 'E2', 'E1']; + +export function seatNames(nOpp) { + return ['H', ...FILL_ORDER.slice(0, Math.min(6, nOpp))]; +} + +export function railUV(name, offset = 0) { + const s = SEATS[name]; + const d = RAIL.W * 0.5; + if (s.side === 'near') return { u: s.u + offset, v: 1 + d }; + return { u: 1 + d, v: s.v + offset }; +} + +export function railPose(name, offset = 0) { + const { u, v } = railUV(name, offset); + return lift(u, v, RAIL.H); +} + +export function seatPortrait(name) { + const s = SEATS[name]; + if (s.side === 'near') { + const p = lift(s.u, 1 + RAIL.W, RAIL.H); + return { x: p.x + 74, y: p.y + RAIL.FACE * p.s + 22, r: 30 }; + } + const p = lift(1 + RAIL.W, s.v, RAIL.H); + return { x: p.x + 4, y: p.y - 56, r: 30 }; +} + +// ── Furniture ──────────────────────────────────────────────────────────────── +export const BANK = { u0: -0.47, u1: -0.15 }; // dealer's chip float, set into the far rail +export function bankPose() { return lift((BANK.u0 + BANK.u1) / 2, -RAIL.W * 0.5, RAIL.H); } + + +// Screen furniture. +export const BOARD = { x: 940, y: 10, w: 640, h: 160 }; // history marquee (top, left of the music widget) +export const CALL = { x: 560, y: 118 }; // dealer call line (above the far rail) +export const CAM = { x: 600, y: 236, w: 930, h: 600 }; // wheel-cam panel +export const STACK = { human: 46, ai: 38 }; // chip diameter at s = 1 diff --git a/src/games/roulette/RouletteWheel.js b/src/games/roulette/RouletteWheel.js new file mode 100644 index 0000000..b8d4407 --- /dev/null +++ b/src/games/roulette/RouletteWheel.js @@ -0,0 +1,151 @@ +// The 3D roulette wheel: static bowl (baked in perspective), a rotating head +// inside a container squashed to the view tilt (rotation happens inside the +// squash, so the head stays a true ellipse at every angle), the chrome turret, +// a fixed overhead-light gloss, and the ball with its contact shadow. +// +// Every part is its own root object at a fractional depth (containers ignore +// child depth). The wheel is driven from outside: setAngle(head angle) and +// setBall({angle, r, h}) in the wheel plane (see RouletteBall.js); the cam +// close-up is simply a second instance at a bigger radius. + +import { WHEELS } from './RouletteLogic.js'; +import { GEO, bowlHeight } from './RouletteBall.js'; +import { ensureBowl, bowlLayout, HEAD_TEX, HEAD_PX, BALL_TEX, TURRET } from './RouletteArt.js'; + +const TWO_PI = Math.PI * 2; + +export class RouletteWheel { + constructor(scene, { x, y, R, tilt, depth = 5, variant = 'us' }) { + this.scene = scene; + this.R = R; + this.tilt = tilt; + this.k = Math.sqrt(1 - tilt * tilt); + this.depth = depth; + this.variant = variant; + this.angle = 0; + this.ballState = null; + this.highlight = null; // { values, color, alpha } + + const bowlKey = ensureBowl(scene, R, tilt); + const L = bowlLayout(R, tilt); + this.bowl = scene.add.image(x, y, bowlKey).setOrigin(L.cx / L.w, L.cy / L.h).setDepth(depth); + + const headScale = (GEO.R_HEAD * R) / HEAD_PX; + this.head = scene.add.container(x, y).setScale(1, tilt).setDepth(depth + 0.1); + this.headImg = scene.add.image(0, 0, `roulette-head-${variant}`).setScale(headScale); + this.hl = scene.add.graphics(); + this.head.add([this.headImg, this.hl]); + + this.gloss = scene.add.image(x, y, 'roulette-gloss').setScale(headScale, headScale * tilt).setDepth(depth + 0.3); + this.gloss.setBlendMode('SCREEN'); + const tScale = R / 180; + this.turret = scene.add.image(x, y, 'roulette-turret') + .setOrigin(0.5, TURRET.footY / TURRET.h).setScale(tScale * 0.62).setDepth(depth + 0.35); + + this.ballShadow = scene.add.ellipse(x, y, 10, 5, 0x000000, 0.45).setDepth(depth + 0.38).setVisible(false); + this.ball = scene.add.image(x, y, 'roulette-ball').setDepth(depth + 0.4).setVisible(false); + this.x = x; this.y = y; + this.parts = [this.bowl, this.head, this.gloss, this.turret, this.ballShadow, this.ball]; + } + + get step() { return TWO_PI / WHEELS[this.variant].pockets.length; } + + setVariant(variant) { + this.variant = variant; + this.headImg.setTexture(`roulette-head-${variant}`); + this.drawHighlight(); + } + + setPosition(x, y) { + this.x = x; this.y = y; + this.bowl.setPosition(x, y); + this.head.setPosition(x, y); + this.gloss.setPosition(x, y); + this.turret.setPosition(x, y); + this.setBall(this.ballState); + return this; + } + + setVisible(v) { this.parts.forEach(p => p.setVisible(v)); if (v) this.setBall(this.ballState); return this; } + setAlpha(a) { this.parts.forEach(p => p.setAlpha(a)); return this; } + + setAngle(a) { + this.angle = a; + this.headImg.rotation = a; + this.hl.rotation = a; + return this; + } + + // Screen point for a wheel-plane position. + toScreen(angle, r, h = 0) { + return { + x: this.x + Math.cos(angle) * r * this.R, + y: this.y + Math.sin(angle) * r * this.R * this.tilt - h * this.R * this.k, + }; + } + + // Ball in the wheel plane; null hides it. + setBall(b) { + this.ballState = b; + if (!b) { this.ball.setVisible(false); this.ballShadow.setVisible(false); return this; } + const p = this.toScreen(b.angle, b.r, b.h); + const surf = bowlHeight(b.r); + const sp = this.toScreen(b.angle, b.r, surf); + // a touch bigger when nearer the camera (the bottom of the ellipse) + const depthK = 1 + Math.sin(b.angle) * 0.07; + const d = GEO.BALL_R * 2 * this.R * depthK; + this.ball.setPosition(p.x, p.y - (d / 2) * this.k).setScale(d / BALL_TEX).setVisible(true); + const lift = Math.max(0, b.h - surf); + this.ballShadow.setPosition(sp.x + d * 0.12, sp.y + d * 0.05) + .setSize(d * (1.1 - lift * 3), d * 0.5 * (1.1 - lift * 3)) + .setAlpha(Math.max(0.12, 0.45 - lift * 4)) + .setVisible(true); + // behind the turret when on the far side of the cone, in front when near + this.ball.setDepth(this.depth + (Math.sin(b.angle) < 0 && b.r < 0.5 ? 0.32 : 0.4)); + return this; + } + + // Glow pockets (wheel values) on the head; null clears. + setHighlight(values, color = 0xf5d020, alpha = 0.8) { + this.highlight = values && values.length ? { values, color, alpha } : null; + this.drawHighlight(); + return this; + } + + drawHighlight() { + const g = this.hl; + g.clear(); + if (!this.highlight) return; + const pockets = WHEELS[this.variant].pockets; + const step = this.step; + const r0 = 0.47 * this.R, r1 = GEO.R_HEAD * this.R * 0.985; + const { values, color, alpha } = this.highlight; + for (const v of values) { + const i = pockets.indexOf(v); + if (i < 0) continue; + const a0 = (i - 0.5) * step, a1 = (i + 0.5) * step; + g.fillStyle(color, alpha * 0.35); + g.beginPath(); + g.arc(0, 0, r1, a0, a1, false); + g.arc(0, 0, r0, a1, a0, true); + g.closePath(); + g.fillPath(); + g.lineStyle(3, color, alpha); + g.beginPath(); + g.arc(0, 0, r1, a0, a1, false); + g.arc(0, 0, r0, a1, a0, true); + g.closePath(); + g.strokePath(); + } + } + + // Where pocket `value` is on screen right now (for sparkles / labels). + pocketScreen(value, r = GEO.R_POCKET) { + const i = WHEELS[this.variant].pockets.indexOf(value); + return this.toScreen(this.angle + i * this.step, r, 0); + } + + destroy() { this.parts.forEach(p => p.destroy()); } +} + +export { HEAD_TEX }; diff --git a/src/ui/CasinoChips.js b/src/ui/CasinoChips.js index d9ae9f8..947ad64 100644 --- a/src/ui/CasinoChips.js +++ b/src/ui/CasinoChips.js @@ -67,8 +67,7 @@ function annularSector(ctx, cx, cy, r0, r1, a0, a1) { const DEG = Math.PI / 180; // ── Face ───────────────────────────────────────────────────────────────────── -function drawFace(ctx, denom) { - const def = CHIP_DEFS[denom]; +function drawFace(ctx, denom, def = CHIP_DEFS[denom], label = String(denom)) { const cx = FACE / 2, cy = FACE / 2; // Body @@ -130,8 +129,13 @@ function drawFace(ctx, denom) { } ctx.globalAlpha = 1; + if (label == null) { + drawEmblem(ctx, cx, cy + 1, inR - 13, def.text); + drawGloss(ctx, cx, cy); + return; + } + // Denomination (embossed) - const label = String(denom); const size = label.length === 1 ? 44 : label.length === 2 ? 38 : 30; ctx.font = `${size}px Righteous, "Julius Sans One", sans-serif`; ctx.textAlign = 'center'; @@ -141,7 +145,10 @@ function drawFace(ctx, denom) { ctx.fillStyle = def.text; ctx.fillText(label, cx, cy + 2); - // Gloss + drawGloss(ctx, cx, cy); +} + +function drawGloss(ctx, cx, cy) { const gloss = ctx.createRadialGradient(cx - R * 0.45, cy - R * 0.5, 0, cx - R * 0.3, cy - R * 0.35, R * 1.05); gloss.addColorStop(0, 'rgba(255,255,255,0.32)'); gloss.addColorStop(0.45, 'rgba(255,255,255,0.06)'); @@ -150,9 +157,35 @@ function drawFace(ctx, denom) { ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); } +// A tiny roulette-wheel emblem for denomination-less "wheel chips". +function drawEmblem(ctx, cx, cy, r, color) { + ctx.save(); + ctx.strokeStyle = color; + ctx.fillStyle = color; + ctx.lineWidth = 2.5; + ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.arc(cx, cy, r * 0.62, 0, Math.PI * 2); ctx.stroke(); + for (let i = 0; i < 12; i++) { + const a = (i / 12) * Math.PI * 2; + ctx.beginPath(); + ctx.moveTo(cx + Math.cos(a) * r * 0.62, cy + Math.sin(a) * r * 0.62); + ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); + ctx.stroke(); + } + ctx.beginPath(); ctx.arc(cx, cy, r * 0.2, 0, Math.PI * 2); ctx.fill(); + for (let i = 0; i < 4; i++) { + const a = (i / 4) * Math.PI * 2 + Math.PI / 4; + ctx.beginPath(); + ctx.moveTo(cx, cy); + ctx.lineTo(cx + Math.cos(a) * r * 0.5, cy + Math.sin(a) * r * 0.5); + ctx.stroke(); + } + ctx.restore(); +} + // ── Tilted slice (edge band + squashed face) ───────────────────────────────── -function drawSlice(ctx, faceCanvas, denom) { - const def = CHIP_DEFS[denom]; +function drawSlice(ctx, faceCanvas, denom, def = CHIP_DEFS[denom]) { const cx = FACE / 2, rx = R, ry = SLICE_RY; const yT = SLICE_CY_TOP, yB = SLICE_CY_BOT; @@ -235,6 +268,23 @@ export function ensureChipTextures(scene) { } } +// A roulette "wheel chip": a seat-coloured chip with no denomination. Bakes +// chip-face- / chip-slice-, so makeChip / makeChipSlice / stacks built +// from them work like any denomination (pass the id where a denom goes). +export function ensureColorChip(scene, id, baseHex, { insert = '#f4efe4', accent = '#1b1b20', text = null } = {}) { + const faceKey = `chip-face-${id}`; + const sliceKey = `chip-slice-${id}`; + if (scene.textures.exists(faceKey) && scene.textures.exists(sliceKey)) return id; + const def = { base: baseHex, insert, accent, text: text ?? shade(baseHex, -0.35) }; + const face = makeCanvas(FACE, FACE); + drawFace(face.getContext('2d'), id, def, null); + if (!scene.textures.exists(faceKey)) scene.textures.addCanvas(faceKey, face); + const slice = makeCanvas(FACE, SLICE_H); + drawSlice(slice.getContext('2d'), face, id, def); + if (!scene.textures.exists(sliceKey)) scene.textures.addCanvas(sliceKey, slice); + return id; +} + // ── Game objects ───────────────────────────────────────────────────────────── // Flat top-down chip (an Image, so its hit area can be set in texture space: @@ -302,6 +352,26 @@ export function makeChipStack(scene, x, y, amount, { return cont; } +// A straight column of `count` identical chips (rail racks, colour-chip bets). +// Origin = felt contact point of the bottom chip, like makeChipStack. +export function makeChipColumn(scene, x, y, denom, count, { size = 40, depth, seed = 0, shadow = true } = {}) { + const cont = scene.add.container(x, y); + if (depth !== undefined) cont.setDepth(depth); + const k = size / FACE; + if (shadow) { + const sh = scene.add.graphics(); + sh.fillStyle(0x000000, 0.4); + sh.fillEllipse(size * 0.06, size * 0.05, size * 1.1, SLICE_RY * 2 * k * 1.1); + cont.add(sh); + } + for (let i = 0; i < count; i++) { + cont.add(scene.add.image(jitter(i, seed) * 1.2 * k * 2, -i * SLICE_T * k, `chip-slice-${denom}`) + .setOrigin(0.5, SLICE_CY_BOT / SLICE_H).setScale(k)); + } + cont.stackTopY = -(Math.max(1, count) - 1) * SLICE_T * k - (SLICE_T + SLICE_RY) * k; + return cont; +} + // ── Chip flights (scene-agnostic; callers own their stack bookkeeping) ─────── const lerpN = (a, b, t) => a + (b - a) * t; diff --git a/tools/verifyRoulette.js b/tools/verifyRoulette.js new file mode 100644 index 0000000..047f8ee --- /dev/null +++ b/tools/verifyRoulette.js @@ -0,0 +1,452 @@ +#!/usr/bin/env node +// verifyRoulette.js — headless checks for Roulette: both wheels, every legal +// inside bet, felt hit-testing (sweep + round trip from each chip spot), +// payouts and exact house edges, La Partage, call bets and the racetrack, +// table limits, an AI + random-human chip-conservation soak, the ball planner +// landing on every pocket, and screen layout sanity. + +import { + WHEELS, BET, INSIDE, EVEN_MONEY, PAYOUT, TABLE_LIMITS, RED, colorOf, legalInsideBets, normalizeSpec, betKey, + createInitialState, placeBet, removeBet, refundBets, setVariant, maxAddable, spotLimit, resolveSpin, betOutcome, + houseEdge, totalAtRisk, callBetSpecs, callBetNumbers, CALL_BETS, neighbours, spinResult, dealerCall, numberWords, + outsideNumbers, findBet, +} from '../src/games/roulette/RouletteLogic.js'; +import { chooseBets, chooseLateBets, noteResult, personalityOf, PERSONALITIES } from '../src/games/roulette/RouletteAI.js'; +import { + P, VIEW, hitBetUV, hitBet, spotFor, insideSpots, feltBoxes, ZERO_U0, GRID_U0, CELL_U, GRID_U1, COL_U1, GRID_V0, ROW_V, + GRID_V1, DOZ_V1, EVEN_V1, RT, RT_GEOM, RT_STEP, racetrackPoint, hitRacetrackUV, racetrackSectionCenters, racetrackLines, SEATS, + seatNames, seatPortrait, railPose, bankPose, BOARD, CAM, CALL, DOCK, WHEEL, wheelCenter, CABINET_U1, NEIGHBOUR_UI, + tableOutline, numberCenter, +} from '../src/games/roulette/RouletteTable.js'; +import { planSpin, mulberry32, GEO, WHEEL_SPEED, wheelAngleAt } from '../src/games/roulette/RouletteBall.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-9) => Math.abs(a - b) <= eps; +const VARIANTS = ['us', 'eu']; + +// ── 1. Wheels ──────────────────────────────────────────────────────────────── +section('1. Wheels'); +{ + for (const v of VARIANTS) { + const P_ = WHEELS[v].pockets; + const expect = v === 'us' ? 38 : 37; + ok(`${v}: ${expect} pockets`, P_.length === expect, String(P_.length)); + ok(`${v}: every number once`, new Set(P_).size === P_.length); + for (let n = 1; n <= 36; n++) ok(`${v}: has ${n}`, P_.includes(n)); + ok(`${v}: zeros`, WHEELS[v].zeros.every((z) => P_.includes(z))); + // red and black alternate round the wheel (zeros aside) + let alt = true; + for (let i = 0; i < P_.length; i++) { + const a = P_[i], b = P_[(i + 1) % P_.length]; + if (colorOf(a) !== 'green' && colorOf(b) !== 'green' && colorOf(a) === colorOf(b)) alt = false; + } + ok(`${v}: red/black alternate`, alt); + } + const EU = [0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26]; + ok('eu: exact pocket order', JSON.stringify(WHEELS.eu.pockets) === JSON.stringify(EU)); + ok('18 reds', RED.size === 18); + ok('partage only on eu', WHEELS.eu.partage && !WHEELS.us.partage); +} + +// ── 2. Legal bets & payouts ────────────────────────────────────────────────── +section('2. Legal bets, payouts, house edges'); +{ + const counts = (v) => legalInsideBets(v).reduce((m, b) => (m[b.type] = (m[b.type] ?? 0) + 1, m), {}); + const us = counts('us'), eu = counts('eu'); + ok('us counts', us.straight === 38 && us.split === 62 && us.street === 12 && us.corner === 22 && us.sixline === 11 && us.trio === 3 && us.basket === 1 && !us.firstfour, JSON.stringify(us)); + ok('eu counts', eu.straight === 37 && eu.split === 60 && eu.street === 12 && eu.corner === 22 && eu.sixline === 11 && eu.trio === 2 && eu.firstfour === 1 && !eu.basket, JSON.stringify(eu)); + for (const v of VARIANTS) { + const keys = new Set(); + for (const b of legalInsideBets(v)) { + const k = betKey(b.type, b.numbers); + ok(`${v}: unique ${k}`, !keys.has(k)); + keys.add(k); + const n = b.numbers.length; + if (b.type === BET.BASKET) ok('basket pays 6', PAYOUT[b.type] === 6 && n === 5); + else ok(`${v}: ${k} pays 36/n − 1`, PAYOUT[b.type] === 36 / n - 1, `${PAYOUT[b.type]} vs ${36 / n - 1}`); + ok(`${v}: ${k} numbers on wheel`, b.numbers.every((x) => WHEELS[v].pockets.includes(x))); + } + } + const outside = [ + [BET.RED], [BET.BLACK], [BET.ODD], [BET.EVEN], [BET.LOW], [BET.HIGH], + [BET.DOZEN, 1], [BET.DOZEN, 2], [BET.DOZEN, 3], [BET.COLUMN, 1], [BET.COLUMN, 2], [BET.COLUMN, 3], + ]; + for (const [type, number] of outside) { + const nums = outsideNumbers(type, number ?? null); + ok(`${type}${number ?? ''} pays 36/n − 1`, PAYOUT[type] === 36 / nums.length - 1); + } + ok('column 1 = 1,4,7…', JSON.stringify(outsideNumbers(BET.COLUMN, 1).slice(0, 3)) === '[1,4,7]'); + ok('red set', outsideNumbers(BET.RED).length === 18 && outsideNumbers(BET.RED).every((n) => RED.has(n))); + ok('illegal split rejected', normalizeSpec('us', { type: BET.SPLIT, numbers: [3, 4] }) === null); + ok('eu has no 00', normalizeSpec('eu', { type: BET.STRAIGHT, numbers: ['00'] }) === null); + ok('us basket ok', !!normalizeSpec('us', { type: BET.BASKET, numbers: [3, 2, 1, '00', 0] })); + ok('eu first four ok', !!normalizeSpec('eu', { type: BET.FIRST_FOUR, numbers: [0, 1, 2, 3] })); + ok('bad dozen rejected', normalizeSpec('us', { type: BET.DOZEN, number: 4 }) === null); + + // exact edges + for (const b of legalInsideBets('us')) { + const e = houseEdge(b, 'us'); + ok(`us edge ${b.type}`, near(e, b.type === BET.BASKET ? 3 / 38 : 2 / 38, 1e-12), String(e)); + } + for (const b of legalInsideBets('eu')) ok(`eu edge ${b.type}`, near(houseEdge(b, 'eu'), 1 / 37, 1e-12)); + for (const [type, number] of outside) { + ok(`us edge ${type}`, near(houseEdge({ type, number }, 'us'), 2 / 38, 1e-12)); + const eu = houseEdge({ type, number }, 'eu'); + ok(`eu edge ${type}`, near(eu, EVEN_MONEY.has(type) ? 0.5 / 37 : 1 / 37, 1e-12), String(eu)); + } + console.log(` edges: US ${(2 / 38 * 100).toFixed(2)}%, basket ${(3 / 38 * 100).toFixed(2)}%, EU ${(1 / 37 * 100).toFixed(2)}%, EU even-money ${(0.5 / 37 * 100).toFixed(2)}%`); +} + +// ── 3. Placement, limits, resolution ───────────────────────────────────────── +section('3. Placement, limits, resolution'); +{ + let s = createInitialState([], 5000, 'T', 'us'); + s = placeBet(s, 0, { type: BET.STRAIGHT, numbers: [17], amount: 25 }); + s = placeBet(s, 0, { type: BET.STRAIGHT, numbers: [17], amount: 25 }); + ok('stacks merge', s.players[0].bets.length === 1 && s.players[0].bets[0].amount === 50); + ok('stake leaves bankroll', s.players[0].chips === 4950); + ok('maxAddable straight', maxAddable(s, 0, { type: BET.STRAIGHT, numbers: [17] }) === 50); + const s2 = placeBet(s, 0, { type: BET.STRAIGHT, numbers: [17], amount: 60 }); + ok('over limit rejected', s2 === s); + ok('limits', spotLimit(BET.SPLIT) === 200 && spotLimit(BET.RED) === TABLE_LIMITS.outside); + const s3 = placeBet(s, 0, { type: BET.RED, amount: 6000 }); + ok('unaffordable rejected', s3 === s); + ok('zero amount rejected', placeBet(s, 0, { type: BET.RED, amount: 0 }) === s); + let r = removeBet(s, 0, s.players[0].bets[0].key, 20); + ok('partial remove', findBet(r.players[0], 'straight:17').amount === 30 && r.players[0].chips === 4970); + r = removeBet(r, 0, 'straight:17'); + ok('remove all', r.players[0].bets.length === 0 && r.players[0].chips === 5000); + // resolution + let t = createInitialState([], 1000, 'T', 'eu'); + t = placeBet(t, 0, { type: BET.RED, amount: 20 }); + t = placeBet(t, 0, { type: BET.STRAIGHT, numbers: [0], amount: 10 }); + t = placeBet(t, 0, { type: BET.DOZEN, number: 1, amount: 10 }); + const z = resolveSpin(t, 0); + const red = z.payouts.find((p) => p.type === BET.RED); + ok('partage half back', red.result === 'partage' && red.credited === 10 && red.delta === -10); + ok('zero straight pays 35', z.payouts.find((p) => p.type === BET.STRAIGHT).winnings === 350); + ok('dozen loses on 0', z.payouts.find((p) => p.type === BET.DOZEN).result === 'lose'); + ok('eu zero bankroll', z.state.players[0].chips === 960 + 10 + 360 && z.state.players[0].lastDelta === -10 + 350 - 10); + ok('bets cleared', z.state.players[0].bets.length === 0); + let u = createInitialState([], 1000, 'T', 'us'); + u = placeBet(u, 0, { type: BET.RED, amount: 20 }); + const uz = resolveSpin(u, 0); + ok('no partage on us', uz.payouts[0].result === 'lose' && uz.state.players[0].chips === 980); + const w = resolveSpin(u, 3); + ok('red wins on 3 (stake back + 1:1)', w.state.players[0].chips === 1020 && w.payouts[0].credited === 40); + let sv = setVariant(u, 'eu'); + ok('setVariant refunds', sv.variant === 'eu' && sv.players[0].chips === 1000 && !sv.players[0].bets.length); + ok('refundBets', refundBets(u, 0).players[0].chips === 1000); + ok('betOutcome win credited', betOutcome({ type: BET.SPLIT, numbers: [1, 2], amount: 10 }, 2, 'us').credited === 180); + // dealer calls + for (const v of WHEELS.us.pockets) { + const c = dealerCall(v); + ok(`call ${v}`, typeof c === 'string' && !c.includes('undefined') && c.length > 3, c); + } + ok('numberWords 27', numberWords(27) === 'Twenty-seven'); +} + +// ── 4. Call bets & racetrack ───────────────────────────────────────────────── +section('4. Call bets & racetrack'); +{ + const expect = { voisins: [9, 17], tiers: [6, 12], orphelins: [5, 8], zero: [4, 7] }; + for (const [name, [chips, nums]] of Object.entries(expect)) { + const specs = callBetSpecs('eu', name, 5); + ok(`${name} chips`, specs.reduce((a, s) => a + s.amount, 0) === chips * 5); + ok(`${name} numbers`, callBetNumbers('eu', name).length === nums, String(callBetNumbers('eu', name).length)); + ok(`${name} all legal`, specs.every((s) => normalizeSpec('eu', s))); + } + const all = new Set([...callBetNumbers('eu', 'voisins'), ...callBetNumbers('eu', 'tiers'), ...callBetNumbers('eu', 'orphelins')]); + ok('voisins + tiers + orphelins = whole wheel', all.size === 37); + const zeroIn = callBetNumbers('eu', 'zero').every((n) => callBetNumbers('eu', 'voisins').includes(n)); + ok('jeu zéro ⊂ voisins', zeroIn); + // sections are contiguous runs on the wheel + const contiguous = (nums) => { + const P_ = WHEELS.eu.pockets; + const idx = nums.map((n) => P_.indexOf(n)); + let runs = 0; + for (const i of idx) if (!idx.includes((i - 1 + 37) % 37)) runs++; + return runs; + }; + ok('voisins one arc', contiguous(callBetNumbers('eu', 'voisins')) === 1); + ok('tiers one arc', contiguous(callBetNumbers('eu', 'tiers')) === 1); + ok('orphelins two arcs', contiguous(callBetNumbers('eu', 'orphelins')) === 2); + ok('jeu zéro one arc', contiguous(callBetNumbers('eu', 'zero')) === 1); + for (const v of VARIANTS) { + for (const n of WHEELS[v].pockets) { + const nb = neighbours(v, n, 2); + ok(`${v} neighbours ${n}`, nb.length === 5 && nb[2] === n && contiguous.length >= 0); + ok(`${v} neighbour specs legal ${n}`, callBetSpecs(v, 'neighbours', 1, { number: n, k: 3 }).every((s) => normalizeSpec(v, s))); + } + } + // racetrack: every segment clicks as its own number; inside regions match their numbers + const P_ = WHEELS.eu.pockets; + for (let i = 0; i < P_.length; i++) { + const m = racetrackPoint(i * RT_STEP); + const h = hitRacetrackUV(m.u, m.v); + ok(`racetrack segment ${P_[i]}`, h?.call === 'neighbours' && h.number === P_[i], JSON.stringify(h)); + // just inside the band, the section region should include this number + const inner = RT_GEOM.R - RT.band - RT_GEOM.RC - 0.012; + const q = { u: m.u + m.nu * inner, v: m.v + m.nv * inner }; + const s = hitRacetrackUV(q.u, q.v); + ok(`inside the band beside ${P_[i]} is a section`, s && s.call !== 'neighbours'); + // away from the (slanted) dividers, the section holds the number beside it + const clear = racetrackLines().every(([t, b]) => Math.abs(q.u - (t.u + (b.u - t.u) * (q.v - t.v) / (b.v - t.v))) > 0.05); + if (clear) ok(`section beside ${P_[i]}`, callBetNumbers('eu', s.call).includes(P_[i]), `${JSON.stringify(s)}`); + } + for (const c of racetrackSectionCenters()) { + ok(`section label ${c.name} hits`, hitRacetrackUV(c.u, c.v)?.call === c.name); + } + ok('racetrack above grid', RT.v1 < GRID_V0); + ok('no racetrack on us', !hitBetUV((RT.u0 + RT.u1) / 2, RT.v0 + 0.01, 'us')); +} + +// ── 5. Felt hit-testing ────────────────────────────────────────────────────── +section('5. Felt hit-testing'); +{ + for (const v of VARIANTS) { + // round trip: clicking exactly on each legal bet's chip spot gives that bet + for (const b of insideSpots(v)) { + const h = hitBetUV(b.spot.u, b.spot.v, v); + ok(`${v} spot round-trip ${b.key}`, h?.key === b.key, `${h?.key}`); + const sp = spotFor({ ...b }, v); + ok(`${v} spotFor ${b.key}`, near(sp.u, b.spot.u) && near(sp.v, b.spot.v)); + } + // a fine sweep: every hit is legal, near its own chip spot; every bet is reachable + const seen = new Set(); + let bad = 0, far = 0; + for (let u = ZERO_U0 - 0.01; u <= COL_U1 + 0.01; u += 0.0025) { + for (let vv = GRID_V0 - 0.01; vv <= EVEN_V1 + 0.01; vv += 0.0025) { + const h = hitBetUV(u, vv, v); + if (!h) continue; + if (h.kind !== 'bet') continue; + const norm = normalizeSpec(v, h); + if (!norm) { bad++; continue; } + seen.add(norm.key); + if (INSIDE.has(norm.type)) { + const sp = spotFor(norm, v); + const tolV = isZeroStraight(norm) ? (v === 'eu' ? 1.55 : 1.0) * ROW_V : 0.62 * ROW_V; + if (Math.abs(sp.u - u) > 0.62 * CELL_U || Math.abs(sp.v - vv) > tolV) far++; + } + } + } + ok(`${v} sweep: all hits legal`, bad === 0, String(bad)); + ok(`${v} sweep: chips land near the pointer`, far === 0, String(far)); + const missing = legalInsideBets(v).filter((b) => !seen.has(betKey(b.type, b.numbers))); + ok(`${v} sweep: every inside bet reachable`, missing.length === 0, missing.map((b) => betKey(b.type, b.numbers)).slice(0, 6).join(' ')); + for (const k of ['red', 'black', 'odd', 'even', 'low', 'high', 'dozen:1', 'dozen:2', 'dozen:3', 'column:1', 'column:2', 'column:3']) { + ok(`${v} sweep: reaches ${k}`, seen.has(k)); + } + // each outside box: its centre hits it, and the spot is inside the box + for (const b of feltBoxes(v).filter((x) => x.kind === 'out')) { + const h = hitBetUV((b.u0 + b.u1) / 2, (b.v0 + b.v1) / 2, v); + ok(`${v} box ${b.type}${b.number ?? ''}`, h?.type === b.type && (h.number ?? null) === (b.number ?? null)); + } + // number boxes: centre is a straight-up of that number + for (const b of feltBoxes(v).filter((x) => x.kind === 'num')) { + const c = numberCenter(b.n, v); + const h = hitBetUV(c.u, c.v, v); + ok(`${v} number ${b.n}`, h?.type === BET.STRAIGHT && h.numbers[0] === b.n, JSON.stringify(h)); + } + } + // screen round trip through the projection + const s = P.project(GRID_U0 + CELL_U * 5.5, GRID_V0 + ROW_V * 1.5); + ok('screen hit (5.5, 1.5) = 17', hitBet(s.x, s.y, 'us')?.numbers?.[0] === 17); + ok('far off the felt = nothing', hitBet(5, 5, 'us') === null); +} +function isZeroStraight(norm) { return norm.type === BET.STRAIGHT && (norm.numbers[0] === 0 || norm.numbers[0] === '00'); } + +// ── 6. AI ──────────────────────────────────────────────────────────────────── +section('6. AI'); +{ + const names = Array.from({ length: 60 }, (_, i) => `Bot${i}`); + const kinds = new Set(names.map((n) => personalityOf({ name: n }))); + ok('every personality used', kinds.size === Object.keys(PERSONALITIES).length, [...kinds].join(',')); + const rng = mulberry32(7); + for (const v of VARIANTS) { + for (const name of names) { + for (const chips of [2000, 140, 12, 3]) { + const p = { name, chips, bets: [] }; + const mem = {}; + const specs = chooseBets(p, { variant: v, history: [17, 17, 4, 0, 22], memory: mem, rng }); + const total = specs.reduce((a, s) => a + s.amount, 0); + ok(`${v} ${name} ${chips}: affordable`, total <= chips, `${total}`); + ok(`${v} ${name}: legal`, specs.every((s) => normalizeSpec(v, s) && s.amount >= 1 && s.amount <= spotLimit(s.type)), JSON.stringify(specs)); + const late = chooseLateBets(p, { variant: v, rng }); + ok(`${v} ${name}: late legal`, late.every((s) => normalizeSpec(v, s) && s.amount <= chips)); + } + } + } + // martingale doubles after a loss and resets on a win + const mName = names.find((n) => personalityOf({ name: n }) === 'martingale'); + const mp = { name: mName, chips: 2000, bets: [] }; + const mem = {}; + chooseBets(mp, { variant: 'us', memory: mem, rng }); + const base = mem.stake; + noteResult(mp, mem, [{ type: mem.type, result: 'lose' }]); + ok('martingale doubles', mem.stake === base * 2); + noteResult(mp, mem, [{ type: mem.type, result: 'win' }]); + ok('martingale resets', mem.stake === base); +} + +// ── 7. Soak: chip conservation ─────────────────────────────────────────────── +section('7. Soak (20k spins)'); +{ + const rng = mulberry32(12345); + const pickR = (a) => a[Math.floor(rng() * a.length)]; + for (const v of VARIANTS) { + const opps = Array.from({ length: 6 }, (_, i) => ({ name: `Soak${i}${v}` })); + let s = createInitialState(opps, 5000, 'Human', v); + const mem = s.players.map(() => ({})); + const hist = []; + let violations = 0, neg = 0, deltaMismatch = 0; + const legal = legalInsideBets(v); + for (let spin = 0; spin < 10000; spin++) { + // refill busted players so the soak keeps exercising bets + for (const p of s.players) if (p.chips < 50 && !p.bets.length) p.chips += 2000; + for (let pi = 1; pi < s.players.length; pi++) { + for (const spec of chooseBets(s.players[pi], { variant: v, history: hist, memory: mem[pi], rng })) s = placeBet(s, pi, spec); + for (const spec of chooseLateBets(s.players[pi], { variant: v, rng })) s = placeBet(s, pi, spec); + } + // the human: random inside/outside/call bets, some removes + const n = Math.floor(rng() * 5); + for (let k = 0; k < n; k++) { + const r = rng(); + if (r < 0.5) { const b = pickR(legal); s = placeBet(s, 0, { ...b, amount: 1 + Math.floor(rng() * 30) }); } + else if (r < 0.8) s = placeBet(s, 0, { type: pickR([BET.RED, BET.BLACK, BET.ODD, BET.EVEN, BET.LOW, BET.HIGH]), amount: 1 + Math.floor(rng() * 50) }); + else if (v === 'eu') for (const spec of callBetSpecs(v, pickR(['voisins', 'tiers', 'orphelins', 'zero']), 1)) s = placeBet(s, 0, spec); + else s = placeBet(s, 0, { type: BET.DOZEN, number: 1 + Math.floor(rng() * 3), amount: 5 }); + } + if (s.players[0].bets.length && rng() < 0.1) s = removeBet(s, 0, s.players[0].bets[0].key, 3); + const before = s.players.map((p) => p.chips + totalAtRisk(p)); + for (const p of s.players) for (const b of p.bets) if (b.amount > spotLimit(b.type)) violations++; + const value = spinResult(v, rng); + hist.push(value); + const out = resolveSpin(s, value); + s = out.state; + s.players.forEach((p, pi) => { + if (p.chips < 0) neg++; + if (p.chips !== before[pi] + p.lastDelta) deltaMismatch++; + const sum = out.payouts.filter((x) => x.playerIndex === pi).reduce((a, x) => a + x.delta, 0); + if (sum !== p.lastDelta) deltaMismatch++; + noteResult(p, mem[pi], out.payouts.filter((x) => x.playerIndex === pi)); + }); + } + ok(`${v}: chips conserved (stake + delta)`, deltaMismatch === 0, String(deltaMismatch)); + ok(`${v}: never negative`, neg === 0); + ok(`${v}: table limits respected`, violations === 0); + } + // empirical edge on red, 200k spins + for (const v of VARIANTS) { + const r = mulberry32(99); + let net = 0; + const N = 200000; + for (let i = 0; i < N; i++) { + const val = spinResult(v, r); + net += betOutcome({ type: BET.RED, numbers: outsideNumbers(BET.RED), amount: 2 }, val, v).credited - 2; + } + const edge = -net / (2 * N); + const want = v === 'us' ? 2 / 38 : 0.5 / 37; + ok(`${v}: empirical red edge ≈ ${(want * 100).toFixed(2)}%`, Math.abs(edge - want) < 0.006, (edge * 100).toFixed(2)); + } +} + +// ── 8. Ball planner ────────────────────────────────────────────────────────── +section('8. Ball planner'); +{ + let landed = 0, total = 0; + const stats = { settle: [], nmb: [], w: [] }; + for (const v of VARIANTS) { + const pockets = WHEELS[v].pockets; + for (const target of pockets) { + for (let s = 1; s <= 25; s++) { + const plan = planSpin({ variant: v, target, wheelAngle0: s * 0.77, seed: s * 7919 + pockets.indexOf(target) }); + total++; + const T = plan.T; + const good = plan.pocketUnderBall(T.settle) === target && plan.pocketUnderBall(T.end) === target && plan.pocketUnderBall(T.end + 3) === target; + if (good) landed++; + else ok(`${v} ${target} seed ${s} lands`, false, String(plan.pocketUnderBall(T.end))); + ok(`${v} ${target} ω₀ in range`, plan.omega0 >= WHEEL_SPEED.min - 1e-9 && plan.omega0 <= WHEEL_SPEED.max + 1e-9, plan.omega0.toFixed(3)); + ok(`${v} ${target} timeline order`, T.noMoreBets < T.drop && T.drop < T.entry && T.entry < T.settle && T.settle < T.end); + stats.settle.push(T.settle); stats.nmb.push(T.noMoreBets); stats.w.push(plan.omega0); + if (s > 3) continue; // the per-frame sweep is slow; three seeds per pocket + let prev = plan.sample(0), maxJump = 0, rOut = 0, bad = 0, maxWJump = 0; + for (let t = 1 / 120; t <= T.end + 0.5; t += 1 / 120) { + const q = plan.sample(t); + const b = q.ball; + if (![b.angle, b.r, b.h, q.wheel].every(Number.isFinite)) bad++; + if (b.r < GEO.R_POCKET - 0.02 || b.r > GEO.R_TRACK + 0.02 || b.h < -0.01 || b.h > 0.3) rOut++; + maxJump = Math.max(maxJump, Math.abs(b.angle - prev.ball.angle)); + maxWJump = Math.max(maxWJump, Math.abs(q.wheel - prev.wheel)); + prev = q; + } + ok(`${v} ${target} s${s}: finite`, bad === 0); + ok(`${v} ${target} s${s}: ball inside the bowl`, rOut === 0, String(rOut)); + ok(`${v} ${target} s${s}: smooth ball`, maxJump < 0.2, maxJump.toFixed(3)); + ok(`${v} ${target} s${s}: smooth wheel`, maxWJump < 0.05, maxWJump.toFixed(3)); + ok(`${v} ${target} s${s}: ≤ 2 diamond hits`, plan.diamondHits.length <= 2); + } + } + } + ok(`every spin lands on its number (${landed}/${total})`, landed === total); + const mm = (a) => `${Math.min(...a).toFixed(2)}–${Math.max(...a).toFixed(2)}`; + console.log(` settle ${mm(stats.settle)}s · no-more-bets ${mm(stats.nmb)}s · wheel push ${mm(stats.w)} rad/s`); + ok('wheel starts at idle speed', near(planSpin({ variant: 'us', target: 5, seed: 3 }).wheelSpeed(0), WHEEL_SPEED.idle, 1e-9)); + ok('wheelAngleAt(0) = W0', near(wheelAngleAt(1.23, 2.5, 0), 1.23)); + // uniform landing is the RNG's job: spinResult covers the wheel evenly + const r = mulberry32(4); + const freq = new Map(); + for (let i = 0; i < 38000; i++) { const x = spinResult('us', r); freq.set(x, (freq.get(x) ?? 0) + 1); } + ok('spinResult hits every pocket', freq.size === 38); + ok('spinResult roughly uniform', Math.max(...freq.values()) < 1250 && Math.min(...freq.values()) > 750); +} + +// ── 9. Screen layout ───────────────────────────────────────────────────────── +section('9. Screen layout'); +{ + const inScreen = (p, m = 0) => p.x >= m && p.x <= 1920 - m && p.y >= m && p.y <= 1080 - m; + for (const [u, v] of [[-1, 0], [1, 0], [-1, 1], [1, 1]]) ok(`table corner ${u},${v} on screen`, inScreen(P.project(u, v))); + const layoutCorners = [[ZERO_U0, GRID_V0], [COL_U1, GRID_V0], [ZERO_U0, EVEN_V1], [COL_U1, EVEN_V1]]; + for (const [u, v] of layoutCorners) { + ok(`layout corner ${u.toFixed(2)},${v.toFixed(2)} on felt`, u > -1 && u < 1 && v > 0 && v < 1); + } + ok('layout right of the wheel cabinet', ZERO_U0 > CABINET_U1); + const wc = wheelCenter(); + const bowlRight = wc.x + WHEEL.R * 1.12; + const zeroLeft = P.project(ZERO_U0, WHEEL.v).x; + ok('wheel bowl clear of the layout', bowlRight < zeroLeft, `${bowlRight.toFixed(0)} vs ${zeroLeft.toFixed(0)}`); + ok('wheel bowl on screen', wc.x - WHEEL.R * 1.12 > 150 && wc.y - WHEEL.R * WHEEL.tilt * 1.4 > 190); + const ports = []; + for (const name of Object.keys(SEATS)) { + if (name === 'H') continue; + const pt = seatPortrait(name); + ok(`seat ${name} portrait on screen`, inScreen(pt, pt.r)); + ok(`seat ${name} above the dock`, pt.y + pt.r < DOCK.y, `${pt.y + pt.r}`); + ok(`seat ${name} clear of the marquee`, !(pt.x + pt.r > BOARD.x && pt.x - pt.r < BOARD.x + BOARD.w && pt.y - pt.r < BOARD.y + BOARD.h)); + ports.push(pt); + ok(`seat ${name} rail on screen`, inScreen(railPose(name, 0.05)) && inScreen(railPose(name, -0.05))); + } + for (let i = 0; i < ports.length; i++) for (let j = i + 1; j < ports.length; j++) { + ok(`portraits ${i}/${j} apart`, Math.hypot(ports[i].x - ports[j].x, ports[i].y - ports[j].y) > ports[i].r * 2 + 60); + } + ok('seat names for 6', seatNames(6).length === 7 && new Set(seatNames(6)).size === 7); + ok('bank on screen', inScreen(bankPose())); + ok('marquee left of the music widget', BOARD.x + BOARD.w <= 1600 && BOARD.y >= 0); + ok('marquee above the table', BOARD.y + BOARD.h < P.project(0, 0).y - 20); + ok('cam panel above the dock', CAM.y + CAM.h < DOCK.y && CAM.x + CAM.w < 1920); + ok('dealer call clear of the left buttons', CALL.x - 350 > 170); + const nb = P.project(NEIGHBOUR_UI.u, NEIGHBOUR_UI.v); + ok('neighbour stepper right of the racetrack', nb.x - 50 > P.project(RT.u1, NEIGHBOUR_UI.v).x, `${nb.x}`); + ok('neighbour stepper on the felt', NEIGHBOUR_UI.u < 1 - 0.05); + // cell size on screen is comfortable to click + const a = P.project(GRID_U0, GRID_V0), b = P.project(GRID_U0 + CELL_U, GRID_V0); + ok('far cells ≥ 60px wide', b.x - a.x >= 60, (b.x - a.x).toFixed(0)); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);