Overhaul craps with full table art, 3D dice, expanded bets, and AI

- Add perspective-projected craps tub: baked felt layout, padded rail, diamond-pyramid walls, house bank, dice bowl, ON/OFF puck (CrapsArt.js)
- True 3D die rendering and physics-lite throw that relabels the cube to match the rolled face (CrapsDice.js)
- Table geometry module with zones, seats, bet lanes, hit-testing shared by art and input (CrapsTable.js)
- Expand rules: Buy/Lay/Big/Hardways and all one-roll props; 3-4-5× odds caps, barred 12s, called-on working, contract bets, come-bet travel, plain-English payout explanations (CrapsLogic.js)
- Rewrite the scene: shared casino dock, per-seat chip stacks in the rail, felt click-through hit-testing, learner hints, roll-history board, results card, speed/felt settings (CrapsGame.js)
- AI profiles gain hardway/prop/lay appetite and injectable RNG for deterministic verification (CrapsAI.js)
- Add headless verifier: 36-combo resolution tables, exact Markov house edges, chip-conservation AI soak, geometry and dice-throw checks (tools/verifyCraps.js)
This commit is contained in:
Brian Fertig 2026-11-24 09:18:11 -07:00
parent d33ab09ae0
commit 7a3205799b
No known key found for this signature in database
7 changed files with 4227 additions and 1098 deletions

View File

