diff --git a/src/games/nerts/NertsArt.js b/src/games/nerts/NertsArt.js index 36dd1bb..760ea93 100644 --- a/src/games/nerts/NertsArt.js +++ b/src/games/nerts/NertsArt.js @@ -341,6 +341,12 @@ function bakeHand(scene) { scene.textures.addCanvas('nerts-hand', c); } +/** The white ghost-hand texture ('nerts-hand'), baked on first use — shared with Phase 10. */ +export function ensureGhostHand(scene) { + if (!scene.textures.exists('nerts-hand')) bakeHand(scene); + return 'nerts-hand'; +} + function bakeTab(scene) { const c = canvas(40, 40); const ctx = c.getContext('2d'); diff --git a/src/games/phase10/Phase10AI.js b/src/games/phase10/Phase10AI.js index 01f125e..4f8cce8 100644 --- a/src/games/phase10/Phase10AI.js +++ b/src/games/phase10/Phase10AI.js @@ -1,8 +1,8 @@ -// Phase 10 AI — heuristic single-action chooser. +// Phase 10 AI — heuristic single-action chooser, scaled by skill (1..5). // -// The caller invokes chooseAction(state) and receives one action; after -// applying it (with animation), call again. The turn ends when a 'discard' -// action is returned (or the round/match ends). +// The caller invokes chooseAction(state, { skill }) and receives one action; +// after applying it (with animation), call again. The turn ends when a +// 'discard' action is returned (or the round/match ends). // // Actions: // { type: 'drawDeck' } @@ -10,28 +10,67 @@ // { type: 'laydown', groups: [{ kind, cardIds: [...] }, ...] } // { type: 'hit', handIdx, targetSeat, groupIdx, position } // { type: 'discard', handIdx, skipTargetSeat? } +// +// Skill: +// 1-2 sloppy: noisy discards, rarely reads the discard pile, may miss a +// laydown or a hit for a turn, Skips whoever and whenever. +// 3 solid: the classic heuristics. +// 4-5 sharp: won't feed laid-down phases or cards an opponent picked up, +// Skips the real threat and holds the Skip until it matters. +// +// Timing for the on-screen ghost hand lives here too (aiTiming), so the +// verify script can check it. import { getPhase } from './PhaseSpec.js'; import { cardPoints, discardTop, getHitTargets, + skipTargets, } from './Phase10Logic.js'; -export function chooseAction(state) { +// Hand speed per skill (fraction of full speed) — same feel as Nerts. +export const HAND_SPEED = { 1: 0.25, 2: 0.3, 3: 0.5, 4: 0.8, 5: 1 }; +export const PACE = { relaxed: 1.4, normal: 1, fast: 0.6 }; +const BASE = { think: 520, between: 260, reach: 190, carry: 250, hesitate: 240 }; + +const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3))); + +/** Milliseconds for each part of an AI turn at a skill + table pace. */ +export function aiTiming(skill, pace = 1) { + const k = clampSkill(skill); + const slow = pace / HAND_SPEED[k]; + // thinking slows less steeply than the hands + const mind = pace * (1 + (5 - k) * 0.18); + return { + think: Math.round(BASE.think * mind), + between: Math.round(BASE.between * mind), + hesitate: Math.round(BASE.hesitate * mind), + reach: Math.round(BASE.reach * slow), + carry: Math.round(BASE.carry * slow), + }; +} + +const NOISE = { 1: 160, 2: 90, 3: 22, 4: 6, 5: 0 }; +const MISS_LAYDOWN = { 1: 0.25, 2: 0.1, 3: 0, 4: 0, 5: 0 }; +const MISS_HIT = { 1: 0.4, 2: 0.2, 3: 0, 4: 0, 5: 0 }; + +export function chooseAction(state, opts = {}) { if (state.roundPhase !== 'play') return null; + const skill = clampSkill(opts.skill); + const rand = opts.rng ?? Math.random; const seat = state.currentPlayer; const player = state.players[seat]; // ── Step 1: draw ── if (!state.drawnThisTurn) { - return chooseDraw(state); + return chooseDraw(state, skill, rand); } // ── Step 2: lay down if possible ── - if (!player.laidDown) { + if (!player.laidDown && !state.laidDownThisTurn) { const layout = findLaydown(player.hand, player.phase); - if (layout) { + if (layout && !(rand() < MISS_LAYDOWN[skill])) { return { type: 'laydown', groups: layout.map((g) => ({ kind: g.kind, cardIds: g.cards.map((c) => c.id) })), @@ -41,21 +80,59 @@ export function chooseAction(state) { // ── Step 3: hit ── if (player.laidDown) { - const hit = findBestHit(state); - if (hit) return hit; + const hit = findBestHit(state, skill); + if (hit && !(rand() < MISS_HIT[skill])) return hit; } // ── Step 4: discard ── - return chooseDiscard(state); + return chooseDiscard(state, skill, rand); +} + +/** + * Coaching for the human (or any seat): which cards to keep, which to throw, + * which can be hit right now, and whether the phase can be laid down. + */ +export function adviseHand(state, seat) { + const player = state.players[seat]; + const hand = player.hand; + const out = { keepers: new Set(), hittable: new Set(), discardId: null, laydown: null }; + if (!player.laidDown) { + out.laydown = findLaydown(hand, player.phase); + const keep = out.laydown + ? new Set(out.laydown.flatMap((g) => g.cards.map((c) => c.id))) + : reserveLikelyKeepers(hand, player.phase); + out.keepers = keep; + } else { + for (const c of hand) { + if (c.value !== 'skip' && getHitTargets(state, c).length) out.hittable.add(c.id); + } + } + if (state.currentPlayer === seat && state.drawnThisTurn && hand.length) { + const d = chooseDiscard(state, 5, () => 0.5); + out.discardId = hand[d.handIdx]?.id ?? null; + } + return out; } // ── Draw step ─────────────────────────────────────────────────────────────── -function chooseDraw(state) { +function chooseDraw(state, skill = 3, rand = Math.random) { const seat = state.currentPlayer; const player = state.players[seat]; const top = discardTop(state); - if (top && top.value !== 'skip') { + // A card that has already changed hands twice this round is being passed + // around in a loop — go to the deck instead so the round keeps moving. + const recycled = top && (state.takes ?? []).filter((t) => t.id === top.id).length >= 2; + if (top && top.value !== 'skip' && !recycled) { + if (top.value === 'wild') return { type: 'drawDiscard' }; + // Low skill only notices a discard that finishes the phase outright. + if (skill <= 2) { + const completes = !player.laidDown && !findLaydown(player.hand, player.phase) + && findLaydown([...player.hand, top], player.phase); + if (completes && rand() < (skill === 1 ? 0.6 : 0.85)) return { type: 'drawDiscard' }; + if (!completes && rand() < 0.12 * skill && cardIsUseful(top, player)) return { type: 'drawDiscard' }; + return { type: 'drawDeck' }; + } // Take from discard if the top is immediately useful. if (cardIsUseful(top, player)) return { type: 'drawDiscard' }; } @@ -131,7 +208,7 @@ function progressContribution(card, hand, phaseNum) { // ── Hit step ──────────────────────────────────────────────────────────────── -function findBestHit(state) { +function findBestHit(state, skill = 3) { const seat = state.currentPlayer; const hand = state.players[seat].hand; if (hand.length === 0) return null; @@ -155,7 +232,7 @@ function findBestHit(state) { // ── Discard step ──────────────────────────────────────────────────────────── -function chooseDiscard(state) { +function chooseDiscard(state, skill = 3, rand = Math.random) { const seat = state.currentPlayer; const player = state.players[seat]; const hand = player.hand; @@ -173,24 +250,30 @@ function chooseDiscard(state) { } } - // Choose card to discard. - // Priority: 1) Skip (with targeted opponent), 2) Wilds NEVER, 3) unreserved - // high-point natural, 4) any unreserved card, 5) reserved card. - - // 1) If we hold a Skip, save it for now unless our hand is large and the - // opponent leader is close to going out. + // 1) Skips: low skill throws one at whoever, right away; higher skill saves + // it for the real threat (or when our hand is heavy). const skipIdx = hand.findIndex((c) => c.value === 'skip'); - if (skipIdx !== -1) { - const leader = pickSkipTarget(state, seat); + const targets = skipTargets(state, seat); + if (skipIdx !== -1 && targets.length) { + if (skill <= 2) { + return { type: 'discard', handIdx: skipIdx, skipTargetSeat: targets[Math.floor(rand() * targets.length)] }; + } + const leader = pickSkipTarget(state, seat, skill); if (leader != null) { - // Use the Skip when an opponent is at ≤ 3 cards OR our hand is heavy. - const leaderHand = state.players[leader].hand.length; - if (leaderHand <= 3 || hand.length >= 8) { - return { type: 'discard', handIdx: skipIdx, skipTargetSeat: leader }; - } + const lp = state.players[leader]; + const threat = skill >= 4 + ? (lp.laidDown && lp.hand.length <= 4) || lp.hand.length <= 3 || hand.length >= 8 || hand.length <= 2 + : lp.hand.length <= 3 || hand.length >= 8; + if (threat) return { type: 'discard', handIdx: skipIdx, skipTargetSeat: leader }; } } + // What the table can use (sharp players won't feed it). + const feeds = skill >= 4 ? feedRisk(state, seat) : null; + // Never throw back the card just taken from the pile (two players would + // otherwise trade it back and forth forever and the deck never moves). + const justTook = new Set((state.takes ?? []).filter((t) => t.seat === seat && t.turn === state.turnCount).map((t) => t.id)); + // Score every card; higher = more discardable. let bestIdx = -1; let bestScore = -Infinity; @@ -200,38 +283,56 @@ function chooseDiscard(state) { if (c.value === 'wild') s -= 1000; // never discard wilds if (c.value === 'skip') s -= 500; // don't discard skips here (handled above) if (reservedIds.has(c.id)) s -= 100; + if (justTook.has(c.id)) s -= 400; + if (feeds) s -= feeds(c); + s += rand() * NOISE[skill]; if (s > bestScore) { bestScore = s; bestIdx = i; } } if (bestIdx === -1) bestIdx = 0; const out = { type: 'discard', handIdx: bestIdx }; - // If forced to discard a skip (no other choice), target someone valid. + // Forced to discard a skip (no other choice): target someone if anyone can be skipped. if (hand[bestIdx].value === 'skip') { - const tgt = pickSkipTarget(state, seat); + const tgt = pickSkipTarget(state, seat, skill); if (tgt != null) out.skipTargetSeat = tgt; - else { - // No valid skip target — pick a different card. - for (let i = 0; i < hand.length; i++) { - if (hand[i].value !== 'skip' && hand[i].value !== 'wild') { - out.handIdx = i; - delete out.skipTargetSeat; - break; - } - } - } } return out; } -function pickSkipTarget(state, seat) { +// Penalty (0..) for discarding `card` because it would help someone else: +// it can be hit onto a laid-down phase, or it matches what an opponent has +// been picking up off the discard pile. +function feedRisk(state, seat) { + const others = state.players.filter((p) => p.seat !== seat); + const anyLaid = others.some((p) => p.laidDown); + const takes = (state.takes ?? []).filter((t) => t.seat !== seat); + return (card) => { + if (typeof card.value !== 'number') return 0; + let pen = 0; + if (anyLaid && getHitTargets(state, card).length) pen += 45; + for (const t of takes) { + const tp = state.players[t.seat]; + const spec = getPhase(tp.phase); + if (!spec || tp.laidDown) continue; + const kinds = spec.groups.map((g) => g.kind); + if (kinds.includes('set') && t.value === card.value) pen += 30; + if (kinds.includes('color') && t.color === card.color) pen += 18; + if (kinds.includes('run') && typeof t.value === 'number' && Math.abs(t.value - card.value) <= 2 && t.value !== card.value) pen += 12; + } + return Math.min(pen, 90); + }; +} + +function pickSkipTarget(state, seat, skill = 3) { // Pick the opponent with the smallest hand; tie-break by furthest phase - // (most threatening) and then by lowest score. + // (most threatening) and then by lowest score. Sharp players weigh a + // laid-down phase (they're close to going out) above everything. let best = null; let bestKey = null; - for (let s = 0; s < state.players.length; s++) { - if (s === seat) continue; + for (const s of skipTargets(state, seat)) { const p = state.players[s]; - if (p.skipped) continue; - const key = [p.hand.length, -p.phase, p.score]; + const key = skill >= 4 + ? [p.laidDown ? 0 : 1, p.hand.length, -p.phase, p.score] + : [p.hand.length, -p.phase, p.score]; if (best === null || lex(key, bestKey) < 0) { best = s; bestKey = key; } } return best; diff --git a/src/games/phase10/Phase10Art.js b/src/games/phase10/Phase10Art.js new file mode 100644 index 0000000..b8f3542 --- /dev/null +++ b/src/games/phase10/Phase10Art.js @@ -0,0 +1,630 @@ +// Phase 10 art — all baked once into canvas textures (no image files). +// +// p10-cards atlas at 2× — frames '-<1..12>', 'wild', 'skip' +// p10-back retro striped card back (used when no sprite back is chosen) +// p10-glow soft card-sized outline (selection / target glow, tinted) +// p10-spot radial light pool (turn spotlight, additive) +// p10-table- the whole room for n players: wood-panel wall, chrome-rim +// card table with tufted vinyl, seat placemats, pile spots +// +// The score pad paper and the ghost hand come from the Nerts art module +// (ensurePad / ensureGhostHand). Geometry is Phase10Table.js, so mats and pile +// spots line up with where the scene puts cards. + +import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { COLORS_LIST } from './PhaseSpec.js'; +import { + P, W, H, CARD_W, CARD_H, FELT_K, RAIL_FACE_PX, SEAT_HEX, SQ, + outline, layoutFor, matCorners, poseScale, +} from './Phase10Table.js'; + +const RES = 2; +const CW = CARD_W * RES; +const CH = CARD_H * RES; +const FONT = 'Righteous, "Arial Black", sans-serif'; + +export const CARD_COLORS = { + red: { hi: '#f0634f', mid: '#d23a2c', lo: '#8f1d16', ink: '#b22a1f' }, + blue: { hi: '#5a92ec', mid: '#2b62c8', lo: '#173a7c', ink: '#1f4fa8' }, + yellow: { hi: '#ffd44f', mid: '#f0ae1a', lo: '#a86c08', ink: '#b77b06' }, + green: { hi: '#5cc77a', mid: '#2e9a4f', lo: '#185c2c', ink: '#1f7a3b' }, +}; +const CREAM = '#fbf4e2'; +// Table-top vinyl: deep retro teal, so it reads apart from the wood paneling +// and the straw placemats. +const VINYL = '#1d5250'; +const VINYL_TUFT = '#0c2a29'; +const CREAM_DK = '#e9dcbd'; + +// ── Cards ──────────────────────────────────────────────────────────────────── +function cardBase(ctx, x, y) { + rr(ctx, x + 2, y + 2, CW - 4, CH - 4, 16); + ctx.fillStyle = CREAM; + ctx.fill(); + ctx.save(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 96, 14); + ctx.fillRect(x, y, CW, CH); + ctx.restore(); + rr(ctx, x + 2, y + 2, CW - 4, CH - 4, 16); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(40,28,14,0.55)'; + ctx.stroke(); +} + +function panelPath(ctx, x, y) { + rr(ctx, x + 13, y + 13, CW - 26, CH - 26, 12); +} + +// Colour-blind helper shapes, one per colour. +function shape(ctx, color, cx, cy, r, fill) { + ctx.save(); + ctx.fillStyle = fill; + ctx.beginPath(); + if (color === 'red') ctx.arc(cx, cy, r, 0, Math.PI * 2); + else if (color === 'blue') ctx.rect(cx - r * 0.88, cy - r * 0.88, r * 1.76, r * 1.76); + else if (color === 'yellow') { ctx.moveTo(cx, cy - r * 1.1); ctx.lineTo(cx + r * 1.05, cy + r * 0.8); ctx.lineTo(cx - r * 1.05, cy + r * 0.8); ctx.closePath(); } + else { ctx.moveTo(cx, cy - r * 1.15); ctx.lineTo(cx + r, cy); ctx.lineTo(cx, cy + r * 1.15); ctx.lineTo(cx - r, cy); ctx.closePath(); } + ctx.fill(); + ctx.restore(); +} + +function cornerIndex(ctx, x, y, text, color, fill, underline) { + const draw = () => { + ctx.font = `${text.length > 1 ? 40 : 46}px ${FONT}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = fill; + ctx.fillText(text, 0, 0); + if (underline) ctx.fillRect(-12, 25, 24, 4); + if (color) shape(ctx, color, 0, 46, 9, fill); + }; + ctx.save(); + ctx.translate(x + 38, y + 46); + draw(); + ctx.restore(); + ctx.save(); + ctx.translate(x + CW - 38, y + CH - 46); + ctx.rotate(Math.PI); + draw(); + ctx.restore(); +} + +function lozenge(ctx, cx, cy, w, h) { + ctx.beginPath(); + ctx.ellipse(cx, cy, w / 2, h / 2, -0.32, 0, Math.PI * 2); +} + +function drawNumberCard(ctx, x, y, color, value) { + const c = CARD_COLORS[color]; + cardBase(ctx, x, y); + ctx.save(); + panelPath(ctx, x, y); + const g = ctx.createLinearGradient(x, y, x + CW, y + CH); + g.addColorStop(0, c.hi); + g.addColorStop(0.55, c.mid); + g.addColorStop(1, c.lo); + ctx.fillStyle = g; + ctx.fill(); + ctx.clip(); + // 70s pinstripes through the middle + ctx.globalAlpha = 0.16; + ctx.fillStyle = CREAM; + for (let i = -3; i <= 3; i++) { + ctx.save(); + ctx.translate(x + CW / 2, y + CH / 2); + ctx.rotate(-0.32); + ctx.fillRect(-CW, i * 22 - 5, CW * 2, 7); + ctx.restore(); + } + ctx.globalAlpha = 1; + ctx.restore(); + // cream bubble with the big number + const cx = x + CW / 2, cy = y + CH / 2; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.35)'; + ctx.shadowBlur = 8; + ctx.shadowOffsetY = 3; + lozenge(ctx, cx, cy, 142, 176); + ctx.fillStyle = CREAM; + ctx.fill(); + ctx.restore(); + lozenge(ctx, cx, cy, 142, 176); + ctx.lineWidth = 3; + ctx.strokeStyle = c.lo; + ctx.stroke(); + const txt = String(value); + ctx.font = `${txt.length > 1 ? 92 : 108}px ${FONT}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.lineWidth = 8; + ctx.strokeStyle = 'rgba(30,20,10,0.55)'; + ctx.strokeText(txt, cx, cy + 4); + ctx.fillStyle = c.ink; + ctx.fillText(txt, cx, cy + 4); + if (value === 6 || value === 9) { + ctx.fillStyle = c.ink; + ctx.fillRect(cx - 22, cy + 52, 44, 7); + } + cornerIndex(ctx, x, y, txt, color, CREAM, value === 6 || value === 9); + // gloss + ctx.save(); + panelPath(ctx, x, y); + ctx.clip(); + const gl = ctx.createLinearGradient(x, y, x + CW * 0.6, y + CH * 0.5); + gl.addColorStop(0, 'rgba(255,255,255,0.28)'); + gl.addColorStop(0.5, 'rgba(255,255,255,0.04)'); + gl.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = gl; + ctx.fillRect(x, y, CW, CH); + ctx.restore(); +} + +function drawWild(ctx, x, y) { + cardBase(ctx, x, y); + ctx.save(); + panelPath(ctx, x, y); + ctx.clip(); + const order = ['red', 'yellow', 'green', 'blue']; + ctx.translate(x + CW / 2, y + CH / 2); + ctx.rotate(-0.5); + for (let i = 0; i < 8; i++) { + ctx.fillStyle = CARD_COLORS[order[i % 4]].mid; + ctx.fillRect(-CW * 1.5 + i * 58 - 58, -CH, 58, CH * 2); + } + ctx.restore(); + const cx = x + CW / 2, cy = y + CH / 2; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.4)'; + ctx.shadowBlur = 8; + ctx.shadowOffsetY = 3; + lozenge(ctx, cx, cy, 148, 182); + ctx.fillStyle = '#2a1d12'; + ctx.fill(); + ctx.restore(); + lozenge(ctx, cx, cy, 148, 182); + ctx.lineWidth = 4; + ctx.strokeStyle = CREAM; + ctx.stroke(); + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.font = `100px ${FONT}`; + const grad = ctx.createLinearGradient(cx - 40, cy - 50, cx + 40, cy + 40); + grad.addColorStop(0, CARD_COLORS.yellow.hi); + grad.addColorStop(0.5, CARD_COLORS.red.hi); + grad.addColorStop(1, CARD_COLORS.blue.hi); + ctx.fillStyle = grad; + ctx.fillText('W', cx, cy - 6); + ctx.font = `30px ${FONT}`; + ctx.fillStyle = CREAM; + ctx.fillText('WILD', cx, cy + 58); + cornerIndex(ctx, x, y, 'W', null, CREAM, false); +} + +function drawSkip(ctx, x, y) { + cardBase(ctx, x, y); + ctx.save(); + panelPath(ctx, x, y); + const g = ctx.createLinearGradient(x, y, x, y + CH); + g.addColorStop(0, '#3a3430'); + g.addColorStop(1, '#141110'); + ctx.fillStyle = g; + ctx.fill(); + ctx.clip(); + ctx.globalAlpha = 0.12; + ctx.fillStyle = '#ff8a5b'; + for (let i = -4; i <= 4; i++) ctx.fillRect(x + CW / 2 + i * 26 - 3, y, 6, CH); + ctx.globalAlpha = 1; + ctx.restore(); + const cx = x + CW / 2, cy = y + CH / 2 - 6; + ctx.lineCap = 'round'; + ctx.lineWidth = 16; + ctx.strokeStyle = '#ff6b4a'; + ctx.beginPath(); + ctx.arc(cx, cy, 52, 0, Math.PI * 2); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(cx - 36, cy - 36); + ctx.lineTo(cx + 36, cy + 36); + ctx.stroke(); + ctx.lineCap = 'butt'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.font = `32px ${FONT}`; + ctx.fillStyle = CREAM; + ctx.fillText('SKIP', cx, cy + 86); + cornerIndex(ctx, x, y, 'S', null, '#ff9a7a', false); +} + +export function frameKey(card) { + if (card.value === 'wild') return 'wild'; + if (card.value === 'skip') return 'skip'; + return `${card.color}-${card.value}`; +} + +function bakeCards(scene) { + const keys = []; + for (const col of COLORS_LIST) for (let v = 1; v <= 12; v++) keys.push([`${col}-${v}`, (ctx, x, y) => drawNumberCard(ctx, x, y, col, v)]); + keys.push(['wild', drawWild], ['skip', drawSkip]); + const cols = 10; + const rows = Math.ceil(keys.length / cols); + const c = canvas(cols * CW, rows * CH); + const ctx = c.getContext('2d'); + keys.forEach(([, draw], i) => draw(ctx, (i % cols) * CW, Math.floor(i / cols) * CH)); + const tex = scene.textures.addCanvas('p10-cards', c); + keys.forEach(([k], i) => tex.add(k, 0, (i % cols) * CW, Math.floor(i / cols) * CH, CW, CH)); +} + +function bakeBack(scene) { + const c = canvas(CW, CH); + const ctx = c.getContext('2d'); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.fillStyle = '#3b2416'; + ctx.fill(); + ctx.save(); + ctx.clip(); + // stacked 70s stripes arching across the card + const bands = ['#f2ead8', '#f0ae1a', '#e2702a', '#b5402a', '#6b2a1c']; + for (let i = 0; i < bands.length; i++) { + ctx.beginPath(); + ctx.ellipse(CW / 2, CH * 1.05, CW * (1.05 - i * 0.14), CH * (0.82 - i * 0.11), 0, Math.PI, 0); + ctx.lineWidth = 15; + ctx.strokeStyle = bands[i]; + ctx.stroke(); + } + for (let i = 0; i < bands.length; i++) { + ctx.beginPath(); + ctx.ellipse(CW / 2, -CH * 0.05, CW * (1.05 - i * 0.14), CH * (0.82 - i * 0.11), 0, 0, Math.PI); + ctx.lineWidth = 15; + ctx.strokeStyle = bands[i]; + ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 96, 20); + ctx.fillRect(0, 0, CW, CH); + ctx.restore(); + // centre medallion + ctx.beginPath(); + ctx.arc(CW / 2, CH / 2, 40, 0, Math.PI * 2); + ctx.fillStyle = '#2a1a10'; + ctx.fill(); + ctx.lineWidth = 4; + ctx.strokeStyle = '#f0ae1a'; + ctx.stroke(); + ctx.font = `40px ${FONT}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#f2ead8'; + ctx.fillText('10', CW / 2, CH / 2 + 2); + rr(ctx, 9, 9, CW - 18, CH - 18, 11); + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(242,234,216,0.75)'; + ctx.stroke(); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(0,0,0,0.6)'; + ctx.stroke(); + scene.textures.addCanvas('p10-back', c); +} + +function bakeGlow(scene) { + const pad = 30; + const c = canvas(CW + pad * 2, CH + pad * 2); + const ctx = c.getContext('2d'); + ctx.shadowColor = '#ffffff'; + ctx.shadowBlur = 22; + rr(ctx, pad, pad, CW, CH, 18); + ctx.lineWidth = 8; + ctx.strokeStyle = '#ffffff'; + ctx.stroke(); + ctx.stroke(); + scene.textures.addCanvas('p10-glow', c); +} + +function bakeSpot(scene) { + const S = 256; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2); + g.addColorStop(0, 'rgba(255,255,255,1)'); + g.addColorStop(0.45, 'rgba(255,255,255,0.45)'); + g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, S, S); + scene.textures.addCanvas('p10-spot', c); +} + +// ── The room ──────────────────────────────────────────────────────────────── +function drawWall(ctx) { + // vertical wood paneling with V-grooves + const base = ctx.createLinearGradient(0, 0, 0, H); + base.addColorStop(0, '#2c1a0e'); + base.addColorStop(0.5, '#4a2c16'); + base.addColorStop(1, '#22140a'); + ctx.fillStyle = base; + ctx.fillRect(0, 0, W, H); + let x = 0; + let i = 0; + while (x < W) { + const w = 74 + ((i * 37) % 3) * 9; + const tone = ['#5a361b', '#4d2d16', '#63401f', '#523118'][i % 4]; + ctx.globalAlpha = 0.55; + ctx.fillStyle = tone; + ctx.fillRect(x + 2, 0, w - 4, H); + // grain + ctx.globalAlpha = 0.14; + for (let k = 0; k < 9; k++) { + const gx = x + 6 + Math.random() * (w - 12); + ctx.beginPath(); + ctx.moveTo(gx, 0); + for (let y = 0; y <= H; y += 60) ctx.lineTo(gx + Math.sin(y * 0.01 + k + i) * 3, y); + ctx.lineWidth = 1 + Math.random() * 2; + ctx.strokeStyle = Math.random() < 0.5 ? '#1a0d05' : '#8a5a2c'; + ctx.stroke(); + } + ctx.globalAlpha = 1; + // groove + ctx.fillStyle = '#140a04'; + ctx.fillRect(x, 0, 2, H); + ctx.fillStyle = 'rgba(255,200,140,0.1)'; + ctx.fillRect(x + 2, 0, 1, H); + x += w; + i++; + } + ctx.fillStyle = noisePattern(ctx, 128, 16); + ctx.fillRect(0, 0, W, H); + // warm lamp wash at the top, dark corners + const lamp = ctx.createRadialGradient(W / 2, 120, 40, W / 2, 200, 1100); + lamp.addColorStop(0, 'rgba(255,190,110,0.28)'); + lamp.addColorStop(0.5, 'rgba(255,170,90,0.06)'); + lamp.addColorStop(1, 'rgba(0,0,0,0.5)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); +} + +function drawFloorShadow(ctx) { + const OFF = 6000; + const pts = outline(1.0, 18).map(p => ({ x: p.x - OFF, y: p.y + RAIL_FACE_PX * p.s + 8 })); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.8)'; + ctx.shadowBlur = 70; + ctx.shadowOffsetX = OFF; + ctx.shadowOffsetY = 30; + poly(ctx, pts); + ctx.fillStyle = '#000'; + ctx.fill(); + ctx.restore(); +} + +function drawFrontFace(ctx) { + // chrome edge band: bright / dark stripes like a diner table + const top = outline(1.0, 18); + const tones = ['#f4f6f8', '#c9ced4', '#7d848c', '#e4e8ec', '#9aa1a9', '#5b6168', '#3b3f44']; + for (let i = 0; i <= 14; i++) { + const f = i / 14; + poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f }))); + ctx.fillStyle = tones[Math.min(tones.length - 1, Math.floor(f * tones.length))]; + ctx.fill(); + } + // ribbed grooves + for (const f of [0.3, 0.55, 0.8]) { + poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f })), true); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(30,32,36,0.5)'; + ctx.stroke(); + } + poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s }))); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.85)'; + ctx.stroke(); +} + +function bandPath(ctx, k0, k1) { + const outer = outline(k1, 18), inner = outline(k0, 18); + ctx.beginPath(); + outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + ctx.closePath(); + inner.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); + ctx.closePath(); +} + +function ring(ctx, k, width, color) { + poly(ctx, outline(k, 18)); + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); +} + +function drawRim(ctx) { + ctx.save(); + bandPath(ctx, FELT_K, 1.0); + ctx.fillStyle = '#aab0b7'; + ctx.fill('evenodd'); + ctx.clip('evenodd'); + for (let i = 0; i <= 18; i++) { + const f = i / 18; + const crown = Math.sin(f * Math.PI); + ring(ctx, lerp(FELT_K, 1.0, f), 4, mix('#4c5258', '#ffffff', Math.pow(crown, 2.2) * 0.95)); + } + // lamp reflections along the far chrome + const c = P.project(0, 0.0); + const glint = ctx.createRadialGradient(c.x, c.y, 10, c.x, c.y, 420); + glint.addColorStop(0, 'rgba(255,240,210,0.65)'); + glint.addColorStop(1, 'rgba(255,240,210,0)'); + ctx.fillStyle = glint; + ctx.fillRect(0, 0, W, H); + ctx.restore(); + ring(ctx, 1.0, 2, 'rgba(0,0,0,0.6)'); + // black rubber gasket where the vinyl meets the chrome + ring(ctx, FELT_K + 0.002, 5, '#141416'); +} + +function drawVinyl(ctx) { + const felt = outline(FELT_K, 18); + ctx.save(); + poly(ctx, felt); + ctx.clip(); + ctx.fillStyle = VINYL; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 192, 26); + ctx.fillRect(0, 0, W, H); + // tufted diamond quilting in table space (perspective-correct) + const du = 0.16, dv = 0.16 * 0.56; + const line = (u0, v0, u1, v1, color, width, dy = 0) => { + const a = P.project(u0, v0), b = P.project(u1, v1); + ctx.beginPath(); + ctx.moveTo(a.x, a.y + dy); + ctx.lineTo(b.x, b.y + dy); + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); + }; + for (let k = -20; k <= 20; k++) { + const u = k * du; + // two diagonal families: (u + t, t) and (u - t, t) scaled to the diamond aspect + const a0 = { u: u, v: -0.05 }, a1 = { u: u + (1.1 / dv) * du, v: 1.05 }; + const b1 = { u: u - (1.1 / dv) * du, v: 1.05 }; + line(a0.u, a0.v, a1.u, a1.v, 'rgba(0,18,20,0.4)', 3); + line(a0.u, a0.v, a1.u, a1.v, 'rgba(170,240,230,0.08)', 1.5, 2); + line(a0.u, a0.v, b1.u, b1.v, 'rgba(0,18,20,0.4)', 3); + line(a0.u, a0.v, b1.u, b1.v, 'rgba(170,240,230,0.08)', 1.5, 2); + } + // tuft buttons at the crossings + // the two families cross every half-step down, alternating half-step across + for (let row = 0; row * (dv / 2) <= 1.1; row++) { + const v = -0.05 + row * (dv / 2); + const off = row % 2 ? du / 2 : 0; + for (let k = -8; k <= 8; k++) { + const p = P.project(k * du + off, v); + ctx.beginPath(); + ctx.ellipse(p.x, p.y, 4.5 * p.s, 3.6 * p.s, 0, 0, Math.PI * 2); + ctx.fillStyle = VINYL_TUFT; + ctx.fill(); + ctx.beginPath(); + ctx.ellipse(p.x - 1, p.y - 1, 1.8 * p.s, 1.3 * p.s, 0, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(190,250,240,0.28)'; + ctx.fill(); + } + } + // overhead lamp pool + vignette + const c = P.project(0, 0.5); + const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1050); + lamp.addColorStop(0, 'rgba(255,214,150,0.26)'); + lamp.addColorStop(0.45, 'rgba(255,214,150,0.08)'); + lamp.addColorStop(1, 'rgba(255,214,150,0)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); + const vig = ctx.createRadialGradient(c.x, c.y, 360, c.x, c.y, 1150); + vig.addColorStop(0, 'rgba(0,0,0,0)'); + vig.addColorStop(1, 'rgba(0,0,0,0.55)'); + ctx.fillStyle = vig; + ctx.fillRect(0, 0, W, H); + for (let i = 0; i < 10; i++) ring(ctx, FELT_K - i * 0.004, 4, `rgba(0,0,0,${0.32 * (1 - i / 10)})`); + ctx.restore(); +} + +function drawMats(ctx, L) { + for (const st of L.seats) { + const hex = SEAT_HEX[st.seat]; + const pts = matCorners(L, st.seat, 10); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.5)'; + ctx.shadowBlur = 14; + ctx.shadowOffsetY = 5; + poly(ctx, pts); + ctx.fillStyle = '#c99a52'; + ctx.fill(); + ctx.restore(); + ctx.save(); + poly(ctx, pts); + ctx.clip(); + // woven straw placemat: two families of fine stripes + const top = Math.min(...pts.map(p => p.y)), btm = Math.max(...pts.map(p => p.y)); + const lft = Math.min(...pts.map(p => p.x)), rgt = Math.max(...pts.map(p => p.x)); + const g = ctx.createLinearGradient(0, top, 0, btm); + g.addColorStop(0, '#d9ac62'); + g.addColorStop(1, '#a8772f'); + ctx.fillStyle = g; + ctx.fillRect(lft, top, rgt - lft, btm - top); + ctx.globalAlpha = 0.18; + for (let y = top; y < btm; y += 5) { + ctx.fillStyle = (Math.round(y / 5) % 2) ? '#6b4214' : '#f6d79a'; + ctx.fillRect(lft, y, rgt - lft, 2); + } + ctx.globalAlpha = 0.08; + for (let x = lft; x < rgt; x += 9) { + ctx.fillStyle = '#4a2a0c'; + ctx.fillRect(x, top, 2, btm - top); + } + ctx.globalAlpha = 1; + ctx.fillStyle = noisePattern(ctx, 96, 22); + ctx.fillRect(lft, top, rgt - lft, btm - top); + // subtle darkening so cards pop + ctx.fillStyle = 'rgba(40,20,6,0.18)'; + ctx.fillRect(lft, top, rgt - lft, btm - top); + ctx.restore(); + // seat-coloured piping + stitch + poly(ctx, pts); + ctx.lineWidth = 5; + ctx.strokeStyle = hex; + ctx.stroke(); + poly(ctx, matCorners(L, st.seat, 3)); + ctx.setLineDash([7, 6]); + ctx.lineWidth = 1.4; + ctx.strokeStyle = 'rgba(255,244,214,0.55)'; + ctx.stroke(); + ctx.setLineDash([]); + } +} + +function pileSpot(ctx, pose, label) { + const { sx, sy } = poseScale(pose.s, pose.rot, SQ); + ctx.save(); + ctx.translate(pose.x, pose.y); + ctx.scale(sx, sy); + rr(ctx, -CARD_W / 2 - 8, -CARD_H / 2 - 8, CARD_W + 16, CARD_H + 16, 14); + ctx.fillStyle = 'rgba(0,0,0,0.22)'; + ctx.fill(); + ctx.setLineDash([9, 7]); + ctx.lineWidth = 2.2 / sx; + ctx.strokeStyle = 'rgba(242,214,160,0.45)'; + ctx.stroke(); + ctx.setLineDash([]); + ctx.restore(); + ctx.font = `16px "Julius Sans One", sans-serif`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(242,214,160,0.5)'; + ctx.fillText(label, pose.x, pose.y - (CARD_H / 2) * sy - 26); +} + +function bakeTable(scene, key, playerCount) { + const L = layoutFor(playerCount); + const c = canvas(W, H); + const ctx = c.getContext('2d'); + drawWall(ctx); + drawFloorShadow(ctx); + drawFrontFace(ctx); + drawRim(ctx); + drawVinyl(ctx); + ctx.save(); + poly(ctx, outline(FELT_K, 18)); + ctx.clip(); + drawMats(ctx, L); + pileSpot(ctx, L.deck, 'DRAW'); + pileSpot(ctx, L.discard, 'DISCARD'); + ctx.restore(); + scene.textures.addCanvas(key, c); +} + +export async function preparePhase10Art(scene, playerCount) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('p10-cards')) bakeCards(scene); + if (!scene.textures.exists('p10-back')) bakeBack(scene); + if (!scene.textures.exists('p10-glow')) bakeGlow(scene); + if (!scene.textures.exists('p10-spot')) bakeSpot(scene); + const key = `p10-table-${playerCount}`; + if (!scene.textures.exists(key)) bakeTable(scene, key, playerCount); + return key; +} + +export { CW as CARD_TEX_W, CH as CARD_TEX_H, CREAM, CREAM_DK }; diff --git a/src/games/phase10/Phase10Game.js b/src/games/phase10/Phase10Game.js index 944102b..444c561 100644 --- a/src/games/phase10/Phase10Game.js +++ b/src/games/phase10/Phase10Game.js @@ -1,12 +1,18 @@ import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; +import { Tooltip } from '../../ui/Tooltip.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 { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { PHASES, getPhase, validateLaydown } from './PhaseSpec.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; +import { jitterFor } from '../../ui/casino/CasinoCards.js'; +import { ensurePad, ensureGhostHand } from '../nerts/NertsArt.js'; +import { + PHASES, getPhase, groupStatus, groupGoalLabel, laidGroupLabel, cardName, COLOR_NAMES, +} from './PhaseSpec.js'; import { applyDrawFromDeck, applyDrawFromDiscard, @@ -19,111 +25,65 @@ import { getHitTargets, runAssignedValues, startNextRound, + orderGroupCards, + skipTargets, } from './Phase10Logic.js'; -import { chooseAction, findLaydown } from './Phase10AI.js'; +import { chooseAction, findLaydown, adviseHand, aiTiming, PACE } from './Phase10AI.js'; +import { + CARD_W, CARD_H, SQ, SEAT_COLORS, SEAT_HEX, PLATE, TOP_BUTTONS, DOCK, SORT_ROW, KEYS_BOX, + layoutFor, poseScale, handPose, handHit, handInsertIndex, handZone, handBadge, handHome, + groupAreas, groupCardPose, groupRect, areaRect, inRect, inPose, deckTopPose, discardPose, + stackLift, cardCorners, spotFor, matCentre, +} from './Phase10Table.js'; +import { preparePhase10Art, frameKey, CARD_COLORS } from './Phase10Art.js'; + +// ─── Phase 10 ───────────────────────────────────────────────────────────────── +// A rec-room card table. Geometry lives in Phase10Table.js, the baked art in +// Phase10Art.js, the rules in Phase10Logic.js and the opponents in +// Phase10AI.js — this file is flow, animation and input. +// +// Every visible card is a persistent sprite keyed by card id. After any state +// change layout() works out where every card should be and tweens the ones +// that moved, so draws, lay-downs, hits and discards all glide (and flip) into +// place. Opponents play with a ghost hand whose speed follows their skill. -// ── Layout constants ──────────────────────────────────────────────────────── const CX = GAME_WIDTH / 2; const CY = GAME_HEIGHT / 2; -const CARD_W = 90; -const CARD_H = 126; -const CARD_R = 8; -const HAND_SPREAD = 96; -const GROUP_GAP = 14; -const LAIDOWN_CARD_W = 60; -const LAIDOWN_CARD_H = 84; - const D = { - felt: -1, board: 0, pile: 5, card: 10, highlight: 20, - ui: 30, portrait: 35, chip: 40, banner: 60, - playbookPanel: 70, playbookTab: 71, modal: 80, + bg: -3, playfield: -2, table: -1, spot: 2, slots: 4, labels: 6, cards: 10, glow: 24, + oppHand: 26, hand: 30, fly: 40, ghost: 46, drag: 50, float: 54, plates: 56, ui: 60, stamp: 70, modal: 80, }; -// Suit color tinting. -const SUIT = { - red: { fill: 0xfbe7e2, stroke: 0xc92a2a, num: '#c92a2a' }, - blue: { fill: 0xe2ecfb, stroke: 0x2b7fbf, num: '#1c63a3' }, - yellow: { fill: 0xfbf3d4, stroke: 0xc69a1f, num: '#a17a10' }, - green: { fill: 0xdff3e3, stroke: 0x2f9e44, num: '#1c6b30' }, -}; -const WILD_FILL = 0xf2ead8; -const WILD_STRIPE = 0xc8a84b; -const SKIP_FILL = 0x1e1a12; -const SKIP_GLYPH = 0xe06c75; +const SETTINGS_KEY = 'phase10-settings'; +const DOUBLE_CLICK_MS = 320; +const COLOR_ORDER = { red: 0, blue: 1, yellow: 2, green: 3 }; +const FONT_HAND = '"YummyCupcakes", "Comic Sans MS", cursive'; -// Seat slot mapping. Slot index in SLOTS_USED matches seat index. -const SLOTS_USED = { - 2: ['bottom', 'top'], - 3: ['bottom', 'left', 'right'], - 4: ['bottom', 'left', 'top', 'right'], +const lerp = (a, b, t) => a + (b - a) * t; +const lerpAngle = (a, b, t) => { + let d = b - a; + while (d > Math.PI) d -= Math.PI * 2; + while (d < -Math.PI) d += Math.PI * 2; + return a + d * t; }; +const samePose = (a, b) => a && b && Math.abs(a.x - b.x) < 0.5 && Math.abs(a.y - b.y) < 0.5 + && Math.abs(a.rot - b.rot) < 0.001 && Math.abs(a.s - b.s) < 0.001 && Math.abs((a.q ?? SQ) - (b.q ?? SQ)) < 0.001; -function slotLayout(slot) { - switch (slot) { - case 'bottom': - return { - rotation: 0, - handStart: { x: 460, y: 990 }, - handAxis: 'x', - handFaceUp: true, - laidStart: { x: 700, y: 720 }, - laidAxis: 'x', - portrait: { x: 684, y: 846, r: 56 }, - nameLabel: { x: 684, y: 916 }, - chip: { x: 752, y: 870 }, - rotateCards: 0, - }; - case 'top': - return { - rotation: 180, - handStart: { x: 460, y: 60 }, - handAxis: 'x', - handFaceUp: false, - laidStart: { x: 700, y: 344 }, - laidAxis: 'x', - portrait: { x: 1094, y: 198, r: 50 }, - nameLabel: { x: 1094, y: 262 }, - chip: { x: 752, y: 180 }, - rotateCards: 180, - }; - case 'left': - return { - rotation: 90, - handStart: { x: 60, y: 900 }, - handAxis: 'y-up', - handFaceUp: false, - laidStart: { x: 524, y: 340 }, - laidAxis: 'y', - portrait: { x: 180, y: 266, r: 50 }, - nameLabel: { x: 180, y: 202 }, - chip: { x: 180, y: 328 }, - chipRotation: Math.PI / 2, - rotateCards: 90, - }; - case 'right': - return { - rotation: 270, - handStart: { x: 1860, y: 900 }, - handAxis: 'y-up', - handFaceUp: false, - laidStart: { x: 1396, y: 340 }, - laidAxis: 'y', - portrait: { x: 1740, y: 670, r: 50 }, - nameLabel: { x: 1740, y: 734 }, - chip: { x: 1740, y: 608 }, - chipRotation: -Math.PI / 2, - rotateCards: 270, - }; - default: - throw new Error(`Unknown slot: ${slot}`); - } +function loadSettings() { + const base = { pace: 'normal', hints: true, warn: true, sort: 'number' }; + try { + return { ...base, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; + } catch { return base; } } -const DRAW_POS = { x: CX - 80, y: CY }; -const DISCARD_POS = { x: CX + 80, y: CY }; +const isNum = (c) => typeof c.value === 'number'; +const rankOf = (c) => (isNum(c) ? 0 : c.value === 'wild' ? 1 : 2); +const byNumber = (a, b) => rankOf(a) - rankOf(b) + || (isNum(a) && isNum(b) ? a.value - b.value || COLOR_ORDER[a.color] - COLOR_ORDER[b.color] : 0) || a.id - b.id; +const byColor = (a, b) => rankOf(a) - rankOf(b) + || (isNum(a) && isNum(b) ? COLOR_ORDER[a.color] - COLOR_ORDER[b.color] || a.value - b.value : 0) || a.id - b.id; -// ── Scene ─────────────────────────────────────────────────────────────────── export default class Phase10Game extends Phaser.Scene { constructor() { super('Phase10Game'); } @@ -132,1663 +92,2116 @@ export default class Phase10Game extends Phaser.Scene { this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; this.cardBack = data.cardBack ?? null; + this.playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); + this.L = layoutFor(this.playerCount); + this.settings = loadSettings(); this.gs = null; - this.animating = false; - this.matchOver = false; + this.mode = 'idle'; // idle | deal | human | ai | ending | summary + this.turnToken = 0; + this.busy = false; // a human action is animating + this.modal = null; + this.paused = false; - this.cardObjs = new Map(); - this.transientObjs = []; - this.highlightObjs = []; - this.opponentPortraits = []; - - this.selectedHandIdx = null; - this.slotForSeat = []; - - this.seatChips = []; // seat → { container, phaseText, scoreText, doneRibbon } - this.playbookOpen = false; - this.playbookPanel = null; - - this.localHandCards = []; - this.dragState = null; + this.sprites = new Map(); // card id → container + this.lastLoc = new Map(); // card id → { pose, faceUp, depth } + this.stage = null; // human staging: [[ids], [ids]] per phase group + this.selectedId = null; + this.hoverId = null; + this.lastClick = { id: null, at: 0 }; this.potentialDrag = null; - this.stagingGroups = null; - this.submitBtn = null; - this.clearBtn = null; + this.dragState = null; + this.revealAll = false; + this.advice = null; + + this.history = []; // per round: lastRoundSummary + this.discardLog = []; // { id, seat } — who threw what this round + this.prevHandSizes = []; + this.skipShown = []; + this.plates = []; + this.portraits = []; + this.badges = []; + this.hands = []; + this.labels = []; + this.fx = []; } - create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildPlayfield(); - this.assignSeats(); - this.buildSeatAreas(); - this.buildCenter(); - this.buildPlaybook(); - this.buildHUD(); - this.setupDragHandlers(); - this.startNewMatch(); + // ── Lifecycle ─────────────────────────────────────────────────────────────── + async create() { + try { + const music = this.cache.json.get('music'); + if (music?.tracks) new MusicPlayer(this, music.tracks); + } catch (_) { /* music optional */ } + + this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x120a05).setDepth(D.bg); + this.events.once('shutdown', () => { + this.turnToken++; + this.input.setDefaultCursor('default'); + }); + + const tableKey = await preparePhase10Art(this, this.playerCount); + if (!this.sys.isActive()) return; + ensureGhostHand(this); + this.add.image(0, 0, tableKey).setOrigin(0, 0).setDepth(D.table); + + this.spot = this.add.image(CX, CY, 'p10-spot').setDepth(D.spot).setBlendMode(Phaser.BlendModes.ADD) + .setTint(0xffc884).setAlpha(0); + this.slabG = this.add.graphics().setDepth(D.cards - 1); + this.slotG = this.add.graphics().setDepth(D.slots); + this.dropSlotG = this.add.graphics().setVisible(false); + this.dropSlotGlow = this.add.image(0, 0, 'p10-glow').setTint(0xffd35a).setVisible(false); + this.tweens.add({ targets: this.dropSlotGlow, alpha: { from: 1, to: 0.45 }, duration: 520, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + this.targetG = this.add.graphics().setDepth(D.glow); + this.deckTxt = this.add.text(this.L.deck.x, this.L.deck.y + 66, '', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#f2d6a0', + }).setOrigin(0.5).setDepth(D.labels).setAlpha(0.8); + + this.buildLabels(); + this.buildPlates(); + this.buildBadges(); + this.buildHands(); + this.buildTopButtons(); + this.buildDock(); + this.buildSortRow(); + this.buildTooltips(); + this.setupInput(); + + this.gs = createInitialState({ playerCount: this.playerCount, startingPlayer: 0 }); + this.startRound(); } - // ── Setup ──────────────────────────────────────────────────────────────── + alive() { return this.sys.isActive(); } + wait(ms) { return new Promise(res => this.time.delayedCall(Math.max(0, ms), res)); } + nameForSeat(seat) { + if (seat === 0) return auth.user?.username ?? 'You'; + return this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`; + } + shortName(seat, max = 12) { + const n = seat === 0 ? 'You' : this.nameForSeat(seat); + return n.length > max ? `${n.slice(0, max - 1)}…` : n; + } + skillFor(seat) { return this.opponents[seat - 1]?.skill ?? 3; } + pace() { return PACE[this.settings.pace] ?? 1; } + timing(seat) { return aiTiming(this.skillFor(seat), this.pace()); } + me() { return this.gs.players[0]; } + isMyTurn() { return this.mode === 'human' && this.gs?.roundPhase === 'play' && this.gs.currentPlayer === 0; } + canAct() { return this.isMyTurn() && !this.busy && !this.modal && !this.paused; } + canStage() { return this.canAct() && this.gs.drawnThisTurn && !this.me().laidDown; } - 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); + saveSettings() { + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + } + + // ── Seat furniture ───────────────────────────────────────────────────────── + buildLabels() { + for (let seat = 0; seat < this.playerCount; seat++) { + this.labels[seat] = [0, 1].map(() => this.add.text(0, 0, '', { + fontFamily: '"Julius Sans One"', fontSize: seat === 0 ? '16px' : '13px', color: '#fff4d6', + stroke: '#2a1608', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels).setVisible(false)); } } - assignSeats() { - const playerCount = 1 + this.opponents.length; - const slots = SLOTS_USED[playerCount]; - if (!slots) throw new Error(`Phase 10 needs 2..4 players, got ${playerCount}`); - this.slotForSeat = slots.slice(); + buildPlates() { + const key = ensureLeatherPanel(this, 'p10-plate', PLATE.w, PLATE.h, { radius: 14 }); + for (let seat = 0; seat < this.playerCount; seat++) { + const { x, y } = this.L.seats[seat].plate; + const bg = this.add.image(x, y, key).setDepth(D.plates); + const glow = this.add.graphics().setDepth(D.plates - 0.5); + glow.lineStyle(5, SEAT_COLORS[seat], 1); + glow.strokeRoundedRect(x - PLATE.w / 2 - 4, y - PLATE.h / 2 - 4, PLATE.w + 8, PLATE.h + 8, 16); + glow.setAlpha(0); + const stripe = this.add.graphics().setDepth(D.plates + 0.5); + stripe.fillStyle(SEAT_COLORS[seat], 1); + stripe.fillRoundedRect(x - PLATE.w / 2 + 8, y - 34, 6, 68, 3); + const px = x - PLATE.w / 2 + 52; + this.portraits[seat] = seat === 0 + ? createPlayerPortrait(this, px, y, 32, D.plates + 1, 'Phase10Game') + : createOpponentPortrait(this, this.opponents[seat - 1], px, y, 32, D.plates + 1); + const tx = x - PLATE.w / 2 + 96; + const rx = x + PLATE.w / 2 - 14; + const nameTxt = this.add.text(tx, y - 27, this.shortName(seat, 13), { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.plates + 2); + const scoreTxt = this.add.text(rx, y - 27, '0', { + fontFamily: 'Righteous', fontSize: '20px', color: SEAT_HEX[seat], + }).setOrigin(1, 0.5).setDepth(D.plates + 2); + const phaseTxt = this.add.text(tx, y + 1, 'Phase 1', { + fontFamily: 'Righteous', fontSize: '17px', color: COLORS.goldHex, + }).setOrigin(0, 0.5).setDepth(D.plates + 2); + const statusTxt = this.add.text(rx, y + 1, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#8ce99a', + }).setOrigin(1, 0.5).setDepth(D.plates + 2); + const ladder = this.add.graphics().setDepth(D.plates + 2); + if (seat > 0) { + const skill = this.skillFor(seat); + for (let i = 0; i < 5; i++) { + this.add.circle(rx - 4 - (4 - i) * 10, y + 29, 3.2, i < skill ? COLORS.accent : COLORS.muted, i < skill ? 1 : 0.35) + .setDepth(D.plates + 2); + } + } + const tallyTxt = this.add.text(x, seat === 0 ? y - 86 : y + 82, '', { + fontFamily: 'Righteous', fontSize: '38px', color: SEAT_HEX[seat], stroke: '#120c06', strokeThickness: 7, + }).setOrigin(0.5).setDepth(D.stamp - 1).setVisible(false); + const skipStamp = this.add.text(x + 30, y, 'SKIPPED', { + fontFamily: 'Righteous', fontSize: '40px', color: '#ff6b4a', stroke: '#2a0c04', strokeThickness: 6, + }).setOrigin(0.5).setRotation(-0.12).setDepth(D.plates + 4).setVisible(false); + this.plates[seat] = { x, y, bg, glow, nameTxt, scoreTxt, phaseTxt, statusTxt, ladder, tallyTxt, skipStamp, tx }; + } } - buildSeatAreas() { - const playerCount = this.slotForSeat.length; - for (let seat = 0; seat < playerCount; seat++) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); + // What a plate shows: live state, or the pre-round values while a finished + // round is still being counted up. + plateInfo(seat) { + const p = this.gs.players[seat]; + const h = this.plateHold?.[seat]; + return h ? { ...h, laidDown: p.laidDown, hand: p.hand } : { score: p.score, phase: p.phase, clearedAt: p.clearedAt, laidDown: p.laidDown, hand: p.hand }; + } - // Portrait & name - if (seat === 0) { - createPlayerPortrait(this, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait, 'Phase10Game'); - 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); + drawLadder(seat, highlightPhase = null) { + const pl = this.plates[seat]; + const p = this.plateInfo(seat); + const g = pl.ladder; + g.clear(); + const x0 = pl.tx, y = pl.y + 29; + const done = p.clearedAt != null ? 10 : p.phase - 1; + for (let i = 0; i < 10; i++) { + const x = x0 + i * 13; + if (i < done) { + g.fillStyle(SEAT_COLORS[seat], i + 1 === highlightPhase ? 1 : 0.85); + g.fillRoundedRect(x, y - 5, 10, 10, 2); + } else if (i === done) { + g.lineStyle(2, 0xfff4d6, 1); + g.strokeRoundedRect(x, y - 5, 10, 10, 2); } 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); - } - } - - // Phase chip + score badge anchored next to portrait. - this.seatChips[seat] = this.makeSeatChip(seat, layout.chip.x, layout.chip.y); - if (layout.chipRotation) this.seatChips[seat].container.setRotation(layout.chipRotation); - } - } - - makeSeatChip(seat, 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(0, -32, 280, 64, 10); - bg.lineStyle(2, COLORS.accent, 1); - bg.strokeRoundedRect(0, -32, 280, 64, 10); - container.add(bg); - - const phaseText = this.add.text(14, -22, '', { - fontFamily: 'Righteous', fontSize: '16px', color: COLORS.goldHex, - }); - const goalText = this.add.text(14, 0, '', { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.textHex, wordWrap: { width: 200 }, - }); - const scoreText = this.add.text(264, -22, '', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(1, 0); - const scoreLabel = this.add.text(264, 4, 'pts', { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: COLORS.mutedHex, - }).setOrigin(1, 0); - - const ribbon = this.add.text(140, 18, '', { - fontFamily: '"Julius Sans One"', fontSize: '12px', - color: COLORS.textDarkHex, backgroundColor: COLORS.goldHex, - padding: { x: 6, y: 2 }, - }).setOrigin(0.5); - ribbon.setVisible(false); - - container.add([phaseText, goalText, scoreText, scoreLabel, ribbon]); - return { container, phaseText, goalText, scoreText, ribbon }; - } - - buildCenter() { - // Draw pile placeholder - const drawRect = this.add.rectangle(DRAW_POS.x, DRAW_POS.y, CARD_W + 8, CARD_H + 8, 0x000000, 0.4) - .setStrokeStyle(2, COLORS.accent).setDepth(D.pile) - .setInteractive({ useHandCursor: true }); - drawRect.on('pointerdown', () => this.onDrawDeckClick()); - this.add.text(DRAW_POS.x, DRAW_POS.y - CARD_H / 2 - 18, 'DRAW', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.drawPileText = this.add.text(DRAW_POS.x, DRAW_POS.y + CARD_H / 2 + 16, '', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.ui); - this.drawPileRect = drawRect; - - // Discard pile placeholder - const discRect = this.add.rectangle(DISCARD_POS.x, DISCARD_POS.y, CARD_W + 8, CARD_H + 8, 0x000000, 0.4) - .setStrokeStyle(2, COLORS.muted).setDepth(D.pile) - .setInteractive({ useHandCursor: true }); - discRect.on('pointerdown', () => this.onDiscardPileClick()); - this.add.text(DISCARD_POS.x, DISCARD_POS.y - CARD_H / 2 - 18, 'DISCARD', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.discardPileRect = discRect; - } - - buildPlaybook() { - // Vertical "ribbon" tab on the right edge. - const tabX = GAME_WIDTH - 22; - const tabY = CY; - const tab = this.add.container(tabX, tabY).setDepth(D.playbookTab); - const tabBg = this.add.graphics(); - const drawTab = (color) => { - tabBg.clear(); - tabBg.fillStyle(color, 1); - tabBg.fillRoundedRect(-18, -110, 36, 220, 8); - tabBg.lineStyle(2, COLORS.accent, 1); - tabBg.strokeRoundedRect(-18, -110, 36, 220, 8); - }; - drawTab(COLORS.panel); - const tabText = this.add.text(0, 0, 'PHASES', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.goldHex, - }).setOrigin(0.5); - tabText.setRotation(-Math.PI / 2); - tab.add([tabBg, tabText]); - tab.setSize(36, 220); - tab.setInteractive(new Phaser.Geom.Rectangle(-18, -110, 36, 220), Phaser.Geom.Rectangle.Contains); - tab.input.cursor = 'pointer'; - tab.on('pointerover', () => drawTab(COLORS.accent)); - tab.on('pointerout', () => drawTab(this.playbookOpen ? COLORS.accent : COLORS.panel)); - tab.on('pointerdown', () => this.togglePlaybook()); - this.playbookTab = tab; - - // Off-screen panel container — slides in from the right when opened. - const panelW = 480; - const panelH = 880; - const panelX = GAME_WIDTH + panelW / 2; // start fully off-screen - const panel = this.add.container(panelX, CY).setDepth(D.playbookPanel); - const pbg = this.add.graphics(); - pbg.fillStyle(COLORS.panel, 0.97); - pbg.fillRoundedRect(-panelW / 2, -panelH / 2, panelW, panelH, 16); - pbg.lineStyle(3, COLORS.accent, 1); - pbg.strokeRoundedRect(-panelW / 2, -panelH / 2, panelW, panelH, 16); - panel.add(pbg); - - const header = this.add.text(0, -panelH / 2 + 30, 'PHASE PLAYBOOK', { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.goldHex, - }).setOrigin(0.5); - panel.add(header); - const subhead = this.add.text(0, -panelH / 2 + 64, 'race to clear all ten', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5); - panel.add(subhead); - - // 10 phase rows - this.playbookRows = []; - const rowH = 70; - const rowY0 = -panelH / 2 + 100; - for (let i = 0; i < PHASES.length; i++) { - const phase = PHASES[i]; - const y = rowY0 + i * rowH; - const rowBg = this.add.graphics(); - const drawRowBg = (highlight) => { - rowBg.clear(); - rowBg.fillStyle(highlight ? COLORS.gold : COLORS.bg, highlight ? 0.2 : 0.6); - rowBg.fillRoundedRect(-panelW / 2 + 16, y - rowH / 2 + 4, panelW - 32, rowH - 8, 8); - if (highlight) { - rowBg.lineStyle(2, COLORS.gold, 0.8); - rowBg.strokeRoundedRect(-panelW / 2 + 16, y - rowH / 2 + 4, panelW - 32, rowH - 8, 8); - } - }; - drawRowBg(false); - panel.add(rowBg); - - const num = this.add.text(-panelW / 2 + 36, y - 14, `${phase.num}`, { - fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex, - }).setOrigin(0, 0.5); - const goal = this.add.text(-panelW / 2 + 84, y - 14, phase.short, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, - }).setOrigin(0, 0.5); - const dots = this.add.container(-panelW / 2 + 84, y + 16); - panel.add([num, goal, dots]); - - this.playbookRows.push({ phase: phase.num, drawRowBg, dots }); - } - - panel.setSize(panelW, panelH); - this.playbookPanel = panel; - this.playbookPanelW = panelW; - this.playbookClosedX = panelX; - this.playbookOpenX = GAME_WIDTH - panelW / 2 - 40; - } - - togglePlaybook() { - if (!this.playbookPanel) return; - const open = !this.playbookOpen; - this.playbookOpen = open; - this.tweens.add({ - targets: this.playbookPanel, - x: open ? this.playbookOpenX : this.playbookClosedX, - duration: 260, - ease: 'Cubic.easeOut', - }); - } - - refreshPlaybook() { - if (!this.gs || !this.playbookRows) return; - for (const row of this.playbookRows) { - const isLocalCurrent = this.gs.players[0]?.phase === row.phase; - row.drawRowBg(isLocalCurrent); - row.dots.removeAll(true); - // Per-player chip showing where each seat is relative to this phase. - const dotR = 9; - const seatColors = [COLORS.gold, 0x4dabf7, 0xa78bfa, 0xff8a5b]; - for (let s = 0; s < this.gs.players.length; s++) { - const p = this.gs.players[s]; - const x = s * 26; - const onThisPhase = p.phase === row.phase && p.clearedAt == null; - const passed = p.phase > row.phase || (p.clearedAt != null && row.phase <= 10); - const color = seatColors[s % seatColors.length]; - - const dot = this.add.graphics(); - if (passed) { - // dim filled dot - dot.fillStyle(color, 0.35); - dot.fillCircle(x, 0, dotR); - } else if (onThisPhase) { - dot.fillStyle(color, 1); - dot.fillCircle(x, 0, dotR); - dot.lineStyle(2, COLORS.text, 0.95); - dot.strokeCircle(x, 0, dotR); - } else { - dot.lineStyle(2, color, 0.6); - dot.strokeCircle(x, 0, dotR); - } - row.dots.add(dot); - // Seat initial label - const label = this.add.text(x, 0, s === 0 ? 'Y' : `${s + 1}`, { - fontFamily: '"Julius Sans One"', fontSize: '10px', - color: passed ? COLORS.mutedHex : COLORS.textDarkHex, fontStyle: 'bold', - }).setOrigin(0.5); - if (!onThisPhase) label.setColor(COLORS.mutedHex); - row.dots.add(label); + g.fillStyle(0xffffff, 0.12); + g.fillRoundedRect(x, y - 5, 10, 10, 2); } } } - buildHUD() { - this.statusBg = this.add.graphics().setDepth(D.ui - 1).setVisible(false); - this.statusText = this.add.text(1052, 870, '', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex, + buildBadges() { + 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 ring = this.add.circle(0, 0, 22, 0xff6b4a, 0); + const g = this.add.graphics(); + g.fillStyle(0x140d07, 0.92); + g.fillCircle(0, 0, 15); + g.lineStyle(2.5, SEAT_COLORS[seat], 1); + g.strokeCircle(0, 0, 15); + const t = this.add.text(0, 1, '10', { fontFamily: 'Righteous', fontSize: '15px', color: COLORS.textHex }).setOrigin(0.5); + c.add([ring, g, t]); + this.badges[seat] = { c, ring, t, tw: null }; + } + } + + buildHands() { + for (let seat = 1; seat < this.playerCount; seat++) { + const home = handHome(this.L, seat); + const k = this.L.seats[seat].hand.k; + const img = this.add.image(home.x, home.y, 'nerts-hand') + .setTint(SEAT_COLORS[seat]).setAlpha(0.2).setRotation(home.rot) + .setScale(0.6 * (0.5 + k)).setDepth(D.ghost); + this.hands[seat] = { img, home, tw: null, ret: null }; + } + } + + buildTopButtons() { + const acts = { Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Phases: () => this.openPhases() }; + for (const b of TOP_BUTTONS) { + new Button(this, b.x, b.y, b.label, () => { if (!this.modal) acts[b.label](); }, { + variant: 'ghost', width: b.w, height: b.h, fontSize: 17, + }).setDepth(D.ui); + } + this.add.text(KEYS_BOX.x0, KEYS_BOX.y0 + 2, 'D draw · T take · A auto-fill · Enter lay down · X discard\nP hit all · S sort · H hint · 1-0 pick a card · Esc menu', { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#c9b08a', lineSpacing: 2, + }).setOrigin(0, 0).setDepth(D.ui).setAlpha(0.75); + } + + buildDock() { + const w = DOCK.x1 - DOCK.x0, h = DOCK.y1 - DOCK.y0; + const cx = (DOCK.x0 + DOCK.x1) / 2, cy = (DOCK.y0 + DOCK.y1) / 2; + const key = ensureLeatherPanel(this, 'p10-dock', w, h, { radius: 16 }); + this.add.image(cx, cy, key).setDepth(D.ui - 1); + this.prompt = this.add.text(cx, DOCK.y0 + 46, '', { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex, align: 'center', + wordWrap: { width: w - 34 }, lineSpacing: 3, + }).setOrigin(0.5).setDepth(D.ui); + this.dockBtns = []; + this.dockActs = []; + const spots = [[cx - 76, DOCK.y0 + 118], [cx + 76, DOCK.y0 + 118], [cx - 76, DOCK.y0 + 176], [cx + 76, DOCK.y0 + 176]]; + spots.forEach(([x, y], i) => { + const b = new Button(this, x, y, '', () => { if (!this.modal) this.dockActs[i]?.(); }, { + width: 144, height: 46, fontSize: 16, + }).setDepth(D.ui).setVisible(false); + this.dockBtns.push(b); + }); + } + + buildSortRow() { + const lbl = this.add.text(SORT_ROW.xs[0] - SORT_ROW.w / 2, SORT_ROW.y - 36, 'SORT HAND', { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#c9b08a', }).setOrigin(0, 0.5).setDepth(D.ui); - - new Button(this, 55, GAME_HEIGHT - 20, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 110, height: 40, fontSize: 18, - }).setDepth(D.ui); - new Button(this, 55, GAME_HEIGHT - 60, 'New', () => this.startNewMatch(), { - variant: 'ghost', width: 110, height: 40, fontSize: 18, - }).setDepth(D.ui); - - } - - // ── Drag-and-drop hand reordering ─────────────────────────────────────── - - 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', (pointer) => { - if (this.potentialDrag) { - const handIdx = this.potentialDrag.handIdx; - this.potentialDrag = null; - this.onHandClick(handIdx); - return; - } - if (this.dragState) { - this.endCardDrag(); - } + void lbl; + const opts = [['number', '1·2·3'], ['color', 'Color'], ['phase', 'Phase']]; + this.sortBtns = opts.map(([mode, text], i) => { + const b = new Button(this, SORT_ROW.xs[i], SORT_ROW.y, text, () => { + if (this.modal) return; + this.settings.sort = mode; + this.saveSettings(); + this.sortHand(); + this.layout(); + this.refreshSortButtons(); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.35, rate: 1.4 }); + }, { width: SORT_ROW.w, height: SORT_ROW.h, fontSize: 15, variant: 'ghost' }).setDepth(D.ui); + b.mode = mode; + return b; }); + this.refreshSortButtons(); } - onHandPointerDown(handIdx, pointer) { - if (this.dragState) return; - const card = this.localHandCards[handIdx]; - if (!card) return; - this.potentialDrag = { - handIdx, - startX: pointer.x, - startY: pointer.y, - offsetX: pointer.x - card.x, - offsetY: pointer.y - card.y, - }; + refreshSortButtons() { + for (const b of this.sortBtns ?? []) b.setActive(b.mode === this.settings.sort); } - startCardDrag(handIdx, offsetX, offsetY) { - const card = this.localHandCards[handIdx]; - if (!card) return; - const n = this.gs.players[0].hand.length; - const insertIdx = Phaser.Math.Clamp(Math.round((card.x - 460) / HAND_SPREAD), 0, n - 1); - - 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.transientObjs.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(460 + insertIdx * HAND_SPREAD, 990); - slotIndicator.setDepth(D.card - 1); - this.transientObjs.push(slotIndicator); - - this.dragState = { cardIdx: handIdx, offsetX, offsetY, prevX: card.x, shadow, slotIndicator, insertIdx, dropTarget: null, actionHighlight: null }; - - card.setDepth(D.card + 10); - this.tweens.add({ targets: card, scaleX: 1.08, scaleY: 1.08, duration: 120, ease: 'Cubic.easeOut' }); - } - - 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 tiltRad = Phaser.Math.Clamp((pointer.x - ds.prevX) * 0.008, -0.17, 0.17); - card.setRotation(tiltRad); - ds.prevX = pointer.x; - - const newDropTarget = this._getDropTarget(card.x, card.y); - if (!this._dropTargetsEqual(newDropTarget, ds.dropTarget)) { - ds.dropTarget = newDropTarget; - this._updateActionHighlight(newDropTarget); - if (newDropTarget) { - // Entered a drop zone — hide slot indicator, settle hand to no-gap - this.tweens.killTweensOf(ds.slotIndicator); - ds.slotIndicator.setAlpha(0); - this._settleNonDraggedCards(); - } else { - // Left drop zone — restore slot indicator and gap - ds.slotIndicator.setAlpha(1); - this._updateNonDraggedCards(); - } - } - - if (!newDropTarget) { - const stagedCount = this.stagingGroups - ? this.stagingGroups.reduce((s, g) => s + g.slots.filter((id) => id !== null).length, 0) : 0; - const effectiveN = n - stagedCount; - const newInsertIdx = Phaser.Math.Clamp(Math.round((card.x - 460) / HAND_SPREAD), 0, Math.max(0, effectiveN - 1)); - if (newInsertIdx !== ds.insertIdx) { - ds.insertIdx = newInsertIdx; - this.tweens.killTweensOf(ds.slotIndicator); - this.tweens.add({ targets: ds.slotIndicator, x: 460 + newInsertIdx * HAND_SPREAD, duration: 100, ease: 'Cubic.easeOut' }); - this._updateNonDraggedCards(); - } - } - } - - _updateNonDraggedCards() { - const ds = this.dragState; - const hand = this.gs.players[0].hand; - const n = hand.length; - const stagedIds = this.stagingGroups - ? new Set(this.stagingGroups.flatMap((g) => g.slots.filter((id) => id !== null))) - : new Set(); - const others = []; - for (let i = 0; i < n; i++) { - if (i !== ds.cardIdx && !stagedIds.has(hand[i].id)) others.push(i); - } - - for (let k = 0; k < others.length; k++) { - const j = others[k]; - const finalPos = k < ds.insertIdx ? k : k + 1; - const targetX = 460 + 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' }); - } - } - - _settleNonDraggedCards() { - const ds = this.dragState; - const hand = this.gs.players[0].hand; - const n = hand.length; - const stagedIds = this.stagingGroups - ? new Set(this.stagingGroups.flatMap((g) => g.slots.filter((id) => id !== null))) - : new Set(); - let k = 0; - for (let j = 0; j < n; j++) { - if (j === ds.cardIdx) continue; - if (stagedIds.has(hand[j].id)) continue; - const cardObj = this.localHandCards[j]; - this.tweens.killTweensOf(cardObj); - this.tweens.add({ targets: cardObj, x: 460 + k * HAND_SPREAD, rotation: 0, scaleX: 1, scaleY: 1, duration: 100, ease: 'Cubic.easeOut' }); - k++; - } - } - - endCardDrag() { - const ds = this.dragState; - const card = this.localHandCards[ds.cardIdx]; - const n = this.gs.players[0].hand.length; - const dropTarget = this._getDropTarget(card.x, card.y); - - // ── Discard path ────────────────────────────────────────────────────── - if (dropTarget?.type === 'discard') { - if (this._hasStagedCards()) { - this.tweens.killTweensOf(card); - this._settleNonDraggedCards(); - this.dragState = null; - this.tweens.add({ targets: card, x: 460 + ds.cardIdx * HAND_SPREAD, y: 990, rotation: 0, scaleX: 1, scaleY: 1, duration: 200, ease: 'Back.easeOut' }); - this.setStatus('Submit or clear your phase first — you have cards staged.'); - this._shakeStagingButtons(); - return; - } - const handIdx = ds.cardIdx; - const handCard = this.gs.players[0].hand[handIdx]; - this.tweens.killTweensOf(card); - this._settleNonDraggedCards(); - this.dragState = null; - - if (handCard.value === 'skip') { - // Snap back to hand, then immediately open skip-target modal. - this.tweens.add({ targets: card, x: 460 + handIdx * HAND_SPREAD, y: 990, rotation: 0, scaleX: 1, scaleY: 1, duration: 140, ease: 'Back.easeOut' }); - this.time.delayedCall(160, () => { this.renderAll(); this.openSkipTargetModal(handIdx); }); - return; - } - - this.tweens.add({ - targets: card, x: DISCARD_POS.x, y: DISCARD_POS.y, rotation: 0, scaleX: 1, scaleY: 1, - duration: 160, ease: 'Cubic.easeOut', - onComplete: () => { this.selectedHandIdx = handIdx; this.commitDiscard(handIdx); }, - }); - return; - } - - // ── Hit path ────────────────────────────────────────────────────────── - if (dropTarget?.type === 'hit') { - const handIdx = ds.cardIdx; - const target = { targetSeat: dropTarget.targetSeat, groupIdx: dropTarget.groupIdx, position: dropTarget.position }; - const gc = this._getGroupCenter(target); - this.tweens.killTweensOf(card); - this._settleNonDraggedCards(); - this.dragState = null; - - this.tweens.add({ - targets: card, x: gc ? gc.x : card.x, y: gc ? gc.y : card.y, rotation: 0, scaleX: 1, scaleY: 1, - duration: 160, ease: 'Cubic.easeOut', - onComplete: () => { this.selectedHandIdx = handIdx; this.commitHit(target); }, - }); - return; - } - - // ── Stage path ──────────────────────────────────────────────────────── - if (dropTarget?.type === 'stage') { - const { groupIdx } = dropTarget; - const g = this.stagingGroups[groupIdx]; - const emptySlotIdx = g.slots.indexOf(null); - if (emptySlotIdx !== -1) { - const handCard = this.gs.players[0].hand[ds.cardIdx]; - for (const sg of this.stagingGroups) { - const old = sg.slots.indexOf(handCard.id); - if (old !== -1) { sg.slots[old] = null; break; } - } - g.slots[emptySlotIdx] = handCard.id; - const pos = this._getStagingSlotPos(groupIdx, emptySlotIdx); - const scale = LAIDOWN_CARD_W / CARD_W; - this.tweens.killTweensOf(card); - this._settleNonDraggedCards(); - this.dragState = null; - this.tweens.add({ - targets: card, x: pos.x, y: pos.y, rotation: 0, scaleX: scale, scaleY: scale, - duration: 160, ease: 'Cubic.easeOut', - onComplete: () => this.renderAll(), + buildTooltips() { + this.tip = new Tooltip(this, { depth: D.modal - 2, hoverDelay: 220 }); + const zone = (x, y, w, h, fn) => { + const z = this.add.zone(x, y, w, h).setInteractive(); + z.isP10Zone = true; + let timer = null; + z.on('pointerover', () => { + timer?.remove(false); + timer = this.time.delayedCall(220, () => { + const content = this.modal || this.dragState ? null : fn(); + if (!content) return; + this.tip.setContent(content); + this.tip._owner = z; + const ptr = this.input.activePointer; + this.tip._reposition(ptr.x, ptr.y); + this.tip.container.setVisible(true); }); - return; - } + }); + z.on('pointerout', () => { timer?.remove(false); timer = null; if (this.tip._owner === z) this.tip.hide(); }); + return z; + }; + for (let seat = 1; seat < this.playerCount; seat++) { + const pl = this.L.seats[seat].plate; + zone(pl.x, pl.y, PLATE.w, PLATE.h, () => this.seatTip(seat)); } - - // ── Reorder path (existing) ─────────────────────────────────────────── - // Clear staging slot if this card was staged - if (this.stagingGroups) { - const handCard = this.gs.players[0].hand[ds.cardIdx]; - for (const sg of this.stagingGroups) { - const old = sg.slots.indexOf(handCard.id); - if (old !== -1) { sg.slots[old] = null; break; } - } - } - const finalIdx = Phaser.Math.Clamp(Math.round((card.x - 460) / HAND_SPREAD), 0, n - 1); - - this.selectedHandIdx = null; - - this.tweens.killTweensOf(card); - this.tweens.add({ targets: card, x: 460 + finalIdx * HAND_SPREAD, y: 990, 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 cardObj = this.localHandCards[j]; - this.tweens.killTweensOf(cardObj); - this.tweens.add({ targets: cardObj, x: 460 + finalPos * HAND_SPREAD, rotation: 0, scaleX: 1, scaleY: 1, duration: 120, ease: 'Cubic.easeOut' }); - } - - const hand = this.gs.players[0].hand; - const [moved] = hand.splice(ds.cardIdx, 1); - hand.splice(finalIdx, 0, moved); - - this.dragState = null; - this.time.delayedCall(240, () => this.renderAll()); + const d = this.L.discard; + zone(d.x, d.y, CARD_W * d.s + 20, CARD_H * d.s * SQ + 20, () => this.discardTip()); } - _getStagingSlotPos(gi, si) { - const { laidStart } = slotLayout('bottom'); - let cx = laidStart.x; - for (let k = 0; k < gi; k++) { - cx += this.stagingGroups[k].count * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25) + GROUP_GAP; - } - return { x: cx + si * (LAIDOWN_CARD_W * 0.75) + LAIDOWN_CARD_W / 2, y: laidStart.y }; + seatTip(seat) { + if (!this.gs) return null; + const p = this.gs.players[seat]; + const ph = getPhase(p.phase); + const lines = [ + { text: p.clearedAt != null ? 'Finished all ten phases' : `Phase ${p.phase}: ${ph?.short ?? ''}`, color: COLORS.goldHex }, + { text: `${p.hand.length} card${p.hand.length === 1 ? '' : 's'} in hand` }, + { text: p.laidDown ? 'Phase laid down ✓ — can hit' : 'Phase not laid down yet', color: p.laidDown ? '#8ce99a' : COLORS.mutedHex }, + { text: `Score ${p.score} (lower is better)` }, + { text: `Skill ${this.skillFor(seat)} / 5`, color: COLORS.mutedHex }, + ]; + if (p.skipped) lines.push({ text: 'Next turn will be skipped', color: '#ff8a7a' }); + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; } - _getStagingGroupBounds(gi) { - const { laidStart } = slotLayout('bottom'); - let cx = laidStart.x; - for (let k = 0; k < gi; k++) { - cx += this.stagingGroups[k].count * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25) + GROUP_GAP; - } - const gw = this.stagingGroups[gi].count * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25); - return { cx: cx + gw / 2, cy: laidStart.y, hw: gw / 2 + 16, hh: LAIDOWN_CARD_H / 2 + 16 }; - } - - renderStagingArea() { - if (!this.stagingGroups) return; - const { laidStart } = slotLayout('bottom'); - - let totalW = 0; - for (let gi = 0; gi < this.stagingGroups.length; gi++) { - if (gi > 0) totalW += GROUP_GAP; - totalW += this.stagingGroups[gi].count * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25); - } - - const PX = 14, LABEL_H = 22, PY = 8; - const panelX = laidStart.x - PX; - const panelY = laidStart.y - LAIDOWN_CARD_H / 2 - LABEL_H - PY; - const panelW = totalW + PX * 2; - const panelH = LAIDOWN_CARD_H + LABEL_H + PY * 2; - - const bg = this.add.graphics().setDepth(D.card - 2); - bg.fillStyle(COLORS.panel, 0.92); - bg.fillRoundedRect(panelX, panelY, panelW, panelH, 10); - bg.lineStyle(2, COLORS.accent, 0.6); - bg.strokeRoundedRect(panelX, panelY, panelW, panelH, 10); - this.transientObjs.push(bg); - - let cx = laidStart.x; - for (let gi = 0; gi < this.stagingGroups.length; gi++) { - const g = this.stagingGroups[gi]; - const gw = g.count * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25); - const kindLabel = g.kind === 'set' ? `Set of ${g.count}` - : g.kind === 'run' ? `Run of ${g.count}` - : `${g.count} of one color`; - const lbl = this.add.text(cx + gw / 2, panelY + PY + 2, kindLabel, { - fontFamily: 'Righteous', fontSize: '13px', color: COLORS.goldHex, - }).setOrigin(0.5, 0).setDepth(D.card - 1); - this.transientObjs.push(lbl); - - for (let si = 0; si < g.count; si++) { - if (g.slots[si] === null) { - const pos = this._getStagingSlotPos(gi, si); - const sg = this.add.graphics().setDepth(D.card - 1); - sg.lineStyle(2, COLORS.accent, 0.35); - sg.strokeRoundedRect(pos.x - LAIDOWN_CARD_W / 2, pos.y - LAIDOWN_CARD_H / 2, LAIDOWN_CARD_W, LAIDOWN_CARD_H, 6); - sg.fillStyle(COLORS.accent, 0.04); - sg.fillRoundedRect(pos.x - LAIDOWN_CARD_W / 2, pos.y - LAIDOWN_CARD_H / 2, LAIDOWN_CARD_W, LAIDOWN_CARD_H, 6); - this.transientObjs.push(sg); - } - } - cx += gw + GROUP_GAP; - } - - } - - submitStagingLaydown() { - const player = this.gs.players[0]; - for (let gi = 0; gi < this.stagingGroups.length; gi++) { - if (this.stagingGroups[gi].slots.some((s) => s === null)) { - this.setStatus(`Group ${gi + 1} needs ${this.stagingGroups[gi].count} cards — fill all slots.`); - return; - } - } - const resolved = this.stagingGroups.map((g) => ({ - kind: g.kind, - cards: g.slots.map((id) => player.hand.find((c) => c.id === id)), + discardTip() { + if (!this.gs || !this.discardLog.length) return null; + const recent = this.discardLog.slice(-7).reverse(); + const lines = recent.map(({ card, seat }) => ({ + text: `${seat < 0 ? 'Turned up' : this.shortName(seat, 14)} — ${cardName(card)}`, + color: seat < 0 ? COLORS.mutedHex : SEAT_HEX[seat], })); - const vr = validateLaydown(player.phase, resolved); - if (!vr.ok) { - this.setStatus(`Invalid: ${vr.reason}`); - return; - } - const next = applyLaydown(this.gs, this.stagingGroups.map((g) => ({ - kind: g.kind, cardIds: g.slots.slice(), - }))); - if (next === this.gs) { - this.setStatus("Couldn't lay down — check your cards."); - return; - } - this.stagingGroups = null; - this._destroyStagingButtons(); - this.gs = next; - this.selectedHandIdx = null; - this.clearHighlights(); - this.renderAll(); - this.setStatus('Laid down! Now hit or discard.'); + return { title: 'Recent discards', lines }; } - clearStagingLaydown() { - if (!this.stagingGroups) return; - for (const g of this.stagingGroups) g.slots.fill(null); - this.renderAll(); - } - - _dropTargetsEqual(a, b) { - if (!a && !b) return true; - if (!a || !b) return false; - if (a.type !== b.type) return false; - if (a.type === 'hit') return a.targetSeat === b.targetSeat && a.groupIdx === b.groupIdx && a.position === b.position; - return true; - } - - _getDropTarget(cardX, cardY) { - if (!this.isLocalTurn() || !this.gs.drawnThisTurn) return null; - const handCard = this.gs.players[0].hand[this.dragState.cardIdx]; - - // Staging area drop targets - if (this.stagingGroups && !this.gs.players[0].laidDown) { - for (let gi = 0; gi < this.stagingGroups.length; gi++) { - if (!this.stagingGroups[gi].slots.some((s) => s === null)) continue; - const b = this._getStagingGroupBounds(gi); - if (Math.abs(cardX - b.cx) < b.hw && Math.abs(cardY - b.cy) < b.hh) { - return { type: 'stage', groupIdx: gi }; - } - } - } - - // Discard pile — generous hit area - if (Math.abs(cardX - DISCARD_POS.x) < CARD_W && Math.abs(cardY - DISCARD_POS.y) < CARD_H) { - return { type: 'discard' }; - } - - // Hit targets — only when the local player has already laid down - if (this.gs.players[0].laidDown) { - const targets = getHitTargets(this.gs, handCard); - // Bucket by group so runs with both low+high positions are handled together. - const byGroup = new Map(); - for (const t of targets) { - const key = `${t.targetSeat}:${t.groupIdx}`; - if (!byGroup.has(key)) byGroup.set(key, []); - byGroup.get(key).push(t); - } - for (const groupTargets of byGroup.values()) { - const gc = this._getGroupCenter(groupTargets[0]); - if (!gc) continue; - if (Math.abs(cardX - gc.x) < gc.w / 2 + 20 && Math.abs(cardY - gc.y) < gc.h / 2 + 20) { - if (groupTargets.length === 1) return { type: 'hit', ...groupTargets[0] }; - // Run with both low and high: pick based on which side the card is on. - const low = groupTargets.find((t) => t.position === 'low'); - const high = groupTargets.find((t) => t.position === 'high'); - const chosen = (low && cardX < gc.x) ? low : (high ?? low); - return { type: 'hit', ...chosen }; - } - } - } - - return null; - } - - _getGroupCenter(target) { - const slot = this.slotForSeat[target.targetSeat]; - const layout = slotLayout(slot); - const laid = this.gs.players[target.targetSeat].laidDown; - if (!laid) return null; - - let cursorX = layout.laidStart.x; - let cursorY = layout.laidStart.y; - for (let gi = 0; gi < laid.length; gi++) { - const group = laid[gi]; - const N = group.cards.length; - const groupW = N * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25); - if (gi === target.groupIdx) { - if (layout.laidAxis === 'x') { - const cx = cursorX + groupW / 2; - return { x: cx, y: cursorY, w: groupW + 6, h: LAIDOWN_CARD_H + 8, lowX: cursorX - 8, highX: cursorX + groupW + 8, axis: 'x' }; - } else { - const groupH = N * (LAIDOWN_CARD_H * 0.5) + (LAIDOWN_CARD_H * 0.5); - return { x: cursorX, y: cursorY + groupH / 2, w: LAIDOWN_CARD_W + 8, h: groupH + 6, axis: 'y' }; - } - } - if (layout.laidAxis === 'x') cursorX += groupW + GROUP_GAP; - else cursorY += N * (LAIDOWN_CARD_H * 0.5) + GROUP_GAP; - } - return null; - } - - _updateActionHighlight(dropTarget) { - const ds = this.dragState; - if (ds.actionHighlight) { - const idx = this.transientObjs.indexOf(ds.actionHighlight); - if (idx !== -1) this.transientObjs.splice(idx, 1); - ds.actionHighlight.destroy(); - ds.actionHighlight = null; - } - if (!dropTarget) return; - - const g = this.add.graphics(); - if (dropTarget.type === 'discard') { - const px = DISCARD_POS.x - CARD_W / 2 - 8; - const py = DISCARD_POS.y - CARD_H / 2 - 8; - g.lineStyle(4, 0xff6b6b, 1); - g.strokeRoundedRect(px, py, CARD_W + 16, CARD_H + 16, 10); - g.fillStyle(0xff6b6b, 0.18); - g.fillRoundedRect(px, py, CARD_W + 16, CARD_H + 16, 10); - } else if (dropTarget.type === 'hit') { - const gc = this._getGroupCenter(dropTarget); - if (gc) { - g.lineStyle(4, 0xffd700, 1); - g.strokeRoundedRect(gc.x - gc.w / 2, gc.y - gc.h / 2, gc.w, gc.h, 8); - g.fillStyle(0xffd700, 0.22); - g.fillRoundedRect(gc.x - gc.w / 2, gc.y - gc.h / 2, gc.w, gc.h, 8); - } - } else if (dropTarget.type === 'stage') { - const b = this._getStagingGroupBounds(dropTarget.groupIdx); - g.lineStyle(4, COLORS.accent, 1); - g.strokeRoundedRect(b.cx - b.hw, b.cy - b.hh, b.hw * 2, b.hh * 2, 8); - g.fillStyle(COLORS.accent, 0.18); - g.fillRoundedRect(b.cx - b.hw, b.cy - b.hh, b.hw * 2, b.hh * 2, 8); - } - g.setDepth(D.highlight); - ds.actionHighlight = g; - this.transientObjs.push(g); - } - - endCardDragImmediate() { - if (!this.dragState) return; - const ds = this.dragState; - const card = this.localHandCards[ds.cardIdx]; - this.tweens.killTweensOf(card); - this.tweens.killTweensOf(ds.slotIndicator); - - const hand = this.gs.players[0].hand; - const [moved] = hand.splice(ds.cardIdx, 1); - hand.splice(ds.insertIdx, 0, moved); - - this.selectedHandIdx = null; + // ── Round lifecycle ────────────────────────────────────────────────────────── + clearTable() { + for (const c of this.sprites.values()) { c._tw?.stop(); c.destroy(); } + this.sprites.clear(); + this.lastLoc = new Map(); + for (const o of this.fx) o.destroy?.(); + this.fx = []; + this.stage = null; + this.selectedId = null; + this.hoverId = null; this.dragState = null; this.potentialDrag = null; + this.clearDropPreview(); + this.revealAll = false; + this.targetG.clear(); + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.skipStamp.setVisible(false); } + this.skipShown = new Array(this.playerCount).fill(false); + this.plateHold = null; + this.plateTally = null; } - // ── Match lifecycle ────────────────────────────────────────────────────── - - startNewMatch() { - if (this.animating) return; - this.matchOver = false; - if (this.dragState) this.endCardDragImmediate(); - this.stagingGroups = null; - this._destroyStagingButtons(); - this.clearAllCardObjs(); - this.clearHighlights(); - this.selectedHandIdx = null; - - const playerCount = this.slotForSeat.length; - this.gs = createInitialState({ playerCount }); + async startRound() { + this.clearTable(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + const gs = this.gs; + const n = this.playerCount; + this.discardLog = gs.discardPile.map(card => ({ card, seat: -1 })); + this.prevHandSizes = gs.players.map(p => p.hand.length); + const from = { ...this.L.deck, y: this.L.deck.y - 10 }; + for (const p of gs.players) for (const card of p.hand) this.lastLoc.set(card.id, { pose: from, faceUp: false, depth: D.fly }); + for (const card of gs.discardPile) this.lastLoc.set(card.id, { pose: from, faceUp: false, depth: D.fly }); + this.sortHand(); + this.updatePlates(); + this.updateDock(); playSound(this, SFX.CARD_SHUFFLE); - this.renderAll(); - this.setStatus('Your turn — draw from deck or discard.'); - this.maybeStartAITurn(); + const start = gs.currentPlayer; + const order = (seat) => (seat - start + n) % n; + const dealOrder = new Map(); + gs.players.forEach(p => { + // deal order follows the logical deal (i-th card to each seat in turn), not the sorted fan + const dealt = [...p.hand].sort((a, b) => a.id - b.id); + dealt.forEach((c, i) => dealOrder.set(c.id, i * n + order(p.seat))); + }); + const step = 42; + const last = 10 * n * step; + let ticks = 0; + this.layout({ + duration: 300, + delayFor: (v) => { + if (v.kind === 'discard') return 280 + last + 160; + const k = dealOrder.get(v.card.id) ?? 0; + return 280 + k * step; + }, + }); + for (let i = 0; i < 10 * n; i += 4) this.time.delayedCall(300 + i * step, () => { if (ticks++ < 20) playSoundEx(this, SFX.CARD_DEAL, { volume: 0.45 }); }); + await this.wait(280 + last + 560); + if (!this.alive() || token !== this.turnToken) return; + this.beginTurn(); } - // ── Card sprite factory ───────────────────────────────────────────────── + beginTurn() { + if (!this.alive()) return; + const gs = this.gs; + if (gs.roundPhase !== 'play') { this.onRoundOver(); return; } + const seat = gs.currentPlayer; + this.setSpot(seat); + this.updatePlates(); + if (seat === 0) { + this.mode = 'human'; + this.stage = null; + this.selectedId = null; + this.layout(); + this.updateDock(); + playSoundEx(this, SFX.UI_PICK, { volume: 0.4 }); + } else { + this.mode = 'ai'; + this.selectedId = null; + this.layout(); + this.updateDock(); + this.runAITurn(seat); + } + } - 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); + // Apply a new state; report skip consumption, last-card warnings, recycles. + commit(next, { thrower = null } = {}) { + const prev = this.gs; + const deckWas = prev.drawPile.length; + this.gs = next; + if (prev.roundPhase === 'play' && next.roundPhase !== 'play') { + // hold the plates at their pre-round numbers until the count-back runs + this.plateHold = prev.players.map(p => ({ score: p.score, phase: p.phase, clearedAt: p.clearedAt })); + this.plateTally = prev.players.map(() => 0); + } + // the turn moved on: every seat strictly between the old and new player was skipped + const passed = []; + if (next.roundPhase === 'play' && next.turnCount !== prev.turnCount) { + const n = next.players.length; + for (let s = (prev.currentPlayer + 1) % n; s !== next.currentPlayer; s = (s + 1) % n) passed.push(s); + } + for (const s of passed) { + this.skipShown[s] = false; + const pl = this.plates[s]; + pl.skipStamp.setVisible(true).setScale(2.2).setAlpha(0); + this.tweens.add({ targets: pl.skipStamp, scale: 1, alpha: 1, duration: 200, ease: 'Back.easeOut' }); + this.tweens.add({ targets: pl.skipStamp, alpha: 0, delay: 1500, duration: 400, onComplete: () => { if (!this.skipShown[s]) pl.skipStamp.setVisible(false).setAlpha(1); } }); + this.floatText({ x: pl.x, y: pl.y + (s === 0 ? -64 : 66) }, s === 0 ? 'Your turn is skipped!' : 'Turn skipped!', '#ff8a7a', { size: 24, ms: 1600 }); + if (s > 0) this.portraits[s]?.playEmotion?.('upset'); + } + next.players.forEach((p, s) => { + if (p.skipped && !this.skipShown[s]) { + this.skipShown[s] = true; + const st = this.plates[s].skipStamp; + st.setVisible(true).setScale(2.4).setAlpha(0); + this.tweens.add({ targets: st, scale: 1, alpha: 1, duration: 220, ease: 'Back.easeOut' }); + this.cameras.main.shake(140, 0.004); + } + }); + if (deckWas === 0 && next.drawPile.length > 0 && next.roundPhase === 'play') { + this.floatText({ x: this.L.deck.x, y: this.L.deck.y - 70 }, 'Discards reshuffled', '#f2d6a0', { size: 20, ms: 1500 }); + playSound(this, SFX.CARD_SHUFFLE); + } + next.players.forEach((p, s) => { + const before = this.prevHandSizes[s] ?? p.hand.length; + if (p.hand.length === 1 && before !== 1 && next.roundPhase === 'play') { + const at = s === 0 ? { x: CX, y: 880 } : handBadge(this.L, s); + this.floatText(at, s === 0 ? 'Last card!' : `${this.shortName(s)}: last card!`, '#ffb15a', { size: 24, ms: 1600 }); + } + }); + this.prevHandSizes = next.players.map(p => p.hand.length); + if (thrower !== null) { + const top = discardTop(next); + if (top) this.discardLog.push({ card: top, seat: thrower }); + } + // forget cards that left the pile (taken, or reshuffled into the deck) + const inPile = new Set(next.discardPile.map(c => c.id)); + this.discardLog = this.discardLog.filter(e => inPile.has(e.card.id)); + this.updatePlates(); + } + + // ── AI ────────────────────────────────────────────────────────────────────── + async runAITurn(seat) { + const token = ++this.turnToken; + const T = this.timing(seat); + const still = () => this.alive() && token === this.turnToken && this.gs.roundPhase === 'play' && this.gs.currentPlayer === seat; + await this.wait(T.think); + let guard = 0; + while (still() && guard++ < 40) { + const action = chooseAction(this.gs, { skill: this.skillFor(seat) }); + if (!action) break; + const ok = await this.aiPlay(seat, action, T); + if (!this.alive() || token !== this.turnToken) return; + if (this.gs.roundPhase !== 'play') { this.onRoundOver(); return; } + if (!ok || action.type === 'discard') break; + await this.wait(T.between); + } + if (!this.alive() || token !== this.turnToken) return; + if (this.gs.roundPhase !== 'play') { this.onRoundOver(); return; } + if (this.gs.currentPlayer === seat) { + // safety net: never let an AI turn stall the table + const next = applyDiscard(this.gs, 0, skipTargets(this.gs, seat)[0] ?? null); + if (next !== this.gs) this.commit(next, { thrower: seat }); + } + this.layout(); + this.beginTurn(); + } + + async aiPlay(seat, action, T) { + const gs = this.gs; + const player = gs.players[seat]; + if (action.type === 'drawDeck' || action.type === 'drawDiscard') { + const fromDiscard = action.type === 'drawDiscard'; + const src = fromDiscard ? this.sprites.get(discardTop(gs)?.id)?.pose ?? this.L.discard : deckTopPose(this.L, gs.drawPile.length); + this.moveHand(seat, src, T.reach); + await this.wait(T.reach); + if (fromDiscard) await this.wait(T.hesitate); + const next = fromDiscard ? applyDrawFromDiscard(this.gs) : applyDrawFromDeck(this.gs); + if (next === this.gs) return false; + this.commit(next); + const hand = this.gs.players[seat].hand; + const id = hand[hand.length - 1].id; + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.55 }); + this.layout({ durationFor: (v) => (v.card.id === id ? T.carry : null) }); + this.moveHand(seat, handPose(this.L, seat, hand.length - 1, hand.length), T.carry, 'Cubic.easeOut'); + await this.wait(T.carry); + this.handRest(seat, T.carry * 0.6); + return true; + } + if (action.type === 'laydown') { + const mid = handPose(this.L, seat, Math.floor(player.hand.length / 2), player.hand.length); + this.moveHand(seat, mid, T.reach * 0.6); + await this.wait(T.reach * 0.6); + const next = applyLaydown(this.gs, action.groups); + if (next === this.gs) return false; + this.commit(next); + const ids = new Map(); + let k = 0; + for (const g of this.gs.players[seat].laidDown) for (const c of g.cards) ids.set(c.id, k++); + const per = Math.max(45, Math.min(110, T.carry * 0.22)); + this.layout({ + delayFor: (v) => (ids.has(v.card.id) ? ids.get(v.card.id) * per : 0), + durationFor: (v) => (ids.has(v.card.id) ? T.carry * 0.8 : null), + }); + this.moveHand(seat, matCentre(this.L, seat), T.carry, 'Sine.easeInOut'); + for (let i = 0; i < k; i += 2) this.time.delayedCall(i * per, () => playSoundEx(this, SFX.CARD_PLACE, { volume: 0.4 })); + await this.wait(k * per + T.carry * 0.8); + this.phaseStamp(seat, player.phase); + this.portraits[seat]?.playEmotion?.('happy'); + this.handRest(seat, T.carry * 0.6); + await this.wait(500); + return true; + } + if (action.type === 'hit') { + const card = player.hand[action.handIdx]; + if (!card) return false; + this.moveHand(seat, this.sprites.get(card.id)?.pose ?? handPose(this.L, seat, action.handIdx, player.hand.length), T.reach * 0.6); + await this.wait(T.reach * 0.6); + const next = applyHit(this.gs, action.handIdx, action.targetSeat, action.groupIdx, action.position); + if (next === this.gs) return false; + this.commit(next); + this.layout({ durationFor: (v) => (v.card.id === card.id ? T.carry : null) }); + const to = this.poseOf(card.id); + if (to) this.moveHand(seat, to, T.carry, 'Cubic.easeOut'); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.6 }); + await this.wait(T.carry); + if (to) this.floatText(to, 'Hit!', SEAT_HEX[seat], { size: 22, rise: 32 }); + if (action.targetSeat === 0 && action.targetSeat !== seat) this.floatText({ x: to?.x ?? CX, y: (to?.y ?? CY) - 30 }, `on your ${this.shortGroup(0, action.groupIdx)}`, SEAT_HEX[seat], { size: 17, rise: 26, ms: 1100 }); + this.handRest(seat, T.carry * 0.6); + return true; + } + if (action.type === 'discard') { + const card = player.hand[action.handIdx]; + if (!card) return false; + this.moveHand(seat, this.sprites.get(card.id)?.pose ?? handPose(this.L, seat, action.handIdx, player.hand.length), T.reach * 0.6); + await this.wait(T.reach * 0.6); + const next = applyDiscard(this.gs, action.handIdx, action.skipTargetSeat ?? null); + if (next === this.gs) return false; + this.commit(next, { thrower: seat }); + this.layout({ durationFor: (v) => (v.card.id === card.id ? T.carry : null) }); + this.moveHand(seat, this.L.discard, T.carry, 'Cubic.easeOut'); + await this.wait(T.carry); + if (card.value === 'skip') this.skipSlam(seat, action.skipTargetSeat); + else playSoundEx(this, SFX.CARD_PLACE, { volume: 0.55 }); + this.handRest(seat, T.carry * 0.7); + return true; + } + return false; + } + + shortGroup(seat, gi) { + const g = this.gs.players[seat].laidDown?.[gi]; + if (!g) return 'phase'; + return g.kind === 'run' ? 'run' : g.kind === 'set' ? 'set' : 'color group'; + } + + poseOf(id) { + const v = this._lastVisible?.get(id); + return v?.pose ?? null; + } + + moveHand(seat, pt, duration, ease = 'Sine.easeInOut') { + const h = this.hands[seat]; + if (!h) return; + h.tw?.stop(); + h.ret?.remove(false); + h.img.setAlpha(0.66); + h.tw = this.tweens.add({ targets: h.img, x: pt.x, y: pt.y + 6, duration: Math.max(60, duration), ease }); + } + + handRest(seat, duration, delay = 0) { + const h = this.hands[seat]; + if (!h) return; + h.ret?.remove(false); + h.ret = this.time.delayedCall(delay, () => { + h.tw?.stop(); + h.tw = this.tweens.add({ targets: h.img, x: h.home.x, y: h.home.y, alpha: 0.2, duration: Math.max(80, duration), ease: 'Sine.easeInOut' }); + }); + } + + // ── Layout: put every card where the state says it is ────────────────────── + stagedIds() { + const s = new Set(); + if (this.stage) for (const g of this.stage) for (const id of g) s.add(id); + return s; + } + + stageCards(gi) { + const hand = this.me().hand; + return (this.stage?.[gi] ?? []).map(id => hand.find(c => c.id === id)).filter(Boolean); + } + + // Display order of a group being staged (complete runs in position order). + stageOrder(kind, count, cards) { + if (kind === 'run' && cards.length === count && groupStatus(kind, count, cards).ok) return orderGroupCards('run', cards); + if (kind === 'run') return [...cards.filter(isNum).sort((a, b) => a.value - b.value), ...cards.filter(c => !isNum(c))]; + return orderGroupCards(kind, cards); + } + + computeLayout() { + const L = this.L, gs = this.gs; + const visible = new Map(); + const loc = new Map(); + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + const dn = gs.drawPile.length; + gs.drawPile.forEach((card, i) => { + const pose = deckTopPose(L, dn); + if (i === dn - 1) put(card, { kind: 'deck', pose, faceUp: false, depth: D.cards + 1 }); + else loc.set(card.id, { pose, faceUp: false, depth: D.cards }); + }); + const pn = gs.discardPile.length; + gs.discardPile.forEach((card, i) => { + const base = discardPose(L, i, pn); + const j = jitterFor(`p10-${card.id}`); + const pose = { ...base, x: base.x + j.x * 3, y: base.y + j.y * 2, rot: j.rot * 3 }; + if (i >= pn - 3) put(card, { kind: 'discard', pose, faceUp: true, depth: D.cards + 1 + (i - pn + 3) * 0.01 }); + else loc.set(card.id, { pose, faceUp: true, depth: D.cards }); + }); + const staged = this.stagedIds(); + for (const p of gs.players) { + const seat = p.seat; + if (seat === 0) { + // while a card is dragged over the hand, the rest open a gap where it would land + const order = this.dragPreview; + const held = order + ? order.map(id => p.hand.find(c => c.id === id)).filter(Boolean) + : p.hand.filter(c => !staged.has(c.id)); + held.forEach((card, i) => { + const lift = card.id === this.selectedId ? 46 : card.id === this.hoverId ? 24 : 0; + put(card, { kind: 'hand', seat, idx: i, pose: handPose(L, 0, i, held.length, lift), faceUp: true, depth: D.hand + i * 0.01 }); + }); + } else { + p.hand.forEach((card, i) => { + put(card, { kind: 'hand', seat, idx: i, pose: handPose(L, seat, i, p.hand.length), faceUp: this.revealAll, depth: D.oppHand + i * 0.01 }); + }); + } + if (p.laidDown) { + const gc = p.laidDown.length; + p.laidDown.forEach((g, gi) => { + const vals = g.kind === 'run' ? runAssignedValues(g) : null; + g.cards.forEach((card, ci) => { + put(card, { + kind: 'laid', seat, gi, ci, pose: groupCardPose(L, seat, gi, gc, ci, g.cards.length), faceUp: true, + depth: D.cards + 2 + ci * 0.01, chip: card.value === 'wild' && vals ? vals[ci] : null, + }); + }); + }); + } + } + if (this.stage) { + const spec = getPhase(this.me().phase); + const gc = spec.groups.length; + spec.groups.forEach((g, gi) => { + const cards = this.stageOrder(g.kind, g.count, this.stageCards(gi)); + const vals = g.kind === 'run' && cards.length === g.count && groupStatus(g.kind, g.count, cards).ok + ? runAssignedValues({ kind: 'run', cards }) : null; + cards.forEach((card, ci) => { + put(card, { + kind: 'stage', seat: 0, gi, ci, pose: groupCardPose(L, 0, gi, gc, ci, Math.max(g.count, cards.length)), faceUp: true, + depth: D.cards + 3 + ci * 0.01, chip: card.value === 'wild' && vals ? vals[ci] : null, + }); + }); + }); + } + return { visible, loc }; + } + + layout({ delayFor = null, duration = 260, durationFor = null } = {}) { + if (!this.gs) return; + const { visible, loc } = this.computeLayout(); + this.advice = this.settings.hints || this.mode === 'human' ? adviseHand(this.gs, 0) : null; + for (const [id, v] of visible) { + let c = this.sprites.get(id); + if (!c) { + const prev = this.lastLoc.get(id) ?? v; + c = this.makeCard(v.card, prev.faceUp, prev.pose); + c.setDepth(prev.depth); + this.sprites.set(id, c); + } + this.decorate(c, v); + if (this.dragState?.id === id) continue; + if (c._tw && samePose(c._to, v.pose) && c._toFace === v.faceUp) continue; + if (!samePose(c.pose, v.pose) || c.faceUp !== v.faceUp) { + this.tweenCard(c, v.pose, { + faceUp: v.faceUp, depth: v.depth, duration: durationFor?.(v) ?? duration, delay: delayFor ? delayFor(v) : 0, + }); + } else if (!c._tw) { + c.setDepth(v.depth); + } + } + for (const [id, c] of this.sprites) { + if (visible.has(id)) continue; + this.sprites.delete(id); + const to = loc.get(id); + c.mark.setVisible(false); + c.chip.setVisible(false); + c.glow.setVisible(false); + if (to) this.tweenCard(c, to.pose, { faceUp: to.faceUp, depth: to.depth - 0.005, duration, onDone: () => c.destroy() }); + else { c._tw?.stop(); c.destroy(); } + } + this.lastLoc = loc; + this._lastVisible = visible; + this.drawSlabs(); + this.drawMatOverlays(); + this.drawTargets(); + this.updateBadges(); + this.deckTxt.setText(this.gs.drawPile.length ? `${this.gs.drawPile.length} left` : ''); + } + + // Hint marks + wild value chips + selection glow. + decorate(c, v) { + let mark = '', color = '#ffffff'; + if (v.kind === 'hand' && v.seat === 0 && this.settings.hints && this.advice && this.mode === 'human') { + const a = this.advice; + if (this.me().laidDown) { + if (a.hittable.has(v.card.id)) { mark = '+'; color = '#7cf0a0'; } + } else if (a.keepers.has(v.card.id)) { mark = '★'; color = '#ffd35a'; } + if (a.discardId === v.card.id && this.gs.drawnThisTurn && this.gs.currentPlayer === 0) { mark = '▼'; color = '#ff9a7a'; } + } + c.mark.setText(mark).setColor(color).setVisible(!!mark && v.faceUp); + c.chip.setText(v.chip != null ? String(v.chip) : '').setVisible(v.chip != null && v.faceUp); + c.glow.setVisible(v.kind === 'hand' && v.seat === 0 && v.card.id === this.selectedId); + } + + drawSlabs() { + const g = this.slabG; + g.clear(); + const stack = (base, n) => { + if (n <= 1) return; + const lift = stackLift(n, base.s); + const layers = Math.max(1, Math.min(7, Math.ceil(lift / 1.6))); + for (let j = 0; j < layers; j++) { + const corners = cardCorners({ ...base, y: base.y - (lift * j) / layers }); + g.fillStyle(j % 2 ? 0xe9dcbd : 0xcdbf9e, 1); + g.fillPoints(corners, true); + g.lineStyle(1, 0x000000, 0.3); + g.strokePoints(corners, true); + } + }; + stack(this.L.deck, this.gs.drawPile.length); + stack(this.L.discard, Math.min(30, this.gs.discardPile.length - 2)); + } + + // Slot outlines + group labels on every mat. + drawMatOverlays() { + const g = this.slotG; + g.clear(); + const gs = this.gs; + const showStage = !!this.stage; + for (const p of gs.players) { + const seat = p.seat; + const labels = this.labels[seat]; + labels.forEach(t => t.setVisible(false)); + const spec = getPhase(p.phase); + if (p.laidDown) { + const gc = p.laidDown.length; + const areas = groupAreas(this.L, seat, gc); + p.laidDown.forEach((grp, gi) => { + const vals = grp.kind === 'run' ? runAssignedValues(grp) : null; + labels[gi].setText(laidGroupLabel(grp, vals)).setColor(SEAT_HEX[seat]).setPosition(areas[gi].cx, areas[gi].labelY).setVisible(true); + }); + continue; + } + if (!spec || p.clearedAt != null) continue; + const gc = spec.groups.length; + const areas = groupAreas(this.L, seat, gc); + spec.groups.forEach((sg, gi) => { + const area = areas[gi]; + const staging = seat === 0 && showStage; + const cards = staging ? this.stageCards(gi) : []; + const n = Math.max(sg.count, cards.length); + for (let ci = cards.length; ci < n; ci++) { + const pose = groupCardPose(this.L, seat, gi, gc, ci, n); + const { sx, sy } = poseScale(pose.s, 0, SQ); + const w = CARD_W * sx, h = CARD_H * sy; + g.fillStyle(0x000000, staging ? 0.16 : 0.1); + g.fillRoundedRect(pose.x - w / 2, pose.y - h / 2, w, h, 6); + g.lineStyle(staging ? 2 : 1.5, 0xfff4d6, staging ? 0.5 : 0.26); + g.strokeRoundedRect(pose.x - w / 2, pose.y - h / 2, w, h, 6); + } + let text = groupGoalLabel(sg.kind, sg.count), color = '#fff4d6'; + if (staging) { + const st = groupStatus(sg.kind, sg.count, cards); + text = st.text; + color = st.ok ? '#8ce99a' : st.valid ? '#fff4d6' : '#ff9a7a'; + } else if (seat > 0) { + color = '#e8d6b0'; + } + labels[gi].setText(text).setColor(color).setPosition(area.cx, area.labelY).setVisible(true); + }); + } + } + + // Glow on whatever the selected / dragged card can go to. + legalFor(id) { + if (!this.canAct() || !this.gs.drawnThisTurn) return null; + const card = this.me().hand.find(c => c.id === id); + if (!card) return null; + const out = { discard: true, stage: [], hits: [] }; + if (this.canStage() && this.stage) { + const spec = getPhase(this.me().phase); + spec.groups.forEach((sg, gi) => { + const cur = this.stageCards(gi).filter(c => c.id !== id); + if (cur.length >= sg.count) return; + const fits = groupStatus(sg.kind, sg.count, [...cur, card]).valid && card.value !== 'skip'; + out.stage.push({ gi, fits }); + }); + } + if (this.me().laidDown) out.hits = getHitTargets(this.gs, card); + return out; + } + + drawTargets(hover = null) { + const g = this.targetG; + g.clear(); + const id = this.dragState?.id ?? this.selectedId; + if (id == null) return; + const legal = this.legalFor(id); + if (!legal) return; + const box = (r, color, hot) => { + g.fillStyle(color, hot ? 0.22 : 0.08); + g.fillRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 12); + g.lineStyle(hot ? 4 : 2.5, color, hot ? 1 : 0.8); + g.strokeRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 12); + }; + if (legal.discard) { + const d = this.L.discard; + const hw = (CARD_W / 2) * d.s + 12, hh = (CARD_H / 2) * d.s * SQ + 12; + box({ x0: d.x - hw, x1: d.x + hw, y0: d.y - hh - 8, y1: d.y + hh }, 0x6cc4ff, hover?.type === 'discard'); + } + if (legal.stage.length) { + const gc = getPhase(this.me().phase).groups.length; + for (const s of legal.stage) { + box(areaRect(this.L, 0, s.gi, gc, 8), s.fits ? 0x7cf0a0 : 0xffb15a, hover?.type === 'stage' && hover.gi === s.gi); + } + } + const seen = new Set(); + for (const t of legal.hits) { + const p = this.gs.players[t.targetSeat]; + const grp = p.laidDown[t.groupIdx]; + const r = groupRect(this.L, t.targetSeat, t.groupIdx, p.laidDown.length, grp.cards.length, 1, 12); + const key = `${t.targetSeat}-${t.groupIdx}`; + const hot = hover?.type === 'hit' && hover.targetSeat === t.targetSeat && hover.groupIdx === t.groupIdx; + if (!seen.has(key)) { seen.add(key); box(r, 0xffd35a, hot); } + if (t.position) { + const x = t.position === 'low' ? r.x0 - 12 : r.x1 + 12; + const dir = t.position === 'low' ? -1 : 1; + const on = hot && hover.position === t.position; + g.fillStyle(0xffd35a, on ? 1 : 0.75); + g.fillTriangle(x + dir * 10, r.y, x - dir * 4, r.y - 11, x - dir * 4, r.y + 11); + } + } + } + + updateBadges() { + for (let seat = 1; seat < this.playerCount; seat++) { + const b = this.badges[seat]; + const n = this.gs.players[seat].hand.length; + b.t.setText(String(n)); + b.t.setColor(n <= 2 ? '#ffb15a' : COLORS.textHex); + const danger = n <= 2 && this.gs.players[seat].laidDown && this.gs.roundPhase === 'play'; + if (danger && !b.tw) { + b.ring.setAlpha(0.55); + b.tw = this.tweens.add({ targets: b.ring, alpha: 0.05, scale: 1.3, duration: 520, yoyo: true, repeat: -1 }); + } else if (!danger && b.tw) { + b.tw.stop(); b.tw = null; b.ring.setAlpha(0).setScale(1); + } + b.c.setVisible(this.gs.roundPhase === 'play' || this.mode === 'ending'); + } + } + + updatePlates() { + if (!this.gs) return; + for (let seat = 0; seat < this.playerCount; seat++) { + const p = this.plateInfo(seat); + const pl = this.plates[seat]; + pl.scoreTxt.setText(`${p.score + (this.plateTally?.[seat] ?? 0)}`); + pl.phaseTxt.setText(p.clearedAt != null ? 'All 10 done!' : `Phase ${p.phase}`); + pl.statusTxt.setText(p.laidDown ? 'laid down ✓' : '').setColor('#8ce99a'); + this.drawLadder(seat); + const active = this.gs.roundPhase === 'play' && this.gs.currentPlayer === seat && (this.mode === 'human' || this.mode === 'ai'); + if (active && !pl.glowTw) { + pl.glow.setAlpha(1); + pl.glowTw = this.tweens.add({ targets: pl.glow, alpha: 0.35, duration: 700, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + } else if (!active && pl.glowTw) { + pl.glowTw.stop(); pl.glowTw = null; pl.glow.setAlpha(0); + } + } + } + + setSpot(seat) { + const s = spotFor(this.L, seat); + this.tweens.killTweensOf(this.spot); + if (this.spot.alpha === 0) this.spot.setPosition(s.x, s.y).setDisplaySize(s.w, s.h); + this.tweens.add({ + targets: this.spot, x: s.x, y: s.y, displayWidth: s.w, displayHeight: s.h, alpha: 0.32, + duration: 420, ease: 'Sine.easeInOut', + }); + } + + // ── Card sprites ───────────────────────────────────────────────────────────── + makeCard(card, faceUp, pose) { + const c = this.add.container(pose.x, pose.y).setDepth(D.cards); + const sh = this.add.image(5, 8, 'casino-card-shadow').setScale(0.5).setAlpha(0.6); + const glow = this.add.image(0, 0, 'p10-glow').setScale(0.5).setTint(0xffd35a).setVisible(false); + const face = this.add.image(0, 0, 'p10-back').setScale(0.5); + const mark = this.add.text(-CARD_W / 2 + 22, -CARD_H / 2 - 6, '', { + fontFamily: 'sans-serif', fontSize: '22px', color: '#ffffff', stroke: '#1a0e06', strokeThickness: 5, + }).setOrigin(0.5).setVisible(false); + const chip = this.add.text(-CARD_W / 2 + 26, -CARD_H / 2 + 74, '', { + fontFamily: 'Righteous', fontSize: '24px', color: '#1a0e06', backgroundColor: '#ffd35a', padding: { x: 7, y: 1 }, + }).setOrigin(0.5).setVisible(false); + c.add([sh, glow, face, mark, chip]); + c.shadowImg = sh; + c.faceImg = face; + c.glow = glow; + c.mark = mark; + c.chip = chip; c.card = card; + this.setFace(c, faceUp); + this.applyPose(c, pose); return c; } - renderCardFace(container, card, faceUp) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); + setFace(c, faceUp) { + c.faceUp = faceUp; + if (faceUp) { + c.faceImg.setTexture('p10-cards', frameKey(c.card)).setScale(0.5); + } else if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { + c.faceImg.setTexture('cardbacks', this.cardBack.spriteIndex).setDisplaySize(CARD_W, CARD_H); + } else { + c.faceImg.setTexture('p10-back').setScale(0.5); + } + } - 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 { - this.drawCardBackGfx(g, x, y); - container.add(g); - } + applyPose(c, pose, lift = 0) { + const q = pose.q ?? SQ; + const { sx, sy } = poseScale(pose.s, pose.rot, q); + const grow = 1 + 0.08 * lift; + c.setPosition(pose.x, pose.y - lift * 18).setRotation(pose.rot).setScale(sx * grow, sy * grow); + c.pose = pose; + if (c.shadowImg) { + const ox = 5 + lift * 16, oy = 8 + lift * 26; + const cos = Math.cos(-pose.rot), sin = Math.sin(-pose.rot); + c.shadowImg.setPosition((ox * cos - oy * sin) / (sx * grow), (ox * sin + oy * cos) / (sy * grow)) + .setAlpha(0.6 - lift * 0.3); + } + } + + tweenCard(c, to, { faceUp, depth, duration = 260, delay = 0, onDone, lift = 0.55 } = {}) { + c._tw?.stop(); + const from = c.pose ?? to; + const flip = faceUp !== undefined && faceUp !== c.faceUp; + const dist = Math.hypot(to.x - from.x, to.y - from.y); + const liftAmt = dist > 12 ? lift : 0.1; + const prox = { t: 0 }; + let flipped = false; + let started = false; + c._to = to; + c._toFace = faceUp ?? c.faceUp; + c._tw = this.tweens.add({ + targets: prox, t: 1, duration, delay, ease: 'Cubic.easeOut', + onUpdate: () => { + if (!started) { started = true; c.setDepth(D.fly + (depth ?? D.cards) * 0.01); } + const t = prox.t; + const up = Math.sin(Math.PI * t) * liftAmt; + const pose = { + x: lerp(from.x, to.x, t), y: lerp(from.y, to.y, t), + rot: lerpAngle(from.rot, to.rot, t), s: lerp(from.s, to.s, t), q: lerp(from.q ?? SQ, to.q ?? SQ, t), + }; + this.applyPose(c, pose, up); + if (flip) { + if (!flipped && t >= 0.5) { flipped = true; this.setFace(c, faceUp); } + c.scaleX *= Math.max(0.03, Math.abs(Math.cos(Math.PI * t))); + } + }, + onComplete: () => { + c._tw = null; + if (flip && !flipped) this.setFace(c, faceUp); + this.applyPose(c, to); + if (depth !== undefined) c.setDepth(depth); + onDone?.(); + }, + }); + } + + // ── Effects ───────────────────────────────────────────────────────────────── + floatText(at, text, color, { size = 28, rise = 44, ms = 900 } = {}) { + const t = this.add.text(at.x, at.y - 20, text, { + fontFamily: 'Righteous', fontSize: `${size}px`, color, stroke: '#120c06', strokeThickness: 5, + }).setOrigin(0.5).setDepth(D.float); + this.tweens.add({ targets: t, y: t.y - rise, alpha: 0, delay: ms * 0.35, duration: ms * 0.65, ease: 'Cubic.easeIn', onComplete: () => t.destroy() }); + } + + stamp(text, at, color, { size = 96, sub = null, hold = 1100 } = {}) { + const t = this.add.text(at.x, at.y, text, { + fontFamily: 'Righteous', fontSize: `${size}px`, color, stroke: '#120c06', strokeThickness: Math.round(size / 9), + }).setOrigin(0.5).setDepth(D.stamp).setScale(2.6).setAlpha(0).setRotation(-0.06); + const objs = [t]; + this.tweens.add({ targets: t, scale: 1, alpha: 1, duration: 220, ease: 'Back.easeOut' }); + if (sub) { + const s = this.add.text(at.x, at.y + size * 0.62, sub, { + fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.3)}px`, color: '#f2ead8', stroke: '#120c06', strokeThickness: 6, + }).setOrigin(0.5).setDepth(D.stamp).setAlpha(0); + this.tweens.add({ targets: s, alpha: 1, delay: 200, duration: 200 }); + objs.push(s); + } + this.tweens.add({ targets: objs, alpha: 0, delay: hold, duration: 320, onComplete: () => objs.forEach(o => o.destroy()) }); + } + + phaseStamp(seat, phaseNum) { + const c = matCentre(this.L, seat); + this.stamp(`PHASE ${phaseNum}!`, c, SEAT_HEX[seat], { size: seat === 0 ? 84 : 58, hold: 900 }); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.6 }); + } + + skipSlam(seat, target) { + const d = this.L.discard; + this.cameras.main.shake(180, 0.006); + playSound(this, SFX.CARD_PLACE); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.4, rate: 1.6 }); + for (let i = 0; i < 8; i++) { + const a = (i / 8) * Math.PI * 2; + const dot = this.add.circle(d.x, d.y, 6, 0xff6b4a, 0.85).setDepth(D.float); + this.tweens.add({ targets: dot, x: d.x + Math.cos(a) * 70, y: d.y + Math.sin(a) * 50, alpha: 0, scale: 1.8, duration: 420, ease: 'Cubic.easeOut', onComplete: () => dot.destroy() }); + } + if (target != null) { + const who = target === 0 ? 'you' : this.shortName(target); + this.floatText({ x: d.x, y: d.y - 60 }, `${seat === 0 ? 'You skip' : `${this.shortName(seat)} skips`} ${who}!`, '#ff8a7a', { size: 24, ms: 1500 }); + } + } + + nudge(id) { + const c = this.sprites.get(id); + if (!c || c._tw || this.dragState?.id === id) return; + const p = c.pose; + this.tweens.add({ targets: c, x: p.x + 7, duration: 50, yoyo: true, repeat: 2, onComplete: () => this.applyPose(c, p) }); + playSoundEx(this, SFX.CLICK, { volume: 0.4 }); + } + + // ── Dock ──────────────────────────────────────────────────────────────────── + setDock(prompt, buttons = []) { + this.prompt.setText(prompt); + this.dockBtns.forEach((b, i) => { + const spec = buttons[i]; + this.dockActs[i] = spec?.act ?? null; + if (!spec) { b.setVisible(false); return; } + b.setVisible(true).setLabel(spec.label).setEnabled(spec.enabled !== false); + b.setActive(!!spec.hot && spec.enabled !== false); + }); + } + + updateDock() { + if (!this.gs) return; + const gs = this.gs; + if (this.mode === 'deal') { this.setDock('Shuffling and dealing…'); return; } + if (this.mode === 'ending' || this.mode === 'summary') { this.setDock('Round over — counting up hands.'); return; } + if (this.mode === 'ai') { this.setDock(`${this.nameForSeat(gs.currentPlayer)} is playing…`); return; } + if (this.mode !== 'human') { this.setDock(''); return; } + const me = this.me(); + const top = discardTop(gs); + const phaseNum = me.phase; + if (!gs.drawnThisTurn) { + const takeOk = top && top.value !== 'skip'; + this.setDock( + takeOk ? `Your turn — draw from the deck, or take the ${cardName(top)}.` : 'Your turn — draw from the deck. (A Skip can\'t be taken.)', + [ + { label: 'Draw (D)', act: () => this.drawDeck(), hot: true }, + { label: takeOk ? `Take ${top.value === 'wild' ? 'Wild' : top.value} (T)` : 'Take (T)', act: () => this.takeDiscard(), enabled: !!takeOk }, + ], + ); return; } - - if (card.value === 'wild') { - g.fillStyle(WILD_FILL, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, WILD_STRIPE, 1); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, WILD_STRIPE, 0.5); - for (let s = -CARD_H; s < CARD_W; s += 14) { - const t0 = Math.max(0, -s / CARD_H); - const t1 = Math.min(1, (CARD_W - s) / CARD_H); - if (t0 >= t1) continue; - g.beginPath(); - g.moveTo(x + s + t0 * CARD_H, y + CARD_H * (1 - t0)); - g.lineTo(x + s + t1 * CARD_H, y + CARD_H * (1 - t1)); - g.strokePath(); - } - container.add(g); - container.add(this.add.text(0, 0, 'W', { - fontFamily: 'Righteous', fontSize: '46px', color: COLORS.textDarkHex, - }).setOrigin(0.5)); + const sel = this.selectedId != null && me.hand.some(c => c.id === this.selectedId); + const discardBtn = { label: 'Discard (X)', act: () => this.discardSelected(), enabled: sel }; + if (!me.laidDown) { + const spec = getPhase(phaseNum); + const staged = this.stage ? this.stage.some(g => g.length) : false; + const ready = !!this.stage && spec.groups.every((sg, gi) => groupStatus(sg.kind, sg.count, this.stageCards(gi)).ok); + const can = !!this.advice?.laydown; + let prompt; + if (ready) prompt = `Phase ${phaseNum} is ready — lay it down!`; + else if (can) prompt = `You can make Phase ${phaseNum}! Tap Auto-fill or build it on your mat.`; + else if (staged) prompt = 'Keep building — or Clear and discard to end your turn.'; + else prompt = `Build Phase ${phaseNum} (${spec.short}) on your mat, or discard a card to end your turn.`; + this.setDock(prompt, [ + { label: 'Lay down ↵', act: () => this.layDown(), enabled: ready, hot: ready }, + { label: 'Auto-fill (A)', act: () => this.autoFill(), enabled: can, hot: can && !ready }, + { label: 'Clear', act: () => this.clearStage(), enabled: staged }, + discardBtn, + ]); return; } - - if (card.value === 'skip') { - g.fillStyle(SKIP_FILL, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, SKIP_GLYPH, 1); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - // ⊘ glyph - g.lineStyle(5, SKIP_GLYPH, 1); - g.strokeCircle(0, 0, 26); - g.beginPath(); - g.moveTo(-18, -18); g.lineTo(18, 18); - g.strokePath(); - container.add(g); - container.add(this.add.text(0, 36, 'SKIP', { - fontFamily: 'Righteous', fontSize: '14px', color: COLORS.dangerHex, - }).setOrigin(0.5)); - return; - } - - // Numbered colored card - const suit = SUIT[card.color] ?? SUIT.red; - g.fillStyle(suit.fill, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(4, suit.stroke, 1); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - - const numStyle = (sz) => ({ fontFamily: 'Righteous', fontSize: `${sz}px`, color: suit.num }); - container.add(this.add.text(x + 8, y + 6, `${card.value}`, numStyle(20))); - container.add(this.add.text(0, 0, `${card.value}`, numStyle(46)).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 8, y + CARD_H - 8, `${card.value}`, numStyle(20)).setOrigin(1, 1)); + const hits = this.advice?.hittable?.size ?? 0; + this.setDock( + hits ? `Hit cards onto any laid-down phase (${hits} can go), then discard.` : 'Discard a card to end your turn.', + [ + { label: 'Hit all (P)', act: () => this.hitAll(), enabled: hits > 0, hot: hits > 0 }, + discardBtn, + ], + ); } - drawCardBackGfx(g, x, y) { - const color = this.cardBack?.fallbackColor - ? parseInt(this.cardBack.fallbackColor.replace('#', ''), 16) : 0x1a3a6b; - g.fillStyle(color, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 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); + // ── Human actions ─────────────────────────────────────────────────────────── + sortHand() { + if (!this.gs || this.settings.sort === 'manual') return; + const hand = this.me().hand; + hand.splice(0, hand.length, ...this.sortedHand(hand)); } - clearAllCardObjs() { - for (const c of this.cardObjs.values()) c.destroy(); - this.cardObjs.clear(); - for (const o of this.transientObjs) o.destroy(); - this.transientObjs = []; - this.localHandCards = []; - } - - // ── Rendering ──────────────────────────────────────────────────────────── - - renderAll() { - if (this.dragState) this.endCardDragImmediate(); - this.refreshStagingArea(); - this.clearAllCardObjs(); - this.renderCenter(); - for (let seat = 0; seat < this.gs.players.length; seat++) { - this.renderSeat(seat); - } - this.renderSeatChips(); - this.renderTurnIndicator(); - this.refreshPlaybook(); - this.renderStagingArea(); - } - - renderCenter() { - const remaining = this.gs.drawPile.length; - if (remaining > 0) { - const c = this.makeCardSprite({ value: 'back', id: -1 }, DRAW_POS.x, DRAW_POS.y, { faceUp: false }); - c.card = null; - this.cardObjs.set('draw', c); - } - this.drawPileText.setText(`${remaining}`); - - const top = discardTop(this.gs); - if (top) { - const c = this.makeCardSprite(top, DISCARD_POS.x, DISCARD_POS.y, { faceUp: true }); - this.cardObjs.set(`discard-top-${top.id}`, c); - } - } - - renderSeat(seat) { - const player = this.gs.players[seat]; - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - - if (seat === 0) this.localHandCards = []; - - // Build staged-card lookup for seat 0 - const stagedMap = new Map(); // cardId → { gi, si } - if (seat === 0 && this.stagingGroups) { - for (let gi = 0; gi < this.stagingGroups.length; gi++) { - this.stagingGroups[gi].slots.forEach((id, si) => { - if (id !== null) stagedMap.set(id, { gi, si }); - }); - } - } - let handPosCounter = 0; - - // Hand - for (let i = 0; i < player.hand.length; i++) { - const card = player.hand[i]; - let x, y, cardScale = 1; - if (seat === 0 && this.stagingGroups) { - const staged = stagedMap.get(card.id); - if (staged) { - const pos = this._getStagingSlotPos(staged.gi, staged.si); - x = pos.x; y = pos.y; cardScale = LAIDOWN_CARD_W / CARD_W; - } else { - x = layout.handStart.x + handPosCounter * HAND_SPREAD; - y = layout.handStart.y; - handPosCounter++; - } - } else { - if (layout.handAxis === 'x') { - x = layout.handStart.x + i * HAND_SPREAD; - y = layout.handStart.y; - } else { - x = layout.handStart.x; - y = layout.handStart.y - i * HAND_SPREAD; + // The hand in the current sort order (a copy; manual = as is). + sortedHand(hand) { + const mode = this.settings.sort; + if (mode === 'manual') return hand.slice(); + let sorted; + if (mode === 'color') sorted = [...hand].sort(byColor); + else if (mode === 'phase') { + const me = this.me(); + const front = []; + if (!me.laidDown) { + const lay = findLaydown(hand, me.phase); + if (lay) for (const g of lay) front.push(...orderGroupCards(g.kind, g.cards)); + else { + const a = adviseHand(this.gs, 0); + front.push(...hand.filter(c => a.keepers.has(c.id) && isNum(c)).sort(byNumber)); } } - const c = this.makeCardSprite(card, x, y, { - faceUp: layout.handFaceUp, rotation: layout.rotateCards, scale: cardScale, - }); - this.cardObjs.set(`hand-${seat}-${card.id}`, c); - if (seat === 0) { - this.localHandCards.push(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'; - c.on('pointerdown', (pointer) => this.onHandPointerDown(i, pointer)); - } - } - - // Laid-down phase - if (player.laidDown) this.renderLaidDown(seat, player.laidDown); + const ids = new Set(front.map(c => c.id)); + sorted = [...front, ...hand.filter(c => !ids.has(c.id)).sort(byNumber)]; + } else sorted = [...hand].sort(byNumber); + return sorted; } - renderLaidDown(seat, laid) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - - let cursorX = layout.laidStart.x; - let cursorY = layout.laidStart.y; - - for (let gi = 0; gi < laid.length; gi++) { - const group = laid[gi]; - const N = group.cards.length; - const groupW = N * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25); - - // Determine run values for labelling - const runVals = group.kind === 'run' ? runAssignedValues(group) : null; - - for (let ci = 0; ci < N; ci++) { - const card = group.cards[ci]; - let x, y; - if (layout.laidAxis === 'x') { - x = cursorX + ci * (LAIDOWN_CARD_W * 0.75) + LAIDOWN_CARD_W / 2; - y = cursorY; - } else { - x = cursorX; - y = cursorY + ci * (LAIDOWN_CARD_H * 0.5) + LAIDOWN_CARD_H / 2; - } - const c = this.makeCardSprite(card, x, y, { - faceUp: true, - rotation: layout.rotateCards, - scale: LAIDOWN_CARD_W / CARD_W, - }); - // If wild in a run, overlay its assigned value as a small chip. - if (card.value === 'wild' && runVals) { - const chip = this.add.text(x, y, `${runVals[ci]}`, { - fontFamily: 'Righteous', fontSize: '18px', - color: COLORS.textDarkHex, backgroundColor: COLORS.goldHex, - padding: { x: 4, y: 1 }, - }).setOrigin(0.5).setDepth(D.card + 1); - this.transientObjs.push(chip); - } - this.cardObjs.set(`laid-${seat}-${gi}-${ci}-${card.id}`, c); - } - - // Advance cursor for next group - if (layout.laidAxis === 'x') cursorX += groupW + GROUP_GAP; - else cursorY += N * (LAIDOWN_CARD_H * 0.5) + GROUP_GAP; - } + afterHumanChange({ sort = false } = {}) { + if (sort) this.sortHand(); + if (this.canStage()) this.ensureStage(); + if (this.gs.roundPhase !== 'play') { this.layout(); this.onRoundOver(); return; } + this.layout(); + this.updateDock(); } - 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; - if (p.clearedAt != null) { - chip.phaseText.setText('Phase 10 ✓'); - chip.goalText.setText('cleared'); - } else { - const ph = getPhase(p.phase); - chip.phaseText.setText(`Phase ${p.phase}`); - chip.goalText.setText(ph ? ph.short : ''); - } - chip.scoreText.setText(`${p.score}`); - chip.ribbon.setVisible(!!p.laidDown); - chip.ribbon.setText('LAID DOWN'); - } - } - - 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); - } - - refreshStagingArea() { - const player = this.gs.players[0]; - const eligible = this.isLocalTurn() && this.gs.drawnThisTurn && !player.laidDown; - if (!eligible) { - this.stagingGroups = null; - this._destroyStagingButtons(); - return; - } - if (!this.stagingGroups) { - const spec = getPhase(player.phase); - if (!spec) return; - this.stagingGroups = spec.groups.map((g) => ({ - kind: g.kind, - count: g.count, - slots: new Array(g.count).fill(null), - })); - this._createStagingButtons(); - } - } - - _createStagingButtons() { - this._destroyStagingButtons(); - const { laidStart } = slotLayout('bottom'); - let totalW = 0; - for (let i = 0; i < this.stagingGroups.length; i++) { - if (i > 0) totalW += GROUP_GAP; - totalW += this.stagingGroups[i].count * (LAIDOWN_CARD_W * 0.75) + (LAIDOWN_CARD_W * 0.25); - } - const panelX = laidStart.x - 14; - const panelW = totalW + 28; - const btnX = panelX + panelW + 200; - this.submitBtn = new Button(this, btnX, laidStart.y - 18, 'Submit Phase', () => this.submitStagingLaydown(), { - width: 200, height: 44, fontSize: 18, - }).setDepth(D.ui); - this.clearBtn = new Button(this, btnX, laidStart.y + 34, 'Clear', () => this.clearStagingLaydown(), { - variant: 'ghost', width: 200, height: 34, fontSize: 14, - }).setDepth(D.ui); - } - - _destroyStagingButtons() { - if (this.submitBtn) { this.submitBtn.destroy(); this.submitBtn = null; } - if (this.clearBtn) { this.clearBtn.destroy(); this.clearBtn = null; } - } - - // ── Local input ───────────────────────────────────────────────────────── - - isLocalTurn() { - return this.gs && !this.matchOver && this.gs.roundPhase === 'play' && this.gs.currentPlayer === 0; - } - - onDrawDeckClick() { - if (!this.isLocalTurn() || this.animating) return; - if (this.gs.drawnThisTurn) return; + drawDeck() { + if (!this.canAct() || this.gs.drawnThisTurn) return; const next = applyDrawFromDeck(this.gs); if (next === this.gs) return; - this.gs = next; - this.animating = true; + this.commit(next); playSound(this, SFX.CARD_DEAL); - const layout = slotLayout('bottom'); - const handLen = this.gs.players[0].hand.length; - const targetX = layout.handStart.x + (handLen - 1) * HAND_SPREAD; - this._flyCard(DRAW_POS.x, DRAW_POS.y, targetX, layout.handStart.y, - { value: 'back', id: -1 }, { faceUp: false, duration: 450 }, () => { - this.animating = false; - this.renderAll(); - this.setStatus('Drew from deck. Lay down, hit, or discard.'); - }); + const hand = this.me().hand; + const drawn = hand[hand.length - 1]; + this.selectedId = null; + this.afterHumanChange({ sort: true }); + this.flashCard(drawn.id); } - onDiscardPileClick() { - if (!this.isLocalTurn() || this.animating) return; - // If we have a card selected and we've already drawn, discarding ends turn. - if (this.gs.drawnThisTurn && this.selectedHandIdx != null) { - if (this._hasStagedCards()) { - this.setStatus('Submit or clear your phase first — you have cards staged.'); - this._shakeStagingButtons(); - return; - } - const handIdx = this.selectedHandIdx; - this.selectedHandIdx = null; - this.clearHighlights(); - this.commitDiscard(handIdx); + takeDiscard() { + if (!this.canAct() || this.gs.drawnThisTurn) return; + const top = discardTop(this.gs); + if (!top) return; + if (top.value === 'skip') { this.floatText({ x: this.L.discard.x, y: this.L.discard.y - 60 }, "Skips can't be taken", '#ff9a7a', { size: 20 }); return; } + const next = applyDrawFromDiscard(this.gs); + if (next === this.gs) return; + this.commit(next); + playSound(this, SFX.CARD_DEAL); + this.selectedId = null; + this.afterHumanChange({ sort: true }); + this.flashCard(top.id); + } + + flashCard(id) { + this.time.delayedCall(300, () => { + const c = this.sprites.get(id); + if (!c) return; + c.glow.setVisible(true).setTint(0x7cf0a0).setAlpha(1); + this.tweens.add({ + targets: c.glow, alpha: 0, duration: 900, delay: 300, + onComplete: () => { c.glow.setTint(0xffd35a).setAlpha(1); c.glow.setVisible(c.card.id === this.selectedId); }, + }); + }); + } + + select(id) { + this.selectedId = this.selectedId === id ? null : id; + if (this.selectedId != null) playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + this.updateDock(); + } + + ensureStage() { + if (!this.stage) this.stage = getPhase(this.me().phase).groups.map(() => []); + } + + stageCard(id, gi) { + if (!this.canStage()) return false; + this.ensureStage(); + const spec = getPhase(this.me().phase).groups[gi]; + const card = this.me().hand.find(c => c.id === id); + if (!spec || !card) return false; + if (card.value === 'skip') { this.floatText(this.groupLabelPos(gi), "Skips can't be played", '#ff9a7a', { size: 20 }); this.nudge(id); return false; } + for (const g of this.stage) { const k = g.indexOf(id); if (k >= 0) g.splice(k, 1); } + if (this.stage[gi].length >= spec.count) { this.nudge(id); this.layout(); return false; } + this.stage[gi].push(id); + if (this.selectedId === id) this.selectedId = null; + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.5 }); + this.layout(); + this.updateDock(); + return true; + } + + unstage(id) { + if (!this.stage) return; + for (const g of this.stage) { const k = g.indexOf(id); if (k >= 0) g.splice(k, 1); } + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.35 }); + this.layout(); + this.updateDock(); + } + + groupLabelPos(gi) { + const gc = getPhase(this.me().phase).groups.length; + const a = groupAreas(this.L, 0, gc)[gi]; + return { x: a.cx, y: a.labelY }; + } + + // Best group for a card while staging: first non-full group it fits, else first non-full. + bestStageGroup(id) { + const legal = this.legalFor(id); + if (!legal?.stage.length) return null; + return (legal.stage.find(s => s.fits) ?? legal.stage[0]).gi; + } + + autoFill() { + if (!this.canStage()) return; + const lay = findLaydown(this.me().hand, this.me().phase); + if (!lay) return; + this.stage = lay.map(g => g.cards.map(c => c.id)); + this.selectedId = null; + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.45, rate: 1.3 }); + this.layout({ duration: 300, delayFor: (v) => (v.kind === 'stage' ? v.gi * 120 + v.ci * 45 : 0) }); + this.updateDock(); + } + + clearStage() { + if (!this.stage) return; + this.stage = null; + if (this.canStage()) this.ensureStage(); + this.layout(); + this.updateDock(); + } + + layDown() { + if (!this.canStage() || !this.stage) return; + const me = this.me(); + const spec = getPhase(me.phase); + const groups = spec.groups.map((sg, gi) => ({ kind: sg.kind, cardIds: this.stage[gi].slice() })); + const next = applyLaydown(this.gs, groups); + if (next === this.gs) { + this.floatText(matCentre(this.L, 0), 'Not a valid phase yet', '#ff9a7a', { size: 24 }); return; } - // Otherwise, attempt draw from discard. + const phaseNum = me.phase; + this.stage = null; + this.selectedId = null; + this.commit(next); + this.afterHumanChange({ sort: true }); + this.phaseStamp(0, phaseNum); + playSound(this, SFX.CARD_SHOW); + } + + // Hit `id` onto a target (or the first legal target). + hitCard(id, target = null) { + if (!this.canAct() || !this.gs.drawnThisTurn || !this.me().laidDown) return false; + const hand = this.me().hand; + const idx = hand.findIndex(c => c.id === id); + if (idx < 0) return false; + const targets = getHitTargets(this.gs, hand[idx]); + const t = target ?? targets[0]; + if (!t) { this.nudge(id); return false; } + const next = applyHit(this.gs, idx, t.targetSeat, t.groupIdx, t.position); + if (next === this.gs) { this.nudge(id); return false; } + this.selectedId = null; + this.commit(next); + playSound(this, SFX.CARD_PLACE); + this.afterHumanChange(); + return true; + } + + async hitAll() { + if (!this.canAct() || !this.me().laidDown || !this.gs.drawnThisTurn) return; + this.busy = true; + let guard = 0; + while (this.alive() && this.gs.roundPhase === 'play' && guard++ < 30) { + const card = this.me().hand.find(c => c.value !== 'skip' && getHitTargets(this.gs, c).length); + if (!card) break; + this.busy = false; + const ok = this.hitCard(card.id); + this.busy = true; + if (!ok) break; + await this.wait(200); + } + this.busy = false; + if (this.alive() && this.gs.roundPhase === 'play') this.updateDock(); + } + + discardSelected() { + if (this.selectedId != null) this.discardCard(this.selectedId); + } + + discardCard(id, { confirmed = false } = {}) { + if (!this.canAct() || !this.gs.drawnThisTurn) return; + const hand = this.me().hand; + const idx = hand.findIndex(c => c.id === id); + if (idx < 0) return; + const card = hand[idx]; + if (!confirmed && this.settings.warn) { + const inPhase = !this.me().laidDown && this.advice?.laydown?.some(g => g.cards.some(c => c.id === id)); + if (card.value === 'wild' || inPhase) { + this.confirmDiscard(card, inPhase ? 'That card is part of your phase — you could lay it down this turn.' : 'Wilds fit anywhere and cost 25 points if you\'re caught with them — but they\'re gold for building.', () => this.discardCard(id, { confirmed: true })); + return; + } + } + if (card.value === 'skip') { + const targets = skipTargets(this.gs, 0); + if (targets.length > 1) { this.openSkipPicker(id, targets); return; } + this.finishDiscard(idx, targets[0] ?? null); + return; + } + this.finishDiscard(idx, null); + } + + finishDiscard(idx, target) { + const card = this.me().hand[idx]; + const next = applyDiscard(this.gs, idx, target); + if (next === this.gs) { this.nudge(card.id); return; } + this.stage = null; + this.selectedId = null; + this.commit(next, { thrower: 0 }); + this.layout(); + if (card.value === 'skip') { + this.skipSlam(0, target); + if (target != null) this.portraits[target]?.playEmotion?.('upset'); + } else playSound(this, SFX.CARD_PLACE); + this.mode = 'idle'; + this.targetG.clear(); + this.updateDock(); + if (this.gs.roundPhase !== 'play') { this.onRoundOver(); return; } + this.time.delayedCall(280, () => this.beginTurn()); + } + + // ── 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)); + const kb = this.input.keyboard; + if (kb) { + kb.addCapture(['ENTER', 'SPACE']); + kb.on('keydown', (e) => this.onKey(e)); + } + } + + liftFor(heldIds) { + return (i) => (heldIds[i] === this.selectedId ? 46 : heldIds[i] === this.hoverId ? 24 : 0); + } + + heldIds() { + const staged = this.stagedIds(); + return this.me().hand.filter(c => !staged.has(c.id)).map(c => c.id); + } + + // What the human pressed: { kind: 'hand'|'stage'|'deck'|'discard'|'group'|'hit', ... } + hitTest(pt) { + if (!this.gs) return null; + const held = this.heldIds(); + const hi = handHit(this.L, held.length, pt, this.liftFor(held)); + if (hi >= 0) return { kind: 'hand', id: held[hi] }; + if (this.stage) { + // staged cards, topmost first + const vis = this._lastVisible; + const stagedVis = [...(vis?.values() ?? [])].filter(v => v.kind === 'stage').sort((a, b) => b.depth - a.depth); + for (const v of stagedVis) if (inPose(pt, v.pose)) return { kind: 'stage', id: v.card.id }; + } + if (inPose(pt, deckTopPose(this.L, this.gs.drawPile.length), 8)) return { kind: 'deck' }; + if (inPose(pt, this.L.discard, 10)) return { kind: 'discard' }; + if (this.selectedId != null) { + const t = this.dropTargetAt(pt, this.selectedId); + if (t && t.type !== 'discard' && t.type !== 'hand') return { kind: 'target', target: t }; + } + return null; + } + + dropTargetAt(pt, id) { + if (inPose(pt, this.L.discard, 34) && this.canAct() && this.gs.drawnThisTurn) return { type: 'discard' }; + const legal = this.legalFor(id); + if (legal) { + const gc = getPhase(this.me().phase)?.groups.length ?? 1; + for (const s of legal.stage) if (inRect(pt, areaRect(this.L, 0, s.gi, gc, 18))) return { type: 'stage', gi: s.gi }; + let best = null; + for (const t of legal.hits) { + const p = this.gs.players[t.targetSeat]; + const r = groupRect(this.L, t.targetSeat, t.groupIdx, p.laidDown.length, p.laidDown[t.groupIdx].cards.length, 1, 22); + if (!inRect(pt, r)) continue; + const want = pt.x < r.cx ? 'low' : 'high'; + if (!best || (t.position === want)) best = { type: 'hit', targetSeat: t.targetSeat, groupIdx: t.groupIdx, position: t.position }; + } + if (best) return best; + } + const z = handZone(this.L, this.heldIds().length); + if (inRect(pt, z)) return { type: 'hand', at: handInsertIndex(this.L, this.heldIds().length, pt.x) }; + return null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState) return; + if (over?.some(o => !o.isP10Zone)) return; + if (this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const hit = this.hitTest(pointer); + if (!hit) { + if (this.selectedId != null) { this.selectedId = null; this.layout({ duration: 140 }); this.updateDock(); } + return; + } + if (hit.kind === 'hand' || hit.kind === 'stage') { + this.potentialDrag = { ...hit, x: pointer.x, y: pointer.y }; + return; + } + if (!this.canAct()) return; + if (hit.kind === 'deck') { if (!this.gs.drawnThisTurn) this.drawDeck(); else this.nudgeDeck(); return; } + if (hit.kind === 'discard') { + if (!this.gs.drawnThisTurn) this.takeDiscard(); + else if (this.selectedId != null) this.discardCard(this.selectedId); + else this.floatText({ x: this.L.discard.x, y: this.L.discard.y - 60 }, 'Pick a card to discard', '#f2d6a0', { size: 20 }); + return; + } + if (hit.kind === 'target') this.applyTarget(this.selectedId, hit.target); + } + + nudgeDeck() { + this.floatText({ x: this.L.deck.x, y: this.L.deck.y - 60 }, 'Already drew this turn', '#f2d6a0', { size: 20 }); + } + + applyTarget(id, t) { + if (!t) return false; + if (t.type === 'discard') { this.discardCard(id); return true; } + if (t.type === 'stage') return this.stageCard(id, t.gi); + if (t.type === 'hit') return this.hitCard(id, { targetSeat: t.targetSeat, groupIdx: t.groupIdx, position: t.position }); + return false; + } + + 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 held = this.heldIds(); + const hi = handHit(this.L, held.length, pointer, this.liftFor(held)); + const id = hi >= 0 ? held[hi] : null; + if (id !== this.hoverId) { + this.hoverId = id; + this.layout({ duration: 120 }); + } + let cursor = 'default'; + if (id != null) cursor = 'grab'; + else if (this.canAct()) { + const h = this.hitTest(pointer); + if (h && (h.kind === 'deck' || h.kind === 'discard' || h.kind === 'target' || h.kind === 'stage')) cursor = 'pointer'; + } + this.input.setDefaultCursor(cursor); + } + + onPointerUp(pointer) { + if (this.dragState) { this.endDrag(pointer); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + if (pd.kind === 'stage') { if (this.canStage()) this.unstage(pd.id); return; } + // a click on a hand card: select / double-click smart play + const now = this.time.now; + const dbl = this.lastClick.id === pd.id && now - this.lastClick.at < DOUBLE_CLICK_MS; + this.lastClick = { id: pd.id, at: now }; + if (!this.canAct() || !this.gs.drawnThisTurn) { + if (this.canAct()) this.floatText({ x: CX, y: 870 }, 'Draw a card first', '#f2d6a0', { size: 20 }); + return; + } + if (dbl) { this.lastClick = { id: null, at: 0 }; this.smartPlay(pd.id); return; } + this.select(pd.id); + } + + smartPlay(id) { + if (this.me().laidDown) { + if (!this.hitCard(id)) this.select(id); + return; + } + if (this.canStage()) { + const gi = this.bestStageGroup(id); + if (gi != null) { this.stageCard(id, gi); return; } + } + this.nudge(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); + c.glow.setVisible(false); + this.dragState = { id: pd.id, from: pd.kind, offX: c.pose.x - pd.x, offY: c.pose.y - pd.y, sprite: c, target: null }; + this.hoverId = null; + this.input.setDefaultCursor('grabbing'); + this.updateDrag(pointer); + } + + 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 - 640) / 320)); + const pose = { x, y, rot: 0, s: lerp(0.74, 1, t), q: lerp(SQ, 1, t) }; + this.applyPose(ds.sprite, pose, 1); + ds.target = this.dropTargetAt(pointer, ds.id); + const order = ds.target?.type === 'hand' ? this.previewOrder(ds, ds.target.at) : null; + const key = order ? order.join(',') : ''; + if (key !== ds.previewKey) { + ds.previewKey = key; + this.dragPreview = order; + this.layout({ duration: 150 }); + } + this.drawDropSlot(order, ds.id); + this.drawTargets(ds.target); + } + + // The hand order a drop at insertion slot `at` produces (dragged card included). + previewOrder(ds, at) { + const hand = this.me().hand; + const staged = this.stagedIds(); + staged.delete(ds.id); + if (ds.from === 'stage' && this.settings.sort !== 'manual') { + // back from the mat into a sorted hand: it goes where the sort puts it + return this.sortedHand(hand).filter(c => !staged.has(c.id)).map(c => c.id); + } + const held = this.heldIds(); + const fromIdx = held.indexOf(ds.id); + const rest = held.filter(id => id !== ds.id); + const ins = fromIdx >= 0 && fromIdx < at ? at - 1 : at; + rest.splice(Math.max(0, Math.min(rest.length, ins)), 0, ds.id); + return rest; + } + + // Outline of the empty slot the dragged card will drop into, layered between + // its neighbours exactly as the card will be. + drawDropSlot(order, id) { + const g = this.dropSlotG, glow = this.dropSlotGlow; + if (!order) { g.setVisible(false); glow.setVisible(false); return; } + const idx = order.indexOf(id); + const pose = handPose(this.L, 0, idx, order.length); + const depth = D.hand + idx * 0.01 - 0.004; + g.clear(); + g.fillStyle(0x1a0e06, 0.55); + g.fillPoints(cardCorners(pose), true); + g.setDepth(depth).setVisible(true); + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? 1); + glow.setPosition(pose.x, pose.y).setRotation(pose.rot).setScale(0.5 * sx, 0.5 * sy) + .setDepth(depth + 0.001).setVisible(true); + } + + clearDropPreview() { + this.dragPreview = null; + this.drawDropSlot(null); + } + + endDrag(pointer) { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + const t = ds.target ?? this.dropTargetAt(pointer, ds.id); + let done = false; + if (t?.type === 'hand') { + done = true; + this.dropIntoHand(ds, this.previewOrder(ds, t.at)); + } else if (t && this.canAct()) { + done = this.applyTarget(ds.id, t); + } + this.clearDropPreview(); + if (!done) this.layout(); + this.drawTargets(); + } + + // Commit a hand drop: the hand takes exactly the order the preview showed. + dropIntoHand(ds, order) { + const hand = this.me().hand; + const before = this.heldIds().join(','); + if (ds.from === 'stage' && this.stage) { + for (const g of this.stage) { const k = g.indexOf(ds.id); if (k >= 0) g.splice(k, 1); } + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.35 }); + } + const staged = this.stagedIds(); + const byId = new Map(hand.map(c => [c.id, c])); + const stagedCards = hand.filter(c => staged.has(c.id)); + hand.splice(0, hand.length, ...order.map(id => byId.get(id)).filter(Boolean), ...stagedCards); + if (ds.from === 'hand' && order.join(',') !== before && this.settings.sort !== 'manual') { + this.settings.sort = 'manual'; + this.saveSettings(); + this.refreshSortButtons(); + } + this.dragPreview = null; + this.layout(); + if (ds.from === 'stage') this.updateDock(); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) { + if (this.selectedId != null) { this.selectedId = 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 === 's') { this.cycleSort(); return; } + if (k === 'h') { this.flashHint(); return; } + if (!this.canAct()) return; + if (k === 'd') this.drawDeck(); + else if (k === 't') this.takeDiscard(); + else if (k === 'a') this.autoFill(); + else if (e.code === 'Enter') this.layDown(); + else if (k === 'x') this.discardSelected(); + else if (k === 'p') this.hitAll(); + else if (/^[0-9-]$/.test(k) && this.gs.drawnThisTurn) { + const held = this.heldIds(); + const i = k === '0' ? 9 : k === '-' ? 10 : Number(k) - 1; + if (held[i] != null) this.select(held[i]); + } + } + + cycleSort() { + const order = ['number', 'color', 'phase']; + const i = order.indexOf(this.settings.sort); + this.settings.sort = order[(i + 1) % order.length]; + this.saveSettings(); + this.sortHand(); + this.layout(); + this.refreshSortButtons(); + } + + // H: briefly show what the hints suggest, even with hints off. + flashHint() { + if (!this.gs || this.mode !== 'human') return; + const a = adviseHand(this.gs, 0); + let ids = [], text = ''; if (!this.gs.drawnThisTurn) { const top = discardTop(this.gs); - if (!top) { this.setStatus('Discard pile is empty.'); return; } - if (top.value === 'skip') { this.setStatus("Can't draw a Skip from the discard pile."); return; } - const next = applyDrawFromDiscard(this.gs); - if (next === this.gs) return; - this.gs = next; - this.animating = true; - playSound(this, SFX.CARD_DEAL); - const layout = slotLayout('bottom'); - const handLen = this.gs.players[0].hand.length; - const targetX = layout.handStart.x + (handLen - 1) * HAND_SPREAD; - this._flyCard(DISCARD_POS.x, DISCARD_POS.y, targetX, layout.handStart.y, - top, { faceUp: true, duration: 450 }, () => { - this.animating = false; - this.renderAll(); - this.setStatus('Took from discard. Lay down, hit, or discard.'); - }); + const helps = top && top.value !== 'skip' && (top.value === 'wild' || (!this.me().laidDown && !a.laydown && findLaydown([...this.me().hand, top], this.me().phase))); + text = helps ? `Take the ${cardName(top)} — it completes your phase!` : 'Draw from the deck.'; + } else if (a.laydown) { ids = a.laydown.flatMap(g => g.cards.map(c => c.id)); text = 'You can lay your phase down — press A.'; } + else if (a.hittable.size) { ids = [...a.hittable]; text = 'These can be hit onto the table.'; } + else if (a.discardId != null) { ids = [a.discardId]; text = `Safest discard: ${cardName(this.me().hand.find(c => c.id === a.discardId))}.`; } + this.floatText({ x: CX, y: 880 }, text, '#7cf0a0', { size: 22, ms: 2200, rise: 20 }); + for (const id of ids) { + const c = this.sprites.get(id); + if (!c) continue; + c.glow.setVisible(true).setTint(0x7cf0a0).setAlpha(1); + this.tweens.add({ targets: c.glow, alpha: 0.2, duration: 380, yoyo: true, repeat: 2, onComplete: () => { c.glow.setTint(0xffd35a).setAlpha(1).setVisible(c.card.id === this.selectedId); } }); } } - onHandClick(handIdx) { - if (!this.isLocalTurn() || this.animating) return; - if (!this.gs.drawnThisTurn) { - this.setStatus('Draw a card first.'); - return; - } - this.selectedHandIdx = handIdx; - this.highlightTargetsForCard(); - const card = this.gs.players[0].hand[handIdx]; - if (card.value === 'skip') { - this.setStatus('Click the discard pile to discard. Choose a target to skip.'); - } else if (this.gs.players[0].laidDown) { - this.setStatus('Click a laid-down group to hit, or the discard pile to end turn.'); - } else { - this.setStatus('Click the discard pile to end your turn.'); - } + // ── Modals ───────────────────────────────────────────────────────────────── + freeze(on) { + this.paused = on; + this.time.paused = on; + if (on) this.tweens.pauseAll(); else this.tweens.resumeAll(); } - - highlightTargetsForCard() { - this.clearHighlights(); - if (this.selectedHandIdx == null) return; - const card = this.gs.players[0].hand[this.selectedHandIdx]; - - // Discard pile target — always available (with a Skip-target picker if skip). - { - const h = this.add.rectangle(DISCARD_POS.x, DISCARD_POS.y, CARD_W + 18, CARD_H + 18, 0x4dabf7, 0.18) - .setStrokeStyle(3, 0x4dabf7, 0.9).setDepth(D.highlight); - this.highlightObjs.push(h); - } - - // Hit targets — only if we've laid down. - if (this.gs.players[0].laidDown) { - const targets = getHitTargets(this.gs, card); - for (const t of targets) { - const rect = this.hitTargetHighlight(t); - if (rect) this.highlightObjs.push(rect); - } - } + setVideos(visible) { + for (const p of this.portraits) p?.setVideoVisible?.(visible); } - hitTargetHighlight(target) { - const gc = this._getGroupCenter(target); - if (!gc) return null; - - const seatColor = 0xffd700; - const rect = this.add.rectangle(gc.x, gc.y, gc.w, gc.h, seatColor, 0.12) - .setStrokeStyle(2, seatColor, 0.9).setDepth(D.highlight) - .setInteractive({ useHandCursor: true }); - rect.on('pointerdown', () => this.commitHit(target)); - if (target.position && gc.axis === 'x') { - const tipX = target.position === 'low' ? gc.lowX : gc.highX; - const tip = this.add.text(tipX, gc.y, target.position === 'low' ? '◀' : '▶', { - fontFamily: 'Righteous', fontSize: '20px', color: '#ffd700', - }).setOrigin(0.5).setDepth(D.highlight); - this.transientObjs.push(tip); - } - return rect; + openModal({ w, h, paper = false, onEscape = null, freeze = true } = {}) { + if (this.modal) this.closeModal(); + if (this.dragState) { this.dragState = null; this.clearDropPreview(); this.layout(); } + this.potentialDrag = null; + this.tip?.hide(); + const objs = []; + objs.push(this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62).setInteractive().setDepth(D.modal)); + if (paper) objs.push(this.add.image(CX, CY, ensurePad(this, `p10-pad-${w}x${h}`, w, h)).setDepth(D.modal).setRotation(-0.01)); + else objs.push(this.add.image(CX, CY, ensureLeatherPanel(this, `p10-panel-${w}x${h}`, w, h, { radius: 18 })).setDepth(D.modal)); + const wasFrozen = this.paused; + if (freeze && !wasFrozen) this.freeze(true); + this.setVideos(false); + this.input.setDefaultCursor('default'); + this.modal = { objs, onEscape, froze: freeze && !wasFrozen }; + return this.modal; } - clearHighlights() { - for (const h of this.highlightObjs) h.destroy(); - this.highlightObjs = []; + addToModal(o) { this.modal?.objs.push(o); return o; } + + closeModal() { + const m = this.modal; + if (!m) return; + this.modal = null; + for (const o of m.objs) o.destroy(); + this.setVideos(true); + if (m.froze) this.freeze(false); } - // ── Action commit (local) ─────────────────────────────────────────────── - - commitDiscard(handIdx) { - const card = this.gs.players[0].hand[handIdx]; - if (card.value === 'skip') { - this.openSkipTargetModal(handIdx); - return; - } - const next = applyDiscard(this.gs, handIdx); - if (next === this.gs) { this.setStatus("Can't discard right now."); return; } - playSound(this, SFX.CARD_PLACE); - this.gs = next; - this.renderAll(); - this.afterTurnTransition(); + modalText(x, y, text, style) { + return this.addToModal(this.add.text(x, y, text, style).setOrigin(0.5).setDepth(D.modal + 1)); } - openSkipTargetModal(handIdx) { - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setInteractive().setDepth(D.modal); - const w = 560, h = 280; - const panel = this.add.rectangle(CX, CY, w, h, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - const title = this.add.text(CX, CY - h / 2 + 40, 'Skip which player?', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.modal); + modalButton(x, y, label, fn, opts = {}) { + return this.addToModal(new Button(this, x, y, label, fn, { width: 240, height: 52, fontSize: 20, ...opts }).setDepth(D.modal + 1)); + } - const buttons = []; - const valid = []; - for (let s = 1; s < this.gs.players.length; s++) { - if (this.gs.players[s].skipped) continue; - valid.push(s); - } - if (valid.length === 0) { - // No valid target; just close and reset. - overlay.destroy(); panel.destroy(); title.destroy(); - this.setStatus('No one to skip. Pick a different card to discard.'); - this.selectedHandIdx = null; - this.clearHighlights(); - return; - } - const startX = CX - ((valid.length - 1) * 180) / 2; - valid.forEach((s, i) => { - const opp = this.opponents[s - 1]; - const name = opp?.name ?? `Player ${s + 1}`; - const btn = new Button(this, startX + i * 180, CY + 10, name, () => { - overlay.destroy(); panel.destroy(); title.destroy(); - for (const b of buttons) b.destroy(); - cancelBtn.destroy(); - const next = applyDiscard(this.gs, handIdx, s); - if (next === this.gs) { this.setStatus("Can't skip that player."); return; } - this.opponentPortraits[s]?.playEmotion('upset'); - this.gs = next; - this.renderAll(); - this.afterTurnTransition(); - }, { width: 160, height: 56, fontSize: 18 }).setDepth(D.modal); - buttons.push(btn); + openPause() { + if (this.modal || this.mode === 'summary') return; + this.openModal({ w: 520, h: 470, onEscape: () => this.closeModal() }); + this.modalText(CX, CY - 180, 'Paused', { fontFamily: 'Righteous', fontSize: '46px', color: COLORS.goldHex }); + this.modalButton(CX, CY - 100, 'Resume', () => this.closeModal(), { width: 300 }); + this.modalButton(CX, CY - 36, 'Settings', () => { this.closeModal(); this.openSettings(); }, { width: 300 }); + this.modalButton(CX, CY + 28, 'Score sheet', () => { this.closeModal(); this.openScorePad({ readOnly: true }); }, { width: 300 }); + this.modalButton(CX, CY + 92, 'New game', () => this.confirm('Start a new game?', 'This match will be thrown out.', 'New game', () => this.restartMatch()), { width: 300, variant: 'ghost' }); + this.modalButton(CX, CY + 156, 'Leave table', () => this.onLeave(), { width: 300, variant: 'ghost' }); + } + + confirm(title, body, yes, onYes, { no = 'Cancel', onNo = null } = {}) { + this.openModal({ w: 620, h: 300, onEscape: () => { this.closeModal(); onNo?.(); } }); + this.modalText(CX, CY - 88, title, { fontFamily: 'Righteous', fontSize: '34px', color: COLORS.textHex }); + this.modalText(CX, CY - 24, body, { fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex, align: 'center', wordWrap: { width: 540 } }); + this.modalButton(CX - 130, CY + 72, yes, () => { this.closeModal(); onYes(); }, { width: 220 }); + this.modalButton(CX + 130, CY + 72, no, () => { this.closeModal(); onNo?.(); }, { width: 220, variant: 'ghost' }); + this.modal.onEnter = () => { this.closeModal(); onYes(); }; + } + + confirmDiscard(card, why, onYes) { + this.confirm(`Discard the ${cardName(card)}?`, why, 'Discard it', onYes, { no: 'Keep it' }); + } + + onLeave() { + const inMatch = this.history.length > 0 || this.mode === 'human' || this.mode === 'ai'; + if (!inMatch || this.gs?.roundPhase === 'gameOver') { this.scene.start('GameMenu'); return; } + this.confirm('Leave this match?', 'Your progress in this match will be lost.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay' }); + } + + openSkipPicker(id, targets) { + const w = 260 * targets.length + 120, h = 430; + this.openModal({ w, h, onEscape: () => this.closeModal() }); + this.modalText(CX, CY - h / 2 + 48, 'Skip whose next turn?', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.goldHex }); + const x0 = CX - ((targets.length - 1) * 260) / 2; + const idx = () => this.me().hand.findIndex(c => c.id === id); + const boxTop = CY - 118, boxH = 214; + targets.forEach((s, i) => { + const p = this.gs.players[s]; + const x = x0 + i * 260; + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.fillStyle(0x000000, 0.35); + g.fillRoundedRect(x - 115, boxTop, 230, boxH, 14); + g.lineStyle(3, SEAT_COLORS[s], 1); + g.strokeRoundedRect(x - 115, boxTop, 230, boxH, 14); + // profile thumbnail (a static copy — the live video can't sit inside a modal) + const py = boxTop + 44, pr = 30; + for (const o of this.portraits[s]?.renderInto?.(x, py, pr, D.modal + 2) ?? []) this.addToModal(o); + const ring = this.addToModal(this.add.graphics().setDepth(D.modal + 4)); + ring.lineStyle(3, SEAT_COLORS[s], 1); + ring.strokeCircle(x, py, pr + 3); + this.modalText(x, boxTop + 96, this.shortName(s, 14), { fontFamily: 'Righteous', fontSize: '22px', color: SEAT_HEX[s] }); + this.modalText(x, boxTop + 124, `Phase ${p.phase}${p.laidDown ? ' · laid down' : ''}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex }); + this.modalText(x, boxTop + 148, `${p.hand.length} cards · ${p.score} pts`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex }); + this.modalButton(x, boxTop + boxH - 28, 'Skip', () => { this.closeModal(); this.finishDiscard(idx(), s); }, { width: 140, height: 38, fontSize: 18 }); }); - const cancelBtn = new Button(this, CX, CY + h / 2 - 40, 'Cancel', () => { - overlay.destroy(); panel.destroy(); title.destroy(); - for (const b of buttons) b.destroy(); - cancelBtn.destroy(); - }, { variant: 'ghost', width: 160, height: 40, fontSize: 16 }).setDepth(D.modal); + this.modalButton(CX, CY + h / 2 - 40, 'Cancel', () => this.closeModal(), { width: 180, height: 42, fontSize: 17, variant: 'ghost' }); } - commitHit(target) { - if (this.selectedHandIdx == null) return; - const handIdx = this.selectedHandIdx; - this.selectedHandIdx = null; - this.clearHighlights(); - const next = applyHit(this.gs, handIdx, target.targetSeat, target.groupIdx, target.position); - if (next === this.gs) { this.setStatus("Can't hit there."); return; } - playSound(this, SFX.CARD_PLACE); - this.gs = next; - this.renderAll(); - if (this.gs.roundPhase === 'roundOver' || this.gs.roundPhase === 'gameOver') { - this.handleRoundEnd(); - return; - } - if (this.gs.players[0].hand.length === 0) { - this.handleRoundEnd(); - return; - } - this.setStatus('Hit! Hit again or discard.'); - } - - afterTurnTransition() { - if (this.gs.roundPhase === 'roundOver' || this.gs.roundPhase === 'gameOver') { - this.handleRoundEnd(); - return; - } - this.maybeStartAITurn(); - } - - maybeStartAITurn() { - if (this.gs.currentPlayer === 0) { - this.setStatus('Your turn — draw from deck or discard.'); - return; - } - this.runAIStep(); - } - - // ── AI loop ───────────────────────────────────────────────────────────── - - runAIStep() { - if (this.matchOver) return; - if (this.gs.roundPhase !== 'play') { this.handleRoundEnd(); return; } - if (this.gs.currentPlayer === 0) { - this.setStatus('Your turn — draw from deck or discard.'); - return; - } - const seat = this.gs.currentPlayer; - const name = this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`; - this.setStatus(`${name}'s turn…`); - this.time.delayedCall(250, () => this.applyAIAction()); - } - - applyAIAction() { - if (this.matchOver) return; - if (this.gs.roundPhase !== 'play') { this.handleRoundEnd(); return; } - const action = chooseAction(this.gs); - if (!action) { this.runAIStep(); return; } - - const seat = this.gs.currentPlayer; - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - - const apply = () => { - if (this.matchOver) return; - let next; - if (action.type === 'drawDeck') next = applyDrawFromDeck(this.gs); - else if (action.type === 'drawDiscard') next = applyDrawFromDiscard(this.gs); - else if (action.type === 'laydown') next = applyLaydown(this.gs, action.groups); - else if (action.type === 'hit') next = applyHit(this.gs, action.handIdx, action.targetSeat, action.groupIdx, action.position); - else if (action.type === 'discard') next = applyDiscard(this.gs, action.handIdx, action.skipTargetSeat ?? null); - else next = this.gs; - if (next === this.gs) { - next = applyDiscard(this.gs, 0); - } - if (action.type === 'discard' && action.skipTargetSeat != null) { - this.opponentPortraits[action.skipTargetSeat]?.playEmotion('upset'); - } - this.gs = next; - this.renderAll(); - if (this.gs.roundPhase === 'roundOver' || this.gs.roundPhase === 'gameOver') { - this.handleRoundEnd(); - return; - } - if (this.gs.currentPlayer === 0) { - this.setStatus('Your turn — draw from deck or discard.'); - return; - } - this.time.delayedCall(150, () => this.applyAIAction()); + openSettings(onDone = null) { + const back = () => { this.closeModal(); onDone?.(); }; + this.openModal({ w: 760, h: 520, onEscape: back }); + const y0 = CY - 196; + this.modalText(CX, y0, 'Table Settings', { fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex }); + const row = (y, label, options, current, apply) => { + this.addToModal(this.add.text(CX - 330, y, label, { + fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + const btns = []; + const bw = 104, gap = 10; + const startX = CX + 330 - options.length * bw - (options.length - 1) * gap + bw / 2; + options.forEach(([value, text], i) => { + const b = new Button(this, startX + i * (bw + gap), y, text, () => { + apply(value); + btns.forEach(([v, bb]) => bb.setActive(v === value)); + this.saveSettings(); + }, { width: bw, height: 42, fontSize: 15 }).setDepth(D.modal + 1); + b.setActive(value === current); + btns.push([value, b]); + this.addToModal(b); + }); }; - - if (action.type === 'drawDeck') { - playSound(this, SFX.CARD_DEAL); - this._flyCard(DRAW_POS.x, DRAW_POS.y, layout.handStart.x, layout.handStart.y, - { value: 'back', id: -1 }, { faceUp: false, rotation: layout.rotateCards, duration: 450 }, apply); - } else if (action.type === 'drawDiscard') { - const top = discardTop(this.gs); - playSound(this, SFX.CARD_DEAL); - this._flyCard(DISCARD_POS.x, DISCARD_POS.y, layout.handStart.x, layout.handStart.y, - top, { faceUp: true, rotation: layout.rotateCards, duration: 450 }, apply); - } else if (action.type === 'discard') { - const card = this.gs.players[seat].hand[action.handIdx]; - playSound(this, SFX.CARD_PLACE); - this._flyCard(layout.handStart.x, layout.handStart.y, DISCARD_POS.x, DISCARD_POS.y, - card, { faceUp: true, rotation: layout.rotateCards, duration: 380 }, apply); - } else if (action.type === 'laydown') { - this.opponentPortraits[seat]?.playEmotion('happy'); - playSound(this, SFX.CARD_SHOW); - this._animateAILaydown(seat, layout, action.groups, apply); - } else if (action.type === 'hit') { - const card = this.gs.players[seat].hand[action.handIdx]; - const gc = this._getGroupCenter({ targetSeat: action.targetSeat, groupIdx: action.groupIdx }); - playSound(this, SFX.CARD_PLACE); - this._flyCard(layout.handStart.x, layout.handStart.y, - gc ? gc.x : CX, gc ? gc.y : CY, - card, { faceUp: true, rotation: layout.rotateCards, duration: 380 }, apply); - } else { - apply(); - } - } - - // ── Round / match end ─────────────────────────────────────────────────── - - handleRoundEnd() { - if (this.gs.roundPhase === 'gameOver') { - this.matchOver = true; - this.recordHistory(); - this.showMatchEndPanel(); - return; - } - // roundOver - this.showRoundSummaryPanel(); - } - - showRoundSummaryPanel() { - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setInteractive().setDepth(D.modal); - const w = 720, h = 460; - const bg = this.add.rectangle(CX, CY, w, h, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - const items = [overlay, bg]; - - const summary = this.gs.lastRoundSummary; - const winnerName = this.nameForSeat(summary.winnerSeat); - const title = this.add.text(CX, CY - h / 2 + 40, `Round ${summary.roundNum} — ${winnerName} went out`, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.modal); - items.push(title); - - summary.rows.forEach((row, i) => { - const y = CY - h / 2 + 100 + i * 50; - const name = this.nameForSeat(row.seat); - const status = row.cleared10 ? 'cleared phase 10!' : row.advanced ? `→ phase ${row.phaseNext}` : `still phase ${row.phaseNext}`; - const t = this.add.text(CX - w / 2 + 36, y, `${name}`, { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.textHex, - }).setDepth(D.modal); - const sc = this.add.text(CX - 100, y, `+${row.pointsThisRound} (total ${row.totalScore})`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setDepth(D.modal); - const ph = this.add.text(CX + 160, y, status, { - fontFamily: '"Julius Sans One"', fontSize: '18px', - color: row.advanced ? COLORS.goldHex : COLORS.dangerHex, - }).setDepth(D.modal); - items.push(t, sc, ph); + row(y0 + 86, 'Opponent pace', [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], this.settings.pace, (v) => { this.settings.pace = v; }); + row(y0 + 152, 'Card hints (★ keep · ▼ toss · + hit)', [[false, 'Off'], [true, 'On']], this.settings.hints, (v) => { this.settings.hints = v; this.layout(); }); + row(y0 + 218, 'Warn before tossing a Wild / phase card', [[false, 'Off'], [true, 'On']], this.settings.warn, (v) => { this.settings.warn = v; }); + row(y0 + 284, 'Hand order', [['manual', 'Manual'], ['number', '1·2·3'], ['color', 'Color'], ['phase', 'Phase']], this.settings.sort, (v) => { + this.settings.sort = v; this.sortHand(); this.layout(); this.refreshSortButtons(); }); - - const tieNote = this.gs.matchTied ? 'Tie among phase 10 finishers — extra round!' : null; - if (tieNote) { - items.push(this.add.text(CX, CY + h / 2 - 90, tieNote, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.modal)); - } - - const btn = new Button(this, CX, CY + h / 2 - 50, 'Next round', () => { - for (const o of items) o.destroy(); - btn.destroy(); - this.gs = startNextRound(this.gs); - playSound(this, SFX.CARD_SHUFFLE); - this.renderAll(); - this.maybeStartAITurn(); - }, { width: 240, height: 48, fontSize: 20 }).setDepth(D.modal); + this.modalText(CX, y0 + 340, 'Opponent hand speed also follows each opponent\'s skill.', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex }); + this.modalButton(CX, y0 + 404, 'Done', back, { width: 220, height: 50, fontSize: 21 }); } - showMatchEndPanel() { - const winner = this.gs.matchWinner; - const youWon = winner === 0; - const name = this.nameForSeat(winner); - const msg = youWon ? `You win!` : `${name} wins!`; - this.setStatus(msg); - - for (let s = 1; s < this.gs.players.length; s++) { - const p = this.opponentPortraits[s]; - if (!p) continue; - if (winner === s) p.playEmotion?.('win'); - else p.playEmotion?.('loss'); - } - - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.65) - .setInteractive().setDepth(D.modal); - const w = 720, h = 360; - this.add.rectangle(CX, CY, w, h, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - this.add.text(CX, CY - h / 2 + 56, msg, { - fontFamily: 'Righteous', fontSize: '42px', - color: youWon ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal); - - const me = this.gs.players[0]; - this.add.text(CX, CY - 10, `Final score: ${me.score} (lower is better)`, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modal); - - new Button(this, CX - 130, CY + h / 2 - 60, 'Play again', () => { - overlay.destroy(); - this.scene.restart({ - game: this.gameDef, opponents: this.opponents, - playfield: this.playfield, cardBack: this.cardBack, + openPhases() { + if (this.modal || !this.gs) return; + const h = 150 + PHASES.length * 62; + this.openModal({ w: 760, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 52, 'The Ten Phases', { fontFamily: 'Righteous', fontSize: '38px', color: COLORS.goldHex }); + PHASES.forEach((ph, i) => { + const y = top + 112 + i * 62; + const mine = this.me().phase === ph.num && this.me().clearedAt == null; + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.fillStyle(mine ? 0xf2c14e : 0x000000, mine ? 0.18 : 0.25); + g.fillRoundedRect(CX - 340, y - 26, 680, 52, 10); + if (mine) { g.lineStyle(2, 0xf2c14e, 0.9); g.strokeRoundedRect(CX - 340, y - 26, 680, 52, 10); } + this.addToModal(this.add.text(CX - 316, y, `${ph.num}`, { fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + this.addToModal(this.add.text(CX - 270, y, ph.short, { fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + let k = 0; + this.gs.players.forEach((p, s) => { + const on = p.clearedAt == null && p.phase === ph.num; + const passed = p.clearedAt != null || p.phase > ph.num; + if (!on && !passed) return; + const x = CX + 316 - k * 30; + k++; + const dot = this.addToModal(this.add.circle(x, y, 11, SEAT_COLORS[s], on ? 1 : 0.28).setDepth(D.modal + 2)); + if (on) dot.setStrokeStyle(2, 0xffffff, 0.9); + this.addToModal(this.add.text(x, y, s === 0 ? 'Y' : this.nameForSeat(s)[0].toUpperCase(), { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: on ? '#1a0e06' : '#c9b08a', + }).setOrigin(0.5).setDepth(D.modal + 3)); }); - }, { width: 220, fontSize: 22 }).setDepth(D.modal); - new Button(this, CX + 130, CY + h / 2 - 60, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 220, fontSize: 22 }).setDepth(D.modal); + }); + this.modalButton(CX, top + h - 40, 'Back to the table', () => this.closeModal(), { width: 280, height: 46, fontSize: 18 }); + } + + // The paper score pad: round-by-round. Doubles as the round-end screen. + openScorePad({ summary = null, readOnly = false } = {}) { + if (!this.gs) return; + const rows = this.playerCount; + const w = 1080, h = 250 + rows * 62 + 90; + const matchOver = this.gs.roundPhase === 'gameOver' && !readOnly; + const m = this.openModal({ w, h, paper: true, onEscape: readOnly ? () => this.closeModal() : null, freeze: readOnly }); + const top = CY - h / 2, left = CX - w / 2; + const ink = '#22201a', blue = '#1c3f8f', red = '#b8231f', green = '#1e7a3b', grey = '#6c6450'; + let title; + if (readOnly) title = `Score sheet — round ${this.gs.roundNum}`; + else if (matchOver) title = this.gs.matchWinner === 0 ? 'You win the match!' : `${this.nameForSeat(this.gs.matchWinner)} wins the match!`; + else { + const s = this.gs.lastRoundSummary; + title = s.winnerSeat === 0 ? `Round ${s.roundNum} — you went out!` : `Round ${s.roundNum} — ${this.nameForSeat(s.winnerSeat)} went out`; + } + this.modalText(CX, top + 62, title, { fontFamily: FONT_HAND, fontSize: '44px', color: matchOver && this.gs.matchWinner === 0 ? red : ink }); + const sub = matchOver ? 'Lowest score among players who finished Phase 10 wins' + : this.gs.matchTied && !readOnly ? 'Tie at the top — one more round to settle it!' + : 'Points are bad: lowest total wins once someone finishes Phase 10'; + this.modalText(CX, top + 104, sub, { fontFamily: '"Julius Sans One"', fontSize: '14px', color: grey }); + + const shown = this.history.slice(-8); + const first = this.history.length - shown.length + 1; + const nameX = left + 120, colX0 = left + 380, colW = 66, phaseX = left + w - 190, totalX = left + w - 80; + const headY = top + 150; + this.modalText(nameX + 60, headY, 'Player', { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + shown.forEach((_, i) => this.modalText(colX0 + i * colW, headY, `R${first + i}`, { fontFamily: FONT_HAND, fontSize: '22px', color: grey })); + this.modalText(phaseX, headY, 'Phase', { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + this.modalText(totalX, headY, 'Total', { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + const totals = this.gs.players.map(p => p.score); + const finishers = this.gs.players.filter(p => p.clearedAt != null); + const bestPool = finishers.length ? finishers : this.gs.players; + const best = Math.min(...bestPool.map(p => p.score)); + const writes = []; + for (let seat = 0; seat < rows; seat++) { + const y = headY + 56 + seat * 62; + const p = this.gs.players[seat]; + this.addToModal(this.add.circle(nameX - 22, y, 8, SEAT_COLORS[seat]).setDepth(D.modal + 1)); + this.addToModal(this.add.text(nameX, y, this.shortName(seat, 14), { fontFamily: FONT_HAND, fontSize: '28px', color: ink }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + shown.forEach((sum, i) => { + const r = sum.rows.find(x => x.seat === seat); + const isNew = summary && i === shown.length - 1; + const t = this.add.text(colX0 + i * colW, y - 6, r.pointsThisRound ? `+${r.pointsThisRound}` : '0', { + fontFamily: FONT_HAND, fontSize: '25px', color: r.pointsThisRound ? blue : green, + }).setOrigin(0.5).setDepth(D.modal + 1); + const mk = this.add.text(colX0 + i * colW, y + 17, r.advanced ? '✓' : '✗', { + fontFamily: 'sans-serif', fontSize: '14px', color: r.advanced ? green : red, + }).setOrigin(0.5).setDepth(D.modal + 1).setAlpha(0.8); + this.addToModal(t); + this.addToModal(mk); + if (isNew) { t.setAlpha(0); mk.setAlpha(0); writes.push(t, mk); } + }); + const ph = this.add.text(phaseX, y, p.clearedAt != null ? '10 ✓' : String(p.phase), { fontFamily: FONT_HAND, fontSize: '30px', color: ink }).setOrigin(0.5).setDepth(D.modal + 1); + const tot = this.add.text(totalX, y, String(totals[seat]), { + fontFamily: FONT_HAND, fontSize: '32px', color: (bestPool.includes(p) && totals[seat] === best) ? red : ink, + }).setOrigin(0.5).setDepth(D.modal + 1); + this.addToModal(ph); + this.addToModal(tot); + if (summary) { ph.setAlpha(0); tot.setAlpha(0); writes.push(ph, tot); } + if (matchOver && seat === this.gs.matchWinner) { + const ring = this.add.graphics().setDepth(D.modal + 1); + ring.lineStyle(3, 0xb8231f, 0.85); + ring.strokeEllipse(totalX, y, 96, 52); + this.addToModal(ring); + } + } + writes.forEach((t, i) => this.tweens.add({ targets: t, alpha: t.alpha === 0 ? 1 : t.alpha, delay: 250 + i * 110, duration: 160 })); + if (writes.length) this.time.delayedCall(250, () => playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.6 })); + + const btnY = top + h - 56; + if (readOnly) { + this.modalButton(CX, btnY, 'Back to the table', () => this.closeModal(), { width: 300, height: 50 }); + return m; + } + if (matchOver) { + this.modalButton(CX - 240, btnY, 'Play again', () => this.restartMatch(), { width: 220 }); + } else { + const b = this.modalButton(CX - 240, btnY, 'Next round', () => this.nextRound(), { width: 220, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + void b; + this.modal.onEnter = () => this.nextRound(); + } + this.modalButton(CX, btnY, 'Settings', () => { this.closeModal(); this.openSettings(() => this.openScorePad({})); }, { width: 200, variant: 'ghost' }); + this.modalButton(CX + 240, btnY, 'Leave', () => this.scene.start('GameMenu'), { width: 220, variant: 'ghost' }); + return m; + } + + async nextRound() { + this.closeModal(); + if (this.gs.roundPhase !== 'roundOver' || this.mode !== 'summary') return; + this.mode = 'deal'; + this.updateDock(); + await this.sweepTable(); + if (!this.alive()) return; + this.gs = startNextRound(this.gs); + this.startRound(); + } + + // Gather every card on the table back into the deck before the next deal. + async sweepTable() { + const deck = { ...this.L.deck }; + let i = 0; + for (const c of this.sprites.values()) { + c.mark.setVisible(false); + c.chip.setVisible(false); + c.glow.setVisible(false); + this.tweenCard(c, deck, { faceUp: false, duration: 360, delay: Math.min(500, i++ * 14), lift: 0.4 }); + } + this.slotG.clear(); + for (const ls of this.labels) ls.forEach(t => t.setVisible(false)); + if (i) playSound(this, SFX.CARD_SHUFFLE); + await this.wait(Math.min(500, i * 14) + 420); + } + + restartMatch() { + this.closeModal(); + this.scene.restart({ game: this.gameDef, opponents: this.opponents, playfield: this.playfield, cardBack: this.cardBack }); + } + + // ── End of round: out! → reveal → count-back → phases → score pad ────────── + async onRoundOver() { + if (this.mode === 'ending' || this.mode === 'summary') return; + this.mode = 'ending'; + this.turnToken++; + this.busy = false; + this.stage = null; + this.selectedId = null; + this.hoverId = null; + this.dragState = null; + this.clearDropPreview(); + this.potentialDrag = null; + this.targetG.clear(); + this.input.setDefaultCursor('default'); + for (let s = 1; s < this.playerCount; s++) this.handRest(s, 300); + this.updateDock(); + this.updatePlates(); + this.layout(); + const sum = this.gs.lastRoundSummary; + const winner = sum.winnerSeat; + await this.wait(420); + if (!this.alive()) return; + this.stamp(winner === 0 ? 'You went out!' : `${this.shortName(winner, 14)} went out!`, { x: CX, y: CY - 30 }, SEAT_HEX[winner], { size: 90, hold: 1000 }); + playSound(this, winner === 0 ? SFX.CASINO_WIN : SFX.CARD_SHOW); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(s === winner ? 'happy' : 'upset'); + await this.wait(1250); + if (!this.alive()) return; + + // flip every hand face up + this.revealAll = true; + this.layout({ duration: 360 }); + playSoundEx(this, SFX.CARD_SHOW, { volume: 0.6 }); + await this.wait(800); + if (!this.alive()) return; + + await this.countBack(sum); + if (!this.alive()) return; + await this.phaseResults(sum); + if (!this.alive()) return; + + this.history.push(sum); + this.updatePlates(); + if (this.gs.roundPhase === 'gameOver') { + this.recordHistory(); + playSound(this, this.gs.matchWinner === 0 ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(this.gs.matchWinner === s ? 'win' : 'loss'); + } + this.mode = 'summary'; + this.openScorePad({ summary: sum }); + } + + async countBack(sum) { + let longest = 0; + let ticks = 0; + for (const p of this.gs.players) { + const pl = this.plates[p.seat]; + const t = pl.tallyTxt; + t.setText('+0').setVisible(true).setAlpha(0); + this.tweens.add({ targets: t, alpha: 1, duration: 200 }); + let tally = 0; + const cards = p.hand.slice(); + cards.forEach((card, i) => { + const c = this.sprites.get(card.id); + if (!c) return; + this.sprites.delete(card.id); + const delay = i * 150 + p.seat * 60; + longest = Math.max(longest, delay + 460); + this.tweenCard(c, { x: pl.x, y: pl.y, rot: 0, s: 0.4, q: 1 }, { + delay, duration: 460, lift: 0.8, faceUp: true, onDone: () => { + c.destroy(); + tally += cardPoints(card); + t.setText(`+${tally}`); + if (this.plateTally) { this.plateTally[p.seat] = tally; pl.scoreTxt.setText(`${this.plateInfo(p.seat).score + tally}`); } + this.tweens.add({ targets: t, scale: 1.2, duration: 70, yoyo: true }); + if ((ticks++ % 2) === 0) playSoundEx(this, SFX.CARD_PLACE, { volume: 0.35, rate: 1.1 }); + }, + }); + }); + if (!cards.length) t.setText(p.seat === sum.winnerSeat ? 'Out! 0' : '0').setColor('#8ce99a'); + else t.setColor(SEAT_HEX[p.seat]); + } + await this.wait(longest + 300); + for (const r of sum.rows) this.plates[r.seat].tallyTxt.setText(r.pointsThisRound ? `+${r.pointsThisRound}` : (r.seat === sum.winnerSeat ? 'Out! 0' : '0')); + this.updateBadges(); + } + + async phaseResults(sum) { + const before = this.plateHold; + this.plateHold = null; + this.plateTally = null; + this.updatePlates(); + for (const r of sum.rows) { + const pl = this.plates[r.seat]; + const from = before?.[r.seat]?.phase ?? r.phaseNext; + const text = r.advanced ? (from === 10 ? 'Phase 10 done!' : `Phase ${from} ✓`) : `Phase ${from} again`; + this.floatText({ x: pl.x, y: pl.y + (r.seat === 0 ? -130 : 128) }, text, r.advanced ? '#8ce99a' : '#ff9a7a', { size: 24, ms: 1800, rise: 20 }); + if (r.advanced) { + this.drawLadder(r.seat, from); + const fx = this.add.circle(pl.tx + (from - 1) * 13 + 5, pl.y + 29, 6, SEAT_COLORS[r.seat], 0.9).setDepth(D.plates + 3); + this.tweens.add({ targets: fx, scale: 3.2, alpha: 0, duration: 650, ease: 'Cubic.easeOut', onComplete: () => fx.destroy() }); + } + } + playSoundEx(this, SFX.UI_CHIME, { volume: 0.5 }); + await this.wait(1500); + for (const pl of this.plates) this.tweens.add({ targets: pl.tallyTxt, alpha: 0, duration: 300 }); } async recordHistory() { try { const me = this.gs.players[0]; - const youWon = this.gs.matchWinner === 0; - const opponentScores = []; - for (let s = 1; s < this.gs.players.length; s++) opponentScores.push(this.gs.players[s].score); await api.post('/history/single-player', { slug: 'phase10', - score: me.score, // lower is better, but the schema is generic — record raw score - opponentScores, - result: youWon ? 'win' : 'loss', + score: me.score, + opponentScores: this.gs.players.slice(1).map(p => p.score), + result: this.gs.matchWinner === 0 ? 'win' : 'loss', }); } catch (err) { console.warn('[phase10] failed to record history', err); } } - - // ── Card flight animation ──────────────────────────────────────────────── - - _flyCard(fromX, fromY, toX, toY, card, opts = {}, onComplete) { - const { faceUp = false, rotation = 0, duration = 420 } = opts; - const c = this.makeCardSprite(card, fromX, fromY, { faceUp, rotation }); - c.setDepth(D.card + 5); - this.tweens.add({ - targets: c, x: toX, y: toY, duration, - ease: 'Cubic.easeInOut', - onComplete: () => { c.destroy(); if (onComplete) onComplete(); }, - }); - } - - _animateAILaydown(seat, layout, groups, onComplete) { - if (groups.length === 0) { onComplete(); return; } - const hand = this.gs.players[seat].hand; - let remaining = groups.length; - groups.forEach((group, gi) => { - const repCard = hand.find(c => c.id === group.cardIds[0]) ?? { value: 'back', id: -1 }; - let tx = layout.laidStart.x; - let ty = layout.laidStart.y; - if (layout.laidAxis === 'x') tx += gi * 60; - else ty += gi * 60; - this.time.delayedCall(gi * 130, () => { - this._flyCard(layout.handStart.x, layout.handStart.y, tx, ty, - repCard, { faceUp: true, rotation: layout.rotateCards, duration: 380 }, () => { - remaining--; - if (remaining === 0) onComplete(); - }); - }); - }); - } - - // ── HUD helpers ───────────────────────────────────────────────────────── - - _hasStagedCards() { - return this.stagingGroups?.some((g) => g.slots.some((s) => s !== null)) ?? false; - } - - _shakeStagingButtons() { - const targets = [this.submitBtn, this.clearBtn].filter(Boolean); - if (!targets.length) return; - for (const btn of targets) { - const ox = btn.x; - this.tweens.add({ - targets: btn, - x: { from: ox - 8, to: ox + 8 }, - duration: 60, - ease: 'Sine.easeInOut', - yoyo: true, - repeat: 3, - onComplete: () => { btn.x = ox; }, - }); - } - } - - setStatus(s) { - if (!this.statusText) return; - this.statusText.setText(s); - if (!s) { - this.statusBg.setVisible(false); - return; - } - const pad = 12; - const w = this.statusText.width + pad * 2; - this.statusBg.clear(); - this.statusBg.fillStyle(0x000000, 0.5); - this.statusBg.fillRoundedRect(1040, 838, w, 64, 8); - this.statusBg.setVisible(true); - } - - nameForSeat(seat) { - if (seat === 0) return auth.user?.username ?? 'You'; - return this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`; - } } + +export { COLOR_NAMES, CARD_COLORS }; diff --git a/src/games/phase10/Phase10Logic.js b/src/games/phase10/Phase10Logic.js index 2a12819..e2f3f9d 100644 --- a/src/games/phase10/Phase10Logic.js +++ b/src/games/phase10/Phase10Logic.js @@ -77,6 +77,7 @@ export function createInitialState({ playerCount, seed, startingPlayer = 0 } = { lastRoundSummary: null, drawnThisTurn: false, laidDownThisTurn: false, + takes: [], // this round's discard pick-ups: { seat, value, color, id, turn } }; for (let i = 0; i < playerCount; i++) { state.players.push({ @@ -108,6 +109,7 @@ function dealRound(state) { state.laidDownThisTurn = false; state.roundPhase = 'play'; state.roundWinner = null; + state.takes = []; } // ── Cloning ───────────────────────────────────────────────────────────────── @@ -138,6 +140,7 @@ export function cloneState(state) { : null, drawnThisTurn: state.drawnThisTurn, laidDownThisTurn: state.laidDownThisTurn, + takes: (state.takes ?? []).map((t) => ({ ...t })), }; } @@ -151,6 +154,12 @@ export function discardTop(state) { return state.discardPile.length > 0 ? state.discardPile[state.discardPile.length - 1] : null; } +export function handPoints(hand) { + let pts = 0; + for (const c of hand) pts += cardPoints(c); + return pts; +} + export function cardPoints(card) { if (card.value === 'wild') return POINTS.wild; if (card.value === 'skip') return POINTS.skip; @@ -188,6 +197,7 @@ export function applyDrawFromDiscard(state) { const card = next.discardPile.pop(); next.players[next.currentPlayer].hand.push(card); next.drawnThisTurn = true; + next.takes.push({ seat: next.currentPlayer, value: card.value, color: card.color, id: card.id, turn: next.turnCount }); return next; } @@ -229,12 +239,44 @@ export function applyLaydown(state, groups) { nextPlayer.hand = nextPlayer.hand.filter((c) => !usedIds.has(c.id)); nextPlayer.laidDown = resolved.map((g) => ({ kind: g.kind, - cards: g.cards.map(cloneCard), + cards: orderGroupCards(g.kind, g.cards).map(cloneCard), })); next.laidDownThisTurn = true; return next; } +/** + * Put a group's cards in table order. Runs MUST be in position order (hits and + * runAssignedValues read the ends), so naturals are placed at their values and + * wilds fill the gaps — leftover wilds extend the top (or the bottom when the + * top would pass 12). Sets: naturals then wilds. Colour groups: by value. + */ +export function orderGroupCards(kind, cards) { + const nat = cards.filter((c) => c.value !== 'wild'); + const wild = cards.filter((c) => c.value === 'wild'); + if (kind === 'run') { + const N = cards.length; + const vals = nat.map((c) => c.value).filter((v) => typeof v === 'number'); + if (vals.length !== nat.length) return cards.slice(); + if (!vals.length) return cards.slice(); + const lo = Math.min(...vals), hi = Math.max(...vals); + const minS = Math.max(1, hi - N + 1); + const maxS = Math.min(lo, 13 - N); + if (minS > maxS) return cards.slice(); + const S = maxS; + const byVal = new Map(nat.map((c) => [c.value, c])); + if (byVal.size !== nat.length) return cards.slice(); + const out = []; + let w = 0; + for (let v = S; v < S + N; v++) out.push(byVal.get(v) ?? wild[w++]); + return out; + } + if (kind === 'color') { + return [...nat.slice().sort((a, b) => a.value - b.value), ...wild]; + } + return [...nat, ...wild]; +} + // ── Hitting ───────────────────────────────────────────────────────────────── /** @@ -260,12 +302,12 @@ export function canHit(group, card, position) { return card.color === col; } if (group.kind === 'run') { - if (card.value === 'wild') return true; // Reconstruct the assigned values from the run order. const vals = runAssignedValues(group); if (!vals) return false; - if (position === 'low') return vals[0] > 1 && card.value === vals[0] - 1; - if (position === 'high') return vals[vals.length - 1] < 12 && card.value === vals[vals.length - 1] + 1; + const wild = card.value === 'wild'; + if (position === 'low') return vals[0] > 1 && (wild || card.value === vals[0] - 1); + if (position === 'high') return vals[vals.length - 1] < 12 && (wild || card.value === vals[vals.length - 1] + 1); return false; } return false; @@ -366,9 +408,14 @@ export function applyDiscard(state, handIdx, skipTargetSeat = null) { const card = player.hand[handIdx]; if (card.value === 'skip') { - if (skipTargetSeat == null || skipTargetSeat === seat) return state; - const tgt = state.players[skipTargetSeat]; - if (!tgt || tgt.skipped) return state; + const anyTarget = skipTargets(state, seat).length > 0; + if (skipTargetSeat == null) { + if (anyTarget) return state; // must pick someone while anyone can be skipped + } else { + if (skipTargetSeat === seat) return state; + const tgt = state.players[skipTargetSeat]; + if (!tgt || tgt.skipped) return state; + } } const next = cloneState(state); @@ -389,6 +436,15 @@ export function applyDiscard(state, handIdx, skipTargetSeat = null) { return next; } +/** Seats a Skip discarded by `seat` may target (not yourself, not already skipped). */ +export function skipTargets(state, seat) { + const out = []; + for (let s = 0; s < state.players.length; s++) { + if (s !== seat && !state.players[s].skipped) out.push(s); + } + return out; +} + function advanceTurn(state) { state.turnCount += 1; let nextSeat = (state.currentPlayer + 1) % state.players.length; diff --git a/src/games/phase10/Phase10Table.js b/src/games/phase10/Phase10Table.js new file mode 100644 index 0000000..2ac6170 --- /dev/null +++ b/src/games/phase10/Phase10Table.js @@ -0,0 +1,366 @@ +// Phase 10 table layout — Phaser-free so tools/verifyPhase10.js can test it. +// +// A retro rec-room card table (chrome-banded rim, quilted vinyl top) seen in +// mild perspective from the human's chair, built on the shared casino +// projection (makeProjection). Each player has: +// +// hand — the cards they hold, fanned at the table's edge (the human's is +// full-size along the bottom of the screen, face up) +// mat — a placemat on the table in front of them where their phase is +// built and laid down. Cards on mats stay upright so every number +// reads from your chair. +// plate — the name / phase-ladder / score nameplate +// +// Seats per player count: +// 2 human · across +// 3 human · far-left corner · far-right corner +// 4 human · left side · across · right side +// +// Logic seats fill clockwise from the human's left (seat 1 = left / far-left). +// Mats are rectangles in table space (u ∈ [-1, 1] left→right, v ∈ [0, 1] +// far→near) so they foreshorten like the table does; a mat holds one or two +// rows, and each row lays its cards at that row's depth scale. + +import { makeProjection } from '../../ui/casino/CasinoGeometry.js'; + +export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 }; +export const P = makeProjection(VIEW); +export const SQ = VIEW.squash; +export const CARD_W = 96; +export const CARD_H = 134; +export const W = 1920, H = 1080; + +// Seat colours (human gold, then blue, red, green). +export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c]; +export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c']; + +// ── Table outline (table space: u ∈ [-1, 1], v ∈ [0, 1], far → near) ───────── +export const TABLE = { halfU: 1, corner: 0.17 }; +export const FELT_K = 0.955; // vinyl inset from the outer chrome (fraction of the outline) +export const RAIL_FACE_PX = 34; // visible front face of the table edge at s = 1 + +export function outlineUV(k = 1, steps = 14) { + const cu = 0, cv = 0.5; + const hu = TABLE.halfU * k, hv = 0.5 * k, r = TABLE.corner * k; + const rv = r * 0.62; + const pts = []; + const corner = (ox, oy, a0) => { + for (let i = 0; i <= steps; i++) { + const a = a0 + (Math.PI / 2) * (i / steps); + pts.push({ u: ox + Math.cos(a) * r, v: oy + Math.sin(a) * rv }); + } + }; + corner(cu + hu - r, cv + hv - rv, 0); + corner(cu - hu + r, cv + hv - rv, Math.PI / 2); + corner(cu - hu + r, cv - hv + rv, Math.PI); + corner(cu + hu - r, cv - hv + rv, Math.PI * 1.5); + return pts; +} + +export function outline(k = 1, steps = 14) { + return outlineUV(k, steps).map(p => P.project(p.u, p.v)); +} + +export function pointInPoly(pt, poly) { + let inside = false; + for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { + const a = poly[i], b = poly[j]; + if ((a.y > pt.y) !== (b.y > pt.y) && pt.x < ((b.x - a.x) * (pt.y - a.y)) / (b.y - a.y) + a.x) inside = !inside; + } + return inside; +} + +export function onFelt(pt, k = FELT_K) { + const { u, v } = P.unproject(pt.x, pt.y); + return pointInPoly({ x: u, y: v }, outlineUV(k).map(p => ({ x: p.u, y: p.v }))); +} + +// ── Seats ──────────────────────────────────────────────────────────────────── +// hand: anchor (screen), rot (owner frame → screen), k (card scale), spread +// (px between cards at k), curve (px drop per step² toward the owner), +// tilt (rad per step), q (1 = held upright, SQ = lying flat) +// mat: table-space rect + rows + k (card scale on top of the depth scale) +const HUMAN = { + hand: { x: 960, y: 994, rot: 0, k: 1, spread: 82, curve: 1.3, tilt: 0.034, q: 1 }, + mat: { u0: -0.56, u1: 0.56, v0: 0.70, v1: 0.865, rows: 1, k: 0.74 }, + plate: { x: 190, y: 902 }, +}; + +const opp = (x, y, rot, k, spread) => ({ x, y, rot, k, spread, curve: 0.5, tilt: 0.03, q: 1 }); + +const SEATS = { + 2: [ + HUMAN, + { + hand: opp(960, 74, Math.PI, 0.5, 30), + mat: { u0: -0.56, u1: 0.56, v0: 0.15, v1: 0.345, rows: 1, k: 0.7 }, + plate: { x: 1420, y: 86 }, + }, + ], + 3: [ + HUMAN, + { + hand: opp(600, 76, Math.PI - 0.1, 0.48, 29), + mat: { u0: -0.84, u1: -0.06, v0: 0.16, v1: 0.355, rows: 1, k: 0.66 }, + plate: { x: 190, y: 150 }, + }, + { + hand: opp(1320, 76, Math.PI + 0.1, 0.48, 29), + mat: { u0: 0.06, u1: 0.84, v0: 0.16, v1: 0.355, rows: 1, k: 0.66 }, + plate: { x: 1730, y: 150 }, + }, + ], + 4: [ + HUMAN, + { + hand: opp(84, 520, Math.PI / 2, 0.46, 30), + mat: { u0: -0.93, u1: -0.4, v0: 0.37, v1: 0.67, rows: 2, k: 0.64 }, + plate: { x: 190, y: 150 }, + }, + { + hand: opp(960, 74, Math.PI, 0.46, 28), + mat: { u0: -0.5, u1: 0.5, v0: 0.13, v1: 0.33, rows: 1, k: 0.66 }, + plate: { x: 1400, y: 84 }, + }, + { + hand: opp(1836, 520, -Math.PI / 2, 0.46, 30), + mat: { u0: 0.4, u1: 0.93, v0: 0.37, v1: 0.67, rows: 2, k: 0.64 }, + plate: { x: 1730, y: 150 }, + }, + ], +}; + +export const PLATE = { w: 300, h: 96 }; +export const PILE_K = 0.92; +export const DECK_UV = { u: -0.105, v: 0.5 }; +export const DISCARD_UV = { u: 0.105, v: 0.5 }; + +// HUD furniture (screen rects, centre + size) — checked for overlaps by verify. +export const TOP_BUTTONS = [ + { x: 70, y: 38, w: 110, h: 40, label: 'Menu' }, + { x: 190, y: 38, w: 110, h: 40, label: 'Scores' }, + { x: 310, y: 38, w: 110, h: 40, label: 'Phases' }, +]; +export const DOCK = { x0: 1588, x1: 1904, y0: 846, y1: 1072 }; +export const SORT_ROW = { y: 1020, xs: [90, 190, 290], w: 96, h: 40 }; +export const KEYS_BOX = { x0: 16, x1: 452, y0: 1046, y1: 1078 }; // two lines of keyboard help + +const rot2 = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) }); + +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(`Phase 10 layout supports 2..4 players, got ${playerCount}`); + const seats = defs.map((d, seat) => ({ seat, hand: d.hand, mat: d.mat, plate: d.plate })); + const deckP = P.project(DECK_UV.u, DECK_UV.v); + const discP = P.project(DISCARD_UV.u, DISCARD_UV.v); + const out = { + playerCount, + seats, + deck: { x: deckP.x, y: deckP.y, rot: 0, s: deckP.s * PILE_K, q: SQ }, + discard: { x: discP.x, y: discP.y, rot: 0, s: discP.s * PILE_K, q: SQ }, + }; + cache.set(playerCount, out); + return out; +} + +// Card container scale for a pose: the squash (q) always acts on the SCREEN +// vertical, so a card turned 90° squashes its local x instead. +export function poseScale(s, rot, q = SQ) { + const c2 = Math.cos(rot) ** 2, s2 = Math.sin(rot) ** 2; + return { sx: s * (c2 + s2 * q), sy: s * (s2 + c2 * q) }; +} + +export function cardCorners(pose) { + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? SQ); + return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => { + const p = rot2(a * (CARD_W / 2) * sx, b * (CARD_H / 2) * sy, pose.rot); + return { x: pose.x + p.x, y: pose.y + p.y }; + }); +} + +export function cardBounds(pose) { + const c = cardCorners(pose); + const xs = c.map(p => p.x), ys = c.map(p => p.y); + return { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) }; +} + +// Is a screen point on a (possibly rotated) card pose? +export function inPose(pt, pose, pad = 0) { + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? SQ); + const d = rot2(pt.x - pose.x, pt.y - pose.y, -pose.rot); + return Math.abs(d.x) <= (CARD_W / 2) * sx + pad && Math.abs(d.y) <= (CARD_H / 2) * sy + pad; +} + +// ── Hands ──────────────────────────────────────────────────────────────────── +/** Pose of card i of n in a seat's hand. `lift` raises it toward the table (px at k). */ +export function handPose(L, seat, i, n, lift = 0) { + const h = L.seats[seat].hand; + const mid = (n - 1) / 2; + const d = i - mid; + // the human's fan tightens a little past 11 cards so it never leaves the gap + const spread = seat === 0 ? Math.min(h.spread, 860 / Math.max(1, n - 1)) : h.spread; + const ox = d * spread * h.k; + const oy = (d * d * h.curve - lift) * h.k; + const p = rot2(ox, oy, h.rot); + return { x: h.x + p.x, y: h.y + p.y, rot: h.rot + d * h.tilt, s: h.k, q: h.q }; +} + +/** Topmost card index of the human's hand under a point (or -1). */ +export function handHit(L, n, pt, liftFor = () => 0) { + for (let i = n - 1; i >= 0; i--) { + if (inPose(pt, handPose(L, 0, i, n, liftFor(i)))) return i; + } + return -1; +} + +/** Where the human's hand would insert a card dropped at screen x. */ +export function handInsertIndex(L, n, x) { + if (n <= 0) return 0; + for (let i = 0; i < n; i++) { + if (x < handPose(L, 0, i, n).x) return i; + } + return n; +} + +/** Bounding rect of the human's hand fan region (for drop-to-hand). */ +export function handZone(L, n) { + const a = handPose(L, 0, 0, Math.max(1, n)); + const b = handPose(L, 0, Math.max(0, n - 1), Math.max(1, n)); + return { x0: Math.min(a.x, b.x) - CARD_W * 0.7, x1: Math.max(a.x, b.x) + CARD_W * 0.7, y0: L.seats[0].hand.y - CARD_H * 0.75, y1: H }; +} + +// Card-count badge for an opponent's hand (end of the fan). +export function handBadge(L, seat) { + const h = L.seats[seat].hand; + const p = rot2(-(5.5 * h.spread + CARD_W / 2 + 10) * h.k, 0, h.rot); + return { x: h.x + p.x, y: h.y + p.y }; +} + +// Where an opponent's ghost hand rests (just in front of their cards) and its rotation. +export function handHome(L, seat) { + const h = L.seats[seat].hand; + const p = rot2(0, -CARD_H * 0.95 * h.k, h.rot); + return { x: h.x + p.x, y: h.y + p.y, rot: h.rot }; +} + +// ── Mats ───────────────────────────────────────────────────────────────────── +export function matCorners(L, seat, pad = 0) { + const m = L.seats[seat].mat; + const du = pad / VIEW.halfW; + return [ + P.project(m.u0 - du, m.v0 - du), P.project(m.u1 + du, m.v0 - du), + P.project(m.u1 + du, m.v1 + du), P.project(m.u0 - du, m.v1 + du), + ]; +} + +export function matCentre(L, seat) { + const m = L.seats[seat].mat; + return P.project((m.u0 + m.u1) / 2, (m.v0 + m.v1) / 2); +} + +const LABEL_GAP = 0.034; // v reserved above each row for its label +const AREA_PAD_PX = 14; + +/** + * Card areas for `groupCount` groups on a seat's mat. Each area is one row of + * cards: { gi, x0, x1, y (row centre), s (card scale), labelY, cx }. + */ +export function groupAreas(L, seat, groupCount) { + const m = L.seats[seat].mat; + const gc = Math.max(1, groupCount); + const rows = []; + if (m.rows === 2 && gc === 2) { + const h = (m.v1 - m.v0) / 2; + rows.push({ v0: m.v0, v1: m.v0 + h, u0: m.u0, u1: m.u1 }); + rows.push({ v0: m.v0 + h, v1: m.v1, u0: m.u0, u1: m.u1 }); + } else if (gc === 2) { + const gap = 0.03; + const mid = (m.u0 + m.u1) / 2; + rows.push({ v0: m.v0, v1: m.v1, u0: m.u0, u1: mid - gap / 2 }); + rows.push({ v0: m.v0, v1: m.v1, u0: mid + gap / 2, u1: m.u1 }); + } else { + rows.push({ v0: m.v0, v1: m.v1, u0: m.u0, u1: m.u1 }); + } + return rows.map((r, gi) => { + const vc = (r.v0 + LABEL_GAP + r.v1) / 2; + const c = P.project((r.u0 + r.u1) / 2, vc); + const a = P.project(r.u0, vc), b = P.project(r.u1, vc); + const s = c.s * m.k; + const top = c.y - (CARD_H / 2) * s * SQ; + return { gi, x0: a.x + AREA_PAD_PX * c.s, x1: b.x - AREA_PAD_PX * c.s, y: c.y, s, labelY: top - 13 * c.s, cx: c.x }; + }); +} + +/** Horizontal step between overlapped cards in an area holding n cards. */ +export function areaStep(area, n) { + const cw = CARD_W * area.s; + if (n <= 1) return 0; + return Math.min(cw * 0.66, (area.x1 - area.x0 - cw) / (n - 1)); +} + +/** Pose of card ci of n in group gi (of groupCount) on a seat's mat. */ +export function groupCardPose(L, seat, gi, groupCount, ci, n) { + const area = groupAreas(L, seat, groupCount)[gi]; + const step = areaStep(area, n); + const cw = CARD_W * area.s; + const total = cw + step * (n - 1); + const x = area.cx - total / 2 + cw / 2 + ci * step; + return { x, y: area.y, rot: 0, s: area.s, q: SQ }; +} + +/** Screen rect of a group (cards actually there, at least `minCount` wide) — hit target + glow. */ +export function groupRect(L, seat, gi, groupCount, n, minCount = 1, pad = 10) { + const area = groupAreas(L, seat, groupCount)[gi]; + const m = Math.max(n, minCount, 1); + const a = groupCardPose(L, seat, gi, groupCount, 0, m); + const b = groupCardPose(L, seat, gi, groupCount, m - 1, m); + const hw = (CARD_W / 2) * area.s, hh = (CARD_H / 2) * area.s * SQ; + return { x0: a.x - hw - pad, x1: b.x + hw + pad, y0: area.y - hh - pad, y1: area.y + hh + pad, cx: (a.x + b.x) / 2, y: area.y, s: area.s }; +} + +/** The whole area of a group (hit target while staging — the slots, not just the cards). */ +export function areaRect(L, seat, gi, groupCount, pad = 6) { + const area = groupAreas(L, seat, groupCount)[gi]; + const hh = (CARD_H / 2) * area.s * SQ; + return { x0: area.x0 - pad, x1: area.x1 + pad, y0: area.y - hh - pad, y1: area.y + hh + pad }; +} + +export const inRect = (pt, r) => pt.x >= r.x0 && pt.x <= r.x1 && pt.y >= r.y0 && pt.y <= r.y1; + +// ── Piles ──────────────────────────────────────────────────────────────────── +// Lift (screen px, toward the camera) that a stack of n cards shows as thickness. +export function stackLift(n, k = 1) { + return Math.min(12, Math.max(0, n - 1) * 0.16) * k; +} + +export function deckTopPose(L, n) { + return { ...L.deck, y: L.deck.y - stackLift(n, L.deck.s) }; +} + +export function discardPose(L, i, n) { + return { ...L.discard, y: L.discard.y - stackLift(Math.min(n, 30), L.discard.s) * (i + 1) / Math.max(1, n) }; +} + +// ── Plates & seat focus ────────────────────────────────────────────────────── +export function plateRect(L, seat) { + const p = L.seats[seat].plate; + return { x0: p.x - PLATE.w / 2, x1: p.x + PLATE.w / 2, y0: p.y - PLATE.h / 2, y1: p.y + PLATE.h / 2 }; +} + +/** Where the turn spotlight sits for a seat (its mat), and how big. */ +export function spotFor(L, seat) { + const c = matCentre(L, seat); + const m = L.seats[seat].mat; + const a = P.project(m.u0, (m.v0 + m.v1) / 2), b = P.project(m.u1, (m.v0 + m.v1) / 2); + const t = P.project(m.u0, m.v0), btm = P.project(m.u0, m.v1); + return { x: c.x, y: c.y, w: (b.x - a.x) * 1.25, h: (btm.y - t.y) * 1.7 + 60 }; +} + +export function rectsOverlap(a, b) { + return a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; +} + +export const centreRect = (r) => ({ x0: r.x - r.w / 2, x1: r.x + r.w / 2, y0: r.y - r.h / 2, y1: r.y + r.h / 2 }); diff --git a/src/games/phase10/PhaseSpec.js b/src/games/phase10/PhaseSpec.js index 82d51aa..c27aa6b 100644 --- a/src/games/phase10/PhaseSpec.js +++ b/src/games/phase10/PhaseSpec.js @@ -175,3 +175,75 @@ function validateRun(cards) { void wildCount; return { ok: true }; } + +// ── Live helpers for the UI ───────────────────────────────────────────────── + +export const COLOR_NAMES = { red: 'Red', blue: 'Blue', yellow: 'Yellow', green: 'Green' }; + +/** "Set of 3", "Run of 4", "7 of one color". */ +export function groupGoalLabel(kind, count) { + if (kind === 'set') return `Set of ${count}`; + if (kind === 'run') return `Run of ${count}`; + return `${count} of one color`; +} + +/** Short name for a card: "Blue 7", "Wild", "Skip". */ +export function cardName(card) { + if (!card) return ''; + if (card.value === 'wild') return 'Wild'; + if (card.value === 'skip') return 'Skip'; + return `${COLOR_NAMES[card.color] ?? card.color} ${card.value}`; +} + +/** + * Status of a partly built group while the player stages it. + * Returns { ok, full, valid, text } — `valid` means "nothing wrong so far", + * `ok` means complete and legal, `text` is a short coaching line. + */ +export function groupStatus(kind, count, cards) { + const n = cards.length; + const goal = groupGoalLabel(kind, count); + if (n === 0) return { ok: false, full: false, valid: true, text: goal }; + if (cards.some((c) => c.value === 'skip')) { + return { ok: false, full: n >= count, valid: false, text: 'Skips can\'t be played' }; + } + if (n > count) return { ok: false, full: true, valid: false, text: `Only ${count} cards` }; + // partial runs are judged against the full window (3 and 5 can still become 3-4-5-6) + const r = kind === 'run' && n < count ? { ok: true } : validateGroup({ kind, cards }); + if (!r.ok) return { ok: false, full: n >= count, valid: false, text: r.reason }; + if (kind === 'run') { + const nat = cards.filter((c) => c.value !== 'wild').map((c) => c.value); + if (new Set(nat).size !== nat.length) return { ok: false, full: n >= count, valid: false, text: 'No repeats in a run' }; + if (nat.length) { + const lo = Math.min(...nat), hi = Math.max(...nat); + if (hi - lo + 1 > count) return { ok: false, full: n >= count, valid: false, text: 'Too spread out' }; + if (Math.max(1, hi - count + 1) > Math.min(lo, 13 - count)) { + return { ok: false, full: n >= count, valid: false, text: 'Won\'t fit in 1–12' }; + } + } + } + if (n === count) return { ok: true, full: true, valid: true, text: `${goal} ✓` }; + const left = count - n; + const nat = cards.find((c) => c.value !== 'wild'); + let need; + if (!nat) need = `${left} more`; + else if (kind === 'set') need = `${left} more ${nat.value}${left > 1 ? 's' : ''} or Wild${left > 1 ? 's' : ''}`; + else if (kind === 'color') need = `${left} more ${COLOR_NAMES[nat.color] ?? nat.color}`; + else need = `${left} more in a row`; + return { ok: false, full: false, valid: true, text: `${n}/${count} · needs ${need}` }; +} + +/** Label for a laid-down group: "Run 3–9", "Set of 7s", "All Blue". */ +export function laidGroupLabel(group, runValues = null) { + const n = group.cards.length; + if (group.kind === 'run') { + if (runValues && runValues.length) return `Run ${runValues[0]}–${runValues[runValues.length - 1]}`; + return `Run of ${n}`; + } + if (group.kind === 'set') { + const v = group.cards.find((c) => c.value !== 'wild')?.value; + return v != null ? `Set of ${v}s · ${n}` : `Set · ${n}`; + } + const col = group.cards.find((c) => c.color)?.color; + return col ? `All ${COLOR_NAMES[col]} · ${n}` : `One color · ${n}`; +} diff --git a/src/scenes/OpponentSelectScene.js b/src/scenes/OpponentSelectScene.js index 4b1eb9b..74ff5ff 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', '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', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) { bio.style.webkitLineClamp = '1'; const skillRow = document.createElement('div'); diff --git a/tools/verifyPhase10.js b/tools/verifyPhase10.js new file mode 100644 index 0000000..71845cd --- /dev/null +++ b/tools/verifyPhase10.js @@ -0,0 +1,433 @@ +#!/usr/bin/env node +// verifyPhase10.js — headless checks for Phase 10: rules (laydowns, run order, +// hits incl. wild bounds, skips, scoring, match end + tie round), the live +// staging helpers, the AI (always legal, skill-scaled timing, advice), the +// table layout for 2/3/4 players (everything on screen and on the table, mats / +// hands / plates / HUD clear of each other, hit-test round trips), and an +// all-AI soak (every round ends, cards are conserved, higher skill wins more). +// Usage: node tools/verifyPhase10.js [--quick] + +import { + createInitialState, buildDeck, applyDrawFromDeck, applyDrawFromDiscard, applyLaydown, applyHit, + applyDiscard, canHit, runAssignedValues, getHitTargets, startNextRound, cardPoints, handPoints, + orderGroupCards, skipTargets, discardTop, cloneState, +} from '../src/games/phase10/Phase10Logic.js'; +import { + PHASES, getPhase, validateLaydown, groupStatus, laidGroupLabel, groupGoalLabel, cardName, +} from '../src/games/phase10/PhaseSpec.js'; +import { chooseAction, findLaydown, adviseHand, aiTiming, HAND_SPEED, PACE } from '../src/games/phase10/Phase10AI.js'; +import { + W, H, CARD_W, CARD_H, SQ, PLATE, TOP_BUTTONS, DOCK, SORT_ROW, KEYS_BOX, layoutFor, handPose, handHit, handInsertIndex, + handZone, handBadge, handHome, groupAreas, groupCardPose, groupRect, areaRect, inRect, inPose, cardBounds, + deckTopPose, discardPose, plateRect, matCorners, onFelt, rectsOverlap, centreRect, spotFor, +} from '../src/games/phase10/Phase10Table.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 nextId = 1000; +const C = (value, color = 'red') => ({ value, color: value === 'wild' || value === 'skip' ? null : color, id: nextId++ }); +const Wd = () => C('wild'); +const Sk = () => C('skip'); + +// Put a hand + phase on seat `seat` and make it that seat's post-draw turn. +function rig(gs, seat, hand, phase = 1) { + gs.players[seat].hand = hand; + gs.players[seat].phase = phase; + gs.currentPlayer = seat; + gs.drawnThisTurn = true; + gs.laidDownThisTurn = false; + return gs; +} + +function apply(gs, a) { + if (a.type === 'drawDeck') return applyDrawFromDeck(gs); + if (a.type === 'drawDiscard') return applyDrawFromDiscard(gs); + if (a.type === 'laydown') return applyLaydown(gs, a.groups); + if (a.type === 'hit') return applyHit(gs, a.handIdx, a.targetSeat, a.groupIdx, a.position); + return applyDiscard(gs, a.handIdx, a.skipTargetSeat ?? null); +} + +const countCards = (gs) => gs.drawPile.length + gs.discardPile.length + + gs.players.reduce((n, p) => n + p.hand.length + (p.laidDown ? p.laidDown.reduce((m, g) => m + g.cards.length, 0) : 0), 0); + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +{ + const deck = buildDeck(); + ok('108-card deck', deck.length === 108); + ok('8 wilds + 4 skips', deck.filter(c => c.value === 'wild').length === 8 && deck.filter(c => c.value === 'skip').length === 4); + ok('2 of each colour/value', [1, 6, 12].every(v => ['red', 'blue', 'yellow', 'green'].every(col => deck.filter(c => c.value === v && c.color === col).length === 2))); + ok('unique ids', new Set(deck.map(c => c.id)).size === 108); + for (const n of [2, 3, 4]) { + const gs = createInitialState({ playerCount: n, seed: 7 }); + ok(`${n}p: 10 cards each`, gs.players.every(p => p.hand.length === 10)); + ok(`${n}p: one card turned up`, gs.discardPile.length === 1); + ok(`${n}p: conserves 108`, countCards(gs) === 108); + ok(`${n}p: takes log empty`, Array.isArray(gs.takes) && gs.takes.length === 0); + } + ok('points: 5 / 10 / 15 / 25', cardPoints(C(9)) === 5 && cardPoints(C(10)) === 10 && cardPoints(Sk()) === 15 && cardPoints(Wd()) === 25); + ok('handPoints sums', handPoints([C(1), C(12), Wd()]) === 40); +} +{ + const gs = createInitialState({ playerCount: 2, seed: 3 }); + gs.discardPile.push(Sk()); + ok('cannot take a Skip from the discard', applyDrawFromDiscard(gs) === gs); + gs.discardPile.push(C(7, 'blue')); + const next = applyDrawFromDiscard(gs); + ok('taking a discard logs it', next.takes.length === 1 && next.takes[0].seat === 0 && next.takes[0].value === 7 && next.takes[0].color === 'blue'); + ok('takes survive a clone', cloneState(next).takes.length === 1); + ok('cannot draw twice', applyDrawFromDeck(next) === next); +} +{ + // laydown validation per phase + const v = (ph, groups) => validateLaydown(ph, groups).ok; + ok('phase 1: two sets of 3', v(1, [{ kind: 'set', cards: [C(4), C(4, 'blue'), Wd()] }, { kind: 'set', cards: [C(9), C(9), C(9, 'green')] }])); + ok('phase 1: mismatched set rejected', !v(1, [{ kind: 'set', cards: [C(4), C(5), Wd()] }, { kind: 'set', cards: [C(9), C(9), C(9)] }])); + ok('phase 4: run of 7 any order', v(4, [{ kind: 'run', cards: [C(7), C(3), Wd(), C(5), C(6), C(4), C(8)] }])); + ok('phase 4: run past 12 rejected', !v(4, [{ kind: 'run', cards: [C(7), C(8), C(9), C(10), C(11), C(12), Wd()].slice(0, 6).concat([C(6)]).map((c, i) => (i === 6 ? C(12) : c)) }])); + ok('phase 8: 7 of one colour', v(8, [{ kind: 'color', cards: [C(1, 'blue'), C(3, 'blue'), C(3, 'blue'), C(9, 'blue'), C(11, 'blue'), Wd(), C(12, 'blue')] }])); + ok('phase 8: mixed colours rejected', !v(8, [{ kind: 'color', cards: [C(1, 'blue'), C(3, 'red'), C(3, 'blue'), C(9, 'blue'), C(11, 'blue'), Wd(), C(12, 'blue')] }])); + ok('all-wild laydown rejected', !v(9, [{ kind: 'set', cards: [Wd(), Wd(), Wd(), Wd(), Wd()] }, { kind: 'set', cards: [Wd(), Wd()] }])); + ok('skip in a laydown rejected', !v(1, [{ kind: 'set', cards: [C(4), C(4), Sk()] }, { kind: 'set', cards: [C(9), C(9), C(9)] }])); +} +{ + // run order normalisation → hits work after an out-of-order laydown + const gs = createInitialState({ playerCount: 2, seed: 11 }); + const run = [C(6), Wd(), C(3), C(4)]; // 3 4 5(W) 6 + const set = [C(10), C(10, 'blue'), C(10, 'green')]; + rig(gs, 0, [...run, ...set, C(2), C(7, 'blue'), C(12)], 2); + const next = applyLaydown(gs, [{ kind: 'set', cardIds: set.map(c => c.id) }, { kind: 'run', cardIds: run.map(c => c.id) }]); + ok('out-of-order run lays down', next !== gs); + const laidRun = next.players[0].laidDown.find(g => g.kind === 'run'); + const vals = runAssignedValues(laidRun); + ok('run stored in position order', vals && vals.join(',') === '3,4,5,6', vals?.join(',')); + ok('wild fills the 5', laidRun.cards[2].value === 'wild'); + const gi = next.players[0].laidDown.indexOf(laidRun); + const tHigh = getHitTargets(next, next.players[0].hand.find(c => c.value === 7)); + ok('7 hits the high end', tHigh.some(t => t.groupIdx === gi && t.position === 'high')); + const tLow = getHitTargets(next, next.players[0].hand.find(c => c.value === 2)); + ok('2 hits the low end', tLow.some(t => t.groupIdx === gi && t.position === 'low')); + ok('12 hits nothing', getHitTargets(next, next.players[0].hand.find(c => c.value === 12)).length === 0); + ok('orderGroupCards: leftover wild goes high', orderGroupCards('run', [C(2), C(3), Wd()]).map(c => c.value).join() === '2,3,wild'); + ok('orderGroupCards: wild goes low at the top', orderGroupCards('run', [C(11), C(12), Wd()]).map(c => c.value).join() === 'wild,11,12'); + ok('orderGroupCards: set naturals first', orderGroupCards('set', [Wd(), C(5), C(5)]).map(c => c.value).join() === '5,5,wild'); +} +{ + // wild hits respect 1..12 + const top = { kind: 'run', cards: [C(9), C(10), C(11), C(12)] }; + ok('wild cannot extend past 12', !canHit(top, Wd(), 'high') && canHit(top, Wd(), 'low')); + const bottom = { kind: 'run', cards: [C(1), C(2), C(3)] }; + ok('wild cannot extend below 1', !canHit(bottom, Wd(), 'low') && canHit(bottom, Wd(), 'high')); + ok('set takes matching or wild', canHit({ kind: 'set', cards: [C(5), C(5)] }, C(5, 'green')) && canHit({ kind: 'set', cards: [C(5), C(5)] }, Wd()) && !canHit({ kind: 'set', cards: [C(5), C(5)] }, C(6))); + ok('colour takes matching colour', canHit({ kind: 'color', cards: [C(1, 'blue')] }, C(9, 'blue')) && !canHit({ kind: 'color', cards: [C(1, 'blue')] }, C(9, 'red'))); + ok('skips never hit', !canHit({ kind: 'set', cards: [C(5)] }, Sk())); +} +{ + // skips + const gs = createInitialState({ playerCount: 2, seed: 5 }); + const sk = Sk(); + rig(gs, 0, [sk, C(3), C(4)]); + ok('skip needs a target while one exists', applyDiscard(gs, 0, null) === gs); + const next = applyDiscard(gs, 0, 1); + ok('2p skip: you go again', next.currentPlayer === 0 && !next.players[1].skipped); + const g3 = createInitialState({ playerCount: 3, seed: 5 }); + rig(g3, 0, [Sk(), C(3), C(4)]); + const n3 = applyDiscard(g3, 0, 2); + ok('3p skip flags the target', n3.players[2].skipped && n3.currentPlayer === 1); + const n3b = rig(n3, 1, [Sk(), C(8)]); + ok('cannot skip an already-skipped seat', applyDiscard(n3b, 0, 2) === n3b); + ok('skipTargets excludes flagged + self', skipTargets(n3b, 1).join() === '0'); + const n3c = applyDiscard(n3b, 0, 0); + ok('both others skipped → turn comes back around', n3c.currentPlayer === 1 && !n3c.players[0].skipped && !n3c.players[2].skipped); + // nobody skippable: a lone Skip may still be thrown + const g4 = createInitialState({ playerCount: 3, seed: 9 }); + g4.players[1].skipped = true; g4.players[2].skipped = true; + rig(g4, 0, [Sk(), C(5)]); + const n4 = applyDiscard(g4, 0, null); + ok('skip with no valid target still discards', n4 !== g4 && discardTop(n4).value === 'skip'); +} +{ + // scoring, phase advance, match end, tie round + const gs = createInitialState({ playerCount: 2, seed: 21 }); + const set1 = [C(4), C(4), C(4)], set2 = [C(8), C(8), C(8)]; + rig(gs, 0, [...set1, ...set2, C(2)], 1); + let s = applyLaydown(gs, [{ kind: 'set', cardIds: set1.map(c => c.id) }, { kind: 'set', cardIds: set2.map(c => c.id) }]); + s.players[1].hand = [C(10), Wd(), C(3)]; + s = applyDiscard(s, 0); + ok('going out ends the round', s.roundPhase === 'roundOver' && s.roundWinner === 0); + ok('loser scores their hand', s.players[1].score === 40 && s.players[0].score === 0); + ok('laid-down player advances', s.players[0].phase === 2 && s.players[1].phase === 1); + const r2 = startNextRound(s); + ok('next round deals fresh', r2.roundNum === 2 && r2.players.every(p => p.hand.length === 10 && !p.laidDown) && countCards(r2) === 108); + ok('next round: winner+1 starts', r2.currentPlayer === 1); + ok('takes reset each round', r2.takes.length === 0); + + const end = createInitialState({ playerCount: 2, seed: 4 }); + const a = [C(6), C(6), C(6), C(6), C(6)], b = [C(2), C(2), C(2)]; + rig(end, 0, [...a, ...b, C(9)], 10); + end.players[1].phase = 10; end.players[1].clearedAt = null; end.players[1].hand = [C(1)]; + let e = applyLaydown(end, [{ kind: 'set', cardIds: a.map(c => c.id) }, { kind: 'set', cardIds: b.map(c => c.id) }]); + e = applyDiscard(e, 0); + ok('clearing phase 10 ends the match', e.roundPhase === 'gameOver' && e.matchWinner === 0); + + const tie = createInitialState({ playerCount: 2, seed: 4 }); + const ta = [C(6), C(6), C(6), C(6), C(6)], tb = [C(2), C(2), C(2)]; + rig(tie, 0, [...ta, ...tb, C(9)], 10); + tie.players[1].phase = 10; tie.players[1].clearedAt = 3; tie.players[1].score = 0; + tie.players[1].hand = []; + let t = applyLaydown(tie, [{ kind: 'set', cardIds: ta.map(c => c.id) }, { kind: 'set', cardIds: tb.map(c => c.id) }]); + t = applyDiscard(t, 0); + ok('tied finishers play another round', t.roundPhase === 'roundOver' && t.matchTied && t.matchWinner === null); +} + +// ── Staging helpers ────────────────────────────────────────────────────────── +section('Staging helpers'); +{ + ok('empty group shows its goal', groupStatus('set', 3, []).text === 'Set of 3'); + ok('partial set coaches', /needs 1 more 7/.test(groupStatus('set', 3, [C(7), C(7)]).text)); + ok('wrong set value flagged', !groupStatus('set', 3, [C(7), C(8)]).valid); + ok('partial run with a gap is fine', groupStatus('run', 4, [C(3), C(5)]).valid); + ok('spread-out run flagged', !groupStatus('run', 4, [C(3), C(9)]).valid); + ok('repeat in a run flagged', !groupStatus('run', 4, [C(3), C(3)]).valid); + ok('run that cannot fit 1..12 flagged', !groupStatus('run', 9, [C(12), C(5)]).valid || !groupStatus('run', 9, [C(12), C(5)]).ok); + ok('complete run ok', groupStatus('run', 4, [C(5), Wd(), C(3), C(6)]).ok); + ok('skip never valid', !groupStatus('set', 3, [Sk()]).valid); + ok('colour coaching names the colour', /Blue/.test(groupStatus('color', 7, [C(2, 'blue')]).text)); + ok('laid run label', laidGroupLabel({ kind: 'run', cards: [C(3), C(4)] }, [3, 4]) === 'Run 3–4'); + ok('laid set label', laidGroupLabel({ kind: 'set', cards: [C(7), Wd()] }) === 'Set of 7s · 2'); + ok('goal labels', groupGoalLabel('color', 7) === '7 of one color' && groupGoalLabel('run', 9) === 'Run of 9'); + ok('card names', cardName(C(7, 'blue')) === 'Blue 7' && cardName(Wd()) === 'Wild' && cardName(Sk()) === 'Skip'); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + ok('hand speeds as set for Nerts', HAND_SPEED[1] === 0.25 && HAND_SPEED[2] === 0.3 && HAND_SPEED[3] === 0.5 && HAND_SPEED[4] === 0.8 && HAND_SPEED[5] === 1); + let mono = true; + for (let k = 1; k < 5; k++) { + const a = aiTiming(k), b = aiTiming(k + 1); + if (!(a.reach > b.reach && a.carry > b.carry && a.think >= b.think)) mono = false; + } + ok('lower skill = slower hands', mono); + ok('pace scales timing', aiTiming(3, PACE.fast).carry < aiTiming(3, PACE.normal).carry && aiTiming(3, PACE.relaxed).carry > aiTiming(3).carry); + ok('skill 3 carry is half of skill 5', Math.abs(aiTiming(3).carry - 2 * aiTiming(5).carry) <= 1); + ok('even skill 1 turns stay reasonable', aiTiming(1).reach + aiTiming(1).carry < 2000); + + // findLaydown always returns a legal laydown + let bad = 0, found = 0; + const trials = QUICK ? 400 : 2000; + for (let i = 0; i < trials; i++) { + const gs = createInitialState({ playerCount: 2, seed: 1000 + i }); + const hand = [...gs.players[0].hand, gs.drawPile.pop(), gs.drawPile.pop(), gs.drawPile.pop()]; + const phase = 1 + (i % 10); + const lay = findLaydown(hand, phase); + if (lay) { + found++; + if (!validateLaydown(phase, lay).ok) bad++; + const ids = lay.flatMap(g => g.cards.map(c => c.id)); + if (new Set(ids).size !== ids.length) bad++; + } + } + ok('findLaydown results are legal', bad === 0, `${bad} bad of ${found}`); + ok('findLaydown finds some', found > trials * 0.05, `${found}/${trials}`); + + // adviseHand + const gs = createInitialState({ playerCount: 2, seed: 77 }); + const s1 = [C(4), C(4), C(4)], s2 = [C(9), C(9), Wd()]; + rig(gs, 0, [...s1, ...s2, C(1), C(12, 'blue'), C(7, 'green'), C(2)], 1); + const adv = adviseHand(gs, 0); + ok('advice spots a laydown', !!adv.laydown); + ok('advice keeps the phase cards', [...s1, ...s2].every(c => adv.keepers.has(c.id))); + ok('advice never tosses a phase card or wild', adv.discardId != null && ![...s1, ...s2].some(c => c.id === adv.discardId)); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +const onScreen = (b, m = 0) => b.x0 >= -m && b.x1 <= W + m && b.y0 >= -m && b.y1 <= H + m; +for (const n of [2, 3, 4]) { + const L = layoutFor(n); + const furniture = []; + for (let s = 0; s < n; s++) furniture.push({ name: `plate ${s}`, r: plateRect(L, s) }); + TOP_BUTTONS.forEach(b => furniture.push({ name: `button ${b.label}`, r: centreRect(b) })); + furniture.push({ name: 'dock', r: DOCK }); + SORT_ROW.xs.forEach((x, i) => furniture.push({ name: `sort ${i}`, r: centreRect({ x, y: SORT_ROW.y, w: SORT_ROW.w, h: SORT_ROW.h }) })); + furniture.push({ name: 'keys line', r: KEYS_BOX }); + + // furniture vs furniture + for (let i = 0; i < furniture.length; i++) { + for (let j = i + 1; j < furniture.length; j++) { + ok(`${n}p: ${furniture[i].name} clear of ${furniture[j].name}`, !rectsOverlap(furniture[i].r, furniture[j].r)); + } + } + const matBox = (s) => { + const c = matCorners(L, s, 10); + return { x0: Math.min(...c.map(p => p.x)), x1: Math.max(...c.map(p => p.x)), y0: Math.min(...c.map(p => p.y)), y1: Math.max(...c.map(p => p.y)) }; + }; + const handBox = (s, cards = 11) => { + let b = null; + for (let i = 0; i < cards; i++) { + const cb = cardBounds(handPose(L, s, i, cards, s === 0 ? 46 : 0)); + b = b ? { x0: Math.min(b.x0, cb.x0), x1: Math.max(b.x1, cb.x1), y0: Math.min(b.y0, cb.y0), y1: Math.max(b.y1, cb.y1) } : cb; + } + return b; + }; + const pileBox = (p) => cardBounds({ ...p, y: p.y - 14 }); + const deckB = pileBox(L.deck), discB = pileBox(L.discard); + ok(`${n}p: deck and discard apart`, !rectsOverlap(deckB, discB)); + for (let s = 0; s < n; s++) { + const mb = matBox(s); + ok(`${n}p seat ${s}: mat on the table`, matCorners(L, s, 10).every(p => onFelt(p))); + ok(`${n}p seat ${s}: mat clear of piles`, !rectsOverlap(mb, deckB) && !rectsOverlap(mb, discB)); + for (let t = s + 1; t < n; t++) ok(`${n}p mats ${s}/${t} apart`, !rectsOverlap(mb, matBox(t))); + for (const f of furniture) ok(`${n}p seat ${s}: mat clear of ${f.name}`, !rectsOverlap(mb, f.r)); + const hb = handBox(s); + ok(`${n}p seat ${s}: hand on screen`, onScreen(hb, s === 0 ? 40 : 6), JSON.stringify(hb)); + for (let t = 0; t < n; t++) ok(`${n}p hand ${s} clear of mat ${t}`, !rectsOverlap(hb, matBox(t)), `${JSON.stringify(hb)} vs ${JSON.stringify(matBox(t))}`); + for (const f of furniture) ok(`${n}p hand ${s} clear of ${f.name}`, !rectsOverlap(hb, f.r), `${JSON.stringify(hb)} vs ${JSON.stringify(f.r)}`); + ok(`${n}p hand ${s} clear of piles`, !rectsOverlap(hb, deckB) && !rectsOverlap(hb, discB)); + if (s > 0) { + const b = handBadge(L, s); + const br = { x0: b.x - 16, x1: b.x + 16, y0: b.y - 16, y1: b.y + 16 }; + ok(`${n}p seat ${s}: badge on screen`, onScreen(br)); + for (const f of furniture) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r)); + const hh = handHome(L, s); + ok(`${n}p seat ${s}: ghost hand home on screen`, hh.x > 0 && hh.x < W && hh.y > 0 && hh.y < H); + } + // groups: long rows stay inside their area, cards on the felt, labels on screen + for (const gc of [1, 2]) { + const areas = groupAreas(L, s, gc); + for (let gi = 0; gi < gc; gi++) { + for (const len of [2, 5, 9, 12, 16]) { + const first = cardBounds(groupCardPose(L, s, gi, gc, 0, len)); + const last = cardBounds(groupCardPose(L, s, gi, gc, len - 1, len)); + const a = areas[gi]; + ok(`${n}p seat ${s} g${gi}/${gc} len ${len}: inside area`, first.x0 >= a.x0 - 1 && last.x1 <= a.x1 + 1, `${first.x0.toFixed(0)}..${last.x1.toFixed(0)} vs ${a.x0.toFixed(0)}..${a.x1.toFixed(0)}`); + ok(`${n}p seat ${s} g${gi}/${gc} len ${len}: on felt`, onFelt({ x: first.x0, y: first.y0 }) && onFelt({ x: last.x1, y: last.y1 })); + } + const step12 = groupCardPose(L, s, gi, gc, 1, 12).x - groupCardPose(L, s, gi, gc, 0, 12).x; + ok(`${n}p seat ${s} g${gi}/${gc}: 12-card row stays readable`, step12 >= 18, step12.toFixed(1)); + ok(`${n}p seat ${s} g${gi}/${gc}: label on the mat`, a0(areas[gi].labelY)); + } + if (gc === 2) { + const r0 = areaRect(L, s, 0, 2, 0), r1 = areaRect(L, s, 1, 2, 0); + ok(`${n}p seat ${s}: two group areas apart`, !rectsOverlap(r0, r1)); + } + } + const sp = spotFor(L, s); + ok(`${n}p seat ${s}: spotlight sized`, sp.w > 100 && sp.h > 100); + } + // human hand hit-tests round trip; insertion index is monotone + for (const cards of [1, 5, 10, 11]) { + let rt = true; + for (let i = 0; i < cards; i++) { + const p = handPose(L, 0, i, cards); + // aim at the visible left strip (later cards overlap the right side) + const pt = { x: p.x - CARD_W * 0.3, y: p.y - CARD_H * 0.3 }; + if (handHit(L, cards, pt) !== i) rt = false; + } + ok(`${n}p: hand hit-test round trip (${cards})`, rt); + let monotone = true, prev = -1; + for (let x = 300; x <= 1620; x += 15) { + const k = handInsertIndex(L, cards, x); + if (k < prev) monotone = false; + prev = k; + } + ok(`${n}p: insert index monotone (${cards})`, monotone && handInsertIndex(L, cards, 0) === 0 && handInsertIndex(L, cards, W) === cards); + const z = handZone(L, cards); + ok(`${n}p: hand zone covers the fan (${cards})`, inRect(handPose(L, 0, 0, cards), z) && inRect(handPose(L, 0, cards - 1, cards), z)); + } + ok(`${n}p: deck pose hit`, inPose(L.deck, deckTopPose(L, 80)) && inPose(L.discard, discardPose(L, 3, 4))); + // group rects cover their cards (hit targets) + for (let s = 0; s < n; s++) { + const r = groupRect(L, s, 1, 2, 7, 1, 10); + const p0 = groupCardPose(L, s, 1, 2, 0, 7), p6 = groupCardPose(L, s, 1, 2, 6, 7); + ok(`${n}p seat ${s}: group rect covers its cards`, inRect(p0, r) && inRect(p6, r)); + } +} +function a0(y) { return y > 0 && y < H; } +void SQ; void PLATE; + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +function playMatch(n, skills, seed, { maxRounds = 80 } = {}) { + let gs = createInitialState({ playerCount: n, seed }); + let rounds = 0, turns = 0, noop = 0, conserve = true, stuck = false, loops = 0; + let rng = seed * 9301 + 49297; + const rand = () => { rng = (rng * 9301 + 49297) % 233280; return rng / 233280; }; + while (gs.roundPhase !== 'gameOver' && rounds < maxRounds) { + let steps = 0; + while (gs.roundPhase === 'play' && steps < 3000) { + const a = chooseAction(gs, { skill: skills[gs.currentPlayer], rng: rand }); + const next = apply(gs, a); + if (next === gs) { + noop++; + // the scene's safety net: discard the first card + const fb = applyDiscard(gs, 0, skipTargets(gs, gs.currentPlayer)[0] ?? null); + if (fb === gs) { stuck = true; break; } + gs = fb; + } else gs = next; + if (a.type === 'discard') turns++; + if (gs.takes?.length && gs.takes.filter(t => t.id === gs.takes[gs.takes.length - 1].id).length > 3) loops++; + if (countCards(gs) !== 108) conserve = false; + steps++; + } + if (stuck || gs.roundPhase === 'play') { stuck = true; break; } + rounds++; + if (gs.roundPhase === 'roundOver') gs = startNextRound(gs); + } + return { gs, rounds, turns, noop, conserve, stuck, loops, over: gs.roundPhase === 'gameOver' }; +} +{ + const N = QUICK ? 12 : 60; + for (const n of [2, 3, 4]) { + let ended = 0, noops = 0, conserved = true, stuck = 0, rounds = 0, scoreOk = true, loops = 0; + for (let i = 0; i < N; i++) { + const skills = Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5)); + const r = playMatch(n, skills, 500 + i * 13 + n); + if (r.over) ended++; + noops += r.noop; + if (!r.conserve) conserved = false; + if (r.stuck) stuck++; + loops += r.loops; + rounds += r.rounds; + if (r.over) { + const w = r.gs.players[r.gs.matchWinner]; + const fin = r.gs.players.filter(p => p.clearedAt != null); + if (!w || w.clearedAt == null || fin.some(p => p.score < w.score)) scoreOk = false; + } + } + ok(`${n}p soak: every match ends`, ended === N, `${ended}/${N}`); + ok(`${n}p soak: AI never plays an illegal action`, noops === 0, `${noops} no-ops`); + ok(`${n}p soak: 108 cards conserved`, conserved); + ok(`${n}p soak: no stuck rounds`, stuck === 0); + ok(`${n}p soak: no card passed around in a loop`, loops === 0, `${loops}`); + ok(`${n}p soak: winner is the lowest finisher`, scoreOk); + console.log(` ${n}p: ${N} matches, avg ${(rounds / N).toFixed(1)} rounds`); + } + // skill matters + const duel = (a, b, M) => { + let wa = 0; + for (let i = 0; i < M; i++) { + const seatA = i % 2; + const skills = seatA === 0 ? [a, b] : [b, a]; + const r = playMatch(2, skills, 9000 + i * 7); + if (r.over && r.gs.matchWinner === seatA) wa++; + } + return wa / M; + }; + const M = QUICK ? 40 : 160; + const r51 = duel(5, 1, M), r31 = duel(3, 1, M), r53 = duel(5, 3, M); + console.log(` win rates: skill 5 vs 1 ${(r51 * 100).toFixed(0)}%, 3 vs 1 ${(r31 * 100).toFixed(0)}%, 5 vs 3 ${(r53 * 100).toFixed(0)}%`); + // measured over 300 matches: 5v1 ≈ 84%, 3v1 ≈ 81%, 5v3 ≈ 60% (quick mode is noisier) + ok('skill 5 clearly beats skill 1', r51 >= (QUICK ? 0.65 : 0.72), `${(r51 * 100).toFixed(0)}%`); + ok('skill 3 beats skill 1', r31 >= (QUICK ? 0.6 : 0.68), `${(r31 * 100).toFixed(0)}%`); + ok('skill 5 beats skill 3', r53 >= (QUICK ? 0.42 : 0.52), `${(r53 * 100).toFixed(0)}%`); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);