diff --git a/src/games/dominion/DominionAI.js b/src/games/dominion/DominionAI.js index 080c5d5..018d41f 100644 --- a/src/games/dominion/DominionAI.js +++ b/src/games/dominion/DominionAI.js @@ -10,7 +10,7 @@ import { } from './DominionCards.js'; import { legalActionIids, allCards, handCoinValue, - affordableSupply, canGain, cardCost, + affordableSupply, canGain, cardCost, buyAllowed, } from './DominionLogic.js'; import { getExpansion } from './expansions/index.js'; @@ -111,6 +111,9 @@ export function chooseBuy(state, seat, skill = 3) { if (cardCost(state, id, { seat, phase: 'buy' }) > coins) continue; if ((state.supply[id] ?? 0) <= 0) continue; if (countOwned(state, seat, id) >= cap) continue; + // Respect buy restrictions (Grand Market can't be bought with Copper in + // play) — buyCard rejects them, and re-picking one stalled the AI's turn. + if (!buyAllowed(state, id)) continue; return id; } } diff --git a/src/games/dominion/DominionArt.js b/src/games/dominion/DominionArt.js new file mode 100644 index 0000000..5bdc1d1 --- /dev/null +++ b/src/games/dominion/DominionArt.js @@ -0,0 +1,1037 @@ +// Dominion — "Steward's Hall" procedural art. +// +// Everything is painted on canvases and registered as Phaser textures, baked +// once per page load (keys are stable, so scene restarts reuse them): +// +// dom-table oak plank tabletop (opaque, full screen) +// dom-light lamp pool + vignette (transparent overlay) +// dom-furn- treasury tray, baize runner, clock + trash mats, play +// mat, steward's tray, seat plaques, deck/discard spots +// dom-c-- card faces: the user's painted art in a type-coloured +// frame (L = 270×390 with rules text, M = 150×216 @1.5×) +// dom-tile-- landscape treasury tiles for the basic piles +// dom-back- card back (the player's chosen back, rounded) +// dom-banner- heraldic pennant in the seat colour +// dom-shadow, dom-glow, dom-seal, dom-plaque, dom-flame, dom-tok-action, +// dom-tok-buy, dom-coin, dom-purse, dom-parch-x, dom-ribbon- +// +// The card frame is an original design (parchment title plate, inset art +// window, parchment text panel, type bar) — the painted art is the user's. + +import { canvas, rr, poly, mix, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { getCard } from './DominionCards.js'; +import { + W, H, TREASURY, MAT, TRAY, TRAY_WELLS, DOCK, HUMAN_PLATE, DECK, DISCARD, HAND, + SEAT_HEX, SEAT_CHARGES, rectW, rectH, +} from './DominionLayout.js'; + +export const SERIF = 'Georgia, "Times New Roman", serif'; +export const PHASER_SERIF = 'Georgia, "Times New Roman", serif'; + +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); +} + +// Wavy wood grain over a rect (caller clips). +function grain(ctx, x, y, w, h, { dark = 'rgba(40,22,8,0.18)', light = 'rgba(255,220,170,0.06)', spacing = 7, amp = 2.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.7 ? 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 woodRect(ctx, x, y, w, h, r, top, bottom, seed = 1, spacing = 6) { + ctx.save(); + rr(ctx, x, y, w, h, r); + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, top); g.addColorStop(1, bottom); + ctx.fillStyle = g; + ctx.fill(); + ctx.clip(); + grain(ctx, x, y, w, h, { seed, spacing }); + ctx.fillStyle = noisePattern(ctx, 64, 18); + ctx.fillRect(x, y, w, h); + ctx.restore(); +} + +function dropShadow(ctx, fn, { blur = 18, dy = 6, alpha = 0.55 } = {}) { + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; + ctx.shadowOffsetY = dy; + fn(); + ctx.restore(); +} + +function brassStroke(ctx, x, y, w, h, r, width = 3) { + ctx.save(); + rr(ctx, x, y, w, h, r); + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, '#f1d58a'); g.addColorStop(0.45, '#b8913f'); g.addColorStop(1, '#6e5220'); + ctx.strokeStyle = g; + ctx.lineWidth = width; + ctx.stroke(); + ctx.restore(); +} + +function engraved(ctx, text, x, y, size, { color = 'rgba(236,214,160,0.75)', align = 'center', font = SERIF, weight = 'bold', spacing = 0 } = {}) { + ctx.save(); + ctx.font = `${weight} ${size}px ${font}`; + ctx.textAlign = align; + ctx.textBaseline = 'middle'; + if (spacing) ctx.letterSpacing = `${spacing}px`; + ctx.fillStyle = 'rgba(0,0,0,0.55)'; + ctx.fillText(text, x, y + 1.5); + ctx.fillStyle = color; + ctx.fillText(text, x, y); + ctx.restore(); +} + +// ── Table + light ─────────────────────────────────────────────────────────── +function bakeTable(scene) { + const key = 'dom-table'; + if (scene.textures.exists(key)) return key; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + const PH = 120; + const tones = ['#4a2e18', '#52331b', '#472c16', '#55361d', '#4c2f19', '#4e301a', '#583a20', '#4b2e18', '#51321b']; + for (let i = 0, y = -18; y < H; i++, y += PH) { + ctx.beginPath(); ctx.rect(0, y, W, 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], '#1c0f06', 0.3)); + ctx.fillStyle = g; ctx.fill(); + ctx.save(); ctx.clip(); + grain(ctx, 0, y, W, PH, { seed: i + 11, spacing: 6 }); + ctx.restore(); + ctx.fillStyle = 'rgba(12,6,2,0.6)'; ctx.fillRect(0, y, W, 2); + ctx.fillStyle = 'rgba(255,214,160,0.05)'; ctx.fillRect(0, y + 2, W, 1); + const off = (i * 613) % 820; + for (let x = off; x < W; x += 1040) { + ctx.fillStyle = 'rgba(12,6,2,0.5)'; ctx.fillRect(x, y, 2, PH); + // iron nails at the butt joint + for (const ny of [y + 18, y + PH - 18]) { + ctx.fillStyle = '#1d1712'; ctx.beginPath(); ctx.arc(x - 8, ny, 3, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(255,230,190,0.18)'; ctx.beginPath(); ctx.arc(x - 9, ny - 1, 1.2, 0, Math.PI * 2); ctx.fill(); + } + } + } + ctx.fillStyle = noisePattern(ctx, 96, 16); + ctx.fillRect(0, 0, W, H); + return addCanvas(scene, key, c); +} + +function bakeLight(scene) { + const key = 'dom-light'; + if (scene.textures.exists(key)) return key; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + // two candle pools: over the market and over the player's side + const pool = (x, y, r0, r1, a) => { + const g = ctx.createRadialGradient(x, y, r0, x, y, r1); + g.addColorStop(0, `rgba(255,206,130,${a})`); + g.addColorStop(0.5, `rgba(255,190,110,${a * 0.35})`); + g.addColorStop(1, 'rgba(255,190,110,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); + }; + pool(860, 300, 30, 900, 0.2); + pool(900, 860, 30, 700, 0.12); + const vg = ctx.createRadialGradient(900, 520, 520, 900, 520, 1300); + vg.addColorStop(0, 'rgba(0,0,0,0)'); + vg.addColorStop(1, 'rgba(0,0,0,0.62)'); + ctx.fillStyle = vg; ctx.fillRect(0, 0, W, H); + return addCanvas(scene, key, c); +} + +// ── Furniture ─────────────────────────────────────────────────────────────── +function leather(ctx, x, y, w, h, r, base = '#5a2418') { + dropShadow(ctx, () => { rr(ctx, x, y, w, h, r); ctx.fillStyle = base; ctx.fill(); }, { blur: 22, dy: 8, alpha: 0.6 }); + ctx.save(); + rr(ctx, x, y, w, h, r); + const g = ctx.createLinearGradient(x, y, x + w * 0.3, y + h); + g.addColorStop(0, mix(base, '#ffffff', 0.08)); g.addColorStop(1, mix(base, '#000000', 0.35)); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 48, 34); ctx.fillRect(x, y, w, h); + ctx.restore(); + // stitching + ctx.save(); + ctx.setLineDash([7, 5]); + ctx.lineWidth = 1.6; + ctx.strokeStyle = 'rgba(232,200,140,0.55)'; + rr(ctx, x + 9, y + 9, w - 18, h - 18, Math.max(2, r - 6)); ctx.stroke(); + ctx.restore(); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(0,0,0,0.6)'; + rr(ctx, x, y, w, h, r); ctx.stroke(); +} + +function baize(ctx, x, y, w, h, r, base = '#1f4a2f') { + dropShadow(ctx, () => { rr(ctx, x, y, w, h, r); ctx.fillStyle = base; ctx.fill(); }, { blur: 24, dy: 8, alpha: 0.55 }); + ctx.save(); + rr(ctx, x, y, w, h, r); + const g = ctx.createRadialGradient(x + w / 2, y + h * 0.4, 20, x + w / 2, y + h / 2, Math.max(w, h) * 0.7); + g.addColorStop(0, mix(base, '#ffffff', 0.07)); g.addColorStop(1, mix(base, '#000000', 0.35)); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 30); ctx.fillRect(x, y, w, h); + // inner shadow + ctx.lineWidth = 16; ctx.strokeStyle = 'rgba(0,0,0,0.22)'; + rr(ctx, x, y, w, h, r); ctx.stroke(); + ctx.restore(); + brassStroke(ctx, x + 6, y + 6, w - 12, h - 12, Math.max(2, r - 4), 2); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(0,0,0,0.6)'; + rr(ctx, x, y, w, h, r); ctx.stroke(); +} + +function plaque(ctx, x, y, w, h, r = 14, seed = 7) { + dropShadow(ctx, () => { rr(ctx, x, y, w, h, r); ctx.fillStyle = '#2b1709'; ctx.fill(); }, { blur: 20, dy: 7, alpha: 0.6 }); + woodRect(ctx, x, y, w, h, r, '#3d2312', '#1f1108', seed, 5); + brassStroke(ctx, x + 3, y + 3, w - 6, h - 6, r - 2, 2.5); + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(0,0,0,0.7)'; + rr(ctx, x, y, w, h, r); ctx.stroke(); + // brass corner studs + for (const [cx, cy] of [[x + 12, y + 12], [x + w - 12, y + 12], [x + 12, y + h - 12], [x + w - 12, y + h - 12]]) { + const g = ctx.createRadialGradient(cx - 1, cy - 1, 0.5, cx, cy, 4); + g.addColorStop(0, '#fff0c0'); g.addColorStop(1, '#7a5a22'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, 3.6, 0, Math.PI * 2); ctx.fill(); + } +} + +function chalkSpot(ctx, cx, cy, w, h, label) { + ctx.save(); + ctx.setLineDash([10, 7]); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(240,220,180,0.22)'; + rr(ctx, cx - w / 2, cy - h / 2, w, h, 12); ctx.stroke(); + ctx.restore(); + engraved(ctx, label, cx, cy, 20, { color: 'rgba(240,220,180,0.28)', weight: 'normal' }); +} + +function bakeFurniture(scene, L) { + const sig = `${L.playerCount}-${L.tiles.length}-${L.kingdom.length}-${L.tileSize.h}`; + const key = `dom-furn-${sig}`; + if (scene.textures.exists(key)) return key; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + + // Treasury tray (leather) with engraved title. + const T = TREASURY; + leather(ctx, T.x0, T.y0, rectW(T), rectH(T), 18, '#5b2617'); + engraved(ctx, 'TREASURY', (T.x0 + T.x1) / 2, T.y0 + 24, 17, { spacing: 4 }); + // tile wells + for (const t of L.tiles) { + ctx.save(); + rr(ctx, t.x - t.w / 2 - 5, t.y - t.h / 2 - 5, t.w + 10, t.h + 28, 10); + ctx.fillStyle = 'rgba(0,0,0,0.26)'; ctx.fill(); + ctx.restore(); + } + + // Kingdom runner (baize). + const R = L.runner; + baize(ctx, R.x0, R.y0, rectW(R), rectH(R), 20, '#1d4a30'); + + // Game-end clock panel and Trash. + const C = L.clock; + plaque(ctx, C.x0, C.y0, rectW(C), rectH(C), 16, 21); + engraved(ctx, 'THE RECKONING', (C.x0 + C.x1) / 2, C.y0 + 22, 13, { spacing: 2 }); + const Tr = L.trash; + plaque(ctx, Tr.x0, Tr.y0, rectW(Tr), rectH(Tr), 16, 23); + engraved(ctx, 'TRASH', (Tr.x0 + Tr.x1) / 2, Tr.y0 + 24, 16, { spacing: 4 }); + // iron ash pan under the trash card + { + const tc = L.trashCard; + const x = tc.x - tc.w / 2 - 12, y = tc.y - tc.h / 2 - 12, w = tc.w + 24, h = tc.h + 24; + ctx.save(); + rr(ctx, x, y, w, h, 14); + const g = ctx.createRadialGradient(tc.x, tc.y, 10, tc.x, tc.y, w); + g.addColorStop(0, '#2c2620'); g.addColorStop(1, '#0d0b09'); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + // ember glow + grate bars + const e = ctx.createRadialGradient(tc.x, tc.y + tc.h * 0.3, 4, tc.x, tc.y + tc.h * 0.3, w * 0.7); + e.addColorStop(0, 'rgba(255,120,40,0.22)'); e.addColorStop(1, 'rgba(255,120,40,0)'); + ctx.fillStyle = e; ctx.fillRect(x, y, w, h); + ctx.strokeStyle = 'rgba(90,80,70,0.55)'; ctx.lineWidth = 3; + for (let gx = x + 14; gx < x + w; gx += 16) { ctx.beginPath(); ctx.moveTo(gx, y); ctx.lineTo(gx, y + h); ctx.stroke(); } + ctx.restore(); + ctx.lineWidth = 3; ctx.strokeStyle = '#4a423a'; rr(ctx, x, y, w, h, 14); ctx.stroke(); + } + + // Play mat (deep felt with a woven border). + baize(ctx, MAT.x0, MAT.y0, rectW(MAT), rectH(MAT), 22, '#22333f'); + ctx.save(); + ctx.setLineDash([3, 4]); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(214,190,130,0.28)'; + rr(ctx, MAT.x0 + 16, MAT.y0 + 16, rectW(MAT) - 32, rectH(MAT) - 32, 14); ctx.stroke(); + ctx.restore(); + + // Steward's tray (wood with recessed wells). + plaque(ctx, TRAY.x0, TRAY.y0, rectW(TRAY), rectH(TRAY), 14, 31); + for (const [name, r] of Object.entries(TRAY_WELLS)) { + ctx.save(); + rr(ctx, r.x0, r.y0, rectW(r), rectH(r), 10); + const g = ctx.createLinearGradient(0, r.y0, 0, r.y1); + g.addColorStop(0, '#120a05'); g.addColorStop(1, '#2a180b'); + ctx.fillStyle = g; ctx.fill(); + ctx.restore(); + ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(255,220,160,0.18)'; + rr(ctx, r.x0, r.y0 + 1, rectW(r), rectH(r), 10); ctx.stroke(); + engraved(ctx, name.toUpperCase(), r.x0 + 10, r.y0 + 11, 10, { align: 'left', spacing: 2, color: 'rgba(236,214,160,0.55)' }); + } + // Button dock (dark leather strip). + leather(ctx, DOCK.x0, DOCK.y0, rectW(DOCK), rectH(DOCK), 14, '#2d1d14'); + + // Seat plaques. + plaque(ctx, HUMAN_PLATE.x0, HUMAN_PLATE.y0, rectW(HUMAN_PLATE), rectH(HUMAN_PLATE), 16, 41); + L.plates.forEach((p, i) => plaque(ctx, p.rect.x0, p.rect.y0, rectW(p.rect), rectH(p.rect), 16, 50 + i)); + + // Deck + discard spots. + chalkSpot(ctx, DECK.x, DECK.y, HAND.w + 10, HAND.h + 10, 'Deck'); + chalkSpot(ctx, DISCARD.x, DISCARD.y, HAND.w + 10, HAND.h + 10, 'Discard'); + + return addCanvas(scene, key, c); +} + +// ── Card faces ────────────────────────────────────────────────────────────── +const TYPE_PAL = { + action: { a: '#eadbb2', b: '#bf9f66', edge: '#4f3a1c', ink: '#3b2a14' }, + treasure: { a: '#f2d276', b: '#b98a2c', edge: '#5a3f0e', ink: '#3d2a08' }, + victory: { a: '#a7cf93', b: '#4e8a49', edge: '#1c3a1b', ink: '#173016' }, + reaction: { a: '#b3cfeb', b: '#5b8bbf', edge: '#1d3858', ink: '#14263c' }, + curse: { a: '#cdb0e2', b: '#7a4e9b', edge: '#331f48', ink: '#2a183b' }, + duration: { a: '#f4c08a', b: '#c8763a', edge: '#5a2e10', ink: '#3e1f0a' }, +}; +const ATTACK_TRIM = '#a3322a'; + +// Which palette(s) a card's frame uses: reaction wins; otherwise split frames +// for multi-type cards (Treasure–Victory, Action–Victory …). +export function framePalettes(types) { + if (types.includes('curse')) return [TYPE_PAL.curse]; + if (types.includes('reaction')) return [TYPE_PAL.reaction]; + if (types.includes('duration')) return [TYPE_PAL.duration]; + const keys = ['action', 'treasure', 'victory'].filter((t) => types.includes(t)); + if (keys.length === 0) return [TYPE_PAL.action]; + return keys.map((k) => TYPE_PAL[k]); +} + +export function typeLine(def) { + return def.types.map((t) => t.charAt(0).toUpperCase() + t.slice(1)).join(' – '); +} + +const COIN_TINT = { copper: ['#e9a26a', '#9a4f1f'], silver: ['#f2f4f6', '#8e959e'], gold: ['#fbe08a', '#b0811c'], platinum: ['#ffffff', '#a8b0c4'] }; + +// Measured painted-art height in each 270×390 sheet cell. +const ART_H = { 'dominion-cards': 247, 'dominion-prosperity': 269 }; + +function frameOf(scene, sheet, frame) { + if (!scene.textures.exists(sheet)) return null; + const tex = scene.textures.get(sheet); + const fr = tex.has(String(frame)) || tex.has(frame) ? tex.get(frame) : null; + if (!fr) return null; + return { img: tex.getSourceImage(), sx: fr.cutX, sy: fr.cutY, sw: fr.cutWidth, sh: fr.cutHeight }; +} + +// Draw the card's art cover-fitted into (x, y, w, h), biased toward the top. +function drawArt(ctx, scene, def, x, y, w, h, bias = 0.45) { + const f = frameOf(scene, def.sheet ?? 'dominion-cards', def.frame); + if (!f) { + const pal = framePalettes(def.types)[0]; + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, mix(pal.b, '#000000', 0.15)); g.addColorStop(1, mix(pal.b, '#000000', 0.5)); + ctx.fillStyle = g; ctx.fillRect(x, y, w, h); + ctx.fillStyle = 'rgba(255,240,210,0.55)'; + ctx.font = `bold ${Math.round(h * 0.16)}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(def.name, x + w / 2, y + h / 2); + return false; + } + const artH = Math.min(f.sh, ART_H[def.sheet] ?? Math.round(f.sh * 0.63)); + const srcAspect = f.sw / artH, dstAspect = w / h; + let sw = f.sw, sh = artH, sx = f.sx, sy = f.sy; + if (srcAspect > dstAspect) { sw = artH * dstAspect; sx += (f.sw - sw) / 2; } + else { sh = f.sw / dstAspect; sy += (artH - sh) * bias; } + ctx.drawImage(f.img, sx, sy, sw, sh, x, y, w, h); + return true; +} + +function wrapLines(ctx, text, maxW) { + const words = text.split(/\s+/).filter(Boolean); + const lines = []; + let line = ''; + for (const w of words) { + const t = line ? `${line} ${w}` : w; + if (ctx.measureText(t).width <= maxW || !line) line = t; + else { lines.push(line); line = w; } + } + if (line) lines.push(line); + return lines; +} + +// Fit `text` into a box, shrinking from sizes[0]; truncates with … if needed. +function fitText(ctx, text, maxW, maxH, sizes, weight = 'normal', lh = 1.18) { + for (const s of sizes) { + ctx.font = `${weight} ${s}px ${SERIF}`; + const lines = wrapLines(ctx, text, maxW); + if (lines.length * s * lh <= maxH) return { lines, size: s }; + } + const s = sizes[sizes.length - 1]; + ctx.font = `${weight} ${s}px ${SERIF}`; + const lines = wrapLines(ctx, text, maxW); + const max = Math.max(1, Math.floor(maxH / (s * lh))); + const out = lines.slice(0, max); + if (lines.length > max) out[max - 1] = `${out[max - 1].replace(/[,.;]?\s*\S*$/, '')}…`; + return { lines: out, size: s }; +} + +function drawLines(ctx, lines, cx, y0, size, color, weight = 'normal', lh = 1.18) { + ctx.font = `${weight} ${size}px ${SERIF}`; + ctx.fillStyle = color; + ctx.textAlign = 'center'; + ctx.textBaseline = 'top'; + lines.forEach((l, i) => ctx.fillText(l, cx, y0 + i * size * lh)); +} + +// Bonus lines from the vanilla `plus` block. +function bonusParts(def) { + const p = def.plus ?? {}; + const out = []; + if (p.cards) out.push(`+${p.cards} Card${p.cards > 1 ? 's' : ''}`); + if (p.actions) out.push(`+${p.actions} Action${p.actions > 1 ? 's' : ''}`); + if (p.buys) out.push(`+${p.buys} Buy${p.buys > 1 ? 's' : ''}`); + if (p.coins) out.push(`+$${p.coins}`); + return out; +} + +// Rules text with the vanilla bonus prefix removed (the bonus lines show it). +export function rulesRemainder(def) { + let t = (def.text ?? '').trim(); + if (/^Worth [\w-]+ (Coins?|Victory Points?)\.?$/i.test(t)) return ''; + t = t.replace(/^(\s*\+\d+\s+(Cards?|Actions?|Buys?|Coins?)\s*[,.]?\s*)+/i, '').trim(); + return t; +} + +function coin(ctx, x, y, r, label, tint = ['#fbe08a', '#b0811c'], ink = '#3a2606') { + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = r * 0.4; ctx.shadowOffsetY = r * 0.12; + const g = ctx.createRadialGradient(x - r * 0.35, y - r * 0.4, r * 0.1, x, y, r); + g.addColorStop(0, tint[0]); g.addColorStop(1, tint[1]); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + ctx.lineWidth = Math.max(1, r * 0.09); ctx.strokeStyle = mix(tint[1], '#000000', 0.35); + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = Math.max(0.8, r * 0.05); ctx.strokeStyle = 'rgba(255,255,255,0.4)'; + ctx.beginPath(); ctx.arc(x, y, r * 0.78, 0, Math.PI * 2); ctx.stroke(); + ctx.fillStyle = ink; + ctx.font = `bold ${Math.round(r * 1.15)}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(label, x, y + r * 0.06); +} + +function shield(ctx, x, y, r, label, fill = '#3f7f3c', ink = '#fff6dc') { + ctx.save(); + ctx.beginPath(); + ctx.moveTo(x - r, y - r * 0.9); + ctx.lineTo(x + r, y - r * 0.9); + ctx.lineTo(x + r, y + r * 0.1); + ctx.quadraticCurveTo(x + r * 0.9, y + r * 0.8, x, y + r * 1.15); + ctx.quadraticCurveTo(x - r * 0.9, y + r * 0.8, x - r, y + r * 0.1); + ctx.closePath(); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = r * 0.4; ctx.shadowOffsetY = r * 0.12; + const g = ctx.createLinearGradient(x, y - r, x, y + r); + g.addColorStop(0, mix(fill, '#ffffff', 0.25)); g.addColorStop(1, mix(fill, '#000000', 0.3)); + ctx.fillStyle = g; ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.lineWidth = Math.max(1, r * 0.1); ctx.strokeStyle = '#e2c46e'; ctx.stroke(); + ctx.restore(); + ctx.fillStyle = ink; + ctx.font = `bold ${Math.round(r * (label.length > 2 ? 0.8 : 1.05))}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(label, x, y + r * 0.02); +} + +function framePath(ctx, w, h, r) { rr(ctx, 0, 0, w, h, r); } + +function paintFrame(ctx, def, w, h, r) { + const pals = framePalettes(def.types); + ctx.save(); + framePath(ctx, w, h, r); + ctx.clip(); + if (pals.length === 1) { + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, pals[0].a); g.addColorStop(1, pals[0].b); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + } else { + pals.forEach((p, i) => { + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, p.a); g.addColorStop(1, p.b); + ctx.fillStyle = g; + ctx.beginPath(); + const x0 = (w / pals.length) * i, x1 = (w / pals.length) * (i + 1); + const sk = w * 0.08; + ctx.moveTo(i === 0 ? 0 : x0 + sk, 0); + ctx.lineTo(i === pals.length - 1 ? w : x1 + sk, 0); + ctx.lineTo(i === pals.length - 1 ? w : x1 - sk, h); + ctx.lineTo(i === 0 ? 0 : x0 - sk, h); + ctx.closePath(); ctx.fill(); + }); + } + ctx.fillStyle = noisePattern(ctx, 48, 20); ctx.fillRect(0, 0, w, h); + ctx.restore(); + const pal = pals[0]; + ctx.lineWidth = Math.max(1.5, w * 0.008); ctx.strokeStyle = pal.edge; + framePath(ctx, w, h, r); ctx.stroke(); + ctx.lineWidth = Math.max(1, w * 0.005); ctx.strokeStyle = 'rgba(255,255,255,0.35)'; + rr(ctx, w * 0.018, w * 0.018, w - w * 0.036, h - w * 0.036, r * 0.8); ctx.stroke(); + if (def.types.includes('attack')) { + ctx.lineWidth = Math.max(1.5, w * 0.011); ctx.strokeStyle = ATTACK_TRIM; + rr(ctx, w * 0.03, w * 0.03, w - w * 0.06, h - w * 0.06, r * 0.7); ctx.stroke(); + } + return pal; +} + +function parchmentBox(ctx, x, y, w, h, r, light = false) { + ctx.save(); + rr(ctx, x, y, w, h, r); + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, light ? '#fbf3df' : '#f4e6c3'); g.addColorStop(1, light ? '#eedfba' : '#dfc893'); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 48, 16); ctx.fillRect(x, y, w, h); + ctx.restore(); + ctx.lineWidth = Math.max(1, w * 0.006); ctx.strokeStyle = 'rgba(70,48,20,0.6)'; + rr(ctx, x, y, w, h, r); ctx.stroke(); +} + +function artWindow(ctx, scene, def, x, y, w, h) { + ctx.save(); + ctx.fillStyle = '#120c06'; ctx.fillRect(x - 2, y - 2, w + 4, h + 4); + ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); + drawArt(ctx, scene, def, x, y, w, h); + // inner bevel shadow + const g = ctx.createLinearGradient(0, y, 0, y + 14); + g.addColorStop(0, 'rgba(0,0,0,0.45)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; ctx.fillRect(x, y, w, 14); + ctx.restore(); + ctx.lineWidth = 1.5; ctx.strokeStyle = 'rgba(30,20,8,0.9)'; ctx.strokeRect(x - 1, y - 1, w + 2, h + 2); + ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(255,240,200,0.35)'; ctx.strokeRect(x - 3, y - 3, w + 6, h + 6); +} + +function titlePlate(ctx, def, x, y, w, h, maxSize, pal) { + parchmentBox(ctx, x, y, w, h, h * 0.3); + let s = maxSize; + ctx.font = `bold ${s}px ${SERIF}`; + while (ctx.measureText(def.name).width > w - h * 0.6 && s > 8) { s -= 1; ctx.font = `bold ${s}px ${SERIF}`; } + ctx.fillStyle = pal.ink; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(def.name, x + w / 2, y + h / 2 + 1); +} + +function valueInPanel(ctx, def, cx, cy, r) { + if (def.coin !== undefined && def.types.includes('treasure')) { + coin(ctx, cx, cy, r, `${def.coin}`, COIN_TINT[def.id] ?? COIN_TINT.gold); + return true; + } + if (def.types.includes('curse')) { shield(ctx, cx, cy, r * 0.9, `${def.vp ?? -1}`, '#6a3d8f'); return true; } + if (def.types.includes('victory') && def.vp !== undefined) { shield(ctx, cx, cy, r * 0.9, `${def.vp}`); return true; } + return false; +} + +// L = 270×390 (hover / showcase / prompt modals): full rules text. +function paintLarge(ctx, scene, def) { + const w = 270, h = 390; + const pal = paintFrame(ctx, def, w, h, 16); + titlePlate(ctx, def, 14, 12, w - 28, 36, 22, pal); + artWindow(ctx, scene, def, 16, 56, w - 32, 186); + parchmentBox(ctx, 14, 250, w - 28, 102, 8, true); + // panel content + const bonus = bonusParts(def); + const rest = rulesRemainder(def); + const cx = w / 2; + let y = 258; + const isValueCard = (def.types.includes('treasure') && def.coin !== undefined) || def.types.includes('victory') || def.types.includes('curse'); + if (isValueCard && !rest) { + valueInPanel(ctx, def, cx, 300, 30); + } else { + if (isValueCard && valueInPanel(ctx, def, 40, 276, 16)) { /* small value badge */ } + if (bonus.length) { + const rows = bonus.length <= 2 ? bonus : [bonus.slice(0, 2).join(' '), bonus.slice(2).join(' ')]; + const bs = rest ? 16 : 20; + drawLines(ctx, rows, cx, y + (rest ? 0 : 18), bs, pal.ink, 'bold', 1.15); + y += rows.length * bs * 1.15 + 4; + if (rest) { + ctx.strokeStyle = 'rgba(70,48,20,0.35)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(60, y); ctx.lineTo(w - 60, y); ctx.stroke(); + y += 4; + } + } + if (rest) { + const maxH = 346 - y; + const fit = fitText(ctx, rest, w - 46, maxH, [15, 14, 13, 12, 11, 10, 9]); + const blockH = fit.lines.length * fit.size * 1.18; + drawLines(ctx, fit.lines, cx, y + Math.max(0, (maxH - blockH) / 2), fit.size, '#2a1d0c'); + } + } + // type bar + ctx.font = `bold 13px ${SERIF}`; + ctx.fillStyle = pal.ink; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(typeLine(def), cx, 370); + coin(ctx, 34, 370, 15, `${def.cost}`); + if (def.types.includes('victory') && def.vp !== undefined) shield(ctx, w - 34, 368, 13, `${def.vp}`); +} + +// M = 150×216 design units (baked at 1.5×): hand, kingdom piles, play mat. +function paintMedium(ctx, scene, def) { + const w = 150, h = 216; + const pal = paintFrame(ctx, def, w, h, 10); + titlePlate(ctx, def, 7, 6, w - 14, 23, 14, pal); + artWindow(ctx, scene, def, 9, 34, w - 18, 92); + parchmentBox(ctx, 7, 131, w - 14, 63, 6, true); + const bonus = bonusParts(def); + const rest = rulesRemainder(def); + const cx = w / 2; + const isValueCard = (def.types.includes('treasure') && def.coin !== undefined) || def.types.includes('victory') || def.types.includes('curse'); + if (isValueCard && !rest) { + valueInPanel(ctx, def, cx, 162, 21); + } else if (bonus.length && !rest) { + const rows = bonus.length <= 2 ? bonus : [bonus.slice(0, 2).join(' '), bonus.slice(2).join(' ')]; + const bs = rows.length > 2 ? 11 : 13; + const blockH = rows.length * bs * 1.15; + drawLines(ctx, rows, cx, 162 - blockH / 2, bs, pal.ink, 'bold', 1.15); + } else { + let y = 135; + if (bonus.length) { + const row = bonus.join(' '); + ctx.font = `bold 11px ${SERIF}`; + const rows = ctx.measureText(row).width > w - 22 ? [bonus.slice(0, 2).join(' '), bonus.slice(2).join(' ')].filter(Boolean) : [row]; + drawLines(ctx, rows, cx, y, 11, pal.ink, 'bold', 1.1); + y += rows.length * 12.1 + 2; + } + if (isValueCard) valueInPanel(ctx, def, 22, 147, 10); + if (rest) { + const maxH = 191 - y; + const fit = fitText(ctx, rest, w - 24, maxH, [10.5, 10, 9.5, 9, 8.5, 8]); + const blockH = fit.lines.length * fit.size * 1.18; + drawLines(ctx, fit.lines, cx, y + Math.max(0, (maxH - blockH) / 2), fit.size, '#2a1d0c'); + } + } + ctx.font = `bold 9px ${SERIF}`; + ctx.fillStyle = pal.ink; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(typeLine(def), cx + 6, 205); + coin(ctx, 17, 204, 10, `${def.cost}`); + if (def.types.includes('victory') && def.vp !== undefined) shield(ctx, w - 17, 203, 8.5, `${def.vp}`); +} + +const SHEET_READY = (scene, def) => scene.textures.exists(def.sheet ?? 'dominion-cards'); + +/** Lazy-baked card face texture key. size: 'L' (270×390) or 'M' (150×216 @1.5×). */ +export function cardKey(scene, id, size = 'M') { + const def = getCard(id); + const ph = SHEET_READY(scene, def) ? '' : '-ph'; + const key = `dom-c-${size}-${id}${ph}`; + if (scene.textures.exists(key)) return key; + const [dw, dh, k] = size === 'L' ? [270, 390, 1] : [150, 216, 1.5]; + const c = canvas(Math.round(dw * k), Math.round(dh * k)); + const ctx = c.getContext('2d'); + ctx.scale(k, k); + if (size === 'L') paintLarge(ctx, scene, def); else paintMedium(ctx, scene, def); + return addCanvas(scene, key, c); +} + +/** Landscape treasury tile for a basic pile. */ +export function tileKey(scene, id, w, h) { + const def = getCard(id); + const ph = SHEET_READY(scene, def) ? '' : '-ph'; + const key = `dom-tile-${id}-${w}x${h}${ph}`; + if (scene.textures.exists(key)) return key; + const k = 2; + const c = canvas(w * k, h * k); + const ctx = c.getContext('2d'); + ctx.scale(k, k); + const pal = paintFrame(ctx, def, w, h, 9); + const ax = 5, ay = 5, aw = w - 10, ah = h - 27; + ctx.save(); + ctx.fillStyle = '#120c06'; ctx.fillRect(ax - 1, ay - 1, aw + 2, ah + 2); + ctx.beginPath(); ctx.rect(ax, ay, aw, ah); ctx.clip(); + drawArt(ctx, scene, def, ax, ay, aw, ah, 0.55); + const g = ctx.createLinearGradient(0, ay, 0, ay + 10); + g.addColorStop(0, 'rgba(0,0,0,0.4)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; ctx.fillRect(ax, ay, aw, 10); + ctx.restore(); + parchmentBox(ctx, 4, h - 21, w - 8, 17, 5); + ctx.font = `bold 12px ${SERIF}`; + ctx.fillStyle = pal.ink; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(def.name, w / 2 + 8, h - 12); + coin(ctx, 15, h - 13, 8.5, `${def.cost}`); + // value badge (top-right) + if (def.types.includes('treasure') && def.coin !== undefined) coin(ctx, w - 16, 16, 11, `${def.coin}`, COIN_TINT[def.id] ?? COIN_TINT.gold); + else if (def.types.includes('curse')) shield(ctx, w - 16, 15, 10, `${def.vp ?? -1}`, '#6a3d8f'); + else if (def.vp !== undefined) shield(ctx, w - 16, 15, 10, `${def.vp}`); + return addCanvas(scene, key, c); +} + +/** Card back: the player's chosen back (cardbacks sheet) in a rounded frame. */ +export function backKey(scene, spriteIndex = 0) { + const has = scene.textures.exists('cardbacks'); + const key = `dom-back-${has ? spriteIndex : 'x'}`; + if (scene.textures.exists(key)) return key; + const k = 1.5, w = 150, h = 216; + const c = canvas(w * k, h * k); + const ctx = c.getContext('2d'); + ctx.scale(k, k); + ctx.save(); + rr(ctx, 0, 0, w, h, 10); ctx.clip(); + const f = has ? frameOf(scene, 'cardbacks', spriteIndex) : null; + if (f) { + const sa = f.sw / f.sh, da = w / h; + let sw = f.sw, sh = f.sh, sx = f.sx, sy = f.sy; + if (sa > da) { sw = f.sh * da; sx += (f.sw - sw) / 2; } else { sh = f.sw / da; sy += (f.sh - sh) / 2; } + ctx.drawImage(f.img, sx, sy, sw, sh, 0, 0, w, h); + } else { + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, '#6b1d24'); g.addColorStop(1, '#3a0d12'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + ctx.strokeStyle = 'rgba(226,196,110,0.35)'; ctx.lineWidth = 1; + for (let i = -h; i < w + h; i += 14) { + ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i + h, h); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(i + h, 0); ctx.lineTo(i, h); ctx.stroke(); + } + } + ctx.restore(); + ctx.lineWidth = 2; ctx.strokeStyle = '#1a1008'; rr(ctx, 0, 0, w, h, 10); ctx.stroke(); + ctx.lineWidth = 1.2; ctx.strokeStyle = 'rgba(226,196,110,0.8)'; rr(ctx, 4, 4, w - 8, h - 8, 7); ctx.stroke(); + return addCanvas(scene, key, c); +} + +// ── Small props ───────────────────────────────────────────────────────────── +function bakeShadow(scene) { + const key = 'dom-shadow'; + if (scene.textures.exists(key)) return; + const pad = 26, w = 150, h = 216; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.shadowColor = 'rgba(0,0,0,0.7)'; ctx.shadowBlur = 16; ctx.shadowOffsetX = 1000; + rr(ctx, pad - 1000, pad, w, h, 12); ctx.fillStyle = '#000'; ctx.fill(); + addCanvas(scene, key, c); +} + +function bakeGlow(scene) { + const key = 'dom-glow'; + if (scene.textures.exists(key)) return; + const pad = 30, w = 150, h = 216; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.shadowColor = 'rgba(255,200,90,1)'; ctx.shadowBlur = 22; + ctx.lineWidth = 5; ctx.strokeStyle = 'rgba(255,214,120,0.95)'; + for (let i = 0; i < 2; i++) { rr(ctx, pad, pad, w, h, 12); ctx.stroke(); } + addCanvas(scene, key, c); +} + +function bakeSeal(scene) { + const key = 'dom-seal'; + if (scene.textures.exists(key)) return; + const s = 96; + const c = canvas(s, s); + const ctx = c.getContext('2d'); + const cx = s / 2, cy = s / 2; + const rnd = seeded(5); + ctx.beginPath(); + for (let i = 0; i <= 24; i++) { + const a = (i / 24) * Math.PI * 2; + const r = 40 + (rnd() - 0.5) * 7; + const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r; + if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); + } + ctx.closePath(); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 8; ctx.shadowOffsetY = 3; + const g = ctx.createRadialGradient(cx - 10, cy - 12, 4, cx, cy, 44); + g.addColorStop(0, '#d8483c'); g.addColorStop(1, '#6e130f'); + ctx.fillStyle = g; ctx.fill(); + ctx.restore(); + ctx.lineWidth = 3; ctx.strokeStyle = 'rgba(60,8,6,0.6)'; + ctx.beginPath(); ctx.arc(cx, cy, 28, 0, Math.PI * 2); ctx.stroke(); + ctx.fillStyle = 'rgba(255,215,200,0.9)'; + ctx.font = `bold 15px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('EMPTY', cx, cy + 1); + addCanvas(scene, key, c); +} + +function bakePlaque(scene) { + const key = 'dom-plaque'; + if (scene.textures.exists(key)) return; + const w = 64, h = 26, k = 2; + const c = canvas(w * k, h * k); + const ctx = c.getContext('2d'); + ctx.scale(k, k); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 5; ctx.shadowOffsetY = 2; + rr(ctx, 2, 2, w - 4, h - 4, 6); + const g = ctx.createLinearGradient(0, 2, 0, h - 2); + g.addColorStop(0, '#f2d68c'); g.addColorStop(0.5, '#c39a45'); g.addColorStop(1, '#7c5a1f'); + ctx.fillStyle = g; ctx.fill(); + ctx.restore(); + ctx.lineWidth = 1; ctx.strokeStyle = '#4e3810'; rr(ctx, 2, 2, w - 4, h - 4, 6); ctx.stroke(); + for (const x of [8, w - 8]) { + ctx.fillStyle = '#5c4314'; ctx.beginPath(); ctx.arc(x, h / 2, 1.8, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, key, c); +} + +function bakeSpot(scene) { + const key = 'dom-spot'; + if (scene.textures.exists(key)) return; + const s = 256; + const c = canvas(s, s); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(s / 2, s / 2, 4, s / 2, s / 2, s / 2); + g.addColorStop(0, 'rgba(255,255,255,1)'); + g.addColorStop(0.35, 'rgba(255,255,255,0.45)'); + g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, s, s); + addCanvas(scene, key, c); +} + +function bakeFlame(scene) { + const key = 'dom-flame'; + if (scene.textures.exists(key)) return; + const w = 40, h = 64; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(w / 2, h * 0.68, 1, w / 2, h * 0.6, h * 0.5); + g.addColorStop(0, 'rgba(255,255,235,1)'); + g.addColorStop(0.25, 'rgba(255,214,110,0.95)'); + g.addColorStop(0.6, 'rgba(255,130,40,0.55)'); + g.addColorStop(1, 'rgba(255,90,20,0)'); + ctx.fillStyle = g; + ctx.beginPath(); + ctx.moveTo(w / 2, 2); + ctx.bezierCurveTo(w * 0.9, h * 0.45, w * 0.85, h * 0.92, w / 2, h - 2); + ctx.bezierCurveTo(w * 0.15, h * 0.92, w * 0.1, h * 0.45, w / 2, 2); + ctx.fill(); + addCanvas(scene, key, c); +} + +function bakeTokens(scene) { + if (!scene.textures.exists('dom-tok-action')) { + const s = 30, k = 2, c = canvas(s * k, s * k), ctx = c.getContext('2d'); + ctx.scale(k, k); + ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 4; ctx.shadowOffsetY = 2; + const g = ctx.createRadialGradient(11, 10, 2, 15, 15, 14); + g.addColorStop(0, '#d9a066'); g.addColorStop(1, '#7a4720'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(15, 15, 12.5, 0, Math.PI * 2); ctx.fill(); ctx.restore(); + ctx.strokeStyle = '#4a2a10'; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(15, 15, 12.5, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = 'rgba(70,40,14,0.5)'; ctx.beginPath(); ctx.arc(15, 15, 8, 0, Math.PI * 2); ctx.stroke(); + // little sword glyph + ctx.fillStyle = '#3a200c'; + ctx.fillRect(14, 8, 2, 11); ctx.fillRect(11, 17, 8, 1.6); ctx.fillRect(14.2, 19, 1.6, 4); + addCanvas(scene, 'dom-tok-action', c); + } + if (!scene.textures.exists('dom-tok-buy')) { + const s = 30, k = 2, c = canvas(s * k, s * k), ctx = c.getContext('2d'); + ctx.scale(k, k); + const pts = []; for (let i = 0; i < 6; i++) { const a = Math.PI / 6 + i * Math.PI / 3; pts.push({ x: 15 + Math.cos(a) * 13, y: 15 + Math.sin(a) * 13 }); } + ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 4; ctx.shadowOffsetY = 2; + poly(ctx, pts); + const g = ctx.createLinearGradient(0, 2, 0, 28); + g.addColorStop(0, '#d9c27a'); g.addColorStop(1, '#6d5523'); + ctx.fillStyle = g; ctx.fill(); ctx.restore(); + ctx.strokeStyle = '#3d2f10'; ctx.lineWidth = 1; poly(ctx, pts); ctx.stroke(); + ctx.fillStyle = '#3d2f10'; ctx.font = `bold 13px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('B', 15, 15.5); + addCanvas(scene, 'dom-tok-buy', c); + } + if (!scene.textures.exists('dom-coin')) { + const s = 28, k = 2, c = canvas(s * k, s * k), ctx = c.getContext('2d'); + ctx.scale(k, k); + coin(ctx, 14, 14, 11.5, '$'); + addCanvas(scene, 'dom-coin', c); + } + if (!scene.textures.exists('dom-purse')) { + const s = 60, k = 2, c = canvas(s * k, s * k), ctx = c.getContext('2d'); + ctx.scale(k, k); + ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 6; ctx.shadowOffsetY = 3; + ctx.beginPath(); + ctx.moveTo(20, 18); + ctx.bezierCurveTo(4, 30, 4, 56, 30, 56); + ctx.bezierCurveTo(56, 56, 56, 30, 40, 18); + ctx.closePath(); + const g = ctx.createRadialGradient(24, 30, 4, 30, 38, 30); + g.addColorStop(0, '#9a6a3c'); g.addColorStop(1, '#4a2c14'); + ctx.fillStyle = g; ctx.fill(); ctx.restore(); + // gathered neck + drawstring + ctx.fillStyle = '#5a3a1c'; + ctx.beginPath(); ctx.ellipse(30, 15, 13, 5, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#d8b46a'; ctx.lineWidth = 1.6; + ctx.beginPath(); ctx.moveTo(18, 18); ctx.quadraticCurveTo(30, 23, 42, 18); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(40, 19); ctx.quadraticCurveTo(48, 26, 44, 32); ctx.stroke(); + // coin peeking out + coin(ctx, 34, 11, 5, ''); + addCanvas(scene, 'dom-purse', c); + } +} + +// Heraldic pennant: a swallow-tailed banner on a rod. +export function bannerKey(scene, seat) { + const key = `dom-banner-${seat}`; + if (scene.textures.exists(key)) return key; + const w = 48, h = 150, k = 2; + const c = canvas(w * k, h * k); + const ctx = c.getContext('2d'); + ctx.scale(k, k); + const field = SEAT_HEX[seat % SEAT_HEX.length]; + // rod + ctx.fillStyle = '#3a240f'; ctx.fillRect(0, 4, w, 5); + ctx.fillStyle = '#d8b46a'; + ctx.beginPath(); ctx.arc(2.5, 6.5, 3.5, 0, Math.PI * 2); ctx.fill(); + ctx.beginPath(); ctx.arc(w - 2.5, 6.5, 3.5, 0, Math.PI * 2); ctx.fill(); + // cloth + const cloth = [ + { x: 4, y: 9 }, { x: w - 4, y: 9 }, { x: w - 4, y: h - 4 }, { x: w / 2, y: h - 26 }, { x: 4, y: h - 4 }, + ]; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 8; ctx.shadowOffsetY = 4; + poly(ctx, cloth); ctx.fillStyle = field; ctx.fill(); + ctx.restore(); + ctx.save(); + poly(ctx, cloth); ctx.clip(); + const sh = ctx.createLinearGradient(4, 0, w - 4, 0); + sh.addColorStop(0, 'rgba(0,0,0,0.3)'); sh.addColorStop(0.35, 'rgba(255,255,255,0.12)'); + sh.addColorStop(0.65, 'rgba(0,0,0,0.05)'); sh.addColorStop(1, 'rgba(0,0,0,0.35)'); + ctx.fillStyle = sh; ctx.fillRect(0, 0, w, h); + ctx.fillStyle = noisePattern(ctx, 32, 24); ctx.fillRect(0, 0, w, h); + ctx.restore(); + ctx.lineWidth = 2; ctx.strokeStyle = '#d8b46a'; + poly(ctx, [{ x: 7, y: 12 }, { x: w - 7, y: 12 }, { x: w - 7, y: h - 10 }, { x: w / 2, y: h - 31 }, { x: 7, y: h - 10 }]); + ctx.stroke(); + // charge + ctx.fillStyle = '#e9c870'; + ctx.strokeStyle = '#e9c870'; + const cx = w / 2, cy = 62; + switch (SEAT_CHARGES[seat % SEAT_CHARGES.length]) { + case 'chevron': + ctx.beginPath(); ctx.moveTo(cx - 15, cy + 12); ctx.lineTo(cx, cy - 6); ctx.lineTo(cx + 15, cy + 12); + ctx.lineTo(cx + 15, cy + 20); ctx.lineTo(cx, cy + 2); ctx.lineTo(cx - 15, cy + 20); ctx.closePath(); ctx.fill(); + break; + case 'cross': + ctx.fillRect(cx - 3.5, cy - 16, 7, 32); ctx.fillRect(cx - 14, cy - 5, 28, 7); + break; + case 'mullet': { + ctx.beginPath(); + for (let i = 0; i < 10; i++) { + const a = -Math.PI / 2 + (i * Math.PI) / 5, r = i % 2 === 0 ? 15 : 6.5; + const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r; + if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); + } + ctx.closePath(); ctx.fill(); + break; + } + default: // tower + ctx.fillRect(cx - 10, cy - 6, 20, 24); + for (const dx of [-10, -2.5, 5]) ctx.fillRect(cx + dx, cy - 12, 5, 7); + ctx.fillStyle = SEAT_HEX[seat % SEAT_HEX.length]; ctx.fillRect(cx - 3, cy + 8, 6, 10); + } + return addCanvas(scene, key, c); +} + +// A parchment panel (modals, the prompt ribbon, the proclamation). +export function parchmentKey(scene, w, h) { + w = Math.round(w); h = Math.round(h); + const key = `dom-parch-${w}x${h}`; + if (scene.textures.exists(key)) return key; + const pad = 24; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.translate(pad, pad); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.65)'; ctx.shadowBlur = 22; ctx.shadowOffsetY = 8; + rr(ctx, 0, 0, w, h, 14); ctx.fillStyle = '#e8d5a6'; ctx.fill(); + ctx.restore(); + ctx.save(); + rr(ctx, 0, 0, w, h, 14); ctx.clip(); + const g = ctx.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.2, w / 2, h / 2, Math.max(w, h) * 0.75); + g.addColorStop(0, '#f6ead0'); g.addColorStop(1, '#cdb37a'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + ctx.fillStyle = noisePattern(ctx, 64, 22); ctx.fillRect(0, 0, w, h); + // foxing + const rnd = seeded(w + h); + for (let i = 0; i < 10; i++) { + const x = rnd() * w, y = rnd() * h, r = 10 + rnd() * 40; + const f = ctx.createRadialGradient(x, y, 1, x, y, r); + f.addColorStop(0, 'rgba(140,100,40,0.10)'); f.addColorStop(1, 'rgba(140,100,40,0)'); + ctx.fillStyle = f; ctx.fillRect(x - r, y - r, r * 2, r * 2); + } + ctx.restore(); + ctx.lineWidth = 2; ctx.strokeStyle = '#7a5a26'; rr(ctx, 0, 0, w, h, 14); ctx.stroke(); + ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(122,90,38,0.6)'; rr(ctx, 7, 7, w - 14, h - 14, 10); ctx.stroke(); + return addCanvas(scene, key, c); +} + +// A ribbon banner with forked tails. +export function ribbonKey(scene, w, color = '#7c1f22') { + w = Math.round(w); + const key = `dom-ribbon-${w}-${color.slice(1)}`; + if (scene.textures.exists(key)) return key; + const h = 46, tail = 34, k = 2; + const c = canvas((w + tail * 2) * k, (h + 16) * k); + const ctx = c.getContext('2d'); + ctx.scale(k, k); + ctx.translate(tail, 4); + const dark = mix(color, '#000000', 0.45); + for (const side of [-1, 1]) { + const x = side < 0 ? -tail : w; + ctx.fillStyle = dark; + poly(ctx, side < 0 + ? [{ x: x + tail + 6, y: 8 }, { x, y: 8 }, { x: x + 12, y: 8 + h / 2 }, { x, y: 8 + h }, { x: x + tail + 6, y: 8 + h }] + : [{ x: x - 6, y: 8 }, { x: x + tail, y: 8 }, { x: x + tail - 12, y: 8 + h / 2 }, { x: x + tail, y: 8 + h }, { x: x - 6, y: 8 + h }]); + ctx.fill(); + } + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 8; ctx.shadowOffsetY = 3; + ctx.fillStyle = color; ctx.fillRect(0, 0, w, h); + ctx.restore(); + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, 'rgba(255,255,255,0.18)'); g.addColorStop(0.5, 'rgba(255,255,255,0)'); g.addColorStop(1, 'rgba(0,0,0,0.25)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + ctx.strokeStyle = '#e2c46e'; ctx.lineWidth = 1.5; + ctx.strokeRect(3, 4, w - 6, h - 8); + return addCanvas(scene, key, c); +} + +/** Add a ribbon image whose cloth spans `w` px (tails extend beyond). */ +export function addRibbon(scene, x, y, w, color = '#7c1f22') { + const img = scene.add.image(x, y, ribbonKey(scene, w, color)); + img.setDisplaySize(w + 68, 62); + return img; +} + +/** Bake everything the table needs up front (cards bake lazily). */ +export function prepareDominionArt(scene, L) { + bakeTable(scene); + bakeLight(scene); + const furn = bakeFurniture(scene, L); + bakeShadow(scene); + bakeGlow(scene); + bakeSeal(scene); + bakePlaque(scene); + bakeFlame(scene); + bakeSpot(scene); + bakeTokens(scene); + for (let s = 0; s < 4; s++) bannerKey(scene, s); + return { furniture: furn }; +} diff --git a/src/games/dominion/DominionEndScreen.js b/src/games/dominion/DominionEndScreen.js new file mode 100644 index 0000000..8868465 --- /dev/null +++ b/src/games/dominion/DominionEndScreen.js @@ -0,0 +1,172 @@ +// Dominion — "The Reckoning" scoring ceremony + Royal Proclamation. +// +// Each player's row lays out their victory cards group by group (Colony, +// Province, Duchy, Estate, Gardens …, then Curses), the VP counter ticking as +// each group lands; VP tokens follow. Then the winner's row is crowned, the +// proclamation ribbon names them, and the stats + buttons appear. A click +// skips straight to the result. + +import { Button } from '../../ui/Button.js'; +import { COLORS } from '../../config.js'; +import { playSound, SFX } from '../../ui/Sounds.js'; +import { getCard } from './DominionCards.js'; +import { finalScores } from './DominionLogic.js'; +import { reckoning, seatStats } from './DominionScoring.js'; +import { W, H, SEAT_COLORS } from './DominionLayout.js'; +import { cardKey, bannerKey, parchmentKey, addRibbon, PHASER_SERIF } from './DominionArt.js'; + +const INK = '#2f1f0c'; +const TXT = (size, color = INK, extra = {}) => ({ fontFamily: PHASER_SERIF, fontSize: `${size}px`, color, fontStyle: 'bold', ...extra }); + +export function showEndScreen(scene, { state, seatName, bestCoins = [], depth = 90, onNew, onLeave }) { + const objs = []; + const add = (o) => { objs.push(o); return o; }; + const timers = []; + const scores = finalScores(state); + const winners = new Set(state.winnerSeats); + const order = scores.slice().sort((a, b) => (b.vp - a.vp) || ((state.turnsTaken[a.seat] ?? 0) - (state.turnsTaken[b.seat] ?? 0)) || (a.seat - b.seat)); + + const overlay = add(scene.add.rectangle(W / 2, H / 2, W, H, 0x000000, 0).setDepth(depth).setInteractive()); + scene.tweens.add({ targets: overlay, fillAlpha: 0.72, duration: 400 }); + + const n = order.length; + const rowH = n >= 4 ? 158 : 176; + const panelW = 1640, panelH = 150 + n * rowH + 110; + const py = H / 2 - panelH / 2 + 20; + const panel = add(scene.add.image(W / 2, py + panelH / 2, parchmentKey(scene, panelW, panelH)).setDepth(depth + 1).setAlpha(0)); + scene.tweens.add({ targets: panel, alpha: 1, y: { from: py + panelH / 2 + 30, to: py + panelH / 2 }, duration: 450, ease: 'Cubic.Out' }); + + add(addRibbon(scene, W / 2, py + 18, 760, '#7c1f22').setDepth(depth + 3)); + const title = add(scene.add.text(W / 2, py + 14 + 2, 'The Reckoning', TXT(30, '#fbefcf')).setOrigin(0.5).setDepth(depth + 4)); + title.setShadow(0, 2, '#000', 4, false, true); + const sub = add(scene.add.text(W / 2, py + 74, 'Every card is counted…', TXT(18, '#5a4120', { fontStyle: 'italic' })).setOrigin(0.5).setDepth(depth + 2)); + + const left = W / 2 - panelW / 2; + const rows = order.map((sc, r) => { + const seat = sc.seat; + const y = py + 120 + r * rowH + rowH / 2; + const rk = reckoning(state, seat); + const st = seatStats(state, seat); + // seat banner + name + add(scene.add.image(left + 64, y - rowH / 2 + 18, bannerKey(scene, seat)).setOrigin(0.5, 0).setDisplaySize(40, 124).setDepth(depth + 2)); + add(scene.add.text(left + 104, y - 46, seatName(seat), TXT(26)).setOrigin(0, 0.5).setDepth(depth + 2)); + add(scene.add.text(left + 104, y - 14, `${rk.total} cards · ${st.turns} turns`, TXT(15, '#5a4120', { fontStyle: 'normal' })).setOrigin(0, 0.5).setDepth(depth + 2)); + // deck composition bar + const barX = left + 104, barY = y + 14, barW = 230, barH = 14; + const g = add(scene.add.graphics().setDepth(depth + 2)); + g.fillStyle(0x000000, 0.25); g.fillRoundedRect(barX - 1, barY - 1, barW + 2, barH + 2, 4); + let bx = barX; + for (const [k, col] of [['treasure', 0xd9a72e], ['action', 0xb89a62], ['victory', 0x4e8a49], ['curse', 0x7a4e9b]]) { + const w = rk.total ? (rk.census[k] / rk.total) * barW : 0; + if (w > 0) { g.fillStyle(col, 1); g.fillRect(bx, barY, w, barH); bx += w; } + } + add(scene.add.text(barX, barY + 26, `${rk.census.treasure} treasure · ${rk.census.action} action · ${rk.census.victory} victory${rk.census.curse ? ` · ${rk.census.curse} curse` : ''}`, + TXT(12, '#5a4120', { fontStyle: 'normal' })).setOrigin(0, 0.5).setDepth(depth + 2)); + // stats + const best = bestCoins[seat] ?? 0; + const sig = st.signature ? `${getCard(st.signature.id).name} ×${st.signature.n}` : '—'; + const statText = add(scene.add.text(left + panelW - 250, y - 30, `Bought ${st.bought}\nBest turn $${best}\nSignature: ${sig}`, + TXT(14, '#5a4120', { fontStyle: 'normal', lineSpacing: 4 })).setOrigin(0, 0.5).setDepth(depth + 2).setAlpha(0)); + // VP counter + const vpText = add(scene.add.text(left + panelW - 330, y - 6, '0', TXT(44, '#2f5f33')).setOrigin(0.5).setDepth(depth + 3)); + add(scene.add.text(left + panelW - 330, y + 30, 'VP', TXT(14, '#5a4120')).setOrigin(0.5).setDepth(depth + 2)); + // separator + if (r < n - 1) { + const sep = add(scene.add.graphics().setDepth(depth + 2)); + sep.lineStyle(1, 0x7a5a26, 0.35); sep.lineBetween(left + 40, y + rowH / 2, left + panelW - 40, y + rowH / 2); + } + const items = rk.groups.map((gp) => ({ kind: 'group', ...gp })); + if (rk.tokens) items.push({ kind: 'tokens', vp: rk.tokens, n: rk.tokens }); + return { seat, y, items, vpText, statText, shown: 0, vp: 0, finalVp: sc.vp, nodes: [] }; + }); + + const groupX0 = left + 400, groupStep = 108; + const cw = 64, ch = 92; + const revealItem = (row, i, animate) => { + const it = row.items[i]; + const x = groupX0 + i * groupStep; + const y = row.y - 12; + let node; + if (it.kind === 'group') { + node = scene.add.image(x, y, cardKey(scene, it.id, 'M')).setDisplaySize(cw, ch).setDepth(depth + 3); + if (it.n > 1) { + const back = scene.add.image(x + 5, y + 4, cardKey(scene, it.id, 'M')).setDisplaySize(cw, ch).setDepth(depth + 2).setTint(0xbbbbbb); + add(back); row.nodes.push(back); + } + const badge = add(scene.add.text(x + cw / 2 - 2, y - ch / 2 + 4, `×${it.n}`, TXT(15, '#fff6dc', { backgroundColor: '#3b2a14', padding: { x: 5, y: 1 } })) + .setOrigin(1, 0).setDepth(depth + 4)); + const label = it.id === 'gardens' ? `${it.each} each` : `${it.vp > 0 ? '+' : ''}${it.vp}`; + const lab = add(scene.add.text(x, y + ch / 2 + 14, label, TXT(16, it.vp < 0 ? '#8a2a20' : '#2f5f33')).setOrigin(0.5).setDepth(depth + 3)); + row.nodes.push(badge, lab); + if (it.id === 'gardens') { + const sub2 = add(scene.add.text(x, y + ch / 2 + 31, `= ${it.vp}`, TXT(13, '#2f5f33')).setOrigin(0.5).setDepth(depth + 3)); + row.nodes.push(sub2); + } + } else { + const has = scene.textures.exists('dominion-tokens'); + node = has ? scene.add.image(x, y, 'dominion-tokens', it.vp >= 5 ? 1 : 0).setDisplaySize(58, 58) + : scene.add.circle(x, y, 28, 0xd4a017); + node.setDepth(depth + 3); + const lab = add(scene.add.text(x, y + ch / 2 + 14, `+${it.vp} tokens`, TXT(15, '#2f5f33')).setOrigin(0.5).setDepth(depth + 3)); + row.nodes.push(lab); + } + add(node); + row.nodes.push(node); + row.vp += it.vp; + if (animate) { + const sx = node.scaleX, sy = node.scaleY; + node.setScale(sx * 1.6, sy * 1.6).setAlpha(0); + scene.tweens.add({ targets: node, scaleX: sx, scaleY: sy, alpha: 1, duration: 300, ease: 'Back.Out' }); + const from = { v: row.vp - it.vp }; + scene.tweens.add({ + targets: from, v: row.vp, duration: 320, + onUpdate: () => row.vpText.setText(`${Math.round(from.v)}`), + }); + } else row.vpText.setText(`${row.vp}`); + }; + + let finished = false; + const maxItems = Math.max(0, ...rows.map((r) => r.items.length)); + const finish = () => { + if (finished) return; + finished = true; + timers.forEach((t) => t.remove()); + for (const row of rows) { + while (row.shown < row.items.length) revealItem(row, row.shown++, false); + row.vpText.setText(`${row.finalVp}`); + scene.tweens.add({ targets: row.statText, alpha: 1, duration: 300 }); + } + const youWon = winners.has(0); + const lead = order[0]; + const titleText = youWon ? (winners.size > 1 ? 'A shared crown!' : 'You rule the realm!') : `${seatName(lead.seat)} rules the realm`; + title.setText(titleText); + sub.setText(winners.size > 1 ? 'Tied on points and turns — the crown is shared.' : 'By royal proclamation, the reckoning is complete.'); + playSound(scene, youWon ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (const row of rows) { + if (!winners.has(row.seat)) continue; + const crown = add(scene.add.text(left + panelW - 330, row.y - 54, '♛', TXT(34, '#c99a2e')).setOrigin(0.5).setDepth(depth + 4)); + crown.setShadow(0, 2, '#000', 3, false, true); + scene.tweens.add({ targets: crown, y: crown.y - 6, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + const glow = add(scene.add.rectangle(W / 2, row.y, panelW - 60, rowH - 12, SEAT_COLORS[row.seat % 4], 0.12).setDepth(depth + 1.5)); + glow.setStrokeStyle(2, 0xc99a2e, 0.8); + } + const by = py + panelH - 52; + add(new Button(scene, W / 2 - 150, by, 'New game', onNew, { + width: 260, bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex, + }).setDepth(depth + 5)); + add(new Button(scene, W / 2 + 150, by, 'Leave', onLeave, { variant: 'ghost', width: 260 }).setDepth(depth + 5)); + }; + + overlay.on('pointerup', () => finish()); + for (let k = 0; k < maxItems; k++) { + timers.push(scene.time.delayedCall(700 + k * 480, () => { + if (finished) return; + let any = false; + for (const row of rows) if (row.shown < row.items.length) { revealItem(row, row.shown++, true); any = true; } + if (any) playSound(scene, SFX.CARD_SHOW); + })); + } + timers.push(scene.time.delayedCall(700 + maxItems * 480 + 500, finish)); + + return { destroy: () => { timers.forEach((t) => t.remove()); objs.forEach((o) => o.destroy?.()); } }; +} diff --git a/src/games/dominion/DominionGame.js b/src/games/dominion/DominionGame.js index a08f4bf..3628264 100644 --- a/src/games/dominion/DominionGame.js +++ b/src/games/dominion/DominionGame.js @@ -13,10 +13,30 @@ import { legalActionIids, canGain, emptyPileCount, buyCost, buyAllowed, } from './DominionLogic.js'; import * as AI from './DominionAI.js'; +import { + computeLayout, splitBasics, inPlayPositions, handPositions, oppHandPositions, + HAND, PLAY, MINI, MINI_DISC, SHOW, HOVER, MAT, RIBBON_Y, DOCK, DECK, DISCARD, HAND_Y, HAND_ZONE, + LEAVE, MUSIC, SEAT_COLORS, SEAT_HEX, rectCX, rectCY, rectW, +} from './DominionLayout.js'; +import { + prepareDominionArt, cardKey, tileKey, backKey, parchmentKey, addRibbon, PHASER_SERIF, +} from './DominionArt.js'; +import { StewardTray, EndClock, VpDish, SeatBanner, makePhaseDial } from './DominionHud.js'; +import { showEndScreen } from './DominionEndScreen.js'; +import { tuckInfo } from './DominionScoring.js'; const CX = GAME_WIDTH / 2; +const RIBBON_CX = 1040; -const D = { bg: -1, supply: 5, inplay: 6, hand: 10, hud: 15, portrait: 20, prompt: 40, modal: 80, popup: 95 }; +const D = { table: -3, light: -2, furniture: -1, supply: 5, inplay: 6, hand: 10, hud: 15, portrait: 20, prompt: 40, modal: 80, popup: 95 }; + +const AI_STEP_MS = 420; +const AI_PENDING_MS = 520; + +const SERIF = (size, color = '#f3e6c8', extra = {}) => ({ + fontFamily: PHASER_SERIF, fontSize: `${size}px`, color, fontStyle: 'bold', ...extra, +}); +const INK = '#2f1f0c'; // Returns the screen (x, y) at distance d along the clockwise perimeter of a // rectangle with top-left corner (left, top) and dimensions W×H. @@ -32,34 +52,14 @@ function perimPoint(d, W, H, left, top) { return [left, top + H - d]; } -const SUPPLY_W = 100, SUPPLY_H = 144; -const HAND_W = 132, HAND_H = 190; -const PLAY_W = 78, PLAY_H = 112; - -const DECK_PILE_X = 240, DECK_PILE_Y = 968; -const DISCARD_PILE_X = 1704, DISCARD_PILE_Y = 968; // right edge aligns with opponent portrait center (x=1770) -const OPP_W = 36, OPP_H = 52; - -const AI_STEP_MS = 420; -const AI_PENDING_MS = 520; - -// Card-face colour styling by type. -function typeStyle(def) { - if (!def) return { art: 0x2a2a40, border: 0x554f38, band: 0x14110b }; - if (isType(def.id, 'curse')) return { art: 0x6a3d8f, border: 0x9b59b6, band: 0x1c1226 }; - if (isType(def.id, 'treasure')) { - const art = def.id === 'gold' ? 0xd4af37 : def.id === 'silver' ? 0xb8bcc2 : 0xb87333; - return { art, border: 0xc8a84b, band: 0x231b0e }; - } - if (isType(def.id, 'victory')) return { art: 0x2e7d4f, border: 0x3fa86a, band: 0x10241a }; - if (isType(def.id, 'attack')) return { art: 0xbb9a6a, border: 0xd0563b, band: 0x231a12 }; - if (isType(def.id, 'reaction')) return { art: 0x8fb0cf, border: 0x4a90d9, band: 0x141d27 }; - return { art: 0xcdbb8f, border: 0xc8a84b, band: 0x231f17 }; // action -} - -function typeLine(def) { - return def.types.map((t) => t.charAt(0).toUpperCase() + t.slice(1)).join(' – '); -} +const PRESET_LABELS = { + standard: 'First Game', 'size-distortion': 'Size Distortion', 'deck-top': 'Deck Top', + 'silver-gold': 'Silver & Gold', 'helpful-actions': 'Helpful Actions', + beginners: 'Beginners', 'friendly-interactive': 'Friendly Interactive', + 'bigger-treasures': 'Bigger Treasures', 'the-king': 'The King', random: 'A Random Kingdom', +}; +const EXPANSION_LABELS = { base: 'Base Game', prosperity: 'Prosperity' }; +const presetLabel = (id) => PRESET_LABELS[id] ?? id.replace(/(^|-)\w/g, (s) => s.replace('-', ' ').toUpperCase()); export default class DominionGame extends Phaser.Scene { constructor() { super('DominionGame'); } @@ -94,14 +94,17 @@ export default class DominionGame extends Phaser.Scene { this._handOrder = null; this.oppHandSprites = {}; this.oppInPlaySprites = {}; + this.oppPiles = {}; this.phaseDials = []; - this.turnArrow = null; - this._arrowSeat = null; + this.banners = []; + this.vpDishes = []; this._boughtThisTurn = false; this._suppressTurnUi = false; this._handFxGraphics = []; this._handFxTweens = []; this._supplyFxEmitters = []; + this._supplyFxTweens = []; + this._supplyFxGraphics = []; this._deckAnimDisplay = null; this._discardAnimDisplay = null; this._liveDeckPile = null; @@ -110,12 +113,18 @@ export default class DominionGame extends Phaser.Scene { this._liveDiscardPile = null; this._liveDiscardBadge = null; this._liveDiscardCountText = null; - this.tokenSprites = []; - this.lastVpTokens = { 0: 0, 1: 0, 2: 0, 3: 0 }; + this._liveDiscardTop = null; + this.bestCoins = [0, 0, 0, 0]; + this._introRunning = false; + this.endScreen = null; } create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); + try { + new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? [], undefined, { + right: MUSIC.right, top: MUSIC.top, infoColor: '#e9d7a8', + }); + } catch (_) { /* no music manifest */ } if (!this.textures.exists('dominion-sparkle')) { const g = this.add.graphics(); g.fillStyle(0xffffff, 1); @@ -123,10 +132,28 @@ export default class DominionGame extends Phaser.Scene { g.generateTexture('dominion-sparkle', 6, 6); g.destroy(); } + + const initialState = createInitialState({ + seed: (Date.now() ^ (Math.random() * 1e9)) >>> 0, + playerCount: this.playerCount, + deckMode: this.deckMode, + expansion: this.expansion, + }); + this.pileMax = { ...initialState.supply }; + const basicIds = Object.keys(initialState.supply).filter((id) => !initialState.kingdom.includes(id)); + basicIds.sort((a, b) => getCard(a).cost - getCard(b).cost); + this.L = computeLayout({ + playerCount: this.playerCount, + basics: splitBasics(basicIds, (id) => getCard(id).types), + kingdomCount: initialState.kingdom.length, + }); + this.art = prepareDominionArt(this, this.L); + // Bake the supply's faces now so the first render / hover doesn't hitch. + for (const id of Object.keys(initialState.supply)) { cardKey(this, id, 'M'); cardKey(this, id, 'L'); } + this.buildBackground(); - this.buildPortraits(); - this.buildTurnArrow(); - this.buildPhaseDials(); + this.buildSeats(); + this.buildHud(); this.buildHoverPopup(); this.buildButtons(); this.animLayer = this.add.container(0, 0).setDepth(D.hand + 50); @@ -145,17 +172,10 @@ export default class DominionGame extends Phaser.Scene { this.events.once('shutdown', () => { this.portraits.forEach((pt) => pt?.destroy?.()); - this.turnArrow?.destroy(); this.phaseDials.forEach((d) => d?.destroy?.()); }); - const initialState = createInitialState({ - seed: (Date.now() ^ (Math.random() * 1e9)) >>> 0, - playerCount: this.playerCount, - deckMode: this.deckMode, - expansion: this.expansion, - }); - // Show an empty hand first, then animate the deal. + // Show an empty hand first, reveal the Kingdom, then animate the deal. const p0 = initialState.players[0]; const preDeal = { ...initialState, @@ -164,10 +184,14 @@ export default class DominionGame extends Phaser.Scene { ), }; this.gs = preDeal; + this._introRunning = true; this.render(); this._deckAnimDisplay = preDeal.players[0].deck.length; // 10 before deal this._discardAnimDisplay = 0; - this._animDrawCards(p0.hand, initialState); + this._playKingdomReveal(() => { + this._introRunning = false; + this._animDrawCards(p0.hand, initialState); + }); } // ── Static scaffolding ───────────────────────────────────────────────────── @@ -175,46 +199,59 @@ export default class DominionGame extends Phaser.Scene { buildBackground() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg); + // A chosen playfield becomes the tablecloth; the hall's candlelight still falls on it. + this.add.image(CX, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.table); + this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.3).setDepth(D.table); } else { - this.add.image(CX, GAME_HEIGHT / 2, 'bg-room').setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg); + this.add.image(0, 0, 'dom-table').setOrigin(0).setDepth(D.table); } - this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.45).setDepth(D.bg); + this.add.image(0, 0, 'dom-light').setOrigin(0).setDepth(D.light); + this.add.image(0, 0, this.art.furniture).setOrigin(0).setDepth(D.furniture); } - // Opponent panels live on the right column; the human sits bottom-left. - oppSlot(i) { - const ys = this.opponents.length === 2 ? [300, 600] : [180, 430, 680]; - return { x: 1770, y: ys[i] ?? 180, r: 52 }; - } - - buildPortraits() { - createPlayerPortrait(this, 92, 928, 56, D.portrait, 'DominionGame'); - this.add.text(92, 928 + 56 + 14, this.seatName(0), { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.hud); + buildSeats() { + const L = this.L; + const h = L.human; + this.banners[0] = new SeatBanner(this, 0, h.banner, L.human.rect, -0.6); + createPlayerPortrait(this, h.portrait.x, h.portrait.y, h.portrait.r, D.portrait, 'DominionGame'); + this.add.text(h.name.x, h.name.y, this.seatName(0), SERIF(19)).setOrigin(0.5).setDepth(D.hud) + .setShadow(0, 2, '#000', 4, false, true); + this.phaseDials[0] = makePhaseDial(this, h.dial.x, h.dial.y, h.dial.r, D.portrait); + this.vpDishes[0] = new VpDish(this, h.vp.x, h.vp.y, D.hud, { size: 34, max: 7 }); this.opponents.forEach((opp, i) => { - const s = this.oppSlot(i); - const pt = createOpponentPortrait(this, opp, s.x, s.y, s.r, D.portrait); - this.portraits[i + 1] = pt; - this.add.text(s.x, s.y + s.r + 14, opp.name ?? `Player ${i + 2}`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.hud); + const seat = i + 1; + const p = L.plates[i]; + this.banners[seat] = new SeatBanner(this, seat, p.banner, p.rect, -0.6); + const pt = createOpponentPortrait(this, opp, p.portrait.x, p.portrait.y, p.portrait.r, D.portrait); + this.portraits[seat] = pt; + this.add.text(p.name.x, p.name.y, opp.name ?? `Player ${seat + 1}`, SERIF(16)).setOrigin(0.5).setDepth(D.hud) + .setShadow(0, 2, '#000', 4, false, true); + this.phaseDials[seat] = makePhaseDial(this, p.dial.x, p.dial.y, p.dial.r, D.portrait); + this.vpDishes[seat] = new VpDish(this, p.vp.x, p.vp.y, D.hud, { size: 26, max: 4 }); }); } + buildHud() { + this.tray = new StewardTray(this, D.hud); + this.endClock = new EndClock(this, this.L.clock, D.supply, { colony: this.gs?.supply?.colony !== undefined || this.pileMax.colony !== undefined }); + } + buildButtons() { - this.btnEndAction = new Button(this, CX, 830, 'End Action Phase', () => this.humanEndAction(), { + const y = rectCY(DOCK); + const gold = { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex }; + this.btnEndAction = new Button(this, rectCX(DOCK), y, 'End Action Phase', () => this.humanEndAction(), { width: 240, height: 48, fontSize: 20, }).setDepth(D.hud).setVisible(false); - this.btnEndTurn = new Button(this, CX, 830, 'End Turn', () => this.humanEndTurn(), { - width: 240, height: 48, fontSize: 20, bg: COLORS.accent, bgHover: COLORS.gold, - textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex, + this.btnPlayTreasures = new Button(this, rectCX(DOCK) - 130, y, 'Play Treasures', () => this.humanPlayTreasures(), { + width: 220, height: 48, fontSize: 19, + }).setDepth(D.hud).setVisible(false); + this.btnEndTurn = new Button(this, rectCX(DOCK), y, 'End Turn', () => this.humanEndTurn(), { + width: 220, height: 48, fontSize: 20, ...gold, }).setDepth(D.hud).setVisible(false); - new Button(this, 92, 1028, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 130, height: 40, fontSize: 18, + new Button(this, LEAVE.x, LEAVE.y, 'Leave', () => this.scene.start('GameMenu'), { + variant: 'ghost', width: LEAVE.w, height: LEAVE.h, fontSize: 18, }).setDepth(D.hud); } @@ -227,186 +264,10 @@ export default class DominionGame extends Phaser.Scene { return this.opponents[seat - 1]?.skill ?? 3; } - // ── Turn arrow + phase dials (persistent overlay) ───────────────────────────── + plate(seat) { return this.L.plates[seat - 1]; } - // Yellow turn arrow, mirroring the Settlers of Catan indicator. - buildTurnArrow() { - const g = this.add.graphics().setDepth(D.portrait + 5); - g.fillStyle(0xffdd00, 1); - g.fillTriangle(-12, -15, -12, 15, 12, 0); - g.setPosition(-9999, -9999); - this.turnArrow = g; - this._arrowSeat = null; - this.tweens.add({ - targets: g, scaleX: 1.4, scaleY: 1.4, duration: 700, - yoyo: true, repeat: -1, ease: 'Sine.InOut', - }); - } + // ── Turn indicator: banners + phase dials ────────────────────────────────── - // Portrait anchor the arrow points at, by seat. - arrowSeatPos(seat) { - if (seat === 0) return { x: 92, y: 928, r: 56 }; - const s = this.oppSlot(seat - 1); - return { x: s.x, y: s.y, r: s.r }; - } - - buildPhaseDials() { - this.phaseDials[0] = this.makePhaseDial(168, 748, 60, 60); - this.opponents.forEach((opp, i) => { - const s = this.oppSlot(i); - const r = 26; - this.phaseDials[i + 1] = this.makePhaseDial(s.x + s.r + 14 + r, s.y, r); - }); - } - - // A 3-wedge ring (Action/Buy/Clean Up) that spins so the active wedge locks - // under a fixed top pointer. Returns a controller with setActive/setPhase. - makePhaseDial(x, y, outerR, labelDY = 0) { - const scene = this; - const PHASE = { action: 0, buy: 1, cleanup: 2 }; - const colors = [0xd0563b, 0xd4a017, 0x4a90d9]; - const TWO_PI_3 = (Math.PI * 2) / 3; - const HALF = Math.PI / 3; - const TOP = -Math.PI / 2; - - const container = this.add.container(x, y).setDepth(D.portrait); - const ring = this.add.container(0, 0); - container.add(ring); - - const a0 = [], a1 = [], mid = []; - for (let i = 0; i < 3; i++) { - const c = TOP + i * TWO_PI_3; - a0[i] = c - HALF; a1[i] = c + HALF; mid[i] = c; - } - - const wedges = []; - for (let i = 0; i < 3; i++) { - const w = this.add.graphics(); - ring.add(w); - wedges.push(w); - } - const paintWedges = (activeIdx) => { - for (let i = 0; i < 3; i++) { - const w = wedges[i]; - const on = i === activeIdx; - w.clear(); - w.fillStyle(colors[i], on ? 0.95 : 0.26); - w.beginPath(); w.moveTo(0, 0); w.arc(0, 0, outerR, a0[i], a1[i], false); w.closePath(); w.fillPath(); - w.lineStyle(on ? Math.max(2, outerR * 0.05) : 1.5, on ? colors[i] : COLORS.accent, on ? 1 : 0.55); - w.beginPath(); w.moveTo(0, 0); w.arc(0, 0, outerR, a0[i], a1[i], false); w.closePath(); w.strokePath(); - } - }; - paintWedges(-1); - - const ic = outerR * 0.22; - const midR = outerR * 0.66; - const drawSword = (g) => { - g.fillStyle(0xf2ead8, 1); - g.fillTriangle(-0.16 * ic, -0.5 * ic, 0.16 * ic, -0.5 * ic, 0, -1.15 * ic); - g.fillRect(-0.14 * ic, -0.5 * ic, 0.28 * ic, 0.85 * ic); - g.fillStyle(0xc8a84b, 1); - g.fillRect(-0.5 * ic, 0.3 * ic, ic, 0.16 * ic); - g.fillRect(-0.12 * ic, 0.46 * ic, 0.24 * ic, 0.5 * ic); - }; - const drawCoin = (g) => { - g.fillStyle(0xd4a017, 1); g.fillCircle(0, 0, 0.95 * ic); - g.lineStyle(Math.max(1, 0.14 * ic), 0x6e5410, 1); g.strokeCircle(0, 0, 0.95 * ic); - g.lineStyle(Math.max(1, 0.14 * ic), 0xfff3c4, 0.9); g.strokeCircle(0, 0, 0.5 * ic); - }; - const drawRefresh = (g) => { - g.lineStyle(Math.max(1.5, 0.2 * ic), 0xf2ead8, 1); - g.beginPath(); g.arc(0, 0, 0.85 * ic, Phaser.Math.DegToRad(-50), Phaser.Math.DegToRad(200), false); g.strokePath(); - const end = Phaser.Math.DegToRad(200); - const ex = Math.cos(end) * 0.85 * ic, ey = Math.sin(end) * 0.85 * ic; - g.fillStyle(0xf2ead8, 1); - g.fillTriangle(ex - 0.45 * ic, ey - 0.1 * ic, ex + 0.1 * ic, ey - 0.5 * ic, ex + 0.15 * ic, ey + 0.35 * ic); - }; - const drawers = [drawSword, drawCoin, drawRefresh]; - const icons = []; - for (let i = 0; i < 3; i++) { - const g = this.add.graphics(); - drawers[i](g); - g.setPosition(Math.cos(mid[i]) * midR, Math.sin(mid[i]) * midR); - ring.add(g); - icons.push(g); - } - - const hub = this.add.graphics(); - hub.fillStyle(0x141008, 0.88); hub.fillCircle(0, 0, outerR * 0.42); - hub.lineStyle(Math.max(1.5, outerR * 0.03), COLORS.accent, 0.7); hub.strokeCircle(0, 0, outerR * 0.42); - container.add(hub); - - const pointer = this.add.graphics(); - const pw = outerR * 0.16, ph = outerR * 0.3, ty = -outerR; - pointer.fillStyle(COLORS.gold, 1); - pointer.fillTriangle(-pw, ty - ph, pw, ty - ph, 0, ty + ph * 0.5); - pointer.lineStyle(1.5, COLORS.textDark, 0.6); - pointer.strokeTriangle(-pw, ty - ph, pw, ty - ph, 0, ty + ph * 0.5); - container.add(pointer); - - const names = ['Action Phase', 'Buy Phase', 'Clean-up Phase']; - const nameHex = ['#d0563b', '#d4a017', '#4a90d9']; - const labelSize = Math.max(12, Math.round(outerR * 0.36)); - const label = this.add.text(0, -(outerR + labelSize) - labelDY, '', { - fontFamily: 'Righteous', fontSize: `${labelSize}px`, color: nameHex[0], - }).setOrigin(0.5).setVisible(false); - label.setShadow(0, 2, '#000000', 4, false, true); - container.add(label); - const applyLabel = (idx) => { label.setText(names[idx]); label.setColor(nameHex[idx]); }; - - container.setAlpha(0.38); - - return { - container, - _active: false, - _phaseIdx: 0, - _pulse: null, - _rot: null, - setActive(on) { - if (this._active === on) return; - this._active = on; - scene.tweens.add({ targets: container, alpha: on ? 1 : 0.38, duration: 300, ease: 'Sine.Out' }); - if (on) { - paintWedges(this._phaseIdx); - applyLabel(this._phaseIdx); - label.setVisible(true); - this._pulse?.remove(); - this._pulse = scene.tweens.add({ - targets: container, scaleX: 1.06, scaleY: 1.06, - duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut', - }); - } else { - this._pulse?.remove(); this._pulse = null; - this._rot?.remove(); this._rot = null; - scene.tweens.add({ targets: container, scaleX: 1, scaleY: 1, duration: 200 }); - ring.rotation = 0; - icons.forEach((g) => { g.rotation = 0; }); - this._phaseIdx = 0; - paintWedges(-1); - label.setVisible(false); - } - }, - setPhase(name) { - const idx = PHASE[name] ?? 0; - if (idx === this._phaseIdx) return; - this._phaseIdx = idx; - paintWedges(idx); - applyLabel(idx); - this._rot?.remove(); - this._rot = scene.tweens.add({ - targets: ring, rotation: -idx * TWO_PI_3, duration: 500, ease: 'Cubic.Out', - onUpdate: () => { icons.forEach((g) => { g.rotation = -ring.rotation; }); }, - onComplete: () => { icons.forEach((g) => { g.rotation = -ring.rotation; }); }, - }); - }, - destroy() { - this._pulse?.remove(); this._rot?.remove(); - container.destroy(true); - }, - }; - } - - // Reflects whose turn it is (arrow) and the active phase (dials) into the overlay. updateTurnUi() { if (this._suppressTurnUi) { this.phaseDials[0]?.setActive(true); @@ -414,32 +275,36 @@ export default class DominionGame extends Phaser.Scene { return; } const gs = this.gs; - if (!gs || !this.turnArrow) return; - - if (this.gameOver) { - this.turnArrow.setVisible(false); - } else { - this.turnArrow.setVisible(true); - const seat = gs.turn; - const pos = this.arrowSeatPos(seat); - if (pos && this._arrowSeat !== seat) { - this._arrowSeat = seat; - const tx = pos.x - pos.r - 18, ty = pos.y; - if (this.turnArrow.x < 0) this.turnArrow.setPosition(tx, ty); - else this.tweens.add({ targets: this.turnArrow, x: tx, y: ty, duration: 600, ease: 'Cubic.Out' }); - } - } - + if (!gs) return; for (let seat = 0; seat < this.playerCount; seat++) { + const active = !this.gameOver && !this._introRunning && gs.turn === seat; + this.banners[seat]?.setActive(active); const dial = this.phaseDials[seat]; if (!dial) continue; - const active = !this.gameOver && gs.turn === seat; dial.setActive(active); if (active) dial.setPhase(gs.phase === 'buy' ? 'buy' : 'action'); } } - // ── Render (dynamic layer) ─────────────────────────────────────────────────── + // ── Card faces (baked textures) ─────────────────────────────────────────── + + buildCardFace(w, h, def, { faceDown = false, dimmed = false, shadow = true } = {}) { + const c = this.add.container(0, 0); + if (shadow) { + const sh = this.add.image(1.5, 3, 'dom-shadow').setDisplaySize(w * (202 / 150), h * (268 / 216)).setAlpha(0.75); + c.add(sh); + } + const key = faceDown || !def + ? backKey(this, this.cardBack?.spriteIndex ?? 0) + : cardKey(this, def.id, w >= 200 ? 'L' : 'M'); + const img = this.add.image(0, 0, key).setDisplaySize(w, h); + if (dimmed) img.setTint(0x6a6a6a); + c.add(img); + c.setData('img', img); + return c; + } + + // ── Render (dynamic layer) ───────────────────────────────────────────────── render() { this._clearHandFx(); @@ -453,6 +318,7 @@ export default class DominionGame extends Phaser.Scene { this.inPlaySprites = []; this.oppHandSprites = {}; this.oppInPlaySprites = {}; + this.oppPiles = {}; this.renderSupply(); this.renderInPlay(); @@ -465,128 +331,230 @@ export default class DominionGame extends Phaser.Scene { renderSupply() { const gs = this.gs; - // Basic supply row; Prosperity inserts Platinum after Gold and Colony after Province. - const base = ['copper', 'silver', 'gold']; - if (gs.supply.platinum !== undefined) base.push('platinum'); - base.push('estate', 'duchy', 'province'); - if (gs.supply.colony !== undefined) base.push('colony'); - base.push('curse'); - this.layoutPileRow(base, 100); - const k = gs.kingdom; - this.layoutPileRow(k.slice(0, 5), 274); - this.layoutPileRow(k.slice(5, 10), 446); - - // Trash indicator - const tx = 1480, ty = 100; - const t = this.add.text(tx, ty, `Trash\n${gs.trash.length}`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, align: 'center', - }).setOrigin(0.5).setDepth(D.supply); - this.dynamicLayer.add(t); - } - - layoutPileRow(ids, y) { - const gap = 16; - const totalW = ids.length * SUPPLY_W + (ids.length - 1) * gap; - const startX = 760 - totalW / 2 + SUPPLY_W / 2; - ids.forEach((id, i) => { - const x = startX + i * (SUPPLY_W + gap); - this.renderPile(id, x, y); + const L = this.L; + for (const t of L.tiles) { + if (gs.supply[t.id] === undefined) continue; + this.renderPile(t.id, t.x, t.y, t.w, t.h, tileKey(this, t.id, t.w, t.h), 'tile'); + } + gs.kingdom.forEach((id, i) => { + const k = L.kingdom[i]; + if (k) this.renderPile(id, k.x, k.y, L.kSize.w, L.kSize.h, cardKey(this, id, 'M'), 'kingdom'); }); + this.renderTrash(); + this.endClock.update(gs.supply, this.pileMax, emptyPileCount(gs), { animate: !this._introRunning }); } - renderPile(id, x, y) { + renderPile(id, x, y, w, h, texKey, kind) { const gs = this.gs; const count = gs.supply[id] ?? 0; + const max = Math.max(1, this.pileMax[id] ?? count); const def = getCard(id); - const face = this.buildCardFace(SUPPLY_W, SUPPLY_H, def, { dimmed: count <= 0 }); - face.setPosition(x, y).setDepth(D.supply); + const parts = []; + + // Stacked card edges: thickness follows the pile's count. + const layers = count <= 0 ? 0 : Math.max(1, Math.ceil(6 * count / max)); + const edges = this.add.graphics(); + edges.fillStyle(0x000000, 0.35); + edges.fillRoundedRect(x - w / 2 + 3, y - h / 2 + 6 + layers * 2.4, w, h, 9); + for (let i = layers; i >= 1; i--) { + const ox = i * 0.5, oy = i * 2.4; + edges.fillStyle(i % 2 ? 0xe6d6ae : 0xcdb98a, 1); + edges.fillRoundedRect(x - w / 2 + ox, y - h / 2 + oy, w, h, 9); + edges.lineStyle(1, 0x3a2810, 0.55); + edges.strokeRoundedRect(x - w / 2 + ox, y - h / 2 + oy, w, h, 9); + } + this.dynamicLayer.add(edges); + parts.push(edges); + + // Buy phase: affordable piles blaze (glow + pulsing edges + running light, + // see _buildSupplyFxItem); everything else on the market dims back. + const p = gs.players[0]; + const humanBuying = !gs.pending && gs.turn === 0 && gs.phase === 'buy' && !this._introRunning && p.buys > 0; + const buyable = humanBuying && count > 0 && p.coins >= buyCost(gs, id) && buyAllowed(gs, id); + if (buyable) { + const glow = this.add.image(x, y - 6, 'dom-glow').setDisplaySize(w * 1.55, h * 1.42) + .setBlendMode(Phaser.BlendModes.ADD).setTint(0xffc21a).setAlpha(0.5); + this.dynamicLayer.add(glow); + const sx = glow.scaleX, sy = glow.scaleY; + this._supplyFxTweens.push(this.tweens.add({ + targets: glow, alpha: 1, scaleX: sx * 1.07, scaleY: sy * 1.07, + duration: 650, yoyo: true, repeat: -1, ease: 'Sine.InOut', + })); + parts.push(glow); + } + + const face = this.add.container(x, y); + const img = this.add.image(0, 0, texKey).setDisplaySize(w, h); + face.add(img); + if (count <= 0) { + img.setTint(0x5a5a5a); + face.add(this.add.image(0, 0, 'dom-seal').setDisplaySize(Math.min(w, h) * 0.62, Math.min(w, h) * 0.62).setAngle(-12)); + } else if (humanBuying && !buyable) { + img.setTint(0x7c7c7c); + } + if (buyable) { + face.setY(y - 6); + // A gentle "breathing" lift, in step with the glow. + this._supplyFxTweens.push(this.tweens.add({ + targets: face, scaleX: 1.035, scaleY: 1.035, duration: 650, yoyo: true, repeat: -1, ease: 'Sine.InOut', + })); + } this.dynamicLayer.add(face); + parts.push(face); - // count badge - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.82); - g.fillCircle(x + SUPPLY_W / 2 - 14, y - SUPPLY_H / 2 + 14, 15); - g.lineStyle(2, COLORS.accent, 1); - g.strokeCircle(x + SUPPLY_W / 2 - 14, y - SUPPLY_H / 2 + 14, 15); - g.setDepth(D.supply + 1); - const ct = this.add.text(x + SUPPLY_W / 2 - 14, y - SUPPLY_H / 2 + 14, `${count}`, { - fontFamily: 'Righteous', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.supply + 1); - this.dynamicLayer.add(g); + // Brass count plaque. + const py = y + h / 2 + (kind === 'tile' ? 12 : 16); + const plq = this.add.image(x, py, 'dom-plaque').setDisplaySize(kind === 'tile' ? 50 : 56, kind === 'tile' ? 20 : 23); + const ct = this.add.text(x, py, `${count}`, SERIF(14, count <= 0 ? '#7a1f1a' : '#2f1f0c')).setOrigin(0.5); + this.dynamicLayer.add(plq); this.dynamicLayer.add(ct); + parts.push(plq, ct); - const hit = this.add.rectangle(x, y, SUPPLY_W, SUPPLY_H, 0x000000, 0).setDepth(D.supply + 2); + const hit = this.add.rectangle(x, y, w, h, 0x000000, 0); this.dynamicLayer.add(hit); this.attachHover(hit, def); - this.supplySprites.push({ id, x, y, hit, face }); + this.supplySprites.push({ id, x, y, w, h, hit, face, parts, kind }); - // Normal buy wiring (human buy phase, no pending). - if (!gs.pending && gs.turn === 0 && gs.phase === 'buy') { - const p = gs.players[0]; - const affordable = count > 0 && p.buys > 0 && p.coins >= buyCost(gs, id) && buyAllowed(gs, id); - if (affordable) { - hit.setInteractive({ useHandCursor: true }); - hit.on('pointerup', () => this.humanBuy(id)); - this.markBuyable(face); - this._buildSupplyFxItem(x, y); - } + if (buyable) { + hit.setInteractive({ useHandCursor: true }); + hit.on('pointerup', () => this.humanBuy(id)); + this._buildSupplyFxItem(x, y - 6, w, h); } } - markBuyable(face) { - const glow = this.add.rectangle(0, 0, SUPPLY_W + 6, SUPPLY_H + 6, COLORS.gold, 0); - glow.setStrokeStyle(3, COLORS.gold, 0.95); - face.addAt(glow, 0); + renderTrash() { + const gs = this.gs; + const tc = this.L.trashCard; + const n = gs.trash.length; + if (n > 0) { + const top = gs.trash[n - 1]; + const face = this.buildCardFace(tc.w, tc.h, getCard(top.id)); + face.setPosition(tc.x, tc.y).setAngle(-4); + if (n > 1) { + const under = this.buildCardFace(tc.w, tc.h, getCard(gs.trash[n - 2].id), { shadow: false }); + under.setPosition(tc.x + 6, tc.y + 4).setAngle(5); + under.getData('img').setTint(0x8a8a8a); + this.dynamicLayer.add(under); + } + this.dynamicLayer.add(face); + } + const py = this.L.trash.y1 - 26; + this.dynamicLayer.add(this.add.image(tc.x, py, 'dom-plaque').setDisplaySize(64, 24)); + this.dynamicLayer.add(this.add.text(tc.x, py, `${n}`, SERIF(14, INK)).setOrigin(0.5)); + const hit = this.add.rectangle(tc.x, tc.y, tc.w + 20, tc.h + 20, 0x000000, 0); + this.dynamicLayer.add(hit); + if (n > 0) { + this.attachHover(hit, getCard(gs.trash[n - 1].id)); + hit.setInteractive({ useHandCursor: true }); + hit.on('pointerup', () => { if (!this._dragState) this.openTrashViewer(); }); + } } _clearSupplyFx() { this._supplyFxEmitters.forEach(e => e.destroy()); this._supplyFxEmitters = []; + this._supplyFxTweens.forEach(t => t.remove()); + this._supplyFxTweens = []; + this._supplyFxGraphics.forEach(g => g.destroy()); + this._supplyFxGraphics = []; } - _buildSupplyFxItem(x, y) { + // Affordable pile: a pulsing amber frame with a white-hot inner line, two + // light "comets" racing round the edge, and sparks lifting off the top. + // Every affordable pile is built in the same render, so they pulse in unison. + _buildSupplyFxItem(x, y, w, h) { const emitter = this.add.particles(x, y, 'dominion-sparkle', { - x: { min: -SUPPLY_W / 2 + 4, max: SUPPLY_W / 2 - 4 }, - y: -SUPPLY_H / 2, - speedX: { min: -18, max: 18 }, - speedY: { min: -70, max: -30 }, + x: { min: -w / 2 + 4, max: w / 2 - 4 }, + y: -h / 2, + speedX: { min: -16, max: 16 }, + speedY: { min: -60, max: -26 }, alpha: { start: 0.9, end: 0 }, - scale: { start: 0.8, end: 0.15 }, + scale: { start: 0.8, end: 0.1 }, lifespan: 900, - frequency: 100, - tint: [0xffffff, 0xffeebb, 0xd4a017, 0xc8a84b], + frequency: 150, + tint: [0xffffff, 0xfff0a0, 0xffc21a], depth: D.supply + 8, }); this._supplyFxEmitters.push(emitter); + + const gfx = this.add.graphics().setDepth(D.supply + 4); + this._supplyFxGraphics.push(gfx); + const pad = 4; + const left = x - w / 2 - pad, top = y - h / 2 - pad, W = w + pad * 2, H = h + pad * 2; + const perim = 2 * (W + H); + const TAIL = Math.min(120, perim * 0.2); + const SEG = 18; + const tracker = { t: 0 }; + this._supplyFxTweens.push(this.tweens.add({ + targets: tracker, t: { from: 0, to: 1 }, duration: 2600, repeat: -1, ease: 'Linear', + onUpdate: () => { + // Two heartbeat pulses per lap (1300ms), matching the glow's yoyo. + const pulse = 0.5 + 0.5 * Math.sin(tracker.t * Math.PI * 4 - Math.PI / 2); + gfx.clear(); + gfx.lineStyle(7 + 5 * pulse, 0xff9d00, 0.12 + 0.2 * pulse); + gfx.strokeRoundedRect(left - 3, top - 3, W + 6, H + 6, 13); + gfx.lineStyle(3 + 2.5 * pulse, 0xffc21a, 0.55 + 0.45 * pulse); + gfx.strokeRoundedRect(left, top, W, H, 11); + gfx.lineStyle(1.5, 0xfff6d0, 0.3 + 0.6 * pulse); + gfx.strokeRoundedRect(left + 3, top + 3, W - 6, H - 6, 9); + for (let c = 0; c < 2; c++) { + const head = ((tracker.t + c / 2) % 1) * perim; + for (let s = 0; s < SEG; s++) { + const f = s / SEG; + const d1 = (head - (1 - f) * TAIL + perim * 100) % perim; + const d2 = (head - (1 - (s + 1) / SEG) * TAIL + perim * 100) % perim; + const [x1, y1] = perimPoint(d1, W, H, left, top); + const [x2, y2] = perimPoint(d2, W, H, left, top); + const tip = f > 0.8; + gfx.lineStyle(tip ? 5 : 3, tip ? 0xffffff : 0xffe066, 0.15 + f * 0.85); + gfx.beginPath(); gfx.moveTo(x1, y1); gfx.lineTo(x2, y2); gfx.strokePath(); + } + } + }, + })); } renderInPlay() { const gs = this.gs; - const p = gs.players[gs.turn]; + const seat = gs.turn; + const p = gs.players[seat]; const cards = p.inPlay; + + // Mat title: whose cards these are. + const lbl = this.add.text(MAT.x0 + 30, RIBBON_Y, `${this.seatName(seat)}'s play`, SERIF(17, '#e9d7a8')) + .setOrigin(0, 0.5); + lbl.setShadow(0, 2, '#000', 3, false, true); + const chip = this.add.rectangle(MAT.x0 + 22, RIBBON_Y, 8, 22, SEAT_COLORS[seat % 4], 1).setStrokeStyle(1, 0xe2c46e, 0.9); + this.dynamicLayer.add(chip); + this.dynamicLayer.add(lbl); if (cards.length === 0) return; - const gap = 8; - const totalW = Math.min(cards.length, 12) * (PLAY_W + gap); - const startX = CX - totalW / 2 + PLAY_W / 2; - cards.slice(0, 12).forEach((c, i) => { + + const { tucked, mult } = tuckInfo(gs.log, seat, cards); + const pos = inPlayPositions(cards.length, tucked); + const order = [...cards.keys()].sort((a, b) => (tucked[b] ? 1 : 0) - (tucked[a] ? 1 : 0)); + for (const i of order) { + const c = cards[i]; const def = getCard(c.id); - const face = this.buildCardFace(PLAY_W, PLAY_H, def); - face.setPosition(startX + i * (PLAY_W + gap), 610).setDepth(D.inplay); + const { x, y } = pos[i]; + const face = this.buildCardFace(PLAY.w, PLAY.h, def); + face.setPosition(x, y); this.dynamicLayer.add(face); - const hit = this.add.rectangle(startX + i * (PLAY_W + gap), 610, PLAY_W, PLAY_H, 0x000000, 0) - .setDepth(D.inplay + 1); + if (tucked[i]) { + const b = this.add.text(x + PLAY.w / 2 - 4, y + PLAY.h / 2 - 4, `×${mult[i]}`, SERIF(15, '#fff6dc', { + backgroundColor: '#7c1f22', padding: { x: 5, y: 1 }, + })).setOrigin(1, 1); + this.dynamicLayer.add(b); + } + const hit = this.add.rectangle(x, y, PLAY.w, PLAY.h, 0x000000, 0); this.dynamicLayer.add(hit); this.attachHover(hit, def); - this.inPlaySprites.push({ iid: c.iid, id: c.id, x: startX + i * (PLAY_W + gap), y: 610, face }); - if (gs.turn !== 0) { - if (!this.oppInPlaySprites[gs.turn]) this.oppInPlaySprites[gs.turn] = []; - this.oppInPlaySprites[gs.turn].push({ iid: c.iid, id: c.id, x: startX + i * (PLAY_W + gap), y: 610, face }); + const sp = { iid: c.iid, id: c.id, x, y, face }; + this.inPlaySprites.push(sp); + if (seat !== 0) { + if (!this.oppInPlaySprites[seat]) this.oppInPlaySprites[seat] = []; + this.oppInPlaySprites[seat].push(sp); } - }); - const lbl = this.add.text(CX, 540, `${this.seatName(gs.turn)} — in play`, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.inplay); - this.dynamicLayer.add(lbl); + } } renderHand() { @@ -594,11 +562,8 @@ export default class DominionGame extends Phaser.Scene { const rawHand = gs.players[0].hand; this._reconcileHandOrder(rawHand); const hand = this._getOrderedHand(rawHand); - const gap = Math.min(18, (1300 - hand.length * HAND_W) / Math.max(1, hand.length - 1)); - const step = HAND_W + Math.max(-HAND_W * 0.45, gap); - const totalW = (hand.length - 1) * step + HAND_W; - const startX = CX - totalW / 2 + HAND_W / 2; - const baseY = 968; + const { xs } = handPositions(hand.length); + const baseY = HAND_Y; const canPlayAction = !gs.pending && gs.turn === 0 && gs.phase === 'action' && gs.players[0].actions > 0; const canPlayTreasure = !gs.pending && gs.turn === 0 && gs.phase === 'buy'; @@ -606,15 +571,15 @@ export default class DominionGame extends Phaser.Scene { hand.forEach((c, i) => { const def = getCard(c.id); - const x = startX + i * step; + const x = xs[i]; const isPlayableAction = canPlayAction && legalAct.has(c.iid); const isPlayableTreasure = canPlayTreasure && isType(c.id, 'treasure'); - const face = this.buildCardFace(HAND_W, HAND_H, def); - face.setPosition(x, baseY).setDepth(D.hand + i); + const face = this.buildCardFace(HAND.w, HAND.h, def); + face.setPosition(x, baseY); if (this._animatingIids.has(c.iid)) face.setAlpha(0); else if (this._dragState?.iid === c.iid) face.setAlpha(0.2); this.dynamicLayer.add(face); - const hit = this.add.rectangle(x, baseY, HAND_W, HAND_H, 0x000000, 0).setDepth(D.hand + i + 1); + const hit = this.add.rectangle(x, baseY, HAND.w, HAND.h, 0x000000, 0); this.dynamicLayer.add(hit); // Only attach hover and interactivity once the card is visible (not animating in). if (!this._animatingIids.has(c.iid)) { @@ -642,8 +607,8 @@ export default class DominionGame extends Phaser.Scene { } highlightFace(face, color) { - const glow = this.add.rectangle(0, 0, HAND_W + 6, HAND_H + 6, color, 0); - glow.setStrokeStyle(3, color, 0.9); + const glow = this.add.image(0, 0, 'dom-glow').setDisplaySize(HAND.w * (210 / 150), HAND.h * (276 / 216)) + .setTint(color).setBlendMode(Phaser.BlendModes.ADD); face.addAt(glow, 0); } @@ -659,7 +624,7 @@ export default class DominionGame extends Phaser.Scene { gfx.setDepth(D.hand + 25); this._handFxGraphics.push(gfx); - const W = HAND_W, H = HAND_H; + const W = HAND.w, H = HAND.h; const perim = 2 * (W + H); const TAIL_PX = 90; const SEGMENTS = 20; @@ -676,9 +641,10 @@ export default class DominionGame extends Phaser.Scene { const left = hs.x - W / 2; const top = hs.face.y - H / 2; gfx.clear(); + gfx.setAlpha(hs.face.alpha); gfx.lineStyle(2, color, 0.2); - gfx.strokeRect(left, top, W, H); + gfx.strokeRoundedRect(left, top, W, H, 10); for (let c = 0; c < COMETS; c++) { const headDist = ((tracker.t + c / COMETS) % 1) * perim; @@ -703,410 +669,157 @@ export default class DominionGame extends Phaser.Scene { this._handFxTweens.push(tween); } + // Count badge (dark disc, gold ring, serif number). + _badge(x, y, text, r = 20, size = 20) { + const g = this.add.graphics(); + g.fillStyle(0x000000, 0.45); g.fillCircle(x + 1, y + 2, r + 1); + g.fillStyle(0x1c120a, 0.92); g.fillCircle(x, y, r); + g.lineStyle(2, 0xc9a24e, 1); g.strokeCircle(x, y, r); + const t = this.add.text(x, y, text, SERIF(size, '#f6d77a')).setOrigin(0.5); + this.dynamicLayer.add(g); + this.dynamicLayer.add(t); + return { g, t }; + } + + _deckEdges(x, y, w, h, n, perCard = 0.22, maxLayers = 9) { + const layers = Math.min(maxLayers, Math.ceil(n * perCard)); + if (layers <= 0) return; + const g = this.add.graphics(); + for (let i = layers; i >= 1; i--) { + g.fillStyle(i % 2 ? 0x2a1a0e : 0x3a2614, 1); + g.fillRoundedRect(x - w / 2 - i * 0.4, y - h / 2 + i * 1.6, w, h, Math.max(3, w * 0.065)); + } + this.dynamicLayer.add(g); + } + renderCounts() { const gs = this.gs; - const displayDeck = this._deckAnimDisplay ?? gs.players[0].deck.length; - const displayDiscard = this._discardAnimDisplay ?? gs.players[0].discard.length; + const me = gs.players[0]; + const displayDeck = this._deckAnimDisplay ?? me.deck.length; + const displayDiscard = this._discardAnimDisplay ?? me.discard.length; - // Human deck — face-down card pile with count badge - const deckPile = this.buildCardFace(HAND_W, HAND_H, null, { faceDown: true }); - deckPile.setPosition(DECK_PILE_X, DECK_PILE_Y).setDepth(D.hand); + // Human deck — face-down stack with count badge. + this._deckEdges(DECK.x, DECK.y, HAND.w, HAND.h, displayDeck); + const deckPile = this.buildCardFace(HAND.w, HAND.h, null, { faceDown: true }); + deckPile.setPosition(DECK.x, DECK.y); deckPile.setVisible(displayDeck > 0); this.dynamicLayer.add(deckPile); - const dcBg = this.add.graphics(); - dcBg.fillStyle(0x000000, 0.72); - dcBg.fillCircle(DECK_PILE_X, DECK_PILE_Y, 22); - dcBg.lineStyle(2, COLORS.accent, 1); - dcBg.strokeCircle(DECK_PILE_X, DECK_PILE_Y, 22); - dcBg.setDepth(D.hand + 1); - dcBg.setVisible(displayDeck > 0); - const dcText = this.add.text(DECK_PILE_X, DECK_PILE_Y, `${displayDeck}`, { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.hand + 1); - dcText.setVisible(displayDeck > 0); - this.dynamicLayer.add(dcBg); - this.dynamicLayer.add(dcText); + const db = this._badge(DECK.x, DECK.y, `${displayDeck}`, 22, 22); + db.g.setVisible(displayDeck > 0); db.t.setVisible(displayDeck > 0); this._liveDeckPile = deckPile; - this._liveDeckBadge = dcBg; - this._liveDeckCountText = dcText; + this._liveDeckBadge = db.g; + this._liveDeckCountText = db.t; - // Human discard pile — face-down card with count badge - const discardPile = this.buildCardFace(HAND_W, HAND_H, null, { faceDown: true }); - discardPile.setPosition(DISCARD_PILE_X, DISCARD_PILE_Y).setDepth(D.hand); + // Human discard — face-up, showing its top card. + // Mid-animation (before a shuffle lands) the state's discard may already be + // empty while the pile is still on the table: show the last card that landed. + const topId = me.discard[me.discard.length - 1]?.id ?? (displayDiscard > 0 ? this._lastDiscardTopId : null); + const topCard = topId ? { id: topId } : null; + const discardPile = this.buildCardFace(HAND.w, HAND.h, topCard ? getCard(topCard.id) : null, { faceDown: !topCard }); + discardPile.setPosition(DISCARD.x, DISCARD.y); discardPile.setVisible(displayDiscard > 0); this.dynamicLayer.add(discardPile); - const dpBg = this.add.graphics(); - dpBg.fillStyle(0x000000, 0.72); - dpBg.fillCircle(DISCARD_PILE_X, DISCARD_PILE_Y, 22); - dpBg.lineStyle(2, COLORS.accent, 1); - dpBg.strokeCircle(DISCARD_PILE_X, DISCARD_PILE_Y, 22); - dpBg.setDepth(D.hand + 1); - dpBg.setVisible(displayDiscard > 0); - const dpText = this.add.text(DISCARD_PILE_X, DISCARD_PILE_Y, `${displayDiscard}`, { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.hand + 1); - dpText.setVisible(displayDiscard > 0); - this.dynamicLayer.add(dpBg); - this.dynamicLayer.add(dpText); + const bx = DISCARD.x + HAND.w / 2 - 6, by = DISCARD.y - HAND.h / 2 + 6; + const dbd = this._badge(bx, by, `${displayDiscard}`, 19, 18); + dbd.g.setVisible(displayDiscard > 0); dbd.t.setVisible(displayDiscard > 0); + if (topCard) { + const hit = this.add.rectangle(DISCARD.x, DISCARD.y, HAND.w, HAND.h, 0x000000, 0); + this.dynamicLayer.add(hit); + this.attachHover(hit, getCard(topCard.id)); + } this._liveDiscardPile = discardPile; - this._liveDiscardBadge = dpBg; - this._liveDiscardCountText = dpText; + this._liveDiscardBadge = dbd.g; + this._liveDiscardCountText = dbd.t; + this._liveDiscardTop = discardPile.getData('img'); + // Opponent plates: mini deck, face-up discard, hand fan. this.opponents.forEach((opp, i) => { const seat = i + 1; const p = gs.players[seat]; - const s = this.oppSlot(i); - const active = gs.turn === seat; - const txt = `Hand ${p.hand.length} Deck ${p.deck.length} Disc ${p.discard.length}`; - this.dynamicLayer.add(this.add.text(s.x, s.y + s.r + 38, txt, { - fontFamily: '"Julius Sans One"', fontSize: '15px', - color: active ? COLORS.goldHex : COLORS.mutedHex, align: 'center', - backgroundColor: 'rgba(0,0,0,0.55)', padding: { x: 8, y: 4 }, - }).setOrigin(0.5).setDepth(D.hud)); + const pl = this.plate(seat); + if (!pl) return; + this.oppPiles[seat] = { deck: pl.deck, discard: pl.discard }; + + this._deckEdges(pl.deck.x, pl.deck.y, MINI_DISC.w, MINI_DISC.h, p.deck.length, 0.18, 5); + if (p.deck.length > 0) { + const d = this.buildCardFace(MINI_DISC.w, MINI_DISC.h, null, { faceDown: true }); + d.setPosition(pl.deck.x, pl.deck.y); + this.dynamicLayer.add(d); + } + const top = p.discard[p.discard.length - 1]; + if (top) { + const d = this.buildCardFace(MINI_DISC.w, MINI_DISC.h, getCard(top.id)); + d.setPosition(pl.discard.x, pl.discard.y); + this.dynamicLayer.add(d); + const hit = this.add.rectangle(pl.discard.x, pl.discard.y, MINI_DISC.w, MINI_DISC.h, 0x000000, 0); + this.dynamicLayer.add(hit); + this.attachHover(hit, getCard(top.id)); + } + const capY = pl.deck.y + MINI_DISC.h / 2 + 9; + const cap = (x, s) => this.dynamicLayer.add(this.add.text(x, capY, s, SERIF(12, '#d9c8a0', { fontStyle: 'normal' })).setOrigin(0.5)); + cap(pl.deck.x, `Deck ${p.deck.length}`); + cap(pl.discard.x, `Disc ${p.discard.length}`); - // Mini face-down cards representing the opponent's hand const handSize = p.hand.length; this.oppHandSprites[seat] = []; - if (handSize > 0) { - const gap = Math.min(4, (200 - handSize * OPP_W) / Math.max(1, handSize - 1)); - const step = OPP_W + Math.max(-OPP_W * 0.6, gap); - const totalW = (handSize - 1) * step + OPP_W; - const startX = s.x - totalW / 2 + OPP_W / 2; - const cardY = s.y + s.r + 75; - for (let j = 0; j < handSize; j++) { - const c = p.hand[j]; - const mini = this.buildCardFace(OPP_W, OPP_H, null, { faceDown: true }); - mini.setPosition(startX + j * step, cardY).setDepth(D.hud + j); - this.dynamicLayer.add(mini); - this.oppHandSprites[seat].push({ iid: c.iid, id: c.id, x: startX + j * step, y: cardY, face: mini }); - } + const { xs } = oppHandPositions(pl, handSize); + for (let j = 0; j < handSize; j++) { + const c = p.hand[j]; + const mini = this.buildCardFace(MINI.w, MINI.h, null, { faceDown: true, shadow: j === 0 }); + mini.setPosition(xs[j], pl.hand.y).setAngle((j - (handSize - 1) / 2) * 2.5); + this.dynamicLayer.add(mini); + this.oppHandSprites[seat].push({ iid: c.iid, id: c.id, x: xs[j], y: pl.hand.y, face: mini }); } + cap(pl.hand.x, `Hand ${handSize}`); }); } renderHud() { const gs = this.gs; - const p = gs.players[gs.turn]; - const turnName = this.seatName(gs.turn); - const phaseLbl = gs.phase === 'action' ? 'Action Phase' : gs.phase === 'buy' ? 'Buy Phase' : ''; + const seat = gs.turn; + const me = gs.players[seat]; - this.dynamicLayer.add(this.add.text(CX, 700, `${turnName}'s turn — ${phaseLbl}`, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.hud)); - - const me = gs.players[gs.turn]; - const stat = `Actions ${me.actions} Buys ${me.buys} Coins ${me.coins}`; - this.dynamicLayer.add(this.add.text(CX, 742, stat, { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, - backgroundColor: 'rgba(0,0,0,0.5)', padding: { x: 14, y: 6 }, - }).setOrigin(0.5).setDepth(D.hud)); - - const provLeft = gs.supply.province ?? 0; - const colonyNote = gs.supply.colony !== undefined ? ` Colonies left: ${gs.supply.colony ?? 0}` : ''; - this.dynamicLayer.add(this.add.text(CX, 786, `Provinces left: ${provLeft}${colonyNote} Empty piles: ${emptyPileCount(gs)}/3`, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.hud)); - - this.renderVpTokens(); - } - - // VP-token badges (Prosperity: Monument, Bishop, …). Drawn per seat near each - // portrait; only shown for seats that have accrued tokens. - renderVpTokens() { - const gs = this.gs; - gs.players.forEach((p, seat) => { - const n = p.vpTokens ?? 0; - if (n <= 0) return; - const pos = seat === 0 ? { x: 92 + 46, y: 928 - 46 } : (() => { - const s = this.oppSlot(seat - 1); return { x: s.x - s.r - 6, y: s.y - s.r - 2 }; - })(); - const g = this.add.graphics().setDepth(D.hud + 1); - g.fillStyle(0x000000, 0.82); g.fillCircle(pos.x, pos.y, 18); - g.lineStyle(2, COLORS.gold, 1); g.strokeCircle(pos.x, pos.y, 18); - this.dynamicLayer.add(g); - this.dynamicLayer.add(this.add.text(pos.x, pos.y, `★${n}`, { - fontFamily: 'Righteous', fontSize: '14px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.hud + 2)); - }); - } - - // ── Floating token sprites (Prosperity expansion) ───────────────────────────── - // Spawns a token sprite above the player's phase dial with random position - // and rotation when VP tokens or gold are earned. - - // Phase dial anchor positions (mirrors buildPhaseDials). - _dialPos(seat) { - if (seat === 0) return { x: 168, y: 748 }; - const s = this.oppSlot(seat - 1); - const r = 26; - return { x: s.x + s.r + 14 + r, y: s.y }; - } - - spawnTokenSprite(seat, tokenType) { - // tokenType: 'vp1', 'vp5', or 'gold' - const spriteMap = { vp1: 0, vp5: 1, gold: 2 }; - const frameIndex = spriteMap[tokenType]; - if (frameIndex === undefined || !this.textures.exists('dominion-tokens')) return; - - const dial = this._dialPos(seat); - // Random position in a ~200×250 area above the dial - const offsetX = Phaser.Math.Between(-100, 100); - const offsetY = Phaser.Math.Between(-400, -200); - const x = dial.x + offsetX; - const y = dial.y + offsetY; - // Clamp to visible area - const clampedX = Phaser.Math.Clamp(x, 75, GAME_WIDTH - 75); - const clampedY = Phaser.Math.Clamp(y, 50, GAME_HEIGHT - 50); - - const angle = Phaser.Math.Between(-35, 35); - const targetScale = 80 / 150; // 80px final size from 150px source - - const sprite = this.add.sprite(clampedX, clampedY, 'dominion-tokens', frameIndex) - .setDisplaySize(80, 80) - .setAngle(angle) - .setDepth(D.popup) - .setAlpha(0) - .setScale(1.5) - .setData('tokenType', tokenType); - - this.tokenSprites.push(sprite); - - // Animate from larger size down to 80×80 — token stays for the rest of the game - this.tweens.add({ - targets: sprite, - alpha: 0.92, - scaleX: targetScale, - scaleY: targetScale, - duration: 1200, - ease: 'Back.easeOut', - }); - } - - // Count 1-VP tokens currently visible in the placement area (above human player's dial) - _countOneVpTokens() { - const dial = this._dialPos(0); - let count = 0; - for (const s of this.tokenSprites) { - if (s.getData('tokenType') === 'vp1' && - s.active && s.alpha > 0.1 && - s.y < dial.y - 200) { // in the area above the dial - count++; - } + // Coins fly from the last Treasure on the mat into the purse. + let from = { x: rectCX(MAT), y: rectCY(MAT) }; + for (let i = this.inPlaySprites.length - 1; i >= 0; i--) { + const sp = this.inPlaySprites[i]; + if (isType(sp.id, 'treasure')) { from = { x: sp.x, y: sp.y }; break; } } - return count; - } + this.tray.update({ actions: me.actions, buys: me.buys, coins: me.coins, seat }, { animate: !this._introRunning, coinsFrom: from }); - // Remove all 1-VP tokens from the placement area with a fade-out - _removeOneVpTokens() { - for (const s of this.tokenSprites) { - if (s.getData('tokenType') === 'vp1' && s.active && s.alpha > 0.1 && s.y < this._dialPos(0).y - 200) { - this.tweens.add({ - targets: s, - alpha: 0, - duration: 400, - ease: 'Sine.In', - onComplete: () => { - const idx = this.tokenSprites.indexOf(s); - if (idx > -1) this.tokenSprites.splice(idx, 1); - s.destroy(); - }, - }); - } - } - } + gs.players.forEach((p, s) => this.vpDishes[s]?.update(p.vpTokens ?? 0, { animate: !this._introRunning })); - _checkTokenGains(prevState, newState) { - const prevVp = this.lastVpTokens; - const newVp = {}; - newState.players.forEach((p, seat) => { newVp[seat] = p.vpTokens ?? 0; }); - - // Only show token animations for the human player (seat 0) - const humanSeat = 0; - const diff = newVp[humanSeat] - (prevVp[humanSeat] ?? 0); - if (diff > 0) { - // Keep replacing 1-VP tokens with 5-VP tokens until we can't anymore - let remaining = diff; - while (remaining > 0) { - const currentOneVp = this._countOneVpTokens(); - if (currentOneVp > 0 && currentOneVp < 5 && currentOneVp + remaining >= 5) { - // Remove all 1-VP tokens and spawn one 5-VP token - this._removeOneVpTokens(); - this.spawnTokenSprite(humanSeat, 'vp5'); - remaining -= (5 - currentOneVp); - } else if (remaining >= 5) { - // No 1-VP tokens on screen, but we have 5+ to spend — spawn a 5-VP token - this.spawnTokenSprite(humanSeat, 'vp5'); - remaining -= 5; - } else { - // Just spawn 1-VP tokens - for (let i = 0; i < remaining; i++) { - this.spawnTokenSprite(humanSeat, 'vp1'); - } - remaining = 0; - } - } - } - this.lastVpTokens = newVp; - - // Detect gold gains from log events (human player only) - const newLog = newState.log.slice(prevState.log.length); - for (const evt of newLog) { - if (evt.kind === 'gain' && evt.id === 'gold' && evt.seat === humanSeat) { - this.spawnTokenSprite(humanSeat, 'gold'); - } + // Dock status line when it's not the human's move. + const humanMove = gs.turn === 0 && !gs.pending && !this.gameOver; + const humanPrompt = gs.pending?.seat === 0; + if (!humanMove && !humanPrompt && !this.gameOver && !this._introRunning) { + const phase = gs.phase === 'buy' ? 'buying' : 'playing actions'; + const who = gs.pending ? `${this.seatName(gs.pending.seat)} is deciding…` : `${this.seatName(seat)} is ${phase}…`; + const t = this.add.text(rectCX(DOCK), rectCY(DOCK), who, SERIF(18, '#e9d7a8', { fontStyle: 'italic' })).setOrigin(0.5); + t.setShadow(0, 2, '#000', 3, false, true); + this.dynamicLayer.add(t); } } updateControls() { const gs = this.gs; - const humanTurn = gs.turn === 0 && !gs.pending && !this.gameOver && !this._animating; + const humanTurn = gs.turn === 0 && !gs.pending && !this.gameOver && !this._animating && !this._introRunning; const action = humanTurn && gs.phase === 'action'; const buy = humanTurn && gs.phase === 'buy'; + const hasTreasure = buy && gs.players[0].hand.some((c) => isType(c.id, 'treasure')); this.btnEndAction.setVisible(action); + this.btnPlayTreasures.setVisible(hasTreasure); this.btnEndTurn.setVisible(buy); - } - - // ── Card face builder ─────────────────────────────────────────────────────── - - buildCardFace(w, h, def, { faceDown = false, dimmed = false } = {}) { - const c = this.add.container(0, 0); - const style = typeStyle(def); - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.35); g.fillRoundedRect(-w / 2 + 2, -h / 2 + 3, w, h, 8); - g.fillStyle(0x14110b, 1); g.fillRoundedRect(-w / 2, -h / 2, w, h, 8); - g.lineStyle(2, style.border, 1); g.strokeRoundedRect(-w / 2, -h / 2, w, h, 8); - c.add(g); - - if (faceDown) { - if (this.textures.exists('cardbacks')) { - c.add(this.add.image(0, 0, 'cardbacks', this.cardBack?.spriteIndex ?? 0).setDisplaySize(w - 6, h - 6)); - } else { - c.add(this.add.rectangle(0, 0, w - 8, h - 8, 0x2a2a40)); - } - if (dimmed) c.add(this.add.rectangle(0, 0, w, h, 0x000000, 0.5)); - return c; - } - - const artH = h * 0.58; - const artTop = -h / 2; - const bandTop = artTop + artH; - const fsTitle = Phaser.Math.Clamp(Math.round(h * 0.085), 9, 20); - const fsType = Phaser.Math.Clamp(Math.round(h * 0.05), 7, 12); - - const sheetKey = def.sheet ?? 'dominion-cards'; - if (this.textures.exists(sheetKey)) { - c.add(this.add.image(0, 0, sheetKey, def.frame).setDisplaySize(w - 6, h - 6)); - // legibility band over the lower portion - c.add(this.add.rectangle(0, bandTop + (h / 2 - bandTop) / 2, w - 6, h / 2 - bandTop, style.band, 0.9)); + const y = rectCY(DOCK); + if (hasTreasure) { + this.btnPlayTreasures.setPosition(rectCX(DOCK) - 118, y); + this.btnEndTurn.setPosition(rectCX(DOCK) + 118, y); } else { - c.add(this.add.rectangle(0, artTop + artH / 2, w - 8, artH - 4, style.art)); - c.add(this.add.rectangle(0, bandTop + (h / 2 - bandTop) / 2, w - 6, h / 2 - bandTop, style.band, 0.95)); - // placeholder: name in the art area for identification - c.add(this.add.text(0, artTop + artH / 2, def.name, { - fontFamily: 'Righteous', fontSize: `${fsTitle}px`, color: '#1a1208', - align: 'center', wordWrap: { width: w - 16 }, - }).setOrigin(0.5)); - } - - // Title in the band - c.add(this.add.text(0, bandTop + fsTitle * 0.9, def.name, { - fontFamily: 'Righteous', fontSize: `${fsTitle}px`, color: COLORS.textHex, - align: 'center', wordWrap: { width: w - 12 }, - }).setOrigin(0.5, 0.5)); - - // Type line (small) - c.add(this.add.text(0, h / 2 - fsType * 1.2, typeLine(def), { - fontFamily: '"Julius Sans One"', fontSize: `${fsType}px`, color: COLORS.mutedHex, - }).setOrigin(0.5)); - - // Icon row (between title and type line) - this.addIconRow(c, def, 0, bandTop + (h / 2 - bandTop) * 0.55, h, w); - - // Cost coin (top-left) - this.addCoinBadge(c, -w / 2 + 14, -h / 2 + 14, def.cost, Math.round(h * 0.075)); - - // VP badge (top-right) for victory cards - if (isType(def.id, 'victory')) { - const vpLabel = def.id === 'gardens' ? '★' : `${def.vp}`; - this.addVpBadge(c, w / 2 - 14, -h / 2 + 14, vpLabel, Math.round(h * 0.075)); - } - - if (dimmed) c.add(this.add.rectangle(0, 0, w, h, 0x000000, 0.5)); - return c; - } - - addIconRow(container, def, cx, cy, h, w = Infinity) { - const tokens = []; - if (def.plus.cards) tokens.push(['cards', def.plus.cards, 0x2f6fb0]); - if (def.plus.actions) tokens.push(['action', def.plus.actions, 0x3f9b54]); - if (def.plus.buys) tokens.push(['buy', def.plus.buys, 0x8a5fb0]); - if (def.plus.coins) tokens.push(['$', def.plus.coins, 0xd4a017]); - if (def.coin !== undefined) tokens.push(['$', def.coin, 0xd4a017]); // treasure value - if (tokens.length === 0) return; - - const fs0 = Phaser.Math.Clamp(Math.round(h * 0.06), 8, 13); - let tw = fs0 * 4.2; - let fs = fs0; - const gap = 4; - const maxW = w - 8; - - const nominalTotalW = tokens.length * tw + (tokens.length - 1) * gap; - if (nominalTotalW > maxW) { - tw = (maxW - (tokens.length - 1) * gap) / tokens.length; - fs = Math.floor(tw / 4.2); - if (fs < 7) { - const barGap = 2; - const barW = (maxW - (tokens.length - 1) * barGap) / tokens.length; - const barH = Math.max(3, Math.round(h * 0.025)); - let bx = cx - maxW / 2 + barW / 2; - for (const [, , color] of tokens) { - const bar = this.add.rectangle(bx, cy, barW, barH, color, 0.9); - bar.setStrokeStyle(0.5, 0x000000, 0.3); - container.add(bar); - bx += barW + barGap; - } - return; - } - } - - const totalW = tokens.length * tw + (tokens.length - 1) * gap; - let x = cx - totalW / 2 + tw / 2; - for (const [kind, val, color] of tokens) { - const pill = this.add.rectangle(x, cy, tw, fs * 1.7, color, 0.95); - pill.setStrokeStyle(1, 0x000000, 0.4); - container.add(pill); - const label = kind === '$' ? `+${val}$` - : kind === 'cards' ? `+${val}C` - : kind === 'action' ? `+${val}A` - : `+${val}B`; - container.add(this.add.text(x, cy, label, { - fontFamily: 'Righteous', fontSize: `${fs}px`, color: '#ffffff', - }).setOrigin(0.5)); - x += tw + gap; + this.btnEndTurn.setPosition(rectCX(DOCK), y); } } - addCoinBadge(container, x, y, value, r) { - const g = this.add.graphics(); - g.fillStyle(0xd4a017, 1); g.fillCircle(x, y, r); - g.lineStyle(1.5, 0x6b5310, 1); g.strokeCircle(x, y, r); - container.add(g); - container.add(this.add.text(x, y, `${value}`, { - fontFamily: 'Righteous', fontSize: `${Math.round(r * 1.2)}px`, color: '#1a1208', - }).setOrigin(0.5)); - } - - addVpBadge(container, x, y, label, r) { - const g = this.add.graphics(); - g.fillStyle(0x2e7d4f, 1); g.fillCircle(x, y, r); - g.lineStyle(1.5, 0x14241a, 1); g.strokeCircle(x, y, r); - container.add(g); - container.add(this.add.text(x, y, `${label}`, { - fontFamily: 'Righteous', fontSize: `${Math.round(r * 1.1)}px`, color: '#ffffff', - }).setOrigin(0.5)); - } - - // ── Hover popup ─────────────────────────────────────────────────────────────── + // ── Hover popup ───────────────────────────────────────────────────────────── buildHoverPopup() { this.hoverPopup = this.add.container(-9999, -9999).setDepth(D.popup).setVisible(false); @@ -1126,39 +839,25 @@ export default class DominionGame extends Phaser.Scene { showHover(def) { this.hoverPopup.removeAll(true); - - const W_CARD = 264, H_CARD = 380; - const PAD = 20, GAP = 16; - const W_POP = W_CARD + PAD * 2; - - const hasText = def.text && def.text.trim().length > 0; - const rulesText = hasText - ? this.add.text(0, 0, def.text, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.textHex, - align: 'center', wordWrap: { width: W_CARD }, - }).setOrigin(0.5, 0) - : null; - - const totalH = PAD + H_CARD + (hasText ? GAP + rulesText.height + PAD : PAD); - const halfH = totalH / 2; - - const bg = this.add.graphics(); - bg.fillStyle(0x0d1117, 0.97); - bg.fillRoundedRect(-W_POP / 2, -halfH, W_POP, totalH, 14); - bg.lineStyle(2, COLORS.accent, 0.95); - bg.strokeRoundedRect(-W_POP / 2, -halfH, W_POP, totalH, 14); - - const cardFace = this.buildCardFace(W_CARD, H_CARD, def); - - this.hoverPopup.add(bg); - this.hoverPopup.add(cardFace); - cardFace.setPosition(0, -halfH + PAD + H_CARD / 2); - - if (rulesText) { - this.hoverPopup.add(rulesText); - rulesText.setPosition(0, -halfH + PAD + H_CARD + GAP); + const PAD = 14; + let note = null; + if (def.id === 'gardens' && this.gs) { + const me = this.gs.players[0]; + const n = me.deck.length + me.hand.length + me.discard.length + me.inPlay.length; + note = `Worth ${Math.floor(n / 10)} VP to you now (${n} cards)`; } - + const noteText = note ? this.add.text(0, 0, note, SERIF(15, '#f6d77a', { fontStyle: 'italic' })).setOrigin(0.5, 0) : null; + const W_POP = HOVER.w + PAD * 2; + const totalH = PAD + HOVER.h + (noteText ? 10 + noteText.height + PAD : PAD); + const halfH = totalH / 2; + const bg = this.add.graphics(); + bg.fillStyle(0x000000, 0.45); bg.fillRoundedRect(-W_POP / 2 + 4, -halfH + 6, W_POP, totalH, 14); + bg.fillStyle(0x1c120a, 0.96); bg.fillRoundedRect(-W_POP / 2, -halfH, W_POP, totalH, 14); + bg.lineStyle(2, 0xc9a24e, 0.95); bg.strokeRoundedRect(-W_POP / 2, -halfH, W_POP, totalH, 14); + this.hoverPopup.add(bg); + const card = this.add.image(0, -halfH + PAD + HOVER.h / 2, cardKey(this, def.id, 'L')).setDisplaySize(HOVER.w, HOVER.h); + this.hoverPopup.add(card); + if (noteText) { noteText.setPosition(0, -halfH + PAD + HOVER.h + 10); this.hoverPopup.add(noteText); } this.hoverPopup.setData('w', W_POP); this.hoverPopup.setData('h', totalH); this.hoverVisible = true; @@ -1170,7 +869,9 @@ export default class DominionGame extends Phaser.Scene { positionHover(px, py) { const w = this.hoverPopup.getData('w') ?? 360; const h = this.hoverPopup.getData('h') ?? 200; - const x = Phaser.Math.Clamp(px + w / 2 + 24, w / 2 + 8, GAME_WIDTH - w / 2 - 8); + let x = px + w / 2 + 24; + if (x + w / 2 > GAME_WIDTH - 8) x = px - w / 2 - 24; + x = Phaser.Math.Clamp(x, w / 2 + 8, GAME_WIDTH - w / 2 - 8); const y = Phaser.Math.Clamp(py, h / 2 + 8, GAME_HEIGHT - h / 2 - 8); this.hoverPopup.setPosition(x, y); } @@ -1180,15 +881,88 @@ export default class DominionGame extends Phaser.Scene { this.hoverPopup.setVisible(false).setPosition(-9999, -9999); } + // ── Kingdom reveal (game start) ───────────────────────────────────────────── + + _playKingdomReveal(done) { + const gs = this.gs; + const timers = []; + let finished = false; + const all = this.supplySprites; + for (const sp of all) sp.parts.forEach((o) => o.setAlpha(0)); + const ribbonW = 700; + const rib = addRibbon(this, rectCX(this.L.runner), 266, ribbonW, '#7c1f22').setDepth(D.prompt).setAlpha(0); + const t1 = this.add.text(rib.x, 264, `Kingdom: ${presetLabel(this.deckMode)} · ${EXPANSION_LABELS[this.expansion] ?? this.expansion}`, SERIF(24, '#fbefcf')) + .setOrigin(0.5).setDepth(D.prompt + 1).setAlpha(0); + t1.setShadow(0, 2, '#000', 4, false, true); + if (t1.width > ribbonW - 30) t1.setScale((ribbonW - 30) / t1.width); + const intro = [rib, t1]; + this.tweens.add({ targets: intro, alpha: 1, duration: 350 }); + + const tiles = all.filter((s) => s.kind === 'tile'); + const kings = gs.kingdom.map((id) => all.find((s) => s.kind === 'kingdom' && s.id === id)).filter(Boolean); + const special = tiles.filter((s) => s.id === 'platinum' || s.id === 'colony'); + tiles.forEach((sp, i) => { + timers.push(this.time.delayedCall(250 + i * 60, () => { + this.tweens.add({ targets: sp.parts, alpha: 1, duration: 220 }); + })); + }); + const k0 = 250 + tiles.length * 60 + 200; + kings.forEach((sp, i) => { + timers.push(this.time.delayedCall(k0 + i * 170, () => { + playSound(this, SFX.CARD_SHOW); + const others = sp.parts.filter((o) => o !== sp.face); + this.tweens.add({ targets: others, alpha: 1, duration: 200 }); + const fy = sp.face.y; + sp.face.setAlpha(1).setScale(0, 1).setY(fy - 24); + this.tweens.add({ targets: sp.face, scaleX: 1, y: fy, duration: 260, ease: 'Back.Out' }); + })); + }); + const kEnd = k0 + kings.length * 170 + 200; + special.forEach((sp, i) => { + timers.push(this.time.delayedCall(kEnd + i * 160, () => { + playSound(this, SFX.COINS); + this.tweens.add({ targets: sp.face, scale: { from: 1.25, to: 1 }, duration: 420, ease: 'Back.Out' }); + const em = this.add.particles(sp.x, sp.y, 'dominion-sparkle', { + speed: { min: 60, max: 180 }, lifespan: 700, quantity: 24, emitting: false, + scale: { start: 1, end: 0 }, tint: [0xffeebb, 0xd4a017], depth: D.prompt, + }); + em.explode(24); + this.time.delayedCall(900, () => em.destroy()); + })); + }); + const end = kEnd + special.length * 160 + 900; + const finish = () => { + if (finished) return; + finished = true; + timers.forEach((t) => t.remove()); + this.input.off('pointerdown', skip); + for (const sp of all) { + sp.parts.forEach((o) => { this.tweens.killTweensOf(o); o.setAlpha(1); }); + sp.face.setScale(1); + } + this.tweens.add({ targets: intro, alpha: 0, duration: 300, onComplete: () => intro.forEach((o) => o.destroy()) }); + this.render(); + done(); + }; + const skip = () => finish(); + this.time.delayedCall(300, () => { if (!finished) this.input.once('pointerdown', skip); }); + timers.push(this.time.delayedCall(end, finish)); + } + // ── Turn driver ─────────────────────────────────────────────────────────────── setState(s) { + // Track each seat's best coin total in a turn (for the end-of-game stats). + const cur = s.players[s.turn]; + if (cur) this.bestCoins[s.turn] = Math.max(this.bestCoins[s.turn] ?? 0, cur.coins ?? 0); + if (this._animating) { this._pendingAnimState = s; return; } const prev = this.gs; if (!prev) { this.gs = s; this.clearPrompt(); this.render(); this.scheduleAdvance(10); return; } + this._lastDiscardTopId = prev.players[0].discard[prev.players[0].discard.length - 1]?.id ?? null; const newLog = s.log.slice(prev.log.length); const prevHand = prev.players[0].hand; @@ -1242,7 +1016,7 @@ export default class DominionGame extends Phaser.Scene { : s.players[0].deck.find(c => !prevDeck.find(d => d.iid === c.iid)); if (gainedCard) { const sp = this.supplySprites.find(sp => sp.id === gainEvent.id); - this._animGainCard(gainedCard, sp?.x ?? CX, sp?.y ?? 300, gainEvent.dest, s); + this._animGainCard(gainedCard, sp?.x ?? CX, sp?.y ?? 300, gainEvent.dest, s, sp); return; } } @@ -1290,13 +1064,13 @@ export default class DominionGame extends Phaser.Scene { } if (gainEvt) { const sp = this.supplySprites.find(sp => sp.id === gainEvt.id); - this._animOppGain(seat, gainEvt.id, sp?.x ?? CX, sp?.y ?? 300, s); + const bought = seatLog.some(e => e.kind === 'buy' && e.id === gainEvt.id); + this._animOppGain(seat, gainEvt.id, sp?.x ?? CX, sp?.y ?? 300, s, { bought, src: sp }); return; } } this.gs = s; - this._checkTokenGains(prev, s); this.clearPrompt(); this.render(); this.scheduleAdvance(10); @@ -1361,9 +1135,13 @@ export default class DominionGame extends Phaser.Scene { } const buy = AI.chooseBuy(gs, seat, skill); if (buy) { + const next = buyCard(gs, buy); + // Safety net: a rejected buy returns the same state — end the turn + // rather than asking the AI the same question forever. + if (next === gs) { this.setState(endTurn(gs)); return; } playSound(this, SFX.PURCHASE); - if (buy === 'province') this.portraits[seat]?.playEmotion?.('happy'); - this.setState(buyCard(gs, buy)); + if (buy === 'province' || buy === 'colony') this.portraits[seat]?.playEmotion?.('happy'); + this.setState(next); } else { this.setState(endTurn(gs)); } @@ -1395,6 +1173,8 @@ export default class DominionGame extends Phaser.Scene { if (this.gs.pending || this.gs.turn !== 0 || this._animating) return; this._boughtThisTurn = true; playSound(this, SFX.PURCHASE); + const sp = this.supplySprites.find((s) => s.id === id); + if (sp) this.tray.flyCoins(this.tray.purseAt, { x: sp.x, y: sp.y }, Math.min(4, buyCost(this.gs, id))); this.setState(buyCard(this.gs, id)); } @@ -1438,20 +1218,37 @@ export default class DominionGame extends Phaser.Scene { this.setState(resolvePending(this.gs, choice)); } + // A crimson ribbon across the top of the play mat. promptBanner(text) { - const t = this.add.text(CX, 720, text, { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex, align: 'center', - backgroundColor: 'rgba(0,0,0,0.78)', padding: { x: 18, y: 10 }, wordWrap: { width: 1000 }, - }).setOrigin(0.5).setDepth(D.prompt); - this.promptObjs.push(t); + const t = this.add.text(RIBBON_CX, RIBBON_Y + 1, text, SERIF(19, '#fbefcf', { align: 'center', wordWrap: { width: 800 } })) + .setOrigin(0.5).setDepth(D.prompt + 1); + t.setShadow(0, 2, '#000', 4, false, true); + const w = Math.min(860, Math.max(360, t.width + 70)); + const rib = addRibbon(this, RIBBON_CX, RIBBON_Y + 4, w, '#7c1f22').setDepth(D.prompt); + if (t.height > 30) rib.setDisplaySize(rib.displayWidth, 62 * (t.height + 20) / 46); + this.promptObjs.push(rib, t); + rib.setAlpha(0); t.setAlpha(0); + this.tweens.add({ targets: [rib, t], alpha: 1, duration: 200 }); return t; } - promptButton(x, label, cb, opts = {}) { - const b = new Button(this, x, 825, label, cb, { width: 200, height: 46, fontSize: 20, ...opts }) - .setDepth(D.prompt); - this.promptObjs.push(b); - return b; + // Lay out prompt buttons evenly in the dock. specs: [{ label, cb, primary?, ghost? }] + promptButtons(specs) { + const n = specs.length; + if (!n) return []; + const gap = 12; + const w = Math.min(210, Math.floor((rectW(DOCK) - 24 - (n - 1) * gap) / n)); + const total = n * w + (n - 1) * gap; + const x0 = rectCX(DOCK) - total / 2 + w / 2; + return specs.map((s, i) => { + const opts = s.primary + ? { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex } + : s.ghost ? { variant: 'ghost' } : {}; + const b = new Button(this, x0 + i * (w + gap), rectCY(DOCK), s.label, s.cb, { width: w, height: 46, fontSize: n > 3 ? 17 : 19, ...opts }) + .setDepth(D.prompt); + this.promptObjs.push(b); + return b; + }); } promptHuman(pend) { @@ -1538,9 +1335,10 @@ export default class DominionGame extends Phaser.Scene { confirmBtn.setEnabled(n >= min && n <= max); confirmBtn.setLabel(`${confirm} (${n})`); }; - const confirmBtn = this.promptButton(CX, `${confirm} (0)`, () => { - this.resolveHuman({ iids: [...this.selection] }); - }, { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex }); + const [confirmBtn] = this.promptButtons([{ + label: `${confirm} (0)`, primary: true, + cb: () => this.resolveHuman({ iids: [...this.selection] }), + }]); for (const hs of this.handSprites) { hs.hit.setInteractive({ useHandCursor: true }); @@ -1565,14 +1363,14 @@ export default class DominionGame extends Phaser.Scene { promptPickHand(pend, { filter, banner, allowSkip, key = 'iid', choiceExtra = {} }) { this.promptBanner(banner); if (allowSkip) { - this.promptButton(CX + 230, 'Skip', () => this.resolveHuman({ [key]: null, ...choiceExtra }), { variant: 'ghost' }); + this.promptButtons([{ label: 'Skip', ghost: true, cb: () => this.resolveHuman({ [key]: null, ...choiceExtra }) }]); } for (const hs of this.handSprites) { const ok = filter(hs); if (!ok) continue; hs.hit.setInteractive({ useHandCursor: true }); hs.hit.removeAllListeners('pointerup'); - this.highlightFace(hs.face, COLORS.danger); + this.highlightFace(hs.face, 0xff7a50); hs.hit.on('pointerup', () => this.resolveHuman({ [key]: hs.iid, ...choiceExtra })); } } @@ -1598,8 +1396,9 @@ export default class DominionGame extends Phaser.Scene { any = true; sp.hit.setInteractive({ useHandCursor: true }); sp.hit.removeAllListeners('pointerup'); - const glow = this.add.rectangle(sp.x, sp.y, SUPPLY_W + 8, SUPPLY_H + 8, COLORS.gold, 0) - .setStrokeStyle(4, COLORS.gold, 0.95).setDepth(D.supply + 3); + const glow = this.add.image(sp.x, sp.y, 'dom-glow').setDisplaySize(sp.w * (210 / 150), sp.h * (276 / 216)) + .setBlendMode(Phaser.BlendModes.ADD).setDepth(D.supply + 3); + this.tweens.add({ targets: glow, alpha: { from: 1, to: 0.5 }, duration: 700, yoyo: true, repeat: -1 }); this.promptObjs.push(glow); sp.hit.on('pointerup', () => this.resolveHuman({ id: sp.id })); } @@ -1611,138 +1410,146 @@ export default class DominionGame extends Phaser.Scene { const def = getCard(pend.cardId); this.promptBanner(`Crystal Ball reveals ${def.name}.`); const playable = isType(pend.cardId, 'action') || isType(pend.cardId, 'treasure'); - let x = CX - (playable ? 285 : 190); - this.promptButton(x, 'Trash', () => this.resolveHuman({ action: 'trash' }), { variant: 'ghost' }); x += 190; - this.promptButton(x, 'Discard', () => this.resolveHuman({ action: 'discard' }), { variant: 'ghost' }); x += 190; - if (playable) { this.promptButton(x, 'Play', () => this.resolveHuman({ action: 'play' }), { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex }); x += 190; } - this.promptButton(x, 'Keep', () => this.resolveHuman({ action: 'keep' }), { variant: 'ghost' }); + const specs = [ + { label: 'Trash', ghost: true, cb: () => this.resolveHuman({ action: 'trash' }) }, + { label: 'Discard', ghost: true, cb: () => this.resolveHuman({ action: 'discard' }) }, + ]; + if (playable) specs.push({ label: 'Play', primary: true, cb: () => this.resolveHuman({ action: 'play' }) }); + specs.push({ label: 'Keep', ghost: true, cb: () => this.resolveHuman({ action: 'keep' }) }); + this.promptButtons(specs); } // Investment: choose +1 Coin, or trash a Treasure for VP. promptInvestment(pend) { this.promptBanner('Investment: choose a benefit.'); - this.promptButton(CX - 150, '+1 Coin', () => this.resolveHuman({ mode: 'coin' }), { variant: 'ghost' }); - this.promptButton(CX + 150, 'Trash a Treasure', () => { - this.clearPrompt(); - this.promptPickHand(pend, { - filter: (c) => isType(c.id, 'treasure'), - banner: 'Investment: trash a Treasure (+1 VP, +1 VP per differently named Treasure in hand).', - allowSkip: false, key: 'iid', - choiceExtra: { mode: 'trash' }, - }); - }, { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex }); + this.promptButtons([ + { label: '+1 Coin', ghost: true, cb: () => this.resolveHuman({ mode: 'coin' }) }, + { + label: 'Trash a Treasure', primary: true, + cb: () => { + this.clearPrompt(); + this.promptPickHand(pend, { + filter: (c) => isType(c.id, 'treasure'), + banner: 'Investment: trash a Treasure (+1 VP, +1 VP per differently named Treasure in hand).', + allowSkip: false, key: 'iid', + choiceExtra: { mode: 'trash' }, + }); + }, + }, + ]); } // Watchtower: react to a just-gained card. promptWatchtower(pend) { this.promptBanner(`Watchtower: you gained ${getCard(pend.cardId).name}. Reveal Watchtower to…`); - this.promptButton(CX - 200, 'Trash it', () => this.resolveHuman({ action: 'trash' }), { variant: 'ghost' }); - this.promptButton(CX, 'Top-deck it', () => this.resolveHuman({ action: 'topdeck' }), { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex }); - this.promptButton(CX + 200, 'Keep it', () => this.resolveHuman({ action: 'keep' }), { variant: 'ghost' }); + this.promptButtons([ + { label: 'Trash it', ghost: true, cb: () => this.resolveHuman({ action: 'trash' }) }, + { label: 'Top-deck it', primary: true, cb: () => this.resolveHuman({ action: 'topdeck' }) }, + { label: 'Keep it', ghost: true, cb: () => this.resolveHuman({ action: 'keep' }) }, + ]); } promptYesNo(banner, cb) { this.promptBanner(banner); - this.promptButton(CX - 120, 'Yes', () => cb(true), { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex }); - this.promptButton(CX + 120, 'No', () => cb(false), { variant: 'ghost' }); + this.promptButtons([ + { label: 'Yes', primary: true, cb: () => cb(true) }, + { label: 'No', ghost: true, cb: () => cb(false) }, + ]); + } + + // A parchment modal panel; returns its centre-top y for content. + _modalPanel(w, h, title, cy = GAME_HEIGHT / 2) { + const overlay = this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6) + .setDepth(D.modal).setInteractive(); + const panel = this.add.image(CX, cy, parchmentKey(this, w, h)).setDepth(D.modal + 0.5); + const t = this.add.text(CX, cy - h / 2 + 46, title, SERIF(24, INK, { align: 'center', wordWrap: { width: w - 80 } })) + .setOrigin(0.5).setDepth(D.modal + 1); + this.promptObjs.push(overlay, panel, t); + return { top: cy - h / 2, bottom: cy + h / 2 }; } // "Are you sure?" modal — blocks interaction with underlying buttons. showConfirm(message, onConfirm) { this.clearPrompt(); - const overlay = this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setDepth(D.modal).setInteractive(); - this.promptObjs.push(overlay); - this.promptObjs.push(this.add.text(CX, GAME_HEIGHT / 2 - 40, message, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, align: 'center', - wordWrap: { width: 900 }, - }).setOrigin(0.5).setDepth(D.modal + 1)); - this.promptObjs.push(new Button(this, CX - 130, GAME_HEIGHT / 2 + 50, 'Confirm', () => { + const { bottom } = this._modalPanel(760, 230, message); + this.promptObjs.push(new Button(this, CX - 130, bottom - 58, 'Confirm', () => { this.clearPrompt(); onConfirm(); }, { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex, width: 200, height: 46, fontSize: 20 }).setDepth(D.modal + 1)); - this.promptObjs.push(new Button(this, CX + 130, GAME_HEIGHT / 2 + 50, 'Cancel', () => { + this.promptObjs.push(new Button(this, CX + 130, bottom - 58, 'Cancel', () => { this.clearPrompt(); - }, { variant: 'ghost', width: 200, height: 46, fontSize: 20 }).setDepth(D.modal + 1)); + }, { width: 200, height: 46, fontSize: 20 }).setDepth(D.modal + 1)); } // Modal list of cards to pick one (harbinger discard, bandit/bureaucrat options). promptPickList(cards, banner, allowSkip, cb) { - const overlay = this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6) - .setDepth(D.modal).setInteractive(); - this.promptObjs.push(overlay); - this.promptObjs.push(this.add.text(CX, 360, banner, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, align: 'center', - wordWrap: { width: 1100 }, - }).setOrigin(0.5).setDepth(D.modal + 1)); - const uniq = []; const seen = new Set(); for (const c of cards) { if (!seen.has(c.iid)) { seen.add(c.iid); uniq.push(c); } } - + const shown = uniq.slice(0, 8); const gap = 18; - const totalW = Math.min(uniq.length, 8) * (HAND_W + gap); - const startX = CX - totalW / 2 + (HAND_W + gap) / 2; - uniq.slice(0, 8).forEach((c, i) => { + const panelW = Math.max(700, shown.length * (HAND.w + gap) + 120); + const { top } = this._modalPanel(panelW, 420 + (allowSkip ? 40 : 0), banner, 540); + const totalW = shown.length * (HAND.w + gap) - gap; + const startX = CX - totalW / 2 + HAND.w / 2; + const cy = top + 220; + shown.forEach((c, i) => { const def = getCard(c.id); - const face = this.buildCardFace(HAND_W, HAND_H, def).setPosition(startX + i * (HAND_W + gap), 560).setDepth(D.modal + 1); + const x = startX + i * (HAND.w + gap); + const face = this.buildCardFace(HAND.w, HAND.h, def).setPosition(x, cy).setDepth(D.modal + 1); this.promptObjs.push(face); - const hit = this.add.rectangle(startX + i * (HAND_W + gap), 560, HAND_W, HAND_H, 0x000000, 0) + const hit = this.add.rectangle(x, cy, HAND.w, HAND.h, 0x000000, 0) .setDepth(D.modal + 2).setInteractive({ useHandCursor: true }); this.promptObjs.push(hit); this.attachHover(hit, def); + hit.on('pointerover', () => face.setY(cy - 10)); + hit.on('pointerout', () => face.setY(cy)); hit.on('pointerup', () => cb(c.iid)); }); if (allowSkip) { - this.promptObjs.push(new Button(this, CX, 760, 'Skip', () => cb(null), { variant: 'ghost', width: 180 }).setDepth(D.modal + 2)); + this.promptObjs.push(new Button(this, CX, cy + HAND.h / 2 + 50, 'Skip', () => cb(null), { width: 180 }).setDepth(D.modal + 2)); } } // Sentry modal: per-card Trash / Discard / Keep over the top 2 cards. promptSentry(pend) { - const overlay = this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6) - .setDepth(D.modal).setInteractive(); - this.promptObjs.push(overlay); - this.promptObjs.push(this.add.text(CX, 320, 'Sentry: choose what to do with the top 2 cards of your deck.', { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, align: 'center', wordWrap: { width: 1100 }, - }).setOrigin(0.5).setDepth(D.modal + 1)); - + const { top } = this._modalPanel(820, 500, 'Sentry: choose what to do with the top 2 cards of your deck.', 540); const cards = pend.cards ?? []; const decisions = new Map(cards.map((c) => [c.iid, 'top'])); // default keep on top const gap = 80; - const totalW = cards.length * (HAND_W + gap); - const startX = CX - totalW / 2 + (HAND_W + gap) / 2; - const labels = new Map(); + const totalW = cards.length * (HAND.w + gap) - gap; + const startX = CX - totalW / 2 + HAND.w / 2; + const cy = top + 220; cards.forEach((c, i) => { const def = getCard(c.id); - const x = startX + i * (HAND_W + gap); - const face = this.buildCardFace(HAND_W, HAND_H, def).setPosition(x, 540).setDepth(D.modal + 1); + const x = startX + i * (HAND.w + gap); + const face = this.buildCardFace(HAND.w, HAND.h, def).setPosition(x, cy).setDepth(D.modal + 1); this.promptObjs.push(face); - const hit = this.add.rectangle(x, 540, HAND_W, HAND_H, 0x000000, 0).setDepth(D.modal + 2); + const hit = this.add.rectangle(x, cy, HAND.w, HAND.h, 0x000000, 0).setDepth(D.modal + 2); this.promptObjs.push(hit); this.attachHover(hit, def); - const lbl = this.add.text(x, 540 + HAND_H / 2 + 24, 'Keep on top', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.modal + 2); + const lbl = this.add.text(x, cy + HAND.h / 2 + 22, 'Keep on top', SERIF(18, '#2f5f33')).setOrigin(0.5).setDepth(D.modal + 2); this.promptObjs.push(lbl); - labels.set(c.iid, lbl); const cycle = ['top', 'discard', 'trash']; const text = { top: 'Keep on top', discard: 'Discard', trash: 'Trash' }; - const colors = { top: COLORS.goldHex, discard: COLORS.mutedHex, trash: COLORS.dangerHex }; + const colors = { top: '#2f5f33', discard: '#5a4120', trash: '#8a2a20' }; hit.setInteractive({ useHandCursor: true }); hit.on('pointerup', () => { const cur = decisions.get(c.iid); const nxt = cycle[(cycle.indexOf(cur) + 1) % cycle.length]; decisions.set(c.iid, nxt); lbl.setText(text[nxt]).setColor(colors[nxt]); + face.getData('img').setTint(nxt === 'trash' ? 0xd08070 : nxt === 'discard' ? 0xb0b0b0 : 0xffffff); }); }); + this.promptObjs.push(this.add.text(CX, cy + HAND.h / 2 + 52, 'Click a card to cycle Keep → Discard → Trash', + SERIF(14, '#5a4120', { fontStyle: 'italic' })).setOrigin(0.5).setDepth(D.modal + 1)); - this.promptObjs.push(new Button(this, CX, 800, 'Confirm', () => { + this.promptObjs.push(new Button(this, CX, cy + HAND.h / 2 + 100, 'Confirm', () => { const trash = [], discard = [], top = []; for (const c of cards) { const d = decisions.get(c.iid); @@ -1754,6 +1561,44 @@ export default class DominionGame extends Phaser.Scene { }, { bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex, width: 200 }).setDepth(D.modal + 2)); } + // The Trash, grouped by card — read-only. + openTrashViewer() { + if (this._trashObjs) return; + const counts = new Map(); + for (const c of this.gs.trash) counts.set(c.id, (counts.get(c.id) ?? 0) + 1); + const groups = [...counts.entries()].sort((a, b) => getCard(b[0]).cost - getCard(a[0]).cost || b[1] - a[1]); + const perRow = 8, cw = 100, ch = 144, gx = 22, gy = 34; + const rows = Math.max(1, Math.ceil(groups.length / perRow)); + const w = Math.min(perRow, Math.max(3, groups.length)) * (cw + gx) + 100; + const h = 170 + rows * (ch + gy); + const objs = []; + const overlay = this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6).setDepth(D.modal).setInteractive(); + const panel = this.add.image(CX, GAME_HEIGHT / 2, parchmentKey(this, w, h)).setDepth(D.modal + 0.5); + const top = GAME_HEIGHT / 2 - h / 2; + const title = this.add.text(CX, top + 40, `The Trash — ${this.gs.trash.length} card${this.gs.trash.length === 1 ? '' : 's'}`, SERIF(24, INK)).setOrigin(0.5).setDepth(D.modal + 1); + objs.push(overlay, panel, title); + groups.forEach(([id, n], i) => { + const r = Math.floor(i / perRow), c = i % perRow; + const inRow = Math.min(perRow, groups.length - r * perRow); + const x = CX - ((inRow - 1) * (cw + gx)) / 2 + c * (cw + gx); + const y = top + 90 + ch / 2 + r * (ch + gy); + const face = this.buildCardFace(cw, ch, getCard(id)).setPosition(x, y).setDepth(D.modal + 1); + const badge = this.add.text(x + cw / 2 - 2, y - ch / 2 + 2, `×${n}`, SERIF(15, '#fff6dc', { backgroundColor: '#3b2a14', padding: { x: 5, y: 1 } })) + .setOrigin(1, 0).setDepth(D.modal + 2); + const hit = this.add.rectangle(x, y, cw, ch, 0x000000, 0).setDepth(D.modal + 2); + this.attachHover(hit, getCard(id)); + objs.push(face, badge, hit); + }); + const close = () => { + objs.forEach((o) => o.destroy()); + this._trashObjs = null; + this.hideHover(); + }; + objs.push(new Button(this, CX, top + h - 42, 'Close', close, { width: 180, height: 44 }).setDepth(D.modal + 2)); + overlay.on('pointerup', close); + this._trashObjs = objs; + } + // ── Game over ─────────────────────────────────────────────────────────────── onGameOver() { @@ -1762,39 +1607,24 @@ export default class DominionGame extends Phaser.Scene { this.clearPrompt(); this.hideHover(); this.updateControls(); - this.turnArrow?.setVisible(false); this.phaseDials.forEach((d) => d?.setActive(false)); + this.banners.forEach((b) => b?.setActive(false)); const scores = finalScores(this.gs); - const winners = new Set(this.gs.winnerSeats); - const youWon = winners.has(0); - playSound(this, youWon ? SFX.CASINO_WIN : SFX.CASINO_LOSE); - this.recordHistory(scores); - const overlay = this.add.rectangle(CX, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.7) - .setDepth(D.modal).setInteractive(); - const ordered = scores.slice().sort((a, b) => b.vp - a.vp); - const lines = ordered.map((s) => `${this.seatName(s.seat)}: ${s.vp} VP${winners.has(s.seat) ? ' ★' : ''}`); - const h = 220 + lines.length * 44; - const box = this.add.rectangle(CX, GAME_HEIGHT / 2, 660, h, COLORS.panel, 1) - .setStrokeStyle(3, COLORS.accent).setDepth(D.modal + 1); - const title = youWon ? (winners.size > 1 ? 'Tie game!' : 'You win!') : `${this.seatName(ordered[0].seat)} wins`; - this.add.text(CX, GAME_HEIGHT / 2 - h / 2 + 48, title, { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.goldHex, - }).setOrigin(0.5).setDepth(D.modal + 2); - lines.forEach((line, i) => { - this.add.text(CX, GAME_HEIGHT / 2 - h / 2 + 116 + i * 44, line, { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal + 2); + this.time.delayedCall(500, () => { + // Opponent portraits are DOM videos that sit above the canvas. + this.portraits.forEach((p) => p?.hide?.()); + this.endScreen = showEndScreen(this, { + state: this.gs, + seatName: (s) => this.seatName(s), + bestCoins: this.bestCoins, + depth: D.modal, + onNew: () => this.scene.restart(), + onLeave: () => this.scene.start('GameMenu'), + }); }); - - new Button(this, CX - 150, GAME_HEIGHT / 2 + h / 2 - 44, 'New game', () => this.scene.restart(), { - width: 260, bg: COLORS.accent, bgHover: COLORS.gold, textColor: COLORS.textDarkHex, textHoverColor: COLORS.textDarkHex, - }).setDepth(D.modal + 2); - new Button(this, CX + 150, GAME_HEIGHT / 2 + h / 2 - 44, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 260, - }).setDepth(D.modal + 2); } async recordHistory(scores) { @@ -1814,14 +1644,20 @@ export default class DominionGame extends Phaser.Scene { // ── AI opponent animations ──────────────────────────────────────────────────── + _resumeAfterAnim() { + this._animating = false; + if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } + else this.scheduleAdvance(10); + } + _animOppPlayCards(seat, playedCards, drawnCards, newState, humanGainEvt = null) { this._animating = true; - const slot = this.oppSlot(seat - 1); + const pl = this.plate(seat); // Capture source positions before render destroys sprite refs const sources = playedCards.map(card => { const hs = (this.oppHandSprites[seat] ?? []).find(s => s.iid === card.iid); - return { iid: card.iid, id: card.id, x: hs?.x ?? slot.x, y: hs?.y ?? (slot.y + slot.r + 75) }; + return { iid: card.iid, id: card.id, x: hs?.x ?? pl.hand.x, y: hs?.y ?? pl.hand.y }; }); this.gs = newState; @@ -1829,19 +1665,10 @@ export default class DominionGame extends Phaser.Scene { this.render(); // Hide newly-played in-play sprites — ghost will reveal them on arrival - for (const card of playedCards) { + const targets = playedCards.map(card => { const sp = (this.oppInPlaySprites[seat] ?? []).find(s => s.iid === card.iid); if (sp) sp.face.setAlpha(0); - } - - // Target positions in the in-play area - const newInPlay = newState.players[seat].inPlay; - const ipGap = 8; - const ipTotal = Math.min(newInPlay.length, 12) * (PLAY_W + ipGap); - const ipStartX = CX - ipTotal / 2 + PLAY_W / 2; - const targets = playedCards.map(card => { - const idx = newInPlay.findIndex(c => c.iid === card.iid); - return { x: ipStartX + Math.max(0, idx) * (PLAY_W + ipGap), y: 610 }; + return { x: sp?.x ?? rectCX(MAT), y: sp?.y ?? rectCY(MAT), sp }; }); let idx = 0; @@ -1849,16 +1676,13 @@ export default class DominionGame extends Phaser.Scene { if (idx >= sources.length) { if (drawnCards.length > 0) { this._animOppDraw(seat, drawnCards.length, newState, humanGainEvt); return; } if (humanGainEvt) { this._chainHumanGain(humanGainEvt, newState); return; } - this._animating = false; - if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } - else this.scheduleAdvance(10); + this._resumeAfterAnim(); return; } const src = sources[idx]; const tgt = targets[idx++]; - const sp = (this.oppInPlaySprites[seat] ?? []).find(s => s.iid === src.iid); this._animOppOnePlay(src, tgt.x, tgt.y, getCard(src.id), () => { - if (sp) sp.face.setAlpha(1); + if (tgt.sp) tgt.sp.face.setAlpha(1); next(); }); }; @@ -1867,7 +1691,7 @@ export default class DominionGame extends Phaser.Scene { _animOppOnePlay(src, tx, ty, def, onComplete) { // Phase 1 (150ms): face-down mini unfolds from scale 0 - const fd = this.buildCardFace(OPP_W, OPP_H, null, { faceDown: true }); + const fd = this.buildCardFace(MINI.w, MINI.h, null, { faceDown: true }); fd.setPosition(src.x, src.y).setScale(0, 1); this.animLayer.add(fd); this.tweens.add({ @@ -1879,8 +1703,8 @@ export default class DominionGame extends Phaser.Scene { onComplete: () => { fd.destroy(); // Phase 3 (350ms): face-up, grow from mini scale to full, fly to target - const fu = this.buildCardFace(PLAY_W, PLAY_H, def); - fu.setPosition(src.x, src.y).setScale(OPP_W / PLAY_W, OPP_H / PLAY_H); + const fu = this.buildCardFace(PLAY.w, PLAY.h, def); + fu.setPosition(src.x, src.y).setScale(MINI.w / PLAY.w, MINI.h / PLAY.h); this.animLayer.add(fu); playSound(this, SFX.CARD_SHOW); this.tweens.add({ @@ -1900,7 +1724,7 @@ export default class DominionGame extends Phaser.Scene { this.clearPrompt(); this.render(); } - const slot = this.oppSlot(seat - 1); + const pl = this.plate(seat); const handSprites = this.oppHandSprites[seat] ?? []; // The last `count` sprites are the newly drawn ones const targets = handSprites.slice(-count); @@ -1911,18 +1735,16 @@ export default class DominionGame extends Phaser.Scene { if (idx >= count) { handSprites.forEach(sp => { if (sp?.face) sp.face.setAlpha(1); }); if (humanGainEvt) { this._chainHumanGain(humanGainEvt, newState); return; } - this._animating = false; - if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } - else this.scheduleAdvance(10); + this._resumeAfterAnim(); return; } const tgt = targets[idx++]; - const tx = tgt?.x ?? slot.x, ty = tgt?.y ?? (slot.y + slot.r + 75); - const mini = this.buildCardFace(OPP_W, OPP_H, null, { faceDown: true }); - mini.setPosition(slot.x, slot.y); + const tx = tgt?.x ?? pl.hand.x, ty = tgt?.y ?? pl.hand.y; + const mini = this.buildCardFace(MINI.w, MINI.h, null, { faceDown: true }); + mini.setPosition(pl.deck.x, pl.deck.y); this.animLayer.add(mini); this.tweens.add({ - targets: mini, x: tx, y: ty, duration: 320, ease: 'Cubic.easeOut', + targets: mini, x: tx, y: ty, angle: tgt?.face?.angle ?? 0, duration: 320, ease: 'Cubic.easeOut', onComplete: () => { mini.destroy(); playSound(this, SFX.CARD_DEAL); @@ -1936,16 +1758,16 @@ export default class DominionGame extends Phaser.Scene { _animOppCleanup(seat, cleanupCards, newCards, newState) { this._animating = true; - const slot = this.oppSlot(seat - 1); + const pl = this.plate(seat); this.phaseDials[seat]?.setPhase('cleanup'); // Capture sources before any render wipes the sprite arrays const sources = cleanupCards.map(card => { const ip = (this.oppInPlaySprites[seat] ?? []).find(s => s.iid === card.iid); - if (ip) return { iid: card.iid, id: card.id, x: ip.x, y: ip.y, face: ip.face }; + if (ip) return { iid: card.iid, id: card.id, x: ip.x, y: ip.y, face: ip.face, faceUp: true }; const hs = (this.oppHandSprites[seat] ?? []).find(s => s.iid === card.iid); - if (hs) return { iid: card.iid, id: card.id, x: hs.x, y: hs.y, face: hs.face }; - return { iid: card.iid, id: card.id, x: slot.x, y: slot.y, face: null }; + if (hs) return { iid: card.iid, id: card.id, x: hs.x, y: hs.y, face: hs.face, faceUp: false }; + return { iid: card.iid, id: card.id, x: pl.hand.x, y: pl.hand.y, face: null, faceUp: false }; }); this.clearPrompt(); @@ -1958,50 +1780,49 @@ export default class DominionGame extends Phaser.Scene { if (newCards.length > 0) { this._animOppDraw(seat, newCards.length, newState); } else { - this._animating = false; - if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } - else this.scheduleAdvance(10); + this._resumeAfterAnim(); } return; } const src = sources[idx++]; if (src.face) src.face.setAlpha(0); - const card = this.buildCardFace(OPP_W, OPP_H, null, { faceDown: true }); + const card = src.faceUp + ? this.buildCardFace(PLAY.w, PLAY.h, getCard(src.id)) + : this.buildCardFace(MINI.w, MINI.h, null, { faceDown: true }); card.setPosition(src.x, src.y); this.animLayer.add(card); + const sx = MINI_DISC.w / (src.faceUp ? PLAY.w : MINI.w), sy = MINI_DISC.h / (src.faceUp ? PLAY.h : MINI.h); this.tweens.add({ - targets: card, x: slot.x, y: slot.y, duration: 280, ease: 'Cubic.easeIn', + targets: card, x: pl.discard.x, y: pl.discard.y, scaleX: sx, scaleY: sy, duration: 280, ease: 'Cubic.easeIn', onComplete: () => { card.destroy(); nextCleanup(); }, }); }; nextCleanup(); } - _animOppGain(seat, cardId, srcX, srcY, newState) { + _animOppGain(seat, cardId, srcX, srcY, newState, { bought = true, src = null } = {}) { this._animating = true; this.gs = newState; this.clearPrompt(); this.render(); - const slot = this.oppSlot(seat - 1); + const pl = this.plate(seat); + const tx = pl.discard.x, ty = pl.discard.y; - this._animPurchaseShowcase(cardId, srcX, srcY, slot.x, slot.y, () => { + this._animPurchaseShowcase(cardId, srcX, srcY, tx, ty, () => { const cardName = getCard(cardId).name; - const label = this.add.text(slot.x - slot.r - 74, slot.y, `Purchased:\n${cardName}`, { - fontFamily: 'Righteous', fontSize: '32px', color: '#FFD700', - align: 'right', stroke: '#000000', strokeThickness: 4, - }).setOrigin(1, 0.5).setDepth(D.hud + 5).setAlpha(1); + const label = this.add.text(pl.rect.x0 - 16, rectCY(pl.rect), `${bought ? 'Purchased' : 'Gained'}:\n${cardName}`, SERIF(30, '#f6d77a', { + align: 'right', stroke: '#000000', strokeThickness: 5, + })).setOrigin(1, 0.5).setDepth(D.hud + 5).setAlpha(1); - const src = { iid: -1, id: cardId, x: slot.x, y: slot.y }; - this._animDiscardCard(src, slot.x, slot.y, () => { + const s = { iid: -1, id: cardId, x: tx, y: ty, w: MINI_DISC.w, h: MINI_DISC.h }; + this._animDiscardCard(s, tx, ty, () => { this.tweens.add({ targets: label, alpha: 0, duration: 600, delay: 400, ease: 'Sine.easeIn', onComplete: () => label.destroy(), }); - this._animating = false; - if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } - else this.scheduleAdvance(10); - }, { flyDuration: 1, foldDuration: 500 }); - }); + this._resumeAfterAnim(); + }, { flyDuration: 1, foldDuration: 500, w: MINI_DISC.w, h: MINI_DISC.h }); + }, { seat, bought, toW: MINI_DISC.w, toH: MINI_DISC.h, srcW: src?.w, srcH: src?.h }); } _chainHumanGain(gainEvt, newState) { @@ -2012,11 +1833,9 @@ export default class DominionGame extends Phaser.Scene { : newState.players[0].deck.find(c => !this.gs.players[0].deck.find(d => d.iid === c.iid)); if (gained) { const sp = this.supplySprites.find(s => s.id === gainEvt.id); - this._animGainCard(gained, sp?.x ?? CX, sp?.y ?? 300, gainEvt.dest, newState); + this._animGainCard(gained, sp?.x ?? CX, sp?.y ?? 300, gainEvt.dest, newState, sp); } else { - this._animating = false; - if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } - else this.scheduleAdvance(10); + this._resumeAfterAnim(); } } @@ -2029,10 +1848,10 @@ export default class DominionGame extends Phaser.Scene { // The face ref lets us hide each card exactly when its animation begins. const sources = discardedCards.map(card => { const hs = this.handSprites.find(s => s.iid === card.iid); - if (hs) return { iid: card.iid, id: card.id, x: hs.x, y: hs.baseY, face: hs.face }; + if (hs) return { iid: card.iid, id: card.id, x: hs.x, y: hs.face.y, face: hs.face, w: HAND.w, h: HAND.h }; const ip = this.inPlaySprites.find(s => s.iid === card.iid); - if (ip) return { iid: card.iid, id: card.id, x: ip.x, y: ip.y, face: ip.face }; - return { iid: card.iid, id: card.id, x: CX, y: 610, face: null }; + if (ip) return { iid: card.iid, id: card.id, x: ip.x, y: ip.y, face: ip.face, w: PLAY.w, h: PLAY.h }; + return { iid: card.iid, id: card.id, x: rectCX(MAT), y: rectCY(MAT), face: null, w: PLAY.w, h: PLAY.h }; }); // Don't render yet — keep existing sprites visible until each card starts animating. @@ -2045,8 +1864,11 @@ export default class DominionGame extends Phaser.Scene { this._discardAnimDisplay = (this._discardAnimDisplay ?? 0) + 1; if (this._liveDiscardCountText?.active) this._liveDiscardCountText.setText(`${this._discardAnimDisplay}`); + this._lastDiscardTopId = sources[idx - 1].id; + if (this._liveDiscardTop?.active) this._liveDiscardTop.setTexture(cardKey(this, sources[idx - 1].id, 'M')).setDisplaySize(HAND.w, HAND.h); if (this._liveDiscardPile?.active) this._liveDiscardPile.setVisible(true); if (this._liveDiscardBadge?.active) this._liveDiscardBadge.setVisible(true); + if (this._liveDiscardCountText?.active) this._liveDiscardCountText.setVisible(true); } if (idx >= sources.length) { // All cards have landed. Now render the intermediate/final state. @@ -2073,37 +1895,48 @@ export default class DominionGame extends Phaser.Scene { this._discardAnimDisplay = null; this._suppressTurnUi = false; this.updateTurnUi(); - this._animating = false; - if (this._pendingAnimState) { - const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); - } else { - this.scheduleAdvance(10); - } + this._resumeAfterAnim(); } return; } const src = sources[idx++]; // Hide the existing sprite at the moment the animation sprite takes over. if (src.face) src.face.setAlpha(0); - this._animDiscardCard(src, DISCARD_PILE_X, DISCARD_PILE_Y, animateNext); + this._animDiscardCard(src, DISCARD.x, DISCARD.y, animateNext); }; animateNext(); } - _animDiscardCard(src, tx, ty, onComplete, { flyDuration = 500, foldDuration = 250 } = {}) { + // Fly a face-up card to a pile. faceUp landing (discard) settles in place; + // otherwise (deck) it flips to its back. Total time is the same either way. + _animDiscardCard(src, tx, ty, onComplete, { flyDuration = 500, foldDuration = 250, faceUp = true, w = HAND.w, h = HAND.h } = {}) { const def = getCard(src.id); - const fuCard = this.buildCardFace(HAND_W, HAND_H, def); - fuCard.setPosition(src.x, src.y); + const sw = src.w ?? w, sh = src.h ?? h; + const fuCard = this.buildCardFace(w, h, def); + fuCard.setPosition(src.x, src.y).setScale(sw / w, sh / h); this.animLayer.add(fuCard); this.tweens.add({ - targets: fuCard, x: tx, y: ty, duration: flyDuration, ease: 'Cubic.easeIn', + targets: fuCard, x: tx, y: ty, scaleX: 1, scaleY: 1, duration: flyDuration, ease: 'Cubic.easeIn', onComplete: () => { + if (faceUp) { + this.tweens.add({ + targets: fuCard, scaleX: 1.08, scaleY: 1.08, duration: foldDuration, ease: 'Sine.easeOut', + onComplete: () => { + playSound(this, SFX.CARD_SHOW); + this.tweens.add({ + targets: fuCard, scaleX: 1, scaleY: 1, duration: foldDuration, ease: 'Sine.easeIn', + onComplete: () => { fuCard.destroy(); onComplete(); }, + }); + }, + }); + return; + } this.tweens.add({ targets: fuCard, scaleX: 0, duration: foldDuration, ease: 'Sine.easeIn', onComplete: () => { fuCard.destroy(); - const fdCard = this.buildCardFace(HAND_W, HAND_H, null, { faceDown: true }); + const fdCard = this.buildCardFace(w, h, null, { faceDown: true }); fdCard.setPosition(tx, ty).setScale(0, 1); this.animLayer.add(fdCard); playSound(this, SFX.CARD_SHOW); @@ -2117,9 +1950,9 @@ export default class DominionGame extends Phaser.Scene { }); } - _animPurchaseShowcase(cardId, srcX, srcY, tx, ty, onComplete) { + _animPurchaseShowcase(cardId, srcX, srcY, tx, ty, onComplete, { seat = 0, bought = true, toW = HAND.w, toH = HAND.h, srcW = null, srcH = null } = {}) { const cy = GAME_HEIGHT / 2; - const SHOW_W = 270, SHOW_H = 390; + const SHOW_W = SHOW.w, SHOW_H = SHOW.h; const def = getCard(cardId); const overlay = this.add.rectangle(CX, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0) @@ -2127,12 +1960,21 @@ export default class DominionGame extends Phaser.Scene { this.tweens.add({ targets: overlay, alpha: 0.65, duration: 250 }); const card = this.buildCardFace(SHOW_W, SHOW_H, def); - card.setPosition(srcX, srcY).setScale(SUPPLY_W / SHOW_W).setDepth(D.modal + 1); + card.setPosition(srcX, srcY).setScale((srcW ?? 100) / SHOW_W, (srcH ?? 144) / SHOW_H).setDepth(D.modal + 1); + + // The buyer's banner ribbon under the card. + const ribW = 380; + const rib = addRibbon(this, CX, cy + SHOW_H / 2 + 38, ribW, SEAT_HEX[seat % 4]).setDepth(D.modal + 1).setAlpha(0); + const ribT = this.add.text(CX, cy + SHOW_H / 2 + 34, `${this.seatName(seat)} ${bought ? 'buys' : 'gains'} ${def.name}`, + SERIF(19, '#fbefcf', { fixedWidth: 0 })).setOrigin(0.5).setDepth(D.modal + 2).setAlpha(0); + ribT.setShadow(0, 2, '#000', 3, false, true); + if (ribT.width > ribW - 20) ribT.setScale((ribW - 20) / ribT.width); this.tweens.add({ targets: card, x: CX, y: cy, scaleX: 1, scaleY: 1, duration: 350, ease: 'Back.easeOut', onComplete: () => { + this.tweens.add({ targets: [rib, ribT], alpha: 1, duration: 200 }); // Comet border effect around the full-size card const gfx = this.add.graphics().setDepth(D.modal + 2); const perim = 2 * (SHOW_W + SHOW_H); @@ -2172,38 +2014,45 @@ export default class DominionGame extends Phaser.Scene { this.time.delayedCall(1500, () => { borderTween.stop(); gfx.destroy(); - this.tweens.add({ targets: overlay, alpha: 0, duration: 300 }); + this.tweens.add({ targets: [overlay, rib, ribT], alpha: 0, duration: 300 }); this.tweens.add({ targets: card, - x: tx, y: ty, scaleX: HAND_W / SHOW_W, scaleY: HAND_H / SHOW_H, + x: tx, y: ty, scaleX: toW / SHOW_W, scaleY: toH / SHOW_H, duration: 400, ease: 'Cubic.easeIn', - onComplete: () => { card.destroy(); overlay.destroy(); onComplete(); }, + onComplete: () => { card.destroy(); overlay.destroy(); rib.destroy(); ribT.destroy(); onComplete(); }, }); }); }, }); } - _animGainCard(gainedCard, srcX, srcY, dest, newState) { + _animGainCard(gainedCard, srcX, srcY, dest, newState, src = null) { this._animating = true; this.gs = newState; this.clearPrompt(); this.render(); - const tx = dest === 'deck' ? DECK_PILE_X : DISCARD_PILE_X; - const ty = dest === 'deck' ? DECK_PILE_Y : DISCARD_PILE_Y; + const tx = dest === 'deck' ? DECK.x : DISCARD.x; + const ty = dest === 'deck' ? DECK.y : DISCARD.y; + const bought = newState.log.slice(-6).some((e) => e.kind === 'buy' && e.seat === 0 && e.id === gainedCard.id); + // While the showcase plays, the discard pile keeps showing what was there. + if (dest === 'discard' && this._liveDiscardTop?.active) { + const d = newState.players[0].discard; + const under = d[d.length - 2]; + if (under) this._liveDiscardTop.setTexture(cardKey(this, under.id, 'M')).setDisplaySize(HAND.w, HAND.h); + else this._liveDiscardPile?.setVisible(false); + } this._animPurchaseShowcase(gainedCard.id, srcX, srcY, tx, ty, () => { - const src = { iid: gainedCard.iid, id: gainedCard.id, x: tx, y: ty }; - this._animDiscardCard(src, tx, ty, () => { - this._animating = false; - if (this._pendingAnimState) { - const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); - } else { - this.scheduleAdvance(10); + const s = { iid: gainedCard.iid, id: gainedCard.id, x: tx, y: ty }; + this._animDiscardCard(s, tx, ty, () => { + if (this._liveDiscardTop?.active && dest === 'discard') { + this._liveDiscardTop.setTexture(cardKey(this, gainedCard.id, 'M')).setDisplaySize(HAND.w, HAND.h); + this._liveDiscardPile?.setVisible(true); } - }, { flyDuration: 1, foldDuration: 250 }); - }); + this._resumeAfterAnim(); + }, { flyDuration: 1, foldDuration: 250, faceUp: dest !== 'deck' }); + }, { seat: 0, bought, srcW: src?.w, srcH: src?.h }); } // ── Drag and drop ───────────────────────────────────────────────────────────── @@ -2245,7 +2094,7 @@ export default class DominionGame extends Phaser.Scene { offsetX, offsetY, }; hs.face.setAlpha(0.2); - const ghost = this.buildCardFace(HAND_W, HAND_H, hs.def); + const ghost = this.buildCardFace(HAND.w, HAND.h, hs.def); ghost.setPosition(pointer.x + offsetX, pointer.y + offsetY); ghost.setDepth(D.hand + 100); this.animLayer.add(ghost); @@ -2268,7 +2117,7 @@ export default class DominionGame extends Phaser.Scene { ds.ghost.destroy(); this._dragState = null; const cardCenterY = p.y + ds.offsetY; - if (cardCenterY < 870 && (ds.isPlayableAction || ds.isPlayableTreasure)) { + if (cardCenterY < HAND_ZONE.y0 - 10 && (ds.isPlayableAction || ds.isPlayableTreasure)) { const hs = this.handSprites.find(s => s.iid === ds.iid); if (hs) hs.face.setAlpha(1); if (ds.isPlayableAction) this.humanPlayAction(ds.iid); @@ -2292,13 +2141,10 @@ export default class DominionGame extends Phaser.Scene { _reorderHand(iid, dropX) { const ordered = this._getOrderedHand(this.gs.players[0].hand); const rest = ordered.filter(c => c.iid !== iid); - const gap = Math.min(18, (1300 - rest.length * HAND_W) / Math.max(1, rest.length - 1)); - const step = HAND_W + Math.max(-HAND_W * 0.45, gap); - const total = (rest.length - 1) * step + HAND_W; - const startX = CX - total / 2 + HAND_W / 2; + const { xs } = handPositions(rest.length); let insertIdx = rest.length; for (let i = 0; i < rest.length; i++) { - if (dropX < startX + i * step) { insertIdx = i; break; } + if (dropX < xs[i]) { insertIdx = i; break; } } this._handOrder = [ ...rest.slice(0, insertIdx).map(c => c.iid), @@ -2312,14 +2158,13 @@ export default class DominionGame extends Phaser.Scene { const g = this.add.graphics(); g.fillStyle(COLORS.gold, 0.08); g.lineStyle(2, COLORS.gold, 0.55); - g.fillRoundedRect(CX - 700, 490, 1400, 340, 20); - g.strokeRoundedRect(CX - 700, 490, 1400, 340, 20); + g.fillRoundedRect(MAT.x0, MAT.y0, rectW(MAT), MAT.y1 - MAT.y0, 22); + g.strokeRoundedRect(MAT.x0, MAT.y0, rectW(MAT), MAT.y1 - MAT.y0, 22); g.setDepth(D.inplay - 1); this.animLayer.add(g); this._dragDropZone = g; - const lbl = this.add.text(CX, 660, '▲ Drop here to play', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.goldHex, - }).setOrigin(0.5).setAlpha(0.7).setDepth(D.inplay); + const lbl = this.add.text(rectCX(MAT), rectCY(MAT), '▲ Drop here to play', SERIF(22, '#f6d77a')) + .setOrigin(0.5).setAlpha(0.75).setDepth(D.inplay); this.animLayer.add(lbl); this._dragDropLabel = lbl; } @@ -2346,6 +2191,7 @@ export default class DominionGame extends Phaser.Scene { const empty = this._deckAnimDisplay <= 0; if (this._liveDeckPile?.active) this._liveDeckPile.setVisible(!empty); if (this._liveDeckBadge?.active) this._liveDeckBadge.setVisible(!empty); + if (this._liveDeckCountText?.active) this._liveDeckCountText.setVisible(!empty); }; const doShuffle = (callback) => { @@ -2353,6 +2199,10 @@ export default class DominionGame extends Phaser.Scene { playSound(this, SFX.CARD_SHUFFLE); const startVal = this._discardAnimDisplay ?? 0; const counter = { v: startVal }; + // The discard pile is gathered up and turned face-down into the deck. + if (this._liveDiscardPile?.active) { + this.tweens.add({ targets: this._liveDiscardPile, alpha: 0, duration: 500 }); + } this.tweens.add({ targets: counter, v: 0, duration: 600, ease: 'Cubic.Out', onUpdate: () => { @@ -2361,6 +2211,8 @@ export default class DominionGame extends Phaser.Scene { this._liveDiscardCountText.setText(`${this._discardAnimDisplay}`); }, onComplete: () => { + if (this._liveDiscardBadge?.active) this._liveDiscardBadge.setVisible(false); + if (this._liveDiscardCountText?.active) this._liveDiscardCountText.setVisible(false); const postDeck = (drawnCards.length - drawnSoFar) + newState.players[0].deck.length; this._deckAnimDisplay = postDeck; updateDeckDisplay(); @@ -2384,7 +2236,7 @@ export default class DominionGame extends Phaser.Scene { const card = drawnCards[idx++]; const sprite = this.handSprites.find(s => s.iid === card.iid); const tx = sprite?.x ?? CX; - this._animateOneCard(card, tx, 968, () => { + this._animateOneCard(card, tx, HAND_Y, () => { drawnSoFar++; playSound(this, SFX.CARD_DEAL); const s2 = this.handSprites.find(s => s.iid === card.iid); @@ -2401,8 +2253,8 @@ export default class DominionGame extends Phaser.Scene { } _animateOneCard(card, tx, ty, onComplete) { - const fdCard = this.buildCardFace(HAND_W, HAND_H, null, { faceDown: true }); - fdCard.setPosition(DECK_PILE_X, DECK_PILE_Y); + const fdCard = this.buildCardFace(HAND.w, HAND.h, null, { faceDown: true }); + fdCard.setPosition(DECK.x, DECK.y); this.animLayer.add(fdCard); this.tweens.add({ @@ -2411,8 +2263,8 @@ export default class DominionGame extends Phaser.Scene { fdCard.destroy(); const def = getCard(card.id); - const fuCard = this.buildCardFace(HAND_W, HAND_H, def); - fuCard.setPosition(DECK_PILE_X, DECK_PILE_Y).setScale(0, 1); + const fuCard = this.buildCardFace(HAND.w, HAND.h, def); + fuCard.setPosition(DECK.x, DECK.y).setScale(0, 1); this.animLayer.add(fuCard); playSound(this, SFX.CARD_SHOW); @@ -2441,15 +2293,16 @@ export default class DominionGame extends Phaser.Scene { } }); this._animatingIids.clear(); - this._animating = false; this._suppressTurnUi = false; this.updateTurnUi(); - + // Re-render so the discard pile shows its true (post-shuffle) state. + this._animating = false; if (this._pendingAnimState) { const s = this._pendingAnimState; this._pendingAnimState = null; this.setState(s); } else { + this.render(); this.scheduleAdvance(10); } } diff --git a/src/games/dominion/DominionHud.js b/src/games/dominion/DominionHud.js new file mode 100644 index 0000000..f88b1cc --- /dev/null +++ b/src/games/dominion/DominionHud.js @@ -0,0 +1,431 @@ +// Dominion — persistent table furniture that changes with the state: +// StewardTray Actions / Buys / Coins wells for the active player +// EndClock Province (and Colony) candles + three empty-pile seal slots +// VpDish a seat's Victory-point tokens +// SeatBanner heraldic pennant + candle-glow for the active seat +// makePhaseDial the brass Action / Buy / Clean-up dial +// +// None of these live in the scene's per-render dynamic layer: each owns its +// objects, diffs its inputs, and animates the change. + +import * as Phaser from 'phaser'; +import { TRAY_WELLS, SEAT_COLORS, rectCX, rectCY, rectW, rectH } from './DominionLayout.js'; +import { bannerKey, PHASER_SERIF } from './DominionArt.js'; + +const TXT = (size, color = '#f3e6c8', extra = {}) => ({ + fontFamily: PHASER_SERIF, fontSize: `${size}px`, color, fontStyle: 'bold', ...extra, +}); + +// ── Steward's tray ────────────────────────────────────────────────────────── +export class StewardTray { + constructor(scene, depth) { + this.scene = scene; + this.depth = depth; + this.root = scene.add.container(0, 0).setDepth(depth); + this.wells = {}; + this.last = null; + for (const k of ['actions', 'buys']) { + const r = TRAY_WELLS[k]; + const box = scene.add.container(0, 0); + const count = scene.add.text(r.x1 - 12, rectCY(r) + 6, '', TXT(18)).setOrigin(1, 0.5); + count.setShadow(0, 2, '#000', 3, false, true); + this.root.add([box, count]); + this.wells[k] = { r, box, count, sprites: [] }; + } + const rc = TRAY_WELLS.coins; + this.purse = scene.add.image(rc.x0 + 34, rectCY(rc) + 4, 'dom-purse').setDisplaySize(46, 46); + this.coinText = scene.add.text(rc.x0 + 66, rectCY(rc) + 5, '0', TXT(28, '#f6d77a')).setOrigin(0, 0.5); + this.coinText.setShadow(0, 2, '#000', 4, false, true); + this.coinCap = scene.add.text(rc.x1 - 12, rectCY(rc) + 8, 'coins', TXT(12, 'rgba(236,214,160,0.7)', { fontStyle: 'normal' })).setOrigin(1, 0.5); + this.root.add([this.purse, this.coinText, this.coinCap]); + } + + // Where coins fly to / from. + get purseAt() { return { x: this.purse.x, y: this.purse.y }; } + + update({ actions, buys, coins, seat }, { animate = true, coinsFrom = null } = {}) { + const prev = this.last; + const sameSeat = prev && prev.seat === seat; + this._tokens('actions', actions, 'dom-tok-action', animate && sameSeat ? prev.actions : actions); + this._tokens('buys', buys, 'dom-tok-buy', animate && sameSeat ? prev.buys : buys); + this.coinText.setText(`${coins}`); + if (animate && sameSeat && coins !== prev.coins) { + this.scene.tweens.add({ targets: this.coinText, scale: { from: 1.35, to: 1 }, duration: 380, ease: 'Back.Out' }); + this.scene.tweens.add({ targets: this.purse, angle: { from: -10, to: 0 }, duration: 420, ease: 'Elastic.Out' }); + if (coins > prev.coins && coinsFrom) this.flyCoins(coinsFrom, this.purseAt, coins - prev.coins); + } + this.last = { actions, buys, coins, seat }; + } + + _tokens(k, n, tex, prevN) { + const w = this.wells[k]; + w.sprites.forEach((s) => s.destroy()); + w.sprites = []; + const shown = Math.min(n, 5); + const x0 = w.r.x0 + 22, y = rectCY(w.r) + 6; + for (let i = 0; i < shown; i++) { + const s = this.scene.add.image(x0 + i * 21, y - (i % 2) * 2, tex).setDisplaySize(26, 26); + w.box.add(s); + w.sprites.push(s); + if (i >= prevN) { + s.setScale(s.scaleX * 1.8).setAlpha(0); + this.scene.tweens.add({ targets: s, scaleX: 26 / 60, scaleY: 26 / 60, alpha: 1, duration: 320, delay: (i - prevN) * 70, ease: 'Back.Out' }); + } + } + w.count.setText(n > 5 ? `×${n}` : n === 0 ? '—' : ''); + w.count.setColor(n === 0 ? 'rgba(236,214,160,0.45)' : '#f3e6c8'); + } + + // Little coins arc from `from` to `to` (non-blocking flourish). + flyCoins(from, to, n) { + const count = Math.min(6, Math.max(1, n)); + for (let i = 0; i < count; i++) { + const c = this.scene.add.image(from.x + Phaser.Math.Between(-24, 24), from.y + Phaser.Math.Between(-12, 12), 'dom-coin') + .setDisplaySize(22, 22).setDepth(this.depth + 20).setAlpha(0); + const midX = (c.x + to.x) / 2, midY = Math.min(c.y, to.y) - 70 - Math.random() * 40; + const path = { t: 0 }; + const sx = c.x, sy = c.y; + this.scene.tweens.add({ + targets: path, t: 1, duration: 520, delay: i * 60, ease: 'Sine.InOut', + onStart: () => c.setAlpha(1), + onUpdate: () => { + const t = path.t, u = 1 - t; + c.setPosition(u * u * sx + 2 * u * t * midX + t * t * to.x, u * u * sy + 2 * u * t * midY + t * t * to.y); + c.setAngle(t * 540); + }, + onComplete: () => c.destroy(), + }); + } + } + + setVisible(v) { this.root.setVisible(v); } + destroy() { this.root.destroy(true); } +} + +// ── Game-end clock ────────────────────────────────────────────────────────── +export class EndClock { + constructor(scene, rect, depth, { colony = false } = {}) { + this.scene = scene; + this.rect = rect; + this.depth = depth; + this.colony = colony; + this.root = scene.add.container(0, 0).setDepth(depth); + this.g = scene.add.graphics(); + this.root.add(this.g); + this.candles = []; + const ids = colony ? ['province', 'colony'] : ['province']; + const cx0 = rect.x0 + (colony ? 36 : 50); + ids.forEach((id, i) => { + const x = cx0 + i * 46; + const flame = scene.add.image(x, 0, 'dom-flame').setDisplaySize(18, 30).setOrigin(0.5, 0.9).setBlendMode(Phaser.BlendModes.ADD); + const halo = scene.add.image(x, 0, 'dom-spot').setDisplaySize(90, 90).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.35); + const label = scene.add.text(x, rect.y1 - 14, '', TXT(12, '#e9d7a8')).setOrigin(0.5); + this.root.add([halo, flame, label]); + scene.tweens.add({ targets: flame, scaleX: flame.scaleX * 0.86, duration: 260 + i * 40, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + scene.tweens.add({ targets: halo, alpha: 0.22, duration: 700 + i * 90, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.candles.push({ id, x, flame, halo, label, frac: 1 }); + }); + // empty-pile seals + this.sealX = rect.x1 - 38; + this.sealYs = [rect.y0 + 76, rect.y0 + 132, rect.y0 + 188]; + this.seals = this.sealYs.map((y) => { + const s = scene.add.image(this.sealX, y, 'dom-seal').setDisplaySize(44, 44).setVisible(false); + this.root.add(s); + return s; + }); + this.pilesLabel = scene.add.text(this.sealX, rect.y1 - 14, 'Piles', TXT(12, '#e9d7a8')).setOrigin(0.5); + this.root.add(this.pilesLabel); + this.lastEmpty = 0; + } + + update(supply, pileMax, emptyCount, { animate = true } = {}) { + const g = this.g; + g.clear(); + const baseY = this.rect.y1 - 34; + const maxH = 150; + for (const c of this.candles) { + const left = Math.max(0, supply[c.id] ?? 0); + const max = Math.max(1, pileMax[c.id] ?? left); + const frac = left / max; + const h = 14 + (maxH - 14) * frac; + // holder + g.fillStyle(0x6e5220, 1); g.fillEllipse(c.x, baseY + 6, 40, 12); + g.fillStyle(0xb8913f, 1); g.fillEllipse(c.x, baseY + 3, 34, 9); + // wax column + const wax = c.id === 'colony' ? 0xd9dce8 : 0xf1e4c4; + g.fillStyle(0x000000, 0.25); g.fillRect(c.x - 8, baseY - h + 2, 18, h); + g.fillStyle(wax, 1); g.fillRect(c.x - 9, baseY - h, 18, h); + g.fillStyle(0xffffff, 0.35); g.fillRect(c.x - 7, baseY - h, 4, h); + g.fillStyle(0x000000, 0.12); g.fillRect(c.x + 4, baseY - h, 5, h); + // drip + g.fillStyle(wax, 1); g.fillEllipse(c.x - 6, baseY - h + 10, 6, 16); + g.fillStyle(0x2a1a0a, 1); g.fillRect(c.x - 0.75, baseY - h - 7, 1.5, 8); + c.flame.setY(baseY - h - 3); + c.halo.setY(baseY - h - 12); + const low = left <= 2; + c.flame.setTint(low ? 0xffa070 : 0xffffff); + c.label.setText(`${c.id === 'colony' ? 'Col' : 'Prov'} ${left}`); + c.label.setColor(low ? '#ff9a7a' : '#e9d7a8'); + if (animate && frac < c.frac) { + this.scene.tweens.add({ targets: c.halo, alpha: { from: 0.9, to: 0.3 }, duration: 600 }); + } + c.frac = frac; + } + // seal slots + for (let i = 0; i < 3; i++) { + g.lineStyle(2, 0xd8b46a, 0.35); + g.strokeCircle(this.sealX, this.sealYs[i], 20); + const on = i < emptyCount; + const s = this.seals[i]; + if (on && !s.visible) { + s.setVisible(true); + if (animate) { + s.setScale(s.scaleX * 2.2).setAlpha(0); + this.scene.tweens.add({ targets: s, scaleX: 44 / 96, scaleY: 44 / 96, alpha: 1, duration: 420, ease: 'Back.Out' }); + } + } else if (!on) s.setVisible(false); + } + this.pilesLabel.setText(`Piles ${Math.min(emptyCount, 3)}/3`); + this.pilesLabel.setColor(emptyCount >= 2 ? '#ff9a7a' : '#e9d7a8'); + this.lastEmpty = emptyCount; + } + + destroy() { this.root.destroy(true); } +} + +// ── Victory-point dish ────────────────────────────────────────────────────── +export class VpDish { + constructor(scene, x, y, depth, { size = 30, max = 6 } = {}) { + this.scene = scene; + this.x = x; this.y = y; + this.size = size; + this.max = max; + this.root = scene.add.container(0, 0).setDepth(depth); + this.n = 0; + this.sprites = []; + this.label = scene.add.text(x, y + size * 0.72, '', TXT(13, '#f6d77a')).setOrigin(0.5); + this.label.setShadow(0, 1, '#000', 3, false, true); + this.root.add(this.label); + } + + update(n, { animate = true } = {}) { + if (n === this.n && this.sprites.length) return; + const prev = this.n; + this.sprites.forEach((s) => s.destroy()); + this.sprites = []; + this.n = n; + this.label.setText(n > 0 ? `${n} VP` : ''); + if (n <= 0) return; + const fives = Math.floor(n / 5), ones = n % 5; + const list = [...Array(fives).fill(1), ...Array(ones).fill(0)]; + const shown = list.slice(0, this.max); + const step = this.size * 0.55; + const x0 = this.x - ((shown.length - 1) * step) / 2; + const has = this.scene.textures.exists('dominion-tokens'); + shown.forEach((fr, i) => { + const s = has + ? this.scene.add.image(x0 + i * step, this.y - (i % 2) * 2, 'dominion-tokens', fr) + : this.scene.add.circle(x0 + i * step, this.y, this.size / 2, fr ? 0xd4a017 : 0xc8a84b); + if (has) s.setDisplaySize(this.size, this.size); + s.setAngle(((i * 37) % 30) - 15); + this.root.add(s); + this.sprites.push(s); + }); + this.root.bringToTop(this.label); + if (animate && n > prev) { + const last = this.sprites[this.sprites.length - 1]; + const sx = last.scaleX, sy = last.scaleY; + last.setScale(sx * 2.4, sy * 2.4).setAlpha(0); + this.scene.tweens.add({ targets: last, scaleX: sx, scaleY: sy, alpha: 1, duration: 520, ease: 'Back.Out' }); + this.scene.tweens.add({ targets: this.label, scale: { from: 1.4, to: 1 }, duration: 420, ease: 'Back.Out' }); + } + } + + destroy() { this.root.destroy(true); } +} + +// ── Seat banner + active candle-glow ──────────────────────────────────────── +// depth should sit between the baked furniture and the scene's dynamic layer +// (e.g. -0.6) so the glow lights the plaque but stays under the plate's cards. +export class SeatBanner { + constructor(scene, seat, bannerRect, plateRect, depth) { + this.scene = scene; + this.seat = seat; + const glowW = rectW(plateRect) + 80, glowH = rectH(plateRect) + 80; + this.glow = scene.add.image(rectCX(plateRect), rectCY(plateRect), 'dom-spot') + .setDisplaySize(glowW, glowH).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0).setDepth(depth) + .setTint(0xffc070); + this.frame = scene.add.graphics().setDepth(depth + 0.1).setAlpha(0); + this.frame.lineStyle(3, SEAT_COLORS[seat % SEAT_COLORS.length], 1); + this.frame.strokeRoundedRect(plateRect.x0 - 3, plateRect.y0 - 3, rectW(plateRect) + 6, rectH(plateRect) + 6, 18); + this.frame.lineStyle(1.5, 0xf1d58a, 0.9); + this.frame.strokeRoundedRect(plateRect.x0 - 6, plateRect.y0 - 6, rectW(plateRect) + 12, rectH(plateRect) + 12, 20); + const bw = rectW(bannerRect), bh = rectH(bannerRect); + this.banner = scene.add.image(rectCX(bannerRect), bannerRect.y0, bannerKey(scene, seat)) + .setOrigin(0.5, 0).setDisplaySize(bw, bh).setDepth(depth + 0.2); + this.baseSY = this.banner.scaleY; + this.active = false; + this.banner.setScale(this.banner.scaleX, this.baseSY * 0.72).setAlpha(0.75); + } + + setActive(on) { + if (on === this.active) return; + this.active = on; + const sc = this.scene; + sc.tweens.killTweensOf([this.glow, this.frame, this.banner]); + if (on) { + sc.tweens.add({ targets: this.banner, scaleY: this.baseSY, alpha: 1, duration: 520, ease: 'Back.Out' }); + sc.tweens.add({ targets: this.frame, alpha: 1, duration: 300 }); + sc.tweens.add({ + targets: this.glow, alpha: { from: 0.0, to: 0.42 }, duration: 400, + onComplete: () => sc.tweens.add({ targets: this.glow, alpha: 0.28, duration: 1100, yoyo: true, repeat: -1, ease: 'Sine.InOut' }), + }); + } else { + sc.tweens.add({ targets: this.banner, scaleY: this.baseSY * 0.72, alpha: 0.75, duration: 360, ease: 'Sine.Out' }); + sc.tweens.add({ targets: [this.frame, this.glow], alpha: 0, duration: 300 }); + } + } + + hide() { this.glow.setVisible(false); this.frame.setVisible(false); } +} + +// ── Brass phase dial ──────────────────────────────────────────────────────── +// A 3-wedge ring (Action / Buy / Clean-up) that spins so the active wedge locks +// under a fixed top pointer. Returns { container, setActive(on), setPhase(name) }. +export function makePhaseDial(scene, x, y, outerR, depth) { + const PHASE = { action: 0, buy: 1, cleanup: 2 }; + const colors = [0xa8322d, 0xc99a2e, 0x3f6fa8]; + const TWO_PI_3 = (Math.PI * 2) / 3; + const HALF = Math.PI / 3; + const TOP = -Math.PI / 2; + + const container = scene.add.container(x, y).setDepth(depth); + const rim = scene.add.graphics(); + rim.fillStyle(0x000000, 0.45); rim.fillCircle(2, 4, outerR + 7); + rim.fillStyle(0x6e5220, 1); rim.fillCircle(0, 0, outerR + 6); + rim.fillStyle(0xc9a24e, 1); rim.fillCircle(0, -1, outerR + 4); + rim.fillStyle(0x7c5a1f, 1); rim.fillCircle(0, 0, outerR + 1); + for (let i = 0; i < 24; i++) { + const a = (i / 24) * Math.PI * 2; + rim.fillStyle(0xf1d58a, 0.8); + rim.fillCircle(Math.cos(a) * (outerR + 3), Math.sin(a) * (outerR + 3), Math.max(0.8, outerR * 0.025)); + } + container.add(rim); + const ring = scene.add.container(0, 0); + container.add(ring); + + const a0 = [], a1 = [], mid = []; + for (let i = 0; i < 3; i++) { const c = TOP + i * TWO_PI_3; a0[i] = c - HALF; a1[i] = c + HALF; mid[i] = c; } + const wedges = []; + for (let i = 0; i < 3; i++) { const w = scene.add.graphics(); ring.add(w); wedges.push(w); } + const paintWedges = (activeIdx) => { + for (let i = 0; i < 3; i++) { + const w = wedges[i]; + const on = i === activeIdx; + w.clear(); + w.fillStyle(colors[i], on ? 1 : 0.42); + w.beginPath(); w.moveTo(0, 0); w.arc(0, 0, outerR, a0[i], a1[i], false); w.closePath(); w.fillPath(); + w.lineStyle(Math.max(1.5, outerR * 0.04), 0x2a1a08, 0.8); + w.beginPath(); w.moveTo(0, 0); w.arc(0, 0, outerR, a0[i], a1[i], false); w.closePath(); w.strokePath(); + } + }; + paintWedges(-1); + + const ic = outerR * 0.22; + const midR = outerR * 0.66; + const drawSword = (g) => { + g.fillStyle(0xf2ead8, 1); + g.fillTriangle(-0.16 * ic, -0.5 * ic, 0.16 * ic, -0.5 * ic, 0, -1.15 * ic); + g.fillRect(-0.14 * ic, -0.5 * ic, 0.28 * ic, 0.85 * ic); + g.fillStyle(0xe2c46e, 1); + g.fillRect(-0.5 * ic, 0.3 * ic, ic, 0.16 * ic); + g.fillRect(-0.12 * ic, 0.46 * ic, 0.24 * ic, 0.5 * ic); + }; + const drawCoin = (g) => { + g.fillStyle(0xf6d77a, 1); g.fillCircle(0, 0, 0.95 * ic); + g.lineStyle(Math.max(1, 0.14 * ic), 0x6e5410, 1); g.strokeCircle(0, 0, 0.95 * ic); + g.lineStyle(Math.max(1, 0.14 * ic), 0xfff3c4, 0.9); g.strokeCircle(0, 0, 0.5 * ic); + }; + const drawRefresh = (g) => { + g.lineStyle(Math.max(1.5, 0.2 * ic), 0xf2ead8, 1); + g.beginPath(); g.arc(0, 0, 0.85 * ic, Phaser.Math.DegToRad(-50), Phaser.Math.DegToRad(200), false); g.strokePath(); + const end = Phaser.Math.DegToRad(200); + const ex = Math.cos(end) * 0.85 * ic, ey = Math.sin(end) * 0.85 * ic; + g.fillStyle(0xf2ead8, 1); + g.fillTriangle(ex - 0.45 * ic, ey - 0.1 * ic, ex + 0.1 * ic, ey - 0.5 * ic, ex + 0.15 * ic, ey + 0.35 * ic); + }; + const icons = [drawSword, drawCoin, drawRefresh].map((fn, i) => { + const g = scene.add.graphics(); + fn(g); + g.setPosition(Math.cos(mid[i]) * midR, Math.sin(mid[i]) * midR); + ring.add(g); + return g; + }); + + const hub = scene.add.graphics(); + hub.fillStyle(0x6e5220, 1); hub.fillCircle(0, 0, outerR * 0.4); + hub.fillStyle(0xc9a24e, 1); hub.fillCircle(0, -1, outerR * 0.36); + hub.fillStyle(0x8a6a2a, 1); hub.fillCircle(0, 0, outerR * 0.26); + hub.fillStyle(0xf1d58a, 0.8); hub.fillCircle(-outerR * 0.08, -outerR * 0.1, outerR * 0.07); + container.add(hub); + + const pointer = scene.add.graphics(); + const pw = outerR * 0.17, ph = outerR * 0.32, ty = -outerR - 2; + pointer.fillStyle(0x000000, 0.4); pointer.fillTriangle(-pw + 1, ty - ph + 2, pw + 1, ty - ph + 2, 1, ty + ph * 0.5 + 2); + pointer.fillStyle(0xe2c46e, 1); pointer.fillTriangle(-pw, ty - ph, pw, ty - ph, 0, ty + ph * 0.5); + pointer.lineStyle(1.5, 0x4e3810, 0.9); pointer.strokeTriangle(-pw, ty - ph, pw, ty - ph, 0, ty + ph * 0.5); + container.add(pointer); + + const names = ['Action Phase', 'Buy Phase', 'Clean-up']; + const nameHex = ['#e3796f', '#f2cf6a', '#8fb6e6']; + const labelSize = Math.max(12, Math.round(outerR * 0.34)); + const label = scene.add.text(0, -(outerR + labelSize + 6), '', TXT(labelSize, nameHex[0])).setOrigin(0.5).setVisible(false); + label.setShadow(0, 2, '#000000', 4, false, true); + container.add(label); + const applyLabel = (idx) => { label.setText(names[idx]); label.setColor(nameHex[idx]); }; + + container.setAlpha(0.55); + + return { + container, + _active: false, + _phaseIdx: 0, + _pulse: null, + _rot: null, + setActive(on) { + if (this._active === on) return; + this._active = on; + scene.tweens.add({ targets: container, alpha: on ? 1 : 0.55, duration: 300, ease: 'Sine.Out' }); + if (on) { + paintWedges(this._phaseIdx); + applyLabel(this._phaseIdx); + label.setVisible(true); + this._pulse?.remove(); + this._pulse = scene.tweens.add({ targets: container, scaleX: 1.05, scaleY: 1.05, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + } else { + this._pulse?.remove(); this._pulse = null; + this._rot?.remove(); this._rot = null; + scene.tweens.add({ targets: container, scaleX: 1, scaleY: 1, duration: 200 }); + ring.rotation = 0; + icons.forEach((g) => { g.rotation = 0; }); + this._phaseIdx = 0; + paintWedges(-1); + label.setVisible(false); + } + }, + setPhase(name) { + const idx = PHASE[name] ?? 0; + if (idx === this._phaseIdx) return; + this._phaseIdx = idx; + paintWedges(idx); + applyLabel(idx); + this._rot?.remove(); + this._rot = scene.tweens.add({ + targets: ring, rotation: -idx * TWO_PI_3, duration: 500, ease: 'Cubic.Out', + onUpdate: () => { icons.forEach((g) => { g.rotation = -ring.rotation; }); }, + onComplete: () => { icons.forEach((g) => { g.rotation = -ring.rotation; }); }, + }); + }, + destroy() { container.destroy(true); }, + }; +} diff --git a/src/games/dominion/DominionLayout.js b/src/games/dominion/DominionLayout.js new file mode 100644 index 0000000..ebee455 --- /dev/null +++ b/src/games/dominion/DominionLayout.js @@ -0,0 +1,264 @@ +// Dominion — "Steward's Hall" screen layout (pure, no Phaser). +// +// Every rectangle the scene and the art baker use comes from computeLayout(), +// which flexes for: +// • 2–4 players (1–3 opponent plates in the right column), +// • any number of basic piles (base 7, Prosperity 9, later Potion/Ruins …) — +// treasures stack in the treasury's left column, victory cards in the right, +// anything else (Curse, …) fills extra rows, +// • a kingdom of 10 (or 11 with a future bane) in two cost-ordered rows. +// +// Coordinates are the 1920×1080 game space. Rects are {x0, y0, x1, y1}. + +export const W = 1920, H = 1080; + +// Card display sizes. +export const KCARD = { w: 150, h: 216 }; // kingdom piles + the hand +export const HAND = { w: 150, h: 216 }; +export const PLAY = { w: 100, h: 144 }; // the play mat +export const MINI = { w: 34, h: 49 }; // opponent hand (backs) +export const MINI_DISC = { w: 44, h: 64 }; // opponent deck / discard +export const SHOW = { w: 270, h: 390 }; // purchase showcase / large art +export const HOVER = { w: 264, h: 380 }; + +// Heraldic seat colours (field) + gold charge drawn on each seat's banner. +export const SEAT_COLORS = [0x8e1f2c, 0x23508f, 0x2f6b3b, 0x5e3a86]; +export const SEAT_HEX = ['#8e1f2c', '#23508f', '#2f6b3b', '#5e3a86']; +export const SEAT_CHARGES = ['chevron', 'cross', 'mullet', 'tower']; + +export const rect = (x0, y0, x1, y1) => ({ x0, y0, x1, y1 }); +export const centred = (x, y, w, h) => rect(x - w / 2, y - h / 2, x + w / 2, y + h / 2); +export const rectW = (r) => r.x1 - r.x0; +export const rectH = (r) => r.y1 - r.y0; +export const rectCX = (r) => (r.x0 + r.x1) / 2; +export const rectCY = (r) => (r.y0 + r.y1) / 2; +export const rectsOverlap = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; +export const inside = (inner, outer, m = 0) => + inner.x0 >= outer.x0 - m && inner.x1 <= outer.x1 + m && inner.y0 >= outer.y0 - m && inner.y1 <= outer.y1 + m; +export const onScreen = (r, m = 0) => r.x0 >= -m && r.y0 >= -m && r.x1 <= W + m && r.y1 <= H + m; + +// Fixed regions. +export const TREASURY = rect(16, 12, 336, 548); +export const RUNNER_ZONE = rect(352, 12, 1544, 548); // kingdom + clock + trash share this +export const PLATE_COL = rect(1560, 74, 1904, 852); // opponent plates (music player sits above) +export const MUSIC = { right: 1908, top: 0 }; +export const MAT = rect(360, 560, 1536, 772); // the play mat +export const MAT_CARD_Y = 684; +export const RIBBON_Y = 586; // prompt ribbon / mat title +export const TRAY = rect(360, 784, 968, 852); // steward's tray +export const DOCK = rect(984, 784, 1536, 852); // End Action / End Turn / prompt buttons +export const HUMAN_PLATE = rect(16, 560, 336, 852); +export const DECK = { x: 176, y: 966 }; +export const DISCARD = { x: 1650, y: 966 }; +export const HAND_ZONE = rect(360, 858, 1536, 1076); +export const HAND_Y = 966; +export const LEAVE = { x: 1838, y: 1046, w: 120, h: 40 }; + +// Tray wells (Actions | Buys | Coins). +export const TRAY_WELLS = { + actions: rect(372, 792, 552, 844), + buys: rect(564, 792, 744, 844), + coins: rect(756, 792, 956, 844), +}; + +// Split basic-pile ids into treasury columns. typeOf(id) → array of types. +export function splitBasics(ids, typeOf) { + const treasure = [], victory = [], other = []; + for (const id of ids) { + const t = typeOf(id); + if (t.includes('curse')) other.push(id); + else if (t.includes('treasure')) treasure.push(id); + else if (t.includes('victory')) victory.push(id); + else other.push(id); + } + return { treasure, victory, other }; +} + +/** + * @param {object} o + * @param {number} o.playerCount 2–4 + * @param {{treasure:string[], victory:string[], other:string[]}} o.basics + * @param {number} [o.kingdomCount=10] + */ +export function computeLayout({ playerCount, basics, kingdomCount = 10 }) { + const L = { + playerCount, TREASURY, RUNNER_ZONE, PLATE_COL, MAT, MAT_CARD_Y, RIBBON_Y, TRAY, TRAY_WELLS, + DOCK, HUMAN_PLATE, DECK, DISCARD, HAND_ZONE, HAND_Y, LEAVE, MUSIC, + }; + + // ── Treasury: two columns of landscape tiles, extra rows for the rest ───── + const colA = basics.treasure, colB = basics.victory; + const otherRows = Math.ceil(basics.other.length / 2); + const rows = Math.max(colA.length, colB.length) + otherRows; + // Each row: tile (h) + count plaque under it (≈22) + breathing room. + const top = TREASURY.y0 + 38, bottom = TREASURY.y1 - 8; + const pitch = (bottom - top) / Math.max(1, rows); + const tileH = Math.floor(Math.min(96, pitch - 28)); + const tileW = 140; + const colX = [TREASURY.x0 + 20 + tileW / 2, TREASURY.x1 - 20 - tileW / 2]; + const tiles = []; + const tileAt = (id, col, row, x = colX[col]) => { + const y = top + pitch * row + 4 + tileH / 2; + tiles.push({ id, x, y, w: tileW, h: tileH }); + }; + colA.forEach((id, r) => tileAt(id, 0, r)); + colB.forEach((id, r) => tileAt(id, 1, r)); + const baseRow = Math.max(colA.length, colB.length); + basics.other.forEach((id, i) => { + const row = baseRow + Math.floor(i / 2); + const lastAlone = i === basics.other.length - 1 && i % 2 === 0; + tileAt(id, i % 2, row, lastAlone ? rectCX(TREASURY) : colX[i % 2]); + }); + L.tiles = tiles; + L.tileSize = { w: tileW, h: tileH }; + + // ── Kingdom: two rows on the baize runner; clock + trash to its right ──── + const kCols = Math.ceil(kingdomCount / 2); + const side = 176; // clock / trash column width + const gap = 26; + const maxRunnerW = rectW(RUNNER_ZONE) - side - 24; + const kw = Math.min(KCARD.w, Math.floor((maxRunnerW - 56 - (kCols - 1) * gap) / kCols)); + const kh = Math.round(kw * KCARD.h / KCARD.w); + const runnerW = kCols * kw + (kCols - 1) * gap + 56; + const totalW = runnerW + 24 + side; + const rx0 = Math.round(RUNNER_ZONE.x0 + (rectW(RUNNER_ZONE) - totalW) / 2); + L.runner = rect(rx0, RUNNER_ZONE.y0, rx0 + runnerW, RUNNER_ZONE.y1); + L.kSize = { w: kw, h: kh }; + const rowY = [132, 392]; + L.kingdom = []; + for (let i = 0; i < kingdomCount; i++) { + const r = Math.floor(i / kCols), c = i % kCols; + const n = r === 0 ? Math.min(kCols, kingdomCount) : kingdomCount - kCols; + const rowW = n * kw + (n - 1) * gap; + const x0 = rectCX(L.runner) - rowW / 2 + kw / 2; + L.kingdom.push({ x: x0 + c * (kw + gap), y: rowY[r] }); + } + const sx0 = L.runner.x1 + 24; + L.clock = rect(sx0, RUNNER_ZONE.y0, sx0 + side, 262); + L.trash = rect(sx0, 276, sx0 + side, RUNNER_ZONE.y1); + L.trashCard = { x: rectCX(L.trash), y: 412, w: 110, h: 158 }; + + // ── Opponent plates ─────────────────────────────────────────────────────── + const nOpp = playerCount - 1; + const pgap = 14; + const ph = Math.min(300, Math.floor((rectH(PLATE_COL) - (nOpp - 1) * pgap) / Math.max(1, nOpp))); + const stackH = nOpp * ph + (nOpp - 1) * pgap; + const py0 = Math.round(PLATE_COL.y0 + (rectH(PLATE_COL) - stackH) / 2); + L.plates = []; + for (let i = 0; i < nOpp; i++) { + const y0 = py0 + i * (ph + pgap); + const x0 = PLATE_COL.x0; + const r = rect(x0, y0, PLATE_COL.x1, y0 + ph); + const by = y0 + ph - 50; // bottom row (deck / discard / hand) + L.plates.push({ + seat: i + 1, + rect: r, + banner: rect(x0 + 12, y0 - 4, x0 + 60, y0 + Math.min(150, ph - 70)), + portrait: { x: x0 + 112, y: y0 + 64, r: 42 }, + name: { x: x0 + 112, y: y0 + 120 }, + dial: { x: x0 + 214, y: y0 + 70, r: 26 }, + vp: { x: x0 + 292, y: y0 + 54 }, + mat: rect(x0 + 252, y0 + 86, x0 + 334, y0 + 128), // reserved (Seaside mats, Coffers…) + deck: { x: x0 + 92, y: by }, + discard: { x: x0 + 148, y: by }, + hand: { x: x0 + 262, y: by, w: 140 }, + }); + } + + // ── Human seat ──────────────────────────────────────────────────────────── + L.human = { + rect: HUMAN_PLATE, + banner: rect(HUMAN_PLATE.x0 + 12, HUMAN_PLATE.y0 - 4, HUMAN_PLATE.x0 + 60, HUMAN_PLATE.y0 + 150), + portrait: { x: 136, y: 648, r: 54 }, + name: { x: 136, y: 724 }, + dial: { x: 266, y: 660, r: 50 }, + vp: { x: 176, y: 800 }, + }; + return L; +} + +// Seat anchors (portrait) — used for flights to/from a player. +export function seatAnchor(L, seat) { + if (seat === 0) return L.human.portrait; + return L.plates[seat - 1]?.portrait ?? { x: rectCX(PLATE_COL), y: rectCY(PLATE_COL), r: 40 }; +} + +// x positions for a row of `n` cards of width `w`, centred on cx and squeezed +// (overlapping) to fit maxW. Returns { xs, step }. +export function rowPositions(n, w, cx, maxW, gap = 10) { + if (n <= 0) return { xs: [], step: 0 }; + let step = w + gap; + if (n > 1 && (n - 1) * step + w > maxW) step = (maxW - w) / (n - 1); + const total = (n - 1) * step + w; + const x0 = cx - total / 2 + w / 2; + return { xs: Array.from({ length: n }, (_, i) => x0 + i * step), step }; +} + +// The play mat: in-play cards in order. `tucked[i]` = card i is tucked under +// card i-1 (a Throne Room / King's Court target) and shares its slot, offset. +export const TUCK_DX = 34, TUCK_DY = 12; +export function inPlayPositions(n, tucked = []) { + const slots = []; + for (let i = 0; i < n; i++) if (!tucked[i] || i === 0) slots.push(i); + const maxW = rectW(MAT) - 40; + const { xs } = rowPositions(slots.length, PLAY.w + TUCK_DX * 0.5, rectCX(MAT), maxW, 10); + const out = new Array(n); + let s = -1; + for (let i = 0; i < n; i++) { + if (!tucked[i] || i === 0) { s++; out[i] = { x: xs[s] - TUCK_DX * 0.25, y: MAT_CARD_Y, tucked: false }; } + else { const p = out[i - 1]; out[i] = { x: p.x + TUCK_DX, y: p.y + TUCK_DY, tucked: true }; } + } + return out; +} + +// The human's hand row. +export function handPositions(n) { + return rowPositions(n, HAND.w, rectCX(HAND_ZONE), rectW(HAND_ZONE) - 8, 12); +} + +// Opponent mini hand fan inside a plate. +export function oppHandPositions(plate, n) { + return rowPositions(n, MINI.w, plate.hand.x, plate.hand.w, 4); +} + +// Every piece of fixed furniture, for overlap checks (verify script). +export function furniture(L) { + const out = [ + ['treasury', TREASURY], + ['runner', L.runner], + ['clock', L.clock], + ['trash', L.trash], + ['mat', MAT], + ['tray', TRAY], + ['dock', DOCK], + ['humanPlate', HUMAN_PLATE], + ['deck', centred(DECK.x, DECK.y, HAND.w, HAND.h)], + ['discard', centred(DISCARD.x, DISCARD.y, HAND.w, HAND.h)], + ['hand', HAND_ZONE], + ['leave', centred(LEAVE.x, LEAVE.y, LEAVE.w, LEAVE.h)], + ['music', rect(MUSIC.right - 90, 0, MUSIC.right, 70)], + ]; + L.plates.forEach((p, i) => out.push([`plate${i + 1}`, p.rect])); + return out; +} + +// Children that must sit inside their parent furniture. +export function furnitureChildren(L) { + const out = []; + for (const t of L.tiles) out.push([`tile:${t.id}`, centred(t.x, t.y + 9, t.w + 6, t.h + 28), TREASURY]); + L.kingdom.forEach((k, i) => out.push([`kingdom${i}`, centred(k.x, k.y + 10, L.kSize.w, L.kSize.h + 44), L.runner])); + out.push(['trashCard', centred(L.trashCard.x, L.trashCard.y, L.trashCard.w, L.trashCard.h), L.trash]); + for (const p of L.plates) { + const pr = p.rect; + out.push([`plate${p.seat}:portrait`, centred(p.portrait.x, p.portrait.y, p.portrait.r * 2, p.portrait.r * 2), pr]); + out.push([`plate${p.seat}:dial`, centred(p.dial.x, p.dial.y, p.dial.r * 2, p.dial.r * 2), pr]); + out.push([`plate${p.seat}:deck`, centred(p.deck.x, p.deck.y, MINI_DISC.w, MINI_DISC.h), pr]); + out.push([`plate${p.seat}:discard`, centred(p.discard.x, p.discard.y, MINI_DISC.w, MINI_DISC.h), pr]); + out.push([`plate${p.seat}:hand`, centred(p.hand.x, p.hand.y, p.hand.w, MINI.h), pr]); + } + const h = L.human; + out.push(['human:portrait', centred(h.portrait.x, h.portrait.y, h.portrait.r * 2, h.portrait.r * 2), HUMAN_PLATE]); + out.push(['human:dial', centred(h.dial.x, h.dial.y, h.dial.r * 2, h.dial.r * 2), HUMAN_PLATE]); + for (const [k, r] of Object.entries(TRAY_WELLS)) out.push([`well:${k}`, r, TRAY]); + return out; +} diff --git a/src/games/dominion/DominionScoring.js b/src/games/dominion/DominionScoring.js new file mode 100644 index 0000000..707f8ff --- /dev/null +++ b/src/games/dominion/DominionScoring.js @@ -0,0 +1,72 @@ +// Dominion — pure helpers for the table and the end screen (no Phaser): +// reckoning(state, seat) VP groups + deck census for the scoring ceremony +// seatStats(state, seat) bought / signature card / turns from the log +// tuckInfo(log, seat, cards) which in-play cards were doubled by Throne Room +// / King's Court (drawn tucked under it) + +import { getCard, isType } from './DominionCards.js'; +import { allCards } from './DominionLogic.js'; + +export function reckoning(state, seat) { + const cards = allCards(state, seat); + const counts = new Map(); + for (const c of cards) counts.set(c.id, (counts.get(c.id) ?? 0) + 1); + const groups = []; + for (const [id, n] of counts) { + const def = getCard(id); + let each = null; + if (id === 'gardens') each = Math.floor(cards.length / 10); + else if (def.vp !== undefined && (isType(id, 'victory') || isType(id, 'curse'))) each = def.vp; + if (each === null) continue; + groups.push({ id, n, each, vp: n * each }); + } + groups.sort((a, b) => (b.each - a.each) || (b.n - a.n) || (a.id < b.id ? -1 : 1)); + const census = { treasure: 0, action: 0, victory: 0, curse: 0 }; + for (const c of cards) { + const t = getCard(c.id).types; + if (t.includes('curse')) census.curse++; + else if (t.includes('action')) census.action++; + else if (t.includes('treasure')) census.treasure++; + else census.victory++; + } + return { groups, census, total: cards.length, tokens: state.players[seat].vpTokens ?? 0 }; +} + +export function seatStats(state, seat) { + let bought = 0; + const plays = new Map(); + for (const e of state.log) { + if (e.seat !== seat) continue; + if (e.kind === 'buy') bought++; + else if (e.kind === 'play') plays.set(e.id, (plays.get(e.id) ?? 0) + 1); + } + let signature = null; + for (const [id, n] of plays) if (!signature || n > signature.n) signature = { id, n }; + return { bought, signature, turns: state.turnsTaken[seat] ?? 0 }; +} + +const DOUBLERS = { throneroom: 2, kingscourt: 3 }; + +export function tuckInfo(log, seat, cards) { + const tucked = new Array(cards.length).fill(false); + const mult = new Array(cards.length).fill(0); + let start = 0; + for (let i = log.length - 1; i >= 0; i--) { + const e = log[i]; + if (e.kind === 'turnStart' && e.seat === seat) { start = i; break; } + } + const pool = new Map(); + for (let i = start; i < log.length; i++) { + const e = log[i]; + if (e.kind === 'play' && e.throne && e.seat === seat) pool.set(e.id, (pool.get(e.id) ?? 0) + 1); + } + for (let i = 1; i < cards.length; i++) { + const k = DOUBLERS[cards[i - 1].id]; + if (k && (pool.get(cards[i].id) ?? 0) > 0) { + pool.set(cards[i].id, pool.get(cards[i].id) - 1); + tucked[i] = true; + mult[i] = k; + } + } + return { tucked, mult }; +} diff --git a/tools/verifyDominion.js b/tools/verifyDominion.js new file mode 100644 index 0000000..7f6cad0 --- /dev/null +++ b/tools/verifyDominion.js @@ -0,0 +1,240 @@ +#!/usr/bin/env node +// verifyDominion.js — headless checks for the Dominion "Steward's Hall" table: +// • screen layout for every variant (2–4 players × Base/Prosperity × every +// preset + Random): furniture on screen, no overlaps, children inside their +// parents, one treasury tile per basic pile, kingdom slots that don't touch, +// in-play / hand / opponent-fan rows that stay inside their furniture +// • card art: every card's frame exists in its sheet (PNG header sizes) +// • scoring ceremony maths (reckoning) equals the engine's finalScores, and +// seatStats agrees with the log, across an all-AI soak +// • Throne Room / King's Court tuck detection only tucks real doubled cards +// • engine fingerprint: the AI-vs-AI games are byte-for-byte what they were +// before the table overhaul (the overhaul must not touch the rules) +// Usage: node tools/verifyDominion.js [--quick] + +import fs from 'node:fs'; +import * as Lg from '../src/games/dominion/DominionLogic.js'; +import * as AI from '../src/games/dominion/DominionAI.js'; +import { CARDS, getCard, isType } from '../src/games/dominion/DominionCards.js'; +import { registerExpansionCards } from '../src/games/dominion/expansions/index.js'; +import { + computeLayout, splitBasics, furniture, furnitureChildren, inPlayPositions, handPositions, + oppHandPositions, rectsOverlap, inside, onScreen, centred, MAT, HAND_ZONE, PLAY, HAND, MINI, +} from '../src/games/dominion/DominionLayout.js'; +import { reckoning, seatStats, tuckInfo } from '../src/games/dominion/DominionScoring.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); + +const VARIANTS = [ + ['base', ['standard', 'size-distortion', 'deck-top', 'silver-gold', 'helpful-actions', 'random']], + ['prosperity', ['beginners', 'friendly-interactive', 'bigger-treasures', 'the-king', 'random']], +]; + +function layoutFor(state) { + const basicIds = Object.keys(state.supply).filter((id) => !state.kingdom.includes(id)); + basicIds.sort((a, b) => getCard(a).cost - getCard(b).cost); + return { + L: computeLayout({ playerCount: state.playerCount, basics: splitBasics(basicIds, (id) => getCard(id).types), kingdomCount: state.kingdom.length }), + basicIds, + }; +} + +// ── Layout ────────────────────────────────────────────────────────────────── +section('Layout'); +{ + const seen = new Set(); + for (const [exp, modes] of VARIANTS) { + for (const mode of modes) { + for (let pc = 2; pc <= 4; pc++) { + for (let seed = 1; seed <= (mode === 'random' ? 6 : 1); seed++) { + const s = Lg.createInitialState({ seed: seed * 101 + pc, playerCount: pc, deckMode: mode, expansion: exp }); + const { L, basicIds } = layoutFor(s); + const tag = `${exp}/${mode}/${pc}p`; + const furn = furniture(L); + for (const [name, r] of furn) ok(`${tag} ${name} on screen`, onScreen(r), JSON.stringify(r)); + for (let i = 0; i < furn.length; i++) { + for (let j = i + 1; j < furn.length; j++) { + const [a, ra] = furn[i], [b, rb] = furn[j]; + ok(`${tag} ${a} ∩ ${b}`, !rectsOverlap(ra, rb), `${JSON.stringify(ra)} vs ${JSON.stringify(rb)}`); + } + } + for (const [name, r, parent] of furnitureChildren(L)) ok(`${tag} ${name} inside parent`, inside(r, parent, 0.5), `${JSON.stringify(r)} in ${JSON.stringify(parent)}`); + ok(`${tag} one tile per basic pile`, L.tiles.length === basicIds.length && basicIds.every((id) => L.tiles.some((t) => t.id === id))); + ok(`${tag} tiles readable`, L.tileSize.h >= 70, `h=${L.tileSize.h}`); + ok(`${tag} kingdom slot per card`, L.kingdom.length === s.kingdom.length); + for (let i = 0; i < L.tiles.length; i++) for (let j = i + 1; j < L.tiles.length; j++) { + const a = L.tiles[i], b = L.tiles[j]; + ok(`${tag} tiles ${a.id}/${b.id} apart`, !rectsOverlap(centred(a.x, a.y + 9, a.w, a.h + 28), centred(b.x, b.y + 9, b.w, b.h + 28))); + } + for (let i = 0; i < L.kingdom.length; i++) for (let j = i + 1; j < L.kingdom.length; j++) { + const a = L.kingdom[i], b = L.kingdom[j]; + ok(`${tag} kingdom ${i}/${j} apart`, !rectsOverlap(centred(a.x, a.y + 10, L.kSize.w, L.kSize.h + 40), centred(b.x, b.y + 10, L.kSize.w, L.kSize.h + 40))); + } + ok(`${tag} kingdom in cost order`, s.kingdom.every((id, i) => i === 0 || getCard(s.kingdom[i - 1]).cost <= getCard(id).cost)); + ok(`${tag} plates for every opponent`, L.plates.length === pc - 1); + const sig = `${pc}-${L.tiles.length}`; + if (!seen.has(sig)) { + seen.add(sig); + for (const p of L.plates) { + for (let n = 0; n <= 14; n++) { + const { xs } = oppHandPositions(p, n); + ok(`${tag} plate ${p.seat} fan of ${n} inside`, xs.every((x) => x - MINI.w / 2 >= p.rect.x0 && x + MINI.w / 2 <= p.rect.x1)); + } + } + } + } + } + } + } + // Rows that grow with the game. + for (let n = 1; n <= 30; n++) { + const pos = inPlayPositions(n, []); + ok(`in-play ${n} inside mat`, pos.every((p) => p.x - PLAY.w / 2 >= MAT.x0 && p.x + PLAY.w / 2 <= MAT.x1 && p.y + PLAY.h / 2 <= MAT.y1)); + const tucked = Array.from({ length: n }, (_, i) => i % 3 === 2); + const tp = inPlayPositions(n, tucked); + ok(`in-play ${n} with tucks inside mat`, tp.every((p) => p.x - PLAY.w / 2 >= MAT.x0 - 0.5 && p.x + PLAY.w / 2 <= MAT.x1 + 0.5 && p.y + PLAY.h / 2 <= MAT.y1)); + ok(`in-play ${n} tucked follow parent`, tp.every((p, i) => !tucked[i] || p.x > tp[i - 1].x)); + } + for (let n = 1; n <= 20; n++) { + const { xs } = handPositions(n); + ok(`hand ${n} inside zone`, xs.every((x) => x - HAND.w / 2 >= HAND_ZONE.x0 && x + HAND.w / 2 <= HAND_ZONE.x1)); + ok(`hand ${n} ordered`, xs.every((x, i) => i === 0 || x > xs[i - 1])); + } +} + +// ── Card art ──────────────────────────────────────────────────────────────── +section('Card art'); +{ + registerExpansionCards(); + const pngSize = (f) => { const b = fs.readFileSync(f); return { w: b.readUInt32BE(16), h: b.readUInt32BE(20) }; }; + const sheets = { + 'dominion-cards': pngSize('assets/images/dominioncards.png'), + 'dominion-prosperity': pngSize('assets/images/dominion-prosperity.png'), + }; + for (const def of Object.values(CARDS)) { + const sh = sheets[def.sheet]; + ok(`${def.id} sheet known`, !!sh, def.sheet); + if (!sh) continue; + const frames = Math.floor(sh.w / 270) * Math.floor(sh.h / 390); + ok(`${def.id} frame ${def.frame} in sheet`, def.frame >= 0 && def.frame < frames, `${frames} frames`); + } + const used = new Map(); + for (const def of Object.values(CARDS)) { + const k = `${def.sheet}#${def.frame}`; + ok(`${def.id} frame not shared`, !used.has(k), used.get(k)); + used.set(k, def.id); + } +} + +// ── Soak: scoring ceremony + tucks + engine fingerprint ──────────────────── +section('Soak'); +function playGame(seed, pc, exp, mode, onStep) { + let s = Lg.createInitialState({ seed, playerCount: pc, deckMode: mode, expansion: exp }); + let steps = 0; + while (!Lg.isGameOver(s) && steps < 20000) { + steps++; + if (s.pending) s = Lg.resolvePending(s, AI.resolvePending(s, 3)); + else { + const seat = s.turn; + if (s.phase === 'action') { const iid = AI.chooseAction(s, seat); s = iid != null ? Lg.playAction(s, iid) : Lg.endActionPhase(s); } + else if (s.players[seat].hand.some((c) => isType(c.id, 'treasure'))) s = Lg.playAllTreasures(s); + else { const b = AI.chooseBuy(s, seat, 3); s = b ? Lg.buyCard(s, b) : Lg.endTurn(s); } + } + onStep?.(s); + } + return s; +} +{ + const out = []; + let tuckSeen = 0; + for (const [exp, modes] of [['base', ['standard', 'size-distortion', 'random']], ['prosperity', ['beginners', 'the-king', 'random']]]) { + for (const mode of modes) { + for (let pc = 2; pc <= 4; pc++) { + for (let seed = 1; seed <= 4; seed++) { + const s = playGame(seed * 7919 + pc, pc, exp, mode, (st) => { + const seat = st.turn; + const cards = st.players[seat].inPlay; + const { tucked, mult } = tuckInfo(st.log, seat, cards); + for (let i = 0; i < cards.length; i++) { + if (!tucked[i]) continue; + tuckSeen++; + const parent = cards[i - 1]?.id; + if (!(parent === 'throneroom' || parent === 'kingscourt') || !isType(cards[i].id, 'action') || mult[i] !== (parent === 'kingscourt' ? 3 : 2)) { + ok(`tuck ${exp}/${mode} under ${parent}`, false, cards.map((c) => c.id).join(',')); + } else pass++; + } + }); + out.push(Lg.finalScores(s).map((x) => x.vp).join(',') + '|' + s.turnsTaken.join(',') + '|' + s.log.length); + const scores = Lg.finalScores(s); + for (const sc of scores) { + const rk = reckoning(s, sc.seat); + const sum = rk.groups.reduce((a, g) => a + g.vp, 0) + rk.tokens; + ok(`${exp}/${mode}/${pc}p seed ${seed} seat ${sc.seat} reckoning = finalScores`, sum === sc.vp, `${sum} vs ${sc.vp}`); + ok('census adds up', rk.census.treasure + rk.census.action + rk.census.victory + rk.census.curse === rk.total); + const st = seatStats(s, sc.seat); + ok('bought = buy log events', st.bought === s.log.filter((e) => e.kind === 'buy' && e.seat === sc.seat).length); + ok('turns match', st.turns === s.turnsTaken[sc.seat]); + } + ok(`${exp}/${mode}/${pc}p seed ${seed} game finished`, Lg.isGameOver(s)); + } + } + } + } + // The AI rarely buys Throne Room, so script the tuck cases directly. + const scripted = (exp, hand, steps) => { + let st = Lg.createInitialState({ seed: 5, playerCount: 2, deckMode: exp === 'base' ? 'size-distortion' : 'the-king', expansion: exp }); + st.players[0].hand = hand.map((id, i) => ({ iid: 9000 + i, id })); + for (const step of steps) st = step(st); + return { st, ...tuckInfo(st.log, 0, st.players[0].inPlay) }; + }; + { + const { st, tucked, mult } = scripted('base', ['throneroom', 'smithy', 'copper'], [ + (s) => Lg.playAction(s, 9000), (s) => Lg.resolvePending(s, { iid: 9001 }), + ]); + ok('Throne Room target tucked ×2', st.players[0].inPlay.map((c) => c.id).join() === 'throneroom,smithy' && tucked[1] && mult[1] === 2, JSON.stringify({ tucked, mult })); + } + { + const { st, tucked } = scripted('base', ['village', 'throneroom', 'smithy'], [ + (s) => Lg.playAction(s, 9000), (s) => Lg.playAction(s, 9001), (s) => Lg.resolvePending(s, { iid: null }), + (s) => Lg.playAction(s, 9002), + ]); + ok('skipped Throne Room tucks nothing', st.players[0].inPlay.some((c) => c.id === 'smithy') && !tucked.some(Boolean), JSON.stringify({ ids: st.players[0].inPlay.map((c) => c.id), tucked })); + } + { + const { st, tucked, mult } = scripted('prosperity', ['kingscourt', 'smithy', 'copper'], [ + (s) => Lg.playAction(s, 9000), (s) => Lg.resolvePending(s, { iid: 9001 }), + ]); + ok("King's Court target tucked ×3", st.players[0].inPlay.map((c) => c.id).join() === 'kingscourt,smithy' && tucked[1] && mult[1] === 3, JSON.stringify({ ids: st.players[0].inPlay.map((c) => c.id), tucked, mult })); + } + // Recorded from the engine + AI before the 2026-11-25 table overhaul. + // Base games must be byte-for-byte what they were before the overhaul (the + // AI's buy-restriction fix only touches Prosperity, whose games used to stall). + let hb = 0; + for (const ch of out.slice(0, 36).join(';')) hb = (Math.imul(hb, 31) + ch.charCodeAt(0)) >>> 0; + ok('base engine fingerprint unchanged (36 AI games)', hb === 2754080371, `hash ${hb}`); + ok('72 soak games recorded', out.length === 72, `${out.length}`); +} + +// ── Larger random soak ────────────────────────────────────────────────────── +if (!QUICK) { + section('Random soak'); + for (let g = 0; g < 120; g++) { + const exp = g % 2 ? 'prosperity' : 'base'; + const pc = 2 + (g % 3); + const s = playGame(90000 + g, pc, exp, 'random'); + ok(`random game ${g} finished`, Lg.isGameOver(s)); + for (const sc of Lg.finalScores(s)) { + const rk = reckoning(s, sc.seat); + ok(`random game ${g} seat ${sc.seat} reckoning`, rk.groups.reduce((a, x) => a + x.vp, 0) + rk.tokens === sc.vp); + } + } +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);