diff --git a/src/games/splendor/SplendorAI.js b/src/games/splendor/SplendorAI.js index d074ee1..ebcd08b 100644 --- a/src/games/splendor/SplendorAI.js +++ b/src/games/splendor/SplendorAI.js @@ -1,99 +1,295 @@ -// Splendor AI — synchronous, in-browser heuristic. 1-ply greedy over a board -// evaluation, with a skill model (1–5) that adds blunders / score noise and -// picks from a widening top-N, exactly the shape used by Connect4AI / IslandAI. +// Splendor AI — synchronous, in-browser planner. +// +// Every legal action is played out (applyAction + the AI's own discard / noble +// choices) and the resulting position is scored by `evaluate`: +// • prestige, heavily weighted; +// • the engine: card bonuses, weighted by how much the table still wants +// each colour and tapering as the game ages; +// • targets: every card it could aim for (market + its own reserve), worth +// points + bonus value, discounted by an estimate of the turns needed to +// afford it (tokens missing after bonuses and gold, and whether the case +// can still supply them); +// • noble progress, discounted when a rival is closer; +// • liquidity: a little for tokens, a little more for gold. +// On top of that: denial (what is the best buy a rival will have next turn on +// the resulting market?), end-race awareness (in the final round only points +// matter; finishing ahead of everyone is worth a lot), and from skill 3 a +// one-step follow-up (its best next action from the resulting position) for +// the leading candidates (2 / 2 / 10 of them at skill 3 / 4 / 5), so it +// sequences take → buy. +// +// Skill 1–5 vary the target horizon, the denial and follow-up terms, score +// noise, top-N picking and "blunders" — which are drawn only from sensible +// moves (a three-gem take or a buy), never a random reserve. -import { GEMS, GOLD, WIN_POINTS } from './SplendorData.js'; -import { legalActions, applyAction, purchaseCost } from './SplendorLogic.js'; +import { GEMS, GOLD, WIN_POINTS, HAND_LIMIT, NOBLE_POINTS } from './SplendorData.js'; +import { + legalActions, applyAction, applyDiscard, applyNobleChoice, purchaseCost, tokenTotal, nobleProgress, +} from './SplendorLogic.js'; -const SKILL_PROFILES = { - 1: { topN: 5, blunder: 0.45, noise: 40, delay: [700, 1200] }, - 2: { topN: 4, blunder: 0.25, noise: 22, delay: [650, 1100] }, - 3: { topN: 3, blunder: 0.12, noise: 12, delay: [600, 1000] }, - 4: { topN: 2, blunder: 0.04, noise: 5, delay: [520, 900] }, - 5: { topN: 1, blunder: 0.00, noise: 0, delay: [440, 820] }, +export const TUNE = { + pts: 40, // value of one prestige point + bonus: 12, // base value of one permanent bonus + bonusLate: 0.35, // bonus value multiplier at the end of the game + demand: 1.4, // extra bonus value per unit of table demand + token: 0.6, // tokens mostly count through the targets they bring closer + gold: 2, + tokenCrowd: 3, // per token above 8 (near the hand limit) + targetW: [1, 0.45, 0.2], + contention: 0.85, // market targets can be taken by others + nobleW: 34, // value of a noble at full progress (~3 pts minus risk) + rivalNoble: 0.5, // noble value multiplier when a rival is ahead on it + reserveClog: 6, // per reserved card that is far off (T > 3) + denial: 0.4, // per point of a rival's best next buy + finishAhead: 900, + finalRoundPts: 160, + follow: 0.55, // weight of the follow-up (skill 3+) + ready: 0.8, // target factor for a card affordable right now }; -function profileFor(skill) { - return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; +const PROFILES = { + 1: { decay: 0.42, denial: 0, follow: 0, noise: 75, topN: 3, blunder: 0.3, delay: [700, 1200] }, + 2: { decay: 0.5, denial: 0, follow: 0, noise: 28, topN: 2, blunder: 0.1, delay: [650, 1100] }, + 3: { decay: 0.56, denial: 0.5, follow: 2, noise: 12, topN: 2, blunder: 0.04, delay: [600, 1000] }, + 4: { decay: 0.6, denial: 1, follow: 2, noise: 12, topN: 1, blunder: 0.01, delay: [520, 900] }, + 5: { decay: 0.62, denial: 1, follow: 10, noise: 0, topN: 1, blunder: 0, delay: [440, 820] }, +}; + +export function profileFor(skill) { + return PROFILES[Math.max(1, Math.min(5, Math.round(skill ?? 3)))] ?? PROFILES[3]; } -export function nextThinkDelay(skill) { +export function nextThinkDelay(skill, rnd = Math.random) { const [lo, hi] = profileFor(skill).delay; - return lo + Math.random() * (hi - lo); + return lo + rnd() * (hi - lo); } -// Coloured tokens (excluding gold) still required for `card` after bonuses and -// the player's current tokens — i.e. how far off buying it they are. -function shortfall(p, card) { - let s = 0; - for (const color of GEMS) { - s += Math.max(0, (card.cost[color] ?? 0) - (p.bonuses[color] ?? 0) - p.tokens[color]); +// ── evaluation ────────────────────────────────────────────────────────────────── +// Estimated turns until `p` can buy `card` (0 = now), given the case. +export function turnsToAfford(p, card, bank) { + let total = 0, maxOne = 0, scarce = 0; + for (const c of GEMS) { + const d = Math.max(0, (card.cost[c] ?? 0) - (p.bonuses[c] ?? 0) - (p.tokens[c] ?? 0)); + total += d; + if (d > maxOne) maxOne = d; + if (bank && d > (bank[c] ?? 0)) scarce += d - bank[c]; } - return Math.max(0, s - p.tokens[GOLD]); + total = Math.max(0, total - (p.tokens[GOLD] ?? 0)); + if (total === 0) return 0; + return Math.max(Math.ceil(total / 3), Math.ceil(maxOne / 2)) + Math.ceil(scarce / 2); } -// Evaluate the whole position from `seat`'s perspective (higher = better). -function evalPlayer(state, seat) { - const p = state.players[seat]; - let v = p.points * 100; - - // Permanent engine: each card bonus is lasting buying power; reward breadth. - let bonusSum = 0, distinct = 0; - for (const g of GEMS) { bonusSum += p.bonuses[g]; if (p.bonuses[g] > 0) distinct++; } - v += bonusSum * 9 + distinct * 4; - - // Tokens are minor liquid value; gold (wild) is worth a touch more. - for (const g of GEMS) v += p.tokens[g] * 1.0; - v += p.tokens[GOLD] * 1.6; - - // Progress toward the nobles still on the table. - for (const n of state.nobles) { - let prog = 0; - for (const [color, req] of Object.entries(n.requires)) { - prog += Math.min(p.bonuses[color] ?? 0, req); +function colourDemand(state) { + const d = { white: 0, blue: 0, green: 0, red: 0, black: 0 }; + for (const t of [1, 2, 3]) { + for (const c of state.board[t]) { + if (!c) continue; + const w = c.points ? 1 + c.points * 0.3 : 0.6; + for (const g of GEMS) if (c.cost[g]) d[g] += (c.cost[g] / 4) * w * 0.25; } - v += prog * 2; + } + for (const n of state.nobles) for (const g of Object.keys(n.requires)) d[g] += 0.5; + return d; +} + +function stageOf(state) { + let top = 0; + for (const p of state.players) top = Math.max(top, p.points); + return Math.min(1, top / WIN_POINTS); +} + +export function evaluate(state, seat, prof = PROFILES[5], cache = {}) { + const p = state.players[seat]; + const stage = cache.stage ?? (cache.stage = stageOf(state)); + const demand = cache.demand ?? (cache.demand = colourDemand(state)); + let v = p.points * TUNE.pts; + + // Engine. + const bonusMul = 1 - (1 - TUNE.bonusLate) * stage; + for (const g of GEMS) { + const b = p.bonuses[g] ?? 0; + const eff = Math.min(b, 5) + Math.max(0, b - 5) * 0.35; + v += eff * (TUNE.bonus + TUNE.demand * demand[g]) * bonusMul; } - // Reach: how close is the best high-value card we could aim for? - let best = 0; - const targets = []; - for (const t of [1, 2, 3]) for (const c of state.board[t]) if (c) targets.push(c); - for (const c of p.reserved) targets.push(c); - for (const c of targets) { - const reach = c.points * 6 - shortfall(p, c) * 1.5; - if (reach > best) best = reach; - } - v += best; + // Liquidity. + for (const g of GEMS) v += (p.tokens[g] ?? 0) * TUNE.token; + v += (p.tokens[GOLD] ?? 0) * TUNE.gold; + const held = tokenTotal(p); + if (held > 8) v -= (held - 8) * TUNE.tokenCrowd; - // Mild nudge to close out the game when in front. - if (p.points >= WIN_POINTS) v += 500; + // Nobles. + for (const n of state.nobles) { + const mine = nobleProgress(p, n); + let frac = mine.have / mine.need; + let rivalAhead = false; + for (const o of state.players) { + if (o.seat === seat) continue; + if (nobleProgress(o, n).have > mine.have) { rivalAhead = true; break; } + } + v += TUNE.nobleW * frac * frac * (rivalAhead ? TUNE.rivalNoble : 1) * (0.5 + 0.5 * stage + 0.25); + } + + // Targets. + const scores = []; + const consider = (c, own) => { + const T = turnsToAfford(p, c, state.bank); + const bonusV = (TUNE.bonus + TUNE.demand * demand[c.bonus]) * bonusMul * 0.5; + let w = c.points * TUNE.pts + bonusV; + if (!own) w *= TUNE.contention; + if (T === 0) w *= TUNE.ready; // affordable now: worth less than owning it, more than T=1 + scores.push(w * prof.decay ** T); + if (own && T > 3) v -= TUNE.reserveClog; + }; + for (const t of [1, 2, 3]) for (const c of state.board[t]) if (c) consider(c, false); + for (const c of p.reserved) consider(c, true); + scores.sort((a, b) => b - a); + TUNE.targetW.forEach((w, i) => { if (scores[i]) v += scores[i] * w; }); + + // Reaching the line. + if (p.points >= WIN_POINTS) { + let best = 0; + for (const o of state.players) if (o.seat !== seat) best = Math.max(best, o.points); + v += p.points > best ? TUNE.finishAhead * 0.4 : 0; + } return v; } +// The best buy (points + noble unlock) `p` could make on `state` right now. +function bestImmediateBuy(state, p) { + let best = 0; + const check = (c) => { + if (!c) return; + const { gold } = purchaseCost(p, c); + if (gold > (p.tokens[GOLD] ?? 0)) return; + let gain = c.points; + const nb = { ...p.bonuses, [c.bonus]: (p.bonuses[c.bonus] ?? 0) + 1 }; + if (state.nobles.some((n) => Object.entries(n.requires).every(([g, r]) => (nb[g] ?? 0) >= r))) gain += NOBLE_POINTS; + if (gain > best) best = gain; + }; + for (const t of [1, 2, 3]) state.board[t].forEach(check); + p.reserved.forEach(check); + return best; +} + +// ── parked-phase choices ───────────────────────────────────────────────────────── +// Return the tokens whose loss hurts the evaluation least (gold last). +export function chooseDiscards(state) { + const seat = state.current; + const p = state.players[seat]; + const excess = tokenTotal(p) - HAND_LIMIT; + const map = {}; + let cur = state; + for (let k = 0; k < excess; k++) { + let best = null, bestV = -Infinity; + for (const g of [...GEMS, GOLD]) { + const have = cur.players[seat].tokens[g] - 0; + if (have <= 0) continue; + const trial = { ...cur, players: cur.players.map((q) => (q.seat === seat ? { ...q, tokens: { ...q.tokens, [g]: q.tokens[g] - 1 } } : q)) }; + const v = evaluate(trial, seat) - (g === GOLD ? 2 : 0); + if (v > bestV) { bestV = v; best = g; } + } + if (!best) break; + map[best] = (map[best] ?? 0) + 1; + cur = { ...cur, players: cur.players.map((q) => (q.seat === seat ? { ...q, tokens: { ...q.tokens, [best]: q.tokens[best] - 1 } } : q)) }; + } + return map; +} + +// Several nobles qualify: take the one a rival is closest to. +export function chooseNoble(state) { + const seat = state.current; + let best = state.pendingNobles[0], bestV = -1; + for (const id of state.pendingNobles) { + const n = state.nobles.find((x) => x.id === id); + let rival = 0; + for (const o of state.players) { + if (o.seat === seat) continue; + const pr = nobleProgress(o, n); + rival = Math.max(rival, pr.have / pr.need); + } + if (rival > bestV) { bestV = rival; best = id; } + } + return best; +} + +export function settle(state) { + let s = state; + for (let g = 0; g < 8; g++) { + if (s.phase === 'discard') s = applyDiscard(s, chooseDiscards(s)); + else if (s.phase === 'noble') s = applyNobleChoice(s, chooseNoble(s)); + else break; + } + return s; +} + +// ── action choice ──────────────────────────────────────────────────────────────── +function scoreOutcome(before, after, seat, prof) { + const me = after.players[seat]; + if (after.phase === 'gameOver') { + let best = -1, bestCards = 99; + for (const o of after.players) { + if (o.seat === seat) continue; + if (o.points > best || (o.points === best && o.cardsCount < bestCards)) { best = o.points; bestCards = o.cardsCount; } + } + const win = me.points > best || (me.points === best && me.cardsCount < bestCards); + return (win ? 1e6 : 0) + me.points * 1000 - me.cardsCount; + } + let v = evaluate(after, seat, prof); + if (before.triggeredEnd) v += me.points * TUNE.finalRoundPts; + if (prof.denial) { + let threat = 0; + for (const o of after.players) { + if (o.seat === seat) continue; + threat = Math.max(threat, bestImmediateBuy(after, o)); + } + v -= threat * TUNE.denial * TUNE.pts * prof.denial; + } + return v; +} + +const sensible = (a) => a.type === 'buy' || (a.type === 'take3' && a.colors.length === 3); + // Returns a single action object for the current player, or { type: 'pass' }. -export function chooseAction(state, skill) { +export function chooseAction(state, skill, rnd = Math.random) { const prof = profileFor(skill); const seat = state.current; const legal = legalActions(state); if (legal.length === 0) return { type: 'pass' }; if (legal.length === 1) return legal[0]; - const ranked = legal - .map((action) => { - let score = evalPlayer(applyAction(state, action), seat); - score += (Math.random() * 2 - 1) * prof.noise; - return { action, score }; - }) - .sort((a, b) => b.score - a.score); - - if (Math.random() < prof.blunder) { - return legal[Math.floor(Math.random() * legal.length)]; + if (prof.blunder && rnd() < prof.blunder) { + const pool = legal.filter(sensible); + if (pool.length) return pool[Math.floor(rnd() * pool.length)]; } + + const ranked = legal.map((action) => { + const after = settle(applyAction(state, action)); + return { action, after, score: scoreOutcome(state, after, seat, prof) }; + }); + + if (prof.follow) { + ranked.sort((a, b) => b.score - a.score); + for (const r of ranked.slice(0, prof.follow)) { + if (r.after.phase === 'gameOver' || state.triggeredEnd) continue; + // Pretend it's our turn again on the resulting position. + const mine = { ...r.after, current: seat, phase: 'turn', triggeredEnd: false }; + let best = -Infinity; + for (const a2 of legalActions(mine)) { + const after2 = settle(applyAction(mine, a2)); + best = Math.max(best, evaluate(after2, seat, prof)); + } + if (best > -Infinity) r.score = r.score * (1 - TUNE.follow) + best * TUNE.follow; + } + } + + for (const r of ranked) r.score += (rnd() * 2 - 1) * prof.noise; + ranked.sort((a, b) => b.score - a.score); const pool = ranked.slice(0, Math.max(1, prof.topN)); - return pool[Math.floor(Math.random() * pool.length)].action; + // Weighted toward the best of the pool. + const pick = pool.length > 1 && rnd() < 0.35 ? pool[1 + Math.floor(rnd() * (pool.length - 1))] : pool[0]; + return pick.action; } -// Re-export so the scene can resolve AI / quick discards without importing Logic -// for that one helper. +// Kept for callers that used the old helper. export { defaultDiscards } from './SplendorLogic.js'; diff --git a/src/games/splendor/SplendorArt.js b/src/games/splendor/SplendorArt.js new file mode 100644 index 0000000..1938ddd --- /dev/null +++ b/src/games/splendor/SplendorArt.js @@ -0,0 +1,752 @@ +// SplendorArt.js — "The Counting House" procedural art. +// +// Everything is painted on canvases and registered as textures once per page +// load (stable keys; scene restarts reuse them): +// +// spl-room damask wall, gilt picture rail, walnut desk, baize +// counting cloth under the market (opaque, full screen) +// spl-light oil-lamp pool + vignette (transparent overlay) +// spl-track the Guild Register: prestige rule 0–15 with a crown +// spl-plaque- brass row plaque ("The Mines" …) +// spl-case the jewel case (bank): walnut box, velvet wells +// spl-ledger-x tooled-leather merchant's ledger for a seat +// spl-dock the merchant's slate (prompt + gem tray) +// spl-card- card faces: the user's painting in a metal frame with +// points, bonus gem and cost chips (256×352, shown at ½) +// spl-back- deck backs (the user's merchant art, framed) +// spl-noble- a patron: portrait in a gilt frame over a req plate +// spl-chip- gem token (96×96) +// spl-glow, spl-spark, spl-spot, spl-seal, spl-glint, spl-dust, spl-flame, +// spl-pawn, spl-shadow +// +// The frames, furniture and tokens are original designs; the paintings and the +// gem sprites are the user's (splendor-cards / splendor-gems sheets). When the +// sheets are missing everything falls back to drawn gems and colour washes. + +import { canvas, rr, mix, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + GEMS, GOLD, GEM_NAME, NOBLES, TIER_NAME, cardFrame, nobleFrame, deckBackFrame, gemFrame, +} from './SplendorData.js'; +import { + W, H, WALL, GALLERY, TRACK, TRACK_RULE, trackX, MARKET, BANK, BANK_ORDER, bankCell, DOCK, + CW, CH, ledgerParts, +} from './SplendorLayout.js'; + +export const SERIF = 'Georgia, "Times New Roman", serif'; +export const DISPLAY = 'Caesar, Georgia, serif'; +export const INK = '#2a1a0c'; +export const CREAM = '#f3e6c8'; +export const BRASS = '#d9b45a'; + +// Gem palette for canvas work (css) — richer than the flat GEM_HEX. +export const GEM_CSS = { + white: { hi: '#ffffff', mid: '#e6e2d8', lo: '#9a958a', ink: '#2a2620', rim: '#b9b4a6' }, + blue: { hi: '#8fc0ff', mid: '#2f6fc0', lo: '#123a70', ink: '#ffffff', rim: '#1b4c80' }, + green: { hi: '#9ff0b4', mid: '#2f9b54', lo: '#11522a', ink: '#ffffff', rim: '#1f6e3a' }, + red: { hi: '#ff9a8a', mid: '#c4302a', lo: '#6a1210', ink: '#ffffff', rim: '#8a2419' }, + black: { hi: '#8a8580', mid: '#3a3634', lo: '#0e0c0a', ink: '#ffffff', rim: '#16140f' }, + gold: { hi: '#fff0a8', mid: '#d9a520', lo: '#7a5608', ink: '#2a1a0c', rim: '#8a6a0c' }, +}; +const TIER_METAL = { + 1: { hi: '#f0b27a', mid: '#b87333', lo: '#5a3412' }, // copper + 2: { hi: '#f4f4fa', mid: '#a9adb8', lo: '#4c505a' }, // silver + 3: { hi: '#fff0b0', mid: '#d6aa48', lo: '#6e5018' }, // gold +}; + +export const FACE_W = 256, FACE_H = 352; // card face texture size (2× of CW×CH) +export const NOBLE_TW = 224, NOBLE_TH = 280; // noble texture (2× of 112×140) +export const CHIP_PX = 96; + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); + return key; +} +function seeded(seed) { + let r = (seed * 9301 + 49297) % 233280; + return () => ((r = (r * 9301 + 49297) % 233280) / 233280); +} + +// ── shared drawing helpers ─────────────────────────────────────────────────────── +function grain(ctx, x, y, w, h, { dark = 'rgba(30,14,4,0.2)', light = 'rgba(255,210,160,0.05)', spacing = 6, amp = 2, seed = 1 } = {}) { + const rnd = seeded(seed); + ctx.save(); + ctx.lineWidth = 1; + for (let yy = y; yy < y + h; yy += spacing * (0.6 + rnd() * 0.8)) { + ctx.strokeStyle = rnd() < 0.72 ? dark : light; + ctx.beginPath(); + const ph = rnd() * 6, fq = 0.004 + rnd() * 0.01; + for (let xx = x; xx <= x + w; xx += 12) { + const yv = yy + Math.sin(xx * fq + ph) * amp + Math.sin(xx * fq * 3.1 + ph) * amp * 0.3; + if (xx === x) ctx.moveTo(xx, yv); else ctx.lineTo(xx, yv); + } + ctx.stroke(); + } + ctx.restore(); +} + +function metalGrad(ctx, x, y, w, h, m = TIER_METAL[3]) { + const g = ctx.createLinearGradient(x, y, x + w * 0.3, y + h); + g.addColorStop(0, m.hi); g.addColorStop(0.45, m.mid); g.addColorStop(1, m.lo); + return g; +} + +function gilt(ctx, x, y, w, h, r, width = 3, m = TIER_METAL[3]) { + ctx.save(); + rr(ctx, x, y, w, h, r); + ctx.strokeStyle = metalGrad(ctx, x, y, w, h, m); + ctx.lineWidth = width; + ctx.stroke(); + ctx.restore(); +} + +function engraved(ctx, text, x, y, size, { color = 'rgba(240,220,170,0.9)', align = 'center', font = SERIF, weight = 'bold', spacing = 0, shadow = 'rgba(0,0,0,0.6)' } = {}) { + ctx.save(); + ctx.font = `${weight} ${size}px ${font}`; + ctx.textAlign = align; + ctx.textBaseline = 'middle'; + if (spacing && 'letterSpacing' in ctx) ctx.letterSpacing = `${spacing}px`; + ctx.fillStyle = shadow; + ctx.fillText(text, x, y + Math.max(1, size * 0.05)); + ctx.fillStyle = color; + ctx.fillText(text, x, y); + ctx.restore(); +} + +function shadowed(ctx, fn, { blur = 16, dy = 6, alpha = 0.55 } = {}) { + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; + ctx.shadowOffsetY = dy; + fn(); + ctx.restore(); +} + +function sheetImage(scene, key) { + if (!scene.textures.exists(key)) return null; + try { return scene.textures.get(key).getSourceImage(); } catch (_) { return null; } +} + +// A cut gem: the user's sprite when present, else a faceted polygon. +function drawGem(scene, ctx, color, cx, cy, size) { + const src = sheetImage(scene, 'splendor-gems'); + if (src) { + ctx.drawImage(src, gemFrame(color) * 64, 0, 64, 64, cx - size / 2, cy - size / 2, size, size); + return; + } + const c = GEM_CSS[color]; + const r = size * 0.42; + ctx.save(); + ctx.beginPath(); + for (let i = 0; i < 8; i++) { + const a = (i / 8) * Math.PI * 2 + Math.PI / 8; + ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r * 0.9); + } + ctx.closePath(); + const g = ctx.createRadialGradient(cx - r * 0.3, cy - r * 0.35, r * 0.1, cx, cy, r); + g.addColorStop(0, c.hi); g.addColorStop(0.55, c.mid); g.addColorStop(1, c.lo); + ctx.fillStyle = g; ctx.fill(); + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; ctx.lineWidth = Math.max(1, size / 40); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(cx - r * 0.5, cy - r * 0.2); ctx.lineTo(cx, cy - r * 0.6); ctx.lineTo(cx + r * 0.5, cy - r * 0.2); ctx.lineTo(cx, cy + r * 0.7); ctx.closePath(); + ctx.strokeStyle = 'rgba(255,255,255,0.22)'; ctx.stroke(); + ctx.restore(); +} + +// A glossy gem-coloured pip with a number. +function pip(ctx, color, cx, cy, r, label, size) { + const c = GEM_CSS[color]; + ctx.save(); + ctx.beginPath(); ctx.arc(cx, cy + r * 0.08, r, 0, Math.PI * 2); ctx.fillStyle = 'rgba(0,0,0,0.55)'; ctx.fill(); + ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); + const g = ctx.createRadialGradient(cx - r * 0.35, cy - r * 0.4, r * 0.1, cx, cy, r); + g.addColorStop(0, c.hi); g.addColorStop(0.5, c.mid); g.addColorStop(1, c.lo); + ctx.fillStyle = g; ctx.fill(); + ctx.lineWidth = r * 0.14; ctx.strokeStyle = 'rgba(236,210,150,0.9)'; ctx.stroke(); + ctx.lineWidth = r * 0.06; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; + ctx.beginPath(); ctx.arc(cx, cy, r * 1.07, 0, Math.PI * 2); ctx.stroke(); + if (label != null) { + ctx.font = `bold ${size}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = color === 'white' || color === 'gold' ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.55)'; + ctx.fillText(label, cx + 1, cy + 2); + ctx.fillStyle = c.ink; + ctx.fillText(label, cx, cy + 1); + } + ctx.restore(); +} + +// ── the room ──────────────────────────────────────────────────────────────────────── +function bakeRoom(scene) { + const key = 'spl-room'; + if (scene.textures.exists(key)) return; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + + // Damask wall. + const wg = ctx.createLinearGradient(0, 0, 0, WALL.h); + wg.addColorStop(0, '#16261c'); wg.addColorStop(1, '#0f1c14'); + ctx.fillStyle = wg; ctx.fillRect(0, 0, W, WALL.h); + ctx.save(); + ctx.globalAlpha = 0.16; + for (let y = -20; y < WALL.h + 40; y += 64) { + for (let x = ((y / 64) % 2) * 40 - 40; x < W + 60; x += 80) { + ctx.strokeStyle = '#7fae7a'; ctx.lineWidth = 1.4; + ctx.beginPath(); + ctx.moveTo(x, y - 22); ctx.bezierCurveTo(x + 18, y - 10, x + 18, y + 10, x, y + 22); + ctx.bezierCurveTo(x - 18, y + 10, x - 18, y - 10, x, y - 22); + ctx.stroke(); + ctx.beginPath(); ctx.arc(x, y, 4, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x - 12, y); ctx.quadraticCurveTo(x - 26, y - 14, x - 34, y); ctx.moveTo(x + 12, y); ctx.quadraticCurveTo(x + 26, y - 14, x + 34, y); ctx.stroke(); + } + } + ctx.restore(); + ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(0, 0, W, WALL.h); + // Picture rail and chair rail. + ctx.fillStyle = metalGrad(ctx, 0, 0, W, 6); ctx.fillRect(0, 0, W, 4); + const rail = ctx.createLinearGradient(0, WALL.h - 4, 0, WALL.h + 10); + rail.addColorStop(0, '#6a4024'); rail.addColorStop(0.5, '#3a2210'); rail.addColorStop(1, '#1c0e06'); + ctx.fillStyle = rail; ctx.fillRect(0, WALL.h - 4, W, 14); + ctx.fillStyle = 'rgba(255,220,160,0.12)'; ctx.fillRect(0, WALL.h - 4, W, 1); + + // Walnut desk. + const PH = 110; + const tones = ['#3e2414', '#452817', '#3a2112', '#48291a', '#402515', '#4a2c1a']; + for (let i = 0, y = WALL.h + 10; y < H; i++, y += PH) { + const g = ctx.createLinearGradient(0, y, 0, y + PH); + g.addColorStop(0, tones[i % tones.length]); g.addColorStop(1, mix(tones[i % tones.length], '#140904', 0.3)); + ctx.fillStyle = g; ctx.fillRect(0, y, W, PH); + ctx.save(); ctx.beginPath(); ctx.rect(0, y, W, PH); ctx.clip(); + grain(ctx, 0, y, W, PH, { seed: i + 3, spacing: 5 }); + ctx.restore(); + ctx.fillStyle = 'rgba(8,4,1,0.6)'; ctx.fillRect(0, y, W, 2); + } + ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(0, WALL.h + 10, W, H - WALL.h - 10); + + // Baize counting cloth under the market, with brass corners. + const m = MARKET; + shadowed(ctx, () => { rr(ctx, m.x, m.y, m.w, m.h, 14); ctx.fillStyle = '#123224'; ctx.fill(); }, { blur: 20, dy: 8, alpha: 0.6 }); + ctx.save(); + rr(ctx, m.x, m.y, m.w, m.h, 14); ctx.clip(); + const bz = ctx.createRadialGradient(m.x + m.w * 0.55, m.y + m.h * 0.45, 40, m.x + m.w / 2, m.y + m.h / 2, m.w * 0.7); + bz.addColorStop(0, '#1f5a3e'); bz.addColorStop(1, '#0d2a1c'); + ctx.fillStyle = bz; ctx.fillRect(m.x, m.y, m.w, m.h); + ctx.fillStyle = noisePattern(ctx, 48, 26); ctx.fillRect(m.x, m.y, m.w, m.h); + ctx.restore(); + ctx.strokeStyle = 'rgba(214,178,96,0.55)'; ctx.lineWidth = 2; + rr(ctx, m.x + 6, m.y + 6, m.w - 12, m.h - 12, 10); ctx.stroke(); + for (const [x, y, sx, sy] of [[m.x, m.y, 1, 1], [m.x + m.w, m.y, -1, 1], [m.x, m.y + m.h, 1, -1], [m.x + m.w, m.y + m.h, -1, -1]]) { + ctx.save(); ctx.translate(x, y); ctx.scale(sx, sy); + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(34, 0); ctx.lineTo(34, 6); ctx.lineTo(6, 6); ctx.lineTo(6, 34); ctx.lineTo(0, 34); ctx.closePath(); + ctx.fillStyle = metalGrad(ctx, 0, 0, 34, 34); ctx.fill(); + ctx.restore(); + } + + // Gallery: a darker panel where the patrons hang. + const gl = GALLERY; + ctx.save(); + rr(ctx, gl.x, gl.y, gl.w, gl.h, 8); + ctx.fillStyle = 'rgba(0,0,0,0.25)'; ctx.fill(); + ctx.restore(); + addCanvas(scene, key, c); +} + +function bakeLight(scene) { + const key = 'spl-light'; + if (scene.textures.exists(key)) return; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(640, 470, 60, 700, 520, 1200); + g.addColorStop(0, 'rgba(255,200,120,0.10)'); + g.addColorStop(0.35, 'rgba(255,190,110,0.03)'); + g.addColorStop(0.7, 'rgba(0,0,0,0.18)'); + g.addColorStop(1, 'rgba(0,0,0,0.5)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); + addCanvas(scene, key, c); +} + +// ── the Guild Register (prestige track) ───────────────────────────────────────────── +function bakeTrack(scene) { + const key = 'spl-track'; + if (scene.textures.exists(key)) return; + const t = TRACK; + const c = canvas(t.w, t.h); + const ctx = c.getContext('2d'); + shadowed(ctx, () => { rr(ctx, 4, 4, t.w - 8, t.h - 10, 12); ctx.fillStyle = '#3a2412'; ctx.fill(); }, { blur: 10, dy: 4 }); + ctx.save(); + rr(ctx, 4, 4, t.w - 8, t.h - 10, 12); ctx.clip(); + const lg = ctx.createLinearGradient(0, 0, 0, t.h); + lg.addColorStop(0, '#4a2e18'); lg.addColorStop(1, '#2a180a'); + ctx.fillStyle = lg; ctx.fillRect(0, 0, t.w, t.h); + grain(ctx, 0, 0, t.w, t.h, { seed: 41, spacing: 5 }); + ctx.restore(); + gilt(ctx, 10, 10, t.w - 20, t.h - 22, 9, 2); + + // Title with a little balance scale. + engraved(ctx, 'THE GUILD REGISTER', t.w / 2, 30, 17, { font: DISPLAY, color: 'rgba(236,206,140,0.95)', spacing: 2 }); + const bx = t.w / 2 - 150, by = 30; + for (const sx of [bx, t.w - bx]) { + ctx.save(); ctx.translate(sx, by); + ctx.strokeStyle = BRASS; ctx.fillStyle = BRASS; ctx.lineWidth = 1.6; + ctx.beginPath(); ctx.moveTo(0, -10); ctx.lineTo(0, 9); ctx.moveTo(-6, 10); ctx.lineTo(6, 10); ctx.moveTo(-13, -6); ctx.lineTo(13, -6); ctx.stroke(); + for (const px of [-13, 13]) { ctx.beginPath(); ctx.moveTo(px - 5, 2); ctx.lineTo(px, -6); ctx.lineTo(px + 5, 2); ctx.stroke(); ctx.beginPath(); ctx.ellipse(px, 3, 6, 2, 0, 0, Math.PI); ctx.fill(); } + ctx.restore(); + } + + // The brass rule. + const y = TRACK_RULE.y - t.y, x0 = TRACK_RULE.x0 - t.x, x1 = TRACK_RULE.x1 - t.x; + ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fillRect(x0 - 4, y - 3, x1 - x0 + 8, 9); + ctx.fillStyle = metalGrad(ctx, x0, y - 4, x1 - x0, 8); ctx.fillRect(x0 - 4, y - 4, x1 - x0 + 8, 7); + for (let p = 0; p <= 15; p++) { + const x = trackX(p) - t.x; + const major = p % 5 === 0; + ctx.fillStyle = BRASS; + ctx.fillRect(x - 1, y - (major ? 16 : 10), 2, major ? 12 : 6); + engraved(ctx, String(p), x, y + 24, major ? 15 : 12, { color: major ? 'rgba(244,222,170,0.95)' : 'rgba(220,196,150,0.7)' }); + } + // Crown at 15. + const cx = trackX(15) - t.x + 40, cy = y - 2; + ctx.save(); ctx.translate(cx, cy); + ctx.beginPath(); + ctx.moveTo(-16, 10); ctx.lineTo(-18, -8); ctx.lineTo(-8, 0); ctx.lineTo(0, -14); ctx.lineTo(8, 0); ctx.lineTo(18, -8); ctx.lineTo(16, 10); ctx.closePath(); + ctx.fillStyle = metalGrad(ctx, -18, -14, 36, 24); ctx.fill(); + ctx.strokeStyle = '#5a3a10'; ctx.lineWidth = 1.2; ctx.stroke(); + for (const [gx, gc] of [[-9, 'red'], [0, 'blue'], [9, 'green']]) { ctx.beginPath(); ctx.arc(gx, 4, 2.6, 0, Math.PI * 2); ctx.fillStyle = GEM_CSS[gc].mid; ctx.fill(); } + ctx.restore(); + engraved(ctx, 'victory', cx, y + 24, 11, { weight: 'italic', color: 'rgba(230,200,140,0.8)' }); + addCanvas(scene, key, c); +} + +// ── row plaques ────────────────────────────────────────────────────────────────────── +function bakePlaques(scene) { + for (const tier of [1, 2, 3]) { + const key = `spl-plaque-${tier}`; + if (scene.textures.exists(key)) continue; + const w = 40 * 2, h = (CH - 12) * 2; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + shadowed(ctx, () => { rr(ctx, 6, 4, w - 12, h - 10, 12); ctx.fillStyle = metalGrad(ctx, 0, 0, w, h, TIER_METAL[tier]); ctx.fill(); }, { blur: 8, dy: 3 }); + rr(ctx, 12, 10, w - 24, h - 22, 8); ctx.strokeStyle = 'rgba(60,30,8,0.5)'; ctx.lineWidth = 2; ctx.stroke(); + for (const [sx, sy] of [[w / 2, 20], [w / 2, h - 26]]) { ctx.beginPath(); ctx.arc(sx, sy, 4, 0, Math.PI * 2); ctx.fillStyle = 'rgba(60,30,8,0.6)'; ctx.fill(); } + ctx.save(); + ctx.translate(w / 2, h / 2); ctx.rotate(-Math.PI / 2); + engraved(ctx, TIER_NAME[tier].toUpperCase(), 0, -4, 19, { font: DISPLAY, color: 'rgba(54,28,6,0.92)', shadow: 'rgba(255,240,200,0.45)', spacing: 1 }); + engraved(ctx, '★'.repeat(tier), 0, 20, 15, { color: 'rgba(54,28,6,0.8)', shadow: 'rgba(255,240,200,0.4)' }); + ctx.restore(); + addCanvas(scene, key, c); + } +} + +// ── the jewel case ─────────────────────────────────────────────────────────────────── +function bakeCase(scene) { + const key = 'spl-case'; + if (scene.textures.exists(key)) return; + const b = BANK; + const pad = 16; + const c = canvas(b.w + pad * 2, b.h + pad * 2); + const ctx = c.getContext('2d'); + shadowed(ctx, () => { rr(ctx, pad, pad, b.w, b.h, 14); ctx.fillStyle = '#3a200e'; ctx.fill(); }, { blur: 18, dy: 8, alpha: 0.7 }); + ctx.save(); + rr(ctx, pad, pad, b.w, b.h, 14); ctx.clip(); + const wg = ctx.createLinearGradient(pad, 0, pad + b.w, 0); + wg.addColorStop(0, '#5a321a'); wg.addColorStop(0.5, '#6e4024'); wg.addColorStop(1, '#4a2812'); + ctx.fillStyle = wg; ctx.fillRect(pad, pad, b.w, b.h); + grain(ctx, pad, pad, b.w, b.h, { seed: 9, spacing: 4 }); + ctx.restore(); + gilt(ctx, pad + 4, pad + 4, b.w - 8, b.h - 8, 11, 2.5); + for (const color of BANK_ORDER) { + const cell = bankCell(color); + const x = cell.x - b.x + pad, y = cell.y - b.y + pad; + // Velvet well. + ctx.save(); + rr(ctx, x, y, cell.w, cell.h, 10); + ctx.fillStyle = '#1a0306'; ctx.fill(); + ctx.clip(); + const vg = ctx.createRadialGradient(x + 50, y + cell.h / 2, 6, x + 50, y + cell.h / 2, cell.w * 0.8); + vg.addColorStop(0, '#6e1424'); vg.addColorStop(0.6, '#3e0812'); vg.addColorStop(1, '#1a0306'); + ctx.fillStyle = vg; ctx.fillRect(x, y, cell.w, cell.h); + ctx.fillStyle = noisePattern(ctx, 32, 30); ctx.fillRect(x, y, cell.w, cell.h); + // inner shadow + ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.lineWidth = 6; rr(ctx, x - 2, y - 2, cell.w + 4, cell.h + 4, 12); ctx.stroke(); + ctx.restore(); + rr(ctx, x, y, cell.w, cell.h, 10); ctx.strokeStyle = 'rgba(214,178,96,0.45)'; ctx.lineWidth = 1.2; ctx.stroke(); + // Name plate. + const px = x + cell.w - 64, py = y + cell.h - 22; + rr(ctx, px, py, 56, 16, 4); ctx.fillStyle = metalGrad(ctx, px, py, 56, 16); ctx.fill(); + engraved(ctx, GEM_NAME[color].toUpperCase(), px + 28, py + 8.5, 8.5, { color: 'rgba(54,28,6,0.95)', shadow: 'rgba(255,240,200,0.4)', spacing: 0.5 }); + } + engraved(ctx, 'THE JEWEL CASE', pad + b.w / 2, pad + b.h - 4, 9, { color: 'rgba(236,206,140,0.6)' }); + addCanvas(scene, key, c); +} + +// ── ledgers ────────────────────────────────────────────────────────────────────────── +export function ledgerKey(L) { return `spl-ledger-${L.w}x${L.h}${L.human ? '-h' : ''}`; } +export function ensureLedger(scene, L) { + const key = ledgerKey(L); + if (scene.textures.exists(key)) return key; + const pad = 14; + const c = canvas(L.w + pad * 2, L.h + pad * 2); + const ctx = c.getContext('2d'); + const ox = pad - L.x, oy = pad - L.y; + shadowed(ctx, () => { rr(ctx, pad, pad, L.w, L.h, 14); ctx.fillStyle = '#21150c'; ctx.fill(); }, { blur: 16, dy: 6, alpha: 0.65 }); + ctx.save(); + rr(ctx, pad, pad, L.w, L.h, 14); ctx.clip(); + const lg = ctx.createLinearGradient(0, pad, 0, pad + L.h); + lg.addColorStop(0, L.human ? '#3a2616' : '#30200f'); lg.addColorStop(1, L.human ? '#24160b' : '#1e1309'); + ctx.fillStyle = lg; ctx.fillRect(pad, pad, L.w, L.h); + ctx.fillStyle = noisePattern(ctx, 64, 22); ctx.fillRect(pad, pad, L.w, L.h); + ctx.restore(); + // Tooled border. + gilt(ctx, pad + 5, pad + 5, L.w - 10, L.h - 10, 10, 1.6); + ctx.save(); + ctx.setLineDash([2, 4]); ctx.strokeStyle = 'rgba(214,178,96,0.3)'; ctx.lineWidth = 1; + rr(ctx, pad + 10, pad + 10, L.w - 20, L.h - 20, 8); ctx.stroke(); + ctx.restore(); + + const P = ledgerParts(L); + // Header block divider. + ctx.fillStyle = 'rgba(214,178,96,0.22)'; ctx.fillRect(L.x + 180 + ox, L.y + 18 + oy, 1, L.h - 36); + // Colour wells. + for (const g of GEMS) { + const col = P.cols[g]; + const x = col.x + 4 + ox, y = col.stackTop - 8 + oy, w = col.w - 8, h = L.h - 34 - (col.stackTop - L.y) + 22; + ctx.save(); + rr(ctx, x, y, w, h, 8); ctx.fillStyle = 'rgba(0,0,0,0.22)'; ctx.fill(); + ctx.strokeStyle = 'rgba(214,178,96,0.18)'; ctx.lineWidth = 1; ctx.stroke(); + ctx.restore(); + // ghost card outline where the stack begins + ctx.save(); + ctx.setLineDash([4, 4]); ctx.strokeStyle = 'rgba(214,178,96,0.2)'; + rr(ctx, col.cx - 30 + ox, col.stackTop + oy, 60, 83, 6); ctx.stroke(); + ctx.restore(); + ctx.globalAlpha = 0.28; + drawGem(scene, ctx, g, col.cx + ox, col.stackTop + 41 + oy, 30); + ctx.globalAlpha = 1; + } + // Gold well. + { + const x = P.gold.cx - 32 + ox, y = P.cols.white.stackTop - 8 + oy, w = 64, h = L.h - 34 - (P.cols.white.stackTop - L.y) + 22; + rr(ctx, x, y, w, h, 8); ctx.fillStyle = 'rgba(0,0,0,0.18)'; ctx.fill(); + engraved(ctx, 'GOLD', P.gold.cx + ox, y + 18, 10, { color: 'rgba(236,206,140,0.55)' }); + } + // Reserve slots. + engraved(ctx, 'RESERVED', P.reserveLabel.x + ox, P.reserveLabel.y + oy, 10, { color: 'rgba(236,206,140,0.55)', spacing: 1.5 }); + for (const r of P.reserve) { + ctx.save(); + ctx.setLineDash([5, 4]); ctx.strokeStyle = 'rgba(214,178,96,0.3)'; ctx.lineWidth = 1.2; + rr(ctx, r.x + ox, r.y + oy, r.w, r.h, 7); ctx.stroke(); + ctx.restore(); + } + return addCanvas(scene, key, c); +} + +function bakeDock(scene) { + const key = 'spl-dock'; + if (scene.textures.exists(key)) return; + const d = DOCK, pad = 12; + const c = canvas(d.w + pad * 2, d.h + pad * 2); + const ctx = c.getContext('2d'); + shadowed(ctx, () => { rr(ctx, pad, pad, d.w, d.h, 12); ctx.fillStyle = '#2a1a0c'; ctx.fill(); }, { blur: 14, dy: 5 }); + ctx.save(); + rr(ctx, pad, pad, d.w, d.h, 12); ctx.clip(); + const g = ctx.createLinearGradient(0, pad, 0, pad + d.h); + g.addColorStop(0, '#efe0bd'); g.addColorStop(1, '#d9c497'); + ctx.fillStyle = g; ctx.fillRect(pad, pad, d.w, d.h); + ctx.fillStyle = noisePattern(ctx, 64, 26); ctx.fillRect(pad, pad, d.w, d.h); + ctx.restore(); + gilt(ctx, pad + 3, pad + 3, d.w - 6, d.h - 6, 10, 3, TIER_METAL[1]); + // Tray recess (three velvet hollows). + const tx = pad + 520, ty = pad + d.h / 2; + rr(ctx, tx - 14, ty - 34, 3 * 56 + 16, 68, 30); ctx.fillStyle = '#3e0812'; ctx.fill(); + rr(ctx, tx - 14, ty - 34, 3 * 56 + 16, 68, 30); ctx.strokeStyle = 'rgba(160,110,40,0.8)'; ctx.lineWidth = 2; ctx.stroke(); + for (let i = 0; i < 3; i++) { ctx.beginPath(); ctx.arc(tx + 26 + i * 56, ty, 22, 0, Math.PI * 2); ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fill(); } + addCanvas(scene, key, c); +} +export const TRAY_SLOT = (i) => ({ x: DOCK.x + 520 + 26 + i * 56, y: DOCK.y + DOCK.h / 2 }); + +// ── cards ──────────────────────────────────────────────────────────────────────────── +export function cardKey(card) { return `spl-card-${card.id}`; } +export function ensureCardFace(scene, card) { + const key = cardKey(card); + if (scene.textures.exists(key)) return key; + const w = FACE_W, h = FACE_H; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + const metal = TIER_METAL[card.tier]; + const gc = GEM_CSS[card.bonus]; + ctx.save(); + rr(ctx, 0, 0, w, h, 16); ctx.clip(); + const src = sheetImage(scene, 'splendor-cards'); + if (src) { + const f = cardFrame(card); + const sx = (f % 8) * 270, sy = Math.floor(f / 8) * 390; + ctx.drawImage(src, sx, sy + 8, 270, 371, 0, 0, w, h); + } else { + const g = ctx.createLinearGradient(0, 0, w, h); + g.addColorStop(0, gc.mid); g.addColorStop(1, gc.lo); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + ctx.globalAlpha = 0.25; drawGem(scene, ctx, card.bonus, w / 2, h / 2 + 20, 170); ctx.globalAlpha = 1; + } + // Top band for points + bonus. + const tb = ctx.createLinearGradient(0, 0, 0, 104); + tb.addColorStop(0, 'rgba(14,8,3,0.86)'); tb.addColorStop(0.65, 'rgba(14,8,3,0.5)'); tb.addColorStop(1, 'rgba(14,8,3,0)'); + ctx.fillStyle = tb; ctx.fillRect(0, 0, w, 104); + // Bottom-left wash behind the cost chips. + const costs = GEMS.filter((g) => (card.cost[g] ?? 0) > 0); + const bl = ctx.createRadialGradient(10, h - 10, 10, 10, h - 10, 70 + costs.length * 52); + bl.addColorStop(0, 'rgba(10,6,2,0.7)'); bl.addColorStop(1, 'rgba(10,6,2,0)'); + ctx.fillStyle = bl; ctx.fillRect(0, h - 70 - costs.length * 54, 150, 70 + costs.length * 54); + ctx.restore(); + + if (card.points > 0) { + ctx.save(); + ctx.font = `bold 62px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.lineWidth = 6; ctx.strokeStyle = 'rgba(0,0,0,0.75)'; + ctx.strokeText(String(card.points), 40, 46); + ctx.fillStyle = metalGrad(ctx, 20, 16, 40, 60, TIER_METAL[3]); + ctx.fillText(String(card.points), 40, 46); + ctx.restore(); + } + // Bonus gem in a bezel. + const bx = w - 46, by = 44; + ctx.beginPath(); ctx.arc(bx, by + 2, 33, 0, Math.PI * 2); ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fill(); + ctx.beginPath(); ctx.arc(bx, by, 32, 0, Math.PI * 2); + const bez = ctx.createRadialGradient(bx, by, 8, bx, by, 32); + bez.addColorStop(0, gc.lo); bez.addColorStop(1, '#0c0804'); + ctx.fillStyle = bez; ctx.fill(); + ctx.lineWidth = 5; ctx.strokeStyle = metalGrad(ctx, bx - 32, by - 32, 64, 64, metal); ctx.stroke(); + drawGem(scene, ctx, card.bonus, bx, by, 50); + + // Cost chips. + costs.forEach((g, i) => pip(ctx, g, 36, h - 36 - i * 50, 22, String(card.cost[g]), 26)); + + // Frame. + rr(ctx, 2, 2, w - 4, h - 4, 15); ctx.lineWidth = 5; ctx.strokeStyle = 'rgba(10,6,2,0.9)'; ctx.stroke(); + rr(ctx, 4, 4, w - 8, h - 8, 13); ctx.lineWidth = 4; ctx.strokeStyle = metalGrad(ctx, 0, 0, w, h, metal); ctx.stroke(); + rr(ctx, 9, 9, w - 18, h - 18, 10); ctx.lineWidth = 1.2; ctx.strokeStyle = 'rgba(255,240,200,0.25)'; ctx.stroke(); + return addCanvas(scene, key, c); +} + +export function backKey(tier) { return `spl-back-${tier}`; } +function bakeBacks(scene) { + for (const tier of [1, 2, 3]) { + const key = backKey(tier); + if (scene.textures.exists(key)) continue; + const w = FACE_W, h = FACE_H; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + const metal = TIER_METAL[tier]; + ctx.save(); + rr(ctx, 0, 0, w, h, 16); ctx.clip(); + const src = sheetImage(scene, 'splendor-cards'); + if (src) { + const f = deckBackFrame(tier); + ctx.drawImage(src, (f % 8) * 270, Math.floor(f / 8) * 390 + 8, 270, 371, 0, 0, w, h); + } else { + const g = ctx.createLinearGradient(0, 0, w, h); + g.addColorStop(0, ['#3a2a18', '#2a3a1a', '#1a2a4a'][tier - 1]); g.addColorStop(1, '#0a0604'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + engraved(ctx, '★'.repeat(tier), w / 2, h / 2, 48, { color: BRASS }); + } + ctx.restore(); + rr(ctx, 2, 2, w - 4, h - 4, 15); ctx.lineWidth = 5; ctx.strokeStyle = 'rgba(10,6,2,0.9)'; ctx.stroke(); + rr(ctx, 4, 4, w - 8, h - 8, 13); ctx.lineWidth = 4; ctx.strokeStyle = metalGrad(ctx, 0, 0, w, h, metal); ctx.stroke(); + addCanvas(scene, key, c); + } +} + +// ── nobles ─────────────────────────────────────────────────────────────────────────── +export function nobleKey(noble) { return `spl-noble-${noble.id}`; } +export function ensureNoble(scene, noble) { + const key = nobleKey(noble); + if (scene.textures.exists(key)) return key; + const w = NOBLE_TW, h = NOBLE_TH, ph = 224; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + // Portrait. + ctx.save(); + rr(ctx, 12, 12, w - 24, ph - 24, 6); ctx.clip(); + const src = sheetImage(scene, 'splendor-cards'); + if (src) { + const f = nobleFrame(noble); + ctx.drawImage(src, (f % 8) * 270 + 10, Math.floor(f / 8) * 390 + 18, 250, 250, 12, 12, w - 24, ph - 24); + } else { + const g = ctx.createRadialGradient(w / 2, ph * 0.4, 10, w / 2, ph / 2, w * 0.6); + g.addColorStop(0, '#6a4a2a'); g.addColorStop(1, '#1a0e06'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, ph); + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.beginPath(); ctx.arc(w / 2, ph * 0.42, 40, 0, Math.PI * 2); ctx.fill(); + ctx.beginPath(); ctx.ellipse(w / 2, ph + 10, 80, 70, 0, Math.PI, 0); ctx.fill(); + } + ctx.restore(); + // Gilt frame. + ctx.save(); + ctx.lineWidth = 14; + rr(ctx, 6, 6, w - 12, ph - 12, 10); ctx.strokeStyle = metalGrad(ctx, 0, 0, w, ph); ctx.stroke(); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(60,30,6,0.8)'; + rr(ctx, 12, 12, w - 24, ph - 24, 6); ctx.stroke(); + rr(ctx, 1, 1, w - 2, ph - 2, 12); ctx.stroke(); + ctx.restore(); + // Prestige badge. + ctx.beginPath(); ctx.arc(34, 34, 22, 0, Math.PI * 2); ctx.fillStyle = 'rgba(20,10,2,0.85)'; ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = metalGrad(ctx, 12, 12, 44, 44); ctx.stroke(); + engraved(ctx, '3', 34, 35, 28, { color: '#f4d47a' }); + // Requirement plate. + shadowed(ctx, () => { rr(ctx, 14, ph - 2, w - 28, h - ph - 4, 8); ctx.fillStyle = '#3a2210'; ctx.fill(); }, { blur: 6, dy: 3 }); + rr(ctx, 14, ph - 2, w - 28, h - ph - 4, 8); ctx.lineWidth = 2; ctx.strokeStyle = metalGrad(ctx, 14, ph, w - 28, 50); ctx.stroke(); + const reqs = Object.entries(noble.requires); + const step = 50, x0 = w / 2 - ((reqs.length - 1) * step) / 2; + reqs.forEach(([color, n], i) => pip(ctx, color, x0 + i * step, ph + (h - ph) / 2 - 3, 19, String(n), 22)); + return addCanvas(scene, key, c); +} + +// ── tokens ─────────────────────────────────────────────────────────────────────────── +export function chipKey(color) { return `spl-chip-${color}`; } +function bakeChips(scene) { + for (const color of [...GEMS, GOLD]) { + const key = chipKey(color); + if (scene.textures.exists(key)) continue; + const s = CHIP_PX, r = s / 2 - 4, cx = s / 2, cy = s / 2; + const c = canvas(s, s); + const ctx = c.getContext('2d'); + const gc = GEM_CSS[color]; + // Edge (gives stacks their side). + ctx.beginPath(); ctx.arc(cx, cy + 3, r, 0, Math.PI * 2); ctx.fillStyle = gc.lo; ctx.fill(); + ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); + const g = ctx.createRadialGradient(cx - r * 0.3, cy - r * 0.35, r * 0.2, cx, cy, r); + g.addColorStop(0, gc.hi); g.addColorStop(0.55, gc.mid); g.addColorStop(1, gc.lo); + ctx.fillStyle = g; ctx.fill(); + // Inlay notches around the rim. + ctx.save(); + for (let i = 0; i < 12; i++) { + const a = (i / 12) * Math.PI * 2; + ctx.save(); ctx.translate(cx + Math.cos(a) * (r - 6), cy + Math.sin(a) * (r - 6)); ctx.rotate(a); + ctx.fillStyle = color === 'gold' ? 'rgba(90,50,6,0.55)' : 'rgba(255,244,214,0.7)'; + ctx.fillRect(-3, -5, 6, 10); + ctx.restore(); + } + ctx.restore(); + // Inner disc. + ctx.beginPath(); ctx.arc(cx, cy, r * 0.66, 0, Math.PI * 2); + const ig = ctx.createRadialGradient(cx, cy - 6, 4, cx, cy, r * 0.66); + ig.addColorStop(0, '#2a1c10'); ig.addColorStop(1, '#0c0804'); + ctx.fillStyle = ig; ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = metalGrad(ctx, cx - r, cy - r, 2 * r, 2 * r); ctx.stroke(); + drawGem(scene, ctx, color, cx, cy, r * 1.1); + ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.stroke(); + addCanvas(scene, key, c); + } +} + +// ── fx textures ────────────────────────────────────────────────────────────────────── +function bakeFx(scene) { + if (!scene.textures.exists('spl-glow')) { + const pad = 30, w = CW * 2, h = CH * 2; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.shadowColor = 'rgba(255,255,255,1)'; ctx.shadowBlur = 26; + ctx.lineWidth = 7; ctx.strokeStyle = 'rgba(255,255,255,0.95)'; + for (let i = 0; i < 2; i++) { rr(ctx, pad, pad, w, h, 18); ctx.stroke(); } + addCanvas(scene, 'spl-glow', c); + } + if (!scene.textures.exists('spl-spark')) { + const s = 24, c = canvas(s, s), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); + g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.3, 'rgba(255,255,255,0.7)'); g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, s, s); + ctx.fillStyle = 'rgba(255,255,255,0.95)'; + ctx.beginPath(); ctx.moveTo(s / 2, 0); ctx.lineTo(s / 2 + 1.5, s / 2 - 1.5); ctx.lineTo(s, s / 2); ctx.lineTo(s / 2 + 1.5, s / 2 + 1.5); + ctx.lineTo(s / 2, s); ctx.lineTo(s / 2 - 1.5, s / 2 + 1.5); ctx.lineTo(0, s / 2); ctx.lineTo(s / 2 - 1.5, s / 2 - 1.5); ctx.closePath(); ctx.fill(); + addCanvas(scene, 'spl-spark', c); + } + if (!scene.textures.exists('spl-dust')) { + const s = 12, c = canvas(s, s), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); + g.addColorStop(0, 'rgba(255,230,190,0.9)'); g.addColorStop(1, 'rgba(255,230,190,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, s, s); + addCanvas(scene, 'spl-dust', c); + } + if (!scene.textures.exists('spl-spot')) { + const s = 512, c = canvas(s, s), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); + g.addColorStop(0, 'rgba(255,214,150,0.55)'); g.addColorStop(0.5, 'rgba(255,190,110,0.18)'); g.addColorStop(1, 'rgba(255,190,110,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, s, s); + addCanvas(scene, 'spl-spot', c); + } + if (!scene.textures.exists('spl-glint')) { + const w = 90, h = 420, c = canvas(w, h), ctx = c.getContext('2d'); + const g = ctx.createLinearGradient(0, 0, w, 0); + g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(255,255,255,0.55)'); g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + addCanvas(scene, 'spl-glint', c); + } + if (!scene.textures.exists('spl-shadow')) { + const pad = 24, w = CW * 2, h = CH * 2, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'); + ctx.shadowColor = 'rgba(0,0,0,0.75)'; ctx.shadowBlur = 18; ctx.shadowOffsetX = 2000; + rr(ctx, pad - 2000, pad, w, h, 16); ctx.fillStyle = '#000'; ctx.fill(); + addCanvas(scene, 'spl-shadow', c); + } + if (!scene.textures.exists('spl-seal')) { + const s = 120, c = canvas(s, s), ctx = c.getContext('2d'); + const rnd = seeded(7); + ctx.beginPath(); + for (let i = 0; i <= 28; i++) { + const a = (i / 28) * Math.PI * 2, r = 52 + (rnd() - 0.5) * 8; + ctx.lineTo(s / 2 + Math.cos(a) * r, s / 2 + Math.sin(a) * r); + } + ctx.closePath(); + const g = ctx.createRadialGradient(s / 2 - 12, s / 2 - 14, 6, s / 2, s / 2, 56); + g.addColorStop(0, '#d0403a'); g.addColorStop(0.6, '#8e1a16'); g.addColorStop(1, '#4a0806'); + ctx.fillStyle = g; ctx.fill(); + ctx.beginPath(); ctx.arc(s / 2, s / 2, 36, 0, Math.PI * 2); ctx.lineWidth = 3; ctx.strokeStyle = 'rgba(40,0,0,0.45)'; ctx.stroke(); + // Crown imprint. + ctx.save(); ctx.translate(s / 2, s / 2 + 2); + ctx.beginPath(); ctx.moveTo(-20, 12); ctx.lineTo(-22, -8); ctx.lineTo(-10, 2); ctx.lineTo(0, -16); ctx.lineTo(10, 2); ctx.lineTo(22, -8); ctx.lineTo(20, 12); ctx.closePath(); + ctx.fillStyle = 'rgba(50,0,0,0.5)'; ctx.fill(); + ctx.restore(); + addCanvas(scene, 'spl-seal', c); + } + if (!scene.textures.exists('spl-flame')) { + const w = 24, h = 40, c = canvas(w, h), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(w / 2, h * 0.7, 1, w / 2, h * 0.6, h * 0.6); + g.addColorStop(0, 'rgba(255,255,220,1)'); g.addColorStop(0.35, 'rgba(255,200,80,0.95)'); g.addColorStop(1, 'rgba(255,120,20,0)'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.moveTo(w / 2, 0); ctx.quadraticCurveTo(w, h * 0.6, w / 2, h); ctx.quadraticCurveTo(0, h * 0.6, w / 2, 0); ctx.fill(); + addCanvas(scene, 'spl-flame', c); + } + if (!scene.textures.exists('spl-pawn')) { + const s = 48, c = canvas(s, s), ctx = c.getContext('2d'); + ctx.beginPath(); ctx.arc(s / 2, s / 2 + 2, 20, 0, Math.PI * 2); ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fill(); + ctx.beginPath(); ctx.arc(s / 2, s / 2, 20, 0, Math.PI * 2); + const g = ctx.createRadialGradient(s / 2 - 6, s / 2 - 7, 2, s / 2, s / 2, 20); + g.addColorStop(0, '#ffffff'); g.addColorStop(0.5, '#d8d8d8'); g.addColorStop(1, '#8a8a8a'); + ctx.fillStyle = g; ctx.fill(); + ctx.lineWidth = 2.5; ctx.strokeStyle = 'rgba(40,24,8,0.9)'; ctx.stroke(); + addCanvas(scene, 'spl-pawn', c); + } +} + +// ── entry point ────────────────────────────────────────────────────────────────────── +// Waits (briefly) for the display font so canvas text bakes in the right face. +export async function prepareSplendorArt(scene, ledgers = []) { + try { + if (document.fonts?.load) { + await Promise.race([ + Promise.all([document.fonts.load('20px Caesar'), document.fonts.load('14px "Julius Sans One"')]), + new Promise((res) => setTimeout(res, 1200)), + ]); + } + } catch (_) { /* fall back to Georgia */ } + bakeRoom(scene); + bakeLight(scene); + bakeTrack(scene); + bakePlaques(scene); + bakeCase(scene); + bakeDock(scene); + bakeBacks(scene); + bakeChips(scene); + bakeFx(scene); + for (const L of ledgers) ensureLedger(scene, L); + for (const n of NOBLES) ensureNoble(scene, n); + // Card faces bake lazily (ensureCardFace) — 90 of them would be ~32 MB. +} diff --git a/src/games/splendor/SplendorData.js b/src/games/splendor/SplendorData.js index 85880e4..489a5b4 100644 --- a/src/games/splendor/SplendorData.js +++ b/src/games/splendor/SplendorData.js @@ -143,3 +143,33 @@ export function nobleFrame(noble) { return 15 + noble.frame; } export function deckBackFrame(tier) { return 25 + (tier - 1); } // Gem spritesheet (splendor-gems): white(0) blue(1) green(2) red(3) black(4) gold(5) export function gemFrame(color) { return color === GOLD ? 5 : GEMS.indexOf(color); } + +// ── Counting-house flavour ─────────────────────────────────────────────────── +// The art tells a story: tier 1 cards are the mines, tier 2 the trade routes +// that carry the stones, tier 3 the merchant houses that sell them. +export const TIER_NAME = { 1: 'The Mines', 2: 'The Trade Routes', 3: 'The Merchant Houses' }; +export const TIER_NOUN = { 1: 'mine', 2: 'trade route', 3: 'merchant house' }; + +// One place name per card-art frame (cardFrame(card) → 0..14). Original names +// for the user's paintings. +export const LOCATION = [ + 'The Glacier Shaft', 'The Fen Barrow Adit', 'The Terraced Pit', 'The Red Canyon Mine', 'The Onyx Seam', + 'The High-Pass Yak Train', 'The Elephant Road', 'The Red-Sail Dhow', 'The Harbour Galleon', 'The Dune Caravan', + 'The Timbered House', 'The Tiled Bazaar House', 'The Corner Emporium', 'The Canal House', 'The Domed Exchange', +]; +export function locationOf(card) { return LOCATION[cardFrame(card)] ?? ''; } + +// The patrons (one per noble portrait, by noble.frame). +export const NOBLE_INFO = [ + { name: 'Count Aurelio', title: 'Master of the Mint' }, + { name: 'Sir Matthias', title: 'Warden of the Western Roads' }, + { name: 'Duke Edmund', title: 'Keeper of the Royal Seal' }, + { name: 'Lady Isabeau', title: 'Patroness of the Goldsmiths' }, + { name: 'Princess Catalina', title: 'Heir to the Coral Throne' }, + { name: 'Baron Lucien', title: 'Lord of the Salt Marches' }, + { name: 'Lady Margarethe', title: 'Mistress of the Harbour' }, + { name: 'Duke Ottavio', title: 'Elder of the Merchant Council' }, + { name: 'Countess Elise', title: 'Collector of Rare Stones' }, + { name: 'Lady Serafina', title: 'Patroness of the Night Market' }, +]; +export function nobleInfo(noble) { return NOBLE_INFO[noble.frame] ?? { name: 'A Noble', title: '' }; } diff --git a/src/games/splendor/SplendorDialogs.js b/src/games/splendor/SplendorDialogs.js new file mode 100644 index 0000000..e0cf42a --- /dev/null +++ b/src/games/splendor/SplendorDialogs.js @@ -0,0 +1,188 @@ +// SplendorDialogs.js — the counting house's pop-ups: a parchment card in a +// walnut frame. Each opener returns { close() } and swallows clicks beneath. +// +// openPauseMenu resume · pace · hints · rivals' reach · undo · ambience · rules · new game · leave +// confirmBox yes / no +// openReturn choose the tokens to hand back over the 10-gem limit +// openNobleChoice several patrons qualify — pick one + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { GEMS, GOLD, GEM_NAME, HAND_LIMIT, nobleInfo } from './SplendorData.js'; +import { tokenTotal } from './SplendorLogic.js'; +import { SERIF, DISPLAY, INK, chipKey, nobleKey } from './SplendorArt.js'; + +export function frame(scene, x, y, w, h, depth) { + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.5).fillRoundedRect(x + 4, y + 8, w, h, 14); + g.fillStyle(0x4a2a14, 1).fillRoundedRect(x, y, w, h, 14); + g.lineStyle(2, 0xd9b45a, 0.9).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 11); + g.fillStyle(0xf0e2c0, 1).fillRoundedRect(x + 10, y + 10, w - 20, h - 20, 8); + g.lineStyle(1.5, 0x8a6420, 0.8).strokeRoundedRect(x + 16, y + 16, w - 32, h - 32, 6); + return g; +} +export function blocker(scene, depth, alpha = 0) { + return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, alpha) + .setDepth(depth).setInteractive(); +} +export function title(scene, x, y, text, depth, size = 26) { + return scene.add.text(x, y, text, { fontFamily: DISPLAY, fontSize: `${size}px`, color: '#4a2008', align: 'center' }) + .setOrigin(0.5).setDepth(depth); +} +function handle(objs, onClose) { + let closed = false; + return { + objs, + close() { + if (closed) return; + closed = true; + objs.forEach((o) => o?.destroy?.()); + onClose?.(); + }, + }; +} + +const onOff = (v) => (v ? 'On' : 'Off'); +export const PACE_LABEL = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Brisk' }; + +// ── pause / settings ────────────────────────────────────────────────────────────────── +export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 520, h = 660; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 50, 'The Counting House', depth + 1, 28)); + const cx = x + w / 2; + let hRef = null; + const rows = [ + ['Resume', () => hRef.close(), 0x2a4a30], + [() => `Pace: ${PACE_LABEL[settings.pace]}`, () => { + const order = ['relaxed', 'normal', 'fast']; + onChange('pace', order[(order.indexOf(settings.pace) + 1) % order.length]); + }], + [() => `Buying hints: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)], + [() => `Rivals' reach markers: ${onOff(settings.reach)}`, () => onChange('reach', !settings.reach)], + [() => `Undo last move: ${onOff(settings.undo)}`, () => onChange('undo', !settings.undo)], + [() => `Lamp & dust ambience: ${onOff(settings.ambient)}`, () => onChange('ambient', !settings.ambient)], + ['How to Play', () => onRules()], + ['New Game', () => { hRef.close(); onNewGame(); }, 0x6a4a1a], + ['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a2a1a], + ]; + rows.forEach(([label, fn, bg], i) => { + const text = typeof label === 'function' ? label() : label; + const btn = new Button(scene, cx, y + 110 + i * 54, text, () => { + fn(); + if (typeof label === 'function') btn.setLabel(label()); + }, { width: 420, height: 44, fontSize: 17, bg: bg ?? 0x5a3820 }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 34, 'Pace: Relaxed plays every showcase in full; Normal shortens rivals\'; Brisk skips them.\nKeys: 1–5 gems · Enter take · Esc clear · Z undo · M menu', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: w - 60 }, + }).setOrigin(0.5).setDepth(depth + 1)); + hRef = handle(objs, onClose); + return hRef; +} + +// ── confirm ───────────────────────────────────────────────────────────────────────────── +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 520, h = 250; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 48, heading, depth + 1, 24)); + objs.push(scene.add.text(x + w / 2, y + 108, text, { + fontFamily: SERIF, fontSize: '16px', color: INK, align: 'center', wordWrap: { width: w - 70 }, + }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + objs.push(new Button(scene, x + w / 2 - 116, y + h - 52, yes, () => { hRef.close(); onYes?.(); }, { width: 200, height: 46, fontSize: 18, bg: 0x2a4a30 }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 116, y + h - 52, no, () => { hRef.close(); onNo?.(); }, { width: 200, height: 46, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + objs[0].on('pointerdown', () => { hRef.close(); onNo?.(); }); + hRef = handle(objs); + return hRef; +} + +// ── hand back tokens ───────────────────────────────────────────────────────────────────── +// Starts from `suggested` (a colour → n map); click a chip in "Keep" to move it +// to "Return" and back. Confirm once exactly the excess is chosen. +export function openReturn(scene, { player, suggested = {}, depth, onDone }) { + const objs = [blocker(scene, depth - 1, 0.55)]; + const excess = tokenTotal(player) - HAND_LIMIT; + const w = 760, h = 420; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 46, 'Too Many Gems', depth + 1, 26)); + const sub = scene.add.text(x + w / 2, y + 84, '', { fontFamily: SERIF, fontSize: '16px', color: INK, align: 'center' }).setOrigin(0.5).setDepth(depth + 1); + objs.push(sub); + const order = [...GEMS, GOLD]; + const ret = {}; + for (const c of order) ret[c] = Math.min(player.tokens[c] ?? 0, suggested[c] ?? 0); + let dyn = []; + let confirmBtn = null; + const chosen = () => order.reduce((n, c) => n + ret[c], 0); + const draw = () => { + dyn.forEach((o) => o.destroy()); + dyn = []; + const left = excess - chosen(); + sub.setText(left > 0 ? `You may hold ${HAND_LIMIT}. Choose ${left} more to return to the case.` + : left < 0 ? `That is ${-left} too many — keep some back.` : 'Ready — these go back to the jewel case.'); + order.forEach((c, i) => { + const cx = x + 90 + i * 116; + const keep = (player.tokens[c] ?? 0) - ret[c]; + dyn.push(scene.add.text(cx, y + 124, GEM_NAME[c], { fontFamily: SERIF, fontSize: '13px', fontStyle: 'bold', color: '#4a2008' }).setOrigin(0.5).setDepth(depth + 1)); + const mk = (yy, n, label, fn) => { + const img = scene.add.image(cx, yy, chipKey(c)).setDisplaySize(58, 58).setDepth(depth + 1).setAlpha(n > 0 ? 1 : 0.2); + dyn.push(img); + dyn.push(scene.add.text(cx + 34, yy, `×${n}`, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'bold', color: INK }).setOrigin(0, 0.5).setDepth(depth + 1)); + if (n > 0) { img.setInteractive({ useHandCursor: true }); img.on('pointerdown', fn); } + void label; + }; + mk(y + 172, keep, 'keep', () => { ret[c]++; draw(); }); + mk(y + 270, ret[c], 'return', () => { ret[c]--; draw(); }); + }); + dyn.push(scene.add.text(x + 30, y + 172, 'Keep', { fontFamily: DISPLAY, fontSize: '15px', color: '#4a2008' }).setOrigin(0, 0.5).setAngle(-90).setDepth(depth + 1)); + dyn.push(scene.add.text(x + 30, y + 270, 'Return', { fontFamily: DISPLAY, fontSize: '15px', color: '#8a1a10' }).setOrigin(0, 0.5).setAngle(-90).setDepth(depth + 1)); + confirmBtn?.setEnabled?.(left === 0); + confirmBtn?.setAlpha(left === 0 ? 1 : 0.5); + }; + const g = scene.add.graphics().setDepth(depth); + g.lineStyle(1, 0x8a6420, 0.5).lineBetween(x + 50, y + 221, x + w - 50, y + 221); + objs.push(g); + let hRef = null; + confirmBtn = new Button(scene, x + w / 2, y + h - 48, 'Return to the case', () => { + if (chosen() !== excess) return; + const map = {}; + for (const c of order) if (ret[c]) map[c] = ret[c]; + hRef.close(); + onDone(map); + }, { width: 260, height: 46, fontSize: 18, bg: 0x2a4a30 }).setDepth(depth + 2); + objs.push(confirmBtn); + draw(); + hRef = handle(objs, () => dyn.forEach((o) => o.destroy())); + return hRef; +} + +// ── several patrons ────────────────────────────────────────────────────────────────────── +export function openNobleChoice(scene, { nobles, depth, onPick }) { + const objs = [blocker(scene, depth - 1, 0.55)]; + const w = 200 + nobles.length * 190, h = 400; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 46, 'Patrons Seek You Out', depth + 1, 26)); + objs.push(scene.add.text(x + w / 2, y + 82, 'Only one may visit this turn. Choose your patron.', { + fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: INK, + }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + nobles.forEach((n, i) => { + const cx = x + w / 2 + (i - (nobles.length - 1) / 2) * 190; + const img = scene.add.image(cx, y + 210, nobleKey(n)).setDisplaySize(140, 175).setDepth(depth + 1).setInteractive({ useHandCursor: true }); + img.on('pointerover', () => img.setDisplaySize(150, 187)); + img.on('pointerout', () => img.setDisplaySize(140, 175)); + img.on('pointerdown', () => { hRef.close(); onPick(n.id); }); + objs.push(img); + const info = nobleInfo(n); + objs.push(scene.add.text(cx, y + 318, info.name, { fontFamily: DISPLAY, fontSize: '16px', color: '#4a2008' }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(cx, y + 340, info.title, { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: 170 } }).setOrigin(0.5, 0).setDepth(depth + 1)); + }); + hRef = handle(objs); + return hRef; +} diff --git a/src/games/splendor/SplendorEndScreen.js b/src/games/splendor/SplendorEndScreen.js new file mode 100644 index 0000000..6e37d5a --- /dev/null +++ b/src/games/splendor/SplendorEndScreen.js @@ -0,0 +1,125 @@ +// SplendorEndScreen.js — "The Guild Ledger": the final page of the register. +// +// A ranked row per merchant: place, name, prestige, cards (the tiebreak), +// patrons, the bonus engine by colour, a prestige-over-turns line, and any +// honours earned. Play Again / Leave at the foot. Returns { close() }. + +import * as Phaser from 'phaser'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { GEMS, WIN_POINTS } from './SplendorData.js'; +import { finalRanking, awardsFor } from './SplendorLogic.js'; +import { SERIF, DISPLAY, INK, chipKey } from './SplendorArt.js'; +import { SEAT_HEX, SEAT_CSS } from './SplendorLayout.js'; +import { cameo } from './SplendorHud.js'; +import { burst } from './SplendorFx.js'; + +const ORD = ['1st', '2nd', '3rd', '4th']; + +export function showSplendorEndScreen(scene, { state, names, humanSeat = 0, depth, onPlayAgain, onLeave }) { + const objs = []; + const add = (o) => { objs.push(o); return o; }; + const ranking = finalRanking(state); + const awards = awardsFor(state); + const winner = ranking[0]; + + const dim = add(scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0).setDepth(depth).setInteractive()); + scene.tweens.add({ targets: dim, fillAlpha: 0.66, duration: 450 }); + + const rowH = 148; + const w = 1380, h = 220 + ranking.length * rowH; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + const page = add(scene.add.container(0, 0).setDepth(depth + 1)); + const g = scene.add.graphics(); + g.fillStyle(0x000000, 0.5).fillRoundedRect(x + 6, y + 10, w, h, 18); + g.fillStyle(0x3a2212, 1).fillRoundedRect(x, y, w, h, 18); + g.lineStyle(3, 0xd9b45a, 1).strokeRoundedRect(x + 6, y + 6, w - 12, h - 12, 14); + g.fillStyle(0xf2e4c2, 1).fillRoundedRect(x + 16, y + 16, w - 32, h - 32, 10); + // ruled lines + g.lineStyle(1, 0x9a8058, 0.35); + for (let yy = y + 150; yy < y + h - 70; yy += 24) g.lineBetween(x + 40, yy, x + w - 40, yy); + g.lineStyle(1.5, 0xb04a3a, 0.5).lineBetween(x + 120, y + 30, x + 120, y + h - 30); + page.add(g); + + page.add(scene.add.text(x + w / 2, y + 56, 'The Guild Ledger', { fontFamily: DISPLAY, fontSize: '40px', color: '#4a2008' }).setOrigin(0.5)); + const human = ranking.find((r) => r.seat === humanSeat); + const headline = winner.seat === humanSeat + ? (ranking[1] && ranking[1].place === 1 ? 'You share the guild\'s highest honour.' : 'Your house is named first merchant of the guild.') + : `${names[winner.seat]} is named first merchant of the guild.`; + page.add(scene.add.text(x + w / 2, y + 98, headline, { fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: INK }).setOrigin(0.5)); + const tb = winner.wonOnTiebreak ? `Tied on prestige — decided by fewest cards (${winner.cards} vs ${ranking[1].cards}).` : `Closed in round ${state.round - (state.phase === 'gameOver' ? 1 : 0)} · ${WIN_POINTS} prestige ends the game.`; + page.add(scene.add.text(x + w / 2, y + 124, tb, { fontFamily: SERIF, fontSize: '14px', color: '#6a4a28' }).setOrigin(0.5)); + + ranking.forEach((r, i) => { + const p = state.players[r.seat]; + const ry = y + 160 + i * rowH; + const rg = scene.add.graphics(); + if (r.seat === humanSeat) { rg.fillStyle(0xe6c98a, 0.35).fillRoundedRect(x + 30, ry - 4, w - 60, rowH - 10, 10); } + rg.fillStyle(SEAT_HEX[r.seat], 1).fillRect(x + 30, ry - 4, 6, rowH - 10); + page.add(rg); + page.add(scene.add.text(x + 78, ry + 50, ORD[r.place - 1], { fontFamily: DISPLAY, fontSize: r.place === 1 ? '36px' : '28px', color: r.place === 1 ? '#9a6a10' : '#5a4428' }).setOrigin(0.5)); + page.add(scene.add.text(x + 140, ry + 14, names[r.seat] + (r.seat === humanSeat ? ' (you)' : ''), { fontFamily: DISPLAY, fontSize: '24px', color: SEAT_CSS[r.seat], stroke: '#2a1408', strokeThickness: 3 })); + page.add(scene.add.text(x + 140, ry + 52, `${r.points}`, { fontFamily: SERIF, fontSize: '42px', fontStyle: 'bold', color: INK })); + page.add(scene.add.text(x + 140 + (r.points >= 10 ? 56 : 32), ry + 66, 'prestige', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#6a4a28' })); + page.add(scene.add.text(x + 140, ry + 104, `${r.cards} cards · ${p.nobles.length} patron${p.nobles.length === 1 ? '' : 's'} · ${p.stats.reserves} reserved`, { fontFamily: SERIF, fontSize: '13px', color: '#5a4428' })); + + // Patrons. + p.nobles.forEach((nb, k) => { + page.add(cameo(scene, nb, x + 400 + k * 48, ry + 40, 42, 0)); + const fr = scene.add.graphics(); + fr.lineStyle(2, 0xb8902a, 1).strokeRoundedRect(x + 400 + k * 48 - 21, ry + 19, 42, 42, 5); + page.add(fr); + }); + // Engine by colour. + GEMS.forEach((gc, k) => { + const cx = x + 400 + k * 58, cy = ry + 96; + page.add(scene.add.image(cx, cy, chipKey(gc)).setDisplaySize(40, 40)); + page.add(scene.add.text(cx + 15, cy + 12, String(p.bonuses[gc]), { fontFamily: SERIF, fontSize: '16px', fontStyle: 'bold', color: INK, stroke: '#f2e4c2', strokeThickness: 4 }).setOrigin(0.5)); + }); + + // Prestige over the turns. + const sx = x + 720, sy = ry + 10, sw = 260, sh = 100; + const pts = p.stats.pointsByTurn; + const top = Math.max(WIN_POINTS, ...ranking.map((q) => q.points)); + const lg = scene.add.graphics(); + lg.fillStyle(0xffffff, 0.35).fillRect(sx, sy, sw, sh); + lg.lineStyle(1, 0x9a8058, 0.6).strokeRect(sx, sy, sw, sh); + lg.lineStyle(1, 0xb04a3a, 0.5).lineBetween(sx, sy + sh - (WIN_POINTS / top) * sh, sx + sw, sy + sh - (WIN_POINTS / top) * sh); + if (pts.length > 1) { + lg.lineStyle(3, SEAT_HEX[r.seat], 1); + lg.beginPath(); + pts.forEach((v, k) => { + const px = sx + (k / (pts.length - 1)) * sw, py = sy + sh - (v / top) * sh; + if (k === 0) lg.moveTo(px, py); else lg.lineTo(px, py); + }); + lg.strokePath(); + } + page.add(lg); + page.add(scene.add.text(sx + sw / 2, sy + sh + 12, `prestige over ${pts.length} turns`, { fontFamily: SERIF, fontSize: '11px', fontStyle: 'italic', color: '#6a4a28' }).setOrigin(0.5)); + + // Honours. + const mine = awards.filter((a) => a.seat === r.seat); + mine.slice(0, 4).forEach((a, k) => { + page.add(scene.add.text(x + 1010, ry + 8 + k * 30, `✦ ${a.title}`, { fontFamily: SERIF, fontSize: '15px', fontStyle: 'bold', color: '#7a4a08' })); + page.add(scene.add.text(x + 1030, ry + 8 + k * 30 + 17, a.detail, { fontFamily: SERIF, fontSize: '11px', fontStyle: 'italic', color: '#5a4428' })); + }); + }); + + page.setAlpha(0); + page.y = 30; + scene.tweens.add({ targets: page, alpha: 1, y: 0, duration: 520, ease: 'Cubic.Out' }); + + const by = y + h - 48; + add(new Button(scene, GAME_WIDTH / 2 - 130, by, 'Play Again', () => onPlayAgain?.(), { width: 220, height: 48, fontSize: 20, bg: 0x2a4a30 }).setDepth(depth + 3)); + add(new Button(scene, GAME_WIDTH / 2 + 130, by, 'Leave', () => onLeave?.(), { width: 220, height: 48, fontSize: 20, bg: 0x5a3820 }).setDepth(depth + 3)); + + if (human && human.place === 1) { + scene.time.delayedCall(500, () => { + for (let k = 0; k < 4; k++) { + scene.time.delayedCall(k * 220, () => burst(scene, x + 200 + Math.random() * (w - 400), y + 60 + Math.random() * 80, [0xffffff, 0xffd87a, 0xf0b030, 0xff9a8a], { depth: depth + 4, count: 30 })); + } + }); + } + void Phaser; + return { close() { objs.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); } }; +} diff --git a/src/games/splendor/SplendorFx.js b/src/games/splendor/SplendorFx.js new file mode 100644 index 0000000..0ef3023 --- /dev/null +++ b/src/games/splendor/SplendorFx.js @@ -0,0 +1,183 @@ +// SplendorFx.js — highlight and celebration effects. +// +// makeBlaze(scene, rect, opts) the "you can buy this" treatment around a card +// kind 'now' amber halo + pulsing gilt frame + two light comets racing the +// edge + facet sparkles in the card's gem colour + a glint sweep +// kind 'gold' the same in deep gold with one comet and a "uses N gold" tag +// kind 'near' a still silver outline with a "1 away" tag +// returns { destroy() }. Every blaze built in the same refresh pulses in step. +// burst(scene, x, y, tints, opts) a one-shot sparkle explosion +// floatText(scene, x, y, text, opts) +// +// The pulsing frame + comets follow DominionGame._buildSupplyFxItem. + +import * as Phaser from 'phaser'; +import { GEM_CSS, SERIF } from './SplendorArt.js'; + +function perimPoint(d, W, H, left, top) { + const perim = 2 * (W + H); + d = ((d % perim) + perim) % perim; + if (d < W) return [left + d, top]; + d -= W; + if (d < H) return [left + W, top + d]; + d -= H; + if (d < W) return [left + W - d, top + H]; + d -= W; + return [left, top + H - d]; +} +const hexNum = (css) => parseInt(css.slice(1), 16); + +const PALETTE = { + now: { glow: 0xffb21a, outer: 0xff9d00, mid: 0xffc21a, inner: 0xfff6d0, head: 0xffffff, tail: 0xffe066 }, + gold: { glow: 0xffd23a, outer: 0xc88a00, mid: 0xf0c030, inner: 0xfff0a0, head: 0xfffbe0, tail: 0xf8d040 }, +}; + +export function makeBlaze(scene, rect, { kind = 'now', gem = 'white', depth = 12, goldUsed = 0, glint = true, sparkles = true, tagText = null } = {}) { + const objs = []; + const tweens = []; + const { x, y, w, h } = rect; + const cx = x + w / 2, cy = y + h / 2; + const add = (o) => { objs.push(o); return o; }; + + if (kind === 'near') { + const g = add(scene.add.graphics().setDepth(depth + 2)); + g.lineStyle(2.5, 0xdfe6f0, 0.75).strokeRoundedRect(x - 3, y - 3, w + 6, h + 6, 10); + g.lineStyle(1, 0xffffff, 0.35).strokeRoundedRect(x, y, w, h, 8); + tag(scene, add, rect, tagText ?? '1 gem away', 0x3a4250, '#e8eef6', depth + 3); + return handle(scene, objs, tweens); + } + + const P = PALETTE[kind] ?? PALETTE.now; + const glow = add(scene.add.image(cx, cy, 'spl-glow').setDisplaySize(w * 1.47, h * 1.34) + .setBlendMode(Phaser.BlendModes.ADD).setTint(P.glow).setAlpha(0.45).setDepth(depth)); + const sx = glow.scaleX, sy = glow.scaleY; + tweens.push(scene.tweens.add({ targets: glow, alpha: 0.95, scaleX: sx * 1.06, scaleY: sy * 1.06, duration: 650, yoyo: true, repeat: -1, ease: 'Sine.InOut' })); + + // Pulsing frame + comets. + const gfx = add(scene.add.graphics().setDepth(depth + 3)); + const pad = 4; + const left = x - pad, top = y - pad, Wd = w + pad * 2, Hd = h + pad * 2; + const perim = 2 * (Wd + Hd); + const TAIL = Math.min(110, perim * 0.2); + const SEG = 16; + const comets = kind === 'gold' ? 1 : 2; + const tracker = { t: 0 }; + tweens.push(scene.tweens.add({ + targets: tracker, t: { from: 0, to: 1 }, duration: 2600, repeat: -1, ease: 'Linear', + onUpdate: () => { + const pulse = 0.5 + 0.5 * Math.sin(tracker.t * Math.PI * 4 - Math.PI / 2); + gfx.clear(); + gfx.lineStyle(6 + 5 * pulse, P.outer, 0.12 + 0.2 * pulse); + gfx.strokeRoundedRect(left - 3, top - 3, Wd + 6, Hd + 6, 13); + gfx.lineStyle(3 + 2 * pulse, P.mid, 0.55 + 0.45 * pulse); + gfx.strokeRoundedRect(left, top, Wd, Hd, 11); + gfx.lineStyle(1.4, P.inner, 0.3 + 0.6 * pulse); + gfx.strokeRoundedRect(left + 3, top + 3, Wd - 6, Hd - 6, 9); + for (let c = 0; c < comets; c++) { + const head = ((tracker.t + c / comets) % 1) * perim; + for (let s = 0; s < SEG; s++) { + const f = s / SEG; + const d1 = head - (1 - f) * TAIL; + const d2 = head - (1 - (s + 1) / SEG) * TAIL; + const [x1, y1] = perimPoint(d1, Wd, Hd, left, top); + const [x2, y2] = perimPoint(d2, Wd, Hd, left, top); + const tip = f > 0.8; + gfx.lineStyle(tip ? 5 : 3, tip ? P.head : P.tail, 0.15 + f * 0.85); + gfx.beginPath(); gfx.moveTo(x1, y1); gfx.lineTo(x2, y2); gfx.strokePath(); + } + } + }, + })); + + // Facet sparkles lifting off the card, in its gem colour. + if (sparkles) { + const c = GEM_CSS[gem] ?? GEM_CSS.white; + const em = add(scene.add.particles(cx, cy, 'spl-spark', { + x: { min: -w / 2 + 6, max: w / 2 - 6 }, + y: { min: -h / 2, max: h / 2 - 20 }, + speedY: { min: -36, max: -12 }, + speedX: { min: -10, max: 10 }, + alpha: { start: 0.95, end: 0 }, + scale: { start: 0.7, end: 0.05 }, + rotate: { min: 0, max: 90 }, + lifespan: 900, + frequency: 260, + tint: [0xffffff, hexNum(c.hi), kind === 'gold' ? 0xffd700 : hexNum(c.mid)], + blendMode: 'ADD', + }).setDepth(depth + 4)); + em.setDepth(depth + 4); + } + + // A glint sweeping across the face every few seconds. + if (glint) { + const maskG = scene.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRoundedRect(x, y, w, h, 8); + objs.push({ destroy: () => maskG.destroy() }); + const streak = add(scene.add.image(x - 60, cy, 'spl-glint').setDisplaySize(46, h * 1.5).setAngle(18) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.8).setDepth(depth + 3)); + streak.setMask(maskG.createGeometryMask()); + tweens.push(scene.tweens.add({ + targets: streak, x: x + w + 60, duration: 750, ease: 'Sine.InOut', + repeat: -1, repeatDelay: 2200 + Math.random() * 800, delay: Math.random() * 1200, + })); + } + + if (kind === 'gold') tag(scene, add, rect, tagText ?? `uses ${goldUsed} gold`, 0x6a4a08, '#fff0b0', depth + 5); + return handle(scene, objs, tweens); +} + +// A small pill tucked into the card's lower-right corner (cost chips sit left). +function tag(scene, add, rect, text, bg, color, depth) { + const t = scene.add.text(0, 0, text, { fontFamily: SERIF, fontSize: rect.w < 100 ? '10px' : '12px', fontStyle: 'bold', color }).setOrigin(0.5).setDepth(depth + 1); + const w = t.width + 14; + const cx = rect.x + rect.w - 5 - w / 2, y = rect.y + rect.h - 24; + t.setPosition(cx, y + 9); + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.4).fillRoundedRect(cx - w / 2 + 1, y + 2, w, 18, 9); + g.fillStyle(bg, 0.95).fillRoundedRect(cx - w / 2, y, w, 18, 9); + g.lineStyle(1, 0xd9b45a, 0.8).strokeRoundedRect(cx - w / 2, y, w, 18, 9); + add(g); add(t); +} + +function handle(scene, objs, tweens) { + let dead = false; + return { + objs, + destroy() { + if (dead) return; + dead = true; + tweens.forEach((t) => { try { t.remove(); } catch (_) { /* gone */ } }); + objs.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); + }, + }; +} + +export function burst(scene, x, y, tints, { count = 28, depth = 70, speed = [80, 260], lifespan = 900, scale = 1 } = {}) { + const em = scene.add.particles(x, y, 'spl-spark', { + speed: { min: speed[0], max: speed[1] }, + lifespan: { min: lifespan * 0.6, max: lifespan }, + gravityY: 120, + rotate: { min: 0, max: 180 }, + scale: { start: 1.1 * scale, end: 0 }, + alpha: { start: 1, end: 0 }, + tint: tints, + blendMode: 'ADD', + emitting: false, + }).setDepth(depth); + em.explode(count); + scene.time.delayedCall(lifespan + 200, () => { try { em.destroy(); } catch (_) { /* gone */ } }); + return em; +} + +export function gemTints(gem) { + const c = GEM_CSS[gem] ?? GEM_CSS.white; + return [0xffffff, hexNum(c.hi), hexNum(c.mid), 0xffd87a]; +} + +export function floatText(scene, x, y, text, { color = '#ffe9a8', size = 24, depth = 72, rise = 46, duration = 1100 } = {}) { + const t = scene.add.text(x, y, text, { + fontFamily: SERIF, fontSize: `${size}px`, fontStyle: 'bold', color, stroke: '#1a0e04', strokeThickness: 5, + }).setOrigin(0.5).setDepth(depth); + scene.tweens.add({ targets: t, y: y - rise, alpha: { from: 1, to: 0 }, duration, ease: 'Cubic.Out', onComplete: () => t.destroy() }); + return t; +} diff --git a/src/games/splendor/SplendorGame.js b/src/games/splendor/SplendorGame.js index 06566cf..632189a 100644 --- a/src/games/splendor/SplendorGame.js +++ b/src/games/splendor/SplendorGame.js @@ -1,1520 +1,1099 @@ +// SplendorGame.js — the Splendor table: a gem merchant's counting house. +// +// A walnut desk under an oil lamp. The patrons hang in gilt frames along the +// damask wall beside the Guild Register (the prestige track); the market lies on +// a baize counting cloth in three rows — the Mines, the Trade Routes and the +// Merchant Houses — beside a velvet-lined jewel case (the bank). Every merchant +// keeps a tooled-leather ledger: card bonuses stacked by colour, gem tokens, +// gold, reserved cards and patron cameos. +// +// SplendorData catalog + flavour names SplendorLogic rules (pure) +// SplendorAI planning opponents (1–5) SplendorLayout every rect (pure) +// SplendorArt canvas bakes SplendorHud gallery, register, case, ledgers, dock +// SplendorFx buy highlights, bursts SplendorSound chips, chimes, fanfare +// SplendorDialogs pause / confirm / return / noble choice +// SplendorEndScreen the Guild Ledger +// +// Market cards are persistent sprites (dealt from the deck, lifted into a +// spotlight showcase, flown into a ledger). Gems fly between the case, the tray +// and the ledgers. On your turn affordable cards blaze, gold-only buys glow +// gold, one-gem-away cards get a silver outline, and every cost chip shows what +// you still owe after your bonuses. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { - GEMS, GOLD, GEM_HEX, GEM_EDGE, GEM_NAME, cardFrame, nobleFrame, deckBackFrame, gemFrame, - WIN_POINTS, MAX_RESERVED, TAKE_SAME_MIN, -} from './SplendorData.js'; -import { - createInitialState, legalActions, applyAction, applyDiscard, defaultDiscards, - canAfford, tokenTotal, isGameOver, finalRanking, currentPlayer, -} from './SplendorLogic.js'; +import { Tooltip } from '../../ui/Tooltip.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { HAND_LIMIT } from './SplendorData.js'; -import { chooseAction, nextThinkDelay } from './SplendorAI.js'; +import { PACE, clampSkill } from '../../ui/cardtable/AITiming.js'; +import { + GEMS, GOLD, GEM_NAME, NOBLES, HAND_LIMIT, MAX_RESERVED, TAKE_SAME_MIN, TIER_NAME, TIER_NOUN, locationOf, nobleInfo, +} from './SplendorData.js'; +import * as L from './SplendorLogic.js'; +import * as AI from './SplendorAI.js'; +import { + computeLayout, slotRect, deckRect, plaqueRect, CW, CH, MINI, RES, TRACK, BANK, DOCK, MUSIC, MENU_BTN, HELP_BTN, + bankChipPos, SEAT_HEX, W as SW, H as SH, +} from './SplendorLayout.js'; +import { + prepareSplendorArt, ensureCardFace, cardKey, backKey, nobleKey, chipKey, SERIF, DISPLAY, TRAY_SLOT, +} from './SplendorArt.js'; +import { + drawGallery, drawTrack, drawBank, drawLedger, drawDock, showPreview, ledgerChipPos, ledgerStackPos, reserveSlot, + cameoPos, portraitPos, nobleSlotRect, +} from './SplendorHud.js'; +import { makeBlaze, burst, gemTints, floatText } from './SplendorFx.js'; +import * as Snd from './SplendorSound.js'; +import { openPauseMenu, confirmBox, openReturn, openNobleChoice } from './SplendorDialogs.js'; +import { showSplendorEndScreen } from './SplendorEndScreen.js'; -// ── Layout ─────────────────────────────────────────────────────────────────── -const CW = 128, CH = 176, CARD_GAP = 16; // development card size -const DECK_W = 110; -const MARKET_X = 80; // left edge of decks -const CARDS_X = MARKET_X + DECK_W + 24; // first face-up card -const TIER_Y = { 3: 168, 2: 168 + CH + 26, 1: 168 + (CH + 26) * 2 }; -const NOBLE = 96, NOBLE_Y = 56; -const NOBLE_THUMB = 34, NOBLE_THUMB_GAP = 4; // square noble thumbnails in player panels - -const BANK_X = 830, BANK_Y0 = 176, BANK_STEP = 88, TOKEN_R = 36; - -const PANEL_X = 1036, PANEL_W = GAME_WIDTH - PANEL_X - 28; -const CONTROL_Y = 794; // bottom context bar - -const DEPTH = { bg: 0, board: 10, card: 14, ui: 40, popup: 60, banner: 90 }; - -// ── bought-card thumbnails in player panels ─────────────────────────────────── -const THUMB_W = 44; -const THUMB_H = Math.round(THUMB_W * CH / CW); // ≈ 60 — maintains card aspect ratio -const THUMB_GAP = 4; // horizontal gap between cards -const THUMB_ROW_GAP = 3; // vertical gap between rows -const PORTRAIT_R = 34; // must match buildPortraits -const THUMB_AREA_REL_X = PORTRAIT_R * 2 + 16 + 8; // portrait right-edge + 8 px left padding -const THUMB_GEM_REL_X = PANEL_W - 16 - 14 - 5 * 36 - 14; // gem-row left edge, panel-relative -const THUMB_PER_ROW = Math.floor((THUMB_GEM_REL_X - THUMB_AREA_REL_X) / (THUMB_W + THUMB_GAP)); -const THUMB_ROW_TOP_REL = 38; // panel-relative top (aligns with portrait top) - -const hexStr = (n) => '#' + (n >>> 0).toString(16).padStart(6, '0').slice(-6); +const D = { + room: 0, light: 1, furniture: 2, gallery: 4, track: 4, bank: 6, ledger: 8, deck: 10, glow: 12, card: 14, + hint: 18, reach: 19, select: 22, dust: 28, dock: 30, preview: 40, flight: 50, overlay: 60, showcase: 62, + banner: 70, modal: 80, end: 85, tooltip: 95, +}; +const SETTINGS_KEY = 'splendor-settings'; +const DEFAULT_SETTINGS = { pace: 'normal', hints: true, reach: true, undo: true, ambient: true }; +const HUMAN = 0; +const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`; +const withTokens = (s, seat, tokens, bank) => ({ + ...s, + bank: bank ?? s.bank, + players: s.players.map((p) => (p.seat === seat && tokens ? { ...p, tokens } : p)), +}); export default class SplendorGame extends Phaser.Scene { constructor() { super('SplendorGame'); } init(data) { - this._initData = { ...data }; - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.humanSeat = 0; - this.gs = null; - this.busy = false; - this.selection = []; // colours chosen for a take action - this.selectedCard = null; // { card, source } chosen to buy/reserve - this.dyn = []; // dynamic objects rebuilt every render - this.preview = []; // hover card preview — cleared separately - this.portraits = []; // one per seat, created once - this.animatingReserve = null; // { seat, cardId } suppresses that pill during animation - this.animatingBuy = null; // { seat, cardId } suppresses thumbnail during animation - this.boughtCards = {}; // seat → card[] — persists purchased cards for display - this._thumbHoverTimer = null; // pending 500 ms intent timer for thumbnail preview - this.animatingNoble = null; // { seat, nobleId } suppresses noble thumbnail during animation - this._pendingNoble = null; // { seat, noble, srcX, srcY } queued noble animation + this._initData = { ...data }; + this.gameDef = data.game; + this.opponents = data.opponents ?? []; + this.playfield = data.playfield ?? null; + this.gs = null; + this.busy = true; + this.ended = false; + this.modal = null; + this.tray = []; + this.trayPending = new Set(); // tray slots whose chip is still flying in + this.selected = null; // { card, source: 'board'|'reserve', rect } + this.lastClick = null; + this.undoSnap = null; + this.aiTimer = null; + this.portraits = []; + this.cardSprites = new Map(); // card id → market sprite + this.dyn = []; + this.fx = []; + this.breathing = []; + this.dockObjs = []; + this.hoverObjs = []; + this.previewObjs = []; + this.previewTimer = null; + this.dockHover = null; + this.finalAnnounced = false; + try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } } create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* optional */ } - this.hasArt = this.textures.exists('splendor-cards'); - this.hasGems = this.textures.exists('splendor-gems'); - this.buildBackground(); - - const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); - this.skillBySeat = {}; - const names = []; - for (let seat = 0; seat < playerCount; seat++) { - if (seat === this.humanSeat) { - names.push(auth.user?.username ?? 'You'); - this.skillBySeat[seat] = 5; - } else { - const opp = this.opponents[seat - 1]; - names.push(opp?.name ?? `Player ${seat}`); - this.skillBySeat[seat] = Math.max(1, Math.min(5, opp?.skill ?? 3)); - } - } - - this.gs = createInitialState({ playerCount, names }); - this.buildPortraits(); - this.render(); - this.advance(); + try { + new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? [], undefined, { + right: MUSIC.right, top: MUSIC.top, infoColor: '#f3e6c8', + }); + } catch (_) { /* no music json */ } + this.events.once('shutdown', () => { this.ended = true; }); + const n = Math.max(2, Math.min(4, 1 + this.opponents.length)); + this.layout = computeLayout(n); + prepareSplendorArt(this, this.layout.ledgers).then(() => { + if (!this.sys?.isActive()) return; + this.build(n); + }); + } + + // ── build ────────────────────────────────────────────────────────────────────────── + build(playerCount) { + this.names = []; + this.skills = []; + for (let seat = 0; seat < playerCount; seat++) { + if (seat === HUMAN) { this.names.push(auth.user?.username ?? 'You'); this.skills.push(null); } + else { + const opp = this.opponents[seat - 1]; + this.names.push(opp?.name ?? `Merchant ${seat}`); + this.skills.push(clampSkill(opp?.skill ?? 3)); + } + } + this.gs = L.createInitialState({ playerCount, names: this.names }); + this.nobleSlots = this.gs.nobles.slice(); + this.tooltip = new Tooltip(this, { depth: D.tooltip, hoverDelay: 260 }); + + this.buildRoom(); + this.buildPortraits(); + this.buildButtons(); + this.buildInput(); + this.setAmbient(this.settings.ambient); + + // Opening: the patrons fade in, then the market is dealt. + this.refresh(); + this.dockSpec = { title: 'The market opens', body: 'The dealer lays out the mines, the trade routes and the merchant houses…' }; + this.refreshDock(); + this.time.delayedCall(300, async () => { + await this.syncMarket(this.gs, { animate: true, stagger: 70 }); + if (this.ended) return; + this.dockSpec = null; + this.advance(); + }); + } + + get k() { return PACE[this.settings.pace] ?? 1; } + wait(ms) { return new Promise((res) => this.time.delayedCall(Math.max(0, ms), res)); } + tw(cfg) { return new Promise((res) => this.tweens.add({ ...cfg, onComplete: () => { cfg.onComplete?.(); res(); } })); } + ledgerOf(seat) { return this.layout.ledgers[seat]; } + + buildRoom() { + this.add.image(0, 0, 'spl-room').setOrigin(0, 0).setDepth(D.room); + this.light = this.add.image(0, 0, 'spl-light').setOrigin(0, 0).setDepth(D.light); + this.add.image(TRACK.x, TRACK.y, 'spl-track').setOrigin(0, 0).setDepth(D.furniture); + for (const t of [1, 2, 3]) { + const r = plaqueRect(t); + this.add.image(r.x + r.w / 2, r.y + r.h / 2, `spl-plaque-${t}`).setDisplaySize(r.w, r.h).setDepth(D.furniture); + } + this.add.image(BANK.x - 16, BANK.y - 16, 'spl-case').setOrigin(0, 0).setDepth(D.bank); + this.add.image(DOCK.x - 12, DOCK.y - 12, 'spl-dock').setOrigin(0, 0).setDepth(D.dock - 1); } - // ── portraits (created once, not part of dyn) ──────────────────────────────── buildPortraits() { - const n = this.gs.players.length; - const gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const portraitR = 34; + this.layout.ledgers.forEach((Lr) => { + const pp = portraitPos(Lr); + this.portraits[Lr.seat] = Lr.seat === HUMAN + ? createPlayerPortrait(this, pp.x, pp.y, pp.r, D.ledger + 3, 'SplendorGame') + : createOpponentPortrait(this, this.opponents[Lr.seat - 1], pp.x, pp.y, pp.r, D.ledger + 3); + }); + } + hidePortraits() { this.portraits.forEach((p) => p?.hide?.()); } + showPortraits() { if (!this.modal && !this.endScreen && !this.showcasing) this.portraits.forEach((p) => p?.show?.()); } - this.gs.players.forEach((_, idx) => { - const panelY = 76 + idx * (h + gap); - const px = PANEL_X + 16 + portraitR; - const py = panelY + 38 + portraitR; // below 22px name + small gap + buildButtons() { + const mk = (r, label, fn) => new Button(this, r.x + r.w / 2, r.y + r.h / 2, label, fn, { + width: r.w, height: r.h, fontSize: 15, bg: 0x4a2c16, + }).setDepth(D.dock); + mk(MENU_BTN, 'Menu', () => this.openMenu()); + mk(HELP_BTN, 'Rules', () => this.openRules()); + } - if (idx === this.humanSeat) { - this.portraits[idx] = createPlayerPortrait(this, px, py, portraitR, DEPTH.ui + 1, 'SplendorGame'); - } else { - const opp = this.opponents[idx - 1]; - this.portraits[idx] = createOpponentPortrait(this, opp, px, py, portraitR, DEPTH.ui + 1); + buildInput() { + const kb = this.input.keyboard; + if (!kb) return; + kb.on('keydown', (ev) => { + if (this.modal || this.ended || this.endScreen) return; + const k = ev.key; + if (k === 'z' || k === 'Z') { this.undo(); return; } + if (k === 'm' || k === 'M') { this.openMenu(); return; } + if (!this.canAct()) return; + if (k >= '1' && k <= '5') { const c = GEMS[Number(k) - 1]; if (this.pickable(c).ok) this.pickGem(c); return; } + if (k === 'Enter' || k === ' ') { if (this.trayAction()) this.confirmTake(); return; } + if (k === 'Escape' || k === 'Backspace') { + if (this.tray.length || this.selected) { this.tray = []; this.selected = null; this.refresh(); } } }); } - // ── static background / chrome ────────────────────────────────────────────── - buildBackground() { - const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.bg); - } else { - const g = this.add.graphics().setDepth(DEPTH.bg); - g.fillGradientStyle(0x14110b, 0x14110b, 0x070503, 0x070503, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - } - this.add.text(GAME_WIDTH / 2, 26, 'Splendor', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui); - - new Button(this, GAME_WIDTH - 96, GAME_HEIGHT - 36, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 140, height: 42, fontSize: 18 }).setDepth(DEPTH.ui); + setAmbient(on) { + this.ambientObjs?.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); + this.ambientTimer?.remove(); + this.ambientObjs = []; + this.tweens.killTweensOf(this.light); + this.light.setAlpha(1); + if (!on) return; + const dust = this.add.particles(0, 0, 'spl-dust', { + x: { min: 180, max: 1150 }, y: { min: 180, max: 820 }, + speedX: { min: -6, max: 6 }, speedY: { min: -9, max: -2 }, + alpha: { start: 0, end: 0.4, ease: 'Sine.InOut' }, scale: { min: 0.3, max: 0.9 }, + lifespan: 7000, frequency: 420, blendMode: 'ADD', + }).setDepth(D.dust); + this.ambientObjs.push(dust); + const flicker = () => { + if (this.ended) return; + this.tweens.add({ targets: this.light, alpha: 0.9 + Math.random() * 0.1, duration: 120 + Math.random() * 260, ease: 'Sine.InOut' }); + this.ambientTimer = this.time.delayedCall(200 + Math.random() * 900, flicker); + }; + flicker(); } - // ── render: rebuild all dynamic visuals from this.gs ───────────────────────── - reg(obj) { this.dyn.push(obj); return obj; } + // ── market sprites ────────────────────────────────────────────────────────────────── + makeSprite(card, x, y, { faceUp = true, tier = card.tier } = {}) { + if (faceUp) ensureCardFace(this, card); + const c = this.add.container(x, y).setDepth(D.card); + const shadow = this.add.image(3, 5, 'spl-shadow').setDisplaySize(CW * 1.19, CH * 1.14).setAlpha(0.75); + const img = this.add.image(0, 0, faceUp ? cardKey(card) : backKey(tier)).setDisplaySize(CW, CH); + c.add([shadow, img]); + return { card, c, img, shadow, faceUp }; + } - regMaskedImg(x, y, w, h, key, frame, depth, r = 10) { - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff).fillRoundedRect(x, y, w, h, r); - this.dyn.push({ destroy: () => maskG.destroy() }); - return this.reg( - this.add.image(x + w / 2, y + h / 2, key, frame) - .setDisplaySize(w, h).setMask(maskG.createGeometryMask()).setDepth(depth) - ); + async flip(sp, toFace, dur = 200) { + const s = sp.c.scaleX; + await this.tw({ targets: sp.c, scaleX: 0.02, duration: dur / 2, ease: 'Sine.In' }); + if (toFace) ensureCardFace(this, sp.card); + sp.img.setTexture(toFace ? cardKey(sp.card) : backKey(sp.card.tier)).setDisplaySize(CW, CH); + sp.faceUp = toFace; + await this.tw({ targets: sp.c, scaleX: s, duration: dur / 2, ease: 'Sine.Out' }); + } + + // Bring the market sprites in line with `state`: remove stale ones, deal new + // ones from the deck (animated) or place them. + async syncMarket(state, { animate = true, stagger = 0 } = {}) { + const want = new Map(); + for (const t of [1, 2, 3]) state.board[t].forEach((c, slot) => { if (c) want.set(c.id, { card: c, tier: t, slot }); }); + for (const [id, sp] of this.cardSprites) { + if (!want.has(id)) { sp.c.destroy(); this.cardSprites.delete(id); } + } + const jobs = []; + let order = 0; + for (const [id, w] of want) { + const r = slotRect(w.tier, w.slot); + const cx = r.x + CW / 2, cy = r.y + CH / 2; + let sp = this.cardSprites.get(id); + if (!sp) { + if (!animate) { + sp = this.makeSprite(w.card, cx, cy); + this.cardSprites.set(id, sp); + continue; + } + const dr = deckRect(w.tier); + sp = this.makeSprite(w.card, dr.x + CW / 2, dr.y + CH / 2, { faceUp: false }); + sp.c.setDepth(D.flight); + this.cardSprites.set(id, sp); + const delay = order++ * stagger; + jobs.push(this.wait(delay).then(async () => { + if (this.ended || !sp.c.scene) return; + Snd.swish(this); + const move = this.tw({ targets: sp.c, x: cx, y: cy, duration: 380 * Math.min(1, this.k), ease: 'Cubic.Out' }); + await this.wait(120 * Math.min(1, this.k)); + if (sp.c.scene) await this.flip(sp, true, 220 * Math.min(1, this.k)); + await move; + if (sp.c.scene) sp.c.setDepth(D.card); + })); + } else if (Math.abs(sp.c.x - cx) > 1 || Math.abs(sp.c.y - cy) > 1) { + sp.c.setPosition(cx, cy); + } + } + await Promise.all(jobs); + this.refresh(); + } + + rebuildMarket() { + for (const sp of this.cardSprites.values()) sp.c.destroy(); + this.cardSprites.clear(); + for (const t of [1, 2, 3]) { + this.gs.board[t].forEach((c, slot) => { + if (!c) return; + const r = slotRect(t, slot); + this.cardSprites.set(c.id, this.makeSprite(c, r.x + CW / 2, r.y + CH / 2)); + }); + } + } + + // ── refresh ────────────────────────────────────────────────────────────────────────── + canAct() { + return !this.busy && !this.modal && !this.ended && this.gs && this.gs.phase === 'turn' && this.gs.current === HUMAN; } clearDyn() { - this.clearPreview(); - if (this._thumbHoverTimer) { this._thumbHoverTimer.remove(); this._thumbHoverTimer = null; } - for (const o of this.dyn) { try { o.destroy(); } catch { /* noop */ } } + this.tooltip?.hide(); + this.clearHover(); + this.dyn.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); this.dyn = []; - } - - clearPreview() { - for (const o of this.preview) { try { o.destroy(); } catch { /* noop */ } } - this.preview = []; - } - - findCardBoardPos(cardId) { - for (const tier of [1, 2, 3]) { - const col = this.gs.board[tier].findIndex((c) => c?.id === cardId); - if (col !== -1) { - return { x: CARDS_X + col * (CW + CARD_GAP) + CW / 2, y: TIER_Y[tier] + CH / 2 }; - } - } - return null; - } - - findCard(cardId) { - for (const tier of [1, 2, 3]) { - const c = this.gs.board[tier].find((c) => c?.id === cardId); - if (c) return c; - } - for (const p of this.gs.players) { - const c = p.reserved.find((c) => c?.id === cardId); - if (c) return c; - } - return null; - } - - // Wraps applyAction and detects if a noble was earned this turn. - _applyAction(action) { - const prevNobles = this.gs.nobles.slice(); - const prevCounts = this.gs.players.map((p) => p.nobles.length); - const next = applyAction(this.gs, action); - this.gs = next; - for (let seat = 0; seat < this.gs.players.length; seat++) { - if (this.gs.players[seat].nobles.length > prevCounts[seat]) { - const claimed = prevNobles.find((pn) => !this.gs.nobles.some((n) => n.id === pn.id)); - if (claimed) { - const si = prevNobles.indexOf(claimed); - this._pendingNoble = { - seat, - noble: claimed, - srcX: MARKET_X + si * (NOBLE + 14) + NOBLE / 2, - srcY: NOBLE_Y + NOBLE / 2, - }; - } - break; - } + this.fx.forEach((h) => h.destroy()); + this.fx = []; + this.breathing.forEach((t) => t.remove()); + this.breathing = []; + for (const sp of this.cardSprites.values()) { + if (sp.detached) continue; + sp.img.clearTint(); + sp.c.setScale(1); } } - nobleThumbPos(seat, nobleIdx) { - const n = this.gs.players.length; - const gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const panelY = 76 + seat * (h + gap); - const totalCY = panelY + 70 + 57; - const nobleCount = this.gs.players[seat].nobles.length; - const groupW = nobleCount * NOBLE_THUMB + Math.max(0, nobleCount - 1) * NOBLE_THUMB_GAP; - const tx = PANEL_X + PANEL_W - 16 - groupW + nobleIdx * (NOBLE_THUMB + NOBLE_THUMB_GAP); - const ty = totalCY + 14 + 3; - return { cx: tx + NOBLE_THUMB / 2, cy: ty + NOBLE_THUMB / 2 }; - } - - boughtCardThumbPos(seat, idx) { - const n = this.gs.players.length; - const gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const panelY = 76 + seat * (h + gap); - const col = idx % THUMB_PER_ROW; - const row = Math.floor(idx / THUMB_PER_ROW); - const tx = PANEL_X + THUMB_AREA_REL_X + col * (THUMB_W + THUMB_GAP); - const ty = panelY + THUMB_ROW_TOP_REL + row * (THUMB_H + THUMB_ROW_GAP); - return { cx: tx + THUMB_W / 2, cy: ty + THUMB_H / 2 }; - } - - showCardPreview(card, barCenterX, barBottomY) { - this.clearPreview(); - const pw = 270, ph = 390; - const rp = (obj) => { this.preview.push(obj); return obj; }; - - const px = Math.min(Math.max(barCenterX - pw / 2, 8), GAME_WIDTH - pw - 8); - const pyBelow = barBottomY + 4; - const py = pyBelow + ph > GAME_HEIGHT - 8 ? barBottomY - ph - 4 : pyBelow; - - // Drop shadow panel - rp(this.add.graphics().setDepth(DEPTH.popup)) - .fillStyle(0x000000, 0.65).fillRoundedRect(px - 7, py - 7, pw + 14, ph + 14, 14); - - // Card background (same tinted-rect approach as drawCard) - const g = rp(this.add.graphics().setDepth(DEPTH.popup)); - const tint = GEM_HEX[card.bonus]; - g.fillStyle(0x14110b, 1).fillRoundedRect(px, py, pw, ph, 10); - g.fillStyle(tint, 0.20).fillRoundedRect(px, py, pw, ph, 10); - if (!this.hasArt) { - g.fillStyle(tint, 0.9).fillRoundedRect(px, py, pw, 65, { tl: 10, tr: 10, bl: 0, br: 0 }); - } - if (this.hasArt) { - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff).fillRoundedRect(px, py, pw, ph, 10); - this.preview.push({ destroy: () => maskG.destroy() }); - rp(this.add.image(px + pw / 2, py + ph / 2, 'splendor-cards', cardFrame(card)) - .setDisplaySize(pw, ph).setMask(maskG.createGeometryMask()).setDepth(DEPTH.popup)); - } - // Border drawn above art - rp(this.add.graphics().setDepth(DEPTH.popup + 1)) - .lineStyle(3, GEM_EDGE[card.bonus], 1).strokeRoundedRect(px, py, pw, ph, 10); - - // Points - if (card.points > 0) { - rp(this.add.text(px + 18, py + 8, String(card.points), { - fontFamily: 'Righteous', fontSize: '54px', - color: card.bonus === 'white' ? '#222' : '#fff', - }).setDepth(DEPTH.popup + 1)); - } - - // Bonus gem badge top-right - const bg = rp(this.add.graphics().setDepth(DEPTH.popup + 1)); - bg.fillStyle(GEM_HEX[card.bonus], 1).fillCircle(px + pw - 40, py + 36, 26); - bg.lineStyle(3, GEM_EDGE[card.bonus], 1).strokeCircle(px + pw - 40, py + 36, 26); - if (this.hasGems) { - rp(this.add.image(px + pw - 40, py + 36, 'splendor-gems', gemFrame(card.bonus)) - .setDisplaySize(40, 40).setDepth(DEPTH.popup + 2)); - } - - // Cost pips bottom-left stacked - const costs = GEMS.filter((c) => (card.cost[c] ?? 0) > 0); - costs.forEach((c, i) => { - const cy = py + ph - 44 - i * 62; - const pg = rp(this.add.graphics().setDepth(DEPTH.popup + 1)); - pg.fillStyle(GEM_HEX[c], 1).fillCircle(px + 40, cy, 26); - pg.lineStyle(3, GEM_EDGE[c], 1).strokeCircle(px + 40, cy, 26); - rp(this.add.text(px + 40, cy, String(card.cost[c]), { - fontFamily: 'Righteous', fontSize: '28px', - color: c === 'white' ? '#222' : '#fff', - }).setOrigin(0.5).setDepth(DEPTH.popup + 2)); - }); - } - - render() { + refresh(view = this.gs, opts = {}) { + if (!this.gs || this.ended) return; this.clearDyn(); - this.drawNobles(); - this.drawMarket(); - this.drawBank(); - this.drawPanels(); - this.drawControlBar(); - this.drawTurnLabel(); - } + const dyn = this.dyn; + const live = this.canAct() && view === this.gs; + const human = view.players[HUMAN]; + const hints = live && this.settings.hints; - // ── nobles ────────────────────────────────────────────────────────────────── - drawNobles() { - this.gs.nobles.forEach((n, i) => { - const x = MARKET_X + i * (NOBLE + 14); - const g = this.reg(this.add.graphics().setDepth(DEPTH.card)); - g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 3, NOBLE_Y + 4, NOBLE, NOBLE, 10); - g.fillStyle(0x2b2620, 1).fillRoundedRect(x, NOBLE_Y, NOBLE, NOBLE, 10); - if (this.hasArt) { - this.regMaskedImg(x, NOBLE_Y, NOBLE, NOBLE, 'splendor-cards', nobleFrame(n), DEPTH.card + 1); - } - this.reg(this.add.graphics().setDepth(DEPTH.card + 2)) - .lineStyle(1.5, COLORS.accent, 0.8).strokeRoundedRect(x, NOBLE_Y, NOBLE, NOBLE, 10); - // prestige (always drawn over art) - this.reg(this.add.text(x + 8, NOBLE_Y + 4, '3', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.goldHex, - }).setDepth(DEPTH.card + 2)); - // requirement chips along the bottom (always drawn over art) - const reqs = Object.entries(n.requires); - reqs.forEach(([color, req], j) => { - const cx = x + 16 + j * 30, cy = NOBLE_Y + NOBLE - 18; - const c = this.reg(this.add.graphics().setDepth(DEPTH.card + 2)); - c.fillStyle(GEM_HEX[color], 1).fillCircle(cx, cy, 11); - c.lineStyle(2, GEM_EDGE[color], 1).strokeCircle(cx, cy, 11); - this.reg(this.add.text(cx, cy, String(req), { - fontFamily: 'Righteous', fontSize: '14px', - color: color === 'white' ? '#222' : '#fff', - }).setOrigin(0.5).setDepth(DEPTH.card + 3)); - }); - }); - } - - // ── market ────────────────────────────────────────────────────────────────── - drawMarket() { - for (const tier of [3, 2, 1]) { - const y = TIER_Y[tier]; - // deck pile - const deckN = this.gs.decks[tier].length; - const dg = this.reg(this.add.graphics().setDepth(DEPTH.card)); - dg.fillStyle(0x000000, 0.45).fillRoundedRect(MARKET_X + 3, y + 4, DECK_W, CH, 10); - dg.fillStyle(tier === 3 ? 0x2a3550 : tier === 2 ? 0x3a4a2a : 0x4a3a2a, 1) - .fillRoundedRect(MARKET_X, y, DECK_W, CH, 10); - if (deckN > 0 && this.hasArt) { - this.regMaskedImg(MARKET_X, y, DECK_W, CH, 'splendor-cards', deckBackFrame(tier), DEPTH.card + 1); - } - this.reg(this.add.graphics().setDepth(DEPTH.card + 2)) - .lineStyle(1.5, tier === 3 ? 0x4a6090 : tier === 2 ? 0x5a7040 : 0x705030, 0.8) - .strokeRoundedRect(MARKET_X, y, DECK_W, CH, 10); - this.reg(this.add.text(MARKET_X + DECK_W / 2, y + 30, '★'.repeat(tier), { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.card + 2)); - this.reg(this.add.text(MARKET_X + DECK_W / 2, y + CH - 26, `${deckN}`, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.card + 2)); - if (deckN > 0 && this.isHumanTurn()) { - const zone = this.reg(this.add.zone(MARKET_X + DECK_W / 2, y + CH / 2, DECK_W, CH) - .setInteractive({ useHandCursor: true }).setDepth(DEPTH.card + 2)); - zone.on('pointerdown', () => this.onDeckClick(tier)); - } - - // face-up cards - this.gs.board[tier].forEach((card, i) => { - if (!card) return; - const x = CARDS_X + i * (CW + CARD_GAP); - this.drawCard(card, x, y, 'board'); - }); - } - } - - drawCard(card, x, y, source) { - const human = this.gs.players[this.humanSeat]; - const affordable = this.isHumanTurn() && canAfford(human, card); - const selected = this.selectedCard && this.selectedCard.card.id === card.id; - - // Card background — always draw the tinted rect (provides border shape and colour identity) - const g = this.reg(this.add.graphics().setDepth(DEPTH.card + 1)); - const tint = GEM_HEX[card.bonus]; - g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 3, y + 4, CW, CH, 10); - g.fillStyle(0x14110b, 1).fillRoundedRect(x, y, CW, CH, 10); - g.fillStyle(tint, 0.20).fillRoundedRect(x, y, CW, CH, 10); - if (!this.hasArt) { - g.fillStyle(tint, 0.9).fillRoundedRect(x, y, CW, 30, { tl: 10, tr: 10, bl: 0, br: 0 }); - } - - // Spritesheet art clipped to rounded rect - if (this.hasArt) { - this.regMaskedImg(x, y, CW, CH, 'splendor-cards', cardFrame(card), DEPTH.card + 1); - } - // Border drawn on top of art - this.reg(this.add.graphics().setDepth(DEPTH.card + 2)) - .lineStyle(1.5, GEM_EDGE[card.bonus], 1).strokeRoundedRect(x, y, CW, CH, 10); - - // Vector overlays — always drawn on top of whatever background is present - if (card.points > 0) { - this.reg(this.add.text(x + 10, y + 2, String(card.points), { - fontFamily: 'Righteous', fontSize: '26px', - color: card.bonus === 'white' ? '#222' : '#fff', - }).setDepth(DEPTH.card + 2)); - } - // bonus gem badge (top-right) - const bg = this.reg(this.add.graphics().setDepth(DEPTH.card + 2)); - bg.fillStyle(GEM_HEX[card.bonus], 1).fillCircle(x + CW - 22, y + 15, 12); - bg.lineStyle(2, GEM_EDGE[card.bonus], 1).strokeCircle(x + CW - 22, y + 15, 12); - if (this.hasGems) { - this.reg(this.add.image(x + CW - 22, y + 15, 'splendor-gems', gemFrame(card.bonus)) - .setDisplaySize(18, 18).setDepth(DEPTH.card + 3)); - } - // cost pips, bottom-left stacked - const costs = GEMS.filter((c) => (card.cost[c] ?? 0) > 0); - costs.forEach((c, i) => { - const cy = y + CH - 22 - i * 30; - const pg = this.reg(this.add.graphics().setDepth(DEPTH.card + 2)); - pg.fillStyle(GEM_HEX[c], 1).fillCircle(x + 20, cy, 12); - pg.lineStyle(2, GEM_EDGE[c], 1).strokeCircle(x + 20, cy, 12); - this.reg(this.add.text(x + 20, cy, String(card.cost[c]), { - fontFamily: 'Righteous', fontSize: '15px', - color: c === 'white' ? '#222' : '#fff', - }).setOrigin(0.5).setDepth(DEPTH.card + 3)); - }); - - // affordability / selection ring - if (selected || affordable) { - const ring = this.reg(this.add.graphics().setDepth(DEPTH.card + 4)); - ring.lineStyle(4, selected ? COLORS.gold : 0x57c46a, selected ? 1 : 0.85) - .strokeRoundedRect(x - 3, y - 3, CW + 6, CH + 6, 12); - } - - if (this.isHumanTurn()) { - const zone = this.reg(this.add.zone(x + CW / 2, y + CH / 2, CW, CH) - .setInteractive({ useHandCursor: true }).setDepth(DEPTH.card + 5)); - zone.on('pointerdown', () => this.onCardClick(card, source)); - } - } - - // ── token bank ────────────────────────────────────────────────────────────── - drawBank() { - const order = [...GEMS, GOLD]; - const pad = 16; - const bgX = BANK_X - TOKEN_R - pad; - const bgY = BANK_Y0 - TOKEN_R - pad; - const bgW = PANEL_X - bgX - pad; - const bgH = (order.length - 1) * BANK_STEP + TOKEN_R * 2 + pad * 2; - const bg = this.reg(this.add.graphics().setDepth(DEPTH.card - 1)); - bg.fillStyle(0x000000, 0.72).fillRoundedRect(bgX, bgY, bgW, bgH, 12); - bg.lineStyle(1, COLORS.accent, 0.5).strokeRoundedRect(bgX, bgY, bgW, bgH, 12); - - order.forEach((color, i) => { - const cx = BANK_X, cy = BANK_Y0 + i * BANK_STEP; - const n = this.gs.bank[color]; - const g = this.reg(this.add.graphics().setDepth(DEPTH.card)); - g.fillStyle(GEM_HEX[color], n > 0 ? 1 : 0.25).fillCircle(cx, cy, TOKEN_R); - g.lineStyle(3, GEM_EDGE[color], 1).strokeCircle(cx, cy, TOKEN_R); - if (this.hasGems) { - this.reg(this.add.image(cx, cy, 'splendor-gems', gemFrame(color)) - .setDisplaySize(56, 56).setAlpha(n > 0 ? 0.9 : 0.35).setDepth(DEPTH.card + 1)); - } - const textX = cx + TOKEN_R + 12; - this.reg(this.add.text(textX, cy, String(n), { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.card + 2)); - this.reg(this.add.text(textX + 32, cy, GEM_NAME[color], { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.card + 2)); - // selection count overlay - const sel = this.selection.filter((c) => c === color).length; - if (sel > 0) { - this.reg(this.add.text(cx - TOKEN_R - 6, cy - TOKEN_R, `+${sel}`, { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.goldHex, - }).setOrigin(1, 0).setDepth(DEPTH.card + 3)); - } - if (this.isHumanTurn() && color !== GOLD && n > 0) { - const ring = this.reg(this.add.graphics().setDepth(DEPTH.card + 3).setAlpha(0)); - ring.lineStyle(4, 0xffffff, 1).strokeCircle(cx, cy, TOKEN_R + 7); - - const zone = this.reg(this.add.zone(cx, cy, TOKEN_R * 2, TOKEN_R * 2) - .setInteractive({ useHandCursor: true }).setDepth(DEPTH.card + 4)); - zone.on('pointerover', () => ring.setAlpha(1)); - zone.on('pointerout', () => ring.setAlpha(0)); - zone.on('pointerdown', () => this.onTokenClick(color)); - } - }); - } - - // ── player panels ─────────────────────────────────────────────────────────── - drawPanels() { - const n = this.gs.players.length; - const gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - this.gs.players.forEach((p, idx) => { - const x = PANEL_X, y = 76 + idx * (h + gap), w = PANEL_W; - const isCurrent = idx === this.gs.current && !isGameOver(this.gs); - const g = this.reg(this.add.graphics().setDepth(DEPTH.ui)); - g.fillStyle(0x000000, 0.62).fillRoundedRect(x, y, w, h, 12); - g.lineStyle(isCurrent ? 3 : 1, isCurrent ? COLORS.gold : COLORS.accent, isCurrent ? 1 : 0.4) - .strokeRoundedRect(x, y, w, h, 12); - - const youTag = idx === this.humanSeat ? ' (you)' : ''; - this.reg(this.add.text(x + 16, y + 10, `${p.name}${youTag}`, { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - }).setDepth(DEPTH.ui + 1)); - this.reg(this.add.text(x + w - 16, y + 8, `${p.points}`, { - fontFamily: 'Righteous', fontSize: '34px', color: COLORS.goldHex, - }).setOrigin(1, 0).setDepth(DEPTH.ui + 1)); - this.reg(this.add.text(x + w - 70, y + 18, 'pts', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(1, 0).setDepth(DEPTH.ui + 1)); - - // gem cells: cards (bonus) over tokens — compact, right-aligned - const order = [...GEMS, GOLD]; - const gemR = 10; - const totalR = 14; - const gemSpacing = 36; - const gemStartX = x + w - 16 - totalR - (order.length - 1) * gemSpacing; - order.forEach((color, ci) => { - const ccx = gemStartX + ci * gemSpacing; - const ccy = y + 70; - const cards = color === GOLD ? 0 : (p.bonuses[color] ?? 0); - const toks = p.tokens[color] ?? 0; - const cg = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - cg.fillStyle(GEM_HEX[color], 1).fillCircle(ccx, ccy, gemR); - cg.lineStyle(1.5, GEM_EDGE[color], 1).strokeCircle(ccx, ccy, gemR); - if (color !== GOLD) { - this.reg(this.add.text(ccx, ccy, String(cards), { - fontFamily: 'Righteous', fontSize: '12px', - color: color === 'white' ? '#222' : '#fff', - }).setOrigin(0.5).setDepth(DEPTH.ui + 2)); - } - this.reg(this.add.text(ccx, ccy + 22, `${toks}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.ui + 2)); - // discard interactivity (human, over limit) - const discardable = this.gs.phase === 'discard' && this.gs.current === this.humanSeat - && idx === this.humanSeat && toks > 0; - if (discardable) { - const z = this.reg(this.add.zone(ccx, ccy + 8, gemSpacing, 50) - .setInteractive({ useHandCursor: true }).setDepth(DEPTH.ui + 3)); - z.on('pointerdown', () => this.onDiscardClick(color)); - } - }); - - // divider + total row (card bonuses + tokens) - const ccy = y + 70; - const divY = ccy + 38; - const totalCY = ccy + 57; - const divG = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - divG.lineStyle(1, COLORS.accent, 0.35) - .lineBetween(gemStartX - totalR - 2, divY, gemStartX + (order.length - 1) * gemSpacing + totalR + 2, divY); - order.forEach((color, ci) => { - const ccx = gemStartX + ci * gemSpacing; - const total = (color === GOLD ? 0 : (p.bonuses[color] ?? 0)) + (p.tokens[color] ?? 0); - const tg = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - tg.fillStyle(GEM_HEX[color], total > 0 ? 0.8 : 0.2).fillCircle(ccx, totalCY, totalR); - tg.lineStyle(2, GEM_EDGE[color], 1).strokeCircle(ccx, totalCY, totalR); - this.reg(this.add.text(ccx, totalCY, String(total), { - fontFamily: 'Righteous', fontSize: '14px', - color: color === 'white' ? '#222' : '#fff', - }).setOrigin(0.5).setDepth(DEPTH.ui + 2)); - }); - - // noble thumbnails — right-aligned below the total circles row - if (p.nobles.length > 0) { - const nobleCount = p.nobles.length; - const nobleGroupW = nobleCount * NOBLE_THUMB + (nobleCount - 1) * NOBLE_THUMB_GAP; - const nobleGroupLeft = x + w - 16 - nobleGroupW; - const nTY = totalCY + 14 + 3; - p.nobles.forEach((noble, ni) => { - if (this.animatingNoble?.seat === idx && this.animatingNoble?.nobleId === noble.id) return; - const nTX = nobleGroupLeft + ni * (NOBLE_THUMB + NOBLE_THUMB_GAP); - const ng = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - ng.fillStyle(0x000000, 0.32).fillRoundedRect(nTX + 2, nTY + 2, NOBLE_THUMB, NOBLE_THUMB, 4); - ng.fillStyle(0x2b2620, 1).fillRoundedRect(nTX, nTY, NOBLE_THUMB, NOBLE_THUMB, 4); - if (this.hasArt) { - this.regMaskedImg(nTX, nTY, NOBLE_THUMB, NOBLE_THUMB, 'splendor-cards', nobleFrame(noble), DEPTH.ui + 2, 4); - } - this.reg(this.add.graphics().setDepth(DEPTH.ui + 3)) - .lineStyle(1.5, COLORS.accent, 0.85).strokeRoundedRect(nTX, nTY, NOBLE_THUMB, NOBLE_THUMB, 4); - this.reg(this.add.text(nTX + 3, nTY + 1, '3', { - fontFamily: 'Righteous', fontSize: '10px', color: COLORS.goldHex, - }).setDepth(DEPTH.ui + 4)); - }); - } - - // bought card thumbnails (right of portrait, left of gems, wrapping into rows) - (this.boughtCards[idx] ?? []).forEach((bc, bi) => { - if (this.animatingBuy?.seat === idx && this.animatingBuy?.cardId === bc.id) return; - const col = bi % THUMB_PER_ROW; - const row = Math.floor(bi / THUMB_PER_ROW); - const tx = x + THUMB_AREA_REL_X + col * (THUMB_W + THUMB_GAP); - const ty = y + THUMB_ROW_TOP_REL + row * (THUMB_H + THUMB_ROW_GAP); - const tg = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - tg.fillStyle(0x000000, 0.32).fillRoundedRect(tx + 2, ty + 2, THUMB_W, THUMB_H, 4); - tg.fillStyle(0x14110b, 1).fillRoundedRect(tx, ty, THUMB_W, THUMB_H, 4); - tg.fillStyle(GEM_HEX[bc.bonus], 0.22).fillRoundedRect(tx, ty, THUMB_W, THUMB_H, 4); - if (this.hasArt) { - this.regMaskedImg(tx, ty, THUMB_W, THUMB_H, 'splendor-cards', cardFrame(bc), DEPTH.ui + 2, 4); - } - this.reg(this.add.graphics().setDepth(DEPTH.ui + 3)) - .lineStyle(1, GEM_EDGE[bc.bonus], 0.9).strokeRoundedRect(tx, ty, THUMB_W, THUMB_H, 4); - if (bc.points > 0) { - this.reg(this.add.text(tx + 3, ty + 1, String(bc.points), { - fontFamily: 'Righteous', fontSize: '10px', - color: bc.bonus === 'white' ? '#333' : '#fff', - }).setDepth(DEPTH.ui + 4)); - } - // 500 ms hover-intent preview - const tz = this.reg( - this.add.zone(tx + THUMB_W / 2, ty + THUMB_H / 2, THUMB_W, THUMB_H) - .setInteractive().setDepth(DEPTH.ui + 5) - ); - tz.on('pointerover', () => { - this._thumbHoverTimer = this.time.delayedCall(500, () => { - for (const p of this.portraits) p?.hide(); - this.showCardPreview(bc, tx + THUMB_W / 2, ty + THUMB_H); - }); - }); - tz.on('pointerout', () => { - if (this._thumbHoverTimer) { this._thumbHoverTimer.remove(); this._thumbHoverTimer = null; } - this.clearPreview(); - for (const p of this.portraits) p?.show(); - }); - }); - - // reserved cards - const rN = p.reserved.length; - this.reg(this.add.text(x + 16, y + h - 30, `Reserved: ${rN}/${MAX_RESERVED}`, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setDepth(DEPTH.ui + 1)); - if (rN > 0) { - const isHuman = idx === this.humanSeat; - p.reserved.forEach((card, ri) => { - if (this.animatingReserve?.seat === idx && this.animatingReserve?.cardId === card.id) return; - const rx = x + 150 + ri * 116, ry = y + h - 40; - const canBuy = isHuman && this.isHumanTurn() && canAfford(p, card); - const mg = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - mg.fillStyle(GEM_HEX[card.bonus], 0.85).fillRoundedRect(rx, ry, 104, 30, 6); - mg.lineStyle(2, canBuy ? 0x57c46a : GEM_EDGE[card.bonus], canBuy ? 1 : 0.8) - .strokeRoundedRect(rx, ry, 104, 30, 6); - this.reg(this.add.text(rx + 52, ry + 15, - `${card.points || ''} ${'★'.repeat(card.tier)}`.trim(), { - fontFamily: 'Righteous', fontSize: '14px', - color: card.bonus === 'white' ? '#222' : '#fff', - }).setOrigin(0.5).setDepth(DEPTH.ui + 2)); - const z = this.reg(this.add.zone(rx + 52, ry + 15, 104, 30) - .setInteractive({ useHandCursor: isHuman && this.isHumanTurn() }) - .setDepth(DEPTH.ui + 3)); - z.on('pointerover', () => this.showCardPreview(card, rx + 52, ry + 30)); - z.on('pointerout', () => this.clearPreview()); - if (isHuman && this.isHumanTurn()) { - z.on('pointerdown', () => this.onCardClick(card, 'reserve')); - } - }); - } - }); - } - - // ── bottom control bar ────────────────────────────────────────────────────── - drawControlBar() { - const n = this.gs?.players?.length ?? 4; - const panelGap = 16; - const panelH = Math.min(220, Math.floor((GAME_HEIGHT - 90 - panelGap * (n - 1)) / n)); - const lastPanelBottom = 76 + (n - 1) * (panelH + panelGap) + panelH; - const x = MARKET_X, y = CONTROL_Y, w = 920, h = Math.max(120, lastPanelBottom - y); - const g = this.reg(this.add.graphics().setDepth(DEPTH.ui)); - g.fillStyle(0x000000, 0.55).fillRoundedRect(x, y, w, h, 12); - g.lineStyle(1, COLORS.accent, 0.4).strokeRoundedRect(x, y, w, h, 12); - - if (isGameOver(this.gs)) return; - - // Discard prompt - if (this.gs.phase === 'discard' && this.gs.current === this.humanSeat) { - const over = tokenTotal(currentPlayer(this.gs)) - HAND_LIMIT; - this.reg(this.add.text(x + 20, y + 18, - `Over the ${HAND_LIMIT}-token limit — return ${over} token${over === 1 ? '' : 's'}.`, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.dangerHex, - }).setDepth(DEPTH.ui + 1)); - this.reg(this.add.text(x + 20, y + 52, 'Click your tokens in the panel at right to return them.', { - fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex, - }).setDepth(DEPTH.ui + 1)); - return; - } - - if (!this.isHumanTurn()) { - this.reg(this.add.text(x + 20, y + 22, `${this.pname(this.gs.current)} is thinking…`, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setDepth(DEPTH.ui + 1)); - return; - } - - // Human turn — card selected → buy/reserve options - if (this.selectedCard) { - const { card, source } = this.selectedCard; - const human = this.gs.players[this.humanSeat]; - this.reg(this.add.text(x + 20, y + 16, - `Tier ${card.tier} • ${GEM_NAME[card.bonus]}${card.points ? ` • ${card.points} pts` : ''}`, { - fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, - }).setDepth(DEPTH.ui + 1)); - let bx = x + 24; - if (canAfford(human, card)) { - this.addButton(bx + 80, y + 70, 'Buy', () => this.applyHuman({ type: 'buy', cardId: card.id, source }), - { width: 150, height: 46 }); - bx += 170; - } - if (source === 'board' && human.reserved.length < MAX_RESERVED) { - this.addButton(bx + 115, y + 70, 'Reserve (+1 gold)', - () => this.applyHuman({ type: 'reserve', cardId: card.id, tier: card.tier }), - { width: 230, height: 46, variant: 'ghost' }); - bx += 285; - } - this.addButton(bx + 70, y + 70, 'Cancel', () => { this.selectedCard = null; this.render(); }, - { width: 130, height: 46, variant: 'ghost' }); - return; - } - - // Token selection - if (this.selection.length > 0) { - this.reg(this.add.text(x + 20, y + 16, 'Taking gems:', { - fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, - }).setDepth(DEPTH.ui + 1)); - this.selection.forEach((color, i) => { - const cx = x + 160 + i * 44; - const cg = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - cg.fillStyle(GEM_HEX[color], 1).fillCircle(cx, y + 26, 16); - cg.lineStyle(2, GEM_EDGE[color], 1).strokeCircle(cx, y + 26, 16); - }); - this.addButton(x + 110, y + 78, 'Take', () => this.confirmTake(), { width: 160, height: 44 }); - this.addButton(x + 290, y + 78, 'Clear', () => { this.selection = []; this.render(); }, - { width: 140, height: 44, variant: 'ghost' }); - return; - } - - this.reg(this.add.text(x + 20, y + 26, - 'Your turn — take gems (3 different, or 2 of one), or click a card to buy or reserve.', { - fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, - wordWrap: { width: w - 40 }, - }).setDepth(DEPTH.ui + 1)); - } - - addButton(x, y, label, fn, opts = {}) { - const b = new Button(this, x, y, label, fn, { fontSize: 20, ...opts }).setDepth(DEPTH.ui + 2); - this.dyn.push(b); - return b; - } - - drawTurnLabel() { - const txt = isGameOver(this.gs) ? 'Game over' : `${this.pname(this.gs.current)}'s turn`; - this.reg(this.add.text(BANK_X, GAME_HEIGHT - 48, txt, { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(DEPTH.ui + 1)); - } - - // ── helpers ───────────────────────────────────────────────────────────────── - isHumanTurn() { - return !this.busy && this.gs.phase === 'turn' && this.gs.current === this.humanSeat; - } - pname(seat) { return this.gs.players[seat]?.name ?? `Player ${seat}`; } - - // Returns the screen centre of any player's gem cell for a given colour. - playerGemPos(seat, color) { - const n = this.gs.players.length; - const gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const order = [...GEMS, GOLD]; - const totalR = 14; - const gemSpacing = 36; - const gemStartX = PANEL_X + PANEL_W - 16 - totalR - (order.length - 1) * gemSpacing; - const ci = order.indexOf(color); - return { x: gemStartX + ci * gemSpacing, y: 76 + seat * (h + gap) + 70 }; - } - - humanGemPos(color) { return this.playerGemPos(this.humanSeat, color); } - - // Animate gems taken by an AI player from the bank to their panel. - animAITake(seat, action) { - const taken = action.type === 'take2' - ? [action.color, action.color] - : action.colors; - - const preTokens = { ...this.gs.players[seat].tokens }; - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard') { - this.gs = applyDiscard(this.gs, defaultDiscards(this.gs)); - } - const postTokens = this.gs.players[seat].tokens; - - // Render with pre-take token counts so the panel doesn't jump yet - this.gs.players[seat].tokens = preTokens; - this.render(); - this.gs.players[seat].tokens = postTokens; - - const gemOrder = [...GEMS, GOLD]; - let pending = taken.length; - taken.forEach((color, i) => { - const srcX = BANK_X, srcY = BANK_Y0 + gemOrder.indexOf(color) * BANK_STEP; - const dest = this.playerGemPos(seat, color); - const gem = this.add.image(srcX, srcY, 'splendor-gems', gemFrame(color)) - .setDisplaySize(56, 56).setDepth(DEPTH.popup); - this.tweens.add({ - targets: gem, - x: dest.x, y: dest.y, - displayWidth: 26, displayHeight: 26, - duration: 380, - delay: i * 90, - ease: 'Cubic.easeOut', - onStart: () => { - try { - const a = new Audio(`assets/fx/gem-0${(i % 2) + 1}.mp3`); - a.volume = 0.7; a.play(); - } catch { /* */ } - }, - onComplete: () => { - gem.destroy(); - if (--pending === 0) { - this.busy = false; - this.render(); - this.advance(); - } - }, - }); - }); - } - - // Animates a gem icon from its bank position to the Take-bar selection slot. - animGemToSelection(color, destIdx) { - if (!this.hasGems) return; - const order = [...GEMS, GOLD]; - const srcX = BANK_X, srcY = BANK_Y0 + order.indexOf(color) * BANK_STEP; - const dstX = MARKET_X + 160 + destIdx * 44; - const dstY = CONTROL_Y + 26; - const gem = this.add.image(srcX, srcY, 'splendor-gems', gemFrame(color)) - .setDisplaySize(56, 56).setDepth(DEPTH.popup); - this.tweens.add({ - targets: gem, - x: dstX, y: dstY, - displayWidth: 32, displayHeight: 32, - duration: 300, - ease: 'Cubic.easeOut', - onStart: () => { - try { - const a = new Audio(`assets/fx/gem-0${(destIdx % 2) + 1}.mp3`); - a.volume = 0.7; a.play(); - } catch { /* */ } - }, - onComplete: () => gem.destroy(), - }); - } - - // ── noble animation ────────────────────────────────────────────────────────── - animNoble(seat, noble, srcX, srcY, onDone) { - const DISP = 270; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - - for (const p of this.portraits) p?.hide(); - - const overlay = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000) - .setAlpha(0).setDepth(DEPTH.popup); - this.tweens.add({ targets: overlay, alpha: 0.52, duration: 280 }); - - const container = this.add.container(srcX, srcY).setDepth(DEPTH.popup + 1); - const bg = this.add.graphics(); - bg.fillStyle(0x2b2620, 1).fillRoundedRect(-NOBLE / 2, -NOBLE / 2, NOBLE, NOBLE, 10); - container.add(bg); - if (this.hasArt) { - container.add( - this.add.image(0, 0, 'splendor-cards', nobleFrame(noble)).setDisplaySize(NOBLE, NOBLE) - ); - } - const border = this.add.graphics(); - border.lineStyle(2, COLORS.accent, 0.9).strokeRoundedRect(-NOBLE / 2, -NOBLE / 2, NOBLE, NOBLE, 10); - container.add(border); - container.add(this.add.text(-NOBLE / 2 + 8, -NOBLE / 2 + 4, '3', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.goldHex, + dyn.push(...drawGallery(this, view, { slots: this.nobleSlots, depth: D.gallery, tooltip: this.tooltip, hideNobles: opts.hideNobles, names: this.names })); + dyn.push(...drawTrack(this, view, { depth: D.track + 1, names: this.names })); + dyn.push(...drawBank(this, view, { + depth: D.bank, selection: live ? this.tray : [], interactive: live, + pickable: (c) => this.pickable(c), onPick: (c) => this.pickGem(c), tooltip: this.tooltip, })); + this.drawDecks(view, live); - this.tweens.add({ - targets: container, - x: cx, y: cy, - scale: DISP / NOBLE, - duration: 420, - ease: 'Cubic.easeOut', - onComplete: () => { - this._playReserveFireworks(cx, cy, 'white'); - try { const a = new Audio('assets/fx/firework.mp3'); a.volume = 0.7; a.play(); } catch { /* */ } - - this.time.delayedCall(1200, () => { - const ni = this.gs.players[seat].nobles.findIndex((n) => n.id === noble.id); - const { cx: thumbCX, cy: thumbCY } = this.nobleThumbPos(seat, ni >= 0 ? ni : 0); - - this.tweens.add({ targets: overlay, alpha: 0, duration: 300, - onComplete: () => { try { overlay.destroy(); } catch { /* */ } } }); - try { const a = new Audio('assets/fx/ui-attach.mp3'); a.volume = 0.8; a.play(); } catch { /* */ } - - this.tweens.add({ - targets: container, - x: thumbCX, y: thumbCY, - scale: NOBLE_THUMB / NOBLE, - alpha: 0, - duration: 360, - ease: 'Cubic.easeIn', - onComplete: () => { - for (const p of this.portraits) p?.show(); - container.removeAll(true); - container.destroy(); - onDone(); - }, - }); - }); - }, - }); - } - - // Builds a card container centred at (x,y) in world space with full overlay art. - // All draw coords are in container-local space (0,0 = card centre). - _buildCardContainer(x, y, card) { - const container = this.add.container(x, y).setDepth(DEPTH.popup + 1); - const tint = GEM_HEX[card.bonus]; - - // Background - const bg = this.add.graphics(); - bg.fillStyle(0x14110b, 1).fillRoundedRect(-CW / 2, -CH / 2, CW, CH, 10); - bg.fillStyle(tint, 0.22).fillRoundedRect(-CW / 2, -CH / 2, CW, CH, 10); - container.add(bg); - - // Art - if (this.hasArt) { - container.add( - this.add.image(0, 0, 'splendor-cards', cardFrame(card)).setDisplaySize(CW, CH) - ); - } - - // Border above art - const border = this.add.graphics(); - border.lineStyle(1.5, GEM_EDGE[card.bonus], 1).strokeRoundedRect(-CW / 2, -CH / 2, CW, CH, 10); - container.add(border); - - // Points — top-left - if (card.points > 0) { - container.add(this.add.text(-CW / 2 + 10, -CH / 2 + 2, String(card.points), { - fontFamily: 'Righteous', fontSize: '26px', - color: card.bonus === 'white' ? '#222' : '#fff', + for (const Lr of this.layout.ledgers) { + const isMe = Lr.seat === HUMAN; + dyn.push(...drawLedger(this, view, Lr, { + depth: D.ledger, viewer: HUMAN, names: this.names, skills: this.skills, tooltip: this.tooltip, + hideCards: opts.hideCards, hideNobles: opts.hideNobles, + active: view.current === Lr.seat && view.phase !== 'gameOver', + onReserved: isMe && live ? (c, r) => this.onCardClick(c, 'reserve', r) : null, + extraFor: isMe && live ? (c, r) => this.reserveExtras(c, r, human, hints) : null, + preview: (c, r) => this.queuePreview(c, r, isMe && live ? 'reserve' : null), + unpreview: () => this.clearHover(), })); } - // Gem bonus badge — top-right - const badgeG = this.add.graphics(); - badgeG.fillStyle(GEM_HEX[card.bonus], 1).fillCircle(CW / 2 - 22, -CH / 2 + 15, 12); - badgeG.lineStyle(2, GEM_EDGE[card.bonus], 1).strokeCircle(CW / 2 - 22, -CH / 2 + 15, 12); - container.add(badgeG); - if (this.hasGems) { - container.add( - this.add.image(CW / 2 - 22, -CH / 2 + 15, 'splendor-gems', gemFrame(card.bonus)) - .setDisplaySize(18, 18) - ); + // Market: highlights, owed chips, rivals' reach, input zones. + for (const sp of this.cardSprites.values()) { + if (sp.detached) continue; + const pos = L.boardSlotOf(view, sp.card.id); + if (!pos) continue; + const r = slotRect(pos.tier, pos.slot); + if (hints) this.highlightCard(sp, r, human); + if (this.settings.reach) this.drawReach(view, sp.card, r); + const z = this.add.zone(r.x + CW / 2, r.y + CH / 2, CW, CH).setInteractive({ useHandCursor: live }).setDepth(D.hint + 1); + z.on('pointerover', () => this.queuePreview(sp.card, r, live ? 'board' : null)); + z.on('pointerout', () => this.clearHover()); + if (live) z.on('pointerdown', () => this.onCardClick(sp.card, 'board', r)); + dyn.push(z); } - - // Cost pips — lower-left, stacked - const costs = GEMS.filter((c) => (card.cost[c] ?? 0) > 0); - costs.forEach((c, i) => { - const pipY = CH / 2 - 22 - i * 30; - const pipG = this.add.graphics(); - pipG.fillStyle(GEM_HEX[c], 1).fillCircle(-CW / 2 + 20, pipY, 12); - pipG.lineStyle(2, GEM_EDGE[c], 1).strokeCircle(-CW / 2 + 20, pipY, 12); - container.add(pipG); - container.add(this.add.text(-CW / 2 + 20, pipY, String(card.cost[c]), { - fontFamily: 'Righteous', fontSize: '15px', - color: c === 'white' ? '#222' : '#fff', - }).setOrigin(0.5)); - }); - - return container; + if (live && this.selected) this.drawSelection(); + this.refreshDock(view); } - // ── reserve animation ─────────────────────────────────────────────────────── - animReserve(seat, card, srcX, srcY, onDone) { - const PW = 270, PH = 390; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - - // DOM video portraits render above the canvas; hide them for the duration - for (const p of this.portraits) p?.hide(); - - const overlay = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000) - .setAlpha(0).setDepth(DEPTH.popup); - this.tweens.add({ targets: overlay, alpha: 0.52, duration: 280 }); - - const container = this._buildCardContainer(srcX, srcY, card); - - // Phase 1: fly to centre and grow - this.tweens.add({ - targets: container, - x: cx, y: cy, - scaleX: PW / CW, scaleY: PH / CH, - duration: 420, - ease: 'Cubic.easeOut', - onComplete: () => { - this._playReserveFireworks(cx, cy, card.bonus); - - // Phase 2: hold 1.2 s, then shrink to reserve-pill slot - this.time.delayedCall(1200, () => { - const n = this.gs.players.length; - const gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const panelY = 76 + seat * (h + gap); - const ri = this.gs.players[seat].reserved.findIndex((c) => c.id === card.id); - const pillCX = PANEL_X + 150 + Math.max(0, ri) * 116 + 52; - const pillCY = panelY + h - 40 + 15; - - this.tweens.add({ targets: overlay, alpha: 0, duration: 300, - onComplete: () => { try { overlay.destroy(); } catch { /* */ } } }); - - try { const a = new Audio('assets/fx/ui-attach.mp3'); a.volume = 0.8; a.play(); } catch { /* */ } - - this.tweens.add({ - targets: container, - x: pillCX, y: pillCY, - scale: 0.08, - alpha: 0, - duration: 360, - ease: 'Cubic.easeIn', - onComplete: () => { - for (const p of this.portraits) p?.show(); - container.removeAll(true); - container.destroy(); - onDone(); - }, - }); - }); - }, - }); - } - - _playReserveFireworks(cx, cy, bonus) { - // 5 distinct bursts staggered in time, each at a random position around the card - const tint = GEM_HEX[bonus]; - const edge = GEM_EDGE[bonus]; - const palettes = [ - [tint, edge, 0xffffff], - [0xffd700, 0xffbb00, 0xffffff], - [tint, 0xffffff, edge], - [0xff6644, 0xffaa00, 0xffd700], - [edge, tint, 0xaaffdd], - ]; - - const BURSTS = 5; - // Card at center is 270×390; place bursts in a ring around it - const RX = 195, RY = 240; // semi-axes of the ring (just outside card edges) - - for (let b = 0; b < BURSTS; b++) { - const delay = b * 190 + Math.random() * 70; - // Spread bursts evenly around the card with some jitter - const angle = (b / BURSTS) * Math.PI * 2 + (Math.random() - 0.5) * 0.7; - const rScale = 1.05 + Math.random() * 0.55; - const bx = cx + Math.cos(angle) * RX * rScale; - const by = cy + Math.sin(angle) * RY * rScale; - const palette = palettes[b % palettes.length]; - const sparkCount = 16 + Math.floor(Math.random() * 8); - - this.time.delayedCall(delay, () => { - try { const fw = new Audio('assets/fx/firework.mp3'); fw.volume = 0.7; fw.play(); } catch { /* */ } - - // Central flash — expands and fades - const flash = this.add.circle(bx, by, 7, palette[0], 1).setDepth(DEPTH.popup + 2); - this.tweens.add({ - targets: flash, scaleX: 4.5, scaleY: 4.5, alpha: 0, - duration: 260, ease: 'Cubic.easeOut', - onComplete: () => { try { flash.destroy(); } catch { /* */ } }, - }); - - // Sparks radiate outward from the burst point - for (let i = 0; i < sparkCount; i++) { - const sparkAngle = (i / sparkCount) * Math.PI * 2 + (Math.random() - 0.5) * 0.3; - const speed = 90 + Math.random() * 170; - const size = 2.5 + Math.random() * 5; - const color = palette[Math.floor(Math.random() * palette.length)]; - const spark = this.add.circle(bx, by, size, color, 1).setDepth(DEPTH.popup + 2); - this.tweens.add({ - targets: spark, - x: bx + Math.cos(sparkAngle) * speed, - y: by + Math.sin(sparkAngle) * speed + speed * 0.28, // slight gravity droop - scaleX: 0.12, scaleY: 0.12, - alpha: 0, - duration: 600 + Math.random() * 480, - ease: 'Cubic.easeOut', - onComplete: () => { try { spark.destroy(); } catch { /* */ } }, - }); + drawDecks(view, live) { + for (const t of [1, 2, 3]) { + const r = deckRect(t); + const n = view.decks[t].length; + const cx = r.x + CW / 2, cy = r.y + CH / 2; + const g = this.add.graphics().setDepth(D.deck); + if (n > 0) { + const layers = Math.min(7, Math.ceil(n / 5)); + g.fillStyle(0x000000, 0.4).fillRoundedRect(r.x + 3, r.y + 6 + layers * 2, CW, CH, 9); + for (let i = layers; i >= 1; i--) { + g.fillStyle(i % 2 ? 0xe6d6ae : 0xcdb98a, 1).fillRoundedRect(r.x + i * 0.6, r.y + i * 2.2, CW, CH, 9); + g.lineStyle(1, 0x3a2810, 0.5).strokeRoundedRect(r.x + i * 0.6, r.y + i * 2.2, CW, CH, 9); } - }); + this.dyn.push(g); + this.dyn.push(this.add.image(cx, cy, backKey(t)).setDisplaySize(CW, CH).setDepth(D.deck + 1)); + } else { + g.lineStyle(2, 0xd6b260, 0.35).strokeRoundedRect(r.x, r.y, CW, CH, 10); + this.dyn.push(g); + this.dyn.push(this.add.text(cx, cy, 'exhausted', { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#a89070' }).setOrigin(0.5).setDepth(D.deck + 1)); + } + const pg = this.add.graphics().setDepth(D.deck + 2); + pg.fillStyle(0x140a04, 0.88).fillRoundedRect(cx - 26, r.y + CH - 30, 52, 22, 8); + pg.lineStyle(1.5, 0xd9b45a, 0.9).strokeRoundedRect(cx - 26, r.y + CH - 30, 52, 22, 8); + this.dyn.push(pg); + this.dyn.push(this.add.text(cx, r.y + CH - 19, String(n), { fontFamily: SERIF, fontSize: '15px', fontStyle: 'bold', color: '#f3e6c8' }).setOrigin(0.5).setDepth(D.deck + 3)); + const canReserve = live && n > 0 && view.players[HUMAN].reserved.length < MAX_RESERVED; + const z = this.add.zone(cx, cy, CW, CH).setInteractive({ useHandCursor: canReserve }).setDepth(D.deck + 4); + this.tooltip.attachTo(z, () => ({ + title: `${TIER_NAME[t]} — deck`, + lines: [plural(n, 'card') + ' left.', canReserve ? 'Click to reserve the top card sight unseen (+1 gold).' : (live && n > 0 ? 'Your reserve is full (3).' : '')].filter(Boolean), + })); + if (canReserve) z.on('pointerdown', () => this.confirmBlindReserve(t)); + this.dyn.push(z); } } - // ── buy animation ──────────────────────────────────────────────────────────── - animBuy(seat, card, srcX, srcY, onDone) { - if (!this.hasArt) { onDone(); return; } + // Three-tier buy highlighting for one market card. + highlightCard(sp, r, human) { + const st = L.affordState(human, sp.card); + if (st.kind === 'now' || st.kind === 'gold') { + this.fx.push(makeBlaze(this, r, { kind: st.kind, gem: sp.card.bonus, depth: D.glow, goldUsed: st.gold })); + this.breathing.push(this.tweens.add({ targets: sp.c, scaleX: 1.035, scaleY: 1.035, duration: 650, yoyo: true, repeat: -1, ease: 'Sine.InOut' })); + } else if (st.kind === 'near') { + this.fx.push(makeBlaze(this, r, { kind: 'near', depth: D.glow })); + } else { + sp.img.setTint(0x8c8478); + } + this.drawOwed(sp.card, r, human); + } - const PW = 270, PH = 390; - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - - for (const p of this.portraits) p?.hide(); - - const overlay = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000) - .setAlpha(0).setDepth(DEPTH.popup); - this.tweens.add({ targets: overlay, alpha: 0.52, duration: 280 }); - - const container = this._buildCardContainer(srcX, srcY, card); - - this.tweens.add({ - targets: container, - x: cx, y: cy, - scaleX: PW / CW, scaleY: PH / CH, - duration: 420, - ease: 'Cubic.easeOut', - onComplete: () => { - this._playReserveFireworks(cx, cy, card.bonus); - - this.time.delayedCall(1200, () => { - const bought = this.boughtCards[seat] ?? []; - const bi = bought.findIndex((c) => c.id === card.id); - const { cx: thumbCX, cy: thumbCY } = this.boughtCardThumbPos(seat, bi >= 0 ? bi : bought.length - 1); - - this.tweens.add({ targets: overlay, alpha: 0, duration: 300, - onComplete: () => { try { overlay.destroy(); } catch { /* */ } } }); - - try { const a = new Audio('assets/fx/ui-attach.mp3'); a.volume = 0.8; a.play(); } catch { /* */ } - - this.tweens.add({ - targets: container, - x: thumbCX, y: thumbCY, - scaleX: THUMB_W / CW, scaleY: THUMB_H / CH, - alpha: 0, - duration: 360, - ease: 'Cubic.easeIn', - onComplete: () => { - for (const p of this.portraits) p?.show(); - container.removeAll(true); - container.destroy(); - onDone(); - }, - }); - }); - }, + // Cost chips annotated with what is still owed after the bonuses. + drawOwed(card, r, human) { + const rows = L.effectiveCost(human, card); + const g = this.add.graphics().setDepth(D.hint); + this.dyn.push(g); + rows.forEach((row, i) => { + const px = r.x + 18, py = r.y + CH - 18 - i * 25; + if (row.covered >= row.printed) { + g.fillStyle(0x0c0804, 0.62).fillCircle(px, py, 11.5); + this.dyn.push(this.add.text(px, py, '✓', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'bold', color: '#ffd87a' }).setOrigin(0.5).setDepth(D.hint + 0.5)); + return; + } + if (row.short > 0) g.lineStyle(2.5, 0xff5a4a, 0.95).strokeCircle(px, py, 12.5); + if (row.covered > 0) { + const bx = px + 13, by = py - 8; + g.fillStyle(row.short > 0 ? 0x9a2a1a : 0x2a7a3a, 1).fillCircle(bx, by, 7.5); + g.lineStyle(1, 0xf3e6c8, 0.9).strokeCircle(bx, by, 7.5); + this.dyn.push(this.add.text(bx, by, String(row.owed), { fontFamily: SERIF, fontSize: '10px', fontStyle: 'bold', color: '#ffffff' }).setOrigin(0.5).setDepth(D.hint + 0.5)); + } }); } - // ── human input ───────────────────────────────────────────────────────────── - onTokenClick(color) { - if (!this.isHumanTurn()) return; - this.selectedCard = null; - const sel = this.selection; - const sameCount = sel.filter((c) => c === color).length; - const lenBefore = sel.length; - - if (sel.length === 0) { sel.push(color); } - else if (sel.length === 1 && sel[0] === color) { - if (this.gs.bank[color] >= TAKE_SAME_MIN) sel.push(color); - } else if (sel.length < 3 && sameCount === 0) { - const isTake2 = sel.length === 2 && sel[0] === sel[1]; - if (!isTake2) sel.push(color); + drawReach(view, card, r) { + let k = 0; + for (const p of view.players) { + if (p.seat === HUMAN || !L.canAfford(p, card)) continue; + const x = r.x + CW - 10, y = r.y + 64 + k * 17; + this.dyn.push(this.add.image(x, y, 'spl-pawn').setDisplaySize(16, 16).setTint(SEAT_HEX[p.seat]).setDepth(D.reach)); + k++; } + if (k) { + const z = this.add.zone(r.x + CW - 10, r.y + 64 + (k - 1) * 8.5, 18, k * 17).setInteractive().setDepth(D.reach + 3); + this.tooltip.attachTo(z, () => ({ + title: "Rivals' reach", + lines: view.players.filter((p) => p.seat !== HUMAN && L.canAfford(p, card)).map((p) => `${this.names[p.seat]} can afford this now.`), + })); + this.dyn.push(z); + } + } - const destIdx = sel.length - 1; - const added = sel.length > lenBefore; - this.render(); - if (added) this.animGemToSelection(color, destIdx); + reserveExtras(card, r, human, hints) { + const objs = []; + if (hints) { + const st = L.affordState(human, card); + if (st.kind === 'now' || st.kind === 'gold') this.fx.push(makeBlaze(this, r, { kind: st.kind, gem: card.bonus, depth: D.ledger + 1, goldUsed: st.gold, sparkles: false })); + else if (st.kind === 'near') this.fx.push(makeBlaze(this, r, { kind: 'near', depth: D.ledger + 1, tagText: '1 away' })); + } + return objs; + } + + drawSelection() { + const { card, source, rect: r } = this.selected; + const human = this.gs.players[HUMAN]; + const g = this.add.graphics().setDepth(D.select); + g.lineStyle(4, 0xfff0b0, 1).strokeRoundedRect(r.x - 5, r.y - 5, r.w + 10, r.h + 10, 12); + this.dyn.push(g); + const cx = r.x + r.w / 2; + const afford = L.canAfford(human, card); + const canRes = source === 'board' && human.reserved.length < MAX_RESERVED; + const btns = []; + if (afford) btns.push(['Acquire', () => this.humanAct({ type: 'buy', cardId: card.id, source }), 0x2a5a30]); + if (canRes) btns.push([this.gs.bank.gold > 0 ? 'Reserve +gold' : 'Reserve', () => this.humanAct({ type: 'reserve', cardId: card.id, tier: card.tier }), 0x5a3820]); + const baseY = source === 'board' ? r.y + r.h - 18 - (btns.length - 1) * 32 : r.y - 22 - (btns.length - 1) * 32; + btns.forEach(([label, fn, bg], i) => { + this.dyn.push(new Button(this, cx, baseY + i * 32, label, fn, { width: Math.max(116, r.w - 8), height: 28, fontSize: 14, bg }).setDepth(D.select + 1)); + }); + } + + // ── the dock ─────────────────────────────────────────────────────────────────────────── + refreshDock(view = this.gs) { + this.dockObjs.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); + this.dockObjs = []; + if (!this.gs) return; + this.dockObjs = drawDock(this, this.dockFor(view), D.dock); + } + + dockFor(view) { + if (this.dockSpec) return this.dockSpec; + const gs = this.gs; + if (L.isGameOver(gs)) return { title: 'The books are closed', body: 'The guild tallies the ledgers…' }; + const undoBtn = this.undoSnap && this.aiTimer && this.settings.undo + ? [{ label: 'Undo (Z)', fn: () => this.undo(), bg: 0x6a4a1a }] : []; + if (this.actingSeat != null) { + const seat = this.actingSeat; + return seat === HUMAN ? { title: 'Your move', body: '' } : { title: `${this.names[seat]}'s move`, body: '' }; + } + if (gs.current !== HUMAN) { + return { title: `${this.names[gs.current]}'s turn`, body: 'Weighing the market…', buttons: undoBtn }; + } + if (!this.canAct()) return { title: 'Your turn', body: '' }; + const human = gs.players[HUMAN]; + if (this.tray.length) { + const act = this.trayAction(); + const after = L.tokenTotal(human) + this.tray.length; + const body = `${this.tray.map((c) => GEM_NAME[c]).join(', ')}. ${act ? 'Take them?' : this.trayHint()}`; + return { + title: 'Taking gems', body, tray: this.tray, trayHidden: this.trayPending, onTray: (i) => { this.tray.splice(i, 1); this.refresh(); }, + warn: after > HAND_LIMIT ? `You'll hold ${after} — ${after - HAND_LIMIT} must go back to the case.` : null, + buttons: [ + ...(act ? [{ label: 'Take (Enter)', fn: () => this.confirmTake(), bg: 0x2a5a30 }] : []), + { label: 'Clear (Esc)', fn: () => { this.tray = []; this.refresh(); }, bg: 0x5a3820 }, + ], + }; + } + if (this.dockHover) return this.dockHover; + if (this.selected) { + const { card } = this.selected; + return { + title: locationOf(this.selected.card), + body: this.payText(human, card) + (this.selected.source === 'board' && human.reserved.length >= MAX_RESERVED ? ' Your reserve is full.' : ''), + buttons: [{ label: 'Cancel (Esc)', fn: () => { this.selected = null; this.refresh(); }, bg: 0x5a3820 }], + }; + } + return { + title: 'Your turn', + body: 'Pick gems from the jewel case — three different, or two of a kind from a pile of four or more — or click a card to acquire or reserve it. Click a deck to reserve blind.', + }; + } + + payText(p, card) { + const pv = L.previewBuy(this.gs, p, card); + const parts = []; + if (pv.affordable) { + const pay = GEMS.filter((g) => pv.pay[g]).map((g) => `${pv.pay[g]} ${GEM_NAME[g]}`); + if (pv.gold) pay.push(plural(pv.gold, 'gold')); + parts.push(pay.length ? `Pay ${pay.join(', ')}.` : 'Free — your bonuses cover it all!'); + } else { + const rows = L.effectiveCost(p, card).filter((r) => r.short > 0); + const gold = p.tokens.gold; + parts.push(`Missing ${rows.map((r) => `${r.short} ${GEM_NAME[r.color]}`).join(', ')}${gold ? ` (your ${plural(gold, 'gold')} cover${gold === 1 ? 's' : ''} ${Math.min(gold, rows.reduce((n, r) => n + r.short, 0))})` : ''}.`); + } + if (pv.saved) parts.push(`Bonuses save ${plural(pv.saved, 'gem')}.`); + parts.push(`+1 ${GEM_NAME[card.bonus]} bonus${card.points ? `, +${card.points} prestige` : ''}.`); + for (const n of pv.nobles) { + const info = nobleInfo(n.noble); + parts.push(n.after >= n.need ? `${info.name} will visit (+3)!` : `${info.name} ${n.after}/${n.need}.`); + } + return parts.join(' '); + } + + // ── hover: preview, payment preview ───────────────────────────────────────────────────── + queuePreview(card, rect, actionable) { + this.clearHover(); + if (actionable && this.canAct() && !this.tray.length) { + const human = this.gs.players[HUMAN]; + this.dockHover = { title: locationOf(card), body: this.payText(human, card) }; + this.refreshDock(); + if (L.canAfford(human, card)) { + const { pay, gold } = L.purchaseCost(human, card); + const Lr = this.ledgerOf(HUMAN); + for (const c of [...GEMS, GOLD]) { + const n = c === GOLD ? gold : pay[c]; + if (!n) continue; + const pos = ledgerChipPos(Lr, c); + this.hoverObjs.push(this.add.text(pos.x, pos.y - 32, `−${n}`, { + fontFamily: SERIF, fontSize: '17px', fontStyle: 'bold', color: '#ff9a8a', stroke: '#140a04', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.hint + 4)); + } + } + } + this.previewTimer = this.time.delayedCall(420, () => { + this.previewTimer = null; + this.hidePortraits(); + this.previewObjs = showPreview(this, card, rect, D.preview); + }); + } + + clearHover() { + this.previewTimer?.remove(); + this.previewTimer = null; + if (this.previewObjs.length) { + this.previewObjs.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); + this.previewObjs = []; + this.showPortraits(); + } + this.hoverObjs.forEach((o) => { try { o.destroy(); } catch (_) { /* gone */ } }); + this.hoverObjs = []; + if (this.dockHover) { this.dockHover = null; this.refreshDock(); } + } + + // ── human input ─────────────────────────────────────────────────────────────────────── + pickable(color) { + const gs = this.gs; + const t = this.tray; + const left = gs.bank[color] - t.filter((c) => c === color).length; + if (left <= 0) return { ok: false, reason: `The case holds no more ${GEM_NAME[color]}.` }; + if (t.length === 0) return { ok: true }; + if (t.length >= 3) return { ok: false, reason: 'Your tray is full — take these or clear it.' }; + if (t.length === 2 && t[0] === t[1]) return { ok: false, reason: `You're already taking two ${GEM_NAME[t[0]]}s.` }; + if (t.length === 1 && t[0] === color) { + return gs.bank[color] >= TAKE_SAME_MIN ? { ok: true } + : { ok: false, reason: `Two of a kind needs ${TAKE_SAME_MIN} in the case (there ${gs.bank[color] === 1 ? 'is' : 'are'} ${gs.bank[color]}).` }; + } + if (t.includes(color)) return { ok: false, reason: 'Three different colours — one of each.' }; + return { ok: true }; + } + + pickGem(color) { + if (!this.canAct() || !this.pickable(color).ok) return; + this.selected = null; + const i = this.tray.length; + this.tray.push(color); + Snd.pick(this, i); + const from = bankChipPos(color), to = TRAY_SLOT(i); + const chip = this.add.image(from.x, from.y, chipKey(color)).setDisplaySize(62, 62).setDepth(D.flight); + this.trayPending.add(i); + this.tweens.add({ + targets: chip, x: to.x, y: to.y, displayWidth: 44, displayHeight: 44, duration: 260, ease: 'Cubic.Out', + onComplete: () => { + chip.destroy(); + Snd.chips(this, { n: 1, vol: 0.05 }); + this.trayPending.delete(i); + if (!this.ended && this.tray.length > i) this.refreshDock(); + }, + }); + this.refresh(); + } + + trayAction() { + const t = this.tray; + if (!t.length) return null; + const action = t.length === 2 && t[0] === t[1] ? { type: 'take2', color: t[0] } : { type: 'take3', colors: [...t] }; + return L.isLegal(this.gs, action) ? action : null; + } + + trayHint() { + const t = this.tray; + if (t.length === 1) return this.gs.bank[t[0]] >= TAKE_SAME_MIN ? 'Add a second of it, or two other colours.' : 'Add two other colours.'; + if (t.length === 2) return 'Add a third colour.'; + return ''; } confirmTake() { - const sel = this.selection; - if (sel.length === 0) return; - const action = (sel.length === 2 && sel[0] === sel[1]) - ? { type: 'take2', color: sel[0] } - : { type: 'take3', colors: [...new Set(sel)] }; - const ok = legalActions(this.gs).some((a) => this.sameAction(a, action)); - if (!ok) { this.selection = []; this.render(); return; } + const a = this.trayAction(); + if (a) this.humanAct(a); + } - // Capture gem sources before clearing selection - const sources = sel.map((color, i) => ({ - color, x: MARKET_X + 160 + i * 44, y: CONTROL_Y + 26, - })); - - this.selectedCard = null; - this.selection = []; - - // Save token state before and after applying the action - const preTokens = { ...this.gs.players[this.humanSeat].tokens }; - this._applyAction(action); - this.playActionSound(action); - const postTokens = this.gs.players[this.humanSeat].tokens; - - // Skip animation for edge cases (discard required, game over, or no gem art) - if (!this.hasGems || this.gs.phase === 'discard' || isGameOver(this.gs)) { - this.render(); - this.advance(); + onCardClick(card, source, rect) { + if (!this.canAct()) return; + const now = this.time.now; + const human = this.gs.players[HUMAN]; + if (this.lastClick?.id === card.id && now - this.lastClick.t < 320 && L.canAfford(human, card)) { + this.lastClick = null; + this.humanAct({ type: 'buy', cardId: card.id, source }); return; } + this.lastClick = { id: card.id, t: now }; + this.tray = []; + this.selected = this.selected?.card.id === card.id ? null : { card, source, rect: { x: rect.x, y: rect.y, w: rect.w ?? CW, h: rect.h ?? CH } }; + Snd.chips(this, { n: 1, vol: 0.03 }); + this.refresh(); + } - // Render with pre-take token counts so the panel doesn't jump yet - this.busy = true; - this.gs.players[this.humanSeat].tokens = preTokens; - this.render(); - this.gs.players[this.humanSeat].tokens = postTokens; - - // Animate each gem from its Take-bar slot to the player panel - let pending = sources.length; - sources.forEach(({ color, x: sx, y: sy }, i) => { - const dest = this.humanGemPos(color); - const gem = this.add.image(sx, sy, 'splendor-gems', gemFrame(color)) - .setDisplaySize(32, 32).setDepth(DEPTH.popup); - this.tweens.add({ - targets: gem, - x: dest.x, y: dest.y, - displayWidth: 26, displayHeight: 26, - duration: 380, - delay: i * 90, - ease: 'Cubic.easeOut', - onStart: () => { - try { - const a = new Audio(`assets/fx/gem-0${(i % 2) + 1}.mp3`); - a.volume = 0.7; a.play(); - } catch { /* */ } - }, - onComplete: () => { - gem.destroy(); - if (--pending === 0) { - this.busy = false; - this.render(); - this.advance(); - } - }, - }); + confirmBlindReserve(tier) { + if (!this.canAct()) return; + this.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Reserve Sight Unseen?', + text: `Take the top card of ${TIER_NAME[tier]} into your reserve without seeing it first${this.gs.bank.gold > 0 ? ', and one gold from the case' : ''}. Your rivals won't see it either.`, + yes: 'Reserve it', depth: D.modal, + onYes: () => { this.modal = null; this.showPortraits(); this.humanAct({ type: 'reserveDeck', tier }); }, + onNo: () => { this.modal = null; this.showPortraits(); }, }); } - sameAction(a, b) { - if (a.type !== b.type) return false; - if (a.type === 'take2') return a.color === b.color; - if (a.type === 'take3') { - const as = [...a.colors].sort().join(), bs = [...b.colors].sort().join(); - return as === bs; - } - return false; - } - - onCardClick(card, source) { - if (!this.isHumanTurn()) return; - this.selection = []; - this.selectedCard = { card, source }; - this.render(); - } - - onDeckClick(tier) { - if (!this.isHumanTurn()) return; - if (this.gs.players[this.humanSeat].reserved.length >= MAX_RESERVED) return; - this.applyHuman({ type: 'reserveDeck', tier }); - } - - onDiscardClick(color) { - if (this.gs.phase !== 'discard' || this.gs.current !== this.humanSeat) return; - this.gs = applyDiscard(this.gs, { [color]: 1 }); - if (this.gs.phase === 'turn' || isGameOver(this.gs)) { - // discard completed → the turn finalized - this.render(); - this.advance(); - } else { - this.render(); - } - } - - applyHuman(action) { - this.selectedCard = null; - this.selection = []; - - if (this.hasArt && action.type === 'buy') { - const seat = this.humanSeat; - const card = this.findCard(action.cardId); - const boardPos = this.findCardBoardPos(action.cardId); - let srcX, srcY; - if (boardPos) { - srcX = boardPos.x; srcY = boardPos.y; - } else { - const n = this.gs.players.length, gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const panelY = 76 + seat * (h + gap); - const ri = Math.max(0, this.gs.players[seat].reserved.findIndex((c) => c?.id === action.cardId)); - srcX = PANEL_X + 150 + ri * 116 + 52; srcY = panelY + h - 40 + 15; - } - - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard' && this.gs.current === seat) { this.render(); return; } - - if (!this.boughtCards[seat]) this.boughtCards[seat] = []; - this.boughtCards[seat].push(card); - this.animatingBuy = { seat, cardId: card.id }; - this.busy = true; - this.render(); - - this.animBuy(seat, card, srcX, srcY, () => { - this.animatingBuy = null; - this.busy = false; - this.render(); - this.advance(); - }); - return; - } - - if (this.hasArt && (action.type === 'reserve' || action.type === 'reserveDeck')) { - const srcPos = action.type === 'reserve' - ? this.findCardBoardPos(action.cardId) - : { x: MARKET_X + DECK_W / 2, y: TIER_Y[action.tier] + CH / 2 }; - const srcX = srcPos?.x ?? GAME_WIDTH / 2; - const srcY = srcPos?.y ?? GAME_HEIGHT / 2; - - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard' && this.gs.current === this.humanSeat) { - this.render(); - return; - } - - const reserved = this.gs.players[this.humanSeat].reserved; - const card = reserved[reserved.length - 1]; - this.animatingReserve = { seat: this.humanSeat, cardId: card.id }; - this.busy = true; - this.render(); - - this.animReserve(this.humanSeat, card, srcX, srcY, () => { - this.animatingReserve = null; - this.busy = false; - this.render(); - this.advance(); - }); - return; - } - - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard' && this.gs.current === this.humanSeat) { - this.render(); - return; - } - this.render(); + async humanAct(action) { + if (!this.canAct() || !L.isLegal(this.gs, action)) return; + this.selected = null; + this.tray = []; + this.clearHover(); + this.busy = true; + const snap = { gs: this.gs, finalAnnounced: this.finalAnnounced }; + await this.perform(HUMAN, action); + if (this.ended) return; + this.undoSnap = this.settings.undo && !L.isGameOver(this.gs) ? snap : null; this.advance(); } - // ── turn loop ─────────────────────────────────────────────────────────────── + undo() { + if (!this.undoSnap || !this.aiTimer || !this.settings.undo || this.modal) return; + this.aiTimer.remove(); + this.aiTimer = null; + const snap = this.undoSnap; + this.undoSnap = null; + this.gs = snap.gs; + this.finalAnnounced = snap.finalAnnounced; + this.rebuildMarket(); + this.busy = false; + Snd.swish(this); + floatText(this, DOCK.x + DOCK.w / 2, DOCK.y - 10, 'Move taken back', { size: 20 }); + this.refresh(); + } + + // ── turn flow ───────────────────────────────────────────────────────────────────────── advance() { - if (this._pendingNoble) { - const { seat, noble, srcX, srcY } = this._pendingNoble; - this._pendingNoble = null; - this.animatingNoble = { seat, nobleId: noble.id }; - this.busy = true; - this.render(); - this.animNoble(seat, noble, srcX, srcY, () => { - this.animatingNoble = null; - this.busy = false; - this.render(); - this.advance(); - }); - return; - } - if (isGameOver(this.gs)) { this.render(); this.onGameOver(); return; } - if (this.gs.phase === 'discard') { - // Only the human ever parks here interactively; AI auto-discards inline. - this.busy = false; - this.render(); - return; - } - if (this.gs.current === this.humanSeat) { - this.busy = false; - this.render(); - return; - } - this.aiTurn(); - } - - aiTurn() { - this.busy = true; - this.render(); + if (this.ended) return; + if (L.isGameOver(this.gs)) { this.finish(); return; } const seat = this.gs.current; - const skill = this.skillBySeat[seat]; - this.showTurnBanner(`${this.pname(seat)}'s turn`); - this.time.delayedCall(nextThinkDelay(skill), () => { - const action = chooseAction(this.gs, skill); - - if (this.hasGems && (action.type === 'take2' || action.type === 'take3')) { - this.animAITake(seat, action); - return; - } - - if (this.hasArt && (action.type === 'reserve' || action.type === 'reserveDeck')) { - const srcPos = action.type === 'reserve' - ? this.findCardBoardPos(action.cardId) - : { x: MARKET_X + DECK_W / 2, y: TIER_Y[action.tier] + CH / 2 }; - const srcX = srcPos?.x ?? GAME_WIDTH / 2; - const srcY = srcPos?.y ?? GAME_HEIGHT / 2; - - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard') { - this.gs = applyDiscard(this.gs, defaultDiscards(this.gs)); - } - - const reserved = this.gs.players[seat].reserved; - const card = reserved[reserved.length - 1]; - this.animatingReserve = { seat, cardId: card.id }; - this.render(); - - this.animReserve(seat, card, srcX, srcY, () => { - this.animatingReserve = null; - this.busy = false; - this.render(); - this.advance(); - }); - return; - } - - if (this.hasArt && action.type === 'buy') { - const card = this.findCard(action.cardId); - const boardPos = this.findCardBoardPos(action.cardId); - let srcX, srcY; - if (boardPos) { - srcX = boardPos.x; srcY = boardPos.y; - } else { - const n = this.gs.players.length, gap = 16; - const h = Math.min(220, Math.floor((GAME_HEIGHT - 90 - gap * (n - 1)) / n)); - const panelY = 76 + seat * (h + gap); - const ri = Math.max(0, this.gs.players[seat].reserved.findIndex((c) => c?.id === action.cardId)); - srcX = PANEL_X + 150 + ri * 116 + 52; srcY = panelY + h - 40 + 15; - } - - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard') { - this.gs = applyDiscard(this.gs, defaultDiscards(this.gs)); - } - - if (card.points > 0) this.portraits[seat]?.playEmotion('happy'); - if (!this.boughtCards[seat]) this.boughtCards[seat] = []; - this.boughtCards[seat].push(card); - this.animatingBuy = { seat, cardId: card.id }; - this.render(); - - this.animBuy(seat, card, srcX, srcY, () => { - this.animatingBuy = null; - this.busy = false; - this.render(); - this.advance(); - }); - return; - } - - if (action.type === 'buy') { - const card = this.findCard(action.cardId); - if (card?.points > 0) this.portraits[seat]?.playEmotion('happy'); - } - this._applyAction(action); - this.playActionSound(action); - if (this.gs.phase === 'discard') { - this.gs = applyDiscard(this.gs, defaultDiscards(this.gs)); - } + if (seat === HUMAN) { this.busy = false; - this.render(); - this.advance(); - }); - } - - playActionSound(action) { - if (!action) return; - if (action.type === 'buy') playSound(this, SFX.PURCHASE); - else if (action.type === 'reserve' || action.type === 'reserveDeck') playSound(this, SFX.CARD_DEAL); - // gem sounds played per-gem in animAITake / confirmTake - } - - showTurnBanner(text) { - const cx = GAME_WIDTH / 2; - const banner = this.add.text(cx, 130, text, { - fontFamily: 'Righteous', fontSize: '30px', color: COLORS.textHex, - backgroundColor: '#111923ee', padding: { x: 24, y: 10 }, - }).setOrigin(0.5).setDepth(DEPTH.banner); - this.tweens.add({ - targets: banner, y: 160, duration: 280, ease: 'Back.easeOut', - onComplete: () => this.time.delayedCall(800, () => - this.tweens.add({ targets: banner, alpha: 0, y: 130, duration: 220, onComplete: () => banner.destroy() })), - }); - } - - // ── game over ─────────────────────────────────────────────────────────────── - onGameOver() { + this.undoSnap = null; + if (!L.legalActions(this.gs).length) { + this.busy = true; + floatText(this, DOCK.x + DOCK.w / 2, DOCK.y - 10, 'No move possible — you pass', { size: 20 }); + this.time.delayedCall(900, async () => { await this.perform(HUMAN, { type: 'pass' }); this.advance(); }); + return; + } + this.refresh(); + return; + } this.busy = true; - const ranking = finalRanking(this.gs); - const humanRank = ranking.findIndex((r) => r.seat === this.humanSeat); - const won = humanRank === 0; - const humanPoints = this.gs.players[this.humanSeat].points; - const oppScores = ranking.filter((r) => r.seat !== this.humanSeat).map((r) => r.points); - this.recordResult(won ? 'win' : 'loss', humanPoints, oppScores); - - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - const w = 640, h = 120 + ranking.length * 46; - this.add.rectangle(cx, cy, w, h, 0x0a0e14, 0.94).setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.banner); - this.add.text(cx, cy - h / 2 + 30, won ? '🎉 You win!' : 'Game over', { - fontFamily: 'Righteous', fontSize: '34px', color: won ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); - ranking.forEach((r, i) => { - this.add.text(cx, cy - h / 2 + 80 + i * 40, - `${i + 1}. ${this.pname(r.seat)}${r.seat === this.humanSeat ? ' (you)' : ''} — ${r.points} pts (${r.cards} cards)`, { - fontFamily: '"Julius Sans One"', fontSize: '22px', - color: i === 0 ? COLORS.goldHex : COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); + const think = AI.nextThinkDelay(this.skills[seat]) * this.k; + const delay = this.undoSnap && this.settings.undo ? Math.max(think, 1500 * this.k) : think; + this.aiTimer = this.time.delayedCall(delay, async () => { + this.aiTimer = null; + this.undoSnap = null; + // Rivals wait politely while the menu is open. + while (this.modal && !this.ended) await this.wait(200); + if (this.ended) return; + this.refresh(); + const action = AI.chooseAction(this.gs, this.skills[seat]); + await this.perform(seat, action); + if (!this.ended) this.advance(); + }); + this.refresh(); + } + + async perform(seat, action) { + this.actingSeat = seat; + try { await this.performInner(seat, action); } finally { this.actingSeat = null; } + if (!this.ended) this.refresh(); + } + + async performInner(seat, action) { + const prev = this.gs; + let next = L.applyAction(prev, action); + if (next === prev) next = L.applyAction(prev, { type: 'pass' }); + const la = next.lastAction; + switch (la.type) { + case 'take3': case 'take2': await this.animTake(prev, next, seat, la.colors); break; + case 'reserve': case 'reserveDeck': await this.animReserve(prev, next, seat, la); break; + case 'buy': await this.animBuy(prev, next, seat, la); break; + default: { + this.gs = next; + const pp = portraitPos(this.ledgerOf(seat)); + floatText(this, pp.x, pp.y - 30, 'passes', { color: '#d8c08a' }); + this.refresh(); + } + } + if (this.ended) return; + await this.resolveParked(seat); + if (this.ended) return; + if (this.gs.lastVisit && this.gs.turn > prev.turn) await this.animNoble(this.gs.lastVisit.seat, this.gs.lastVisit.nobleId); + if (this.ended) return; + if (this.gs.triggeredEnd && !this.finalAnnounced) { + this.finalAnnounced = true; + await this.announceFinal(); + } + } + + async resolveParked(seat) { + for (let guard = 0; guard < 6 && !this.ended; guard++) { + if (this.gs.phase === 'discard') { + const map = seat === HUMAN ? await this.askReturn() : AI.chooseDiscards(this.gs); + const before = this.gs; + this.gs = L.applyDiscard(before, map); + await this.animReturn(before, seat, map); + } else if (this.gs.phase === 'noble') { + const id = seat === HUMAN ? await this.askNoble() : AI.chooseNoble(this.gs); + this.gs = L.applyNobleChoice(this.gs, id); + } else break; + } + } + + askReturn() { + return new Promise((res) => { + this.hidePortraits(); + this.refresh(this.gs); + const p = this.gs.players[HUMAN]; + this.modal = openReturn(this, { + player: p, suggested: AI.chooseDiscards(this.gs), depth: D.modal, + onDone: (map) => { this.modal = null; this.showPortraits(); res(map); }, + }); + }); + } + + askNoble() { + return new Promise((res) => { + this.hidePortraits(); + const nobles = this.gs.pendingNobles.map((id) => this.gs.nobles.find((n) => n.id === id)); + this.modal = openNobleChoice(this, { + nobles, depth: D.modal, + onPick: (id) => { this.modal = null; this.showPortraits(); res(id); }, + }); + }); + } + + // ── animations ──────────────────────────────────────────────────────────────────────── + flyChip(color, from, to, { delay = 0, dur = 380, from: s0 = 62, to: s1 = 32, i = 0, sound = 'pick' } = {}) { + return new Promise((res) => { + const chip = this.add.image(from.x, from.y, chipKey(color)).setDisplaySize(s0, s0).setDepth(D.flight).setAlpha(0); + const midY = Math.min(from.y, to.y) - 40; + const st = { t: 0 }; + this.tweens.add({ + targets: st, t: 1, delay, duration: dur * Math.min(1.2, this.k), ease: 'Sine.InOut', + onStart: () => { chip.setAlpha(1); if (sound === 'pick') Snd.pick(this, i); }, + onUpdate: () => { + const t = st.t, u = 1 - t; + chip.x = u * u * from.x + 2 * u * t * ((from.x + to.x) / 2) + t * t * to.x; + chip.y = u * u * from.y + 2 * u * t * midY + t * t * to.y; + const s = s0 + (s1 - s0) * t; + chip.setDisplaySize(s, s); + }, + onComplete: () => { chip.destroy(); Snd.chips(this, { n: 1, vol: 0.06 }); res(); }, + }); + }); + } + + async animTake(prev, next, seat, colors) { + const Lr = this.ledgerOf(seat); + const fromTray = seat === HUMAN; + this.gs = next; + this.refresh(withTokens(next, seat, prev.players[seat].tokens)); + await Promise.all(colors.map((c, i) => this.flyChip(c, fromTray ? TRAY_SLOT(i) : bankChipPos(c), ledgerChipPos(Lr, c), { + delay: i * 90, from: fromTray ? 44 : 62, i, + }))); + if (this.ended) return; + this.refresh(); + } + + async animReturn(before, seat, map) { + const Lr = this.ledgerOf(seat); + this.refresh(withTokens(this.gs, seat, before.players[seat].tokens, before.bank)); + const jobs = []; + let i = 0; + for (const [c, n] of Object.entries(map)) { + for (let k = 0; k < n; k++) jobs.push(this.flyChip(c, ledgerChipPos(Lr, c), bankChipPos(c), { delay: i++ * 80, from: 32, to: 62, sound: 'none' })); + } + if (jobs.length) Snd.chips(this, { n: Math.min(4, jobs.length) }); + await Promise.all(jobs); + if (this.ended) return; + this.refresh(); + } + + async flyPayment(seat, la) { + const Lr = this.ledgerOf(seat); + const jobs = []; + let i = 0; + for (const c of GEMS) { + for (let k = 0; k < (la.pay[c] ?? 0); k++) jobs.push(this.flyChip(c, ledgerChipPos(Lr, c), bankChipPos(c), { delay: i++ * 70, from: 32, to: 62, sound: 'none' })); + } + for (let k = 0; k < la.gold; k++) jobs.push(this.flyChip(GOLD, ledgerChipPos(Lr, GOLD), bankChipPos(GOLD), { delay: i++ * 70 + 120, from: 32, to: 62, sound: 'none' })); + if (jobs.length) Snd.coins(this); + await Promise.all(jobs); + } + + showcaseMode(seat) { + if (seat === HUMAN) return 'full'; + return { relaxed: 'full', normal: 'short', fast: 'skip' }[this.settings.pace] ?? 'short'; + } + + // Lift a card sprite into the lamp light with a caption, then leave it there + // for the caller to fly home. + async showcase(sp, card, seat, verb, { hidden = false } = {}) { + const mode = this.showcaseMode(seat); + if (mode === 'skip' || this.ended) return; + const T = mode === 'full' ? { in: 420, hold: 1200, out: 300 } : { in: 320, hold: 650, out: 260 }; + const cx = SW / 2 - 120, cy = SH / 2 - 30; + this.showcasing = true; + this.hidePortraits(); + const objs = []; + const overlay = this.add.rectangle(SW / 2, SH / 2, SW, SH, 0x000000).setAlpha(0).setDepth(D.overlay); + const spot = this.add.image(cx, cy, 'spl-spot').setDisplaySize(900, 900).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0).setDepth(D.overlay + 1); + objs.push(overlay, spot); + this.tweens.add({ targets: overlay, alpha: 0.6, duration: 260 }); + this.tweens.add({ targets: spot, alpha: 1, duration: 360 }); + sp.c.setDepth(D.showcase); + const scale = 270 / CW; + await this.tw({ targets: sp.c, x: cx, y: cy, scaleX: scale, scaleY: scale, duration: T.in, ease: 'Cubic.Out' }); + if (this.ended) return; + if (!sp.faceUp && !hidden) await this.flip(sp, true, 260); + if (!hidden) { + burst(this, cx, cy, gemTints(card.bonus), { depth: D.showcase + 2, count: 34 }); + Snd.chime(this, { n: 1 + card.points }); + } else Snd.swish(this); + const lines = [ + `${this.names[seat]} ${verb}`, + hidden ? `a ${TIER_NOUN[card.tier]}, sight unseen` : locationOf(card), + hidden ? 'The card stays face-down to rivals.' : `${card.points ? `+${card.points} prestige · ` : ''}+1 ${GEM_NAME[card.bonus]} bonus${verb.startsWith('reserve') ? ' (when bought)' : ''}`, + ]; + const capY = cy + (CH * scale) / 2 + 18; + const pg = this.add.graphics().setDepth(D.showcase + 1); + pg.fillStyle(0x1a0e06, 0.92).fillRoundedRect(cx - 230, capY - 6, 460, 92, 12); + pg.lineStyle(2, 0xd9b45a, 1).strokeRoundedRect(cx - 230, capY - 6, 460, 92, 12); + objs.push(pg); + objs.push(this.add.text(cx, capY + 12, lines[0], { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#d8c08a' }).setOrigin(0.5).setDepth(D.showcase + 2)); + objs.push(this.add.text(cx, capY + 38, lines[1], { fontFamily: DISPLAY, fontSize: '24px', color: '#f4dc9a' }).setOrigin(0.5).setDepth(D.showcase + 2)); + objs.push(this.add.text(cx, capY + 66, lines[2], { fontFamily: SERIF, fontSize: '14px', color: '#e8d8b0' }).setOrigin(0.5).setDepth(D.showcase + 2)); + if (card.points > 0 && seat !== HUMAN && !hidden && verb === 'acquires') this.portraits[seat]?.playEmotion?.('happy'); + await this.wait(T.hold * (mode === 'full' ? 1 : this.k)); + objs.forEach((o) => this.tweens.add({ targets: o, alpha: 0, duration: T.out, onComplete: () => o.destroy() })); + this.time.delayedCall(T.out, () => { this.showcasing = false; this.showPortraits(); }); + } + + async flyCard(sp, dest, scale, dur = 380) { + sp.c.setDepth(D.flight); + await this.tw({ targets: sp.c, x: dest.x, y: dest.y, scaleX: scale, scaleY: scale, duration: dur * Math.min(1.2, this.k), ease: 'Cubic.InOut' }); + } + + detachSprite(cardId) { + const sp = this.cardSprites.get(cardId); + if (!sp) return null; + this.cardSprites.delete(cardId); + sp.detached = true; + this.tweens.killTweensOf(sp.c); + sp.c.setScale(1); + sp.img.clearTint(); + return sp; + } + + async animBuy(prev, next, seat, la) { + const p = next.players[seat]; + const card = p.cards[p.cards.length - 1]; + const Lr = this.ledgerOf(seat); + let sp; + if (la.source === 'board') sp = this.detachSprite(card.id) ?? this.spriteAtSlot(card, la.tier, la.slot); + else { + const idx = prev.players[seat].reserved.findIndex((c) => c.id === card.id); + const rs = reserveSlot(Lr, Math.max(0, idx)); + sp = this.makeSprite(card, rs.x, rs.y); + sp.c.setScale(RES.w / CW); + sp.detached = true; + } + this.gs = next; + const hide = new Set([card.id]); + this.refresh(withTokens(next, seat, prev.players[seat].tokens, prev.bank), { hideCards: hide }); + const payment = this.flyPayment(seat, la).then(() => { if (!this.ended) this.refresh(next, { hideCards: hide }); }); + await this.showcase(sp, card, seat, 'acquires'); + await payment; + if (this.ended) return; + const n = p.cards.filter((c) => c.bonus === card.bonus).length; + const dest = ledgerStackPos(Lr, card.bonus, n - 1, n); + await this.flyCard(sp, dest, MINI.w / CW); + Snd.thud(this); + sp.c.destroy(); + if (this.ended) return; + this.refresh(next); + if (card.points) floatText(this, dest.x, dest.y - 40, `+${card.points}`, { color: '#ffe9a8', size: 26 }); + await this.syncMarket(next, { animate: true }); + } + + async animReserve(prev, next, seat, la) { + const p = next.players[seat]; + const card = p.reserved[p.reserved.length - 1]; + const Lr = this.ledgerOf(seat); + const hidden = la.type === 'reserveDeck' && seat !== HUMAN; + let sp; + if (la.type === 'reserve') sp = this.detachSprite(card.id) ?? this.spriteAtSlot(card, la.tier, la.slot); + else { + const dr = deckRect(la.tier); + sp = this.makeSprite(card, dr.x + CW / 2, dr.y + CH / 2, { faceUp: false }); + sp.detached = true; + Snd.swish(this); + } + this.gs = next; + const hide = new Set([card.id]); + const view = withTokens(next, seat, prev.players[seat].tokens, prev.bank); + this.refresh(view, { hideCards: hide }); + await this.showcase(sp, card, seat, la.type === 'reserveDeck' ? 'reserves sight unseen' : 'reserves', { hidden }); + if (this.ended) return; + const idx = p.reserved.length - 1; + const rs = reserveSlot(Lr, idx); + if (la.type === 'reserveDeck' && !hidden && !sp.faceUp) await this.flip(sp, true, 220); + await this.flyCard(sp, rs, RES.w / CW); + Snd.thud(this); + sp.c.destroy(); + if (this.ended) return; + this.refresh(view); + if (la.gold) await this.flyChip(GOLD, bankChipPos(GOLD), ledgerChipPos(Lr, GOLD), { i: 1 }); + if (this.ended) return; + this.refresh(next); + await this.syncMarket(next, { animate: true }); + } + + spriteAtSlot(card, tier, slot) { + const r = slotRect(tier, slot ?? 0); + const sp = this.makeSprite(card, r.x + CW / 2, r.y + CH / 2); + sp.detached = true; + return sp; + } + + async animNoble(seat, nobleId) { + const noble = NOBLES.find((n) => n.id === nobleId); + const slot = this.nobleSlots.findIndex((n) => n.id === nobleId); + const r = nobleSlotRect(Math.max(0, slot)); + const hide = new Set([nobleId]); + this.refresh(this.gs, { hideNobles: hide }); + const mode = this.showcaseMode(seat); + const img = this.add.image(r.x + r.w / 2, r.y + r.h / 2, nobleKey(noble)).setDisplaySize(r.w, r.h).setDepth(D.showcase); + const info = nobleInfo(noble); + const Lr = this.ledgerOf(seat); + const ci = this.gs.players[seat].nobles.findIndex((n) => n.id === nobleId); + const dest = cameoPos(Lr, Math.max(0, ci), this.gs.players[seat].nobles.length); + if (mode !== 'skip') { + this.showcasing = true; + this.hidePortraits(); + const cx = SW / 2 - 120, cy = SH / 2 - 60; + const overlay = this.add.rectangle(SW / 2, SH / 2, SW, SH, 0x000000).setAlpha(0).setDepth(D.overlay); + const spot = this.add.image(cx, cy, 'spl-spot').setDisplaySize(900, 900).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0).setDepth(D.overlay + 1); + this.tweens.add({ targets: overlay, alpha: 0.62, duration: 280 }); + this.tweens.add({ targets: spot, alpha: 1, duration: 380 }); + await this.tw({ targets: img, x: cx, y: cy, displayWidth: 268, displayHeight: 335, duration: 480, ease: 'Cubic.Out' }); + if (this.ended) return; + Snd.fanfare(this); + const seal = this.add.image(cx + 110, cy + 120, 'spl-seal').setDisplaySize(190, 190).setAlpha(0).setAngle(-14).setDepth(D.showcase + 2); + await this.wait(380); + this.tweens.add({ targets: seal, alpha: 1, displayWidth: 96, displayHeight: 96, duration: 220, ease: 'Back.Out' }); + await this.wait(200); + Snd.stamp(this); + burst(this, cx + 110, cy + 120, [0xff6a5a, 0xffd87a, 0xffffff], { depth: D.showcase + 3, count: 22, speed: [60, 180] }); + burst(this, cx, cy - 60, [0xffffff, 0xffd87a, 0xf0b030], { depth: D.showcase + 3, count: 36 }); + const pg = this.add.graphics().setDepth(D.showcase + 1); + const capY = cy + 190; + pg.fillStyle(0x1a0e06, 0.92).fillRoundedRect(cx - 250, capY, 500, 92, 12); + pg.lineStyle(2, 0xd9b45a, 1).strokeRoundedRect(cx - 250, capY, 500, 92, 12); + const t1 = this.add.text(cx, capY + 22, 'Royal Patronage', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#d8c08a' }).setOrigin(0.5).setDepth(D.showcase + 2); + const t2 = this.add.text(cx, capY + 48, `${info.name}, ${info.title}`, { fontFamily: DISPLAY, fontSize: '20px', color: '#f4dc9a' }).setOrigin(0.5).setDepth(D.showcase + 2); + const t3 = this.add.text(cx, capY + 74, `becomes ${seat === HUMAN ? 'your' : `${this.names[seat]}'s`} patron · +3 prestige`, { fontFamily: SERIF, fontSize: '14px', color: '#e8d8b0' }).setOrigin(0.5).setDepth(D.showcase + 2); + if (seat !== HUMAN) this.portraits[seat]?.playEmotion?.('happy'); + await this.wait((mode === 'full' ? 1500 : 800) * (mode === 'full' ? 1 : this.k)); + for (const o of [overlay, spot, pg, t1, t2, t3, seal]) this.tweens.add({ targets: o, alpha: 0, duration: 300, onComplete: () => o.destroy() }); + this.time.delayedCall(300, () => { this.showcasing = false; this.showPortraits(); }); + } else { + Snd.fanfare(this); + } + await this.tw({ targets: img, x: dest.x, y: dest.y + 6, displayWidth: dest.size, displayHeight: dest.size * 1.25, alpha: 0.4, duration: 420, ease: 'Cubic.In' }); + img.destroy(); + Snd.chime(this, { n: 3 }); + floatText(this, dest.x, dest.y - 24, '+3', { size: 24 }); + if (!this.ended) this.refresh(); + } + + async announceFinal() { + const seat = this.gs.endTriggeredBy; + Snd.chime(this, { n: 4 }); + const cx = 500, cy = 470; + const g = this.add.graphics().setDepth(D.banner); + g.fillStyle(0x1a0806, 0.92).fillRoundedRect(cx - 330, cy - 50, 660, 100, 14); + g.lineStyle(3, 0xd9b45a, 1).strokeRoundedRect(cx - 330, cy - 50, 660, 100, 14); + const t1 = this.add.text(cx, cy - 14, 'The Final Round', { fontFamily: DISPLAY, fontSize: '32px', color: '#ffd8a0' }).setOrigin(0.5).setDepth(D.banner + 1); + const t2 = this.add.text(cx, cy + 24, `${seat === HUMAN ? 'You have' : `${this.names[seat]} has`} reached 15 prestige — the round plays out, then the books close.`, { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#e8d8b0', + }).setOrigin(0.5).setDepth(D.banner + 1); + const all = [g, t1, t2]; + all.forEach((o) => o.setAlpha(0)); + await this.tw({ targets: all, alpha: 1, duration: 260 }); + await this.wait(1500 * Math.max(0.7, this.k)); + await this.tw({ targets: all, alpha: 0, duration: 300 }); + all.forEach((o) => o.destroy()); + } + + // ── end ───────────────────────────────────────────────────────────────────────────────── + finish() { + if (this.endScreen || this.ended) return; + this.busy = true; + this.refresh(); + const ranking = L.finalRanking(this.gs); + const human = ranking.find((r) => r.seat === HUMAN); + const won = human.place === 1; + this.recordResult(won ? 'win' : 'loss', this.gs.players[HUMAN].points, ranking.filter((r) => r.seat !== HUMAN).map((r) => r.points)); + this.time.delayedCall(700, () => { + if (this.ended) return; + this.hidePortraits(); + if (won) Snd.fanfare(this); else Snd.chime(this, { n: 2 }); + this.endScreen = showSplendorEndScreen(this, { + state: this.gs, names: this.names, humanSeat: HUMAN, depth: D.end, + onPlayAgain: () => this.scene.restart(this._initData), + onLeave: () => this.scene.start('GameMenu'), + }); }); - new Button(this, cx - 110, cy + h / 2 - 36, 'Play Again', () => this.scene.restart(this._initData), - { width: 190, fontSize: 22 }).setDepth(DEPTH.banner + 1); - new Button(this, cx + 110, cy + h / 2 - 36, 'Leave', () => this.scene.start('GameMenu'), - { width: 190, fontSize: 22, variant: 'ghost' }).setDepth(DEPTH.banner + 1); } async recordResult(result, score, opponentScores) { @@ -1522,4 +1101,36 @@ export default class SplendorGame extends Phaser.Scene { await api.post('/history/single-player', { slug: 'splendor', score, opponentScores, result }); } catch { /* best effort */ } } + + // ── menu ──────────────────────────────────────────────────────────────────────────────── + openMenu() { + if (this.modal || this.endScreen) return; + this.clearHover(); + this.hidePortraits(); + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => this.openRules(), + onNewGame: () => { + this.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Start a New Game?', text: 'This game will be abandoned.', yes: 'New Game', depth: D.modal, + onYes: () => this.scene.restart(this._initData), + onNo: () => { this.modal = null; this.showPortraits(); }, + }); + }, + onLeave: () => this.scene.start('GameMenu'), + onClose: () => { this.modal = null; this.showPortraits(); }, + }); + } + + openRules() { new TutorialModal(this.gameDef).open(); } + + changeSetting(key, value) { + this.settings[key] = value; + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + if (key === 'ambient') this.setAmbient(value); + if (key === 'undo' && !value) this.undoSnap = null; + if (!this.busy || this.aiTimer) this.refresh(); + } } diff --git a/src/games/splendor/SplendorHud.js b/src/games/splendor/SplendorHud.js new file mode 100644 index 0000000..7b05386 --- /dev/null +++ b/src/games/splendor/SplendorHud.js @@ -0,0 +1,407 @@ +// SplendorHud.js — the table's furniture that redraws from state. +// +// Each draw* function builds its objects for one refresh and returns them in +// an array (the scene destroys them on the next refresh). Market cards and the +// opponents' portraits are persistent and live in SplendorGame. +// +// drawGallery patrons in gilt frames, vacant hooks, everyone's progress +// drawTrack the Guild Register: a pawn per seat, final-round candle +// drawBank the jewel case: chip stacks, counts, pick zones +// drawLedger a merchant's ledger: seal, colour stacks, chips, gold, +// reserved cards (blind ones face-down to rivals), cameos +// drawDock the merchant's slate: prompt, gem tray, buttons +// showPreview a big card with its place name (hover) +// plus position helpers the flights use. + +import * as Phaser from 'phaser'; +import { GEMS, GOLD, GEM_NAME, TIER_NAME, HAND_LIMIT, MAX_RESERVED, locationOf, nobleInfo } from './SplendorData.js'; +import { tokenTotal, nobleProgress } from './SplendorLogic.js'; +import { + GALLERY, NOBLE, NOBLE_PROGRESS_Y, TRACK, TRACK_RULE, trackX, bankCell, bankChipPos, BANK_ORDER, BANK_CHIP, + ledgerParts, stackPos, MINI, RES, DOCK, SEAT_HEX, SEAT_CSS, W, H, +} from './SplendorLayout.js'; +import { + cardKey, ensureCardFace, backKey, nobleKey, chipKey, ledgerKey, SERIF, DISPLAY, CREAM, BRASS, INK, NOBLE_TW, NOBLE_TH, + FACE_W, FACE_H, TRAY_SLOT, +} from './SplendorArt.js'; +import { Button } from '../../ui/Button.js'; + +const txt = (scene, x, y, s, style) => scene.add.text(x, y, s, { fontFamily: SERIF, ...style }); + +// ── positions ──────────────────────────────────────────────────────────────────────── +export function nobleSlotRect(i) { + return { x: GALLERY.x + 14 + i * NOBLE.step, y: NOBLE.y, w: NOBLE.w, h: NOBLE.h + NOBLE.plateH }; +} +export function ledgerChipPos(L, color) { + const P = ledgerParts(L); + const c = color === GOLD ? P.gold.chip : P.cols[color].chip; + return { x: c.x, y: c.y }; +} +export function ledgerStackPos(L, color, index, n) { + return stackPos(ledgerParts(L).cols[color], index, n); +} +export function reserveSlot(L, i) { + const r = ledgerParts(L).reserve[i]; + return { x: r.x + r.w / 2, y: r.y + r.h / 2, w: r.w, h: r.h }; +} +export function cameoPos(L, i, n = 1) { + const c = ledgerParts(L).cameos; + const size = n > 4 ? 28 : c.size, gap = n > 4 ? 4 : c.gap; + return { x: c.x + i * (size + gap) + size / 2, y: c.y + c.size - size / 2, size }; +} +export function portraitPos(L) { return ledgerParts(L).portrait; } + +// A chip pile: n chips stepped upward (capped), bottom chip centred at (x, y). +export function chipPile(scene, color, x, y, n, size, depth, { cap = 7, step = 3.5, alpha = 1 } = {}) { + const objs = []; + const k = Math.min(n, cap); + for (let i = 0; i < k; i++) { + objs.push(scene.add.image(x, y - i * step, chipKey(color)).setDisplaySize(size, size).setDepth(depth).setAlpha(alpha)); + } + return objs; +} + +// Crop a noble texture to its portrait (no plate), top-left anchored. +export function cameo(scene, noble, cx, cy, size, depth) { + const img = scene.add.image(cx - size / 2, cy - size / 2, nobleKey(noble)).setOrigin(0, 0); + img.setCrop(0, 0, NOBLE_TW, NOBLE_TW); + img.setScale(size / NOBLE_TW).setDepth(depth); + return img; +} + +// ── gallery ────────────────────────────────────────────────────────────────────────── +export function drawGallery(scene, view, { slots, depth, tooltip, hideNobles = new Set(), names }) { + const objs = []; + const n = view.players.length; + slots.forEach((noble, i) => { + const r = nobleSlotRect(i); + const onTable = view.nobles.some((x) => x.id === noble.id) && !hideNobles.has(noble.id); + // Brass nail + cord. + const g = scene.add.graphics().setDepth(depth); + g.lineStyle(1.2, 0xb89a5a, 0.7); + g.lineBetween(r.x + r.w / 2, r.y - 8, r.x + 18, r.y + 2); + g.lineBetween(r.x + r.w / 2, r.y - 8, r.x + r.w - 18, r.y + 2); + g.fillStyle(0xd9b45a, 1).fillCircle(r.x + r.w / 2, r.y - 8, 3); + objs.push(g); + if (onTable) { + objs.push(scene.add.image(r.x + r.w / 2 + 3, r.y + r.h / 2 + 5, nobleKey(noble)).setDisplaySize(r.w, r.h).setTint(0x000000).setAlpha(0.45).setDepth(depth)); + const img = scene.add.image(r.x + r.w / 2, r.y + r.h / 2, nobleKey(noble)).setDisplaySize(r.w, r.h).setDepth(depth + 1); + objs.push(img); + const zone = scene.add.zone(r.x + r.w / 2, r.y + r.h / 2, r.w, r.h).setInteractive().setDepth(depth + 2); + objs.push(zone); + tooltip?.attachTo(zone, () => { + const info = nobleInfo(noble); + const req = Object.entries(noble.requires).map(([c, k]) => `${k} ${GEM_NAME[c]}`).join(' · '); + const lines = [info.title, `Visits the first merchant holding ${req} in card bonuses. +3 prestige`]; + view.players.forEach((p) => { + const pr = nobleProgress(p, noble); + lines.push(`${names[p.seat]}: ${pr.have}/${pr.need}${pr.have >= pr.need ? ' ✓' : ''}`); + }); + return { title: info.name, lines }; + }); + // Progress rows, one per seat. + const need = Object.values(noble.requires).reduce((a, b) => a + b, 0); + const pw = 4, gap = 1.6, total = need * (pw + gap) - gap; + const x0 = r.x + r.w / 2 - total / 2 + 6; + const pg = scene.add.graphics().setDepth(depth + 1); + view.players.forEach((p, s) => { + const yy = NOBLE_PROGRESS_Y + s * 6; + const have = nobleProgress(p, noble).have; + pg.fillStyle(SEAT_HEX[s], 1).fillCircle(x0 - 9, yy + 2, 2.6); + for (let k = 0; k < need; k++) { + pg.fillStyle(k < have ? SEAT_HEX[s] : 0x000000, k < have ? 1 : 0.45).fillRect(x0 + k * (pw + gap), yy, pw, 4); + } + }); + objs.push(pg); + } else { + // Vacant hook — the patron has left with someone. + const owner = view.players.find((p) => p.nobles.some((x) => x.id === noble.id)); + const vg = scene.add.graphics().setDepth(depth); + vg.lineStyle(1.5, 0xb89a5a, 0.25).strokeRoundedRect(r.x + 4, r.y + 4, r.w - 8, NOBLE.h - 8, 8); + vg.fillStyle(0x000000, 0.18).fillRoundedRect(r.x + 4, r.y + 4, r.w - 8, NOBLE.h - 8, 8); + objs.push(vg); + if (owner && !hideNobles.has(noble.id)) { + objs.push(txt(scene, r.x + r.w / 2, r.y + NOBLE.h / 2 - 8, 'patron of', { fontSize: '12px', fontStyle: 'italic', color: '#bfa57a' }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(txt(scene, r.x + r.w / 2, r.y + NOBLE.h / 2 + 10, names[owner.seat], { fontSize: '15px', fontStyle: 'bold', color: SEAT_CSS[owner.seat], wordWrap: { width: r.w - 12 }, align: 'center' }).setOrigin(0.5).setDepth(depth + 1)); + } + } + }); + void n; + return objs; +} + +// ── the Guild Register ───────────────────────────────────────────────────────────────── +export function drawTrack(scene, view, { depth, names }) { + const objs = []; + objs.push(txt(scene, TRACK.x + 26, TRACK.y + 30, `Round ${view.round}`, { fontSize: '13px', fontStyle: 'italic', color: '#d8c08a' }).setOrigin(0, 0.5).setDepth(depth)); + const groups = new Map(); + view.players.forEach((p) => { + const k = Math.min(15, p.points); + if (!groups.has(k)) groups.set(k, []); + groups.get(k).push(p); + }); + for (const [pts, ps] of groups) { + ps.forEach((p, i) => { + const x = trackX(pts) + (ps.length > 1 ? (i - (ps.length - 1) / 2) * 9 : 0); + const y = TRACK_RULE.y - 22 - i * 7; + objs.push(scene.add.image(x, y, 'spl-pawn').setDisplaySize(26, 26).setTint(SEAT_HEX[p.seat]).setDepth(depth + 1 + i)); + objs.push(txt(scene, x, y, (names[p.seat] ?? '?').slice(0, 1).toUpperCase(), { fontSize: '13px', fontStyle: 'bold', color: '#1a0e04' }).setOrigin(0.5).setDepth(depth + 1 + i)); + if (p.points > 15) objs.push(txt(scene, x + 14, y - 12, String(p.points), { fontSize: '12px', fontStyle: 'bold', color: '#ffe9a8' }).setOrigin(0.5).setDepth(depth + 2 + i)); + }); + } + if (view.triggeredEnd) { + const cx = TRACK.x + 30, cy = TRACK_RULE.y + 6; + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0xf1e6c8, 1).fillRect(cx - 5, cy - 20, 10, 26); + g.fillStyle(0x000000, 0.25).fillRect(cx + 2, cy - 20, 3, 26); + g.fillStyle(0xb89a5a, 1).fillEllipse(cx, cy + 8, 26, 8); + objs.push(g); + const flame = scene.add.image(cx, cy - 30, 'spl-flame').setDisplaySize(14, 24).setBlendMode(Phaser.BlendModes.ADD).setDepth(depth + 1); + const halo = scene.add.image(cx, cy - 28, 'spl-spot').setDisplaySize(90, 90).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.5).setDepth(depth); + scene.tweens.add({ targets: flame, scaleY: flame.scaleY * 0.86, scaleX: flame.scaleX * 1.08, duration: 160, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + scene.tweens.add({ targets: halo, alpha: 0.3, duration: 420, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + objs.push(flame, halo); + objs.push(txt(scene, TRACK.x + TRACK.w / 2, TRACK.y + 50, `FINAL ROUND — ${names[view.endTriggeredBy] ?? ''} reached 15`, { + fontSize: '13px', fontStyle: 'bold', color: '#ffb09a', + }).setOrigin(0.5).setDepth(depth)); + } + return objs; +} + +// ── the jewel case ───────────────────────────────────────────────────────────────────── +// opts.selection: colours currently on the tray. opts.pickable(color) → +// { ok, reason }. opts.onPick(color). +export function drawBank(scene, view, { depth, selection = [], interactive = false, pickable, onPick, tooltip, hover }) { + const objs = []; + for (const color of BANK_ORDER) { + const cell = bankCell(color); + const sel = selection.filter((c) => c === color).length; + const n = Math.max(0, view.bank[color] - sel); + const pos = bankChipPos(color); + objs.push(...chipPile(scene, color, pos.x, pos.y, n, BANK_CHIP, depth + 1, { cap: 7, step: 4 })); + objs.push(scene.add.text(cell.x + cell.w - 34, cell.y + cell.h / 2 - 8, String(n), { + fontFamily: DISPLAY, fontSize: '30px', color: n > 0 ? CREAM : '#6a5a48', stroke: '#1a0806', strokeThickness: 4, + }).setOrigin(0.5).setDepth(depth + 2)); + if (!interactive || color === GOLD) { + if (color === GOLD) { + const z = scene.add.zone(cell.x + cell.w / 2, cell.y + cell.h / 2, cell.w, cell.h).setInteractive().setDepth(depth + 3); + objs.push(z); + tooltip?.attachTo(z, () => ({ title: 'Gold', lines: ['Wild: pays for any gem.', 'You take one when you reserve a card.'] })); + } + continue; + } + const verdict = pickable(color); + const zone = scene.add.zone(cell.x + cell.w / 2, cell.y + cell.h / 2, cell.w, cell.h).setInteractive({ useHandCursor: verdict.ok }).setDepth(depth + 3); + objs.push(zone); + const ring = scene.add.graphics().setDepth(depth + 2).setAlpha(0); + ring.lineStyle(3, 0xffe2a0, 1).strokeRoundedRect(cell.x - 2, cell.y - 2, cell.w + 4, cell.h + 4, 12); + objs.push(ring); + if (!verdict.ok) { + const shade = scene.add.graphics().setDepth(depth + 2); + shade.fillStyle(0x000000, 0.45).fillRoundedRect(cell.x, cell.y, cell.w, cell.h, 10); + objs.push(shade); + tooltip?.attachTo(zone, () => ({ title: GEM_NAME[color], lines: [verdict.reason] })); + } else { + zone.on('pointerover', () => { ring.setAlpha(1); hover?.(color, true); }); + zone.on('pointerout', () => { ring.setAlpha(0); hover?.(color, false); }); + zone.on('pointerdown', () => onPick(color)); + } + } + return objs; +} + +// ── a merchant's ledger ──────────────────────────────────────────────────────────────── +// opts.viewer: the seat looking (blind reserves of other seats show backs). +// opts.hideCards / hideNobles: ids still in flight. opts.active: whose turn. +// opts.onReserved(card, rect) for the human's reserve slots; opts.preview(card, rect) +// / opts.unpreview() for hover; opts.extraFor(card) → extra objects (blazes). +export function drawLedger(scene, view, L, opts) { + const { depth, viewer = 0, hideCards = new Set(), hideNobles = new Set(), active = false, names, skills, tokenDelta = null } = opts; + const objs = []; + const p = view.players[L.seat]; + const P = ledgerParts(L); + objs.push(scene.add.image(L.x - 14, L.y - 14, ledgerKey(L)).setOrigin(0, 0).setDepth(depth)); + + if (active) { + const g = scene.add.graphics().setDepth(depth + 1); + g.lineStyle(4, SEAT_HEX[L.seat], 0.9).strokeRoundedRect(L.x - 2, L.y - 2, L.w + 4, L.h + 4, 15); + g.lineStyle(10, SEAT_HEX[L.seat], 0.18).strokeRoundedRect(L.x - 6, L.y - 6, L.w + 12, L.h + 12, 18); + scene.tweens.add({ targets: g, alpha: { from: 1, to: 0.55 }, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + objs.push(g); + } + + // Header: name, prestige seal, gem count. + const you = L.seat === viewer; + objs.push(scene.add.text(P.name.x, P.name.y, `${names[L.seat]}${you ? ' (you)' : ''}`, { + fontFamily: DISPLAY, fontSize: '19px', color: SEAT_CSS[L.seat], stroke: '#140a04', strokeThickness: 3, + }).setDepth(depth + 2)); + if (!you && skills?.[L.seat]) { + objs.push(txt(scene, P.name.x, P.name.y + 24, `merchant · skill ${skills[L.seat]}`, { fontSize: '11px', fontStyle: 'italic', color: '#a89070' }).setDepth(depth + 2)); + } + const s = P.seal; + const sg = scene.add.graphics().setDepth(depth + 2); + sg.fillStyle(0x000000, 0.45).fillCircle(s.x + 1, s.y + 3, s.r); + sg.fillStyle(0x8a6420, 1).fillCircle(s.x, s.y, s.r); + sg.fillStyle(0xd9b45a, 1).fillCircle(s.x, s.y, s.r - 3); + sg.fillStyle(0xf0d48a, 1).fillCircle(s.x - 4, s.y - 5, s.r - 12); + sg.fillStyle(0xd9b45a, 1).fillCircle(s.x, s.y, s.r - 9); + sg.lineStyle(1.2, 0x6e5018, 0.9).strokeCircle(s.x, s.y, s.r - 7); + objs.push(sg); + objs.push(scene.add.text(s.x, s.y - 3, String(p.points), { fontFamily: SERIF, fontSize: '28px', fontStyle: 'bold', color: INK }).setOrigin(0.5).setDepth(depth + 3)); + objs.push(txt(scene, s.x, s.y + 17, 'prestige', { fontSize: '9px', fontStyle: 'italic', color: '#4a3010' }).setOrigin(0.5).setDepth(depth + 3)); + const held = tokenTotal(p); + objs.push(txt(scene, s.x, s.y + s.r + 12, `${held}/${HAND_LIMIT} gems`, { + fontSize: '12px', fontStyle: 'bold', color: held >= HAND_LIMIT ? '#ffb09a' : '#d8c08a', + }).setOrigin(0.5).setDepth(depth + 2)); + objs.push(txt(scene, s.x, s.y + s.r + 27, `${p.cardsCount} card${p.cardsCount === 1 ? '' : 's'}`, { + fontSize: '11px', color: '#a89070', + }).setOrigin(0.5).setDepth(depth + 2)); + + // Patron cameos. + p.nobles.forEach((nb, i) => { + if (hideNobles.has(nb.id)) return; + const c = cameoPos(L, i, p.nobles.length); + const ring = scene.add.graphics().setDepth(depth + 2); + ring.fillStyle(0x000000, 0.5).fillRoundedRect(c.x - c.size / 2 + 1, c.y - c.size / 2 + 2, c.size, c.size, 5); + objs.push(ring); + objs.push(cameo(scene, nb, c.x, c.y, c.size, depth + 3)); + const fr = scene.add.graphics().setDepth(depth + 4); + fr.lineStyle(2, 0xd9b45a, 1).strokeRoundedRect(c.x - c.size / 2, c.y - c.size / 2, c.size, c.size, 5); + objs.push(fr); + const z = scene.add.zone(c.x, c.y, c.size, c.size).setInteractive().setDepth(depth + 5); + objs.push(z); + opts.tooltip?.attachTo(z, () => ({ title: nobleInfo(nb).name, lines: [nobleInfo(nb).title, '+3 prestige'] })); + }); + + // Colour stacks + chips. + for (const g of GEMS) { + const col = P.cols[g]; + const cards = p.cards.filter((c) => c.bonus === g && !hideCards.has(c.id)); + cards.forEach((c, i) => { + ensureCardFace(scene, c); + const pos = stackPos(col, i, cards.length); + const img = scene.add.image(pos.x, pos.y, cardKey(c)).setDisplaySize(MINI.w, MINI.h).setDepth(depth + 2); + objs.push(img); + const next = i < cards.length - 1 ? stackPos(col, i + 1, cards.length) : null; + const top = pos.y - MINI.h / 2; + const hh = next ? Math.max(6, next.y - pos.y) : MINI.h; + const z = scene.add.zone(pos.x, top + hh / 2, MINI.w, hh).setInteractive().setDepth(depth + 3); + z.on('pointerover', () => opts.preview?.(c, { x: pos.x - MINI.w / 2, y: top, w: MINI.w, h: MINI.h })); + z.on('pointerout', () => opts.unpreview?.()); + objs.push(z); + }); + if (cards.length) { + const bx = col.cx + MINI.w / 2 - 2, by = col.stackTop - 4; + const bg = scene.add.graphics().setDepth(depth + 4); + bg.fillStyle(0x140a04, 0.9).fillCircle(bx, by, 10); + bg.lineStyle(1.5, 0xd9b45a, 1).strokeCircle(bx, by, 10); + objs.push(bg); + objs.push(txt(scene, bx, by, String(cards.length), { fontSize: '12px', fontStyle: 'bold', color: CREAM }).setOrigin(0.5).setDepth(depth + 5)); + } + objs.push(...chipColumn(scene, p, g, col.chip, depth, tokenDelta)); + } + objs.push(...chipColumn(scene, p, GOLD, P.gold.chip, depth, tokenDelta)); + + // Reserved. + const shown = p.reserved; + objs.push(txt(scene, P.reserveLabel.x, P.reserveLabel.y + 13, `${shown.length}/${MAX_RESERVED}`, { fontSize: '10px', color: '#a89070' }).setOrigin(0.5).setDepth(depth + 2)); + shown.forEach((c, i) => { + if (hideCards.has(c.id)) return; + const r = P.reserve[i]; + const hidden = c.blind && L.seat !== viewer; + if (!hidden) ensureCardFace(scene, c); + objs.push(scene.add.image(r.x + r.w / 2 + 2, r.y + r.h / 2 + 4, 'spl-shadow').setDisplaySize(r.w * 1.18, r.h * 1.14).setAlpha(0.7).setDepth(depth + 1)); + const img = scene.add.image(r.x + r.w / 2, r.y + r.h / 2, hidden ? backKey(c.tier) : cardKey(c)).setDisplaySize(r.w, r.h).setDepth(depth + 2); + objs.push(img); + if (c.blind && !hidden) { + objs.push(txt(scene, r.x + r.w / 2, r.y + r.h + 9, 'blind', { fontSize: '10px', fontStyle: 'italic', color: '#a89070' }).setOrigin(0.5).setDepth(depth + 2)); + } + if (opts.extraFor) objs.push(...(opts.extraFor(c, r, img) ?? [])); + const z = scene.add.zone(r.x + r.w / 2, r.y + r.h / 2, r.w, r.h).setInteractive({ useHandCursor: !!opts.onReserved }).setDepth(depth + 6); + if (!hidden) { + z.on('pointerover', () => opts.preview?.(c, r)); + z.on('pointerout', () => opts.unpreview?.()); + } else { + opts.tooltip?.attachTo(z, () => ({ title: `A ${TIER_NAME[c.tier].replace('The ', '').replace(/s$/, '').toLowerCase()} card, face-down`, lines: ['Reserved sight unseen from the deck.'] })); + } + if (opts.onReserved) z.on('pointerdown', () => opts.onReserved(c, r)); + objs.push(z); + }); + return objs; +} + +function chipColumn(scene, p, color, pos, depth, tokenDelta) { + const objs = []; + const n = p.tokens[color] ?? 0; + if (n > 0) objs.push(...chipPile(scene, color, pos.x, pos.y, n, 32, depth + 2, { cap: 6, step: 3 })); + else objs.push(scene.add.image(pos.x, pos.y, chipKey(color)).setDisplaySize(32, 32).setAlpha(0.18).setDepth(depth + 2)); + objs.push(scene.add.text(pos.x + 22, pos.y, String(n), { + fontFamily: SERIF, fontSize: '17px', fontStyle: 'bold', color: n > 0 ? CREAM : '#6a5a48', stroke: '#140a04', strokeThickness: 3, + }).setOrigin(0, 0.5).setDepth(depth + 3)); + const d = tokenDelta?.[color]; + if (d) { + objs.push(scene.add.text(pos.x, pos.y - 30, `${d > 0 ? '+' : '−'}${Math.abs(d)}`, { + fontFamily: SERIF, fontSize: '16px', fontStyle: 'bold', color: d > 0 ? '#9ff0b4' : '#ff8a7a', stroke: '#140a04', strokeThickness: 4, + }).setOrigin(0.5).setDepth(depth + 6)); + } + return objs; +} + +// ── the merchant's slate ──────────────────────────────────────────────────────────────── +// spec: { title, body, warn, tray: [colours], onTray(i), buttons: [{label, fn, bg, w}] } +export function drawDock(scene, spec, depth) { + const objs = []; + const d = DOCK; + objs.push(scene.add.text(d.x + 22, d.y + 14, spec.title ?? '', { + fontFamily: DISPLAY, fontSize: '20px', color: '#3a1a06', + }).setDepth(depth)); + objs.push(txt(scene, d.x + 22, d.y + 44, spec.body ?? '', { + fontSize: '14px', color: INK, wordWrap: { width: 470 }, lineSpacing: 3, + }).setDepth(depth)); + if (spec.warn) { + objs.push(txt(scene, d.x + 22, d.y + d.h - 22, spec.warn, { fontSize: '13px', fontStyle: 'bold italic', color: '#8a1a10' }).setDepth(depth)); + } + (spec.tray ?? []).forEach((color, i) => { + if (spec.trayHidden?.has(i)) return; + const s = TRAY_SLOT(i); + const img = scene.add.image(s.x, s.y, chipKey(color)).setDisplaySize(44, 44).setDepth(depth + 1); + objs.push(img); + if (spec.onTray) { + img.setInteractive({ useHandCursor: true }); + img.on('pointerdown', () => spec.onTray(i)); + } + }); + const btns = spec.buttons ?? []; + const bx = d.x + d.w - 100; + btns.forEach((b, i) => { + const y = btns.length === 1 ? d.y + d.h / 2 : d.y + 30 + i * 52; + const btn = new Button(scene, b.x ?? bx, y, b.label, b.fn, { + width: b.w ?? 170, height: 42, fontSize: 17, bg: b.bg ?? 0x5a3820, + }).setDepth(depth + 2); + objs.push(btn); + }); + return objs; +} + +// ── big card preview ───────────────────────────────────────────────────────────────────── +export function showPreview(scene, card, anchor, depth) { + ensureCardFace(scene, card); + const objs = []; + const pw = 250, ph = Math.round(pw * FACE_H / FACE_W), capH = 74; + let x = anchor.x + anchor.w + 16; + if (x + pw > W - 10) x = anchor.x - pw - 16; + let y = anchor.y + anchor.h / 2 - (ph + capH) / 2; + y = Math.max(10, Math.min(H - ph - capH - 10, y)); + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.55).fillRoundedRect(x - 8, y - 8, pw + 16, ph + capH + 16, 16); + objs.push(g); + objs.push(scene.add.image(x + pw / 2, y + ph / 2, cardKey(card)).setDisplaySize(pw, ph).setDepth(depth + 1)); + const cg = scene.add.graphics().setDepth(depth + 1); + cg.fillStyle(0x2a1a0c, 1).fillRoundedRect(x, y + ph + 6, pw, capH - 8, 8); + cg.lineStyle(1.5, 0xd9b45a, 0.9).strokeRoundedRect(x, y + ph + 6, pw, capH - 8, 8); + objs.push(cg); + objs.push(scene.add.text(x + pw / 2, y + ph + 24, locationOf(card), { fontFamily: DISPLAY, fontSize: '17px', color: '#f4dc9a' }).setOrigin(0.5).setDepth(depth + 2)); + const pts = card.points ? `${card.points} prestige · ` : ''; + objs.push(txt(scene, x + pw / 2, y + ph + 48, `${TIER_NAME[card.tier]} · ${pts}${GEM_NAME[card.bonus]} bonus`, { fontSize: '12px', fontStyle: 'italic', color: '#d8c08a' }).setOrigin(0.5).setDepth(depth + 2)); + return objs; +} diff --git a/src/games/splendor/SplendorLayout.js b/src/games/splendor/SplendorLayout.js new file mode 100644 index 0000000..172f5d6 --- /dev/null +++ b/src/games/splendor/SplendorLayout.js @@ -0,0 +1,137 @@ +// SplendorLayout.js — every rect on the counting-house table (pure, no Phaser). +// +// ┌ Patrons' Gallery (nobles) ─────┬ Guild Register (prestige track) ┬ music ┐ +// ├ market: 3 rows (plaque, deck, 4 cards) ┬ jewel case ┬ rival ledgers │ +// │ │ (bank) │ (1–3, stacked) │ +// ├ your ledger ────────────────────────────┴────────────┼ merchant's dock ─┘ +// +// 1920×1080 canvas. `computeLayout(playerCount)` returns the per-seat ledger +// rects; everything else is fixed. + +import { GEMS, GOLD } from './SplendorData.js'; + +export const W = 1920, H = 1080; + +// ── top band ────────────────────────────────────────────────────────────────────── +export const WALL = { x: 0, y: 0, w: W, h: 186 }; +export const GALLERY = { x: 22, y: 6, w: 790, h: 176 }; +export const NOBLE = { w: 112, h: 112, plateH: 28, step: 148, y: 14 }; // portrait + req plate +export const NOBLE_PROGRESS_Y = NOBLE.y + NOBLE.h + NOBLE.plateH + 4; // first progress row +export const TRACK = { x: 838, y: 22, w: 740, h: 142 }; // leaves room for the music line +export const MUSIC = { right: 1906, top: 4 }; +export const MENU_BTN = { x: 1700, y: 120, w: 96, h: 40 }; +export const HELP_BTN = { x: 1806, y: 120, w: 100, h: 40 }; + +// ── market ────────────────────────────────────────────────────────────────────── +export const CW = 128, CH = 176; // market card display size +export const CARD_GAP = 14; +export const PLAQUE = { x: 24, w: 40 }; +export const DECK_X = 74; +export const CARDS_X = DECK_X + CW + 24; // first face-up slot +export const ROW_Y = { 3: 200, 2: 390, 1: 580 }; +export const MARKET = { x: 16, y: 192, w: 774, h: 572 }; + +export function slotRect(tier, slot) { + return { x: CARDS_X + slot * (CW + CARD_GAP), y: ROW_Y[tier], w: CW, h: CH }; +} +export function deckRect(tier) { return { x: DECK_X, y: ROW_Y[tier], w: CW, h: CH }; } +export function plaqueRect(tier) { return { x: PLAQUE.x, y: ROW_Y[tier] + 6, w: PLAQUE.w, h: CH - 12 }; } + +// ── jewel case (bank) ───────────────────────────────────────────────────────────── +export const BANK = { x: 804, y: 192, w: 192, h: 572 }; +export const BANK_ORDER = [...GEMS, GOLD]; +const BANK_PAD = 14; +export const BANK_CELL_H = (BANK.h - BANK_PAD * 2) / BANK_ORDER.length; +export const BANK_CHIP = 62; // chip display size in the case +export function bankCell(color) { + const i = BANK_ORDER.indexOf(color); + return { x: BANK.x + BANK_PAD, y: BANK.y + BANK_PAD + i * BANK_CELL_H, w: BANK.w - BANK_PAD * 2, h: BANK_CELL_H - 6 }; +} +export function bankChipPos(color) { + const c = bankCell(color); + return { x: c.x + 50, y: c.y + c.h / 2 + 4 }; +} + +// ── ledgers ─────────────────────────────────────────────────────────────────────── +export const HUMAN_LEDGER = { x: 16, y: 774, w: 980, h: 294 }; +export const RIVALS = { x: 1012, y: 192, w: 892, h: 752 }; +export const DOCK = { x: 1012, y: 954, w: 892, h: 114 }; + +export function computeLayout(playerCount) { + const n = Math.max(2, Math.min(4, playerCount)); + const rivals = n - 1; + const gap = 12; + const h = Math.min(300, Math.floor((RIVALS.h - gap * (rivals - 1)) / rivals)); + const ledgers = [{ ...HUMAN_LEDGER, seat: 0, human: true }]; + for (let i = 0; i < rivals; i++) { + ledgers.push({ x: RIVALS.x, y: RIVALS.y + i * (h + gap), w: RIVALS.w, h, seat: i + 1, human: false }); + } + return { n, ledgers }; +} + +// Inside a ledger: header block, five colour columns, gold, reserve slots. +export const MINI = { w: 60, h: 83 }; // tableau mini-card +export const RES = { w: 68, h: 94 }; // reserve-slot card +export const HEAD_W = 186; +export function ledgerParts(L) { + const resW = 3 * RES.w + 2 * 8; + const goldW = 70; + const colsX = L.x + HEAD_W; + const colsW = L.w - HEAD_W - resW - goldW - 34; + const colW = colsW / GEMS.length; + const chipY = L.y + L.h - 34; + const stackTop = L.y + 34; + const stackBottom = chipY - 26; + const cols = {}; + GEMS.forEach((g, i) => { + const cx = colsX + i * colW + colW / 2; + cols[g] = { cx, x: colsX + i * colW, w: colW, stackTop, stackBottom, chip: { x: cx - 12, y: chipY } }; + }); + const goldX = colsX + colsW + 8; + const resX = goldX + goldW + 10; + const reserve = [0, 1, 2].map((i) => ({ x: resX + i * (RES.w + 8), y: L.y + L.h / 2 - RES.h / 2 + 8, w: RES.w, h: RES.h })); + return { + name: { x: L.x + 18, y: L.y + 12 }, + portrait: { x: L.x + 58, y: L.y + 92, r: 36 }, + seal: { x: L.x + 146, y: L.y + 84, r: 30 }, + cameos: { x: L.x + 16, y: L.y + L.h - 52, size: 38, gap: 5 }, + cols, + gold: { cx: goldX + goldW / 2, chip: { x: goldX + goldW / 2 - 12, y: chipY }, top: stackTop }, + reserve, + reserveLabel: { x: resX + (3 * RES.w + 16) / 2, y: L.y + 16 }, + }; +} + +// Mini-card position within a colour stack (index i of n). +export function stackPos(col, i, n) { + const avail = col.stackBottom - col.stackTop - MINI.h; + const step = n <= 1 ? 0 : Math.min(18, avail / (n - 1)); + return { x: col.cx, y: col.stackTop + MINI.h / 2 + i * step }; +} + +// ── prestige track ──────────────────────────────────────────────────────────────── +export const TRACK_RULE = { x0: TRACK.x + 60, x1: TRACK.x + TRACK.w - 70, y: TRACK.y + 86 }; +export function trackX(points) { + const p = Math.max(0, Math.min(15, points)); + return TRACK_RULE.x0 + (TRACK_RULE.x1 - TRACK_RULE.x0) * (p / 15); +} + +export const SEAT_HEX = [0xe2bd62, 0xc0533f, 0x3f9aa8, 0x9a68c0]; +export const SEAT_CSS = ['#e2bd62', '#c0533f', '#3f9aa8', '#9a68c0']; + +// ── geometry helpers (also used by the verifier) ────────────────────────────────── +export const rectsOverlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; +export const inside = (inner, outer) => inner.x >= outer.x - 0.5 && inner.y >= outer.y - 0.5 + && inner.x + inner.w <= outer.x + outer.w + 0.5 && inner.y + inner.h <= outer.y + outer.h + 0.5; +export const onScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H; +export const contains = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h; + +// Big furniture rects that must not overlap one another. +export function furniture(playerCount) { + const { ledgers } = computeLayout(playerCount); + const out = [ + ['gallery', GALLERY], ['track', TRACK], ['market', MARKET], ['bank', BANK], ['dock', DOCK], + ...ledgers.map((l) => [`ledger${l.seat}`, l]), + ]; + return out; +} diff --git a/src/games/splendor/SplendorLogic.js b/src/games/splendor/SplendorLogic.js index a054758..6871050 100644 --- a/src/games/splendor/SplendorLogic.js +++ b/src/games/splendor/SplendorLogic.js @@ -1,20 +1,28 @@ // Splendor — pure state engine. No Phaser, no network, no rendering. // // State is immutable from the outside: every mutator deep-clones and returns a -// fresh state (the IslandLogic/BlokusLogic idiom). Randomness is seeded so games -// are reproducible and testable. A turn is exactly one action (take3 / take2 / -// reserve / buy); if it leaves the player over the 10-token limit the state -// parks in a 'discard' phase until tokens are returned, then the turn finalizes -// (noble visit + end-of-game check + advance). +// fresh state. Randomness is seeded so games are reproducible and testable. +// +// A turn is exactly one action (take3 / take2 / reserve / reserveDeck / buy / +// pass). After it the turn may park: +// phase 'discard' the player holds more than 10 tokens → applyDiscard(map) +// phase 'noble' more than one noble qualifies → applyNobleChoice(id) +// and then finalizes (noble visit, end-of-game check, advance to next seat). +// +// Scene-facing extras: every player keeps `cards` (bought, in order), reserved +// cards carry `blind: true` when drawn from a deck (hidden from opponents), +// per-seat `stats`, and `lastAction` / `lastVisit` describe the latest move so +// the table can animate it. import { - GEMS, GOLD, CARDS_BY_TIER, NOBLES, tokenSupplyFor, + GEMS, GOLD, CARDS_BY_TIER, NOBLES, tokenSupplyFor, GEM_NAME, TIER_NOUN, locationOf, nobleInfo, WIN_POINTS, HAND_LIMIT, MAX_RESERVED, FACE_UP_PER_TIER, TAKE_SAME_MIN, NOBLE_POINTS, } from './SplendorData.js'; -const TIERS = [1, 2, 3]; +export const TIERS = [1, 2, 3]; +const ALL = [...GEMS, GOLD]; -// ── seeded RNG (mulberry32), matching IslandLogic ──────────────────────────── +// ── seeded RNG (mulberry32) ───────────────────────────────────────────────────── function rngFrom(seedState) { let a = seedState >>> 0; return () => { @@ -33,15 +41,32 @@ function shuffle(arr, rng) { return a; } -const clone = (s) => JSON.parse(JSON.stringify(s)); +export const clone = (s) => JSON.parse(JSON.stringify(s)); const emptyTokens = () => ({ white: 0, blue: 0, green: 0, red: 0, black: 0, gold: 0 }); const emptyBonuses = () => ({ white: 0, blue: 0, green: 0, red: 0, black: 0 }); +export function emptyStats() { + return { + taken: emptyTokens(), // tokens drawn from the case (gold = from reserving) + returned: 0, // tokens handed back over the hand limit + goldSpent: 0, + bonusSaved: 0, // gems the card bonuses paid for + bought: { 1: 0, 2: 0, 3: 0 }, + fromReserve: 0, + reserves: 0, + blindReserves: 0, + biggest: null, // { cardId, points, price } — highest-point buy (price breaks ties) + pointsByTurn: [], // prestige after each of this player's turns + turns: 0, + }; +} +const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`; +const gemList = (colors) => colors.map((c) => GEM_NAME[c]).join(', '); -// ── queries ────────────────────────────────────────────────────────────────── +// ── queries ────────────────────────────────────────────────────────────────────── export function currentPlayer(state) { return state.players[state.current]; } export function tokenTotal(p) { - return GEMS.reduce((n, g) => n + p.tokens[g], 0) + p.tokens[GOLD]; + return ALL.reduce((n, g) => n + (p.tokens[g] ?? 0), 0); } // How a player would pay for `card`: coloured tokens used per colour + gold to @@ -62,12 +87,51 @@ export function canAfford(p, card) { return purchaseCost(p, card).gold <= p.tokens[GOLD]; } +// Per-colour breakdown for the cost pips: printed cost, what the bonuses +// cover, what is still owed in tokens, and how many of those are missing. +export function effectiveCost(p, card) { + const rows = []; + for (const color of GEMS) { + const printed = card.cost[color] ?? 0; + if (!printed) continue; + const covered = Math.min(printed, p.bonuses[color] ?? 0); + const owed = printed - covered; + const short = Math.max(0, owed - (p.tokens[color] ?? 0)); + rows.push({ color, printed, covered, owed, short }); + } + return rows; +} + +// Affordability class for highlighting: +// 'now' buy with coloured tokens alone +// 'gold' buy, but only by spending gold (goldUsed > 0) +// 'near' exactly one gem short even after gold +// 'far' anything else +export function affordState(p, card) { + const { gold } = purchaseCost(p, card); + const have = p.tokens[GOLD] ?? 0; + if (gold === 0) return { kind: 'now', gold: 0, short: 0 }; + if (gold <= have) return { kind: 'gold', gold, short: 0 }; + const short = gold - have; + return { kind: short === 1 ? 'near' : 'far', gold: have, short }; +} + // Nobles the player currently qualifies for. export function qualifyingNobles(state, p) { return state.nobles.filter((n) => Object.entries(n.requires).every(([color, req]) => (p.bonuses[color] ?? 0) >= req)); } +// { have, need } toward a noble (bonuses only, capped per colour). +export function nobleProgress(p, noble) { + let have = 0, need = 0; + for (const [color, req] of Object.entries(noble.requires)) { + need += req; + have += Math.min(req, p.bonuses[color] ?? 0); + } + return { have, need }; +} + export function cardById(state, id) { for (const t of TIERS) { const found = state.board[t].find((c) => c && c.id === id); @@ -80,12 +144,46 @@ export function cardById(state, id) { return null; } -// ── construction ───────────────────────────────────────────────────────────── +// Where a card sits on the market: { tier, slot } or null. +export function boardSlotOf(state, id) { + for (const t of TIERS) { + const i = state.board[t].findIndex((c) => c && c.id === id); + if (i >= 0) return { tier: t, slot: i }; + } + return null; +} + +// What buying `card` would do for `p`: tokens paid, gold, bonus saved, points, +// and the nobles it would unlock or bring closer. +export function previewBuy(state, p, card) { + const { pay, gold } = purchaseCost(p, card); + let saved = 0; + for (const color of GEMS) saved += Math.min(card.cost[color] ?? 0, p.bonuses[color] ?? 0); + const after = { ...p, bonuses: { ...p.bonuses, [card.bonus]: (p.bonuses[card.bonus] ?? 0) + 1 } }; + const nobles = state.nobles.map((n) => { + const before = nobleProgress(p, n), now = nobleProgress(after, n); + return { noble: n, before: before.have, after: now.have, need: now.need, gained: now.have > before.have }; + }).filter((x) => x.gained); + const unlocks = nobles.filter((x) => x.after >= x.need).map((x) => x.noble); + return { + pay, gold, saved, + affordable: gold <= (p.tokens[GOLD] ?? 0), + points: card.points, + pointsAfter: p.points + card.points + (unlocks.length ? NOBLE_POINTS : 0), + nobles, unlocks, + }; +} + +// Opponents' view of a player's reserve: blind cards are face-down. +export function visibleReserved(p, viewerSeat) { + return p.reserved.map((c) => (c.blind && p.seat !== viewerSeat ? { id: c.id, tier: c.tier, hidden: true } : c)); +} + +// ── construction ───────────────────────────────────────────────────────────────── export function createInitialState({ playerCount = 4, names = [], seed } = {}) { const pc = Math.max(2, Math.min(4, playerCount)); const s = { seed: (seed ?? Math.floor(Math.random() * 1e9)) >>> 0, - rngCursor: 0, playerCount: pc, bank: tokenSupplyFor(pc), decks: {}, @@ -93,9 +191,14 @@ export function createInitialState({ playerCount = 4, names = [], seed } = {}) { nobles: [], players: [], current: 0, - phase: 'turn', // turn | discard | gameOver + turn: 0, // turns completed in total + round: 1, // 1-based round number + phase: 'turn', // turn | discard | noble | gameOver pendingDiscardSeat: null, + pendingNobles: null, // noble ids to choose from (phase 'noble') triggeredEnd: false, + endTriggeredBy: null, // seat that first reached 15 + lastAction: null, lastVisit: null, // { seat, nobleId } for the scene to animate log: [], }; @@ -116,15 +219,17 @@ export function createInitialState({ playerCount = 4, names = [], seed } = {}) { tokens: emptyTokens(), bonuses: emptyBonuses(), reserved: [], + cards: [], nobles: [], points: 0, cardsCount: 0, + stats: emptyStats(), }); } return s; } -// ── legal actions ──────────────────────────────────────────────────────────── +// ── legal actions ──────────────────────────────────────────────────────────────── function combinations(arr, k) { if (k === 0) return [[]]; if (arr.length < k) return []; @@ -140,13 +245,11 @@ export function legalActions(state) { const p = currentPlayer(state); const actions = []; - // take 3 different (or as many distinct colours as the bank can offer, up to 3) + // take 3 different (or as many distinct colours as the case can offer, up to 3) const avail = GEMS.filter((g) => state.bank[g] > 0); const k = Math.min(3, avail.length); if (k > 0) { - for (const combo of combinations(avail, k)) { - actions.push({ type: 'take3', colors: combo }); - } + for (const combo of combinations(avail, k)) actions.push({ type: 'take3', colors: combo }); } // take 2 of one colour (pile must have ≥4) @@ -177,15 +280,34 @@ export function legalActions(state) { return actions; } -// ── helpers used by applyAction ────────────────────────────────────────────── +// Is `action` legal right now? (selection UIs build actions by hand) +export function isLegal(state, action) { + return legalActions(state).some((a) => sameAction(a, action)); +} + +export function sameAction(a, b) { + if (!a || !b || a.type !== b.type) return false; + switch (a.type) { + case 'take2': return a.color === b.color; + case 'take3': return [...a.colors].sort().join() === [...b.colors].sort().join(); + case 'reserve': case 'buy': return a.cardId === b.cardId; + case 'reserveDeck': return a.tier === b.tier; + default: return true; + } +} + +// ── helpers used by applyAction ────────────────────────────────────────────────── function drawTop(s, tier) { return s.decks[tier].length ? s.decks[tier].shift() : null; } +// Replace the taken card; returns { tier, slot, cardId } (cardId null = empty). function refillSlot(s, tier, cardId) { const row = s.board[tier]; const idx = row.findIndex((c) => c && c.id === cardId); - if (idx >= 0) row[idx] = drawTop(s, tier); + if (idx < 0) return null; + row[idx] = drawTop(s, tier); + return { tier, slot: idx, cardId: row[idx]?.id ?? null }; } // After tokens change, either park for discard or finalize the turn. @@ -198,97 +320,153 @@ function afterAction(s) { return finalizeTurn(s); } -// Noble visit, win trigger, advance to next seat. +function awardNoble(s, p, noble) { + s.nobles = s.nobles.filter((n) => n.id !== noble.id); + p.nobles.push(noble); + p.points += NOBLE_POINTS; + s.lastVisit = { seat: p.seat, nobleId: noble.id }; + const info = nobleInfo(noble); + s.log.push(`${info.name}, ${info.title}, becomes ${p.name}'s patron (+${NOBLE_POINTS}).`); +} + +// Noble visit (or park for a choice), then end the turn. function finalizeTurn(s) { const p = currentPlayer(s); + s.lastVisit = null; const eligible = qualifyingNobles(s, p); - if (eligible.length) { - // Award the highest-requirement noble (ties: first). One visit per turn. - const noble = eligible[0]; - s.nobles = s.nobles.filter((n) => n.id !== noble.id); - p.nobles.push(noble); - p.points += NOBLE_POINTS; - s.lastVisit = { seat: p.seat, nobleId: noble.id }; - } else { - s.lastVisit = null; + if (eligible.length > 1) { + s.phase = 'noble'; + s.pendingDiscardSeat = null; + s.pendingNobles = eligible.map((n) => n.id); + return s; } + if (eligible.length === 1) awardNoble(s, p, eligible[0]); + return endTurn(s); +} - if (p.points >= WIN_POINTS) s.triggeredEnd = true; - +function endTurn(s) { + const p = currentPlayer(s); + p.stats.turns++; + p.stats.pointsByTurn.push(p.points); + if (p.points >= WIN_POINTS && !s.triggeredEnd) { + s.triggeredEnd = true; + s.endTriggeredBy = p.seat; + s.log.push(`${p.name} reaches ${p.points} prestige — the final round begins.`); + } + s.turn++; s.current = (s.current + 1) % s.playerCount; + if (s.current === 0) s.round++; s.phase = (s.triggeredEnd && s.current === 0) ? 'gameOver' : 'turn'; s.pendingDiscardSeat = null; + s.pendingNobles = null; return s; } -// ── apply a turn action ────────────────────────────────────────────────────── +// ── apply a turn action ────────────────────────────────────────────────────────── export function applyAction(state, action) { const s = clone(state); if (s.phase !== 'turn') return s; const p = currentPlayer(s); + const seat = p.seat; switch (action.type) { case 'take3': { - for (const g of action.colors) { s.bank[g]--; p.tokens[g]++; } - s.log.push(`${p.name} takes ${action.colors.join(', ')}.`); + const colors = [...new Set(action.colors)]; + if (!colors.length || colors.length > 3 || colors.some((g) => !GEMS.includes(g) || s.bank[g] <= 0)) return state; + for (const g of colors) { s.bank[g]--; p.tokens[g]++; p.stats.taken[g]++; } + s.lastAction = { seat, type: 'take3', colors }; + s.log.push(`${p.name} takes ${gemList(colors)}.`); return afterAction(s); } case 'take2': { - s.bank[action.color] -= 2; p.tokens[action.color] += 2; - s.log.push(`${p.name} takes 2 ${action.color}.`); + if (!GEMS.includes(action.color) || s.bank[action.color] < TAKE_SAME_MIN) return state; + s.bank[action.color] -= 2; p.tokens[action.color] += 2; p.stats.taken[action.color] += 2; + s.lastAction = { seat, type: 'take2', color: action.color, colors: [action.color, action.color] }; + s.log.push(`${p.name} takes two ${GEM_NAME[action.color]}s.`); return afterAction(s); } case 'reserve': { - const card = cardById(s, action.cardId); - if (!card) return s; - refillSlot(s, action.tier, action.cardId); - p.reserved.push(card); - if (s.bank[GOLD] > 0) { s.bank[GOLD]--; p.tokens[GOLD]++; } - s.log.push(`${p.name} reserves a tier-${action.tier} card.`); + if (p.reserved.length >= MAX_RESERVED) return state; + const pos = boardSlotOf(s, action.cardId); + if (!pos) return state; + const card = s.board[pos.tier][pos.slot]; + const refill = refillSlot(s, pos.tier, card.id); + p.reserved.push({ ...card }); + const gold = s.bank[GOLD] > 0 ? 1 : 0; + if (gold) { s.bank[GOLD]--; p.tokens[GOLD]++; p.stats.taken.gold++; } + p.stats.reserves++; + s.lastAction = { seat, type: 'reserve', cardId: card.id, tier: pos.tier, slot: pos.slot, refill, gold }; + s.log.push(`${p.name} reserves ${locationOf(card)} (${TIER_NOUN[card.tier]})${gold ? ' and takes a gold' : ''}.`); return afterAction(s); } case 'reserveDeck': { + if (p.reserved.length >= MAX_RESERVED) return state; const card = drawTop(s, action.tier); - if (!card) return s; - p.reserved.push(card); - if (s.bank[GOLD] > 0) { s.bank[GOLD]--; p.tokens[GOLD]++; } - s.log.push(`${p.name} reserves the top tier-${action.tier} card.`); + if (!card) return state; + p.reserved.push({ ...card, blind: true }); + const gold = s.bank[GOLD] > 0 ? 1 : 0; + if (gold) { s.bank[GOLD]--; p.tokens[GOLD]++; p.stats.taken.gold++; } + p.stats.reserves++; p.stats.blindReserves++; + s.lastAction = { seat, type: 'reserveDeck', cardId: card.id, tier: action.tier, gold }; + s.log.push(`${p.name} reserves a ${TIER_NOUN[action.tier]} sight unseen${gold ? ' and takes a gold' : ''}.`); return afterAction(s); } case 'buy': { - const card = cardById(s, action.cardId); - if (!card || !canAfford(p, card)) return s; + const fromReserve = p.reserved.some((c) => c.id === action.cardId); + const pos = fromReserve ? null : boardSlotOf(s, action.cardId); + if (!fromReserve && !pos) return state; + const card = fromReserve ? p.reserved.find((c) => c.id === action.cardId) : s.board[pos.tier][pos.slot]; + if (!canAfford(p, card)) return state; const { pay, gold } = purchaseCost(p, card); - for (const color of GEMS) { p.tokens[color] -= pay[color]; s.bank[color] += pay[color]; } + let saved = 0, price = 0; + for (const color of GEMS) { + p.tokens[color] -= pay[color]; s.bank[color] += pay[color]; + saved += Math.min(card.cost[color] ?? 0, p.bonuses[color] ?? 0); + price += card.cost[color] ?? 0; + } p.tokens[GOLD] -= gold; s.bank[GOLD] += gold; p.bonuses[card.bonus]++; p.points += card.points; p.cardsCount++; - if (action.source === 'reserve') { - p.reserved = p.reserved.filter((c) => c.id !== card.id); - } else { - refillSlot(s, card.tier, card.id); + const { blind: _b, ...clean } = card; + p.cards.push(clean); + p.stats.goldSpent += gold; + p.stats.bonusSaved += saved; + p.stats.bought[card.tier]++; + const big = p.stats.biggest; + if (card.points > 0 && (!big || card.points > big.points || (card.points === big.points && price > big.price))) { + p.stats.biggest = { cardId: card.id, points: card.points, price }; } - s.log.push(`${p.name} buys a ${card.bonus} card${card.points ? ` (+${card.points})` : ''}.`); + let refill = null; + if (fromReserve) { + p.reserved = p.reserved.filter((c) => c.id !== card.id); + p.stats.fromReserve++; + } else { + refill = refillSlot(s, card.tier, card.id); + } + s.lastAction = { + seat, type: 'buy', cardId: card.id, tier: card.tier, source: fromReserve ? 'reserve' : 'board', + slot: pos?.slot ?? null, pay, gold, refill, + }; + s.log.push(`${p.name} acquires ${locationOf(card)}${card.points ? ` (+${card.points})` : ''}${gold ? `, spending ${plural(gold, 'gold')}` : ''}.`); return afterAction(s); } case 'pass': - // No legal action available (bank empty, nothing affordable, reserve full). + s.lastAction = { seat, type: 'pass' }; s.log.push(`${p.name} cannot act and passes.`); return finalizeTurn(s); default: - return s; + return state; } } -// ── discard phase ──────────────────────────────────────────────────────────── +// ── discard phase ────────────────────────────────────────────────────────────────── // Default choice: return the most-abundant coloured tokens first, never gold. export function defaultDiscards(state) { const p = currentPlayer(state); const excess = tokenTotal(p) - HAND_LIMIT; const map = {}; let left = Math.max(0, excess); - // Greedily shave from the largest non-gold piles. const pools = GEMS.map((g) => ({ g, n: p.tokens[g] })); while (left > 0) { pools.sort((a, b) => (b.n - (map[b.g] ?? 0)) - (a.n - (map[a.g] ?? 0))); @@ -304,25 +482,83 @@ export function applyDiscard(state, discardMap) { const s = clone(state); if (s.phase !== 'discard') return s; const p = currentPlayer(s); + const returned = {}; for (const [color, n] of Object.entries(discardMap)) { - const take = Math.min(n, p.tokens[color] ?? 0); + if (!ALL.includes(color)) continue; + const take = Math.max(0, Math.min(n, p.tokens[color] ?? 0)); + if (!take) continue; p.tokens[color] -= take; s.bank[color] += take; + p.stats.returned += take; + returned[color] = take; } - if (tokenTotal(p) > HAND_LIMIT) { - // Still over (incomplete discard) — stay parked. - return s; + const n = Object.values(returned).reduce((a, b) => a + b, 0); + if (n) { + s.log.push(`${p.name} returns ${Object.entries(returned).map(([c, k]) => `${k} ${GEM_NAME[c]}`).join(', ')}.`); + s.lastDiscard = { seat: p.seat, returned }; } + if (tokenTotal(p) > HAND_LIMIT) return s; // still over — stay parked s.phase = 'turn'; return finalizeTurn(s); } -// ── end of game ────────────────────────────────────────────────────────────── +// ── noble choice ─────────────────────────────────────────────────────────────────── +export function applyNobleChoice(state, nobleId) { + if (state.phase !== 'noble' || !state.pendingNobles?.includes(nobleId)) return state; + const s = clone(state); + const p = currentPlayer(s); + const noble = s.nobles.find((n) => n.id === nobleId); + awardNoble(s, p, noble); + return endTurn(s); +} + +// ── end of game ──────────────────────────────────────────────────────────────────── export function isGameOver(state) { return state.phase === 'gameOver'; } // Ranking: most prestige, then fewest purchased cards (official tiebreak). +// `place` is shared on a full tie. export function finalRanking(state) { - return state.players + const rows = state.players .map((p) => ({ seat: p.seat, name: p.name, points: p.points, cards: p.cardsCount })) - .sort((a, b) => (b.points - a.points) || (a.cards - b.cards)); + .sort((a, b) => (b.points - a.points) || (a.cards - b.cards) || (a.seat - b.seat)); + rows.forEach((r, i) => { + const prev = rows[i - 1]; + r.place = prev && prev.points === r.points && prev.cards === r.cards ? prev.place : i + 1; + r.wonOnTiebreak = i === 0 && rows[1] && rows[1].points === r.points && rows[1].cards > r.cards; + }); + return rows; +} + +// Run the game forward through parked phases with the given resolvers. +// Used by headless tools; the scene drives phases itself. +export function resolvePending(state, { discard = defaultDiscards, noble = (s) => s.pendingNobles[0] } = {}) { + let s = state; + for (let guard = 0; guard < 8; guard++) { + if (s.phase === 'discard') s = applyDiscard(s, discard(s)); + else if (s.phase === 'noble') s = applyNobleChoice(s, noble(s)); + else break; + } + return s; +} + +// ── end-of-game honours (pure; shown on the Guild Ledger) ────────────────────────── +// Each award goes to every seat tied for the best (and only when it is > 0). +export function awardsFor(state) { + const out = []; + const best = (title, valueOf, detailOf) => { + let top = 0; + for (const p of state.players) top = Math.max(top, valueOf(p)); + if (top <= 0) return; + for (const p of state.players) if (valueOf(p) === top) out.push({ seat: p.seat, title, detail: detailOf(p, top) }); + }; + const bigOf = (p) => (p.stats.biggest ? p.stats.biggest.points * 100 + p.stats.biggest.price : 0); + best('Grandest Acquisition', bigOf, (p) => { + const c = p.cards.find((x) => x.id === p.stats.biggest.cardId); + return c ? `${locationOf(c)} (+${c.points})` : `+${p.stats.biggest.points}`; + }); + best('Shrewdest Buyer', (p) => p.stats.bonusSaved, (p, v) => `card bonuses paid ${plural(v, 'gem')}`); + best('Golden Hand', (p) => p.stats.goldSpent, (p, v) => `spent ${v} gold`); + best("Patrons' Favourite", (p) => p.nobles.length, (p, v) => plural(v, 'noble patron')); + best('Shipping Magnate', (p) => p.stats.bought[2], (p, v) => plural(v, 'trade route')); + return out; } diff --git a/src/games/splendor/SplendorSound.js b/src/games/splendor/SplendorSound.js new file mode 100644 index 0000000..c07dd2d --- /dev/null +++ b/src/games/splendor/SplendorSound.js @@ -0,0 +1,172 @@ +// SplendorSound.js — the counting house's sounds. +// +// Small Web Audio synths (no files) layered with the shared gem / coin mp3s. +// Everything is silent when the game is muted or Web Audio is missing. +// +// chips(scene, { n }) gem tokens set down (n staggered clacks) +// pick(scene, i) a single gem lifted from the case (mp3) +// swish(scene) a card dealt / slid across the cloth +// thud(scene) a card laid on the velvet of a ledger +// coins(scene) payment poured back into the case (mp3) +// chime(scene, { n }) a bright bell (bigger purchases ring higher) +// fanfare(scene) a patron arrives +// stamp(scene) the wax seal pressed + +function ctxOf(scene) { + const sm = scene.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} + +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 0.6), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + noiseCache.set(ac, buf); + return buf; +} + +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} + +// One clay-chip click: a damped mid partial pair with a knock of filtered noise. +function click(ac, dest, t0, { freq = 2100, decay = 0.06, vol = 1, body = 0.5 } = {}) { + for (const [f, a] of [[freq, 1], [freq * 1.38, 0.45], [freq * 0.47, body]]) { + const o = ac.createOscillator(); + o.type = 'sine'; + o.frequency.setValueAtTime(f, t0); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(vol * a, t0 + 0.002); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + decay * (f < freq ? 1.5 : 1)); + o.connect(g); g.connect(dest); + o.start(t0); o.stop(t0 + decay * 2 + 0.02); + } + const n = ac.createBufferSource(); + n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 2400; bp.Q.value = 0.8; + const ng = ac.createGain(); + ng.gain.setValueAtTime(vol * 0.7, t0); + ng.gain.exponentialRampToValueAtTime(0.0005, t0 + 0.02); + n.connect(bp); bp.connect(ng); ng.connect(dest); + n.start(t0, Math.random() * 0.4); n.stop(t0 + 0.03); +} + +export function chips(scene, { n = 1, vol = 0.08, spread = 0.05 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.005; + for (let k = 0; k < Math.min(n, 6); k++) { + click(ac, dest, t0 + k * spread + Math.random() * 0.012, { freq: 1800 + Math.random() * 600, decay: 0.05 + Math.random() * 0.02 }); + } + } catch (_) { /* audio is decoration */ } +} + +export function swish(scene, { vol = 0.05 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.005; + const src = ac.createBufferSource(); src.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.Q.value = 0.7; + bp.frequency.setValueAtTime(900, t0); bp.frequency.exponentialRampToValueAtTime(3200, t0 + 0.16); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(1, t0 + 0.05); g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.2); + src.connect(bp); bp.connect(g); g.connect(dest); + src.start(t0, Math.random() * 0.3); src.stop(t0 + 0.22); + } catch (_) { /* audio is decoration */ } +} + +export function thud(scene, { vol = 0.12 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.005; + const o = ac.createOscillator(); const g = ac.createGain(); + o.frequency.setValueAtTime(150, t0); o.frequency.exponentialRampToValueAtTime(70, t0 + 0.12); + g.gain.setValueAtTime(0.8, t0); g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.16); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + 0.18); + const src = ac.createBufferSource(); src.buffer = noise(ac); + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 900; + const ng = ac.createGain(); ng.gain.setValueAtTime(0.5, t0); ng.gain.exponentialRampToValueAtTime(0.001, t0 + 0.08); + src.connect(lp); lp.connect(ng); ng.connect(dest); src.start(t0); src.stop(t0 + 0.1); + } catch (_) { /* audio is decoration */ } +} + +export function chime(scene, { n = 1, vol = 0.055 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.01; + const scale = [0, 4, 7, 12, 16, 19]; + const notes = Math.max(1, Math.min(4, n)); + for (let k = 0; k < notes; k++) { + const base = 783.99 * 2 ** (scale[Math.min(scale.length - 1, k + Math.max(0, n - 2))] / 12); + const t = t0 + k * 0.09; + for (const [mul, a, dur] of [[1, 1, 1.1], [2.76, 0.3, 0.5], [5.4, 0.1, 0.25]]) { + const o = ac.createOscillator(); o.type = 'sine'; o.frequency.value = base * mul; + const g = ac.createGain(); + g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + 0.005); g.gain.exponentialRampToValueAtTime(0.0005, t + dur); + o.connect(g); g.connect(dest); o.start(t); o.stop(t + dur + 0.05); + } + } + } catch (_) { /* audio is decoration */ } +} + +export function fanfare(scene, { vol = 0.06 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.01; + [[392, 0, 0.25], [523.25, 0.16, 0.25], [659.25, 0.32, 0.25], [783.99, 0.48, 0.9]].forEach(([f, dt, dur]) => { + for (const [mul, a] of [[1, 0.7], [2, 0.25], [3, 0.12]]) { + const o = ac.createOscillator(); o.type = 'triangle'; o.frequency.value = f * mul; + const g = ac.createGain(); + const t = t0 + dt; + g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + 0.02); + g.gain.setValueAtTime(a, t + dur * 0.6); g.gain.exponentialRampToValueAtTime(0.0005, t + dur); + o.connect(g); g.connect(dest); o.start(t); o.stop(t + dur + 0.05); + } + }); + } catch (_) { /* audio is decoration */ } +} + +export function stamp(scene, { vol = 0.14 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const dest = out(scene, ac, vol); + const t0 = ac.currentTime + 0.005; + const o = ac.createOscillator(); const g = ac.createGain(); + o.frequency.setValueAtTime(95, t0); o.frequency.exponentialRampToValueAtTime(45, t0 + 0.2); + g.gain.setValueAtTime(1, t0); g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.25); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + 0.27); + } catch (_) { /* audio is decoration */ } +} + +// ── shared mp3s ───────────────────────────────────────────────────────────────────── +function mp3(scene, file, vol) { + if (scene.sound?.mute) return; + try { + const a = new Audio(`assets/fx/${file}`); + a.volume = Math.max(0, Math.min(1, vol * (scene.sound?.volume ?? 1))); + a.play()?.catch?.(() => {}); + } catch (_) { /* audio is decoration */ } +} +export function pick(scene, i = 0) { mp3(scene, `gem-0${(i % 2) + 1}.mp3`, 0.55); } +export function coins(scene) { mp3(scene, 'coins.mp3', 0.45); } +export function gemChain(scene) { mp3(scene, 'gem-chain.mp3', 0.5); } diff --git a/src/games/splendor/sprite.md b/src/games/splendor/sprite.md index 213e70f..1700bdf 100644 --- a/src/games/splendor/sprite.md +++ b/src/games/splendor/sprite.md @@ -55,8 +55,14 @@ Each noble has unique art. Nobles are displayed at 96 × 96 px (square), so desi ## Display Sizes (for reference) -| Element | Rendered size | -|---------|--------------| -| Development cards | 128 × 176 px | -| Nobles | 96 × 96 px | -| Deck backs | 110 × 176 px | +Since the 2026-11-25 counting-house overhaul the art is baked into framed +textures by `SplendorArt.js` rather than drawn raw: + +| Element | Source crop | Shown at | +|---------|-------------|----------| +| Development cards | 270×371 from the top of the cell (+8px) | 128×176 market, 60×83 ledger stacks, 68×94 reserve, ~270×371 showcase | +| Nobles | 250×250 square from (10, 18) in the cell | 112×112 portrait over a requirement plate; 38×38 ledger cameo | +| Deck backs | 270×371 like the cards | 128×176 | + +Points, the bonus gem and cost chips are painted over the art in the bake, so +keep the top ~25% and the bottom-left corner of card art free of key detail. diff --git a/src/games/splendor/tutorial.md b/src/games/splendor/tutorial.md index bfdbcf6..9d9ac2f 100644 --- a/src/games/splendor/tutorial.md +++ b/src/games/splendor/tutorial.md @@ -104,7 +104,7 @@ Pick any face-up card from the grid (or the top card of any face-down tier deck, You also receive **1 gold token** from the bank (if any remain). -Reserved cards are only visible to you. No one else can buy them while they're in your hand. +No one else can buy a reserved card while it's in your hand. A card you reserve from the face-up grid stays visible to everyone (they all saw you take it); one you take blind from the top of a deck stays face-down to your rivals. This action does two things: - It protects a card you want before someone else grabs it @@ -136,7 +136,7 @@ Cash flow management. I track my petal budget obsessively. You can't just keep a ## Noble Visits -At the end of your turn, after buying or taking tokens, check whether you qualify for any Noble tile. If you do, one Noble automatically joins your tableau and awards you **3 prestige points**. If you qualify for more than one, you take only one (the game picks for you). +At the end of your turn, after buying or taking tokens, check whether you qualify for any Noble tile. If you do, one Noble automatically joins your tableau and awards you **3 prestige points**. If you qualify for more than one, only one visits this turn — you choose which. Once a Noble is claimed, they're gone from the board. @@ -154,6 +154,19 @@ After the round completes: --- +## Reading the Counting House + +A few things the table does to help you out: + +- **Glowing cards** are ones you can buy right now. A **gold** glow means you can only afford it by spending gold (the tag says how much). A thin **silver outline** means you're one gem short. +- The **cost chips** on each card account for your bonuses: a ✓ means your cards already cover that colour, a small badge shows what you still owe, and a red ring marks a colour you're short on. +- **Hover a card** to see exactly what you'd pay and which Noble it brings closer. Click it to Acquire or Reserve, or double-click to buy straight away. Click a deck to reserve its top card blind. +- **Little coloured pawns** on a market card (Rivals' reach) mean that opponent could buy it on their turn. +- Under each Noble, a row of ticks per player shows how close everyone is. +- Keys: **1–5** pick gems (Diamond, Sapphire, Emerald, Ruby, Onyx), **Enter** takes them, **Esc** clears, **Z** undoes your last move until the next merchant starts, **M** opens the menu (pace, hints and other settings). + +--- + ## Juliet's Strategy Notes **Buy Tier 1 cards, even the zero-point ones.** This is the hardest thing to get new players to do. A Tier 1 card that costs 4 red tokens and gives you a permanent green bonus feels like a waste. It is not. It's infrastructure. At Petal & Stem, I spent the first six months of business buying equipment that didn't directly make money — refrigeration, delivery bags, the good scissors. You need the foundation before you can build the thing. diff --git a/src/ui/MenuMusic.js b/src/ui/MenuMusic.js index 34c792f..99b98cb 100644 --- a/src/ui/MenuMusic.js +++ b/src/ui/MenuMusic.js @@ -23,6 +23,10 @@ export function playMenuMusic() { a.play().catch(() => {}); } +export function isMenuMusicPlaying() { + return !!_audio && !_audio.paused; +} + export function stopMenuMusic() { if (_audio) _audio.pause(); } diff --git a/src/ui/TutorialModal.js b/src/ui/TutorialModal.js index 94b2031..e508a63 100644 --- a/src/ui/TutorialModal.js +++ b/src/ui/TutorialModal.js @@ -1,4 +1,4 @@ -import { playMenuMusic, stopMenuMusic } from './MenuMusic.js'; +import { playMenuMusic, stopMenuMusic, isMenuMusicPlaying } from './MenuMusic.js'; // Lightweight markdown-to-HTML renderer for the tutorial subset: // ## / ###, **bold**, *italic*, ---, | tables |, - lists, 1. lists, paragraphs. @@ -152,7 +152,10 @@ export class TutorialModal { this._el = overlay; document.body.appendChild(overlay); document.addEventListener('keydown', this._onKey); - stopMenuMusic(); + // Pause the menu theme only if it is actually playing (tutorials opened + // from inside a game must not start it again on close). + this._resumeMenuMusic = isMenuMusicPlaying(); + if (this._resumeMenuMusic) stopMenuMusic(); // Start video (lazy — created here, not before) video.play().catch(() => {}); @@ -171,7 +174,8 @@ export class TutorialModal { this._el?.remove(); this._el = null; document.removeEventListener('keydown', this._onKey); - playMenuMusic(); + if (this._resumeMenuMusic) playMenuMusic(); + this._resumeMenuMusic = false; // Briefly swallow input so the closing click doesn't fall through to the // button (e.g. on the Phaser canvas) sitting behind the close button. diff --git a/tools/verifySplendor.js b/tools/verifySplendor.js new file mode 100644 index 0000000..723f2f2 --- /dev/null +++ b/tools/verifySplendor.js @@ -0,0 +1,355 @@ +#!/usr/bin/env node +// verifySplendor.js — headless checks for Splendor: +// • rules: takes, take-2 threshold, reserve (gold, limit, blind), buy (bonuses, +// gold, refill, purchased cards), hand limit discard phase, noble visits incl. +// the choice phase, end-of-round finish, ranking tiebreak, helper queries +// • previewBuy / effectiveCost / affordState agree with applyAction +// • all-AI soak (2–4 players, mixed skills): every game ends, tokens and the 90 +// cards are conserved after every step, decision times stay small +// • skill ladder: mirrored seats and seeds, 2 players +// • screen layout: furniture on screen and apart, children inside parents +// • art sheets: PNG header sizes match the frame maps +// Usage: node tools/verifySplendor.js [--quick] + +import fs from 'node:fs'; +import * as L from '../src/games/splendor/SplendorLogic.js'; +import * as AI from '../src/games/splendor/SplendorAI.js'; +import { + GEMS, GOLD, CARDS, NOBLES, tokenSupplyFor, HAND_LIMIT, MAX_RESERVED, LOCATION, NOBLE_INFO, + cardFrame, nobleFrame, deckBackFrame, +} from '../src/games/splendor/SplendorData.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + computeLayout, furniture, onScreen, rectsOverlap, inside, ledgerParts, slotRect, deckRect, MARKET, BANK, bankCell, + BANK_ORDER, GALLERY, DOCK, stackPos, MINI, RES, trackX, TRACK, W, H, +} from '../src/games/splendor/SplendorLayout.js'; +import { cameoPos } from '../src/games/splendor/SplendorHud.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}`); +function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; } + +const ALL = [...GEMS, GOLD]; +const tokensIn = (s) => { + const t = {}; + for (const c of ALL) t[c] = s.bank[c] + s.players.reduce((n, p) => n + p.tokens[c], 0); + return t; +}; +const cardCount = (s) => { + let n = 0; + for (const t of [1, 2, 3]) n += s.decks[t].length + s.board[t].filter(Boolean).length; + for (const p of s.players) n += p.reserved.length + p.cards.length; + return n; +}; +// Put `p` at the current seat with the given tokens/bonuses (direct rule tests). +function rig(s, { tokens = {}, bonuses = {}, seat = s.current } = {}) { + const p = s.players[seat]; + for (const c of ALL) { s.bank[c] += p.tokens[c]; p.tokens[c] = 0; } + for (const [c, n] of Object.entries(tokens)) { p.tokens[c] = n; s.bank[c] -= n; } + for (const [c, n] of Object.entries(bonuses)) p.bonuses[c] = n; + return s; +} +const fresh = (pc = 2, seed = 11) => L.createInitialState({ playerCount: pc, seed }); + +// ── rules ───────────────────────────────────────────────────────────────────────────── +section('Rules'); +{ + ok('90 cards, 40/30/20', CARDS.length === 90 && [1, 2, 3].map((t) => CARDS.filter((c) => c.tier === t).length).join() === '40,30,20'); + ok('15 location names, 10 noble names', LOCATION.length === 15 && NOBLE_INFO.length === 10); + for (const pc of [2, 3, 4]) { + const s = fresh(pc); + ok(`${pc}p: supply`, GEMS.every((g) => s.bank[g] === tokenSupplyFor(pc)[g]) && s.bank.gold === 5); + ok(`${pc}p: ${pc + 1} nobles, 4 cards a row`, s.nobles.length === pc + 1 && [1, 2, 3].every((t) => s.board[t].filter(Boolean).length === 4)); + ok(`${pc}p: 90 cards`, cardCount(s) === 90); + } + // take3 + let s = fresh(); + const s1 = L.applyAction(s, { type: 'take3', colors: ['white', 'blue', 'green'] }); + ok('take3 moves 3 tokens', s1.players[0].tokens.white === 1 && s1.bank.white === s.bank.white - 1 && s1.current === 1); + ok('take3 rejects duplicates in disguise', L.applyAction(s, { type: 'take3', colors: ['red', 'red', 'red'] }).players[0].tokens.red === 1); + // take2 threshold + s = fresh(2); // 4 per colour + ok('take2 legal at 4', L.isLegal(s, { type: 'take2', color: 'red' })); + const s2 = L.applyAction(s, { type: 'take2', color: 'red' }); + ok('take2 takes two', s2.players[0].tokens.red === 2 && s2.bank.red === 2); + s2.current = 0; + ok('take2 illegal below 4', !L.isLegal(s2, { type: 'take2', color: 'red' }) && L.applyAction(s2, { type: 'take2', color: 'red' }) === s2); + // reserve + s = fresh(); + const card = s.board[1][0]; + const r1 = L.applyAction(s, { type: 'reserve', cardId: card.id, tier: 1 }); + ok('reserve takes the card + 1 gold', r1.players[0].reserved[0].id === card.id && r1.players[0].tokens.gold === 1 && r1.bank.gold === 4); + ok('reserve refills the slot', r1.board[1][0] && r1.board[1][0].id !== card.id && r1.decks[1].length === s.decks[1].length - 1); + ok('lastAction names the refill', r1.lastAction.refill?.slot === 0 && r1.lastAction.refill.cardId === r1.board[1][0].id); + const r2 = L.applyAction(r1, { type: 'reserveDeck', tier: 3 }); + ok('blind reserve flagged', r2.players[1].reserved[0].blind === true && r2.decks[3].length === s.decks[3].length - 1); + ok('blind reserve hidden from rivals', L.visibleReserved(r2.players[1], 0)[0].hidden === true && !L.visibleReserved(r2.players[1], 1)[0].hidden); + ok('reserve with no gold left', (() => { const t = fresh(); t.bank.gold = 0; const u = L.applyAction(t, { type: 'reserveDeck', tier: 1 }); return u.players[0].tokens.gold === 0 && u.players[0].reserved.length === 1; })()); + { + const t = fresh(); + t.players[0].reserved = [CARDS[0], CARDS[1], CARDS[2]].map((c) => ({ ...c })); + ok('reserve limit 3', !L.legalActions(t).some((a) => a.type.startsWith('reserve')) && MAX_RESERVED === 3); + } + // buy with bonuses + gold + { + const t = fresh(); + const c = t.board[2][0]; + const cost = c.cost; + const tokens = { gold: 1 }; + const bonuses = {}; + let first = true; + for (const g of GEMS) { + if (!cost[g]) continue; + if (first) { bonuses[g] = 1; tokens[g] = cost[g] - 2; first = false; } // 1 bonus + 1 gold cover 2 + else tokens[g] = cost[g]; + } + for (const g of GEMS) if (tokens[g] < 0) tokens[g] = 0; + rig(t, { tokens, bonuses }); + const pv = L.previewBuy(t, t.players[0], c); + const before = tokensIn(t); + const u = L.applyAction(t, { type: 'buy', cardId: c.id, source: 'board' }); + const p = u.players[0]; + ok('buy: affordable with gold', pv.affordable && L.affordState(t.players[0], c).kind === (pv.gold ? 'gold' : 'now')); + ok('buy: card recorded + bonus + points', p.cards.length === 1 && p.cards[0].id === c.id && p.bonuses[c.bonus] === (bonuses[c.bonus] ?? 0) + 1 && p.points === c.points); + ok('buy: previewBuy matches payment', GEMS.every((g) => u.lastAction.pay[g] === pv.pay[g]) && u.lastAction.gold === pv.gold); + ok('buy: tokens conserved', ALL.every((g) => tokensIn(u)[g] === before[g])); + ok('buy: refill from deck', u.board[2][0] && u.board[2][0].id !== c.id); + ok('buy: stats', p.stats.bought[2] === 1 && p.stats.goldSpent === pv.gold && p.stats.bonusSaved === pv.saved); + } + // buy from reserve + { + const t = fresh(); + const c = CARDS.find((x) => x.tier === 1 && Object.keys(x.cost).length === 1); + t.players[0].reserved = [{ ...c, blind: true }]; + rig(t, { tokens: { ...c.cost } }); + const u = L.applyAction(t, { type: 'buy', cardId: c.id, source: 'reserve' }); + ok('buy from reserve', u.players[0].reserved.length === 0 && u.players[0].cards[0].id === c.id && !('blind' in u.players[0].cards[0])); + } + // unaffordable buy rejected + { + const t = fresh(); + const c = t.board[3][0]; + ok('unaffordable buy rejected', L.applyAction(t, { type: 'buy', cardId: c.id }) === t && L.affordState(t.players[0], c).kind !== 'now'); + } + // effectiveCost + { + const p = { tokens: { white: 1, blue: 0, green: 0, red: 0, black: 0, gold: 0 }, bonuses: { white: 2, blue: 0, green: 0, red: 0, black: 0 } }; + const card = { cost: { white: 3, blue: 2 } }; + const rows = L.effectiveCost(p, card); + ok('effectiveCost covered/owed/short', rows[0].covered === 2 && rows[0].owed === 1 && rows[0].short === 0 && rows[1].short === 2); + ok('affordState near', L.affordState({ ...p, tokens: { ...p.tokens, gold: 1 } }, card).kind === 'near'); + } + // discard phase + { + const t = fresh(); + rig(t, { tokens: { white: 3, blue: 3, green: 3 } }); + const u = L.applyAction(t, { type: 'take3', colors: ['red', 'black', 'white'] }); + ok('over 10 parks in discard', u.phase === 'discard' && u.current === 0); + ok('no actions while parked', L.legalActions(u).length === 0); + const v = L.applyDiscard(u, { white: 1 }); + ok('partial discard stays parked', v.phase === 'discard'); + const w = L.applyDiscard(v, { blue: 1 }); + ok('discard completes the turn', w.phase === 'turn' && w.current === 1 && L.tokenTotal(w.players[0]) === HAND_LIMIT); + ok('gold may be returned', (() => { const a = fresh(); rig(a, { tokens: { gold: 2, white: 3, blue: 3, green: 3 } }); a.phase = 'discard'; const b = L.applyDiscard(a, { gold: 1 }); return b.players[0].tokens.gold === 1 && b.phase === 'turn'; })()); + } + // nobles: single auto visit, choice when two + { + const t = fresh(3); + t.nobles = [NOBLES[0], NOBLES[1], NOBLES[2]]; // wb4, bg4, gr4 + rig(t, { bonuses: { white: 4, blue: 3 } }); + const c = t.board[1].find(Boolean); + t.board[1][0] = { ...c, bonus: 'blue', cost: {} }; + const u = L.applyAction(t, { type: 'buy', cardId: t.board[1][0].id }); + ok('one noble visits automatically', u.players[0].nobles.length === 1 && u.players[0].nobles[0].id === 'n0' && u.lastVisit?.nobleId === 'n0' && u.players[0].points === 3 + c.points * 0 + (t.board[1][0].points)); + const t2 = fresh(3); + t2.nobles = [NOBLES[0], NOBLES[1], NOBLES[2]]; + rig(t2, { bonuses: { white: 4, blue: 3, green: 4 } }); + t2.board[1][0] = { ...t2.board[1][0], bonus: 'blue', cost: {} }; + const v = L.applyAction(t2, { type: 'buy', cardId: t2.board[1][0].id }); + ok('two nobles → choice phase', v.phase === 'noble' && v.pendingNobles.length === 2 && v.current === 0); + const w = L.applyNobleChoice(v, 'n1'); + ok('chosen noble visits, other stays', w.players[0].nobles[0].id === 'n1' && w.nobles.some((n) => n.id === 'n0') && w.current === 1); + ok('illegal noble choice ignored', L.applyNobleChoice(v, 'n2') === v); + ok('AI picks a pending noble', v.pendingNobles.includes(AI.chooseNoble(v))); + } + // end of game: finish the round + { + const t = fresh(3); + t.current = 1; + t.players[1].points = 14; + t.board[1][0] = { ...t.board[1][0], points: 1, cost: {} }; + const u = L.applyAction(t, { type: 'buy', cardId: t.board[1][0].id }); + ok('15 triggers the final round', u.triggeredEnd && u.endTriggeredBy === 1 && u.phase === 'turn' && u.current === 2); + const v = L.applyAction(u, { type: 'take3', colors: ['white', 'blue', 'green'] }); + ok('game ends when the round completes', v.phase === 'gameOver' && v.current === 0); + } + // ranking tiebreak + { + const t = fresh(3); + t.players[0].points = 15; t.players[0].cardsCount = 12; + t.players[1].points = 15; t.players[1].cardsCount = 10; + t.players[2].points = 15; t.players[2].cardsCount = 12; + const r = L.finalRanking(t); + ok('fewest cards wins a tie', r[0].seat === 1 && r[0].wonOnTiebreak && r[0].place === 1); + ok('full tie shares a place', r[1].place === 2 && r[2].place === 2); + } +} + +// ── preview vs reality ─────────────────────────────────────────────────────────────── +section('Preview vs applyAction'); +{ + seedRandom(5); + let checked = 0; + for (let g = 0; g < (QUICK ? 6 : 20); g++) { + let s = L.createInitialState({ playerCount: 2 + (g % 3), seed: 900 + g }); + for (let step = 0; step < 400 && !L.isGameOver(s); step++) { + const p = L.currentPlayer(s); + for (const a of L.legalActions(s).filter((x) => x.type === 'buy')) { + const card = L.cardById(s, a.cardId); + const pv = L.previewBuy(s, p, card); + const u = L.applyAction(s, a); + const q = u.players[p.seat]; + const tok = GEMS.every((c) => q.tokens[c] === p.tokens[c] - pv.pay[c]) && q.tokens.gold === p.tokens.gold - pv.gold; + if (!tok || !pv.affordable) { ok('previewBuy payment', false, `game ${g} step ${step}`); break; } + if (pv.unlocks.length && u.phase !== 'noble' && !u.players[p.seat].nobles.some((n) => pv.unlocks.some((x) => x.id === n.id))) { + ok('previewBuy unlocks', false, `game ${g} step ${step}`); + } + checked++; + } + s = AI.settle(L.applyAction(s, AI.chooseAction(s, 2))); + } + } + ok(`${checked} buy previews matched`, checked > 50); +} + +// ── soak ───────────────────────────────────────────────────────────────────────────── +section('All-AI soak'); +{ + const games = QUICK ? 24 : 120; + let finished = 0, maxTurns = 0, worstMs = 0, totalTurns = 0, conserveFail = 0, passes = 0, nobleChoices = 0, discards = 0, awardsSeen = 0; + const t0 = Date.now(); + for (let g = 0; g < games; g++) { + const rnd = seedRandom(3000 + g); + const pc = 2 + (g % 3); + const skills = Array.from({ length: pc }, (_, i) => 1 + ((g + i * 2) % 5)); + let s = L.createInitialState({ playerCount: pc, seed: 4000 + g }); + const supply = tokensIn(s); + let guard = 0; + while (!L.isGameOver(s) && guard++ < 600) { + const tA = Date.now(); + const a = AI.chooseAction(s, skills[s.current], rnd); + worstMs = Math.max(worstMs, Date.now() - tA); + if (a.type === 'pass') passes++; + let u = L.applyAction(s, a); + if (u === s) { ok('AI chose a legal action', false, JSON.stringify(a)); break; } + if (u.phase === 'discard') discards++; + if (u.phase === 'noble') nobleChoices++; + u = AI.settle(u); + const t = tokensIn(u); + if (!ALL.every((c) => t[c] === supply[c]) || cardCount(u) !== 90 || ALL.some((c) => u.bank[c] < 0) || u.players.some((p) => ALL.some((c) => p.tokens[c] < 0) || L.tokenTotal(p) > HAND_LIMIT)) conserveFail++; + s = u; + } + if (L.isGameOver(s)) { + finished++; + const turns = s.turn / pc; + totalTurns += turns; + maxTurns = Math.max(maxTurns, turns); + const pts = s.players.map((p) => p.points); + ok('someone reached 15', Math.max(...pts) >= 15); + ok('points = cards + nobles', s.players.every((p) => p.points === p.cards.reduce((n, c) => n + c.points, 0) + p.nobles.length * 3)); + ok('pointsByTurn length = turns', s.players.every((p) => p.stats.pointsByTurn.length === p.stats.turns)); + awardsSeen += L.awardsFor(s).length; + } + } + ok(`${finished}/${games} games finished`, finished === games); + ok('tokens + 90 cards conserved, hand limit kept', conserveFail === 0, `${conserveFail} bad steps`); + ok('awards produced', awardsSeen > games); + console.log(` avg ${(totalTurns / Math.max(1, finished)).toFixed(1)} turns/player (max ${maxTurns.toFixed(0)}), worst decision ${worstMs}ms, ${discards} discards, ${nobleChoices} noble choices, ${passes} passes, ${((Date.now() - t0) / 1000).toFixed(1)}s`); + ok('decisions stay under 400ms', worstMs < 400, `${worstMs}ms`); +} + +// ── ladder ─────────────────────────────────────────────────────────────────────────── +section('Skill ladder (2 players, mirrored)'); +{ + const pairs = QUICK ? [[5, 3], [3, 1]] : [[2, 1], [3, 2], [4, 3], [5, 4]]; + const N = QUICK ? 10 : 30; + for (const [a, b] of pairs) { + let wins = 0, games = 0; + for (let g = 0; g < N; g++) { + for (const swap of [false, true]) { + const rnd = seedRandom(7000 + g * 3 + (swap ? 1 : 0)); + let s = L.createInitialState({ playerCount: 2, seed: 8000 + g }); + const seatA = swap ? 1 : 0; + let guard = 0; + while (!L.isGameOver(s) && guard++ < 500) { + s = AI.settle(L.applyAction(s, AI.chooseAction(s, s.current === seatA ? a : b, rnd))); + } + if (L.finalRanking(s)[0].seat === seatA) wins++; + games++; + } + } + const pct = (100 * wins) / games; + console.log(` skill ${a} vs ${b}: ${pct.toFixed(0)}%`); + ok(`skill ${a} beats ${b}`, pct > 50, `${pct.toFixed(0)}%`); + } +} + +// ── layout ─────────────────────────────────────────────────────────────────────────── +section('Layout'); +for (const pc of [2, 3, 4]) { + const F = furniture(pc); + for (const [name, r] of F) ok(`${pc}p ${name} on screen`, onScreen(r), JSON.stringify(r)); + for (let i = 0; i < F.length; i++) for (let j = i + 1; j < F.length; j++) { + ok(`${pc}p ${F[i][0]} / ${F[j][0]} apart`, !rectsOverlap(F[i][1], F[j][1])); + } + for (const Lr of computeLayout(pc).ledgers) { + const P = ledgerParts(Lr); + for (const r of P.reserve) ok(`${pc}p ledger ${Lr.seat} reserve slot inside`, inside(r, Lr)); + for (const g of GEMS) { + const col = P.cols[g]; + const last = stackPos(col, 9, 10); + ok(`${pc}p ledger ${Lr.seat} ${g} stack of 10 inside`, inside({ x: last.x - MINI.w / 2, y: col.stackTop, w: MINI.w, h: last.y + MINI.h / 2 - col.stackTop }, Lr)); + ok(`${pc}p ledger ${Lr.seat} ${g} chip clear of stack`, col.chip.y - 16 > last.y + MINI.h / 2 - 4); + } + ok(`${pc}p ledger ${Lr.seat} columns clear of reserve`, P.cols.black.x + P.cols.black.w < P.reserve[0].x); + for (const n of [4, 5]) { + const last = cameoPos(Lr, n - 1, n); + ok(`${pc}p ledger ${Lr.seat} ${n} cameos inside`, last.y + last.size / 2 <= Lr.y + Lr.h && last.x + last.size / 2 < P.cols.white.x); + } + } +} +for (const t of [1, 2, 3]) { + ok(`deck ${t} inside market`, inside(deckRect(t), MARKET)); + for (let i = 0; i < 4; i++) ok(`slot ${t}/${i} inside market`, inside(slotRect(t, i), MARKET)); +} +for (const c of BANK_ORDER) ok(`case cell ${c} inside`, inside(bankCell(c), BANK)); +for (let i = 0; i < 5; i++) { + const x = GALLERY.x + 14 + i * 148; + ok(`noble slot ${i} inside gallery`, x + 112 <= GALLERY.x + GALLERY.w); +} +ok('register spans 0..15', trackX(0) > TRACK.x && trackX(15) + 60 < TRACK.x + TRACK.w); +ok('dock on screen', onScreen(DOCK) && DOCK.y + DOCK.h <= H && DOCK.x + DOCK.w <= W); +ok('reserve card size sane', RES.w > MINI.w); + +// ── art sheets ─────────────────────────────────────────────────────────────────────── +section('Art sheets'); +function pngSize(path) { + const b = fs.readFileSync(path); + return { w: b.readUInt32BE(16), h: b.readUInt32BE(20) }; +} +{ + const cards = pngSize('assets/images/splendor-cards.png'); + const cols = Math.floor(cards.w / 270), rows = Math.floor(cards.h / 390); + const maxFrame = Math.max(...CARDS.map(cardFrame), ...NOBLES.map(nobleFrame), deckBackFrame(3)); + ok(`splendor-cards ${cards.w}×${cards.h} holds frame ${maxFrame}`, cols * rows > maxFrame && cols === 8, `${cols}×${rows}`); + const gems = pngSize('assets/images/splendor-gems.png'); + ok(`splendor-gems ${gems.w}×${gems.h} = 6 frames`, gems.w / 64 >= 6 && gems.h === 64); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);