Rework Uno and Skip-Bo on the shared card-table scene with skill-scaled AIs

- Add `src/ui/cardtable/` kit (CardTableScene base class, TableGeometry,
  TableArt, AITiming) so both games share perspective layout, card sprites,
  ghost hands, plates and opponent pacing.
- Rewrite Uno: official rules plus optional stacking and draw-until-playable,
  UNO! call/catch, Wild +4 bluff/challenge odds, scoring to a target with
  match play, and a 90s-kitchen table with baked card art (UnoArt/UnoTable).
- Rewrite Skip-Bo: skill-scaled AI with stock-chain search and opponent-aware
  discards, match scoring to 500, dining-room table with vintage card art
  (SkipBoArt/SkipBoTable).
- Allow Uno to be played against a single opponent (minOpponents 1).
- Expose the skill slider for uno and skipbo in OpponentSelectScene.
- Add headless `tools/verifyUno.js` and `tools/verifySkipBo.js` covering
  rules, AI legality/skill ordering, layout bounds and all-AI soaks.
This commit is contained in:
Brian Fertig 2026-11-24 20:57:02 -07:00
parent a1bf2bf783
commit e09986d53f
No known key found for this signature in database
18 changed files with 5675 additions and 3079 deletions

View File

@ -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: '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: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 });
registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, iconFrame: 8 }); registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 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: '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: '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 }); registerGame({ slug: 'mexicantrain', name: 'Mexican Train', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 12 });

View File

