diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 62ef1fc..463811c 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -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: '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: '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: '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 }); diff --git a/src/games/monopoly/MonopolyAI.js b/src/games/monopoly/MonopolyAI.js index b2c02ad..d1452cf 100644 --- a/src/games/monopoly/MonopolyAI.js +++ b/src/games/monopoly/MonopolyAI.js @@ -5,6 +5,8 @@ import { } from './MonopolyData.js'; import { ownsGroup, canBuildHouse, canBuildHotel, netWorth, isTradeable, validateTrade, + canMortgage, canSellHouse, canSellHotel, canUnmortgage, unmortgageCost, isShort, + currentDebt, canSettleDebt, mustGoBankrupt, railroadsOwned, mortgageInterest, tradeInterest, } from './MonopolyLogic.js'; const PROFILES = { @@ -34,36 +36,84 @@ export function nextThinkDelay(skill) { 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 ─────────────────────────────────────────────────────────────── export function chooseBuy(state, seat, skill) { const prof = PROFILES[skill] ?? PROFILES[3]; - if (Math.random() < prof.blunder) return Math.random() < 0.5; const { spaceIdx } = state.pendingBuy; const sp = SPACES[spaceIdx]; 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; } // ── Auction bid ─────────────────────────────────────────────────────────────── +// Bids climb in steps (so auctions read like auctions) up to a private ceiling. export function chooseBid(state, seat, skill) { const prof = PROFILES[skill] ?? PROFILES[3]; const auc = state.pendingAuction; + if (!auc) return null; const sp = SPACES[auc.spaceIdx]; const p = state.players[seat]; - const maxBid = Math.min(p.cash * 0.7, sp.price * prof.maxBidMult + noise(prof.noise)); - if (maxBid <= auc.highBid) return null; // pass - return Math.max(auc.highBid + 1, Math.floor(maxBid)); + const keep = skill >= 3 ? Math.min(prof.reserve * 0.4, 120) : 0; + const ceiling = Math.floor(Math.min(p.cash - keep, aiValue(state, seat, auc.spaceIdx, skill) + noise(prof.noise))); + 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 ───────────────────────────────────────────────────────────── +// 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) { + const prof = PROFILES[skill] ?? PROFILES[3]; const p = state.players[seat]; - if (p.getOutOfJailFree > 0) return 'card'; - if (skill >= 3 && p.cash >= 50) { - // Higher skill: pay to get back in action - return 'pay'; + const unowned = PURCHASABLE.filter(i => state.board[i]?.owner === null).length; + let oppBuildings = 0; + for (const idx of PURCHASABLE) { + 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'; } @@ -110,7 +160,13 @@ export function scoreTrade(state, aiSeat, offer, skill, noiseless = false) { const before = state.board; 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 gainVal = giveProps.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; } -// ── Build decisions ──────────────────────────────────────────────────────────── -// Returns { action: 'house'|'hotel', spaceIdx } or null -export function chooseBuild(state, seat, skill) { +// ── Manage: build, lift mortgages ──────────────────────────────────────────────── +// Returns { action: 'house'|'hotel'|'unmortgage', spaceIdx } or null. +export function chooseManage(state, seat, skill) { const prof = PROFILES[skill] ?? PROFILES[3]; 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) { - if (!canBuildHotel(state, seat, idx)) continue; + const own = state.board[idx]; const sp = SPACES[idx]; - if (p.cash - sp.houseCost >= prof.reserve) { - return { action: 'hotel', spaceIdx: idx }; + if (own.owner !== seat || !own.mortgaged || sp.type !== 'property') continue; + 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) { - if (!canBuildHouse(state, seat, idx)) continue; const sp = SPACES[idx]; - if (p.cash - sp.houseCost >= prof.reserve) { - return { action: 'house', spaceIdx: idx }; - } + if (sp.type !== 'property' || p.cash - sp.houseCost < reserve) continue; + 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; } +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' }; +} diff --git a/src/games/monopoly/MonopolyArt.js b/src/games/monopoly/MonopolyArt.js new file mode 100644 index 0000000..35aa759 --- /dev/null +++ b/src/games/monopoly/MonopolyArt.js @@ -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- paper bills ($1 … $500) +// mono-mini- 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; +} diff --git a/src/games/monopoly/MonopolyBank.js b/src/games/monopoly/MonopolyBank.js new file mode 100644 index 0000000..59f59fd --- /dev/null +++ b/src/games/monopoly/MonopolyBank.js @@ -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 }; } +} diff --git a/src/games/monopoly/MonopolyData.js b/src/games/monopoly/MonopolyData.js index d0f0b65..8a35872 100644 --- a/src/games/monopoly/MonopolyData.js +++ b/src/games/monopoly/MonopolyData.js @@ -1,9 +1,40 @@ // Monopoly — static data. No Phaser, no state. -export const BOARD_SIZE = 840; -export const CORNER_SIZE = 105; -export const SPACE_W = 70; -export const BAND_H = 18; +// Board geometry (board-relative px). 2 corners + 9 spaces per side: 136·2 + 80·9 = 992. +export const BOARD_SIZE = 992; +export const CORNER_SIZE = 136; +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 = { brown: 0x9B5524, @@ -159,6 +190,23 @@ export function nearestUtility(pos) { 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 export const PAWN_FRAME = (seat) => seat; // Card spritesheet: frame 0 = Chance, frame 1 = Community Chest, 200×300 px cells diff --git a/src/games/monopoly/MonopolyDeed.js b/src/games/monopoly/MonopolyDeed.js new file mode 100644 index 0000000..02ac29e --- /dev/null +++ b/src/games/monopoly/MonopolyDeed.js @@ -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 (_) { /* */ } +} diff --git a/src/games/monopoly/MonopolyDialogs.js b/src/games/monopoly/MonopolyDialogs.js new file mode 100644 index 0000000..41d36bf --- /dev/null +++ b/src/games/monopoly/MonopolyDialogs.js @@ -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 }; diff --git a/src/games/monopoly/MonopolyEndScreen.js b/src/games/monopoly/MonopolyEndScreen.js new file mode 100644 index 0000000..a79db0f --- /dev/null +++ b/src/games/monopoly/MonopolyEndScreen.js @@ -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; +} diff --git a/src/games/monopoly/MonopolyGame.js b/src/games/monopoly/MonopolyGame.js index 113f61f..48c1c5a 100644 --- a/src/games/monopoly/MonopolyGame.js +++ b/src/games/monopoly/MonopolyGame.js @@ -1,113 +1,154 @@ +// MonopolyGame.js — "The Boardwalk Hotel": Monopoly in a 1930s Art Deco card +// room. This scene orchestrates; the pieces live alongside it: +// +// MonopolyLogic pure rules engine (debts, bankruptcy, auctions, house rules) +// MonopolyAI skill 1–5 decisions (buy, bid, build, raise funds, trade) +// MonopolyLayout every screen rect (Phaser-free, verified by tools/verifyMonopoly.js) +// MonopolyArt baked canvas textures (board, bills, deeds, furniture) +// MonopolyTray / MonopolyBank / MonopolyHud / MonopolyDialogs / MonopolyEndScreen +// MonopolyTrade the trading screens (mixed in) +// +// Flow: every state change goes through advance(), which first replays the +// engine's fx events (pawn walks, bills in flight, builds, deeds), then +// redraws, saves, and hands the next decision to the AI or waits for you. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { auth } from '../../services/auth.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { Tooltip } from '../../ui/Tooltip.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; import { - SPACES, RAILROADS, UTILITIES, PURCHASABLE, GROUPS, GROUP_COLORS, GROUP_HEX, - PLAYER_COLORS, PLAYER_COLOR_HEX, BAND_H, CORNER_SIZE, SPACE_W, BOARD_SIZE, - CHANCE_CARDS, CC_CARDS, CARD_FRAME, PAWN_FRAME, - spaceGeometry, spaceCenter, + SPACES, PURCHASABLE, PLAYER_COLORS, PLAYER_COLOR_HEX, CARD_FRAME, PAWN_FRAME, + DEFAULT_SETTINGS, DEFAULT_RULES, } from './MonopolyData.js'; +import * as L from './MonopolyLogic.js'; +import { chooseBuy, chooseBid, chooseJailAction, chooseManage, chooseDebtAction, nextThinkDelay } from './MonopolyAI.js'; import { - createInitialState, rollDice, resolveSpace, buyProperty, declineProperty, - placeBid, passAuction, buildHouse, buildHotel, sellHouse, sellHotel, - mortgageProperty, unmortgageProperty, payJailFine, useJailCard, - applyCardEffect, applyRent, endTurn, checkGameOver, calculateRent, - canBuildHouse, canBuildHotel, ownsGroup, netWorth, - isTradeable, validateTrade, applyTrade, -} from './MonopolyLogic.js'; -import { chooseBuy, chooseBid, chooseJailAction, chooseBuild, nextThinkDelay, evaluateTrade, buildAiTradeOffer } from './MonopolyAI.js'; + BOARD, BOARD_CX, BOARD_CY, DEPTH, ACTIONS, MENU_BTN, LEAVE_BTN, CHANCE_DECK, CC_DECK, DECK_W, DECK_H, + POT, THREAT_BOX, plaqueParts, spaceRect, spaceCenter, spaceRot, pawnSpot, jailSpot, bandSpot, flagSpot, sideOf, +} from './MonopolyLayout.js'; +import { prepareMonopolyArt, DECO, DISPLAY } from './MonopolyArt.js'; +import { DiceTray } from './MonopolyTray.js'; +import { Bank } from './MonopolyBank.js'; +import { Hud } from './MonopolyHud.js'; +import { buildDeedCard, destroyContainer, MODAL_W, MODAL_H } from './MonopolyDeed.js'; +import * as Dlg from './MonopolyDialogs.js'; +import { showEndScreen } from './MonopolyEndScreen.js'; +import * as Snd from './MonopolySound.js'; +import { applyTradeMixin } from './MonopolyTrade.js'; -// ── Layout ──────────────────────────────────────────────────────────────────── -const BL = 30; // board left -const BT = 120; // board top -const BS = BOARD_SIZE; // 840 - -// Right panel -const RP_X = BL + BS + 50; // 920 -const RP_W = GAME_WIDTH - RP_X - 20; // ~980 - -// Depth -const DEPTH = { bg:0, board:5, band:6, text:7, houses:10, pawns:15, ui:25, dice:40, popup:50, banner:90 }; - -// Center deck offset (must match drawCenterDecks constant) -const DECK_D = 130; - -// Property purchase modal -const MODAL_W = 340; -const MODAL_H = 500; -const MODAL_BAND_H = 80; -const MODAL_TARGET_X = GAME_WIDTH / 2; // 960 -const MODAL_TARGET_Y = GAME_HEIGHT / 2; // 540 -const MODAL_AUCTION_X = 680; -const MODAL_AUCTION_Y = 500; -const MODAL_AUCTION_SCALE = 0.80; - -// Pip positions for each die face (relative to die center) -const PIPS = { - 1: [[0,0]], - 2: [[-1,-1],[1,1]], - 3: [[-1,-1],[0,0],[1,1]], - 4: [[-1,-1],[1,-1],[-1,1],[1,1]], - 5: [[-1,-1],[1,-1],[0,0],[-1,1],[1,1]], - 6: [[-1,-1],[1,-1],[-1,0],[1,0],[-1,1],[1,1]], -}; +const SETTINGS_KEY = 'monopoly-settings'; +const SAVE_KEY = 'monopoly-save-v1'; +const PACE = { relaxed: 1.4, normal: 1, fast: 0.55 }; +const MODAL_X = BOARD_CX - 60, MODAL_Y = BOARD_CY; // the deed card sits over the board +const AUCTION_CARD = { x: 330, y: BOARD_CY, scale: 0.8 }; +const POPUP_D = DEPTH.popup + 20; export default class MonopolyGame extends Phaser.Scene { constructor() { super('MonopolyGame'); } init(data) { + this.initData = data; this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; this.humanSeat = 0; this.gs = null; this.busy = false; + this.paused = false; + this.dead = false; this.dyn = []; this.portraits = []; - this.pawns = {}; // seat → image/circle - this.dieGfx = []; // [die1Graphics, die2Graphics] - this.dieVals = [1,1]; - this.dicePositions = []; // [{cx,cy,angle}×2] — updated on each throw landing - this.diceAnimating = false; - this.cardPopup = null; // popup container - this.bidInput = 0; // human bid amount for auction - // Property purchase modal (managed outside dyn) + this.pawns = {}; + this.shadows = {}; + this.pawnPos = {}; + this.pawnInCell = {}; + this.moving = new Set(); + this.lastFx = 0; + this.cardAnimPlayed = false; + this.cardPopupObjs = []; + this.bidInput = 0; this.modalActive = false; - this.modalGfx = []; this.modalContainer = null; this.modalOverlay = null; this.modalSpaceIdx = null; this.modalOrigin = null; - // Card draw animation flag — suppresses static popup until animation finishes - this.cardAnimPlayed = false; - // Trade modal (self-contained overlay, like build/mortgage menus) + this.modal = null; // Front Desk / setup / resume / confirm + this.manageH = null; // manage / raise-funds sheet + this.endH = null; + this.outShown = false; + this.watching = false; + this.hoverCard = null; + this.aiManageCount = 0; + this.aiTraded = false; + this.lastSaved = null; + // trade screens (MonopolyTrade.js) this.tradeMenuOpen = false; this.tradeMenuObjs = []; this.tradeHoverCard = null; - this.tradeOffer = null; // { giveProps, getProps, giveCash, getCash } - this.tradeCounterparty = null; // selected opponent seat + this.tradeOffer = null; + this.tradeCounterparty = null; this.tradeDragGhost = null; - this._dragHintTween = null; // pulses draggable cards while offer is empty + this._dragHintTween = null; this._dragHintCards = []; - // AI-initiated trades: per-seat cooldown (in that seat's own turns) for proposing - // to the human, so each AI bothers the player at most once every other of its turns. this.humanTradeCooldown = {}; - // Counter-offer state (when the human counters an AI's incoming proposal) this.tradeCounterMode = false; this.tradeCounterFrom = null; - this._tradeResolve = null; // resolves the pending AI-proposal promise - this.tradeSummaryOpen = false; // incoming-proposal / AI-AI flash popup is showing + this._tradeResolve = null; + this.tradeSummaryOpen = false; + try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } + this.settings.rules = { ...DEFAULT_RULES, ...(this.settings.rules ?? {}) }; } create() { + this.cameras.main.setBackgroundColor('#06231a'); + this.events.once('shutdown', () => { this.dead = true; }); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + prepareMonopolyArt(this).then(() => { if (!this.dead) this.boot(); }); + } + + // ── Boot: resume or deal a new game ───────────────────────────────────────── + boot() { try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* */ } this.hasPawns = this.textures.exists('monopoly-pawns'); this.hasCards = this.textures.exists('monopoly-cards'); + this.buildRoom(); + const save = this.readSave(); + if (save) { + const g = save.gs; + const names = g.players.map((p) => p.name).join(', '); + this.modal = Dlg.openResume(this, { + depth: POPUP_D, + info: `A game is in progress at the Boardwalk Hotel — ${names}.\nRound ${g.round}, ${Dlg.rulesSummary(g.rules)}.`, + onResume: () => { this.modal = null; this.startFromSave(save); }, + onNew: () => { this.modal = null; this.openSetup(); }, + onLeave: () => this.leave(), + }); + } else { + this.openSetup(); + } + } + openSetup() { + this.modal = Dlg.openSetup(this, { + rules: this.settings.rules, depth: POPUP_D, + onStart: (rules) => { + this.modal = null; + this.settings.rules = rules; + this.saveSettings(); + this.clearSave(); + this.startNew(rules); + }, + onLeave: () => this.leave(), + }); + } + + startNew(rules) { const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); this.skillBySeat = {}; const names = []; @@ -121,2775 +162,1170 @@ export default class MonopolyGame extends Phaser.Scene { this.skillBySeat[seat] = Math.max(1, Math.min(5, opp?.skill ?? 3)); } } + this.gs = L.createInitialState({ playerCount, names, rules }); + this.lastFx = this.gs.fxSeq; + this.buildTable(); + if (rules.mode === 'short') Dlg.toast(this, 'Short Game — two deeds dealt to each player', { y: 520 }); + } - this.gs = createInitialState({ playerCount, names }); + startFromSave(save) { + this.opponents = save.opponents ?? this.opponents; + this.skillBySeat = save.skillBySeat; + this.humanTradeCooldown = save.humanTradeCooldown ?? {}; + this.gs = save.gs; + this.lastFx = this.gs.fxSeq; + this.buildTable(); + } - this.buildBackground(); - this.buildBoard(); - this.buildPawns(); - this.buildDiceDisplay(); + leave() { this.scene.start('GameMenu'); } + + // ── Static table ──────────────────────────────────────────────────────────── + buildRoom() { + const pf = this.playfield; + if (pf?.key && this.textures.exists(pf.key)) { + // a chosen playfield becomes the tablecloth; the parlour lamp still falls on it + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.bg); + this.add.image(0, 0, 'mono-room').setOrigin(0).setDepth(DEPTH.bg + 0.5).setAlpha(0.45); + } else { + this.add.image(0, 0, 'mono-room').setOrigin(0).setDepth(DEPTH.bg); + } + this.add.image(BOARD.x, BOARD.y, 'mono-board').setOrigin(0).setDisplaySize(BOARD.w, BOARD.h).setDepth(DEPTH.board); + // the two decks, a few cards thick + for (const [deck, key] of [[CHANCE_DECK, 'mono-back-chance'], [CC_DECK, 'mono-back-cc']]) { + for (let k = 3; k >= 0; k--) { + this.add.image(deck.x + k * 1.6, deck.y + k * 2, key).setDisplaySize(DECK_W, DECK_H).setRotation(deck.rot) + .setDepth(DEPTH.board + 1 + (3 - k) * 0.01).setTint(k ? 0xb8a890 : 0xffffff); + } + } + } + + buildTable() { + const gs = this.gs; + // pawns + for (let seat = 0; seat < gs.playerCount; seat++) { + this.shadows[seat] = this.add.image(0, 0, 'mono-shadow').setDisplaySize(40, 16).setDepth(DEPTH.pawnShadow); + if (this.hasPawns) { + this.pawns[seat] = this.add.image(0, 0, 'monopoly-pawns', PAWN_FRAME(seat)).setDisplaySize(46, 46).setDepth(DEPTH.pawns); + } else { + const g = this.add.graphics().setDepth(DEPTH.pawns); + g.fillStyle(PLAYER_COLORS[seat], 1).fillCircle(0, 0, 15); + g.lineStyle(3, 0xffffff, 0.9).strokeCircle(0, 0, 15); + this.pawns[seat] = g; + } + this.pawnPos[seat] = gs.players[seat].position; + this.pawnInCell[seat] = gs.players[seat].jailed; + } + this.tray = new DiceTray(this, DEPTH.tray, { onClick: () => this.onRollDice() }).build(); + if (gs.diceRoll) this.tray.show(gs.diceRoll[0], gs.diceRoll[1]); + this.bank = new Bank(this, DEPTH.hud).build(); + this.hud = new Hud(this, { + humanSeat: this.humanSeat, playerCount: gs.playerCount, + onDeedHover: (i) => this.showHoverDeed(i), + onDeedOut: () => this.hideHoverDeed(), + onDeedClick: (i) => this.onSpaceClick(i), + }).build(gs); + this.hud.setModeText(Dlg.rulesSummary(gs.rules)); + this.hud.setLedgerVisible(this.settings.ledger); + this.add.image(ACTIONS.x - 20, ACTIONS.y - 20, 'mono-actions').setOrigin(0).setDepth(DEPTH.hud); this.buildPortraits(); - - new Button(this, GAME_WIDTH - 80, GAME_HEIGHT - 36, 'Leave', - () => this.scene.start('GameMenu'), - { variant:'ghost', width:120, height:40, fontSize:18 }).setDepth(DEPTH.ui); - + new Button(this, MENU_BTN.x, MENU_BTN.y, 'Menu', () => this.openFrontDesk(), { width: 110, height: 32, fontSize: 15, bg: 0x4a2e1a }).setDepth(DEPTH.hudText); + new Button(this, LEAVE_BTN.x, LEAVE_BTN.y, 'Leave', () => this.leave(), { width: 110, height: 32, fontSize: 15, variant: 'ghost' }).setDepth(DEPTH.hudText); + // hover / click zones over the 40 spaces + this.tooltip = new Tooltip(this, { depth: DEPTH.tooltip }); + for (let i = 0; i < 40; i++) { + const r = spaceRect(i); + const z = this.add.zone(r.x + r.w / 2, r.y + r.h / 2, r.w, r.h).setDepth(DEPTH.pawns + 1).setInteractive(); + z.on('pointerover', () => this.showHoverDeed(i)); + z.on('pointerout', () => this.hideHoverDeed()); + z.on('pointerdown', () => this.onSpaceClick(i)); + } + this.statusText = this.add.text(ACTIONS.x + ACTIONS.w / 2, ACTIONS.y + 40, '', { + fontFamily: DECO, fontSize: '16px', color: '#ecd690', align: 'center', wordWrap: { width: ACTIONS.w - 50 }, + }).setOrigin(0.5).setDepth(DEPTH.hudText); + this.tableBuilt = true; this.render(); this.advance(); } - // ── Background ────────────────────────────────────────────────────────────── - buildBackground() { - const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH/2, GAME_HEIGHT/2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.bg); - } else { - const g = this.add.graphics().setDepth(DEPTH.bg); - g.fillGradientStyle(0x1a1508, 0x1a1508, 0x0a0805, 0x0a0805, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - } - this.add.text(BL + BS/2, 60, 'Monopoly', { - fontFamily:'Righteous', fontSize:'52px', color:'#E8C12C', - }).setOrigin(0.5).setDepth(DEPTH.ui); - } - - // ── Static Board ──────────────────────────────────────────────────────────── - buildBoard() { - const g = this.add.graphics().setDepth(DEPTH.board); - // Outer board background - g.fillStyle(0xFFF8E7, 1); - g.fillRect(BL, BT, BS, BS); - g.lineStyle(3, 0x2c1810, 1); - g.strokeRect(BL, BT, BS, BS); - - // Center area - const cx = BL + CORNER_SIZE; - const cy = BT + CORNER_SIZE; - const cw = BS - 2 * CORNER_SIZE; - g.fillStyle(0xFFF0D0, 1); - g.fillRect(cx, cy, cw, cw); - - // Center MONOPOLY logo - this.add.text(BL + BS/2, BT + BS/2 - 30, 'MONOPOLY', { - fontFamily:'Righteous', fontSize:'52px', color:'#B71C1C', stroke:'#7f1010', strokeThickness:3, - }).setOrigin(0.5).setDepth(DEPTH.text); - this.add.text(BL + BS/2, BT + BS/2 + 32, '🎩 THE CLASSIC BOARD GAME', { - fontFamily:'"Julius Sans One"', fontSize:'14px', color:'#555544', - }).setOrigin(0.5).setDepth(DEPTH.text); - - // Draw all 40 spaces - for (let i = 0; i < 40; i++) this.drawBoardSpace(g, i); - - this.drawCenterDecks(); - } - - drawCenterDecks() { - const cx = BL + BS / 2; // 450 - const cy = BT + BS / 2; // 540 - // Chance: lower-left, orange; Community Chest: upper-right, blue - this._drawCardDeck(cx - DECK_D, cy + DECK_D, 88, 126, -0.14, 0xE77A2C, 'Chance'); - this._drawCardDeck(cx + DECK_D, cy - DECK_D, 88, 126, 0.12, 0x1565C0, 'Community\nChest'); - } - - _drawCardDeck(x, y, w, h, rot, color, label) { - // Darken the base color for shadow card layers - const dr = (((color >> 16) & 0xFF) * 0.60) | 0; - const dg = (((color >> 8) & 0xFF) * 0.60) | 0; - const db = ((color & 0xFF) * 0.60) | 0; - const dark = (dr << 16) | (dg << 8) | db; - - const container = this.add.container(x, y).setDepth(DEPTH.text).setRotation(rot); - - // Shadow card layers — offset downward-right to simulate deck thickness - for (let i = 3; i >= 1; i--) { - const sg = this.add.graphics(); - sg.fillStyle(dark, 1); - sg.lineStyle(1, 0x1a1208, 0.6); - sg.fillRoundedRect(-w / 2 + i * 2, -h / 2 + i * 2, w, h, 5); - sg.strokeRoundedRect(-w / 2 + i * 2, -h / 2 + i * 2, w, h, 5); - container.add(sg); - } - - // Top card body - const bg = this.add.graphics(); - bg.fillStyle(color, 1); - bg.lineStyle(2, 0x1a1208, 1); - bg.fillRoundedRect(-w / 2, -h / 2, w, h, 5); - bg.strokeRoundedRect(-w / 2, -h / 2, w, h, 5); - container.add(bg); - - // Inner cream border - const bdr = this.add.graphics(); - bdr.lineStyle(1.5, 0xFFF8E7, 0.85); - bdr.strokeRoundedRect(-w / 2 + 6, -h / 2 + 6, w - 12, h - 12, 3); - container.add(bdr); - - // Label - const txt = this.add.text(0, 0, label, { - fontFamily: 'Righteous', - fontSize: '11px', - color: '#FFFFFF', - align: 'center', - stroke: '#00000055', - strokeThickness: 1, - }).setOrigin(0.5); - container.add(txt); - } - - drawBoardSpace(g, idx) { - const geo = spaceGeometry(idx); - const bx = BL + geo.x, by = BT + geo.y; - const sp = SPACES[idx]; - - // Space background - g.fillStyle(0xFFF8E7, 1); - g.fillRect(bx, by, geo.w, geo.h); - g.lineStyle(1, 0x2c1810, 1); - g.strokeRect(bx, by, geo.w, geo.h); - - if (geo.isCorner) { - this.drawCornerSpace(g, idx, bx, by, geo.w, geo.h); - return; - } - - // Color band for properties - if (sp.group && GROUP_COLORS[sp.group]) { - const col = GROUP_COLORS[sp.group]; - g.fillStyle(col, 1); - switch (geo.bandEdge) { - case 'top': g.fillRect(bx, by, geo.w, BAND_H); break; - case 'bottom': g.fillRect(bx, by + geo.h - BAND_H, geo.w, BAND_H); break; - case 'left': g.fillRect(bx, by, BAND_H, geo.h); break; - case 'right': g.fillRect(bx + geo.w - BAND_H, by, BAND_H, geo.h); break; - } - g.lineStyle(1, 0x2c1810, 1); - switch (geo.bandEdge) { - case 'top': g.strokeRect(bx, by, geo.w, BAND_H); break; - case 'bottom': g.strokeRect(bx, by + geo.h - BAND_H, geo.w, BAND_H); break; - case 'left': g.strokeRect(bx, by, BAND_H, geo.h); break; - case 'right': g.strokeRect(bx + geo.w - BAND_H, by, BAND_H, geo.h); break; - } - } - - // Space name - const cx = bx + geo.w / 2; - const cy = by + geo.h / 2; - const ww = geo.rotation === 0 || geo.rotation === Math.PI ? geo.w - 6 : geo.h - 6; - const nameText = this.add.text(cx, cy, sp.name, { - fontFamily:'"Julius Sans One"', fontSize:'8px', color:'#1a1208', - align:'center', wordWrap:{ width: ww, useAdvancedWrap:true }, - }).setOrigin(0.5).setRotation(geo.rotation).setDepth(DEPTH.text); - - // Price/amount below name - let sub = ''; - if (sp.type === 'property') sub = `$${sp.price}`; - else if (sp.type === 'railroad') sub = `$${sp.price}`; - else if (sp.type === 'utility') sub = `$${sp.price}`; - else if (sp.type === 'tax') sub = `$${sp.amount}`; - - if (sub) { - // Offset price below name, accounting for rotation - const offsetAlong = geo.rotation === 0 ? { x:0, y:20 } - : geo.rotation === Math.PI ? { x:0, y:-20 } - : geo.rotation === Math.PI/2 ? { x:-20, y:0 } - : { x:20, y:0 }; - this.add.text(cx + offsetAlong.x, cy + offsetAlong.y, sub, { - fontFamily:'"Julius Sans One"', fontSize:'7px', color:'#444433', - }).setOrigin(0.5).setRotation(geo.rotation).setDepth(DEPTH.text); - } - - // Railroad indicator - if (sp.type === 'railroad') { - const g2 = this.add.graphics().setDepth(DEPTH.text); - g2.fillStyle(0x1a1208, 1); - // Small locomotive silhouette: just a rounded rect - const rw = 20, rh = 12; - g2.fillRoundedRect(cx - rw/2, cy - 14 - rh/2, rw, rh, 3); - g2.fillRect(cx - 8, cy - 14 + rh/2, 16, 4); - } - - // Utility indicator - if (sp.type === 'utility') { - const g2 = this.add.graphics().setDepth(DEPTH.text); - const isElectric = idx === 12; - g2.fillStyle(isElectric ? 0xFFD700 : 0x1565C0, 1); - g2.fillCircle(cx, cy - 12, 9); - g2.lineStyle(2, 0x1a1208, 1); - g2.strokeCircle(cx, cy - 12, 9); - } - } - - drawCornerSpace(g, idx, bx, by, w, h) { - const mid = { x: bx + w/2, y: by + h/2 }; - switch (idx) { - case 0: { // Go - g.fillStyle(0x1B5E20, 1); - g.fillRect(bx, by, w, 3); - g.fillRect(bx, by, 3, h); - this.add.text(bx + w/2, by + h/2 - 10, 'GO', { - fontFamily:'Righteous', fontSize:'24px', color:'#B71C1C', - }).setOrigin(0.5).setDepth(DEPTH.text); - this.add.text(bx + w/2, by + h/2 + 16, 'COLLECT\n$200 SALARY', { - fontFamily:'"Julius Sans One"', fontSize:'8px', color:'#1B5E20', align:'center', - }).setOrigin(0.5).setDepth(DEPTH.text); - // Arrow - const ag = this.add.graphics().setDepth(DEPTH.text); - ag.fillStyle(0x1B5E20, 1); - ag.fillTriangle(bx+14, by+h-14, bx+28, by+h-28, bx+28, by+h-14); - break; - } - case 10: { // Jail - // Just Visiting bar - g.fillStyle(0xE8C12C, 1); - g.fillRect(bx+3, by+3, w-6, 6); - this.add.text(bx + w/2, by + h*0.3, 'JUST\nVISITING', { - fontFamily:'"Julius Sans One"', fontSize:'8px', color:'#1a1208', align:'center', - }).setOrigin(0.5).setDepth(DEPTH.text); - // Jail bars - const jg = this.add.graphics().setDepth(DEPTH.text); - jg.lineStyle(2, 0x555544, 1); - for (let bar = 0; bar < 4; bar++) { - const bx2 = bx + 14 + bar * 14; - jg.lineBetween(bx2, by + h*0.5, bx2, by + h*0.85); - } - jg.lineBetween(bx+10, by+h*0.5, bx+66, by+h*0.5); - jg.lineBetween(bx+10, by+h*0.85, bx+66, by+h*0.85); - this.add.text(bx + w/2, by + h*0.7, 'JAIL', { - fontFamily:'Righteous', fontSize:'14px', color:'#E53935', - }).setOrigin(0.5).setDepth(DEPTH.text + 1); - break; - } - case 20: { // Free Parking - this.add.text(bx + w/2, by + h/2 - 14, 'FREE', { - fontFamily:'Righteous', fontSize:'18px', color:'#E77A2C', - }).setOrigin(0.5).setDepth(DEPTH.text); - this.add.text(bx + w/2, by + h/2 + 4, 'PARKING', { - fontFamily:'Righteous', fontSize:'13px', color:'#E77A2C', - }).setOrigin(0.5).setDepth(DEPTH.text); - // Car icon - const cg = this.add.graphics().setDepth(DEPTH.text); - cg.fillStyle(0x1565C0, 1); - cg.fillRoundedRect(bx+22, by+h-30, 60, 16, 4); - cg.fillRoundedRect(bx+30, by+h-42, 44, 14, 4); - cg.fillStyle(0x1a1208, 1); - cg.fillCircle(bx+32, by+h-14, 5); - cg.fillCircle(bx+72, by+h-14, 5); - break; - } - case 30: { // Go to Jail - g.fillStyle(0xE53935, 1); - g.fillRect(bx, by+h-3, w, 3); - g.fillRect(bx+w-3, by, 3, h); - this.add.text(bx + w/2, by + h/2 - 20, 'GO TO\nJAIL', { - fontFamily:'Righteous', fontSize:'16px', color:'#E53935', align:'center', - }).setOrigin(0.5).setDepth(DEPTH.text); - // Police badge - const pg = this.add.graphics().setDepth(DEPTH.text); - pg.fillStyle(0xE8C12C, 1); - pg.fillCircle(bx + w/2, by + h/2 + 20, 18); - pg.lineStyle(2, 0x1a1208, 1); - pg.strokeCircle(bx + w/2, by + h/2 + 20, 18); - this.add.text(bx + w/2, by + h/2 + 20, '🚔', { fontSize:'18px' }).setOrigin(0.5).setDepth(DEPTH.text+1); - break; - } - } - } - - // ── Pawns (created once, positioned dynamically) ──────────────────────────── - buildPawns() { - for (let seat = 0; seat < this.gs.playerCount; seat++) { - const { x, y } = this.spacePxCenter(0); // start at Go - let pawn; - if (this.hasPawns) { - pawn = this.add.image(x, y, 'monopoly-pawns', PAWN_FRAME(seat)) - .setDisplaySize(32, 32).setDepth(DEPTH.pawns); - } else { - const g = this.add.graphics().setDepth(DEPTH.pawns); - g.fillStyle(PLAYER_COLORS[seat], 1); - g.fillCircle(0, 0, 12); - g.lineStyle(2, 0xffffff, 0.8); - g.strokeCircle(0, 0, 12); - g.x = x; g.y = y; - pawn = g; - } - this.pawns[seat] = pawn; - } - } - - // ── Dice Display (created once in right panel) ────────────────────────────── - buildDiceDisplay() { - const dx = RP_X + RP_W/2 - 55; - const dy = BT + this.playerPanelTotalH() + 30; - this.diceY = dy; - this.dicePositions = [ - { cx: dx, cy: dy, angle: 0 }, - { cx: dx + 84, cy: dy, angle: 0 }, - ]; - this.dieGfx = [ - this.add.graphics().setDepth(DEPTH.dice), - this.add.graphics().setDepth(DEPTH.dice), - ]; - this.drawDie(0, dx, dy, 1); - this.drawDie(1, dx + 84, dy, 1); - } - - playerPanelTotalH() { - const n = this.gs.playerCount; - const rows = Math.ceil(n / 2); - return rows * 190 + (rows - 1) * 12 + 20; - } - - drawDie(idx, cx, cy, value, angle = 0) { - const g = this.dieGfx[idx]; - const size = 66; - const half = size / 2; - g.clear(); - g.setPosition(cx, cy); - g.setAngle(angle); - g.fillStyle(0xFFF8E7, 1); - g.fillRoundedRect(-half, -half, size, size, 10); - g.lineStyle(2, 0x4A3728, 1); - g.strokeRoundedRect(-half, -half, size, size, 10); - // Pips drawn in local space (centered at origin) - g.fillStyle(0x1a1208, 1); - const pipR = 5; - const step = 18; - const pips = PIPS[value] ?? PIPS[1]; - for (const [px, py] of pips) { - g.fillCircle(px * step, py * step, pipR); - } - } - - // ── Portraits ────────────────────────────────────────────────────────────── buildPortraits() { - const n = this.gs.playerCount; - for (let seat = 0; seat < n; seat++) { - const { px, py } = this.panelPos(seat); - const portraitR = 40; - if (seat === this.humanSeat) { - this.portraits[seat] = createPlayerPortrait(this, px + 16 + portraitR, py + 16 + portraitR, portraitR, DEPTH.ui+1, 'MonopolyGame'); - } else { - const opp = this.opponents[seat - 1]; - this.portraits[seat] = createOpponentPortrait(this, opp, px + 16 + portraitR, py + 16 + portraitR, portraitR, DEPTH.ui+1); - } + for (let seat = 0; seat < this.gs.playerCount; seat++) { + const { portrait: P } = plaqueParts(seat); + try { + if (seat === this.humanSeat) this.portraits[seat] = createPlayerPortrait(this, P.x, P.y, P.r, DEPTH.hud + 1, 'MonopolyGame'); + else this.portraits[seat] = createOpponentPortrait(this, this.opponents[seat - 1], P.x, P.y, P.r, DEPTH.hud + 1); + } catch (_) { /* portraits are decoration */ } } } - panelPos(seat) { - const col = seat % 2; - const row = Math.floor(seat / 2); - const panelW = this.gs.playerCount <= 2 ? RP_W - 10 : Math.floor((RP_W - 10) / 2); - const px = RP_X + col * (panelW + 10); - const py = BT + row * (190 + 12); - return { px, py, panelW, panelH: 182 }; + overlayOpen() { + return !!(this.modalActive || this.tradeMenuOpen || this.tradeSummaryOpen || (this.gs?.pendingCard && this.gs.phase === 'card') + || this.modal || this.manageH || this.endH || this.cardAnimating); + } + hidePortraits() { this.portraits.forEach((p) => { if (p?.hide) p.hide(); }); } + showPortraits() { this.portraits.forEach((p) => { if (p?.show) p.show(); }); } + refreshPortraits() { if (this.overlayOpen()) this.hidePortraits(); else this.showPortraits(); } + + // ── Settings & saves ──────────────────────────────────────────────────────── + saveSettings() { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } } + + readSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || s.gs?.version !== 2 || s.gs.phase === 'gameover') return null; + return s; + } catch (_) { return null; } } - // ── Dynamic Render ───────────────────────────────────────────────────────── - reg(o) { this.dyn.push(o); return o; } - clearDyn() { this.dyn.forEach(o => { try { o.destroy(); } catch {} }); this.dyn = []; } + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } - hidePortraits() { this.portraits.forEach(p => { if (p?.hide) p.hide(); }); } - showPortraits() { this.portraits.forEach(p => { if (p?.show) p.show(); }); } + maybeSave() { + if (!this.gs || this.gs === this.lastSaved) return; + this.lastSaved = this.gs; + if (this.gs.phase === 'gameover') { this.clearSave(); return; } + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ + v: 1, gs: this.gs, opponents: this.opponents, skillBySeat: this.skillBySeat, + humanTradeCooldown: this.humanTradeCooldown, savedAt: Date.now(), + })); + } catch (_) { /* storage full / private mode */ } + } + // ── Helpers ───────────────────────────────────────────────────────────────── + reg(o) { this.dyn.push(o); return o; } + clearDyn() { this.dyn.forEach((o) => { try { o.destroy(); } catch { /* */ } }); this.dyn = []; } + delay(ms) { return new Promise((r) => this.time.delayedCall(Math.max(0, ms), r)); } + pace() { return PACE[this.settings.pace] ?? 1; } + isFast(seat = this.gs?.current) { return this.settings.skipAI && (seat !== this.humanSeat || this.watching); } + humanActing() { return this.gs && this.gs.phase !== 'gameover' && L.actingSeat(this.gs) === this.humanSeat && this.gs.players[this.humanSeat].active; } + anchorOf(who) { + if (typeof who === 'number') return this.hud.anchor(who); + if (who === 'pot') return { x: POT.x, y: POT.y }; + return this.bank.anchor(); + } + + // ── Render ────────────────────────────────────────────────────────────────── render() { + if (!this.tableBuilt) return; this.clearDyn(); - this.drawHousesHotels(); + this.drawBoardState(); this.positionPawns(); - this.drawPlayerPanels(); + this.hud.update(this.gs, { activeSeat: this.gs.current, actingSeat: L.actingSeat(this.gs), rails: !this.inFx }); + this.bank.update(this.gs); + if (!this.inFx) this.bank.updatePot(this.gs); this.drawActionBar(); - if (this.gs.pendingCard && this.cardAnimPlayed) this.drawCardPopup(); + this.drawThreat(); + this.drawCardPopup(); if (this.gs.phase === 'auction' && this.gs.pendingAuction) this.drawAuctionPanel(); if (this.modalActive && this.gs.phase === 'buy') this.drawModalBuyButtons(); - // DOM video portraits always render above canvas — hide them during any overlay - if (this.gs.pendingCard || this.modalActive || this.tradeMenuOpen || this.tradeSummaryOpen) this.hidePortraits(); - else this.showPortraits(); + this.tray.setEnabled(this.canHumanRoll()); + this.refreshPortraits(); + // state changed outside advance() (e.g. a trade) — let its fx play + if (!this.busy && this.hasUnplayedFx() && !this._fxKick) { + this._fxKick = true; + this.time.delayedCall(0, () => { this._fxKick = false; this.advance(); }); + } } - drawHousesHotels() { - const g = this.reg(this.add.graphics().setDepth(DEPTH.houses)); + drawBoardState() { + const g = this.reg(this.add.graphics().setDepth(DEPTH.owner)); + // builds / purchases still waiting to be animated are held back so they + // appear when their animation lands, not before + const pendingHouses = {}, pendingHotel = new Set(), pendingDeed = new Set(); + for (const e of this.gs.fx) { + if (e.id <= this.lastFx) continue; + if (e.type === 'build' && e.kind === 'house') pendingHouses[e.idx] = (pendingHouses[e.idx] ?? 0) + 1; + if (e.type === 'build' && e.kind === 'hotel') pendingHotel.add(e.idx); + if (e.type === 'deed') pendingDeed.add(e.idx); + } for (const idx of PURCHASABLE) { - const own = this.gs.board[idx]; - if (!own || own.mortgaged) { - if (own?.mortgaged) { - // Show mortgage stripe - const geo = spaceGeometry(idx); - const bx = BL + geo.x, by = BT + geo.y; - g.fillStyle(0x888888, 0.4); - g.fillRect(bx, by, geo.w, geo.h); - } - continue; - } - if (own.owner !== null) { - // Subtle ownership tint over the cream background - const geo = spaceGeometry(idx); - const bx = BL + geo.x, by = BT + geo.y; - g.fillStyle(PLAYER_COLORS[own.owner], 0.20); - g.fillRect(bx, by, geo.w, geo.h); + const real = this.gs.board[idx]; + if (real.owner === null || pendingDeed.has(idx)) continue; + const own = { ...real }; + if (pendingHotel.has(idx)) { own.hotel = false; own.houses = L.housesForHotel(this.gs); } + if (pendingHouses[idx]) own.houses = Math.max(0, own.houses - pendingHouses[idx]); + const r = spaceRect(idx); + const side = sideOf(idx); + const f = flagSpot(idx); + // owner's colour strip on the outer edge, with a little brass pin + const horiz = side === 0 || side === 2; + const [fw, fh] = horiz ? [r.w - 18, 8] : [8, r.h - 18]; + g.fillStyle(0x000000, 0.25).fillRoundedRect(f.x - fw / 2 + 1, f.y - fh / 2 + 2, fw, fh, 3); + g.fillStyle(PLAYER_COLORS[own.owner], 1).fillRoundedRect(f.x - fw / 2, f.y - fh / 2, fw, fh, 3); + g.lineStyle(1, 0xffffff, 0.7).strokeRoundedRect(f.x - fw / 2, f.y - fh / 2, fw, fh, 3); + if (own.mortgaged) { + g.fillStyle(0x3a2a1a, 0.42).fillRect(r.x + 1, r.y + 1, r.w - 2, r.h - 2); + const c = spaceCenter(idx); + this.reg(this.add.text(c.x, c.y, 'MORTGAGED', { + fontFamily: DISPLAY, fontSize: '13px', color: '#ffdfd6', backgroundColor: '#8e1f1f', padding: { x: 4, y: 1 }, + }).setOrigin(0.5).setRotation(spaceRot(idx) + (horiz ? -0.35 : 0.35)).setDepth(DEPTH.owner + 0.5)); } if (own.hotel) { - this.drawHotelOnSpace(g, idx); + const p = bandSpot(idx, 0, 1); + this.reg(this.add.image(p.x, p.y - 2, 'mono-hotel').setDisplaySize(32, 21).setDepth(DEPTH.build)); } else if (own.houses > 0) { - this.drawHousesOnSpace(g, idx, own.houses); + for (let k = 0; k < own.houses; k++) { + const p = bandSpot(idx, k, own.houses, 17); + this.reg(this.add.image(p.x, p.y - 2, 'mono-house').setDisplaySize(19, 19).setDepth(DEPTH.build + k * 0.01)); + } } } } - drawHousesOnSpace(g, idx, count) { - const geo = spaceGeometry(idx); - const bx = BL + geo.x, by = BT + geo.y; - const hw = 10, hh = 12; - const totalW = count * hw + (count - 1) * 2; - let sx, sy; - switch (geo.bandEdge) { - case 'top': sx = bx + (geo.w - totalW)/2; sy = by + geo.h - hh - 3; break; - case 'bottom': sx = bx + (geo.w - totalW)/2; sy = by + 3; break; - case 'left': sx = bx + geo.w - hh - 3; sy = by + (geo.h - totalW)/2; break; - case 'right': sx = bx + 3; sy = by + (geo.h - totalW)/2; break; - default: sx = bx + 4; sy = by + geo.h - hh - 3; - } - g.fillStyle(0x1B5E20, 1); - g.lineStyle(1, 0xffffff, 0.8); - for (let i = 0; i < count; i++) { - if (geo.bandEdge === 'left' || geo.bandEdge === 'right') { - g.fillRect(sx, sy + i * (hw+2), hh, hw); - g.strokeRect(sx, sy + i * (hw+2), hh, hw); - } else { - g.fillRect(sx + i * (hw+2), sy, hw, hh); - g.strokeRect(sx + i * (hw+2), sy, hw, hh); - } - } - } - - drawHotelOnSpace(g, idx) { - const geo = spaceGeometry(idx); - const bx = BL + geo.x, by = BT + geo.y; - const hw = 20, hh = 14; - let hx, hy; - switch (geo.bandEdge) { - case 'top': hx = bx + (geo.w - hw)/2; hy = by + geo.h - hh - 3; break; - case 'bottom': hx = bx + (geo.w - hw)/2; hy = by + 3; break; - case 'left': hx = bx + geo.w - hh - 3; hy = by + (geo.h - hw)/2; break; - case 'right': hx = bx + 3; hy = by + (geo.h - hw)/2; break; - default: hx = bx + 4; hy = by + geo.h - hh - 3; - } - g.fillStyle(0xB71C1C, 1); - g.lineStyle(1, 0xffffff, 0.8); - if (geo.bandEdge === 'left' || geo.bandEdge === 'right') { - g.fillRect(hx, hy, hh, hw); - g.strokeRect(hx, hy, hh, hw); - } else { - g.fillRect(hx, hy, hw, hh); - g.strokeRect(hx, hy, hw, hh); - } - } - positionPawns() { const gs = this.gs; - const seated = {}; // position → count of seated players + const groups = {}; for (let seat = 0; seat < gs.playerCount; seat++) { - if (gs.players[seat].bankrupt) { - if (this.pawns[seat]) { try { this.pawns[seat].setVisible(false); } catch {} } + if (gs.players[seat].bankrupt && !this.moving.has(seat)) { + this.pawns[seat]?.setVisible(false); this.shadows[seat]?.setVisible(false); continue; } - const pos = gs.players[seat].position; - seated[pos] = (seated[pos] ?? 0) + 1; + const pos = this.pawnPos[seat]; + const key = pos === 10 ? (this.pawnInCell[seat] ? 'cell' : 'visit') : String(pos); + (groups[key] ??= []).push(seat); } - const placed = {}; - for (let seat = 0; seat < gs.playerCount; seat++) { - if (gs.players[seat].bankrupt) continue; - const pos = gs.players[seat].position; - const { x, y } = this.spacePxCenter(pos); - const n = seated[pos] ?? 1; - const i = placed[pos] ?? 0; - placed[pos] = i + 1; - const offsets = this.pawnOffsets(n); - const pawn = this.pawns[seat]; - if (!pawn) continue; - try { - pawn.setVisible(true); - if (typeof pawn.setPosition === 'function') pawn.setPosition(x + offsets[i].x, y + offsets[i].y); - else { pawn.x = x + offsets[i].x; pawn.y = y + offsets[i].y; } - } catch {} + for (const [key, seats] of Object.entries(groups)) { + seats.forEach((seat, k) => { + if (this.moving.has(seat)) return; + const pt = key === 'cell' ? jailSpot(k, seats.length, true) + : key === 'visit' ? jailSpot(k, seats.length, false) + : pawnSpot(Number(key), k, seats.length); + this.placePawn(seat, pt.x, pt.y); + }); } } - pawnOffsets(n) { - const offsets = [ - [{x:0,y:0}], - [{x:-8,y:0},{x:8,y:0}], - [{x:-8,y:-6},{x:8,y:-6},{x:0,y:8}], - [{x:-8,y:-6},{x:8,y:-6},{x:-8,y:8},{x:8,y:8}], - ]; - return offsets[Math.min(n,4) - 1] ?? offsets[0]; + placePawn(seat, x, y, lift = 0) { + const p = this.pawns[seat], s = this.shadows[seat]; + if (!p) return; + p.setVisible(true); s.setVisible(true); + p.x = x; p.y = y - 6 - lift; + s.x = x + 2; s.y = y + 14; + s.setAlpha(Math.max(0.25, 0.8 - lift / 60)); + p.setDepth(DEPTH.pawns + y * 0.0001 + (lift > 0 ? 0.5 : 0)); } - spacePxCenter(idx) { - const c = spaceCenter(idx); - return { x: BL + c.x, y: BT + c.y }; + // ── Action panel ──────────────────────────────────────────────────────────── + canHumanRoll() { + const gs = this.gs; + return !this.busy && !this.paused && !this.overlayOpen() && gs.phase === 'preroll' && gs.current === this.humanSeat && gs.players[this.humanSeat].active; } - // ── Player Panels ────────────────────────────────────────────────────────── - drawPlayerPanels() { - const n = this.gs.playerCount; - for (let seat = 0; seat < n; seat++) { - this.drawOnePanel(seat); - } + canManage() { + const gs = this.gs; + if (!this.humanActing() || this.busy) return false; + if (gs.phase === 'debt') return true; // the Raise Funds sheet (bankruptcy lives there too) + return ['preroll', 'endturn', 'buy'].includes(gs.phase) && L.ownedBy(gs, this.humanSeat).length > 0; } - drawOnePanel(seat) { - const { px, py, panelW, panelH } = this.panelPos(seat); - const p = this.gs.players[seat]; - const isCurrent = this.gs.current === seat && this.gs.phase !== 'gameover'; - const g = this.reg(this.add.graphics().setDepth(DEPTH.ui)); - - // Panel background - const bg = isCurrent ? 0x2a2010 : 0x1e1a12; - g.fillStyle(bg, 1); - g.fillRoundedRect(px, py, panelW, panelH, 8); - g.lineStyle(2, isCurrent ? COLORS.gold : COLORS.accent, isCurrent ? 1 : 0.5); - g.strokeRoundedRect(px, py, panelW, panelH, 8); - - if (p.bankrupt) { - this.reg(this.add.text(px + panelW/2, py + panelH/2, 'BANKRUPT', { - fontFamily:'Righteous', fontSize:'22px', color:COLORS.dangerHex, - }).setOrigin(0.5).setDepth(DEPTH.ui+1)); - return; - } - - // Name - const nameColor = isCurrent ? COLORS.goldHex : COLORS.textHex; - this.reg(this.add.text(px + 96, py + 14, p.name, { - fontFamily:'Righteous', fontSize:'17px', color: nameColor, - }).setOrigin(0, 0).setDepth(DEPTH.ui+1)); - - // Cash - this.reg(this.add.text(px + 96, py + 36, `$${p.cash.toLocaleString()}`, { - fontFamily:'"Julius Sans One"', fontSize:'26px', color:'#7fb87f', - }).setOrigin(0, 0).setDepth(DEPTH.ui+1)); - - // Net worth - const nw = netWorth(this.gs, seat); - this.reg(this.add.text(px + 96, py + 72, `Net: $${nw.toLocaleString()}`, { - fontFamily:'"Julius Sans One"', fontSize:'13px', color:COLORS.mutedHex, - }).setOrigin(0, 0).setDepth(DEPTH.ui+1)); - - // Jail indicator - if (p.jailed) { - this.reg(this.add.text(px + 96, py + 90, '🔒 In Jail', { - fontFamily:'"Julius Sans One"', fontSize:'12px', color:COLORS.dangerHex, - }).setOrigin(0, 0).setDepth(DEPTH.ui+1)); - } - - // GOOJF card indicator - if (p.getOutOfJailFree > 0) { - this.reg(this.add.text(px + 96, py + (p.jailed ? 106 : 90), `🎴 ×${p.getOutOfJailFree}`, { - fontFamily:'"Julius Sans One"', fontSize:'11px', color:'#aaccaa', - }).setOrigin(0, 0).setDepth(DEPTH.ui+1)); - } - - // Property color swatches - let sx = px + 96, sy = py + panelH - 26; - for (const [group, idxArr] of Object.entries(GROUPS)) { - const owned = idxArr.filter(i => this.gs.board[i]?.owner === seat).length; - if (owned === 0) continue; - const hasAll = owned === idxArr.length; - g.fillStyle(GROUP_COLORS[group], hasAll ? 1 : 0.4); - g.fillRoundedRect(sx, sy, 16, 14, 3); - g.lineStyle(1, 0xffffff, 0.5); - g.strokeRoundedRect(sx, sy, 16, 14, 3); - sx += 20; - } - // Railroads - const rrOwned = RAILROADS.filter(i => this.gs.board[i]?.owner === seat).length; - if (rrOwned > 0) { - this.reg(this.add.text(sx, sy + 2, `🚂×${rrOwned}`, { - fontFamily:'"Julius Sans One"', fontSize:'11px', color:COLORS.mutedHex, - }).setOrigin(0,0).setDepth(DEPTH.ui+1)); - sx += 40; - } - } - - // ── Action Bar ───────────────────────────────────────────────────────────── drawActionBar() { const gs = this.gs; - if (gs.phase === 'gameover') return; + const A = ACTIONS; + const cx = A.x + A.w / 2; + const human = gs.players[this.humanSeat]; + const actor = L.actingSeat(gs); + let status; + if (gs.phase === 'gameover') status = 'The game is over.'; + else if (!human.active) status = `You are out — ${gs.players[gs.current].name} to play.`; + else if (actor !== this.humanSeat) { + const who = gs.players[actor]?.name ?? ''; + status = gs.phase === 'auction' ? `${who} is bidding…` : gs.phase === 'debt' ? `${who} is raising funds…` : `${who} is playing…`; + } else if (gs.phase === 'preroll') status = human.jailed ? `You're in Jail (try ${human.jailTurns + 1} of 3).\nRoll doubles, pay $50, or use a card.` : gs.doublesCount > 0 ? 'Doubles! Roll again.' : 'Your turn — roll the dice.'; + else if (gs.phase === 'endturn') status = gs.doublesCount > 0 && !human.jailed ? 'You rolled doubles — roll again\nwhen you are ready.' : 'Build, trade, or end your turn.'; + else if (gs.phase === 'buy') status = 'Buy it, or send it to auction.'; + else if (gs.phase === 'auction') status = 'Your bid…'; + else if (gs.phase === 'debt') status = 'You owe more than you have —\nraise funds.'; + else status = ''; + this.statusText.setText(status); + if (!this.humanActing() || this.busy) return; - // Dice values display — use stored landing positions/angles; skip during throw animation - if (gs.diceRoll && !this.diceAnimating) { - const [dp0, dp1] = this.dicePositions; - this.drawDie(0, dp0.cx, dp0.cy, gs.diceRoll[0], dp0.angle); - this.drawDie(1, dp1.cx, dp1.cy, gs.diceRoll[1], dp1.angle); - } - - // Buttons only for human's turn - const isHumanTurn = gs.current === this.humanSeat; - const inAuction = gs.phase === 'auction' && gs.pendingAuction; - const auctionIsHuman = inAuction && - gs.pendingAuction.bidOrder[gs.pendingAuction.currentBidderIdx] === this.humanSeat; - - if (!isHumanTurn && !auctionIsHuman) return; - if (inAuction) return; // auction panel handles its own buttons - - const btnW = RP_W - 20; - const BTN_H = 52; - const BTN_GAP = 10; // spacing between buttons (62 = BTN_H + BTN_GAP) - - // First pass: count buttons to determine starting Y - const p = gs.players[this.humanSeat]; - const phase = gs.phase; - let btnCount = 0; - - if (phase === 'preroll' || phase === 'endturn') { - if (phase === 'preroll') { - if (p.jailed) { - if (p.getOutOfJailFree > 0) btnCount++; - btnCount++; - btnCount++; - } else { - btnCount++; - } - } - if (phase === 'endturn') btnCount++; - if (PURCHASABLE.some(idx => - canBuildHouse(gs, this.humanSeat, idx) || canBuildHotel(gs, this.humanSeat, idx))) { - btnCount++; - } - if (PURCHASABLE.some(idx => { - const own = gs.board[idx]; - return own?.owner === this.humanSeat && !own.mortgaged && own.houses === 0 && !own.hotel; - }) || PURCHASABLE.some(idx => { - const own = gs.board[idx]; - return own?.owner === this.humanSeat && own.mortgaged && - p.cash >= Math.ceil(SPACES[idx].mortgage * 1.1); - })) { - btnCount++; - } - if (phase === 'endturn' && this.canInitiateTrade()) btnCount++; - } - - // Second pass: draw buttons aligned to board bottom (BT + BS) - const boardBottom = BT + BS; - const totalBtnH = btnCount * BTN_H + (btnCount - 1) * BTN_GAP; - const btnY0 = boardBottom - totalBtnH; - let yOff = 0; - const mkBtn = (label, cb, enabled=true, opts={}) => { - const btn = new Button(this, RP_X + btnW/2 + 10, btnY0 + yOff, label, cb, - { width: btnW, height: BTN_H, fontSize: 22, ...opts }); - btn.setDepth(DEPTH.ui); - if (!enabled) btn.setEnabled(false); - this.reg(btn); - yOff += BTN_H + BTN_GAP; + const mk = (x, y, label, fn, o = {}) => { + const b = new Button(this, x, y, label, fn, { width: o.w ?? 330, height: o.h ?? 52, fontSize: o.size ?? 22, bg: o.bg ?? 0x4a2e1a, variant: o.variant ?? 'solid' }); + b.setDepth(DEPTH.hudText); + if (o.enabled === false) b.setEnabled(false); + return this.reg(b); }; - - if (phase === 'preroll' || phase === 'endturn') { - if (phase === 'preroll') { - if (p.jailed) { - if (p.getOutOfJailFree > 0) { - mkBtn('Use GOOJF Card', () => this.onUseJailCard()); - } - mkBtn('Pay $50 Fine', () => this.onPayJailFine(), p.cash >= 50); - mkBtn('Roll Dice', () => this.onRollDice()); - } else { - mkBtn('Roll Dice', () => this.onRollDice()); - } - } - if (phase === 'endturn') { - mkBtn('End Turn', () => this.onEndTurn()); - } - // Build options - const canBuild = PURCHASABLE.some(idx => - canBuildHouse(gs, this.humanSeat, idx) || canBuildHotel(gs, this.humanSeat, idx)); - if (canBuild) { - mkBtn('Build Houses / Hotels', () => this.showBuildMenu(), true, { variant:'ghost' }); - } - // Mortgage options - const canMortgage = PURCHASABLE.some(idx => { - const own = gs.board[idx]; - return own?.owner === this.humanSeat && !own.mortgaged && own.houses === 0 && !own.hotel; - }); - const canUnmortgage = PURCHASABLE.some(idx => { - const own = gs.board[idx]; - return own?.owner === this.humanSeat && own.mortgaged && - p.cash >= Math.ceil(SPACES[idx].mortgage * 1.1); - }); - if (canMortgage || canUnmortgage) { - mkBtn('Mortgage / Unmortgage', () => this.showMortgageMenu(), true, { variant:'ghost' }); - } - // Trade option (after rolling, i.e. endturn) - if (phase === 'endturn' && this.canInitiateTrade()) { - mkBtn('Initiate Trade', () => this.showTradeModal(), true, { variant:'ghost' }); + const y0 = A.y + 104; + if (gs.phase === 'preroll') { + mk(cx, y0, human.jailed ? 'Roll for Doubles' : 'Roll Dice', () => this.onRollDice(), { bg: 0x1d6a48 }); + if (human.jailed) { + mk(cx - 84, y0 + 58, `Jail Free Card${human.getOutOfJailFree > 1 ? ` ×${human.getOutOfJailFree}` : ''}`, () => this.onUseJailCard(), { w: 162, h: 42, size: 15, enabled: human.getOutOfJailFree > 0 }); + mk(cx + 84, y0 + 58, 'Pay $50', () => this.onPayJailFine(), { w: 162, h: 42, size: 16, enabled: human.cash >= 50 }); } + } else if (gs.phase === 'endturn') { + const again = gs.doublesCount > 0 && !human.jailed; + mk(cx, y0, again ? 'Roll Again' : 'End Turn', () => this.onEndTurn(), { bg: again ? 0x1d6a48 : 0x6a4a1a }); + } else if (gs.phase === 'debt') { + mk(cx, y0, 'Raise Funds…', () => this.openRaiseFunds(), { bg: 0x7a2a1a }); } - - // Card OK button is drawn inside drawCardPopup(), overlaid on the card - - if (phase === 'jailChoice') { - // Jail handling is in preroll above + if (['preroll', 'endturn'].includes(gs.phase)) { + const ry = human.jailed && gs.phase === 'preroll' ? y0 + 108 : y0 + 62; + mk(cx - 84, ry, 'Manage (M)', () => this.openManage(), { w: 162, h: 42, size: 16, enabled: this.canManage() }); + mk(cx + 84, ry, 'Trade', () => this.showTradeModal(), { w: 162, h: 42, size: 16, enabled: this.canInitiateTrade() }); + } + if (gs.phase === 'preroll') { + mk(cx, A.y + A.h - 34, `Threat map (T): ${this.settings.threat ? 'On' : 'Off'}`, () => this.toggleSetting('threat'), { w: 240, h: 32, size: 13, variant: 'ghost' }); } } - // ── Rent Payment Animation ───────────────────────────────────────────────── - async animateRent() { - const { payer, receiver, amount } = this.gs.pendingRent; - const depth = DEPTH.banner - 1; // 89 — above all game elements - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - - playSound(this, SFX.MONOPOLY_EXPENSE); - - // Phase 1: Banner + amount appear centered - const bannerTxt = this.add.text(cx, cy - 60, 'PAY RENT', { - fontFamily: 'Righteous', fontSize: '80px', color: '#FFFFFF', - stroke: '#1a1208', strokeThickness: 5, - }).setOrigin(0.5).setDepth(depth); - - const amtTxt = this.add.text(cx, cy + 40, `$${amount.toLocaleString()}`, { - fontFamily: 'Righteous', fontSize: '56px', color: '#FFD700', - stroke: '#1a1208', strokeThickness: 4, - }).setOrigin(0.5).setDepth(depth); - - await this.delay(1000); - - // Phase 2: Amount flies to payer's panel (750 ms), turns red, adds minus - const { px: ppx, py: ppy, panelW: ppw } = this.panelPos(payer); - const { px: rpx, py: rpy, panelW: rpw } = this.panelPos(receiver); - const payerX = ppx + ppw / 2, payerY = ppy + 44; - const recvX = rpx + rpw / 2, recvY = rpy + 44; - - amtTxt.setText(`-$${amount.toLocaleString()}`); - amtTxt.setColor('#FF4444'); - // Fade banner out simultaneously - this.tweens.add({ targets: bannerTxt, alpha: 0, duration: 750, ease: 'Linear' }); - - await new Promise(resolve => { - this.tweens.add({ - targets: amtTxt, - x: payerX, y: payerY, - scaleX: 0.5, scaleY: 0.5, - duration: 750, ease: 'Cubic.easeIn', - onComplete: resolve, - }); - }); - - await this.delay(250); - - playSound(this, SFX.MONOPAY); - - // Phase 3: Amount arches to receiver's panel (1200 ms), turns green, adds plus - amtTxt.setText(`+$${amount.toLocaleString()}`); - amtTxt.setColor('#44FF88'); - - const sx = amtTxt.x, sy = amtTxt.y; - const midX = (sx + recvX) / 2; - const midY = Math.min(sy, recvY) - 220; // arch above both panels - const proxy = { t: 0 }; - - await new Promise(resolve => { - this.tweens.add({ - targets: proxy, t: 1, - duration: 1200, ease: 'Sine.easeInOut', - onUpdate: () => { - const t = proxy.t, u = 1 - t; - amtTxt.x = u*u*sx + 2*u*t*midX + t*t*recvX; - amtTxt.y = u*u*sy + 2*u*t*midY + t*t*recvY; - }, - onComplete: resolve, - }); - }); - - playSound(this, SFX.MONOPOLY_PAID); - await this.delay(300); - bannerTxt.destroy(); - amtTxt.destroy(); - } - - // ── Card Draw Animation ──────────────────────────────────────────────────── - async animateCardDraw() { - const { cardType, text } = this.gs.pendingCard; - const isChance = cardType === 'chance'; - const BOARD_CX = BL + BS / 2; - const BOARD_CY = BT + BS / 2; - const cardColor = isChance ? 0xE77A2C : 0x1565C0; - - // Deck position — must match drawCenterDecks() - const deckX = isChance ? BOARD_CX - DECK_D : BOARD_CX + DECK_D; - const deckY = isChance ? BOARD_CY + DECK_D : BOARD_CY - DECK_D; - const deckRot = isChance ? -0.14 : 0.12; - - // Full popup card size; container scales up from deck visual width - const CW = 360, CH = 480; - const startScale = 88 / CW; // ≈ 0.244 - - // Dim overlay (not in dyn — destroyed at end of animation) - const overlay = this.add.rectangle( - GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0 - ).setDepth(DEPTH.popup - 2); - this.tweens.add({ targets: overlay, alpha: 0.6, duration: 500, ease: 'Linear' }); - - // Container starts at deck position, scaled and rotated to match deck - const container = this.add.container(deckX, deckY) - .setDepth(DEPTH.popup - 1) - .setScale(startScale) - .setRotation(deckRot); - - // ── Back face (matches the face-down deck appearance) ───────────────── - const backGfx = this.add.graphics(); - backGfx.fillStyle(cardColor, 1); - backGfx.lineStyle(3, 0xFFF8E7, 1); - backGfx.fillRoundedRect(-CW / 2, -CH / 2, CW, CH, 16); - backGfx.strokeRoundedRect(-CW / 2, -CH / 2, CW, CH, 16); - backGfx.lineStyle(2, 0xFFF8E7, 0.75); - backGfx.strokeRoundedRect(-CW / 2 + 14, -CH / 2 + 14, CW - 28, CH - 28, 10); - container.add(backGfx); - - const backLabel = this.add.text(0, 0, isChance ? 'Chance' : 'Community\nChest', { - fontFamily: 'Righteous', fontSize: '36px', color: '#FFF8E7', align: 'center', - }).setOrigin(0.5); - container.add(backLabel); - - // ── Front face (matches drawCardPopup content, hidden until flip) ───── - const frontObjs = []; - - const frontBg = this.add.graphics(); - frontBg.fillStyle(cardColor, 1); - frontBg.lineStyle(4, 0xFFF8E7, 1); - frontBg.fillRoundedRect(-CW / 2, -CH / 2, CW, CH, 16); - frontBg.strokeRoundedRect(-CW / 2, -CH / 2, CW, CH, 16); - frontBg.setVisible(false); - container.add(frontBg); - frontObjs.push(frontBg); - - if (this.hasCards) { - const frame = isChance ? CARD_FRAME.chance : CARD_FRAME.community_chest; - const art = this.add.image(0, -CH / 2 + 120, 'monopoly-cards', frame) - .setDisplaySize(CW - 20, 220).setVisible(false); - container.add(art); - frontObjs.push(art); - } else { - const fallBg = this.add.graphics(); - fallBg.fillStyle(0xffffff, 0.15); - fallBg.fillRoundedRect(-CW / 2 + 10, -CH / 2 + 10, CW - 20, 210, 12); - fallBg.setVisible(false); - container.add(fallBg); - frontObjs.push(fallBg); - - const icon = this.add.text(0, -CH / 2 + 110, isChance ? '?' : '📦', { - fontFamily: 'Righteous', fontSize: '80px', color: '#ffffff', - }).setOrigin(0.5).setVisible(false); - container.add(icon); - frontObjs.push(icon); - } - - const frontTitle = this.add.text(0, -CH / 2 + 30, isChance ? 'CHANCE' : 'COMMUNITY CHEST', { - fontFamily: 'Righteous', fontSize: '18px', color: '#FFF8E7', - }).setOrigin(0.5).setVisible(false); - container.add(frontTitle); - frontObjs.push(frontTitle); - - const frontBody = this.add.text(0, -CH / 2 + 250, text, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#FFF8E7', - align: 'center', wordWrap: { width: CW - 30 }, - }).setOrigin(0.5, 0).setVisible(false); - container.add(frontBody); - frontObjs.push(frontBody); - - // Phase 1: fly from deck to center, grow, straighten (700 ms) - await new Promise(resolve => { - this.tweens.add({ - targets: container, - x: GAME_WIDTH / 2, - y: GAME_HEIGHT / 2, - scaleX: 1, scaleY: 1, - rotation: 0, - duration: 700, - ease: 'Cubic.easeOut', - onComplete: resolve, - }); - }); - - // Phase 2a: flip first half — collapse to zero width - await new Promise(resolve => { - this.tweens.add({ - targets: container, - scaleX: 0, - duration: 180, - ease: 'Sine.easeIn', - onComplete: resolve, - }); - }); - - // Swap faces at zero-width moment - backGfx.setVisible(false); - backLabel.setVisible(false); - frontObjs.forEach(o => o.setVisible(true)); - - // Phase 2b: flip second half — expand back to full width - await new Promise(resolve => { - this.tweens.add({ - targets: container, - scaleX: 1, - duration: 180, - ease: 'Sine.easeOut', - onComplete: resolve, - }); - }); - - // Cleanup — render() will immediately draw the static popup at the same coords - container.each(child => { try { child.destroy(); } catch {} }); - container.destroy(); - overlay.destroy(); - } - - // ── Card Popup ───────────────────────────────────────────────────────────── - drawCardPopup() { - if (!this.gs.pendingCard) return; - const { cardType, text } = this.gs.pendingCard; - const isChance = cardType === 'chance'; - const pw = 360, ph = 480; - const px = GAME_WIDTH/2 - pw/2, py = GAME_HEIGHT/2 - ph/2; - - // Overlay - const overlay = this.reg(this.add.graphics().setDepth(DEPTH.popup - 1)); - overlay.fillStyle(0x000000, 0.6); - overlay.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - - // Card background - const g = this.reg(this.add.graphics().setDepth(DEPTH.popup)); - const cardColor = isChance ? 0xE77A2C : 0x1565C0; - g.fillStyle(cardColor, 1); - g.fillRoundedRect(px, py, pw, ph, 16); - g.lineStyle(4, 0xFFF8E7, 1); - g.strokeRoundedRect(px, py, pw, ph, 16); - - if (this.hasCards) { - const frame = isChance ? CARD_FRAME.chance : CARD_FRAME.community_chest; - this.reg(this.add.image(px + pw/2, py + 120, 'monopoly-cards', frame) - .setDisplaySize(pw - 20, 220).setDepth(DEPTH.popup)); - } else { - // Fallback art - const ag = this.reg(this.add.graphics().setDepth(DEPTH.popup)); - ag.fillStyle(0xffffff, 0.15); - ag.fillRoundedRect(px + 10, py + 10, pw - 20, 210, 12); - this.reg(this.add.text(px + pw/2, py + 110, isChance ? '?' : '📦', { - fontFamily:'Righteous', fontSize:'80px', color:'#ffffff', - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - } - - this.reg(this.add.text(px + pw/2, py + 30, isChance ? 'CHANCE' : 'COMMUNITY CHEST', { - fontFamily:'Righteous', fontSize:'18px', color:'#FFF8E7', - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - this.reg(this.add.text(px + pw/2, py + 250, text, { - fontFamily:'"Julius Sans One"', fontSize:'18px', color:'#FFF8E7', - align:'center', wordWrap:{ width: pw - 30 }, - }).setOrigin(0.5, 0).setDepth(DEPTH.popup+1)); - - // OK button — only shown on the human player's turn - if (this.gs.current === this.humanSeat) { - const btn = new Button(this, px + pw/2, py + ph - 36, 'OK', () => this.onDismissCard(), { - width: 220, height: 48, fontSize: 20, - }); - btn.setDepth(DEPTH.popup + 2); - this.reg(btn); - } - } - - // ── Auction Panel ────────────────────────────────────────────────────────── - drawAuctionPanel() { - const auc = this.gs.pendingAuction; - const sp = SPACES[auc.spaceIdx]; - const bidderSeat = auc.bidOrder[auc.currentBidderIdx]; - const isHuman = bidderSeat === this.humanSeat; - - const pw = this.modalActive ? 520 : RP_W - 20; - const ph = 360; - const px = this.modalActive ? GAME_WIDTH - pw - 30 : RP_X + 10; - const py = GAME_HEIGHT/2 - ph/2; - - const g = this.reg(this.add.graphics().setDepth(DEPTH.popup)); - g.fillStyle(0x1e1a12, 1); - g.fillRoundedRect(px, py, pw, ph, 12); - g.lineStyle(2, COLORS.gold, 1); - g.strokeRoundedRect(px, py, pw, ph, 12); - - this.reg(this.add.text(px + pw/2, py + 20, 'AUCTION', { - fontFamily:'Righteous', fontSize:'26px', color:COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - // Property color band - if (sp.group) { - const bg2 = this.reg(this.add.graphics().setDepth(DEPTH.popup)); - bg2.fillStyle(GROUP_COLORS[sp.group] ?? COLORS.accent, 1); - bg2.fillRect(px + 20, py + 55, pw - 40, 22); - } - this.reg(this.add.text(px + pw/2, py + 66, sp.name, { - fontFamily:'Righteous', fontSize:'18px', color:'#FFF8E7', - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - this.reg(this.add.text(px + pw/2, py + 100, `List Price: $${sp.price}`, { - fontFamily:'"Julius Sans One"', fontSize:'15px', color:COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - const highBidText = auc.highBid > 0 - ? `High bid: $${auc.highBid} (${this.gs.players[auc.highBidder].name})` - : 'No bids yet'; - this.reg(this.add.text(px + pw/2, py + 128, highBidText, { - fontFamily:'"Julius Sans One"', fontSize:'15px', color:'#aaddaa', - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - const bidderName = this.gs.players[bidderSeat]?.name ?? '?'; - this.reg(this.add.text(px + pw/2, py + 156, `${bidderName}'s turn to bid`, { - fontFamily:'"Julius Sans One"', fontSize:'14px', color:COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - if (isHuman) { - // Bid controls - const minBid = auc.highBid + 1; - if (this.bidInput < minBid) this.bidInput = minBid; - const phuman = this.gs.players[this.humanSeat]; - if (this.bidInput > phuman.cash) this.bidInput = phuman.cash; - - this.reg(this.add.text(px + pw/2, py + 188, `Your bid: $${this.bidInput}`, { - fontFamily:'Righteous', fontSize:'22px', color:COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - - const btnH = 44, btnGap = 10; - // -50, -10, +10, +50 buttons - const nudgeValues = [[-50, '−50'], [-10, '−10'], [+10, '+10'], [+50, '+50']]; - const nudgeBtnW = (pw - 50) / 4; - nudgeValues.forEach(([delta, label], i) => { - const nbx = px + 20 + i * (nudgeBtnW + 4); - const btn = new Button(this, nbx + nudgeBtnW/2, py + 230, label, () => { - this.bidInput = Math.max(minBid, Math.min(phuman.cash, this.bidInput + delta)); - this.render(); - }, { width: nudgeBtnW, height: 38, fontSize: 16 }); - btn.setDepth(DEPTH.popup+2); - this.reg(btn); - }); - - const bidBtn = new Button(this, px + pw/2 - 80, py + 288, 'BID', () => { - if (this.bidInput >= minBid && this.bidInput <= phuman.cash) { - this.gs = placeBid(this.gs, this.humanSeat, this.bidInput); - this.bidInput = 0; - this.render(); - this.advance(); - } - }, { width: 130, height: btnH, fontSize: 20 }); - bidBtn.setDepth(DEPTH.popup+2); - this.reg(bidBtn); - - const passBtn = new Button(this, px + pw/2 + 80, py + 288, 'PASS', () => { - this.gs = passAuction(this.gs, this.humanSeat); - this.bidInput = 0; - this.render(); - this.advance(); - }, { width: 130, height: btnH, fontSize: 20, variant:'ghost' }); - passBtn.setDepth(DEPTH.popup+2); - this.reg(passBtn); - } else { - this.reg(this.add.text(px + pw/2, py + 230, 'Waiting for AI…', { - fontFamily:'"Julius Sans One"', fontSize:'16px', color:COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1)); - } - } - - // ── Build Menu ───────────────────────────────────────────────────────────── - showBuildMenu() { - if (this.buildMenuOpen) return; - this.buildMenuOpen = true; - this.buildMenuObjs = []; - + // ── Threat map ────────────────────────────────────────────────────────────── + drawThreat() { const gs = this.gs; - const seat = this.humanSeat; - const eligible = PURCHASABLE.filter(idx => - canBuildHouse(gs, seat, idx) || canBuildHotel(gs, seat, idx)); - - const pw = 420, itemH = 48; - const ph = Math.min(600, 60 + eligible.length * (itemH + 8) + 20); - const px = GAME_WIDTH/2 - pw/2, py = GAME_HEIGHT/2 - ph/2; - - const overlay = this.add.graphics().setDepth(DEPTH.popup - 1); - overlay.fillStyle(0x000000, 0.5); - overlay.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - this.buildMenuObjs.push(overlay); - - const panel = this.add.graphics().setDepth(DEPTH.popup); - panel.fillStyle(0x1e1a12, 1); - panel.fillRoundedRect(px, py, pw, ph, 12); - panel.lineStyle(2, COLORS.gold, 1); - panel.strokeRoundedRect(px, py, pw, ph, 12); - this.buildMenuObjs.push(panel); - - const title = this.add.text(px + pw/2, py + 22, 'Build Houses / Hotels', { - fontFamily:'Righteous', fontSize:'20px', color:COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1); - this.buildMenuObjs.push(title); - - eligible.forEach((idx, i) => { - const sp = SPACES[idx]; - const own = gs.board[idx]; - const hotelReady = canBuildHotel(gs, seat, idx); - const label = hotelReady - ? `${sp.name} — Build Hotel ($${sp.houseCost})` - : `${sp.name} — House ${own.houses + 1}/4 ($${sp.houseCost})`; - const by = py + 56 + i * (itemH + 8); - const btn = new Button(this, px + pw/2, by + itemH/2, label, () => { - this.closeBuildMenu(); - if (hotelReady) { - this.gs = buildHotel(this.gs, seat, idx); - } else { - this.gs = buildHouse(this.gs, seat, idx); - } - this.render(); - }, { width: pw - 20, height: itemH, fontSize: 16 }); - btn.setDepth(DEPTH.popup+2); - this.buildMenuObjs.push(btn); - }); - - if (eligible.length === 0) { - const noElig = this.add.text(px + pw/2, py + 80, 'No properties eligible to build on.', { - fontFamily:'"Julius Sans One"', fontSize:'16px', color:COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1); - this.buildMenuObjs.push(noElig); + if (!this.settings.threat || gs.phase !== 'preroll' || gs.current !== this.humanSeat || !gs.players[this.humanSeat].active || this.busy) return; + const tm = L.threatMap(gs, this.humanSeat); + const g = this.reg(this.add.graphics().setDepth(DEPTH.threat)); + const COL = { rent: 0xd32f2f, tax: 0xef6c00, jail: 0x1e3a8a, card: 0x7b3fa0, buy: 0x2e7d32, safe: 0x607d8b }; + let worst = null; + for (const c of tm.cells) { + const r = spaceRect(c.idx); + const a = Math.min(0.62, 0.14 + c.prob * 3.2); + if (c.kind === 'buy') { + g.lineStyle(3, COL.buy, 0.9).strokeRect(r.x + 3, r.y + 3, r.w - 6, r.h - 6); + } else { + g.fillStyle(COL[c.kind], a).fillRect(r.x + 1, r.y + 1, r.w - 2, r.h - 2); + } + const ctr = spaceCenter(c.idx); + const label = `${Math.round(c.prob * 100)}%${c.cost ? `\n$${c.cost.toLocaleString()}` : c.kind === 'jail' ? '\nJAIL' : ''}`; + this.reg(this.add.text(ctr.x, ctr.y, label, { + fontFamily: DISPLAY, fontSize: '15px', color: '#ffffff', align: 'center', stroke: '#1a0f08', strokeThickness: 4, + }).setOrigin(0.5).setDepth(DEPTH.threat + 0.5)); + if (c.cost && (!worst || c.cost > worst.cost)) worst = c; } - - const closeBtn = new Button(this, px + pw/2, py + ph - 30, 'Close', () => this.closeBuildMenu(), - { variant:'ghost', width:120, height:40, fontSize:16 }); - closeBtn.setDepth(DEPTH.popup+2); - this.buildMenuObjs.push(closeBtn); - } - - closeBuildMenu() { - this.buildMenuOpen = false; - this.buildMenuObjs?.forEach(o => { try { o.destroy(); } catch {} }); - this.buildMenuObjs = []; - } - - // ── Mortgage Menu ────────────────────────────────────────────────────────── - showMortgageMenu() { - if (this.mortMenuOpen) return; - this.mortMenuOpen = true; - this.mortMenuObjs = []; - - const gs = this.gs; - const seat = this.humanSeat; - const canMort = PURCHASABLE.filter(idx => { - const own = gs.board[idx]; - return own?.owner === seat && !own.mortgaged && own.houses === 0 && !own.hotel; - }); - const canUnmort = PURCHASABLE.filter(idx => { - const own = gs.board[idx]; - return own?.owner === seat && own.mortgaged; - }); - - const items = [ - ...canMort.map(idx => ({ idx, action:'mortgage' })), - ...canUnmort.map(idx => ({ idx, action:'unmortgage' })), + const B = THREAT_BOX; + const bg = this.reg(this.add.graphics().setDepth(DEPTH.threat)); + bg.fillStyle(0x1a0f08, 0.86).fillRoundedRect(B.x, B.y, B.w, B.h, 10); + bg.lineStyle(2, 0xc9a24a, 1).strokeRoundedRect(B.x, B.y, B.w, B.h, 10); + const lines = [ + 'YOUR NEXT ROLL', + `Chance you pay: ${Math.round(tm.pAny * 100)}%`, + `Average cost: $${Math.round(tm.expected).toLocaleString()}`, + worst ? `Worst: $${worst.cost.toLocaleString()} (${SPACES[worst.idx].name})` : 'Worst: nothing to pay', ]; - - const pw = 440, itemH = 48; - const ph = Math.min(800, 60 + items.length * (itemH + 8) + 48); - const px = GAME_WIDTH/2 - pw/2, py = GAME_HEIGHT/2 - ph/2; - - const overlay = this.add.graphics().setDepth(DEPTH.popup - 1); - overlay.fillStyle(0x000000, 0.5); - overlay.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - this.mortMenuObjs.push(overlay); - - const panel = this.add.graphics().setDepth(DEPTH.popup); - panel.fillStyle(0x1e1a12, 1); - panel.fillRoundedRect(px, py, pw, ph, 12); - panel.lineStyle(2, COLORS.gold, 1); - panel.strokeRoundedRect(px, py, pw, ph, 12); - this.mortMenuObjs.push(panel); - - const title = this.add.text(px + pw/2, py + 22, 'Mortgage / Unmortgage', { - fontFamily:'Righteous', fontSize:'20px', color:COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1); - this.mortMenuObjs.push(title); - - items.forEach(({ idx, action }, i) => { - const sp = SPACES[idx]; - const cost = action === 'mortgage' ? sp.mortgage : Math.ceil(sp.mortgage * 1.1); - const label = action === 'mortgage' - ? `Mortgage ${sp.name} (+$${cost})` - : `Unmortgage ${sp.name} (−$${cost})`; - const enabled = action === 'unmortgage' ? gs.players[seat].cash >= cost : true; - const by = py + 56 + i * (itemH + 8); - const btn = new Button(this, px + pw/2, by + itemH/2, label, () => { - this.closeMortMenu(); - if (action === 'mortgage') { - this.gs = mortgageProperty(this.gs, seat, idx); - } else { - this.gs = unmortgageProperty(this.gs, seat, idx); - } - this.render(); - }, { width: pw - 20, height: itemH, fontSize: 15 }); - btn.setDepth(DEPTH.popup+2); - if (!enabled) btn.setEnabled(false); - this.mortMenuObjs.push(btn); - }); - - if (items.length === 0) { - const noItems = this.add.text(px + pw/2, py + 80, 'Nothing to mortgage or unmortgage.', { - fontFamily:'"Julius Sans One"', fontSize:'16px', color:COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.popup+1); - this.mortMenuObjs.push(noItems); - } - - const closeBtn = new Button(this, px + pw/2, py + ph - 30, 'Close', () => this.closeMortMenu(), - { variant:'ghost', width:120, height:40, fontSize:16 }); - closeBtn.setDepth(DEPTH.popup+2); - this.mortMenuObjs.push(closeBtn); + lines.forEach((t, k) => this.reg(this.add.text(B.x + B.w / 2, B.y + 20 + k * 26, t, { + fontFamily: k ? DECO : DISPLAY, fontSize: k ? '14px' : '15px', color: k ? '#f3e7c8' : '#ecd690', + }).setOrigin(0.5).setDepth(DEPTH.threat + 0.6))); } - closeMortMenu() { - this.mortMenuOpen = false; - this.mortMenuObjs?.forEach(o => { try { o.destroy(); } catch {} }); - this.mortMenuObjs = []; - } - - // ── 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) { + // ── Hover cards & clicks ──────────────────────────────────────────────────── + showHoverDeed(idx) { + this.hideHoverDeed(); + if (!this.gs || this.overlayOpen()) return; const sp = SPACES[idx]; - return sp.group ? GROUP_COLORS[sp.group] - : sp.type === 'railroad' ? 0x1a1208 - : sp.type === 'utility' && idx === 12 ? 0xFFD700 - : 0x1565C0; - } - - // ── 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) { + if (PURCHASABLE.includes(idx)) { + const card = buildDeedCard(this, this.gs, idx, { live: true }); + card.setPosition(BOARD_CX, BOARD_CY).setScale(0.74).setDepth(DEPTH.tooltip); + this.hoverCard = card; + return; + } 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; + const info = { + go: ['GO', ['Collect $200 salary every time you pass.', gs.rules.doubleGo ? 'House rule: land exactly on GO for $400.' : '']], + jail: ['Jail', ['Just Visiting unless you were sent here.', 'Leave by rolling doubles, paying $50,', 'or using a Get Out of Jail Free card.', 'Third failed try: pay $50 and move.']], + freeparking: ['Free Parking', gs.rules.freeParkingJackpot ? [`Jackpot: $${gs.freeParkingPot.toLocaleString()}`, 'Taxes and fees pile up here — land to collect.'] : ['A free resting place.']], + gotojail: ['Go To Jail', ['Go directly to Jail.', 'Do not pass GO, do not collect $200.']], + chance: ['Chance', [`${gs.chanceDeck.length} cards in the deck.`, 'Draw the top card and follow it.']], + community_chest: ['Community Chest', [`${gs.ccDeck.length} cards in the deck.`, 'Draw the top card and follow it.']], + tax: [sp.name, [`Pay $${sp.amount} to the ${gs.rules.freeParkingJackpot ? 'Free Parking pot' : 'bank'}.`]], + }[sp.type]; + if (!info) return; + this.tooltip.setContent({ title: info[0], lines: info[1].filter(Boolean) }); + this.tooltip._reposition(this.input.activePointer.x, this.input.activePointer.y); + this.tooltip.container.setVisible(true); + this.tooltipShown = true; + } - // Tick this AI's human-proposal cooldown down once per its own turn. - if (this.humanTradeCooldown[seat] > 0) this.humanTradeCooldown[seat]--; + hideHoverDeed() { + if (this.hoverCard) { destroyContainer(this.hoverCard); this.hoverCard = null; } + if (this.tooltipShown) { this.tooltip.hide(); this.tooltipShown = false; } + } - const skill = this.skillBySeat[seat] ?? 3; + onSpaceClick(idx) { + const own = this.gs?.board?.[idx]; + if (!own || own.owner !== this.humanSeat || !this.canManage()) return; + this.hideHoverDeed(); + this.openManage(idx); + } - // 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; + // ── Keyboard ──────────────────────────────────────────────────────────────── + onKey(e) { + if (!this.gs || !this.tableBuilt) return; + const k = e.key; + if (k === 'Escape') { + if (this.manageH && this.gs.phase !== 'debt') { this.manageH.close(); return; } + if (this.tradeMenuOpen) { this.closeTradeModal(); return; } + if (this.modal) return; + this.openFrontDesk(); + return; } + if (this.modal || this.manageH || this.tradeMenuOpen || this.endH) return; + if (k === ' ' || k === 'Enter') { + e.preventDefault?.(); + if (this.gs.phase === 'card' && this.cardAnimPlayed && this.gs.current === this.humanSeat) this.onDismissCard(); + else if (this.canHumanRoll()) this.onRollDice(); + else if (this.gs.phase === 'endturn' && this.humanActing() && !this.busy) this.onEndTurn(); + } else if (k === 'm' || k === 'M') { if (this.canManage()) this.openManage(); } + else if (k === 't' || k === 'T') this.toggleSetting('threat'); + else if (k === 'l' || k === 'L') this.toggleSetting('ledger'); } - // 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:'Righteous', 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:'Righteous', 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); - 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; - const panel = this.add.graphics().setDepth(DEPTH.popup); - panel.fillStyle(0x1e1a12, 1); panel.fillRoundedRect(PX, PY, PW, PH, 14); - panel.lineStyle(2, COLORS.gold, 1); panel.strokeRoundedRect(PX, PY, PW, PH, 14); - objs.push(panel); - - objs.push(this.add.text(GAME_WIDTH/2, PY + 22, `${fromName} proposes a trade`, { - fontFamily:'Righteous', 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); - playSound(this, SFX.MONOPOLY_PURCHASE); - 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; - const panel = this.add.graphics().setDepth(DEPTH.popup); - panel.fillStyle(0x1e1a12, 1); panel.fillRoundedRect(PX, PY, PW, PH, 14); - panel.lineStyle(2, COLORS.gold, 1); panel.strokeRoundedRect(PX, PY, PW, PH, 14); - objs.push(panel); - - objs.push(this.add.text(GAME_WIDTH/2, PY + 22, `${fromName} ⇄ ${toName} — Trade`, { - fontFamily:'Righteous', 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:'Righteous', 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 || this.gs.phase !== 'endturn')) 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 - const panel = this.add.graphics().setDepth(DEPTH.popup); - panel.fillStyle(0x1e1a12, 1); - panel.fillRoundedRect(PX, PY, PW, PH, 14); - panel.lineStyle(2, COLORS.gold, 1); - panel.strokeRoundedRect(PX, PY, PW, PH, 14); - this.tradeMenuObjs.push(panel); - - 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:'Righteous', 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:'Righteous', 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:'Righteous', 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:'Righteous', 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:'Righteous', 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', { - 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:'Righteous', 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:'Righteous', 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 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, 'good'); - playSound(this, SFX.MONOPOLY_PURCHASE); - 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(); - } - - // ── Game Over ────────────────────────────────────────────────────────────── - showGameOver() { - const winner = this.gs.winner !== null ? this.gs.players[this.gs.winner] : null; - const overlay = this.add.graphics().setDepth(DEPTH.banner); - overlay.fillStyle(0x000000, 0.7); - overlay.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - - const pw = 600, ph = 280; - const px = GAME_WIDTH/2 - pw/2, py = GAME_HEIGHT/2 - ph/2; - const bg = this.add.graphics().setDepth(DEPTH.banner+1); - bg.fillStyle(0x1e1a12, 1); - bg.fillRoundedRect(px, py, pw, ph, 16); - bg.lineStyle(3, COLORS.gold, 1); - bg.strokeRoundedRect(px, py, pw, ph, 16); - - const msg = winner ? `${winner.name} Wins!` : 'Game Over'; - this.add.text(GAME_WIDTH/2, py + 60, msg, { - fontFamily:'Righteous', fontSize:'54px', color:COLORS.goldHex, - }).setOrigin(0.5).setDepth(DEPTH.banner+2); - - if (winner) { - this.add.text(GAME_WIDTH/2, py + 140, `Net worth: $${netWorth(this.gs, winner.seat).toLocaleString()}`, { - fontFamily:'"Julius Sans One"', fontSize:'22px', color:COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.banner+2); - } - - new Button(this, GAME_WIDTH/2, py + 218, 'Back to Menu', () => this.scene.start('GameMenu'), { - width:220, height:52, fontSize:22, - }).setDepth(DEPTH.banner+3); - } - - // ── Game Flow ────────────────────────────────────────────────────────────── - advance() { - if (this.busy) return; + toggleSetting(key) { + this.settings[key] = !this.settings[key]; + this.saveSettings(); + if (key === 'ledger') this.hud.setLedgerVisible(this.settings.ledger); this.render(); - const gs = this.gs; - if (gs.phase === 'gameover') { this.showGameOver(); return; } + } + + // ── Front Desk ────────────────────────────────────────────────────────────── + openFrontDesk() { + if (this.modal || !this.gs) return; + this.paused = true; + this.hideHoverDeed(); + this.modal = Dlg.openFrontDesk(this, { + settings: this.settings, rules: this.gs.rules, depth: POPUP_D, + onChange: (k, v) => { this.settings[k] = v; this.saveSettings(); if (k === 'ledger') this.hud.setLedgerVisible(v); }, + onRules: () => new TutorialModal(this.gameDef).open(), + onNewGame: () => { + this.paused = true; + this.modal = Dlg.confirmBox(this, { + heading: 'New game?', body: 'Abandon this game and deal a new one?', yes: 'New Game', depth: POPUP_D + 10, + onYes: () => { this.clearSave(); this.scene.restart(this.initData); }, + onNo: () => { this.modal = null; this.paused = false; this.render(); this.advance(); }, + }); + }, + onLeave: () => this.leave(), + onClose: () => { this.modal = null; this.paused = false; this.render(); this.advance(); }, + }); + this.refreshPortraits(); + } + + // ── Manage / Raise Funds ──────────────────────────────────────────────────── + openManage(focusIdx = null) { + if (this.manageH || !this.canManage()) return; + this.hideHoverDeed(); + const seat = this.humanSeat; + const act = (kind, idx) => { + const gs = this.gs; + const fn = { house: L.buildHouse, hotel: L.buildHotel, sellHouse: L.sellHouse, sellHotel: L.sellHotel, mortgage: L.mortgageProperty, unmortgage: L.unmortgageProperty }[kind]; + const next = fn(gs, seat, idx); + if (next === gs) return; + this.commit(next); + this.manageH?.refresh(); + }; + this.manageH = Dlg.openManage(this, { + getState: () => this.gs, seat, depth: POPUP_D, focusIdx, + onAct: act, + onEvenBuild: (group) => { + const cost = SPACES[L.ownedBy(this.gs, seat).find((i) => SPACES[i].group === group)].houseCost; + const plan = L.planEvenBuild(this.gs, seat, group, cost * (group === 'brown' || group === 'darkblue' ? 2 : 3)); + let s = this.gs; + for (const st of plan) s = st.kind === 'house' ? L.buildHouse(s, seat, st.idx) : L.buildHotel(s, seat, st.idx); + if (s !== this.gs) { this.commit(s); this.manageH?.refresh(); } + }, + onSettle: () => { + if (!L.canSettleDebt(this.gs)) return; + this.manageH?.close(); + this.commit(L.settleDebt(this.gs)); + }, + onAuto: () => { + let s = this.gs; + for (let k = 0; k < 40; k++) { + const a = chooseDebtAction(s, seat, 5); + if (!a || a.action === 'settle' || a.action === 'bankrupt') break; + const fn = { mortgage: L.mortgageProperty, sellHouse: L.sellHouse, sellHotel: L.sellHotel }[a.action]; + const n = fn(s, seat, a.spaceIdx); + if (n === s) break; + s = n; + } + if (s !== this.gs) { this.commit(s); this.manageH?.refresh(); } + }, + onBankrupt: () => { + this.modal = Dlg.confirmBox(this, { + heading: 'Declare bankruptcy?', body: 'Even selling everything would not cover the debt. You will be out of the game.', yes: 'Bankrupt', depth: POPUP_D + 20, + onYes: () => { this.modal = null; this.manageH?.close(); this.commit(L.declareBankruptcy(this.gs)); }, + onNo: () => { this.modal = null; }, + }); + }, + onClose: () => { this.manageH = null; this.render(); this.advance(); }, + }); + this.refreshPortraits(); + } + + openRaiseFunds() { this.openManage(); } + + // Replace the state and let advance() animate / continue. + commit(next) { + if (!next || next === this.gs) return; + this.gs = next; + this.advance(); + } + + // ── Game flow ─────────────────────────────────────────────────────────────── + hasUnplayedFx() { return (this.gs.fxSeq ?? 0) > this.lastFx; } + + advance() { + if (!this.tableBuilt || this.busy || this.dead) return; + const gs = this.gs; + if (this.hasUnplayedFx()) { + this.busy = true; + this.inFx = true; + this.render(); + this.playFx().then(() => { this.inFx = false; this.busy = false; this.advance(); }); + return; + } + this.render(); + this.maybeSave(); + if (this.paused) return; + + if (gs.phase === 'gameover') { this.showGameOver(); return; } + if (!gs.players[this.humanSeat].active && !this.outShown) { this.showOut(); return; } - // Guard 1: zoom property card to center when entering 'buy' phase if (gs.phase === 'buy' && gs.pendingBuy && !this.modalActive) { this.busy = true; - this.showPropertyModal(gs.pendingBuy.spaceIdx).then(() => { - this.busy = false; - this.advance(); - }); + this.showPropertyModal(gs.pendingBuy.spaceIdx).then(() => { this.busy = false; this.advance(); }); return; } - - // Guard 2: dismiss modal when phase leaves buy/auction - if (this.modalActive && gs.phase !== 'buy' && gs.phase !== 'auction') { + if (this.modalActive && gs.phase !== 'buy' && !(gs.phase === 'auction' && gs.pendingAuction?.spaceIdx === this.modalSpaceIdx)) { this.busy = true; - this.dismissPropertyModal().then(() => { - this.busy = false; - this.time.delayedCall(0, () => this.advance()); - }); + this.dismissPropertyModal().then(() => { this.busy = false; this.time.delayedCall(0, () => this.advance()); }); return; } - - // Guard 3: animate card draw once per card event (human and AI) if (gs.phase === 'card' && gs.pendingCard && !this.cardAnimPlayed) { this.busy = true; - this.hidePortraits(); - this.animateCardDraw().then(() => { - this.cardAnimPlayed = true; - this.busy = false; - this.render(); - this.advance(); - }); + this.animateCardDraw().then(() => { this.cardAnimPlayed = true; this.busy = false; this.advance(); }); return; } - - // Guard 4: animate rent payment (human and AI) if (gs.phase === 'rent' && gs.pendingRent) { this.busy = true; - this.hidePortraits(); - this.animateRent().then(() => { - this.gs = applyRent(this.gs); - this.showPortraits(); - this.busy = false; - this.render(); - this.advance(); - }); + this.rentBanner().then(() => { this.gs = L.applyRent(this.gs); this.busy = false; this.advance(); }); return; } - // Determine who acts next - let actingSeat = gs.current; - if (gs.phase === 'auction' && gs.pendingAuction) { - actingSeat = gs.pendingAuction.bidOrder[gs.pendingAuction.currentBidderIdx]; + const actor = L.actingSeat(gs); + if (actor === this.humanSeat) { + if (gs.phase === 'debt' && !this.manageH) this.openManage(); + return; } - - if (actingSeat !== this.humanSeat) { - this.busy = true; - const delay = nextThinkDelay(this.skillBySeat[actingSeat] ?? 3); - this.time.delayedCall(delay, () => { - this.doAiAction(actingSeat).then(() => { - this.busy = false; - this.time.delayedCall(0, () => this.advance()); - }); - }); - } - // Human: buttons are live from render() - } - - aiDelay(seat) { - return nextThinkDelay(this.skillBySeat[seat] ?? 3); - } - - delay(ms) { - return new Promise(r => this.time.delayedCall(ms, r)); + // an opponent's move + this.busy = true; + const skill = this.skillBySeat[actor] ?? 3; + const quick = this.isFast(actor) ? 0.35 : 1; + let wait = nextThinkDelay(skill) * this.pace() * quick; + if (gs.phase === 'debt' || (gs.phase === 'preroll' && this.aiManageCount > 0)) wait = 380 * this.pace() * quick; + if (gs.phase === 'auction') wait = 420 * this.pace() * quick; + this.time.delayedCall(wait, () => { + if (this.dead) return; + if (this.paused) { this.busy = false; return; } + this.doAiAction(actor).then(() => { this.busy = false; this.time.delayedCall(0, () => this.advance()); }); + }); } async doAiAction(seat) { const gs = this.gs; const skill = this.skillBySeat[seat] ?? 3; - - if (gs.phase === 'auction') { - const bid = chooseBid(gs, seat, skill); - if (bid !== null) { - this.gs = placeBid(this.gs, seat, bid); - } else { - this.gs = passAuction(this.gs, seat); - } - this.render(); - return; - } - - if (gs.current !== seat) return; - switch (gs.phase) { + case 'auction': { + const bid = chooseBid(gs, seat, skill); + this.gs = bid !== null ? L.placeBid(gs, seat, bid) : L.passAuction(gs, seat); + return; + } + case 'debt': { + const a = chooseDebtAction(gs, seat, skill); + if (!a) return; + if (a.action === 'settle') this.gs = L.settleDebt(gs); + else if (a.action === 'bankrupt') this.gs = L.declareBankruptcy(gs); + else this.gs = ({ mortgage: L.mortgageProperty, sellHouse: L.sellHouse, sellHotel: L.sellHotel }[a.action])(gs, seat, a.spaceIdx); + return; + } case 'preroll': { - // Build first if possible - const buildAct = chooseBuild(gs, seat, skill); - if (buildAct) { - if (buildAct.action === 'hotel') { - this.gs = buildHotel(this.gs, seat, buildAct.spaceIdx); - } else { - this.gs = buildHouse(this.gs, seat, buildAct.spaceIdx); + if (gs.current !== seat) return; + if (this.aiManageCount < 24) { + const m = chooseManage(gs, seat, skill); + if (m) { + const fn = m.action === 'hotel' ? L.buildHotel : m.action === 'house' ? L.buildHouse : L.unmortgageProperty; + const next = fn(gs, seat, m.spaceIdx); + if (next !== gs) { this.aiManageCount++; this.gs = next; return; } } - this.render(); - await this.delay(350); - await this.doAiAction(seat); - return; } - // Jail handling - if (gs.players[seat].jailed) { + this.aiManageCount = 0; + const p = gs.players[seat]; + if (p.jailed) { const ja = chooseJailAction(gs, seat, skill); - if (ja === 'card' && gs.players[seat].getOutOfJailFree > 0) { - this.gs = useJailCard(this.gs, seat); - this.render(); - await this.delay(500); - } else if (ja === 'pay' && gs.players[seat].cash >= 50) { - this.gs = payJailFine(this.gs, seat); - this.render(); - await this.delay(500); - } + if (ja === 'card' && p.getOutOfJailFree > 0) { this.gs = L.useJailCard(gs, seat); return; } + if (ja === 'pay' && p.cash >= 50) { this.gs = L.payJailFine(gs, seat); return; } } await this.executeRoll(seat); - break; + return; } case 'buy': { - // Modal already zoomed in (advance() called showPropertyModal before doAiAction) - const buy = chooseBuy(gs, seat, skill); - await this.delay(700); // AI "thinking" pause - if (buy) { - this.gs = buyProperty(this.gs, seat); - await this.dismissPropertyModal(); // fill with owner color + zoom back - } else { - this.gs = declineProperty(this.gs, seat); - await this.shiftModalForAuction(); + await this.delay(500 * this.pace() * (this.isFast(seat) ? 0.3 : 1)); + if (chooseBuy(gs, seat, skill)) this.gs = L.buyProperty(gs, seat); + else { + this.gs = L.declineProperty(gs, seat); + if (this.gs.phase === 'auction') await this.shiftModalForAuction(); } - this.render(); - break; + return; } case 'card': { - await this.delay(2800); - this.cardAnimPlayed = false; - this.gs = applyCardEffect(this.gs, seat); - this.render(); - // If card moved player to buy or another phase, handle next advance - break; + await this.delay((this.isFast(seat) ? 500 : 2200) * this.pace()); + await this.resolveCard(seat); + return; } case 'endturn': { - await this.aiAttemptTrades(seat); - await this.delay(450); - this.gs = endTurn(this.gs); - this.render(); - break; + if (gs.current !== seat) return; + if (!this.aiTraded) { + this.aiTraded = true; + await this.aiAttemptTrades(seat); + return; + } + this.aiTraded = false; + this.gs = L.endTurn(gs); + return; } + default: } } async executeRoll(seat) { - const d1 = Math.floor(Math.random() * 6) + 1; - const d2 = Math.floor(Math.random() * 6) + 1; - playSound(this, SFX.DICE_ROLL); - await this.animateDice(d1, d2); - const prevPos = this.gs.players[seat].position; + const d1 = 1 + Math.floor(Math.random() * 6); + const d2 = 1 + Math.floor(Math.random() * 6); + this.tray.setInk(PLAYER_COLORS[seat]); + this.tray.setGlow(0); + await this.tray.throw(d1, d2, { fast: this.isFast(seat), speed: seat === this.humanSeat ? 1 : this.pace() }); const wasJailed = this.gs.players[seat].jailed; - this.gs = rollDice(this.gs, seat, d1, d2); - const finalPos = this.gs.players[seat].position; - const nowJailed = this.gs.players[seat].jailed; - // Animate the dice-total steps; snap to finalPos afterward if redirected (e.g. Go to Jail) - const diceTarget = (prevPos + d1 + d2) % 40; - const shouldAnimate = wasJailed ? !nowJailed : true; - if (shouldAnimate) { - await this.animatePawnMove(seat, prevPos, diceTarget); - if (finalPos !== diceTarget) { - const pawn = this.pawns[seat]; - if (pawn) { const { x, y } = this.spacePxCenter(finalPos); pawn.x = x; pawn.y = y; } + this.gs = L.rollDice(this.gs, seat, d1, d2); + if (d1 === d2) { + this.tray.setGlow(0.9); + const p = this.gs.players[seat]; + if (wasJailed && !p.jailed) this.ribbon('DOUBLES — OUT OF JAIL!'); + else if (!p.jailed) this.ribbon(this.gs.doublesCount === 2 ? 'DOUBLES AGAIN!' : 'DOUBLES!'); + } + } + + async resolveCard(seat) { + this.cardAnimPlayed = false; + let dice; + if (L.cardNeedsDice(this.gs)) { + dice = [1 + Math.floor(Math.random() * 6), 1 + Math.floor(Math.random() * 6)]; + this.closeCardPopup(); + await this.tray.throw(dice[0], dice[1], { fast: this.isFast(seat) }); + } + this.gs = L.applyCardEffect(this.gs, seat, dice ? { dice } : {}); + this.closeCardPopup(); + } + + // ── Fx replay ─────────────────────────────────────────────────────────────── + async playFx() { + const evs = this.gs.fx.filter((e) => e.id > this.lastFx); + this.flights = []; + for (const e of evs) { + if (this.dead) return; + this.lastFx = e.id; + const fast = this.isFast(typeof e.seat === 'number' ? e.seat : this.gs.current) || this.isFast(this.gs.current); + switch (e.type) { + case 'move': await this.animateMove(e, fast); break; + case 'pay': await this.animatePay(e, fast); break; + case 'free': this.pawnInCell[e.seat] = false; this.positionPawns(); break; + case 'build': await this.animateBuild(e, fast); break; + case 'sell': this.puff(bandSpot(e.idx, 0, 1)); Snd.thunk(this, 0.06); break; + case 'deed': await this.animateDeed(e, fast); break; + case 'deeds': await this.animateDeeds(e, fast); break; + case 'mortgage': case 'unmortgage': Snd.thunk(this, 0.08); this.flashSpace(e.idx, e.type === 'mortgage' ? 0xb3261e : 0x2e7d32); break; + case 'auction': Snd.gavel(this, 1); break; + case 'bankrupt': await this.banner(`${this.gs.players[e.seat].name.toUpperCase()} IS BANKRUPT`, '#ff9a8a', fast ? 500 : 1300); break; + default: } } + // let the last bills land, then snap the presentation to the truth + await Promise.all(this.flights); + this.flights = []; + this.hud.sync(this.gs); + for (let s = 0; s < this.gs.playerCount; s++) { + this.pawnPos[s] = this.gs.players[s].position; + this.pawnInCell[s] = this.gs.players[s].jailed; + } + } + + async animateMove(e, fast) { + const seat = e.seat; + if (e.mode === 'jail') { + this.moving.add(seat); + this.pawnInCell[seat] = true; + const start = { x: this.pawns[seat].x, y: this.pawns[seat].y + 6 }; + const end = jailSpot(0, 1, true); + Snd.clang(this); + const banner = this.banner('GO TO JAIL!', '#ff8a80', fast ? 450 : 1100); + await this.tweenPawn(seat, start, end, fast ? 260 : 900, 70); + this.moving.delete(seat); + this.pawnPos[seat] = 10; + this.positionPawns(); + await banner; + return; + } + const back = e.mode === 'back'; + const steps = back ? (e.from - e.to + 40) % 40 : (e.to - e.from + 40) % 40; + const per = fast ? 70 : (seat === this.humanSeat ? 190 : 190 * this.pace()); + this.moving.add(seat); + this.pawnInCell[seat] = false; + let cur = e.from; + for (let k = 0; k < steps; k++) { + const next = back ? (cur + 39) % 40 : (cur + 1) % 40; + const a = cur === 10 ? jailSpot(0, 1, false) : pawnSpot(cur, 0, 1); + const b = next === 10 ? jailSpot(0, 1, false) : pawnSpot(next, 0, 1); + await this.tweenPawn(seat, { x: this.pawns[seat].x, y: this.pawns[seat].y + 6 }, b, per, fast ? 8 : 20); + if (!fast) Snd.tap(this, k); + cur = next; + this.pawnPos[seat] = cur; + void a; + } + this.moving.delete(seat); + this.pawnPos[seat] = e.to; + this.positionPawns(); + if (!fast) this.spotlight(e.to); + } + + tweenPawn(seat, from, to, dur, arc) { + const prox = { t: 0 }; + const p = this.pawns[seat]; + return new Promise((resolve) => { + this.tweens.add({ + targets: prox, t: 1, duration: dur, ease: 'Sine.easeInOut', + onUpdate: () => { + const t = prox.t; + const lift = Math.sin(Math.PI * t) * arc; + this.placePawn(seat, from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t, lift); + }, + onComplete: () => { + this.placePawn(seat, to.x, to.y); + if (this.hasPawns && p.setScale) { + this.tweens.killTweensOf(p); + p.setDisplaySize(46, 46); + const sx = p.scaleX, sy = p.scaleY; + p.setScale(sx * 1.08, sy * 0.86); + this.tweens.add({ targets: p, scaleX: sx, scaleY: sy, duration: 120, ease: 'Back.easeOut' }); + } + resolve(); + }, + }); + }); + } + + async animatePay(e, fast) { + const from = this.anchorOf(e.from), to = this.anchorOf(e.to); + if (typeof e.from === 'number') this.hud.bump(e.from, -e.amount); + if (e.why === 'salary') Snd.bell(this); + else if (e.why === 'tax' || e.why === 'jail fine') playSoundEx(this, SFX.MONOPOLY_EXPENSE, { volume: 0.6 }); + else if (e.why === 'rent') playSound(this, SFX.MONOPAY); + const done = this.bank.pay(from, to, e.amount, { + fast, + onArrive: () => { + if (typeof e.to === 'number') this.hud.bump(e.to, e.amount); + if (e.why === 'rent') playSoundEx(this, SFX.MONOPOLY_PAID, { volume: 0.7 }); + if (e.to === 'pot') this.bank.updatePot(this.gs); + }, + }); + this.flights.push(done); + // short payments overlap a little with the next event + if (fast || e.amount < 60) await this.delay(fast ? 120 : 260); + else await done; + } + + async animateBuild(e, fast) { + const own = this.gs.board[e.idx]; + const isHotel = e.kind === 'hotel'; + const n = isHotel ? 1 : Math.max(1, own.houses); + const p = isHotel ? bandSpot(e.idx, 0, 1) : bandSpot(e.idx, n - 1, n, 17); + const img = this.add.image(p.x, p.y - 70, isHotel ? 'mono-hotel' : 'mono-house') + .setDisplaySize(isHotel ? 32 : 19, isHotel ? 21 : 19).setDepth(DEPTH.build + 1).setAlpha(0); + await new Promise((res) => this.tweens.add({ + targets: img, y: p.y - 2, alpha: 1, duration: fast ? 140 : 380, ease: 'Bounce.easeOut', onComplete: res, + })); + Snd.thunk(this); + this.puff(p); + this.time.delayedCall(fast ? 60 : 200, () => img.destroy()); this.render(); } - // ── Animations ───────────────────────────────────────────────────────────── - animateDice(d1, d2) { - return new Promise(resolve => { - const defaultX = RP_X + RP_W / 2 - 55; - const defaultY = this.diceY; + async animateDeed(e, fast) { + if (e.auction) { Snd.gavel(this, 3); this.ribbon(`SOLD TO ${this.gs.players[e.seat].name.toUpperCase()}!`); } + // the deed card goes back to its space (stamped SOLD) before it flies to the rail + if (this.modalActive && this.modalSpaceIdx === e.idx) await this.dismissPropertyModal(); + Snd.kaching(this); + const c = spaceCenter(e.idx); + const to = this.hud.railPoint(e.seat); + const img = this.add.image(c.x, c.y, `mono-mini-${e.idx}`).setDisplaySize(60, 84).setDepth(DEPTH.bills); + await new Promise((res) => this.tweens.add({ + targets: img, x: to.x, y: to.y, displayWidth: 30, displayHeight: 42, angle: 360, + duration: fast ? 260 : 700, ease: 'Cubic.easeInOut', onComplete: res, + })); + img.destroy(); + this.hud.railSig[e.seat] = null; + this.hud.renderRail(this.gs, e.seat); + this.render(); + } - // Landing positions — scattered near default spots, random angle - const land0 = { - x: defaultX + Phaser.Math.Between(-20, 20), - y: defaultY + Phaser.Math.Between(-14, 14), - angle: Phaser.Math.Between(-30, 30), - }; - const land1 = { - x: defaultX + 84 + Phaser.Math.Between(-20, 20), - y: defaultY + Phaser.Math.Between(-14, 14), - angle: Phaser.Math.Between(-30, 30), - }; - - // Throw origin — below the landing area (like a hand tossing upward) - const throwX = RP_X + RP_W / 2; - const throwY = GAME_HEIGHT - 40; - - // Arch control points — above the landing area so dice overshoot upward then fall back down - const ctrl0 = { x: defaultX - 60, y: defaultY - 380 }; - const ctrl1 = { x: defaultX + 80, y: defaultY - 350 }; - - // Total spin per die: 2–3 full rotations ending at the landing angle - const dir0 = Math.random() < 0.5 ? 1 : -1; - const dir1 = Math.random() < 0.5 ? 1 : -1; - const spin0 = dir0 * (Phaser.Math.Between(2, 3) * 360 + land0.angle * dir0); - const spin1 = dir1 * (Phaser.Math.Between(2, 3) * 360 + land1.angle * dir1); - - const THROW_MS = 820; - let face0 = Phaser.Math.Between(1, 6); - let face1 = Phaser.Math.Between(1, 6); - - // Randomize pip faces during flight - const faceTimer = this.time.addEvent({ - delay: 90, - repeat: Math.ceil(THROW_MS / 90), - callback: () => { - face0 = Phaser.Math.Between(1, 6); - face1 = Phaser.Math.Between(1, 6); - }, - }); - - this.diceAnimating = true; - - const proxy = { t: 0 }; + async animateDeeds(e, fast) { + const from = this.hud.railPoint(e.from), to = this.hud.railPoint(e.to); + await Promise.all(e.idxs.map((idx, k) => new Promise((res) => { + const img = this.add.image(from.x, from.y, `mono-mini-${idx}`).setDisplaySize(30, 42).setDepth(DEPTH.bills); this.tweens.add({ - targets: proxy, - t: 1, - duration: THROW_MS, - ease: 'Sine.easeIn', - onUpdate: () => { - const t = proxy.t; - const inv = 1 - t; - - // Quadratic bezier: start → control → land - const x0 = inv*inv*throwX + 2*inv*t*ctrl0.x + t*t*land0.x; - const y0 = inv*inv*throwY + 2*inv*t*ctrl0.y + t*t*land0.y; - const x1 = inv*inv*throwX + 2*inv*t*ctrl1.x + t*t*land1.x; - const y1 = inv*inv*throwY + 2*inv*t*ctrl1.y + t*t*land1.y; - - // Scale up as dice approach (perspective/depth effect) - const scale = 0.45 + t * 0.55; - this.dieGfx[0].setScale(scale); - this.dieGfx[1].setScale(scale); - - this.drawDie(0, x0, y0, face0, spin0 * t); - this.drawDie(1, x1, y1, face1, spin1 * t); - }, - onComplete: () => { - faceTimer.remove(); - - // Snap to final values at landing positions - this.dieGfx[0].setScale(1); - this.dieGfx[1].setScale(1); - this.drawDie(0, land0.x, land0.y, d1, land0.angle); - this.drawDie(1, land1.x, land1.y, d2, land1.angle); - - // Store landing state for subsequent renders - this.dicePositions[0] = { cx: land0.x, cy: land0.y, angle: land0.angle }; - this.dicePositions[1] = { cx: land1.x, cy: land1.y, angle: land1.angle }; - - // Impact bounce: scale 1 → 1.18 → 1 - this.dieGfx[0].setScale(1.18); - this.dieGfx[1].setScale(1.18); - this.tweens.add({ - targets: [this.dieGfx[0], this.dieGfx[1]], - scaleX: 1, scaleY: 1, - duration: 200, - ease: 'Back.easeOut', - onComplete: () => { - this.diceAnimating = false; - resolve(); - }, - }); - }, + targets: img, x: to.x + (k - (e.idxs.length - 1) / 2) * 12, y: to.y, delay: k * 80, duration: fast ? 240 : 650, ease: 'Cubic.easeInOut', + onComplete: () => { img.destroy(); res(); }, }); - }); + }))); + this.hud.railSig[e.from] = null; this.hud.railSig[e.to] = null; + this.hud.renderRail(this.gs, e.from); this.hud.renderRail(this.gs, e.to); + this.render(); } - animatePawnMove(seat, fromPos, toPos) { - return new Promise(resolve => { - const steps = ((toPos - fromPos + 40) % 40) || 0; - if (steps === 0) { resolve(); return; } - const pawn = this.pawns[seat]; - if (!pawn) { resolve(); return; } - - // Board center — arches always point toward here - const BOARD_CX = BL + BS / 2; - const BOARD_CY = BT + BS / 2; - const ARCH_H = 44; // pixels the arc peak is pushed toward board center - - let step = 0; - let cur = fromPos; - - const hopOne = () => { - if (step >= steps) { resolve(); return; } - step++; - const fromSpace = cur; - cur = (cur + 1) % 40; - - const start = { x: pawn.x, y: pawn.y }; - const { x: ex, y: ey } = this.spacePxCenter(cur); - - // Midpoint of start → end - const mx = (start.x + ex) / 2; - const my = (start.y + ey) / 2; - - // Unit vector from midpoint toward board center - const dx = BOARD_CX - mx; - const dy = BOARD_CY - my; - const dist = Math.hypot(dx, dy); - let nx = dist > 0 ? dx / dist : 0; - let ny = dist > 0 ? dy / dist : -1; - - // Top row (spaces 20–29): arch away from center so the piece hops outward - if (fromSpace >= 20 && fromSpace <= 29) { nx = -nx; ny = -ny; } - - // Quadratic Bézier control point: ARCH_H px toward/away from board center - const ctrl = { x: mx + nx * ARCH_H, y: my + ny * ARCH_H }; - - const proxy = { t: 0 }; - this.tweens.add({ - targets: proxy, - t: 1, - duration: 500, - ease: 'Sine.easeInOut', - onUpdate: () => { - const t = proxy.t; - const inv = 1 - t; - pawn.x = inv * inv * start.x + 2 * inv * t * ctrl.x + t * t * ex; - pawn.y = inv * inv * start.y + 2 * inv * t * ctrl.y + t * t * ey; - }, - onComplete: () => { - playSound(this, SFX.PIECE_CLICK); - hopOne(); - }, - }); - }; - - hopOne(); - }); - } - - // ── Property Purchase Modal ──────────────────────────────────────────────── - - buildPropertyCardContainer(spaceIdx) { - const sp = SPACES[spaceIdx]; - const w = MODAL_W, h = MODAL_H, bh = MODAL_BAND_H; - const container = this.add.container(0, 0); - - const g = this.add.graphics(); - - // Card background + border - g.fillStyle(0xFFF8E7, 1); - g.fillRoundedRect(-w/2, -h/2, w, h, 8); - g.lineStyle(2, 0x2c1810, 1); - g.strokeRoundedRect(-w/2, -h/2, w, h, 8); - - // Top band - const bandCol = sp.group ? GROUP_COLORS[sp.group] - : sp.type === 'railroad' ? 0x1a1208 - : sp.type === 'utility' && spaceIdx === 12 ? 0xFFD700 - : 0x1565C0; - g.fillStyle(bandCol, 1); - g.fillRoundedRect(-w/2, -h/2, w, bh, { tl:8, tr:8, bl:0, br:0 }); - - // Band separator line - g.lineStyle(1, 0x2c1810, 0.5); - g.beginPath(); g.moveTo(-w/2, -h/2 + bh); g.lineTo(w/2, -h/2 + bh); g.strokePath(); - - container.add(g); - - const bandTextCol = '#FFF8E7'; - const darkTextCol = '#1a1208'; - - // "TITLE DEED" inside band - container.add(this.add.text(0, -h/2 + 8, 'TITLE DEED', { - fontFamily: '"Julius Sans One"', fontSize: '10px', color: bandTextCol, align: 'center', - }).setOrigin(0.5, 0)); - - // Property name inside band - container.add(this.add.text(0, -h/2 + 24, sp.name, { - fontFamily: 'Righteous', fontSize: '18px', color: bandTextCol, - align: 'center', wordWrap: { width: w - 20, useAdvancedWrap: true }, - }).setOrigin(0.5, 0)); - - // --- Content area below band --- - const contentTop = -h/2 + bh + 14; - let cy = contentTop; - - if (sp.type === 'property') { - const rentLabels = [ - ['Rent', sp.rent[0]], - ['Color group', sp.rent[1]], - ['1 House', sp.rent[2]], - ['2 Houses', sp.rent[3]], - ['3 Houses', sp.rent[4]], - ['4 Houses', sp.rent[5]], - ['Hotel', sp.rent[6]], - ]; - rentLabels.forEach(([label, val]) => { - const row = this.add.text(0, cy, `${label} $${val}`, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: darkTextCol, align: 'center', - }).setOrigin(0.5, 0); - container.add(row); - cy += 20; - }); - cy += 6; - container.add(this.add.text(0, cy, `Houses / Hotels $${sp.houseCost} each`, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#555544', align: 'center', - }).setOrigin(0.5, 0)); - cy += 16; - container.add(this.add.text(0, cy, `Mortgage value $${sp.mortgage}`, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#555544', align: 'center', - }).setOrigin(0.5, 0)); - } else if (sp.type === 'railroad') { - [['1 Railroad', '$25'], ['2 Railroads', '$50'], ['3 Railroads', '$100'], ['4 Railroads', '$200']] - .forEach(([label, val]) => { - container.add(this.add.text(0, cy, `${label} ${val}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: darkTextCol, align: 'center', - }).setOrigin(0.5, 0)); - cy += 24; - }); - cy += 6; - container.add(this.add.text(0, cy, `Mortgage value $${sp.mortgage}`, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#555544', align: 'center', - }).setOrigin(0.5, 0)); - } else if (sp.type === 'utility') { - ['If 1 Utility owned:', '4× your dice roll', '', 'If 2 Utilities owned:', '10× your dice roll'] - .forEach((line) => { - container.add(this.add.text(0, cy, line, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: darkTextCol, align: 'center', - }).setOrigin(0.5, 0)); - cy += line ? 20 : 8; - }); - cy += 6; - container.add(this.add.text(0, cy, `Mortgage value $${sp.mortgage}`, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: '#555544', align: 'center', - }).setOrigin(0.5, 0)); + puff(p) { + for (let k = 0; k < 6; k++) { + const a = (k / 6) * Math.PI * 2; + const d = this.add.image(p.x, p.y, 'mono-puff').setDepth(DEPTH.build + 2).setScale(0.6).setAlpha(0.8); + this.tweens.add({ targets: d, x: p.x + Math.cos(a) * 22, y: p.y + Math.sin(a) * 10 - 4, scale: 1.2, alpha: 0, duration: 420, onComplete: () => d.destroy() }); } - - // Price banner near bottom of info area - container.add(this.add.text(0, h/2 - 88, `Purchase Price $${sp.price}`, { - fontFamily: 'Righteous', fontSize: '18px', color: darkTextCol, align: 'center', - }).setOrigin(0.5, 0)); - - // Horizontal rule above price - const ruleG = this.add.graphics(); - ruleG.lineStyle(1, 0x2c1810, 0.4); - ruleG.beginPath(); ruleG.moveTo(-w/2 + 12, h/2 - 98); ruleG.lineTo(w/2 - 12, h/2 - 98); ruleG.strokePath(); - container.add(ruleG); - - // Player pieces currently on this space - const onSpace = this.gs.players.filter(p => p.position === spaceIdx && !p.bankrupt); - if (onSpace.length > 0) { - const spacing = 52; - const startX = -(onSpace.length - 1) * spacing / 2; - onSpace.forEach((p, i) => { - const px = startX + i * spacing; - const py = h/2 - 44; - if (this.hasPawns) { - container.add(this.add.image(px, py, 'monopoly-pawns', PAWN_FRAME(p.seat)).setDisplaySize(44, 44)); - } else { - const pg = this.add.graphics(); - pg.fillStyle(PLAYER_COLORS[p.seat], 1); - pg.fillCircle(px, py, 20); - pg.lineStyle(2, 0xffffff, 0.8); - pg.strokeCircle(px, py, 20); - container.add(pg); - } - }); - } - - return container; } + spotlight(idx) { + const c = spaceCenter(idx); + const g = this.add.image(c.x, c.y, 'mono-glow').setDepth(DEPTH.threat).setScale(1.3).setAlpha(0.85).setBlendMode(Phaser.BlendModes.ADD); + this.tweens.add({ targets: g, alpha: 0, scale: 1.7, duration: 900, onComplete: () => g.destroy() }); + } + + flashSpace(idx, color) { + const r = spaceRect(idx); + const g = this.add.graphics().setDepth(DEPTH.threat); + g.fillStyle(color, 0.45).fillRect(r.x, r.y, r.w, r.h); + this.tweens.add({ targets: g, alpha: 0, duration: 600, onComplete: () => g.destroy() }); + } + + // A deco plate across the middle of the board. + banner(text, color = '#ecd690', hold = 1000) { + const g = this.add.graphics().setDepth(DEPTH.banner); + const w = 640, h = 104, x = BOARD_CX - w / 2, y = BOARD_CY - h / 2; + g.fillStyle(0x140b05, 0.92).fillRoundedRect(x, y, w, h, 14); + g.lineStyle(3, 0xc9a24a, 1).strokeRoundedRect(x, y, w, h, 14); + g.lineStyle(1, 0xecd690, 0.6).strokeRoundedRect(x + 7, y + 7, w - 14, h - 14, 10); + const t = this.add.text(BOARD_CX, BOARD_CY, text, { fontFamily: DISPLAY, fontSize: '44px', color, stroke: '#140b05', strokeThickness: 4 }) + .setOrigin(0.5).setDepth(DEPTH.banner + 1); + if (t.width > w - 40) t.setScale((w - 40) / t.width); + const objs = [g, t]; + objs.forEach((o) => { o.setAlpha(0); }); + this.tweens.add({ targets: objs, alpha: 1, duration: 160 }); + return new Promise((res) => this.time.delayedCall(hold, () => { + this.tweens.add({ targets: objs, alpha: 0, duration: 220, onComplete: () => { objs.forEach((o) => o.destroy()); res(); } }); + })); + } + + ribbon(text) { + const t = this.add.text(BOARD_CX, BOARD.y + BOARD.h - 190, text, { + fontFamily: DISPLAY, fontSize: '34px', color: '#fff3c4', stroke: '#7a4a0a', strokeThickness: 6, + }).setOrigin(0.5).setDepth(DEPTH.banner).setScale(0.4).setAlpha(0); + this.tweens.add({ targets: t, scale: 1, alpha: 1, duration: 260, ease: 'Back.easeOut' }); + this.tweens.add({ targets: t, alpha: 0, y: t.y - 30, delay: 1300, duration: 400, onComplete: () => t.destroy() }); + } + + async rentBanner() { + const { payer, receiver, amount, spaceIdx } = this.gs.pendingRent; + const fast = this.isFast(payer) && this.isFast(receiver); + const P = this.gs.players; + playSound(this, SFX.MONOPOLY_EXPENSE); + const sub = `${P[payer].name} → ${P[receiver].name} · ${SPACES[spaceIdx].name}`; + const sg = this.add.text(BOARD_CX, BOARD_CY + 76, sub, { fontFamily: DECO, fontSize: '18px', color: '#f3e7c8', stroke: '#140b05', strokeThickness: 4 }) + .setOrigin(0.5).setDepth(DEPTH.banner + 1); + await this.banner(`RENT $${amount.toLocaleString()}`, '#ffd27a', fast ? 350 : 1000); + sg.destroy(); + } + + // ── Cards ─────────────────────────────────────────────────────────────────── + async animateCardDraw() { + const { cardType } = this.gs.pendingCard; + const isChance = cardType === 'chance'; + const deck = isChance ? CHANCE_DECK : CC_DECK; + const fast = this.isFast(this.gs.current); + this.cardAnimating = true; + this.hidePortraits(); + const CW = 360; + const card = this.add.image(deck.x, deck.y, isChance ? 'mono-back-chance' : 'mono-back-cc') + .setDisplaySize(DECK_W, DECK_H).setRotation(deck.rot).setDepth(DEPTH.popup); + playSound(this, SFX.CARD_DEAL); + await new Promise((res) => this.tweens.add({ + targets: card, x: BOARD_CX, y: BOARD_CY, rotation: 0, displayWidth: CW * 0.7, displayHeight: 480 * 0.7, + duration: fast ? 220 : 600, ease: 'Cubic.easeOut', onComplete: res, + })); + await new Promise((res) => this.tweens.add({ targets: card, scaleX: 0, duration: fast ? 80 : 160, ease: 'Sine.easeIn', onComplete: res })); + card.destroy(); + playSound(this, SFX.UI_FLIP); + this.cardAnimating = false; + } + + closeCardPopup() { this.cardPopupObjs.forEach((o) => { try { o.destroy(); } catch { /* */ } }); this.cardPopupObjs = []; } + + drawCardPopup() { + this.closeCardPopup(); + const gs = this.gs; + if (!gs.pendingCard || gs.phase !== 'card' || !this.cardAnimPlayed) return; + const { cardType, text } = gs.pendingCard; + const isChance = cardType === 'chance'; + const pw = 360, ph = 480; + const px = BOARD_CX - pw / 2, py = BOARD_CY - ph / 2; + const add = (o) => { this.cardPopupObjs.push(o); return o; }; + const ov = add(this.add.graphics().setDepth(DEPTH.popup - 1)); + ov.fillStyle(0x000000, 0.55).fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); + const g = add(this.add.graphics().setDepth(DEPTH.popup)); + const col = isChance ? 0xd9622b : 0x2f6db0; + g.fillStyle(0x000000, 0.4).fillRoundedRect(px + 8, py + 12, pw, ph, 16); + g.fillStyle(col, 1).fillRoundedRect(px, py, pw, ph, 16); + g.lineStyle(4, 0xfbf1dc, 1).strokeRoundedRect(px + 6, py + 6, pw - 12, ph - 12, 12); + g.lineStyle(1, 0xfbf1dc, 0.7).strokeRoundedRect(px + 14, py + 14, pw - 28, ph - 28, 8); + if (this.hasCards) { + add(this.add.image(px + pw / 2, py + 160, 'monopoly-cards', isChance ? CARD_FRAME.chance : CARD_FRAME.community_chest) + .setDisplaySize(146, 220).setDepth(DEPTH.popup)); + } else { + add(this.add.image(px + pw / 2, py + 160, isChance ? 'mono-back-chance' : 'mono-back-cc').setDisplaySize(150, 212).setDepth(DEPTH.popup)); + } + add(this.add.text(px + pw / 2, py + 34, isChance ? 'CHANCE' : 'COMMUNITY CHEST', { + fontFamily: DISPLAY, fontSize: '24px', color: '#fbf1dc', stroke: '#00000066', strokeThickness: 3, + }).setOrigin(0.5).setDepth(DEPTH.popup + 1)); + const tg = add(this.add.graphics().setDepth(DEPTH.popup)); + tg.fillStyle(0xfbf1dc, 1).fillRoundedRect(px + 22, py + 282, pw - 44, 130, 10); + add(this.add.text(px + pw / 2, py + 347, text, { + fontFamily: DECO, fontSize: '17px', color: '#241a10', align: 'center', wordWrap: { width: pw - 70 }, lineSpacing: 4, + }).setOrigin(0.5).setDepth(DEPTH.popup + 1)); + if (gs.current === this.humanSeat && !this.busy) { + const b = new Button(this, px + pw / 2, py + ph - 38, 'OK', () => this.onDismissCard(), { width: 200, height: 46, fontSize: 20, bg: 0x4a2e1a }); + b.setDepth(DEPTH.popup + 2); + add(b); + } else { + add(this.add.text(px + pw / 2, py + ph - 38, `${gs.players[gs.current].name} reads the card…`, { fontFamily: DECO, fontSize: '15px', color: '#fbf1dc' }) + .setOrigin(0.5).setDepth(DEPTH.popup + 1)); + } + } + + // ── Auction panel ─────────────────────────────────────────────────────────── + drawAuctionPanel() { + const gs = this.gs; + const auc = gs.pendingAuction; + const sp = SPACES[auc.spaceIdx]; + const bidder = L.auctionBidder(gs); + const isHuman = bidder === this.humanSeat && !this.busy; + const pw = 560, ph = 470, px = 500, py = BOARD_CY - ph / 2; + this.reg(Dlg.frame(this, px, py, pw, ph, DEPTH.popup)); + const T = (x, y, s, size, color, font = DECO) => this.reg(this.add.text(x, y, s, { fontFamily: font, fontSize: `${size}px`, color, align: 'center', wordWrap: { width: pw - 60 } }) + .setOrigin(0.5).setDepth(DEPTH.popup + 1)); + T(px + pw / 2, py + 46, auc.reason === 'bankrupt' ? 'BANKRUPTCY AUCTION' : 'AUCTION', 32, '#ecd690', DISPLAY); + T(px + pw / 2, py + 84, `${sp.name} · list price $${sp.price}`, 18, '#f3e7c8'); + const hb = auc.highBidder !== null ? `High bid $${auc.highBid.toLocaleString()} — ${gs.players[auc.highBidder].name}` : 'No bids yet — open the bidding!'; + T(px + pw / 2, py + 126, hb, 24, auc.highBidder !== null ? PLAYER_COLOR_HEX[auc.highBidder] : '#c9b892', DISPLAY); + // paddle row: who is still in + const live = auc.bidders; + const all = gs.players.filter((p) => p.active); + all.forEach((p, k) => { + const x = px + pw / 2 + (k - (all.length - 1) / 2) * 120; + const inIt = live.includes(p.seat); + const g = this.reg(this.add.graphics().setDepth(DEPTH.popup + 1)); + g.fillStyle(PLAYER_COLORS[p.seat], inIt ? 1 : 0.25).fillCircle(x, py + 186, 22); + g.lineStyle(3, p.seat === bidder ? 0xffffff : 0x140b05, 1).strokeCircle(x, py + 186, 22); + g.fillStyle(0x6b4a2a, inIt ? 1 : 0.3).fillRect(x - 3, py + 208, 6, 22); + T(x, py + 186, inIt ? (p.seat === auc.highBidder ? '★' : '') : '✕', 18, '#ffffff', DISPLAY); + T(x, py + 246, p.name.length > 10 ? `${p.name.slice(0, 9)}…` : p.name, 13, inIt ? '#f3e7c8' : '#7a6a50'); + }); + const last = auc.history.slice(-2).map((h) => (h.pass ? `${gs.players[h.seat].name} drops out.` : `${gs.players[h.seat].name} bids $${h.amount}.`)).join(' '); + T(px + pw / 2, py + 280, last || ' ', 14, '#c9b892'); + + if (isHuman) { + const me = gs.players[this.humanSeat]; + const min = auc.highBid + 1; + if (this.bidInput < min) this.bidInput = Math.min(me.cash, Math.max(min, auc.highBid + 10)); + if (this.bidInput > me.cash) this.bidInput = me.cash; + const can = me.cash >= min; + T(px + pw / 2, py + 318, can ? `Your bid: $${this.bidInput.toLocaleString()} (cash $${me.cash.toLocaleString()})` : `You can't top $${auc.highBid} — you have $${me.cash}.`, 19, '#ecd690', DISPLAY); + [[-10, '−10'], [1, '+1'], [10, '+10'], [50, '+50'], [100, '+100']].forEach(([d, label], k) => { + const b = new Button(this, px + pw / 2 + (k - 2) * 96, py + 362, label, () => { + this.bidInput = Math.max(min, Math.min(me.cash, this.bidInput + d)); this.render(); + }, { width: 86, height: 36, fontSize: 16, bg: 0x4a2e1a }); + b.setDepth(DEPTH.popup + 2); if (!can) b.setEnabled(false); this.reg(b); + }); + const bid = new Button(this, px + pw / 2 - 110, py + ph - 48, `Bid $${this.bidInput.toLocaleString()}`, () => { + if (this.busy) return; + const amt = this.bidInput; this.bidInput = 0; + Snd.gavel(this, 1); + this.commit(L.placeBid(this.gs, this.humanSeat, amt)); + }, { width: 200, height: 50, fontSize: 20, bg: 0x1d6a48 }); + bid.setDepth(DEPTH.popup + 2); if (!can) bid.setEnabled(false); this.reg(bid); + const pass = new Button(this, px + pw / 2 + 110, py + ph - 48, 'Drop Out', () => { + if (this.busy) return; + this.bidInput = 0; + this.commit(L.passAuction(this.gs, this.humanSeat)); + }, { width: 200, height: 50, fontSize: 20, bg: 0x6a2a1a }); + pass.setDepth(DEPTH.popup + 2); this.reg(pass); + } else { + T(px + pw / 2, py + 360, bidder !== null ? `${gs.players[bidder].name} is considering…` : '', 18, '#c9b892'); + } + } + + // ── Property purchase modal ───────────────────────────────────────────────── + buildPropertyCardContainer(idx) { return buildDeedCard(this, this.gs, idx, { live: false }); } + async showPropertyModal(spaceIdx) { - const geo = spaceGeometry(spaceIdx); - const ox = BL + geo.x + geo.w / 2; - const oy = BT + geo.y + geo.h / 2; - const scaleStart = geo.w / MODAL_W; - const rotStart = -geo.rotation; - - // Hide DOM portraits immediately — they render above canvas regardless of depth - this.hidePortraits(); - - // Dim overlay - this.modalOverlay = this.add.rectangle(GAME_WIDTH/2, GAME_HEIGHT/2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0) + const c0 = spaceCenter(spaceIdx); + const scaleStart = 80 / MODAL_W; + const rotStart = spaceRot(spaceIdx); + this.hideHoverDeed(); + this.modalOverlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0) .setDepth(DEPTH.popup - 2).setInteractive(); - this.modalGfx.push(this.modalOverlay); - this.tweens.add({ targets: this.modalOverlay, alpha: 0.68, duration: 400 }); - - // Property card container - const container = this.buildPropertyCardContainer(spaceIdx); - container.setPosition(ox, oy).setScale(scaleStart).setRotation(rotStart).setDepth(DEPTH.popup - 1); - this.modalGfx.push(container); - this.modalContainer = container; - this.modalSpaceIdx = spaceIdx; - this.modalOrigin = { ox, oy, scaleStart, rotStart }; - this.modalActive = true; - - return new Promise(resolve => { - this.tweens.add({ - targets: container, - x: MODAL_TARGET_X, y: MODAL_TARGET_Y, - scaleX: 1, scaleY: 1, - rotation: 0, - duration: 700, - ease: 'Cubic.easeOut', - onComplete: resolve, - }); - }); - } - - async animateModalFill(seat) { - if (!this.modalContainer) return; - playSound(this, SFX.MONOPOLY_PURCHASE); - const fillGfx = this.add.graphics(); - this.modalContainer.add(fillGfx); - const proxy = { h: 0 }; - return new Promise(resolve => { - this.tweens.add({ - targets: proxy, - h: MODAL_H, - duration: 1200, - ease: 'Linear', - onUpdate: () => { - fillGfx.clear(); - fillGfx.fillStyle(PLAYER_COLORS[seat], 0.55); - fillGfx.fillRect(-MODAL_W/2, MODAL_H/2 - proxy.h, MODAL_W, proxy.h); - }, - onComplete: resolve, - }); - }); + this.tweens.add({ targets: this.modalOverlay, alpha: 0.6, duration: 350 }); + const card = buildDeedCard(this, this.gs, spaceIdx, { pawns: true, hasPawns: this.hasPawns }); + card.setPosition(c0.x, c0.y).setScale(scaleStart).setRotation(rotStart).setDepth(DEPTH.popup - 1); + this.modalContainer = card; + this.modalSpaceIdx = spaceIdx; + this.modalOrigin = { ox: c0.x, oy: c0.y, scaleStart, rotStart }; + this.modalActive = true; + this.hidePortraits(); + const fast = this.isFast(this.gs.current); + playSound(this, SFX.CARD_SHOW); + return new Promise((resolve) => this.tweens.add({ + targets: card, x: MODAL_X, y: MODAL_Y, scaleX: 1, scaleY: 1, rotation: 0, + duration: fast ? 220 : 600, ease: 'Cubic.easeOut', onComplete: resolve, + })); } async shiftModalForAuction() { if (!this.modalContainer) return; - return new Promise(resolve => { - this.tweens.add({ - targets: this.modalContainer, - x: MODAL_AUCTION_X, y: MODAL_AUCTION_Y, - scaleX: MODAL_AUCTION_SCALE, scaleY: MODAL_AUCTION_SCALE, - duration: 400, - ease: 'Cubic.easeInOut', - onComplete: resolve, - }); - }); + return new Promise((resolve) => this.tweens.add({ + targets: this.modalContainer, x: AUCTION_CARD.x, y: AUCTION_CARD.y, scaleX: AUCTION_CARD.scale, scaleY: AUCTION_CARD.scale, + duration: 380, ease: 'Cubic.easeInOut', onComplete: resolve, + })); } async dismissPropertyModal() { - if (!this.modalContainer) return; - - // Fill with owner color if someone bought this property - const winner = this.gs.board?.[this.modalSpaceIdx]?.owner; - if (winner !== null && winner !== undefined) { - await this.animateModalFill(winner); - await this.delay(500); + if (!this.modalContainer) { this.modalActive = false; return; } + const owner = this.gs.board?.[this.modalSpaceIdx]?.owner; + const fast = this.isFast(this.gs.current); + if (owner !== null && owner !== undefined) { + // the owner's seal stamps the deed + const seal = this.add.graphics(); + seal.fillStyle(PLAYER_COLORS[owner], 0.9).fillCircle(MODAL_W / 2 - 60, -MODAL_H / 2 + 130, 34); + seal.lineStyle(3, 0xfbf6e8, 1).strokeCircle(MODAL_W / 2 - 60, -MODAL_H / 2 + 130, 28); + const st = this.add.text(MODAL_W / 2 - 60, -MODAL_H / 2 + 130, 'SOLD', { fontFamily: DISPLAY, fontSize: '16px', color: '#fbf6e8' }).setOrigin(0.5).setAngle(-14); + seal.setScale(2.2); st.setScale(2.2); seal.setAlpha(0); st.setAlpha(0); + this.modalContainer.add([seal, st]); + await new Promise((res) => this.tweens.add({ targets: [seal, st], scale: 1, alpha: 1, duration: fast ? 120 : 260, ease: 'Back.easeOut', onComplete: res })); + await this.delay(fast ? 120 : 450); } - const { ox, oy, scaleStart, rotStart } = this.modalOrigin; - - // Animate card back to board position - const returnP = new Promise(resolve => { - this.tweens.add({ - targets: this.modalContainer, - x: ox, y: oy, - scaleX: scaleStart, scaleY: scaleStart, - rotation: rotStart, - duration: 600, - ease: 'Cubic.easeIn', - onComplete: resolve, - }); - }); - - // Simultaneously fade out overlay - this.tweens.add({ targets: this.modalOverlay, alpha: 0, duration: 400 }); - - await returnP; - - // Destroy container children first (Phaser won't do it automatically) - if (this.modalContainer) { - this.modalContainer.each(child => { try { child.destroy(); } catch {} }); - this.modalContainer.destroy(); - } - if (this.modalOverlay) this.modalOverlay.destroy(); - this.modalGfx = []; - this.modalContainer = null; - this.modalOverlay = null; - this.modalSpaceIdx = null; - this.modalOrigin = null; - this.modalActive = false; + const back = new Promise((resolve) => this.tweens.add({ + targets: this.modalContainer, x: ox, y: oy, scaleX: scaleStart, scaleY: scaleStart, rotation: rotStart, + duration: fast ? 200 : 520, ease: 'Cubic.easeIn', onComplete: resolve, + })); + this.tweens.add({ targets: this.modalOverlay, alpha: 0, duration: 350 }); + await back; + destroyContainer(this.modalContainer); + this.modalOverlay?.destroy(); + this.modalContainer = null; this.modalOverlay = null; this.modalSpaceIdx = null; this.modalOrigin = null; + this.modalActive = false; + this.refreshPortraits(); } drawModalBuyButtons() { const gs = this.gs; - if (!gs.pendingBuy || gs.current !== this.humanSeat) return; + if (!gs.pendingBuy || gs.current !== this.humanSeat || this.busy) return; const sp = SPACES[gs.pendingBuy.spaceIdx]; - const p = gs.players[this.humanSeat]; - const bx = GAME_WIDTH / 2; - const by = MODAL_TARGET_Y + MODAL_H / 2 + 52; - - const buyBtn = new Button(this, bx, by, - `Buy $${sp.price}`, - () => this.onBuyProperty(), - { width: 340, height: 56, fontSize: 24, enabled: p.cash >= sp.price }); - buyBtn.setDepth(DEPTH.popup + 1); - this.reg(buyBtn); - - const declineBtn = new Button(this, bx, by + 66, - 'Decline → Auction', - () => this.onDeclineProperty(), - { width: 340, height: 50, fontSize: 20, variant: 'ghost' }); - declineBtn.setDepth(DEPTH.popup + 1); - this.reg(declineBtn); + const p = gs.players[this.humanSeat]; + const bx = MODAL_X + MODAL_W / 2 + 190, by = MODAL_Y - 90; + const mk = (y, label, fn, o = {}) => { + const b = new Button(this, bx, y, label, fn, { width: 300, height: o.h ?? 54, fontSize: o.size ?? 22, bg: o.bg ?? 0x4a2e1a }); + b.setDepth(DEPTH.popup + 1); + if (o.enabled === false) b.setEnabled(false); + return this.reg(b); + }; + mk(by, `Buy $${sp.price}`, () => this.onBuyProperty(), { bg: 0x1d6a48, enabled: p.cash >= sp.price }); + if (p.cash < sp.price) { + const could = p.cash + L.liquidationValue(gs, this.humanSeat) >= sp.price; + mk(by + 66, could ? 'Raise Funds to Buy…' : `Short $${(sp.price - p.cash).toLocaleString()}`, () => this.openManage(gs.pendingBuy.spaceIdx), { h: 46, size: 17, enabled: could && this.canManage() }); + } + mk(by + (p.cash < sp.price ? 126 : 70), gs.rules.auctions ? 'Decline → Auction' : 'Decline', () => this.onDeclineProperty(), { h: 48, size: 19, bg: 0x6a2a1a }); + this.reg(this.add.text(bx, by + 190, `Cash on hand $${p.cash.toLocaleString()}`, { fontFamily: DECO, fontSize: '16px', color: '#f3e7c8' }).setOrigin(0.5).setDepth(DEPTH.popup + 1)); } - // ── Human Handlers ───────────────────────────────────────────────────────── + // ── Human handlers ────────────────────────────────────────────────────────── onRollDice() { - if (this.busy) return; + if (!this.canHumanRoll()) return; this.busy = true; - this.executeRoll(this.humanSeat).then(() => { - this.busy = false; - this.advance(); - }); + this.render(); // drops the buttons and the threat map while the dice fly + this.executeRoll(this.humanSeat).then(() => { this.busy = false; this.advance(); }); } async onBuyProperty() { if (this.busy) return; - this.busy = true; - this.gs = buyProperty(this.gs, this.humanSeat); // owner set → dismissPropertyModal fills - await this.dismissPropertyModal(); // fill + zoom back - this.busy = false; - this.advance(); + const next = L.buyProperty(this.gs, this.humanSeat); + if (next === this.gs) return; + this.commit(next); } async onDeclineProperty() { if (this.busy) return; this.busy = true; - this.gs = declineProperty(this.gs, this.humanSeat); - await this.shiftModalForAuction(); + this.gs = L.declineProperty(this.gs, this.humanSeat); + if (this.gs.phase === 'auction') await this.shiftModalForAuction(); this.busy = false; this.advance(); } onDismissCard() { - if (this.busy) return; - this.cardAnimPlayed = false; - this.gs = applyCardEffect(this.gs, this.humanSeat); - this.render(); - this.advance(); + if (this.busy || this.gs.phase !== 'card' || this.gs.current !== this.humanSeat) return; + this.busy = true; + this.resolveCard(this.humanSeat).then(() => { this.busy = false; this.advance(); }); } onEndTurn() { - if (this.busy) return; - this.gs = endTurn(this.gs); - this.render(); - this.advance(); + if (this.busy || this.gs.phase !== 'endturn' || !this.humanActing()) return; + const couldBuild = PURCHASABLE.some((i) => L.canBuildHouse(this.gs, this.humanSeat, i) || L.canBuildHotel(this.gs, this.humanSeat, i)); + const go = () => { this.aiTraded = false; this.commit(L.endTurn(this.gs)); }; + if (this.settings.confirmEnd && couldBuild && !(this.gs.doublesCount > 0)) { + this.modal = Dlg.confirmBox(this, { + heading: 'End your turn?', body: 'You could still build houses on a complete set.', yes: 'End Turn', no: 'Build First', depth: POPUP_D, + onYes: () => { this.modal = null; go(); }, + onNo: () => { this.modal = null; this.openManage(); }, + }); + return; + } + go(); } onPayJailFine() { - if (this.busy) return; - if (this.gs.players[this.humanSeat].cash < 50) return; - this.gs = payJailFine(this.gs, this.humanSeat); - this.render(); - this.advance(); + if (this.busy || !this.humanActing()) return; + this.commit(L.payJailFine(this.gs, this.humanSeat)); } onUseJailCard() { - if (this.busy) return; - this.gs = useJailCard(this.gs, this.humanSeat); - this.render(); - this.advance(); + if (this.busy || !this.humanActing()) return; + this.commit(L.useJailCard(this.gs, this.humanSeat)); + } + + // ── Endings ───────────────────────────────────────────────────────────────── + showOut() { + this.outShown = true; + this.paused = true; + this.endH = showEndScreen(this, this.gs, { + humanSeat: this.humanSeat, depth: DEPTH.end, hasPawns: this.hasPawns, out: true, + onWatch: () => { this.endH = null; this.watching = true; this.paused = false; this.refreshPortraits(); this.advance(); }, + onPlayAgain: () => { this.clearSave(); this.scene.restart(this.initData); }, + onMenu: () => { this.clearSave(); this.leave(); }, + }); + this.refreshPortraits(); + } + + showGameOver() { + if (this.endH) return; + this.clearSave(); + const won = this.gs.winner === this.humanSeat; + playSound(this, won ? SFX.VICTORY_SHORT : SFX.CASINO_LOSE); + this.endH = showEndScreen(this, this.gs, { + humanSeat: this.humanSeat, depth: DEPTH.end, hasPawns: this.hasPawns, + onPlayAgain: () => this.scene.restart(this.initData), + onMenu: () => this.leave(), + }); + this.refreshPortraits(); } } + +applyTradeMixin(MonopolyGame); diff --git a/src/games/monopoly/MonopolyHud.js b/src/games/monopoly/MonopolyHud.js new file mode 100644 index 0000000..5eeb25d --- /dev/null +++ b/src/games/monopoly/MonopolyHud.js @@ -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('')}`; +} diff --git a/src/games/monopoly/MonopolyLayout.js b/src/games/monopoly/MonopolyLayout.js new file mode 100644 index 0000000..43b6f08 --- /dev/null +++ b/src/games/monopoly/MonopolyLayout.js @@ -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 }; diff --git a/src/games/monopoly/MonopolyLogic.js b/src/games/monopoly/MonopolyLogic.js index 837be6c..58ace6c 100644 --- a/src/games/monopoly/MonopolyLogic.js +++ b/src/games/monopoly/MonopolyLogic.js @@ -1,13 +1,25 @@ // Monopoly — pure state engine. No Phaser, no rendering. -// All mutators deep-clone and return a fresh state. +// Every exported mutator deep-clones and returns a fresh state; internal +// helpers (lower-case, unexported) mutate the clone they are handed. +// +// Money never goes negative. A payment the payer can't cover in cash becomes a +// debt on state.debts and the game enters phase 'debt': the debtor raises funds +// (sell buildings evenly, mortgage) and settles, or — only when even selling +// everything wouldn't cover it — declares bankruptcy (official rules: to a +// player → buildings sold at half, everything of value to the creditor; to the +// bank → buildings returned, properties auctioned). +// +// state.fx is a short rolling list of presentation events ({id, type, …}) the +// scene replays (bill flights, pawn walks, jail, builds). Ids increase via +// state.fxSeq, so the scene plays only events newer than the last one it saw. import { - SPACES, RAILROADS, UTILITIES, PURCHASABLE, GROUPS, GROUP_COLORS, - CHANCE_CARDS, CC_CARDS, nearestRailroad, nearestUtility, + SPACES, RAILROADS, UTILITIES, PURCHASABLE, GROUPS, DEFAULT_RULES, GOOJF_CARD, + CHANCE_CARDS, CC_CARDS, RAIL_RENT, DICE_P, nearestRailroad, nearestUtility, } from './MonopolyData.js'; // ── RNG ─────────────────────────────────────────────────────────────────────── -function rngFrom(seed) { +export function rngFrom(seed) { let a = (seed >>> 0) || 1; return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; @@ -27,49 +39,113 @@ function shuffle(arr, rng) { } const clone = (s) => JSON.parse(JSON.stringify(s)); +const JAIL = 10; +const half = (n) => Math.floor(n / 2); // ── State ───────────────────────────────────────────────────────────────────── -export function createInitialState({ playerCount, names, seed = Date.now() }) { +export function createInitialState({ playerCount, names = [], seed = Date.now(), rules = {} }) { + const R = { ...DEFAULT_RULES, ...rules }; const rng = rngFrom(seed); const board = {}; for (const idx of PURCHASABLE) board[idx] = { owner: null, houses: 0, hotel: false, mortgaged: false }; - return { + const s = { + version: 2, playerCount, seed, + rules: R, phase: 'preroll', current: 0, doublesCount: 0, diceRoll: null, + round: 1, + turn: 1, houseSupply: 32, hotelSupply: 12, players: Array.from({ length: playerCount }, (_, seat) => ({ seat, name: names[seat] ?? `Player ${seat + 1}`, - cash: 1500, + cash: R.startingCash, position: 0, jailed: false, jailTurns: 0, - getOutOfJailFree: 0, + jailCards: [], // [{ deck:'chance'|'community_chest', idx }] + getOutOfJailFree: 0, // derived: jailCards.length bankrupt: false, + bankruptTurn: null, active: true, })), board, - chanceOrder: shuffle(CHANCE_CARDS.map((_, i) => i), rng), - chanceIdx: 0, - ccOrder: shuffle(CC_CARDS.map((_, i) => i), rng), - ccIdx: 0, + chanceDeck: shuffle(CHANCE_CARDS.map((_, i) => i), rng), + ccDeck: shuffle(CC_CARDS.map((_, i) => i), rng), pendingCard: null, pendingBuy: null, pendingAuction: null, pendingRent: null, + debts: [], + debtResume: null, + auctionQueue: [], + freeParkingPot: 0, winner: null, + endReason: null, + standings: null, log: [], + fx: [], + fxSeq: 0, + stats: newStats(playerCount), + }; + if (R.mode === 'short') dealShortGame(s, rng); + sampleHistory(s); + return s; +} + +function newStats(n) { + const z = () => Array(n).fill(0); + return { + rentPaid: z(), rentCollected: z(), goPasses: z(), jailVisits: z(), doubles: z(), + bought: z(), built: z(), cardsDrawn: z(), landings: Array(40).fill(0), + biggest: null, // { amount, from, to, why, spaceIdx } + history: [], // per round: [netWorth per seat] }; } -// ── Helpers ─────────────────────────────────────────────────────────────────── -function log(s, msg) { s.log = [msg, ...s.log.slice(0, 49)]; } +// Official short game: deal two title deeds to each player, who pays the bank for them. +function dealShortGame(s, rng) { + const deck = shuffle(PURCHASABLE, rng); + for (let round = 0; round < 2; round++) { + for (const p of s.players) { + const idx = deck.shift(); + s.board[idx].owner = p.seat; + p.cash -= SPACES[idx].price; + s.stats.bought[p.seat]++; + log(s, `${p.name} is dealt ${SPACES[idx].name} and pays $${SPACES[idx].price}.`, p.seat); + } + } +} + +// ── Small helpers ───────────────────────────────────────────────────────────── +function log(s, msg, seat = null) { + s.log.push({ msg, seat, turn: s.turn }); + if (s.log.length > 160) s.log.splice(0, s.log.length - 160); +} + +function fx(s, ev) { + s.fxSeq = (s.fxSeq ?? 0) + 1; + s.fx.push({ id: s.fxSeq, ...ev }); + if (s.fx.length > 48) s.fx.splice(0, s.fx.length - 48); +} + +function syncCards(p) { p.getOutOfJailFree = p.jailCards.length; } + +export const isShort = (state) => state.rules?.mode === 'short'; +// Houses needed on every lot of a group before a hotel (4; 3 in the short game). +export function housesForHotel(state) { return isShort(state) ? 3 : 4; } +// Building "level" of a lot: houses, or N+1 for a hotel. +export function level(state, idx) { + const own = state.board[idx]; + if (!own) return 0; + return own.hotel ? housesForHotel(state) + 1 : own.houses; +} export function ownsGroup(state, seat, group) { const indices = GROUPS[group]; @@ -77,14 +153,36 @@ export function ownsGroup(state, seat, group) { return indices.every(i => state.board[i]?.owner === seat); } -function railroadsOwned(state, seat) { +export function groupMortgaged(state, group) { + return (GROUPS[group] ?? []).some(i => state.board[i]?.mortgaged); +} + +export function groupHasBuildings(state, group) { + return (GROUPS[group] ?? []).some(i => state.board[i]?.houses > 0 || state.board[i]?.hotel); +} + +export function ownedBy(state, seat) { + return PURCHASABLE.filter(i => state.board[i]?.owner === seat); +} + +export function railroadsOwned(state, seat) { return RAILROADS.filter(i => state.board[i]?.owner === seat).length; } -function utilitiesOwned(state, seat) { +export function utilitiesOwned(state, seat) { return UTILITIES.filter(i => state.board[i]?.owner === seat).length; } +export function activePlayers(state) { return state.players.filter(p => p.active); } + +// Who has to act right now (auction bidder, debtor, or the player whose turn it is). +export function actingSeat(state) { + if (state.phase === 'auction' && state.pendingAuction) return auctionBidder(state); + if (state.phase === 'debt' && state.debts.length) return state.debts[0].debtor; + return state.current; +} + +// ── Rent & value ────────────────────────────────────────────────────────────── export function calculateRent(state, spaceIdx, diceTotal, forceUtilityMult = null) { const sp = SPACES[spaceIdx]; const own = state.board[spaceIdx]; @@ -99,10 +197,7 @@ export function calculateRent(state, spaceIdx, diceTotal, forceUtilityMult = nul else idx = 0; return sp.rent[idx]; } - if (sp.type === 'railroad') { - const cnt = railroadsOwned(state, owner); - return 25 * Math.pow(2, cnt - 1); - } + if (sp.type === 'railroad') return RAIL_RENT[railroadsOwned(state, owner)] ?? 0; if (sp.type === 'utility') { const mult = forceUtilityMult ?? (utilitiesOwned(state, owner) === 2 ? 10 : 4); return mult * diceTotal; @@ -110,116 +205,150 @@ export function calculateRent(state, spaceIdx, diceTotal, forceUtilityMult = nul return 0; } +// Net worth = the official short-game valuation: cash + printed price of each +// deed (half if mortgaged) + buildings at what they cost (a hotel counts the +// houses turned in for it). export function netWorth(state, seat) { const p = state.players[seat]; + if (!p) return 0; let w = p.cash; + const N = housesForHotel(state); for (const idx of PURCHASABLE) { const own = state.board[idx]; if (own?.owner !== seat) continue; const sp = SPACES[idx]; - w += sp.mortgage ?? 0; // half price - if (!own.mortgaged) { - if (sp.type === 'property') { - w += own.houses * (sp.houseCost / 2); - if (own.hotel) w += sp.houseCost * 2; // hotel = 4 houses → sell back half - } + w += own.mortgaged ? half(sp.price) : sp.price; + if (sp.type === 'property') { + w += own.houses * sp.houseCost; + if (own.hotel) w += (N + 1) * sp.houseCost; } } return w; } +export const shortGameValue = netWorth; -// Auto-liquidate houses and mortgage properties to cover a debt. -// Returns new state; sets player bankrupt if still can't pay. -function liquidate(state, seat, creditorSeat) { - const s = clone(state); +// Cash a player could still raise: every building sold back at half, then +// every unmortgaged deed mortgaged. (Excludes cash on hand.) +export function liquidationValue(state, seat) { + const N = housesForHotel(state); + let v = 0; + for (const idx of PURCHASABLE) { + const own = state.board[idx]; + if (own?.owner !== seat) continue; + const sp = SPACES[idx]; + if (sp.type === 'property') { + v += own.houses * half(sp.houseCost); + if (own.hotel) v += (N + 1) * half(sp.houseCost); + } + if (!own.mortgaged) v += sp.mortgage; + } + return v; +} + +export function unmortgageCost(state, idx) { + const m = SPACES[idx].mortgage; + return isShort(state) ? m : m + Math.ceil(m / 10); +} + +// Fee a new owner pays when a mortgaged deed changes hands (10%; none in the short game). +export function mortgageInterest(state, idx) { + return isShort(state) ? 0 : Math.ceil(SPACES[idx].mortgage / 10); +} + +// ── Money ───────────────────────────────────────────────────────────────────── +// Destinations / sources: a seat number, 'bank', or 'pot' (Free Parking jackpot). +function sink(s) { return s.rules.freeParkingJackpot ? 'pot' : 'bank'; } + +function credit(s, to, amount) { + if (typeof to === 'number') s.players[to].cash += amount; + else if (to === 'pot') s.freeParkingPot += amount; +} + +function noteBiggest(s, amount, from, to, why) { + const b = s.stats.biggest; + if (!b || amount > b.amount) { + s.stats.biggest = { amount, from, to, why, spaceIdx: typeof from === 'number' ? s.players[from].position : null }; + } +} + +function transfer(s, from, to, amount, why) { + if (amount <= 0) return; + if (typeof from === 'number') s.players[from].cash -= amount; + else if (from === 'pot') s.freeParkingPot -= amount; + credit(s, to, amount); + fx(s, { type: 'pay', from, to, amount, why }); + if (why === 'rent' && typeof from === 'number' && typeof to === 'number') { + s.stats.rentPaid[from] += amount; + s.stats.rentCollected[to] += amount; + } + if (typeof from === 'number') noteBiggest(s, amount, from, to, why); +} + +// Pay if cash covers it; otherwise queue a debt. A payer who already owes +// something queues behind their earlier debt so payments stay in order. +function charge(s, payer, to, amount, why) { + if (amount <= 0) return true; + const p = s.players[payer]; + const behind = s.debts.some(d => d.debtor === payer); + if (!behind && p.cash >= amount) { transfer(s, payer, to, amount, why); return true; } + s.debts.push({ debtor: payer, creditor: to, amount, why }); + log(s, `${p.name} owes $${amount} (${why}) — must raise funds.`, payer); + fx(s, { type: 'debt', seat: payer, amount, why }); + return false; +} + +// After an action: enter 'debt' if anything is owed, else move to `next`. +function settlePhase(s, next = 'endturn') { + if (s.debts.length) { + if (!s.debtResume) s.debtResume = { phase: next }; + s.phase = 'debt'; + } else { + s.phase = next; + } + return s; +} + +// ── Movement ────────────────────────────────────────────────────────────────── +function passGo(s, seat, landed) { + const amount = landed && s.rules.doubleGo ? 400 : 200; const p = s.players[seat]; - - // Sell houses first (even selling), then hotels - let progress = true; - while (p.cash < 0 && progress) { - progress = false; - for (const idx of PURCHASABLE) { - if (p.cash >= 0) break; - const own = s.board[idx]; - if (own?.owner !== seat) continue; - const sp = SPACES[idx]; - if (own.hotel) { - own.hotel = false; - own.houses = 4; // hotels become 4 houses - p.cash += sp.houseCost; // sell hotel back at half - s.hotelSupply++; - progress = true; - } - } - for (const idx of PURCHASABLE) { - if (p.cash >= 0) break; - const own = s.board[idx]; - if (own?.owner !== seat || own.houses === 0) continue; - const sp = SPACES[idx]; - own.houses--; - p.cash += sp.houseCost / 2; - s.houseSupply++; - progress = true; - } - // Mortgage un-mortgaged properties - for (const idx of PURCHASABLE) { - if (p.cash >= 0) break; - const own = s.board[idx]; - if (own?.owner !== seat || own.mortgaged || own.houses > 0 || own.hotel) continue; - const sp = SPACES[idx]; - own.mortgaged = true; - p.cash += sp.mortgage; - progress = true; - } - } - - if (p.cash < 0) { - // Bankrupt: transfer remaining properties to creditor (or bank if creditorSeat null) - for (const idx of PURCHASABLE) { - const own = s.board[idx]; - if (own?.owner !== seat) continue; - if (creditorSeat !== null && creditorSeat !== undefined) { - own.owner = creditorSeat; - own.mortgaged = true; // creditor inherits mortgaged - own.houses = 0; own.hotel = false; - } else { - own.owner = null; - own.houses = 0; own.hotel = false; - own.mortgaged = false; - } - } - if (creditorSeat !== null && creditorSeat !== undefined) { - s.players[creditorSeat].cash += Math.max(0, p.cash + p.cash); // whatever was left (≤0, so skip) - } - p.cash = 0; - p.bankrupt = true; - p.active = false; - log(s, `${p.name} is bankrupt and out of the game.`); - } - return s; + p.cash += amount; + s.stats.goPasses[seat]++; + fx(s, { type: 'pay', from: 'bank', to: seat, amount, why: 'salary' }); + log(s, landed && amount === 400 ? `${p.name} lands on GO — double salary, $400!` : `${p.name} passes GO, collects $${amount}.`, seat); } -function payTo(state, payerSeat, receiverSeat, amount) { - const s = clone(state); - s.players[payerSeat].cash -= amount; - if (receiverSeat !== null && receiverSeat !== undefined) { - s.players[receiverSeat].cash += amount; - } - if (s.players[payerSeat].cash < 0) { - return liquidate(s, payerSeat, receiverSeat); - } - return s; +function moveForward(s, seat, steps, mode = 'walk') { + const p = s.players[seat]; + const from = p.position; + const to = (from + steps) % 40; + p.position = to; + fx(s, { type: 'move', seat, from, to, mode }); + if (to < from) passGo(s, seat, to === 0); } -export function checkGameOver(state) { - const s = clone(state); - const active = s.players.filter(p => p.active); - if (active.length <= 1) { - s.phase = 'gameover'; - s.winner = active[0]?.seat ?? null; - if (s.winner !== null) log(s, `${s.players[s.winner].name} wins!`); - } - return s; +// Card advance: move forward to `target`, collecting salary if GO is passed/reached. +function advanceTo(s, seat, target) { + const p = s.players[seat]; + const from = p.position; + if (target === from) return; + p.position = target; + fx(s, { type: 'move', seat, from, to: target, mode: 'walk' }); + if (target < from) passGo(s, seat, target === 0); +} + +function sendToJail(s, seat, why = '') { + const p = s.players[seat]; + const from = p.position; + p.position = JAIL; + p.jailed = true; + p.jailTurns = 0; + s.doublesCount = 0; + s.stats.jailVisits[seat]++; + s.stats.landings[JAIL]++; + fx(s, { type: 'move', seat, from, to: JAIL, mode: 'jail' }); + fx(s, { type: 'jail', seat }); + log(s, `${p.name} goes to Jail${why ? ` (${why})` : ''}!`, seat); } // ── Roll & Move ─────────────────────────────────────────────────────────────── @@ -228,132 +357,130 @@ export function rollDice(state, seat, d1, d2) { s.diceRoll = [d1, d2]; const p = s.players[seat]; const isDoubles = d1 === d2; + if (isDoubles) s.stats.doubles[seat]++; if (p.jailed) { if (isDoubles) { p.jailed = false; p.jailTurns = 0; - const newPos = (p.position + d1 + d2) % 40; - p.position = newPos; - // Don't get another turn from jail doubles - s.doublesCount = 0; - log(s, `${p.name} rolls doubles and escapes jail!`); - } else { - p.jailTurns++; - if (p.jailTurns >= 3) { - p.cash -= 50; - if (p.cash < 0) { const ls = liquidate(s, seat, null); Object.assign(s, ls); } - p.jailed = false; - p.jailTurns = 0; - const newPos = (p.position + d1 + d2) % 40; - s.players[seat].position = newPos; - log(s, `${p.name} pays $50 to leave jail after 3 turns.`); - } else { - log(s, `${p.name} fails to roll doubles in jail (turn ${p.jailTurns}).`); - s.phase = 'endturn'; - return s; - } + s.doublesCount = 0; // doubles out of jail don't earn another roll + log(s, `${p.name} rolls doubles and walks out of Jail!`, seat); + fx(s, { type: 'free', seat }); + moveForward(s, seat, d1 + d2); + return landOn(s, seat); } - } else { - if (isDoubles) { - s.doublesCount++; - if (s.doublesCount >= 3) { - // Three doubles: go to jail - p.position = 10; - p.jailed = true; - p.jailTurns = 0; - s.doublesCount = 0; - log(s, `${p.name} rolls 3 doubles in a row — Go to Jail!`); - s.phase = 'endturn'; - return s; - } - } else { - s.doublesCount = 0; + p.jailTurns++; + if (p.jailTurns < 3) { + log(s, `${p.name} fails to roll doubles in Jail (try ${p.jailTurns} of 3).`, seat); + s.phase = 'endturn'; + return s; } - const oldPos = p.position; - const newPos = (oldPos + d1 + d2) % 40; - p.position = newPos; - if (newPos < oldPos || (oldPos === 0 && newPos > 0)) { - p.cash += 200; - log(s, `${p.name} passes GO, collects $200.`); + // Third failed try: pay the $50 fine, then move the number thrown. + p.jailed = false; + p.jailTurns = 0; + s.doublesCount = 0; + log(s, `${p.name} must pay $50 to leave Jail after three tries.`, seat); + if (!charge(s, seat, sink(s), 50, 'jail fine')) { + s.debtResume = { phase: 'move', steps: d1 + d2 }; + s.phase = 'debt'; + return s; } + fx(s, { type: 'free', seat }); + moveForward(s, seat, d1 + d2); + return landOn(s, seat); } - return resolveSpace(s, seat); + if (isDoubles) { + s.doublesCount++; + if (s.doublesCount >= 3) { + sendToJail(s, seat, 'three doubles — speeding'); + s.phase = 'endturn'; + return s; + } + } else { + s.doublesCount = 0; + } + moveForward(s, seat, d1 + d2); + return landOn(s, seat); } // ── Space Resolution ────────────────────────────────────────────────────────── export function resolveSpace(state, seat) { - const s = clone(state); + return landOn(clone(state), seat); +} + +function drawCard(s, deckName) { + const deck = deckName === 'chance' ? s.chanceDeck : s.ccDeck; + const cardIdx = deck.shift(); + const card = (deckName === 'chance' ? CHANCE_CARDS : CC_CARDS)[cardIdx]; + // Ordinary cards go straight to the bottom; a Get Out of Jail Free card is + // kept by the player and only returns when used (or on bankruptcy to the bank). + if (card.effect !== 'goojf') deck.push(cardIdx); + return { cardIdx, card }; +} + +function landOn(s, seat) { const p = s.players[seat]; const spIdx = p.position; const sp = SPACES[spIdx]; + s.stats.landings[spIdx]++; switch (sp.type) { - case 'go': - s.phase = 'endturn'; - break; - case 'property': case 'railroad': case 'utility': { const own = s.board[spIdx]; - if (!own || own.owner === null) { + if (own.owner === null) { s.pendingBuy = { spaceIdx: spIdx }; s.phase = 'buy'; } else if (own.owner === seat) { - log(s, `${p.name} owns this property.`); s.phase = 'endturn'; } else if (own.mortgaged) { - log(s, `${SPACES[spIdx].name} is mortgaged — no rent.`); + log(s, `${sp.name} is mortgaged — no rent.`, seat); s.phase = 'endturn'; } else { - const dice = s.diceRoll[0] + s.diceRoll[1]; + const dice = (s.diceRoll?.[0] ?? 0) + (s.diceRoll?.[1] ?? 0); const rent = calculateRent(s, spIdx, dice); - s.pendingRent = { payer: seat, receiver: own.owner, amount: rent }; - log(s, `${p.name} pays $${rent} rent to ${s.players[own.owner].name}.`); + s.pendingRent = { payer: seat, receiver: own.owner, amount: rent, spaceIdx: spIdx }; + log(s, `${p.name} owes $${rent} rent to ${s.players[own.owner].name} for ${sp.name}.`, seat); s.phase = 'rent'; } break; } case 'tax': { - const result = payTo(s, seat, null, sp.amount); - Object.assign(s, result); - log(s, `${p.name} pays ${sp.name} ($${sp.amount}).`); - s.phase = 'endturn'; - break; - } - - case 'chance': { - const cardIdx = s.chanceOrder[s.chanceIdx % s.chanceOrder.length]; - s.chanceIdx++; - const card = CHANCE_CARDS[cardIdx]; - s.pendingCard = { cardType: 'chance', cardIdx, text: card.text, effect: card }; - s.phase = 'card'; + log(s, `${p.name} pays ${sp.name} ($${sp.amount}).`, seat); + charge(s, seat, sink(s), sp.amount, 'tax'); + settlePhase(s); break; } + case 'chance': case 'community_chest': { - const cardIdx = s.ccOrder[s.ccIdx % s.ccOrder.length]; - s.ccIdx++; - const card = CC_CARDS[cardIdx]; - s.pendingCard = { cardType: 'community_chest', cardIdx, text: card.text, effect: card }; + const { cardIdx, card } = drawCard(s, sp.type); + s.stats.cardsDrawn[seat]++; + s.pendingCard = { cardType: sp.type, cardIdx, text: card.text, effect: card }; s.phase = 'card'; break; } case 'gotojail': - p.position = 10; - p.jailed = true; - p.jailTurns = 0; - s.doublesCount = 0; - log(s, `${p.name} is sent to Jail!`); + sendToJail(s, seat); s.phase = 'endturn'; break; + case 'freeparking': { + const pot = s.freeParkingPot; + if (s.rules.freeParkingJackpot && pot > 0) { + transfer(s, 'pot', seat, pot, 'jackpot'); + log(s, `${p.name} hits the Free Parking jackpot — $${pot}!`, seat); + } + s.phase = 'endturn'; + break; + } + + case 'go': case 'jail': - case 'freeparking': default: s.phase = 'endturn'; break; @@ -362,105 +489,87 @@ export function resolveSpace(state, seat) { } // ── Card Effects ────────────────────────────────────────────────────────────── -export function applyCardEffect(state, seat) { +// opts.dice: [d1,d2] for the "nearest utility — throw dice, pay 10×" card +// (the scene animates a fresh throw); defaults to a random throw. +export function cardNeedsDice(state) { + const pc = state.pendingCard; + if (pc?.effect?.effect !== 'nearest_utility') return false; + const p = state.players[state.current]; + const own = state.board[nearestUtility(p.position)]; + return own.owner !== null && own.owner !== state.current && !own.mortgaged; +} + +export function applyCardEffect(state, seat, opts = {}) { let s = clone(state); const p = s.players[seat]; - const card = s.pendingCard?.effect; - if (!card) { s.pendingCard = null; s.phase = 'endturn'; return s; } + const pc = s.pendingCard; + const card = pc?.effect; + s.pendingCard = null; + if (!card) { s.phase = 'endturn'; return s; } switch (card.effect) { - case 'advance_to': { - const target = card.target; - const old = p.position; - p.position = target; - if (target <= old && target !== old) { - p.cash += 200; - log(s, `${p.name} passes GO, collects $200.`); - } - s.pendingCard = null; - s = resolveSpace(s, seat); - break; - } - case 'nearest_railroad': { - const target = nearestRailroad(p.position); - const old = p.position; - p.position = target; - if (target <= old) { p.cash += 200; log(s, `${p.name} passes GO, collects $200.`); } - s.pendingCard = null; - const own = s.board[target]; - if (!own || own.owner === null) { - s.pendingBuy = { spaceIdx: target }; - s.phase = 'buy'; - } else if (own.owner !== seat && !own.mortgaged) { - const cnt = railroadsOwned(s, own.owner); - const rent = 25 * Math.pow(2, cnt - 1) * (card.doubleRent ? 2 : 1); - const result = payTo(s, seat, own.owner, rent); - Object.assign(s, result); - log(s, `${p.name} pays $${rent} (double) railroad rent.`); - s.phase = 'endturn'; - } else { - s.phase = 'endturn'; - } - break; - } + case 'advance_to': + advanceTo(s, seat, card.target); + return landOn(s, seat); + + case 'nearest_railroad': case 'nearest_utility': { - const target = nearestUtility(p.position); - const old = p.position; - p.position = target; - if (target <= old) { p.cash += 200; log(s, `${p.name} passes GO, collects $200.`); } - s.pendingCard = null; + const isRail = card.effect === 'nearest_railroad'; + const target = isRail ? nearestRailroad(p.position) : nearestUtility(p.position); + advanceTo(s, seat, target); + s.stats.landings[target]++; const own = s.board[target]; - if (!own || own.owner === null) { + if (own.owner === null) { s.pendingBuy = { spaceIdx: target }; s.phase = 'buy'; - } else if (own.owner !== seat && !own.mortgaged) { - const dice = s.diceRoll[0] + s.diceRoll[1]; - const rent = 10 * dice; - const result = payTo(s, seat, own.owner, rent); - Object.assign(s, result); - log(s, `${p.name} pays $${rent} (10× dice) utility rent.`); + } else if (own.owner === seat || own.mortgaged) { s.phase = 'endturn'; } else { - s.phase = 'endturn'; + let rent; + if (isRail) { + rent = (RAIL_RENT[railroadsOwned(s, own.owner)] ?? 0) * 2; + } else { + const dice = opts.dice ?? [1 + Math.floor(Math.random() * 6), 1 + Math.floor(Math.random() * 6)]; + rent = 10 * (dice[0] + dice[1]); + s.cardDice = dice; + } + s.pendingRent = { payer: seat, receiver: own.owner, amount: rent, spaceIdx: target, card: true }; + log(s, `${p.name} owes ${s.players[own.owner].name} $${rent} (${isRail ? 'double railroad rent' : '10× the dice'}).`, seat); + s.phase = 'rent'; } - break; + return s; } + case 'collect': - p.cash += card.amount; - log(s, `${p.name} collects $${card.amount}.`); - s.pendingCard = null; + transfer(s, 'bank', seat, card.amount, 'card'); + log(s, `${p.name} collects $${card.amount}.`, seat); s.phase = 'endturn'; - break; - case 'pay': { - const result = payTo(s, seat, null, card.amount); - Object.assign(s, result); - log(s, `${p.name} pays $${card.amount}.`); - s.pendingCard = null; - s.phase = 'endturn'; - break; - } + return s; + + case 'pay': + log(s, `${p.name} pays $${card.amount}.`, seat); + charge(s, seat, sink(s), card.amount, 'card'); + return settlePhase(s); + case 'goojf': - p.getOutOfJailFree++; - log(s, `${p.name} receives a Get Out of Jail Free card.`); - s.pendingCard = null; + p.jailCards.push({ deck: pc.cardType, idx: pc.cardIdx }); + syncCards(p); + log(s, `${p.name} keeps a Get Out of Jail Free card.`, seat); s.phase = 'endturn'; - break; + return s; + case 'go_to_jail': - p.position = 10; - p.jailed = true; - p.jailTurns = 0; - s.doublesCount = 0; - log(s, `${p.name} goes to Jail!`); - s.pendingCard = null; + sendToJail(s, seat); s.phase = 'endturn'; - break; + return s; + case 'back3': { - p.position = (p.position - 3 + 40) % 40; - s.pendingCard = null; - s = resolveSpace(s, seat); - // Don't award Go on back3 - break; + const from = p.position; + p.position = (from + 37) % 40; + fx(s, { type: 'move', seat, from, to: p.position, mode: 'back' }); + return landOn(s, seat); } + case 'repairs': { let total = 0; for (const idx of PURCHASABLE) { @@ -470,124 +579,146 @@ export function applyCardEffect(state, seat) { if (own.hotel) total += card.hotel; } if (total > 0) { - const result = payTo(s, seat, null, total); - Object.assign(s, result); - log(s, `${p.name} pays $${total} for repairs.`); + log(s, `${p.name} pays $${total} for repairs.`, seat); + charge(s, seat, sink(s), total, 'repairs'); + } else { + log(s, `${p.name} has no buildings to repair.`, seat); } - s.pendingCard = null; - s.phase = 'endturn'; - break; + return settlePhase(s); } - case 'pay_each': { - let paid = 0; + + case 'pay_each': + log(s, `${p.name} pays $${card.amount} to each player.`, seat); for (const other of s.players) { if (!other.active || other.seat === seat) continue; - const amount = Math.min(card.amount, s.players[seat].cash); - s.players[seat].cash -= amount; - other.cash += amount; - paid += amount; + charge(s, seat, other.seat, card.amount, 'card'); } - log(s, `${p.name} pays $${card.amount} to each player.`); - s.pendingCard = null; - s.phase = 'endturn'; - break; - } - case 'collect_each': { + return settlePhase(s); + + case 'collect_each': + log(s, `${p.name} collects $${card.amount} from every player.`, seat); for (const other of s.players) { if (!other.active || other.seat === seat) continue; - const amount = Math.min(card.amount, other.cash); - other.cash -= amount; - s.players[seat].cash += amount; + charge(s, other.seat, seat, card.amount, 'card'); } - log(s, `${p.name} collects $${card.amount} from each player.`); - s.pendingCard = null; - s.phase = 'endturn'; - break; - } + return settlePhase(s); + default: - s.pendingCard = null; s.phase = 'endturn'; + return s; } - return s; } // ── Property Purchase ───────────────────────────────────────────────────────── export function buyProperty(state, seat) { - const s = clone(state); - const { spaceIdx } = s.pendingBuy; + const { spaceIdx } = state.pendingBuy ?? {}; + if (spaceIdx === undefined) return state; const sp = SPACES[spaceIdx]; - s.players[seat].cash -= sp.price; + if (state.players[seat].cash < sp.price) return state; + const s = clone(state); + transfer(s, seat, 'bank', sp.price, 'purchase'); s.board[spaceIdx].owner = seat; - log(s, `${s.players[seat].name} buys ${sp.name} for $${sp.price}.`); + s.stats.bought[seat]++; + fx(s, { type: 'deed', seat, idx: spaceIdx }); + log(s, `${s.players[seat].name} buys ${sp.name} for $${sp.price}.`, seat); s.pendingBuy = null; - s.phase = s.doublesCount > 0 ? 'preroll' : 'endturn'; - return checkGameOver(s); + s.phase = 'endturn'; + return s; } export function declineProperty(state, seat) { - return startAuction(state, state.pendingBuy.spaceIdx); + const s = clone(state); + const idx = s.pendingBuy?.spaceIdx; + s.pendingBuy = null; + if (idx === undefined) { s.phase = 'endturn'; return s; } + if (s.rules.auctions) return startAuction(s, idx, 'declined'); + log(s, `${s.players[seat].name} passes on ${SPACES[idx].name}; it stays with the bank.`, seat); + s.phase = 'endturn'; + return s; } // ── Auction ─────────────────────────────────────────────────────────────────── -function startAuction(state, spaceIdx) { - const s = clone(state); - const bidOrder = []; +// Bidding goes round the table from the current player. A player may bid any +// amount above the high bid (up to their cash) or drop out; the auction ends +// when everyone but the high bidder has dropped out. +function startAuction(s, spaceIdx, reason) { + const bidders = []; for (let i = 0; i < s.playerCount; i++) { const seat = (s.current + i) % s.playerCount; - if (s.players[seat].active) bidOrder.push(seat); + if (s.players[seat].active) bidders.push(seat); } s.pendingBuy = null; - s.pendingAuction = { spaceIdx, bidOrder, currentBidderIdx: 0, bids: {}, highBid: 0, highBidder: null }; + s.pendingAuction = { spaceIdx, bidders, turn: 0, highBid: 0, highBidder: null, reason, history: [] }; s.phase = 'auction'; - return s; + fx(s, { type: 'auction', idx: spaceIdx }); + log(s, `${SPACES[spaceIdx].name} goes to auction.`); + return checkAuction(s); +} + +export function auctionBidder(state) { + const a = state.pendingAuction; + return a ? (a.bidders[a.turn] ?? null) : null; +} + +function nextTurn(a, from) { + const n = a.bidders.length; + for (let k = 0; k < n; k++) { + const i = (from + k) % n; + if (a.bidders[i] !== a.highBidder) return i; + } + return 0; } export function placeBid(state, seat, amount) { + const a0 = state.pendingAuction; + if (!a0 || a0.bidders[a0.turn] !== seat) return state; const s = clone(state); - const auc = s.pendingAuction; - if (amount > s.players[seat].cash) amount = s.players[seat].cash; - if (amount <= auc.highBid) return passAuction(s, seat); - auc.bids[seat] = amount; - auc.highBid = amount; - auc.highBidder = seat; - auc.currentBidderIdx = (auc.currentBidderIdx + 1) % auc.bidOrder.length; - // Skip to next active bidder who hasn't committed to their max - return advanceAuction(s); + const a = s.pendingAuction; + amount = Math.floor(Math.min(amount, s.players[seat].cash)); + if (amount <= a.highBid) return passAuction(s, seat); + a.highBid = amount; + a.highBidder = seat; + a.history.push({ seat, amount }); + fx(s, { type: 'bid', seat, amount }); + a.turn = nextTurn(a, a.turn + 1); + return checkAuction(s); } export function passAuction(state, seat) { + const a0 = state.pendingAuction; + if (!a0) return state; const s = clone(state); - const auc = s.pendingAuction; - auc.bidOrder = auc.bidOrder.filter(bs => bs !== seat); - if (auc.currentBidderIdx >= auc.bidOrder.length) auc.currentBidderIdx = 0; - return advanceAuction(s); + const a = s.pendingAuction; + const i = a.bidders.indexOf(seat); + if (i < 0) return s; + a.bidders.splice(i, 1); + a.history.push({ seat, pass: true }); + fx(s, { type: 'bidpass', seat }); + if (a.bidders.length) a.turn = nextTurn(a, i % a.bidders.length); + return checkAuction(s); } -function advanceAuction(state) { - const s = clone(state); - const auc = s.pendingAuction; - if (auc.bidOrder.length === 0 || (auc.bidOrder.length === 1 && auc.highBidder === auc.bidOrder[0])) { - return resolveAuction(s); - } - if (auc.bidOrder.length === 1 && auc.highBidder === null) { - return resolveAuction(s); // no one bid - } +function checkAuction(s) { + const a = s.pendingAuction; + const live = a.bidders.filter(b => b !== a.highBidder); + if (live.length === 0) return resolveAuction(s); return s; } -function resolveAuction(state) { - const s = clone(state); - const auc = s.pendingAuction; - if (auc.highBidder !== null && auc.highBid > 0) { - s.players[auc.highBidder].cash -= auc.highBid; - s.board[auc.spaceIdx].owner = auc.highBidder; - log(s, `${s.players[auc.highBidder].name} wins auction for ${SPACES[auc.spaceIdx].name} at $${auc.highBid}.`); +function resolveAuction(s) { + const a = s.pendingAuction; + if (a.highBidder !== null && a.highBid > 0) { + transfer(s, a.highBidder, 'bank', a.highBid, 'auction'); + s.board[a.spaceIdx].owner = a.highBidder; + s.stats.bought[a.highBidder]++; + fx(s, { type: 'deed', seat: a.highBidder, idx: a.spaceIdx, auction: true }); + log(s, `${s.players[a.highBidder].name} wins ${SPACES[a.spaceIdx].name} at auction for $${a.highBid}.`, a.highBidder); } else { - log(s, `No one bid on ${SPACES[auc.spaceIdx].name} — it stays in the bank.`); + log(s, `No bids on ${SPACES[a.spaceIdx].name} — it stays with the bank.`); } s.pendingAuction = null; - s.phase = s.doublesCount > 0 ? 'preroll' : 'endturn'; - return checkGameOver(s); + if (s.auctionQueue.length) return startAuction(s, s.auctionQueue.shift(), 'bankrupt'); + return applyResume(s); } // ── Building ────────────────────────────────────────────────────────────────── @@ -596,21 +727,12 @@ export function canBuildHouse(state, seat, spaceIdx) { const own = state.board[spaceIdx]; if (!own || own.owner !== seat || own.mortgaged || own.hotel) return false; if (sp.type !== 'property') return false; - if (!ownsGroup(state, seat, sp.group)) return false; + if (!ownsGroup(state, seat, sp.group) || groupMortgaged(state, sp.group)) return false; if (state.houseSupply <= 0) return false; - // Even building: can't have more than 1 house more than any other in group - const groupMin = Math.min(...GROUPS[sp.group].map(i => state.board[i]?.houses ?? 0)); - return own.houses <= groupMin && own.houses < 4; -} - -export function buildHouse(state, seat, spaceIdx) { - const s = clone(state); - const sp = SPACES[spaceIdx]; - s.players[seat].cash -= sp.houseCost; - s.board[spaceIdx].houses++; - s.houseSupply--; - log(s, `${s.players[seat].name} builds a house on ${sp.name}.`); - return s; + if (state.players[seat].cash < sp.houseCost) return false; + if (own.houses >= housesForHotel(state)) return false; + const groupMin = Math.min(...GROUPS[sp.group].map(i => level(state, i))); + return own.houses <= groupMin; } export function canBuildHotel(state, seat, spaceIdx) { @@ -618,84 +740,278 @@ export function canBuildHotel(state, seat, spaceIdx) { const own = state.board[spaceIdx]; if (!own || own.owner !== seat || own.mortgaged || own.hotel) return false; if (sp.type !== 'property') return false; - if (!ownsGroup(state, seat, sp.group)) return false; + if (!ownsGroup(state, seat, sp.group) || groupMortgaged(state, sp.group)) return false; if (state.hotelSupply <= 0) return false; - // All properties in group must have 4 houses - return GROUPS[sp.group].every(i => state.board[i]?.houses === 4 || state.board[i]?.hotel); + if (state.players[seat].cash < sp.houseCost) return false; + const N = housesForHotel(state); + if (own.houses !== N) return false; + return GROUPS[sp.group].every(i => level(state, i) >= N); +} + +export function buildHouse(state, seat, spaceIdx) { + if (!canBuildHouse(state, seat, spaceIdx)) return state; + const s = clone(state); + const sp = SPACES[spaceIdx]; + transfer(s, seat, 'bank', sp.houseCost, 'building'); + s.board[spaceIdx].houses++; + s.houseSupply--; + s.stats.built[seat]++; + fx(s, { type: 'build', seat, idx: spaceIdx, kind: 'house' }); + log(s, `${s.players[seat].name} builds a house on ${sp.name}.`, seat); + return s; } export function buildHotel(state, seat, spaceIdx) { + if (!canBuildHotel(state, seat, spaceIdx)) return state; const s = clone(state); const sp = SPACES[spaceIdx]; - s.players[seat].cash -= sp.houseCost; + const N = housesForHotel(state); + transfer(s, seat, 'bank', sp.houseCost, 'building'); s.board[spaceIdx].houses = 0; s.board[spaceIdx].hotel = true; - s.houseSupply += 4; // return the 4 houses + s.houseSupply += N; // the houses go back to the bank s.hotelSupply--; - log(s, `${s.players[seat].name} builds a hotel on ${sp.name}.`); + s.stats.built[seat]++; + fx(s, { type: 'build', seat, idx: spaceIdx, kind: 'hotel' }); + log(s, `${s.players[seat].name} builds a hotel on ${sp.name}.`, seat); return s; } +// Even selling: a house may only come off the most-built lot(s) of the group. +export function canSellHouse(state, seat, spaceIdx) { + const sp = SPACES[spaceIdx]; + const own = state.board[spaceIdx]; + if (!own || own.owner !== seat || own.hotel || own.houses <= 0) return false; + const groupMax = Math.max(...GROUPS[sp.group].map(i => level(state, i))); + return own.houses >= groupMax; +} + +export function canSellHotel(state, seat, spaceIdx) { + const own = state.board[spaceIdx]; + return !!own && own.owner === seat && own.hotel; +} + export function sellHouse(state, seat, spaceIdx) { + if (!canSellHouse(state, seat, spaceIdx)) return state; const s = clone(state); const sp = SPACES[spaceIdx]; s.board[spaceIdx].houses--; - s.players[seat].cash += Math.floor(sp.houseCost / 2); s.houseSupply++; + transfer(s, 'bank', seat, half(sp.houseCost), 'sale'); + fx(s, { type: 'sell', seat, idx: spaceIdx, kind: 'house' }); + log(s, `${s.players[seat].name} sells a house on ${sp.name}.`, seat); return s; } +// A hotel is sold back for half its price and breaks down into houses again — +// if the bank has them. In a housing shortage the lot is sold down to bare land. export function sellHotel(state, seat, spaceIdx) { - const s = clone(state); - const sp = SPACES[spaceIdx]; - s.board[spaceIdx].hotel = false; - s.board[spaceIdx].houses = 0; - s.players[seat].cash += Math.floor(sp.houseCost / 2); - s.hotelSupply++; - s.houseSupply -= 4; - return s; -} - -export function mortgageProperty(state, seat, spaceIdx) { + if (!canSellHotel(state, seat, spaceIdx)) return state; const s = clone(state); const sp = SPACES[spaceIdx]; const own = s.board[spaceIdx]; - if (own.houses > 0 || own.hotel) return s; // must sell buildings first - own.mortgaged = true; - s.players[seat].cash += sp.mortgage; - log(s, `${s.players[seat].name} mortgages ${sp.name} for $${sp.mortgage}.`); + const N = housesForHotel(s); + own.hotel = false; + s.hotelSupply++; + if (s.houseSupply >= N) { + own.houses = N; + s.houseSupply -= N; + transfer(s, 'bank', seat, half(sp.houseCost), 'sale'); + log(s, `${s.players[seat].name} sells the hotel on ${sp.name} (back to ${N} houses).`, seat); + } else { + own.houses = 0; + transfer(s, 'bank', seat, half(sp.houseCost) * (N + 1), 'sale'); + log(s, `${s.players[seat].name} sells the hotel on ${sp.name} — no houses left in the bank, so the lot is cleared.`, seat); + } + fx(s, { type: 'sell', seat, idx: spaceIdx, kind: 'hotel' }); + return s; +} + +// Mortgage only with no buildings anywhere in the group. +export function canMortgage(state, seat, spaceIdx) { + const own = state.board[spaceIdx]; + if (!own || own.owner !== seat || own.mortgaged) return false; + const sp = SPACES[spaceIdx]; + if (sp.type === 'property' && groupHasBuildings(state, sp.group)) return false; + return true; +} + +export function canUnmortgage(state, seat, spaceIdx) { + const own = state.board[spaceIdx]; + if (!own || own.owner !== seat || !own.mortgaged) return false; + return state.players[seat].cash >= unmortgageCost(state, spaceIdx); +} + +export function mortgageProperty(state, seat, spaceIdx) { + if (!canMortgage(state, seat, spaceIdx)) return state; + const s = clone(state); + const sp = SPACES[spaceIdx]; + s.board[spaceIdx].mortgaged = true; + transfer(s, 'bank', seat, sp.mortgage, 'mortgage'); + fx(s, { type: 'mortgage', seat, idx: spaceIdx }); + log(s, `${s.players[seat].name} mortgages ${sp.name} for $${sp.mortgage}.`, seat); return s; } export function unmortgageProperty(state, seat, spaceIdx) { + if (!canUnmortgage(state, seat, spaceIdx)) return state; const s = clone(state); const sp = SPACES[spaceIdx]; - const cost = Math.ceil(sp.mortgage * 1.1); - if (s.players[seat].cash < cost) return s; + const cost = unmortgageCost(s, spaceIdx); s.board[spaceIdx].mortgaged = false; - s.players[seat].cash -= cost; - log(s, `${s.players[seat].name} unmortgages ${sp.name} for $${cost}.`); + transfer(s, seat, 'bank', cost, 'unmortgage'); + fx(s, { type: 'unmortgage', seat, idx: spaceIdx }); + log(s, `${s.players[seat].name} lifts the mortgage on ${sp.name} for $${cost}.`, seat); return s; } -// ── Trading ───────────────────────────────────────────────────────────────────── -// A property may be traded only if it (and the rest of its color group) carries no -// buildings — otherwise transferring it would strand houses / break even-building. -// Railroads & utilities never have buildings; mortgaged properties may be traded. +// Even-build plan: how many houses/hotels `budget` buys across one group, +// following the even-building rule. Returns [{ idx, kind }] in build order. +export function planEvenBuild(state, seat, group, budget) { + let s = state; + const steps = []; + for (let guard = 0; guard < 40; guard++) { + let best = null; + for (const idx of GROUPS[group] ?? []) { + const sp = SPACES[idx]; + if (s.players[seat].cash - sp.houseCost < state.players[seat].cash - budget) continue; + if (canBuildHouse(s, seat, idx)) { best = { idx, kind: 'house' }; break; } + if (canBuildHotel(s, seat, idx)) { best = { idx, kind: 'hotel' }; break; } + } + if (!best) break; + steps.push(best); + s = best.kind === 'house' ? buildHouse(s, seat, best.idx) : buildHotel(s, seat, best.idx); + } + return steps; +} + +// ── Debts & bankruptcy ──────────────────────────────────────────────────────── +export function currentDebt(state) { return state.debts?.[0] ?? null; } + +export function canSettleDebt(state) { + const d = currentDebt(state); + return !!d && state.players[d.debtor].cash >= d.amount; +} + +// Bankruptcy is only allowed once selling everything still couldn't pay. +export function mustGoBankrupt(state) { + const d = currentDebt(state); + if (!d) return false; + return state.players[d.debtor].cash + liquidationValue(state, d.debtor) < d.amount; +} + +export function settleDebt(state) { + if (!canSettleDebt(state)) return state; + const s = clone(state); + const d = s.debts.shift(); + transfer(s, d.debtor, d.creditor, d.amount, d.why); + log(s, `${s.players[d.debtor].name} settles $${d.amount} (${d.why}).`, d.debtor); + if (s.debts.length) { s.phase = 'debt'; return s; } + return afterDebts(s); +} + +export function declareBankruptcy(state) { + if (!mustGoBankrupt(state)) return state; + const s = clone(state); + const d = s.debts[0]; + const seat = d.debtor; + const creditor = typeof d.creditor === 'number' && s.players[d.creditor].active ? d.creditor : 'bank'; + goBankrupt(s, seat, creditor); + s.debts = s.debts + .filter(x => x.debtor !== seat) + .map(x => (x.creditor === seat ? { ...x, creditor: 'bank' } : x)); + if (checkGameOverInPlace(s)) return s; + if (s.debts.length) { s.phase = 'debt'; return s; } + return afterDebts(s); +} + +function goBankrupt(s, seat, creditor) { + const p = s.players[seat]; + const N = housesForHotel(s); + // Buildings go back to the bank at half price. + let sale = 0; + for (const idx of PURCHASABLE) { + const own = s.board[idx]; + if (own?.owner !== seat) continue; + const sp = SPACES[idx]; + if (own.hotel) { sale += (N + 1) * half(sp.houseCost); s.hotelSupply++; own.hotel = false; } + if (own.houses) { sale += own.houses * half(sp.houseCost); s.houseSupply += own.houses; own.houses = 0; } + } + if (sale) { transfer(s, 'bank', seat, sale, 'sale'); fx(s, { type: 'clear', seat }); } + const deeds = ownedBy(s, seat); + if (typeof creditor === 'number') { + const c = s.players[creditor]; + if (p.cash > 0) transfer(s, seat, creditor, p.cash, 'bankruptcy'); + for (const idx of deeds) s.board[idx].owner = creditor; + if (deeds.length) fx(s, { type: 'deeds', from: seat, to: creditor, idxs: deeds }); + c.jailCards.push(...p.jailCards); + p.jailCards = []; + syncCards(c); + log(s, `${p.name} is bankrupt — everything goes to ${c.name}.`, seat); + const fee = deeds.filter(i => s.board[i].mortgaged).reduce((a, i) => a + mortgageInterest(s, i), 0); + if (fee > 0) { + log(s, `${c.name} owes $${fee} interest on the mortgaged deeds received.`, creditor); + charge(s, creditor, 'bank', fee, 'mortgage interest'); + } + } else { + if (p.cash > 0) transfer(s, seat, 'bank', p.cash, 'bankruptcy'); + for (const idx of deeds) { + const own = s.board[idx]; + own.owner = null; + own.mortgaged = false; + if (s.rules.auctions) s.auctionQueue.push(idx); + } + for (const jc of p.jailCards) (jc.deck === 'chance' ? s.chanceDeck : s.ccDeck).push(jc.idx); + p.jailCards = []; + log(s, `${p.name} is bankrupt to the bank${deeds.length && s.rules.auctions ? ' — the deeds go up for auction' : ''}.`, seat); + } + syncCards(p); + p.cash = 0; + p.bankrupt = true; + p.active = false; + p.jailed = false; + p.bankruptTurn = s.turn; + fx(s, { type: 'bankrupt', seat, to: creditor }); +} + +function afterDebts(s) { + if (s.auctionQueue.length && !s.pendingAuction) return startAuction(s, s.auctionQueue.shift(), 'bankrupt'); + return applyResume(s); +} + +function applyResume(s) { + const r = s.debtResume ?? { phase: 'endturn' }; + s.debtResume = null; + if (s.phase === 'gameover') return s; + if (!s.players[s.current].active) return passTurn(s); + if (r.phase === 'move') { + fx(s, { type: 'free', seat: s.current }); + moveForward(s, s.current, r.steps); + return landOn(s, s.current); + } + s.phase = r.phase; + return s; +} + +// ── Trading ─────────────────────────────────────────────────────────────────── +// A property may be traded only if it (and the rest of its colour group) carries +// no buildings. Railroads & utilities never have buildings; mortgaged deeds may +// be traded, and the receiver pays the bank 10% interest on them. export function isTradeable(state, spaceIdx) { const own = state.board[spaceIdx]; if (!own || own.owner === null || own.owner === undefined) return false; if (own.houses > 0 || own.hotel) return false; const sp = SPACES[spaceIdx]; - if (sp.type === 'property') { - for (const i of GROUPS[sp.group]) { - const o = state.board[i]; - if (o && (o.houses > 0 || o.hotel)) return false; - } - } + if (sp.type === 'property' && groupHasBuildings(state, sp.group)) return false; return true; } +// Interest each side owes the bank for mortgaged deeds it receives. +export function tradeInterest(state, offer) { + const fee = (idxs) => (idxs ?? []).filter(i => state.board[i]?.mortgaged).reduce((a, i) => a + mortgageInterest(state, i), 0); + return { from: fee(offer.getProps), to: fee(offer.giveProps) }; +} + // Pure validator. Returns { ok:true } or { ok:false, reason }. Never mutates. // offer = { fromSeat, toSeat, giveProps:[idx], getProps:[idx], giveCash, getCash } export function validateTrade(state, offer) { @@ -719,20 +1035,22 @@ export function validateTrade(state, offer) { } for (const idx of giveProps) { if (state.board[idx]?.owner !== fromSeat) return { ok: false, reason: 'You do not own a property you are offering.' }; - if (!isTradeable(state, idx)) return { ok: false, reason: `${SPACES[idx].name} has buildings and cannot be traded.` }; + if (!isTradeable(state, idx)) return { ok: false, reason: `${SPACES[idx].name} has buildings in its group and cannot be traded.` }; } for (const idx of getProps) { if (state.board[idx]?.owner !== toSeat) return { ok: false, reason: 'They do not own a property you requested.' }; - if (!isTradeable(state, idx)) return { ok: false, reason: `${SPACES[idx].name} has buildings and cannot be traded.` }; + if (!isTradeable(state, idx)) return { ok: false, reason: `${SPACES[idx].name} has buildings in its group and cannot be traded.` }; } if (giveCash > from.cash) return { ok: false, reason: 'You cannot afford that cash offer.' }; if (getCash > to.cash) return { ok: false, reason: 'They cannot afford that cash request.' }; + const fee = tradeInterest(state, offer); + if (from.cash - giveCash + getCash < fee.from) return { ok: false, reason: `You couldn't cover the $${fee.from} mortgage interest.` }; + if (to.cash - getCash + giveCash < fee.to) return { ok: false, reason: `They couldn't cover the $${fee.to} mortgage interest.` }; return { ok: true }; } // Apply a trade. No-op (returns original state) when the offer is invalid. -// Cash flows both ways; ownership transfers; mortgaged flag is preserved (no interest). -// Does NOT touch s.phase — trading happens within the human's endturn. +// Does NOT touch s.phase — trading happens within a turn. export function applyTrade(state, offer) { const v = validateTrade(state, offer); if (!v.ok) return state; @@ -742,70 +1060,171 @@ export function applyTrade(state, offer) { const getProps = offer.getProps ?? []; const giveCash = offer.giveCash ?? 0; const getCash = offer.getCash ?? 0; + const fee = tradeInterest(s, offer); - s.players[fromSeat].cash -= giveCash; - s.players[toSeat].cash += giveCash; - s.players[toSeat].cash -= getCash; - s.players[fromSeat].cash += getCash; - + if (giveCash) transfer(s, fromSeat, toSeat, giveCash, 'trade'); + if (getCash) transfer(s, toSeat, fromSeat, getCash, 'trade'); for (const idx of giveProps) s.board[idx].owner = toSeat; for (const idx of getProps) s.board[idx].owner = fromSeat; + if (giveProps.length) fx(s, { type: 'deeds', from: fromSeat, to: toSeat, idxs: [...giveProps] }); + if (getProps.length) fx(s, { type: 'deeds', from: toSeat, to: fromSeat, idxs: [...getProps] }); + if (fee.from) transfer(s, fromSeat, 'bank', fee.from, 'mortgage interest'); + if (fee.to) transfer(s, toSeat, 'bank', fee.to, 'mortgage interest'); const giveNames = giveProps.map(i => SPACES[i].name).join(', ') || '—'; const getNames = getProps.map(i => SPACES[i].name).join(', ') || '—'; log(s, `${s.players[fromSeat].name} traded ${giveNames}${giveCash ? ` + $${giveCash}` : ''} ` + - `to ${s.players[toSeat].name} for ${getNames}${getCash ? ` + $${getCash}` : ''}.`); + `to ${s.players[toSeat].name} for ${getNames}${getCash ? ` + $${getCash}` : ''}.`, fromSeat); return s; } // ── Jail ────────────────────────────────────────────────────────────────────── export function payJailFine(state, seat) { + const p0 = state.players[seat]; + if (!p0.jailed || p0.cash < 50) return state; const s = clone(state); - s.players[seat].cash -= 50; + transfer(s, seat, sink(s), 50, 'jail fine'); s.players[seat].jailed = false; s.players[seat].jailTurns = 0; - log(s, `${s.players[seat].name} pays $50 to get out of jail.`); + fx(s, { type: 'free', seat }); + log(s, `${s.players[seat].name} pays $50 to get out of Jail.`, seat); s.phase = 'preroll'; return s; } export function useJailCard(state, seat) { + const p0 = state.players[seat]; + if (!p0.jailed || !p0.jailCards?.length) return state; const s = clone(state); - s.players[seat].getOutOfJailFree--; - s.players[seat].jailed = false; - s.players[seat].jailTurns = 0; - log(s, `${s.players[seat].name} uses a Get Out of Jail Free card.`); + const p = s.players[seat]; + const jc = p.jailCards.shift(); + (jc.deck === 'chance' ? s.chanceDeck : s.ccDeck).push(jc.idx); + syncCards(p); + p.jailed = false; + p.jailTurns = 0; + fx(s, { type: 'free', seat }); + log(s, `${p.name} uses a Get Out of Jail Free card.`, seat); s.phase = 'preroll'; return s; } export function applyRent(state) { + if (!state.pendingRent) return state; const s = clone(state); const { payer, receiver, amount } = s.pendingRent; - const result = payTo(s, payer, receiver, amount); - Object.assign(s, result); s.pendingRent = null; - s.phase = 'endturn'; - return s; + s.cardDice = null; + charge(s, payer, receiver, amount, 'rent'); + return settlePhase(s); } // ── Turn ────────────────────────────────────────────────────────────────────── +function sampleHistory(s) { + s.stats.history.push(s.players.map(p => (p.active ? netWorth(s, p.seat) : 0))); + if (s.stats.history.length > 400) s.stats.history.shift(); +} + +function passTurn(s) { + s.doublesCount = 0; + s.diceRoll = null; + let next = s.current; + for (let k = 1; k <= s.playerCount; k++) { + const c = (s.current + k) % s.playerCount; + if (s.players[c].active) { next = c; break; } + } + if (next <= s.current) { + s.round++; + sampleHistory(s); + } + s.current = next; + s.turn++; + s.phase = 'preroll'; + if (checkGameOverInPlace(s)) return s; + if (s.rules.roundLimit && s.round > s.rules.roundLimit) finishGame(s, 'rounds'); + return s; +} + export function endTurn(state) { const s = clone(state); - // If doubles were rolled and player isn't jailed: same player rolls again - if (s.doublesCount > 0 && !s.players[s.current].jailed) { + if (s.phase === 'gameover') return s; + const p = s.players[s.current]; + // Doubles: the same player rolls again (unless jailed or out). + if (p.active && s.doublesCount > 0 && !p.jailed) { s.phase = 'preroll'; return s; } - s.doublesCount = 0; - // Advance to next active player - let next = (s.current + 1) % s.playerCount; - let guard = 0; - while (!s.players[next].active && guard++ < s.playerCount) { - next = (next + 1) % s.playerCount; - } - s.current = next; - s.diceRoll = null; - s.phase = 'preroll'; - return checkGameOver(s); + return passTurn(s); +} + +// ── Game over ───────────────────────────────────────────────────────────────── +function finishGame(s, reason) { + s.phase = 'gameover'; + s.endReason = reason; + const alive = s.players.filter(p => p.active) + .sort((a, b) => netWorth(s, b.seat) - netWorth(s, a.seat)); + const out = s.players.filter(p => !p.active) + .sort((a, b) => (b.bankruptTurn ?? 0) - (a.bankruptTurn ?? 0)); + s.standings = [...alive, ...out].map(p => p.seat); + s.winner = s.standings[0] ?? null; + s.pendingAuction = null; + s.pendingBuy = null; + s.pendingRent = null; + s.pendingCard = null; + s.debts = []; + sampleHistory(s); + if (s.winner !== null) { + const why = reason === 'short' ? ' (short game — richest player)' + : reason === 'rounds' ? ' (round limit — richest player)' : ''; + log(s, `${s.players[s.winner].name} wins${why}!`, s.winner); + } +} + +function checkGameOverInPlace(s) { + if (s.phase === 'gameover') return true; + const active = s.players.filter(p => p.active); + if (active.length <= 1) { finishGame(s, 'last'); return true; } + if (isShort(s) && s.players.some(p => p.bankrupt)) { finishGame(s, 'short'); return true; } + return false; +} + +export function checkGameOver(state) { + const s = clone(state); + checkGameOverInPlace(s); + return s; +} + +// ── Threat map ──────────────────────────────────────────────────────────────── +// For `seat`'s next roll: every reachable space with its probability and what +// landing there would cost. Ignores the follow-up roll after doubles. +export function threatMap(state, seat) { + const p = state.players[seat]; + const cells = []; + let pAny = 0, expected = 0; + for (let t = 2; t <= 12; t++) { + // Jailed: only doubles move you (1/36 each) — except the forced third try. + let prob = DICE_P[t]; + if (p.jailed && p.jailTurns < 2) prob = t % 2 === 0 ? 1 / 36 : 0; + if (prob <= 0) continue; + const idx = (p.position + t) % 40; + const sp = SPACES[idx]; + let cost = 0, kind = 'safe'; + const own = state.board[idx]; + if (own && own.owner !== null && own.owner !== seat && !own.mortgaged) { + cost = calculateRent(state, idx, t); + kind = 'rent'; + } else if (own && own.owner === null) { + kind = 'buy'; + } else if (sp.type === 'tax') { + cost = sp.amount; kind = 'tax'; + } else if (sp.type === 'gotojail') { + kind = 'jail'; + } else if (sp.type === 'chance' || sp.type === 'community_chest') { + kind = 'card'; + } + const prev = cells.find(c => c.idx === idx); + if (prev) prev.prob += prob; + else cells.push({ idx, prob, cost, kind, total: t }); + if (cost > 0) { pAny += prob; expected += prob * cost; } + } + return { cells, pAny, expected }; } diff --git a/src/games/monopoly/MonopolySound.js b/src/games/monopoly/MonopolySound.js new file mode 100644 index 0000000..48728b5 --- /dev/null +++ b/src/games/monopoly/MonopolySound.js @@ -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 }); + }); +} diff --git a/src/games/monopoly/MonopolyTrade.js b/src/games/monopoly/MonopolyTrade.js new file mode 100644 index 0000000..73b015e --- /dev/null +++ b/src/games/monopoly/MonopolyTrade.js @@ -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]; + } +} diff --git a/src/games/monopoly/MonopolyTray.js b/src/games/monopoly/MonopolyTray.js new file mode 100644 index 0000000..e342e85 --- /dev/null +++ b/src/games/monopoly/MonopolyTray.js @@ -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]; + } +} diff --git a/src/games/monopoly/sprites.md b/src/games/monopoly/sprites.md deleted file mode 100644 index 2abf1a4..0000000 --- a/src/games/monopoly/sprites.md +++ /dev/null @@ -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 diff --git a/src/games/monopoly/tutorial.md b/src/games/monopoly/tutorial.md new file mode 100644 index 0000000..b780ca3 --- /dev/null +++ b/src/games/monopoly/tutorial.md @@ -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." diff --git a/tools/verifyMonopoly.js b/tools/verifyMonopoly.js new file mode 100644 index 0000000..7a64b4e --- /dev/null +++ b/tools/verifyMonopoly.js @@ -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);