Overhaul Dominion table with Steward's Hall art and scoring ceremony

- Add procedural "Steward's Hall" visuals (DominionArt.js): baked oak
  table, candlelight, treasury tiles, baize runner, steward tray, banners,
  parchment panels, and type-coloured card faces for both sizes.
- Extract a pure layout engine (DominionLayout.js) that flexes for 2–4
  players, any basic-pile set, and the kingdom; verify it headlessly with
  tools/verifyDominion.js across every variant.
- Add persistent HUD furniture (DominionHud.js): Steward's tray with coin
  flights, Province/Colony end clock with empty-pile seals, VP token dishes,
  heraldic seat banners, and the brass phase dial.
- Replace the plain game-over modal with "The Reckoning" ceremony
  (DominionEndScreen.js) that counts victory cards group by group and crowns
  the winner; add scoring helpers in DominionScoring.js.
- Fix AI stalling on restricted buys (e.g. Grand Market) by skipping cards
  buyAllowed rejects, and end the turn if a buy is rejected as a safety net.
- Add a kingdom-reveal intro, trash viewer, tuck display for Throne Room /
  King's Court targets, and an all-AI soak that keeps base-game results
  byte-for-byte identical to before the overhaul.
This commit is contained in:
Brian Fertig 2026-11-25 18:09:17 -07:00
parent c530bc5b30
commit d1906f6b94
No known key found for this signature in database
8 changed files with 3054 additions and 982 deletions

View File

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

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

240
tools/verifyDominion.js Normal file
View File

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