@ -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 // The caller invokes chooseAction(state, { skill, rng }) repeatedly. Each call
// action: either a play or a discard. The scene applies the action with // returns ONE action: a play or the turn-ending discard.
// animation, then re-invokes until a discard is returned (which ends the // { type: 'play', source, sourceIdx, buildIdx, asNumber? }
// turn) or the game ends. // { 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 { import {
BUILD_PILE_COUNT, BUILD_PILE_COUNT,
DISCARD_PILE_COUNT, DISCARD_PILE_COUNT,
buildPileTopValue,
canPlayOnBuild,
discardTop, discardTop,
getValidPlays, getValidPlays,
nextRequired, nextRequired,
stockTop, stockTop,
} from './SkipBoLogic.js'; } from './SkipBoLogic.js';
import { clampSkill } from '../../ui/cardtable/AITiming.js';
const PLAY_PRIORITY = { stock: 3, discard: 2, hand: 1 }; 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 };
/** export function chooseAction(state, opts = {}) {
* 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) {
if (state.phase !== 'play') return null; if (state.phase !== 'play') return null;
const skill = clampSkill(opts.skill);
const rand = opts.rng ?? Math.random;
const seat = state.currentPlayer; const seat = state.currentPlayer;
const player = state.players[seat]; const player = state.players[seat];
const plays = getValidPlays(state); const plays = getValidPlays(state);
// 1) Stock-emptying play (winning move) trumps everything. // 1) The stock card always comes first (it's how you win).
if (player.stock.length === 1) { const stockPlays = plays.filter((p) => p.source === 'stock');
for (const p of plays) { if (stockPlays.length && !(rand() < MISS_STOCK[skill])) {
if (p.source === 'stock') return playAction(state, p); return playAction(state, bestStockPlay(state, stockPlays, skill));
}
} }
// 2) Filter / score plays. // 2) Sharp players look for a chain of plays that frees the stock card.
if (plays.length > 0) { 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; const stockReq = stockTop(state, seat)?.value;
let best = null; let best = null;
let bestScore = -Infinity; let bestScore = -Infinity;
for (const p of plays) { 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; } if (sc > bestScore) { bestScore = sc; best = p; }
} }
// Only commit to a play if it doesn't "waste" a wild unnecessarily. // sharp players would rather discard than set up the next player
if (best && (best.card.value !== 'wild' || shouldUseWild(state, best, plays))) { const floor = mustPlay ? -Infinity : skill >= 4 ? 0 : -500;
return playAction(state, best); if (best && bestScore > floor) return playAction(state, best);
}
} }
// 3) No useful play — must discard. // 4) Nothing worth playing — discard to end the turn.
return chooseDiscard(state); if (player.hand.length === 0) return null;
return chooseDiscard(state, skill, rand);
} }
function playAction(state, play) { function playAction(state, play) {
const action = { const action = { type: 'play', source: play.source, sourceIdx: play.sourceIdx, buildIdx: play.buildIdx };
type: 'play', if (play.card.value === 'wild') action.asNumber = nextRequired(state, play.buildIdx);
source: play.source,
sourceIdx: play.sourceIdx,
buildIdx: play.buildIdx,
};
if (play.card.value === 'wild') {
action.asNumber = nextRequired(state, play.buildIdx);
}
return action; return action;
} }
function scorePlay(state, play, stockTopValue) { // With several piles open for the stock card, keep away from setting up the
let s = PLAY_PRIORITY[play.source] * 100; // next player (skill 4+), else prefer the fullest pile.
function bestStockPlay(state, stockPlays, skill) {
// Bias toward plays that unlock the stock top right now or soon if (stockPlays.length === 1 || skill < 4) return stockPlays[0];
if (stockTopValue !== undefined && stockTopValue !== 'wild') { const threat = opponentNeeds(state, state.currentPlayer, skill);
const after = nextRequired(state, play.buildIdx) + 1; let best = stockPlays[0], bestScore = -Infinity;
if (play.card.value === stockTopValue) s += 50; // playing the same value we need on stock for (const p of stockPlays) {
if (after === stockTopValue) s += 80; // this play sets up stock to play next 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); 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; 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; 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; 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; 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) { function shouldUseWild(state, play, allPlays) {
if (play.source === 'stock') return true; if (play.source === 'stock') return true;
const need = nextRequired(state, play.buildIdx); const need = nextRequired(state, play.buildIdx);
if (need === 12) return true; if (need === 12) return true;
const st = stockTop(state, state.currentPlayer);
const seat = state.currentPlayer; if (st && st.value !== 'wild' && need + 1 === st.value) return true;
const stockTopCard = stockTop(state, seat); if (allPlays.some((p) => p.card.value !== 'wild')) return false;
if (stockTopCard && stockTopCard.value !== 'wild') { return state.players[state.currentPlayer].hand.filter((c) => c.value === 'wild').length >= 2;
// 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;
} }
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 seat = state.currentPlayer;
const player = state.players[seat]; const player = state.players[seat];
const hand = player.hand; const hand = player.hand;
if (hand.length === 0) { if (hand.length === 0) return null;
// Shouldn't happen — refill to 5 happens automatically. Fail-safe:
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 = []; const nexts = [];
for (let b = 0; b < BUILD_PILE_COUNT; b++) nexts.push(nextRequired(state, b)); 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 bestHandIdx = -1;
let bestCardScore = -Infinity; let bestCardScore = -Infinity;
for (let i = 0; i < hand.length; i++) { for (let i = 0; i < hand.length; i++) {
const c = hand[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 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 (score > bestCardScore) { bestCardScore = score; bestHandIdx = i; }
} }
if (bestHandIdx === -1) { if (bestHandIdx === -1) bestHandIdx = 0;
// All wilds in hand — pick the first (forced discard)
bestHandIdx = 0;
}
const cardToDiscard = hand[bestHandIdx]; 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 bestPileIdx = -1;
let bestPileScore = -Infinity; let bestPileScore = -Infinity;
for (let d = 0; d < DISCARD_PILE_COUNT; d++) { for (let d = 0; d < DISCARD_PILE_COUNT; d++) {
const top = discardTop(state, seat, d); const top = discardTop(state, seat, d);
let s = 0; let s = 0;
if (!top) { if (!top) s = 50;
s = 50; // empty pile is great else if (top.value === 'wild') s = -200;
} else if (top.value === 'wild' || top.playedAs === 'wild') { else if (cardToDiscard.value === 'wild') s = player.discards[d].length === 0 ? 30 : -50;
s = -200; // don't bury wilds else {
} else if (cardToDiscard.value === 'wild') { const topVal = top.value;
s = -50; // wild on any pile is mediocre if (topVal === cardToDiscard.value + 1) s = 40;
if (player.discards[d].length === 0) s = 30; else if (topVal === cardToDiscard.value) s = 25;
} else { else s = -Math.abs(topVal - cardToDiscard.value);
const topVal = top.playedAs ?? top.value; // sharp players keep one pile for high cards rather than burying low ones
if (topVal === cardToDiscard.value + 1) s = 40; // stack descending (replayable) if (skill >= 4 && cardToDiscard.value >= 10 && topVal >= 10) s += 10;
else if (topVal === cardToDiscard.value) s = 25; // duplicate stack
else s = -Math.abs(topVal - cardToDiscard.value); // closer is better
} }
// Prefer shorter piles slightly
s += (8 - player.discards[d].length) * 0.5; s += (8 - player.discards[d].length) * 0.5;
if (s > bestPileScore) { bestPileScore = s; bestPileIdx = d; } if (s > bestPileScore) { bestPileScore = s; bestPileIdx = d; }
} }
if (bestPileIdx === -1) bestPileIdx = 0; if (bestPileIdx === -1) bestPileIdx = 0;
return { type: 'discard', handIdx: bestHandIdx, discardIdx: bestPileIdx }; return { type: 'discard', handIdx: bestHandIdx, discardIdx: bestPileIdx };
} }
@ -193,13 +264,18 @@ function minPlayDistance(value, nexts) {
let best = 12; let best = 12;
for (const n of nexts) { for (const n of nexts) {
if (n > 12) continue; if (n > 12) continue;
if (value >= n) { const d = value >= n ? value - n : (12 - n) + value;
const d = value - n; if (d < best) best = d;
if (d < best) best = d;
} else {
const d = (12 - n) + value; // would have to wrap
if (d < best) best = d;
}
} }
return best; 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 });
}

View File

@ -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-<n> 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 };

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,10 @@
// of your 4 discard piles. Wilds are any value. Turn ends by discarding // 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). // one hand card onto any of your 4 personal discard piles (your choice).
// - First to empty their stock wins. // - 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 ──────────────────────────────────────────────────────────── // ── Card factory ────────────────────────────────────────────────────────────
// //
@ -54,13 +58,16 @@ function shuffle(arr, seed) {
} }
export const STOCK_SIZE = 30; export const STOCK_SIZE = 30;
export const MATCH_TARGET = 500;
export const HAND_SIZE = 5; export const HAND_SIZE = 5;
export const BUILD_PILE_COUNT = 4; export const BUILD_PILE_COUNT = 4;
export const DISCARD_PILE_COUNT = 4; export const DISCARD_PILE_COUNT = 4;
// ── State construction ────────────────────────────────────────────────────── // ── 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) { if (playerCount < 2 || playerCount > 4) {
throw new Error(`Skip-Bo supports 2..4 players, got ${playerCount}`); throw new Error(`Skip-Bo supports 2..4 players, got ${playerCount}`);
} }
@ -69,7 +76,7 @@ export function createInitialState({ playerCount, seed, startingPlayer = 0 } = {
const players = []; const players = [];
for (let i = 0; i < playerCount; i++) { for (let i = 0; i < playerCount; i++) {
const stock = deck.splice(0, STOCK_SIZE); const stock = deck.splice(0, stockSize);
players.push({ players.push({
seat: i, seat: i,
stock, stock,
@ -89,6 +96,14 @@ export function createInitialState({ playerCount, seed, startingPlayer = 0 } = {
seed: seed ?? null, seed: seed ?? null,
turnCount: 0, turnCount: 0,
consecutiveStuckTurns: 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 // 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; for (const c of recycled) c.playedAs = null;
shuffle(recycled, state.seed ? state.seed + state.turnCount : undefined); shuffle(recycled, state.seed ? state.seed + state.turnCount : undefined);
state.drawPile.push(...recycled); state.drawPile.push(...recycled);
state.log?.push({ kind: 'recycle', count: recycled.length });
} }
function drawOne(state) { function drawOne(state) {
@ -116,11 +132,14 @@ function drawOne(state) {
function refillHand(state, seat) { function refillHand(state, seat) {
const p = state.players[seat]; const p = state.players[seat];
let n = 0;
while (p.hand.length < HAND_SIZE) { while (p.hand.length < HAND_SIZE) {
const c = drawOne(state); const c = drawOne(state);
if (!c) break; if (!c) break;
p.hand.push(c); p.hand.push(c);
n++;
} }
if (n) state.log?.push({ kind: 'refill', seat, count: n });
} }
// ── Cloning ───────────────────────────────────────────────────────────────── // ── Cloning ─────────────────────────────────────────────────────────────────
@ -142,6 +161,14 @@ export function cloneState(state) {
seed: state.seed, seed: state.seed,
turnCount: state.turnCount, turnCount: state.turnCount,
consecutiveStuckTurns: state.consecutiveStuckTurns, 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); 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 // If pile completed (top is 12), recycle it
const topVal = buildPileTopValue(next, play.buildIdx); const topVal = buildPileTopValue(next, play.buildIdx);
@ -271,12 +300,13 @@ export function applyPlay(state, play) {
const cleared = next.buildPiles[play.buildIdx].splice(0); const cleared = next.buildPiles[play.buildIdx].splice(0);
for (const c of cleared) c.playedAs = null; for (const c of cleared) c.playedAs = null;
next.completedPile.push(...cleared); 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 // Check for win first — stock empty after a stock play wins immediately
if (player.stock.length === 0) { if (player.stock.length === 0) {
next.phase = 'gameover'; finishGame(next, seat);
next.winner = seat;
return next; return next;
} }
@ -302,6 +332,7 @@ export function applyDiscard(state, handIdx, discardIdx) {
const [card] = player.hand.splice(handIdx, 1); const [card] = player.hand.splice(handIdx, 1);
card.playedAs = null; card.playedAs = null;
player.discards[discardIdx].push(card); player.discards[discardIdx].push(card);
next.log.push({ kind: 'discard', seat, discardIdx, cardId: card.id });
// Advance turn // Advance turn
next.currentPlayer = (seat + 1) % next.players.length; next.currentPlayer = (seat + 1) % next.players.length;
@ -339,8 +370,11 @@ export function applyAutoPass(state) {
if (next.consecutiveStuckTurns >= next.players.length) { if (next.consecutiveStuckTurns >= next.players.length) {
next.phase = 'gameover'; next.phase = 'gameover';
next.winner = -1; // draw next.winner = -1; // draw
next.gameResult = { winner: -1, points: 0, perSeat: next.players.map(() => 0) };
if (next.target > 0) next.phase = 'handOver';
return next; return next;
} }
next.log.push({ kind: 'stuck', seat: next.currentPlayer });
next.currentPlayer = (next.currentPlayer + 1) % next.players.length; next.currentPlayer = (next.currentPlayer + 1) % next.players.length;
next.turnCount += 1; next.turnCount += 1;
@ -348,6 +382,48 @@ export function applyAutoPass(state) {
return next; 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 // Convenience for UI — count cards in each pile per seat for the always-on
// HUD. The top stock card is always visible separately. // HUD. The top stock card is always visible separately.
export function snapshotCounts(state) { export function snapshotCounts(state) {

View File

@ -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 };

View File

@ -1,19 +1,31 @@
// Uno AI — pure decision function. Mirrors the gofish/GoFishAI.js shape: // Uno AI — pure decision functions, scaled by skill (1..5). No scene state.
// one stateless function per decision, no scene state.
// //
// Returns one of: // chooseAction(state, seat, { skill, rng }) returns one of:
// { kind: 'play', cardId, chosenColor? } // { kind: 'play', cardId, chosenColor? }
// { kind: 'draw' } // { kind: 'draw' } — also "take the stacked penalty"
// { kind: 'playDrawn' } — after a draw, when the drawn card is playable // { kind: 'playDrawn' } | { kind: 'passDrawn' }
// { kind: 'passDrawn' } — keep the drawn card, end turn
// { kind: 'chooseColor', color } — phase === 'choosingColor' // { 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 { UNO_COLORS, buildDeck } from './UnoDeck.js';
import { legalPlays, isLegalPlay } from './UnoLogic.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_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 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) { function colorTally(hand) {
const tally = { r: 0, y: 0, g: 0, b: 0 }; const tally = { r: 0, y: 0, g: 0, b: 0 };
@ -21,113 +33,151 @@ function colorTally(hand) {
return tally; return tally;
} }
/** Pick the color the AI has the most of (ties broken by deck order). */ /** Colours a seat has recently drawn on (probably can't follow them). */
function bestColor(hand) { 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); const t = colorTally(hand);
let best = UNO_COLORS[0]; const voids = skill >= 4 ? likelyVoids(state, nextSeat(state, seat, 1)) : new Set();
for (const c of UNO_COLORS) if (t[c] > t[best]) best = c; 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; return best;
} }
/** function scoreCandidate(state, seat, card, hand, skill, rand) {
* Score a candidate play. Higher is better. Considers: const nxt = nextSeat(state, seat, 1);
* - Punish dangerous opponents (next opponent with small hand → favor action cards) const nextHandSize = state.players[nxt].hand.length;
* - 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;
const dangerous = nextHandSize <= 2; const dangerous = nextHandSize <= 2;
const ourHandSize = hand.length; const earlyGame = hand.length >= 5;
const earlyGame = ourHandSize >= 5;
let score; let score;
if (dangerous) { if (dangerous && skill >= 2) score = (KIND_PRIORITY_LATE[card.kind] ?? 0) * 10;
score = (KIND_PRIORITY_LATE[card.kind] ?? 0) * 10; else if (earlyGame) score = (KIND_PRIORITY_EARLY[card.kind] ?? 0) * 10;
} else if (earlyGame) { else score = card.kind === 'number' ? 30 : (card.kind === 'wild4' ? 5 : 25);
score = (KIND_PRIORITY_EARLY[card.kind] ?? 0) * 10; if (card.color !== 'w') score += colorTally(hand)[card.color];
} 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 (card.kind === 'wild4' && !dangerous) score -= 25; if (card.kind === 'wild4' && !dangerous) score -= 25;
if (isBluff(state, card, hand)) score -= dangerous ? (skill >= 4 ? 5 : 30) : (skill >= 4 ? 30 : 45);
// Small randomization for variety. if (card.kind === 'wild' && skill >= 3 && !dangerous) score -= 8;
score += Math.random() * 0.5; 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; 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') { 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') { 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; const pw = state.pendingWild4;
if (!pw) return { kind: 'challenge', doChallenge: false }; if (!pw) return { kind: 'challenge', doChallenge: false };
const playerHandSize = state.players[pw.playerSeat].hand.length; const stack = stackableWild4(state, seat);
const ourHandSize = state.players[seat].hand.length; if (stack.length && (skill >= 2 || rand() < 0.6)) return { kind: 'stack', cardId: stack[0] };
const suspicious = playerHandSize >= 4; let doChallenge;
const lowRisk = ourHandSize <= 3; if (skill <= 2) doChallenge = rand() < 0.3;
const doChallenge = suspicious && (lowRisk || Math.random() < 0.4); 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 }; return { kind: 'challenge', doChallenge };
} }
if (state.phase === 'mustPlayDrawn') { 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; const drawn = state.pendingDrawn;
if (!drawn) return { kind: 'passDrawn' }; if (!drawn || !isLegalPlay(state, drawn, me.hand)) return { kind: 'passDrawn' };
if (!isLegalPlay(state, drawn, me.hand)) return { kind: 'passDrawn' }; if (skill <= 1 && rand() < 0.15) return { kind: 'passDrawn' };
// Always play numbers / actions when we can. For wilds, play them only if return { kind: 'playDrawn', chosenColor: drawn.color === 'w' ? bestColor(state, seat, me.hand.filter(c => c.id !== drawn.id), skill, rand) : undefined };
// we have no other play (we already drew, so we're not blowing tempo).
return { kind: 'playDrawn' };
} }
if (state.phase !== 'play') return { kind: 'draw' }; if (state.phase !== 'play') return { kind: 'draw' };
const me = state.players[seat];
const legalIds = legalPlays(state, seat); const legalIds = legalPlays(state, seat);
if (legalIds.length === 0) return { kind: 'draw' }; 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 bestCard = null, bestScore = -Infinity;
let bestScore = -Infinity;
for (const id of legalIds) { for (const id of legalIds) {
const card = me.hand.find((c) => c.id === id); const card = me.hand.find((c) => c.id === id);
if (!card) continue; if (!card) continue;
const s = scoreCandidate(state, seat, card, me.hand); if (skill <= 2 && isBluff(state, card, me.hand)) continue; // beginners play it straight
if (s > bestScore) { const s = scoreCandidate(state, seat, card, me.hand, skill, rand);
bestScore = s; if (s > bestScore) { bestScore = s; bestCard = card; }
bestCard = card;
}
} }
if (!bestCard) return { kind: 'draw' }; if (!bestCard) return { kind: 'draw' };
const result = { kind: 'play', cardId: bestCard.id }; const result = { kind: 'play', cardId: bestCard.id };
if (bestCard.color === 'w') { if (bestCard.color === 'w') result.chosenColor = bestColor(state, seat, me.hand.filter((c) => c.id !== bestCard.id), skill, rand);
// 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));
}
return result; 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;
}

445
src/games/uno/UnoArt.js Normal file
View File

@ -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 '<c>-<0..9>', '<c>-skip', '<c>-reverse',
// '<c>-draw2', 'wild', 'wild4', and 'wild-<c>' / 'wild4-<c>'
// (a played wild ringed in its chosen colour)
// uno-back neon 90s card back
// uno-table-<n> 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 };

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
// Uno — pure state engine. No Phaser imports. // Uno — pure state engine. No Phaser imports.
// //
// Mattel rules (official): // Official rules:
// - 108-card deck; 7 cards dealt to each of 2..4 players. // - 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 // - 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 // 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 // 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 // loses turn), Wild (choose color), Wild Draw 4 (choose color; next player
// draws 4 and loses turn — but may challenge first). // draws 4 and loses turn — but may challenge first).
// - Wild Draw 4 is only legal if you have no card matching the active color. // - Wild Draw 4 is only allowed with no card matching the active color — but
// If challenged and the challenge succeeds, the player who played it draws // nothing stops a bluff. The next player may challenge: if the player held
// the 4 and play continues normally; if the challenge fails, the challenger // the colour they draw the 4 and play continues normally; if not, the
// draws 6 instead and loses their turn. // challenger draws 6 instead and loses their turn.
// - No stacking, no jump-in, no 7-0 swap. // - "UNO!": a player who plays down to one card must call it. If someone
// - First player to empty their hand wins. // 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'; import { buildDeck, cloneCard, UNO_COLORS } from './UnoDeck.js';
export const HAND_DEAL = 7; export const HAND_DEAL = 7;
export const DEFAULT_TARGET = 500;
// ── PRNG (Mulberry32) — mirrors GoFishLogic for seedable shuffles. ────────── // ── PRNG (Mulberry32) — seedable shuffles. ──────────────────────────────────
function rng(seed) { function rng(seed) {
let a = (seed >>> 0) || 1; let a = (seed >>> 0) || 1;
return () => { return () => {
@ -33,7 +43,7 @@ function rng(seed) {
} }
function shuffle(arr, 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--) { for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1)); const j = Math.floor(rand() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]]; [arr[i], arr[j]] = [arr[j], arr[i]];
@ -43,36 +53,41 @@ function shuffle(arr, seed) {
// ── State helpers ─────────────────────────────────────────────────────────── // ── State helpers ───────────────────────────────────────────────────────────
export function cloneState(state) { export function cloneState(state) {
return { return {
players: state.players.map((p) => ({ players: state.players.map((p) => ({ seat: p.seat, hand: p.hand.map(cloneCard) })),
seat: p.seat, drawPile: state.drawPile.map(cloneCard),
hand: p.hand.map(cloneCard),
})),
drawPile: state.drawPile.map(cloneCard),
discardPile: state.discardPile.map(cloneCard), discardPile: state.discardPile.map(cloneCard),
currentPlayer: state.currentPlayer, currentPlayer: state.currentPlayer,
direction: state.direction, startingPlayer: state.startingPlayer,
direction: state.direction,
currentColor: state.currentColor, currentColor: state.currentColor,
phase: state.phase, phase: state.phase,
pendingWild4: state.pendingWild4 ? { ...state.pendingWild4 } : null, pendingWild4: state.pendingWild4 ? { ...state.pendingWild4 } : null,
pendingDrawn: state.pendingDrawn ? cloneCard(state.pendingDrawn) : null, pendingDrawn: state.pendingDrawn ? cloneCard(state.pendingDrawn) : null,
lastAction: state.lastAction ? { ...state.lastAction } : null, pendingDraw: state.pendingDraw ? { ...state.pendingDraw } : null,
log: state.log.map((e) => ({ ...e })), lastAction: state.lastAction ? { ...state.lastAction } : null,
winnerSeat: state.winnerSeat, log: state.log.map((e) => ({ ...e })),
seed: state.seed, winnerSeat: state.winnerSeat,
turnCount: state.turnCount, 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]; 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; const N = state.players.length;
let s = fromSeat; let s = fromSeat;
for (let i = 0; i < hops; i++) { for (let i = 0; i < hops; i++) s = ((s + state.direction) % N + N) % N;
s = ((s + state.direction) % N + N) % N;
}
return s; return s;
} }
@ -81,18 +96,13 @@ function advanceTurn(state, hops = 1) {
state.turnCount += 1; state.turnCount += 1;
} }
/** /** Take all but the top discard, reset wilds, shuffle, make it the draw pile. */
* 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.
*/
function reshuffleIfNeeded(state) { function reshuffleIfNeeded(state) {
if (state.drawPile.length > 0) return; 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 top = state.discardPile.pop();
const recycled = state.discardPile; const recycled = state.discardPile;
for (const c of recycled) { for (const c of recycled) if (c.color === 'w') c.chosenColor = null;
if (c.color === 'w') c.chosenColor = null;
}
shuffle(recycled); shuffle(recycled);
state.drawPile = recycled; state.drawPile = recycled;
state.discardPile = [top]; state.discardPile = [top];
@ -103,39 +113,43 @@ function drawN(state, seat, n) {
const drawn = []; const drawn = [];
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
reshuffleIfNeeded(state); 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(); const c = state.drawPile.pop();
state.players[seat].hand.push(c); state.players[seat].hand.push(c);
drawn.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; 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 ──────────────────────────────────────────────────────────────── // ── Legality ────────────────────────────────────────────────────────────────
/** /**
* Whether `card` may be played on top of the current discard given * Whether `card` may be played on top of the current discard. A Wild +4 may
* state.currentColor. Wilds are always legal except Wild +4, which is only * always be played — but holding a card of the active colour makes it a
* legal when the player has no card matching state.currentColor (other wilds * bluff, which the next player can challenge (see isBluff). With a stacked
* don't block it). * Draw 2 penalty waiting, only a Draw 2 may be played.
*/ */
export function isLegalPlay(state, card, playerHand) { export function isLegalPlay(state, card, playerHand) {
if (card.color === 'w') { if (state.pendingDraw) return card.kind === 'draw2';
if (card.kind === 'wild4') { if (card.color === 'w') return true;
// 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 (card.color === state.currentColor) return true; if (card.color === state.currentColor) return true;
const top = topDiscard(state); 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' && top.kind === 'number' && card.value === top.value) return true;
if (card.kind !== 'number' && card.kind === top.kind) return true; if (card.kind !== 'number' && card.kind === top.kind) return true;
return false; 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) { export function legalPlays(state, seat) {
if (state.phase !== 'play') return []; if (state.phase !== 'play') return [];
if (state.currentPlayer !== seat) 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); 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) { export function hasAnyLegalPlay(state, seat) {
return legalPlays(state, seat).length > 0; 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 ─────────────────────────────────────────────────────────── // ── Initial state ───────────────────────────────────────────────────────────
export function createInitialState({ playerCount = 4, seed } = {}) { export function createInitialState({
if (playerCount < 2 || playerCount > 4) { playerCount = 4, seed, rules = {}, target = DEFAULT_TARGET, scores = null, handNum = 1, startingPlayer = 0,
throw new Error(`Uno supports 2..4 players, got ${playerCount}`); } = {}) {
} if (playerCount < 2 || playerCount > 4) throw new Error(`Uno supports 2..4 players, got ${playerCount}`);
const deck = buildDeck(); const deck = buildDeck();
shuffle(deck, seed); shuffle(deck, seed);
const players = []; const players = [];
for (let i = 0; i < playerCount; i++) { for (let i = 0; i < playerCount; i++) players.push({ seat: i, hand: deck.splice(0, HAND_DEAL) });
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(); let top = deck.pop();
while (top.kind === 'wild4') { for (let tries = 1; top.kind === 'wild4'; tries++) {
deck.unshift(top); 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(); top = deck.pop();
} }
@ -173,22 +198,31 @@ export function createInitialState({ playerCount = 4, seed } = {}) {
players, players,
drawPile: deck, drawPile: deck,
discardPile: [top], discardPile: [top],
currentPlayer: 0, currentPlayer: startingPlayer,
startingPlayer,
direction: 1, direction: 1,
currentColor: top.color === 'w' ? null : top.color, currentColor: top.color === 'w' ? null : top.color,
phase: 'play', phase: 'play',
pendingWild4: null, pendingWild4: null,
pendingDrawn: null, pendingDrawn: null,
pendingDraw: null,
lastAction: null, lastAction: null,
log: [{ kind: 'start', topCard: cloneCard(top) }], log: [{ kind: 'start', topCard: cloneCard(top) }],
winnerSeat: null, winnerSeat: null,
matchWinner: null,
seed: seed ?? null, seed: seed ?? null,
turnCount: 0, 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') { if (top.kind === 'wild') {
// First player must choose a color before play begins.
state.phase = 'choosingColor'; state.phase = 'choosingColor';
state.lastAction = { kind: 'startingWild' }; state.lastAction = { kind: 'startingWild' };
} else if (top.kind === 'skip') { } else if (top.kind === 'skip') {
@ -197,28 +231,65 @@ export function createInitialState({ playerCount = 4, seed } = {}) {
} else if (top.kind === 'reverse') { } else if (top.kind === 'reverse') {
state.direction = -1; state.direction = -1;
state.log.push({ kind: 'startReverse' }); state.log.push({ kind: 'startReverse' });
if (playerCount === 2) { if (playerCount === 2) advanceTurn(state, 1);
// 2-player reverse acts as a skip — first player loses their turn. else state.currentPlayer = nextSeat(state, startingPlayer, 1);
advanceTurn(state, 1);
} else {
// Direction reversed; the "first" player becomes the one before seat 0.
state.currentPlayer = nextSeat(state, 0, 1);
}
} else if (top.kind === 'draw2') { } else if (top.kind === 'draw2') {
const drawn = drawN(state, state.currentPlayer, 2); const drawn = drawN(state, state.currentPlayer, 2);
state.log.push({ kind: 'startDraw2', seat: state.currentPlayer, count: drawn.length }); state.log.push({ kind: 'startDraw2', seat: state.currentPlayer, count: drawn.length });
advanceTurn(state, 1); advanceTurn(state, 1);
} }
return state; 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 * Play `cardId` from `seat`'s hand. For wilds the engine moves to
* 'choosingColor' phase — call applyChooseColor next. Returns the same state * 'choosingColor' — call applyChooseColor next. Returns the same state if illegal.
* (unchanged) if the action is illegal.
*/ */
export function applyPlay(state, seat, cardId) { export function applyPlay(state, seat, cardId) {
if (state.phase !== 'play') return state; if (state.phase !== 'play') return state;
@ -230,79 +301,61 @@ export function applyPlay(state, seat, cardId) {
if (!isLegalPlay(state, card, player.hand)) return state; if (!isLegalPlay(state, card, player.hand)) return state;
const next = cloneState(state); const next = cloneState(state);
closeUnoWindow(next, seat);
const me = next.players[seat]; const me = next.players[seat];
// Snapshot whether the player had a color match BEFORE removing the card, const hadColorMatch = me.hand.some((c) => c.id !== cardId && c.color === next.currentColor);
// for Wild +4 challenge resolution.
const hadColorMatch = me.hand.some(
(c) => c.id !== cardId && c.color === next.currentColor,
);
const played = me.hand.splice(idx, 1)[0]; const played = me.hand.splice(idx, 1)[0];
played.chosenColor = null; played.chosenColor = null;
next.discardPile.push(played); next.discardPile.push(played);
next.lastAction = { kind: 'play', seat, card: cloneCard(played) }; next.lastAction = { kind: 'play', seat, card: cloneCard(played) };
next.log.push({ kind: 'play', seat, cardId: played.id }); next.log.push({ kind: 'play', seat, cardId: played.id });
// Win check — playing your last card wins immediately. if (me.hand.length === 0) return finishHand(next, seat, played);
if (me.hand.length === 0) { if (me.hand.length === 1) {
next.winnerSeat = seat; if (next.unoCalled[seat]) next.log.push({ kind: 'uno', seat });
next.phase = 'gameOver'; else next.unoVulnerable = seat;
next.log.push({ kind: 'win', seat });
return next;
} }
// Resolve effects.
if (played.kind === 'wild') { if (played.kind === 'wild') {
next.phase = 'choosingColor'; next.phase = 'choosingColor';
return next; return next;
} }
if (played.kind === 'wild4') { if (played.kind === 'wild4') {
next.phase = 'choosingColor'; next.phase = 'choosingColor';
next.pendingWild4 = { next.pendingWild4 = { playerSeat: seat, challengerSeat: nextSeat(next, seat, 1), hadColorMatch, count: 4, priorColor: next.currentColor };
playerSeat: seat,
challengerSeat: nextSeat(next, seat, 1),
hadColorMatch,
};
return next; return next;
} }
next.currentColor = played.color;
if (played.kind === 'skip') { if (played.kind === 'skip') {
next.currentColor = played.color; next.log.push({ kind: 'skip', seat: nextSeat(next, seat, 1) });
const skipped = nextSeat(next, seat, 1);
next.log.push({ kind: 'skip', seat: skipped });
advanceTurn(next, 2); advanceTurn(next, 2);
return next; return next;
} }
if (played.kind === 'reverse') { if (played.kind === 'reverse') {
next.currentColor = played.color;
next.direction = -next.direction; next.direction = -next.direction;
next.log.push({ kind: 'reverse' }); next.log.push({ kind: 'reverse' });
if (next.players.length === 2) { advanceTurn(next, next.players.length === 2 ? 2 : 1);
// 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);
}
return next; return next;
} }
if (played.kind === 'draw2') { if (played.kind === 'draw2') {
next.currentColor = played.color;
const target = nextSeat(next, seat, 1); 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); const drawn = drawN(next, target, 2);
next.log.push({ kind: 'draw2', seat: target, count: drawn.length }); next.log.push({ kind: 'draw2', seat: target, count: drawn.length });
advanceTurn(next, 2); advanceTurn(next, 2);
return next; return next;
} }
// Number card.
next.currentColor = played.color;
advanceTurn(next, 1); advanceTurn(next, 1);
return next; return next;
} }
/** /** Choose the color after a Wild / Wild +4 (or the starting Wild). */
* 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'.
*/
export function applyChooseColor(state, color) { export function applyChooseColor(state, color) {
if (state.phase !== 'choosingColor') return state; if (state.phase !== 'choosingColor') return state;
if (!UNO_COLORS.includes(color)) return state; if (!UNO_COLORS.includes(color)) return state;
@ -311,17 +364,11 @@ export function applyChooseColor(state, color) {
const top = topDiscard(next); const top = topDiscard(next);
if (top.color === 'w') top.chosenColor = color; if (top.color === 'w') top.chosenColor = color;
next.log.push({ kind: 'chooseColor', color }); next.log.push({ kind: 'chooseColor', color });
// Resolve the pending follow-up.
if (next.pendingWild4) { if (next.pendingWild4) {
next.phase = 'challengeWindow'; next.phase = 'challengeWindow';
next.lastAction = { kind: 'wild4Pending', color }; next.lastAction = { kind: 'wild4Pending', color };
return next; 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'; const wasStartingWild = next.lastAction?.kind === 'startingWild';
next.phase = 'play'; next.phase = 'play';
if (!wasStartingWild) advanceTurn(next, 1); if (!wasStartingWild) advanceTurn(next, 1);
@ -329,56 +376,31 @@ export function applyChooseColor(state, color) {
return next; return next;
} }
/** /** The challenger accepts the Wild +4 penalty, or challenges it. */
* The challenger either accepts the Wild +4 or challenges it. Resolves the
* draw and turn order accordingly.
*/
export function applyChallengeWild4(state, doChallenge) { export function applyChallengeWild4(state, doChallenge) {
if (state.phase !== 'challengeWindow') return state; if (state.phase !== 'challengeWindow') return state;
const next = cloneState(state); const next = cloneState(state);
const pw = next.pendingWild4; const pw = next.pendingWild4;
if (!pw) return state; if (!pw) return state;
closeUnoWindow(next, pw.challengerSeat);
const count = pw.count ?? 4;
if (!doChallenge) { if (!doChallenge) {
// Accept: challenger draws 4 and is skipped. const drawn = drawN(next, pw.challengerSeat, count);
const drawn = drawN(next, pw.challengerSeat, 4);
next.log.push({ kind: 'wild4Accept', seat: pw.challengerSeat, count: drawn.length }); next.log.push({ kind: 'wild4Accept', seat: pw.challengerSeat, count: drawn.length });
next.lastAction = { next.lastAction = { kind: 'wild4Resolve', result: 'accept', drawSeat: pw.challengerSeat, drawCount: drawn.length };
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.currentPlayer = pw.playerSeat; next.currentPlayer = pw.playerSeat;
advanceTurn(next, 2); advanceTurn(next, 2);
next.pendingWild4 = null; } else if (pw.hadColorMatch) {
next.phase = 'play'; const drawn = drawN(next, pw.playerSeat, count);
return next;
}
if (pw.hadColorMatch) {
// Successful challenge: WD4 player draws 4, play continues normally.
const drawn = drawN(next, pw.playerSeat, 4);
next.log.push({ kind: 'wild4ChallengeWin', seat: pw.playerSeat, count: drawn.length }); next.log.push({ kind: 'wild4ChallengeWin', seat: pw.playerSeat, count: drawn.length });
next.lastAction = { next.lastAction = { kind: 'wild4Resolve', result: 'challengeWin', drawSeat: pw.playerSeat, drawCount: drawn.length };
kind: 'wild4Resolve',
result: 'challengeWin',
drawSeat: pw.playerSeat,
drawCount: drawn.length,
};
next.currentPlayer = pw.challengerSeat; next.currentPlayer = pw.challengerSeat;
next.turnCount += 1; next.turnCount += 1;
} else { } else {
// Failed challenge: challenger draws 6 and is skipped. const drawn = drawN(next, pw.challengerSeat, count + 2);
const drawn = drawN(next, pw.challengerSeat, 6);
next.log.push({ kind: 'wild4ChallengeLose', seat: pw.challengerSeat, count: drawn.length }); next.log.push({ kind: 'wild4ChallengeLose', seat: pw.challengerSeat, count: drawn.length });
next.lastAction = { next.lastAction = { kind: 'wild4Resolve', result: 'challengeLose', drawSeat: pw.challengerSeat, drawCount: drawn.length };
kind: 'wild4Resolve',
result: 'challengeLose',
drawSeat: pw.challengerSeat,
drawCount: drawn.length,
};
next.currentPlayer = pw.playerSeat; next.currentPlayer = pw.playerSeat;
advanceTurn(next, 2); advanceTurn(next, 2);
} }
@ -387,24 +409,71 @@ export function applyChallengeWild4(state, doChallenge) {
return next; 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 * Draw from the pile. With a stacked Draw 2 penalty waiting this takes the
* state transitions to 'mustPlayDrawn' and the UI prompts the player to keep * whole penalty and ends the turn. Otherwise draws one card (or, with the
* or play it. Otherwise the turn advances automatically. * 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) { export function applyDraw(state, seat) {
if (state.phase !== 'play') return state; if (state.phase !== 'play') return state;
if (state.currentPlayer !== seat) return state; if (state.currentPlayer !== seat) return state;
const next = cloneState(state); const next = cloneState(state);
const drawn = drawN(next, seat, 1); closeUnoWindow(next, seat);
if (drawn.length === 0) { if (next.pendingDraw) {
// Both piles dry — pathological. Just advance the turn. 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); advanceTurn(next, 1);
return next; return next;
} }
const card = drawn[0]; const color = next.currentColor;
next.lastAction = { kind: 'draw', seat, card: cloneCard(card) }; const drawn = [];
next.log.push({ kind: 'draw', seat, count: 1 }); 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)) { if (isLegalPlay(next, card, next.players[seat].hand)) {
next.phase = 'mustPlayDrawn'; next.phase = 'mustPlayDrawn';
next.pendingDrawn = cloneCard(card); next.pendingDrawn = cloneCard(card);
@ -414,11 +483,6 @@ export function applyDraw(state, seat) {
return next; 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) { export function applyPlayDrawn(state, seat) {
if (state.phase !== 'mustPlayDrawn') return state; if (state.phase !== 'mustPlayDrawn') return state;
if (state.currentPlayer !== seat) return state; if (state.currentPlayer !== seat) return state;
@ -430,7 +494,6 @@ export function applyPlayDrawn(state, seat) {
return applyPlay(intermediate, seat, cardId); return applyPlay(intermediate, seat, cardId);
} }
/** After drawing a playable card, elect to keep it and pass. */
export function applyPassAfterDraw(state, seat) { export function applyPassAfterDraw(state, seat) {
if (state.phase !== 'mustPlayDrawn') return state; if (state.phase !== 'mustPlayDrawn') return state;
if (state.currentPlayer !== seat) return state; if (state.currentPlayer !== seat) return state;
@ -441,6 +504,47 @@ export function applyPassAfterDraw(state, seat) {
return next; 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) { export function isGameOver(state) {
return state.phase === 'gameOver'; 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);
}

101
src/games/uno/UnoTable.js Normal file
View File

@ -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 };

View File

@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
// Skill control: pips always show the level; the +/- buttons appear only // 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. // 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'; bio.style.webkitLineClamp = '1';
const skillRow = document.createElement('div'); const skillRow = document.createElement('div');

View File

@ -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;
};
}

View File

@ -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 };

View File

@ -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 };

View File

@ -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;
}

276
tools/verifySkipBo.js Normal file
View File

@ -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);

336
tools/verifyUno.js Normal file
View File

@ -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);