Redesign Phase 10 with a rec-room table, skill-scaled AI, and full tooling

- New perspective card-table layout (Phase10Table.js) and baked art module
  (Phase10Art.js): wood-paneled room, chrome-rim vinyl top, placemats,
  ghost hands, glow/spotlight effects, per-player-count backgrounds.
- Phase10Game rewritten around persistent card sprites with pose-based tweens:
  deal animation, staged laydowns on mats, hit/discard fly-ins, skip slams,
  turn spotlight, plate ladders, dock prompts, sort controls, tooltips, and
  keyboard shortcuts.
- AI (Phase10AI.js) now takes a 1-5 skill level: timing scales with hand
  speed and table pace, lower skills miss laydowns/hits, feed opponents,
  and skip randomly; higher skills avoid feeding phases and target real
  threats. Added adviseHand() for live coaching marks.
- Logic (Phase10Logic.js): orderGroupCards normalizes run position so hits
  work after out-of-order laydowns; skipTargets/applyDiscard enforce valid
  skip targets; takes log tracks discard pick-ups to break card loops.
- PhaseSpec gains groupStatus, laidGroupLabel, groupGoalLabel, cardName for
  live staging coaching and plate labels.
- OpponentSelectScene: enable the skill picker for phase10.
- tools/verifyPhase10.js: headless test suite covering rules, staging
  helpers, AI legality/timing, layout collision checks for 2/3/4 players,
  and an all-AI soak with win-rate assertions.
- NertsArt: export ensureGhostHand so Phase 10 shares the baked ghost-hand
  texture.
This commit is contained in:
Brian Fertig 2026-11-24 19:08:34 -07:00
parent e0fd2e5573
commit a1bf2bf783
No known key found for this signature in database
9 changed files with 3778 additions and 1701 deletions

View File

