Rework Monopoly into the Boardwalk Hotel with full rules and UI

- Rewrite the logic engine for official rules: debt queue, raise-funds phase,
  bankruptcy to a player (buildings at half, mortgages carried with 10% interest)
  or to the bank (auctions), even building/selling, housing shortage, Get Out of
  Jail Free cards leaving the deck while held, and stats/history tracking.
- Add house rules and modes: Short Game (dealt deeds, 3-house hotels, end at first
  bankruptcy), starting cash, Free Parking jackpot, double GO, auctions toggle, and
  round limit, all configurable from a new setup card and Front Desk menu.
- Replace the flat board with a baked Art Deco parlour: procedural board art,
  title-deed cards, banker's tray with flying bills, house/hotel rack, felt dice
  tray with 3D dice, player plaques with deed rails, ledger, and Web Audio SFX.
- Split the scene into focused modules (Art, Bank, Deed, Dialogs, EndScreen, Hud,
  Layout, Sound, Trade, Tray) and add a stats-rich end screen plus mid-game
  bankruptcy watch mode.
- Improve AI decisions for buying, bidding, jail, building/unmortgaging, debt
  resolution, and trades; default to three opponents and enable the tutorial.
- Add tools/verifyMonopoly.js for headless rules, AI soak, save round-trip, and
  layout checks; replace sprites.md with a written tutorial.
This commit is contained in:
Brian Fertig 2026-11-26 20:50:56 -07:00
parent 14c17d2eb0
commit 3fba22fc9f
No known key found for this signature in database
18 changed files with 5690 additions and 3224 deletions

View File

