diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 5b1e3e0..62c1fe1 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -62,7 +62,7 @@ registerGame({ slug: 'battleship', name: 'Battleship', category: 'tabletop', min registerGame({ slug: 'mastermind', name: 'Mastermind', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 32 }); registerGame({ slug: 'connect4', name: 'Connect 4', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 33 }); registerGame({ slug: 'boggle', name: 'Boggle', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 34 }); -registerGame({ slug: 'oldmaid', name: 'Old Maid', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 35 }); +registerGame({ slug: 'oldmaid', name: 'Old Maid', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 35 }); registerGame({ slug: 'blokus', name: 'Blokus', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 36 }); registerGame({ slug: 'spellingbee', name: 'Spelling Bee', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 37 }); registerGame({ slug: 'minicrossword', name: 'Mini Crossword', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 38 }); diff --git a/src/games/oldmaid/OldMaidAI.js b/src/games/oldmaid/OldMaidAI.js index 2a0a935..2e08450 100644 --- a/src/games/oldmaid/OldMaidAI.js +++ b/src/games/oldmaid/OldMaidAI.js @@ -32,6 +32,7 @@ export function createMemory(seatCount) { omCardId: null, // id of the Old Maid card, once we've ever identified it omLocation: null, // seat we believe currently holds the Old Maid, or null confidence: 0, // 0..1 belief strength in omLocation + posKnown: false, // can we still point at the Old Maid in that hand? (lost when it's shuffled) logCursor: 0, }; } @@ -51,6 +52,7 @@ export function observeLog(memory, state, selfSeat) { memory.omCardId = e.cardId; memory.omLocation = e.drawerSeat; // it landed in the drawer's hand memory.confidence = 1; + memory.posKnown = true; } else if (e.drawerSeat === selfSeat && memory.omLocation === e.fromSeat) { // We drew from a seat we suspected — and it wasn't the Old Maid, so // the Old Maid definitely stayed behind. Belief firms up. @@ -61,6 +63,9 @@ export function observeLog(memory, state, selfSeat) { // may have been the Old Maid — we're now less sure it stayed put. memory.confidence *= 0.5; } + } else if (e.kind === 'shuffle') { + // they shuffled: we may still know WHO holds it, but not which card + if (memory.omLocation === e.seat && e.seat !== selfSeat) memory.posKnown = false; } else if (e.kind === 'safe') { // A safe seat has an empty hand, so it cannot hold the (unpairable) Old // Maid. If we thought it did, we were wrong — reset to unknown. @@ -77,6 +82,34 @@ export function observeLog(memory, state, selfSeat) { * Pick the cardId to draw from the current player's target. Falls back to a * uniform-random draw when the AI has no usable read. */ +/** + * Does `seat` shuffle its hand after a draw? Careful players hide the Old Maid + * by shuffling whenever they hold it — and the best also shuffle now and then + * when they don't, so the shuffle itself gives nothing away. + */ +export function wantsShuffle(state, seat, skill = 3, rand = Math.random) { + const hand = state.players[seat].hand; + if (hand.length < 2) return false; + const holdsOM = hand.some((c) => c.rank === OLD_MAID_RANK); + if (skill <= 2) return false; + if (holdsOM) return true; + return skill >= 4 && rand() < 0.4; +} + +/** + * The reaction an opponent's face gives when you hover one of their cards: + * 'hopeful' (go on, take that one) or 'worried'. Low skill is honest — hopeful + * over the Old Maid; 3 is a coin flip; 4-5 bluff, mostly the wrong way round. + * Returns null for no visible reaction. + */ +export function tellFor(isOldMaid, skill = 3, rand = Math.random) { + if (rand() < (skill >= 4 ? 0.5 : 0.35)) return null; + const honest = skill <= 2 ? 0.85 : skill === 3 ? 0.5 : 0.25; + const truthful = rand() < honest; + const hopeful = isOldMaid ? truthful : !truthful; + return hopeful ? 'hopeful' : 'worried'; +} + export function chooseDraw(state, seat, memory, skill = 3) { const prof = profileFor(skill); const targetSeat = nextActiveSeat(state, seat); @@ -95,7 +128,7 @@ export function chooseDraw(state, seat, memory, skill = 3) { let suspectId = null; // Hard knowledge: we watched the Old Maid into this seat. - if (memory.omCardId != null && memory.omLocation === targetSeat && memory.confidence >= 0.5) { + if (memory.omCardId != null && memory.posKnown && memory.omLocation === targetSeat && memory.confidence >= 0.5) { if (hand.some((c) => c.id === memory.omCardId)) suspectId = memory.omCardId; } diff --git a/src/games/oldmaid/OldMaidArt.js b/src/games/oldmaid/OldMaidArt.js new file mode 100644 index 0000000..35287de --- /dev/null +++ b/src/games/oldmaid/OldMaidArt.js @@ -0,0 +1,230 @@ +// Old Maid art — a candlelit Victorian parlour, baked once per page load. The +// card FACES are the owner's own illustrated sheet ('oldmaid-cards', frames +// A..K = 0..12, the Old Maid = 13, loaded via the asset manifest); this module +// adds a matching back and the room. +// +// oldmaid-back burgundy back with gold filigree and a cameo +// oldmaid-table- damask wallpaper + gilt frames, an oval mahogany table +// with a lace doily, brass candlesticks (flames are live) + +import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js'; +import { + bakeRoom, canvas, rr, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, CARD_TEX, +} from '../../ui/cardtable/TableArt.js'; +import { W, H } from '../../ui/cardtable/TableGeometry.js'; +import { T, candlePose, PILE } from './OldMaidTable.js'; + +const CW = CARD_TEX.W, CH = CARD_TEX.H; + +function cameo(ctx, cx, cy, r, bg, fg) { + ctx.beginPath(); ctx.ellipse(cx, cy, r * 0.8, r, 0, 0, Math.PI * 2); ctx.fillStyle = bg; ctx.fill(); + ctx.lineWidth = 4; ctx.strokeStyle = '#d9a84a'; ctx.stroke(); + // a lady's profile silhouette with a bun + ctx.save(); + ctx.translate(cx, cy); + ctx.scale(r / 50, r / 50); + ctx.fillStyle = fg; + ctx.beginPath(); + ctx.moveTo(-4, 40); + ctx.bezierCurveTo(-26, 34, -28, 10, -18, 0); + ctx.bezierCurveTo(-26, -18, -16, -36, 2, -36); + ctx.bezierCurveTo(14, -36, 20, -28, 20, -18); + ctx.lineTo(26, -8); ctx.lineTo(20, -4); ctx.lineTo(22, 4); ctx.lineTo(16, 8); + ctx.bezierCurveTo(18, 16, 10, 20, 6, 22); + ctx.lineTo(10, 40); + ctx.closePath(); + ctx.fill(); + ctx.beginPath(); ctx.arc(-14, -32, 10, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); +} + +function bakeBack(scene) { + const c = canvas(CW, CH); + const ctx = c.getContext('2d'); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.fillStyle = '#5a1424'; + ctx.fill(); + ctx.save(); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.clip(); + ctx.strokeStyle = 'rgba(217,168,74,0.35)'; + ctx.lineWidth = 2; + for (let i = -CH; i < CW + CH; i += 16) { + ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i + CH * 0.6, CH); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(i + CH * 0.6, 0); ctx.lineTo(i, CH); ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 96, 18); + ctx.fillRect(0, 0, CW, CH); + ctx.restore(); + rr(ctx, 10, 10, CW - 20, CH - 20, 11); + ctx.lineWidth = 4; ctx.strokeStyle = '#d9a84a'; ctx.stroke(); + rr(ctx, 17, 17, CW - 34, CH - 34, 8); + ctx.lineWidth = 1.5; ctx.stroke(); + cameo(ctx, CW / 2, CH / 2, 50, '#f3e6c8', '#3a0c18'); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.lineWidth = 2.5; ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.stroke(); + scene.textures.addCanvas('oldmaid-back', c); +} + +// ── The parlour ───────────────────────────────────────────────────────────── +function wall(ctx) { + ctx.fillStyle = '#16261c'; + ctx.fillRect(0, 0, W, H); + // damask + ctx.globalAlpha = 0.18; + ctx.fillStyle = '#c9b27a'; + const size = 110; + for (let row = 0, y = 0; y < H + size; row++, y += size * 0.8) { + for (let x = row % 2 ? size / 2 : 0; x < W + size; x += size) { + ctx.save(); + ctx.translate(x, y); + for (let k = 0; k < 4; k++) { + ctx.rotate(Math.PI / 2); + ctx.beginPath(); ctx.ellipse(0, -size * 0.22, size * 0.08, size * 0.2, 0, 0, Math.PI * 2); ctx.fill(); + } + ctx.restore(); + } + } + ctx.globalAlpha = 1; + // gilt-framed portraits high on the wall + for (const [x, y, w, h] of [[150, 40, 120, 150], [1650, 40, 120, 150], [880, 12, 160, 70]]) { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 12; + ctx.fillStyle = '#8a6a22'; ctx.fillRect(x - 10, y - 10, w + 20, h + 20); + ctx.restore(); + ctx.strokeStyle = '#e8c86a'; ctx.lineWidth = 3; ctx.strokeRect(x - 6, y - 6, w + 12, h + 12); + ctx.fillStyle = '#2a1e14'; ctx.fillRect(x, y, w, h); + if (h > 100) cameo(ctx, x + w / 2, y + h / 2, h * 0.36, '#3a2c1e', '#120a06'); + } + ctx.fillStyle = noisePattern(ctx, 128, 16); + ctx.fillRect(0, 0, W, H); + // candlelit: warm pools near the table, dark corners + const glow = ctx.createRadialGradient(W / 2, 380, 60, W / 2, 400, 1200); + glow.addColorStop(0, 'rgba(255,190,110,0.22)'); + glow.addColorStop(0.5, 'rgba(255,170,90,0.05)'); + glow.addColorStop(1, 'rgba(0,0,0,0.6)'); + ctx.fillStyle = glow; + ctx.fillRect(0, 0, W, H); +} + +function front(ctx, Tb) { + frontBands(ctx, Tb, ['#6a2414', '#561c10', '#44160c', '#341008', '#260a05'], { grooves: [0.45] }); +} + +function rim(ctx, Tb) { + rimBand(ctx, Tb, { base: '#5a1e10', dark: '#260a04', light: '#a04a2a', grain: ['#1a0602', '#c86a42'], gloss: 1.6 }); +} + +function top(ctx, Tb) { + // polished mahogany: long grain streaks + a deep gloss + const g = ctx.createLinearGradient(0, 100, 0, 1000); + g.addColorStop(0, '#4a160c'); g.addColorStop(1, '#2e0c06'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + ctx.globalAlpha = 0.18; + for (let i = 0; i < 160; i++) { + const y = 90 + Math.random() * 920; + ctx.beginPath(); + ctx.moveTo(0, y); + for (let x = 0; x <= W; x += 60) ctx.lineTo(x, y + Math.sin(x / 140 + i) * 6); + ctx.lineWidth = 1 + Math.random() * 2.5; + ctx.strokeStyle = Math.random() < 0.5 ? '#160502' : '#8a3a1c'; + ctx.stroke(); + } + ctx.globalAlpha = 1; + ctx.fillStyle = noisePattern(ctx, 200, 22); + ctx.fillRect(0, 0, W, H); + // round lace doily in the middle + const steps = 72; + const rings = [0.38, 0.33, 0.27, 0.2, 0.13, 0.07]; + const ptsAt = (r, wob = 0) => { + const out = []; + for (let i = 0; i < steps; i++) { + const a = (i / steps) * Math.PI * 2; + const rr2 = r + wob * Math.sin(a * 18); + out.push(Tb.P.project(PILE.u + Math.cos(a) * rr2, PILE.v - 0.12 + Math.sin(a) * rr2 * 0.5)); + } + return out; + }; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 4; + poly(ctx, ptsAt(0.4, 0.012)); ctx.fillStyle = 'rgba(244,234,212,0.92)'; ctx.fill(); + ctx.restore(); + ctx.save(); + poly(ctx, ptsAt(0.4, 0.012)); + ctx.clip(); + for (const r of rings) { + poly(ctx, ptsAt(r, 0.006)); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(150,110,70,0.35)'; + ctx.stroke(); + for (let i = 0; i < steps; i += 2) { + const a = (i / steps) * Math.PI * 2; + const p = Tb.P.project(PILE.u + Math.cos(a) * (r - 0.025), PILE.v - 0.12 + Math.sin(a) * (r - 0.025) * 0.5); + ctx.beginPath(); ctx.arc(p.x, p.y, 3 * p.s, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(70,20,12,0.4)'; ctx.fill(); + } + } + ctx.restore(); + lampPool(ctx, Tb, { color: '255,200,130', alpha: 0.24, vignette: 0.6, at: { u: 0, v: 0.4 } }); + rimShadow(ctx, Tb, 0.4); +} + +// Brass candlesticks; the flames themselves are animated in the scene. +function candles(ctx) { + for (let i = 0; i < 2; i++) { + const p = candlePose(i); + const s = p.s; + // light pool on the table + const pool = ctx.createRadialGradient(p.x, p.y, 4, p.x, p.y, 220 * s); + pool.addColorStop(0, 'rgba(255,200,120,0.32)'); + pool.addColorStop(1, 'rgba(255,200,120,0)'); + ctx.fillStyle = pool; + ctx.beginPath(); ctx.ellipse(p.x, p.y, 230 * s, 230 * s * 0.5, 0, 0, Math.PI * 2); ctx.fill(); + // base + ctx.beginPath(); ctx.ellipse(p.x, p.y, 30 * s, 12 * s, 0, 0, Math.PI * 2); + ctx.fillStyle = '#8a6a22'; ctx.fill(); + ctx.strokeStyle = '#e8c86a'; ctx.lineWidth = 2; ctx.stroke(); + // stem + const g = ctx.createLinearGradient(p.x - 8 * s, 0, p.x + 8 * s, 0); + g.addColorStop(0, '#6a4a12'); g.addColorStop(0.5, '#f2d47a'); g.addColorStop(1, '#6a4a12'); + ctx.fillStyle = g; + ctx.fillRect(p.x - 6 * s, p.y - 56 * s, 12 * s, 56 * s); + ctx.beginPath(); ctx.ellipse(p.x, p.y - 56 * s, 16 * s, 6 * s, 0, 0, Math.PI * 2); ctx.fill(); + // candle + ctx.fillStyle = '#f3ead2'; + ctx.fillRect(p.x - 7 * s, p.y - 112 * s, 14 * s, 56 * s); + ctx.fillStyle = 'rgba(0,0,0,0.15)'; + ctx.fillRect(p.x + 2 * s, p.y - 112 * s, 5 * s, 56 * s); + ctx.strokeStyle = '#2a1a0a'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(p.x, p.y - 112 * s); ctx.lineTo(p.x, p.y - 118 * s); ctx.stroke(); + } +} + +export function flameTop(i) { + const p = candlePose(i); + return { x: p.x, y: p.y - 128 * p.s, s: p.s }; +} + +export async function prepareOldMaidArt(scene, playerCount) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('oldmaid-back')) bakeBack(scene); + if (!scene.textures.exists('oldmaid-flame')) { + const c = canvas(64, 96); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(32, 62, 2, 32, 56, 40); + g.addColorStop(0, 'rgba(255,255,230,1)'); + g.addColorStop(0.35, 'rgba(255,200,90,0.95)'); + g.addColorStop(1, 'rgba(255,120,40,0)'); + ctx.fillStyle = g; + ctx.beginPath(); + ctx.moveTo(32, 4); + ctx.bezierCurveTo(50, 40, 54, 66, 32, 88); + ctx.bezierCurveTo(10, 66, 14, 40, 32, 4); + ctx.fill(); + scene.textures.addCanvas('oldmaid-flame', c); + } + return bakeRoom(scene, `oldmaid-table-${playerCount}`, T, { wall, front, rim, top, after: candles }); +} + +export { mix }; diff --git a/src/games/oldmaid/OldMaidGame.js b/src/games/oldmaid/OldMaidGame.js index 475cbf8..0e9d586 100644 --- a/src/games/oldmaid/OldMaidGame.js +++ b/src/games/oldmaid/OldMaidGame.js @@ -1,681 +1,801 @@ 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 { auth } from '../../services/auth.js'; -import { api } from '../../services/api.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { - createInitialState, - applyDraw, - drawTargetSeat, - canDraw, - isGameOver, + CardTableScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { CARD_W, CARD_H, fanHit, fanInsertIndex, fanZone, inRect } from '../../ui/cardtable/TableGeometry.js'; +import { createMemory, observeLog, chooseDraw, wantsShuffle, tellFor } from './OldMaidAI.js'; +import { + createInitialState, applyDraw, applyShuffle, drawTargetSeat, isGameOver, OLD_MAID_RANK, } from './OldMaidLogic.js'; -import { createMemory, observeLog, chooseDraw, profileFor } from './OldMaidAI.js'; +import { + T, SQ, SEAT_COLORS, SEAT_HEX, layoutFor, handPose, offerPose, pilePose, handHome, handBadge, tellAt, spotFor, + OFFER_FAN, REVEAL, CANDLES, showPose, +} from './OldMaidTable.js'; +import { prepareOldMaidArt, flameTop } from './OldMaidArt.js'; -// ── Layout constants ──────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; +// ─── Old Maid ───────────────────────────────────────────────────────────────── +// A candlelit Victorian parlour on the shared card-table kit (src/ui/cardtable/). +// The card faces are the owner's own illustrated sheet ('oldmaid-cards'). +// Rules: OldMaidLogic.js · opponents: OldMaidAI.js · this file is flow, +// animation and input. Every card is a persistent sprite keyed by id. -const CARD_W = 90; -const CARD_H = 126; -const CARD_R = 8; -const HAND_SPREAD = 70; +const OLDMAID_CARD_FRAME = { A: 0, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8, T: 9, J: 10, Q: 11, K: 12, OM: 13 }; +const RANK_ORDER = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'OM']; +const RANK_NAME = { A: 'Aces', 2: 'Twos', 3: 'Threes', 4: 'Fours', 5: 'Fives', 6: 'Sixes', 7: 'Sevens', 8: 'Eights', 9: 'Nines', T: 'Tens', J: 'Jacks', Q: 'Queens', K: 'Kings' }; +const DEFAULTS = { pace: 'normal', hints: true, sort: 'rank', tells: true }; -const D = { - felt: -1, board: 0, card: 10, highlight: 20, - ui: 30, portrait: 35, chip: 40, banner: 60, modal: 80, -}; - -const SLOTS_USED = { - 2: ['bottom', 'top'], - 3: ['bottom', 'left', 'right'], - 4: ['bottom', 'left', 'top', 'right'], -}; - -function slotLayout(slot) { - switch (slot) { - case 'bottom': { - const bchipY = GAME_HEIGHT - 100 - CARD_H / 2 - 30; - const bpr = 56, bpx = CX - 90 - 12 - bpr, bpy = bchipY + 22 - bpr; - return { - handCenter: { x: CX, y: GAME_HEIGHT - 100 }, - handAxis: 'x', handFaceUp: true, - portrait: { x: bpx, y: bpy, r: bpr }, - nameLabel: { x: bpx, y: bpy - bpr - 14 }, - chip: { x: CX, y: bchipY }, chipRotation: 0, rotateCards: 0, - }; - } - case 'top': { - const tchipY = 110 + CARD_H / 2 + 30; - const tpr = 50, tpx = CX - 90 - 12 - tpr, tpy = tchipY - 22 + tpr; - return { - handCenter: { x: CX, y: 110 }, - handAxis: 'x', handFaceUp: false, - portrait: { x: tpx, y: tpy, r: tpr }, - nameLabel: { x: tpx, y: tpy + tpr + 14 }, - chip: { x: CX, y: tchipY }, chipRotation: 0, rotateCards: 180, - }; - } - case 'left': { - const lchipX = 110 + CARD_H / 2 + 10 + 22; - const lpr = 50, lpx = lchipX - 22 + lpr, lpy = CY - 90 - 12 - lpr; - return { - handCenter: { x: 110, y: CY }, - handAxis: 'y', handFaceUp: false, - portrait: { x: lpx, y: lpy, r: lpr }, - nameLabel: { x: lpx, y: lpy - lpr - 14 }, - chip: { x: lchipX, y: CY }, chipRotation: Math.PI / 2, rotateCards: 90, - }; - } - case 'right': { - const rchipX = GAME_WIDTH - 110 - CARD_H / 2 - 10 - 22; - const rpr = 50, rpx = rchipX + 22 - rpr, rpy = CY - 90 - 12 - rpr; - return { - handCenter: { x: GAME_WIDTH - 110, y: CY }, - handAxis: 'y', handFaceUp: false, - portrait: { x: rpx, y: rpy, r: rpr }, - nameLabel: { x: rpx, y: rpy - rpr - 14 }, - chip: { x: rchipX, y: CY }, chipRotation: -Math.PI / 2, rotateCards: 270, - }; - } - default: - throw new Error(`Unknown slot: ${slot}`); - } -} - -const DECK_POS = { x: CX, y: CY }; - -const SUIT_COLORS = { - s: { fill: 0xf2ead8, stroke: 0x1a1208, glyph: '#1a1208' }, - c: { fill: 0xf2ead8, stroke: 0x1a1208, glyph: '#1a1208' }, - h: { fill: 0xfbe7e2, stroke: 0xc92a2a, glyph: '#c92a2a' }, - d: { fill: 0xfbe7e2, stroke: 0xc92a2a, glyph: '#c92a2a' }, -}; -const OLDMAID_CARD_FRAME = { A: 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7, '9': 8, T: 9, J: 10, Q: 11, K: 12, OM: 13 }; - -// ── Scene ─────────────────────────────────────────────────────────────────── -export default class OldMaidGame extends Phaser.Scene { +export default class OldMaidGame extends CardTableScene { constructor() { super('OldMaidGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.cardBack = data.cardBack ?? null; - + this.initTable(data, { settingsKey: 'oldmaid-settings', defaults: DEFAULTS }); + this.L = layoutFor(this.playerCount); this.gs = null; - this.animating = false; - this.gameOver = false; - - this.cardObjs = new Map(); - this.transientObjs = []; - this.opponentPortraits = []; - this.seatChips = []; - this.slotForSeat = []; - this.aiMemory = []; + this.history = []; + this.memories = []; + this.hoverId = null; + this.offerHover = null; + this.potentialDrag = null; + this.dragState = null; + this.dragPreview = null; + this.gathering = null; + this.revealId = null; + this.tellSeen = new Set(); + this.aiHover = null; // { seat, id } — an opponent's hand hovering over your card + this.showcase = null; // { seat, ids } — cards held up in front of a player + this.pendingPile = new Set(); // dealt pairs waiting to be shown before they hit the pile } - create() { - new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); - this.buildPlayfield(); - this.assignSeats(); - this.buildSeatAreas(); - this.buildCenter(); - this.buildHUD(); - this.startNewMatch(); + faceFrame(card) { return { key: 'oldmaid-cards', frame: OLDMAID_CARD_FRAME[card.rank], sized: true }; } + + async create() { + this.createTableBase(); + const key = await prepareOldMaidArt(this, this.playerCount); + if (!this.alive()) return; + this.backKey = 'oldmaid-back'; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildSpot(); + this.buildCandles(); + this.buildDropSlot(); + this.buildPlates(this.L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'SAFE!' }); + this.buildBadges(); + this.buildGhostHands(this.L.seats.map((_, s) => (s ? handHome(this.L, s) : null)), SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Rules: () => this.openRules(), + }, 'Your turn: pick a card from the hand held out to you · watch their face for a tell\nSpace shuffle your hand · D draw blind · S sort · H hint · Esc menu'); + this.buildDock(); + this.buildSortRow([['rank', 'Rank'], ['manual', 'Mine']], () => { this.sortHand(); this.layout(); }); + this.buildTooltips(); + this.setupInput(); + this.newGame(); } - buildPlayfield() { - const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.felt); - } else { - const color = pf?.fallbackColor ? parseInt(pf.fallbackColor.replace('#', ''), 16) : 0x14532d; - this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, color).setDepth(D.felt); + // Candle flames flicker; their glow breathes on the table. + buildCandles() { + this.flames = CANDLES.map((_, i) => { + const t = flameTop(i); + const glow = this.add.image(t.x, t.y + 10, 'ct-spot').setDisplaySize(260 * t.s, 260 * t.s).setTint(0xffb050) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.35).setDepth(D.spot); + const flame = this.add.image(t.x, t.y, 'oldmaid-flame').setScale(0.55 * t.s).setOrigin(0.5, 0.92).setDepth(D.labels); + const flick = () => { + if (!this.alive()) return; + const d = 90 + Math.random() * 160; + this.tweens.add({ targets: flame, scaleX: (0.5 + Math.random() * 0.1) * t.s, scaleY: (0.5 + Math.random() * 0.14) * t.s, angle: (Math.random() - 0.5) * 8, duration: d, ease: 'Sine.easeInOut' }); + this.tweens.add({ targets: glow, alpha: 0.28 + Math.random() * 0.14, duration: d, ease: 'Sine.easeInOut', onComplete: flick }); + }; + flick(); + return { glow, flame }; + }); + } + + buildBadges() { + this.badges = []; + for (let seat = 1; seat < this.playerCount; seat++) { + const p = handBadge(this.L, seat); + const c = this.add.container(p.x, p.y).setDepth(D.oppHand + 2); + const g = this.add.graphics(); + g.fillStyle(0x140d07, 0.92); + g.fillCircle(0, 0, 16); + g.lineStyle(2.5, SEAT_COLORS[seat], 1); + g.strokeCircle(0, 0, 16); + const t = this.add.text(0, 1, '', { fontFamily: 'Righteous', fontSize: '16px', color: COLORS.textHex }).setOrigin(0.5); + c.add([g, t]); + this.badges[seat] = { c, t }; } } - assignSeats() { - const playerCount = 1 + this.opponents.length; - const slots = SLOTS_USED[playerCount]; - if (!slots) throw new Error(`Old Maid needs 2..4 players, got ${playerCount}`); - this.slotForSeat = slots.slice(); - } - - buildSeatAreas() { - for (let seat = 0; seat < this.slotForSeat.length; seat++) { - const layout = slotLayout(this.slotForSeat[seat]); - if (seat === 0) { - createPlayerPortrait(this, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait, 'OldMaidGame'); - this.add.text(layout.nameLabel.x, layout.nameLabel.y, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - } else { - const opp = this.opponents[seat - 1]; - if (opp) { - this.opponentPortraits[seat] = createOpponentPortrait(this, opp, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait); - this.add.text(layout.nameLabel.x, layout.nameLabel.y, opp.name ?? `P${seat + 1}`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - } - } - this.seatChips[seat] = this.makeSeatChip(layout.chip.x, layout.chip.y); - this.seatChips[seat].container.setRotation(layout.chipRotation); + buildTooltips() { + for (let seat = 1; seat < this.playerCount; seat++) { + const pl = this.L.seats[seat].plate; + this.hoverZone(pl.x, pl.y, 300, 96, () => this.seatTip(seat)); } } - makeSeatChip(x, y) { - const container = this.add.container(x, y).setDepth(D.chip); - const bg = this.add.graphics(); - bg.fillStyle(COLORS.panel, 0.92); - bg.fillRoundedRect(-90, -22, 180, 44, 10); - bg.lineStyle(2, COLORS.accent, 1); - bg.strokeRoundedRect(-90, -22, 180, 44, 10); - const label = this.add.text(-78, 0, 'PAIRS', { - fontFamily: 'Righteous', fontSize: '16px', color: COLORS.goldHex, - }).setOrigin(0, 0.5); - const count = this.add.text(78, 0, '0', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.accentHex, - }).setOrigin(1, 0.5); - container.add([bg, label, count]); - return { container, count }; + seatTip(seat) { + if (!this.gs) return null; + const p = this.gs.players[seat]; + const lines = [ + { text: p.safe ? 'Safe — out of cards!' : `${p.hand.length} card${p.hand.length === 1 ? '' : 's'} in hand`, color: p.safe ? '#8ce99a' : COLORS.textHex }, + { text: `${p.discardPairs} pairs thrown`, color: COLORS.goldHex }, + { text: `Stuck with the Old Maid ${this.timesStuck(seat)}× tonight` }, + { text: `Skill ${this.skillFor(seat)} / 5 — ${this.skillFor(seat) <= 2 ? 'an open book' : this.skillFor(seat) >= 4 ? 'a poker face' : 'hard to read'}`, color: COLORS.mutedHex }, + ]; + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; } - buildCenter() { - this.bannerBg = this.add.graphics().setDepth(D.banner - 1).setVisible(false); - this.bannerText = this.add.text(CX, CY, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, align: 'center', - wordWrap: { width: 900 }, - }).setOrigin(0.5).setDepth(D.banner).setVisible(false); + timesStuck(seat) { return this.history.filter(h => h.loser === seat).length; } + + // ── Game lifecycle ──────────────────────────────────────────────────────── + newGame() { + this.gs = createInitialState({ playerCount: this.playerCount }); + this.memories = this.L.seats.map((_, s) => (s ? createMemory(this.playerCount) : null)); + this.startGame(); } - buildHUD() { - const bchipY = GAME_HEIGHT - 100 - CARD_H / 2 - 30; - this.statusBg = this.add.graphics().setDepth(D.ui - 1); - this.statusText = this.add.text(CX - 90, bchipY - 22 - 14, '', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex, align: 'left', - }).setOrigin(0, 1).setDepth(D.ui); - - new Button(this, 80, GAME_HEIGHT - 30, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 120, height: 40, fontSize: 18, - }).setDepth(D.ui); - new Button(this, 80, GAME_HEIGHT - 75, 'New', () => this.startNewMatch(), { - variant: 'ghost', width: 120, height: 40, fontSize: 18, - }).setDepth(D.ui); - } - - // ── Match lifecycle ──────────────────────────────────────────────────────── - - startNewMatch() { - if (this.animating) return; - this.gameOver = false; - this.clearAllCardObjs(); - this.hideBanner(); - - const playerCount = this.slotForSeat.length; - const finalState = createInitialState({ playerCount }); - this.aiMemory = []; - for (let s = 0; s < playerCount; s++) { - this.aiMemory[s] = createMemory(playerCount); - observeLog(this.aiMemory[s], finalState, s); - } - + async startGame() { + this.clearSprites(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + this.revealId = null; + this.gathering = null; + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } + const gs = this.gs; + const centre = T.flat(0, 0.45, 0.7); + const all = [...gs.players.flatMap(p => p.hand), ...gs.discarded.flat()]; + this.showcase = null; + this.pendingPile = new Set(gs.discarded.flat().map(c => c.id)); + for (const c of all) this.lastLoc.set(c.id, { pose: centre, faceUp: false, depth: D.fly }); + const n = this.playerCount; + this.sortHand(); + this.updatePlates(); + this.updateDock(); playSound(this, SFX.CARD_SHUFFLE); - this.animating = true; + const step = 22; + let k = 0; + const order = new Map(); + for (let i = 0; i < 53; i++) order.set(i, k++); + const dealt = all.length; + this.layout({ + duration: 300, + delayFor: (v) => (v.kind === 'pile' ? 500 + dealt * step + (v.idx ?? 0) * 40 : 300 + (order.get(v.card.id) ?? 0) * step), + }); + for (let i = 0; i < 53; i += 4) this.time.delayedCall(320 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.35 })); + await this.wait(400 + dealt * step + 300); + if (!this.alive() || token !== this.turnToken) return; + // everyone lays down the pairs they were dealt, one player at a time + for (const { seat, pairedCards } of (gs.initialDealPairs ?? [])) { + const ids = pairedCards.map(c => c.id); + await this.holdUp(seat, ids, 900, { caption: `${seat === 0 ? 'Your' : `${this.shortName(seat)}'s`} ${ids.length / 2} pair${ids.length > 2 ? 's' : ''}`, color: SEAT_HEX[seat], burst: true }); + if (!this.alive() || token !== this.turnToken) return; + this.showcase = null; + for (const id of ids) this.pendingPile.delete(id); + this.layout({ duration: 420 }); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.45 }); + await this.wait(300); + if (!this.alive() || token !== this.turnToken) return; + } + this.pendingPile.clear(); + gs.players.forEach((p, s) => { if (p.safe) this.plateStamp(s, 'SAFE!', '#8ce99a', 0); }); + this.observeAll(); + this.advance(); + } - const deck = this.makeCardSprite({ label: '', suit: 's', suitSymbol: '' }, DECK_POS.x, DECK_POS.y, { faceUp: false }); - this.transientObjs.push(deck); - for (const chip of this.seatChips) { if (chip) chip.count.setText('0'); } + observeAll() { + for (let s = 1; s < this.playerCount; s++) observeLog(this.memories[s], this.gs, s); + } - // Round-robin deal sequence over the dealt hands. - const hands = finalState.players.map((p) => [...p.hand]); - const maxCards = Math.max(...hands.map((h) => h.length)); - const sequence = []; - for (let round = 0; round < maxCards; round++) { - for (let seat = 0; seat < playerCount; seat++) { - if (round < hands[seat].length) sequence.push({ seat, card: hands[seat][round], handIndex: round }); + advance() { + if (!this.alive() || !this.gs) return; + const gs = this.gs; + if (isGameOver(gs)) { this.onGameOver(); return; } + const seat = gs.currentPlayer; + this.setSpot(spotFor(this.L, seat)); + this.tellSeen = new Set(); + if (seat === 0) { + this.mode = 'human'; + this.layout({ duration: 380 }); + this.updateDock(); + this.updatePlates(); + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + } else { + this.mode = 'ai'; + this.layout(); + this.updateDock(); + this.updatePlates(); + this.runAITurn(seat); + } + } + + commit(next, { carry = null, carrySeat = null } = {}) { + const prev = this.gs; + this.gs = next; + const fresh = next.log.slice(prev.log.length); + if (this.settings.sort !== 'manual') this.sortHand(); + // new pairs wait off the pile until they've been shown in front of their player + for (const c of next.discarded.flat()) if (!prev.discarded.flat().some(p => p.id === c.id)) this.pendingPile.add(c.id); + this.layout({ + durationFor: (v) => (carry != null && v.card.id === carry ? this.timing(carrySeat).carry : null), + }); + for (const e of fresh) { + if (e.kind === 'safe') { + this.time.delayedCall(900, () => { + this.plateStamp(e.seat, 'SAFE!', '#8ce99a', 0); + this.floatText({ x: this.plates[e.seat].x, y: this.plates[e.seat].y + (e.seat === 0 ? -70 : 70) }, e.seat === 0 ? 'You\'re safe!' : 'Safe!', '#8ce99a', { size: 26, ms: 1500 }); + if (e.seat > 0) this.portraits[e.seat]?.playEmotion?.('happy'); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.55 }); + }); } } + this.observeAll(); + this.updatePlates(); + this.updateDock(); + } - const STAGGER = 70, DURATION = 180; - sequence.forEach(({ seat, card, handIndex }, idx) => { - this.time.delayedCall(idx * STAGGER, () => { - const layout = slotLayout(this.slotForSeat[seat]); - const n = hands[seat].length; - const offset = handIndex - (n - 1) / 2; - const tx = layout.handAxis === 'x' ? layout.handCenter.x + offset * HAND_SPREAD : layout.handCenter.x; - const ty = layout.handAxis === 'x' ? layout.handCenter.y : layout.handCenter.y + offset * HAND_SPREAD; - const sprite = this.makeCardSprite(card, DECK_POS.x, DECK_POS.y, { faceUp: false, rotation: layout.rotateCards }); - sprite.setDepth(D.card + 5); - this.transientObjs.push(sprite); - if (idx % 4 === 0) playSound(this, SFX.CARD_DEAL); - this.tweens.add({ - targets: sprite, x: tx, y: ty, duration: DURATION, ease: 'Cubic.easeOut', - onComplete: () => { - if (!sprite.active) return; - if (layout.handFaceUp) this.renderCardFace(sprite, card, true); - sprite.setDepth(D.card); - }, + // Hold cards up in front of a player for a moment. + async holdUp(seat, ids, ms, { caption = null, color = '#f2ead8', burst = false } = {}) { + this.showcase = { seat, ids }; + this.layout({ duration: 360 }); + await this.wait(380); + if (!this.alive()) return; + const at = showPose(this.L, seat, 0, 1); + if (caption) this.floatText({ x: at.x, y: at.y - (CARD_H / 2) * at.s - 4 }, caption, color, { size: seat === 0 ? 24 : 20, ms: ms + 300, rise: 14 }); + if (burst) { + this.burst({ x: at.x, y: at.y }, SEAT_COLORS[seat], { n: 14, r: 110 }); + this.burst({ x: at.x, y: at.y }, 0xffd35a, { n: 10, r: 70 }); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.5 }); + } + await this.wait(ms); + } + + // Show every match a draw made, one pair at a time, then let them go to the pile. + async showMatches(seat, pairs) { + for (const pair of pairs) { + const ids = pair.map(c => c.id); + const rank = pair[0].rank; + await this.holdUp(seat, ids, 1100, { caption: `${seat === 0 ? 'Your' : `${this.shortName(seat)}'s`} pair of ${RANK_NAME[rank]}!`, color: SEAT_HEX[seat], burst: true }); + if (!this.alive()) return; + } + this.showcase = null; + for (const pair of pairs) for (const c of pair) this.pendingPile.delete(c.id); + this.layout({ duration: 480 }); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.5 }); + await this.wait(480); + } + + // A player's hand gathers into a stack and spreads back out, shuffled. + async shuffleHand(seat) { + const next = applyShuffle(this.gs, seat); + if (next === this.gs) return; + this.gathering = seat; + this.layout({ duration: 200 }); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.5 }); + await this.wait(260); + if (!this.alive()) return; + this.gs = next; + this.observeAll(); + this.gathering = null; + if (seat === 0 && this.settings.sort !== 'manual') { this.settings.sort = 'manual'; this.saveSettings(); this.refreshSortButtons(); } + this.layout({ duration: 280 }); + if (seat > 0) this.floatText(handHome(this.L, seat), 'shuffles', '#e8d6b0', { size: 18, ms: 900, rise: 20 }); + await this.wait(300); + } + + newPairs(prev, next) { + const had = new Set(prev.discarded.flat().map(c => c.id)); + return next.discarded.filter(pair => !had.has(pair[0].id)); + } + + // ── AI ────────────────────────────────────────────────────────────────────── + async runAITurn(seat) { + const token = ++this.turnToken; + const T0 = this.timing(seat); + await this.wait(T0.think); + if (!this.alive() || token !== this.turnToken || this.gs.currentPlayer !== seat) return; + const from = drawTargetSeat(this.gs, seat); + observeLog(this.memories[seat], this.gs, seat); + const id = chooseDraw(this.gs, seat, this.memories[seat], this.skillFor(seat)); + if (id == null || from < 0) { this.advance(); return; } + // hesitate over a card or two (in your hand you can see which) before taking one + const hand = this.gs.players[from].hand; + const hovers = Math.min(hand.length - 1, 1 + Math.floor(Math.random() * 2)); + for (let i = 0; i < hovers; i++) { + const other = hand[Math.floor(Math.random() * hand.length)]; + if (from === 0) this.aiHover = { seat, id: other.id }; + this.layout({ duration: 140 }); + this.moveHand(seat, this.poseOf(other.id), T0.reach * 0.7); + await this.wait(T0.reach * 0.7 + T0.hesitate); + if (!this.alive() || token !== this.turnToken) return; + } + if (from === 0) this.aiHover = { seat, id }; + this.layout({ duration: 140 }); + this.moveHand(seat, this.poseOf(id), T0.reach * 0.6); + await this.wait(T0.reach * 0.6 + T0.hesitate * 0.6); + if (!this.alive() || token !== this.turnToken) return; + this.aiHover = null; + const card = this.gs.players[from].hand.find(c => c.id === id); + const next = applyDraw(this.gs, seat, id); + if (next === this.gs) { this.advance(); return; } + if (from === 0 && card?.rank === OLD_MAID_RANK) { + this.floatText({ x: CX, y: 860 }, `${this.shortName(seat)} took the Old Maid!`, '#8ce99a', { size: 26, ms: 1800 }); + this.portraits[seat]?.playEmotion?.('upset'); + } else if (from === 0) { + this.floatText({ x: CX, y: 860 }, `${this.shortName(seat)} took your ${card?.rank === 'T' ? '10' : card?.rank}`, '#f2d6a0', { size: 20, ms: 1300 }); + } + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.55 }); + const pairs = next.lastDraw?.paired ? this.newPairs(this.gs, next) : []; + if (pairs.length) this.showcase = { seat, ids: pairs[0].map(c => c.id) }; + this.commit(next, { carry: id, carrySeat: seat }); + this.moveHand(seat, pairs.length ? showPose(this.L, seat) : handHome(this.L, seat), T0.carry, 'Cubic.easeOut'); + await this.wait(T0.carry + 300); + if (!this.alive() || token !== this.turnToken) return; + this.handRest(seat, 300); + if (pairs.length) { + await this.showMatches(seat, pairs); + if (!this.alive() || token !== this.turnToken) return; + } + // careful players shuffle to hide the Old Maid + for (const s of [seat, from]) { + if (s > 0 && !this.gs.players[s].safe && !isGameOver(this.gs) && wantsShuffle(this.gs, s, this.skillFor(s))) { + await this.shuffleHand(s); + if (!this.alive() || token !== this.turnToken) return; + } + } + await this.wait(T0.between); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } + + // ── Layout ────────────────────────────────────────────────────────────────── + computeLayout() { + const gs = this.gs; + const visible = new Map(), loc = new Map(); + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + let pi = 0; + const centre = T.flat(0, 0.45, 0.7); + gs.discarded.forEach(pair => pair.forEach(c => { + if (this.pendingPile.has(c.id)) { + // waiting to be shown: stay exactly where it was (still in the hand), or out of sight + const was = this._lastVisible.get(c.id); + if (was && was.kind !== 'pile') put(c, { ...was, card: c }); + else loc.set(c.id, { pose: centre, faceUp: false, depth: D.cards }); + } else put(c, { kind: 'pile', idx: pi, pose: pilePose(c.id, pi), faceUp: true, depth: D.cards + pi * 0.005 }); + pi++; + })); + const offering = this.mode === 'human' && gs.currentPlayer === 0 && !isGameOver(gs) ? drawTargetSeat(gs, 0) : -1; + for (const p of gs.players) { + const seat = p.seat; + const n = p.hand.length; + if (seat === 0) { + const ids = this.dragPreview ?? p.hand.map(c => c.id); + ids.forEach((id, i) => { + const c = p.hand.find(h => h.id === id); + if (!c) return; + let lift = id === this.hoverId ? 24 : 0; + if (this.aiHover?.id === id) lift = 36; + const pose = this.gathering === 0 ? handPose(this.L, 0, (n - 1) / 2, n) : handPose(this.L, 0, i, ids.length, lift); + put(c, { kind: 'hand', seat: 0, idx: i, pose, faceUp: true, depth: D.hand + i * 0.01 }); }); + } else if (seat === offering) { + // held out toward you, face down, big enough to pick from + p.hand.forEach((c, i) => { + const lift = this.offerHover === c.id ? 30 : 0; + put(c, { kind: 'offer', seat, idx: i, pose: offerPose(i, n, lift), faceUp: false, depth: D.hand - 2 + i * 0.01 }); + }); + } else { + p.hand.forEach((c, i) => { + const pose = this.gathering === seat ? handPose(this.L, seat, (n - 1) / 2, n) : handPose(this.L, seat, i, n); + put(c, { kind: 'hand', seat, idx: i, pose, faceUp: this.revealSeat === seat, depth: D.oppHand + i * 0.01 }); + }); + } + } + // a match (or a freshly drawn card) held up in front of its player + if (this.showcase) { + const byId = new Map(); + for (const c of [...gs.discarded.flat(), ...gs.players.flatMap(p => p.hand)]) byId.set(c.id, c); + const { seat, ids } = this.showcase; + ids.forEach((id, i) => { + const c = byId.get(id); + if (c) put(c, { kind: 'show', seat, pose: showPose(this.L, seat, i, ids.length), faceUp: true, depth: D.float - 4 + i * 0.01 }); }); - }); - - const doneAt = (sequence.length - 1) * STAGGER + DURATION + 250; - this.time.delayedCall(doneAt, () => { - this.gs = finalState; - this.renderAll(); - const initialPairs = (finalState.initialDealPairs ?? []).filter((e) => e.pairedCards.length >= 2); - if (initialPairs.length > 0) { - this.playInitialDealPairs(initialPairs, 0, () => { this.animating = false; this.beginTurn(); }); - } else { - this.animating = false; - this.beginTurn(); - } - }); - } - - playInitialDealPairs(pairs, idx, onComplete) { - if (idx >= pairs.length) { onComplete(); return; } - const { seat, pairedCards } = pairs[idx]; - const rank = pairedCards[0].rank === 'T' ? '10' : pairedCards[0].rank; - const count = pairedCards.length / 2; - this.showBanner(`${this.opponentName(seat)} discards ${count > 1 ? count + ' starting pairs' : 'a starting pair'} of ${rank}s`); - this.animatePairDiscard(seat, pairedCards, () => { - this.hideBanner(); - this.time.delayedCall(200, () => this.playInitialDealPairs(pairs, idx + 1, onComplete)); - }); - } - - // ── Card sprite factory ─────────────────────────────────────────────────── - - makeCardSprite(card, x, y, { faceUp = true, rotation = 0, scale = 1 } = {}) { - const c = this.add.container(x, y).setDepth(D.card); - c.setRotation((rotation * Math.PI) / 180); - c.setScale(scale); - this.renderCardFace(c, card, faceUp); - c.card = card; - return c; - } - - renderCardFace(container, card, faceUp) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - - if (!faceUp) { - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - g.destroy(); - container.add(this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex).setDisplaySize(CARD_W, CARD_H).setOrigin(0.5)); - } else { - 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, COLORS.accent, 0.6); - g.strokeRoundedRect(x + 6, y + 6, CARD_W - 12, CARD_H - 12, CARD_R - 2); - g.lineStyle(1, 0xffffff, 0.15); - g.strokeRoundedRect(x + 10, y + 10, CARD_W - 20, CARD_H - 20, CARD_R - 4); - container.add(g); - } - return; } - - const frame = OLDMAID_CARD_FRAME[card.rank]; - if (frame !== undefined && this.textures.exists('oldmaid-cards')) { - g.destroy(); - container.add(this.add.image(0, 0, 'oldmaid-cards', frame).setDisplaySize(CARD_W, CARD_H).setOrigin(0.5)); - return; - } - - const suit = SUIT_COLORS[card.suit] ?? SUIT_COLORS.s; - g.fillStyle(suit.fill, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, suit.stroke, 1); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - const labelStyle = (sz) => ({ fontFamily: 'Righteous', fontSize: `${sz}px`, color: suit.glyph }); - container.add(this.add.text(x + 8, y + 6, card.label, labelStyle(20))); - container.add(this.add.text(x + 8, y + 28, card.suitSymbol, labelStyle(20))); - container.add(this.add.text(0, 0, card.suitSymbol, labelStyle(54)).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 8, y + CARD_H - 8, card.label, labelStyle(20)).setOrigin(1, 1)); - } - - clearAllCardObjs() { - for (const c of this.cardObjs.values()) c.destroy(); - this.cardObjs.clear(); - for (const o of this.transientObjs) o.destroy(); - this.transientObjs = []; - } - - // ── Rendering ───────────────────────────────────────────────────────────── - - handCardPos(seat, index, n, layout) { - const offset = index - (n - 1) / 2; - if (layout.handAxis === 'x') return { x: layout.handCenter.x + offset * HAND_SPREAD, y: layout.handCenter.y }; - return { x: layout.handCenter.x, y: layout.handCenter.y + offset * HAND_SPREAD }; - } - - renderAll() { - this.clearAllCardObjs(); - const drawTarget = (!this.gameOver && this.isLocalTurn()) ? drawTargetSeat(this.gs, 0) : -1; - for (let seat = 0; seat < this.gs.players.length; seat++) { - this.renderSeat(seat, seat === drawTarget); - } - this.renderSeatChips(); - this.renderTurnIndicator(); - this.updateStatus(); - } - - renderSeat(seat, isDrawTarget) { - const player = this.gs.players[seat]; - const layout = slotLayout(this.slotForSeat[seat]); - const n = player.hand.length; - for (let i = 0; i < n; i++) { - const card = player.hand[i]; - const { x, y } = this.handCardPos(seat, i, n, layout); - const c = this.makeCardSprite(card, x, y, { faceUp: layout.handFaceUp, rotation: layout.rotateCards }); - this.cardObjs.set(`hand-${seat}-${card.id}`, c); - - if (isDrawTarget) { - // The human's draw target — its face-down cards are clickable. - c.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - c.input.cursor = 'pointer'; - const baseY = y; - c.on('pointerover', () => { - if (this.animating) return; - this.tweens.add({ targets: c, scaleX: 1.08, scaleY: 1.08, duration: 100 }); - c.setDepth(D.highlight); - }); - c.on('pointerout', () => { - this.tweens.add({ targets: c, scaleX: 1, scaleY: 1, duration: 100, y: baseY }); - c.setDepth(D.card); - }); - c.on('pointerdown', () => this.onNeighborCardClick(seat, card.id)); + if (this.revealId != null) { + for (const p of gs.players) { + const c = p.hand.find(h => h.id === this.revealId); + if (c) put(c, { kind: 'reveal', pose: { x: REVEAL.x, y: REVEAL.y, rot: -0.05, s: REVEAL.s, q: 1 }, faceUp: true, depth: D.float - 1 }); } } + return { visible, loc }; } - renderSeatChips() { - for (let s = 0; s < this.gs.players.length; s++) { + decorate(c, v) { + c.mark.setVisible(false); + c.chip.setVisible(false); + c.glow.setVisible(v.kind === 'offer' && this.offerHover === v.card.id).setTint(0xffd35a).setAlpha(1); + c.faceImg.setTint(0xffffff); + } + + afterLayout() { + for (let s = 1; s < this.playerCount; s++) { const p = this.gs.players[s]; - const chip = this.seatChips[s]; - if (!chip) continue; - chip.count.setText(p.safe ? 'SAFE ✓' : `${p.discardPairs}`); - chip.count.setColor(p.safe ? COLORS.goldHex : COLORS.accentHex); + this.badges[s]?.t.setText(p.safe ? '✓' : String(p.hand.length)); } } - renderTurnIndicator() { - const seat = this.gs.currentPlayer; - const lay = slotLayout(this.slotForSeat[seat]); - if (!this.turnGlow) this.turnGlow = this.add.circle(0, 0, 70, COLORS.accent, 0.18).setDepth(D.portrait - 1); - this.turnGlow.setPosition(lay.portrait.x, lay.portrait.y).setVisible(!this.gameOver); - } - - // ── Status / banner ───────────────────────────────────────────────────────── - - updateStatus() { - if (this.gameOver) { this.statusText.setText(''); this.statusBg.setVisible(false); return; } - if (this.isLocalTurn()) { - const target = drawTargetSeat(this.gs, 0); - this.statusText.setText(target === -1 ? 'Your turn…' : `Your turn — draw a card from ${this.opponentName(target)}.`); - } else { - this.statusText.setText(`${this.opponentName(this.gs.currentPlayer)} is thinking…`); + updatePlates() { + if (!this.gs) return; + const gs = this.gs; + for (let s = 0; s < this.playerCount; s++) { + const pl = this.plates[s]; + const p = gs.players[s]; + pl.scoreTxt.setText(`OM ×${this.timesStuck(s)}`); + pl.infoTxt.setText(p.safe ? 'Safe!' : `${p.hand.length} card${p.hand.length === 1 ? '' : 's'}`).setColor(p.safe ? '#8ce99a' : COLORS.goldHex); + pl.statusTxt.setText(`${p.discardPairs} pairs`).setColor('#e8d6b0'); + this.setPlateActive(s, !isGameOver(gs) && gs.currentPlayer === s && (this.mode === 'human' || this.mode === 'ai')); } - this.refreshStatusBg(); } - refreshStatusBg() { - const t = this.statusText, pad = 8; - this.statusBg.clear(); - this.statusBg.fillStyle(0x000000, 0.55); - this.statusBg.fillRoundedRect(t.x - pad, t.y - t.height - pad, t.width + pad * 2, t.height + pad * 2, 6); - this.statusBg.setVisible(true); + // ── Dock ──────────────────────────────────────────────────────────────────── + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const shuffle = { label: 'Shuffle (Space)', act: () => this.humanShuffle(), enabled: gs.players[0].hand.length > 1 && this.mode !== 'deal' && this.mode !== 'ending' && this.mode !== 'summary' }; + if (this.mode === 'deal') { this.setDock('Dealing out the whole deck — pairs go straight in.'); return; } + if (this.mode === 'ending' || this.mode === 'summary') { this.setDock('Game over.'); return; } + if (this.mode === 'human') { + const from = drawTargetSeat(gs, 0); + this.setDock(`Draw a card from ${this.shortName(from)}. ${this.settings.tells ? 'Hover a card — watch their face.' : ''}`, [ + { label: 'Draw blind (D)', act: () => this.drawRandom() }, + shuffle, + ]); + return; + } + if (gs.players[0].safe) { this.setDock('You\'re safe! Watching to see who ends up with the Old Maid…'); return; } + this.setDock(`${this.nameForSeat(gs.currentPlayer)} is drawing…`, [shuffle]); } - showBanner(text) { - this.bannerText.setText(text).setVisible(true); - this.bannerBg.clear(); - this.bannerBg.fillStyle(COLORS.panel, 0.85); - const w = Math.max(this.bannerText.width + 60, 360); - const h = this.bannerText.height + 28; - this.bannerBg.fillRoundedRect(this.bannerText.x - w / 2, this.bannerText.y - h / 2, w, h, 10); - this.bannerBg.lineStyle(2, COLORS.accent, 1); - this.bannerBg.strokeRoundedRect(this.bannerText.x - w / 2, this.bannerText.y - h / 2, w, h, 10); - this.bannerBg.setVisible(true); + // ── Human actions ─────────────────────────────────────────────────────────── + sortHand() { + if (!this.gs || this.settings.sort === 'manual') return; + this.gs.players[0].hand.sort((a, b) => RANK_ORDER.indexOf(a.rank) - RANK_ORDER.indexOf(b.rank) || a.id - b.id); } - hideBanner() { - this.bannerText?.setVisible(false); - this.bannerBg?.setVisible(false); - } - - // ── Turn flow ──────────────────────────────────────────────────────────────── - - isLocalTurn() { - return !this.gameOver && this.gs && this.gs.currentPlayer === 0; - } - - opponentName(seat) { - if (seat === 0) return 'You'; - return this.opponents[seat - 1]?.name ?? `P${seat + 1}`; - } - - skillForSeat(seat) { - return this.opponents[seat - 1]?.skill ?? 3; - } - - beginTurn() { - if (this.gameOver) return; - if (isGameOver(this.gs)) { this.endGame(); return; } - if (this.isLocalTurn()) { this.updateStatus(); return; } - const seat = this.gs.currentPlayer; - const [lo, hi] = profileFor(this.skillForSeat(seat)).delay; - const delay = lo + Math.random() * (hi - lo); - this.time.delayedCall(delay, () => this.runAITurn()); - } - - runAITurn() { - if (this.gameOver || this.animating) return; - const seat = this.gs.currentPlayer; - if (seat === 0) return; - observeLog(this.aiMemory[seat], this.gs, seat); - if (!canDraw(this.gs, seat)) { this.endGame(); return; } - const cardId = chooseDraw(this.gs, seat, this.aiMemory[seat], this.skillForSeat(seat)); - if (cardId == null) { this.endGame(); return; } - this.executeDraw(seat, cardId); - } - - onNeighborCardClick(targetSeat, cardId) { - if (!this.isLocalTurn() || this.animating) return; - if (drawTargetSeat(this.gs, 0) !== targetSeat) return; - this.executeDraw(0, cardId); - } - - executeDraw(drawerSeat, cardId) { - this.animating = true; - const before = this.gs; - const targetSeat = drawTargetSeat(before, drawerSeat); - const after = applyDraw(before, drawerSeat, cardId); - if (after === before) { this.animating = false; return; } - const last = after.lastDraw; - - // Grab the on-screen sprite of the drawn card from the target's hand. - const startSprite = this.cardObjs.get(`hand-${targetSeat}-${cardId}`); - const drawerLayout = slotLayout(this.slotForSeat[drawerSeat]); - const startX = startSprite?.x ?? slotLayout(this.slotForSeat[targetSeat]).handCenter.x; - const startY = startSprite?.y ?? slotLayout(this.slotForSeat[targetSeat]).handCenter.y; - - // Detach the start sprite so renderAll's clear doesn't kill mid-flight; use a fresh flyer. - const flyer = this.makeCardSprite(last.card, startX, startY, { - faceUp: targetSeat === 0, // only the human's hand was face-up - rotation: slotLayout(this.slotForSeat[targetSeat]).rotateCards, - }); - flyer.setDepth(D.banner - 4); - this.transientObjs.push(flyer); - if (startSprite) { startSprite.destroy(); this.cardObjs.delete(`hand-${targetSeat}-${cardId}`); } + canAct() { return this.mode === 'human' && !this.modal && !this.paused && !this.busy; } + async draw(id) { + if (!this.canAct()) return; + const from = drawTargetSeat(this.gs, 0); + const card = this.gs.players[from]?.hand.find(c => c.id === id); + const next = applyDraw(this.gs, 0, id); + if (next === this.gs) return; + this.busy = true; + this.mode = 'idle'; + this.offerHover = null; playSound(this, SFX.CARD_DEAL); - this.showBanner(`${this.opponentName(drawerSeat)} draws from ${this.opponentName(targetSeat)}`); - - const destRot = (drawerLayout.rotateCards * Math.PI) / 180; - this.tweens.add({ - targets: flyer, - x: drawerLayout.handCenter.x, y: drawerLayout.handCenter.y, - rotation: destRot, duration: 420, ease: 'Cubic.easeOut', - onComplete: () => { - // Reveal to the human when they drew; hide when an AI took a face-up card. - if (drawerSeat === 0) this.flipCardFaceUp(flyer, last.card); - else if (targetSeat === 0) this.flipCardFaceDown(flyer); - this.time.delayedCall(drawerSeat === 0 || targetSeat === 0 ? 320 : 120, () => { - this.commitDraw(after, drawerSeat, targetSeat, last, flyer); - }); - }, - }); - } - - commitDraw(after, drawerSeat, targetSeat, last, flyer) { - if (flyer?.active) flyer.destroy(); - this.gs = after; - for (let s = 0; s < this.gs.players.length; s++) observeLog(this.aiMemory[s], this.gs, s); - - // React to receiving the Old Maid. - if (last.card.isOldMaid && drawerSeat !== 0) this.opponentPortraits[drawerSeat]?.playEmotion('upset'); - - const finish = () => { - this.hideBanner(); - this.renderAll(); - if (isGameOver(this.gs)) { this.animating = false; this.endGame(); return; } - this.animating = false; - this.beginTurn(); - }; - - if (last.paired) { - this.renderAll(); // paired cards already removed from hand state - if (drawerSeat !== 0) this.opponentPortraits[drawerSeat]?.playEmotion('happy'); - this.animatePairDiscard(drawerSeat, last.pairedCards, finish); - } else { - finish(); + const pairs = next.lastDraw?.paired ? this.newPairs(this.gs, next) : []; + // the card you drew is held up first, face up, so you can see what you got + this.showcase = { seat: 0, ids: [id] }; + this.commit(next); + const isOM = card?.rank === OLD_MAID_RANK; + const name = isOM ? 'the Old Maid' : `${/^[A8]/.test(card.rank) ? 'an' : 'a'} ${card.rank === 'T' ? '10' : { A: 'Ace', J: 'Jack', Q: 'Queen', K: 'King' }[card.rank] ?? card.rank}`; + await this.holdUp(0, [id], 1000, { caption: `You drew ${name}${pairs.length ? ' — a match!' : ''}`, color: isOM ? '#ff8a7a' : '#f2ead8' }); + if (!this.alive()) return; + if (isOM) { + this.stamp('The Old Maid!', { x: CX, y: CY - 30 }, '#ff8a7a', { size: 64, sub: 'Pass her on before the end…', hold: 1300 }); + this.cameras.main.shake(200, 0.005); + if (from > 0) this.portraits[from]?.playEmotion?.('happy'); } - } - - flipCardFaceUp(container, card) { - this.tweens.add({ - targets: container, scaleX: 0, duration: 150, ease: 'Linear', - onComplete: () => { - container.setRotation(0); - this.renderCardFace(container, card, true); - this.tweens.add({ targets: container, scaleX: 1, duration: 150, ease: 'Linear' }); - }, - }); - } - - flipCardFaceDown(container) { - this.tweens.add({ - targets: container, scaleX: 0, duration: 150, ease: 'Linear', - onComplete: () => { - this.renderCardFace(container, container.card, false); - this.tweens.add({ targets: container, scaleX: 1, duration: 150, ease: 'Linear' }); - }, - }); - } - - animatePairDiscard(seat, pairedCards, onComplete) { - const layout = slotLayout(this.slotForSeat[seat]); - const n = pairedCards.length; - const GAP = 10; - const totalW = n * CARD_W + (n - 1) * GAP; - const sprites = []; - for (let i = 0; i < n; i++) { - let tx, ty; - switch (this.slotForSeat[seat]) { - case 'bottom': tx = CX - totalW / 2 + CARD_W / 2 + i * (CARD_W + GAP); ty = layout.handCenter.y - CARD_H - GAP; break; - case 'top': tx = CX - totalW / 2 + CARD_W / 2 + i * (CARD_W + GAP); ty = layout.handCenter.y + CARD_H + GAP; break; - case 'left': tx = layout.handCenter.x + CARD_H / 2 + GAP + CARD_W / 2 + i * (CARD_W + GAP); ty = CY; break; - case 'right': tx = layout.handCenter.x - CARD_H / 2 - GAP - CARD_W / 2 - (n - 1 - i) * (CARD_W + GAP); ty = CY; break; - default: tx = CX; ty = CY; - } - const sprite = this.makeCardSprite(pairedCards[i], CX, CY, { faceUp: true }); - sprite.setDepth(D.banner - 5).setAlpha(0); - this.transientObjs.push(sprite); - this.tweens.add({ targets: sprite, x: tx, y: ty, alpha: 1, duration: 300, ease: 'Back.easeOut' }); - sprites.push({ sprite, tx, ty }); + if (pairs.length) await this.showMatches(0, pairs); + else { + this.showcase = null; + this.layout({ duration: 380 }); + this.flashGlow(id, 0x7cf0a0, { delay: 380, hold: 700 }); + await this.wait(420); } - playSound(this, SFX.CARD_PLACE); - this.time.delayedCall(350, () => { - const cx = sprites.reduce((s, o) => s + o.tx, 0) / sprites.length; - const cy = sprites.reduce((s, o) => s + o.ty, 0) / sprites.length; - this.spawnFireworks(cx, cy); - }); - this.time.delayedCall(1200, () => { - for (const { sprite } of sprites) { - if (!sprite.active) continue; - this.tweens.add({ targets: sprite, x: CX, y: CY, alpha: 0, duration: 450, ease: 'Cubic.easeIn', onComplete: () => { if (sprite.active) sprite.destroy(); } }); - } - }); - this.time.delayedCall(1700, onComplete); + if (!this.alive()) return; + // the player you drew from may shuffle to hide what's left + if (this.alive() && from > 0 && !this.gs.players[from].safe && !isGameOver(this.gs) && wantsShuffle(this.gs, from, this.skillFor(from))) await this.shuffleHand(from); + this.busy = false; + if (!this.alive()) return; + this.advance(); } - spawnFireworks(cx, cy) { - const BURST_COLORS = [0xd4a017, 0xe06c75, 0x61afef, 0xc678dd, 0x98c379, 0xe5c07b]; - const COUNT = 18; - for (let i = 0; i < COUNT; i++) { - const angle = (i / COUNT) * Math.PI * 2; - const dist = 60 + Math.random() * 70; - const g = this.add.graphics().setDepth(D.banner - 2); - g.fillStyle(BURST_COLORS[i % BURST_COLORS.length], 1); - g.fillCircle(0, 0, 3 + Math.random() * 4); - g.setPosition(cx, cy); - this.transientObjs.push(g); - this.tweens.add({ - targets: g, x: cx + Math.cos(angle) * dist, y: cy + Math.sin(angle) * dist, alpha: 0, - duration: 600 + Math.random() * 300, ease: 'Quad.easeOut', - onComplete: () => { if (g.active) g.destroy(); }, - }); + drawRandom() { + if (!this.canAct()) return; + const from = drawTargetSeat(this.gs, 0); + const hand = this.gs.players[from]?.hand ?? []; + if (hand.length) this.draw(hand[Math.floor(Math.random() * hand.length)].id); + } + + async humanShuffle() { + if (this.busy || this.modal || this.gs.players[0].hand.length < 2) return; + if (this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + this.busy = true; + await this.shuffleHand(0); + this.busy = false; + this.floatText({ x: CX, y: 860 }, 'Shuffled — nobody can track your Old Maid now', '#f2d6a0', { size: 18, ms: 1400 }); + } + + // Hovering a card in the hand held out to you can draw a reaction. + showTell(id) { + if (!this.settings.tells || this.tellSeen.has(id)) return; + this.tellSeen.add(id); + const from = drawTargetSeat(this.gs, 0); + if (from < 1) return; + const card = this.gs.players[from].hand.find(c => c.id === id); + const tell = tellFor(card?.rank === OLD_MAID_RANK, this.skillFor(from)); + if (!tell) return; + const at = tellAt(this.L, from); + const t = this.add.text(at.x, at.y, tell === 'hopeful' ? '😏' : '😬', { fontFamily: 'sans-serif', fontSize: '44px' }) + .setOrigin(0.5).setDepth(D.float).setScale(0.3); + this.tweens.add({ targets: t, scale: 1, duration: 160, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, y: at.y - 20, delay: 900, duration: 300, onComplete: () => t.destroy() }); + } + + // ── Input ────────────────────────────────────────────────────────────────── + setupInput() { + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + } + + heldIds() { return this.gs.players[0].hand.map(c => c.id); } + + handIdAt(pt) { + const ids = this.heldIds(); + const i = fanHit(this.L.seats[0].fan, ids.length, pt, (k) => (ids[k] === this.hoverId ? 24 : 0)); + return i >= 0 ? ids[i] : null; + } + + offerIdAt(pt) { + if (this.mode !== 'human') return null; + const from = drawTargetSeat(this.gs, 0); + const hand = this.gs.players[from]?.hand ?? []; + const i = fanHit(OFFER_FAN, hand.length, pt, (k) => (hand[k]?.id === this.offerHover ? 30 : 0)); + return i >= 0 ? hand[i].id : null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState || this.overUI(over)) return; + const off = this.offerIdAt(pointer); + if (off != null) { this.draw(off); return; } + if (this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const id = this.handIdAt(pointer); + if (id != null) this.potentialDrag = { id, x: pointer.x, y: pointer.y }; + } + + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.x, dy = pointer.y - this.potentialDrag.y; + if (dx * dx + dy * dy > 64) this.startDrag(pointer); + return; } - } - - // ── Game over ──────────────────────────────────────────────────────────────── - - endGame() { - if (this.gameOver) return; - this.gameOver = true; - this.animating = false; - this.hideBanner(); - this.renderAll(); - - const loser = this.gs.loserSeat; - const humanLost = loser === 0; - if (loser > 0) this.opponentPortraits[loser]?.playEmotion('upset'); - this.recordResult(humanLost ? 'loss' : 'win'); - - const lines = []; - if (humanLost) { - lines.push('You got stuck with the Old Maid!', 'Better luck next time.'); - } else { - lines.push(`${this.opponentName(loser)} is stuck with the Old Maid!`, 'You got away safe. 🎉'); + if (pointer.isDown || this.modal || !this.gs) return; + const off = this.offerIdAt(pointer); + if (off !== this.offerHover) { + this.offerHover = off; + this.layout({ duration: 120 }); + if (off != null) this.showTell(off); } - - const cx = CX, cy = CY; - const overlay = this.add.rectangle(cx, cy, 760, 300, 0x0a0e14, 0.92).setStrokeStyle(3, COLORS.accent).setDepth(D.modal); - const txt = this.add.text(cx, cy - 40, lines.join('\n'), { - fontFamily: '"Julius Sans One"', fontSize: '30px', - color: humanLost ? COLORS.textHex : '#ffd700', align: 'center', - }).setOrigin(0.5).setDepth(D.modal + 1); - const again = new Button(this, cx - 100, cy + 80, 'Play Again', () => { - overlay.destroy(); txt.destroy(); again.destroy(); leave.destroy(); this.startNewMatch(); - }, { width: 170, fontSize: 22 }).setDepth(D.modal + 1); - const leave = new Button(this, cx + 100, cy + 80, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 170, fontSize: 22 }).setDepth(D.modal + 1); + const id = off == null ? this.handIdAt(pointer) : null; + if (id !== this.hoverId) { this.hoverId = id; this.layout({ duration: 120 }); } + this.input.setDefaultCursor(off != null ? 'pointer' : id != null ? 'grab' : 'default'); } - async recordResult(result) { - try { - const score = result === 'win' ? 100 : 0; - await api.post('/history/single-player', { slug: 'oldmaid', score, opponentScores: [], result }); - } catch { /* best effort */ } + onPointerUp() { + if (this.dragState) { this.endDrag(); return; } + this.potentialDrag = null; + } + + startDrag(pointer) { + const pd = this.potentialDrag; + this.potentialDrag = null; + const c = this.sprites.get(pd.id); + if (!c) return; + c._tw?.stop(); + c._tw = null; + c.setDepth(D.drag); + this.dragState = { id: pd.id, offX: c.pose.x - pd.x, offY: c.pose.y - pd.y, sprite: c, target: null, previewKey: '' }; + this.hoverId = null; + this.input.setDefaultCursor('grabbing'); + this.updateDrag(pointer); + } + + updateDrag(pointer) { + const ds = this.dragState; + this.applyPose(ds.sprite, { x: pointer.x + ds.offX, y: pointer.y + ds.offY, rot: 0, s: 1, q: 1 }, 1); + const ids = this.heldIds(); + ds.target = inRect(pointer, fanZone(this.L.seats[0].fan, ids.length)) ? { at: fanInsertIndex(this.L.seats[0].fan, ids.length, pointer.x) } : null; + const order = ds.target ? CardTableScene.reorderPreview(ids, ds.id, ds.target.at) : null; + const key = order ? order.join(',') : ''; + if (key !== ds.previewKey) { + ds.previewKey = key; + this.dragPreview = order; + this.layout({ duration: 150 }); + } + if (order) { + const idx = order.indexOf(ds.id); + this.drawDropSlot(handPose(this.L, 0, idx, order.length), D.hand + idx * 0.01 - 0.004); + } else this.drawDropSlot(null); + } + + cancelDrag() { + if (!this.dragState) return; + this.dragState = null; + this.dragPreview = null; + this.drawDropSlot(null); + this.layout(); + } + + endDrag() { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.drawDropSlot(null); + this.dragPreview = null; + if (ds.target) { + const order = CardTableScene.reorderPreview(this.heldIds(), ds.id, ds.target.at); + const hand = this.gs.players[0].hand; + const byId = new Map(hand.map(c => [c.id, c])); + const changed = order.join(',') !== hand.map(c => c.id).join(','); + hand.splice(0, hand.length, ...order.map(id => byId.get(id))); + if (changed && this.settings.sort !== 'manual') { this.settings.sort = 'manual'; this.saveSettings(); this.refreshSortButtons(); } + } + this.layout(); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) this.openPause(); + return; + } + if (this.modal) { if (e.code === 'Enter') this.modal.onEnter?.(); return; } + if (this.dragState) return; + const k = e.key?.toLowerCase(); + if (e.code === 'Space') { e.preventDefault?.(); this.humanShuffle(); return; } + if (k === 'd') this.drawRandom(); + else if (k === 's') { this.settings.sort = this.settings.sort === 'rank' ? 'manual' : 'rank'; this.saveSettings(); this.refreshSortButtons(); this.sortHand(); this.layout(); } + else if (k === 'h') this.flashHint(); + } + + flashHint() { + if (!this.gs) return; + const mine = this.gs.players[0].hand.some(c => c.rank === OLD_MAID_RANK); + const text = this.mode === 'human' + ? 'It\'s a blind draw — hover the cards and read their face. Beginners give it away; experts bluff.' + : mine ? 'You hold the Old Maid — shuffle (Space) so nobody can track her.' : 'Sit tight — and remember who took what.'; + this.floatText({ x: CX, y: 860 }, text, '#7cf0a0', { size: 20, ms: 2600, rise: 20 }); + } + + // ── Menus ─────────────────────────────────────────────────────────────────── + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Tally', act: () => { this.closeModal(); this.openScorePad({ readOnly: true }); } }, + { label: 'How to play', act: () => { this.closeModal(); this.openRules(); } }, + { label: 'New game', ghost: true, act: () => this.confirm('Start a new game?', 'This game will be thrown out.', 'New game', () => this.restart()) }, + { label: 'Leave parlour', ghost: true, act: () => this.onLeave() }, + ]); + } + + openSettings(onDone = null) { + const s = this.settings; + this.openSettingsModal([ + { label: 'Opponent pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } }, + { label: 'Show opponents\' tells', options: [[false, 'Off'], [true, 'On']], get: () => s.tells, set: (v) => { s.tells = v; this.updateDock(); } }, + { label: 'Hand order', options: [['rank', 'Rank'], ['manual', 'Mine']], get: () => s.sort, set: (v) => { s.sort = v; this.refreshSortButtons(); this.sortHand(); this.layout(); } }, + ], { note: 'Low-skill opponents give honest tells; skilled ones bluff. Their hands move at their skill\'s speed.', onDone }); + } + + openRules() { + const h = 560; + this.openModal({ w: 900, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 54, 'How to play', { fontFamily: 'Righteous', fontSize: '38px', color: COLORS.goldHex }); + const lines = [ + 'The whole deck is dealt out, plus one odd card: the Old Maid.', + 'Any pairs in your hand go straight into the middle.', + 'On your turn, draw one card blind from the next player\'s hand.', + 'Make a pair? It goes in too. Run out of cards and you\'re safe.', + 'The Old Maid never pairs — whoever holds her at the end loses.', + 'Shuffle your hand so nobody can tell where she is.', + 'Watch faces when you hover: beginners give it away, experts bluff.', + ]; + lines.forEach((l, i) => this.addToModal(this.add.text(CX - 410, top + 122 + i * 46, l, { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1))); + this.modalButton(CX, top + h - 46, 'Back to the table', () => this.closeModal(), { width: 280, height: 46, fontSize: 18 }); + } + + onLeave() { + const inGame = this.mode === 'human' || this.mode === 'ai'; + if (!inGame) { this.scene.start('GameMenu'); return; } + this.confirm('Leave the parlour?', 'This game will be lost.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay' }); + } + + restart() { + this.closeModal(); + this.scene.restart({ game: this.gameDef, opponents: this.opponents, playfield: this.playfield, cardBack: this.cardBack }); + } + + openScorePad({ result = false, readOnly = false } = {}) { + if (!this.gs) return; + const gs = this.gs; + let title; + if (readOnly || !isGameOver(gs)) title = 'Who got stuck with her'; + else title = gs.loserSeat === 0 ? 'You\'re the Old Maid!' : `${this.nameForSeat(gs.loserSeat)} is the Old Maid`; + const least = Math.min(...gs.players.map((_, s) => this.timesStuck(s))); + const rows = gs.players.map((p, s) => ({ + seat: s, color: SEAT_COLORS[s], name: this.shortName(s, 14), + cells: this.history.map(h => (h.loser === s ? { text: 'OM', color: '#b8231f' } : { text: `${h.order[s] + 1}`, color: '#1c3f8f', mark: 'safe', markColor: '#6c6450' })), + total: this.timesStuck(s), totalColor: this.timesStuck(s) === least ? '#1e7a3b' : '#22201a', + circled: result && s === gs.loserSeat, + })); + const buttons = readOnly ? [{ label: 'Back to the table', act: () => this.closeModal() }] : [ + { label: 'Play again', act: () => this.playAgain(), hot: true }, + { label: 'Settings', ghost: true, act: () => { this.closeModal(); this.openSettings(() => this.openScorePad({ result })); } }, + { label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }, + ]; + this.openScorePadModal({ + title, titleColor: result && gs.loserSeat === 0 ? '#b8231f' : '#22201a', + sub: 'Each game: the order players got safe, or OM for whoever was left holding her · total = times stuck', + columns: this.history.map((_, i) => `G${i + 1}`), + rows, writeLast: !!result, buttons, readOnly, + onEnter: readOnly ? null : () => this.playAgain(), + }); + } + + async playAgain() { + this.closeModal(); + if (this.mode !== 'summary') return; + this.mode = 'deal'; + this.revealId = null; + this.revealSeat = null; + this.showcase = null; + this.updateDock(); + await this.sweepCards(T.flat(0, 0.45, 0.7)); + if (!this.alive()) return; + this.newGame(); + } + + // ── The reveal ───────────────────────────────────────────────────────────── + async onGameOver() { + if (this.mode === 'ending' || this.mode === 'summary') return; + this.mode = 'ending'; + this.turnToken++; + this.cancelDrag(); + this.input.setDefaultCursor('default'); + this.updateDock(); + const gs = this.gs; + const loser = gs.loserSeat; + await this.wait(700); + if (!this.alive()) return; + const om = gs.players[loser]?.hand.find(c => c.rank === OLD_MAID_RANK); + if (om) { + this.revealId = om.id; + this.layout({ duration: 700 }); + playSoundEx(this, SFX.CARD_SHOW, { volume: 0.8, rate: 0.8 }); + } + await this.wait(800); + if (!this.alive()) return; + this.stamp(loser === 0 ? 'You\'re the Old Maid!' : `${this.shortName(loser, 14)} is the Old Maid!`, { x: CX, y: CY + 170 }, loser === 0 ? '#ff8a7a' : SEAT_HEX[loser], { size: 62, hold: 1800 }); + this.cameras.main.shake(260, 0.006); + playSound(this, loser === 0 ? SFX.CASINO_LOSE : SFX.CASINO_WIN); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(s === loser ? 'loss' : 'win'); + await this.wait(2200); + if (!this.alive()) return; + const order = gs.players.map(p => (p.finishOrder ?? gs.players.length)); + this.history.push({ loser, order }); + this.updatePlates(); + this.recordResult('oldmaid', { + score: this.timesStuck(0), opponentScores: gs.players.slice(1).map((_, i) => this.timesStuck(i + 1)), won: loser !== 0, + }); + this.mode = 'summary'; + this.openScorePad({ result: true }); } } + +export { CARD_W, CARD_H, SQ }; diff --git a/src/games/oldmaid/OldMaidLogic.js b/src/games/oldmaid/OldMaidLogic.js index aa6f068..02b0605 100644 --- a/src/games/oldmaid/OldMaidLogic.js +++ b/src/games/oldmaid/OldMaidLogic.js @@ -79,6 +79,7 @@ export function cloneState(state) { turnCount: state.turnCount, finishCounter: state.finishCounter, seed: state.seed, + discarded: (state.discarded ?? []).map((pair) => pair.map(cloneCard)), }; } @@ -109,6 +110,7 @@ export function createInitialState({ playerCount = 4, seed } = {}) { finishCounter: 0, seed: seed ?? null, initialDealPairs: [], + discarded: [], // every pair thrown in so far (card objects) }; // Discard any pairs dealt into the opening hands. @@ -149,6 +151,7 @@ export function discardPairs(player, state) { player.hand = player.hand.filter((c) => !idsToRemove.has(c.id)); player.discardPairs += 1; collected += 1; + if (state) (state.discarded ??= []).push(group.map(cloneCard)); if (state) state.log.push({ kind: 'pair', seat: player.seat, rank: foundRank }); } return { count: collected, pairedCards }; @@ -258,6 +261,28 @@ function checkGameOver(state) { } } +/** + * Shuffle a player's hand (hides where the Old Maid sits). Logged so the other + * players' memories can forget positions they'd been tracking. + */ +export function applyShuffle(state, seat, rand = Math.random) { + const p = state.players[seat]; + if (!p || p.hand.length < 2) return state; + const next = cloneState(state); + const hand = next.players[seat].hand; + for (let i = hand.length - 1; i > 0; i--) { + const j = Math.floor(rand() * (i + 1)); + [hand[i], hand[j]] = [hand[j], hand[i]]; + } + next.log.push({ kind: 'shuffle', seat }); + return next; +} + +/** Every card in the game — hands plus discarded pairs (53 with the Old Maid). */ +export function countCards(state) { + return state.players.reduce((n, p) => n + p.hand.length, 0) + (state.discarded ?? []).reduce((n, pr) => n + pr.length, 0); +} + export function isGameOver(state) { return state.phase === 'gameOver'; } diff --git a/src/games/oldmaid/OldMaidTable.js b/src/games/oldmaid/OldMaidTable.js new file mode 100644 index 0000000..eedf1f0 --- /dev/null +++ b/src/games/oldmaid/OldMaidTable.js @@ -0,0 +1,119 @@ +// Old Maid table layout — Phaser-free so tools/verifyOldMaid.js can test it. +// +// A round (oval) mahogany parlour table by candlelight on the shared +// card-table kit. Seats as in Uno / Go Fish (2–4 players). In the middle: the +// pile of discarded pairs, and — on your turn — your neighbour's hand held out +// toward you as a big face-down fan to pick a card from. + +import { makeTable, CARD_W, CARD_H, fanPose, fanPoint, HUMAN_PLATE, PLATE } from '../../ui/cardtable/TableGeometry.js'; + +export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 }; +export const T = makeTable(VIEW, { shape: 'oval', feltK: 0.95, faceH: 38 }); +export const SQ = VIEW.squash; + +export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c]; +export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c']; + +const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 82, curve: 1.3, tilt: 0.034, q: 1, maxSpan: 880, maxDrop: 34, maxTilt: 0.2 }; +const opp = (x, y, rot, k = 0.55) => ({ x, y, rot, k, spread: 34, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 420, maxDrop: 14, maxTilt: 0.16 }); + +const SEATS = { + 2: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(960, 80, Math.PI), plate: { x: 1420, y: 86 } }, + ], + 3: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(600, 82, Math.PI - 0.1), plate: { x: 190, y: 150 } }, + { fan: opp(1320, 82, Math.PI + 0.1), plate: { x: 1730, y: 150 } }, + ], + 4: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 } }, + { fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 } }, + { fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 } }, + ], +}; + +// The neighbour's hand, held out for you to pick from. +export const OFFER_FAN = { x: 960, y: 392, rot: 0, k: 0.8, spread: 74, curve: 1.1, tilt: 0.045, q: 1, maxSpan: 720, maxDrop: 22, maxTilt: 0.22 }; +export const PILE = { u: 0, v: 0.6, k: 0.62 }; +export const CANDLES = [{ u: -0.58, v: 0.24 }, { u: 0.58, v: 0.24 }]; +export const REVEAL = { x: 960, y: 470, s: 1.45 }; + +const cache = new Map(); +export function layoutFor(playerCount) { + if (cache.has(playerCount)) return cache.get(playerCount); + const defs = SEATS[playerCount]; + if (!defs) throw new Error(`Old Maid layout supports 2..4 players, got ${playerCount}`); + const L = { playerCount, seats: defs.map((d, seat) => ({ seat, ...d })) }; + cache.set(playerCount, L); + return L; +} + +export const handPose = (L, seat, i, n, lift = 0) => fanPose(L.seats[seat].fan, i, n, lift); +export const offerPose = (i, n, lift = 0) => ({ ...fanPose(OFFER_FAN, i, n, lift) }); + +function hash01(id, salt) { + let h = Math.imul((id + 3) * 2654435761 + salt * 40503, 2246822507) >>> 0; + h ^= h >>> 13; h = Math.imul(h, 3266489909) >>> 0; h ^= h >>> 16; + return (h >>> 0) / 4294967296; +} + +/** A discarded card on the messy pile in the middle (stable per card id). */ +export function pilePose(id, i) { + const p = T.flat(PILE.u + (hash01(id, 1) - 0.5) * 0.12, PILE.v + (hash01(id, 2) - 0.5) * 0.05, PILE.k, (hash01(id, 3) - 0.5) * 1.2); + return { ...p, y: p.y - Math.min(10, i * 0.25) }; +} + +export function pileRect() { + const c = T.flat(PILE.u, PILE.v, PILE.k); + const r = (CARD_H / 2) * c.s + 0.06 * VIEW.halfW * c.s + 14; + return { x0: c.x - r - 30, x1: c.x + r + 30, y0: c.y - r * SQ - 10, y1: c.y + r * SQ + 6 }; +} + +// Showcase spots: between each player's hand and the middle, where a fresh +// match (or the card you just drew) is held up for everyone to see. +const SHOW = { + 2: [{ x: 960, y: 790, maxW: 560 }, { x: 960, y: 228, maxW: 440 }], + 3: [{ x: 960, y: 790, maxW: 560 }, { x: 735, y: 225, maxW: 260 }, { x: 1185, y: 225, maxW: 260 }], + 4: [{ x: 960, y: 790, maxW: 560 }, { x: 290, y: 470, maxW: 250 }, { x: 960, y: 228, maxW: 440 }, { x: 1630, y: 470, maxW: 250 }], +}; + +/** Card i of n held up at a seat's showcase spot (upright, readable). */ +export function showPose(L, seat, i = 0, n = 1) { + const c = SHOW[L.playerCount][seat]; + const k = seat === 0 ? 0.86 : 0.72; + const cw = CARD_W * k; + const step = n <= 1 ? 0 : Math.min(cw + 10, (c.maxW - cw) / (n - 1)); + return { x: c.x + (i - (n - 1) / 2) * step, y: c.y, rot: (i - (n - 1) / 2) * 0.04, s: k, q: 1 }; +} + +export function candlePose(i) { const c = CANDLES[i]; return T.P.project(c.u, c.v); } + +export function handHome(L, seat) { + const f = L.seats[seat].fan; + const p = fanPoint(f, 0, -CARD_H * 0.95); + return { ...p, rot: f.rot, k: f.k }; +} + +export function handBadge(L, seat) { + const f = L.seats[seat].fan; + return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 50), 0); +} + +/** Where an opponent's face reaction (tell) pops up — beside their plate. */ +export function tellAt(L, seat) { + const p = L.seats[seat].plate; + return { x: p.x + (p.x > 960 ? -190 : 190), y: p.y + 4 }; +} + +export function spotFor(L, seat) { + const f = L.seats[seat].fan; + if (seat === 0) return { x: f.x, y: 820, w: 1300, h: 420 }; + const c = fanPoint(f, 0, -CARD_H * 0.9); + const side = Math.abs(Math.sin(f.rot)) > 0.7; + return side ? { x: c.x, y: c.y, w: 420, h: 620 } : { x: c.x, y: c.y + 30, w: 640, h: 320 }; +} + +export { PLATE }; diff --git a/src/scenes/OpponentSelectScene.js b/src/scenes/OpponentSelectScene.js index 69ea6a0..f6c01cd 100644 --- a/src/scenes/OpponentSelectScene.js +++ b/src/scenes/OpponentSelectScene.js @@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene { // Skill control: pips always show the level; the +/- buttons appear only // when this opponent is selected. Enabled for games with a 1–5 AI skill. - if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) { + if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) { bio.style.webkitLineClamp = '1'; const skillRow = document.createElement('div'); diff --git a/tools/verifyGoFish.js b/tools/verifyGoFish.js index 4800a5b..92db1ad 100644 --- a/tools/verifyGoFish.js +++ b/tools/verifyGoFish.js @@ -243,7 +243,8 @@ function game(skills, seed, matchSize = 4) { const w51 = one(5, 1, G4), w53 = one(5, 3, G4), w15 = one(1, 5, G4); console.log(` 4p win rates (fair 25%): skill 5 vs 1s ${(w51 * 100).toFixed(0)}% · 5 vs 3s ${(w53 * 100).toFixed(0)}% · 1 vs 5s ${(w15 * 100).toFixed(0)}%`); ok('skill 5 dominates a table of skill 1s', w51 >= 0.45); - ok('skill 5 beats a table of skill 3s', w53 >= (QUICK ? 0.27 : 0.29)); + // measured over 800 games after the no-repeat-target rule: ≈ 30% (fair 25%) + ok('skill 5 beats a table of skill 3s', w53 >= (QUICK ? 0.25 : 0.28)); ok('skill 1 loses to a table of skill 5s', w15 <= 0.16); } diff --git a/tools/verifyOldMaid.js b/tools/verifyOldMaid.js new file mode 100644 index 0000000..a759e60 --- /dev/null +++ b/tools/verifyOldMaid.js @@ -0,0 +1,216 @@ +#!/usr/bin/env node +// verifyOldMaid.js — headless checks for Old Maid: rules (deal, pairs, blind +// draws, safe players, the Old Maid never pairs, game end + loser, shuffles), +// the AI (memory, shuffles hide positions, tells honest vs bluffing by skill), +// the parlour layout for 2/3/4 players, and an all-AI soak (every game ends, +// 53 cards conserved, better players get stuck less). +// Usage: node tools/verifyOldMaid.js [--quick] + +import * as O from '../src/games/oldmaid/OldMaidLogic.js'; +import { Card } from '../src/games/cards/Deck.js'; +import { createMemory, observeLog, chooseDraw, wantsShuffle, tellFor } from '../src/games/oldmaid/OldMaidAI.js'; +import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + CARD_W, CARD_H, cardBounds, fanHit, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, unionRect, +} from '../src/ui/cardtable/TableGeometry.js'; +import { + T, layoutFor, handPose, offerPose, pilePose, pileRect, candlePose, handBadge, handHome, tellAt, OFFER_FAN, REVEAL, showPose, +} from '../src/games/oldmaid/OldMaidTable.js'; + +const QUICK = process.argv.includes('--quick'); +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}`); +let nid = 700; +const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++ }); +const OM = () => ({ rank: O.OLD_MAID_RANK, suit: null, value: 0, key: 'OM', isOldMaid: true, id: nid++ }); + +function rig(hands, current = 0) { + const gs = O.createInitialState({ playerCount: hands.length, seed: 4 }); + gs.players.forEach((p, s) => { p.hand = hands[s]; p.safe = false; p.finishOrder = null; p.discardPairs = 0; }); + gs.discarded = []; + gs.currentPlayer = current; + gs.phase = 'play'; + gs.log = []; + return gs; +} + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +for (const n of [2, 3, 4]) { + const gs = O.createInitialState({ playerCount: n, seed: 20 + n }); + ok(`${n}p: 53 cards (deck + Old Maid)`, O.countCards(gs) === 53); + ok(`${n}p: no pairs left in any hand`, gs.players.every(p => { const r = p.hand.map(c => c.rank).filter(x => x !== 'OM'); return new Set(r).size === r.length; })); + ok(`${n}p: dealt pairs kept for the pile`, gs.discarded.length > 0 && gs.discarded.every(pr => pr.length === 2 && pr[0].rank === pr[1].rank)); + ok(`${n}p: exactly one Old Maid`, gs.players.flatMap(p => p.hand).filter(c => c.isOldMaid).length === 1); +} +{ + const gs = rig([[C('7s'), C('2d')], [C('7h'), OM(), C('Kc')]]); + ok('draw target is the next player', O.drawTargetSeat(gs, 0) === 1); + const d = O.applyDraw(gs, 0, gs.players[1].hand[0].id); + ok('drawing a match throws the pair in', d.players[0].hand.length === 1 && d.discarded.length === 1); + ok('turn passes', d.currentPlayer === 1); + const om = O.applyDraw(gs, 0, gs.players[1].hand[1].id); + ok('the Old Maid never pairs', om.players[0].hand.some(c => c.isOldMaid) && om.discarded.length === 0); + ok('cannot draw a card they do not hold', O.applyDraw(gs, 0, 99999) === gs); +} +{ + const gs = rig([[C('7s')], [C('7h'), OM()], [C('Kc'), C('Kd')]]); + const d = O.applyDraw(gs, 0, gs.players[1].hand[0].id); + ok('empty hand → safe', d.players[0].safe && d.log.some(e => e.kind === 'safe')); + const end = rig([[OM()], [C('7h')]]); + end.players[1].hand = [C('7h')]; + end.players[0].hand = [C('7c'), OM()]; + const e = O.applyDraw(end, 0, end.players[1].hand[0].id); + ok('last card holder of the Old Maid loses', O.isGameOver(e) && e.loserSeat === 0); + const sh = O.applyShuffle(rig([[C('2s'), C('3s'), C('4s'), C('5s'), C('6s'), C('7s')], [C('8h')]]), 0, mulberry32(3)); + ok('shuffle keeps the cards, logs it', sh.players[0].hand.length === 6 && sh.log.some(e2 => e2.kind === 'shuffle')); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry); + // seat 2 (who draws from seat 0) takes the Old Maid → seat 0 knows exactly where it is + const gs = rig([[OM(), C('2s')], [C('3h'), C('4h')], [C('5c'), C('6c'), C('9d')]], 2); + const g1 = O.applyDraw(gs, 2, gs.players[0].hand[0].id); + const mem = createMemory(3); + observeLog(mem, g1, 0); + ok('memory: knows who took the Old Maid', mem.omLocation === 2 && mem.posKnown); + const sh = O.applyShuffle(g1, 2, mulberry32(1)); + observeLog(mem, sh, 0); + ok('their shuffle hides the position', mem.omLocation === 2 && !mem.posKnown); + ok('careful players shuffle while holding the Old Maid', wantsShuffle(g1, 2, 4, () => 0.9) && !wantsShuffle(g1, 2, 1)); + let honest = 0, bluff = 0; + const N = 4000; + const r = mulberry32(9); + for (let i = 0; i < N; i++) { if (tellFor(true, 1, r) === 'hopeful') honest++; if (tellFor(true, 5, r) === 'hopeful') bluff++; } + ok('beginners give honest tells over the Old Maid', honest / N > 0.45, `${(honest / N).toFixed(2)}`); + ok('experts mostly bluff', bluff / N < 0.2, `${(bluff / N).toFixed(2)}`); + const d = chooseDraw(g1, 2, createMemory(3), 3); + ok('draws a real card from the target', g1.players[O.drawTargetSeat(g1, 2)].hand.some(c => c.id === d)); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +for (const n of [2, 3, 4]) { + const L = layoutFor(n); + const furn = hudFurniture(); + for (let s = 1; s < n; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) }); + for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) ok(`${n}p: ${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r)); + const pile = pileRect(); + ok(`${n}p: pair pile on the table`, T.onFelt({ x: pile.x0, y: pile.y0 }) && T.onFelt({ x: pile.x1, y: pile.y1 })); + let pileOk = true; + for (let id = 0; id < 53; id++) { const b = cardBounds(pilePose(id, 20)); if (b.x0 < pile.x0 || b.x1 > pile.x1 || b.y0 < pile.y0 - 12 || b.y1 > pile.y1) pileOk = false; } + ok(`${n}p: pile cards stay in the pile area`, pileOk); + let offer = null; + for (let i = 0; i < 14; i++) offer = unionRect(offer, cardBounds(offerPose(i, 14, 30))); + ok(`${n}p: offered hand on screen + on the table`, onScreen(offer) && T.onFelt({ x: offer.x0, y: offer.y1 }) && T.onFelt({ x: offer.x1, y: offer.y1 })); + ok(`${n}p: offered hand clear of the pile`, !rectsOverlap(offer, pile)); + for (const f of furn) ok(`${n}p: offered hand clear of ${f.name}`, !rectsOverlap(offer, f.r)); + const reveal = cardBounds({ ...REVEAL, rot: -0.05, q: 1 }); + ok(`${n}p: the reveal card on screen`, onScreen(reveal)); + for (let c = 0; c < 2; c++) { + const cp = candlePose(c); + const cr = { x0: cp.x - 40, x1: cp.x + 40, y0: cp.y - 140 * cp.s, y1: cp.y + 14 }; + ok(`${n}p candle ${c} clear of the offered hand`, !rectsOverlap(cr, offer)); + for (let s = 0; s < n; s++) ok(`${n}p candle ${c} clear of hand ${s}`, !rectsOverlap(cr, fanBounds(L.seats[s].fan, 14)), JSON.stringify(cr)); + for (const f of furn) ok(`${n}p candle ${c} clear of ${f.name}`, !rectsOverlap(cr, f.r)); + } + for (let s = 0; s < n; s++) { + for (const cards of [1, 8, 14]) { + const hb = fanBounds(L.seats[s].fan, cards, s === 0 ? 36 : 0); + ok(`${n}p seat ${s} (${cards}): hand on screen`, onScreen(hb, s === 0 ? 50 : 10)); + for (const f of furn) ok(`${n}p seat ${s} (${cards}): hand clear of ${f.name}`, !rectsOverlap(hb, f.r), `${JSON.stringify(hb)} vs ${JSON.stringify(f.r)}`); + ok(`${n}p seat ${s} (${cards}): hand clear of the offered hand`, !rectsOverlap(hb, offer)); + ok(`${n}p seat ${s} (${cards}): hand clear of the pile`, !rectsOverlap(hb, pile)); + } + if (s > 0) { + const b = handBadge(L, s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 }; + ok(`${n}p seat ${s}: badge on screen`, onScreen(br)); + for (const f of furn) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r)); + const t = tellAt(L, s), tr = { x0: t.x - 26, x1: t.x + 26, y0: t.y - 26, y1: t.y + 26 }; + ok(`${n}p seat ${s}: tell face on screen`, onScreen(tr)); + for (let u = 0; u < n; u++) ok(`${n}p seat ${s}: tell clear of hand ${u}`, !rectsOverlap(tr, fanBounds(L.seats[u].fan, 14))); + const hh = handHome(L, s); + ok(`${n}p seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < 1920 && hh.y > 0 && hh.y < 1080); + } + } + // showcase spots: a pair (or up to 6 dealt pairs) held up, clear of everything + const shows = []; + for (let s = 0; s < n; s++) { + let r = null; + for (const cnt of [1, 2, 12]) for (let i = 0; i < cnt; i++) r = unionRect(r, cardBounds(showPose(L, s, i, cnt))); + shows[s] = r; + ok(`${n}p seat ${s}: showcase on screen`, onScreen(r)); + ok(`${n}p seat ${s}: showcase clear of the pile`, !rectsOverlap(r, pile)); + for (const f of furn) ok(`${n}p seat ${s}: showcase clear of ${f.name}`, !rectsOverlap(r, f.r), `${JSON.stringify(r)} vs ${JSON.stringify(f.r)}`); + for (let u = 0; u < n; u++) ok(`${n}p showcase ${s} clear of hand ${u}`, !rectsOverlap(r, fanBounds(L.seats[u].fan, 14, u === 0 ? 30 : 0)), `${JSON.stringify(r)}`); + for (let c = 0; c < 2; c++) { + const cp = candlePose(c); + ok(`${n}p showcase ${s} clear of candle ${c}`, !rectsOverlap(r, { x0: cp.x - 40, x1: cp.x + 40, y0: cp.y - 140 * cp.s, y1: cp.y + 14 })); + } + if (s > 0) ok(`${n}p showcase ${s} clear of the offered hand`, !rectsOverlap(r, offer)); + } + for (let s = 0; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p showcases ${s}/${t} apart`, !rectsOverlap(shows[s], shows[t])); + let rt = true; + for (let i = 0; i < 9; i++) { const p = offerPose(i, 9); if (fanHit(OFFER_FAN, 9, { x: p.x - CARD_W * 0.25, y: p.y - CARD_H * 0.25 }) !== i) rt = false; } + ok(`${n}p: offered-hand hit-test round trip`, rt); + rt = true; + for (let i = 0; i < 12; i++) { const p = handPose(L, 0, i, 12); if (fanHit(L.seats[0].fan, 12, { x: p.x - CARD_W * 0.3, y: p.y - CARD_H * 0.3 }) !== i) rt = false; } + ok(`${n}p: hand hit-test round trip`, rt); +} + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +function game(skills, seed) { + const rand = mulberry32(seed); + let gs = O.createInitialState({ playerCount: skills.length, seed }); + const mem = skills.map(() => createMemory(skills.length)); + let steps = 0, noop = 0, conserve = true; + while (!O.isGameOver(gs) && steps++ < 2000) { + mem.forEach((m, s) => observeLog(m, gs, s)); + const s = gs.currentPlayer; + const id = chooseDraw(gs, s, mem[s], skills[s]); + const from = O.drawTargetSeat(gs, s); + const nx = O.applyDraw(gs, s, id); + if (nx === gs) { noop++; break; } + gs = nx; + for (const t of [s, from]) if (!gs.players[t].safe && !O.isGameOver(gs) && wantsShuffle(gs, t, skills[t], rand)) gs = O.applyShuffle(gs, t, rand); + if (O.countCards(gs) !== 53) conserve = false; + } + return { gs, over: O.isGameOver(gs), noop, conserve }; +} +{ + const M = QUICK ? 60 : 250; + for (const n of [2, 3, 4]) { + let over = 0, noop = 0, conserved = true, loserHolds = true; + for (let i = 0; i < M; i++) { + const r = game(Array.from({ length: n }, (_, s) => 1 + ((i + s) % 5)), 300 + i * 11 + n); + if (r.over) over++; + noop += r.noop; + if (!r.conserve) conserved = false; + if (r.over && !r.gs.players[r.gs.loserSeat].hand.some(c => c.isOldMaid)) loserHolds = false; + } + ok(`${n}p: every game ends`, over === M, `${over}/${M}`); + ok(`${n}p: AI never draws illegally`, noop === 0); + ok(`${n}p: 53 cards conserved`, conserved); + ok(`${n}p: the loser holds the Old Maid`, loserHolds); + } + const stuck = (a, b, games) => { + let lost = 0; + for (let i = 0; i < games; i++) { const seat = i % 4; const sk = [b, b, b, b]; sk[seat] = a; if (game(sk, 9000 + i).gs.loserSeat === seat) lost++; } + return lost / games; + }; + const G = QUICK ? 600 : 2000; + const s5 = stuck(5, 1, G), s1 = stuck(1, 5, G); + console.log(` 4p: skill 5 among skill 1s is stuck ${(s5 * 100).toFixed(0)}% of games · skill 1 among skill 5s ${(s1 * 100).toFixed(0)}% (fair 25%)`); + ok('skill 5 gets stuck less than its fair share', s5 < 0.22); + ok('skill 1 gets stuck more than its fair share', s1 > 0.28); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);