@ -4,26 +4,36 @@
// shapes what they bet and how big. Functions return plain bet specs / odds
// requests; the scene applies them through CrapsLogic (which guards affordability).
import { BET, POINT_NUMBERS, legalBetTypes, oddsEligibleBets, maxOddsFor } from './CrapsLogic.js';
import {
BET, POINT_NUMBERS, HARD_NUMBERS, legalBetTypes, oddsEligibleBets, maxOddsFor,
} from './CrapsLogic.js';
const PROFILES = {
// unitPct: flat-bet size as a fraction of bankroll
// oddsMult: odds as a multiple of the flat bet
// fieldChance: probability of tossing a field bet on a come-out
// place: which numbers they like to place during the point phase
// dontChance: probability of betting the Don't side instead of Pass
conservative: { unitPct: 0.03, oddsMult: 1, fieldChance: 0.10, place: [], dontChance: 0.18, comeChance: 0.10 },
balanced: { unitPct: 0.05, oddsMult: 2, fieldChance: 0.25, place: [6, 8], dontChance: 0.10, comeChance: 0.25 },
aggressive: { unitPct: 0.08, oddsMult: 3, fieldChance: 0.55, place: [6, 8, 5, 9], dontChance: 0.05, comeChance: 0.45 },
gambler: { unitPct: 0.11, oddsMult: 3, fieldChance: 0.80, place: [6, 8, 4, 10],dontChance: 0.00, comeChance: 0.60 },
// oddsMult: odds as a multiple of the flat bet (capped at the table's 3-4-5×)
// fieldChance: chance of a field flyer on a roll
// place: numbers they like to place during the point phase
// dontChance: chance of betting the Don't side instead of Pass
// comeChance / maxCome: come-bet appetite (and how many working at once)
// hardChance: chance of backing the point (and 6/8) the hard way
// propChance: chance of a one-roll proposition flyer (C&E / Yo / Any craps)
// layChance: chance of laying the 4 or 10 (dark-side players only)
conservative: { unitPct: 0.03, oddsMult: 1, fieldChance: 0.05, place: [], dontChance: 0.35, comeChance: 0.10, maxCome: 1, hardChance: 0, propChance: 0, layChance: 0.4 },
balanced: { unitPct: 0.05, oddsMult: 2, fieldChance: 0.12, place: [6, 8], dontChance: 0.10, comeChance: 0.30, maxCome: 2, hardChance: 0.12, propChance: 0.05, layChance: 0 },
aggressive: { unitPct: 0.08, oddsMult: 5, fieldChance: 0.30, place: [6, 8, 5, 9], dontChance: 0.05, comeChance: 0.45, maxCome: 2, hardChance: 0.30, propChance: 0.15, layChance: 0 },
gambler: { unitPct: 0.11, oddsMult: 5, fieldChance: 0.45, place: [6, 8, 4, 10], dontChance: 0.00, comeChance: 0.55, maxCome: 3, hardChance: 0.50, propChance: 0.35, layChance: 0 },
};
const PROFILE_KEYS = Object.keys(PROFILES);
function profileFor(player) {
export function profileName(player) {
const name = player.name ?? player.avatar?.id ?? 'bot';
let h = 0;
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
return PROFILES[PROFILE_KEYS[h % PROFILE_KEYS.length]];
return PROFILE_KEYS[h % PROFILE_KEYS.length];
}
function profileFor(player) {
return PROFILES[profileName(player)];
}
const snap = (n, step) => Math.max(step, Math.round(n / step) * step);
@ -38,45 +48,56 @@ function placeSize(player, prof, number) {
return Math.min(120, snap(player.chips * prof.unitPct, step));
}
// Flat bets to open for the current phase. Returns an array of bet specs.
export function chooseBets(player, state) {
// Flat bets to open for the next roll. Returns an array of bet specs.
// `rng` is injectable so the verify soak is deterministic.
export function chooseBets(player, state, rng = Math.random) {
const prof = profileFor(player);
const legal = legalBetTypes(state);
const specs = [];
let budget = player.chips;
const afford = (amt) => amt > 0 && amt <= budget;
const push = (spec) => { if (afford(spec.amount)) { specs.push(spec); budget -= spec.amount; } };
const has = (type, number = null) => player.bets.some((b) => b.type === type && (number == null || b.number === number));
const unit = unitFor(player, prof);
if (state.point === null) {
// Come-out: take a line bet, maybe a field flyer.
const unit = unitFor(player, prof);
const hasLine = player.bets.some((b) => b.type === BET.PASS || b.type === BET.DONT_PASS);
if (!hasLine && afford(unit)) {
const dont = Math.random() < prof.dontChance && legal.has(BET.DONT_PASS);
specs.push({ type: dont ? BET.DONT_PASS : BET.PASS, amount: unit });
budget -= unit;
// Come-out: a line bet, maybe a flyer.
const hasLine = has(BET.PASS) || has(BET.DONT_PASS);
if (!hasLine && legal.has(BET.PASS)) {
const dont = rng() < prof.dontChance;
push({ type: dont ? BET.DONT_PASS : BET.PASS, amount: unit });
}
if (Math.random() < prof.fieldChance) {
const f = snap(unit / 2, 5);
if (afford(f)) { specs.push({ type: BET.FIELD, amount: f }); budget -= f; }
}
} else {
// Point phase: maybe a come bet, plus favourite place numbers.
if (Math.random() < prof.comeChance) {
const unit = unitFor(player, prof);
if (afford(unit)) { specs.push({ type: BET.COME, amount: unit }); budget -= unit; }
}
const placed = new Set(player.bets.filter((b) => b.type === BET.PLACE).map((b) => b.number));
for (const num of prof.place) {
if (placed.has(num) || num === state.point) continue;
if (!POINT_NUMBERS.includes(num)) continue;
const amt = placeSize(player, prof, num);
if (afford(amt)) { specs.push({ type: BET.PLACE, number: num, amount: amt }); budget -= amt; }
if (rng() < prof.fieldChance) push({ type: BET.FIELD, amount: snap(unit / 2, 5) });
if (rng() < prof.propChance) push({ type: rng() < 0.6 ? BET.CE : BET.YO, amount: rng() < 0.5 ? 2 : 5 });
return specs;
}
// Point phase.
const comeCount = player.bets.filter((b) => b.type === BET.COME || b.type === BET.DONT_COME).length;
const dark = has(BET.DONT_PASS);
if (comeCount < prof.maxCome && rng() < prof.comeChance) {
push({ type: dark ? BET.DONT_COME : BET.COME, amount: unit });
}
if (dark && rng() < prof.layChance) {
for (const n of [4, 10]) {
if (n !== state.point && !has(BET.LAY, n)) { push({ type: BET.LAY, number: n, amount: snap(unit * 2, 20) }); break; }
}
}
const comeNums = new Set(player.bets.map((b) => b.comePoint).filter((n) => n != null));
for (const num of prof.place) {
if (has(BET.PLACE, num) || num === state.point || comeNums.has(num)) continue;
if (!POINT_NUMBERS.includes(num)) continue;
push({ type: BET.PLACE, number: num, amount: placeSize(player, prof, num) });
}
if (HARD_NUMBERS.includes(state.point) && !has(BET.HARD, state.point) && rng() < prof.hardChance) {
push({ type: BET.HARD, number: state.point, amount: 5 });
}
if (rng() < prof.fieldChance * 0.5) push({ type: BET.FIELD, amount: snap(unit / 2, 5) });
if (rng() < prof.propChance * 0.4) push({ type: BET.ANY_CRAPS, amount: 1 + Math.floor(rng() * 5) });
return specs;
}
// Odds to lay behind eligible line/come bets. Returns [{ betId, amount }].
// Odds behind eligible line/come bets that don't have them yet. Returns [{ betId, amount }].
export function chooseOdds(player, state) {
const prof = profileFor(player);
if (prof.oddsMult <= 0) return [];
@ -84,8 +105,9 @@ export function chooseOdds(player, state) {
let budget = player.chips;
for (const bet of oddsEligibleBets(player, state)) {
if (bet.oddsAmount > 0) continue;
const want = Math.min(bet.amount * prof.oddsMult, maxOddsFor(bet));
const amt = snap(want, 5);
const cap = maxOddsFor(bet, state);
const want = Math.min(bet.amount * prof.oddsMult, cap);
const amt = Math.min(cap, snap(want, 5));
if (amt > 0 && amt <= budget) { out.push({ betId: bet.id, amount: amt }); budget -= amt; }
}
return out;

699
src/games/craps/CrapsArt.js Normal file
View File

@ -0,0 +1,699 @@
// Craps table art — one end of a casino craps tub baked once into 'craps-table':
// floor shadow, padded rail with a wooden chip groove, the sunken felt with the
// full betting layout, proposition box and C&E circles, diamond-pyramid rubber
// on the inner walls, the house bank set into the far rail, and the stickman's
// dice bowl. Also bakes the ON/OFF puck.
//
// All positions come from CrapsTable.js so the art lines up with hit-testing
// and chip placement.
import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern } from '../../ui/casino/CasinoArt.js';
import { CHIP_DEFS } from '../../ui/CasinoChips.js';
import {
P, VIEW, TUB, lift, tubOutline, ZONES, ROWS, BOX_NUMS, boxU, END_U, LAYOUT_U1, PASS_SIDE,
PROP, LANDING, BANK, BOWL, LANES, SLOT_ORDER, rectCenter,
} from './CrapsTable.js';
const W = 1920, H = 1080;
export const FELTS = { green: '#0d5a2e', blue: '#123c78', red: '#6a1020' };
const LINE = 'rgba(244,236,214,0.88)';
const LINE_SOFT = 'rgba(244,236,214,0.45)';
const WHITE = '#f4ecd6';
const RED = '#d8392b';
const GOLD = '#e8c15a';
const SERIF = 'Georgia, "Times New Roman", serif';
const SANS = '"Julius Sans One", sans-serif';
const LEATHER_DARK = '#0f0806', LEATHER_MID = '#2c1a12', LEATHER_HI = '#5e3e2b';
export async function prepareCrapsArt(scene, felt = 'green') {
await prepareCasinoArt(scene);
const key = `craps-table-${felt}`;
if (!scene.textures.exists(key)) bakeTable(scene, key, FELTS[felt] ?? FELTS.green);
if (!scene.textures.exists('craps-puck-on')) bakePuck(scene, 'craps-puck-on', true);
if (!scene.textures.exists('craps-puck-off')) bakePuck(scene, 'craps-puck-off', false);
return key;
}
// ── Small projection helpers ─────────────────────────────────────────────────
const toScreen = (pts, h = 0) => pts.map(p => lift(p.u, p.v, h));
function rectPts(r) {
return [P.project(r.u0, r.v0), P.project(r.u1, r.v0), P.project(r.u1, r.v1), P.project(r.u0, r.v1)];
}
function strokeRect(ctx, r, color = LINE, width = 2.4) {
poly(ctx, rectPts(r));
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.stroke();
}
function fillRect(ctx, r, color) {
poly(ctx, rectPts(r));
ctx.fillStyle = color;
ctx.fill();
}
// Text lying flat on the felt at (u, v): sized in px at s = 1.
function feltText(ctx, u, v, text, size, color, {
font = SERIF, bold = true, rot = 0, spacing = 0, alpha = 1, maxW = null, shadow = true,
} = {}) {
const p = P.project(u, v);
ctx.save();
ctx.globalAlpha = alpha;
ctx.translate(p.x, p.y);
ctx.scale(p.s, p.s * VIEW.squash);
ctx.rotate(rot);
ctx.font = `${bold ? 'bold ' : ''}${size}px ${font}`;
if (spacing) ctx.letterSpacing = `${spacing}px`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
if (shadow) {
ctx.shadowColor = 'rgba(0,0,0,0.4)';
ctx.shadowBlur = 2;
ctx.shadowOffsetY = 1;
}
ctx.fillStyle = color;
if (maxW) {
const w = ctx.measureText(text).width;
if (w > maxW) ctx.scale(maxW / w, 1);
}
ctx.fillText(text, 0, 0);
ctx.restore();
}
const PIPS = {
1: [[0, 0]], 2: [[-1, -1], [1, 1]], 3: [[-1, -1], [0, 0], [1, 1]],
4: [[-1, -1], [1, -1], [-1, 1], [1, 1]], 5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]],
6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]],
};
// A small die printed on the felt.
function feltDie(ctx, u, v, size, face, { body = '#f4ecd6', pip = '#1a1208', alpha = 1 } = {}) {
const p = P.project(u, v);
ctx.save();
ctx.globalAlpha = alpha;
ctx.translate(p.x, p.y);
ctx.scale(p.s, p.s * VIEW.squash);
rr(ctx, -size / 2, -size / 2, size, size, size * 0.2);
ctx.fillStyle = body;
ctx.fill();
ctx.lineWidth = 1.2;
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.stroke();
ctx.fillStyle = pip;
for (const [x, y] of PIPS[face]) {
ctx.beginPath();
ctx.arc(x * size * 0.27, y * size * 0.27, size * 0.1, 0, Math.PI * 2);
ctx.fill();
}
ctx.restore();
}
// Text printed up a band that runs along v at a fixed u (reading bottom → top,
// i.e. from v1 toward v0). Each letter sits on the projected centre line with
// its baseline along the band and its uprights along the felt's u direction, so
// the lettering leans with the perspective instead of standing straight up.
function feltTextUpBand(ctx, u, v0, v1, text, size, color, { font = SERIF, bold = true, spacing = 0, alpha = 1 } = {}) {
ctx.save();
ctx.globalAlpha = alpha;
ctx.font = `${bold ? 'bold ' : ''}${size}px ${font}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = color;
ctx.shadowColor = 'rgba(0,0,0,0.4)';
ctx.shadowBlur = 2;
ctx.shadowOffsetY = 1;
const q = VIEW.squash;
const chars = [...text];
const widths = chars.map((ch) => (ctx.measureText(ch).width + spacing) * q);
const total = widths.reduce((a, b) => a + b, 0) - spacing * q;
const DV = 0.0005;
// Walk `px` felt-pixels (screen distance ÷ local scale) along the band; dir −1 = up the screen.
const walk = (v, px, dir) => {
let rem = px;
while (rem > 1e-6) {
const a = P.project(u, v), b = P.project(u, v + dir * DV);
const d = Math.hypot(b.x - a.x, b.y - a.y) / a.s;
if (d >= rem) { v += dir * DV * (rem / d); rem = 0; } else { v += dir * DV; rem -= d; }
}
return v;
};
let v = walk((v0 + v1) / 2, total / 2, +1); // start below the centre
chars.forEach((ch, i) => {
const mid = walk(v, widths[i] / 2, -1);
v = walk(v, widths[i], -1);
if (ch === ' ') return;
const p = P.project(u, mid);
const up = P.project(u, mid - DV), dn = P.project(u, mid + DV);
const tl = Math.hypot(up.x - dn.x, up.y - dn.y);
const tx = (up.x - dn.x) / tl, ty = (up.y - dn.y) / tl; // reading direction
const r0 = P.project(u - 0.001, mid), r1 = P.project(u + 0.001, mid);
const rl = Math.hypot(r1.x - r0.x, r1.y - r0.y);
const rx = (r1.x - r0.x) / rl, ry = (r1.y - r0.y) / rl; // glyph "down" = toward +u
const k = p.s;
ctx.save();
ctx.transform(tx * k * q, ty * k * q, rx * k, ry * k, p.x, p.y);
ctx.fillText(ch, 0, 0);
ctx.restore();
});
ctx.restore();
}
function dicePair(ctx, u, v, size, a, b, opts) {
const p = P.project(u, v);
const du = (size * 0.62) / (VIEW.halfW * p.s);
feltDie(ctx, u - du, v, size, a, opts);
feltDie(ctx, u + du, v, size, b, opts);
}
// ── Table ────────────────────────────────────────────────────────────────────
function bakeTable(scene, key, felt) {
const c = canvas(W, H);
const ctx = c.getContext('2d');
drawFloorShadow(ctx);
drawRailFace(ctx);
drawFelt(ctx, felt);
drawWalls(ctx);
drawRailTop(ctx);
drawBank(ctx);
drawBowl(ctx);
scene.textures.addCanvas(key, c);
}
function outlineScreen(d, h, extraDown = 0) {
return tubOutline(d, 14, 40).map(p => {
const q = lift(p.u, p.v, h);
return { x: q.x, y: q.y + extraDown * q.s, s: q.s };
});
}
function drawFloorShadow(ctx) {
const OFF = 6000;
const pts = outlineScreen(TUB.RW, TUB.H, TUB.FACE + 10);
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.75)';
ctx.shadowBlur = 70;
ctx.shadowOffsetX = OFF;
ctx.shadowOffsetY = 30;
poly(ctx, pts.map(p => ({ x: p.x - OFF, y: p.y })));
ctx.fillStyle = '#000';
ctx.fill();
ctx.restore();
}
// The rail's outer side (visible below the near rail and around the end).
function drawRailFace(ctx) {
const top = outlineScreen(TUB.RW, TUB.H);
ctx.save();
poly(ctx, top.map(p => ({ x: p.x, y: p.y + TUB.FACE * p.s })));
ctx.fillStyle = '#2a170c';
ctx.fill();
for (let i = 0; i <= 14; i++) {
const f = i / 14;
poly(ctx, top.map(p => ({ x: p.x, y: p.y + TUB.FACE * p.s * f })));
ctx.lineWidth = 4;
ctx.strokeStyle = mix('#7a4520', '#2a170c', Math.min(1, f * 1.2));
ctx.stroke();
}
// brass kick-rail line
poly(ctx, top.map(p => ({ x: p.x, y: p.y + TUB.FACE * p.s * 0.78 })));
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgba(214,174,90,0.55)';
ctx.stroke();
ctx.restore();
}
function drawFelt(ctx, felt) {
const feltPts = outlineScreen(0, 0);
ctx.save();
poly(ctx, feltPts);
ctx.clip();
ctx.fillStyle = felt;
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = noisePattern(ctx, 256, 22);
ctx.fillRect(0, 0, W, H);
drawLayout(ctx, felt);
drawProps(ctx, felt);
drawLanding(ctx);
// overhead lamp + vignette toward the walls
const c = P.project(-0.1, 0.5);
const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1000);
lamp.addColorStop(0, 'rgba(255,246,205,0.18)');
lamp.addColorStop(0.5, 'rgba(255,246,205,0.06)');
lamp.addColorStop(1, 'rgba(255,246,205,0)');
ctx.fillStyle = lamp;
ctx.fillRect(0, 0, W, H);
const vig = ctx.createRadialGradient(c.x, c.y, 420, c.x, c.y, 1150);
vig.addColorStop(0, 'rgba(0,0,0,0)');
vig.addColorStop(1, 'rgba(0,0,0,0.45)');
ctx.fillStyle = vig;
ctx.fillRect(0, 0, W, H);
// contact shadow along the walls
for (let i = 0; i < 9; i++) {
poly(ctx, toScreen(tubOutline(-i * 0.006, 14, 40)));
ctx.lineWidth = 5;
ctx.strokeStyle = `rgba(0,0,0,${0.3 * (1 - i / 9)})`;
ctx.stroke();
}
ctx.restore();
}
// ── Betting end ──────────────────────────────────────────────────────────────
function drawLayout(ctx, felt) {
const Z = (k) => ZONES[k].rects[0];
// Number boxes
for (const n of BOX_NUMS) {
const { u0, u1 } = boxU(n);
const um = (u0 + u1) / 2;
strokeRect(ctx, { u0, u1, v0: ROWS.lay[0], v1: ROWS.buy[1] }, LINE, 2.6);
strokeRect(ctx, { u0, u1, v0: ROWS.lay[1], v1: ROWS.main[1] }, LINE_SOFT, 1.4);
const label = n === 6 ? 'SIX' : n === 9 ? 'NINE' : String(n);
feltText(ctx, um, 0.15, label, n === 6 || n === 9 ? 34 : 50, WHITE, { maxW: 120 });
feltText(ctx, um, ROWS.lay[0] + 0.028, 'LAY', 13, LINE_SOFT, { font: SANS, bold: false, spacing: 2 });
const pays = n === 6 || n === 8 ? '7 TO 6' : n === 5 || n === 9 ? '7 TO 5' : '9 TO 5';
feltText(ctx, um, 0.225, pays, 12, GOLD, { font: SANS, bold: false, alpha: 0.8 });
feltText(ctx, um, (ROWS.buy[0] + ROWS.buy[1]) / 2, 'BUY', 13, LINE_SOFT, { font: SANS, bold: false, spacing: 2 });
}
// Don't Come bar
{
const r = Z('dontcome');
strokeRect(ctx, r, LINE, 2.6);
const um = (r.u0 + r.u1) / 2;
feltText(ctx, um, 0.08, "DON'T", 17, WHITE);
feltText(ctx, um, 0.125, 'COME', 17, WHITE);
feltText(ctx, um, 0.17, 'BAR', 14, WHITE, { font: SANS });
dicePair(ctx, um, 0.215, 15, 6, 6);
}
// Come
{
const r = Z('come');
strokeRect(ctx, r, LINE, 2.6);
const c = rectCenter(r);
feltText(ctx, c.u, c.v - 0.012, 'COME', 64, RED, { spacing: 14 });
}
// Field
{
const r = Z('field');
strokeRect(ctx, r, LINE, 2.6);
const nums = [2, 3, 4, 9, 10, 11, 12];
const u0 = r.u0 + 0.16, u1 = r.u1 - 0.05;
const vm = r.v0 + (r.v1 - r.v0) * 0.36;
feltText(ctx, r.u0 + 0.075, vm + 0.012, 'FIELD', 30, GOLD, { spacing: 3 });
nums.forEach((n, i) => {
const u = u0 + ((i + 0.5) / nums.length) * (u1 - u0);
if (n === 2 || n === 12) {
const p = P.project(u, vm);
ctx.save();
ctx.translate(p.x, p.y);
ctx.scale(p.s, p.s * VIEW.squash);
ctx.beginPath();
ctx.arc(0, 0, 25, 0, Math.PI * 2);
ctx.lineWidth = 2.4;
ctx.strokeStyle = GOLD;
ctx.stroke();
ctx.restore();
feltText(ctx, u, vm + 0.004, String(n), 30, WHITE);
feltText(ctx, u, vm + 0.058, n === 2 ? 'PAYS DOUBLE' : 'PAYS TRIPLE', 11, GOLD, { font: SANS, bold: false });
} else {
feltText(ctx, u, vm + 0.004, String(n), 34, WHITE);
if (i < nums.length - 1) feltText(ctx, u + (u1 - u0) / nums.length / 2, vm, '•', 18, GOLD);
}
});
}
// Big 6 / 8
for (const [k, n] of [['big6', 6], ['big8', 8]]) {
const r = Z(k);
strokeRect(ctx, r, LINE, 2.6);
const c = rectCenter(r);
feltText(ctx, c.u, c.v - 0.018, String(n), 54, RED);
feltText(ctx, c.u, r.v0 + 0.02, 'BIG', 12, WHITE, { font: SANS, bold: false });
}
// Don't Pass bar
{
const r = Z('dontpass');
strokeRect(ctx, r, LINE, 2.6);
const c = rectCenter(r);
feltText(ctx, c.u - 0.06, c.v, "DON'T PASS BAR", 24, WHITE, { spacing: 3 });
dicePair(ctx, c.u + 0.24, c.v, 18, 6, 6);
}
// Pass line — bottom band + the band up the end, drawn as one L
{
const b = ZONES.pass.rects[0], sd = ZONES.pass.rects[1];
const pts = [
P.project(sd.u0, sd.v0), P.project(sd.u1, sd.v0), P.project(sd.u1, b.v0),
P.project(b.u1, b.v0), P.project(b.u1, b.v1), P.project(b.u0, b.v1),
];
poly(ctx, pts);
ctx.lineWidth = 3;
ctx.strokeStyle = LINE;
ctx.stroke();
const c = rectCenter(b);
feltText(ctx, c.u - 0.03, c.v - 0.012, 'PASS LINE', 56, WHITE, { spacing: 8 });
// up the end
feltTextUpBand(ctx, (sd.u0 + sd.u1) / 2, sd.v0, b.v0, 'PASS LINE', 34, WHITE, { spacing: 6 });
}
// Odds strip behind the line (subtle)
{
const r = ZONES.odds.rects[0];
const pts = [P.project(r.u0, r.v0), P.project(r.u1, r.v0)];
ctx.save();
ctx.setLineDash([10, 8]);
poly(ctx, pts, false);
ctx.lineWidth = 1.4;
ctx.strokeStyle = LINE_SOFT;
ctx.stroke();
ctx.restore();
for (const u of [r.u0 + 0.12, (r.u0 + r.u1) / 2, r.u1 - 0.12]) {
feltText(ctx, u, (r.v0 + r.v1) / 2 + 0.006, 'ODDS', 14, LINE_SOFT, { font: SANS, bold: false, spacing: 4 });
}
}
void felt;
}
// ── Proposition box ──────────────────────────────────────────────────────────
function drawProps(ctx, felt) {
const outer = { u0: PROP.u0, u1: PROP.u1, v0: PROP.v0, v1: PROP.v1 };
fillRect(ctx, outer, 'rgba(0,0,0,0.12)');
strokeRect(ctx, outer, GOLD, 3);
const Z = (k) => ZONES[k].rects[0];
// Any seven
{
const r = Z('any7');
strokeRect(ctx, r, LINE, 2);
const c = rectCenter(r);
feltText(ctx, c.u, c.v, 'SEVEN 4 TO 1', 22, RED, { maxW: 200 });
}
// Hardways
const HW = { hard6: [3, 3, '9 TO 1'], hard10: [5, 5, '7 TO 1'], hard8: [4, 4, '9 TO 1'], hard4: [2, 2, '7 TO 1'] };
for (const [k, [a, b, pays]] of Object.entries(HW)) {
const r = Z(k);
strokeRect(ctx, r, LINE, 2);
const c = rectCenter(r);
dicePair(ctx, c.u, c.v - 0.025, 22, a, b, { body: '#c41f2a', pip: '#fbf3df' });
feltText(ctx, c.u, c.v + 0.04, pays, 15, WHITE, { font: SANS });
}
// One-roll row
const ONE = { acedeuce: [1, 2, '15 TO 1'], aces: [1, 1, '30 TO 1'], boxcars: [6, 6, '30 TO 1'], yo: [5, 6, '15 TO 1'] };
for (const [k, [a, b, pays]] of Object.entries(ONE)) {
const r = Z(k);
strokeRect(ctx, r, LINE, 2);
const c = rectCenter(r);
dicePair(ctx, c.u, c.v - 0.025, 15, a, b, { body: '#c41f2a', pip: '#fbf3df' });
feltText(ctx, c.u, c.v + 0.032, pays, 11, WHITE, { font: SANS });
}
// Horn
{
const r = Z('horn');
strokeRect(ctx, r, LINE, 2);
const c = rectCenter(r);
feltText(ctx, c.u - 0.07, c.v, 'HORN', 22, GOLD, { spacing: 4 });
feltText(ctx, c.u + 0.07, c.v, '2 · 3 · 11 · 12', 15, WHITE, { font: SANS });
}
// Any craps
{
const r = Z('anycraps');
strokeRect(ctx, r, LINE, 2);
const c = rectCenter(r);
feltText(ctx, c.u, c.v, 'ANY CRAPS 7 TO 1', 22, RED, { maxW: 220 });
}
// C & E circles — one per seat position, top to bottom
{
const r = Z('ce');
strokeRect(ctx, r, LINE, 2);
const L = LANES.ce;
for (let i = 0; i < SLOT_ORDER.length; i++) {
const v = L.v0 + ((i + 0.5) / SLOT_ORDER.length) * (L.v1 - L.v0);
const p = P.project(L.u, v);
ctx.save();
ctx.translate(p.x, p.y);
ctx.scale(p.s, p.s * VIEW.squash);
const rad = 17;
ctx.beginPath(); ctx.arc(0, 0, rad, Math.PI, 0); ctx.closePath();
ctx.fillStyle = 'rgba(244,236,214,0.9)'; ctx.fill();
ctx.beginPath(); ctx.arc(0, 0, rad, 0, Math.PI); ctx.closePath();
ctx.fillStyle = RED; ctx.fill();
ctx.beginPath(); ctx.arc(0, 0, rad, 0, Math.PI * 2);
ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke();
ctx.font = `bold 13px ${SERIF}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#7a1010'; ctx.fillText('C', 0, -7);
ctx.fillStyle = '#fbf3df'; ctx.fillText('E', 0, 8);
ctx.restore();
}
}
void felt;
}
// ── Landing area ─────────────────────────────────────────────────────────────
function drawLanding(ctx) {
const c = { u: (LANDING.u0 + LANDING.u1) / 2, v: (LANDING.v0 + LANDING.v1) / 2 };
feltTextUpBand(ctx, c.u, LANDING.v0, LANDING.v1, '♦ C R A P S ♦', 38, GOLD, { alpha: 0.22, spacing: 6 });
}
// ── Walls with diamond-pyramid rubber ────────────────────────────────────────
function drawWalls(ctx) {
const base = tubOutline(0, 18, 60);
const n = base.length;
for (let i = 0; i < n; i++) {
const a = base[i], b = base[(i + 1) % n];
// inner face normal (pointing into the tub) — skip faces turned away
const nu = -(b.v - a.v), nv = b.u - a.u; // left normal of a clockwise outline points inward
const facing = nv > 1e-6 || Math.abs(nu) > 1e-6 && nv >= -1e-6;
if (!facing) continue;
const A0 = lift(a.u, a.v, 0), B0 = lift(b.u, b.v, 0);
const A1 = lift(a.u, a.v, TUB.H), B1 = lift(b.u, b.v, TUB.H);
// padded rubber base
poly(ctx, [A0, B0, B1, A1]);
ctx.fillStyle = '#17110d';
ctx.fill();
ctx.lineWidth = 0.6;
ctx.strokeStyle = '#17110d';
ctx.stroke();
// pyramids: two rows of diamonds per segment
const rows = 2;
for (let r = 0; r < rows; r++) {
const t0 = r / rows, t1 = (r + 1) / rows;
const q = [
mixPt(A0, A1, t0), mixPt(B0, B1, t0), mixPt(B0, B1, t1), mixPt(A0, A1, t1),
];
const apex = mixPt(mixPt(q[0], q[2], 0.5), mixPt(q[1], q[3], 0.5), 0.5);
apex.y -= 1.2;
const faces = [
[q[3], q[2], apex, '#4a3a2e'], // top facet (lit)
[q[0], q[3], apex, '#2a2019'],
[q[2], q[1], apex, '#231a14'],
[q[1], q[0], apex, '#120c09'], // bottom facet (shadow)
];
for (const [p1, p2, p3, col] of faces) {
ctx.beginPath();
ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.lineTo(p3.x, p3.y); ctx.closePath();
ctx.fillStyle = col;
ctx.fill();
}
}
}
// seam where wall meets felt
poly(ctx, toScreen(base));
ctx.lineWidth = 1.5;
ctx.strokeStyle = 'rgba(0,0,0,0.55)';
ctx.stroke();
}
function mixPt(a, b, t) { return { x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t) }; }
// ── Rail top: padded leather lip, wooden chip groove, padded outer roll ──────
function bandPath(ctx, d0, d1) {
const outer = toScreen(tubOutline(d1, 14, 40), TUB.H);
const inner = toScreen(tubOutline(d0, 14, 40), TUB.H);
ctx.beginPath();
outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.closePath();
inner.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.closePath();
}
function ring(ctx, d, width, color) {
poly(ctx, toScreen(tubOutline(d, 14, 40), TUB.H));
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.stroke();
}
function padColor(f) {
const ridge = Math.max(0, Math.cos((f - 0.45) * Math.PI));
return ridge > 0.7 ? mix(LEATHER_MID, LEATHER_HI, (ridge - 0.7) / 0.3) : mix(LEATHER_DARK, LEATHER_MID, Math.min(1, ridge * 1.4));
}
export const GROOVE = { d0: 0.3, d1: 0.72 }; // fraction of the rail width
function drawRailTop(ctx) {
const RW = TUB.RW;
const g0 = RW * GROOVE.d0, g1 = RW * GROOVE.d1;
// inner padded lip
ctx.save();
bandPath(ctx, 0, g0);
ctx.fillStyle = LEATHER_MID;
ctx.fill('evenodd');
ctx.clip('evenodd');
for (let i = 0; i <= 10; i++) ring(ctx, lerp(0, g0, i / 10), 3, padColor(i / 10));
ctx.fillStyle = noisePattern(ctx, 128, 24);
ctx.fillRect(0, 0, W, H);
ctx.restore();
// wooden groove
ctx.save();
bandPath(ctx, g0, g1);
ctx.fillStyle = '#6b3b18';
ctx.fill('evenodd');
ctx.clip('evenodd');
for (let i = 0; i <= 12; i++) {
const f = i / 12;
ring(ctx, lerp(g0, g1, f), 3, mix('#3a1e0a', '#8a5426', Math.sin(f * Math.PI) * 0.9));
}
ctx.fillStyle = noisePattern(ctx, 128, 18);
ctx.fillRect(0, 0, W, H);
ctx.restore();
ring(ctx, g0, 1.5, 'rgba(0,0,0,0.6)');
ring(ctx, g1, 1.2, 'rgba(255,210,150,0.25)');
// outer padded roll
ctx.save();
bandPath(ctx, g1, RW);
ctx.fillStyle = LEATHER_MID;
ctx.fill('evenodd');
ctx.clip('evenodd');
for (let i = 0; i <= 14; i++) ring(ctx, lerp(g1, RW, i / 14), 3, padColor(i / 14));
ctx.fillStyle = noisePattern(ctx, 128, 26);
ctx.fillRect(0, 0, W, H);
ctx.setLineDash([7, 5]);
ring(ctx, lerp(g1, RW, 0.5), 1.4, 'rgba(214,174,120,0.4)');
ctx.setLineDash([]);
ctx.restore();
ring(ctx, RW, 2, 'rgba(0,0,0,0.75)');
ring(ctx, 0, 1.5, 'rgba(0,0,0,0.6)');
}
// House bank: chips racked in the far rail.
function drawBank(ctx) {
const d = TUB.RW * (GROOVE.d0 + GROOVE.d1) / 2;
const a = lift(BANK.u0, -d, TUB.H), b = lift(BANK.u1, -d, TUB.H);
const h = 22 * a.s;
rr(ctx, a.x - 8, a.y - h / 2 - 5, b.x - a.x + 16, h + 10, 6);
ctx.fillStyle = '#120c08';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgba(214,174,120,0.6)';
ctx.stroke();
const cols = [1, 5, 5, 25, 25, 25, 50, 100, 100, 100, 50, 25, 25, 25, 5, 5, 1];
const cw = (b.x - a.x) / cols.length;
cols.forEach((den, i) => {
const def = CHIP_DEFS[den];
const x0 = a.x + i * cw + 1.5;
for (let k = 0; k < 7; k++) {
ctx.fillStyle = k % 2 ? def.base : mix(def.base, '#000000', 0.22);
ctx.fillRect(x0, a.y - h / 2 + (k * h) / 7, cw - 3, h / 7 + 0.5);
}
ctx.fillStyle = 'rgba(255,255,255,0.18)';
ctx.fillRect(x0, a.y - h / 2, (cw - 3) * 0.35, h);
});
// brass plate
const m = { x: (a.x + b.x) / 2, y: a.y - h / 2 - 22 };
rr(ctx, m.x - 70, m.y - 11, 140, 22, 5);
const g = ctx.createLinearGradient(0, m.y - 11, 0, m.y + 11);
g.addColorStop(0, '#f0d78a'); g.addColorStop(1, '#9a7428');
ctx.fillStyle = g;
ctx.fill();
ctx.font = `bold 11px ${SANS}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#2a1a06';
ctx.fillText('TABLE MIN $1 · MAX $500', m.x, m.y + 1);
}
// The stickman's dice bowl at the far rail.
function drawBowl(ctx) {
const p = lift(BOWL.u, -TUB.RW * 0.5, TUB.H);
const rx = 40 * p.s, ry = 15 * p.s;
ctx.save();
ctx.beginPath();
ctx.ellipse(p.x, p.y + 4, rx + 3, ry + 5, 0, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fill();
const g = ctx.createLinearGradient(p.x - rx, 0, p.x + rx, 0);
g.addColorStop(0, '#3b2414'); g.addColorStop(0.5, '#8b5a30'); g.addColorStop(1, '#2a180c');
ctx.beginPath();
ctx.ellipse(p.x, p.y, rx, ry, 0, 0, Math.PI * 2);
ctx.fillStyle = g;
ctx.fill();
ctx.beginPath();
ctx.ellipse(p.x, p.y - 1, rx * 0.78, ry * 0.7, 0, 0, Math.PI * 2);
ctx.fillStyle = '#1a0f08';
ctx.fill();
// a few spare dice in the bowl
const dice = [[-14, -2], [2, 1], [15, -3]];
for (const [dx, dy] of dice) {
const s = 10 * p.s;
rr(ctx, p.x + dx * p.s - s / 2, p.y + dy * p.s - s / 2, s, s * 0.8, 2);
ctx.fillStyle = '#c41f2a';
ctx.fill();
ctx.fillStyle = '#fbf3df';
ctx.beginPath(); ctx.arc(p.x + dx * p.s, p.y + dy * p.s - 0.5, 1.3, 0, Math.PI * 2); ctx.fill();
}
ctx.restore();
}
// ── ON / OFF puck: a thick tilted disc ───────────────────────────────────────
export const PUCK = { w: 128, h: 76, rx: 56, ry: 24, t: 14 };
function bakePuck(scene, key, on) {
const { w, h, rx, ry, t } = PUCK;
const c = canvas(w, h);
const ctx = c.getContext('2d');
const cx = w / 2, yT = ry + 3, yB = yT + t;
// edge
ctx.beginPath();
ctx.moveTo(cx - rx, yT);
ctx.lineTo(cx - rx, yB);
ctx.ellipse(cx, yB, rx, ry, 0, Math.PI, 0, true);
ctx.lineTo(cx + rx, yT);
ctx.closePath();
const eg = ctx.createLinearGradient(cx - rx, 0, cx + rx, 0);
const edge = on ? ['#9a9a9a', '#f4f4f4', '#7a7a7a'] : ['#050505', '#3a3a3a', '#030303'];
eg.addColorStop(0, edge[0]); eg.addColorStop(0.35, edge[1]); eg.addColorStop(1, edge[2]);
ctx.fillStyle = eg;
ctx.fill();
// top
ctx.beginPath();
ctx.ellipse(cx, yT, rx, ry, 0, 0, Math.PI * 2);
const tg = ctx.createRadialGradient(cx - rx * 0.3, yT - ry * 0.4, 2, cx, yT, rx);
if (on) { tg.addColorStop(0, '#ffffff'); tg.addColorStop(1, '#d8d8d2'); } else { tg.addColorStop(0, '#2e2e2e'); tg.addColorStop(1, '#0a0a0a'); }
ctx.fillStyle = tg;
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = on ? '#1d6b2c' : '#7a7a7a';
ctx.beginPath();
ctx.ellipse(cx, yT, rx * 0.86, ry * 0.86, 0, 0, Math.PI * 2);
ctx.stroke();
ctx.save();
ctx.translate(cx, yT + 1);
ctx.scale(1, ry / rx * 1.25);
ctx.font = `bold 34px ${SANS}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = on ? '#1d6b2c' : '#f4ecd6';
ctx.fillText(on ? 'ON' : 'OFF', 0, 0);
ctx.restore();
scene.textures.addCanvas(key, c);
}

