diff --git a/src/games/nerts/NertsAI.js b/src/games/nerts/NertsAI.js index 57d5282..609a267 100644 --- a/src/games/nerts/NertsAI.js +++ b/src/games/nerts/NertsAI.js @@ -1,44 +1,144 @@ -// Nerts AI — skill-aware, real-time decision making. +// Nerts AI — skill-aware, real-time, and paced like a person at the table. // -// The scene runs an independent timer per AI seat. Each tick it calls -// chooseAction(state, seat, skill) for ONE atomic action, applies it, then -// reschedules after nextThinkDelay(skill) ms. Skill (1..5) controls three axes: -// • reaction speed — how fast the next tick fires (thinkDelay range) -// • decision quality — how strictly moves are ordered by strategic value -// • mistakes — missChance to dawdle (flip) or take a sloppy move -// Level 1 is slow and sloppy; level 5 is fast and near-optimal. +// A real player doesn't act on a metronome. They need a moment to READ a card +// they've just flipped or uncovered, longer to NOTICE that someone else's play +// in the middle opened something up for them, and they POUNCE quickly when the +// one card their Nerts pile has been waiting for finally lands. They also glance +// away now and then, and they don't shuffle cards between work piles for nothing. +// +// That is modelled with a small per-seat "mind": +// • every legal play has a moment it became available (the seat's own last +// change, or the last change to the foundation it targets); +// • it is only *noticed* after a perception delay that depends on what kind +// of change it was (read / notice / pounce / chain / opening scan) and on +// skill, using a stable per-play random draw so nothing flickers; +// • after each of its own actions a seat needs a read-length look over its +// layout before it sees everything again or flips the stock. +// +// The scene calls planMove() on a short poll; it returns either an action to +// perform (the scene then adds the hand's reach time) or how long to wait. +// Skill 1..5 sets the speed bands, decision quality, mistakes and distraction. import { canFlipStock, + canPlayOnFoundation, getValidPlays, + rv, } from './NertsLogic.js'; const SKILL_PROFILES = { - 1: { delay: [1500, 2300], miss: 0.55, quality: 0.15 }, - 2: { delay: [1050, 1700], miss: 0.38, quality: 0.35 }, - 3: { delay: [700, 1150], miss: 0.22, quality: 0.55 }, - 4: { delay: [450, 750], miss: 0.10, quality: 0.78 }, - 5: { delay: [280, 460], miss: 0.03, quality: 0.95 }, + 1: { miss: 0.45, quality: 0.15, distract: 0.10 }, + 2: { miss: 0.30, quality: 0.35, distract: 0.08 }, + 3: { miss: 0.18, quality: 0.55, distract: 0.06 }, + 4: { miss: 0.09, quality: 0.78, distract: 0.04 }, + 5: { miss: 0.03, quality: 0.95, distract: 0.025 }, }; +// Perception delays [lo, hi] ms by skill (before the pace multiplier). +// read — a card the seat itself just flipped / uncovered +// notice — the middle changed because of someone else +// pounce — …and it's the exact card the seat's Nerts top was waiting for +// chain — building on a foundation the seat just played to itself +// scan — the opening look at a freshly dealt layout +export const PERCEPTION = { + read: { 1: [1400, 2400], 2: [1150, 1950], 3: [900, 1550], 4: [700, 1200], 5: [520, 900] }, + notice: { 1: [2000, 3400], 2: [1700, 2900], 3: [1400, 2400], 4: [1100, 1900], 5: [850, 1450] }, + pounce: { 1: [900, 1500], 2: [750, 1250], 3: [600, 1000], 4: [450, 780], 5: [340, 580] }, + chain: { 1: [700, 1200], 2: [600, 1000], 3: [480, 820], 4: [380, 650], 5: [280, 480] }, + scan: { 1: [2400, 3600], 2: [2100, 3200], 3: [1800, 2800], 4: [1500, 2300], 5: [1200, 1900] }, +}; + +// AI pace setting → multiplier on every delay (Relaxed / Normal / Frantic). +export const PACE = { relaxed: 1.35, normal: 1, frantic: 0.72 }; + +const clampSkill = (skill) => Math.max(1, Math.min(5, skill | 0)) || 3; + function profileFor(skill) { - return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; + return SKILL_PROFILES[clampSkill(skill)]; } -/** Milliseconds until this AI's next think tick, randomized within its band. */ -export function nextThinkDelay(skill) { - const [lo, hi] = profileFor(skill).delay; - return lo + Math.random() * (hi - lo); +// Stable 0..1 from a string (FNV-1a) — the same play keeps the same draw. +function hashU(str) { + let h = 2166136261; + for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 16777619); + return ((h >>> 0) % 100000) / 100000; +} + +export function perceptionDelay(cls, skill, u, pace = 1) { + const [lo, hi] = PERCEPTION[cls][clampSkill(skill)]; + return (lo + u * (hi - lo)) * pace; +} + +// Ghost-hand speed by skill, as a fraction of each skill's original hand +// timing (HAND_BASE): a novice's hand moves at a quarter speed, an expert's +// at full speed. Applies to the reach, the carry and the return home. +export const HAND_SPEED = { 1: 0.25, 2: 0.30, 3: 0.5, 4: 0.8, 5: 1 }; +const HAND_BASE = { 1: 420, 2: 360, 3: 300, 4: 240, 5: 190 }; // full-speed reach (ms) +const CARRY_BASE = 300; // full-speed carry (ms) + +export function handSpeed(skill) { + return HAND_SPEED[clampSkill(skill)]; +} + +/** + * How long the AI's (ghost) hand takes to reach the card it picked — the motor + * part of a move, added on top of perception. The move only lands when the hand + * arrives, which is what makes races on a foundation possible. + */ +export function reachDelay(skill, pace = 1, kind = 'move') { + const s = clampSkill(skill); + return (HAND_BASE[s] / HAND_SPEED[s]) * pace * (kind === 'flip' ? 0.55 : 1); +} + +/** How long the hand takes to carry a card to where it's going (the card rides with it). */ +export function carryDelay(skill, pace = 1) { + return (CARRY_BASE / HAND_SPEED[clampSkill(skill)]) * pace; +} + +// ── Which plays are worth making ───────────────────────────────────────────── +const isRed = (c) => c.suit === 'h' || c.suit === 'd'; +const links = (a, b) => rv(b) === rv(a) - 1 && isRed(a) !== isRed(b); + +/** + * Nobody shuffles cards between work piles for nothing. A work→work move is + * worth it only if it empties the pile, lifts a run off a card it isn't in + * sequence with (so something new is uncovered), or splits a run to free a + * card that goes straight to a foundation. (When the whole table is stuck, + * planMove lets players rearrange more freely — see STUCK_MS.) + */ +export function isUsefulPlay(state, seat, play) { + if (play.kind !== 'work' || play.source.type !== 'work') return true; + const pile = state.players[seat].work[play.source.idx]; + const k = pile.length - (play.source.count ?? 1); + if (k === 0) return state.players[seat].work[play.dest].length > 0; // whole pile → empty pile is pointless + if (!links(pile[k - 1], pile[k])) return true; + const freed = pile[k - 1]; + return state.foundations.some((_, f) => canPlayOnFoundation(state, freed, f)); +} + +export function usefulPlays(state, seat) { + return getValidPlays(state, seat).filter(p => isUsefulPlay(state, seat, p)); +} + +// Once nobody at the table has made progress for this long, players start +// rearranging their work piles looking for something (any move except +// dumping a whole pile onto an empty one). Stalls end it either way. +export const STUCK_MS = 20000; + +function rummagePlays(state, seat) { + return getValidPlays(state, seat).filter(p => { + if (p.kind !== 'work' || p.source.type !== 'work') return true; + const pile = state.players[seat].work[p.source.idx]; + return !(pile.length === (p.source.count ?? 1) && state.players[seat].work[p.dest].length === 0); + }); } /** Strategic value of a play, before quality/noise weighting is applied. */ function strategicScore(state, seat, play) { let s = play.kind === 'foundation' ? 100 : 40; - // Offloading the Nerts pile is the whole game — prize it heavily. if (play.source.type === 'nerts') s += 60; else if (play.source.type === 'waste') s += 8; - // Emptying a work pile (frees a column for any card) is worthwhile. if (play.source.type === 'work') { const pile = state.players[seat].work[play.source.idx]; @@ -51,37 +151,142 @@ function toAction(play) { return { kind: play.kind, source: play.source, dest: play.dest }; } -/** - * Return one action for the AI at `seat`, or null if it can do nothing. - * Action shapes (mirror the NertsLogic mutators): - * { kind:'foundation', source, dest } - * { kind:'work', source, dest } - * { kind:'flip' } - */ -export function chooseAction(state, seat, skill) { - if (state.phase !== 'playing') return null; - const prof = profileFor(skill); - const plays = getValidPlays(state, seat); - const canFlip = canFlipStock(state, seat); +/** Legal, sensible plays for a seat, best first (used for the human's hint glow). */ +export function rankedPlays(state, seat) { + return usefulPlays(state, seat) + .map(p => ({ p, s: strategicScore(state, seat, p) })) + .sort((a, b) => b.s - a.s) + .map(x => x.p); +} - if (plays.length === 0) { - return canFlip ? { kind: 'flip' } : null; - } - - // Mistake: dawdle (flip instead of playing) or take a random sloppy move. +function pick(state, seat, plays, prof, canFlip) { + // Mistake: dawdle (flip instead of playing) or take a sloppy move. if (Math.random() < prof.miss) { if (canFlip && Math.random() < 0.5) return { kind: 'flip' }; return toAction(plays[Math.floor(Math.random() * plays.length)]); } - // Weighted pick: low quality flattens strategy and adds large noise. let best = null; let bestScore = -Infinity; for (const p of plays) { - const strategic = strategicScore(state, seat, p); const noise = Math.random() * 120 * (1 - prof.quality); - const score = strategic * (0.4 + 0.6 * prof.quality) + noise; + const score = strategicScore(state, seat, p) * (0.4 + 0.6 * prof.quality) + noise; if (score > bestScore) { bestScore = score; best = p; } } return toAction(best); } + +/** + * Instant decision with no perception model (kept for tools and as a fallback). + * Action shapes (mirror the NertsLogic mutators): + * { kind:'foundation', source, dest } | { kind:'work', source, dest } | { kind:'flip' } + */ +export function chooseAction(state, seat, skill) { + if (state.phase !== 'playing') return null; + const plays = usefulPlays(state, seat); + const canFlip = canFlipStock(state, seat); + if (plays.length === 0) return canFlip ? { kind: 'flip' } : null; + return pick(state, seat, plays, profileFor(skill), canFlip); +} + +// ── The paced planner ──────────────────────────────────────────────────────── + +/** A fresh mind for a seat at the start of a round (`now` = play clock ms). */ +export function createMind(skill, now = 0) { + return { skill: clampSkill(skill), start: now, ownAt: now, ownKind: 'deal', pauseUntil: 0, avail: new Map() }; +} + +/** Tell the mind its own layout changed (after it flips, plays, or fumbles). */ +export function noteOwnChange(mind, now, kind = 'move') { + mind.ownAt = now; + mind.ownKind = kind; +} + +const playKey = (p) => `${p.kind}:${p.source.type}:${p.source.idx ?? ''}:${p.source.count ?? 1}:${p.dest}:${p.card.id}`; +const flipDraw = (seat, mind) => hashU(`${seat}|flip|${Math.round(mind.ownAt)}`); + +/** + * When will this seat notice `play`, judged at the moment it first appears? + * Returns { t, cls } (play-clock ms; pure — the same inputs give the same answer). + */ +export function noticeInfo(seat, mind, play, ctx) { + const pace = ctx.pace ?? 1; + const f = play.kind === 'foundation' ? ctx.foundationAt?.[play.dest] : null; + let at = mind.ownAt; + let cls = mind.ownKind === 'deal' ? 'scan' : 'read'; + let u = null; + if (f && f.seat === seat && f.at >= mind.ownAt) { + at = f.at; + cls = 'chain'; // building on our own play + } else if (f && f.at > mind.ownAt) { + at = f.at; + cls = play.source.type === 'nerts' ? 'pounce' : 'notice'; + } else if (play.source.type === 'waste' && mind.ownKind === 'flip') { + u = flipDraw(seat, mind); // read in the same glance as the flip + } + if (u === null) u = hashU(`${seat}|${playKey(play)}|${Math.round(at)}`); + return { t: at + perceptionDelay(cls, mind.skill, u, pace), cls }; +} + +export function noticeAt(seat, mind, play, ctx) { + return noticeInfo(seat, mind, play, ctx).t; +} + +// Reactions quick enough to happen mid-look (before the seat's scan is done). +const FAST = new Set(['pounce', 'chain']); + +/** + * Decide what this seat does now. + * ctx = { now, pace, foundationAt: [{ at, seat }], stalledMs } (play-clock ms; + * stalledMs = time since anyone at the table made progress) + * Returns { action } to perform now, or { wait: ms } to look again later. + * + * Each opportunity gets ONE clock, started when it first appears and kept + * while it stays legal; and every own action is followed by a read-length look + * over the seat's layout, after which it sees everything (so it never flips + * past a card it could have played just because it hadn't "noticed" it yet). + */ +export function planMove(state, seat, mind, ctx) { + if (state.phase !== 'playing') return { wait: 500 }; + const now = ctx.now; + const pace = ctx.pace ?? 1; + const prof = profileFor(mind.skill); + if (now < mind.pauseUntil) return { wait: mind.pauseUntil - now }; + + const plays = (ctx.stalledMs ?? 0) >= STUCK_MS ? rummagePlays(state, seat) : usefulPlays(state, seat); + const canFlip = canFlipStock(state, seat); + // After every own action the seat takes a read-length look over its whole + // layout. Once that look is done it sees every play (and may flip again); + // before then, only quick reactions get through — pouncing on the card its + // Nerts top was waiting for, or building on its own foundation play. + const scanCls = mind.ownKind === 'deal' ? 'scan' : 'read'; + const scanAt = mind.ownAt + perceptionDelay(scanCls, mind.skill, flipDraw(seat, mind), pace); + const scanned = now >= scanAt; + + const live = new Set(); + const noticed = []; + let nextNotice = Infinity; + for (const p of plays) { + const key = playKey(p); + live.add(key); + let info = mind.avail.get(key); + if (info === undefined) { info = noticeInfo(seat, mind, p, ctx); mind.avail.set(key, info); } + // mid-look, only the quick reactions fire; anything else waits for the scan + // (so a seat never grabs a stale low-value move just because it's the only + // one "in mind" a moment after its last action) + if (scanned || (FAST.has(info.cls) && info.t <= now)) noticed.push(p); + else nextNotice = Math.min(nextNotice, FAST.has(info.cls) ? info.t : scanAt); + } + for (const key of mind.avail.keys()) if (!live.has(key)) mind.avail.delete(key); + + if (noticed.length) { + if (Math.random() < prof.distract) { + mind.pauseUntil = now + (600 + Math.random() * 1200) * pace; // glanced away + return { wait: mind.pauseUntil - now }; + } + return { action: pick(state, seat, noticed, prof, canFlip && scanned) }; + } + if (scanned && canFlip) return { action: { kind: 'flip' } }; + if (!scanned) return { wait: Math.max(40, Math.min(scanAt, nextNotice) - now) }; + return { wait: Number.isFinite(nextNotice) ? Math.max(40, nextNotice - now) : 500 }; +} diff --git a/src/games/nerts/NertsArt.js b/src/games/nerts/NertsArt.js new file mode 100644 index 0000000..36dd1bb --- /dev/null +++ b/src/games/nerts/NertsArt.js @@ -0,0 +1,365 @@ +// Nerts table art — a home card table baked once per player count into +// 'nerts-table-': floor shadow, a walnut table edge with a visible front +// face, a lamp-lit green felt top, a faint seat-coloured placemat (with pile +// outlines) in front of every player, and the shared foundation zone with a +// suit hint printed in each empty slot. +// +// Also bakes: 'nerts-pad' (paper score pad), 'nerts-hand' (ghost hand, white — +// tinted per seat), 'nerts-tab' (owner corner tab for foundation cards). + +import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern, drawSuit } from '../../ui/casino/CasinoArt.js'; +import { FOUNDATION_SUITS } from './NertsLogic.js'; +import { + P, VIEW, W, H, CARD_W, CARD_H, FELT_K, RAIL_FACE_PX, SEAT_HEX, + outline, layoutFor, pileBase, placematRect, poseScale, +} from './NertsTable.js'; + +const FELT = '#1f5a3c'; +const WOOD_DARK = '#3a1f0e', WOOD_MID = '#6b3c1c', WOOD_HI = '#a8692f'; + +// ── Table ──────────────────────────────────────────────────────────────────── +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.75)'; + ctx.shadowBlur = 70; + ctx.shadowOffsetX = OFF; + ctx.shadowOffsetY = 30; + poly(ctx, pts); + ctx.fillStyle = '#000'; + ctx.fill(); + ctx.restore(); +} + +function drawFrontFace(ctx) { + const top = outline(1.0, 18); + ctx.save(); + 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 = mix(WOOD_MID, WOOD_DARK, Math.min(1, 0.25 + f * 0.9)); + ctx.fill(); + } + 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.8)'; + ctx.stroke(); + ctx.restore(); +} + +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 = WOOD_MID; + ctx.fill('evenodd'); + ctx.clip('evenodd'); + // rounded bevel: dark at both edges, a warm highlight along the crown + for (let i = 0; i <= 16; i++) { + const f = i / 16; + const crown = Math.sin(f * Math.PI); + ring(ctx, lerp(FELT_K, 1.0, f), 5, mix(WOOD_DARK, WOOD_HI, Math.pow(crown, 1.6) * 0.85)); + } + // grain: long faint streaks + ctx.globalAlpha = 0.16; + for (let i = 0; i < 70; i++) { + const k = lerp(FELT_K + 0.004, 0.996, Math.random()); + const pts = 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 ? '#1c0d05' : '#d9a066'; + ctx.stroke(); + } + ctx.globalAlpha = 1; + ctx.fillStyle = noisePattern(ctx, 128, 18); + ctx.fillRect(0, 0, W, H); + ctx.restore(); + ring(ctx, 1.0, 2, 'rgba(0,0,0,0.55)'); + ring(ctx, FELT_K, 2, 'rgba(0,0,0,0.7)'); + ring(ctx, lerp(FELT_K, 1.0, 0.55), 1.2, 'rgba(255,220,170,0.18)'); +} + +function drawFelt(ctx) { + ctx.save(); + poly(ctx, outline(FELT_K, 18)); + ctx.clip(); + ctx.fillStyle = FELT; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 256, 24); + ctx.fillRect(0, 0, W, H); + // overhead lamp + vignette + const c = P.project(0, 0.55); + const lamp = ctx.createRadialGradient(c.x, c.y, 60, c.x, c.y, 1000); + lamp.addColorStop(0, 'rgba(255,240,200,0.22)'); + lamp.addColorStop(0.5, 'rgba(255,240,200,0.07)'); + lamp.addColorStop(1, 'rgba(255,240,200,0)'); + ctx.fillStyle = lamp; + ctx.fillRect(0, 0, W, H); + const vig = ctx.createRadialGradient(c.x, c.y, 380, c.x, c.y, 1100); + vig.addColorStop(0, 'rgba(0,0,0,0)'); + vig.addColorStop(1, 'rgba(0,0,0,0.5)'); + ctx.fillStyle = vig; + ctx.fillRect(0, 0, W, H); + // shadow cast by the rim onto the felt + for (let i = 0; i < 10; i++) ring(ctx, FELT_K - i * 0.004, 4, `rgba(0,0,0,${0.3 * (1 - i / 10)})`); + ctx.restore(); +} + +// A card-sized slot outline at a pose (matches how Phaser draws a card there). +function slot(ctx, pose, { dash = true, alpha = 0.3, fill = null } = {}) { + const { sx, sy } = poseScale(pose.s, pose.rot); + ctx.save(); + ctx.translate(pose.x, pose.y); + ctx.rotate(pose.rot); + ctx.scale(sx, sy); + rr(ctx, -CARD_W / 2 - 3, -CARD_H / 2 - 3, CARD_W + 6, CARD_H + 6, 11); + if (fill) { ctx.fillStyle = fill; ctx.fill(); } + if (dash) ctx.setLineDash([8, 6]); + ctx.lineWidth = 2 / Math.max(sx, 0.4); + ctx.strokeStyle = `rgba(242,234,216,${alpha})`; + ctx.stroke(); + ctx.setLineDash([]); + ctx.restore(); +} + +function drawPlacemats(ctx, L) { + for (const st of L.seats) { + const r = placematRect(st.seat); + const hex = SEAT_HEX[st.seat]; + ctx.save(); + ctx.translate(st.anchor.x, st.anchor.y); + ctx.rotate(st.rot); + ctx.scale(st.k, st.k); + rr(ctx, r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 26); + ctx.globalAlpha = 0.07; + ctx.fillStyle = hex; + ctx.fill(); + ctx.globalAlpha = 0.32; + ctx.lineWidth = 2.5 / st.k; + ctx.strokeStyle = hex; + ctx.stroke(); + ctx.globalAlpha = 1; + // a tiny stitched inner line + rr(ctx, r.x0 + 8, r.y0 + 8, r.x1 - r.x0 - 16, r.y1 - r.y0 - 16, 20); + ctx.setLineDash([6, 6]); + ctx.lineWidth = 1 / st.k; + ctx.strokeStyle = 'rgba(242,234,216,0.12)'; + ctx.stroke(); + ctx.setLineDash([]); + ctx.restore(); + + // pile outlines + slot(ctx, pileBase(L, st.seat, 'nerts'), { dash: false, alpha: 0.42, fill: 'rgba(0,0,0,0.12)' }); + for (let w = 0; w < 4; w++) slot(ctx, pileBase(L, st.seat, 'work', w), { alpha: 0.22 }); + slot(ctx, pileBase(L, st.seat, 'stock'), { alpha: 0.26 }); + slot(ctx, pileBase(L, st.seat, 'waste'), { alpha: 0.16 }); + + if (st.seat === 0) { + ctx.font = '15px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(242,234,216,0.4)'; + const lbl = (kind, text, dy) => { + const b = pileBase(L, 0, kind); + ctx.fillText(text, b.x, b.y + dy); + }; + lbl('stock', 'STOCK', CARD_H * 0.45 + 22); + lbl('waste', 'WASTE', CARD_H * 0.45 + 22); + } + } +} + +function drawFoundationZone(ctx, L) { + const fs = L.foundations; + const k = fs[0].s; + const x0 = Math.min(...fs.map(f => f.x)) - (CARD_W * k) / 2 - 26; + const x1 = Math.max(...fs.map(f => f.x)) + (CARD_W * k) / 2 + 26; + const y0 = Math.min(...fs.map(f => f.y)) - (CARD_H * k * VIEW.squash) / 2 - 26; + const y1 = Math.max(...fs.map(f => f.y)) + (CARD_H * k * VIEW.squash) / 2 + 26; + rr(ctx, x0, y0, x1 - x0, y1 - y0, 22); + ctx.fillStyle = 'rgba(0,0,0,0.10)'; + ctx.fill(); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(217,180,90,0.42)'; + ctx.stroke(); + rr(ctx, x0 + 7, y0 + 7, x1 - x0 - 14, y1 - y0 - 14, 17); + ctx.lineWidth = 1; + ctx.strokeStyle = 'rgba(217,180,90,0.2)'; + ctx.stroke(); + + fs.forEach((f, i) => { + slot(ctx, f, { dash: false, alpha: 0.2, fill: 'rgba(255,255,255,0.05)' }); + const suit = FOUNDATION_SUITS[i % 4]; + ctx.save(); + ctx.globalAlpha = 0.24; + drawSuit(ctx, suit, f.x, f.y, 44 * f.s, suit === 'h' || suit === 'd' ? '#f08a8a' : '#e8e2d0'); + ctx.globalAlpha = 0.3; + ctx.font = `bold ${Math.round(22 * f.s)}px Georgia, serif`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = '#e8e2d0'; + ctx.fillText('A', f.x, f.y - 44 * f.s); + ctx.restore(); + }); + + ctx.font = '15px "Julius Sans One", sans-serif'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(232,193,90,0.55)'; + ctx.fillText('ACES UP · BUILD BY SUIT · ANYONE MAY PLAY', (x0 + x1) / 2, y1 + 18); +} + +function bakeTable(scene, key, playerCount) { + const L = layoutFor(playerCount); + const c = canvas(W, H); + const ctx = c.getContext('2d'); + drawFloorShadow(ctx); + drawFrontFace(ctx); + drawRim(ctx); + drawFelt(ctx); + ctx.save(); + poly(ctx, outline(FELT_K, 18)); + ctx.clip(); + drawPlacemats(ctx, L); + drawFoundationZone(ctx, L); + ctx.restore(); + scene.textures.addCanvas(key, c); +} + +// ── Score pad paper ────────────────────────────────────────────────────────── +// A spiral-bound pad: cream paper, blue rules, red margin. Drawn at any size. +export function ensurePad(scene, key, w, h) { + if (scene.textures.exists(key)) return key; + const c = canvas(w + 24, h + 24); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; + ctx.shadowBlur = 16; + ctx.shadowOffsetX = 4; + ctx.shadowOffsetY = 8; + rr(ctx, 8, 8, w, h, 6); + ctx.fillStyle = '#f7f1dc'; + ctx.fill(); + ctx.restore(); + ctx.save(); + rr(ctx, 8, 8, w, h, 6); + ctx.clip(); + const g = ctx.createLinearGradient(0, 8, 0, h + 8); + g.addColorStop(0, '#fbf6e4'); + g.addColorStop(1, '#ece3c6'); + ctx.fillStyle = g; + ctx.fillRect(8, 8, w, h); + ctx.fillStyle = noisePattern(ctx, 128, 12); + ctx.fillRect(8, 8, w, h); + const top = 8 + Math.max(30, h * 0.12); + const step = Math.max(22, Math.round(h / 16)); + ctx.lineWidth = 1; + ctx.strokeStyle = 'rgba(80,120,200,0.32)'; + for (let y = top + step; y < h + 8; y += step) { + ctx.beginPath(); ctx.moveTo(8, y); ctx.lineTo(w + 8, y); ctx.stroke(); + } + ctx.strokeStyle = 'rgba(210,60,60,0.45)'; + ctx.beginPath(); ctx.moveTo(8 + w * 0.16, 8); ctx.lineTo(8 + w * 0.16, h + 8); ctx.stroke(); + // binding strip + spiral rings + ctx.fillStyle = '#2b2b33'; + ctx.fillRect(8, 8, w, Math.max(14, h * 0.045)); + const rings = Math.max(6, Math.round(w / 34)); + for (let i = 0; i < rings; i++) { + const x = 8 + ((i + 0.5) * w) / rings; + ctx.beginPath(); + ctx.ellipse(x, 8 + Math.max(14, h * 0.045) * 0.5, 5, 9, 0, 0, Math.PI * 2); + ctx.lineWidth = 2.5; + ctx.strokeStyle = '#b9b9c2'; + ctx.stroke(); + } + ctx.restore(); + scene.textures.addCanvas(key, c); + return key; +} + +// ── Ghost hand ─────────────────────────────────────────────────────────────── +// A soft cartoon hand seen from above, fingers pointing "up" (away from its +// owner). White so the scene can tint it per seat. +function bakeHand(scene) { + const S = 128; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + ctx.translate(S / 2, S / 2 + 10); + const shape = () => { + ctx.beginPath(); + // palm + ctx.ellipse(0, 18, 30, 30, 0, 0, Math.PI * 2); + // fingers + const fingers = [[-22, -18, 9, 26], [-7, -28, 9.5, 32], [8, -26, 9.5, 31], [22, -14, 8.5, 24]]; + for (const [fx, fy, rw, rh] of fingers) { + ctx.moveTo(fx + rw, fy); + ctx.ellipse(fx, fy, rw, rh, 0, 0, Math.PI * 2); + } + // thumb + ctx.moveTo(-26, 26); + ctx.ellipse(-34, 14, 9, 22, -0.75, 0, Math.PI * 2); + // wrist/cuff + ctx.rect(-22, 36, 44, 22); + }; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; + ctx.shadowBlur = 8; + ctx.shadowOffsetY = 4; + shape(); + ctx.fillStyle = '#ffffff'; + ctx.fill('nonzero'); + ctx.restore(); + ctx.lineWidth = 3; + ctx.strokeStyle = 'rgba(0,0,0,0.35)'; + shape(); + ctx.stroke(); + // cuff band + ctx.fillStyle = 'rgba(0,0,0,0.18)'; + ctx.fillRect(-22, 44, 44, 14); + scene.textures.addCanvas('nerts-hand', c); +} + +function bakeTab(scene) { + const c = canvas(40, 40); + const ctx = c.getContext('2d'); + ctx.beginPath(); + ctx.moveTo(40, 0); + ctx.lineTo(40, 34); + ctx.quadraticCurveTo(40, 40, 34, 40); + ctx.lineTo(0, 0); + ctx.closePath(); + ctx.fillStyle = '#ffffff'; + ctx.fill(); + scene.textures.addCanvas('nerts-tab', c); +} + +export async function prepareNertsArt(scene, playerCount) { + await prepareCasinoArt(scene); + const key = `nerts-table-${playerCount}`; + if (!scene.textures.exists(key)) bakeTable(scene, key, playerCount); + if (!scene.textures.exists('nerts-hand')) bakeHand(scene); + if (!scene.textures.exists('nerts-tab')) bakeTab(scene); + return key; +} diff --git a/src/games/nerts/NertsGame.js b/src/games/nerts/NertsGame.js index 4094d21..964c013 100644 --- a/src/games/nerts/NertsGame.js +++ b/src/games/nerts/NertsGame.js @@ -4,13 +4,15 @@ import { Button } from '../../ui/Button.js'; import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { CardSkin } from '../../ui/casino/CasinoCards.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; import { - WORK_PILE_COUNT, DEFAULT_TARGET_SCORE, createInitialState, canPlayOnFoundation, + canPlayOnWork, playToFoundation, playToWork, flipStock, @@ -18,52 +20,68 @@ import { allStuck, nertsTop, wasteTop, - workTop, validRunFromIndex, + maxRunStart, + foundationTopRank, + rv, + liveFoundationCounts, + isFoundationComplete, + rotateStocks, reshuffleAllStocks, } from './NertsLogic.js'; -import { chooseAction, nextThinkDelay } from './NertsAI.js'; +import { planMove, createMind, noteOwnChange, reachDelay, carryDelay, handSpeed, rankedPlays, PACE } from './NertsAI.js'; +import { + CARD_W, CARD_H, SQ, SEAT_COLORS, SEAT_HEX, SEAT_BACK_HEX, SCORE_PAD, + layoutFor, cardPose, pileBase, foundationPose, stackLift, cardCorners, poseScale, + seatHome, dealSpot, humanHit, dropTargetAt, targetPose, dragScale, fanStep, nertsBadge, inPose, +} from './NertsTable.js'; +import { prepareNertsArt, ensurePad } from './NertsArt.js'; + +// ─── Nerts ──────────────────────────────────────────────────────────────────── +// A real-time race on a home card table. Geometry lives in NertsTable.js and +// the baked art in NertsArt.js; this file is flow, animation and input. +// +// Every card on the table is a persistent sprite keyed by card id. After any +// state change layout() works out where every card should be and tweens the +// ones that moved — so a card you drop, a flip from the stock, or an +// opponent's play onto the middle all glide (and flip) into place instead of +// being redrawn. const CX = GAME_WIDTH / 2; const CY = GAME_HEIGHT / 2; -const CARD_W = 84; -const CARD_H = 118; -const CARD_R = 8; -const FAN_Y = 26; // vertical fan offset for work piles -const WASTE_FAN = 30; // horizontal fan for the waste's visible cards -const NERTS_FAN = 8; // horizontal fan offset for the nerts pile cards - const D = { - felt: -1, pile: 5, card: 10, drag: 40, ui: 30, fly: 50, panel: 28, modal: 80, + bg: -3, playfield: -2, table: -1, slab: 4, cards: 10, glow: 30, fly: 40, hands: 44, + drag: 50, float: 54, plates: 56, ui: 60, stamp: 70, modal: 80, }; -// Per-seat owner colors — used as a rim on foundation cards so contributions read. -const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c]; -const SEAT_COLOR_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c']; +const SETTINGS_KEY = 'nerts-settings'; +const TARGETS = [50, 100, 150]; +const STALL_PROMPT_MS = 30000; // no progress → offer to rotate stocks +const STALL_AUTO_MS = 60000; // the table agrees on its own +const STALL_END_MS = 90000; // offer to end the round +const STALL_GIVE_UP_MS = 180000; // nobody can move: the round ends on its own +const ROTATE_GAP_MS = 30000; // minimum gap between stock rotations +const HINT_IDLE_MS = 8000; +const RACE_WINDOW_MS = 1500; -// ── Foundation layout ────────────────────────────────────────────────────── -const FOUND_PER_ROW = 8; -const FOUND_GAP_X = 18; -const FOUND_ROW_Y = [286, 286 + CARD_H + 24]; - -// ── Local tableau layout ───────────────────────────────────────────────────── -// x values are recomputed in buildFoundations() based on player count; NERTS x mirrors STOCK x -let NERTS_POS = { x: 340, y: 640 - CARD_H - 16 }; -let WORK_TOP_Y = 540; -const WORK_X = [800, 990, 1180, 1370]; -let STOCK_POS = { x: 1470, y: 640 }; -let WASTE_POS = { x: 1600, y: 640 }; -const LOCAL_PORTRAIT = { x: 130, y: 820, r: 58 }; - -// ── Opponent panel layout ───────────────────────────────────────────────────── -const PANEL_W = 320; -const PANEL_H = 160; -const PANEL_POSITIONS = { - 1: [{ x: 960, y: 120 }], - 2: [{ x: 620, y: 120 }, { x: 1300, y: 120 }], - 3: [{ x: 430, y: 120 }, { x: 960, y: 120 }, { x: 1490, y: 120 }], +const lerp = (a, b, t) => a + (b - a) * t; +const lerpAngle = (a, b, t) => { + let d = b - a; + while (d > Math.PI) d -= Math.PI * 2; + while (d < -Math.PI) d += Math.PI * 2; + return a + d * t; }; +const samePose = (a, b) => a && b && Math.abs(a.x - b.x) < 0.5 && Math.abs(a.y - b.y) < 0.5 + && Math.abs(a.rot - b.rot) < 0.001 && Math.abs(a.s - b.s) < 0.001; + +function loadSettings(defaultTarget) { + const base = { target: defaultTarget, draw: 3, pace: 'normal', hints: false }; + try { + const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + return { ...base, ...saved }; + } catch { return base; } +} export default class NertsGame extends Phaser.Scene { constructor() { super('NertsGame'); } @@ -73,353 +91,538 @@ export default class NertsGame extends Phaser.Scene { this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; this.cardBack = data.cardBack ?? null; - this.targetScore = data.game?.targetScore ?? DEFAULT_TARGET_SCORE; + this.playerCount = Math.min(4, 1 + this.opponents.length); + this.L = layoutFor(this.playerCount); + this.settings = loadSettings(data.game?.targetScore ?? DEFAULT_TARGET_SCORE); - this.playerCount = 1 + this.opponents.length; this.gs = null; this.totals = new Array(this.playerCount).fill(0); + this.history = []; // per round: summary array + this.round = 0; + + this.sprites = new Map(); // card id → card container + this.lastLoc = new Map(); // card id → { pose, faceUp, depth } from the last layout + this.dragIds = new Set(); + this.mode = 'idle'; // idle | dealing | countdown | playing | ending | summary + this.paused = false; + this.modal = null; - this.localCardObjs = new Map(); // card.id → container (local tableau) - this.localExtraObjs = []; // non-keyed local sprites (face-down backs) - this.foundationCardObjs = []; // foundation top-card sprites - this.foundationPos = []; // idx → {x,y} - this.foundationSlotRects = []; - this.foundationHints = []; // idx → { bg, label } shown when slot is empty - this.oppPanelPos = []; // seat → {x,y} (portrait pos, for fly origin) - this.oppDynamic = []; // seat → { nertsText, scoreText } - this.opponentPortraits = []; this.aiTimers = []; - this.foundationCooldowns = []; // idx → Phaser time when slot becomes AI-playable again - - this.lastMoveSeconds = 0; - this.lastMoveTimer = null; - this.lastMoveCountText = null; - this.shuffleBtn = null; - this.resignBtn = null; - + this.hands = []; + this.minds = []; // seat → AI perception state (NertsAI.createMind) + this.foundationChanged = []; // idx → { at (play clock), seat, rank, suit } + this.portraits = []; + this.plates = []; + this.badges = []; this.potentialDrag = null; this.dragState = null; - this.dropHighlight = null; - this.foundationPulseObjs = []; - this.roundEnding = false; - this.panelObjs = []; + + this.playMs = 0; // play-clock (excludes pause / deal / scoring) + this.lastProgressMs = 0; + this.lastHumanMs = 0; + this.lastRotateMs = -Infinity; + this.rotations = 0; + this.hint = null; } - create() { + // ── Lifecycle ─────────────────────────────────────────────────────────────── + async create() { try { const music = this.cache.json.get('music'); if (music?.tracks) new MusicPlayer(this, music.tracks); } catch (_) { /* music optional */ } - this.buildPlayfield(); - this.buildFoundations(); - this.buildLocalArea(); - this.buildOpponentPanels(); - this.buildHUD(); - this.buildLastMovePanel(); - this.setupDragHandlers(); + this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, COLORS.bg ?? 0x120e09).setDepth(D.bg); + const pf = this.playfield; + if (pf?.key && this.textures.exists(pf.key)) { + this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.playfield); + } + this.events.once('shutdown', () => { + this.stopAI(); + this.input.setDefaultCursor('default'); + }); - this.events.once('shutdown', () => this.stopAITimers()); + const tableKey = await prepareNertsArt(this, this.playerCount); + if (!this.sys.isActive()) return; + this.add.image(0, 0, tableKey).setOrigin(0, 0).setDepth(D.table); + + this.skins = []; + for (let seat = 0; seat < this.playerCount; seat++) { + this.skins[seat] = seat === 0 + ? new CardSkin(this, this.cardBack, { depth: D.cards }) + : new CardSkin(this, { fallbackColor: SEAT_BACK_HEX[seat] }, { depth: D.cards }); + } + + this.slabG = this.add.graphics().setDepth(D.slab); + this.targetG = this.add.graphics().setDepth(D.glow); + this.hintG = this.add.graphics().setDepth(D.glow + 1); + this.recycleTxt = this.add.text(0, 0, '↻', { + fontFamily: 'sans-serif', fontSize: '54px', color: '#f2ead8', + }).setOrigin(0.5).setAlpha(0.55).setDepth(D.slab + 1).setVisible(false); + const sb = pileBase(this.L, 0, 'stock'); + this.recycleTxt.setPosition(sb.x, sb.y); + + this.buildPlates(); + this.buildBadges(); + this.buildHands(); + this.buildMiniPad(); + this.buildTopButtons(); + this.buildStallWidget(); + this.setupInput(); this.startRound(); } - // ── Static layout ──────────────────────────────────────────────────────── + update(_time, delta) { + if (this.mode !== 'playing' || this.paused || this.modal) return; + this.playMs += delta; + this.updateStall(); + this.updateHint(); + } - buildPlayfield() { - const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.felt); - } else { - const color = pf?.fallbackColor ? parseInt(pf.fallbackColor.replace('#', ''), 16) : 0x14532d; - this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, color).setDepth(D.felt); + alive() { return this.sys.isActive(); } + wait(ms) { return new Promise(res => this.time.delayedCall(ms, res)); } + canAct() { return this.mode === 'playing' && !this.paused && !this.modal; } + nameForSeat(seat) { + if (seat === 0) return auth.user?.username ?? 'You'; + if (seat < 0) return 'Nobody'; + return this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`; + } + skillFor(seat) { return this.opponents[seat - 1]?.skill ?? 3; } + pace() { return PACE[this.settings.pace] ?? 1; } + + saveSettings() { + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + } + + // ── Seat furniture ───────────────────────────────────────────────────────── + buildPlates() { + const panelKey = ensureLeatherPanel(this, 'nerts-plate', 268, 92, { radius: 14 }); + for (let seat = 0; seat < this.playerCount; seat++) { + const pl = this.L.seats[seat].plate; + const bg = this.add.image(pl.x, pl.y, panelKey).setDepth(D.plates); + const stripe = this.add.graphics().setDepth(D.plates + 0.5); + stripe.fillStyle(SEAT_COLORS[seat], 1); + stripe.fillRoundedRect(pl.x - 128, pl.y - 34, 6, 68, 3); + const px = pl.x - 84; + this.portraits[seat] = seat === 0 + ? createPlayerPortrait(this, px, pl.y, 34, D.plates + 1, 'NertsGame') + : createOpponentPortrait(this, this.opponents[seat - 1], px, pl.y, 34, D.plates + 1); + let name = this.nameForSeat(seat); + if (name.length > 13) name = `${name.slice(0, 12)}…`; + const tx = pl.x - 40; + const nameTxt = this.add.text(tx, pl.y - 22, name, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.plates + 2); + if (seat > 0) { + const skill = this.skillFor(seat); + for (let i = 0; i < 5; i++) { + this.add.circle(tx + 4 + i * 12, pl.y + 1, 3.5, i < skill ? COLORS.accent : COLORS.muted, i < skill ? 1 : 0.35) + .setDepth(D.plates + 2); + } + } else { + this.add.text(tx, pl.y + 1, 'YOU', { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: SEAT_HEX[0], + }).setOrigin(0, 0.5).setDepth(D.plates + 2); + } + const totalTxt = this.add.text(tx, pl.y + 23, 'Total 0', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, + }).setOrigin(0, 0.5).setDepth(D.plates + 2); + const liveTxt = this.add.text(pl.x + 122, pl.y + 21, '+0', { + fontFamily: 'Righteous', fontSize: '24px', color: SEAT_HEX[seat], + }).setOrigin(1, 0.5).setDepth(D.plates + 2); + // count-back tally, shown only while a round is being scored + const tallyY = seat === 0 ? pl.y - 82 : pl.y + 74; + const tallyTxt = this.add.text(pl.x, tallyY, '', { + fontFamily: 'Righteous', fontSize: '40px', color: SEAT_HEX[seat], + stroke: '#120c06', strokeThickness: 7, + }).setOrigin(0.5).setDepth(D.stamp - 1).setVisible(false); + this.plates[seat] = { bg, stripe, nameTxt, totalTxt, liveTxt, tallyTxt, pulse: null, x: pl.x, y: pl.y }; } } - buildFoundations() { - const total = 4 * this.playerCount; - const countInRow0 = Math.min(FOUND_PER_ROW, total); - const rowW = countInRow0 * CARD_W + (countInRow0 - 1) * FOUND_GAP_X; - // Nerts + stock + waste live on the left; work piles are on the right. - NERTS_POS.x = 600; - STOCK_POS.x = 495; - WASTE_POS.x = 605; - - const yOffset = this.opponents.length >= 2 ? 100 : 0; - WORK_TOP_Y = 540 + yOffset; - STOCK_POS.y = 715 + yOffset; - WASTE_POS.y = 715 + yOffset; - NERTS_POS.y = 640 - CARD_H - 16 + yOffset; - - for (let idx = 0; idx < total; idx++) { - const row = Math.floor(idx / FOUND_PER_ROW); - const col = idx % FOUND_PER_ROW; - const countInRow = Math.min(FOUND_PER_ROW, total - row * FOUND_PER_ROW); - const rowW = countInRow * CARD_W + (countInRow - 1) * FOUND_GAP_X; - const startX = CX - rowW / 2 + CARD_W / 2; - const x = startX + col * (CARD_W + FOUND_GAP_X); - const y = FOUND_ROW_Y[row]; - this.foundationPos[idx] = { x, y }; - const r = this.add.rectangle(x, y, CARD_W + 4, CARD_H + 4, 0x000000, 0.22) - .setStrokeStyle(2, COLORS.muted, 0.5).setDepth(D.pile); - this.foundationSlotRects[idx] = r; - - const HINT_SUITS = ['♠', '♥', '♦', '♣']; - const HINT_COLORS = ['#aab0cc', '#cc8888', '#cc8888', '#aab0cc']; - const suit = idx % 4; - const hintBg = this.add.graphics().setDepth(D.card - 1); - hintBg.fillStyle(0xffffff, 0.45); - hintBg.fillRoundedRect(x - CARD_W / 2, y - CARD_H / 2, CARD_W, CARD_H, CARD_R); - const hintLabel = this.add.text(x, y, HINT_SUITS[suit], { - fontFamily: 'Arial', fontSize: '52px', color: HINT_COLORS[suit], - }).setOrigin(0.5).setAlpha(0.95).setDepth(D.card - 1); - this.foundationHints[idx] = { bg: hintBg, label: hintLabel }; - } - this.add.text(CX, FOUND_ROW_Y[0] - CARD_H / 2 - 26, 'FOUNDATIONS — play Aces here, build up by suit', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - } - - buildLocalArea() { - // Nerts pile - this.add.rectangle(NERTS_POS.x, NERTS_POS.y, CARD_W + 8, CARD_H + 8, 0x000000, 0.4) - .setStrokeStyle(3, COLORS.accent).setDepth(D.pile); - this.add.text(NERTS_POS.x, NERTS_POS.y - CARD_H / 2 - 40, 'NERTS', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.ui); - this.localNertsText = this.add.text(NERTS_POS.x, NERTS_POS.y - CARD_H / 2 - 18, '13 left', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - // Work pile placeholders - for (let i = 0; i < WORK_PILE_COUNT; i++) { - this.add.rectangle(WORK_X[i], WORK_TOP_Y, CARD_W + 4, CARD_H + 4, 0x000000, 0.2) - .setStrokeStyle(1, COLORS.muted, 0.5).setDepth(D.pile); - } - - // Stock + waste - const stockRect = this.add.rectangle(STOCK_POS.x, STOCK_POS.y, CARD_W + 8, CARD_H + 8, 0x000000, 0.4) - .setStrokeStyle(2, COLORS.muted).setDepth(D.pile).setInteractive({ useHandCursor: true }); - stockRect.on('pointerdown', () => this.onStockClick()); - this.add.text(STOCK_POS.x, STOCK_POS.y - CARD_H / 2 - 18, 'STOCK', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.localStockText = this.add.text(STOCK_POS.x, STOCK_POS.y + CARD_H / 2 + 16, '', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - - // Local portrait + name + score - createPlayerPortrait(this, LOCAL_PORTRAIT.x, LOCAL_PORTRAIT.y, LOCAL_PORTRAIT.r, D.ui, 'NertsGame'); - this.add.text(LOCAL_PORTRAIT.x, LOCAL_PORTRAIT.y + LOCAL_PORTRAIT.r + 16, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - this.localScoreText = this.add.text(LOCAL_PORTRAIT.x, LOCAL_PORTRAIT.y + LOCAL_PORTRAIT.r + 44, 'Score: 0', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.ui); - } - - buildOpponentPanels() { - const positions = PANEL_POSITIONS[this.opponents.length] ?? []; - for (let i = 0; i < this.opponents.length; i++) { - const seat = i + 1; - const opp = this.opponents[i]; - const pos = positions[i] ?? { x: 960, y: 120 }; - - this.add.rectangle(pos.x, pos.y, PANEL_W, PANEL_H, COLORS.panel, 0.82) - .setStrokeStyle(2, SEAT_COLORS[seat] ?? COLORS.muted).setDepth(D.panel); - - const portX = pos.x - PANEL_W / 2 + 56; - this.opponentPortraits[seat] = createOpponentPortrait(this, opp, portX, pos.y, 46, D.panel + 1); - this.oppPanelPos[seat] = { x: portX, y: pos.y }; - - const textX = portX + 64; - this.add.text(textX, pos.y - 56, opp.name ?? `Player ${seat + 1}`, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.panel + 1); - - this.buildSkillPips(textX, pos.y - 26, opp.skill ?? 3); - - const nertsText = this.add.text(textX, pos.y + 8, 'Nerts: 13', { - fontFamily: 'Righteous', fontSize: '24px', color: SEAT_COLOR_HEX[seat] ?? COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.panel + 1); - const scoreText = this.add.text(textX, pos.y + 40, 'Score: 0', { - fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.panel + 1); - - this.oppDynamic[seat] = { nertsText, scoreText, panelPos: { x: pos.x, y: pos.y }, nertsCard: null, stockCard: null, wasteCards: [] }; + buildBadges() { + for (let seat = 0; seat < this.playerCount; seat++) { + const p = nertsBadge(this.L, seat); + const r = seat === 0 ? 19 : 15; + const c = this.add.container(p.x, p.y).setDepth(D.glow + 2); + const glow = this.add.circle(0, 0, r + 7, 0xff8a2a, 0.0); + const g = this.add.graphics(); + g.fillStyle(0x140d07, 0.92); + g.fillCircle(0, 0, r); + g.lineStyle(2.5, SEAT_COLORS[seat], 1); + g.strokeCircle(0, 0, r); + const t = this.add.text(0, 1, '13', { + fontFamily: 'Righteous', fontSize: `${seat === 0 ? 20 : 16}px`, color: COLORS.textHex, + }).setOrigin(0.5); + c.add([glow, g, t]); + if (seat === 0) { + const lbl = this.add.text(0, -r - 11, 'NERTS', { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: SEAT_HEX[0], + }).setOrigin(0.5); + c.add(lbl); + } + this.badges[seat] = { c, glow, t, glowTw: null, last: 13 }; } } - buildSkillPips(x, y, skill) { - this.add.text(x, y, 'SKILL', { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.panel + 1); - const pipX = x + 52; - for (let i = 0; i < 5; i++) { - const filled = i < skill; - this.add.circle(pipX + i * 18, y, 6, filled ? COLORS.accent : COLORS.muted, filled ? 1 : 0.35) - .setStrokeStyle(1, COLORS.accent, filled ? 1 : 0.4).setDepth(D.panel + 1); + buildHands() { + for (let seat = 1; seat < this.playerCount; seat++) { + const st = this.L.seats[seat]; + const home = seatHome(this.L, seat); + const h = this.add.image(home.x, home.y, 'nerts-hand') + .setTint(SEAT_COLORS[seat]).setAlpha(0.22).setRotation(st.rot) + .setScale(0.62 * (0.5 + st.k)).setDepth(D.hands); + this.hands[seat] = { img: h, home, tw: null, retTimer: null }; } } - buildHUD() { - this.statusText = this.add.text(24, 36, `Nerts — first to ${this.targetScore} points`, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui); - - new Button(this, GAME_WIDTH - 90, GAME_HEIGHT - 50, 'Leave', - () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 130, height: 40, fontSize: 18 }).setDepth(D.ui); + buildMiniPad() { + const { x, y, w, h } = SCORE_PAD; + const key = ensurePad(this, 'nerts-pad-mini', w, h); + this.miniPad = this.add.image(x, y, key).setDepth(D.plates).setRotation(-0.035) + .setInteractive({ useHandCursor: true }); + this.miniPad.on('pointerup', () => { if (!this.modal && (this.mode === 'playing' || this.mode === 'countdown')) this.openScorePad({ readOnly: true }); }); + const font = '"YummyCupcakes", "Comic Sans MS", cursive'; + this.miniTitle = this.add.text(x - w / 2 + 48, y - h / 2 + 34, '', { + fontFamily: font, fontSize: '22px', color: '#2a2418', + }).setOrigin(0, 0.5).setDepth(D.plates + 1).setRotation(-0.035); + this.miniRows = []; + for (let seat = 0; seat < this.playerCount; seat++) { + const ry = y - h / 2 + 76 + seat * 32; + const dot = this.add.circle(x - w / 2 + 30, ry, 6, SEAT_COLORS[seat]).setDepth(D.plates + 1); + let nm = seat === 0 ? 'You' : this.nameForSeat(seat); + if (nm.length > 10) nm = `${nm.slice(0, 9)}…`; + const name = this.add.text(x - w / 2 + 48, ry, nm, { + fontFamily: font, fontSize: '20px', color: '#2a2418', + }).setOrigin(0, 0.5).setDepth(D.plates + 1).setRotation(-0.035); + const score = this.add.text(x + w / 2 - 22, ry, '0', { + fontFamily: font, fontSize: '22px', color: '#1c3f8f', + }).setOrigin(1, 0.5).setDepth(D.plates + 1).setRotation(-0.035); + this.miniRows[seat] = { dot, name, score }; + } + this.add.text(x - w / 2 + 48, y + h / 2 - 20, 'tap for scores', { + fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#8a7e66', + }).setOrigin(0, 0.5).setDepth(D.plates + 1).setRotation(-0.035); + const gear = this.add.text(x + w / 2 - 18, y - h / 2 + 32, '⚙', { + fontFamily: 'sans-serif', fontSize: '28px', color: '#5a4e38', + }).setOrigin(0.5).setDepth(D.plates + 2).setInteractive({ useHandCursor: true }); + gear.on('pointerup', (p, lx, ly, ev) => { ev?.stopPropagation?.(); if (!this.modal) this.openSettings(); }); + this.updateMiniPad(); } - buildLastMovePanel() { - this.add.rectangle(130, 460, 180, 200, 0x000000, 0.55).setDepth(D.ui).setOrigin(0.5); - this.add.text(130, 390, 'Last Move', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.lastMoveCountText = this.add.text(130, 440, '00', { - fontFamily: 'Righteous', fontSize: '64px', color: '#ffffff', - }).setOrigin(0.5).setDepth(D.ui); - this.add.text(130, 500, 'seconds', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.shuffleBtn = new Button(this, 130, 545, 'Shuffle Stock', - () => this.onShuffleStock(), - { width: 160, height: 38, fontSize: 15 } - ).setDepth(D.ui).setVisible(false); - this.resignBtn = new Button(this, 130, 591, 'Resign', - () => this.onResign(), - { width: 160, height: 38, fontSize: 15, variant: 'ghost' } - ).setDepth(D.ui).setVisible(false); + updateMiniPad() { + if (!this.miniTitle) return; + this.miniTitle.setText(`Round ${Math.max(1, this.round)} · to ${this.settings.target}`); + const best = Math.max(...this.totals); + for (let seat = 0; seat < this.playerCount; seat++) { + const r = this.miniRows[seat]; + r.score.setText(String(this.totals[seat])); + r.score.setColor(this.totals[seat] === best && best > 0 ? '#b8231f' : '#1c3f8f'); + } } - startLastMoveTimer() { - if (this.lastMoveTimer) { this.lastMoveTimer.remove(false); this.lastMoveTimer = null; } - this.lastMoveSeconds = 0; - this.lastMoveCountText?.setText('00'); - this.shuffleBtn?.setVisible(false); - this.lastMoveTimer = this.time.addEvent({ - delay: 1000, loop: true, callback: this.onLastMoveTick, callbackScope: this, + buildTopButtons() { + new Button(this, 84, 44, 'Leave', () => this.onLeave(), { + variant: 'ghost', width: 130, height: 44, fontSize: 18, + }).setDepth(D.ui); + this.pauseBtn = new Button(this, 226, 44, 'Pause', () => this.togglePause(), { + variant: 'ghost', width: 130, height: 44, fontSize: 18, + }).setDepth(D.ui); + this.keysTxt = this.add.text(20, GAME_HEIGHT - 16, + 'Click a card to auto-play · drag to place · Space flip · N nerts · W waste · 1-4 piles · H hint · Esc pause', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + }).setOrigin(0, 1).setDepth(D.ui).setAlpha(0.8); + } + + buildStallWidget() { + const x = 200, y = 760; + const c = this.add.container(x, y).setDepth(D.ui).setVisible(false); + const bg = this.add.graphics(); + bg.fillStyle(0x140d07, 0.86); + bg.fillRoundedRect(-150, -46, 300, 92, 12); + bg.lineStyle(2, COLORS.accent, 0.8); + bg.strokeRoundedRect(-150, -46, 300, 92, 12); + // sand timer (drawn about its own centre so it can spin) + const hg = this.add.graphics(); + hg.lineStyle(2, 0xe8c15a, 1); + hg.strokeTriangle(-12, -20, 12, -20, 0, 0); + hg.strokeTriangle(-12, 20, 12, 20, 0, 0); + hg.fillStyle(0xe8c15a, 0.8); + hg.fillTriangle(-8, 17, 8, 17, 0, 6); + hg.setPosition(-116, -4); + this.stallTxt = this.add.text(-92, -24, 'Table stuck?', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, + }).setOrigin(0, 0.5); + this.stallBtn = new Button(this, 22, 16, 'Rotate stocks', () => this.rotateTable(false), { + width: 150, height: 36, fontSize: 15, }); + this.stallEndBtn = new Button(this, 22, 16, 'End round', () => this.onEndRoundEarly(), { + width: 150, height: 36, fontSize: 15, variant: 'ghost', + }); + this.stallEndBtn.setVisible(false); + c.add([bg, hg, this.stallTxt, this.stallBtn, this.stallEndBtn]); + this.stall = c; + this.hgSpin = this.tweens.add({ targets: hg, angle: 180, duration: 900, repeat: -1, repeatDelay: 1400, paused: true }); } - onLastMoveTick() { - if (this.roundEnding) return; - this.lastMoveSeconds += 1; - const s = this.lastMoveSeconds; - this.lastMoveCountText?.setText(String(s).padStart(2, '0')); - const color = s > 60 ? '#ff2222' : s > 45 ? '#ff8800' : s > 30 ? '#ffee00' : '#ffffff'; - this.lastMoveCountText?.setColor(color); - if (s >= 60) this.shuffleBtn?.setVisible(true); - if (s >= 90) this.resignBtn?.setVisible(true); - } - - resetLastMoveTimer() { - this.lastMoveSeconds = 0; - this.lastMoveCountText?.setText('00'); - this.lastMoveCountText?.setColor('#ffffff'); - this.shuffleBtn?.setVisible(false); - this.resignBtn?.setVisible(false); - } - - onResign() { - if (!this.isPlayable()) return; - this.finishRound(); - } - - onShuffleStock() { - if (!this.isPlayable()) return; - reshuffleAllStocks(this.gs); - playSound(this, SFX.CARD_SHUFFLE); - this.resetLastMoveTimer(); - this.renderAll(); - } - - // ── Round lifecycle ──────────────────────────────────────────────────────── - + // ── Round lifecycle ────────────────────────────────────────────────────────── startRound() { - this.roundEnding = false; - this.foundationCooldowns = []; + this.clearTable(); + this.round += 1; + this.mode = 'dealing'; + this.rotations = 0; + this.lastRotateMs = -Infinity; + this.foundationChanged = []; this.gs = createInitialState({ playerCount: this.playerCount, - targetScore: this.targetScore, + targetScore: this.settings.target, totals: this.totals, + drawCount: this.settings.draw, }); - playSound(this, SFX.CARD_SHUFFLE); - this.renderAll(); - this.startAITimers(); - this.startLastMoveTimer(); + // every card starts in its owner's hand, face down + this.lastLoc = new Map(); + for (const p of this.gs.players) { + const from = dealSpot(this.L, p.seat); + const all = [...p.nerts, ...p.work.flat(), ...p.stockDraw]; + for (const card of all) this.lastLoc.set(card.id, { pose: from, faceUp: false, depth: D.fly }); + } + for (const pl of this.plates) pl.tallyTxt.setVisible(false); + this.updateMiniPad(); + this.updateHUD(); + this.runDeal(); } - startAITimers() { - this.stopAITimers(); - for (let seat = 1; seat < this.playerCount; seat++) { - this.scheduleAITick(seat); + clearTable() { + this.stopAI(); + for (const c of this.sprites.values()) { c._tw?.stop(); c.destroy(); } + this.sprites.clear(); + this.dragIds.clear(); + this.dragState = null; + this.potentialDrag = null; + this.slabG?.clear(); + this.targetG?.clear(); + this.clearHint(); + this.stall?.setVisible(false); + if (this.fx) for (const o of this.fx) o.destroy(); + this.fx = []; + } + + async runDeal() { + playSound(this, SFX.CARD_SHUFFLE); + // A few loose backs "counted out" toward the nerts and stock piles first. + for (let seat = 0; seat < this.playerCount; seat++) { + const from = dealSpot(this.L, seat); + const skin = this.skins[seat]; + const piles = [['nerts', 5], ['stock', 3]]; + let n = 0; + for (const [kind, count] of piles) { + for (let i = 0; i < count; i++) { + const to = pileBase(this.L, seat, kind); + const c = skin.make(null, false, from.x, from.y, from.s, from.rot); + this.applyPose(c, from); + c.setDepth(D.fly); + this.fx.push(c); + this.tweenCard(c, to, { delay: n * 55 + seat * 40, duration: 260, onDone: () => c.destroy() }); + n++; + } + } + } + this.time.delayedCall(260, () => playSound(this, SFX.CARD_DEAL)); + this.layout({ + slabs: false, + delayFor: (v) => { + const base = 480 + v.seat * 40; + if (v.kind === 'nerts') return base; + if (v.kind === 'work') return base + 140 + v.idx * 90; + return base + 560; + }, + duration: 320, + }); + await this.wait(1350); + if (!this.alive()) return; + this.drawSlabs(); + await this.countdown(); + if (!this.alive()) return; + this.mode = 'playing'; + this.playMs = 0; + this.lastProgressMs = 0; + this.lastHumanMs = 0; + this.startAI(); + } + + async countdown() { + this.mode = 'countdown'; + const words = [['Ready…', '#f2ead8', SFX.COUNTDOWN_TICK], ['Set…', '#f2ead8', SFX.COUNTDOWN_TICK], ['NERTS!', '#ffd35a', SFX.COUNTDOWN_GO]]; + const y = this.L.foundations.reduce((a, f) => a + f.y, 0) / this.L.foundations.length; + for (const [word, color, sfx] of words) { + const t = this.add.text(CX, y, word, { + fontFamily: 'Righteous', fontSize: word === 'NERTS!' ? '120px' : '84px', color, + stroke: '#120c06', strokeThickness: 10, + }).setOrigin(0.5).setDepth(D.stamp).setScale(1.7).setAlpha(0); + playSound(this, sfx); + this.tweens.add({ targets: t, scale: 1, alpha: 1, duration: 200, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, scale: 0.9, delay: word === 'NERTS!' ? 520 : 420, duration: 180, onComplete: () => t.destroy() }); + await this.wait(word === 'NERTS!' ? 260 : 620); + if (!this.alive()) return; } } - scheduleAITick(seat) { - const skill = this.opponents[seat - 1]?.skill ?? 3; - this.aiTimers[seat] = this.time.delayedCall(nextThinkDelay(skill), () => this.aiTick(seat)); + // ── AI ────────────────────────────────────────────────────────────────────── + startAI() { + this.stopAI(); + for (let seat = 1; seat < this.playerCount; seat++) { + this.minds[seat] = createMind(this.skillFor(seat), this.playMs); + this.scheduleAI(seat, 100 + Math.random() * 200); + } } - stopAITimers() { - for (const t of this.aiTimers) { if (t) t.remove(false); } + stopAI() { + for (const t of this.aiTimers) t?.remove(false); this.aiTimers = []; } + scheduleAI(seat, delay) { + this.aiTimers[seat]?.remove(false); + this.aiTimers[seat] = this.time.delayedCall(Math.max(16, delay), () => this.aiTick(seat)); + } + + // Each AI seat looks at the table on a short poll. NertsAI.planMove decides + // whether it has noticed anything yet (reading its own cards, noticing other + // players' plays, pouncing on a card it was waiting for) — or how long to keep + // looking. Then the ghost hand reaches, and the move lands when it arrives. aiTick(seat) { - if (this.roundEnding || !this.gs || this.gs.phase !== 'playing') return; - - const skill = this.opponents[seat - 1]?.skill ?? 3; - const action = chooseAction(this.gs, seat, skill); - if (action) this.applyAIAction(seat, action); - - if (this.checkEnd()) return; - this.scheduleAITick(seat); + if (this.mode !== 'playing' || !this.gs) return; + const plan = planMove(this.gs, seat, this.minds[seat], { + now: this.playMs, pace: this.pace(), foundationAt: this.foundationChanged, + stalledMs: this.playMs - this.lastProgressMs, + }); + if (!plan.action) { + // re-check at least every 250ms: someone else's play may change things + this.scheduleAI(seat, Math.min(250, plan.wait ?? 250)); + return; + } + const action = plan.action; + const skill = this.skillFor(seat); + const reach = reachDelay(skill, this.pace(), action.kind === 'flip' ? 'flip' : 'move'); + const grabAt = action.kind === 'flip' + ? cardPose(this.L, seat, 'stock', 0, 0, 1) + : this.sourcePose(seat, action.source); + this.moveHand(seat, grabAt, reach); + this.aiTimers[seat] = this.time.delayedCall(reach, () => this.aiCommit(seat, action)); } - markFoundationCooldown(idx) { - this.foundationCooldowns[idx] = this.time.now + 2000; - } - - applyAIAction(seat, action) { - if (action.kind === 'foundation') { - if (this.time.now < (this.foundationCooldowns[action.dest] ?? 0)) return; - const card = this.actionCard(seat, action); + aiCommit(seat, action) { + if (this.mode !== 'playing' || !this.gs) return; + const mind = this.minds[seat]; + const skill = this.skillFor(seat); + const slow = this.pace() / handSpeed(skill); // scales every hand motion for this seat + const carry = carryDelay(skill, this.pace()); // the card rides with the hand + let next = 60; + if (action.kind === 'flip') { + const log = flipStock(this.gs, seat); + if (log) playSoundEx(this, log.type === 'recycle' ? SFX.CARD_SHUFFLE : SFX.CARD_SHOW, { volume: 0.25 }); + noteOwnChange(mind, this.playMs, 'flip'); + this.layout(); + this.handHome(seat, 260 * slow); + } else if (action.kind === 'foundation') { + const card = this.sourceCard(seat, action.source); const log = playToFoundation(this.gs, seat, action.source, action.dest); - if (log) { - this.markFoundationCooldown(action.dest); - this.resetLastMoveTimer(); - const dest = this.foundationPos[action.dest]; - const origin = this.oppPanelPos[seat]; - if (card && dest && origin) this.spawnFly(card, origin.x, origin.y, dest.x, dest.y, seat); - playSound(this, SFX.CARD_PLACE); - if (action.source.type === 'nerts' && Math.random() < 0.5) { - this.opponentPortraits[seat]?.playEmotion('happy'); - } + if (!log) { + // beaten to it — fumble the card, pull back, take a moment to regroup + this.tooSlow(action.dest, seat, card); + noteOwnChange(mind, this.playMs, 'fumble'); + this.handHome(seat, 420 * slow); + } else { + noteOwnChange(mind, this.playMs, 'move'); + this.moveHand(seat, this.L.foundations[action.dest], carry, 'Cubic.easeOut'); + this.afterMove(seat, log, { carry }); + if (action.source.type === 'nerts' && Math.random() < 0.5) this.portraits[seat]?.playEmotion?.('happy'); + this.handHome(seat, 520 * slow, carry + 60); + next = carry; } } else if (action.kind === 'work') { - const wlog = playToWork(this.gs, seat, action.source, action.dest); - if (wlog && action.source.type === 'nerts') this.resetLastMoveTimer(); - } else if (action.kind === 'flip') { - flipStock(this.gs, seat); - playSound(this, SFX.CARD_SHOW); + const log = playToWork(this.gs, seat, action.source, action.dest); + noteOwnChange(mind, this.playMs, 'move'); + if (log) { + const n = this.gs.players[seat].work[action.dest].length; + const k = n - log.cards.length; + this.moveHand(seat, cardPose(this.L, seat, 'work', action.dest, k, n), carry, 'Cubic.easeOut'); + this.afterMove(seat, log, { carry }); + this.handHome(seat, 480 * slow, carry + 60); + next = carry; + } else { + this.handHome(seat, 480 * slow); + } } - this.renderFoundations(); - this.renderOpponents(); + // the hand finishes carrying before it reaches for anything else + if (this.mode === 'playing') this.scheduleAI(seat, next); } - actionCard(seat, action) { - const s = action.source; - if (s.type === 'nerts') return nertsTop(this.gs, seat); - if (s.type === 'waste') return wasteTop(this.gs, seat); - if (s.type === 'work') return workTop(this.gs, seat, s.idx); - return null; + sourceCard(seat, source) { + if (source.type === 'nerts') return nertsTop(this.gs, seat); + if (source.type === 'waste') return wasteTop(this.gs, seat); + const pile = this.gs.players[seat].work[source.idx]; + return pile[pile.length - (source.count ?? 1)] ?? null; + } + + sourcePose(seat, source) { + const p = this.gs.players[seat]; + if (source.type === 'nerts') return cardPose(this.L, seat, 'nerts', 0, p.nerts.length - 1, p.nerts.length); + if (source.type === 'waste') return cardPose(this.L, seat, 'waste', 0, p.stockWaste.length - 1, p.stockWaste.length); + const pile = p.work[source.idx]; + const k = pile.length - (source.count ?? 1); + return cardPose(this.L, seat, 'work', source.idx, k, pile.length); + } + + moveHand(seat, pt, duration, ease = 'Sine.easeInOut') { + const h = this.hands[seat]; + if (!h) return; + h.tw?.stop(); + h.retTimer?.remove(false); + h.img.setAlpha(0.62); + h.tw = this.tweens.add({ targets: h.img, x: pt.x, y: pt.y + 6, duration, ease }); + } + + handHome(seat, duration, delay = 0) { + const h = this.hands[seat]; + if (!h) return; + h.retTimer?.remove(false); + h.retTimer = 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.22, duration, ease: 'Sine.easeInOut' }); + }); + } + + // ── After any move ─────────────────────────────────────────────────────────── + afterMove(seat, log, { carry = null } = {}) { + if (log.type === 'foundation') { + if (seat !== 0 && this.hint?.play?.kind === 'foundation' && this.hint.play.dest === log.fIdx) this.clearHint(); + this.foundationChanged[log.fIdx] = { at: this.playMs, seat, rank: rv(log.card), suit: log.card.suit }; + this.lastProgressMs = this.playMs; + this.floatText(this.L.foundations[log.fIdx], '+1', SEAT_HEX[seat]); + if (seat === 0) playSound(this, SFX.CARD_PLACE); + else playSoundEx(this, SFX.CARD_PLACE, { volume: 0.5 }); + if (isFoundationComplete(this.gs, log.fIdx)) this.time.delayedCall(280, () => playSoundEx(this, SFX.UI_CHIME, { volume: 0.5 })); + } else { + if (log.source.type === 'nerts') this.lastProgressMs = this.playMs; + if (seat === 0) playSound(this, SFX.CARD_PLACE); + else playSoundEx(this, SFX.CARD_PLACE, { volume: 0.3 }); + } + if (seat === 0) { this.lastHumanMs = this.playMs; this.clearHint(); } + if (this.lastProgressMs === this.playMs) this.hideStall(); + if (carry) { + // the moved card(s) travel with the AI's hand, at its speed + const ids = new Set(log.type === 'foundation' ? [log.card.id] : log.cards.map(c => c.id)); + this.layout({ durationFor: (v) => (ids.has(v.card.id) ? carry : null) }); + } else { + this.layout(); + } + this.checkEnd(); } checkEnd() { - if (this.roundEnding) return true; + if (this.mode !== 'playing') return true; if (this.gs.nertsCaller !== null || allStuck(this.gs)) { this.finishRound(); return true; @@ -427,543 +630,953 @@ export default class NertsGame extends Phaser.Scene { return false; } - finishRound() { - this.roundEnding = true; - this.stopAITimers(); - if (this.lastMoveTimer) { this.lastMoveTimer.remove(false); this.lastMoveTimer = null; } - this.shuffleBtn?.setVisible(false); - this.resignBtn?.setVisible(false); - this._clearDrag(); - - const summary = endRound(this.gs); - this.totals = this.gs.players.map((p) => p.totalScore); - this.renderAll(); - - const winner = this.gs.winner; - if (this.gs.phase === 'matchover') { - const youWon = this.gs.matchWinner === 0; - this.recordHistory(youWon); + // ── Layout: put every card where the state says it is ────────────────────── + computeLayout() { + const L = this.L, gs = this.gs; + const visible = new Map(); // id → view + const loc = new Map(); // id → { pose, faceUp, depth } for every card + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + for (const p of gs.players) { + const seat = p.seat; + // nerts: top face up, the rest hidden underneath + const nn = p.nerts.length; + p.nerts.forEach((card, i) => { + const pose = cardPose(L, seat, 'nerts', 0, nn - 1, nn); + if (i === nn - 1) put(card, { seat, kind: 'nerts', idx: 0, pose, faceUp: true, depth: D.cards + 0.5 }); + else loc.set(card.id, { pose, faceUp: false, depth: D.cards }); + }); + // work piles: all face up, fanned + p.work.forEach((pile, w) => { + pile.forEach((card, i) => { + put(card, { seat, kind: 'work', idx: w, pose: cardPose(L, seat, 'work', w, i, pile.length), faceUp: true, depth: D.cards + i * 0.01 }); + }); + }); + // stock: only the top back is a sprite + const sn = p.stockDraw.length; + p.stockDraw.forEach((card, i) => { + const pose = cardPose(L, seat, 'stock', 0, sn - 1, sn); + if (i === sn - 1) put(card, { seat, kind: 'stock', idx: 0, pose, faceUp: false, depth: D.cards + 0.5 }); + else loc.set(card.id, { pose, faceUp: false, depth: D.cards }); + }); + // waste: the last three show + const wn = p.stockWaste.length; + p.stockWaste.forEach((card, i) => { + const pose = cardPose(L, seat, 'waste', 0, i, wn); + if (i >= wn - 3) put(card, { seat, kind: 'waste', idx: 0, pose, faceUp: true, depth: D.cards + 0.1 + i * 0.01 }); + else loc.set(card.id, { pose, faceUp: true, depth: D.cards }); + }); } - // Portrait reactions - for (let s = 1; s < this.playerCount; s++) { - this.opponentPortraits[s]?.playEmotion?.(winner === s ? 'happy' : 'upset'); + gs.foundations.forEach((slot, f) => { + if (!slot) return; + const n = slot.cards.length; + const complete = foundationTopRank(slot) >= 13; + const base = foundationPose(L, f, n); + slot.cards.forEach((card, i) => { + if (i === n - 1) { + const pose = complete ? { ...base, s: base.s * 0.94, rot: (f % 2 ? 0.05 : -0.04) } : base; + put(card, { seat: -1, kind: 'foundation', idx: f, pose, faceUp: !complete, depth: D.cards + 0.6, tab: true }); + } else { + loc.set(card.id, { pose: base, faceUp: true, depth: D.cards }); + } + }); + }); + return { visible, loc }; + } + + layout({ slabs = true, delayFor = null, duration = 260, durationFor = null } = {}) { + if (!this.gs) return; + 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); + } + if (this.dragIds.has(id)) continue; + c.tab.setVisible(!!v.tab && v.faceUp); + 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); + } } - playSound(this, winner === 0 ? SFX.CASINO_WIN : SFX.CARD_PLACE); - - this.showRoundPanel(summary); - } - - // ── Rendering ──────────────────────────────────────────────────────────── - - renderAll() { - this.renderLocal(); - this.renderFoundations(); - this.renderOpponents(); - } - - clearLocalCards() { - for (const c of this.localCardObjs.values()) c.destroy(); - this.localCardObjs.clear(); - for (const o of this.localExtraObjs) o.destroy(); - this.localExtraObjs = []; - } - - renderLocal() { - this.clearLocalCards(); - const p = this.gs.players[0]; - - // Nerts pile: fan left-to-right so card count is visible; top card face-up and draggable. - p.nerts.forEach((card, i) => { - const x = NERTS_POS.x - (p.nerts.length - 1 - i) * NERTS_FAN; - const isTop = i === p.nerts.length - 1; - if (isTop) { - const c = this.makeCardSprite(card, x, NERTS_POS.y, { faceUp: true }); - this.makeDraggable(c, { kind: 'nerts' }); + for (const [id, c] of this.sprites) { + if (visible.has(id)) continue; + this.sprites.delete(id); + this.dragIds.delete(id); + const to = loc.get(id); + if (to) { + c.tab.setVisible(false); + this.tweenCard(c, to.pose, { faceUp: to.faceUp, depth: to.depth - 0.005, duration, onDone: () => c.destroy() }); } else { - this.localExtraObjs.push( - this.makeCardSprite(card, x, NERTS_POS.y, { faceUp: false, store: false }) - ); + c._tw?.stop(); + c.destroy(); } + } + this.lastLoc = loc; + if (slabs) this.drawSlabs(); + this.updateHUD(); + } + + // Stack thickness for the piles that sit squared up (nerts, stock, foundations). + drawSlabs() { + const g = this.slabG; + g.clear(); + const stack = (base, n, k) => { + if (n <= 1) return; + const lift = stackLift(n, k); + const layers = Math.max(1, Math.min(6, Math.ceil(lift / 1.5))); + for (let j = 0; j < layers; j++) { + const corners = cardCorners({ ...base, y: base.y - (lift * j) / layers }); + g.fillStyle(j % 2 ? 0xe6dfca : 0xcfc6ae, 1); + g.fillPoints(corners, true); + g.lineStyle(1, 0x000000, 0.28); + g.strokePoints(corners, true); + } + }; + for (const p of this.gs.players) { + const k = this.L.seats[p.seat].k; + stack(pileBase(this.L, p.seat, 'nerts'), p.nerts.length, k); + stack(pileBase(this.L, p.seat, 'stock'), p.stockDraw.length, k); + } + this.gs.foundations.forEach((slot, f) => { + if (slot) stack(this.L.foundations[f], slot.cards.length, this.L.foundations[f].s); }); - this.localNertsText.setText(`${p.nerts.length} left`); - - // Work piles: fan downward; cards starting a valid run are draggable. - for (let i = 0; i < WORK_PILE_COUNT; i++) { - const pile = p.work[i]; - for (let k = 0; k < pile.length; k++) { - const card = pile[k]; - const x = WORK_X[i]; - const y = WORK_TOP_Y + k * FAN_Y; - const c = this.makeCardSprite(card, x, y, { faceUp: true }); - if (validRunFromIndex(pile, k)) this.makeDraggable(c, { kind: 'work', idx: i, k }); - } - } - - // Stock (face-down) + count. - if (p.stockDraw.length > 0) { - this.localExtraObjs.push( - this.makeCardSprite({ id: 'stock-back' }, STOCK_POS.x, STOCK_POS.y, { faceUp: false, store: false }) - ); - } - this.localStockText.setText( - p.stockDraw.length > 0 ? `${p.stockDraw.length} (click to flip 3)` : 'click to recycle' - ); - - // Waste: show up to the last 3, fanned right; top is draggable. - const wasteShown = p.stockWaste.slice(-3); - wasteShown.forEach((card, i) => { - const x = WASTE_POS.x + i * WASTE_FAN; - const isTop = i === wasteShown.length - 1; - const c = this.makeCardSprite(card, x, WASTE_POS.y, { faceUp: true }); - if (isTop) this.makeDraggable(c, { kind: 'waste' }); - }); - - this.localScoreText.setText(`Score: ${this.gs.players[0].totalScore}`); + const h = this.gs.players[0]; + this.recycleTxt.setVisible(h.stockDraw.length === 0 && h.stockWaste.length > 0); } - renderFoundations() { - for (const c of this.foundationCardObjs) c.destroy(); - this.foundationCardObjs = []; - for (let idx = 0; idx < this.gs.foundations.length; idx++) { - const slot = this.gs.foundations[idx]; - const complete = slot && slot.cards.length > 0 && slot.cards[slot.cards.length - 1].rank === 'K'; - this.foundationSlotRects[idx]?.setFillStyle(complete ? 0x111111 : 0x000000, complete ? 0.5 : 0.22); - const empty = !slot || slot.cards.length === 0; - this.foundationHints[idx]?.bg.setVisible(empty); - this.foundationHints[idx]?.label.setVisible(empty); - if (empty) continue; - const top = slot.cards[slot.cards.length - 1]; - const pos = this.foundationPos[idx]; - const c = this.makeCardSprite(top, pos.x, pos.y, { - faceUp: true, rim: SEAT_COLORS[top.owner], store: false, - }); - if (complete) c.setAlpha(0.4); - this.foundationCardObjs.push(c); + updateHUD() { + if (!this.gs) return; + const live = liveFoundationCounts(this.gs); + for (let seat = 0; seat < this.playerCount; seat++) { + const pl = this.plates[seat]; + pl.totalTxt.setText(`Total ${this.totals[seat]}`); + pl.liveTxt.setText(`+${live[seat]}`); + const n = this.gs.players[seat].nerts.length; + const b = this.badges[seat]; + b.t.setText(String(n)); + b.t.setColor(n <= 3 ? '#ffb15a' : COLORS.textHex); + if (n <= 3 && n > 0 && !b.glowTw) { + b.glow.setAlpha(0.5); + b.glowTw = this.tweens.add({ targets: b.glow, alpha: 0.05, scale: 1.25, duration: 520, yoyo: true, repeat: -1 }); + } else if ((n > 3 || n === 0) && b.glowTw) { + b.glowTw.stop(); b.glowTw = null; b.glow.setAlpha(0).setScale(1); + } + if (n < b.last && this.mode === 'playing') { + this.tweens.add({ targets: b.c, scale: 1.25, duration: 90, yoyo: true }); + } + b.last = n; + // pressure: an opponent about to go out + const danger = seat > 0 && n <= 2 && this.mode === 'playing'; + if (danger && !pl.pulse) { + pl.pulse = this.tweens.add({ targets: pl.bg, scale: 1.06, duration: 380, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + } else if (!danger && pl.pulse) { + pl.pulse.stop(); pl.pulse = null; pl.bg.setScale(1); + } } } - renderOpponents() { - for (let seat = 1; seat < this.playerCount; seat++) { - const dyn = this.oppDynamic[seat]; - if (!dyn) continue; - dyn.nertsText.setText(`Nerts: ${this.gs.players[seat].nerts.length}`); - dyn.scoreText.setText(`Score: ${this.gs.players[seat].totalScore}`); - - if (dyn.nertsCard) { dyn.nertsCard.destroy(); dyn.nertsCard = null; } - if (dyn.stockCard) { dyn.stockCard.destroy(); dyn.stockCard = null; } - for (const wc of dyn.wasteCards) wc.destroy(); - dyn.wasteCards = []; - - const { x: px, y: py } = dyn.panelPos; - const cardX = px + PANEL_W / 2 + 20 - CARD_W * 0.35; - const cardY = py + PANEL_H / 2 + 20 - CARD_H * 0.35; - - // Nerts top card (scale 0.7) - const top = nertsTop(this.gs, seat); - if (top) { - dyn.nertsCard = this.makeCardSprite(top, cardX, cardY, { - faceUp: true, rim: SEAT_COLORS[seat] ?? null, store: false, - }).setScale(0.7).setDepth(D.panel + 2); - } - - // Stock + waste above the nerts card (scale 0.55) - const SMALL = 0.55; - const smallHalfW = CARD_W * SMALL / 2; - const smallHalfH = CARD_H * SMALL / 2; - const stockX = cardX + CARD_W * 0.35 - smallHalfW; - const stockY = cardY - CARD_H * 0.35 - smallHalfH - 6; - - if (this.gs.players[seat].stockDraw.length > 0) { - dyn.stockCard = this.makeCardSprite({ id: `opp-stock-${seat}` }, stockX, stockY, { - faceUp: false, store: false, - }).setScale(SMALL).setDepth(D.panel + 2); - } - - const wasteShown = this.gs.players[seat].stockWaste.slice(-3); - const wasteBaseX = stockX + smallHalfW * 2 + 4; - wasteShown.forEach((card, i) => { - const wc = this.makeCardSprite(card, wasteBaseX + i * WASTE_FAN * SMALL, stockY, { - faceUp: true, rim: SEAT_COLORS[seat] ?? null, store: false, - }).setScale(SMALL).setDepth(D.panel + 2 + i); - dyn.wasteCards.push(wc); - }); - } - } - - // ── Card sprites ───────────────────────────────────────────────────────── - - makeCardSprite(card, x, y, { faceUp = true, rim = null, store = true } = {}) { - const c = this.add.container(x, y).setDepth(D.card); - this.renderCardFace(c, card, faceUp, rim); - c.card = card; - c.homeX = x; - c.homeY = y; - if (store && card && card.id !== undefined) this.localCardObjs.set(card.id, c); + // ── Card sprites ───────────────────────────────────────────────────────────── + makeCard(card, faceUp, pose) { + const skin = this.skins[card.owner] ?? this.skins[0]; + const c = skin.make(card, faceUp, pose.x, pose.y, pose.s, pose.rot); + const tab = this.add.image(CARD_W / 2 - 10, -CARD_H / 2 + 10, 'nerts-tab') + .setScale(0.55).setTint(SEAT_COLORS[card.owner] ?? 0xffffff).setVisible(false); + c.add(tab); + c.tab = tab; + c.skin = skin; + this.applyPose(c, pose); return c; } - renderCardFace(container, card, faceUp, rim) { - container.removeAll(true); - const x = -CARD_W / 2, y = -CARD_H / 2; - - if (!faceUp) { - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - container.add(this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H).setOrigin(0.5)); - } else { - const g = this.add.graphics(); - const color = this.cardBack?.fallbackColor - ? parseInt(this.cardBack.fallbackColor.replace('#', ''), 16) : 0x1a3a6b; - g.fillStyle(color, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, COLORS.accent, 0.6); - g.strokeRoundedRect(x + 6, y + 6, CARD_W - 12, CARD_H - 12, CARD_R - 2); - container.add(g); - } - const edge = this.add.graphics(); - edge.lineStyle(1.5, 0xffffff, 0.28); - edge.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - container.add(edge); - return; + // Place a card container at a pose. `lift` (0..1) raises it toward the + // camera; the drop shadow always falls screen-down-right whatever the rotation. + applyPose(c, pose, lift = 0, extraScale = 1) { + const { sx, sy } = poseScale(pose.s, pose.rot); + const grow = (1 + 0.08 * lift) * extraScale; + 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); } - - const g = this.add.graphics(); - g.fillStyle(0xfbf6e7, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(rim ? 4 : 2, rim ?? 0xcc803a, rim ? 1 : 0.5); - g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - - const colorHex = card.isRed ? '#c0392b' : '#1a1208'; - const label = card.label; - const sym = card.suitSymbol; - container.add(this.add.text(x + 7, y + 5, label, { - fontFamily: 'Righteous', fontSize: '20px', color: colorHex, - })); - container.add(this.add.text(x + 8, y + 28, sym, { - fontFamily: 'sans-serif', fontSize: '18px', color: colorHex, - })); - container.add(this.add.text(0, 4, sym, { - fontFamily: 'sans-serif', fontSize: '40px', color: colorHex, - }).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 5, label, { - fontFamily: 'Righteous', fontSize: '20px', color: colorHex, - }).setOrigin(1, 1)); } - makeDraggable(container, descriptor) { - container.setInteractive( - new Phaser.Geom.Rectangle(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H), - Phaser.Geom.Rectangle.Contains - ); - container.input.cursor = 'grab'; - container.on('pointerdown', (pointer) => this.onCardDown(descriptor, container, pointer)); - } - - /** A short throwaway sprite that flies from->to for AI foundation plays. */ - spawnFly(card, fromX, fromY, toX, toY, ownerSeat) { - const c = this.add.container(fromX, fromY).setDepth(D.fly); - this.renderCardFace(c, card, true, SEAT_COLORS[ownerSeat]); - c.setScale(0.7); - this.tweens.add({ - targets: c, x: toX, y: toY, scale: 1, duration: 300, ease: 'Cubic.easeOut', - onComplete: () => c.destroy(), + tweenCard(c, to, { faceUp, depth, duration = 260, delay = 0, onDone, lift = 0.55 } = {}) { + c._tw?.stop(); + const from = c.pose ?? to; + const flip = faceUp !== undefined && faceUp !== c.faceUp; + const dist = Math.hypot(to.x - from.x, to.y - from.y); + const liftAmt = dist > 12 ? lift : 0.15; + const prox = { t: 0 }; + let flipped = false; + let started = false; + c._tw = this.tweens.add({ + targets: prox, t: 1, duration, delay, ease: 'Cubic.easeOut', + onUpdate: () => { + if (!started) { started = true; c.setDepth(D.fly + (depth ?? D.cards) * 0.01); } + const t = prox.t; + const up = Math.sin(Math.PI * t) * liftAmt; + const pose = { + x: lerp(from.x, to.x, t), y: lerp(from.y, to.y, t), + rot: lerpAngle(from.rot, to.rot, t), s: lerp(from.s, to.s, t), + }; + this.applyPose(c, pose, up); + if (flip) { + if (!flipped && t >= 0.5) { flipped = true; c.skin.setFace(c, faceUp); } + c.scaleX *= Math.max(0.03, Math.abs(Math.cos(Math.PI * t))); + } + }, + onComplete: () => { + c._tw = null; + if (flip && !flipped) c.skin.setFace(c, faceUp); + this.applyPose(c, to); + if (depth !== undefined) c.setDepth(depth); + onDone?.(); + }, }); } - // ── Local input: stock / drag-drop ─────────────────────────────────────── - - isPlayable() { - return this.gs && this.gs.phase === 'playing' && !this.roundEnding; + // ── Effects ───────────────────────────────────────────────────────────────── + floatText(at, text, color, { size = 30, rise = 46, ms = 760 } = {}) { + 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, duration: ms, ease: 'Cubic.easeOut', onComplete: () => t.destroy() }); } - onStockClick() { - if (!this.isPlayable() || this.dragState) return; - const log = flipStock(this.gs, 0); - if (log) { - playSound(this, log.type === 'recycle' ? SFX.CARD_SHUFFLE : SFX.CARD_SHOW); - this.renderLocal(); + puff(at, color = 0xf2ead8) { + for (let i = 0; i < 7; i++) { + const a = (i / 7) * Math.PI * 2 + Math.random() * 0.4; + const d = this.add.circle(at.x, at.y, 7 + Math.random() * 5, color, 0.7).setDepth(D.float); + this.tweens.add({ + targets: d, x: at.x + Math.cos(a) * 46, y: at.y + Math.sin(a) * 34, scale: 1.8, alpha: 0, + duration: 420, ease: 'Cubic.easeOut', onComplete: () => d.destroy(), + }); } } - onCardDown(descriptor, container, pointer) { - if (!this.isPlayable() || this.dragState) return; - const sprites = this.dragSpritesFor(descriptor); - if (sprites.length === 0) return; - this.potentialDrag = { - descriptor, - sprites: sprites.map((obj) => ({ obj, offX: obj.x - pointer.x, offY: obj.y - pointer.y })), - startX: pointer.x, startY: pointer.y, - }; + tooSlow(fIdx, seat, card) { + const at = this.L.foundations[fIdx]; + this.puff(at); + this.floatText(at, seat === 0 ? 'Too slow!' : 'Beat them!', seat === 0 ? '#ff8a7a' : SEAT_HEX[0], { size: 26, rise: 40, ms: 900 }); + // the beaten card hops in place + const c = card && this.sprites.get(card.id); + if (c && seat !== 0 && !c._tw) { + const p = c.pose; + this.tweenCard(c, p, { duration: 300, lift: 0.9 }); + } + playSoundEx(this, SFX.CARD_SHOW, { volume: 0.4, rate: 1.3 }); } - dragSpritesFor(descriptor) { - if (descriptor.kind === 'nerts') { - const c = nertsTop(this.gs, 0); - return c ? [this.localCardObjs.get(c.id)].filter(Boolean) : []; + // ── Human input ────────────────────────────────────────────────────────────── + setupInput() { + this.input.on('pointerdown', (p) => this.onPointerDown(p)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + const kb = this.input.keyboard; + if (kb) { + kb.addCapture('SPACE'); + kb.on('keydown', (e) => this.onKey(e)); } - if (descriptor.kind === 'waste') { - const c = wasteTop(this.gs, 0); - return c ? [this.localCardObjs.get(c.id)].filter(Boolean) : []; + } + + isDraggable(hit) { + if (!hit) return false; + const p = this.gs.players[0]; + if (hit.kind === 'nerts') return p.nerts.length > 0; + if (hit.kind === 'waste') return p.stockWaste.length > 0; + if (hit.kind === 'work') return hit.k >= 0 && validRunFromIndex(p.work[hit.idx], hit.k); + return false; + } + + onPointerDown(pointer) { + if (!this.canAct() || this.dragState || !this.gs) return; + const hit = humanHit(this.L, this.gs.players[0], pointer); + if (!hit) return; + if (hit.kind === 'stock') { this.onStockClick(); return; } + if (!this.isDraggable(hit)) { + // a buried work card: nudge it so the click reads as "can't move that" + if (hit.kind === 'work' && hit.k >= 0) this.nudge(this.gs.players[0].work[hit.idx][hit.k]); + return; } - if (descriptor.kind === 'work') { - const pile = this.gs.players[0].work[descriptor.idx]; - return pile.slice(descriptor.k).map((card) => this.localCardObjs.get(card.id)).filter(Boolean); + const ids = this.idsFor(hit); + const sprites = ids.map(id => this.sprites.get(id)).filter(Boolean); + if (!sprites.length) return; + this.potentialDrag = { hit, sprites, startX: pointer.x, startY: pointer.y }; + } + + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.startX, dy = pointer.y - this.potentialDrag.startY; + if (dx * dx + dy * dy > 64) this.promoteDrag(pointer); + return; } + if (!pointer.isDown && this.gs && this.canAct()) { + const hit = humanHit(this.L, this.gs.players[0], pointer); + this.input.setDefaultCursor(hit?.kind === 'stock' ? 'pointer' : this.isDraggable(hit) ? 'grab' : 'default'); + } + } + + onPointerUp() { + if (this.dragState) { this.endDrag(); return; } + if (this.potentialDrag) { + const pd = this.potentialDrag; + this.potentialDrag = null; + if (this.canAct()) this.smartPlay(pd.hit); + } + } + + idsFor(hit) { + const p = this.gs.players[0]; + if (hit.kind === 'nerts') return [nertsTop(this.gs, 0)?.id]; + if (hit.kind === 'waste') return [wasteTop(this.gs, 0)?.id]; + if (hit.kind === 'work') return p.work[hit.idx].slice(hit.k).map(c => c.id); return []; } - startFoundationPulse(card) { - if (!card || card.rank !== 'A') return; - for (let f = 0; f < this.foundationPos.length; f++) { - if (!canPlayOnFoundation(this.gs, card, f)) continue; - const { x, y } = this.foundationPos[f]; - const rect = this.add.rectangle(x, y, CARD_W + 18, CARD_H + 18, 0xffd700, 0.55) - .setStrokeStyle(3, 0xffd700, 1).setDepth(D.card - 1).setAlpha(0.55); - const tween = this.tweens.add({ - targets: rect, alpha: 0.15, duration: 520, ease: 'Sine.easeInOut', yoyo: true, repeat: -1, - }); - this.foundationPulseObjs.push({ rect, tween }); + sourceFor(hit) { + if (hit.kind === 'nerts') return { type: 'nerts' }; + if (hit.kind === 'waste') return { type: 'waste' }; + const pile = this.gs.players[0].work[hit.idx]; + return { type: 'work', idx: hit.idx, count: pile.length - hit.k }; + } + + legalTargets(hit) { + const src = this.sourceFor(hit); + const card = this.sourceCard(0, src); + if (!card) return []; + const out = []; + if ((src.count ?? 1) === 1) { + for (let f = 0; f < this.gs.foundations.length; f++) { + if (canPlayOnFoundation(this.gs, card, f)) out.push({ type: 'foundation', idx: f }); + } } + for (let w = 0; w < 4; w++) { + if (hit.kind === 'work' && hit.idx === w) continue; + const empty = this.gs.players[0].work[w].length === 0; + if (empty && hit.kind === 'work' && hit.k === 0) continue; // pointless: whole pile to an empty pile + if (canPlayOnWork(this.gs, 0, card, w)) out.push({ type: 'work', idx: w }); + } + return out; } - stopFoundationPulse() { - for (const { rect, tween } of this.foundationPulseObjs) { tween.stop(); rect.destroy(); } - this.foundationPulseObjs = []; - } - - setupDragHandlers() { - this.input.on('pointermove', (pointer) => { - if (!pointer.isDown) return; - if (this.dragState) { - this.updateDrag(pointer); - } else if (this.potentialDrag) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (dx * dx + dy * dy > 64) this.promoteDrag(); - } - }); - this.input.on('pointerup', () => { - if (this.dragState) this.endDrag(); - else if (this.potentialDrag) { - const pd = this.potentialDrag; - this.potentialDrag = null; - this.onCardClick(pd.descriptor); // tap = try auto-play to a foundation - } - }); - } - - promoteDrag() { + promoteDrag(pointer) { const pd = this.potentialDrag; this.potentialDrag = null; - pd.sprites.forEach(({ obj }, i) => { - obj.setDepth(D.drag + i); - this.tweens.add({ targets: obj, scaleX: 1.06, scaleY: 1.06, duration: 90 }); + pd.sprites.forEach((c, i) => { + c._tw?.stop(); + c._tw = null; + this.dragIds.add(c.card.id); + c.setDepth(D.drag + i * 0.01); }); - this.dragState = pd; - const dragCard = pd.descriptor.kind === 'nerts' ? nertsTop(this.gs, 0) - : pd.descriptor.kind === 'waste' ? wasteTop(this.gs, 0) - : workTop(this.gs, 0, pd.descriptor.idx); - this.startFoundationPulse(dragCard); + const first = pd.sprites[0]; + this.dragState = { + hit: pd.hit, + sprites: pd.sprites, + offX: first.pose.x - pd.startX, + offY: first.pose.y - pd.startY, + legal: this.legalTargets(pd.hit), + }; + this.input.setDefaultCursor('grabbing'); + this.clearHint(); + this.updateDrag(pointer); } updateDrag(pointer) { - for (const { obj, offX, offY } of this.dragState.sprites) { - obj.x = pointer.x + offX; - obj.y = pointer.y + offY; - } - const primary = this.dragState.sprites[0].obj; - this.updateDropHighlight(this.getDropTargetAt(primary.x, primary.y)); + const ds = this.dragState; + ds.legal = this.legalTargets(ds.hit); // the middle changes under you in real time + const x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const s = dragScale(this.L, y); + const step = fanStep(this.L.seats[0].tpl, ds.sprites.length) * (s / this.L.seats[0].k); + ds.sprites.forEach((c, i) => { + this.applyPose(c, { x, y: y + i * step, rot: 0, s }, 1); + }); + ds.at = { x, y }; + ds.target = dropTargetAt(this.L, this.gs.players[0], ds.at, ds.legal); + this.drawTargets(ds.legal, ds.target); } - getDropTargetAt(x, y) { - for (let f = 0; f < this.foundationPos.length; f++) { - const pos = this.foundationPos[f]; - if (Math.abs(x - pos.x) < CARD_W * 0.7 && Math.abs(y - pos.y) < CARD_H * 0.7) { - return { type: 'foundation', idx: f }; - } + drawTargets(legal, hover) { + const g = this.targetG; + g.clear(); + for (const t of legal) { + const p = targetPose(this.L, this.gs.players[0], t); + const isHover = hover && hover.type === t.type && hover.idx === t.idx; + const color = t.type === 'foundation' ? 0xffd35a : 0x6cc4ff; + const pad = isHover ? 10 : 5; + const hw = (CARD_W / 2) * p.s + pad, hh = (CARD_H / 2) * p.s * SQ + pad; + g.fillStyle(color, isHover ? 0.22 : 0.08); + g.fillRoundedRect(p.x - hw, p.y - hh, hw * 2, hh * 2, 10); + g.lineStyle(isHover ? 4 : 2, color, isHover ? 1 : 0.7); + g.strokeRoundedRect(p.x - hw, p.y - hh, hw * 2, hh * 2, 10); } - if (y > WORK_TOP_Y - 70) { - for (let i = 0; i < WORK_PILE_COUNT; i++) { - if (Math.abs(x - WORK_X[i]) < CARD_W * 0.7) return { type: 'work', idx: i }; - } - } - return null; - } - - updateDropHighlight(target) { - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } - if (!target) return; - const pos = target.type === 'foundation' ? this.foundationPos[target.idx] - : { x: WORK_X[target.idx], y: WORK_TOP_Y }; - const color = target.type === 'foundation' ? 0xffd700 : 0x4dabf7; - this.dropHighlight = this.add.rectangle(pos.x, pos.y, CARD_W + 16, CARD_H + 16, color, 0.18) - .setStrokeStyle(3, color, 0.9).setDepth(D.card - 1); } endDrag() { const ds = this.dragState; this.dragState = null; - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } - this.stopFoundationPulse(); - - const primary = ds.sprites[0].obj; - const target = this.getDropTargetAt(primary.x, primary.y); - const committed = target ? this.commitDrop(ds.descriptor, target) : false; - // On success the sprites are torn down by the re-render; only animate them - // back home when the drop was rejected. - if (!committed) { - ds.sprites.forEach(({ obj }) => { - this.tweens.add({ - targets: obj, x: obj.homeX, y: obj.homeY, scaleX: 1, scaleY: 1, - duration: 240, ease: 'Back.easeOut', - }); - }); + this.targetG.clear(); + this.input.setDefaultCursor('default'); + for (const c of ds.sprites) this.dragIds.delete(c.card.id); + let ok = false; + if (this.canAct() && ds.target) ok = this.commit(ds.hit, ds.target); + if (!ok) { + if (this.canAct() && (this.sourceFor(ds.hit).count ?? 1) === 1) this.checkHumanRace(ds); + this.layout(); // slides the cards home from where they were dropped } } - sourceFor(descriptor) { - if (descriptor.kind === 'nerts') return { type: 'nerts' }; - if (descriptor.kind === 'waste') return { type: 'waste' }; - const pile = this.gs.players[0].work[descriptor.idx]; - return { type: 'work', idx: descriptor.idx, count: pile.length - descriptor.k }; + // Dropped on a foundation someone just filled with the very card you held? + checkHumanRace(ds) { + const card = this.sourceCard(0, this.sourceFor(ds.hit)); + if (!card || !ds.at) return; + this.L.foundations.forEach((f, idx) => { + if (!inPose(ds.at, f, 30)) return; + const ch = this.foundationChanged[idx]; + if (ch && ch.seat !== 0 && this.playMs - ch.at < RACE_WINDOW_MS && ch.suit === card.suit && ch.rank === rv(card)) { + this.tooSlow(idx, 0, card); + } + }); } - commitDrop(descriptor, target) { - const source = this.sourceFor(descriptor); + commit(hit, target) { + const src = this.sourceFor(hit); let log = null; if (target.type === 'foundation') { - if ((source.count ?? 1) > 1) return false; // foundations take single cards only - log = playToFoundation(this.gs, 0, source, target.idx); - if (log) { this.markFoundationCooldown(target.idx); this.resetLastMoveTimer(); } + if ((src.count ?? 1) > 1) return false; + log = playToFoundation(this.gs, 0, src, target.idx); } else { - log = playToWork(this.gs, 0, source, target.idx); - if (log && source.type === 'nerts') this.resetLastMoveTimer(); + log = playToWork(this.gs, 0, src, target.idx); } if (!log) return false; - playSound(this, SFX.CARD_PLACE); - this.afterLocalMove(); + this.afterMove(0, log); return true; } - onCardClick(descriptor) { - if (!this.isPlayable()) return; - // Tap = try to play the single top card onto the first legal foundation. - if (descriptor.kind === 'work') { - const pile = this.gs.players[0].work[descriptor.idx]; - if (descriptor.k !== pile.length - 1) return; // only the visible top can quick-play + // Click (or hotkey): foundation first, otherwise the best work pile. + smartPlay(hit, { allowRunFallback = false } = {}) { + if (!this.canAct() || !hit) return false; + const p = this.gs.players[0]; + if (hit.kind === 'work') { + const pile = p.work[hit.idx]; + if (!pile.length) return false; + if (hit.k === undefined || hit.k < 0) hit = { ...hit, k: pile.length - 1 }; } - const source = this.sourceFor(descriptor); - if ((source.count ?? 1) > 1) return; - const card = descriptor.kind === 'nerts' ? nertsTop(this.gs, 0) - : descriptor.kind === 'waste' ? wasteTop(this.gs, 0) - : workTop(this.gs, 0, descriptor.idx); - if (!card) return; - for (let f = 0; f < this.gs.foundations.length; f++) { - if (canPlayOnFoundation(this.gs, card, f)) { - if (playToFoundation(this.gs, 0, source, f)) { - this.markFoundationCooldown(f); - this.resetLastMoveTimer(); - playSound(this, SFX.CARD_PLACE); - this.afterLocalMove(); - } - return; + const legal = this.legalTargets(hit); + const found = legal.find(t => t.type === 'foundation'); + const work = legal.filter(t => t.type === 'work') + .sort((a, b) => (p.work[a.idx].length ? 0 : 1) - (p.work[b.idx].length ? 0 : 1)); + const target = found ?? work[0] ?? null; + if (target && this.commit(hit, target)) return true; + if (allowRunFallback && hit.kind === 'work') { + const k = maxRunStart(p.work[hit.idx]); + if (k < p.work[hit.idx].length - 1) return this.smartPlay({ ...hit, k }); + } + const cards = this.idsFor(hit); + const card = this.sprites.get(cards[0])?.card; + if (card) this.nudge(card); + return false; + } + + nudge(card) { + const c = card && this.sprites.get(card.id); + if (!c || c._tw || this.dragIds.has(card.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 }); + } + + onStockClick() { + if (!this.canAct()) return; + const log = flipStock(this.gs, 0); + if (!log) return; + playSound(this, log.type === 'recycle' ? SFX.CARD_SHUFFLE : SFX.CARD_SHOW); + this.lastHumanMs = this.playMs; + this.clearHint(); + this.layout({ duration: 230 }); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) this.togglePause(); + return; + } + if (!this.canAct() || this.dragState) return; + const k = e.key?.toLowerCase(); + if (e.code === 'Space') this.onStockClick(); + else if (k === 'n') this.smartPlay({ kind: 'nerts' }); + else if (k === 'w') this.smartPlay({ kind: 'waste' }); + else if (k >= '1' && k <= '4') this.smartPlay({ kind: 'work', idx: Number(k) - 1, k: -1 }, { allowRunFallback: true }); + else if (k === 'h') this.showHint(true); + } + + // ── Hints ─────────────────────────────────────────────────────────────────── + updateHint() { + if (!this.settings.hints || this.hint || this.dragState) return; + if (this.playMs - this.lastHumanMs > HINT_IDLE_MS) this.showHint(false); + } + + showHint(force) { + if (this.hint && !force) return; + this.clearHint(); + const play = rankedPlays(this.gs, 0)[0]; + const g = this.hintG; + let from, to = null; + if (play) { + from = this.sourcePose(0, play.source); + to = play.kind === 'foundation' ? this.L.foundations[play.dest] : targetPose(this.L, this.gs.players[0], { type: 'work', idx: play.dest }); + } else { + const n = this.gs.players[0].stockDraw.length; + from = cardPose(this.L, 0, 'stock', 0, Math.max(0, n - 1), Math.max(1, n)); + } + const ring = (p, color) => { + const hw = (CARD_W / 2) * p.s + 8, hh = (CARD_H / 2) * p.s * SQ + 8; + g.lineStyle(4, color, 1); + g.strokeRoundedRect(p.x - hw, p.y - hh, hw * 2, hh * 2, 12); + }; + ring(from, 0x7cf0a0); + if (to) ring(to, 0x7cf0a0); + g.setAlpha(1); + this.hint = { play, tw: this.tweens.add({ targets: g, alpha: 0.25, duration: 520, yoyo: true, repeat: -1 }) }; + this.lastHumanMs = this.playMs; + } + + clearHint() { + if (this.hint) { this.hint.tw.stop(); this.hint = null; } + this.hintG?.clear(); + } + + // ── Stalemate ─────────────────────────────────────────────────────────────── + // The stall clock runs from the last real progress (a foundation play or a + // card off a Nerts pile). Rotating stocks doesn't reset it, so a table that + // stays stuck still reaches "End round" — and, eventually, ends on its own. + updateStall() { + const idle = this.playMs - this.lastProgressMs; + if (idle >= STALL_PROMPT_MS && !this.stall.visible) { + this.stall.setVisible(true).setAlpha(0); + this.tweens.add({ targets: this.stall, alpha: 1, duration: 300 }); + this.hgSpin.resume(); + } + if (this.stall.visible) { + const secs = Math.floor(idle / 1000); + const late = idle >= STALL_END_MS; + const recent = this.playMs - this.lastRotateMs < ROTATE_GAP_MS; + this.stallTxt.setText(recent && !late ? `Stocks rotated · ${secs}s` : `Table stuck? ${secs}s`); + this.stallEndBtn.setVisible(late); + this.stallBtn.setVisible(!late); + if (this._stallBtnOn !== !recent) { this._stallBtnOn = !recent; this.stallBtn.setEnabled(!recent); } + } + if (idle >= STALL_AUTO_MS && this.playMs - this.lastRotateMs >= ROTATE_GAP_MS) this.rotateTable(true); + if (idle >= STALL_GIVE_UP_MS) this.finishRound(); + } + + hideStall() { + if (this.stall?.visible) { this.stall.setVisible(false); this.hgSpin.pause(); } + } + + rotateTable(auto) { + if (this.mode !== 'playing') return; + if (this.playMs - this.lastRotateMs < ROTATE_GAP_MS && !auto) return; + if (this.rotations === 0) rotateStocks(this.gs); + else reshuffleAllStocks(this.gs); + this.rotations += 1; + this.lastRotateMs = this.playMs; + for (const m of this.minds) if (m) noteOwnChange(m, this.playMs, 'flip'); // everyone re-reads their stock + playSound(this, SFX.CARD_SHUFFLE); + const who = auto && this.playerCount > 1 ? `${this.nameForSeat(1)}: "Let's rotate the stocks!"` : 'Stocks rotated — keep going!'; + this.floatText({ x: CX, y: this.L.foundations[0].y - 70 }, who, '#f2ead8', { size: 24, rise: 30, ms: 1800 }); + this.layout(); + } + + onEndRoundEarly() { + if (this.mode !== 'playing') return; + this.finishRound(); + } + + // ── Pause / modals ───────────────────────────────────────────────────────── + togglePause() { + if (this.modal) return; + if (this.mode === 'summary' || this.mode === 'ending') return; + this.openPause(); + } + + 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(); + if (this.dragState) this.endDrag(); + this.potentialDrag = null; + const objs = []; + const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62) + .setInteractive().setDepth(D.modal); + objs.push(overlay); + if (paper) { + const key = ensurePad(this, `nerts-pad-${w}x${h}`, w, h); + objs.push(this.add.image(CX, CY, key).setDepth(D.modal).setRotation(-0.01)); + } else { + const key = ensureLeatherPanel(this, `nerts-panel-${w}x${h}`, w, h, { radius: 18 }); + objs.push(this.add.image(CX, CY, key).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); + } + + openPause() { + const m = this.openModal({ w: 520, h: 360, onEscape: () => this.closeModal() }); + const title = this.add.text(CX, CY - 120, 'Paused', { + fontFamily: 'Righteous', fontSize: '48px', color: COLORS.goldHex, + }).setOrigin(0.5).setDepth(D.modal + 1); + this.addToModal(title); + this.addToModal(new Button(this, CX, CY - 30, 'Resume', () => this.closeModal(), { width: 280, height: 54, fontSize: 22 }).setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX, CY + 40, 'Settings', () => { this.closeModal(); this.openSettings(); }, { width: 280, height: 54, fontSize: 22 }).setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX, CY + 110, 'Leave game', () => this.scene.start('GameMenu'), { variant: 'ghost', width: 280, height: 54, fontSize: 22 }).setDepth(D.modal + 1)); + return m; + } + + onLeave() { + if (this.mode === 'summary' || this.history.length === 0 && this.mode !== 'playing') { + this.scene.start('GameMenu'); + return; + } + if (this.modal) this.closeModal(); + this.openModal({ w: 560, h: 280, onEscape: () => this.closeModal() }); + this.addToModal(this.add.text(CX, CY - 70, 'Leave this match?', { + fontFamily: 'Righteous', fontSize: '38px', color: COLORS.textHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX, CY - 22, 'Scores from this match will be lost.', { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX - 120, CY + 60, 'Leave', () => this.scene.start('GameMenu'), { width: 200, height: 52, fontSize: 21, variant: 'ghost' }).setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX + 120, CY + 60, 'Stay', () => this.closeModal(), { width: 200, height: 52, fontSize: 21 }).setDepth(D.modal + 1)); + } + + openSettings(onDone = null) { + const back = () => { this.closeModal(); onDone?.(); }; + this.openModal({ w: 700, h: 520, onEscape: back }); + const y0 = CY - 190; + this.addToModal(this.add.text(CX, y0, 'Table Settings', { + fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); + + const row = (y, label, options, current, apply) => { + this.addToModal(this.add.text(CX - 300, y, label, { + fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + const btns = []; + const bw = 112, gap = 10; + const startX = CX + 300 - options.length * bw - (options.length - 1) * gap + bw / 2; + options.forEach(([value, text], i) => { + const b = new Button(this, startX + i * (bw + gap), y, text, () => { + apply(value); + btns.forEach(([v, bb]) => bb.setActive(v === value)); + this.saveSettings(); + }, { width: bw, height: 42, fontSize: 16 }).setDepth(D.modal + 1); + b.setActive(value === current); + btns.push([value, b]); + this.addToModal(b); + }); + }; + row(y0 + 90, 'Play to', TARGETS.map(t => [t, String(t)]), this.settings.target, (v) => { + this.settings.target = v; + if (this.gs) this.gs.targetScore = v; + this.updateMiniPad(); + }); + row(y0 + 160, 'Stock draws', [[3, '3 cards'], [1, '1 card']], this.settings.draw, (v) => { + this.settings.draw = v; + if (this.gs) this.gs.drawCount = v; + }); + row(y0 + 230, 'Opponent pace', [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['frantic', 'Frantic']], this.settings.pace, (v) => { + this.settings.pace = v; + }); + row(y0 + 300, 'Idle hints', [[false, 'Off'], [true, 'On']], this.settings.hints, (v) => { + this.settings.hints = v; + if (!v) this.clearHint(); + }); + this.addToModal(this.add.text(CX, y0 + 350, '"Play to" changes take effect at the end of this round.', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX, y0 + 410, 'Done', back, { width: 220, height: 50, fontSize: 21 }).setDepth(D.modal + 1)); + } + + // ── End of round: NERTS! → count-back → score pad ────────────────────────── + async finishRound() { + if (this.mode !== 'playing') return; + this.mode = 'ending'; + this.stopAI(); + if (this.dragState) { + const ds = this.dragState; + this.dragState = null; + for (const c of ds.sprites) this.dragIds.delete(c.card.id); + this.targetG.clear(); + } + this.potentialDrag = null; + this.input.setDefaultCursor('default'); + this.clearHint(); + this.hideStall(); + for (let s = 1; s < this.playerCount; s++) this.handHome(s, 400); + this.layout(); + + const caller = this.gs.nertsCaller; + const summary = endRound(this.gs); + const winner = this.gs.winner; + + // stamp + table slap + const stampText = caller !== null ? 'NERTS!' : 'Time!'; + const sub = caller === null ? 'The table is stuck — count it up' + : caller === 0 ? 'You called it!' : `${this.nameForSeat(caller)} called it!`; + const color = caller !== null ? SEAT_HEX[caller] : '#f2ead8'; + const stamp = this.add.text(CX, CY - 40, stampText, { + fontFamily: 'Righteous', fontSize: '160px', color, stroke: '#120c06', strokeThickness: 14, + }).setOrigin(0.5).setDepth(D.stamp).setScale(3).setAlpha(0).setRotation(-0.08); + const subT = this.add.text(CX, CY + 70, sub, { + fontFamily: 'Righteous', fontSize: '36px', color: '#f2ead8', stroke: '#120c06', strokeThickness: 7, + }).setOrigin(0.5).setDepth(D.stamp).setAlpha(0); + this.fx.push(stamp, subT); + this.tweens.add({ + targets: stamp, scale: 1, alpha: 1, duration: 240, ease: 'Back.easeOut', + onComplete: () => { + this.cameras.main.shake(240, 0.007); + playSound(this, SFX.CARD_PLACE); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.6, rate: 1.4 }); + }, + }); + this.tweens.add({ targets: subT, alpha: 1, delay: 260, duration: 220 }); + for (let s = 1; s < this.playerCount; s++) { + this.portraits[s]?.playEmotion?.(winner === s ? 'happy' : 'upset'); + } + await this.wait(1300); + if (!this.alive()) return; + this.tweens.add({ targets: [stamp, subT], alpha: 0, duration: 260 }); + + await this.countBack(summary); + if (!this.alive()) return; + await this.penalties(summary); + if (!this.alive()) return; + await this.wait(700); + if (!this.alive()) return; + + this.totals = this.gs.players.map(p => p.totalScore); + this.history.push(summary); + this.updateMiniPad(); + this.updateHUD(); + if (this.gs.phase === 'matchover') this.recordHistory(this.gs.matchWinner === 0); + playSound(this, (this.gs.phase === 'matchover' ? this.gs.matchWinner : winner) === 0 ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + this.mode = 'summary'; + this.openScorePad({ summary }); + } + + async countBack(summary) { + const tallies = new Array(this.playerCount).fill(0); + for (let s = 0; s < this.playerCount; s++) { + const t = this.plates[s].tallyTxt; + t.setText('+0').setVisible(true).setAlpha(0); + this.tweens.add({ targets: t, alpha: 1, duration: 200 }); + } + // lift every foundation off the table, top card first, back to its owner + let longest = 0; + let ticks = 0; + this.gs.foundations.forEach((slot, f) => { + if (!slot) return; + const n = slot.cards.length; + for (let i = n - 1; i >= 0; i--) { + const card = slot.cards[i]; + const top = this.sprites.get(card.id); + if (top) { top._tw?.stop(); top.destroy(); this.sprites.delete(card.id); } + const from = foundationPose(this.L, f, i + 1); + const c = this.makeCard(card, true, from); + c.setDepth(D.cards + 0.6 + i * 0.001); + this.fx.push(c); + const pl = this.plates[card.owner]; + const to = { x: pl.x, y: pl.y, rot: 0, s: 0.45 }; + const delay = (n - 1 - i) * 75 + f * 12; + longest = Math.max(longest, delay + 440); + this.tweenCard(c, to, { + delay, duration: 440, lift: 0.8, onDone: () => { + c.destroy(); + tallies[card.owner] += 1; + const t = this.plates[card.owner].tallyTxt; + t.setText(`+${tallies[card.owner]}`); + this.tweens.add({ targets: t, scale: 1.18, duration: 60, yoyo: true }); + if ((ticks++ % 3) === 0) playSoundEx(this, SFX.CARD_PLACE, { volume: 0.35, rate: 1.1 }); + }, + }); + } + }); + this.slabG.clear(); + this.drawSlabsTableauOnly(); + await this.wait(longest + 250); + // guarantee the final numbers whatever the animation timing + summary.forEach(s => this.plates[s.seat].tallyTxt.setText(`+${s.founded}`)); + } + + drawSlabsTableauOnly() { + const saved = this.gs.foundations; + this.gs.foundations = saved.map(() => null); + this.drawSlabs(); + this.gs.foundations = saved; + } + + async penalties(summary) { + const losers = summary.filter(s => s.nertsLeft > 0); + if (!losers.length) return; + await this.wait(250); + let any = false; + for (const s of losers) { + const top = nertsTop(this.gs, s.seat); + const c = top && this.sprites.get(top.id); + if (c) c.faceImg.setTint(0xff9a8a); + const b = this.badges[s.seat]; + this.tweens.add({ targets: b.c, scale: 1.35, duration: 120, yoyo: true, repeat: 2 }); + const at = cardPose(this.L, s.seat, 'nerts', 0, 0, 1); + this.floatText(at, `−2 × ${s.nertsLeft}`, '#ff8a7a', { size: s.seat === 0 ? 30 : 24, rise: 36, ms: 1400 }); + const t = this.plates[s.seat].tallyTxt; + const steps = s.nertsLeft; + for (let i = 1; i <= steps; i++) { + this.time.delayedCall(i * 90, () => { + t.setText(`${s.founded - 2 * i >= 0 ? '+' : ''}${s.founded - 2 * i}`).setColor('#ff8a7a'); + }); + } + this.time.delayedCall(steps * 90 + 200, () => t.setColor(SEAT_HEX[s.seat])); + if (s.seat === 0) any = true; + } + if (any) playSoundEx(this, SFX.CASINO_LOSE, { volume: 0.5 }); + const longest = Math.max(...losers.map(s => s.nertsLeft)) * 90 + 500; + await this.wait(longest); + } + + // The paper score pad: round-by-round columns. Doubles as the round-end screen. + openScorePad({ summary = null, readOnly = false } = {}) { + const rows = this.playerCount; + const w = 860, h = 250 + rows * 58 + (readOnly ? 70 : 90); + const m = this.openModal({ w, h, paper: true, onEscape: readOnly ? () => this.closeModal() : null, freeze: readOnly }); + const font = '"YummyCupcakes", "Comic Sans MS", cursive'; + const top = CY - h / 2; + const left = CX - w / 2; + const ink = '#22201a', blue = '#1c3f8f', red = '#b8231f'; + const matchOver = this.gs?.phase === 'matchover' && !readOnly; + let title; + if (readOnly) title = `Score sheet — first to ${this.settings.target}`; + else if (matchOver) { + title = this.gs.matchWinner === 0 ? 'You win the match!' + : this.gs.matchWinner === -1 ? "It's a tie!" : `${this.nameForSeat(this.gs.matchWinner)} wins the match!`; + } else { + const wnr = this.gs.winner; + title = this.gs.nertsCaller === null ? `Round ${this.round} — stalled out` : wnr === 0 ? `Round ${this.round} — Nerts! You did it` : `Round ${this.round} — ${this.nameForSeat(wnr)} went out`; + } + this.addToModal(this.add.text(CX, top + 62, title, { + fontFamily: font, fontSize: '44px', color: (matchOver && this.gs.matchWinner === 0) ? red : ink, + }).setOrigin(0.5).setDepth(D.modal + 1)); + + const shown = this.history.slice(-5); + const firstRound = this.history.length - shown.length + 1; + const nameX = left + 150, colX0 = left + 400, colW = 74, totalX = left + w - 80; + const headY = top + 130; + this.addToModal(this.add.text(nameX, headY, 'Player', { fontFamily: font, fontSize: '24px', color: '#6c6450' }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + shown.forEach((_, i) => { + this.addToModal(this.add.text(colX0 + i * colW, headY, `R${firstRound + i}`, { + fontFamily: font, fontSize: '22px', color: '#6c6450', + }).setOrigin(0.5).setDepth(D.modal + 1)); + }); + this.addToModal(this.add.text(totalX, headY, 'Total', { fontFamily: font, fontSize: '24px', color: '#6c6450' }).setOrigin(0.5).setDepth(D.modal + 1)); + + const best = Math.max(...this.totals); + const writes = []; + for (let seat = 0; seat < rows; seat++) { + const y = headY + 56 + seat * 58; + this.addToModal(this.add.circle(nameX - 22, y, 8, SEAT_COLORS[seat]).setDepth(D.modal + 1)); + this.addToModal(this.add.text(nameX, y, this.nameForSeat(seat), { fontFamily: font, fontSize: '28px', color: ink }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + shown.forEach((sum, i) => { + const s = sum.find(x => x.seat === seat); + const isNew = summary && i === shown.length - 1; + const v = s.roundScore; + const t = this.add.text(colX0 + i * colW, y, `${v > 0 ? '+' : ''}${v}`, { + fontFamily: font, fontSize: '26px', color: v < 0 ? red : blue, + }).setOrigin(0.5).setDepth(D.modal + 1); + if (isNew) { t.setAlpha(0); writes.push(t); } + this.addToModal(t); + }); + const tot = this.add.text(totalX, y, String(this.totals[seat]), { + fontFamily: font, fontSize: '32px', color: this.totals[seat] === best && best > 0 ? red : ink, + }).setOrigin(0.5).setDepth(D.modal + 1); + if (summary) { tot.setAlpha(0); writes.push(tot); } + this.addToModal(tot); + if (seat === (matchOver ? this.gs.matchWinner : -99)) { + const ring = this.add.graphics().setDepth(D.modal + 1); + ring.lineStyle(3, 0xb8231f, 0.85); + ring.strokeEllipse(totalX, y, 92, 50); + this.addToModal(ring); } } - } - - afterLocalMove() { - this.renderLocal(); - this.renderFoundations(); - this.renderOpponents(); - this.checkEnd(); - } - - _clearDrag() { - if (this.dropHighlight) { this.dropHighlight.destroy(); this.dropHighlight = null; } - this.dragState = null; - this.potentialDrag = null; - } - - // ── Round / match summary panel ────────────────────────────────────────── - - showRoundPanel(summary) { - const matchOver = this.gs.phase === 'matchover'; - const winner = this.gs.winner; - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.68) - .setInteractive().setDepth(D.modal); - this.panelObjs.push(overlay); - - const panelW = 760; - const panelH = 120 + this.playerCount * 52 + 90; - const panel = this.add.rectangle(CX, CY, panelW, panelH, COLORS.panel, 1) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - this.panelObjs.push(panel); - - const title = matchOver - ? (this.gs.matchWinner === 0 ? 'You win the match!' - : this.gs.matchWinner === -1 ? "It's a tie!" - : `${this.nameForSeat(this.gs.matchWinner)} wins the match!`) - : (winner === 0 ? 'Nerts! You won the round' : `${this.nameForSeat(winner)} called Nerts!`); - const t = this.add.text(CX, CY - panelH / 2 + 44, title, { - fontFamily: 'Righteous', fontSize: '38px', - color: (matchOver ? this.gs.matchWinner : winner) === 0 ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal + 1); - this.panelObjs.push(t); - - // Scoreboard rows - const rowTop = CY - panelH / 2 + 96; - summary.forEach((s, i) => { - const y = rowTop + i * 52; - const name = this.nameForSeat(s.seat); - const deltaSign = s.roundScore >= 0 ? '+' : ''; - const line = `${name}: ${s.founded} on foundations, ${s.nertsLeft} left in Nerts (${deltaSign}${s.roundScore})`; - this.panelObjs.push(this.add.text(CX - panelW / 2 + 50, y, line, { - fontFamily: '"Julius Sans One"', fontSize: '20px', - color: s.seat === winner ? COLORS.accentHex : COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.modal + 1)); - this.panelObjs.push(this.add.text(CX + panelW / 2 - 50, y, `Total: ${s.totalScore}`, { - fontFamily: 'Righteous', fontSize: '22px', color: SEAT_COLOR_HEX[s.seat] ?? COLORS.textHex, - }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + // "write" the new numbers in, one after another + writes.forEach((t, i) => { + this.tweens.add({ targets: t, alpha: 1, delay: 250 + i * 180, duration: 160 }); }); + if (writes.length) this.time.delayedCall(250, () => playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.6 })); - const btnY = CY + panelH / 2 - 50; - if (matchOver) { - const b1 = new Button(this, CX - 130, btnY, 'Play again', () => this.restartMatch(), - { width: 220, fontSize: 22 }).setDepth(D.modal + 1); - this.panelObjs.push(b1); - } else { - const b1 = new Button(this, CX - 130, btnY, 'Next round', () => this.nextRound(), - { width: 220, fontSize: 22, bg: COLORS.accent, textColor: COLORS.textDarkHex }).setDepth(D.modal + 1); - this.panelObjs.push(b1); + const btnY = top + h - 58; + if (readOnly) { + this.addToModal(new Button(this, CX, btnY, 'Back to the table', () => this.closeModal(), { width: 300, height: 50, fontSize: 20 }).setDepth(D.modal + 1)); + return m; } - const b2 = new Button(this, CX + 130, btnY, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 220, fontSize: 22 }).setDepth(D.modal + 1); - this.panelObjs.push(b2); - } - - clearPanel() { - for (const o of this.panelObjs) o.destroy(); - this.panelObjs = []; + const next = matchOver + ? new Button(this, CX - 240, btnY, 'Play again', () => this.restartMatch(), { width: 220, height: 52, fontSize: 21 }) + : new Button(this, CX - 240, btnY, 'Next round', () => this.nextRound(), { width: 220, height: 52, fontSize: 21, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + this.addToModal(next.setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX, btnY, 'Settings', () => { this.closeModal(); this.openSettings(() => this.openScorePad({})); }, { width: 200, height: 52, fontSize: 20, variant: 'ghost' }).setDepth(D.modal + 1)); + this.addToModal(new Button(this, CX + 240, btnY, 'Leave', () => this.scene.start('GameMenu'), { width: 220, height: 52, fontSize: 21, variant: 'ghost' }).setDepth(D.modal + 1)); + m.onEscape = null; + return m; } nextRound() { - this.clearPanel(); + this.closeModal(); this.startRound(); } restartMatch() { + this.closeModal(); this.totals = new Array(this.playerCount).fill(0); - this.clearPanel(); + this.history = []; + this.round = 0; this.startRound(); } - nameForSeat(seat) { - if (seat === 0) return auth.user?.username ?? 'You'; - if (seat < 0) return 'Nobody'; - return this.opponents[seat - 1]?.name ?? `Player ${seat + 1}`; - } - async recordHistory(youWon) { try { await api.post('/history/single-player', { diff --git a/src/games/nerts/NertsLogic.js b/src/games/nerts/NertsLogic.js index 6ee4079..83e21c8 100644 --- a/src/games/nerts/NertsLogic.js +++ b/src/games/nerts/NertsLogic.js @@ -48,7 +48,7 @@ function isRed(card) { // ── State construction ──────────────────────────────────────────────────────── -export function createInitialState({ playerCount, targetScore = DEFAULT_TARGET_SCORE, totals = null } = {}) { +export function createInitialState({ playerCount, targetScore = DEFAULT_TARGET_SCORE, totals = null, drawCount = STOCK_FLIP } = {}) { if (playerCount < 2 || playerCount > 4) { throw new Error(`Nerts supports 2..4 players, got ${playerCount}`); } @@ -80,6 +80,7 @@ export function createInitialState({ playerCount, targetScore = DEFAULT_TARGET_S return { phase: 'playing', // 'playing' | 'roundover' | 'matchover' targetScore, + drawCount: drawCount === 1 ? 1 : STOCK_FLIP, // stock flips 3 (standard) or 1 (relaxed) // Fixed-length slot array. Each slot is null (empty — accepts an Ace) or a // foundation { suit, cards: [...] }. Max foundations = 4 suits × playerCount. foundations: new Array(4 * playerCount).fill(null), @@ -281,7 +282,7 @@ export function playToWork(state, seat, source, dstIdx) { return log; } -/** Flip up to STOCK_FLIP cards from draw to waste. +/** Flip up to drawCount (default STOCK_FLIP) cards from draw to waste. * If draw is empty, recycles waste back to draw and returns without dealing — * the player must click again to actually draw the next three cards. */ export function flipStock(state, seat) { @@ -292,7 +293,7 @@ export function flipStock(state, seat) { p.stockWaste = []; return { type: 'recycle', seat }; } - const n = Math.min(STOCK_FLIP, p.stockDraw.length); + const n = Math.min(state.drawCount ?? STOCK_FLIP, p.stockDraw.length); for (let i = 0; i < n; i++) p.stockWaste.push(p.stockDraw.pop()); return { type: 'flip', seat, n }; } @@ -349,6 +350,38 @@ export function endRound(state) { return summary; } +/** Cards each seat currently has on the shared foundations (the live "+N"). */ +export function liveFoundationCounts(state) { + const counts = new Array(state.players.length).fill(0); + for (const slot of state.foundations) { + if (!slot) continue; + for (const card of slot.cards) counts[card.owner] += 1; + } + return counts; +} + +/** A foundation slot that has been built all the way to its King. */ +export function isFoundationComplete(state, fIdx) { + const slot = state.foundations[fIdx]; + return !!slot && foundationTopRank(slot) >= 13; +} + +/** + * Stalemate house rule: every player gathers their stock (waste turned back + * over, in order) and moves the top card to the bottom, so the next pass + * through the stock groups different cards together. + */ +export function rotateStocks(state) { + for (const p of state.players) { + // The order cards would be drawn in from here on: the rest of the draw + // pile (top first), then the waste turned back over (oldest flip first). + const seq = [...p.stockDraw].reverse().concat(p.stockWaste); + if (seq.length > 1) seq.push(seq.shift()); + p.stockDraw = seq.reverse(); // last element = top of the face-down pile + p.stockWaste = []; + } +} + export function reshuffleAllStocks(state) { for (const p of state.players) { const combined = [...p.stockDraw, ...p.stockWaste]; diff --git a/src/games/nerts/NertsTable.js b/src/games/nerts/NertsTable.js new file mode 100644 index 0000000..945cbc2 --- /dev/null +++ b/src/games/nerts/NertsTable.js @@ -0,0 +1,321 @@ +// Nerts table layout — Phaser-free so tools/verifyNerts.js can test it. +// +// A home card table (rounded rectangle, wooden rim, felt top) seen in mild +// perspective from the human's chair, built on the shared casino projection +// (makeProjection). Everyone races on the shared foundations in the middle; +// each player's own tableau sits in front of them, turned toward its owner: +// +// 2 players human (near) · opponent straight across +// 3 players human · far-left corner · far-right corner +// 4 players human · left side · across · right side +// +// Logic seats fill clockwise from the human's left (seat 1 = left/far-left). +// +// Every tableau uses the same template in its owner's frame: x runs along the +// row (owner's left → right), y points toward the owner (work piles fan that +// way). A seat maps the template to the screen with an anchor, a rotation and +// a card scale — so opponents' piles are the real thing, just further away. + +import { makeProjection } from '../../ui/casino/CasinoGeometry.js'; + +export const VIEW = { cx: 960, yFar: 78, yNear: 1022, sFar: 0.74, halfW: 930, 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) and each seat's deck back. +export const SEAT_COLORS = [0xf2c14e, 0x4dabf7, 0xe06c75, 0x69db7c]; +export const SEAT_HEX = ['#f2c14e', '#4dabf7', '#e06c75', '#69db7c']; +export const SEAT_BACK_HEX = ['#7a5a12', '#1d4f8a', '#8a1f2c', '#1e6b3c']; + +// ── Table outline (table space: u ∈ [-1, 1], v ∈ [0, 1], far → near) ───────── +export const TABLE = { halfU: 1, v0: 0, v1: 1, corner: 0.17 }; +export const FELT_K = 0.955; // felt inset from the outer rim (fraction of the outline) +export const RAIL_FACE_PX = 30; // visible front face of the table edge at s = 1 + +// Rounded-rectangle outline in table space, scaled about the table centre by k. +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 pts = []; + const corner = (ox, oy, a0) => { + for (let i = 0; i <= steps; i++) { + const a = a0 + (Math.PI / 2) * (i / steps); + // the v axis is squeezed (depth 1 vs width 2) — keep corners round on screen + pts.push({ u: ox + Math.cos(a) * r, v: oy + Math.sin(a) * r * 0.62 }); + } + }; + const rv = r * 0.62; + corner(cu + hu - r, cv + hv - rv, 0); // near-right + corner(cu - hu + r, cv + hv - rv, Math.PI / 2); // near-left + corner(cu - hu + r, cv - hv + rv, Math.PI); // far-left + corner(cu + hu - r, cv - hv + rv, Math.PI * 1.5); // far-right + return pts; +} + +export function outline(k = 1, steps = 14) { + return outlineUV(k, steps).map(p => P.project(p.u, p.v)); +} + +export function onTable(pt, k = 1) { + 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 }))); +} + +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; +} + +// ── Tableau template (owner's frame, px at card scale 1) ───────────────────── +// x along the row, y toward the owner. `fan` = work-pile fan step, `fanMax` = +// the longest a work pile may grow before its fan compresses. +export const HUMAN_TEMPLATE = { + nerts: -392, work: [-195, -65, 65, 195], stock: 392, waste: 512, + fan: 32, fanMax: 250, wasteFan: 26, +}; +export const OPP_TEMPLATE = { + nerts: -372, work: [-218, -110, -2, 106], stock: 246, waste: 352, + fan: 28, fanMax: 190, wasteFan: 22, +}; + +// Seat definitions per player count. anchor = the row's centre line (table space), +// rot = screen rotation of the owner's frame (0 = human, π = across), k = card scale. +const SEATS = { + 2: [ + { uv: { u: 0, v: 0.74 }, rot: 0, k: 1.0, plate: { x: 196, y: 872 } }, + { uv: { u: 0, v: 0.2 }, rot: Math.PI, k: 0.66, plate: { x: 1468, y: 118 } }, + ], + 3: [ + { uv: { u: 0, v: 0.74 }, rot: 0, k: 1.0, plate: { x: 196, y: 872 } }, + { uv: { u: -0.42, v: 0.175 }, rot: Math.PI - 0.16, k: 0.55, plate: { x: 160, y: 300 } }, + { uv: { u: 0.42, v: 0.175 }, rot: Math.PI + 0.16, k: 0.55, plate: { x: 1760, y: 300 } }, + ], + 4: [ + { uv: { u: 0, v: 0.74 }, rot: 0, k: 1.0, plate: { x: 196, y: 872 } }, + { uv: { u: -0.735, v: 0.455 }, rot: Math.PI / 2, k: 0.47, plate: { x: 150, y: 200 } }, + { uv: { u: 0, v: 0.135 }, rot: Math.PI, k: 0.5, plate: { x: 1450, y: 104 } }, + { uv: { u: 0.735, v: 0.455 }, rot: -Math.PI / 2, k: 0.47, plate: { x: 1770, y: 200 } }, + ], +}; + +// Foundations: rows × cols block in the middle of the table. +const FOUNDATION_GRID = { + 2: { cols: 4, rows: 2, k: 0.78, gapX: 16, gapY: 18, uv: { u: 0, v: 0.5 } }, + 3: { cols: 6, rows: 2, k: 0.74, gapX: 14, gapY: 16, uv: { u: 0, v: 0.5 } }, + 4: { cols: 8, rows: 2, k: 0.7, gapX: 12, gapY: 14, uv: { u: 0, v: 0.475 } }, +}; + +const rot2 = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) }); + +// Card container scale for a pose: the perspective squash always acts on the +// SCREEN vertical, so a card turned 90° squashes its local x instead. +export function poseScale(s, rot) { + const c2 = Math.cos(rot) ** 2, s2 = Math.sin(rot) ** 2; + return { sx: s * (c2 + s2 * SQ), sy: s * (s2 + c2 * SQ) }; +} + +// Screen corners of a card pose. +export function cardCorners(pose) { + const { sx, sy } = poseScale(pose.s, pose.rot); + 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) }; +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +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(`Nerts layout supports 2..4 players, got ${playerCount}`); + const seats = defs.map((d, seat) => { + const a = P.project(d.uv.u, d.uv.v); + const tpl = seat === 0 ? HUMAN_TEMPLATE : OPP_TEMPLATE; + return { seat, anchor: { x: a.x, y: a.y }, rot: d.rot, k: d.k, tpl, plate: d.plate }; + }); + const g = FOUNDATION_GRID[playerCount]; + const c = P.project(g.uv.u, g.uv.v); + const fw = CARD_W * g.k, fh = CARD_H * g.k * SQ; + const foundations = []; + for (let i = 0; i < 4 * playerCount; i++) { + const row = Math.floor(i / g.cols), col = i % g.cols; + const x = c.x + (col - (g.cols - 1) / 2) * (fw + g.gapX); + const y = c.y + (row - (g.rows - 1) / 2) * (fh + g.gapY); + foundations.push({ x, y, rot: 0, s: g.k }); + } + const out = { playerCount, seats, foundations, grid: g }; + cache.set(playerCount, out); + return out; +} + +// Map an owner-frame offset (px at card scale 1) to a screen point for a seat. +export function seatPoint(L, seat, dx, dy) { + const st = L.seats[seat]; + const p = rot2(dx * st.k, dy * st.k, st.rot); + return { x: st.anchor.x + p.x, y: st.anchor.y + p.y }; +} + +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 }; +} + +// Fan step for a work pile of n cards (compresses so it never exceeds fanMax). +export function fanStep(tpl, n) { + if (n <= 1) return tpl.fan; + return Math.min(tpl.fan, tpl.fanMax / (n - 1)); +} + +// Lift (screen px, toward the camera) that a stack of n cards shows as thickness. +export function stackLift(n, k = 1) { + return Math.min(9, Math.max(0, n - 1) * 0.42) * k; +} + +/** Base pose of a pile (where its bottom card lies). kind: nerts | work | stock | waste. */ +export function pileBase(L, seat, kind, idx = 0) { + const t = L.seats[seat].tpl; + if (kind === 'work') return pose(L, seat, t.work[idx], 0); + return pose(L, seat, t[kind], 0); +} + +/** Pose of card i (0 = bottom) in a pile of n cards. */ +export function cardPose(L, seat, kind, idx, i, n) { + const st = L.seats[seat], t = st.tpl; + if (kind === 'work') return pose(L, seat, t.work[idx], i * fanStep(t, n)); + if (kind === 'waste') { + // only the last three show, fanned along the row + const shown = Math.min(3, n); + const j = Math.max(0, i - (n - shown)); + return pose(L, seat, t.waste + j * t.wasteFan, 0); + } + // stacked piles (nerts, stock): the top card rides on the stack's thickness + const base = pose(L, seat, t[kind], 0); + const lift = stackLift(i + 1, st.k); + return { ...base, y: base.y - lift }; +} + +export function foundationPose(L, idx, n = 1) { + const f = L.foundations[idx]; + return { ...f, y: f.y - stackLift(n, f.s) }; +} + +// Where a seat's player "sits" — ghost hands rest here, count-back cards land here. +export function seatHome(L, seat) { + const st = L.seats[seat]; + if (seat === 0) return { x: st.plate.x + 150, y: st.plate.y + 20 }; + return seatPoint(L, seat, 0, 300); +} + +// Spot each seat's deck is dealt from (just in front of the owner). +export function dealSpot(L, seat) { + return { ...pose(L, seat, 0, seat === 0 ? 210 : 260) }; +} + +// ── Human hit-testing ──────────────────────────────────────────────────────── +// Human piles are upright (rot 0), so card rects are axis-aligned. +export function inPose(pt, p, pad = 0) { + const hw = (CARD_W / 2) * p.s + pad, hh = (CARD_H / 2) * p.s * SQ + pad; + return Math.abs(pt.x - p.x) <= hw && Math.abs(pt.y - p.y) <= hh; +} + +/** + * Which human card / pile is under a screen point? + * Returns { kind:'nerts'|'waste'|'stock'|'work', idx?, k? } or null. + * `player` is gs.players[0]. + */ +export function humanHit(L, player, pt) { + const p = player; + // work piles — topmost card first + for (let w = 0; w < 4; w++) { + const pile = p.work[w]; + for (let k = pile.length - 1; k >= 0; k--) { + if (inPose(pt, cardPose(L, 0, 'work', w, k, pile.length))) return { kind: 'work', idx: w, k }; + } + if (pile.length === 0 && inPose(pt, pileBase(L, 0, 'work', w))) return { kind: 'work', idx: w, k: -1 }; + } + if (p.stockWaste.length) { + const n = p.stockWaste.length; + if (inPose(pt, cardPose(L, 0, 'waste', 0, n - 1, n))) return { kind: 'waste' }; + } + if (inPose(pt, cardPose(L, 0, 'stock', 0, Math.max(0, p.stockDraw.length - 1), Math.max(1, p.stockDraw.length)), 6)) return { kind: 'stock' }; + if (p.nerts.length && inPose(pt, cardPose(L, 0, 'nerts', 0, p.nerts.length - 1, p.nerts.length))) return { kind: 'nerts' }; + return null; +} + +/** + * Nearest legal drop target for a card dragged to `pt` (its centre). + * `legal` is an array of { type:'foundation'|'work', idx }. Snaps within a + * generous radius; returns null when nothing legal is close. + */ +export function dropTargetAt(L, player, pt, legal) { + let best = null, bestD = Infinity; + for (const t of legal) { + const p = targetPose(L, player, t); + const reach = t.type === 'foundation' ? CARD_W * p.s * 1.15 : CARD_W * 1.05; + // work piles accept a drop anywhere along their fan + let d = Math.hypot(pt.x - p.x, (pt.y - p.y) * 0.85); + if (t.type === 'work') { + const top = pileBase(L, 0, 'work', t.idx).y; + const dy = pt.y < top ? top - pt.y : Math.max(0, pt.y - (p.y + CARD_H * 0.35)); + d = Math.hypot(pt.x - p.x, dy * 0.85); + } + if (d < reach && d < bestD) { bestD = d; best = t; } + } + return best; +} + +// Where a target's next card would land (for highlights + snapping). +export function targetPose(L, player, t) { + if (t.type === 'foundation') return L.foundations[t.idx]; + const n = player.work[t.idx].length; + return cardPose(L, 0, 'work', t.idx, n, n + 1); +} + +// Depth-of-field scale for a dragged card at screen y — shrinks a touch as it +// travels "away" across the table toward the centre. +export function dragScale(L, y) { + const base = P.unproject(L.seats[0].anchor.x, L.seats[0].anchor.y).s; + const s = P.unproject(VIEW.cx, Math.max(VIEW.yFar + 40, y)).s; + return Math.max(0.74, Math.min(1.04, s / base)) * L.seats[0].k; +} + +// ── Seat furniture ─────────────────────────────────────────────────────────── +// Placemat: a rounded rect around the tableau, in the owner's frame (px at k = 1). +export function placematRect(seat) { + const t = seat === 0 ? HUMAN_TEMPLATE : OPP_TEMPLATE; + const x0 = t.nerts - CARD_W / 2 - 34, x1 = t.waste + 2 * t.wasteFan + CARD_W / 2 + 30; + const y0 = -CARD_H / 2 - 40, y1 = CARD_H / 2 + t.fanMax * 0.55 + 30; + return { x0, x1, y0, y1 }; +} + +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), + ]; +} + +// The paper score pad (screen rect) and the Nerts-count badge offset per pile. +export const SCORE_PAD = { x: 1765, y: 880, w: 250, h: 220 }; + +export function nertsBadge(L, seat) { + const t = L.seats[seat].tpl; + return seatPoint(L, seat, t.nerts, -CARD_H / 2 - (seat === 0 ? 24 : 30)); +} diff --git a/tools/verifyNerts.js b/tools/verifyNerts.js new file mode 100644 index 0000000..fb41d2e --- /dev/null +++ b/tools/verifyNerts.js @@ -0,0 +1,437 @@ +#!/usr/bin/env node +// verifyNerts.js — headless checks for Nerts: rules, the table layout for +// 2/3/4 players (everything on screen, seats/foundations/furniture clear of +// each other, human hit-tests and drop snapping round-trip), and an AI soak +// where every seat is played by the AI (rounds must end, cards are conserved, +// scores add up). Usage: node tools/verifyNerts.js [--quick] + +import { + createInitialState, canPlayOnFoundation, canPlayOnWork, playToFoundation, playToWork, + flipStock, endRound, allStuck, nertsTop, getValidPlays, validRunFromIndex, maxRunStart, + liveFoundationCounts, isFoundationComplete, rotateStocks, reshuffleAllStocks, rv, + NERTS_PILE_SIZE, WORK_PILE_COUNT, FOUNDATION_SUITS, +} from '../src/games/nerts/NertsLogic.js'; +import { + chooseAction, reachDelay, carryDelay, handSpeed, HAND_SPEED, rankedPlays, PACE, PERCEPTION, planMove, createMind, noteOwnChange, noticeAt, + isUsefulPlay, usefulPlays, +} from '../src/games/nerts/NertsAI.js'; +import { + W, H, CARD_W, CARD_H, layoutFor, cardPose, pileBase, foundationPose, cardBounds, cardCorners, + humanHit, dropTargetAt, targetPose, dragScale, fanStep, placematCorners, nertsBadge, seatHome, + dealSpot, SCORE_PAD, onTable, FELT_K, HUMAN_TEMPLATE, OPP_TEMPLATE, inPose, +} from '../src/games/nerts/NertsTable.js'; +import { Card } from '../src/games/cards/Deck.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}`); +const C = (key, owner = 0, id = 0) => Object.assign(new Card(key[0], key[1]), { owner, id }); + +// ── Rules ──────────────────────────────────────────────────────────────────── +section('Rules'); +for (const n of [2, 3, 4]) { + const gs = createInitialState({ playerCount: n }); + ok(`${n}p: foundations = 4 × players`, gs.foundations.length === 4 * n); + for (const p of gs.players) { + ok(`${n}p seat ${p.seat}: 13 nerts`, p.nerts.length === NERTS_PILE_SIZE); + ok(`${n}p seat ${p.seat}: 4 work piles of 1`, p.work.length === WORK_PILE_COUNT && p.work.every(w => w.length === 1)); + ok(`${n}p seat ${p.seat}: 35 in stock`, p.stockDraw.length === 35 && p.stockWaste.length === 0); + const all = [...p.nerts, ...p.work.flat(), ...p.stockDraw]; + ok(`${n}p seat ${p.seat}: owns its 52`, all.length === 52 && all.every(c => c.owner === p.seat)); + } + const ids = gs.players.flatMap(p => [...p.nerts, ...p.work.flat(), ...p.stockDraw].map(c => c.id)); + ok(`${n}p: card ids unique`, new Set(ids).size === ids.length); +} +{ + const gs = createInitialState({ playerCount: 2 }); + gs.foundations.fill(null); + ok('empty slot takes only its suit\'s ace', canPlayOnFoundation(gs, C('As'), 0) && !canPlayOnFoundation(gs, C('Ah'), 0)); + ok('slot 1 wants hearts', canPlayOnFoundation(gs, C('Ah'), 1) && FOUNDATION_SUITS[1] === 'h'); + ok('non-ace cannot start a slot', !canPlayOnFoundation(gs, C('2s'), 0)); + gs.foundations[0] = { suit: 's', cards: [C('As')] }; + ok('builds up by suit', canPlayOnFoundation(gs, C('2s'), 0) && !canPlayOnFoundation(gs, C('2c'), 0) && !canPlayOnFoundation(gs, C('3s'), 0)); + const p = gs.players[0]; + p.work[0] = [C('9h')]; + ok('work builds down alternating colour', canPlayOnWork(gs, 0, C('8s'), 0) && !canPlayOnWork(gs, 0, C('8d'), 0) && !canPlayOnWork(gs, 0, C('7s'), 0)); + p.work[1] = []; + ok('empty work pile takes anything', canPlayOnWork(gs, 0, C('Kd'), 1)); + ok('valid run detection', validRunFromIndex([C('9h'), C('8s'), C('7d')], 0) && !validRunFromIndex([C('9h'), C('8h')], 0)); + ok('maxRunStart', maxRunStart([C('5c'), C('9h'), C('8s'), C('7d')]) === 1); + ok('rank values ace-low', rv(C('As')) === 1 && rv(C('Kd')) === 13 && rv(C('Td')) === 10); + const full = { suit: 'd', cards: 'A23456789TJQK'.split('').map(r => C(`${r}d`)) }; + gs.foundations[2] = full; + ok('complete foundation detected', isFoundationComplete(gs, 2) && !isFoundationComplete(gs, 0)); + ok('nothing plays on a completed foundation', !canPlayOnFoundation(gs, C('Ad'), 2)); +} +{ + // stock: draw 3 / draw 1, recycle order + for (const dc of [3, 1]) { + const gs = createInitialState({ playerCount: 2, drawCount: dc }); + const p = gs.players[0]; + const order = [...p.stockDraw].reverse().map(c => c.id); + const seen = []; + let guard = 0; + while (p.stockDraw.length && guard++ < 100) { + const before = p.stockWaste.length; + flipStock(gs, 0); + seen.push(...p.stockWaste.slice(before).map(c => c.id)); + ok(`draw ${dc}: flips ${dc} (or the rest)`, p.stockWaste.length - before === Math.min(dc, 35 - before)); + } + ok(`draw ${dc}: cards come off in pile order`, seen.join() === order.join()); + const r = flipStock(gs, 0); + ok(`draw ${dc}: empty draw recycles`, r?.type === 'recycle' && p.stockDraw.length === 35 && p.stockWaste.length === 0); + const again = [...p.stockDraw].reverse().map(c => c.id); + ok(`draw ${dc}: recycle keeps the order`, again.join() === order.join()); + } + // rotateStocks: the next card to come off moves to the bottom + const gs = createInitialState({ playerCount: 3 }); + for (const p of gs.players) { flipStock(gs, p.seat); flipStock(gs, p.seat); } + const seqs = gs.players.map(p => [...p.stockDraw].reverse().concat(p.stockWaste).map(c => c.id)); + rotateStocks(gs); + gs.players.forEach((p, i) => { + const now = [...p.stockDraw].reverse().map(c => c.id); + ok(`rotateStocks seat ${i}: waste gathered`, p.stockWaste.length === 0 && p.stockDraw.length === 35); + ok(`rotateStocks seat ${i}: top card to the bottom`, now.join() === [...seqs[i].slice(1), seqs[i][0]].join()); + }); + reshuffleAllStocks(gs); + ok('reshuffle keeps every stock card', gs.players.every(p => p.stockDraw.length === 35 && p.stockWaste.length === 0)); +} +{ + // scoring + const gs = createInitialState({ playerCount: 2, targetScore: 10 }); + gs.foundations.fill(null); + gs.foundations[0] = { suit: 's', cards: [C('As', 0), C('2s', 1), C('3s', 0)] }; + gs.players[0].nerts = []; + gs.players[1].nerts = gs.players[1].nerts.slice(0, 5); + gs.nertsCaller = 0; + ok('live counts by owner', liveFoundationCounts(gs).join() === '2,1'); + const sum = endRound(gs); + ok('caller wins the round', gs.winner === 0); + ok('+1 per centre card', sum[0].roundScore === 2); + ok('−2 per card left in Nerts', sum[1].roundScore === 1 - 10); + ok('round only, below target', gs.phase === 'roundover'); +} + +// ── AI helpers ─────────────────────────────────────────────────────────────── +section('AI pacing'); +const band = (cls, skill) => PERCEPTION[cls][skill]; +for (let skill = 1; skill <= 5; skill++) { + ok(`skill ${skill}: pouncing on an awaited card beats noticing in general`, band('pounce', skill)[1] <= band('notice', skill)[0] + 200); + ok(`skill ${skill}: building on your own play is quicker than a fresh read`, band('chain', skill)[1] <= band('read', skill)[1] && band('chain', skill)[0] < band('read', skill)[0]); + ok(`skill ${skill}: the opening scan is the slowest look`, band('scan', skill)[0] >= band('read', skill)[1] * 0.9); + if (skill > 1) { + for (const cls of Object.keys(PERCEPTION)) { + ok(`${cls}: skill ${skill} quicker than skill ${skill - 1}`, band(cls, skill)[1] < band(cls, skill - 1)[1]); + } + } + for (const [name, mult] of Object.entries(PACE)) { + // fresh deal: nothing may happen before the opening scan has had time + const gs = createInitialState({ playerCount: 2 }); + const mind = createMind(skill, 0); + const early = band('scan', skill)[0] * mult - 1; + const plan = planMove(gs, 1, mind, { now: early, pace: mult, foundationAt: [] }); + ok(`skill ${skill} ${name}: no move before the opening scan`, !plan.action && plan.wait > 0, JSON.stringify(plan)); + // after a flip the seat must read before it does anything new + const fresh = createMind(skill, 0); + noteOwnChange(fresh, 10000, 'flip'); + const p2 = planMove(gs, 1, fresh, { now: 10000 + band('read', skill)[0] * mult - 1, pace: mult, foundationAt: [] }); + ok(`skill ${skill} ${name}: reads before acting after a flip`, !p2.action); + ok(`skill ${skill} ${name}: waits are finite and positive`, Number.isFinite(p2.wait) && p2.wait > 0); + } + if (skill > 1) { + ok(`skill ${skill}: hand at least as fast as skill ${skill - 1}`, handSpeed(skill) >= handSpeed(skill - 1) + && reachDelay(skill) < reachDelay(skill - 1) && carryDelay(skill) < carryDelay(skill - 1)); + } +} +ok('hand speeds: ¼ · 0.3 · ½ · 0.8 · full', [1, 2, 3, 4, 5].map(k => HAND_SPEED[k]).join() === '0.25,0.3,0.5,0.8,1'); +ok('skill 5 hand unchanged (190ms reach)', Math.abs(reachDelay(5) - 190) < 1e-9 && Math.abs(carryDelay(5) - 300) < 1e-9); +ok('skill 3 hand at half speed', Math.abs(reachDelay(3) - 600) < 1e-9 && Math.abs(carryDelay(3) - 600) < 1e-9); +ok('skill 1 hand at quarter speed', Math.abs(reachDelay(1) - 1680) < 1e-9); +{ + // pounce vs notice: someone plays the A♥ our Nerts 2♥ was waiting for + const gs = createInitialState({ playerCount: 2 }); + gs.foundations.fill(null); + const two = C('2h', 1, 990); + gs.players[1].nerts.push(two); + gs.foundations[1] = { suit: 'h', cards: [C('Ah', 0, 991)] }; + const mind = createMind(3, 0); + noteOwnChange(mind, 1000, 'move'); + const fAt = []; fAt[1] = { at: 5000, seat: 0 }; + const play = { kind: 'foundation', source: { type: 'nerts' }, dest: 1, card: two }; + const t = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }) - 5000; + ok('a Nerts card someone else unlocks is pounced on', t >= band('pounce', 3)[0] && t <= band('pounce', 3)[1], String(t)); + const wplay = { kind: 'foundation', source: { type: 'waste' }, dest: 1, card: two }; + const tw = noticeAt(1, mind, wplay, { pace: 1, foundationAt: fAt }) - 5000; + ok('a waste card someone else unlocks takes longer to notice', tw >= band('notice', 3)[0] && tw <= band('notice', 3)[1], String(tw)); + fAt[1] = { at: 1000, seat: 1 }; + const tc = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }) - 1000; + ok('building on your own play is a quick chain', tc >= band('chain', 3)[0] && tc <= band('chain', 3)[1], String(tc)); + const again = noticeAt(1, mind, play, { pace: 1, foundationAt: fAt }); + ok('the same play keeps the same notice time (no flicker)', again - 1000 === tc); +} +{ + // no busy-work: split runs and whole-pile-to-empty moves are filtered, and + // repeatedly applying useful work→work moves never loops + const gs = createInitialState({ playerCount: 2 }); + const p = gs.players[0]; + p.work = [[C('Kc', 0, 800), C('Qh', 0, 801), C('Js', 0, 802)], [C('Qd', 0, 803)], [], [C('5s', 0, 804), C('Th', 0, 805)]]; + const split = { kind: 'work', source: { type: 'work', idx: 0, count: 1 }, dest: 1, card: p.work[0][2] }; + ok('splitting a run is not useful', !isUsefulPlay(gs, 0, split)); + const whole = { kind: 'work', source: { type: 'work', idx: 0, count: 3 }, dest: 2, card: p.work[0][0] }; + ok('a whole pile onto an empty pile is not useful', !isUsefulPlay(gs, 0, whole)); + const uncover = { kind: 'work', source: { type: 'work', idx: 3, count: 1 }, dest: 2, card: p.work[3][1] }; + ok('lifting a card off a non-sequence card is useful', isUsefulPlay(gs, 0, uncover)); + for (let trial = 0; trial < 200; trial++) { + const g = createInitialState({ playerCount: 2 }); + const seen = new Set(); + let looped = false; + for (let step = 0; step < 60; step++) { + const moves = usefulPlays(g, 0).filter(m => m.kind === 'work' && m.source.type === 'work'); + if (!moves.length) break; + const m = moves[Math.floor(Math.random() * moves.length)]; + playToWork(g, 0, m.source, m.dest); + const key = g.players[0].work.map(w => w.map(c => c.id).join('.')).join('|'); + if (seen.has(key)) { looped = true; break; } + seen.add(key); + } + if (looped) { ok('useful work moves never loop', false); break; } + } + ok('useful work moves never loop', true); +} +{ + const gs = createInitialState({ playerCount: 2 }); + const plays = rankedPlays(gs, 0); + ok('rankedPlays returns sensible legal plays', plays.length === usefulPlays(gs, 0).length); + ok('chooseAction still works headless', chooseAction(gs, 1, 3) !== undefined); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +const onScreen = (b, m = 0) => b.x0 >= -m && b.y0 >= -m && b.x1 <= W + m && b.y1 <= H + m; +const boxOf = (pts) => ({ + x0: Math.min(...pts.map(p => p.x)), x1: Math.max(...pts.map(p => p.x)), + y0: Math.min(...pts.map(p => p.y)), y1: Math.max(...pts.map(p => p.y)), +}); +const union = (bs) => ({ x0: Math.min(...bs.map(b => b.x0)), x1: Math.max(...bs.map(b => b.x1)), y0: Math.min(...bs.map(b => b.y0)), y1: Math.max(...bs.map(b => b.y1)) }); +const overlap = (a, b, pad = 0) => a.x0 < b.x1 + pad && b.x0 < a.x1 + pad && a.y0 < b.y1 + pad && b.y0 < a.y1 + pad; +const rectBox = (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 }); +const PLATE = { w: 268, h: 92 }; + +// Every card a seat could show at worst: 13-deep work piles, a full waste fan, full stacks. +function seatCardBoxes(L, seat) { + const out = []; + out.push(cardBounds(cardPose(L, seat, 'nerts', 0, 12, 13))); + for (let w = 0; w < 4; w++) for (let i = 0; i < 13; i++) out.push(cardBounds(cardPose(L, seat, 'work', w, i, 13))); + out.push(cardBounds(cardPose(L, seat, 'stock', 0, 34, 35))); + for (let i = 0; i < 3; i++) out.push(cardBounds(cardPose(L, seat, 'waste', 0, 30 + i, 33))); + return out; +} + +for (const n of [2, 3, 4]) { + const L = layoutFor(n); + ok(`${n}p: one seat per player`, L.seats.length === n); + const seatBoxes = []; + for (let seat = 0; seat < n; seat++) { + const boxes = seatCardBoxes(L, seat); + ok(`${n}p seat ${seat}: every card on screen`, boxes.every(b => onScreen(b, 2)), JSON.stringify(union(boxes))); + // the base row sits on the felt; fans may run onto the rail but not off the table + const base = [cardPose(L, seat, 'nerts', 0, 0, 1), ...[0, 1, 2, 3].map(w => pileBase(L, seat, 'work', w)), pileBase(L, seat, 'stock'), pileBase(L, seat, 'waste')]; + ok(`${n}p seat ${seat}: pile bases on the felt`, base.every(p => onTable(p, FELT_K))); + seatBoxes[seat] = { boxes, all: union(boxes) }; + const badge = nertsBadge(L, seat); + ok(`${n}p seat ${seat}: nerts badge on screen`, badge.x > 20 && badge.x < W - 20 && badge.y > 20 && badge.y < H - 20); + const plate = rectBox({ ...L.seats[seat].plate, ...PLATE }); + ok(`${n}p seat ${seat}: nameplate on screen`, onScreen(plate)); + const d = dealSpot(L, seat), h = seatHome(L, seat); + ok(`${n}p seat ${seat}: deal spot / hand rest on screen`, d.x > 0 && d.x < W && d.y > -40 && d.y < H && h.y > -60); + } + // seats never overlap each other (card by card) + for (let a = 0; a < n; a++) { + for (let b = a + 1; b < n; b++) { + const hit = seatBoxes[a].boxes.some(x => seatBoxes[b].boxes.some(y => overlap(x, y, 6))); + ok(`${n}p: seat ${a} clear of seat ${b}`, !hit); + } + } + // foundations: on the felt, no overlap with each other, clear of every seat + const fBoxes = L.foundations.map((f, i) => cardBounds(foundationPose(L, i, 13))); + ok(`${n}p: foundations on the felt`, L.foundations.every(f => onTable(f, FELT_K * 0.95))); + ok(`${n}p: foundations don't overlap`, fBoxes.every((x, i) => fBoxes.every((y, j) => i === j || !overlap(x, y)))); + const fAll = union(fBoxes); + for (let seat = 0; seat < n; seat++) { + ok(`${n}p: foundations clear of seat ${seat}`, !seatBoxes[seat].boxes.some(b => overlap(b, fAll, 20))); + } + // plates / score pad / stall widget clear of every seat's cards and the foundations + const furniture = [ + ...L.seats.map(st => ['plate ' + st.seat, rectBox({ ...st.plate, ...PLATE })]), + ['score pad', rectBox(SCORE_PAD)], + ['stall widget', rectBox({ x: 200, y: 760, w: 300, h: 92 })], + ['top buttons', { x0: 19, x1: 291, y0: 22, y1: 66 }], + ]; + for (const [name, box] of furniture) { + for (let seat = 0; seat < n; seat++) { + ok(`${n}p: ${name} clear of seat ${seat} cards`, !seatBoxes[seat].boxes.some(b => overlap(b, box, 4))); + } + ok(`${n}p: ${name} clear of the foundations`, !overlap(box, fAll, 4)); + } + for (let i = 0; i < furniture.length; i++) { + for (let j = i + 1; j < furniture.length; j++) { + ok(`${n}p: ${furniture[i][0]} clear of ${furniture[j][0]}`, !overlap(furniture[i][1], furniture[j][1], 4)); + } + } + + // human hit-testing round-trips on a crafted tableau + const gs = createInitialState({ playerCount: n }); + const p = gs.players[0]; + p.work[0] = [C('9h', 0, 900), C('8s', 0, 901), C('7d', 0, 902)]; + p.work[1] = []; + p.work[2] = Array.from({ length: 13 }, (_, i) => C('5c', 0, 910 + i)); + flipStock(gs, 0); + const pile0 = p.work[0]; + pile0.forEach((_, k) => { + const pose = cardPose(L, 0, 'work', 0, k, pile0.length); + // a point inside the visible strip of card k (above the next card's top edge) + const pt = k === pile0.length - 1 ? pose : { x: pose.x, y: pose.y - (CARD_H / 2) * 0.9 + 6 }; + const hit = humanHit(L, p, pt); + ok(`${n}p: hit work card ${k}`, hit?.kind === 'work' && hit.idx === 0 && hit.k === k, JSON.stringify(hit)); + }); + const deep = cardPose(L, 0, 'work', 2, 12, 13); + ok(`${n}p: hit top of a 13-deep pile`, humanHit(L, p, deep)?.k === 12); + ok(`${n}p: hit the nerts top`, humanHit(L, p, cardPose(L, 0, 'nerts', 0, 12, 13))?.kind === 'nerts'); + ok(`${n}p: hit the waste top`, humanHit(L, p, cardPose(L, 0, 'waste', 0, 2, 3))?.kind === 'waste'); + ok(`${n}p: hit the stock`, humanHit(L, p, cardPose(L, 0, 'stock', 0, 31, 32))?.kind === 'stock'); + ok(`${n}p: empty work pile is a target`, humanHit(L, p, pileBase(L, 0, 'work', 1))?.k === -1); + ok(`${n}p: felt centre hits nothing`, humanHit(L, p, { x: 960, y: L.foundations[0].y }) === null); + + // drop snapping: each legal target snaps from its own landing spot, and only legal ones + const targets = [...L.foundations.map((_, i) => ({ type: 'foundation', idx: i })), ...[0, 1, 2, 3].map(i => ({ type: 'work', idx: i }))]; + for (const t of targets) { + const at = targetPose(L, p, t); + const got = dropTargetAt(L, p, at, [t]); + ok(`${n}p: drop snaps to ${t.type} ${t.idx}`, got && got.type === t.type && got.idx === t.idx); + ok(`${n}p: illegal ${t.type} ${t.idx} never snaps`, dropTargetAt(L, p, at, targets.filter(x => x !== t))?.idx !== t.idx || dropTargetAt(L, p, at, targets.filter(x => x !== t))?.type !== t.type); + } + ok(`${n}p: drop far from everything snaps to nothing`, dropTargetAt(L, p, { x: 40, y: 500 }, targets) === null); + const top = dragScale(L, 200), near = dragScale(L, L.seats[0].anchor.y); + ok(`${n}p: a dragged card shrinks toward the middle`, top < near && near <= 1.04 && top >= 0.74); +} +ok('fan compresses long piles', fanStep(HUMAN_TEMPLATE, 13) * 12 <= HUMAN_TEMPLATE.fanMax + 1e-9 && fanStep(OPP_TEMPLATE, 3) === OPP_TEMPLATE.fan); + +// ── AI soak ────────────────────────────────────────────────────────────────── +// Every seat is an AI. Simulated time: each seat acts on its own think timer; +// foundation cooldowns mirror the scene; stalls rotate then reshuffle stocks. +section('AI soak'); +function countCards(gs) { + const counts = new Array(gs.players.length).fill(0); + for (const p of gs.players) { + for (const c of [...p.nerts, ...p.work.flat(), ...p.stockDraw, ...p.stockWaste]) counts[c.owner]++; + } + for (const s of gs.foundations) if (s) for (const c of s.cards) counts[c.owner]++; + return counts; +} + +// Mirrors NertsGame's AI loop on a simulated play clock: each seat polls +// planMove (≤250ms apart), an action lands after the hand's reach, the seat +// re-plans 60ms after its move. Records every AI action's time per seat. +function soakRound(n, skills, drawCount, pace = 1) { + const gs = createInitialState({ playerCount: n, drawCount }); + const minds = skills.map(s => createMind(s, 0)); + const foundationAt = []; + const next = skills.map(() => 100 + Math.random() * 200); // next poll per seat + const pending = skills.map(() => null); // { at, action } + const actionTimes = skills.map(() => []); + let now = 0, lastProgress = 0, lastRotate = -Infinity, rotations = 0, actions = 0, conserved = true, foundationOk = true; + let gaveUp = false, fumbles = 0; + while (gs.nertsCaller === null && !allStuck(gs) && now < 30 * 60 * 1000) { + let seat = 0, t = Infinity; + for (let s = 0; s < n; s++) { + const ts = pending[s] ? pending[s].at : next[s]; + if (ts < t) { t = ts; seat = s; } + } + now = t; + if (!pending[seat]) { + const plan = planMove(gs, seat, minds[seat], { now, pace, foundationAt, stalledMs: now - lastProgress }); + if (!plan.action) { next[seat] = now + Math.min(250, plan.wait ?? 250); continue; } + const reach = reachDelay(skills[seat], pace, plan.action.kind === 'flip' ? 'flip' : 'move'); + pending[seat] = { at: now + reach, action: plan.action }; + continue; + } + const a = pending[seat].action; + pending[seat] = null; + if (a.kind === 'flip') { flipStock(gs, seat); noteOwnChange(minds[seat], now, 'flip'); } + else if (a.kind === 'foundation') { + const log = playToFoundation(gs, seat, a.source, a.dest); + if (log) { foundationAt[a.dest] = { at: now, seat }; lastProgress = now; noteOwnChange(minds[seat], now, 'move'); } + else { fumbles++; noteOwnChange(minds[seat], now, 'fumble'); } + } else if (a.kind === 'work') { + const log = playToWork(gs, seat, a.source, a.dest); + if (log && a.source.type === 'nerts') lastProgress = now; + noteOwnChange(minds[seat], now, 'move'); + } + actionTimes[seat].push(now); + actions++; + // the hand finishes carrying a played card before it reaches again + next[seat] = now + (a.kind === 'flip' ? 60 : carryDelay(skills[seat], pace)); + // mirrors NertsGame.updateStall: rotate at 60s idle (30s apart), give up at 180s + if (now - lastProgress >= 60000 && now - lastRotate >= 30000) { + if (rotations === 0) rotateStocks(gs); else reshuffleAllStocks(gs); + for (const m of minds) noteOwnChange(m, now, 'flip'); + rotations++; + lastRotate = now; + } + if (now - lastProgress >= 180000) { gaveUp = true; break; } + if (actions % 50 === 0) { + if (!countCards(gs).every(c => c === 52)) conserved = false; + for (const s of gs.foundations) { + if (!s) continue; + s.cards.forEach((c, i) => { if (c.suit !== s.suit || rv(c) !== i + 1) foundationOk = false; }); + } + } + } + if (!countCards(gs).every(c => c === 52)) conserved = false; + const live = liveFoundationCounts(gs); + const nertsLeft = gs.players.map(p => p.nerts.length); + const ended = gs.nertsCaller !== null || allStuck(gs) || gaveUp; + const summary = endRound(gs); + const scoresOk = summary.every(s => s.founded === live[s.seat] && s.roundScore === s.founded - 2 * nertsLeft[s.seat]); + return { ended, gaveUp, conserved, foundationOk, scoresOk, minutes: now / 60000, rotations, caller: gs.nertsCaller, actions, actionTimes, fumbles }; +} + +const ROUNDS = QUICK ? 24 : 150; +const stats = { ended: 0, gaveUp: 0, minutes: [], rotations: 0, wins: [0, 0, 0, 0], fumbles: 0, gaps: {} }; +for (let r = 0; r < ROUNDS; r++) { + const n = 2 + (r % 3); + const skills = [3, ...Array.from({ length: n - 1 }, (_, i) => 1 + ((r + i * 2) % 5))]; + const res = soakRound(n, skills, r % 4 === 3 ? 1 : 3); + ok(`round ${r} (${n}p): ended`, res.ended, `${res.minutes.toFixed(1)} min, ${res.rotations} rotations`); + ok(`round ${r}: cards conserved`, res.conserved); + ok(`round ${r}: foundations build A→K by suit`, res.foundationOk); + ok(`round ${r}: scores = +1/centre card −2/nerts card`, res.scoresOk); + if (res.ended) stats.ended++; + if (res.gaveUp) stats.gaveUp++; + stats.minutes.push(res.minutes); + stats.rotations += res.rotations; + if (res.caller !== null) stats.wins[res.caller]++; + stats.fumbles += res.fumbles; + res.actionTimes.forEach((times, seat) => { + const g = (stats.gaps[skills[seat]] ??= []); + for (let i = 1; i < times.length; i++) g.push(times[i] - times[i - 1]); + }); +} +const mins = stats.minutes.sort((a, b) => a - b); +console.log(` ${stats.ended}/${ROUNDS} rounds ended (${stats.gaveUp} stalled out) · median ${mins[Math.floor(mins.length / 2)].toFixed(1)} sim-min · max ${mins[mins.length - 1].toFixed(1)} · ${stats.rotations} stock rotations · callers by seat ${stats.wins.join('/')}`); + +const avg = (a) => a.reduce((x, y) => x + y, 0) / a.length; +const paceLine = Object.keys(stats.gaps).sort().map(sk => `skill ${sk} ${(avg(stats.gaps[sk]) / 1000).toFixed(2)}s`).join(' · '); +console.log(` avg time between a seat's actions: ${paceLine} · ${stats.fumbles} lost races`); +for (const sk of Object.keys(stats.gaps)) { + const a = avg(stats.gaps[sk]) / 1000; + ok(`skill ${sk}: plays at a human pace (${a.toFixed(2)}s/action)`, a >= 0.7 && a <= 6); +} +if (stats.gaps[1] && stats.gaps[5]) ok('skill 5 plays faster than skill 1', avg(stats.gaps[5]) < avg(stats.gaps[1])); + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);