@ -341,6 +341,12 @@ function bakeHand(scene) {
scene.textures.addCanvas('nerts-hand', c);
}
/** The white ghost-hand texture ('nerts-hand'), baked on first use — shared with Phase 10. */
export function ensureGhostHand(scene) {
if (!scene.textures.exists('nerts-hand')) bakeHand(scene);
return 'nerts-hand';
}
function bakeTab(scene) {
const c = canvas(40, 40);
const ctx = c.getContext('2d');

View File

@ -1,8 +1,8 @@
// Phase 10 AI — heuristic single-action chooser.
// Phase 10 AI — heuristic single-action chooser, scaled by skill (1..5).
//
// The caller invokes chooseAction(state) and receives one action; after
// applying it (with animation), call again. The turn ends when a 'discard'
// action is returned (or the round/match ends).
// The caller invokes chooseAction(state, { skill }) and receives one action;
// after applying it (with animation), call again. The turn ends when a
// 'discard' action is returned (or the round/match ends).
//
// Actions:
// { type: 'drawDeck' }
@ -10,28 +10,67 @@
// { type: 'laydown', groups: [{ kind, cardIds: [...] }, ...] }
// { type: 'hit', handIdx, targetSeat, groupIdx, position }
// { type: 'discard', handIdx, skipTargetSeat? }
//
// Skill:
// 1-2 sloppy: noisy discards, rarely reads the discard pile, may miss a
// laydown or a hit for a turn, Skips whoever and whenever.
// 3 solid: the classic heuristics.
// 4-5 sharp: won't feed laid-down phases or cards an opponent picked up,
// Skips the real threat and holds the Skip until it matters.
//
// Timing for the on-screen ghost hand lives here too (aiTiming), so the
// verify script can check it.
import { getPhase } from './PhaseSpec.js';
import {
cardPoints,
discardTop,
getHitTargets,
skipTargets,
} from './Phase10Logic.js';
export function chooseAction(state) {
// Hand speed per skill (fraction of full speed) — same feel as Nerts.
export const HAND_SPEED = { 1: 0.25, 2: 0.3, 3: 0.5, 4: 0.8, 5: 1 };
export const PACE = { relaxed: 1.4, normal: 1, fast: 0.6 };
const BASE = { think: 520, between: 260, reach: 190, carry: 250, hesitate: 240 };
const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
/** Milliseconds for each part of an AI turn at a skill + table pace. */
export function aiTiming(skill, pace = 1) {
const k = clampSkill(skill);
const slow = pace / HAND_SPEED[k];
// thinking slows less steeply than the hands
const mind = pace * (1 + (5 - k) * 0.18);
return {
think: Math.round(BASE.think * mind),
between: Math.round(BASE.between * mind),
hesitate: Math.round(BASE.hesitate * mind),
reach: Math.round(BASE.reach * slow),
carry: Math.round(BASE.carry * slow),
};
}
const NOISE = { 1: 160, 2: 90, 3: 22, 4: 6, 5: 0 };
const MISS_LAYDOWN = { 1: 0.25, 2: 0.1, 3: 0, 4: 0, 5: 0 };
const MISS_HIT = { 1: 0.4, 2: 0.2, 3: 0, 4: 0, 5: 0 };
export function chooseAction(state, opts = {}) {
if (state.roundPhase !== 'play') return null;
const skill = clampSkill(opts.skill);
const rand = opts.rng ?? Math.random;
const seat = state.currentPlayer;
const player = state.players[seat];
// ── Step 1: draw ──
if (!state.drawnThisTurn) {
return chooseDraw(state);
return chooseDraw(state, skill, rand);
}
// ── Step 2: lay down if possible ──
if (!player.laidDown) {
if (!player.laidDown && !state.laidDownThisTurn) {
const layout = findLaydown(player.hand, player.phase);
if (layout) {
if (layout && !(rand() < MISS_LAYDOWN[skill])) {
return {
type: 'laydown',
groups: layout.map((g) => ({ kind: g.kind, cardIds: g.cards.map((c) => c.id) })),
@ -41,21 +80,59 @@ export function chooseAction(state) {
// ── Step 3: hit ──
if (player.laidDown) {
const hit = findBestHit(state);
if (hit) return hit;
const hit = findBestHit(state, skill);
if (hit && !(rand() < MISS_HIT[skill])) return hit;
}
// ── Step 4: discard ──
return chooseDiscard(state);
return chooseDiscard(state, skill, rand);
}
/**
* Coaching for the human (or any seat): which cards to keep, which to throw,
* which can be hit right now, and whether the phase can be laid down.
*/
export function adviseHand(state, seat) {
const player = state.players[seat];
const hand = player.hand;
const out = { keepers: new Set(), hittable: new Set(), discardId: null, laydown: null };
if (!player.laidDown) {
out.laydown = findLaydown(hand, player.phase);
const keep = out.laydown
? new Set(out.laydown.flatMap((g) => g.cards.map((c) => c.id)))
: reserveLikelyKeepers(hand, player.phase);
out.keepers = keep;
} else {
for (const c of hand) {
if (c.value !== 'skip' && getHitTargets(state, c).length) out.hittable.add(c.id);
}
}
if (state.currentPlayer === seat && state.drawnThisTurn && hand.length) {
const d = chooseDiscard(state, 5, () => 0.5);
out.discardId = hand[d.handIdx]?.id ?? null;
}
return out;
}
// ── Draw step ───────────────────────────────────────────────────────────────
function chooseDraw(state) {
function chooseDraw(state, skill = 3, rand = Math.random) {
const seat = state.currentPlayer;
const player = state.players[seat];
const top = discardTop(state);
if (top && top.value !== 'skip') {
// A card that has already changed hands twice this round is being passed
// around in a loop — go to the deck instead so the round keeps moving.
const recycled = top && (state.takes ?? []).filter((t) => t.id === top.id).length >= 2;
if (top && top.value !== 'skip' && !recycled) {
if (top.value === 'wild') return { type: 'drawDiscard' };
// Low skill only notices a discard that finishes the phase outright.
if (skill <= 2) {
const completes = !player.laidDown && !findLaydown(player.hand, player.phase)
&& findLaydown([...player.hand, top], player.phase);
if (completes && rand() < (skill === 1 ? 0.6 : 0.85)) return { type: 'drawDiscard' };
if (!completes && rand() < 0.12 * skill && cardIsUseful(top, player)) return { type: 'drawDiscard' };
return { type: 'drawDeck' };
}
// Take from discard if the top is immediately useful.
if (cardIsUseful(top, player)) return { type: 'drawDiscard' };
}
@ -131,7 +208,7 @@ function progressContribution(card, hand, phaseNum) {
// ── Hit step ────────────────────────────────────────────────────────────────
function findBestHit(state) {
function findBestHit(state, skill = 3) {
const seat = state.currentPlayer;
const hand = state.players[seat].hand;
if (hand.length === 0) return null;
@ -155,7 +232,7 @@ function findBestHit(state) {
// ── Discard step ────────────────────────────────────────────────────────────
function chooseDiscard(state) {
function chooseDiscard(state, skill = 3, rand = Math.random) {
const seat = state.currentPlayer;
const player = state.players[seat];
const hand = player.hand;
@ -173,24 +250,30 @@ function chooseDiscard(state) {
}
}
// Choose card to discard.
// Priority: 1) Skip (with targeted opponent), 2) Wilds NEVER, 3) unreserved
// high-point natural, 4) any unreserved card, 5) reserved card.
// 1) If we hold a Skip, save it for now unless our hand is large and the
// opponent leader is close to going out.
// 1) Skips: low skill throws one at whoever, right away; higher skill saves
// it for the real threat (or when our hand is heavy).
const skipIdx = hand.findIndex((c) => c.value === 'skip');
if (skipIdx !== -1) {
const leader = pickSkipTarget(state, seat);
const targets = skipTargets(state, seat);
if (skipIdx !== -1 && targets.length) {
if (skill <= 2) {
return { type: 'discard', handIdx: skipIdx, skipTargetSeat: targets[Math.floor(rand() * targets.length)] };
}
const leader = pickSkipTarget(state, seat, skill);
if (leader != null) {
// Use the Skip when an opponent is at ≤ 3 cards OR our hand is heavy.
const leaderHand = state.players[leader].hand.length;
if (leaderHand <= 3 || hand.length >= 8) {
return { type: 'discard', handIdx: skipIdx, skipTargetSeat: leader };
}
const lp = state.players[leader];
const threat = skill >= 4
? (lp.laidDown && lp.hand.length <= 4) || lp.hand.length <= 3 || hand.length >= 8 || hand.length <= 2
: lp.hand.length <= 3 || hand.length >= 8;
if (threat) return { type: 'discard', handIdx: skipIdx, skipTargetSeat: leader };
}
}
// What the table can use (sharp players won't feed it).
const feeds = skill >= 4 ? feedRisk(state, seat) : null;
// Never throw back the card just taken from the pile (two players would
// otherwise trade it back and forth forever and the deck never moves).
const justTook = new Set((state.takes ?? []).filter((t) => t.seat === seat && t.turn === state.turnCount).map((t) => t.id));
// Score every card; higher = more discardable.
let bestIdx = -1;
let bestScore = -Infinity;
@ -200,38 +283,56 @@ function chooseDiscard(state) {
if (c.value === 'wild') s -= 1000; // never discard wilds
if (c.value === 'skip') s -= 500; // don't discard skips here (handled above)
if (reservedIds.has(c.id)) s -= 100;
if (justTook.has(c.id)) s -= 400;
if (feeds) s -= feeds(c);
s += rand() * NOISE[skill];
if (s > bestScore) { bestScore = s; bestIdx = i; }
}
if (bestIdx === -1) bestIdx = 0;
const out = { type: 'discard', handIdx: bestIdx };
// If forced to discard a skip (no other choice), target someone valid.
// Forced to discard a skip (no other choice): target someone if anyone can be skipped.
if (hand[bestIdx].value === 'skip') {
const tgt = pickSkipTarget(state, seat);
const tgt = pickSkipTarget(state, seat, skill);
if (tgt != null) out.skipTargetSeat = tgt;
else {
// No valid skip target — pick a different card.
for (let i = 0; i < hand.length; i++) {
if (hand[i].value !== 'skip' && hand[i].value !== 'wild') {
out.handIdx = i;
delete out.skipTargetSeat;
break;
}
}
}
}
return out;
}
function pickSkipTarget(state, seat) {
// Penalty (0..) for discarding `card` because it would help someone else:
// it can be hit onto a laid-down phase, or it matches what an opponent has
// been picking up off the discard pile.
function feedRisk(state, seat) {
const others = state.players.filter((p) => p.seat !== seat);
const anyLaid = others.some((p) => p.laidDown);
const takes = (state.takes ?? []).filter((t) => t.seat !== seat);
return (card) => {
if (typeof card.value !== 'number') return 0;
let pen = 0;
if (anyLaid && getHitTargets(state, card).length) pen += 45;
for (const t of takes) {
const tp = state.players[t.seat];
const spec = getPhase(tp.phase);
if (!spec || tp.laidDown) continue;
const kinds = spec.groups.map((g) => g.kind);
if (kinds.includes('set') && t.value === card.value) pen += 30;
if (kinds.includes('color') && t.color === card.color) pen += 18;
if (kinds.includes('run') && typeof t.value === 'number' && Math.abs(t.value - card.value) <= 2 && t.value !== card.value) pen += 12;
}
return Math.min(pen, 90);
};
}
function pickSkipTarget(state, seat, skill = 3) {
// Pick the opponent with the smallest hand; tie-break by furthest phase
// (most threatening) and then by lowest score.
// (most threatening) and then by lowest score. Sharp players weigh a
// laid-down phase (they're close to going out) above everything.
let best = null;
let bestKey = null;
for (let s = 0; s < state.players.length; s++) {
if (s === seat) continue;
for (const s of skipTargets(state, seat)) {
const p = state.players[s];
if (p.skipped) continue;
const key = [p.hand.length, -p.phase, p.score];
const key = skill >= 4
? [p.laidDown ? 0 : 1, p.hand.length, -p.phase, p.score]
: [p.hand.length, -p.phase, p.score];
if (best === null || lex(key, bestKey) < 0) { best = s; bestKey = key; }
}
return best;

View File

@ -0,0 +1,630 @@
// Phase 10 art — all baked once into canvas textures (no image files).
//
// p10-cards atlas at 2× — frames '<color>-<1..12>', 'wild', 'skip'
// p10-back retro striped card back (used when no sprite back is chosen)
// p10-glow soft card-sized outline (selection / target glow, tinted)
// p10-spot radial light pool (turn spotlight, additive)
// p10-table-<n> the whole room for n players: wood-panel wall, chrome-rim
// card table with tufted vinyl, seat placemats, pile spots
//
// The score pad paper and the ghost hand come from the Nerts art module
// (ensurePad / ensureGhostHand). Geometry is Phase10Table.js, so mats and pile
// spots line up with where the scene puts cards.
import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern } from '../../ui/casino/CasinoArt.js';
import { COLORS_LIST } from './PhaseSpec.js';
import {
P, W, H, CARD_W, CARD_H, FELT_K, RAIL_FACE_PX, SEAT_HEX, SQ,
outline, layoutFor, matCorners, poseScale,
} from './Phase10Table.js';
const RES = 2;
const CW = CARD_W * RES;
const CH = CARD_H * RES;
const FONT = 'Righteous, "Arial Black", sans-serif';
export const CARD_COLORS = {
red: { hi: '#f0634f', mid: '#d23a2c', lo: '#8f1d16', ink: '#b22a1f' },
blue: { hi: '#5a92ec', mid: '#2b62c8', lo: '#173a7c', ink: '#1f4fa8' },
yellow: { hi: '#ffd44f', mid: '#f0ae1a', lo: '#a86c08', ink: '#b77b06' },
green: { hi: '#5cc77a', mid: '#2e9a4f', lo: '#185c2c', ink: '#1f7a3b' },
};
const CREAM = '#fbf4e2';
// Table-top vinyl: deep retro teal, so it reads apart from the wood paneling
// and the straw placemats.
const VINYL = '#1d5250';
const VINYL_TUFT = '#0c2a29';
const CREAM_DK = '#e9dcbd';
// ── Cards ────────────────────────────────────────────────────────────────────
function cardBase(ctx, x, y) {
rr(ctx, x + 2, y + 2, CW - 4, CH - 4, 16);
ctx.fillStyle = CREAM;
ctx.fill();
ctx.save();
ctx.clip();
ctx.fillStyle = noisePattern(ctx, 96, 14);
ctx.fillRect(x, y, CW, CH);
ctx.restore();
rr(ctx, x + 2, y + 2, CW - 4, CH - 4, 16);
ctx.lineWidth = 2.5;
ctx.strokeStyle = 'rgba(40,28,14,0.55)';
ctx.stroke();
}
function panelPath(ctx, x, y) {
rr(ctx, x + 13, y + 13, CW - 26, CH - 26, 12);
}
// Colour-blind helper shapes, one per colour.
function shape(ctx, color, cx, cy, r, fill) {
ctx.save();
ctx.fillStyle = fill;
ctx.beginPath();
if (color === 'red') ctx.arc(cx, cy, r, 0, Math.PI * 2);
else if (color === 'blue') ctx.rect(cx - r * 0.88, cy - r * 0.88, r * 1.76, r * 1.76);
else if (color === 'yellow') { ctx.moveTo(cx, cy - r * 1.1); ctx.lineTo(cx + r * 1.05, cy + r * 0.8); ctx.lineTo(cx - r * 1.05, cy + r * 0.8); ctx.closePath(); }
else { ctx.moveTo(cx, cy - r * 1.15); ctx.lineTo(cx + r, cy); ctx.lineTo(cx, cy + r * 1.15); ctx.lineTo(cx - r, cy); ctx.closePath(); }
ctx.fill();
ctx.restore();
}
function cornerIndex(ctx, x, y, text, color, fill, underline) {
const draw = () => {
ctx.font = `${text.length > 1 ? 40 : 46}px ${FONT}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = fill;
ctx.fillText(text, 0, 0);
if (underline) ctx.fillRect(-12, 25, 24, 4);
if (color) shape(ctx, color, 0, 46, 9, fill);
};
ctx.save();
ctx.translate(x + 38, y + 46);
draw();
ctx.restore();
ctx.save();
ctx.translate(x + CW - 38, y + CH - 46);
ctx.rotate(Math.PI);
draw();
ctx.restore();
}
function lozenge(ctx, cx, cy, w, h) {
ctx.beginPath();
ctx.ellipse(cx, cy, w / 2, h / 2, -0.32, 0, Math.PI * 2);
}
function drawNumberCard(ctx, x, y, color, value) {
const c = CARD_COLORS[color];
cardBase(ctx, x, y);
ctx.save();
panelPath(ctx, x, y);
const g = ctx.createLinearGradient(x, y, x + CW, y + CH);
g.addColorStop(0, c.hi);
g.addColorStop(0.55, c.mid);
g.addColorStop(1, c.lo);
ctx.fillStyle = g;
ctx.fill();
ctx.clip();
// 70s pinstripes through the middle
ctx.globalAlpha = 0.16;
ctx.fillStyle = CREAM;
for (let i = -3; i <= 3; i++) {
ctx.save();
ctx.translate(x + CW / 2, y + CH / 2);
ctx.rotate(-0.32);
ctx.fillRect(-CW, i * 22 - 5, CW * 2, 7);
ctx.restore();
}
ctx.globalAlpha = 1;
ctx.restore();
// cream bubble with the big number
const cx = x + CW / 2, cy = y + CH / 2;
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.35)';
ctx.shadowBlur = 8;
ctx.shadowOffsetY = 3;
lozenge(ctx, cx, cy, 142, 176);
ctx.fillStyle = CREAM;
ctx.fill();
ctx.restore();
lozenge(ctx, cx, cy, 142, 176);
ctx.lineWidth = 3;
ctx.strokeStyle = c.lo;
ctx.stroke();
const txt = String(value);
ctx.font = `${txt.length > 1 ? 92 : 108}px ${FONT}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineWidth = 8;
ctx.strokeStyle = 'rgba(30,20,10,0.55)';
ctx.strokeText(txt, cx, cy + 4);
ctx.fillStyle = c.ink;
ctx.fillText(txt, cx, cy + 4);
if (value === 6 || value === 9) {
ctx.fillStyle = c.ink;
ctx.fillRect(cx - 22, cy + 52, 44, 7);
}
cornerIndex(ctx, x, y, txt, color, CREAM, value === 6 || value === 9);
// gloss
ctx.save();
panelPath(ctx, x, y);
ctx.clip();
const gl = ctx.createLinearGradient(x, y, x + CW * 0.6, y + CH * 0.5);
gl.addColorStop(0, 'rgba(255,255,255,0.28)');
gl.addColorStop(0.5, 'rgba(255,255,255,0.04)');
gl.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = gl;
ctx.fillRect(x, y, CW, CH);
ctx.restore();
}
function drawWild(ctx, x, y) {
cardBase(ctx, x, y);
ctx.save();
panelPath(ctx, x, y);
ctx.clip();
const order = ['red', 'yellow', 'green', 'blue'];
ctx.translate(x + CW / 2, y + CH / 2);
ctx.rotate(-0.5);
for (let i = 0; i < 8; i++) {
ctx.fillStyle = CARD_COLORS[order[i % 4]].mid;
ctx.fillRect(-CW * 1.5 + i * 58 - 58, -CH, 58, CH * 2);
}
ctx.restore();
const cx = x + CW / 2, cy = y + CH / 2;
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.4)';
ctx.shadowBlur = 8;
ctx.shadowOffsetY = 3;
lozenge(ctx, cx, cy, 148, 182);
ctx.fillStyle = '#2a1d12';
ctx.fill();
ctx.restore();
lozenge(ctx, cx, cy, 148, 182);
ctx.lineWidth = 4;
ctx.strokeStyle = CREAM;
ctx.stroke();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = `100px ${FONT}`;
const grad = ctx.createLinearGradient(cx - 40, cy - 50, cx + 40, cy + 40);
grad.addColorStop(0, CARD_COLORS.yellow.hi);
grad.addColorStop(0.5, CARD_COLORS.red.hi);
grad.addColorStop(1, CARD_COLORS.blue.hi);
ctx.fillStyle = grad;
ctx.fillText('W', cx, cy - 6);
ctx.font = `30px ${FONT}`;
ctx.fillStyle = CREAM;
ctx.fillText('WILD', cx, cy + 58);
cornerIndex(ctx, x, y, 'W', null, CREAM, false);
}
function drawSkip(ctx, x, y) {
cardBase(ctx, x, y);
ctx.save();
panelPath(ctx, x, y);
const g = ctx.createLinearGradient(x, y, x, y + CH);
g.addColorStop(0, '#3a3430');
g.addColorStop(1, '#141110');
ctx.fillStyle = g;
ctx.fill();
ctx.clip();
ctx.globalAlpha = 0.12;
ctx.fillStyle = '#ff8a5b';
for (let i = -4; i <= 4; i++) ctx.fillRect(x + CW / 2 + i * 26 - 3, y, 6, CH);
ctx.globalAlpha = 1;
ctx.restore();
const cx = x + CW / 2, cy = y + CH / 2 - 6;
ctx.lineCap = 'round';
ctx.lineWidth = 16;
ctx.strokeStyle = '#ff6b4a';
ctx.beginPath();
ctx.arc(cx, cy, 52, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(cx - 36, cy - 36);
ctx.lineTo(cx + 36, cy + 36);
ctx.stroke();
ctx.lineCap = 'butt';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = `32px ${FONT}`;
ctx.fillStyle = CREAM;
ctx.fillText('SKIP', cx, cy + 86);
cornerIndex(ctx, x, y, 'S', null, '#ff9a7a', false);
}
export function frameKey(card) {
if (card.value === 'wild') return 'wild';
if (card.value === 'skip') return 'skip';
return `${card.color}-${card.value}`;
}
function bakeCards(scene) {
const keys = [];
for (const col of COLORS_LIST) for (let v = 1; v <= 12; v++) keys.push([`${col}-${v}`, (ctx, x, y) => drawNumberCard(ctx, x, y, col, v)]);
keys.push(['wild', drawWild], ['skip', drawSkip]);
const cols = 10;
const rows = Math.ceil(keys.length / cols);
const c = canvas(cols * CW, rows * CH);
const ctx = c.getContext('2d');
keys.forEach(([, draw], i) => draw(ctx, (i % cols) * CW, Math.floor(i / cols) * CH));
const tex = scene.textures.addCanvas('p10-cards', c);
keys.forEach(([k], i) => tex.add(k, 0, (i % cols) * CW, Math.floor(i / cols) * CH, CW, CH));
}
function bakeBack(scene) {
const c = canvas(CW, CH);
const ctx = c.getContext('2d');
rr(ctx, 2, 2, CW - 4, CH - 4, 16);
ctx.fillStyle = '#3b2416';
ctx.fill();
ctx.save();
ctx.clip();
// stacked 70s stripes arching across the card
const bands = ['#f2ead8', '#f0ae1a', '#e2702a', '#b5402a', '#6b2a1c'];
for (let i = 0; i < bands.length; i++) {
ctx.beginPath();
ctx.ellipse(CW / 2, CH * 1.05, CW * (1.05 - i * 0.14), CH * (0.82 - i * 0.11), 0, Math.PI, 0);
ctx.lineWidth = 15;
ctx.strokeStyle = bands[i];
ctx.stroke();
}
for (let i = 0; i < bands.length; i++) {
ctx.beginPath();
ctx.ellipse(CW / 2, -CH * 0.05, CW * (1.05 - i * 0.14), CH * (0.82 - i * 0.11), 0, 0, Math.PI);
ctx.lineWidth = 15;
ctx.strokeStyle = bands[i];
ctx.stroke();
}
ctx.fillStyle = noisePattern(ctx, 96, 20);
ctx.fillRect(0, 0, CW, CH);
ctx.restore();
// centre medallion
ctx.beginPath();
ctx.arc(CW / 2, CH / 2, 40, 0, Math.PI * 2);
ctx.fillStyle = '#2a1a10';
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = '#f0ae1a';
ctx.stroke();
ctx.font = `40px ${FONT}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#f2ead8';
ctx.fillText('10', CW / 2, CH / 2 + 2);
rr(ctx, 9, 9, CW - 18, CH - 18, 11);
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgba(242,234,216,0.75)';
ctx.stroke();
rr(ctx, 2, 2, CW - 4, CH - 4, 16);
ctx.lineWidth = 2.5;
ctx.strokeStyle = 'rgba(0,0,0,0.6)';
ctx.stroke();
scene.textures.addCanvas('p10-back', c);
}
function bakeGlow(scene) {
const pad = 30;
const c = canvas(CW + pad * 2, CH + pad * 2);
const ctx = c.getContext('2d');
ctx.shadowColor = '#ffffff';
ctx.shadowBlur = 22;
rr(ctx, pad, pad, CW, CH, 18);
ctx.lineWidth = 8;
ctx.strokeStyle = '#ffffff';
ctx.stroke();
ctx.stroke();
scene.textures.addCanvas('p10-glow', c);
}
function bakeSpot(scene) {
const S = 256;
const c = canvas(S, S);
const ctx = c.getContext('2d');
const g = ctx.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2);
g.addColorStop(0, 'rgba(255,255,255,1)');
g.addColorStop(0.45, 'rgba(255,255,255,0.45)');
g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, S, S);
scene.textures.addCanvas('p10-spot', c);
}
// ── The room ────────────────────────────────────────────────────────────────
function drawWall(ctx) {
// vertical wood paneling with V-grooves
const base = ctx.createLinearGradient(0, 0, 0, H);
base.addColorStop(0, '#2c1a0e');
base.addColorStop(0.5, '#4a2c16');
base.addColorStop(1, '#22140a');
ctx.fillStyle = base;
ctx.fillRect(0, 0, W, H);
let x = 0;
let i = 0;
while (x < W) {
const w = 74 + ((i * 37) % 3) * 9;
const tone = ['#5a361b', '#4d2d16', '#63401f', '#523118'][i % 4];
ctx.globalAlpha = 0.55;
ctx.fillStyle = tone;
ctx.fillRect(x + 2, 0, w - 4, H);
// grain
ctx.globalAlpha = 0.14;
for (let k = 0; k < 9; k++) {
const gx = x + 6 + Math.random() * (w - 12);
ctx.beginPath();
ctx.moveTo(gx, 0);
for (let y = 0; y <= H; y += 60) ctx.lineTo(gx + Math.sin(y * 0.01 + k + i) * 3, y);
ctx.lineWidth = 1 + Math.random() * 2;
ctx.strokeStyle = Math.random() < 0.5 ? '#1a0d05' : '#8a5a2c';
ctx.stroke();
}
ctx.globalAlpha = 1;
// groove
ctx.fillStyle = '#140a04';
ctx.fillRect(x, 0, 2, H);
ctx.fillStyle = 'rgba(255,200,140,0.1)';
ctx.fillRect(x + 2, 0, 1, H);
x += w;
i++;
}
ctx.fillStyle = noisePattern(ctx, 128, 16);
ctx.fillRect(0, 0, W, H);
// warm lamp wash at the top, dark corners
const lamp = ctx.createRadialGradient(W / 2, 120, 40, W / 2, 200, 1100);
lamp.addColorStop(0, 'rgba(255,190,110,0.28)');
lamp.addColorStop(0.5, 'rgba(255,170,90,0.06)');
lamp.addColorStop(1, 'rgba(0,0,0,0.5)');
ctx.fillStyle = lamp;
ctx.fillRect(0, 0, W, H);
}
function drawFloorShadow(ctx) {
const OFF = 6000;
const pts = outline(1.0, 18).map(p => ({ x: p.x - OFF, y: p.y + RAIL_FACE_PX * p.s + 8 }));
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.8)';
ctx.shadowBlur = 70;
ctx.shadowOffsetX = OFF;
ctx.shadowOffsetY = 30;
poly(ctx, pts);
ctx.fillStyle = '#000';
ctx.fill();
ctx.restore();
}
function drawFrontFace(ctx) {
// chrome edge band: bright / dark stripes like a diner table
const top = outline(1.0, 18);
const tones = ['#f4f6f8', '#c9ced4', '#7d848c', '#e4e8ec', '#9aa1a9', '#5b6168', '#3b3f44'];
for (let i = 0; i <= 14; i++) {
const f = i / 14;
poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f })));
ctx.fillStyle = tones[Math.min(tones.length - 1, Math.floor(f * tones.length))];
ctx.fill();
}
// ribbed grooves
for (const f of [0.3, 0.55, 0.8]) {
poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f })), true);
ctx.lineWidth = 1.5;
ctx.strokeStyle = 'rgba(30,32,36,0.5)';
ctx.stroke();
}
poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s })));
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgba(0,0,0,0.85)';
ctx.stroke();
}
function bandPath(ctx, k0, k1) {
const outer = outline(k1, 18), inner = outline(k0, 18);
ctx.beginPath();
outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.closePath();
inner.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
ctx.closePath();
}
function ring(ctx, k, width, color) {
poly(ctx, outline(k, 18));
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.stroke();
}
function drawRim(ctx) {
ctx.save();
bandPath(ctx, FELT_K, 1.0);
ctx.fillStyle = '#aab0b7';
ctx.fill('evenodd');
ctx.clip('evenodd');
for (let i = 0; i <= 18; i++) {
const f = i / 18;
const crown = Math.sin(f * Math.PI);
ring(ctx, lerp(FELT_K, 1.0, f), 4, mix('#4c5258', '#ffffff', Math.pow(crown, 2.2) * 0.95));
}
// lamp reflections along the far chrome
const c = P.project(0, 0.0);
const glint = ctx.createRadialGradient(c.x, c.y, 10, c.x, c.y, 420);
glint.addColorStop(0, 'rgba(255,240,210,0.65)');
glint.addColorStop(1, 'rgba(255,240,210,0)');
ctx.fillStyle = glint;
ctx.fillRect(0, 0, W, H);
ctx.restore();
ring(ctx, 1.0, 2, 'rgba(0,0,0,0.6)');
// black rubber gasket where the vinyl meets the chrome
ring(ctx, FELT_K + 0.002, 5, '#141416');
}
function drawVinyl(ctx) {
const felt = outline(FELT_K, 18);
ctx.save();
poly(ctx, felt);
ctx.clip();
ctx.fillStyle = VINYL;
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = noisePattern(ctx, 192, 26);
ctx.fillRect(0, 0, W, H);
// tufted diamond quilting in table space (perspective-correct)
const du = 0.16, dv = 0.16 * 0.56;
const line = (u0, v0, u1, v1, color, width, dy = 0) => {
const a = P.project(u0, v0), b = P.project(u1, v1);
ctx.beginPath();
ctx.moveTo(a.x, a.y + dy);
ctx.lineTo(b.x, b.y + dy);
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.stroke();
};
for (let k = -20; k <= 20; k++) {
const u = k * du;
// two diagonal families: (u + t, t) and (u - t, t) scaled to the diamond aspect
const a0 = { u: u, v: -0.05 }, a1 = { u: u + (1.1 / dv) * du, v: 1.05 };
const b1 = { u: u - (1.1 / dv) * du, v: 1.05 };
line(a0.u, a0.v, a1.u, a1.v, 'rgba(0,18,20,0.4)', 3);
line(a0.u, a0.v, a1.u, a1.v, 'rgba(170,240,230,0.08)', 1.5, 2);
line(a0.u, a0.v, b1.u, b1.v, 'rgba(0,18,20,0.4)', 3);
line(a0.u, a0.v, b1.u, b1.v, 'rgba(170,240,230,0.08)', 1.5, 2);
}
// tuft buttons at the crossings
// the two families cross every half-step down, alternating half-step across
for (let row = 0; row * (dv / 2) <= 1.1; row++) {
const v = -0.05 + row * (dv / 2);
const off = row % 2 ? du / 2 : 0;
for (let k = -8; k <= 8; k++) {
const p = P.project(k * du + off, v);
ctx.beginPath();
ctx.ellipse(p.x, p.y, 4.5 * p.s, 3.6 * p.s, 0, 0, Math.PI * 2);
ctx.fillStyle = VINYL_TUFT;
ctx.fill();
ctx.beginPath();
ctx.ellipse(p.x - 1, p.y - 1, 1.8 * p.s, 1.3 * p.s, 0, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(190,250,240,0.28)';
ctx.fill();
}
}
// overhead lamp pool + vignette
const c = P.project(0, 0.5);
const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1050);
lamp.addColorStop(0, 'rgba(255,214,150,0.26)');
lamp.addColorStop(0.45, 'rgba(255,214,150,0.08)');
lamp.addColorStop(1, 'rgba(255,214,150,0)');
ctx.fillStyle = lamp;
ctx.fillRect(0, 0, W, H);
const vig = ctx.createRadialGradient(c.x, c.y, 360, c.x, c.y, 1150);
vig.addColorStop(0, 'rgba(0,0,0,0)');
vig.addColorStop(1, 'rgba(0,0,0,0.55)');
ctx.fillStyle = vig;
ctx.fillRect(0, 0, W, H);
for (let i = 0; i < 10; i++) ring(ctx, FELT_K - i * 0.004, 4, `rgba(0,0,0,${0.32 * (1 - i / 10)})`);
ctx.restore();
}
function drawMats(ctx, L) {
for (const st of L.seats) {
const hex = SEAT_HEX[st.seat];
const pts = matCorners(L, st.seat, 10);
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.shadowBlur = 14;
ctx.shadowOffsetY = 5;
poly(ctx, pts);
ctx.fillStyle = '#c99a52';
ctx.fill();
ctx.restore();
ctx.save();
poly(ctx, pts);
ctx.clip();
// woven straw placemat: two families of fine stripes
const top = Math.min(...pts.map(p => p.y)), btm = Math.max(...pts.map(p => p.y));
const lft = Math.min(...pts.map(p => p.x)), rgt = Math.max(...pts.map(p => p.x));
const g = ctx.createLinearGradient(0, top, 0, btm);
g.addColorStop(0, '#d9ac62');
g.addColorStop(1, '#a8772f');
ctx.fillStyle = g;
ctx.fillRect(lft, top, rgt - lft, btm - top);
ctx.globalAlpha = 0.18;
for (let y = top; y < btm; y += 5) {
ctx.fillStyle = (Math.round(y / 5) % 2) ? '#6b4214' : '#f6d79a';
ctx.fillRect(lft, y, rgt - lft, 2);
}
ctx.globalAlpha = 0.08;
for (let x = lft; x < rgt; x += 9) {
ctx.fillStyle = '#4a2a0c';
ctx.fillRect(x, top, 2, btm - top);
}
ctx.globalAlpha = 1;
ctx.fillStyle = noisePattern(ctx, 96, 22);
ctx.fillRect(lft, top, rgt - lft, btm - top);
// subtle darkening so cards pop
ctx.fillStyle = 'rgba(40,20,6,0.18)';
ctx.fillRect(lft, top, rgt - lft, btm - top);
ctx.restore();
// seat-coloured piping + stitch
poly(ctx, pts);
ctx.lineWidth = 5;
ctx.strokeStyle = hex;
ctx.stroke();
poly(ctx, matCorners(L, st.seat, 3));
ctx.setLineDash([7, 6]);
ctx.lineWidth = 1.4;
ctx.strokeStyle = 'rgba(255,244,214,0.55)';
ctx.stroke();
ctx.setLineDash([]);
}
}
function pileSpot(ctx, pose, label) {
const { sx, sy } = poseScale(pose.s, pose.rot, SQ);
ctx.save();
ctx.translate(pose.x, pose.y);
ctx.scale(sx, sy);
rr(ctx, -CARD_W / 2 - 8, -CARD_H / 2 - 8, CARD_W + 16, CARD_H + 16, 14);
ctx.fillStyle = 'rgba(0,0,0,0.22)';
ctx.fill();
ctx.setLineDash([9, 7]);
ctx.lineWidth = 2.2 / sx;
ctx.strokeStyle = 'rgba(242,214,160,0.45)';
ctx.stroke();
ctx.setLineDash([]);
ctx.restore();
ctx.font = `16px "Julius Sans One", sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(242,214,160,0.5)';
ctx.fillText(label, pose.x, pose.y - (CARD_H / 2) * sy - 26);
}
function bakeTable(scene, key, playerCount) {
const L = layoutFor(playerCount);
const c = canvas(W, H);
const ctx = c.getContext('2d');
drawWall(ctx);
drawFloorShadow(ctx);
drawFrontFace(ctx);
drawRim(ctx);
drawVinyl(ctx);
ctx.save();
poly(ctx, outline(FELT_K, 18));
ctx.clip();
drawMats(ctx, L);
pileSpot(ctx, L.deck, 'DRAW');
pileSpot(ctx, L.discard, 'DISCARD');
ctx.restore();
scene.textures.addCanvas(key, c);
}
export async function preparePhase10Art(scene, playerCount) {
await prepareCasinoArt(scene);
if (!scene.textures.exists('p10-cards')) bakeCards(scene);
if (!scene.textures.exists('p10-back')) bakeBack(scene);
if (!scene.textures.exists('p10-glow')) bakeGlow(scene);
if (!scene.textures.exists('p10-spot')) bakeSpot(scene);
const key = `p10-table-${playerCount}`;
if (!scene.textures.exists(key)) bakeTable(scene, key, playerCount);
return key;
}
export { CW as CARD_TEX_W, CH as CARD_TEX_H, CREAM, CREAM_DK };

File diff suppressed because it is too large Load Diff

View File

@ -77,6 +77,7 @@ export function createInitialState({ playerCount, seed, startingPlayer = 0 } = {
lastRoundSummary: null,
drawnThisTurn: false,
laidDownThisTurn: false,
takes: [], // this round's discard pick-ups: { seat, value, color, id, turn }
};
for (let i = 0; i < playerCount; i++) {
state.players.push({
@ -108,6 +109,7 @@ function dealRound(state) {
state.laidDownThisTurn = false;
state.roundPhase = 'play';
state.roundWinner = null;
state.takes = [];
}
// ── Cloning ─────────────────────────────────────────────────────────────────
@ -138,6 +140,7 @@ export function cloneState(state) {
: null,
drawnThisTurn: state.drawnThisTurn,
laidDownThisTurn: state.laidDownThisTurn,
takes: (state.takes ?? []).map((t) => ({ ...t })),
};
}
@ -151,6 +154,12 @@ export function discardTop(state) {
return state.discardPile.length > 0 ? state.discardPile[state.discardPile.length - 1] : null;
}
export function handPoints(hand) {
let pts = 0;
for (const c of hand) pts += cardPoints(c);
return pts;
}
export function cardPoints(card) {
if (card.value === 'wild') return POINTS.wild;
if (card.value === 'skip') return POINTS.skip;
@ -188,6 +197,7 @@ export function applyDrawFromDiscard(state) {
const card = next.discardPile.pop();
next.players[next.currentPlayer].hand.push(card);
next.drawnThisTurn = true;
next.takes.push({ seat: next.currentPlayer, value: card.value, color: card.color, id: card.id, turn: next.turnCount });
return next;
}
@ -229,12 +239,44 @@ export function applyLaydown(state, groups) {
nextPlayer.hand = nextPlayer.hand.filter((c) => !usedIds.has(c.id));
nextPlayer.laidDown = resolved.map((g) => ({
kind: g.kind,
cards: g.cards.map(cloneCard),
cards: orderGroupCards(g.kind, g.cards).map(cloneCard),
}));
next.laidDownThisTurn = true;
return next;
}
/**
* Put a group's cards in table order. Runs MUST be in position order (hits and
* runAssignedValues read the ends), so naturals are placed at their values and
* wilds fill the gaps — leftover wilds extend the top (or the bottom when the
* top would pass 12). Sets: naturals then wilds. Colour groups: by value.
*/
export function orderGroupCards(kind, cards) {
const nat = cards.filter((c) => c.value !== 'wild');
const wild = cards.filter((c) => c.value === 'wild');
if (kind === 'run') {
const N = cards.length;
const vals = nat.map((c) => c.value).filter((v) => typeof v === 'number');
if (vals.length !== nat.length) return cards.slice();
if (!vals.length) return cards.slice();
const lo = Math.min(...vals), hi = Math.max(...vals);
const minS = Math.max(1, hi - N + 1);
const maxS = Math.min(lo, 13 - N);
if (minS > maxS) return cards.slice();
const S = maxS;
const byVal = new Map(nat.map((c) => [c.value, c]));
if (byVal.size !== nat.length) return cards.slice();
const out = [];
let w = 0;
for (let v = S; v < S + N; v++) out.push(byVal.get(v) ?? wild[w++]);
return out;
}
if (kind === 'color') {
return [...nat.slice().sort((a, b) => a.value - b.value), ...wild];
}
return [...nat, ...wild];
}
// ── Hitting ─────────────────────────────────────────────────────────────────
/**
@ -260,12 +302,12 @@ export function canHit(group, card, position) {
return card.color === col;
}
if (group.kind === 'run') {
if (card.value === 'wild') return true;
// Reconstruct the assigned values from the run order.
const vals = runAssignedValues(group);
if (!vals) return false;
if (position === 'low') return vals[0] > 1 && card.value === vals[0] - 1;
if (position === 'high') return vals[vals.length - 1] < 12 && card.value === vals[vals.length - 1] + 1;
const wild = card.value === 'wild';
if (position === 'low') return vals[0] > 1 && (wild || card.value === vals[0] - 1);
if (position === 'high') return vals[vals.length - 1] < 12 && (wild || card.value === vals[vals.length - 1] + 1);
return false;
}
return false;
@ -366,9 +408,14 @@ export function applyDiscard(state, handIdx, skipTargetSeat = null) {
const card = player.hand[handIdx];
if (card.value === 'skip') {
if (skipTargetSeat == null || skipTargetSeat === seat) return state;
const tgt = state.players[skipTargetSeat];
if (!tgt || tgt.skipped) return state;
const anyTarget = skipTargets(state, seat).length > 0;
if (skipTargetSeat == null) {
if (anyTarget) return state; // must pick someone while anyone can be skipped
} else {
if (skipTargetSeat === seat) return state;
const tgt = state.players[skipTargetSeat];
if (!tgt || tgt.skipped) return state;
}
}
const next = cloneState(state);
@ -389,6 +436,15 @@ export function applyDiscard(state, handIdx, skipTargetSeat = null) {
return next;
}
/** Seats a Skip discarded by `seat` may target (not yourself, not already skipped). */
export function skipTargets(state, seat) {
const out = [];
for (let s = 0; s < state.players.length; s++) {
if (s !== seat && !state.players[s].skipped) out.push(s);
}
return out;
}
function advanceTurn(state) {
state.turnCount += 1;
let nextSeat = (state.currentPlayer + 1) % state.players.length;

View File

@ -0,0 +1,366 @@
// Phase 10 table layout — Phaser-free so tools/verifyPhase10.js can test it.
//
// A retro rec-room card table (chrome-banded rim, quilted vinyl top) seen in
// mild perspective from the human's chair, built on the shared casino
// projection (makeProjection). Each player has:
//
// hand — the cards they hold, fanned at the table's edge (the human's is
// full-size along the bottom of the screen, face up)
// mat — a placemat on the table in front of them where their phase is
// built and laid down. Cards on mats stay upright so every number
// reads from your chair.
// plate — the name / phase-ladder / score nameplate
//
// Seats per player count:
// 2 human · across
// 3 human · far-left corner · far-right corner
// 4 human · left side · across · right side
//
// Logic seats fill clockwise from the human's left (seat 1 = left / far-left).
// Mats are rectangles in table space (u ∈ [-1, 1] left→right, v ∈ [0, 1]
// far→near) so they foreshorten like the table does; a mat holds one or two
// rows, and each row lays its cards at that row's depth scale.
import { makeProjection } from '../../ui/casino/CasinoGeometry.js';
export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 };
export const P = makeProjection(VIEW);
export const SQ = VIEW.squash;
export const CARD_W = 96;
export const CARD_H = 134;
export const W = 1920, H = 1080;
// Seat colours (human gold, then blue, red, green).
export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c];
export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c'];
// ── Table outline (table space: u ∈ [-1, 1], v ∈ [0, 1], far → near) ─────────
export const TABLE = { halfU: 1, corner: 0.17 };
export const FELT_K = 0.955; // vinyl inset from the outer chrome (fraction of the outline)
export const RAIL_FACE_PX = 34; // visible front face of the table edge at s = 1
export function outlineUV(k = 1, steps = 14) {
const cu = 0, cv = 0.5;
const hu = TABLE.halfU * k, hv = 0.5 * k, r = TABLE.corner * k;
const rv = r * 0.62;
const pts = [];
const corner = (ox, oy, a0) => {
for (let i = 0; i <= steps; i++) {
const a = a0 + (Math.PI / 2) * (i / steps);
pts.push({ u: ox + Math.cos(a) * r, v: oy + Math.sin(a) * rv });
}
};
corner(cu + hu - r, cv + hv - rv, 0);
corner(cu - hu + r, cv + hv - rv, Math.PI / 2);
corner(cu - hu + r, cv - hv + rv, Math.PI);
corner(cu + hu - r, cv - hv + rv, Math.PI * 1.5);
return pts;
}
export function outline(k = 1, steps = 14) {
return outlineUV(k, steps).map(p => P.project(p.u, p.v));
}
export function pointInPoly(pt, poly) {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i], b = poly[j];
if ((a.y > pt.y) !== (b.y > pt.y) && pt.x < ((b.x - a.x) * (pt.y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
}
return inside;
}
export function onFelt(pt, k = FELT_K) {
const { u, v } = P.unproject(pt.x, pt.y);
return pointInPoly({ x: u, y: v }, outlineUV(k).map(p => ({ x: p.u, y: p.v })));
}
// ── Seats ────────────────────────────────────────────────────────────────────
// hand: anchor (screen), rot (owner frame → screen), k (card scale), spread
// (px between cards at k), curve (px drop per step² toward the owner),
// tilt (rad per step), q (1 = held upright, SQ = lying flat)
// mat: table-space rect + rows + k (card scale on top of the depth scale)
const HUMAN = {
hand: { x: 960, y: 994, rot: 0, k: 1, spread: 82, curve: 1.3, tilt: 0.034, q: 1 },
mat: { u0: -0.56, u1: 0.56, v0: 0.70, v1: 0.865, rows: 1, k: 0.74 },
plate: { x: 190, y: 902 },
};
const opp = (x, y, rot, k, spread) => ({ x, y, rot, k, spread, curve: 0.5, tilt: 0.03, q: 1 });
const SEATS = {
2: [
HUMAN,
{
hand: opp(960, 74, Math.PI, 0.5, 30),
mat: { u0: -0.56, u1: 0.56, v0: 0.15, v1: 0.345, rows: 1, k: 0.7 },
plate: { x: 1420, y: 86 },
},
],
3: [
HUMAN,
{
hand: opp(600, 76, Math.PI - 0.1, 0.48, 29),
mat: { u0: -0.84, u1: -0.06, v0: 0.16, v1: 0.355, rows: 1, k: 0.66 },
plate: { x: 190, y: 150 },
},
{
hand: opp(1320, 76, Math.PI + 0.1, 0.48, 29),
mat: { u0: 0.06, u1: 0.84, v0: 0.16, v1: 0.355, rows: 1, k: 0.66 },
plate: { x: 1730, y: 150 },
},
],
4: [
HUMAN,
{
hand: opp(84, 520, Math.PI / 2, 0.46, 30),
mat: { u0: -0.93, u1: -0.4, v0: 0.37, v1: 0.67, rows: 2, k: 0.64 },
plate: { x: 190, y: 150 },
},
{
hand: opp(960, 74, Math.PI, 0.46, 28),
mat: { u0: -0.5, u1: 0.5, v0: 0.13, v1: 0.33, rows: 1, k: 0.66 },
plate: { x: 1400, y: 84 },
},
{
hand: opp(1836, 520, -Math.PI / 2, 0.46, 30),
mat: { u0: 0.4, u1: 0.93, v0: 0.37, v1: 0.67, rows: 2, k: 0.64 },
plate: { x: 1730, y: 150 },
},
],
};
export const PLATE = { w: 300, h: 96 };
export const PILE_K = 0.92;
export const DECK_UV = { u: -0.105, v: 0.5 };
export const DISCARD_UV = { u: 0.105, v: 0.5 };
// HUD furniture (screen rects, centre + size) — checked for overlaps by verify.
export const TOP_BUTTONS = [
{ x: 70, y: 38, w: 110, h: 40, label: 'Menu' },
{ x: 190, y: 38, w: 110, h: 40, label: 'Scores' },
{ x: 310, y: 38, w: 110, h: 40, label: 'Phases' },
];
export const DOCK = { x0: 1588, x1: 1904, y0: 846, y1: 1072 };
export const SORT_ROW = { y: 1020, xs: [90, 190, 290], w: 96, h: 40 };
export const KEYS_BOX = { x0: 16, x1: 452, y0: 1046, y1: 1078 }; // two lines of keyboard help
const rot2 = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
const cache = new Map();
export function layoutFor(playerCount) {
if (cache.has(playerCount)) return cache.get(playerCount);
const defs = SEATS[playerCount];
if (!defs) throw new Error(`Phase 10 layout supports 2..4 players, got ${playerCount}`);
const seats = defs.map((d, seat) => ({ seat, hand: d.hand, mat: d.mat, plate: d.plate }));
const deckP = P.project(DECK_UV.u, DECK_UV.v);
const discP = P.project(DISCARD_UV.u, DISCARD_UV.v);
const out = {
playerCount,
seats,
deck: { x: deckP.x, y: deckP.y, rot: 0, s: deckP.s * PILE_K, q: SQ },
discard: { x: discP.x, y: discP.y, rot: 0, s: discP.s * PILE_K, q: SQ },
};
cache.set(playerCount, out);
return out;
}
// Card container scale for a pose: the squash (q) always acts on the SCREEN
// vertical, so a card turned 90° squashes its local x instead.
export function poseScale(s, rot, q = SQ) {
const c2 = Math.cos(rot) ** 2, s2 = Math.sin(rot) ** 2;
return { sx: s * (c2 + s2 * q), sy: s * (s2 + c2 * q) };
}
export function cardCorners(pose) {
const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? SQ);
return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => {
const p = rot2(a * (CARD_W / 2) * sx, b * (CARD_H / 2) * sy, pose.rot);
return { x: pose.x + p.x, y: pose.y + p.y };
});
}
export function cardBounds(pose) {
const c = cardCorners(pose);
const xs = c.map(p => p.x), ys = c.map(p => p.y);
return { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) };
}
// Is a screen point on a (possibly rotated) card pose?
export function inPose(pt, pose, pad = 0) {
const { sx, sy } = poseScale(pose.s, pose.rot, pose.q ?? SQ);
const d = rot2(pt.x - pose.x, pt.y - pose.y, -pose.rot);
return Math.abs(d.x) <= (CARD_W / 2) * sx + pad && Math.abs(d.y) <= (CARD_H / 2) * sy + pad;
}
// ── Hands ────────────────────────────────────────────────────────────────────
/** Pose of card i of n in a seat's hand. `lift` raises it toward the table (px at k). */
export function handPose(L, seat, i, n, lift = 0) {
const h = L.seats[seat].hand;
const mid = (n - 1) / 2;
const d = i - mid;
// the human's fan tightens a little past 11 cards so it never leaves the gap
const spread = seat === 0 ? Math.min(h.spread, 860 / Math.max(1, n - 1)) : h.spread;
const ox = d * spread * h.k;
const oy = (d * d * h.curve - lift) * h.k;
const p = rot2(ox, oy, h.rot);
return { x: h.x + p.x, y: h.y + p.y, rot: h.rot + d * h.tilt, s: h.k, q: h.q };
}
/** Topmost card index of the human's hand under a point (or -1). */
export function handHit(L, n, pt, liftFor = () => 0) {
for (let i = n - 1; i >= 0; i--) {
if (inPose(pt, handPose(L, 0, i, n, liftFor(i)))) return i;
}
return -1;
}
/** Where the human's hand would insert a card dropped at screen x. */
export function handInsertIndex(L, n, x) {
if (n <= 0) return 0;
for (let i = 0; i < n; i++) {
if (x < handPose(L, 0, i, n).x) return i;
}
return n;
}
/** Bounding rect of the human's hand fan region (for drop-to-hand). */
export function handZone(L, n) {
const a = handPose(L, 0, 0, Math.max(1, n));
const b = handPose(L, 0, Math.max(0, n - 1), Math.max(1, n));
return { x0: Math.min(a.x, b.x) - CARD_W * 0.7, x1: Math.max(a.x, b.x) + CARD_W * 0.7, y0: L.seats[0].hand.y - CARD_H * 0.75, y1: H };
}
// Card-count badge for an opponent's hand (end of the fan).
export function handBadge(L, seat) {
const h = L.seats[seat].hand;
const p = rot2(-(5.5 * h.spread + CARD_W / 2 + 10) * h.k, 0, h.rot);
return { x: h.x + p.x, y: h.y + p.y };
}
// Where an opponent's ghost hand rests (just in front of their cards) and its rotation.
export function handHome(L, seat) {
const h = L.seats[seat].hand;
const p = rot2(0, -CARD_H * 0.95 * h.k, h.rot);
return { x: h.x + p.x, y: h.y + p.y, rot: h.rot };
}
// ── Mats ─────────────────────────────────────────────────────────────────────
export function matCorners(L, seat, pad = 0) {
const m = L.seats[seat].mat;
const du = pad / VIEW.halfW;
return [
P.project(m.u0 - du, m.v0 - du), P.project(m.u1 + du, m.v0 - du),
P.project(m.u1 + du, m.v1 + du), P.project(m.u0 - du, m.v1 + du),
];
}
export function matCentre(L, seat) {
const m = L.seats[seat].mat;
return P.project((m.u0 + m.u1) / 2, (m.v0 + m.v1) / 2);
}
const LABEL_GAP = 0.034; // v reserved above each row for its label
const AREA_PAD_PX = 14;
/**
* Card areas for `groupCount` groups on a seat's mat. Each area is one row of
* cards: { gi, x0, x1, y (row centre), s (card scale), labelY, cx }.
*/
export function groupAreas(L, seat, groupCount) {
const m = L.seats[seat].mat;
const gc = Math.max(1, groupCount);
const rows = [];
if (m.rows === 2 && gc === 2) {
const h = (m.v1 - m.v0) / 2;
rows.push({ v0: m.v0, v1: m.v0 + h, u0: m.u0, u1: m.u1 });
rows.push({ v0: m.v0 + h, v1: m.v1, u0: m.u0, u1: m.u1 });
} else if (gc === 2) {
const gap = 0.03;
const mid = (m.u0 + m.u1) / 2;
rows.push({ v0: m.v0, v1: m.v1, u0: m.u0, u1: mid - gap / 2 });
rows.push({ v0: m.v0, v1: m.v1, u0: mid + gap / 2, u1: m.u1 });
} else {
rows.push({ v0: m.v0, v1: m.v1, u0: m.u0, u1: m.u1 });
}
return rows.map((r, gi) => {
const vc = (r.v0 + LABEL_GAP + r.v1) / 2;
const c = P.project((r.u0 + r.u1) / 2, vc);
const a = P.project(r.u0, vc), b = P.project(r.u1, vc);
const s = c.s * m.k;
const top = c.y - (CARD_H / 2) * s * SQ;
return { gi, x0: a.x + AREA_PAD_PX * c.s, x1: b.x - AREA_PAD_PX * c.s, y: c.y, s, labelY: top - 13 * c.s, cx: c.x };
});
}
/** Horizontal step between overlapped cards in an area holding n cards. */
export function areaStep(area, n) {
const cw = CARD_W * area.s;
if (n <= 1) return 0;
return Math.min(cw * 0.66, (area.x1 - area.x0 - cw) / (n - 1));
}
/** Pose of card ci of n in group gi (of groupCount) on a seat's mat. */
export function groupCardPose(L, seat, gi, groupCount, ci, n) {
const area = groupAreas(L, seat, groupCount)[gi];
const step = areaStep(area, n);
const cw = CARD_W * area.s;
const total = cw + step * (n - 1);
const x = area.cx - total / 2 + cw / 2 + ci * step;
return { x, y: area.y, rot: 0, s: area.s, q: SQ };
}
/** Screen rect of a group (cards actually there, at least `minCount` wide) — hit target + glow. */
export function groupRect(L, seat, gi, groupCount, n, minCount = 1, pad = 10) {
const area = groupAreas(L, seat, groupCount)[gi];
const m = Math.max(n, minCount, 1);
const a = groupCardPose(L, seat, gi, groupCount, 0, m);
const b = groupCardPose(L, seat, gi, groupCount, m - 1, m);
const hw = (CARD_W / 2) * area.s, hh = (CARD_H / 2) * area.s * SQ;
return { x0: a.x - hw - pad, x1: b.x + hw + pad, y0: area.y - hh - pad, y1: area.y + hh + pad, cx: (a.x + b.x) / 2, y: area.y, s: area.s };
}
/** The whole area of a group (hit target while staging — the slots, not just the cards). */
export function areaRect(L, seat, gi, groupCount, pad = 6) {
const area = groupAreas(L, seat, groupCount)[gi];
const hh = (CARD_H / 2) * area.s * SQ;
return { x0: area.x0 - pad, x1: area.x1 + pad, y0: area.y - hh - pad, y1: area.y + hh + pad };
}
export const inRect = (pt, r) => pt.x >= r.x0 && pt.x <= r.x1 && pt.y >= r.y0 && pt.y <= r.y1;
// ── Piles ────────────────────────────────────────────────────────────────────
// Lift (screen px, toward the camera) that a stack of n cards shows as thickness.
export function stackLift(n, k = 1) {
return Math.min(12, Math.max(0, n - 1) * 0.16) * k;
}
export function deckTopPose(L, n) {
return { ...L.deck, y: L.deck.y - stackLift(n, L.deck.s) };
}
export function discardPose(L, i, n) {
return { ...L.discard, y: L.discard.y - stackLift(Math.min(n, 30), L.discard.s) * (i + 1) / Math.max(1, n) };
}
// ── Plates & seat focus ──────────────────────────────────────────────────────
export function plateRect(L, seat) {
const p = L.seats[seat].plate;
return { x0: p.x - PLATE.w / 2, x1: p.x + PLATE.w / 2, y0: p.y - PLATE.h / 2, y1: p.y + PLATE.h / 2 };
}
/** Where the turn spotlight sits for a seat (its mat), and how big. */
export function spotFor(L, seat) {
const c = matCentre(L, seat);
const m = L.seats[seat].mat;
const a = P.project(m.u0, (m.v0 + m.v1) / 2), b = P.project(m.u1, (m.v0 + m.v1) / 2);
const t = P.project(m.u0, m.v0), btm = P.project(m.u0, m.v1);
return { x: c.x, y: c.y, w: (b.x - a.x) * 1.25, h: (btm.y - t.y) * 1.7 + 60 };
}
export function rectsOverlap(a, b) {
return a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
}
export const centreRect = (r) => ({ x0: r.x - r.w / 2, x1: r.x + r.w / 2, y0: r.y - r.h / 2, y1: r.y + r.h / 2 });

View File

@ -175,3 +175,75 @@ function validateRun(cards) {
void wildCount;
return { ok: true };
}
// ── Live helpers for the UI ─────────────────────────────────────────────────
export const COLOR_NAMES = { red: 'Red', blue: 'Blue', yellow: 'Yellow', green: 'Green' };
/** "Set of 3", "Run of 4", "7 of one color". */
export function groupGoalLabel(kind, count) {
if (kind === 'set') return `Set of ${count}`;
if (kind === 'run') return `Run of ${count}`;
return `${count} of one color`;
}
/** Short name for a card: "Blue 7", "Wild", "Skip". */
export function cardName(card) {
if (!card) return '';
if (card.value === 'wild') return 'Wild';
if (card.value === 'skip') return 'Skip';
return `${COLOR_NAMES[card.color] ?? card.color} ${card.value}`;
}
/**
* Status of a partly built group while the player stages it.
* Returns { ok, full, valid, text } — `valid` means "nothing wrong so far",
* `ok` means complete and legal, `text` is a short coaching line.
*/
export function groupStatus(kind, count, cards) {
const n = cards.length;
const goal = groupGoalLabel(kind, count);
if (n === 0) return { ok: false, full: false, valid: true, text: goal };
if (cards.some((c) => c.value === 'skip')) {
return { ok: false, full: n >= count, valid: false, text: 'Skips can\'t be played' };
}
if (n > count) return { ok: false, full: true, valid: false, text: `Only ${count} cards` };
// partial runs are judged against the full window (3 and 5 can still become 3-4-5-6)
const r = kind === 'run' && n < count ? { ok: true } : validateGroup({ kind, cards });
if (!r.ok) return { ok: false, full: n >= count, valid: false, text: r.reason };
if (kind === 'run') {
const nat = cards.filter((c) => c.value !== 'wild').map((c) => c.value);
if (new Set(nat).size !== nat.length) return { ok: false, full: n >= count, valid: false, text: 'No repeats in a run' };
if (nat.length) {
const lo = Math.min(...nat), hi = Math.max(...nat);
if (hi - lo + 1 > count) return { ok: false, full: n >= count, valid: false, text: 'Too spread out' };
if (Math.max(1, hi - count + 1) > Math.min(lo, 13 - count)) {
return { ok: false, full: n >= count, valid: false, text: 'Won\'t fit in 1–12' };
}
}
}
if (n === count) return { ok: true, full: true, valid: true, text: `${goal} ✓` };
const left = count - n;
const nat = cards.find((c) => c.value !== 'wild');
let need;
if (!nat) need = `${left} more`;
else if (kind === 'set') need = `${left} more ${nat.value}${left > 1 ? 's' : ''} or Wild${left > 1 ? 's' : ''}`;
else if (kind === 'color') need = `${left} more ${COLOR_NAMES[nat.color] ?? nat.color}`;
else need = `${left} more in a row`;
return { ok: false, full: false, valid: true, text: `${n}/${count} · needs ${need}` };
}
/** Label for a laid-down group: "Run 3–9", "Set of 7s", "All Blue". */
export function laidGroupLabel(group, runValues = null) {
const n = group.cards.length;
if (group.kind === 'run') {
if (runValues && runValues.length) return `Run ${runValues[0]}–${runValues[runValues.length - 1]}`;
return `Run of ${n}`;
}
if (group.kind === 'set') {
const v = group.cards.find((c) => c.value !== 'wild')?.value;
return v != null ? `Set of ${v}s · ${n}` : `Set · ${n}`;
}
const col = group.cards.find((c) => c.color)?.color;
return col ? `All ${COLOR_NAMES[col]} · ${n}` : `One color · ${n}`;
}

View File

@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
// Skill control: pips always show the level; the +/- buttons appear only
// when this opponent is selected. Enabled for games with a 1–5 AI skill.
if (['nerts', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) {
if (['nerts', 'phase10', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) {
bio.style.webkitLineClamp = '1';
const skillRow = document.createElement('div');

433
tools/verifyPhase10.js Normal file
View File

@ -0,0 +1,433 @@
#!/usr/bin/env node
// verifyPhase10.js — headless checks for Phase 10: rules (laydowns, run order,
// hits incl. wild bounds, skips, scoring, match end + tie round), the live
// staging helpers, the AI (always legal, skill-scaled timing, advice), the
// table layout for 2/3/4 players (everything on screen and on the table, mats /
// hands / plates / HUD clear of each other, hit-test round trips), and an
// all-AI soak (every round ends, cards are conserved, higher skill wins more).
// Usage: node tools/verifyPhase10.js [--quick]
import {
createInitialState, buildDeck, applyDrawFromDeck, applyDrawFromDiscard, applyLaydown, applyHit,
applyDiscard, canHit, runAssignedValues, getHitTargets, startNextRound, cardPoints, handPoints,
orderGroupCards, skipTargets, discardTop, cloneState,
} from '../src/games/phase10/Phase10Logic.js';
import {
PHASES, getPhase, validateLaydown, groupStatus, laidGroupLabel, groupGoalLabel, cardName,
} from '../src/games/phase10/PhaseSpec.js';
import { chooseAction, findLaydown, adviseHand, aiTiming, HAND_SPEED, PACE } from '../src/games/phase10/Phase10AI.js';
import {
W, H, CARD_W, CARD_H, SQ, PLATE, TOP_BUTTONS, DOCK, SORT_ROW, KEYS_BOX, layoutFor, handPose, handHit, handInsertIndex,
handZone, handBadge, handHome, groupAreas, groupCardPose, groupRect, areaRect, inRect, inPose, cardBounds,
deckTopPose, discardPose, plateRect, matCorners, onFelt, rectsOverlap, centreRect, spotFor,
} from '../src/games/phase10/Phase10Table.js';
const QUICK = process.argv.includes('--quick');
let pass = 0, fail = 0;
function ok(label, cond, detail = '') {
if (cond) pass++;
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
}
const section = (n) => console.log(`\n${n}`);
let nextId = 1000;
const C = (value, color = 'red') => ({ value, color: value === 'wild' || value === 'skip' ? null : color, id: nextId++ });
const Wd = () => C('wild');
const Sk = () => C('skip');
// Put a hand + phase on seat `seat` and make it that seat's post-draw turn.
function rig(gs, seat, hand, phase = 1) {
gs.players[seat].hand = hand;
gs.players[seat].phase = phase;
gs.currentPlayer = seat;
gs.drawnThisTurn = true;
gs.laidDownThisTurn = false;
return gs;
}
function apply(gs, a) {
if (a.type === 'drawDeck') return applyDrawFromDeck(gs);
if (a.type === 'drawDiscard') return applyDrawFromDiscard(gs);
if (a.type === 'laydown') return applyLaydown(gs, a.groups);
if (a.type === 'hit') return applyHit(gs, a.handIdx, a.targetSeat, a.groupIdx, a.position);
return applyDiscard(gs, a.handIdx, a.skipTargetSeat ?? null);
}
const countCards = (gs) => gs.drawPile.length + gs.discardPile.length
+ gs.players.reduce((n, p) => n + p.hand.length + (p.laidDown ? p.laidDown.reduce((m, g) => m + g.cards.length, 0) : 0), 0);
// ── Rules ────────────────────────────────────────────────────────────────────
section('Rules');
{
const deck = buildDeck();
ok('108-card deck', deck.length === 108);
ok('8 wilds + 4 skips', deck.filter(c => c.value === 'wild').length === 8 && deck.filter(c => c.value === 'skip').length === 4);
ok('2 of each colour/value', [1, 6, 12].every(v => ['red', 'blue', 'yellow', 'green'].every(col => deck.filter(c => c.value === v && c.color === col).length === 2)));
ok('unique ids', new Set(deck.map(c => c.id)).size === 108);
for (const n of [2, 3, 4]) {
const gs = createInitialState({ playerCount: n, seed: 7 });
ok(`${n}p: 10 cards each`, gs.players.every(p => p.hand.length === 10));
ok(`${n}p: one card turned up`, gs.discardPile.length === 1);
ok(`${n}p: conserves 108`, countCards(gs) === 108);
ok(`${n}p: takes log empty`, Array.isArray(gs.takes) && gs.takes.length === 0);
}
ok('points: 5 / 10 / 15 / 25', cardPoints(C(9)) === 5 && cardPoints(C(10)) === 10 && cardPoints(Sk()) === 15 && cardPoints(Wd()) === 25);
ok('handPoints sums', handPoints([C(1), C(12), Wd()]) === 40);
}
{
const gs = createInitialState({ playerCount: 2, seed: 3 });
gs.discardPile.push(Sk());
ok('cannot take a Skip from the discard', applyDrawFromDiscard(gs) === gs);
gs.discardPile.push(C(7, 'blue'));
const next = applyDrawFromDiscard(gs);
ok('taking a discard logs it', next.takes.length === 1 && next.takes[0].seat === 0 && next.takes[0].value === 7 && next.takes[0].color === 'blue');
ok('takes survive a clone', cloneState(next).takes.length === 1);
ok('cannot draw twice', applyDrawFromDeck(next) === next);
}
{
// laydown validation per phase
const v = (ph, groups) => validateLaydown(ph, groups).ok;
ok('phase 1: two sets of 3', v(1, [{ kind: 'set', cards: [C(4), C(4, 'blue'), Wd()] }, { kind: 'set', cards: [C(9), C(9), C(9, 'green')] }]));
ok('phase 1: mismatched set rejected', !v(1, [{ kind: 'set', cards: [C(4), C(5), Wd()] }, { kind: 'set', cards: [C(9), C(9), C(9)] }]));
ok('phase 4: run of 7 any order', v(4, [{ kind: 'run', cards: [C(7), C(3), Wd(), C(5), C(6), C(4), C(8)] }]));
ok('phase 4: run past 12 rejected', !v(4, [{ kind: 'run', cards: [C(7), C(8), C(9), C(10), C(11), C(12), Wd()].slice(0, 6).concat([C(6)]).map((c, i) => (i === 6 ? C(12) : c)) }]));
ok('phase 8: 7 of one colour', v(8, [{ kind: 'color', cards: [C(1, 'blue'), C(3, 'blue'), C(3, 'blue'), C(9, 'blue'), C(11, 'blue'), Wd(), C(12, 'blue')] }]));
ok('phase 8: mixed colours rejected', !v(8, [{ kind: 'color', cards: [C(1, 'blue'), C(3, 'red'), C(3, 'blue'), C(9, 'blue'), C(11, 'blue'), Wd(), C(12, 'blue')] }]));
ok('all-wild laydown rejected', !v(9, [{ kind: 'set', cards: [Wd(), Wd(), Wd(), Wd(), Wd()] }, { kind: 'set', cards: [Wd(), Wd()] }]));
ok('skip in a laydown rejected', !v(1, [{ kind: 'set', cards: [C(4), C(4), Sk()] }, { kind: 'set', cards: [C(9), C(9), C(9)] }]));
}
{
// run order normalisation → hits work after an out-of-order laydown
const gs = createInitialState({ playerCount: 2, seed: 11 });
const run = [C(6), Wd(), C(3), C(4)]; // 3 4 5(W) 6
const set = [C(10), C(10, 'blue'), C(10, 'green')];
rig(gs, 0, [...run, ...set, C(2), C(7, 'blue'), C(12)], 2);
const next = applyLaydown(gs, [{ kind: 'set', cardIds: set.map(c => c.id) }, { kind: 'run', cardIds: run.map(c => c.id) }]);
ok('out-of-order run lays down', next !== gs);
const laidRun = next.players[0].laidDown.find(g => g.kind === 'run');
const vals = runAssignedValues(laidRun);
ok('run stored in position order', vals && vals.join(',') === '3,4,5,6', vals?.join(','));
ok('wild fills the 5', laidRun.cards[2].value === 'wild');
const gi = next.players[0].laidDown.indexOf(laidRun);
const tHigh = getHitTargets(next, next.players[0].hand.find(c => c.value === 7));
ok('7 hits the high end', tHigh.some(t => t.groupIdx === gi && t.position === 'high'));
const tLow = getHitTargets(next, next.players[0].hand.find(c => c.value === 2));
ok('2 hits the low end', tLow.some(t => t.groupIdx === gi && t.position === 'low'));
ok('12 hits nothing', getHitTargets(next, next.players[0].hand.find(c => c.value === 12)).length === 0);
ok('orderGroupCards: leftover wild goes high', orderGroupCards('run', [C(2), C(3), Wd()]).map(c => c.value).join() === '2,3,wild');
ok('orderGroupCards: wild goes low at the top', orderGroupCards('run', [C(11), C(12), Wd()]).map(c => c.value).join() === 'wild,11,12');
ok('orderGroupCards: set naturals first', orderGroupCards('set', [Wd(), C(5), C(5)]).map(c => c.value).join() === '5,5,wild');
}
{
// wild hits respect 1..12
const top = { kind: 'run', cards: [C(9), C(10), C(11), C(12)] };
ok('wild cannot extend past 12', !canHit(top, Wd(), 'high') && canHit(top, Wd(), 'low'));
const bottom = { kind: 'run', cards: [C(1), C(2), C(3)] };
ok('wild cannot extend below 1', !canHit(bottom, Wd(), 'low') && canHit(bottom, Wd(), 'high'));
ok('set takes matching or wild', canHit({ kind: 'set', cards: [C(5), C(5)] }, C(5, 'green')) && canHit({ kind: 'set', cards: [C(5), C(5)] }, Wd()) && !canHit({ kind: 'set', cards: [C(5), C(5)] }, C(6)));
ok('colour takes matching colour', canHit({ kind: 'color', cards: [C(1, 'blue')] }, C(9, 'blue')) && !canHit({ kind: 'color', cards: [C(1, 'blue')] }, C(9, 'red')));
ok('skips never hit', !canHit({ kind: 'set', cards: [C(5)] }, Sk()));
}
{
// skips
const gs = createInitialState({ playerCount: 2, seed: 5 });
const sk = Sk();
rig(gs, 0, [sk, C(3), C(4)]);
ok('skip needs a target while one exists', applyDiscard(gs, 0, null) === gs);
const next = applyDiscard(gs, 0, 1);
ok('2p skip: you go again', next.currentPlayer === 0 && !next.players[1].skipped);
const g3 = createInitialState({ playerCount: 3, seed: 5 });
rig(g3, 0, [Sk(), C(3), C(4)]);
const n3 = applyDiscard(g3, 0, 2);
ok('3p skip flags the target', n3.players[2].skipped && n3.currentPlayer === 1);
const n3b = rig(n3, 1, [Sk(), C(8)]);
ok('cannot skip an already-skipped seat', applyDiscard(n3b, 0, 2) === n3b);
ok('skipTargets excludes flagged + self', skipTargets(n3b, 1).join() === '0');
const n3c = applyDiscard(n3b, 0, 0);
ok('both others skipped → turn comes back around', n3c.currentPlayer === 1 && !n3c.players[0].skipped && !n3c.players[2].skipped);
// nobody skippable: a lone Skip may still be thrown
const g4 = createInitialState({ playerCount: 3, seed: 9 });
g4.players[1].skipped = true; g4.players[2].skipped = true;
rig(g4, 0, [Sk(), C(5)]);
const n4 = applyDiscard(g4, 0, null);
ok('skip with no valid target still discards', n4 !== g4 && discardTop(n4).value === 'skip');
}
{
// scoring, phase advance, match end, tie round
const gs = createInitialState({ playerCount: 2, seed: 21 });
const set1 = [C(4), C(4), C(4)], set2 = [C(8), C(8), C(8)];
rig(gs, 0, [...set1, ...set2, C(2)], 1);
let s = applyLaydown(gs, [{ kind: 'set', cardIds: set1.map(c => c.id) }, { kind: 'set', cardIds: set2.map(c => c.id) }]);
s.players[1].hand = [C(10), Wd(), C(3)];
s = applyDiscard(s, 0);
ok('going out ends the round', s.roundPhase === 'roundOver' && s.roundWinner === 0);
ok('loser scores their hand', s.players[1].score === 40 && s.players[0].score === 0);
ok('laid-down player advances', s.players[0].phase === 2 && s.players[1].phase === 1);
const r2 = startNextRound(s);
ok('next round deals fresh', r2.roundNum === 2 && r2.players.every(p => p.hand.length === 10 && !p.laidDown) && countCards(r2) === 108);
ok('next round: winner+1 starts', r2.currentPlayer === 1);
ok('takes reset each round', r2.takes.length === 0);
const end = createInitialState({ playerCount: 2, seed: 4 });
const a = [C(6), C(6), C(6), C(6), C(6)], b = [C(2), C(2), C(2)];
rig(end, 0, [...a, ...b, C(9)], 10);
end.players[1].phase = 10; end.players[1].clearedAt = null; end.players[1].hand = [C(1)];
let e = applyLaydown(end, [{ kind: 'set', cardIds: a.map(c => c.id) }, { kind: 'set', cardIds: b.map(c => c.id) }]);
e = applyDiscard(e, 0);
ok('clearing phase 10 ends the match', e.roundPhase === 'gameOver' && e.matchWinner === 0);
const tie = createInitialState({ playerCount: 2, seed: 4 });
const ta = [C(6), C(6), C(6), C(6), C(6)], tb = [C(2), C(2), C(2)];
rig(tie, 0, [...ta, ...tb, C(9)], 10);
tie.players[1].phase = 10; tie.players[1].clearedAt = 3; tie.players[1].score = 0;
tie.players[1].hand = [];
let t = applyLaydown(tie, [{ kind: 'set', cardIds: ta.map(c => c.id) }, { kind: 'set', cardIds: tb.map(c => c.id) }]);
t = applyDiscard(t, 0);
ok('tied finishers play another round', t.roundPhase === 'roundOver' && t.matchTied && t.matchWinner === null);
}
// ── Staging helpers ──────────────────────────────────────────────────────────
section('Staging helpers');
{
ok('empty group shows its goal', groupStatus('set', 3, []).text === 'Set of 3');
ok('partial set coaches', /needs 1 more 7/.test(groupStatus('set', 3, [C(7), C(7)]).text));
ok('wrong set value flagged', !groupStatus('set', 3, [C(7), C(8)]).valid);
ok('partial run with a gap is fine', groupStatus('run', 4, [C(3), C(5)]).valid);
ok('spread-out run flagged', !groupStatus('run', 4, [C(3), C(9)]).valid);
ok('repeat in a run flagged', !groupStatus('run', 4, [C(3), C(3)]).valid);
ok('run that cannot fit 1..12 flagged', !groupStatus('run', 9, [C(12), C(5)]).valid || !groupStatus('run', 9, [C(12), C(5)]).ok);
ok('complete run ok', groupStatus('run', 4, [C(5), Wd(), C(3), C(6)]).ok);
ok('skip never valid', !groupStatus('set', 3, [Sk()]).valid);
ok('colour coaching names the colour', /Blue/.test(groupStatus('color', 7, [C(2, 'blue')]).text));
ok('laid run label', laidGroupLabel({ kind: 'run', cards: [C(3), C(4)] }, [3, 4]) === 'Run 3–4');
ok('laid set label', laidGroupLabel({ kind: 'set', cards: [C(7), Wd()] }) === 'Set of 7s · 2');
ok('goal labels', groupGoalLabel('color', 7) === '7 of one color' && groupGoalLabel('run', 9) === 'Run of 9');
ok('card names', cardName(C(7, 'blue')) === 'Blue 7' && cardName(Wd()) === 'Wild' && cardName(Sk()) === 'Skip');
}
// ── AI ───────────────────────────────────────────────────────────────────────
section('AI');
{
ok('hand speeds as set for Nerts', HAND_SPEED[1] === 0.25 && HAND_SPEED[2] === 0.3 && HAND_SPEED[3] === 0.5 && HAND_SPEED[4] === 0.8 && HAND_SPEED[5] === 1);
let mono = true;
for (let k = 1; k < 5; k++) {
const a = aiTiming(k), b = aiTiming(k + 1);
if (!(a.reach > b.reach && a.carry > b.carry && a.think >= b.think)) mono = false;
}
ok('lower skill = slower hands', mono);
ok('pace scales timing', aiTiming(3, PACE.fast).carry < aiTiming(3, PACE.normal).carry && aiTiming(3, PACE.relaxed).carry > aiTiming(3).carry);
ok('skill 3 carry is half of skill 5', Math.abs(aiTiming(3).carry - 2 * aiTiming(5).carry) <= 1);
ok('even skill 1 turns stay reasonable', aiTiming(1).reach + aiTiming(1).carry < 2000);
// findLaydown always returns a legal laydown
let bad = 0, found = 0;
const trials = QUICK ? 400 : 2000;
for (let i = 0; i < trials; i++) {
const gs = createInitialState({ playerCount: 2, seed: 1000 + i });
const hand = [...gs.players[0].hand, gs.drawPile.pop(), gs.drawPile.pop(), gs.drawPile.pop()];
const phase = 1 + (i % 10);
const lay = findLaydown(hand, phase);
if (lay) {
found++;
if (!validateLaydown(phase, lay).ok) bad++;
const ids = lay.flatMap(g => g.cards.map(c => c.id));
if (new Set(ids).size !== ids.length) bad++;
}
}
ok('findLaydown results are legal', bad === 0, `${bad} bad of ${found}`);
ok('findLaydown finds some', found > trials * 0.05, `${found}/${trials}`);
// adviseHand
const gs = createInitialState({ playerCount: 2, seed: 77 });
const s1 = [C(4), C(4), C(4)], s2 = [C(9), C(9), Wd()];
rig(gs, 0, [...s1, ...s2, C(1), C(12, 'blue'), C(7, 'green'), C(2)], 1);
const adv = adviseHand(gs, 0);
ok('advice spots a laydown', !!adv.laydown);
ok('advice keeps the phase cards', [...s1, ...s2].every(c => adv.keepers.has(c.id)));
ok('advice never tosses a phase card or wild', adv.discardId != null && ![...s1, ...s2].some(c => c.id === adv.discardId));
}
// ── Layout ───────────────────────────────────────────────────────────────────
section('Layout');
const onScreen = (b, m = 0) => b.x0 >= -m && b.x1 <= W + m && b.y0 >= -m && b.y1 <= H + m;
for (const n of [2, 3, 4]) {
const L = layoutFor(n);
const furniture = [];
for (let s = 0; s < n; s++) furniture.push({ name: `plate ${s}`, r: plateRect(L, s) });
TOP_BUTTONS.forEach(b => furniture.push({ name: `button ${b.label}`, r: centreRect(b) }));
furniture.push({ name: 'dock', r: DOCK });
SORT_ROW.xs.forEach((x, i) => furniture.push({ name: `sort ${i}`, r: centreRect({ x, y: SORT_ROW.y, w: SORT_ROW.w, h: SORT_ROW.h }) }));
furniture.push({ name: 'keys line', r: KEYS_BOX });
// furniture vs furniture
for (let i = 0; i < furniture.length; i++) {
for (let j = i + 1; j < furniture.length; j++) {
ok(`${n}p: ${furniture[i].name} clear of ${furniture[j].name}`, !rectsOverlap(furniture[i].r, furniture[j].r));
}
}
const matBox = (s) => {
const c = matCorners(L, s, 10);
return { x0: Math.min(...c.map(p => p.x)), x1: Math.max(...c.map(p => p.x)), y0: Math.min(...c.map(p => p.y)), y1: Math.max(...c.map(p => p.y)) };
};
const handBox = (s, cards = 11) => {
let b = null;
for (let i = 0; i < cards; i++) {
const cb = cardBounds(handPose(L, s, i, cards, s === 0 ? 46 : 0));
b = b ? { x0: Math.min(b.x0, cb.x0), x1: Math.max(b.x1, cb.x1), y0: Math.min(b.y0, cb.y0), y1: Math.max(b.y1, cb.y1) } : cb;
}
return b;
};
const pileBox = (p) => cardBounds({ ...p, y: p.y - 14 });
const deckB = pileBox(L.deck), discB = pileBox(L.discard);
ok(`${n}p: deck and discard apart`, !rectsOverlap(deckB, discB));
for (let s = 0; s < n; s++) {
const mb = matBox(s);
ok(`${n}p seat ${s}: mat on the table`, matCorners(L, s, 10).every(p => onFelt(p)));
ok(`${n}p seat ${s}: mat clear of piles`, !rectsOverlap(mb, deckB) && !rectsOverlap(mb, discB));
for (let t = s + 1; t < n; t++) ok(`${n}p mats ${s}/${t} apart`, !rectsOverlap(mb, matBox(t)));
for (const f of furniture) ok(`${n}p seat ${s}: mat clear of ${f.name}`, !rectsOverlap(mb, f.r));
const hb = handBox(s);
ok(`${n}p seat ${s}: hand on screen`, onScreen(hb, s === 0 ? 40 : 6), JSON.stringify(hb));
for (let t = 0; t < n; t++) ok(`${n}p hand ${s} clear of mat ${t}`, !rectsOverlap(hb, matBox(t)), `${JSON.stringify(hb)} vs ${JSON.stringify(matBox(t))}`);
for (const f of furniture) ok(`${n}p hand ${s} clear of ${f.name}`, !rectsOverlap(hb, f.r), `${JSON.stringify(hb)} vs ${JSON.stringify(f.r)}`);
ok(`${n}p hand ${s} clear of piles`, !rectsOverlap(hb, deckB) && !rectsOverlap(hb, discB));
if (s > 0) {
const b = handBadge(L, s);
const br = { x0: b.x - 16, x1: b.x + 16, y0: b.y - 16, y1: b.y + 16 };
ok(`${n}p seat ${s}: badge on screen`, onScreen(br));
for (const f of furniture) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r));
const hh = handHome(L, s);
ok(`${n}p seat ${s}: ghost hand home on screen`, hh.x > 0 && hh.x < W && hh.y > 0 && hh.y < H);
}
// groups: long rows stay inside their area, cards on the felt, labels on screen
for (const gc of [1, 2]) {
const areas = groupAreas(L, s, gc);
for (let gi = 0; gi < gc; gi++) {
for (const len of [2, 5, 9, 12, 16]) {
const first = cardBounds(groupCardPose(L, s, gi, gc, 0, len));
const last = cardBounds(groupCardPose(L, s, gi, gc, len - 1, len));
const a = areas[gi];
ok(`${n}p seat ${s} g${gi}/${gc} len ${len}: inside area`, first.x0 >= a.x0 - 1 && last.x1 <= a.x1 + 1, `${first.x0.toFixed(0)}..${last.x1.toFixed(0)} vs ${a.x0.toFixed(0)}..${a.x1.toFixed(0)}`);
ok(`${n}p seat ${s} g${gi}/${gc} len ${len}: on felt`, onFelt({ x: first.x0, y: first.y0 }) && onFelt({ x: last.x1, y: last.y1 }));
}
const step12 = groupCardPose(L, s, gi, gc, 1, 12).x - groupCardPose(L, s, gi, gc, 0, 12).x;
ok(`${n}p seat ${s} g${gi}/${gc}: 12-card row stays readable`, step12 >= 18, step12.toFixed(1));
ok(`${n}p seat ${s} g${gi}/${gc}: label on the mat`, a0(areas[gi].labelY));
}
if (gc === 2) {
const r0 = areaRect(L, s, 0, 2, 0), r1 = areaRect(L, s, 1, 2, 0);
ok(`${n}p seat ${s}: two group areas apart`, !rectsOverlap(r0, r1));
}
}
const sp = spotFor(L, s);
ok(`${n}p seat ${s}: spotlight sized`, sp.w > 100 && sp.h > 100);
}
// human hand hit-tests round trip; insertion index is monotone
for (const cards of [1, 5, 10, 11]) {
let rt = true;
for (let i = 0; i < cards; i++) {
const p = handPose(L, 0, i, cards);
// aim at the visible left strip (later cards overlap the right side)
const pt = { x: p.x - CARD_W * 0.3, y: p.y - CARD_H * 0.3 };
if (handHit(L, cards, pt) !== i) rt = false;
}
ok(`${n}p: hand hit-test round trip (${cards})`, rt);
let monotone = true, prev = -1;
for (let x = 300; x <= 1620; x += 15) {
const k = handInsertIndex(L, cards, x);
if (k < prev) monotone = false;
prev = k;
}
ok(`${n}p: insert index monotone (${cards})`, monotone && handInsertIndex(L, cards, 0) === 0 && handInsertIndex(L, cards, W) === cards);
const z = handZone(L, cards);
ok(`${n}p: hand zone covers the fan (${cards})`, inRect(handPose(L, 0, 0, cards), z) && inRect(handPose(L, 0, cards - 1, cards), z));
}
ok(`${n}p: deck pose hit`, inPose(L.deck, deckTopPose(L, 80)) && inPose(L.discard, discardPose(L, 3, 4)));
// group rects cover their cards (hit targets)
for (let s = 0; s < n; s++) {
const r = groupRect(L, s, 1, 2, 7, 1, 10);
const p0 = groupCardPose(L, s, 1, 2, 0, 7), p6 = groupCardPose(L, s, 1, 2, 6, 7);
ok(`${n}p seat ${s}: group rect covers its cards`, inRect(p0, r) && inRect(p6, r));
}
}
function a0(y) { return y > 0 && y < H; }
void SQ; void PLATE;
// ── Soak ─────────────────────────────────────────────────────────────────────
section('Soak');
function playMatch(n, skills, seed, { maxRounds = 80 } = {}) {
let gs = createInitialState({ playerCount: n, seed });
let rounds = 0, turns = 0, noop = 0, conserve = true, stuck = false, loops = 0;
let rng = seed * 9301 + 49297;
const rand = () => { rng = (rng * 9301 + 49297) % 233280; return rng / 233280; };
while (gs.roundPhase !== 'gameOver' && rounds < maxRounds) {
let steps = 0;
while (gs.roundPhase === 'play' && steps < 3000) {
const a = chooseAction(gs, { skill: skills[gs.currentPlayer], rng: rand });
const next = apply(gs, a);
if (next === gs) {
noop++;
// the scene's safety net: discard the first card
const fb = applyDiscard(gs, 0, skipTargets(gs, gs.currentPlayer)[0] ?? null);
if (fb === gs) { stuck = true; break; }
gs = fb;
} else gs = next;
if (a.type === 'discard') turns++;
if (gs.takes?.length && gs.takes.filter(t => t.id === gs.takes[gs.takes.length - 1].id).length > 3) loops++;
if (countCards(gs) !== 108) conserve = false;
steps++;
}
if (stuck || gs.roundPhase === 'play') { stuck = true; break; }
rounds++;
if (gs.roundPhase === 'roundOver') gs = startNextRound(gs);
}
return { gs, rounds, turns, noop, conserve, stuck, loops, over: gs.roundPhase === 'gameOver' };
}
{
const N = QUICK ? 12 : 60;
for (const n of [2, 3, 4]) {
let ended = 0, noops = 0, conserved = true, stuck = 0, rounds = 0, scoreOk = true, loops = 0;
for (let i = 0; i < N; i++) {
const skills = Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5));
const r = playMatch(n, skills, 500 + i * 13 + n);
if (r.over) ended++;
noops += r.noop;
if (!r.conserve) conserved = false;
if (r.stuck) stuck++;
loops += r.loops;
rounds += r.rounds;
if (r.over) {
const w = r.gs.players[r.gs.matchWinner];
const fin = r.gs.players.filter(p => p.clearedAt != null);
if (!w || w.clearedAt == null || fin.some(p => p.score < w.score)) scoreOk = false;
}
}
ok(`${n}p soak: every match ends`, ended === N, `${ended}/${N}`);
ok(`${n}p soak: AI never plays an illegal action`, noops === 0, `${noops} no-ops`);
ok(`${n}p soak: 108 cards conserved`, conserved);
ok(`${n}p soak: no stuck rounds`, stuck === 0);
ok(`${n}p soak: no card passed around in a loop`, loops === 0, `${loops}`);
ok(`${n}p soak: winner is the lowest finisher`, scoreOk);
console.log(` ${n}p: ${N} matches, avg ${(rounds / N).toFixed(1)} rounds`);
}
// skill matters
const duel = (a, b, M) => {
let wa = 0;
for (let i = 0; i < M; i++) {
const seatA = i % 2;
const skills = seatA === 0 ? [a, b] : [b, a];
const r = playMatch(2, skills, 9000 + i * 7);
if (r.over && r.gs.matchWinner === seatA) wa++;
}
return wa / M;
};
const M = QUICK ? 40 : 160;
const r51 = duel(5, 1, M), r31 = duel(3, 1, M), r53 = duel(5, 3, M);
console.log(` win rates: skill 5 vs 1 ${(r51 * 100).toFixed(0)}%, 3 vs 1 ${(r31 * 100).toFixed(0)}%, 5 vs 3 ${(r53 * 100).toFixed(0)}%`);
// measured over 300 matches: 5v1 ≈ 84%, 3v1 ≈ 81%, 5v3 ≈ 60% (quick mode is noisier)
ok('skill 5 clearly beats skill 1', r51 >= (QUICK ? 0.65 : 0.72), `${(r51 * 100).toFixed(0)}%`);
ok('skill 3 beats skill 1', r31 >= (QUICK ? 0.6 : 0.68), `${(r31 * 100).toFixed(0)}%`);
ok('skill 5 beats skill 3', r53 >= (QUICK ? 0.42 : 0.52), `${(r53 * 100).toFixed(0)}%`);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);