View File

@ -0,0 +1,334 @@
// Craps dice — true 3D cubes drawn live (Graphics) and a physics-lite throw.
//
// The roll's result is decided first by the game RNG. simulateThrow() then flies
// a canonical die (gravity, felt bounces, the pyramid wall, sliding friction,
// tumble), snaps it flat, and finally relabels the die (a fixed cube rotation
// applied in the die's own frame) so the face that ends up on top carries the
// rolled number. Outcomes stay fair; the animation just agrees with them.
//
// Phaser-free apart from the Graphics objects handed in by the scene, so the
// simulation can be verified under Node.
import { P, lift, WALL_U, LANDING, NEAR_VISIBLE_V, VIEW } from './CrapsTable.js';
// ── Tuning ───────────────────────────────────────────────────────────────────
export const DIE = { size: 30 }; // edge length, px at s = 1
const UX = VIEW.halfW; // px per u-unit at s = 1
const VY = VIEW.halfW * (4 / 3); // px per v-unit (the felt is 4 ft deep, half-length 3 ft)
const SIN_E = 0.7, COS_E = 0.71; // camera elevation used to draw the cubes
const G = 2600; // gravity, px/s²
const DT = 1 / 240;
const LIGHT = norm([-0.35, 0.45, 0.82]);
// Local face normals and the pips on them (opposite faces add to 7).
const FACES = [
{ n: [0, 0, 1], label: 1, e1: [1, 0, 0], e2: [0, 1, 0] },
{ n: [0, 0, -1], label: 6, e1: [1, 0, 0], e2: [0, -1, 0] },
{ n: [0, 1, 0], label: 2, e1: [1, 0, 0], e2: [0, 0, 1] },
{ n: [0, -1, 0], label: 5, e1: [-1, 0, 0], e2: [0, 0, 1] },
{ n: [1, 0, 0], label: 3, e1: [0, 1, 0], e2: [0, 0, 1] },
{ n: [-1, 0, 0], label: 4, e1: [0, -1, 0], e2: [0, 0, 1] },
];
const PIPS = {
1: [[0, 0]], 2: [[-1, -1], [1, 1]], 3: [[-1, -1], [0, 0], [1, 1]],
4: [[-1, -1], [1, -1], [-1, 1], [1, 1]], 5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]],
6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]],
};
// ── Vector / quaternion helpers ──────────────────────────────────────────────
function norm(v) { const l = Math.hypot(...v) || 1; return v.map(x => x / l); }
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
export function qmul(a, b) {
return [
a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2],
a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1],
a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0],
];
}
function qnorm(q) { const l = Math.hypot(...q) || 1; return q.map(x => x / l); }
export function qaxis(axis, ang) {
const a = norm(axis), s = Math.sin(ang / 2);
return [Math.cos(ang / 2), a[0] * s, a[1] * s, a[2] * s];
}
export function qrot(q, v) {
const [w, x, y, z] = q;
const ix = w * v[0] + y * v[2] - z * v[1];
const iy = w * v[1] + z * v[0] - x * v[2];
const iz = w * v[2] + x * v[1] - y * v[0];
const iw = -x * v[0] - y * v[1] - z * v[2];
return [
ix * w + iw * -x + iy * -z - iz * -y,
iy * w + iw * -y + iz * -x - ix * -z,
iz * w + iw * -z + ix * -y - iy * -x,
];
}
function qslerp(a, b, t) {
let d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
if (d < 0) { b = b.map(x => -x); d = -d; }
if (d > 0.9995) return qnorm(a.map((x, i) => x + (b[i] - x) * t));
const th = Math.acos(d), s = Math.sin(th);
const wa = Math.sin((1 - t) * th) / s, wb = Math.sin(t * th) / s;
return a.map((x, i) => x * wa + b[i] * wb);
}
function randomQ(rng) {
const u1 = rng(), u2 = rng(), u3 = rng();
return [
Math.sqrt(1 - u1) * Math.sin(2 * Math.PI * u2), Math.sqrt(1 - u1) * Math.cos(2 * Math.PI * u2),
Math.sqrt(u1) * Math.sin(2 * Math.PI * u3), Math.sqrt(u1) * Math.cos(2 * Math.PI * u3),
];
}
// Rotate q so the local axis nearest world-up points exactly up (keeps the yaw).
function snapFlat(q) {
let best = null;
for (const f of FACES) {
const w = qrot(q, f.n);
if (!best || w[2] > best.w[2]) best = { w, f };
}
const up = [0, 0, 1];
const ax = cross(best.w, up);
const l = Math.hypot(...ax);
if (l < 1e-9) return q;
return qnorm(qmul(qaxis(ax, Math.acos(Math.min(1, dot(best.w, up)))), q));
}
// The label on top for an orientation.
export function topFace(q) {
let best = null;
for (const f of FACES) {
const z = qrot(q, f.n)[2];
if (!best || z > best.z) best = { z, label: f.label };
}
return best.label;
}
// Cube rotation (die frame) that moves the face labelled `target` onto local axis `a`.
function relabel(target, a) {
const t = FACES.find(f => f.label === target).n;
const d = dot(t, a);
if (d > 0.999) return [1, 0, 0, 0];
if (d < -0.999) {
const perp = Math.abs(t[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
return qaxis(cross(t, perp), Math.PI);
}
return qaxis(cross(t, a), Math.PI / 2);
}
// ── Simulation ───────────────────────────────────────────────────────────────
// origin {u, v, h}; returns { frames: [{u, v, h, q}], u, v } at 120 fps.
function flyOne(origin, rng, aimV) {
const half = DIE.size / 2;
const wallX = WALL_U * UX - half;
const farY = 0.03 * VY + half, nearY = (NEAR_VISIBLE_V - 0.03) * VY - half; // the real near wall
let X = origin.u * UX, Y = origin.v * VY, Z = origin.h;
const TX = wallX, TY = aimV * VY;
const dist = Math.hypot(TX - X, TY - Y);
const tf = Math.max(0.35, (dist / 1500) * (0.85 + rng() * 0.3));
let vx = (TX - X) / tf, vy = (TY - Y) / tf;
const zArrive = 25 + rng() * 40;
let vz = (zArrive - Z + 0.5 * G * tf * tf) / tf;
let q = randomQ(rng);
let w = norm([rng() - 0.5, rng() - 0.5, rng() - 0.5]).map(x => x * (16 + rng() * 12));
const frames = [];
let t = 0, grounded = false, hitWall = false, step = 0;
const push = () => frames.push({ u: X / UX, v: Y / VY, h: Z, q });
push();
while (t < 3.4) {
// integrate
vz -= grounded ? 0 : G * DT;
X += vx * DT; Y += vy * DT; Z += vz * DT;
const wl = Math.hypot(...w);
if (wl > 1e-6) q = qnorm(qmul(qaxis(w, wl * DT), q));
// felt
if (Z <= 0 && !grounded) {
Z = 0;
if (hitWall && Math.abs(vz) < 140) { vz = 0; grounded = true; }
else if (!hitWall) {
// a short throw skips along the felt — it still has to reach the wall
vz = Math.max(260, -vz * 0.5);
vx *= 0.92; vy *= 0.92;
w = w.map(x => x * 0.7 + (rng() - 0.5) * 12);
} else {
vz = -vz * 0.36;
vx *= 0.7; vy *= 0.7;
w = w.map(x => x * 0.55 + (rng() - 0.5) * 14);
}
}
if (grounded) {
Z = 0;
const sp = Math.hypot(vx, vy);
const dec = Math.min(sp, 1700 * DT);
if (sp > 0) { vx -= (vx / sp) * dec; vy -= (vy / sp) * dec; }
w = w.map(x => x * 0.965);
}
// walls
if (X >= wallX) {
X = wallX; vx = -Math.abs(vx) * 0.28; vy += (rng() - 0.5) * 420; vz += 120 + rng() * 160;
grounded = false; hitWall = true;
w = w.map(x => x * 0.6 + (rng() - 0.5) * 22);
}
if (X <= (-0.97 * UX + half)) { X = -0.97 * UX + half; vx = Math.abs(vx) * 0.5; }
if (Y <= farY) { Y = farY; vy = Math.abs(vy) * 0.5; }
if (Y >= nearY) { Y = nearY; vy = -Math.abs(vy) * 0.5; }
t += DT;
if (++step % 2 === 0) push();
if (grounded && hitWall && Math.hypot(vx, vy) < 18 && Math.hypot(...w) < 4) break;
}
// settle flat over ~0.16 s with a little slide
const q0 = q, qf = snapFlat(q);
const n = 20;
for (let i = 1; i <= n; i++) {
const k = i / n, e = 1 - (1 - k) * (1 - k);
X += vx * DT * 2 * (1 - k); Y += vy * DT * 2 * (1 - k);
frames.push({ u: X / UX, v: Y / VY, h: Math.sin(k * Math.PI) * 2.5, q: qslerp(q0, qf, e) });
}
return { frames, u: X / UX, v: Y / VY, hitWall, q: qf };
}
// Plan a throw of both dice from `origin` landing on `faces` [a, b].
export function simulateThrow(origin, faces, rng = Math.random) {
const out = [];
let tries = 0;
for (let i = 0; i < 2; i++) {
let best = null;
for (let k = 0; k < 40; k++) {
tries++;
const aim = 0.16 + rng() * 0.36; // the upper part of the wall, so dice settle above the results card
const o = { u: origin.u, v: origin.v + (i ? 0.02 : -0.02), h: origin.h };
const fly = flyOne(o, rng, aim);
const inLanding = fly.u >= LANDING.u0 - 0.04 && fly.u <= LANDING.u1 && fly.v >= LANDING.v0 && fly.v <= LANDING.v1;
const sep = i ? Math.hypot((fly.u - out[0].u) * UX, (fly.v - out[0].v) * VY) : Infinity;
const okSep = sep >= DIE.size * 1.5;
const score = (inLanding ? 2 : 0) + (okSep ? 1 : 0) + (fly.hitWall ? 2 : 0);
if (!best || score > best.score) best = { ...fly, score };
if (score === 5) break;
}
// Relabel so the face that lands on top shows the rolled number.
const up = qrot([best.q[0], -best.q[1], -best.q[2], -best.q[3]], [0, 0, 1]).map(Math.round);
best.Q = relabel(faces[i], up);
best.frames = best.frames.map(f => ({ ...f, q: qmul(f.q, best.Q) }));
best.top = topFace(best.frames[best.frames.length - 1].q);
out.push(best);
}
// pad the shorter path so both finish together
const len = Math.max(out[0].frames.length, out[1].frames.length);
for (const d of out) while (d.frames.length < len) d.frames.push(d.frames[d.frames.length - 1]);
return { dice: out, duration: (len - 1) / 120, tries };
}
// A resting orientation showing `face` on top with a given yaw.
export function restingQ(face, yaw = 0) {
const base = relabel(face, [0, 0, 1]);
return qmul(qaxis([0, 0, 1], yaw), base);
}
// ── Rendering ────────────────────────────────────────────────────────────────
const BODY = [196, 28, 40];
function shadeHex(rgb, k) {
const c = rgb.map(x => Math.max(0, Math.min(255, Math.round(x * k))));
return (c[0] << 16) | (c[1] << 8) | c[2];
}
export class Die3D {
constructor(scene, depth) {
this.scene = scene;
this.shadow = scene.add.graphics().setDepth(depth - 0.5);
this.g = scene.add.graphics().setDepth(depth);
this.state = { u: 0, v: 0, h: 0, q: [1, 0, 0, 0] };
this.scale = 1;
this.glow = 0;
this.visible = true;
}
setVisible(v) { this.visible = v; this.g.setVisible(v); this.shadow.setVisible(v); return this; }
set(u, v, h, q) { Object.assign(this.state, { u, v, h, q }); this.draw(); return this; }
screenCenter() {
const { u, v, h } = this.state;
const p = P.project(u, v);
const half = DIE.size / 2;
return { x: p.x, y: p.y - (h + half) * COS_E * p.s * this.scale, s: p.s };
}
draw() {
const g = this.g, sh = this.shadow;
g.clear(); sh.clear();
if (!this.visible) return;
const { u, v, h, q } = this.state;
const p = lift(u, v, 0);
const s = p.s * this.scale;
const half = DIE.size / 2;
const hc = h + half;
const proj = (w) => ({ x: p.x + s * w[0], y: p.y + s * (w[1] * SIN_E - (hc + w[2]) * COS_E) });
// shadow on the felt
const fade = Math.max(0.12, 0.42 - h / 500);
sh.fillStyle(0x000000, fade);
sh.fillEllipse(p.x + 4 * s + h * 0.04, p.y + 3 * s, DIE.size * 1.25 * s, DIE.size * 0.75 * s);
if (this.glow > 0) {
g.lineStyle(3, 0xf5d020, this.glow);
g.strokeEllipse(p.x, p.y + 2 * s, DIE.size * 1.7 * s, DIE.size * 1.0 * s);
}
const cam = [0, SIN_E, COS_E];
for (const f of FACES) {
const n = qrot(q, f.n);
const facing = dot(n, cam);
if (facing <= 0.02) continue;
const e1 = qrot(q, f.e1), e2 = qrot(q, f.e2);
const c = n.map(x => x * half);
const corner = (a, b) => proj([
c[0] + (e1[0] * a + e2[0] * b) * half,
c[1] + (e1[1] * a + e2[1] * b) * half,
c[2] + (e1[2] * a + e2[2] * b) * half,
]);
// slightly chamfered square
const k = 0.82;
const pts = [
corner(-k, -1), corner(k, -1), corner(1, -k), corner(1, k),
corner(k, 1), corner(-k, 1), corner(-1, k), corner(-1, -k),
];
const lit = 0.5 + 0.55 * Math.max(0, dot(n, LIGHT));
g.fillStyle(shadeHex(BODY, lit), 0.97);
g.fillPoints(pts, true);
g.lineStyle(1, shadeHex(BODY, lit * 0.55), 0.9);
g.strokePoints(pts, true);
// gloss on the top-lit face
if (n[2] > 0.6) {
g.fillStyle(0xffffff, 0.08 + 0.1 * n[2]);
g.fillPoints([corner(-0.75, 0.2), corner(-0.2, 0.75), corner(-0.75, 0.75)], true);
}
// pips
const pipA = Math.min(1, facing * 2.4);
g.fillStyle(0xfdf6e6, 0.95 * pipA);
for (const [a, b] of PIPS[f.label]) {
const ring = [];
for (let i = 0; i < 8; i++) {
const t = (i / 8) * Math.PI * 2;
ring.push(corner(a * 0.52 + Math.cos(t) * 0.17, b * 0.52 + Math.sin(t) * 0.17));
}
g.fillPoints(ring, true);
}
}
}
destroy() { this.g.destroy(); this.shadow.destroy(); }
}
// Play a planned throw on two Die3D objects. `progress` 0…1 drives the frames.
export function poseFromPlan(plan, i, progress) {
const fr = plan.dice[i].frames;
const f = Math.min(fr.length - 1, Math.max(0, progress * (fr.length - 1)));
const a = fr[Math.floor(f)], b = fr[Math.ceil(f)];
const t = f - Math.floor(f);
return {
u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t, h: a.h + (b.h - a.h) * t,
q: t < 0.5 ? a.q : b.q,
};
}

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,64 @@
// Pure Craps rules. No Phaser dependency.
// Pure Craps rules. No Phaser dependency (verify scripts import this under Node).
//
// Scope: Pass Line, Don't Pass (bar 12), Field, Place (4·5·6·8·9·10),
// Come / Don't Come, and free Odds behind Pass/Don't and Come/Don't Come.
// Bets:
// Line Pass / Don't Pass (bar 12), Come / Don't Come, with free odds
// behind them (3-4-5× on the right side, 6× flat-equivalent laid)
// Numbers Place (4·5·6·8·9·10), Buy (true odds, 5% vig on wins),
// Lay (true odds against, 5% of the win), Big 6 / Big 8
// Hardways Hard 4·6·8·10 (off on the come-out unless called on)
// One-roll Field (2 double, 12 triple), Any 7, Any Craps, Yo-11, Aces,
// Ace-Deuce, Boxcars, C&E, Horn
//
// A "round" is one shooter sequence. The shooter rolls a come-out; if a point
// is set the game enters the point phase and the shooter keeps rolling until
// the point repeats (pass wins) or a 7 shows (seven-out → shooter rotates).
// A "round" is one shooter sequence: a come-out roll, then (if a point is set)
// rolls until the point repeats (pass wins) or a 7 shows (seven-out → the dice
// move to the next player).
//
// State is treated as immutable: every mutating helper returns a fresh object.
export const POINT_NUMBERS = [4, 5, 6, 8, 9, 10];
export const HARD_NUMBERS = [4, 6, 8, 10];
// Bet types and where they live on the layout.
export const BET = {
PASS: 'pass',
DONT_PASS: 'dontpass',
FIELD: 'field',
PLACE: 'place',
COME: 'come',
DONT_COME: 'dontcome',
FIELD: 'field',
PLACE: 'place',
BUY: 'buy',
LAY: 'lay',
BIG: 'big', // number 6 or 8
HARD: 'hard', // number 4, 6, 8 or 10
ANY7: 'any7',
ANY_CRAPS: 'anycraps',
YO: 'yo',
ACES: 'aces',
ACE_DEUCE: 'acedeuce',
BOXCARS: 'boxcars',
CE: 'ce',
HORN: 'horn',
};
// Bets that carry a number (and which numbers are valid).
export const NUMBERED = {
[BET.PLACE]: POINT_NUMBERS,
[BET.BUY]: POINT_NUMBERS,
[BET.LAY]: POINT_NUMBERS,
[BET.BIG]: [6, 8],
[BET.HARD]: HARD_NUMBERS,
};
export const ONE_ROLL = new Set([
BET.FIELD, BET.ANY7, BET.ANY_CRAPS, BET.YO, BET.ACES, BET.ACE_DEUCE, BET.BOXCARS, BET.CE, BET.HORN,
]);
// Bets that are "off" on the come-out roll unless the player calls them on.
const OFF_ON_COMEOUT = new Set([BET.PLACE, BET.BUY, BET.HARD]);
// Chip denominations offered in the UI.
export const CHIP_AMOUNTS = [5, 25, 50, 100];
export const CHIP_AMOUNTS = [1, 5, 25, 50, 100];
export const VIG = 0.05;
// ─── Setup ───────────────────────────────────────────────────────────────────
@ -41,10 +77,11 @@ export function createInitialState(opponents = [], humanChips = 2000, humanName
return {
players,
shooterIndex: 0,
phase: 'betting', // betting → comeout → point → (betting | gameover)
phase: 'comeout', // comeout | point | gameover
point: null,
dice: [1, 1],
rollCount: 0,
shooterRolls: 0, // rolls by the current shooter (resets on seven-out)
_nextBetId: 1,
};
}
@ -53,89 +90,184 @@ export function cloneState(state) {
return JSON.parse(JSON.stringify(state));
}
// ─── Bet placement ─────────────────────────────────────────────────────────--
// ─── Queries ─────────────────────────────────────────────────────────────────
// Which base bet types may be opened right now.
// Which bet types may be opened right now.
export function legalBetTypes(state) {
const out = new Set([BET.FIELD, BET.PLACE]);
const out = new Set(Object.values(BET));
if (state.point === null) {
out.add(BET.PASS);
out.add(BET.DONT_PASS);
out.delete(BET.COME);
out.delete(BET.DONT_COME);
} else {
out.add(BET.COME);
out.add(BET.DONT_COME);
out.delete(BET.PASS);
out.delete(BET.DONT_PASS);
}
return out;
}
export function isLegalBet(state, type, number = null) {
if (!legalBetTypes(state).has(type)) return false;
if (NUMBERED[type]) return NUMBERED[type].includes(number);
return number == null;
}
// The number a line/come bet's odds are tied to (null until established).
export function oddsNumber(bet, state) {
if (bet.type === BET.PASS || bet.type === BET.DONT_PASS) return state.point;
if (bet.type === BET.COME || bet.type === BET.DONT_COME) return bet.comePoint ?? null;
return null;
}
// A line/come bet that can still receive odds (point/come-point established).
export function oddsEligibleBets(player, state) {
return player.bets.filter((b) => {
if (b.type === BET.PASS || b.type === BET.DONT_PASS) return state.point !== null;
if (b.type === BET.COME || b.type === BET.DONT_COME) return b.comePoint != null;
return false;
});
return player.bets.filter((b) => oddsNumber(b, state) != null);
}
export function maxOddsFor(bet) {
// Keep it simple: allow up to 3× the flat bet behind the line.
return bet.amount * 3;
// 3-4-5× odds behind the line; laid odds capped so the win is at most 6× the flat.
export function oddsMultiple(number) {
if (number === 4 || number === 10) return 3;
if (number === 5 || number === 9) return 4;
if (number === 6 || number === 8) return 5;
return 0;
}
// Place a flat bet. Stake is removed from the player's bankroll immediately.
export function maxOddsFor(bet, state) {
const n = oddsNumber(bet, state);
if (n == null) return 0;
const dont = bet.type === BET.DONT_PASS || bet.type === BET.DONT_COME;
return dont ? bet.amount * 6 : bet.amount * oddsMultiple(n);
}
// Is this bet live for the next roll?
export function isWorking(bet, state) {
if (state.point === null && OFF_ON_COMEOUT.has(bet.type)) return !!bet.onComeOut;
return true;
}
// Contract bets may not be taken down: Pass once a point is set, and a Come bet
// once it has travelled to its number.
export function isContract(bet, state) {
if (bet.type === BET.PASS) return state.point !== null;
if (bet.type === BET.COME) return bet.comePoint != null;
return false;
}
export function canToggleWorking(bet, state) {
return state.point === null && OFF_ON_COMEOUT.has(bet.type);
}
// ─── Bet placement ───────────────────────────────────────────────────────────
function findMatch(bets, type, number) {
return bets.find((b) => b.type === type && (b.number ?? null) === (number ?? null) && b.comePoint == null);
}
// Place (or add to) a flat bet. The stake leaves the bankroll immediately.
// Returns the same state object when the placement is rejected.
export function placeBet(state, playerIndex, { type, number = null, amount }) {
const player = state.players[playerIndex];
if (amount <= 0 || amount > player.chips) return state;
if (!legalBetTypes(state).has(type)) return state;
if (type === BET.PLACE && !POINT_NUMBERS.includes(number)) return state;
amount = Math.floor(amount);
if (!(amount > 0) || amount > player.chips) return state;
if (!NUMBERED[type]) number = null;
if (!isLegalBet(state, type, number)) return state;
const s = cloneState(state);
const p = s.players[playerIndex];
// Stack onto an existing matching flat bet rather than duplicating it.
const existing = p.bets.find((b) =>
b.type === type &&
(type === BET.PLACE ? b.number === number : b.comePoint == null && b.number == null));
if (existing && type !== BET.COME && type !== BET.DONT_COME) {
const existing = findMatch(p.bets, type, number);
if (existing) {
existing.amount += amount;
} else {
p.bets.push({
id: s._nextBetId++,
type,
number: type === BET.PLACE ? number : null,
number,
comePoint: null,
amount,
oddsAmount: 0,
// Place bets sit "off" during a come-out; everything else is working.
working: type === BET.PLACE ? state.point !== null : true,
onComeOut: false,
});
}
p.chips -= amount;
return s;
}
// Add odds behind an eligible line/come bet.
// Add odds behind an eligible line/come bet (clamped to the cap and bankroll).
export function addOdds(state, playerIndex, betId, amount) {
const bet = state.players[playerIndex].bets.find((b) => b.id === betId);
if (!bet) return state;
const cap = maxOddsFor(bet, state) - bet.oddsAmount;
const add = Math.min(Math.floor(amount), cap, state.players[playerIndex].chips);
if (add <= 0) return state;
const s = cloneState(state);
const p = s.players[playerIndex];
const bet = p.bets.find((b) => b.id === betId);
if (!bet) return state;
const cap = maxOddsFor(bet) - bet.oddsAmount;
const add = Math.min(amount, cap, p.chips);
if (add <= 0) return state;
bet.oddsAmount += add;
const b = p.bets.find((x) => x.id === betId);
b.oddsAmount += add;
p.chips -= add;
return s;
}
// Return un-resolved stakes to the bankroll (only sensible during a betting
// window). Used by "Clear" and when leaving the table.
export function refundBets(state, playerIndex, predicate = () => true) {
// Odds that would be added by "max odds" for this bet.
export function oddsRoom(state, playerIndex, betId) {
const p = state.players[playerIndex];
const bet = p.bets.find((b) => b.id === betId);
if (!bet) return 0;
return Math.max(0, Math.min(maxOddsFor(bet, state) - bet.oddsAmount, p.chips));
}
// Take `amount` (default: all) off a bet's flat stake or odds. Contract flats
// can't come down. Removing the whole flat also returns its odds.
export function reduceBet(state, playerIndex, betId, { part = 'flat', amount = Infinity } = {}) {
const bet = state.players[playerIndex].bets.find((b) => b.id === betId);
if (!bet) return state;
if (part === 'odds') {
const take = Math.min(bet.oddsAmount, Math.floor(amount));
if (take <= 0) return state;
const s = cloneState(state);
const p = s.players[playerIndex];
p.bets.find((b) => b.id === betId).oddsAmount -= take;
p.chips += take;
return s;
}
if (isContract(bet, state)) return state;
const take = Math.min(bet.amount, Math.floor(amount));
if (take <= 0) return state;
const s = cloneState(state);
const p = s.players[playerIndex];
const b = p.bets.find((x) => x.id === betId);
if (take >= b.amount) {
p.chips += b.amount + b.oddsAmount;
p.bets = p.bets.filter((x) => x.id !== betId);
} else {
b.amount -= take;
p.chips += take;
const excess = b.oddsAmount - maxOddsFor(b, s);
if (excess > 0) { b.oddsAmount -= excess; p.chips += excess; }
}
return s;
}
export function removeBet(state, playerIndex, betId) {
return reduceBet(state, playerIndex, betId, { part: 'flat' });
}
// Call a Place / Buy / Hardway bet on (or off) for the come-out roll.
export function setWorking(state, playerIndex, betId, on) {
const bet = state.players[playerIndex].bets.find((b) => b.id === betId);
if (!bet || !canToggleWorking(bet, state)) return state;
const s = cloneState(state);
s.players[playerIndex].bets.find((b) => b.id === betId).onComeOut = !!on;
return s;
}
// Return every removable stake to the bankroll (Clear, and leaving the table).
// Contract bets stay unless `force` (leaving refunds everything, since only
// resolved deltas are ever posted to the server).
export function refundBets(state, playerIndex, { force = false, predicate = () => true } = {}) {
const s = cloneState(state);
const p = s.players[playerIndex];
const kept = [];
for (const b of p.bets) {
if (predicate(b)) p.chips += b.amount + b.oddsAmount;
if (predicate(b) && (force || !isContract(b, state))) p.chips += b.amount + b.oddsAmount;
else kept.push(b);
}
p.bets = kept;
@ -144,9 +276,9 @@ export function refundBets(state, playerIndex, predicate = () => true) {
// ─── Dice ────────────────────────────────────────────────────────────────────
export function rollDice(state) {
export function rollDice(state, rng = Math.random) {
const s = cloneState(state);
s.dice = [1 + Math.floor(Math.random() * 6), 1 + Math.floor(Math.random() * 6)];
s.dice = [1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)];
s.rollCount += 1;
return s;
}
@ -158,50 +290,96 @@ export function setDice(state, dice) {
return s;
}
// ─── Payout tables (return winnings only, not the returned stake) ─────────────
// ─── Payout tables (winnings only, not the returned stake) ───────────────────
function floor(n) { return Math.floor(n); }
const floor = Math.floor;
function passOddsWin(amount, number) {
if (number === 4 || number === 10) return amount * 2; // 2:1
if (number === 5 || number === 9) return floor(amount * 3 / 2); // 3:2
if (number === 6 || number === 8) return floor(amount * 6 / 5); // 6:5
// True odds for the right side (point → pays X to Y).
export function trueOddsWin(amount, number) {
if (number === 4 || number === 10) return amount * 2; // 2:1
if (number === 5 || number === 9) return floor((amount * 3) / 2); // 3:2
if (number === 6 || number === 8) return floor((amount * 6) / 5); // 6:5
return 0;
}
function dontOddsWin(amount, number) {
if (number === 4 || number === 10) return floor(amount / 2); // 1:2
if (number === 5 || number === 9) return floor(amount * 2 / 3); // 2:3
if (number === 6 || number === 8) return floor(amount * 5 / 6); // 5:6
// True odds laid against a number.
export function layOddsWin(amount, number) {
if (number === 4 || number === 10) return floor(amount / 2); // 1:2
if (number === 5 || number === 9) return floor((amount * 2) / 3); // 2:3
if (number === 6 || number === 8) return floor((amount * 5) / 6); // 5:6
return 0;
}
function placeWin(amount, number) {
if (number === 4 || number === 10) return floor(amount * 9 / 5);
if (number === 5 || number === 9) return floor(amount * 7 / 5);
if (number === 6 || number === 8) return floor(amount * 7 / 6);
export function placeWin(amount, number) {
if (number === 4 || number === 10) return floor((amount * 9) / 5);
if (number === 5 || number === 9) return floor((amount * 7) / 5);
if (number === 6 || number === 8) return floor((amount * 7) / 6);
return 0;
}
function fieldWin(amount, total) {
if (total === 2) return amount * 2; // 2 pays double
if (total === 12) return amount * 3; // 12 pays triple
return amount; // 3,4,9,10,11 pay 1:1
export function vig(amount) {
return Math.max(1, floor(amount * VIG));
}
// ─── Resolution ────────────────────────────────────────────────────────────--
// Payout ratios shown on the layout / tooltips.
export const PAYS = {
[BET.PASS]: '1 to 1', [BET.DONT_PASS]: '1 to 1', [BET.COME]: '1 to 1', [BET.DONT_COME]: '1 to 1',
[BET.FIELD]: '1 to 1 · 2 pays 2× · 12 pays 3×',
[BET.BIG]: '1 to 1',
[BET.ANY7]: '4 to 1', [BET.ANY_CRAPS]: '7 to 1', [BET.YO]: '15 to 1',
[BET.ACES]: '30 to 1', [BET.ACE_DEUCE]: '15 to 1', [BET.BOXCARS]: '30 to 1',
[BET.CE]: 'Craps 3 to 1 · 11 pays 7 to 1', [BET.HORN]: '2/12 pay 27 to 4 · 3/11 pay 3 to 1',
};
export function paysLabel(type, number) {
if (type === BET.PLACE) return number === 6 || number === 8 ? '7 to 6' : number === 5 || number === 9 ? '7 to 5' : '9 to 5';
if (type === BET.BUY) return `${number === 6 || number === 8 ? '6 to 5' : number === 5 || number === 9 ? '3 to 2' : '2 to 1'} · 5% vig on wins`;
if (type === BET.LAY) return `${number === 6 || number === 8 ? '5 to 6' : number === 5 || number === 9 ? '2 to 3' : '1 to 2'} · 5% vig on wins`;
if (type === BET.HARD) return number === 4 || number === 10 ? '7 to 1' : '9 to 1';
return PAYS[type] ?? '';
}
// House edge (per bet, as a %) for tooltips — verified exactly in tools/verifyCraps.js.
export function houseEdge(type, number) {
switch (type) {
case BET.PASS: case BET.COME: return 1.41;
case BET.DONT_PASS: case BET.DONT_COME: return 1.4; // per decision (a barred 12 is no action)
case BET.FIELD: return 2.78;
case BET.PLACE: return number === 6 || number === 8 ? 1.52 : number === 5 || number === 9 ? 4.0 : 6.67;
// Buy / Lay quoted at their natural sizes ($20 buys, lays that win $20).
case BET.BUY: return number === 6 || number === 8 ? 2.27 : number === 5 || number === 9 ? 2.0 : 1.67;
case BET.LAY: return number === 6 || number === 8 ? 1.82 : number === 5 || number === 9 ? 2.0 : 1.67;
case BET.BIG: return 9.09;
case BET.HARD: return number === 6 || number === 8 ? 9.09 : 11.11;
case BET.ANY7: return 16.67;
case BET.ANY_CRAPS: case BET.YO: case BET.ACE_DEUCE: case BET.CE: return 11.11;
case BET.ACES: case BET.BOXCARS: return 13.89;
case BET.HORN: return 12.5;
default: return null;
}
}
// ─── Resolution ──────────────────────────────────────────────────────────────
// Resolve every bet against the dice already set on `state`.
// Returns { state, total, payouts, pointEstablished, pointMade, sevenOut, newComeOut }.
// Returns { state, total, hard, payouts, moves, pointEstablished, pointMade, sevenOut, newComeOut }.
//
// payouts entry: { playerIndex, betType, number, result, amount, delta }
// result ∈ 'win' | 'lose' | 'push'; delta is the net bankroll change for the bet.
// payouts entry: { playerIndex, betId, betType, number, result, amount, winnings,
// commission, refund, kept, delta }
// result ∈ 'win' | 'lose' | 'push'; amount = stake at risk; delta = net bankroll change.
// kept = the bet stays on the felt after a win (Place, Buy, Lay, Big, Hard).
// moves entry: { playerIndex, betId, type, to } — a Come / Don't Come bet
// travelling to its number.
export function resolveRoll(state) {
const s = cloneState(state);
const total = s.dice[0] + s.dice[1];
const [d1, d2] = s.dice;
const total = d1 + d2;
const hard = d1 === d2;
const point = s.point;
const isComeOut = point === null;
const payouts = [];
const moves = [];
const ctx = { total, hard, point, isComeOut, state };
let pointEstablished = null;
let pointMade = false;
@ -212,30 +390,42 @@ export function resolveRoll(state) {
const kept = [];
for (const bet of p.bets) {
const resolved = resolveBet(bet, { total, point, isComeOut });
if (resolved.result === 'open') {
// Bet survives (possibly mutated, e.g. a come bet that travelled).
kept.push(resolved.bet ?? bet);
const r = resolveBet(bet, ctx);
if (r.result === 'open') {
const nb = r.bet ?? bet;
// A Come / Don't Come bet travelling to its number. (An older come bet on
// that number always resolves on this same roll — "off and on" — and
// placeBet keeps one unmoved come bet per player, so no twins can exist.)
if (nb.comePoint != null && bet.comePoint == null) {
moves.push({ playerIndex: pi, betId: bet.id, type: bet.type, to: nb.comePoint });
}
kept.push(nb);
continue;
}
// Credit returned stake + winnings; delta is net of the staked amount.
const stake = bet.amount + bet.oddsAmount;
const winnings = r.winnings ?? 0;
const commission = r.commission ?? 0;
let credited = 0;
if (resolved.result === 'win') credited = stake + resolved.winnings;
else if (resolved.result === 'push') credited = stake;
if (r.result === 'win') credited = (r.keep ? 0 : stake) + winnings - commission;
else if (r.result === 'push') credited = stake;
else credited = r.refund ?? 0;
p.chips += credited;
const delta = credited - stake;
const delta = r.keep ? winnings - commission : credited - stake;
p.lastDelta += delta;
payouts.push({
playerIndex: pi,
betId: bet.id,
betType: bet.type,
number: bet.number ?? bet.comePoint ?? null,
result: resolved.result,
result: r.result,
amount: stake,
winnings,
commission,
refund: r.result === 'lose' ? (r.refund ?? 0) : 0,
kept: !!r.keep,
delta,
});
// A winning Place bet stays up and working; everything else clears.
if (resolved.keep) kept.push(resolved.bet ?? bet);
if (r.keep) kept.push(bet);
}
p.bets = kept;
}
@ -246,10 +436,6 @@ export function resolveRoll(state) {
pointEstablished = total;
s.point = total;
s.phase = 'point';
// Place bets switch on once a point exists.
for (const p of s.players) for (const b of p.bets) {
if (b.type === BET.PLACE) b.working = true;
}
} else {
s.phase = 'comeout';
}
@ -257,36 +443,38 @@ export function resolveRoll(state) {
pointMade = true;
s.point = null;
s.phase = 'comeout';
for (const p of s.players) for (const b of p.bets) {
if (b.type === BET.PLACE) b.working = false;
}
} else if (total === 7) {
sevenOut = true;
s.point = null;
s.phase = 'comeout';
for (const p of s.players) for (const b of p.bets) {
if (b.type === BET.PLACE) b.working = false;
}
}
// Called-on flags only last for a come-out.
if (s.point !== null) for (const p of s.players) for (const b of p.bets) b.onComeOut = false;
s.shooterRolls += 1;
const newComeOut = pointMade || sevenOut;
if (sevenOut) {
s.shooterIndex = (s.shooterIndex + 1) % s.players.length;
s.shooterRolls = 0;
}
return { state: s, total, payouts, pointEstablished, pointMade, sevenOut, newComeOut };
return { state: s, total, hard, payouts, moves, pointEstablished, pointMade, sevenOut, newComeOut };
}
// Resolve a single bet. Returns one of:
// { result:'open', bet } — unresolved (bet may have mutated)
// { result:'win', winnings, keep } — paid; keep=true leaves it on the felt
// { result:'lose' } | { result:'push' }
function resolveBet(bet, { total, point, isComeOut }) {
// { result:'open', bet? } unresolved (bet may have mutated)
// { result:'win', winnings, commission?, keep? } paid; keep → stays on the felt
// { result:'lose', refund? } refund = odds that were off
// { result:'push' }
function resolveBet(bet, { total, hard, point, isComeOut, state }) {
const n = bet.number;
if (!isWorking(bet, state)) return { result: 'open' };
switch (bet.type) {
case BET.FIELD: {
if ([2, 3, 4, 9, 10, 11, 12].includes(total)) {
return { result: 'win', winnings: fieldWin(bet.amount, total) };
}
if (total === 2) return { result: 'win', winnings: bet.amount * 2 };
if (total === 12) return { result: 'win', winnings: bet.amount * 3 };
if ([3, 4, 9, 10, 11].includes(total)) return { result: 'win', winnings: bet.amount };
return { result: 'lose' };
}
@ -294,12 +482,9 @@ function resolveBet(bet, { total, point, isComeOut }) {
if (isComeOut) {
if (total === 7 || total === 11) return { result: 'win', winnings: bet.amount };
if (total === 2 || total === 3 || total === 12) return { result: 'lose' };
return { result: 'open' }; // point established, ride it
}
if (total === point) {
const winnings = bet.amount + passOddsWin(bet.oddsAmount, point);
return { result: 'win', winnings };
return { result: 'open' };
}
if (total === point) return { result: 'win', winnings: bet.amount + trueOddsWin(bet.oddsAmount, point) };
if (total === 7) return { result: 'lose' };
return { result: 'open' };
}
@ -307,56 +492,98 @@ function resolveBet(bet, { total, point, isComeOut }) {
case BET.DONT_PASS: {
if (isComeOut) {
if (total === 2 || total === 3) return { result: 'win', winnings: bet.amount };
if (total === 12) return { result: 'push' }; // bar 12
if (total === 12) return { result: 'open' }; // barred: no action, the bet stands
if (total === 7 || total === 11) return { result: 'lose' };
return { result: 'open' };
}
if (total === 7) {
const winnings = bet.amount + dontOddsWin(bet.oddsAmount, point);
return { result: 'win', winnings };
}
if (total === 7) return { result: 'win', winnings: bet.amount + layOddsWin(bet.oddsAmount, point) };
if (total === point) return { result: 'lose' };
return { result: 'open' };
}
case BET.PLACE: {
if (!bet.working) return { result: 'open' };
if (total === bet.number) {
return { result: 'win', winnings: placeWin(bet.amount, bet.number), keep: true };
}
if (total === 7) return { result: 'lose' };
return { result: 'open' };
}
case BET.COME:
case BET.DONT_COME: {
const isDont = bet.type === BET.DONT_COME;
const dont = bet.type === BET.DONT_COME;
if (bet.comePoint == null) {
// This roll is the come bet's own come-out.
if (total === 7 || total === 11) return isDont ? { result: 'lose' } : { result: 'win', winnings: bet.amount };
if (total === 2 || total === 3) return isDont ? { result: 'win', winnings: bet.amount } : { result: 'lose' };
if (total === 12) return isDont ? { result: 'push' } : { result: 'lose' };
// Travels to its number.
if (total === 7 || total === 11) return dont ? { result: 'lose' } : { result: 'win', winnings: bet.amount };
if (total === 2 || total === 3) return dont ? { result: 'win', winnings: bet.amount } : { result: 'lose' };
if (total === 12) return dont ? { result: 'open' } : { result: 'lose' }; // barred 12 stands
return { result: 'open', bet: { ...bet, comePoint: total } };
}
// Come point established.
if (total === bet.comePoint) {
if (isDont) return { result: 'lose' };
return { result: 'win', winnings: bet.amount + passOddsWin(bet.oddsAmount, bet.comePoint) };
}
if (total === 7) {
if (isDont) return { result: 'win', winnings: bet.amount + dontOddsWin(bet.oddsAmount, bet.comePoint) };
return { result: 'lose' };
const cp = bet.comePoint;
if (!dont) {
// Come odds are off on the come-out roll: returned, not paid or lost.
const oddsOn = !isComeOut;
if (total === cp) {
return { result: 'win', winnings: bet.amount + (oddsOn ? trueOddsWin(bet.oddsAmount, cp) : 0) };
}
if (total === 7) return { result: 'lose', refund: oddsOn ? 0 : bet.oddsAmount };
return { result: 'open' };
}
if (total === 7) return { result: 'win', winnings: bet.amount + layOddsWin(bet.oddsAmount, cp) };
if (total === cp) return { result: 'lose' };
return { result: 'open' };
}
case BET.PLACE: {
if (total === n) return { result: 'win', winnings: placeWin(bet.amount, n), keep: true };
if (total === 7) return { result: 'lose' };
return { result: 'open' };
}
case BET.BUY: {
if (total === n) return { result: 'win', winnings: trueOddsWin(bet.amount, n), commission: vig(bet.amount), keep: true };
if (total === 7) return { result: 'lose' };
return { result: 'open' };
}
case BET.LAY: {
if (total === 7) {
const w = layOddsWin(bet.amount, n);
return { result: 'win', winnings: w, commission: Math.min(w, vig(w)), keep: true };
}
if (total === n) return { result: 'lose' };
return { result: 'open' };
}
case BET.BIG: {
if (total === n) return { result: 'win', winnings: bet.amount, keep: true };
if (total === 7) return { result: 'lose' };
return { result: 'open' };
}
case BET.HARD: {
if (total === n && hard) {
return { result: 'win', winnings: bet.amount * (n === 4 || n === 10 ? 7 : 9), keep: true };
}
if (total === 7 || total === n) return { result: 'lose' };
return { result: 'open' };
}
case BET.ANY7: return total === 7 ? { result: 'win', winnings: bet.amount * 4 } : { result: 'lose' };
case BET.ANY_CRAPS:
return [2, 3, 12].includes(total) ? { result: 'win', winnings: bet.amount * 7 } : { result: 'lose' };
case BET.YO: return total === 11 ? { result: 'win', winnings: bet.amount * 15 } : { result: 'lose' };
case BET.ACES: return total === 2 ? { result: 'win', winnings: bet.amount * 30 } : { result: 'lose' };
case BET.ACE_DEUCE: return total === 3 ? { result: 'win', winnings: bet.amount * 15 } : { result: 'lose' };
case BET.BOXCARS: return total === 12 ? { result: 'win', winnings: bet.amount * 30 } : { result: 'lose' };
case BET.CE: {
if ([2, 3, 12].includes(total)) return { result: 'win', winnings: bet.amount * 3 };
if (total === 11) return { result: 'win', winnings: bet.amount * 7 };
return { result: 'lose' };
}
case BET.HORN: {
if (total === 2 || total === 12) return { result: 'win', winnings: floor((bet.amount * 27) / 4) };
if (total === 3 || total === 11) return { result: 'win', winnings: bet.amount * 3 };
return { result: 'lose' };
}
default:
return { result: 'open' };
}
}
// ─── Round / table helpers ─────────────────────────────────────────────────--
// ─── Round / table helpers ───────────────────────────────────────────────────
export function clearLastDeltas(state) {
const s = cloneState(state);
@ -374,7 +601,120 @@ export function hasActiveBets(player) {
// Human net result vs. the chips they walked in with, for match history.
export function getNetResult(player, startingChips) {
if (player.chips > startingChips) return 'win';
if (player.chips < startingChips) return 'loss';
const equity = player.chips + totalAtRisk(player);
if (equity > startingChips) return 'win';
if (equity < startingChips) return 'loss';
return 'draw';
}
// Stickman's call for a roll (flavour text).
export function stickCall(res, prevPoint) {
const { total, hard } = res;
const easyHard = POINT_NUMBERS.includes(total) && total !== 5 && total !== 9
? (hard ? `Hard ${total}!` : `Easy ${total}`) : null;
if (res.sevenOut) return 'Seven out — line away, pay the don\'ts!';
if (res.pointMade) return `${hard && HARD_NUMBERS.includes(total) ? `Hard ${total}` : total}, winner! Pay the line`;
if (res.pointEstablished) {
const base = total === 6 ? 'Six' : total === 8 ? 'Eight' : total === 9 ? 'Nine' : total === 10 ? 'Ten' : total === 4 ? 'Four' : 'Five';
return `${easyHard ?? base} — the point is ${total}, mark it!`;
}
if (prevPoint === null) {
if (total === 7) return 'Seven, winner on the pass line!';
if (total === 11) return 'Yo-leven! Front line winner!';
if (total === 2) return 'Aces — craps! Line away';
if (total === 3) return 'Ace-deuce, craps three';
if (total === 12) return 'Boxcars! Craps — bar the don\'ts';
}
if (total === 11) return 'Yo-leven!';
if (total === 2) return 'Aces, snake eyes!';
if (total === 3) return 'Three craps three';
if (total === 12) return 'Midnight — boxcars!';
if (easyHard) return easyHard;
if (total === 5) return 'Five, no field five';
if (total === 9) return 'Nine, centre field';
return `${total}`;
}
// ─── Plain-English results ───────────────────────────────────────────────────
const PROP_NAME = {
[BET.FIELD]: 'Field', [BET.ANY7]: 'Any Seven', [BET.ANY_CRAPS]: 'Any Craps', [BET.YO]: 'Yo-Eleven',
[BET.ACES]: 'Aces', [BET.ACE_DEUCE]: 'Ace-Deuce', [BET.BOXCARS]: 'Boxcars', [BET.CE]: 'C & E', [BET.HORN]: 'Horn',
};
// Display name for a resolved bet (payout entry) or a live bet.
export function betLabel(type, number = null, comePoint = null) {
switch (type) {
case BET.PASS: return 'Pass Line';
case BET.DONT_PASS: return "Don't Pass";
case BET.COME: return comePoint ?? number ? `Come on ${comePoint ?? number}` : 'Come';
case BET.DONT_COME: return comePoint ?? number ? `Don't Come on ${comePoint ?? number}` : "Don't Come";
case BET.PLACE: return `Place ${number}`;
case BET.BUY: return `Buy ${number}`;
case BET.LAY: return `Lay ${number}`;
case BET.BIG: return `Big ${number}`;
case BET.HARD: return `Hard ${number}`;
default: return PROP_NAME[type] ?? type;
}
}
// Why a bet won or lost on this roll. `ctx` = { dice: [a, b], prevPoint, unmoved }
// where unmoved = it was a Come / Don't Come bet still in its own come-out.
export function explainPayout(p, { dice, prevPoint, unmoved = false }) {
const t = dice[0] + dice[1];
const n = p.number;
const win = p.result === 'win';
const sevenOut = prevPoint !== null && t === 7;
const seven = sevenOut ? 'Seven-out' : 'A 7 rolled';
let why;
if (p.result === 'push') why = 'Push — stake returned';
else switch (p.betType) {
case BET.FIELD:
why = !win ? `${t} isn't a Field number` : t === 2 ? '2 in the Field pays double' : t === 12 ? '12 in the Field pays triple' : `${t} is a Field number`;
break;
case BET.PASS:
if (prevPoint === null) why = win ? `Natural ${t} on the come-out` : `Craps ${t} on the come-out`;
else why = win ? `Point ${prevPoint} made` : 'Seven-out before the point';
break;
case BET.DONT_PASS:
if (prevPoint === null) why = win ? `Craps ${t} — the Don't wins` : `Natural ${t} beats the Don't`;
else why = win ? 'Seven-out — the Don\'t wins' : `Point ${prevPoint} made`;
break;
case BET.COME:
if (unmoved) why = win ? `Natural ${t} on the Come` : `Craps ${t} on the Come`;
else why = win ? `${n} rolled again` : `${seven} before the ${n}`;
break;
case BET.DONT_COME:
if (unmoved) why = win ? `Craps ${t} — the Don't Come wins` : `Natural ${t} beats the Don't Come`;
else why = win ? `7 before the ${n}` : `The ${n} rolled`;
break;
case BET.PLACE: case BET.BUY: case BET.BIG:
why = win ? `The ${n} rolled` : `${seven} before the ${n}`;
break;
case BET.LAY:
why = win ? `7 before the ${n}` : `The ${n} rolled`;
break;
case BET.HARD:
if (win) why = `Hard ${n} — ${n / 2} and ${n / 2}`;
else why = t === 7 ? seven : `${n} came easy (${dice[0]}-${dice[1]})`;
break;
case BET.ANY7: why = win ? 'Seven!' : `${t} — no seven`; break;
case BET.ANY_CRAPS: why = win ? `Craps ${t}` : `${t} — no 2, 3 or 12`; break;
case BET.YO: why = win ? 'Yo-eleven!' : `${t} — no 11`; break;
case BET.ACES: why = win ? 'Snake eyes!' : `${t} — no 2`; break;
case BET.ACE_DEUCE: why = win ? 'Ace-deuce!' : `${t} — no 3`; break;
case BET.BOXCARS: why = win ? 'Boxcars!' : `${t} — no 12`; break;
case BET.CE: why = !win ? `${t} — no craps or 11` : t === 11 ? '11 pays 7 to 1' : `Craps ${t} pays 3 to 1`; break;
case BET.HORN: why = win ? `${t} on the Horn` : `${t} — no 2, 3, 11 or 12`; break;
default: why = win ? 'Winner' : 'Loser';
}
const extra = [];
if (win && p.kept) extra.push('stays up');
if (p.commission > 0) extra.push(`$${p.commission} vig`);
if (p.refund > 0) extra.push('odds returned (off on the come-out)');
return extra.length ? `${why} · ${extra.join(' · ')}` : why;
}
export function explainMove(m) {
return m.type === BET.DONT_COME ? `Moves behind the ${m.to}` : `Moves to the ${m.to}`;
}

View File

@ -0,0 +1,313 @@
// Craps table geometry — Phaser-free so tools/verifyCraps.js can import it.
//
// One end of a craps tub seen from the near rail, through the shared casino
// perspective camera (makeProjection). Table space:
// u left/right, −1 (the curved end, left) … +1 (the pyramid wall, right)
// v depth, 0 = far wall … 1 = near wall (the player's rail)
// The felt is the rounded rectangle u∈[−1,1], v∈[0,1] sunk TUB.H px below the
// padded rail. Everything lying on the felt goes through P.project(u, v); things
// raised off it (rail, flying dice) through lift(u, v, h).
//
// Left ~60% of the felt is the betting end (number boxes, Come, Field, Don't
// Pass, Pass Line wrapping the end); the centre strip is the proposition box;
// the right end is open felt where the dice land against the pyramid wall.
import { makeProjection, DOCK } from '../../ui/casino/CasinoGeometry.js';
export { DOCK };
export const VIEW = { cx: 960, yFar: 172, yNear: 812, sFar: 0.72, halfW: 795, squash: 0.9 };
export const P = makeProjection(VIEW);
export const TUB = {
H: 46, // wall height (px at s = 1): the felt sits this far below the rail top
RW: 0.085, // padded rail width (table units)
FACE: 30, // rail's outer face (px at s = 1)
CR: 0.1, // felt corner radius (table units)
};
// Raised points are nearer the camera, so they also spread out from the centre
// line a little — that is what makes the side walls and the end rail read as 3D.
export const LIFT_SPREAD = 0.0011;
export function lift(u, v, h) {
const p = P.project(u, v);
return { x: VIEW.cx + (p.x - VIEW.cx) * (1 + h * LIFT_SPREAD), y: p.y - h * p.s, s: p.s };
}
// Rounded-rectangle outline of the tub offset `d` outward (table units), clockwise
// from the top-left corner. Returned as table-space points.
export function tubOutline(d = 0, perCorner = 10, perSide = 24) {
const r = TUB.CR + d;
const u0 = -1 - d, u1 = 1 + d, v0 = -d, v1 = 1 + d;
const pts = [];
const corner = (cu, cv, a0) => {
for (let i = 0; i <= perCorner; i++) {
const a = (a0 + (90 * i) / perCorner) * (Math.PI / 180);
pts.push({ u: cu + Math.cos(a) * r, v: cv + Math.sin(a) * r });
}
};
const side = (a, b) => {
for (let i = 1; i < perSide; i++) {
const t = i / perSide;
pts.push({ u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t });
}
};
corner(u0 + r, v0 + r, 180); // top-left
side({ u: u0 + r, v: v0 }, { u: u1 - r, v: v0 });
corner(u1 - r, v0 + r, 270); // top-right
side({ u: u1, v: v0 + r }, { u: u1, v: v1 - r });
corner(u1 - r, v1 - r, 0); // bottom-right
side({ u: u1 - r, v: v1 }, { u: u0 + r, v: v1 });
corner(u0 + r, v1 - r, 90); // bottom-left
side({ u: u0, v: v1 - r }, { u: u0, v: v0 + r });
return pts;
}
export function inTub(u, v, d = 0) {
const r = TUB.CR + d;
if (u < -1 - d || u > 1 + d || v < -d || v > 1 + d) return false;
const cu = Math.max(-1 + TUB.CR, Math.min(1 - TUB.CR, u));
const cv = Math.max(TUB.CR, Math.min(1 - TUB.CR, v));
return Math.hypot(u - cu, v - cv) <= r + 1e-9;
}
// Visible felt ends where the near rail's top edge occludes it.
export const NEAR_VISIBLE_V = (() => {
const y = lift(0, 1, TUB.H).y;
return P.unproject(VIEW.cx, y).v;
})();
// ── Layout ───────────────────────────────────────────────────────────────────
const BOX_U0 = -0.66, BOX_W = 0.16;
export const BOX_NUMS = [4, 5, 6, 8, 9, 10];
export const ROWS = {
lay: [0.035, 0.09], main: [0.09, 0.28], buy: [0.28, 0.335],
come: [0.355, 0.47], field: [0.49, 0.625], dontpass: [0.645, 0.715],
pass: [0.735, 0.865], odds: [0.875, 0.94],
};
export const END_U = [-0.86, -0.685]; // Don't Come box + Big 6/8 column
export const LAYOUT_U1 = BOX_U0 + 6 * BOX_W; // 0.30: right edge of the betting end
export const PASS_SIDE = { u0: -0.975, u1: -0.875, v0: 0.05 };
export const PROP = { u0: 0.345, u1: 0.67, v0: 0.05, v1: 0.79, ceU1: 0.395 };
// Dice settle in the upper two-thirds of the open end; the lower right is the results card.
export const LANDING = { u0: 0.71, u1: 0.95, v0: 0.08, v1: 0.66 };
export const WALL_U = 0.985; // dice bounce off the pyramid wall here
export const OFFER = { u0: 0.4, u1: 0.64, v: 0.885 }; // stickman pushes the dice here
export function boxU(n) {
const i = BOX_NUMS.indexOf(n);
return { u0: BOX_U0 + i * BOX_W, u1: BOX_U0 + (i + 1) * BOX_W };
}
const R = (u0, u1, v0, v1) => ({ u0, u1, v0, v1 });
// Prop-box cells
const PU0 = PROP.ceU1 + 0.005;
const PW = PROP.u1 - PU0;
const PROP_ROWS = {
any7: [0.05, 0.14], hardA: [0.15, 0.31], hardB: [0.31, 0.47], one: [0.48, 0.6], horn: [0.61, 0.69], craps: [0.7, 0.79],
};
// Every clickable zone: key → { type, number, rects, name }
// (types match CrapsLogic BET values).
export const ZONES = {};
function zone(key, type, number, name, ...rects) { ZONES[key] = { key, type, number, name, rects }; }
zone('pass', 'pass', null, 'Pass Line',
R(PASS_SIDE.u0, LAYOUT_U1, ROWS.pass[0], ROWS.pass[1]),
R(PASS_SIDE.u0, PASS_SIDE.u1, PASS_SIDE.v0, ROWS.pass[0]));
zone('odds', 'odds', null, 'Odds', R(PASS_SIDE.u1, LAYOUT_U1, ROWS.odds[0], ROWS.odds[1]));
zone('dontpass', 'dontpass', null, "Don't Pass Bar", R(END_U[0], LAYOUT_U1, ROWS.dontpass[0], ROWS.dontpass[1]));
zone('dontcome', 'dontcome', null, "Don't Come Bar", R(END_U[0], END_U[1], ROWS.lay[0], ROWS.buy[1]));
zone('come', 'come', null, 'Come', R(BOX_U0, LAYOUT_U1, ROWS.come[0], ROWS.come[1]));
zone('field', 'field', null, 'Field', R(BOX_U0, LAYOUT_U1, ROWS.field[0], ROWS.field[1]));
zone('big6', 'big', 6, 'Big 6', R(END_U[0], END_U[1], ROWS.come[0], (ROWS.come[0] + ROWS.field[1]) / 2));
zone('big8', 'big', 8, 'Big 8', R(END_U[0], END_U[1], (ROWS.come[0] + ROWS.field[1]) / 2, ROWS.field[1]));
for (const n of BOX_NUMS) {
const { u0, u1 } = boxU(n);
zone(`lay${n}`, 'lay', n, `Lay ${n}`, R(u0, u1, ROWS.lay[0], ROWS.lay[1]));
zone(`place${n}`, 'place', n, `Place ${n}`, R(u0, u1, ROWS.main[0], ROWS.main[1]));
zone(`buy${n}`, 'buy', n, `Buy ${n}`, R(u0, u1, ROWS.buy[0], ROWS.buy[1]));
}
zone('any7', 'any7', null, 'Any Seven', R(PU0, PROP.u1, ...PROP_ROWS.any7));
zone('hard6', 'hard', 6, 'Hard 6', R(PU0, PU0 + PW / 2, ...PROP_ROWS.hardA));
zone('hard10', 'hard', 10, 'Hard 10', R(PU0 + PW / 2, PROP.u1, ...PROP_ROWS.hardA));
zone('hard8', 'hard', 8, 'Hard 8', R(PU0, PU0 + PW / 2, ...PROP_ROWS.hardB));
zone('hard4', 'hard', 4, 'Hard 4', R(PU0 + PW / 2, PROP.u1, ...PROP_ROWS.hardB));
['acedeuce', 'aces', 'boxcars', 'yo'].forEach((k, i) => {
const names = { acedeuce: 'Ace-Deuce', aces: 'Aces', boxcars: 'Boxcars', yo: 'Yo-Eleven' };
zone(k, k, null, names[k], R(PU0 + (PW * i) / 4, PU0 + (PW * (i + 1)) / 4, ...PROP_ROWS.one));
});
zone('horn', 'horn', null, 'Horn', R(PU0, PROP.u1, ...PROP_ROWS.horn));
zone('anycraps', 'anycraps', null, 'Any Craps', R(PU0, PROP.u1, ...PROP_ROWS.craps));
zone('ce', 'ce', null, 'C & E', R(PROP.u0, PROP.ceU1, PROP.v0, PROP.v1));
export function rectCenter(r) { return { u: (r.u0 + r.u1) / 2, v: (r.v0 + r.v1) / 2 }; }
export function hitZoneUV(u, v) {
for (const z of Object.values(ZONES)) {
for (const r of z.rects) if (u >= r.u0 && u <= r.u1 && v >= r.v0 && v <= r.v1) return z.key;
}
return null;
}
export function hitZone(x, y) {
const { u, v } = P.unproject(x, y);
return hitZoneUV(u, v);
}
// Screen outline of a table-space rect (for highlights).
export function rectOutline(r) {
return [P.project(r.u0, r.v0), P.project(r.u1, r.v0), P.project(r.u1, r.v1), P.project(r.u0, r.v1)];
}
export function zoneKeyFor(type, number) {
for (const z of Object.values(ZONES)) if (z.type === type && (z.number ?? null) === (number ?? null)) return z.key;
return null;
}
// ── Seats ────────────────────────────────────────────────────────────────────
// Seven places around the rail. The human stands at the near rail; opponents
// fill FILL_ORDER. `slot` is the left-to-right order used for seat-fixed spots
// on the long lanes (Pass, Field, Come, ...), so each player's chips sit
// roughly in front of where they stand.
export const SEATS = {
H: { side: 'near', u: -0.18 },
N2: { side: 'near', u: -0.56 },
N1: { side: 'near', u: -0.88 },
E: { side: 'end', v: 0.42 },
F3: { side: 'far', u: -0.78 },
F2: { side: 'far', u: -0.45 },
F1: { side: 'far', u: -0.12 },
};
export const FILL_ORDER = ['N2', 'F2', 'E', 'F1', 'N1', 'F3'];
export const SLOT_ORDER = ['E', 'N1', 'F3', 'N2', 'F2', 'H', 'F1'];
// Player index → seat name for a table of n opponents.
export function seatNames(nOpp) {
return ['H', ...FILL_ORDER.slice(0, Math.min(6, nOpp))];
}
// Table-space point in the middle of the rail's chip groove for a seat.
export function railUV(name, offset = 0) {
const s = SEATS[name];
const d = TUB.RW * 0.5;
if (s.side === 'near') return { u: s.u + offset, v: 1 + d };
if (s.side === 'far') return { u: s.u + offset, v: -d };
return { u: -1 - d, v: s.v + offset };
}
// Where a seat's chips sit in the rail (screen, raised to the rail top).
export function railPose(name, offset = 0) {
const { u, v } = railUV(name, offset);
return lift(u, v, TUB.H);
}
// Portrait placement (screen) — beside the rail, outside the tub.
export function seatPortrait(name) {
const s = SEATS[name];
if (s.side === 'near') {
const p = lift(s.u, 1 + TUB.RW, TUB.H);
return { x: p.x + 70, y: p.y + TUB.FACE * p.s + 12, r: 32 };
}
if (s.side === 'far') {
const p = lift(s.u, -TUB.RW, TUB.H);
return { x: p.x, y: p.y - 40, r: 32 };
}
const p = lift(-1 - TUB.RW, s.v, TUB.H);
return { x: p.x - 48, y: p.y - 8, r: 34 };
}
// Where a shooter releases the dice (table space, above the rail).
export function throwOrigin(name) {
const s = SEATS[name];
if (s.side === 'near') return { u: s.u + 0.05, v: 0.96, h: TUB.H + 30 };
if (s.side === 'far') return { u: s.u + 0.05, v: 0.04, h: TUB.H + 30 };
return { u: -0.96, v: s.v, h: TUB.H + 30 };
}
// ── Bet spots ────────────────────────────────────────────────────────────────
// A lane is where stacks for one kind of bet are laid out:
// 'slots' — one fixed spot per seat (long lanes), ordered by SLOT_ORDER
// 'flow' — stacks share a cell, spread left-to-right in seat order
export const LANES = {
pass: { kind: 'slots', u0: PASS_SIDE.u1 + 0.02, u1: LAYOUT_U1 - 0.02, v: 0.81 },
odds: { kind: 'slots', u0: PASS_SIDE.u1 + 0.02, u1: LAYOUT_U1 - 0.02, v: 0.912 },
dontpass: { kind: 'slots', u0: END_U[0] + 0.03, u1: LAYOUT_U1 - 0.03, v: 0.695 },
come: { kind: 'slots', u0: BOX_U0 + 0.03, u1: LAYOUT_U1 - 0.03, v: 0.445 },
field: { kind: 'slots', u0: BOX_U0 + 0.03, u1: LAYOUT_U1 - 0.03, v: 0.6 },
ce: { kind: 'vslots', u: (PROP.u0 + PROP.ceU1) / 2, v0: PROP.v0 + 0.05, v1: PROP.v1 - 0.04 },
dontcome: { kind: 'flow', u0: END_U[0] + 0.02, u1: END_U[1] - 0.02, v: 0.29 },
};
for (const n of BOX_NUMS) {
const { u0, u1 } = boxU(n);
LANES[`place${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.195 };
LANES[`comept${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.255 };
LANES[`buy${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.318 };
LANES[`lay${n}`] = { kind: 'flow', u0: u0 + 0.02, u1: u1 - 0.02, v: 0.07 };
}
for (const k of ['big6', 'big8', 'hard4', 'hard6', 'hard8', 'hard10', 'any7', 'acedeuce', 'aces', 'boxcars', 'yo', 'horn', 'anycraps']) {
const r = ZONES[k].rects[0];
LANES[k] = { kind: 'flow', u0: r.u0 + 0.025, u1: r.u1 - 0.025, v: r.v0 + (r.v1 - r.v0) * 0.66 };
}
// Lane key for a bet (types match CrapsLogic BET values).
export function laneForBet(bet) {
switch (bet.type) {
case 'pass': return 'pass';
case 'dontpass': return 'dontpass';
case 'come': return bet.comePoint == null ? 'come' : `comept${bet.comePoint}`;
case 'dontcome': return bet.comePoint == null ? 'dontcome' : `lay${bet.comePoint}`;
case 'field': return 'field';
case 'place': return `place${bet.number}`;
case 'buy': return `buy${bet.number}`;
case 'lay': return `lay${bet.number}`;
case 'big': return `big${bet.number}`;
case 'hard': return `hard${bet.number}`;
default: return LANES[bet.type] ? bet.type : null;
}
}
// Table-space spot for a stack in `lane`: seat-fixed lanes use the seat's slot;
// flow lanes use the stack's index among the `count` stacks sharing the lane.
export function laneSpot(laneKey, { seat = 'H', index = 0, count = 1 } = {}) {
const L = LANES[laneKey];
const slot = SLOT_ORDER.indexOf(seat);
if (L.kind === 'slots') {
return { u: L.u0 + ((slot + 0.5) / SLOT_ORDER.length) * (L.u1 - L.u0), v: L.v };
}
if (L.kind === 'vslots') {
return { u: L.u, v: L.v0 + ((slot + 0.5) / SLOT_ORDER.length) * (L.v1 - L.v0) };
}
const w = L.u1 - L.u0;
const step = count > 1 ? Math.min(0.06, w / (count - 1)) : 0;
return { u: (L.u0 + L.u1) / 2 + (index - (count - 1) / 2) * step, v: L.v };
}
// Where odds go for a line / come bet relative to its flat stack (table units).
export function oddsOffset(laneKey) {
if (laneKey === 'pass') return null; // behind the line: the 'odds' lane
return { du: 0.03, dv: -0.012 };
}
// ── Furniture ────────────────────────────────────────────────────────────────
export const BANK = { u0: 0.36, u1: 0.68 }; // house chip rack in the far rail
export function bankPose() { return lift((BANK.u0 + BANK.u1) / 2, -TUB.RW * 0.5, TUB.H); }
export const BOWL = { u: 0.84 }; // stickman's dice bowl (far rail)
export function bowlPose() { return lift(BOWL.u, -TUB.RW * 0.5, TUB.H); }
export function puckOffUV() { return { u: (END_U[0] + END_U[1]) / 2, v: 0.12 }; }
export function puckOnUV(n) { const { u0, u1 } = boxU(n); return { u: (u0 + u1) / 2, v: 0.125 }; }
export function offerSpot(i, n = 5) {
return { u: OFFER.u0 + ((i + 0.5) / n) * (OFFER.u1 - OFFER.u0), v: OFFER.v };
}
// Roll-history board (screen rect, top-right) and the stickman's call line.
// Below the music widget (buttons + track name fill the top ~76px on the right).
export const BOARD = { x: 1670, y: 88, w: 238, h: 150 };
export const CALL = { x: 1330, y: 40, maxW: 500 };
export const STACK = { human: 50, ai: 42 }; // chip-stack diameter at s = 1
// "This roll" results card, lower right (over the near corner of the open end).
export const RESULT = { x: 1560, y: 566, w: 348, h: 374 };

598
tools/verifyCraps.js Normal file
View File

@ -0,0 +1,598 @@
#!/usr/bin/env node
// verifyCraps.js — headless checks for Craps: every bet against all 36 dice
// combos, exact house edges (Markov solve over resolveRoll itself), odds caps,
// take-down / working rules, a seeded AI soak for chip conservation, and the
// table geometry (zones, per-seat bet spots, rail stacks).
import { readFileSync } from 'node:fs';
import {
BET, POINT_NUMBERS, HARD_NUMBERS, NUMBERED, ONE_ROLL,
createInitialState, placeBet, addOdds, reduceBet, removeBet, setWorking, refundBets,
setDice, rollDice, resolveRoll, clearLastDeltas, totalAtRisk, maxOddsFor, oddsRoom,
isContract, isWorking, houseEdge, paysLabel, stickCall, explainPayout, explainMove, betLabel,
} from '../src/games/craps/CrapsLogic.js';
import { chooseBets, chooseOdds } from '../src/games/craps/CrapsAI.js';
import {
P, VIEW, TUB, ZONES, LANES, SEATS, SLOT_ORDER, FILL_ORDER, seatNames, laneSpot, laneForBet, hitZoneUV, inTub,
NEAR_VISIBLE_V, railUV, railPose, seatPortrait, throwOrigin, LANDING, BOARD, DOCK, offerSpot, OFFER, PROP, CALL,
puckOnUV, puckOffUV, BOX_NUMS, zoneKeyFor, lift, RESULT,
} from '../src/games/craps/CrapsTable.js';
import { simulateThrow, topFace, restingQ, DIE } from '../src/games/craps/CrapsDice.js';
let pass = 0, fail = 0;
function ok(label, cond, detail = '') {
if (cond) pass++;
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
}
const section = (n) => console.log(`\n${n}`);
const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;
function mulberry32(seed) {
return function () {
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const ALL_DICE = [];
for (let a = 1; a <= 6; a++) for (let b = 1; b <= 6; b++) ALL_DICE.push([a, b]);
// A one-player table with the bankroll large enough for anything.
function table(point = null, chips = 100000) {
const s = createInitialState([], chips, 'T');
s.point = point;
s.phase = point === null ? 'comeout' : 'point';
return s;
}
function withBet(point, spec, { comePoint = null, odds = 0, onComeOut = false } = {}) {
const line = spec.type === BET.PASS || spec.type === BET.DONT_PASS;
const come = spec.type === BET.COME || spec.type === BET.DONT_COME;
let s = table(line ? null : come ? 6 : (point === 'cp' ? 6 : point));
s = placeBet(s, 0, spec);
const b = s.players[0].bets[0];
if (!b) throw new Error(`withBet: rejected ${JSON.stringify(spec)}`);
if (comePoint != null) b.comePoint = comePoint;
b.oddsAmount = odds;
s.players[0].chips -= odds;
b.onComeOut = onComeOut;
if (point !== 'cp') s.point = point;
s.phase = s.point === null ? 'comeout' : 'point';
return s;
}
// One roll with a single bet: returns { delta, result, kept, open, next }.
function oneRoll(state, dice) {
const r = resolveRoll(setDice(state, dice));
const pay = r.payouts.find((p) => p.playerIndex === 0);
return { r, pay, next: r.state };
}
// Exact expected value (per decision) of the player's single bet, by value
// iteration over the Markov chain that resolveRoll itself defines.
function exactEV(start) {
const key = (s) => JSON.stringify([s.point, s.players[0].bets.map((b) => [b.comePoint, b.amount, b.oddsAmount, b.onComeOut])]);
const states = new Map();
const queue = [start];
states.set(key(start), { s: start, edges: null, v: 0 });
while (queue.length) {
const s = queue.shift();
const node = states.get(key(s));
node.edges = [];
for (const d of ALL_DICE) {
const { pay, next } = oneRoll(s, d);
if (pay) { node.edges.push({ p: 1 / 36, delta: pay.delta }); continue; }
next.players[0].lastDelta = 0;
const k = key(next);
if (!states.has(k)) { states.set(k, { s: next, edges: null, v: 0 }); queue.push(next); }
node.edges.push({ p: 1 / 36, to: k });
}
}
for (let it = 0; it < 4000; it++) {
let change = 0;
for (const node of states.values()) {
let v = 0;
for (const e of node.edges) v += e.p * (e.to ? states.get(e.to).v : e.delta);
change = Math.max(change, Math.abs(v - node.v));
node.v = v;
}
if (change < 1e-13) break;
}
return states.get(key(start)).v;
}
const edgeOf = (s) => -exactEV(s) / (s.players[0].bets[0].amount + s.players[0].bets[0].oddsAmount) * 100;
// ── 1. Every bet × all 36 rolls against a hand-written table ─────────────────
section('Single-roll resolution (36 combos per bet)');
{
// expected(total, hard, isComeOut) → ['win', winnings] | ['lose'] | ['push'] | ['open']
const W = (w) => ['win', w];
const L = ['lose'], O = ['open'], Pu = ['push'];
const cases = [
{ name: 'Field $10', spec: { type: BET.FIELD, amount: 10 }, point: null,
exp: (t) => (t === 2 ? W(20) : t === 12 ? W(30) : [3, 4, 9, 10, 11].includes(t) ? W(10) : L) },
{ name: 'Pass $10 come-out', spec: { type: BET.PASS, amount: 10 }, point: null,
exp: (t) => (t === 7 || t === 11 ? W(10) : [2, 3, 12].includes(t) ? L : O) },
{ name: "Don't Pass $10 come-out", spec: { type: BET.DONT_PASS, amount: 10 }, point: null,
exp: (t) => (t === 2 || t === 3 ? W(10) : t === 7 || t === 11 ? L : O) }, // 12 barred: stands
{ name: 'Any 7 $5', spec: { type: BET.ANY7, amount: 5 }, point: 6, exp: (t) => (t === 7 ? W(20) : L) },
{ name: 'Any Craps $5', spec: { type: BET.ANY_CRAPS, amount: 5 }, point: 6, exp: (t) => ([2, 3, 12].includes(t) ? W(35) : L) },
{ name: 'Yo $5', spec: { type: BET.YO, amount: 5 }, point: null, exp: (t) => (t === 11 ? W(75) : L) },
{ name: 'Aces $5', spec: { type: BET.ACES, amount: 5 }, point: null, exp: (t) => (t === 2 ? W(150) : L) },
{ name: 'Ace-Deuce $5', spec: { type: BET.ACE_DEUCE, amount: 5 }, point: null, exp: (t) => (t === 3 ? W(75) : L) },
{ name: 'Boxcars $5', spec: { type: BET.BOXCARS, amount: 5 }, point: null, exp: (t) => (t === 12 ? W(150) : L) },
{ name: 'C&E $2', spec: { type: BET.CE, amount: 2 }, point: null, exp: (t) => ([2, 3, 12].includes(t) ? W(6) : t === 11 ? W(14) : L) },
{ name: 'Horn $4', spec: { type: BET.HORN, amount: 4 }, point: null, exp: (t) => (t === 2 || t === 12 ? W(27) : t === 3 || t === 11 ? W(12) : L) },
{ name: 'Big 6 $10', spec: { type: BET.BIG, number: 6, amount: 10 }, point: 5, exp: (t) => (t === 6 ? W(10) : t === 7 ? L : O) },
{ name: 'Hard 8 $5 (point)', spec: { type: BET.HARD, number: 8, amount: 5 }, point: 5,
exp: (t, h) => (t === 8 && h ? W(45) : t === 8 || t === 7 ? L : O) },
{ name: 'Hard 4 $5 (point)', spec: { type: BET.HARD, number: 4, amount: 5 }, point: 5,
exp: (t, h) => (t === 4 && h ? W(35) : t === 4 || t === 7 ? L : O) },
{ name: 'Hard 6 $5 (come-out, off)', spec: { type: BET.HARD, number: 6, amount: 5 }, point: null, exp: () => O },
{ name: 'Place 6 $12 (point)', spec: { type: BET.PLACE, number: 6, amount: 12 }, point: 5, exp: (t) => (t === 6 ? W(14) : t === 7 ? L : O) },
{ name: 'Place 4 $10 (point)', spec: { type: BET.PLACE, number: 4, amount: 10 }, point: 5, exp: (t) => (t === 4 ? W(18) : t === 7 ? L : O) },
{ name: 'Place 9 $10 (point)', spec: { type: BET.PLACE, number: 9, amount: 10 }, point: 5, exp: (t) => (t === 9 ? W(14) : t === 7 ? L : O) },
{ name: 'Place 8 $6 (come-out, off)', spec: { type: BET.PLACE, number: 8, amount: 6 }, point: null, exp: () => O },
{ name: 'Buy 10 $20', spec: { type: BET.BUY, number: 10, amount: 20 }, point: 5, exp: (t) => (t === 10 ? W(40) : t === 7 ? L : O) },
{ name: 'Lay 4 $40', spec: { type: BET.LAY, number: 4, amount: 40 }, point: null, exp: (t) => (t === 7 ? W(20) : t === 4 ? L : O) },
];
for (const c of cases) {
const s0 = placeBet(table(c.point), 0, c.spec);
ok(`${c.name}: placed`, s0.players[0].bets.length === 1);
let bad = 0;
for (const d of ALL_DICE) {
const t = d[0] + d[1], h = d[0] === d[1];
const [res, w] = c.exp(t, h);
const { pay } = oneRoll(s0, d);
const got = pay ? pay.result : 'open';
if (got !== res || (res === 'win' && pay.winnings !== w)) {
bad++;
if (bad < 3) ok(`${c.name} on ${d.join('-')}`, false, `expected ${res}${w ? ' ' + w : ''}, got ${got}${pay ? ' ' + pay.winnings : ''}`);
}
}
ok(`${c.name}: all 36 combos`, bad === 0);
}
// Commissions
{
const s0 = placeBet(table(5), 0, { type: BET.BUY, number: 4, amount: 20 });
const { pay } = oneRoll(s0, [2, 2]);
ok('Buy 4 $20: pays 40 less $1 vig', pay.winnings === 40 && pay.commission === 1 && pay.delta === 39 && pay.kept);
const s1 = placeBet(table(5), 0, { type: BET.LAY, number: 10, amount: 40 });
const r1 = oneRoll(s1, [3, 4]).pay;
ok('Lay 10 $40: wins 20 less $1 vig', r1.winnings === 20 && r1.commission === 1 && r1.delta === 19 && r1.kept);
}
// Pass / Don't on the point, with odds
for (const n of POINT_NUMBERS) {
const mult = n === 4 || n === 10 ? 3 : n === 5 || n === 9 ? 4 : 5;
let s = placeBet(table(null), 0, { type: BET.PASS, amount: 10 });
s.point = n; s.phase = 'point';
const b = s.players[0].bets[0];
ok(`Pass on ${n}: odds cap is ${mult}×`, maxOddsFor(b, s) === 10 * mult);
s = addOdds(s, 0, b.id, 10000);
ok(`Pass on ${n}: addOdds clamps to the cap`, s.players[0].bets[0].oddsAmount === 10 * mult);
const odds = 10 * mult;
const trueW = n === 4 || n === 10 ? odds * 2 : n === 5 || n === 9 ? odds * 3 / 2 : odds * 6 / 5;
const hit = oneRoll(s, n === 4 ? [2, 2] : n === 10 ? [5, 5] : [1, n - 1]).pay;
ok(`Pass on ${n} + max odds: point made pays flat + true odds`, hit.result === 'win' && hit.winnings === 10 + trueW, `${hit.winnings}`);
const seven = oneRoll(s, [3, 4]).pay;
ok(`Pass on ${n} + odds: seven-out loses everything`, seven.result === 'lose' && seven.delta === -(10 + odds));
let d = placeBet(table(null), 0, { type: BET.DONT_PASS, amount: 10 });
d.point = n; d.phase = 'point';
const db = d.players[0].bets[0];
ok(`Don't on ${n}: lay cap is 6× flat`, maxOddsFor(db, d) === 60);
d = addOdds(d, 0, db.id, 60);
const layW = n === 4 || n === 10 ? 30 : n === 5 || n === 9 ? 40 : 50;
const dw = oneRoll(d, [3, 4]).pay;
ok(`Don't on ${n} + 6× lay: seven pays flat + ${layW} (max win = 6× flat)`, dw.result === 'win' && dw.winnings === 10 + layW);
}
// A barred 12 is no action: the Don't bet stays exactly where it is.
{
const dp = placeBet(table(null), 0, { type: BET.DONT_PASS, amount: 10 });
const r = resolveRoll(setDice(dp, [6, 6]));
ok("Don't Pass on a come-out 12 stays up, untouched", r.payouts.length === 0 && r.state.players[0].bets.length === 1
&& r.state.players[0].bets[0].amount === 10 && r.state.players[0].chips === dp.players[0].chips);
const dc = placeBet(table(8), 0, { type: BET.DONT_COME, amount: 10 });
const r2 = resolveRoll(setDice(dc, [6, 6]));
ok("Don't Come on a 12 stays in the Don't Come box", r2.payouts.length === 0 && r2.state.players[0].bets[0].comePoint == null);
}
// Come bets travel, then win / lose; come odds off on the come-out.
{
let s = placeBet(table(5), 0, { type: BET.COME, amount: 10 });
const r = resolveRoll(setDice(s, [4, 4]));
ok('Come on 8: travels', r.moves.length === 1 && r.moves[0].to === 8 && r.state.players[0].bets[0].comePoint === 8);
s = r.state;
const cb = s.players[0].bets[0];
ok('Come on 8: is a contract bet', isContract(cb, s));
ok('Come on 8: cannot be taken down', removeBet(s, 0, cb.id) === s);
s = addOdds(s, 0, cb.id, 50);
ok('Come on 8: takes 5× odds', s.players[0].bets[0].oddsAmount === 50);
const win = oneRoll(s, [5, 3]).pay;
ok('Come 8 hits: flat + 6:5 odds', win.result === 'win' && win.winnings === 10 + 60);
// come-out: odds off
const co = { ...s, point: null, phase: 'comeout' };
const lose7 = oneRoll(co, [3, 4]).pay;
ok('Come 8 on a come-out 7: flat loses, odds returned', lose7.result === 'lose' && lose7.refund === 50 && lose7.delta === -10);
const hit8 = oneRoll(co, [4, 4]).pay;
ok('Come 8 hits on the come-out: flat paid, odds returned unpaid', hit8.result === 'win' && hit8.winnings === 10 && hit8.delta === 10);
// Don't Come
let dc = placeBet(table(5), 0, { type: BET.DONT_COME, amount: 10 });
dc = resolveRoll(setDice(dc, [2, 2])).state;
const dcb = dc.players[0].bets[0];
ok("Don't Come travels to 4", dcb.comePoint === 4 && !isContract(dcb, dc));
ok("Don't Come lay cap 6×", maxOddsFor(dcb, dc) === 60);
ok("Don't Come can be taken down", removeBet(dc, 0, dcb.id).players[0].bets.length === 0);
}
}
// ── 2. Exact house edges ─────────────────────────────────────────────────────
section('Exact house edges (Markov solve)');
{
const E = [
['Pass', withBet(null, { type: BET.PASS, amount: 10 }), 7 / 495 * 100],
// per decision: a barred 12 is no action, so the bet simply stands
["Don't Pass", withBet(null, { type: BET.DONT_PASS, amount: 10 }), 108 / 7700 * 100],
['Come', withBet('cp', { type: BET.COME, amount: 10 }), 7 / 495 * 100],
["Don't Come", withBet('cp', { type: BET.DONT_COME, amount: 10 }), 108 / 7700 * 100],
['Field', withBet(null, { type: BET.FIELD, amount: 10 }), 100 / 36],
['Place 6 $6', withBet(5, { type: BET.PLACE, number: 6, amount: 6 }), 100 / 66],
['Place 5 $5', withBet(6, { type: BET.PLACE, number: 5, amount: 5 }), 4],
['Place 4 $5', withBet(6, { type: BET.PLACE, number: 4, amount: 5 }), 100 / 15],
['Place 8 $6 from the come-out', withBet(null, { type: BET.PLACE, number: 8, amount: 6 }), 100 / 66],
['Buy 4 $20', withBet(6, { type: BET.BUY, number: 4, amount: 20 }), 5 / 3],
['Buy 5 $20', withBet(6, { type: BET.BUY, number: 5, amount: 20 }), 2],
['Buy 6 $20', withBet(5, { type: BET.BUY, number: 6, amount: 20 }), 25 / 11],
['Lay 4 $40', withBet(6, { type: BET.LAY, number: 4, amount: 40 }), 5 / 3],
['Lay 5 $30', withBet(6, { type: BET.LAY, number: 5, amount: 30 }), 2],
['Lay 6 $30', withBet(5, { type: BET.LAY, number: 6, amount: 30 }), 20 / 11],
['Big 6', withBet(5, { type: BET.BIG, number: 6, amount: 10 }), 100 / 11],
['Hard 6', withBet(5, { type: BET.HARD, number: 6, amount: 5 }), 100 / 11],
['Hard 4', withBet(5, { type: BET.HARD, number: 4, amount: 5 }), 100 / 9],
['Hard 10 from the come-out', withBet(null, { type: BET.HARD, number: 10, amount: 5 }), 100 / 9],
['Any 7', withBet(null, { type: BET.ANY7, amount: 5 }), 100 / 6],
['Any Craps', withBet(null, { type: BET.ANY_CRAPS, amount: 5 }), 100 / 9],
['Yo', withBet(null, { type: BET.YO, amount: 5 }), 100 / 9],
['Aces', withBet(null, { type: BET.ACES, amount: 5 }), 500 / 36],
['Ace-Deuce', withBet(null, { type: BET.ACE_DEUCE, amount: 5 }), 100 / 9],
['Boxcars', withBet(null, { type: BET.BOXCARS, amount: 5 }), 500 / 36],
['C&E $2', withBet(null, { type: BET.CE, amount: 2 }), 100 / 9],
['Horn $4', withBet(null, { type: BET.HORN, amount: 4 }), 12.5],
];
for (const [name, s, want] of E) {
const got = edgeOf(s);
ok(`${name}: edge ${want.toFixed(3)}%`, near(got, want, 1e-6), `got ${got.toFixed(6)}%`);
const b = s.players[0].bets[0];
const shown = houseEdge(b.type, b.number);
ok(`${name}: tooltip edge ${shown}% matches to 2dp`, shown != null && Math.abs(shown - want) < 0.006, `exact ${want.toFixed(4)}`);
}
// Odds are free: adding max odds to a Pass/Come on any point leaves EV unchanged.
for (const n of POINT_NUMBERS) {
const mult = n === 4 || n === 10 ? 3 : n === 5 || n === 9 ? 4 : 5;
const flat = withBet(n, { type: BET.PASS, amount: 10 });
const odds = withBet(n, { type: BET.PASS, amount: 10 }, { odds: 10 * mult });
ok(`Pass odds on ${n} are zero-edge`, near(exactEV(flat), exactEV(odds), 1e-9));
const dflat = withBet(n, { type: BET.DONT_PASS, amount: 10 });
const dodds = withBet(n, { type: BET.DONT_PASS, amount: 10 }, { odds: 60 });
ok(`Lay odds on ${n} are zero-edge`, near(exactEV(dflat), exactEV(dodds), 1e-9));
}
}
// ── 3. Placement, take-downs, working ────────────────────────────────────────
section('Placement / take-down / working rules');
{
let s = table(null, 100);
ok('Come is illegal on the come-out', placeBet(s, 0, { type: BET.COME, amount: 5 }) === s);
ok('Place needs a point number', placeBet(s, 0, { type: BET.PLACE, number: 7, amount: 5 }) === s);
ok('Hard needs 4/6/8/10', placeBet(s, 0, { type: BET.HARD, number: 5, amount: 5 }) === s);
ok('Big only 6/8', placeBet(s, 0, { type: BET.BIG, number: 4, amount: 5 }) === s);
ok('Cannot bet more than the bankroll', placeBet(s, 0, { type: BET.FIELD, amount: 101 }) === s);
s = placeBet(s, 0, { type: BET.PASS, amount: 10 });
s = placeBet(s, 0, { type: BET.PASS, amount: 5 });
ok('Repeat chips stack onto the same bet', s.players[0].bets.length === 1 && s.players[0].bets[0].amount === 15);
ok('Bankroll debited', s.players[0].chips === 85);
const pb = s.players[0].bets[0];
ok('Pass is not contract before the point', !isContract(pb, s));
const part = reduceBet(s, 0, pb.id, { amount: 5 });
ok('Undo a chip: reduceBet partial', part.players[0].bets[0].amount === 10 && part.players[0].chips === 90);
const off = removeBet(s, 0, pb.id);
ok('Pass can come down on the come-out', off.players[0].bets.length === 0 && off.players[0].chips === 100);
// Place bets: off on come-out, can be called on.
let p = placeBet(table(null, 100), 0, { type: BET.PLACE, number: 6, amount: 12 });
const plb = p.players[0].bets[0];
ok('Place is off on the come-out', !isWorking(plb, p));
p = setWorking(p, 0, plb.id, true);
ok('Place called on for the come-out', isWorking(p.players[0].bets[0], p));
const hit = oneRoll(p, [3, 3]).pay;
ok('Called-on Place 6 wins on a come-out 6', hit && hit.result === 'win' && hit.winnings === 14);
const after = oneRoll(p, [3, 3]).next;
ok('A point resets the called-on flag', after.point === 6 && after.players[0].bets[0].onComeOut === false);
ok('Winning place stays up, stake not returned', after.players[0].chips === 100 - 12 + 14 && after.players[0].bets[0].amount === 12);
const pt = table(5, 100);
const pp = placeBet(pt, 0, { type: BET.PLACE, number: 6, amount: 12 });
ok('setWorking only during the come-out', setWorking(pp, 0, pp.players[0].bets[0].id, false) === pp);
// Contract Pass after the point.
let c = placeBet(table(null, 100), 0, { type: BET.PASS, amount: 10 });
c = resolveRoll(setDice(c, [2, 2])).state;
const cb = c.players[0].bets[0];
ok('Pass is contract once the point is set', isContract(cb, c) && removeBet(c, 0, cb.id) === c);
c = addOdds(c, 0, cb.id, 30);
ok('oddsRoom is 0 at the cap', oddsRoom(c, 0, cb.id) === 0);
const oddsOff = reduceBet(c, 0, cb.id, { part: 'odds' });
ok('Odds can always come down', oddsOff.players[0].bets[0].oddsAmount === 0 && oddsOff.players[0].chips === c.players[0].chips + 30);
const cleared = refundBets(c, 0);
ok('Clear leaves contract bets', cleared.players[0].bets.length === 1);
const left = refundBets(c, 0, { force: true });
ok('Leaving refunds everything', left.players[0].bets.length === 0 && left.players[0].chips === 100);
// Shrinking a Don't flat trims laid odds above the new cap.
let dd = placeBet(table(null, 500), 0, { type: BET.DONT_PASS, amount: 20 });
dd = resolveRoll(setDice(dd, [2, 2])).state;
const ddb = dd.players[0].bets[0];
dd = addOdds(dd, 0, ddb.id, 120);
const dd2 = reduceBet(dd, 0, ddb.id, { amount: 10 });
ok("Shrinking a Don't flat returns excess odds", dd2.players[0].bets[0].oddsAmount === 60 && dd2.players[0].chips === dd.players[0].chips + 10 + 60);
// Stickman always has something to say.
let calls = 0;
for (const point of [null, 4, 6, 9]) {
for (const d of ALL_DICE) {
const r = resolveRoll(setDice(table(point), d));
if (typeof stickCall(r, point) === 'string' && stickCall(r, point).length > 0) calls++;
}
}
ok('stickCall covers every roll', calls === 4 * 36);
// Every decision on every bet gets a plain-English reason and a name.
let explained = 0, blank = 0;
for (const point of [null, 4, 5, 6, 8, 9, 10]) {
for (const z of Object.values(ZONES)) {
if (z.type === 'odds') continue;
const s0 = table(point);
s0.players[0].bets.push({ id: 1, type: z.type, number: z.number ?? null, comePoint: null, amount: 20, oddsAmount: 0, onComeOut: true });
const moved = table(point);
if (z.type === BET.COME || z.type === BET.DONT_COME) moved.players[0].bets.push({ id: 2, type: z.type, number: null, comePoint: 6, amount: 20, oddsAmount: 20, onComeOut: false });
for (const d of ALL_DICE) {
for (const [st, unmoved] of [[s0, true], [moved, false]]) {
const r = resolveRoll(setDice(st, d));
for (const p of r.payouts) {
const why = explainPayout(p, { dice: d, prevPoint: point, unmoved: unmoved && p.betId === 1 });
const name = betLabel(p.betType, p.number);
if (!why || !name || /undefined|null|NaN/.test(why + name)) { blank++; if (blank < 4) ok(`explain ${p.betType} ${d}`, false, `${name}: ${why}`); }
else explained++;
}
for (const m of r.moves) if (!explainMove(m).includes(String(m.to))) blank++;
}
}
}
}
ok(`every decision explained (${explained})`, blank === 0 && explained > 3000, `${blank} blank`);
const ex = (type, number, result, dice, prevPoint, extra = {}) => explainPayout({ betType: type, number, result, commission: 0, refund: 0, kept: false, ...extra }, { dice, prevPoint, ...extra });
ok('Field loss says why', ex(BET.FIELD, null, 'lose', [5, 3], 6) === "8 isn't a Field number");
ok('Hard way lost to the easy way', ex(BET.HARD, 8, 'lose', [5, 3], 6) === '8 came easy (5-3)');
ok('Seven-out named', ex(BET.PLACE, 6, 'lose', [3, 4], 9) === 'Seven-out before the 6');
ok('Point made named', ex(BET.PASS, null, 'win', [4, 2], 6) === 'Point 6 made');
ok('Come natural on its own come-out', ex(BET.COME, null, 'win', [5, 6], 8, { unmoved: true }) === 'Natural 11 on the Come');
ok('Buy vig noted', ex(BET.BUY, 4, 'win', [2, 2], 8, { commission: 1, kept: true }) === 'The 4 rolled · stays up · $1 vig');
ok('Come odds returned noted', ex(BET.COME, 8, 'lose', [3, 4], null, { refund: 40 }).includes('odds returned'));
for (const type of Object.values(BET)) {
const nums = NUMBERED[type] ?? [null];
for (const n of nums) ok(`${type}${n ?? ''} has a pays label`, paysLabel(type, n).length > 0);
}
}
// ── 4. Seeded AI soak: chip conservation ─────────────────────────────────────
section('AI soak (chip conservation, 6 bots × 20k rolls)');
{
const rng = mulberry32(20261124);
// names chosen so all four AI personalities play
const opps = ['ava', 'ben', 'cara', 'eli', 'ivy', 'kai'].map((id) => ({ id, name: id }));
let s = createInitialState(opps, 2000, 'Human');
s.players[0].isAI = true;
let violations = 0, rolls = 0, sevenOuts = 0, points = 0, propHits = 0;
const seen = new Set();
for (let i = 0; i < 20000; i++) {
for (let pi = 0; pi < s.players.length; pi++) {
if (s.players[pi].chips + totalAtRisk(s.players[pi]) < 50) s.players[pi].chips += 2000; // rebuy
for (const spec of chooseBets(s.players[pi], s, rng)) s = placeBet(s, pi, spec);
for (const o of chooseOdds(s.players[pi], s)) s = addOdds(s, pi, o.betId, o.amount);
}
for (const p of s.players) for (const b of p.bets) {
seen.add(b.type);
if (b.amount <= 0 || b.oddsAmount < 0 || b.oddsAmount > Math.max(0, maxOddsFor(b, s))) violations++;
}
const before = s.players.map((p) => p.chips + totalAtRisk(p));
s = clearLastDeltas(rollDice(s, rng));
const r = resolveRoll(s);
s = r.state;
rolls++;
if (r.sevenOut) sevenOuts++;
if (r.pointEstablished) points++;
propHits += r.payouts.filter((p) => ONE_ROLL.has(p.betType) && p.result === 'win').length;
s.players.forEach((p, pi) => {
const after = p.chips + totalAtRisk(p);
if (after - before[pi] !== p.lastDelta) violations++;
if (p.chips < 0) violations++;
});
}
ok('no conservation / cap violations', violations === 0, `${violations}`);
ok('shooter rotated', sevenOuts > 1000, `${sevenOuts}`);
ok('points were set', points > 2000, `${points}`);
ok('props got hit', propHits > 50, `${propHits}`);
for (const t of [BET.PASS, BET.DONT_PASS, BET.COME, BET.DONT_COME, BET.FIELD, BET.PLACE, BET.HARD, BET.LAY, BET.CE, BET.YO, BET.ANY_CRAPS]) {
ok(`AI uses ${t}`, seen.has(t));
}
}
// ── 5. Source lint ───────────────────────────────────────────────────────────
section('Source lint');
{
const logic = readFileSync(new URL('../src/games/craps/CrapsLogic.js', import.meta.url), 'utf8');
ok('logic is Phaser-free', !/from 'phaser'/.test(logic));
for (const f of ['CrapsTable.js', 'CrapsDice.js', 'CrapsAI.js']) {
const src = readFileSync(new URL(`../src/games/craps/${f}`, import.meta.url), 'utf8');
ok(`${f} is Phaser-free`, !/from 'phaser'/.test(src));
}
const game = readFileSync(new URL('../src/games/craps/CrapsGame.js', import.meta.url), 'utf8');
ok('no hand-built Rectangle hit areas', !/new Phaser\.Geom\.Rectangle\(/.test(game));
ok('no setInteractive on containers', !/add\.container\([^)]*\)[^;]*setInteractive/.test(game));
ok('felt clicks go through table-space hit-testing', /hitZone\(x, y\)/.test(game));
ok('uses the shared dock + chip stacks', /new CasinoDock\(/.test(game) && /makeChipStack\(/.test(game));
}
// ── 6. Table geometry ────────────────────────────────────────────────────────
section('Table geometry');
{
const inRect = (pt, r, eps = 1e-9) => pt.u >= r.u0 - eps && pt.u <= r.u1 + eps && pt.v >= r.v0 - eps && pt.v <= r.v1 + eps;
const all = Object.values(ZONES).flatMap((z) => z.rects.map((r) => ({ key: z.key, r })));
for (const { key, r } of all) {
const corners = [[r.u0, r.v0], [r.u1, r.v0], [r.u0, r.v1], [r.u1, r.v1]];
ok(`${key}: on the felt`, corners.every(([u, v]) => inTub(u, v)));
ok(`${key}: not hidden under the near rail`, r.v1 <= NEAR_VISIBLE_V);
const c = { u: (r.u0 + r.u1) / 2, v: (r.v0 + r.v1) / 2 };
ok(`${key}: centre hit-tests to itself`, hitZoneUV(c.u, c.v) === key, hitZoneUV(c.u, c.v));
const a = P.project(r.u0, r.v0), b = P.project(r.u1, r.v1);
ok(`${key}: big enough to click (≥ 24px)`, Math.abs(b.x - a.x) >= 24 && Math.abs(b.y - a.y) >= 20, `${(b.x - a.x).toFixed(0)}×${(b.y - a.y).toFixed(0)}`);
}
let overlaps = 0;
for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {
const A = all[i].r, B = all[j].r;
const ou = Math.min(A.u1, B.u1) - Math.max(A.u0, B.u0), ov = Math.min(A.v1, B.v1) - Math.max(A.v0, B.v0);
if (ou > 1e-6 && ov > 1e-6 && all[i].key !== all[j].key) { overlaps++; ok(`${all[i].key} ∩ ${all[j].key}`, false); }
}
ok('no two zones overlap', overlaps === 0);
// Every bet type maps to a zone the player can click.
for (const type of Object.values(BET)) {
for (const n of NUMBERED[type] ?? [null]) ok(`${type}${n ?? ''} has a zone`, !!zoneKeyFor(type, n));
}
// Lane spots sit inside their zone, for every seat / crowding.
const laneZone = (k) => {
if (k.startsWith('comept')) return ZONES[`place${k.slice(6)}`];
return ZONES[k];
};
for (const [k, L] of Object.entries(LANES)) {
const z = laneZone(k);
ok(`lane ${k} has a zone`, !!z);
if (!z) continue;
const pts = [];
if (L.kind === 'flow') for (let n = 1; n <= 7; n++) for (let i = 0; i < n; i++) pts.push(laneSpot(k, { index: i, count: n }));
else for (const seat of SLOT_ORDER) pts.push(laneSpot(k, { seat }));
ok(`lane ${k}: every spot inside ${z.key}`, pts.every((p) => z.rects.some((r) => inRect(p, r))));
}
// Seat-fixed lanes give each seat its own spot.
for (const k of ['pass', 'field', 'come', 'dontpass', 'odds', 'ce']) {
const keys = new Set(SLOT_ORDER.map((seat) => JSON.stringify(laneSpot(k, { seat }))));
ok(`lane ${k}: 7 distinct seat spots`, keys.size === 7);
}
// Bets → lanes
const sample = [
{ type: 'pass' }, { type: 'dontpass' }, { type: 'come' }, { type: 'come', comePoint: 9 }, { type: 'dontcome' },
{ type: 'dontcome', comePoint: 4 }, { type: 'field' }, { type: 'place', number: 6 }, { type: 'buy', number: 10 },
{ type: 'lay', number: 5 }, { type: 'big', number: 8 }, { type: 'hard', number: 4 }, { type: 'any7' }, { type: 'horn' },
{ type: 'ce' }, { type: 'yo' }, { type: 'aces' }, { type: 'acedeuce' }, { type: 'boxcars' }, { type: 'anycraps' },
];
for (const b of sample) ok(`${b.type}${b.number ?? b.comePoint ?? ''} has a lane`, !!LANES[laneForBet(b)]);
// Seats
ok('seat names: human first, fill order after', seatNames(6).join() === ['H', ...FILL_ORDER].join());
const portraits = seatNames(6).slice(1).map((n) => ({ n, ...seatPortrait(n) }));
for (const p of portraits) {
ok(`${p.n}: portrait on screen`, p.x - p.r >= 0 && p.x + p.r <= 1920 && p.y - p.r >= 0);
ok(`${p.n}: portrait clear of the dock`, p.y + p.r + 22 <= DOCK.y, `${p.y + p.r}`);
ok(`${p.n}: portrait clear of the history board`, p.x + p.r < BOARD.x || p.y - p.r > BOARD.y + BOARD.h);
ok(`${p.n}: portrait clear of the Leave button`, !(p.x - p.r < 160 && p.y - p.r < 72));
}
for (let i = 0; i < portraits.length; i++) for (let j = i + 1; j < portraits.length; j++) {
const a = portraits[i], b = portraits[j];
ok(`${a.n}/${b.n}: portraits don't overlap`, Math.hypot(a.x - b.x, a.y - b.y) > a.r + b.r + 60);
}
for (const n of Object.keys(SEATS)) {
const { u, v } = railUV(n);
ok(`${n}: chips sit on the rail, not the felt`, !inTub(u, v) && inTub(u, v, TUB.RW));
const r = railPose(n);
ok(`${n}: rail stack on screen`, r.x > 20 && r.x < 1900 && r.y > 60 && r.y < DOCK.y);
const o = throwOrigin(n);
ok(`${n}: throw starts over the felt`, inTub(o.u, o.v));
}
// Furniture
for (let i = 0; i < 5; i++) {
const o = offerSpot(i);
ok(`offer die ${i} on visible felt, below the prop box`, inTub(o.u, o.v) && o.v <= NEAR_VISIBLE_V && o.v > PROP.v1 && !hitZoneUV(o.u, o.v));
}
for (const n of BOX_NUMS) ok(`puck ON spot inside place${n}`, ZONES[`place${n}`].rects.some((r) => inRect(puckOnUV(n), r)));
ok('puck OFF spot inside the Don\'t Come box', ZONES.dontcome.rects.some((r) => inRect(puckOffUV(), r)));
ok('board on screen', BOARD.x + BOARD.w <= 1920 && BOARD.y >= 0);
{
const inCard = (p, pad = 0) => p.x > RESULT.x - pad && p.x < RESULT.x + RESULT.w + pad && p.y > RESULT.y - pad && p.y < RESULT.y + RESULT.h + pad;
ok('results card on screen, above the dock', RESULT.x + RESULT.w <= 1920 && RESULT.y + RESULT.h <= DOCK.y - 4);
ok('results card clear of the history board', RESULT.y > BOARD.y + BOARD.h);
const L = LANDING;
ok('landing area clear of the results card', [[L.u0, L.v0], [L.u1, L.v0], [L.u1, L.v1], [L.u0, L.v1]].every(([u, v]) => !inCard(P.project(u, v))));
for (const z of Object.values(ZONES)) for (const r of z.rects) {
ok(`${z.key} clear of the results card`, [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]].every(([u, v]) => !inCard(P.project(u, v))));
}
for (let i = 0; i < 5; i++) ok(`offer die ${i} clear of the results card`, !inCard(P.project(offerSpot(i).u, offerSpot(i).v), 24));
for (const n of seatNames(6).slice(1)) { const p = seatPortrait(n); ok(`${n} portrait clear of the results card`, !inCard(p, p.r)); }
}
ok('board below the music player (top ~76px on the right)', BOARD.y >= 80);
{
// right rail's outer edge where the board's bottom-left corner sits
let near = null;
for (let v = -0.1; v <= 1.1; v += 0.001) {
const p = lift(1 + TUB.RW, v, TUB.H);
if (!near || Math.abs(p.y - (BOARD.y + BOARD.h)) < Math.abs(near.y - (BOARD.y + BOARD.h))) near = p;
}
ok('board clear of the right rail', BOARD.x - near.x >= 8, `${(BOARD.x - near.x).toFixed(0)}px`);
}
{
const c0 = CALL.x - CALL.maxW / 2, c1 = CALL.x + CALL.maxW / 2;
ok('stickman banner clear of the history board', c1 < BOARD.x);
for (const n of ['F1', 'F2', 'F3']) {
const p = seatPortrait(n);
const plateEnd = p.x + p.r + 12 + 120; // name / bankroll plate to the right
ok(`stickman banner clear of ${n}'s plate`, plateEnd < c0 || p.x - p.r > c1, `${plateEnd.toFixed(0)} vs ${c0}`);
}
}
ok('landing area on the felt', inTub(LANDING.u0, LANDING.v0) && inTub(LANDING.u1, LANDING.v1));
}
// ── 7. Dice throws ───────────────────────────────────────────────────────────
section('Dice throws (300 seeded throws)');
{
const rng = mulberry32(777);
let wrongFace = 0, outside = 0, close = 0, noWall = 0, maxDur = 0, maxTries = 0, underCard = 0;
for (let i = 0; i < 300; i++) {
const seat = seatNames(6)[i % 7];
const faces = [1 + (i % 6), 1 + ((i * 5 + 2) % 6)];
const plan = simulateThrow(throwOrigin(seat), faces, rng);
maxDur = Math.max(maxDur, plan.duration);
maxTries = Math.max(maxTries, plan.tries);
plan.dice.forEach((d, k) => {
const last = d.frames[d.frames.length - 1];
if (topFace(last.q) !== faces[k]) wrongFace++;
if (!(last.u >= LANDING.u0 - 0.04 && last.u <= LANDING.u1 && last.v >= LANDING.v0 && last.v <= LANDING.v1)) outside++;
const sp = P.project(last.u, last.v);
if (sp.x > RESULT.x - 24 && sp.y > RESULT.y - 12) underCard++;
if (!d.hitWall) noWall++;
if (!d.frames.every((f) => inTub(f.u, f.v) && f.h >= 0 && Number.isFinite(f.u))) outside++;
});
const [a, b] = plan.dice.map((d) => d.frames[d.frames.length - 1]);
if (Math.hypot((a.u - b.u) * VIEW.halfW, (a.v - b.v) * VIEW.halfW * 4 / 3) < DIE.size * 1.2) close++;
}
ok('every die lands showing the rolled number', wrongFace === 0, `${wrongFace}`);
ok('dice stay in the tub and land in the landing area', outside === 0, `${outside}`);
ok('every die hits the back wall', noWall === 0, `${noWall}`);
ok('no die comes to rest under the results card', underCard === 0, `${underCard}`);
ok('dice never come to rest on top of each other', close === 0, `${close}`);
ok('throws last under 3.6 s', maxDur < 3.6, maxDur.toFixed(2));
for (let f = 1; f <= 6; f++) ok(`restingQ shows ${f}`, topFace(restingQ(f, f * 0.7)) === f);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);