@ -75,7 +75,7 @@ registerGame({ slug: 'videopoker', name: 'Video Poker', category: 'casino', card
registerGame({ slug: 'farkel', name: 'Farkle', category: 'cards', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 45 }); registerGame({ slug: 'farkel', name: 'Farkle', category: 'cards', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 45 });
registerGame({ slug: 'stratego', name: 'Stratego', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: false, iconFrame: 46, defaultPlayfield: 'combat' }); registerGame({ slug: 'stratego', name: 'Stratego', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: false, iconFrame: 46, defaultPlayfield: 'combat' });
registerGame({ slug: 'kiitos', name: 'Kiitos', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 47 }); registerGame({ slug: 'kiitos', name: 'Kiitos', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 47 });
registerGame({ slug: 'monopoly', name: 'Monopoly', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 48, defaultPlayfield: 'cherry' }); registerGame({ slug: 'monopoly', name: 'Monopoly', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, defaultOpponents: 3, hasTutorial: true, iconFrame: 48 });
registerGame({ slug: 'triominoes', name: 'Tri-Ominoes', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 49 }); registerGame({ slug: 'triominoes', name: 'Tri-Ominoes', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 49 });
registerGame({ slug: 'freecell', name: 'Freecell', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 50 }); registerGame({ slug: 'freecell', name: 'Freecell', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 50 });
registerGame({ slug: 'rushhour', name: 'Rush Hour', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, hasTutorial: true, iconFrame: 51 }); registerGame({ slug: 'rushhour', name: 'Rush Hour', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, hasTutorial: true, iconFrame: 51 });

View File

@ -5,6 +5,8 @@ import {
} from './MonopolyData.js'; } from './MonopolyData.js';
import { import {
ownsGroup, canBuildHouse, canBuildHotel, netWorth, isTradeable, validateTrade, ownsGroup, canBuildHouse, canBuildHotel, netWorth, isTradeable, validateTrade,
canMortgage, canSellHouse, canSellHotel, canUnmortgage, unmortgageCost, isShort,
currentDebt, canSettleDebt, mustGoBankrupt, railroadsOwned, mortgageInterest, tradeInterest,
} from './MonopolyLogic.js'; } from './MonopolyLogic.js';
const PROFILES = { const PROFILES = {
@ -34,36 +36,84 @@ export function nextThinkDelay(skill) {
return rnd(lo, hi); return rnd(lo, hi);
} }
// ── Shared valuation ────────────────────────────────────────────────────────────
function groupStats(state, seat, idx) {
const key = groupKey(idx);
const idxs = groupIndices(key);
const mine = idxs.filter(i => state.board[i]?.owner === seat).length;
let oppMax = 0;
for (const p of state.players) {
if (p.seat === seat || !p.active) continue;
oppMax = Math.max(oppMax, idxs.filter(i => state.board[i]?.owner === p.seat).length);
}
return { key, n: idxs.length, mine, oppMax };
}
// What `seat` thinks an unowned deed is worth to them.
export function aiValue(state, seat, idx, skill) {
const prof = PROFILES[skill] ?? PROFILES[3];
const sp = SPACES[idx];
const { key, n, mine, oppMax } = groupStats(state, seat, idx);
let v = sp.price * prof.maxBidMult;
if (key !== 'utility' && mine === n - 1) v *= skill >= 3 ? 1.7 : 1.3; // completes a set
else if (key !== 'utility' && oppMax === n - 1) v *= skill >= 3 ? 1.35 : 1.1; // blocks a set
else if (mine > 0) v *= 1.12;
if (isShort(state)) v *= 1.1;
return v;
}
// ── Buy decision ─────────────────────────────────────────────────────────────── // ── Buy decision ───────────────────────────────────────────────────────────────
export function chooseBuy(state, seat, skill) { export function chooseBuy(state, seat, skill) {
const prof = PROFILES[skill] ?? PROFILES[3]; const prof = PROFILES[skill] ?? PROFILES[3];
if (Math.random() < prof.blunder) return Math.random() < 0.5;
const { spaceIdx } = state.pendingBuy; const { spaceIdx } = state.pendingBuy;
const sp = SPACES[spaceIdx]; const sp = SPACES[spaceIdx];
const p = state.players[seat]; const p = state.players[seat];
const reserve = prof.reserve + noise(prof.noise); if (p.cash < sp.price) return false;
if (Math.random() < prof.blunder) return Math.random() < 0.5;
const { key, n, mine, oppMax } = groupStats(state, seat, spaceIdx);
let reserve = prof.reserve * (isShort(state) ? 0.5 : 1) + noise(prof.noise);
const unowned = PURCHASABLE.filter(i => state.board[i]?.owner === null).length;
if (unowned > 16) reserve *= 0.6; // land grab early on
if (key !== 'utility' && (mine === n - 1 || oppMax === n - 1)) reserve = Math.min(reserve, 40);
return p.cash - sp.price >= reserve; return p.cash - sp.price >= reserve;
} }
// ── Auction bid ─────────────────────────────────────────────────────────────── // ── Auction bid ───────────────────────────────────────────────────────────────
// Bids climb in steps (so auctions read like auctions) up to a private ceiling.
export function chooseBid(state, seat, skill) { export function chooseBid(state, seat, skill) {
const prof = PROFILES[skill] ?? PROFILES[3]; const prof = PROFILES[skill] ?? PROFILES[3];
const auc = state.pendingAuction; const auc = state.pendingAuction;
if (!auc) return null;
const sp = SPACES[auc.spaceIdx]; const sp = SPACES[auc.spaceIdx];
const p = state.players[seat]; const p = state.players[seat];
const maxBid = Math.min(p.cash * 0.7, sp.price * prof.maxBidMult + noise(prof.noise)); const keep = skill >= 3 ? Math.min(prof.reserve * 0.4, 120) : 0;
if (maxBid <= auc.highBid) return null; // pass const ceiling = Math.floor(Math.min(p.cash - keep, aiValue(state, seat, auc.spaceIdx, skill) + noise(prof.noise)));
return Math.max(auc.highBid + 1, Math.floor(maxBid)); if (ceiling <= auc.highBid) return null;
const step = Math.max(5, Math.round(sp.price * 0.1 / 5) * 5);
let bid = auc.highBid === 0
? Math.round(sp.price * (0.35 + Math.random() * 0.25) / 5) * 5
: auc.highBid + step * (Math.random() < 0.25 ? 2 : 1);
bid = Math.max(auc.highBid + 1, Math.min(bid, ceiling));
return bid;
} }
// ── Jail decision ───────────────────────────────────────────────────────────── // ── Jail decision ─────────────────────────────────────────────────────────────
// Early on, get out and buy land. Late in the game, when the board is full of
// opponents' houses, a careful player sits in Jail (rolling) and dodges rent.
export function chooseJailAction(state, seat, skill) { export function chooseJailAction(state, seat, skill) {
const prof = PROFILES[skill] ?? PROFILES[3];
const p = state.players[seat]; const p = state.players[seat];
if (p.getOutOfJailFree > 0) return 'card'; const unowned = PURCHASABLE.filter(i => state.board[i]?.owner === null).length;
if (skill >= 3 && p.cash >= 50) { let oppBuildings = 0;
// Higher skill: pay to get back in action for (const idx of PURCHASABLE) {
return 'pay'; const own = state.board[idx];
if (own.owner === null || own.owner === seat) continue;
oppBuildings += own.houses + (own.hotel ? 5 : 0);
} }
const late = unowned <= 6 && oppBuildings >= 6;
if (skill >= 3 && late) return 'roll';
if (p.getOutOfJailFree > 0) return 'card';
if (skill >= 2 && p.cash >= 50 + prof.reserve * 0.5) return 'pay';
return 'roll'; return 'roll';
} }
@ -110,7 +160,13 @@ export function scoreTrade(state, aiSeat, offer, skill, noiseless = false) {
const before = state.board; const before = state.board;
const after = boardAfter(state, offer); const after = boardAfter(state, offer);
const valueOf = idx => SPACES[idx].price ?? 0; // A mortgaged deed is worth its price less what it costs to lift (plus the
// 10% the receiver pays the bank on transfer).
const valueOf = idx => {
const sp = SPACES[idx];
if (!state.board[idx]?.mortgaged) return sp.price ?? 0;
return (sp.price ?? 0) - unmortgageCost(state, idx) - mortgageInterest(state, idx);
};
const cashDelta = giveCash - getCash; // +ve = AI receives money const cashDelta = giveCash - getCash; // +ve = AI receives money
const gainVal = giveProps.reduce((a, i) => a + valueOf(i), 0); const gainVal = giveProps.reduce((a, i) => a + valueOf(i), 0);
const loseVal = getProps.reduce((a, i) => a + valueOf(i), 0); const loseVal = getProps.reduce((a, i) => a + valueOf(i), 0);
@ -256,27 +312,78 @@ export function buildAiTradeOffer(state, aiSeat, targetSeat, skill, opts = {}) {
return null; return null;
} }
// ── Build decisions ──────────────────────────────────────────────────────────── // ── Manage: build, lift mortgages ────────────────────────────────────────────────
// Returns { action: 'house'|'hotel', spaceIdx } or null // Returns { action: 'house'|'hotel'|'unmortgage', spaceIdx } or null.
export function chooseBuild(state, seat, skill) { export function chooseManage(state, seat, skill) {
const prof = PROFILES[skill] ?? PROFILES[3]; const prof = PROFILES[skill] ?? PROFILES[3];
const p = state.players[seat]; const p = state.players[seat];
const reserve = prof.reserve * (isShort(state) ? 0.5 : 1);
// Try to build hotels first on complete sets // 1. A mortgage that blocks building on a completed set.
for (const idx of PURCHASABLE) { for (const idx of PURCHASABLE) {
if (!canBuildHotel(state, seat, idx)) continue; const own = state.board[idx];
const sp = SPACES[idx]; const sp = SPACES[idx];
if (p.cash - sp.houseCost >= prof.reserve) { if (own.owner !== seat || !own.mortgaged || sp.type !== 'property') continue;
return { action: 'hotel', spaceIdx: idx }; if (!ownsGroup(state, seat, sp.group)) continue;
if (canUnmortgage(state, seat, idx) && p.cash - unmortgageCost(state, idx) >= reserve * 0.5) {
return { action: 'unmortgage', spaceIdx: idx };
} }
} }
// Build houses on monopolies // 2. Hotels, then houses — on the group with the best rent jump per dollar.
let best = null;
for (const idx of PURCHASABLE) { for (const idx of PURCHASABLE) {
if (!canBuildHouse(state, seat, idx)) continue;
const sp = SPACES[idx]; const sp = SPACES[idx];
if (p.cash - sp.houseCost >= prof.reserve) { if (sp.type !== 'property' || p.cash - sp.houseCost < reserve) continue;
return { action: 'house', spaceIdx: idx }; const hotel = canBuildHotel(state, seat, idx);
} if (!hotel && !canBuildHouse(state, seat, idx)) continue;
const lvl = state.board[idx].houses;
const gain = (sp.rent[hotel ? 6 : lvl + 2] - sp.rent[lvl === 0 ? 1 : lvl + 1]) / sp.houseCost;
// the 3rd house is the big jump; low skill builds wherever it happens to look first
const score = skill <= 1 ? Math.random() : gain + (lvl === 2 ? 1 : 0);
if (!best || score > best.score) best = { action: hotel ? 'hotel' : 'house', spaceIdx: idx, score };
}
if (best) return { action: best.action, spaceIdx: best.spaceIdx };
// 3. Spare cash: lift other mortgages, set-members first.
for (const idx of PURCHASABLE) {
const own = state.board[idx];
if (own.owner !== seat || !own.mortgaged) continue;
if (p.cash - unmortgageCost(state, idx) >= reserve * 2 + 150) return { action: 'unmortgage', spaceIdx: idx };
} }
return null; return null;
} }
export const chooseBuild = chooseManage;
// ── Raising funds ────────────────────────────────────────────────────────────────
// One step at a time while in debt: settle if possible, otherwise the least
// damaging sale/mortgage; bankruptcy only when it is the only legal option.
// Returns { action:'settle'|'bankrupt'|'mortgage'|'sellHouse'|'sellHotel', spaceIdx? }.
export function chooseDebtAction(state, seat, skill) {
const d = currentDebt(state);
if (!d || d.debtor !== seat) return null;
if (canSettleDebt(state)) return { action: 'settle' };
if (mustGoBankrupt(state)) return { action: 'bankrupt' };
const jitter = skill <= 1 ? 4 : skill === 2 ? 1.5 : 0;
let best = null;
const consider = (action, spaceIdx, score) => {
score += Math.random() * jitter;
if (!best || score < best.score) best = { action, spaceIdx, score };
};
for (const idx of PURCHASABLE) {
const own = state.board[idx];
if (own.owner !== seat) continue;
const sp = SPACES[idx];
if (canMortgage(state, seat, idx)) {
if (sp.type === 'utility') consider('mortgage', idx, 2);
else if (sp.type === 'railroad') consider('mortgage', idx, 3 + railroadsOwned(state, seat) / 10);
else {
const { n, mine } = groupStats(state, seat, idx);
if (mine === n) consider('mortgage', idx, 6 + sp.price / 1000);
else if (mine / n > 0.5) consider('mortgage', idx, 4 + sp.price / 1000);
else consider('mortgage', idx, 1 + sp.price / 1000);
}
}
if (canSellHouse(state, seat, idx)) consider('sellHouse', idx, 5 + sp.houseCost / 1000);
if (canSellHotel(state, seat, idx)) consider('sellHotel', idx, 7 + sp.houseCost / 1000);
}
return best ? { action: best.action, spaceIdx: best.spaceIdx } : { action: 'bankrupt' };
}

View File

@ -0,0 +1,750 @@
// MonopolyArt.js — procedural canvas art for the Boardwalk Hotel parlour
// (a 1930s Art Deco card room). Everything is baked once into Phaser canvas
// textures; the user's pawn and card sheets are kept as they are.
//
// mono-room emerald baize card table, lamp pool, gilt deco border
// mono-board the printed board: linen-ivory stock, colour bands,
// names, prices, icons (locomotive, bulb, faucet, ring,
// pouch, ?, chest), four corners, deco sunburst centre,
// deck plates — the scene draws only dynamic things on top
// mono-bill-<d> paper bills ($1 … $500)
// mono-mini-<i> little title deed for the plaque rails; mono-mini-back (mortgaged)
// mono-house / mono-hotel building pieces; mono-shadow soft pawn shadow
// mono-back-chance / mono-back-cc deck card backs
// mono-tray / mono-bank / mono-plaque / mono-actions / mono-ledger / mono-header
// mono-glow / mono-puff FX sprites
import { canvas, rr, mix, noisePattern } from '../../ui/casino/CasinoArt.js';
import {
SPACES, GROUP_HEX, BILLS, BILL_TINT, BOARD_SIZE, CORNER_SIZE, SPACE_W, BAND_H, PURCHASABLE,
} from './MonopolyData.js';
import {
BOARD, TRAY, TRAY_FELT, BANK, ACTIONS, LEDGER, HEADER, PLAQUE_W, PLAQUE_H, BILL_W, BILL_H,
CHANCE_DECK, CC_DECK, DECK_W, DECK_H, HOUSE_RACK, billSlot, spaceRect, spaceRot,
} from './MonopolyLayout.js';
export const DECO = '"Julius Sans One", Georgia, serif';
export const DISPLAY = 'Righteous, Georgia, serif';
export const SERIF = 'Georgia, "Times New Roman", serif';
export const INK = '#241a10';
export const IVORY = '#f3ead2';
export const GOLD = '#c9a24a';
export const GOLD_LT = '#ecd690';
export const EMERALD = '#0f4a34';
export const CHANCE_ORANGE = '#d9622b';
export const CHEST_BLUE = '#2f6db0';
const hex = (n) => `#${n.toString(16).padStart(6, '0')}`;
function add(scene, key, c) { if (scene.textures.exists(key)) scene.textures.remove(key); scene.textures.addCanvas(key, c); }
function wrap(ctx, text, maxW) {
const words = text.split(/\s+/);
const lines = [];
let line = '';
for (const w of words) {
const t = line ? `${line} ${w}` : w;
if (ctx.measureText(t).width > maxW && line) { lines.push(line); line = w; } else line = t;
}
if (line) lines.push(line);
return lines;
}
// Deco fan (quarter sunburst) in a corner: cx,cy = apex, a0 = start angle.
function fan(ctx, cx, cy, r, a0, color, n = 7) {
ctx.save();
ctx.strokeStyle = color;
ctx.lineWidth = 1.4;
for (let k = 0; k <= n; k++) {
const a = a0 + (Math.PI / 2) * (k / n);
ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); ctx.stroke();
}
for (const rr2 of [r * 0.45, r * 0.75, r]) {
ctx.beginPath(); ctx.arc(cx, cy, rr2, a0, a0 + Math.PI / 2); ctx.stroke();
}
ctx.restore();
}
// Walnut panel with a gilt double rule and deco corner fans.
function decoPanel(ctx, x, y, w, h, { r = 14, wood = ['#4a2e1a', '#2a180c'], gilt = GOLD, fans = true } = {}) {
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 18; ctx.shadowOffsetY = 6;
const g = ctx.createLinearGradient(x, y, x, y + h);
g.addColorStop(0, wood[0]); g.addColorStop(1, wood[1]);
rr(ctx, x, y, w, h, r); ctx.fillStyle = g; ctx.fill();
ctx.restore();
// grain
ctx.save(); rr(ctx, x, y, w, h, r); ctx.clip();
ctx.globalAlpha = 0.08; ctx.strokeStyle = '#000';
for (let yy = y + 3; yy < y + h; yy += 5) {
ctx.beginPath(); ctx.moveTo(x, yy);
for (let xx = x; xx <= x + w; xx += 24) ctx.lineTo(xx, yy + Math.sin(xx * 0.03 + yy * 0.11) * 1.6);
ctx.stroke();
}
ctx.globalAlpha = 1;
ctx.fillStyle = noisePattern(ctx, 64, 22); ctx.fillRect(x, y, w, h);
ctx.restore();
ctx.strokeStyle = gilt; ctx.lineWidth = 2;
rr(ctx, x + 5, y + 5, w - 10, h - 10, Math.max(2, r - 4)); ctx.stroke();
ctx.globalAlpha = 0.55; ctx.lineWidth = 1;
rr(ctx, x + 10, y + 10, w - 20, h - 20, Math.max(2, r - 7)); ctx.stroke();
ctx.globalAlpha = 1;
if (fans) {
const fr = Math.min(26, h / 5);
fan(ctx, x + 10, y + 10, fr, 0, 'rgba(236,214,144,0.45)', 5);
fan(ctx, x + w - 10, y + 10, fr, Math.PI / 2, 'rgba(236,214,144,0.45)', 5);
fan(ctx, x + w - 10, y + h - 10, fr, Math.PI, 'rgba(236,214,144,0.45)', 5);
fan(ctx, x + 10, y + h - 10, fr, Math.PI * 1.5, 'rgba(236,214,144,0.45)', 5);
}
}
export { decoPanel };
// ── Room ─────────────────────────────────────────────────────────────────────
function bakeRoom(scene) {
const W = 1920, H = 1080;
const c = canvas(W, H), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(540, 560, 80, 760, 540, 1500);
g.addColorStop(0, '#1c6e4d'); g.addColorStop(0.45, '#11503a'); g.addColorStop(1, '#06231a');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
// felt nap
ctx.fillStyle = noisePattern(ctx, 128, 26); ctx.fillRect(0, 0, W, H);
// faint deco chevron weave in the baize
ctx.save(); ctx.globalAlpha = 0.035; ctx.strokeStyle = '#ecd690'; ctx.lineWidth = 1;
for (let x = -H; x < W; x += 36) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x + H, H); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x + H, 0); ctx.lineTo(x, H); ctx.stroke(); }
ctx.restore();
// lamp pool over the board + a second over the right-hand furniture
for (const [x, y, r, a] of [[540, 540, 640, 0.20], [1490, 560, 520, 0.10]]) {
const lg = ctx.createRadialGradient(x, y, 0, x, y, r);
lg.addColorStop(0, `rgba(255,226,160,${a})`); lg.addColorStop(1, 'rgba(255,226,160,0)');
ctx.fillStyle = lg; ctx.fillRect(0, 0, W, H);
}
// vignette
const v = ctx.createRadialGradient(W / 2, H / 2, H * 0.45, W / 2, H / 2, H * 1.1);
v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(0,0,0,0.55)');
ctx.fillStyle = v; ctx.fillRect(0, 0, W, H);
// gilt border + deco fans
ctx.strokeStyle = 'rgba(201,162,74,0.7)'; ctx.lineWidth = 2; ctx.strokeRect(6, 6, W - 12, H - 12);
ctx.strokeStyle = 'rgba(201,162,74,0.35)'; ctx.lineWidth = 1; ctx.strokeRect(12, 12, W - 24, H - 24);
fan(ctx, 12, 12, 30, 0, 'rgba(236,214,144,0.35)');
fan(ctx, W - 12, 12, 30, Math.PI / 2, 'rgba(236,214,144,0.35)');
fan(ctx, W - 12, H - 12, 30, Math.PI, 'rgba(236,214,144,0.35)');
fan(ctx, 12, H - 12, 30, Math.PI * 1.5, 'rgba(236,214,144,0.35)');
// the board's shadow on the felt
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.75)'; ctx.shadowBlur = 40; ctx.shadowOffsetX = 6; ctx.shadowOffsetY = 14;
ctx.fillStyle = '#0a1f16'; ctx.fillRect(BOARD.x + 4, BOARD.y + 4, BOARD.w - 8, BOARD.h - 8);
ctx.restore();
add(scene, 'mono-room', c);
}
// ── Icons (drawn centred on 0,0 in the current transform) ───────────────────
function iconLoco(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
ctx.fillStyle = INK;
// boiler
rr(ctx, -24, -6, 30, 14, 5); ctx.fill();
// smokestack + dome
ctx.fillRect(-20, -16, 6, 11); ctx.fillRect(-22, -18, 10, 3);
ctx.beginPath(); ctx.arc(-6, -6, 4, Math.PI, 0); ctx.fill();
// cab
ctx.fillRect(4, -16, 16, 24); ctx.fillRect(2, -18, 20, 3);
ctx.fillStyle = IVORY; ctx.fillRect(8, -12, 8, 7);
// cow-catcher
ctx.fillStyle = INK;
ctx.beginPath(); ctx.moveTo(-24, 4); ctx.lineTo(-30, 12); ctx.lineTo(-22, 12); ctx.closePath(); ctx.fill();
// wheels
for (const [x, r] of [[-16, 5], [-4, 5], [12, 6]]) {
ctx.beginPath(); ctx.arc(x, 13, r, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = IVORY; ctx.beginPath(); ctx.arc(x, 13, r * 0.35, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = INK;
}
ctx.fillRect(-22, 12, 38, 2);
// puff of smoke
ctx.globalAlpha = 0.25;
for (const [x, y, r] of [[-16, -24, 4], [-10, -29, 5], [-2, -32, 6]]) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); }
ctx.restore();
}
function iconBulb(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
// rays
ctx.strokeStyle = '#c99a1e'; ctx.lineWidth = 2;
for (let k = 0; k < 7; k++) {
const a = Math.PI + (Math.PI * k) / 6;
ctx.beginPath(); ctx.moveTo(Math.cos(a) * 17, -4 + Math.sin(a) * 17); ctx.lineTo(Math.cos(a) * 24, -4 + Math.sin(a) * 24); ctx.stroke();
}
const g = ctx.createRadialGradient(-3, -8, 2, 0, -4, 14);
g.addColorStop(0, '#fff7c8'); g.addColorStop(1, '#f2c53d');
ctx.fillStyle = g; ctx.strokeStyle = INK; ctx.lineWidth = 1.6;
ctx.beginPath(); ctx.arc(0, -4, 12, Math.PI * 0.8, Math.PI * 2.2); ctx.lineTo(5, 12); ctx.lineTo(-5, 12); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.fillStyle = '#8a8a8a'; ctx.fillRect(-6, 12, 12, 8);
ctx.strokeStyle = INK; ctx.lineWidth = 1; for (const y of [14, 17]) { ctx.beginPath(); ctx.moveTo(-6, y); ctx.lineTo(6, y); ctx.stroke(); }
ctx.strokeStyle = '#a56a10'; ctx.lineWidth = 1.2;
ctx.beginPath(); ctx.moveTo(-3, 10); ctx.lineTo(-3, -2); ctx.lineTo(0, -6); ctx.lineTo(3, -2); ctx.lineTo(3, 10); ctx.stroke();
ctx.restore();
}
function iconFaucet(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
ctx.fillStyle = '#7d8a93'; ctx.strokeStyle = INK; ctx.lineWidth = 1.5;
// pipe from the wall
rr(ctx, -26, -10, 16, 10, 2); ctx.fill(); ctx.stroke();
// body + spout
ctx.beginPath(); ctx.moveTo(-12, -14); ctx.lineTo(8, -14); ctx.quadraticCurveTo(18, -14, 18, -2); ctx.lineTo(18, 4); ctx.lineTo(10, 4); ctx.lineTo(10, -2); ctx.quadraticCurveTo(10, -6, 6, -6); ctx.lineTo(-12, -6); ctx.closePath(); ctx.fill(); ctx.stroke();
// handle
ctx.fillRect(-4, -22, 4, 8); ctx.strokeRect(-4, -22, 4, 8);
rr(ctx, -12, -26, 20, 5, 2); ctx.fill(); ctx.stroke();
// drops
ctx.fillStyle = '#3d86c6';
for (const [y, r] of [[12, 3.4], [22, 2.6]]) {
ctx.beginPath(); ctx.moveTo(14, y - r * 2); ctx.quadraticCurveTo(14 + r * 1.2, y, 14, y + r); ctx.quadraticCurveTo(14 - r * 1.2, y, 14, y - r * 2); ctx.fill();
}
ctx.restore();
}
function iconRing(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
ctx.strokeStyle = '#b8902c'; ctx.lineWidth = 4;
ctx.beginPath(); ctx.ellipse(0, 8, 13, 11, 0, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = '#ecd690'; ctx.lineWidth = 1.2;
ctx.beginPath(); ctx.ellipse(0, 8, 13, 11, 0, Math.PI * 1.1, Math.PI * 1.6); ctx.stroke();
// diamond
ctx.fillStyle = '#d9eef7'; ctx.strokeStyle = INK; ctx.lineWidth = 1.2;
ctx.beginPath(); ctx.moveTo(-9, -8); ctx.lineTo(-5, -14); ctx.lineTo(5, -14); ctx.lineTo(9, -8); ctx.lineTo(0, 2); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-9, -8); ctx.lineTo(9, -8); ctx.moveTo(-3, -14); ctx.lineTo(-4, -8); ctx.lineTo(0, 2); ctx.lineTo(4, -8); ctx.lineTo(3, -14); ctx.stroke();
ctx.fillStyle = '#fff'; ctx.globalAlpha = 0.9; ctx.beginPath(); ctx.arc(-4, -11, 1.2, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
function iconPouch(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
ctx.fillStyle = '#8a6a3c'; ctx.strokeStyle = INK; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(-6, -12); ctx.quadraticCurveTo(-20, 0, -14, 12); ctx.quadraticCurveTo(0, 20, 14, 12); ctx.quadraticCurveTo(20, 0, 6, -12); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.fillStyle = '#6b5030'; ctx.beginPath(); ctx.ellipse(0, -14, 9, 4, 0, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
ctx.strokeStyle = '#c9a24a'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(-7, -10); ctx.lineTo(7, -10); ctx.stroke();
ctx.fillStyle = '#ecd690'; ctx.font = `bold 16px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('$', 0, 3);
ctx.restore();
}
function iconChest(ctx, s = 1, color = CHEST_BLUE) {
ctx.save(); ctx.scale(s, s);
ctx.strokeStyle = INK; ctx.lineWidth = 1.6;
ctx.fillStyle = '#9a6233';
rr(ctx, -20, -2, 40, 20, 2); ctx.fill(); ctx.stroke();
ctx.fillStyle = '#b5773e';
ctx.beginPath(); ctx.moveTo(-20, -2); ctx.quadraticCurveTo(-20, -18, 0, -18); ctx.quadraticCurveTo(20, -18, 20, -2); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.fillStyle = color;
for (const x of [-14, 10]) { ctx.fillRect(x, -16, 4, 34); ctx.strokeRect(x, -16, 4, 34); }
ctx.fillStyle = '#e3c35a'; rr(ctx, -4, -4, 8, 9, 2); ctx.fill(); ctx.stroke();
ctx.restore();
}
function iconQuestion(ctx, size, color = CHANCE_ORANGE) {
ctx.save();
ctx.font = `${size}px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(0,0,0,0.25)'; ctx.fillText('?', 2, 3);
ctx.fillStyle = color; ctx.fillText('?', 0, 0);
ctx.lineWidth = 1.2; ctx.strokeStyle = INK; ctx.strokeText('?', 0, 0);
ctx.restore();
}
function iconCar(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
ctx.fillStyle = '#b8322a'; ctx.strokeStyle = INK; ctx.lineWidth = 1.6;
ctx.beginPath();
ctx.moveTo(-30, 6); ctx.lineTo(-28, -2); ctx.quadraticCurveTo(-20, -6, -12, -6); ctx.lineTo(-6, -16); ctx.lineTo(12, -16);
ctx.lineTo(20, -6); ctx.quadraticCurveTo(30, -5, 31, 2); ctx.lineTo(31, 6); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.fillStyle = '#d6ecf2'; ctx.beginPath(); ctx.moveTo(-4, -13); ctx.lineTo(3, -13); ctx.lineTo(3, -7); ctx.lineTo(-8, -7); ctx.closePath(); ctx.fill();
ctx.beginPath(); ctx.moveTo(6, -13); ctx.lineTo(11, -13); ctx.lineTo(16, -7); ctx.lineTo(6, -7); ctx.closePath(); ctx.fill();
ctx.fillStyle = INK;
for (const x of [-18, 18]) { ctx.beginPath(); ctx.arc(x, 7, 6, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = '#c9c9c9'; ctx.beginPath(); ctx.arc(x, 7, 2.5, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = INK; }
ctx.fillStyle = '#ecd690'; ctx.fillRect(28, -1, 4, 3);
ctx.restore();
}
function iconBadge(ctx, s = 1) {
ctx.save(); ctx.scale(s, s);
ctx.fillStyle = '#d9b24a'; ctx.strokeStyle = INK; ctx.lineWidth = 1.6;
ctx.beginPath();
for (let k = 0; k < 14; k++) {
const a = -Math.PI / 2 + (k * Math.PI) / 7;
const r = k % 2 ? 11 : 22;
ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r);
}
ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.fillStyle = '#20324f'; ctx.beginPath(); ctx.arc(0, 0, 9, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#ecd690'; ctx.font = `bold 9px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('P.D.', 0, 1);
ctx.restore();
}
// ── Board ────────────────────────────────────────────────────────────────────
const RES = 2;
function spaceText(ctx, text, y, { size = 11, font = DECO, color = INK, maxW = 70, lh = 13 } = {}) {
ctx.font = `${size}px ${font}`;
ctx.fillStyle = color; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
const lines = wrap(ctx, text.toUpperCase(), maxW);
lines.forEach((l, k) => ctx.fillText(l, 0, y + k * lh));
return lines.length;
}
function drawSpace(ctx, i) {
const sp = SPACES[i];
const hw = SPACE_W / 2, hh = CORNER_SIZE / 2; // local: 80 wide, 136 tall, band on top
const bandTop = -hh;
if (sp.type === 'property') {
const col = GROUP_HEX[sp.group];
const bg = ctx.createLinearGradient(0, bandTop, 0, bandTop + BAND_H);
bg.addColorStop(0, mix(col, '#ffffff', 0.12)); bg.addColorStop(1, mix(col, '#000000', 0.12));
ctx.fillStyle = bg; ctx.fillRect(-hw, bandTop, SPACE_W, BAND_H);
ctx.fillStyle = 'rgba(255,255,255,0.22)'; ctx.fillRect(-hw, bandTop, SPACE_W, 3);
ctx.strokeStyle = INK; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(-hw, bandTop + BAND_H); ctx.lineTo(hw, bandTop + BAND_H); ctx.stroke();
spaceText(ctx, sp.name, bandTop + BAND_H + 16, { size: 11.5, maxW: 70, lh: 14 });
// deco hairline above the price
ctx.strokeStyle = 'rgba(36,26,16,0.35)'; ctx.lineWidth = 0.8;
ctx.beginPath(); ctx.moveTo(-22, hh - 30); ctx.lineTo(22, hh - 30); ctx.stroke();
spaceText(ctx, `$${sp.price}`, hh - 17, { size: 14, font: DISPLAY });
return;
}
if (sp.type === 'railroad') {
const n = spaceText(ctx, sp.name.replace(' Railroad', ''), bandTop + 14, { size: 11, maxW: 72 });
spaceText(ctx, 'RAILROAD', bandTop + 14 + n * 13, { size: 9, color: '#5a4a38' });
ctx.save(); ctx.translate(0, 10); iconLoco(ctx, 1.05); ctx.restore();
spaceText(ctx, `$${sp.price}`, hh - 17, { size: 14, font: DISPLAY });
return;
}
if (sp.type === 'utility') {
spaceText(ctx, sp.name, bandTop + 16, { size: 11, maxW: 70, lh: 14 });
ctx.save(); ctx.translate(0, 6);
if (i === 12) iconBulb(ctx, 1.25); else iconFaucet(ctx, 1.2);
ctx.restore();
spaceText(ctx, `$${sp.price}`, hh - 17, { size: 14, font: DISPLAY });
return;
}
if (sp.type === 'chance') {
spaceText(ctx, 'CHANCE', bandTop + 18, { size: 13, font: DISPLAY, color: CHANCE_ORANGE });
ctx.save(); ctx.translate(0, 14); iconQuestion(ctx, 70); ctx.restore();
return;
}
if (sp.type === 'community_chest') {
spaceText(ctx, 'COMMUNITY CHEST', bandTop + 16, { size: 11, maxW: 70, lh: 14, color: CHEST_BLUE });
ctx.save(); ctx.translate(0, 18); iconChest(ctx, 1.2); ctx.restore();
spaceText(ctx, 'FOLLOW THE CARD', hh - 22, { size: 8, maxW: 70, lh: 10, color: '#5a4a38' });
return;
}
if (sp.type === 'tax') {
spaceText(ctx, sp.name, bandTop + 16, { size: 12, maxW: 70, lh: 14 });
ctx.save(); ctx.translate(0, 8);
if (i === 4) iconPouch(ctx, 1.25); else iconRing(ctx, 1.25);
ctx.restore();
spaceText(ctx, `PAY $${sp.amount}`, hh - 18, { size: 12, font: DISPLAY });
}
}
function drawCorner(ctx, i) {
const C = CORNER_SIZE, h = C / 2;
ctx.save();
if (i === 0) {
// GO — bottom-right; travel heads left along the bottom row.
ctx.save(); ctx.rotate(-Math.PI / 4);
spaceText(ctx, 'COLLECT $200 SALARY', -40, { size: 10, maxW: 120 });
spaceText(ctx, 'AS YOU PASS', -27, { size: 10, maxW: 120 });
ctx.font = `64px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(0,0,0,0.18)'; ctx.fillText('GO', 2, 14);
ctx.fillStyle = '#b3261e'; ctx.fillText('GO', 0, 12);
ctx.restore();
// arrow along the bottom edge pointing left
ctx.fillStyle = '#b3261e';
ctx.beginPath(); ctx.moveTo(-h + 10, h - 20); ctx.lineTo(-h + 34, h - 34); ctx.lineTo(-h + 34, h - 26); ctx.lineTo(h - 12, h - 26);
ctx.lineTo(h - 12, h - 14); ctx.lineTo(-h + 34, h - 14); ctx.lineTo(-h + 34, h - 6); ctx.closePath(); ctx.fill();
} else if (i === 10) {
// Jail — bottom-left. The cell sits in the inner (top-right) square.
const cx = h - 46, cy = -h + 46, cs = 92;
ctx.fillStyle = '#e48a3a'; ctx.fillRect(cx - cs / 2, cy - cs / 2, cs, cs);
ctx.strokeStyle = INK; ctx.lineWidth = 1.2; ctx.strokeRect(cx - cs / 2, cy - cs / 2, cs, cs);
ctx.save(); ctx.translate(cx, cy); ctx.rotate(Math.PI / 4);
spaceText(ctx, 'IN', -30, { size: 12, font: DISPLAY });
ctx.fillStyle = '#f6e9cf'; ctx.fillRect(-22, -18, 44, 38);
ctx.strokeStyle = INK; ctx.lineWidth = 2;
for (let k = -2; k <= 2; k++) { ctx.beginPath(); ctx.moveTo(k * 8.5, -18); ctx.lineTo(k * 8.5, 20); ctx.stroke(); }
ctx.strokeRect(-22, -18, 44, 38);
spaceText(ctx, 'JAIL', 32, { size: 12, font: DISPLAY });
ctx.restore();
// Just Visiting along the outer L
ctx.save(); ctx.translate(-h + 14, -12); ctx.rotate(Math.PI / 2);
spaceText(ctx, 'JUST', 0, { size: 13, font: DISPLAY, maxW: 200 });
ctx.restore();
spaceText(ctx, 'VISITING', h - 14, { size: 13, font: DISPLAY, maxW: 200 });
} else if (i === 20) {
ctx.rotate(Math.PI * 3 / 4);
spaceText(ctx, 'FREE', -36, { size: 18, font: DISPLAY, color: '#b3261e' });
ctx.save(); ctx.translate(0, 2); iconCar(ctx, 1.25); ctx.restore();
spaceText(ctx, 'PARKING', 38, { size: 18, font: DISPLAY, color: '#b3261e' });
} else if (i === 30) {
ctx.rotate(-Math.PI * 3 / 4);
spaceText(ctx, 'GO TO', -38, { size: 18, font: DISPLAY, color: '#20324f' });
ctx.save(); ctx.translate(0, 0); iconBadge(ctx, 1.2); ctx.restore();
spaceText(ctx, 'JAIL', 38, { size: 18, font: DISPLAY, color: '#20324f' });
}
ctx.restore();
}
function drawCentre(ctx) {
const C = CORNER_SIZE, S = BOARD_SIZE, M = S / 2;
const inner = S - 2 * C;
// centre panel: pale celadon with a gilt frame
const g = ctx.createRadialGradient(M, M, 40, M, M, inner * 0.72);
g.addColorStop(0, '#eef1e2'); g.addColorStop(1, '#dfe6d2');
ctx.fillStyle = g; ctx.fillRect(C, C, inner, inner);
ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(C, C, inner, inner);
// sunburst rays
ctx.save(); ctx.translate(M, M);
for (let k = 0; k < 48; k++) {
const a0 = (k / 48) * Math.PI * 2, a1 = ((k + 0.5) / 48) * Math.PI * 2;
ctx.fillStyle = k % 2 ? 'rgba(201,162,74,0.10)' : 'rgba(15,74,52,0.06)';
ctx.beginPath(); ctx.moveTo(0, 0); ctx.arc(0, 0, inner * 0.7, a0, a1); ctx.closePath(); ctx.fill();
}
// stepped deco rings
for (const [r, w, a] of [[250, 2, 0.6], [242, 1, 0.4], [180, 1.5, 0.5]]) {
ctx.strokeStyle = `rgba(201,162,74,${a})`; ctx.lineWidth = w; ctx.beginPath(); ctx.arc(0, 0, r, 0, Math.PI * 2); ctx.stroke();
}
// medallion
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.35)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 4;
const mg = ctx.createRadialGradient(-30, -40, 10, 0, 0, 150);
mg.addColorStop(0, '#1d7352'); mg.addColorStop(1, '#0b3a28');
ctx.fillStyle = mg; ctx.beginPath(); ctx.arc(0, 0, 150, 0, Math.PI * 2); ctx.fill();
ctx.restore();
ctx.strokeStyle = GOLD; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(0, 0, 150, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = GOLD_LT; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(0, 0, 140, 0, Math.PI * 2); ctx.stroke();
// little rays inside the medallion top
ctx.save(); ctx.strokeStyle = 'rgba(236,214,144,0.5)'; ctx.lineWidth = 1.2;
for (let k = 0; k <= 12; k++) { const a = Math.PI + (k / 12) * Math.PI; ctx.beginPath(); ctx.moveTo(Math.cos(a) * 60, -20 + Math.sin(a) * 60); ctx.lineTo(Math.cos(a) * 128, -20 + Math.sin(a) * 128); ctx.stroke(); }
ctx.restore();
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = `15px ${DECO}`; ctx.fillStyle = GOLD_LT;
ctx.fillText('THE', 0, -42);
ctx.font = `44px ${DISPLAY}`; ctx.fillStyle = '#000'; ctx.globalAlpha = 0.3; ctx.fillText('BOARDWALK', 2, 6); ctx.globalAlpha = 1;
const tg = ctx.createLinearGradient(0, -20, 0, 26);
tg.addColorStop(0, '#fff3c4'); tg.addColorStop(0.5, '#e6c565'); tg.addColorStop(1, '#a87d2a');
ctx.fillStyle = tg; ctx.fillText('BOARDWALK', 0, 4);
ctx.font = `13px ${DECO}`; ctx.fillStyle = GOLD_LT;
ctx.fillText('HOTEL · PARLOUR EDITION', 0, 44);
ctx.strokeStyle = 'rgba(236,214,144,0.6)'; ctx.lineWidth = 1;
for (const y of [32, 58]) { ctx.beginPath(); ctx.moveTo(-90, y); ctx.lineTo(90, y); ctx.stroke(); }
ctx.font = `11px ${DECO}`; ctx.fillText('A PROPERTY TRADING GAME', 0, 76);
ctx.restore();
// deck plates
for (const [deck, label, color] of [[CHANCE_DECK, 'CHANCE', CHANCE_ORANGE], [CC_DECK, 'COMMUNITY CHEST', CHEST_BLUE]]) {
ctx.save();
ctx.translate(deck.x - BOARD.x, deck.y - BOARD.y); ctx.rotate(deck.rot);
ctx.setLineDash([6, 4]); ctx.strokeStyle = color; ctx.lineWidth = 2;
rr(ctx, -DECK_W / 2 - 8, -DECK_H / 2 - 8, DECK_W + 16, DECK_H + 16, 10); ctx.stroke();
ctx.setLineDash([]);
ctx.globalAlpha = 0.08; ctx.fillStyle = color; rr(ctx, -DECK_W / 2 - 8, -DECK_H / 2 - 8, DECK_W + 16, DECK_H + 16, 10); ctx.fill(); ctx.globalAlpha = 1;
ctx.font = `13px ${DISPLAY}`; ctx.fillStyle = color; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(label, 0, DECK_H / 2 + 22);
ctx.restore();
}
}
function bakeBoard(scene) {
const S = BOARD_SIZE;
const c = canvas(S * RES, S * RES), ctx = c.getContext('2d');
ctx.scale(RES, RES);
// stock: warm ivory linen
const g = ctx.createLinearGradient(0, 0, S, S);
g.addColorStop(0, '#f6eed8'); g.addColorStop(1, '#ece0c2');
ctx.fillStyle = g; ctx.fillRect(0, 0, S, S);
ctx.save(); ctx.globalAlpha = 0.05; ctx.strokeStyle = '#7a6040'; ctx.lineWidth = 0.5;
for (let k = 0; k < S; k += 3) { ctx.beginPath(); ctx.moveTo(k, 0); ctx.lineTo(k, S); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, k); ctx.lineTo(S, k); ctx.stroke(); }
ctx.restore();
ctx.fillStyle = noisePattern(ctx, 128, 16); ctx.fillRect(0, 0, S, S);
drawCentre(ctx);
// spaces
for (let i = 0; i < 40; i++) {
const r = spaceRect(i);
const x = r.x - BOARD.x, y = r.y - BOARD.y;
ctx.save();
ctx.translate(x + r.w / 2, y + r.h / 2);
if (r.corner) drawCorner(ctx, i);
else { ctx.rotate(spaceRot(i)); drawSpace(ctx, i); }
ctx.restore();
ctx.strokeStyle = INK; ctx.lineWidth = 1.2; ctx.strokeRect(x, y, r.w, r.h);
}
// frames: outer ink + gilt, inner gilt rule round the centre
ctx.strokeStyle = INK; ctx.lineWidth = 4; ctx.strokeRect(2, 2, S - 4, S - 4);
ctx.strokeStyle = GOLD; ctx.lineWidth = 2; ctx.strokeRect(6, 6, S - 12, S - 12);
ctx.strokeStyle = INK; ctx.lineWidth = 2.5; ctx.strokeRect(CORNER_SIZE, CORNER_SIZE, S - 2 * CORNER_SIZE, S - 2 * CORNER_SIZE);
ctx.strokeStyle = GOLD; ctx.lineWidth = 1.5; ctx.strokeRect(CORNER_SIZE + 5, CORNER_SIZE + 5, S - 2 * CORNER_SIZE - 10, S - 2 * CORNER_SIZE - 10);
add(scene, 'mono-board', c);
}
// ── Money ────────────────────────────────────────────────────────────────────
function bakeBills(scene) {
const R = 2, w = BILL_W * R, h = BILL_H * R;
for (const d of BILLS) {
const c = canvas(w, h), ctx = c.getContext('2d');
ctx.scale(R, R);
const tint = hex(BILL_TINT[d]);
const g = ctx.createLinearGradient(0, 0, BILL_W, BILL_H);
g.addColorStop(0, mix(tint, '#ffffff', 0.35)); g.addColorStop(1, tint);
rr(ctx, 0.5, 0.5, BILL_W - 1, BILL_H - 1, 2); ctx.fillStyle = g; ctx.fill();
ctx.strokeStyle = mix(tint, '#000000', 0.45); ctx.lineWidth = 1; ctx.stroke();
ctx.strokeStyle = mix(tint, '#000000', 0.3); ctx.lineWidth = 0.6; ctx.strokeRect(3, 3, BILL_W - 6, BILL_H - 6);
// guilloche
ctx.globalAlpha = 0.25;
for (let k = 0; k < 9; k++) { ctx.beginPath(); for (let x = 4; x <= BILL_W - 4; x += 2) ctx.lineTo(x, BILL_H / 2 + Math.sin(x * 0.35 + k) * (BILL_H / 2 - 6) * ((k + 1) / 9)); ctx.stroke(); }
ctx.globalAlpha = 1;
// centre oval
ctx.fillStyle = mix(tint, '#ffffff', 0.6); ctx.beginPath(); ctx.ellipse(BILL_W / 2, BILL_H / 2, 12, 10, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = mix(tint, '#000000', 0.4); ctx.stroke();
ctx.fillStyle = mix(tint, '#000000', 0.62); ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = `${d >= 100 ? 9 : 11}px ${DISPLAY}`; ctx.fillText(String(d), BILL_W / 2, BILL_H / 2 + 0.5);
ctx.font = `7px ${DISPLAY}`;
ctx.fillText(String(d), 9, 8); ctx.fillText(String(d), BILL_W - 9, BILL_H - 8);
add(scene, `mono-bill-${d}`, c);
}
}
// ── Deeds ────────────────────────────────────────────────────────────────────
function miniBandColor(i) {
const sp = SPACES[i];
if (sp.group) return GROUP_HEX[sp.group];
if (sp.type === 'railroad') return '#2b2b2b';
return i === 12 ? '#e0b52c' : '#3d86c6';
}
function bakeMiniDeeds(scene) {
const R = 3, w = 30, h = 42;
for (const i of PURCHASABLE) {
const c = canvas(w * R, h * R), ctx = c.getContext('2d');
ctx.scale(R, R);
rr(ctx, 0.5, 0.5, w - 1, h - 1, 3); ctx.fillStyle = '#fbf6e8'; ctx.fill();
ctx.strokeStyle = 'rgba(36,26,16,0.7)'; ctx.lineWidth = 0.8; ctx.stroke();
const sp = SPACES[i];
ctx.fillStyle = miniBandColor(i);
ctx.fillRect(2.5, 2.5, w - 5, 11);
ctx.save(); ctx.translate(w / 2, 26);
if (sp.type === 'railroad') iconLoco(ctx, 0.36);
else if (sp.type === 'utility') (i === 12 ? iconBulb : iconFaucet)(ctx, 0.42);
else {
ctx.strokeStyle = 'rgba(36,26,16,0.45)'; ctx.lineWidth = 0.8;
for (let k = 0; k < 4; k++) { ctx.beginPath(); ctx.moveTo(-9, -6 + k * 4.5); ctx.lineTo(9, -6 + k * 4.5); ctx.stroke(); }
}
ctx.restore();
add(scene, `mono-mini-${i}`, c);
}
const c = canvas(w * R, h * R), ctx = c.getContext('2d');
ctx.scale(R, R);
rr(ctx, 0.5, 0.5, w - 1, h - 1, 3); ctx.fillStyle = '#7d1f24'; ctx.fill();
ctx.strokeStyle = '#ecd690'; ctx.lineWidth = 0.8; rr(ctx, 2.5, 2.5, w - 5, h - 5, 2); ctx.stroke();
ctx.fillStyle = '#ecd690'; ctx.font = `13px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('M', w / 2, h / 2 + 1);
add(scene, 'mono-mini-back', c);
}
// ── Buildings & sprites ──────────────────────────────────────────────────────
function bakeBuildings(scene) {
const R = 3;
// house: 18×18 — front face, gabled roof, right side wall (3/4 view)
{
const w = 18, h = 18, c = canvas(w * R, h * R), ctx = c.getContext('2d');
ctx.scale(R, R);
ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.beginPath(); ctx.ellipse(9, 16, 8, 2.2, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#1e6a2e'; ctx.beginPath(); ctx.moveTo(12, 8); ctx.lineTo(16, 6); ctx.lineTo(16, 13); ctx.lineTo(12, 15); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#34a048'; ctx.fillRect(2, 8, 10, 7);
ctx.fillStyle = '#2a8a3c'; ctx.beginPath(); ctx.moveTo(1, 8.5); ctx.lineTo(7, 2); ctx.lineTo(13, 8.5); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#226f31'; ctx.beginPath(); ctx.moveTo(7, 2); ctx.lineTo(11, 0.5); ctx.lineTo(17, 6.5); ctx.lineTo(13, 8.5); ctx.closePath(); ctx.fill();
ctx.strokeStyle = '#0e3a17'; ctx.lineWidth = 0.6;
ctx.beginPath(); ctx.moveTo(1, 8.5); ctx.lineTo(7, 2); ctx.lineTo(11, 0.5); ctx.lineTo(17, 6.5); ctx.lineTo(16, 13); ctx.lineTo(12, 15); ctx.lineTo(2, 15); ctx.lineTo(2, 8.5); ctx.stroke();
ctx.fillStyle = 'rgba(255,255,255,0.35)'; ctx.fillRect(2.5, 8.5, 9, 1);
add(scene, 'mono-house', c);
}
// hotel: 30×20
{
const w = 30, h = 20, c = canvas(w * R, h * R), ctx = c.getContext('2d');
ctx.scale(R, R);
ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.beginPath(); ctx.ellipse(15, 18, 14, 2.4, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#7d1414'; ctx.beginPath(); ctx.moveTo(24, 8); ctx.lineTo(28, 6); ctx.lineTo(28, 15); ctx.lineTo(24, 17); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#c62828'; ctx.fillRect(2, 8, 22, 9);
ctx.fillStyle = '#a82020'; ctx.beginPath(); ctx.moveTo(1, 8.5); ctx.lineTo(7, 2); ctx.lineTo(19, 2); ctx.lineTo(25, 8.5); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#8f1b1b'; ctx.beginPath(); ctx.moveTo(19, 2); ctx.lineTo(23, 0.5); ctx.lineTo(29, 6.5); ctx.lineTo(25, 8.5); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#ffe9a8'; for (let k = 0; k < 4; k++) ctx.fillRect(4 + k * 5, 10.5, 2.4, 2.4);
ctx.strokeStyle = '#3d0707'; ctx.lineWidth = 0.6; ctx.strokeRect(2, 8, 22, 9);
add(scene, 'mono-hotel', c);
}
// soft shadow
{
const c = canvas(64, 32), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(32, 16, 2, 32, 16, 30);
g.addColorStop(0, 'rgba(0,0,0,0.55)'); g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = g; ctx.save(); ctx.scale(1, 0.5); ctx.beginPath(); ctx.arc(32, 32, 30, 0, Math.PI * 2); ctx.fill(); ctx.restore();
add(scene, 'mono-shadow', c);
}
// glow + puff
{
const c = canvas(128, 128), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(64, 64, 4, 64, 64, 62);
g.addColorStop(0, 'rgba(255,240,200,0.9)'); g.addColorStop(0.4, 'rgba(255,220,150,0.35)'); g.addColorStop(1, 'rgba(255,220,150,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, 128, 128);
add(scene, 'mono-glow', c);
}
{
const c = canvas(32, 32), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(16, 16, 1, 16, 16, 15);
g.addColorStop(0, 'rgba(240,230,210,0.8)'); g.addColorStop(1, 'rgba(240,230,210,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, 32, 32);
add(scene, 'mono-puff', c);
}
}
// ── Deck backs ───────────────────────────────────────────────────────────────
function bakeDeckBacks(scene) {
const R = 2;
for (const [key, base, label, icon] of [['mono-back-chance', CHANCE_ORANGE, 'CHANCE', 'q'], ['mono-back-cc', CHEST_BLUE, 'COMMUNITY CHEST', 'c']]) {
const c = canvas(DECK_W * R, DECK_H * R), ctx = c.getContext('2d');
ctx.scale(R, R);
const g = ctx.createLinearGradient(0, 0, 0, DECK_H);
g.addColorStop(0, mix(base, '#ffffff', 0.15)); g.addColorStop(1, mix(base, '#000000', 0.25));
rr(ctx, 0.5, 0.5, DECK_W - 1, DECK_H - 1, 8); ctx.fillStyle = g; ctx.fill();
ctx.strokeStyle = '#fbf1dc'; ctx.lineWidth = 2; rr(ctx, 5, 5, DECK_W - 10, DECK_H - 10, 6); ctx.stroke();
ctx.lineWidth = 0.8; rr(ctx, 9, 9, DECK_W - 18, DECK_H - 18, 4); ctx.stroke();
fan(ctx, 9, 9, 16, 0, 'rgba(251,241,220,0.6)', 4);
fan(ctx, DECK_W - 9, DECK_H - 9, 16, Math.PI, 'rgba(251,241,220,0.6)', 4);
ctx.save(); ctx.translate(DECK_W / 2, DECK_H / 2 - 6);
if (icon === 'q') iconQuestion(ctx, 64, '#fbf1dc'); else { iconChest(ctx, 1.4, mix(base, '#000000', 0.3)); }
ctx.restore();
ctx.fillStyle = '#fbf1dc'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = `${label.length > 8 ? 9 : 12}px ${DISPLAY}`;
ctx.fillText(label, DECK_W / 2, DECK_H - 20);
add(scene, key, c);
}
}
// ── Furniture ────────────────────────────────────────────────────────────────
function bakeTray(scene) {
const { w, h } = TRAY;
const c = canvas(w + 40, h + 40), ctx = c.getContext('2d');
ctx.translate(20, 20);
decoPanel(ctx, 0, 0, w, h, { r: 16, fans: false });
const fx = TRAY_FELT.x - TRAY.x, fy = TRAY_FELT.y - TRAY.y;
const fg = ctx.createRadialGradient(w / 2, fy + TRAY_FELT.h / 2, 10, w / 2, fy + TRAY_FELT.h / 2, w * 0.7);
fg.addColorStop(0, '#1b7a55'); fg.addColorStop(1, '#0c3d2a');
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.8)'; ctx.shadowBlur = 10; ctx.shadowOffsetY = 3;
rr(ctx, fx, fy, TRAY_FELT.w, TRAY_FELT.h, 8); ctx.fillStyle = fg; ctx.fill(); ctx.restore();
ctx.fillStyle = noisePattern(ctx, 64, 30); rr(ctx, fx, fy, TRAY_FELT.w, TRAY_FELT.h, 8); ctx.fill();
ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.lineWidth = 2; rr(ctx, fx, fy, TRAY_FELT.w, TRAY_FELT.h, 8); ctx.stroke();
// label
ctx.fillStyle = GOLD_LT; ctx.font = `13px ${DECO}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('— DICE TRAY —', w / 2, 24);
add(scene, 'mono-tray', c);
}
function bakeBank(scene) {
const { w, h } = BANK;
const c = canvas(w + 40, h + 40), ctx = c.getContext('2d');
ctx.translate(20, 20);
decoPanel(ctx, 0, 0, w, h, { r: 16, wood: ['#5a2a1a', '#2c120a'], fans: false });
ctx.fillStyle = GOLD_LT; ctx.font = `13px ${DECO}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('— THE BANK —', w / 2, 24);
// bill compartments
for (let i = 0; i < 7; i++) {
const s = billSlot(i);
const x = s.x - BANK.x + 2, y = s.y - BANK.y, cw = s.w - 4;
const g = ctx.createLinearGradient(0, y, 0, y + s.h);
g.addColorStop(0, '#1a0c06'); g.addColorStop(1, '#3a1d10');
rr(ctx, x, y, cw, s.h, 4); ctx.fillStyle = g; ctx.fill();
ctx.strokeStyle = 'rgba(201,162,74,0.65)'; ctx.lineWidth = 1; ctx.stroke();
ctx.fillStyle = GOLD_LT; ctx.font = `10px ${DISPLAY}`;
ctx.fillText(`$${BILLS[i]}`, x + cw / 2, y + s.h - 9);
}
// building rack
const R2 = { x: HOUSE_RACK.x - BANK.x, y: HOUSE_RACK.y - BANK.y, w: HOUSE_RACK.w, h: HOUSE_RACK.h };
const fg = ctx.createLinearGradient(0, R2.y, 0, R2.y + R2.h);
fg.addColorStop(0, '#0d3a29'); fg.addColorStop(1, '#155c41');
rr(ctx, R2.x, R2.y, R2.w, R2.h, 6); ctx.fillStyle = fg; ctx.fill();
ctx.strokeStyle = 'rgba(201,162,74,0.65)'; ctx.stroke();
add(scene, 'mono-bank', c);
}
function bakePlaque(scene) {
const w = PLAQUE_W, h = PLAQUE_H;
const c = canvas(w + 40, h + 40), ctx = c.getContext('2d');
ctx.translate(20, 20);
decoPanel(ctx, 0, 0, w, h, { r: 14 });
// deed rail: a felt strip with a brass lip
const ry = 110, rh = 80;
const g = ctx.createLinearGradient(0, ry, 0, ry + rh);
g.addColorStop(0, '#0c3a28'); g.addColorStop(1, '#13573d');
rr(ctx, 12, ry, w - 24, rh, 6); ctx.fillStyle = g; ctx.fill();
ctx.strokeStyle = 'rgba(201,162,74,0.6)'; ctx.lineWidth = 1; ctx.stroke();
ctx.fillStyle = 'rgba(201,162,74,0.85)'; ctx.fillRect(14, ry + rh - 5, w - 28, 3);
// portrait ring
ctx.strokeStyle = GOLD; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(52, 56, 42, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(236,214,144,0.5)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(52, 56, 46, 0, Math.PI * 2); ctx.stroke();
add(scene, 'mono-plaque', c);
}
function bakeActions(scene) {
const { w, h } = ACTIONS;
const c = canvas(w + 40, h + 40), ctx = c.getContext('2d');
ctx.translate(20, 20);
decoPanel(ctx, 0, 0, w, h, { r: 16 });
add(scene, 'mono-actions', c);
}
function bakeLedger(scene) {
const { w, h } = LEDGER;
const c = canvas(w + 40, h + 40), ctx = c.getContext('2d');
ctx.translate(20, 20);
decoPanel(ctx, 0, 0, w, h, { r: 16, fans: false });
// paper page
const px = 14, py = 14, pw = w - 28, ph = h - 28;
ctx.save(); ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 6; ctx.shadowOffsetY = 2;
ctx.fillStyle = '#f3ead2'; ctx.fillRect(px, py, pw, ph); ctx.restore();
ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(px, py, pw, ph);
ctx.strokeStyle = 'rgba(70,110,160,0.35)'; ctx.lineWidth = 1;
for (let y = py + 40; y < py + ph - 4; y += 21) { ctx.beginPath(); ctx.moveTo(px + 4, y); ctx.lineTo(px + pw - 4, y); ctx.stroke(); }
ctx.strokeStyle = 'rgba(190,50,50,0.5)'; ctx.beginPath(); ctx.moveTo(px + 36, py); ctx.lineTo(px + 36, py + ph); ctx.stroke();
ctx.fillStyle = INK; ctx.font = `14px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('THE LEDGER', w / 2, py + 17);
add(scene, 'mono-ledger', c);
}
function bakeHeader(scene) {
const { w, h } = HEADER;
const c = canvas(w, h), ctx = c.getContext('2d');
const g = ctx.createLinearGradient(0, 0, 0, h);
g.addColorStop(0, 'rgba(20,12,6,0.85)'); g.addColorStop(1, 'rgba(36,22,12,0.85)');
rr(ctx, 1, 1, w - 2, h - 2, 10); ctx.fillStyle = g; ctx.fill();
ctx.strokeStyle = GOLD; ctx.lineWidth = 1.5; ctx.stroke();
add(scene, 'mono-header', c);
}
// ── Entry ────────────────────────────────────────────────────────────────────
let baked = false;
export async function prepareMonopolyArt(scene) {
try {
if (document.fonts?.load) {
await Promise.race([
Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]),
new Promise((res) => setTimeout(res, 1200)),
]);
}
} catch (_) { /* fall back to Georgia */ }
if (!baked || !scene.textures.exists('mono-board')) {
bakeRoom(scene); bakeBoard(scene); bakeBills(scene); bakeMiniDeeds(scene); bakeBuildings(scene);
bakeDeckBacks(scene); bakeTray(scene); bakeBank(scene); bakePlaque(scene); bakeActions(scene);
bakeLedger(scene); bakeHeader(scene);
baked = true;
}
}
export function bandColorNum(i) {
const sp = SPACES[i];
if (sp.group) return parseInt(GROUP_HEX[sp.group].slice(1), 16);
if (sp.type === 'railroad') return 0x2b2b2b;
return i === 12 ? 0xe0b52c : 0x3d86c6;
}

View File

@ -0,0 +1,134 @@
// MonopolyBank.js — the banker's tray, the building rack, the Free Parking
// pot, and paper money in flight.
//
// build() the tray image, bill stacks, house/hotel pieces
// update(state) show the bank's house/hotel stock (amber when low)
// updatePot(state) the Free Parking jackpot pile on the board
// pay(from, to, amount, opts) bills fly between anchors (a seat's plaque, the
// bank, the pot); onArrive fires as they land
//
// The amount is broken into real denominations (largest first), capped at a
// handful of bills so big payments still read as a fat wad, not a blizzard.
import { BILLS } from './MonopolyData.js';
import {
BANK, BANK_ANCHOR, HOUSE_RACK, BILL_W, BILL_H, POT, billSlot,
} from './MonopolyLayout.js';
import { rustle } from './MonopolySound.js';
export function breakIntoBills(amount, cap = 9) {
const out = [];
let left = Math.max(0, Math.floor(amount));
for (const d of BILLS) {
while (left >= d && out.length < cap) { out.push(d); left -= d; }
}
if (!out.length && amount > 0) out.push(1);
return out;
}
export class Bank {
constructor(scene, depth) {
this.scene = scene;
this.depth = depth;
this.houses = [];
this.hotels = [];
this.potObjs = [];
}
build() {
const s = this.scene;
s.add.image(BANK.x - 20, BANK.y - 20, 'mono-bank').setOrigin(0).setDepth(this.depth);
// bill stacks — fanned a little so each compartment reads as a pile
for (let i = 0; i < 7; i++) {
const slot = billSlot(i);
for (let k = 0; k < 6; k++) {
s.add.image(slot.cx + (k % 2 ? 1.5 : -1.5), slot.cy - 6 - k * 1.6, `mono-bill-${BILLS[i]}`)
.setDisplaySize(BILL_W * 0.95, BILL_H * 0.95).setAngle(-90 + (k - 3) * 1.2).setDepth(this.depth + 1 + k * 0.01);
}
}
// building rack: 32 houses (2×16) on the left, 12 hotels (2×6) on the right
const R = HOUSE_RACK;
for (let k = 0; k < 32; k++) {
const col = k % 16, row = Math.floor(k / 16);
this.houses.push(s.add.image(R.x + 16 + col * 14.5, R.y + 18 + row * 20, 'mono-house').setDisplaySize(17, 17).setDepth(this.depth + 2));
}
for (let k = 0; k < 12; k++) {
const col = k % 6, row = Math.floor(k / 6);
this.hotels.push(s.add.image(R.x + 262 + col * 21, R.y + 18 + row * 20, 'mono-hotel').setDisplaySize(24, 16).setDepth(this.depth + 2));
}
const lbl = { fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#ecd690' };
this.houseText = s.add.text(R.x + 12, R.y + R.h - 14, '', lbl).setOrigin(0, 0.5).setDepth(this.depth + 2);
this.hotelText = s.add.text(R.x + R.w - 12, R.y + R.h - 14, '', lbl).setOrigin(1, 0.5).setDepth(this.depth + 2);
this.lowGlow = s.add.graphics().setDepth(this.depth + 1.5);
this.lowGlow.lineStyle(3, 0xffb030, 1).strokeRoundedRect(R.x - 2, R.y - 2, R.w + 4, R.h + 4, 8);
this.lowGlow.setAlpha(0);
this.lowTween = s.tweens.add({ targets: this.lowGlow, alpha: { from: 0.2, to: 0.95 }, duration: 700, yoyo: true, repeat: -1, paused: true });
return this;
}
update(state) {
this.houses.forEach((h, k) => h.setVisible(k < state.houseSupply));
this.hotels.forEach((h, k) => h.setVisible(k < state.hotelSupply));
this.houseText.setText(`HOUSES ${state.houseSupply}`);
this.hotelText.setText(`HOTELS ${state.hotelSupply}`);
const low = state.houseSupply <= 6 || state.hotelSupply <= 2;
this.houseText.setColor(state.houseSupply <= 6 ? '#ffc46a' : '#ecd690');
this.hotelText.setColor(state.hotelSupply <= 2 ? '#ffc46a' : '#ecd690');
if (low && this.lowTween.isPaused()) this.lowTween.resume();
if (!low) { this.lowTween.pause(); this.lowGlow.setAlpha(0); }
}
// Free Parking jackpot: a little heap of bills on the board with its total.
updatePot(state) {
this.potObjs.forEach((o) => o.destroy());
this.potObjs = [];
if (!state.rules?.freeParkingJackpot) return;
const s = this.scene;
const amt = state.freeParkingPot;
const bills = breakIntoBills(amt, 10);
bills.forEach((d, k) => {
const a = (k * 2.4) % (Math.PI * 2);
this.potObjs.push(s.add.image(POT.x + Math.cos(a) * (6 + k * 2), POT.y + Math.sin(a) * (4 + k), `mono-bill-${d}`)
.setDisplaySize(BILL_W, BILL_H).setAngle(-25 + k * 17).setDepth(8 + k * 0.01));
});
this.potObjs.push(s.add.text(POT.x, POT.y + 36, amt > 0 ? `JACKPOT $${amt.toLocaleString()}` : 'JACKPOT EMPTY', {
fontFamily: 'Righteous', fontSize: '16px', color: '#b3261e', stroke: '#f3ead2', strokeThickness: 4,
}).setOrigin(0.5).setDepth(8.5));
}
// Fly bills from one anchor to another. Resolves when the last one lands.
pay(fromPt, toPt, amount, { fast = false, onArrive = null, delay = 0 } = {}) {
const s = this.scene;
const bills = breakIntoBills(amount, fast ? 3 : 9);
if (!bills.length) { onArrive?.(); return Promise.resolve(); }
const dur = fast ? 260 : 620;
const stagger = fast ? 25 : 70;
if (!fast) s.time.delayedCall(delay, () => rustle(s));
const ps = bills.map((d, k) => new Promise((resolve) => {
const img = s.add.image(fromPt.x, fromPt.y, `mono-bill-${d}`).setScale(0.5).setDepth(44 + k * 0.01).setAngle(Math.random() * 30 - 15).setAlpha(0);
const mx = (fromPt.x + toPt.x) / 2 + (Math.random() - 0.5) * 60;
const my = Math.min(fromPt.y, toPt.y) - 80 - Math.random() * 60;
const sx = fromPt.x + (Math.random() - 0.5) * 20, sy = fromPt.y + (Math.random() - 0.5) * 12;
const ex = toPt.x + (Math.random() - 0.5) * 26, ey = toPt.y + (Math.random() - 0.5) * 14;
const prox = { t: 0 };
s.tweens.add({
targets: prox, t: 1, duration: dur, delay: delay + k * stagger, ease: 'Sine.easeInOut',
onStart: () => img.setAlpha(1),
onUpdate: () => {
const t = prox.t, u = 1 - t;
img.x = u * u * sx + 2 * u * t * mx + t * t * ex;
img.y = u * u * sy + 2 * u * t * my + t * t * ey;
img.angle += 3.5;
img.setScale(0.5 * (1 + Math.sin(Math.PI * t) * 0.25)); // textures are baked at 2×
},
onComplete: () => {
s.tweens.add({ targets: img, alpha: 0, scale: 0.3, duration: 160, onComplete: () => img.destroy() });
resolve();
},
});
}));
return Promise.all(ps).then(() => onArrive?.());
}
anchor() { return { ...BANK_ANCHOR }; }
}

View File

@ -1,9 +1,40 @@
// Monopoly — static data. No Phaser, no state. // Monopoly — static data. No Phaser, no state.
export const BOARD_SIZE = 840; // Board geometry (board-relative px). 2 corners + 9 spaces per side: 136·2 + 80·9 = 992.
export const CORNER_SIZE = 105; export const BOARD_SIZE = 992;
export const SPACE_W = 70; export const CORNER_SIZE = 136;
export const BAND_H = 18; export const SPACE_W = 80;
export const BAND_H = 26;
// ── Rules & settings ─────────────────────────────────────────────────────────
// Rules are fixed for the life of a game (stored in state.rules). The standard
// game is the default; Short Game and the house rules are opt-in.
export const DEFAULT_RULES = {
mode: 'classic', // 'classic' | 'short' (official short-game rules)
startingCash: 1500,
freeParkingJackpot: false, // taxes & fees pile up on Free Parking; landing collects
doubleGo: false, // $400 for landing exactly on GO
auctions: true, // a declined property is auctioned (official)
roundLimit: 0, // 0 = off; otherwise richest player wins after N rounds
};
export const STARTING_CASH_OPTIONS = [1000, 1500, 2000, 2500];
export const ROUND_LIMIT_OPTIONS = [0, 30, 50, 75];
// Table-side preferences (persisted in localStorage, apply immediately).
export const DEFAULT_SETTINGS = {
pace: 'normal', // opponent speed: 'relaxed' | 'normal' | 'fast'
skipAI: false, // snap opponent moves, short bill flights
threat: false, // threat map before you roll
confirmEnd: false, // ask before ending a turn with money/builds still possible
ledger: true, // show the ledger panel
rules: { ...DEFAULT_RULES }, // house rules for the NEXT game
};
// Paper money, largest first. Tints are 1930s-ish banknote inks.
export const BILLS = [500, 100, 50, 20, 10, 5, 1];
export const BILL_TINT = {
500: 0xe9c46a, 100: 0xe8d6a0, 50: 0x9cc3d5, 20: 0x9bcf9b, 10: 0xe9b7c8, 5: 0xcdb6de, 1: 0xf2efe6,
};
export const GROUP_COLORS = { export const GROUP_COLORS = {
brown: 0x9B5524, brown: 0x9B5524,
@ -159,6 +190,23 @@ export function nearestUtility(pos) {
return UTILITIES[0]; return UTILITIES[0];
} }
// Index of the Get Out of Jail Free card in each deck.
export const GOOJF_CARD = {
chance: CHANCE_CARDS.findIndex(c => c.effect === 'goojf'),
community_chest: CC_CARDS.findIndex(c => c.effect === 'goojf'),
};
export const GROUP_NAMES = {
brown: 'Brown', lightblue: 'Light Blue', pink: 'Pink', orange: 'Orange',
red: 'Red', yellow: 'Yellow', green: 'Green', darkblue: 'Dark Blue',
};
// Rent table for a railroad by number owned (1–4).
export const RAIL_RENT = [0, 25, 50, 100, 200];
// Probability of each 2d6 total.
export const DICE_P = Array.from({ length: 13 }, (_, t) => (t < 2 ? 0 : (6 - Math.abs(t - 7)) / 36));
// Pawn spritesheet: frame = seat index (0-3), 80×80 px cells // Pawn spritesheet: frame = seat index (0-3), 80×80 px cells
export const PAWN_FRAME = (seat) => seat; export const PAWN_FRAME = (seat) => seat;
// Card spritesheet: frame 0 = Chance, frame 1 = Community Chest, 200×300 px cells // Card spritesheet: frame 0 = Chance, frame 1 = Community Chest, 200×300 px cells

View File

@ -0,0 +1,142 @@
// MonopolyDeed.js — the title-deed card (Container), deco-styled.
// Used by the purchase modal (zooms off the board), hover cards and the trade
// screen. Centre-origin, MODAL_W × MODAL_H at scale 1.
//
// opts.live adds an owner / current-rent footer and the MORTGAGED stamp.
// opts.pawns adds the pawns standing on the space (the purchase modal).
import { SPACES, PLAYER_COLOR_HEX, RAIL_RENT, PAWN_FRAME, PLAYER_COLORS } from './MonopolyData.js';
import { calculateRent, ownsGroup, unmortgageCost, housesForHotel } from './MonopolyLogic.js';
import { bandColorNum, DECO, DISPLAY, INK } from './MonopolyArt.js';
export const MODAL_W = 340;
export const MODAL_H = 500;
const BAND_H = 84;
function luminance(n) { return (((n >> 16) & 255) * 0.299 + ((n >> 8) & 255) * 0.587 + (n & 255) * 0.114) / 255; }
export function buildDeedCard(scene, state, idx, { live = false, pawns = false, hasPawns = false } = {}) {
const sp = SPACES[idx];
const w = MODAL_W, h = MODAL_H, bh = BAND_H;
const c = scene.add.container(0, 0);
const g = scene.add.graphics();
// card stock + soft shadow
g.fillStyle(0x000000, 0.35); g.fillRoundedRect(-w / 2 + 6, -h / 2 + 10, w, h, 12);
g.fillStyle(0xfbf6e8, 1); g.fillRoundedRect(-w / 2, -h / 2, w, h, 12);
g.lineStyle(2, 0x241a10, 1); g.strokeRoundedRect(-w / 2, -h / 2, w, h, 12);
g.lineStyle(1, 0xc9a24a, 1); g.strokeRoundedRect(-w / 2 + 8, -h / 2 + 8, w - 16, h - 16, 8);
// band
const band = bandColorNum(idx);
g.fillStyle(band, 1); g.fillRect(-w / 2 + 14, -h / 2 + 14, w - 28, bh);
g.lineStyle(1.5, 0x241a10, 1); g.strokeRect(-w / 2 + 14, -h / 2 + 14, w - 28, bh);
c.add(g);
const onBand = luminance(band) > 0.62 ? '#241a10' : '#fbf6e8';
c.add(scene.add.text(0, -h / 2 + 30, sp.type === 'property' ? 'TITLE DEED' : sp.type === 'railroad' ? 'RAILROAD' : 'UTILITY', {
fontFamily: DECO, fontSize: '12px', color: onBand,
}).setOrigin(0.5));
c.add(scene.add.text(0, -h / 2 + 14 + bh / 2 + 10, sp.name.toUpperCase(), {
fontFamily: DISPLAY, fontSize: '22px', color: onBand, align: 'center', wordWrap: { width: w - 48 },
}).setOrigin(0.5));
const row = (y, label, val, { size = 15, color = INK, bold = false } = {}) => {
c.add(scene.add.text(-w / 2 + 34, y, label, { fontFamily: DECO, fontSize: `${size}px`, color }).setOrigin(0, 0.5));
c.add(scene.add.text(w / 2 - 34, y, val, { fontFamily: bold ? DISPLAY : DECO, fontSize: `${size}px`, color }).setOrigin(1, 0.5));
const lg = scene.add.graphics();
lg.lineStyle(1, 0x241a10, 0.22);
for (let x = -w / 2 + 34; x < w / 2 - 34; x += 6) lg.lineBetween(x, y + 9, x + 2, y + 9);
c.add(lg);
};
let y = -h / 2 + bh + 40;
const own = state?.board?.[idx];
// highlight the row that applies right now
let liveRow = -1;
if (own && own.owner !== null && sp.type === 'property') {
liveRow = own.hotel ? 6 : own.houses > 0 ? own.houses + 1 : ownsGroup(state, own.owner, sp.group) ? 1 : 0;
}
const hl = (k, yy) => {
if (k !== liveRow) return;
const hg = scene.add.graphics();
hg.fillStyle(PLAYER_COLORS[own.owner], 0.18); hg.fillRoundedRect(-w / 2 + 26, yy - 12, w - 52, 24, 5);
c.addAt(hg, 1);
};
if (sp.type === 'property') {
const N = state ? housesForHotel(state) : 4;
const rows = [
['Rent', sp.rent[0]], ['With colour set', sp.rent[1]], ['With 1 house', sp.rent[2]], ['With 2 houses', sp.rent[3]],
['With 3 houses', sp.rent[4]], ['With 4 houses', sp.rent[5]], ['With hotel', sp.rent[6]],
];
rows.forEach(([l, v], k) => {
if (N === 3 && k === 5) return; // short game: hotel after 3 houses
hl(k, y); row(y, l, `$${v.toLocaleString()}`, { bold: k === 6 }); y += 27;
});
y += 6;
row(y, 'Houses cost', `$${sp.houseCost} each`, { size: 13, color: '#5a4a38' }); y += 22;
row(y, `Hotels cost`, `$${sp.houseCost} + ${N} houses`, { size: 13, color: '#5a4a38' }); y += 22;
row(y, 'Mortgage value', `$${sp.mortgage}`, { size: 13, color: '#5a4a38' });
} else if (sp.type === 'railroad') {
for (let n = 1; n <= 4; n++) { row(y, `${n} railroad${n > 1 ? 's' : ''} owned`, `$${RAIL_RENT[n]}`); y += 30; }
y += 6;
row(y, 'Mortgage value', `$${sp.mortgage}`, { size: 13, color: '#5a4a38' });
} else {
const t = (s, yy, size = 15) => c.add(scene.add.text(0, yy, s, { fontFamily: DECO, fontSize: `${size}px`, color: INK, align: 'center', wordWrap: { width: w - 70 } }).setOrigin(0.5));
t('If one utility is owned, rent is', y); y += 24;
t('4 × the dice thrown', y, 18); y += 40;
t('If both utilities are owned, rent is', y); y += 24;
t('10 × the dice thrown', y, 18); y += 46;
row(y, 'Mortgage value', `$${sp.mortgage}`, { size: 13, color: '#5a4a38' });
}
// price ribbon
const pg = scene.add.graphics();
pg.lineStyle(1, 0xc9a24a, 1); pg.lineBetween(-w / 2 + 30, h / 2 - 100, w / 2 - 30, h / 2 - 100);
c.add(pg);
c.add(scene.add.text(0, h / 2 - 80, `PRICE $${sp.price}`, { fontFamily: DISPLAY, fontSize: '20px', color: INK }).setOrigin(0.5));
if (live && own) {
let foot;
if (own.owner === null) foot = 'Unowned — for sale by the bank';
else {
const who = state.players[own.owner];
const dice = sp.type === 'utility' ? null : 0;
const rent = own.mortgaged ? 0 : sp.type === 'utility' ? null : calculateRent(state, idx, dice ?? 7);
foot = own.mortgaged
? `${who.name} · mortgaged (lift $${unmortgageCost(state, idx)})`
: sp.type === 'utility'
? `${who.name} · rent ${own.owner !== null && state.board[idx === 12 ? 28 : 12].owner === own.owner ? 10 : 4}× dice`
: `${who.name} · rent now $${rent.toLocaleString()}`;
c.add(scene.add.text(0, h / 2 - 46, foot, {
fontFamily: DECO, fontSize: '14px', color: PLAYER_COLOR_HEX[own.owner], align: 'center', wordWrap: { width: w - 50 },
stroke: '#fbf6e8', strokeThickness: 2,
}).setOrigin(0.5));
foot = null;
}
if (foot) c.add(scene.add.text(0, h / 2 - 46, foot, { fontFamily: DECO, fontSize: '14px', color: '#5a4a38' }).setOrigin(0.5));
if (own.mortgaged) {
const st = scene.add.text(0, -10, 'MORTGAGED', {
fontFamily: DISPLAY, fontSize: '44px', color: '#b3261e',
}).setOrigin(0.5).setAngle(-22).setAlpha(0.72);
const sg = scene.add.graphics();
sg.lineStyle(4, 0xb3261e, 0.72); sg.strokeRoundedRect(-st.width / 2 - 10, -36, st.width + 20, 54, 6);
const box = scene.add.container(0, -10, [sg]).setAngle(-22);
sg.y = 10;
c.add([box, st]);
}
}
if (pawns && state) {
const on = state.players.filter((p) => p.position === idx && !p.bankrupt);
const spacing = 52, start = -(on.length - 1) * spacing / 2;
on.forEach((p, i) => {
const x = start + i * spacing, yy = h / 2 - 40;
if (hasPawns) c.add(scene.add.image(x, yy, 'monopoly-pawns', PAWN_FRAME(p.seat)).setDisplaySize(46, 46));
else { const pg2 = scene.add.graphics(); pg2.fillStyle(PLAYER_COLORS[p.seat], 1).fillCircle(x, yy, 18); c.add(pg2); }
});
}
return c;
}
export function destroyContainer(c) {
if (!c) return;
try { c.each((ch) => { try { ch.destroy(); } catch (_) { /* */ } }); c.destroy(); } catch (_) { /* */ }
}

View File

@ -0,0 +1,306 @@
// MonopolyDialogs.js — deco pop-ups for the Boardwalk Hotel. Each opener
// returns { close() } (some add refresh()) and swallows clicks beneath it.
//
// openFrontDesk the Esc menu: table settings, this game's rules, new game
// openSetup the new-game card: Classic / Short Game + house rules
// openResume "resume your game?" when a save exists
// openManage manage properties; in debt mode it is the Raise Funds sheet
// confirmBox, toast
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { canvas } from '../../ui/casino/CasinoArt.js';
import {
SPACES, GROUPS, RAILROADS, UTILITIES, GROUP_COLORS, STARTING_CASH_OPTIONS, ROUND_LIMIT_OPTIONS, PLAYER_COLOR_HEX,
} from './MonopolyData.js';
import {
canBuildHouse, canBuildHotel, canSellHouse, canSellHotel, canMortgage, canUnmortgage, unmortgageCost,
currentDebt, canSettleDebt, mustGoBankrupt, liquidationValue, ownsGroup, groupMortgaged, housesForHotel,
} from './MonopolyLogic.js';
import { decoPanel, DECO, DISPLAY, bandColorNum } from './MonopolyArt.js';
const CREAM = '#f3e7c8';
const GOLD_HEX = '#ecd690';
const MUTED = '#c9b892';
const BTN = 0x4a2e1a;
export function panelKey(scene, w, h) {
const key = `mono-panel-${w}x${h}`;
if (!scene.textures.exists(key)) {
const c = canvas(w + 60, h + 60);
const ctx = c.getContext('2d');
ctx.translate(30, 30);
decoPanel(ctx, 0, 0, w, h, { r: 18 });
scene.textures.addCanvas(key, c);
}
return key;
}
export function frame(scene, x, y, w, h, depth) {
return scene.add.image(x - 30, y - 30, panelKey(scene, w, h)).setOrigin(0).setDepth(depth);
}
export function blocker(scene, depth, alpha = 0) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x050302, alpha).setDepth(depth).setInteractive();
}
export function handle(objs, onClose) {
let closed = false;
return {
objs,
get closed() { return closed; },
close() { if (closed) return; closed = true; objs.forEach((o) => o?.destroy?.()); onClose?.(); },
};
}
const text = (scene, x, y, s, size, color, depth, opts = {}) =>
scene.add.text(x, y, s, { fontFamily: opts.font ?? DECO, fontSize: `${size}px`, color, align: opts.align ?? 'center', wordWrap: opts.wrap ? { width: opts.wrap } : undefined, lineSpacing: opts.lineSpacing ?? 2 })
.setOrigin(opts.ox ?? 0.5, opts.oy ?? 0.5).setDepth(depth);
const btn = (scene, x, y, label, fn, depth, o = {}) => {
const b = new Button(scene, x, y, label, fn, { width: o.w ?? 220, height: o.h ?? 44, fontSize: o.size ?? 17, bg: o.bg ?? BTN, variant: o.variant ?? 'solid' });
b.setDepth(depth);
if (o.enabled === false) b.setEnabled(false);
return b;
};
export function confirmBox(scene, { heading, body, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 560, h = 290, x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(text(scene, x + w / 2, y + 60, heading, 28, GOLD_HEX, depth + 1, { font: DISPLAY }));
objs.push(text(scene, x + w / 2, y + 128, body, 17, CREAM, depth + 1, { wrap: w - 90 }));
let hRef = null;
objs.push(btn(scene, x + w / 2 - 125, y + h - 56, yes, () => { hRef.close(); onYes?.(); }, depth + 2, { bg: 0x7a2a1a }));
objs.push(btn(scene, x + w / 2 + 125, y + h - 56, no, () => { hRef.close(); onNo?.(); }, depth + 2));
hRef = handle(objs);
return hRef;
}
export function toast(scene, msg, { depth = 95, color = GOLD_HEX, y = 92, ms = 2200 } = {}) {
const t = scene.add.text(560, y, msg, {
fontFamily: DISPLAY, fontSize: '22px', color, backgroundColor: '#1a0f08', padding: { x: 16, y: 8 },
}).setOrigin(0.5).setDepth(depth).setAlpha(0);
scene.tweens.add({ targets: t, alpha: 1, y: y + 6, duration: 200 });
scene.tweens.add({ targets: t, alpha: 0, delay: ms, duration: 400, onComplete: () => t.destroy() });
return t;
}
// ── Rules summary ────────────────────────────────────────────────────────────
export function rulesSummary(r) {
const bits = [r.mode === 'short' ? 'Short Game' : 'Classic'];
if (r.startingCash !== 1500) bits.push(`$${r.startingCash.toLocaleString()} start`);
if (r.freeParkingJackpot) bits.push('Free Parking jackpot');
if (r.doubleGo) bits.push('$400 on GO');
if (!r.auctions) bits.push('no auctions');
if (r.roundLimit) bits.push(`${r.roundLimit} rounds`);
return bits.join(' · ');
}
const MODE_TEXT = {
classic: 'The standard game. Buy, build, trade and bankrupt your rivals — the last player with money wins.',
short: 'Official short rules: two title deeds are dealt to each player (paid for at once), a hotel needs only three houses, lifting a mortgage costs no interest, and the game ends at the first bankruptcy — the richest player wins.',
};
// ── Setup card ───────────────────────────────────────────────────────────────
export function openSetup(scene, { rules, depth, onStart, onLeave, title = 'A NEW GAME' }) {
const r = { ...rules };
const objs = [blocker(scene, depth - 1, 0.6)];
const w = 720, h = 760, x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(text(scene, x + w / 2, y + 56, 'THE FRONT DESK', 15, MUTED, depth + 1));
objs.push(text(scene, x + w / 2, y + 90, title, 34, GOLD_HEX, depth + 1, { font: DISPLAY }));
const cx = x + w / 2;
const desc = text(scene, cx, y + 214, '', 16, CREAM, depth + 1, { wrap: w - 120 });
objs.push(desc);
const modeBtns = [];
const paintModes = () => {
modeBtns.forEach(([m, b]) => b.setActive(r.mode === m));
desc.setText(MODE_TEXT[r.mode]);
};
for (const [m, label, dx] of [['classic', 'Classic Game', -150], ['short', 'Short Game', 150]]) {
const b = btn(scene, cx + dx, y + 150, label, () => { r.mode = m; paintModes(); }, depth + 2, { w: 270, h: 50, size: 20 });
modeBtns.push([m, b]); objs.push(b);
}
objs.push(text(scene, cx, y + 296, 'HOUSE RULES', 15, MUTED, depth + 1));
const onOff = (v) => (v ? 'On' : 'Off');
const cycle = (arr, v) => arr[(arr.indexOf(v) + 1) % arr.length];
const rows = [
[() => `Starting cash: $${r.startingCash.toLocaleString()}`, () => { r.startingCash = cycle(STARTING_CASH_OPTIONS, r.startingCash); }],
[() => `Free Parking jackpot (taxes & fees pile up): ${onOff(r.freeParkingJackpot)}`, () => { r.freeParkingJackpot = !r.freeParkingJackpot; }],
[() => `$400 for landing exactly on GO: ${onOff(r.doubleGo)}`, () => { r.doubleGo = !r.doubleGo; }],
[() => `Auction a property nobody buys: ${onOff(r.auctions)}`, () => { r.auctions = !r.auctions; }],
[() => `Round limit (richest wins): ${r.roundLimit ? `${r.roundLimit} rounds` : 'Off'}`, () => { r.roundLimit = cycle(ROUND_LIMIT_OPTIONS, r.roundLimit); }],
];
rows.forEach(([label, fn], i) => {
const b = btn(scene, cx, y + 342 + i * 54, label(), () => { fn(); b.setLabel(label()); }, depth + 2, { w: 600, h: 44, size: 16 });
objs.push(b);
});
objs.push(text(scene, cx, y + h - 128, 'The standard rules are the defaults. Your choices are remembered for next time.', 13, MUTED, depth + 1, { wrap: w - 120 }));
let hRef = null;
objs.push(btn(scene, cx - 130, y + h - 66, 'Deal Me In', () => { hRef.close(); onStart(r); }, depth + 2, { w: 240, h: 54, size: 22, bg: 0x1d6a48 }));
objs.push(btn(scene, cx + 130, y + h - 66, onLeave ? 'Leave' : 'Cancel', () => { hRef.close(); onLeave?.(); }, depth + 2, { w: 200, h: 54, size: 20 }));
paintModes();
hRef = handle(objs);
return hRef;
}
// ── Resume ───────────────────────────────────────────────────────────────────
export function openResume(scene, { info, depth, onResume, onNew, onLeave }) {
const objs = [blocker(scene, depth - 1, 0.6)];
const w = 620, h = 400, x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(text(scene, x + w / 2, y + 62, 'WELCOME BACK', 34, GOLD_HEX, depth + 1, { font: DISPLAY }));
objs.push(text(scene, x + w / 2, y + 140, info, 17, CREAM, depth + 1, { wrap: w - 100 }));
let hRef = null;
objs.push(btn(scene, x + w / 2, y + 232, 'Resume Your Game', () => { hRef.close(); onResume(); }, depth + 2, { w: 300, h: 54, size: 21, bg: 0x1d6a48 }));
objs.push(btn(scene, x + w / 2 - 110, y + 310, 'New Game', () => { hRef.close(); onNew(); }, depth + 2, { w: 190, h: 46 }));
objs.push(btn(scene, x + w / 2 + 110, y + 310, 'Leave', () => { hRef.close(); onLeave(); }, depth + 2, { w: 190, h: 46 }));
hRef = handle(objs);
return hRef;
}
// ── Front Desk (Esc) ─────────────────────────────────────────────────────────
const PACE = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' };
export function openFrontDesk(scene, { settings, rules, depth, onChange, onRules, onNewGame, onLeave, onClose }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 640, h = 800, x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
objs.push(text(scene, x + w / 2, y + 62, 'THE FRONT DESK', 32, GOLD_HEX, depth + 1, { font: DISPLAY }));
objs.push(text(scene, x + w / 2, y + 104, `This game: ${rulesSummary(rules)}`, 14, MUTED, depth + 1, { wrap: w - 80 }));
const cx = x + w / 2;
const onOff = (v) => (v ? 'On' : 'Off');
let hRef = null;
const cycle = (k, order) => onChange(k, order[(order.indexOf(settings[k]) + 1) % order.length]);
const rows = [
['Resume', () => hRef.close(), 0x1d6a48],
[() => `Opponent speed: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])],
[() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)],
[() => `Threat map before you roll (T): ${onOff(settings.threat)}`, () => onChange('threat', !settings.threat)],
[() => `Ledger panel (L): ${onOff(settings.ledger)}`, () => onChange('ledger', !settings.ledger)],
[() => `Ask before ending a turn with money to build: ${onOff(settings.confirmEnd)}`, () => onChange('confirmEnd', !settings.confirmEnd)],
['How to Play', () => onRules()],
['New Game…', () => { hRef.close(); onNewGame(); }, 0x6a4a1a],
['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a2a1a],
];
rows.forEach(([label, fn, bg], i) => {
const t = typeof label === 'function' ? label() : label;
const b = btn(scene, cx, y + 168 + i * 60, t, () => { fn(); if (typeof label === 'function') b.setLabel(label()); }, depth + 2, { w: 540, h: 46, size: 16, bg });
objs.push(b);
});
objs.push(text(scene, cx, y + h - 46, 'Keys: Space roll / end turn · M manage · T threat map · L ledger · Esc this menu', 13, MUTED, depth + 1, { wrap: w - 80 }));
hRef = handle(objs, onClose);
return hRef;
}
// ── Manage / Raise Funds ─────────────────────────────────────────────────────
const ORDER = [...Object.keys(GROUPS), 'railroad', 'utility'];
const idxsOf = (k) => (k === 'railroad' ? RAILROADS : k === 'utility' ? UTILITIES : GROUPS[k]);
export function openManage(scene, { getState, seat, depth, focusIdx = null, onAct, onSettle, onBankrupt, onAuto, onEvenBuild, onClose }) {
const objs = [blocker(scene, depth - 1, 0.6)];
const w = 1120, h = 820, x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
let dyn = [];
let hRef = null;
const render = () => {
dyn.forEach((o) => o.destroy());
dyn = [];
const st = getState();
const debt = currentDebt(st);
const inDebt = st.phase === 'debt' && debt?.debtor === seat;
const p = st.players[seat];
const add = (o) => { dyn.push(o); return o; };
const N = housesForHotel(st);
add(text(scene, x + w / 2, y + 52, inDebt ? 'RAISE FUNDS' : 'MANAGE PROPERTIES', 32, inDebt ? '#ff9a8a' : GOLD_HEX, depth + 1, { font: DISPLAY }));
if (inDebt) {
const who = typeof debt.creditor === 'number' ? st.players[debt.creditor].name : debt.creditor === 'pot' ? 'the Free Parking pot' : 'the bank';
const short = Math.max(0, debt.amount - p.cash);
add(text(scene, x + w / 2, y + 94, `You owe $${debt.amount.toLocaleString()} to ${who} (${debt.why}). Cash on hand: $${p.cash.toLocaleString()}`, 18, CREAM, depth + 1));
add(text(scene, x + w / 2, y + 122, short > 0
? `Still short $${short.toLocaleString()} — sell buildings (evenly, at half price) or mortgage deeds. You could raise up to $${liquidationValue(st, seat).toLocaleString()}.`
: 'You have enough — settle the debt.', 15, short > 0 ? '#ffc46a' : '#9fe0a8', depth + 1, { wrap: w - 80 }));
} else {
add(text(scene, x + w / 2, y + 96, `Cash on hand: $${p.cash.toLocaleString()} · Bank stock: ${st.houseSupply} houses, ${st.hotelSupply} hotels`, 17, CREAM, depth + 1));
add(text(scene, x + w / 2, y + 122, `Build evenly across a full colour set (no mortgages in it). A hotel needs ${N} houses on every lot. Mortgage only with no buildings in the set.`, 13, MUTED, depth + 1, { wrap: w - 80 }));
}
// two columns of deed rows
const rows = [];
for (const k of ORDER) {
const mine = idxsOf(k).filter((i) => st.board[i]?.owner === seat);
if (mine.length) rows.push({ k, idxs: mine });
}
const flat = [];
rows.forEach((g) => { g.idxs.forEach((i, n) => flat.push({ i, k: g.k, first: n === 0, size: g.idxs.length })); });
if (!flat.length) add(text(scene, x + w / 2, y + 340, 'You do not own any deeds yet.', 18, MUTED, depth + 1));
const colW = (w - 80) / 2, rowH = 36, top = y + 160;
const perCol = 14;
flat.forEach((r, n) => {
const col = n < perCol ? 0 : 1, row = n % perCol;
const rx = x + 40 + col * colW, ry = top + row * rowH;
const sp = SPACES[r.i], own = st.board[r.i];
if (r.i === focusIdx) {
const fg = add(scene.add.graphics().setDepth(depth + 1));
fg.fillStyle(0xecd690, 0.16).fillRoundedRect(rx - 6, ry - 16, colW - 14, 32, 6);
}
const sw = add(scene.add.graphics().setDepth(depth + 1));
sw.fillStyle(bandColorNum(r.i), 1).fillRoundedRect(rx, ry - 11, 16, 22, 3);
if (own.mortgaged) sw.lineStyle(2, 0xb3261e, 1).strokeRoundedRect(rx, ry - 11, 16, 22, 3);
add(text(scene, rx + 26, ry, sp.name, 15, own.mortgaged ? '#a89878' : CREAM, depth + 1, { ox: 0 }));
const stTxt = own.mortgaged ? 'mortgaged' : own.hotel ? 'HOTEL' : own.houses ? `${own.houses} house${own.houses > 1 ? 's' : ''}` : '';
add(text(scene, rx + 222, ry, stTxt, 13, own.mortgaged ? '#ff9a8a' : own.hotel ? '#ff8a80' : '#9fe0a8', depth + 1, { ox: 0 }));
let bx = rx + colW - 22;
const small = (label, fn, enabled, wdt = 92, bg = BTN) => {
bx -= wdt / 2;
const b = add(btn(scene, bx, ry, label, fn, depth + 2, { w: wdt, h: 30, size: 13, enabled, bg }));
bx -= wdt / 2 + 6;
return b;
};
if (own.mortgaged) small(`Lift $${unmortgageCost(st, r.i)}`, () => onAct('unmortgage', r.i), !inDebt && canUnmortgage(st, seat, r.i), 104);
else small(`Mortgage +$${sp.mortgage}`, () => onAct('mortgage', r.i), canMortgage(st, seat, r.i), 128, 0x5a2a1a);
if (sp.type === 'property') {
const canSell = canSellHotel(st, seat, r.i) || canSellHouse(st, seat, r.i);
small('−', () => onAct(own.hotel ? 'sellHotel' : 'sellHouse', r.i), canSell, 34, 0x5a2a1a);
const hotelNext = canBuildHotel(st, seat, r.i);
small(hotelNext ? '+H' : '+', () => onAct(hotelNext ? 'hotel' : 'house', r.i), !inDebt && (hotelNext || canBuildHouse(st, seat, r.i)), 34, 0x1d6a48);
}
});
// even-build chips for every complete set
if (!inDebt) {
const sets = Object.keys(GROUPS).filter((k) => ownsGroup(st, seat, k));
if (sets.length) {
add(text(scene, x + 40, y + h - 116, 'Build evenly:', 14, MUTED, depth + 1, { ox: 0 }));
sets.forEach((k, n) => {
const ok = !groupMortgaged(st, k) && GROUPS[k].some((i) => canBuildHouse(st, seat, i) || canBuildHotel(st, seat, i));
const cost = SPACES[GROUPS[k][0]].houseCost;
const bxx = x + 210 + n * 132;
const b = add(btn(scene, bxx, y + h - 116, `+1 each $${cost}`, () => onEvenBuild(k), depth + 2, { w: 124, h: 32, size: 12, enabled: ok, bg: 0x1d6a48 }));
b.setAlpha(ok ? 1 : 0.4);
const sw = add(scene.add.graphics().setDepth(depth + 3));
sw.fillStyle(GROUP_COLORS[k], 1).fillRect(bxx - 58, y + h - 129, 8, 26);
});
}
}
// footer
const fy = y + h - 58;
if (inDebt) {
add(btn(scene, x + w / 2 - 300, fy, 'Auto-raise', () => onAuto(), depth + 2, { w: 200, h: 50, size: 18 }));
add(btn(scene, x + w / 2 - 40, fy, `Settle $${debt.amount.toLocaleString()}`, () => onSettle(), depth + 2, { w: 260, h: 50, size: 20, bg: 0x1d6a48, enabled: canSettleDebt(st) }));
if (mustGoBankrupt(st)) add(btn(scene, x + w / 2 + 250, fy, 'Declare Bankruptcy', () => onBankrupt(), depth + 2, { w: 260, h: 50, size: 18, bg: 0x7a1a1a }));
else add(text(scene, x + w / 2 + 250, fy, 'Bankruptcy is only allowed once\nyou can no longer raise the money.', 12, MUTED, depth + 1));
} else {
add(btn(scene, x + w / 2, fy, 'Done', () => hRef.close(), depth + 2, { w: 220, h: 50, size: 20 }));
}
};
render();
hRef = handle(objs, () => { dyn.forEach((o) => o.destroy()); dyn = []; onClose?.(); });
hRef.refresh = () => { if (!hRef.closed) render(); };
return hRef;
}
export { PLAYER_COLOR_HEX, GROUP_COLORS };

View File

@ -0,0 +1,163 @@
// MonopolyEndScreen.js — the closing ceremony: standings, a net-worth-over-time
// chart, per-player stats, the most-landed spaces as a heat strip round a mini
// board, and the biggest single payment of the game.
//
// Also used mid-game when the human goes bankrupt (opts.out): the AIs can play
// on while you watch.
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { SPACES, PLAYER_COLORS, PLAYER_COLOR_HEX, PAWN_FRAME } from './MonopolyData.js';
import { netWorth } from './MonopolyLogic.js';
import { frame, blocker, handle } from './MonopolyDialogs.js';
import { DECO, DISPLAY } from './MonopolyArt.js';
import { Button } from '../../ui/Button.js';
const CREAM = '#f3e7c8', GOLD_HEX = '#ecd690', MUTED = '#c9b892';
const REASON = {
last: 'Last player standing',
short: 'Short game — the first bankruptcy ends it; richest player wins',
rounds: 'Round limit reached — richest player wins',
};
export function showEndScreen(scene, state, { humanSeat, depth, hasPawns, out = false, onPlayAgain, onMenu, onWatch }) {
const objs = [blocker(scene, depth - 1, 0.72)];
const w = 1560, h = 920, x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
const T = (tx, ty, s, size, color, o = {}) => {
const t = scene.add.text(tx, ty, s, { fontFamily: o.font ?? DECO, fontSize: `${size}px`, color, align: o.align ?? 'center', wordWrap: o.wrap ? { width: o.wrap } : undefined })
.setOrigin(o.ox ?? 0.5, o.oy ?? 0.5).setDepth(depth + 1);
objs.push(t); return t;
};
const standings = state.standings ?? [...state.players]
.sort((a, b) => (b.active - a.active) || (netWorth(state, b.seat) - netWorth(state, a.seat)) || ((b.bankruptTurn ?? 0) - (a.bankruptTurn ?? 0)))
.map((p) => p.seat);
const winner = state.players[state.winner ?? standings[0]];
const youWon = state.phase === 'gameover' && winner?.seat === humanSeat;
const title = out ? 'YOU ARE BANKRUPT' : youWon ? 'YOU WIN!' : `${winner?.name ?? '—'} WINS`;
T(x + w / 2, y + 60, title, 46, out ? '#ff9a8a' : GOLD_HEX, { font: DISPLAY });
T(x + w / 2, y + 104, out ? `Finished ${ordinal(standings.indexOf(humanSeat) + 1)} of ${state.playerCount} — the others play on` : (REASON[state.endReason] ?? ''), 17, MUTED);
T(x + w / 2, y + 130, `${state.round} rounds · ${state.turn} turns`, 14, MUTED);
// ── standings ──
const sx = x + 60, sy = y + 180;
T(sx, sy, 'FINAL STANDINGS', 16, MUTED, { ox: 0 });
standings.forEach((seat, k) => {
const p = state.players[seat];
const ry = sy + 44 + k * 74;
const g = scene.add.graphics().setDepth(depth + 1);
g.fillStyle(PLAYER_COLORS[seat], k === 0 && !out ? 0.28 : 0.14).fillRoundedRect(sx, ry - 30, 430, 62, 10);
g.lineStyle(2, PLAYER_COLORS[seat], 0.8).strokeRoundedRect(sx, ry - 30, 430, 62, 10);
objs.push(g);
T(sx + 28, ry, String(k + 1), 30, k === 0 ? GOLD_HEX : CREAM, { font: DISPLAY });
if (hasPawns) objs.push(scene.add.image(sx + 78, ry, 'monopoly-pawns', PAWN_FRAME(seat)).setDisplaySize(50, 50).setDepth(depth + 1));
T(sx + 116, ry - 12, p.name + (seat === humanSeat ? ' (you)' : ''), 19, CREAM, { ox: 0, font: DISPLAY });
T(sx + 116, ry + 14, p.bankrupt ? `bankrupt on turn ${p.bankruptTurn}` : `net worth $${netWorth(state, seat).toLocaleString()}`, 14, p.bankrupt ? '#ff9a8a' : '#9fe0a8', { ox: 0 });
});
// ── net worth chart ──
const cx0 = x + 540, cy0 = y + 180, cw = 960, ch = 300;
T(cx0, cy0, 'NET WORTH OVER TIME', 16, MUTED, { ox: 0 });
const hist = state.stats?.history ?? [];
const g = scene.add.graphics().setDepth(depth + 1);
objs.push(g);
const px = cx0 + 60, py = cy0 + 24, pw = cw - 80, ph = ch - 40;
g.fillStyle(0x0c2a1d, 0.75).fillRoundedRect(px - 10, py - 10, pw + 20, ph + 30, 8);
const max = Math.max(1, ...hist.flat());
const step = niceStep(max);
for (let v = 0; v <= max; v += step) {
const yy = py + ph - (v / max) * ph;
g.lineStyle(1, 0xecd690, 0.12).lineBetween(px, yy, px + pw, yy);
T(px - 14, yy, `$${shortNum(v)}`, 11, MUTED, { ox: 1 });
}
if (hist.length >= 2) {
for (let seat = 0; seat < state.playerCount; seat++) {
g.lineStyle(seat === humanSeat ? 4 : 2.5, PLAYER_COLORS[seat], 0.95);
g.beginPath();
let started = false;
hist.forEach((row, k) => {
const v = row[seat] ?? 0;
const xx = px + (k / (hist.length - 1)) * pw, yy = py + ph - (v / max) * ph;
if (!started) { g.moveTo(xx, yy); started = true; } else g.lineTo(xx, yy);
});
g.strokePath();
}
T(px, py + ph + 12, 'start', 11, MUTED, { ox: 0 });
T(px + pw, py + ph + 12, `round ${state.round}`, 11, MUTED, { ox: 1 });
} else {
T(px + pw / 2, py + ph / 2, 'not enough rounds played to chart', 14, MUTED);
}
// ── stats table ──
const s = state.stats;
const tx = x + 540, ty = y + 520;
T(tx, ty, 'THE BOOKS', 16, MUTED, { ox: 0 });
const cols = [['Rent collected', 'rentCollected', '$'], ['Rent paid', 'rentPaid', '$'], ['Passed GO', 'goPasses'], ['Jail visits', 'jailVisits'], ['Doubles', 'doubles'], ['Deeds bought', 'bought'], ['Buildings', 'built']];
cols.forEach(([label], c) => T(tx + 200 + c * 110, ty + 30, label, 12, MUTED));
for (let seat = 0; seat < state.playerCount; seat++) {
const ry = ty + 60 + seat * 30;
T(tx, ry, state.players[seat].name, 15, PLAYER_COLOR_HEX[seat], { ox: 0, font: DISPLAY });
cols.forEach(([, key, pre], c) => T(tx + 200 + c * 110, ry, `${pre ?? ''}${(s?.[key]?.[seat] ?? 0).toLocaleString()}`, 15, CREAM));
}
// ── landings heat strip + biggest payment ──
const hx = x + 60, hy = y + 520;
T(hx, hy, 'MOST-LANDED SPACES', 16, MUTED, { ox: 0 });
const land = s?.landings ?? Array(40).fill(0);
const total = Math.max(1, land.reduce((a, b) => a + b, 0));
const top = land.map((n, i) => ({ i, n })).sort((a, b) => b.n - a.n).slice(0, 5);
const hg = scene.add.graphics().setDepth(depth + 1);
objs.push(hg);
const mx = Math.max(1, ...land);
// a tiny board ring: 11 cells per side
const cell = 16, ox = hx + 10, oy = hy + 30;
for (let i = 0; i < 40; i++) {
const side = Math.floor(i / 10), k = i % 10;
let cxp, cyp;
if (side === 0) { cxp = ox + (10 - k) * cell; cyp = oy + 10 * cell; }
else if (side === 1) { cxp = ox; cyp = oy + (10 - k) * cell; }
else if (side === 2) { cxp = ox + k * cell; cyp = oy; }
else { cxp = ox + 10 * cell; cyp = oy + k * cell; }
const t = land[i] / mx;
hg.fillStyle(mixInt(0x2a3a30, 0xff7043, t), 1).fillRect(cxp, cyp, cell - 2, cell - 2);
}
top.forEach((e, k) => T(ox + 11 * cell + 20, oy + 10 + k * 24, `${k + 1}. ${SPACES[e.i].name} ${(100 * e.n / total).toFixed(1)}%`, 14, CREAM, { ox: 0 }));
if (s?.biggest) {
const b = s.biggest;
const from = typeof b.from === 'number' ? state.players[b.from].name : 'The bank';
const to = typeof b.to === 'number' ? state.players[b.to].name : b.to === 'pot' ? 'the Free Parking pot' : 'the bank';
const where = b.why === 'rent' && b.spaceIdx !== null ? ` (rent on ${SPACES[b.spaceIdx].name})` : ` (${b.why})`;
T(hx, oy + 11 * cell + 26, `Biggest payment: $${b.amount.toLocaleString()} — ${from} to ${to}${where}`, 15, GOLD_HEX, { ox: 0, wrap: 460, align: 'left' });
}
// ── buttons ──
let hRef = null;
const bY = y + h - 60;
const mk = (bx, label, fn, bg) => {
const b = new Button(scene, bx, bY, label, () => { hRef.close(); fn(); }, { width: 240, height: 54, fontSize: 20, bg: bg ?? 0x4a2e1a });
b.setDepth(depth + 2); objs.push(b);
};
if (out && onWatch) {
mk(x + w / 2 - 270, 'Watch to the End', onWatch, 0x1d6a48);
mk(x + w / 2, 'Play Again', onPlayAgain);
mk(x + w / 2 + 270, 'Main Menu', onMenu);
} else {
mk(x + w / 2 - 140, 'Play Again', onPlayAgain, 0x1d6a48);
mk(x + w / 2 + 140, 'Main Menu', onMenu);
}
hRef = handle(objs);
return hRef;
}
function ordinal(n) { const s = ['th', 'st', 'nd', 'rd'], v = n % 100; return `${n}${s[(v - 20) % 10] || s[v] || s[0]}`; }
function niceStep(max) {
const raw = max / 5;
const p = Math.pow(10, Math.floor(Math.log10(raw)));
return [1, 2, 2.5, 5, 10].map((m) => m * p).find((s) => s >= raw) ?? raw;
}
function shortNum(v) { return v >= 1000 ? `${(v / 1000).toFixed(v % 1000 ? 1 : 0)}k` : String(Math.round(v)); }
function mixInt(a, b, t) {
const r = Math.round(((a >> 16) & 255) + (((b >> 16) & 255) - ((a >> 16) & 255)) * t);
const g = Math.round(((a >> 8) & 255) + (((b >> 8) & 255) - ((a >> 8) & 255)) * t);
const bl = Math.round((a & 255) + ((b & 255) - (a & 255)) * t);
return (r << 16) | (g << 8) | bl;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,209 @@
// MonopolyHud.js — the right-hand furniture that tracks the players.
//
// Plaques walnut nameplates: portrait ring, name, rolling cash counter, net
// worth, status chips (turn, jail tally, Jail Free cards), and a
// felt deed rail with each player's title deeds fanned by colour
// group (mortgaged deeds turned over, completed sets edged in gilt)
// Ledger the game log on a ruled page, colour-coded by player, scrollable
//
// Cash is shown from `shown[seat]`, which the scene nudges as bills land so the
// counter rolls in step with the money animation; sync() snaps it to the truth.
import { SPACES, GROUPS, RAILROADS, UTILITIES, PURCHASABLE, PLAYER_COLORS, PLAYER_COLOR_HEX } from './MonopolyData.js';
import { netWorth, ownsGroup } from './MonopolyLogic.js';
import { plaqueParts, LEDGER, HEADER, DEPTH } from './MonopolyLayout.js';
import { DECO, DISPLAY } from './MonopolyArt.js';
const RAIL_ORDER = [...Object.keys(GROUPS), 'railroad', 'utility'];
const groupIdxs = (k) => (k === 'railroad' ? RAILROADS : k === 'utility' ? UTILITIES : GROUPS[k]);
export class Hud {
constructor(scene, { humanSeat, playerCount, onDeedHover, onDeedOut, onDeedClick }) {
this.scene = scene;
this.humanSeat = humanSeat;
this.n = playerCount;
this.onDeedHover = onDeedHover;
this.onDeedOut = onDeedOut;
this.onDeedClick = onDeedClick;
this.plaques = [];
this.shown = [];
this.railSig = [];
this.ledgerScroll = 0;
this.ledgerLines = [];
}
build(state) {
const s = this.scene;
s.add.image(HEADER.x, HEADER.y, 'mono-header').setOrigin(0).setDepth(DEPTH.hud);
s.add.text(HEADER.x + 18, HEADER.y + HEADER.h / 2, 'THE BOARDWALK HOTEL', { fontFamily: DISPLAY, fontSize: '20px', color: '#ecd690' })
.setOrigin(0, 0.5).setDepth(DEPTH.hudText);
this.modeText = s.add.text(HEADER.x + 290, HEADER.y + HEADER.h / 2, '', { fontFamily: DECO, fontSize: '13px', color: '#c9b892' })
.setOrigin(0, 0.5).setDepth(DEPTH.hudText);
for (let seat = 0; seat < this.n; seat++) {
const parts = plaqueParts(seat);
const P = parts.P;
const o = { parts };
o.glow = s.add.graphics().setDepth(DEPTH.hud - 0.5);
o.glow.lineStyle(4, PLAYER_COLORS[seat], 1).strokeRoundedRect(P.x - 4, P.y - 4, P.w + 8, P.h + 8, 16);
o.glow.lineStyle(10, PLAYER_COLORS[seat], 0.25).strokeRoundedRect(P.x - 8, P.y - 8, P.w + 16, P.h + 16, 18);
o.glow.setAlpha(0);
o.glowTween = s.tweens.add({ targets: o.glow, alpha: { from: 0.45, to: 1 }, duration: 900, yoyo: true, repeat: -1, paused: true });
s.add.image(P.x - 20, P.y - 20, 'mono-plaque').setOrigin(0).setDepth(DEPTH.hud);
// seat colour tab under the portrait
const tab = s.add.graphics().setDepth(DEPTH.hud + 0.5);
tab.fillStyle(PLAYER_COLORS[seat], 1).fillRoundedRect(parts.portrait.x - 30, parts.portrait.y + 40, 60, 8, 3);
o.name = s.add.text(parts.name.x, parts.name.y, '', { fontFamily: DISPLAY, fontSize: '19px', color: '#f3e7c8' }).setDepth(DEPTH.hudText);
o.cash = s.add.text(parts.cash.x, parts.cash.y, '', { fontFamily: DISPLAY, fontSize: '32px', color: '#9fe0a8', stroke: '#0b2416', strokeThickness: 3 }).setDepth(DEPTH.hudText);
o.worth = s.add.text(parts.worth.x, parts.worth.y, '', { fontFamily: DECO, fontSize: '13px', color: '#c9b892' }).setDepth(DEPTH.hudText);
o.chips = s.add.text(parts.chips.x, parts.chips.y, '', { fontFamily: DECO, fontSize: '13px', color: '#ecd690', align: 'right' }).setOrigin(1, 0).setDepth(DEPTH.hudText);
o.flash = s.add.text(parts.anchor.x + 120, parts.anchor.y - 18, '', { fontFamily: DISPLAY, fontSize: '22px', color: '#9fe0a8', stroke: '#0b2416', strokeThickness: 4 })
.setOrigin(0.5).setDepth(DEPTH.hudText + 1).setAlpha(0);
o.out = s.add.text(P.x + P.w / 2, P.y + 92, '', { fontFamily: DISPLAY, fontSize: '34px', color: '#e06c75', stroke: '#1a0808', strokeThickness: 5 })
.setOrigin(0.5).setAngle(-8).setDepth(DEPTH.hudText + 2);
o.rail = [];
this.plaques[seat] = o;
this.shown[seat] = state.players[seat].cash;
}
// Ledger
this.ledgerBg = s.add.image(LEDGER.x - 20, LEDGER.y - 20, 'mono-ledger').setOrigin(0).setDepth(DEPTH.hud);
const lz = s.add.zone(LEDGER.x + LEDGER.w / 2, LEDGER.y + LEDGER.h / 2, LEDGER.w, LEDGER.h).setInteractive().setDepth(DEPTH.hud + 1);
lz.on('wheel', (_p, _dx, dy) => { this.ledgerScroll = Math.max(0, this.ledgerScroll + (dy > 0 ? -2 : 2)); this.renderLedger(this._lastState); });
for (let k = 0; k < 11; k++) {
this.ledgerLines.push(s.add.text(LEDGER.x + 56, LEDGER.y + 38 + k * 21, '', {
fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#241a10', wordWrap: { width: LEDGER.w - 80 }, maxLines: 1,
}).setDepth(DEPTH.hudText));
}
this.ledgerDots = s.add.graphics().setDepth(DEPTH.hudText);
this.ledgerHint = s.add.text(LEDGER.x + LEDGER.w - 22, LEDGER.y + 30, '', { fontFamily: DECO, fontSize: '11px', color: '#7a6a50' })
.setOrigin(1, 0.5).setDepth(DEPTH.hudText);
return this;
}
setModeText(t) { this.modeText.setText(t); }
sync(state) { for (let s = 0; s < this.n; s++) this.shown[s] = state.players[s].cash; }
// Money arriving / leaving (called by the scene as bills land).
bump(seat, delta) {
const o = this.plaques[seat];
if (!o) return;
const from = this.shown[seat];
this.shown[seat] = from + delta;
const prox = { v: from };
o.rolling = (o.rolling ?? 0) + 1;
this.scene.tweens.add({
targets: prox, v: this.shown[seat], duration: 380, ease: 'Sine.easeOut',
onUpdate: () => o.cash.setText(`$${Math.round(prox.v).toLocaleString()}`),
onComplete: () => { o.rolling--; if (!o.rolling) o.cash.setText(`$${Math.round(this.shown[seat]).toLocaleString()}`); },
});
o.flash.setText(`${delta > 0 ? '+' : '−'}$${Math.abs(delta).toLocaleString()}`).setColor(delta > 0 ? '#9fe0a8' : '#ff8a80').setAlpha(1).setY(o.parts.anchor.y - 18);
this.scene.tweens.add({ targets: o.flash, y: o.parts.anchor.y - 40, alpha: 0, delay: 500, duration: 700 });
}
update(state, { activeSeat = null, actingSeat = null, rails = true } = {}) {
this._lastState = state;
for (let seat = 0; seat < this.n; seat++) {
const o = this.plaques[seat];
const p = state.players[seat];
if (!o.rolling) o.cash.setText(`$${Math.round(this.shown[seat]).toLocaleString()}`);
o.worth.setText(p.bankrupt ? '' : `Net worth $${netWorth(state, seat).toLocaleString()}`);
const chips = [];
if (p.jailed) chips.push(`IN JAIL ${'▮'.repeat(p.jailTurns)}${'▯'.repeat(Math.max(0, 3 - p.jailTurns))}`);
if (p.getOutOfJailFree > 0) chips.push(`JAIL FREE ×${p.getOutOfJailFree}`);
if (seat === actingSeat && seat !== activeSeat && state.phase === 'auction') chips.push('BIDDING');
if (seat === actingSeat && state.phase === 'debt') chips.push('RAISING FUNDS');
o.chips.setText(chips.join('\n'));
const max = chips.length ? 13 : 18; // leave room for the chips
o.name.setText(p.name.length > max ? `${p.name.slice(0, max - 1)}…` : p.name);
o.out.setText(p.bankrupt ? 'BANKRUPT' : '');
o.cash.setAlpha(p.bankrupt ? 0.35 : 1);
const lit = state.phase !== 'gameover' && (seat === activeSeat || seat === actingSeat);
if (lit && o.glowTween.isPaused()) o.glowTween.resume();
if (!lit) { o.glowTween.pause(); o.glow.setAlpha(0); }
if (rails) this.renderRail(state, seat);
}
this.renderLedger(state);
}
renderRail(state, seat) {
const o = this.plaques[seat];
const owned = PURCHASABLE.filter((i) => state.board[i]?.owner === seat);
const sig = owned.map((i) => `${i}${state.board[i].mortgaged ? 'm' : ''}`).join(',') + (state.players[seat].bankrupt ? 'x' : '');
if (sig === this.railSig[seat]) return;
this.railSig[seat] = sig;
o.rail.forEach((r) => r.destroy());
o.rail = [];
const R = o.parts.rail;
const clusters = [];
for (const k of RAIL_ORDER) {
const mine = groupIdxs(k).filter((i) => state.board[i]?.owner === seat);
if (mine.length) clusters.push({ k, idxs: mine, full: k !== 'railroad' && k !== 'utility' ? ownsGroup(state, seat, k) : mine.length === groupIdxs(k).length });
}
if (!clusters.length) {
o.rail.push(this.scene.add.text(R.x + R.w / 2, R.y + R.h / 2 - 2, state.players[seat].bankrupt ? '' : 'no deeds yet', {
fontFamily: DECO, fontSize: '12px', color: '#6f9c84',
}).setOrigin(0.5).setDepth(DEPTH.hudText));
return;
}
const CW = 30, CH = 42, GAP = 8;
let off = 11;
const width = () => clusters.reduce((a, c) => a + CW + (c.idxs.length - 1) * off, 0) + GAP * (clusters.length - 1);
while (width() > R.w - 12 && off > 4) off -= 1;
let x = R.x + (R.w - width()) / 2 + CW / 2;
const y = R.y + R.h / 2 - 3;
clusters.forEach((c) => {
c.idxs.forEach((i, k) => {
const m = state.board[i].mortgaged;
const img = this.scene.add.image(x + k * off, y + (k % 2 ? 1 : -1), m ? 'mono-mini-back' : `mono-mini-${i}`)
.setDisplaySize(CW, CH).setDepth(DEPTH.hudText + k * 0.01).setAngle((k - (c.idxs.length - 1) / 2) * 4);
img.setInteractive({ useHandCursor: true });
img.on('pointerover', () => { img.y -= 6; this.onDeedHover?.(i, img.x, img.y); });
img.on('pointerout', () => { img.y += 6; this.onDeedOut?.(i); });
img.on('pointerdown', () => this.onDeedClick?.(i));
o.rail.push(img);
});
if (c.full) {
const span = CW + (c.idxs.length - 1) * off;
const g = this.scene.add.graphics().setDepth(DEPTH.hudText - 0.1);
g.lineStyle(2, 0xecd690, 0.95).strokeRoundedRect(x - CW / 2 - 3, y - CH / 2 - 4, span + 6, CH + 8, 5);
o.rail.push(g);
}
x += CW + (c.idxs.length - 1) * off + GAP;
});
}
renderLedger(state) {
if (!state) return;
const log = state.log;
const n = this.ledgerLines.length;
this.ledgerScroll = Math.min(this.ledgerScroll, Math.max(0, log.length - n));
const end = log.length - this.ledgerScroll;
const slice = log.slice(Math.max(0, end - n), end);
this.ledgerDots.clear();
this.ledgerLines.forEach((t, k) => {
const e = slice[k];
t.setText(e ? e.msg : '');
t.setColor(e?.seat !== null && e?.seat !== undefined ? darker(PLAYER_COLOR_HEX[e.seat]) : '#4a3a28');
if (e && e.seat !== null && e.seat !== undefined) {
this.ledgerDots.fillStyle(PLAYER_COLORS[e.seat], 1).fillCircle(LEDGER.x + 40, t.y + 8, 5);
}
});
this.ledgerHint.setText(this.ledgerScroll > 0 ? `▲ ${this.ledgerScroll} newer — scroll` : log.length > n ? 'scroll for more' : '');
}
setLedgerVisible(v) {
this.ledgerBg.setVisible(v); this.ledgerLines.forEach((t) => t.setVisible(v)); this.ledgerDots.setVisible(v); this.ledgerHint.setVisible(v);
}
anchor(seat) { return { ...this.plaques[seat].parts.anchor }; }
railPoint(seat) { const R = this.plaques[seat].parts.rail; return { x: R.x + R.w / 2, y: R.y + R.h / 2 }; }
}
// Ink a player's colour down a little so it reads on the cream page.
function darker(hex) {
const n = parseInt(hex.slice(1), 16);
const f = (v) => Math.round(v * 0.72);
return `#${[(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => f(v).toString(16).padStart(2, '0')).join('')}`;
}

View File

@ -0,0 +1,152 @@
// MonopolyLayout.js — every screen rect for the Boardwalk Hotel table.
// Phaser-free so tools/verifyMonopoly.js can check bounds and overlaps.
//
// ┌──────────── board 992² ────────────┐ ┌─ header ───────────────────────┐
// │ │ │ plaque 0 plaque 1 │
// │ │ │ plaque 2 plaque 3 │
// │ │ │ dice tray banker's tray │
// │ │ │ action panel ledger │
// └────────────────────────────────────┘ └─────────────────────────────────┘
import { BOARD_SIZE, CORNER_SIZE, SPACE_W, BAND_H, spaceGeometry } from './MonopolyData.js';
export const W = 1920, H = 1080;
export const BOARD = { x: 44, y: 44, w: BOARD_SIZE, h: BOARD_SIZE };
export const INNER = {
x: BOARD.x + CORNER_SIZE, y: BOARD.y + CORNER_SIZE,
w: BOARD_SIZE - 2 * CORNER_SIZE, h: BOARD_SIZE - 2 * CORNER_SIZE,
};
export const BOARD_CX = BOARD.x + BOARD.w / 2;
export const BOARD_CY = BOARD.y + BOARD.h / 2;
export const DEPTH = {
bg: 0, board: 5, owner: 7, build: 9, threat: 8, pawnShadow: 14, pawns: 15, hud: 20, hudText: 22,
tray: 30, bills: 44, popup: 50, tooltip: 72, banner: 90, end: 100,
};
// Right-hand column
export const RX = 1080;
export const RW = 820;
export const HEADER = { x: RX, y: 10, w: RW, h: 42 };
export const PLAQUE_W = 402, PLAQUE_H = 200;
export function plaqueRect(slot) {
const col = slot % 2, row = Math.floor(slot / 2);
return { x: RX + col * (PLAQUE_W + 16), y: 62 + row * (PLAQUE_H + 12), w: PLAQUE_W, h: PLAQUE_H };
}
export const TRAY = { x: RX, y: 488, w: 380, h: 238 };
export const BANK = { x: RX + 396, y: 488, w: 424, h: 238 };
export const ACTIONS = { x: RX, y: 742, w: 380, h: 294 };
export const LEDGER = { x: RX + 396, y: 742, w: 424, h: 294 };
// Inside a plaque
export function plaqueParts(slot) {
const P = plaqueRect(slot);
return {
P,
portrait: { x: P.x + 52, y: P.y + 56, r: 38 },
name: { x: P.x + 104, y: P.y + 16 },
cash: { x: P.x + 104, y: P.y + 40 },
worth: { x: P.x + 104, y: P.y + 80 },
chips: { x: P.x + P.w - 14, y: P.y + 16 }, // right-aligned status chips
rail: { x: P.x + 12, y: P.y + 110, w: P.w - 24, h: 80 },
anchor: { x: P.x + 180, y: P.y + 58 }, // where bills land
};
}
// Inside the tray / bank
export const TRAY_WALL = 18;
export const TRAY_FELT = { x: TRAY.x + TRAY_WALL, y: TRAY.y + TRAY_WALL + 22, w: TRAY.w - TRAY_WALL * 2, h: TRAY.h - TRAY_WALL * 2 - 22 };
export const TRAY_WORLD = { w: TRAY_FELT.w, h: TRAY_FELT.h };
export const DIE_SIZE = 50;
export function groundTray(u, v) { return { x: TRAY_FELT.x + u, y: TRAY_FELT.y + v, s: 1 }; }
export function diceRest() {
return [0.34, 0.66].map((u) => ({ u: TRAY_WORLD.w * u, v: TRAY_WORLD.h * 0.52 }));
}
// Dice are tossed in from the bottom edge (the player's side of the tray).
export function throwOrigin() { return { u: TRAY_WORLD.w * (0.3 + Math.random() * 0.4), v: TRAY_WORLD.h + 90, h: 140 }; }
export const BILL_W = 64, BILL_H = 32;
export function billSlot(i) { // the 7 compartments of the banker's tray
const x0 = BANK.x + 18, w = (BANK.w - 36) / 7;
return { x: x0 + i * w, y: BANK.y + 40, w, h: 92, cx: x0 + i * w + w / 2, cy: BANK.y + 40 + 46 };
}
export const BANK_ANCHOR = { x: BANK.x + BANK.w / 2, y: BANK.y + 86 };
export const HOUSE_RACK = { x: BANK.x + 18, y: BANK.y + 146, w: BANK.w - 36, h: 78 };
// Board centre furniture
export const CHANCE_DECK = { x: BOARD_CX - 190, y: BOARD_CY + 172, rot: -0.12 };
export const CC_DECK = { x: BOARD_CX + 190, y: BOARD_CY - 172, rot: 0.12 };
export const DECK_W = 96, DECK_H = 136;
export const POT = { x: BOARD_CX - 200, y: BOARD_CY - 190 };
export const THREAT_BOX = { x: BOARD_CX + 40, y: BOARD_CY + 120, w: 300, h: 118 };
export const MENU_BTN = { x: HEADER.x + HEADER.w - 186, y: HEADER.y + 21 };
export const LEAVE_BTN = { x: HEADER.x + HEADER.w - 60, y: HEADER.y + 21 };
// ── Space geometry ───────────────────────────────────────────────────────────
// Side 0 = bottom row (GO → Jail), 1 = left column, 2 = top row, 3 = right column.
export function sideOf(i) { return Math.floor(i / 10); }
// Rotation that makes a space's printing read for the player on that side:
// text "up" faces the middle of the board, where the colour band is.
export function spaceRot(i) { return [0, Math.PI / 2, Math.PI, -Math.PI / 2][sideOf(i)]; }
export function spaceRect(i) {
const g = spaceGeometry(i);
return { x: BOARD.x + g.x, y: BOARD.y + g.y, w: g.w, h: g.h, corner: !!g.isCorner, band: g.bandEdge };
}
export function spaceCenter(i) {
const r = spaceRect(i);
return { x: r.x + r.w / 2, y: r.y + r.h / 2 };
}
// Unit vector from a space toward the board middle (its "inner" direction).
export function inward(i) {
if (i % 10 === 0) { const c = spaceCenter(i); const dx = BOARD_CX - c.x, dy = BOARD_CY - c.y, l = Math.hypot(dx, dy); return { x: dx / l, y: dy / l }; }
return [{ x: 0, y: -1 }, { x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }][sideOf(i)];
}
// Point a distance `d` in from the space centre toward (+) or away from (−) the band.
export function along(i, d) {
const c = spaceCenter(i), n = inward(i);
return { x: c.x + n.x * d, y: c.y + n.y * d };
}
// Where pawns stand: the outer part of the space, clear of the colour band.
export function pawnSpot(i, k, n) {
if (i === 10) return jailSpot(k, n, false);
const base = i % 10 === 0 ? spaceCenter(i) : along(i, -16);
const offs = [[0, 0], [-15, 0, 15, 0], [-17, -9, 17, -9, 0, 13], [-15, -13, 15, -13, -15, 13, 15, 13]][Math.min(n, 4) - 1];
const ox = offs[k * 2] ?? 0, oy = offs[k * 2 + 1] ?? 0;
// rotate the offset with the side so pawns line up along the space
const side = sideOf(i);
const [rx, ry] = side === 1 || side === 3 ? [oy, ox] : [ox, oy];
return { x: base.x + rx, y: base.y + ry };
}
// Jail corner: inmates stand in the barred cell, visitors on the outer L.
export function jailSpot(k, n, inCell) {
const r = spaceRect(10);
if (inCell) {
const cx = r.x + r.w - 46, cy = r.y + 46;
const offs = [[0, 0], [-12, -8, 12, 8], [-14, -10, 14, -10, 0, 12], [-12, -12, 12, -12, -12, 12, 12, 12]][Math.min(n, 4) - 1];
return { x: cx + (offs[k * 2] ?? 0), y: cy + (offs[k * 2 + 1] ?? 0) };
}
const spots = [{ x: r.x + 22, y: r.y + 40 }, { x: r.x + 22, y: r.y + 84 }, { x: r.x + 52, y: r.y + r.h - 20 }, { x: r.x + 96, y: r.y + r.h - 20 }];
return spots[k % 4];
}
// Point on the colour band of a property (where buildings sit), k of n along it.
function longSide(i) { const r = spaceRect(i); return r.band === 'top' || r.band === 'bottom' ? r.h : r.w; }
export function bandSpot(i, k, n, spacing = 17) {
const c = along(i, longSide(i) / 2 - BAND_H / 2);
const off = (k - (n - 1) / 2) * spacing;
const side = sideOf(i);
return side === 0 || side === 2 ? { x: c.x + off, y: c.y } : { x: c.x, y: c.y + off };
}
// The owner flag sits on the outer edge of the space.
export function flagSpot(i) {
return along(i, -(longSide(i) / 2 - 5));
}
export function hudFurniture() {
const f = { board: BOARD, header: HEADER, tray: TRAY, bank: BANK, actions: ACTIONS, ledger: LEDGER };
for (let s = 0; s < 4; s++) f[`plaque${s}`] = plaqueRect(s);
return f;
}
export { CORNER_SIZE, SPACE_W, BAND_H };

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,124 @@
// MonopolySound.js — small Web Audio synths for the Boardwalk Hotel parlour.
// No audio files; silent without Web Audio or when muted.
//
// kaching(scene) brass cash-register bell + drawer rattle (a purchase)
// bell(scene) the GO bell — a bright two-note ding
// clang(scene) the cell door slamming (Go To Jail)
// gavel(scene, n) the auctioneer's gavel (n knocks)
// rustle(scene) a short paper-money rustle (bills changing hands)
// thunk(scene) a house / hotel set down on the board
// tap(scene, k) a pawn tapping a space (k = step number)
function ctxOf(scene) {
const sm = scene?.sound;
if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null;
return sm.context;
}
const noiseCache = new WeakMap();
function noise(ac) {
if (noiseCache.has(ac)) return noiseCache.get(ac);
const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 1.5), ac.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ac, buf);
return buf;
}
function out(scene, ac, gain) {
const sm = scene.sound;
const node = sm.masterVolumeNode ?? sm.destination ?? null;
const g = ac.createGain();
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
g.connect(node ?? ac.destination);
return g;
}
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1 } = {}) {
const o = ac.createOscillator(); o.type = type;
o.frequency.setValueAtTime(f, t0);
if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d);
const g = ac.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(a, t0 + 0.004);
g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03);
}
function burst(ac, dest, t0, { f = 2000, q = 1.5, d = 0.05, vol = 1, type = 'bandpass' } = {}) {
const n = ac.createBufferSource(); n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.value = f; bp.Q.value = q;
const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02);
}
const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } };
export function kaching(scene, vol = 0.12) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
for (let i = 0; i < 5; i++) burst(ac, dest, t + i * 0.022, { f: 3200 + i * 300, q: 3, d: 0.03, vol: 0.5 });
tone(ac, dest, t + 0.12, 2093, { type: 'sine', a: 0.6, d: 0.9 });
tone(ac, dest, t + 0.12, 3136, { type: 'sine', a: 0.25, d: 0.6 });
tone(ac, dest, t + 0.12, 5274, { type: 'sine', a: 0.08, d: 0.3 });
});
}
export function bell(scene, vol = 0.1) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
tone(ac, dest, t, 1568, { a: 0.7, d: 0.7 });
tone(ac, dest, t, 3920, { a: 0.12, d: 0.25 });
tone(ac, dest, t + 0.16, 2093, { a: 0.7, d: 1.0 });
tone(ac, dest, t + 0.16, 5232, { a: 0.1, d: 0.3 });
});
}
export function clang(scene, vol = 0.14) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
burst(ac, dest, t, { f: 900, q: 0.8, d: 0.12, vol: 1, type: 'lowpass' });
for (const [f, a, d] of [[220, 0.5, 0.9], [347, 0.35, 0.7], [523, 0.22, 0.6], [811, 0.12, 0.4]]) {
tone(ac, dest, t, f, { type: 'triangle', a, d, glide: 0.985 });
}
// the bolt
burst(ac, dest, t + 0.32, { f: 2400, q: 4, d: 0.04, vol: 0.7 });
});
}
export function gavel(scene, n = 1, vol = 0.14) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
for (let i = 0; i < n; i++) {
const t0 = t + i * 0.32;
tone(ac, dest, t0, 180, { type: 'sine', a: 0.9, d: 0.16, glide: 0.6 });
burst(ac, dest, t0, { f: 1400, q: 1.2, d: 0.05, vol: 0.8 });
}
});
}
export function rustle(scene, vol = 0.06) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
for (let i = 0; i < 4; i++) burst(ac, dest, t + i * 0.035 + Math.random() * 0.01, { f: 4200 + Math.random() * 1800, q: 0.7, d: 0.06, vol: 0.6 });
});
}
export function thunk(scene, vol = 0.1) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
tone(ac, dest, t, 340, { type: 'triangle', a: 0.7, d: 0.08, glide: 0.6 });
burst(ac, dest, t, { f: 1800, q: 2, d: 0.03, vol: 0.5 });
});
}
export function tap(scene, k = 0, vol = 0.07) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
const f = 760 + (k % 4) * 35;
tone(ac, dest, t, f, { type: 'triangle', a: 0.55, d: 0.05, glide: 0.7 });
burst(ac, dest, t, { f: f * 2.6, q: 2, d: 0.025, vol: 0.4 });
});
}

