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
This commit is contained in:
Brian Fertig 2026-11-24 09:59:28 -07:00
parent 7a3205799b
commit 2d1a673b7e
No known key found for this signature in database
9 changed files with 3973 additions and 725 deletions

View File

@ -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);
}

View File

@ -0,0 +1,780 @@
// Roulette art — every texture is baked once into a canvas (no image files).
//
// roulette-table-<felt>-<variant> 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-<variant> the rotating wheel head, top-down
// roulette-bowl-<R> 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 };

View File

@ -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];
},
};
}

File diff suppressed because it is too large Load Diff

View File

@ -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(', ')}`;
}

View File

@ -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

View File

@ -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 };

View File

@ -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-<id> / chip-slice-<id>, 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;

452
tools/verifyRoulette.js Normal file
View File

@ -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);