Redesign Splendor as "The Counting House" with full art, AI planner, and HUD

- Replace the flat UI with a procedural counting-house scene: baked room, baize market, velvet jewel case, tooled-leather ledgers, gilt patron gallery, and Guild Register prestige track (SplendorArt, SplendorLayout, SplendorHud)
- Add three-tier buy highlighting (blaze/gold/near), cost-chip annotations showing what bonuses cover, rivals' reach pawns, hover previews with place names, and gem-flight animations (SplendorFx)
- Rewrite the AI from a 1-ply greedy into a full planner: evaluate prestige, engine demand, targets discounted by turns-to-afford, noble contention, denial, end-race awareness, and skill-gated follow-up lookahead; sensible blunders only for low skills (SplendorAI)
- Extend the rules engine: blind deck reserves hidden from rivals, per-seat stats and awards, explicit noble-choice phase when multiple qualify, effectiveCost/affordState/previewBuy helpers, and shared-place ranking (SplendorLogic)
- Add dialogs (pause/settings, confirm, hand-back tokens, noble choice), a Guild Ledger end screen with charts and honours, and synthesized Web Audio SFX (SplendorDialogs, SplendorEndScreen, SplendorSound)
- Add headless verifier covering rules, preview-vs-reality, AI soak/conservation, skill ladder, layout bounds, and art-sheet sizes (tools/verifySplendor.js)
- Fix TutorialModal to only resume menu music if it was actually playing when the modal opened
This commit is contained in:
Brian Fertig 2026-11-25 19:18:47 -07:00
parent d1906f6b94
commit e74449ffa1
No known key found for this signature in database
16 changed files with 4009 additions and 1590 deletions

View File

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

View File

@ -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-<t> brass row plaque ("The Mines" …)
// spl-case the jewel case (bank): walnut box, velvet wells
// spl-ledger-<w>x<h> tooled-leather merchant's ledger for a seat
// spl-dock the merchant's slate (prompt + gem tray)
// spl-card-<id> card faces: the user's painting in a metal frame with
// points, bonus gem and cost chips (256×352, shown at ½)
// spl-back-<t> deck backs (the user's merchant art, framed)
// spl-noble-<id> a patron: portrait in a gilt frame over a req plate
// spl-chip-<colour> 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.
}

View File

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

View File

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

View File

@ -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 */ } }); } };
}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

@ -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.

View File

@ -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.

View File

@ -23,6 +23,10 @@ export function playMenuMusic() {
a.play().catch(() => {});
}
export function isMenuMusicPlaying() {
return !!_audio && !_audio.paused;
}
export function stopMenuMusic() {
if (_audio) _audio.pause();
}

View File

@ -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.

355
tools/verifySplendor.js Normal file
View File

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