diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index d5174c6..c93e5b2 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -36,7 +36,7 @@ registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: tru registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 }); registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 }); registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 8 }); -registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 9 }); +registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 9 }); registerGame({ slug: 'craps', name: 'Craps', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 10 }); registerGame({ slug: 'roulette', name: 'Roulette', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 11 }); registerGame({ slug: 'mexicantrain', name: 'Mexican Train', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 12 }); diff --git a/src/games/skipbo/SkipBoAI.js b/src/games/skipbo/SkipBoAI.js index f57a111..089d869 100644 --- a/src/games/skipbo/SkipBoAI.js +++ b/src/games/skipbo/SkipBoAI.js @@ -1,191 +1,262 @@ -// Skip-Bo AI — single-action heuristic chooser. +// Skip-Bo AI — single-action chooser, scaled by skill (1..5). // -// The caller invokes chooseAction(state) repeatedly. Each call returns ONE -// action: either a play or a discard. The scene applies the action with -// animation, then re-invokes until a discard is returned (which ends the -// turn) or the game ends. +// The caller invokes chooseAction(state, { skill, rng }) repeatedly. Each call +// returns ONE action: a play or the turn-ending discard. +// { type: 'play', source, sourceIdx, buildIdx, asNumber? } +// { type: 'discard', handIdx, discardIdx } +// +// Skill: +// 1-2 plays its stock when it sees it, otherwise picks plays loosely, +// sometimes stops early, discards without much thought. +// 3 the classic greedy heuristics (stock first, save wilds, stack +// discards downward). +// 4-5 searches for a CHAIN of hand / discard plays that frees the stock +// card this turn (5 looks deeper), and won't build a pile up to the +// value the next player's stock needs. import { BUILD_PILE_COUNT, DISCARD_PILE_COUNT, - buildPileTopValue, - canPlayOnBuild, discardTop, getValidPlays, nextRequired, stockTop, } from './SkipBoLogic.js'; +import { clampSkill } from '../../ui/cardtable/AITiming.js'; const PLAY_PRIORITY = { stock: 3, discard: 2, hand: 1 }; +const NOISE = { 1: 120, 2: 60, 3: 6, 4: 1, 5: 0 }; +const STOP_EARLY = { 1: 0.2, 2: 0.08, 3: 0, 4: 0, 5: 0 }; +const MISS_STOCK = { 1: 0.1, 2: 0.03, 3: 0, 4: 0, 5: 0 }; +const CHAIN_DEPTH = { 4: 4, 5: 7 }; -/** - * Return one action for the AI player at `state.currentPlayer`, or null if - * `state.phase !== 'play'`. - * - * Actions: - * { type: 'play', source, sourceIdx, buildIdx, asNumber? } - * { type: 'discard', handIdx, discardIdx } - */ -export function chooseAction(state) { +export function chooseAction(state, opts = {}) { if (state.phase !== 'play') return null; + const skill = clampSkill(opts.skill); + const rand = opts.rng ?? Math.random; const seat = state.currentPlayer; const player = state.players[seat]; - const plays = getValidPlays(state); - // 1) Stock-emptying play (winning move) trumps everything. - if (player.stock.length === 1) { - for (const p of plays) { - if (p.source === 'stock') return playAction(state, p); - } + // 1) The stock card always comes first (it's how you win). + const stockPlays = plays.filter((p) => p.source === 'stock'); + if (stockPlays.length && !(rand() < MISS_STOCK[skill])) { + return playAction(state, bestStockPlay(state, stockPlays, skill)); } - // 2) Filter / score plays. - if (plays.length > 0) { + // 2) Sharp players look for a chain of plays that frees the stock card. + if (skill >= 4 && plays.length) { + const chain = planChain(state, seat, CHAIN_DEPTH[skill]); + if (chain) return playAction(state, chain); + } + + // 3) Otherwise score the single plays. With an empty hand (and nothing left + // to draw) there's nothing to discard, so keep playing whatever fits. + const mustPlay = player.hand.length === 0; + if (plays.length > 0 && (mustPlay || !(rand() < STOP_EARLY[skill]))) { const stockReq = stockTop(state, seat)?.value; let best = null; let bestScore = -Infinity; for (const p of plays) { - const sc = scorePlay(state, p, stockReq); + let sc = scorePlay(state, p, stockReq, skill) + rand() * NOISE[skill]; + if (p.card.value === 'wild' && skill >= 2 && !shouldUseWild(state, p, plays)) sc -= 1000; if (sc > bestScore) { bestScore = sc; best = p; } } - // Only commit to a play if it doesn't "waste" a wild unnecessarily. - if (best && (best.card.value !== 'wild' || shouldUseWild(state, best, plays))) { - return playAction(state, best); - } + // sharp players would rather discard than set up the next player + const floor = mustPlay ? -Infinity : skill >= 4 ? 0 : -500; + if (best && bestScore > floor) return playAction(state, best); } - // 3) No useful play — must discard. - return chooseDiscard(state); + // 4) Nothing worth playing — discard to end the turn. + if (player.hand.length === 0) return null; + return chooseDiscard(state, skill, rand); } function playAction(state, play) { - const action = { - type: 'play', - source: play.source, - sourceIdx: play.sourceIdx, - buildIdx: play.buildIdx, - }; - if (play.card.value === 'wild') { - action.asNumber = nextRequired(state, play.buildIdx); - } + const action = { type: 'play', source: play.source, sourceIdx: play.sourceIdx, buildIdx: play.buildIdx }; + if (play.card.value === 'wild') action.asNumber = nextRequired(state, play.buildIdx); return action; } -function scorePlay(state, play, stockTopValue) { - let s = PLAY_PRIORITY[play.source] * 100; - - // Bias toward plays that unlock the stock top right now or soon - if (stockTopValue !== undefined && stockTopValue !== 'wild') { - const after = nextRequired(state, play.buildIdx) + 1; - if (play.card.value === stockTopValue) s += 50; // playing the same value we need on stock - if (after === stockTopValue) s += 80; // this play sets up stock to play next +// With several piles open for the stock card, keep away from setting up the +// next player (skill 4+), else prefer the fullest pile. +function bestStockPlay(state, stockPlays, skill) { + if (stockPlays.length === 1 || skill < 4) return stockPlays[0]; + const threat = opponentNeeds(state, state.currentPlayer, skill); + let best = stockPlays[0], bestScore = -Infinity; + for (const p of stockPlays) { + const after = nextRequired(state, p.buildIdx) + 1; + let s = state.buildPiles[p.buildIdx].length; + if (threat.has(after)) s -= 50; + if (s > bestScore) { bestScore = s; best = p; } } + return best; +} - // Prefer plays that complete a pile (top would be 12 after play) +/** Stock-top values the opponents need (next player only below skill 5). */ +function opponentNeeds(state, seat, skill) { + const out = new Set(); + const n = state.players.length; + const seats = skill >= 5 ? Array.from({ length: n - 1 }, (_, i) => (seat + 1 + i) % n) : [(seat + 1) % n]; + for (const s of seats) { + const t = stockTop(state, s); + if (t && t.value !== 'wild') out.add(t.value); + } + return out; +} + +function scorePlay(state, play, stockTopValue, skill) { + let s = PLAY_PRIORITY[play.source] * 100; const need = nextRequired(state, play.buildIdx); + if (skill >= 3 && stockTopValue !== undefined && stockTopValue !== 'wild') { + const after = need + 1; + if (play.card.value === stockTopValue) s += 50; + if (after === stockTopValue) s += 80; + } if (play.card.value === 12 || (play.card.value === 'wild' && need === 12)) s += 40; - - // Light penalty for wilds (we want to save them) if (play.card.value === 'wild') s -= 60; - - // Tiny tie-breaker — prefer lower build piles to keep them moving s += (4 - state.buildPiles[play.buildIdx].length) * 0.1; - + if (skill >= 4) { + // don't hand the next player their stock card + const after = need >= 12 ? 1 : need + 1; + if (opponentNeeds(state, state.currentPlayer, skill).has(after)) s -= 120; + // emptying the hand draws five fresh cards + if (play.source === 'hand' && state.players[state.currentPlayer].hand.length === 1) s += 30; + } return s; } -/** - * Decide if a wild play is worthwhile. We accept a wild play when: - * - it empties our stock (handled above), - * - it's playing from stock (always good — frees the stock), - * - it completes a build pile (need === 12), - * - it unblocks the stock top (next-required after play === stock top value), - * - or we have nothing else useful AND we're holding extra wilds (>1). - */ function shouldUseWild(state, play, allPlays) { if (play.source === 'stock') return true; - const need = nextRequired(state, play.buildIdx); if (need === 12) return true; - - const seat = state.currentPlayer; - const stockTopCard = stockTop(state, seat); - if (stockTopCard && stockTopCard.value !== 'wild') { - // After this play, would the stock top become playable on this pile? - if (need + 1 === stockTopCard.value) return true; - } - - // Count non-wild useful plays remaining - const hasNonWildPlay = allPlays.some((p) => p.card.value !== 'wild'); - if (hasNonWildPlay) return false; - - // Otherwise only use a wild if we have multiple - const wildsInHand = state.players[seat].hand.filter((c) => c.value === 'wild').length; - return wildsInHand >= 2; + const st = stockTop(state, state.currentPlayer); + if (st && st.value !== 'wild' && need + 1 === st.value) return true; + if (allPlays.some((p) => p.card.value !== 'wild')) return false; + return state.players[state.currentPlayer].hand.filter((c) => c.value === 'wild').length >= 2; } -function chooseDiscard(state) { +// ── Chain search ──────────────────────────────────────────────────────────── +// A light simulation: build piles as their next-required value, hand values, +// discard piles as value stacks. Depth-first search for the cheapest sequence +// of plays after which the stock card fits a pile. Cost: plays + 3 per wild. +// We can't see past an emptied hand (five unknown cards), so the search +// treats that as a dead end. +export function planChain(state, seat, depth = 6) { + const p = state.players[seat]; + const st = stockTop(state, seat); + if (!st || st.value === 'wild') return null; + const target = st.value; + const builds = state.buildPiles.map((_, b) => nextRequired(state, b)); + const hand = p.hand.map((c) => c.value); + const discards = p.discards.map((d) => d.map((c) => c.value)); + let best = null; + const seen = new Map(); + + const fits = (bs) => bs.some((need) => need === target); + const key = (bs, h, ds) => `${bs.join(',')}|${h.slice().sort().join(',')}|${ds.map((d) => d.length).join(',')}`; + + function dfs(bs, h, ds, cost, path) { + if (best && cost >= best.cost) return; + if (path.length && fits(bs)) { best = { cost, first: path[0] }; return; } + if (path.length >= depth) return; + const k = key(bs, h, ds); + if (seen.has(k) && seen.get(k) <= cost) return; + seen.set(k, cost); + // hand cards + for (let i = 0; i < h.length; i++) { + const v = h[i]; + if (h.length === 1) continue; // emptying the hand is a blind refill — stop there + for (let b = 0; b < BUILD_PILE_COUNT; b++) { + const need = bs[b]; + if (need > 12 || (v !== 'wild' && v !== need)) continue; + const nb = bs.slice(); nb[b] = need === 12 ? 1 : need + 1; + const nh = h.slice(); nh.splice(i, 1); + dfs(nb, nh, ds, cost + 1 + (v === 'wild' ? 3 : 0), [...path, { source: 'hand', sourceIdx: handIndex(p.hand, h, i, path), buildIdx: b, v }]); + } + } + // discard tops + for (let d = 0; d < DISCARD_PILE_COUNT; d++) { + const pile = ds[d]; + if (!pile.length) continue; + const v = pile[pile.length - 1]; + for (let b = 0; b < BUILD_PILE_COUNT; b++) { + const need = bs[b]; + if (need > 12 || (v !== 'wild' && v !== need)) continue; + const nb = bs.slice(); nb[b] = need === 12 ? 1 : need + 1; + const nd = ds.map((x, j) => (j === d ? x.slice(0, -1) : x)); + dfs(nb, h, nd, cost + 1 + (v === 'wild' ? 3 : 0), [...path, { source: 'discard', sourceIdx: d, buildIdx: b, v }]); + } + } + } + dfs(builds, hand, discards, 0, []); + if (!best) return null; + // only the first move is played; the caller re-plans after it lands + const f = best.first; + const card = f.source === 'hand' ? p.hand[f.sourceIdx] : discardTop(state, seat, f.sourceIdx); + return { source: f.source, sourceIdx: f.sourceIdx, buildIdx: f.buildIdx, card }; +} + +// Only the first step of a path is ever executed, so its hand index is the +// index in the real hand (no earlier removals to account for). +function handIndex(realHand, simHand, i, path) { + if (path.length === 0) return i; + return -1; +} + +// ── Discard step ──────────────────────────────────────────────────────────── +function chooseDiscard(state, skill = 3, rand = Math.random) { const seat = state.currentPlayer; const player = state.players[seat]; const hand = player.hand; - if (hand.length === 0) { - // Shouldn't happen — refill to 5 happens automatically. Fail-safe: - return null; + if (hand.length === 0) return null; + + if (skill <= 1 && rand() < 0.5) { + const idx = hand.findIndex((c) => c.value !== 'wild'); + return { type: 'discard', handIdx: idx >= 0 ? idx : 0, discardIdx: Math.floor(rand() * DISCARD_PILE_COUNT) }; } - // Build piles' next-required values; useful for ranking what to keep. const nexts = []; for (let b = 0; b < BUILD_PILE_COUNT; b++) nexts.push(nextRequired(state, b)); + const threat = skill >= 4 ? opponentNeeds(state, seat, skill) : new Set(); - // 1) Choose which CARD to discard. - // Prefer: highest non-wild value (less likely playable soon), then ties - // broken by least usefulness vs current build piles. let bestHandIdx = -1; let bestCardScore = -Infinity; for (let i = 0; i < hand.length; i++) { const c = hand[i]; - if (c.value === 'wild') continue; // never discard wilds first + if (c.value === 'wild') continue; const dist = minPlayDistance(c.value, nexts); - const score = c.value * 2 + dist * 3; // higher = better to discard + let score = c.value * 2 + dist * 3; + // keep cards that lead toward our own stock card + const st = stockTop(state, seat); + if (skill >= 4 && st && st.value !== 'wild' && c.value < st.value && st.value - c.value <= 3) score -= 12; + void threat; + score += rand() * (NOISE[skill] / 10); if (score > bestCardScore) { bestCardScore = score; bestHandIdx = i; } } - if (bestHandIdx === -1) { - // All wilds in hand — pick the first (forced discard) - bestHandIdx = 0; - } - + if (bestHandIdx === -1) bestHandIdx = 0; const cardToDiscard = hand[bestHandIdx]; - // 2) Choose which DISCARD PILE. - // Prefer building a descending run from the top down (so we can replay - // later when build piles allow): place on pile whose top is exactly - // cardValue + 1, falling back to cardValue, then the emptiest pile, then - // pile with smallest difference. Never bury a wild. let bestPileIdx = -1; let bestPileScore = -Infinity; for (let d = 0; d < DISCARD_PILE_COUNT; d++) { const top = discardTop(state, seat, d); let s = 0; - if (!top) { - s = 50; // empty pile is great - } else if (top.value === 'wild' || top.playedAs === 'wild') { - s = -200; // don't bury wilds - } else if (cardToDiscard.value === 'wild') { - s = -50; // wild on any pile is mediocre - if (player.discards[d].length === 0) s = 30; - } else { - const topVal = top.playedAs ?? top.value; - if (topVal === cardToDiscard.value + 1) s = 40; // stack descending (replayable) - else if (topVal === cardToDiscard.value) s = 25; // duplicate stack - else s = -Math.abs(topVal - cardToDiscard.value); // closer is better + if (!top) s = 50; + else if (top.value === 'wild') s = -200; + else if (cardToDiscard.value === 'wild') s = player.discards[d].length === 0 ? 30 : -50; + else { + const topVal = top.value; + if (topVal === cardToDiscard.value + 1) s = 40; + else if (topVal === cardToDiscard.value) s = 25; + else s = -Math.abs(topVal - cardToDiscard.value); + // sharp players keep one pile for high cards rather than burying low ones + if (skill >= 4 && cardToDiscard.value >= 10 && topVal >= 10) s += 10; } - // Prefer shorter piles slightly s += (8 - player.discards[d].length) * 0.5; if (s > bestPileScore) { bestPileScore = s; bestPileIdx = d; } } if (bestPileIdx === -1) bestPileIdx = 0; - return { type: 'discard', handIdx: bestHandIdx, discardIdx: bestPileIdx }; } @@ -193,13 +264,18 @@ function minPlayDistance(value, nexts) { let best = 12; for (const n of nexts) { if (n > 12) continue; - if (value >= n) { - const d = value - n; - if (d < best) best = d; - } else { - const d = (12 - n) + value; // would have to wrap - if (d < best) best = d; - } + const d = value >= n ? value - n : (12 - n) + value; + if (d < best) best = d; } return best; } + +/** The discard a sharp player would make now (even if plays remain). */ +export function suggestDiscard(state) { + return chooseDiscard(state, 5, () => 0.5); +} + +/** What a sharp player would do now — the human's hint. */ +export function suggestAction(state) { + return chooseAction(state, { skill: 5, rng: () => 0.5 }); +} diff --git a/src/games/skipbo/SkipBoArt.js b/src/games/skipbo/SkipBoArt.js new file mode 100644 index 0000000..e61548d --- /dev/null +++ b/src/games/skipbo/SkipBoArt.js @@ -0,0 +1,350 @@ +// Skip-Bo art — baked once into canvas textures (no image files). Original +// vintage card design: ivory stock, a double border and a rosette medallion in +// the card's range colour (1-4 cornflower, 5-8 sea green, 9-12 rose), corner +// indices; the wild is a gold star rosette. +// +// sb-cards atlas at 2× — frames '1'..'12', 'wild' +// sb-back burgundy damask back with a gold medallion +// sb-table- Grandma's dining room: damask wallpaper, mahogany table, +// burgundy tablecloth, lace runner + doilies, pile spots + +import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js'; +import { + bakeRoom, canvas, rr, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, pileSpot, CARD_TEX, +} from '../../ui/cardtable/TableArt.js'; +import { W, H } from '../../ui/cardtable/TableGeometry.js'; +import { T, layoutFor, placematCorners, SEAT_HEX } from './SkipBoTable.js'; + +const CW = CARD_TEX.W, CH = CARD_TEX.H; +const SERIF = 'Georgia, "Times New Roman", serif'; +const IVORY = '#fbf6e8'; + +export function rangeColor(v) { + if (v === 'wild') return '#b8902c'; + if (v <= 4) return '#2f6db5'; + if (v <= 8) return '#2e8b57'; + return '#b8324a'; +} +const DARK = (v) => mix(rangeColor(v), '#000000', 0.35); + +function cardBase(ctx, x, y) { + rr(ctx, x + 2, y + 2, CW - 4, CH - 4, 16); + ctx.fillStyle = IVORY; + ctx.fill(); + ctx.save(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 96, 12); + ctx.fillRect(x, y, CW, CH); + const g = ctx.createRadialGradient(x + CW / 2, y + CH / 2, 20, x + CW / 2, y + CH / 2, CH * 0.7); + g.addColorStop(0, 'rgba(255,255,255,0)'); + g.addColorStop(1, 'rgba(160,120,60,0.18)'); + ctx.fillStyle = g; + 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.5)'; + ctx.stroke(); +} + +function borders(ctx, x, y, color) { + rr(ctx, x + 12, y + 12, CW - 24, CH - 24, 11); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + rr(ctx, x + 19, y + 19, CW - 38, CH - 38, 8); + ctx.lineWidth = 1.5; + ctx.stroke(); +} + +function rosette(ctx, cx, cy, r, color, petals = 12) { + ctx.save(); + ctx.translate(cx, cy); + ctx.fillStyle = mix(color, '#ffffff', 0.82); + for (let i = 0; i < petals; i++) { + ctx.save(); + ctx.rotate((i / petals) * Math.PI * 2); + ctx.beginPath(); + ctx.ellipse(0, -r * 0.78, r * 0.2, r * 0.32, 0, 0, Math.PI * 2); + ctx.fill(); + ctx.restore(); + } + ctx.beginPath(); + ctx.arc(0, 0, r * 0.7, 0, Math.PI * 2); + ctx.fillStyle = IVORY; + ctx.fill(); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + ctx.beginPath(); + ctx.arc(0, 0, r * 0.6, 0, Math.PI * 2); + ctx.lineWidth = 1.5; + ctx.stroke(); + ctx.restore(); +} + +function corners(ctx, x, y, text, color, underline) { + const draw = () => { + ctx.font = `bold ${text.length > 1 ? 40 : 44}px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = color; + ctx.fillText(text, 0, 0); + if (underline) ctx.fillRect(-12, 22, 24, 3.5); + }; + ctx.save(); ctx.translate(x + 44, y + 50); draw(); ctx.restore(); + ctx.save(); ctx.translate(x + CW - 44, y + CH - 50); ctx.rotate(Math.PI); draw(); ctx.restore(); +} + +function drawNumber(ctx, x, y, v) { + const c = rangeColor(v); + cardBase(ctx, x, y); + borders(ctx, x, y, c); + rosette(ctx, x + CW / 2, y + CH / 2, 64, c); + const t = String(v); + ctx.font = `bold ${t.length > 1 ? 78 : 92}px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = DARK(v); + ctx.fillText(t, x + CW / 2 + 2, y + CH / 2 + 6); + ctx.fillStyle = c; + ctx.fillText(t, x + CW / 2, y + CH / 2 + 4); + if (v === 6 || v === 9) { ctx.fillStyle = c; ctx.fillRect(x + CW / 2 - 18, y + CH / 2 + 42, 36, 5); } + corners(ctx, x, y, t, c, v === 6 || v === 9); +} + +function star(ctx, cx, cy, r, points = 8) { + ctx.beginPath(); + for (let i = 0; i < points * 2; i++) { + const a = (i / (points * 2)) * Math.PI * 2 - Math.PI / 2; + const rr2 = i % 2 ? r * 0.45 : r; + const px = cx + Math.cos(a) * rr2, py = cy + Math.sin(a) * rr2; + if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); + } + ctx.closePath(); +} + +function drawWild(ctx, x, y) { + cardBase(ctx, x, y); + ctx.save(); + rr(ctx, x + 12, y + 12, CW - 24, CH - 24, 11); + ctx.clip(); + const g = ctx.createLinearGradient(x, y, x + CW, y + CH); + g.addColorStop(0, '#f8e7b0'); g.addColorStop(0.5, '#e8c56a'); g.addColorStop(1, '#b8902c'); + ctx.fillStyle = g; + ctx.fillRect(x, y, CW, CH); + // a faint sunburst + ctx.globalAlpha = 0.18; + for (let i = 0; i < 24; i++) { + ctx.save(); + ctx.translate(x + CW / 2, y + CH / 2); + ctx.rotate((i / 24) * Math.PI * 2); + ctx.fillStyle = '#fffaf0'; + ctx.fillRect(-3, 0, 6, CH); + ctx.restore(); + } + ctx.globalAlpha = 1; + ctx.restore(); + borders(ctx, x, y, '#7a5a12'); + star(ctx, x + CW / 2, y + CH / 2 - 10, 58); + ctx.fillStyle = IVORY; + ctx.fill(); + ctx.lineWidth = 4; + ctx.strokeStyle = '#7a5a12'; + ctx.stroke(); + star(ctx, x + CW / 2, y + CH / 2 - 10, 30, 4); + ctx.fillStyle = '#b8324a'; + ctx.fill(); + ctx.font = `bold 34px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#5a3a0a'; + ctx.fillText('WILD', x + CW / 2, y + CH / 2 + 76); + corners(ctx, x, y, '★', '#7a5a12', false); +} + +export function frameKey(card) { + return card.value === 'wild' ? 'wild' : String(card.value); +} + +function bakeCards(scene) { + const frames = []; + for (let v = 1; v <= 12; v++) frames.push([String(v), (ctx, x, y) => drawNumber(ctx, x, y, v)]); + frames.push(['wild', drawWild]); + const cols = 7, rows = Math.ceil(frames.length / cols); + const cv = canvas(cols * CW, rows * CH); + const ctx = cv.getContext('2d'); + frames.forEach(([, draw], i) => draw(ctx, (i % cols) * CW, Math.floor(i / cols) * CH)); + const tex = scene.textures.addCanvas('sb-cards', cv); + frames.forEach(([k], i) => tex.add(k, 0, (i % cols) * CW, Math.floor(i / cols) * CH, CW, CH)); +} + +function damask(ctx, x0, y0, w, h, base, ink, size = 90, alpha = 0.35) { + ctx.fillStyle = base; + ctx.fillRect(x0, y0, w, h); + ctx.save(); + ctx.beginPath(); ctx.rect(x0, y0, w, h); ctx.clip(); + ctx.globalAlpha = alpha; + ctx.fillStyle = ink; + for (let row = 0, y = y0; y < y0 + h + size; row++, y += size * 0.8) { + for (let x = x0 + (row % 2 ? size / 2 : 0); x < x0 + w + size; x += size) { + ctx.save(); + ctx.translate(x, y); + for (let k = 0; k < 4; k++) { + ctx.rotate(Math.PI / 2); + ctx.beginPath(); + ctx.ellipse(0, -size * 0.22, size * 0.09, size * 0.2, 0, 0, Math.PI * 2); + ctx.fill(); + } + ctx.beginPath(); ctx.arc(0, 0, size * 0.07, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + } + } + ctx.restore(); +} + +function bakeBack(scene) { + const c = canvas(CW, CH); + const ctx = c.getContext('2d'); + rr(ctx, 2, 2, CW - 4, CH - 4, 16); + ctx.save(); + ctx.clip(); + damask(ctx, 0, 0, CW, CH, '#5e1424', '#d9a84a', 46, 0.3); + ctx.restore(); + rr(ctx, 10, 10, CW - 20, CH - 20, 11); + ctx.lineWidth = 4; + ctx.strokeStyle = '#d9a84a'; + ctx.stroke(); + ctx.beginPath(); ctx.ellipse(CW / 2, CH / 2, 42, 54, 0, 0, Math.PI * 2); + ctx.fillStyle = '#3e0c18'; ctx.fill(); + ctx.lineWidth = 4; ctx.strokeStyle = '#d9a84a'; ctx.stroke(); + star(ctx, CW / 2, CH / 2, 26); + ctx.fillStyle = '#d9a84a'; ctx.fill(); + 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('sb-back', c); +} + +// ── Grandma's dining room ─────────────────────────────────────────────────── +function wall(ctx) { + damask(ctx, 0, 0, W, H, '#6f7f62', '#e9e0c6', 120, 0.22); + ctx.fillStyle = noisePattern(ctx, 128, 14); + ctx.fillRect(0, 0, W, H); + // crown moulding + const g = ctx.createLinearGradient(0, 0, 0, 30); + g.addColorStop(0, '#f4ecd8'); g.addColorStop(1, '#bfae88'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, 26); + ctx.fillStyle = 'rgba(0,0,0,0.3)'; + ctx.fillRect(0, 26, W, 3); + const lamp = ctx.createRadialGradient(W / 2, 60, 30, W / 2, 260, 1150); + lamp.addColorStop(0, 'rgba(255,220,160,0.32)'); + lamp.addColorStop(0.45, 'rgba(120,80,40,0.08)'); + lamp.addColorStop(1, 'rgba(15,8,4,0.66)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); +} + +const WOOD = { base: '#5a2416', dark: '#2a0e08', light: '#a0512f', grain: ['#1a0804', '#c46e42'] }; + +function front(ctx, Tb) { + frontBands(ctx, Tb, ['#7a3420', '#5e2616', '#4a1c10', '#3a140b', '#2c0e07'], { grooves: [0.35, 0.7] }); +} + +function rim(ctx, Tb) { + rimBand(ctx, Tb, { base: WOOD.base, dark: WOOD.dark, light: WOOD.light, grain: WOOD.grain, gloss: 1.4 }); +} + +function lacePattern(ctx, pts, { base = '#efe5cf', hole = 'rgba(90,30,30,0.32)', step = 18 } = {}) { + ctx.save(); + poly(ctx, pts); + ctx.clip(); + const xs = pts.map(p => p.x), ys = pts.map(p => p.y); + const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys); + ctx.fillStyle = base; + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + for (let y = y0, r = 0; y < y1 + step; y += step * 0.8, r++) { + for (let x = x0 + (r % 2 ? step / 2 : 0); x < x1 + step; x += step) { + ctx.beginPath(); ctx.arc(x, y, step * 0.18, 0, Math.PI * 2); ctx.fillStyle = hole; ctx.fill(); + ctx.beginPath(); ctx.arc(x, y, step * 0.38, 0, Math.PI * 2); + ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(140,100,60,0.22)'; ctx.stroke(); + } + } + ctx.fillStyle = noisePattern(ctx, 96, 14); + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + ctx.restore(); +} + +// scallops along the edge from a to b (bumps bulge to the side `out`) +function scallopEdge(ctx, a, b, color, r = 8) { + const len = Math.hypot(b.x - a.x, b.y - a.y); + const n = Math.max(1, Math.round(len / (r * 2))); + for (let i = 0; i < n; i++) { + const t = (i + 0.5) / n; + ctx.beginPath(); + ctx.arc(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, r, 0, Math.PI * 2); + ctx.fillStyle = color; + ctx.fill(); + } +} + +function top(ctx, Tb) { + // burgundy cloth with a tone-on-tone damask + damask(ctx, 0, 0, W, H, '#6a1626', '#8e2a3c', 150, 0.45); + ctx.fillStyle = noisePattern(ctx, 160, 22); + ctx.fillRect(0, 0, W, H); + // lace runner under the middle row + const P = Tb.P; + const run = [P.project(-0.62, 0.325), P.project(0.62, 0.325), P.project(0.62, 0.48), P.project(-0.62, 0.48)]; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.4)'; ctx.shadowBlur = 10; ctx.shadowOffsetY = 4; + poly(ctx, run); ctx.fillStyle = '#efe5cf'; ctx.fill(); + ctx.restore(); + for (const [a, b] of [[run[0], run[1]], [run[3], run[2]]]) scallopEdge(ctx, a, b, '#efe5cf', 7); + lacePattern(ctx, run, {}); + lampPool(ctx, Tb, { color: '255,220,165', alpha: 0.26, vignette: 0.52, at: { u: 0, v: 0.45 } }); + rimShadow(ctx, Tb, 0.4); +} + +function mats(ctx, playerCount) { + const L = layoutFor(playerCount); + for (const st of L.seats) { + const pts = placematCorners(L, st.seat); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 4; + poly(ctx, pts); ctx.fillStyle = '#efe5cf'; ctx.fill(); + ctx.restore(); + for (let i = 0; i < 4; i++) scallopEdge(ctx, pts[i], pts[(i + 1) % 4], '#efe5cf', 6 * Math.max(0.6, st.k)); + lacePattern(ctx, pts, { base: '#f1e8d4', step: 16 * Math.max(0.6, st.k) }); + poly(ctx, pts); + ctx.lineWidth = 3; + ctx.strokeStyle = SEAT_HEX[st.seat]; + ctx.globalAlpha = 0.75; + ctx.stroke(); + ctx.globalAlpha = 1; + } +} + +function spots(ctx, playerCount) { + const L = layoutFor(playerCount); + const col = '110,40,40'; + pileSpot(ctx, L.draw, 'DRAW', { color: col, alpha: 0.55 }); + L.builds.forEach((b) => pileSpot(ctx, b, '', { color: col, alpha: 0.5 })); + pileSpot(ctx, L.completed, 'DONE', { color: col, alpha: 0.4 }); +} + +export async function prepareSkipBoArt(scene, playerCount) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('sb-cards')) bakeCards(scene); + if (!scene.textures.exists('sb-back')) bakeBack(scene); + const key = `sb-table-${playerCount}`; + bakeRoom(scene, key, T, { + wall, front, rim, top, + onTop: (ctx) => { mats(ctx, playerCount); spots(ctx, playerCount); }, + }); + return key; +} + +export { IVORY }; diff --git a/src/games/skipbo/SkipBoGame.js b/src/games/skipbo/SkipBoGame.js index e3dbf67..84ee67d 100644 --- a/src/games/skipbo/SkipBoGame.js +++ b/src/games/skipbo/SkipBoGame.js @@ -1,1108 +1,968 @@ -import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { auth } from '../../services/auth.js'; -import { api } from '../../services/api.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { - BUILD_PILE_COUNT, - DISCARD_PILE_COUNT, - HAND_SIZE, - STOCK_SIZE, - applyAutoPass, - applyDiscard, - applyPlay, - buildPileTopValue, - canPlayOnBuild, - createInitialState, - discardTop, - getValidPlays, - isPlayerStuck, - nextRequired, - stockTop, + CardTableScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { + CARD_W, CARD_H, inPose, fanHit, fanInsertIndex, fanZone, inRect, poseScale, +} from '../../ui/cardtable/TableGeometry.js'; +import { chooseAction, suggestAction, suggestDiscard } from './SkipBoAI.js'; +import { + createInitialState, startNextGame, applyPlay, applyDiscard, applyAutoPass, isPlayerStuck, isGameDone, + canPlayOnBuild, nextRequired, stockTop, discardTop, getValidPlays, BUILD_PILE_COUNT, DISCARD_PILE_COUNT, MATCH_TARGET, } from './SkipBoLogic.js'; -import { chooseAction } from './SkipBoAI.js'; +import { + T, SQ, SEAT_COLORS, SEAT_HEX, layoutFor, stockPose, stockBase, discardPose, discardRect, buildPose, pilePose, + handPose, stockBadge, handHome, spotFor, +} from './SkipBoTable.js'; +import { prepareSkipBoArt, frameKey } from './SkipBoArt.js'; -// ── Layout constants ──────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; +// ─── Skip-Bo ────────────────────────────────────────────────────────────────── +// Grandma's dining table on the shared card-table kit (src/ui/cardtable/). +// Rules: SkipBoLogic.js (pure) · opponents: SkipBoAI.js · this file is flow, +// animation and input. Every card is a persistent sprite keyed by id. -const CARD_W = 90; -const CARD_H = 126; -const CARD_R = 8; -const HAND_SPREAD = 110; +const DEFAULTS = { pace: 'normal', hints: true, sort: 'number', stock: 30, target: 0 }; +const byValue = (a, b) => (a.value === 'wild' ? 13 : a.value) - (b.value === 'wild' ? 13 : b.value) || a.id - b.id; +const DOUBLE_CLICK_MS = 320; -const D = { - felt: -1, board: 0, pile: 5, card: 10, highlight: 20, - ui: 30, portrait: 35, banner: 60, modal: 80, -}; - -// Rim color per number band so a glance reveals the top-of-pile value. -const NUMBER_RIM = { - 1: 0x2b7fbf, 2: 0x2b7fbf, 3: 0x2b7fbf, - 4: 0x2f9e44, 5: 0x2f9e44, 6: 0x2f9e44, - 7: 0xe6b800, 8: 0xe6b800, 9: 0xe6b800, - 10: 0xc92a2a, 11: 0xc92a2a, 12: 0xc92a2a, -}; -const WILD_FILL = 0xf2ead8; -const WILD_STRIPE = 0xc8a84b; - -// ── Seat anchors ──────────────────────────────────────────────────────────── -// Indexed by SEAT slot (0=bottom local, 1=left, 2=top, 3=right). At runtime -// we map game-state seat indices to slots based on player count. -const SEAT_SLOTS = ['bottom', 'left', 'top', 'right']; - -// Number of slot positions used per player count: always uses the bottom slot -// for the local player, then top/left/right in this order for opponents. -const SLOTS_USED = { - 2: ['bottom', 'top'], - 3: ['bottom', 'left', 'right'], - 4: ['bottom', 'left', 'top', 'right'], -}; - -// ── Slot layout ───────────────────────────────────────────────────────────── -// Each slot returns positions for: stock, 4 discards, the hand row's start -// position (cards laid out along an axis), the portrait position, and the -// hand layout direction. -function slotLayout(slot) { - switch (slot) { - case 'bottom': - return { - rotation: 0, - stock: { x: 460, y: 950 }, - discards: [{ x: 630, y: 950 }, { x: 750, y: 950 }, { x: 870, y: 950 }, { x: 990, y: 950 }], - handStart: { x: 1110, y: 975 }, - handAxis: 'x', - portrait: { x: 320, y: 950, r: 60 }, - nameLabel: { x: 320, y: 1030 }, - stockCntPos: { x: 460, y: 855 }, - rotateCards: 0, - outlineRotation: 0, - }; - case 'top': - return { - rotation: 180, - stock: { x: 560, y: 130 }, - discards: [{ x: 730, y: 130 }, { x: 850, y: 130 }, { x: 970, y: 130 }, { x: 1090, y: 130 }], - handStart: { x: 1000, y: 80 }, - handAxis: 'x', - portrait: { x: 420, y: 130, r: 60 }, - nameLabel: { x: 420, y: 210 }, - stockCntPos: { x: 560, y: 225 }, - rotateCards: 180, - outlineRotation: 0, - }; - case 'left': - return { - rotation: 90, - stock: { x: 100, y: 260 }, - discards: [{ x: 100, y: 430 }, { x: 100, y: 550 }, { x: 100, y: 670 }, { x: 100, y: 790 }], - handStart: { x: 40, y: 920 }, - handAxis: 'y-up', // hand fans upward toward 920..520 - portrait: { x: 100, y: 130, r: 56 }, - nameLabel: { x: 100, y: 50 }, - stockCntPos: { x: 205, y: 260 }, - rotateCards: 90, - outlineRotation: 90, - }; - case 'right': - return { - rotation: 270, - stock: { x: 1820, y: 260 }, - discards: [{ x: 1820, y: 430 }, { x: 1820, y: 550 }, { x: 1820, y: 670 }, { x: 1820, y: 790 }], - handStart: { x: 1880, y: 920 }, - handAxis: 'y-up', - portrait: { x: 1820, y: 130, r: 56 }, - nameLabel: { x: 1820, y: 50 }, - stockCntPos: { x: 1715, y: 260 }, - rotateCards: 270, - outlineRotation: 90, - }; - default: - throw new Error(`Unknown slot: ${slot}`); - } -} - -// Center build piles -const BUILD_X0 = CX - (CARD_W + 28) * 1.5; -const BUILD_Y = CY + 30; -function buildPilePos(idx) { - return { x: BUILD_X0 + idx * (CARD_W + 28), y: BUILD_Y }; -} -const DRAW_POS = { x: CX - 320, y: CY + 30 }; - -// ── Scene ─────────────────────────────────────────────────────────────────── -export default class SkipBoGame extends Phaser.Scene { +export default class SkipBoGame extends CardTableScene { constructor() { super('SkipBoGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.cardBack = data.cardBack ?? null; - - // Runtime state + this.initTable(data, { settingsKey: 'skipbo-settings', defaults: DEFAULTS }); + this.L = layoutFor(this.playerCount); + this.backKey = 'sb-back'; this.gs = null; - this.animating = false; - this.gameOver = false; - - // Card visuals: map card.id → Phaser.Container - this.cardObjs = new Map(); - // Decorations cleared every renderAll (count chips, etc.) - this.transientObjs = []; - - // Pile drop targets (rects + zones) - this.buildPileObjs = []; // [{ rect, label }] - this.discardPileObjs = []; // [seat][discIdx] → { rect } - this.stockPileObjs = []; // seat → { rect, count } - - // Local interaction - this.selectedSource = null; // { kind: 'hand'|'stock'|'discard', idx? } - this.highlightObjs = []; + this.history = []; + this.selected = null; // { source, sourceIdx, id } + this.hoverId = null; this.potentialDrag = null; this.dragState = null; - this.handObjs = []; // seat → [container] for arranging - this.opponentPortraits = []; // seat → portrait controller (or null) - - // Seat slot mapping. Slot index in SLOTS_USED matches seat index. - this.slotForSeat = []; + this.dragPreview = null; + this.revealAll = false; + this.lastClick = { id: null, at: 0 }; + this.badges = []; } - create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildPlayfield(); - this.assignSeats(); - this.buildSeatAreas(); - this.buildCenter(); - this.buildHUD(); - this.setupDragHandlers(); - this.startNewGame(); + faceFrame(card) { return { key: 'sb-cards', frame: frameKey(card) }; } + + async create() { + this.createTableBase(); + const key = await prepareSkipBoArt(this, this.playerCount); + if (!this.alive()) return; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildSpot(); + this.slabG = this.add.graphics().setDepth(D.cards - 1); + this.targetG = this.add.graphics().setDepth(D.glow); + this.needTxt = this.L.builds.map(b => this.add.text(b.x, b.y + (CARD_H / 2) * b.s * SQ + 18, '', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f2e2c4', stroke: '#3a0c14', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels)); + this.drawTxt = this.add.text(this.L.draw.x, this.L.draw.y + (CARD_H / 2) * this.L.draw.s * SQ + 18, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#f2e2c4', stroke: '#3a0c14', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels); + this.buildDropSlot(); + this.buildPlates(this.L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'WINS!' }); + this.buildBadges(); + this.buildGhostHands(this.L.seats.map((_, s) => (s ? handHome(this.L, s) : null)), SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Rules: () => this.openRules(), + }, 'Click a card, then a build pile · double-click to auto-play · drag works too\nEnd your turn by putting a hand card on one of your 4 piles · B best play · X auto-discard · H hint · Esc menu'); + this.buildDock(); + this.buildSortRow([['number', '1·2·3'], ['manual', 'Mine']], () => { this.sortHand(); this.layout(); }); + this.buildTooltips(); + this.setupInput(); + this.newMatch(); } - // ── Setup ──────────────────────────────────────────────────────────────── - - 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); + // ── Furniture ───────────────────────────────────────────────────────────── + buildBadges() { + for (let seat = 0; seat < this.playerCount; seat++) { + const p = stockBadge(this.L, seat); + const r = seat === 0 ? 19 : 15; + const c = this.add.container(p.x, p.y).setDepth(D.glow + 2); + const glow = this.add.circle(0, 0, r + 7, 0xff8a2a, 0); + const g = this.add.graphics(); + g.fillStyle(0x140d07, 0.92); + g.fillCircle(0, 0, r); + g.lineStyle(2.5, SEAT_COLORS[seat], 1); + g.strokeCircle(0, 0, r); + const t = this.add.text(0, 1, '30', { fontFamily: 'Righteous', fontSize: `${seat === 0 ? 19 : 15}px`, color: COLORS.textHex }).setOrigin(0.5); + c.add([glow, g, t]); + if (seat === 0) c.add(this.add.text(0, -r - 11, 'STOCK', { fontFamily: '"Julius Sans One"', fontSize: '12px', color: SEAT_HEX[0] }).setOrigin(0.5)); + this.badges[seat] = { c, glow, t, tw: null, last: null }; } } - assignSeats() { - const playerCount = 1 + this.opponents.length; - const slots = SLOTS_USED[playerCount]; - if (!slots) throw new Error(`Skip-Bo needs 2..4 players, got ${playerCount}`); - this.slotForSeat = slots.slice(); - } - - buildSeatAreas() { - const playerCount = this.slotForSeat.length; - for (let seat = 0; seat < playerCount; seat++) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - - // Stock placeholder - const sRect = this.add.rectangle(layout.stock.x, layout.stock.y, CARD_W + 6, CARD_H + 6, 0x000000, 0.35) - .setStrokeStyle(2, COLORS.muted).setAngle(layout.outlineRotation).setDepth(D.pile); - // Stock count badge - this.add.rectangle(layout.stockCntPos.x, layout.stockCntPos.y, 52, 34, 0x000000, 0.55) - .setDepth(D.ui); - const sCnt = this.add.text(layout.stockCntPos.x, layout.stockCntPos.y, '0', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.accentHex, fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.ui + 1); - this.stockPileObjs[seat] = { rect: sRect, count: sCnt, x: layout.stock.x, y: layout.stock.y }; - - if (seat === 0) { - // Clickable for local player - sRect.setInteractive({ useHandCursor: true }); - sRect.on('pointerdown', () => this.onStockClick()); - } - - // Discard placeholders - this.discardPileObjs[seat] = []; - for (let d = 0; d < DISCARD_PILE_COUNT; d++) { - const pos = layout.discards[d]; - const r = this.add.rectangle(pos.x, pos.y, CARD_W + 6, CARD_H + 6, 0x000000, 0.25) - .setStrokeStyle(1, COLORS.muted).setAngle(layout.outlineRotation).setDepth(D.pile); - if (seat === 0) { - r.setInteractive({ useHandCursor: true }); - r.on('pointerdown', () => this.onDiscardClick(d)); - } - this.discardPileObjs[seat][d] = { rect: r, x: pos.x, y: pos.y }; - } - - // Portrait + name - if (seat === 0) { - createPlayerPortrait(this, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait, 'SkipBoGame'); - this.add.text(layout.nameLabel.x, layout.nameLabel.y, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - } else { - const opp = this.opponents[seat - 1]; - if (opp) { - this.opponentPortraits[seat] = createOpponentPortrait(this, opp, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait); - this.add.text(layout.nameLabel.x, layout.nameLabel.y, opp.name ?? `P${seat + 1}`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - } - } + buildTooltips() { + for (let seat = 1; seat < this.playerCount; seat++) { + const pl = this.L.seats[seat].plate; + this.hoverZone(pl.x, pl.y, 300, 96, () => this.seatTip(seat)); } } - 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); - this.add.text(DRAW_POS.x, DRAW_POS.y - CARD_H / 2 - 18, 'DRAW', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.drawPileText = this.add.text(DRAW_POS.x, DRAW_POS.y, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.accentHex, fontStyle: 'bold', - }).setOrigin(0.5).setDepth(D.ui); - this.drawPileRect = drawRect; - - // Build piles - for (let i = 0; i < BUILD_PILE_COUNT; i++) { - const p = buildPilePos(i); - const r = this.add.rectangle(p.x, p.y, CARD_W + 8, CARD_H + 8, 0x000000, 0.3) - .setStrokeStyle(2, COLORS.muted).setDepth(D.pile) - .setInteractive({ useHandCursor: true }); - r.on('pointerdown', () => this.onBuildPileClick(i)); - const label = this.add.text(p.x, p.y - CARD_H / 2 - 18, `BUILD ${i + 1}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - const needText = this.add.text(p.x, p.y + CARD_H / 2 + 18, 'next: 1', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.ui); - this.buildPileObjs[i] = { rect: r, label, needText, x: p.x, y: p.y }; - } - } - - buildHUD() { - this.statusText = this.add.text(CX, 36, '', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - new Button(this, 110, GAME_HEIGHT - 50, 'New', () => this.startNewGame(), { - variant: 'ghost', width: 110, height: 40, fontSize: 18, - }).setDepth(D.ui); - new Button(this, 110, GAME_HEIGHT - 100, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 110, height: 40, fontSize: 18, - }).setDepth(D.ui); - - // Clicking empty space deselects the current card - this.input.on('pointerdown', (pointer) => { - if (!this.selectedSource) return; - if (this.potentialDrag || this.dragState) return; - if (this.input.hitTestPointer(pointer).length === 0) { - this.selectedSource = null; - this.clearHighlights(); - this.setStatus('Your turn'); - } - }); - } - - // ── Game start ─────────────────────────────────────────────────────────── - - startNewGame() { - if (this.animating) return; - this._clearDragState(); - this.gameOver = false; - this.clearAllCardObjs(); - this.clearHighlights(); - this.selectedSource = null; - - const playerCount = this.slotForSeat.length; - this.gs = createInitialState({ playerCount }); - playSound(this, SFX.CARD_SHUFFLE); - - this.renderAll(); - this.setStatus('Your turn'); - - if (this.gs.currentPlayer !== 0) { - this.runAITurn(); - } - } - - // ── Card sprite factory ───────────────────────────────────────────────── - - makeCardSprite(card, x, y, { faceUp = true, rotation = 0 } = {}) { - const c = this.add.container(x, y).setDepth(D.card); - c.setRotation((rotation * Math.PI) / 180); - this.renderCardFace(c, card, faceUp); - c.card = card; - return c; - } - - renderCardFace(container, card, faceUp) { - // Remove existing children safely - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - - if (!faceUp) { - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - g.destroy(); - container.add( - this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H) - .setOrigin(0.5) - ); - } else { - this.drawCardBackGfx(g, x, y); - container.add(g); - } - return; - } - - if (card.value === 'wild') { - // Wild face — gold stripes + "SKIP-BO" text - 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); - // Diagonal stripes — clipped to card bounds - 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); - - if (card.playedAs) { - // Big played-as number overlaid on a chip - const chip = this.add.graphics(); - chip.fillStyle(0x1a1208, 0.9); - chip.fillRoundedRect(-26, -22, 52, 44, 8); - chip.lineStyle(2, WILD_STRIPE, 1); - chip.strokeRoundedRect(-26, -22, 52, 44, 8); - container.add(chip); - container.add(this.add.text(0, 0, `${card.playedAs}`, { - fontFamily: '"Julius Sans One"', fontSize: '32px', - color: COLORS.accentHex, fontStyle: 'bold', - }).setOrigin(0.5)); - } else { - container.add(this.add.text(0, -8, 'SKIP', { - fontFamily: 'Righteous', fontSize: '18px', color: '#1a1208', - }).setOrigin(0.5)); - container.add(this.add.text(0, 14, 'BO', { - fontFamily: 'Righteous', fontSize: '18px', color: '#1a1208', - }).setOrigin(0.5)); - } - return; - } - - // Numbered face - const rim = NUMBER_RIM[card.value] ?? 0x888888; - g.fillStyle(0xfbf6e7, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(4, rim, 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: '#1a1208', - }); - 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)); - } - - 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); - } - - clearAllCardObjs() { - for (const c of this.cardObjs.values()) c.destroy(); - this.cardObjs.clear(); - for (const o of this.transientObjs) o.destroy(); - this.transientObjs = []; - } - - // ── Rendering ──────────────────────────────────────────────────────────── - - renderAll() { - this._clearDragState(); - this.clearAllCardObjs(); - this.renderCenter(); - for (let seat = 0; seat < this.gs.players.length; seat++) { - this.renderSeat(seat); - } - this.renderTurnIndicator(); - } - - renderCenter() { - // Draw pile — show a card back representing the deck size - 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}`); - - // Build piles - for (let i = 0; i < BUILD_PILE_COUNT; i++) { - const pile = this.gs.buildPiles[i]; - const obj = this.buildPileObjs[i]; - const top = pile.length > 0 ? pile[pile.length - 1] : null; - if (top) { - const c = this.makeCardSprite(top, obj.x, obj.y, { faceUp: true }); - this.cardObjs.set(`build-${i}-${top.id}`, c); - } - const need = nextRequired(this.gs, i); - obj.needText.setText(need > 12 ? '—' : `next: ${need}`); - } - } - - renderSeat(seat) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - const player = this.gs.players[seat]; - - // Stock — show the top card if any - const stockCnt = this.stockPileObjs[seat].count; - stockCnt.setText(`${player.stock.length}`); + seatTip(seat) { + if (!this.gs) return null; + const p = this.gs.players[seat]; const top = stockTop(this.gs, seat); - if (top) { - const c = this.makeCardSprite(top, layout.stock.x, layout.stock.y, { - faceUp: true, rotation: layout.rotateCards, - }); - this.cardObjs.set(`stock-${seat}-${top.id}`, c); - if (seat === 0) { - 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._onCardPointerDown('stock', 0, c, pointer)); - } - } - - // Discards — show top of each - for (let d = 0; d < DISCARD_PILE_COUNT; d++) { - const pile = player.discards[d]; - if (pile.length === 0) continue; - const t = pile[pile.length - 1]; - const pos = layout.discards[d]; - const c = this.makeCardSprite(t, pos.x, pos.y, { - faceUp: true, rotation: layout.rotateCards, - }); - this.cardObjs.set(`discard-${seat}-${d}-${t.id}`, c); - if (seat === 0) { - 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._onCardPointerDown('discard', d, c, pointer)); - } - // Pile-depth chip if more than one card - if (pile.length > 1) { - const chip = this.add.text(pos.x + CARD_W / 2 - 4, pos.y + CARD_H / 2 - 4, `×${pile.length}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', - color: COLORS.textDarkHex, backgroundColor: COLORS.accentHex, - padding: { x: 4, y: 2 }, - }).setOrigin(1, 1).setDepth(D.ui); - this.transientObjs.push(chip); - } - } - - // Hand - this.renderHand(seat); + const lines = [ + { text: `${p.stock.length} left in stock`, color: p.stock.length <= 3 ? '#ffb15a' : COLORS.textHex }, + { text: top ? `Stock shows ${top.value === 'wild' ? 'a Wild' : `a ${top.value}`}` : 'Stock empty', color: COLORS.goldHex }, + { text: `${p.hand.length} cards in hand` }, + { text: this.gs.target > 0 ? `Score ${this.gs.scores[seat]} / ${this.gs.target}` : `Games won ${this.gamesWon(seat)}` }, + { text: `Skill ${this.skillFor(seat)} / 5`, color: COLORS.mutedHex }, + ]; + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; } - renderHand(seat) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot); - const player = this.gs.players[seat]; - const isLocal = seat === 0; + gamesWon(seat) { return this.history.filter(h => h.winner === seat).length; } - for (let i = 0; i < player.hand.length; i++) { - const card = player.hand[i]; - let x, y; - if (layout.handAxis === 'x') { - x = layout.handStart.x + i * HAND_SPREAD; - y = layout.handStart.y; - } else { // 'y-up' - x = layout.handStart.x; - y = layout.handStart.y - i * HAND_SPREAD; - } - const c = this.makeCardSprite(card, x, y, { - faceUp: isLocal, rotation: layout.rotateCards, - }); - this.cardObjs.set(`hand-${seat}-${card.id}`, c); - if (isLocal) { - 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._onCardPointerDown('hand', i, c, pointer)); - } - } + // ── Match lifecycle ────────────────────────────────────────────────────── + newMatch() { + this.history = []; + this.gs = createInitialState({ playerCount: this.playerCount, stockSize: this.settings.stock, target: this.settings.target }); + this.startGame(); } - renderTurnIndicator() { + async startGame() { + this.clearSprites(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + this.revealAll = false; + this.selected = null; + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } + const gs = this.gs; + const from = { ...this.L.draw, y: this.L.draw.y - 8 }; + for (const p of gs.players) { + for (const c of p.stock) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + for (const c of p.hand) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + } + this.sortHand(); + this.updatePlates(); + this.updateDock(); + playSound(this, SFX.CARD_SHUFFLE); + // stock piles are counted out (a few loose backs fly to each), then the stock tops flip + const n = this.playerCount; + for (let s = 0; s < n; s++) { + for (let i = 0; i < 6; i++) { + const c = this.makeCard({ value: 1, id: -1 }, false, from); + c.setDepth(D.fly); + this.fx.push(c); + this.tweenCard(c, stockBase(this.L, s), { delay: i * 70 + s * 50, duration: 280, onDone: () => c.destroy() }); + } + } + this.time.delayedCall(250, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.5 })); + this.layout({ + duration: 320, + delayFor: (v) => (v.kind === 'stock' ? 520 + v.seat * 80 : v.kind === 'hand' ? 800 + v.idx * 60 : 0), + }); + await this.wait(1500); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } + + advance() { + if (!this.alive() || !this.gs) return; + if (isGameDone(this.gs)) { this.onGameOver(); return; } const seat = this.gs.currentPlayer; - const slot = this.slotForSeat[seat]; - const lay = slotLayout(slot); - if (!this.turnGlow) { - this.turnGlow = this.add.circle(0, 0, 80, COLORS.accent, 0.18).setDepth(D.portrait - 1); - } - this.turnGlow.setPosition(lay.portrait.x, lay.portrait.y); - } - - // ── Local input ───────────────────────────────────────────────────────── - - isLocalTurn() { - return this.gs && !this.gameOver && this.gs.phase === 'play' && this.gs.currentPlayer === 0; - } - - onHandClick(handIdx) { - if (!this.isLocalTurn() || this.animating) return; - this.selectedSource = { kind: 'hand', idx: handIdx }; - this.highlightValidTargets(); - this.setStatus('Choose a build pile, or click a discard pile to end your turn.'); - } - - onStockClick() { - if (!this.isLocalTurn() || this.animating) return; - this.selectedSource = { kind: 'stock' }; - this.highlightValidTargets(); - this.setStatus('Choose a build pile for your stock top.'); - } - - onDiscardClick(discardIdx) { - if (!this.isLocalTurn() || this.animating) return; - // If we have a selected hand card, treat this as a discard-to-end-turn. - if (this.selectedSource?.kind === 'hand') { - const handIdx = this.selectedSource.idx; - this.selectedSource = null; - this.clearHighlights(); - this.commitDiscard(handIdx, discardIdx); + this.setSpot(spotFor(this.L, seat)); + if (isPlayerStuck(this.gs)) { + this.floatText(this.seatCentre(seat), seat === 0 ? 'No cards to play — you pass' : `${this.shortName(seat)} can't play — pass`, '#f2d6a0', { size: 22, ms: 1600 }); + this.time.delayedCall(900 * this.pace(), () => { this.commit(applyAutoPass(this.gs)); this.advance(); }); return; } - // Otherwise treat as selecting that discard top as a source. - const top = discardTop(this.gs, 0, discardIdx); - if (!top) return; - this.selectedSource = { kind: 'discard', idx: discardIdx }; - this.highlightValidTargets(); - this.setStatus('Choose a build pile for the discard top.'); - } - - onBuildPileClick(buildIdx) { - if (!this.isLocalTurn() || this.animating) return; - const sel = this.selectedSource; - if (!sel) { - this.setStatus('Select a card first (hand, stock top, or discard top).'); - return; - } - const card = this.cardForSelection(sel); - if (!card) { this.selectedSource = null; return; } - if (!canPlayOnBuild(this.gs, card, buildIdx)) { - this.setStatus("Can't play there."); - return; - } - const play = this.buildPlayObject(sel, buildIdx, card); - if (card.value === 'wild') { - play.asNumber = nextRequired(this.gs, buildIdx); - } - this.selectedSource = null; - this.clearHighlights(); - this.commitPlay(play); - } - - cardForSelection(sel) { - if (sel.kind === 'hand') return this.gs.players[0].hand[sel.idx]; - if (sel.kind === 'stock') return stockTop(this.gs, 0); - if (sel.kind === 'discard') return discardTop(this.gs, 0, sel.idx); - return null; - } - - buildPlayObject(sel, buildIdx, card) { - return { - type: 'play', - source: sel.kind, - sourceIdx: sel.kind === 'hand' ? sel.idx : (sel.kind === 'discard' ? sel.idx : 0), - buildIdx, - }; - } - - highlightValidTargets() { - this.clearHighlights(); - const sel = this.selectedSource; - const card = this.cardForSelection(sel); - if (!card) return; - for (let i = 0; i < BUILD_PILE_COUNT; i++) { - if (canPlayOnBuild(this.gs, card, i)) { - const obj = this.buildPileObjs[i]; - const h = this.add.rectangle(obj.x, obj.y, CARD_W + 18, CARD_H + 18, 0xffd700, 0.18) - .setStrokeStyle(3, 0xffd700, 0.9).setDepth(D.highlight); - this.highlightObjs.push(h); - } - } - // Highlight discard piles only when a hand card is selected (turn-ender) - if (sel.kind === 'hand') { - for (let d = 0; d < DISCARD_PILE_COUNT; d++) { - const pos = slotLayout(this.slotForSeat[0]).discards[d]; - const h = this.add.rectangle(pos.x, pos.y, CARD_W + 18, CARD_H + 18, 0x4dabf7, 0.12) - .setStrokeStyle(2, 0x4dabf7, 0.7).setDepth(D.highlight); - this.highlightObjs.push(h); - } - } - } - - clearHighlights() { - for (const h of this.highlightObjs) h.destroy(); - this.highlightObjs = []; - } - - // ── Drag and drop ──────────────────────────────────────────────────────── - - setupDragHandlers() { - this.input.on('pointermove', (pointer) => { - if (!pointer.isDown) return; - if (this.dragState) { - this._updateCardDrag(pointer); - } else if (this.potentialDrag) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (dx * dx + dy * dy > 64) this._promoteToDrag(); - } - }); - this.input.on('pointerup', () => { - if (this.dragState) { - this._endCardDrag(); - } else if (this.potentialDrag) { - const pd = this.potentialDrag; - this.potentialDrag = null; - if (pd.kind === 'hand') this.onHandClick(pd.idx); - else if (pd.kind === 'stock') this.onStockClick(); - else if (pd.kind === 'discard') this.onDiscardClick(pd.idx); - } - }); - } - - _onCardPointerDown(kind, idx, cardObj, pointer) { - if (!this.isLocalTurn() || this.animating || this.dragState) return; - this.potentialDrag = { - kind, idx, cardObj, - origX: cardObj.x, origY: cardObj.y, - startX: pointer.x, startY: pointer.y, - offsetX: pointer.x - cardObj.x, - offsetY: pointer.y - cardObj.y, - }; - } - - _promoteToDrag() { - const pd = this.potentialDrag; - this.potentialDrag = null; - this.selectedSource = null; - this.clearHighlights(); - - const { cardObj, origX, origY, offsetX, offsetY, kind, idx } = pd; - cardObj.setDepth(D.card + 10); - this.tweens.add({ targets: cardObj, scaleX: 1.08, scaleY: 1.08, duration: 100, ease: 'Cubic.easeOut' }); - - const shadow = this.add.ellipse(cardObj.x + 6, cardObj.y + 18, CARD_W * 1.05, 26, 0x000000, 0.35) - .setDepth(D.card + 9); - this.transientObjs.push(shadow); - - this.dragState = { kind, idx, cardObj, origX, origY, offsetX, offsetY, shadow, dropTarget: null, highlight: null }; - } - - _updateCardDrag(pointer) { - const ds = this.dragState; - ds.cardObj.x = pointer.x - ds.offsetX; - ds.cardObj.y = pointer.y - ds.offsetY; - ds.shadow.setPosition(ds.cardObj.x + 6, ds.cardObj.y + 18); - - const newTarget = this._getDropTargetAt(ds.cardObj.x, ds.cardObj.y, ds.kind, this._cardForDragState()); - if (!this._dropTargetsEqual(newTarget, ds.dropTarget)) { - ds.dropTarget = newTarget; - this._updateDropHighlight(newTarget); - } - } - - _cardForDragState() { - const ds = this.dragState; - if (!ds) return null; - if (ds.kind === 'hand') return this.gs.players[0].hand[ds.idx]; - if (ds.kind === 'stock') return stockTop(this.gs, 0); - if (ds.kind === 'discard') return discardTop(this.gs, 0, ds.idx); - return null; - } - - _getDropTargetAt(x, y, kind, card) { - if (!this.isLocalTurn() || this.animating || !card) return null; - - for (let i = 0; i < BUILD_PILE_COUNT; i++) { - const obj = this.buildPileObjs[i]; - if (Math.abs(x - obj.x) < CARD_W * 0.8 && Math.abs(y - obj.y) < CARD_H * 0.8) { - if (canPlayOnBuild(this.gs, card, i)) return { type: 'build', idx: i }; - } - } - - if (kind === 'hand') { - const discards = slotLayout(this.slotForSeat[0]).discards; - for (let d = 0; d < DISCARD_PILE_COUNT; d++) { - const pos = discards[d]; - if (Math.abs(x - pos.x) < CARD_W * 0.8 && Math.abs(y - pos.y) < CARD_H * 0.8) { - return { type: 'discard', idx: d }; - } - } - } - - return null; - } - - _dropTargetsEqual(a, b) { - if (!a && !b) return true; - if (!a || !b) return false; - return a.type === b.type && a.idx === b.idx; - } - - _updateDropHighlight(dropTarget) { - const ds = this.dragState; - if (ds.highlight) { - const i = this.transientObjs.indexOf(ds.highlight); - if (i >= 0) this.transientObjs.splice(i, 1); - ds.highlight.destroy(); - ds.highlight = null; - } - if (!dropTarget) return; - - let x, y, color; - if (dropTarget.type === 'build') { - ({ x, y } = this.buildPileObjs[dropTarget.idx]); - color = 0xffd700; + if (seat === 0) { + this.mode = 'human'; + this.selected = null; + this.layout(); + this.updateDock(); + this.updatePlates(); + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); } else { - const pos = slotLayout(this.slotForSeat[0]).discards[dropTarget.idx]; - x = pos.x; y = pos.y; - color = 0x4dabf7; - } - const h = this.add.rectangle(x, y, CARD_W + 20, CARD_H + 20, color, 0.22) - .setStrokeStyle(4, color, 1).setDepth(D.highlight); - ds.highlight = h; - this.transientObjs.push(h); - } - - _endCardDrag() { - const ds = this.dragState; - this.dragState = null; - - if (ds.highlight) { ds.highlight.destroy(); ds.highlight = null; } - if (ds.shadow) { ds.shadow.destroy(); ds.shadow = null; } - - ds.cardObj.setDepth(D.card); - this.tweens.add({ targets: ds.cardObj, scaleX: 1, scaleY: 1, duration: 80 }); - - const card = (() => { - if (ds.kind === 'hand') return this.gs.players[0].hand[ds.idx]; - if (ds.kind === 'stock') return stockTop(this.gs, 0); - if (ds.kind === 'discard') return discardTop(this.gs, 0, ds.idx); - return null; - })(); - - const target = this._getDropTargetAt(ds.cardObj.x, ds.cardObj.y, ds.kind, card); - - if (target?.type === 'build') { - const action = { type: 'play', source: ds.kind, sourceIdx: ds.idx, buildIdx: target.idx }; - if (card?.value === 'wild') action.asNumber = nextRequired(this.gs, target.idx); - this.commitPlay(action); - } else if (target?.type === 'discard') { - this.commitDiscard(ds.idx, target.idx); - } else { - this._returnCardToOrigin(ds.cardObj, ds.origX, ds.origY); + this.mode = 'ai'; + this.selected = null; + this.layout(); + this.updateDock(); + this.updatePlates(); + this.runAITurn(seat); } } - _returnCardToOrigin(cardObj, origX, origY) { - this.tweens.killTweensOf(cardObj); - this.tweens.add({ - targets: cardObj, x: origX, y: origY, scaleX: 1, scaleY: 1, - duration: 280, ease: 'Back.easeOut', + seatCentre(seat) { + if (seat === 0) return { x: CX, y: 860 }; + return handHome(this.L, seat); + } + + commit(next, { carry = null, carrySeat = null } = {}) { + const prev = this.gs; + this.gs = next; + const fresh = next.log.slice(prev.log.length); + const order = new Map(); + next.players.forEach((p, s) => { + const had = new Set(prev.players[s].hand.map(c => c.id)); + let k = 0; + for (const c of p.hand) if (!had.has(c.id)) order.set(c.id, k++); }); - } - - _clearDragState() { - if (this.dragState) { - if (this.dragState.shadow) this.dragState.shadow.destroy(); - if (this.dragState.highlight) this.dragState.highlight.destroy(); - this.dragState = null; - } - this.potentialDrag = null; - } - - // ── Action commit ─────────────────────────────────────────────────────── - - commitPlay(action) { - this.animating = true; - const beforeSeat = this.gs.currentPlayer; - const next = applyPlay(this.gs, action); - this.animatePlay(this.gs, next, action, () => { - this.gs = next; - this.renderAll(); - this.animating = false; - if (this.gs.phase === 'gameover') { this.endGame(); return; } - if (this.checkForStuck()) return; - // After a successful play it's still the same player's turn until they - // discard. If AI's turn, continue. - if (this.gs.currentPlayer !== 0) { - this.runAITurn(); - } else { - this.setStatus("Play more, or end your turn by discarding."); - } + if (order.size && this.settings.sort !== 'manual') this.sortHand(); + this.layout({ + delayFor: (v) => (order.has(v.card.id) ? 120 + order.get(v.card.id) * 90 : 0), + durationFor: (v) => (carry != null && v.card.id === carry ? this.timing(carrySeat).carry : null), }); + for (const e of fresh) this.logEffect(e); + this.updatePlates(); + this.updateDock(); } - commitDiscard(handIdx, discardIdx) { - this.animating = true; - const next = applyDiscard(this.gs, handIdx, discardIdx); - this.animateDiscard(this.gs, next, handIdx, discardIdx, () => { - this.gs = next; - this.renderAll(); - this.animating = false; - if (this.gs.phase === 'gameover') { this.endGame(); return; } - if (this.checkForStuck()) return; - if (this.gs.currentPlayer !== 0) { - this.runAITurn(); - } else { - this.setStatus('Your turn'); - } - }); - } - - // ── Animation ─────────────────────────────────────────────────────────── - // Cheap approach: identify the source card object before mutating, tween it - // to the destination, then on complete fully re-render from the next state. - - animatePlay(before, after, action, done) { - const fromKey = this.sourceKey(before, action); - const target = this.cardObjs.get(fromKey); - const dest = buildPilePos(action.buildIdx); - if (!target) { done(); return; } - playSound(this, SFX.CARD_PLACE); - this.tweens.add({ - targets: target, - x: dest.x, y: dest.y, scale: 1, - duration: 280, ease: 'Cubic.easeOut', - onComplete: done, - }); - } - - animateDiscard(before, after, handIdx, discardIdx, done) { - const card = before.players[before.currentPlayer].hand[handIdx]; - const fromKey = `hand-${before.currentPlayer}-${card.id}`; - const target = this.cardObjs.get(fromKey); - const layout = slotLayout(this.slotForSeat[before.currentPlayer]); - const dest = layout.discards[discardIdx]; - if (!target) { done(); return; } - playSound(this, SFX.CARD_PLACE); - this.tweens.add({ - targets: target, x: dest.x, y: dest.y, - duration: 240, ease: 'Cubic.easeOut', - onComplete: done, - }); - } - - sourceKey(state, action) { - const seat = state.currentPlayer; - if (action.source === 'stock') { - const top = stockTop(state, seat); - return top ? `stock-${seat}-${top.id}` : null; - } - if (action.source === 'hand') { - const c = state.players[seat].hand[action.sourceIdx]; - return c ? `hand-${seat}-${c.id}` : null; - } - if (action.source === 'discard') { - const c = discardTop(state, seat, action.sourceIdx); - return c ? `discard-${seat}-${action.sourceIdx}-${c.id}` : null; - } - return null; - } - - // ── AI loop ───────────────────────────────────────────────────────────── - - runAITurn() { - if (this.gameOver) return; - const seat = this.gs.currentPlayer; - const slot = this.slotForSeat[seat]; - const name = (this.opponents[seat - 1]?.name) ?? `Player ${seat + 1}`; - this.setStatus(`${name}'s turn…`); - this.time.delayedCall(450, () => this.stepAI()); - } - - stepAI() { - if (this.gameOver) return; - if (this.gs.currentPlayer === 0) { - this.setStatus('Your turn'); - return; - } - const action = chooseAction(this.gs); - if (!action) { - // Defensive — shouldn't happen - this.setStatus('AI passed.'); - return; - } - if (action.type === 'play') { - this.animating = true; - const seat = this.gs.currentPlayer; - if (action.source === 'stock') { - this.opponentPortraits[seat]?.playEmotion('happy'); - } - const next = applyPlay(this.gs, action); - this.animatePlay(this.gs, next, action, () => { - this.gs = next; - this.renderAll(); - this.animating = false; - if (this.gs.phase === 'gameover') { this.endGame(); return; } - if (this.checkForStuck()) return; - this.time.delayedCall(420, () => this.stepAI()); - }); - } else { - this.animating = true; - const next = applyDiscard(this.gs, action.handIdx, action.discardIdx); - this.animateDiscard(this.gs, next, action.handIdx, action.discardIdx, () => { - this.gs = next; - this.renderAll(); - this.animating = false; - if (this.gs.phase === 'gameover') { this.endGame(); return; } - if (this.checkForStuck()) return; - if (this.gs.currentPlayer === 0) { - this.setStatus('Your turn'); - } else { - this.runAITurn(); - } - }); + logEffect(e) { + if (e.kind === 'complete') { + const b = this.L.builds[e.buildIdx]; + this.floatText(b, 'Complete!', '#ffd35a', { size: 28 }); + this.burst(b, 0xffd35a, { n: 10, r: 80 }); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.55 }); + } else if (e.kind === 'recycle') { + this.floatText({ x: this.L.draw.x, y: this.L.draw.y - 70 }, `Shuffled ${e.count} back in`, '#f2e2c4', { size: 20, ms: 1600 }); + playSound(this, SFX.CARD_SHUFFLE); + } else if (e.kind === 'play' && e.source === 'stock') { + const st = this.L.seats[e.seat]; + const at = stockBase(this.L, e.seat); + this.floatText(at, e.seat === 0 ? 'Stock card played!' : 'Stock!', SEAT_HEX[e.seat], { size: e.seat === 0 ? 24 : 18, rise: 30 }); + void st; + if (e.seat > 0 && this.gs.players[e.seat].stock.length <= 3) this.portraits[e.seat]?.playEmotion?.('happy'); + } else if (e.kind === 'play' && e.wild) { + this.floatText(this.L.builds[e.buildIdx], `Wild as ${e.value}`, '#ffd35a', { size: 20, rise: 30 }); } } - // ── Stuck / auto-pass ─────────────────────────────────────────────────── + // ── AI ────────────────────────────────────────────────────────────────────── + async runAITurn(seat) { + const token = ++this.turnToken; + const T0 = this.timing(seat); + const still = () => this.alive() && token === this.turnToken && !isGameDone(this.gs) && this.gs.currentPlayer === seat; + await this.wait(T0.think); + let guard = 0; + while (still() && guard++ < 60) { + const a = chooseAction(this.gs, { skill: this.skillFor(seat) }); + if (!a) { this.commit(applyAutoPass(this.gs)); break; } + const ok = await this.aiPlay(seat, a, T0); + if (!this.alive() || token !== this.turnToken) return; + if (!ok || a.type === 'discard' || isGameDone(this.gs)) break; + await this.wait(T0.between); + } + if (!this.alive() || token !== this.turnToken) return; + if (!isGameDone(this.gs) && this.gs.currentPlayer === seat) { + // safety net: never stall the table + const g = this.gs; + const next = g.players[seat].hand.length ? applyDiscard(g, 0, 0) : applyAutoPass(g); + if (next !== g) this.commit(next); + } + this.advance(); + } - checkForStuck() { - if (!isPlayerStuck(this.gs)) return false; - const seat = this.gs.currentPlayer; - const name = seat === 0 - ? (auth.user?.username ?? 'You') - : (this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`); - const subject = seat === 0 ? 'You have' : `${name} has`; - this.setStatus(`${subject} no moves — passing turn.`); - this.animating = true; - this.time.delayedCall(1400, () => { - this.gs = applyAutoPass(this.gs); - this.renderAll(); - this.animating = false; - if (this.gs.phase === 'gameover') { this.endGame(); return; } - if (this.checkForStuck()) return; - if (this.gs.currentPlayer !== 0) { - this.runAITurn(); - } else { - this.setStatus('Your turn'); - } - }); + sourcePose(seat, source, sourceIdx) { + const p = this.gs.players[seat]; + if (source === 'stock') return stockPose(this.L, seat, p.stock.length); + if (source === 'discard') { + const n = p.discards[sourceIdx].length; + return discardPose(this.L, seat, sourceIdx, n - 1, n); + } + return this.poseOf(p.hand[sourceIdx]?.id) ?? handPose(this.L, seat, sourceIdx, p.hand.length); + } + + sourceCard(seat, source, sourceIdx) { + if (source === 'stock') return stockTop(this.gs, seat); + if (source === 'discard') return discardTop(this.gs, seat, sourceIdx); + return this.gs.players[seat].hand[sourceIdx]; + } + + async aiPlay(seat, a, T0) { + const card = a.type === 'play' ? this.sourceCard(seat, a.source, a.sourceIdx) : this.gs.players[seat].hand[a.handIdx]; + if (!card) return false; + const from = a.type === 'play' ? this.sourcePose(seat, a.source, a.sourceIdx) : this.poseOf(card.id); + this.moveHand(seat, from, T0.reach); + await this.wait(T0.reach); + const next = a.type === 'play' ? applyPlay(this.gs, a) : applyDiscard(this.gs, a.handIdx, a.discardIdx); + if (next === this.gs) return false; + this.commit(next, { carry: card.id, carrySeat: seat }); + const to = a.type === 'play' ? this.L.builds[a.buildIdx] : this.poseOf(card.id); + this.moveHand(seat, to, T0.carry, 'Cubic.easeOut'); + await this.wait(T0.carry); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.55 }); + this.handRest(seat, T0.carry * 0.7); return true; } - // ── Endgame ───────────────────────────────────────────────────────────── - - endGame() { - this.gameOver = true; - const winnerSeat = this.gs.winner; - - if (winnerSeat === -1) { - this.setStatus("It's a draw!"); - for (let s = 1; s < this.gs.players.length; s++) { - this.opponentPortraits[s]?.playEmotion?.('loss'); + // ── Layout ────────────────────────────────────────────────────────────────── + computeLayout() { + const L = this.L, gs = this.gs; + const visible = new Map(), loc = new Map(); + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + const dn = gs.drawPile.length; + const drawTop = pilePose(L.draw, dn); + gs.drawPile.forEach((c, i) => (i === dn - 1 ? put(c, { kind: 'draw', pose: drawTop, faceUp: false, depth: D.cards + 1 }) : loc.set(c.id, { pose: drawTop, faceUp: false, depth: D.cards }))); + const cn = gs.completedPile.length; + const doneTop = pilePose(L.completed, cn); + gs.completedPile.forEach((c, i) => (i === cn - 1 ? put(c, { kind: 'done', pose: doneTop, faceUp: false, depth: D.cards + 1 }) : loc.set(c.id, { pose: doneTop, faceUp: false, depth: D.cards }))); + gs.buildPiles.forEach((pile, b) => { + const n = pile.length; + const pose = buildPose(L, b, n); + pile.forEach((c, i) => { + if (i >= n - 2) put(c, { kind: 'build', idx: b, pose, faceUp: true, depth: D.cards + 1 + (i - n + 2) * 0.01, chip: c.value === 'wild' ? c.playedAs : null }); + else loc.set(c.id, { pose, faceUp: true, depth: D.cards }); + }); + }); + const sel = this.selected; + for (const p of gs.players) { + const seat = p.seat; + const sn = p.stock.length; + p.stock.forEach((c, i) => { + const pose = stockPose(L, seat, sn); + const lift = seat === 0 && sel?.source === 'stock' ? 14 : 0; + if (i === sn - 1) put(c, { kind: 'stock', seat, pose: lift ? { ...pose, y: pose.y - lift } : pose, faceUp: true, depth: D.cards + 1.5, source: 'stock', sourceIdx: 0 }); + else loc.set(c.id, { pose, faceUp: false, depth: D.cards }); + }); + p.discards.forEach((pile, d) => { + const n = pile.length; + pile.forEach((c, i) => { + const top = i === n - 1; + const lift = seat === 0 && top && sel?.source === 'discard' && sel.sourceIdx === d ? 14 : 0; + const pose = discardPose(L, seat, d, i, n); + put(c, { kind: 'discard', seat, idx: d, pose: lift ? { ...pose, y: pose.y - lift } : pose, faceUp: true, depth: D.cards + 1 + i * 0.01, source: top ? 'discard' : null, sourceIdx: d }); + }); + }); + if (seat === 0) { + const ids = this.dragPreview ?? p.hand.map(c => c.id); + ids.forEach((id, i) => { + const c = p.hand.find(h => h.id === id); + if (!c) return; + const lift = sel?.id === id ? 40 : id === this.hoverId ? 22 : 0; + put(c, { kind: 'hand', seat: 0, idx: i, pose: handPose(L, 0, i, ids.length, lift), faceUp: true, depth: D.hand + i * 0.01, source: 'hand' }); + }); + } else { + p.hand.forEach((c, i) => put(c, { kind: 'hand', seat, idx: i, pose: handPose(L, seat, i, p.hand.length), faceUp: this.revealAll, depth: D.oppHand + i * 0.01 })); } - this.recordHistory(false); - this.showGameOverPanel("It's a draw!", false, null, 'No player could make a move.'); + } + return { visible, loc }; + } + + beforeLayout() { + this.suggestion = this.mode === 'human' && this.gs.currentPlayer === 0 && this.settings.hints ? suggestAction(this.gs) : null; + this.playableSources = this.mode === 'human' ? this.humanSources() : new Set(); + } + + // Card ids the human could play onto a build pile right now. + humanSources() { + const out = new Set(); + if (this.gs.currentPlayer !== 0 || isGameDone(this.gs)) return out; + for (const p of getValidPlays(this.gs)) out.add(p.card.id); + return out; + } + + suggestedId() { + const a = this.suggestion; + if (!a) return null; + if (a.type === 'play') return this.sourceCard(0, a.source, a.sourceIdx)?.id ?? null; + return this.gs.players[0].hand[a.handIdx]?.id ?? null; + } + + decorate(c, v) { + let mark = '', color = '#ffffff'; + const mine = v.seat === 0 && (v.kind === 'hand' || v.kind === 'stock' || (v.kind === 'discard' && v.source)); + if (mine && this.settings.hints && this.mode === 'human') { + if (this.suggestedId() === v.card.id) { + mark = this.suggestion.type === 'play' ? '★' : '▼'; + color = this.suggestion.type === 'play' ? '#ffd35a' : '#ff9a7a'; + } + } + c.mark.setText(mark).setColor(color).setVisible(!!mark && v.faceUp); + if (v.chip != null) c.chip.setText(String(v.chip)).setVisible(true); else c.chip.setVisible(false); + const playable = mine && this.playableSources?.has(v.card.id) && this.settings.hints; + c.glow.setVisible(this.selected?.id === v.card.id || !!playable); + c.glow.setTint(this.selected?.id === v.card.id ? 0xffd35a : 0x7cf0a0).setAlpha(this.selected?.id === v.card.id ? 1 : 0.55); + } + + afterLayout() { + this.drawSlabs(); + this.updateBadges(); + this.gs.buildPiles.forEach((_, b) => { + const need = nextRequired(this.gs, b); + this.needTxt[b].setText(need > 12 ? '' : `needs ${need}`); + }); + this.drawTxt.setText(this.gs.drawPile.length ? `${this.gs.drawPile.length} to draw` : 'empty'); + this.drawTargets(); + } + + drawSlabs() { + const g = this.slabG; + g.clear(); + const stack = (base, n, k) => { + if (n <= 1) return; + const lift = Math.min(10, (n - 1) * 0.3) * k; + const layers = Math.max(1, Math.min(7, Math.ceil(lift / 1.5))); + for (let j = 0; j < layers; j++) { + const p = { ...base, y: base.y - (lift * j) / layers }; + const { sx, sy } = poseScale(p.s, p.rot, p.q ?? SQ); + g.fillStyle(j % 2 ? 0xf3ece0 : 0xd9d0c0, 1); + const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => { + const x = a * (CARD_W / 2) * sx, y = b * (CARD_H / 2) * sy; + return { x: p.x + x * Math.cos(p.rot) - y * Math.sin(p.rot), y: p.y + x * Math.sin(p.rot) + y * Math.cos(p.rot) }; + }); + g.fillPoints(pts, true); + g.lineStyle(1, 0x000000, 0.28); + g.strokePoints(pts, true); + } + }; + stack(this.L.draw, this.gs.drawPile.length, this.L.draw.s); + stack(this.L.completed, this.gs.completedPile.length, this.L.completed.s); + this.gs.buildPiles.forEach((pile, b) => stack(this.L.builds[b], pile.length, this.L.builds[b].s)); + for (const p of this.gs.players) stack(stockBase(this.L, p.seat), p.stock.length, this.L.seats[p.seat].k); + } + + updateBadges() { + for (let s = 0; s < this.playerCount; s++) { + const b = this.badges[s]; + const n = this.gs.players[s].stock.length; + b.t.setText(String(n)).setColor(n <= 3 ? '#ffb15a' : COLORS.textHex); + const danger = n <= 3 && n > 0 && !isGameDone(this.gs); + if (danger && !b.tw) { b.glow.setAlpha(0.5); b.tw = this.tweens.add({ targets: b.glow, alpha: 0.05, scale: 1.25, duration: 520, yoyo: true, repeat: -1 }); } + else if (!danger && b.tw) { b.tw.stop(); b.tw = null; b.glow.setAlpha(0).setScale(1); } + if (b.last != null && n < b.last && this.mode !== 'deal') this.tweens.add({ targets: b.c, scale: 1.25, duration: 90, yoyo: true }); + b.last = n; + } + } + + updatePlates() { + if (!this.gs) return; + const gs = this.gs; + for (let s = 0; s < this.playerCount; s++) { + const pl = this.plates[s]; + const p = gs.players[s]; + pl.scoreTxt.setText(gs.target > 0 ? `${gs.scores[s] + (this.plateTally?.[s] ?? 0)}` : `${this.gamesWon(s)} won`); + pl.infoTxt.setText(`Stock ${p.stock.length}`).setColor(p.stock.length <= 3 ? '#ffb15a' : COLORS.goldHex); + const top = stockTop(gs, s); + pl.statusTxt.setText(top ? `shows ${top.value === 'wild' ? '★' : top.value}` : '').setColor('#e8d6b0'); + this.setPlateActive(s, !isGameDone(gs) && gs.currentPlayer === s && (this.mode === 'human' || this.mode === 'ai')); + } + } + + // ── Targets ───────────────────────────────────────────────────────────────── + // Where the selected / dragged card can go: build piles (if it fits) and, + // for a hand card, your own discard piles (ends the turn). + targetsFor(sel) { + const out = { builds: [], discards: [] }; + if (!sel || !this.canAct()) return out; + const card = this.sourceCard(0, sel.source, sel.sourceIdx); + if (!card) return out; + for (let b = 0; b < BUILD_PILE_COUNT; b++) if (canPlayOnBuild(this.gs, card, b)) out.builds.push(b); + if (sel.source === 'hand') for (let d = 0; d < DISCARD_PILE_COUNT; d++) out.discards.push(d); + return out; + } + + drawTargets(hover = null) { + const g = this.targetG; + g.clear(); + const sel = this.dragState?.sel ?? this.selected; + if (!sel) return; + const t = this.targetsFor(sel); + 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); + }; + for (const b of t.builds) box(this.buildRect(b), 0x7cf0a0, hover?.type === 'build' && hover.idx === b); + for (const d of t.discards) box(discardRect(this.L, 0, d, this.gs.players[0].discards[d].length, 8), 0x6cc4ff, hover?.type === 'discard' && hover.idx === d); + } + + buildRect(b, pad = 12) { + const p = buildPose(this.L, b, this.gs.buildPiles[b].length); + const hw = (CARD_W / 2) * p.s + pad, hh = (CARD_H / 2) * p.s * SQ + pad; + return { x0: p.x - hw, x1: p.x + hw, y0: p.y - hh, y1: p.y + hh }; + } + + // ── Dock ──────────────────────────────────────────────────────────────────── + canAct() { return this.mode === 'human' && !this.modal && !this.paused && this.gs?.currentPlayer === 0 && !isGameDone(this.gs); } + + updateDock() { + if (!this.gs || !this.prompt) return; + if (this.mode === 'deal') { this.setDock('Counting out the stock piles…'); return; } + if (this.mode === 'ending' || this.mode === 'summary') { this.setDock('Game over.'); return; } + if (this.mode !== 'human') { this.setDock(`${this.nameForSeat(this.gs.currentPlayer)} is playing…`); return; } + const plays = getValidPlays(this.gs); + const st = stockTop(this.gs, 0); + const stockPlay = plays.some(p => p.source === 'stock'); + let prompt; + if (stockPlay) prompt = `Your stock ${st.value === 'wild' ? 'Wild' : st.value} can go on a build pile — play it!`; + else if (plays.length) prompt = `Play onto the build piles. Your stock needs ${st ? (st.value === 'wild' ? 'any pile' : `a pile at ${st.value - 1}`) : '—'}. End by discarding.`; + else prompt = 'Nothing fits — put a hand card on one of your four piles to end your turn.'; + const sug = suggestAction(this.gs); + if (!this.gs.players[0].hand.length) { + this.setDock(plays.length ? 'Your hand is empty and the draw pile is out — play what you can, then pass.' : 'Nothing left to play — pass.', [ + { label: 'Best play (B)', act: () => this.playSuggestion(), enabled: sug?.type === 'play' }, + { label: 'Pass', act: () => this.passTurn(), hot: !plays.length }, + ]); return; } - - const youWon = winnerSeat === 0; - const name = winnerSeat === 0 - ? (auth.user?.username ?? 'You') - : (this.opponents[winnerSeat - 1]?.name ?? `Player ${winnerSeat + 1}`); - const msg = youWon ? `You win!` : `${name} wins!`; - this.setStatus(msg); - - // Emotion reactions for AI portraits - for (let s = 1; s < this.gs.players.length; s++) { - const p = this.opponentPortraits[s]; - if (!p) continue; - if (winnerSeat === s) p.playEmotion?.('win'); - else p.playEmotion?.('loss'); - } - - this.recordHistory(youWon); - this.showGameOverPanel(msg, youWon, name, youWon - ? 'You emptied your stock first.' - : `${name} emptied their stock first.`); + this.setDock(prompt, [ + { label: 'Best play (B)', act: () => this.playSuggestion(), enabled: sug?.type === 'play', hot: stockPlay }, + { label: 'Auto-discard (X)', act: () => this.autoDiscard(), enabled: this.gs.players[0].hand.length > 0, hot: !plays.length }, + ]); } - showGameOverPanel(msg, youWon, name, subtitle) { - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.65) - .setInteractive().setDepth(D.modal); - const panelW = 720; - const panelH = 320; - this.add.rectangle(CX, CY, panelW, panelH, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - this.add.text(CX, CY - panelH / 2 + 56, msg, { - fontFamily: 'Righteous', fontSize: '42px', - color: youWon ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal); - this.add.text(CX, CY - 10, subtitle, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modal); - - new Button(this, CX - 130, CY + panelH / 2 - 60, 'Play again', () => { - overlay.destroy(); - this.scene.restart({ - game: this.gameDef, opponents: this.opponents, - playfield: this.playfield, cardBack: this.cardBack, - }); - }, { width: 220, fontSize: 22 }).setDepth(D.modal); - new Button(this, CX + 130, CY + panelH / 2 - 60, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 220, fontSize: 22 }).setDepth(D.modal); + // ── Human actions ─────────────────────────────────────────────────────────── + sortHand() { + if (!this.gs || this.settings.sort === 'manual') return; + this.gs.players[0].hand.sort(byValue); } - async recordHistory(youWon) { - try { - const localStockRemaining = this.gs.players[0].stock.length; - const opponentScores = []; - for (let s = 1; s < this.gs.players.length; s++) { - opponentScores.push(this.gs.players[s].stock.length); + play(sel, buildIdx) { + if (!this.canAct() || !sel) return false; + const card = this.sourceCard(0, sel.source, sel.sourceIdx); + if (!card || !canPlayOnBuild(this.gs, card, buildIdx)) { if (card) this.nudge(card.id); return false; } + const play = { source: sel.source, sourceIdx: sel.sourceIdx, buildIdx, asNumber: card.value === 'wild' ? nextRequired(this.gs, buildIdx) : undefined }; + const next = applyPlay(this.gs, play); + if (next === this.gs) return false; + this.selected = null; + this.commit(next); + playSound(this, SFX.CARD_PLACE); + if (isGameDone(this.gs)) { this.onGameOver(); return true; } + if (isPlayerStuck(this.gs)) this.advance(); + return true; + } + + discard(handIdx, discardIdx) { + if (!this.canAct()) return false; + const next = applyDiscard(this.gs, handIdx, discardIdx); + if (next === this.gs) return false; + this.selected = null; + this.commit(next); + playSound(this, SFX.CARD_PLACE); + this.mode = 'idle'; + this.targetG.clear(); + this.updateDock(); + this.time.delayedCall(280, () => this.advance()); + return true; + } + + passTurn() { + if (!this.canAct()) return; + this.commit(applyAutoPass(this.gs)); + this.mode = 'idle'; + this.updateDock(); + this.time.delayedCall(280, () => this.advance()); + } + + // Double-click: the best build pile for this card (fullest pile that takes it). + autoPlay(sel) { + const t = this.targetsFor(sel); + if (!t.builds.length) { const c = this.sourceCard(0, sel.source, sel.sourceIdx); if (c) this.nudge(c.id); return; } + const sug = suggestAction(this.gs); + let b = t.builds.slice().sort((x, y) => this.gs.buildPiles[y].length - this.gs.buildPiles[x].length)[0]; + if (sug?.type === 'play' && sug.source === sel.source && sug.sourceIdx === sel.sourceIdx && t.builds.includes(sug.buildIdx)) b = sug.buildIdx; + this.play(sel, b); + } + + playSuggestion() { + if (!this.canAct()) return; + const a = suggestAction(this.gs); + if (a?.type !== 'play') return; + this.play({ source: a.source, sourceIdx: a.sourceIdx }, a.buildIdx); + } + + autoDiscard() { + if (!this.canAct() || !this.gs.players[0].hand.length) return; + const a = suggestAction(this.gs); + if (a?.type === 'discard') { this.discard(a.handIdx, a.discardIdx); return; } + // plays are still open — check before ending the turn early + const d = suggestDiscard(this.gs); + this.confirm('End your turn now?', 'You still have cards that could go on a build pile.', 'Discard anyway', () => this.discard(d.handIdx, d.discardIdx), { no: 'Keep playing' }); + } + + // ── Input ────────────────────────────────────────────────────────────────── + setupInput() { + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + } + + heldIds() { return this.gs.players[0].hand.map(c => c.id); } + + liftFor(ids) { return (i) => (ids[i] === this.selected?.id ? 40 : ids[i] === this.hoverId ? 22 : 0); } + + // What the human pressed: a source card, a build pile or a discard pile. + hitTest(pt) { + if (!this.gs) return null; + const ids = this.heldIds(); + const hi = fanHit(this.L.seats[0].fan, ids.length, pt, this.liftFor(ids)); + if (hi >= 0) return { kind: 'source', sel: { source: 'hand', sourceIdx: hi, id: ids[hi] } }; + const p = this.gs.players[0]; + if (p.stock.length && inPose(pt, stockPose(this.L, 0, p.stock.length), 6)) return { kind: 'source', sel: { source: 'stock', sourceIdx: 0, id: stockTop(this.gs, 0).id } }; + for (let b = 0; b < BUILD_PILE_COUNT; b++) if (inRect(pt, this.buildRect(b, 6))) return { kind: 'build', idx: b }; + for (let d = 0; d < DISCARD_PILE_COUNT; d++) { + const n = p.discards[d].length; + if (inRect(pt, discardRect(this.L, 0, d, n, 4))) { + return n ? { kind: 'discardPile', idx: d, sel: { source: 'discard', sourceIdx: d, id: discardTop(this.gs, 0, d).id } } : { kind: 'discardPile', idx: d }; } - // Score = (STOCK_SIZE - cards remaining in your stock); higher = better - const score = STOCK_SIZE - localStockRemaining; - await api.post('/history/single-player', { - slug: 'skipbo', - score, - opponentScores, - result: youWon ? 'win' : 'loss', - }); - } catch (err) { - console.warn('[skipbo] failed to record history', err); + } + return null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState) return; + if (this.overUI(over)) return; + if (this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const hit = this.hitTest(pointer); + if (!hit) { if (this.selected) { this.selected = null; this.layout({ duration: 140 }); } return; } + // with a hand card selected, a discard pile is a target, not a source + if (hit.kind === 'discardPile' && this.selected?.source === 'hand' && this.canAct()) { + const idx = this.gs.players[0].hand.findIndex(c => c.id === this.selected.id); + if (idx >= 0) this.discard(idx, hit.idx); + return; + } + if (hit.kind === 'build') { if (this.selected) this.play(this.selected, hit.idx); return; } + if (hit.sel) this.potentialDrag = { sel: hit.sel, x: pointer.x, y: pointer.y }; + } + + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.x, dy = pointer.y - this.potentialDrag.y; + if (dx * dx + dy * dy > 64) this.startDrag(pointer); + return; + } + if (pointer.isDown || this.modal || !this.gs || this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const ids = this.heldIds(); + const hi = fanHit(this.L.seats[0].fan, ids.length, pointer, this.liftFor(ids)); + const id = hi >= 0 ? ids[hi] : null; + if (id !== this.hoverId) { this.hoverId = id; this.layout({ duration: 120 }); } + const h = id == null ? this.hitTest(pointer) : null; + this.input.setDefaultCursor(id != null || h?.sel || (h && this.selected) ? 'pointer' : 'default'); + } + + onPointerUp() { + if (this.dragState) { this.endDrag(); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + if (!this.canAct()) { + if (this.mode === 'ai') this.floatText({ x: CX, y: 860 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); + return; + } + const now = this.time.now; + const dbl = this.lastClick.id === pd.sel.id && now - this.lastClick.at < DOUBLE_CLICK_MS; + this.lastClick = { id: pd.sel.id, at: now }; + if (dbl) { this.lastClick = { id: null, at: 0 }; this.autoPlay(pd.sel); return; } + this.selected = this.selected?.id === pd.sel.id ? null : pd.sel; + if (this.selected) playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + } + + startDrag(pointer) { + const pd = this.potentialDrag; + this.potentialDrag = null; + const c = this.sprites.get(pd.sel.id); + if (!c) return; + c._tw?.stop(); + c._tw = null; + c.setDepth(D.drag); + this.dragState = { id: pd.sel.id, sel: pd.sel, offX: c.pose.x - pd.x, offY: c.pose.y - pd.y, sprite: c, target: null, previewKey: '' }; + this.selected = null; + this.hoverId = null; + this.input.setDefaultCursor('grabbing'); + this.updateDrag(pointer); + } + + dropTargetAt(pt, sel) { + const t = this.targetsFor(sel); + for (const b of t.builds) if (inRect(pt, this.buildRect(b, 26))) return { type: 'build', idx: b }; + for (const d of t.discards) if (inRect(pt, discardRect(this.L, 0, d, this.gs.players[0].discards[d].length, 14))) return { type: 'discard', idx: d }; + if (sel.source === 'hand') { + const ids = this.heldIds(); + if (inRect(pt, fanZone(this.L.seats[0].fan, ids.length))) return { type: 'hand', at: fanInsertIndex(this.L.seats[0].fan, ids.length, pt.x) }; + } + return null; + } + + updateDrag(pointer) { + const ds = this.dragState; + const x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const t = Math.max(0, Math.min(1, (y - 600) / 360)); + const s = this.L.builds[0].s + (1 - this.L.builds[0].s) * t; + this.applyPose(ds.sprite, { x, y, rot: 0, s, q: SQ + (1 - SQ) * t }, 1); + ds.target = this.dropTargetAt(pointer, ds.sel); + const order = ds.target?.type === 'hand' ? CardTableScene.reorderPreview(this.heldIds(), ds.id, ds.target.at) : null; + const key = order ? order.join(',') : ''; + if (key !== ds.previewKey) { + ds.previewKey = key; + this.dragPreview = order; + this.layout({ duration: 150 }); + } + if (order) { + const idx = order.indexOf(ds.id); + this.drawDropSlot(handPose(this.L, 0, idx, order.length), D.hand + idx * 0.01 - 0.004); + } else this.drawDropSlot(null); + this.drawTargets(ds.target); + } + + cancelDrag() { + if (!this.dragState) return; + this.dragState = null; + this.dragPreview = null; + this.drawDropSlot(null); + this.targetG?.clear(); + this.layout(); + } + + endDrag() { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.drawDropSlot(null); + const t = ds.target; + this.dragPreview = null; + if (t?.type === 'hand') { + const order = CardTableScene.reorderPreview(this.heldIds(), ds.id, t.at); + const hand = this.gs.players[0].hand; + const byId = new Map(hand.map(c => [c.id, c])); + const changed = order.join(',') !== hand.map(c => c.id).join(','); + hand.splice(0, hand.length, ...order.map(id => byId.get(id))); + if (changed && this.settings.sort !== 'manual') { this.settings.sort = 'manual'; this.saveSettings(); this.refreshSortButtons(); } + this.layout(); + return; + } + if (t?.type === 'build' && this.play(ds.sel, t.idx)) return; + if (t?.type === 'discard' && ds.sel.source === 'hand') { + const idx = this.gs.players[0].hand.findIndex(c => c.id === ds.id); + if (idx >= 0 && this.discard(idx, t.idx)) return; + } + this.layout(); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) { if (this.selected) { this.selected = null; this.layout(); } 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 === 'h') { this.flashHint(); return; } + if (!this.canAct()) return; + if (k === 'b') this.playSuggestion(); + else if (k === 'x') this.autoDiscard(); + else if (k >= '1' && k <= '5') { + const i = Number(k) - 1; + const c = this.gs.players[0].hand[i]; + if (c) { this.selected = this.selected?.id === c.id ? null : { source: 'hand', sourceIdx: i, id: c.id }; this.layout({ duration: 140 }); } + } else if (e.code === 'Space') { + const st = stockTop(this.gs, 0); + if (st) { this.selected = this.selected?.id === st.id ? null : { source: 'stock', sourceIdx: 0, id: st.id }; this.layout({ duration: 140 }); } } } - // ── HUD helpers ───────────────────────────────────────────────────────── + flashHint() { + if (!this.gs || this.mode !== 'human') return; + const a = suggestAction(this.gs); + let text = 'Nothing to do.'; + let id = null; + if (a?.type === 'play') { + const c = this.sourceCard(0, a.source, a.sourceIdx); + id = c?.id; + text = `Play your ${a.source === 'stock' ? 'stock card' : a.source === 'discard' ? `discard-pile ${c.value === 'wild' ? 'Wild' : c.value}` : (c.value === 'wild' ? 'Wild' : c.value)} on build pile ${a.buildIdx + 1}.`; + } else if (a?.type === 'discard') { + const c = this.gs.players[0].hand[a.handIdx]; + id = c?.id; + text = `Discard the ${c.value === 'wild' ? 'Wild' : c.value} onto pile ${a.discardIdx + 1}.`; + } + this.floatText({ x: CX, y: 860 }, text, '#7cf0a0', { size: 22, ms: 2200, rise: 20 }); + if (id != null) this.flashGlow(id, 0x7cf0a0, { delay: 0, hold: 900 }); + } - setStatus(s) { - if (this.statusText) this.statusText.setText(s); + // ── Menus ─────────────────────────────────────────────────────────────────── + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Score sheet', act: () => { this.closeModal(); this.openScorePad({ readOnly: true }); } }, + { label: 'How to play', act: () => { this.closeModal(); this.openRules(); } }, + { label: 'New game', ghost: true, act: () => this.confirm('Start a new game?', 'This game will be thrown out.', 'New game', () => this.restart()) }, + { label: 'Leave table', ghost: true, act: () => this.onLeave() }, + ]); + } + + openSettings(onDone = null) { + const s = this.settings; + this.openSettingsModal([ + { label: 'Opponent pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } }, + { label: 'Hints (glow playable · ★ best · ▼ toss)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; this.layout(); } }, + { label: 'Stock pile size', options: [[10, '10'], [20, '20'], [30, '30']], get: () => s.stock, set: (v) => { s.stock = v; } }, + { label: 'Play', options: [[0, 'One game'], [MATCH_TARGET, 'Match to 500']], get: () => s.target, set: (v) => { s.target = v; } }, + { label: 'Hand order', options: [['number', '1·2·3'], ['manual', 'Mine']], get: () => s.sort, set: (v) => { s.sort = v; this.refreshSortButtons(); this.sortHand(); this.layout(); } }, + ], { note: 'Stock size and match play start with the next game.', onDone }); + } + + openRules() { + const h = 600; + this.openModal({ w: 900, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 54, 'How to play', { fontFamily: 'Righteous', fontSize: '38px', color: COLORS.goldHex }); + const lines = [ + 'Empty your stock pile first to win. Only its top card is ever face up.', + 'The four build piles in the middle go 1, 2, 3 … 12, then clear away.', + 'Wilds count as whatever number a pile needs.', + 'On your turn, play from your hand, your stock top, or the top of', + ' any of your four discard piles — as many plays as you like.', + 'Empty your hand mid-turn? You draw five fresh cards.', + 'End your turn by putting one hand card on one of your discard piles.', + 'Tip: stack your discard piles high-to-low so they play back in order.', + 'Match play: the winner scores 25 + 5 for every card left in other stocks.', + ]; + lines.forEach((l, i) => this.addToModal(this.add.text(CX - 400, top + 122 + i * 40, l, { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1))); + this.modalButton(CX, top + h - 46, 'Back to the table', () => this.closeModal(), { width: 280, height: 46, fontSize: 18 }); + } + + onLeave() { + const inGame = this.history.length > 0 || this.mode === 'human' || this.mode === 'ai'; + if (!inGame || this.gs?.phase === 'gameover') { this.scene.start('GameMenu'); return; } + this.confirm('Leave this game?', 'Your progress will be lost.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay' }); + } + + restart() { + this.closeModal(); + this.scene.restart({ game: this.gameDef, opponents: this.opponents, playfield: this.playfield, cardBack: this.cardBack }); + } + + openScorePad({ result = null, readOnly = false } = {}) { + if (!this.gs) return; + const gs = this.gs; + const match = gs.target > 0; + const over = gs.phase === 'gameover' && !readOnly; + let title; + if (readOnly) title = match ? `Score sheet — first to ${gs.target}` : 'Games at this table'; + else if (result?.winner === -1) title = 'Nobody can move — a draw'; + else if (over && match) title = gs.matchWinner === 0 ? 'You win the match!' : `${this.nameForSeat(gs.matchWinner)} wins the match!`; + else title = result.winner === 0 ? 'You emptied your stock — you win!' : `${this.nameForSeat(result.winner)} wins the game`; + const rows = gs.players.map((p, s) => ({ + seat: s, color: SEAT_COLORS[s], name: this.shortName(s, 14), + cells: this.history.map(h => (h.winner === s ? { text: match ? `+${h.points}` : 'won', color: '#1c3f8f', mark: '★', markColor: '#b8231f' } : { text: h.stocks ? `${h.stocks[s]} left` : '—', color: '#8a7e66' })), + extra: `${p.stock.length}`, + total: match ? gs.scores[s] : this.gamesWon(s), + totalColor: '#22201a', + circled: (over && match && s === gs.matchWinner) || (!match && !readOnly && result?.winner === s), + })); + const buttons = []; + if (readOnly) buttons.push({ label: 'Back to the table', act: () => this.closeModal() }); + else { + buttons.push(over ? { label: 'Play again', act: () => this.playAgain(), hot: true } : { label: 'Next game', act: () => this.nextGame(), hot: true }); + buttons.push({ label: 'Settings', ghost: true, act: () => { this.closeModal(); this.openSettings(() => this.openScorePad({ result })); } }); + buttons.push({ label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }); + } + this.openScorePadModal({ + title, titleColor: (result?.winner === 0 && !readOnly) ? '#b8231f' : '#22201a', + sub: match ? 'Winner scores 25 + 5 per card left in the other stock piles' : 'First to empty their stock pile wins', + columns: this.history.map((_, i) => `G${i + 1}`), + rows, extraLabel: 'Stock', writeLast: !!result, buttons, readOnly, + onEnter: !readOnly ? (over ? () => this.playAgain() : () => this.nextGame()) : null, + }); + } + + async nextGame() { + this.closeModal(); + if (this.mode !== 'summary') return; + this.mode = 'deal'; + this.updateDock(); + await this.sweepCards({ ...this.L.draw }); + if (!this.alive()) return; + this.gs = startNextGame(this.gs); + this.startGame(); + } + + // A single game that's over: keep the table's tally and deal again. + async playAgain() { + this.closeModal(); + if (this.gs.target > 0) { this.restart(); return; } + this.mode = 'deal'; + await this.sweepCards({ ...this.L.draw }); + if (!this.alive()) return; + this.gs = createInitialState({ + playerCount: this.playerCount, stockSize: this.settings.stock, target: this.settings.target, + startingPlayer: (this.gs.startingPlayer + 1) % this.playerCount, + }); + this.startGame(); + } + + // ── Game over ────────────────────────────────────────────────────────────── + async onGameOver() { + if (this.mode === 'ending' || this.mode === 'summary') return; + this.mode = 'ending'; + this.turnToken++; + this.cancelDrag(); + this.selected = null; + this.potentialDrag = null; + this.input.setDefaultCursor('default'); + for (let s = 1; s < this.playerCount; s++) this.handRest(s, 300); + this.updateDock(); + this.layout(); + const r = this.gs.gameResult; + await this.wait(600); + if (!this.alive()) return; + if (r.winner >= 0) { + this.stamp(r.winner === 0 ? 'You win!' : `${this.shortName(r.winner, 14)} wins!`, { x: CX, y: CY - 30 }, SEAT_HEX[r.winner], { size: 92, sub: 'Stock pile cleared', hold: 1200 }); + this.plateStamp(r.winner, 'WINS!', '#ffd35a', 0); + playSound(this, r.winner === 0 ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(s === r.winner ? 'win' : 'loss'); + } else { + this.stamp('Stalemate', { x: CX, y: CY - 30 }, '#f2ead8', { size: 80, hold: 1100 }); + } + await this.wait(1500); + if (!this.alive()) return; + this.revealAll = true; + this.layout({ duration: 360 }); + if (this.gs.target > 0 && r.winner >= 0) await this.countStocks(r); + if (!this.alive()) return; + this.history.push({ winner: r.winner, points: r.points, stocks: this.gs.players.map(p => p.stock.length) }); + this.updatePlates(); + if (this.gs.phase === 'gameover' && r.winner >= 0) { + this.recordResult('skipbo', { + score: this.gs.target > 0 ? this.gs.scores[0] : this.gs.players[0].stock.length, + opponentScores: this.gs.players.slice(1).map((p, i) => (this.gs.target > 0 ? this.gs.scores[i + 1] : p.stock.length)), + won: (this.gs.target > 0 ? this.gs.matchWinner : r.winner) === 0, + }); + } + this.mode = 'summary'; + this.openScorePad({ result: r }); + } + + // Match play: tally the winner's 25 + 5 per card left in the other stocks. + async countStocks(r) { + const pl = this.plates[r.winner]; + const t = pl.tallyTxt; + let tally = 25; + t.setText('+25').setVisible(true).setAlpha(1).setColor(SEAT_HEX[r.winner]); + this.plateTally = this.gs.players.map(() => 0); + this.plateTally[r.winner] = -r.points; + this.updatePlates(); + await this.wait(500); + for (const p of this.gs.players) { + if (p.seat === r.winner || !p.stock.length) continue; + const badge = this.badges[p.seat]; + for (let i = 0; i < p.stock.length; i++) { + this.time.delayedCall(i * 60, () => { + tally += 5; + t.setText(`+${tally}`); + pl.scoreTxt.setText(`${this.gs.scores[r.winner] - r.points + tally}`); + if (i % 2 === 0) playSoundEx(this, SFX.CARD_PLACE, { volume: 0.3, rate: 1.2 }); + }); + } + this.tweens.add({ targets: badge.c, scale: 1.3, duration: 120, yoyo: true, repeat: 2 }); + await this.wait(p.stock.length * 60 + 300); + if (!this.alive()) return; + } + t.setText(`+${r.points}`); + this.plateTally = null; + this.updatePlates(); + await this.wait(700); + this.tweens.add({ targets: t, alpha: 0, duration: 300 }); } } diff --git a/src/games/skipbo/SkipBoLogic.js b/src/games/skipbo/SkipBoLogic.js index 35ba28b..f82ee85 100644 --- a/src/games/skipbo/SkipBoLogic.js +++ b/src/games/skipbo/SkipBoLogic.js @@ -11,6 +11,10 @@ // of your 4 discard piles. Wilds are any value. Turn ends by discarding // one hand card onto any of your 4 personal discard piles (your choice). // - First to empty their stock wins. +// +// Match play (optional, state.target > 0): the winner of each game scores 25 +// plus 5 for every card left in the other stock piles; first to the target +// (official: 500) wins. target 0 = a single game. // ── Card factory ──────────────────────────────────────────────────────────── // @@ -54,13 +58,16 @@ function shuffle(arr, seed) { } export const STOCK_SIZE = 30; +export const MATCH_TARGET = 500; export const HAND_SIZE = 5; export const BUILD_PILE_COUNT = 4; export const DISCARD_PILE_COUNT = 4; // ── State construction ────────────────────────────────────────────────────── -export function createInitialState({ playerCount, seed, startingPlayer = 0 } = {}) { +export function createInitialState({ + playerCount, seed, startingPlayer = 0, stockSize = STOCK_SIZE, target = 0, scores = null, gameNum = 1, +} = {}) { if (playerCount < 2 || playerCount > 4) { throw new Error(`Skip-Bo supports 2..4 players, got ${playerCount}`); } @@ -69,7 +76,7 @@ export function createInitialState({ playerCount, seed, startingPlayer = 0 } = { const players = []; for (let i = 0; i < playerCount; i++) { - const stock = deck.splice(0, STOCK_SIZE); + const stock = deck.splice(0, stockSize); players.push({ seat: i, stock, @@ -89,6 +96,14 @@ export function createInitialState({ playerCount, seed, startingPlayer = 0 } = { seed: seed ?? null, turnCount: 0, consecutiveStuckTurns: 0, + startingPlayer, + stockSize, + target, + scores: scores ? scores.slice() : new Array(playerCount).fill(0), + gameNum, + gameResult: null, + matchWinner: null, + log: [], }; // Top of every stock starts face-up. We model "face-up" implicitly: stock @@ -106,6 +121,7 @@ function recycleCompletedIntoDraw(state) { for (const c of recycled) c.playedAs = null; shuffle(recycled, state.seed ? state.seed + state.turnCount : undefined); state.drawPile.push(...recycled); + state.log?.push({ kind: 'recycle', count: recycled.length }); } function drawOne(state) { @@ -116,11 +132,14 @@ function drawOne(state) { function refillHand(state, seat) { const p = state.players[seat]; + let n = 0; while (p.hand.length < HAND_SIZE) { const c = drawOne(state); if (!c) break; p.hand.push(c); + n++; } + if (n) state.log?.push({ kind: 'refill', seat, count: n }); } // ── Cloning ───────────────────────────────────────────────────────────────── @@ -142,6 +161,14 @@ export function cloneState(state) { seed: state.seed, turnCount: state.turnCount, consecutiveStuckTurns: state.consecutiveStuckTurns, + startingPlayer: state.startingPlayer, + stockSize: state.stockSize, + target: state.target, + scores: state.scores.slice(), + gameNum: state.gameNum, + gameResult: state.gameResult ? { ...state.gameResult, perSeat: state.gameResult.perSeat.slice() } : null, + matchWinner: state.matchWinner, + log: state.log.map((e) => ({ ...e })), }; } @@ -264,6 +291,8 @@ export function applyPlay(state, play) { } next.buildPiles[play.buildIdx].push(card); + const entry = { kind: 'play', seat, source: play.source, sourceIdx: play.sourceIdx, buildIdx: play.buildIdx, cardId: card.id, value: card.playedAs ?? card.value, wild: card.value === 'wild' }; + next.log.push(entry); // If pile completed (top is 12), recycle it const topVal = buildPileTopValue(next, play.buildIdx); @@ -271,12 +300,13 @@ export function applyPlay(state, play) { const cleared = next.buildPiles[play.buildIdx].splice(0); for (const c of cleared) c.playedAs = null; next.completedPile.push(...cleared); + entry.completed = true; + next.log.push({ kind: 'complete', buildIdx: play.buildIdx, count: cleared.length }); } // Check for win first — stock empty after a stock play wins immediately if (player.stock.length === 0) { - next.phase = 'gameover'; - next.winner = seat; + finishGame(next, seat); return next; } @@ -302,6 +332,7 @@ export function applyDiscard(state, handIdx, discardIdx) { const [card] = player.hand.splice(handIdx, 1); card.playedAs = null; player.discards[discardIdx].push(card); + next.log.push({ kind: 'discard', seat, discardIdx, cardId: card.id }); // Advance turn next.currentPlayer = (seat + 1) % next.players.length; @@ -339,8 +370,11 @@ export function applyAutoPass(state) { if (next.consecutiveStuckTurns >= next.players.length) { next.phase = 'gameover'; next.winner = -1; // draw + next.gameResult = { winner: -1, points: 0, perSeat: next.players.map(() => 0) }; + if (next.target > 0) next.phase = 'handOver'; return next; } + next.log.push({ kind: 'stuck', seat: next.currentPlayer }); next.currentPlayer = (next.currentPlayer + 1) % next.players.length; next.turnCount += 1; @@ -348,6 +382,48 @@ export function applyAutoPass(state) { return next; } +// The winner scores 25 + 5 per card left in the other stocks (match play). +function finishGame(next, seat) { + const perSeat = next.players.map((p) => (p.seat === seat ? 0 : p.stock.length * 5)); + const points = 25 + perSeat.reduce((a, b) => a + b, 0); + next.winner = seat; + next.scores[seat] += points; + next.gameResult = { winner: seat, points, perSeat }; + next.log.push({ kind: 'win', seat, points }); + if (next.target > 0 && next.scores[seat] < next.target) { + next.phase = 'handOver'; + } else { + next.phase = 'gameover'; + next.matchWinner = seat; + } +} + +/** Deal the next game of a match (scores carry over, the first player rotates). */ +export function startNextGame(state) { + if (state.phase !== 'handOver') return state; + const n = state.players.length; + return createInitialState({ + playerCount: n, + seed: state.seed == null ? undefined : state.seed + state.gameNum * 131, + startingPlayer: (state.startingPlayer + 1) % n, + stockSize: state.stockSize, + target: state.target, + scores: state.scores, + gameNum: state.gameNum + 1, + }); +} + +export function isGameDone(state) { + return state.phase === 'gameover' || state.phase === 'handOver'; +} + +/** Every card in the game (for conservation checks). */ +export function countCards(state) { + let n = state.drawPile.length + state.completedPile.length + state.buildPiles.reduce((a, p) => a + p.length, 0); + for (const p of state.players) n += p.stock.length + p.hand.length + p.discards.reduce((a, d) => a + d.length, 0); + return n; +} + // Convenience for UI — count cards in each pile per seat for the always-on // HUD. The top stock card is always visible separately. export function snapshotCounts(state) { diff --git a/src/games/skipbo/SkipBoTable.js b/src/games/skipbo/SkipBoTable.js new file mode 100644 index 0000000..823fdf2 --- /dev/null +++ b/src/games/skipbo/SkipBoTable.js @@ -0,0 +1,184 @@ +// Skip-Bo table layout — Phaser-free so tools/verifySkipBo.js can test it. +// +// Grandma's mahogany dining table (burgundy cloth, lace runner) on the shared +// card-table kit. Every player has a tableau in front of them — their stock +// pile and four discard piles, fanned TOWARD the owner so every card in a +// discard pile can be read — plus a hand (the human's is the big fan along +// the bottom; opponents hold five small backs at the table's edge). The +// middle holds the draw pile, the four shared build piles and the +// completed-piles stack. +// +// Seats (logic seats clockwise from the human's left): +// 2 human · across 3 human · far corners 4 human · left · across · right +// +// Tableau template in the owner's frame (px at scale 1): x along the row, +// y toward the owner. + +import { + makeTable, CARD_W, CARD_H, fanPose, fanPoint, rot2, poseScale, HUMAN_PLATE, PLATE, +} from '../../ui/cardtable/TableGeometry.js'; + +export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 }; +export const T = makeTable(VIEW, { shape: 'rect', corner: 0.17, feltK: 0.935, faceH: 34 }); +export const SQ = VIEW.squash; + +export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c]; +export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c']; + +export const TEMPLATE = { + 0: { stock: -240, discards: [-96, 16, 128, 240], fan: 30, fanMax: 150 }, + opp: { stock: -240, discards: [-96, 16, 128, 240], fan: 22, fanMax: 84 }, +}; + +const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 96, curve: 2.2, tilt: 0.05, q: 1, maxSpan: 600, maxDrop: 30, maxTilt: 0.14 }; +const oppFan = (x, y, rot, k = 0.42) => ({ x, y, rot, k, spread: 30, curve: 0.6, tilt: 0.05, q: 1, maxSpan: 200, maxDrop: 8, maxTilt: 0.12 }); + +const SEATS = { + 2: [ + { uv: { u: 0, v: 0.67 }, rot: 0, k: 0.92, fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { uv: { u: 0, v: 0.21 }, rot: Math.PI, k: 0.72, fan: oppFan(960, 62, Math.PI), plate: { x: 1420, y: 86 } }, + ], + 3: [ + { uv: { u: 0, v: 0.67 }, rot: 0, k: 0.92, fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { uv: { u: -0.43, v: 0.21 }, rot: Math.PI - 0.16, k: 0.58, fan: oppFan(560, 66, Math.PI - 0.1, 0.4), plate: { x: 190, y: 150 } }, + { uv: { u: 0.43, v: 0.21 }, rot: Math.PI + 0.16, k: 0.58, fan: oppFan(1360, 66, Math.PI + 0.1, 0.4), plate: { x: 1730, y: 150 } }, + ], + 4: [ + { uv: { u: 0, v: 0.67 }, rot: 0, k: 0.92, fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { uv: { u: -0.74, v: 0.46 }, rot: Math.PI / 2, k: 0.5, fan: oppFan(70, 470, Math.PI / 2, 0.4), plate: { x: 190, y: 150 } }, + { uv: { u: 0, v: 0.19 }, rot: Math.PI, k: 0.56, fan: oppFan(960, 58, Math.PI, 0.38), plate: { x: 1400, y: 86 } }, + { uv: { u: 0.74, v: 0.46 }, rot: -Math.PI / 2, k: 0.5, fan: oppFan(1850, 470, -Math.PI / 2, 0.4), plate: { x: 1730, y: 150 } }, + ], +}; + +// The middle row: draw pile · four build piles · completed piles. +export const CENTRE = { v: 0.4, k: 0.78, xs: [-292, -150, -50, 50, 150, 292] }; + +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(`Skip-Bo layout supports 2..4 players, got ${playerCount}`); + const seats = defs.map((d, seat) => { + const a = T.P.project(d.uv.u, d.uv.v); + // screen px per unit of v at the anchor (for mapping owner-frame depth onto the table) + const ydv = (T.P.project(d.uv.u, d.uv.v + 0.0005).y - T.P.project(d.uv.u, d.uv.v - 0.0005).y) / 0.001; + return { + seat, anchor: { x: a.x, y: a.y }, uv: d.uv, sA: a.s, ydv, rot: d.rot, k: d.k, + tpl: seat === 0 ? TEMPLATE[0] : TEMPLATE.opp, fan: d.fan, plate: d.plate, + }; + }); + const c = T.P.project(0, CENTRE.v); + const slot = (dx) => ({ x: c.x + dx, y: c.y, rot: 0, s: CENTRE.k, q: SQ }); + const L = { + playerCount, seats, + draw: slot(CENTRE.xs[0]), + builds: CENTRE.xs.slice(1, 5).map(slot), + completed: slot(CENTRE.xs[5]), + }; + cache.set(playerCount, L); + return L; +} + +// Owner-frame offsets live ON the table: (dx along the owner's row, dy toward +// the owner) in flat px at scale k are turned by the seat's orientation, mapped +// into table space (u, v) and projected — so a side player's row runs along +// the table's receding edge and its far cards come out smaller. +function seatUV(st, dx, dy) { + const f = rot2(dx, dy, st.rot); + return { + u: st.uv.u + (f.x * st.k) / (T.view.halfW * st.sA), + v: st.uv.v + (f.y * st.k * SQ) / st.ydv, + }; +} + +/** Owner-frame offset (flat px at k = 1) → screen point (with its depth scale). */ +export function seatPoint(L, seat, dx, dy) { + const st = L.seats[seat]; + const { u, v } = seatUV(st, dx, dy); + const p = T.P.project(u, v); + return { x: p.x, y: p.y, s: p.s }; +} + +function pose(L, seat, dx, dy) { + const st = L.seats[seat]; + const p = seatPoint(L, seat, dx, dy); + return { x: p.x, y: p.y, rot: st.rot, s: st.k * (p.s / st.sA), q: SQ }; +} + +export function stackLift(n, k = 1) { + return Math.min(10, Math.max(0, n - 1) * 0.3) * k; +} + +export function fanStep(tpl, n) { + if (n <= 1) return tpl.fan; + return Math.min(tpl.fan, tpl.fanMax / (n - 1)); +} + +export function stockPose(L, seat, n) { + const st = L.seats[seat]; + const base = pose(L, seat, st.tpl.stock, 0); + return { ...base, y: base.y - stackLift(n, st.k) }; +} + +export function stockBase(L, seat) { return pose(L, seat, L.seats[seat].tpl.stock, 0); } + +/** Card i (0 = bottom) of discard pile d holding n cards — fanned toward the owner. */ +export function discardPose(L, seat, d, i, n) { + const t = L.seats[seat].tpl; + return pose(L, seat, t.discards[d], i * fanStep(t, n)); +} + +export function discardBase(L, seat, d) { return pose(L, seat, L.seats[seat].tpl.discards[d], 0); } + +/** Screen rect of a discard pile's whole fan (for the human's drop targets). */ +export function discardRect(L, seat, d, n, pad = 10) { + const a = discardPose(L, seat, d, 0, Math.max(1, n)); + const b = discardPose(L, seat, d, Math.max(0, n - 1), Math.max(1, n)); + const { sx, sy } = poseScale(a.s, a.rot, a.q); + const hw = (CARD_W / 2) * sx, hh = (CARD_H / 2) * sy; + return { x0: Math.min(a.x, b.x) - hw - pad, x1: Math.max(a.x, b.x) + hw + pad, y0: Math.min(a.y, b.y) - hh - pad, y1: Math.max(a.y, b.y) + hh + pad }; +} + +export function buildPose(L, b, n) { + const base = L.builds[b]; + return { ...base, y: base.y - stackLift(n, base.s) }; +} + +export function pilePose(base, n) { return { ...base, y: base.y - stackLift(n, base.s) }; } + +export const handPose = (L, seat, i, n, lift = 0) => fanPose(L.seats[seat].fan, i, n, lift); + +/** Stock-count badge above a seat's stock pile. */ +export function stockBadge(L, seat) { + const t = L.seats[seat].tpl; + return seatPoint(L, seat, t.stock, -CARD_H / 2 - (seat === 0 ? 24 : 30)); +} + +/** Ghost hand rest point (between the opponent's hand and their tableau). */ +export function handHome(L, seat) { + const f = L.seats[seat].fan; + const p = fanPoint(f, 0, -CARD_H * 1.05); + return { ...p, rot: f.rot, k: L.seats[seat].k }; +} + +/** Placemat (owner frame, px at k = 1) around a tableau. */ +export function placematRect(seat) { + const t = seat === 0 ? TEMPLATE[0] : TEMPLATE.opp; + return { x0: t.stock - CARD_W / 2 - 30, x1: t.discards[3] + CARD_W / 2 + 30, y0: -CARD_H / 2 - 34, y1: CARD_H / 2 + t.fanMax + 22 }; +} + +export function placematCorners(L, seat) { + const r = placematRect(seat); + return [seatPoint(L, seat, r.x0, r.y0), seatPoint(L, seat, r.x1, r.y0), seatPoint(L, seat, r.x1, r.y1), seatPoint(L, seat, r.x0, r.y1)]; +} + +export function spotFor(L, seat) { + const st = L.seats[seat]; + const c = seatPoint(L, seat, 0, st.tpl.fanMax * 0.35); + const side = Math.abs(Math.sin(st.rot)) > 0.7; + const len = 760 * st.k, dep = 520 * st.k; + return side ? { x: c.x, y: c.y, w: dep, h: len } : { x: c.x, y: c.y, w: len, h: dep }; +} + +export { PLATE }; diff --git a/src/games/uno/UnoAI.js b/src/games/uno/UnoAI.js index cb148c1..8d9ec90 100644 --- a/src/games/uno/UnoAI.js +++ b/src/games/uno/UnoAI.js @@ -1,19 +1,31 @@ -// Uno AI — pure decision function. Mirrors the gofish/GoFishAI.js shape: -// one stateless function per decision, no scene state. +// Uno AI — pure decision functions, scaled by skill (1..5). No scene state. // -// Returns one of: +// chooseAction(state, seat, { skill, rng }) returns one of: // { kind: 'play', cardId, chosenColor? } -// { kind: 'draw' } -// { kind: 'playDrawn' } — after a draw, when the drawn card is playable -// { kind: 'passDrawn' } — keep the drawn card, end turn +// { kind: 'draw' } — also "take the stacked penalty" +// { kind: 'playDrawn' } | { kind: 'passDrawn' } // { kind: 'chooseColor', color } — phase === 'choosingColor' -// { kind: 'challenge', doChallenge: bool } — phase === 'challengeWindow' +// { kind: 'challenge', doChallenge } | { kind: 'stack', cardId } — challengeWindow +// +// Skill: +// 1-2 noisy card choice, random-ish colours, sometimes draws with a play in +// hand, challenges on a whim, forgets to call UNO, slow to catch others. +// 3 solid heuristics (save wilds, punish a near-empty next player). +// 4-5 reads the table: plays into colours the next player has been drawing +// on, challenges a Wild +4 by the odds, always calls UNO, quick catches. -import { UNO_COLORS } from './UnoDeck.js'; -import { legalPlays, isLegalPlay } from './UnoLogic.js'; +import { UNO_COLORS, buildDeck } from './UnoDeck.js'; +import { legalPlays, isLegalPlay, isBluff, stackableWild4, nextSeat } from './UnoLogic.js'; +import { clampSkill } from '../../ui/cardtable/AITiming.js'; const KIND_PRIORITY_LATE = { wild4: 9, draw2: 8, skip: 7, reverse: 6, wild: 5, number: 1 }; const KIND_PRIORITY_EARLY = { number: 5, reverse: 4, skip: 3, draw2: 2, wild: 1, wild4: 0 }; +const NOISE = { 1: 40, 2: 20, 3: 4, 4: 1, 5: 0.3 }; +const LAZY_DRAW = { 1: 0.12, 2: 0.05, 3: 0, 4: 0, 5: 0 }; + +export const UNO_CALL_CHANCE = { 1: 0.6, 2: 0.75, 3: 0.9, 4: 0.97, 5: 1 }; +export const CATCH_CHANCE = { 1: 0.25, 2: 0.4, 3: 0.6, 4: 0.8, 5: 0.92 }; +export const CATCH_DELAY = { 1: 1500, 2: 1200, 3: 900, 4: 650, 5: 450 }; function colorTally(hand) { const tally = { r: 0, y: 0, g: 0, b: 0 }; @@ -21,113 +33,151 @@ function colorTally(hand) { return tally; } -/** Pick the color the AI has the most of (ties broken by deck order). */ -function bestColor(hand) { +/** Colours a seat has recently drawn on (probably can't follow them). */ +export function likelyVoids(state, seat) { + const out = new Set(); + // walk the log back to this seat's last play; draws since then name voids + for (let i = state.log.length - 1; i >= 0; i--) { + const e = state.log[i]; + if (e.seat !== seat) continue; + if (e.kind === 'play') break; + if (e.kind === 'draw' && e.color) out.add(e.color); + } + return out; +} + +function bestColor(state, seat, hand, skill, rand) { + if (skill <= 1 && rand() < 0.5) return UNO_COLORS[Math.floor(rand() * 4)]; const t = colorTally(hand); - let best = UNO_COLORS[0]; - for (const c of UNO_COLORS) if (t[c] > t[best]) best = c; + const voids = skill >= 4 ? likelyVoids(state, nextSeat(state, seat, 1)) : new Set(); + let best = UNO_COLORS[0], bestScore = -Infinity; + for (const c of UNO_COLORS) { + const s = t[c] * 10 + (voids.has(c) ? 6 : 0); + if (s > bestScore) { bestScore = s; best = c; } + } return best; } -/** - * Score a candidate play. Higher is better. Considers: - * - Punish dangerous opponents (next opponent with small hand → favor action cards) - * - Save high-value cards for late game otherwise - * - Prefer playing cards whose color matches the rest of our hand - * - Never voluntarily play Wild +4 when a non-wild play exists - */ -function scoreCandidate(state, seat, card, hand) { - const N = state.players.length; - const nextSeat = ((seat + state.direction) % N + N) % N; - const nextHandSize = state.players[nextSeat].hand.length; +function scoreCandidate(state, seat, card, hand, skill, rand) { + const nxt = nextSeat(state, seat, 1); + const nextHandSize = state.players[nxt].hand.length; const dangerous = nextHandSize <= 2; - const ourHandSize = hand.length; - const earlyGame = ourHandSize >= 5; - + const earlyGame = hand.length >= 5; let score; - if (dangerous) { - score = (KIND_PRIORITY_LATE[card.kind] ?? 0) * 10; - } else if (earlyGame) { - score = (KIND_PRIORITY_EARLY[card.kind] ?? 0) * 10; - } else { - // Mid-game: neutral preference for non-wild plays. - score = card.kind === 'number' ? 30 : (card.kind === 'wild4' ? 5 : 25); - } - - // Bonus: playing this card leaves us with more of our dominant color in hand. - if (card.color !== 'w') { - const tally = colorTally(hand); - score += tally[card.color]; // staying in our strongest color is good - } - - // Penalty: blow a Wild +4 unless it's a strong move (dangerous opponent - // OR we're stuck with this Wild +4 long-term). + if (dangerous && skill >= 2) score = (KIND_PRIORITY_LATE[card.kind] ?? 0) * 10; + else if (earlyGame) score = (KIND_PRIORITY_EARLY[card.kind] ?? 0) * 10; + else score = card.kind === 'number' ? 30 : (card.kind === 'wild4' ? 5 : 25); + if (card.color !== 'w') score += colorTally(hand)[card.color]; if (card.kind === 'wild4' && !dangerous) score -= 25; - - // Small randomization for variety. - score += Math.random() * 0.5; + if (isBluff(state, card, hand)) score -= dangerous ? (skill >= 4 ? 5 : 30) : (skill >= 4 ? 30 : 45); + if (card.kind === 'wild' && skill >= 3 && !dangerous) score -= 8; + if (skill >= 4 && card.color !== 'w' && likelyVoids(state, nxt).has(card.color)) score += 12; + // heads-up, Skip / Reverse / Draw 2 all mean "go again" — chain them + if (skill >= 4 && state.players.length === 2 && (card.kind === 'skip' || card.kind === 'reverse' || card.kind === 'draw2')) score += 30; + // shed points late in a scored game + if (skill >= 4 && hand.length <= 3) score += card.points / 10; + score += rand() * NOISE[skill]; return score; } /** - * Pick the single best action for the current phase. + * Chance (0..1) that the Wild +4 player still holds a card of the colour that + * was in play, from card counts alone — judged from `viewerSeat`'s point of + * view (cards outside the viewer's hand and the discard pile are unseen; + * hypergeometric over the player's hand size). */ -export function chooseAction(state, seat) { +export function holdOdds(state, viewerSeat) { + const pw = state.pendingWild4; + if (!pw || !pw.priorColor) return 0.5; + const seen = new Set([...state.players[viewerSeat].hand.map(c => c.id), ...state.discardPile.map(c => c.id)]); + const all = buildDeck(); + const unseen = all.filter(c => !seen.has(c.id)); + const U = unseen.length; + const k = unseen.filter(c => c.color === pw.priorColor).length; + const h = state.players[pw.playerSeat].hand.length; + let none = 1; + for (let i = 0; i < h; i++) none *= Math.max(0, U - k - i) / Math.max(1, U - i); + return 1 - none; +} + +// How often a player holding the colour bluffs a +4 anyway, relative to +// playing it honestly. Players rarely bluff, so a +4 is weak evidence. +export const BLUFF_RATE = 0.25; + +/** + * Chance (0..1) that challenging the pending Wild +4 wins: Bayes over the + * card-count odds that they held the colour and how rarely people bluff. + */ +export function challengeOdds(state, viewerSeat) { + const h = holdOdds(state, viewerSeat); + const bluff = h * BLUFF_RATE; + return bluff / (bluff + (1 - h)); +} + +export function chooseAction(state, seat, opts = {}) { + const skill = clampSkill(opts.skill); + const rand = opts.rng ?? Math.random; + const me = state.players[seat]; + if (state.phase === 'choosingColor') { - return { kind: 'chooseColor', color: bestColor(state.players[seat].hand) }; + return { kind: 'chooseColor', color: bestColor(state, seat, me.hand, skill, rand) }; } if (state.phase === 'challengeWindow') { - // We are the challenger. Without perfect information we challenge only - // when there's reasonable suspicion. Heuristics: - // - The +4 player has many cards (likely had a color match). - // - Our own hand is small (the gamble is lower-risk). const pw = state.pendingWild4; if (!pw) return { kind: 'challenge', doChallenge: false }; - const playerHandSize = state.players[pw.playerSeat].hand.length; - const ourHandSize = state.players[seat].hand.length; - const suspicious = playerHandSize >= 4; - const lowRisk = ourHandSize <= 3; - const doChallenge = suspicious && (lowRisk || Math.random() < 0.4); + const stack = stackableWild4(state, seat); + if (stack.length && (skill >= 2 || rand() < 0.6)) return { kind: 'stack', cardId: stack[0] }; + let doChallenge; + if (skill <= 2) doChallenge = rand() < 0.3; + else if (skill === 3) { + const suspicious = state.players[pw.playerSeat].hand.length >= 4; + doChallenge = suspicious && (me.hand.length <= 3 || rand() < 0.4); + } else { + // challenge when the expected draw is lower: lose → count + 2, accept → count + const p = challengeOdds(state, seat); + const count = pw.count ?? 4; + const threshold = skill === 5 ? 2 / (count + 2) : 0.5; + doChallenge = p > threshold; + } return { kind: 'challenge', doChallenge }; } if (state.phase === 'mustPlayDrawn') { - // We just drew. Pass unless the drawn card is genuinely playable and - // playing it is better than holding it for later. - const me = state.players[seat]; const drawn = state.pendingDrawn; - if (!drawn) return { kind: 'passDrawn' }; - if (!isLegalPlay(state, drawn, me.hand)) return { kind: 'passDrawn' }; - // Always play numbers / actions when we can. For wilds, play them only if - // we have no other play (we already drew, so we're not blowing tempo). - return { kind: 'playDrawn' }; + if (!drawn || !isLegalPlay(state, drawn, me.hand)) return { kind: 'passDrawn' }; + if (skill <= 1 && rand() < 0.15) return { kind: 'passDrawn' }; + return { kind: 'playDrawn', chosenColor: drawn.color === 'w' ? bestColor(state, seat, me.hand.filter(c => c.id !== drawn.id), skill, rand) : undefined }; } if (state.phase !== 'play') return { kind: 'draw' }; - const me = state.players[seat]; const legalIds = legalPlays(state, seat); if (legalIds.length === 0) return { kind: 'draw' }; + if (state.pendingDraw) { + // stacked Draw 2 coming our way: pass it on if we can + if (skill >= 2 || rand() < 0.7) return { kind: 'play', cardId: legalIds[0] }; + return { kind: 'draw' }; + } + if (rand() < LAZY_DRAW[skill]) return { kind: 'draw' }; - let bestCard = null; - let bestScore = -Infinity; + let bestCard = null, bestScore = -Infinity; for (const id of legalIds) { const card = me.hand.find((c) => c.id === id); if (!card) continue; - const s = scoreCandidate(state, seat, card, me.hand); - if (s > bestScore) { - bestScore = s; - bestCard = card; - } + if (skill <= 2 && isBluff(state, card, me.hand)) continue; // beginners play it straight + const s = scoreCandidate(state, seat, card, me.hand, skill, rand); + if (s > bestScore) { bestScore = s; bestCard = card; } } - if (!bestCard) return { kind: 'draw' }; const result = { kind: 'play', cardId: bestCard.id }; - if (bestCard.color === 'w') { - // Pre-compute the color we'll choose so the scene can animate atomically. - // The engine still calls applyChooseColor separately. - result.chosenColor = bestColor(me.hand.filter((c) => c.id !== bestCard.id)); - } + if (bestCard.color === 'w') result.chosenColor = bestColor(state, seat, me.hand.filter((c) => c.id !== bestCard.id), skill, rand); return result; } + +/** The play a sharp player would make — used for the human's hint. */ +export function suggestPlay(state, seat) { + if (state.phase !== 'play' || state.currentPlayer !== seat) return null; + const a = chooseAction(state, seat, { skill: 5, rng: () => 0.5 }); + return a.kind === 'play' ? a.cardId : null; +} diff --git a/src/games/uno/UnoArt.js b/src/games/uno/UnoArt.js new file mode 100644 index 0000000..31d0917 --- /dev/null +++ b/src/games/uno/UnoArt.js @@ -0,0 +1,445 @@ +// Uno art — baked once into canvas textures (no image files). Original card +// design (no Mattel layout): a colour panel with 90s confetti, a white diamond +// badge holding the symbol, corner indices and a small colour-blind shape. +// +// uno-cards atlas at 2× — frames '-<0..9>', '-skip', '-reverse', +// '-draw2', 'wild', 'wild4', and 'wild-' / 'wild4-' +// (a played wild ringed in its chosen colour) +// uno-back neon 90s card back +// uno-table- the kitchen: striped wallpaper, gingham tablecloth draped +// over the table, pile spots + +import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js'; +import { + bakeRoom, canvas, rr, poly, mix, noisePattern, lampPool, checks, pileSpot, CARD_TEX, +} from '../../ui/cardtable/TableArt.js'; +import { W, H } from '../../ui/cardtable/TableGeometry.js'; +import { T, layoutFor } from './UnoTable.js'; + +const CW = CARD_TEX.W, CH = CARD_TEX.H; +const FONT = 'Righteous, "Arial Black", sans-serif'; + +export const UNO_HEX = { r: '#e0392f', y: '#f4bb22', g: '#2f9e55', b: '#2b67d6' }; +const HI = { r: '#ff6a55', y: '#ffd95a', g: '#5ccc7f', b: '#5d92f2' }; +const LO = { r: '#8d1a14', y: '#a87106', g: '#155c2d', b: '#163c86' }; +export const COLOR_NAME = { r: 'Red', y: 'Yellow', g: 'Green', b: 'Blue' }; +const WHITE = '#fffaf0'; + +// deterministic sprinkles per frame +function seeded(key) { + let h = 2166136261; + for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 16777619); + return () => { h = Math.imul(h ^ (h >>> 15), 2246822507); h = Math.imul(h ^ (h >>> 13), 3266489909); return ((h ^= h >>> 16) >>> 0) / 4294967296; }; +} + +function confetti(ctx, x, y, key, palette, alpha = 0.22) { + const rand = seeded(key); + ctx.save(); + ctx.globalAlpha = alpha; + for (let i = 0; i < 26; i++) { + const px = x + 16 + rand() * (CW - 32), py = y + 16 + rand() * (CH - 32); + ctx.strokeStyle = ctx.fillStyle = palette[i % palette.length]; + const t = i % 3; + ctx.save(); + ctx.translate(px, py); + ctx.rotate(rand() * Math.PI * 2); + if (t === 0) { // squiggle + ctx.lineWidth = 4; + ctx.beginPath(); + ctx.moveTo(-12, 0); + ctx.bezierCurveTo(-6, -8, 0, 8, 6, 0); + ctx.bezierCurveTo(9, -4, 11, -4, 13, 0); + ctx.stroke(); + } else if (t === 1) { // triangle + ctx.beginPath(); ctx.moveTo(0, -7); ctx.lineTo(7, 6); ctx.lineTo(-7, 6); ctx.closePath(); ctx.fill(); + } else { // dot + ctx.beginPath(); ctx.arc(0, 0, 4, 0, Math.PI * 2); ctx.fill(); + } + ctx.restore(); + } + ctx.restore(); +} + +function base(ctx, x, y) { + rr(ctx, x + 2, y + 2, CW - 4, CH - 4, 18); + ctx.fillStyle = WHITE; + ctx.fill(); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(30,20,10,0.5)'; + ctx.stroke(); +} + +function panel(ctx, x, y, fillFn) { + ctx.save(); + rr(ctx, x + 12, y + 12, CW - 24, CH - 24, 13); + ctx.clip(); + fillFn(); + ctx.restore(); +} + +// Colour-blind helpers: one shape per colour. +function shape(ctx, c, cx, cy, r, fill) { + ctx.fillStyle = fill; + ctx.beginPath(); + if (c === 'r') ctx.arc(cx, cy, r, 0, Math.PI * 2); + else if (c === 'b') ctx.rect(cx - r * 0.88, cy - r * 0.88, r * 1.76, r * 1.76); + else if (c === 'y') { 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(); +} + +function diamond(ctx, cx, cy, size, fill, stroke) { + ctx.save(); + ctx.translate(cx, cy); + ctx.rotate(Math.PI / 4); + ctx.shadowColor = 'rgba(0,0,0,0.35)'; + ctx.shadowBlur = 8; + ctx.shadowOffsetY = 3; + rr(ctx, -size / 2, -size / 2, size, size, 16); + ctx.fillStyle = fill; + ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.lineWidth = 4; + ctx.strokeStyle = stroke; + ctx.stroke(); + ctx.restore(); +} + +// ── Symbols (drawn centred at 0,0; `s` = scale) ────────────────────────────── +function symSkip(ctx, s, color, outline) { + ctx.save(); + ctx.scale(s, s); + ctx.lineCap = 'round'; + for (const [w, c] of [[16, outline], [10, color]]) { + ctx.lineWidth = w; + ctx.strokeStyle = c; + ctx.beginPath(); ctx.arc(0, 0, 26, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(-18, 18); ctx.lineTo(18, -18); ctx.stroke(); + } + ctx.restore(); +} + +// Two bold arrows chasing each other round a circle: one over the top +// heading right, one under the bottom heading left, each with a solid +// arrowhead aimed along the circle and a clear gap before the next shaft. +function symReverse(ctx, s, color, outline) { + ctx.save(); + ctx.scale(s, s); + const R = 21, a0 = Math.PI * 1.02, a1 = Math.PI * 1.66; + const arrow = (rot, shaftW, fill, edge) => { + ctx.save(); + ctx.rotate(rot); + ctx.lineCap = 'round'; + ctx.lineWidth = shaftW; + ctx.strokeStyle = fill; + ctx.beginPath(); + ctx.arc(0, 0, R, a0, a1); + ctx.stroke(); + // arrowhead at the end of the arc, pointing clockwise along it + const hx = Math.cos(a1) * R, hy = Math.sin(a1) * R; + const tx = -Math.sin(a1), ty = Math.cos(a1); // clockwise tangent + const nx = Math.cos(a1), ny = Math.sin(a1); // radial + const len = 17, half = 12; + ctx.beginPath(); + ctx.moveTo(hx + tx * len, hy + ty * len); + ctx.lineTo(hx + nx * half - tx * 3, hy + ny * half - ty * 3); + ctx.lineTo(hx - nx * half - tx * 3, hy - ny * half - ty * 3); + ctx.closePath(); + ctx.fillStyle = fill; + ctx.fill(); + if (edge) { + ctx.lineJoin = 'round'; + ctx.lineWidth = edge; + ctx.strokeStyle = fill; + ctx.stroke(); + } + ctx.restore(); + }; + // dark outline pass, then the colour pass on top + arrow(0, 17, outline, 7); + arrow(Math.PI, 17, outline, 7); + arrow(0, 9, color, 0); + arrow(Math.PI, 9, color, 0); + ctx.restore(); +} + +function symText(ctx, text, size, color, outline, underline = false) { + ctx.font = `${size}px ${FONT}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.lineWidth = Math.max(4, size / 11); + ctx.strokeStyle = outline; + ctx.strokeText(text, 0, 3); + ctx.fillStyle = color; + ctx.fillText(text, 0, 3); + if (underline) { + ctx.fillStyle = color; + ctx.fillRect(-size * 0.22, size * 0.42, size * 0.44, Math.max(4, size / 14)); + } +} + +function symDraw2(ctx, s, color, outline) { + ctx.save(); + ctx.scale(s, s); + for (const [dx, dy] of [[-9, 6], [9, -6]]) { + rr(ctx, dx - 15, dy - 21, 30, 42, 6); + ctx.fillStyle = color; + ctx.fill(); + ctx.lineWidth = 4; + ctx.strokeStyle = outline; + ctx.stroke(); + } + ctx.restore(); +} + +function pinwheel(ctx, r) { + const order = ['r', 'y', 'g', 'b']; + for (let i = 0; i < 4; i++) { + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.arc(0, 0, r, -Math.PI / 2 + (i * Math.PI) / 2, -Math.PI / 2 + ((i + 1) * Math.PI) / 2); + ctx.closePath(); + ctx.fillStyle = UNO_HEX[order[i]]; + ctx.fill(); + } + ctx.lineWidth = 4; + ctx.strokeStyle = WHITE; + ctx.beginPath(); ctx.arc(0, 0, r, 0, Math.PI * 2); ctx.stroke(); +} + +function corners(ctx, x, y, draw) { + ctx.save(); ctx.translate(x + 40, y + 46); draw(); ctx.restore(); + ctx.save(); ctx.translate(x + CW - 40, y + CH - 46); ctx.rotate(Math.PI); draw(); ctx.restore(); +} + +function drawColored(ctx, x, y, c, kind, value) { + base(ctx, x, y); + panel(ctx, x, y, () => { + const g = ctx.createLinearGradient(x, y, x + CW, y + CH); + g.addColorStop(0, HI[c]); g.addColorStop(0.55, UNO_HEX[c]); g.addColorStop(1, LO[c]); + ctx.fillStyle = g; + ctx.fillRect(x, y, CW, CH); + confetti(ctx, x, y, `${c}${kind}${value}`, [WHITE, LO[c], HI[c]]); + }); + const cx = x + CW / 2, cy = y + CH / 2; + diamond(ctx, cx, cy, 104, WHITE, LO[c]); + ctx.save(); + ctx.translate(cx, cy); + if (kind === 'number') symText(ctx, String(value), 92, UNO_HEX[c], LO[c], value === 6 || value === 9); + else if (kind === 'skip') symSkip(ctx, 1.35, UNO_HEX[c], LO[c]); + else if (kind === 'reverse') symReverse(ctx, 1.35, UNO_HEX[c], LO[c]); + else { symDraw2(ctx, 1.05, UNO_HEX[c], LO[c]); } + ctx.restore(); + if (kind === 'draw2') { ctx.save(); ctx.translate(cx + 2, cy + 60); symText(ctx, '+2', 40, WHITE, LO[c]); ctx.restore(); } + corners(ctx, x, y, () => { + if (kind === 'number') symText(ctx, String(value), 44, WHITE, LO[c], value === 6 || value === 9); + else if (kind === 'skip') symSkip(ctx, 0.55, WHITE, LO[c]); + else if (kind === 'reverse') symReverse(ctx, 0.7, WHITE, LO[c]); + else symText(ctx, '+2', 34, WHITE, LO[c]); + shape(ctx, c, 0, 40, 8, WHITE); + }); + gloss(ctx, x, y); +} + +function drawWild(ctx, x, y, four, chosen = null) { + base(ctx, x, y); + panel(ctx, x, y, () => { + const g = ctx.createLinearGradient(x, y, x, y + CH); + g.addColorStop(0, '#2c2438'); g.addColorStop(1, '#0f0b16'); + ctx.fillStyle = g; + ctx.fillRect(x, y, CW, CH); + confetti(ctx, x, y, four ? 'wild4' : 'wild', [UNO_HEX.r, UNO_HEX.y, UNO_HEX.g, UNO_HEX.b], 0.55); + }); + if (chosen) { + rr(ctx, x + 14, y + 14, CW - 28, CH - 28, 12); + ctx.lineWidth = 12; + ctx.strokeStyle = UNO_HEX[chosen]; + ctx.stroke(); + } + const cx = x + CW / 2, cy = y + CH / 2; + diamond(ctx, cx, cy, 104, '#1b1424', WHITE); + ctx.save(); + ctx.translate(cx, cy); + pinwheel(ctx, 42); + ctx.restore(); + if (four) { ctx.save(); ctx.translate(cx, cy + 62); symText(ctx, '+4', 44, WHITE, '#1b1424'); ctx.restore(); } + corners(ctx, x, y, () => { + if (four) symText(ctx, '+4', 34, WHITE, '#1b1424'); + else { ctx.save(); pinwheel(ctx, 15); ctx.restore(); } + if (chosen) shape(ctx, chosen, 0, 40, 9, UNO_HEX[chosen]); + }); + gloss(ctx, x, y); +} + +function gloss(ctx, x, y) { + ctx.save(); + rr(ctx, x + 12, y + 12, CW - 24, CH - 24, 13); + ctx.clip(); + const gl = ctx.createLinearGradient(x, y, x + CW * 0.6, y + CH * 0.5); + gl.addColorStop(0, 'rgba(255,255,255,0.26)'); + 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(); +} + +export function frameKey(card) { + if (card.kind === 'wild' || card.kind === 'wild4') return card.chosenColor ? `${card.kind}-${card.chosenColor}` : card.kind; + if (card.kind === 'number') return `${card.color}-${card.value}`; + return `${card.color}-${card.kind}`; +} + +function bakeCards(scene) { + const frames = []; + for (const c of ['r', 'y', 'g', 'b']) { + for (let v = 0; v <= 9; v++) frames.push([`${c}-${v}`, (ctx, x, y) => drawColored(ctx, x, y, c, 'number', v)]); + for (const k of ['skip', 'reverse', 'draw2']) frames.push([`${c}-${k}`, (ctx, x, y) => drawColored(ctx, x, y, c, k)]); + } + frames.push(['wild', (ctx, x, y) => drawWild(ctx, x, y, false)], ['wild4', (ctx, x, y) => drawWild(ctx, x, y, true)]); + for (const c of ['r', 'y', 'g', 'b']) { + frames.push([`wild-${c}`, (ctx, x, y) => drawWild(ctx, x, y, false, c)], [`wild4-${c}`, (ctx, x, y) => drawWild(ctx, x, y, true, c)]); + } + const cols = 10, rows = Math.ceil(frames.length / cols); + const cv = canvas(cols * CW, rows * CH); + const ctx = cv.getContext('2d'); + frames.forEach(([, draw], i) => draw(ctx, (i % cols) * CW, Math.floor(i / cols) * CH)); + const tex = scene.textures.addCanvas('uno-cards', cv); + frames.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, 18); + ctx.fillStyle = WHITE; + ctx.fill(); + ctx.save(); + rr(ctx, 12, 12, CW - 24, CH - 24, 13); + ctx.clip(); + const g = ctx.createLinearGradient(0, 0, CW, CH); + g.addColorStop(0, '#2a1650'); g.addColorStop(1, '#120a2a'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, CW, CH); + confetti(ctx, 0, 0, 'back', ['#25e0d0', '#ff4fb4', '#ffd84a', '#7cf05c'], 0.75); + ctx.restore(); + ctx.save(); + ctx.translate(CW / 2, CH / 2); + ctx.rotate(-0.25); + ctx.beginPath(); ctx.arc(0, 0, 50, 0, Math.PI * 2); ctx.fillStyle = '#120a2a'; ctx.fill(); + pinwheel(ctx, 40); + ctx.restore(); + rr(ctx, 2, 2, CW - 4, CH - 4, 18); + ctx.lineWidth = 2.5; + ctx.strokeStyle = 'rgba(0,0,0,0.6)'; + ctx.stroke(); + scene.textures.addCanvas('uno-back', c); +} + +// ── The kitchen ───────────────────────────────────────────────────────────── +function wall(ctx) { + ctx.fillStyle = '#efe4cc'; + ctx.fillRect(0, 0, W, H); + // sage pinstripe wallpaper + for (let x = 0; x < W; x += 46) { + ctx.fillStyle = 'rgba(122,150,112,0.32)'; + ctx.fillRect(x, 0, 16, H); + ctx.fillStyle = 'rgba(122,150,112,0.18)'; + ctx.fillRect(x + 24, 0, 3, H); + } + // floral border strip near the ceiling + ctx.fillStyle = '#8a4a3a'; + ctx.fillRect(0, 18, W, 30); + for (let x = 12; x < W; x += 44) { + ctx.fillStyle = '#f2c4a0'; + ctx.beginPath(); ctx.arc(x, 33, 7, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#7a9a6e'; + ctx.beginPath(); ctx.ellipse(x + 14, 33, 8, 3.5, 0.5, 0, Math.PI * 2); ctx.fill(); + } + ctx.fillStyle = 'rgba(0,0,0,0.25)'; + ctx.fillRect(0, 48, W, 2); + ctx.fillStyle = noisePattern(ctx, 128, 14); + ctx.fillRect(0, 0, W, H); + // warm pendant light, dark corners + const lamp = ctx.createRadialGradient(W / 2, 140, 40, W / 2, 300, 1150); + lamp.addColorStop(0, 'rgba(255,214,150,0.2)'); + lamp.addColorStop(0.5, 'rgba(120,80,40,0.1)'); + lamp.addColorStop(1, 'rgba(20,10,4,0.62)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); +} + +const CLOTH = ['#a87e52', '#d2ae82', '#f1e2c6']; // tan gingham: both / one / neither +const CLOTH_DRAPE = '#c49c70'; + +function drape(ctx, Tb) { + // the tablecloth hangs over the edge: folds + a scalloped hem + const top = Tb.outline(1.0, 30); + const bottom = top.map(p => ({ x: p.x, y: p.y + Tb.faceH * p.s })); + poly(ctx, [...top, ...bottom.slice().reverse()]); + ctx.fillStyle = CLOTH_DRAPE; + ctx.fill(); + ctx.save(); + poly(ctx, [...top, ...bottom.slice().reverse()]); + ctx.clip(); + for (let x = 0; x < W; x += 6) { + const f = Math.sin(x / 23) * 0.5 + Math.sin(x / 9.5) * 0.18; + ctx.fillStyle = f > 0 ? `rgba(255,240,215,${f * 0.22})` : `rgba(40,20,6,${-f * 0.34})`; + ctx.fillRect(x, 0, 6, H); + } + // faint gingham stripes on the drape + for (let x = 0; x < W; x += 44) { ctx.fillStyle = 'rgba(120,80,40,0.16)'; ctx.fillRect(x, 0, 22, H); } + const shade = ctx.createLinearGradient(0, 600, 0, H); + shade.addColorStop(0, 'rgba(0,0,0,0)'); + shade.addColorStop(1, 'rgba(0,0,0,0.35)'); + ctx.fillStyle = shade; + ctx.fillRect(0, 0, W, H); + ctx.restore(); + // scalloped hem with a cream trim + const midY = Tb.P.project(0, 0.5).y; + for (let i = 0; i < bottom.length - 1; i++) { + const a = bottom[i], b = bottom[i + 1]; + if (a.y < midY || b.y < midY) continue; // only the visible near half of the hem + const steps = Math.max(1, Math.round(Math.hypot(b.x - a.x, b.y - a.y) / 18)); + for (let k = 0; k < steps; k++) { + const t = (k + 0.5) / steps; + const x = a.x + (b.x - a.x) * t, y = a.y + (b.y - a.y) * t; + ctx.beginPath(); ctx.arc(x, y, 7, 0, Math.PI); ctx.fillStyle = '#f6ecd8'; ctx.fill(); + } + } +} + +function clothTop(ctx, Tb) { + checks(ctx, Tb, { cell: 0.07, colors: CLOTH, aspect: 0.58 }); + ctx.fillStyle = noisePattern(ctx, 160, 22); + ctx.fillRect(0, 0, W, H); + // weave texture: faint fine lines + ctx.globalAlpha = 0.06; + for (let y = 0; y < H; y += 3) { ctx.fillStyle = '#3a2410'; ctx.fillRect(0, y, W, 1); } + ctx.globalAlpha = 1; + lampPool(ctx, Tb, { color: '255,222,170', alpha: 0.2, vignette: 0.48, at: { u: 0, v: 0.48 } }); + // the edge rolls over: shade the last few % of the top + for (let i = 0; i < 12; i++) { + poly(ctx, Tb.outline(Tb.feltK - i * 0.003, 18)); + ctx.lineWidth = 3; + ctx.strokeStyle = `rgba(60,35,12,${0.22 * (1 - i / 12)})`; + ctx.stroke(); + } +} + +function spots(ctx) { + const L = layoutFor(2); + pileSpot(ctx, L.deck, 'DRAW', { color: '90,60,30', alpha: 0.5 }); + pileSpot(ctx, L.discard, 'PLAY', { color: '90,60,30', alpha: 0.5 }); +} + +export async function prepareUnoArt(scene, playerCount) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('uno-cards')) bakeCards(scene); + if (!scene.textures.exists('uno-back')) bakeBack(scene); + const key = `uno-table-${playerCount}`; + bakeRoom(scene, key, T, { wall, front: drape, top: clothTop, onTop: spots }); + return key; +} + +export { mix }; diff --git a/src/games/uno/UnoGame.js b/src/games/uno/UnoGame.js index 8ebe4ea..95f4958 100644 --- a/src/games/uno/UnoGame.js +++ b/src/games/uno/UnoGame.js @@ -1,1697 +1,1205 @@ import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; -import { Modal } from '../../ui/Modal.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { auth } from '../../services/auth.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { - createInitialState, - legalPlays, - isLegalPlay, - applyPlay, - applyChooseColor, - applyDraw, - applyPlayDrawn, - applyPassAfterDraw, - applyChallengeWild4, - isGameOver, + CardTableScene, DEPTH as D, CX, CY, COLORS, Button, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { jitterFor } from '../../ui/casino/CasinoCards.js'; +import { + CARD_W, CARD_H, inPose, fanHit, fanInsertIndex, fanZone, inRect, stackLift, DOCK, +} from '../../ui/cardtable/TableGeometry.js'; +import { UNO_CALL_CHANCE, CATCH_CHANCE, CATCH_DELAY, chooseAction, challengeOdds, suggestPlay } from './UnoAI.js'; +import { + createInitialState, startNextHand, applyPlay, applyChooseColor, applyChallengeWild4, applyStackWild4, + applyDraw, applyPlayDrawn, applyPassAfterDraw, applyCallUno, applyCatchUno, canCatchUno, + legalPlays, stackableWild4, topDiscard, nextSeat, isHandOver, isBluff, DEFAULT_TARGET, } from './UnoLogic.js'; -import { chooseAction } from './UnoAI.js'; +import { + T, SQ, SEAT_COLORS, SEAT_HEX, layoutFor, handPose, handHome, handBadge, spotFor, ringPoints, +} from './UnoTable.js'; +import { prepareUnoArt, frameKey, UNO_HEX, COLOR_NAME } from './UnoArt.js'; -// ── Layout constants ──────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; +// ─── Uno ────────────────────────────────────────────────────────────────────── +// A 90s kitchen table on the shared card-table kit (src/ui/cardtable/). +// Rules live in UnoLogic.js (pure), opponents in UnoAI.js; this file is flow, +// animation and input. Every card is a persistent sprite keyed by id. -const CARD_W = 88; -const CARD_H = 132; -const CARD_R = 10; -const HAND_SPREAD_MAX = 70; // max px between adjacent hand cards (local) -const HAND_FACEUP_MAX_W = 1300; // local hand band max width +const COLOR_INT = { r: 0xe0392f, y: 0xf4bb22, g: 0x2f9e55, b: 0x2b67d6 }; +const KIND_ORDER = { number: 0, skip: 1, reverse: 2, draw2: 3, wild: 4, wild4: 5 }; +const COLOR_ORDER = { r: 0, y: 1, g: 2, b: 3, w: 4 }; +const byColor = (a, b) => COLOR_ORDER[a.color] - COLOR_ORDER[b.color] || KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || (a.value ?? 0) - (b.value ?? 0) || a.id - b.id; +const byNumber = (a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || (a.value ?? 0) - (b.value ?? 0) || COLOR_ORDER[a.color] - COLOR_ORDER[b.color] || a.id - b.id; +const UNO_GRACE_MS = 1500; // the table pauses this long so a forgotten UNO! can be caught +const DEFAULTS = { pace: 'normal', hints: true, sort: 'color', stacking: false, drawUntil: false, target: DEFAULT_TARGET }; -const DRAW_OFFSET = -110; // x offset of draw pile from center -const DISCARD_OFFSET = 110; // x offset of discard pile from center - -const D = { - felt: -1, board: 0, card: 10, highlight: 20, - ui: 30, portrait: 35, chip: 40, banner: 60, modal: 80, modalUI: 82, -}; - -const SLOTS_USED = { - 2: ['bottom', 'top'], - 3: ['bottom', 'left', 'right'], - 4: ['bottom', 'left', 'top', 'right'], -}; - -const UNO_COLOR_HEX = { - r: 0xd32f2f, - y: 0xf9a825, - g: 0x2e7d32, - b: 0x1565c0, - w: 0x1a1a1a, // wild card body -}; -const UNO_COLOR_HEXTXT = { - r: '#d32f2f', y: '#f9a825', g: '#2e7d32', b: '#1565c0', w: '#1a1a1a', -}; -const UNO_COLOR_NAMES = { r: 'Red', y: 'Yellow', g: 'Green', b: 'Blue' }; - -function slotLayout(slot, playerCount) { - switch (slot) { - case 'bottom': { - const bchipY = GAME_HEIGHT - 110 - CARD_H / 2 - 30; - const bpr = 56, bpx = CX - 100 - 12 - bpr, bpy = bchipY + 22 - bpr; - return { - handCenter: { x: CX, y: GAME_HEIGHT - 110 }, - handAxis: 'x', - handFaceUp: true, - portrait: { x: bpx, y: bpy, r: bpr }, - nameLabel: { x: bpx, y: bpy - bpr - 14 }, - chip: { x: CX, y: bchipY }, - chipRotation: 0, - rotateCards: 0, - }; - } - case 'top': { - const tchipY = 110 + CARD_H / 2 + 30; - const tpr = 50, tpx = CX - 100 - 12 - tpr, tpy = tchipY - 22 + tpr; - return { - handCenter: { x: CX, y: 110 }, - handAxis: 'x', - handFaceUp: false, - portrait: { x: tpx, y: tpy, r: tpr }, - nameLabel: { x: tpx, y: tpy + tpr + 14 }, - chip: { x: CX, y: tchipY }, - chipRotation: 0, - rotateCards: 180, - }; - } - case 'left': { - const lchipX = 110 + CARD_H / 2 + 10 + 22; - const lpr = 50, lpx = lchipX - 22 + lpr, lpy = CY - 90 - 12 - lpr; - return { - handCenter: { x: 110, y: CY }, - handAxis: 'y', - handFaceUp: false, - portrait: { x: lpx, y: lpy, r: lpr }, - nameLabel: { x: lpx, y: lpy - lpr - 14 }, - chip: { x: lchipX, y: CY }, - chipRotation: Math.PI / 2, - rotateCards: 90, - }; - } - case 'right': { - const rchipX = GAME_WIDTH - 110 - CARD_H / 2 - 10 - 22; - const rpr = 50, rpx = rchipX + 22 - rpr, rpy = CY - 90 - 12 - rpr; - return { - handCenter: { x: GAME_WIDTH - 110, y: CY }, - handAxis: 'y', - handFaceUp: false, - portrait: { x: rpx, y: rpy, r: rpr }, - nameLabel: { x: rpx, y: rpy - rpr - 14 }, - chip: { x: rchipX, y: CY }, - chipRotation: -Math.PI / 2, - rotateCards: 270, - }; - } - default: - throw new Error(`Unknown slot: ${slot}`); - } -} - -const DRAW_POS = { x: CX + DRAW_OFFSET, y: CY }; -const DISCARD_POS = { x: CX + DISCARD_OFFSET, y: CY }; - -// ── Scene ─────────────────────────────────────────────────────────────────── -export default class UnoGame extends Phaser.Scene { +export default class UnoGame extends CardTableScene { constructor() { super('UnoGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.cardBack = data.cardBack ?? null; - + this.initTable(data, { settingsKey: 'uno-settings', defaults: DEFAULTS }); + this.L = layoutFor(this.playerCount); + this.backKey = 'uno-back'; this.gs = null; - this.animating = false; - this.gameOver = false; - - this.cardObjs = new Map(); - this.transientObjs = []; - this.opponentPortraits = []; - this.seatChips = []; - this.slotForSeat = []; - this.bannerText = null; - this.directionArrow = null; - this.colorSwatch = null; - this.pendingWildPlayCardId = null; // local: card chosen but awaiting color - - this.localHandCards = []; - this.dragState = null; + this.history = []; + this.selectedId = null; + this.hoverId = null; this.potentialDrag = null; - } - - create() { - new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); - this.buildPlayfield(); - this.assignSeats(); - this.buildSeatAreas(); - this.buildCenter(); - this.buildHUD(); - this.setupDragHandlers(); - this.startNewMatch(); - } - - 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); - } - } - - assignSeats() { - const playerCount = 1 + this.opponents.length; - const slots = SLOTS_USED[playerCount]; - if (!slots) throw new Error(`Uno needs 2..4 players, got ${playerCount}`); - this.slotForSeat = slots.slice(); - } - - buildSeatAreas() { - const N = this.slotForSeat.length; - for (let seat = 0; seat < N; seat++) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot, N); - - if (seat === 0) { - createPlayerPortrait(this, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait, 'UnoGame'); - this.add.text(layout.nameLabel.x, layout.nameLabel.y, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - } else { - const opp = this.opponents[seat - 1]; - if (opp) { - this.opponentPortraits[seat] = createOpponentPortrait(this, opp, layout.portrait.x, layout.portrait.y, layout.portrait.r, D.portrait); - this.add.text(layout.nameLabel.x, layout.nameLabel.y, opp.name ?? `P${seat + 1}`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - } - } - - // Hand-count chip (number of cards held). - this.seatChips[seat] = this.makeSeatChip(layout.chip.x, layout.chip.y); - this.seatChips[seat].container.setRotation(layout.chipRotation); - } - } - - makeSeatChip(x, y) { - const container = this.add.container(x, y).setDepth(D.chip); - const bg = this.add.graphics(); - bg.fillStyle(COLORS.panel, 0.92); - bg.fillRoundedRect(-100, -22, 200, 44, 10); - bg.lineStyle(2, COLORS.accent, 1); - bg.strokeRoundedRect(-100, -22, 200, 44, 10); - const label = this.add.text(-88, 0, 'CARDS', { - fontFamily: 'Righteous', fontSize: '16px', color: COLORS.goldHex, - }).setOrigin(0, 0.5); - const count = this.add.text(88, 0, '0', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.accentHex, - }).setOrigin(1, 0.5); - container.add([bg, label, count]); - return { container, count }; - } - - buildCenter() { - // Direction arrow ring (drawn around the center piles). - this.directionArrow = this.add.graphics().setDepth(D.board); - this.drawDirectionArrow(1); - - // Current-color swatch (shown between the piles). - this.colorSwatch = this.add.graphics().setDepth(D.board + 1); - - // Banner text (last action, hints). - this.bannerBg = this.add.graphics().setDepth(D.banner - 1).setVisible(false); - this.bannerText = this.add.text(CX, CY + CARD_H + 90, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, align: 'center', - wordWrap: { width: 900 }, - }).setOrigin(0.5).setDepth(D.banner); - } - - drawDirectionArrow(direction) { - const g = this.directionArrow; - g.clear(); - const radius = 180; - g.lineStyle(4, 0xffe066, 0.35); - // Top semicircle arrow - g.beginPath(); - if (direction === 1) { - g.arc(CX, CY, radius, Math.PI, 0, false); - } else { - g.arc(CX, CY, radius, 0, Math.PI, true); - } - g.strokePath(); - // Arrowhead at the end of the arc (top of arrow ring). - const tipAngle = direction === 1 ? 0 : Math.PI; - const tipX = CX + radius * Math.cos(tipAngle); - const tipY = CY + radius * Math.sin(tipAngle); - const headLen = 18; - const sign = direction === 1 ? 1 : -1; - g.lineStyle(4, 0xffe066, 0.85); - g.beginPath(); - g.moveTo(tipX, tipY); - g.lineTo(tipX - headLen * sign, tipY - headLen); - g.moveTo(tipX, tipY); - g.lineTo(tipX - headLen * sign, tipY + headLen); - g.strokePath(); - } - - updateColorSwatch() { - const g = this.colorSwatch; - g.clear(); - if (!this.gs || !this.gs.currentColor) return; - const color = UNO_COLOR_HEX[this.gs.currentColor]; - g.fillStyle(color, 1); - g.fillCircle(CX, CY, 22); - g.lineStyle(3, 0xffffff, 0.9); - g.strokeCircle(CX, CY, 22); - } - - buildHUD() { - const bchipY = GAME_HEIGHT - 110 - CARD_H / 2 - 30; - this.statusBg = this.add.graphics().setDepth(D.ui - 1); - this.statusText = this.add.text(CX - 100, bchipY - 22 - 14, '', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, align: 'left', - }).setOrigin(0, 1).setDepth(D.ui); - - new Button(this, 80, GAME_HEIGHT - 30, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 120, height: 40, fontSize: 18, - }).setDepth(D.ui); - new Button(this, 80, GAME_HEIGHT - 75, 'New', () => this.startNewMatch(), { - variant: 'ghost', width: 120, height: 40, fontSize: 18, - }).setDepth(D.ui); - } - - // ── Match lifecycle ──────────────────────────────────────────────────────── - - startNewMatch() { - if (this.animating) return; - this.gameOver = false; - this.pendingWildPlayCardId = null; - this.closeAnyModal(); - this.clearAllCardObjs(); - this.hideBanner(); - - const playerCount = this.slotForSeat.length; - const finalState = createInitialState({ playerCount }); - - playSound(this, SFX.CARD_SHUFFLE); - this.animating = true; - - // Visualize the deck as the deal source. - const deck = this.makeUnoCardSprite(null, DRAW_POS.x, DRAW_POS.y, { faceUp: false }); - this.transientObjs.push(deck); - for (const chip of this.seatChips) { if (chip) chip.count.setText('0'); } - - // Round-robin deal sequence. - const hands = finalState.players.map((p) => [...p.hand]); - const maxCards = Math.max(...hands.map((h) => h.length)); - const sequence = []; - for (let round = 0; round < maxCards; round++) { - for (let seat = 0; seat < playerCount; seat++) { - if (round < hands[seat].length) { - sequence.push({ seat, card: hands[seat][round], handIndex: round }); - } - } - } - - const STAGGER = 80; - const DURATION = 200; - - sequence.forEach(({ seat, card, handIndex }, idx) => { - this.time.delayedCall(idx * STAGGER, () => { - const layout = slotLayout(this.slotForSeat[seat], playerCount); - const n = hands[seat].length; - const spread = this.handSpreadFor(seat, n); - const offset = handIndex - (n - 1) / 2; - const tx = layout.handAxis === 'x' - ? layout.handCenter.x + offset * spread - : layout.handCenter.x; - const ty = layout.handAxis === 'x' - ? layout.handCenter.y - : layout.handCenter.y + offset * spread; - - const sprite = this.makeUnoCardSprite(card, DRAW_POS.x, DRAW_POS.y, { - faceUp: false, rotation: layout.rotateCards, - }); - sprite.setDepth(D.card + 5); - this.transientObjs.push(sprite); - - if (idx % 4 === 0) playSound(this, SFX.CARD_DEAL); - - this.tweens.add({ - targets: sprite, - x: tx, y: ty, - duration: DURATION, - ease: 'Cubic.easeOut', - onComplete: () => { - if (!sprite.active) return; - if (layout.handFaceUp) this.renderUnoCardFace(sprite, card, true); - sprite.setDepth(D.card); - }, - }); - }); - }); - - const doneAt = (sequence.length - 1) * STAGGER + DURATION + 250; - this.time.delayedCall(doneAt, () => { - this.gs = finalState; - this.animating = false; - this.renderAll(); - this.updateStatus(); - this.handlePostStateChange(); - }); - } - - // ── Card sprite factory ─────────────────────────────────────────────────── - - makeUnoCardSprite(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.renderUnoCardFace(c, card, faceUp); - c.card = card; - return c; - } - - renderUnoCardFace(container, card, faceUp) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - - if (!faceUp || !card) { - // Card back — red oval on dark body with "UNO" branding. - g.fillStyle(0x111111, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xffffff, 0.6); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - g.fillStyle(0xd32f2f, 1); - g.fillEllipse(0, 0, CARD_W * 0.78, CARD_H * 0.5); - container.add(g); - const t = this.add.text(0, 0, 'UNO', { - fontFamily: 'Righteous', fontSize: '24px', color: '#fff8e1', - }).setOrigin(0.5).setRotation(-Math.PI / 12); - const t2 = this.add.text(0, 0, 'UNO', { - fontFamily: 'Righteous', fontSize: '24px', color: '#000000', - }).setOrigin(0.5).setRotation(-Math.PI / 12).setAlpha(0.25); - t2.setPosition(1, 1); - container.add([t2, t]); - return; - } - - // Card body — white frame with colored center. - g.fillStyle(0xffffff, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, 0x111111, 1); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - const bodyColor = UNO_COLOR_HEX[card.color] ?? UNO_COLOR_HEX.w; - g.fillStyle(bodyColor, 1); - g.fillRoundedRect(x + 8, y + 8, CARD_W - 16, CARD_H - 16, CARD_R - 2); - container.add(g); - - if (card.isWild) { - // Four quadrants of color inside the body. - const cx = 0, cy = 0; - const w = CARD_W - 16, h = CARD_H - 16; - const cardX = x + 8, cardY = y + 8; - const quadG = this.add.graphics(); - quadG.fillStyle(UNO_COLOR_HEX.r, 1); - quadG.fillRect(cardX, cardY, w / 2, h / 2); - quadG.fillStyle(UNO_COLOR_HEX.y, 1); - quadG.fillRect(cardX + w / 2, cardY, w / 2, h / 2); - quadG.fillStyle(UNO_COLOR_HEX.b, 1); - quadG.fillRect(cardX, cardY + h / 2, w / 2, h / 2); - quadG.fillStyle(UNO_COLOR_HEX.g, 1); - quadG.fillRect(cardX + w / 2, cardY + h / 2, w / 2, h / 2); - container.add(quadG); - } - - // White ellipse with the label. - const ovalG = this.add.graphics(); - const ovalColor = card.isWild ? 0x000000 : 0xffffff; - ovalG.fillStyle(ovalColor, 1); - ovalG.fillEllipse(0, 0, CARD_W * 0.7, CARD_H * 0.55); - container.add(ovalG); - - // Center label. - const labelColor = card.isWild - ? '#ffffff' - : UNO_COLOR_HEXTXT[card.color] ?? COLORS.textDarkHex; - const labelText = card.label; - const isWide = labelText.length > 1; - const fontSize = isWide ? 36 : 48; - container.add( - this.add.text(0, 0, labelText, { - fontFamily: 'Righteous', - fontSize: `${fontSize}px`, - color: labelColor, - }).setOrigin(0.5), - ); - - // Corner labels (top-left, bottom-right). - const cornerColor = card.isWild ? '#ffffff' : COLORS.textHex; - const cornerStyle = (sz) => ({ - fontFamily: 'Righteous', fontSize: `${sz}px`, color: cornerColor, - }); - container.add( - this.add.text(x + 10, y + 8, labelText, cornerStyle(18)), - ); - container.add( - this.add.text(x + CARD_W - 10, y + CARD_H - 8, labelText, cornerStyle(18)) - .setOrigin(1, 1), - ); - - // If a wild's chosen color is set, indicate it via a small swatch. - if (card.isWild && card.chosenColor) { - const sw = this.add.graphics(); - sw.fillStyle(UNO_COLOR_HEX[card.chosenColor], 1); - sw.fillCircle(0, CARD_H / 2 - 18, 9); - sw.lineStyle(2, 0xffffff, 0.9); - sw.strokeCircle(0, CARD_H / 2 - 18, 9); - container.add(sw); - } - } - - clearAllCardObjs() { - for (const c of this.cardObjs.values()) c.destroy(); - this.cardObjs.clear(); - for (const o of this.transientObjs) o.destroy(); - this.transientObjs = []; - } - - // ── Rendering ───────────────────────────────────────────────────────────── - - renderAll() { - this.clearAllCardObjs(); - this.renderDrawPile(); - this.renderDiscardPile(); - for (let seat = 0; seat < this.gs.players.length; seat++) { - this.renderSeat(seat); - } - this.renderHandCountChips(); - this.renderTurnIndicator(); - this.drawDirectionArrow(this.gs.direction); - this.updateColorSwatch(); - } - - renderDrawPile() { - const remaining = this.gs.drawPile.length; - if (remaining === 0) return; - // Render the top three card backs stacked for visual depth. - const stack = Math.min(remaining, 3); - for (let i = 0; i < stack; i++) { - const c = this.makeUnoCardSprite(null, DRAW_POS.x - i * 2, DRAW_POS.y - i * 2, { faceUp: false }); - c.setDepth(D.card - i); - this.cardObjs.set(`draw-${i}`, c); - } - // Top card is interactive on the local turn. - if (this.isLocalTurn() && this.gs.phase === 'play') { - const top = this.cardObjs.get('draw-0'); - if (top) { - top.setInteractive( - new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), - Phaser.Geom.Rectangle.Contains, - ); - top.input.cursor = 'pointer'; - top.on('pointerover', () => { - this.tweens.add({ targets: top, scaleX: 1.04, scaleY: 1.04, duration: 100 }); - top.setDepth(D.highlight); - }); - top.on('pointerout', () => { - this.tweens.add({ targets: top, scaleX: 1, scaleY: 1, duration: 100 }); - top.setDepth(D.card); - }); - top.on('pointerdown', () => this.onDrawClick()); - } - } - } - - renderDiscardPile() { - // Render just the top card (animations create extras as needed). - const top = this.gs.discardPile[this.gs.discardPile.length - 1]; - if (!top) return; - const c = this.makeUnoCardSprite(top, DISCARD_POS.x, DISCARD_POS.y, { faceUp: true }); - c.setDepth(D.card); - this.cardObjs.set('discard-top', c); - } - - handSpreadFor(seat, n) { - if (seat === 0) { - // Local player — face-up; compress when hand is large. - if (n <= 1) return HAND_SPREAD_MAX; - const maxSpread = HAND_FACEUP_MAX_W / Math.max(n - 1, 1); - return Math.min(HAND_SPREAD_MAX, maxSpread); - } - // Opponent hands — tighter fan, capped. - if (n <= 1) return 40; - const maxOppW = 600; - return Math.min(40, maxOppW / Math.max(n - 1, 1)); - } - - renderSeat(seat) { - const player = this.gs.players[seat]; - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot, this.gs.players.length); - const n = player.hand.length; - const spread = this.handSpreadFor(seat, n); - const localLegal = (seat === 0 && this.gs.phase === 'play' && this.isLocalTurn()) - ? new Set(legalPlays(this.gs, 0)) - : null; - - if (seat === 0) this.localHandCards = []; - - for (let i = 0; i < n; i++) { - const card = player.hand[i]; - const offset = i - (n - 1) / 2; - let x, y; - if (layout.handAxis === 'x') { - x = layout.handCenter.x + offset * spread; - y = layout.handCenter.y; - } else { - x = layout.handCenter.x; - y = layout.handCenter.y + offset * spread; - } - const c = this.makeUnoCardSprite(card, x, y, { - faceUp: layout.handFaceUp, - rotation: layout.rotateCards, - }); - 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'; - const baseY = y; - c.on('pointerover', () => { - if (this.animating || this.dragState) return; - this.tweens.add({ targets: c, y: baseY - 14, duration: 120 }); - c.setDepth(D.highlight); - }); - c.on('pointerout', () => { - if (this.dragState) return; - this.tweens.add({ targets: c, y: baseY, duration: 120 }); - c.setDepth(D.card); - }); - c.on('pointerdown', (pointer) => this.onHandPointerDown(i, pointer)); - if (localLegal && !localLegal.has(card.id)) { - c.setAlpha(0.6); - } - } - } - } - - renderHandCountChips() { - for (let s = 0; s < this.gs.players.length; s++) { - const p = this.gs.players[s]; - const chip = this.seatChips[s]; - if (!chip) continue; - chip.count.setText(`${p.hand.length}`); - } - } - - // ── Hand drag-to-sort ───────────────────────────────────────────────────── - - setupDragHandlers() { - this.input.on('pointermove', (pointer) => { - if (this.potentialDrag && !this.dragState) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (Math.sqrt(dx * dx + dy * dy) >= 8) { - const pd = this.potentialDrag; - this.potentialDrag = null; - this.startCardDrag(pd.handIdx, pd.offsetX, pd.offsetY); - } - } - if (this.dragState) { - this.updateCardDrag(pointer); - } - }); - - this.input.on('pointerup', () => { - if (this.potentialDrag) { - const { cardId } = this.potentialDrag; - this.potentialDrag = null; - this.onHandCardClick(cardId); - return; - } - if (this.dragState) { - this.endCardDrag(); - } - }); - } - - onHandPointerDown(handIdx, pointer) { - if (this.dragState || this.animating) return; - const card = this.localHandCards[handIdx]; - if (!card) return; - const cardId = this.gs.players[0].hand[handIdx]?.id; - if (!cardId) return; - this.potentialDrag = { - handIdx, - cardId, - startX: pointer.x, - startY: pointer.y, - offsetX: pointer.x - card.x, - offsetY: pointer.y - card.y, - }; - } - - startCardDrag(handIdx, offsetX, offsetY) { - const card = this.localHandCards[handIdx]; - if (!card) return; - const n = this.gs.players[0].hand.length; - const layout = slotLayout('bottom', this.gs.players.length); - const spread = this.handSpreadFor(0, n); - const handStartX = layout.handCenter.x - (n - 1) / 2 * spread; - const handCenterY = layout.handCenter.y; - const insertIdx = Phaser.Math.Clamp(Math.round((card.x - handStartX) / spread), 0, n - 1); - - this.tweens.killTweensOf(card); - - const shadow = this.add.graphics(); - shadow.fillStyle(0x000000, 0.35); - shadow.fillEllipse(0, 0, CARD_W * 1.1, 28); - shadow.setPosition(card.x + 6, card.y + 16); - shadow.setDepth(D.card + 9); - this.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(handStartX + insertIdx * spread, handCenterY); - slotIndicator.setDepth(D.card - 1); - this.transientObjs.push(slotIndicator); - - const discardHighlight = this.add.graphics(); - discardHighlight.lineStyle(3, COLORS.accent, 0.9); - discardHighlight.strokeRoundedRect(-CARD_W / 2 - 6, -CARD_H / 2 - 6, CARD_W + 12, CARD_H + 12, 12); - discardHighlight.fillStyle(COLORS.accent, 0.18); - discardHighlight.fillRoundedRect(-CARD_W / 2 - 6, -CARD_H / 2 - 6, CARD_W + 12, CARD_H + 12, 12); - discardHighlight.setPosition(DISCARD_POS.x, DISCARD_POS.y); - discardHighlight.setDepth(D.card + 1); - discardHighlight.setAlpha(0); - this.transientObjs.push(discardHighlight); - - this.dragState = { cardIdx: handIdx, offsetX, offsetY, prevX: card.x, shadow, slotIndicator, discardHighlight, insertIdx, spread, handStartX, handCenterY, overDiscard: false }; - - 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 overDiscard = this._isDiscardDropTarget(card.x, card.y); - if (overDiscard !== ds.overDiscard) { - ds.overDiscard = overDiscard; - if (overDiscard) { - this.tweens.killTweensOf(ds.slotIndicator); - ds.slotIndicator.setAlpha(0); - this._settleNonDraggedCards(); - this.tweens.add({ targets: ds.discardHighlight, alpha: 1, duration: 150 }); - } else { - ds.slotIndicator.setAlpha(1); - this._updateNonDraggedCards(); - this.tweens.add({ targets: ds.discardHighlight, alpha: 0, duration: 150 }); - } - } - - if (!overDiscard) { - const newInsertIdx = Phaser.Math.Clamp(Math.round((card.x - ds.handStartX) / ds.spread), 0, Math.max(0, n - 1)); - if (newInsertIdx !== ds.insertIdx) { - ds.insertIdx = newInsertIdx; - this.tweens.killTweensOf(ds.slotIndicator); - this.tweens.add({ targets: ds.slotIndicator, x: ds.handStartX + newInsertIdx * ds.spread, duration: 100, ease: 'Cubic.easeOut' }); - this._updateNonDraggedCards(); - } - } - } - - _isDiscardDropTarget(cardX, cardY) { - if (!this.isLocalTurn() || this.gs.phase !== 'play') return false; - const me = this.gs.players[0]; - const handCard = me.hand[this.dragState.cardIdx]; - if (!handCard || !isLegalPlay(this.gs, handCard, me.hand)) return false; - return Math.abs(cardX - DISCARD_POS.x) < CARD_W * 1.2 && Math.abs(cardY - DISCARD_POS.y) < CARD_H * 1.2; - } - - _settleNonDraggedCards() { - const ds = this.dragState; - const n = this.gs.players[0].hand.length; - let k = 0; - for (let j = 0; j < n; j++) { - if (j === ds.cardIdx) continue; - const cardObj = this.localHandCards[j]; - this.tweens.killTweensOf(cardObj); - this.tweens.add({ targets: cardObj, x: ds.handStartX + k * ds.spread, rotation: 0, scaleX: 1, scaleY: 1, duration: 100, ease: 'Cubic.easeOut' }); - k++; - } - } - - _updateNonDraggedCards() { - const ds = this.dragState; - const n = this.gs.players[0].hand.length; - const others = []; - for (let i = 0; i < n; i++) { if (i !== ds.cardIdx) others.push(i); } - - for (let k = 0; k < others.length; k++) { - const j = others[k]; - const finalPos = k < ds.insertIdx ? k : k + 1; - const targetX = ds.handStartX + finalPos * ds.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' }); - } - } - - endCardDrag() { - const ds = this.dragState; - const card = this.localHandCards[ds.cardIdx]; - const hand = this.gs.players[0].hand; - const n = hand.length; - - this.tweens.killTweensOf(ds.discardHighlight); - ds.discardHighlight.setAlpha(0); - - // ── Play path: dropped on discard pile ─────────────────────────────────── - if (ds.overDiscard) { - const handCard = hand[ds.cardIdx]; - this.tweens.killTweensOf(card); - card.setScale(1); - card.setRotation(0); - ds.shadow.setAlpha(0); - this._settleNonDraggedCards(); - this.dragState = null; - if (handCard.isWild) { - this.pendingWildPlayCardId = handCard.id; - this.openColorPicker((color) => { - this.pendingWildPlayCardId = null; - this.executeLocalPlay(handCard.id, color); - }); - } else { - this.executeLocalPlay(handCard.id); - } - return; - } - - // ── Reorder path: dropped back in hand ─────────────────────────────────── - const finalIdx = Phaser.Math.Clamp(Math.round((card.x - ds.handStartX) / ds.spread), 0, n - 1); - - this.tweens.killTweensOf(card); - this.tweens.add({ targets: card, x: ds.handStartX + finalIdx * ds.spread, y: ds.handCenterY, 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: ds.handStartX + finalPos * ds.spread, rotation: 0, scaleX: 1, scaleY: 1, duration: 120, ease: 'Cubic.easeOut' }); - } - - const [moved] = hand.splice(ds.cardIdx, 1); - hand.splice(finalIdx, 0, moved); - this.dragState = null; - this.time.delayedCall(240, () => this.renderAll()); + this.dragPreview = null; + this.revealAll = false; + this.lastClickAt = 0; + this.ringPhase = 0; + this.wheel = null; + this.prevSizes = []; } - renderTurnIndicator() { - const seat = this.gs.currentPlayer; - const slot = this.slotForSeat[seat]; - const lay = slotLayout(slot, this.gs.players.length); - 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); + faceFrame(card) { return { key: 'uno-cards', frame: frameKey(card) }; } + + async create() { + this.createTableBase(); + const key = await prepareUnoArt(this, this.playerCount); + if (!this.alive()) return; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildSpot(); + this.haloG = this.add.graphics().setDepth(D.slots); + this.ringG = this.add.graphics().setDepth(D.slots + 0.5); + this.slabG = this.add.graphics().setDepth(D.cards - 1); + this.targetG = this.add.graphics().setDepth(D.glow); + this.deckTxt = this.add.text(this.L.deck.x, this.L.deck.y + 84, '', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#5a3a1c', + }).setOrigin(0.5).setDepth(D.labels); + this.buildDropSlot(); + this.buildPlates(this.L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'UNO!' }); + this.buildBadges(); + this.buildGhostHands(this.L.seats.map((_, s) => (s ? handHome(this.L, s) : null)), SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Rules: () => this.openRules(), + }, 'Click a card to play · D draw · U call UNO! · C catch · P play drawn · K keep\nR Y G B pick a colour · S sort · H hint · Esc menu'); + this.buildDock(); + this.buildSortRow([['color', 'Color'], ['number', '1·2·3'], ['manual', 'Mine']], () => { this.sortHand(); this.layout(); }); + this.buildTooltips(); + this.setupInput(); + this.newMatch(); } - // ── Status / banner ──────────────────────────────────────────────────────── + update(_t, dt) { + if (!this.gs || this.paused) return; + this.ringPhase += (dt / 1000) * 0.55 * (this.gs.direction ?? 1); + this.drawRing(); + } - updateStatus() { - if (this.gameOver) { - this.statusText.setText(''); - this.statusBg.setVisible(false); - return; + // ── Furniture ───────────────────────────────────────────────────────────── + buildBadges() { + this.badges = []; + for (let seat = 1; seat < this.playerCount; seat++) { + const p = handBadge(this.L, seat); + const c = this.add.container(p.x, p.y).setDepth(D.oppHand + 2); + const ring = this.add.circle(0, 0, 22, 0xffb15a, 0); + const g = this.add.graphics(); + g.fillStyle(0x140d07, 0.92); + g.fillCircle(0, 0, 16); + g.lineStyle(2.5, SEAT_COLORS[seat], 1); + g.strokeCircle(0, 0, 16); + const t = this.add.text(0, 1, '7', { fontFamily: 'Righteous', fontSize: '16px', color: COLORS.textHex }).setOrigin(0.5); + c.add([ring, g, t]); + this.badges[seat] = { c, ring, t, tw: null }; } - if (!this.gs) return; - let msg; - switch (this.gs.phase) { - case 'choosingColor': - msg = this.isLocalTurn() || this.pendingWildPlayCardId !== null - ? 'Pick a color for your Wild card.' - : `${this.opponentName(this.gs.currentPlayer)} is picking a color…`; - break; - case 'challengeWindow': { - const challenger = this.gs.pendingWild4?.challengerSeat; - msg = challenger === 0 - ? `Challenge ${this.opponentName(this.gs.pendingWild4.playerSeat)}'s Wild +4?` - : `${this.opponentName(challenger)} is deciding whether to challenge…`; - break; + } + + buildTooltips() { + for (let seat = 1; seat < this.playerCount; seat++) { + const pl = this.L.seats[seat].plate; + this.hoverZone(pl.x, pl.y, 300, 96, () => this.seatTip(seat)); + } + const d = this.L.discard; + this.hoverZone(d.x, d.y, CARD_W * d.s + 30, CARD_H * d.s * SQ + 30, () => this.pileTip()); + } + + seatTip(seat) { + if (!this.gs) return null; + const p = this.gs.players[seat]; + const lines = [ + { text: `${p.hand.length} card${p.hand.length === 1 ? '' : 's'} in hand`, color: p.hand.length <= 2 ? '#ffb15a' : COLORS.textHex }, + { text: this.gs.target > 0 ? `Score ${this.gs.scores[seat]} / ${this.gs.target}` : `Hands won ${this.gs.scores[seat] ? 'this match' : '—'}` }, + { text: `Skill ${this.skillFor(seat)} / 5`, color: COLORS.mutedHex }, + ]; + if (p.hand.length === 1) lines.push({ text: this.gs.unoCalled[seat] ? 'Called UNO!' : 'Didn\'t call UNO — catch them!', color: this.gs.unoCalled[seat] ? '#8ce99a' : '#ff8a7a' }); + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; + } + + pileTip() { + if (!this.gs) return null; + const top = topDiscard(this.gs); + const c = this.gs.currentColor; + const lines = [ + { text: c ? `Colour in play: ${COLOR_NAME[c]}` : 'No colour chosen yet', color: c ? UNO_HEX[c] : COLORS.mutedHex }, + { text: `Direction: ${this.gs.direction === 1 ? 'clockwise' : 'counter-clockwise'}` }, + { text: `${this.gs.drawPile.length} cards left to draw` }, + ]; + if (this.gs.pendingDraw) lines.push({ text: `Stacked penalty: +${this.gs.pendingDraw.count}`, color: '#ff8a7a' }); + return { title: `Top card: ${this.cardName(top)}`, lines }; + } + + cardName(c) { + if (!c) return ''; + if (c.kind === 'wild') return c.chosenColor ? `Wild (${COLOR_NAME[c.chosenColor]})` : 'Wild'; + if (c.kind === 'wild4') return c.chosenColor ? `Wild Draw 4 (${COLOR_NAME[c.chosenColor]})` : 'Wild Draw 4'; + const kind = c.kind === 'number' ? c.value : c.kind === 'draw2' ? 'Draw 2' : c.kind === 'skip' ? 'Skip' : 'Reverse'; + return `${COLOR_NAME[c.color]} ${kind}`; + } + + // ── Match / hand lifecycle ──────────────────────────────────────────────── + newMatch() { + this.history = []; + this.gs = createInitialState({ + playerCount: this.playerCount, + rules: { stacking: this.settings.stacking, drawUntilPlayable: this.settings.drawUntil }, + target: this.settings.target, + }); + this.startHand(); + } + + async startHand() { + this.clearSprites(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + this.revealAll = false; + this.selectedId = null; + this.closeWheel(); + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } + const gs = this.gs; + const n = this.playerCount; + const from = { ...this.L.deck, y: this.L.deck.y - 10 }; + for (const p of gs.players) for (const c of p.hand) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + for (const c of gs.discardPile) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + this.prevSizes = gs.players.map(p => p.hand.length); + this.sortHand(); + this.updatePlates(); + this.updateDock(); + playSound(this, SFX.CARD_SHUFFLE); + const start = gs.startingPlayer; + const order = (seat) => (seat - start + n) % n; + const dealOrder = new Map(); + gs.players.forEach(p => [...p.hand].sort((a, b) => a.id - b.id).forEach((c, i) => dealOrder.set(c.id, i * n + order(p.seat)))); + const step = 46; + const last = 7 * n * step; + this.layout({ + duration: 300, + delayFor: (v) => (v.kind === 'discard' ? 300 + last + 200 : 300 + (dealOrder.get(v.card.id) ?? 0) * step), + }); + for (let i = 0; i < 7 * n; i += 3) this.time.delayedCall(320 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.45 })); + await this.wait(300 + last + 700); + if (!this.alive() || token !== this.turnToken) return; + // starting-card effects the engine already applied + for (const e of gs.log) { + if (e.kind === 'startSkip') this.plateStamp(e.seat, 'SKIPPED', '#ff6b4a'); + if (e.kind === 'startReverse') this.floatText(this.L.discard, 'Reverse!', '#f2ead8', { size: 30 }); + if (e.kind === 'startDraw2') this.floatText(this.seatAnchor(e.seat), `+${e.count}`, '#ff8a7a', { size: 34 }); + } + this.advance(); + } + + actorSeat() { + const gs = this.gs; + if (gs.phase === 'challengeWindow') return gs.pendingWild4.challengerSeat; + return gs.currentPlayer; + } + + // Decide who acts next after any change. + advance() { + if (!this.alive() || !this.gs) return; + if (isHandOver(this.gs)) { this.onHandOver(); return; } + const seat = this.actorSeat(); + this.setSpot(spotFor(this.L, seat)); + this.updatePlates(); + if (seat === 0) { + this.mode = 'human'; + this.layout(); + this.updateDock(); + if (this.gs.phase === 'choosingColor') this.openWheel(); + else playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + } else { + this.mode = 'ai'; + this.closeWheel(); + this.layout(); + this.updateDock(); + this.runAITurn(seat); + } + } + + // Apply a new state; animate draws, report effects from the log. + commit(next, { carry = null, carrySeat = null } = {}) { + const prev = this.gs; + this.gs = next; + const fresh = next.log.slice(prev.log.length); + // new cards per seat (draws / penalties) fly in one after another + const order = new Map(); + next.players.forEach((p, s) => { + const had = new Set(prev.players[s].hand.map(c => c.id)); + let k = 0; + for (const c of p.hand) if (!had.has(c.id)) order.set(c.id, k++); + }); + if (this.settings.sort !== 'manual' && order.size) this.sortHand(); + this.layout({ + delayFor: (v) => (order.has(v.card.id) ? order.get(v.card.id) * 110 : 0), + durationFor: (v) => (carry && carrySeat != null && v.card.id === carry ? this.timing(carrySeat).carry : order.has(v.card.id) ? 300 : null), + }); + for (const e of fresh) this.logEffect(e, prev, next); + if (prev.unoVulnerable == null && next.unoVulnerable != null) this.scheduleCatches(next.unoVulnerable); + next.players.forEach((p, s) => { + if (p.hand.length === 1 && (this.prevSizes[s] ?? 0) !== 1 && !isHandOver(next)) { + this.floatText(this.seatAnchor(s), s === 0 ? 'One card left!' : `${this.shortName(s)}: one card!`, '#ffb15a', { size: 22, ms: 1500 }); } - case 'mustPlayDrawn': { - const card = this.gs.pendingDrawn; - msg = this.isLocalTurn() - ? `Drew ${this.describeCard(card)} — play it or keep it.` - : `${this.opponentName(this.gs.currentPlayer)} drew a card…`; + }); + this.prevSizes = next.players.map(p => p.hand.length); + this.updatePlates(); + this.updateDock(); + } + + seatAnchor(seat) { + if (seat === 0) return { x: CX, y: 880 }; + return handHome(this.L, seat); + } + + logEffect(e, prev, next) { + switch (e.kind) { + case 'skip': + this.plateStamp(e.seat, 'SKIPPED', '#ff6b4a'); + this.floatText(this.seatAnchor(e.seat), 'Skipped!', '#ff8a7a', { size: 26 }); + this.cameras.main.shake(120, 0.003); break; - } - case 'play': - msg = this.isLocalTurn() - ? 'Your turn — tap a playable card or the draw pile.' - : `${this.opponentName(this.gs.currentPlayer)} is thinking…`; + case 'reverse': + this.stamp('REVERSE', this.L.discard, '#f2ead8', { size: 56, hold: 500 }); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.5, rate: 1.5 }); + break; + case 'draw2': case 'draw2Stack': case 'wild4Accept': case 'wild4ChallengeLose': case 'finalDraw': + if (e.kind === 'draw2Stack') this.floatText(this.L.discard, `Stack +${e.count}!`, '#ffb15a', { size: 30 }); + else this.floatText(this.seatAnchor(e.seat), `+${e.count}`, '#ff8a7a', { size: 36, ms: 1300 }); + if (e.kind === 'wild4ChallengeLose') this.stamp('Challenge failed!', { x: CX, y: CY - 40 }, '#ff8a7a', { size: 52, hold: 900 }); + if (e.kind === 'draw2' || e.kind === 'wild4Accept') this.plateStamp(e.seat, 'SKIPPED', '#ff6b4a'); + break; + case 'wild4ChallengeWin': + this.stamp('Caught bluffing!', { x: CX, y: CY - 40 }, '#8ce99a', { size: 52, hold: 900 }); + this.floatText(this.seatAnchor(e.seat), `+${e.count}`, '#ff8a7a', { size: 36, ms: 1300 }); + break; + case 'chooseColor': + this.burst(this.L.discard, COLOR_INT[e.color], { n: 10, r: 90 }); + this.floatText({ x: this.L.discard.x, y: this.L.discard.y - 70 }, COLOR_NAME[e.color], UNO_HEX[e.color], { size: 30 }); + break; + case 'unoCall': + this.plateStamp(e.seat, 'UNO!', '#ffd35a', 1800); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.6 }); + break; + case 'uno': + break; + case 'unoCaught': + this.plateStamp(e.seat, 'CAUGHT!', '#ff6b4a', 1800); + this.floatText(this.seatAnchor(e.seat), `${e.seat === 0 ? 'You forgot' : `${this.shortName(e.seat)} forgot`} UNO! +2`, '#ff8a7a', { size: 24, ms: 1800 }); + if (e.by > 0 && e.seat === 0) this.portraits[e.by]?.playEmotion?.('happy'); + if (e.seat > 0) this.portraits[e.seat]?.playEmotion?.('upset'); + this.cameras.main.shake(160, 0.004); + break; + case 'reshuffle': + this.floatText({ x: this.L.deck.x, y: this.L.deck.y - 80 }, 'Reshuffled the discards', '#5a3a1c', { size: 20, ms: 1500 }); + playSound(this, SFX.CARD_SHUFFLE); break; default: - msg = ''; - } - this.statusText.setText(msg); - this.refreshStatusBg(); - } - - refreshStatusBg() { - const t = this.statusText; - const pad = 8; - this.statusBg.clear(); - if (!t.text) { this.statusBg.setVisible(false); return; } - this.statusBg.fillStyle(0x000000, 0.55); - this.statusBg.fillRoundedRect(t.x - pad, t.y - t.height - pad, t.width + pad * 2, t.height + pad * 2, 6); - this.statusBg.setVisible(true); - } - - showBanner(text) { - this.bannerText.setText(text); - this.bannerText.setVisible(true); - this.bannerBg.clear(); - this.bannerBg.fillStyle(COLORS.panel, 0.85); - const w = Math.max(this.bannerText.width + 60, 360); - const h = this.bannerText.height + 28; - this.bannerBg.fillRoundedRect(this.bannerText.x - w / 2, this.bannerText.y - h / 2, w, h, 10); - this.bannerBg.lineStyle(2, COLORS.accent, 1); - this.bannerBg.strokeRoundedRect(this.bannerText.x - w / 2, this.bannerText.y - h / 2, w, h, 10); - this.bannerBg.setVisible(true); - } - - hideBanner() { - this.bannerText?.setVisible(false); - this.bannerBg?.setVisible(false); - } - - describeCard(card) { - if (!card) return ''; - if (card.isWild) return card.kind === 'wild4' ? 'a Wild +4' : 'a Wild'; - const colorName = UNO_COLOR_NAMES[card.color] ?? card.color; - switch (card.kind) { - case 'number': return `${colorName} ${card.value}`; - case 'skip': return `${colorName} Skip`; - case 'reverse': return `${colorName} Reverse`; - case 'draw2': return `${colorName} +2`; - default: return `${colorName} card`; + break; } } - // ── Turn flow ────────────────────────────────────────────────────────────── - - isLocalTurn() { - return !this.gameOver && this.gs && this.gs.currentPlayer === 0; - } - - opponentName(seat) { - if (seat === 0) return 'You'; - const opp = this.opponents[seat - 1]; - return opp?.name ?? `P${seat + 1}`; - } - - // ── Input (local player) ────────────────────────────────────────────────── - - onHandCardClick(cardId) { - if (!this.isLocalTurn() || this.animating) return; - if (this.gs.phase !== 'play') return; - const me = this.gs.players[0]; - const card = me.hand.find((c) => c.id === cardId); - if (!card) return; - if (!isLegalPlay(this.gs, card, me.hand)) { - this.shakeCardSprite(this.cardObjs.get(`hand-0-${card.id}`)); - this.showBanner(`That ${this.describeCard(card)} doesn't match.`); - this.time.delayedCall(1100, () => this.hideBanner()); - return; + // ── AI ────────────────────────────────────────────────────────────────────── + async runAITurn(seat) { + const token = ++this.turnToken; + const T0 = this.timing(seat); + const still = () => this.alive() && token === this.turnToken && !isHandOver(this.gs) && this.actorSeat() === seat; + // give the table a moment to catch a forgotten UNO! before the next player acts + const grace = this.gs.unoVulnerable != null && this.gs.unoVulnerable !== seat ? UNO_GRACE_MS * this.pace() : 0; + await this.wait(T0.think + grace); + if (!still()) return; + let guard = 0; + while (still() && guard++ < 20) { + const action = chooseAction(this.gs, seat, { skill: this.skillFor(seat) }); + const ok = await this.aiPlay(seat, action, T0); + if (!this.alive() || token !== this.turnToken) return; + if (!ok) break; + if (isHandOver(this.gs) || this.actorSeat() !== seat) break; + await this.wait(T0.between); } - if (card.isWild) { - this.pendingWildPlayCardId = card.id; - this.openColorPicker((color) => { - this.pendingWildPlayCardId = null; - this.executeLocalPlay(card.id, color); - }); - return; + if (!this.alive() || token !== this.turnToken) return; + if (!isHandOver(this.gs) && this.actorSeat() === seat) { + // safety net: never stall the table + const g = this.gs; + const next = g.phase === 'challengeWindow' ? applyChallengeWild4(g, false) + : g.phase === 'choosingColor' ? applyChooseColor(g, 'r') + : g.phase === 'mustPlayDrawn' ? applyPassAfterDraw(g, seat) : applyDraw(g, seat); + if (next !== g) this.commit(next); } - this.executeLocalPlay(card.id); + this.advance(); } - onDrawClick() { - if (!this.isLocalTurn() || this.animating) return; - if (this.gs.phase !== 'play') return; - this.executeLocalDraw(); - } - - // ── Execution wrappers ──────────────────────────────────────────────────── - - executeLocalPlay(cardId, chosenColor) { - this.animating = true; - const seat = 0; - const before = this.gs; - const card = before.players[seat].hand.find((c) => c.id === cardId); - if (!card) { this.animating = false; return; } - const after = applyPlay(before, seat, cardId); - if (after === before) { this.animating = false; return; } - - this.animatePlayCard(seat, card, () => { - this.gs = after; - this.renderAll(); - // Auto-call UNO when we've just dropped to 1 card. - if (this.gs.players[seat].hand.length === 1) this.showUnoCallout(seat); - this.handleLogEffects(before, after, () => { - // If the played card was a Wild and we have a pre-chosen color, apply it. - if (chosenColor && this.gs.phase === 'choosingColor') { - this.time.delayedCall(150, () => this.executeChooseColor(chosenColor)); - return; - } - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - }); - } - - executeLocalDraw() { - this.animating = true; - const seat = 0; - const before = this.gs; - const after = applyDraw(before, seat); - if (after === before) { this.animating = false; return; } - const drawnCard = after.lastAction?.kind === 'draw' ? after.lastAction.card : null; - this.animateDrawCard(seat, drawnCard, /* reveal */ true, () => { - this.gs = after; - this.renderAll(); - this.animating = false; - this.updateStatus(); - if (this.gs.phase === 'mustPlayDrawn') { - this.openPlayDrawnPrompt(); - } else { - this.handlePostStateChange(); + async aiPlay(seat, a, T0) { + const gs = this.gs; + const hand = gs.players[seat].hand; + if (a.kind === 'chooseColor') { + await this.wait(T0.hesitate); + const next = applyChooseColor(this.gs, a.color); + if (next === this.gs) return false; + this.commit(next); + return true; + } + if (a.kind === 'challenge') { + await this.wait(T0.hesitate * 1.5); + if (a.doChallenge) this.floatText(this.seatAnchor(seat), 'I challenge!', SEAT_HEX[seat], { size: 24, ms: 1200 }); + const next = applyChallengeWild4(this.gs, a.doChallenge); + if (next === this.gs) return false; + this.commit(next); + await this.wait(500); + return true; + } + if (a.kind === 'draw' || a.kind === 'passDrawn') { + if (a.kind === 'passDrawn') { + await this.wait(T0.hesitate); + const next = applyPassAfterDraw(this.gs, seat); + if (next === this.gs) return false; + this.commit(next); + return true; } - }); - } - - executeChooseColor(color) { - const before = this.gs; - const after = applyChooseColor(before, color); - if (after === before) return; - this.animating = true; - this.gs = after; - this.renderAll(); - this.showBanner(`Color set to ${UNO_COLOR_NAMES[color]}.`); - this.time.delayedCall(700, () => this.hideBanner()); - this.time.delayedCall(150, () => { - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - } - - executeChallenge(doChallenge) { - const before = this.gs; - const after = applyChallengeWild4(before, doChallenge); - if (after === before) return; - this.animating = true; - const last = after.lastAction; - const banner = this.formatChallengeBanner(last); - this.gs = after; - this.renderAll(); - if (banner) { - this.showBanner(banner); - this.time.delayedCall(1300, () => this.hideBanner()); + this.moveHand(seat, this.deckTop(), T0.reach); + await this.wait(T0.reach); + const next = applyDraw(this.gs, seat); + if (next === this.gs) return false; + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.55 }); + this.commit(next); + const h = this.gs.players[seat].hand; + this.moveHand(seat, handPose(this.L, seat, h.length - 1, h.length), T0.carry, 'Cubic.easeOut'); + await this.wait(T0.carry); + this.handRest(seat, T0.carry * 0.6); + return true; } - this.handleLogEffects(before, after, () => { - this.time.delayedCall(400, () => { - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - }); + // a play (from hand, a drawn card, or a stacked +4) + const cardId = a.kind === 'playDrawn' ? gs.pendingDrawn?.id : a.cardId; + const card = hand.find(c => c.id === cardId); + if (!card) return false; + // say UNO! as the second-to-last card goes down (or forget to) + if (hand.length === 2 && !gs.unoCalled[seat] && Math.random() < UNO_CALL_CHANCE[this.clampSkill(seat)]) { + this.commit(applyCallUno(this.gs, seat)); + this.speech(seat, 'UNO!'); + } + this.moveHand(seat, this.poseOf(card.id) ?? handPose(this.L, seat, 0, hand.length), T0.reach * 0.6); + await this.wait(T0.reach * 0.6); + let next = a.kind === 'playDrawn' ? applyPlayDrawn(this.gs, seat) + : a.kind === 'stack' ? applyStackWild4(this.gs, seat, card.id) : applyPlay(this.gs, seat, card.id); + if (next === this.gs) return false; + this.commit(next, { carry: card.id, carrySeat: seat }); + this.moveHand(seat, this.L.discard, T0.carry, 'Cubic.easeOut'); + await this.wait(T0.carry); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.6 }); + this.handRest(seat, T0.carry * 0.7); + // colour choice follows a wild immediately + if (this.gs.phase === 'choosingColor' && this.actorSeat() === seat && a.chosenColor) { + await this.wait(T0.hesitate); + next = applyChooseColor(this.gs, a.chosenColor); + if (next !== this.gs) this.commit(next); + } + return true; } - formatChallengeBanner(last) { - if (!last || last.kind !== 'wild4Resolve') return null; - const who = this.opponentName(last.drawSeat); - if (last.result === 'accept') return `${who} draws ${last.drawCount} and is skipped.`; - if (last.result === 'challengeWin') return `Challenge succeeded — ${who} draws ${last.drawCount}.`; - if (last.result === 'challengeLose')return `Challenge failed — ${who} draws ${last.drawCount} and is skipped.`; + clampSkill(seat) { return Math.max(1, Math.min(5, Math.round(this.skillFor(seat)))); } + + speech(seat, text) { + const at = seat === 0 ? { x: CX, y: 860 } : handHome(this.L, seat); + const t = this.add.text(at.x, at.y - 10, text, { + fontFamily: 'Righteous', fontSize: '26px', color: '#1a0e06', backgroundColor: '#fff4d6', padding: { x: 12, y: 6 }, + }).setOrigin(0.5).setDepth(D.float).setScale(0.4); + this.tweens.add({ targets: t, scale: 1, duration: 180, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, y: t.y - 24, delay: 1100, duration: 350, onComplete: () => t.destroy() }); + } + + // When someone goes down to one card without calling, the others may catch it. + scheduleCatches(victim) { + for (let s = 1; s < this.playerCount; s++) { + if (s === victim) continue; + const k = this.clampSkill(s); + if (Math.random() >= CATCH_CHANCE[k]) continue; + const token = this.turnToken; + const delay = CATCH_DELAY[k] * this.pace() * (0.8 + Math.random() * 0.5); + this.time.delayedCall(delay, () => { + if (!this.alive() || !this.gs || !canCatchUno(this.gs, s) || this.gs.unoVulnerable !== victim) return; + if (this.mode === 'ending' || this.mode === 'summary') return; + void token; + this.speech(s, victim === 0 ? 'You didn\'t say UNO!' : 'Gotcha — UNO!'); + this.commit(applyCatchUno(this.gs, s)); + }); + } + } + + // ── Layout ────────────────────────────────────────────────────────────────── + deckTop() { + const n = this.gs.drawPile.length; + return { ...this.L.deck, y: this.L.deck.y - stackLift(n, this.L.deck.s, 0.12, 14) }; + } + + heldIds() { return this.gs.players[0].hand.map(c => c.id); } + + computeLayout() { + const L = this.L, gs = this.gs; + const visible = new Map(), loc = new Map(); + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + const dn = gs.drawPile.length; + const deckPose = this.deckTop(); + gs.drawPile.forEach((card, i) => { + if (i === dn - 1) put(card, { kind: 'deck', pose: deckPose, faceUp: false, depth: D.cards + 1 }); + else loc.set(card.id, { pose: deckPose, faceUp: false, depth: D.cards }); + }); + const pn = gs.discardPile.length; + gs.discardPile.forEach((card, i) => { + const j = jitterFor(`uno-${card.id}`); + const lift = stackLift(Math.min(pn, 40), L.discard.s, 0.12, 8) * ((i + 1) / pn); + const pose = { ...L.discard, x: L.discard.x + j.x * 5, y: L.discard.y - lift + j.y * 4, rot: j.rot * 7 }; + if (i >= pn - 4) put(card, { kind: 'discard', pose, faceUp: true, depth: D.cards + 1 + (i - pn + 4) * 0.01 }); + else loc.set(card.id, { pose, faceUp: true, depth: D.cards }); + }); + const mine = this.isMyPlayTurn() ? new Set(legalPlays(gs, 0)) : null; + for (const p of gs.players) { + if (p.seat === 0) { + const ids = this.dragPreview ?? p.hand.map(c => c.id); + const n = ids.length; + ids.forEach((id, i) => { + const card = p.hand.find(c => c.id === id); + if (!card) return; + let lift = 0; + if (id === this.hoverId) lift = 26; + else if (mine?.has(id) && this.settings.hints) lift = 10; + if (id === this.gs.pendingDrawn?.id && gs.phase === 'mustPlayDrawn' && gs.currentPlayer === 0) lift = 40; + put(card, { kind: 'hand', seat: 0, idx: i, pose: handPose(L, 0, i, n, lift), faceUp: true, depth: D.hand + i * 0.01, legal: mine?.has(id) }); + }); + } else { + p.hand.forEach((card, i) => put(card, { + kind: 'hand', seat: p.seat, idx: i, pose: handPose(L, p.seat, i, p.hand.length), faceUp: this.revealAll, depth: D.oppHand + i * 0.01, + })); + } + } + return { visible, loc }; + } + + decorate(c, v) { + let mark = '', color = '#ffffff'; + const mineTurn = v.kind === 'hand' && v.seat === 0 && this.isMyPlayTurn(); + if (mineTurn && this.settings.hints && this.suggested === v.card.id) { mark = '★'; color = '#ffd35a'; } + c.mark.setText(mark).setColor(color).setVisible(!!mark && v.faceUp); + c.chip.setVisible(false); + // dim what can't be played on your turn + const dim = mineTurn && this.settings.hints && v.legal === false; + c.faceImg.setTint(dim ? 0x9a948a : 0xffffff); + const glow = v.kind === 'hand' && v.seat === 0 && (v.card.id === this.selectedId + || (this.gs.phase === 'mustPlayDrawn' && this.gs.currentPlayer === 0 && v.card.id === this.gs.pendingDrawn?.id)); + c.glow.setVisible(glow); + } + + beforeLayout() { + this.suggested = this.isMyPlayTurn() ? suggestPlay(this.gs, 0) : null; + } + + afterLayout() { + this.drawSlabs(); + this.drawHalo(); + this.updateBadges(); + this.deckTxt.setText(this.gs.drawPile.length ? `${this.gs.drawPile.length} left` : ''); + } + + drawSlabs() { + const g = this.slabG; + g.clear(); + const n = this.gs.drawPile.length; + if (n <= 1) return; + const lift = stackLift(n, this.L.deck.s, 0.12, 14); + const layers = Math.max(1, Math.min(8, Math.ceil(lift / 1.6))); + for (let j = 0; j < layers; j++) { + const p = { ...this.L.deck, y: this.L.deck.y - (lift * j) / layers }; + const { sx, sy } = { sx: p.s, sy: p.s * SQ }; + g.fillStyle(j % 2 ? 0xf3ece0 : 0xd9d0c0, 1); + g.fillRoundedRect(p.x - (CARD_W / 2) * sx, p.y - (CARD_H / 2) * sy, CARD_W * sx, CARD_H * sy, 8); + g.lineStyle(1, 0x000000, 0.25); + g.strokeRoundedRect(p.x - (CARD_W / 2) * sx, p.y - (CARD_H / 2) * sy, CARD_W * sx, CARD_H * sy, 8); + } + } + + drawHalo() { + const g = this.haloG; + g.clear(); + const c = this.gs.currentColor; + if (!c) return; + const d = this.L.discard; + const col = COLOR_INT[c]; + for (let i = 0; i < 6; i++) { + g.lineStyle(10 - i, col, 0.08 + i * 0.05); + g.strokeEllipse(d.x, d.y + 2, CARD_W * d.s * 1.9 - i * 8, CARD_H * d.s * SQ * 1.45 - i * 6); + } + if (!this.haloTw) this.haloTw = this.tweens.add({ targets: g, alpha: { from: 1, to: 0.55 }, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + } + + drawRing() { + const g = this.ringG; + g.clear(); + const c = this.gs.currentColor; + const col = c ? COLOR_INT[c] : 0xf2ead8; + const pts = ringPoints(16, this.ringPhase); + const dir = this.gs.direction ?? 1; + for (const p of pts) { + const s = 9 * p.s; + const a = p.ang + (dir > 0 ? 0 : Math.PI); + const ax = Math.cos(a), ay = Math.sin(a); + const nx = -ay, ny = ax; + g.fillStyle(col, 0.5); + g.fillTriangle(p.x + ax * s * 1.3, p.y + ay * s * 1.3 * SQ, p.x - ax * s + nx * s, p.y + (-ay * s + ny * s) * SQ, p.x - ax * s - nx * s, p.y + (-ay * s - ny * s) * SQ); + } + } + + 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)).setColor(n <= 2 ? '#ffb15a' : COLORS.textHex); + const danger = n === 1 && !isHandOver(this.gs); + if (danger && !b.tw) { b.ring.setAlpha(0.6); 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); } + } + } + + updatePlates() { + if (!this.gs) return; + const gs = this.gs; + for (let s = 0; s < this.playerCount; s++) { + const pl = this.plates[s]; + const p = gs.players[s]; + pl.scoreTxt.setText(gs.target > 0 ? `${gs.scores[s] + (this.plateTally?.[s] ?? 0)}` : `${this.handsWon(s)} won`); + pl.infoTxt.setText(`${p.hand.length} card${p.hand.length === 1 ? '' : 's'}`).setColor(p.hand.length <= 2 ? '#ffb15a' : COLORS.goldHex); + pl.statusTxt.setText(p.hand.length === 1 && !isHandOver(gs) ? (gs.unoCalled[s] ? 'UNO! ✓' : 'no UNO?') : '') + .setColor(gs.unoCalled[s] ? '#8ce99a' : '#ff8a7a'); + this.setPlateActive(s, !isHandOver(gs) && this.actorSeat() === s && (this.mode === 'human' || this.mode === 'ai')); + } + } + + handsWon(seat) { return this.history.filter(h => h.winner === seat).length; } + + // ── Dock ──────────────────────────────────────────────────────────────────── + isMyPlayTurn() { + return this.mode === 'human' && this.gs?.phase === 'play' && this.gs.currentPlayer === 0; + } + + canAct() { return this.mode === 'human' && !this.modal && !this.paused && !this.busy; } + + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const extra = []; + const me = gs.players[0]; + if (me.hand.length <= 2 && me.hand.length > 0 && !gs.unoCalled[0] && !isHandOver(gs) + && ((gs.currentPlayer === 0 && me.hand.length === 2) || gs.unoVulnerable === 0)) { + extra.push({ label: 'UNO! (U)', act: () => this.callUno(), hot: true }); + } + if (canCatchUno(gs, 0)) extra.push({ label: 'Catch! (C)', act: () => this.catchUno(), hot: true }); + if (this.mode === 'deal') { this.setDock('Shuffling and dealing…'); return; } + if (this.mode === 'ending' || this.mode === 'summary') { this.setDock('Hand over — counting up.'); return; } + if (this.mode !== 'human') { + const seat = this.actorSeat(); + this.setDock(canCatchUno(gs, 0) ? `${this.shortName(gs.unoVulnerable)} didn't call UNO — catch them!` : `${this.nameForSeat(seat)} is playing…`, extra); + return; + } + if (gs.phase === 'choosingColor') { + this.setDock(extra.some(b => b.label.startsWith('UNO')) ? 'Pick the new colour — and press U to call UNO!' : 'Pick the new colour.', ['r', 'y', 'g', 'b'].map(c => ({ label: `${COLOR_NAME[c]} (${c.toUpperCase()})`, act: () => this.chooseColor(c) }))); + return; + } + if (gs.phase === 'challengeWindow') { + const pw = gs.pendingWild4; + const odds = Math.round(challengeOdds(gs, 0) * 100); + const stack = stackableWild4(gs, 0); + this.setDock( + `${this.shortName(pw.playerSeat)} played Wild +${pw.count}. Bluff? A challenge wins if they held a ${COLOR_NAME[pw.priorColor] ?? 'match'} (≈${odds}% likely). Lose → +${pw.count + 2}.`, + [ + { label: 'Challenge', act: () => this.challenge(true), hot: odds >= 50 }, + { label: `Take +${pw.count}`, act: () => this.challenge(false) }, + stack.length ? { label: 'Stack +4', act: () => this.stackWild4(stack[0]), hot: true } : null, + ...extra, + ].slice(0, 4), + ); + return; + } + if (gs.phase === 'mustPlayDrawn') { + this.setDock(`You drew a ${this.cardName(gs.pendingDrawn)} — play it or keep it?`, [ + { label: 'Play it (P)', act: () => this.playDrawn(), hot: true }, + { label: 'Keep it (K)', act: () => this.keepDrawn() }, + ...extra, + ].slice(0, 4)); + return; + } + if (gs.pendingDraw) { + this.setDock(`+${gs.pendingDraw.count} coming your way! Stack a Draw 2 to pass it on, or take them.`, [ + { label: `Take +${gs.pendingDraw.count} (D)`, act: () => this.draw() }, + ...extra, + ]); + return; + } + const top = topDiscard(gs); + const n = legalPlays(gs, 0).length; + this.setDock( + n ? `Your turn — match ${COLOR_NAME[gs.currentColor] ?? 'the colour'} or the ${this.cardName(top).replace(/^\w+ /, '')}. ${n} card${n === 1 ? '' : 's'} can go.` + : 'Nothing matches — draw a card.', + [{ label: 'Draw (D)', act: () => this.draw(), hot: n === 0 }, ...extra], + ); + } + + // ── Human actions ─────────────────────────────────────────────────────────── + sortHand() { + if (!this.gs || this.settings.sort === 'manual') return; + const hand = this.gs.players[0].hand; + hand.sort(this.settings.sort === 'number' ? byNumber : byColor); + } + + playCard(id, { confirmed = false } = {}) { + if (!this.canAct()) return false; + const gs = this.gs; + if (gs.phase === 'mustPlayDrawn') { + if (id === gs.pendingDrawn?.id) { this.playDrawn(); return true; } + this.nudge(id); + return false; + } + if (gs.phase === 'challengeWindow') { + if (stackableWild4(gs, 0).includes(id)) { this.stackWild4(id); return true; } + this.nudge(id); + return false; + } + if (!this.isMyPlayTurn()) return false; + const card0 = gs.players[0].hand.find(c => c.id === id); + if (card0 && !confirmed && isBluff(gs, card0, gs.players[0].hand)) { + this.confirm('Bluff with the Wild +4?', `You still hold a ${COLOR_NAME[gs.currentColor]} card. If ${this.shortName(nextSeat(gs, 0, 1))} challenges, you draw 4 instead.`, 'Bluff it', () => this.playCard(id, { confirmed: true }), { no: 'Play fair' }); + return false; + } + const next = applyPlay(gs, 0, id); + if (next === gs) { + this.nudge(id); + const card = gs.players[0].hand.find(c => c.id === id); + const why = gs.pendingDraw ? 'Only a Draw 2 can be stacked' : 'Doesn\'t match'; + this.floatText({ x: CX, y: 870 }, why, '#ff9a7a', { size: 20 }); + return false; + } + this.selectedId = null; + this.commit(next); + playSound(this, SFX.CARD_PLACE); + this.afterHuman(); + return true; + } + + afterHuman() { + if (isHandOver(this.gs)) { this.onHandOver(); return; } + if (this.actorSeat() === 0) { + this.layout(); + this.updateDock(); + if (this.gs.phase === 'choosingColor') this.openWheel(); + return; + } + this.mode = 'idle'; + this.updateDock(); + this.time.delayedCall(260, () => this.advance()); + } + + draw() { + if (!this.canAct() || !this.isMyPlayTurn()) return; + const next = applyDraw(this.gs, 0); + if (next === this.gs) return; + playSound(this, SFX.CARD_DEAL); + this.commit(next); + if (next.phase === 'mustPlayDrawn') this.flashGlow(next.pendingDrawn.id, 0x7cf0a0, { delay: 260 }); + else if (next.lastAction?.kind === 'draw') this.floatText({ x: CX, y: 870 }, next.lastAction.count > 1 ? `Drew ${next.lastAction.count} — no luck` : 'No match — turn passes', '#f2d6a0', { size: 20 }); + this.afterHuman(); + } + + playDrawn() { + if (!this.canAct() || this.gs.phase !== 'mustPlayDrawn') return; + const next = applyPlayDrawn(this.gs, 0); + if (next === this.gs) return; + this.commit(next); + playSound(this, SFX.CARD_PLACE); + this.afterHuman(); + } + + keepDrawn() { + if (!this.canAct() || this.gs.phase !== 'mustPlayDrawn') return; + const next = applyPassAfterDraw(this.gs, 0); + if (next === this.gs) return; + this.commit(next); + this.afterHuman(); + } + + chooseColor(c) { + if (!this.canAct() || this.gs.phase !== 'choosingColor' || this.actorSeat() !== 0) return; + const next = applyChooseColor(this.gs, c); + if (next === this.gs) return; + this.closeWheel(); + this.commit(next); + this.afterHuman(); + } + + challenge(yes) { + if (!this.canAct() || this.gs.phase !== 'challengeWindow') return; + const next = applyChallengeWild4(this.gs, yes); + if (next === this.gs) return; + this.commit(next); + this.afterHuman(); + } + + stackWild4(id) { + if (!this.canAct()) return; + const next = applyStackWild4(this.gs, 0, id); + if (next === this.gs) { this.nudge(id); return; } + this.commit(next); + playSound(this, SFX.CARD_PLACE); + this.afterHuman(); + } + + callUno() { + if (!this.gs) return; + const next = applyCallUno(this.gs, 0); + if (next === this.gs) return; + this.speech(0, 'UNO!'); + this.commit(next); + } + + catchUno() { + if (!this.gs || !canCatchUno(this.gs, 0)) return; + const victim = this.gs.unoVulnerable; + this.speech(0, 'You didn\'t say UNO!'); + this.commit(applyCatchUno(this.gs, 0)); + this.portraits[victim]?.playEmotion?.('upset'); + } + + // ── Colour wheel ──────────────────────────────────────────────────────────── + openWheel() { + if (this.wheel) return; + const d = this.L.discard; + const objs = []; + const R = 150, r0 = 66; + const order = ['r', 'y', 'g', 'b']; + order.forEach((c, i) => { + const a0 = -Math.PI / 2 + (i * Math.PI) / 2 - Math.PI / 4, a1 = a0 + Math.PI / 2; + const g = this.add.graphics().setDepth(D.modal - 4); + const drawWedge = (hot) => { + g.clear(); + g.fillStyle(COLOR_INT[c], hot ? 1 : 0.88); + g.slice(d.x, d.y, hot ? R + 12 : R, a0 + 0.04, a1 - 0.04, false); + g.fillPath(); + g.fillStyle(0x000000, 0.25); + g.slice(d.x, d.y, r0, a0, a1, false); + g.fillPath(); + g.lineStyle(3, 0xfffaf0, 0.9); + g.beginPath(); + g.arc(d.x, d.y, hot ? R + 12 : R, a0 + 0.04, a1 - 0.04); + g.strokePath(); + }; + drawWedge(false); + const mid = (a0 + a1) / 2; + const lbl = this.add.text(d.x + Math.cos(mid) * (R * 0.72), d.y + Math.sin(mid) * (R * 0.72), COLOR_NAME[c], { + fontFamily: 'Righteous', fontSize: '20px', color: '#fffaf0', stroke: '#1a0e06', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.modal - 3); + const z = this.add.zone(d.x + Math.cos(mid) * (R * 0.66), d.y + Math.sin(mid) * (R * 0.66), R * 0.7, R * 0.7).setInteractive({ useHandCursor: true }).setDepth(D.modal - 2); + z.isTableZone = true; + z.on('pointerover', () => drawWedge(true)); + z.on('pointerout', () => drawWedge(false)); + z.on('pointerup', () => this.chooseColor(c)); + objs.push(g, lbl, z); + g.setScale(0.2).setAlpha(0); + g.x = d.x * 0.8; g.y = d.y * 0.8; + this.tweens.add({ targets: g, scale: 1, x: 0, y: 0, alpha: 1, duration: 220, ease: 'Back.easeOut' }); + }); + const title = this.add.text(d.x, d.y - R - 30, 'Pick a colour', { + fontFamily: 'Righteous', fontSize: '24px', color: '#fffaf0', stroke: '#1a0e06', strokeThickness: 5, + }).setOrigin(0.5).setDepth(D.modal - 3); + objs.push(title); + this.wheel = objs; + } + + closeWheel() { + if (!this.wheel) return; + for (const o of this.wheel) o.destroy(); + this.wheel = null; + } + + // ── Input ────────────────────────────────────────────────────────────────── + setupInput() { + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + } + + liftFor(ids) { + const legal = this.isMyPlayTurn() && this.settings.hints ? new Set(legalPlays(this.gs, 0)) : null; + return (i) => (ids[i] === this.hoverId ? 26 : legal?.has(ids[i]) ? 10 : 0); + } + + handIndexAt(pt) { + const ids = this.heldIds(); + const i = fanHit(this.L.seats[0].fan, ids.length, pt, this.liftFor(ids)); + return i >= 0 ? ids[i] : null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState) return; + if (this.overUI(over)) return; + if (this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const id = this.handIndexAt(pointer); + if (id != null) { this.potentialDrag = { id, x: pointer.x, y: pointer.y }; return; } + if (inPose(pointer, this.deckTop(), 10)) { this.draw(); return; } + } + + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.x, dy = pointer.y - this.potentialDrag.y; + if (dx * dx + dy * dy > 64) this.startDrag(pointer); + return; + } + if (pointer.isDown || this.modal || !this.gs || this.mode === 'deal' || this.mode === 'ending' || this.mode === 'summary') return; + const id = this.handIndexAt(pointer); + if (id !== this.hoverId) { this.hoverId = id; this.layout({ duration: 120 }); } + let cursor = id != null ? 'pointer' : 'default'; + if (id == null && this.isMyPlayTurn() && inPose(pointer, this.deckTop(), 10)) 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 (!this.canAct()) { + if (this.mode === 'ai') this.floatText({ x: CX, y: 870 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); + return; + } + this.playCard(pd.id); + } + + startDrag(pointer) { + const pd = this.potentialDrag; + this.potentialDrag = null; + const c = this.sprites.get(pd.id); + if (!c) return; + c._tw?.stop(); + c._tw = null; + c.setDepth(D.drag); + c.glow.setVisible(false); + this.dragState = { id: pd.id, offX: c.pose.x - pd.x, offY: c.pose.y - pd.y, sprite: c, target: null, previewKey: '' }; + this.hoverId = null; + this.input.setDefaultCursor('grabbing'); + this.updateDrag(pointer); + } + + dropTargetAt(pt) { + if (inPose(pt, this.L.discard, 50)) return { type: 'play' }; + const ids = this.heldIds(); + if (inRect(pt, fanZone(this.L.seats[0].fan, ids.length))) return { type: 'hand', at: fanInsertIndex(this.L.seats[0].fan, ids.length, pt.x) }; return null; } - /** - * Inspects the state transition's log entries for visual effects (skip, reverse, - * draw cards into opponents' hands) and animates each in a brief banner. - */ - handleLogEffects(before, after, onDone) { - const oldLen = before.log.length; - let drawAnim = null; - for (let i = oldLen; i < after.log.length; i++) { - const e = after.log[i]; - if (e.kind === 'skip') { - this.opponentPortraits[e.seat]?.playEmotion('upset'); - this.showSkipOverlay(e.seat); - this.showBanner(`${this.opponentName(e.seat)} is skipped!`); - this.time.delayedCall(900, () => this.hideBanner()); - } else if (e.kind === 'reverse') { - this.showBanner('Direction reversed.'); - this.time.delayedCall(900, () => this.hideBanner()); - } else if (e.kind === 'draw2') { - this.opponentPortraits[e.seat]?.playEmotion('upset'); - this.showBanner(`${this.opponentName(e.seat)} draws 2 and is skipped.`); - this.time.delayedCall(1100, () => this.hideBanner()); - drawAnim = { seat: e.seat, count: e.count ?? 2 }; - } else if (e.kind === 'wild4Accept' || e.kind === 'wild4ChallengeLose' || e.kind === 'wild4ChallengeWin') { - this.opponentPortraits[e.seat]?.playEmotion('upset'); - drawAnim = { seat: e.seat, count: e.count ?? 4 }; - } else if (e.kind === 'play') { - const playedCard = before.players[e.seat]?.hand?.find((c) => c.id === e.cardId); - if (playedCard?.kind === 'wild4') { - this.opponentPortraits[e.seat]?.playEmotion('happy'); - } - } else if (e.kind === 'win') { - // handled by endGame + updateDrag(pointer) { + const ds = this.dragState; + const x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const t = Math.max(0, Math.min(1, (y - 600) / 360)); + const s = this.L.discard.s + (1 - this.L.discard.s) * t; + this.applyPose(ds.sprite, { x, y, rot: 0, s, q: SQ + (1 - SQ) * t }, 1); + ds.target = this.dropTargetAt(pointer); + const order = ds.target?.type === 'hand' ? CardTableScene.reorderPreview(this.heldIds(), ds.id, ds.target.at) : null; + const key = order ? order.join(',') : ''; + if (key !== ds.previewKey) { + ds.previewKey = key; + this.dragPreview = order; + this.layout({ duration: 150 }); + } + if (order) { + const idx = order.indexOf(ds.id); + this.drawDropSlot(handPose(this.L, 0, idx, order.length), D.hand + idx * 0.01 - 0.004); + } else this.drawDropSlot(null); + const g = this.targetG; + g.clear(); + const legal = this.isMyPlayTurn() && legalPlays(this.gs, 0).includes(ds.id) + || (this.gs.phase === 'challengeWindow' && stackableWild4(this.gs, 0).includes(ds.id)) + || (this.gs.phase === 'mustPlayDrawn' && this.gs.pendingDrawn?.id === ds.id); + if (legal && this.mode === 'human') { + const d = this.L.discard; + const hot = ds.target?.type === 'play'; + const hw = (CARD_W / 2) * d.s + 18, hh = (CARD_H / 2) * d.s * SQ + 18; + g.fillStyle(0x7cf0a0, hot ? 0.22 : 0.08); + g.fillRoundedRect(d.x - hw, d.y - hh, hw * 2, hh * 2, 14); + g.lineStyle(hot ? 4 : 2.5, 0x7cf0a0, hot ? 1 : 0.8); + g.strokeRoundedRect(d.x - hw, d.y - hh, hw * 2, hh * 2, 14); + } + } + + cancelDrag() { + if (!this.dragState) return; + this.dragState = null; + this.dragPreview = null; + this.drawDropSlot(null); + this.targetG?.clear(); + this.layout(); + } + + endDrag(pointer) { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.targetG.clear(); + const t = ds.target ?? this.dropTargetAt(pointer); + this.drawDropSlot(null); + if (t?.type === 'hand') { + const order = CardTableScene.reorderPreview(this.heldIds(), ds.id, t.at); + const hand = this.gs.players[0].hand; + const byId = new Map(hand.map(c => [c.id, c])); + const changed = order.join(',') !== hand.map(c => c.id).join(','); + hand.splice(0, hand.length, ...order.map(id => byId.get(id))); + if (changed && this.settings.sort !== 'manual') { + this.settings.sort = 'manual'; + this.saveSettings(); + this.refreshSortButtons(); + } + this.dragPreview = null; + this.layout(); + return; + } + this.dragPreview = null; + if (t?.type === 'play' && this.canAct() && this.playCard(ds.id)) return; + this.layout(); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) this.openPause(); + return; + } + if (this.modal) { if (e.code === 'Enter') this.modal.onEnter?.(); return; } + if (this.dragState) return; + const k = e.key?.toLowerCase(); + if (k === 'u') { this.callUno(); return; } + if (k === 'c') { this.catchUno(); return; } + if (k === 's') { this.cycleSort(); return; } + if (k === 'h') { this.flashHint(); return; } + if (!this.canAct()) return; + if (this.gs.phase === 'choosingColor' && 'rygb'.includes(k) && k.length === 1) { this.chooseColor(k); return; } + if (k === 'd') this.draw(); + else if (k === 'p') this.playDrawn(); + else if (k === 'k') this.keepDrawn(); + } + + cycleSort() { + const order = ['color', 'number', 'manual']; + this.settings.sort = order[(order.indexOf(this.settings.sort) + 1) % order.length]; + this.saveSettings(); + this.refreshSortButtons(); + this.sortHand(); + this.layout(); + } + + flashHint() { + if (!this.gs || this.mode !== 'human') return; + let text, id = null; + if (this.gs.phase === 'challengeWindow') { + const p = challengeOdds(this.gs, 0); + text = p > 2 / ((this.gs.pendingWild4.count ?? 4) + 2) ? `Challenging pays off on average (≈${Math.round(p * 100)}% to win).` : 'Probably safer to take the cards.'; + } else if (this.gs.phase === 'mustPlayDrawn') { text = 'Usually play it — fewer cards, fewer points.'; id = this.gs.pendingDrawn?.id; } + else if (this.gs.phase === 'choosingColor') { + const t = { r: 0, y: 0, g: 0, b: 0 }; + for (const c of this.gs.players[0].hand) if (c.color !== 'w') t[c.color]++; + const best = Object.keys(t).sort((a, b) => t[b] - t[a])[0]; + text = `Pick ${COLOR_NAME[best]} — you hold the most of it.`; + } else { + id = suggestPlay(this.gs, 0); + text = id != null ? `Try the ${this.cardName(this.gs.players[0].hand.find(c => c.id === id))}.` : 'Nothing to play — draw.'; + } + this.floatText({ x: CX, y: 880 }, text, '#7cf0a0', { size: 22, ms: 2200, rise: 20 }); + if (id != null) this.flashGlow(id, 0x7cf0a0, { delay: 0, hold: 900 }); + } + + // ── Menus ─────────────────────────────────────────────────────────────────── + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Score sheet', act: () => { this.closeModal(); this.openScorePad({ readOnly: true }); } }, + { label: 'House rules', act: () => { this.closeModal(); this.openRules(); } }, + { label: 'New game', ghost: true, act: () => this.confirm('Start a new game?', 'This match will be thrown out.', 'New game', () => this.restart()) }, + { label: 'Leave table', ghost: true, act: () => this.onLeave() }, + ]); + } + + openSettings(onDone = null) { + const s = this.settings; + this.openSettingsModal([ + { label: 'Opponent pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } }, + { label: 'Hints (★ best play · dim unplayable)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; this.layout(); } }, + { label: 'Play to', options: [[0, 'One hand'], [250, '250'], [500, '500']], get: () => s.target, set: (v) => { s.target = v; if (this.gs && this.mode !== 'summary') this.gs.target = v; this.updatePlates(); } }, + { label: 'House rule: stacking +2 / +4', options: [[false, 'Off'], [true, 'On']], get: () => s.stacking, set: (v) => { s.stacking = v; } }, + { label: 'House rule: draw until playable', options: [[false, 'Off'], [true, 'On']], get: () => s.drawUntil, set: (v) => { s.drawUntil = v; } }, + { label: 'Hand order', options: [['color', 'Color'], ['number', '1·2·3'], ['manual', 'Mine']], get: () => s.sort, set: (v) => { s.sort = v; this.refreshSortButtons(); this.sortHand(); this.layout(); } }, + ], { note: 'House rules start with the next hand. Opponent hands also move at their skill\'s speed.', onDone }); + } + + openRules() { + const h = 640; + this.openModal({ w: 900, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 54, 'How to play', { fontFamily: 'Righteous', fontSize: '38px', color: COLORS.goldHex }); + const st = this.gs?.rules ?? {}; + const lines = [ + 'Match the top card by colour, number or symbol — or play a Wild.', + 'Can\'t (or won\'t) play? Draw. A playable draw may be played straight away.', + 'Skip: next player misses a turn · Reverse: direction flips (2 players: acts as Skip)', + 'Draw 2: next player draws 2 and misses a turn.', + 'Wild Draw 4: meant for when nothing matches the colour — bluff at your peril.', + ' The next player may challenge: bluff caught → you draw 4 · honest → they draw 6.', + 'Down to one card? Call UNO! (U) — get caught without it and you draw 2.', + 'Catch others who forget (C) before the next player moves.', + 'Going out scores every card left in the other hands: numbers face value,', + ' actions 20, wilds 50.', + `House rules this hand: stacking ${st.stacking ? 'ON' : 'off'} · draw until playable ${st.drawUntilPlayable ? 'ON' : 'off'}`, + ]; + lines.forEach((l, i) => this.addToModal(this.add.text(CX - 400, top + 118 + i * 38, l, { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: i === lines.length - 1 ? COLORS.goldHex : COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1))); + this.modalButton(CX, top + h - 46, 'Back to the table', () => this.closeModal(), { width: 280, height: 46, fontSize: 18 }); + } + + onLeave() { + const inMatch = this.history.length > 0 || this.mode === 'human' || this.mode === 'ai'; + if (!inMatch || this.gs?.phase === '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' }); + } + + restart() { + this.closeModal(); + this.scene.restart({ game: this.gameDef, opponents: this.opponents, playfield: this.playfield, cardBack: this.cardBack }); + } + + openScorePad({ result = null, readOnly = false } = {}) { + if (!this.gs) return; + const gs = this.gs; + const over = gs.phase === 'gameOver' && !readOnly; + const single = gs.target <= 0; + let title; + if (readOnly) title = single ? 'Hands so far' : `Score sheet — first to ${gs.target}`; + else if (over) title = gs.matchWinner === 0 ? 'You win the match!' : `${this.nameForSeat(gs.matchWinner)} wins the match!`; + else title = result.winner === 0 ? `Hand ${gs.handNum} — you went out!` : `Hand ${gs.handNum} — ${this.nameForSeat(result.winner)} went out`; + const best = Math.max(...gs.scores); + const rows = gs.players.map((p, s) => ({ + seat: s, color: SEAT_COLORS[s], name: this.shortName(s, 14), + cells: this.history.map(h => (h.winner === s ? { text: `+${h.points}`, color: '#1c3f8f', mark: '★', markColor: '#b8231f' } : { text: '—', color: '#8a7e66' })), + total: single ? this.handsWon(s) : gs.scores[s], + totalColor: (single ? this.handsWon(s) === Math.max(...gs.players.map((_, k) => this.handsWon(k))) : gs.scores[s] === best && best > 0) ? '#b8231f' : '#22201a', + circled: over && s === gs.matchWinner, + })); + const buttons = []; + if (readOnly) buttons.push({ label: 'Back to the table', act: () => this.closeModal() }); + else { + buttons.push(over ? { label: 'Play again', act: () => this.restart(), hot: true } : { label: 'Next hand', act: () => this.nextHand(), hot: true }); + buttons.push({ label: 'Settings', ghost: true, act: () => { this.closeModal(); this.openSettings(() => this.openScorePad({ result })); } }); + buttons.push({ label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }); + } + this.openScorePadModal({ + title, titleColor: over && gs.matchWinner === 0 ? '#b8231f' : '#22201a', + sub: single ? 'One hand: first out wins' : 'The player who goes out scores the cards left in everyone else\'s hand', + columns: this.history.map((_, i) => `H${i + 1}`), + rows, writeLast: !!result, buttons, readOnly, + onEnter: !readOnly ? (over ? () => this.restart() : () => this.nextHand()) : null, + }); + } + + async nextHand() { + this.closeModal(); + if (this.gs.phase !== 'handOver' || this.mode !== 'summary') return; + this.mode = 'deal'; + this.updateDock(); + await this.sweepCards({ ...this.L.deck }); + if (!this.alive()) return; + this.gs = startNextHand(this.gs); + this.gs.rules = { stacking: this.settings.stacking, drawUntilPlayable: this.settings.drawUntil }; + this.startHand(); + } + + // ── End of a hand: out! → reveal → count the points → score pad ─────────── + async onHandOver() { + if (this.mode === 'ending' || this.mode === 'summary') return; + this.mode = 'ending'; + this.turnToken++; + this.closeWheel(); + this.cancelDrag(); + this.potentialDrag = null; + this.hoverId = null; + this.input.setDefaultCursor('default'); + for (let s = 1; s < this.playerCount; s++) this.handRest(s, 300); + this.updateDock(); + this.layout(); + const r = this.gs.handResult; + await this.wait(600); + if (!this.alive()) return; + this.stamp(r.winner === 0 ? 'You went out!' : `${this.shortName(r.winner, 14)} went out!`, { x: CX, y: CY - 30 }, SEAT_HEX[r.winner], { size: 88, hold: 1000 }); + playSound(this, r.winner === 0 ? SFX.CASINO_WIN : SFX.CARD_SHOW); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(s === r.winner ? 'happy' : 'upset'); + await this.wait(1250); + if (!this.alive()) return; + this.revealAll = true; + this.layout({ duration: 360 }); + await this.wait(800); + if (!this.alive()) return; + await this.countBack(r); + if (!this.alive()) return; + this.history.push({ winner: r.winner, points: r.points, handNum: this.gs.handNum }); + this.updatePlates(); + if (this.gs.phase === 'gameOver') { + const w = this.gs.matchWinner; + this.recordResult('uno', { score: this.gs.scores[0], opponentScores: this.gs.scores.slice(1), won: w === 0 }); + playSound(this, w === 0 ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < this.playerCount; s++) this.portraits[s]?.playEmotion?.(w === s ? 'win' : 'loss'); + } + this.mode = 'summary'; + this.openScorePad({ result: r }); + } + + // Every card left in a losing hand flies to the winner's plate, adding up. + async countBack(r) { + const pl = this.plates[r.winner]; + const t = pl.tallyTxt; + t.setText('+0').setVisible(true).setAlpha(1).setColor(SEAT_HEX[r.winner]); + const base = this.gs.scores[r.winner] - r.points; + this.plateTally = this.gs.players.map(() => 0); + this.plateTally[r.winner] = -r.points; + this.updatePlates(); + let tally = 0, longest = 0, k = 0; + for (const p of this.gs.players) { + if (p.seat === r.winner) continue; + for (const card of p.hand) { + const c = this.sprites.get(card.id); + if (!c) continue; + this.sprites.delete(card.id); + const delay = k++ * 110; + 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 += card.points; + t.setText(`+${tally}`); + pl.scoreTxt.setText(this.gs.target > 0 ? `${base + tally}` : pl.scoreTxt.text); + this.tweens.add({ targets: t, scale: 1.2, duration: 70, yoyo: true }); + if (k % 2 === 0) playSoundEx(this, SFX.CARD_PLACE, { volume: 0.35, rate: 1.1 }); + }, + }); } } - if (drawAnim) { - this.animateForcedDraw(drawAnim.seat, drawAnim.count, onDone); - } else { - onDone?.(); - } - } - - // ── Animations ──────────────────────────────────────────────────────────── - - animatePlayCard(seat, card, onComplete) { - const layout = slotLayout(this.slotForSeat[seat], this.gs.players.length); - const handFaceUp = layout.handFaceUp; - const isOpponent = seat !== 0; - const fromSprite = this.cardObjs.get(`hand-${seat}-${card.id}`); - let sprite; - if (fromSprite) { - sprite = fromSprite; - this.cardObjs.delete(`hand-${seat}-${card.id}`); - } else { - // Fallback: spawn at the hand center. - sprite = this.makeUnoCardSprite(card, layout.handCenter.x, layout.handCenter.y, { - faceUp: handFaceUp, rotation: layout.rotateCards, - }); - } - sprite.setDepth(D.banner - 4); - this.transientObjs.push(sprite); - - playSound(this, SFX.CARD_PLACE); - this.tweens.add({ - targets: sprite, - x: DISCARD_POS.x, y: DISCARD_POS.y, - rotation: 0, - duration: isOpponent ? 600 : 360, - ease: 'Cubic.easeOut', - onComplete: () => { - if (!handFaceUp) this.renderUnoCardFace(sprite, card, true); - sprite.setDepth(D.card); - if (isOpponent) { - // Showcase: grow then shrink over 1.5 s to spotlight the played card. - this.tweens.add({ - targets: sprite, scaleX: 1.3, scaleY: 1.3, - duration: 750, ease: 'Sine.easeInOut', yoyo: true, - onComplete: () => onComplete && onComplete(), - }); - } else { - // Small bounce for local player. - this.tweens.add({ - targets: sprite, scaleX: 1.08, scaleY: 1.08, yoyo: true, duration: 90, - onComplete: () => onComplete && onComplete(), - }); - } - }, - }); - } - - /** - * Animate a single card being drawn from the draw pile to `seat`'s hand. - * If `reveal` is true (local player), flip the card face-up in place midway. - */ - animateDrawCard(seat, card, reveal, onComplete) { - const layout = slotLayout(this.slotForSeat[seat], this.gs.players.length); - const sprite = this.makeUnoCardSprite(null, DRAW_POS.x, DRAW_POS.y, { - faceUp: false, rotation: layout.rotateCards, - }); - sprite.setDepth(D.banner - 4); - this.transientObjs.push(sprite); - playSound(this, SFX.CARD_DEAL); - - const finishFly = () => { - const dest = { x: layout.handCenter.x, y: layout.handCenter.y }; - this.tweens.add({ - targets: sprite, - x: dest.x, y: dest.y, - rotation: 0, - duration: seat !== 0 ? 650 : 400, - ease: 'Cubic.easeIn', - onComplete: () => onComplete && onComplete(), - }); - }; - - if (reveal && card) { - this.flipCardFaceUp(sprite, card, () => { - this.time.delayedCall(650, finishFly); - }); - } else { - finishFly(); - } - } - - /** - * Animate `count` card backs flying from the draw pile into `seat`'s hand - * (for forced draws — Draw 2, Wild +4 effects). - */ - animateBatchDraw(seat, count, onComplete, timing = {}) { - if (count <= 0) { onComplete && onComplete(); return; } - const layout = slotLayout(this.slotForSeat[seat], this.gs.players.length); - const isOpponent = seat !== 0; - const flyDuration = timing.flyDuration ?? (isOpponent ? 480 : 320); - const stagger = timing.stagger ?? (isOpponent ? 170 : 110); - let remaining = count; - const fire = (i) => { - const sprite = this.makeUnoCardSprite(null, DRAW_POS.x, DRAW_POS.y, { - faceUp: false, rotation: layout.rotateCards, - }); - sprite.setDepth(D.banner - 5); - this.transientObjs.push(sprite); - playSound(this, SFX.CARD_DEAL); - this.tweens.add({ - targets: sprite, - x: layout.handCenter.x, y: layout.handCenter.y, - duration: flyDuration, - ease: 'Cubic.easeIn', - onComplete: () => { - remaining -= 1; - if (remaining === 0) onComplete && onComplete(); - }, - }); - }; - for (let i = 0; i < count; i++) { - this.time.delayedCall(i * stagger, () => fire(i)); - } - } - - flipCardFaceUp(container, card, onComplete) { - this.tweens.add({ - targets: container, scaleX: 0, duration: 150, ease: 'Linear', - onComplete: () => { - container.setRotation(0); - this.renderUnoCardFace(container, card, true); - this.tweens.add({ - targets: container, scaleX: 1, duration: 150, ease: 'Linear', - onComplete: () => onComplete && onComplete(), - }); - }, - }); - } - - shakeCardSprite(sprite) { - if (!sprite) return; - const x0 = sprite.x; - this.tweens.add({ - targets: sprite, - x: { from: x0 - 6, to: x0 }, - duration: 80, yoyo: true, repeat: 2, ease: 'Sine.easeInOut', - }); - } - - showUnoCallout(seat) { - const slot = this.slotForSeat[seat]; - const layout = slotLayout(slot, this.gs.players.length); - const t = this.add.text(layout.portrait.x, layout.portrait.y - 70, 'UNO!', { - fontFamily: 'Righteous', fontSize: '64px', color: '#d32f2f', - stroke: '#ffffff', strokeThickness: 6, - }).setOrigin(0.5).setDepth(D.banner + 2).setScale(0.2); - this.transientObjs.push(t); - playSound(this, SFX.CASINO_WIN); - this.opponentPortraits[seat]?.playEmotion('happy'); - this.tweens.add({ - targets: t, scaleX: 1, scaleY: 1, duration: 280, ease: 'Back.easeOut', - onComplete: () => { - this.tweens.add({ - targets: t, alpha: 0, duration: 600, delay: 700, - onComplete: () => { if (t.active) t.destroy(); }, - }); - }, - }); - } - - showSkipOverlay(skippedSeat) { - const slot = this.slotForSeat[skippedSeat]; - const layout = slotLayout(slot, this.gs.players.length); - const { x: px, y: py, r: pr } = layout.portrait; - const r = pr + 8; - const size = r * 2; - const strokeW = Math.round(r * 0.09); - const slashW = Math.round(r * 0.13); - - // Build as a DOM element so it renders above the portrait video layer. - const el = document.createElement('div'); - el.style.cssText = `width:${size}px;height:${size}px;border-radius:50%;background:transparent;border:${strokeW}px solid rgba(204,0,0,0.95);box-sizing:border-box;position:relative;overflow:hidden;`; - const slash = document.createElement('div'); - slash.style.cssText = `position:absolute;width:${slashW}px;height:${Math.round(size * 1.1)}px;background:rgba(204,0,0,0.95);border-radius:${Math.round(slashW / 2)}px;top:50%;left:50%;transform:translate(-50%,-50%) rotate(-45deg);`; - el.appendChild(slash); - - const domObj = this.add.dom(DISCARD_POS.x, DISCARD_POS.y, el); - domObj.setDepth(D.banner); - domObj.setScale(0.2); - this.transientObjs.push(domObj); - - this.tweens.add({ - targets: domObj, - x: px, y: py, - scaleX: 1, scaleY: 1, - duration: 1500, - ease: 'Back.easeOut', - }); - } - - animateForcedDraw(seat, count, onDone) { - const label = `+${count}`; - const t = this.add.text(CX, CY - CARD_H - 20, label, { - fontFamily: 'Righteous', - fontSize: '90px', - color: '#ff3030', - stroke: '#ffffff', - strokeThickness: 8, - }).setOrigin(0.5).setDepth(D.banner + 1).setScale(0); - this.transientObjs.push(t); - - this.tweens.add({ - targets: t, - scaleX: 1, scaleY: 1, - duration: 450, - ease: 'Back.easeOut', - onComplete: () => { - this.animateBatchDraw(seat, count, () => { - this.tweens.add({ - targets: t, - scaleX: 0, scaleY: 0, - alpha: 0, - duration: 300, - ease: 'Back.easeIn', - onComplete: () => onDone?.(), - }); - }, { flyDuration: 700, stagger: 350 }); - }, - }); - } - - // ── Color picker modal ──────────────────────────────────────────────────── - - openColorPicker(onPick) { - if (this.colorPicker) this.closeColorPicker(); - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setDepth(D.modal).setInteractive(); - const title = this.add.text(CX, CY - 170, 'Choose a color', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modalUI); - - const swatchSize = 140; - const gap = 24; - const half = swatchSize / 2; - const positions = { - r: { x: CX - swatchSize / 2 - gap / 2, y: CY - half - gap / 2 }, - y: { x: CX + swatchSize / 2 + gap / 2, y: CY - half - gap / 2 }, - g: { x: CX - swatchSize / 2 - gap / 2, y: CY + half + gap / 2 }, - b: { x: CX + swatchSize / 2 + gap / 2, y: CY + half + gap / 2 }, - }; - const swatches = []; - for (const color of ['r', 'y', 'g', 'b']) { - const pos = positions[color]; - const g = this.add.graphics().setDepth(D.modalUI); - g.fillStyle(UNO_COLOR_HEX[color], 1); - g.fillRoundedRect(pos.x - half, pos.y - half, swatchSize, swatchSize, 12); - g.lineStyle(3, 0xffffff, 0.9); - g.strokeRoundedRect(pos.x - half, pos.y - half, swatchSize, swatchSize, 12); - const label = this.add.text(pos.x, pos.y, UNO_COLOR_NAMES[color], { - fontFamily: 'Righteous', fontSize: '24px', color: '#ffffff', - }).setOrigin(0.5).setDepth(D.modalUI + 1); - const hit = this.add.rectangle(pos.x, pos.y, swatchSize, swatchSize, 0xffffff, 0) - .setInteractive({ useHandCursor: true }).setDepth(D.modalUI + 2); - hit.on('pointerover', () => g.setAlpha(0.85)); - hit.on('pointerout', () => g.setAlpha(1)); - hit.on('pointerdown', () => { - this.closeColorPicker(); - onPick(color); - }); - swatches.push(g, label, hit); - } - this.colorPicker = { overlay, title, swatches }; - } - - closeColorPicker() { - if (!this.colorPicker) return; - this.colorPicker.overlay.destroy(); - this.colorPicker.title.destroy(); - for (const o of this.colorPicker.swatches) o.destroy(); - this.colorPicker = null; - } - - // ── Challenge prompt ────────────────────────────────────────────────────── - - openChallengePrompt() { - if (this.challengePrompt) this.closeChallengePrompt(); - const pw = this.gs.pendingWild4; - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setDepth(D.modal).setInteractive(); - const panel = this.add.rectangle(CX, CY, 720, 280, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modalUI); - const title = this.add.text(CX, CY - 80, `${this.opponentName(pw.playerSeat)} played Wild +4`, { - fontFamily: 'Righteous', fontSize: '32px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modalUI + 1); - const sub = this.add.text(CX, CY - 30, 'Win the challenge: they draw 4.\nLose the challenge: you draw 6 and lose your turn.', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, align: 'center', - }).setOrigin(0.5).setDepth(D.modalUI + 1); - const challengeBtn = new Button(this, CX - 130, CY + 70, 'Challenge', () => { - this.closeChallengePrompt(); - this.executeChallenge(true); - }, { width: 220, height: 56, fontSize: 22 }).setDepth(D.modalUI + 1); - const acceptBtn = new Button(this, CX + 130, CY + 70, 'Accept (draw 4)', () => { - this.closeChallengePrompt(); - this.executeChallenge(false); - }, { variant: 'ghost', width: 240, height: 56, fontSize: 22 }).setDepth(D.modalUI + 1); - this.challengePrompt = { overlay, panel, title, sub, challengeBtn, acceptBtn }; - } - - closeChallengePrompt() { - if (!this.challengePrompt) return; - for (const k of Object.keys(this.challengePrompt)) this.challengePrompt[k].destroy(); - this.challengePrompt = null; - } - - // ── Play-drawn prompt ───────────────────────────────────────────────────── - - openPlayDrawnPrompt() { - if (this.drawnPrompt) this.closeDrawnPrompt(); - const card = this.gs.pendingDrawn; - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.5) - .setDepth(D.modal).setInteractive(); - const panel = this.add.rectangle(CX, CY, 680, 280, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modalUI); - const title = this.add.text(CX, CY - 80, `You drew ${this.describeCard(card)}`, { - fontFamily: 'Righteous', fontSize: '32px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modalUI + 1); - const sub = this.add.text(CX, CY - 30, "Play it now or keep it.", { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modalUI + 1); - const playBtn = new Button(this, CX - 130, CY + 70, 'Play', () => { - this.closeDrawnPrompt(); - this.executeLocalPlayDrawn(); - }, { width: 220, height: 56, fontSize: 22 }).setDepth(D.modalUI + 1); - const keepBtn = new Button(this, CX + 130, CY + 70, 'Keep', () => { - this.closeDrawnPrompt(); - this.executeLocalPassDrawn(); - }, { variant: 'ghost', width: 220, height: 56, fontSize: 22 }).setDepth(D.modalUI + 1); - this.drawnPrompt = { overlay, panel, title, sub, playBtn, keepBtn }; - } - - closeDrawnPrompt() { - if (!this.drawnPrompt) return; - for (const k of Object.keys(this.drawnPrompt)) this.drawnPrompt[k].destroy(); - this.drawnPrompt = null; - } - - executeLocalPlayDrawn() { - const seat = 0; - const card = this.gs.pendingDrawn; - if (!card) return; - if (card.isWild) { - this.openColorPicker((color) => { - const after = applyPlayDrawn(this.gs, seat); - if (after === this.gs) return; - this.animating = true; - this.animatePlayCard(seat, card, () => { - this.gs = after; - this.renderAll(); - if (this.gs.players[seat].hand.length === 1) this.showUnoCallout(seat); - if (this.gs.phase === 'choosingColor') { - this.time.delayedCall(120, () => this.executeChooseColor(color)); - } else { - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - } - }); - }); - return; - } - const before = this.gs; - const after = applyPlayDrawn(before, seat); - if (after === before) return; - this.animating = true; - this.animatePlayCard(seat, card, () => { - this.gs = after; - this.renderAll(); - if (this.gs.players[seat].hand.length === 1) this.showUnoCallout(seat); - this.handleLogEffects(before, after, () => { - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - }); - } - - executeLocalPassDrawn() { - const seat = 0; - const before = this.gs; - const after = applyPassAfterDraw(before, seat); - if (after === before) return; - this.gs = after; - this.renderAll(); - this.updateStatus(); - this.handlePostStateChange(); - } - - closeAnyModal() { - this.closeColorPicker(); - this.closeChallengePrompt(); - this.closeDrawnPrompt(); - } - - // ── AI scheduling ───────────────────────────────────────────────────────── - - handlePostStateChange() { - if (this.animating) return; - if (isGameOver(this.gs)) { this.endGame(); return; } - // If it's our turn but we just entered challengeWindow as the challenger, - // open the prompt. - if (this.gs.phase === 'challengeWindow' && this.gs.pendingWild4?.challengerSeat === 0) { - this.openChallengePrompt(); - return; - } - // If it's our turn but the engine wants a color choice (starting Wild), - // open the picker. - if (this.gs.phase === 'choosingColor' && this.gs.currentPlayer === 0 - && this.pendingWildPlayCardId === null) { - this.openColorPicker((color) => this.executeChooseColor(color)); - return; - } - if (this.isLocalTurn() && this.gs.phase === 'play') return; - if (this.isLocalTurn() && this.gs.phase === 'mustPlayDrawn') { - this.openPlayDrawnPrompt(); - return; - } - // Otherwise, schedule an AI step. - this.time.delayedCall(700, () => this.runAIStep()); - } - - runAIStep() { - if (this.gameOver || this.animating) return; - if (!this.gs) return; - if (isGameOver(this.gs)) { this.endGame(); return; } - - // Some phases require action from a non-current player (challenge window). - let actingSeat = this.gs.currentPlayer; - if (this.gs.phase === 'challengeWindow') actingSeat = this.gs.pendingWild4.challengerSeat; - if (actingSeat === 0) { - // Local needs to act — defer to local input. - if (this.gs.phase === 'challengeWindow') this.openChallengePrompt(); - else if (this.gs.phase === 'mustPlayDrawn') this.openPlayDrawnPrompt(); - else if (this.gs.phase === 'choosingColor') this.openColorPicker((c) => this.executeChooseColor(c)); - else this.updateStatus(); - return; - } - - const action = chooseAction(this.gs, actingSeat); - this.executeAIAction(actingSeat, action); - } - - executeAIAction(seat, action) { - if (!action) return; - const before = this.gs; - - if (action.kind === 'play') { - const card = before.players[seat].hand.find((c) => c.id === action.cardId); - if (!card) return; - const after = applyPlay(before, seat, action.cardId); - if (after === before) return; - this.animating = true; - this.animatePlayCard(seat, card, () => { - this.gs = after; - this.renderAll(); - if (this.gs.players[seat].hand.length === 1) this.showUnoCallout(seat); - this.handleLogEffects(before, after, () => { - // If wild, the AI has a pre-chosen color. - if (action.chosenColor && this.gs.phase === 'choosingColor') { - this.time.delayedCall(450, () => { - const after2 = applyChooseColor(this.gs, action.chosenColor); - this.gs = after2; - this.renderAll(); - this.showBanner(`${this.opponentName(seat)} chose ${UNO_COLOR_NAMES[action.chosenColor]}.`); - this.time.delayedCall(900, () => this.hideBanner()); - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - return; - } - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - }); - return; - } - - if (action.kind === 'draw') { - const after = applyDraw(before, seat); - if (after === before) return; - this.animating = true; - // AI never reveals the drawn card. - this.animateDrawCard(seat, null, false, () => { - this.gs = after; - this.renderAll(); - this.animating = false; - this.updateStatus(); - // If the drawn card was playable, the AI will choose play/pass on the next step. - this.handlePostStateChange(); - }); - return; - } - - if (action.kind === 'playDrawn') { - const card = before.pendingDrawn; - if (!card) return; - const after = applyPlayDrawn(before, seat); - if (after === before) return; - this.animating = true; - this.animatePlayCard(seat, card, () => { - this.gs = after; - this.renderAll(); - if (this.gs.players[seat].hand.length === 1) this.showUnoCallout(seat); - this.handleLogEffects(before, after, () => { - if (this.gs.phase === 'choosingColor') { - // AI just played a wild as the drawn card — pick its color now. - const color = chooseAction(this.gs, seat).color ?? 'r'; - this.time.delayedCall(450, () => { - const after2 = applyChooseColor(this.gs, color); - this.gs = after2; - this.renderAll(); - this.showBanner(`${this.opponentName(seat)} chose ${UNO_COLOR_NAMES[color]}.`); - this.time.delayedCall(900, () => this.hideBanner()); - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - return; - } - this.animating = false; - this.updateStatus(); - this.handlePostStateChange(); - }); - }); - return; - } - - if (action.kind === 'passDrawn') { - const after = applyPassAfterDraw(before, seat); - if (after === before) return; - this.gs = after; - this.renderAll(); - this.updateStatus(); - this.handlePostStateChange(); - return; - } - - if (action.kind === 'chooseColor') { - const after = applyChooseColor(before, action.color); - if (after === before) return; - this.gs = after; - this.renderAll(); - this.showBanner(`${this.opponentName(seat)} chose ${UNO_COLOR_NAMES[action.color]}.`); - this.time.delayedCall(900, () => this.hideBanner()); - this.updateStatus(); - this.handlePostStateChange(); - return; - } - - if (action.kind === 'challenge') { - this.executeChallenge(action.doChallenge); - return; - } - } - - // ── Game over ────────────────────────────────────────────────────────────── - - endGame() { - if (this.gameOver) return; - this.gameOver = true; - this.hideBanner(); - const winner = this.gs.winnerSeat; - const lines = [ - winner === 0 ? 'You won!' : `${this.opponentName(winner)} wins.`, - ]; - for (let s = 0; s < this.gs.players.length; s++) { - lines.push(`${this.opponentName(s)}: ${this.gs.players[s].hand.length} card${this.gs.players[s].hand.length === 1 ? '' : 's'} remaining`); - } - playSound(this, winner === 0 ? SFX.CASINO_WIN : SFX.CASINO_LOSE); - new Modal(this, lines.join('\n'), {}).setDepth(D.modal); + await this.wait(longest + 500); + t.setText(`+${r.points}`); + this.plateTally = null; + this.updatePlates(); + await this.wait(700); + this.tweens.add({ targets: t, alpha: 0, duration: 300 }); } } + +export { DOCK, Button, Phaser }; diff --git a/src/games/uno/UnoLogic.js b/src/games/uno/UnoLogic.js index 4af42d5..cbf8f00 100644 --- a/src/games/uno/UnoLogic.js +++ b/src/games/uno/UnoLogic.js @@ -1,6 +1,6 @@ // Uno — pure state engine. No Phaser imports. // -// Mattel rules (official): +// Official rules: // - 108-card deck; 7 cards dealt to each of 2..4 players. // - On your turn, play a card matching the top discard's color, number, or // action; or play a Wild; or draw one card from the draw pile. If the drawn @@ -9,18 +9,28 @@ // in a 2-player game it acts like a Skip), Draw 2 (next player draws 2 and // loses turn), Wild (choose color), Wild Draw 4 (choose color; next player // draws 4 and loses turn — but may challenge first). -// - Wild Draw 4 is only legal if you have no card matching the active color. -// If challenged and the challenge succeeds, the player who played it draws -// the 4 and play continues normally; if the challenge fails, the challenger -// draws 6 instead and loses their turn. -// - No stacking, no jump-in, no 7-0 swap. -// - First player to empty their hand wins. +// - Wild Draw 4 is only allowed with no card matching the active color — but +// nothing stops a bluff. The next player may challenge: if the player held +// the colour they draw the 4 and play continues normally; if not, the +// challenger draws 6 instead and loses their turn. +// - "UNO!": a player who plays down to one card must call it. If someone +// catches them before the next player acts, they draw 2. +// - Scoring: the player who goes out scores every card left in the other +// hands (numbers face value, actions 20, wilds 50). If the last card was a +// Draw 2 / Wild Draw 4 the next player draws those cards first. First to +// the target (default 500) wins the match; target 0 = a single hand. +// +// Optional house rules (state.rules, all off by default): +// - stacking: a Draw 2 may be answered with a Draw 2, a Wild Draw 4 with a +// Wild Draw 4, passing the growing penalty on to the next player. +// - drawUntilPlayable: drawing keeps going until a playable card turns up. import { buildDeck, cloneCard, UNO_COLORS } from './UnoDeck.js'; export const HAND_DEAL = 7; +export const DEFAULT_TARGET = 500; -// ── PRNG (Mulberry32) — mirrors GoFishLogic for seedable shuffles. ────────── +// ── PRNG (Mulberry32) — seedable shuffles. ────────────────────────────────── function rng(seed) { let a = (seed >>> 0) || 1; return () => { @@ -33,7 +43,7 @@ function rng(seed) { } function shuffle(arr, seed) { - const rand = seed === undefined ? Math.random : rng(seed); + const rand = seed === undefined || seed === null ? Math.random : rng(seed); for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; @@ -43,36 +53,41 @@ function shuffle(arr, seed) { // ── State helpers ─────────────────────────────────────────────────────────── export function cloneState(state) { return { - players: state.players.map((p) => ({ - seat: p.seat, - hand: p.hand.map(cloneCard), - })), - drawPile: state.drawPile.map(cloneCard), + players: state.players.map((p) => ({ seat: p.seat, hand: p.hand.map(cloneCard) })), + drawPile: state.drawPile.map(cloneCard), discardPile: state.discardPile.map(cloneCard), currentPlayer: state.currentPlayer, - direction: state.direction, + startingPlayer: state.startingPlayer, + direction: state.direction, currentColor: state.currentColor, - phase: state.phase, + phase: state.phase, pendingWild4: state.pendingWild4 ? { ...state.pendingWild4 } : null, pendingDrawn: state.pendingDrawn ? cloneCard(state.pendingDrawn) : null, - lastAction: state.lastAction ? { ...state.lastAction } : null, - log: state.log.map((e) => ({ ...e })), - winnerSeat: state.winnerSeat, - seed: state.seed, - turnCount: state.turnCount, + pendingDraw: state.pendingDraw ? { ...state.pendingDraw } : null, + lastAction: state.lastAction ? { ...state.lastAction } : null, + log: state.log.map((e) => ({ ...e })), + winnerSeat: state.winnerSeat, + matchWinner: state.matchWinner, + seed: state.seed, + turnCount: state.turnCount, + rules: { ...state.rules }, + target: state.target, + scores: state.scores.slice(), + handNum: state.handNum, + handResult: state.handResult ? { ...state.handResult, perSeat: state.handResult.perSeat.slice() } : null, + unoCalled: state.unoCalled.slice(), + unoVulnerable: state.unoVulnerable, }; } -function topDiscard(state) { +export function topDiscard(state) { return state.discardPile[state.discardPile.length - 1]; } -function nextSeat(state, fromSeat = state.currentPlayer, hops = 1) { +export function nextSeat(state, fromSeat = state.currentPlayer, hops = 1) { const N = state.players.length; let s = fromSeat; - for (let i = 0; i < hops; i++) { - s = ((s + state.direction) % N + N) % N; - } + for (let i = 0; i < hops; i++) s = ((s + state.direction) % N + N) % N; return s; } @@ -81,18 +96,13 @@ function advanceTurn(state, hops = 1) { state.turnCount += 1; } -/** - * If the draw pile is empty, take all but the top discard, reset wilds, shuffle, - * and make it the new draw pile. No-op if the draw pile still has cards. - */ +/** Take all but the top discard, reset wilds, shuffle, make it the draw pile. */ function reshuffleIfNeeded(state) { if (state.drawPile.length > 0) return; - if (state.discardPile.length <= 1) return; // shouldn't happen mid-game + if (state.discardPile.length <= 1) return; const top = state.discardPile.pop(); const recycled = state.discardPile; - for (const c of recycled) { - if (c.color === 'w') c.chosenColor = null; - } + for (const c of recycled) if (c.color === 'w') c.chosenColor = null; shuffle(recycled); state.drawPile = recycled; state.discardPile = [top]; @@ -103,39 +113,43 @@ function drawN(state, seat, n) { const drawn = []; for (let i = 0; i < n; i++) { reshuffleIfNeeded(state); - if (state.drawPile.length === 0) break; // pathological — both piles dry + if (state.drawPile.length === 0) break; // pathological — both piles dry const c = state.drawPile.pop(); state.players[seat].hand.push(c); drawn.push(c); } + if (state.players[seat].hand.length > 2) state.unoCalled[seat] = false; + if (state.unoVulnerable === seat && state.players[seat].hand.length !== 1) state.unoVulnerable = null; return drawn; } +// Someone other than the exposed player acting closes the UNO-catch window. +function closeUnoWindow(state, actor) { + if (state.unoVulnerable != null && state.unoVulnerable !== actor) state.unoVulnerable = null; +} + // ── Legality ──────────────────────────────────────────────────────────────── /** - * Whether `card` may be played on top of the current discard given - * state.currentColor. Wilds are always legal except Wild +4, which is only - * legal when the player has no card matching state.currentColor (other wilds - * don't block it). + * Whether `card` may be played on top of the current discard. A Wild +4 may + * always be played — but holding a card of the active colour makes it a + * bluff, which the next player can challenge (see isBluff). With a stacked + * Draw 2 penalty waiting, only a Draw 2 may be played. */ export function isLegalPlay(state, card, playerHand) { - if (card.color === 'w') { - if (card.kind === 'wild4') { - // Only legal when the player has no card matching the active color - // (wilds in hand don't count as a matching color). - return !playerHand.some((c) => c.color === state.currentColor); - } - return true; - } + if (state.pendingDraw) return card.kind === 'draw2'; + if (card.color === 'w') return true; if (card.color === state.currentColor) return true; const top = topDiscard(state); - // Match by kind when colors differ. For number cards: same value. if (card.kind === 'number' && top.kind === 'number' && card.value === top.value) return true; if (card.kind !== 'number' && card.kind === top.kind) return true; return false; } -/** Returns the list of card ids the seat could legally play right now. */ +/** Playing this Wild +4 now would be a bluff (you hold the colour in play). */ +export function isBluff(state, card, playerHand) { + return card.kind === 'wild4' && playerHand.some((c) => c.id !== card.id && c.color === state.currentColor); +} + export function legalPlays(state, seat) { if (state.phase !== 'play') return []; if (state.currentPlayer !== seat) return []; @@ -143,29 +157,40 @@ export function legalPlays(state, seat) { return hand.filter((c) => isLegalPlay(state, c, hand)).map((c) => c.id); } -/** True if the seat could legally play any card (used before forcing a draw). */ export function hasAnyLegalPlay(state, seat) { return legalPlays(state, seat).length > 0; } +/** Wild +4s `seat` could stack in the current challenge window (stacking rule). */ +export function stackableWild4(state, seat) { + if (state.phase !== 'challengeWindow' || !state.rules.stacking) return []; + if (state.pendingWild4?.challengerSeat !== seat) return []; + return state.players[seat].hand.filter((c) => c.kind === 'wild4').map((c) => c.id); +} + +export function handPoints(hand) { + let pts = 0; + for (const c of hand) pts += c.points; + return pts; +} + // ── Initial state ─────────────────────────────────────────────────────────── -export function createInitialState({ playerCount = 4, seed } = {}) { - if (playerCount < 2 || playerCount > 4) { - throw new Error(`Uno supports 2..4 players, got ${playerCount}`); - } +export function createInitialState({ + playerCount = 4, seed, rules = {}, target = DEFAULT_TARGET, scores = null, handNum = 1, startingPlayer = 0, +} = {}) { + if (playerCount < 2 || playerCount > 4) throw new Error(`Uno supports 2..4 players, got ${playerCount}`); const deck = buildDeck(); shuffle(deck, seed); const players = []; - for (let i = 0; i < playerCount; i++) { - players.push({ seat: i, hand: deck.splice(0, HAND_DEAL) }); - } + for (let i = 0; i < playerCount; i++) players.push({ seat: i, hand: deck.splice(0, HAND_DEAL) }); - // Flip top discard, re-flipping if it's a Wild +4 (Mattel rule). + // Flip top discard, re-flipping if it's a Wild +4. let top = deck.pop(); - while (top.kind === 'wild4') { + for (let tries = 1; top.kind === 'wild4'; tries++) { deck.unshift(top); - shuffle(deck); + // a fresh seed each try — re-using one could cycle the +4 back on top forever + shuffle(deck, seed == null ? undefined : seed + tries * 7919); top = deck.pop(); } @@ -173,22 +198,31 @@ export function createInitialState({ playerCount = 4, seed } = {}) { players, drawPile: deck, discardPile: [top], - currentPlayer: 0, + currentPlayer: startingPlayer, + startingPlayer, direction: 1, currentColor: top.color === 'w' ? null : top.color, phase: 'play', pendingWild4: null, pendingDrawn: null, + pendingDraw: null, lastAction: null, log: [{ kind: 'start', topCard: cloneCard(top) }], winnerSeat: null, + matchWinner: null, seed: seed ?? null, turnCount: 0, + rules: { stacking: !!rules.stacking, drawUntilPlayable: !!rules.drawUntilPlayable }, + target, + scores: scores ? scores.slice() : new Array(playerCount).fill(0), + handNum, + handResult: null, + unoCalled: new Array(playerCount).fill(false), + unoVulnerable: null, }; - // Apply starting-card effects (the first player has not yet acted). + // Starting-card effects (the first player has not yet acted). if (top.kind === 'wild') { - // First player must choose a color before play begins. state.phase = 'choosingColor'; state.lastAction = { kind: 'startingWild' }; } else if (top.kind === 'skip') { @@ -197,28 +231,65 @@ export function createInitialState({ playerCount = 4, seed } = {}) { } else if (top.kind === 'reverse') { state.direction = -1; state.log.push({ kind: 'startReverse' }); - if (playerCount === 2) { - // 2-player reverse acts as a skip — first player loses their turn. - advanceTurn(state, 1); - } else { - // Direction reversed; the "first" player becomes the one before seat 0. - state.currentPlayer = nextSeat(state, 0, 1); - } + if (playerCount === 2) advanceTurn(state, 1); + else state.currentPlayer = nextSeat(state, startingPlayer, 1); } else if (top.kind === 'draw2') { const drawn = drawN(state, state.currentPlayer, 2); state.log.push({ kind: 'startDraw2', seat: state.currentPlayer, count: drawn.length }); advanceTurn(state, 1); } - return state; } -// ── Actions ───────────────────────────────────────────────────────────────── +/** Deal the next hand of a match (scores carry over, the first player rotates). */ +export function startNextHand(state) { + if (state.phase !== 'handOver') return state; + const n = state.players.length; + return createInitialState({ + playerCount: n, + seed: state.seed == null ? undefined : state.seed + state.handNum * 101, + rules: state.rules, + target: state.target, + scores: state.scores, + handNum: state.handNum + 1, + startingPlayer: (state.startingPlayer + 1) % n, + }); +} +// ── Going out ─────────────────────────────────────────────────────────────── +// The winner's last card still bites: Draw 2 / Wild Draw 4 make the next +// player draw before the hand is counted. Then score the other hands. +function finishHand(next, seat, played) { + let bite = 0; + if (played.kind === 'draw2') bite = (next.pendingDraw?.count ?? 0) + 2; + if (played.kind === 'wild4') bite = (next.pendingWild4?.count ?? 0) + 4; + if (bite) { + const victim = nextSeat(next, seat, 1); + const drawn = drawN(next, victim, bite); + next.log.push({ kind: 'finalDraw', seat: victim, count: drawn.length }); + } + next.pendingDraw = null; + next.pendingWild4 = null; + next.unoVulnerable = null; + const perSeat = next.players.map((p) => (p.seat === seat ? 0 : handPoints(p.hand))); + const points = perSeat.reduce((a, b) => a + b, 0); + next.scores[seat] += points; + next.winnerSeat = seat; + next.handResult = { winner: seat, points, perSeat }; + next.log.push({ kind: 'win', seat, points }); + if (next.target <= 0 || next.scores[seat] >= next.target) { + next.phase = 'gameOver'; + next.matchWinner = seat; + } else { + next.phase = 'handOver'; + } + return next; +} + +// ── Actions ───────────────────────────────────────────────────────────────── /** - * Play `cardId` from `seat`'s hand. For wilds, the engine transitions to - * 'choosingColor' phase — call applyChooseColor next. Returns the same state - * (unchanged) if the action is illegal. + * Play `cardId` from `seat`'s hand. For wilds the engine moves to + * 'choosingColor' — call applyChooseColor next. Returns the same state if illegal. */ export function applyPlay(state, seat, cardId) { if (state.phase !== 'play') return state; @@ -230,79 +301,61 @@ export function applyPlay(state, seat, cardId) { if (!isLegalPlay(state, card, player.hand)) return state; const next = cloneState(state); + closeUnoWindow(next, seat); const me = next.players[seat]; - // Snapshot whether the player had a color match BEFORE removing the card, - // for Wild +4 challenge resolution. - const hadColorMatch = me.hand.some( - (c) => c.id !== cardId && c.color === next.currentColor, - ); + const hadColorMatch = me.hand.some((c) => c.id !== cardId && c.color === next.currentColor); const played = me.hand.splice(idx, 1)[0]; played.chosenColor = null; next.discardPile.push(played); next.lastAction = { kind: 'play', seat, card: cloneCard(played) }; next.log.push({ kind: 'play', seat, cardId: played.id }); - // Win check — playing your last card wins immediately. - if (me.hand.length === 0) { - next.winnerSeat = seat; - next.phase = 'gameOver'; - next.log.push({ kind: 'win', seat }); - return next; + if (me.hand.length === 0) return finishHand(next, seat, played); + if (me.hand.length === 1) { + if (next.unoCalled[seat]) next.log.push({ kind: 'uno', seat }); + else next.unoVulnerable = seat; } - // Resolve effects. if (played.kind === 'wild') { next.phase = 'choosingColor'; return next; } if (played.kind === 'wild4') { next.phase = 'choosingColor'; - next.pendingWild4 = { - playerSeat: seat, - challengerSeat: nextSeat(next, seat, 1), - hadColorMatch, - }; + next.pendingWild4 = { playerSeat: seat, challengerSeat: nextSeat(next, seat, 1), hadColorMatch, count: 4, priorColor: next.currentColor }; return next; } + next.currentColor = played.color; if (played.kind === 'skip') { - next.currentColor = played.color; - const skipped = nextSeat(next, seat, 1); - next.log.push({ kind: 'skip', seat: skipped }); + next.log.push({ kind: 'skip', seat: nextSeat(next, seat, 1) }); advanceTurn(next, 2); return next; } if (played.kind === 'reverse') { - next.currentColor = played.color; next.direction = -next.direction; next.log.push({ kind: 'reverse' }); - if (next.players.length === 2) { - // 2-player Reverse acts as Skip — same player goes again. With only two - // seats, flipping direction alone still hands the turn to the opponent, - // so we advance by 2 to wrap back to the same seat. - advanceTurn(next, 2); - } else { - advanceTurn(next, 1); - } + advanceTurn(next, next.players.length === 2 ? 2 : 1); return next; } if (played.kind === 'draw2') { - next.currentColor = played.color; const target = nextSeat(next, seat, 1); + if (next.rules.stacking) { + const count = (next.pendingDraw?.count ?? 0) + 2; + next.pendingDraw = { count, by: seat }; + next.log.push({ kind: 'draw2Stack', seat: target, count }); + advanceTurn(next, 1); + return next; + } const drawn = drawN(next, target, 2); next.log.push({ kind: 'draw2', seat: target, count: drawn.length }); advanceTurn(next, 2); return next; } - // Number card. - next.currentColor = played.color; advanceTurn(next, 1); return next; } -/** - * Choose the color after playing a Wild or Wild +4 (or after the starting Wild - * top-discard). Returns the same state if not currently in 'choosingColor'. - */ +/** Choose the color after a Wild / Wild +4 (or the starting Wild). */ export function applyChooseColor(state, color) { if (state.phase !== 'choosingColor') return state; if (!UNO_COLORS.includes(color)) return state; @@ -311,17 +364,11 @@ export function applyChooseColor(state, color) { const top = topDiscard(next); if (top.color === 'w') top.chosenColor = color; next.log.push({ kind: 'chooseColor', color }); - - // Resolve the pending follow-up. if (next.pendingWild4) { next.phase = 'challengeWindow'; next.lastAction = { kind: 'wild4Pending', color }; return next; } - - // After a regular Wild: advance turn. - // After a starting Wild (top discard was wild at game start): the same seat 0 - // gets the first play — do NOT advance. const wasStartingWild = next.lastAction?.kind === 'startingWild'; next.phase = 'play'; if (!wasStartingWild) advanceTurn(next, 1); @@ -329,56 +376,31 @@ export function applyChooseColor(state, color) { return next; } -/** - * The challenger either accepts the Wild +4 or challenges it. Resolves the - * draw and turn order accordingly. - */ +/** The challenger accepts the Wild +4 penalty, or challenges it. */ export function applyChallengeWild4(state, doChallenge) { if (state.phase !== 'challengeWindow') return state; const next = cloneState(state); const pw = next.pendingWild4; if (!pw) return state; + closeUnoWindow(next, pw.challengerSeat); + const count = pw.count ?? 4; if (!doChallenge) { - // Accept: challenger draws 4 and is skipped. - const drawn = drawN(next, pw.challengerSeat, 4); + const drawn = drawN(next, pw.challengerSeat, count); next.log.push({ kind: 'wild4Accept', seat: pw.challengerSeat, count: drawn.length }); - next.lastAction = { - kind: 'wild4Resolve', - result: 'accept', - drawSeat: pw.challengerSeat, - drawCount: drawn.length, - }; - // Move past the player who played the +4 and past the now-skipped challenger. + next.lastAction = { kind: 'wild4Resolve', result: 'accept', drawSeat: pw.challengerSeat, drawCount: drawn.length }; next.currentPlayer = pw.playerSeat; advanceTurn(next, 2); - next.pendingWild4 = null; - next.phase = 'play'; - return next; - } - - if (pw.hadColorMatch) { - // Successful challenge: WD4 player draws 4, play continues normally. - const drawn = drawN(next, pw.playerSeat, 4); + } else if (pw.hadColorMatch) { + const drawn = drawN(next, pw.playerSeat, count); next.log.push({ kind: 'wild4ChallengeWin', seat: pw.playerSeat, count: drawn.length }); - next.lastAction = { - kind: 'wild4Resolve', - result: 'challengeWin', - drawSeat: pw.playerSeat, - drawCount: drawn.length, - }; + next.lastAction = { kind: 'wild4Resolve', result: 'challengeWin', drawSeat: pw.playerSeat, drawCount: drawn.length }; next.currentPlayer = pw.challengerSeat; next.turnCount += 1; } else { - // Failed challenge: challenger draws 6 and is skipped. - const drawn = drawN(next, pw.challengerSeat, 6); + const drawn = drawN(next, pw.challengerSeat, count + 2); next.log.push({ kind: 'wild4ChallengeLose', seat: pw.challengerSeat, count: drawn.length }); - next.lastAction = { - kind: 'wild4Resolve', - result: 'challengeLose', - drawSeat: pw.challengerSeat, - drawCount: drawn.length, - }; + next.lastAction = { kind: 'wild4Resolve', result: 'challengeLose', drawSeat: pw.challengerSeat, drawCount: drawn.length }; next.currentPlayer = pw.playerSeat; advanceTurn(next, 2); } @@ -387,24 +409,71 @@ export function applyChallengeWild4(state, doChallenge) { return next; } +/** Stacking rule: the challenger answers a Wild +4 with their own Wild +4. */ +export function applyStackWild4(state, seat, cardId) { + if (!stackableWild4(state, seat).includes(cardId)) return state; + const next = cloneState(state); + closeUnoWindow(next, seat); + const pw = next.pendingWild4; + const me = next.players[seat]; + const idx = me.hand.findIndex((c) => c.id === cardId); + const hadColorMatch = me.hand.some((c) => c.id !== cardId && c.color === next.currentColor); + const played = me.hand.splice(idx, 1)[0]; + played.chosenColor = null; + next.discardPile.push(played); + next.currentPlayer = seat; + next.turnCount += 1; + next.lastAction = { kind: 'play', seat, card: cloneCard(played) }; + next.log.push({ kind: 'play', seat, cardId: played.id, stacked: true }); + const count = (pw.count ?? 4) + 4; + if (me.hand.length === 0) { + next.pendingWild4 = { ...pw, count: count - 4 }; + return finishHand(next, seat, played); + } + if (me.hand.length === 1) { + if (next.unoCalled[seat]) next.log.push({ kind: 'uno', seat }); + else next.unoVulnerable = seat; + } + next.pendingWild4 = { playerSeat: seat, challengerSeat: nextSeat(next, seat, 1), hadColorMatch, count, priorColor: next.currentColor }; + next.phase = 'choosingColor'; + return next; +} + /** - * Draw a single card from the draw pile. If the drawn card is playable the - * state transitions to 'mustPlayDrawn' and the UI prompts the player to keep - * or play it. Otherwise the turn advances automatically. + * Draw from the pile. With a stacked Draw 2 penalty waiting this takes the + * whole penalty and ends the turn. Otherwise draws one card (or, with the + * drawUntilPlayable rule, until a playable one turns up); a playable draw + * moves to 'mustPlayDrawn' (play it or keep it), else the turn passes. */ export function applyDraw(state, seat) { if (state.phase !== 'play') return state; if (state.currentPlayer !== seat) return state; const next = cloneState(state); - const drawn = drawN(next, seat, 1); - if (drawn.length === 0) { - // Both piles dry — pathological. Just advance the turn. + closeUnoWindow(next, seat); + if (next.pendingDraw) { + const drawn = drawN(next, seat, next.pendingDraw.count); + next.log.push({ kind: 'draw2', seat, count: drawn.length, stacked: true }); + next.lastAction = { kind: 'penaltyDraw', seat, count: drawn.length }; + next.pendingDraw = null; advanceTurn(next, 1); return next; } - const card = drawn[0]; - next.lastAction = { kind: 'draw', seat, card: cloneCard(card) }; - next.log.push({ kind: 'draw', seat, count: 1 }); + const color = next.currentColor; + const drawn = []; + const limit = next.rules.drawUntilPlayable ? 108 : 1; + for (let i = 0; i < limit; i++) { + const got = drawN(next, seat, 1); + if (!got.length) break; + drawn.push(got[0]); + if (isLegalPlay(next, got[0], next.players[seat].hand)) break; + } + if (drawn.length === 0) { + advanceTurn(next, 1); + return next; + } + const card = drawn[drawn.length - 1]; + next.lastAction = { kind: 'draw', seat, card: cloneCard(card), count: drawn.length }; + next.log.push({ kind: 'draw', seat, count: drawn.length, color }); if (isLegalPlay(next, card, next.players[seat].hand)) { next.phase = 'mustPlayDrawn'; next.pendingDrawn = cloneCard(card); @@ -414,11 +483,6 @@ export function applyDraw(state, seat) { return next; } -/** - * After drawing, the player elects to play the drawn card. Internally this is - * just applyPlay (with the same card id), but it transitions from - * 'mustPlayDrawn' back to 'play' first. - */ export function applyPlayDrawn(state, seat) { if (state.phase !== 'mustPlayDrawn') return state; if (state.currentPlayer !== seat) return state; @@ -430,7 +494,6 @@ export function applyPlayDrawn(state, seat) { return applyPlay(intermediate, seat, cardId); } -/** After drawing a playable card, elect to keep it and pass. */ export function applyPassAfterDraw(state, seat) { if (state.phase !== 'mustPlayDrawn') return state; if (state.currentPlayer !== seat) return state; @@ -441,6 +504,47 @@ export function applyPassAfterDraw(state, seat) { return next; } +// ── UNO! ──────────────────────────────────────────────────────────────────── +/** Call "UNO!" — allowed holding two cards (about to play one) or one card. */ +export function applyCallUno(state, seat) { + if (state.phase === 'gameOver' || state.phase === 'handOver') return state; + const n = state.players[seat].hand.length; + if (n > 2 || n === 0 || state.unoCalled[seat]) return state; + const next = cloneState(state); + next.unoCalled[seat] = true; + if (next.unoVulnerable === seat) next.unoVulnerable = null; + next.log.push({ kind: 'unoCall', seat }); + return next; +} + +/** Catch a player who is down to one card without having called UNO: they draw 2. */ +export function canCatchUno(state, catcherSeat) { + const v = state.unoVulnerable; + return v != null && v !== catcherSeat && state.players[v].hand.length === 1 + && state.phase !== 'gameOver' && state.phase !== 'handOver'; +} + +export function applyCatchUno(state, catcherSeat) { + if (!canCatchUno(state, catcherSeat)) return state; + const next = cloneState(state); + const v = next.unoVulnerable; + next.unoVulnerable = null; + const drawn = drawN(next, v, 2); + next.unoCalled[v] = false; + next.log.push({ kind: 'unoCaught', seat: v, by: catcherSeat, count: drawn.length }); + next.lastAction = { kind: 'unoCaught', seat: v, by: catcherSeat }; + return next; +} + export function isGameOver(state) { return state.phase === 'gameOver'; } + +export function isHandOver(state) { + return state.phase === 'handOver' || state.phase === 'gameOver'; +} + +/** Every card in the game (for conservation checks). */ +export function countCards(state) { + return state.drawPile.length + state.discardPile.length + state.players.reduce((n, p) => n + p.hand.length, 0); +} diff --git a/src/games/uno/UnoTable.js b/src/games/uno/UnoTable.js new file mode 100644 index 0000000..39d510b --- /dev/null +++ b/src/games/uno/UnoTable.js @@ -0,0 +1,101 @@ +// Uno table layout — Phaser-free so tools/verifyUno.js can test it. +// +// A 90s family kitchen table (gingham tablecloth) on the shared card-table +// kit. Uno has nothing laid down in front of players, so each opponent just +// holds a fan of cards at the table's edge and everything happens in the +// middle: the draw pile, the discard pile, the colour halo and the direction +// ring that circles them. +// +// 2 human · across 3 human · far corners 4 human · left · across · right +// Logic seats run clockwise from the human's left (seat 1 = left / far-left), +// matching the engine's direction = +1. + +import { + makeTable, CARD_W, CARD_H, fanPose, fanPoint, HUMAN_PLATE, PLATE, +} from '../../ui/cardtable/TableGeometry.js'; + +export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 }; +export const T = makeTable(VIEW, { shape: 'rect', corner: 0.17, feltK: 1.0, faceH: 46 }); // the cloth covers the whole top +export const SQ = VIEW.squash; + +export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c]; +export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c']; + +const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 82, curve: 1.3, tilt: 0.034, q: 1, maxSpan: 880, maxDrop: 34, maxTilt: 0.2 }; +const opp = (x, y, rot, k = 0.55) => ({ x, y, rot, k, spread: 34, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 520, maxDrop: 14, maxTilt: 0.16 }); + +const SEATS = { + 2: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(960, 80, Math.PI), plate: { x: 1420, y: 86 } }, + ], + 3: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(600, 82, Math.PI - 0.1), plate: { x: 190, y: 150 } }, + { fan: opp(1320, 82, Math.PI + 0.1), plate: { x: 1730, y: 150 } }, + ], + 4: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 } }, + { fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 } }, + { fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 } }, + ], +}; + +export const PILE_K = 1.04; +export const DECK_UV = { u: -0.15, v: 0.47 }; +export const DISCARD_UV = { u: 0.075, v: 0.47 }; +export const RING = { u: -0.035, v: 0.47, ru: 0.36, rv: 0.2 }; // direction ring around the piles + +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(`Uno layout supports 2..4 players, got ${playerCount}`); + const L = { + playerCount, + seats: defs.map((d, seat) => ({ seat, fan: d.fan, plate: d.plate })), + deck: T.flat(DECK_UV.u, DECK_UV.v, PILE_K), + discard: T.flat(DISCARD_UV.u, DISCARD_UV.v, PILE_K), + }; + cache.set(playerCount, L); + return L; +} + +export const handPose = (L, seat, i, n, lift = 0) => fanPose(L.seats[seat].fan, i, n, lift); + +/** Where an opponent's ghost hand rests (just in front of their cards). */ +export function handHome(L, seat) { + const f = L.seats[seat].fan; + const p = fanPoint(f, 0, -CARD_H * 0.95); + return { ...p, rot: f.rot, k: f.k }; +} + +/** Card-count badge at the end of an opponent's (largest) fan. */ +export function handBadge(L, seat) { + const f = L.seats[seat].fan; + return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 50), 0); +} + +/** Turn spotlight over a seat. */ +export function spotFor(L, seat) { + const f = L.seats[seat].fan; + if (seat === 0) return { x: f.x, y: 820, w: 1300, h: 420 }; + const c = fanPoint(f, 0, -CARD_H * 0.9); + const side = Math.abs(Math.sin(f.rot)) > 0.7; + return side ? { x: c.x, y: c.y, w: 420, h: 620 } : { x: c.x, y: c.y + 30, w: 640, h: 320 }; +} + +/** Points on the direction ring (table space → screen) for `n` chevrons, phase in radians. */ +export function ringPoints(n, phase = 0) { + const out = []; + for (let i = 0; i < n; i++) { + const a = phase + (i / n) * Math.PI * 2; + const p = T.P.project(RING.u + Math.cos(a) * RING.ru, RING.v + Math.sin(a) * RING.rv); + const p2 = T.P.project(RING.u + Math.cos(a + 0.02) * RING.ru, RING.v + Math.sin(a + 0.02) * RING.rv); + out.push({ x: p.x, y: p.y, s: p.s, ang: Math.atan2(p2.y - p.y, p2.x - p.x) }); + } + return out; +} + +export { PLATE }; diff --git a/src/scenes/OpponentSelectScene.js b/src/scenes/OpponentSelectScene.js index 74ff5ff..45bd281 100644 --- a/src/scenes/OpponentSelectScene.js +++ b/src/scenes/OpponentSelectScene.js @@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene { // Skill control: pips always show the level; the +/- buttons appear only // when this opponent is selected. Enabled for games with a 1–5 AI skill. - if (['nerts', 'phase10', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) { + if (['nerts', 'phase10', 'uno', 'skipbo', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) { bio.style.webkitLineClamp = '1'; const skillRow = document.createElement('div'); diff --git a/src/ui/cardtable/AITiming.js b/src/ui/cardtable/AITiming.js new file mode 100644 index 0000000..3298f5f --- /dev/null +++ b/src/ui/cardtable/AITiming.js @@ -0,0 +1,37 @@ +// Shared opponent pacing for the table card games — Phaser-free. +// +// Ghost-hand speed follows skill exactly as in Nerts / Phase 10 (the user set +// these: skill 1 = ¼ speed … skill 5 = full speed). Thinking time slows less +// steeply than the hands. `pace` is the table setting (relaxed / normal / fast). + +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 }; +export const DEFAULT_BASE = { think: 520, between: 260, reach: 190, carry: 250, hesitate: 240 }; + +export 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, base = DEFAULT_BASE) { + const k = clampSkill(skill); + const slow = pace / HAND_SPEED[k]; + 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), + }; +} + +/** Seedable PRNG for AIs that need repeatable randomness in tests. */ +export function mulberry32(seed) { + let a = (seed >>> 0) || 1; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} diff --git a/src/ui/cardtable/CardTableScene.js b/src/ui/cardtable/CardTableScene.js new file mode 100644 index 0000000..948be1e --- /dev/null +++ b/src/ui/cardtable/CardTableScene.js @@ -0,0 +1,751 @@ +import * as Phaser from 'phaser'; +import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; +import { Button } from '../Button.js'; +import { Tooltip } from '../Tooltip.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../Portrait.js'; +import { auth } from '../../services/auth.js'; +import { api } from '../../services/api.js'; +import { playSound, playSoundEx, SFX } from '../Sounds.js'; +import { MusicPlayer } from '../MusicPlayer.js'; +import { ensureLeatherPanel } from '../casino/CasinoArt.js'; +import { ensurePad, ensureGhostHand } from '../../games/nerts/NertsArt.js'; +import { ensureTableTextures } from './TableArt.js'; +import { aiTiming, PACE } from './AITiming.js'; +import { + CARD_W, CARD_H, PLATE, TOP_BUTTONS, DOCK, SORT_ROW, KEYS_BOX, poseScale, cardCorners, +} from './TableGeometry.js'; + +// ─── CardTableScene ─────────────────────────────────────────────────────────── +// Base scene for the home-table card games (Uno first; Skip-Bo, Hearts, Go +// Fish and Old Maid next). Extracted from Phase 10 / Nerts. +// +// A game subclass provides: +// faceFrame(card) → { key, frame } texture for a face-up card +// computeLayout() → { visible: Map(id → view), loc: Map(id → {pose,faceUp,depth}) } +// view = { card, pose, faceUp, depth, kind, … } +// decorate(c, view) (optional) hint marks / chips / glow per card +// afterLayout() (optional) overlays redrawn after every layout +// and calls layout() after every state change: each card is a persistent +// sprite keyed by id and glides (and flips) to wherever the state says it is. + +export const BASE_DEPTH = { + bg: -3, 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, +}; +const D = BASE_DEPTH; +export const CX = GAME_WIDTH / 2; +export const CY = GAME_HEIGHT / 2; +export const FONT_HAND = '"YummyCupcakes", "Comic Sans MS", cursive'; + +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; +}; +export 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 ?? 1) - (b.q ?? 1)) < 0.001; + +export class CardTableScene extends Phaser.Scene { + // ── Setup ───────────────────────────────────────────────────────────────── + initTable(data, { settingsKey, defaults, maxPlayers = 4, minPlayers = 2 }) { + this.gameDef = data.game; + this.opponents = data.opponents ?? []; + this.playfield = data.playfield ?? null; + this.cardBack = data.cardBack ?? null; + this.playerCount = Math.max(minPlayers, Math.min(maxPlayers, 1 + this.opponents.length)); + this.settingsKey = settingsKey; + try { + this.settings = { ...defaults, ...JSON.parse(localStorage.getItem(settingsKey) || '{}') }; + } catch { this.settings = { ...defaults }; } + + this.mode = 'idle'; + this.turnToken = 0; + this.modal = null; + this.paused = false; + this.sprites = new Map(); + this.lastLoc = new Map(); + this._lastVisible = new Map(); + this.plates = []; + this.portraits = []; + this.hands = []; + this.fx = []; + this.dockBtns = []; + this.dockActs = []; + } + + /** Common create(): music, background, shared textures, shutdown hook. */ + createTableBase() { + 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'); + }); + ensureTableTextures(this); + ensureGhostHand(this); + } + + saveSettings() { + try { localStorage.setItem(this.settingsKey, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + } + + 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, base) { return aiTiming(this.skillFor(seat), this.pace(), base); } + + // ── Card sprites ─────────────────────────────────────────────────────────── + backFrame() { + if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { + return { key: 'cardbacks', frame: this.cardBack.spriteIndex, sized: true }; + } + return { key: this.backKey, frame: undefined }; + } + + 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, 'ct-glow').setScale(0.5).setTint(0xffd35a).setVisible(false); + const face = this.add.image(0, 0, this.backKey).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; + } + + setFace(c, faceUp) { + c.faceUp = faceUp; + if (faceUp) { + const f = this.faceFrame(c.card); + c.faceImg.setTexture(f.key, f.frame).setScale(0.5); + } else { + const b = this.backFrame(); + c.faceImg.setTexture(b.key, b.frame); + if (b.sized) c.faceImg.setDisplaySize(CARD_W, CARD_H); else c.faceImg.setScale(0.5); + } + } + + applyPose(c, pose, lift = 0) { + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? 1); + 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, ease = 'Cubic.easeOut' } = {}) { + 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, + 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 ?? 1, to.q ?? 1, 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?.(); + }, + }); + } + + /** Sync every card sprite with computeLayout(). */ + layout({ delayFor = null, duration = 260, durationFor = null } = {}) { + if (!this.gs) return; + this.beforeLayout?.(); + const { visible, loc } = this.computeLayout(); + 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); + } + c.card = v.card; + 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); + if (c.faceUp) this.setFace(c, true); // a wild's face may change after play + } + } + 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.afterLayout?.(); + } + + poseOf(id) { return this._lastVisible.get(id)?.pose ?? null; } + + clearSprites() { + for (const c of this.sprites.values()) { c._tw?.stop(); c.destroy(); } + this.sprites.clear(); + this.lastLoc = new Map(); + this._lastVisible = new Map(); + } + + /** Gather every card back to `to` (the deck) before a new deal. */ + async sweepCards(to) { + 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, to, { faceUp: false, duration: 360, delay: Math.min(500, i++ * 12), lift: 0.4 }); + } + if (i) playSound(this, SFX.CARD_SHUFFLE); + await this.wait(Math.min(500, i * 12) + 420); + } + + 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 }); + } + + flashGlow(id, tint = 0x7cf0a0, { delay = 300, hold = 300 } = {}) { + this.time.delayedCall(delay, () => { + const c = this.sprites.get(id); + if (!c) return; + c.glow.setVisible(true).setTint(tint).setAlpha(1); + this.tweens.add({ + targets: c.glow, alpha: 0, duration: 900, delay: hold, + onComplete: () => { c.glow.setTint(0xffd35a).setAlpha(1); this.decorate?.(c, this._lastVisible.get(c.card.id) ?? {}); }, + }); + }); + } + + // ── Drag-to-reorder preview ──────────────────────────────────────────────── + /** Order of `heldIds` after dropping `dragId` at insertion slot `at`. */ + static reorderPreview(heldIds, dragId, at) { + const fromIdx = heldIds.indexOf(dragId); + const rest = heldIds.filter(id => id !== dragId); + const ins = fromIdx >= 0 && fromIdx < at ? at - 1 : at; + rest.splice(Math.max(0, Math.min(rest.length, ins)), 0, dragId); + return rest; + } + + buildDropSlot() { + this.dropSlotG = this.add.graphics().setVisible(false); + this.dropSlotGlow = this.add.image(0, 0, 'ct-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' }); + } + + /** Outline of the empty slot a dragged card will drop into (pose + depth), or hide. */ + drawDropSlot(pose, depth) { + const g = this.dropSlotG, glow = this.dropSlotGlow; + if (!g) return; + if (!pose) { g.setVisible(false); glow.setVisible(false); return; } + 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); + } + + // ── Ghost hands ───────────────────────────────────────────────────────────── + /** homes[seat] = { x, y, rot, k } for every AI seat. */ + buildGhostHands(homes, colors) { + homes.forEach((home, seat) => { + if (!home || seat === 0) return; + const img = this.add.image(home.x, home.y, 'nerts-hand') + .setTint(colors[seat]).setAlpha(0.2).setRotation(home.rot) + .setScale(0.6 * (0.5 + (home.k ?? 0.5))).setDepth(D.ghost); + this.hands[seat] = { img, home, tw: null, ret: null }; + }); + } + + moveHand(seat, pt, duration, ease = 'Sine.easeInOut') { + const h = this.hands[seat]; + if (!h || !pt) 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' }); + }); + } + + // ── Seat plates ───────────────────────────────────────────────────────────── + /** + * Leather nameplates. positions[seat] = { x, y }. Each plate has: + * nameTxt (top-left) · scoreTxt (top-right) · infoTxt (mid-left) · + * statusTxt (mid-right) · extra Graphics for the bottom row · stamp text. + */ + buildPlates(positions, colors, hexes, { stampText = 'SKIPPED' } = {}) { + const key = ensureLeatherPanel(this, 'ct-plate', PLATE.w, PLATE.h, { radius: 14 }); + positions.forEach(({ x, y }, seat) => { + const bg = this.add.image(x, y, key).setDepth(D.plates); + const glow = this.add.graphics().setDepth(D.plates - 0.5); + glow.lineStyle(5, 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(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, this.scene.key) + : 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, '', { + fontFamily: 'Righteous', fontSize: '20px', color: hexes[seat], + }).setOrigin(1, 0.5).setDepth(D.plates + 2); + const infoTxt = this.add.text(tx, y + 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 extra = 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: hexes[seat], stroke: '#120c06', strokeThickness: 7, + }).setOrigin(0.5).setDepth(D.stamp - 1).setVisible(false); + const stamp = this.add.text(x + 30, y, stampText, { + 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, infoTxt, statusTxt, extra, tallyTxt, stamp, tx, rx }; + }); + } + + setPlateActive(seat, active) { + const pl = this.plates[seat]; + if (!pl) return; + 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); + } + } + + /** Pop a stamp ("SKIPPED", "UNO!", …) on a plate; hold = ms before it fades (0 = stays). */ + plateStamp(seat, text, color = '#ff6b4a', hold = 1500) { + const st = this.plates[seat]?.stamp; + if (!st) return; + st.setText(text).setColor(color).setVisible(true).setScale(2.3).setAlpha(0); + this.tweens.killTweensOf(st); + this.tweens.add({ targets: st, scale: 1, alpha: 1, duration: 210, ease: 'Back.easeOut' }); + if (hold > 0) this.tweens.add({ targets: st, alpha: 0, delay: hold, duration: 400, onComplete: () => st.setVisible(false).setAlpha(1) }); + } + + // ── HUD ───────────────────────────────────────────────────────────────────── + buildTopButtons(actions, keysText) { + for (const b of TOP_BUTTONS) { + const act = actions[b.label]; + if (!act) continue; + new Button(this, b.x, b.y, b.label, () => { if (!this.modal) act(); }, { + variant: 'ghost', width: b.w, height: b.h, fontSize: 17, + }).setDepth(D.ui); + } + if (keysText) { + this.add.text(KEYS_BOX.x0, KEYS_BOX.y0 + 2, keysText, { + 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; + this.add.image(cx, cy, ensureLeatherPanel(this, 'ct-dock', w, h, { radius: 16 })).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); + 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); + }); + } + + /** buttons: up to 4 of { label, act, enabled = true, hot = false } (null = empty slot). */ + 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); + }); + } + + /** opts: [[mode, label], …] (≤ 3). onPick(mode) is called after the setting saves. */ + buildSortRow(opts, onPick) { + 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); + 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.refreshSortButtons(); + onPick(mode); + 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(); + } + + refreshSortButtons() { + for (const b of this.sortBtns ?? []) b.setActive(b.mode === this.settings.sort); + } + + buildSpot() { + this.spot = this.add.image(CX, CY, 'ct-spot').setDepth(D.spot).setBlendMode(Phaser.BlendModes.ADD) + .setTint(0xffc884).setAlpha(0); + } + + /** s = { x, y, w, h } — glide the turn spotlight there. */ + setSpot(s, alpha = 0.32) { + if (!this.spot || !s) return; + 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, duration: 420, ease: 'Sine.easeInOut' }); + } + + /** Hover tooltip over a rect; fn() returns Tooltip content or null. */ + hoverZone(x, y, w, h, fn) { + if (!this.tip) this.tip = new Tooltip(this, { depth: D.modal - 2 }); + const z = this.add.zone(x, y, w, h).setInteractive(); + z.isTableZone = 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); + }); + }); + z.on('pointerout', () => { timer?.remove(false); timer = null; if (this.tip._owner === z) this.tip.hide(); }); + return z; + } + + /** True when a pointer event landed on a real UI control (buttons, overlays). */ + overUI(over) { return !!over?.some(o => !o.isTableZone); } + + // ── 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()) }); + } + + burst(at, color, { n = 8, r = 70 } = {}) { + for (let i = 0; i < n; i++) { + const a = (i / n) * Math.PI * 2; + const dot = this.add.circle(at.x, at.y, 6, color, 0.85).setDepth(D.float); + this.tweens.add({ targets: dot, x: at.x + Math.cos(a) * r, y: at.y + Math.sin(a) * r * 0.72, alpha: 0, scale: 1.8, duration: 420, ease: 'Cubic.easeOut', onComplete: () => dot.destroy() }); + } + } + + // ── Modals ───────────────────────────────────────────────────────────────── + freeze(on) { + this.paused = on; + this.time.paused = on; + if (on) this.tweens.pauseAll(); else this.tweens.resumeAll(); + } + + setVideos(visible) { + for (const p of this.portraits) p?.setVideoVisible?.(visible); + } + + openModal({ w, h, paper = false, onEscape = null, freeze = true } = {}) { + if (this.modal) this.closeModal(); + this.cancelDrag?.(); + 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, `ct-pad-${w}x${h}`, w, h)).setDepth(D.modal).setRotation(-0.01)); + else objs.push(this.add.image(CX, CY, ensureLeatherPanel(this, `ct-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; + } + + 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); + } + + modalText(x, y, text, style) { + return this.addToModal(this.add.text(x, y, text, style).setOrigin(0.5).setDepth(D.modal + 1)); + } + + 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)); + } + + /** A static copy of a seat's portrait inside a modal. */ + modalPortrait(seat, x, y, r, ringColor) { + for (const o of this.portraits[seat]?.renderInto?.(x, y, r, D.modal + 2) ?? []) this.addToModal(o); + const ring = this.addToModal(this.add.graphics().setDepth(D.modal + 4)); + ring.lineStyle(3, ringColor, 1); + ring.strokeCircle(x, y, r + 3); + } + + 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(); }; + } + + /** items: [{ label, act, ghost? }] — Resume is always first. */ + openPauseMenu(items) { + if (this.modal) return; + const h = 200 + items.length * 64; + this.openModal({ w: 520, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 60, 'Paused', { fontFamily: 'Righteous', fontSize: '46px', color: COLORS.goldHex }); + const all = [{ label: 'Resume', act: () => this.closeModal() }, ...items]; + all.forEach((it, i) => this.modalButton(CX, top + 140 + i * 64, it.label, it.act, { width: 300, variant: it.ghost ? 'ghost' : 'solid' })); + } + + /** + * rows: [{ label, options: [[value, text], …], get(), set(v) }]. note: small + * line under the rows. Each change saves settings. + */ + openSettingsModal(rows, { note = '', onDone = null, title = 'Table Settings' } = {}) { + const back = () => { this.closeModal(); onDone?.(); }; + const h = 220 + rows.length * 66; + this.openModal({ w: 780, h, onEscape: back }); + const top = CY - h / 2; + this.modalText(CX, top + 56, title, { fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex }); + rows.forEach((row, ri) => { + const y = top + 130 + ri * 66; + this.addToModal(this.add.text(CX - 340, y, row.label, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + const btns = []; + const bw = row.options.length > 3 ? 100 : 108, gap = 10; + const startX = CX + 340 - row.options.length * bw - (row.options.length - 1) * gap + bw / 2; + const current = row.get(); + row.options.forEach(([value, text], i) => { + const b = new Button(this, startX + i * (bw + gap), y, text, () => { + row.set(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 (note) this.modalText(CX, top + h - 96, note, { fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, align: 'center', wordWrap: { width: 700 } }); + this.modalButton(CX, top + h - 46, 'Done', back, { width: 220, height: 48, fontSize: 21 }); + } + + /** + * Paper score pad. + * title, sub + * columns: ['R1', …] (shown = last 8) + * rows: [{ seat, color, name, cells: [{ text, color, mark?, markColor? }], extra?, total, totalColor, circled }] + * extraLabel: optional column before Total + * writeLast: animate the newest column + totals being written in + * buttons: [{ label, act, hot?, ghost? }] (centre-aligned, ≤ 3) + */ + openScorePadModal({ title, titleColor = '#22201a', sub = '', columns = [], rows, extraLabel = null, writeLast = false, buttons, readOnly = false, onEnter = null }) { + const w = 1080, h = 250 + rows.length * 62 + 90; + 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', grey = '#6c6450'; + this.modalText(CX, top + 62, title, { fontFamily: FONT_HAND, fontSize: '44px', color: titleColor }); + if (sub) this.modalText(CX, top + 104, sub, { fontFamily: '"Julius Sans One"', fontSize: '14px', color: grey }); + const shownCols = columns.slice(-8); + const skip = columns.length - shownCols.length; + const nameX = left + 120, colX0 = left + 380, colW = 66, extraX = left + w - 190, totalX = left + w - 80; + const headY = top + 150; + this.modalText(nameX + 60, headY, 'Player', { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + shownCols.forEach((c, i) => this.modalText(colX0 + i * colW, headY, c, { fontFamily: FONT_HAND, fontSize: '22px', color: grey })); + if (extraLabel) this.modalText(extraX, headY, extraLabel, { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + this.modalText(totalX, headY, 'Total', { fontFamily: FONT_HAND, fontSize: '24px', color: grey }); + const writes = []; + rows.forEach((row, ri) => { + const y = headY + 56 + ri * 62; + this.addToModal(this.add.circle(nameX - 22, y, 8, row.color).setDepth(D.modal + 1)); + this.addToModal(this.add.text(nameX, y, row.name, { fontFamily: FONT_HAND, fontSize: '28px', color: ink }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + row.cells.slice(skip).forEach((cell, i) => { + const isNew = writeLast && i === shownCols.length - 1; + const t = this.add.text(colX0 + i * colW, y - (cell.mark ? 6 : 0), cell.text, { + fontFamily: FONT_HAND, fontSize: '25px', color: cell.color ?? ink, + }).setOrigin(0.5).setDepth(D.modal + 1); + this.addToModal(t); + if (isNew) { t.setAlpha(0); writes.push(t); } + if (cell.mark) { + const mk = this.add.text(colX0 + i * colW, y + 17, cell.mark, { + fontFamily: 'sans-serif', fontSize: '14px', color: cell.markColor ?? grey, + }).setOrigin(0.5).setDepth(D.modal + 1); + this.addToModal(mk); + if (isNew) { mk.setAlpha(0); writes.push(mk); } + } + }); + if (extraLabel) { + const ex = this.add.text(extraX, y, row.extra ?? '', { fontFamily: FONT_HAND, fontSize: '30px', color: ink }).setOrigin(0.5).setDepth(D.modal + 1); + this.addToModal(ex); + if (writeLast) { ex.setAlpha(0); writes.push(ex); } + } + const tot = this.add.text(totalX, y, String(row.total), { fontFamily: FONT_HAND, fontSize: '32px', color: row.totalColor ?? ink }).setOrigin(0.5).setDepth(D.modal + 1); + this.addToModal(tot); + if (writeLast) { tot.setAlpha(0); writes.push(tot); } + if (row.circled) { + const ringG = this.add.graphics().setDepth(D.modal + 1); + ringG.lineStyle(3, 0xb8231f, 0.85); + ringG.strokeEllipse(totalX, y, 96, 52); + this.addToModal(ringG); + } + }); + writes.forEach((t, i) => this.tweens.add({ targets: t, alpha: 1, 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; + const n = buttons.length; + buttons.forEach((b, i) => { + const x = CX + (i - (n - 1) / 2) * 240; + const opts = b.ghost ? { variant: 'ghost' } : b.hot ? { bg: COLORS.accent, textColor: COLORS.textDarkHex } : {}; + this.modalButton(x, btnY, b.label, b.act, { width: 220, ...opts }); + }); + if (onEnter) this.modal.onEnter = onEnter; + return m; + } + + // ── History ───────────────────────────────────────────────────────────────── + async recordResult(slug, { score, opponentScores, won }) { + try { + await api.post('/history/single-player', { slug, score, opponentScores, result: won ? 'win' : 'loss' }); + } catch (err) { + console.warn(`[${slug}] failed to record history`, err); + } + } +} + +export { D as DEPTH, COLORS, Button, playSound, playSoundEx, SFX }; diff --git a/src/ui/cardtable/TableArt.js b/src/ui/cardtable/TableArt.js new file mode 100644 index 0000000..e37bd9b --- /dev/null +++ b/src/ui/cardtable/TableArt.js @@ -0,0 +1,243 @@ +// Card-table art kit — canvas painters for the "home table" card games. +// +// A game bakes its whole room once per page load (bakeRoom) from painters: +// +// bakeRoom(scene, key, T, { +// wall(ctx), // the room behind the table (full canvas) +// front(ctx, T), // the table's visible front edge +// rim(ctx, T), // the band between the outer edge and the top +// top(ctx, T), // the playing surface (already clipped to it) +// onTop(ctx, T), // mats, pile spots… (clipped to the surface) +// after(ctx, T), // anything drawn over everything +// }) +// +// The helpers below cover the common parts (floor shadow, banded edges, lamp +// pools, perspective-correct patterns). Shared runtime textures: +// ct-glow soft card-sized outline (selection / target glow, tinted) +// ct-spot radial light pool (turn spotlight, additive) + +import { canvas, rr, poly, mix, lerp, noisePattern } from '../casino/CasinoArt.js'; +import { W, H, CARD_W, CARD_H, poseScale } from './TableGeometry.js'; + +export { canvas, rr, poly, mix, lerp, noisePattern }; + +const RES = 2; + +export function bakeRoom(scene, key, T, spec) { + if (scene.textures.exists(key)) return key; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + spec.wall?.(ctx, T); + floorShadow(ctx, T); + spec.front?.(ctx, T); + spec.rim?.(ctx, T); + ctx.save(); + poly(ctx, T.outline(T.feltK, 18)); + ctx.clip(); + spec.top?.(ctx, T); + spec.onTop?.(ctx, T); + ctx.restore(); + spec.after?.(ctx, T); + scene.textures.addCanvas(key, c); + return key; +} + +// ── Common painters ────────────────────────────────────────────────────────── +export function floorShadow(ctx, T, { blur = 70, alpha = 0.8 } = {}) { + const OFF = 6000; + const pts = T.outline(1.0, 18).map(p => ({ x: p.x - OFF, y: p.y + T.faceH * p.s + 8 })); + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; + ctx.shadowOffsetX = OFF; + ctx.shadowOffsetY = 30; + poly(ctx, pts); + ctx.fillStyle = '#000'; + ctx.fill(); + ctx.restore(); +} + +/** The table's front edge as stacked bands (tones top → bottom). */ +export function frontBands(ctx, T, tones, { grooves = [], k = 1.0 } = {}) { + const top = T.outline(k, 18); + const n = 14; + for (let i = 0; i <= n; i++) { + const f = i / n; + poly(ctx, top.map(p => ({ x: p.x, y: p.y + T.faceH * p.s * f }))); + ctx.fillStyle = tones[Math.min(tones.length - 1, Math.floor(f * tones.length))]; + ctx.fill(); + } + for (const f of grooves) { + poly(ctx, top.map(p => ({ x: p.x, y: p.y + T.faceH * p.s * f }))); + ctx.lineWidth = 1.5; + ctx.strokeStyle = 'rgba(20,14,8,0.45)'; + ctx.stroke(); + } + poly(ctx, top.map(p => ({ x: p.x, y: p.y + T.faceH * p.s }))); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.85)'; + ctx.stroke(); +} + +export function bandPath(ctx, T, k0, k1) { + const outer = T.outline(k1, 18), inner = T.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(); +} + +export function ring(ctx, T, k, width, color) { + poly(ctx, T.outline(k, 18)); + ctx.lineWidth = width; + ctx.strokeStyle = color; + ctx.stroke(); +} + +/** A rounded rim band from the surface edge to the outer edge, dark at both edges. */ +export function rimBand(ctx, T, { base, dark, light, grain = null, gloss = 1.6 }) { + ctx.save(); + bandPath(ctx, T, T.feltK, 1.0); + ctx.fillStyle = base; + ctx.fill('evenodd'); + ctx.clip('evenodd'); + for (let i = 0; i <= 16; i++) { + const f = i / 16; + const crown = Math.sin(f * Math.PI); + ring(ctx, T, lerp(T.feltK, 1.0, f), 5, mix(dark, light, Math.pow(crown, gloss) * 0.85)); + } + if (grain) { + ctx.globalAlpha = 0.16; + for (let i = 0; i < 70; i++) { + const k = lerp(T.feltK + 0.004, 0.996, Math.random()); + const pts = T.outline(k, 18); + const a = Math.floor(Math.random() * pts.length); + const len = 6 + Math.floor(Math.random() * 18); + ctx.beginPath(); + for (let j = 0; j < len; j++) { + const p = pts[(a + j) % pts.length]; + if (j) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); + } + ctx.lineWidth = 1 + Math.random() * 1.5; + ctx.strokeStyle = Math.random() < 0.5 ? grain[0] : grain[1]; + ctx.stroke(); + } + ctx.globalAlpha = 1; + } + ctx.fillStyle = noisePattern(ctx, 128, 16); + ctx.fillRect(0, 0, W, H); + ctx.restore(); + ring(ctx, T, 1.0, 2, 'rgba(0,0,0,0.55)'); + ring(ctx, T, T.feltK, 2, 'rgba(0,0,0,0.7)'); +} + +/** Warm overhead light + vignette over the playing surface. */ +export function lampPool(ctx, T, { color = '255,214,150', alpha = 0.24, vignette = 0.5, at = { u: 0, v: 0.5 } } = {}) { + const c = T.P.project(at.u, at.v); + const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1050); + lamp.addColorStop(0, `rgba(${color},${alpha})`); + lamp.addColorStop(0.45, `rgba(${color},${alpha * 0.32})`); + lamp.addColorStop(1, `rgba(${color},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,${vignette})`); + ctx.fillStyle = vig; + ctx.fillRect(0, 0, W, H); +} + +/** Soft shadow the rim casts onto the surface. */ +export function rimShadow(ctx, T, strength = 0.32) { + for (let i = 0; i < 10; i++) ring(ctx, T, T.feltK - i * 0.004, 4, `rgba(0,0,0,${strength * (1 - i / 10)})`); +} + +/** + * Perspective-correct checks (gingham, tiles…). cell = u size; colours by + * parity: [both, one, neither]. aspect squeezes v so cells look square. + */ +export function checks(ctx, T, { cell = 0.06, colors, aspect = 0.56, u0 = -1.05, u1 = 1.05, v0 = -0.05, v1 = 1.05 }) { + const dv = cell * aspect; + for (let j = 0; v0 + j * dv < v1; j++) { + for (let i = 0; u0 + i * cell < u1; i++) { + const ua = u0 + i * cell, va = v0 + j * dv; + const a = T.P.project(ua, va), b = T.P.project(ua + cell, va), c = T.P.project(ua + cell, va + dv), d = T.P.project(ua, va + dv); + const n = (i % 2) + (j % 2); + ctx.fillStyle = colors[n === 2 ? 0 : n === 1 ? 1 : 2]; + ctx.beginPath(); + ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.lineTo(c.x, c.y); ctx.lineTo(d.x, d.y); + ctx.closePath(); + ctx.fill(); + } + } +} + +/** A dashed card-outline "spot" for a pile, with a label above it. */ +export function pileSpot(ctx, pose, label, { color = '242,214,160', alpha = 0.45, labelDy = 26 } = {}) { + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? 1); + ctx.save(); + ctx.translate(pose.x, pose.y); + ctx.rotate(pose.rot); + 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.18)'; + ctx.fill(); + ctx.setLineDash([9, 7]); + ctx.lineWidth = 2.2 / sx; + ctx.strokeStyle = `rgba(${color},${alpha})`; + ctx.stroke(); + ctx.setLineDash([]); + ctx.restore(); + if (label) { + ctx.font = '16px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = `rgba(${color},${Math.min(1, alpha + 0.05)})`; + ctx.fillText(label, pose.x, pose.y - (CARD_H / 2) * sy - labelDy); + } +} + +/** Fill a quad (mat / board) with a soft drop shadow. */ +export function shadowedPoly(ctx, pts, fill, { blur = 14, dy = 5, alpha = 0.5 } = {}) { + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; + ctx.shadowOffsetY = dy; + poly(ctx, pts); + ctx.fillStyle = fill; + ctx.fill(); + ctx.restore(); +} + +// ── Shared runtime textures ────────────────────────────────────────────────── +export function ensureTableTextures(scene) { + if (!scene.textures.exists('ct-glow')) { + const pad = 30; + const CW = CARD_W * RES, CH = CARD_H * RES; + 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('ct-glow', c); + } + if (!scene.textures.exists('ct-spot')) { + 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('ct-spot', c); + } +} + +export const CARD_TEX = { W: CARD_W * RES, H: CARD_H * RES, RES }; diff --git a/src/ui/cardtable/TableGeometry.js b/src/ui/cardtable/TableGeometry.js new file mode 100644 index 0000000..92a3d4a --- /dev/null +++ b/src/ui/cardtable/TableGeometry.js @@ -0,0 +1,199 @@ +// Card-table geometry kit — Phaser-free so each game's verify script can test it. +// +// Shared by the "home table" card games (Uno, Skip-Bo, Hearts, Go Fish, Old +// Maid). A table is a rounded rectangle (or ellipse) in flat table space +// pushed through the casino perspective projection: +// +// u ∈ [-1, 1] left → right v ∈ [0, 1] far edge → near edge +// +// Cards lying on the table squash vertically by `squash` (q); cards held in a +// hand are upright toward their owner (q = 1). A "pose" is +// { x, y, rot, s, q } — screen centre, rotation, scale, squash. +// +// Each game builds its own seats/piles on top of makeTable() and the fan +// helpers below (see e.g. src/games/uno/UnoTable.js). + +import { makeProjection } from '../casino/CasinoGeometry.js'; + +export const CARD_W = 96; +export const CARD_H = 134; +export const W = 1920, H = 1080; + +export const rot2 = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) }); + +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; +} + +/** + * A perspective table. + * view — makeProjection view { cx, yFar, yNear, sFar, halfW, squash } + * shape — 'rect' (rounded rectangle, `corner` radius in u) or 'oval' + * feltK — inset of the playing surface from the outer edge (fraction) + * faceH — visible front-face height of the table edge at s = 1 (px) + */ +export function makeTable(view, { shape = 'rect', corner = 0.17, feltK = 0.955, faceH = 34 } = {}) { + const P = makeProjection(view); + const SQ = view.squash; + const outlineUV = (k = 1, steps = 14) => { + const cu = 0, cv = 0.5; + if (shape === 'oval') { + const pts = []; + const n = steps * 4; + for (let i = 0; i < n; i++) { + const a = (i / n) * Math.PI * 2; + pts.push({ u: cu + Math.cos(a) * k, v: cv + Math.sin(a) * 0.5 * k }); + } + return pts; + } + const hu = k, hv = 0.5 * k, r = corner * k, rv = r * 0.62; + const pts = []; + const arc = (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 }); + } + }; + arc(cu + hu - r, cv + hv - rv, 0); + arc(cu - hu + r, cv + hv - rv, Math.PI / 2); + arc(cu - hu + r, cv - hv + rv, Math.PI); + arc(cu + hu - r, cv - hv + rv, Math.PI * 1.5); + return pts; + }; + const outline = (k = 1, steps = 14) => outlineUV(k, steps).map(p => P.project(p.u, p.v)); + const onFelt = (pt, k = feltK) => { + 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 }))); + }; + /** Pose of a card lying flat at table point (u, v), scaled by k. */ + const flat = (u, v, k = 1, rot = 0) => { + const p = P.project(u, v); + return { x: p.x, y: p.y, rot, s: p.s * k, q: SQ }; + }; + return { view, P, SQ, shape, corner, feltK, faceH, outlineUV, outline, onFelt, flat }; +} + +// ── Card poses ─────────────────────────────────────────────────────────────── +// The squash (q) acts on the SCREEN vertical, so a card turned 90° squashes +// its local x instead. +export function poseScale(s, rot, q = 1) { + 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, w = CARD_W, h = CARD_H) { + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? 1); + return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => { + const p = rot2(a * (w / 2) * sx, b * (h / 2) * sy, pose.rot); + return { x: pose.x + p.x, y: pose.y + p.y }; + }); +} + +export function cardBounds(pose, w = CARD_W, h = CARD_H) { + const c = cardCorners(pose, w, h); + 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) }; +} + +export function inPose(pt, pose, pad = 0, w = CARD_W, h = CARD_H) { + const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? 1); + const d = rot2(pt.x - pose.x, pt.y - pose.y, -pose.rot); + return Math.abs(d.x) <= (w / 2) * sx + pad && Math.abs(d.y) <= (h / 2) * sy + pad; +} + +// Lift (screen px toward the camera) a stack of n cards shows as thickness. +export function stackLift(n, k = 1, per = 0.16, max = 12) { + return Math.min(max, Math.max(0, n - 1) * per) * k; +} + +// ── Hand fans ──────────────────────────────────────────────────────────────── +// A fan descriptor: { x, y, rot, k, spread, curve, tilt, q, maxSpan } +// rot owner frame → screen (0 = the human at the bottom) +// spread px between cards at k; compresses so the fan never exceeds maxSpan +// curve px drop per step² toward the owner (capped so big hands stay on screen) +// tilt rad per step (capped likewise) +export function fanStep(fan, n) { + if (n <= 1) return fan.spread; + return Math.min(fan.spread, (fan.maxSpan ?? 860) / (n - 1)); +} + +export function fanPose(fan, i, n, lift = 0) { + const mid = (n - 1) / 2; + const d = i - mid; + const step = fanStep(fan, n); + const curve = mid > 0 ? Math.min(fan.curve, (fan.maxDrop ?? 34) / (mid * mid)) : 0; + const tilt = mid > 0 ? Math.min(fan.tilt, (fan.maxTilt ?? 0.18) / mid) : 0; + const p = rot2(d * step * fan.k, (d * d * curve - lift) * fan.k, fan.rot); + return { x: fan.x + p.x, y: fan.y + p.y, rot: fan.rot + d * tilt, s: fan.k, q: fan.q ?? 1 }; +} + +/** Topmost card index of a fan under a point (or -1). */ +export function fanHit(fan, n, pt, liftFor = () => 0) { + for (let i = n - 1; i >= 0; i--) { + if (inPose(pt, fanPose(fan, i, n, liftFor(i)))) return i; + } + return -1; +} + +/** Insertion slot for a card dropped at screen x along an upright (rot 0) fan. */ +export function fanInsertIndex(fan, n, x) { + for (let i = 0; i < n; i++) if (x < fanPose(fan, i, n).x) return i; + return n; +} + +/** Screen rect covering an upright fan (drop-to-hand zone). */ +export function fanZone(fan, n, extraTop = 0) { + const a = fanPose(fan, 0, Math.max(1, n)), b = fanPose(fan, Math.max(0, n - 1), Math.max(1, n)); + return { x0: Math.min(a.x, b.x) - CARD_W * 0.7 * fan.k, x1: Math.max(a.x, b.x) + CARD_W * 0.7 * fan.k, y0: fan.y - CARD_H * 0.75 * fan.k - extraTop, y1: H }; +} + +/** A point in a fan's owner frame (dx along the row, dy toward the owner). */ +export function fanPoint(fan, dx, dy) { + const p = rot2(dx * fan.k, dy * fan.k, fan.rot); + return { x: fan.x + p.x, y: fan.y + p.y }; +} + +// ── Rects ──────────────────────────────────────────────────────────────────── +export const inRect = (pt, r) => pt.x >= r.x0 && pt.x <= r.x1 && pt.y >= r.y0 && pt.y <= r.y1; +export const rectsOverlap = (a, b) => 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 }); +export const unionRect = (a, b) => (a ? { x0: Math.min(a.x0, b.x0), x1: Math.max(a.x1, b.x1), y0: Math.min(a.y0, b.y0), y1: Math.max(a.y1, b.y1) } : b); +export const onScreen = (r, m = 0) => r.x0 >= -m && r.x1 <= W + m && r.y0 >= -m && r.y1 <= H + m; + +/** Bounding rect of a whole fan of n cards (with an optional lift on every card). */ +export function fanBounds(fan, n, lift = 0) { + let b = null; + for (let i = 0; i < n; i++) b = unionRect(b, cardBounds(fanPose(fan, i, n, lift))); + return b; +} + +// ── Standard HUD furniture (same corners in every table game) ──────────────── +export const PLATE = { w: 300, h: 96 }; +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: 'Rules' }, +]; +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 }; +export const HUMAN_PLATE = { x: 190, y: 902 }; + +export function plateRect(p) { + 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 }; +} + +/** Every fixed HUD rect, named — verify scripts check seats against these. */ +export function hudFurniture() { + const out = TOP_BUTTONS.map(b => ({ name: `button ${b.label}`, r: centreRect(b) })); + out.push({ name: 'dock', r: DOCK }); + SORT_ROW.xs.forEach((x, i) => out.push({ name: `sort ${i}`, r: centreRect({ x, y: SORT_ROW.y, w: SORT_ROW.w, h: SORT_ROW.h }) })); + out.push({ name: 'keys line', r: KEYS_BOX }); + out.push({ name: 'human plate', r: plateRect(HUMAN_PLATE) }); + return out; +} diff --git a/tools/verifySkipBo.js b/tools/verifySkipBo.js new file mode 100644 index 0000000..d9786cc --- /dev/null +++ b/tools/verifySkipBo.js @@ -0,0 +1,276 @@ +#!/usr/bin/env node +// verifySkipBo.js — headless checks for Skip-Bo: rules (deal, plays, wilds, +// completing a pile, recycling, refills, discards, stuck passes, wins, match +// scoring), the AI (legal actions, the stock-chain search, skill timing), the +// dining-table layout for 2/3/4 players (on screen, on the table, clear of the +// HUD and each other, hit-tests), and an all-AI soak (every game ends, 162 +// cards conserved, skill ordering). +// Usage: node tools/verifySkipBo.js [--quick] + +import * as S from '../src/games/skipbo/SkipBoLogic.js'; +import { chooseAction, planChain, suggestAction, suggestDiscard } from '../src/games/skipbo/SkipBoAI.js'; +import { aiTiming, mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + CARD_W, CARD_H, cardBounds, inPose, fanHit, fanBounds, inRect, rectsOverlap, onScreen, hudFurniture, plateRect, unionRect, +} from '../src/ui/cardtable/TableGeometry.js'; +import { + T, layoutFor, stockPose, discardPose, discardRect, buildPose, handPose, stockBadge, handHome, spotFor, placematCorners, +} from '../src/games/skipbo/SkipBoTable.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +let nid = 9000; +const C = (value) => ({ value, id: nid++, playedAs: null }); + +function rig({ n = 2, hand = [], stock = [C(7)], discards = [[], [], [], []], builds = [[], [], [], []], current = 0, target = 0 }) { + const gs = S.createInitialState({ playerCount: n, seed: 5, target }); + gs.currentPlayer = current; + const p = gs.players[current]; + p.hand = hand; + p.stock = stock; + p.discards = discards; + gs.buildPiles = builds; + return gs; +} +const run = (vals) => vals.map(v => ({ value: v, id: nid++, playedAs: null })); + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +{ + const deck = S.buildDeck(); + ok('162 cards', deck.length === 162); + ok('12 of each number + 18 wilds', [1, 7, 12].every(v => deck.filter(c => c.value === v).length === 12) && deck.filter(c => c.value === 'wild').length === 18); + for (const n of [2, 3, 4]) { + for (const stockSize of [10, 20, 30]) { + const gs = S.createInitialState({ playerCount: n, seed: 3 + n, stockSize }); + ok(`${n}p stock ${stockSize}: stocks dealt`, gs.players.every(p => p.stock.length === stockSize)); + ok(`${n}p stock ${stockSize}: opener holds 5`, gs.players[0].hand.length === 5 && gs.players.slice(1).every(p => p.hand.length === 0)); + ok(`${n}p stock ${stockSize}: 162 conserved`, S.countCards(gs) === 162); + } + } +} +{ + const gs = rig({ hand: [C(1), C(2), C('wild'), C(9), C(9)], stock: [C(5), C(4)] }); + ok('empty pile needs a 1', S.nextRequired(gs, 0) === 1 && S.canPlayOnBuild(gs, C(1), 0) && !S.canPlayOnBuild(gs, C(2), 0)); + let g = S.applyPlay(gs, { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + ok('play from hand builds up', S.nextRequired(g, 0) === 2 && g.players[0].hand.length === 4); + g = S.applyPlay(g, { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + g = S.applyPlay(g, { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + ok('a wild plays as the needed number', S.buildPileTopValue(g, 0) === 3 && g.buildPiles[0][2].playedAs === 3); + g = S.applyPlay(g, { source: 'stock', sourceIdx: 0, buildIdx: 0 }); + ok('stock top plays', S.nextRequired(g, 0) === 5 && g.players[0].stock.length === 1); + ok('play log records it', g.log.some(e => e.kind === 'play' && e.source === 'stock')); +} +{ + const builds = [run([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), [], [], []]; + const gs = rig({ hand: [C(12), C(3), C(4), C(5), C(6)], builds }); + const g = S.applyPlay(gs, { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + ok('reaching 12 clears the pile', g.buildPiles[0].length === 0 && g.completedPile.length === 12); + ok('completion is logged', g.log.some(e => e.kind === 'complete')); + ok('completed wilds forget their number', g.completedPile.every(c => c.playedAs === null)); +} +{ + const gs = rig({ hand: [C(1)], stock: [C(9), C(9)] }); + const g = S.applyPlay(gs, { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + ok('emptying the hand draws five', g.players[0].hand.length === 5); + const d = rig({ hand: [C(8), C(3)], stock: [C(9), C(9)] }); + const dn = S.applyDiscard(d, 0, 2); + ok('discard ends the turn', dn.currentPlayer === 1 && dn.players[0].discards[2].length === 1); + ok('next player is dealt up to five', dn.players[1].hand.length === 5); + ok('bad discard pile index rejected', S.applyDiscard(d, 0, 4) === d); +} +{ + const gs = rig({ hand: [C(2)], stock: [C(1)] }); + gs.drawPile = []; + gs.completedPile = run([1, 2, 3, 4, 5, 6]); + const g = S.applyPlay(gs, { source: 'stock', sourceIdx: 0, buildIdx: 0 }); + ok('stock emptied → win', g.phase === 'gameover' && g.winner === 0); + const r = rig({ hand: [C(5)], stock: [C(9), C(9)] }); + r.drawPile = []; + r.completedPile = run([1, 2, 3, 4, 5, 6, 7]); + const r2 = S.applyPlay(rig({ hand: [C(1)], stock: [C(9), C(9)] }), { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + void r2; + r.players[0].hand = [C(1)]; + const rr = S.applyPlay(r, { source: 'hand', sourceIdx: 0, buildIdx: 0 }); + ok('empty draw pile recycles the completed piles', rr.players[0].hand.length === 5 && rr.log.some(e => e.kind === 'recycle')); +} +{ + const gs = rig({ hand: [], stock: [C(9)] }); + gs.drawPile = []; gs.completedPile = []; + ok('no hand, no draw, no play → stuck', S.isPlayerStuck(gs)); + const p = S.applyAutoPass(gs); + ok('stuck player passes', p.currentPlayer === 1 && p.consecutiveStuckTurns === 1); +} +{ + const gs = rig({ n: 3, hand: [C(2)], stock: [C(1)], target: 500 }); + gs.players[1].stock = run([5, 5, 5]); + gs.players[2].stock = run([5]); + const g = S.applyPlay(gs, { source: 'stock', sourceIdx: 0, buildIdx: 0 }); + ok('match: winner scores 25 + 5 per stock card left', g.scores[0] === 25 + 20 && g.gameResult.points === 45); + ok('match: below target → next game', g.phase === 'handOver'); + const nx = S.startNextGame(g); + ok('next game keeps scores, rotates the opener', nx.scores[0] === 45 && nx.gameNum === 2 && nx.currentPlayer === 1); + const big = rig({ hand: [C(2)], stock: [C(1)], target: 30 }); + big.players[1].stock = run([5]); + ok('match: reaching the target ends it', S.applyPlay(big, { source: 'stock', sourceIdx: 0, buildIdx: 0 }).phase === 'gameover'); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry); + // chain: stock needs 4; builds at 1 (needs 2); hand has 2 and 3 + const gs = rig({ hand: [C(9), C(3), C(11), C(2), C(10)], stock: [C(4)], builds: [run([1]), [], [], []] }); + const ch = planChain(gs, 0, 6); + ok('chain search finds 2 → 3 → stock 4', ch && ch.source === 'hand' && gs.players[0].hand[ch.sourceIdx].value === 2 && ch.buildIdx === 0); + const a5 = chooseAction(gs, { skill: 5, rng: () => 0.5 }); + ok('skill 5 starts the chain', a5.type === 'play' && a5.source === 'hand' && gs.players[0].hand[a5.sourceIdx].value === 2); + const viaDiscard = rig({ hand: [C(9), C(10), C(11), C(12), C(12)], stock: [C(3)], discards: [run([2]), [], [], []], builds: [run([1]), [], [], []] }); + const cd = planChain(viaDiscard, 0, 6); + ok('chain uses discard tops', cd && cd.source === 'discard' && cd.sourceIdx === 0); + const stockFirst = rig({ hand: [C(1), C(2)], stock: [C(1)] }); + ok('stock card always first', chooseAction(stockFirst, { skill: 3, rng: () => 0.5 }).source === 'stock'); + const block = rig({ n: 2, hand: [C(5), C(9), C(9), C(10), C(10)], stock: [C(12)], builds: [run([1, 2, 3, 4]), [], [], []] }); + block.players[1].stock = run([6]); + const ab = chooseAction(block, { skill: 4, rng: () => 0.5 }); + ok("skill 4 won't build up to the next player's stock card", !(ab.type === 'play' && ab.source === 'hand' && block.players[0].hand[ab.sourceIdx].value === 5)); + const sd = suggestDiscard(block); + ok('suggested discard is legal', sd.type === 'discard' && sd.handIdx >= 0 && sd.handIdx < 5 && sd.discardIdx >= 0 && sd.discardIdx < 4); + const sug = suggestAction(rig({ hand: [C(1)], stock: [C(9), C(9)] })); + ok('hint suggests a play', sug.type === 'play'); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +for (const n of [2, 3, 4]) { + const L = layoutFor(n); + const furn = hudFurniture(); + for (let s = 1; s < n; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) }); + for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) ok(`${n}p: ${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r)); + const centre = [L.draw, ...L.builds, L.completed].map(p => cardBounds({ ...p, y: p.y - 12 })); + for (let i = 0; i < centre.length; i++) for (let j = i + 1; j < centre.length; j++) ok(`${n}p: centre piles ${i}/${j} apart`, !rectsOverlap(centre[i], centre[j])); + const centreBox = centre.reduce((a, b) => unionRect(a, b), null); + const centreArea = { ...centreBox, y0: centreBox.y0 - 6, y1: centreBox.y1 + 30 }; // 'needs N' labels below + ok(`${n}p: centre row on the table`, T.onFelt({ x: centreBox.x0, y: centreBox.y0 }) && T.onFelt({ x: centreBox.x1, y: centreBox.y1 })); + const tableau = []; + for (let s = 0; s < n; s++) { + let tb = cardBounds({ ...stockPose(L, s, 30), y: stockPose(L, s, 30).y }); + for (let d = 0; d < 4; d++) for (const len of [1, 12]) tb = unionRect(tb, discardRect(L, s, d, len, 0)); + tableau[s] = tb; + ok(`${n}p seat ${s}: tableau on screen`, onScreen(tb), JSON.stringify(tb)); + ok(`${n}p seat ${s}: placemat on the table`, placematCorners(L, s).every(p => T.onFelt(p))); + ok(`${n}p seat ${s}: tableau clear of the centre`, !rectsOverlap(tb, centreArea), `${JSON.stringify(tb)} vs ${JSON.stringify(centreArea)}`); + for (const f of furn) ok(`${n}p seat ${s}: tableau clear of ${f.name}`, !rectsOverlap(tb, f.r), `${JSON.stringify(tb)} vs ${JSON.stringify(f.r)}`); + const hb = fanBounds(L.seats[s].fan, 5, s === 0 ? 40 : 0); + ok(`${n}p seat ${s}: hand on screen`, onScreen(hb, s === 0 ? 50 : 10)); + for (const f of furn) ok(`${n}p seat ${s}: hand clear of ${f.name}`, !rectsOverlap(hb, f.r), `${JSON.stringify(hb)} vs ${JSON.stringify(f.r)}`); + ok(`${n}p seat ${s}: hand clear of the centre`, !rectsOverlap(hb, centreArea)); + const b = stockBadge(L, s); + const br = { x0: b.x - 19, x1: b.x + 19, y0: b.y - 30, y1: b.y + 19 }; + ok(`${n}p seat ${s}: stock badge on screen`, onScreen(br)); + for (const f of furn) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r)); + if (s > 0) { + const hh = handHome(L, s); + ok(`${n}p seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < 1920 && hh.y > 0 && hh.y < 1080); + } + ok(`${n}p seat ${s}: spotlight sized`, spotFor(L, s).w > 100); + } + for (let s = 0; s < n; s++) { + for (let t = s + 1; t < n; t++) ok(`${n}p tableaux ${s}/${t} apart`, !rectsOverlap(tableau[s], tableau[t])); + for (let t = 0; t < n; t++) { + if (t === s) continue; + ok(`${n}p hand ${s} clear of tableau ${t}`, !rectsOverlap(fanBounds(L.seats[s].fan, 5), tableau[t])); + } + } + ok(`${n}p: human hand clear of own tableau`, !rectsOverlap(fanBounds(L.seats[0].fan, 5, 40), tableau[0])); + // hit-tests + let rt = true; + for (let i = 0; i < 5; i++) { + const p = handPose(L, 0, i, 5); + if (fanHit(L.seats[0].fan, 5, { x: p.x - CARD_W * 0.3, y: p.y - CARD_H * 0.3 }) !== i) rt = false; + } + ok(`${n}p: hand hit-test round trip`, rt); + ok(`${n}p: stock top hit`, inPose(stockPose(L, 0, 12), stockPose(L, 0, 12))); + let dt = true; + for (let d = 0; d < 4; d++) for (const len of [1, 6, 14]) if (!inRect(discardPose(L, 0, d, len - 1, len), discardRect(L, 0, d, len, 4))) dt = false; + ok(`${n}p: discard tops inside their drop rects`, dt); + let ov = true; + for (let d = 0; d < 3; d++) if (rectsOverlap(discardRect(L, 0, d, 12, 4), discardRect(L, 0, d + 1, 12, 4))) ov = false; + ok(`${n}p: discard drop rects don't overlap`, ov); + ok(`${n}p: build piles hit`, L.builds.every((b, i) => inPose(buildPose(L, i, 5), buildPose(L, i, 5)))); +} + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +function game(skills, seed, { stockSize = 30, target = 0 } = {}) { + const rand = mulberry32(seed); + let gs = S.createInitialState({ playerCount: skills.length, seed, stockSize, target }); + let steps = 0, noop = 0, conserve = true; + while (!S.isGameDone(gs) && steps++ < 30000) { + if (S.isPlayerStuck(gs)) { gs = S.applyAutoPass(gs); continue; } + const a = chooseAction(gs, { skill: skills[gs.currentPlayer], rng: rand }); + let nx = !a ? gs : a.type === 'play' ? S.applyPlay(gs, a) : S.applyDiscard(gs, a.handIdx, a.discardIdx); + if (!a) { gs = S.applyAutoPass(gs); continue; } // empty hand, nothing worth playing + if (nx === gs) { noop++; nx = S.applyDiscard(gs, 0, 0); if (nx === gs) break; } + gs = nx; + if (S.countCards(gs) !== 162) conserve = false; + } + return { gs, done: S.isGameDone(gs), noop, conserve }; +} +{ + const M = QUICK ? 15 : 60; + for (const n of [2, 3, 4]) { + for (const stockSize of [10, 30]) { + let done = 0, noops = 0, conserved = true, draws = 0, turns = 0; + for (let i = 0; i < M; i++) { + const r = game(Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5)), 200 + i * 13 + n, { stockSize }); + if (r.done) done++; + noops += r.noop; + if (!r.conserve) conserved = false; + if (r.gs.winner === -1) draws++; + turns += r.gs.turnCount; + } + const tag = `${n}p stock ${stockSize}`; + ok(`${tag}: every game ends`, done === M, `${done}/${M}`); + ok(`${tag}: AI never makes an illegal move`, noops === 0, `${noops}`); + ok(`${tag}: 162 cards conserved`, conserved); + ok(`${tag}: stalemates are rare`, draws <= Math.ceil(M * 0.1), `${draws}`); + console.log(` ${tag}: avg ${(turns / M).toFixed(0)} turns, ${draws} stalemates`); + } + } + // a short match to 500 finishes + let gs = S.createInitialState({ playerCount: 3, seed: 77, stockSize: 10, target: 200 }); + const rand = mulberry32(77); + let games = 0; + while (gs.phase !== 'gameover' && games < 40) { + let st = 0; + while (!S.isGameDone(gs) && st++ < 30000) { + if (S.isPlayerStuck(gs)) { gs = S.applyAutoPass(gs); continue; } + const a = chooseAction(gs, { skill: 3, rng: rand }); + gs = !a ? S.applyAutoPass(gs) : a.type === 'play' ? S.applyPlay(gs, a) : S.applyDiscard(gs, a.handIdx, a.discardIdx); + } + games++; + if (gs.phase === 'handOver') gs = S.startNextGame(gs); + } + ok('a match to 200 finishes with a winner at the target', gs.phase === 'gameover' && gs.scores[gs.matchWinner] >= 200, `${games} games`); + + const duel = (a, b, M2) => { + let w = 0; + for (let i = 0; i < M2; i++) { const sa = i % 2; if (game(sa ? [b, a] : [a, b], 5000 + i).gs.winner === sa) w++; } + return w / M2; + }; + const G = QUICK ? 80 : 300; + const r51 = duel(5, 1, G), r31 = duel(3, 1, G), r53 = duel(5, 3, G); + console.log(` win rates: 5v1 ${(r51 * 100).toFixed(0)}% · 3v1 ${(r31 * 100).toFixed(0)}% · 5v3 ${(r53 * 100).toFixed(0)}%`); + ok('skill 5 beats skill 1', r51 >= 0.8); + ok('skill 3 beats skill 1', r31 >= 0.75); + ok('skill 5 beats skill 3', r53 >= (QUICK ? 0.55 : 0.58)); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/tools/verifyUno.js b/tools/verifyUno.js new file mode 100644 index 0000000..9a5d539 --- /dev/null +++ b/tools/verifyUno.js @@ -0,0 +1,336 @@ +#!/usr/bin/env node +// verifyUno.js — headless checks for Uno: rules (legality, actions, Wild +4 +// challenge, UNO! call / catch, scoring to a target, both house rules), the AI +// (always legal, challenge odds, skill timing), the kitchen-table layout for +// 2/3/4 players (on screen, clear of the HUD, hit-tests), and an all-AI soak +// (every match ends, 108 cards conserved, no stalls, skill ordering). +// Usage: node tools/verifyUno.js [--quick] + +import * as U from '../src/games/uno/UnoLogic.js'; +import { buildDeck, UnoCard } from '../src/games/uno/UnoDeck.js'; +import { chooseAction, challengeOdds, holdOdds, suggestPlay, likelyVoids, UNO_CALL_CHANCE, CATCH_CHANCE } from '../src/games/uno/UnoAI.js'; +import { aiTiming, HAND_SPEED, mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + W, H, CARD_W, CARD_H, cardBounds, inPose, fanHit, fanInsertIndex, fanZone, fanBounds, inRect, + rectsOverlap, onScreen, hudFurniture, plateRect, +} from '../src/ui/cardtable/TableGeometry.js'; +import { T, layoutFor, handPose, handHome, handBadge, spotFor, ringPoints } from '../src/games/uno/UnoTable.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +let nid = 5000; +const C = (color, kind, value = null) => Object.assign(new UnoCard({ color, kind, value }), { id: nid++ }); +const N = (color, v) => C(color, 'number', v); + +// A controlled table: seat hands, top card, colour, whose turn. +function rig({ n = 2, hands, top, color, current = 0, rules = {}, target = 500, draw = null }) { + const gs = U.createInitialState({ playerCount: n, seed: 3, rules, target }); + gs.players.forEach((p, s) => { p.hand = hands[s] ?? [N('r', 1)]; }); + gs.discardPile = [top]; + gs.currentColor = color ?? top.color; + gs.currentPlayer = current; + gs.phase = 'play'; + gs.direction = 1; + gs.pendingDraw = null; + gs.pendingWild4 = null; + gs.unoCalled = new Array(n).fill(false); + gs.unoVulnerable = null; + if (draw) gs.drawPile = draw; else gs.drawPile = Array.from({ length: 30 }, (_, i) => N('g', i % 10)); + return gs; +} + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +{ + const deck = buildDeck(); + ok('108 cards', deck.length === 108); + ok('4 wild + 4 wild4', deck.filter(c => c.kind === 'wild').length === 4 && deck.filter(c => c.kind === 'wild4').length === 4); + ok('one 0 and two 1-9 per colour', ['r', 'y', 'g', 'b'].every(col => deck.filter(c => c.color === col && c.value === 0).length === 1 && deck.filter(c => c.color === col && c.value === 7).length === 2)); + ok('points: face / 20 / 50', N('r', 7).points === 7 && C('r', 'skip').points === 20 && C('w', 'wild4').points === 50); + for (const n of [2, 3, 4]) { + const gs = U.createInitialState({ playerCount: n, seed: 11 + n }); + ok(`${n}p: 7 each (start card may add 2)`, gs.players.every(p => p.hand.length === 7 || p.hand.length === 9)); + ok(`${n}p: 108 conserved`, U.countCards(gs) === 108); + ok(`${n}p: top is never Wild +4`, U.topDiscard(gs).kind !== 'wild4'); + } + // seeded deals re-flip a +4 with a fresh seed each try (a fixed seed could cycle forever) + let flipsOk = true; + for (let seed = 1; seed <= 3000; seed++) if (U.topDiscard(U.createInitialState({ playerCount: 2, seed })).kind === 'wild4') flipsOk = false; + ok('3000 seeded deals all finish with a non-+4 top card', flipsOk); +} +{ + const gs = rig({ hands: [[N('r', 3), N('b', 5), C('w', 'wild4'), C('w', 'wild')], [N('g', 1), N('g', 2)]], top: N('r', 5) }); + const legal = U.legalPlays(gs, 0); + ok('colour match legal', legal.includes(gs.players[0].hand[0].id)); + ok('number match legal', legal.includes(gs.players[0].hand[1].id)); + ok('Wild +4 may be played as a bluff', legal.includes(gs.players[0].hand[2].id) && U.isBluff(gs, gs.players[0].hand[2], gs.players[0].hand)); + ok('Wild +4 with no colour match is honest', !U.isBluff(gs, gs.players[0].hand[2], gs.players[0].hand.filter(c => c.color !== 'r'))); + ok('Wild always legal', legal.includes(gs.players[0].hand[3].id)); + const nx = U.applyPlay(gs, 0, gs.players[0].hand[0].id); + ok('number play passes the turn', nx.currentPlayer === 1 && nx.currentColor === 'r'); + ok('not your turn → no-op', U.applyPlay(nx, 0, nx.players[0].hand[0].id) === nx); +} +{ + // skip / reverse / draw2 in 2p and 3p + const s2 = rig({ hands: [[C('r', 'skip'), N('r', 1)], [N('g', 1), N('g', 2)]], top: N('r', 5) }); + ok('2p skip: you go again', U.applyPlay(s2, 0, s2.players[0].hand[0].id).currentPlayer === 0); + const r2 = rig({ hands: [[C('r', 'reverse'), N('r', 1)], [N('g', 1), N('g', 2)]], top: N('r', 5) }); + ok('2p reverse acts as skip', U.applyPlay(r2, 0, r2.players[0].hand[0].id).currentPlayer === 0); + const r3 = rig({ n: 3, hands: [[C('r', 'reverse'), N('r', 1)], [N('g', 1), N('g', 2)], [N('y', 1), N('y', 2)]], top: N('r', 5) }); + const r3n = U.applyPlay(r3, 0, r3.players[0].hand[0].id); + ok('3p reverse flips direction', r3n.direction === -1 && r3n.currentPlayer === 2); + const d2 = rig({ n: 3, hands: [[C('r', 'draw2'), N('r', 1)], [N('g', 1)], [N('y', 1)]], top: N('r', 5) }); + const d2n = U.applyPlay(d2, 0, d2.players[0].hand[0].id); + ok('draw2: next draws 2 and is skipped', d2n.players[1].hand.length === 3 && d2n.currentPlayer === 2); +} +{ + // wild + colour, wild4 challenge outcomes + const w = rig({ hands: [[C('w', 'wild'), N('b', 1)], [N('g', 1), N('g', 2)]], top: N('r', 5) }); + let x = U.applyPlay(w, 0, w.players[0].hand[0].id); + ok('wild asks for a colour', x.phase === 'choosingColor' && x.currentPlayer === 0); + x = U.applyChooseColor(x, 'b'); + ok('colour set + turn passes', x.currentColor === 'b' && x.currentPlayer === 1 && U.topDiscard(x).chosenColor === 'b'); + + const honest = rig({ hands: [[C('w', 'wild4'), N('b', 1), N('g', 3)], [N('g', 1), N('g', 2)]], top: N('r', 5) }); + let h = U.applyChooseColor(U.applyPlay(honest, 0, honest.players[0].hand[0].id), 'g'); + ok('wild4 opens a challenge window', h.phase === 'challengeWindow' && h.pendingWild4.challengerSeat === 1 && h.pendingWild4.priorColor === 'r'); + const lose = U.applyChallengeWild4(h, true); + ok('failed challenge: challenger draws 6, skipped', lose.players[1].hand.length === 8 && lose.currentPlayer === 0); + const acc = U.applyChallengeWild4(h, false); + ok('accept: draws 4, skipped', acc.players[1].hand.length === 6 && acc.currentPlayer === 0); + + const bluff = rig({ hands: [[C('w', 'wild4'), N('r', 1), N('g', 3)], [N('g', 1), N('g', 2)]], top: N('b', 5), color: 'b' }); + bluff.players[0].hand[0] = Object.assign(new UnoCard({ color: 'w', kind: 'wild4' }), { id: nid++ }); + bluff.currentColor = 'y'; // nothing yellow in hand → the +4 is legal + let b = U.applyPlay(bluff, 0, bluff.players[0].hand[0].id); + b.pendingWild4.hadColorMatch = true; // they held the colour + b = U.applyChooseColor(b, 'g'); + const win = U.applyChallengeWild4(b, true); + ok('successful challenge: player draws 4, challenger plays', win.players[0].hand.length === 6 && win.currentPlayer === 1); +} +{ + // UNO! call and catch + const g = rig({ n: 3, hands: [[N('r', 3), N('r', 4)], [N('g', 1), N('g', 2)], [N('y', 1), N('y', 2)]], top: N('r', 5) }); + const forgot = U.applyPlay(g, 0, g.players[0].hand[0].id); + ok('forgetting UNO leaves you exposed', forgot.unoVulnerable === 0 && U.canCatchUno(forgot, 1) && !U.canCatchUno(forgot, 0)); + const caught = U.applyCatchUno(forgot, 2); + ok('caught → draw 2, window closes', caught.players[0].hand.length === 3 && caught.unoVulnerable === null && caught.currentPlayer === forgot.currentPlayer); + const late = U.applyCallUno(forgot, 0); + ok('calling late (before anyone acts) is safe', late.unoVulnerable === null && !U.canCatchUno(late, 1)); + const moved = U.applyDraw(forgot, 1); + ok('next player acting closes the window', moved.unoVulnerable === null); + const called = U.applyPlay(U.applyCallUno(g, 0), 0, g.players[0].hand[0].id); + ok('calling first protects you', called.unoVulnerable === null && called.unoCalled[0]); + ok('cannot call with 3+ cards', U.applyCallUno(rig({ hands: [[N('r', 1), N('r', 2), N('r', 3)], [N('g', 1)]], top: N('r', 5) }), 0).unoCalled[0] === false); +} +{ + // scoring + match target + const g = rig({ n: 3, hands: [[N('r', 3)], [N('g', 7), C('w', 'wild')], [C('y', 'skip'), N('y', 2)]], top: N('r', 5), target: 500 }); + const out = U.applyPlay(g, 0, g.players[0].hand[0].id); + ok('going out scores the other hands', out.phase === 'handOver' && out.scores[0] === 7 + 50 + 20 + 2 && out.handResult.points === 79); + const next = U.startNextHand(out); + ok('next hand keeps scores, rotates the opener', next.scores[0] === 79 && next.handNum === 2 && next.startingPlayer === 1 && next.phase !== 'handOver'); + const fin = rig({ hands: [[C('r', 'draw2')], [N('g', 9)]], top: N('r', 5), target: 20 }); + const f = U.applyPlay(fin, 0, fin.players[0].hand[0].id); + ok('last-card Draw 2 still makes the next player draw', f.players[1].hand.length === 3); + ok('reaching the target ends the match', f.phase === 'gameOver' && f.matchWinner === 0); + const single = rig({ hands: [[N('r', 3)], [N('g', 9)]], top: N('r', 5), target: 0 }); + ok('target 0 = one hand', U.applyPlay(single, 0, single.players[0].hand[0].id).phase === 'gameOver'); +} +{ + // house rule: stacking + const g = rig({ n: 3, rules: { stacking: true }, hands: [[C('r', 'draw2'), N('r', 1)], [C('b', 'draw2'), N('g', 2)], [N('y', 1), N('y', 2)]], top: N('r', 5) }); + const a = U.applyPlay(g, 0, g.players[0].hand[0].id); + ok('stacking: +2 waits on the next player', a.pendingDraw?.count === 2 && a.currentPlayer === 1 && a.players[1].hand.length === 2); + ok('stacking: only a Draw 2 is legal', U.legalPlays(a, 1).length === 1); + const b = U.applyPlay(a, 1, a.players[1].hand[0].id); + ok('stacking: +2 on +2 = +4 on the next', b.pendingDraw?.count === 4 && b.currentPlayer === 2); + const c = U.applyDraw(b, 2); + ok('stacking: taking it draws all and skips', c.players[2].hand.length === 6 && c.pendingDraw === null && c.currentPlayer === 0); + + const w = rig({ n: 3, rules: { stacking: true }, hands: [[C('w', 'wild4'), N('b', 1)], [C('w', 'wild4'), N('g', 2)], [N('y', 1), N('y', 2)]], top: N('r', 5) }); + let x = U.applyChooseColor(U.applyPlay(w, 0, w.players[0].hand[0].id), 'g'); + ok('stacking: challenger may stack a +4', U.stackableWild4(x, 1).length === 1); + x = U.applyStackWild4(x, 1, x.players[1].hand[0].id); + ok('stacked +4 asks for a colour', x.phase === 'choosingColor' && x.currentPlayer === 1 && x.pendingWild4.count === 8); + x = U.applyChooseColor(x, 'y'); + const take = U.applyChallengeWild4(x, false); + ok('stacked +4: next takes 8', take.players[2].hand.length === 10); + const plain = rig({ n: 3, hands: [[C('w', 'wild4'), N('b', 1)], [C('w', 'wild4'), N('g', 2)], [N('y', 1)]], top: N('r', 5) }); + const px = U.applyChooseColor(U.applyPlay(plain, 0, plain.players[0].hand[0].id), 'g'); + ok('no stacking without the rule', px.phase === 'challengeWindow' && U.stackableWild4(px, 1).length === 0); +} +{ + // house rule: draw until playable + const draw = [N('r', 9), N('g', 1), N('g', 2), N('g', 3)]; // popped from the end: 3g, 2g, 1g, 9r + const g = rig({ rules: { drawUntilPlayable: true }, hands: [[N('b', 1)], [N('y', 1)]], top: N('r', 5), draw }); + const a = U.applyDraw(g, 0); + ok('draw-until-playable keeps drawing', a.players[0].hand.length === 5 && a.phase === 'mustPlayDrawn' && a.pendingDrawn.value === 9); + const plain = rig({ hands: [[N('b', 1)], [N('y', 1)]], top: N('r', 5), draw: [N('r', 9), N('g', 1)] }); + const b = U.applyDraw(plain, 0); + ok('normal draw takes one', b.players[0].hand.length === 2 && b.currentPlayer === 1); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + ok('hand speeds as in Nerts', HAND_SPEED[1] === 0.25 && HAND_SPEED[3] === 0.5 && HAND_SPEED[5] === 1); + ok('slower hands at low skill', aiTiming(1).carry > aiTiming(3).carry && aiTiming(3).carry > aiTiming(5).carry); + ok('UNO call / catch chances rise with skill', UNO_CALL_CHANCE[1] < UNO_CALL_CHANCE[5] && CATCH_CHANCE[1] < CATCH_CHANCE[5]); + const g = rig({ n: 3, hands: [[N('r', 3)], [C('w', 'wild4'), N('g', 2), N('b', 3), N('b', 4), N('b', 5), N('b', 6)], [N('y', 1)]], top: N('y', 5), color: 'y', current: 1 }); + let x = U.applyChooseColor(U.applyPlay(g, 1, g.players[1].hand[0].id), 'b'); + const p = challengeOdds(x, 2); + ok('challenge odds are a probability', p > 0 && p < 1, p.toFixed(3)); + const big = rig({ n: 3, hands: [[N('r', 3)], [C('w', 'wild4'), ...Array.from({ length: 12 }, (_, i) => N('b', i % 10))], [N('y', 1)]], top: N('g', 5), color: 'r', current: 1 }); + const bx = U.applyChooseColor(U.applyPlay(big, 1, big.players[1].hand[0].id), 'b'); + ok('more cards in hand → likelier they held the colour', holdOdds(bx, 2) > holdOdds(x, 2) && challengeOdds(bx, 2) > p); + ok('bluffs are rare: challenge odds below the raw hold odds', challengeOdds(bx, 2) < holdOdds(bx, 2)); + const v = rig({ n: 3, hands: [[N('r', 3)], [N('g', 1)], [N('y', 1)]], top: N('b', 5) }); + v.log.push({ kind: 'draw', seat: 1, count: 1, color: 'b' }); + ok('likely voids come from the log', likelyVoids(v, 1).has('b')); + const sp = rig({ hands: [[N('r', 3), N('g', 4)], [N('y', 1)]], top: N('r', 5) }); + ok('hint suggests a legal play', U.legalPlays(sp, 0).includes(suggestPlay(sp, 0))); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +for (const n of [2, 3, 4]) { + const L = layoutFor(n); + const furn = hudFurniture(); + for (let s = 1; s < n; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) }); + for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) { + ok(`${n}p: ${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r)); + } + const deckB = cardBounds({ ...L.deck, y: L.deck.y - 14 }), discB = cardBounds(L.discard); + ok(`${n}p: piles apart`, !rectsOverlap(deckB, discB)); + ok(`${n}p: piles on the cloth`, T.onFelt({ x: deckB.x0, y: deckB.y0 }) && T.onFelt({ x: discB.x1, y: discB.y1 })); + // the colour wheel (radius 162) around the discard stays on screen and off the human hand + const wheel = { x0: L.discard.x - 162, x1: L.discard.x + 162, y0: L.discard.y - 192, y1: L.discard.y + 162 }; + ok(`${n}p: colour wheel on screen`, onScreen(wheel)); + for (let s = 0; s < n; s++) { + for (const cards of [1, 7, 15, 25]) { + const fb = fanBounds(L.seats[s].fan, cards, s === 0 ? 40 : 0); + ok(`${n}p seat ${s} (${cards} cards): hand on screen`, onScreen(fb, s === 0 ? 50 : 10), JSON.stringify(fb)); + for (const f of furn) ok(`${n}p seat ${s} (${cards}): hand clear of ${f.name}`, !rectsOverlap(fb, f.r), `${JSON.stringify(fb)} vs ${JSON.stringify(f.r)}`); + ok(`${n}p seat ${s} (${cards}): hand clear of piles`, !rectsOverlap(fb, deckB) && !rectsOverlap(fb, discB)); + if (s > 0) ok(`${n}p seat ${s} (${cards}): clear of the wheel`, !rectsOverlap(fb, wheel)); + } + if (s > 0) { + const b = handBadge(L, s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 }; + ok(`${n}p seat ${s}: badge on screen`, onScreen(br)); + for (const f of furn) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r)); + for (let t = 1; t < n; t++) ok(`${n}p seat ${s}: badge clear of hand ${t}`, !rectsOverlap(br, fanBounds(L.seats[t].fan, 25))); + const hh = handHome(L, s); + ok(`${n}p seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < W && hh.y > 0 && hh.y < H); + } + const sp = spotFor(L, s); + ok(`${n}p seat ${s}: spotlight sized`, sp.w > 100 && sp.h > 100); + } + for (const cards of [1, 7, 12, 25]) { + let rt = true; + for (let i = 0; i < cards; i++) { + const p = handPose(L, 0, i, cards); + const step = cards > 1 ? handPose(L, 0, 1, cards).x - handPose(L, 0, 0, cards).x : CARD_W; + const pt = { x: p.x - CARD_W / 2 + Math.min(step, CARD_W) * 0.45, y: p.y - CARD_H * 0.3 }; + if (fanHit(L.seats[0].fan, cards, pt) !== i) rt = false; + } + ok(`${n}p: hand hit-test round trip (${cards})`, rt); + const z = fanZone(L.seats[0].fan, 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: insert index ends (${cards})`, fanInsertIndex(L.seats[0].fan, cards, 0) === 0 && fanInsertIndex(L.seats[0].fan, cards, W) === cards); + } + ok(`${n}p: deck + discard hit`, inPose(L.deck, L.deck) && inPose(L.discard, L.discard)); + ok(`${n}p: direction ring on the cloth`, ringPoints(16, 0.3).every(p => T.onFelt(p))); +} + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +function step(gs, skills, rand) { + const seat = gs.phase === 'challengeWindow' ? gs.pendingWild4.challengerSeat : gs.currentPlayer; + const a = chooseAction(gs, seat, { skill: skills[seat], rng: rand }); + let g = gs, nx; + const callFirst = () => { if (g.players[seat].hand.length === 2 && rand() < UNO_CALL_CHANCE[skills[seat]]) g = U.applyCallUno(g, seat); }; + if (a.kind === 'play') { callFirst(); nx = U.applyPlay(g, seat, a.cardId); if (nx !== g && nx.phase === 'choosingColor') nx = U.applyChooseColor(nx, a.chosenColor ?? 'r'); } + else if (a.kind === 'draw') nx = U.applyDraw(g, seat); + else if (a.kind === 'playDrawn') { callFirst(); nx = U.applyPlayDrawn(g, seat); if (nx !== g && nx.phase === 'choosingColor') nx = U.applyChooseColor(nx, a.chosenColor ?? 'r'); } + else if (a.kind === 'passDrawn') nx = U.applyPassAfterDraw(g, seat); + else if (a.kind === 'chooseColor') nx = U.applyChooseColor(g, a.color); + else if (a.kind === 'challenge') nx = U.applyChallengeWild4(g, a.doChallenge); + else if (a.kind === 'stack') nx = U.applyStackWild4(g, seat, a.cardId); + if (nx === g) return { gs, noop: a }; + if (nx.unoVulnerable != null) { + for (let s = 0; s < nx.players.length; s++) { + if (s !== nx.unoVulnerable && rand() < CATCH_CHANCE[skills[s]] * 0.5) { nx = U.applyCatchUno(nx, s); break; } + } + } + return { gs: nx }; +} +function playMatch(n, skills, seed, rules = {}, target = 500) { + const rand = mulberry32(seed); + let gs = U.createInitialState({ playerCount: n, seed, rules, target }); + let hands = 0, noops = 0, conserve = true; + for (;;) { + let st = 0; + while (!U.isHandOver(gs) && st++ < 4000) { + const o = step(gs, skills, rand); + if (o.noop) { noops++; break; } + gs = o.gs; + if (U.countCards(gs) !== 108) conserve = false; + } + if (!U.isHandOver(gs)) return { stuck: true, noops, conserve, hands }; + hands++; + if (gs.phase === 'gameOver') return { gs, hands, noops, conserve }; + if (hands > 80) return { stuck: true, noops, conserve, hands }; + gs = U.startNextHand(gs); + } +} +{ + const M = QUICK ? 10 : 40; + for (const rules of [{}, { stacking: true }, { drawUntilPlayable: true }, { stacking: true, drawUntilPlayable: true }]) { + for (const n of [2, 3, 4]) { + let ended = 0, noops = 0, conserved = true, hands = 0, scoreOk = true; + for (let i = 0; i < M; i++) { + const skills = Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5)); + const r = playMatch(n, skills, 300 + i * 17 + n, rules); + if (!r.stuck) ended++; + noops += r.noops; + if (!r.conserve) conserved = false; + hands += r.hands; + if (r.gs) { + const w = r.gs.matchWinner; + if (r.gs.scores[w] < 500 || r.gs.scores.some((x, s) => s !== w && x >= 500)) scoreOk = false; + } + } + const tag = `${n}p ${JSON.stringify(rules)}`; + ok(`${tag}: every match ends`, ended === M, `${ended}/${M}`); + ok(`${tag}: AI never makes an illegal move`, noops === 0, `${noops}`); + ok(`${tag}: 108 cards conserved`, conserved); + ok(`${tag}: winner reached 500, nobody else did`, scoreOk); + if (!rules.stacking && !rules.drawUntilPlayable) console.log(` ${n}p: ${M} matches to 500, avg ${(hands / M).toFixed(1)} hands`); + } + } + const duel = (a, b, games, target) => { + let w = 0; + for (let i = 0; i < games; i++) { + const sa = i % 2; + const r = playMatch(2, sa === 0 ? [a, b] : [b, a], 9000 + i * 7, {}, target); + if (r.gs?.matchWinner === sa) w++; + } + return w / games; + }; + const G = QUICK ? 300 : 2000; + const r51 = duel(5, 1, G, 0), r31 = duel(3, 1, G, 0), r53 = duel(5, 3, G, 0); + console.log(` single-hand win rates: 5v1 ${(r51 * 100).toFixed(0)}% · 3v1 ${(r31 * 100).toFixed(0)}% · 5v3 ${(r53 * 100).toFixed(0)}%`); + ok('skill 5 beats skill 1', r51 >= (QUICK ? 0.55 : 0.6), `${(r51 * 100).toFixed(0)}%`); + ok('skill 3 beats skill 1', r31 >= (QUICK ? 0.55 : 0.58), `${(r31 * 100).toFixed(0)}%`); + // Uno is luck-heavy: measured over 10k hands, 5v3 ≈ 54%, 5v1 ≈ 72% + ok('skill 5 edges skill 3', r53 >= (QUICK ? 0.45 : 0.5), `${(r53 * 100).toFixed(0)}%`); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);