From a103c9ed74eedcc76a059c7920ed1f273f2c7f3b Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Mon, 23 Nov 2026 20:10:11 -0700 Subject: [PATCH] Refactor casino tables to shared perspective geometry and art kit - Extract table layout into Phaser-free *Table.js modules so headless verify scripts can test projection, hit-testing, payouts, and scoreboard roads - Add shared casino art pipeline (CasinoArt/CasinoCards/CasinoChips/CasinoDock) that bakes felt, rail, cards, chips, and HUD dock from one perspective model - Replace per-game hand-drawn tables, betting UI, and chip rendering in Baccarat, Blackjack, and Pai Gow with the shared kit plus game-specific markings - Add keyboard shortcuts, rebet controls, and a Baccarat bead plate/big road scoreboard - Extend verifyBaccarat/verifyBlackjack/verifyPaiGowPoker with layout, overlap, and source-lint checks --- src/games/baccarat/BaccaratArt.js | 83 + src/games/baccarat/BaccaratGame.js | 1588 ++++++++------- src/games/baccarat/BaccaratRoads.js | 68 + src/games/baccarat/BaccaratTable.js | 116 ++ src/games/blackjack/BlackjackArt.js | 65 + src/games/blackjack/BlackjackGame.js | 2387 +++++++++++------------ src/games/blackjack/BlackjackTable.js | 109 ++ src/games/paigow/PaiGowArt.js | 70 + src/games/paigow/PaiGowPokerGame.js | 2550 +++++++++---------------- src/games/paigow/PaiGowTable.js | 134 ++ src/ui/CasinoChips.js | 398 ++++ src/ui/casino/CasinoArt.js | 996 ++++++++++ src/ui/casino/CasinoCards.js | 184 ++ src/ui/casino/CasinoDock.js | 164 ++ src/ui/casino/CasinoGeometry.js | 122 ++ tools/verifyBaccarat.js | 169 ++ tools/verifyBlackjack.js | 163 ++ tools/verifyPaiGowPoker.js | 85 + 18 files changed, 5781 insertions(+), 3670 deletions(-) create mode 100644 src/games/baccarat/BaccaratArt.js create mode 100644 src/games/baccarat/BaccaratRoads.js create mode 100644 src/games/baccarat/BaccaratTable.js create mode 100644 src/games/blackjack/BlackjackArt.js create mode 100644 src/games/blackjack/BlackjackTable.js create mode 100644 src/games/paigow/PaiGowArt.js create mode 100644 src/games/paigow/PaiGowTable.js create mode 100644 src/ui/CasinoChips.js create mode 100644 src/ui/casino/CasinoArt.js create mode 100644 src/ui/casino/CasinoCards.js create mode 100644 src/ui/casino/CasinoDock.js create mode 100644 src/ui/casino/CasinoGeometry.js create mode 100644 tools/verifyBaccarat.js create mode 100644 tools/verifyBlackjack.js diff --git a/src/games/baccarat/BaccaratArt.js b/src/games/baccarat/BaccaratArt.js new file mode 100644 index 0000000..379dfed --- /dev/null +++ b/src/games/baccarat/BaccaratArt.js @@ -0,0 +1,83 @@ +// Baccarat table art: burgundy felt, three curved betting boxes per seat +// (PLAYER / BANKER / TIE), and the dealer's PLAYER and BANKER card boxes. + +import { prepareCasinoArt, bakeCasinoTable, poly, rr, drawArcText } from '../../ui/casino/CasinoArt.js'; +import { + VIEW, SEAT_ANGLES, BANDS, BET_TYPES, BET_META, boxOutline, handBoxRect, handCardPose, + CARD_W, CARD_H, FELT_TEXT, TRAY, SHOE, DISCARD, PLACARD, +} from './BaccaratTable.js'; + +function hexToRgba(hex, a) { + const n = parseInt(hex.slice(1), 16); + return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`; +} + +function drawMarkings(ctx) { + SEAT_ANGLES.forEach((theta, seat) => { + for (const type of BET_TYPES) { + const meta = BET_META[type]; + poly(ctx, boxOutline(seat, type)); + ctx.fillStyle = hexToRgba(meta.felt, 0.09); + ctx.fill(); + ctx.lineWidth = 2.5; + ctx.strokeStyle = hexToRgba(meta.felt, 0.85); + ctx.stroke(); + poly(ctx, boxOutline(seat, type, 0.012)); + ctx.lineWidth = 1; + ctx.strokeStyle = 'rgba(242,234,216,0.22)'; + ctx.stroke(); + const { r0, r1 } = BANDS[type]; + drawArcText(ctx, { + text: meta.label, r: (r0 + r1) / 2, size: type === 'tie' ? 15 : 16, color: meta.felt, + alpha: 0.9, spacing: 1.08, bold: true, centerDeg: theta, + }); + } + }); + + for (const side of ['player', 'banker']) { + const meta = BET_META[side]; + const b = handBoxRect(side); + rr(ctx, b.x - b.w / 2, b.y - b.h / 2, b.w, b.h, 12 * b.s); + ctx.fillStyle = hexToRgba(meta.felt, 0.08); + ctx.fill(); + ctx.lineWidth = 2.5; + ctx.strokeStyle = hexToRgba(meta.felt, 0.8); + ctx.stroke(); + ctx.save(); + ctx.translate(b.x, b.y); + ctx.scale(b.s, b.s * VIEW.squash); + ctx.font = 'bold 30px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = hexToRgba(meta.felt, 0.55); + ctx.fillText(meta.label, 0, 0); + ctx.restore(); + + // third-card spot (sideways) + const t = handCardPose(side, 2); + ctx.save(); + ctx.translate(t.x, t.y); + ctx.rotate(t.rot); + ctx.scale(t.s, t.s * VIEW.squash); + ctx.setLineDash([8, 6]); + rr(ctx, -CARD_W / 2 - 6, -CARD_H / 2 - 6, CARD_W + 12, CARD_H + 12, 10); + ctx.lineWidth = 2 / t.s; + ctx.strokeStyle = hexToRgba(meta.felt, 0.6); + ctx.stroke(); + ctx.setLineDash([]); + ctx.restore(); + } +} + +export async function prepareBaccaratArt(scene) { + await prepareCasinoArt(scene); + bakeCasinoTable(scene, 'bac-table', { + felt: '#5c1020', + markings: drawMarkings, + text: FELT_TEXT, + tray: TRAY, + shoe: SHOE, + discard: DISCARD, + placard: PLACARD, + }); +} diff --git a/src/games/baccarat/BaccaratGame.js b/src/games/baccarat/BaccaratGame.js index b7b2edb..17f6d89 100644 --- a/src/games/baccarat/BaccaratGame.js +++ b/src/games/baccarat/BaccaratGame.js @@ -2,63 +2,44 @@ import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { Modal } from '../../ui/Modal.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { createOpponentPortrait } from '../../ui/Portrait.js'; import { api } from '../../services/api.js'; import { playSound, playChipBet, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { makeChipStack, throwChip, throwStack, settleStack } from '../../ui/CasinoChips.js'; +import { CasinoDock } from '../../ui/casino/CasinoDock.js'; +import { CardSkin } from '../../ui/casino/CasinoCards.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; import { BET, buildShoe, handValue, createInitialState, prepareRound, applyBet, dealCoup, resolveRound, } from './BaccaratLogic.js'; import { chooseBet, chooseBetType } from './BaccaratAI.js'; +import { + VIEW, project, boxCenter, boxOutline, hitBox, seatPortrait, handCenter, handCardPose, handBoxRect, + BET_META, DISPLAY_ORDER, SHOE, DISCARD, TRAY, DOCK, READOUT, BOARD, boardSize, TOTAL_BADGE_DY, +} from './BaccaratTable.js'; +import { counts, beadPlate, bigRoadWindow } from './BaccaratRoads.js'; +import { prepareBaccaratArt } from './BaccaratArt.js'; -// ─── Layout ─────────────────────────────────────────────────────────────────── +// ─── Layout / tuning ────────────────────────────────────────────────────────── +// Positions come from BaccaratTable.js (shared casino perspective); the art is +// baked by BaccaratArt.js + the shared casino kit. This file is flow + animation. const CX = GAME_WIDTH / 2; -const CARD_W = 90; -const CARD_H = 126; -const CARD_R = 8; -const CARD_SPREAD = 34; // horizontal offset between fanned cards - -// Central Player / Banker hand columns. -const HAND_Y = 470; -const PLAYER_X = CX - 235; -const BANKER_X = CX + 235; -const HEADER_Y = 352; -const TOTAL_Y = 572; - -// Where flying cards originate from (the shoe). -const SHOE_X = 1660; -const SHOE_Y = 180; - -// 7 seats: seat 0 (human) anchored bottom-centre, 6 opponents fanned around the -// oval. Each seat has a portrait plus a felt bet spot where its chip sits. -const SEAT_POS = [ - { betX: CX, betY: 772, portraitR: 72, portraitX: CX - 250, portraitY: 882 }, // 0 human - { betX: 1330, betY: 700, portraitR: 58, portraitX: 1600, portraitY: 800 }, // 1 right-bottom - { betX: 590, betY: 700, portraitR: 58, portraitX: 320, portraitY: 800 }, // 2 left-bottom - { betX: 1470, betY: 600, portraitR: 58, portraitX: 1805, portraitY: 610 }, // 3 right-mid - { betX: 450, betY: 600, portraitR: 58, portraitX: 115, portraitY: 610 }, // 4 left-mid - { betX: 1390, betY: 478, portraitR: 58, portraitX: 1705, portraitY: 345 }, // 5 right-top - { betX: 530, betY: 478, portraitR: 58, portraitX: 215, portraitY: 345 }, // 6 left-top -]; - -// Reveal results top-right then clockwise. -const DISPLAY_ORDER = [5, 3, 1, 0, 2, 4, 6]; - -const CHIP_COLORS = { 5: 0xe05c5c, 25: 0x5cb85c, 50: 0x4a90d9, 100: 0x2c2c2c }; -const CHIP_TEXT_COLORS = { 5: '#ffffff', 25: '#ffffff', 50: '#ffffff', 100: '#ffffff' }; -const CHIP_AMOUNTS = [5, 25, 50, 100]; +const SQ = VIEW.squash; +const DOCK_Y = DOCK.y + DOCK.h / 2; +const MIN_BET = 5; const MAX_BET = 500; +const CHIP_AMOUNTS = [5, 25, 50, 100]; +const STACK_SIZE = 54; +const TYPES = [BET.PLAYER, BET.BANKER, BET.TIE]; +const TYPE_KEYS = { p: BET.PLAYER, b: BET.BANKER, t: BET.TIE }; -// Bet-type styling (shared by the pills and the felt chips). -const BET_META = { - [BET.PLAYER]: { label: 'Player', short: 'P', color: 0x4a90d9, hex: '#4a90d9' }, - [BET.BANKER]: { label: 'Banker', short: 'B', color: 0xe05c5c, hex: '#e05c5c' }, - [BET.TIE]: { label: 'Tie', short: 'T', color: 0x5cb85c, hex: '#5cb85c' }, +const D = { + bg: -2, playfield: -1, table: 0, feltHi: 2, cards: 10, stacks: 12, flying: 22, badges: 24, + dock: 26, ui: 30, dockUi: 32, prompt: 38, readout: 44, modal: 50, }; -const D = { bg: -1, table: 0, cards: 10, chips: 20, ui: 30, modal: 50 }; - // Total-reveal ("Equation Ribbon") sequence — cinematic, no-skip. All tunable. const TALLY = { cardLift: 16, // px a card rises while spotlighted @@ -67,12 +48,12 @@ const TALLY = { dropMs: 480, // tens digit fall + ones digit slide to badge badgeHoldMs: 820, // hold on the final single-digit badge betweenHandsMs: 480, // gap between Player and Banker walkthroughs - ribbonY: 624, // readout-panel centre, below the cards (cards bottom ≈533) - panelW: 400, - panelH: 170, - badgeR: 34, + badgeR: 20, }; +const SQUEEZE_FIRST = { peekMs: 650, holdMs: 450, peelMs: 700 }; +const SQUEEZE_NEXT = { peekMs: 420, holdMs: 260, peelMs: 520 }; + // ─── Scene ──────────────────────────────────────────────────────────────────── export default class BaccaratGame extends Phaser.Scene { constructor() { super('BaccaratGame'); } @@ -86,279 +67,286 @@ export default class BaccaratGame extends Phaser.Scene { async create() { new MusicPlayer(this, this.cache.json.get('music').tracks); - this.shoe = buildShoe(); + this.shoe = []; this.gs = null; - this.animating = false; + this.busy = false; this.pendingBet = 0; - this.selectedBetType = BET.PLAYER; + this.selectedType = BET.PLAYER; + this.lastBet = 0; + this.lastType = BET.PLAYER; this.portraits = []; - this.playerCardGraphics = []; - this.bankerCardGraphics = []; - this.betGraphics = {}; // seat → Phaser.Container - this.chipTxts = {}; + this.cards = new Map(); // 'player:i' / 'banker:i' → card container + this.stacks = {}; // seat → chip stack + this.settled = new Set(); + this.decor = []; // glows, totals, banners — cleared each round + this.tallyObjs = []; + this.totalBadges = {}; + this.history = []; // scoreboard, resets with each new shoe this.nameTxts = {}; - this.bettingUIGroup = []; - this.betTypePills = []; - this.chipBtnGraphics = []; - this.betDisplayText = null; - this.balanceText = null; - this.outcomeBanner = null; - this.tallyObjs = []; // transient objects for the total-reveal sequence - - this.events.once('shutdown', () => this.clearTally()); + this.chipTxts = {}; + this.dockMode = null; + this.hoverType = null; this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); this.buildPlayfield(); - this.buildTable(); - this.buildTableMarkings(); - this.buildCentralAreas(); - this.buildSeats(); - this.buildBettingUI(); - new Button(this, 80, GAME_HEIGHT - 44, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 140, fontSize: 20, - }); + await prepareBaccaratArt(this); + if (!this.sys.isActive()) return; + this.skin = new CardSkin(this, this.cardBack, { depth: D.cards }); + + this.add.image(0, 0, 'bac-table').setOrigin(0, 0).setDepth(D.table); + this.buildDealerArea(); + this.buildFeltInput(); + this.buildSeats(); + this.buildDock(); + this.buildScoreboard(); + + new Button(this, 84, 44, 'Leave', () => this.scene.start('GameMenu'), { + variant: 'ghost', width: 140, height: 48, fontSize: 20, + }).setDepth(D.ui); + + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); await this.loadPlayerChips(); - this.initGame(); + if (!this.sys.isActive()) return; + this.gs = createInitialState(this.opponents, this._playerChips); + this.startNewRound(); } - // ── Playfield background ───────────────────────────────────────────────── + wait(ms) { return new Promise(res => this.time.delayedCall(ms, res)); } + + tweenP(cfg) { + return new Promise(res => { + this.tweens.add({ ...cfg, onComplete: (...a) => { cfg.onComplete?.(...a); res(); } }); + }); + } + + alive() { return this.sys.isActive(); } + + // ── Static scenery ───────────────────────────────────────────────────────── buildPlayfield() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT) - .setDepth(D.bg + 1); + this.add.image(CX, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.playfield); } } - // ── Table ───────────────────────────────────────────────────────────────── - buildTable() { - const g = this.add.graphics().setDepth(D.table); - g.fillStyle(0x1a5c2a, 1); - g.fillEllipse(CX, 540, 1500, 700); - g.lineStyle(8, 0x2e7d32, 1); - g.strokeEllipse(CX, 540, 1500, 700); - g.lineStyle(3, 0x4caf50, 0.4); - g.strokeEllipse(CX, 540, 1440, 640); + buildDealerArea() { + this.add.text(CX, 52, 'Baccarat', { + fontFamily: 'Righteous', fontSize: '48px', color: COLORS.textHex, + shadow: { offsetX: 0, offsetY: 3, color: '#000000', blur: 10, fill: true }, + }).setOrigin(0.5).setDepth(D.ui); + const shoe = project(SHOE.u, SHOE.v); + this.shoePos = { x: shoe.x - 66 * shoe.s, y: shoe.y - 4 * shoe.s, s: shoe.s * 0.9 }; + const disc = project(DISCARD.u, DISCARD.v); + this.discardPos = { x: disc.x, y: disc.y - 6 * disc.s, s: disc.s * 0.85 }; + const tray = project((TRAY.u0 + TRAY.u1) / 2, (TRAY.v0 + TRAY.v1) / 2); + this.trayPos = { x: tray.x, y: tray.y, s: tray.s }; } - // ── Felt markings: bet spots + curved payout lettering ───────────────────── - buildTableMarkings() { - const g = this.add.graphics().setDepth(D.table + 1); - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const pos = SEAT_POS[seat]; - g.lineStyle(2, 0xffffff, 0.5); - g.strokeCircle(pos.betX, pos.betY, 32); - } - - this.drawArcText('BANKER PAYS 1 TO 1', CX, 642, 760, { - fontSize: 26, color: COLORS.goldHex, bold: true, advanceFactor: 0.98, - }); - this.drawArcText('5% COMMISSION ON BANKER · TIE PAYS 8 TO 1', CX, 694, 720, { - fontSize: 18, color: COLORS.mutedHex, advanceFactor: 0.86, - }); - } - - // Draws a string along a downward-bulging arc, glyph by glyph. - drawArcText(text, centerX, baseY, radius, opts = {}) { - const fontSize = opts.fontSize ?? 24; - const anglePer = ((opts.advanceFactor ?? 0.92) * fontSize) / radius; - const cy = baseY - radius; - const start = -anglePer * (text.length - 1) / 2; - const style = { - fontFamily: opts.fontFamily ?? '"Julius Sans One"', - fontSize: `${fontSize}px`, - color: opts.color ?? COLORS.textHex, - ...(opts.bold ? { fontStyle: 'bold' } : {}), + // Clicking your own PLAYER / BANKER / TIE box on the felt picks the bet. + // A full-screen zone under everything else; hit-testing is exact (table space). + buildFeltInput() { + this.boxHi = this.add.graphics().setDepth(D.feltHi); + const zone = this.add.zone(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT).setDepth(D.table + 1).setInteractive(); + const humanBox = (p) => { + const hit = hitBox(p.worldX, p.worldY); + return hit && hit.seat === 0 ? hit.type : null; }; - const depth = opts.depth ?? (D.table + 1); - for (let i = 0; i < text.length; i++) { - const ch = text[i]; - if (ch === ' ') continue; - const a = start + i * anglePer; - this.add.text(centerX + radius * Math.sin(a), cy + radius * Math.cos(a), ch, style) - .setOrigin(0.5) - .setRotation(-a) - .setDepth(depth); - } + zone.on('pointermove', (p) => { + const t = this.dockMode === 'bet' ? humanBox(p) : null; + if (t !== this.hoverType) { + this.hoverType = t; + this.input.setDefaultCursor(t ? 'pointer' : 'default'); + this.drawBoxHighlight(); + } + }); + zone.on('pointerout', () => { + this.hoverType = null; + this.input.setDefaultCursor('default'); + this.drawBoxHighlight(); + }); + zone.on('pointerdown', (p) => { + const t = humanBox(p); + if (t) this.selectBetType(t); + }); + this.events.once('shutdown', () => this.input.setDefaultCursor('default')); } - // ── Central Player / Banker hand areas ────────────────────────────────────── - buildCentralAreas() { - this.add.text(CX, 60, 'Baccarat', { - fontFamily: 'Righteous', fontSize: '52px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - // Winner glow rectangles (hidden until a coup resolves). - this.playerGlow = this.add.graphics().setDepth(D.table + 2).setVisible(false); - this.bankerGlow = this.add.graphics().setDepth(D.table + 2).setVisible(false); - for (const [glow, hx] of [[this.playerGlow, PLAYER_X], [this.bankerGlow, BANKER_X]]) { - glow.fillStyle(COLORS.accent, 0.18); - glow.fillRoundedRect(hx - 130, HAND_Y - 95, 260, 200, 16); - glow.lineStyle(4, COLORS.accent, 0.9); - glow.strokeRoundedRect(hx - 130, HAND_Y - 95, 260, 200, 16); - } - - const mkHeader = (x, text, hex) => { - const t = this.add.text(x, HEADER_Y, text, { - fontFamily: 'Righteous', fontSize: '34px', color: hex, - }).setOrigin(0.5).setDepth(D.ui); - const pill = this.add.rectangle(x, HEADER_Y, t.width + 40, t.height + 14, 0x000000, 0.6).setDepth(D.ui - 1); - this.children.moveBelow(pill, t); + drawBoxHighlight() { + const g = this.boxHi; + g.clear(); + if (this.dockMode !== 'bet') return; + const draw = (type, fillA, lineA, width) => { + const meta = BET_META[type]; + const pts = boxOutline(0, type); + g.fillStyle(meta.color, fillA); + g.lineStyle(width, 0xf5d020, lineA); + g.beginPath(); + pts.forEach((p, i) => (i ? g.lineTo(p.x, p.y) : g.moveTo(p.x, p.y))); + g.closePath(); + g.fillPath(); + g.strokePath(); }; - mkHeader(PLAYER_X, 'PLAYER', BET_META[BET.PLAYER].hex); - mkHeader(BANKER_X, 'BANKER', BET_META[BET.BANKER].hex); - - this.playerTotalTxt = this.add.text(PLAYER_X, TOTAL_Y, '', { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - this.bankerTotalTxt = this.add.text(BANKER_X, TOTAL_Y, '', { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); + draw(this.selectedType, 0.22, 0.95, 3); + if (this.hoverType && this.hoverType !== this.selectedType) draw(this.hoverType, 0.1, 0.5, 2); } - // ── Seat labels & portraits ─────────────────────────────────────────────── buildSeats() { - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const pos = SEAT_POS[seat]; - const active = seat === 0 ? true : seat <= this.opponents.length; - if (!active) continue; - - const name = seat === 0 ? 'You' : (this.opponents[seat - 1]?.name ?? ''); - const px = pos.portraitX ?? pos.betX; - const py = pos.portraitY ?? pos.betY; - const nameY = py + pos.portraitR + 18; + for (let seat = 1; seat <= 6; seat++) { + const opp = this.opponents[seat - 1]; + if (!opp) continue; + const pt = seatPortrait(seat); + const nameY = pt.y + pt.r + 18; const chipY = nameY + 24; - - this.nameTxts[seat] = this.add.text(px, nameY, name, { + this.nameTxts[seat] = this.add.text(pt.x, nameY, opp.name ?? '', { fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, }).setOrigin(0.5).setDepth(D.ui); - - this.chipTxts[seat] = this.add.text(px, chipY, '', { + this.chipTxts[seat] = this.add.text(pt.x, chipY, '', { fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, }).setOrigin(0.5).setDepth(D.ui); - - { - const rectW = Math.max(this.nameTxts[seat].width, 130) + 20; - const rectH = (chipY - nameY) + 36; - const bg = this.add.graphics().setDepth(D.ui - 1); - bg.fillStyle(0x000000, 0.60); - bg.fillRoundedRect(px - rectW / 2, (nameY + chipY) / 2 - rectH / 2, rectW, rectH, 6); - } - - if (seat === 0) { - this.portraits[seat] = createPlayerPortrait(this, px, py, pos.portraitR, D.ui, 'BaccaratGame'); - } else { - this.portraits[seat] = createOpponentPortrait(this, this.opponents[seat - 1], px, py, pos.portraitR, D.ui); - } + const rectW = Math.max(this.nameTxts[seat].width, 130) + 20; + const rectH = (chipY - nameY) + 36; + const bg = this.add.graphics().setDepth(D.ui - 1); + bg.fillStyle(0x000000, 0.6); + bg.fillRoundedRect(pt.x - rectW / 2, (nameY + chipY) / 2 - rectH / 2, rectW, rectH, 6); + this.portraits[seat] = createOpponentPortrait(this, opp, pt.x, pt.y, pt.r, D.ui); } } - // ── Betting UI (human only) ─────────────────────────────────────────────── - buildBettingUI() { - // Shifted right of centre so the panel clears the human portrait. - const panelCx = CX + 200; - const balanceY = GAME_HEIGHT - 186; - const pillY = GAME_HEIGHT - 128; - const chipY = GAME_HEIGHT - 60; - const panelW = 700, panelL = panelCx - panelW / 2; - const panelTop = GAME_HEIGHT - 208, panelH = 196; + buildDock() { + this.dock = new CasinoDock(this, { + sceneName: 'BaccaratGame', + portrait: seatPortrait(0), + depth: { dock: D.dock, ui: D.ui, dockUi: D.dockUi, prompt: D.prompt }, + chipAmounts: CHIP_AMOUNTS, chipX0: 470, chipDX: 88, chipSize: 74, + betPillX: 830, + keys: { + bet: '1–4 add chips · P / B / T pick a box · Space deal / rebet · R rebet · C clear', + next: 'Space next round · R rebet & deal', + }, + canChip: (amt) => this.chipAffordable(amt), + onChip: (amt) => this.onChipClick(amt), + }); + this.portraits[0] = this.dock.portrait; + this.nameTxts[0] = this.dock.nameTxt; + this.chipTxts[0] = this.dock.balanceTxt; - const panel = this.add.graphics().setDepth(D.ui); - panel.fillStyle(0x000000, 1); - panel.fillRoundedRect(panelL, panelTop, panelW, panelH, 18); - panel.lineStyle(3, COLORS.accent, 1); - panel.strokeRoundedRect(panelL, panelTop, panelW, panelH, 18); - this.bettingUIGroup.push(panel); - - // Bet-type pills - const types = [BET.PLAYER, BET.BANKER, BET.TIE]; - const pillW = 150, pillH = 50, pillGap = 16; - const totalW = types.length * pillW + (types.length - 1) * pillGap; - types.forEach((type, i) => { - const x = panelCx - totalW / 2 + i * (pillW + pillGap) + pillW / 2; + const btnOpts = { width: 112, height: 50, fontSize: 18, variant: 'ghost' }; + this.clearBtn = new Button(this, 1140, DOCK_Y, 'Clear', () => this.onClearBet(), btnOpts); + this.rebetBtn = new Button(this, 1262, DOCK_Y, 'Rebet', () => this.onRebet(1), btnOpts); + this.rebet2Btn = new Button(this, 1384, DOCK_Y, 'Rebet x2', () => this.onRebet(2), btnOpts); + this.dealBtn = new Button(this, 1524, DOCK_Y, 'Deal', () => this.onDealClick(), { width: 146, height: 56, fontSize: 24 }); + for (const b of [this.clearBtn, this.rebetBtn, this.rebet2Btn, this.dealBtn]) b.setDepth(D.dockUi); + this.typeBtns = {}; + TYPES.forEach((type, i) => { const meta = BET_META[type]; - const bg = this.add.rectangle(x, pillY, pillW, pillH, COLORS.panel) - .setStrokeStyle(3, COLORS.muted) - .setInteractive({ useHandCursor: true }) - .setDepth(D.ui + 1); - const txt = this.add.text(x, pillY, meta.label, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui + 2); - bg.on('pointerup', () => this.onBetTypeSelect(type)); - bg.on('pointerover', () => { if (this.selectedBetType !== type) bg.setStrokeStyle(3, COLORS.text); }); - bg.on('pointerout', () => { if (this.selectedBetType !== type) bg.setStrokeStyle(3, COLORS.muted); }); - this.betTypePills.push({ type, bg, txt, meta }); - this.bettingUIGroup.push(bg, txt); + const label = type === BET.TIE ? 'Tie' : meta.label[0] + meta.label.slice(1).toLowerCase(); + const b = new Button(this, 1678 + i * 104, DOCK_Y, label, () => this.selectBetType(type), { + width: 96, height: 44, fontSize: 16, variant: 'ghost', bgHover: meta.color, + }).setDepth(D.dockUi); + this.typeBtns[type] = b; }); - - // Chip buttons - const chipStartX = panelCx - 290; - CHIP_AMOUNTS.forEach((amt, i) => { - const bx = chipStartX + i * 72; - const container = this.add.container(bx, chipY).setDepth(D.ui + 1); - const g = this.add.graphics(); - g.lineStyle(3, 0xffffff, 0.4); - g.strokeCircle(0, 0, 28); - g.fillStyle(CHIP_COLORS[amt], 1); - g.fillCircle(0, 0, 28); - container.add(g); - container.setInteractive(new Phaser.Geom.Circle(0, 0, 28), Phaser.Geom.Circle.Contains); - container.on('pointerdown', () => this.onChipClick(amt)); - container.on('pointerover', () => container.setAlpha(0.8)); - container.on('pointerout', () => container.setAlpha(1)); - - const t = this.add.text(bx, chipY, `$${amt}`, { - fontFamily: '"Julius Sans One"', fontSize: '13px', - color: CHIP_TEXT_COLORS[amt], fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.ui + 2); - - this.bettingUIGroup.push(container, t); - this.chipBtnGraphics.push(container); - }); - - this.betDisplayText = this.add.text(panelCx - 10, chipY, 'Bet: $0', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui + 1); - - this.balanceText = this.add.text(panelCx, balanceY, '', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui + 1); - - const clearBtn = new Button(this, panelCx + 170, chipY, 'Clear', () => this.onClearBet(), { - width: 100, height: 50, fontSize: 18, variant: 'ghost', - }); - this.dealBtn = new Button(this, panelCx + 285, chipY, 'Deal', () => this.onDealClick(), { - width: 110, height: 50, fontSize: 20, - }); - this.dealBtn.setEnabled(false); - clearBtn.setDepth(D.ui + 1); - this.dealBtn.setDepth(D.ui + 1); - - this.bettingUIGroup.push(this.betDisplayText, this.balanceText, clearBtn, this.dealBtn); - this.refreshBetTypePills(); - this.hideBettingUI(); + this.dock.addToGroup('bet', this.clearBtn, this.rebetBtn, this.rebet2Btn, this.dealBtn, ...Object.values(this.typeBtns)); } - refreshBetTypePills() { - for (const pill of this.betTypePills) { - const sel = pill.type === this.selectedBetType; - pill.bg.setStrokeStyle(sel ? 4 : 3, sel ? pill.meta.color : COLORS.muted); - pill.bg.setFillStyle(sel ? pill.meta.color : COLORS.panel, sel ? 0.32 : 1); - pill.txt.setColor(sel ? pill.meta.hex : COLORS.textHex); + // mode: 'bet' | 'next' | 'wait' + setDockMode(mode, status = '') { + this.dockMode = mode; + this.dock.setMode(mode, mode === 'wait' ? status : ''); + if (mode === 'bet') { + for (const b of Object.values(this.typeBtns)) b.setEnabled(true); + this.updateBetDisplay(); + } else { + this.hoverType = null; + this.input.setDefaultCursor('default'); + } + this.drawBoxHighlight(); + } + + // ── Scoreboard ───────────────────────────────────────────────────────────── + buildScoreboard() { + const { w, h } = boardSize(); + ensureLeatherPanel(this, 'bac-board', w, h, { radius: 14 }); + this.add.image(BOARD.x, BOARD.y, 'bac-board').setOrigin(0, 0).setDepth(D.ui); + this.boardG = this.add.graphics().setDepth(D.ui + 1); + this.boardTitle = this.add.text(BOARD.x + BOARD.pad + 4, BOARD.y + 17, 'SCOREBOARD', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#d9b45a', + }).setOrigin(0, 0.5).setDepth(D.ui + 2); + this.boardCounts = this.add.text(BOARD.x + w - BOARD.pad - 4, BOARD.y + 17, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#f2ead8', + }).setOrigin(1, 0.5).setDepth(D.ui + 2); + this.beadTxts = []; + this.drawScoreboard(); + } + + drawScoreboard() { + const g = this.boardG; + const { cell, rows, beadCols, roadCols, pad, header } = BOARD; + const x0 = BOARD.x + pad, y0 = BOARD.y + header; + const roadX0 = x0 + beadCols * cell + pad; + g.clear(); + // LED grid wells + g.fillStyle(0x050403, 1); + g.fillRect(x0 - 2, y0 - 2, beadCols * cell + 4, rows * cell + 4); + g.fillRect(roadX0 - 2, y0 - 2, roadCols * cell + 4, rows * cell + 4); + g.lineStyle(1, 0xffffff, 0.06); + for (let c = 0; c <= beadCols; c++) g.lineBetween(x0 + c * cell, y0, x0 + c * cell, y0 + rows * cell); + for (let c = 0; c <= roadCols; c++) g.lineBetween(roadX0 + c * cell, y0, roadX0 + c * cell, y0 + rows * cell); + for (let r = 0; r <= rows; r++) { + g.lineBetween(x0, y0 + r * cell, x0 + beadCols * cell, y0 + r * cell); + g.lineBetween(roadX0, y0 + r * cell, roadX0 + roadCols * cell, y0 + r * cell); + } + + // Bead plate: solid discs with a letter + const beads = beadPlate(this.history, rows, beadCols); + beads.forEach((b, i) => { + const cx = x0 + b.col * cell + cell / 2, cy = y0 + b.row * cell + cell / 2; + g.fillStyle(BET_META[b.outcome].color, 1); + g.fillCircle(cx, cy, cell / 2 - 2); + let t = this.beadTxts[i]; + if (!t) { + t = this.add.text(0, 0, '', { fontFamily: '"Julius Sans One"', fontSize: '10px', color: '#ffffff', fontStyle: 'bold' }) + .setOrigin(0.5).setDepth(D.ui + 2); + this.beadTxts[i] = t; + } + t.setText(BET_META[b.outcome].short).setPosition(cx, cy + 0.5).setVisible(true); + }); + for (let i = beads.length; i < this.beadTxts.length; i++) this.beadTxts[i].setVisible(false); + + // Big road: hollow rings, ties as a green slash + for (const c of bigRoadWindow(this.history, rows, roadCols)) { + const cx = roadX0 + c.col * cell + cell / 2, cy = y0 + c.row * cell + cell / 2; + g.lineStyle(2.5, BET_META[c.outcome].color, 1); + g.strokeCircle(cx, cy, cell / 2 - 3); + if (c.ties > 0) { + g.lineStyle(2, BET_META[BET.TIE].color, 1); + g.lineBetween(cx - 5, cy + 5, cx + 5, cy - 5); + } + } + + const k = counts(this.history); + this.boardCounts.setText(`P ${k.player} B ${k.banker} T ${k.tie} · ${this.history.length} hands`); + } + + // ── Keyboard ─────────────────────────────────────────────────────────────── + onKey(e) { + if (!this.gs) return; + const k = (e.key ?? '').toLowerCase(); + if (this.dockMode === 'bet') { + if (k === ' ' || k === 'enter') { + if (this.pendingBet >= MIN_BET) this.onDealClick(); else this.onRebet(1); + } else if (k === 'r') this.onRebet(1); + else if (k === 'c' || k === 'backspace') this.onClearBet(); + else if (TYPE_KEYS[k]) this.selectBetType(TYPE_KEYS[k]); + else if (['1', '2', '3', '4'].includes(k)) this.onChipClick(CHIP_AMOUNTS[Number(k) - 1]); + } else if (this.dockMode === 'next') { + if (k === ' ' || k === 'enter') this.onNextRound(false); + else if (k === 'r') this.onNextRound(true); } } - showBettingUI() { - for (const o of this.bettingUIGroup) o.setVisible?.(true) || (o.visible = true); - } - hideBettingUI() { - for (const o of this.bettingUIGroup) o.setVisible?.(false) || (o.visible = false); - } - - // ── Chip balance ────────────────────────────────────────────────────────── + // ── Chip balance ─────────────────────────────────────────────────────────── async loadPlayerChips() { try { const { profile } = await api.get('/profile'); @@ -368,441 +356,531 @@ export default class BaccaratGame extends Phaser.Scene { } } - // ── Game init ───────────────────────────────────────────────────────────── - initGame() { - this.gs = createInitialState(this.opponents, this._playerChips); - this.startNewRound(); + async updateServerChips() { + const delta = this.gs.players[0].chipsWon ?? 0; + if (delta === 0) return; + try { + await api.post('/profile/chips/adjust', { delta }); + } catch { /* balance will resync next load */ } } - startNewRound() { - if (this.shoe.length < 32) this.shoe = buildShoe(); - playSound(this, SFX.CARD_SHUFFLE); - this.pendingBet = 0; - this.gs = prepareRound(this.gs); - this.clearTally(); - this.clearHandGraphics(); - this.playerGlow.setVisible(false); - this.bankerGlow.setVisible(false); - this.playerTotalTxt.setText(''); - this.bankerTotalTxt.setText(''); - if (this.outcomeBanner) { this.outcomeBanner.destroy(); this.outcomeBanner = null; } - this.renderAll(); - this.showBettingUI(); - this.updateBetDisplay(); - } - - // ── Render ──────────────────────────────────────────────────────────────── - renderAll() { - this.renderHands(); - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (p?.active) this.renderSeatInfo(seat); + // ── Round lifecycle ──────────────────────────────────────────────────────── + async startNewRound() { + this.setDockMode('wait', ''); + await this.sweepTable(); + if (this.shoe.length < 32) { + this.shoe = buildShoe(); + this.history = []; + this.drawScoreboard(); + await this.animateReshuffle(); } - this.renderBetChips(); + this.pendingBet = 0; + this.settled.clear(); + this.gs = prepareRound(this.gs); + this.renderSeatInfo(); + this.renderBetAreas(); + this.setDockMode('bet'); + this.startBettingPrompts(); } - renderHands() { - this.clearHandGraphics(); - const draw = (hand, centerX, store) => { - hand.forEach((card, i) => { - const x = this.cardX(centerX, i, hand.length); - const cont = this.add.container(x, HAND_Y).setDepth(D.cards); - this.drawCard(cont, card, true); - store.push(cont); + async sweepTable() { + this.clearTally(); + for (const o of this.decor) { this.tweens.killTweensOf(o); o.destroy(); } + this.decor = []; + this.totalBadges = {}; + for (const st of Object.values(this.stacks)) { + this.tweens.add({ targets: st, alpha: 0, duration: 200, onComplete: () => st.destroy() }); + } + this.stacks = {}; + const all = [...this.cards.values()]; + this.cards.clear(); + if (!all.length) return; + playSound(this, SFX.CARD_PLACE); + const d = this.discardPos; + all.forEach((c, i) => { + c.setDepth(D.flying); + this.tweens.add({ + targets: c, x: d.x + (Math.random() - 0.5) * 6, y: d.y, + rotation: (Math.random() - 0.5) * 0.08, scaleX: d.s, scaleY: d.s * SQ, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 420, delay: i * 30, ease: 'Cubic.easeInOut', + onComplete: () => c.destroy(), }); - }; - draw(this.gs.playerHand, PLAYER_X, this.playerCardGraphics); - draw(this.gs.bankerHand, BANKER_X, this.bankerCardGraphics); + }); + await this.wait(440 + all.length * 30); } - updateTotals() { - const pv = handValue(this.gs.playerHand); - const bv = handValue(this.gs.bankerHand); - this.playerTotalTxt.setText(this.gs.playerHand.length ? `${pv}` : ''); - this.bankerTotalTxt.setText(this.gs.bankerHand.length ? `${bv}` : ''); - - const win = this.gs.outcome; - this.playerGlow.setVisible(win === 'player' || win === 'tie'); - this.bankerGlow.setVisible(win === 'banker' || win === 'tie'); - this.playerTotalTxt.setColor(win === 'player' ? COLORS.goldHex : COLORS.textHex); - this.bankerTotalTxt.setColor(win === 'banker' ? COLORS.goldHex : COLORS.textHex); + async animateReshuffle() { + const banner = this.banner('Shuffling a fresh eight-deck shoe…', 360); + playSound(this, SFX.CARD_SHUFFLE); + const sp = this.shoePos; + for (let i = 0; i < 14; i++) { + const c = this.skin.make(null, false, sp.x, sp.y, sp.s, 0); + c.setDepth(D.flying + i); + const left = i % 2 === 0; + const k = Math.floor(i / 2); + this.tweens.add({ + targets: c, x: sp.x + (left ? -150 : -60) + k * 3, y: sp.y + 46 - k * 2, + rotation: (left ? -0.22 : 0.22) + (k - 3) * 0.02, duration: 260, delay: i * 18, ease: 'Cubic.easeOut', + onComplete: () => this.tweens.add({ + targets: c, x: sp.x - 105, y: sp.y + 40 - i * 0.8, rotation: 0, + duration: 180, delay: 260 + (13 - i) * 22, ease: 'Sine.easeIn', + onComplete: () => this.tweens.add({ + targets: c, x: sp.x, y: sp.y, alpha: 0, duration: 220, delay: 240, ease: 'Cubic.easeIn', + onComplete: () => c.destroy(), + }), + }), + }); + } + await this.wait(1350); + await this.tweenP({ targets: banner, alpha: 0, duration: 220 }); + banner.destroy(); } - showOutcomeBanner() { - const label = this.gs.outcome === 'tie' ? 'TIE' - : this.gs.outcome === 'player' ? 'PLAYER WINS' : 'BANKER WINS'; - const hex = this.gs.outcome === 'tie' ? BET_META[BET.TIE].hex - : this.gs.outcome === 'player' ? BET_META[BET.PLAYER].hex : BET_META[BET.BANKER].hex; - this.outcomeBanner = this.add.text(CX, 150, label, { - fontFamily: 'Righteous', fontSize: '40px', color: hex, - stroke: '#000000', strokeThickness: 5, - }).setOrigin(0.5).setDepth(D.modal).setAlpha(0).setScale(1.3); - this.tweens.add({ - targets: this.outcomeBanner, alpha: 1, scaleX: 1, scaleY: 1, - duration: 220, ease: 'Back.Out', + banner(text, y, color = '#f7ecd0', size = 26) { + const c = this.add.container(CX, y).setDepth(D.prompt).setAlpha(0); + const t = this.add.text(0, 0, text, { + fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, + }).setOrigin(0.5); + const bg = this.add.graphics(); + bg.fillStyle(0x0b0806, 0.85); + bg.fillRoundedRect(-t.width / 2 - 28, -t.height / 2 - 14, t.width + 56, t.height + 28, (t.height + 28) / 2); + bg.lineStyle(2, COLORS.accent, 0.8); + bg.strokeRoundedRect(-t.width / 2 - 28, -t.height / 2 - 14, t.width + 56, t.height + 28, (t.height + 28) / 2); + c.add([bg, t]); + this.tweens.add({ targets: c, alpha: 1, duration: 220 }); + return c; + } + + renderSeatInfo() { + for (const p of this.gs.players) { + if (p.active) this.chipTxts[p.seat]?.setText(`$${p.chips.toLocaleString()}`); + } + } + + seatSource(seat) { + if (seat === 0) return this.dock.sourcePos(); + const pt = seatPortrait(seat); + return { x: pt.x, y: pt.y, s: 0.9 }; + } + + // ── Chip stacks ──────────────────────────────────────────────────────────── + renderBetAreas() { + for (const st of Object.values(this.stacks)) st.destroy(); + this.stacks = {}; + if (!this.gs) return; + for (const p of this.gs.players) { + if (!p.active) continue; + const betting = p.seat === 0 && this.gs.phase === 'betting'; + const amount = betting ? this.pendingBet : p.bet; + const type = betting ? this.selectedType : p.betType; + if (amount <= 0 || !type || this.settled.has(p.seat)) continue; + const pose = boxCenter(p.seat, type); + const size = STACK_SIZE * pose.s; + const st = makeChipStack(this, pose.x, pose.y + 6 * pose.s, amount, { size, depth: D.stacks, seed: p.seat + amount }); + st.chipSize = size; + this.stacks[p.seat] = st; + } + } + + // ── Betting ──────────────────────────────────────────────────────────────── + chipAffordable(amt) { + const human = this.gs?.players[0]; + return !!human && this.pendingBet + amt <= Math.min(MAX_BET, human.chips); + } + + rebetAmount(mult) { + const human = this.gs?.players[0]; + if (!human || !this.lastBet) return 0; + return Math.floor(Math.min(this.lastBet * mult, MAX_BET, human.chips) / MIN_BET) * MIN_BET; + } + + selectBetType(type) { + if (this.dockMode !== 'bet' || this.busy || type === this.selectedType) { + if (this.dockMode === 'bet' && type === this.selectedType) this.drawBoxHighlight(); + return; + } + this.selectedType = type; + playSound(this, SFX.CARD_PLACE); + const st = this.stacks[0]; + if (st) { + // slide the chips already down over to the new box + const to = boxCenter(0, type); + this.tweens.add({ + targets: st, x: to.x, y: to.y + 6 * to.s, duration: 260, ease: 'Cubic.easeInOut', + onComplete: () => this.renderBetAreas(), + }); + } + this.updateBetDisplay(); + this.drawBoxHighlight(); + } + + throwChip(denom, from, delay = 0) { + const to = boxCenter(0, this.selectedType); + return throwChip(this, denom, from, { x: to.x, y: to.y + 6 * to.s, s: to.s }, { + delay, size: STACK_SIZE, depth: D.flying, + sound: () => { playChipBet(this); this.renderBetAreas(); }, }); } - renderSeatInfo(seat) { - const p = this.gs.players[seat]; - if (this.chipTxts[seat]) this.chipTxts[seat].setText(`$${p.chips.toLocaleString()}`); + onChipClick(amt) { + if (this.dockMode !== 'bet' || this.busy || !this.chipAffordable(amt)) return; + const btn = this.dock.chipButton(amt); + this.pendingBet += amt; + this.dock.hidePrompts(); + this.updateBetDisplay(); + this.throwChip(amt, { x: btn.img.x, y: btn.img.y }); } - renderBetChips() { - for (const g of Object.values(this.betGraphics)) g.destroy(); - this.betGraphics = {}; - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (!p.active || p.bet === 0 || !p.betType) continue; - const meta = BET_META[p.betType]; - const pos = SEAT_POS[seat]; - const cont = this.add.container(pos.betX, pos.betY).setDepth(D.chips); - const circle = this.add.graphics(); - circle.fillStyle(meta.color, 1); - circle.fillCircle(0, 0, 28); - circle.lineStyle(2, 0xffffff, 0.8); - circle.strokeCircle(0, 0, 28); - const amt = this.add.text(0, -6, `$${p.bet}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5); - const tag = this.add.text(0, 12, meta.short, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#ffffff', - }).setOrigin(0.5); - cont.add([circle, amt, tag]); - this.betGraphics[seat] = cont; + async onRebet(mult) { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet > 0) return; + const amt = this.rebetAmount(mult); + if (amt < MIN_BET) return; + this.busy = true; + this.selectedType = this.lastType; + this.drawBoxHighlight(); + this.pendingBet = amt; + this.dock.hidePrompts(); + this.updateBetDisplay(); + const throws = []; + let rest = amt, i = 0; + for (const d of [...CHIP_AMOUNTS].reverse()) { + while (rest >= d) { + const btn = this.dock.chipButton(d); + throws.push(this.throwChip(d, { x: btn.img.x, y: btn.img.y }, i++ * 60)); + rest -= d; + } } - } - - clearHandGraphics() { - for (const c of this.playerCardGraphics) c.destroy(); - for (const c of this.bankerCardGraphics) c.destroy(); - this.playerCardGraphics = []; - this.bankerCardGraphics = []; - } - - // ── Card drawing ────────────────────────────────────────────────────────── - addCardBackToContainer(container) { - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - container.add( - this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H) - .setOrigin(0.5) - ); - } else { - const g = this.add.graphics(); - this.drawCardBack(g, -CARD_W / 2, -CARD_H / 2); - container.add(g); - } - } - - cardX(centerX, idx, total) { - const totalW = total * CARD_SPREAD + (CARD_W - CARD_SPREAD); - return centerX - totalW / 2 + CARD_W / 2 + idx * CARD_SPREAD; - } - - drawCard(container, card, faceUp) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - if (faceUp && card) { - const g = this.add.graphics(); - g.fillStyle(0xffffff, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(1, 0xcccccc, 1); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - container.add(g); - const color = card.isRed ? '#c0392b' : '#1a1a2e'; - const style = (sz, bold = false) => ({ - fontFamily: '"Julius Sans One"', fontSize: `${sz}px`, color, - ...(bold ? { fontStyle: 'bold' } : {}), - }); - container.add(this.add.text(x + 7, y + 5, card.label, style(17, true))); - container.add(this.add.text(x + 7, y + 23, card.suitSymbol, style(13))); - container.add(this.add.text(0, 4, card.suitSymbol, style(40)).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 8, card.label, style(17, true)).setOrigin(1, 1)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 22, card.suitSymbol, style(13)).setOrigin(1, 1)); - } else { - this.addCardBackToContainer(container); - } - } - - drawCardBack(g, x, y) { - const color = this.cardBack?.fallbackColor - ? parseInt(this.cardBack.fallbackColor.replace('#', ''), 16) : 0x1a3a6b; - g.fillStyle(color, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xffffff, 0.25); - g.strokeRoundedRect(x + 6, y + 6, CARD_W - 12, CARD_H - 12, CARD_R - 2); - g.lineStyle(1, 0xffffff, 0.1); - g.strokeRoundedRect(x + 10, y + 10, CARD_W - 20, CARD_H - 20, CARD_R - 4); - } - - // ── Betting phase ───────────────────────────────────────────────────────── - onBetTypeSelect(type) { - if (this.animating) return; - this.selectedBetType = type; - this.refreshBetTypePills(); - } - - onChipClick(amount) { - if (this.animating) return; - const human = this.gs.players[0]; - if (this.pendingBet + amount > MAX_BET) return; - if (this.pendingBet + amount > human.chips) return; - this.pendingBet += amount; + await Promise.all(throws); + this.busy = false; this.updateBetDisplay(); } onClearBet() { - if (this.animating) return; + if (this.dockMode !== 'bet' || this.busy || this.pendingBet === 0) return; this.pendingBet = 0; + const st = this.stacks[0]; + delete this.stacks[0]; + if (st) { + this.tweens.add({ + targets: st, x: this.dock.chipCenterX, y: DOCK_Y, alpha: 0, scale: 0.7, + duration: 320, ease: 'Cubic.easeIn', onComplete: () => st.destroy(), + }); + } this.updateBetDisplay(); + this.startBettingPrompts(); } updateBetDisplay() { - if (this.betDisplayText) this.betDisplayText.setText(`Bet: $${this.pendingBet}`); - if (this.dealBtn) this.dealBtn.setEnabled(this.pendingBet >= 5); const human = this.gs?.players[0]; - if (this.balanceText && human) this.balanceText.setText(`Balance: $${human.chips.toLocaleString()}`); + const meta = BET_META[this.selectedType]; + this.dock.betPill.setText(`BET $${this.pendingBet} · ${meta.label.replace(' 8:1', '')}`).setColor(meta.hex); + if (human) this.chipTxts[0].setText(`$${human.chips.toLocaleString()}`); + if (this.dockMode !== 'bet' || !human) return; + this.dealBtn.setEnabled(this.pendingBet >= MIN_BET && !this.busy); + this.clearBtn.setEnabled(this.pendingBet > 0 && !this.busy); + const r1 = this.rebetAmount(1), r2 = this.rebetAmount(2); + this.rebetBtn.setEnabled(r1 >= MIN_BET && this.pendingBet === 0 && !this.busy); + this.rebetBtn.setLabel(r1 >= MIN_BET ? `Rebet $${r1}` : 'Rebet'); + this.rebet2Btn.setEnabled(r2 > r1 && this.pendingBet === 0 && !this.busy); + for (const [type, b] of Object.entries(this.typeBtns)) b.setActive(type === this.selectedType); + this.dock.setChipStates(amt => this.chipAffordable(amt)); } - onDealClick() { - if (this.animating || this.pendingBet < 5) return; - this.animating = true; - this.hideBettingUI(); + startBettingPrompts() { + if (this.pendingBet > 0) return; + this.dock.startPrompts('Click PLAYER, BANKER or TIE on the felt, add chips, then Deal', () => this.pendingBet === 0); + } - // Commit human bet, then AI bets. - this.gs = applyBet(this.gs, 0, this.pendingBet, this.selectedBetType); - for (let seat = 1; seat < SEAT_POS.length; seat++) { + async onDealClick() { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet < MIN_BET) return; + this.busy = true; + this.lastBet = this.pendingBet; + this.lastType = this.selectedType; + this.setDockMode('wait', 'No more bets'); + + this.gs = applyBet(this.gs, 0, this.pendingBet, this.selectedType); + const throws = []; + let n = 0; + for (let seat = 1; seat < this.gs.players.length; seat++) { const p = this.gs.players[seat]; if (!p.active) continue; - const bet = Math.max(5, chooseBet(p)); - this.gs = applyBet(this.gs, seat, bet, chooseBetType()); + const bet = Math.max(MIN_BET, chooseBet(p)); + const type = chooseBetType(); + this.gs = applyBet(this.gs, seat, bet, type); + const to = boxCenter(seat, type); + throws.push(throwStack(this, this.seatSource(seat), { x: to.x, y: to.y + 6 * to.s, s: to.s }, bet, { + delay: n++ * 90, size: STACK_SIZE, depth: D.flying, sound: () => playChipBet(this), + }).then(() => this.renderBetAreas())); + } + await Promise.all(throws); + + this.gs = dealCoup(this.gs, this.shoe); + await this.playCoup(); + } + + // ── The coup ─────────────────────────────────────────────────────────────── + squeezeSides() { + const t = this.gs.players[0].betType; + if (t === BET.PLAYER) return ['player']; + if (t === BET.BANKER) return ['banker']; + return ['player', 'banker']; + } + + handOf(side) { return side === 'player' ? this.gs.playerHand : this.gs.bankerHand; } + + dealTo(side, i) { + const card = this.handOf(side)[i]; + const { c, promise } = this.skin.deal(card, false, this.shoePos, handCardPose(side, i), { + duration: 300, flyingDepth: D.flying, sound: () => playSound(this, SFX.CARD_DEAL), + }); + this.cards.set(`${side}:${i}`, c); + return promise; + } + + async revealCard(side, i, first) { + const c = this.cards.get(`${side}:${i}`); + if (this.squeezeSides().includes(side)) { + this.setDockMode('wait', `Squeezing your ${side === 'player' ? 'PLAYER' : 'BANKER'} card…`); + await this.skin.peel(c, { ...(first ? SQUEEZE_FIRST : SQUEEZE_NEXT), onPeek: () => playSound(this, SFX.CARD_SHOW) }); + } else { + playSound(this, SFX.CARD_SHOW); + await this.skin.flip(c, true, 280); + } + } + + async playCoup() { + // P1, B1, P2, B2 face-down + for (const [side, i] of [['player', 0], ['banker', 0], ['player', 1], ['banker', 1]]) { + this.dealTo(side, i); + await this.wait(200); + } + await this.wait(260); + if (!this.alive()) return; + + for (const side of ['player', 'banker']) { + await this.revealCard(side, 0, true); + await this.revealCard(side, 1, false); + this.showTotal(side, 2); + await this.wait(260); } - // Resolve the coup up front; reveal it through animation. - this.gs = dealCoup(this.gs, this.shoe); + for (const side of ['player', 'banker']) { + if (this.handOf(side).length < 3) continue; + this.setDockMode('wait', `${side === 'player' ? 'Player' : 'Banker'} draws a third card`); + await this.wait(300); + await this.dealTo(side, 2); + await this.revealCard(side, 2, false); + this.showTotal(side, 3); + await this.wait(260); + } + if (!this.alive()) return; - this.animateBets(() => { - this.renderHands(); - this.animateDeal(() => { - // Keep `animating` true through the whole tally so nothing re-fires. - this.runTallySequence(() => { - this.animating = false; - this.updateTotals(); - this.showOutcomeBanner(); - this.time.delayedCall(900, () => this.finishRound()); - }); - }); - }); + this.setDockMode('wait', ''); + await this.runTallySequence(); + if (!this.alive()) return; + this.showOutcome(); + this.history.push(this.gs.outcome); + this.drawScoreboard(); + await this.wait(700); + this.finishRound(); + } + + // Running total pill under a hand. + showTotal(side, nCards) { + const meta = BET_META[side]; + const total = handValue(this.handOf(side).slice(0, nCards)); + const c = handCenter(side); + let b = this.totalBadges[side]; + if (!b) { + b = this.add.container(c.x, c.y + TOTAL_BADGE_DY * c.s).setDepth(D.badges); + b.g = this.add.graphics(); + b.t = this.add.text(0, 0, '', { fontFamily: '"Julius Sans One"', fontSize: '22px', color: '#ffffff', fontStyle: 'bold' }).setOrigin(0.5); + b.add([b.g, b.t]); + this.totalBadges[side] = b; + this.decor.push(b); + b.setScale(0.6); + this.tweens.add({ targets: b, scale: 1, duration: 200, ease: 'Back.Out' }); + } + this.drawTotal(b, `${meta.label} ${total}`, meta.color, false); + } + + drawTotal(b, text, color, winner) { + b.t.setText(text).setColor(winner ? '#1a1208' : '#ffffff'); + const w = b.t.width + 28, h = 34; + b.g.clear(); + if (winner) { + b.g.fillStyle(0xf5d020, 0.28); + b.g.fillRoundedRect(-w / 2 - 6, -h / 2 - 6, w + 12, h + 12, 22); + } + b.g.fillStyle(winner ? 0xf5d020 : color, 0.95); + b.g.fillRoundedRect(-w / 2, -h / 2, w, h, 17); + b.g.lineStyle(2, 0xffffff, 0.6); + b.g.strokeRoundedRect(-w / 2, -h / 2, w, h, 17); + } + + showOutcome() { + const o = this.gs.outcome; + const pv = handValue(this.gs.playerHand), bv = handValue(this.gs.bankerHand); + const winners = o === 'tie' ? ['player', 'banker'] : [o]; + for (const side of winners) { + const r = handBoxRect(side); + const g = this.add.graphics().setDepth(D.feltHi); + g.lineStyle(5, 0xf5d020, 0.95); + g.strokeRoundedRect(r.x - r.w / 2 - 4, r.y - r.h / 2 - 4, r.w + 8, r.h + 8, 14); + g.fillStyle(0xf5d020, 0.12); + g.fillRoundedRect(r.x - r.w / 2 - 4, r.y - r.h / 2 - 4, r.w + 8, r.h + 8, 14); + this.tweens.add({ targets: g, alpha: 0.45, duration: 600, yoyo: true, repeat: 3 }); + this.decor.push(g); + const b = this.totalBadges[side]; + if (b) this.drawTotal(b, `${BET_META[side].label} ${side === 'player' ? pv : bv}`, BET_META[side].color, true); + } + const label = o === 'tie' ? `TIE ${pv} – ${bv}` : o === 'player' ? `PLAYER WINS ${pv} – ${bv}` : `BANKER WINS ${bv} – ${pv}`; + const color = BET_META[o === 'tie' ? BET.TIE : o].hex; + const banner = this.banner(label, 128, color, 30); + this.decor.push(banner); + playSound(this, o === 'tie' ? SFX.CASINO_BLACKJACK : SFX.CASINO_WIN); } // ── Total-reveal sequence ("Equation Ribbon") ────────────────────────────── - // After the deal, walk through each hand's math one card at a time and reduce - // the two-digit sum to a single digit (mod 10): Player first, then Banker. - runTallySequence(onComplete) { - this.tallyHand('player', () => { - if (!this.scene.isActive('BaccaratGame')) return; - this.time.delayedCall(TALLY.betweenHandsMs, () => { - if (!this.scene.isActive('BaccaratGame')) return; - this.tallyHand('banker', () => { - if (!this.scene.isActive('BaccaratGame')) return; - this.restoreCards(); - this.fadeOutTally(onComplete); - }); - }); - }); + // Walk through each hand's math one card at a time and reduce the two-digit + // sum to a single digit (mod 10): Player first, then Banker. + async runTallySequence() { + await this.tallyHand('player'); + if (!this.alive()) return; + await this.wait(TALLY.betweenHandsMs); + await this.tallyHand('banker'); + if (!this.alive()) return; + this.restoreCards(); + await this.fadeOutTally(); } - // Runs the per-hand walkthrough: spotlight each card, build the equation, then - // perform the mod-10 reduction flourish. `onDone` fires once the badge holds. - tallyHand(side, onDone) { - const isPlayer = side === 'player'; - const hand = isPlayer ? this.gs.playerHand : this.gs.bankerHand; - const centerX = isPlayer ? PLAYER_X : BANKER_X; - const cardConts = isPlayer ? this.playerCardGraphics : this.bankerCardGraphics; - const otherConts = isPlayer ? this.bankerCardGraphics : this.playerCardGraphics; - const accentHex = isPlayer ? BET_META[BET.PLAYER].hex : BET_META[BET.BANKER].hex; + async tallyHand(side) { + const hand = this.handOf(side); + const other = side === 'player' ? 'banker' : 'player'; + const conts = hand.map((_, i) => this.cards.get(`${side}:${i}`)); + const otherConts = this.handOf(other).map((_, i) => this.cards.get(`${other}:${i}`)); + const meta = BET_META[side]; + if (!hand.length) return; - if (!hand.length) { onDone(); return; } + for (const c of conts) this.tweens.add({ targets: c, alpha: 1, duration: 220 }); + for (const c of otherConts) this.tweens.add({ targets: c, alpha: 0.35, duration: 220 }); - // Spotlight the active hand, dim the inactive one. - for (const c of cardConts) this.tweens.add({ targets: c, alpha: 1, duration: 220 }); - for (const c of otherConts) this.tweens.add({ targets: c, alpha: 0.3, duration: 220 }); - - // Scoreboard readout panel behind the equation. - const panel = this.add.graphics().setDepth(D.modal - 1); - panel.fillStyle(0x000000, 0.82); - panel.fillRoundedRect(centerX - TALLY.panelW / 2, TALLY.ribbonY - TALLY.panelH / 2, - TALLY.panelW, TALLY.panelH, 16); - panel.lineStyle(3, COLORS.accent, 0.9); - panel.strokeRoundedRect(centerX - TALLY.panelW / 2, TALLY.ribbonY - TALLY.panelH / 2, - TALLY.panelW, TALLY.panelH, 16); - panel.setAlpha(0); - this.tallyObjs.push(panel); - this.tweens.add({ targets: panel, alpha: 1, duration: 200 }); - - // Header label inside the panel. - const header = this.add.text(centerX, TALLY.ribbonY - TALLY.panelH / 2 + 25, - isPlayer ? 'PLAYER' : 'BANKER', { - fontFamily: 'Righteous', fontSize: '20px', color: accentHex, - }).setOrigin(0.5).setDepth(D.modal).setAlpha(0); - this.tallyObjs.push(header); - this.tweens.add({ targets: header, alpha: 1, duration: 200 }); - - // Equation ribbon (rebuilt as terms are added). - const ribbon = this.add.text(centerX, TALLY.ribbonY - 8, '', { - fontFamily: '"Julius Sans One"', fontSize: '40px', color: COLORS.textHex, fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.modal); - this.tallyObjs.push(ribbon); + this.clearTally(); + ensureLeatherPanel(this, 'bac-readout', READOUT.w, READOUT.h, { radius: 16, felt: '#2a0910' }); + const panel = this.add.image(READOUT.x, READOUT.y, 'bac-readout').setDepth(D.readout - 1).setAlpha(0); + const header = this.add.text(READOUT.x, READOUT.y - READOUT.h / 2 + 17, meta.label, { + fontFamily: 'Righteous', fontSize: '16px', color: meta.hex, + }).setOrigin(0.5).setDepth(D.readout).setAlpha(0); + const ribbon = this.add.text(READOUT.x, READOUT.y - 6, '', { + fontFamily: '"Julius Sans One"', fontSize: '30px', color: COLORS.textHex, fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.readout); + this.tallyObjs.push(panel, header, ribbon); + this.tweens.add({ targets: [panel, header], alpha: 1, duration: 200 }); let rawSum = 0; const terms = []; - - const stepCard = (i) => { - if (!this.scene.isActive('BaccaratGame')) return; - if (i >= hand.length) { - // Show "= rawSum", beat, then reduce. - ribbon.setText(`${terms.join(' + ')} = ${rawSum}`); - this.time.delayedCall(TALLY.sumHoldMs, () => { - if (!this.scene.isActive('BaccaratGame')) return; - this.playReduction(centerX, ribbon, rawSum, onDone); - }); - return; - } - const card = hand[i]; - const cont = cardConts[i]; - rawSum += card.value; - terms.push(`${card.value}`); - ribbon.setText(terms.join(' + ')); - - this.spotlightCard(cont); - this.popCardValue(cont ? cont.x : centerX, card.value); - - this.time.delayedCall(TALLY.perCardMs, () => stepCard(i + 1)); - }; - stepCard(0); + for (let i = 0; i < hand.length; i++) { + if (!this.alive()) return; + rawSum += hand[i].value; + terms.push(`${hand[i].value}`); + ribbon.setText(terms.join(' + ')); + this.spotlightCard(conts[i]); + this.popCardValue(conts[i], hand[i].value); + await this.wait(TALLY.perCardMs); + } + ribbon.setText(`${terms.join(' + ')} = ${rawSum}`); + await this.wait(TALLY.sumHoldMs); + await this.playReduction(ribbon, rawSum); } // Lift + glow a single card briefly, then settle it back. - spotlightCard(cont) { - if (!cont) return; - const baseY = HAND_Y; - const glow = this.add.graphics().setDepth(D.cards - 1); - glow.lineStyle(4, COLORS.gold, 0.9); - glow.strokeRoundedRect(cont.x - CARD_W / 2 - 5, baseY - TALLY.cardLift - CARD_H / 2 - 5, - CARD_W + 10, CARD_H + 10, CARD_R + 3); - glow.setAlpha(0); - this.tallyObjs.push(glow); - + spotlightCard(c) { + if (!c) return; + const base = { y: c.y, sx: c.scaleX, sy: c.scaleY }; this.tweens.add({ - targets: cont, y: baseY - TALLY.cardLift, scaleX: 1.06, scaleY: 1.06, - duration: 200, ease: 'Back.Out', - yoyo: true, hold: TALLY.perCardMs - 400, - onComplete: () => { cont.y = baseY; cont.setScale(1); }, + targets: c, y: base.y - TALLY.cardLift, scaleX: base.sx * 1.06, scaleY: base.sy * 1.06, + duration: 200, ease: 'Back.Out', yoyo: true, hold: TALLY.perCardMs - 400, + onComplete: () => { c.y = base.y; c.setScale(base.sx, base.sy); }, }); - this.tweens.add({ targets: glow, alpha: 1, duration: 180, yoyo: true, hold: TALLY.perCardMs - 360 }); playSound(this, SFX.CARD_SHOW); } // Big gold number that pops above a card and fades down toward the ribbon. - popCardValue(x, value) { - const t = this.add.text(x, HAND_Y - CARD_H / 2 - 40, `${value}`, { - fontFamily: '"Julius Sans One"', fontSize: '52px', color: COLORS.goldHex, fontStyle: 'bold', + popCardValue(c, value) { + const x = c?.x ?? READOUT.x, y = (c?.y ?? READOUT.y) - 80 * (c?.scaleY ?? 1); + const t = this.add.text(x, y, `${value}`, { + fontFamily: '"Julius Sans One"', fontSize: '50px', color: COLORS.goldHex, fontStyle: 'bold', stroke: '#000000', strokeThickness: 5, - }).setOrigin(0.5).setDepth(D.modal + 1).setAlpha(0).setScale(1.5); + }).setOrigin(0.5).setDepth(D.readout + 1).setAlpha(0).setScale(1.5); this.tweens.add({ targets: t, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.Out' }); this.tweens.add({ - targets: t, y: TALLY.ribbonY - 30, alpha: 0, - duration: 340, delay: TALLY.perCardMs - 360, ease: 'Power2', + targets: t, y: READOUT.y - 30, alpha: 0, duration: 340, delay: TALLY.perCardMs - 360, ease: 'Power2', onComplete: () => t.destroy(), }); } // The signature flourish: drop the tens digit, land the ones digit in a badge. - playReduction(centerX, ribbon, rawSum, onDone) { + async playReduction(ribbon, rawSum) { const tens = Math.floor(rawSum / 10); const ones = rawSum % 10; - const badgeY = TALLY.ribbonY + 48; // lower third of the readout panel + const badgeY = READOUT.y + 30; + const badgeX = READOUT.x; - const settleBadge = () => { - const badge = this.add.graphics().setDepth(D.modal); + const settleBadge = async () => { + const badge = this.add.graphics().setDepth(D.readout); badge.lineStyle(4, COLORS.accent, 1); - badge.strokeCircle(centerX, badgeY, TALLY.badgeR); + badge.fillStyle(0x0b0806, 0.9); + badge.fillCircle(badgeX, badgeY, TALLY.badgeR); + badge.strokeCircle(badgeX, badgeY, TALLY.badgeR); badge.setAlpha(0); - this.tallyObjs.push(badge); - const digit = this.add.text(centerX, badgeY, `${ones}`, { - fontFamily: 'Righteous', fontSize: '46px', color: COLORS.goldHex, - stroke: '#000000', strokeThickness: 5, - }).setOrigin(0.5).setDepth(D.modal + 1).setScale(1.6).setAlpha(0); - this.tallyObjs.push(digit); + const digit = this.add.text(badgeX, badgeY, `${ones}`, { + fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex, stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.readout + 1).setScale(1.6).setAlpha(0); + this.tallyObjs.push(badge, digit); this.tweens.add({ targets: [badge, digit], alpha: 1, duration: 200 }); - this.tweens.add({ - targets: digit, scaleX: 1, scaleY: 1, duration: 280, ease: 'Back.Out', - }); + this.tweens.add({ targets: digit, scaleX: 1, scaleY: 1, duration: 280, ease: 'Back.Out' }); playSound(this, SFX.CHIP_BET); - this.time.delayedCall(TALLY.badgeHoldMs, () => { if (this.scene.isActive('BaccaratGame')) onDone(); }); + await this.wait(TALLY.badgeHoldMs); }; if (tens === 0) { // No reduction needed — fade the equation and settle the single digit. this.tweens.add({ targets: ribbon, alpha: 0, duration: 220 }); - this.time.delayedCall(140, settleBadge); + await this.wait(140); + await settleBadge(); return; } - // Split the trailing two-digit sum into separate tens/ones digits, aligned to - // the right end of the ribbon, then drop the tens and slide the ones up. const eqText = `${ribbon.text}`; const rightX = ribbon.x + ribbon.width / 2; - ribbon.setText(eqText.slice(0, eqText.length - 2)); // strip the "NN" - - const tensTxt = this.add.text(rightX - 44, ribbon.y, `${tens}`, { - fontFamily: '"Julius Sans One"', fontSize: '40px', color: COLORS.textHex, fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.modal + 1); - const onesTxt = this.add.text(rightX - 16, ribbon.y, `${ones}`, { - fontFamily: '"Julius Sans One"', fontSize: '40px', color: COLORS.textHex, fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.modal + 1); - // tensTxt/onesTxt manage their own destruction below — not tracked in tallyObjs. - - // Flag the tens digit red, then let it fall away. + ribbon.setText(eqText.slice(0, eqText.length - 2)); + const style = { fontFamily: '"Julius Sans One"', fontSize: '30px', color: COLORS.textHex, fontStyle: 'bold' }; + const tensTxt = this.add.text(rightX - 32, ribbon.y, `${tens}`, style).setOrigin(0.5).setDepth(D.readout + 1); + const onesTxt = this.add.text(rightX - 12, ribbon.y, `${ones}`, style).setOrigin(0.5).setDepth(D.readout + 1); tensTxt.setColor(COLORS.dangerHex); this.tweens.add({ targets: tensTxt, scaleX: 1.35, scaleY: 1.35, duration: 200, yoyo: true }); - this.time.delayedCall(280, () => { - if (!this.scene.isActive('BaccaratGame')) return; - this.tweens.add({ - targets: tensTxt, y: tensTxt.y + 90, alpha: 0, angle: -25, - duration: TALLY.dropMs, ease: 'Quad.In', - onComplete: () => tensTxt.destroy(), - }); - // Slide the ones digit up into the badge position. - this.tweens.add({ - targets: onesTxt, x: centerX, y: badgeY, scaleX: 1.15, scaleY: 1.15, - duration: TALLY.dropMs, ease: 'Power2', - onComplete: () => { onesTxt.destroy(); settleBadge(); }, - }); - this.tweens.add({ targets: ribbon, alpha: 0, duration: TALLY.dropMs }); + await this.wait(280); + if (!this.alive()) return; + this.tweens.add({ + targets: tensTxt, y: tensTxt.y + 80, alpha: 0, angle: -25, duration: TALLY.dropMs, ease: 'Quad.In', + onComplete: () => tensTxt.destroy(), }); + this.tweens.add({ targets: ribbon, alpha: 0, duration: TALLY.dropMs }); + await this.tweenP({ targets: onesTxt, x: badgeX, y: badgeY, scaleX: 1.15, scaleY: 1.15, duration: TALLY.dropMs, ease: 'Power2' }); + onesTxt.destroy(); + await settleBadge(); } - // Restore both hands to their resting state after the walkthrough. restoreCards() { - for (const c of [...this.playerCardGraphics, ...this.bankerCardGraphics]) { - if (c?.active === false) continue; - c.setAlpha?.(1); - c.setScale?.(1); - if (c) c.y = HAND_Y; - } + for (const c of this.cards.values()) c?.setAlpha?.(1); } - // Fade out the readout panels/ribbons/badges, then hand off to the results. - fadeOutTally(onDone) { + async fadeOutTally() { const objs = this.tallyObjs.filter(o => o && o.active !== false); this.tallyObjs = []; - if (objs.length === 0) { onDone(); return; } - this.tweens.add({ - targets: objs, alpha: 0, duration: 260, ease: 'Power2', - onComplete: () => { for (const o of objs) o?.destroy?.(); onDone(); }, - }); + if (!objs.length) return; + await this.tweenP({ targets: objs, alpha: 0, duration: 260, ease: 'Power2' }); + for (const o of objs) o?.destroy?.(); } clearTally() { @@ -810,232 +888,128 @@ export default class BaccaratGame extends Phaser.Scene { this.tallyObjs = []; } - // ── Animations ──────────────────────────────────────────────────────────── - animateBets(onComplete) { - this.renderBetChips(); - playChipBet(this); - const active = this.gs.players.filter(p => p.active && p.bet > 0); - if (active.length === 0) { onComplete(); return; } - let done = 0; - for (const p of active) { - const pos = SEAT_POS[p.seat]; - const px = pos.portraitX ?? pos.betX; - const py = pos.portraitY ?? pos.betY; - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(BET_META[p.betType].color, 1); - chip.fillCircle(0, 0, 16); - chip.x = px; chip.y = py; - this.tweens.add({ - targets: chip, x: pos.betX, y: pos.betY, duration: 280, ease: 'Power2', - onComplete: () => { - chip.destroy(); - if (++done >= active.length) onComplete(); - }, - }); - } - } - - animateDeal(onComplete) { - // Coup order: P1, B1, P2, B2, then any player third, then any banker third. - const seq = [ - { side: 'player', idx: 0 }, { side: 'banker', idx: 0 }, - { side: 'player', idx: 1 }, { side: 'banker', idx: 1 }, - ]; - if (this.gs.playerHand.length === 3) seq.push({ side: 'player', idx: 2 }); - if (this.gs.bankerHand.length === 3) seq.push({ side: 'banker', idx: 2 }); - - const conts = { player: this.playerCardGraphics, banker: this.bankerCardGraphics }; - for (const c of [...conts.player, ...conts.banker]) c.setAlpha(0); - - let idx = 0; - const stagger = 110; - const dealNext = () => { - if (idx >= seq.length) { onComplete(); return; } - const entry = seq[idx++]; - const target = conts[entry.side][entry.idx]; - const flying = this.add.container(SHOE_X, SHOE_Y).setDepth(D.cards + 10); - this.addCardBackToContainer(flying); - this.tweens.add({ - targets: flying, x: target.x, y: target.y, duration: 190, ease: 'Power2', - onComplete: () => { - flying.destroy(); - playSound(this, SFX.CARD_DEAL); - target.setAlpha(1); - this.time.delayedCall(stagger, dealNext); - }, - }); - }; - dealNext(); - } - - // ── Resolve ─────────────────────────────────────────────────────────────── - finishRound() { + // ── Resolve ──────────────────────────────────────────────────────────────── + async finishRound() { this.gs = resolveRound(this.gs); - this.renderAll(); - this.updateTotals(); - this.showAllResults(() => { - this.updateServerChips(); - this.showNextRoundPrompt(); - }); - } - - showAllResults(onComplete) { const seats = DISPLAY_ORDER.filter(seat => { const p = this.gs.players[seat]; return p?.active && p.betType && p.bet > 0; }); - if (seats.length === 0) { onComplete(); return; } - let pending = seats.length; - const done = () => { if (--pending <= 0) onComplete(); }; - seats.forEach((seat, i) => { - this.time.delayedCall(i * 420, () => this.animateSeatResult(seat, done)); - }); + await Promise.all(seats.map((seat, i) => this.wait(i * 380).then(() => this.animateSeatResult(seat)))); + this.updateServerChips(); + this.showNextRoundPrompt(); } - animateSeatResult(seat, onComplete) { + async animateSeatResult(seat) { const p = this.gs.players[seat]; - if (!p?.active || !p.result) { onComplete(); return; } - - const isWin = p.result === 'win'; - const isLose = p.result === 'lose'; + if (!p?.active || !p.result) return; + const isWin = p.result === 'win', isLose = p.result === 'lose'; const bigWin = isWin && p.betType === BET.TIE; - if (bigWin) playSound(this, SFX.CASINO_BLACKJACK); else if (isWin) playSound(this, SFX.CASINO_WIN); else if (isLose) playSound(this, SFX.CASINO_LOSE); + if (seat > 0) this.portraits[seat]?.playEmotion?.(isWin ? 'happy' : 'upset'); - if (seat > 0 && this.portraits[seat]) { - this.portraits[seat].playEmotion?.(isWin ? 'happy' : 'upset'); - } + const st = this.stacks[seat]; + this.settled.add(seat); + delete this.stacks[seat]; + const commission = isWin && p.betType === BET.BANKER ? p.bet - p.chipsWon : 0; + const settle = settleStack(this, st, isWin ? 'win' : isLose ? 'lose' : 'push', { + payout: isWin ? p.chipsWon : 0, commission, + tray: this.trayPos, dest: this.seatSource(seat), depth: D.stacks, sound: () => playChipBet(this), + }).then(() => { + if (seat === 0 && p.chipsWon !== 0) { + const t = this.chipTxts[0]; + this.floatText(t.x + t.width + 50, t.y, `${p.chipsWon > 0 ? '+' : '−'}$${Math.abs(p.chipsWon).toLocaleString()}`, + p.chipsWon > 0 ? '#7ee081' : '#ff8a80'); + } + }); const LABELS = { win: bigWin ? 'Tie Win!' : 'Win!', lose: 'Lose', push: 'Push' }; - const TXT_COLORS = { win: '#f5d020', lose: '#e05c5c', push: '#9aa5b4' }; - const SIZES = { win: '46px', lose: '40px', push: '34px' }; - const linger = isWin ? 1400 : isLose ? 1000 : 700; - - const pos = SEAT_POS[seat]; - const px = pos.portraitX ?? pos.betX; - const py = pos.portraitY ?? pos.betY; - const textY = py - pos.portraitR - 26; - const badge = this.add.text(px, textY, LABELS[p.result] ?? p.result, { - fontFamily: '"Julius Sans One"', - fontSize: SIZES[p.result] ?? '40px', - color: TXT_COLORS[p.result] ?? '#ffffff', - fontStyle: 'bold', - stroke: '#000000', strokeThickness: 5, - shadow: isWin - ? { offsetX: 0, offsetY: 0, color: TXT_COLORS[p.result], blur: 24, fill: true } - : undefined, + const COLORS_ = { win: '#f5d020', lose: '#e05c5c', push: '#9aa5b4' }; + const at = boxCenter(seat, p.betType); + const textY = at.y - 70 * at.s; + const badge = this.add.text(at.x, textY, LABELS[p.result] ?? p.result, { + fontFamily: '"Julius Sans One"', fontSize: isWin ? '46px' : '38px', color: COLORS_[p.result] ?? '#ffffff', + fontStyle: 'bold', stroke: '#000000', strokeThickness: 5, + shadow: isWin ? { offsetX: 0, offsetY: 0, color: COLORS_.win, blur: 24, fill: true } : undefined, }).setOrigin(0.5).setAlpha(0).setScale(1.4).setDepth(D.modal); + this.tweens.add({ targets: badge, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.Out' }); + if (isWin) this.animateFireworks(at.x, textY, bigWin ? 5 : 3); + await this.wait(isWin ? 1400 : isLose ? 1000 : 700); + await this.tweenP({ targets: badge, alpha: 0, y: textY - 30, duration: 380, ease: 'Power2' }); + badge.destroy(); + await settle; + } + floatText(x, y, str, color) { + const t = this.add.text(x, y, str, { + fontFamily: '"Julius Sans One"', fontSize: '28px', color, fontStyle: 'bold', + stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.modal); this.tweens.add({ - targets: badge, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.Out', + targets: t, y: y - 60, alpha: { value: 0, ease: 'Expo.easeIn' }, + duration: 1500, ease: 'Cubic.easeOut', onComplete: () => t.destroy(), }); - this.time.delayedCall(linger, () => { - this.tweens.add({ - targets: badge, alpha: 0, y: textY - 30, duration: 380, ease: 'Power2', - onComplete: () => { badge.destroy(); onComplete(); }, - }); - }); - - if (isWin) { - this.animateChipsToSeat(seat, p.chipsWon); - this.animateFireworks(px, textY); - } else if (isLose) { - this.animateChipsToCenter(seat); - } } - animateChipsToCenter(seat) { - const pos = SEAT_POS[seat]; - for (let i = 0; i < 4; i++) { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(CHIP_COLORS[25], 1); chip.fillCircle(0, 0, 14); - chip.lineStyle(2, 0xffffff, 0.3); chip.strokeCircle(0, 0, 14); - chip.x = pos.betX + (Math.random() - 0.5) * 22; - chip.y = pos.betY; - this.tweens.add({ - targets: chip, x: CX, y: HAND_Y, duration: 440, delay: i * 55, ease: 'Power2', - onComplete: () => chip.destroy(), - }); - } - } - - animateChipsToSeat(seat, amount) { - if (!amount || amount <= 0) return; - const pos = SEAT_POS[seat]; - const count = Math.min(Math.ceil(amount / 25), 7); - for (let i = 0; i < count; i++) { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(CHIP_COLORS[25], 1); chip.fillCircle(0, 0, 14); - chip.lineStyle(2, 0xffffff, 0.3); chip.strokeCircle(0, 0, 14); - chip.x = CX + (Math.random() - 0.5) * 50; - chip.y = HAND_Y; - this.tweens.add({ - targets: chip, - x: pos.betX + (Math.random() - 0.5) * 28, - y: pos.betY, - duration: 460, delay: i * 55, ease: 'Power2', - onComplete: () => chip.destroy(), - }); - } - } - - animateFireworks(cx, cy) { + animateFireworks(cx, cy, bursts = 3) { const palette = [0xf5d020, 0xff8c00, 0x5cb85c, 0x4a90d9, 0xff69b4, 0xffffff, 0x00e5ff]; - for (let burst = 0; burst < 3; burst++) { + for (let burst = 0; burst < bursts; burst++) { this.time.delayedCall(burst * 380, () => { - if (!this.scene.isActive('BaccaratGame')) return; + if (!this.alive()) return; const bx = cx + (Math.random() - 0.5) * 140; const by = cy - 10 + (Math.random() - 0.5) * 80; for (let i = 0; i < 10; i++) { const angle = (i / 10) * Math.PI * 2 + Math.random() * 0.3; const dist = 65 + Math.random() * 65; - const color = palette[Math.floor(Math.random() * palette.length)]; const dot = this.add.graphics().setDepth(D.modal + 5); - dot.fillStyle(color, 1); + dot.fillStyle(palette[Math.floor(Math.random() * palette.length)], 1); dot.fillCircle(0, 0, 4 + Math.random() * 3); dot.x = bx; dot.y = by; this.tweens.add({ - targets: dot, - x: bx + Math.cos(angle) * dist, - y: by + Math.sin(angle) * dist, - alpha: 0, scaleX: 0.1, scaleY: 0.1, - duration: 700 + Math.random() * 400, - delay: Math.random() * 100, - ease: 'Power2', - onComplete: () => dot.destroy(), + targets: dot, x: bx + Math.cos(angle) * dist, y: by + Math.sin(angle) * dist, + alpha: 0, scaleX: 0.1, scaleY: 0.1, duration: 700 + Math.random() * 400, + delay: Math.random() * 100, ease: 'Power2', onComplete: () => dot.destroy(), }); } }); } } - async updateServerChips() { - const human = this.gs.players[0]; - const delta = human.chipsWon ?? 0; - if (delta === 0) return; - try { - await api.post('/profile/chips/adjust', { delta }); - } catch { /* balance will resync next load */ } - } - + // ── Next round ───────────────────────────────────────────────────────────── showNextRoundPrompt() { const human = this.gs.players[0]; - this.renderAll(); - this.updateTotals(); - - if (human.chips <= 0) { - new Modal(this, 'Out of chips! Visit your profile to request a reset.', { - autoCloseMs: 4000, - }); + this.renderSeatInfo(); + if (human.chips < MIN_BET) { + this.setDockMode('wait', ''); + new Modal(this, 'Out of chips! Visit your profile to request a reset.', { autoCloseMs: 4000 }); this.time.delayedCall(4200, () => this.scene.start('GameMenu')); return; } + this.busy = false; + this.setDockMode('next'); + const next = new Button(this, CX - 140, DOCK_Y, 'Next Round', () => this.onNextRound(false), { width: 230, height: 58, fontSize: 24 }); + next.setDepth(D.dockUi); + this.dock.addTransient(next); + const amt = this.rebetAmount(1); + if (amt >= MIN_BET) { + const label = BET_META[this.lastType].label.replace(' 8:1', ''); + const rebet = new Button(this, CX + 150, DOCK_Y, `Rebet $${amt} ${label}`, () => this.onNextRound(true), { + width: 300, height: 58, fontSize: 19, variant: 'ghost', + }); + rebet.setDepth(D.dockUi); + this.dock.addTransient(rebet); + } + } - const btn = new Button(this, CX, 935, 'Next Round', () => { - btn.destroy(); - this.startNewRound(); - }, { width: 220, height: 60, fontSize: 24 }); + async onNextRound(rebet) { + if (this.dockMode !== 'next') return; + if (rebet && this.rebetAmount(1) < MIN_BET) rebet = false; + this.setDockMode('wait', ''); + await this.startNewRound(); + if (!rebet || this.dockMode !== 'bet') return; + await this.onRebet(1); + this.onDealClick(); } } diff --git a/src/games/baccarat/BaccaratRoads.js b/src/games/baccarat/BaccaratRoads.js new file mode 100644 index 0000000..803276f --- /dev/null +++ b/src/games/baccarat/BaccaratRoads.js @@ -0,0 +1,68 @@ +// Baccarat scoreboard "roads" — pure, so tools/verifyBaccarat.js can test them. +// +// history: array of coup outcomes, oldest first: 'player' | 'banker' | 'tie'. +// +// Bead plate: every coup in order, filling columns top-to-bottom (6 rows), +// showing only the most recent whole columns that fit. +// Big road: one column per streak of the same winner (P or B). Ties don't +// take a cell — they mark the latest cell (a green slash). A streak +// longer than the column turns right along its last row ("dragon tail"). +// Each new streak starts in the column after the previous streak began. + +export function counts(history) { + const c = { player: 0, banker: 0, tie: 0 }; + for (const h of history) c[h]++; + return c; +} + +export function beadPlate(history, rows = 6, cols = 10) { + const usedCols = Math.ceil(history.length / rows); + const dropCols = Math.max(0, usedCols - cols); + const start = dropCols * rows; + return history.slice(start).map((outcome, k) => ({ col: Math.floor(k / rows), row: k % rows, outcome })); +} + +export function bigRoad(history, rows = 6) { + const cells = []; + const taken = new Set(); + const key = (c, r) => `${c},${r}`; + let last = null; // last placed cell + let streakCol = -1; // column where the current streak started + let pendingTies = 0; // ties before the first P/B + for (const outcome of history) { + if (outcome === 'tie') { + if (last) last.ties++; + else pendingTies++; + continue; + } + let col, row; + if (last && last.outcome === outcome) { + // continue the streak: down if free, otherwise turn right + if (!last.tail && last.row + 1 < rows && !taken.has(key(last.col, last.row + 1))) { + col = last.col; row = last.row + 1; + } else { + col = last.col + 1; row = last.row; + while (taken.has(key(col, row))) col++; + } + } else { + streakCol += 1; + col = streakCol; row = 0; + while (taken.has(key(col, row))) { streakCol++; col = streakCol; } + } + const cell = { col, row, outcome, ties: pendingTies, tail: last && last.outcome === outcome && col !== last.col }; + if (last && last.outcome === outcome && last.tail) cell.tail = true; + pendingTies = 0; + taken.add(key(col, row)); + cells.push(cell); + last = cell; + } + return cells; +} + +// The big-road cells that fit in a window of `cols` columns (most recent). +export function bigRoadWindow(history, rows = 6, cols = 18) { + const cells = bigRoad(history, rows); + const maxCol = cells.reduce((m, c) => Math.max(m, c.col), -1); + const offset = Math.max(0, maxCol + 1 - cols); + return cells.filter(c => c.col >= offset).map(c => ({ ...c, col: c.col - offset })); +} diff --git a/src/games/baccarat/BaccaratTable.js b/src/games/baccarat/BaccaratTable.js new file mode 100644 index 0000000..f239d12 --- /dev/null +++ b/src/games/baccarat/BaccaratTable.js @@ -0,0 +1,116 @@ +// Baccarat table layout — Phaser-free so tools/verifyBaccarat.js can test it. +// +// Shared perspective + rail geometry come from src/ui/casino/CasinoGeometry.js +// (re-exported). Every seat has three curved betting boxes in concentric bands — +// PLAYER nearest the rail, then BANKER, then TIE — and the dealer row holds the +// PLAYER and BANKER card boxes. + +import { polar, project, toPolar, feltSector } from '../../ui/casino/CasinoGeometry.js'; +import { BET } from './BaccaratLogic.js'; + +export * from '../../ui/casino/CasinoGeometry.js'; + +export const CARD_W = 96; +export const CARD_H = 134; + +// Same seating as Blackjack: 0 = human bottom-centre, then outward-alternating. +export const SEAT_ANGLES = [0, 25, -25, 49, -49, 71, -71]; +export const DISPLAY_ORDER = [5, 3, 1, 0, 2, 4, 6]; + +// Concentric betting bands (table-space radii) and each box's half-width in degrees. +export const BANDS = { + [BET.PLAYER]: { r0: 0.846, r1: 0.952 }, + [BET.BANKER]: { r0: 0.732, r1: 0.836 }, + [BET.TIE]: { r0: 0.632, r1: 0.722 }, +}; +export const BOX_HALF_DEG = 10; +export const BET_TYPES = [BET.PLAYER, BET.BANKER, BET.TIE]; + +export const BET_META = { + [BET.PLAYER]: { label: 'PLAYER', short: 'P', color: 0x3d7fd6, hex: '#4a90d9', felt: '#5d9be6' }, + [BET.BANKER]: { label: 'BANKER', short: 'B', color: 0xd64545, hex: '#e05c5c', felt: '#ee6a6a' }, + [BET.TIE]: { label: 'TIE 8:1', short: 'T', color: 0x3aa35c, hex: '#5cb85c', felt: '#6cd08a' }, +}; + +const PORTRAITS = [ + { x: 160, y: 1013, r: 50 }, // 0 human — in the dock + { x: 1556, y: 812, r: 56 }, // 1 right-bottom + { x: 364, y: 812, r: 56 }, // 2 left-bottom + { x: 1786, y: 640, r: 56 }, // 3 right-mid + { x: 134, y: 640, r: 56 }, // 4 left-mid + { x: 1810, y: 330, r: 56 }, // 5 right-top + { x: 110, y: 330, r: 56 }, // 6 left-top +]; + +export function seatPortrait(seat) { + return { ...PORTRAITS[seat] }; +} + +// Centre of a seat's betting box (where its chips stack). +export function boxCenter(seat, type) { + const { r0, r1 } = BANDS[type]; + return polar((r0 + r1) / 2, SEAT_ANGLES[seat]); +} + +// Projected outline of a seat's betting box. +export function boxOutline(seat, type, inset = 0) { + const { r0, r1 } = BANDS[type]; + const th = SEAT_ANGLES[seat]; + return feltSector(r0 + inset, r1 - inset, th - BOX_HALF_DEG + inset * 40, th + BOX_HALF_DEG - inset * 40); +} + +// Which betting box (if any) is under a screen point? → { seat, type } | null +export function hitBox(x, y) { + const { r, theta, v } = toPolar(x, y); + if (v < 0) return null; + const type = BET_TYPES.find(t => r >= BANDS[t].r0 && r <= BANDS[t].r1); + if (!type) return null; + const seat = SEAT_ANGLES.findIndex(a => Math.abs(theta - a) <= BOX_HALF_DEG); + return seat === -1 ? null : { seat, type }; +} + +// ── Dealer row: PLAYER (left) and BANKER (right) card boxes ────────────────── +export const HAND_V = 0.245; +export const HAND_U = 0.21; +export const HAND_BOOST = 1.12; +export const CARD_GAP = 46; // px @ s between the first two cards + +export function handCenter(side) { + const p = project(side === 'player' ? -HAND_U : HAND_U, HAND_V); + return { ...p, s: p.s * HAND_BOOST }; +} + +// Pose of card i (0, 1 = the first two; 2 = the sideways third card). +export function handCardPose(side, i) { + const c = handCenter(side); + const out = side === 'player' ? -1 : 1; // third card sits on the outer side + if (i < 2) return { x: c.x + (i - 0.5) * CARD_GAP * c.s, y: c.y, rot: 0, s: c.s }; + return { x: c.x + out * (CARD_GAP / 2 + CARD_W * 0.5 + CARD_H * 0.45) * c.s, y: c.y + 4, rot: Math.PI / 2, s: c.s }; +} + +// The printed card box around both first cards (+ the third-card spot). +export function handBoxRect(side) { + const c = handCenter(side); + return { x: c.x, y: c.y, w: (CARD_W + CARD_GAP + 26) * c.s, h: (CARD_H + 18) * c.s * 0.9, s: c.s }; +} + +export const TOTAL_BADGE_DY = 92; // px @ s below the hand centre (just under the card box) + +// ── Furniture ──────────────────────────────────────────────────────────────── +export const SHOE = { u: 0.47, v: 0.085 }; +export const DISCARD = { u: -0.47, v: 0.085 }; +export const PLACARD = { u: -0.335, v: 0.035, lines: ['TABLE LIMITS', '$5 – $500'] }; + +export const FELT_TEXT = [ + { text: 'BANKER PAYS 19 TO 20 · TIE PAYS 8 TO 1', r: 0.565, size: 18, color: '#f2ead8', alpha: 0.75, spacing: 0.96 }, +]; + +// The tally readout panel (Equation Ribbon) sits between the hands and the seats. +export const READOUT = { x: 960, y: 430, w: 300, h: 110 }; + +// ── Scoreboard (standing LED board above the dealer edge, top-right) ───────── +export const BOARD = { x: 1342, y: 10, cell: 18, rows: 6, beadCols: 10, roadCols: 18, pad: 12, header: 28 }; +export function boardSize() { + const { cell, rows, beadCols, roadCols, pad, header } = BOARD; + return { w: pad * 3 + (beadCols + roadCols) * cell, h: header + rows * cell + pad * 2 }; +} diff --git a/src/games/blackjack/BlackjackArt.js b/src/games/blackjack/BlackjackArt.js new file mode 100644 index 0000000..abf6547 --- /dev/null +++ b/src/games/blackjack/BlackjackArt.js @@ -0,0 +1,65 @@ +// Blackjack table art. The shared casino kit (src/ui/casino/CasinoArt.js) bakes +// the rail, felt, lighting, cards, chips and dock; this file only supplies +// Blackjack's felt colour, markings, lettering and furniture. + +import { feltCircle } from '../../ui/casino/CasinoGeometry.js'; +import { prepareCasinoArt, bakeCasinoTable, poly, rr, CARD_W, CARD_H } from '../../ui/casino/CasinoArt.js'; +import { + polar, SEAT_ANGLES, BET_R, BET_SPOT_R, cardPose, VIEW, + FELT_TEXT, INSURANCE_LINES, TRAY, SHOE, DISCARD, PLACARD, +} from './BlackjackTable.js'; + +export { CARD_W, CARD_H, ensureCardBack } from '../../ui/casino/CasinoArt.js'; + +function drawMarkings(ctx) { + // Card spots + betting circles for all seven seats + SEAT_ANGLES.forEach((theta, seat) => { + const t = (theta * Math.PI) / 180; + const u = BET_R * Math.sin(t), v = BET_R * Math.cos(t); + poly(ctx, feltCircle(u, v, BET_SPOT_R)); + ctx.fillStyle = 'rgba(0,0,0,0.13)'; + ctx.fill(); + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(217,180,90,0.85)'; + ctx.stroke(); + poly(ctx, feltCircle(u, v, BET_SPOT_R * 0.8)); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(242,234,216,0.4)'; + ctx.stroke(); + + const pose = cardPose(seat, 0, 1, null, CARD_W); + ctx.save(); + ctx.translate(pose.x, pose.y); + ctx.rotate(pose.rot); + ctx.scale(pose.s, pose.s * VIEW.squash); + rr(ctx, -CARD_W / 2 - 14, -CARD_H / 2 - 8, CARD_W + 28, CARD_H + 16, 12); + ctx.lineWidth = 2 / pose.s; + ctx.strokeStyle = 'rgba(242,234,216,0.32)'; + ctx.stroke(); + ctx.restore(); + }); + + // Insurance band + const { r0, r1, span } = INSURANCE_LINES; + for (const r of [r0, r1]) { + const pts = []; + for (let d = -span; d <= span; d += 1) pts.push(polar(r, d)); + poly(ctx, pts, false); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(242,234,216,0.5)'; + ctx.stroke(); + } +} + +export async function prepareBlackjackArt(scene) { + await prepareCasinoArt(scene); + bakeCasinoTable(scene, 'bj-table', { + felt: '#0d5a2c', + markings: drawMarkings, + text: FELT_TEXT, + tray: TRAY, + shoe: SHOE, + discard: DISCARD, + placard: { ...PLACARD, lines: ['TABLE LIMITS', '$5 – $100'] }, + }); +} diff --git a/src/games/blackjack/BlackjackGame.js b/src/games/blackjack/BlackjackGame.js index ea21bf0..0d648cf 100644 --- a/src/games/blackjack/BlackjackGame.js +++ b/src/games/blackjack/BlackjackGame.js @@ -2,59 +2,66 @@ import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { Modal } from '../../ui/Modal.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { createOpponentPortrait } from '../../ui/Portrait.js'; import { api } from '../../services/api.js'; import { playSound, playChipBet, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { makeChipStack, throwChip as kitThrowChip, throwStack as kitThrowStack, settleStack as kitSettleStack } from '../../ui/CasinoChips.js'; +import { CasinoDock } from '../../ui/casino/CasinoDock.js'; +import { CardSkin } from '../../ui/casino/CasinoCards.js'; import { buildShoe, handValue, isBlackjack, isBust, canDouble, canSplit, createInitialState, prepareRound, applyBet, dealAllCards, applyInsurance, resolveInsurance, applyHit, applyStand, applyDouble, applySplit, - runDealerTurn, resolveRound, isPlayerDone, + resolveRound, isPlayerDone, } from './BlackjackLogic.js'; -import { chooseBet, chooseAction, chooseInsurance } from './BlackjackAI.js'; +import { chooseBet, chooseAction } from './BlackjackAI.js'; +import { + VIEW, project, seatLayout, cardPose, dealerCardPose, betPose, badgePose, insurancePose, + PLAY_ORDER, SHOE, DISCARD, TRAY, DOCK, +} from './BlackjackTable.js'; +import { prepareBlackjackArt, CARD_W } from './BlackjackArt.js'; -// ─── Layout ─────────────────────────────────────────────────────────────────── +// ─── Layout / tuning ────────────────────────────────────────────────────────── +// All table positions come from BlackjackTable.js (one perspective projection); +// the art is baked in BlackjackArt.js. This file is flow + animation. const CX = GAME_WIDTH / 2; -const CARD_W = 90; -const CARD_H = 126; -const CARD_R = 8; -const CARD_SPREAD = 28; // horizontal offset between stacked cards +const SQ = VIEW.squash; +const DOCK_Y = DOCK.y + DOCK.h / 2; +const MIN_BET = 5; +const MAX_BET = 100; +const CHIP_AMOUNTS = [5, 25, 50, 100]; +const CHIP_BTN = { x0: 470, dx: 88, size: 74 }; +const STACK_SIZE = 54; // chip diameter at perspective scale 1 +const HINTS_KEY = 'blackjack-hints'; -const DEALER_X = CX; -const DEALER_Y = 420; // ~1/3 down the table ellipse (top ≈190, bottom ≈890) - -// 7 seats fanned around the oval: seat 0 (human) anchored bottom-centre, -// 6 opponents fanned 3-per-side (filled outward-alternating so the table stays -// balanced when fewer than 6 opponents are chosen). -const SEAT_POS = [ - { x: CX, y: 782, portraitR: 72, portraitX: CX - 230, portraitY: 860, betX: 1110, betY: 770 }, // 0 Human (bottom centre) - { x: 1380, y: 710, portraitR: 58, portraitX: 1600, portraitY: 800 }, // 1 right-bottom - { x: 540, y: 710, portraitR: 58, portraitX: 320, portraitY: 800 }, // 2 left-bottom - { x: 1560, y: 588, portraitR: 58, portraitX: 1805, portraitY: 610 }, // 3 right-mid - { x: 360, y: 588, portraitR: 58, portraitX: 115, portraitY: 610 }, // 4 left-mid - { x: 1470, y: 410, portraitR: 58, portraitX: 1705, portraitY: 335, labelDX: 10 }, // 5 right-top - { x: 450, y: 410, portraitR: 58, portraitX: 215, portraitY: 335, labelDX: -10 }, // 6 left-top -]; - -// Turn order: start at the top-right seat and proceed clockwise around the table. -const PLAY_ORDER = [5, 3, 1, 0, 2, 4, 6]; - -// Large per-action callout shown between a player and their cards. const ACTION_LABELS = { hit: 'Hit', stand: 'Stand', double: 'Double', split: 'Split' }; const ACTION_COLORS = { hit: '#3cc6c0', stand: '#f5d020', double: '#ff8c00', split: '#b07cd6' }; -const CHIP_COLORS = { 5: 0xe05c5c, 25: 0x5cb85c, 50: 0x4a90d9, 100: 0x2c2c2c }; -const CHIP_TEXT_COLORS = { 5: '#ffffff', 25: '#ffffff', 50: '#ffffff', 100: '#ffffff' }; -const CHIP_AMOUNTS = [5, 25, 50, 100]; +const RESULT_LABELS = { win: 'Win!', blackjack: 'Blackjack!', push: 'Push', lose: 'Lose', bust: 'Bust' }; +const RESULT_COLORS = { win: '#f5d020', blackjack: '#ffe066', push: '#9aa5b4', lose: '#e05c5c', bust: '#e05c5c' }; +const RESULT_SIZES = { win: '54px', blackjack: '58px', push: '34px', lose: '48px', bust: '48px' }; +const RESULT_RANK = { blackjack: 4, win: 3, push: 2, lose: 1, bust: 1 }; -const D = { bg: -1, table: 0, cards: 10, chips: 20, ui: 30, modal: 50 }; - -const RESULT_COLORS = { - win: '#5cb85c', lose: '#e05c5c', push: '#8a94a6', - blackjack: '#f5d020', bust: '#e05c5c', +const D = { + bg: -2, playfield: -1, table: 0, cards: 10, stacks: 12, flying: 22, badges: 24, + dock: 26, ui: 30, dockUi: 32, prompt: 38, modal: 50, }; +const lerp = (a, b, t) => a + (b - a) * t; + +// Deterministic per-card jitter so cards look tossed but don't wobble on relayout. +function jitterFor(key) { + let h = 2166136261; + for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619); + const r = (n) => (((h >>> n) & 255) / 255) * 2 - 1; + return { rot: r(0) * 0.035, x: r(8) * 2, y: r(16) * 2 }; +} + +function readHints() { + try { return localStorage.getItem(HINTS_KEY) === '1'; } catch { return false; } +} + // ─── Scene ──────────────────────────────────────────────────────────────────── export default class BlackjackGame extends Phaser.Scene { constructor() { super('BlackjackGame'); } @@ -68,385 +75,195 @@ export default class BlackjackGame extends Phaser.Scene { async create() { new MusicPlayer(this, this.cache.json.get('music').tracks); - this.shoe = buildShoe(); + this.shoe = []; this.gs = null; - this.animating = false; + this.busy = false; this.pendingBet = 0; + this.lastBet = 0; this.portraits = []; - this.cardGraphics = {}; // seat → array of Phaser.Container - this.dealerCardGraphics = []; - this.betGraphics = {}; // seat → Phaser.Container - this.bustedSeats = new Set(); - this.actionBtns = []; - this.bettingUIGroup = []; - this.chipBtnGraphics = []; - this.betDisplayText = null; - this.balanceText = null; - this.scoreTxts = {}; - this.dealerScoreTxt = null; - this.statusBadges = {}; + this.cards = new Map(); // key → card container ('seat:hand:idx' or 'd:idx') + this.badges = {}; // key → hand-total badge container + this.stacks = {}; // key → chip stack container ('seat:hand' or 'seat:ins') + this.settled = new Set(); // stack keys already paid / swept this round + this.pendingStacks = new Set(); // stack keys still in flight (don't draw yet) + this.bustedHands = new Set(); // 'seat:hand' + this.hideBadges = false; + this.playActions = null; + this.insuranceChoice = null; this.nameTxts = {}; this.chipTxts = {}; - this.bettingPromptGroup = []; - this.bettingPromptTimer = null; - this.chipPulseTweens = []; + this.dockMode = null; + this.hintsOn = readHints(); this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); this.buildPlayfield(); - this.buildTable(); - this.buildTableMarkings(); + + await prepareBlackjackArt(this); + if (!this.sys.isActive()) return; + this.skin = new CardSkin(this, this.cardBack, { depth: D.cards }); + + this.add.image(0, 0, 'bj-table').setOrigin(0, 0).setDepth(D.table); this.buildDealerArea(); this.buildSeats(); - this.buildBettingUI(); + this.buildDock(); - new Button(this, 80, GAME_HEIGHT - 44, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 140, fontSize: 20, - }); + new Button(this, 84, 44, 'Leave', () => this.scene.start('GameMenu'), { + variant: 'ghost', width: 140, height: 48, fontSize: 20, + }).setDepth(D.ui); + + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); await this.loadPlayerChips(); - this.initGame(); + if (!this.sys.isActive()) return; + this.gs = createInitialState(this.opponents, this._playerChips); + this.startNewRound(); } - // ── Playfield background ───────────────────────────────────────────────── + // ── Small async helpers ──────────────────────────────────────────────────── + wait(ms) { + return new Promise(res => this.time.delayedCall(ms, res)); + } + + tweenP(cfg) { + return new Promise(res => { + this.tweens.add({ ...cfg, onComplete: (...a) => { cfg.onComplete?.(...a); res(); } }); + }); + } + + // ── Static scenery ───────────────────────────────────────────────────────── buildPlayfield() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { this.add.image(CX, GAME_HEIGHT / 2, pf.key) .setDisplaySize(GAME_WIDTH, GAME_HEIGHT) - .setDepth(D.bg + 1); + .setDepth(D.playfield); } } - // ── Table ───────────────────────────────────────────────────────────────── - buildTable() { - const g = this.add.graphics().setDepth(D.table); - g.fillStyle(0x1a5c2a, 1); - g.fillEllipse(CX, 540, 1500, 700); - g.lineStyle(8, 0x2e7d32, 1); - g.strokeEllipse(CX, 540, 1500, 700); - // Inner stripe - g.lineStyle(3, 0x4caf50, 0.4); - g.strokeEllipse(CX, 540, 1440, 640); - } - - // ── Traditional felt markings ─────────────────────────────────────────────── - // White card-deal outlines + bet circles for every seat (drawn for all 7 so - // unoccupied seats still show open spots), plus curved felt lettering. - buildTableMarkings() { - const g = this.add.graphics().setDepth(D.table + 1); - - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const pos = SEAT_POS[seat]; - g.lineStyle(2, 0xffffff, 0.5); - g.strokeRoundedRect( - pos.x - CARD_W / 2 - 4, pos.y - CARD_H / 2 - 4, - CARD_W + 8, CARD_H + 8, CARD_R + 2, - ); - const { x: bx, y: by } = this.betCirclePos(seat); - g.lineStyle(2, 0xffffff, 0.55); - g.strokeCircle(bx, by, 30); - } - - // Curved insurance line + label (concentric with the text arc) - const insBaseY = 512, insRadius = 820; - const insCx = CX, insCy = insBaseY - insRadius; - const insSpan = 0.34; - g.lineStyle(3, 0xffffff, 0.45); - g.beginPath(); - g.arc(insCx, insCy, insRadius + 16, Math.PI / 2 - insSpan, Math.PI / 2 + insSpan, false); - g.strokePath(); - this.drawArcText('INSURANCE PAYS 2 TO 1', insCx, insBaseY, insRadius, { - fontSize: 20, color: COLORS.textHex, advanceFactor: 0.95, - }); - - this.drawArcText('BLACKJACK PAYS 3 TO 2', CX, 610, 760, { - fontSize: 30, color: COLORS.goldHex, bold: true, advanceFactor: 0.98, - }); - - this.drawArcText('DEALER MUST STAND ON ALL 17s · DRAW TO 16', CX, 668, 720, { - fontSize: 19, color: COLORS.mutedHex, advanceFactor: 0.86, - }); - } - - // Draws a string along a downward-bulging arc, glyph by glyph (Phaser has no - // native curved text). (centerX, baseY) is where the middle of the text sits; - // the line curves upward toward both ends. - drawArcText(text, centerX, baseY, radius, opts = {}) { - const fontSize = opts.fontSize ?? 24; - const anglePer = ((opts.advanceFactor ?? 0.92) * fontSize) / radius; - const cy = baseY - radius; // circle centre, above the text - const start = -anglePer * (text.length - 1) / 2; - const style = { - fontFamily: opts.fontFamily ?? '"Julius Sans One"', - fontSize: `${fontSize}px`, - color: opts.color ?? COLORS.textHex, - ...(opts.bold ? { fontStyle: 'bold' } : {}), - }; - const depth = opts.depth ?? (D.table + 1); - for (let i = 0; i < text.length; i++) { - const ch = text[i]; - if (ch === ' ') continue; - const a = start + i * anglePer; // offset from straight-down - this.add.text(centerX + radius * Math.sin(a), cy + radius * Math.cos(a), ch, style) - .setOrigin(0.5) - .setRotation(-a) - .setDepth(depth); - } - } - - // ── Dealer area ─────────────────────────────────────────────────────────── buildDealerArea() { - this.add.text(CX, 60, 'Blackjack', { - fontFamily: 'Righteous', fontSize: '52px', color: COLORS.textHex, + this.add.text(CX, 52, 'Blackjack', { + fontFamily: 'Righteous', fontSize: '48px', color: COLORS.textHex, + shadow: { offsetX: 0, offsetY: 3, color: '#000000', blur: 10, fill: true }, }).setOrigin(0.5).setDepth(D.ui); - this.dealerScoreTxt = this.add.text(CX, DEALER_Y - CARD_H / 2 - 22, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); + const shoe = project(SHOE.u, SHOE.v); + this.shoePos = { x: shoe.x - 66 * shoe.s, y: shoe.y - 4 * shoe.s, s: shoe.s * 0.9 }; + const disc = project(DISCARD.u, DISCARD.v); + this.discardPos = { x: disc.x, y: disc.y - 6 * disc.s, s: disc.s * 0.85 }; + const tray = project((TRAY.u0 + TRAY.u1) / 2, (TRAY.v0 + TRAY.v1) / 2); + this.trayPos = { x: tray.x, y: tray.y, s: tray.s }; } - // ── Seat labels & portraits ─────────────────────────────────────────────── buildSeats() { - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const pos = SEAT_POS[seat]; - const player = seat === 0 - ? { name: 'You', isHuman: true, active: true } - : { name: this.opponents[seat - 1]?.name ?? '', isHuman: false, active: seat <= this.opponents.length }; - - if (!player.active) continue; - - // Portrait centre - const px = pos.portraitX ?? pos.x; - const py = pos.portraitY ?? (seat === 0 ? pos.y : pos.y - CARD_H / 2 - pos.portraitR - 68); - - // Name + bankroll stacked, centred under the portrait - const labelX = px + (pos.labelDX ?? 0); - const nameY = py + pos.portraitR + 18; + for (let seat = 1; seat <= 6; seat++) { + const opp = this.opponents[seat - 1]; + if (!opp) continue; + const pt = seatLayout(seat).portrait; + const nameY = pt.y + pt.r + 18; const chipY = nameY + 24; - this.nameTxts[seat] = this.add.text(labelX, nameY, player.name, { + this.nameTxts[seat] = this.add.text(pt.x, nameY, opp.name ?? '', { fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, }).setOrigin(0.5).setDepth(D.ui); - - this.chipTxts[seat] = this.add.text(labelX, chipY, '', { + this.chipTxts[seat] = this.add.text(pt.x, chipY, '', { fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, }).setOrigin(0.5).setDepth(D.ui); - // Semi-transparent backing behind both text lines, depth below portrait images/videos - { - const maxTW = Math.max(this.nameTxts[seat].width, 130); - const rectW = maxTW + 20; - const rectH = (chipY - nameY) + 36; - const bg = this.add.graphics().setDepth(D.ui - 1); - bg.fillStyle(0x000000, 0.60); - bg.fillRoundedRect(labelX - rectW / 2, (nameY + chipY) / 2 - rectH / 2, rectW, rectH, 6); - } + const rectW = Math.max(this.nameTxts[seat].width, 130) + 20; + const rectH = (chipY - nameY) + 36; + const bg = this.add.graphics().setDepth(D.ui - 1); + bg.fillStyle(0x000000, 0.6); + bg.fillRoundedRect(pt.x - rectW / 2, (nameY + chipY) / 2 - rectH / 2, rectW, rectH, 6); - this.scoreTxts[seat] = this.add.text(pos.x, pos.y - CARD_H / 2 - 11, '', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - // Portraits - if (seat === 0) { - this.portraits[seat] = createPlayerPortrait(this, px, py, pos.portraitR, D.ui, 'BlackjackGame'); - } else { - this.portraits[seat] = createOpponentPortrait(this, this.opponents[seat - 1], px, py, pos.portraitR, D.ui); - } + this.portraits[seat] = createOpponentPortrait(this, opp, pt.x, pt.y, pt.r, D.ui); } } - // ── Betting UI (human only) ─────────────────────────────────────────────── - buildBettingUI() { - const y = GAME_HEIGHT - 80; - const cx = CX + 60; // shift right slightly to avoid portrait - - // Solid window behind all the betting controls (shown between rounds) - const panel = this.add.graphics().setDepth(D.ui); - panel.fillStyle(0x000000, 1); - panel.fillRoundedRect(cx - 174, y - 69, 726, 116, 18); - panel.lineStyle(3, COLORS.accent, 1); - panel.strokeRoundedRect(cx - 174, y - 69, 726, 116, 18); - this.bettingUIGroup.push(panel); - - // Chip buttons - CHIP_AMOUNTS.forEach((amt, i) => { - const bx = cx - 120 + i * 80; - const container = this.add.container(bx, y).setDepth(D.ui + 1); - const g = this.add.graphics(); - g.lineStyle(3, 0xffffff, 0.4); - g.strokeCircle(0, 0, 28); - g.fillStyle(CHIP_COLORS[amt], 1); - g.fillCircle(0, 0, 28); - container.add(g); - container.setInteractive(new Phaser.Geom.Circle(0, 0, 28), Phaser.Geom.Circle.Contains); - container.on('pointerdown', () => this.onChipClick(amt)); - container.on('pointerover', () => container.setAlpha(0.8)); - container.on('pointerout', () => container.setAlpha(1)); - - const t = this.add.text(bx, y, `$${amt}`, { - fontFamily: '"Julius Sans One"', fontSize: '13px', - color: CHIP_TEXT_COLORS[amt], fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.ui + 2); - - this.bettingUIGroup.push(g, t); - this.chipBtnGraphics.push(g); + // ── HUD dock ─────────────────────────────────────────────────────────────── + buildDock() { + this.dock = new CasinoDock(this, { + sceneName: 'BlackjackGame', + portrait: seatLayout(0).portrait, + depth: { dock: D.dock, ui: D.ui, dockUi: D.dockUi, prompt: D.prompt }, + chipAmounts: CHIP_AMOUNTS, chipX0: CHIP_BTN.x0, chipDX: CHIP_BTN.dx, chipSize: CHIP_BTN.size, + betPillX: 850, + keys: { + bet: '1–4 add chips · Space deal / rebet · R rebet · C clear', + play: 'H hit · S stand · D double · P split', + insurance: 'Y take insurance · N decline', + next: 'Space next round · R rebet & deal', + }, + canChip: (amt) => this.chipAffordable(amt), + onChip: (amt) => this.onChipClick(amt), }); + this.portraits[0] = this.dock.portrait; + this.nameTxts[0] = this.dock.nameTxt; + this.chipTxts[0] = this.dock.balanceTxt; + this.chipBtns = this.dock.chipBtns; + this.betPill = this.dock.betPill; - this.betDisplayText = this.add.text(cx + 170, y, 'Bet: $0', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui + 1); - - this.balanceText = this.add.text(cx + 170, y - 32, '', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.ui + 1); - - const clearBtn = new Button(this, cx + 360, y, 'Clear', () => this.onClearBet(), { - width: 100, height: 50, fontSize: 18, variant: 'ghost', + const btnOpts = { width: 116, height: 50, fontSize: 18, variant: 'ghost' }; + this.clearBtn = new Button(this, 1080, DOCK_Y, 'Clear', () => this.onClearBet(), btnOpts); + this.rebetBtn = new Button(this, 1204, DOCK_Y, 'Rebet', () => this.onRebet(1), btnOpts); + this.rebet2Btn = new Button(this, 1328, DOCK_Y, 'Rebet x2', () => this.onRebet(2), btnOpts); + this.dealBtn = new Button(this, 1474, DOCK_Y, 'Deal', () => this.onDealClick(), { + width: 150, height: 56, fontSize: 24, }); - this.dealBtn = new Button(this, cx + 470, y, 'Deal', () => this.onDealClick(), { - width: 110, height: 50, fontSize: 20, - }); - this.dealBtn.setEnabled(false); - // Keep the buttons above the betting window panel - clearBtn.setDepth(D.ui + 1); - this.dealBtn.setDepth(D.ui + 1); + for (const b of [this.clearBtn, this.rebetBtn, this.rebet2Btn, this.dealBtn]) b.setDepth(D.dockUi); + this.dock.addToGroup('bet', this.clearBtn, this.rebetBtn, this.rebet2Btn, this.dealBtn); - this.bettingUIGroup.push(this.betDisplayText, this.balanceText, clearBtn, this.dealBtn); - this.hideBettingUI(); + this.hintBtn = new Button(this, 1800, DOCK_Y, this.hintLabel(), () => this.toggleHints(), { + width: 170, height: 44, fontSize: 16, variant: 'ghost', + }).setDepth(D.dockUi); } - showBettingUI() { - for (const o of this.bettingUIGroup) o.setVisible?.(true) || (o.visible = true); - this.chipBtnGraphics.forEach(g => g.setDepth(D.ui + 1)); - this.startBettingPrompts(); - } - hideBettingUI() { - for (const o of this.bettingUIGroup) o.setVisible?.(false) || (o.visible = false); - this.hideBettingPrompts(); + hintLabel() { return this.hintsOn ? 'Hints: On' : 'Hints: Off'; } + + toggleHints() { + this.hintsOn = !this.hintsOn; + try { localStorage.setItem(HINTS_KEY, this.hintsOn ? '1' : '0'); } catch { /* private mode */ } + this.hintBtn.setLabel(this.hintLabel()); + if (this.dockMode === 'play') this.showActionButtons(); } - startBettingPrompts() { - this.hideBettingPrompts(); - - // Wait 5 seconds before starting any animations - this.bettingPromptTimer = this.time.delayedCall(5000, () => { - if (!this.scene.isActive('BlackjackGame')) return; - if (this.pendingBet > 0) return; // Don't start if already betting - - // Start subtle radius pulsing animation - this.chipBtnGraphics.forEach((chip, index) => { - const delay = index * 200; - const tween = this.tweens.add({ - targets: chip, - scaleX: 1.25, - scaleY: 1.25, - duration: 1200, - ease: 'Sine.easeInOut', - yoyo: true, - repeat: -1, - delay: delay, - }); - this.chipPulseTweens.push(tween); - }); - - // Show prompt text - this.showBettingPrompt(); - }); + // mode: 'bet' | 'play' | 'insurance' | 'next' | 'wait' + setDockMode(mode, status = '') { + this.dockMode = mode; + this.playActions = null; + this.insuranceChoice = null; + this.dock.setMode(mode, mode === 'wait' ? status : ''); + if (mode === 'bet') this.updateBetDisplay(); } - showBettingPrompt() { - if (this.pendingBet > 0) return; // Don't show if already betting - - const y = GAME_HEIGHT - 160; - const cx = CX; - - // Create semi-transparent background - const bg = this.add.rectangle(cx + 100, y, 420, 60, 0x000000, 0.7) - .setOrigin(0.5, 0.5) - .setDepth(D.ui + 10) - .setAlpha(0); - - // Create prompt text - const text = this.add.text(cx + 100, y, 'Choose an amount to bet and click Deal to begin', { - fontFamily: '"Julius Sans One"', - fontSize: '18px', - color: '#ffffff', - align: 'center', - }) - .setOrigin(0.5, 0.5) - .setDepth(D.ui + 11) - .setAlpha(0); - - this.bettingPromptGroup = [bg, text]; - - // Fade in - this.tweens.add({ - targets: bg, - alpha: 0.7, - duration: 300, - ease: 'Power2', - }); - - this.tweens.add({ - targets: text, - alpha: 1, - duration: 300, - ease: 'Power2', - delay: 100, - }); - } - - hideBettingPrompts() { - // Fade out prompt if visible - if (this.bettingPromptGroup && this.bettingPromptGroup.length > 0) { - this.tweens.add({ - targets: this.bettingPromptGroup, - alpha: 0, - duration: 200, - ease: 'Power2', - onComplete: () => { - this.bettingPromptGroup.forEach(obj => obj.destroy()); - this.bettingPromptGroup = []; - } - }); - } else if (this.bettingPromptGroup.length > 0) { - this.bettingPromptGroup.forEach(obj => obj.destroy()); - this.bettingPromptGroup = []; - } - - // Stop chip pulsing - this.chipPulseTweens.forEach(tween => tween.destroy()); - this.chipPulseTweens = []; - this.chipBtnGraphics.forEach(chip => { - chip.setScale(1, 1); - chip.setAlpha(1); - }); - - // Clear timer - if (this.bettingPromptTimer) { - this.bettingPromptTimer.remove(); - this.bettingPromptTimer = null; + // ── Keyboard ─────────────────────────────────────────────────────────────── + onKey(e) { + if (!this.gs) return; + const k = (e.key ?? '').toLowerCase(); + switch (this.dockMode) { + case 'play': + this.playActions?.[k]?.(); + break; + case 'bet': + if (k === ' ' || k === 'enter') { + if (this.pendingBet >= MIN_BET) this.onDealClick(); else this.onRebet(1); + } else if (k === 'r') this.onRebet(1); + else if (k === 'c' || k === 'backspace') this.onClearBet(); + else if (['1', '2', '3', '4'].includes(k)) this.onChipClick(CHIP_AMOUNTS[Number(k) - 1]); + break; + case 'insurance': + if (k === 'y') this.insuranceChoice?.(true); + else if (k === 'n') this.insuranceChoice?.(false); + break; + case 'next': + if (k === ' ' || k === 'enter') this.onNextRound(false); + else if (k === 'r') this.onNextRound(true); + break; + default: + break; } } - startBettingPromptsIfNoBet() { - // Only start prompts if no bet has been placed yet - if (this.pendingBet === 0) { - this.startBettingPrompts(); - } - } - - hideBettingUI() { - for (const o of this.bettingUIGroup) { - o.setVisible?.(false) || (o.visible = false); - } - this.hideBettingPrompts(); - // Also hide chip containers from the betting UI - this.chipBtnGraphics.forEach(g => g.setVisible?.(false) || (g.visible = false)); - this.chipBtnGraphics.forEach(g => g.setDepth(-100)); - } - - // ── Chip balance ────────────────────────────────────────────────────────── + // ── Chip balance ─────────────────────────────────────────────────────────── async loadPlayerChips() { try { const { profile } = await api.get('/profile'); @@ -456,442 +273,1039 @@ export default class BlackjackGame extends Phaser.Scene { } } - // ── Game init ───────────────────────────────────────────────────────────── - initGame() { - this.gs = createInitialState(this.opponents, this._playerChips); - this.startNewRound(); + async updateServerChips() { + const human = this.gs.players[0]; + const delta = human.chipsWon ?? 0; + if (delta === 0) return; + try { + await api.post('/profile/chips/adjust', { delta }); + } catch { /* balance will resync next load */ } } - startNewRound() { - if (this.shoe.length < 52) this.shoe = buildShoe(); - playSound(this, SFX.CARD_SHUFFLE); - this.pendingBet = 0; - this.bustedSeats = new Set(); - this.gs = prepareRound(this.gs); - this.clearCardGraphics(); + // ── Round lifecycle ──────────────────────────────────────────────────────── + async startNewRound() { + this.setDockMode('wait', ''); this.clearActiveHighlight(); - this.renderAll(); - this.showBettingUI(); - this.updateBetDisplay(); - } - - // ── Render ──────────────────────────────────────────────────────────────── - renderAll() { - this.renderDealer(); - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (!p.active) continue; - this.renderSeatCards(seat); - this.renderSeatInfo(seat); + this.hideBadges = true; + this.updateBadges(); + await this.sweepTable(); + if (this.shoe.length < 52) { + this.shoe = buildShoe(); + await this.animateReshuffle(); } + this.pendingBet = 0; + this.settled.clear(); + this.pendingStacks.clear(); + this.bustedHands.clear(); + this.gs = prepareRound(this.gs); + this.hideBadges = false; + this.renderSeatInfo(); this.renderBetAreas(); + this.updateBadges(); + this.setDockMode('bet'); + this.startBettingPrompts(); } - renderDealer() { - // Destroy old dealer cards - for (const c of this.dealerCardGraphics) c.destroy(); - this.dealerCardGraphics = []; - - const hand = this.gs.dealer.hand; - if (hand.length === 0) { - this.dealerScoreTxt.setText(''); - return; + // Cards slide into the discard holder; any leftover stacks fade. + async sweepTable() { + for (const st of Object.values(this.stacks)) { + this.tweens.add({ targets: st, alpha: 0, duration: 200, onComplete: () => st.destroy() }); } - - hand.forEach((card, i) => { - const x = this.cardX(DEALER_X, i, hand.length); - const cont = this.add.container(x, DEALER_Y).setDepth(D.cards); - const faceUp = i === 0 || this.gs.dealer.revealed; - this.drawCard(cont, faceUp ? card : null, faceUp); - this.dealerCardGraphics.push(cont); + this.stacks = {}; + const all = [...this.cards.values()]; + this.cards.clear(); + if (!all.length) return; + playSound(this, SFX.CARD_PLACE); + const d = this.discardPos; + all.forEach((c, i) => { + c.setDepth(D.flying); + this.tweens.add({ + targets: c, + x: d.x + (Math.random() - 0.5) * 6, + y: d.y, + rotation: (Math.random() - 0.5) * 0.08, + scaleX: d.s, + scaleY: d.s * SQ, + alpha: { value: 0, ease: 'Expo.easeIn' }, + duration: 420, + delay: i * 22, + ease: 'Cubic.easeInOut', + onComplete: () => c.destroy(), + }); }); - - const revealed = this.gs.dealer.revealed; - const { score, soft } = handValue(revealed ? hand : [hand[0]]); - const bust = revealed && score > 21; - this.dealerScoreTxt.setText( - bust ? 'BUST' : `${soft && score < 21 ? 'Soft ' : ''}${score}` - ); - this.dealerScoreTxt.setColor(bust ? COLORS.dangerHex : COLORS.textHex); + await this.wait(440 + all.length * 22); } - renderSeatCards(seat) { - if (this.cardGraphics[seat]) { - for (const c of this.cardGraphics[seat]) c.destroy(); - } - this.cardGraphics[seat] = []; + async animateReshuffle() { + const banner = this.add.container(CX, 360).setDepth(D.prompt).setAlpha(0); + const t = this.add.text(0, 0, 'Shuffling a fresh shoe…', { + fontFamily: '"Julius Sans One"', fontSize: '26px', color: '#f7ecd0', + }).setOrigin(0.5); + const bg = this.add.graphics(); + bg.fillStyle(0x0b0806, 0.82); + bg.fillRoundedRect(-t.width / 2 - 28, -28, t.width + 56, 56, 28); + bg.lineStyle(2, COLORS.accent, 0.8); + bg.strokeRoundedRect(-t.width / 2 - 28, -28, t.width + 56, 56, 28); + banner.add([bg, t]); + this.tweens.add({ targets: banner, alpha: 1, duration: 220 }); + playSound(this, SFX.CARD_SHUFFLE); - const p = this.gs.players[seat]; - const pos = SEAT_POS[seat]; - - // Main hand - const h1Offset = p.hand2 ? -80 : 0; - p.hand.forEach((card, i) => { - const x = this.cardX(pos.x + h1Offset, i, p.hand.length); - const cont = this.add.container(x, pos.y).setDepth(D.cards); - this.drawCard(cont, card, true); - this.cardGraphics[seat].push(cont); - }); - - // Split hand - if (p.hand2) { - p.hand2.forEach((card, i) => { - const x = this.cardX(pos.x + 80, i, p.hand2.length); - const cont = this.add.container(x, pos.y).setDepth(D.cards); - this.drawCard(cont, card, true); - this.cardGraphics[seat].push(cont); + // Riffle: two packets fan out beside the shoe and zip back in. + const sp = this.shoePos; + const cards = []; + for (let i = 0; i < 14; i++) { + const c = this.makeCardSprite(null, false, sp.x, sp.y, sp.s, 0); + c.setDepth(D.flying + i); + cards.push(c); + const left = i % 2 === 0; + const k = Math.floor(i / 2); + this.tweens.add({ + targets: c, + x: sp.x + (left ? -150 : -60) + k * 3, + y: sp.y + 46 - k * 2, + rotation: (left ? -0.22 : 0.22) + (k - 3) * 0.02, + duration: 260, delay: i * 18, ease: 'Cubic.easeOut', + onComplete: () => { + this.tweens.add({ + targets: c, x: sp.x - 105, y: sp.y + 40 - i * 0.8, rotation: 0, + duration: 180, delay: 260 + (13 - i) * 22, ease: 'Sine.easeIn', + onComplete: () => { + this.tweens.add({ + targets: c, x: sp.x, y: sp.y, alpha: 0, + duration: 220, delay: 240, ease: 'Cubic.easeIn', + onComplete: () => c.destroy(), + }); + }, + }); + }, }); } + await this.wait(1350); + await this.tweenP({ targets: banner, alpha: 0, duration: 220 }); + banner.destroy(); + } - // Score - const { score, soft } = handValue(p.hand); - const bust = score > 21; - const bj = isBlackjack(p.hand); - let scoreStr = bj ? 'BJ' : (bust ? 'BUST' : `${soft && score < 21 ? 'soft ' : ''}${score}`); - if (p.hand2) { - const { score: s2, soft: sf2 } = handValue(p.hand2); - const b2 = s2 > 21; - const bj2 = isBlackjack(p.hand2); - scoreStr += ` / ${bj2 ? 'BJ' : (b2 ? 'BUST' : `${sf2 && s2 < 21 ? 'soft ' : ''}${s2}`)}`; - } - if (this.scoreTxts[seat]) this.scoreTxts[seat].setText(p.hand.length ? scoreStr : ''); + // ── Card sprites ─────────────────────────────────────────────────────────── + makeCardSprite(card, faceUp, x, y, s, rot) { + return this.skin.make(card, faceUp, x, y, s, rot); + } - // Keep busted cards faded across re-renders - if (this.bustedSeats?.has(seat)) { - for (const c of this.cardGraphics[seat]) c.setAlpha(0.3); + setFace(c, faceUp) { + this.skin.setFace(c, faceUp); + } + + handOf(p, h) { return h === 1 ? p.hand2 : p.hand; } + + targetPose(seat, h, i) { + const p = this.gs.players[seat]; + const split = p.hand2 !== null; + const hand = this.handOf(p, h); + const pose = cardPose(seat, i, hand.length, split ? h : null, CARD_W); + const doubled = h === 1 ? p.doubled2 : p.doubled; + if (doubled && hand.length === 3 && i === 2) pose.rot += Math.PI / 2; // double-down card goes sideways + const j = jitterFor(`${seat}:${h}:${i}`); + return { ...pose, x: pose.x + j.x, y: pose.y + j.y, rot: pose.rot + j.rot }; + } + + dealerPose(i, total) { + const pose = dealerCardPose(i, total); + const j = jitterFor(`d:${i}`); + return { ...pose, x: pose.x + j.x, y: pose.y + j.y, rot: pose.rot + j.rot }; + } + + tweenToPose(c, pose, duration = 220, alpha) { + this.tweens.add({ + targets: c, x: pose.x, y: pose.y, rotation: pose.rot, + scaleX: pose.s, scaleY: pose.s * SQ, + ...(alpha !== undefined ? { alpha } : {}), + duration, ease: 'Cubic.easeOut', + }); + } + + layoutSeat(seat, duration = 220) { + const p = this.gs.players[seat]; + for (const h of p.hand2 !== null ? [0, 1] : [0]) { + const hand = this.handOf(p, h) ?? []; + const faded = this.bustedHands.has(`${seat}:${h}`); + hand.forEach((_, i) => { + const c = this.cards.get(`${seat}:${h}:${i}`); + if (!c || c.flying) return; + this.tweenToPose(c, this.targetPose(seat, h, i), duration, faded ? 0.35 : 1); + }); } } - renderSeatInfo(seat) { + layoutDealer(duration = 220) { + const hand = this.gs.dealer.hand; + hand.forEach((_, i) => { + const c = this.cards.get(`d:${i}`); + if (c && !c.flying) this.tweenToPose(c, this.dealerPose(i, hand.length), duration); + }); + } + + // A card flies out of the shoe with a lift, flipping face-up mid-air if needed. + dealCard(key, card, faceUp, pose, duration = 320) { + const { c, promise } = this.skin.deal(card, faceUp, this.shoePos, pose, { + duration, flyingDepth: D.flying, sound: () => playSound(this, SFX.CARD_DEAL), + }); + this.cards.set(key, c); + return promise; + } + + flipCard(c, faceUp, duration = 300) { + return this.skin.flip(c, faceUp, duration); + } + + async dealToSeat(seat, h, i) { const p = this.gs.players[seat]; - if (this.chipTxts[seat]) this.chipTxts[seat].setText(`$${p.chips.toLocaleString()}`); - // Highlight current player - if (this.nameTxts[seat]) { - this.nameTxts[seat].setColor(p.seat === this.gs.currentSeat && this.gs.phase === 'player_turn' - ? COLORS.accentHex : COLORS.textHex); + const card = this.handOf(p, h)[i]; + this.layoutSeat(seat); + await this.dealCard(`${seat}:${h}:${i}`, card, true, this.targetPose(seat, h, i)); + } + + async dealToDealer(i, faceUp) { + const hand = this.gs.dealer.hand; + this.layoutDealer(); + await this.dealCard(`d:${i}`, hand[i], faceUp, this.dealerPose(i, hand.length)); + } + + // Safety net: make sure every card in state has a sprite and nothing stale lingers. + syncCards() { + const live = new Set(); + for (const p of this.gs.players) { + if (!p.active) continue; + for (const h of p.hand2 !== null ? [0, 1] : [0]) { + (this.handOf(p, h) ?? []).forEach((card, i) => { + const key = `${p.seat}:${h}:${i}`; + live.add(key); + if (!this.cards.has(key)) { + const pose = this.targetPose(p.seat, h, i); + this.cards.set(key, this.makeCardSprite(card, true, pose.x, pose.y, pose.s, pose.rot)); + } + }); + } } + const dh = this.gs.dealer.hand; + dh.forEach((card, i) => { + const key = `d:${i}`; + live.add(key); + if (!this.cards.has(key)) { + const pose = this.dealerPose(i, dh.length); + this.cards.set(key, this.makeCardSprite(card, i === 0 || this.gs.dealer.revealed, pose.x, pose.y, pose.s, pose.rot)); + } + }); + for (const [key, c] of this.cards) { + if (!live.has(key) && !c.flying) { c.destroy(); this.cards.delete(key); } + } + } + + // ── Hand-total badges ────────────────────────────────────────────────────── + handInfo(hand, live) { + const { score, soft } = handValue(hand); + if (isBlackjack(hand)) return { text: 'BLACKJACK', state: 'bj' }; + if (score > 21) return { text: `BUST ${score}`, state: 'bust' }; + if (score === 21) return { text: '21', state: 'gold' }; + if (soft && live) return { text: `${score - 10} / ${score}`, state: 'normal' }; + return { text: `${score}`, state: 'normal' }; + } + + updateBadges() { + const want = new Map(); + if (this.gs && !this.hideBadges) { + const turn = this.gs.phase === 'player_turn'; + for (const p of this.gs.players) { + if (!p.active) continue; + const split = p.hand2 !== null; + for (const h of split ? [0, 1] : [0]) { + const hand = this.handOf(p, h); + if (!hand?.length) continue; + const status = h === 1 ? p.status2 : p.status; + const live = turn && (status === 'playing' || status === 'waiting' || status === null); + const active = turn && this.gs.currentSeat === p.seat && p.activeHand === h; + want.set(`${p.seat}:${h}`, { ...badgePose(p.seat, split ? h : null), ...this.handInfo(hand, live), active }); + } + } + const dh = this.gs.dealer.hand; + if (dh.length) { + const shown = this.gs.dealer.revealed ? dh : [dh[0]]; + const first = dealerCardPose(0, dh.length); + want.set('d', { + x: first.x - (CARD_W * first.s) / 2 - 56, y: first.y, s: first.s + 0.1, + ...this.handInfo(shown, false), active: false, + }); + } + } + for (const key of Object.keys(this.badges)) { + if (!want.has(key)) { this.badges[key].destroy(); delete this.badges[key]; } + } + for (const [key, b] of want) { + let c = this.badges[key]; + if (!c) { + c = this.add.container(b.x, b.y).setDepth(D.badges); + c.g = this.add.graphics(); + c.t = this.add.text(0, 0, '', { + fontFamily: '"Julius Sans One"', fontSize: '20px', color: '#f7ecd0', fontStyle: 'bold', + }).setOrigin(0.5); + c.add([c.g, c.t]); + c.setAlpha(0); + this.tweens.add({ targets: c, alpha: 1, duration: 180 }); + this.badges[key] = c; + } + this.drawBadge(c, b); + } + } + + drawBadge(c, b) { + c.setPosition(b.x, b.y).setScale(Math.min(1.05, b.s + 0.12)); + const STYLE = { + normal: { fill: 0x0b0906, alpha: 0.85, text: '#f7ecd0', stroke: 0xc8a84b }, + gold: { fill: 0xd4a017, alpha: 1, text: '#1a1208', stroke: 0xfff1b0 }, + bj: { fill: 0xf5d020, alpha: 1, text: '#1a1208', stroke: 0xffffff }, + bust: { fill: 0xa8231c, alpha: 0.95, text: '#ffffff', stroke: 0xff8a80 }, + }[b.state]; + c.t.setText(b.text).setColor(STYLE.text); + const w = c.t.width + 26, h = 32; + c.g.clear(); + if (b.state === 'bj' || b.state === 'gold') { + c.g.fillStyle(STYLE.fill, 0.25); + c.g.fillRoundedRect(-w / 2 - 6, -h / 2 - 6, w + 12, h + 12, 20); + } + c.g.fillStyle(STYLE.fill, STYLE.alpha); + c.g.fillRoundedRect(-w / 2, -h / 2, w, h, 16); + c.g.lineStyle(b.active ? 3 : 1.5, b.active ? 0xf5d020 : STYLE.stroke, b.active ? 1 : 0.7); + c.g.strokeRoundedRect(-w / 2, -h / 2, w, h, 16); + } + + // ── Seat info ────────────────────────────────────────────────────────────── + renderSeatInfo() { + for (const p of this.gs.players) { + if (!p.active) continue; + this.chipTxts[p.seat]?.setText(`$${p.chips.toLocaleString()}`); + if (p.seat > 0) { + this.nameTxts[p.seat]?.setColor( + p.seat === this.gs.currentSeat && this.gs.phase === 'player_turn' ? COLORS.accentHex : COLORS.textHex, + ); + } + } + } + + // Where a seat's chips come from / go to. + seatSource(seat) { + if (seat === 0) return this.dock.sourcePos(); + const pt = seatLayout(seat).portrait; + return { x: pt.x, y: pt.y, s: 0.9 }; + } + + // ── Chip stacks on the felt ──────────────────────────────────────────────── + stackSpecs() { + const specs = []; + for (const p of this.gs.players) { + if (!p.active) continue; + if (p.seat === 0 && this.gs.phase === 'betting') { + specs.push({ key: '0:0', pose: betPose(0), amount: this.pendingBet }); + continue; + } + const split = p.hand2 !== null; + specs.push({ key: `${p.seat}:0`, pose: betPose(p.seat, split ? 0 : null), amount: p.bet }); + if (split) specs.push({ key: `${p.seat}:1`, pose: betPose(p.seat, 1), amount: p.bet2 ?? 0 }); + if (p.insuranceBet > 0) specs.push({ key: `${p.seat}:ins`, pose: insurancePose(p.seat), amount: p.insuranceBet }); + } + return specs; } renderBetAreas() { - for (const g of Object.values(this.betGraphics)) g.destroy(); - this.betGraphics = {}; - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (!p.active || p.bet === 0) continue; - const { x: betX, y: betY } = this.betCirclePos(seat); - const cont = this.add.container(betX, betY).setDepth(D.chips); - const circle = this.add.graphics(); - circle.fillStyle(0x2a2a2a, 1); - circle.fillCircle(0, 0, 28); - circle.lineStyle(2, 0xf0e8d0, 0.8); - circle.strokeCircle(0, 0, 28); - const txt = this.add.text(0, 0, `$${p.bet}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f0e8d0', - }).setOrigin(0.5); - cont.add([circle, txt]); - this.betGraphics[seat] = cont; + for (const st of Object.values(this.stacks)) st.destroy(); + this.stacks = {}; + if (!this.gs) return; + for (const { key, pose, amount } of this.stackSpecs()) { + if (amount <= 0 || this.settled.has(key) || this.pendingStacks.has(key)) continue; + const size = STACK_SIZE * pose.s; + const st = makeChipStack(this, pose.x, pose.y, amount, { size, depth: D.stacks, seed: key.length + amount }); + st.chipSize = size; + this.stacks[key] = st; } } - clearCardGraphics() { - for (const cards of Object.values(this.cardGraphics)) { - for (const c of cards) c.destroy(); - } - this.cardGraphics = {}; - for (const c of this.dealerCardGraphics) c.destroy(); - this.dealerCardGraphics = []; - for (const g of Object.values(this.betGraphics)) g.destroy(); - this.betGraphics = {}; + // A stack of `amount` flies from the seat to `pose`; the real stack is redrawn on landing. + async throwStack(seat, pose, amount, delay = 0, pendingKey = null) { + await kitThrowStack(this, this.seatSource(seat), pose, amount, { + delay, size: STACK_SIZE, depth: D.flying, sound: () => playChipBet(this), + }); + if (pendingKey) this.pendingStacks.delete(pendingKey); + this.renderBetAreas(); } - // Returns the {x,y} of a seat's bet chip circle, placed just inboard of the - // card spot (toward the table centre at CX, 540). - betCirclePos(seat) { - const pos = SEAT_POS[seat]; - if (pos.betX !== undefined && pos.betY !== undefined) { - return { x: pos.betX, y: pos.betY }; - } - const t = 0.22; - return { - x: Math.round(pos.x + t * (CX - pos.x)), - y: Math.round(pos.y + t * (540 - pos.y)), - }; + // Pay, push or sweep one stack. outcome: 'win' | 'push' | 'lose' + async settleStack(key, outcome, payout, seat) { + const st = this.stacks[key]; + this.settled.add(key); + delete this.stacks[key]; + await kitSettleStack(this, st, outcome, { + payout, tray: this.trayPos, dest: this.seatSource(seat), depth: D.stacks, + sound: () => playChipBet(this), + }); } - // ── Card drawing ────────────────────────────────────────────────────────── - addCardBackToContainer(container) { - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - container.add( - this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H) - .setOrigin(0.5) - ); - } else { - const g = this.add.graphics(); - this.drawCardBack(g, -CARD_W / 2, -CARD_H / 2); - container.add(g); - } + // ── Betting ──────────────────────────────────────────────────────────────── + chipAffordable(amt) { + const human = this.gs?.players[0]; + if (!human) return false; + return this.pendingBet + amt <= Math.min(MAX_BET, human.chips); } - cardX(centerX, idx, total) { - const totalW = total * CARD_SPREAD + (CARD_W - CARD_SPREAD); - return centerX - totalW / 2 + CARD_W / 2 + idx * CARD_SPREAD; + rebetAmount(mult) { + const human = this.gs?.players[0]; + if (!human || !this.lastBet) return 0; + const amt = Math.min(this.lastBet * mult, MAX_BET, human.chips); + return Math.floor(amt / MIN_BET) * MIN_BET; } - drawCard(container, card, faceUp) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - if (faceUp && card) { - const g = this.add.graphics(); - g.fillStyle(0xffffff, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(1, 0xcccccc, 1); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - container.add(g); - const color = card.isRed ? '#c0392b' : '#1a1a2e'; - const style = (sz, bold = false) => ({ - fontFamily: '"Julius Sans One"', fontSize: `${sz}px`, color, - ...(bold ? { fontStyle: 'bold' } : {}), - }); - container.add(this.add.text(x + 7, y + 5, card.label, style(17, true))); - container.add(this.add.text(x + 7, y + 23, card.suitSymbol, style(13))); - container.add(this.add.text(0, 4, card.suitSymbol, style(40)).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 8, card.label, style(17, true)).setOrigin(1, 1)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 22, card.suitSymbol, style(13)).setOrigin(1, 1)); - } else { - this.addCardBackToContainer(container); - } - } - - drawCardBack(g, x, y) { - const color = this.cardBack?.fallbackColor - ? parseInt(this.cardBack.fallbackColor.replace('#', ''), 16) : 0x1a3a6b; - g.fillStyle(color, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xffffff, 0.25); - g.strokeRoundedRect(x + 6, y + 6, CARD_W - 12, CARD_H - 12, CARD_R - 2); - g.lineStyle(1, 0xffffff, 0.1); - g.strokeRoundedRect(x + 10, y + 10, CARD_W - 20, CARD_H - 20, CARD_R - 4); - } - - // ── Betting phase ───────────────────────────────────────────────────────── - onChipClick(amount) { - if (this.animating) return; - const human = this.gs.players[0]; - if (this.pendingBet + amount > 100) return; - if (this.pendingBet + amount > human.chips) return; - this.pendingBet += amount; - this.updateBetDisplay(); + onChipClick(amt) { + if (this.dockMode !== 'bet' || this.busy || !this.chipAffordable(amt)) return; + const btn = this.chipBtns.find(c => c.amt === amt); + this.pendingBet += amt; this.hideBettingPrompts(); + this.updateBetDisplay(); + this.throwChip(amt, { x: btn.img.x, y: btn.img.y }, betPose(0)); + } + + throwChip(denom, from, to, delay = 0) { + return kitThrowChip(this, denom, from, to, { + delay, size: STACK_SIZE, depth: D.flying, + sound: () => { playChipBet(this); this.renderBetAreas(); }, + }); + } + + async onRebet(mult) { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet > 0) return; + const amt = this.rebetAmount(mult); + if (amt < MIN_BET) return; + this.busy = true; + this.pendingBet = amt; + this.hideBettingPrompts(); + this.updateBetDisplay(); + const throws = []; + let rest = amt, i = 0; + for (const d of [...CHIP_AMOUNTS].reverse()) { + while (rest >= d) { + const btn = this.chipBtns.find(c => c.amt === d); + throws.push(this.throwChip(d, { x: btn.img.x, y: btn.img.y }, betPose(0), i++ * 70)); + rest -= d; + } + } + await Promise.all(throws); + this.busy = false; + this.updateBetDisplay(); } onClearBet() { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet === 0) return; this.pendingBet = 0; + const st = this.stacks['0:0']; + delete this.stacks['0:0']; + if (st) { + this.tweens.add({ + targets: st, x: CHIP_BTN.x0 + CHIP_BTN.dx * 1.5, y: DOCK_Y, alpha: 0, scale: 0.7, + duration: 320, ease: 'Cubic.easeIn', onComplete: () => st.destroy(), + }); + } this.updateBetDisplay(); this.startBettingPromptsIfNoBet(); } updateBetDisplay() { - if (this.betDisplayText) this.betDisplayText.setText(`Bet: $${this.pendingBet}`); - if (this.dealBtn) this.dealBtn.setEnabled(this.pendingBet >= 5); const human = this.gs?.players[0]; - if (this.balanceText && human) this.balanceText.setText(`Balance: $${human.chips.toLocaleString()}`); + this.betPill.setText(`BET $${this.pendingBet}`); + if (human) this.chipTxts[0].setText(`$${human.chips.toLocaleString()}`); + if (this.dockMode !== 'bet' || !human) return; + this.dealBtn.setEnabled(this.pendingBet >= MIN_BET && !this.busy); + this.clearBtn.setEnabled(this.pendingBet > 0 && !this.busy); + const r1 = this.rebetAmount(1), r2 = this.rebetAmount(2); + this.rebetBtn.setEnabled(r1 >= MIN_BET && this.pendingBet === 0 && !this.busy); + this.rebetBtn.setLabel(r1 >= MIN_BET ? `Rebet $${r1}` : 'Rebet'); + this.rebet2Btn.setEnabled(r2 > r1 && this.pendingBet === 0 && !this.busy); + this.dock.setChipStates(amt => this.chipAffordable(amt)); } - onDealClick() { - if (this.animating || this.pendingBet < 5) return; - this.animating = true; - this.hideBettingUI(); - this.hideBettingPrompts(); + startBettingPrompts() { + this.dock.startPrompts( + () => (this.lastBet ? 'Click chips to bet, or press Space to rebet — then Deal' : 'Click chips to place a bet, then Deal'), + () => this.pendingBet === 0, + ); + } + + hideBettingPrompts() { + this.dock.hidePrompts(); + } + + startBettingPromptsIfNoBet() { + if (this.pendingBet === 0) this.startBettingPrompts(); + } + + async onDealClick() { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet < MIN_BET) return; + this.busy = true; + this.lastBet = this.pendingBet; + this.setDockMode('wait', 'Dealing…'); - // Commit human bet this.gs = applyBet(this.gs, 0, this.pendingBet); - - // AI bets - for (let seat = 1; seat < SEAT_POS.length; seat++) { + const throws = []; + let n = 0; + for (let seat = 1; seat < this.gs.players.length; seat++) { const p = this.gs.players[seat]; if (!p.active) continue; - const bet = chooseBet(p); - this.gs = applyBet(this.gs, seat, Math.max(5, bet)); + const bet = Math.max(MIN_BET, chooseBet(p)); + this.gs = applyBet(this.gs, seat, bet); + throws.push(this.throwStack(seat, betPose(seat), bet, n++ * 90)); } + await Promise.all(throws); - // Deal all cards - this.gs = dealAllCards(this.gs, this.shoe); - - // Animate bets then deal - this.animateBets(() => { - this.animateDeal(() => { - this.animating = false; - this.renderAll(); - this.checkInsuranceOrStartPlay(); - }); - }); - } - - // ── Animations ──────────────────────────────────────────────────────────── - animateBets(onComplete) { + // currentSeat is set properly by startPlayerTurns (PLAY_ORDER); until then nobody is "up". + this.gs = { ...dealAllCards(this.gs, this.shoe), currentSeat: -1 }; + await this.animateDeal(); + this.busy = false; this.renderBetAreas(); - playChipBet(this); - let done = 0; - const active = this.gs.players.filter(p => p.active); - if (active.length === 0) { onComplete(); return; } - for (const p of active) { - const pos = SEAT_POS[p.seat]; - const { x: betX, y: betY } = this.betCirclePos(p.seat); - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(CHIP_COLORS[25], 1); - chip.fillCircle(0, 0, 16); - chip.x = pos.x; chip.y = pos.y; - this.tweens.add({ - targets: chip, x: betX, y: betY, duration: 280, ease: 'Power2', - onComplete: () => { - chip.destroy(); - done++; - if (done >= active.length) onComplete(); - }, - }); + this.renderSeatInfo(); + if (this.gs.phase === 'insurance') this.offerInsurance(); + else this.checkImmediateDealerBJ(); + } + + // Real deal order: one card to each player, dealer upcard, second card to + // each player, dealer hole card face-down. + async animateDeal() { + this.hideBadges = true; + this.updateBadges(); + const seats = PLAY_ORDER.filter(seat => this.gs.players[seat]?.active); + const seq = [ + ...seats.map(seat => () => this.dealToSeat(seat, 0, 0)), + () => this.dealToDealer(0, true), + ...seats.map(seat => () => this.dealToSeat(seat, 0, 1)), + () => this.dealToDealer(1, false), + ]; + let last = null; + for (const fn of seq) { + last = fn(); + await this.wait(165); + } + await last; + this.hideBadges = false; + this.updateBadges(); + } + + // ── Insurance ────────────────────────────────────────────────────────────── + offerInsurance() { + for (let seat = 1; seat < this.gs.players.length; seat++) { + if (this.gs.players[seat].active) this.gs = applyInsurance(this.gs, seat, false); + } + const human = this.gs.players[0]; + const cost = Math.floor(human.bet / 2); + if (cost < 1 || human.chips < human.bet + cost) { + this.gs = applyInsurance(this.gs, 0, false); + this.checkImmediateDealerBJ(); + return; + } + + this.setDockMode('insurance'); + const txt = this.add.text(470, DOCK_Y, `Dealer shows an Ace. Insure for $${cost}? Pays 2 to 1.`, { + fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.dockUi); + const choose = async (yes) => { + if (this.dockMode !== 'insurance') return; + this.setDockMode('wait', ''); + this.gs = applyInsurance(this.gs, 0, yes); + if (yes) { + this.pendingStacks.add('0:ins'); + await this.throwStack(0, insurancePose(0), cost, 0, '0:ins'); + } + this.checkImmediateDealerBJ(); + }; + const yesBtn = new Button(this, 1360, DOCK_Y, 'Yes', () => choose(true), { width: 120, height: 52, fontSize: 20 }); + const noBtn = new Button(this, 1494, DOCK_Y, 'No', () => choose(false), { width: 120, height: 52, fontSize: 20, variant: 'ghost' }); + yesBtn.setDepth(D.dockUi); + noBtn.setDepth(D.dockUi); + this.dock.addTransient(txt, yesBtn, noBtn); + this.insuranceChoice = choose; + } + + async checkImmediateDealerBJ() { + const insured = this.gs.players.filter(p => p.active && p.insuranceBet > 0); + const dealerBJ = isBlackjack(this.gs.dealer.hand); + this.gs = resolveInsurance(this.gs); + + if (dealerBJ) { + this.gs = { ...this.gs, phase: 'dealer_turn', currentSeat: -1 }; + this.setDockMode('wait', 'Dealer has Blackjack'); + await this.revealHole(); + await Promise.all(insured.map(p => this.settleStack(`${p.seat}:ins`, 'win', p.insuranceBet * 2, p.seat))); + this.gs = resolveRound(this.gs); + this.updateBadges(); + await this.showAllResults(); + this.updateServerChips(); + this.showNextRoundPrompt(); + return; + } + if (insured.length) { + this.setDockMode('wait', 'No dealer Blackjack'); + await Promise.all(insured.map(p => this.settleStack(`${p.seat}:ins`, 'lose', 0, p.seat))); + } + this.startPlayerTurns(); + } + + // ── Player turns ─────────────────────────────────────────────────────────── + firstPlaySeat() { + for (const seat of PLAY_ORDER) if (this.gs.players[seat]?.active) return seat; + return 0; + } + + nextPlaySeat() { + const start = PLAY_ORDER.indexOf(this.gs.currentSeat); + for (let i = start + 1; i < PLAY_ORDER.length; i++) { + const p = this.gs.players[PLAY_ORDER[i]]; + if (p?.active && (p.status === 'playing' || p.status === 'waiting')) return PLAY_ORDER[i]; + } + return null; + } + + startPlayerTurns() { + const seat = this.firstPlaySeat(); + this.gs = { ...this.gs, phase: 'player_turn', currentSeat: seat }; + this.advanceToPlayer(seat); + } + + advanceToPlayer(seat) { + this.syncCards(); + this.renderSeatInfo(); + this.updateBadges(); + const p = this.gs.players[seat]; + if (!p || !p.active) { this.startDealerTurn(); return; } + + if (isPlayerDone(p)) { + const next = this.nextPlaySeat(); + if (next === null) { this.startDealerTurn(); return; } + this.gs = { ...this.gs, currentSeat: next }; + this.advanceToPlayer(next); + return; + } + + this.highlightActiveSeat(seat); + if (p.isHuman) { + this.showActionButtons(); + } else { + this.setDockMode('wait', `${p.name} is thinking…`); + this.time.delayedCall(900, () => this.runAITurn(seat)); } } - animateDeal(onComplete) { - // Deal order: dealer hole card (face-down), each player card 1, - // dealer upcard (face-up), each player card 2. - const seats = PLAY_ORDER.filter(seat => this.gs.players[seat]?.active); - const dealSeq = []; - dealSeq.push({ type: 'dealer', cardIdx: 1 }); // hole card face-down first - for (const seat of seats) dealSeq.push({ type: 'player', seat, cardIdx: 0 }); - dealSeq.push({ type: 'dealer', cardIdx: 0 }); // upcard face-up - for (const seat of seats) dealSeq.push({ type: 'player', seat, cardIdx: 1 }); + // Chips aren't deducted until the round resolves, so check headroom for every + // bet already on the felt before allowing another. + committed(p) { + return p.bet + (p.bet2 ?? 0) + (p.insuranceBet ?? 0); + } - // Build card graphics now (hands are populated but graphics weren't created yet) - this.renderAll(); + canAffordDouble(p) { + const extra = p.activeHand === 1 ? p.bet2 : p.bet; + return canDouble(p) && p.chips >= this.committed(p) + extra; + } - // Hide all cards and score totals initially - for (const cards of Object.values(this.cardGraphics)) { - for (const c of cards) c.setAlpha(0); + canAffordSplit(p) { + return canSplit(p) && p.chips >= this.committed(p) + p.bet; + } + + recommendedAction(p) { + const up = this.gs.dealer.hand[0]; + let a = chooseAction(p, up); + if (a === 'split' && !this.canAffordSplit(p)) a = chooseAction({ ...p, hand2: [] }, up); + if (a === 'double' && !this.canAffordDouble(p)) a = 'hit'; + return a; + } + + showActionButtons() { + this.setDockMode('play'); + const p = this.gs.players[0]; + const defs = [ + { key: 'h', action: 'hit', label: 'Hit', fn: () => this.onHit() }, + { key: 's', action: 'stand', label: 'Stand', fn: () => this.onStand() }, + ]; + if (this.canAffordDouble(p)) defs.push({ key: 'd', action: 'double', label: 'Double', fn: () => this.onDouble() }); + if (this.canAffordSplit(p)) defs.push({ key: 'p', action: 'split', label: 'Split', fn: () => this.onSplit() }); + + this.playActions = {}; + const startX = 560, step = 164; + const btns = {}; + defs.forEach((d, i) => { + const b = new Button(this, startX + i * step, DOCK_Y, d.label, d.fn, { width: 148, height: 58, fontSize: 24 }); + b.setDepth(D.dockUi); + this.dock.addTransient(b); + this.playActions[d.key] = d.fn; + btns[d.action] = b; + }); + + if (this.hintsOn) { + const rec = this.recommendedAction(p); + const b = btns[rec]; + if (b) { + const ring = this.add.graphics().setDepth(D.dockUi - 1); + ring.lineStyle(4, 0xf5d020, 1); + ring.strokeRoundedRect(b.x - 80, b.y - 35, 160, 70, 12); + this.tweens.add({ targets: ring, alpha: 0.3, duration: 650, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + const label = this.add.text(startX + defs.length * step - 50, DOCK_Y, `Basic strategy: ${ACTION_LABELS[rec]}`, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#f5d020', + }).setOrigin(0, 0.5).setDepth(D.dockUi); + this.dock.addTransient(ring, label); + } } - for (const c of this.dealerCardGraphics) c.setAlpha(0); - for (const txt of Object.values(this.scoreTxts)) txt.setAlpha(0); - this.dealerScoreTxt.setAlpha(0); + } - let idx = 0; - const DECK_X = CX + 200, DECK_Y = 50; - const stagger = 90; + humanCanAct() { + return this.dockMode === 'play' && !this.busy && this.gs.currentSeat === 0; + } - const dealNext = () => { - if (idx >= dealSeq.length) { - for (const txt of Object.values(this.scoreTxts)) txt.setAlpha(1); - this.dealerScoreTxt.setAlpha(1); - onComplete(); + // Shared action bodies (human + AI). Each returns once its animation is done. + async doHit(seat) { + this.animateActionText(seat, 'hit'); + this.busy = true; + this.gs = applyHit(this.gs, seat, this.shoe); + const p = this.gs.players[seat]; + const h = p.activeHand; + const hand = this.handOf(p, h); + await this.dealToSeat(seat, h, hand.length - 1); + this.updateBadges(); + this.busy = false; + if (isBust(hand)) { + this.onPlayerBust(seat, h); + await this.wait(420); + return 'bust'; + } + return handValue(hand).score === 21 ? 'twentyone' : 'continue'; + } + + doStand(seat) { + this.animateActionText(seat, 'stand'); + this.gs = applyStand(this.gs, seat); + const p = this.gs.players[seat]; + return (p.hand2 !== null && p.activeHand === 1 && p.status2 === null) ? 'next-hand' : 'done'; + } + + async doDouble(seat) { + this.animateActionText(seat, 'double'); + this.busy = true; + const before = this.gs.players[seat]; + const h = before.activeHand; + const split = before.hand2 !== null; + const extra = h === 1 ? before.bet2 : before.bet; + this.gs = applyDouble(this.gs, seat, this.shoe); + await this.throwStack(seat, betPose(seat, split ? h : null), extra); + const p = this.gs.players[seat]; + const hand = this.handOf(p, h); + await this.dealToSeat(seat, h, hand.length - 1); + this.updateBadges(); + this.busy = false; + if (isBust(hand)) { + this.onPlayerBust(seat, h); + await this.wait(420); + } + } + + async doSplit(seat) { + this.animateActionText(seat, 'split'); + this.busy = true; + const bet = this.gs.players[seat].bet; + this.gs = applySplit(this.gs, seat, this.shoe); + // The second card of the original hand becomes the first card of hand 2. + const moved = this.cards.get(`${seat}:0:1`); + this.cards.delete(`${seat}:0:1`); + if (moved) this.cards.set(`${seat}:1:0`, moved); + this.pendingStacks.add(`${seat}:1`); + this.renderBetAreas(); + this.layoutSeat(seat, 260); + await this.throwStack(seat, betPose(seat, 1), bet, 0, `${seat}:1`); + await this.wait(120); + await this.dealToSeat(seat, 0, 1); + await this.dealToSeat(seat, 1, 1); + this.updateBadges(); + this.busy = false; + } + + async onHit() { + if (!this.humanCanAct()) return; + this.setDockMode('wait', ''); + const r = await this.doHit(0); + if (r === 'bust') { this.playerDone(0); return; } + if (r === 'twentyone') { this.standHuman(); return; } // nothing to gain — stand automatically + this.showActionButtons(); + } + + onStand() { + if (!this.humanCanAct()) return; + this.standHuman(); + } + + standHuman() { + if (this.doStand(0) === 'next-hand') { + this.updateBadges(); + this.showActionButtons(); + return; + } + this.playerDone(0); + } + + async onDouble() { + if (!this.humanCanAct()) return; + this.setDockMode('wait', ''); + await this.doDouble(0); + this.playerDone(0); + } + + async onSplit() { + if (!this.humanCanAct()) return; + this.setDockMode('wait', ''); + await this.doSplit(0); + if (isPlayerDone(this.gs.players[0])) this.playerDone(0); + else this.showActionButtons(); + } + + onPlayerBust(seat, h) { + this.bustedHands.add(`${seat}:${h}`); + const p = this.gs.players[seat]; + (this.handOf(p, h) ?? []).forEach((_, i) => { + const c = this.cards.get(`${seat}:${h}:${i}`); + if (c) this.tweens.add({ targets: c, alpha: 0.35, duration: 280, ease: 'Power2' }); + }); + this.settleStack(`${seat}:${h}`, 'lose', 0, seat); + if (seat > 0) this.portraits[seat]?.playEmotion?.('upset'); + } + + // Move a split player onto their second hand without touching hand 1's status + // (applyStand would overwrite a 'bust' with 'standing'). + moveToSecondHand(seat) { + const players = this.gs.players.map(p => (p.seat === seat ? { ...p, activeHand: 1 } : p)); + this.gs = { ...this.gs, players }; + } + + playerDone(seat) { + const p = this.gs.players[seat]; + if (p.hand2 !== null && !isPlayerDone(p)) { + if (p.activeHand === 0) this.moveToSecondHand(seat); + this.updateBadges(); + if (p.isHuman) this.showActionButtons(); + else this.time.delayedCall(600, () => this.runAITurn(seat)); + return; + } + const next = this.nextPlaySeat(); + if (next === null) { + this.startDealerTurn(); + } else { + this.gs = { ...this.gs, currentSeat: next }; + this.advanceToPlayer(next); + } + } + + // ── AI turn ──────────────────────────────────────────────────────────────── + async runAITurn(seat) { + if (!this.sys.isActive()) return; + const p = this.gs.players[seat]; + if (!p || !p.active || isPlayerDone(p)) { this.playerDone(seat); return; } + + const hand = this.handOf(p, p.activeHand); + let action = chooseAction(p, this.gs.dealer.hand[0]); + if (action === 'split' && !this.canAffordSplit(p)) action = handValue(hand).score >= 17 ? 'stand' : 'hit'; + if (action === 'double' && !this.canAffordDouble(p)) action = 'hit'; + + switch (action) { + case 'hit': { + const r = await this.doHit(seat); + if (r === 'bust') { this.playerDone(seat); return; } + await this.wait(600); + this.runAITurn(seat); return; } - const entry = dealSeq[idx++]; - // Flying card-back - const flying = this.add.container(DECK_X, DECK_Y).setDepth(D.cards + 10); - this.addCardBackToContainer(flying); - - let tx, ty; - if (entry.type === 'dealer') { - const total = this.gs.dealer.hand.length; - tx = this.cardX(DEALER_X, entry.cardIdx, total); - ty = DEALER_Y; - } else { - const pos = SEAT_POS[entry.seat]; - const p = this.gs.players[entry.seat]; - const h1Offset = p.hand2 ? -80 : 0; - const total = p.hand.length; - tx = this.cardX(pos.x + h1Offset, entry.cardIdx, total); - ty = pos.y; + case 'double': + await this.doDouble(seat); + await this.wait(350); + this.playerDone(seat); + return; + case 'split': + await this.doSplit(seat); + await this.wait(500); + if (isPlayerDone(this.gs.players[seat])) this.playerDone(seat); + else this.runAITurn(seat); + return; + case 'stand': + default: { + const r = this.doStand(seat); + this.updateBadges(); + await this.wait(400); + if (r === 'next-hand') { await this.wait(300); this.runAITurn(seat); return; } + this.playerDone(seat); } - - this.tweens.add({ - targets: flying, x: tx, y: ty, duration: 180, ease: 'Power2', - onComplete: () => { - flying.destroy(); - playSound(this, SFX.CARD_DEAL); - // Reveal the card at destination - if (entry.type === 'dealer') { - const cont = this.dealerCardGraphics[entry.cardIdx]; - if (cont) cont.setAlpha(1); - } else { - const cardConts = this.cardGraphics[entry.seat] ?? []; - if (cardConts[entry.cardIdx]) cardConts[entry.cardIdx].setAlpha(1); - } - this.time.delayedCall(stagger, dealNext); - }, - }); - }; - dealNext(); + } } - animateDealerReveal(onComplete) { - const holeCard = this.dealerCardGraphics[1]; - if (!holeCard) { this.gs.dealer.revealed = true; this.renderAll(); onComplete(); return; } - playSound(this, SFX.CARD_SHOW); - - // Flip: scale X 1→0, redraw face-up, scale X 0→1 - this.tweens.add({ - targets: holeCard, scaleX: 0, duration: 120, ease: 'Linear', - onComplete: () => { - this.gs = { ...this.gs, dealer: { ...this.gs.dealer, revealed: true } }; - this.drawCard(holeCard, this.gs.dealer.hand[1], true); - this.tweens.add({ - targets: holeCard, scaleX: 1, duration: 120, ease: 'Linear', - onComplete: () => { - this.renderDealer(); - onComplete(); - }, - }); - }, - }); + // ── Dealer turn ──────────────────────────────────────────────────────────── + async revealHole() { + this.gs = { ...this.gs, dealer: { ...this.gs.dealer, revealed: true } }; + const c = this.cards.get('d:1'); + if (c) { + playSound(this, SFX.CARD_SHOW); + await this.flipCard(c, true, 340); + } + this.updateBadges(); } - animateSingleCard(seat, card, onComplete) { - const pos = SEAT_POS[seat]; + async startDealerTurn() { + this.clearActiveHighlight(); + this.gs = { ...this.gs, phase: 'dealer_turn', currentSeat: -1 }; + this.setDockMode('wait', "Dealer's turn"); + this.renderSeatInfo(); + this.updateBadges(); + await this.wait(400); + await this.revealHole(); + + // The dealer only draws if someone still has a live hand against them. + const live = (hand, status) => hand && status !== 'bust' && !(status === 'blackjack' && isBlackjack(hand)); + const anyLive = this.gs.players.some(p => p.active && (live(p.hand, p.status) || live(p.hand2, p.status2))); + while (anyLive && handValue(this.gs.dealer.hand).score < 17) { + await this.wait(380); + const card = this.shoe.pop(); + this.gs = { ...this.gs, dealer: { ...this.gs.dealer, hand: [...this.gs.dealer.hand, card] } }; + await this.dealToDealer(this.gs.dealer.hand.length - 1, true); + this.updateBadges(); + } + await this.wait(450); + this.finishRound(); + } + + // ── Resolve ──────────────────────────────────────────────────────────────── + async finishRound() { + this.gs = resolveRound(this.gs); + this.syncCards(); + this.updateBadges(); + await this.showAllResults(); + this.updateServerChips(); + this.showNextRoundPrompt(); + } + + async showAllResults() { + const seats = PLAY_ORDER.filter(seat => this.gs.players[seat]?.active); + await Promise.all(seats.map((seat, i) => this.wait(i * 480).then(() => this.animateSeatResult(seat)))); + } + + async animateSeatResult(seat) { const p = this.gs.players[seat]; - const isH2 = p.activeHand === 1; - const hand = isH2 ? p.hand2 : p.hand; - const total = hand.length; - const cardIdx = total - 1; - const tx = this.cardX(pos.x, cardIdx, total); - const ty = pos.y; + if (!p?.active || !p.result) return; - // Flying card-back dealt from the dealer's area - const flying = this.add.container(DEALER_X, DEALER_Y).setDepth(D.cards + 10); - this.addCardBackToContainer(flying); + const hands = [{ h: 0, result: p.result, bet: p.bet }]; + if (p.hand2 !== null && p.result2) hands.push({ h: 1, result: p.result2, bet: p.bet2 }); + for (const { h, result, bet } of hands) { + const key = `${seat}:${h}`; + if (this.settled.has(key)) continue; + if (result === 'win' || result === 'blackjack') { + const payout = result === 'blackjack' ? Math.floor(bet * 1.5) : bet; + this.settleStack(key, 'win', payout, seat); + } else if (result === 'push') { + this.settleStack(key, 'push', 0, seat); + } else { + this.settleStack(key, 'lose', 0, seat); + } + } + + const best = hands.reduce((a, b) => (RESULT_RANK[b.result] > RESULT_RANK[a.result] ? b : a)).result; + const isWin = best === 'win' || best === 'blackjack'; + const allLose = hands.every(x => x.result === 'lose' || x.result === 'bust'); + if (best === 'blackjack') playSound(this, SFX.CASINO_BLACKJACK); + else if (isWin) playSound(this, SFX.CASINO_WIN); + else if (allLose) playSound(this, SFX.CASINO_LOSE); + + const net = p.chipsWon ?? 0; + if (seat > 0 && net !== 0) this.portraits[seat]?.playEmotion?.(net > 0 ? 'happy' : 'upset'); + if (seat === 0 && net !== 0) { + this.time.delayedCall(1100, () => { + const t = this.chipTxts[0]; + this.floatText(t.x + t.width + 50, t.y, `${net > 0 ? '+' : '−'}$${Math.abs(net).toLocaleString()}`, + net > 0 ? '#7ee081' : '#ff8a80'); + }); + } + + const label = hands.length > 1 + ? hands.map(x => RESULT_LABELS[x.result] ?? x.result).join(' · ') + : (RESULT_LABELS[best] ?? best); + const linger = isWin ? 1500 : allLose ? 1100 : 800; + const { card } = seatLayout(seat); + const textY = card.y - 96 * card.s; + const badge = this.add.text(card.x, textY, label, { + fontFamily: '"Julius Sans One"', + fontSize: hands.length > 1 ? '40px' : (RESULT_SIZES[best] ?? '48px'), + color: RESULT_COLORS[best] ?? '#ffffff', + fontStyle: 'bold', + stroke: '#000000', strokeThickness: 5, + shadow: isWin ? { offsetX: 0, offsetY: 0, color: RESULT_COLORS[best], blur: 24, fill: true } : undefined, + }).setOrigin(0.5).setAlpha(0).setScale(1.4).setDepth(D.modal); + + this.tweens.add({ targets: badge, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.Out' }); + if (isWin) this.animateFireworks(card.x, textY); + await this.wait(linger); + await this.tweenP({ targets: badge, alpha: 0, y: textY - 30, duration: 380, ease: 'Power2' }); + badge.destroy(); + } + + floatText(x, y, str, color) { + const t = this.add.text(x, y, str, { + fontFamily: '"Julius Sans One"', fontSize: '28px', color, fontStyle: 'bold', + stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.modal); this.tweens.add({ - targets: flying, x: tx, y: ty, duration: 200, ease: 'Power2', - onComplete: () => { - flying.destroy(); - playSound(this, SFX.CARD_PLACE); - // Reveal the card face-up at the destination - const cardConts = this.cardGraphics[seat] ?? []; - const targetCont = cardConts[cardIdx]; - if (targetCont) { - targetCont.setAlpha(1); - this.drawCard(targetCont, card, true); - } - onComplete(); - }, + targets: t, y: y - 60, alpha: { value: 0, ease: 'Expo.easeIn' }, + duration: 1500, ease: 'Cubic.easeOut', onComplete: () => t.destroy(), }); } - // ── Per-turn action callout ────────────────────────────────────────────── - // Large colored word (Hit/Stand/Double/Split) shown between the player and - // their cards; lingers >= 1s before fading. Fire-and-forget (no flow gating). + showNextRoundPrompt() { + const human = this.gs.players[0]; + this.renderSeatInfo(); + + if (human.chips <= 0) { + this.setDockMode('wait', ''); + new Modal(this, 'Out of chips! Visit your profile to request a reset.', { autoCloseMs: 4000 }); + this.time.delayedCall(4200, () => this.scene.start('GameMenu')); + return; + } + + this.setDockMode('next'); + const next = new Button(this, CX - 140, DOCK_Y, 'Next Round', () => this.onNextRound(false), { + width: 230, height: 58, fontSize: 24, + }); + next.setDepth(D.dockUi); + this.dock.addTransient(next); + const amt = this.rebetAmount(1); + if (amt >= MIN_BET) { + const rebet = new Button(this, CX + 130, DOCK_Y, `Rebet $${amt} & Deal`, () => this.onNextRound(true), { + width: 270, height: 58, fontSize: 20, variant: 'ghost', + }); + rebet.setDepth(D.dockUi); + this.dock.addTransient(rebet); + } + } + + async onNextRound(rebet) { + if (this.dockMode !== 'next') return; + if (rebet && this.rebetAmount(1) < MIN_BET) rebet = false; + this.setDockMode('wait', ''); + await this.startNewRound(); + if (!rebet || this.dockMode !== 'bet') return; + await this.onRebet(1); + this.onDealClick(); + } + + // ── Per-turn action callout ──────────────────────────────────────────────── + // DOM element so it sits above the opponent portrait videos (also DOM). animateActionText(seat, action) { const label = ACTION_LABELS[action]; if (!label) return; - const pos = SEAT_POS[seat]; - const px = pos.portraitX ?? pos.x; - const py = pos.portraitY ?? pos.y; - const tx = (px + pos.x) / 2; - const ty = (py + pos.y) / 2; + const { card, portrait } = seatLayout(seat); + const tx = seat === 0 ? card.x : (portrait.x + card.x) / 2; + const ty = seat === 0 ? card.y - 112 : (portrait.y + card.y) / 2; - // Rendered as a DOM element with a very high depth so it sits above - // everything, including the opponent portrait videos (which are DOM and - // therefore always drawn above the Phaser canvas). const el = document.createElement('div'); el.textContent = label; el.style.cssText = [ @@ -906,33 +1320,23 @@ export default class BlackjackGame extends Phaser.Scene { ].join(';'); const dom = this.add.dom(tx, ty, el).setDepth(D.modal + 100).setAlpha(0).setScale(1.4); - - this.tweens.add({ - targets: dom, alpha: 1, scaleX: 1, scaleY: 1, - duration: 180, ease: 'Back.Out', - }); + this.tweens.add({ targets: dom, alpha: 1, scaleX: 1, scaleY: 1, duration: 180, ease: 'Back.Out' }); this.time.delayedCall(1000, () => { this.tweens.add({ - targets: dom, alpha: 0, y: ty - 26, - duration: 350, ease: 'Power2', + targets: dom, alpha: 0, y: ty - 26, duration: 350, ease: 'Power2', onComplete: () => dom.destroy(), }); }); } - // ── Active-player turn highlight (pulsing ring around the portrait) ──────── + // ── Active-player highlight (pulsing ring around the portrait) ───────────── highlightActiveSeat(seat) { - const pos = SEAT_POS[seat]; - const px = pos.portraitX ?? pos.x; - const py = pos.portraitY ?? pos.y; - - if (!this.activeRing) { - this.activeRing = this.add.graphics().setDepth(D.ui - 1); - } + const pt = seatLayout(seat).portrait; + if (!this.activeRing) this.activeRing = this.add.graphics().setDepth(D.ui - 1); this.activeRing.clear(); this.activeRing.lineStyle(5, COLORS.accent, 0.9); - this.activeRing.strokeCircle(0, 0, pos.portraitR + 8); - this.activeRing.setPosition(px, py).setVisible(true).setScale(1).setAlpha(1); + this.activeRing.strokeCircle(0, 0, pt.r + 8); + this.activeRing.setPosition(pt.x, pt.y).setVisible(true).setScale(1).setAlpha(1); this.activeRingTween?.stop(); this.activeRingTween = this.tweens.add({ @@ -945,124 +1349,7 @@ export default class BlackjackGame extends Phaser.Scene { clearActiveHighlight() { this.activeRingTween?.stop(); this.activeRingTween = null; - if (this.activeRing) this.activeRing.setVisible(false); - } - - // ── Per-seat result animation (text + chips + fireworks) ───────────────── - animateSeatResult(seat, onComplete) { - const p = this.gs.players[seat]; - if (!p?.active || !p.result) { onComplete(); return; } - - const result = p.result; - const pos = SEAT_POS[seat]; - const isWin = result === 'win' || result === 'blackjack'; - const isLose = result === 'lose' || result === 'bust'; - - if (result === 'blackjack') playSound(this, SFX.CASINO_BLACKJACK); - else if (result === 'win') playSound(this, SFX.CASINO_WIN); - else if (result === 'lose' || result === 'bust') playSound(this, SFX.CASINO_LOSE); - - if (seat > 0 && this.portraits[seat]) { - this.portraits[seat].playEmotion?.(isWin ? 'happy' : 'upset'); - } - - const LABELS = { win: 'Win!', blackjack: 'Blackjack!', push: 'Push', lose: 'Lose', bust: 'Bust' }; - const COLORS = { win: '#f5d020', blackjack: '#ffe066', push: '#9aa5b4', lose: '#e05c5c', bust: '#e05c5c' }; - const SIZES = { win: '54px', blackjack: '58px', push: '34px', lose: '48px', bust: '48px' }; - const linger = isWin ? 1500 : isLose ? 1100 : 700; - - const textY = pos.y - CARD_H / 2 - 60; - const badge = this.add.text(pos.x, textY, LABELS[result] ?? result, { - fontFamily: '"Julius Sans One"', - fontSize: SIZES[result] ?? '48px', - color: COLORS[result] ?? '#ffffff', - fontStyle: 'bold', - stroke: '#000000', strokeThickness: 5, - shadow: isWin - ? { offsetX: 0, offsetY: 0, color: COLORS[result], blur: 24, fill: true } - : undefined, - }).setOrigin(0.5).setAlpha(0).setScale(1.4).setDepth(D.modal); - - // Pop-in - this.tweens.add({ - targets: badge, alpha: 1, scaleX: 1, scaleY: 1, - duration: 200, ease: 'Back.Out', - }); - - // Linger then fade up - this.time.delayedCall(linger, () => { - this.tweens.add({ - targets: badge, alpha: 0, y: textY - 30, - duration: 380, ease: 'Power2', - onComplete: () => { badge.destroy(); onComplete(); }, - }); - }); - - // Chip movement (runs in parallel with text) - if (isWin) { - this.animateChipsFromDealer(seat, p.chipsWon ?? p.bet); - this.animateFireworks(pos.x, textY); - } else if (isLose) { - this.animateChipsToDealer(seat); - } else { - // Push — bet returns to player - this.animateChipReturn(seat); - } - } - - animateChipsToDealer(seat) { - const { x: betX, y: betY } = this.betCirclePos(seat); - for (let i = 0; i < 4; i++) { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(CHIP_COLORS[25], 1); chip.fillCircle(0, 0, 14); - chip.lineStyle(2, 0xffffff, 0.3); chip.strokeCircle(0, 0, 14); - chip.x = betX + (Math.random() - 0.5) * 22; - chip.y = betY; - this.tweens.add({ - targets: chip, x: DEALER_X, y: DEALER_Y, - duration: 440, delay: i * 55, ease: 'Power2', - onComplete: () => chip.destroy(), - }); - } - } - - animateChipsFromDealer(seat, amount) { - if (!amount || amount <= 0) return; - const pos = SEAT_POS[seat]; - const count = Math.min(Math.ceil(amount / 25), 7); - for (let i = 0; i < count; i++) { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(CHIP_COLORS[25], 1); chip.fillCircle(0, 0, 14); - chip.lineStyle(2, 0xffffff, 0.3); chip.strokeCircle(0, 0, 14); - chip.x = DEALER_X + (Math.random() - 0.5) * 50; - chip.y = DEALER_Y; - this.tweens.add({ - targets: chip, - x: pos.x + (Math.random() - 0.5) * 28, - y: pos.y, - duration: 460, delay: i * 55, ease: 'Power2', - onComplete: () => chip.destroy(), - }); - } - } - - animateChipReturn(seat) { - const pos = SEAT_POS[seat]; - const { x: betX, y: betY } = this.betCirclePos(seat); - for (let i = 0; i < 3; i++) { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(CHIP_COLORS[25], 1); chip.fillCircle(0, 0, 14); - chip.lineStyle(2, 0xffffff, 0.3); chip.strokeCircle(0, 0, 14); - chip.x = betX + (Math.random() - 0.5) * 20; - chip.y = betY; - this.tweens.add({ - targets: chip, - x: pos.x + (Math.random() - 0.5) * 20, - y: pos.y, - duration: 380, delay: i * 50, ease: 'Power2', - onComplete: () => chip.destroy(), - }); - } + this.activeRing?.setVisible(false); } animateFireworks(cx, cy) { @@ -1075,9 +1362,8 @@ export default class BlackjackGame extends Phaser.Scene { for (let i = 0; i < 10; i++) { const angle = (i / 10) * Math.PI * 2 + Math.random() * 0.3; const dist = 65 + Math.random() * 65; - const color = palette[Math.floor(Math.random() * palette.length)]; const dot = this.add.graphics().setDepth(D.modal + 5); - dot.fillStyle(color, 1); + dot.fillStyle(palette[Math.floor(Math.random() * palette.length)], 1); dot.fillCircle(0, 0, 4 + Math.random() * 3); dot.x = bx; dot.y = by; this.tweens.add({ @@ -1094,397 +1380,4 @@ export default class BlackjackGame extends Phaser.Scene { }); } } - - // ── Insurance ───────────────────────────────────────────────────────────── - checkInsuranceOrStartPlay() { - if (this.gs.phase === 'insurance') { - this.offerInsurance(); - } else { - this.checkImmediateDealerBJ(); - } - } - - offerInsurance() { - // AI declines immediately - for (let seat = 1; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (p.active) this.gs = applyInsurance(this.gs, seat, false); - } - - // Offer human - const modal = this.add.container(CX, GAME_HEIGHT / 2).setDepth(D.modal); - const bg = this.add.rectangle(0, 0, 560, 200, COLORS.panel).setStrokeStyle(2, COLORS.accent); - const txt = this.add.text(0, -55, 'Dealer shows Ace\nTake insurance? (pays 2:1)', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, align: 'center', - }).setOrigin(0.5); - modal.add([bg, txt]); - - const yesBtn = new Button(this, CX - 120, GAME_HEIGHT / 2 + 30, 'Yes', () => { - modal.destroy(); - yesBtn.destroy(); noBtn.destroy(); - this.gs = applyInsurance(this.gs, 0, true); - this.checkImmediateDealerBJ(); - }, { width: 120, height: 52, fontSize: 20 }); - yesBtn.setDepth(D.modal + 1); - - const noBtn = new Button(this, CX + 120, GAME_HEIGHT / 2 + 30, 'No', () => { - modal.destroy(); - yesBtn.destroy(); noBtn.destroy(); - this.gs = applyInsurance(this.gs, 0, false); - this.checkImmediateDealerBJ(); - }, { width: 120, height: 52, fontSize: 20, variant: 'ghost' }); - noBtn.setDepth(D.modal + 1); - } - - checkImmediateDealerBJ() { - if (isBlackjack(this.gs.dealer.hand)) { - // Dealer blackjack — resolve insurance then show result - this.gs = resolveInsurance(this.gs); - this.animateDealerReveal(() => { - this.gs = resolveRound(this.gs); - this.renderAll(); - this.showAllResults(() => this.showNextRoundPrompt()); - }); - } else { - this.gs = resolveInsurance(this.gs); - this.startPlayerTurns(); - } - } - - // ── Player turns ────────────────────────────────────────────────────────── - // First seat to act, walking PLAY_ORDER (clockwise from top-right). - firstPlaySeat() { - for (const seat of PLAY_ORDER) { - if (this.gs.players[seat]?.active) return seat; - } - return 0; - } - - // Next seat in PLAY_ORDER after the current one that still needs to act. - nextPlaySeat() { - const start = PLAY_ORDER.indexOf(this.gs.currentSeat); - for (let i = start + 1; i < PLAY_ORDER.length; i++) { - const p = this.gs.players[PLAY_ORDER[i]]; - if (p?.active && (p.status === 'playing' || p.status === 'waiting')) return PLAY_ORDER[i]; - } - return null; - } - - startPlayerTurns() { - this.gs = { ...this.gs, phase: 'player_turn' }; - const seat = this.firstPlaySeat(); - this.gs = { ...this.gs, currentSeat: seat }; - this.advanceToPlayer(seat); - } - - advanceToPlayer(seat) { - this.renderAll(); - const p = this.gs.players[seat]; - if (!p || !p.active) { this.startDealerTurn(); return; } - - // Skip if already determined (blackjack on deal) - if (isPlayerDone(p)) { - const next = this.nextPlaySeat(); - if (next === null) { this.startDealerTurn(); return; } - this.gs = { ...this.gs, currentSeat: next }; - this.advanceToPlayer(next); - return; - } - - this.highlightActiveSeat(seat); - if (p.isHuman) { - this.showActionButtons(); - } else { - this.time.delayedCall(900, () => this.runAITurn(seat)); - } - } - - showActionButtons() { - this.hideActionButtons(); - const seat = this.gs.currentSeat; - const p = this.gs.players[seat]; - const pos = SEAT_POS[seat]; - const by = 918; // just under the table felt - let bx = pos.portraitX + pos.portraitR + 80; // first button, just right of the portrait - - const btns = [ - new Button(this, bx, by, 'Hit', () => this.onHit(), { width: 120, height: 52, fontSize: 20 }), - ]; - bx += 130; - btns.push(new Button(this, bx, by, 'Stand', () => this.onStand(), { width: 120, height: 52, fontSize: 20 })); - if (canDouble(p)) { - bx += 130; - btns.push(new Button(this, bx, by, 'Double', () => this.onDouble(), { width: 130, height: 52, fontSize: 20 })); - } - if (canSplit(p) && p.chips >= p.bet) { - bx += 140; - btns.push(new Button(this, bx, by, 'Split', () => this.onSplit(), { width: 120, height: 52, fontSize: 20 })); - } - btns.forEach(btn => btn.setDepth(D.ui + 5)); - this.actionBtns = btns; - } - - hideActionButtons() { - for (const b of this.actionBtns) b.destroy?.(); - this.actionBtns = []; - } - - onPlayerBust(seat) { - this.bustedSeats.add(seat); - // Fade current card graphics (new renders will stay faded via bustedSeats) - for (const c of this.cardGraphics[seat] ?? []) { - this.tweens.add({ targets: c, alpha: 0.3, duration: 280, ease: 'Power2' }); - } - // Chips fly to dealer immediately - this.animateChipsToDealer(seat); - // Opponent portrait: play upset once, Portrait.js auto-returns to idle on ended - if (seat > 0 && this.portraits[seat]) { - this.portraits[seat].playEmotion?.('upset'); - } - } - - onHit() { - this.hideActionButtons(); - this.animateActionText(this.gs.currentSeat, 'hit'); - this.animating = true; - this.gs = applyHit(this.gs, this.gs.currentSeat, this.shoe); - const p = this.gs.players[this.gs.currentSeat]; - const newCard = p.activeHand === 1 - ? p.hand2[p.hand2.length - 1] - : p.hand[p.hand.length - 1]; - - this.animateSingleCard(this.gs.currentSeat, newCard, () => { - this.renderSeatCards(this.gs.currentSeat); - this.time.delayedCall(200, () => { - this.animating = false; - if (isBust(p.activeHand === 1 ? p.hand2 : p.hand)) { - this.onPlayerBust(this.gs.currentSeat); - this.time.delayedCall(380, () => this.playerDone(this.gs.currentSeat)); - } else { - this.showActionButtons(); - } - }); - }); - } - - onStand() { - this.hideActionButtons(); - const seat = this.gs.currentSeat; - this.animateActionText(seat, 'stand'); - this.gs = applyStand(this.gs, seat); - const p = this.gs.players[seat]; - // If split and now playing hand 2, stay on same seat - if (p.activeHand === 1 && p.status2 === null) { - this.showActionButtons(); - return; - } - this.playerDone(seat); - } - - onDouble() { - this.hideActionButtons(); - this.animateActionText(this.gs.currentSeat, 'double'); - this.animating = true; - this.gs = applyDouble(this.gs, this.gs.currentSeat, this.shoe); - this.renderSeatCards(this.gs.currentSeat); - this.renderBetAreas(); - this.time.delayedCall(300, () => { - this.animating = false; - const p = this.gs.players[this.gs.currentSeat]; - if (p.status === 'bust' || p.status2 === 'bust') { - this.onPlayerBust(this.gs.currentSeat); - this.time.delayedCall(380, () => this.playerDone(this.gs.currentSeat)); - } else { - this.playerDone(this.gs.currentSeat); - } - }); - } - - onSplit() { - this.hideActionButtons(); - this.animateActionText(this.gs.currentSeat, 'split'); - this.animating = true; - this.gs = applySplit(this.gs, this.gs.currentSeat, this.shoe); - this.renderSeatCards(this.gs.currentSeat); - this.renderBetAreas(); - this.time.delayedCall(400, () => { - this.animating = false; - const p = this.gs.players[this.gs.currentSeat]; - // If ace split, both hands are immediately standing - if (isPlayerDone(p)) { - this.playerDone(this.gs.currentSeat); - } else { - this.showActionButtons(); - } - }); - } - - playerDone(seat) { - const p = this.gs.players[seat]; - // If split: check if hand 2 needs to be played - if (p.hand2 !== null && p.activeHand === 0 && !isPlayerDone(p)) { - this.gs = applyStand(this.gs, seat); // moves to hand 2 - this.showActionButtons(); - return; - } - const next = this.nextPlaySeat(); - if (next === null) { - this.startDealerTurn(); - } else { - this.gs = { ...this.gs, currentSeat: next }; - this.advanceToPlayer(next); - } - } - - // ── AI turn ─────────────────────────────────────────────────────────────── - runAITurn(seat) { - const p = this.gs.players[seat]; - if (!p || !p.active || isPlayerDone(p)) { - this.playerDone(seat); - return; - } - - const action = chooseAction(p, this.gs.dealer.hand[0]); - this.animateActionText(seat, action); - this.animating = true; - - const doAction = () => { - switch (action) { - case 'hit': - this.gs = applyHit(this.gs, seat, this.shoe); - const pp = this.gs.players[seat]; - const aiNewCard = pp.activeHand === 1 - ? pp.hand2[pp.hand2.length - 1] - : pp.hand[pp.hand.length - 1]; - this.animateSingleCard(seat, aiNewCard, () => { - this.renderSeatCards(seat); - this.time.delayedCall(400, () => { - this.animating = false; - const pp2 = this.gs.players[seat]; - if (isBust(pp2.activeHand === 1 ? pp2.hand2 : pp2.hand)) { - this.onPlayerBust(seat); - this.time.delayedCall(400, () => this.playerDone(seat)); - } else { - this.time.delayedCall(600, () => this.runAITurn(seat)); - } - }); - }); - break; - case 'double': - this.gs = applyDouble(this.gs, seat, this.shoe); - this.renderSeatCards(seat); - this.renderBetAreas(); - this.time.delayedCall(600, () => { - this.animating = false; - const pp = this.gs.players[seat]; - if (pp.status === 'bust' || pp.status2 === 'bust') { - this.onPlayerBust(seat); - this.time.delayedCall(400, () => this.playerDone(seat)); - } else { - this.playerDone(seat); - } - }); - break; - case 'split': - this.gs = applySplit(this.gs, seat, this.shoe); - this.renderSeatCards(seat); - this.renderBetAreas(); - this.time.delayedCall(600, () => { - this.animating = false; - // Play each hand in turn - this.time.delayedCall(700, () => this.runAITurn(seat)); - }); - break; - case 'stand': - default: - this.gs = applyStand(this.gs, seat); - this.time.delayedCall(400, () => { - this.animating = false; - // Handle split hand 2 - const pp = this.gs.players[seat]; - if (pp.hand2 !== null && pp.activeHand === 1 && pp.status2 === null) { - this.time.delayedCall(600, () => this.runAITurn(seat)); - } else { - this.playerDone(seat); - } - }); - break; - } - }; - doAction(); - } - - // ── Dealer turn ─────────────────────────────────────────────────────────── - startDealerTurn() { - this.clearActiveHighlight(); - this.gs = { ...this.gs, phase: 'dealer_turn', currentSeat: -1 }; - this.renderAll(); - this.time.delayedCall(400, () => { - this.animateDealerReveal(() => { - this.runDealerHits(); - }); - }); - } - - runDealerHits() { - const { score } = handValue(this.gs.dealer.hand); - if (score >= 17) { - this.finishRound(); - return; - } - const newCard = this.shoe.pop(); - this.gs = { ...this.gs, dealer: { ...this.gs.dealer, hand: [...this.gs.dealer.hand, newCard] } }; - this.renderDealer(); - this.time.delayedCall(700, () => this.runDealerHits()); - } - - // ── Resolve ─────────────────────────────────────────────────────────────── - finishRound() { - this.gs = resolveRound(this.gs); - this.renderAll(); - this.showAllResults(() => { - this.updateServerChips(); - this.showNextRoundPrompt(); - }); - } - - showAllResults(onComplete) { - // Reveal top-right then clockwise around the table (PLAY_ORDER). - const seats = PLAY_ORDER.filter(seat => this.gs.players[seat]?.active); - if (seats.length === 0) { onComplete(); return; } - - let pending = seats.length; - const done = () => { if (--pending <= 0) onComplete(); }; - - seats.forEach((seat, i) => { - this.time.delayedCall(i * 480, () => this.animateSeatResult(seat, done)); - }); - } - - async updateServerChips() { - const human = this.gs.players[0]; - const delta = human.chipsWon ?? 0; - if (delta === 0) return; - try { - await api.post('/profile/chips/adjust', { delta }); - } catch { /* balance will resync next load */ } - } - - showNextRoundPrompt() { - const human = this.gs.players[0]; - this.renderAll(); - - if (human.chips <= 0) { - new Modal(this, 'Out of chips! Visit your profile to request a reset.', { - autoCloseMs: 4000, - }); - this.time.delayedCall(4200, () => this.scene.start('GameMenu')); - return; - } - - const btn = new Button(this, CX, 925, 'Next Round', () => { - btn.destroy(); - this.startNewRound(); - }, { width: 220, height: 60, fontSize: 24 }); - } } diff --git a/src/games/blackjack/BlackjackTable.js b/src/games/blackjack/BlackjackTable.js new file mode 100644 index 0000000..01c5a07 --- /dev/null +++ b/src/games/blackjack/BlackjackTable.js @@ -0,0 +1,109 @@ +// Blackjack table layout — Phaser-free so tools/verifyBlackjack.js can test it. +// +// The perspective projection and rail geometry are shared by every casino table +// (src/ui/casino/CasinoGeometry.js) and re-exported here; this file only adds +// Blackjack's seats, card spots, bet circles and felt lettering. + +import { polar, project, radialRotation } from '../../ui/casino/CasinoGeometry.js'; + +export * from '../../ui/casino/CasinoGeometry.js'; + +// ── Seats ──────────────────────────────────────────────────────────────────── +// Seat 0 is the human (bottom-centre); 1/2 bottom-right/left, 3/4 mid, 5/6 top. +// Order is outward-alternating so the table stays balanced with few opponents. +export const SEAT_ANGLES = [0, 25, -25, 49, -49, 71, -71]; + +// Turn order: dealer's left ("first base", screen-right top) clockwise. +export const PLAY_ORDER = [5, 3, 1, 0, 2, 4, 6]; + +export const CARD_R = 0.655; // radius of each seat's card spot +export const BET_R = 0.885; // radius of each seat's betting circle +export const BET_SPOT_R = 0.058; +export const BADGE_R = 0.772; // hand-total badge, between the cards and the bet circle +export const CARD_ROT_DAMP = 0.62; // how much cards turn to face their seat + +// Portrait centres sit outside the rail. Bottom seats are pushed sideways +// because the HUD dock owns the bottom of the screen. Seat 0 (the human) +// lives in the dock. +const PORTRAITS = [ + { x: 160, y: 1013, r: 50 }, // 0 human — in the dock, bottom-left + { x: 1556, y: 812, r: 56 }, // 1 right-bottom + { x: 364, y: 812, r: 56 }, // 2 left-bottom + { x: 1786, y: 640, r: 56 }, // 3 right-mid + { x: 134, y: 640, r: 56 }, // 4 left-mid + { x: 1810, y: 330, r: 56 }, // 5 right-top + { x: 110, y: 330, r: 56 }, // 6 left-top +]; + +// Screen rotation for a seat's cards: their bottom edge turns toward the seat. +function cardRotation(theta) { + return radialRotation(CARD_R, theta, CARD_ROT_DAMP); +} + +export function seatLayout(seat) { + const theta = SEAT_ANGLES[seat]; + const card = { ...polar(CARD_R, theta), rot: cardRotation(theta) }; + const bet = polar(BET_R, theta); + const badge = polar(BADGE_R, theta); + return { seat, theta, card, bet, badge, portrait: { ...PORTRAITS[seat] } }; +} + +// Where a hand's cards go. `hand` is 0/1 for split hands (null = unsplit); +// returns the screen pose of card `idx` of `total`. +export const CARD_FAN = { dx: 27, dy: -7 }; // per-card offset in the card's own frame (px @ s=1) +export const SPLIT_GAP = 0.74; // split hands sit ±this many card-widths apart + +export function cardPose(seat, idx, total, hand = null, cardW = 96) { + const { card } = seatLayout(seat); + const s = card.s; + const cos = Math.cos(card.rot), sin = Math.sin(card.rot); + let lx = (idx - (total - 1) / 2) * CARD_FAN.dx * s; + let ly = (idx - (total - 1) / 2) * CARD_FAN.dy * s; + if (hand !== null) lx += (hand === 0 ? -1 : 1) * SPLIT_GAP * cardW * s; + return { + x: card.x + lx * cos - ly * sin, + y: card.y + lx * sin + ly * cos, + rot: card.rot, + s, + }; +} + +// Split hands put their bets / badges a few degrees either side of the seat line. +export const SPLIT_DEG = 6; + +export function betPose(seat, hand = null) { + const theta = SEAT_ANGLES[seat] + (hand === null ? 0 : (hand === 0 ? -SPLIT_DEG : SPLIT_DEG)); + return polar(BET_R, theta); +} + +export function badgePose(seat, hand = null) { + const theta = SEAT_ANGLES[seat] + (hand === null ? 0 : (hand === 0 ? -SPLIT_DEG * 1.15 : SPLIT_DEG * 1.15)); + return polar(BADGE_R, theta); +} + +// Insurance bets sit on the insurance line in front of the seat. +export const INSURANCE_R = 0.348; +export function insurancePose(seat) { + return polar(INSURANCE_R, SEAT_ANGLES[seat] * 0.55); +} + +// ── Felt lettering (table-space arcs) ──────────────────────────────────────── +export const INSURANCE_LINES = { r0: 0.312, r1: 0.386, span: 34 }; +export const FELT_TEXT = [ + { text: 'INSURANCE PAYS 2 TO 1', r: 0.349, size: 21, color: '#f2ead8', alpha: 0.82, spacing: 1.0 }, + { text: 'BLACKJACK PAYS 3 TO 2', r: 0.452, size: 36, color: '#e8c15a', alpha: 0.95, spacing: 1.02, bold: true }, + { text: 'DEALER MUST STAND ON ALL 17s \u00b7 DRAW TO 16', r: 0.525, size: 19, color: '#f2ead8', alpha: 0.7, spacing: 0.94 }, +]; + +// ── Dealer side ────────────────────────────────────────────────────────────── +export const DEALER_V = 0.205; // dealer hand row +export const DEALER_SCALE_BOOST = 1.1; // far cards read a little bigger than strict perspective +export const SHOE = { u: 0.47, v: 0.085 }; +export const DISCARD = { u: -0.47, v: 0.085 }; +export const PLACARD = { u: -0.335, v: 0.035 }; + +export function dealerCardPose(idx, total) { + const p = project(0, DEALER_V); + const s = p.s * DEALER_SCALE_BOOST; + return { x: p.x + (idx - (total - 1) / 2) * 40 * s, y: p.y, rot: 0, s }; +} diff --git a/src/games/paigow/PaiGowArt.js b/src/games/paigow/PaiGowArt.js new file mode 100644 index 0000000..03e5b00 --- /dev/null +++ b/src/games/paigow/PaiGowArt.js @@ -0,0 +1,70 @@ +// Pai Gow Poker table art: royal-blue felt, a bet circle + HIGH / LOW boxes per +// seat, dealer HIGH / LOW boxes. The shared kit bakes everything else. + +import { prepareCasinoArt, bakeCasinoTable, poly, rr } from '../../ui/casino/CasinoArt.js'; +import { + VIEW, feltCircle, seatLayout, dealerHighBox, dealerLowBox, + BET_R, BET_SPOT_R, SEAT_ANGLES, FAN_DX, CARD_W, CARD_H, + FELT_TEXT, TRAY, DISCARD, PLACARD, +} from './PaiGowTable.js'; + +const MARKED_SEATS = [0, 1, 2, 3, 4]; + +function box(ctx, pose, n, label) { + const w = CARD_W + (n - 1) * FAN_DX + 26; + const h = CARD_H + 16; + ctx.save(); + ctx.translate(pose.x, pose.y); + ctx.rotate(pose.rot); + ctx.scale(pose.s, pose.s * VIEW.squash); + rr(ctx, -w / 2, -h / 2, w, h, 12); + ctx.fillStyle = 'rgba(0,0,0,0.12)'; + ctx.fill(); + ctx.lineWidth = 2.2 / pose.s; + ctx.strokeStyle = 'rgba(242,234,216,0.42)'; + ctx.stroke(); + ctx.fillStyle = 'rgba(232,193,90,0.75)'; + ctx.font = 'bold 20px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(label, 0, 0); + ctx.font = '13px "Julius Sans One", sans-serif'; + ctx.fillStyle = 'rgba(242,234,216,0.5)'; + ctx.fillText(n === 5 ? '5 CARDS' : '2 CARDS', 0, 24); + ctx.restore(); +} + +function drawMarkings(ctx) { + for (const seat of MARKED_SEATS) { + const t = (SEAT_ANGLES[seat] * Math.PI) / 180; + const u = BET_R * Math.sin(t), v = BET_R * Math.cos(t); + poly(ctx, feltCircle(u, v, BET_SPOT_R)); + ctx.fillStyle = 'rgba(0,0,0,0.14)'; + ctx.fill(); + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(217,180,90,0.85)'; + ctx.stroke(); + poly(ctx, feltCircle(u, v, BET_SPOT_R * 0.8)); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(242,234,216,0.4)'; + ctx.stroke(); + + const L = seatLayout(seat); + box(ctx, L.high, 5, 'HIGH'); + box(ctx, L.low, 2, 'LOW'); + } + box(ctx, dealerHighBox(), 5, 'HIGH'); + box(ctx, dealerLowBox(), 2, 'LOW'); +} + +export async function preparePaiGowArt(scene) { + await prepareCasinoArt(scene); + bakeCasinoTable(scene, 'pg-table', { + felt: '#123c78', + markings: drawMarkings, + text: FELT_TEXT, + tray: TRAY, + discard: DISCARD, + placard: PLACARD, + }); +} diff --git a/src/games/paigow/PaiGowPokerGame.js b/src/games/paigow/PaiGowPokerGame.js index 6e35e37..89669ec 100644 --- a/src/games/paigow/PaiGowPokerGame.js +++ b/src/games/paigow/PaiGowPokerGame.js @@ -2,60 +2,52 @@ import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { Modal } from '../../ui/Modal.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { createOpponentPortrait } from '../../ui/Portrait.js'; import { api } from '../../services/api.js'; import { playSound, playChipBet, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { makeChipStack, throwChip, throwStack, settleStack } from '../../ui/CasinoChips.js'; +import { CasinoDock } from '../../ui/casino/CasinoDock.js'; +import { CardSkin, withJitter } from '../../ui/casino/CasinoCards.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; import { - HAND_RANK, makeJoker, - evaluate5Card, evaluate2Card, compare5Card, compare2Card, - isFoul, handName5, rankLabel, + evaluate5Card, evaluate2Card, compare5Card, compare2Card, isFoul, handName5, createInitialState, prepareRound, applyBet, dealHands, applyHumanSplit, applyHouseWaySplit, applyDealerHouseWay, resolveRound, } from './PaiGowPokerLogic.js'; import { chooseBet, houseWay } from './PaiGowPokerAI.js'; +import { + VIEW, project, seatLayout, fanPose, stackPose, boxCorner, boxBadge, + dealerHighBox, dealerLowBox, dealerRowPose, PLAY_ORDER, + DICE_CUP, DICE_LAND, DECK, DISCARD, TRAY, DOCK, CARD_W, CARD_H, + SET_TRAY, TRAY_CARD_Y, TRAY_SCALE, TRAY_HIGH, TRAY_LOW, trayHighX, trayLowX, + diceStartIndex, rotateFrom, +} from './PaiGowTable.js'; +import { preparePaiGowArt } from './PaiGowArt.js'; -// ─── Layout ─────────────────────────────────────────────────────────────────── +// ─── Layout / tuning ────────────────────────────────────────────────────────── +// Positions come from PaiGowTable.js (shared casino perspective); the art is +// baked by PaiGowArt.js + the shared casino kit. This file is flow + animation. const CX = GAME_WIDTH / 2; -const CARD_W = 90; -const CARD_H = 126; -const CARD_R = 8; -const CARD_SPREAD_FAN = 22; // overlap in 7-card fan at opponent seats -const CARD_SPREAD_SPLIT = 10; // tighter spread for 5-card split display on main table -const MODAL_CARD_SPREAD = 55; // wider spread so each card is clearly visible in comparison modal - -const TABLE_CY = 475; // table centre — slightly higher than Blackjack to make room for panel - -const DEALER_X = CX; -const DEALER_Y = 315; - -// Seat 0 = human (bottom-centre); seats 1-5 = AI -const SEAT_POS = [ - { x: CX, y: 762, portraitR: 72, portraitX: CX - 230, portraitY: 840, betX: 1110, betY: 750 }, - { x: 1380, y: 690, portraitR: 58, portraitX: 1600, portraitY: 780 }, - { x: 540, y: 690, portraitR: 58, portraitX: 320, portraitY: 780 }, - { x: 1560, y: 560, portraitR: 58, portraitX: 1805, portraitY: 583 }, - { x: 360, y: 560, portraitR: 58, portraitX: 115, portraitY: 583 }, - { x: 1440, y: 395, portraitR: 58, portraitX: 1675, portraitY: 320, labelDX: 10 }, -]; - -// AI turn order (clockwise from top-right) -const PLAY_ORDER = [5, 3, 1, 0, 2, 4]; - -const CHIP_COLORS = { 5: 0xe05c5c, 25: 0x5cb85c, 50: 0x4a90d9, 100: 0x2c2c2c }; +const SQ = VIEW.squash; +const DOCK_Y = DOCK.y + DOCK.h / 2; +const MIN_BET = 5; +const MAX_BET = 100; const CHIP_AMOUNTS = [5, 25, 50, 100]; -const RESULT_COLORS = { win: '#5cb85c', lose: '#e05c5c', push: '#8a94a6', foul: '#e05c5c' }; +const STACK_SIZE = 54; +const FELT = '#123c78'; -const D = { bg: -1, table: 0, chips: 10, cards: 20, ui: 30, panel: 25, modal: 50 }; +const RESULT_LABELS = { win: 'Win!', push: 'Push', lose: 'Lose', foul: 'Foul' }; +const RESULT_COLORS = { win: '#f5d020', push: '#9aa5b4', lose: '#e05c5c', foul: '#e05c5c' }; -// ─── Hand-setting panel geometry ────────────────────────────────────────────── -const PANEL_H = 390; // panel height -const PANEL_Y0 = Math.round(540 - PANEL_H / 2); // vertically centred on 1080px canvas -const HIGH_SLOT_CX = 480; // centre-X of 5-card zone -const LOW_SLOT_CX = 1440; // centre-X of 2-card zone -const SLOT_Y = PANEL_Y0 + 95; // centre-Y of drop slots -const SOURCE_Y = PANEL_Y0 + 275; // centre-Y of source cards (180px below slot centre) -const SLOT_GAP = 100; // slot-to-slot horizontal spacing +const D = { + bg: -2, playfield: -1, table: 0, cards: 10, stacks: 12, flying: 22, badges: 24, + dock: 26, ui: 30, dockUi: 32, tray: 33, trayCards: 35, trayUi: 36, prompt: 38, + closeup: 44, modal: 50, +}; + +// Pre-reveal staging row where the dealer builds the seven-card stacks. +const STAGING_V = 0.315; // ─── Scene ──────────────────────────────────────────────────────────────────── export default class PaiGowPokerGame extends Phaser.Scene { @@ -71,745 +63,222 @@ export default class PaiGowPokerGame extends Phaser.Scene { async create() { new MusicPlayer(this, this.cache.json.get('music').tracks); this.gs = null; - this.animating = false; + this.busy = false; this.pendingBet = 0; + this.lastBet = 0; this.portraits = []; - this.seatCardGraphics = {}; // seat → [containers] for the 7-card fan - this.dealerCardGraphics = []; - this.betGraphics = {}; - this.actionBtns = []; - this.bettingUIGroup = []; - this.chipBtnGraphics = []; - this.betDisplayText = null; - this.balanceText = null; - this.scoreTxts = {}; + this.cards = new Map(); // 'seat:i' / 'd:i' (i = index into hand) → card container + this.stacks = {}; // seat → chip stack + this.settled = new Set(); + this.decor = []; // badges, markers — cleared each round this.nameTxts = {}; this.chipTxts = {}; - - // Hand-setting panel state - this.setPanelGroup = []; // all objects in the panel (toggled visible) - this.setCardConts = []; // 7 containers, one per dealt card - this.setHighSlots = []; // 5 slot graphics - this.setLowSlots = []; // 2 slot graphics - this.humanHighSlots = [null, null, null, null, null]; - this.humanLowSlots = [null, null]; - this.selectedCardIdx = null; // which source-card index is selected - this.highRankTxt = null; - this.lowRankTxt = null; - this.foulWarnTxt = null; - this.setHandBtn = null; - this.houseWayBtn = null; - this.panelVisible = false; + this.dockMode = null; + this.lowSel = []; + this.trayOrder = []; + this.trayActive = false; + this.aiSetPromise = Promise.resolve(); this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); this.buildPlayfield(); - this.buildTable(); - this.buildTableMarkings(); + + await preparePaiGowArt(this); + if (!this.sys.isActive()) return; + this.skin = new CardSkin(this, this.cardBack, { depth: D.cards }); + + this.add.image(0, 0, 'pg-table').setOrigin(0, 0).setDepth(D.table); this.buildDealerArea(); this.buildSeats(); - this.buildBettingUI(); - this.buildHandSetPanel(); + this.buildDock(); + this.buildSetTray(); - new Button(this, 80, GAME_HEIGHT - 44, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 140, fontSize: 20, - }); + new Button(this, 84, 44, 'Leave', () => this.scene.start('GameMenu'), { + variant: 'ghost', width: 140, height: 48, fontSize: 20, + }).setDepth(D.ui); + + this.input.dragDistanceThreshold = 6; + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); await this.loadPlayerChips(); - this.initGame(); + if (!this.sys.isActive()) return; + this.gs = createInitialState(this.opponents, this._playerChips); + this.startNewRound(); } - // ── Playfield ───────────────────────────────────────────────────────────── + wait(ms) { return new Promise(res => this.time.delayedCall(ms, res)); } + + tweenP(cfg) { + return new Promise(res => { + this.tweens.add({ ...cfg, onComplete: (...a) => { cfg.onComplete?.(...a); res(); } }); + }); + } + + // ── Static scenery ───────────────────────────────────────────────────────── buildPlayfield() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg + 1); + this.add.image(CX, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.playfield); } } - // ── Table ───────────────────────────────────────────────────────────────── - buildTable() { - const g = this.add.graphics().setDepth(D.table); - g.fillStyle(0x1a5c2a, 1); - g.fillEllipse(CX, TABLE_CY, 1500, 680); - g.lineStyle(8, 0x2e7d32, 1); - g.strokeEllipse(CX, TABLE_CY, 1500, 680); - g.lineStyle(3, 0x4caf50, 0.4); - g.strokeEllipse(CX, TABLE_CY, 1440, 620); - } - - buildTableMarkings() { - const g = this.add.graphics().setDepth(D.table + 1); - - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const active = seat === 0 ? true : !!(this.opponents[seat - 1] ?? null); - if (!active) continue; - const pos = SEAT_POS[seat]; - g.lineStyle(2, 0xffffff, 0.5); - g.strokeRoundedRect(pos.x - CARD_W / 2 - 4, pos.y - CARD_H / 2 - 4, CARD_W + 8, CARD_H + 8, CARD_R + 2); - const { x: bx, y: by } = this.betCirclePos(seat); - g.lineStyle(2, 0xffffff, 0.55); - g.strokeCircle(bx, by, 30); - } - - this.drawArcText('PAI GOW POKER', CX, 580, 760, { - fontSize: 32, color: COLORS.goldHex, bold: true, advanceFactor: 0.96, - }); - this.drawArcText('BANKER WINS ALL TIES · 5% COMMISSION ON WINS', CX, 636, 720, { - fontSize: 19, color: COLORS.mutedHex, advanceFactor: 0.84, - }); - } - - drawArcText(text, centerX, baseY, radius, opts = {}) { - const fontSize = opts.fontSize ?? 24; - const anglePer = ((opts.advanceFactor ?? 0.92) * fontSize) / radius; - const cy = baseY - radius; - const start = -anglePer * (text.length - 1) / 2; - const style = { - fontFamily: opts.fontFamily ?? '"Julius Sans One"', - fontSize: `${fontSize}px`, - color: opts.color ?? COLORS.textHex, - ...(opts.bold ? { fontStyle: 'bold' } : {}), - }; - const depth = opts.depth ?? (D.table + 1); - for (let i = 0; i < text.length; i++) { - if (text[i] === ' ') continue; - const a = start + i * anglePer; - this.add.text(centerX + radius * Math.sin(a), cy + radius * Math.cos(a), text[i], style) - .setOrigin(0.5).setRotation(-a).setDepth(depth); - } - } - - // ── Dealer area ─────────────────────────────────────────────────────────── buildDealerArea() { - this.add.text(CX, 55, 'Pai Gow Poker', { + this.add.text(CX, 52, 'Pai Gow Poker', { fontFamily: 'Righteous', fontSize: '48px', color: COLORS.textHex, + shadow: { offsetX: 0, offsetY: 3, color: '#000000', blur: 10, fill: true }, }).setOrigin(0.5).setDepth(D.ui); - this.dealerHighLabel = this.add.text(CX - 170, DEALER_Y - CARD_H / 2 - 24, '', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); + const deck = project(DECK.u, DECK.v); + this.deckPos = { x: deck.x, y: deck.y, s: deck.s * 0.92 }; + const disc = project(DISCARD.u, DISCARD.v); + this.discardPos = { x: disc.x, y: disc.y - 6 * disc.s, s: disc.s * 0.85 }; + const tray = project((TRAY.u0 + TRAY.u1) / 2, (TRAY.v0 + TRAY.v1) / 2); + this.trayPos = { x: tray.x, y: tray.y, s: tray.s }; + const cup = project(DICE_CUP.u, DICE_CUP.v); + this.cupPos = cup; + this.cup = this.add.image(cup.x, cup.y + 8, 'casino-dice-cup') + .setOrigin(0.5, 0.88).setScale(0.62 * cup.s / 0.72).setDepth(D.cards + 1); - this.dealerLowLabel = this.add.text(CX + 170, DEALER_Y - CARD_H / 2 - 24, '', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); + // A face-down deck in the dealer's hands. + this.deckSprites = []; + for (let i = 0; i < 4; i++) { + const c = this.skin.make(null, false, deck.x + i * 0.8, deck.y - i * 1.6, deck.s * 0.92, -0.08); + c.setDepth(D.cards); + this.deckSprites.push(c); + } } - // ── Seats ───────────────────────────────────────────────────────────────── buildSeats() { - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const pos = SEAT_POS[seat]; - const opp = seat === 0 ? null : this.opponents[seat - 1] ?? null; - const active = seat === 0 ? true : !!opp; - if (!active) continue; - - const px = pos.portraitX ?? pos.x; - const py = pos.portraitY ?? (pos.y - CARD_H / 2 - (pos.portraitR ?? 58) - 60); - const labelX = px + (pos.labelDX ?? 0); - const nameY = py + (pos.portraitR ?? 58) + 18; + for (let seat = 1; seat <= 5; seat++) { + const opp = this.opponents[seat - 1]; + if (!opp) continue; + const pt = seatLayout(seat).portrait; + const nameY = pt.y + pt.r + 18; const chipY = nameY + 24; - - this.nameTxts[seat] = this.add.text(labelX, nameY, seat === 0 ? 'You' : opp.name, { + this.nameTxts[seat] = this.add.text(pt.x, nameY, opp.name ?? '', { fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, }).setOrigin(0.5).setDepth(D.ui); - - this.chipTxts[seat] = this.add.text(labelX, chipY, '', { + this.chipTxts[seat] = this.add.text(pt.x, chipY, '', { fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, }).setOrigin(0.5).setDepth(D.ui); - - { - const maxTW = Math.max(this.nameTxts[seat].width, 130); - const rectW = maxTW + 20; - const rectH = (chipY - nameY) + 36; - const bg = this.add.graphics().setDepth(D.ui - 1); - bg.fillStyle(0x000000, 0.60); - bg.fillRoundedRect(labelX - rectW / 2, (nameY + chipY) / 2 - rectH / 2, rectW, rectH, 6); - } - - this.scoreTxts[seat] = this.add.text(pos.x, pos.y - CARD_H / 2 - 11, '', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - if (seat === 0) { - this.portraits[seat] = createPlayerPortrait(this, px, py, pos.portraitR ?? 72, D.ui, 'PaiGowPokerGame'); - } else { - this.portraits[seat] = createOpponentPortrait(this, opp, px, py, pos.portraitR ?? 58, D.ui); - } + const rectW = Math.max(this.nameTxts[seat].width, 130) + 20; + const rectH = (chipY - nameY) + 36; + const bg = this.add.graphics().setDepth(D.ui - 1); + bg.fillStyle(0x000000, 0.6); + bg.fillRoundedRect(pt.x - rectW / 2, (nameY + chipY) / 2 - rectH / 2, rectW, rectH, 6); + this.portraits[seat] = createOpponentPortrait(this, opp, pt.x, pt.y, pt.r, D.ui); } } - // ── Betting UI ──────────────────────────────────────────────────────────── - buildBettingUI() { - const y = GAME_HEIGHT - 80; - const cx = CX + 60; - - const panel = this.add.graphics().setDepth(D.ui); - panel.fillStyle(0x000000, 1); - panel.fillRoundedRect(cx - 174, y - 69, 726, 116, 18); - panel.lineStyle(3, COLORS.accent, 1); - panel.strokeRoundedRect(cx - 174, y - 69, 726, 116, 18); - this.bettingUIGroup.push(panel); - - CHIP_AMOUNTS.forEach((amt, i) => { - const bx = cx - 120 + i * 80; - const container = this.add.container(bx, y).setDepth(D.ui + 1); - const g = this.add.graphics(); - g.lineStyle(3, 0xffffff, 0.4); - g.strokeCircle(0, 0, 28); - g.fillStyle(CHIP_COLORS[amt], 1); - g.fillCircle(0, 0, 28); - container.add(g); - container.setInteractive(new Phaser.Geom.Circle(0, 0, 28), Phaser.Geom.Circle.Contains); - container.on('pointerdown', () => this.onChipClick(amt)); - container.on('pointerover', () => container.setAlpha(0.8)); - container.on('pointerout', () => container.setAlpha(1)); - - const t = this.add.text(bx, y, `$${amt}`, { - fontFamily: '"Julius Sans One"', fontSize: '13px', - color: '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.ui + 2); - - this.bettingUIGroup.push(container, t); - this.chipBtnGraphics.push(container); + buildDock() { + this.dock = new CasinoDock(this, { + sceneName: 'PaiGowPokerGame', + portrait: seatLayout(0).portrait, + depth: { dock: D.dock, ui: D.ui, dockUi: D.dockUi, prompt: D.prompt }, + chipAmounts: CHIP_AMOUNTS, chipX0: 470, chipDX: 88, chipSize: 74, + betPillX: 850, + keys: { + bet: '1–4 add chips · Space deal / rebet · R rebet · C clear', + next: 'Space next round · R rebet & deal', + }, + canChip: (amt) => this.chipAffordable(amt), + onChip: (amt) => this.onChipClick(amt), }); + this.portraits[0] = this.dock.portrait; + this.nameTxts[0] = this.dock.nameTxt; + this.chipTxts[0] = this.dock.balanceTxt; - this.betDisplayText = this.add.text(cx + 170, y, 'Bet: $0', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui + 1); - - this.balanceText = this.add.text(cx + 170, y - 32, '', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.ui + 1); - - const clearBtn = new Button(this, cx + 360, y, 'Clear', () => this.onClearBet(), { - width: 100, height: 50, fontSize: 18, variant: 'ghost', - }); - this.dealBtn = new Button(this, cx + 470, y, 'Deal', () => this.onDealClick(), { - width: 110, height: 50, fontSize: 20, - }); - this.dealBtn.setEnabled(false); - clearBtn.setDepth(D.ui + 1); - this.dealBtn.setDepth(D.ui + 1); - - this.bettingUIGroup.push(this.betDisplayText, this.balanceText, clearBtn, this.dealBtn); - this.hideBettingUI(); + const btnOpts = { width: 116, height: 50, fontSize: 18, variant: 'ghost' }; + this.clearBtn = new Button(this, 1080, DOCK_Y, 'Clear', () => this.onClearBet(), btnOpts); + this.rebetBtn = new Button(this, 1204, DOCK_Y, 'Rebet', () => this.onRebet(1), btnOpts); + this.rebet2Btn = new Button(this, 1328, DOCK_Y, 'Rebet x2', () => this.onRebet(2), btnOpts); + this.dealBtn = new Button(this, 1474, DOCK_Y, 'Deal', () => this.onDealClick(), { width: 150, height: 56, fontSize: 24 }); + for (const b of [this.clearBtn, this.rebetBtn, this.rebet2Btn, this.dealBtn]) b.setDepth(D.dockUi); + this.dock.addToGroup('bet', this.clearBtn, this.rebetBtn, this.rebet2Btn, this.dealBtn); } - showBettingUI() { - for (const o of this.bettingUIGroup) o.setVisible?.(true) ?? (o.visible = true); - } - hideBettingUI() { - for (const o of this.bettingUIGroup) o.setVisible?.(false) ?? (o.visible = false); + // ── Hand-setting tray (rises out of the dock) ────────────────────────────── + buildSetTray() { + const w = SET_TRAY.x1 - SET_TRAY.x0, h = SET_TRAY.y1 - SET_TRAY.y0; + ensureLeatherPanel(this, 'pg-set-tray', w, h + 20, { radius: 20, felt: FELT }); + const bg = this.add.image(SET_TRAY.x0, SET_TRAY.y0, 'pg-set-tray').setOrigin(0, 0).setDepth(D.tray); + + const zones = this.add.graphics().setDepth(D.tray + 1); + const zy = TRAY_CARD_Y - (CARD_H * TRAY_SCALE) / 2 - 10; + const zh = CARD_H * TRAY_SCALE + 20; + zones.lineStyle(2, 0xf2ead8, 0.35); + zones.strokeRoundedRect(TRAY_HIGH.x0, zy, TRAY_HIGH.x1 - TRAY_HIGH.x0, zh, 12); + zones.lineStyle(2, 0xe8c15a, 0.7); + zones.strokeRoundedRect(TRAY_LOW.x0, zy, TRAY_LOW.x1 - TRAY_LOW.x0, zh, 12); + + const mid = (a) => (a.x0 + a.x1) / 2; + const style = (size, color) => ({ fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color }); + const title = this.add.text(CX - 60, SET_TRAY.y0 + 26, + 'SET YOUR HAND — pick 2 cards for the LOW hand, the other 5 play HIGH', style(17, '#f7ecd0')) + .setOrigin(0.5).setDepth(D.trayUi); + const hiLabel = this.add.text(mid(TRAY_HIGH), zy - 12, 'HIGH · 5 CARDS', style(14, '#c9c2b0')) + .setOrigin(0.5).setDepth(D.trayUi); + const loLabel = this.add.text(mid(TRAY_LOW), zy - 12, 'LOW · 2 CARDS', style(14, '#e8c15a')) + .setOrigin(0.5).setDepth(D.trayUi); + this.highNameTxt = this.add.text(mid(TRAY_HIGH), zy + zh + 18, '', style(20, '#f5d020')) + .setOrigin(0.5).setDepth(D.trayUi); + this.lowNameTxt = this.add.text(mid(TRAY_LOW), zy + zh + 18, '', style(20, '#f5d020')) + .setOrigin(0.5).setDepth(D.trayUi); + this.foulTxt = this.add.text((TRAY_HIGH.x0 + TRAY_LOW.x1) / 2, zy + zh + 46, '', style(16, '#ff8a80')) + .setOrigin(0.5).setDepth(D.trayUi); + const legend = this.add.text(CX - 60, SET_TRAY.y1 - 12, + 'Click or drag cards · 1–7 toggle a card · W house way · C clear · Enter set hand', style(13, '#9e9080')) + .setOrigin(0.5).setDepth(D.trayUi); + + const bx = 1398; + this.houseWayBtn = new Button(this, bx, 840, 'House Way', () => this.applyHouseWay(), { width: 190, height: 50, fontSize: 18, variant: 'ghost' }); + this.trayClearBtn = new Button(this, bx, 900, 'Clear', () => this.clearTray(), { width: 190, height: 50, fontSize: 18, variant: 'ghost' }); + this.setHandBtn = new Button(this, bx, 972, 'Set Hand', () => this.onSetHand(), { width: 190, height: 62, fontSize: 24 }); + for (const b of [this.houseWayBtn, this.trayClearBtn, this.setHandBtn]) b.setDepth(D.trayUi); + + this.dock.addToGroup('set', bg, zones, title, hiLabel, loLabel, this.highNameTxt, this.lowNameTxt, + this.foulTxt, legend, this.houseWayBtn, this.trayClearBtn, this.setHandBtn); } - // ── Hand-setting panel ──────────────────────────────────────────────────── - buildHandSetPanel() { - const panelBg = this.add.graphics().setDepth(D.panel).setVisible(false); - panelBg.fillStyle(0x000000, 0.90); - panelBg.fillRoundedRect(40, PANEL_Y0, GAME_WIDTH - 80, PANEL_H, 14); - panelBg.lineStyle(2, COLORS.accent, 0.7); - panelBg.strokeRoundedRect(40, PANEL_Y0, GAME_WIDTH - 80, PANEL_H, 14); - this.setPanelGroup.push(panelBg); - - // Zone labels - const labelStyle = { fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex }; - const hiLabel = this.add.text(HIGH_SLOT_CX, PANEL_Y0 + 20, 'HIGH HAND (5 cards)', labelStyle) - .setOrigin(0.5).setDepth(D.panel + 1).setVisible(false); - const loLabel = this.add.text(LOW_SLOT_CX, PANEL_Y0 + 20, 'LOW HAND (2 cards)', labelStyle) - .setOrigin(0.5).setDepth(D.panel + 1).setVisible(false); - this.setPanelGroup.push(hiLabel, loLabel); - - // Separator line between high and low zones - const sep = this.add.graphics().setDepth(D.panel + 1).setVisible(false); - sep.lineStyle(1, 0xffffff, 0.15); - sep.beginPath(); - sep.moveTo(1060, PANEL_Y0 + 10); - sep.lineTo(1060, PANEL_Y0 + PANEL_H - 10); - sep.strokePath(); - this.setPanelGroup.push(sep); - - // 5 drop-zone slots for high hand - this.setHighSlots = []; - for (let i = 0; i < 5; i++) { - const x = HIGH_SLOT_CX - 2 * SLOT_GAP + i * SLOT_GAP; - const g = this.add.graphics().setDepth(D.panel + 1).setVisible(false); - this.drawEmptySlot(g, x, SLOT_Y); - const zone = this.add.zone(x, SLOT_Y, CARD_W + 10, CARD_H + 10) - .setDepth(D.panel + 2).setDropZone().setVisible(false); - zone._pgSlot = { type: 'high', idx: i }; - zone.on('pointerdown', () => this.onHighSlotClick(i)); - this.setHighSlots.push({ g, zone, x, y: SLOT_Y }); - this.setPanelGroup.push(g, zone); - } - - // 2 drop-zone slots for low hand - this.setLowSlots = []; - for (let i = 0; i < 2; i++) { - const x = LOW_SLOT_CX - SLOT_GAP / 2 + i * SLOT_GAP; - const g = this.add.graphics().setDepth(D.panel + 1).setVisible(false); - this.drawEmptySlot(g, x, SLOT_Y); - const zone = this.add.zone(x, SLOT_Y, CARD_W + 10, CARD_H + 10) - .setDepth(D.panel + 2).setDropZone().setVisible(false); - zone._pgSlot = { type: 'low', idx: i }; - zone.on('pointerdown', () => this.onLowSlotClick(i)); - this.setLowSlots.push({ g, zone, x, y: SLOT_Y }); - this.setPanelGroup.push(g, zone); - } - - // Phaser drop-zone events — handle the actual card placement on drop - this.input.on('drop', (_ptr, gameObj, dropZone) => { - if (!this.panelVisible || !dropZone._pgSlot) return; - const cardIdx = this.setCardConts.indexOf(gameObj); - if (cardIdx === -1) return; - const { type, idx } = dropZone._pgSlot; - if (type === 'high') this._dropToHighSlot(cardIdx, idx); - else this._dropToLowSlot(cardIdx, idx); - }); - - this.input.on('dragenter', (_ptr, _obj, zone) => { - if (!this.panelVisible || !zone._pgSlot) return; - const { type, idx } = zone._pgSlot; - const slot = type === 'high' ? this.setHighSlots[idx] : this.setLowSlots[idx]; - this._drawHighlightSlot(slot.g, slot.x, SLOT_Y); - }); - - this.input.on('dragleave', (_ptr, _obj, zone) => { - if (!this.panelVisible || !zone._pgSlot) return; - const { type, idx } = zone._pgSlot; - const slot = type === 'high' ? this.setHighSlots[idx] : this.setLowSlots[idx]; - this.drawEmptySlot(slot.g, slot.x, SLOT_Y); - }); - - // Live rank labels below the slots - this.highRankTxt = this.add.text(HIGH_SLOT_CX, SLOT_Y + CARD_H / 2 + 14, '', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.panel + 1).setVisible(false); - - this.lowRankTxt = this.add.text(LOW_SLOT_CX, SLOT_Y + CARD_H / 2 + 14, '', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.panel + 1).setVisible(false); - - // Foul warning - this.foulWarnTxt = this.add.text(CX, SLOT_Y + CARD_H / 2 + 14, '', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#e06c75', - }).setOrigin(0.5).setDepth(D.panel + 1).setVisible(false); - - this.setPanelGroup.push(this.highRankTxt, this.lowRankTxt, this.foulWarnTxt); - - // Buttons - this.houseWayBtn = new Button(this, HIGH_SLOT_CX - 100, PANEL_Y0 + PANEL_H - 28, 'House Way', () => this.applyHouseWayUI(), { - width: 150, height: 44, fontSize: 16, - }); - this.clearSetBtn = new Button(this, HIGH_SLOT_CX + 75, PANEL_Y0 + PANEL_H - 28, 'Clear', () => this.clearHandSet(), { - width: 110, height: 44, fontSize: 16, variant: 'ghost', - }); - this.setHandBtn = new Button(this, CX + 20, PANEL_Y0 + PANEL_H - 28, 'Set Hand', () => this.onSetHand(), { - width: 160, height: 44, fontSize: 18, - }); - this.setHandBtn.setEnabled(false); - this.houseWayBtn.setDepth(D.panel + 2); - this.clearSetBtn.setDepth(D.panel + 2); - this.setHandBtn.setDepth(D.panel + 2); - this.setPanelGroup.push(this.houseWayBtn, this.clearSetBtn, this.setHandBtn); - - this.hideHandSetPanel(); - } - - drawEmptySlot(g, cx, cy) { - g.clear(); - g.lineStyle(2, 0xffffff, 0.25); - g.strokeRoundedRect(cx - CARD_W / 2, cy - CARD_H / 2, CARD_W, CARD_H, CARD_R); - } - - drawSelectedSlot(g, cx, cy) { - g.clear(); - g.lineStyle(3, 0xf5d020, 0.9); - g.strokeRoundedRect(cx - CARD_W / 2, cy - CARD_H / 2, CARD_W, CARD_H, CARD_R); - } - - showHandSetPanel() { - this.panelVisible = true; - this.animating = true; - for (const o of this.setPanelGroup) o.setVisible(true); - for (const p of this.portraits) p?.hide?.(); - for (const t of Object.values(this.nameTxts)) t.setVisible(false); - for (const t of Object.values(this.chipTxts)) t.setVisible(false); - - // Grab the face-up seat cards that were just dealt - const seatCards = [...(this.seatCardGraphics[0] ?? [])]; - - const onAllArrived = () => { - // Swap animated seat cards for interactive panel cards - for (const c of seatCards) c.destroy(); - this.seatCardGraphics[0] = []; - this.buildSetCardContainers(); - this.updateHandSetUI(); - this.animating = false; - }; - - if (!seatCards.length) { onAllArrived(); return; } - - let done = 0; - seatCards.forEach((cont, i) => { - cont.setDepth(D.panel + 10); - this.tweens.add({ - targets: cont, - x: this.sourceCardX(i), - y: SOURCE_Y, - duration: 380, - delay: i * 65, - ease: 'Back.easeOut', - onComplete: () => { if (++done === seatCards.length) onAllArrived(); }, - }); - }); - } - - hideHandSetPanel() { - this.panelVisible = false; - this._clearDragHighlights(); - if (this._selRings) { for (const r of this._selRings) r.destroy(); this._selRings = []; } - for (const o of this.setPanelGroup) o.setVisible(false); - for (const c of this.setCardConts) c.destroy(); - this.setCardConts = []; - // Restore portraits and seat labels - for (const p of this.portraits) p?.show?.(); - for (const t of Object.values(this.nameTxts)) t.setVisible(true); - for (const t of Object.values(this.chipTxts)) t.setVisible(true); - } - - buildSetCardContainers() { - for (const c of this.setCardConts) c.destroy(); - this.setCardConts = []; - const hand = this.gs.players[0].hand; - hand.forEach((card, i) => { - const sx = this.sourceCardX(i); - const cont = this.add.container(sx, SOURCE_Y).setDepth(D.panel + 3); - this.drawCard(cont, card, true); - cont.setSize(CARD_W, CARD_H); - cont.setInteractive({ useHandCursor: true }); - this.input.setDraggable(cont); - - let _dragged = false; - - cont.on('dragstart', () => { - _dragged = true; - this.selectedCardIdx = null; - if (this._selRings) { for (const r of this._selRings) r.destroy(); this._selRings = []; } - cont.setDepth(D.panel + 10); - }); - - cont.on('drag', (_ptr, dragX, dragY) => { - cont.setPosition(dragX, dragY); - }); - - cont.on('dragend', () => { - cont.setDepth(D.panel + 3); - this._clearDragHighlights(); - // 'drop' event (fired before dragend) already placed the card if it hit a zone. - // Re-render to snap card to its slot (or back to source on a miss). - this.updateHandSetUI(); - }); - - // Only treat as a click when the pointer never moved far enough to trigger a drag - cont.on('pointerdown', () => { _dragged = false; }); - cont.on('pointerup', () => { - if (!_dragged) this.onSourceCardClick(i); - _dragged = false; // reset after the check so dragend's state is preserved - }); - - this.setCardConts.push(cont); - }); - } - - // Highlights whichever slot the card is hovering over; clears all others - _drawHighlightSlot(g, cx, cy) { - g.clear(); - g.fillStyle(0xf5d020, 0.18); - g.fillRoundedRect(cx - CARD_W / 2, cy - CARD_H / 2, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, 0xf5d020, 1); - g.strokeRoundedRect(cx - CARD_W / 2, cy - CARD_H / 2, CARD_W, CARD_H, CARD_R); - } - - _clearDragHighlights() { - for (let i = 0; i < 5; i++) { - const slot = this.setHighSlots[i]; - this.drawEmptySlot(slot.g, slot.x, SLOT_Y); - } - for (let i = 0; i < 2; i++) { - const slot = this.setLowSlots[i]; - this.drawEmptySlot(slot.g, slot.x, SLOT_Y); + // mode: 'bet' | 'set' | 'next' | 'wait' + setDockMode(mode, status = '') { + this.dockMode = mode; + this.dock.setMode(mode, mode === 'wait' ? status : ''); + if (mode === 'bet') this.updateBetDisplay(); + if (mode === 'set') { + this.houseWayBtn.setEnabled(true); + this.trayClearBtn.setEnabled(true); + this.updateTrayUI(); } } - _dropToHighSlot(cardIdx, slotIdx) { - // Remove cardIdx from its current slot (if any) - const fromHi = this.humanHighSlots.indexOf(cardIdx); - const fromLo = this.humanLowSlots.indexOf(cardIdx); - if (fromHi !== -1) this.humanHighSlots[fromHi] = null; - if (fromLo !== -1) this.humanLowSlots[fromLo] = null; - // Displaced occupant goes back to source (its slot becomes null) - // — no extra action needed; it will re-anchor in updateHandSetUI - this.humanHighSlots[slotIdx] = cardIdx; - this.selectedCardIdx = null; - this.updateHandSetUI(); - } - - _dropToLowSlot(cardIdx, slotIdx) { - const fromHi = this.humanHighSlots.indexOf(cardIdx); - const fromLo = this.humanLowSlots.indexOf(cardIdx); - if (fromHi !== -1) this.humanHighSlots[fromHi] = null; - if (fromLo !== -1) this.humanLowSlots[fromLo] = null; - this.humanLowSlots[slotIdx] = cardIdx; - this.selectedCardIdx = null; - this.updateHandSetUI(); - } - - sourceCardX(idx) { - // 7 cards spread centered at CX - return CX - 3 * SLOT_GAP + idx * SLOT_GAP; - } - - updateHandSetUI() { - const hand = this.gs.players[0].hand; - const placedSet = new Set([ - ...this.humanHighSlots.filter(v => v !== null), - ...this.humanLowSlots.filter(v => v !== null), - ]); - - // Position each card container - this.setCardConts.forEach((cont, i) => { - const highIdx = this.humanHighSlots.indexOf(i); - const lowIdx = this.humanLowSlots.indexOf(i); - if (highIdx !== -1) { - // In high hand slot - const slot = this.setHighSlots[highIdx]; - cont.setPosition(slot.x, SLOT_Y); - cont.setAlpha(1); - // Highlight slot outline if this card is "selected" (for swapping) - this.drawEmptySlot(slot.g, slot.x, SLOT_Y); - if (this.selectedCardIdx === i) this.drawSelectedSlot(slot.g, slot.x, SLOT_Y); - } else if (lowIdx !== -1) { - // In low hand slot - const slot = this.setLowSlots[lowIdx]; - cont.setPosition(slot.x, SLOT_Y); - cont.setAlpha(1); - if (this.selectedCardIdx === i) this.drawSelectedSlot(slot.g, slot.x, SLOT_Y); - else this.drawEmptySlot(slot.g, slot.x, SLOT_Y); - } else { - // In source zone - cont.setPosition(this.sourceCardX(i), SOURCE_Y); - cont.setAlpha(this.selectedCardIdx === i ? 0.5 : 1); - // Pulse ring for selected source card - if (this.selectedCardIdx === i) { - // Add a selection ring by re-drawing card with highlight - // (simpler: just alpha fade the others is not great; instead use a ring overlay) - } - } - }); - - // Draw selection ring on selected source card - this.drawSelectionRings(); - - // Update empty slot outlines - for (let i = 0; i < 5; i++) { - const slot = this.setHighSlots[i]; - if (this.humanHighSlots[i] === null) this.drawEmptySlot(slot.g, slot.x, SLOT_Y); + // ── Keyboard ─────────────────────────────────────────────────────────────── + onKey(e) { + if (!this.gs) return; + const k = (e.key ?? '').toLowerCase(); + switch (this.dockMode) { + case 'bet': + if (k === ' ' || k === 'enter') { + if (this.pendingBet >= MIN_BET) this.onDealClick(); else this.onRebet(1); + } else if (k === 'r') this.onRebet(1); + else if (k === 'c' || k === 'backspace') this.onClearBet(); + else if (['1', '2', '3', '4'].includes(k)) this.onChipClick(CHIP_AMOUNTS[Number(k) - 1]); + break; + case 'set': + if (/^[1-7]$/.test(k)) { const i = this.trayOrder[Number(k) - 1]; if (i !== undefined) this.toggleCard(i); } + else if (k === 'w') this.applyHouseWay(); + else if (k === 'c' || k === 'backspace') this.clearTray(); + else if (k === 'enter' || k === ' ') this.onSetHand(); + break; + case 'next': + if (k === ' ' || k === 'enter') this.onNextRound(false); + else if (k === 'r') this.onNextRound(true); + break; + default: + break; } - for (let i = 0; i < 2; i++) { - const slot = this.setLowSlots[i]; - if (this.humanLowSlots[i] === null) this.drawEmptySlot(slot.g, slot.x, SLOT_Y); - } - - // Update rank labels - const highCards = this.humanHighSlots.filter(v => v !== null).map(i => hand[i]); - const lowCards = this.humanLowSlots.filter(v => v !== null).map(i => hand[i]); - - if (highCards.length === 5) { - const ev = evaluate5Card(highCards); - this.highRankTxt.setText(handName5(ev)); - } else { - this.highRankTxt.setText(`${highCards.length}/5 placed`); - } - - if (lowCards.length === 2) { - const ev = evaluate2Card(lowCards); - this.lowRankTxt.setText(ev.name); - } else { - this.lowRankTxt.setText(`${lowCards.length}/2 placed`); - } - - // Validate and update foul / set hand button - const complete = highCards.length === 5 && lowCards.length === 2; - let fouled = false; - if (complete) { - fouled = isFoul(highCards, lowCards); - this.foulWarnTxt.setText(fouled ? 'Invalid: High hand must outrank Low hand' : ''); - } else { - this.foulWarnTxt.setText(''); - } - this.setHandBtn.setEnabled(complete && !fouled); } - drawSelectionRings() { - // Remove existing rings - if (this._selRings) { - for (const r of this._selRings) r.destroy(); - } - this._selRings = []; - if (this.selectedCardIdx === null) return; - const hand = this.gs.players[0].hand; - const hi = this.humanHighSlots.indexOf(this.selectedCardIdx); - const lo = this.humanLowSlots.indexOf(this.selectedCardIdx); - let cx, cy; - if (hi !== -1) { - cx = this.setHighSlots[hi].x; cy = SLOT_Y; - } else if (lo !== -1) { - cx = this.setLowSlots[lo].x; cy = SLOT_Y; - } else { - cx = this.sourceCardX(this.selectedCardIdx); cy = SOURCE_Y; - } - const ring = this.add.graphics().setDepth(D.panel + 4); - ring.lineStyle(4, 0xf5d020, 1); - ring.strokeRoundedRect(cx - CARD_W / 2 - 3, cy - CARD_H / 2 - 3, CARD_W + 6, CARD_H + 6, CARD_R + 2); - this._selRings.push(ring); - } - - onSourceCardClick(idx) { - if (this.animating) return; - if (this.selectedCardIdx === idx) { - // Deselect - this.selectedCardIdx = null; - } else { - // If a slot card was selected, swap them - const prevSelected = this.selectedCardIdx; - if (prevSelected !== null) { - const hiPrev = this.humanHighSlots.indexOf(prevSelected); - const loPrev = this.humanLowSlots.indexOf(prevSelected); - if (hiPrev !== -1) { - // Prev was in high slot → move source card there, return prev to source - this.humanHighSlots[hiPrev] = idx; - } else if (loPrev !== -1) { - this.humanLowSlots[loPrev] = idx; - } - this.selectedCardIdx = null; - } else { - this.selectedCardIdx = idx; - } - } - this.updateHandSetUI(); - } - - onHighSlotClick(slotIdx) { - if (this.animating) return; - const currentInSlot = this.humanHighSlots[slotIdx]; - - if (this.selectedCardIdx !== null) { - // Place selected card into this slot - const prevInSlot = currentInSlot; - // Remove selected card from wherever it currently is - const hiSel = this.humanHighSlots.indexOf(this.selectedCardIdx); - const loSel = this.humanLowSlots.indexOf(this.selectedCardIdx); - if (hiSel !== -1) this.humanHighSlots[hiSel] = null; - if (loSel !== -1) this.humanLowSlots[loSel] = null; - // Put selected card in this slot - this.humanHighSlots[slotIdx] = this.selectedCardIdx; - // If there was a card here before, it stays selected (or goes to source) - this.selectedCardIdx = prevInSlot; // null if slot was empty - } else if (currentInSlot !== null) { - // No card selected — select the card in this slot - this.selectedCardIdx = currentInSlot; - } - this.updateHandSetUI(); - } - - onLowSlotClick(slotIdx) { - if (this.animating) return; - const currentInSlot = this.humanLowSlots[slotIdx]; - - if (this.selectedCardIdx !== null) { - const prevInSlot = currentInSlot; - const hiSel = this.humanHighSlots.indexOf(this.selectedCardIdx); - const loSel = this.humanLowSlots.indexOf(this.selectedCardIdx); - if (hiSel !== -1) this.humanHighSlots[hiSel] = null; - if (loSel !== -1) this.humanLowSlots[loSel] = null; - this.humanLowSlots[slotIdx] = this.selectedCardIdx; - this.selectedCardIdx = prevInSlot; - } else if (currentInSlot !== null) { - this.selectedCardIdx = currentInSlot; - } - this.updateHandSetUI(); - } - - applyHouseWayUI() { - const hand = this.gs.players[0].hand; - const { highHand, lowHand } = houseWay(hand); - // Map card objects to indices in the hand array - this.humanHighSlots = highHand.map(c => hand.indexOf(c)); - this.humanLowSlots = lowHand.map(c => hand.indexOf(c)); - this.selectedCardIdx = null; - this.updateHandSetUI(); - } - - clearHandSet() { - this.humanHighSlots = [null, null, null, null, null]; - this.humanLowSlots = [null, null]; - this.selectedCardIdx = null; - this.updateHandSetUI(); - } - - onSetHand() { - if (this.animating) return; - const hand = this.gs.players[0].hand; - const highHand = this.humanHighSlots.map(i => hand[i]); - const lowHand = this.humanLowSlots.map(i => hand[i]); - this.gs = applyHumanSplit(this.gs, highHand, lowHand); - this.animating = true; - this._animateHandReturnToSeat(() => { - // Clear panel card containers before hideHandSetPanel destroys them - for (const c of this.setCardConts) c.destroy(); - this.setCardConts = []; - this.hideHandSetPanel(); - this.startComparingPhase(); - }); - } - - _animateHandReturnToSeat(onComplete) { - const pos = SEAT_POS[0]; - // Split display mirrors renderSeat's comparing layout - const highCX = pos.x - 130; - const lowCX = pos.x + 130; - - const splitTarget = (cx, count, slotIdx) => { - const totalW = (count - 1) * CARD_SPREAD_SPLIT; - return { x: cx - totalW / 2 + slotIdx * CARD_SPREAD_SPLIT, y: pos.y }; - }; - - // Build ordered list: high hand cards first, then low hand - const moves = []; - this.humanHighSlots.forEach((cardIdx, slotIdx) => { - if (cardIdx !== null) moves.push({ cont: this.setCardConts[cardIdx], ...splitTarget(highCX, 5, slotIdx) }); - }); - this.humanLowSlots.forEach((cardIdx, slotIdx) => { - if (cardIdx !== null) moves.push({ cont: this.setCardConts[cardIdx], ...splitTarget(lowCX, 2, slotIdx) }); - }); - - if (!moves.length) { onComplete(); return; } - - let done = 0; - moves.forEach(({ cont, x, y }, i) => { - cont.setDepth(D.panel + 10); - this.tweens.add({ - targets: cont, - x, y, - duration: 320, - delay: i * 45, - ease: 'Power2.Out', - onComplete: () => { if (++done === moves.length) onComplete(); }, - }); - }); - } - - // ── Chip balance ────────────────────────────────────────────────────────── + // ── Chip balance ─────────────────────────────────────────────────────────── async loadPlayerChips() { try { const { profile } = await api.get('/profile'); @@ -819,899 +288,748 @@ export default class PaiGowPokerGame extends Phaser.Scene { } } - // ── Game init ───────────────────────────────────────────────────────────── - initGame() { - this.gs = createInitialState(this.opponents, this._playerChips); - this.startNewRound(); - } - - startNewRound() { - playSound(this, SFX.CARD_SHUFFLE); - this.pendingBet = 0; - this.gs = prepareRound(this.gs); - this.clearCardGraphics(); - this.renderAll(); - this.showBettingUI(); - this.updateBetDisplay(); - } - - // ── Render ──────────────────────────────────────────────────────────────── - renderAll() { - this.renderDealer(); - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (!p.active) continue; - this.renderSeat(seat); - this.renderSeatInfo(seat); - } - this.renderBetAreas(); - } - - renderDealer() { - for (const c of this.dealerCardGraphics) c.destroy(); - this.dealerCardGraphics = []; - this.dealerHighLabel.setText(''); - this.dealerLowLabel.setText(''); - - const dealer = this.gs.dealer; - if (!dealer.hand.length) return; - - if (!dealer.revealed) { - // Fan of face-down cards - dealer.hand.forEach((card, i) => { - const x = this.fanCardX(DEALER_X, i, dealer.hand.length); - const cont = this.add.container(x, DEALER_Y).setDepth(D.cards); - this.drawCard(cont, null, false); - this.dealerCardGraphics.push(cont); - }); - return; - } - - // After reveal: show split layout (5 HIGH + 2 LOW) - this.renderSplitCards(DEALER_X - 170, DEALER_Y, dealer.highHand, this.dealerCardGraphics); - this.renderSplitCards(DEALER_X + 170, DEALER_Y, dealer.lowHand, this.dealerCardGraphics); - - if (dealer.highEval) this.dealerHighLabel.setText(handName5(dealer.highEval)); - if (dealer.lowEval) this.dealerLowLabel.setText(dealer.lowEval.name); - } - - renderSeat(seat) { - if (this.seatCardGraphics[seat]) { - for (const c of this.seatCardGraphics[seat]) c.destroy(); - } - this.seatCardGraphics[seat] = []; - - const p = this.gs.players[seat]; - const pos = SEAT_POS[seat]; - - if (!p.hand.length) return; - - const phase = this.gs.phase; - const showSplit = phase === 'comparing' || phase === 'resolved'; - - if (seat === 0 && this.panelVisible) { - // Human cards are shown in the panel while it's open — don't render at seat - return; - } - - if (showSplit && p.highHand.length > 0) { - // Split view: high hand left, low hand right - if (seat === 0) { - this.renderSplitCards(pos.x - 130, pos.y, p.highHand, this.seatCardGraphics[seat]); - this.renderSplitCards(pos.x + 130, pos.y, p.lowHand, this.seatCardGraphics[seat]); - } else { - this.renderSplitCards(pos.x - 100, pos.y, p.highHand, this.seatCardGraphics[seat]); - this.renderSplitCards(pos.x + 100, pos.y, p.lowHand, this.seatCardGraphics[seat]); - } - if (this.scoreTxts[seat]) this.scoreTxts[seat].setText(''); - } else { - // Fan view: 7 face-down cards - p.hand.forEach((card, i) => { - const x = this.fanCardX(pos.x, i, p.hand.length); - const cont = this.add.container(x, pos.y).setDepth(D.cards); - // Human's cards are face-up, AI cards face-down during dealing/setting - const faceUp = seat === 0; - this.drawCard(cont, faceUp ? card : null, faceUp); - this.seatCardGraphics[seat].push(cont); - }); - } - } - - renderSplitCards(cx, cy, cards, targetArr) { - cards.forEach((card, i) => { - const total = cards.length; - const spread = CARD_SPREAD_SPLIT; - const totalW = (total - 1) * spread; - const x = cx - totalW / 2 + i * spread; - const cont = this.add.container(x, cy).setDepth(D.cards); - this.drawCard(cont, card, true); - targetArr.push(cont); - }); - } - - renderSeatInfo(seat) { - const p = this.gs.players[seat]; - if (this.chipTxts[seat]) this.chipTxts[seat].setText(`$${p.chips.toLocaleString()}`); - } - - renderBetAreas() { - for (const g of Object.values(this.betGraphics)) g.destroy(); - this.betGraphics = {}; - for (let seat = 0; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (!p.active || p.bet === 0) continue; - const { x: betX, y: betY } = this.betCirclePos(seat); - const cont = this.add.container(betX, betY).setDepth(D.chips); - const circle = this.add.graphics(); - circle.fillStyle(0x2a2a2a, 1); - circle.fillCircle(0, 0, 28); - circle.lineStyle(2, 0xf0e8d0, 0.8); - circle.strokeCircle(0, 0, 28); - const txt = this.add.text(0, 0, `$${p.bet}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f0e8d0', - }).setOrigin(0.5); - cont.add([circle, txt]); - this.betGraphics[seat] = cont; - } - } - - clearCardGraphics() { - for (const cards of Object.values(this.seatCardGraphics)) { - for (const c of cards) c.destroy(); - } - this.seatCardGraphics = {}; - for (const c of this.dealerCardGraphics) c.destroy(); - this.dealerCardGraphics = []; - for (const g of Object.values(this.betGraphics)) g.destroy(); - this.betGraphics = {}; - } - - betCirclePos(seat) { - const pos = SEAT_POS[seat]; - if (pos.betX !== undefined) return { x: pos.betX, y: pos.betY }; - const t = 0.22; - return { - x: Math.round(pos.x + t * (CX - pos.x)), - y: Math.round(pos.y + t * (TABLE_CY - pos.y)), - }; - } - - fanCardX(centerX, idx, total) { - const totalW = (total - 1) * CARD_SPREAD_FAN + CARD_W; - return centerX - totalW / 2 + CARD_W / 2 + idx * CARD_SPREAD_FAN; - } - - // ── Card drawing ────────────────────────────────────────────────────────── - addCardBackToContainer(container) { - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - container.add( - this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H).setOrigin(0.5) - ); - } else { - const g = this.add.graphics(); - this.drawCardBack(g, -CARD_W / 2, -CARD_H / 2); - container.add(g); - } - } - - drawCardBack(g, x, y) { - const color = this.cardBack?.fallbackColor - ? parseInt(this.cardBack.fallbackColor.replace('#', ''), 16) : 0x1a3a6b; - g.fillStyle(color, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xffffff, 0.25); - g.strokeRoundedRect(x + 6, y + 6, CARD_W - 12, CARD_H - 12, CARD_R - 2); - } - - drawCard(container, card, faceUp) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - if (faceUp && card) { - if (card.isJoker) { - // Special Joker rendering - const g = this.add.graphics(); - g.fillStyle(0xffffff, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xd4a017, 1.5); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - container.add(g); - container.add(this.add.text(x + 7, y + 5, 'JK', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#7b2fbe', fontStyle: 'bold', - })); - container.add(this.add.text(0, 4, '★', { - fontFamily: '"Julius Sans One"', fontSize: '50px', color: '#d4a017', - }).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 8, 'JK', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#7b2fbe', fontStyle: 'bold', - }).setOrigin(1, 1)); - } else { - const g = this.add.graphics(); - g.fillStyle(0xffffff, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(1, 0xcccccc, 1); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - container.add(g); - const color = card.isRed ? '#c0392b' : '#1a1a2e'; - const s = (sz, bold = false) => ({ - fontFamily: '"Julius Sans One"', fontSize: `${sz}px`, color, - ...(bold ? { fontStyle: 'bold' } : {}), - }); - container.add(this.add.text(x + 7, y + 5, card.label, s(17, true))); - container.add(this.add.text(x + 7, y + 23, card.suitSymbol, s(13))); - container.add(this.add.text(0, 4, card.suitSymbol, s(40)).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 8, card.label, s(17, true)).setOrigin(1, 1)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 22, card.suitSymbol, s(13)).setOrigin(1, 1)); - } - } else { - this.addCardBackToContainer(container); - } - } - - // ── Betting phase ───────────────────────────────────────────────────────── - onChipClick(amount) { - if (this.animating) return; - const human = this.gs.players[0]; - if (this.pendingBet + amount > 100) return; - if (this.pendingBet + amount > human.chips) return; - this.pendingBet += amount; - this.updateBetDisplay(); - playChipBet(this); - } - - onClearBet() { - this.pendingBet = 0; - this.updateBetDisplay(); - } - - updateBetDisplay() { - if (this.betDisplayText) this.betDisplayText.setText(`Bet: $${this.pendingBet}`); - if (this.dealBtn) this.dealBtn.setEnabled(this.pendingBet >= 5); - const human = this.gs?.players[0]; - if (this.balanceText && human) this.balanceText.setText(`Balance: $${human.chips.toLocaleString()}`); - } - - onDealClick() { - if (this.animating || this.pendingBet < 5) return; - this.animating = true; - this.hideBettingUI(); - - this.gs = applyBet(this.gs, 0, this.pendingBet); - - for (let seat = 1; seat < SEAT_POS.length; seat++) { - const p = this.gs.players[seat]; - if (!p.active) continue; - this.gs = applyBet(this.gs, seat, Math.max(5, chooseBet(p))); - } - - this.gs = dealHands(this.gs); - - this.animateBets(() => { - this.animateDeal(() => { - this.animating = false; - this.renderAll(); - this.startSettingPhase(); - }); - }); - } - - // ── Animations ──────────────────────────────────────────────────────────── - animateBets(onComplete) { - this.renderBetAreas(); - playChipBet(this); - let done = 0; - const active = this.gs.players.filter(p => p.active); - if (!active.length) { onComplete(); return; } - for (const p of active) { - const pos = SEAT_POS[p.seat]; - const { x: betX, y: betY } = this.betCirclePos(p.seat); - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(0x5cb85c, 1); chip.fillCircle(0, 0, 14); - chip.x = pos.x; chip.y = pos.y; - this.tweens.add({ - targets: chip, x: betX, y: betY, duration: 280, ease: 'Power2', - onComplete: () => { chip.destroy(); done++; if (done >= active.length) onComplete(); }, - }); - } - } - - animateDeal(onComplete) { - // All 7 cards dealt face-down to each player and dealer in sequence - const seats = PLAY_ORDER.filter(s => this.gs.players[s]?.active); - const DECK_X = CX + 200, DECK_Y = 50; - const totalDeals = (seats.length + 1) * 7; // seats + dealer - - // Pre-render all cards (face-down initially via renderAll) - this.renderAll(); - - // Hide all seat card graphics - for (const cards of Object.values(this.seatCardGraphics)) { - for (const c of cards) c.setAlpha(0); - } - for (const c of this.dealerCardGraphics) c.setAlpha(0); - - // Build deal sequence: deal 7 cards to each player in order, then dealer - const dealSeq = []; - for (let round = 0; round < 7; round++) { - for (const seat of seats) dealSeq.push({ type: 'player', seat, cardIdx: round }); - dealSeq.push({ type: 'dealer', cardIdx: round }); - } - - let idx = 0; - const stagger = 70; - const dealNext = () => { - if (idx >= dealSeq.length) { onComplete(); return; } - const entry = dealSeq[idx++]; - const flying = this.add.container(DECK_X, DECK_Y).setDepth(D.cards + 10); - this.addCardBackToContainer(flying); - - let tx, ty; - if (entry.type === 'dealer') { - tx = this.fanCardX(DEALER_X, entry.cardIdx, 7); - ty = DEALER_Y; - } else { - const pos = SEAT_POS[entry.seat]; - tx = this.fanCardX(pos.x, entry.cardIdx, 7); - ty = pos.y; - } - - this.tweens.add({ - targets: flying, x: tx, y: ty, duration: 160, ease: 'Power2', - onComplete: () => { - flying.destroy(); - playSound(this, SFX.CARD_DEAL); - if (entry.type === 'dealer') { - if (this.dealerCardGraphics[entry.cardIdx]) this.dealerCardGraphics[entry.cardIdx].setAlpha(1); - } else { - const cards = this.seatCardGraphics[entry.seat] ?? []; - if (cards[entry.cardIdx]) cards[entry.cardIdx].setAlpha(1); - } - this.time.delayedCall(stagger, dealNext); - }, - }); - }; - dealNext(); - } - - animateDealerReveal(onComplete) { - playSound(this, SFX.CARD_SHOW); - // Flip each dealer card to face-up - let done = 0; - const total = this.dealerCardGraphics.length; - if (!total) { this.renderDealer(); onComplete(); return; } - - this.dealerCardGraphics.forEach((cont, i) => { - this.time.delayedCall(i * 120, () => { - this.tweens.add({ - targets: cont, scaleX: 0, duration: 110, ease: 'Linear', - onComplete: () => { - // Reveal the face - const card = this.gs.dealer.hand[i]; - this.drawCard(cont, card, true); - this.tweens.add({ - targets: cont, scaleX: 1, duration: 110, ease: 'Linear', - onComplete: () => { - done++; - if (done === total) { - // Now show split layout - this.time.delayedCall(400, () => { - this.gs = { ...this.gs, dealer: { ...this.gs.dealer, revealed: true } }; - this.renderDealer(); - onComplete(); - }); - } - }, - }); - }, - }); - }); - }); - } - - // ── Setting phase ───────────────────────────────────────────────────────── - startSettingPhase() { - // Auto-set all AI players and dealer via House Way - for (let seat = 1; seat < SEAT_POS.length; seat++) { - if (this.gs.players[seat].active) { - this.gs = applyHouseWaySplit(this.gs, seat); - } - } - this.gs = applyDealerHouseWay(this.gs); - - // Reset human split state - this.humanHighSlots = [null, null, null, null, null]; - this.humanLowSlots = [null, null]; - this.selectedCardIdx = null; - - // Show the hand-setting panel - this.showHandSetPanel(); - } - - // ── Comparing phase ─────────────────────────────────────────────────────── - startComparingPhase() { - this.animating = true; - - // Advance phase so renderSeat renders everyone (including the human) in split layout, - // preserving the animated split the player's cards just landed in. - this.gs = { ...this.gs, phase: 'comparing' }; - - // Briefly reveal all AI splits (1.5s), then reveal dealer - this.renderAll(); // shows AI split layouts - - this.time.delayedCall(1500, () => { - // Reveal dealer cards - this.animateDealerReveal(() => { - // Resolve round - this.gs = resolveRound(this.gs); - this.renderAll(); - // Modal comparison sequence, then chip animations - this.startModalComparisons(() => { - this.animateAllChips(() => { - this.updateServerChips(); - this.time.delayedCall(800, () => { - this.animating = false; - this.showNextRoundPrompt(); - }); - }); - }); - }); - }); - } - - // ── Modal comparison ───────────────────────────────────────────────────────── - - startModalComparisons(onComplete) { - const MODAL_W = 1100; - const MODAL_H = 530; - const MODAL_X = CX - MODAL_W / 2; // 410 - const MODAL_TOP = 150; - const DEALER_ROW_Y = 262; - const PLAYER_ROW_Y = 510; - const ARROW_Y = 393; - const HIGH_CX = 650; - const LOW_CX = 1270; - const RESULT_CENTER_Y = MODAL_TOP + Math.round(MODAL_H / 2); // 415 - - const slotX = (cx, count, i) => cx - ((count - 1) * MODAL_CARD_SPREAD) / 2 + i * MODAL_CARD_SPREAD; - - this._modal = { MODAL_X, MODAL_TOP, MODAL_W, MODAL_H, DEALER_ROW_Y, PLAYER_ROW_Y, - ARROW_Y, HIGH_CX, LOW_CX, RESULT_CENTER_Y, slotX }; - this._buildCompareModal(); - - // Fade in frame elements (arrows/rank text/result have their own reveal animations) - const frameObjs = this._modal.frameObjects; - for (const o of frameObjs) o.setAlpha(0); - this.tweens.add({ - targets: frameObjs, alpha: 1, duration: 250, ease: 'Linear', - onComplete: () => { - this._animateDealerIntoModal(() => { - const players = PLAY_ORDER - .map(seat => this.gs.players[seat]) - .filter(p => p?.active); - const processNext = idx => { - if (idx >= players.length) { - this._destroyModal(); - onComplete(); - return; - } - const isLast = idx === players.length - 1; - this._comparePlayerInModal(players[idx], isLast, () => processNext(idx + 1)); - }; - processNext(0); - }); - }, - }); - } - - _buildCompareModal() { - const { MODAL_X, MODAL_TOP, MODAL_W, MODAL_H, DEALER_ROW_Y, PLAYER_ROW_Y, - HIGH_CX, LOW_CX, RESULT_CENTER_Y } = this._modal; - const LABEL_STYLE = { fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#d4a017' }; - const RANK_STYLE = { fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#c0c0c0' }; - const HEADER_STYLE = { fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#6a7484' }; - - const bg = this.add.graphics().setDepth(D.modal); - bg.fillStyle(0x0a0f1a, 0.94); - bg.fillRoundedRect(MODAL_X, MODAL_TOP, MODAL_W, MODAL_H, 12); - bg.lineStyle(2, 0xd4a017, 0.8); - bg.strokeRoundedRect(MODAL_X, MODAL_TOP, MODAL_W, MODAL_H, 12); - - const sep = this.add.graphics().setDepth(D.modal + 1); - sep.lineStyle(1, 0x3a4454, 0.6); - sep.lineBetween(CX, MODAL_TOP + 20, CX, MODAL_TOP + MODAL_H - 20); - - const dealerLabel = this.add.text(CX, MODAL_TOP + 25, 'DEALER', LABEL_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - - const hiLabel = this.add.text(HIGH_CX, MODAL_TOP + 28, 'HIGH HAND', HEADER_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - const loLabel = this.add.text(LOW_CX, MODAL_TOP + 28, 'LOW HAND', HEADER_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - - const dealerRankHi = this.add.text(HIGH_CX, DEALER_ROW_Y + CARD_H / 2 + 10, '', RANK_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - const dealerRankLo = this.add.text(LOW_CX, DEALER_ROW_Y + CARD_H / 2 + 10, '', RANK_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - - const playerLabel = this.add.text(CX, PLAYER_ROW_Y - CARD_H / 2 - 22, '', LABEL_STYLE) - .setOrigin(0.5, 1).setDepth(D.modal + 1); - const playerRankHi = this.add.text(HIGH_CX, PLAYER_ROW_Y + CARD_H / 2 + 10, '', RANK_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - const playerRankLo = this.add.text(LOW_CX, PLAYER_ROW_Y + CARD_H / 2 + 10, '', RANK_STYLE) - .setOrigin(0.5, 0).setDepth(D.modal + 1); - - const arrowHiG = this.add.graphics().setDepth(D.modal + 2).setAlpha(0); - const arrowLoG = this.add.graphics().setDepth(D.modal + 2).setAlpha(0); - - // resultTxt lives at modal center and flies to portrait after each player - const resultTxt = this.add.text(CX, RESULT_CENTER_Y, '', { - fontFamily: '"Julius Sans One"', fontSize: '72px', fontStyle: 'bold', color: '#f5d020', - }).setOrigin(0.5).setDepth(D.modal + 3).setAlpha(0).setScale(0); - - Object.assign(this._modal, { - bg, sep, dealerLabel, hiLabel, loLabel, - dealerRankHi, dealerRankLo, playerLabel, playerRankHi, playerRankLo, - arrowHiG, arrowLoG, resultTxt, - // frameObjects: modal chrome that hides/shows between players - frameObjects: [bg, sep, dealerLabel, hiLabel, loLabel, dealerRankHi, dealerRankLo], - // dynamicObjects: per-player state reset each round - dynamicObjects: [playerLabel, playerRankHi, playerRankLo, arrowHiG, arrowLoG], - // allObjects: everything for final destroy - allObjects: [bg, sep, dealerLabel, hiLabel, loLabel, - dealerRankHi, dealerRankLo, playerLabel, playerRankHi, playerRankLo, - arrowHiG, arrowLoG, resultTxt], - }); - } - - _animateDealerIntoModal(onComplete) { - const { DEALER_ROW_Y, HIGH_CX, LOW_CX, slotX } = this._modal; - const cards = this.dealerCardGraphics; - const dealer = this.gs.dealer; - const hiCount = dealer.highHand.length; // 5 - const loCount = dealer.lowHand.length; // 2 - - this._dealerCardOrigins = cards.map(c => ({ x: c.x, y: c.y })); - for (const c of cards) c.setDepth(D.modal + 5); - - let done = 0; - const total = cards.length; - cards.forEach((card, i) => { - const isHi = i < hiCount; - const idx = isHi ? i : i - hiCount; - const tx = isHi ? slotX(HIGH_CX, hiCount, idx) : slotX(LOW_CX, loCount, idx); - this.tweens.add({ - targets: card, x: tx, y: DEALER_ROW_Y, - duration: 350, delay: i * 50, ease: 'Power2.Out', - onComplete: () => { - done++; - if (done === total) { - const { dealerRankHi, dealerRankLo } = this._modal; - dealerRankHi.setText(handName5(dealer.highEval)); - dealerRankLo.setText(dealer.lowEval?.name ?? ''); - onComplete(); - } - }, - }); - }); - } - - _drawModalArrow(g, x, y, dealerWins) { - g.clear(); - if (dealerWins) { - g.fillStyle(0xff3a3a, 1); // bright red - g.fillTriangle(x, y - 18, x - 14, y + 14, x + 14, y + 14); // apex up - } else { - g.fillStyle(0x00e676, 1); // bright green - g.fillTriangle(x, y + 18, x - 14, y - 14, x + 14, y - 14); // apex down - } - } - - _comparePlayerInModal(player, isLast, onComplete) { - const { PLAYER_ROW_Y, HIGH_CX, LOW_CX, slotX, - dealerRankHi, dealerRankLo, playerLabel, playerRankHi, playerRankLo, - arrowHiG, arrowLoG, resultTxt, RESULT_CENTER_Y } = this._modal; - const dealer = this.gs.dealer; - const cards = this.seatCardGraphics[player.seat] ?? []; - const hiCount = player.highHand.length; // 5 - const loCount = player.lowHand.length; // 2 - - // Reset per-player UI - arrowHiG.setAlpha(0).setScale(1); - arrowLoG.setAlpha(0).setScale(1); - resultTxt.setAlpha(0).setScale(0).setText('').setPosition(CX, RESULT_CENTER_Y); - playerRankHi.setText('').setColor('#c0c0c0').setAlpha(1); - playerRankLo.setText('').setColor('#c0c0c0').setAlpha(1); - dealerRankHi.setColor('#c0c0c0'); - dealerRankLo.setColor('#c0c0c0'); - playerLabel.setText(player.name.toUpperCase()).setColor('#d4a017').setAlpha(1); - - this._playerCardOrigins = cards.map(c => ({ x: c.x, y: c.y })); - for (const c of cards) c.setDepth(D.modal + 5); - - let done = 0; - const total = cards.length; - if (total === 0) { - this._playerCardOrigins = []; - this._afterCardsIn(player, isLast, onComplete); - return; - } - - cards.forEach((card, i) => { - const isHi = i < hiCount; - const idx = isHi ? i : i - hiCount; - const tx = isHi ? slotX(HIGH_CX, hiCount, idx) : slotX(LOW_CX, loCount, idx); - this.tweens.add({ - targets: card, x: tx, y: PLAYER_ROW_Y, - duration: 280, delay: i * 45, ease: 'Power2.Out', - onComplete: () => { - done++; - if (done === total) { - playerRankHi.setText(handName5(player.highEval)); - playerRankLo.setText(player.lowEval?.name ?? ''); - this._afterCardsIn(player, isLast, onComplete); - } - }, - }); - }); - } - - _afterCardsIn(player, isLast, onComplete) { - const dealer = this.gs.dealer; - const { ARROW_Y, HIGH_CX, LOW_CX, RESULT_CENTER_Y, arrowHiG, arrowLoG, resultTxt, - dealerRankHi, dealerRankLo, playerRankHi, playerRankLo } = this._modal; - - const hiWinDealer = player.isFoul || compare5Card(player.highEval, dealer.highEval) <= 0; - const loWinDealer = player.isFoul || compare2Card(player.lowEval, dealer.lowEval) <= 0; - - // 500ms pause then HIGH arrow - this.time.delayedCall(500, () => { - this._drawModalArrow(arrowHiG, HIGH_CX, ARROW_Y, hiWinDealer); - arrowHiG.setAlpha(0).setScale(0); - this.tweens.add({ targets: arrowHiG, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.easeOut' }); - if (hiWinDealer) { dealerRankHi.setColor('#ffe033'); playerRankHi.setColor('#ff3a3a'); } - else { dealerRankHi.setColor('#ff3a3a'); playerRankHi.setColor('#ffe033'); } - - // 1000ms pause then LOW arrow + verdict - this.time.delayedCall(1000, () => { - this._drawModalArrow(arrowLoG, LOW_CX, ARROW_Y, loWinDealer); - arrowLoG.setAlpha(0).setScale(0); - this.tweens.add({ targets: arrowLoG, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.easeOut' }); - if (loWinDealer) { dealerRankLo.setColor('#ffe033'); playerRankLo.setColor('#ff3a3a'); } - else { dealerRankLo.setColor('#ff3a3a'); playerRankLo.setColor('#ffe033'); } - - // 500ms pause after low arrow before verdict appears - this.time.delayedCall(500, () => { - let verdict, color; - if (player.result === 'win') { verdict = 'WIN'; color = '#ffe033'; } - else if (player.result === 'push') { verdict = 'PUSH'; color = '#a0aabb'; } - else { verdict = 'LOSE'; color = '#ff3a3a'; } - - resultTxt.setText(verdict).setColor(color).setAlpha(0).setScale(0) - .setPosition(CX, RESULT_CENTER_Y); - this.tweens.add({ targets: resultTxt, alpha: 1, scaleX: 1, scaleY: 1, - duration: 250, ease: 'Back.easeOut' }); - const sfx = player.result === 'win' ? SFX.CASINO_WIN - : player.result === 'push' ? SFX.SQUASH - : SFX.CASINO_LOSE; - playSound(this, sfx); - if (player.seat > 0) { - const emotion = player.result === 'win' ? 'happy' : 'upset'; - this.portraits[player.seat]?.playEmotion?.(emotion); - } - }); - - // 500ms (low arrow) + 1200ms (verdict visible) = 1700ms before fly-back - this.time.delayedCall(1700, () => { - const cards = this.seatCardGraphics[player.seat] ?? []; - const origins = this._playerCardOrigins; - const pos = SEAT_POS[player.seat]; - - // Fade out modal frame + dynamic UI + dealer cards together (resultTxt stays) - const fadeTargets = [ - ...this._modal.frameObjects, - ...this._modal.dynamicObjects, - ...this.dealerCardGraphics, - ]; - this.tweens.add({ targets: fadeTargets, alpha: 0, duration: 250, ease: 'Linear' }); - - // Fly player cards back to seat simultaneously - let done = 0; - const afterFly = () => { - // Once cards are home, fly resultTxt to player's portrait - const destX = pos.portraitX ?? pos.x; - const destY = pos.portraitY ?? pos.y; - this.tweens.add({ - targets: resultTxt, x: destX, y: destY, - scaleX: 0.45, scaleY: 0.45, - duration: 1500, ease: 'Power2.In', - onComplete: () => { - this.tweens.add({ targets: resultTxt, alpha: 0, duration: 200, ease: 'Linear', - onComplete: () => { - if (isLast) { - // No need to reopen — _destroyModal follows in processNext - onComplete(); - return; - } - // Reopen modal frame + dealer cards for next player - const reshow = [...this._modal.frameObjects, ...this.dealerCardGraphics]; - for (const o of reshow) o.setAlpha(0); - this.tweens.add({ targets: reshow, alpha: 1, duration: 250, ease: 'Linear', - onComplete: () => onComplete() }); - }, - }); - }, - }); - }; - - if (!cards.length) { - afterFly(); - return; - } - cards.forEach((card, i) => { - const { x, y } = origins[i] ?? { x: card.x, y: card.y }; - this.tweens.add({ - targets: card, x, y, duration: 260, delay: i * 30, ease: 'Power2.In', - onComplete: () => { - done++; - if (done === cards.length) { - for (const c of cards) c.setDepth(D.cards); - afterFly(); - } - }, - }); - }); - }); - }); - }); - } - - _destroyModal() { - if (!this._modal) return; - for (const o of this._modal.allObjects) { if (o?.destroy) o.destroy(); } - // Dealer card containers were faded out in the last player's close; destroy them so - // renderAll can recreate them cleanly for the next round. - for (const c of this.dealerCardGraphics) { if (c?.destroy) c.destroy(); } - this.dealerCardGraphics = []; - delete this._modal; - delete this._dealerCardOrigins; - delete this._playerCardOrigins; - } - - showComparisons(onComplete) { - const activePlayers = this.gs.players.filter(p => p.active); - let done = 0; - const total = activePlayers.length; - - activePlayers.forEach((p, i) => { - this.time.delayedCall(i * 350, () => { - this.showSeatResult(p); - done++; - if (done === total) { - // Animate chip flows - this.animateAllChips(() => { - this.updateServerChips(); - this.time.delayedCall(800, onComplete); - }); - } - }); - }); - } - - showSeatResult(player) { - const pos = SEAT_POS[player.seat]; - const resultColor = RESULT_COLORS[player.result] ?? '#8a94a6'; - - // Net label for human (show commission) - let label; - if (player.result === 'win') { - label = `Win! +$${player.chipsWon}`; - } else if (player.result === 'push') { - label = 'Push'; - } else if (player.result === 'foul') { - label = 'Foul — Lose'; - } else { - label = `Lose -$${-player.chipsWon}`; - } - - const badge = this.add.text(pos.x, pos.y - CARD_H / 2 - 36, label, { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: resultColor, fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.ui + 5).setAlpha(0).setScale(0.7); - - this.tweens.add({ - targets: badge, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.easeOut', - onComplete: () => { - this.time.delayedCall(1800, () => { - this.tweens.add({ targets: badge, alpha: 0, y: badge.y - 30, duration: 380, ease: 'Power2', - onComplete: () => badge.destroy() }); - }); - }, - }); - - playSound(this, player.result === 'win' ? SFX.WIN : SFX.LOSE); - if (this.scoreTxts[player.seat]) this.scoreTxts[player.seat].setText(''); - } - - animateAllChips(onComplete) { - const players = this.gs.players.filter(p => p.active); - let done = 0; - const check = () => { done++; if (done >= players.length) onComplete(); }; - for (const p of players) { - if (p.result === 'win') this.animateChipsFromDealer(p.seat, check); - else if (p.result === 'push') this.animateChipReturn(p.seat, check); - else this.animateChipsToDealer(p.seat, check); - } - } - - animateChipsFromDealer(seat, onComplete) { - const { x: bx, y: by } = this.betCirclePos(seat); - const numChips = 3; - let done = 0; - for (let i = 0; i < numChips; i++) { - this.time.delayedCall(i * 60, () => { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(0xf5d020, 1); chip.fillCircle(0, 0, 12); - chip.x = DEALER_X; chip.y = DEALER_Y; - this.tweens.add({ - targets: chip, x: bx, y: by, duration: 380, ease: 'Power2', - onComplete: () => { chip.destroy(); done++; if (done === numChips) onComplete(); }, - }); - }); - } - } - - animateChipsToDealer(seat, onComplete) { - if (!this.betGraphics[seat]) { onComplete(); return; } - const { x: bx, y: by } = this.betCirclePos(seat); - const numChips = 2; - let done = 0; - for (let i = 0; i < numChips; i++) { - this.time.delayedCall(i * 60, () => { - const chip = this.add.graphics().setDepth(D.chips + 5); - chip.fillStyle(0xe05c5c, 1); chip.fillCircle(0, 0, 12); - chip.x = bx; chip.y = by; - this.tweens.add({ - targets: chip, x: DEALER_X, y: DEALER_Y, duration: 380, ease: 'Power2', - onComplete: () => { chip.destroy(); done++; if (done === numChips) onComplete(); }, - }); - }); - } - } - - animateChipReturn(seat, onComplete) { - // Push — chips return to player from bet circle - if (!this.betGraphics[seat]) { onComplete(); return; } - const bg = this.betGraphics[seat]; - this.tweens.add({ - targets: bg, alpha: 0, duration: 320, ease: 'Power2', - onComplete: () => { onComplete(); }, - }); - } - async updateServerChips() { - const human = this.gs.players[0]; - const delta = human.chipsWon ?? 0; + const delta = this.gs.players[0].chipsWon ?? 0; if (delta === 0) return; try { await api.post('/profile/chips/adjust', { delta }); - } catch { /* silent — local state is still correct */ } + } catch { /* balance will resync next load */ } } - // ── Next round ──────────────────────────────────────────────────────────── - showNextRoundPrompt() { - const human = this.gs.players[0]; - if (human.chips < 5) { - new Modal(this, { - title: 'Out of Chips', - body: 'You ran out of chips. Better luck next time!', - buttons: [{ label: 'Leave', onClick: () => this.scene.start('GameMenu') }], + // ── Round lifecycle ──────────────────────────────────────────────────────── + async startNewRound() { + this.setDockMode('wait', ''); + await this.sweepTable(); + playSound(this, SFX.CARD_SHUFFLE); + this.pendingBet = 0; + this.settled.clear(); + this.lowSel = []; + this.gs = prepareRound(this.gs); + this.renderSeatInfo(); + this.renderBetAreas(); + this.setDockMode('bet'); + this.startBettingPrompts(); + } + + async sweepTable() { + for (const o of this.decor) { this.tweens.killTweensOf(o); o.destroy(); } + this.decor = []; + for (const st of Object.values(this.stacks)) { + this.tweens.add({ targets: st, alpha: 0, duration: 200, onComplete: () => st.destroy() }); + } + this.stacks = {}; + const all = [...this.cards.values()]; + this.cards.clear(); + if (!all.length) return; + playSound(this, SFX.CARD_PLACE); + const d = this.discardPos; + all.forEach((c, i) => { + c.setDepth(D.flying); + this.tweens.add({ + targets: c, x: d.x + (Math.random() - 0.5) * 6, y: d.y, + rotation: (Math.random() - 0.5) * 0.08, scaleX: d.s, scaleY: d.s * SQ, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 420, delay: i * 14, ease: 'Cubic.easeInOut', + onComplete: () => c.destroy(), }); + }); + await this.wait(440 + all.length * 14); + } + + renderSeatInfo() { + for (const p of this.gs.players) { + if (p.active) this.chipTxts[p.seat]?.setText(`$${p.chips.toLocaleString()}`); + } + } + + seatSource(seat) { + if (seat === 0) return this.dock.sourcePos(); + const pt = seatLayout(seat).portrait; + return { x: pt.x, y: pt.y, s: 0.9 }; + } + + activeSeats() { + return PLAY_ORDER.filter(seat => this.gs.players[seat]?.active); + } + + // ── Chip stacks ──────────────────────────────────────────────────────────── + renderBetAreas() { + for (const st of Object.values(this.stacks)) st.destroy(); + this.stacks = {}; + if (!this.gs) return; + for (const p of this.gs.players) { + if (!p.active) continue; + const amount = p.seat === 0 && this.gs.phase === 'betting' ? this.pendingBet : p.bet; + if (amount <= 0 || this.settled.has(p.seat)) continue; + const pose = seatLayout(p.seat).bet; + const size = STACK_SIZE * pose.s; + const st = makeChipStack(this, pose.x, pose.y, amount, { size, depth: D.stacks, seed: p.seat + amount }); + st.chipSize = size; + this.stacks[p.seat] = st; + } + } + + // ── Betting ──────────────────────────────────────────────────────────────── + chipAffordable(amt) { + const human = this.gs?.players[0]; + return !!human && this.pendingBet + amt <= Math.min(MAX_BET, human.chips); + } + + rebetAmount(mult) { + const human = this.gs?.players[0]; + if (!human || !this.lastBet) return 0; + return Math.floor(Math.min(this.lastBet * mult, MAX_BET, human.chips) / MIN_BET) * MIN_BET; + } + + throwChip(denom, from, delay = 0) { + return throwChip(this, denom, from, seatLayout(0).bet, { + delay, size: STACK_SIZE, depth: D.flying, + sound: () => { playChipBet(this); this.renderBetAreas(); }, + }); + } + + onChipClick(amt) { + if (this.dockMode !== 'bet' || this.busy || !this.chipAffordable(amt)) return; + const btn = this.dock.chipButton(amt); + this.pendingBet += amt; + this.dock.hidePrompts(); + this.updateBetDisplay(); + this.throwChip(amt, { x: btn.img.x, y: btn.img.y }); + } + + async onRebet(mult) { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet > 0) return; + const amt = this.rebetAmount(mult); + if (amt < MIN_BET) return; + this.busy = true; + this.pendingBet = amt; + this.dock.hidePrompts(); + this.updateBetDisplay(); + const throws = []; + let rest = amt, i = 0; + for (const d of [...CHIP_AMOUNTS].reverse()) { + while (rest >= d) { + const btn = this.dock.chipButton(d); + throws.push(this.throwChip(d, { x: btn.img.x, y: btn.img.y }, i++ * 70)); + rest -= d; + } + } + await Promise.all(throws); + this.busy = false; + this.updateBetDisplay(); + } + + onClearBet() { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet === 0) return; + this.pendingBet = 0; + const st = this.stacks[0]; + delete this.stacks[0]; + if (st) { + this.tweens.add({ + targets: st, x: this.dock.chipCenterX, y: DOCK_Y, alpha: 0, scale: 0.7, + duration: 320, ease: 'Cubic.easeIn', onComplete: () => st.destroy(), + }); + } + this.updateBetDisplay(); + this.startBettingPrompts(); + } + + updateBetDisplay() { + const human = this.gs?.players[0]; + this.dock.betPill.setText(`BET $${this.pendingBet}`); + if (human) this.chipTxts[0].setText(`$${human.chips.toLocaleString()}`); + if (this.dockMode !== 'bet' || !human) return; + this.dealBtn.setEnabled(this.pendingBet >= MIN_BET && !this.busy); + this.clearBtn.setEnabled(this.pendingBet > 0 && !this.busy); + const r1 = this.rebetAmount(1), r2 = this.rebetAmount(2); + this.rebetBtn.setEnabled(r1 >= MIN_BET && this.pendingBet === 0 && !this.busy); + this.rebetBtn.setLabel(r1 >= MIN_BET ? `Rebet $${r1}` : 'Rebet'); + this.rebet2Btn.setEnabled(r2 > r1 && this.pendingBet === 0 && !this.busy); + this.dock.setChipStates(amt => this.chipAffordable(amt)); + } + + startBettingPrompts() { + if (this.pendingBet > 0) return; + this.dock.startPrompts( + () => (this.lastBet ? 'Click chips to bet, or press Space to rebet — then Deal' : 'Click chips to place a bet, then Deal'), + () => this.pendingBet === 0, + ); + } + + async onDealClick() { + if (this.dockMode !== 'bet' || this.busy || this.pendingBet < MIN_BET) return; + this.busy = true; + this.lastBet = this.pendingBet; + this.setDockMode('wait', 'Dealing…'); + + this.gs = applyBet(this.gs, 0, this.pendingBet); + const throws = []; + let n = 0; + for (let seat = 1; seat < this.gs.players.length; seat++) { + const p = this.gs.players[seat]; + if (!p.active) continue; + const bet = Math.max(MIN_BET, chooseBet(p)); + this.gs = applyBet(this.gs, seat, bet); + throws.push(throwStack(this, this.seatSource(seat), seatLayout(seat).bet, bet, { + delay: n++ * 90, size: STACK_SIZE, depth: D.flying, sound: () => playChipBet(this), + }).then(() => this.renderBetAreas())); + } + await Promise.all(throws); + + this.gs = dealHands(this.gs); + this.renderBetAreas(); + + // Dice decide which position receives the first stack (cosmetic — the deal + // order just rotates). Rolled up front, revealed after the stacks are built. + const dice = [1, 2, 3].map(() => 1 + Math.floor(Math.random() * 6)); + const positions = ['d', ...this.activeSeats()]; + const order = rotateFrom(positions, diceStartIndex(dice[0] + dice[1] + dice[2], positions.length)); + + await this.buildStacks(order); + await this.rollDice(dice, order[0]); + await this.distributeStacks(order); + this.busy = false; + this.startSetting(); + } + + // ── Deal: seven stacks of seven, then the dice, then the hand-out ────────── + stagingPose(k, n, i) { + const u = n === 1 ? 0 : -0.3 + (0.6 * k) / (n - 1); + const p = project(u, STAGING_V); + return { x: p.x + (i - 3) * 1.4 * p.s, y: p.y - i * 1.3 * p.s, rot: 0.02 * (k - n / 2), s: p.s * 0.92 }; + } + + handFor(pos) { + return pos === 'd' ? this.gs.dealer.hand : this.gs.players[pos].hand; + } + + async buildStacks(order) { + const n = order.length; + let last = null; + for (let i = 0; i < 7; i++) { + for (let k = 0; k < n; k++) { + const pos = order[k]; + const card = this.handFor(pos)[i]; + const { c, promise } = this.skin.deal(card, false, this.deckPos, this.stagingPose(k, n, i), { + duration: 220, flyingDepth: D.flying, sound: () => playSound(this, SFX.CARD_DEAL), + }); + c.setDepth(D.cards + i); + this.cards.set(`${pos}:${i}`, c); + last = promise; + await this.wait(38); + } + } + await last; + for (const c of this.cards.values()) c.setDepth(D.cards); + } + + async rollDice(values, firstPos) { + const cup = this.cup; + const base = { rot: cup.rotation, y: cup.y }; + playSound(this, SFX.DICE_ROLL); + await this.tweenP({ targets: cup, rotation: 0.22, duration: 90, yoyo: true, repeat: 4, ease: 'Sine.easeInOut' }); + await this.tweenP({ targets: cup, rotation: -1.05, y: base.y - 10, duration: 180, ease: 'Cubic.easeOut' }); + + const land = project(DICE_LAND.u, DICE_LAND.v); + const dice = values.map((v, i) => { + const img = this.add.image(cup.x - 30, cup.y - 40, `casino-die-${1 + Math.floor(Math.random() * 6)}`) + .setScale(0.5 * land.s / 0.74).setDepth(D.flying); + const tx = land.x + (i - 1) * 40 * land.s + (Math.random() - 0.5) * 10; + const ty = land.y + (Math.random() - 0.5) * 14; + const prox = { t: 0 }; + let lastFace = 0; + return new Promise(res => this.tweens.add({ + targets: prox, t: 1, duration: 620 + i * 90, ease: 'Cubic.easeOut', + onUpdate: () => { + const t = prox.t; + img.x = Phaser.Math.Linear(cup.x - 30, tx, t); + img.y = Phaser.Math.Linear(cup.y - 40, ty, t) - Math.abs(Math.sin(t * Math.PI * 2.5)) * 26 * (1 - t); + img.rotation = (1 - t) * 9 + i; + if (t < 0.85 && this.time.now - lastFace > 60) { + lastFace = this.time.now; + img.setTexture(`casino-die-${1 + Math.floor(Math.random() * 6)}`); + } + }, + onComplete: () => { img.setTexture(`casino-die-${v}`); img.rotation = (Math.random() - 0.5) * 0.4; res(img); }, + })); + }); + const imgs = await Promise.all(dice); + this.tweens.add({ targets: cup, rotation: base.rot, y: base.y, duration: 260, ease: 'Cubic.easeInOut' }); + + const total = values.reduce((a, b) => a + b, 0); + const who = firstPos === 'd' ? 'the dealer' : firstPos === 0 ? 'you' : (this.gs.players[firstPos].name || `seat ${firstPos}`); + const banner = this.banner(`${values.join(' · ')} = ${total} — first hand goes to ${who}`, 330); + await this.wait(1500); + await this.tweenP({ targets: [banner, ...imgs], alpha: 0, duration: 260 }); + banner.destroy(); + imgs.forEach(i => i.destroy()); + } + + banner(text, y) { + const c = this.add.container(CX, y).setDepth(D.prompt).setAlpha(0); + const t = this.add.text(0, 0, text, { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: '#f7ecd0', + }).setOrigin(0.5); + const bg = this.add.graphics(); + bg.fillStyle(0x0b0806, 0.85); + bg.fillRoundedRect(-t.width / 2 - 28, -26, t.width + 56, 52, 26); + bg.lineStyle(2, COLORS.accent, 0.8); + bg.strokeRoundedRect(-t.width / 2 - 28, -26, t.width + 56, 52, 26); + c.add([bg, t]); + this.tweens.add({ targets: c, alpha: 1, duration: 200 }); + return c; + } + + // Unset seven-card stacks slide to each seat's HIGH box (dealer: a row). + async distributeStacks(order) { + const moves = []; + order.forEach((pos, k) => { + for (let i = 0; i < 7; i++) { + const c = this.cards.get(`${pos}:${i}`); + const pose = pos === 'd' ? dealerRowPose(i) : withJitter(stackPose(seatLayout(pos).high, i), `${pos}:${i}`); + moves.push(this.tweenP({ + targets: c, x: pose.x, y: pose.y, rotation: pose.rot, scaleX: pose.s, scaleY: pose.s * SQ, + duration: 360, delay: k * 140 + i * 12, ease: 'Cubic.easeInOut', + })); + } + }); + playSound(this, SFX.CARD_PLACE); + await Promise.all(moves); + } + + // ── Setting ──────────────────────────────────────────────────────────────── + startSetting() { + for (let seat = 1; seat < this.gs.players.length; seat++) { + if (this.gs.players[seat].active) this.gs = applyHouseWaySplit(this.gs, seat); + } + this.gs = applyDealerHouseWay(this.gs); + this.aiSetPromise = this.animateAISets(); + this.openTray(); + } + + // AI players split their stacks face-down into HIGH / LOW, one after another. + async animateAISets() { + let k = 0; + const all = []; + for (const seat of this.activeSeats()) { + if (seat === 0) continue; + const delay = 300 + k++ * 420; + all.push(this.wait(delay).then(() => { + playSound(this, SFX.CARD_PLACE); + return Promise.all(this.setSeatCards(seat, 300)); + })); + } + await Promise.all(all); + } + + // Tween a seat's 7 cards into its HIGH / LOW fans; returns the tween promises. + setSeatCards(seat, duration = 300) { + const p = this.gs.players[seat]; + const L = seatLayout(seat); + return p.hand.map((card, i) => { + const c = this.cards.get(`${seat}:${i}`); + const hi = p.highHand.indexOf(card); + const pose = withJitter(hi !== -1 ? fanPose(L.high, hi, 5) : fanPose(L.low, p.lowHand.indexOf(card), 2), `${seat}:${i}`); + c.setDepth(D.cards + (hi !== -1 ? hi : 10 + p.lowHand.indexOf(card))); + return this.tweenP({ + targets: c, x: pose.x, y: pose.y, rotation: pose.rot, scaleX: pose.s, scaleY: pose.s * SQ, + duration, delay: i * 30, ease: 'Cubic.easeOut', + }); + }); + } + + openTray() { + const hand = this.gs.players[0].hand; + this.trayOrder = hand.map((_, i) => i).sort((a, b) => hand[b].value - hand[a].value); + this.lowSel = []; + this.trayActive = true; + this.setDockMode('set'); + + this.trayOrder.forEach((i, k) => { + const c = this.cards.get(`0:${i}`); + c.setDepth(D.trayCards); + const tag = this.add.text(0, -CARD_H / 2 - 16, `${k + 1}`, { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#f7ecd0', fontStyle: 'bold', + backgroundColor: '#00000099', padding: { x: 6, y: 1 }, + }).setOrigin(0.5); + c.add(tag); + c.tag = tag; + let dragged = false; + c.setSize(CARD_W, CARD_H); + c.setInteractive({ useHandCursor: true, draggable: true }); + c.on('pointerdown', () => { dragged = false; }); + c.on('dragstart', () => { dragged = true; c.setDepth(D.trayCards + 5); }); + c.on('drag', (_p, x, y) => c.setPosition(x, y)); + c.on('dragend', (pointer) => { + c.setDepth(D.trayCards); + const inLow = pointer.x >= TRAY_LOW.x0 - 24 && pointer.x <= TRAY_LOW.x1 + 24; + this.moveCard(i, inLow ? 'low' : 'high'); + }); + c.on('pointerup', () => { if (!dragged) this.toggleCard(i); }); + }); + this.layoutTray(true); + } + + layoutTray(firstTime = false) { + const high = this.trayOrder.filter(i => !this.lowSel.includes(i)); + const place = (i, x) => { + const c = this.cards.get(`0:${i}`); + if (!c) return; + if (firstTime && !c.faceUp) { + // fly up from the felt and flip face-up on the way + this.tweens.add({ targets: c, x, y: TRAY_CARD_Y, rotation: 0, scaleY: TRAY_SCALE, duration: 420, ease: 'Cubic.easeOut' }); + const prox = { t: 0 }; + let flipped = false; + const sx0 = c.scaleX; + this.tweens.add({ + targets: prox, t: 1, duration: 420, ease: 'Sine.easeInOut', + onUpdate: () => { + if (!flipped && prox.t >= 0.5) { flipped = true; this.skin.setFace(c, true); } + c.scaleX = Phaser.Math.Linear(sx0, TRAY_SCALE, prox.t) * Math.max(0.03, Math.abs(Math.cos(Math.PI * prox.t))); + }, + onComplete: () => { c.scaleX = TRAY_SCALE; }, + }); + } else { + this.tweens.add({ targets: c, x, y: TRAY_CARD_Y, rotation: 0, scaleX: TRAY_SCALE, scaleY: TRAY_SCALE, duration: 200, ease: 'Cubic.easeOut' }); + } + }; + high.forEach((i, k) => place(i, trayHighX(k, high.length))); + this.lowSel.forEach((i, k) => place(i, trayLowX(k))); + this.updateTrayUI(); + } + + toggleCard(i) { + if (!this.trayActive) return; + const at = this.lowSel.indexOf(i); + if (at !== -1) this.lowSel.splice(at, 1); + else { + if (this.lowSel.length >= 2) this.lowSel.shift(); + this.lowSel.push(i); + } + playSound(this, SFX.CARD_PLACE); + this.layoutTray(); + } + + moveCard(i, zone) { + if (!this.trayActive) return; + const at = this.lowSel.indexOf(i); + if (zone === 'low' && at === -1) { + if (this.lowSel.length >= 2) this.lowSel.shift(); + this.lowSel.push(i); + } else if (zone === 'high' && at !== -1) { + this.lowSel.splice(at, 1); + } + this.layoutTray(); + } + + applyHouseWay() { + if (!this.trayActive) return; + const hand = this.gs.players[0].hand; + const { lowHand } = houseWay(hand); + this.lowSel = lowHand.map(c => hand.indexOf(c)); + this.layoutTray(); + } + + clearTray() { + if (!this.trayActive) return; + this.lowSel = []; + this.layoutTray(); + } + + traySplit() { + const hand = this.gs.players[0].hand; + const high = this.trayOrder.filter(i => !this.lowSel.includes(i)).map(i => hand[i]); + const low = this.lowSel.map(i => hand[i]); + return { high, low }; + } + + updateTrayUI() { + if (this.dockMode !== 'set') return; + const { high, low } = this.traySplit(); + if (low.length < 2) { + this.highNameTxt.setText(`${high.length} cards`).setColor('#c9c2b0'); + this.lowNameTxt.setText(low.length ? 'pick 1 more' : 'pick 2 cards').setColor('#c9c2b0'); + this.foulTxt.setText(''); + this.setHandBtn.setEnabled(false); return; } + const foul = isFoul(high, low); + this.highNameTxt.setText(handName5(evaluate5Card(high))).setColor(foul ? '#ff8a80' : '#f5d020'); + this.lowNameTxt.setText(evaluate2Card(low).name).setColor(foul ? '#ff8a80' : '#f5d020'); + this.foulTxt.setText(foul ? 'Foul — your HIGH hand must outrank your LOW hand' : ''); + this.setHandBtn.setEnabled(!foul); + } - const btn = new Button(this, CX, GAME_HEIGHT / 2, 'Next Round', () => { - btn.destroy(); - this.startNewRound(); - }, { width: 220, height: 56, fontSize: 24 }); - btn.setDepth(D.ui + 5); + async onSetHand() { + if (!this.trayActive || this.dockMode !== 'set') return; + const { high, low } = this.traySplit(); + if (low.length !== 2 || isFoul(high, low)) return; + this.trayActive = false; + this.gs = applyHumanSplit(this.gs, high, low); + this.setDockMode('wait', 'Hand set — waiting for the table…'); + + const hand = this.gs.players[0].hand; + hand.forEach((_, i) => { + const c = this.cards.get(`0:${i}`); + c.disableInteractive(); + c.removeAllListeners(); + c.tag?.destroy(); + c.tag = null; + }); + playSound(this, SFX.CARD_PLACE); + await Promise.all(this.setSeatCards(0, 380)); + for (let i = 0; i < hand.length; i++) this.cards.get(`0:${i}`).setDepth(D.cards + i); + await this.aiSetPromise; + await this.wait(300); + this.revealDealer(); + } + + // ── Reveal + compare ─────────────────────────────────────────────────────── + async revealDealer() { + this.setDockMode('wait', 'The dealer sets the House Way'); + const dealer = this.gs.dealer; + playSound(this, SFX.CARD_SHOW); + await Promise.all(dealer.hand.map((_, i) => + this.wait(i * 80).then(() => this.skin.flip(this.cards.get(`d:${i}`), true, 260)))); + await this.wait(350); + await Promise.all(dealer.hand.map((card, i) => { + const c = this.cards.get(`d:${i}`); + const hi = dealer.highHand.indexOf(card); + const pose = hi !== -1 ? fanPose(dealerHighBox(), hi, 5) : fanPose(dealerLowBox(), dealer.lowHand.indexOf(card), 2); + c.setDepth(D.cards + (hi !== -1 ? hi : 10 + dealer.lowHand.indexOf(card))); + return this.tweenP({ + targets: c, x: pose.x, y: pose.y, rotation: 0, scaleX: pose.s, scaleY: pose.s * SQ, + duration: 340, delay: i * 40, ease: 'Cubic.easeInOut', + }); + })); + this.gs = { ...this.gs, dealer: { ...this.gs.dealer, revealed: true } }; + this.badge(boxBadge(dealerHighBox()), handName5(dealer.highEval), 'normal'); + this.badge(boxBadge(dealerLowBox()), dealer.lowEval.name, 'normal'); + await this.wait(500); + this.compareAll(); + } + + async compareAll() { + this.gs = resolveRound(this.gs); + for (const seat of this.activeSeats()) { + if (!this.sys.isActive()) return; + if (seat === 0) await this.closeUp(); + else await this.compareSeat(seat); + } + await this.wait(400); + this.updateServerChips(); + this.showNextRoundPrompt(); + } + + boxWins(p) { + const d = this.gs.dealer; + if (p.isFoul) return { hi: false, lo: false }; + return { hi: compare5Card(p.highEval, d.highEval) > 0, lo: compare2Card(p.lowEval, d.lowEval) > 0 }; + } + + async compareSeat(seat) { + this.setDockMode('wait', `Dealer turns over ${this.gs.players[seat].name}'s hand`); + const p = this.gs.players[seat]; + const L = seatLayout(seat); + await Promise.all(p.hand.map((_, i) => + this.wait(i * 35).then(() => this.skin.flip(this.cards.get(`${seat}:${i}`), true, 240)))); + if (p.highEval) this.badge(boxBadge(L.high), handName5(p.highEval), 'normal'); + if (p.lowEval) this.badge(boxBadge(L.low), p.lowEval.name, 'normal'); + await this.wait(350); + const w = this.boxWins(p); + this.marker(boxCorner(L.high, 5), w.hi); + await this.wait(220); + this.marker(boxCorner(L.low, 2), w.lo); + await this.wait(260); + this.seatResult(seat); + await this.wait(950); + } + + seatResult(seat) { + const p = this.gs.players[seat]; + const L = seatLayout(seat); + const result = p.result ?? 'lose'; + const isWin = result === 'win'; + playSound(this, isWin ? SFX.CASINO_WIN : result === 'push' ? SFX.CARD_PLACE : SFX.CASINO_LOSE); + if (seat > 0) this.portraits[seat]?.playEmotion?.(isWin ? 'happy' : result === 'push' ? 'happy' : 'upset'); + + const textY = L.high.y - 92 * L.high.s; + const t = this.add.text(L.high.x, textY, RESULT_LABELS[result] ?? result, { + fontFamily: '"Julius Sans One"', fontSize: isWin ? '48px' : '40px', color: RESULT_COLORS[result], + fontStyle: 'bold', stroke: '#000000', strokeThickness: 5, + shadow: isWin ? { offsetX: 0, offsetY: 0, color: RESULT_COLORS.win, blur: 22, fill: true } : undefined, + }).setOrigin(0.5).setAlpha(0).setScale(1.4).setDepth(D.modal); + this.tweens.add({ targets: t, alpha: 1, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.Out' }); + this.time.delayedCall(1300, () => this.tweens.add({ + targets: t, alpha: 0, y: textY - 30, duration: 380, onComplete: () => t.destroy(), + })); + + const st = this.stacks[seat]; + this.settled.add(seat); + delete this.stacks[seat]; + const outcome = isWin ? 'win' : result === 'push' ? 'push' : 'lose'; + const payout = isWin ? p.chipsWon : 0; + settleStack(this, st, outcome, { + payout, commission: isWin ? p.bet - p.chipsWon : 0, + tray: this.trayPos, dest: this.seatSource(seat), depth: D.stacks, sound: () => playChipBet(this), + }).then(() => { + if (seat === 0 && p.chipsWon !== 0) { + const tx = this.chipTxts[0]; + this.floatText(tx.x + tx.width + 50, tx.y, `${p.chipsWon > 0 ? '+' : '−'}$${Math.abs(p.chipsWon)}`, + p.chipsWon > 0 ? '#7ee081' : '#ff8a80'); + } + }); + } + + // The human's comparison gets a close-up: dealer above, you below, ▲▼ per hand. + async closeUp() { + this.setDockMode('wait', 'Your hand against the dealer'); + const p = this.gs.players[0]; + const d = this.gs.dealer; + const PW = 1120, PH = 560, py = 470; + ensureLeatherPanel(this, 'pg-closeup', PW, PH, { radius: 22, felt: FELT }); + const objs = []; + const add = (o) => { objs.push(o); return o; }; + add(this.add.image(CX, py, 'pg-closeup').setDepth(D.closeup)); + const lbl = (x, y, text, size, color) => add(this.add.text(x, y, text, { + fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, + }).setOrigin(0.5).setDepth(D.closeup + 2)); + const HX = CX - 220, LX = CX + 300; + const DY = py - 135, YY = py + 125; + lbl(HX, py - PH / 2 + 30, 'HIGH HAND', 15, '#c9c2b0'); + lbl(LX, py - PH / 2 + 30, 'LOW HAND', 15, '#c9c2b0'); + lbl(CX - 470, DY, 'DEALER', 18, '#e8c15a').setOrigin(0, 0.5); + lbl(CX - 470, YY, 'YOU', 18, '#e8c15a').setOrigin(0, 0.5); + const row = (cards, cx, y, spread) => cards.forEach((card, i) => { + const c = this.skin.make(card, true, cx + (i - (cards.length - 1) / 2) * spread, y, 0.82, 0); + c.setDepth(D.closeup + 1).setScale(0.62).setAlpha(0); + this.tweens.add({ targets: c, scale: 0.82, alpha: 1, duration: 220, delay: i * 40, ease: 'Back.Out' }); + add(c); + }); + row(d.highHand, HX, DY, 62); row(d.lowHand, LX, DY, 92); + row(p.highHand, HX, YY, 62); row(p.lowHand, LX, YY, 92); + const nameY = (y) => y + 72; + const dHi = lbl(HX, nameY(DY), handName5(d.highEval), 17, '#f2ead8'); + const dLo = lbl(LX, nameY(DY), d.lowEval.name, 17, '#f2ead8'); + const pHi = lbl(HX, nameY(YY), p.highEval ? handName5(p.highEval) : 'Foul', 17, '#f2ead8'); + const pLo = lbl(LX, nameY(YY), p.lowEval ? p.lowEval.name : 'Foul', 17, '#f2ead8'); + const chrome = objs.filter(o => !o.card); + chrome.forEach(o => o.setAlpha(0)); + this.tweens.add({ targets: chrome, alpha: 1, duration: 220 }); + + const w = this.boxWins(p); + const arrow = (x, youWin) => { + const g = add(this.add.graphics().setDepth(D.closeup + 2)); + g.fillStyle(youWin ? 0x00e676 : 0xff3a3a, 1); + if (youWin) g.fillTriangle(0, 20, -16, -14, 16, -14); // ▼ toward you + else g.fillTriangle(0, -20, -16, 14, 16, 14); // ▲ toward the dealer + g.setPosition(x, (DY + YY) / 2 + 10).setScale(0); + this.tweens.add({ targets: g, scale: 1, duration: 220, ease: 'Back.Out' }); + }; + await this.wait(650); + arrow(HX, w.hi); + (w.hi ? pHi : dHi).setColor('#f5d020'); + playSound(this, SFX.CARD_SHOW); + await this.wait(800); + arrow(LX, w.lo); + (w.lo ? pLo : dLo).setColor('#f5d020'); + playSound(this, SFX.CARD_SHOW); + await this.wait(550); + + const result = p.result ?? 'lose'; + const verdict = lbl(CX + 40, (DY + YY) / 2 + 10, (RESULT_LABELS[result] ?? result).toUpperCase().replace('!', ''), 64, RESULT_COLORS[result]); + verdict.setFontStyle('bold').setStroke('#000000', 6).setScale(0).setAlpha(1); + this.tweens.add({ targets: verdict, scale: 1, duration: 260, ease: 'Back.Out' }); + await this.wait(1300); + await this.tweenP({ targets: objs, alpha: 0, duration: 260 }); + objs.forEach(o => o.destroy()); + + const L = seatLayout(0); + if (p.highEval) this.badge(boxBadge(L.high), handName5(p.highEval), 'normal'); + if (p.lowEval) this.badge(boxBadge(L.low), p.lowEval.name, 'normal'); + this.marker(boxCorner(L.high, 5), w.hi); + this.marker(boxCorner(L.low, 2), w.lo); + this.seatResult(0); + await this.wait(900); + } + + // ── Decor: hand-name badges + win/lose markers ───────────────────────────── + badge(pos, text, state = 'normal') { + const c = this.add.container(pos.x, pos.y).setDepth(D.badges).setAlpha(0); + const t = this.add.text(0, 0, text, { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: '#f7ecd0', fontStyle: 'bold', + }).setOrigin(0.5); + const g = this.add.graphics(); + const w = t.width + 22, h = 28; + g.fillStyle(state === 'gold' ? 0xd4a017 : 0x0b0906, 0.86); + g.fillRoundedRect(-w / 2, -h / 2, w, h, 14); + g.lineStyle(1.5, 0xc8a84b, 0.75); + g.strokeRoundedRect(-w / 2, -h / 2, w, h, 14); + c.add([g, t]); + c.setScale(Math.min(1, (pos.s ?? 0.9) + 0.12)); + this.tweens.add({ targets: c, alpha: 1, duration: 180 }); + this.decor.push(c); + return c; + } + + marker(pos, win) { + const g = this.add.graphics().setDepth(D.badges + 1); + g.fillStyle(win ? 0x1f9d55 : 0xb3261e, 1); + g.fillCircle(0, 0, 15); + g.lineStyle(2, 0xffffff, 0.9); + g.strokeCircle(0, 0, 15); + g.lineStyle(3.5, 0xffffff, 1); + if (win) { + g.beginPath(); g.moveTo(-7, 0); g.lineTo(-2, 6); g.lineTo(8, -6); g.strokePath(); + } else { + g.beginPath(); g.moveTo(-6, -6); g.lineTo(6, 6); g.moveTo(6, -6); g.lineTo(-6, 6); g.strokePath(); + } + g.setPosition(pos.x, pos.y).setScale(0); + this.tweens.add({ targets: g, scale: pos.s ?? 1, duration: 220, ease: 'Back.Out' }); + this.decor.push(g); + } + + floatText(x, y, str, color) { + const t = this.add.text(x, y, str, { + fontFamily: '"Julius Sans One"', fontSize: '28px', color, fontStyle: 'bold', + stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.modal); + this.tweens.add({ + targets: t, y: y - 60, alpha: { value: 0, ease: 'Expo.easeIn' }, + duration: 1500, ease: 'Cubic.easeOut', onComplete: () => t.destroy(), + }); + } + + // ── Next round ───────────────────────────────────────────────────────────── + showNextRoundPrompt() { + const human = this.gs.players[0]; + this.renderSeatInfo(); + if (human.chips < MIN_BET) { + this.setDockMode('wait', ''); + new Modal(this, 'Out of chips! Visit your profile to request a reset.', { autoCloseMs: 4000 }); + this.time.delayedCall(4200, () => this.scene.start('GameMenu')); + return; + } + this.setDockMode('next'); + const next = new Button(this, CX - 140, DOCK_Y, 'Next Round', () => this.onNextRound(false), { width: 230, height: 58, fontSize: 24 }); + next.setDepth(D.dockUi); + this.dock.addTransient(next); + const amt = this.rebetAmount(1); + if (amt >= MIN_BET) { + const rebet = new Button(this, CX + 130, DOCK_Y, `Rebet $${amt} & Deal`, () => this.onNextRound(true), { + width: 270, height: 58, fontSize: 20, variant: 'ghost', + }); + rebet.setDepth(D.dockUi); + this.dock.addTransient(rebet); + } + } + + async onNextRound(rebet) { + if (this.dockMode !== 'next') return; + if (rebet && this.rebetAmount(1) < MIN_BET) rebet = false; + this.setDockMode('wait', ''); + await this.startNewRound(); + if (!rebet || this.dockMode !== 'bet') return; + await this.onRebet(1); + this.onDealClick(); } } diff --git a/src/games/paigow/PaiGowTable.js b/src/games/paigow/PaiGowTable.js new file mode 100644 index 0000000..ff2224c --- /dev/null +++ b/src/games/paigow/PaiGowTable.js @@ -0,0 +1,134 @@ +// Pai Gow Poker table layout — Phaser-free so tools/verifyPaiGowPoker.js can test it. +// +// Shared perspective + rail geometry come from src/ui/casino/CasinoGeometry.js +// (re-exported). Each seat has a bet circle near the rail, a HIGH box (5 cards) +// and, inboard toward the dealer, a LOW box (2 cards). + +import { polar, project, radialRotation, VIEW } from '../../ui/casino/CasinoGeometry.js'; + +export * from '../../ui/casino/CasinoGeometry.js'; + +export const CARD_W = 96; +export const CARD_H = 134; + +// Seat 0 = human (bottom-centre); 1/2 bottom-right/left; 3/4 upper-right/left. +// The registry caps the table at 4 opponents; seat 5 only exists so the logic's +// sixth player slot always has somewhere to sit. +export const SEAT_ANGLES = [0, 28, -28, 56, -56, 78]; +export const PLAY_ORDER = [5, 3, 1, 0, 2, 4]; + +export const BET_R = 0.89; +export const HIGH_R = 0.72; +export const LOW_R = 0.528; +export const BET_SPOT_R = 0.058; +export const FAN_DX = 17; // px @ s=1 between fanned cards in a set hand +export const STACK_DX = 2.2; // px between cards in an unset 7-card stack +export const ROT_DAMP = 0.62; + +const PORTRAITS = [ + { x: 160, y: 1013, r: 50 }, // 0 human — in the dock + { x: 1584, y: 800, r: 56 }, // 1 right-bottom + { x: 336, y: 800, r: 56 }, // 2 left-bottom + { x: 1800, y: 560, r: 56 }, // 3 right-upper + { x: 120, y: 560, r: 56 }, // 4 left-upper + { x: 1810, y: 300, r: 56 }, // 5 right-top (unused at 4 opponents) +]; + +export function seatLayout(seat) { + const theta = SEAT_ANGLES[seat]; + const high = { ...polar(HIGH_R, theta), rot: radialRotation(HIGH_R, theta, ROT_DAMP) }; + const low = { ...polar(LOW_R, theta), rot: radialRotation(LOW_R, theta, ROT_DAMP) }; + const bet = polar(BET_R, theta); + return { seat, theta, high, low, bet, portrait: { ...PORTRAITS[seat] } }; +} + +// Offset a box pose along its own (rotated) x/y axes. +function along(box, lx, ly) { + const cos = Math.cos(box.rot), sin = Math.sin(box.rot); + return { x: box.x + lx * cos - ly * sin, y: box.y + lx * sin + ly * cos, rot: box.rot, s: box.s }; +} + +// Card i of n fanned inside a box. +export function fanPose(box, i, n) { + return along(box, (i - (n - 1) / 2) * FAN_DX * box.s, 0); +} + +// Unset 7-card stack sitting in the HIGH box. +export function stackPose(box, i) { + return along(box, (i - 3) * STACK_DX * box.s, -i * 0.6 * box.s); +} + +// Corner of a box (for the ✓ / ✗ markers), n = cards in the box. +export function boxCorner(box, n) { + const halfW = ((CARD_W + (n - 1) * FAN_DX) / 2) * box.s; + const halfH = (CARD_H / 2) * box.s * VIEW.squash; + return along(box, halfW + 4, -halfH + 4); +} + +// Where the hand-name badge goes: over the bottom of the cards. +export function boxBadge(box) { + return along(box, 0, (CARD_H / 2) * box.s * VIEW.squash - 14); +} + +// ── Dealer ─────────────────────────────────────────────────────────────────── +export const DEALER_V = 0.205; +export const DEALER_BOOST = 1.08; +export const DEALER_HIGH = { u: -0.15, v: DEALER_V }; +export const DEALER_LOW = { u: 0.16, v: DEALER_V }; + +function dealerBox(spot) { + const p = project(spot.u, spot.v); + return { ...p, s: p.s * DEALER_BOOST, rot: 0 }; +} +export const dealerHighBox = () => dealerBox(DEALER_HIGH); +export const dealerLowBox = () => dealerBox(DEALER_LOW); + +// Dealer's 7 face-down cards before the reveal, in a row. +export function dealerRowPose(i) { + const p = project(0, DEALER_V); + const s = p.s * DEALER_BOOST; + return { x: p.x + (i - 3) * 30 * s, y: p.y, rot: 0, s }; +} + +// ── Furniture ──────────────────────────────────────────────────────────────── +export const DICE_CUP = { u: 0.47, v: 0.085 }; +export const DICE_LAND = { u: 0.3, v: 0.16 }; // where the dice come to rest +export const DECK = { u: 0.36, v: 0.07 }; // deck in the dealer's hands +export const DISCARD = { u: -0.47, v: 0.085 }; +export const PLACARD = { u: -0.335, v: 0.035, lines: ['5% COMMISSION', '$5 – $100'] }; + +// Felt lettering +export const FELT_TEXT = [ + { text: 'PAI GOW POKER', r: 0.41, size: 30, color: '#e8c15a', alpha: 0.95, spacing: 1.06, bold: true }, + { text: 'COPIES GO TO THE BANKER', r: 0.345, size: 15, color: '#f2ead8', alpha: 0.72, spacing: 0.95 }, +]; + +// ── Dice → first seat ──────────────────────────────────────────────────────── +// Real tables count the dice total counter-clockwise from the dealer (position 1). +// `positions` is the list starting with 'dealer' then the seats in deal order. +export function diceStartIndex(total, positionCount) { + return (((total - 1) % positionCount) + positionCount) % positionCount; +} + +export function rotateFrom(arr, idx) { + return [...arr.slice(idx), ...arr.slice(0, idx)]; +} + +// ── Setting tray (expands up out of the dock) ──────────────────────────────── +export const SET_TRAY = { x0: 400, x1: 1520, y0: 778, y1: 1080 }; +export const TRAY_CARD_Y = 902; +export const TRAY_SCALE = 0.95; +export const TRAY_HIGH = { x0: 430, x1: 1040 }; // HIGH zone (holds up to 7 cards) +export const TRAY_LOW = { x0: 1066, x1: 1266 }; // LOW zone (2 cards) +export const TRAY_HIGH_DX = 82; +export const TRAY_LOW_DX = 98; + +export function trayHighX(i, n) { + const mid = (TRAY_HIGH.x0 + TRAY_HIGH.x1) / 2; + return mid + (i - (n - 1) / 2) * TRAY_HIGH_DX; +} + +export function trayLowX(i) { + const mid = (TRAY_LOW.x0 + TRAY_LOW.x1) / 2; + return mid + (i - 0.5) * TRAY_LOW_DX; +} diff --git a/src/ui/CasinoChips.js b/src/ui/CasinoChips.js new file mode 100644 index 0000000..d9ae9f8 --- /dev/null +++ b/src/ui/CasinoChips.js @@ -0,0 +1,398 @@ +// Casino poker chips — shared, procedurally baked chip art. +// +// Textures (baked once into the global TextureManager, so they survive scene changes): +// chip-face- 128×128 top-down chip (buttons, thrown chips) +// chip-slice- one chip seen at a tilt (top face + edge band) — stack these +// bottom-up, each one SLICE_T px higher, to build a 3D stack. +// +// breakdown() is pure so verify scripts can import this file under Node; the +// bakers only touch `document` when called. +// +// Usage: +// ensureChipTextures(scene); // after fonts are loaded +// makeChip(scene, x, y, 25, { size: 72 }); // flat face image +// makeChipStack(scene, x, y, 135, { scale: 0.9 }); // container, bottom chip centred on (x, y) + +export const CHIP_DEFS = { + 1: { base: '#ebe6da', insert: '#2b5fb4', accent: '#c3242b', text: '#2b5fb4' }, + 5: { base: '#c1222a', insert: '#f4efe4', accent: '#1f4fa0', text: '#a51c22' }, + 25: { base: '#1d7d3a', insert: '#f4efe4', accent: '#e2b93b', text: '#17652f' }, + 50: { base: '#1f5bb8', insert: '#f4efe4', accent: '#f08a1c', text: '#1a4c9a' }, + 100: { base: '#1b1b20', insert: '#f4efe4', accent: '#d4a017', text: '#1b1b20' }, +}; +export const DENOMS = [100, 50, 25, 5, 1]; + +// Greedy denomination breakdown, largest first (= bottom of the stack). +export function breakdown(amount) { + const out = []; + let rest = Math.max(0, Math.floor(amount)); + for (const d of DENOMS) { + while (rest >= d) { out.push(d); rest -= d; } + } + return out; +} + +export function chipColor(denom) { + return parseInt((CHIP_DEFS[denom]?.base ?? '#888888').slice(1), 16); +} + +// ── Geometry of the baked art ──────────────────────────────────────────────── +export const FACE = 128; // face texture size +const R = 62; // chip radius inside the face texture +export const SLICE_RY = 25; // vertical radius of the tilted top ellipse +export const SLICE_T = 11; // edge thickness (texture px) +export const SLICE_H = SLICE_RY * 2 + SLICE_T + 4; +const SLICE_CY_TOP = SLICE_RY + 2; +const SLICE_CY_BOT = SLICE_CY_TOP + SLICE_T; +const INSERT_ANGLES = [30, 90, 150, 210, 270, 330]; +const INSERT_HALF = 13; // degrees + +// ── Colour helpers ─────────────────────────────────────────────────────────── +function shade(hex, amt) { + // amt −1 … +1: darken toward black / lighten toward white + const n = parseInt(hex.slice(1), 16); + let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255; + const t = amt < 0 ? 0 : 255, p = Math.abs(amt); + r = Math.round((t - r) * p + r); g = Math.round((t - g) * p + g); b = Math.round((t - b) * p + b); + return `rgb(${r},${g},${b})`; +} + +function annularSector(ctx, cx, cy, r0, r1, a0, a1) { + ctx.beginPath(); + ctx.arc(cx, cy, r1, a0, a1, false); + ctx.arc(cx, cy, r0, a1, a0, true); + ctx.closePath(); +} + +const DEG = Math.PI / 180; + +// ── Face ───────────────────────────────────────────────────────────────────── +function drawFace(ctx, denom) { + const def = CHIP_DEFS[denom]; + const cx = FACE / 2, cy = FACE / 2; + + // Body + const body = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R); + body.addColorStop(0, shade(def.base, 0.22)); + body.addColorStop(0.6, def.base); + body.addColorStop(1, shade(def.base, -0.35)); + ctx.fillStyle = body; + ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); + + // Edge inserts with thin accent stripes + for (const a of INSERT_ANGLES) { + ctx.fillStyle = def.insert; + annularSector(ctx, cx, cy, R * 0.74, R * 0.985, (a - INSERT_HALF) * DEG, (a + INSERT_HALF) * DEG); + ctx.fill(); + ctx.fillStyle = def.accent; + for (const off of [-6.5, 6.5]) { + annularSector(ctx, cx, cy, R * 0.74, R * 0.985, (a + off - 1.6) * DEG, (a + off + 1.6) * DEG); + ctx.fill(); + } + } + + // Bevel: dark outer edge + a top-left highlight + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; + ctx.beginPath(); ctx.arc(cx, cy, R - 1.5, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; + ctx.beginPath(); ctx.arc(cx, cy, R - 4, 195 * DEG, 290 * DEG); ctx.stroke(); + + // Dashed inner ring + ctx.save(); + ctx.setLineDash([7, 5]); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(255,255,255,0.85)'; + if (denom === 1) ctx.strokeStyle = def.insert; + ctx.beginPath(); ctx.arc(cx, cy, R * 0.67, 0, Math.PI * 2); ctx.stroke(); + ctx.restore(); + + // Inlay + const inR = R * 0.56; + const inlay = ctx.createLinearGradient(cx - inR, cy - inR, cx + inR, cy + inR); + inlay.addColorStop(0, '#fdf9ef'); + inlay.addColorStop(1, '#e3d6bb'); + ctx.fillStyle = inlay; + ctx.beginPath(); ctx.arc(cx, cy, inR, 0, Math.PI * 2); ctx.fill(); + ctx.lineWidth = 2.5; + ctx.strokeStyle = '#c9a24a'; + ctx.beginPath(); ctx.arc(cx, cy, inR, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 1; + ctx.strokeStyle = def.text; + ctx.globalAlpha = 0.55; + ctx.beginPath(); ctx.arc(cx, cy, inR - 5, 0, Math.PI * 2); ctx.stroke(); + // ring of engraved dots + ctx.fillStyle = def.text; + for (let i = 0; i < 16; i++) { + const a = (i / 16) * Math.PI * 2; + ctx.beginPath(); ctx.arc(cx + Math.cos(a) * (inR - 10), cy + Math.sin(a) * (inR - 10), 1.3, 0, Math.PI * 2); ctx.fill(); + } + ctx.globalAlpha = 1; + + // Denomination (embossed) + const label = String(denom); + const size = label.length === 1 ? 44 : label.length === 2 ? 38 : 30; + ctx.font = `${size}px Righteous, "Julius Sans One", sans-serif`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(255,255,255,0.8)'; + ctx.fillText(label, cx + 1, cy + 3); + ctx.fillStyle = def.text; + ctx.fillText(label, cx, cy + 2); + + // Gloss + const gloss = ctx.createRadialGradient(cx - R * 0.45, cy - R * 0.5, 0, cx - R * 0.3, cy - R * 0.35, R * 1.05); + gloss.addColorStop(0, 'rgba(255,255,255,0.32)'); + gloss.addColorStop(0.45, 'rgba(255,255,255,0.06)'); + gloss.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = gloss; + ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); +} + +// ── Tilted slice (edge band + squashed face) ───────────────────────────────── +function drawSlice(ctx, faceCanvas, denom) { + const def = CHIP_DEFS[denom]; + const cx = FACE / 2, rx = R, ry = SLICE_RY; + const yT = SLICE_CY_TOP, yB = SLICE_CY_BOT; + + // Edge band + 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.ellipse(cx, yT, rx, ry, 0, 0, Math.PI, false); + ctx.closePath(); + ctx.fillStyle = shade(def.base, -0.1); + ctx.fill(); + + // Edge inserts visible on the front half of the band + ctx.fillStyle = def.insert; + for (const a of INSERT_ANGLES) { + const a0 = (a - INSERT_HALF) * DEG, a1 = (a + INSERT_HALF) * DEG; + if (Math.sin(a0) <= 0 && Math.sin(a1) <= 0) continue; + ctx.beginPath(); + const steps = 8; + for (let i = 0; i <= steps; i++) { + const t = a0 + ((a1 - a0) * i) / steps; + const y = yT + Math.max(0, Math.sin(t)) * ry; + ctx[i ? 'lineTo' : 'moveTo'](cx + Math.cos(t) * rx, y); + } + for (let i = steps; i >= 0; i--) { + const t = a0 + ((a1 - a0) * i) / steps; + ctx.lineTo(cx + Math.cos(t) * rx, yB + Math.max(0, Math.sin(t)) * ry); + } + ctx.closePath(); + ctx.fill(); + } + + // Cylindrical shading over the band + ctx.save(); + 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(); + ctx.clip(); + const cyl = ctx.createLinearGradient(cx - rx, 0, cx + rx, 0); + cyl.addColorStop(0, 'rgba(0,0,0,0.55)'); + cyl.addColorStop(0.32, 'rgba(255,255,255,0.18)'); + cyl.addColorStop(0.55, 'rgba(0,0,0,0.05)'); + cyl.addColorStop(1, 'rgba(0,0,0,0.6)'); + ctx.fillStyle = cyl; + ctx.fillRect(0, 0, FACE, SLICE_H); + ctx.restore(); + + // Seam between stacked chips + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; + ctx.beginPath(); ctx.ellipse(cx, yB, rx, ry, 0, 0, Math.PI, false); ctx.stroke(); + + // Top face, squashed into the ellipse + const pad = (FACE / 2 - R); + ctx.drawImage(faceCanvas, pad, pad, R * 2, R * 2, cx - rx, yT - ry, rx * 2, ry * 2); +} + +function makeCanvas(w, h) { + const c = document.createElement('canvas'); + c.width = w; c.height = h; + return c; +} + +export function ensureChipTextures(scene) { + for (const d of DENOMS) { + const faceKey = `chip-face-${d}`; + const sliceKey = `chip-slice-${d}`; + if (scene.textures.exists(faceKey) && scene.textures.exists(sliceKey)) continue; + const face = makeCanvas(FACE, FACE); + drawFace(face.getContext('2d'), d); + if (!scene.textures.exists(faceKey)) scene.textures.addCanvas(faceKey, face); + const slice = makeCanvas(FACE, SLICE_H); + drawSlice(slice.getContext('2d'), face, d); + if (!scene.textures.exists(sliceKey)) scene.textures.addCanvas(sliceKey, slice); + } +} + +// ── Game objects ───────────────────────────────────────────────────────────── + +// Flat top-down chip (an Image, so its hit area can be set in texture space: +// img.setInteractive(new Phaser.Geom.Circle(64, 64, 62), Phaser.Geom.Circle.Contains)). +export function makeChip(scene, x, y, denom, { size = 64, depth } = {}) { + const img = scene.add.image(x, y, `chip-face-${denom}`).setDisplaySize(size, size); + if (depth !== undefined) img.setDepth(depth); + return img; +} + +// A single tilted chip (for chips in flight over the felt). +export function makeChipSlice(scene, x, y, denom, { size = 52, depth } = {}) { + const img = scene.add.image(x, y, `chip-slice-${denom}`) + .setOrigin(0.5, SLICE_CY_BOT / SLICE_H) + .setScale(size / FACE); + if (depth !== undefined) img.setDepth(depth); + return img; +} + +// Deterministic tiny jitter so stacks look hand-placed but don't shimmer on redraw. +function jitter(i, seed) { + const s = Math.sin((i + 1) * 12.9898 + seed * 78.233) * 43758.5453; + return (s - Math.floor(s)) * 2 - 1; +} + +// A 3D stack for `amount`. The container's origin is the felt contact point of +// the bottom chip. Children are added bottom-up (containers ignore child depth). +export function makeChipStack(scene, x, y, amount, { + size = 52, depth, label = true, seed = 0, maxChips = 14, +} = {}) { + const cont = scene.add.container(x, y); + if (depth !== undefined) cont.setDepth(depth); + let chips = breakdown(amount); + if (chips.length > maxChips) chips = chips.slice(0, maxChips); + const k = size / FACE; + const step = SLICE_T * k; + + const shadow = scene.add.graphics(); + shadow.fillStyle(0x000000, 0.38); + shadow.fillEllipse(size * 0.08, size * 0.06, size * 1.12, SLICE_RY * 2 * k * 1.15); + cont.add(shadow); + + chips.forEach((d, i) => { + const img = scene.add.image(jitter(i, seed) * 1.4 * k * 2, -i * step, `chip-slice-${d}`) + .setOrigin(0.5, SLICE_CY_BOT / SLICE_H) + .setScale(k); + cont.add(img); + }); + + const topY = -(Math.max(1, chips.length) - 1) * step - (SLICE_T + SLICE_RY) * k; + cont.stackTopY = topY; + + if (label && amount > 0) { + const txt = scene.add.text(size * 0.62, -SLICE_RY * k * 0.2, `$${amount.toLocaleString()}`, { + fontFamily: '"Julius Sans One"', fontSize: `${Math.round(15 * Math.max(0.8, size / 52))}px`, + color: '#f7ecd0', fontStyle: 'bold', + }).setOrigin(0, 0.5); + const pill = scene.add.graphics(); + pill.fillStyle(0x0b0806, 0.78); + pill.fillRoundedRect(txt.x - 6, txt.y - txt.height / 2 - 2, txt.width + 12, txt.height + 4, 6); + pill.lineStyle(1, 0xc8a84b, 0.7); + pill.strokeRoundedRect(txt.x - 6, txt.y - txt.height / 2 - 2, txt.width + 12, txt.height + 4, 6); + cont.add([pill, txt]); + } + return cont; +} + +// ── Chip flights (scene-agnostic; callers own their stack bookkeeping) ─────── +const lerpN = (a, b, t) => a + (b - a) * t; + +function tweenP(scene, cfg) { + return new Promise(res => scene.tweens.add({ ...cfg, onComplete: () => res() })); +} + +// One chip arcs from `from` to `to` ({x, y, s}) and vanishes on landing. +export function throwChip(scene, denom, from, to, { delay = 0, size = 54, depth = 22, sound } = {}) { + const chip = makeChipSlice(scene, from.x, from.y, denom, { size: 64, depth }); + const k0 = chip.scaleX; + const k1 = (size * (to.s ?? 1)) / FACE; + const prox = { t: 0 }; + return new Promise(res => { + scene.tweens.add({ + targets: prox, t: 1, duration: 360, delay, ease: 'Cubic.easeOut', + onUpdate: () => { + const t = prox.t; + chip.x = lerpN(from.x, to.x, t); + chip.y = lerpN(from.y, to.y, t) - Math.sin(Math.PI * t) * 90; + chip.setScale(lerpN(k0, k1, t)); + chip.rotation = (1 - t) * 0.6; + }, + onComplete: () => { chip.destroy(); sound?.(); res(); }, + }); + }); +} + +// A whole stack slides from `from` to `pose`; the caller redraws the real stack after. +export async function throwStack(scene, from, pose, amount, { delay = 0, size = 54, depth = 22, sound } = {}) { + const st = makeChipStack(scene, from.x, from.y, amount, { size: size * (pose.s ?? 1), depth, label: false }); + st.setAlpha(0).setScale(0.8); + await tweenP(scene, { + targets: st, x: pose.x, y: pose.y, alpha: 1, scale: 1, duration: 380, delay, ease: 'Cubic.easeOut', + }); + sound?.(); + st.destroy(); +} + +/** + * Resolve a bet stack that is already on the felt. + * outcome 'lose' → swept to the tray + * outcome 'push' → slides back to the player + * outcome 'win' → the dealer stacks `payout + commission` beside it; the + * commission (if any) peels off back to the tray with a + * "−5%" tag; then everything slides to the player. + * opts: { payout, commission, tray: {x,y}, dest: {x,y}, depth, sound, tag } + */ +export async function settleStack(scene, st, outcome, { + payout = 0, commission = 0, tray, dest, depth = 12, sound, tag = '−5%', +} = {}) { + if (!st) return; + if (outcome === 'lose') { + await tweenP(scene, { + targets: st, x: tray.x + (Math.random() - 0.5) * 120, y: tray.y, + scale: 0.7, alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 520, ease: 'Cubic.easeInOut', + }); + st.destroy(); + return; + } + const size = st.chipSize ?? 54; + const sweepOut = [st]; + if (outcome === 'win' && payout > 0) { + const gross = payout + commission; + let pay = makeChipStack(scene, tray.x, tray.y, gross, { size, depth: depth + 1, seed: gross + 7 }); + pay.setScale(0.75); + const px = st.x + size * 1.05, py = st.y + 2; + await tweenP(scene, { targets: pay, x: px, y: py, scale: 1, duration: 440, ease: 'Cubic.easeOut' }); + sound?.(); + if (commission > 0) { + await new Promise(r => scene.time.delayedCall(380, r)); + pay.destroy(); + pay = makeChipStack(scene, px, py, payout, { size, depth: depth + 1, seed: payout + 7 }); + const cut = makeChipStack(scene, px, py - 4, commission, { size: size * 0.85, depth: depth + 2, label: false }); + const t = scene.add.text(px, py - size * 0.9, tag, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#ff8a80', fontStyle: 'bold', + stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(depth + 3); + scene.tweens.add({ targets: t, y: t.y - 30, alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 1100, onComplete: () => t.destroy() }); + await tweenP(scene, { + targets: cut, x: tray.x, y: tray.y, scale: 0.6, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 560, ease: 'Cubic.easeInOut', + }); + cut.destroy(); + } + sweepOut.push(pay); + await new Promise(r => scene.time.delayedCall(420, r)); + } + await tweenP(scene, { + targets: sweepOut, x: dest.x, y: dest.y, scale: 0.6, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 520, ease: 'Cubic.easeIn', + }); + sweepOut.forEach(o => o.destroy()); +} diff --git a/src/ui/casino/CasinoArt.js b/src/ui/casino/CasinoArt.js new file mode 100644 index 0000000..e5e29eb --- /dev/null +++ b/src/ui/casino/CasinoArt.js @@ -0,0 +1,996 @@ +// Shared casino art — everything is baked once into canvas textures (no image files). +// +// casino-cards atlas, one frame per card key ('As', 'Td', …, 'JK') at 2× resolution +// casino-back- fallback card back in the player's chosen colour +// casino-card-shadow soft drop shadow sized for a card (same 2× scale) +// casino-dock leather/wood control strip along the bottom +// casino-die-<1..6> casino dice faces; casino-dice-cup leather shaker cup +// a full-screen 1920×1080 table baked by bakeCasinoTable(spec) +// +// Table specs come from each game (felt colour, markings callback, lettering, +// furniture). All geometry is CasinoGeometry.js, so markings line up with +// where the game places cards and chips. + +import { + VIEW, project, polar, arcTangent, arcPoints, + FELT_R, RAIL_IN, RAIL_OUT, RAIL_FACE_PX, DOCK, +} from './CasinoGeometry.js'; +import { CHIP_DEFS, ensureChipTextures } from '../CasinoChips.js'; +import { SUITS, RANKS } from '../../games/cards/Deck.js'; + +export const CARD_W = 96; +export const CARD_H = 134; +const RES = 2; +const CW = CARD_W * RES; +const CH = CARD_H * RES; +const CR = 14; // corner radius (texture px) +export const SHADOW_PAD = 40; // texture px around the card in casino-card-shadow + +const W = 1920, H = 1080; +const RED = '#c0182a'; +const BLACK = '#16161d'; +const SERIF = 'Georgia, "Times New Roman", serif'; + +// ── Entry point ────────────────────────────────────────────────────────────── +export async function prepareCasinoArt(scene) { + try { + await Promise.all([ + document.fonts?.load('36px "Julius Sans One"'), + document.fonts?.load('40px Righteous'), + ]); + } catch { /* fall back to whatever is available */ } + ensureChipTextures(scene); + if (!scene.textures.exists('casino-cards')) bakeCards(scene); + if (!scene.textures.exists('casino-card-shadow')) bakeCardShadow(scene); + if (!scene.textures.exists('casino-dock')) bakeDock(scene); + ensureDiceArt(scene); +} + +export function ensureCardBack(scene, fallbackColor) { + const hex = (fallbackColor ?? '#1a3a6b').replace('#', '').toLowerCase(); + const key = `casino-back-${hex}`; + if (scene.textures.exists(key)) return key; + const c = canvas(CW, CH); + drawCardBack(c.getContext('2d'), 0, 0, `#${hex}`); + scene.textures.addCanvas(key, c); + return key; +} + +// ── Helpers (exported for game-specific markings) ──────────────────────────── +export function canvas(w, h) { + const c = document.createElement('canvas'); + c.width = w; c.height = h; + return c; +} + +export function rr(ctx, x, y, w, h, r) { + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.lineTo(x + w - r, y); + ctx.quadraticCurveTo(x + w, y, x + w, y + r); + ctx.lineTo(x + w, y + h - r); + ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h); + ctx.lineTo(x + r, y + h); + ctx.quadraticCurveTo(x, y + h, x, y + h - r); + ctx.lineTo(x, y + r); + ctx.quadraticCurveTo(x, y, x + r, y); + ctx.closePath(); +} + +export function poly(ctx, pts, close = true) { + ctx.beginPath(); + pts.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + if (close) ctx.closePath(); +} + +export function lerp(a, b, t) { return a + (b - a) * t; } + +export function mix(c1, c2, t) { + const a = parseInt(c1.slice(1), 16), b = parseInt(c2.slice(1), 16); + const r = Math.round(lerp((a >> 16) & 255, (b >> 16) & 255, t)); + const g = Math.round(lerp((a >> 8) & 255, (b >> 8) & 255, t)); + const bl = Math.round(lerp(a & 255, b & 255, t)); + return `rgb(${r},${g},${bl})`; +} + +export function noisePattern(ctx, size, alpha) { + const c = canvas(size, size); + const n = c.getContext('2d'); + const img = n.createImageData(size, size); + for (let i = 0; i < img.data.length; i += 4) { + const v = Math.random() < 0.5 ? 0 : 255; + img.data[i] = img.data[i + 1] = img.data[i + 2] = v; + img.data[i + 3] = Math.random() * alpha; + } + n.putImageData(img, 0, 0); + return ctx.createPattern(c, 'repeat'); +} + +// Text along a table-space arc of radius r, centred on θ = centerDeg. +export function drawArcText(ctx, spec) { + const { text, r, size, color, alpha = 1, spacing = 1, bold, centerDeg = 0 } = spec; + ctx.font = `${bold ? 'bold ' : ''}${size}px "Julius Sans One", sans-serif`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + const s0 = polar(r, centerDeg).s; + const pxPerRad = VIEW.halfW * s0 * r; + const widths = [...text].map(ch => ctx.measureText(ch).width * spacing); + const total = widths.reduce((a, b) => a + b, 0); + let a = (centerDeg * Math.PI) / 180 - total / 2 / pxPerRad; + ctx.save(); + ctx.globalAlpha = alpha; + ctx.fillStyle = color; + ctx.shadowColor = 'rgba(0,0,0,0.35)'; + ctx.shadowBlur = 2; + ctx.shadowOffsetY = 1; + [...text].forEach((ch, i) => { + const mid = a + widths[i] / 2 / pxPerRad; + a += widths[i] / pxPerRad; + if (ch === ' ') return; + const deg = (mid * 180) / Math.PI; + const p = polar(r, deg); + const k = p.s / s0; + ctx.save(); + ctx.translate(p.x, p.y); + ctx.rotate(arcTangent(r, deg)); + ctx.scale(k, k * VIEW.squash); + ctx.fillText(ch, 0, 0); + ctx.restore(); + }); + ctx.restore(); +} + +// ── Suits ──────────────────────────────────────────────────────────────────── +function heartPath(ctx, x, y, size) { + const s = size / 2; + ctx.moveTo(x, y + s); + ctx.bezierCurveTo(x - s * 1.3, y - s * 0.05, x - s * 0.72, y - s * 1.18, x, y - s * 0.42); + ctx.bezierCurveTo(x + s * 0.72, y - s * 1.18, x + s * 1.3, y - s * 0.05, x, y + s); + ctx.closePath(); +} + +function stemPath(ctx, x, y, s) { + ctx.moveTo(x, y + s * 0.05); + ctx.quadraticCurveTo(x - s * 0.08, y + s * 0.75, x - s * 0.42, y + s); + ctx.lineTo(x + s * 0.42, y + s); + ctx.quadraticCurveTo(x + s * 0.08, y + s * 0.75, x, y + s * 0.05); + ctx.closePath(); +} + +export function drawSuit(ctx, suit, x, y, size, color) { + const s = size / 2; + ctx.fillStyle = color ?? (suit === 'h' || suit === 'd' ? RED : BLACK); + ctx.beginPath(); + if (suit === 'h') { + heartPath(ctx, x, y, size); + } else if (suit === 'd') { + ctx.moveTo(x, y - s); + ctx.quadraticCurveTo(x + s * 0.28, y - s * 0.3, x + s * 0.74, y); + ctx.quadraticCurveTo(x + s * 0.28, y + s * 0.3, x, y + s); + ctx.quadraticCurveTo(x - s * 0.28, y + s * 0.3, x - s * 0.74, y); + ctx.quadraticCurveTo(x - s * 0.28, y - s * 0.3, x, y - s); + ctx.closePath(); + } else if (suit === 's') { + ctx.save(); + ctx.translate(x, y - s * 0.16); + ctx.scale(1, -1); + heartPath(ctx, 0, 0, size * 0.84); + ctx.restore(); + stemPath(ctx, x, y, s); + } else { + const r = s * 0.36; + ctx.arc(x, y - s * 0.44, r, 0, Math.PI * 2); + ctx.moveTo(x - s * 0.4 + r, y + s * 0.06); + ctx.arc(x - s * 0.4, y + s * 0.06, r, 0, Math.PI * 2); + ctx.moveTo(x + s * 0.4 + r, y + s * 0.06); + ctx.arc(x + s * 0.4, y + s * 0.06, r, 0, Math.PI * 2); + ctx.moveTo(x + s * 0.2, y - s * 0.05); + ctx.arc(x, y - s * 0.05, s * 0.2, 0, Math.PI * 2); + stemPath(ctx, x, y, s); + } + ctx.fill(); +} + +// ── Cards ──────────────────────────────────────────────────────────────────── +const L = 0.3, M = 0.5, R = 0.7, T = 0.21, B = 0.79; +const PIPS = { + 2: [[M, T], [M, B]], + 3: [[M, T], [M, 0.5], [M, B]], + 4: [[L, T], [R, T], [L, B], [R, B]], + 5: [[L, T], [R, T], [M, 0.5], [L, B], [R, B]], + 6: [[L, T], [R, T], [L, 0.5], [R, 0.5], [L, B], [R, B]], + 7: [[L, T], [R, T], [M, 0.355], [L, 0.5], [R, 0.5], [L, B], [R, B]], + 8: [[L, T], [R, T], [M, 0.355], [L, 0.5], [R, 0.5], [M, 0.645], [L, B], [R, B]], + 9: [[L, T], [R, T], [L, 0.405], [R, 0.405], [M, 0.5], [L, 0.595], [R, 0.595], [L, B], [R, B]], + 10: [[L, T], [R, T], [M, 0.31], [L, 0.405], [R, 0.405], [L, 0.595], [R, 0.595], [M, 0.69], [L, B], [R, B]], +}; + +function cardBase(ctx, x, y) { + rr(ctx, x + 1, y + 1, CW - 2, CH - 2, CR); + const g = ctx.createLinearGradient(x, y, x + CW, y + CH); + g.addColorStop(0, '#fffdf7'); + g.addColorStop(1, '#efe7d6'); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = '#cbbfa6'; + ctx.stroke(); + rr(ctx, x + 6, y + 6, CW - 12, CH - 12, CR - 5); + ctx.lineWidth = 1; + ctx.strokeStyle = 'rgba(0,0,0,0.05)'; + ctx.stroke(); +} + +function cornerIndex(ctx, label, suit, color) { + ctx.fillStyle = color; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.font = `bold 40px ${SERIF}`; + ctx.save(); + ctx.translate(24, 32); + if (label.length > 1) ctx.scale(0.72, 1); + ctx.fillText(label, 0, 0); + ctx.restore(); + drawSuit(ctx, suit, 24, 68, 26, color); +} + +function crown(ctx, cx, cy, w, h, points, color) { + const left = cx - w / 2, top = cy - h / 2, base = cy + h / 2; + ctx.beginPath(); + ctx.moveTo(left, base); + ctx.lineTo(left, top); + for (let i = 1; i < points; i++) { + const px = left + (w * i) / (points - 1); + const vx = px - w / (points - 1) / 2; + ctx.lineTo(vx, cy + h * 0.08); + ctx.lineTo(px, top); + } + ctx.lineTo(left + w, base); + ctx.closePath(); + ctx.fillStyle = '#dcae35'; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = '#7c5a12'; + ctx.stroke(); + for (let i = 0; i < points; i++) { + ctx.beginPath(); + ctx.arc(left + (w * i) / (points - 1), top - 3, 4.5, 0, Math.PI * 2); + ctx.fillStyle = color; + ctx.fill(); + } + ctx.fillStyle = color; + ctx.fillRect(left, base - 8, w, 8); + ctx.fillStyle = '#f5d76e'; + for (let i = 0; i < 3; i++) { + ctx.beginPath(); + ctx.arc(cx + (i - 1) * w * 0.3, base - 4, 2.4, 0, Math.PI * 2); + ctx.fill(); + } +} + +function jackCap(ctx, cx, cy, color) { + ctx.beginPath(); + ctx.ellipse(cx, cy + 10, 30, 22, 0, Math.PI, 0); + ctx.closePath(); + ctx.fillStyle = color; + ctx.fill(); + ctx.fillStyle = '#dcae35'; + ctx.fillRect(cx - 32, cy + 8, 64, 8); + ctx.strokeStyle = '#7c5a12'; + ctx.lineWidth = 2; + ctx.strokeRect(cx - 32, cy + 8, 64, 8); + ctx.beginPath(); + ctx.moveTo(cx + 14, cy - 6); + ctx.bezierCurveTo(cx + 34, cy - 34, cx + 52, cy - 22, cx + 46, cy - 6); + ctx.bezierCurveTo(cx + 40, cy - 18, cx + 28, cy - 18, cx + 14, cy - 6); + ctx.fillStyle = '#dcae35'; + ctx.fill(); + ctx.stroke(); +} + +function courtPanel(ctx) { + const px = 46, py = 40, pw = CW - 92, ph = CH - 80; + rr(ctx, px, py, pw, ph, 8); + const g = ctx.createLinearGradient(px, py, px + pw, py + ph); + g.addColorStop(0, '#fbf1d9'); + g.addColorStop(1, '#ecd29c'); + ctx.fillStyle = g; + ctx.fill(); + return { px, py, pw, ph }; +} + +function hatch(ctx, px, py, pw, ph) { + ctx.save(); + rr(ctx, px + 5, py + 5, pw - 10, ph - 10, 5); + ctx.clip(); + ctx.strokeStyle = 'rgba(160,120,40,0.12)'; + ctx.lineWidth = 1; + for (let k = -ph; k < pw + ph; k += 7) { + ctx.beginPath(); ctx.moveTo(px + k, py); ctx.lineTo(px + k - ph, py + ph); ctx.stroke(); + } + ctx.restore(); +} + +function drawCourt(ctx, rank, suit, color) { + const { px, py, pw, ph } = courtPanel(ctx); + ctx.lineWidth = 3; + ctx.strokeStyle = color; + ctx.stroke(); + rr(ctx, px + 5, py + 5, pw - 10, ph - 10, 5); + ctx.lineWidth = 1.5; + ctx.strokeStyle = '#c9a24a'; + ctx.stroke(); + hatch(ctx, px, py, pw, ph); + + const cx = CW / 2; + if (rank === 'K') crown(ctx, cx, 86, 62, 34, 5, color); + else if (rank === 'Q') crown(ctx, cx, 88, 50, 28, 3, color); + else jackCap(ctx, cx, 84, color); + + ctx.font = `bold 84px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.lineWidth = 3; + ctx.strokeStyle = '#c9a24a'; + ctx.strokeText(rank, cx, 150); + ctx.fillStyle = color; + ctx.fillText(rank, cx, 150); + + drawSuit(ctx, suit, cx, 204, 30, color); + drawSuit(ctx, suit, px + 16, py + 18, 16, color); + ctx.save(); + ctx.translate(px + pw - 16, py + ph - 18); + ctx.rotate(Math.PI); + drawSuit(ctx, suit, 0, 0, 16, color); + ctx.restore(); +} + +// Joker — an original jester's cap with bells over a ruffled collar. +function drawJoker(ctx) { + cardBase(ctx, 0, 0); + const PURPLE = '#5b2a86', GOLD = '#d4a017'; + const stackIndex = () => { + ctx.fillStyle = PURPLE; + ctx.font = `bold 22px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + [...'JOKER'].forEach((ch, i) => ctx.fillText(ch, 22, 26 + i * 22)); + }; + stackIndex(); + ctx.save(); + ctx.translate(CW, CH); + ctx.rotate(Math.PI); + stackIndex(); + ctx.restore(); + + const { px, py, pw, ph } = courtPanel(ctx); + ctx.lineWidth = 3; + ctx.strokeStyle = PURPLE; + ctx.stroke(); + hatch(ctx, px, py, pw, ph); + + const cx = CW / 2, base = 150; + // three floppy points of the cap + const tips = [{ x: cx - 46, y: 74, c: RED }, { x: cx, y: 56, c: PURPLE }, { x: cx + 46, y: 74, c: '#1f7a3a' }]; + for (const t of tips) { + ctx.beginPath(); + ctx.moveTo(cx - 30, base); + ctx.quadraticCurveTo((t.x + cx) / 2 - 8, t.y + 20, t.x, t.y); + ctx.quadraticCurveTo((t.x + cx) / 2 + 14, t.y + 34, cx + 30, base); + ctx.closePath(); + ctx.fillStyle = t.c; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.35)'; + ctx.stroke(); + } + for (const t of tips) { + ctx.beginPath(); + ctx.arc(t.x, t.y, 7, 0, Math.PI * 2); + ctx.fillStyle = GOLD; + ctx.fill(); + ctx.strokeStyle = '#7c5a12'; + ctx.lineWidth = 1.5; + ctx.stroke(); + } + // band + ruffled collar + ctx.fillStyle = GOLD; + ctx.fillRect(cx - 34, base - 4, 68, 10); + for (let i = 0; i < 6; i++) { + ctx.beginPath(); + ctx.arc(cx - 30 + i * 12, base + 16, 8, 0, Math.PI); + ctx.fillStyle = i % 2 ? '#f6ecd3' : '#e7d3a5'; + ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.25)'; + ctx.stroke(); + } + // ribbon + rr(ctx, cx - 52, 190, 104, 26, 6); + ctx.fillStyle = PURPLE; + ctx.fill(); + ctx.font = `bold 18px ${SERIF}`; + ctx.fillStyle = '#f5d76e'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText('JOKER', cx, 204); +} + +function drawCardFace(ctx, rank, suit) { + const color = suit === 'h' || suit === 'd' ? RED : BLACK; + const label = rank === 'T' ? '10' : rank; + cardBase(ctx, 0, 0); + cornerIndex(ctx, label, suit, color); + ctx.save(); + ctx.translate(CW, CH); + ctx.rotate(Math.PI); + cornerIndex(ctx, label, suit, color); + ctx.restore(); + + if (rank === 'A') { + const big = suit === 's' ? 112 : 92; + if (suit === 's') { + ctx.beginPath(); + ctx.arc(CW / 2, CH / 2, 72, 0, Math.PI * 2); + ctx.lineWidth = 2; ctx.strokeStyle = '#c9a24a'; ctx.stroke(); + ctx.beginPath(); + ctx.arc(CW / 2, CH / 2, 66, 0, Math.PI * 2); + ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.stroke(); + } + drawSuit(ctx, suit, CW / 2, CH / 2, big, color); + return; + } + if (rank === 'J' || rank === 'Q' || rank === 'K') { drawCourt(ctx, rank, suit, color); return; } + + const n = rank === 'T' ? 10 : Number(rank); + for (const [fx, fy] of PIPS[n]) { + const x = fx * CW, y = fy * CH; + if (fy > 0.5) { + ctx.save(); ctx.translate(x, y); ctx.rotate(Math.PI); + drawSuit(ctx, suit, 0, 0, 42, color); + ctx.restore(); + } else { + drawSuit(ctx, suit, x, y, 42, color); + } + } +} + +function drawCardBack(ctx, x, y, base) { + rr(ctx, x + 1, y + 1, CW - 2, CH - 2, CR); + const g = ctx.createLinearGradient(x, y, x + CW, y + CH); + g.addColorStop(0, mix(base, '#ffffff', 0.12)); + g.addColorStop(1, mix(base, '#000000', 0.25)); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(0,0,0,0.4)'; ctx.stroke(); + + rr(ctx, x + 10, y + 10, CW - 20, CH - 20, CR - 6); + ctx.lineWidth = 4; ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.stroke(); + + ctx.save(); + rr(ctx, x + 16, y + 16, CW - 32, CH - 32, CR - 8); + ctx.clip(); + ctx.strokeStyle = 'rgba(255,255,255,0.16)'; + ctx.lineWidth = 2; + for (let k = -CH; k < CW + CH; k += 13) { + ctx.beginPath(); ctx.moveTo(x + k, y); ctx.lineTo(x + k + CH, y + CH); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x + k, y + CH); ctx.lineTo(x + k + CH, y); ctx.stroke(); + } + ctx.restore(); + + const cx = x + CW / 2, cy = y + CH / 2; + ctx.beginPath(); ctx.arc(cx, cy, 30, 0, Math.PI * 2); + ctx.fillStyle = mix(base, '#000000', 0.35); ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = '#d9b45a'; ctx.stroke(); + drawSuit(ctx, 's', cx, cy, 32, '#d9b45a'); +} + +function bakeCards(scene) { + const GAP = 4; + const c = canvas(13 * (CW + GAP), 5 * (CH + GAP)); + const ctx = c.getContext('2d'); + const frames = []; + SUITS.forEach((suit, row) => { + RANKS.forEach((rank, col) => { + const fx = col * (CW + GAP), fy = row * (CH + GAP); + ctx.save(); + ctx.translate(fx, fy); + drawCardFace(ctx, rank, suit); + ctx.restore(); + frames.push([`${rank}${suit}`, fx, fy]); + }); + }); + const jy = 4 * (CH + GAP); + ctx.save(); + ctx.translate(0, jy); + drawJoker(ctx); + ctx.restore(); + frames.push(['JK', 0, jy]); + const tex = scene.textures.addCanvas('casino-cards', c); + for (const [name, fx, fy] of frames) tex.add(name, 0, fx, fy, CW, CH); +} + +function bakeCardShadow(scene) { + const c = canvas(CW + SHADOW_PAD * 2, CH + SHADOW_PAD * 2); + const ctx = c.getContext('2d'); + const OFF = 4000; + ctx.shadowColor = 'rgba(0,0,0,0.75)'; + ctx.shadowBlur = 20; + ctx.shadowOffsetX = OFF; + rr(ctx, SHADOW_PAD - OFF, SHADOW_PAD, CW, CH, CR); + ctx.fillStyle = '#000'; + ctx.fill(); + scene.textures.addCanvas('casino-card-shadow', c); +} + +// ── Dice ───────────────────────────────────────────────────────────────────── +export const DIE_PX = 64; +const DIE_PIPS = { + 1: [[0.5, 0.5]], + 2: [[0.27, 0.27], [0.73, 0.73]], + 3: [[0.27, 0.27], [0.5, 0.5], [0.73, 0.73]], + 4: [[0.27, 0.27], [0.73, 0.27], [0.27, 0.73], [0.73, 0.73]], + 5: [[0.27, 0.27], [0.73, 0.27], [0.5, 0.5], [0.27, 0.73], [0.73, 0.73]], + 6: [[0.27, 0.25], [0.73, 0.25], [0.27, 0.5], [0.73, 0.5], [0.27, 0.75], [0.73, 0.75]], +}; + +function ensureDiceArt(scene) { + for (let n = 1; n <= 6; n++) { + const key = `casino-die-${n}`; + if (scene.textures.exists(key)) continue; + const c = canvas(DIE_PX, DIE_PX); + const ctx = c.getContext('2d'); + rr(ctx, 2, 2, DIE_PX - 4, DIE_PX - 4, 11); + const g = ctx.createLinearGradient(0, 0, DIE_PX, DIE_PX); + g.addColorStop(0, '#e2333c'); + g.addColorStop(1, '#8e0f17'); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; + ctx.stroke(); + ctx.fillStyle = 'rgba(255,255,255,0.18)'; + rr(ctx, 7, 6, DIE_PX - 24, 12, 6); + ctx.fill(); + for (const [fx, fy] of DIE_PIPS[n]) { + ctx.beginPath(); + ctx.arc(fx * DIE_PX, fy * DIE_PX, 5.6, 0, Math.PI * 2); + ctx.fillStyle = '#fdf6e6'; + ctx.fill(); + } + scene.textures.addCanvas(key, c); + } + if (!scene.textures.exists('casino-dice-cup')) { + const w = 120, h = 130; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(18, 22); ctx.lineTo(w - 18, 22); ctx.lineTo(w - 30, h - 16); ctx.lineTo(30, h - 16); ctx.closePath(); + const g = ctx.createLinearGradient(0, 0, w, 0); + g.addColorStop(0, '#1d0f08'); + g.addColorStop(0.4, '#5a3522'); + g.addColorStop(1, '#140a05'); + ctx.fillStyle = g; + ctx.fill(); + ctx.beginPath(); ctx.ellipse(w / 2, h - 16, w / 2 - 30, 9, 0, 0, Math.PI); ctx.fillStyle = '#140a05'; ctx.fill(); + ctx.beginPath(); ctx.ellipse(w / 2, 22, w / 2 - 18, 12, 0, 0, Math.PI * 2); + ctx.fillStyle = '#0a0503'; ctx.fill(); + ctx.lineWidth = 4; ctx.strokeStyle = '#c9a24a'; ctx.stroke(); + ctx.setLineDash([5, 4]); + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(214,174,120,0.55)'; + ctx.beginPath(); ctx.moveTo(24, 40); ctx.lineTo(w - 24, 40); ctx.stroke(); + ctx.setLineDash([]); + scene.textures.addCanvas('casino-dice-cup', c); + } +} + +// ── Table ──────────────────────────────────────────────────────────────────── +const LEATHER_DARK = '#0f0806'; +const LEATHER_MID = '#2c1a12'; +const LEATHER_HI = '#5e3e2b'; + +function railProfile(f) { + // padded cylinder lit from above-front: bright ridge a little inboard of centre + const ridge = Math.max(0, Math.cos((f - 0.42) * Math.PI * 1.05)); + const c1 = mix(LEATHER_DARK, LEATHER_MID, Math.min(1, ridge * 1.4)); + return ridge > 0.72 ? mix(LEATHER_MID, LEATHER_HI, (ridge - 0.72) / 0.28) : c1; +} + +function drawRailFace(ctx) { + const top = arcPoints(RAIL_OUT, 160); + const bottom = top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s })); + poly(ctx, [...top, ...bottom.reverse()]); + ctx.fillStyle = LEATHER_DARK; + ctx.fill(); + ctx.save(); + ctx.clip(); + const steps = 14; + for (let i = 0; i <= steps; i++) { + const f = i / steps; + const pts = top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f })); + poly(ctx, pts, false); + ctx.lineWidth = 4; + ctx.strokeStyle = mix(LEATHER_MID, LEATHER_DARK, Math.min(1, f * 1.25)); + ctx.stroke(); + } + ctx.restore(); + poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s })), false); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.8)'; + ctx.stroke(); +} + +function drawRailTop(ctx) { + const outer = arcPoints(RAIL_OUT, 160); + const inner = arcPoints(RAIL_IN, 160); + poly(ctx, [...outer, ...inner.slice().reverse()]); + ctx.fillStyle = LEATHER_MID; + ctx.fill(); + ctx.save(); + ctx.clip(); + const steps = 26; + for (let i = 0; i <= steps; i++) { + const f = i / steps; + poly(ctx, arcPoints(lerp(RAIL_IN, RAIL_OUT, f), 160), false); + ctx.lineWidth = 6; + ctx.strokeStyle = railProfile(f); + ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 128, 26); + ctx.fillRect(0, 0, W, H); + poly(ctx, arcPoints(lerp(RAIL_IN, RAIL_OUT, 0.4), 160), false); + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(255,230,200,0.13)'; + ctx.stroke(); + ctx.setLineDash([7, 5]); + for (const f of [0.1, 0.9]) { + poly(ctx, arcPoints(lerp(RAIL_IN, RAIL_OUT, f), 160), false); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(214,174,120,0.42)'; + ctx.stroke(); + } + ctx.setLineDash([]); + ctx.restore(); +} + +function drawWood(ctx) { + const outer = arcPoints(RAIL_IN, 160); + const inner = arcPoints(FELT_R, 160); + poly(ctx, [...outer, ...inner.slice().reverse()]); + ctx.fillStyle = '#7a4520'; + ctx.fill(); + poly(ctx, arcPoints(lerp(FELT_R, RAIL_IN, 0.45), 160), false); + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(214,150,80,0.55)'; + ctx.stroke(); + poly(ctx, inner, false); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; + ctx.stroke(); + + const a = project(-RAIL_OUT, 0), b = project(RAIL_OUT, 0); + const c = project(RAIL_OUT, -0.04), d = project(-RAIL_OUT, -0.04); + poly(ctx, [a, b, c, d]); + const g = ctx.createLinearGradient(0, d.y, 0, a.y); + g.addColorStop(0, '#9b5f2a'); + g.addColorStop(0.5, '#6e3d1a'); + g.addColorStop(1, '#3e200c'); + ctx.fillStyle = g; + ctx.fill(); + ctx.beginPath(); ctx.moveTo(d.x, d.y); ctx.lineTo(c.x, c.y); + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(255,210,150,0.45)'; ctx.stroke(); +} + +function drawFelt(ctx, spec) { + ctx.save(); + poly(ctx, arcPoints(FELT_R, 160)); + ctx.clip(); + ctx.fillStyle = spec.felt ?? '#0d5a2c'; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 256, 22); + ctx.fillRect(0, 0, W, H); + + spec.markings?.(ctx); + for (const t of spec.text ?? []) drawArcText(ctx, t); + + const c = project(0, 0.45); + const lamp = ctx.createRadialGradient(c.x, c.y, 40, c.x, c.y, 900); + lamp.addColorStop(0, 'rgba(255,248,210,0.20)'); + lamp.addColorStop(0.45, 'rgba(255,248,210,0.07)'); + lamp.addColorStop(1, 'rgba(255,248,210,0)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); + const vig = ctx.createRadialGradient(c.x, c.y, 380, c.x, c.y, 1050); + vig.addColorStop(0, 'rgba(0,0,0,0)'); + vig.addColorStop(1, 'rgba(0,0,0,0.5)'); + ctx.fillStyle = vig; + ctx.fillRect(0, 0, W, H); + + for (let i = 0; i < 10; i++) { + poly(ctx, arcPoints(FELT_R - i * 0.004, 160), false); + ctx.lineWidth = 4; + ctx.strokeStyle = `rgba(0,0,0,${0.32 * (1 - i / 10)})`; + ctx.stroke(); + } + const e = ctx.createLinearGradient(0, VIEW.yFar, 0, VIEW.yFar + 18); + e.addColorStop(0, 'rgba(0,0,0,0.4)'); + e.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = e; + ctx.fillRect(0, VIEW.yFar, W, 18); + ctx.restore(); +} + +const DEFAULT_TRAY_COLS = [1, 5, 25, 50, 100, 100, 50, 25, 5, 1]; + +function drawTray(ctx, tray, cols = DEFAULT_TRAY_COLS) { + const pad = 0.012; + const frame = [ + project(tray.u0 - pad, tray.v0 - 0.006), project(tray.u1 + pad, tray.v0 - 0.006), + project(tray.u1 + pad, tray.v1 + pad), project(tray.u0 - pad, tray.v1 + pad), + ]; + poly(ctx, frame); + ctx.fillStyle = '#17110c'; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(214,174,120,0.5)'; + ctx.stroke(); + + const n = cols.length; + const gap = 0.006; + const colW = (tray.u1 - tray.u0 - gap * (n - 1)) / n; + cols.forEach((denom, i) => { + const def = CHIP_DEFS[denom]; + const ua = tray.u0 + i * (colW + gap), ub = ua + colW; + const tl = project(ua, tray.v0), tr = project(ub, tray.v0); + const bl = project(ua, tray.v1), br = project(ub, tray.v1); + const stripes = 9; + for (let k = 0; k < stripes; k++) { + const f0 = k / stripes, f1 = (k + 0.82) / stripes; + const q = [ + { x: lerp(tl.x, bl.x, f0), y: lerp(tl.y, bl.y, f0) }, + { x: lerp(tr.x, br.x, f0), y: lerp(tr.y, br.y, f0) }, + { x: lerp(tr.x, br.x, f1), y: lerp(tr.y, br.y, f1) }, + { x: lerp(tl.x, bl.x, f1), y: lerp(tl.y, bl.y, f1) }, + ]; + poly(ctx, q); + ctx.fillStyle = k % 2 ? def.base : mix(def.base, '#000000', 0.15); + ctx.fill(); + if (k % 3 === 1) { + const mx = (q[0].x + q[1].x) / 2, my = (q[0].y + q[3].y) / 2; + ctx.fillStyle = def.insert; + ctx.fillRect(mx - 2, my - 1, 4, 2); + } + } + const g = ctx.createLinearGradient(tl.x, 0, tr.x, 0); + g.addColorStop(0, 'rgba(0,0,0,0.55)'); + g.addColorStop(0.4, 'rgba(255,255,255,0.18)'); + g.addColorStop(1, 'rgba(0,0,0,0.55)'); + poly(ctx, [tl, tr, br, bl]); + ctx.fillStyle = g; + ctx.fill(); + }); +} + +function drawShoe(ctx, spot) { + const p = project(spot.u, spot.v); + const s = p.s; + const w = 132 * s, d = 54 * s, h = 30 * s; + const x0 = p.x - w / 2, y0 = p.y - d / 2; + + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; + ctx.shadowBlur = 14; + ctx.shadowOffsetY = 8; + ctx.fillStyle = '#000'; + ctx.fillRect(x0 + 4, y0 + 6, w - 8, d + h - 8); + ctx.restore(); + + const fg = ctx.createLinearGradient(0, y0 + d, 0, y0 + d + h); + fg.addColorStop(0, '#3d0b10'); + fg.addColorStop(1, '#1c0407'); + ctx.fillStyle = fg; + ctx.fillRect(x0, y0 + d, w, h); + const tg = ctx.createLinearGradient(x0, y0, x0, y0 + d); + tg.addColorStop(0, '#6b1720'); + tg.addColorStop(1, '#4a0e15'); + ctx.fillStyle = tg; + ctx.fillRect(x0, y0, w, d); + ctx.fillStyle = '#ede4cf'; + ctx.fillRect(x0 + 26 * s, y0 + 10 * s, w - 40 * s, d - 20 * s); + ctx.strokeStyle = 'rgba(0,0,0,0.18)'; + ctx.lineWidth = 1; + for (let k = 0; k < 18; k++) { + const yy = y0 + 10 * s + ((d - 20 * s) * k) / 18; + ctx.beginPath(); ctx.moveTo(x0 + 26 * s, yy); ctx.lineTo(x0 + w - 14 * s, yy); ctx.stroke(); + } + ctx.fillStyle = '#2a070b'; + ctx.fillRect(x0 + w - 22 * s, y0 + 6 * s, 14 * s, d - 12 * s); + ctx.fillStyle = '#1a3a6b'; + ctx.fillRect(x0 - 6 * s, y0 + 12 * s, 30 * s, d - 24 * s); + ctx.strokeStyle = 'rgba(255,255,255,0.8)'; + ctx.lineWidth = 1.5; + ctx.strokeRect(x0 - 3 * s, y0 + 15 * s, 24 * s, d - 30 * s); + ctx.fillStyle = 'rgba(30,8,10,0.85)'; + ctx.beginPath(); + ctx.moveTo(x0, y0); ctx.lineTo(x0 + 20 * s, y0); ctx.lineTo(x0 + 20 * s, y0 + d + h); + ctx.lineTo(x0 - 10 * s, y0 + d + h); ctx.closePath(); + ctx.fill(); + ctx.beginPath(); + ctx.arc(x0 + 6 * s, y0 + d / 2, 7 * s, 0, Math.PI * 2); + ctx.fillStyle = '#0d0204'; + ctx.fill(); + ctx.strokeStyle = 'rgba(255,200,200,0.35)'; + ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(x0 + 2, y0 + 1); ctx.lineTo(x0 + w - 2, y0 + 1); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,255,255,0.12)'; + ctx.beginPath(); ctx.moveTo(x0, y0 + d); ctx.lineTo(x0 + w, y0 + d); ctx.stroke(); +} + +function drawDiscard(ctx, spot) { + const p = project(spot.u, spot.v); + const s = p.s; + const w = 108 * s, d = 48 * s, h = 26 * s; + const x0 = p.x - w / 2, y0 = p.y - d / 2; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.5)'; + ctx.shadowBlur = 12; + ctx.shadowOffsetY = 6; + ctx.fillStyle = 'rgba(0,0,0,0.6)'; + ctx.fillRect(x0 + 4, y0 + 6, w - 8, d + h - 8); + ctx.restore(); + ctx.fillStyle = '#e8dfc9'; + ctx.fillRect(x0 + 10 * s, y0 + d - 16 * s, w - 20 * s, 14 * s); + ctx.strokeStyle = 'rgba(0,0,0,0.2)'; + for (let k = 0; k < 6; k++) { + const yy = y0 + d - 16 * s + k * 2.4 * s; + ctx.beginPath(); ctx.moveTo(x0 + 10 * s, yy); ctx.lineTo(x0 + w - 10 * s, yy); ctx.stroke(); + } + ctx.fillStyle = 'rgba(40,40,48,0.42)'; + ctx.fillRect(x0, y0, w, d); + ctx.fillStyle = 'rgba(20,20,26,0.7)'; + ctx.fillRect(x0, y0 + d, w, h); + ctx.strokeStyle = 'rgba(255,255,255,0.3)'; + ctx.lineWidth = 1.5; + ctx.strokeRect(x0, y0, w, d + h); + ctx.beginPath(); ctx.moveTo(x0, y0 + d); ctx.lineTo(x0 + w, y0 + d); ctx.stroke(); +} + +function drawPlacard(ctx, spot) { + const p = project(spot.u, spot.v); + const s = p.s; + const w = 104 * s, h = 54 * s; + const x0 = p.x - w / 2, yb = p.y; + const [line1 = 'TABLE LIMITS', line2 = ''] = spot.lines ?? []; + ctx.fillStyle = '#111'; + ctx.fillRect(x0 + 8 * s, yb - 5 * s, w - 16 * s, 8 * s); + rr(ctx, x0, yb - h - 4 * s, w, h, 5 * s); + const g = ctx.createLinearGradient(0, yb - h, 0, yb); + g.addColorStop(0, '#1d1913'); + g.addColorStop(1, '#0a0806'); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = '#c9a24a'; + ctx.stroke(); + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#d9b45a'; + ctx.font = `${Math.round(11 * s * 1.3)}px "Julius Sans One", sans-serif`; + ctx.fillText(line1, p.x, yb - h + 12 * s); + ctx.fillStyle = '#f2ead8'; + ctx.font = `bold ${Math.round(17 * s * 1.3)}px "Julius Sans One", sans-serif`; + ctx.fillText(line2, p.x, yb - h + 33 * s); +} + +/** + * Bake a full-screen half-moon table. + * spec = { + * felt: '#0d5a2c', felt base colour + * markings(ctx), game markings, drawn on the felt (clipped) before the lighting + * text: [arc text specs], felt lettering (see drawArcText) + * tray: {u0,u1,v0,v1}|null, trayCols: [denoms] + * shoe, discard: {u,v}|null + * placard: {u, v, lines: [small, big]}|null + * extras(ctx) anything else drawn on top (unclipped) + * } + */ +export function bakeCasinoTable(scene, key, spec) { + if (scene.textures.exists(key)) return; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + + const outline = arcPoints(RAIL_OUT, 120).map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s })); + const back = [project(RAIL_OUT, -0.04), project(-RAIL_OUT, -0.04)]; + const OFF = 6000; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.7)'; + ctx.shadowBlur = 60; + ctx.shadowOffsetX = OFF; + ctx.shadowOffsetY = 26; + poly(ctx, [...outline, ...back].map(p => ({ x: p.x - OFF, y: p.y }))); + ctx.fillStyle = '#000'; + ctx.fill(); + ctx.restore(); + + drawRailFace(ctx); + drawWood(ctx); + drawRailTop(ctx); + drawFelt(ctx, spec); + if (spec.tray) drawTray(ctx, spec.tray, spec.trayCols); + if (spec.discard) drawDiscard(ctx, spec.discard); + if (spec.shoe) drawShoe(ctx, spec.shoe); + if (spec.placard) drawPlacard(ctx, spec.placard); + spec.extras?.(ctx); + + scene.textures.addCanvas(key, c); +} + +// ── HUD dock ───────────────────────────────────────────────────────────────── +function bakeDock(scene) { + const c = canvas(W, DOCK.h); + const ctx = c.getContext('2d'); + const g = ctx.createLinearGradient(0, 0, 0, DOCK.h); + g.addColorStop(0, '#22160f'); + g.addColorStop(1, '#0b0705'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, DOCK.h); + ctx.fillStyle = noisePattern(ctx, 128, 20); + ctx.fillRect(0, 0, W, DOCK.h); + const wg = ctx.createLinearGradient(0, 0, 0, 10); + wg.addColorStop(0, '#a8692f'); + wg.addColorStop(1, '#4e2a10'); + ctx.fillStyle = wg; + ctx.fillRect(0, 0, W, 10); + ctx.fillStyle = 'rgba(200,168,75,0.9)'; + ctx.fillRect(0, 10, W, 1.5); + ctx.setLineDash([7, 5]); + ctx.strokeStyle = 'rgba(214,174,120,0.3)'; + ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(0, 18); ctx.lineTo(W, 18); ctx.stroke(); + ctx.setLineDash([]); + scene.textures.addCanvas('casino-dock', c); +} + +// A leather panel texture of any size (setting tray, close-up panels). +export function ensureLeatherPanel(scene, key, w, h, { radius = 18, felt = null } = {}) { + if (scene.textures.exists(key)) return key; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + rr(ctx, 2, 2, w - 4, h - 4, radius); + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, '#24170f'); + g.addColorStop(1, '#0c0705'); + ctx.fillStyle = g; + ctx.fill(); + ctx.save(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 128, 20); + ctx.fillRect(0, 0, w, h); + if (felt) { + rr(ctx, 16, 16, w - 32, h - 32, radius - 6); + ctx.fillStyle = felt; + ctx.fill(); + ctx.fillStyle = noisePattern(ctx, 128, 22); + ctx.fill(); + const v = ctx.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.2, w / 2, h / 2, Math.max(w, h) * 0.7); + v.addColorStop(0, 'rgba(255,248,210,0.08)'); + v.addColorStop(1, 'rgba(0,0,0,0.45)'); + ctx.fillStyle = v; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.6)'; + ctx.stroke(); + } + ctx.restore(); + rr(ctx, 2, 2, w - 4, h - 4, radius); + ctx.lineWidth = 3; + ctx.strokeStyle = '#c8a84b'; + ctx.stroke(); + ctx.setLineDash([7, 5]); + rr(ctx, 8, 8, w - 16, h - 16, radius - 4); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(214,174,120,0.35)'; + ctx.stroke(); + ctx.setLineDash([]); + scene.textures.addCanvas(key, c); + return key; +} diff --git a/src/ui/casino/CasinoCards.js b/src/ui/casino/CasinoCards.js new file mode 100644 index 0000000..fb41052 --- /dev/null +++ b/src/ui/casino/CasinoCards.js @@ -0,0 +1,184 @@ +// Shared casino card sprites: a card is a Container [shadow, face] scaled by its +// perspective pose (s, s × squash). Flights, flips and the baccarat squeeze all +// animate that container. + +import { VIEW } from './CasinoGeometry.js'; +import { CARD_W, CARD_H, ensureCardBack } from './CasinoArt.js'; + +const SQ = VIEW.squash; +const lerp = (a, b, t) => a + (b - a) * t; + +// Deterministic per-card jitter so cards look tossed but don't wobble on relayout. +export function jitterFor(key) { + let h = 2166136261; + for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619); + const r = (n) => (((h >>> n) & 255) / 255) * 2 - 1; + return { rot: r(0) * 0.035, x: r(8) * 2, y: r(16) * 2 }; +} + +export function withJitter(pose, key) { + const j = jitterFor(key); + return { ...pose, x: pose.x + j.x, y: pose.y + j.y, rot: pose.rot + j.rot }; +} + +// The card skin knows which back to show (player's chosen sprite-sheet back, or +// a baked fallback in their colour). Call after prepareCasinoArt(). +export class CardSkin { + constructor(scene, cardBack, { depth = 10 } = {}) { + this.scene = scene; + this.cardBack = cardBack ?? null; + this.backKey = ensureCardBack(scene, cardBack?.fallbackColor); + this.depth = depth; + } + + make(card, faceUp, x, y, s, rot = 0) { + const scene = this.scene; + const c = scene.add.container(x, y).setDepth(this.depth); + const sh = scene.add.image(5, 8, 'casino-card-shadow').setScale(0.5).setAlpha(0.6); + const back = scene.add.image(0, 0, this.backKey); + c.add([sh, back]); + c.shadowImg = sh; + c.faceImg = back; + c.card = card; + this.setFace(c, faceUp); + c.setRotation(rot); + c.setScale(s, s * SQ); + return c; + } + + setFace(c, faceUp) { + c.faceUp = faceUp; + if (faceUp && c.card) { + c.faceImg.setTexture('casino-cards', c.card.key).setScale(0.5); + } else { + this.applyBack(c.faceImg); + } + } + + applyBack(img) { + if (this.cardBack?.spriteIndex !== undefined && this.scene.textures.exists('cardbacks')) { + img.setTexture('cardbacks', this.cardBack.spriteIndex).setDisplaySize(CARD_W, CARD_H); + } else { + img.setTexture(this.backKey).setScale(0.5); + } + } + + // A card flies from `from` to `pose` with a lift, flipping face-up mid-air if asked. + // Resolves with the container once it has landed. + deal(card, faceUp, from, pose, { duration = 320, flyingDepth = this.depth + 12, sound } = {}) { + const scene = this.scene; + const c = this.make(card, false, from.x, from.y, from.s, -0.3); + c.setDepth(flyingDepth); + c.flying = true; + const prox = { t: 0 }; + let flipped = false; + const promise = new Promise(res => { + scene.tweens.add({ + targets: prox, t: 1, duration, ease: 'Cubic.easeOut', + onUpdate: () => { + const t = prox.t; + const lift = Math.sin(Math.PI * t); + c.x = lerp(from.x, pose.x, t); + c.y = lerp(from.y, pose.y, t) - lift * 22; + c.rotation = lerp(-0.3, pose.rot, t); + const s = lerp(from.s, pose.s, t) * (1 + 0.09 * lift); + let sx = s; + if (faceUp) { + if (!flipped && t >= 0.5) { flipped = true; this.setFace(c, true); } + sx = s * Math.max(0.03, Math.abs(Math.cos(Math.PI * t))); + } + c.setScale(sx, s * SQ); + c.shadowImg.setPosition(5 + lift * 16, 8 + lift * 26).setAlpha(0.6 - lift * 0.3); + }, + onComplete: () => { + c.flying = false; + c.setDepth(this.depth); + if (faceUp && !flipped) this.setFace(c, true); + c.setPosition(pose.x, pose.y).setRotation(pose.rot).setScale(pose.s, pose.s * SQ); + c.shadowImg.setPosition(5, 8).setAlpha(0.6); + if (sound) sound(); + res(c); + }, + }); + }); + return { c, promise }; + } + + // Flip in place with a small lift. + flip(c, faceUp, duration = 300) { + const scene = this.scene; + const base = { x: c.scaleX, y: c.scaleY, py: c.y }; + const prox = { t: 0 }; + let flipped = false; + return new Promise(res => { + scene.tweens.add({ + targets: prox, t: 1, duration, ease: 'Sine.easeInOut', + onUpdate: () => { + const t = prox.t; + const lift = Math.sin(Math.PI * t); + if (!flipped && t >= 0.5) { flipped = true; this.setFace(c, faceUp); } + c.setScale(base.x * Math.max(0.03, Math.abs(Math.cos(Math.PI * t))) * (1 + 0.08 * lift), base.y * (1 + 0.08 * lift)); + c.y = base.py - lift * 14; + c.shadowImg.setPosition(5 + lift * 10, 8 + lift * 18).setAlpha(0.6 - lift * 0.25); + }, + onComplete: () => { + if (!flipped) this.setFace(c, faceUp); + c.setScale(base.x, base.y); + c.y = base.py; + c.shadowImg.setPosition(5, 8).setAlpha(0.6); + res(); + }, + }); + }); + } + + // Baccarat squeeze: the card lifts and grows a little, then the back peels away + // from the bottom edge (face showing underneath) — a slow corner peek, a beat, + // then the full peel. A pale "fold" strip rides the peel edge. + async peel(c, { lift = 1.32, peekMs = 650, holdMs = 450, peelMs = 700, onPeek } = {}) { + const scene = this.scene; + const base = { sx: c.scaleX, sy: c.scaleY, y: c.y, depth: c.depth }; + c.setDepth(base.depth + 20); + await new Promise(res => scene.tweens.add({ + targets: c, scaleX: base.sx * lift, scaleY: base.sy * lift, y: base.y - 18, + duration: 220, ease: 'Cubic.easeOut', onComplete: res, + })); + + // Face image underneath the back. + const face = scene.add.image(0, 0, 'casino-cards', c.card.key).setScale(0.5); + c.addAt(face, 1); + const back = c.faceImg; + const fold = scene.add.rectangle(0, 0, CARD_W, 8, 0xfffbef, 0.9); + c.add(fold); + const fw = back.frame.realWidth, fh = back.frame.realHeight; + const dispH = back.displayHeight; + const setPeel = (f) => { + // f = fraction of the card uncovered, from the bottom edge up + back.setCrop(0, 0, fw, fh * (1 - f)); + fold.setPosition(0, CARD_H / 2 - f * dispH + 3).setAlpha(f > 0.001 && f < 0.999 ? 0.85 : 0); + }; + setPeel(0); + const prox = { f: 0 }; + await new Promise(res => scene.tweens.add({ + targets: prox, f: 0.26, duration: peekMs, ease: 'Sine.easeInOut', + onUpdate: () => setPeel(prox.f), onComplete: res, + })); + onPeek?.(); + await new Promise(res => scene.time.delayedCall(holdMs, res)); + await new Promise(res => scene.tweens.add({ + targets: prox, f: 1, duration: peelMs, ease: 'Cubic.easeIn', + onUpdate: () => setPeel(prox.f), onComplete: res, + })); + + // Swap to the regular single-image face and settle back onto the felt. + face.destroy(); + fold.destroy(); + back.setCrop(); + this.setFace(c, true); + await new Promise(res => scene.tweens.add({ + targets: c, scaleX: base.sx, scaleY: base.sy, y: base.y, + duration: 240, ease: 'Cubic.easeOut', onComplete: res, + })); + c.setDepth(base.depth); + } +} diff --git a/src/ui/casino/CasinoDock.js b/src/ui/casino/CasinoDock.js new file mode 100644 index 0000000..492baf7 --- /dev/null +++ b/src/ui/casino/CasinoDock.js @@ -0,0 +1,164 @@ +// Shared casino HUD dock: the leather strip along the bottom with the player's +// portrait + balance, the chip tray, a bet pill, a status line and a key legend. +// Games add their own buttons into named mode groups and switch with setMode(). + +import * as Phaser from 'phaser'; +import { COLORS } from '../../config.js'; +import { createPlayerPortrait } from '../Portrait.js'; +import { makeChip } from '../CasinoChips.js'; +import { DOCK } from './CasinoGeometry.js'; + +export class CasinoDock { + constructor(scene, { + sceneName, + portrait = { x: 160, y: 1013, r: 50 }, + depth = { dock: 26, ui: 30, dockUi: 32, prompt: 38 }, + chipAmounts = [5, 25, 50, 100], + chipX0 = 470, chipDX = 88, chipSize = 74, + betPillX = 850, + keys = {}, + canChip = () => true, + onChip = () => {}, + }) { + this.scene = scene; + this.depth = depth; + this.keys = keys; + this.y = DOCK.y + DOCK.h / 2; + this.groups = {}; + this.transient = []; + this.mode = null; + this.promptGroup = []; + this.promptTimer = null; + this.pulseTweens = []; + const y = this.y; + + this.bg = scene.add.image(0, DOCK.y, 'casino-dock').setOrigin(0, 0).setDepth(depth.dock); + + this.portrait = createPlayerPortrait(scene, portrait.x, portrait.y, portrait.r, depth.ui, sceneName); + this.portraitPos = portrait; + this.nameTxt = scene.add.text(portrait.x + portrait.r + 22, y - 18, 'You', { + fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(depth.dockUi); + this.balanceTxt = scene.add.text(portrait.x + portrait.r + 22, y + 14, '', { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.goldHex, fontStyle: 'bold', + }).setOrigin(0, 0.5).setDepth(depth.dockUi); + + // Chip tray — Images (not Containers) so the circular hit area is in texture space. + this.chipBtns = chipAmounts.map((amt, i) => { + const x = chipX0 + i * chipDX; + const sh = scene.add.ellipse(x + 3, y + 6, chipSize, chipSize, 0x000000, 0.5).setDepth(depth.dockUi); + const img = makeChip(scene, x, y, amt, { size: chipSize, depth: depth.dockUi + 1 }); + img.baseScale = img.scaleX; + img._dockReenable = true; + img.setInteractive({ + hitArea: new Phaser.Geom.Circle(64, 64, 62), + hitAreaCallback: Phaser.Geom.Circle.Contains, + useHandCursor: true, + }); + img.on('pointerover', () => { if (canChip(amt)) scene.tweens.add({ targets: img, y: y - 8, duration: 110 }); }); + img.on('pointerout', () => scene.tweens.add({ targets: img, y, duration: 110 })); + img.on('pointerdown', () => onChip(amt)); + return { amt, img, sh }; + }); + this.chipCenterX = chipX0 + (chipAmounts.length - 1) * chipDX / 2; + + this.betPill = scene.add.text(betPillX, y, '', { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(depth.dockUi); + + this.addToGroup('bet', ...this.chipBtns.flatMap(c => [c.sh, c.img]), this.betPill); + + this.statusTxt = scene.add.text(scene.scale.width / 2, y, '', { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(depth.dockUi); + this.keysTxt = scene.add.text(scene.scale.width / 2, DOCK.y + DOCK.h - 12, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(depth.dockUi).setAlpha(0.8); + } + + chipButton(denom) { return this.chipBtns.find(c => c.amt === denom); } + + // Where chips come from / return to for the human. + sourcePos() { return { x: this.balanceTxt.x + 40, y: this.balanceTxt.y, s: 1 }; } + + addToGroup(mode, ...objs) { + (this.groups[mode] ??= []).push(...objs); + for (const o of objs) { + const show = this.mode === mode; + o.setVisible(show); + if (!show) o.disableInteractive?.(); + } + } + + addTransient(...objs) { this.transient.push(...objs); } + + clearTransient() { + for (const o of this.transient) { + this.scene.tweens.killTweensOf(o); + o.destroy(); + } + this.transient = []; + } + + // Show `mode`'s group, hide the rest, clear transient widgets, set the status + // line (wait-style modes) and the key legend. + setMode(mode, status = '') { + this.mode = mode; + this.clearTransient(); + for (const [key, objs] of Object.entries(this.groups)) { + const show = key === mode; + for (const o of objs) { + o.setVisible(show); + if (!show) o.disableInteractive?.(); + else if (o._dockReenable) o.setInteractive(); + } + } + if (mode !== 'bet') this.hidePrompts(); + this.statusTxt.setText(status); + this.keysTxt.setText(this.keys[mode] ?? ''); + } + + setChipStates(affordable) { + for (const c of this.chipBtns) c.img.setAlpha(affordable(c.amt) ? 1 : 0.35); + } + + // After 5s with no bet, pulse the chips and show a hint above the dock. + startPrompts(message, stillIdle) { + this.hidePrompts(); + this.promptTimer = this.scene.time.delayedCall(5000, () => { + if (this.mode !== 'bet' || !stillIdle()) return; + this.chipBtns.forEach((c, index) => { + this.pulseTweens.push(this.scene.tweens.add({ + targets: c.img, scale: c.img.baseScale * 1.14, + duration: 1100, ease: 'Sine.easeInOut', yoyo: true, repeat: -1, delay: index * 180, + })); + }); + const scene = this.scene; + const cx = scene.scale.width / 2, y = DOCK.y - 34; + const msg = typeof message === 'function' ? message() : message; + const text = scene.add.text(cx, y, msg, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#ffffff', + }).setOrigin(0.5).setDepth(this.depth.prompt + 1).setAlpha(0); + const bg = scene.add.rectangle(cx, y, text.width + 48, 46, 0x000000, 0.75) + .setDepth(this.depth.prompt).setAlpha(0); + this.promptGroup = [bg, text]; + scene.tweens.add({ targets: this.promptGroup, alpha: 1, duration: 300, ease: 'Power2' }); + }); + } + + hidePrompts() { + const group = this.promptGroup; + this.promptGroup = []; + if (group.length) { + this.scene.tweens.add({ + targets: group, alpha: 0, duration: 200, ease: 'Power2', + onComplete: () => group.forEach(o => o.destroy()), + }); + } + this.pulseTweens.forEach(t => t.remove()); + this.pulseTweens = []; + this.chipBtns.forEach(c => c.img.setScale(c.img.baseScale)); + this.promptTimer?.remove(); + this.promptTimer = null; + } +} diff --git a/src/ui/casino/CasinoGeometry.js b/src/ui/casino/CasinoGeometry.js new file mode 100644 index 0000000..1de5f41 --- /dev/null +++ b/src/ui/casino/CasinoGeometry.js @@ -0,0 +1,122 @@ +// Shared casino-table geometry — Phaser-free so verify scripts can import it. +// +// Every half-moon casino table (Blackjack, Baccarat, Pai Gow) uses the SAME +// perspective: things on the felt are described in flat "table space" and +// pushed through project(). The dealer's straight edge is far away (small, +// narrow), the curved player rail near (large, wide). Cards, chips, betting +// spots and felt lettering all take their screen position AND scale from it. +// +// Table space: the felt is the half-disc u² + v² ≤ 1, v ≥ 0. +// u = left/right (−1 … +1), +u is screen-right +// v = depth from the dealer's straight edge (0) toward the players (1) +// polar(r, θ): θ = 0 points straight at the bottom-centre seat, +θ swings +// toward screen-right. + +export const VIEW = { + cx: 960, + yFar: 168, // screen y of the dealer's straight edge (v = 0) + yNear: 800, // screen y of the felt's nearest point (v = 1) + sFar: 0.70, // scale at the dealer edge (1.0 at the near point) + halfW: 905, // half-width in px of the unit circle at scale 1 + squash: 0.9, // extra vertical squash for things lying flat on the felt +}; + +const A = 1 / VIEW.sFar - 1; +const K = (VIEW.yNear - VIEW.yFar) / (1 - VIEW.sFar); +const Y_HORIZON = VIEW.yFar - VIEW.sFar * K; +const RAD = Math.PI / 180; + +export function depthScale(v) { + return 1 / (1 + A * (1 - v)); +} + +export function project(u, v) { + const s = depthScale(v); + return { x: VIEW.cx + u * VIEW.halfW * s, y: Y_HORIZON + K * s, s }; +} + +export function polar(r, thetaDeg) { + const t = thetaDeg * RAD; + return project(r * Math.sin(t), r * Math.cos(t)); +} + +// Inverse of project() for a screen point. +export function unproject(x, y) { + const s = (y - Y_HORIZON) / K; + const v = 1 - (1 / s - 1) / A; + const u = (x - VIEW.cx) / (VIEW.halfW * s); + return { u, v, s }; +} + +// Screen point → table-space polar (r, θ in degrees). Used for felt hit-testing. +export function toPolar(x, y) { + const { u, v } = unproject(x, y); + return { r: Math.hypot(u, v), theta: Math.atan2(u, v) / RAD, u, v }; +} + +// Screen-space angle (radians, Phaser convention: +ve = clockwise) of the arc of +// radius r at θ, travelling toward +θ. Used to rotate felt lettering. +export function arcTangent(r, thetaDeg) { + const a = polar(r, thetaDeg - 0.25); + const b = polar(r, thetaDeg + 0.25); + return Math.atan2(b.y - a.y, b.x - a.x); +} + +// Screen rotation that turns a card's bottom edge toward a seat at θ (radius r), +// damped so outer seats don't spin a full 90°. +export function radialRotation(r, thetaDeg, damp = 0.62) { + const a = polar(r, thetaDeg); + const b = polar(r + 0.05, thetaDeg); + return Math.atan2(-(b.x - a.x), b.y - a.y) * damp; +} + +// ── Rail / outline ─────────────────────────────────────────────────────────── +export const FELT_R = 0.985; // felt ends here, wood lip to 1.0 +export const RAIL_IN = 1.0; +export const RAIL_OUT = 1.105; +export const RAIL_FACE_PX = 34; // visible thickness of the rail's front face at s = 1 + +// Points along an arc of radius r from θ0 to θ1 (default the whole half-moon, left → right). +export function arcPoints(r, steps = 120, th0 = -90, th1 = 90) { + const pts = []; + for (let i = 0; i <= steps; i++) pts.push(polar(r, th0 + ((th1 - th0) * i) / steps)); + return pts; +} + +// Projected outline of a flat circle on the felt (bet circles, chip shadows). +export function feltCircle(u, v, radius, steps = 48) { + const pts = []; + for (let i = 0; i < steps; i++) { + const a = (i / steps) * Math.PI * 2; + pts.push(project(u + Math.cos(a) * radius, v + Math.sin(a) * radius)); + } + return pts; +} + +// Projected outline of an annular sector (a curved betting box) r0…r1, θ0…θ1. +export function feltSector(r0, r1, th0, th1, steps = 24) { + return [...arcPoints(r1, steps, th0, th1), ...arcPoints(r0, steps, th0, th1).reverse()]; +} + +// Projected outline of a flat rectangle centred at (u, v) with table-space size (w, h). +export function feltRect(u, v, w, h) { + return [ + project(u - w / 2, v - h / 2), project(u + w / 2, v - h / 2), + project(u + w / 2, v + h / 2), project(u - w / 2, v + h / 2), + ]; +} + +export function onFelt(u, v) { + return v >= 0 && u * u + v * v <= FELT_R * FELT_R; +} + +export function screenOnFelt(pt) { + const { u, v } = unproject(pt.x, pt.y); + return onFelt(u, v); +} + +// ── Shared furniture spots (games may override) ────────────────────────────── +export const TRAY = { u0: -0.26, u1: 0.26, v0: 0.012, v1: 0.078 }; + +// ── HUD dock ───────────────────────────────────────────────────────────────── +export const DOCK = { y: 948, h: 132 }; // top edge + height (to the bottom of the 1080 canvas) diff --git a/tools/verifyBaccarat.js b/tools/verifyBaccarat.js new file mode 100644 index 0000000..2d1b3be --- /dev/null +++ b/tools/verifyBaccarat.js @@ -0,0 +1,169 @@ +#!/usr/bin/env node +// verifyBaccarat.js — headless checks for the Baccarat table layout, felt +// hit-testing, payouts as chip stacks, and the scoreboard roads. + +import { readFileSync } from 'node:fs'; +import { BET, betPayout } from '../src/games/baccarat/BaccaratLogic.js'; +import { + VIEW, unproject, onFelt, SEAT_ANGLES, DISPLAY_ORDER, BANDS, BET_TYPES, BOX_HALF_DEG, + boxCenter, boxOutline, hitBox, seatPortrait, handCenter, handCardPose, handBoxRect, + SHOE, DISCARD, PLACARD, TRAY, DOCK, READOUT, BOARD, boardSize, FELT_TEXT, polar, project, + FELT_R, CARD_W, CARD_H, TOTAL_BADGE_DY, +} from '../src/games/baccarat/BaccaratTable.js'; +import { counts, beadPlate, bigRoad, bigRoadWindow } from '../src/games/baccarat/BaccaratRoads.js'; +import { breakdown } from '../src/ui/CasinoChips.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 onFeltPt = (p) => { const q = unproject(p.x, p.y); return onFelt(q.u, q.v); }; +const sum = (a) => a.reduce((x, y) => x + y, 0); +const inRect = (p, r) => p.x > r.x - r.w / 2 && p.x < r.x + r.w / 2 && p.y > r.y - r.h / 2 && p.y < r.y + r.h / 2; + +// ── Payouts → chips ────────────────────────────────────────────────────────── +section('Payouts'); +for (let bet = 5; bet <= 500; bet += 5) { + for (const outcome of ['player', 'banker', 'tie']) { + for (const type of BET_TYPES) { + const net = betPayout(type, bet, outcome); + if (net > 0) { + ok(`$${bet} ${type} on ${outcome}: payout stack sums`, sum(breakdown(net)) === net); + if (type === BET.BANKER) { + const commission = bet - net; + ok(`$${bet} banker: commission is 5% floored`, commission === Math.floor(bet * 0.05)); + ok(`$${bet} banker: gross stack = bet`, sum(breakdown(net + commission)) === bet); + } + if (type === BET.TIE) ok(`$${bet} tie pays 8:1`, net === bet * 8); + } + } + } +} +ok('player/banker push on a tie', betPayout(BET.PLAYER, 25, 'tie') === 0 && betPayout(BET.BANKER, 25, 'tie') === 0); + +// ── Betting boxes ──────────────────────────────────────────────────────────── +section('Betting boxes'); +ok('7 seats', SEAT_ANGLES.length === 7); +ok('display order covers every seat once', [...DISPLAY_ORDER].sort().join() === '0,1,2,3,4,5,6'); +const sorted = [...SEAT_ANGLES].sort((a, b) => a - b); +ok('neighbouring seats\' boxes don\'t overlap', + sorted.every((a, i) => i === 0 || a - sorted[i - 1] > 2 * BOX_HALF_DEG), sorted.join(',')); +ok('bands are disjoint, PLAYER outermost', + BANDS.player.r0 > BANDS.banker.r1 && BANDS.banker.r0 > BANDS.tie.r1); +ok('PLAYER band inside the felt', BANDS.player.r1 < FELT_R); +for (let seat = 0; seat < 7; seat++) { + for (const type of BET_TYPES) { + const c = boxCenter(seat, type); + const hit = hitBox(c.x, c.y); + ok(`seat ${seat} ${type}: centre hit-tests to itself`, hit && hit.seat === seat && hit.type === type, JSON.stringify(hit)); + ok(`seat ${seat} ${type}: outline on the felt`, boxOutline(seat, type).every(onFeltPt)); + const inner = boxOutline(seat, type, 0.01); + ok(`seat ${seat} ${type}: inset outline hit-tests to itself`, + inner.every(p => { const h = hitBox(p.x, p.y); return h && h.seat === seat && h.type === type; })); + ok(`seat ${seat} ${type}: stack well above the dock`, c.y + 40 < DOCK.y); + } +} +ok('gap between bands hits nothing', hitBox(polar((BANDS.banker.r1 + BANDS.player.r0) / 2, 0).x, polar((BANDS.banker.r1 + BANDS.player.r0) / 2, 0).y) === null); +ok('between seats hits nothing', hitBox(polar(0.9, 12.5).x, polar(0.9, 12.5).y) === null); +ok('the dealer row hits nothing', hitBox(handCenter('player').x, handCenter('player').y) === null); +ok('off the felt hits nothing', hitBox(960, 1050) === null && hitBox(960, 100) === null); + +// ── Dealer side ────────────────────────────────────────────────────────────── +section('Dealer side'); +const halfCard = (p, sideways) => sideways + ? { w: (CARD_H / 2) * p.s, h: (CARD_W / 2) * p.s * VIEW.squash } + : { w: (CARD_W / 2) * p.s, h: (CARD_H / 2) * p.s * VIEW.squash }; +for (const side of ['player', 'banker']) { + for (let i = 0; i < 3; i++) ok(`${side} card ${i} on the felt`, onFeltPt(handCardPose(side, i))); + const third = handCardPose(side, 2), hc = halfCard(third, true); + const shoe = project(SHOE.u, SHOE.v), disc = project(DISCARD.u, DISCARD.v); + const furn = side === 'player' ? disc : shoe; + ok(`${side} third card clear of the ${side === 'player' ? 'discard' : 'shoe'}`, third.y - hc.h > furn.y + 40 * furn.s, + `card top ${(third.y - hc.h).toFixed(0)} furniture bottom ${(furn.y + 40 * furn.s).toFixed(0)}`); + const first = handCardPose(side, 0), h1 = halfCard(first, false); + ok(`${side} cards clear of the chip tray`, first.y - h1.h > project(0, TRAY.v1).y); + const box = handBoxRect(side); + ok(`${side} box doesn't overlap the readout`, box.y + box.h / 2 < READOUT.y - READOUT.h / 2 + 4); + const badgeY = handCenter(side).y + TOTAL_BADGE_DY * handCenter(side).s; + ok(`${side} total badge between box and readout`, badgeY > box.y + box.h / 2 && badgeY + 17 < READOUT.y - READOUT.h / 2 + 18, + `badge ${badgeY.toFixed(0)}`); + for (let seat = 0; seat < 7; seat++) { + ok(`${side} third card clear of seat ${seat}'s boxes`, + BET_TYPES.every(t => boxOutline(seat, t).every(p => Math.abs(p.x - third.x) > hc.w || Math.abs(p.y - third.y) > hc.h))); + } +} +ok('the hands sit either side of centre', handCenter('player').x < 960 && handCenter('banker').x > 960); +for (let seat = 0; seat < 7; seat++) { + ok(`readout clear of seat ${seat}'s boxes`, BET_TYPES.every(t => !boxOutline(seat, t).some(p => inRect(p, READOUT)))); +} +ok('felt lettering clear of every box', FELT_TEXT.every(t => t.r < BANDS.tie.r0 - 0.03)); +ok('placard / shoe / discard on the felt', [SHOE, DISCARD, PLACARD].every(p => onFelt(p.u, p.v))); + +// ── Portraits / scoreboard ─────────────────────────────────────────────────── +section('Portraits + scoreboard'); +for (let seat = 1; seat < 7; seat++) { + const pt = seatPortrait(seat); + ok(`seat ${seat}: portrait + labels clear of the dock`, pt.y + pt.r + 60 < DOCK.y); + const q = unproject(pt.x, pt.y); + ok(`seat ${seat}: portrait off the felt`, Math.hypot(q.u, q.v) > FELT_R); +} +const { w: bw, h: bh } = boardSize(); +ok('scoreboard on screen', BOARD.x + bw <= 1910 && BOARD.y >= 0); +ok('scoreboard clear of the title', BOARD.x > 960 + 160); +ok('scoreboard above the shoe and the dealer edge', BOARD.y + bh < project(SHOE.u, SHOE.v).y - 20 && BOARD.y + bh < VIEW.yFar + 8); +ok('scoreboard clear of the top-right portrait', BOARD.y + bh < seatPortrait(5).y - seatPortrait(5).r); + +// ── Roads ──────────────────────────────────────────────────────────────────── +section('Roads'); +const P = 'player', B = 'banker', T = 'tie'; +ok('counts', JSON.stringify(counts([P, B, B, T])) === JSON.stringify({ player: 1, banker: 2, tie: 1 })); +{ + const bp = beadPlate(Array(7).fill(P)); + ok('bead plate fills columns top-down', bp[5].col === 0 && bp[5].row === 5 && bp[6].col === 1 && bp[6].row === 0); + const long = beadPlate(Array.from({ length: 75 }, (_, i) => (i % 2 ? P : B)), 6, 10); + ok('bead plate keeps the last whole columns', long.length <= 60 && long.every(c => c.col < 10) && long[long.length - 1].outcome === B); + ok('bead plate drops whole columns', long[0].row === 0); +} +{ + const r = bigRoad([B, B, B, P, P, B]); + ok('big road: streak goes down', r[0].col === 0 && r[2].row === 2 && r[2].col === 0); + ok('big road: new winner → next column, top row', r[3].col === 1 && r[3].row === 0 && r[4].row === 1); + ok('big road: third streak starts in column 2', r[5].col === 2 && r[5].row === 0); +} +{ + const r = bigRoad([P, T, T, B]); + ok('big road: ties mark the last cell instead of taking one', r.length === 2 && r[0].ties === 2 && r[1].ties === 0); + const lead = bigRoad([T, P]); + ok('big road: leading ties attach to the first cell', lead.length === 1 && lead[0].ties === 1); +} +{ + const r = bigRoad(Array(9).fill(B)); + ok('big road: dragon tail turns right at the bottom row', r[5].row === 5 && r[6].col === 1 && r[6].row === 5 && r[8].col === 3); + const after = bigRoad([...Array(9).fill(B), P]); + ok('big road: next streak starts after the tail\'s first column', after[9].col === 1 && after[9].row === 0); + const blocked = bigRoad([...Array(8).fill(B), ...Array(7).fill(P)]); + const pCells = blocked.filter(c => c.outcome === P); + ok('big road: a streak blocked by an earlier tail turns right early', + pCells[0].col === 1 && pCells[4].row === 4 && pCells[5].row === 4 && pCells[5].col === 2); + const keys = new Set(blocked.map(c => `${c.col},${c.row}`)); + ok('big road: no two cells share a spot', keys.size === blocked.length); +} +{ + const hist = Array.from({ length: 80 }, (_, i) => (i % 3 === 0 ? P : B)); + const win = bigRoadWindow(hist, 6, 18); + ok('big road window fits 18 columns', win.every(c => c.col >= 0 && c.col < 18)); + ok('big road window ends on the latest coup', win[win.length - 1].outcome === hist[hist.length - 1]); +} + +// ── Source lint ────────────────────────────────────────────────────────────── +section('Source lint'); +const src = readFileSync(new URL('../src/games/baccarat/BaccaratGame.js', import.meta.url), 'utf8'); +ok('no hand-built Rectangle hit areas', !/new Phaser\.Geom\.Rectangle\(/.test(src)); +ok('no setInteractive on containers', !/add\.container\([^)]*\)[^;]*setInteractive/.test(src)); +ok('felt clicks go through hitBox', /hitBox\(p\.worldX, p\.worldY\)/.test(src)); +ok('uses the shared dock + card skin', /new CasinoDock\(/.test(src) && /new CardSkin\(/.test(src)); + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/tools/verifyBlackjack.js b/tools/verifyBlackjack.js new file mode 100644 index 0000000..e4619ac --- /dev/null +++ b/tools/verifyBlackjack.js @@ -0,0 +1,163 @@ +#!/usr/bin/env node +// verifyBlackjack.js — headless checks for the Blackjack table geometry and chip maths. +// The art/scene code needs a browser; this covers the pure parts it is built on. + +import { readFileSync } from 'node:fs'; +import { + VIEW, project, unproject, depthScale, polar, onFelt, seatLayout, cardPose, dealerCardPose, + betPose, badgePose, insurancePose, SEAT_ANGLES, PLAY_ORDER, RAIL_OUT, RAIL_FACE_PX, FELT_R, + BET_SPOT_R, INSURANCE_LINES, FELT_TEXT, TRAY, SHOE, DISCARD, PLACARD, DOCK, DEALER_V, +} from '../src/games/blackjack/BlackjackTable.js'; +import { breakdown, DENOMS, CHIP_DEFS } from '../src/ui/CasinoChips.js'; + +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) { pass++; } + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +function section(name) { console.log(`\n${name}`); } + +const CARD_W = 96, CARD_H = 134; +const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y); +const feltR = (pt) => { const { u, v } = unproject(pt.x, pt.y); return Math.hypot(u, v); }; +const isOnFelt = (pt) => { const { u, v } = unproject(pt.x, pt.y); return onFelt(u, v); }; + +// ── Chips ──────────────────────────────────────────────────────────────────── +section('Chip breakdown'); +for (let amt = 0; amt <= 400; amt++) { + const b = breakdown(amt); + ok(`breakdown(${amt}) sums`, b.reduce((a, d) => a + d, 0) === amt); + ok(`breakdown(${amt}) uses known denoms`, b.every(d => DENOMS.includes(d))); + ok(`breakdown(${amt}) is largest-first`, b.every((d, i) => i === 0 || b[i - 1] >= d)); +} +// Every amount the game can put on the felt: bets 5–100 (AI 10/15 too), +// doubles/splits up to 200, 3:2 payouts (floored), insurance (floor bet/2) and its 2:1 pay. +const amounts = new Set(); +for (let bet = 5; bet <= 100; bet += 5) { + amounts.add(bet); amounts.add(bet * 2); amounts.add(Math.floor(bet * 1.5)); + amounts.add(Math.floor(bet / 2)); amounts.add(Math.floor(bet / 2) * 2); +} +for (const a of amounts) ok(`game amount ${a} representable`, breakdown(a).reduce((x, d) => x + d, 0) === a); +ok('every denom has a colour definition', DENOMS.every(d => CHIP_DEFS[d]?.base && CHIP_DEFS[d]?.insert)); +ok('largest game stack fits the 14-chip cap', Math.max(...[...amounts].map(a => breakdown(a).length)) <= 14, + `max ${Math.max(...[...amounts].map(a => breakdown(a).length))}`); + +// ── Projection ─────────────────────────────────────────────────────────────── +section('Projection'); +let prev = null; +for (let v = -0.05; v <= 1.15; v += 0.01) { + const p = project(0, v); + if (prev) { + ok(`scale grows toward the player (v=${v.toFixed(2)})`, p.s > prev.s); + ok(`screen y grows toward the player (v=${v.toFixed(2)})`, p.y > prev.y); + } + prev = p; +} +ok('far edge at yFar', Math.abs(project(0, 0).y - VIEW.yFar) < 1e-6); +ok('near point at yNear', Math.abs(project(0, 1).y - VIEW.yNear) < 1e-6); +ok('scale 1 at the near point', Math.abs(depthScale(1) - 1) < 1e-9); +for (const [u, v] of [[0, 0.3], [0.7, 0.2], [-0.5, 0.8], [0.9, 0.05]]) { + const p = project(u, v), q = unproject(p.x, p.y); + ok(`unproject round-trips (${u},${v})`, Math.abs(q.u - u) < 1e-9 && Math.abs(q.v - v) < 1e-9); +} +ok('table is symmetric', Math.abs(project(0.6, 0.4).x - VIEW.cx - (VIEW.cx - project(-0.6, 0.4).x)) < 1e-9); + +// ── Seats ──────────────────────────────────────────────────────────────────── +section('Seat layout'); +ok('7 seats', SEAT_ANGLES.length === 7); +ok('play order covers every seat once', [...PLAY_ORDER].sort().join() === '0,1,2,3,4,5,6'); +ok('seat 0 is bottom-centre', SEAT_ANGLES[0] === 0); +ok('play order starts at screen-right (first base)', SEAT_ANGLES[PLAY_ORDER[0]] > 0); + +// Approximate a hand of n cards by a bounding circle. +function handRadius(seat, n, split = false) { + const { s } = seatLayout(seat).card; + const card = 0.5 * Math.hypot(CARD_W, CARD_H * VIEW.squash) * s; + if (!split) return card + 0.5 * (n - 1) * 28 * s; + return card + 0.74 * CARD_W * s + 0.5 * (n - 1) * 28 * s; +} + +for (let seat = 0; seat < 7; seat++) { + const L = seatLayout(seat); + ok(`seat ${seat}: card spot on felt`, isOnFelt(L.card)); + ok(`seat ${seat}: bet spot on felt`, isOnFelt(L.bet)); + ok(`seat ${seat}: badge on felt`, isOnFelt(L.badge)); + ok(`seat ${seat}: split bets on felt`, isOnFelt(betPose(seat, 0)) && isOnFelt(betPose(seat, 1))); + ok(`seat ${seat}: split badges on felt`, isOnFelt(badgePose(seat, 0)) && isOnFelt(badgePose(seat, 1))); + ok(`seat ${seat}: insurance spot on felt`, isOnFelt(insurancePose(seat))); + ok(`seat ${seat}: bet circle clear of the rail`, feltR(L.bet) + BET_SPOT_R < FELT_R); + ok(`seat ${seat}: bet circle nearer the player than the cards`, L.bet.s > L.card.s); + const p5 = cardPose(seat, 4, 5), p0 = cardPose(seat, 0, 5); + ok(`seat ${seat}: a 5-card hand stays on the felt`, isOnFelt(p5) && isOnFelt(p0)); + for (let other = seat + 1; other < 7; other++) { + const O = seatLayout(other); + const d = dist(L.card, O.card); + ok(`seats ${seat}/${other}: 3-card hands don't overlap`, d > handRadius(seat, 3) + handRadius(other, 3) - 50, + `d=${d.toFixed(0)}`); + ok(`seats ${seat}/${other}: bet circles apart`, dist(L.bet, O.bet) > 110, dist(L.bet, O.bet).toFixed(0)); + } +} + +section('Portraits'); +for (let seat = 0; seat < 7; seat++) { + const pt = seatLayout(seat).portrait; + ok(`seat ${seat}: portrait on screen`, pt.x - pt.r >= 0 && pt.x + pt.r <= 1920 && pt.y - pt.r >= 0 && pt.y + pt.r <= 1080); + if (seat === 0) { + ok('human portrait sits in the dock', pt.y - pt.r >= DOCK.y - 4); + } else { + ok(`seat ${seat}: portrait + labels clear of the dock`, pt.y + pt.r + 18 + 24 + 18 < DOCK.y); + ok(`seat ${seat}: portrait off the felt`, !isOnFelt({ x: pt.x, y: pt.y }) && feltR(pt) > FELT_R); + } + for (let other = seat + 1; other < 7; other++) { + const q = seatLayout(other).portrait; + ok(`portraits ${seat}/${other} don't overlap`, dist(pt, q) > pt.r + q.r + 20); + } +} + +// ── Dealer side ────────────────────────────────────────────────────────────── +section('Dealer side'); +const dealer2 = dealerCardPose(0, 2); +const dealerTop = dealer2.y - (CARD_H * dealer2.s * VIEW.squash) / 2; +const dealerBottom = dealer2.y + (CARD_H * dealer2.s * VIEW.squash) / 2; +ok('dealer cards clear the chip tray', dealerTop > project(0, TRAY.v1).y, `top=${dealerTop.toFixed(0)}`); +ok('dealer cards clear the insurance line', dealerBottom < polar(INSURANCE_LINES.r0, 0).y, + `bottom=${dealerBottom.toFixed(0)} line=${polar(INSURANCE_LINES.r0, 0).y.toFixed(0)}`); +const d6 = dealerCardPose(5, 6); +ok('6-card dealer hand stays clear of the shoe', d6.x + (CARD_W * d6.s) / 2 < project(SHOE.u, SHOE.v).x - 70 * d6.s); +ok('6-card dealer hand stays clear of the discard', dealerCardPose(0, 6).x - (CARD_W * d6.s) / 2 > project(DISCARD.u, DISCARD.v).x + 60 * d6.s); +ok('dealer row is on the felt', onFelt(0, DEALER_V)); +ok('shoe / discard / placard on the felt', onFelt(SHOE.u, SHOE.v) && onFelt(DISCARD.u, DISCARD.v) && onFelt(PLACARD.u, PLACARD.v)); +ok('placard clear of the tray', project(PLACARD.u, PLACARD.v).x + 52 * 0.72 < project(TRAY.u0, TRAY.v0).x); +ok('placard clear of the discard holder', project(PLACARD.u, PLACARD.v).x - 52 * 0.72 > project(DISCARD.u, DISCARD.v).x + 54 * 0.72); +const humanCardTop = seatLayout(0).card.y - (CARD_H * seatLayout(0).card.s * VIEW.squash) / 2; +const lastText = FELT_TEXT.reduce((a, t) => (t.r > a.r ? t : a)); +ok('felt lettering clears the human\'s cards', polar(lastText.r, 0).y + lastText.size * 0.6 < humanCardTop, + `text=${polar(lastText.r, 0).y.toFixed(0)} cards=${humanCardTop.toFixed(0)}`); +for (const seat of [5, 6]) { + const c = seatLayout(seat).card; + ok(`seat ${seat} cards clear of the shoe/discard`, Math.abs(c.x - project(seat === 5 ? SHOE.u : DISCARD.u, SHOE.v).x) > 90); +} + +section('Dock'); +const railBottom = polar(RAIL_OUT, 0).y + RAIL_FACE_PX * polar(RAIL_OUT, 0).s; +ok('rail front face ends above the dock', railBottom < DOCK.y, `rail=${railBottom.toFixed(0)}`); +ok('dock reaches the bottom of the canvas', DOCK.y + DOCK.h === 1080); +for (let seat = 0; seat < 7; seat++) { + const b = betPose(seat); + ok(`seat ${seat}: bet stack well above the dock`, b.y + 40 < DOCK.y); +} + +// ── Source lint (container hit-area gotcha) ────────────────────────────────── +section('Source lint'); +const read = (rel) => readFileSync(new URL(rel, import.meta.url), 'utf8'); +for (const rel of ['../src/games/blackjack/BlackjackGame.js', '../src/ui/casino/CasinoDock.js', '../src/ui/casino/CasinoCards.js']) { + const src = read(rel); + ok(`${rel}: no hand-built Rectangle hit areas`, !/new Phaser\.Geom\.Rectangle\(/.test(src)); + ok(`${rel}: no setInteractive on containers`, !/add\.container\([^)]*\)[^;]*setInteractive/.test(src)); +} +ok('dock chip buttons use a texture-space circle', /new Phaser\.Geom\.Circle\(64, 64, 62\)/.test(read('../src/ui/casino/CasinoDock.js'))); +ok('Blackjack uses the shared dock + card skin', /new CasinoDock\(/.test(read('../src/games/blackjack/BlackjackGame.js')) + && /new CardSkin\(/.test(read('../src/games/blackjack/BlackjackGame.js'))); + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/tools/verifyPaiGowPoker.js b/tools/verifyPaiGowPoker.js index bcbe8f1..b0ba118 100644 --- a/tools/verifyPaiGowPoker.js +++ b/tools/verifyPaiGowPoker.js @@ -481,6 +481,91 @@ console.log('\nDeck coverage'); // 6 players + dealer × 7 = 49 cards ≤ 53 ok('max 5 AI opponents: 6 players + dealer = 49 cards dealt ≤ 53', 6 * 7 + 7 <= 53); +// ── Table layout (PaiGowTable.js) ───────────────────────────────────────────── +console.log('\nTable layout'); +{ + const T = await import('../src/games/paigow/PaiGowTable.js'); + const { seatLayout, fanPose, stackPose, boxBadge, boxCorner, screenOnFelt, dealerHighBox, dealerLowBox, + dealerRowPose, SET_TRAY, TRAY_HIGH, TRAY_LOW, trayHighX, trayLowX, TRAY_SCALE, TRAY_CARD_Y, + DOCK, VIEW, CARD_W, CARD_H, FAN_DX, diceStartIndex, rotateFrom, PLAY_ORDER, polar, FELT_TEXT, + project, DICE_CUP, DICE_LAND, DECK } = T; + const SEATS = [0, 1, 2, 3, 4]; + const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y); + // bounding circle of a box holding n cards + const boxR = (box, n) => 0.5 * Math.hypot((CARD_W + (n - 1) * FAN_DX) * box.s, CARD_H * box.s * VIEW.squash); + + for (const seat of SEATS) { + const L = seatLayout(seat); + ok(`seat ${seat}: HIGH / LOW / bet on the felt`, screenOnFelt(L.high) && screenOnFelt(L.low) && screenOnFelt(L.bet)); + ok(`seat ${seat}: all 5 HIGH fan cards on the felt`, [0, 4].every(i => screenOnFelt(fanPose(L.high, i, 5)))); + ok(`seat ${seat}: 7-card stack on the felt`, [0, 6].every(i => screenOnFelt(stackPose(L.high, i)))); + const gap = dist(L.high, L.low) - (CARD_H / 2) * L.high.s * VIEW.squash - (CARD_H / 2) * L.low.s * VIEW.squash; + ok(`seat ${seat}: HIGH and LOW boxes don't overlap`, gap > 10, `gap ${gap.toFixed(0)}`); + ok(`seat ${seat}: bet circle nearer the player than the HIGH box`, L.bet.s > L.high.s); + ok(`seat ${seat}: badge + marker on screen`, boxBadge(L.high).y < DOCK.y && boxCorner(L.high, 5).x < 1920); + for (const other of SEATS.filter(o => o > seat)) { + const O = seatLayout(other); + for (const [a, an] of [[L.high, 5], [L.low, 2]]) { + for (const [b, bn] of [[O.high, 5], [O.low, 2]]) { + ok(`seats ${seat}/${other}: boxes apart`, dist(a, b) > boxR(a, an) + boxR(b, bn) - 70, + `d=${dist(a, b).toFixed(0)}`); + } + } + } + const pt = L.portrait; + if (seat > 0) { + ok(`seat ${seat}: portrait + labels clear of the dock`, pt.y + pt.r + 60 < DOCK.y); + ok(`seat ${seat}: portrait clear of the setting tray`, + pt.x + pt.r < SET_TRAY.x0 || pt.x - pt.r > SET_TRAY.x1 || pt.y + pt.r < SET_TRAY.y0); + } + } + const dh = dealerHighBox(), dl = dealerLowBox(); + ok('dealer HIGH and LOW boxes apart', dist(dh, dl) > boxR(dh, 5) + boxR(dl, 2) - 10); + ok('dealer boxes on the felt', screenOnFelt(fanPose(dh, 0, 5)) && screenOnFelt(fanPose(dl, 1, 2))); + ok('dealer 7-card row on the felt', screenOnFelt(dealerRowPose(0)) && screenOnFelt(dealerRowPose(6))); + const dealerBottom = dh.y + (CARD_H / 2) * dh.s * VIEW.squash; + const lowTop = (seat) => { const b = seatLayout(seat).low; return b.y - (CARD_H / 2) * b.s * VIEW.squash; }; + ok('felt lettering sits between the dealer and the seat-0 LOW box', + FELT_TEXT.every(t => polar(t.r, 0).y - t.size * 0.5 > dealerBottom && polar(t.r, 0).y + t.size * 0.5 < lowTop(0)), + `dealer ${dealerBottom.toFixed(0)} low ${lowTop(0).toFixed(0)}`); + ok('dice cup / landing / deck on the felt', [DICE_CUP, DICE_LAND, DECK].every(p => screenOnFelt(project(p.u, p.v)))); + + // Setting tray + for (let n = 5; n <= 7; n++) { + const xs = Array.from({ length: n }, (_, i) => trayHighX(i, n)); + ok(`tray HIGH row of ${n} fits its zone`, xs[0] - (CARD_W * TRAY_SCALE) / 2 >= TRAY_HIGH.x0 - 2 && xs[n - 1] + (CARD_W * TRAY_SCALE) / 2 <= TRAY_HIGH.x1 + 2); + } + ok('tray LOW pair fits its zone', trayLowX(0) - (CARD_W * TRAY_SCALE) / 2 >= TRAY_LOW.x0 - 2 && trayLowX(1) + (CARD_W * TRAY_SCALE) / 2 <= TRAY_LOW.x1 + 2); + ok('tray zones don\'t overlap', TRAY_HIGH.x1 < TRAY_LOW.x0); + ok('tray cards fit vertically', TRAY_CARD_Y - (CARD_H * TRAY_SCALE) / 2 > SET_TRAY.y0 + 40 && TRAY_CARD_Y + (CARD_H * TRAY_SCALE) / 2 < SET_TRAY.y1 - 60); + ok('tray clear of the human bet circle', seatLayout(0).bet.y + 50 < SET_TRAY.y0); + + // Dice → first seat + for (let n = 2; n <= 6; n++) { + const hit = new Set(); + for (let total = 3; total <= 18; total++) { + const idx = diceStartIndex(total, n); + ok(`dice ${total} over ${n} positions in range`, idx >= 0 && idx < n); + hit.add(idx); + } + ok(`every one of ${n} positions can receive the first hand`, hit.size === n); + } + ok('total 1 → the dealer (position 1)', diceStartIndex(1, 5) === 0 && diceStartIndex(6, 5) === 0); + ok('rotateFrom keeps every position once', rotateFrom(['d', 5, 3, 1, 0], 2).join() === '3,1,0,d,5'); + ok('play order covers all six logic seats', [...PLAY_ORDER].sort().join() === '0,1,2,3,4,5'); +} + +// ── Source lint ─────────────────────────────────────────────────────────────── +console.log('\nSource lint'); +{ + const { readFileSync } = await import('node:fs'); + const src = readFileSync(new URL('../src/games/paigow/PaiGowPokerGame.js', import.meta.url), 'utf8'); + ok('no hand-built Rectangle hit areas', !/new Phaser\.Geom\.Rectangle\(/.test(src)); + ok('tray cards set their size before setInteractive', /c\.setSize\(CARD_W, CARD_H\);\s*c\.setInteractive/.test(src)); + ok('out-of-chips Modal gets a string', !/new Modal\(this, \{/.test(src)); + ok('no references to undefined SFX.WIN / SFX.LOSE / SFX.SQUASH', !/SFX\.(WIN|LOSE|SQUASH)\b/.test(src)); +} + // ── Summary ──────────────────────────────────────────────────────────────────── console.log(`\n ${pass} passed, ${fail} failed\n`); if (fail > 0) process.exit(1);