View File

@ -0,0 +1,850 @@
// MonopolyTrade.js — the trading screens, mixed into MonopolyGame:
// • the drag-and-drop trade builder (your deeds | give/get lanes + cash | theirs)
// • incoming AI proposals with Accept / Counter / Decline
// • a brief read-only card for completed AI-to-AI deals
// Trading is open on your own turn, before or after rolling. Mortgaged deeds
// change hands with 10% interest to the bank (see MonopolyLogic.tradeInterest).
import * as Phaser from 'phaser';
import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { SPACES, PURCHASABLE } from './MonopolyData.js';
import { isTradeable, validateTrade, applyTrade, tradeInterest, mortgageInterest } from './MonopolyLogic.js';
import { evaluateTrade, buildAiTradeOffer } from './MonopolyAI.js';
import { DEPTH } from './MonopolyLayout.js';
import { MODAL_W, MODAL_H } from './MonopolyDeed.js';
import { frame } from './MonopolyDialogs.js';
import { DISPLAY, bandColorNum } from './MonopolyArt.js';
import { kaching } from './MonopolySound.js';
export class TradeMixin {
// ── Trade Modal ────────────────────────────────────────────────────────────
canInitiateTrade() {
const gs = this.gs;
return gs.players.some(pl => pl.seat !== this.humanSeat && pl.active && !pl.bankrupt &&
PURCHASABLE.some(i => gs.board[i]?.owner === pl.seat));
}
// Band color matching buildPropertyCardContainer / drawBoardSpace
tradeBandColor(idx) { return bandColorNum(idx); }
// ── AI-initiated trades ──────────────────────────────────────────────────────
// Called during an AI seat's endturn. Proposes to the human (rate-limited to once
// every other of this AI's own turns) then completes up to 5 trades with other AIs.
async aiAttemptTrades(seat) {
const gs = this.gs;
if (!gs || gs.phase !== 'endturn' || gs.current !== seat) return;
const me = gs.players[seat];
if (!me || !me.active || me.bankrupt) return;
// Tick this AI's human-proposal cooldown down once per its own turn.
if (this.humanTradeCooldown[seat] > 0) this.humanTradeCooldown[seat]--;
const skill = this.skillBySeat[seat] ?? 3;
// 1. Propose to the human, if off cooldown.
const human = this.gs.players[this.humanSeat];
if (human && human.active && !human.bankrupt && (this.humanTradeCooldown[seat] ?? 0) <= 0) {
const offer = buildAiTradeOffer(this.gs, seat, this.humanSeat, skill,
{ targetHuman: true, targetSkill: this.skillBySeat[this.humanSeat] ?? 3 });
if (offer && validateTrade(this.gs, offer).ok) {
this.humanTradeCooldown[seat] = 2; // blocks this AI's next own turn
await this.showIncomingTradeProposal(seat, offer);
}
}
// 2. Trade with other AI opponents — up to 5 completed deals this turn.
let done = 0, guard = 0;
while (done < 5 && guard++ < 12) {
const others = this.gs.players
.filter(pl => pl.seat !== seat && pl.seat !== this.humanSeat && pl.active && !pl.bankrupt)
.map(pl => pl.seat);
Phaser.Utils.Array.Shuffle(others);
let made = false;
for (const tSeat of others) {
const tSkill = this.skillBySeat[tSeat] ?? 3;
const offer = buildAiTradeOffer(this.gs, seat, tSeat, skill, { targetSkill: tSkill });
if (!offer || !validateTrade(this.gs, offer).ok) continue;
if (!evaluateTrade(this.gs, tSeat, offer, tSkill).accept) continue;
this.gs = applyTrade(this.gs, offer);
this.render();
await this.flashAiTrade(offer);
done++; made = true;
if (done >= 5) break;
}
if (!made) break;
}
}
// Shared summary layout for both the incoming-proposal popup and the AI-AI flash.
// Returns an array of created display objects for the caller to destroy.
buildTradeSummaryContents(offer, geo, topLabel, bottomLabel) {
const objs = [];
const cardScale = 0.46;
const cw = MODAL_W * cardScale, gap = 24, rowH = MODAL_H * cardScale;
const midX = geo.x + geo.w / 2;
const drawRow = (label, props, cash, labelY) => {
objs.push(this.add.text(geo.x + 30, labelY, label, {
fontFamily:DISPLAY, fontSize:'18px', color:COLORS.goldHex,
}).setOrigin(0, 0).setDepth(DEPTH.popup + 1));
const n = props.length + (cash > 0 ? 1 : 0);
const totalW = n > 0 ? n * cw + (n - 1) * gap : 0;
let x = midX - totalW / 2 + cw / 2;
const cy = labelY + 30 + rowH / 2;
for (const idx of props) {
const card = this.buildPropertyCardContainer(idx);
card.setPosition(x, cy).setScale(cardScale).setDepth(DEPTH.popup + 1);
objs.push(card);
x += cw + gap;
}
if (cash > 0) {
const badge = this.add.container(x, cy).setDepth(DEPTH.popup + 1);
const g = this.add.graphics();
g.fillStyle(0x14110a, 1); g.fillRoundedRect(-cw/2, -42, cw, 84, 10);
g.lineStyle(2, 0x7fb87f, 1); g.strokeRoundedRect(-cw/2, -42, cw, 84, 10);
badge.add(g);
badge.add(this.add.text(0, 0, `$${cash.toLocaleString()}`, {
fontFamily:DISPLAY, fontSize:'26px', color:'#7fdd9f',
}).setOrigin(0.5));
objs.push(badge);
}
if (props.length === 0 && cash <= 0) {
objs.push(this.add.text(midX, cy, '— nothing —', {
fontFamily:'"Julius Sans One"', fontSize:'16px', color:COLORS.mutedHex,
}).setOrigin(0.5).setDepth(DEPTH.popup + 1));
}
};
const row1Y = geo.y + 4;
drawRow(topLabel, offer.giveProps ?? [], offer.giveCash ?? 0, row1Y);
const divY = row1Y + 30 + rowH + 22;
const dg = this.add.graphics().setDepth(DEPTH.popup + 1);
dg.lineStyle(1, COLORS.accent, 0.5);
dg.beginPath(); dg.moveTo(geo.x + 30, divY); dg.lineTo(geo.x + geo.w - 30, divY); dg.strokePath();
objs.push(dg);
drawRow(bottomLabel, offer.getProps ?? [], offer.getCash ?? 0, divY + 14);
const fee = tradeInterest(this.gs, offer);
if (fee.from || fee.to) {
const bits = [];
if (fee.to) bits.push(`${this.gs.players[offer.toSeat].name} pays $${fee.to}`);
if (fee.from) bits.push(`${this.gs.players[offer.fromSeat].name} pays $${fee.from}`);
objs.push(this.add.text(geo.x + geo.w / 2, divY + 14 + 30 + rowH + 24, `Mortgaged deeds change hands with 10% interest to the bank: ${bits.join(', ')}.`, {
fontFamily:'"Julius Sans One"', fontSize:'14px', color:'#ffc46a',
}).setOrigin(0.5, 0).setDepth(DEPTH.popup + 1));
}
return objs;
}
// Incoming proposal from an AI to the human. Resolves when the human Accepts,
// Declines, or finishes a Counter-offer.
showIncomingTradeProposal(fromSeat, offer) {
return new Promise(resolve => {
this._tradeResolve = resolve;
this.tradeSummaryOpen = true;
this.hidePortraits();
const fromName = this.gs.players[fromSeat].name;
const objs = [];
const overlay = this.add.rectangle(GAME_WIDTH/2, GAME_HEIGHT/2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62)
.setDepth(DEPTH.popup - 1).setInteractive();
objs.push(overlay);
const PW = 1180, PH = 760;
const PX = GAME_WIDTH/2 - PW/2, PY = GAME_HEIGHT/2 - PH/2;
objs.push(frame(this, PX, PY, PW, PH, DEPTH.popup));
objs.push(this.add.text(GAME_WIDTH/2, PY + 22, `${fromName} proposes a trade`, {
fontFamily:DISPLAY, fontSize:'26px', color:COLORS.goldHex,
}).setOrigin(0.5).setDepth(DEPTH.popup + 1));
objs.push(...this.buildTradeSummaryContents(offer,
{ x: PX, y: PY + 58, w: PW }, `${fromName} gives you`, `You give ${fromName}`));
const finish = (result) => {
objs.forEach(o => { try { o.destroy(); } catch {} });
this.tradeSummaryOpen = false;
if (result === 'counter') {
this.openCounterModal(fromSeat, offer); // resolves _tradeResolve on close
} else {
this.showPortraits();
const r = this._tradeResolve; this._tradeResolve = null;
if (r) r();
}
};
const by = PY + PH - 54;
const accept = new Button(this, GAME_WIDTH/2 - 230, by, 'Accept', () => {
if (validateTrade(this.gs, offer).ok) {
this.gs = applyTrade(this.gs, offer);
kaching(this);
this.render();
}
finish('accept');
}, { width: 200, height: 50, fontSize: 22 });
accept.setDepth(DEPTH.popup + 2); objs.push(accept);
const counter = new Button(this, GAME_WIDTH/2, by, 'Counter-offer', () => finish('counter'),
{ width: 230, height: 50, fontSize: 20, variant:'ghost' });
counter.setDepth(DEPTH.popup + 2); objs.push(counter);
const decline = new Button(this, GAME_WIDTH/2 + 230, by, 'Decline', () => finish('decline'),
{ width: 200, height: 50, fontSize: 22, variant:'ghost' });
decline.setDepth(DEPTH.popup + 2); objs.push(decline);
});
}
// Brief read-only summary of a completed AI-vs-AI trade.
flashAiTrade(offer) {
return new Promise(resolve => {
this.tradeSummaryOpen = true;
this.hidePortraits();
const fromName = this.gs.players[offer.fromSeat].name;
const toName = this.gs.players[offer.toSeat].name;
const objs = [];
const overlay = this.add.rectangle(GAME_WIDTH/2, GAME_HEIGHT/2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55)
.setDepth(DEPTH.popup - 1).setInteractive();
objs.push(overlay);
const PW = 1180, PH = 760;
const PX = GAME_WIDTH/2 - PW/2, PY = GAME_HEIGHT/2 - PH/2;
objs.push(frame(this, PX, PY, PW, PH, DEPTH.popup));
objs.push(this.add.text(GAME_WIDTH/2, PY + 22, `${fromName} ⇄ ${toName} — Trade`, {
fontFamily:DISPLAY, fontSize:'26px', color:COLORS.goldHex,
}).setOrigin(0.5).setDepth(DEPTH.popup + 1));
objs.push(...this.buildTradeSummaryContents(offer,
{ x: PX, y: PY + 58, w: PW }, `${fromName} gives`, `${toName} gives`));
objs.push(this.add.text(GAME_WIDTH/2, PY + PH - 36, 'ACCEPTED', {
fontFamily:DISPLAY, fontSize:'28px', color:'#7fdd9f',
}).setOrigin(0.5).setDepth(DEPTH.popup + 1));
this.time.delayedCall(1500, () => {
objs.forEach(o => { try { o.destroy(); } catch {} });
this.tradeSummaryOpen = false;
this.showPortraits();
resolve();
});
});
}
// Open the existing drag-drop trade builder in "counter" mode, seeded with the AI's
// offer reversed to the human's perspective and locked to that opponent.
openCounterModal(fromSeat, offer) {
const seed = {
giveProps: [...(offer.getProps ?? [])], // human gives what the AI requested
getProps: [...(offer.giveProps ?? [])], // human gets what the AI offered
giveCash: offer.getCash ?? 0,
getCash: offer.giveCash ?? 0,
};
this.showTradeModal({ counter: true, counterFrom: fromSeat, seedOffer: seed });
}
showTradeModal(opts = {}) {
if (this.tradeMenuOpen) return;
if (!opts.counter && this.busy) return;
if (!opts.counter && (this.gs.current !== this.humanSeat || !['preroll', 'endturn'].includes(this.gs.phase))) return;
this.tradeCounterMode = !!opts.counter;
this.tradeCounterFrom = opts.counterFrom ?? null;
this.tradeMenuOpen = true;
this.tradeMenuObjs = [];
this.tradeLaneObjs = [];
this.tradeRightObjs = [];
this.tradeMineCards = {};
this.tradeOppCards = {};
this.tradeOffer = opts.seedOffer
? { giveProps:[...opts.seedOffer.giveProps], getProps:[...opts.seedOffer.getProps],
giveCash: opts.seedOffer.giveCash, getCash: opts.seedOffer.getCash }
: { giveProps: [], getProps: [], giveCash: 0, getCash: 0 };
this.tradeDragGhost = null;
this._tradeDidDrag = false;
// DOM video portraits render above the canvas — hide them behind the modal
this.hidePortraits();
const gs = this.gs;
if (this.tradeCounterMode && this.tradeCounterFrom !== null) {
this.tradeCounterparty = this.tradeCounterFrom; // locked to the proposing AI
} else {
// Default counterparty: first active opponent owning a property, else first opponent
const opps = gs.players.filter(pl => pl.seat !== this.humanSeat && pl.active && !pl.bankrupt);
this.tradeCounterparty = (opps.find(pl =>
PURCHASABLE.some(i => gs.board[i]?.owner === pl.seat)) ?? opps[0])?.seat ?? null;
}
// Geometry
const PW = 1600, PH = 860;
const PX = GAME_WIDTH/2 - PW/2, PY = GAME_HEIGHT/2 - PH/2;
this._tradeGeo = { PW, PH, PX, PY,
LX: PX + 24, LW: 430,
CX: PX + 474, CW: 600,
RX: PX + 1094, RW: 482,
};
// Overlay (swallows background clicks)
const overlay = this.add.rectangle(GAME_WIDTH/2, GAME_HEIGHT/2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.62)
.setDepth(DEPTH.popup - 1).setInteractive();
this.tradeMenuObjs.push(overlay);
// Panel
this.tradeMenuObjs.push(frame(this, PX, PY, PW, PH, DEPTH.popup));
const titleTxt = this.tradeCounterMode && this.tradeCounterparty !== null
? `Counter-offer to ${gs.players[this.tradeCounterparty].name}`
: 'Propose a Trade';
this.tradeMenuObjs.push(this.add.text(GAME_WIDTH/2, PY + 24, titleTxt, {
fontFamily:DISPLAY, fontSize:'26px', color:COLORS.goldHex,
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
this.buildTradeLeftColumn();
this.buildTradeCenterColumn();
this.renderRightColumn();
// Drag handlers (registered once per open)
this._onTradeDragStart = (pointer, obj) => {
if (!obj || obj._spaceIdx === undefined) return;
this.tradeDragGhost = obj; this._tradeDidDrag = true; obj._dropped = false;
this.stopDragHints();
this.clearTradeHoverCard();
this.showDropHint(obj._side);
obj._homeX = obj.x; obj._homeY = obj.y;
obj.setDepth(DEPTH.popup + 12);
};
this._onTradeDrag = (pointer, obj, dragX, dragY) => {
if (obj !== this.tradeDragGhost) return;
obj.x = dragX; obj.y = dragY;
};
// Native drop — fires only when released over a lane drop zone. Route by whose
// card it is (your card → give, their card → get) so it always lands correctly.
this._onTradeDrop = (pointer, obj, zone) => {
if (obj !== this.tradeDragGhost) return;
const type = zone?.getData?.('laneType');
if (type !== 'give' && type !== 'get') return;
obj._dropped = true;
this.addTradeProp(obj._spaceIdx, obj._side === 'mine' ? 'give' : 'get');
};
this._onTradeDragEnd = (pointer, obj) => {
if (obj !== this.tradeDragGhost) return;
obj.x = obj._homeX; obj.y = obj._homeY; // snap home; drop already handled above
obj.setDepth(DEPTH.popup + 1);
this.tradeDragGhost = null;
this.clearDropHint();
this.refreshDragHints(); // resume pulsing if nothing was dropped
};
this.input.on('dragstart', this._onTradeDragStart);
this.input.on('drag', this._onTradeDrag);
this.input.on('drop', this._onTradeDrop);
this.input.on('dragend', this._onTradeDragEnd);
this.renderTradeOffer();
this.renderTradeCash();
}
buildTradeLeftColumn() {
const { LX, LW, PY } = this._tradeGeo;
const gs = this.gs;
const p = gs.players[this.humanSeat];
this.tradeMenuObjs.push(this.add.text(LX + LW/2, PY + 64, 'Your Properties', {
fontFamily:DISPLAY, fontSize:'18px', color:COLORS.textHex,
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
this.tradeMenuObjs.push(this.add.text(LX + LW/2, PY + 88, `Cash: $${p.cash.toLocaleString()}`, {
fontFamily:'"Julius Sans One"', fontSize:'15px', color:'#7fb87f',
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
const owned = PURCHASABLE.filter(i => gs.board[i]?.owner === this.humanSeat);
owned.forEach((idx, i) => {
const col = i % 3, row = Math.floor(i / 3);
const cx = LX + 70 + col * 140;
const cy = PY + 130 + row * 78;
const card = this.buildTradeMiniCard(idx, 'mine');
card.setPosition(cx, cy);
this.tradeMineCards[idx] = card;
this.tradeMenuObjs.push(card);
});
if (owned.length === 0) {
this.tradeMenuObjs.push(this.add.text(LX + LW/2, PY + 150, 'You own no properties.\nYou can still offer cash.', {
fontFamily:'"Julius Sans One"', fontSize:'13px', color:COLORS.mutedHex, align:'center',
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
}
}
buildTradeCenterColumn() {
const { CX, CW, PY } = this._tradeGeo;
const midX = CX + CW/2;
// Give lane
this.tradeMenuObjs.push(this.add.text(midX, PY + 70, 'You give →', {
fontFamily:DISPLAY, fontSize:'16px', color:COLORS.goldHex,
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
this.tradeGiveLane = { x: CX + 10, y: PY + 90, w: CW - 20, h: 86 };
// Get lane
this.tradeMenuObjs.push(this.add.text(midX, PY + 192, '← You get', {
fontFamily:DISPLAY, fontSize:'16px', color:COLORS.goldHex,
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
this.tradeGetLane = { x: CX + 10, y: PY + 212, w: CW - 20, h: 86 };
const laneG = this.add.graphics().setDepth(DEPTH.popup);
for (const lane of [this.tradeGiveLane, this.tradeGetLane]) {
laneG.fillStyle(0x14110a, 1);
laneG.fillRoundedRect(lane.x, lane.y, lane.w, lane.h, 8);
laneG.lineStyle(1, COLORS.accent, 0.6);
laneG.strokeRoundedRect(lane.x, lane.y, lane.w, lane.h, 8);
}
this.tradeMenuObjs.push(laneG);
// Real Phaser drop zones over each lane. Native drop uses Phaser's own
// render-consistent hit testing (same pipeline as normal clicks), so the
// droppable area matches exactly what's drawn. add.zone(x,y,...) takes the
// CENTER; setRectangleDropZone centers the hit area. A small pad eases aiming.
const mkZone = (lane, type) => {
const zw = lane.w + 16, zh = lane.h + 16;
const z = this.add.zone(lane.x + lane.w/2, lane.y + lane.h/2, zw, zh)
.setRectangleDropZone(zw, zh)
.setDepth(DEPTH.popup + 2);
z.setData('laneType', type);
this.tradeMenuObjs.push(z);
return z;
};
this.tradeGiveZone = mkZone(this.tradeGiveLane, 'give');
this.tradeGetZone = mkZone(this.tradeGetLane, 'get');
// Cash steppers
this.buildCashStepper('give', PY + 326);
this.buildCashStepper('get', PY + 396);
// Propose / Cancel
const proposeLabel = this.tradeCounterMode ? 'Send Counter-offer' : 'Propose Trade';
const proposeBtn = new Button(this, midX, PY + 476, proposeLabel, () => this.onProposeTrade(),
{ width: 260, height: 52, fontSize: 22 });
proposeBtn.setDepth(DEPTH.popup+2);
this.tradeMenuObjs.push(proposeBtn);
const cancelBtn = new Button(this, midX, PY + 540, 'Cancel', () => this.closeTradeModal(),
{ width: 180, height: 44, fontSize: 18, variant:'ghost' });
cancelBtn.setDepth(DEPTH.popup+2);
this.tradeMenuObjs.push(cancelBtn);
this.tradeFeedbackText = this.add.text(midX, PY + 600, 'Build your offer, then propose.', {
fontFamily:'"Julius Sans One"', fontSize:'15px', color:COLORS.mutedHex,
align:'center', wordWrap:{ width: CW - 20 },
}).setOrigin(0.5, 0).setDepth(DEPTH.popup+1);
this.tradeMenuObjs.push(this.tradeFeedbackText);
}
buildCashStepper(side, y) {
const { CX, CW } = this._tradeGeo;
const midX = CX + CW/2;
const label = side === 'give' ? 'You add cash' : 'You request cash';
this.tradeMenuObjs.push(this.add.text(CX + 10, y - 18, label, {
fontFamily:'"Julius Sans One"', fontSize:'14px', color:COLORS.textHex,
}).setOrigin(0, 0.5).setDepth(DEPTH.popup+1));
const valText = this.add.text(midX, y + 8, '$0', {
fontFamily:DISPLAY, fontSize:'20px', color:COLORS.goldHex,
}).setOrigin(0.5).setDepth(DEPTH.popup+1);
this.tradeMenuObjs.push(valText);
if (side === 'give') this.tradeGiveCashText = valText; else this.tradeGetCashText = valText;
const deltas = [[-50,'−50'], [-10,'−10'], [+10,'+10'], [+50,'+50']];
const bw = 64, gap = 8, totalW = deltas.length * bw + (deltas.length - 1) * gap;
let bx = midX - totalW/2 + bw/2;
const rowY = y + 36;
for (const [delta, lbl] of deltas) {
const b = new Button(this, bx, rowY, lbl, () => this.adjustTradeCash(side, delta),
{ width: bw, height: 30, fontSize: 14, variant:'ghost' });
b.setDepth(DEPTH.popup+2);
this.tradeMenuObjs.push(b);
bx += bw + gap;
}
}
adjustTradeCash(side, delta) {
if (!this.tradeOffer) return;
if (side === 'give') {
const max = this.gs.players[this.humanSeat].cash;
this.tradeOffer.giveCash = Phaser.Math.Clamp(this.tradeOffer.giveCash + delta, 0, max);
} else {
const cp = this.tradeCounterparty;
const max = cp !== null ? this.gs.players[cp].cash : 0;
this.tradeOffer.getCash = Phaser.Math.Clamp(this.tradeOffer.getCash + delta, 0, max);
}
this.renderTradeCash();
}
renderTradeCash() {
if (this.tradeGiveCashText) this.tradeGiveCashText.setText(`$${this.tradeOffer.giveCash}`);
if (this.tradeGetCashText) this.tradeGetCashText.setText(`$${this.tradeOffer.getCash}`);
this.refreshDragHints();
}
renderRightColumn() {
(this.tradeRightObjs || []).forEach(o => { try { o.destroy(); } catch {} });
this.tradeRightObjs = [];
this.tradeOppCards = {};
const { RX, RW, PY } = this._tradeGeo;
const gs = this.gs;
const opps = this.tradeCounterMode
? gs.players.filter(pl => pl.seat === this.tradeCounterparty)
: gs.players.filter(pl => pl.seat !== this.humanSeat && pl.active && !pl.bankrupt);
// Opponent tabs
const tabW = Math.min(150, Math.floor((RW - (opps.length - 1) * 8) / Math.max(1, opps.length)));
let tx = RX + tabW/2;
for (const pl of opps) {
const selected = pl.seat === this.tradeCounterparty;
const b = new Button(this, tx, PY + 66, pl.name.length > 10 ? pl.name.slice(0,9)+'…' : pl.name,
() => this.selectTradeCounterparty(pl.seat),
{ width: tabW, height: 36, fontSize: 14, variant: selected ? 'solid' : 'ghost' });
b.setDepth(DEPTH.popup+2);
this.tradeRightObjs.push(b);
tx += tabW + 8;
}
const cp = this.tradeCounterparty;
if (cp === null) return;
this.tradeRightObjs.push(this.add.text(RX + RW/2, PY + 96, `Cash: $${gs.players[cp].cash.toLocaleString()}`, {
fontFamily:'"Julius Sans One"', fontSize:'15px', color:'#7fb87f',
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
const owned = PURCHASABLE.filter(i => gs.board[i]?.owner === cp);
owned.forEach((idx, i) => {
const col = i % 3, row = Math.floor(i / 3);
const cx = RX + 70 + col * 140;
const cy = PY + 138 + row * 78;
const card = this.buildTradeMiniCard(idx, 'opp');
card.setPosition(cx, cy);
this.tradeOppCards[idx] = card;
this.tradeRightObjs.push(card);
});
if (owned.length === 0) {
this.tradeRightObjs.push(this.add.text(RX + RW/2, PY + 150, 'They own no properties.', {
fontFamily:'"Julius Sans One"', fontSize:'13px', color:COLORS.mutedHex,
}).setOrigin(0.5).setDepth(DEPTH.popup+1));
}
this.refreshMiniStates();
}
selectTradeCounterparty(seat) {
if (this.tradeCounterMode) return; // locked to the proposing AI
if (seat === this.tradeCounterparty) return;
this.tradeCounterparty = seat;
// getProps/getCash referenced the previous opponent — reset them
this.tradeOffer.getProps = [];
this.tradeOffer.getCash = 0;
this.renderRightColumn();
this.renderTradeOffer();
this.renderTradeCash();
this.setTradeFeedback('Build your offer, then propose.', 'muted');
}
buildTradeMiniCard(idx, side) {
const sp = SPACES[idx];
const own = this.gs.board[idx];
const MW = 128, MH = 66;
const c = this.add.container(0, 0).setDepth(DEPTH.popup + 1);
const g = this.add.graphics();
g.fillStyle(0xFFF8E7, 1);
g.fillRoundedRect(-MW/2, -MH/2, MW, MH, 6);
g.lineStyle(1, 0x2c1810, 1);
g.strokeRoundedRect(-MW/2, -MH/2, MW, MH, 6);
g.fillStyle(this.tradeBandColor(idx), 1);
g.fillRect(-MW/2, -MH/2, MW, 14);
c.add(g);
c.add(this.add.text(0, -MH/2 + 18, sp.name, {
fontFamily:'"Julius Sans One"', fontSize:'10px', color:'#1a1208',
align:'center', wordWrap:{ width: MW - 10, useAdvancedWrap:true },
}).setOrigin(0.5, 0));
const sub = (sp.type === 'property' || sp.type === 'railroad' || sp.type === 'utility') ? `$${sp.price}` : '';
if (sub) {
c.add(this.add.text(0, MH/2 - 14, sub, {
fontFamily:'"Julius Sans One"', fontSize:'9px', color:'#555544',
}).setOrigin(0.5, 0));
}
if (own.mortgaged) {
const mg = this.add.graphics();
mg.fillStyle(0x888888, 0.45);
mg.fillRoundedRect(-MW/2, -MH/2, MW, MH, 6);
c.add(mg);
c.add(this.add.text(0, 4, `MORTGAGED · +$${mortgageInterest(this.gs, idx)}`, {
fontFamily:'"Julius Sans One"', fontSize:'9px', color:'#cccccc',
}).setOrigin(0.5));
}
const tradeable = isTradeable(this.gs, idx);
if (tradeable) {
const og = this.add.graphics();
og.lineStyle(2, 0x44cc66, 1);
og.strokeRoundedRect(-MW/2, -MH/2, MW, MH, 6);
c.add(og);
} else {
c.setAlpha(0.45);
}
c._spaceIdx = idx; c._side = side; c._tradeable = tradeable;
c._hw = MW/2; c._hh = MH/2; // half-extents for drop-zone overlap testing
// NB: do NOT call setSize() — on a Container it sets displayOrigin = size/2,
// which Phaser's hit test adds to the local point and shifts the hit area up/left.
// NB: the 3rd setInteractive arg is `dropZone` (boolean). Passing a config object
// there made every card a drop zone and broke drag-drop — keep it to 2 args.
c.setInteractive(new Phaser.Geom.Rectangle(-MW/2, -MH/2, MW, MH), Phaser.Geom.Rectangle.Contains);
if (c.input) c.input.cursor = tradeable ? 'grab' : 'default';
c.on('pointerover', () => { if (!this.tradeDragGhost) this.showTradeHoverCard(idx, c.x, c.y); });
c.on('pointerout', () => this.clearTradeHoverCard());
if (tradeable) {
this.input.setDraggable(c, true);
c.on('pointerdown', () => { this._tradeDidDrag = false; });
c.on('pointerup', () => { if (!this._tradeDidDrag) this.toggleTradeProp(idx, side); });
}
return c;
}
showDropHint(side) {
this.clearDropHint();
const lane = side === 'mine' ? this.tradeGiveLane
: side === 'opp' ? this.tradeGetLane : null;
if (!lane) return;
const g = this.add.graphics().setDepth(DEPTH.popup + 3);
g.fillStyle(0x44cc66, 0.22);
g.fillRoundedRect(lane.x, lane.y, lane.w, lane.h, 8);
g.lineStyle(4, 0x66ff88, 1);
g.strokeRoundedRect(lane.x, lane.y, lane.w, lane.h, 8);
const label = this.add.text(lane.x + lane.w/2, lane.y + lane.h/2,
side === 'mine' ? '⬇ DROP HERE TO GIVE' : '⬇ DROP HERE TO GET', {
fontFamily:DISPLAY, fontSize:'22px', color:'#d6ffe0',
stroke:'#0a3a18', strokeThickness:4,
}).setOrigin(0.5).setDepth(DEPTH.popup + 4);
this.tradeDropHintObjs = [g, label];
this.tradeDropHintTween = this.tweens.add({
targets: [g, label],
alpha: { from: 1, to: 0.45 },
duration: 420, yoyo: true, repeat: -1, ease: 'Sine.easeInOut',
});
}
clearDropHint() {
if (this.tradeDropHintTween) { try { this.tradeDropHintTween.stop(); } catch {} this.tradeDropHintTween = null; }
(this.tradeDropHintObjs || []).forEach(o => { try { o.destroy(); } catch {} });
this.tradeDropHintObjs = [];
}
toggleTradeProp(idx, side) {
const lane = side === 'mine' ? 'give' : 'get';
const arr = lane === 'give' ? this.tradeOffer.giveProps : this.tradeOffer.getProps;
if (arr.includes(idx)) this.removeTradeProp(idx, lane);
else this.addTradeProp(idx, lane);
}
addTradeProp(idx, lane) {
const arr = lane === 'give' ? this.tradeOffer.giveProps : this.tradeOffer.getProps;
if (!arr.includes(idx)) { arr.push(idx); this.renderTradeOffer(); }
}
removeTradeProp(idx, lane) {
if (lane === 'give') this.tradeOffer.giveProps = this.tradeOffer.giveProps.filter(i => i !== idx);
else this.tradeOffer.getProps = this.tradeOffer.getProps.filter(i => i !== idx);
this.renderTradeOffer();
}
renderTradeOffer() {
(this.tradeLaneObjs || []).forEach(o => { try { o.destroy(); } catch {} });
this.tradeLaneObjs = [];
const layoutChips = (idxs, lane) => {
const CW = 178, CH = 30, gap = 8, perRow = Math.max(1, Math.floor(lane.w / (CW + gap)));
idxs.forEach((idx, i) => {
const col = i % perRow, row = Math.floor(i / perRow);
const cx = lane.x + 12 + CW/2 + col * (CW + gap);
const cy = lane.y + 20 + row * (CH + 6);
this.tradeLaneObjs.push(this.buildTradeChip(idx, cx, cy,
lane === this.tradeGiveLane ? 'give' : 'get', CW, CH));
});
};
layoutChips(this.tradeOffer.giveProps, this.tradeGiveLane);
layoutChips(this.tradeOffer.getProps, this.tradeGetLane);
this.refreshMiniStates();
this.refreshDragHints();
}
buildTradeChip(idx, cx, cy, lane, CW, CH) {
const sp = SPACES[idx];
const c = this.add.container(cx, cy).setDepth(DEPTH.popup + 2);
const g = this.add.graphics();
g.fillStyle(0x2a2418, 1);
g.fillRoundedRect(-CW/2, -CH/2, CW, CH, 6);
g.lineStyle(2, this.tradeBandColor(idx), 1);
g.strokeRoundedRect(-CW/2, -CH/2, CW, CH, 6);
c.add(g);
c.add(this.add.text(-CW/2 + 8, 0, sp.name, {
fontFamily:'"Julius Sans One"', fontSize:'11px', color:'#FFF8E7',
wordWrap:{ width: CW - 34 },
}).setOrigin(0, 0.5));
c.add(this.add.text(CW/2 - 12, 0, '✕', {
fontFamily:DISPLAY, fontSize:'14px', color:'#ff8888',
}).setOrigin(0.5));
c.setInteractive(new Phaser.Geom.Rectangle(-CW/2, -CH/2, CW, CH), Phaser.Geom.Rectangle.Contains);
if (c.input) c.input.cursor = 'pointer';
c.on('pointerup', () => this.removeTradeProp(idx, lane));
return c;
}
refreshMiniStates() {
const mark = (map, arr) => {
for (const [idx, card] of Object.entries(map)) {
if (!card || !card.active) continue;
const inOffer = arr.includes(Number(idx));
if (!card._tradeable) { card.setAlpha(0.45); continue; }
card.setAlpha(inOffer ? 0.35 : 1);
}
};
mark(this.tradeMineCards, this.tradeOffer.giveProps);
mark(this.tradeOppCards, this.tradeOffer.getProps);
}
isTradeOfferEmpty() {
const o = this.tradeOffer;
return !o || (o.giveProps.length === 0 && o.getProps.length === 0 && o.giveCash === 0 && o.getCash === 0);
}
// While the offer is empty, gently pulse the draggable cards so it's obvious they
// can be picked up. Stops the moment anything is offered or requested.
startDragHints() {
this.stopDragHints();
if (!this.tradeMenuOpen) return;
const cards = [
...Object.values(this.tradeMineCards || {}),
...Object.values(this.tradeOppCards || {}),
].filter(c => c && c.active && c._tradeable);
if (!cards.length) return;
cards.forEach(c => c.setScale(1));
this._dragHintCards = cards;
this._dragHintTween = this.tweens.add({
targets: cards,
scaleX: 1.07, scaleY: 1.07,
duration: 640, yoyo: true, repeat: -1, ease: 'Sine.easeInOut',
});
}
stopDragHints() {
if (this._dragHintTween) { try { this._dragHintTween.stop(); } catch {} this._dragHintTween = null; }
(this._dragHintCards || []).forEach(c => { if (c && c.active) c.setScale(1); });
this._dragHintCards = [];
}
refreshDragHints() {
if (this.tradeMenuOpen && this.isTradeOfferEmpty()) this.startDragHints();
else this.stopDragHints();
}
showTradeHoverCard(idx, x, y) {
this.clearTradeHoverCard();
const card = this.buildPropertyCardContainer(idx);
const s = 0.82;
const hw = MODAL_W * s / 2, hh = MODAL_H * s / 2;
const hx = Phaser.Math.Clamp(x, hw + 10, GAME_WIDTH - hw - 10);
const hy = Phaser.Math.Clamp(y, hh + 10, GAME_HEIGHT - hh - 10);
card.setPosition(hx, hy).setScale(s).setDepth(DEPTH.popup + 6);
this.tradeHoverCard = card;
}
clearTradeHoverCard() {
if (this.tradeHoverCard) {
this.tradeHoverCard.each(c => { try { c.destroy(); } catch {} });
try { this.tradeHoverCard.destroy(); } catch {}
this.tradeHoverCard = null;
}
}
setTradeFeedback(msg, tone = 'muted') {
if (!this.tradeFeedbackText) return;
const color = tone === 'good' ? '#7fdd9f'
: tone === 'bad' ? COLORS.dangerHex
: tone === 'warn' ? COLORS.goldHex
: COLORS.mutedHex;
this.tradeFeedbackText.setColor(color);
this.tradeFeedbackText.setText(msg);
}
onProposeTrade() {
if (!this.tradeOffer || this.tradeCounterparty === null) return;
const offer = {
fromSeat: this.humanSeat,
toSeat: this.tradeCounterparty,
giveProps: [...this.tradeOffer.giveProps],
getProps: [...this.tradeOffer.getProps],
giveCash: this.tradeOffer.giveCash,
getCash: this.tradeOffer.getCash,
};
const v = validateTrade(this.gs, offer);
if (!v.ok) { this.setTradeFeedback(v.reason, 'warn'); return; }
const fee = tradeInterest(this.gs, offer);
const skill = this.skillBySeat[this.tradeCounterparty] ?? 3;
const verdict = evaluateTrade(this.gs, this.tradeCounterparty, offer, skill);
if (verdict.accept) {
this.gs = applyTrade(this.gs, offer);
this.setTradeFeedback('Accepted! ' + verdict.reason + (fee.from ? ` (You paid $${fee.from} mortgage interest.)` : ''), 'good');
kaching(this);
this.time.delayedCall(1200, () => {
this.closeTradeModal();
this.render();
});
} else if (this.tradeCounterMode) {
// The AI gets a single chance to accept a counter — a rejection ends it.
this.setTradeFeedback('They declined your counter. ' + verdict.reason, 'bad');
this.time.delayedCall(1500, () => { this.closeTradeModal(); this.render(); });
} else {
this.setTradeFeedback('Rejected: ' + verdict.reason, 'bad');
}
}
closeTradeModal() {
this.tradeMenuOpen = false;
this.showPortraits();
this.stopDragHints();
this.clearDropHint();
if (this._onTradeDragStart) this.input.off('dragstart', this._onTradeDragStart);
if (this._onTradeDrag) this.input.off('drag', this._onTradeDrag);
if (this._onTradeDrop) this.input.off('drop', this._onTradeDrop);
if (this._onTradeDragEnd) this.input.off('dragend', this._onTradeDragEnd);
this._onTradeDragStart = this._onTradeDrag = this._onTradeDrop = this._onTradeDragEnd = null;
this.clearTradeHoverCard();
(this.tradeLaneObjs || []).forEach(o => { try { o.destroy(); } catch {} });
(this.tradeRightObjs || []).forEach(o => { try { o.destroy(); } catch {} });
(this.tradeMenuObjs || []).forEach(o => { try { o.destroy(); } catch {} });
this.tradeLaneObjs = [];
this.tradeRightObjs = [];
this.tradeMenuObjs = [];
this.tradeMineCards = {};
this.tradeOppCards = {};
this.tradeOffer = null;
this.tradeCounterparty = null;
this.tradeDragGhost = null;
this.tradeGiveCashText = null;
this.tradeGetCashText = null;
this.tradeFeedbackText = null;
this.tradeCounterMode = false;
this.tradeCounterFrom = null;
// If this modal was a counter to an AI proposal, resolve that pending promise.
const r = this._tradeResolve; this._tradeResolve = null;
if (r) r();
}
}
export function applyTradeMixin(Target) {
for (const k of Object.getOwnPropertyNames(TradeMixin.prototype)) {
if (k !== 'constructor') Target.prototype[k] = TradeMixin.prototype[k];
}
}

View File

@ -0,0 +1,122 @@
// MonopolyTray.js — the felt dice tray with two real 3D dice.
//
// Fairness: the engine rolls first; planTrayThrow (src/ui/dice/Dice3D.js)
// then relabels the flight so each die lands on the rolled face. The dice are
// ivory with the roller's colour as the pip ink. Clicking the tray rolls when
// it's lit (the human's turn).
import { Die3D, planTrayThrow, poseFromPlan, restingQ, qslerp } from '../../ui/dice/Dice3D.js';
import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js';
import { TRAY, TRAY_FELT, TRAY_WORLD, DIE_SIZE, groundTray, diceRest, throwOrigin } from './MonopolyLayout.js';
const IVORY = [246, 238, 218];
const YAW = [0.16, -0.12];
const lerp = (a, b, t) => a + (b - a) * t;
const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
export class DiceTray {
constructor(scene, depth, { onClick } = {}) {
this.scene = scene;
this.depth = depth;
this.onClick = onClick;
this.poses = [];
this.faces = [1, 1];
}
build() {
const s = this.scene;
s.add.image(TRAY.x - 20, TRAY.y - 20, 'mono-tray').setOrigin(0).setDepth(this.depth - 2);
this.glow = s.add.graphics().setDepth(this.depth - 1).setAlpha(0);
this.glow.lineStyle(4, 0xf5d77a, 1).strokeRoundedRect(TRAY_FELT.x - 3, TRAY_FELT.y - 3, TRAY_FELT.w + 6, TRAY_FELT.h + 6, 10);
this.hint = s.add.text(TRAY_FELT.x + TRAY_FELT.w / 2, TRAY_FELT.y + TRAY_FELT.h - 18, 'click the tray to roll', {
fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#ecd690',
}).setOrigin(0.5).setDepth(this.depth + 1).setAlpha(0);
this.pulse = s.tweens.add({ targets: [this.glow, this.hint], alpha: { from: 0.3, to: 1 }, duration: 750, yoyo: true, repeat: -1, paused: true });
this.dice = [0, 1].map(() => new Die3D(s, this.depth, { size: DIE_SIZE, body: IVORY, pip: 0x1c1410, sin: 0.86, cos: 0.5, ground: groundTray }));
this.zone = s.add.zone(TRAY_FELT.x + TRAY_FELT.w / 2, TRAY_FELT.y + TRAY_FELT.h / 2, TRAY_FELT.w, TRAY_FELT.h).setDepth(this.depth + 5);
this.zone.on('pointerdown', () => { if (this.enabled) this.onClick?.(); });
const rest = diceRest();
for (let i = 0; i < 2; i++) { this.poses[i] = { ...rest[i], h: 0, q: restingQ(i ? 6 : 5, YAW[i]), alpha: 1 }; this.apply(i); }
this.setEnabled(false);
return this;
}
setEnabled(on) {
this.enabled = !!on;
if (on) { this.zone.setInteractive({ useHandCursor: true }); this.pulse.resume(); }
else {
this.zone.disableInteractive(); this.pulse.pause();
this.glow.setAlpha(0); this.hint.setAlpha(0);
}
}
// Pip ink in the roller's colour.
setInk(color) { for (const d of this.dice) { d.opts.pip = color; d.draw(); } }
apply(i) {
const p = this.poses[i], d = this.dice[i];
d.setDepth(this.depth + p.v * 0.0002 + (p.h > 4 ? 0.3 : 0));
d.g.setAlpha(p.alpha); d.shadow.setAlpha(p.alpha);
d.set(p.u, p.v, p.h, p.q);
}
tweenDie(i, to, dur, { arc = 0, q = null } = {}) {
const p = this.poses[i];
const from = { u: p.u, v: p.v, h: p.h, q: p.q };
const qTo = q ?? p.q;
if (dur <= 0) { Object.assign(p, { u: to.u, v: to.v, h: to.h ?? 0, q: qTo }); this.apply(i); return Promise.resolve(); }
const prox = { t: 0 };
return new Promise((resolve) => {
this.scene.tweens.add({
targets: prox, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const t = easeInOut(prox.t);
p.u = lerp(from.u, to.u, t); p.v = lerp(from.v, to.v, t);
p.h = lerp(from.h, to.h ?? 0, t) + arc * Math.sin(Math.PI * prox.t);
p.q = qslerp(from.q, qTo, t);
this.apply(i);
},
onComplete: resolve,
});
});
}
async throw(d1, d2, { speed = 1, fast = false } = {}) {
const s = this.scene;
const faces = [d1, d2];
const rest = diceRest();
for (let i = 0; i < 2; i++) { this.dice[i].glow = 0; this.poses[i].alpha = 1; }
if (fast) {
for (let i = 0; i < 2; i++) { Object.assign(this.poses[i], { ...rest[i], h: 0, q: restingQ(faces[i], YAW[i]) }); this.apply(i); }
playSoundEx(s, SFX.DICE_ROLL, { volume: 0.35 });
this.faces = faces;
return;
}
const plan = planTrayThrow(TRAY_WORLD, throwOrigin(), faces, Math.random, DIE_SIZE, { spread: 1.3, sep: 1.6, aim: { u0: 0.22, u1: 0.78, v0: 0.3, v1: 0.7 } });
playSound(s, SFX.DICE_ROLL);
const step = (t) => [0, 1].forEach((i) => {
const p = poseFromPlan(plan, i, t);
Object.assign(this.poses[i], { u: p.u, v: p.v, h: p.h, q: p.q });
this.apply(i);
});
step(0);
const prox = { t: 0 };
await new Promise((resolve) => {
s.tweens.add({ targets: prox, t: 1, duration: Math.max(620, plan.duration * 1000) * speed, ease: 'Linear', onUpdate: () => step(prox.t), onComplete: () => { step(1); resolve(); } });
});
// settle side by side so the result reads at a glance
await Promise.all([0, 1].map((i) => this.tweenDie(i, { ...rest[i], h: 0 }, 240 * speed, { q: restingQ(faces[i], YAW[i]) })));
this.faces = faces;
}
setGlow(amount, color = 0xf5d020) {
for (const d of this.dice) { d.glow = amount; d.opts.glowColor = color; d.draw(); }
}
// Show a resting result without a throw (e.g. after loading a save).
show(d1, d2) {
const rest = diceRest();
[d1, d2].forEach((f, i) => { Object.assign(this.poses[i], { ...rest[i], h: 0, q: restingQ(f, YAW[i]) }); this.apply(i); });
this.faces = [d1, d2];
}
}

View File

@ -1,103 +0,0 @@
# Monopoly — Spritesheet Guide
Three image files need to be created or extended. All dimensions are exact — the engine reads pixel-perfect frame boundaries.
---
## 1. `assets/images/monopoly-pawns.png`
**Total sheet size:** 320 × 80 px
**Frame size:** 80 × 80 px
**Layout:** 4 frames in a single horizontal row
**Displayed at:** 32 × 32 px on the board (the image is scaled down, so keep art centered and avoid fine detail near the edges)
Each frame is a single player token on a transparent background. The token should be centered in the 80 × 80 cell with roughly 8–10 px of breathing room on all sides so it doesn't clip when scaled.
| Frame | X offset | Player | Color theme | Suggested token |
|-------|----------|--------|-------------|-----------------|
| 0 | x=0 | Player 1 | Red `#E53935` | Top hat |
| 1 | x=80 | Player 2 | Blue `#1565C0` | Racing car |
| 2 | x=160 | Player 3 | Green `#2E7D32` | Scottie dog |
| 3 | x=240 | Player 4 | Gold `#F57F17` | Battleship |
### Visual guidance per token
**Top hat (frame 0 — red):**
Iconic tall cylinder hat. Brim at bottom, oval crown at top. Deep red or black body with a red highlight/shadow. Works well as a simple 2-tone silhouette.
**Racing car (frame 1 — blue):**
Classic 1930s open-wheel racer viewed at a slight 3/4 angle. Blue body, yellow or silver wheels. Keep it chunky and readable at 32 × 32 px — avoid thin spokes.
**Scottie dog (frame 2 — green):**
Side-on silhouette of a Scottish Terrier with wiry fur. Body in dark green or black-green; eyes as a small white or yellow dot. The iconic bushy-beard chin and erect tail are the key recognition cues.
**Battleship (frame 3 — gold):**
Top-down or slight 3/4 view of a naval destroyer. Gold hull, dark gray turrets, small white wake lines. Keep it horizontal/landscape within the square cell.
---
## 2. `assets/images/monopoly-cards.png`
**Total sheet size:** 400 × 300 px
**Frame size:** 200 × 300 px
**Layout:** 2 frames side by side in one row
**Displayed at:** 340 × 220 px inside the card popup (the engine scales the frame to fit the top area of a 360 × 480 popup)
The code overlays its own text labels on top — "CHANCE" or "COMMUNITY CHEST" is printed at the top by the engine, and the card's effect text is printed in the lower half. **The image only needs to fill the upper ~220 px of visible space** — think of it as providing the background art and mood, not the text.
| Frame | X offset | Card type | Background color | Icon |
|-------|----------|-----------|------------------|------|
| 0 | x=0 | Chance | Orange `#E77A2C` | Large "?" |
| 1 | x=200 | Community Chest | Blue `#1565C0` | Treasure chest |
### Frame 0 — Chance (200 × 300 px)
- **Background:** Warm orange gradient, darker toward the top and bottom edges
- **Border:** A thin ornate gold or cream inner border rect (≈ 8 px from each edge)
- **Central icon:** A large bold "?" character, roughly 100 × 140 px, in cream or white with a slight drop shadow. The "?" should be centered horizontally and sit in the lower ⅔ of the frame (the engine prints "CHANCE" at the very top, so leave the top 40–50 px relatively clean)
- **Decorative touches (optional):** Small radiating lines or sunburst behind the "?", art deco corner flourishes
### Frame 1 — Community Chest (200 × 300 px)
- **Background:** Rich blue gradient, `#1565C0` center fading to `#0D3A6E` at edges
- **Border:** Same style ornate inner border as Chance, in gold or cream
- **Central icon:** A wooden treasure chest, slightly open, with a warm interior glow or gold coins visible. Roughly 80 × 70 px, centered horizontally, sitting in the lower ⅔ of the frame. Classic Monopoly Community Chest chests are brown/tan with gold hardware
- **Decorative touches (optional):** Small star or coin scattered around the chest, "art deco" corner ornaments matching the Chance card style for consistency
---
## 3. `assets/images/game-icons.png` — extend existing sheet
**Current sheet size:** 660 × 660 px
**Grid:** 15 columns × 15 rows of 44 × 44 px cells
**Current frames:** 0 – 47 (48 icons)
**Monopoly frame index:** **48**
### Where to paint frame 48
Frame 48 falls at:
```
Column = 48 % 15 = 3 → x = 3 × 44 = 132 px
Row = 48 / 15 = 3 → y = 3 × 44 = 132 px
```
**Paint the Monopoly icon into the cell at (132, 132) — a 44 × 44 px region — in your existing game-icons PSD.**
### Monopoly icon design (44 × 44 px)
The icon is shown at 44 × 44 px in the game menu next to the game title. Suggested design:
- **Background:** Deep green `#1F3D1F` or a classic Monopoly board green
- **Foreground:** A small white/cream Monopoly board viewed from above — simplified to just the four corner squares (a white square outline with the four corner squares indicated) OR simply the red "M" monogram from the Monopoly logo
- **Alternative:** A gold top hat silhouette centered on a dark background — very legible at small size and immediately recognizable
Keep the art to 2–3 colors at most. At 44 × 44 the icon is tiny; bold shapes with strong contrast read far better than detailed illustrations.
---
## Checklist
- [ ] `monopoly-pawns.png` — 4 tokens, 320 × 80 px, transparent background per token
- [ ] `monopoly-cards.png` — 2 card arts, 400 × 300 px, no text (engine adds text)
- [ ] `game-icons.png` — add Monopoly icon at pixel (132, 132) in the existing 660 × 660 sheet

View File

@ -0,0 +1,102 @@
# Good Evening, and Welcome to the Boardwalk Hotel
> *A gentleman in a crimson jacket with brass buttons glides out from behind the front desk, polishes a monocle on his lapel, and bows.*
Fitzwilliam, night concierge. Charmed, truly. You'll find the card room through the palms, past the orchestra — emerald baize, good lamps, and a board on which fortunes are made and *spectacularly* lost. Allow me to explain the house's favourite game.
## The Object of the Game
Buy property. Collect rent. Build houses and hotels. Drive every rival into **bankruptcy**. The last player with any money left wins.
You play with one, two or three opponents. Everyone starts with **$1,500** from the bank (the Front Desk can change that).
## The Table
- **The board** — forty spaces round the edge. Twenty-two streets in eight colour sets, four railroads, two utilities, taxes, Chance and Community Chest, and the four corners: GO, Jail, Free Parking and Go To Jail.
- **The plaques** on the right — each player's cash, net worth, and their **title deeds**, fanned by colour. A gilt edge means a complete set; a red card with an "M" is mortgaged.
- **The dice tray** — when it glows, it's your roll. Click it (or press **Space**).
- **The bank** — bills for every occasion, and the stock of **32 houses and 12 hotels**. When the rack runs low it glows amber. Houses are a finite luxury, I'm afraid.
- **The ledger** — every transaction, written in each player's own ink. Scroll it with the mouse wheel.
Hover any space or deed to read its title deed, who owns it, and what the rent would be **right now**.
## A Turn
1. **Roll the dice** and move clockwise that many spaces. Passing GO pays you a **$200 salary**.
2. **Do what the space says** (see below).
3. **Build, trade, mortgage** if you wish — then **End Turn**.
**Doubles** mean you roll again after finishing your turn. Roll doubles **three times in a row** and the constabulary takes an interest: straight to Jail.
## The Spaces
**An unowned property.** Buy it at the printed price — or decline, and it goes to **auction**. Everyone may bid, including you, starting at any price. Bid in steps, or drop out; the last bidder standing takes it.
**Someone else's property.** Pay rent. A street's rent **doubles** once its owner holds the whole colour set, and climbs steeply with each house. Railroads pay $25 / $50 / $100 / $200 for one to four owned. Utilities charge 4× the dice — or 10× with both. Mortgaged property collects nothing.
**Chance / Community Chest.** Draw the top card and do as it says. A **Get Out of Jail Free** card is yours to keep until you use it — it leaves the deck while you hold it.
**Income Tax / Luxury Tax.** Pay the bank $200 or $100.
**Go To Jail.** Do not pass GO. Do not collect $200.
**Free Parking.** A pleasant rest. (With the *jackpot* house rule, every tax and fee piles up here — land on it to scoop the lot.)
## Jail
On each turn in Jail you may **pay $50**, **use a Get Out of Jail Free card**, or **try for doubles**. Doubles walk you out (but don't earn another roll). Fail three times and you must pay the $50 and move anyway. You still collect rent while inside — some gentlemen rather prefer it late in the game, when the board is bristling with hotels.
## Building
Own **every street of a colour** and you may build — houses cost what's printed on the deed.
- Build **evenly**: no lot may have two more houses than another in its set.
- After **four houses** on every lot, trade them in for a **hotel**.
- You can't build on a set while any of it is mortgaged.
Press **M** (or **Manage**, or click one of your spaces) to open the property book: build, sell, mortgage or lift a mortgage, deed by deed — or use **"+1 each"** to build a whole round on a set at once.
## Mortgages and Raising Funds
A property with no buildings in its set can be **mortgaged** for half its price. Lifting the mortgage costs the loan **plus 10%**. Buildings sell back to the bank at **half** what you paid, evenly, one at a time.
If you owe more than you have, the **Raise Funds** sheet opens. You choose what to sell and what to mortgage until you can **Settle** the debt. *Auto-raise* will do it for you the way a careful player would.
## Bankruptcy
Only when selling everything you own still couldn't cover the debt may you **declare bankruptcy**:
- **To a player** — your buildings are sold to the bank at half price, and your cash, deeds and Jail Free cards all go to them. Mortgaged deeds keep their mortgage; the new owner pays the bank 10% interest on each.
- **To the bank** — your deeds are cleared of mortgages and **auctioned** to the other players, one by one.
## Trading
On your turn, before or after you roll, press **Trade**. Drag deeds into the lanes (or click them), add cash on either side, and propose. Opponents will tell you what they think — and they'll come to you with offers of their own, which you can accept, decline or counter. Deeds with buildings in their colour set can't change hands, and anyone receiving a mortgaged deed pays the bank 10% interest on it.
## Game Options (the Front Desk)
Every new game begins at the Front Desk. **Classic** is the standard game and the house default. You may also choose:
- **Short Game** — the official short rules: two title deeds are dealt to each player (paid for at once), a hotel needs only **three** houses, lifting a mortgage costs no interest, and the game ends at the **first bankruptcy** — the richest player wins (cash + deeds at price, half for mortgaged ones, buildings at cost).
- **Starting cash** — $1,000 to $2,500.
- **Free Parking jackpot** — taxes and fees collect on Free Parking for the next visitor.
- **$400 on GO** — land exactly on GO for double salary.
- **Auctions** — on by default; switch off to leave declined deeds with the bank.
- **Round limit** — 30, 50 or 75 rounds, then the richest player wins.
Press **Esc** at any time for the Front Desk menu: opponent speed, skipping opponents' animations, the threat map, the ledger, How to Play, a new game, or leaving.
## The Concierge's Little Conveniences
- **Threat map (T)** — before you roll, every space you might land on is shaded by its odds and what it would cost you. The centre of the board shows your chance of paying anything, the average cost and the worst case.
- **Your game is saved** as you play. Leave the table and you'll be welcomed back exactly where you left off.
- **Keys:** Space — roll / end turn · M — manage properties · T — threat map · L — ledger · Esc — the Front Desk.
## A Few Words of Advice
- The **orange** and **red** sets are landed on more than most — they sit just beyond Jail.
- The **third house** is where rent really jumps. Get to three houses before spreading thin.
- Keep a little cash in hand. A hotel on Boardwalk has ended many a promising evening.
- Railroads are steady earners and splendid trade bait.
> *Fitzwilliam replaces his monocle.* "The dice await, and so, I suspect, does your fortune. Do try not to mortgage the hotel."

505
tools/verifyMonopoly.js Normal file
View File

@ -0,0 +1,505 @@
#!/usr/bin/env node
// verifyMonopoly.js — headless checks for Monopoly ("The Boardwalk Hotel"):
// • rules fixes: no salary for leaving GO, GO salary / doubleGo, Get Out of
// Jail Free cards leave the deck while held, the debt queue for every kind
// of payment, settle / bankruptcy legality, bankruptcy to a player (buildings
// at half, mortgages carried + 10% interest) and to the bank (auctions),
// building / even-selling / housing-shortage rules, mortgage interest on
// trades, auctions (everyone gets a say), jail's third try, Free Parking
// jackpot, short game (deal, 3-house hotels, end at first bankruptcy),
// round limit
// • threat map odds
// • AI soak across classic / short / house-rule mixes and skills 1–5:
// games finish, money moves only through fx events, supplies, even
// building, card conservation, nobody ever below $0
// • save round-trip (JSON) of a mid-game state
// • layout: HUD furniture inside the screen and never overlapping
// Usage: node tools/verifyMonopoly.js [--quick]
import * as L from '../src/games/monopoly/MonopolyLogic.js';
import * as AI from '../src/games/monopoly/MonopolyAI.js';
import * as D from '../src/games/monopoly/MonopolyData.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 { SPACES, PURCHASABLE, GROUPS } = D;
const fresh = (n = 2, rules = {}, seed = 7) => L.createInitialState({ playerCount: n, names: ['A', 'B', 'C', 'D'].slice(0, n), seed, rules });
const own = (s, seat, ...idxs) => { for (const i of idxs) s.board[i].owner = seat; return s; };
const withCash = (s, ...cash) => { cash.forEach((c, i) => { s.players[i].cash = c; }); return s; };
const money = (s) => s.players.reduce((a, p) => a + p.cash, 0) + s.freeParkingPot;
section('Movement & GO');
{
let s = fresh();
s = L.rollDice(s, 0, 2, 3);
ok('leaving GO pays nothing', s.players[0].cash === 1500, `cash ${s.players[0].cash}`);
ok('pawn moves the dice total', s.players[0].position === 5);
s = fresh(); s.players[0].position = 38;
s = L.rollDice(s, 0, 1, 3);
ok('passing GO pays $200', s.players[0].cash === 1700 && s.players[0].position === 2);
s = fresh(2, { doubleGo: true }); s.players[0].position = 36;
s = L.rollDice(s, 0, 1, 3);
ok('doubleGo: landing exactly on GO pays $400', s.players[0].cash === 1900, `cash ${s.players[0].cash}`);
s = fresh(2, { doubleGo: true }); s.players[0].position = 38;
s = L.rollDice(s, 0, 1, 3);
ok('doubleGo: passing GO still pays $200', s.players[0].cash === 1700);
s = fresh();
s = L.rollDice(s, 0, 1, 1); s.phase = 'preroll';
s = L.rollDice(s, 0, 2, 2); s.phase = 'preroll';
s = L.rollDice(s, 0, 3, 3);
ok('three doubles → Jail', s.players[0].jailed && s.players[0].position === 10 && s.phase === 'endturn');
s = L.endTurn(s);
ok('…and the turn passes', s.current === 1);
s = fresh(); s = L.rollDice(s, 0, 2, 2);
if (s.phase === 'buy') s = L.buyProperty(s, 0);
s = L.endTurn(s);
ok('doubles: same player rolls again', s.current === 0 && s.phase === 'preroll');
}
section('Get Out of Jail Free');
{
let s = fresh();
// Put the Chance GOOJF card on top and land on Chance (7).
s.chanceDeck = [D.GOOJF_CARD.chance, ...s.chanceDeck.filter(i => i !== D.GOOJF_CARD.chance)];
s.players[0].position = 4;
s = L.rollDice(s, 0, 1, 2);
ok('drew the card', s.phase === 'card' && s.pendingCard.effect.effect === 'goojf');
s = L.applyCardEffect(s, 0);
ok('the player keeps it', s.players[0].getOutOfJailFree === 1 && s.players[0].jailCards.length === 1);
ok('it is no longer in the Chance deck', !s.chanceDeck.includes(D.GOOJF_CARD.chance) && s.chanceDeck.length === 15);
// Cycle the whole deck: it must never come up.
let seen = 0;
for (let k = 0; k < 40; k++) {
s.phase = 'preroll'; s.players[0].position = 4; s.players[0].jailed = false; s.current = 0;
s = L.rollDice(s, 0, 1, 2);
if (s.pendingCard?.effect.effect === 'goojf') seen++;
s.pendingCard = null; s.pendingBuy = null; s.pendingRent = null; s.debts = []; s.phase = 'endturn';
}
ok('a held card is never drawn again', seen === 0);
s = fresh(); s.players[0].jailed = true; s.players[0].position = 10;
s.players[0].jailCards = [{ deck: 'chance', idx: D.GOOJF_CARD.chance }]; s.players[0].getOutOfJailFree = 1;
s.chanceDeck = s.chanceDeck.filter(i => i !== D.GOOJF_CARD.chance);
s = L.useJailCard(s, 0);
ok('using it frees the player', !s.players[0].jailed && s.phase === 'preroll');
ok('…and returns it to the bottom of the deck', s.chanceDeck[s.chanceDeck.length - 1] === D.GOOJF_CARD.chance && s.chanceDeck.length === 16);
}
section('Jail');
{
let s = fresh(); s.players[0].jailed = true; s.players[0].position = 10;
s = L.rollDice(s, 0, 1, 2);
ok('a miss stays in Jail', s.players[0].jailed && s.players[0].jailTurns === 1 && s.phase === 'endturn');
s.phase = 'preroll'; s = L.rollDice(s, 0, 1, 2); s.phase = 'preroll';
const before = s.players[0].cash;
s = L.rollDice(s, 0, 1, 2);
ok('third miss: pay $50 and move', !s.players[0].jailed && s.players[0].cash === before - 50 && s.players[0].position === 13, `pos ${s.players[0].position} cash ${s.players[0].cash}`);
s = fresh(); s.players[0].jailed = true; s.players[0].position = 10;
s = L.rollDice(s, 0, 3, 3);
ok('doubles walk out of Jail', !s.players[0].jailed && s.players[0].position === 16);
if (s.phase === 'buy') s = L.declineProperty(s, 0);
while (s.phase === 'auction') s = L.passAuction(s, L.auctionBidder(s));
s = L.endTurn(s);
ok('…without an extra roll', s.current === 1);
s = fresh(); s.players[0].jailed = true; s.players[0].position = 10; s.players[0].jailTurns = 2; s.players[0].cash = 20;
own(s, 0, 1, 3);
s = L.rollDice(s, 0, 1, 2);
ok('broke on the third try: debt for the fine', s.phase === 'debt' && s.debts[0].amount === 50 && s.players[0].position === 10);
s = L.mortgageProperty(s, 0, 1);
s = L.settleDebt(s);
ok('after settling, the pawn moves on', s.players[0].position === 13 && s.phase !== 'debt', `pos ${s.players[0].position} ${s.phase}`);
s = fresh(2, { freeParkingJackpot: true }); s.players[0].jailed = true; s.players[0].position = 10;
s = L.payJailFine(s, 0);
ok('jackpot rule: the fine goes to the pot', s.freeParkingPot === 50 && s.players[0].cash === 1450);
}
section('Rent, debts and settling');
{
let s = fresh(); own(s, 1, 39); s.players[0].position = 35;
s = L.rollDice(s, 0, 2, 2);
ok('landing on an owned deed → rent phase', s.phase === 'rent' && s.pendingRent.amount === 50);
s = L.applyRent(s);
ok('rent paid', s.players[0].cash === 1450 && s.players[1].cash === 1550 && s.phase === 'endturn');
ok('stats track rent', s.stats.rentPaid[0] === 50 && s.stats.rentCollected[1] === 50);
s = fresh(); own(s, 1, 37, 39); s.board[39].hotel = true; s.players[0].position = 35; s.players[0].cash = 300;
own(s, 0, 1, 3, 5);
s = L.rollDice(s, 0, 2, 2); s = L.applyRent(s);
ok('short of cash → debt, cash untouched', s.phase === 'debt' && s.players[0].cash === 300 && s.debts[0].amount === 2000);
ok('debtor is the acting seat', L.actingSeat(s) === 0);
ok('cannot settle yet', !L.canSettleDebt(s));
ok('bankruptcy legal (300 + 160 of mortgages < 2000)', L.mustGoBankrupt(s));
const same = L.settleDebt(s);
ok('settle refused while short', same === s);
s = fresh(); own(s, 1, 39); s.players[0].position = 35; s.players[0].cash = 30;
own(s, 0, 1, 3);
s = L.rollDice(s, 0, 2, 2); s = L.applyRent(s);
ok('debt $50 with $30 cash and two $30 mortgages', s.phase === 'debt' && !L.mustGoBankrupt(s));
const nope = L.declareBankruptcy(s);
ok('bankruptcy refused when funds can be raised', nope === s);
s = L.mortgageProperty(s, 0, 1);
ok('mortgage raises $30', s.players[0].cash === 60);
s = L.settleDebt(s);
ok('settled: creditor paid, turn resumes', s.players[1].cash === 1550 && s.players[0].cash === 10 && s.phase === 'endturn');
}
section('Cards that charge everyone');
{
let s = fresh(3); s.players[0].cash = 60;
s.pendingCard = { cardType: 'chance', cardIdx: 14, text: '', effect: D.CHANCE_CARDS[14] }; s.phase = 'card';
s = L.applyCardEffect(s, 0);
ok('"pay each player $50" with $60: first paid, second queued', s.players[1].cash === 1550 && s.debts.length === 1 && s.debts[0].creditor === 2 && s.phase === 'debt');
s = fresh(3); s.players[1].cash = 5; s.players[2].cash = 500;
s.pendingCard = { cardType: 'community_chest', cardIdx: 6, text: '', effect: D.CC_CARDS[6] }; s.phase = 'card';
s = L.applyCardEffect(s, 0);
ok('"collect $50 from every player": short opponent gets a debt', s.players[0].cash === 1550 && s.debts.length === 1 && s.debts[0].debtor === 1);
ok('the debtor (not the current player) acts', L.actingSeat(s) === 1);
s = L.declareBankruptcy(s);
ok('broke opponent goes bankrupt to the collector', s.players[1].bankrupt && s.players[0].cash === 1555, `cash ${s.players[0].cash}`);
ok('the current player carries on', s.current === 0 && s.phase === 'endturn');
}
section('Bankruptcy');
{
// To a player: buildings sold at half, cash + deeds (mortgages kept) to the creditor, 10% interest.
let s = fresh(3);
own(s, 0, 1, 3, 5); s.board[1].houses = 2; s.board[3].houses = 2; s.houseSupply -= 4; s.board[5].mortgaged = true;
s.players[0].cash = 10;
s.debts = [{ debtor: 0, creditor: 1, amount: 5000, why: 'rent' }]; s.phase = 'debt';
const c0 = s.players[1].cash;
s = L.declareBankruptcy(s);
ok('debtor out', s.players[0].bankrupt && !s.players[0].active);
ok('houses back in the bank', s.houseSupply === 32 && s.board[1].houses === 0);
ok('creditor gets cash + half the building cost, less 10% interest', s.players[1].cash === c0 + 10 + 4 * 25 - 10, `cash ${s.players[1].cash - c0}`);
ok('deeds transferred with the mortgage kept', s.board[1].owner === 1 && s.board[5].owner === 1 && s.board[5].mortgaged && !s.board[1].mortgaged);
ok('turn passes on from the bankrupt player', s.current === 1 && s.phase === 'preroll');
// To the bank: deeds unmortgaged and auctioned in turn.
s = fresh(3); own(s, 0, 1, 3); s.board[3].mortgaged = true; s.players[0].cash = 0;
s.players[0].jailCards = [{ deck: 'community_chest', idx: D.GOOJF_CARD.community_chest }]; s.players[0].getOutOfJailFree = 1;
s.ccDeck = s.ccDeck.filter(i => i !== D.GOOJF_CARD.community_chest);
s.debts = [{ debtor: 0, creditor: 'bank', amount: 200, why: 'tax' }]; s.phase = 'debt'; s.current = 0;
s = L.declareBankruptcy(s);
ok('bankrupt to the bank → auction of the first deed', s.phase === 'auction' && s.pendingAuction.spaceIdx === 1 && s.auctionQueue.length === 1);
ok('deeds unmortgaged and ownerless', s.board[3].owner === null && !s.board[3].mortgaged);
ok('jail card back in its deck', s.ccDeck.includes(D.GOOJF_CARD.community_chest));
ok('bankrupt player not among bidders', !s.pendingAuction.bidders.includes(0));
s = L.placeBid(s, L.auctionBidder(s), 40);
while (s.phase === 'auction' && s.pendingAuction.spaceIdx === 1) s = L.passAuction(s, L.auctionBidder(s));
ok('second deed auctioned next', s.phase === 'auction' && s.pendingAuction.spaceIdx === 3);
while (s.phase === 'auction') s = L.passAuction(s, L.auctionBidder(s));
ok('then play passes on', s.phase === 'preroll' && s.current === 1 && s.board[1].owner !== null, `phase ${s.phase} cur ${s.current}`);
s = fresh(2); s.debts = [{ debtor: 0, creditor: 1, amount: 5000, why: 'rent' }]; s.phase = 'debt'; s.players[0].cash = 0;
s = L.declareBankruptcy(s);
ok('last player standing wins', s.phase === 'gameover' && s.winner === 1 && s.endReason === 'last');
}
section('Building');
{
let s = fresh(); own(s, 0, 6, 8, 9);
ok('can build with the set', L.canBuildHouse(s, 0, 6));
s.board[9].mortgaged = true;
ok('cannot build while one of the set is mortgaged', !L.canBuildHouse(s, 0, 6));
s.board[9].mortgaged = false;
s = L.buildHouse(s, 0, 6);
ok('even building: not a 2nd house on the same lot', !L.canBuildHouse(s, 0, 6) && L.canBuildHouse(s, 0, 8));
s = L.buildHouse(s, 0, 8); s = L.buildHouse(s, 0, 9); s = L.buildHouse(s, 0, 6);
ok('even selling: only from the most-built lot', L.canSellHouse(s, 0, 6) && !L.canSellHouse(s, 0, 8));
ok('cannot mortgage while the group has buildings', !L.canMortgage(s, 0, 9));
ok('cannot build without the cash', (() => { const t = JSON.parse(JSON.stringify(s)); t.players[0].cash = 10; return !L.canBuildHouse(t, 0, 8); })());
s = fresh(); own(s, 0, 37, 39); s.players[0].cash = 5000;
for (let k = 0; k < 4; k++) { s = L.buildHouse(s, 0, 37); s = L.buildHouse(s, 0, 39); }
ok('4 houses each', s.board[37].houses === 4 && s.board[39].houses === 4 && s.houseSupply === 24);
s = L.buildHotel(s, 0, 39);
ok('hotel returns 4 houses', s.board[39].hotel && s.houseSupply === 28 && s.hotelSupply === 11);
ok('cannot sell a house off the 4-house lot while the other has a hotel', !L.canSellHouse(s, 0, 37));
let c = s.players[0].cash;
s = L.sellHotel(s, 0, 39);
ok('selling the hotel breaks it back into 4 houses', s.board[39].houses === 4 && !s.board[39].hotel && s.houseSupply === 24 && s.players[0].cash === c + 100);
s = L.buildHotel(s, 0, 39);
s.houseSupply = 2; c = s.players[0].cash;
s = L.sellHotel(s, 0, 39);
ok('housing shortage: hotel sold down to bare land', s.board[39].houses === 0 && s.players[0].cash === c + 500 && s.houseSupply === 2);
s = fresh(); own(s, 0, 1, 3); s.houseSupply = 0;
ok('no houses in the bank → no building', !L.canBuildHouse(s, 0, 1));
s = fresh(2, {}); own(s, 0, 21, 23, 24);
const plan = L.planEvenBuild(s, 0, 'red', 900);
ok('even-build plan spreads houses', plan.length === 6 && new Set(plan.slice(0, 3).map(p => p.idx)).size === 3, JSON.stringify(plan));
}
section('Mortgages & trades');
{
let s = fresh(); own(s, 0, 39);
s = L.mortgageProperty(s, 0, 39);
ok('mortgage pays half', s.players[0].cash === 1700 && s.board[39].mortgaged);
s = L.unmortgageProperty(s, 0, 39);
ok('lifting costs +10%', s.players[0].cash === 1480 && !s.board[39].mortgaged);
s = fresh(); own(s, 0, 39); s.board[39].mortgaged = true;
const offer = { fromSeat: 0, toSeat: 1, giveProps: [39], getProps: [], giveCash: 0, getCash: 100 };
ok('trade valid', L.validateTrade(s, offer).ok);
const t = L.applyTrade(s, offer);
ok('receiver of a mortgaged deed pays 10% interest', t.players[1].cash === 1500 - 100 - 20 && t.board[39].owner === 1 && t.board[39].mortgaged);
s.players[1].cash = 110;
ok('trade refused if the receiver cannot cover the interest', !L.validateTrade(s, offer).ok);
s = fresh(2, { mode: 'short' }); const idx = L.ownedBy(s, 0)[0];
s = L.mortgageProperty(s, 0, idx); const c = s.players[0].cash;
s = L.unmortgageProperty(s, 0, idx);
ok('short game: no interest when lifting a mortgage', s.players[0].cash === c - SPACES[idx].mortgage);
}
section('Auctions');
{
let s = fresh(2); s.players[0].position = 1; s.pendingBuy = { spaceIdx: 1 }; s.phase = 'buy';
s = L.declineProperty(s, 0);
ok('declining starts an auction with everyone', s.phase === 'auction' && s.pendingAuction.bidders.length === 2);
s = L.passAuction(s, 0);
ok('the last bidder still gets a say', s.phase === 'auction' && L.auctionBidder(s) === 1);
s = L.placeBid(s, 1, 10);
ok('a lone bid wins', s.board[1].owner === 1 && s.players[1].cash === 1490 && s.phase === 'endturn');
s = fresh(3); s.pendingBuy = { spaceIdx: 39 }; s.phase = 'buy';
s = L.declineProperty(s, 0);
s = L.placeBid(s, 0, 100); s = L.placeBid(s, 1, 150); s = L.passAuction(s, 2);
ok('bidding goes round, skipping the high bidder', L.auctionBidder(s) === 0);
s = L.placeBid(s, 0, 200); s = L.passAuction(s, 1);
ok('auction ends when only the high bidder is left', s.board[39].owner === 0 && s.players[0].cash === 1300);
s = fresh(2, { auctions: false }); s.pendingBuy = { spaceIdx: 1 }; s.phase = 'buy';
s = L.declineProperty(s, 0);
ok('auctions off: declined deed stays with the bank', s.phase === 'endturn' && s.board[1].owner === null);
}
section('House rules & modes');
{
let s = fresh(2, { freeParkingJackpot: true }); s.players[0].position = 1;
s = L.rollDice(s, 0, 1, 2);
ok('jackpot: tax goes to the pot', s.freeParkingPot === 200 && s.players[0].cash === 1300);
s = L.endTurn(s); s.players[1].position = 17;
s = L.rollDice(s, 1, 1, 2);
ok('landing on Free Parking collects the pot', s.players[1].cash === 1700 && s.freeParkingPot === 0);
s = fresh(3, { startingCash: 2500 });
ok('starting cash option', s.players.every(p => p.cash === 2500));
s = fresh(4, { mode: 'short' }, 11);
const owned = PURCHASABLE.filter(i => s.board[i].owner !== null);
ok('short game deals 2 deeds each', owned.length === 8 && s.players.every(p => L.ownedBy(s, p.seat).length === 2));
ok('…and players paid for them', s.players.every(p => p.cash === 1500 - L.ownedBy(s, p.seat).reduce((a, i) => a + SPACES[i].price, 0)));
s = fresh(2, { mode: 'short' }); for (const i of PURCHASABLE) s.board[i].owner = null; own(s, 0, 37, 39); s.players[0].cash = 5000;
for (let k = 0; k < 3; k++) { s = L.buildHouse(s, 0, 37); s = L.buildHouse(s, 0, 39); }
ok('short game: hotel after 3 houses', L.canBuildHotel(s, 0, 39) && !L.canBuildHouse(s, 0, 39));
s = L.buildHotel(s, 0, 39);
ok('…which returns 3 houses', s.houseSupply === 32 - 6 + 3);
s = fresh(3, { mode: 'short' }); s.debts = [{ debtor: 2, creditor: 'bank', amount: 99999, why: 'tax' }]; s.phase = 'debt'; s.players[2].cash = 0;
for (const i of L.ownedBy(s, 2)) s.board[i].owner = null;
s.players[1].cash = 5000;
s = L.declareBankruptcy(s);
ok('short game ends at the first bankruptcy; richest wins', s.phase === 'gameover' && s.endReason === 'short' && s.winner === 1);
s = fresh(2, { roundLimit: 2 });
for (let k = 0; k < 4 && s.phase !== 'gameover'; k++) { s.phase = 'endturn'; s.doublesCount = 0; s = L.endTurn(s); }
ok('round limit ends the game', s.phase === 'gameover' && s.endReason === 'rounds', `${s.phase} r${s.round}`);
}
section('Threat map');
{
let s = fresh(); own(s, 1, 6, 8, 9); s.board[8].houses = 1; s.board[6].houses = 1; s.board[9].houses = 1; s.houseSupply -= 3;
const tm = L.threatMap(s, 0);
const total = tm.cells.reduce((a, c) => a + c.prob, 0);
ok('probabilities sum to 1', Math.abs(total - 1) < 1e-9, total);
ok('rent cells priced', tm.cells.find(c => c.idx === 8)?.cost === 30 && tm.cells.find(c => c.idx === 4)?.kind === 'tax');
ok('P(pay anything) counts rent and tax', Math.abs(tm.pAny - (D.DICE_P[4] + D.DICE_P[6] + D.DICE_P[8] + D.DICE_P[9])) < 1e-9, tm.pAny);
s.players[0].jailed = true; s.players[0].position = 10;
const tj = L.threatMap(s, 0);
ok('jailed: only doubles move', Math.abs(tj.cells.reduce((a, c) => a + c.prob, 0) - 6 / 36) < 1e-9);
}
// ── AI soak ───────────────────────────────────────────────────────────────────
function aiTrades(s, seat, skills) {
let done = 0;
for (const t of s.players) {
if (done >= 2) break;
if (t.seat === seat || !t.active) continue;
const offer = AI.buildAiTradeOffer(s, seat, t.seat, skills[seat], { targetSkill: skills[t.seat] });
if (!offer || !L.validateTrade(s, offer).ok) continue;
if (!AI.evaluateTrade(s, t.seat, offer, skills[t.seat]).accept) continue;
s = L.applyTrade(s, offer); done++;
}
return s;
}
function aiStep(s, skills, rng, ctx) {
const seat = L.actingSeat(s);
const skill = skills[seat];
const die = () => 1 + Math.floor(rng() * 6);
switch (s.phase) {
case 'auction': {
const bid = AI.chooseBid(s, seat, skill);
return bid !== null ? L.placeBid(s, seat, bid) : L.passAuction(s, seat);
}
case 'debt': {
const a = AI.chooseDebtAction(s, seat, skill);
if (a.action === 'settle') return L.settleDebt(s);
if (a.action === 'bankrupt') return L.declareBankruptcy(s);
if (a.action === 'mortgage') return L.mortgageProperty(s, seat, a.spaceIdx);
if (a.action === 'sellHouse') return L.sellHouse(s, seat, a.spaceIdx);
if (a.action === 'sellHotel') return L.sellHotel(s, seat, a.spaceIdx);
throw new Error('bad debt action ' + JSON.stringify(a));
}
case 'preroll': {
if (ctx.manage++ < 30) {
const m = AI.chooseManage(s, seat, skill);
if (m) {
const n = m.action === 'hotel' ? L.buildHotel(s, seat, m.spaceIdx)
: m.action === 'house' ? L.buildHouse(s, seat, m.spaceIdx) : L.unmortgageProperty(s, seat, m.spaceIdx);
if (n !== s) return n;
}
}
ctx.manage = 0;
if (s.players[seat].jailed) {
const ja = AI.chooseJailAction(s, seat, skill);
if (ja === 'card' && s.players[seat].getOutOfJailFree > 0) return L.useJailCard(s, seat);
if (ja === 'pay' && s.players[seat].cash >= 50) return L.payJailFine(s, seat);
}
return L.rollDice(s, seat, die(), die());
}
case 'buy': return AI.chooseBuy(s, seat, skill) ? L.buyProperty(s, seat) : L.declineProperty(s, seat);
case 'card': return L.applyCardEffect(s, seat, { dice: [die(), die()] });
case 'rent': return L.applyRent(s);
case 'endturn': {
if (!ctx.traded) { ctx.traded = true; if (rng() < 0.5) return aiTrades(s, seat, skills); }
ctx.traded = false;
return L.endTurn(s);
}
default: throw new Error('unknown phase ' + s.phase);
}
}
function invariants(s, prev, label, errs) {
const err = (m) => { if (errs.length < 6) errs.push(`${label}: ${m}`); };
for (const p of s.players) if (p.cash < 0) err(`${p.name} cash ${p.cash}`);
if (s.freeParkingPot < 0) err('pot negative');
let houses = 0, hotels = 0;
for (const i of PURCHASABLE) { houses += s.board[i].houses; hotels += s.board[i].hotel ? 1 : 0; }
if (houses + s.houseSupply !== 32) err(`houses ${houses}+${s.houseSupply}`);
if (hotels + s.hotelSupply !== 12) err(`hotels ${hotels}+${s.hotelSupply}`);
for (const [g, idxs] of Object.entries(GROUPS)) {
const lv = idxs.map(i => L.level(s, i));
const built = lv.some(v => v > 0);
if (built && idxs.some(i => s.board[i].mortgaged)) err(`${g} built with a mortgage`);
if (built && !L.ownsGroup(s, s.board[idxs[0]].owner, g)) err(`${g} built without the set`);
if (Math.max(...lv) - Math.min(...lv) > 1 && s.houseSupply > 4) err(`${g} uneven ${lv}`);
}
for (const i of PURCHASABLE) { const o = s.board[i].owner; if (o !== null && !s.players[o].active) err(`deed ${i} owned by bankrupt`); }
const held = { chance: 0, community_chest: 0 };
if (s.pendingCard?.effect?.effect === 'goojf') held[s.pendingCard.cardType]++;
for (const p of s.players) { for (const c of p.jailCards) held[c.deck]++; if (p.getOutOfJailFree !== p.jailCards.length) err('jail card count'); }
if (s.chanceDeck.length + held.chance !== 16) err(`chance cards ${s.chanceDeck.length}+${held.chance}`);
if (s.ccDeck.length + held.community_chest !== 16) err(`cc cards ${s.ccDeck.length}+${held.community_chest}`);
if (s.phase !== 'gameover' && !s.players[L.actingSeat(s)]?.active) err(`acting seat ${L.actingSeat(s)} inactive (${s.phase})`);
// Money moves only through fx events (so every change can be animated).
const fresh = s.fx.filter(e => e.id > prev.fxSeq);
if (s.fxSeq - prev.fxSeq > 48) return;
let flow = 0;
for (const e of fresh) if (e.type === 'pay') {
if (e.from === 'bank') flow += e.amount;
if (e.to === 'bank') flow -= e.amount;
}
if (money(s) - money(prev) !== flow) err(`money ${money(prev)}→${money(s)} but fx flow ${flow} (${prev.phase}→${s.phase})`);
}
section('AI soak');
{
const configs = [
{ n: 4, rules: {} }, { n: 3, rules: {} }, { n: 2, rules: {} },
{ n: 4, rules: { mode: 'short' } }, { n: 3, rules: { freeParkingJackpot: true, doubleGo: true } },
{ n: 4, rules: { auctions: false, startingCash: 1000 } }, { n: 3, rules: { roundLimit: 30 } },
{ n: 2, rules: { mode: 'short', startingCash: 2500 } },
];
const GAMES = QUICK ? 24 : 160;
const STEP_CAP = 60000;
const errs = [];
let finished = 0, capped = 0, totalRounds = 0, steps = 0, bankrupts = 0, debtsSeen = 0, auctions = 0, saveOk = true;
const reasons = {};
for (let g = 0; g < GAMES; g++) {
const cfg = configs[g % configs.length];
const rng = L.rngFrom(1000 + g);
const skills = Array.from({ length: cfg.n }, (_, i) => 1 + ((g + i) % 5));
let s = L.createInitialState({ playerCount: cfg.n, names: ['A', 'B', 'C', 'D'], seed: 500 + g, rules: cfg.rules });
const ctx = { manage: 0, traded: false };
let k = 0;
for (; k < STEP_CAP && s.phase !== 'gameover'; k++) {
const prev = s;
s = aiStep(s, skills, rng, ctx);
if (s.phase === 'debt' && prev.phase !== 'debt') debtsSeen++;
if (s.phase === 'auction' && prev.phase !== 'auction') auctions++;
invariants(s, prev, `game ${g} step ${k}`, errs);
if (k === 400) {
const r = JSON.parse(JSON.stringify(s));
if (JSON.stringify(r) !== JSON.stringify(s)) saveOk = false;
}
if (s.round > 1500) break;
}
steps += k;
if (s.phase === 'gameover') { finished++; reasons[s.endReason] = (reasons[s.endReason] ?? 0) + 1; totalRounds += s.round; }
else capped++;
bankrupts += s.players.filter(p => p.bankrupt).length;
if (s.phase === 'gameover') {
if (s.standings?.length !== cfg.n) errs.push(`game ${g}: standings ${s.standings}`);
if (s.winner !== s.standings[0]) errs.push(`game ${g}: winner mismatch`);
}
}
console.log(` ${GAMES} games: ${finished} finished (${Object.entries(reasons).map(([k, v]) => `${k} ${v}`).join(', ')}), ${capped} capped; avg ${Math.round(totalRounds / Math.max(1, finished))} rounds, ${steps} steps, ${bankrupts} bankruptcies, ${debtsSeen} debts, ${auctions} auctions`);
ok('soak invariants hold', errs.length === 0, '\n ' + errs.join('\n '));
ok('most games finish', finished >= GAMES * 0.9, `${finished}/${GAMES}`);
ok('debts and auctions were exercised', debtsSeen > 0 && auctions > 0);
ok('mid-game state survives a JSON save round-trip', saveOk);
}
// ── Layout ────────────────────────────────────────────────────────────────────
section('Layout');
try {
const Lay = await import('../src/games/monopoly/MonopolyLayout.js');
const F = Lay.hudFurniture();
const inScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= 1920 && r.y + r.h <= 1080;
for (const [k, r] of Object.entries(F)) ok(`${k} on screen`, inScreen(r), JSON.stringify(r));
const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
const keys = Object.keys(F);
const ov = [];
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) if (overlap(F[keys[i]], F[keys[j]])) ov.push(`${keys[i]}×${keys[j]}`);
ok('HUD furniture never overlaps', ov.length === 0, ov.join(', '));
for (let i = 0; i < 40; i++) {
const r = Lay.spaceRect(i);
if (!(r.x >= Lay.BOARD.x - 0.5 && r.y >= Lay.BOARD.y - 0.5 && r.x + r.w <= Lay.BOARD.x + Lay.BOARD.w + 0.5 && r.y + r.h <= Lay.BOARD.y + Lay.BOARD.h + 0.5)) ok(`space ${i} inside the board`, false);
}
ok('spaces tile the board edge', (() => {
let area = 0; for (let i = 0; i < 40; i++) { const r = Lay.spaceRect(i); area += r.w * r.h; }
const B = Lay.BOARD, inner = B.w - 2 * D.CORNER_SIZE;
return Math.abs(area - (B.w * B.h - inner * inner)) < 1;
})());
} catch (e) {
ok('layout module loads', false, e.message);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);