diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index c93e5b2..5b1e3e0 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -35,7 +35,7 @@ registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1, registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 }); registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 }); registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 }); -registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 8 }); +registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 8 }); registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 9 }); registerGame({ slug: 'craps', name: 'Craps', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 10 }); registerGame({ slug: 'roulette', name: 'Roulette', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 11 }); diff --git a/src/games/gofish/GoFishAI.js b/src/games/gofish/GoFishAI.js index caebaec..7bfe6e2 100644 --- a/src/games/gofish/GoFishAI.js +++ b/src/games/gofish/GoFishAI.js @@ -6,11 +6,21 @@ // entries. import { RANKS } from '../cards/Deck.js'; +import { clampSkill } from '../../ui/cardtable/AITiming.js'; + +// Skill = how well the opponent remembers the table. Each fact it sees (who +// asked for what, who handed what over) sticks with this probability, and a +// beginner sometimes just asks a random player for a random card it holds. +export const RECALL = { 1: 0.3, 2: 0.5, 3: 0.75, 4: 0.92, 5: 1 }; +const RANDOM_ASK = { 1: 0.35, 2: 0.18, 3: 0.05, 4: 0, 5: 0 }; const TOTAL_PER_RANK = 4; // 4 suits per rank -export function createMemory(seatCount) { +export function createMemory(seatCount, { skill = 3, matchSize = 4, rng = Math.random } = {}) { return { + skill: clampSkill(skill), + matchSize, + rng, // beliefs[targetSeat][rank] ∈ [0, 4]: a soft count of how many of that // rank we believe `targetSeat` still holds. Bumped when they ask for or // catch a rank; zeroed when they get fished or hand it over. @@ -30,8 +40,13 @@ export function createMemory(seatCount) { * Replay every log entry from memory.logCursor onward and update memory. */ export function observeLog(memory, state, selfSeat) { + const recall = RECALL[memory.skill ?? 5]; + const rand = memory.rng ?? Math.random; for (let i = memory.logCursor; i < state.log.length; i++) { const e = state.log[i]; + // a forgetful player simply misses some of what happens at the table + // (books are laid face up, so everyone always sees those) + if (e.kind !== 'pair' && e.kind !== 'sitout' && rand() > recall) continue; if (e.kind === 'ask') { // The asker held at least 1 of `rank` at the moment of the ask. memory.beliefs[e.askerSeat][e.rank] = Math.max(memory.beliefs[e.askerSeat][e.rank], 1); @@ -52,9 +67,10 @@ export function observeLog(memory, state, selfSeat) { memory.beliefs[e.askerSeat][e.rank] += 1; memory.turnRecorded[e.askerSeat][e.rank] = state.turnCount; } else if (e.kind === 'pair') { - memory.pairedCount[e.rank] += 2; - // The pairer no longer holds 2 of that rank. - memory.beliefs[e.seat][e.rank] = Math.max(0, memory.beliefs[e.seat][e.rank] - 2); + const size = memory.matchSize ?? 2; + memory.pairedCount[e.rank] += size; + // The pairer no longer holds those cards. + memory.beliefs[e.seat][e.rank] = Math.max(0, memory.beliefs[e.seat][e.rank] - size); } else if (e.kind === 'refill') { // Refills draw from the pool; we don't know specific ranks. No update. } else if (e.kind === 'sitout') { @@ -67,6 +83,22 @@ export function observeLog(memory, state, selfSeat) { for (const r of RANKS) memory.beliefs[selfSeat][r] = 0; } +/** + * Players `seat` has already caught cards from during its current turn (a + * catch keeps the turn going). Read back through the log until another + * player's ask — that's where this turn began. + */ +export function caughtFromThisTurn(state, seat) { + const out = new Set(); + for (let i = state.log.length - 1; i >= 0; i--) { + const e = state.log[i]; + if (e.kind !== 'ask') continue; + if (e.askerSeat !== seat) break; + if (e.result === 'catch') out.add(e.targetSeat); + } + return out; +} + /** * Pick (targetSeat, rank) for the AI. Falls back gracefully if memory is * empty (e.g. very first turn). @@ -77,6 +109,17 @@ export function chooseAction(state, seat, memory, exclude = new Set()) { // Our distinct ranks (we must hold at least one). const myRanks = [...new Set(me.hand.map((c) => c.rank))]; + const rand = memory.rng ?? Math.random; + // Don't go back to a player we've already taken cards from this turn — unless + // there's nobody else left to ask (always the case heads-up). + const open = state.players.filter((p) => p.seat !== seat && !p.sittingOut && p.hand.length > 0).map((p) => p.seat); + const caught = caughtFromThisTurn(state, seat); + const fresh = open.filter((t) => !caught.has(t)); + const allowed = new Set(fresh.length ? fresh : open); + if (rand() < RANDOM_ASK[memory.skill ?? 5]) { + const targets = [...allowed]; + if (targets.length) return { targetSeat: targets[Math.floor(rand() * targets.length)], rank: myRanks[Math.floor(rand() * myRanks.length)] }; + } // Cards-per-opponent for statistical weighting. const handSizes = state.players.map((p) => p.hand.length); @@ -94,12 +137,16 @@ export function chooseAction(state, seat, memory, exclude = new Set()) { if (target === seat) continue; const opp = state.players[target]; if (opp.sittingOut || opp.hand.length === 0) continue; + if (!allowed.has(target)) continue; if (exclude.has(`${target}:${rank}`)) continue; let score = 0; const belief = memory.beliefs[target][rank] || 0; // Strong signal: they've shown they hold this rank. if (belief > 0) score += 3 + Math.min(belief, 3); + // …and they just told us "go fish" for it: don't ask straight back. + const said = memory.turnRecorded[target][rank]; + if (belief === 0 && said != null && state.turnCount - said < 3) score -= 3; // We pair on a catch, so more in-hand = bigger payoff. score += myCount; @@ -115,7 +162,7 @@ export function chooseAction(state, seat, memory, exclude = new Set()) { score += (opp.hand.length - avgHand) * 0.3; // Long-tail random tiebreak. - score += Math.random() * 0.1; + score += rand() * 0.1; if (score > bestScore) { bestScore = score; @@ -132,7 +179,7 @@ export function chooseAction(state, seat, memory, exclude = new Set()) { if (t === seat) continue; if (exclude.has(`${t}:${rank}`)) continue; const opp = state.players[t]; - if (!opp.sittingOut && opp.hand.length > 0) { + if (!opp.sittingOut && opp.hand.length > 0 && allowed.has(t)) { return { targetSeat: t, rank }; } } diff --git a/src/games/gofish/GoFishArt.js b/src/games/gofish/GoFishArt.js new file mode 100644 index 0000000..783ecac --- /dev/null +++ b/src/games/gofish/GoFishArt.js @@ -0,0 +1,234 @@ +// Go Fish art — the lakeside dock at dusk, baked once per page load. The card +// FACES are the owner's own illustrated sheet ('gofish-cards', one fish per +// rank, loaded from assets/images/gofish-cards.png via the asset manifest); +// this module only adds a matching back and the room. +// +// gofish-back dusky blue back with waves and a fish +// gofish-table- sunset sky + lake, a plank dock with a pond cut into the +// middle, faint book rows in front of each player + +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, layoutFor, pondOutline, bookRowRect, SEAT_HEX } from './GoFishTable.js'; + +const CW = CARD_TEX.W, CH = CARD_TEX.H; + +function fishShape(ctx, x, y, s, color) { + ctx.save(); + ctx.translate(x, y); + ctx.scale(s, s); + ctx.beginPath(); + ctx.ellipse(0, 0, 34, 20, 0, 0, Math.PI * 2); + ctx.moveTo(30, 0); + ctx.lineTo(56, -18); + ctx.lineTo(52, 0); + ctx.lineTo(56, 18); + ctx.closePath(); + ctx.fillStyle = color; + ctx.fill(); + ctx.beginPath(); ctx.arc(-18, -5, 4, 0, Math.PI * 2); ctx.fillStyle = '#0b1a2e'; 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 = '#f3ecdc'; + ctx.fill(); + ctx.save(); + rr(ctx, 12, 12, CW - 24, CH - 24, 12); + ctx.clip(); + const g = ctx.createLinearGradient(0, 0, 0, CH); + g.addColorStop(0, '#2a4f7a'); g.addColorStop(1, '#122a48'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, CW, CH); + ctx.strokeStyle = 'rgba(160,210,240,0.35)'; + ctx.lineWidth = 4; + for (let y = 20; y < CH; y += 22) { + ctx.beginPath(); + for (let x = 0; x <= CW; x += 8) ctx.lineTo(x, y + Math.sin(x / 14 + y) * 4); + ctx.stroke(); + } + fishShape(ctx, CW / 2 - 8, CH / 2, 1.3, '#f0b23a'); + ctx.restore(); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; + ctx.stroke(); + scene.textures.addCanvas('gofish-back', c); +} + +// ── The dock at dusk ───────────────────────────────────────────────────────── +const HORIZON = 150; + +function sky(ctx) { + const g = ctx.createLinearGradient(0, 0, 0, HORIZON); + g.addColorStop(0, '#2b1f4f'); + g.addColorStop(0.55, '#a0456a'); + g.addColorStop(1, '#f39a4a'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, HORIZON); + // the low sun, half-set behind the far shore + const sun = ctx.createRadialGradient(1320, HORIZON, 4, 1320, HORIZON, 160); + sun.addColorStop(0, 'rgba(255,230,160,0.95)'); + sun.addColorStop(0.25, 'rgba(255,190,110,0.6)'); + sun.addColorStop(1, 'rgba(255,150,80,0)'); + ctx.fillStyle = sun; + ctx.fillRect(0, 0, W, HORIZON); + // tree line on the far shore + ctx.fillStyle = '#1c1630'; + ctx.beginPath(); + ctx.moveTo(0, HORIZON); + for (let x = 0; x <= W; x += 14) { + const h = 14 + Math.abs(Math.sin(x * 0.013) * 22) + Math.abs(Math.sin(x * 0.051)) * 12 + ((x * 7919) % 11); + ctx.lineTo(x, HORIZON - h); + } + ctx.lineTo(W, HORIZON); + ctx.closePath(); + ctx.fill(); + // lake below + const lake = ctx.createLinearGradient(0, HORIZON, 0, H); + lake.addColorStop(0, '#5a3a5e'); + lake.addColorStop(0.2, '#24324e'); + lake.addColorStop(1, '#0b1424'); + ctx.fillStyle = lake; + ctx.fillRect(0, HORIZON, W, H - HORIZON); + // the sun's path on the water + for (let y = HORIZON + 4; y < H; y += 9) { + const w = 30 + (y - HORIZON) * 0.25; + ctx.fillStyle = `rgba(255,190,120,${Math.max(0, 0.5 - (y - HORIZON) / 900)})`; + ctx.fillRect(1320 - w / 2 + Math.sin(y) * 10, y, w, 2); + } +} + +const PLANK = ['#7a5a3a', '#6e5034', '#83633f', '#6a4a2e', '#765638']; + +function front(ctx, Tb) { + frontBands(ctx, Tb, ['#4a3420', '#3e2c1a', '#332414', '#281c10', '#1e150c'], { grooves: [0.5] }); +} + +function rim(ctx, Tb) { + rimBand(ctx, Tb, { base: '#5a4028', dark: '#2a1c10', light: '#9a7448', grain: ['#1a1008', '#b8905a'], gloss: 1.2 }); +} + +function planks(ctx, Tb) { + // boards run left-right; each band is a row of boards with staggered joints + const rows = 26; + for (let r = 0; r < rows; r++) { + const v0 = -0.02 + (r / rows) * 1.04, v1 = v0 + 1.04 / rows; + let u = -1.1 + ((r * 0.37) % 0.4); + let k = r * 3; + while (u < 1.1) { + const len = 0.42 + ((k * 0.61) % 0.3); + const a = Tb.P.project(u, v0), b = Tb.P.project(u + len, v0), c = Tb.P.project(u + len, v1), d = Tb.P.project(u, v1); + ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.lineTo(c.x, c.y); ctx.lineTo(d.x, d.y); ctx.closePath(); + ctx.fillStyle = PLANK[k % PLANK.length]; + ctx.fill(); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(20,12,6,0.65)'; + ctx.stroke(); + // a nail at each end + for (const p of [Tb.P.project(u + 0.02, (v0 + v1) / 2), Tb.P.project(u + len - 0.02, (v0 + v1) / 2)]) { + ctx.beginPath(); ctx.arc(p.x, p.y, 1.8 * p.s, 0, Math.PI * 2); ctx.fillStyle = 'rgba(30,30,34,0.7)'; ctx.fill(); + } + u += len; + k++; + } + } + // weathering + grain + ctx.fillStyle = noisePattern(ctx, 200, 34); + ctx.fillRect(0, 0, W, H); + ctx.globalAlpha = 0.12; + for (let i = 0; i < 260; i++) { + const y = Math.random() * H, x = Math.random() * W; + ctx.fillStyle = Math.random() < 0.5 ? '#1a0e06' : '#c8a070'; + ctx.fillRect(x, y, 40 + Math.random() * 120, 1); + } + ctx.globalAlpha = 1; + // dusk light: warm from the sun (upper right), cool shadow elsewhere + lampPool(ctx, Tb, { color: '255,180,120', alpha: 0.22, vignette: 0.6, at: { u: 0.35, v: 0.2 } }); + ctx.fillStyle = 'rgba(30,30,80,0.12)'; + ctx.fillRect(0, 0, W, H); + rimShadow(ctx, Tb, 0.3); +} + +function pond(ctx) { + const outer = pondOutline(1.07); + const shore = pondOutline(1.0); + // log rim around the hole + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 4; + poly(ctx, outer); ctx.fillStyle = '#4a3220'; ctx.fill(); + ctx.restore(); + for (let i = 0; i < 6; i++) { + poly(ctx, pondOutline(1.07 - i * 0.012)); + ctx.lineWidth = 3; + ctx.strokeStyle = mix('#2a1a0c', '#8a6238', Math.sin((i / 5) * Math.PI)); + ctx.stroke(); + } + // water + ctx.save(); + poly(ctx, shore); + ctx.clip(); + const c = T.P.project(0, 0.44); + const g = ctx.createRadialGradient(c.x, c.y, 10, c.x, c.y, 360); + g.addColorStop(0, '#2f6a86'); + g.addColorStop(0.7, '#1c4560'); + g.addColorStop(1, '#0e2638'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + ctx.strokeStyle = 'rgba(180,225,245,0.18)'; + ctx.lineWidth = 2; + for (let i = 1; i <= 6; i++) { + poly(ctx, pondOutline(i / 7)); + ctx.stroke(); + } + // sunset glints + for (let i = 0; i < 60; i++) { + const x = c.x - 300 + Math.random() * 600, y = c.y - 110 + Math.random() * 220; + ctx.fillStyle = `rgba(255,${180 + Math.floor(Math.random() * 60)},140,${0.12 + Math.random() * 0.2})`; + ctx.fillRect(x, y, 6 + Math.random() * 14, 1.5); + } + ctx.restore(); + poly(ctx, shore); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.6)'; + ctx.stroke(); + ctx.font = '15px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(242,214,160,0.55)'; + ctx.fillText('THE POND', c.x, pondOutline(1.07)[48].y - 18); +} + +function bookRows(ctx, playerCount) { + const L = layoutFor(playerCount); + for (const st of L.seats) { + const r = bookRowRect(L, st.seat, 13); + rr(ctx, r.x0 - 6, r.y0 - 4, r.x1 - r.x0 + 12, r.y1 - r.y0 + 8, 10); + ctx.fillStyle = 'rgba(0,0,0,0.14)'; + ctx.fill(); + ctx.setLineDash([8, 6]); + ctx.lineWidth = 2; + ctx.strokeStyle = SEAT_HEX[st.seat]; + ctx.globalAlpha = 0.45; + ctx.stroke(); + ctx.globalAlpha = 1; + ctx.setLineDash([]); + } +} + +export async function prepareGoFishArt(scene, playerCount) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('gofish-back')) bakeBack(scene); + return bakeRoom(scene, `gofish-table-${playerCount}`, T, { + wall: sky, front, rim, top: planks, + onTop: (ctx) => { pond(ctx); bookRows(ctx, playerCount); }, + }); +} + +export { fishShape }; diff --git a/src/games/gofish/GoFishGame.js b/src/games/gofish/GoFishGame.js index cd13590..9458768 100644 --- a/src/games/gofish/GoFishGame.js +++ b/src/games/gofish/GoFishGame.js @@ -1,1388 +1,998 @@ -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 { playSound, SFX } from '../../ui/Sounds.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { - createInitialState, - applyAsk, - applyFishPick, - legalRanksToAsk, - canAsk, - isGameOver, -} from './GoFishLogic.js'; + CardTableScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { CARD_W, CARD_H, fanHit, fanInsertIndex, fanZone, inRect, inPose } from '../../ui/cardtable/TableGeometry.js'; import { createMemory, observeLog, chooseAction } from './GoFishAI.js'; +import { createInitialState, applyAsk, applyFishPick, isGameOver, canAsk } from './GoFishLogic.js'; +import { + T, SQ, SEAT_COLORS, SEAT_HEX, layoutFor, handPose, poolPose, bookPose, handHome, handBadge, bubbleAt, + seatTargetRect, spotFor, POND, inPond, showPose, +} from './GoFishTable.js'; +import { prepareGoFishArt } from './GoFishArt.js'; -// ── Layout constants ──────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; +// ─── Go Fish ────────────────────────────────────────────────────────────────── +// A lakeside dock at dusk on the shared card-table kit (src/ui/cardtable/). +// The card faces are the owner's own illustrated sheet ('gofish-cards'). +// Rules: GoFishLogic.js · opponents: GoFishAI.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 GOFISH_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 }; +const RANK_ORDER = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']; +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 RANK_ONE = { A: 'Ace', T: '10', J: 'Jack', Q: 'Queen', K: 'King' }; +const DEFAULTS = { pace: 'normal', hints: true, sort: 'rank', match: null, askPause: 'normal' }; +// How long the table holds an ask (the card held up) and the answer (what was +// handed over, or "Go fish!") so you can take in who asked whom for what. +const ASK_PAUSE = { short: 1000, normal: 1800, long: 2800 }; -const D = { - felt: -1, board: 0, pool: 5, 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': { - // chip bottom edge = bchipY + 22; portrait bottom aligns with chip bottom - // portrait left of chip with 12px gap - 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': { - // chip top edge = tchipY - 22; portrait top aligns with chip top - // portrait left of chip with 12px gap - 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': { - // chip at (205, CY) rotated — extends ±90 in y, ±22 in x - // portrait left edge aligned with chip left edge (chipX - 22) - 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': { - // chip at (1715, CY) rotated — extends ±90 in y, ±22 in x - // portrait right edge aligned with chip right edge (chipX + 22) - 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 POOL_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 GOFISH_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 }; - -// ── Scene ─────────────────────────────────────────────────────────────────── -export default class GoFishGame extends Phaser.Scene { +export default class GoFishGame extends CardTableScene { constructor() { super('GoFishGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.cardBack = data.cardBack ?? null; - this.matchVariant = data.matchVariant ?? 4; - + this.initTable(data, { settingsKey: 'gofish-settings', defaults: DEFAULTS }); + this.L = layoutFor(this.playerCount); + this.matchSize = data.matchVariant ?? this.settings.match ?? 4; this.gs = null; - this.animating = false; - this.gameOver = false; - - this.cardObjs = new Map(); - this.transientObjs = []; - this.opponentPortraits = []; - this.seatChips = []; - this.slotForSeat = []; - this.aiMemory = []; - this.selectedRank = null; - this.bannerText = null; - this.poolCardPositions = new Map(); + this.history = []; + this.memories = []; + this.hintMem = null; + this.selRank = null; + this.hoverId = null; + this.hoverPool = null; + this.potentialDrag = null; + this.dragState = null; + this.dragPreview = null; + this.revealAll = false; + this.lineG = null; + this.show = null; // { asker, target, askIds, respIds } while an ask is on display } - create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildPlayfield(); - this.assignSeats(); - this.buildSeatAreas(); - this.buildCenter(); - this.buildHUD(); - this.buildMatchesPanel(); - this.startNewMatch(); + faceFrame(card) { return { key: 'gofish-cards', frame: GOFISH_CARD_FRAME[card.rank], sized: true }; } + unit() { return this.matchSize === 4 ? 'book' : 'pair'; } + + async create() { + this.createTableBase(); + const key = await prepareGoFishArt(this, this.playerCount); + if (!this.alive()) return; + this.backKey = 'gofish-back'; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildSpot(); + this.lineG = this.add.graphics().setDepth(D.ghost - 1); + this.targetG = this.add.graphics().setDepth(D.glow); + this.pondTxt = this.add.text(T.P.project(0, POND.v + POND.rv + 0.03).x, T.P.project(0, POND.v + POND.rv + 0.03).y, '', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f2d6a0', stroke: '#1a1008', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels); + this.buildDropSlot(); + this.buildPlates(this.L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'BOOK!' }); + 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(), + }, 'Click a card, then the player to ask (or drag it onto them) · F fish for me\nA suggest · Q ask log · S sort · H hint · Esc menu'); + this.buildDock(); + this.buildSortRow([['rank', 'Rank'], ['most', 'Most'], ['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); + update(time) { + if (!this.gs || this.paused) return; + // pool cards bob gently in the pond + for (const [id, v] of this._lastVisible) { + if (v.kind !== 'pool') continue; + const c = this.sprites.get(id); + if (!c || c._tw || !c.pose) continue; + const ph = (id * 1.7) % 6.28; + const lift = this.hoverPool === id ? 14 : 0; + c.y = c.pose.y + Math.sin(time * 0.0018 + ph) * 2.2 - lift; + c.rotation = c.pose.rot + Math.sin(time * 0.0013 + ph) * 0.025; } } - assignSeats() { - const playerCount = 1 + this.opponents.length; - const slots = SLOTS_USED[playerCount]; - if (!slots) throw new Error(`Go Fish needs 2..4 players, got ${playerCount}`); - this.slotForSeat = slots.slice(); - } - - buildSeatAreas() { - for (let seat = 0; seat < this.slotForSeat.length; seat++) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - - if (seat === 0) { - createPlayerPortrait(this, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait, 'GoFishGame'); - 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); - } - } - - // Pair counter chip. - this.seatChips[seat] = this.makeSeatChip(layout.chip.x, layout.chip.y); - this.seatChips[seat].container.setRotation(layout.chipRotation); - } - - // Make opponent portraits clickable as ask targets (seats 1..N). - for (let seat = 1; seat < this.slotForSeat.length; seat++) { - const layout = slotLayout(this.slotForSeat[seat]); - const hot = this.add.circle(layout.portrait.x, layout.portrait.y, layout.portrait.r + 8, 0xffffff, 0) - .setDepth(D.portrait + 5) - .setInteractive({ useHandCursor: true }); - hot.on('pointerdown', () => this.onOpponentClick(seat)); - hot.on('pointerover', () => this.highlightOpponent(seat, true)); - hot.on('pointerout', () => this.highlightOpponent(seat, false)); - this.transientObjs.push(hot); + 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, '7', { fontFamily: 'Righteous', fontSize: '16px', color: COLORS.textHex }).setOrigin(0.5); + c.add([g, t]); + this.badges[seat] = { c, t }; } } - 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 chipLabel = this.matchVariant === 4 ? 'BOOKS' : 'PAIRS'; - const label = this.add.text(-78, 0, chipLabel, { - 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 }; - } - - buildCenter() { - // Last-action banner. - this.bannerBg = this.add.graphics().setDepth(D.banner - 1).setVisible(false); - this.bannerText = this.add.text(CX, CY + CARD_H + 80, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, align: 'center', - wordWrap: { width: 900 }, - }).setOrigin(0.5).setDepth(D.banner); - } - - getCentralBounds() { - const PAD = 20; - let left = PAD, right = GAME_WIDTH - PAD, top = PAD, bottom = GAME_HEIGHT - PAD; - for (const slot of this.slotForSeat) { - if (slot === 'bottom') bottom = Math.min(bottom, (GAME_HEIGHT - 100) - CARD_H / 2 - PAD); - if (slot === 'top') top = Math.max(top, 110 + CARD_H / 2 + PAD); - if (slot === 'left') left = Math.max(left, 110 + CARD_H / 2 + PAD); - if (slot === 'right') right = Math.min(right, (GAME_WIDTH - 110) - CARD_H / 2 - PAD); - } - return { left, right, top, bottom }; - } - - scatterPool(pool) { - this.poolCardPositions.clear(); - const { left, right, top, bottom } = this.getCentralBounds(); - const xMin = left + CARD_W / 2, xMax = right - CARD_W / 2; - const yMin = top + CARD_H / 2, yMax = bottom - CARD_H / 2; - for (const card of pool) { - this.poolCardPositions.set(card.id, { - x: xMin + Math.random() * (xMax - xMin), - y: yMin + Math.random() * (yMax - yMin), - rot: Math.random() * 60 - 30, - }); + 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)); } } - buildHUD() { - // Sit just right of bottom portrait (right edge = CX - 90) and just above chip top (bchipY - 22). - 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); + // What you could have remembered about a player: the ranks they've shown. + knownRanks(seat) { + if (!this.hintMem) return []; + return RANK_ORDER.filter(r => (this.hintMem.beliefs[seat][r] || 0) > 0); } - // ── Matches panel ───────────────────────────────────────────────────────── - - buildMatchesPanel() { - const RANK_ORDER = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2']; - const maxPerRank = this.matchVariant === 4 ? 1 : 2; - const totalPossible = 13 * maxPerRank; - const panelTitle = this.matchVariant === 4 ? 'Books so far' : 'Matches so far'; - const remainingPrefix = this.matchVariant === 4 ? 'Remaining Books: ' : 'Remaining Matches: '; - this._matchMaxPerRank = maxPerRank; - this._matchTotalPossible = totalPossible; - this._matchRemainingPrefix = remainingPrefix; - - const px = 10, py = 10; - const padX = 9, padY = 8; - const titleH = 18; - const rowH = 16; - const panelW = 188; - const panelH = padY + titleH + 5 + RANK_ORDER.length * rowH + 5 + rowH + padY; - - const bg = this.add.graphics().setDepth(D.ui - 0.5); - bg.fillStyle(0x000000, 0.70); - bg.fillRoundedRect(px, py, panelW, panelH, 7); - bg.lineStyle(1, COLORS.accent, 0.35); - bg.strokeRoundedRect(px, py, panelW, panelH, 7); - - this.add.text(px + padX, py + padY, panelTitle, { - fontFamily: 'Righteous', fontSize: '13px', color: COLORS.goldHex, - }).setDepth(D.ui); - - this._matchPanelRows = RANK_ORDER.map((rank, i) => { - const label = rank === 'T' ? '10' : rank; - const t = this.add.text( - px + padX, - py + padY + titleH + 5 + i * rowH, - `${label.padEnd(2)} = 0 / ${maxPerRank}`, - { fontFamily: 'Righteous', fontSize: '12px', color: COLORS.textHex } - ).setDepth(D.ui); - return { rank, text: t }; - }); - - this._matchRemainingText = this.add.text( - px + padX, - py + padY + titleH + 5 + RANK_ORDER.length * rowH + 5, - `${remainingPrefix}${totalPossible}`, - { fontFamily: 'Righteous', fontSize: '12px', color: COLORS.goldHex } - ).setDepth(D.ui); + seatTip(seat) { + if (!this.gs) return null; + const p = this.gs.players[seat]; + const known = this.knownRanks(seat); + const lines = [ + { text: `${p.hand.length} card${p.hand.length === 1 ? '' : 's'} in hand${p.sittingOut ? ' — out of the game' : ''}` }, + { text: `${p.pairs} ${this.unit()}${p.pairs === 1 ? '' : 's'}`, color: COLORS.goldHex }, + { text: known.length ? `Has shown: ${known.map(r => RANK_NAME[r]).join(', ')}` : 'Hasn\'t shown any ranks yet', color: known.length ? '#7cf0a0' : COLORS.mutedHex }, + { text: `Skill ${this.skillFor(seat)} / 5`, color: COLORS.mutedHex }, + ]; + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; } - updateMatchesPanel() { - if (!this.gs || !this._matchPanelRows) return; - const tally = new Map(this._matchPanelRows.map(({ rank }) => [rank, 0])); - for (const player of this.gs.players) { - for (const rank of player.pairedRanks) { - tally.set(rank, (tally.get(rank) ?? 0) + 1); - } - } - let totalScored = 0; - for (const { rank, text } of this._matchPanelRows) { - const scored = tally.get(rank) ?? 0; - totalScored += scored; - const label = rank === 'T' ? '10' : rank; - text.setText(`${label.padEnd(2)} = ${scored} / ${this._matchMaxPerRank}`); - text.setColor(scored === this._matchMaxPerRank ? COLORS.mutedHex : COLORS.textHex); - } - this._matchRemainingText.setText(`${this._matchRemainingPrefix}${this._matchTotalPossible - totalScored}`); + // ── Game lifecycle ──────────────────────────────────────────────────────── + newGame() { + this.gs = createInitialState({ playerCount: this.playerCount, matchSize: this.matchSize }); + this.memories = this.L.seats.map((_, s) => (s ? createMemory(this.playerCount, { skill: this.skillFor(s), matchSize: this.matchSize }) : null)); + this.hintMem = createMemory(this.playerCount, { skill: 5, matchSize: this.matchSize }); + this.startGame(); } - // ── Match lifecycle ──────────────────────────────────────────────────────── - - startNewMatch() { - if (this.animating) return; - this.gameOver = false; - this.selectedRank = null; - this.clearAllCardObjs(); - this.hideBanner(); - - const playerCount = this.slotForSeat.length; - const finalState = createInitialState({ playerCount, matchSize: this.matchVariant }); - this.aiMemory = []; - this.aiTurnExclusions = new Map(); - 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.selRank = null; + this.revealAll = false; + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } + const gs = this.gs; + const centre = T.flat(POND.u, POND.v, 0.6); + const n = this.playerCount; + const all = [...gs.pool, ...gs.players.flatMap(p => [...p.hand, ...p.books.flat()])]; + for (const c of all) this.lastLoc.set(c.id, { pose: centre, faceUp: false, depth: D.fly }); + const dealOrder = new Map(); + gs.players.forEach(p => [...p.hand, ...p.books.flat()].sort((a, b) => a.id - b.id).forEach((c, i) => dealOrder.set(c.id, i * n + p.seat))); + this.sortHand(); + this.updatePlates(); + this.updateDock(); playSound(this, SFX.CARD_SHUFFLE); - this.animating = true; - - // Show the deck as the deal source and reset chip display. - const deck = this.makeCardSprite( - { label: '', suit: 's', suitSymbol: '' }, POOL_POS.x, POOL_POS.y, { faceUp: false } - ); - this.transientObjs.push(deck); - for (const chip of this.seatChips) { if (chip) chip.count.setText('0'); } - - // Build round-robin deal sequence. - 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 }); - } - } - } - - const STAGGER = 90; // ms between each card launch - const DURATION = 200; // ms for the card to fly - - 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, POOL_POS.x, POOL_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); - }, - }); - }); - }); - - // Once the last card has landed, switch to live game state. - const doneAt = (sequence.length - 1) * STAGGER + DURATION + 250; - this.time.delayedCall(doneAt, () => { - this.scatterPool(finalState.pool); - this.gs = finalState; - this.renderAll(); - this.updateStatus(); - const initialPairs = (finalState.initialDealPairs ?? []).filter((e) => e.pairedCards.length >= 2); - if (initialPairs.length > 0) { - this.playInitialDealPairs(initialPairs, 0, () => { - this.animating = false; - this.maybeStartAITurn(); - }); - } else { - this.animating = false; - this.maybeStartAITurn(); - } + const step = 40; + const dealt = 7 * n; + this.layout({ + duration: 320, + delayFor: (v) => (v.kind === 'pool' ? 120 + ((v.card.id * 13) % 40) * 12 + : v.kind === 'book' ? 700 + dealt * step + v.idx * 150 + : 600 + (dealOrder.get(v.card.id) ?? 0) * step), }); + for (let i = 0; i < dealt; i += 3) this.time.delayedCall(620 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.4 })); + const dealBooks = gs.initialDealPairs?.length; + await this.wait(700 + dealt * step + (dealBooks ? 900 : 300)); + if (!this.alive() || token !== this.turnToken) return; + if (dealBooks) this.floatText({ x: CX, y: CY - 40 }, `${this.matchSize === 4 ? 'Books' : 'Pairs'} straight off the deal!`, '#ffd35a', { size: 26, ms: 1500 }); + this.observeAll(); + this.advance(); } - playInitialDealPairs(pairs, idx, onComplete) { - if (idx >= pairs.length) { onComplete(); return; } - const { seat, pairedCards } = pairs[idx]; - const name = this.opponentName(seat); - const rank = pairedCards[0].rank === 'T' ? '10' : pairedCards[0].rank; - const unit = this.matchVariant === 4 ? 'book' : 'pair'; - const bookCount = pairedCards.length / this.matchVariant; - const label = bookCount === 1 - ? `${name} dealt a starting ${unit} of ${rank}s!` - : `${name} dealt ${bookCount} starting ${unit}s!`; - this.showBanner(label); - this.animatePairedCards(seat, pairedCards, () => { - this.hideBanner(); - this.time.delayedCall(250, () => this.playInitialDealPairs(pairs, idx + 1, onComplete)); - }); + observeAll() { + for (let s = 1; s < this.playerCount; s++) observeLog(this.memories[s], this.gs, s); + observeLog(this.hintMem, this.gs, 0); } - // ── 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); - } + advance() { + if (!this.alive() || !this.gs) return; + const gs = this.gs; + if (isGameOver(gs)) { this.onGameOver(); return; } + if (gs.phase === 'pick') { + const seat = gs.lastAsk.askerSeat; + this.setSpot(spotFor(this.L, seat)); + if (seat === 0) { this.mode = 'fishing'; this.layout(); this.updateDock(); this.updatePlates(); return; } + this.mode = 'ai'; + this.updateDock(); + this.aiFish(seat); return; } - - const frame = GOFISH_CARD_FRAME[card.rank]; - if (frame !== undefined && this.textures.exists('gofish-cards')) { - g.destroy(); - container.add( - this.add.image(0, 0, 'gofish-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 ───────────────────────────────────────────────────────────── - - renderAll() { - this.clearAllCardObjs(); - this.renderScatteredPool(); - for (let seat = 0; seat < this.gs.players.length; seat++) { - this.renderSeat(seat); - } - this.renderSeatChips(); - this.renderTurnIndicator(); - this.updateMatchesPanel(); - } - - renderScatteredPool() { - const localPickable = this.gs.phase === 'pick' && this.isLocalTurn(); - for (const card of this.gs.pool) { - const pos = this.poolCardPositions.get(card.id); - if (!pos) continue; - const c = this.makeCardSprite( - { label: '', suit: 's', suitSymbol: '' }, pos.x, pos.y, - { faceUp: false, rotation: pos.rot } - ); - c.setDepth(D.pool); - this.cardObjs.set(`pool-${card.id}`, c); - if (localPickable) { - c.setInteractive( - new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), - Phaser.Geom.Rectangle.Contains - ); - c.input.cursor = 'pointer'; - c.on('pointerover', () => { - 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 }); - c.setDepth(D.pool); - }); - c.on('pointerdown', () => this.onPoolCardClick(card.id)); - } - } - } - - renderSeat(seat) { - const player = this.gs.players[seat]; - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - const n = player.hand.length; - - for (let i = 0; i < n; i++) { - const card = player.hand[i]; - const offset = i - (n - 1) / 2; - let x, y; - if (layout.handAxis === 'x') { - x = layout.handCenter.x + offset * HAND_SPREAD; - y = layout.handCenter.y; - } else { - x = layout.handCenter.x; - y = layout.handCenter.y + offset * HAND_SPREAD; - } - const c = this.makeCardSprite(card, x, y, { - faceUp: layout.handFaceUp, - rotation: layout.rotateCards, - }); - this.cardObjs.set(`hand-${seat}-${card.id}`, c); - - c.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - c.input.cursor = 'pointer'; - if (seat === 0) { - c.on('pointerdown', () => this.onHandCardClick(card.rank)); - } else { - c.on('pointerdown', () => this.onOpponentClick(seat)); - c.on('pointerover', () => this.highlightOpponent(seat, true)); - c.on('pointerout', () => this.highlightOpponent(seat, false)); - } - } - - // Highlight selected rank for human seat. - if (seat === 0 && this.selectedRank) { - for (let i = 0; i < n; i++) { - const card = player.hand[i]; - if (card.rank !== this.selectedRank) continue; - const obj = this.cardObjs.get(`hand-${seat}-${card.id}`); - if (!obj) continue; - const ring = this.add.graphics(); - ring.lineStyle(3, COLORS.accent, 1); - ring.strokeRoundedRect(-CARD_W / 2 - 3, -CARD_H / 2 - 3, CARD_W + 6, CARD_H + 6, CARD_R + 2); - ring.setPosition(obj.x, obj.y); - ring.setDepth(D.highlight); - this.transientObjs.push(ring); - obj.setDepth(D.card + 2); - } - } - } - - renderSeatChips() { - for (let s = 0; s < this.gs.players.length; s++) { - const p = this.gs.players[s]; - const chip = this.seatChips[s]; - if (!chip) continue; - chip.count.setText(`${p.pairs}`); - } - } - - renderTurnIndicator() { - const seat = this.gs.currentPlayer; - const slot = this.slotForSeat[seat]; - const lay = slotLayout(slot); - 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); - } - - highlightOpponent(seat, on) { - if (!this.isLocalTurn() || !this.selectedRank) return; - const slot = this.slotForSeat[seat]; - const lay = slotLayout(slot); - if (on) { - const ring = this.add.graphics(); - ring.lineStyle(4, COLORS.gold, 0.9); - ring.strokeCircle(lay.portrait.x, lay.portrait.y, lay.portrait.r + 6); - ring.setDepth(D.portrait - 2); - this._hoverRing = ring; + const seat = gs.currentPlayer; + this.setSpot(spotFor(this.L, seat)); + if (seat === 0) { + this.mode = 'human'; + this.layout(); + this.updateDock(); + this.updatePlates(); } else { - this._hoverRing?.destroy(); - this._hoverRing = null; + this.mode = 'ai'; + this.selRank = null; + this.layout(); + this.updateDock(); + this.updatePlates(); + this.runAITurn(seat); } } - // ── Status / banner ──────────────────────────────────────────────────────── + // ── Speech + effects ─────────────────────────────────────────────────────── + bubble(seat, text, { ms = 1500, color = '#1a0e06', bg = '#fff4d6' } = {}) { + const at = bubbleAt(this.L, seat); + const t = this.add.text(at.x, at.y, text, { + fontFamily: 'Righteous', fontSize: '22px', color, backgroundColor: bg, padding: { x: 12, y: 7 }, + align: 'center', wordWrap: { width: 300 }, + }).setOrigin(0.5).setDepth(D.float).setScale(0.4); + this.tweens.add({ targets: t, scale: 1, duration: 170, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, y: t.y - 18, delay: ms, duration: 320, onComplete: () => t.destroy() }); + } - updateStatus() { - if (this.gameOver) { - this.statusText.setText(''); - this.statusBg.setVisible(false); - return; + splash(at) { + for (let i = 0; i < 3; i++) { + const r = this.add.ellipse(at.x, at.y, 30, 30 * SQ * 0.5, 0xbfe8ff, 0).setStrokeStyle(3, 0xbfe8ff, 0.8).setDepth(D.float); + this.tweens.add({ targets: r, scaleX: 4 + i, scaleY: 4 + i, alpha: 0, delay: i * 140, duration: 700, onComplete: () => r.destroy() }); } - if (this.gs?.phase === 'pick') { - this.statusText.setText( - this.isLocalTurn() - ? 'Click any face-down card from the center to draw.' - : `${this.opponentName(this.gs.currentPlayer)} is drawing…` - ); - this.refreshStatusBg(); - return; + for (let i = 0; i < 9; i++) { + const a = -Math.PI / 2 + (Math.random() - 0.5) * 2.2; + const d = this.add.circle(at.x, at.y, 3 + Math.random() * 3, 0xd6f2ff, 0.9).setDepth(D.float); + this.tweens.add({ targets: d, x: at.x + Math.cos(a) * (40 + Math.random() * 40), y: at.y + Math.sin(a) * (50 + Math.random() * 40), alpha: 0, duration: 520, ease: 'Quad.easeOut', onComplete: () => d.destroy() }); } - if (this.isLocalTurn()) { - if (this.selectedRank) { - this.statusText.setText(`Asking for ${this.selectedRank}s — tap an opponent to ask.`); - } else { - this.statusText.setText('Your turn — tap a card to choose what to ask for.'); - } + playSoundEx(this, SFX.WATER_SPLASH, { volume: 0.5 }); + } + + // A fishing line from the asker's seat to a card in the pond (with a bobber). + castLine(seat, to, ms) { + const from = seat === 0 ? { x: CX, y: 900 } : handHome(this.L, seat); + const g = this.lineG; + const prox = { t: 0 }; + return new Promise(res => { + this.tweens.add({ + targets: prox, t: 1, duration: ms, ease: 'Sine.easeOut', + onUpdate: () => { + const e = { x: from.x + (to.x - from.x) * prox.t, y: from.y + (to.y - from.y) * prox.t }; + const mid = { x: (from.x + e.x) / 2, y: (from.y + e.y) / 2 + 40 * prox.t }; + g.clear(); + g.lineStyle(2, 0xf2ead8, 0.85); + g.beginPath(); g.moveTo(from.x, from.y); + for (let k = 1; k <= 12; k++) { + const t = k / 12; + const x = (1 - t) * (1 - t) * from.x + 2 * (1 - t) * t * mid.x + t * t * e.x; + const y = (1 - t) * (1 - t) * from.y + 2 * (1 - t) * t * mid.y + t * t * e.y; + g.lineTo(x, y); + } + g.strokePath(); + g.fillStyle(0xe0392f, 1); g.fillCircle(e.x, e.y - 4, 6); + g.fillStyle(0xffffff, 1); g.fillCircle(e.x, e.y - 8, 3.5); + }, + onComplete: res, + }); + }); + } + + clearLine(delay = 0) { + this.time.delayedCall(delay, () => this.lineG?.clear()); + } + + // ── Asking ───────────────────────────────────────────────────────────────── + askPause() { return ASK_PAUSE[this.settings.askPause] ?? ASK_PAUSE.normal; } + + // Animate one ask from start to finish and apply it. Returns the new state. + // The asker holds up a card of the rank (face up, in front of them) and a + // line casts to the player asked; the table pauses. Then the answer: the + // cards handed over are laid out in front of the giver (or "Go fish!"), and + // the table pauses again before anything moves on. + async doAsk(asker, target, rank) { + const held = this.gs.players[asker].hand.find(c => c.rank === rank); + if (!held) return null; + const name = target === 0 ? 'you' : this.shortName(target); + this.show = { asker, target, askIds: [held.id], respIds: [] }; + this.layout({ duration: 380 }); + this.bubble(asker, `${target === 0 ? 'Hey' : name}, got any ${RANK_NAME[rank]}?`, { ms: this.askPause() + 300 }); + playSoundEx(this, SFX.UI_PICK, { volume: 0.4 }); + this.time.delayedCall(380, () => this.castLineBetween(showPose(this.L, asker), showPose(this.L, target), 420)); + await this.wait(380 + this.askPause()); + if (!this.alive()) { this.show = null; return null; } + const next = applyAsk(this.gs, target, rank); + if (next === this.gs) { this.show = null; this.lineG.clear(); this.layout(); return null; } + const la = next.lastAsk; + if (la.result === 'catch') { + const k = la.cardsTransferred.length; + this.show.respIds = la.cardsTransferred.map(c => c.id); + this.bubble(target, target === 0 ? `Here — ${k === 1 ? 'one' : k}` : (k === 1 ? 'Here you go…' : `Ugh — ${k} of them`), { ms: this.askPause() }); + if (target > 0) this.portraits[target]?.playEmotion?.('upset'); + if (asker > 0) this.portraits[asker]?.playEmotion?.('happy'); + this.commit(next, { flyMs: 420 }); + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.6 }); + await this.wait(420 + this.askPause()); } else { - this.statusText.setText(`${this.opponentName(this.gs.currentPlayer)} is thinking…`); + this.bubble(target, 'Go fish!', { ms: this.askPause(), bg: '#cdeeff' }); + this.splash(T.P.project(POND.u, POND.v)); + this.commit(next); + await this.wait(this.askPause() * 0.75); } - this.refreshStatusBg(); + if (!this.alive()) return next; + // everything goes home: the cards join the asker's hand (or a new book) + this.show = null; + this.lineG.clear(); + this.layout({ duration: 460 }); + await this.wait(460); + return next; } - refreshStatusBg() { - const t = this.statusText; - const 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); - } - - showBanner(text) { - this.bannerText.setText(text); - this.bannerText.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); - } - - 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'; - const opp = this.opponents[seat - 1]; - return opp?.name ?? `P${seat + 1}`; - } - - onHandCardClick(rank) { - if (!this.isLocalTurn() || this.animating) return; - const legal = legalRanksToAsk(this.gs, 0); - if (!legal.includes(rank)) return; - this.selectedRank = (this.selectedRank === rank) ? null : rank; - this.renderAll(); - this.updateStatus(); - } - - onOpponentClick(targetSeat) { - if (!this.isLocalTurn() || this.animating) return; - if (!this.selectedRank) { - this.showBanner('Pick a card from your hand first.'); - this.time.delayedCall(1400, () => this.hideBanner()); - return; - } - const target = this.gs.players[targetSeat]; - if (!target || target.sittingOut || target.hand.length === 0) { - this.showBanner(`${this.opponentName(targetSeat)} has no cards to give.`); - this.time.delayedCall(1400, () => this.hideBanner()); - return; - } - this.executeAsk(0, targetSeat, this.selectedRank); - } - - executeAsk(askerSeat, targetSeat, rank) { - this.animating = true; - const before = this.gs; - const after = applyAsk(before, targetSeat, rank); - if (after === before) { this.animating = false; return; } - const last = after.lastAsk; - - this.animateAsk(askerSeat, targetSeat, rank, last, before, (liveSprites) => { - // Fish with pool cards remaining — player must pick interactively. - if (after.phase === 'pick') { - this.gs = after; - this.selectedRank = null; - for (let s = 0; s < this.gs.players.length; s++) { - observeLog(this.aiMemory[s], this.gs, s); - } - this.renderAll(); - this.updateStatus(); - this.animating = false; - this.maybeStartAITurn(); - return; - } - - // Catch, or fish with empty pool — normal completion. - if (last.result === 'catch' && askerSeat !== 0) { - if (!this.aiTurnExclusions.has(askerSeat)) this.aiTurnExclusions.set(askerSeat, new Set()); - this.aiTurnExclusions.get(askerSeat).add(`${targetSeat}:${rank}`); - } - if (last.result === 'catch' && targetSeat !== 0) { - this.opponentPortraits[targetSeat]?.playEmotion('upset'); - } - this.showBanner(this.formatAskBanner(last)); - playSound(this, last.result === 'catch' ? SFX.CARD_PLACE : SFX.CARD_DEAL); - - this.gs = after; - this.selectedRank = null; - - for (let s = 0; s < this.gs.players.length; s++) { - observeLog(this.aiMemory[s], this.gs, s); - } - - if (last.newPairs > 0 && last.pairedCards?.length >= 2) { - if (askerSeat !== 0) this.opponentPortraits[askerSeat]?.playEmotion('happy'); - // Cards from animateAsk are already visible in position. - // Do NOT call renderAll() here — it would destroy the liveSprites. - // renderAll() is deferred to after the pair + refill animations complete. - this.hideBanner(); - this.animatePairedCards(askerSeat, last.pairedCards, () => { - this.playRefillsThenFinish(() => { - this.animating = false; - if (isGameOver(this.gs)) { this.endGame(); return; } - this.maybeStartAITurn(); - }); - }, liveSprites ?? null); - } else { - this.time.delayedCall(900, () => { - this.hideBanner(); - this.playRefillsThenFinish(() => { - this.animating = false; - if (isGameOver(this.gs)) { this.endGame(); return; } - this.maybeStartAITurn(); - }); - }); - } - }); - } - - animateAsk(askerSeat, targetSeat, rank, last, beforeState, onComplete) { - const askerSlot = this.slotForSeat[askerSeat]; - const askerLayout = slotLayout(askerSlot); - const askerShow = this.slotShowPos(askerSlot, askerLayout); - const targetSlot = this.slotForSeat[targetSeat]; - const targetLayout = slotLayout(targetSlot); - const targetShow = this.slotShowPos(targetSlot, targetLayout); - - const askerCard = beforeState.players[askerSeat].hand.find(c => c.rank === rank); - if (!askerCard) { onComplete(); return; } - - const existingSprite = this.cardObjs.get(`hand-${askerSeat}-${askerCard.id}`); - const askerSprite = existingSprite - ?? this.makeCardSprite(askerCard, askerLayout.handCenter.x, askerLayout.handCenter.y, { - faceUp: askerLayout.handFaceUp, rotation: 0, - }); - if (existingSprite) this.cardObjs.delete(`hand-${askerSeat}-${askerCard.id}`); - const origX = askerSprite.x; - const origY = askerSprite.y; - askerSprite.setDepth(D.banner - 4); - this.transientObjs.push(askerSprite); - - // Move asker card to show zone then flip it face-up (skip flip if already face-up). + // A line (with bobber) from one show spot to another, left up while the ask is on display. + castLineBetween(from, to, ms) { + const g = this.lineG; + const prox = { t: 0 }; this.tweens.add({ - targets: askerSprite, - x: askerShow.x, y: askerShow.y, - duration: 280, - ease: 'Cubic.easeOut', - onComplete: () => { - if (!askerLayout.handFaceUp) this.flipCardFaceUp(askerSprite, askerCard); - }, - }); - - // After card is revealed, cast fishing line toward the target, then show result. - this.time.delayedCall(640, () => { - this.animateFishingLine(askerShow.x, askerShow.y, targetShow.x, targetShow.y, () => { - if (last.result === 'catch') { - const n = last.cardsTransferred.length; - const isTargetVert = targetSlot === 'left' || targetSlot === 'right'; - const targetSprites = last.cardsTransferred.map((card, i) => { - const tx = isTargetVert ? targetShow.x - : targetShow.x + (i - (n - 1) / 2) * (CARD_W + 8); - const ty = isTargetVert ? targetShow.y + (i - (n - 1) / 2) * (CARD_H + 8) - : targetShow.y; - const existingTargetSprite = this.cardObjs.get(`hand-${targetSeat}-${card.id}`); - const sprite = existingTargetSprite - ?? this.makeCardSprite(card, targetLayout.handCenter.x, targetLayout.handCenter.y, { - faceUp: targetLayout.handFaceUp, rotation: 0, - }); - if (existingTargetSprite) this.cardObjs.delete(`hand-${targetSeat}-${card.id}`); - sprite.setDepth(D.banner - 4); - this.transientObjs.push(sprite); - this.tweens.add({ - targets: sprite, - x: tx, y: ty, - duration: 250, - delay: i * 80, - ease: 'Cubic.easeOut', - onComplete: () => { - if (!targetLayout.handFaceUp) this.flipCardFaceUp(sprite, card); - }, - }); - return { sprite, tx, ty }; - }); - - // After target cards are shown, fan all sprites into a holding position - // at the asker's show zone — they stay visible for the pair animation. - const waitMs = 250 + (n - 1) * 80 + 380; - this.time.delayedCall(waitMs, () => { - const FGAP = 8; - const nTotal = 1 + targetSprites.length; - const isAskerVert = askerSlot === 'left' || askerSlot === 'right'; - const allSprites = [ - askerSprite, - ...targetSprites.map(({ sprite }) => sprite), - ].map((sprite, i) => { - const x = isAskerVert - ? askerShow.x - : askerShow.x + (i - (nTotal - 1) / 2) * (CARD_W + FGAP); - const y = isAskerVert - ? askerShow.y + (i - (nTotal - 1) / 2) * (CARD_H + FGAP) - : askerShow.y; - return { sprite, x, y }; - }); - - for (const { sprite, x, y } of allSprites) { - if (!sprite.active) continue; - this.tweens.add({ targets: sprite, x, y, duration: 280, ease: 'Cubic.easeOut' }); - } - this.time.delayedCall(320, () => onComplete(allSprites)); - }); - } else { - // Fish — flip card back face-down (if needed) and return it to hand. - if (!askerLayout.handFaceUp) this.flipCardFaceDown(askerSprite); - const returnDelay = askerLayout.handFaceUp ? 80 : 340; - this.time.delayedCall(returnDelay, () => { - this.tweens.add({ - targets: askerSprite, - x: origX, y: origY, - duration: 280, ease: 'Cubic.easeIn', - onComplete: () => { if (askerSprite.active) askerSprite.destroy(); }, - }); - this.time.delayedCall(320, onComplete); - }); + targets: prox, t: 1, duration: ms, ease: 'Sine.easeOut', + onUpdate: () => { + if (!this.show) { g.clear(); return; } + const e = { x: from.x + (to.x - from.x) * prox.t, y: from.y + (to.y - from.y) * prox.t }; + const mid = { x: (from.x + e.x) / 2, y: (from.y + e.y) / 2 + 50 * prox.t }; + g.clear(); + g.lineStyle(2.5, 0xf2ead8, 0.8); + g.beginPath(); g.moveTo(from.x, from.y); + for (let k = 1; k <= 14; k++) { + const t = k / 14; + g.lineTo((1 - t) * (1 - t) * from.x + 2 * (1 - t) * t * mid.x + t * t * e.x, (1 - t) * (1 - t) * from.y + 2 * (1 - t) * t * mid.y + t * t * e.y); } - }); - }); - } - - slotShowPos(slot, layout) { - const GAP = 10; - switch (slot) { - case 'bottom': return { x: layout.handCenter.x, y: layout.handCenter.y - CARD_H / 2 - GAP - CARD_H / 2 }; - case 'top': return { x: layout.handCenter.x, y: layout.handCenter.y + CARD_H / 2 + GAP + CARD_H / 2 }; - case 'left': return { x: layout.handCenter.x + CARD_H / 2 + GAP + CARD_W / 2, y: layout.handCenter.y }; - case 'right': return { x: layout.handCenter.x - CARD_H / 2 - GAP - CARD_W / 2, y: layout.handCenter.y }; - default: return { x: CX, y: CY }; - } - } - - 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' }); + g.strokePath(); + g.fillStyle(0xe0392f, 1); g.fillCircle(e.x, e.y - 4, 7); + g.fillStyle(0xffffff, 1); g.fillCircle(e.x, e.y - 9, 4); }, }); } - 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' }); - }, - }); + // A fish pick: line out to the card, reel it in. + async doFish(seat, cardId) { + const v = this._lastVisible.get(cardId); + const to = v?.pose ?? poolPose(cardId); + const T0 = seat ? this.timing(seat) : { reach: 260 }; + if (seat) this.moveHand(seat, to, T0.reach); + await this.castLine(seat, to, Math.max(240, T0.reach)); + if (!this.alive()) return; + const prevRank = this.gs.lastAsk.rank; + const next = applyFishPick(this.gs, cardId); + if (next === this.gs) { this.clearLine(); return; } + this.splash(to); + this.commit(next, { flyMs: 520 }); + this.clearLine(300); + if (seat) this.handRest(seat, 500, 300); + if (next.lastAsk.result === 'lucky') { + this.stamp('Lucky catch!', { x: CX, y: CY - 60 }, '#7cf0a0', { size: 58, sub: `${seat === 0 ? 'You' : this.shortName(seat)} drew the ${RANK_ONE[prevRank] ?? prevRank} — go again`, hold: 1100 }); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.6 }); + } + await this.wait(650); } - animatePairedCards(askerSeat, pairedCards, onComplete, preSprites = null) { - if (preSprites) { - // Cards are already face-up and in position from animateAsk — skip sprite creation. - const sprites = preSprites.map(({ sprite, x, y }) => ({ sprite, targetX: x, targetY: y })); - playSound(this, SFX.CARD_PLACE); - this.time.delayedCall(200, () => { - const cx = sprites.reduce((s, { targetX }) => s + targetX, 0) / sprites.length; - const cy = sprites.reduce((s, { targetY }) => s + targetY, 0) / sprites.length; - this.spawnFireworks(cx, cy); - this.time.delayedCall(350, () => 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: 500, ease: 'Cubic.easeIn', - onComplete: () => { if (sprite.active) sprite.destroy(); }, - }); - } - }); - this.time.delayedCall(1800, onComplete); - return; - } - - const slot = this.slotForSeat[askerSeat]; - const layout = slotLayout(slot); - 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 targetX, targetY; - switch (slot) { - case 'bottom': - targetX = CX - totalW / 2 + CARD_W / 2 + i * (CARD_W + GAP); - targetY = layout.handCenter.y - CARD_H / 2 - GAP - CARD_H / 2; - break; - case 'top': - targetX = CX - totalW / 2 + CARD_W / 2 + i * (CARD_W + GAP); - targetY = layout.handCenter.y + CARD_H / 2 + GAP + CARD_H / 2; - break; - case 'left': { - const leftmostX = layout.handCenter.x + CARD_H / 2 + GAP + CARD_W / 2; - targetX = leftmostX + i * (CARD_W + GAP); - targetY = CY; - break; - } - case 'right': { - const rightmostX = layout.handCenter.x - CARD_H / 2 - GAP - CARD_W / 2; - targetX = rightmostX - (n - 1 - i) * (CARD_W + GAP); - targetY = CY; - break; - } - default: - targetX = CX; targetY = CY; - } - - const sprite = this.makeCardSprite(pairedCards[i], CX, CY, { faceUp: true, rotation: 0 }); - sprite.setDepth(D.banner - 5); - sprite.setAlpha(0); - this.transientObjs.push(sprite); - - this.tweens.add({ - targets: sprite, - x: targetX, y: targetY, alpha: 1, - duration: 300, - ease: 'Back.easeOut', - }); - - sprites.push({ sprite, targetX, targetY }); - } - - playSound(this, SFX.CARD_PLACE); - - this.time.delayedCall(350, () => { - const cx = sprites.reduce((s, { targetX: tx }) => s + tx, 0) / sprites.length; - const cy = sprites.reduce((s, { targetY: ty }) => s + ty, 0) / sprites.length; - this.spawnFireworks(cx, cy); - this.time.delayedCall(350, () => this.spawnFireworks(cx, cy)); + // Apply a new state: cards move, books form, refills fly in. + commit(next, { flyMs = 320 } = {}) { + const prev = this.gs; + this.gs = next; + const fresh = next.log.slice(prev.log.length); + if (this.settings.sort !== 'manual') this.sortHand(); + // books form a beat after the cards arrive + const bookIds = new Set(next.players.flatMap((p, s) => p.books.flat().map(c => c.id)).filter(id => !prev.players.some(pp => pp.books.flat().some(c => c.id === id)))); + this.layout({ + durationFor: (v) => (bookIds.has(v.card.id) ? 520 : flyMs), + delayFor: (v) => (bookIds.has(v.card.id) ? flyMs + 300 : 0), }); - - this.time.delayedCall(1600, () => { - for (const { sprite } of sprites) { - if (!sprite.active) continue; - this.tweens.add({ - targets: sprite, - x: CX, y: CY, alpha: 0, - duration: 500, - ease: 'Cubic.easeIn', - onComplete: () => { if (sprite.active) sprite.destroy(); }, + for (const e of fresh) { + if (e.kind === 'pair') { + const p = this.gs.players[e.seat]; + const at = bookPose(this.L, e.seat, p.books.length - 1, p.books.length); + this.time.delayedCall(flyMs + 500, () => { + this.floatText(at, `${this.matchSize === 4 ? 'Book' : 'Pair'} of ${RANK_NAME[e.rank]}!`, SEAT_HEX[e.seat], { size: 24, ms: 1400 }); + this.burst(at, SEAT_COLORS[e.seat], { n: 8, r: 60 }); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.5 }); }); + } else if (e.kind === 'sitout') { + this.floatText(bubbleAt(this.L, e.seat), `${e.seat === 0 ? 'You are' : `${this.shortName(e.seat)} is`} out of cards`, '#f2d6a0', { size: 20, ms: 1600 }); } - }); - - this.time.delayedCall(2200, onComplete); - } - - // ── Refill animation ────────────────────────────────────────────────────── - - animateRefill(seat, drawnCards, onComplete) { - if (drawnCards.length === 0) { onComplete(); return; } - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - const finalHand = this.gs.players[seat].hand; - const STAGGER = 130; - const FLY = 340; - const targetRot = (layout.rotateCards * Math.PI) / 180; - - const name = this.opponentName(seat); - this.showBanner(`${name}'s hand was empty — drawing new cards…`); - - drawnCards.forEach((card, i) => { - this.time.delayedCall(i * STAGGER, () => { - // Re-use the existing face-down pool sprite if still in cardObjs. - const poolKey = `pool-${card.id}`; - const existing = this.cardObjs.get(poolKey); - let sprite; - if (existing) { - this.cardObjs.delete(poolKey); - this.transientObjs.push(existing); - sprite = existing; - } else { - const pos = this.poolCardPositions.get(card.id) ?? POOL_POS; - sprite = this.makeCardSprite(card, pos.x, pos.y, { faceUp: false }); - this.transientObjs.push(sprite); - } - sprite.setDepth(D.card + 5); - - // Destination: the card's actual position in the final hand. - const cardInHand = finalHand.find(c => c.id === card.id); - let destX = layout.handCenter.x; - let destY = layout.handCenter.y; - if (cardInHand) { - const n = finalHand.length; - const idx = finalHand.indexOf(cardInHand); - const offset = idx - (n - 1) / 2; - if (layout.handAxis === 'x') destX = layout.handCenter.x + offset * HAND_SPREAD; - else destY = layout.handCenter.y + offset * HAND_SPREAD; - } - - if (i % 2 === 0) playSound(this, SFX.CARD_DEAL); - - this.tweens.add({ - targets: sprite, x: destX, y: destY, rotation: targetRot, - duration: FLY, ease: 'Cubic.easeOut', - onComplete: () => { - if (seat === 0 && cardInHand) this.flipCardFaceUp(sprite, card); - }, - }); - }); - }); - - const total = (drawnCards.length - 1) * STAGGER + FLY + (seat === 0 ? 380 : 160); - this.time.delayedCall(total, () => { - this.hideBanner(); - onComplete(); - }); - } - - // Run each refill entry sequentially, then call renderAll + updateStatus + onDone. - playRefillsThenFinish(onDone) { - const refills = (this.gs.lastAsk?.refills ?? []).filter(r => r.cards.length > 0); - const next = (idx) => { - if (idx >= refills.length) { - this.renderAll(); - this.updateStatus(); - onDone(); - return; - } - const { seat, cards } = refills[idx]; - this.animateRefill(seat, cards, () => next(idx + 1)); - }; - next(0); - } - - spawnFireworks(cx, cy) { - const BURST_COLORS = [0xd4a017, 0xe06c75, 0x61afef, 0xc678dd, 0x98c379, 0xe5c07b]; - const COUNT = 20; - for (let i = 0; i < COUNT; i++) { - const angle = (i / COUNT) * Math.PI * 2; - const dist = 70 + Math.random() * 70; - const color = BURST_COLORS[i % BURST_COLORS.length]; - const r = 3 + Math.random() * 4; - const g = this.add.graphics().setDepth(D.banner - 2); - g.fillStyle(color, 1); - g.fillCircle(0, 0, r); - 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(); }, - }); } + this.observeAll(); + this.updatePlates(); + this.updateDock(); } - onPoolCardClick(cardId) { - if (!this.isLocalTurn() || this.animating || this.gs.phase !== 'pick') return; - this.doFishPick(cardId); + // ── 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 || this.gs.phase !== 'play') return; + observeLog(this.memories[seat], this.gs, seat); + const a = chooseAction(this.gs, seat, this.memories[seat]); + if (!a) { this.advance(); return; } + // the ghost hand points at the player being asked + this.moveHand(seat, a.targetSeat === 0 ? { x: CX, y: 860 } : handHome(this.L, a.targetSeat), T0.reach); + const next = await this.doAsk(seat, a.targetSeat, a.rank); + this.handRest(seat, 400, 200); + if (!this.alive() || token !== this.turnToken) return; + if (!next) { this.advance(); return; } + await this.wait(250); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); } - runAIFishPick() { - if (this.gameOver || this.animating) return; - if (this.gs.phase !== 'pick' || this.isLocalTurn()) return; + async aiFish(seat) { + const token = ++this.turnToken; + const T0 = this.timing(seat); + await this.wait(T0.hesitate); + if (!this.alive() || token !== this.turnToken || this.gs.phase !== 'pick') return; const pool = this.gs.pool; - if (pool.length === 0) return; - const card = pool[Math.floor(Math.random() * pool.length)]; - this.doFishPick(card.id); + const pick = pool[Math.floor(Math.random() * pool.length)]; + await this.doFish(seat, pick.id); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); } - doFishPick(cardId) { - this.animating = true; - const askerSeat = this.gs.lastAsk.askerSeat; - const after = applyFishPick(this.gs, cardId); - if (after === this.gs) { this.animating = false; return; } - - const sprite = this.cardObjs.get(`pool-${cardId}`); - if (sprite) this.cardObjs.delete(`pool-${cardId}`); - this.poolCardPositions.delete(cardId); - - const continueAfterDraw = () => { - const last = after.lastAsk; - this.showBanner(this.formatAskBanner(last)); - playSound(this, SFX.CARD_DEAL); - this.gs = after; - this.selectedRank = null; - for (let s = 0; s < this.gs.players.length; s++) { - observeLog(this.aiMemory[s], this.gs, s); - } - if (last.newPairs > 0 && last.pairedCards?.length >= 2) { - if (askerSeat !== 0) this.opponentPortraits[askerSeat]?.playEmotion('happy'); - this.time.delayedCall(600, () => { - this.hideBanner(); - this.animatePairedCards(askerSeat, last.pairedCards, () => { - this.playRefillsThenFinish(() => { - this.animating = false; - if (isGameOver(this.gs)) { this.endGame(); return; } - this.maybeStartAITurn(); - }); - }); + // ── 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); }; + gs.pool.forEach(c => put(c, { kind: 'pool', pose: poolPose(c.id), faceUp: false, depth: D.cards + ((c.id * 7) % 50) * 0.01 })); + for (const p of gs.players) { + const seat = p.seat; + p.books.forEach((book, bi) => { + const base = bookPose(this.L, seat, bi, p.books.length); + book.forEach((c, ci) => { + const pose = { ...base, x: base.x + ci * 1.5, y: base.y - ci * 2.2 }; + put(c, { kind: 'book', seat, idx: bi, pose, faceUp: true, depth: D.cards + 3 + bi * 0.05 + ci * 0.01 }); }); - } else { - this.time.delayedCall(900, () => { - this.hideBanner(); - this.playRefillsThenFinish(() => { - this.animating = false; - if (isGameOver(this.gs)) { this.endGame(); return; } - this.maybeStartAITurn(); - }); - }); - } - }; - - if (sprite) { - const revealCard = askerSeat === 0 ? after.lastAsk.drawnCard : null; - const drawnCard = after.lastAsk.drawnCard; - const newHand = after.players[askerSeat].hand; - const cardIndex = newHand.findIndex(c => c.id === drawnCard.id); - const askerLayout = slotLayout(this.slotForSeat[askerSeat]); - let destX, destY; - if (askerLayout.handAxis === 'x') { - destX = askerLayout.handCenter.x + (cardIndex - (newHand.length - 1) / 2) * HAND_SPREAD; - destY = askerLayout.handCenter.y; - } else { - destX = askerLayout.handCenter.x; - destY = askerLayout.handCenter.y + (cardIndex - (newHand.length - 1) / 2) * HAND_SPREAD; - } - this.animateFishDraw(sprite, revealCard, destX, destY, continueAfterDraw); - } else { - this.time.delayedCall(50, continueAfterDraw); - } - } - - animateFishDraw(sprite, revealCard, destX, destY, onComplete) { - sprite.setDepth(D.banner - 4); - this.transientObjs.push(sprite); - - const flyToHand = () => { - this.tweens.add({ - targets: sprite, - x: destX, y: destY, - rotation: 0, - duration: 400, - ease: 'Cubic.easeIn', - onComplete: () => onComplete(), }); - }; + 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 = 0; + if (this.selRank && c.rank === this.selRank) lift = 40; + else if (id === this.hoverId) lift = 24; + put(c, { kind: 'hand', seat: 0, idx: i, pose: handPose(this.L, 0, i, ids.length, lift), faceUp: true, depth: D.hand + i * 0.01 }); + }); + } else { + p.hand.forEach((c, i) => put(c, { kind: 'hand', seat, idx: i, pose: handPose(this.L, seat, i, p.hand.length), faceUp: this.revealAll, depth: D.oppHand + i * 0.01 })); + } + } + // an ask on display: the asker's card held up, the answer laid out by the giver + if (this.show) { + const byId = new Map(); + for (const p of gs.players) for (const c of [...p.hand, ...p.books.flat()]) byId.set(c.id, c); + const place = (ids, seat) => 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.hand + 2 + i * 0.01 }); + }); + place(this.show.askIds, this.show.asker); + place(this.show.respIds, this.show.target); + } + return { visible, loc }; + } - if (revealCard) { - // Human pick: flip face-up in place, pause to show the card, then fly to hand. - this.flipCardFaceUp(sprite, revealCard); - this.time.delayedCall(700, flyToHand); - } else { - flyToHand(); + beforeLayout() { + this.suggest = this.mode === 'human' && this.settings.hints ? this.suggestion() : null; + } + + suggestion() { + if (!this.gs || this.gs.phase !== 'play' || this.gs.currentPlayer !== 0 || !canAsk(this.gs, 0)) return null; + observeLog(this.hintMem, this.gs, 0); + return chooseAction(this.gs, 0, this.hintMem); + } + + decorate(c, v) { + const mine = v.kind === 'hand' && v.seat === 0; + const star = mine && this.suggest && c.card.rank === this.suggest.rank; + c.mark.setText(star ? '★' : '').setColor('#ffd35a').setVisible(!!star && v.faceUp); + c.chip.setVisible(false); + c.glow.setVisible(mine && this.selRank === c.card.rank).setTint(0xffd35a).setAlpha(1); + c.faceImg.setTint(0xffffff); + } + + afterLayout() { + for (let s = 1; s < this.playerCount; s++) this.badges[s]?.t.setText(String(this.gs.players[s].hand.length)); + this.pondTxt.setText(this.gs.pool.length ? `${this.gs.pool.length} in the pond` : 'the pond is empty'); + this.drawTargets(); + } + + // When you've picked a rank, the players you could ask light up. + drawTargets(hover = null) { + const g = this.targetG; + g.clear(); + const rank = this.dragState ? this.gs.players[0].hand.find(c => c.id === this.dragState.id)?.rank : this.selRank; + if (!rank || this.mode !== 'human') return; + for (const s of this.askable()) { + const r = this.targetRect(s); + const hot = hover === s; + g.fillStyle(SEAT_COLORS[s], hot ? 0.22 : 0.08); + g.fillRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 16); + g.lineStyle(hot ? 4 : 2.5, SEAT_COLORS[s], hot ? 1 : 0.75); + g.strokeRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 16); } } - animateFishingLine(fromX, fromY, toX, toY, onComplete) { - const gfx = this.add.graphics().setDepth(D.banner - 3); - const totalDx = toX - fromX, totalDy = toY - fromY; - const totalLen = Math.sqrt(totalDx * totalDx + totalDy * totalDy) || 1; - const ndx = totalDx / totalLen, ndy = totalDy / totalLen; - const px = -ndy, py = ndx; // left-perpendicular to line direction - const HOOK_R = 10; - const BARB_LEN = 7; - const SWEEP = (4 * Math.PI) / 3; // 240° + askable() { + return this.gs.players.filter(p => p.seat !== 0 && !p.sittingOut && p.hand.length > 0).map(p => p.seat); + } - const drawFrame = (t) => { - gfx.clear(); - gfx.lineStyle(2, 0xffe066, 1); - const tipX = fromX + t * totalDx; - const tipY = fromY + t * totalDy; + targetRect(seat) { + return seatTargetRect(this.L, seat, this.gs.players[seat].hand.length); + } - gfx.beginPath(); - gfx.moveTo(fromX, fromY); - gfx.lineTo(tipX, tipY); - gfx.strokePath(); + 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(`${p.pairs} ${this.matchSize === 4 ? 'bk' : 'pr'}`); + pl.infoTxt.setText(`${p.hand.length} card${p.hand.length === 1 ? '' : 's'}`); + pl.statusTxt.setText(p.sittingOut ? 'out of cards' : '').setColor('#e8d6b0'); + const active = !isGameOver(gs) && (gs.phase === 'pick' ? gs.lastAsk.askerSeat : gs.currentPlayer) === s; + this.setPlateActive(s, active && (this.mode === 'human' || this.mode === 'ai' || this.mode === 'fishing')); + } + } - // Hook arc offset perpendicular from tip - const hookCx = tipX + px * HOOK_R; - const hookCy = tipY + py * HOOK_R; - const startAngle = Math.atan2(tipY - hookCy, tipX - hookCx); - const endAngle = startAngle + SWEEP; - gfx.beginPath(); - gfx.arc(hookCx, hookCy, HOOK_R, startAngle, endAngle, false); - gfx.strokePath(); + // ── Dock ──────────────────────────────────────────────────────────────────── + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const extra = [{ label: 'Ask log (Q)', act: () => this.openAskLog() }]; + if (this.mode === 'deal') { this.setDock('Dealing… the rest go in the pond.'); return; } + if (this.mode === 'ending' || this.mode === 'summary') { this.setDock('Game over!'); return; } + if (this.mode === 'fishing') { + this.setDock(`Go fish! Pick any card from the pond — hoping for ${RANK_NAME[gs.lastAsk.rank]}.`, [ + { label: 'Fish for me (F)', act: () => this.fishRandom(), hot: true }, ...extra, + ]); + return; + } + if (this.mode === 'human') { + const targets = this.askable(); + if (!this.selRank) { + this.setDock(targets.length === 1 ? `Click a card to ask ${this.shortName(targets[0])} for that rank.` : 'Pick a card from your hand, then the player to ask.', [ + { label: 'Suggest (A)', act: () => this.suggestPick() }, ...extra, + ]); + return; + } + this.setDock(`Ask who for ${RANK_NAME[this.selRank]}?`, [ + ...targets.map(s => ({ label: `Ask ${this.shortName(s, 9)}`, act: () => this.humanAsk(s), hot: this.suggest?.rank === this.selRank && this.suggest?.targetSeat === s })), + ...extra, + ].slice(0, 4)); + return; + } + this.setDock(`${this.nameForSeat(gs.phase === 'pick' ? gs.lastAsk.askerSeat : gs.currentPlayer)} is playing…`, extra); + } - // Barb at hook tip - const barbX = hookCx + HOOK_R * Math.cos(endAngle); - const barbY = hookCy + HOOK_R * Math.sin(endAngle); - gfx.beginPath(); - gfx.moveTo(barbX, barbY); - gfx.lineTo(barbX - Math.sin(endAngle) * BARB_LEN, barbY + Math.cos(endAngle) * BARB_LEN); - gfx.strokePath(); + // ── Human actions ─────────────────────────────────────────────────────────── + sortHand() { + if (!this.gs || this.settings.sort === 'manual') return; + const hand = this.gs.players[0].hand; + const counts = {}; + for (const c of hand) counts[c.rank] = (counts[c.rank] ?? 0) + 1; + const ord = (c) => RANK_ORDER.indexOf(c.rank); + if (this.settings.sort === 'most') hand.sort((a, b) => counts[b.rank] - counts[a.rank] || ord(a) - ord(b) || a.id - b.id); + else hand.sort((a, b) => ord(a) - ord(b) || a.id - b.id); + } + + canAct() { return this.mode === 'human' && !this.modal && !this.paused && !this.busy; } + + pickRank(rank) { + if (!this.canAct()) return; + const targets = this.askable(); + if (targets.length === 1) { this.selRank = rank; this.humanAsk(targets[0]); return; } + this.selRank = this.selRank === rank ? null : rank; + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + this.updateDock(); + } + + async humanAsk(target) { + if (!this.canAct() || !this.selRank) return; + const rank = this.selRank; + this.selRank = null; + this.busy = true; + this.mode = 'idle'; + this.targetG.clear(); + this.layout({ duration: 140 }); + this.updateDock(); + const next = await this.doAsk(0, target, rank); + this.busy = false; + if (!this.alive()) return; + await this.wait(250); + if (!this.alive()) return; + this.advance(); + } + + suggestPick() { + if (!this.canAct()) return; + const s = this.suggestion(); + if (!s) return; + this.selRank = s.rank; + this.layout({ duration: 140 }); + this.updateDock(); + this.drawTargets(s.targetSeat); + this.floatText({ x: CX, y: 860 }, `Ask ${this.shortName(s.targetSeat)} for ${RANK_NAME[s.rank]}`, '#7cf0a0', { size: 22, ms: 1800, rise: 20 }); + } + + async fish(cardId) { + if (this.mode !== 'fishing' || this.modal || this.busy) return; + this.busy = true; + this.mode = 'idle'; + this.hoverPool = null; + this.updateDock(); + await this.doFish(0, cardId); + this.busy = false; + if (!this.alive()) return; + this.advance(); + } + + fishRandom() { + const pool = this.gs.pool; + if (pool.length) this.fish(pool[Math.floor(Math.random() * pool.length)].id); + } + + // ── 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); } + + liftFor(ids) { + const hand = this.gs.players[0].hand; + return (i) => { + const c = hand.find(h => h.id === ids[i]); + return this.selRank && c?.rank === this.selRank ? 40 : ids[i] === this.hoverId ? 24 : 0; }; + } - const progress = { t: 0 }; - this.tweens.add({ - targets: progress, - t: 1, - duration: 1000, - ease: 'Cubic.easeOut', - onUpdate: () => drawFrame(progress.t), - onComplete: () => { - drawFrame(1); - this.time.delayedCall(150, () => { - this.tweens.add({ - targets: gfx, - alpha: 0, - duration: 250, - ease: 'Linear', - onComplete: () => { gfx.destroy(); onComplete(); }, - }); - }); - }, + handIdAt(pt) { + const ids = this.heldIds(); + const i = fanHit(this.L.seats[0].fan, ids.length, pt, this.liftFor(ids)); + return i >= 0 ? ids[i] : null; + } + + poolCardAt(pt) { + if (!inPond(pt)) return null; + const vs = [...this._lastVisible.values()].filter(v => v.kind === 'pool').sort((a, b) => b.depth - a.depth); + for (const v of vs) if (inPose(pt, v.pose, 4)) return v.card.id; + return null; + } + + seatAt(pt) { + for (const s of this.askable()) { + if (inRect(pt, this.targetRect(s))) return s; + const pl = this.L.seats[s].plate; + if (Math.abs(pt.x - pl.x) <= 150 && Math.abs(pt.y - pl.y) <= 48) return s; + } + return null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState || this.overUI(over)) return; + if (this.mode === 'fishing') { + const id = this.poolCardAt(pointer); + if (id != null) this.fish(id); + 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 }; return; } + if (this.mode === 'human' && this.selRank) { + const s = this.seatAt(pointer); + if (s != null) this.humanAsk(s); + } + } + + 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; + } + if (pointer.isDown || this.modal || !this.gs) return; + if (this.mode === 'fishing') { + const id = this.poolCardAt(pointer); + this.hoverPool = id; + this.input.setDefaultCursor(id != null ? 'pointer' : 'default'); + return; + } + if (this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const id = this.handIdAt(pointer); + if (id !== this.hoverId) { this.hoverId = id; this.layout({ duration: 120 }); } + const seat = this.mode === 'human' && this.selRank ? this.seatAt(pointer) : null; + if (this.selRank) this.drawTargets(seat); + this.input.setDefaultCursor(id != null || seat != null ? 'pointer' : 'default'); + } + + onPointerUp() { + if (this.dragState) { this.endDrag(); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + if (!this.canAct()) { + if (this.mode === 'ai') this.floatText({ x: CX, y: 870 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); + return; + } + const c = this.gs.players[0].hand.find(h => h.id === pd.id); + if (c) this.pickRank(c.rank); + } + + 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); + } + + dropTargetAt(pt) { + if (this.mode === 'human') { + const s = this.seatAt(pt); + if (s != null) return { type: 'ask', seat: s }; + } + const ids = this.heldIds(); + if (inRect(pt, fanZone(this.L.seats[0].fan, ids.length))) return { type: 'hand', at: fanInsertIndex(this.L.seats[0].fan, ids.length, pt.x) }; + return null; + } + + updateDrag(pointer) { + const ds = this.dragState; + const x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const t = Math.max(0, Math.min(1, (y - 500) / 460)); + this.applyPose(ds.sprite, { x, y, rot: 0, s: 0.6 + 0.4 * t, q: SQ + (1 - SQ) * t }, 1); + ds.target = this.dropTargetAt(pointer); + const order = ds.target?.type === 'hand' ? CardTableScene.reorderPreview(this.heldIds(), 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); + this.drawTargets(ds.target?.type === 'ask' ? ds.target.seat : null); + } + + cancelDrag() { + if (!this.dragState) return; + this.dragState = null; + this.dragPreview = null; + this.drawDropSlot(null); + this.targetG?.clear(); + this.layout(); + } + + endDrag() { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.drawDropSlot(null); + this.targetG.clear(); + const t = ds.target; + this.dragPreview = null; + if (t?.type === 'hand') { + const order = CardTableScene.reorderPreview(this.heldIds(), ds.id, t.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(); + return; + } + if (t?.type === 'ask' && this.canAct()) { + const c = this.gs.players[0].hand.find(h => h.id === ds.id); + this.layout(); + if (c) { this.selRank = c.rank; this.humanAsk(t.seat); } + return; + } + this.layout(); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) { + if (this.selRank) { this.selRank = null; this.layout(); this.updateDock(); } else this.openPause(); + } + return; + } + if (this.modal) { if (e.code === 'Enter') this.modal.onEnter?.(); return; } + if (this.dragState) return; + const k = e.key?.toLowerCase(); + if (k === 'q') { this.openAskLog(); return; } + if (k === 's') { this.cycleSort(); return; } + if (k === 'h') { this.flashHint(); return; } + if (k === 'f' && this.mode === 'fishing') { this.fishRandom(); return; } + if (k === 'a') { this.suggestPick(); return; } + if (e.code === 'Enter' && this.mode === 'human' && this.selRank) { + const s = this.suggest?.rank === this.selRank ? this.suggest.targetSeat : this.askable()[0]; + if (s != null) this.humanAsk(s); + } + } + + cycleSort() { + const order = ['rank', 'most', 'manual']; + this.settings.sort = order[(order.indexOf(this.settings.sort) + 1) % order.length]; + this.saveSettings(); + this.refreshSortButtons(); + this.sortHand(); + this.layout(); + } + + flashHint() { + if (this.mode === 'fishing') { + this.floatText({ x: CX, y: 860 }, 'Any card will do — the pond is face down!', '#7cf0a0', { size: 22, ms: 1800, rise: 20 }); + return; + } + const s = this.suggestion(); + if (!s) return; + const known = (this.hintMem.beliefs[s.targetSeat][s.rank] || 0) > 0; + this.floatText({ x: CX, y: 860 }, `Ask ${this.shortName(s.targetSeat)} for ${RANK_NAME[s.rank]}${known ? ' — they asked for those earlier!' : ''}`, '#7cf0a0', { size: 22, ms: 2200, rise: 20 }); + for (const c of this.gs.players[0].hand) if (c.rank === s.rank) this.flashGlow(c.id, 0x7cf0a0, { delay: 0, hold: 900 }); + } + + // ── Panels ────────────────────────────────────────────────────────────────── + openAskLog() { + if (!this.gs || this.modal) return; + const asks = this.gs.log.filter(e => e.kind === 'ask' || e.kind === 'lucky').slice(-11).reverse(); + const h = 640; + this.openModal({ w: 940, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 44, 'Ask log', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.goldHex }); + this.modalText(CX, top + 78, 'Who asked whom for what — the best memory at the table wins', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex }); + asks.forEach((e, i) => { + const y = top + 120 + i * 32; + let text; + if (e.kind === 'lucky') text = ` ↳ ${this.shortName(e.askerSeat)} fished up ${RANK_ONE[e.rank] ? `a ${RANK_ONE[e.rank]}` : `a ${e.rank}`} — lucky!`; + else text = `${this.shortName(e.askerSeat)} asked ${e.targetSeat === 0 ? 'you' : this.shortName(e.targetSeat)} for ${RANK_NAME[e.rank]} — ${e.result === 'catch' ? `got ${e.count}` : 'go fish'}`; + this.addToModal(this.add.text(CX - 420, y, text, { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: e.kind === 'lucky' ? '#7cf0a0' : e.result === 'catch' ? '#ffd35a' : COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + }); + if (!asks.length) this.modalText(CX, top + 140, 'Nobody has asked for anything yet.', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex }); + const mem = [1, 2, 3].filter(s => s < this.playerCount).map(s => { + const r = this.knownRanks(s); + return `${this.shortName(s, 10)}: ${r.length ? r.map(x => RANK_NAME[x]).join(', ') : '—'}`; + }); + this.modalText(CX, top + h - 112, `Probably holding — ${mem.join(' · ')}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#7cf0a0', align: 'center', wordWrap: { width: 860 } }); + this.modalButton(CX, top + h - 46, 'Back to the dock', () => this.closeModal(), { width: 260, height: 44, fontSize: 18 }); + } + + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Game 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 dock', 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: 'Hints (★ suggested ask)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; this.layout(); } }, + { label: 'Pause to show each ask', options: [['short', 'Short'], ['normal', 'Normal'], ['long', 'Long']], get: () => s.askPause, set: (v) => { s.askPause = v; } }, + { label: 'Collect', options: [[4, 'Books of 4'], [2, 'Pairs']], get: () => s.match ?? this.matchSize, set: (v) => { s.match = v; } }, + { label: 'Hand order', options: [['rank', 'Rank'], ['most', 'Most'], ['manual', 'Mine']], get: () => s.sort, set: (v) => { s.sort = v; this.refreshSortButtons(); this.sortHand(); this.layout(); } }, + ], { note: 'Books / pairs starts with the next game. Opponent hands move at their skill\'s speed.', onDone }); + } + + openRules() { + const h = 580; + 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 = [ + 'On your turn, ask one player for a rank you already hold.', + 'If they have any, they hand over every card of that rank — and you ask again.', + 'If not: "Go fish!" Pick a card from the pond. Fish up the rank you asked for', + ' and you go again; otherwise the turn passes.', + `Collect ${this.matchSize === 4 ? 'all four of a rank (a book)' : 'two of a rank (a pair)'} and it's laid down in front of you.`, + 'Run out of cards? Draw five from the pond. Pond empty too? You\'re out.', + `Most ${this.matchSize === 4 ? 'books' : 'pairs'} when no more can be made wins.`, + 'Tip: remember who asked for what — they still have it!', + ]; + lines.forEach((l, i) => this.addToModal(this.add.text(CX - 410, top + 122 + i * 44, 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 dock', () => this.closeModal(), { width: 280, height: 46, fontSize: 18 }); + } + + onLeave() { + const inGame = this.mode === 'human' || this.mode === 'ai' || this.mode === 'fishing'; + if (!inGame) { this.scene.start('GameMenu'); return; } + this.confirm('Leave the dock?', '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, matchVariant: this.settings.match ?? this.matchSize }); + } + + openScorePad({ result = false, readOnly = false } = {}) { + if (!this.gs) return; + const gs = this.gs; + const done = isGameOver(gs); + const wins = (s) => this.history.filter(h => h.winners.includes(s)).length; + let title; + if (readOnly || !done) title = 'Games at the dock'; + else if (gs.winnerSeats.includes(0)) title = gs.winnerSeats.length > 1 ? 'A tie — you share the win!' : 'You win!'; + else title = `${gs.winnerSeats.map(s => this.nameForSeat(s)).join(' & ')} win${gs.winnerSeats.length > 1 ? '' : 's'}`; + const unitP = this.matchSize === 4 ? 'books' : 'pairs'; + const rows = gs.players.map((p, s) => ({ + seat: s, color: SEAT_COLORS[s], name: this.shortName(s, 14), + cells: this.history.map(h => ({ text: String(h.counts[s]), color: h.winners.includes(s) ? '#1c3f8f' : '#8a7e66', mark: h.winners.includes(s) ? '★' : '', markColor: '#b8231f' })), + total: wins(s), totalColor: '#22201a', + circled: result && gs.winnerSeats.includes(s), + })); + const buttons = readOnly ? [{ label: 'Back to the dock', 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.winnerSeats.includes(0) ? '#b8231f' : '#22201a', + sub: `${unitP[0].toUpperCase()}${unitP.slice(1)} per game · total = games won`, + columns: this.history.map((_, i) => `G${i + 1}`), + rows, writeLast: !!result, buttons, readOnly, + onEnter: readOnly ? null : () => this.playAgain(), }); } - formatAskBanner(last) { - const asker = this.opponentName(last.askerSeat); - const target = this.opponentName(last.targetSeat); - const rank = last.rank === 'T' ? '10' : last.rank; - if (last.result === 'catch') { - const unit = this.matchVariant === 4 ? 'book' : 'pair'; - const tail = last.newPairs > 0 ? ` +${last.newPairs} ${unit}${last.newPairs > 1 ? 's' : ''}!` : ''; - return `${asker} asked ${target} for ${rank}s — caught ${last.cardsTransferred.length}!${tail}`; + async playAgain() { + this.closeModal(); + if (this.mode !== 'summary') return; + this.mode = 'deal'; + this.updateDock(); + await this.sweepCards(T.flat(POND.u, POND.v, 0.6)); + if (!this.alive()) return; + if (this.settings.match && this.settings.match !== this.matchSize) { + this.matchSize = this.settings.match; + this.history = []; } - if (last.result === 'lucky') { - return `${asker} asked ${target} for ${rank}s — Go Fish… lucky draw!`; - } - return `${asker} asked ${target} for ${rank}s — Go Fish.`; - } - - maybeStartAITurn() { - if (this.gameOver || this.animating) return; - if (this.gs.phase === 'pick' && !this.isLocalTurn()) { - this.time.delayedCall(700, () => this.runAIFishPick()); - return; - } - if (this.isLocalTurn()) return; - this.time.delayedCall(700, () => this.runAITurn()); - } - - runAITurn() { - if (this.gameOver || this.animating) return; - const seat = this.gs.currentPlayer; - if (seat === 0) return; - // Clear exclusions when starting a fresh turn (not continuing after a catch). - if (this.gs.lastAsk?.askerSeat !== seat || this.gs.lastAsk?.result !== 'catch') { - this.aiTurnExclusions.set(seat, new Set()); - } - const exclude = this.aiTurnExclusions.get(seat) ?? new Set(); - const action = chooseAction(this.gs, seat, this.aiMemory[seat], exclude); - if (!action) { - // Shouldn't happen — fail-safe: end the game if no action available. - this.endGame(); - return; - } - this.executeAsk(seat, action.targetSeat, action.rank); + this.newGame(); } // ── Game over ────────────────────────────────────────────────────────────── - - endGame() { - if (this.gameOver) return; - this.gameOver = true; - this.hideBanner(); - const rows = this.gs.players - .map((p) => ({ seat: p.seat, pairs: p.pairs })) - .sort((a, b) => b.pairs - a.pairs); - const winners = this.gs.winnerSeats.map((s) => this.opponentName(s)).join(', '); - const unit = this.matchVariant === 4 ? 'book' : 'pair'; - const lines = [`Game over — winner: ${winners}`]; - for (const r of rows) { - lines.push(`${this.opponentName(r.seat)}: ${r.pairs} ${unit}${r.pairs === 1 ? '' : 's'}`); - } - playSound(this, SFX.CASINO_WIN); - new Modal(this, lines.join('\n'), {}).setDepth(D.modal); + async onGameOver() { + if (this.mode === 'ending' || this.mode === 'summary') return; + this.mode = 'ending'; + this.turnToken++; + this.cancelDrag(); + this.selRank = null; + this.show = null; + this.lineG?.clear(); + this.input.setDefaultCursor('default'); + this.updateDock(); + const gs = this.gs; + await this.wait(500); + if (!this.alive()) return; + const w = gs.winnerSeats; + const head = w.includes(0) ? (w.length > 1 ? 'A tie!' : 'You win!') : `${this.shortName(w[0], 14)} wins!`; + this.stamp(head, { x: CX, y: CY - 40 }, w.includes(0) ? '#7cf0a0' : SEAT_HEX[w[0]], { size: 88, sub: `${gs.players[w[0]].pairs} ${this.matchSize === 4 ? 'books' : 'pairs'}`, hold: 1400 }); + for (const s of w) this.plateStamp(s, 'WINNER', '#ffd35a', 0); + playSound(this, w.includes(0) ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(w.includes(s) ? 'win' : 'loss'); + this.revealAll = true; + this.layout({ duration: 360 }); + await this.wait(1800); + if (!this.alive()) return; + this.history.push({ winners: w.slice(), counts: gs.players.map(p => p.pairs) }); + this.recordResult('gofish', { score: gs.players[0].pairs, opponentScores: gs.players.slice(1).map(p => p.pairs), won: w.includes(0) }); + this.mode = 'summary'; + this.openScorePad({ result: true }); } } + +export { CARD_W, CARD_H }; diff --git a/src/games/gofish/GoFishLogic.js b/src/games/gofish/GoFishLogic.js index b4b459e..f0b109c 100644 --- a/src/games/gofish/GoFishLogic.js +++ b/src/games/gofish/GoFishLogic.js @@ -64,6 +64,7 @@ export function cloneState(state) { hand: p.hand.map(cloneCard), pairs: p.pairs, pairedRanks: p.pairedRanks.slice(), + books: (p.books ?? []).map((b) => b.map(cloneCard)), sittingOut: p.sittingOut, })), pool: state.pool.map(cloneCard), @@ -91,6 +92,7 @@ export function createInitialState({ playerCount = 4, matchSize = 4, seed } = {} hand: deck.splice(0, HAND_DEAL), pairs: 0, pairedRanks: [], + books: [], sittingOut: false, }); } @@ -266,6 +268,7 @@ function collectPairs(player, state) { player.hand = player.hand.filter((c) => !idsToRemove.has(c.id)); player.pairs += 1; player.pairedRanks.push(foundRank); + (player.books ??= []).push(group.map(cloneCard)); collected += 1; if (state) state.log.push({ kind: 'pair', seat: player.seat, rank: foundRank }); } @@ -333,6 +336,11 @@ function checkGameOver(state) { } } +/** Every card in the game — hands, pool and books (for conservation checks). */ +export function countCards(state) { + return state.pool.length + state.players.reduce((n, p) => n + p.hand.length + (p.books ?? []).reduce((m, b) => m + b.length, 0), 0); +} + export function isGameOver(state) { return state.phase === 'gameOver'; } diff --git a/src/games/gofish/GoFishTable.js b/src/games/gofish/GoFishTable.js new file mode 100644 index 0000000..fb1a3aa --- /dev/null +++ b/src/games/gofish/GoFishTable.js @@ -0,0 +1,162 @@ +// Go Fish table layout — Phaser-free so tools/verifyGoFish.js can test it. +// +// A weathered lakeside dock at dusk on the shared card-table kit. The draw +// pool is a POND cut into the middle of the boards: its cards float face down +// in the water (scattered by card id, so they never jump around). Each +// player's finished books stack in a row on the boards in front of them. +// +// 2 human · across 3 human · far corners 4 human · left · across · right +// (logic seats clockwise from the human's left, as in every table game) + +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: 'rect', corner: 0.12, feltK: 0.97, faceH: 40 }); +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 }); + +// books: row start (u, v), direction along u, max row width (px) +const HUMAN_BOOKS = { u: 0.02, v: 0.76, dir: 1, maxW: 540 }; +const SEATS = { + 2: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE, books: HUMAN_BOOKS }, + { fan: opp(960, 80, Math.PI), plate: { x: 1420, y: 86 }, books: { u: -0.04, v: 0.17, dir: -1, maxW: 440 } }, + ], + 3: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE, books: HUMAN_BOOKS }, + { fan: opp(600, 82, Math.PI - 0.1), plate: { x: 190, y: 150 }, books: { u: -0.79, v: 0.25, dir: 1, maxW: 280 } }, + { fan: opp(1320, 82, Math.PI + 0.1), plate: { x: 1730, y: 150 }, books: { u: 0.79, v: 0.25, dir: -1, maxW: 280 } }, + ], + 4: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE, books: HUMAN_BOOKS }, + { fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 }, books: { u: -0.86, v: 0.66, dir: 1, maxW: 320 } }, + { fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 }, books: { u: -0.04, v: 0.17, dir: -1, maxW: 420 } }, + { fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 }, books: { u: 0.86, v: 0.66, dir: -1, maxW: 320 } }, + ], +}; + +// The pond: an ellipse in table space. +export const POND = { u: 0, v: 0.44, ru: 0.34, rv: 0.165 }; +export const POOL_K = 0.6; +export const BOOK_K = 0.46; + +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(`Go Fish 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); + +// deterministic 0..1 values per card id +function hash01(id, salt) { + let h = Math.imul((id + 1) * 2654435761 + salt * 40503, 2246822507) >>> 0; + h ^= h >>> 13; h = Math.imul(h, 3266489909) >>> 0; h ^= h >>> 16; + return (h >>> 0) / 4294967296; +} + +/** Where a pool card floats in the pond (stable per card id). */ +export function poolPose(id) { + const a = hash01(id, 1) * Math.PI * 2; + const r = Math.sqrt(hash01(id, 2)) * 0.78; + const u = POND.u + Math.cos(a) * r * POND.ru; + const v = POND.v + Math.sin(a) * r * POND.rv; + return T.flat(u, v, POOL_K, (hash01(id, 3) - 0.5) * 1.4); +} + +/** Points along the pond's shoreline (screen), for the art and checks. */ +export function pondOutline(k = 1, steps = 64) { + const pts = []; + for (let i = 0; i < steps; i++) { + const a = (i / steps) * Math.PI * 2; + pts.push(T.P.project(POND.u + Math.cos(a) * POND.ru * k, POND.v + Math.sin(a) * POND.rv * k)); + } + return pts; +} + +export function inPond(pt) { + const { u, v } = T.P.unproject(pt.x, pt.y); + const du = (u - POND.u) / POND.ru, dv = (v - POND.v) / POND.rv; + return du * du + dv * dv <= 1; +} + +/** Book i of n in a seat's row (each book is a squared-up stack). */ +export function bookPose(L, seat, i, n) { + const b = L.seats[seat].books; + const base = T.flat(b.u, b.v, BOOK_K); + const natural = CARD_W * base.s + 10; + const step = n <= 1 ? natural : Math.min(natural, (b.maxW - CARD_W * base.s) / (n - 1)); + return { ...base, x: base.x + b.dir * i * step, rot: ((i * 37) % 7 - 3) * 0.012 }; +} + +/** Screen rect a seat's book row covers at its widest. */ +export function bookRowRect(L, seat, n = 13) { + const a = bookPose(L, seat, 0, n), b = bookPose(L, seat, n - 1, n); + const hw = (CARD_W / 2) * a.s + 4, hh = (CARD_H / 2) * a.s * SQ + 10; + return { x0: Math.min(a.x, b.x) - hw, x1: Math.max(a.x, b.x) + hw, y0: a.y - hh, y1: a.y + hh }; +} + +// Show spots: where an asker holds up the card they're asking about, and where +// the player asked lays out what they hand over — between their hand and the +// pond, clear of the book rows. +const SHOW = { + 2: [{ x: 700, y: 775 }, { x: 1180, y: 230 }], + 3: [{ x: 700, y: 775 }, { x: 760, y: 205 }, { x: 1160, y: 205 }], + 4: [{ x: 700, y: 775 }, { x: 250, y: 450 }, { x: 1180, y: 230 }, { x: 1670, y: 450 }], +}; +export const SHOW_K = 0.82; + +/** Card i of n laid out at a seat's show spot (upright, readable). */ +export function showPose(L, seat, i = 0, n = 1) { + const c = SHOW[L.playerCount][seat]; + const k = seat === 0 ? 0.86 : SHOW_K; + const step = CARD_W * k * 0.55; + return { x: c.x + (i - (n - 1) / 2) * step, y: c.y, rot: (i - (n - 1) / 2) * 0.06, s: k, q: 1 }; +} + +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 a seat's speech bubble pops up. */ +export function bubbleAt(L, seat) { + if (seat === 0) return { x: 960, y: 846 }; + const f = L.seats[seat].fan; + return fanPoint(f, 0, -CARD_H * 1.55); +} + +/** The clickable region of an opponent (their hand fan) for asking. */ +export function seatTargetRect(L, seat, n = 7) { + const f = L.seats[seat].fan; + const pts = []; + for (let i = 0; i < Math.max(1, n); i++) pts.push(fanPose(f, i, Math.max(1, n))); + const xs = pts.map(p => p.x), ys = pts.map(p => p.y); + const pad = 60; + return { x0: Math.min(...xs) - pad, x1: Math.max(...xs) + pad, y0: Math.min(...ys) - pad, y1: Math.max(...ys) + pad }; +} + +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/games/hearts/HeartsAI.js b/src/games/hearts/HeartsAI.js index 80e2a32..ce08c97 100644 --- a/src/games/hearts/HeartsAI.js +++ b/src/games/hearts/HeartsAI.js @@ -1,13 +1,24 @@ -// Hearts AI — heuristic opponent. No Phaser imports. +// Hearts AI — heuristic opponent scaled by skill (1..5). No Phaser imports. // -// choosePass(state, seat) → array of 3 card ids to pass. -// choosePlay(state, seat) → a single card id to play (always legal). +// choosePass(state, seat, { skill, rng }) → array of 3 card ids to pass. +// choosePlay(state, seat, { skill, rng }) → a single card id to play (always legal). // -// The AI has no hidden-information memory; it plays a sound, defensive game: -// shed dangerous cards in the pass, duck under tricks that carry points, and -// dump high/dangerous cards when void in the led suit. +// Skill: +// 1-2 plays loosely: random-ish passes, sometimes a random legal card. +// 3 sound defensive play: shed danger in the pass, duck under tricks +// that carry points, dump high cards when void. +// 4-5 remembers who is void in what and whether the Queen is gone, leads +// low spades to flush her out, sheds high cards on safe last-to-play +// tricks and breaks up a moon shot. 5 also avoids leading into voids. +// (Measured over 2400 hands: skill 5 takes ~9% fewer points than skill 3.) -import { legalPlays, cardPoints, isQueenOfSpades } from './HeartsLogic.js'; +import { + legalPlays, cardPoints, isQueenOfSpades, knownVoids, playedKeys, PLAYER_COUNT, +} from './HeartsLogic.js'; +import { clampSkill } from '../../ui/cardtable/AITiming.js'; + +const RANDOM_PLAY = { 1: 0.35, 2: 0.15, 3: 0.05, 4: 0, 5: 0 }; +const RANDOM_PASS = { 1: 0.6, 2: 0.25, 3: 0, 4: 0, 5: 0 }; // How much we'd like to be rid of a card. Higher = more dangerous to keep. function danger(card) { @@ -17,44 +28,61 @@ function danger(card) { return card.value; } -export function choosePass(state, seat) { +export function choosePass(state, seat, opts = {}) { + const skill = clampSkill(opts.skill); + const rand = opts.rng ?? Math.random; const hand = state.players[seat].hand; - - // Suit counts so we can reward voiding a short side suit. + if (rand() < RANDOM_PASS[skill]) { + const pool = hand.slice(); + for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; } + return pool.slice(0, 3).map((c) => c.id); + } const counts = { s: 0, h: 0, d: 0, c: 0 }; for (const c of hand) counts[c.suit] += 1; - const scored = hand.map((c) => { let score = danger(c); - // Encourage voiding short non-heart suits — being void buys flexibility. if (c.suit !== 'h' && !isQueenOfSpades(c) && counts[c.suit] <= 2) score += 40; + if (skill === 2) score += rand() * 60; return { c, score }; }); - scored.sort((a, b) => b.score - a.score); return scored.slice(0, 3).map((s) => s.c.id); } -export function choosePlay(state, seat) { +export function choosePlay(state, seat, opts = {}) { + const skill = clampSkill(opts.skill); + const rand = opts.rng ?? Math.random; const legal = legalPlays(state, seat); if (legal.length === 0) return null; if (legal.length === 1) return legal[0].id; + if (rand() < RANDOM_PLAY[skill]) return legal[Math.floor(rand() * legal.length)].id; + const ctx = skill >= 4 ? context(state, seat) : null; const leading = state.trick.length === 0; - if (leading) return chooseLead(state, seat, legal).id; - + if (leading) return chooseLead(state, seat, legal, skill, ctx).id; const haveLead = state.players[seat].hand.some((c) => c.suit === state.leadSuit); - if (!haveLead) return chooseSlough(legal).id; - - return chooseFollow(state, legal).id; + if (!haveLead) return chooseSlough(state, legal, skill, ctx).id; + return chooseFollow(state, seat, legal, skill, ctx).id; } -// Leading a trick: lead low and safe; avoid leading spades while we still hold -// the Queen (don't draw spades onto ourselves) and avoid hearts when possible. -function chooseLead(state, seat, legal) { - const holdsQueen = state.players[seat].hand.some(isQueenOfSpades); - let pool = legal; +// What a sharp player knows: voids, whether the Queen is still out, and +// whether someone is running away with every point (a moon shot). +function context(state, seat) { + const played = playedKeys(state); + const voids = knownVoids(state); + const pts = state.players.map((p) => p.roundPoints); + const totalPts = pts.reduce((a, b) => a + b, 0); + let moonThreat = null; + for (let s = 0; s < PLAYER_COUNT; s++) { + if (s !== seat && pts[s] >= 6 && pts[s] === totalPts) moonThreat = s; + } + return { played, voids, queenOut: !played.has('Qs'), moonThreat }; +} +function chooseLead(state, seat, legal, skill, ctx) { + const hand = state.players[seat].hand; + const holdsQueen = hand.some(isQueenOfSpades); + let pool = legal; if (holdsQueen) { const nonSpade = legal.filter((c) => c.suit !== 's'); if (nonSpade.length > 0) pool = nonSpade; @@ -62,28 +90,54 @@ function chooseLead(state, seat, legal) { const nonHeart = pool.filter((c) => c.suit !== 'h'); if (nonHeart.length > 0) pool = nonHeart; + if (ctx) { + // flush the Queen: lead a low spade when we don't hold her + if (!holdsQueen && ctx.queenOut) { + const lowSpades = legal.filter((c) => c.suit === 's' && c.value < 12); + const highSpades = hand.filter((c) => c.suit === 's' && c.value > 12); + if (lowSpades.length && (lowSpades.length >= highSpades.length)) return lowest(lowSpades); + } + // stay out of suits somebody has shown out of — they'd dump points on us + if (skill >= 5) { + const others = [1, 2, 3].map((d) => (seat + d) % PLAYER_COUNT); + const safe = pool.filter((c) => !others.some((s) => ctx.voids[s].has(c.suit))); + if (safe.length) pool = safe; + } + } return lowest(pool); } -// Void in the led suit — discard the most dangerous card we can. -function chooseSlough(legal) { +function chooseSlough(state, legal, skill, ctx) { + // breaking a moon shot: don't feed the runaway player any more points + if (ctx && ctx.moonThreat != null && trickWinner(state)?.seat === ctx.moonThreat) { + const clean = legal.filter((c) => cardPoints(c) === 0); + if (clean.length) return highest(clean); + } let best = legal[0]; let bestDanger = -Infinity; for (const c of legal) { - const d = danger(c); + let d = danger(c); + // with the Queen gone, A♠ / K♠ are harmless — shed high hearts first + if (ctx && !ctx.queenOut && c.suit === 's' && c.value > 12) d = c.value; if (d > bestDanger) { bestDanger = d; best = c; } } return best; } -// Following in-suit: try to stay under the current winner; otherwise win as -// cheaply as possible. -function chooseFollow(state, legal) { - const winning = currentWinningCard(state); - const under = legal.filter((c) => c.value < winning.value); +function chooseFollow(state, seat, legal, skill, ctx) { + const win = trickWinner(state); + const winning = win.card; + const trickPts = state.trick.reduce((s, t) => s + cardPoints(t.card), 0); + const last = state.trick.length === PLAYER_COUNT - 1; + // stop a moon shot: take a point trick away from the runaway player + if (ctx && ctx.moonThreat != null && win.seat === ctx.moonThreat && trickPts > 0) { + const over = legal.filter((c) => c.value > winning.value && !isQueenOfSpades(c)); + if (over.length) return lowest(over); + } + + const under = legal.filter((c) => c.value < winning.value); if (under.length > 0) { - // We can avoid taking the lead — dump our highest/most dangerous safe card. let best = under[0]; let bestDanger = -Infinity; for (const c of under) { @@ -92,20 +146,19 @@ function chooseFollow(state, legal) { } return best; } - - // Every legal card beats the current winner — we'll likely take it. Spend - // the cheapest card (and never volunteer the Queen if we can avoid it). const nonQueen = legal.filter((c) => !isQueenOfSpades(c)); - return lowest(nonQueen.length > 0 ? nonQueen : legal); + const pool = nonQueen.length > 0 ? nonQueen : legal; + // last to play on a clean trick: we take it anyway, so shed our highest card + if (ctx && last && trickPts === 0) return highest(pool); + return lowest(pool); } -function currentWinningCard(state) { +function trickWinner(state) { + if (!state.trick.length) return null; const lead = state.leadSuit; - let winner = state.trick[0].card; - for (const t of state.trick) { - if (t.card.suit === lead && t.card.value > winner.value) winner = t.card; - } - return winner; + let w = state.trick[0]; + for (const t of state.trick) if (t.card.suit === lead && t.card.value > w.card.value) w = t; + return w; } function lowest(cards) { @@ -113,3 +166,13 @@ function lowest(cards) { for (const c of cards) if (c.value < best.value) best = c; return best; } + +function highest(cards) { + let best = cards[0]; + for (const c of cards) if (c.value > best.value) best = c; + return best; +} + +/** What a sharp player would do — the human's hints. */ +export function suggestPass(state, seat) { return choosePass(state, seat, { skill: 5, rng: () => 0.5 }); } +export function suggestPlay(state, seat) { return choosePlay(state, seat, { skill: 5, rng: () => 0.5 }); } diff --git a/src/games/hearts/HeartsArt.js b/src/games/hearts/HeartsArt.js new file mode 100644 index 0000000..6e0918d --- /dev/null +++ b/src/games/hearts/HeartsArt.js @@ -0,0 +1,177 @@ +// Hearts art — the den, baked once per page load. Cards are the shared casino +// deck ('casino-cards' atlas, keyed 'As', 'Qs', …). +// +// hearts-table bookshelves + fireplace glow, a walnut card table with brass +// studs and an oxblood leather top tooled with a gold border, +// faint trick spots and won-card areas +// hearts-heart a big red heart (cracks in two when hearts are broken) + +import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js'; +import { + bakeRoom, canvas, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, pileSpot, ring, +} from '../../ui/cardtable/TableArt.js'; +import { W, H } from '../../ui/cardtable/TableGeometry.js'; +import { T, trickPose, tricksPose, pointPose, SEAT_HEX } from './HeartsTable.js'; + +function wall(ctx) { + ctx.fillStyle = '#1e120b'; + ctx.fillRect(0, 0, W, H); + // bookshelves: rows of spines + const shelfH = 120; + let seed = 7; + const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }; + const spines = ['#6b1f1f', '#2f4a2a', '#1f3354', '#7a5a22', '#4a2a14', '#5a2a4a', '#8a7a52', '#2a2a2a']; + for (let y = 0; y < H; y += shelfH) { + let x = 0; + while (x < W) { + const w = 14 + Math.floor(rnd() * 22); + const h = shelfH - 18 - Math.floor(rnd() * 26); + const col = spines[Math.floor(rnd() * spines.length)]; + ctx.fillStyle = col; + ctx.fillRect(x, y + shelfH - 12 - h, w - 2, h); + ctx.fillStyle = 'rgba(255,220,150,0.18)'; + ctx.fillRect(x + 3, y + shelfH - 12 - h + 10, w - 8, 3); + ctx.fillRect(x + 3, y + shelfH - 30, w - 8, 2); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; + ctx.fillRect(x + w - 5, y + shelfH - 12 - h, 3, h); + x += w + (rnd() < 0.08 ? 30 : 0); + } + // the shelf board + const g = ctx.createLinearGradient(0, y + shelfH - 12, 0, y + shelfH); + g.addColorStop(0, '#5a3418'); g.addColorStop(1, '#2a160a'); + ctx.fillStyle = g; + ctx.fillRect(0, y + shelfH - 12, W, 12); + } + ctx.fillStyle = noisePattern(ctx, 128, 18); + ctx.fillRect(0, 0, W, H); + // the room is dark; the fire (left) and a lamp (centre) light it + ctx.fillStyle = 'rgba(10,5,2,0.55)'; + ctx.fillRect(0, 0, W, H); + const fire = ctx.createRadialGradient(-80, 760, 40, -80, 760, 1300); + fire.addColorStop(0, 'rgba(255,140,50,0.55)'); + fire.addColorStop(0.4, 'rgba(255,110,40,0.16)'); + fire.addColorStop(1, 'rgba(255,110,40,0)'); + ctx.fillStyle = fire; + ctx.fillRect(0, 0, W, H); + const lamp = ctx.createRadialGradient(W / 2, 90, 30, W / 2, 300, 1000); + lamp.addColorStop(0, 'rgba(255,214,150,0.22)'); + lamp.addColorStop(1, 'rgba(255,214,150,0)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); +} + +function front(ctx, Tb) { + frontBands(ctx, Tb, ['#6b4024', '#56321a', '#432612', '#341c0c', '#26140a'], { grooves: [0.4, 0.75] }); +} + +function rim(ctx, Tb) { + rimBand(ctx, Tb, { base: '#5a3519', dark: '#24130a', light: '#a8692f', grain: ['#1a0d05', '#d9a066'], gloss: 1.5 }); + // brass studs just outside the leather + const pts = Tb.outline(Tb.feltK + 0.012, 60); + let acc = 0; + for (let i = 1; i < pts.length; i++) { + const a = pts[i - 1], b = pts[i]; + acc += Math.hypot(b.x - a.x, b.y - a.y); + if (acc < 26 * b.s) continue; + acc = 0; + const r = 3.6 * b.s; + const g = ctx.createRadialGradient(b.x - r * 0.35, b.y - r * 0.35, 0.5, b.x, b.y, r); + g.addColorStop(0, '#fff2b8'); g.addColorStop(0.5, '#d9a84a'); g.addColorStop(1, '#6a4a12'); + ctx.beginPath(); ctx.arc(b.x, b.y, r, 0, Math.PI * 2); ctx.fillStyle = g; ctx.fill(); + } +} + +function leather(ctx, Tb) { + ctx.fillStyle = '#4a1414'; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 220, 30); + ctx.fillRect(0, 0, W, H); + // leather grain: faint mottling + for (let i = 0; i < 900; i++) { + const x = Math.random() * W, y = Math.random() * H; + ctx.fillStyle = Math.random() < 0.5 ? 'rgba(0,0,0,0.06)' : 'rgba(255,200,170,0.04)'; + ctx.beginPath(); ctx.ellipse(x, y, 6 + Math.random() * 18, 3 + Math.random() * 8, Math.random() * 3, 0, Math.PI * 2); ctx.fill(); + } + // tooled gold border, two lines + ring(ctx, Tb, Tb.feltK * 0.94, 2.5, 'rgba(217,168,74,0.55)'); + ring(ctx, Tb, Tb.feltK * 0.925, 1.2, 'rgba(217,168,74,0.4)'); + lampPool(ctx, Tb, { color: '255,214,160', alpha: 0.26, vignette: 0.55, at: { u: 0, v: 0.46 } }); + // fire warms the left side of the table + const f = Tb.P.project(-1, 0.6); + const fire = ctx.createRadialGradient(f.x, f.y, 20, f.x, f.y, 900); + fire.addColorStop(0, 'rgba(255,130,50,0.22)'); + fire.addColorStop(1, 'rgba(255,130,50,0)'); + ctx.fillStyle = fire; + ctx.fillRect(0, 0, W, H); + rimShadow(ctx, Tb, 0.42); +} + +function marks(ctx) { + // faint card spots where tricks land and where won cards collect + for (let s = 0; s < 4; s++) { + pileSpot(ctx, trickPose(s), '', { color: '217,168,74', alpha: 0.22 }); + pileSpot(ctx, tricksPose(s), '', { color: SEAT_HEX[s].replace('#', '').match(/../g).map(h => parseInt(h, 16)).join(','), alpha: 0.3 }); + const p = pointPose(s, 0); + ctx.font = '13px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(217,168,74,0.4)'; + ctx.fillText('POINTS', p.x + (s === 3 ? -40 : 40), p.y - 36 * (p.s / 0.4)); + } + // a small tooled heart in the middle of the table + const c = T.P.project(0, 0.45); + ctx.save(); + ctx.translate(c.x, c.y); + ctx.scale(1, 0.9); + heartPath(ctx, 0, 0, 34); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(217,168,74,0.35)'; + ctx.stroke(); + ctx.restore(); +} + +export function heartPath(ctx, x, y, r) { + ctx.beginPath(); + ctx.moveTo(x, y + r * 0.9); + ctx.bezierCurveTo(x - r * 1.4, y + r * 0.1, x - r * 0.9, y - r * 1.0, x, y - r * 0.35); + ctx.bezierCurveTo(x + r * 0.9, y - r * 1.0, x + r * 1.4, y + r * 0.1, x, y + r * 0.9); + ctx.closePath(); +} + +function bakeHeart(scene) { + const S = 200; + for (const [key, clip] of [['hearts-heart', null], ['hearts-heart-l', 'l'], ['hearts-heart-r', 'r']]) { + const c = canvas(S, S); + const ctx = c.getContext('2d'); + ctx.save(); + if (clip) { + // a jagged crack down the middle + ctx.beginPath(); + const zig = [[100, 10], [88, 50], [108, 85], [90, 120], [106, 150], [96, 196]]; + if (clip === 'l') { ctx.moveTo(0, 0); zig.forEach(([x, y]) => ctx.lineTo(x, y)); ctx.lineTo(0, S); } + else { ctx.moveTo(S, 0); zig.forEach(([x, y]) => ctx.lineTo(x, y)); ctx.lineTo(S, S); } + ctx.closePath(); + ctx.clip(); + } + heartPath(ctx, S / 2, S / 2 + 6, 70); + const g = ctx.createLinearGradient(40, 30, 160, 170); + g.addColorStop(0, '#ff6a6a'); g.addColorStop(1, '#a8101e'); + ctx.fillStyle = g; + ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 12; + ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.lineWidth = 5; + ctx.strokeStyle = '#5a0810'; + ctx.stroke(); + ctx.restore(); + scene.textures.addCanvas(key, c); + } +} + +export async function prepareHeartsArt(scene) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('hearts-heart')) bakeHeart(scene); + return bakeRoom(scene, 'hearts-table', T, { wall, front, rim, top: leather, onTop: marks }); +} + +export { mix, poly }; diff --git a/src/games/hearts/HeartsGame.js b/src/games/hearts/HeartsGame.js index a982355..3403ab2 100644 --- a/src/games/hearts/HeartsGame.js +++ b/src/games/hearts/HeartsGame.js @@ -1,939 +1,856 @@ import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.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, - selectPass, - playCard, - legalPlays, - startNextHand, - passTargetSeat, - PASS_COUNT, + CardTableScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { ensureCardBack } from '../../ui/casino/CasinoArt.js'; +import { CARD_W, CARD_H, fanHit, fanInsertIndex, fanZone, inRect, inPose } from '../../ui/cardtable/TableGeometry.js'; +import { choosePass, choosePlay, suggestPass, suggestPlay } from './HeartsAI.js'; +import { + createInitialState, selectPass, playCard, startNextHand, legalPlays, cardPoints, isQueenOfSpades, + passTargetSeat, playedKeys, knownVoids, PASS_COUNT, GAME_OVER_SCORE, } from './HeartsLogic.js'; -import { choosePass, choosePlay } from './HeartsAI.js'; +import { SUITS, RANKS } from '../cards/Deck.js'; +import { + T, SQ, SEAT_COLORS, SEAT_HEX, L, handPose, trickPose, tricksPose, pointPose, handHome, handBadge, spotFor, CENTRE, +} from './HeartsTable.js'; +import { prepareHeartsArt } from './HeartsArt.js'; -// ── Layout constants ──────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; +// ─── Hearts ─────────────────────────────────────────────────────────────────── +// A firelit den on the shared card-table kit (src/ui/cardtable/). Rules in +// HeartsLogic.js (pure), opponents in HeartsAI.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 = 64; +const DEFAULTS = { pace: 'normal', hints: true, sort: 'suit', target: GAME_OVER_SCORE, moon: 'add' }; +const SUIT_ORDER = { c: 0, d: 1, s: 2, h: 3 }; +const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣' }; +const SUIT_NAME = { s: 'spades', h: 'hearts', d: 'diamonds', c: 'clubs' }; +const DIR_NAME = { left: 'left', right: 'right', across: 'across', hold: 'nobody' }; +const bySuit = (a, b) => SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit] || a.value - b.value; +const byRank = (a, b) => a.value - b.value || SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit]; +const TRICK_HOLD_MS = 1050; -const D = { - felt: -1, label: 0, score: 5, card: 10, trick: 15, - highlight: 20, ui: 30, portrait: 35, banner: 60, modal: 80, -}; - -// Seats are fixed: you sit at the bottom, opponents fill the other three. -const SLOTS = ['bottom', 'left', 'top', 'right']; - -const DIRECTION_LABEL = { left: 'left', right: 'right', across: 'across', hold: '(holding)' }; - -function slotLayout(slot) { - switch (slot) { - case 'bottom': - return { handCenter: { x: CX, y: GAME_HEIGHT - 100 }, handAxis: 'x', faceUp: true, rotateCards: 0, - portrait: { x: CX - 560, y: GAME_HEIGHT - 150, r: 56 }, trick: { x: CX, y: CY + 95 } }; - case 'top': - return { handCenter: { x: CX, y: 110 }, handAxis: 'x', faceUp: false, rotateCards: 180, - portrait: { x: CX - 560, y: 150, r: 50 }, trick: { x: CX, y: CY - 95 } }; - case 'left': - return { handCenter: { x: 110, y: CY }, handAxis: 'y', faceUp: false, rotateCards: 90, - portrait: { x: 230, y: CY - 320, r: 50 }, trick: { x: CX - 135, y: CY } }; - case 'right': - return { handCenter: { x: GAME_WIDTH - 110, y: CY }, handAxis: 'y', faceUp: false, rotateCards: 270, - portrait: { x: GAME_WIDTH - 230, y: CY - 320, r: 50 }, trick: { x: CX + 135, y: CY } }; - default: - throw new Error(`Unknown slot: ${slot}`); - } -} - -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' }, -}; - -// ── Scene ─────────────────────────────────────────────────────────────────── -export default class HeartsGame extends Phaser.Scene { +export default class HeartsGame extends CardTableScene { constructor() { super('HeartsGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.cardBack = data.cardBack ?? null; - + this.initTable(data, { settingsKey: 'hearts-settings', defaults: DEFAULTS, minPlayers: 4, maxPlayers: 4 }); + this.playerCount = 4; this.gs = null; - this.busy = false; - this.gameOver = false; - this.awaitingHuman = false; - - this.handCardObjs = new Map(); // key `${seat}-${cardId}` → container - this.trickSprites = new Map(); // seat → container currently in the center - this.transient = []; // throwaway highlights / deal sprites - this.legalIds = new Set(); - this.passSelection = new Set(); - this.passButton = null; - this.scoreTexts = []; - this.turnGlow = null; - - this.localHandCards = []; // player 0 card containers in hand order - this.dragState = null; + this.history = []; + this.passSel = new Set(); + this.received = new Set(); + this.hoverId = null; this.potentialDrag = null; + this.dragState = null; + this.dragPreview = null; + this.holdTrick = null; + this.revealAll = false; } - create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildPlayfield(); - this.buildSeats(); - this.buildCenter(); - this.buildHUD(); - this.setupDragHandlers(); - this.startNewMatch(); + faceFrame(card) { return { key: 'casino-cards', frame: card.key }; } + + async create() { + this.createTableBase(); + const key = await prepareHeartsArt(this); + if (!this.alive()) return; + this.backKey = ensureCardBack(this, this.cardBack?.fallbackColor ?? '#5a1424'); + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildSpot(); + this.buildFire(); + this.arrowG = this.add.graphics().setDepth(D.labels); + this.arrowTxt = this.add.text(CENTRE.x, CENTRE.y + 70, '', { + fontFamily: 'Righteous', fontSize: '24px', color: '#f2d6a0', stroke: '#1a0806', strokeThickness: 5, + }).setOrigin(0.5).setDepth(D.labels); + this.buildDropSlot(); + this.buildPlates(L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'MOON!' }); + this.buildBadges(); + this.buildGhostHands(L.seats.map((_, s) => (s ? handHome(s) : null)), SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Rules: () => this.openRules(), + }, 'Click a card to play · pick 3 to pass, then Enter · A suggest a pass · L last trick\nG cards gone · S sort · H hint · Esc menu'); + this.buildDock(); + this.buildSortRow([['suit', 'Suit'], ['rank', 'Rank'], ['manual', 'Mine']], () => { this.sortHand(); this.layout(); }); + this.buildTooltips(); + this.setupInput(); + this.newMatch(); } - 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); - } + // The fire flickers on the left of the room. + buildFire() { + this.fire = this.add.image(-60, 720, 'ct-spot').setDisplaySize(900, 1100).setTint(0xff8a3a) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.22).setDepth(D.spot); + const flicker = () => { + if (!this.alive()) return; + this.tweens.add({ + targets: this.fire, alpha: 0.16 + Math.random() * 0.14, duration: 120 + Math.random() * 220, ease: 'Sine.easeInOut', + onComplete: flicker, + }); + }; + flicker(); } - buildSeats() { - for (let seat = 0; seat < SLOTS.length; seat++) { - const lay = slotLayout(SLOTS[seat]); - const name = this.seatName(seat); - if (seat === 0) { - createPlayerPortrait(this, lay.portrait.x, lay.portrait.y, lay.portrait.r, D.portrait, 'HeartsGame'); - } else { - const opp = this.opponents[seat - 1]; - if (opp) createOpponentPortrait(this, opp, lay.portrait.x, lay.portrait.y, lay.portrait.r, D.portrait); - } - this.add.text(lay.portrait.x, lay.portrait.y + lay.portrait.r + 16, name, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - // Score chip beneath the name. - const chip = this.add.text(lay.portrait.x, lay.portrait.y + lay.portrait.r + 40, 'Total 0 +0', { - fontFamily: 'Righteous', fontSize: '17px', color: COLORS.goldHex, - backgroundColor: 'rgba(0,0,0,0.6)', padding: { x: 8, y: 4 }, - }).setOrigin(0.5).setDepth(D.score); - this.scoreTexts[seat] = chip; - } - } - - buildCenter() { - this.heartsBg = this.add.graphics().setDepth(D.ui - 1); - this.heartsText = this.add.text(CX, CY - 195, '', { - fontFamily: 'Righteous', fontSize: '18px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.ui); - - this.bannerBg = this.add.graphics().setDepth(D.banner - 1).setVisible(false); - this.bannerText = this.add.text(CX, CY + 200, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, align: 'center', - wordWrap: { width: 900 }, - }).setOrigin(0.5).setDepth(D.banner).setVisible(false); - } - - buildHUD() { - this.statusBg = this.add.graphics().setDepth(D.ui - 1); - this.statusText = this.add.text(CX, GAME_HEIGHT - 232, '', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, align: 'center', - }).setOrigin(0.5).setDepth(D.ui); - - new Button(this, 90, GAME_HEIGHT - 30, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 130, height: 40, fontSize: 18, - }).setDepth(D.ui); - new Button(this, 90, GAME_HEIGHT - 78, 'New', () => { if (!this.busy) this.startNewMatch(); }, { - variant: 'ghost', width: 130, height: 40, fontSize: 18, - }).setDepth(D.ui); - } - - seatName(seat) { - if (seat === 0) return auth.user?.username ?? 'You'; - return this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`; - } - - // ── Match lifecycle ───────────────────────────────────────────────────────── - - startNewMatch() { - this.gameOver = false; - this.awaitingHuman = false; - this.clearTrick(); - this.clearHandObjs(); - this.clearTransient(); - this.hideBanner(); - this.gs = createInitialState(); - this.updateScores(); - this.beginHand(); - } - - async beginHand() { - this.busy = true; - this.passSelection.clear(); - this.clearTrick(); - this.hideBanner(); - this.updateHeartsIndicator(); - playSound(this, SFX.CARD_SHUFFLE); - await this.dealAnimation(); - const SUIT_ORDER = { c: 0, d: 1, s: 2, h: 3 }; - this.gs.players[0].hand.sort((a, b) => { - const sd = SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit]; - return sd !== 0 ? sd : a.value - b.value; - }); - this.renderHands(); - this.updateScores(); - this.busy = false; - - if (this.gs.phase === 'passing') { - this.setupPassing(); - } else { - await this.advance(); - } - } - - // ── Passing ────────────────────────────────────────────────────────────────── - - setupPassing() { - // AI opponents lock in their passes immediately (hidden). + buildBadges() { + this.badges = []; for (let seat = 1; seat < 4; seat++) { - this.gs = selectPass(this.gs, seat, choosePass(this.gs, seat)); + const p = handBadge(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, '13', { fontFamily: 'Righteous', fontSize: '16px', color: COLORS.textHex }).setOrigin(0.5); + c.add([g, t]); + this.badges[seat] = { c, t }; } - const dir = DIRECTION_LABEL[this.gs.passDirection]; - this.setStatus(`Choose ${PASS_COUNT} cards to pass ${dir}, then press Pass.`); - this.renderHands(); - - this.passButton = new Button(this, CX, GAME_HEIGHT - 285, `Pass ${PASS_COUNT} ▶`, () => this.confirmPass(), { - width: 220, height: 50, fontSize: 22, - bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex, - }).setDepth(D.ui); - this.passButton.setEnabled(false); } - togglePassSelection(cardId) { - if (this.passSelection.has(cardId)) { - this.passSelection.delete(cardId); - } else if (this.passSelection.size < PASS_COUNT) { - this.passSelection.add(cardId); + buildTooltips() { + for (let seat = 1; seat < 4; seat++) { + const pl = L.seats[seat].plate; + this.hoverZone(pl.x, pl.y, 300, 96, () => this.seatTip(seat)); } - this.passButton?.setEnabled(this.passSelection.size === PASS_COUNT); - this.renderHands(); } - async confirmPass() { - if (this.passSelection.size !== PASS_COUNT) return; - const outgoingIds = [...this.passSelection]; - this.passButton?.destroy(); - this.passButton = null; - this.passSelection.clear(); - this.busy = true; - - const dir = this.gs.passDirection; - const targetSeat = passTargetSeat(0, dir); - - // Find which opponent passes TO player 0. - let sourceSeat = 1; - for (let s = 1; s < 4; s++) { - if (passTargetSeat(s, dir) === 0) { sourceSeat = s; break; } - } - - // Capture incoming card data before state is applied. - const incomingIds = new Set(this.gs.pendingPass[sourceSeat]); - const incomingCards = this.gs.players[sourceSeat].hand.filter((c) => incomingIds.has(c.id)); - - const targetLay = slotLayout(SLOTS[targetSeat]); - const sourceLay = slotLayout(SLOTS[sourceSeat]); - - // ── Phase 1: Player's cards fly to the target opponent ─────────────────── - const outgoingSprites = outgoingIds - .map((id) => this.handCardObjs.get(`0-${id}`)) - .filter(Boolean); - for (const s of outgoingSprites) s.setDepth(D.ui + 5); - playSound(this, SFX.CARD_DEAL); - await Promise.all(outgoingSprites.map((s) => - this.tweenTo(s, targetLay.portrait.x, targetLay.portrait.y, 380) - )); - - // Apply state and sort the final hand. - this.gs = selectPass(this.gs, 0, outgoingIds); - const SUIT_ORDER = { c: 0, d: 1, s: 2, h: 3 }; - this.gs.players[0].hand.sort((a, b) => { - const sd = SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit]; - return sd !== 0 ? sd : a.value - b.value; - }); - - for (const s of outgoingSprites) s.destroy(); - this.renderHands(); - // Keep incoming card positions reserved but invisible until they animate in. - for (const card of incomingCards) { - this.handCardObjs.get(`0-${card.id}`)?.setAlpha(0); - } - - // ── Phase 2: Face-down cards fly in from source opponent ───────────────── - const stagingY = slotLayout('bottom').handCenter.y - 180; - const stagingSprites = incomingCards.map((card) => { - const s = this.makeCardSprite(card, sourceLay.portrait.x, sourceLay.portrait.y, { faceUp: false }); - s.setDepth(D.ui + 5); - return s; - }); - - playSound(this, SFX.CARD_DEAL); - await Promise.all(stagingSprites.map((s, i) => - new Promise((resolve) => { - this.tweens.add({ - targets: s, - x: CX + (i - 1) * (HAND_SPREAD + 12), - y: stagingY, - delay: i * 90, - duration: 380, - ease: 'Cubic.easeOut', - onComplete: resolve, - }); - }) - )); - - // ── Phase 3: Flip each card to reveal face-up ───────────────────────────── - for (let i = 0; i < stagingSprites.length; i++) { - const sprite = stagingSprites[i]; - const card = incomingCards[i]; - await new Promise((resolve) => { - this.tweens.add({ - targets: sprite, scaleX: 0, duration: 140, ease: 'Linear', - onComplete: () => { - this.renderCardFace(sprite, card, true); - this.tweens.add({ targets: sprite, scaleX: 1, duration: 140, ease: 'Linear', onComplete: resolve }); - }, - }); - }); - playSound(this, SFX.CARD_PLACE); - if (i < stagingSprites.length - 1) await this.delay(70); - } - - await this.delay(420); - - // ── Phase 4: Cards slide into their sorted positions in the hand ────────── - await Promise.all(stagingSprites.map((sprite, i) => { - const target = this.handCardObjs.get(`0-${incomingCards[i].id}`); - if (!target) { sprite.destroy(); return Promise.resolve(); } - return new Promise((resolve) => { - this.tweens.add({ - targets: sprite, x: target.x, y: target.y, duration: 320, ease: 'Cubic.easeOut', - onComplete: () => { - target.setAlpha(1); - sprite.destroy(); - resolve(); - }, - }); - }); - })); - - this.busy = false; - await this.advance(); + seatTip(seat) { + if (!this.gs) return null; + const p = this.gs.players[seat]; + const voids = knownVoids(this.gs)[seat]; + const lines = [ + { text: `${p.roundPoints} point${p.roundPoints === 1 ? '' : 's'} taken this hand`, color: p.roundPoints ? '#ff8a7a' : COLORS.textHex }, + { text: `Total ${p.totalScore} (lowest wins)` }, + { text: voids.size ? `Has shown out of ${[...voids].map(s => SUIT_SYM[s]).join(' ')}` : 'Has followed suit so far', color: COLORS.goldHex }, + { text: `${p.hand.length} cards left · skill ${this.skillFor(seat)} / 5`, color: COLORS.mutedHex }, + ]; + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; } - // ── Turn flow ───────────────────────────────────────────────────────────────── + // ── Match / hand lifecycle ──────────────────────────────────────────────── + newMatch() { + this.history = []; + this.gs = createInitialState({ target: this.settings.target, moonMode: this.settings.moon }); + this.startHand(); + } - async advance() { - if (this.gameOver) return; + async startHand() { + this.clearSprites(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + this.passSel = new Set(); + this.received = new Set(); + this.holdTrick = null; + this.revealAll = false; + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } const gs = this.gs; - if (gs.phase === 'playing') { - this.updateTurnIndicator(); - if (gs.currentPlayer === 0) { - this.awaitingHuman = true; - this.legalIds = new Set(legalPlays(gs, 0).map((c) => c.id)); - this.renderHands(); - this.setStatus(this.gs.trickNumber === 0 && this.gs.trick.length === 0 - ? 'Your lead — play the 2♣.' - : 'Your turn — play a card.'); - } else { - this.awaitingHuman = false; - this.setStatus(`${this.seatName(gs.currentPlayer)} is thinking…`); - await this.delay(550); - await this.applyPlay(choosePlay(this.gs, this.gs.currentPlayer)); - await this.advance(); - } - } else if (gs.phase === 'handOver') { - await this.showHandOver(); - } else if (gs.phase === 'gameOver') { - await this.endGame(); + const from = T.flat(0, 0.45, 0.9); + const dealOrder = new Map(); + gs.players.forEach(p => { + [...p.hand].sort((a, b) => a.id - b.id).forEach((c, i) => dealOrder.set(c.id, i * 4 + p.seat)); + for (const c of p.hand) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + }); + this.sortHand(); + this.updatePlates(); + this.updateDock(); + this.drawArrow(); + playSound(this, SFX.CARD_SHUFFLE); + const step = 26; + this.layout({ duration: 280, delayFor: (v) => 300 + (dealOrder.get(v.card.id) ?? 0) * step }); + for (let i = 0; i < 52; i += 4) this.time.delayedCall(320 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.4 })); + await this.wait(300 + 52 * step + 500); + if (!this.alive() || token !== this.turnToken) return; + if (gs.phase === 'passing') this.beginPassing(); + else { + this.floatText(CENTRE, 'No passing this hand', '#f2d6a0', { size: 26, ms: 1600 }); + await this.wait(900); + if (!this.alive()) return; + this.advance(); } } - onCardClick(cardId) { - if (this.busy) return; - if (this.gs.phase === 'passing') { - this.togglePassSelection(cardId); - } else if (this.gs.phase === 'playing' && this.awaitingHuman && this.legalIds.has(cardId)) { - this.playHuman(cardId); - } + beginPassing() { + // the opponents choose straight away; the table waits on you + let gs = this.gs; + for (let s = 1; s < 4; s++) gs = selectPass(gs, s, choosePass(gs, s, { skill: this.skillFor(s) })); + this.gs = gs; + this.mode = 'passing'; + this.drawArrow(); + this.layout(); + this.updateDock(); } - async playHuman(cardId) { - this.awaitingHuman = false; - this.legalIds = new Set(); - await this.applyPlay(cardId); - await this.advance(); + submitPass() { + if (this.mode !== 'passing' || this.passSel.size !== PASS_COUNT || this.modal) return; + const prevHand = new Set(this.gs.players[0].hand.map(c => c.id)); + const next = selectPass(this.gs, 0, [...this.passSel]); + if (next === this.gs) return; + this.passSel = new Set(); + this.gs = next; + this.received = new Set(next.players[0].hand.filter(c => !prevHand.has(c.id)).map(c => c.id)); + this.sortHand(); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.5 }); + this.mode = 'idle'; + this.drawArrow(); + // the passes cross the table together + this.layout({ duration: 520 }); + this.updateDock(); + this.time.delayedCall(900, () => { + for (const id of this.received) this.flashGlow(id, 0x7cf0a0, { delay: 0, hold: 1400 }); + this.floatText({ x: CX, y: 860 }, 'Cards passed — the new ones are glowing', '#7cf0a0', { size: 20, ms: 1800 }); + this.advance(); + }); } - async applyPlay(cardId) { - if (cardId == null) return; - this.busy = true; - const seat = this.gs.currentPlayer; - const lay = slotLayout(SLOTS[seat]); - const card = this.gs.players[seat].hand.find((c) => c.id === cardId); - const cardData = card ? { rank: card.rank, suit: card.suit, id: card.id, label: card.label, suitSymbol: card.suitSymbol } : null; - - this.gs = playCard(this.gs, cardId); - playSound(this, SFX.CARD_PLACE); - this.renderHands(); - - // Fly the played card from the seat's hand into its trick slot. - if (cardData) { - const sprite = this.makeCardSprite(cardData, lay.handCenter.x, lay.handCenter.y, { faceUp: true }); - sprite.setDepth(D.trick); - this.trickSprites.set(seat, sprite); - await this.tweenTo(sprite, lay.trick.x, lay.trick.y, 220); - } - - // Did that play complete the trick? - if (this.gs.lastTrick && this.gs.trick.length === 0) { - const lt = this.gs.lastTrick; - this.showBanner(`${this.seatName(lt.winnerSeat)} takes the trick${lt.points ? ` (+${lt.points})` : ''}.`); - await this.delay(750); - await this.collectTrick(lt.winnerSeat); - this.hideBanner(); - this.updateScores(); - this.updateHeartsIndicator(); - } - this.busy = false; - } - - async collectTrick(winnerSeat) { - const lay = slotLayout(SLOTS[winnerSeat]); - const tweens = []; - for (const sprite of this.trickSprites.values()) { - tweens.push(new Promise((resolve) => { - this.tweens.add({ - targets: sprite, x: lay.portrait.x, y: lay.portrait.y, scaleX: 0.4, scaleY: 0.4, - alpha: 0.2, duration: 320, ease: 'Cubic.easeIn', onComplete: resolve, - }); - })); - } - await Promise.all(tweens); - this.clearTrick(); - } - - // ── Hand / game end ─────────────────────────────────────────────────────────── - - async showHandOver() { + advance() { + if (!this.alive() || !this.gs) return; const gs = this.gs; - const lines = gs.players.map((p, seat) => { - const gained = gs.handScores[seat]; - return `${this.seatName(seat).padEnd(0)}: +${gained} → ${p.totalScore}`; - }); - let title = 'Hand complete'; - if (gs.moonShooter != null) title = `${this.seatName(gs.moonShooter)} shot the moon!`; - - await new Promise((resolve) => { - const panel = this.buildPanel(title, lines, 'Next hand', () => { panel.destroy(true); resolve(); }); - }); - this.gs = startNextHand(this.gs); - await this.beginHand(); - } - - async endGame() { - this.gameOver = true; - this.awaitingHuman = false; - this.updateTurnIndicator(); - const gs = this.gs; - - const order = [...gs.players].sort((a, b) => a.totalScore - b.totalScore); - const winners = new Set(gs.winnerSeats); - const lines = order.map((p) => { - const tag = winners.has(p.seat) ? ' ★' : ''; - return `${this.seatName(p.seat)}: ${p.totalScore}${tag}`; - }); - const youWon = winners.has(0); - const title = youWon ? (winners.size > 1 ? 'Tie game!' : 'You win!') : `${this.seatName(order[0].seat)} wins`; - playSound(this, youWon ? SFX.CASINO_WIN : SFX.CASINO_LOSE); - - this.recordHistory(); - - const panel = this.buildPanel(title, lines, 'New game', () => { panel.destroy(true); this.startNewMatch(); }, true); - } - - async recordHistory() { - const totals = this.gs.players.map((p) => p.totalScore); - const winners = new Set(this.gs.winnerSeats); - let result; - if (winners.has(0) && winners.size === 1) result = 'win'; - else if (winners.has(0)) result = 'draw'; - else result = 'loss'; - try { - await api.post('/history/single-player', { - slug: 'hearts', - score: totals[0], - opponentScores: totals.slice(1), - result, - }); - } catch (_) { /* not signed in / offline — ignore */ } - } - - buildPanel(title, lines, btnLabel, onClick, withLeave = false) { - const panel = this.add.container(0, 0).setDepth(D.modal); - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.65).setInteractive(); - const h = 200 + lines.length * 44; - const box = this.add.rectangle(CX, CY, 640, h, COLORS.panel, 1).setStrokeStyle(3, COLORS.accent); - const titleText = this.add.text(CX, CY - h / 2 + 46, title, { - fontFamily: 'Righteous', fontSize: '38px', color: COLORS.goldHex, - }).setOrigin(0.5); - panel.add([overlay, box, titleText]); - - lines.forEach((line, i) => { - panel.add(this.add.text(CX, CY - h / 2 + 110 + i * 44, line, { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0.5)); - }); - - const btnY = CY + h / 2 - 50; - if (withLeave) { - panel.add(new Button(this, CX - 150, btnY, btnLabel, onClick, { width: 260 })); - panel.add(new Button(this, CX + 150, btnY, 'Leave', () => this.scene.start('GameMenu'), { width: 260, variant: 'ghost' })); + if (gs.phase === 'handOver' || gs.phase === 'gameOver') { this.onHandOver(); return; } + const seat = gs.currentPlayer; + this.setSpot(spotFor(seat)); + if (seat === 0) { + this.mode = 'human'; + this.layout(); + this.updateDock(); + this.updatePlates(); } else { - panel.add(new Button(this, CX, btnY, btnLabel, onClick, { width: 300 })); - } - return panel; - } - - // ── Rendering ────────────────────────────────────────────────────────────────── - - renderHands() { - this.clearHandObjs(); - this.clearTransient(); - for (let seat = 0; seat < this.gs.players.length; seat++) { - this.renderSeatHand(seat); + this.mode = 'ai'; + this.layout(); + this.updateDock(); + this.updatePlates(); + this.runAITurn(seat); } } - renderSeatHand(seat) { - if (seat === 0) this.localHandCards = []; - const player = this.gs.players[seat]; - const lay = slotLayout(SLOTS[seat]); - const n = player.hand.length; - const selecting = this.gs.phase === 'passing' && seat === 0; - const playable = this.gs.phase === 'playing' && seat === 0 && this.awaitingHuman; + // Apply a new state after a play; show a finished trick before it's swept. + async commit(next, { carry = null, carrySeat = null } = {}) { + const prev = this.gs; + this.gs = next; + const fresh = next.log.slice(prev.log.length); + const trickDone = next.trickNumber !== prev.trickNumber || (next.phase !== 'playing' && prev.phase === 'playing'); + if (trickDone) this.holdTrick = next.lastTrick; + this.layout({ durationFor: (v) => (carry != null && v.card.id === carry ? this.timing(carrySeat).carry : null) }); + for (const e of fresh) this.logEffect(e); + this.updatePlates(); + this.updateDock(); + if (!trickDone) return; + const t = next.lastTrick; + const token = this.turnToken; + // the winning card glows, the points float, then the winner sweeps it up + await this.wait(380); + const winCard = t.plays.find(p => p.seat === t.winnerSeat).card; + this.flashGlow(winCard.id, 0xffd35a, { delay: 0, hold: 500 }); + if (t.points) this.floatText(trickPose(t.winnerSeat), `+${t.points}`, '#ff8a7a', { size: 30 }); + await this.wait(TRICK_HOLD_MS * this.pace()); + if (!this.alive() || token !== this.turnToken) return; + if (t.winnerSeat > 0) this.moveHand(t.winnerSeat, trickPose(t.winnerSeat), 260); + this.holdTrick = null; + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.35, rate: 1.6 }); + this.layout({ duration: 420 }); + if (t.winnerSeat > 0) this.handRest(t.winnerSeat, 420, 300); + if (t.plays.some(p => isQueenOfSpades(p.card))) { + this.portraits[t.winnerSeat]?.playEmotion?.('upset'); + this.plateStamp(t.winnerSeat, 'Q♠ +13', '#c9a0ff', 1600); + } + await this.wait(460); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } - for (let i = 0; i < n; i++) { - const card = player.hand[i]; - const offset = i - (n - 1) / 2; - let x = lay.handCenter.x; - let y = lay.handCenter.y; - if (lay.handAxis === 'x') x += offset * HAND_SPREAD; - else y += offset * HAND_SPREAD; - - const selected = selecting && this.passSelection.has(card.id); - if (selected) y -= 26; - - const sprite = this.makeCardSprite(card, x, y, { faceUp: lay.faceUp, rotation: lay.rotateCards }); - this.handCardObjs.set(`${seat}-${card.id}`, sprite); - - if (seat === 0) { - const interactive = selecting || (playable && this.legalIds.has(card.id)); - const dimmed = playable && !this.legalIds.has(card.id); - if (dimmed) sprite.setAlpha(0.45); - - sprite.setInteractive(new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), Phaser.Geom.Rectangle.Contains); - sprite.input.cursor = interactive ? 'pointer' : 'default'; - sprite.on('pointerover', () => { if (!this.busy && !this.dragState) sprite.y -= 10; }); - sprite.on('pointerout', () => { if (!this.busy && !this.dragState) sprite.y += 10; }); - sprite.on('pointerdown', (pointer) => { - if (this.busy || this.dragState) return; - this.potentialDrag = { - handIdx: i, cardId: card.id, isInteractive: interactive, - startX: pointer.x, startY: pointer.y, - offsetX: pointer.x - sprite.x, offsetY: pointer.y - sprite.y, - }; - }); - - this.localHandCards.push(sprite); - if (selected) this.ringCard(x, y); - } + logEffect(e) { + if (e.kind === 'heartsBroken') this.heartsBroken(e.seat); + else if (e.kind === 'queen') { + this.stamp('Queen of Spades!', { x: CX, y: CY - 60 }, '#c9a0ff', { size: 56, hold: 900 }); + this.cameras.main.shake(180, 0.005); + playSoundEx(this, SFX.CARD_SHOW, { volume: 0.7, rate: 0.8 }); } } - ringCard(x, y) { - const ring = this.add.graphics().setDepth(D.highlight); - ring.lineStyle(3, COLORS.accent, 1); - ring.strokeRoundedRect(x - CARD_W / 2 - 3, y - CARD_H / 2 - 3, CARD_W + 6, CARD_H + 6, CARD_R + 2); - this.transient.push(ring); + heartsBroken(seat) { + const at = CENTRE; + const l = this.add.image(at.x, at.y, 'hearts-heart-l').setDepth(D.stamp).setScale(0.2); + const r = this.add.image(at.x, at.y, 'hearts-heart-r').setDepth(D.stamp).setScale(0.2); + this.tweens.add({ targets: [l, r], scale: 0.9, duration: 260, ease: 'Back.easeOut' }); + this.tweens.add({ targets: l, x: at.x - 50, angle: -18, alpha: 0, delay: 650, duration: 600, ease: 'Cubic.easeIn', onComplete: () => l.destroy() }); + this.tweens.add({ targets: r, x: at.x + 50, angle: 18, alpha: 0, delay: 650, duration: 600, ease: 'Cubic.easeIn', onComplete: () => r.destroy() }); + this.floatText({ x: at.x, y: at.y + 90 }, seat === 0 ? 'You broke hearts!' : 'Hearts are broken!', '#ff8a8a', { size: 26, ms: 1500 }); + playSoundEx(this, SFX.CARD_SHOW, { volume: 0.6, rate: 1.3 }); } - makeCardSprite(card, x, y, { faceUp = true, rotation = 0 } = {}) { - const c = this.add.container(x, y).setDepth(D.card); - c.setRotation((rotation * Math.PI) / 180); - this.renderCardFace(c, card, faceUp); - c.cardId = card.id; - 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); - container.add(g); - } - 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)); - } - - updateScores() { - for (let seat = 0; seat < this.gs.players.length; seat++) { - const p = this.gs.players[seat]; - this.scoreTexts[seat]?.setText(`Total ${p.totalScore} +${p.roundPoints}`); - } - } - - updateHeartsIndicator() { - const broken = this.gs.heartsBroken; - this.heartsText?.setText(broken ? '♥ Hearts broken' : ''); - this.heartsBg?.clear(); - if (broken) { - const t = this.heartsText; - const pad = 8; - this.heartsBg.fillStyle(0x000000, 0.55); - this.heartsBg.fillRoundedRect(t.x - t.width / 2 - pad, t.y - t.height / 2 - pad, t.width + pad * 2, t.height + pad * 2, 6); - } - } - - updateTurnIndicator() { - if (this.gameOver || this.gs.phase !== 'playing') { this.turnGlow?.setVisible(false); return; } - const lay = slotLayout(SLOTS[this.gs.currentPlayer]); - if (!this.turnGlow) this.turnGlow = this.add.circle(0, 0, 72, COLORS.accent, 0.2).setDepth(D.portrait - 1); - this.turnGlow.setPosition(lay.portrait.x, lay.portrait.y).setVisible(true); - } - - // ── Deal animation ────────────────────────────────────────────────────────────── - - async dealAnimation() { - const sprites = []; - const deck = this.makeCardSprite({ label: '', suit: 's', suitSymbol: '', id: -1 }, CX, CY, { faceUp: false }); - deck.setDepth(D.card); - - const counts = this.gs.players.map((p) => p.hand.length); - const maxCards = Math.max(...counts); - let order = 0; - const tweens = []; - for (let i = 0; i < maxCards; i++) { - for (let seat = 0; seat < 4; seat++) { - if (i >= counts[seat]) continue; - const lay = slotLayout(SLOTS[seat]); - const sprite = this.makeCardSprite({ label: '', suit: 's', suitSymbol: '', id: -1 }, CX, CY, { faceUp: false }); - sprite.setDepth(D.card); - sprites.push(sprite); - const delay = order * 12; - order += 1; - tweens.push(new Promise((resolve) => { - this.tweens.add({ - targets: sprite, x: lay.handCenter.x, y: lay.handCenter.y, delay, duration: 170, ease: 'Cubic.easeOut', - onStart: () => { if (delay % 48 === 0) playSound(this, SFX.CARD_DEAL); }, - onComplete: resolve, - }); - })); - } - } - await Promise.all(tweens); - for (const s of sprites) s.destroy(); - deck.destroy(); - } - - // ── Status / banner ─────────────────────────────────────────────────────────── - - setStatus(text) { - this.statusText.setText(text); - const t = this.statusText; - const pad = 10; - this.statusBg.clear(); - this.statusBg.fillStyle(0x000000, 0.55); - this.statusBg.fillRoundedRect(t.x - t.width / 2 - pad, t.y - t.height / 2 - pad, t.width + pad * 2, t.height + pad * 2, 6); - this.statusBg.setVisible(true); - } - - showBanner(text) { - this.bannerText.setText(text).setVisible(true); - const w = Math.max(this.bannerText.width + 60, 360); - const h = this.bannerText.height + 28; - this.bannerBg.clear(); - this.bannerBg.fillStyle(COLORS.panel, 0.9); - 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); - } - - hideBanner() { - this.bannerText?.setVisible(false); - this.bannerBg?.setVisible(false); - } - - // ── Cleanup helpers ───────────────────────────────────────────────────────────── - - clearHandObjs() { - this.dragState = null; - this.potentialDrag = null; - this.localHandCards = []; - for (const c of this.handCardObjs.values()) c.destroy(); - this.handCardObjs.clear(); - } - - clearTransient() { - for (const o of this.transient) o.destroy(); - this.transient = []; - } - - clearTrick() { - for (const s of this.trickSprites.values()) s.destroy(); - this.trickSprites.clear(); - } - - // ── Hand drag-to-sort ───────────────────────────────────────────────────── - - setupDragHandlers() { - this.input.on('pointermove', (pointer) => { - if (this.potentialDrag && !this.dragState) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (Math.sqrt(dx * dx + dy * dy) >= 8) { - const pd = this.potentialDrag; - this.potentialDrag = null; - this.startCardDrag(pd.handIdx, pd.offsetX, pd.offsetY); - } - } - if (this.dragState) this.updateCardDrag(pointer); - }); - - this.input.on('pointerup', () => { - if (this.potentialDrag) { - const { cardId, isInteractive } = this.potentialDrag; - this.potentialDrag = null; - if (isInteractive) this.onCardClick(cardId); - return; - } - if (this.dragState) this.endCardDrag(); - }); - } - - startCardDrag(handIdx, offsetX, offsetY) { - const card = this.localHandCards[handIdx]; + // ── 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 || this.gs.phase !== 'playing') return; + const id = choosePlay(this.gs, seat, { skill: this.skillFor(seat) }); + const card = this.gs.players[seat].hand.find(c => c.id === id); if (!card) return; - const hand = this.gs.players[0].hand; - const n = hand.length; - const lay = slotLayout('bottom'); - const handStartX = lay.handCenter.x - (n - 1) / 2 * HAND_SPREAD; - const handCenterY = lay.handCenter.y; - const insertIdx = Phaser.Math.Clamp(Math.round((card.x - handStartX) / HAND_SPREAD), 0, n - 1); - const isLegal = this.gs.phase === 'playing' && this.awaitingHuman && this.legalIds.has(hand[handIdx].id); - - this.tweens.killTweensOf(card); - - const shadow = this.add.graphics(); - shadow.fillStyle(0x000000, 0.35); - shadow.fillEllipse(0, 0, CARD_W * 1.1, 28); - shadow.setPosition(card.x + 6, card.y + 16); - shadow.setDepth(D.card + 9); - this.transient.push(shadow); - - const slotIndicator = this.add.graphics(); - slotIndicator.lineStyle(3, COLORS.accent, 0.75); - slotIndicator.strokeRoundedRect(-CARD_W / 2 - 4, -CARD_H / 2 - 4, CARD_W + 8, CARD_H + 8, 10); - slotIndicator.fillStyle(COLORS.accent, 0.1); - slotIndicator.fillRoundedRect(-CARD_W / 2 - 4, -CARD_H / 2 - 4, CARD_W + 8, CARD_H + 8, 10); - slotIndicator.setPosition(handStartX + insertIdx * HAND_SPREAD, handCenterY); - slotIndicator.setDepth(D.card - 1); - this.transient.push(slotIndicator); - - let playZoneHighlight = null; - if (isLegal) { - const pt = slotLayout('bottom').trick; - playZoneHighlight = this.add.graphics(); - playZoneHighlight.lineStyle(4, COLORS.accent, 0.9); - playZoneHighlight.strokeRoundedRect(-CARD_W / 2 - 6, -CARD_H / 2 - 6, CARD_W + 12, CARD_H + 12, 12); - playZoneHighlight.fillStyle(COLORS.accent, 0.18); - playZoneHighlight.fillRoundedRect(-CARD_W / 2 - 6, -CARD_H / 2 - 6, CARD_W + 12, CARD_H + 12, 12); - playZoneHighlight.setPosition(pt.x, pt.y); - playZoneHighlight.setDepth(D.card + 1); - playZoneHighlight.setAlpha(0); - this.transient.push(playZoneHighlight); - } - - this.dragState = { cardIdx: handIdx, offsetX, offsetY, shadow, slotIndicator, insertIdx, handStartX, handCenterY, isLegal, playZoneHighlight, overPlayZone: false }; - - card.setDepth(D.card + 10); - this.tweens.add({ targets: card, scaleX: 1.08, scaleY: 1.08, duration: 120, ease: 'Cubic.easeOut' }); + this.moveHand(seat, this.poseOf(id) ?? handPose(seat, 0, this.gs.players[seat].hand.length), T0.reach * 0.7); + await this.wait(T0.reach * 0.7); + if (!this.alive() || token !== this.turnToken) return; + const next = playCard(this.gs, id); + if (next === this.gs) return; + this.moveHand(seat, trickPose(seat), T0.carry, 'Cubic.easeOut'); + this.handRest(seat, T0.carry * 0.7, T0.carry); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.55 }); + this.mode = 'idle'; + const done = next.trickNumber !== this.gs.trickNumber || next.phase !== 'playing'; + const p = this.commit(next, { carry: id, carrySeat: seat }); + if (done) return; // commit() advances after the trick is swept + await this.wait(T0.carry); + await p; + if (!this.alive() || token !== this.turnToken) return; + this.advance(); } - _isPlayZone(x, y) { - const pt = slotLayout('bottom').trick; - return Math.abs(x - pt.x) < CARD_W * 1.5 && Math.abs(y - pt.y) < CARD_H * 1.5; - } - - updateCardDrag(pointer) { - const ds = this.dragState; - const card = this.localHandCards[ds.cardIdx]; - const n = this.gs.players[0].hand.length; - - card.x = pointer.x - ds.offsetX; - card.y = pointer.y - ds.offsetY; - ds.shadow.setPosition(card.x + 6, card.y + 16); - - const overPlayZone = ds.isLegal && this._isPlayZone(card.x, card.y); - if (overPlayZone !== ds.overPlayZone) { - ds.overPlayZone = overPlayZone; - if (overPlayZone) { - this.tweens.killTweensOf(ds.slotIndicator); - ds.slotIndicator.setAlpha(0); - this._settleNonDraggedCards(); - this.tweens.add({ targets: ds.playZoneHighlight, alpha: 1, duration: 150 }); + // ── 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); }; + const onTrick = new Set(); + const trick = this.holdTrick?.plays ?? gs.trick; + trick.forEach((t, i) => { onTrick.add(t.card.id); put(t.card, { kind: 'trick', seat: t.seat, pose: trickPose(t.seat), faceUp: true, depth: D.cards + 2 + i * 0.01 }); }); + for (const p of gs.players) { + const seat = p.seat; + // won cards: points face up in a row, the rest in a face-down stack + const pts = p.wonCards.filter(c => cardPoints(c) > 0 && !onTrick.has(c.id)); + const rest = p.wonCards.filter(c => cardPoints(c) === 0 && !onTrick.has(c.id)); + pts.forEach((c, i) => put(c, { kind: 'points', seat, pose: pointPose(seat, i), faceUp: true, depth: D.cards + 1 + i * 0.01 })); + const top = tricksPose(seat, rest.length); + rest.forEach((c, i) => (i === rest.length - 1 ? put(c, { kind: 'tricks', seat, pose: top, faceUp: false, depth: D.cards + 0.5 }) : loc.set(c.id, { pose: top, faceUp: false, depth: D.cards }))); + if (seat === 0) { + const legal = this.mode === 'human' ? new Set(legalPlays(gs, 0).map(c => c.id)) : null; + 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 = 0; + if (this.passSel.has(id)) lift = 44; + else if (id === this.hoverId) lift = 24; + else if (legal?.has(id) && this.settings.hints) lift = 8; + put(c, { kind: 'hand', seat: 0, idx: i, pose: handPose(0, i, ids.length, lift), faceUp: true, depth: D.hand + i * 0.01, legal: legal ? legal.has(id) : null }); + }); } else { - ds.slotIndicator.setAlpha(1); - this._updateNonDraggedCards(); - this.tweens.add({ targets: ds.playZoneHighlight, alpha: 0, duration: 150 }); + p.hand.forEach((c, i) => put(c, { kind: 'hand', seat, idx: i, pose: handPose(seat, i, p.hand.length), faceUp: this.revealAll, depth: D.oppHand + i * 0.01 })); } } + return { visible, loc }; + } - if (!overPlayZone) { - const newInsertIdx = Phaser.Math.Clamp(Math.round((card.x - ds.handStartX) / HAND_SPREAD), 0, Math.max(0, n - 1)); - if (newInsertIdx !== ds.insertIdx) { - ds.insertIdx = newInsertIdx; - this.tweens.killTweensOf(ds.slotIndicator); - this.tweens.add({ targets: ds.slotIndicator, x: ds.handStartX + newInsertIdx * HAND_SPREAD, duration: 100, ease: 'Cubic.easeOut' }); - this._updateNonDraggedCards(); - } + beforeLayout() { + this.suggested = new Set(); + if (!this.settings.hints) return; + if (this.mode === 'passing') for (const id of suggestPass(this.gs, 0)) this.suggested.add(id); + else if (this.mode === 'human' && this.gs.currentPlayer === 0) { + const id = suggestPlay(this.gs, 0); + if (id != null) this.suggested.add(id); } } - _updateNonDraggedCards() { - const ds = this.dragState; - const n = this.gs.players[0].hand.length; - const others = []; - for (let i = 0; i < n; i++) { if (i !== ds.cardIdx) others.push(i); } + decorate(c, v) { + const mine = v.kind === 'hand' && v.seat === 0; + const mark = mine && this.suggested?.has(v.card.id) ? '★' : ''; + c.mark.setText(mark).setColor('#ffd35a').setVisible(!!mark && v.faceUp); + c.chip.setVisible(false); + const dim = mine && this.settings.hints && v.legal === false; + c.faceImg.setTint(dim ? 0x9a948a : 0xffffff); + const sel = mine && this.passSel.has(v.card.id); + c.glow.setVisible(sel).setTint(0xffd35a).setAlpha(1); + } - for (let k = 0; k < others.length; k++) { - const j = others[k]; - const finalPos = k < ds.insertIdx ? k : k + 1; - const targetX = ds.handStartX + finalPos * HAND_SPREAD; - const distFromGap = Math.abs(finalPos - ds.insertIdx); - const leanDir = finalPos < ds.insertIdx ? -1 : 1; - const targetRot = leanDir * Math.max(0, 2 - distFromGap) * 0.04; - const targetScale = distFromGap <= 1 ? 0.95 : 1.0; - const cardObj = this.localHandCards[j]; - this.tweens.killTweensOf(cardObj); - this.tweens.add({ targets: cardObj, x: targetX, rotation: targetRot, scaleX: targetScale, scaleY: targetScale, duration: 100, ease: 'Cubic.easeOut' }); + afterLayout() { + for (let s = 1; s < 4; s++) this.badges[s]?.t.setText(String(this.gs.players[s].hand.length)); + } + + drawArrow() { + const g = this.arrowG; + g.clear(); + if (this.mode !== 'passing' && this.mode !== 'deal') { this.arrowTxt.setText(''); return; } + const dir = this.gs.passDirection; + if (dir === 'hold') { this.arrowTxt.setText(''); return; } + const target = passTargetSeat(0, dir); + const to = handHome(target); + const from = { x: CENTRE.x, y: CENTRE.y + 20 }; + const ang = Math.atan2(to.y - from.y, to.x - from.x); + const len = 120; + const ex = from.x + Math.cos(ang) * len, ey = from.y + Math.sin(ang) * len * SQ; + g.lineStyle(10, 0xf2d6a0, 0.55); + g.beginPath(); g.moveTo(from.x - Math.cos(ang) * 40, from.y - Math.sin(ang) * 40 * SQ); g.lineTo(ex, ey); g.strokePath(); + g.fillStyle(0xf2d6a0, 0.7); + const hx = Math.cos(ang), hy = Math.sin(ang) * SQ; + g.fillTriangle(ex + hx * 28, ey + hy * 28, ex - hy * 20, ey + hx * 20, ex + hy * 20, ey - hx * 20); + this.arrowTxt.setText(`Pass 3 ${DIR_NAME[dir]} → ${this.shortName(target)}`); + } + + updatePlates() { + if (!this.gs) return; + const gs = this.gs; + for (let s = 0; s < 4; s++) { + const pl = this.plates[s]; + const p = gs.players[s]; + pl.scoreTxt.setText(`${p.totalScore + (this.plateTally?.[s] ?? 0)}`); + pl.infoTxt.setText(`♥ ${p.roundPoints} this hand`).setColor(p.roundPoints ? '#ff8a7a' : COLORS.goldHex); + const q = p.wonCards.some(isQueenOfSpades); + pl.statusTxt.setText(q ? 'has Q♠' : '').setColor('#c9a0ff'); + this.setPlateActive(s, gs.phase === 'playing' && gs.currentPlayer === s && (this.mode === 'human' || this.mode === 'ai')); } } - _settleNonDraggedCards() { - const ds = this.dragState; - const hand = this.gs.players[0].hand; - const n = hand.length; - const remaining = n - 1; - const settleStartX = slotLayout('bottom').handCenter.x - (remaining - 1) / 2 * HAND_SPREAD; - let k = 0; - for (let j = 0; j < n; j++) { - if (j === ds.cardIdx) continue; - const cardObj = this.localHandCards[j]; - this.tweens.killTweensOf(cardObj); - this.tweens.add({ targets: cardObj, x: settleStartX + k * HAND_SPREAD, rotation: 0, scaleX: 1, scaleY: 1, duration: 150, ease: 'Cubic.easeOut' }); - k++; - } - } + // ── Dock ──────────────────────────────────────────────────────────────────── + canAct() { return this.mode === 'human' && !this.modal && !this.paused && this.gs?.currentPlayer === 0 && this.gs.phase === 'playing'; } - endCardDrag() { - const ds = this.dragState; - const card = this.localHandCards[ds.cardIdx]; - const hand = this.gs.players[0].hand; - const n = hand.length; - - // ── Play path: dropped on the play zone ─────────────────────────────────── - if (ds.overPlayZone) { - const handCard = hand[ds.cardIdx]; - this.tweens.killTweensOf(card); - card.setScale(1); - card.setRotation(0); - this.dragState = null; - this.playHuman(handCard.id); + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const look = [ + { label: 'Last trick (L)', act: () => this.openLastTrick(), enabled: !!gs.lastTrick }, + { label: 'Cards gone (G)', act: () => this.openTracker() }, + ]; + if (this.mode === 'deal') { this.setDock('Dealing…'); return; } + if (this.mode === 'passing') { + const target = passTargetSeat(0, gs.passDirection); + const n = this.passSel.size; + this.setDock(`Choose 3 cards to pass ${DIR_NAME[gs.passDirection]} to ${this.shortName(target)} (${n}/3).`, [ + { label: 'Pass (Enter)', act: () => this.submitPass(), enabled: n === PASS_COUNT, hot: n === PASS_COUNT }, + { label: 'Suggest (A)', act: () => this.suggestPassPick() }, + { label: 'Clear', act: () => { this.passSel.clear(); this.layout(); this.updateDock(); }, enabled: n > 0 }, + ]); return; } - - // ── Reorder path: dropped back in hand ──────────────────────────────────── - const movedCardId = hand[ds.cardIdx].id; - const finalIdx = Phaser.Math.Clamp(Math.round((card.x - ds.handStartX) / HAND_SPREAD), 0, n - 1); - const isSelected = this.gs.phase === 'passing' && this.passSelection.has(movedCardId); - const finalY = ds.handCenterY - (isSelected ? 26 : 0); - - this.tweens.killTweensOf(card); - this.tweens.add({ targets: card, x: ds.handStartX + finalIdx * HAND_SPREAD, y: finalY, rotation: 0, scaleX: 1, scaleY: 1, duration: 220, ease: 'Back.easeOut' }); - - const others = []; - for (let i = 0; i < n; i++) { if (i !== ds.cardIdx) others.push(i); } - for (let k = 0; k < others.length; k++) { - const j = others[k]; - const finalPos = k < finalIdx ? k : k + 1; - const otherIsSelected = this.gs.phase === 'passing' && this.passSelection.has(hand[j].id); - const cardObj = this.localHandCards[j]; - this.tweens.killTweensOf(cardObj); - this.tweens.add({ targets: cardObj, x: ds.handStartX + finalPos * HAND_SPREAD, y: ds.handCenterY - (otherIsSelected ? 26 : 0), rotation: 0, scaleX: 1, scaleY: 1, duration: 120, ease: 'Cubic.easeOut' }); + if (this.mode === 'ending' || this.mode === 'summary') { this.setDock('Hand over — counting points.'); return; } + if (this.mode === 'human') { + const lead = gs.trick.length === 0; + let prompt; + if (gs.trickNumber === 0 && lead) prompt = 'You hold the 2♣ — lead it to start.'; + else if (lead) prompt = gs.heartsBroken ? 'Your lead.' : 'Your lead — hearts aren\'t broken yet.'; + else { + const has = gs.players[0].hand.some(c => c.suit === gs.leadSuit); + prompt = has ? `Follow ${SUIT_SYM[gs.leadSuit]} ${SUIT_NAME[gs.leadSuit]}.` : `No ${SUIT_NAME[gs.leadSuit]} — play anything${gs.trickNumber === 0 ? ' (no points on the first trick)' : ''}.`; + } + this.setDock(prompt, look); + return; } + const t = this.holdTrick; + if (t) { this.setDock(`${this.nameForSeat(t.winnerSeat)} takes the trick${t.points ? ` (+${t.points})` : ''}.`, look); return; } + this.setDock(`${this.nameForSeat(gs.currentPlayer)} is playing…`, look); + } - const [moved] = hand.splice(ds.cardIdx, 1); - hand.splice(finalIdx, 0, moved); - const [movedCard] = this.localHandCards.splice(ds.cardIdx, 1); - this.localHandCards.splice(finalIdx, 0, movedCard); + // ── Human actions ─────────────────────────────────────────────────────────── + sortHand() { + if (!this.gs || this.settings.sort === 'manual') return; + this.gs.players[0].hand.sort(this.settings.sort === 'rank' ? byRank : bySuit); + } + togglePass(id) { + if (this.passSel.has(id)) this.passSel.delete(id); + else if (this.passSel.size < PASS_COUNT) this.passSel.add(id); + else { this.nudge(id); return; } + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + this.updateDock(); + } + + suggestPassPick() { + if (this.mode !== 'passing') return; + this.passSel = new Set(suggestPass(this.gs, 0)); + this.layout({ duration: 200 }); + this.updateDock(); + } + + play(id) { + if (!this.canAct()) return false; + const next = playCard(this.gs, id); + if (next === this.gs) { + this.nudge(id); + const gs = this.gs; + const card = gs.players[0].hand.find(c => c.id === id); + let why = 'Not allowed'; + if (gs.trickNumber === 0 && gs.trick.length === 0) why = 'Lead the 2♣'; + else if (gs.trick.length && card?.suit !== gs.leadSuit && gs.players[0].hand.some(c => c.suit === gs.leadSuit)) why = `Follow ${SUIT_NAME[gs.leadSuit]}`; + else if (gs.trick.length === 0 && card?.suit === 'h' && !gs.heartsBroken) why = 'Hearts aren\'t broken yet'; + else if (gs.trickNumber === 0) why = 'No points on the first trick'; + this.floatText({ x: CX, y: 870 }, why, '#ff9a7a', { size: 20 }); + return false; + } + this.received.clear(); + this.mode = 'idle'; + playSound(this, SFX.CARD_PLACE); + const done = next.trickNumber !== this.gs.trickNumber || next.phase !== 'playing'; + const p = this.commit(next); + if (!done) p.then(() => this.time.delayedCall(220, () => this.advance())); + return true; + } + + // ── 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); } + + liftFor(ids) { + const legal = this.mode === 'human' && this.settings.hints ? new Set(legalPlays(this.gs, 0).map(c => c.id)) : null; + return (i) => (this.passSel.has(ids[i]) ? 44 : ids[i] === this.hoverId ? 24 : legal?.has(ids[i]) ? 8 : 0); + } + + handIdAt(pt) { + const ids = this.heldIds(); + const i = fanHit(L.seats[0].fan, ids.length, pt, this.liftFor(ids)); + return i >= 0 ? ids[i] : null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState || this.overUI(over)) 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; + } + if (pointer.isDown || this.modal || !this.gs || this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const id = this.handIdAt(pointer); + if (id !== this.hoverId) { this.hoverId = id; this.layout({ duration: 120 }); } + this.input.setDefaultCursor(id != null ? 'pointer' : 'default'); + } + + onPointerUp() { + if (this.dragState) { this.endDrag(); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + if (this.mode === 'passing') { this.togglePass(pd.id); return; } + if (!this.canAct()) { + if (this.mode === 'ai') this.floatText({ x: CX, y: 870 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); + return; + } + this.play(pd.id); + } + + 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); + } + + dropTargetAt(pt) { + if (this.mode === 'human' && inPose(pt, trickPose(0), 60)) return { type: 'play' }; + const ids = this.heldIds(); + if (inRect(pt, fanZone(L.seats[0].fan, ids.length))) return { type: 'hand', at: fanInsertIndex(L.seats[0].fan, ids.length, pt.x) }; + return null; + } + + updateDrag(pointer) { + const ds = this.dragState; + const x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const t = Math.max(0, Math.min(1, (y - 600) / 360)); + this.applyPose(ds.sprite, { x, y, rot: 0, s: 0.84 + 0.16 * t, q: SQ + (1 - SQ) * t }, 1); + ds.target = this.dropTargetAt(pointer); + const order = ds.target?.type === 'hand' ? CardTableScene.reorderPreview(this.heldIds(), 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(0, idx, order.length), D.hand + idx * 0.01 - 0.004); + } else this.drawDropSlot(null); + } + + cancelDrag() { + if (!this.dragState) return; this.dragState = null; - this.time.delayedCall(240, () => { if (!this.dragState) this.renderHands(); }); + this.dragPreview = null; + this.drawDropSlot(null); + this.layout(); } - tweenTo(target, x, y, duration) { - return new Promise((resolve) => this.tweens.add({ targets: target, x, y, duration, ease: 'Cubic.easeOut', onComplete: resolve })); + endDrag() { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.drawDropSlot(null); + const t = ds.target; + this.dragPreview = null; + if (t?.type === 'hand') { + const order = CardTableScene.reorderPreview(this.heldIds(), ds.id, t.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(); + return; + } + if (t?.type === 'play' && this.play(ds.id)) return; + this.layout(); } - delay(ms) { - return new Promise((resolve) => this.time.delayedCall(ms, resolve)); + 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 (k === 'l') { if (this.gs?.lastTrick) this.openLastTrick(); return; } + if (k === 'g') { this.openTracker(); return; } + if (k === 's') { this.cycleSort(); return; } + if (k === 'h') { this.flashHint(); return; } + if (this.mode === 'passing') { + if (e.code === 'Enter') this.submitPass(); + else if (k === 'a') this.suggestPassPick(); + } + } + + cycleSort() { + const order = ['suit', 'rank', 'manual']; + this.settings.sort = order[(order.indexOf(this.settings.sort) + 1) % order.length]; + this.saveSettings(); + this.refreshSortButtons(); + this.sortHand(); + this.layout(); + } + + flashHint() { + if (!this.gs) return; + if (this.mode === 'passing') { + const ids = suggestPass(this.gs, 0); + this.floatText({ x: CX, y: 870 }, 'Pass your most dangerous cards: Q♠, A♠ K♠, high hearts, short suits', '#7cf0a0', { size: 20, ms: 2400, rise: 20 }); + for (const id of ids) this.flashGlow(id, 0x7cf0a0, { delay: 0, hold: 900 }); + return; + } + if (this.mode !== 'human') return; + const id = suggestPlay(this.gs, 0); + const c = this.gs.players[0].hand.find(h => h.id === id); + if (!c) return; + this.floatText({ x: CX, y: 870 }, `Try the ${c.label}${SUIT_SYM[c.suit]}`, '#7cf0a0', { size: 22, ms: 2000, rise: 20 }); + this.flashGlow(id, 0x7cf0a0, { delay: 0, hold: 900 }); + } + + // ── Panels ────────────────────────────────────────────────────────────────── + openLastTrick() { + const t = this.gs?.lastTrick; + if (!t || this.modal) return; + const h = 380; + this.openModal({ w: 760, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 46, `Last trick — ${this.nameForSeat(t.winnerSeat)} took it${t.points ? ` (+${t.points})` : ''}`, { fontFamily: 'Righteous', fontSize: '26px', color: COLORS.goldHex }); + t.plays.forEach((p, i) => { + const x = CX - 255 + i * 170, y = CY + 4; + const img = this.addToModal(this.add.image(x, y, 'casino-cards', p.card.key).setScale(0.62).setDepth(D.modal + 2)); + if (p.seat === t.winnerSeat) { + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.lineStyle(4, 0xffd35a, 1); + g.strokeRoundedRect(x - img.displayWidth / 2 - 6, y - img.displayHeight / 2 - 6, img.displayWidth + 12, img.displayHeight + 12, 10); + } + this.modalText(x, y + 104, `${i === 0 ? 'Led: ' : ''}${this.shortName(p.seat, 12)}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: SEAT_HEX[p.seat] }); + }); + this.modalButton(CX, top + h - 40, 'Back', () => this.closeModal(), { width: 180, height: 42, fontSize: 18 }); + } + + // Which cards are gone, which are still out, and who has shown out of what. + openTracker() { + if (!this.gs || this.modal) return; + const played = playedKeys(this.gs); + const mine = new Set(this.gs.players[0].hand.map(c => c.key)); + const h = 520; + this.openModal({ w: 900, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 44, 'Cards gone this hand', { fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex }); + this.modalText(CX, top + 78, 'dim = played · gold = in your hand · bright = still out there', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex }); + ['c', 'd', 's', 'h'].forEach((suit, r) => { + const y = top + 128 + r * 58; + this.addToModal(this.add.text(CX - 400, y, SUIT_SYM[suit], { + fontFamily: 'sans-serif', fontSize: '34px', color: suit === 'h' || suit === 'd' ? '#ff6a6a' : '#f2ead8', + }).setOrigin(0.5).setDepth(D.modal + 1)); + RANKS.forEach((rank, i) => { + const key = `${rank}${suit}`; + const gone = played.has(key); + const held = mine.has(key); + this.addToModal(this.add.text(CX - 340 + i * 56, y, rank === 'T' ? '10' : rank, { + fontFamily: 'Righteous', fontSize: '24px', + color: held ? '#ffd35a' : gone ? '#5a5048' : '#f2ead8', + }).setOrigin(0.5).setDepth(D.modal + 1).setAlpha(gone ? 0.6 : 1)); + if (gone) { + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 2)); + g.lineStyle(2, 0x8a7e66, 0.7); + g.beginPath(); g.moveTo(CX - 356 + i * 56, y + 2); g.lineTo(CX - 324 + i * 56, y - 2); g.strokePath(); + } + }); + }); + const voids = knownVoids(this.gs); + const lines = [1, 2, 3].map(s => (voids[s].size ? `${this.shortName(s, 12)}: out of ${[...voids[s]].map(x => SUIT_SYM[x]).join(' ')}` : null)).filter(Boolean); + this.modalText(CX, top + 380, lines.length ? `Shown out — ${lines.join(' · ')}` : 'Nobody has shown out of a suit yet.', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex }); + this.modalText(CX, top + 412, played.has('Qs') ? 'The Queen of Spades has been played.' : 'The Queen of Spades is still out.', { fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#c9a0ff' }); + this.modalButton(CX, top + h - 44, 'Back to the table', () => this.closeModal(), { width: 260, height: 44, fontSize: 18 }); + } + + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Score sheet', 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 match will be thrown out.', 'New game', () => this.restart()) }, + { label: 'Leave table', 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: 'Hints (★ suggestion · dim unplayable)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; this.layout(); } }, + { label: 'Play to', options: [[50, '50'], [100, '100']], get: () => s.target, set: (v) => { s.target = v; } }, + { label: 'Shooting the moon', options: [['add', 'Others +26'], ['subtract', 'Me −26']], get: () => s.moon, set: (v) => { s.moon = v; } }, + { label: 'Hand order', options: [['suit', 'Suit'], ['rank', 'Rank'], ['manual', 'Mine']], get: () => s.sort, set: (v) => { s.sort = v; this.refreshSortButtons(); this.sortHand(); this.layout(); } }, + ], { note: '"Play to" and the moon rule start with the next match.', onDone }); + } + + openRules() { + const h = 620; + this.openModal({ w: 920, 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 = [ + 'Avoid points: every heart is 1, the Queen of Spades is 13.', + 'Each hand, pass 3 cards — left, right, across, then no pass, in turn.', + 'Whoever holds the 2♣ leads it. Follow suit if you can; otherwise play anything.', + 'Highest card of the suit that was led wins the trick and leads next.', + 'Hearts can\'t be led until one has been played (unless that\'s all you have).', + 'No points on the very first trick.', + 'Shoot the moon: take every heart AND the Queen — everyone else gets 26.', + `When someone reaches ${this.gs?.target ?? 100}, the lowest score wins.`, + ]; + lines.forEach((l, i) => this.addToModal(this.add.text(CX - 420, top + 122 + i * 44, 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 inMatch = this.history.length > 0 || this.mode === 'human' || this.mode === 'ai' || this.mode === 'passing'; + if (!inMatch || this.gs?.phase === 'gameOver') { this.scene.start('GameMenu'); return; } + this.confirm('Leave this match?', 'Your progress 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 = null, readOnly = false } = {}) { + if (!this.gs) return; + const gs = this.gs; + const over = gs.phase === 'gameOver' && !readOnly; + const totals = gs.players.map(p => p.totalScore); + const best = Math.min(...totals); + let title; + if (readOnly) title = `Score sheet — to ${gs.target}, lowest wins`; + else if (over) title = gs.winnerSeats.includes(0) ? (gs.winnerSeats.length > 1 ? 'You share the win!' : 'You win the match!') : `${gs.winnerSeats.map(s => this.nameForSeat(s)).join(' & ')} win${gs.winnerSeats.length > 1 ? '' : 's'}`; + else if (gs.moonShooter != null) title = gs.moonShooter === 0 ? 'You shot the moon!' : `${this.nameForSeat(gs.moonShooter)} shot the moon!`; + else title = `Hand ${gs.handNumber + 1} scored`; + const rows = gs.players.map((p, s) => ({ + seat: s, color: SEAT_COLORS[s], name: this.shortName(s, 14), + cells: this.history.map(hh => { + const v = hh.scores[s]; + return { text: v > 0 ? `+${v}` : String(v), color: v > 0 ? '#b8231f' : '#1e7a3b', mark: hh.moon === s ? '☾' : hh.queen === s ? 'Q♠' : '', markColor: '#5a3a8a' }; + }), + total: p.totalScore, + totalColor: p.totalScore === best ? '#1e7a3b' : '#22201a', + circled: over && gs.winnerSeats.includes(s), + })); + const buttons = []; + if (readOnly) buttons.push({ label: 'Back to the table', act: () => this.closeModal() }); + else { + buttons.push(over ? { label: 'Play again', act: () => this.restart(), hot: true } : { label: 'Next hand', act: () => this.nextHand(), hot: true }); + buttons.push({ label: 'Settings', ghost: true, act: () => { this.closeModal(); this.openSettings(() => this.openScorePad({ result })); } }); + buttons.push({ label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }); + } + this.openScorePadModal({ + title, titleColor: over && gs.winnerSeats.includes(0) ? '#1e7a3b' : '#22201a', + sub: 'Points are bad — hearts 1 each, the Queen of Spades 13', + columns: this.history.map((_, i) => `H${i + 1}`), + rows, writeLast: !!result, buttons, readOnly, + onEnter: !readOnly ? (over ? () => this.restart() : () => this.nextHand()) : null, + }); + } + + async nextHand() { + this.closeModal(); + if (this.mode !== 'summary' || this.gs.phase !== 'handOver') return; + this.mode = 'deal'; + this.updateDock(); + await this.sweepCards(T.flat(0, 0.45, 0.9)); + if (!this.alive()) return; + this.gs = startNextHand(this.gs); + this.startHand(); + } + + // ── End of hand ───────────────────────────────────────────────────────────── + async onHandOver() { + if (this.mode === 'ending' || this.mode === 'summary') return; + this.mode = 'ending'; + this.turnToken++; + this.cancelDrag(); + this.potentialDrag = null; + this.input.setDefaultCursor('default'); + this.updateDock(); + const gs = this.gs; + const scores = gs.handScores; + await this.wait(400); + if (!this.alive()) return; + if (gs.moonShooter != null) { + const s = gs.moonShooter; + this.stamp(s === 0 ? 'You shot the moon!' : `${this.shortName(s, 14)} shot the moon!`, { x: CX, y: CY - 40 }, '#ffd35a', { size: 72, hold: 1500 }); + this.plateStamp(s, 'MOON!', '#ffd35a', 2000); + for (let i = 0; i < 4; i++) this.time.delayedCall(i * 180, () => this.burst({ x: CX + (i - 1.5) * 140, y: CY - 40 }, 0xff6a6a, { n: 10, r: 110 })); + playSound(this, SFX.CASINO_WIN); + this.portraits[s]?.playEmotion?.('happy'); + await this.wait(1800); + } + // each player's points this hand float up from their plate + for (let s = 0; s < 4; s++) { + const pl = this.plates[s]; + const v = scores[s]; + this.floatText({ x: pl.x, y: pl.y + (s === 0 ? -70 : 70) }, v > 0 ? `+${v}` : v < 0 ? `${v}` : 'clean!', v > 0 ? '#ff8a7a' : '#8ce99a', { size: 30, ms: 1800, rise: 30 }); + } + playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.5 }); + await this.wait(1400); + if (!this.alive()) return; + const queen = gs.players.findIndex(p => p.wonCards.some(isQueenOfSpades)); + this.history.push({ scores: scores.slice(), moon: gs.moonShooter, queen }); + this.updatePlates(); + if (gs.phase === 'gameOver') { + const won = gs.winnerSeats.includes(0); + this.recordResult('hearts', { score: gs.players[0].totalScore, opponentScores: gs.players.slice(1).map(p => p.totalScore), won }); + playSound(this, won ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < 4; s++) this.portraits[s]?.playEmotion?.(gs.winnerSeats.includes(s) ? 'win' : 'loss'); + } + this.mode = 'summary'; + this.openScorePad({ result: true }); } } + +export { CARD_W, CARD_H, SUITS }; diff --git a/src/games/hearts/HeartsLogic.js b/src/games/hearts/HeartsLogic.js index af5832f..9d96fd2 100644 --- a/src/games/hearts/HeartsLogic.js +++ b/src/games/hearts/HeartsLogic.js @@ -14,7 +14,11 @@ // - Scoring: each heart = 1 pt, Q♠ = 13 pts (26 per hand). // - Shooting the moon: if one player takes all 26 points, they score 0 and // every other player gets +26. -// - Match runs until any player's total reaches 100; lowest total wins. +// - Match runs until any player's total reaches the target (default 100); +// lowest total wins. +// +// Options (createInitialState): target (50 / 100), moonMode 'add' (everyone +// else +26, the classic) or 'subtract' (the shooter −26 instead). import { SUITS, RANKS, Card } from '../cards/Deck.js'; @@ -103,6 +107,9 @@ export function cloneState(state) { winnerSeats: state.winnerSeats.slice(), seed: state.seed, log: state.log.map((e) => ({ ...e })), + target: state.target, + moonMode: state.moonMode, + _rand: state._rand, }; } @@ -133,6 +140,7 @@ function dealHand(state, rand) { state.lastTrick = null; state.handScores = null; state.moonShooter = null; + state.log.push({ kind: 'deal', hand: state.handNumber, direction: state.passDirection }); if (state.passDirection === 'hold') { // No passing this hand — go straight to play. @@ -144,7 +152,7 @@ function dealHand(state, rand) { } } -export function createInitialState({ seed } = {}) { +export function createInitialState({ seed, target = GAME_OVER_SCORE, moonMode = 'add' } = {}) { const rand = seed === undefined ? Math.random : rng(seed); const players = []; for (let i = 0; i < PLAYER_COUNT; i++) { @@ -169,6 +177,8 @@ export function createInitialState({ seed } = {}) { seed: seed ?? null, log: [], _rand: rand, + target, + moonMode, }; dealHand(state, rand); return state; @@ -285,8 +295,12 @@ export function playCard(state, cardId) { if (next.trick.length === 0) next.leadSuit = card.suit; next.trick.push({ seat, card }); - if (card.suit === 'h') next.heartsBroken = true; + if (card.suit === 'h' && !next.heartsBroken) { + next.heartsBroken = true; + next.log.push({ kind: 'heartsBroken', seat }); + } next.log.push({ kind: 'play', seat, card: { rank: card.rank, suit: card.suit }, leadSuit: next.leadSuit }); + if (isQueenOfSpades(card)) next.log.push({ kind: 'queen', seat }); if (next.trick.length < PLAYER_COUNT) { next.currentPlayer = (seat + 1) % PLAYER_COUNT; @@ -335,10 +349,12 @@ function scoreHand(state) { const applied = roundPoints.slice(); if (shooter !== -1) { - // Shoot the moon: shooter scores 0, everyone else +26. + // Shoot the moon: shooter scores 0 and everyone else +26 — or, with the + // 'subtract' option, the shooter −26 and everyone else 0. state.moonShooter = shooter; for (let seat = 0; seat < PLAYER_COUNT; seat++) { - applied[seat] = seat === shooter ? 0 : MAX_POINTS; + if (state.moonMode === 'subtract') applied[seat] = seat === shooter ? -MAX_POINTS : 0; + else applied[seat] = seat === shooter ? 0 : MAX_POINTS; } } else { state.moonShooter = null; @@ -350,7 +366,7 @@ function scoreHand(state) { state.handScores = applied; state.log.push({ kind: 'handScored', applied, shooter }); - const reached = state.players.some((p) => p.totalScore >= GAME_OVER_SCORE); + const reached = state.players.some((p) => p.totalScore >= (state.target ?? GAME_OVER_SCORE)); if (reached) { state.phase = 'gameOver'; const min = Math.min(...state.players.map((p) => p.totalScore)); @@ -373,6 +389,33 @@ export function startNextHand(state) { return next; } +/** Log entries for the hand in progress (since its deal). */ +export function handLog(state) { + for (let i = state.log.length - 1; i >= 0; i--) if (state.log[i].kind === 'deal') return state.log.slice(i); + return state.log; +} + +/** Card keys ('Qs', '7h', …) already played this hand, including the open trick. */ +export function playedKeys(state) { + const out = new Set(); + for (const e of handLog(state)) if (e.kind === 'play') out.add(`${e.card.rank}${e.card.suit}`); + return out; +} + +/** voids[seat] = set of suits that seat has shown out of this hand. */ +export function knownVoids(state) { + const voids = state.players.map(() => new Set()); + for (const e of handLog(state)) { + if (e.kind === 'play' && e.leadSuit && e.card.suit !== e.leadSuit) voids[e.seat].add(e.leadSuit); + } + return voids; +} + +/** Points each seat has taken so far this hand. */ +export function pointsTaken(state) { + return state.players.map((p) => p.roundPoints); +} + export function isGameOver(state) { return state.phase === 'gameOver'; } diff --git a/src/games/hearts/HeartsTable.js b/src/games/hearts/HeartsTable.js new file mode 100644 index 0000000..4f244b4 --- /dev/null +++ b/src/games/hearts/HeartsTable.js @@ -0,0 +1,92 @@ +// Hearts table layout — Phaser-free so tools/verifyHearts.js can test it. +// +// A leather-topped card table in a firelit den, on the shared card-table kit. +// Always four players: human (bottom) · left · across · right (logic seats +// clockwise from the human's left, so "pass left" = seat + 1). +// +// Each seat has a hand fan, a spot in the middle where its trick card lands, +// and a "won" area: a face-down stack of the tricks it has taken plus a +// face-up row of the point cards (hearts, Q♠) among them — so everyone's +// points this hand are visible at a glance. + +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: 'rect', corner: 0.17, feltK: 0.94, faceH: 36 }); +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) => ({ x, y, rot, k, spread: 34, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 520, maxDrop: 14, maxTilt: 0.16 }); + +export const SEATS = [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE, trick: { u: 0, v: 0.6 }, tricks: { u: 0.36, v: 0.74 }, points: { u: 0.45, v: 0.74, dir: 1 } }, + { fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 }, trick: { u: -0.17, v: 0.46 }, tricks: { u: -0.62, v: 0.28 }, points: { u: -0.53, v: 0.28, dir: 1 } }, + { fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 }, trick: { u: 0, v: 0.3 }, tricks: { u: 0.3, v: 0.17 }, points: { u: 0.39, v: 0.17, dir: 1 } }, + { fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 }, trick: { u: 0.17, v: 0.46 }, tricks: { u: 0.62, v: 0.28 }, points: { u: 0.53, v: 0.28, dir: -1 } }, +]; + +export const TRICK_K = 0.95; +export const WON_K = 0.44; +const POINT_STEP = 19; // px between overlapped point cards (at s = 1) + +export function layout() { + return { seats: SEATS.map((d, seat) => ({ seat, ...d })) }; +} +export const L = layout(); + +export const handPose = (seat, i, n, lift = 0) => fanPose(SEATS[seat].fan, i, n, lift); + +/** Where `seat`'s card lands in the trick (slightly turned, readable from your chair). */ +export function trickPose(seat) { + const t = SEATS[seat].trick; + const tilt = [0.02, -0.12, 0.05, 0.12][seat]; + return T.flat(t.u, t.v, TRICK_K, tilt); +} + +/** Top of `seat`'s face-down won-tricks stack (n cards). */ +export function tricksPose(seat, n = 1) { + const t = SEATS[seat].tricks; + const p = T.flat(t.u, t.v, WON_K, 0.06 * (seat % 2 ? -1 : 1)); + return { ...p, y: p.y - Math.min(8, Math.max(0, n - 1) * 0.18) }; +} + +/** Point card i of n in `seat`'s face-up row. */ +export function pointPose(seat, i) { + const t = SEATS[seat].points; + const base = T.flat(t.u, t.v, WON_K); + return { ...base, x: base.x + t.dir * i * POINT_STEP * (base.s / WON_K) }; +} + +/** Screen rect a seat's point row covers when it holds `n` cards. */ +export function pointRowRect(seat, n) { + const a = pointPose(seat, 0), b = pointPose(seat, Math.max(0, n - 1)); + const hw = (CARD_W / 2) * a.s, hh = (CARD_H / 2) * a.s * SQ; + return { x0: Math.min(a.x, b.x) - hw, x1: Math.max(a.x, b.x) + hw, y0: a.y - hh, y1: a.y + hh }; +} + +export function handHome(seat) { + const f = SEATS[seat].fan; + const p = fanPoint(f, 0, -CARD_H * 0.95); + return { ...p, rot: f.rot, k: f.k }; +} + +export function handBadge(seat) { + const f = SEATS[seat].fan; + return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 50), 0); +} + +export function spotFor(seat) { + const f = 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 }; +} + +/** Where the pass arrow sits (the middle of the table). */ +export const CENTRE = T.P.project(0, 0.45); + +export { PLATE }; diff --git a/src/scenes/OpponentSelectScene.js b/src/scenes/OpponentSelectScene.js index 45bd281..69ea6a0 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', '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', '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/src/ui/cardtable/CardTableScene.js b/src/ui/cardtable/CardTableScene.js index 948be1e..e905cca 100644 --- a/src/ui/cardtable/CardTableScene.js +++ b/src/ui/cardtable/CardTableScene.js @@ -20,7 +20,8 @@ import { // Fish and Old Maid next). Extracted from Phase 10 / Nerts. // // A game subclass provides: -// faceFrame(card) → { key, frame } texture for a face-up card +// faceFrame(card) → { key, frame, sized? } texture for a face-up card +// (sized: true → scaled to the card, for custom sheets) // computeLayout() → { visible: Map(id → view), loc: Map(id → {pose,faceUp,depth}) } // view = { card, pose, faceUp, depth, kind, … } // decorate(c, view) (optional) hint marks / chips / glow per card @@ -143,7 +144,10 @@ export class CardTableScene extends Phaser.Scene { c.faceUp = faceUp; if (faceUp) { const f = this.faceFrame(c.card); - c.faceImg.setTexture(f.key, f.frame).setScale(0.5); + c.faceImg.setTexture(f.key, f.frame); + // custom sheets (e.g. Go Fish's own illustrated faces) are sized to the + // card; baked 2× atlases just halve + if (f.sized) c.faceImg.setDisplaySize(CARD_W, CARD_H); else c.faceImg.setScale(0.5); } else { const b = this.backFrame(); c.faceImg.setTexture(b.key, b.frame); diff --git a/tools/verifyGoFish.js b/tools/verifyGoFish.js new file mode 100644 index 0000000..4800a5b --- /dev/null +++ b/tools/verifyGoFish.js @@ -0,0 +1,251 @@ +#!/usr/bin/env node +// verifyGoFish.js — headless checks for Go Fish: rules (deal, asks, catches, +// go fish + lucky draws, books AND pairs, refills, sitting out, game end), the +// memory AI (always legal, skill-scaled recall), the dock layout for 2/3/4 +// players (pond, book rows, hands, HUD all clear), and an all-AI soak (every +// game ends, 52 cards conserved, better memory wins more). +// Usage: node tools/verifyGoFish.js [--quick] + +import * as G from '../src/games/gofish/GoFishLogic.js'; +import { Card } from '../src/games/cards/Deck.js'; +import { createMemory, observeLog, chooseAction, RECALL, caughtFromThisTurn } from '../src/games/gofish/GoFishAI.js'; +import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + CARD_W, CARD_H, cardBounds, cardCorners, fanHit, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, inRect, unionRect, +} from '../src/ui/cardtable/TableGeometry.js'; +import { + T, layoutFor, handPose, poolPose, pondOutline, inPond, bookPose, bookRowRect, handBadge, handHome, bubbleAt, seatTargetRect, POND, showPose, +} from '../src/games/gofish/GoFishTable.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 = 900; +const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++ }); + +function rig(hands, { matchSize = 4, pool = ['9s', '9h', 'Kd', '2c', '3c'], current = 0 } = {}) { + const gs = G.createInitialState({ playerCount: hands.length, matchSize, seed: 3 }); + gs.players.forEach((p, s) => { p.hand = hands[s].map(C); p.books = []; p.pairs = 0; p.pairedRanks = []; p.sittingOut = false; }); + gs.pool = pool.map(C); + gs.currentPlayer = current; + gs.phase = 'play'; + gs.log = []; + return gs; +} + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +for (const n of [2, 3, 4]) for (const m of [2, 4]) { + const gs = G.createInitialState({ playerCount: n, matchSize: m, seed: 10 + n + m }); + ok(`${n}p ${m === 4 ? 'books' : 'pairs'}: 52 conserved`, G.countCards(gs) === 52); + ok(`${n}p ${m === 4 ? 'books' : 'pairs'}: dealt 7 (minus deal books)`, gs.players.every(p => p.hand.length + p.books.flat().length === 7 || p.hand.length > 0)); +} +{ + const gs = rig([['7s', '7h', '2d'], ['7d', '7c', 'Kh']]); + ok('cannot ask for a rank you lack', G.applyAsk(gs, 1, 'K') === gs); + ok('cannot ask yourself', G.applyAsk(gs, 0, '7') === gs); + const c = G.applyAsk(gs, 1, '7'); + ok('catch takes every card of the rank', c.lastAsk.result === 'catch' && c.lastAsk.cardsTransferred.length === 2); + ok('four of a kind makes a book', c.players[0].pairs === 1 && c.players[0].books[0].length === 4 && c.players[0].hand.length === 1); + ok('book logged', c.log.some(e => e.kind === 'pair' && e.rank === '7')); + ok('catch: asker goes again', c.currentPlayer === 0); + ok('52 conserved after a catch', G.countCards({ ...c, pool: c.pool }) === G.countCards(gs)); +} +{ + const gs = rig([['7s', '2d'], ['Kd', 'Kh']], { pool: ['3c', '7h'] }); + const f = G.applyAsk(gs, 1, '7'); + ok('miss → go fish (pick phase)', f.phase === 'pick' && f.lastAsk.result === 'fish'); + const lucky = G.applyFishPick(f, f.pool.find(c => c.rank === '7').id); + ok('fishing up the asked rank is lucky: go again', lucky.lastAsk.result === 'lucky' && lucky.currentPlayer === 0); + const plain = G.applyFishPick(f, f.pool.find(c => c.rank === '3').id); + ok('otherwise the turn passes', plain.lastAsk.result === 'fish' && plain.currentPlayer === 1); +} +{ + const gs = rig([['7s', '2d'], ['7d', 'Kh']], { matchSize: 2 }); + const c = G.applyAsk(gs, 1, '7'); + ok('pairs mode: two make a pair', c.players[0].pairs === 1 && c.players[0].books[0].length === 2); + const empty = rig([['7s'], ['7d']], { matchSize: 2, pool: ['2c', '3c', '4c', '5c', '6c', '8c', '9c', 'Tc', 'Jc', 'Qc'] }); + const e = G.applyAsk(empty, 1, '7'); + ok('emptied hands refill to five', e.players[0].hand.length === 5 && e.players[1].hand.length === 5); + const out = rig([['7s'], ['7d']], { matchSize: 2, pool: [] }); + const o = G.applyAsk(out, 1, '7'); + ok('no cards and an empty pond → game over', G.isGameOver(o)); +} +{ + // a full game always conserves cards + const gs = G.createInitialState({ playerCount: 3, matchSize: 4, seed: 99 }); + ok('countCards', G.countCards(gs) === 52); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry); + ok('recall rises with skill', RECALL[1] < RECALL[3] && RECALL[3] < RECALL[5] && RECALL[5] === 1); + const gs = rig([['7s', '2d'], ['Kd', 'Kh'], ['Qs', '9d']], { current: 1 }); + let g = G.applyAsk(gs, 0, 'K'); // seat 1 asks the human for kings: go fish + g = G.applyFishPick(g, g.pool[0].id); + const mem = createMemory(3, { skill: 5, matchSize: 4, rng: () => 0.5 }); + observeLog(mem, g, 2); + ok('perfect memory: seat 1 holds kings', mem.beliefs[1].K >= 1); + g.currentPlayer = 2; + g.players[2].hand.push(C('Kc')); + const a = chooseAction(g, 2, mem); + ok('asks the player who showed the rank', a && a.targetSeat === 1 && a.rank === 'K'); + // after a catch, the asker won't go back to the same player this turn + const t3 = rig([['7s', '9d', 'Qh'], ['7d', 'Kh'], ['9s', 'Qc'], ['2c', '3d']], { current: 0 }); + const caught = G.applyAsk(t3, 1, '7'); + ok('catch noted for this turn', caughtFromThisTurn(caught, 0).has(1) && caught.currentPlayer === 0); + let againOk = true; + for (const sk of [1, 2, 3, 4, 5]) for (let k = 0; k < 20; k++) { + const m = createMemory(4, { skill: sk, matchSize: 4, rng: mulberry32(k * 31 + sk) }); + observeLog(m, caught, 0); + const a = chooseAction(caught, 0, m); + if (!a || a.targetSeat === 1) againOk = false; + } + ok('no skill asks the same player twice in one turn', againOk); + const nextTurn = G.applyAsk(caught, 2, '7'); // a different player's ask ends the run + nextTurn.currentPlayer = 1; + ok('the rule resets on the next turn', caughtFromThisTurn({ ...nextTurn, log: [...nextTurn.log, { kind: 'ask', askerSeat: 3, targetSeat: 0, rank: '2', result: 'fish' }] }, 0).size === 0); + const heads = rig([['7s', '9d'], ['7d', '9h', 'Kh']], { current: 0 }); + const h1 = G.applyAsk(heads, 1, '7'); + const hm = createMemory(2, { skill: 5, matchSize: 4, rng: () => 0.5 }); + observeLog(hm, h1, 0); + const ha = chooseAction(h1, 0, hm); + ok('heads-up: the only opponent can still be asked again', ha && ha.targetSeat === 1); + const forgetful = createMemory(3, { skill: 1, matchSize: 4, rng: () => 0.99 }); + observeLog(forgetful, g, 2); + ok('skill 1 can miss what it saw', (forgetful.beliefs[1].K || 0) === 0); +} + +// ── 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 pond = pondOutline(1.07); + const pondBox = { x0: Math.min(...pond.map(p => p.x)), x1: Math.max(...pond.map(p => p.x)), y0: Math.min(...pond.map(p => p.y)) - 30, y1: Math.max(...pond.map(p => p.y)) + 34 }; + ok(`${n}p: pond on the dock`, pond.every(p => T.onFelt(p))); + let inside = true; + for (let id = 0; id < 52; id++) { const p = poolPose(id); if (!inPond(p)) inside = false; } + ok(`${n}p: every pool card floats inside the pond`, inside); + const rows = []; + for (let s = 0; s < n; s++) { + const row = bookRowRect(L, s, 13); + rows[s] = row; + ok(`${n}p seat ${s}: book row on the dock`, T.onFelt({ x: row.x0, y: row.y0 }) && T.onFelt({ x: row.x1, y: row.y1 }), JSON.stringify(row)); + ok(`${n}p seat ${s}: book row clear of the pond`, !rectsOverlap(row, pondBox), `${JSON.stringify(row)} vs ${JSON.stringify(pondBox)}`); + for (const f of furn) ok(`${n}p seat ${s}: book row clear of ${f.name}`, !rectsOverlap(row, f.r), `${JSON.stringify(row)} vs ${JSON.stringify(f.r)}`); + for (const cards of [1, 7, 15, 22]) { + const hb = fanBounds(L.seats[s].fan, cards, s === 0 ? 40 : 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 pond`, !rectsOverlap(hb, pondBox)); + for (let t = 0; t < n; t++) ok(`${n}p hand ${s} (${cards}) clear of book row ${t}`, !rectsOverlap(hb, bookRowRect(L, t, 13))); + } + 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 bb = bubbleAt(L, s); + ok(`${n}p seat ${s}: speech bubble on screen`, bb.x > 120 && bb.x < 1800 && bb.y > 40 && bb.y < 1000); + const tr = seatTargetRect(L, s, 7); + ok(`${n}p seat ${s}: ask target covers their hand`, inRect(handPose(L, s, 3, 7), tr)); + 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); + } + } + for (let s = 0; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p book rows ${s}/${t} apart`, !rectsOverlap(rows[s], rows[t])); + // show spots: up to 3 cards held up / laid out, clear of everything else + const shows = []; + for (let s = 0; s < n; s++) { + let r = null; + const corners = []; + for (let i = 0; i < 3; i++) { const p = showPose(L, s, i, 3); r = unionRect(r, cardBounds(p)); corners.push(...cardCorners(p)); } + shows[s] = r; + ok(`${n}p seat ${s}: show spot on screen`, onScreen(r)); + ok(`${n}p seat ${s}: show spot clear of the pond`, corners.every(p => !inPond(p))); + for (const f of furn) ok(`${n}p seat ${s}: show spot clear of ${f.name}`, !rectsOverlap(r, f.r), `${JSON.stringify(r)} vs ${JSON.stringify(f.r)}`); + for (let t = 0; t < n; t++) { + ok(`${n}p show ${s} clear of book row ${t}`, !rectsOverlap(r, rows[t]), `${JSON.stringify(r)} vs ${JSON.stringify(rows[t])}`); + ok(`${n}p show ${s} clear of hand ${t}`, !rectsOverlap(r, fanBounds(L.seats[t].fan, 15, t === 0 ? 40 : 0)), `${JSON.stringify(r)}`); + } + } + for (let s = 0; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p show spots ${s}/${t} apart`, !rectsOverlap(shows[s], shows[t])); + for (let s = 1; s < n; s++) for (let t = s + 1; t < n; t++) ok(`${n}p ask targets ${s}/${t} apart`, !rectsOverlap(seatTargetRect(L, s, 7), seatTargetRect(L, t, 7))); + let rt = true; + for (let i = 0; i < 7; i++) { const p = handPose(L, 0, i, 7); if (fanHit(L.seats[0].fan, 7, { 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); + ok(`${n}p: books compress to fit 13`, bookPose(L, 0, 12, 13).x !== bookPose(L, 0, 0, 13).x); +} +void POND; void cardBounds; + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +function game(skills, seed, matchSize = 4) { + const rand = mulberry32(seed); + let gs = G.createInitialState({ playerCount: skills.length, matchSize, seed }); + const mem = skills.map((sk) => createMemory(skills.length, { skill: sk, matchSize, rng: rand })); + let steps = 0, noop = 0, conserve = true, repeats = 0; + while (!G.isGameOver(gs) && steps++ < 3000) { + mem.forEach((m, s) => observeLog(m, gs, s)); + if (gs.phase === 'pick') { gs = G.applyFishPick(gs, gs.pool[Math.floor(rand() * gs.pool.length)].id); continue; } + const s = gs.currentPlayer; + const a = chooseAction(gs, s, mem[s]); + if (!a) { noop++; break; } + const open = gs.players.filter(p => p.seat !== s && !p.sittingOut && p.hand.length > 0).map(p => p.seat); + const before = caughtFromThisTurn(gs, s); + if (before.has(a.targetSeat) && open.some(t => !before.has(t))) repeats++; + const nx = G.applyAsk(gs, a.targetSeat, a.rank); + if (nx === gs) { noop++; break; } + gs = nx; + if (G.countCards(gs) !== 52) conserve = false; + } + return { gs, over: G.isGameOver(gs), noop, conserve, repeats }; +} +{ + const M = QUICK ? 40 : 150; + for (const m of [4, 2]) for (const n of [2, 3, 4]) { + let over = 0, noop = 0, conserved = true, books = true, repeats = 0; + for (let i = 0; i < M; i++) { + const r = game(Array.from({ length: n }, (_, s) => 1 + ((i + s) % 5)), 100 + i * 7 + n, m); + if (r.over) over++; + noop += r.noop; + if (!r.conserve) conserved = false; + repeats += r.repeats; + const total = r.gs.players.reduce((a, p) => a + p.pairs, 0); + if (m === 4 && total !== 13) books = false; + } + const tag = `${n}p ${m === 4 ? 'books' : 'pairs'}`; + ok(`${tag}: every game ends`, over === M, `${over}/${M}`); + ok(`${tag}: AI never makes an illegal ask`, noop === 0); + ok(`${tag}: 52 cards conserved`, conserved); + ok(`${tag}: never re-asks a player already caught from this turn`, repeats === 0, `${repeats}`); + if (m === 4) ok(`${tag}: all 13 books get made`, books); + } + // skill: in 4-player games memory matters a lot; heads-up books is mostly luck + const one = (a, b, games) => { + let w = 0; + for (let i = 0; i < games; i++) { + const seat = i % 4; const sk = [b, b, b, b]; sk[seat] = a; + const r = game(sk, 7000 + i, 4); + if (r.gs.winnerSeats.includes(seat)) w += 1 / r.gs.winnerSeats.length; + } + return w / games; + }; + const G4 = QUICK ? 300 : 800; + 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)); + ok('skill 1 loses to a table of skill 5s', w15 <= 0.16); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/tools/verifyHearts.js b/tools/verifyHearts.js new file mode 100644 index 0000000..5fa637c --- /dev/null +++ b/tools/verifyHearts.js @@ -0,0 +1,282 @@ +#!/usr/bin/env node +// verifyHearts.js — headless checks for Hearts: rules (deal, passing in all +// four directions, 2♣ lead, follow suit, hearts breaking, first-trick rule, +// scoring, both moon rules, match end at the target), the memory helpers and +// AI (always legal, skill timing), the den layout (on screen, clear of the HUD +// and each other), and an all-AI soak (every match ends, 52 cards conserved, +// skill ordering by points per hand). +// Usage: node tools/verifyHearts.js [--quick] + +import * as Hr from '../src/games/hearts/HeartsLogic.js'; +import { Card } from '../src/games/cards/Deck.js'; +import { choosePass, choosePlay, suggestPass, suggestPlay } from '../src/games/hearts/HeartsAI.js'; +import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + CARD_W, CARD_H, cardBounds, fanHit, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, inPose, +} from '../src/ui/cardtable/TableGeometry.js'; +import { T, L, handPose, trickPose, tricksPose, pointRowRect, handBadge, handHome, CENTRE } from '../src/games/hearts/HeartsTable.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 = 500; +const C = (key) => Object.assign(new Card(key[0], key[1]), { id: nid++ }); +const count = (gs) => gs.players.reduce((n, p) => n + p.hand.length + p.wonCards.length, 0) + gs.trick.length; + +function playing(hands, { current = 0, broken = false, trickNumber = 1 } = {}) { + const gs = Hr.createInitialState({ seed: 4 }); + gs.phase = 'playing'; + gs.players.forEach((p, s) => { p.hand = hands[s].map(C); p.wonCards = []; p.roundPoints = 0; }); + gs.currentPlayer = current; + gs.heartsBroken = broken; + gs.trickNumber = trickNumber; + gs.trick = []; + gs.leadSuit = null; + return gs; +} + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +{ + const gs = Hr.createInitialState({ seed: 9 }); + ok('13 cards each', gs.players.every(p => p.hand.length === 13)); + ok('52 unique', new Set(gs.players.flatMap(p => p.hand.map(c => c.id))).size === 52); + ok('first hand passes left', gs.phase === 'passing' && gs.passDirection === 'left'); + ok('deal is logged', gs.log.some(e => e.kind === 'deal')); + ok('pass targets', Hr.passTargetSeat(0, 'left') === 1 && Hr.passTargetSeat(0, 'right') === 3 && Hr.passTargetSeat(0, 'across') === 2); + let g = gs; + const picks = []; + for (let s = 0; s < 4; s++) { const ids = g.players[s].hand.slice(0, 3).map(c => c.id); picks.push(ids); g = Hr.selectPass(g, s, ids); } + ok('passes resolve when all four are in', g.phase === 'playing' && g.players.every(p => p.hand.length === 13)); + ok('passed cards land with the left neighbour', picks[0].every(id => g.players[1].hand.some(c => c.id === id))); + ok('2♣ holder leads', g.players[g.currentPlayer].hand.some(c => c.key === '2c')); + ok('must lead the 2♣', Hr.legalPlays(g, g.currentPlayer).length === 1 && Hr.legalPlays(g, g.currentPlayer)[0].key === '2c'); + // directions cycle left → right → across → hold + let h = Hr.createInitialState({ seed: 3 }); + const dirs = []; + for (let k = 0; k < 4; k++) { + dirs.push(h.passDirection); + h.phase = 'handOver'; + h = Hr.startNextHand(h); + } + ok('pass directions cycle', dirs.join() === 'left,right,across,hold'); + let hold = Hr.createInitialState({ seed: 3 }); + for (let k = 0; k < 3; k++) { hold.phase = 'handOver'; hold = Hr.startNextHand(hold); } + ok('hold hand skips passing', hold.passDirection === 'hold' && hold.phase === 'playing' && hold.players[hold.currentPlayer].hand.some(c => c.key === '2c')); +} +{ + const gs = playing([['5c', 'Kh', 'Qs'], ['9c', '2h', '3d'], ['Ac', '4h', '5d'], ['2c', 'Jh', '6s']], { current: 3, trickNumber: 0 }); + let g = Hr.playCard(gs, gs.players[3].hand[0].id); + ok('must follow suit', Hr.legalPlays(g, 0).every(c => c.suit === 'c')); + g = Hr.playCard(g, g.players[0].hand[0].id); + g = Hr.playCard(g, g.players[1].hand[0].id); + g = Hr.playCard(g, g.players[2].hand[0].id); + ok('highest of the led suit wins', g.lastTrick.winnerSeat === 2 && g.currentPlayer === 2); + ok('hearts not broken yet', !g.heartsBroken); + ok('cannot lead hearts before broken', Hr.legalPlays(g, 2).every(c => c.suit !== 'h')); +} +{ + const first = playing([['Qs', 'Kh', '9d'], ['2c', '2h', '3d'], ['Ac', '4h', '5d'], ['3c', 'Jh', '6s']], { current: 1, trickNumber: 0 }); + let g = Hr.playCard(first, first.players[1].hand[0].id); + g = Hr.playCard(g, g.players[2].hand[0].id); + g = Hr.playCard(g, g.players[3].hand[0].id); + const leg = Hr.legalPlays(g, 0); + ok('no points on the first trick when void', leg.length === 1 && leg[0].key === '9d'); + const allPts = playing([['Qs', 'Kh'], ['2c', '2h'], ['Ac', '4h'], ['3c', 'Jh']], { current: 1, trickNumber: 0 }); + let a = Hr.playCard(allPts, allPts.players[1].hand[0].id); + a = Hr.playCard(a, a.players[2].hand[0].id); + a = Hr.playCard(a, a.players[3].hand[0].id); + ok('…unless you hold only point cards', Hr.legalPlays(a, 0).length === 2); + const brk = playing([['5c', 'Kh'], ['9c', '2h'], ['2d', '4h'], ['3d', 'Jh']], { current: 0, trickNumber: 3 }); + let b = Hr.playCard(brk, brk.players[0].hand[0].id); + b = Hr.playCard(b, b.players[1].hand[0].id); + b = Hr.playCard(b, b.players[2].hand[1].id); + ok('a heart breaks hearts (logged)', b.heartsBroken && b.log.some(e => e.kind === 'heartsBroken')); + const onlyH = playing([['Kh', '2h'], ['9c'], ['2d'], ['3d']], { current: 0, trickNumber: 3 }); + ok('may lead hearts holding nothing else', Hr.legalPlays(onlyH, 0).length === 2); + const voids = playing([['5c'], ['9c'], ['2d'], ['3d']], { current: 0, trickNumber: 3 }); + let v = Hr.playCard(voids, voids.players[0].hand[0].id); + v = Hr.playCard(v, v.players[1].hand[0].id); + v = Hr.playCard(v, v.players[2].hand[0].id); + ok('known voids from the log', Hr.knownVoids(v)[2].has('c')); + ok('played keys tracked', Hr.playedKeys(v).has('5c') && Hr.playedKeys(v).has('2d')); +} +{ + // scoring: a full hand dealt by hand; seat 0 takes everything → moon + const mk = (target, moonMode) => { + const gs = Hr.createInitialState({ seed: 1, target, moonMode }); + gs.phase = 'playing'; + const suits = ['h', 's', 'd', 'c']; + const ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']; + // seat 0 holds every heart; others hold the rest; Q♠ forced onto seat 0's trick + gs.players[0].hand = ranks.map(r => C(`${r}h`)); + gs.players[1].hand = ranks.map(r => C(`${r}s`)); + gs.players[2].hand = ranks.map(r => C(`${r}d`)); + gs.players[3].hand = ranks.map(r => C(`${r}c`)); + gs.players.forEach(p => { p.wonCards = []; p.roundPoints = 0; }); + gs.heartsBroken = true; + gs.trickNumber = 1; + gs.currentPlayer = 0; + return gs; + }; + const runOut = (g) => { + let guard = 0; + while (g.phase === 'playing' && guard++ < 100) { + const s = g.currentPlayer; + const legal = Hr.legalPlays(g, s); + // seat 1 dumps the Queen as soon as it can + const pick = s === 1 ? (legal.find(c => c.key === 'Qs') ?? legal[legal.length - 1]) : legal[legal.length - 1]; + g = Hr.playCard(g, pick.id); + } + return g; + }; + const m = runOut(mk(100, 'add')); + ok('moon: shooter 0, others +26', m.moonShooter === 0 && m.handScores.join() === '0,26,26,26'); + const sub = runOut(mk(100, 'subtract')); + ok('moon (subtract): shooter −26, others 0', sub.handScores.join() === '-26,0,0,0'); + const low = runOut(mk(20, 'add')); + ok('reaching the target ends the match, lowest wins', low.phase === 'gameOver' && low.winnerSeats.join() === '0'); + ok('52 cards accounted for after a hand', m.players.reduce((n, p) => n + p.wonCards.length, 0) === 52); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry); + const gs = Hr.createInitialState({ seed: 12 }); + for (const sk of [1, 3, 5]) { + const ids = choosePass(gs, 1, { skill: sk, rng: mulberry32(sk) }); + ok(`skill ${sk} passes 3 of its own cards`, ids.length === 3 && new Set(ids).size === 3 && ids.every(id => gs.players[1].hand.some(c => c.id === id))); + } + const withQ = playing([['Qs', '5c', '9d'], ['2c'], ['3c'], ['4c']], { current: 1, trickNumber: 3 }); + withQ.players[0].hand = [C('Qs'), C('9d'), C('Kh')]; + let g = Hr.playCard(withQ, withQ.players[1].hand[0].id); + g = Hr.playCard(g, g.players[2].hand[0].id); + g = Hr.playCard(g, g.players[3].hand[0].id); + ok('void → dumps the Queen', choosePlay(g, 0, { skill: 3, rng: () => 0.5 }) === g.players[0].hand.find(c => c.key === 'Qs').id); + const duck = playing([['Kd', '7d', '2d'], ['9d'], ['3c'], ['4c']], { current: 1, trickNumber: 3 }); + const d1 = Hr.playCard(duck, duck.players[1].hand[0].id); + const d2 = Hr.playCard(Hr.playCard(d1, d1.players[2].hand[0].id), Hr.playCard(d1, d1.players[2].hand[0].id).players[3].hand[0].id); + ok('ducks under the winner with its highest safe card', choosePlay(d2, 0, { skill: 3, rng: () => 0.5 }) === d2.players[0].hand.find(c => c.key === '7d').id); + ok('hints are legal', (() => { const s = Hr.createInitialState({ seed: 2 }); return suggestPass(s, 0).length === 3; })()); + const lead = playing([['5c', '9d', 'Kh'], ['2c'], ['3c'], ['4c']], { current: 0, trickNumber: 3, broken: true }); + ok('hint play is legal', Hr.isLegalPlay(lead, 0, suggestPlay(lead, 0))); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +{ + const furn = hudFurniture(); + for (let s = 1; s < 4; 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(`${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r)); + const tricks = [0, 1, 2, 3].map(s => cardBounds(trickPose(s))); + for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) ok(`trick spots ${i}/${j} apart`, !rectsOverlap(tricks[i], tricks[j])); + const won = [0, 1, 2, 3].map(s => { + const st = cardBounds(tricksPose(s, 20)); + const pr = pointRowRect(s, 14); + return { st, pr }; + }); + const fans = [0, 1, 2, 3].map(s => fanBounds(L.seats[s].fan, 13, s === 0 ? 44 : 0)); + for (let s = 0; s < 4; s++) { + ok(`seat ${s}: hand on screen`, onScreen(fans[s], s === 0 ? 50 : 10)); + ok(`seat ${s}: trick spot on the table`, T.onFelt({ x: tricks[s].x0, y: tricks[s].y0 }) && T.onFelt({ x: tricks[s].x1, y: tricks[s].y1 })); + ok(`seat ${s}: won stack on the table`, T.onFelt({ x: won[s].st.x0, y: won[s].st.y0 }) && T.onFelt({ x: won[s].st.x1, y: won[s].st.y1 })); + ok(`seat ${s}: 14-card point row on the table`, T.onFelt({ x: won[s].pr.x0, y: won[s].pr.y0 }) && T.onFelt({ x: won[s].pr.x1, y: won[s].pr.y1 })); + ok(`seat ${s}: won stack clear of its point row`, !rectsOverlap(won[s].st, won[s].pr)); + for (const f of furn) { + ok(`seat ${s}: hand clear of ${f.name}`, !rectsOverlap(fans[s], f.r), `${JSON.stringify(fans[s])} vs ${JSON.stringify(f.r)}`); + ok(`seat ${s}: point row clear of ${f.name}`, !rectsOverlap(won[s].pr, f.r)); + ok(`seat ${s}: won stack clear of ${f.name}`, !rectsOverlap(won[s].st, f.r)); + } + for (let t = 0; t < 4; t++) { + ok(`hand ${s} clear of trick spot ${t}`, !rectsOverlap(fans[s], tricks[t])); + ok(`hand ${s} clear of point row ${t}`, !rectsOverlap(fans[s], won[t].pr), `${JSON.stringify(fans[s])} vs ${JSON.stringify(won[t].pr)}`); + ok(`trick ${s} clear of point row ${t}`, !rectsOverlap(tricks[s], won[t].pr)); + if (t !== s) ok(`point rows ${s}/${t} apart`, !rectsOverlap(won[s].pr, won[t].pr) && !rectsOverlap(won[s].pr, won[t].st)); + } + if (s > 0) { + const b = handBadge(s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 }; + ok(`seat ${s}: badge on screen`, onScreen(br)); + for (const f of furn) ok(`seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r)); + const hh = handHome(s); + ok(`seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < 1920 && hh.y > 0 && hh.y < 1080); + } + } + let rt = true; + for (let i = 0; i < 13; i++) { + const p = handPose(0, i, 13); + const step = handPose(0, 1, 13).x - handPose(0, 0, 13).x; + if (fanHit(L.seats[0].fan, 13, { x: p.x - CARD_W / 2 + step * 0.45, y: p.y - CARD_H * 0.3 }) !== i) rt = false; + } + ok('hand hit-test round trip (13)', rt); + ok('drop onto your trick spot', inPose(trickPose(0), trickPose(0), 60)); + ok('pass arrow centre on the table', T.onFelt(CENTRE)); +} + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +function match(skills, seed, opts = {}) { + const rand = mulberry32(seed); + let gs = Hr.createInitialState({ seed, ...opts }); + let hands = 0, noop = 0, conserve = true; + const pts = [0, 0, 0, 0]; + while (!Hr.isGameOver(gs) && hands < 80) { + let st = 0; + while (gs.phase !== 'handOver' && gs.phase !== 'gameOver' && st++ < 600) { + if (gs.phase === 'passing') { for (let s = 0; s < 4; s++) if (!gs.passReady[s]) gs = Hr.selectPass(gs, s, choosePass(gs, s, { skill: skills[s], rng: rand })); continue; } + const id = choosePlay(gs, gs.currentPlayer, { skill: skills[gs.currentPlayer], rng: rand }); + const nx = Hr.playCard(gs, id); + if (nx === gs) { noop++; break; } + gs = nx; + if (count(gs) !== 52) conserve = false; + } + if (gs.phase !== 'handOver' && gs.phase !== 'gameOver') break; + hands++; + gs.handScores.forEach((p, s) => { pts[s] += p; }); + if (gs.phase === 'handOver') gs = Hr.startNextHand(gs); + } + return { gs, hands, noop, conserve, pts }; +} +{ + const M = QUICK ? 20 : 80; + for (const opts of [{}, { target: 50 }, { moonMode: 'subtract' }]) { + let ended = 0, noops = 0, conserved = true, hands = 0; + for (let i = 0; i < M; i++) { + const r = match([1, 2, 3, 4].map((_, s) => 1 + ((i + s) % 5)), 400 + i * 7, opts); + if (Hr.isGameOver(r.gs)) ended++; + noops += r.noop; + if (!r.conserve) conserved = false; + hands += r.hands; + } + const tag = JSON.stringify(opts); + ok(`${tag}: every match ends`, ended === M, `${ended}/${M}`); + ok(`${tag}: AI never plays illegally`, noops === 0, `${noops}`); + ok(`${tag}: 52 cards conserved`, conserved); + console.log(` ${tag}: avg ${(hands / M).toFixed(1)} hands per match`); + } + // skill: one seat of skill a among three of skill b — points per hand + const vs = (a, b, games) => { + let pa = 0, pb = 0, hands = 0; + for (let i = 0; i < games; i++) { + const seat = i % 4; + const skills = [b, b, b, b]; skills[seat] = a; + const r = match(skills, 9000 + i); + hands += r.hands; + pa += r.pts[seat]; + pb += r.pts.reduce((x, y) => x + y, 0) - r.pts[seat]; + } + return { a: pa / hands, b: pb / hands / 3 }; + }; + const G = QUICK ? 80 : 300; + const s53 = vs(5, 3, G), s31 = vs(3, 1, G); + console.log(` points per hand: skill 5 ${s53.a.toFixed(2)} vs skill 3 ${s53.b.toFixed(2)} · skill 3 ${s31.a.toFixed(2)} vs skill 1 ${s31.b.toFixed(2)}`); + ok('skill 3 takes clearly fewer points than skill 1', s31.a < s31.b * 0.85); + ok('skill 5 takes fewer points than skill 3', s53.a < s53.b * (QUICK ? 1.0 : 0.97)); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);