fertig-classic-games/src/games/paigow/PaiGowPokerGame.js

1036 lines
43 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 } 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 {
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 / 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 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 STACK_SIZE = 54;
const FELT = '#123c78';
const RESULT_LABELS = { win: 'Win!', push: 'Push', lose: 'Lose', foul: 'Foul' };
const RESULT_COLORS = { win: '#f5d020', push: '#9aa5b4', lose: '#e05c5c', foul: '#e05c5c' };
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 {
constructor() { super('PaiGowPokerGame'); }
init(data) {
this.gameDef = data.game;
this.opponents = data.opponents ?? [];
this.playfield = data.playfield ?? null;
this.cardBack = data.cardBack ?? null;
}
async create() {
new MusicPlayer(this, this.cache.json.get('music').tracks);
this.gs = null;
this.busy = false;
this.pendingBet = 0;
this.lastBet = 0;
this.portraits = [];
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 = {};
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();
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.buildDock();
this.buildSetTray();
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();
if (!this.sys.isActive()) return;
this.gs = createInitialState(this.opponents, this._playerChips);
this.startNewRound();
}
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.playfield);
}
}
buildDealerArea() {
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);
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);
// 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);
}
}
buildSeats() {
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(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(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.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);
}
}
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;
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);
}
// ── 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);
}
// 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();
}
}
// ── 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;
}
}
// ── Chip balance ───────────────────────────────────────────────────────────
async loadPlayerChips() {
try {
const { profile } = await api.get('/profile');
this._playerChips = profile.chips ?? 2000;
} catch {
this._playerChips = 2000;
}
}
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 */ }
}
// ── 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);
}
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();
}
}