From 8ef312ef453b93614b8c91bc2f98f532c5632f91 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Wed, 25 Nov 2026 01:09:43 -0700 Subject: [PATCH] Overhaul Catan and Ticket to Ride with procedural art tables, shared 3D dice, skill-scaled AI, end screens, and headless verification tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Catan: bake the wooden table, sea frame, caddy, tray, opponent boards and end screen from code; add piece-supply limits, official bank-shortage rule, per-game stats, AI trade reasons, and a felt dice tray using shared 3D dice - Ticket to Ride: render an antique parchment map with score track, desk pad HUD, dialogs, sound synth, and scoring ceremony; rewrite the AI as a 1–5 skill ladder with network planning and turn-weighted routing; add forced-pass/stall guard, route lock reasons, per-player stats, and face-up market replacement - Extract the 3D dice cube math and renderer into src/ui/dice/Dice3D.js so Craps and Catan share one implementation - Add tools/verifyCatan.js and tools/verifyTicketToRide.js for headless rules, soak, AI ladder, dice, and layout checks - Enable skill selection for Ticket to Ride in the opponent select screen; make MusicPlayer controls positionable for the map corner --- src/games/catan/CatanAI.js | 34 +- src/games/catan/CatanArt.js | 561 ++++ src/games/catan/CatanBoards.js | 164 ++ src/games/catan/CatanCaddy.js | 153 ++ src/games/catan/CatanEndScreen.js | 225 ++ src/games/catan/CatanGame.js | 2376 ++++++++--------- src/games/catan/CatanLayout.js | 251 ++ src/games/catan/CatanLogic.js | 111 +- src/games/catan/CatanTray.js | 106 + src/games/craps/CrapsDice.js | 222 +- src/games/tickettoride/TicketToRideAI.js | 493 +++- src/games/tickettoride/TicketToRideArt.js | 982 +++++++ src/games/tickettoride/TicketToRideDialogs.js | 271 ++ .../tickettoride/TicketToRideEndScreen.js | 253 ++ src/games/tickettoride/TicketToRideGame.js | 2051 +++++++------- src/games/tickettoride/TicketToRideHud.js | 614 +++++ src/games/tickettoride/TicketToRideLayout.js | 142 + src/games/tickettoride/TicketToRideLogic.js | 161 +- src/games/tickettoride/TicketToRideSound.js | 77 + src/games/tickettoride/tutorial.md | 22 + src/scenes/OpponentSelectScene.js | 2 +- src/ui/MusicPlayer.js | 17 +- src/ui/dice/Dice3D.js | 339 +++ tools/verifyCatan.js | 369 +++ tools/verifyTicketToRide.js | 380 +++ 25 files changed, 7749 insertions(+), 2627 deletions(-) create mode 100644 src/games/catan/CatanArt.js create mode 100644 src/games/catan/CatanBoards.js create mode 100644 src/games/catan/CatanCaddy.js create mode 100644 src/games/catan/CatanEndScreen.js create mode 100644 src/games/catan/CatanLayout.js create mode 100644 src/games/catan/CatanTray.js create mode 100644 src/games/tickettoride/TicketToRideArt.js create mode 100644 src/games/tickettoride/TicketToRideDialogs.js create mode 100644 src/games/tickettoride/TicketToRideEndScreen.js create mode 100644 src/games/tickettoride/TicketToRideHud.js create mode 100644 src/games/tickettoride/TicketToRideLayout.js create mode 100644 src/games/tickettoride/TicketToRideSound.js create mode 100644 src/ui/dice/Dice3D.js create mode 100644 tools/verifyCatan.js create mode 100644 tools/verifyTicketToRide.js diff --git a/src/games/catan/CatanAI.js b/src/games/catan/CatanAI.js index 5d05cdc..3c6bc38 100644 --- a/src/games/catan/CatanAI.js +++ b/src/games/catan/CatanAI.js @@ -4,7 +4,7 @@ import { pipCount, COSTS, RESOURCE_TYPES } from './CatanBoard.js'; import { - legalSettlementNodes, legalRoadEdges, canAfford, bestTradeRatio, + legalSettlementNodes, legalRoadEdges, legalCityNodes, canAfford, bestTradeRatio, handSize, nodeBuilding, stealTargets, publicVictoryPoints, victoryPoints, longestRoadFor, geoFor, winVpFor, } from './CatanLogic.js'; @@ -163,7 +163,7 @@ export function chooseAction(state, seat) { const have = p.resources; // Best city upgrade (upgrade highest-value settlement first). - const citySettlements = [...p.settlements].sort((a, b) => nodeValue(state, b) - nodeValue(state, a)); + const citySettlements = legalCityNodes(state, seat).sort((a, b) => nodeValue(state, b) - nodeValue(state, a)); const settleSpots = legalSettlementNodes(state, seat, false) .sort((a, b) => nodeValue(state, b) - nodeValue(state, a)); @@ -333,13 +333,19 @@ function chooseHelpfulDev(state, seat, citySettlements, settleSpots) { return null; } +// What the AI is saving for: a city while one can still be placed (supply and a +// settlement to upgrade), otherwise a settlement. +function primaryTarget(state, seat) { + return legalCityNodes(state, seat).length ? COSTS.city : COSTS.settlement; +} + // ── AI trade initiation ───────────────────────────────────────────────────────── // Propose a 1-for-1 trade that moves `seat` toward its highest objective: // it gives `give` (a surplus resource) and wants `get` (a needed resource). Or null. export function proposeTrade(state, seat, exclude = new Set()) { const p = state.players[seat]; const have = p.resources; - const target = p.settlements.length ? COSTS.city : COSTS.settlement; + const target = primaryTarget(state, seat); if (canAfford(p, target)) return null; // nothing to trade for — just build const missing = RESOURCE_TYPES.filter((r) => (target[r] || 0) > have[r] && !exclude.has(r)); if (!missing.length) return null; @@ -372,12 +378,28 @@ export function respondToTrade(state, seat, give, get, requesterSeat = 0) { return baseAccept(state, seat, give, get); // existing logic } +// The same decision as respondToTrade, plus a short reason the scene can voice +// in a speech bubble: 'deal' | 'lacks' (doesn't hold what's asked) | +// 'leader' (requester is too close to winning) | 'needs' (wants to keep it) | +// 'poor' (the offer isn't worth it). +export function tradeReply(state, seat, give, get, requesterSeat = 0) { + const p = state.players[seat]; + if (RESOURCE_TYPES.some((r) => (give[r] || 0) > p.resources[r])) return { accept: false, reason: 'lacks' }; + const accept = respondToTrade(state, seat, give, get, requesterSeat); + if (accept) return { accept: true, reason: 'deal' }; + const reqVP = publicVictoryPoints(state, requesterSeat); + if (reqVP >= 6) return { accept: false, reason: 'leader' }; + const target = primaryTarget(state, seat); + const needsIt = RESOURCE_TYPES.some((r) => (give[r] || 0) > 0 && p.resources[r] - (give[r] || 0) < (target[r] || 0)); + return { accept: false, reason: needsIt ? 'needs' : 'poor' }; +} + // 0–5 VP: original value heuristic. function baseAccept(state, seat, give, get) { const p = state.players[seat]; const giveCount = RESOURCE_TYPES.reduce((s, r) => s + (give[r] || 0), 0); const getCount = RESOURCE_TYPES.reduce((s, r) => s + (get[r] || 0), 0); - const target = p.settlements.length ? COSTS.city : COSTS.settlement; + const target = primaryTarget(state, seat); const need = (r) => Math.max(0, (target[r] || 0) - p.resources[r]); const valIn = RESOURCE_TYPES.reduce((s, r) => s + (get[r] || 0) * (1 + need(r)), 0); const valOut = RESOURCE_TYPES.reduce((s, r) => s + (give[r] || 0) * (1 + need(r) * 0.5), 0); @@ -388,7 +410,7 @@ function baseAccept(state, seat, give, get) { function tradeBeneficial(state, seat, give, get) { const p = state.players[seat]; const have = p.resources; - const target = p.settlements.length ? COSTS.city : COSTS.settlement; + const target = primaryTarget(state, seat); const need = (r) => Math.max(0, (target[r] || 0) - have[r]); const prod = productionByResource(state, seat); // Benefit: an incoming resource we need for our target, or one we can't produce. @@ -409,7 +431,7 @@ function tradeWinsGame(state, seat, give, get) { const afford2 = (cost) => RESOURCE_TYPES.every((r) => have2[r] >= (cost[r] || 0)); const ownVP = victoryPoints(state, seat); const win = winVpFor(state); - if (p.settlements.length && afford2(COSTS.city) && ownVP + 1 >= win) return true; + if (legalCityNodes(state, seat).length && afford2(COSTS.city) && ownVP + 1 >= win) return true; if (legalSettlementNodes(state, seat, false).length && afford2(COSTS.settlement) && ownVP + 1 >= win) return true; return false; } diff --git a/src/games/catan/CatanArt.js b/src/games/catan/CatanArt.js new file mode 100644 index 0000000..438afbe --- /dev/null +++ b/src/games/catan/CatanArt.js @@ -0,0 +1,561 @@ +// CatanArt.js — procedural canvas art for the Catan table. +// +// Everything is baked once into Phaser canvas textures (no image files): +// catan-table warm plank tabletop, lamp pool and vignette (full screen) +// catan-rail the near table edge where the human's things sit +// catan-frame- the wooden sea frame + sea band around the active board +// catan-caddy the bank card caddy (6 wells + brass plaques) +// catan-tray the felt dice tray +// catan-plaque an opponent's wooden player board +// catan-costcard the parchment Building Costs card +// catan-histo the chalk tally board (roll histogram) +// catan-chit a number-chit token +// catan-set- / catan-city- / catan-road- / catan-ship- pieces +// catan-boat a harbour boat; catan-glint a sea glint +// catan-p-* particles (chip, tuft, chaff, spark, dust, smoke) + +import { canvas, rr, poly, mix, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + W, H, RAIL, CADDY, caddySlot, TRAY, TRAY_WALL, OPP_BOARD, COSTCARD, HISTO, + boardFrame, FRAME, offsetPolygon, +} from './CatanLayout.js'; + +const RES = 2; // pieces/tokens are baked at 2× for crisp scaling + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); + return key; +} + +// Thin wavy grain lines over a rect (already clipped by the caller). +function grain(ctx, x, y, w, h, { dark = 'rgba(40,22,8,0.16)', light = 'rgba(255,220,170,0.06)', spacing = 7, amp = 2.2, seed = 1 } = {}) { + let r = seed * 9301 + 49297; + const rnd = () => ((r = (r * 9301 + 49297) % 233280) / 233280); + ctx.save(); + ctx.lineWidth = 1; + for (let yy = y; yy < y + h; yy += spacing * (0.6 + rnd() * 0.8)) { + ctx.strokeStyle = rnd() < 0.7 ? dark : light; + ctx.beginPath(); + const ph = rnd() * 6, fq = 0.004 + rnd() * 0.01; + for (let xx = x; xx <= x + w; xx += 12) { + const yv = yy + Math.sin(xx * fq + ph) * amp + Math.sin(xx * fq * 3.1 + ph) * amp * 0.3; + if (xx === x) ctx.moveTo(xx, yv); else ctx.lineTo(xx, yv); + } + ctx.stroke(); + } + ctx.restore(); +} + +function woodFill(ctx, x, y, w, h, top, bottom, seed = 1, spacing = 7) { + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, top); g.addColorStop(1, bottom); + ctx.fillStyle = g; + ctx.fill(); + ctx.save(); + ctx.clip(); + grain(ctx, x, y, w, h, { seed, spacing }); + ctx.fillStyle = noisePattern(ctx, 64, 22); + ctx.fillRect(x, y, w, h); + ctx.restore(); +} + +// ── table + rail ───────────────────────────────────────────────────────────── +function bakeTable(scene, { planks = true } = {}) { + const key = planks ? 'catan-table' : 'catan-table-light'; + if (scene.textures.exists(key)) return key; + const c = canvas(W, H); + const ctx = c.getContext('2d'); + if (planks) { + const PH = 128; + const tones = ['#6e4524', '#764b28', '#6a4222', '#7b5130', '#704826', '#6c4423', '#774c29', '#6f4625', '#734a27']; + for (let i = 0, y = 0; y < H; i++, y += PH) { + ctx.beginPath(); ctx.rect(0, y, W, PH); + woodFill(ctx, 0, y, W, PH, tones[i % tones.length], mix(tones[i % tones.length], '#2a160a', 0.25), i + 3, 6); + // seams + staggered butt joints + ctx.fillStyle = 'rgba(20,10,4,0.55)'; + ctx.fillRect(0, y, W, 2); + ctx.fillStyle = 'rgba(255,214,160,0.06)'; + ctx.fillRect(0, y + 2, W, 1); + const off = (i * 523) % 700; + for (let x = off; x < W; x += 900) { + ctx.fillStyle = 'rgba(20,10,4,0.45)'; + ctx.fillRect(x, y, 2, PH); + } + } + } + // lamp pool on the board, vignette towards the edges + const lp = ctx.createRadialGradient(1000, 470, 40, 1000, 470, 980); + lp.addColorStop(0, 'rgba(255,214,150,0.26)'); + lp.addColorStop(0.55, 'rgba(255,200,130,0.08)'); + lp.addColorStop(1, 'rgba(255,200,130,0)'); + ctx.fillStyle = lp; ctx.fillRect(0, 0, W, H); + const vg = ctx.createRadialGradient(1000, 500, 500, 1000, 500, 1250); + vg.addColorStop(0, 'rgba(0,0,0,0)'); + vg.addColorStop(1, 'rgba(0,0,0,0.6)'); + ctx.fillStyle = vg; ctx.fillRect(0, 0, W, H); + return addCanvas(scene, key, c); +} + +function bakeRail(scene) { + const key = 'catan-rail'; + if (scene.textures.exists(key)) return key; + const pad = 24; + const c = canvas(W, RAIL.h + pad); + const ctx = c.getContext('2d'); + // shadow the rail throws back onto the table + const sh = ctx.createLinearGradient(0, 0, 0, pad); + sh.addColorStop(0, 'rgba(0,0,0,0)'); sh.addColorStop(1, 'rgba(0,0,0,0.45)'); + ctx.fillStyle = sh; ctx.fillRect(0, 0, W, pad); + ctx.beginPath(); ctx.rect(0, pad, W, RAIL.h); + woodFill(ctx, 0, pad, W, RAIL.h, '#4a2c16', '#24140a', 41, 5); + // rounded front lip highlight + brass inlay + const lip = ctx.createLinearGradient(0, pad, 0, pad + 14); + lip.addColorStop(0, 'rgba(255,220,170,0.32)'); lip.addColorStop(1, 'rgba(255,220,170,0)'); + ctx.fillStyle = lip; ctx.fillRect(0, pad, W, 14); + ctx.fillStyle = '#b8913f'; ctx.fillRect(0, pad + 16, W, 2); + ctx.fillStyle = 'rgba(255,240,190,0.5)'; ctx.fillRect(0, pad + 16, W, 1); + // a felt runner for the human's cards + ctx.save(); + rr(ctx, 160, pad + 26, 1320, RAIL.h - 36, 14); + ctx.fillStyle = '#20382a'; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 30); ctx.fillRect(160, pad + 26, 1320, RAIL.h - 36); + const inner = ctx.createLinearGradient(0, pad + 26, 0, pad + 46); + inner.addColorStop(0, 'rgba(0,0,0,0.5)'); inner.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = inner; ctx.fillRect(160, pad + 26, 1320, 20); + ctx.restore(); + ctx.strokeStyle = 'rgba(184,145,63,0.55)'; ctx.lineWidth = 1.5; + rr(ctx, 160, pad + 26, 1320, RAIL.h - 36, 14); ctx.stroke(); + return addCanvas(scene, key, c); +} + +// ── board frame ────────────────────────────────────────────────────────────── +export function bakeFrame(scene, geo, boardId) { + const key = `catan-frame-${boardId}`; + const fr = boardFrame(geo); + if (scene.textures.exists(key)) return { key, fr, origin: originOf(fr) }; + const origin = originOf(fr); + const c = canvas(Math.ceil(fr.bounds.w + 80), Math.ceil(fr.bounds.h + 80)); + const ctx = c.getContext('2d'); + const T = (pts) => pts.map((p) => ({ x: p.x - origin.x, y: p.y - origin.y })); + const rim = T(fr.rim), sea = T(fr.sea), hull = T(fr.hull); + + // drop shadow onto the table + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.65)'; ctx.shadowBlur = 34; ctx.shadowOffsetY = 12; + poly(ctx, rim); ctx.fillStyle = '#3a2412'; ctx.fill(); + ctx.restore(); + // wooden rim + const b = { x: 0, y: 0, w: c.width, h: c.height }; + poly(ctx, rim); + woodFill(ctx, b.x, b.y, b.w, b.h, '#9a6634', '#5e3a1b', 17, 5); + ctx.strokeStyle = 'rgba(255,226,170,0.45)'; ctx.lineWidth = 2; poly(ctx, rim); ctx.stroke(); + // sea, deep at the rim, shallow by the coast + const steps = 14; + for (let i = 0; i <= steps; i++) { + const t = i / steps; + const d = FRAME.sea * (1 - t); + const p = T(offsetFrom(fr.hull, d)); + poly(ctx, p); + ctx.fillStyle = mix('#0c3653', '#2e8fae', t); + ctx.fill(); + } + poly(ctx, hull); ctx.fillStyle = '#3197b4'; ctx.fill(); + // wave hatching + ctx.save(); + poly(ctx, sea); ctx.clip(); + ctx.strokeStyle = 'rgba(220,245,255,0.16)'; ctx.lineWidth = 1.4; + let r = 7; + const rnd = () => ((r = (r * 9301 + 49297) % 233280) / 233280); + for (let i = 0; i < 260; i++) { + const x = rnd() * c.width, y = rnd() * c.height, w = 8 + rnd() * 10; + ctx.beginPath(); ctx.moveTo(x, y); + ctx.quadraticCurveTo(x + w / 2, y - 4, x + w, y); + ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 64, 18); ctx.fillRect(0, 0, c.width, c.height); + ctx.restore(); + // inner bevel where the frame meets the sea + ctx.strokeStyle = 'rgba(20,10,4,0.75)'; ctx.lineWidth = 3; poly(ctx, sea); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,226,170,0.18)'; ctx.lineWidth = 1; poly(ctx, T(offsetFrom(fr.hull, FRAME.sea + 2))); ctx.stroke(); + addCanvas(scene, key, c); + return { key, fr, origin }; +} +function originOf(fr) { return { x: Math.floor(fr.bounds.x - 40), y: Math.floor(fr.bounds.y - 40) }; } +function offsetFrom(hull, d) { return offsetPolygon(hull, d); } + +// ── caddy ──────────────────────────────────────────────────────────────────── +function bakeCaddy(scene) { + const key = 'catan-caddy'; + if (scene.textures.exists(key)) return key; + const pad = 20; + const c = canvas(CADDY.w + pad * 2, CADDY.h + pad * 2); + const ctx = c.getContext('2d'); + const ox = pad - CADDY.x, oy = pad - CADDY.y; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 22; ctx.shadowOffsetY = 8; + rr(ctx, pad, pad, CADDY.w, CADDY.h, 14); ctx.fillStyle = '#5a3719'; ctx.fill(); + ctx.restore(); + rr(ctx, pad, pad, CADDY.w, CADDY.h, 14); + woodFill(ctx, pad, pad, CADDY.w, CADDY.h, '#a36d37', '#6b4220', 23, 5); + ctx.strokeStyle = 'rgba(255,230,180,0.5)'; ctx.lineWidth = 2; rr(ctx, pad + 1, pad + 1, CADDY.w - 2, CADDY.h - 2, 13); ctx.stroke(); + // engraved title + ctx.font = '26px Righteous, sans-serif'; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillStyle = 'rgba(255,230,180,0.35)'; ctx.fillText('BANK', pad + CADDY.w / 2 + 1, pad + 29); + ctx.fillStyle = 'rgba(40,20,6,0.8)'; ctx.fillText('BANK', pad + CADDY.w / 2, pad + 28); + for (let i = 0; i < 6; i++) { + const s = caddySlot(i); + const x = s.x + ox, y = s.y + oy; + // recessed well + rr(ctx, x, y, s.w, s.h, 9); + ctx.fillStyle = '#2b190c'; ctx.fill(); + ctx.save(); rr(ctx, x, y, s.w, s.h, 9); ctx.clip(); + const ig = ctx.createLinearGradient(0, y, 0, y + 16); + ig.addColorStop(0, 'rgba(0,0,0,0.65)'); ig.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = ig; ctx.fillRect(x, y, s.w, 16); + const lg = ctx.createLinearGradient(x, 0, x + 12, 0); + lg.addColorStop(0, 'rgba(0,0,0,0.45)'); lg.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = lg; ctx.fillRect(x, y, 12, s.h); + ctx.restore(); + ctx.strokeStyle = 'rgba(255,226,170,0.3)'; ctx.lineWidth = 1; rr(ctx, x - 1, y - 1, s.w + 2, s.h + 2, 10); ctx.stroke(); + // brass plaque + const px = s.plaque.x + ox, py = s.plaque.y + oy; + rr(ctx, px - 24, py - 18, 48, 36, 6); + const bg = ctx.createLinearGradient(0, py - 18, 0, py + 18); + bg.addColorStop(0, '#f0d48a'); bg.addColorStop(0.5, '#c99d42'); bg.addColorStop(1, '#8d6a26'); + ctx.fillStyle = bg; ctx.fill(); + ctx.strokeStyle = 'rgba(60,36,8,0.8)'; ctx.lineWidth = 1.2; ctx.stroke(); + ctx.fillStyle = 'rgba(70,44,10,0.75)'; + for (const [dx, dy] of [[-19, -13], [19, -13], [-19, 13], [19, 13]]) { ctx.beginPath(); ctx.arc(px + dx, py + dy, 1.6, 0, Math.PI * 2); ctx.fill(); } + if (i === 4) { + ctx.strokeStyle = 'rgba(40,20,6,0.6)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(pad + 12, y + s.h + 1); ctx.lineTo(pad + CADDY.w - 12, y + s.h + 1); ctx.stroke(); + } + } + return addCanvas(scene, key, c); +} + +// ── dice tray ──────────────────────────────────────────────────────────────── +function bakeTray(scene) { + const key = 'catan-tray'; + if (scene.textures.exists(key)) return key; + const pad = 20; + const c = canvas(TRAY.w + pad * 2, TRAY.h + pad * 2); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 20; ctx.shadowOffsetY = 8; + rr(ctx, pad, pad, TRAY.w, TRAY.h, 16); ctx.fillStyle = '#4a2c16'; ctx.fill(); + ctx.restore(); + rr(ctx, pad, pad, TRAY.w, TRAY.h, 16); + woodFill(ctx, pad, pad, TRAY.w, TRAY.h, '#8e5a2c', '#5a3518', 31, 5); + ctx.strokeStyle = 'rgba(255,230,180,0.45)'; ctx.lineWidth = 2; rr(ctx, pad + 1, pad + 1, TRAY.w - 2, TRAY.h - 2, 15); ctx.stroke(); + const fx = pad + TRAY_WALL, fy = pad + TRAY_WALL, fw = TRAY.w - TRAY_WALL * 2, fh = TRAY.h - TRAY_WALL * 2; + rr(ctx, fx, fy, fw, fh, 9); + const fg = ctx.createRadialGradient(fx + fw / 2, fy + fh / 2, 10, fx + fw / 2, fy + fh / 2, fw * 0.6); + fg.addColorStop(0, '#2f7a4c'); fg.addColorStop(1, '#174a2d'); + ctx.fillStyle = fg; ctx.fill(); + ctx.save(); rr(ctx, fx, fy, fw, fh, 9); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 34); ctx.fillRect(fx, fy, fw, fh); + const ig = ctx.createLinearGradient(0, fy, 0, fy + 22); + ig.addColorStop(0, 'rgba(0,0,0,0.6)'); ig.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = ig; ctx.fillRect(fx, fy, fw, 22); + const lg = ctx.createLinearGradient(fx, 0, fx + 16, 0); + lg.addColorStop(0, 'rgba(0,0,0,0.4)'); lg.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = lg; ctx.fillRect(fx, fy, 16, fh); + ctx.restore(); + return addCanvas(scene, key, c); +} + +// ── opponent plaque ────────────────────────────────────────────────────────── +function bakePlaque(scene) { + const key = 'catan-plaque'; + if (scene.textures.exists(key)) return key; + const pad = 18, w = OPP_BOARD.w, h = OPP_BOARD.h; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 20; ctx.shadowOffsetY = 7; + rr(ctx, pad, pad, w, h, 16); ctx.fillStyle = '#5a3719'; ctx.fill(); + ctx.restore(); + rr(ctx, pad, pad, w, h, 16); + woodFill(ctx, pad, pad, w, h, '#946234', '#62401f', 57, 6); + ctx.strokeStyle = 'rgba(255,230,180,0.42)'; ctx.lineWidth = 2; rr(ctx, pad + 1, pad + 1, w - 2, h - 2, 15); ctx.stroke(); + ctx.strokeStyle = 'rgba(40,20,6,0.5)'; ctx.lineWidth = 1.5; rr(ctx, pad + 7, pad + 7, w - 14, h - 14, 11); ctx.stroke(); + // inset tray for the cards / pieces + rr(ctx, pad + 152, pad + 14, w - 166, h - 28, 10); + ctx.fillStyle = 'rgba(30,16,6,0.5)'; ctx.fill(); + ctx.save(); rr(ctx, pad + 152, pad + 14, w - 166, h - 28, 10); ctx.clip(); + const ig = ctx.createLinearGradient(0, pad + 14, 0, pad + 30); + ig.addColorStop(0, 'rgba(0,0,0,0.5)'); ig.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = ig; ctx.fillRect(pad + 152, pad + 14, w - 166, 16); + ctx.restore(); + // portrait well + ctx.beginPath(); ctx.arc(pad + 82, pad + 104, 62, 0, Math.PI * 2); + ctx.fillStyle = 'rgba(25,12,4,0.65)'; ctx.fill(); + ctx.strokeStyle = 'rgba(255,226,170,0.3)'; ctx.lineWidth = 1.5; ctx.stroke(); + return addCanvas(scene, key, c); +} + +// ── parchment cost card ────────────────────────────────────────────────────── +function bakeCostCard(scene) { + const key = 'catan-costcard'; + if (scene.textures.exists(key)) return key; + const pad = 14, w = COSTCARD.w, h = COSTCARD.h; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 14; ctx.shadowOffsetY = 5; + rr(ctx, pad, pad, w, h, 10); ctx.fillStyle = '#e7d3a4'; ctx.fill(); + ctx.restore(); + rr(ctx, pad, pad, w, h, 10); + const g = ctx.createRadialGradient(pad + w / 2, pad + h / 2, 20, pad + w / 2, pad + h / 2, w * 0.62); + g.addColorStop(0, '#f4e7c4'); g.addColorStop(1, '#cdb37a'); + ctx.fillStyle = g; ctx.fill(); + ctx.save(); rr(ctx, pad, pad, w, h, 10); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 26); ctx.fillRect(pad, pad, w, h); + ctx.restore(); + ctx.strokeStyle = 'rgba(110,70,24,0.8)'; ctx.lineWidth = 2; rr(ctx, pad + 5, pad + 5, w - 10, h - 10, 7); ctx.stroke(); + ctx.strokeStyle = 'rgba(110,70,24,0.4)'; ctx.lineWidth = 1; rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 5); ctx.stroke(); + return addCanvas(scene, key, c); +} + +// ── chalk tally board ──────────────────────────────────────────────────────── +function bakeHisto(scene) { + const key = 'catan-histo'; + if (scene.textures.exists(key)) return key; + const pad = 14, w = HISTO.w, h = HISTO.h; + const c = canvas(w + pad * 2, h + pad * 2); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 14; ctx.shadowOffsetY = 5; + rr(ctx, pad, pad, w, h, 10); ctx.fillStyle = '#5c3a1b'; ctx.fill(); + ctx.restore(); + rr(ctx, pad, pad, w, h, 10); + woodFill(ctx, pad, pad, w, h, '#8a5a2e', '#5a3719', 77, 5); + rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 6); + ctx.fillStyle = '#25332d'; ctx.fill(); + ctx.save(); rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 6); ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 30); ctx.fillRect(pad, pad, w, h); + // old chalk smudges + for (let i = 0; i < 7; i++) { + const x = pad + 20 + (i * 53) % (w - 40), y = pad + 30 + (i * 37) % (h - 60); + const sg = ctx.createRadialGradient(x, y, 2, x, y, 40); + sg.addColorStop(0, 'rgba(255,255,255,0.05)'); sg.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = sg; ctx.fillRect(x - 40, y - 40, 80, 80); + } + ctx.restore(); + return addCanvas(scene, key, c); +} + +// ── number chit ────────────────────────────────────────────────────────────── +function bakeChit(scene) { + const key = 'catan-chit'; + if (scene.textures.exists(key)) return key; + const S = 64 * RES, R = 25 * RES, cx = S / 2, cy = S / 2 - 2 * RES; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 6 * RES; ctx.shadowOffsetY = 3 * RES; ctx.shadowOffsetX = 1 * RES; + ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fillStyle = '#d8c08c'; ctx.fill(); + ctx.restore(); + // edge thickness + ctx.beginPath(); ctx.arc(cx, cy + 2 * RES, R, 0, Math.PI * 2); ctx.fillStyle = '#a5864e'; ctx.fill(); + const g = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R); + g.addColorStop(0, '#fff6df'); g.addColorStop(0.7, '#efdfb6'); g.addColorStop(1, '#d6bf88'); + ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fillStyle = g; ctx.fill(); + ctx.lineWidth = 2.2 * RES; ctx.strokeStyle = '#a5864e'; ctx.stroke(); + ctx.beginPath(); ctx.arc(cx, cy, R - 4.5 * RES, 0, Math.PI * 2); + ctx.lineWidth = 1 * RES; ctx.strokeStyle = 'rgba(165,134,78,0.6)'; ctx.stroke(); + ctx.beginPath(); ctx.arc(cx, cy, R - 1.5 * RES, Math.PI * 1.05, Math.PI * 1.55); + ctx.lineWidth = 1.5 * RES; ctx.strokeStyle = 'rgba(255,255,255,0.7)'; ctx.stroke(); + return addCanvas(scene, key, c); +} + +// ── pieces ─────────────────────────────────────────────────────────────────── +function shade(hex, k) { + const r = (hex >> 16) & 255, g = (hex >> 8) & 255, b = hex & 255; + const f = (v) => Math.max(0, Math.min(255, Math.round(k >= 0 ? v + (255 - v) * k : v * (1 + k)))); + return `rgb(${f(r)},${f(g)},${f(b)})`; +} + +// A box with a gable roof seen 3/4 from the front-left (light upper-left). +// x,y: bottom-left of the front face; w,h: front face; d: side depth; rh: roof height. +function house(ctx, x, y, w, h, d, rh, col) { + const dx = d * 0.9, dy = -d * 0.55; + const edge = shade(col, -0.62); + ctx.lineJoin = 'round'; + ctx.lineWidth = 1.4 * RES; ctx.strokeStyle = edge; + // right side wall + poly(ctx, [{ x: x + w, y }, { x: x + w + dx, y: y + dy }, { x: x + w + dx, y: y - h + dy }, { x: x + w, y: y - h }]); + ctx.fillStyle = shade(col, -0.38); ctx.fill(); ctx.stroke(); + // roof slope (the right-hand plane, from ridge to the side wall top) + poly(ctx, [{ x: x + w / 2, y: y - h - rh }, { x: x + w / 2 + dx, y: y - h - rh + dy }, { x: x + w + dx, y: y - h + dy }, { x: x + w, y: y - h }]); + ctx.fillStyle = shade(col, -0.18); ctx.fill(); ctx.stroke(); + // front face + gable + poly(ctx, [{ x, y }, { x: x + w, y }, { x: x + w, y: y - h }, { x: x + w / 2, y: y - h - rh }, { x, y: y - h }]); + const g = ctx.createLinearGradient(x, y - h - rh, x + w, y); + g.addColorStop(0, shade(col, 0.28)); g.addColorStop(1, shade(col, 0.02)); + ctx.fillStyle = g; ctx.fill(); ctx.stroke(); + // ridge highlight + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; ctx.lineWidth = 1 * RES; + ctx.beginPath(); ctx.moveTo(x + w / 2, y - h - rh); ctx.lineTo(x + w / 2 + dx, y - h - rh + dy); ctx.stroke(); +} + +function bakeSettlement(scene, ci, col) { + const key = `catan-set-${ci}`; + if (scene.textures.exists(key)) return key; + const S = 56 * RES; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + // shadow + ctx.save(); ctx.filter = `blur(${3 * RES}px)`; + ctx.fillStyle = 'rgba(0,0,0,0.55)'; + ctx.beginPath(); ctx.ellipse(S * 0.56, S * 0.8, S * 0.33, S * 0.11, -0.15, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + house(ctx, S * 0.2, S * 0.8, S * 0.42, S * 0.3, S * 0.2, S * 0.2, col); + return addCanvas(scene, key, c); +} + +function bakeCity(scene, ci, col) { + const key = `catan-city-${ci}`; + if (scene.textures.exists(key)) return key; + const S = 72 * RES; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + ctx.save(); ctx.filter = `blur(${3 * RES}px)`; + ctx.fillStyle = 'rgba(0,0,0,0.55)'; + ctx.beginPath(); ctx.ellipse(S * 0.55, S * 0.82, S * 0.38, S * 0.11, -0.12, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + // tall tower behind-right, low hall in front-left + house(ctx, S * 0.42, S * 0.78, S * 0.26, S * 0.42, S * 0.15, S * 0.16, col); + house(ctx, S * 0.12, S * 0.84, S * 0.36, S * 0.2, S * 0.15, S * 0.1, col); + return addCanvas(scene, key, c); +} + +function bakeRoad(scene, ci, col) { + const key = `catan-road-${ci}`; + if (scene.textures.exists(key)) return key; + const w = 80 * RES, h = 22 * RES; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + ctx.save(); ctx.filter = `blur(${2 * RES}px)`; + rr(ctx, 4 * RES, 8 * RES, w - 6 * RES, 11 * RES, 3 * RES); ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fill(); + ctx.restore(); + // side (thickness) + rr(ctx, 2 * RES, 6 * RES, w - 6 * RES, 11 * RES, 3 * RES); ctx.fillStyle = shade(col, -0.45); ctx.fill(); + // top + rr(ctx, 2 * RES, 3 * RES, w - 6 * RES, 10 * RES, 3 * RES); + const g = ctx.createLinearGradient(0, 3 * RES, 0, 13 * RES); + g.addColorStop(0, shade(col, 0.3)); g.addColorStop(1, shade(col, -0.05)); + ctx.fillStyle = g; ctx.fill(); + ctx.lineWidth = 1.2 * RES; ctx.strokeStyle = shade(col, -0.62); + rr(ctx, 2 * RES, 3 * RES, w - 6 * RES, 13.5 * RES, 3 * RES); ctx.stroke(); + ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(5 * RES, 4.5 * RES, w - 14 * RES, 1.4 * RES); + return addCanvas(scene, key, c); +} + +function bakeShip(scene, ci, col) { + const key = `catan-ship-${ci}`; + if (scene.textures.exists(key)) return key; + const S = 52 * RES; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + drawBoat(ctx, S, col); + return addCanvas(scene, key, c); +} + +function drawBoat(ctx, S, hullCol, sail = '#fbf4e2') { + ctx.save(); ctx.filter = `blur(${2 * RES}px)`; + ctx.fillStyle = 'rgba(0,20,40,0.45)'; + ctx.beginPath(); ctx.ellipse(S * 0.52, S * 0.84, S * 0.36, S * 0.08, 0, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + // hull + poly(ctx, [{ x: S * 0.12, y: S * 0.64 }, { x: S * 0.9, y: S * 0.64 }, { x: S * 0.76, y: S * 0.82 }, { x: S * 0.24, y: S * 0.82 }]); + const hc = typeof hullCol === 'number' ? hullCol : 0x7a4a22; + const g = ctx.createLinearGradient(0, S * 0.64, 0, S * 0.82); + g.addColorStop(0, shade(hc, 0.2)); g.addColorStop(1, shade(hc, -0.35)); + ctx.fillStyle = g; ctx.fill(); + ctx.lineWidth = 1.2 * RES; ctx.strokeStyle = shade(hc, -0.65); ctx.stroke(); + // mast + sail + ctx.strokeStyle = '#4a2c14'; ctx.lineWidth = 1.6 * RES; + ctx.beginPath(); ctx.moveTo(S * 0.5, S * 0.64); ctx.lineTo(S * 0.5, S * 0.1); ctx.stroke(); + poly(ctx, [{ x: S * 0.52, y: S * 0.13 }, { x: S * 0.52, y: S * 0.58 }, { x: S * 0.86, y: S * 0.56 }]); + const sg = ctx.createLinearGradient(S * 0.52, 0, S * 0.86, 0); + sg.addColorStop(0, sail); sg.addColorStop(1, '#d8ccb0'); + ctx.fillStyle = sg; ctx.fill(); ctx.lineWidth = 1 * RES; ctx.strokeStyle = 'rgba(80,60,30,0.7)'; ctx.stroke(); + poly(ctx, [{ x: S * 0.48, y: S * 0.2 }, { x: S * 0.48, y: S * 0.58 }, { x: S * 0.2, y: S * 0.56 }]); + ctx.fillStyle = '#efe3c6'; ctx.fill(); ctx.stroke(); +} + +function bakeHarbourBoat(scene) { + const key = 'catan-boat'; + if (scene.textures.exists(key)) return key; + const S = 56 * RES; + const c = canvas(S, S); + drawBoat(c.getContext('2d'), S, 0x8a5428); + return addCanvas(scene, key, c); +} + +// ── particles / glints ─────────────────────────────────────────────────────── +function bakeParticles(scene) { + const mk = (key, w, h, draw) => { + if (scene.textures.exists(key)) return; + const c = canvas(w, h); + draw(c.getContext('2d'), w, h); + addCanvas(scene, key, c); + }; + const soft = (ctx, w, h, rgb, a = 1) => { + const g = ctx.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2); + g.addColorStop(0, `rgba(${rgb},${a})`); g.addColorStop(1, `rgba(${rgb},0)`); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + }; + mk('catan-p-chip', 12, 6, (ctx, w, h) => { rr(ctx, 0, 0, w, h, 2); ctx.fillStyle = '#a0662c'; ctx.fill(); ctx.fillStyle = '#d9a466'; ctx.fillRect(1, 1, w - 2, 1.5); }); + mk('catan-p-tuft', 16, 16, (ctx, w, h) => soft(ctx, w, h, '255,255,248', 0.95)); + mk('catan-p-chaff', 12, 4, (ctx, w, h) => { rr(ctx, 0, 0, w, h, 2); ctx.fillStyle = '#f3cf4a'; ctx.fill(); }); + mk('catan-p-spark', 14, 14, (ctx, w, h) => { + soft(ctx, w, h, '220,235,255', 0.9); + ctx.fillStyle = '#ffffff'; ctx.fillRect(w / 2 - 0.75, 0, 1.5, h); ctx.fillRect(0, h / 2 - 0.75, w, 1.5); + }); + mk('catan-p-dust', 16, 16, (ctx, w, h) => soft(ctx, w, h, '205,120,70', 0.9)); + mk('catan-p-smoke', 32, 32, (ctx, w, h) => soft(ctx, w, h, '225,225,225', 0.75)); + mk('catan-p-puff', 24, 24, (ctx, w, h) => soft(ctx, w, h, '214,190,150', 0.85)); + mk('catan-glint', 34, 8, (ctx, w, h) => { + const g = ctx.createLinearGradient(0, 0, w, 0); + g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(235,250,255,0.9)'); g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; rr(ctx, 0, h / 2 - 1.5, w, 3, 1.5); ctx.fill(); + }); + mk('catan-window', 10, 10, (ctx, w, h) => soft(ctx, w, h, '255,210,120', 1)); +} + +export const PARTICLE_FOR = { + lumber: { key: 'catan-p-chip', tint: [0xffffff, 0xd9a466], gravity: 220 }, + wool: { key: 'catan-p-tuft', tint: [0xffffff, 0xf4f1e6], gravity: -30 }, + grain: { key: 'catan-p-chaff', tint: [0xffffff, 0xffe27a], gravity: 120 }, + ore: { key: 'catan-p-spark', tint: [0xffffff, 0xcfe0ff], gravity: 60 }, + brick: { key: 'catan-p-dust', tint: [0xffffff, 0xe08a5a], gravity: 40 }, +}; + +// Bake everything the scene needs up front (the frame is baked per board). +export function prepareCatanArt(scene, playerColors) { + bakeTable(scene, { planks: true }); + bakeTable(scene, { planks: false }); + bakeRail(scene); + bakeCaddy(scene); + bakeTray(scene); + bakePlaque(scene); + bakeCostCard(scene); + bakeHisto(scene); + bakeChit(scene); + bakeHarbourBoat(scene); + bakeParticles(scene); + playerColors.forEach((pc, ci) => { + bakeSettlement(scene, ci, pc.hex); + bakeCity(scene, ci, pc.hex); + bakeRoad(scene, ci, pc.hex); + bakeShip(scene, ci, pc.hex); + }); +} + +export const PAD = { caddy: 20, tray: 20, plaque: 18, costcard: 14, histo: 14, rail: 24 }; diff --git a/src/games/catan/CatanBoards.js b/src/games/catan/CatanBoards.js new file mode 100644 index 0000000..7163b21 --- /dev/null +++ b/src/games/catan/CatanBoards.js @@ -0,0 +1,164 @@ +// CatanBoards.js — the opponents' wooden player boards (left column) and the +// human's pieces-left strip on the rail. +// +// Each opponent board shows: portrait + VP badge + name, a face-down resource +// fan with a count (red when they risk discarding on a 7), dev cards, the +// pieces they still hold (road / settlement / city, plus ships in Seafarers), +// their longest road and knights, and any Longest Road / Largest Army card. + +import { createOpponentPortrait } from '../../ui/Portrait.js'; +import { PLAYER_COLORS } from './CatanBoard.js'; +import * as L from './CatanLogic.js'; +import { oppBoardRects, oppBoardAnchors, HUMAN_INFO } from './CatanLayout.js'; +import { PAD } from './CatanArt.js'; + +const MINI = { road: { w: 30, h: 9 }, set: { w: 26, h: 26 }, city: { w: 32, h: 32 }, ship: { w: 26, h: 26 } }; + +export class CatanBoards { + constructor(scene, depth, { opponents, cardBackFrame, pname }) { + this.scene = scene; + this.depth = depth; + this.opponents = opponents; + this.cardBackFrame = cardBackFrame; + this.pname = pname; + this.panels = []; + this.portraits = []; + } + + // Build once the player count is known. + build(gs) { + const s = this.scene; + const seats = []; + for (let seat = 1; seat < gs.playerCount; seat++) seats.push(seat); + const rects = oppBoardRects(seats.length); + seats.forEach((seat, i) => { + const r = rects[i]; + const a = oppBoardAnchors(r); + const col = PLAYER_COLORS[gs.players[seat].colorIndex]; + s.add.image(r.x - PAD.plaque, r.y - PAD.plaque, 'catan-plaque').setOrigin(0, 0).setDepth(this.depth - 1); + // colour strip along the top edge + const strip = s.add.graphics().setDepth(this.depth - 0.5); + strip.fillStyle(col.hex, 1); strip.fillRoundedRect(r.x + 18, r.y + 4, r.w - 36, 6, 3); + strip.fillStyle(0xffffff, 0.25); strip.fillRect(r.x + 22, r.y + 5, r.w - 44, 1.5); + // active-turn glow + const glow = s.add.graphics().setDepth(this.depth - 0.6).setAlpha(0); + glow.lineStyle(5, 0xffd34d, 1); glow.strokeRoundedRect(r.x - 5, r.y - 5, r.w + 10, r.h + 10, 19); + const glowTween = s.tweens.add({ targets: glow, alpha: { from: 0.35, to: 1 }, duration: 750, yoyo: true, repeat: -1, paused: true }); + + const opp = this.opponents[seat - 1]; + const portrait = createOpponentPortrait(s, opp, a.portrait.x, a.portrait.y, a.portrait.r, this.depth); + this.portraits[seat] = portrait; + s.add.circle(a.portrait.x, a.portrait.y, a.portrait.r + 5, col.hex, 0).setStrokeStyle(4, col.hex, 0.95).setDepth(this.depth + 4); + s.add.text(a.name.x, a.name.y, this.pname(seat), { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: '#f6ead0', + wordWrap: { width: 150 }, align: 'center', stroke: '#2a160a', strokeThickness: 3, + }).setOrigin(0.5, 0).setDepth(this.depth + 1); + + const vpG = s.add.graphics().setDepth(this.depth + 5); + const vpT = s.add.text(a.vp.x, a.vp.y, '0', { + fontFamily: 'Righteous', fontSize: '18px', color: col.key === 'white' ? '#000000' : '#ffffff', + }).setOrigin(0.5).setDepth(this.depth + 6); + const cardCount = s.add.text(0, a.cards.y, '', { + fontFamily: 'Righteous', fontSize: '20px', color: '#ffe7a8', stroke: '#1a0d04', strokeThickness: 4, + }).setOrigin(0, 0.5).setDepth(this.depth + 3); + const devCount = s.add.text(0, a.dev.y, '', { + fontFamily: 'Righteous', fontSize: '18px', color: '#e8d8b0', stroke: '#1a0d04', strokeThickness: 4, + }).setOrigin(0, 0.5).setDepth(this.depth + 3); + const stats = s.add.text(a.stats.x, a.stats.y, '', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f0e2c0', + }).setOrigin(0, 0.5).setDepth(this.depth + 1); + const pieces = this.buildPieceStrip(gs, seat, a.pieces.x, a.pieces.y); + this.panels.push({ + seat, rect: r, anchors: a, x: a.portrait.x, y: a.portrait.y, glow, glowTween, + vpG, vpT, cardCount, devCount, stats, pieces, cardFan: [], devFan: [], + }); + }); + // the human's pieces-left strip on the rail + this.humanPieces = this.buildPieceStrip(gs, 0, HUMAN_INFO.x + 4, HUMAN_INFO.y + 40, true); + this.update(gs); + return this; + } + + buildPieceStrip(gs, seat, x, y, compact = false) { + const s = this.scene; + const ci = gs.players[seat].colorIndex; + const kinds = [['road', `catan-road-${ci}`, MINI.road], ['settlement', `catan-set-${ci}`, MINI.set], ['city', `catan-city-${ci}`, MINI.city]]; + if (gs.expansion === 'seafarers') kinds.push(['ship', `catan-ship-${ci}`, MINI.ship]); + const step = compact ? (kinds.length > 3 ? 40 : 54) : (kinds.length > 3 ? 66 : 86); + const out = {}; + kinds.forEach(([k, tex, sz], i) => { + const ix = x + i * step + sz.w / 2; + s.add.image(ix, y, tex).setDisplaySize(sz.w, sz.h).setDepth(this.depth + 2); + out[k] = s.add.text(ix + sz.w / 2 + 2, y + 2, '', { + fontFamily: 'Righteous', fontSize: compact ? '16px' : '17px', color: '#f6ead0', stroke: '#1a0d04', strokeThickness: 3, + }).setOrigin(0, 0.5).setDepth(this.depth + 3); + }); + return out; + } + + setPieceStrip(strip, left) { + for (const k of Object.keys(strip)) { + const n = left[k]; + strip[k].setText(`×${n}`).setColor(n === 0 ? '#ff8a7a' : '#f6ead0'); + } + } + + panelFor(seat) { return this.panels.find((p) => p.seat === seat); } + + update(gs) { + const s = this.scene; + for (const panel of this.panels) { + const p = gs.players[panel.seat]; + const a = panel.anchors; + const col = PLAYER_COLORS[p.colorIndex]; + // VP badge + const vp = L.publicVictoryPoints(gs, panel.seat); + panel.vpG.clear(); + panel.vpG.fillStyle(0x000000, 0.35); panel.vpG.fillCircle(a.vp.x + 1, a.vp.y + 2, 20); + panel.vpG.fillStyle(col.hexDark, 1); panel.vpG.fillCircle(a.vp.x, a.vp.y, 19); + panel.vpG.lineStyle(2.5, 0xffd34d, 0.95); panel.vpG.strokeCircle(a.vp.x, a.vp.y, 19); + panel.vpT.setText(String(vp)); + + // face-down resource fan + panel.cardFan.forEach((o) => o.destroy()); + panel.cardFan = []; + const cards = L.handSize(p); + const show = Math.min(cards, 10); + const step = 17; + for (let i = 0; i < show; i++) { + const img = s.add.image(a.cards.x + i * step, a.cards.y, 'cardbacks', this.cardBackFrame) + .setDisplaySize(32, 46).setAngle((i - (show - 1) / 2) * 2).setDepth(this.depth + 1 + i * 0.01); + panel.cardFan.push(img); + } + const risk = cards > 7; + panel.cardCount.setText(cards ? `${cards}${risk ? ' !' : ''}` : 'no cards') + .setColor(risk ? '#ff8a7a' : (cards ? '#ffe7a8' : '#b89f78')) + .setX(a.cards.x + Math.max(0, show - 1) * step + (show ? 26 : -12)); + + // dev cards (face-down dev back) + panel.devFan.forEach((o) => o.destroy()); + panel.devFan = []; + const devTotal = p.devCards.length + p.newDevCards.length + (p.vpCards ?? 0); + const dshow = Math.min(devTotal, 6); + for (let i = 0; i < dshow; i++) { + panel.devFan.push(s.add.image(a.dev.x + i * 15, a.dev.y, 'catan-cards', 8).setDisplaySize(30, 43).setDepth(this.depth + 1 + i * 0.01)); + } + panel.devCount.setText(devTotal ? `${devTotal} dev` : 'no dev').setColor(devTotal ? '#e8d8b0' : '#b89f78') + .setX(a.dev.x + Math.max(0, dshow - 1) * 15 + (dshow ? 24 : -12)); + + this.setPieceStrip(panel.pieces, L.piecesLeft(gs, panel.seat)); + const road = L.longestRoadFor(gs, panel.seat); + panel.stats.setText(`Road ${road} · Knights ${p.knightsPlayed}`); + } + if (this.humanPieces) this.setPieceStrip(this.humanPieces, L.piecesLeft(gs, 0)); + } + + setActive(seat) { + for (const panel of this.panels) { + const on = panel.seat === seat; + if (on && panel.glowTween.isPaused()) panel.glowTween.resume(); + if (!on) { panel.glowTween.pause(); panel.glow.setAlpha(0); } + } + } +} + diff --git a/src/games/catan/CatanCaddy.js b/src/games/catan/CatanCaddy.js new file mode 100644 index 0000000..d38864b --- /dev/null +++ b/src/games/catan/CatanCaddy.js @@ -0,0 +1,153 @@ +// CatanCaddy.js — the bank's wooden card caddy. +// +// Six recessed wells (five resources + the development deck). Each well holds a +// real stack: card-edge layers whose thickness tracks the count, with the top +// card lying face-up (the dev deck face-down). A brass plaque shows the count. +// Low stacks (≤3) glow amber; an empty well shows its bare felt. Card flights +// read topOf(key) so cards visibly leave from — and land on — the top card. + +import * as Phaser from 'phaser'; +import { RESOURCE_INFO, RESOURCE_TYPES } from './CatanBoard.js'; +import { + CADDY, CADDY_CARD, CADDY_SLOTS, caddySlot, stackLayers, stackTop, STACK_STEP, +} from './CatanLayout.js'; +import { PAD } from './CatanArt.js'; + +const CARD_FRAME = { brick: 0, lumber: 1, wool: 2, grain: 3, ore: 4, dev: 8 }; + +export class CatanCaddy { + constructor(scene, depth, { onHover, onHoverOut } = {}) { + this.scene = scene; + this.depth = depth; + this.onHover = onHover; + this.onHoverOut = onHoverOut; + this.counts = {}; + this.slots = {}; + } + + build() { + const s = this.scene; + s.add.image(CADDY.x - PAD.caddy, CADDY.y - PAD.caddy, 'catan-caddy').setOrigin(0, 0).setDepth(this.depth); + CADDY_SLOTS.forEach((key, i) => { + const slot = caddySlot(i); + const edges = s.add.graphics().setDepth(this.depth + 1); + const glow = s.add.graphics().setDepth(this.depth + 0.5).setAlpha(0); + const empty = s.add.text(slot.card.x, slot.card.y, 'EMPTY', { + fontFamily: 'Righteous', fontSize: '18px', color: '#8a6a44', + }).setOrigin(0.5).setAlpha(0).setDepth(this.depth + 1); + const top = this.makeCard(key).setDepth(this.depth + 2); + top.setPosition(slot.card.x, slot.card.y); + const plaque = s.add.text(slot.plaque.x, slot.plaque.y + 1, '0', { + fontFamily: 'Righteous', fontSize: '22px', color: '#3a2408', + }).setOrigin(0.5).setDepth(this.depth + 2); + // hover / drop zone over the well and plaque + const zone = s.add.zone(slot.x + (CADDY.w - 28) / 2, slot.y + slot.h / 2, CADDY.w - 28, slot.h) + .setInteractive({ useHandCursor: false }).setDepth(this.depth + 3); + zone.on('pointerover', () => this.onHover?.(key, slot)); + zone.on('pointerout', () => this.onHoverOut?.(key)); + const pulse = s.tweens.add({ targets: glow, alpha: { from: 0.25, to: 0.9 }, duration: 700, yoyo: true, repeat: -1, paused: true }); + this.slots[key] = { i, slot, edges, glow, empty, top, plaque, zone, pulse, drop: null }; + this.counts[key] = -1; + }); + return this; + } + + // A landscape card: dark backing, the art rotated -90°, a coloured border. + makeCard(key) { + const s = this.scene; + const { w, h } = CADDY_CARD; + const bg = s.add.graphics(); + bg.fillStyle(0x111111, 0.95); bg.fillRoundedRect(-w / 2, -h / 2, w, h, 6); + const img = s.add.image(0, 0, 'catan-cards', CARD_FRAME[key]).setDisplaySize(h - 9, w - 9).setAngle(-90); + const border = s.add.graphics(); + border.lineStyle(3, key === 'dev' ? 0xc9a24a : RESOURCE_INFO[key].swatch, 1); + border.strokeRoundedRect(-w / 2, -h / 2, w, h, 6); + const sheen = s.add.graphics(); + sheen.fillStyle(0xffffff, 0.08); sheen.fillRoundedRect(-w / 2 + 4, -h / 2 + 3, w - 8, h * 0.28, 4); + return s.add.container(0, 0, [bg, img, border, sheen]); + } + + keyIndex(key) { return CADDY_SLOTS.indexOf(key); } + + topOf(key) { + const i = this.keyIndex(key); + if (i < 0) return { x: CADDY.x + CADDY.w / 2, y: CADDY.y + CADDY.h / 2 }; + return stackTop(i, Math.max(1, this.counts[key] ?? 1)); + } + + setCounts(bank, devCount) { + for (const r of RESOURCE_TYPES) this.setCount(r, bank[r]); + this.setCount('dev', devCount); + } + + // Adjust one well by `delta` (used while cards are in flight so stacks + // shrink/grow per card, ahead of the next full setCounts()). + nudge(key, delta) { this.setCount(key, Math.max(0, (this.counts[key] ?? 0) + delta)); } + + setCount(key, n) { + const sl = this.slots[key]; + if (!sl || this.counts[key] === n) return; + this.counts[key] = n; + const { slot } = sl; + const layers = stackLayers(n); + const { w, h } = CADDY_CARD; + const g = sl.edges; + g.clear(); + for (let j = 0; j < layers; j++) { + const cx = slot.card.x - j * STACK_STEP.dx, cy = slot.card.y - j * STACK_STEP.dy; + g.fillStyle(j % 3 === 0 ? 0xcdbf9f : 0xe9dcbc, 1); + g.fillRoundedRect(cx - w / 2, cy - h / 2, w, h, 6); + g.lineStyle(1, 0x6b5a3a, 0.55); + g.strokeRoundedRect(cx - w / 2, cy - h / 2, w, h, 6); + } + const top = stackTop(sl.i, Math.max(1, n)); + sl.top.setPosition(top.x, top.y).setVisible(n > 0); + sl.empty.setAlpha(n > 0 ? 0 : 0.8); + sl.plaque.setText(String(n)).setColor(n === 0 ? '#7a1d12' : '#3a2408'); + // amber warning on a low stack + const low = n > 0 && n <= 3; + sl.glow.clear(); + if (low || n === 0) { + sl.glow.lineStyle(4, n === 0 ? 0xc0392b : 0xf0a020, 1); + sl.glow.strokeRoundedRect(slot.x - 3, slot.y - 3, slot.w + 6, slot.h + 6, 11); + if (sl.pulse.isPaused()) sl.pulse.resume(); + } else { + sl.pulse.pause(); + sl.glow.setAlpha(0); + } + } + + // A soft settle on the top card when one lands or leaves. + bump(key) { + const sl = this.slots[key]; + if (!sl) return; + this.scene.tweens.add({ targets: sl.top, scaleX: 1.05, scaleY: 1.05, duration: 70, yoyo: true }); + this.scene.tweens.add({ targets: sl.plaque, scale: 1.25, duration: 90, yoyo: true }); + } + + // Which well (resource key) is under a screen point, or null. + slotAt(x, y) { + for (const key of CADDY_SLOTS) { + const { slot } = this.slots[key]; + if (x >= CADDY.x && x <= CADDY.x + CADDY.w && y >= slot.y - 6 && y <= slot.y + slot.h + 6) return key; + } + if (Phaser.Geom.Rectangle.Contains(new Phaser.Geom.Rectangle(CADDY.x, CADDY.y, CADDY.w, CADDY.h), x, y)) return 'caddy'; + return null; + } + + // Highlight the whole caddy as a drop target (drag-to-bank trading). + setDropHint(on) { + if (on && !this._drop) { + const g = this.scene.add.graphics().setDepth(this.depth + 4); + g.lineStyle(4, 0xffd34d, 1); + g.strokeRoundedRect(CADDY.x - 4, CADDY.y - 4, CADDY.w + 8, CADDY.h + 8, 16); + this._drop = g; + this._dropTween = this.scene.tweens.add({ targets: g, alpha: { from: 1, to: 0.35 }, duration: 500, yoyo: true, repeat: -1 }); + } else if (!on && this._drop) { + this._dropTween?.remove(); + this._drop.destroy(); + this._drop = null; + } + } +} + diff --git a/src/games/catan/CatanEndScreen.js b/src/games/catan/CatanEndScreen.js new file mode 100644 index 0000000..9fa69e0 --- /dev/null +++ b/src/games/catan/CatanEndScreen.js @@ -0,0 +1,225 @@ +// CatanEndScreen.js — the end of a game. +// +// 1. Reveal: every hidden Victory Point card flips face-up over its owner's +// board, so the final scores make sense. +// 2. Scoreboard: settlements, cities, Longest Road, Largest Army, VP cards and +// any island bonus per player, the winner's row gilded. +// 3. Two charts: the dice (how often each total came up vs the odds) and +// production (what each player collected, plus robber/steal/trade counts). + +import * as Phaser from 'phaser'; +import { Button } from '../../ui/Button.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { RESOURCE_INFO, RESOURCE_TYPES, PLAYER_COLORS } from './CatanBoard.js'; +import * as L from './CatanLogic.js'; + +const PX = 960, PY = 540, PW = 1260, PH = 840; + +export async function showCatanEndScreen(scene, { depth, onPlayAgain, onLeave, revealAt }) { + const gs = scene.gs; + const winner = gs.winner; + const isHuman = winner === 0; + + // ── 1. reveal hidden VP cards ───────────────────────────────────────────── + const reveals = []; + for (let seat = 0; seat < gs.playerCount; seat++) { + const n = gs.players[seat].vpCards ?? 0; + if (!n) continue; + const at = revealAt(seat); + for (let i = 0; i < n; i++) { + const c = scene.makeCardSprite({ kind: 'devback' }).setPosition(at.x + i * 26, at.y).setDepth(depth + 2).setScale(0.2).setAlpha(0); + reveals.push(c); + scene.tweens.add({ targets: c, scale: 1.1, alpha: 1, duration: 260, delay: 300 * reveals.length, ease: 'Back.Out' }); + scene.time.delayedCall(300 * reveals.length + 420, () => { + scene.tweens.add({ + targets: c, scaleX: 0, duration: 120, + onComplete: () => { c.paint({ kind: 'dev', type: 'vp' }); scene.tweens.add({ targets: c, scaleX: 1.1, duration: 120 }); }, + }); + }); + } + const label = scene.add.text(at.x, at.y - 70, `+${n} VP`, { + fontFamily: 'Righteous', fontSize: '30px', color: '#ffd34d', stroke: '#1a0d04', strokeThickness: 5, + }).setOrigin(0.5).setDepth(depth + 3).setAlpha(0); + reveals.push(label); + scene.tweens.add({ targets: label, alpha: 1, y: at.y - 90, duration: 400, delay: 300 * reveals.length + 300 }); + } + if (reveals.length) await new Promise((r) => scene.time.delayedCall(300 * reveals.length + 1300, r)); + reveals.forEach((o) => scene.tweens.add({ targets: o, alpha: 0, duration: 300, onComplete: () => o.destroy() })); + + // portraits are DOM elements over the canvas: tuck the table's away + scene.opponentPortraits.forEach((p) => p?.hide?.()); + scene.humanPortrait?.hide?.(); + + // ── 2. panel + scoreboard ───────────────────────────────────────────────── + const objs = []; + const add = (o) => { objs.push(o); return o; }; + add(scene.add.rectangle(PX, PY, 1920, 1080, 0x000000, 0.55).setInteractive().setDepth(depth)); + const g = add(scene.add.graphics().setDepth(depth + 1)); + g.fillStyle(0x000000, 0.45); g.fillRoundedRect(PX - PW / 2 + 6, PY - PH / 2 + 10, PW, PH, 18); + g.fillStyle(0x24160b, 0.98); g.fillRoundedRect(PX - PW / 2, PY - PH / 2, PW, PH, 18); + g.lineStyle(3, 0xc9a24a, 1); g.strokeRoundedRect(PX - PW / 2, PY - PH / 2, PW, PH, 18); + g.lineStyle(1, 0xc9a24a, 0.45); g.strokeRoundedRect(PX - PW / 2 + 8, PY - PH / 2 + 8, PW - 16, PH - 16, 13); + + const top = PY - PH / 2; + add(scene.add.text(PX + 70, top + 52, isHuman ? 'Victory!' : `${L.playerName(gs, winner)} wins`, { + fontFamily: 'Righteous', fontSize: '46px', color: isHuman ? '#ffd34d' : '#f2ead8', + }).setOrigin(0.5).setDepth(depth + 2)); + const rolled = gs.stats?.rolls?.reduce((a, b) => a + b, 0) ?? 0; + add(scene.add.text(PX + 70, top + 96, `Reached ${L.winVpFor(gs)} victory points after ${rolled} rolls`, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#cbb994', + }).setOrigin(0.5).setDepth(depth + 2)); + + // winner portrait + const wx = PX - PW / 2 + 130, wy = top + 150; + const ring = add(scene.add.graphics().setDepth(depth + 2)); + ring.fillStyle(0x111111, 1); ring.fillCircle(wx, wy, 86); + ring.lineStyle(5, PLAYER_COLORS[gs.players[winner].colorIndex].hex, 1); ring.strokeCircle(wx, wy, 86); + let portrait = null; + if (isHuman) portrait = createPlayerPortrait(scene, wx, wy, 80, depth + 3, 'CatanGame'); + else { + portrait = createOpponentPortrait(scene, scene.opponents[winner - 1], wx, wy, 80, depth + 3, { playIntro: false }); + portrait?.playEmotion?.('happy'); + } + + // fireworks + const fw = scene.add.particles(PX, PY, 'catanParticle', { + speed: { min: 80, max: 480 }, lifespan: 1400, + scale: { start: 1.2, end: 0 }, alpha: { start: 1, end: 0 }, + quantity: 3, frequency: 35, + tint: [0xffd700, 0xff6644, 0xffffff, 0x44aaff, 0xff44aa, 0x88ff44], + angle: { min: 0, max: 360 }, + emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(-PW / 2, -PH / 2, PW, PH) }, + }).setDepth(depth + 8); + scene.time.delayedCall(3200, () => { fw.stop(); scene.time.delayedCall(1400, () => fw.destroy()); }); + + const cols = [ + { k: 'name', label: 'Player', x: 0, w: 230, align: 0 }, + { k: 'settle', label: 'Settlements', x: 250 }, + { k: 'city', label: 'Cities', x: 360 }, + { k: 'lr', label: 'Long Road', x: 460 }, + { k: 'la', label: 'Army', x: 560 }, + { k: 'vp', label: 'VP cards', x: 650 }, + { k: 'bonus', label: 'Island', x: 745 }, + { k: 'total', label: 'Total', x: 840 }, + ]; + const tx = PX - PW / 2 + 260, ty = top + 140, rowH = 44; + cols.forEach((c) => add(scene.add.text(tx + c.x + (c.align === 0 ? 0 : 30), ty, c.label, { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#cbb994', + }).setOrigin(c.align === 0 ? 0 : 0.5, 0.5).setDepth(depth + 2))); + const order = [...Array(gs.playerCount).keys()].sort((a, b) => L.victoryPoints(gs, b) - L.victoryPoints(gs, a)); + order.forEach((seat, i) => { + const p = gs.players[seat]; + const y = ty + 34 + i * rowH; + const col = PLAYER_COLORS[p.colorIndex]; + const rg = add(scene.add.graphics().setDepth(depth + 1.5)); + if (seat === winner) { rg.fillStyle(0xc9a24a, 0.28); rg.fillRoundedRect(tx - 14, y - rowH / 2 + 3, 920, rowH - 6, 8); rg.lineStyle(2, 0xffd34d, 0.9); rg.strokeRoundedRect(tx - 14, y - rowH / 2 + 3, 920, rowH - 6, 8); } + else { rg.fillStyle(0xffffff, i % 2 ? 0.03 : 0.06); rg.fillRoundedRect(tx - 14, y - rowH / 2 + 3, 920, rowH - 6, 8); } + rg.fillStyle(col.hex, 1); rg.fillCircle(tx, y, 8); + const total = L.victoryPoints(gs, seat); + const base = p.settlements.length + p.cities.length * 2 + (p.vpCards ?? 0) + + (gs.longestRoad.owner === seat ? 2 : 0) + (gs.largestArmy.owner === seat ? 2 : 0); + const vals = { + name: L.playerName(gs, seat), settle: p.settlements.length, city: `${p.cities.length} (${p.cities.length * 2})`, + lr: gs.longestRoad.owner === seat ? '2' : '—', la: gs.largestArmy.owner === seat ? '2' : '—', + vp: p.vpCards || '—', bonus: total - base || '—', total, + }; + cols.forEach((c) => add(scene.add.text(tx + c.x + (c.align === 0 ? 18 : 30), y, String(vals[c.k]), { + fontFamily: c.k === 'total' || c.k === 'name' ? 'Righteous' : '"Julius Sans One"', + fontSize: c.k === 'total' ? '24px' : '18px', + color: c.k === 'total' ? (seat === winner ? '#ffd34d' : '#f2ead8') : '#f2ead8', + }).setOrigin(c.align === 0 ? 0 : 0.5, 0.5).setDepth(depth + 2))); + }); + + // ── 3. charts ───────────────────────────────────────────────────────────── + const chartTop = ty + 34 + 4 * rowH + 10; + const chart = { x: PX - PW / 2 + 60, y: chartTop + 40, w: PW - 120, h: PY + PH / 2 - 96 - (chartTop + 40) }; + const chartObjs = []; + const clearChart = () => { chartObjs.forEach((o) => o.destroy()); chartObjs.length = 0; }; + const cadd = (o) => { chartObjs.push(o); return o; }; + + const drawDice = () => { + clearChart(); + const rolls = gs.stats?.rolls ?? Array(13).fill(0); + const total = rolls.reduce((a, b) => a + b, 0); + const ways = (n) => 6 - Math.abs(7 - n); + let max = 1; + for (let n = 2; n <= 12; n++) max = Math.max(max, rolls[n], total * ways(n) / 36); + const cg = cadd(scene.add.graphics().setDepth(depth + 2)); + const bw = 46, pitch = chart.w / 11, base = chart.y + chart.h - 26, hMax = chart.h - 60; + cg.lineStyle(1.5, 0xcbb994, 0.6); cg.lineBetween(chart.x, base, chart.x + chart.w, base); + for (let n = 2; n <= 12; n++) { + const x = chart.x + pitch * (n - 2) + pitch / 2; + const h = (rolls[n] / max) * hMax; + const hot = n === 6 || n === 8; + cg.fillStyle(n === 7 ? 0x8f9a96 : (hot ? 0xd0553f : 0xe6cf98), 1); + cg.fillRoundedRect(x - bw / 2, base - h, bw, h, { tl: 5, tr: 5, bl: 0, br: 0 }); + const eh = (total * ways(n) / 36 / max) * hMax; + cg.lineStyle(3, 0x7fd0ff, 0.9); cg.lineBetween(x - bw / 2 - 6, base - eh, x + bw / 2 + 6, base - eh); + cadd(scene.add.text(x, base + 6, String(n), { fontFamily: 'Righteous', fontSize: '18px', color: hot ? '#ff9b8a' : '#f2ead8' }).setOrigin(0.5, 0).setDepth(depth + 2)); + if (rolls[n]) cadd(scene.add.text(x, base - h - 4, String(rolls[n]), { fontFamily: 'Righteous', fontSize: '16px', color: '#f2ead8' }).setOrigin(0.5, 1).setDepth(depth + 2)); + } + cadd(scene.add.text(chart.x + chart.w, chart.y - 6, '▬ expected by the odds', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#7fd0ff', + }).setOrigin(1, 0).setDepth(depth + 2)); + }; + + const drawProduction = () => { + clearChart(); + const st = gs.stats; + if (!st) return; + const n = gs.playerCount; + const rowGap = Math.min(70, (chart.h - 10) / n); + let max = 1; + for (let s = 0; s < n; s++) max = Math.max(max, RESOURCE_TYPES.reduce((t, r) => t + st.produced[s][r], 0)); + const barX = chart.x + 200, barW = chart.w - 200 - 360; + const cg = cadd(scene.add.graphics().setDepth(depth + 2)); + for (let s = 0; s < n; s++) { + const y = chart.y + 14 + s * rowGap; + const col = PLAYER_COLORS[gs.players[s].colorIndex]; + cg.fillStyle(col.hex, 1); cg.fillCircle(chart.x + 8, y + 12, 7); + cadd(scene.add.text(chart.x + 22, y + 12, L.playerName(gs, s), { fontFamily: 'Righteous', fontSize: '18px', color: '#f2ead8' }).setOrigin(0, 0.5).setDepth(depth + 2)); + let x = barX; + let tot = 0; + for (const r of RESOURCE_TYPES) { + const v = st.produced[s][r]; + tot += v; + const w = (v / max) * barW; + if (w <= 0) continue; + cg.fillStyle(RESOURCE_INFO[r].swatch, 1); cg.fillRect(x, y, w, 24); + if (w > 22) cadd(scene.add.text(x + w / 2, y + 12, String(v), { fontFamily: 'Righteous', fontSize: '13px', color: '#1a0d04' }).setOrigin(0.5).setDepth(depth + 2)); + x += w; + } + cadd(scene.add.text(x + 8, y + 12, `${tot}`, { fontFamily: 'Righteous', fontSize: '18px', color: '#ffe7a8' }).setOrigin(0, 0.5).setDepth(depth + 2)); + const extra = [ + `robber blocked ${st.blocked[s]}`, `stole ${st.stolen[s]}`, `lost ${st.lostToSteal[s] + st.discarded[s]}`, `trades ${st.trades[s]}`, + ].join(' · '); + cadd(scene.add.text(chart.x + chart.w, y + 12, extra, { fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#cbb994' }).setOrigin(1, 0.5).setDepth(depth + 2)); + } + // legend + let lx = barX; + for (const r of RESOURCE_TYPES) { + cg.fillStyle(RESOURCE_INFO[r].swatch, 1); cg.fillRect(lx, chart.y - 18, 12, 12); + const t = cadd(scene.add.text(lx + 16, chart.y - 12, RESOURCE_INFO[r].label, { fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#cbb994' }).setOrigin(0, 0.5).setDepth(depth + 2)); + lx += 22 + t.width + 14; + } + }; + + const tabY = chartTop + 6; + const tabs = {}; + const select = (k) => { + for (const [key, b] of Object.entries(tabs)) b.setAlpha(key === k ? 1 : 0.55); + if (k === 'dice') drawDice(); else drawProduction(); + }; + tabs.dice = add(new Button(scene, PX - 110, tabY, 'Dice', () => select('dice'), { width: 200, height: 40, fontSize: 18 }).setDepth(depth + 2)); + tabs.prod = add(new Button(scene, PX + 110, tabY, 'Production', () => select('prod'), { width: 200, height: 40, fontSize: 18 }).setDepth(depth + 2)); + select('dice'); + + const by = PY + PH / 2 - 44; + const cleanup = () => { + clearChart(); + objs.forEach((o) => o.destroy()); + portrait?.destroy?.(); + }; + add(new Button(scene, PX - 120, by, 'Play Again', () => { cleanup(); onPlayAgain(); }, { width: 210, fontSize: 22 }).setDepth(depth + 2)); + add(new Button(scene, PX + 120, by, 'Leave', () => { cleanup(); onLeave(); }, { variant: 'ghost', width: 210, fontSize: 22 }).setDepth(depth + 2)); +} diff --git a/src/games/catan/CatanGame.js b/src/games/catan/CatanGame.js index 392849e..6cd6d0c 100644 --- a/src/games/catan/CatanGame.js +++ b/src/games/catan/CatanGame.js @@ -3,7 +3,7 @@ import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { createPlayerPortrait } from '../../ui/Portrait.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { enqueue as enqueueSpeech } from '../../ui/SpeechQueue.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; @@ -13,13 +13,36 @@ import { } from './CatanBoard.js'; import * as L from './CatanLogic.js'; import * as AI from './CatanAI.js'; +import { prepareCatanArt, bakeFrame, PARTICLE_FOR, PAD } from './CatanArt.js'; +import { CatanCaddy } from './CatanCaddy.js'; +import { CatanTray } from './CatanTray.js'; +import { CatanBoards } from './CatanBoards.js'; +import { showCatanEndScreen } from './CatanEndScreen.js'; +import { + RAIL, LEAVE, STATUS, LOG, PORTRAIT, HAND, HAND_CARD, DEV, HUMAN_INFO, HISTO, COSTCARD, + AWARDS, AWARD_CARD, awardHome, humanAwardPos, oppAwardPos, buttonCenter, BUTTONS, + handGroups, handPilePos, pileCardPose, handPileIndexAt, devCardPos, +} from './CatanLayout.js'; -const D = { board: 0, port: 4, chit: 8, robber: 11, road: 12, building: 14, highlight: 20, hud: 30, panel: 60, banner: 80 }; +// Depth bands. Buildings add y/10000 so nearer pieces draw over farther ones. +const D = { + table: -4, frame: -2, glint: -1.5, board: 0, port: 4, chit: 8, robberDim: 9, robber: 11, + road: 12, building: 14, fx: 17, highlight: 20, hud: 30, flight: 70, panel: 60, banner: 80, +}; + +const DEV_VISUAL = { + knight: { frame: 5, border: 0xb03030 }, + roadBuilding: { frame: 6, border: 0x8b5a2b }, + vp: { frame: 7, border: 0xdaa520 }, + monopoly: { frame: 9, border: 0x7b2d8b }, + yearOfPlenty: { frame: 10, border: 0x2d8b57 }, +}; export default class CatanGame extends Phaser.Scene { constructor() { super('CatanGame'); } init(data) { + this.initData = data; this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; @@ -30,30 +53,39 @@ export default class CatanGame extends Phaser.Scene { this.gs = null; this.busy = false; this.highlights = []; - this.pieceObjs = []; + this.pieceSprites = new Map(); this.chitObjs = []; this.robberObj = null; - this.opponentPortraits = []; this.buttons = {}; - this.placeMode = null; // 'road' | 'settlement' | 'city' | null - this.handDisplay = []; - this.handCardObjs = []; - this.handSelectedIdx = null; + this.placeMode = null; // 'road' | 'settlement' | 'city' | 'ship' | null + this.handOrder = [...RESOURCE_TYPES]; + this.handPiles = []; + this.boards = null; + this.glints = 0; } + // Opponent portraits live on the player boards. + get opponentPortraits() { return this.boards?.portraits ?? []; } + get oppPanels() { return this.boards?.panels ?? []; } + create() { new MusicPlayer(this, this.cache.json.get('music').tracks); + prepareCatanArt(this, PLAYER_COLORS); + this.input.dragDistanceThreshold = 6; this.buildParticleTexture(); this.buildPlayfield(); this.buildBoardStatic(); - this.buildDice(); this.buildHUD(); - this.buildBankPanel(); - this.buildOpponentPanels(); + this.caddy = new CatanCaddy(this, D.hud - 1, { + onHover: (key, slot) => this.showCaddyTooltip(key, slot), + onHoverOut: () => this.hideInfoTooltip(), + }).build(); + this.tray = new CatanTray(this, D.hud - 1, { onClick: () => this.onRoll() }).build(); this.startNewMatch(); } buildParticleTexture() { + if (this.textures.exists('catanParticle')) return; const g = this.make.graphics({ x: 0, y: 0, add: false }); g.fillStyle(0xffffff, 1); g.fillCircle(5, 5, 5); g.generateTexture('catanParticle', 10, 10); @@ -63,6 +95,7 @@ export default class CatanGame extends Phaser.Scene { // ── coordinate helpers ────────────────────────────────────────────────────── // Active board geometry (base island, or the selected Seafarers scenario). get geo() { return L.geoFor(this.gs); } + get pieceK() { return (this.geo.size ?? HEX_SIZE) / HEX_SIZE; } nodePos(id) { const n = this.geo.nodes[id]; return { x: n.x, y: n.y }; } edgePos(id) { const [a, b] = this.geo.edges[id].nodes; @@ -70,42 +103,62 @@ export default class CatanGame extends Phaser.Scene { return { x: (N[a].x + N[b].x) / 2, y: (N[a].y + N[b].y) / 2 }; } hexPos(id) { const h = this.geo.hexes[id]; return { x: h.cx, y: h.cy }; } + hexPoints(id, s = 1) { + const { x, y } = this.hexPos(id); + return this.geo.hexes[id].corners.map((c) => { + const n = this.geo.nodes[c]; + return { x: x + (n.x - x) * s, y: y + (n.y - y) * s }; + }); + } playerColor(seat) { return PLAYER_COLORS[this.gs.players[seat].colorIndex]; } pname(seat) { return L.playerName(this.gs, seat); } - // ── playfield / static board ───────────────────────────────────────────────── + // ── table / static board ───────────────────────────────────────────────────── buildPlayfield() { 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(D.board - 2); + // A chosen playfield becomes the tablecloth; the lamp light still falls on it. + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.table - 1); + this.add.image(0, 0, 'catan-table-light').setOrigin(0, 0).setDepth(D.table); } else { - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x14506b).setDepth(D.board - 2); + this.add.image(0, 0, 'catan-table').setOrigin(0, 0).setDepth(D.table); } - // Sea backdrop — radial gradient via concentric circles, dark outer to lighter inner. - const SEA_X = 1000, SEA_Y = 470, SEA_R = 470; - const sea = this.add.graphics().setDepth(D.board - 1); - const STEPS = 20; - for (let i = STEPS; i >= 0; i--) { - const t = i / STEPS; - const r = Math.round(SEA_R * (i / STEPS)); - // Interpolate from outer dark (0x07243a) to inner lighter (0x1a5e80) - const ro = 0x07, go = 0x24, bo = 0x3a; - const ri = 0x1a, gi = 0x5e, bi = 0x80; - const red = Math.round(ro + (ri - ro) * (1 - t)); - const green = Math.round(go + (gi - go) * (1 - t)); - const blue = Math.round(bo + (bi - bo) * (1 - t)); - const color = (red << 16) | (green << 8) | blue; - sea.fillStyle(color, 1); - sea.fillCircle(SEA_X, SEA_Y, r); - } - sea.lineStyle(4, 0x041820, 0.9); - sea.strokeCircle(SEA_X, SEA_Y, SEA_R); + this.add.image(0, RAIL.y - PAD.rail, 'catan-rail').setOrigin(0, 0).setDepth(D.hud - 3); + } + + // The wooden sea frame around the active board, plus drifting sea glints. + drawFrame() { + const { key, fr, origin } = bakeFrame(this, this.geo, this.gs.boardId); + this.frameImg?.destroy(); + this.frameImg = this.add.image(origin.x, origin.y, key).setOrigin(0, 0).setDepth(D.frame); + this.frame = fr; + this.glintTimer?.remove(); + this.glintTimer = this.time.addEvent({ delay: 220, loop: true, callback: () => this.spawnGlint() }); + } + + spawnGlint() { + if (!this.frame || this.glints > 14) return; + const { hull, sea } = this.frame; + const i = Math.floor(Math.random() * hull.length), j = (i + 1) % hull.length; + const t = Math.random(), d = 0.18 + Math.random() * 0.62; + const hx = hull[i].x + (hull[j].x - hull[i].x) * t, hy = hull[i].y + (hull[j].y - hull[i].y) * t; + const sx = sea[i].x + (sea[j].x - sea[i].x) * t, sy = sea[i].y + (sea[j].y - sea[i].y) * t; + const x = hx + (sx - hx) * d, y = hy + (sy - hy) * d; + const g = this.add.image(x, y, 'catan-glint').setDepth(D.glint).setAlpha(0) + .setBlendMode(Phaser.BlendModes.ADD).setScale(0.6 + Math.random() * 0.7, 1); + this.glints++; + this.tweens.add({ + targets: g, alpha: { from: 0, to: 0.55 + Math.random() * 0.3 }, x: x + 10 + Math.random() * 10, + duration: 900 + Math.random() * 700, yoyo: true, ease: 'Sine.InOut', + onComplete: () => { g.destroy(); this.glints--; }, + }); } buildBoardStatic() { // Hexes drawn once from the (static) topology; resources/numbers come from state at startNewMatch. this.hexGfx = this.add.graphics().setDepth(D.board); this.hexBorderGfx = this.add.graphics().setDepth(D.board + 2); + this.hexFxGfx = this.add.graphics().setDepth(D.board + 2.5).setBlendMode(Phaser.BlendModes.ADD); this.hexImgs = []; this.hexLabels = []; this.portObjs = []; @@ -132,41 +185,37 @@ export default class CatanGame extends Phaser.Scene { this.hexImgs = []; this.hexLabels.forEach((t) => t.destroy()); this.hexLabels = []; - this.hexTileFrames = {}; + this.hexTileFrames = this.hexTileFrames ?? {}; - // Inset a convex hex polygon toward its center. - // s=0 collapses to point; s=1 is original. Uses inradius (79.7px) as scale reference. const inset = (pts, cx, cy, s) => pts.map(p => ({ x: cx + (p.x - cx) * s, y: cy + (p.y - cy) * s })); - // Border insets/image size scale with the active board's hex size (the base - // island uses 92; larger Seafarers boards use a smaller hex). const size = this.geo.size ?? HEX_SIZE; const hexW = Math.sqrt(3) * size; const inradius = size * Math.sqrt(3) / 2; + const k = size / HEX_SIZE; for (const hex of this.gs.hexes) { const pts = this.geo.hexes[hex.id].corners.map((c) => ({ x: this.geo.nodes[c].x, y: this.geo.nodes[c].y })); const { x, y } = this.hexPos(hex.id); const terr = this.hexTerrain(hex); - - // Scale factors for the 7px colored ring + 4px dark ring (absolute pixels). - const s1 = 1 - 7 / inradius; // after colored border - const s2 = 1 - 11 / inradius; // after dark border (image area) + const s1 = 1 - 7 / inradius; + const s2 = 1 - 11 / inradius; const innerPts = inset(pts, x, y, s1); const imagePts = inset(pts, x, y, s2); - // Layer 1: terrain swatch fill (outer colored border ring) + // Tile thickness: a dark edge peeking out below each land tile. + if (hex.kind !== 'sea') { + g.fillStyle(0x1e1208, 0.9); + g.fillPoints(inset(pts, x, y, 0.985).map((p) => ({ x: p.x + 1.5 * k, y: p.y + 5 * k })), true); + } g.fillStyle(terr.swatch, 0.55); g.fillPoints(pts, true); - - // Layer 2: dark fill inset (inner black border ring) g.fillStyle(0x111111, 1); g.fillPoints(innerPts, true); - // Layer 3: tile image masked to innermost polygon (land/desert only) if (terr.tileFrames && this.textures.exists('catan-tiles')) { - if (this.hexTileFrames[hex.id] == null) { + if (this.hexTileFrames[hex.id] == null || !terr.tileFrames.includes(this.hexTileFrames[hex.id])) { this.hexTileFrames[hex.id] = terr.tileFrames[Math.floor(Math.random() * 2)]; } const frame = this.hexTileFrames[hex.id]; @@ -179,18 +228,24 @@ export default class CatanGame extends Phaser.Scene { .setDepth(D.board + 1); this.hexImgs.push({ img, maskG }); } else { - // Fallback / water / gold / fog: solid color fill in the image area g.fillStyle(terr.color, 1); g.fillPoints(imagePts, true); } - // Thin outer crisp stroke - this.hexBorderGfx.lineStyle(2, 0x4a3210, 0.35); - this.hexBorderGfx.strokePoints(pts, true); + // bevel: light upper-left edge, dark lower-right edge + const b = this.hexBorderGfx; + b.lineStyle(2, 0x4a3210, 0.35); + b.strokePoints(pts, true); + for (let i = 0; i < imagePts.length; i++) { + const p = imagePts[i], q = imagePts[(i + 1) % imagePts.length]; + const mx = (p.x + q.x) / 2 - x, my = (p.y + q.y) / 2 - y; + const lit = (-mx - my) > 0; + b.lineStyle(2, lit ? 0xfff2d0 : 0x000000, lit ? 0.22 : 0.28); + b.lineBetween(p.x, p.y, q.x, q.y); + } - // Terrain label - this.hexLabels.push(this.add.text(x, y - 56, terr.label, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#2a2118', + this.hexLabels.push(this.add.text(x, y - 56 * k, terr.label, { + fontFamily: '"Julius Sans One"', fontSize: `${Math.round(15 * Math.max(0.8, k))}px`, color: '#2a2118', }).setOrigin(0.5).setAlpha(0.65).setDepth(D.board + 3)); } } @@ -213,6 +268,7 @@ export default class CatanGame extends Phaser.Scene { } } + // Harbours: a little boat bobbing off the coast, moored to its two nodes. drawPorts() { this.portObjs.forEach((o) => o.destroy()); this.portObjs = []; @@ -220,55 +276,57 @@ export default class CatanGame extends Phaser.Scene { const out = 30; const px = port.x + Math.cos(port.angle) * out; const py = port.y + Math.sin(port.angle) * out; - const c = this.add.container(px, py).setDepth(D.port); - const g = this.add.graphics(); - g.fillStyle(0x6b4a1a, 1); g.fillCircle(0, 0, 19); - g.fillStyle(0xefe2c0, 1); g.fillCircle(0, 0, 16); - c.add(g); - const label = port.type === 'any' ? '3:1' : '2:1'; - const sub = port.type === 'any' ? '' : RESOURCE_INFO[port.type].label[0]; - c.add(this.add.text(0, -4, label, { fontFamily: 'Righteous', fontSize: '13px', color: '#2a2118' }).setOrigin(0.5)); - if (sub) c.add(this.add.text(0, 8, sub, { fontFamily: 'Righteous', fontSize: '11px', color: '#8a5a18' }).setOrigin(0.5)); - const title = port.type === 'any' - ? '3:1 Harbor' - : `2:1 ${RESOURCE_INFO[port.type].label} Harbor`; - const desc = port.type === 'any' + // mooring planks to the two coastal nodes + const jg = this.add.graphics().setDepth(D.port - 1); + for (const nid of port.nodes) { + const n = this.geo.nodes[nid]; + jg.lineStyle(6, 0x3a2412, 0.9); jg.lineBetween(px, py + 6, n.x, n.y); + jg.lineStyle(3, 0x9a6a38, 1); jg.lineBetween(px, py + 6, n.x, n.y); + } + + const c = this.add.container(px, py).setDepth(D.port); + const boat = this.add.image(0, -4, 'catan-boat').setDisplaySize(50, 50); + const tag = this.add.graphics(); + const any = port.type === 'any'; + tag.fillStyle(0x000000, 0.3); tag.fillRoundedRect(-21, 15, 44, 20, 6); + tag.fillStyle(0xf3e6c4, 1); tag.fillRoundedRect(-22, 13, 44, 20, 6); + tag.lineStyle(1.5, 0x8a6a34, 1); tag.strokeRoundedRect(-22, 13, 44, 20, 6); + if (!any) { tag.fillStyle(RESOURCE_INFO[port.type].swatch, 1); tag.fillCircle(-12, 23, 6); tag.lineStyle(1, 0x2a2118, 0.6); tag.strokeCircle(-12, 23, 6); } + const label = this.add.text(any ? 0 : 5, 23, any ? '3:1' : '2:1', { + fontFamily: 'Righteous', fontSize: '14px', color: '#2a2118', + }).setOrigin(0.5); + c.add([boat, tag, label]); + // gentle bob, each boat on its own phase + this.tweens.add({ targets: boat, y: -7, angle: { from: -3, to: 3 }, duration: 1500 + Math.random() * 700, yoyo: true, repeat: -1, ease: 'Sine.InOut', delay: Math.random() * 1200 }); + + const title = any ? '3:1 Harbor' : `2:1 ${RESOURCE_INFO[port.type].label} Harbor`; + const desc = any ? 'Trade 3 of any single resource for 1 resource of your choice. Works with brick, lumber, wool, grain, or ore.' : `Trade 2 ${RESOURCE_INFO[port.type].label.toLowerCase()} for 1 resource of your choice. Only ${RESOURCE_INFO[port.type].label.toLowerCase()} qualifies for this rate.`; - c.setInteractive(new Phaser.Geom.Circle(0, 0, 19), Phaser.Geom.Circle.Contains); - c.on('pointerover', () => this.showInfoTooltip(px, py - 19, title, desc, 0xb89a5e)); + c.setInteractive(new Phaser.Geom.Circle(0, 4, 24), Phaser.Geom.Circle.Contains); + c.on('pointerover', () => this.showInfoTooltip(px, py - 30, title, desc, 0xb89a5e)); c.on('pointerout', () => this.hideInfoTooltip()); - - // little jetties to the two coastal nodes - const jg = this.add.graphics().setDepth(D.port - 1); - jg.lineStyle(3, 0x6b4a1a, 0.8); - for (const nid of port.nodes) jg.lineBetween(px, py, this.geo.nodes[nid].x, this.geo.nodes[nid].y); this.portObjs.push(c, jg); } } - // Polished numeric chits: parchment token, number (red for 6/8), probability pips. + // Number chits: a bevelled token, the number (red for 6/8), probability pips. drawChits() { this.chitObjs.forEach((o) => o.destroy()); this.chitObjs = []; this.chitByHexId = {}; + const k = Math.max(0.8, this.pieceK); for (const hex of this.gs.hexes) { if (hex.number == null) continue; const { x, y } = this.hexPos(hex.id); - const c = this.add.container(x, y + 6).setDepth(D.chit); - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.18); g.fillCircle(2, 3, 25); - g.fillStyle(0xf3e6c4, 1); g.fillCircle(0, 0, 24); - g.lineStyle(2.5, 0xb89a5e, 1); g.strokeCircle(0, 0, 24); - g.lineStyle(1.5, 0xd8c79a, 1); g.strokeCircle(0, 0, 20); - c.add(g); + const c = this.add.container(x, y + 6 * k).setDepth(D.chit); + c.add(this.add.image(0, 2, 'catan-chit').setDisplaySize(64, 64)); const hot = hex.number === 6 || hex.number === 8; c.add(this.add.text(0, -5, String(hex.number), { fontFamily: 'Righteous', fontSize: hot ? '26px' : '24px', color: hot ? '#c0392b' : '#2a2118', }).setOrigin(0.5)); - // pips const n = pipCount(hex.number); const pg = this.add.graphics(); pg.fillStyle(hot ? 0xc0392b : 0x2a2118, 1); @@ -276,158 +334,72 @@ export default class CatanGame extends Phaser.Scene { const startX = -((n - 1) * spacing) / 2; for (let i = 0; i < n; i++) pg.fillCircle(startX + i * spacing, 13, 2); c.add(pg); + c.setScale(k); this.chitObjs.push(c); this.chitByHexId[hex.id] = c; - // pop-in c.setScale(0); - this.tweens.add({ targets: c, scale: 1, duration: 260, delay: hex.id * 18, ease: 'Back.easeOut' }); + this.tweens.add({ targets: c, scale: k, duration: 260, delay: hex.id * 18, ease: 'Back.easeOut' }); } } - // ── dice ────────────────────────────────────────────────────────────────────── - buildDice() { - this.diceG = []; - this.diceContainers = []; - const baseX = 1290, baseY = 950; - for (let i = 0; i < 2; i++) { - const g = this.add.graphics(); - const c = this.add.container(baseX + (i === 0 ? -34 : 34), baseY, [g]).setDepth(D.hud).setAlpha(0.25); - this.diceG.push(g); this.diceContainers.push(c); - this.drawDie(g, 1); - } - } - drawDie(g, value) { - const s = 26; - g.clear(); - g.fillStyle(0xf0e8d0, 1); g.fillRoundedRect(-s, -s, s * 2, s * 2, 6); - g.lineStyle(2, 0x2c1a0e, 1); g.strokeRoundedRect(-s, -s, s * 2, s * 2, 6); - const P = { - 1: [[0, 0]], 2: [[-.55, -.55], [.55, .55]], 3: [[-.55, -.55], [0, 0], [.55, .55]], - 4: [[-.55, -.55], [.55, -.55], [-.55, .55], [.55, .55]], - 5: [[-.55, -.55], [.55, -.55], [0, 0], [-.55, .55], [.55, .55]], - 6: [[-.55, -.55], [.55, -.55], [-.55, 0], [.55, 0], [-.55, .55], [.55, .55]], - }; - g.fillStyle(0x1a1a1a, 1); - for (const [px, py] of (P[value] || P[1])) g.fillCircle(px * 16, py * 16, 4); - } - animateDice(values) { - return new Promise((resolve) => { - playSound(this, SFX.DICE_ROLL); - - const landX = [1256, 1324]; - const landY = 950; - const startX = GAME_WIDTH / 2; // 960 — center of bottom bar - const startY = 1015; - const arcY = 755; // arc peak - - // Move dice to throw origin, small, random angle - this.diceContainers.forEach((c, i) => { - c.setAlpha(1).setScale(0.35).setAngle(Phaser.Math.Between(0, 359)) - .setPosition(startX + (i === 0 ? -12 : 12), startY); - this.drawDie(this.diceG[i], Phaser.Math.Between(1, 6)); - }); - - // Cycle random faces while airborne - let cyclerStopped = false; - const cycler = this.time.addEvent({ - delay: 55, loop: true, - callback: () => { - this.drawDie(this.diceG[0], Phaser.Math.Between(1, 6)); - this.drawDie(this.diceG[1], Phaser.Math.Between(1, 6)); - }, - }); - const stopCycler = () => { if (!cyclerStopped) { cyclerStopped = true; cycler.remove(); } }; - - let settled = 0; - this.diceContainers.forEach((c, i) => { - const lx = landX[i] + (Math.random() * 8 - 4); - const ly = landY + (Math.random() * 8 - 4); - const outMs = 295 + i * 32; - const backMs = 430 + i * 44; - const totalMs = outMs + backMs; - - // X flies straight to landing; Y arcs up then bounces down - this.tweens.add({ targets: c, x: lx, duration: totalMs, ease: 'Quad.Out' }); - this.tweens.chain({ - targets: c, tweens: [ - { y: arcY, duration: outMs, ease: 'Quad.Out' }, - { y: ly, duration: backMs, ease: 'Bounce.Out' }, - ] - }); - // Scale up as die approaches - this.tweens.add({ targets: c, scale: 1, duration: outMs + backMs * 0.55, ease: 'Quad.Out' }); - // Spin - this.tweens.add({ - targets: c, - angle: c.angle + 540 + Math.random() * 180, - duration: totalMs, - ease: 'Quad.Out', - }); - - this.time.delayedCall(totalMs, () => { - stopCycler(); - this.drawDie(this.diceG[i], values[i]); - // Snap to nearest upright angle with a small wiggle - const upright = Math.round(c.angle / 90) * 90 + (Math.random() * 10 - 5); - this.tweens.add({ - targets: c, angle: upright, duration: 120, ease: 'Back.Out', - onComplete: () => { - settled++; - if (settled === 2) { - this.diceContainers.forEach((dc) => - this.tweens.add({ targets: dc, scaleX: 1.14, scaleY: 0.88, duration: 80, yoyo: true }) - ); - const numberWords = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']; - enqueueSpeech(`numbers-${numberWords[values[0] + values[1]]}`); - this.time.delayedCall(160, resolve); - } - }, - }); - }); - }); - }); + // ── dice ───────────────────────────────────────────────────────────────────── + // The engine has already rolled; the tray throws real dice onto those faces. + async animateDice(values) { + await this.tray.roll(values, this.gs.currentPlayer === 0); + const numberWords = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']; + enqueueSpeech(`numbers-${numberWords[values[0] + values[1]]}`); + if (values[0] + values[1] === 7) enqueueSpeech(`catan-robber-0${Phaser.Math.Between(1, 4)}`); } - // ── HUD (human hand + buttons + status) ──────────────────────────────────────── + // ── HUD (rail, buttons, status) ────────────────────────────────────────────── buildHUD() { - // bottom panel - this.add.rectangle(GAME_WIDTH / 2, 985, GAME_WIDTH, 190, COLORS.panel, 0.92).setDepth(D.hud - 1); - this.add.rectangle(GAME_WIDTH / 2, 893, GAME_WIDTH, 4, COLORS.accent, 0.6).setDepth(D.hud - 1); - - // human portrait - createPlayerPortrait(this, 90, 980, 64, D.hud, 'CatanGame'); - // VP badge above portrait — graphics redrawn in updateHand() once gs is available + // human portrait + VP badge + name on the rail + this.humanPortrait = createPlayerPortrait(this, PORTRAIT.x, PORTRAIT.y, PORTRAIT.r, D.hud, 'CatanGame'); + this.humanRing = this.add.graphics().setDepth(D.hud + 4); + this.humanGlow = this.add.graphics().setDepth(D.hud - 1).setAlpha(0); + this.humanGlow.lineStyle(6, 0xffd34d, 1); this.humanGlow.strokeCircle(PORTRAIT.x, PORTRAIT.y, PORTRAIT.r + 9); + this.humanGlowTween = this.tweens.add({ targets: this.humanGlow, alpha: { from: 0.3, to: 1 }, duration: 750, yoyo: true, repeat: -1, paused: true }); this.playerVpBadgeGfx = this.add.graphics().setDepth(D.hud + 5); - this.playerVpText = this.add.text(90, 906, '0', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#ffffff', fontStyle: 'bold', + this.playerVpText = this.add.text(PORTRAIT.x + 52, PORTRAIT.y - 50, '0', { + fontFamily: 'Righteous', fontSize: '18px', color: '#ffffff', }).setOrigin(0.5).setDepth(D.hud + 6); - this.add.text(90, 1056, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.hud); + this.add.text(PORTRAIT.x, PORTRAIT.y + PORTRAIT.r + 6, auth.user?.username ?? 'You', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#f6ead0', stroke: '#1a0d04', strokeThickness: 3, + }).setOrigin(0.5, 0).setDepth(D.hud); - // dev card hand area label + this.add.text(HAND.x + 8, HAND.y + 4, 'Your hand', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#cfe3d4', + }).setOrigin(0, 0).setAlpha(0.75).setDepth(D.hud); this.devHandContainer = this.add.container(0, 0).setDepth(D.hud); - this.add.text(740, 916, 'Development Cards', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.hud); + this.add.text(DEV.x + 4, DEV.y + 4, 'Development cards', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#cfe3d4', + }).setOrigin(0, 0).setAlpha(0.75).setDepth(D.hud); + this.add.text(HUMAN_INFO.x + 6, HUMAN_INFO.y + 4, 'Pieces left', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#cfe3d4', + }).setOrigin(0, 0).setAlpha(0.75).setDepth(D.hud); - // status banner (top centre) - this.statusText = this.add.text(1000, 40, '', { + // status banner + latest log line (top centre, over the sea frame) + this.statusText = this.add.text(STATUS.x, STATUS.y, '', { fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - backgroundColor: '#111923cc', padding: { x: 18, y: 8 }, + backgroundColor: '#1a0f07dd', padding: { x: 18, y: 8 }, }).setOrigin(0.5).setDepth(D.banner); + this.logText = this.add.text(LOG.x, LOG.y, '', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#e8dcc0', + backgroundColor: '#1a0f07aa', padding: { x: 10, y: 3 }, + }).setOrigin(0.5).setDepth(D.banner - 1); - // log line (bottom-left) - this.logText = this.add.text(170, 1060, '', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.hud); + this.buildCostCard(); + this.buildHistogram(); + this.buildAwardsPocket(); - // cost legend (bottom bar, right of dice) - this.buildCostLegend(); - - // action buttons (vertical column, right) - const bx = 1815; let by = 250; const step = 60; - const mk = (key, label, fn) => { const b = new Button(this, bx, by, label, fn, { width: 200, height: 46, fontSize: 19 }).setDepth(D.hud); this.buttons[key] = b; by += step; return b; }; + // action buttons (right column) + let bi = 0; + const mk = (key, label, fn) => { + const p = buttonCenter(bi++); + const b = new Button(this, p.x, p.y, label, fn, { width: BUTTONS.w, height: BUTTONS.h, fontSize: 18 }).setDepth(D.hud); + this.buttons[key] = b; + return b; + }; mk('roll', 'Roll Dice', () => this.onRoll()); mk('road', 'Build Road', () => this.enterPlace('road')); if (this.expansion === 'seafarers') mk('ship', 'Build Ship', () => this.enterPlace('ship')); @@ -438,45 +410,55 @@ export default class CatanGame extends Phaser.Scene { mk('trade', 'Trade', () => this.openTradePanel()); mk('endTurn', 'End Turn', () => this.onEndTurn()); - new Button(this, 90, 60, 'Leave', () => this.scene.start('GameMenu'), { variant: 'ghost', width: 120, height: 42, fontSize: 18 }).setDepth(D.hud); + new Button(this, LEAVE.x + LEAVE.w / 2, LEAVE.y + LEAVE.h / 2, 'Leave', () => this.scene.start('GameMenu'), { + variant: 'ghost', width: LEAVE.w, height: LEAVE.h, fontSize: 18, + }).setDepth(D.hud); this.buildDevCardTooltip(); this.buildInfoTooltip(); - this._buildTurnTriangle(); this._buildSpecialCards(); } + // The pocket above the buttons where unclaimed awards wait. + buildAwardsPocket() { + const g = this.add.graphics().setDepth(D.hud - 2); + g.fillStyle(0x000000, 0.35); g.fillRoundedRect(AWARDS.x + 3, AWARDS.y + 5, AWARDS.w, AWARDS.h, 14); + g.fillStyle(0x5a3719, 1); g.fillRoundedRect(AWARDS.x, AWARDS.y, AWARDS.w, AWARDS.h, 14); + g.fillStyle(0x2b190c, 1); g.fillRoundedRect(AWARDS.x + 8, AWARDS.y + 34, AWARDS.w - 16, AWARDS.h - 42, 9); + g.lineStyle(1.5, 0xc9a24a, 0.6); g.strokeRoundedRect(AWARDS.x + 1, AWARDS.y + 1, AWARDS.w - 2, AWARDS.h - 2, 13); + this.add.text(AWARDS.x + AWARDS.w / 2, AWARDS.y + 17, 'AWARDS', { + fontFamily: 'Righteous', fontSize: '18px', color: '#e9cf8a', + }).setOrigin(0.5).setDepth(D.hud - 1); + } + _buildSpecialCards() { - const makeCard = (x, frameIdx, borderColor) => { - const W = 64, H = 90, R = 6, BW = 3; + const makeCard = (frameIdx, borderColor) => { + const { w: W, h: H } = AWARD_CARD, R = 7, BW = 3; const bg = this.add.graphics(); - bg.fillStyle(0x111111, 0.85); - bg.fillRoundedRect(-W / 2, -H / 2, W, H, R); + bg.fillStyle(0x000000, 0.35); bg.fillRoundedRect(-W / 2 + 3, -H / 2 + 4, W, H, R); + bg.fillStyle(0x111111, 0.95); bg.fillRoundedRect(-W / 2, -H / 2, W, H, R); const img = this.add.image(0, 0, 'catan-special-cards', frameIdx).setDisplaySize(W - 6, H - 6); const border = this.add.graphics(); border.lineStyle(BW, borderColor, 1); border.strokeRoundedRect(-W / 2, -H / 2, W, H, R); - const c = this.add.container(x, 760).setDepth(D.hud + 3); - c.add([bg, img, border]); - return c; + return this.add.container(0, 0, [bg, img, border]).setDepth(D.hud + 3); }; - - const cardY = this.expansion === 'seafarers' ? 830 : 760; - this._lrCard = makeCard(1775, 0, 0xdaa520); - this._laCard = makeCard(1855, 1, 0xb03030); - this._lrCard.setY(cardY); - this._laCard.setY(cardY); + this._lrCard = makeCard(0, 0xdaa520); + this._laCard = makeCard(1, 0xb03030); + for (const [card, kind] of [[this._lrCard, 'longestRoad'], [this._laCard, 'largestArmy']]) { + const p = awardHome(kind); + card.setPosition(p.x, p.y); + } this._prevSpecialCardOwners = { longestRoad: null, largestArmy: null }; this._specialCardAnimating = { longestRoad: false, largestArmy: false }; - const H = 90; const attachHover = (card, title, desc, borderColor) => { card.setInteractive( - new Phaser.Geom.Rectangle(-32, -H / 2, 64, H), + new Phaser.Geom.Rectangle(-AWARD_CARD.w / 2, -AWARD_CARD.h / 2, AWARD_CARD.w, AWARD_CARD.h), Phaser.Geom.Rectangle.Contains, ); card.on('pointerover', () => - this.showInfoTooltip(card.x, card.y - (H / 2) * card.scaleY, title, desc, borderColor)); + this.showInfoTooltip(card.x, card.y - (AWARD_CARD.h / 2) * card.scaleY, title, desc, borderColor)); card.on('pointerout', () => this.hideInfoTooltip()); }; attachHover( @@ -492,24 +474,11 @@ export default class CatanGame extends Phaser.Scene { } _getSpecialCardPos(cardType, owner) { - if (owner === null) { - const cardY = this.expansion === 'seafarers' ? 830 : 760; - return cardType === 'longestRoad' - ? { x: 1775, y: cardY, scale: 1 } - : { x: 1855, y: cardY, scale: 1 }; - } - if (owner === 0) { - return cardType === 'longestRoad' - ? { x: 1390, y: 1015, scale: 1 } - : { x: 1462, y: 1015, scale: 1 }; - } - const panel = this.oppPanels?.find((p) => p.seat === owner); - if (!panel) return { x: 0, y: 0, scale: 0.25 }; - const bx = panel.x; - const by = panel.y - 74; - return cardType === 'longestRoad' - ? { x: bx - 28, y: by, scale: 0.25 } - : { x: bx + 28, y: by, scale: 0.25 }; + if (owner === null) { const p = awardHome(cardType); return { ...p, scale: 1 }; } + if (owner === 0) return humanAwardPos(cardType); + const panel = this.oppPanels.find((p) => p.seat === owner); + if (!panel) return { ...awardHome(cardType), scale: 1 }; + return oppAwardPos(panel.rect, cardType); } updateSpecialCards() { @@ -518,7 +487,6 @@ export default class CatanGame extends Phaser.Scene { const newOwner = this.gs[cardType].owner; const prevOwner = this._prevSpecialCardOwners[cardType]; const card = cardType === 'longestRoad' ? this._lrCard : this._laCard; - if (newOwner !== prevOwner) { const fromPos = this._getSpecialCardPos(cardType, prevOwner); this._prevSpecialCardOwners[cardType] = newOwner; @@ -533,71 +501,36 @@ export default class CatanGame extends Phaser.Scene { _animateSpecialCardTransfer(cardType, fromPos, newOwner) { const toPos = this._getSpecialCardPos(cardType, newOwner); const card = cardType === 'longestRoad' ? this._lrCard : this._laCard; - - card.setPosition(fromPos.x, fromPos.y).setScale(fromPos.scale); + card.setPosition(fromPos.x, fromPos.y).setScale(fromPos.scale).setDepth(D.flight); this._specialCardAnimating[cardType] = true; - const peakY = Math.min(fromPos.y, toPos.y) - 150; const midX = (fromPos.x + toPos.x) / 2; - const midScale = (fromPos.scale + toPos.scale) / 2; const half = 380; - this.tweens.chain({ targets: card, tweens: [ - { x: midX, y: peakY, scale: midScale, duration: half, ease: 'Quad.Out' }, + { x: midX, y: peakY, scale: 1.3, angle: 8, duration: half, ease: 'Quad.Out' }, { - x: toPos.x, y: toPos.y, scale: toPos.scale, + x: toPos.x, y: toPos.y, scale: toPos.scale, angle: 0, duration: half, ease: 'Quad.In', - onComplete: () => { this._specialCardAnimating[cardType] = false; }, + onComplete: () => { this._specialCardAnimating[cardType] = false; card.setDepth(D.hud + 3); }, }, - ] + ], }); - enqueueSpeech(cardType === 'longestRoad' ? 'catan-card-road' : 'catan-card-army'); } - _buildTurnTriangle() { - const g = this.add.graphics().setDepth(D.hud + 8); - g.fillStyle(0xffdd00, 1); - g.fillTriangle(-10, -13, -10, 13, 10, 0); - g.setPosition(-9999, -9999); - this.turnIndicator = g; - this._turnSeat = null; - this.tweens.add({ - targets: g, - scaleX: 1.4, scaleY: 1.4, - duration: 700, - yoyo: true, - repeat: -1, - ease: 'Sine.InOut', - }); - } - _seatPortraitPos(seat) { - if (seat === 0) return { x: 90, y: 980, r: 64 }; - const panel = this.oppPanels?.find(p => p.seat === seat); - return panel ? { x: panel.x, y: panel.y, r: 56 } : null; + if (seat === 0) return { x: PORTRAIT.x, y: PORTRAIT.y, r: PORTRAIT.r }; + const panel = this.oppPanels.find(p => p.seat === seat); + return panel ? { x: panel.x, y: panel.y, r: panel.anchors.portrait.r } : null; } _updateTurnIndicator() { const seat = this.gs?.currentPlayer; if (seat == null) return; - const pos = this._seatPortraitPos(seat); - if (!pos) return; - const tx = pos.x - pos.r - 20; - const ty = pos.y; - if (this._turnSeat === seat) return; - this._turnSeat = seat; - if (this.turnIndicator.x < 0) { - this.turnIndicator.setPosition(tx, ty); - } else { - this.tweens.add({ - targets: this.turnIndicator, - x: tx, y: ty, - duration: 600, - ease: 'Cubic.Out', - }); - } + this.boards?.setActive(seat); + if (seat === 0) { if (this.humanGlowTween.isPaused()) this.humanGlowTween.resume(); } + else { this.humanGlowTween.pause(); this.humanGlow.setAlpha(0); } } buildDevCardTooltip() { @@ -620,7 +553,7 @@ export default class CatanGame extends Phaser.Scene { this._devTooltip.popR = popR; } - showDevCardTooltip(cardX, cardTopY, type, isNew, borderColor) { + showDevCardTooltip(cardX, cardTopY, type, isNew, borderColor, playable = false) { const DEV_DESC = { knight: 'Move the Robber to any tile and steal a resource from a player there.', roadBuilding: 'Place 2 roads anywhere you could legally build them, for free.', @@ -638,6 +571,7 @@ export default class CatanGame extends Phaser.Scene { titleTxt.setText(DEV_INFO[type]?.label ?? type); let d = DEV_DESC[type] ?? ''; if (isNew) d += '\n(Not playable until next turn)'; + else if (playable) d += '\nClick to play it now.'; descTxt.setText(d); const ttX = Phaser.Math.Clamp(cardX, popW / 2 + 10, GAME_WIDTH - popW / 2 - 10); tt.setPosition(ttX, cardTopY - popH / 2 - 10); @@ -647,8 +581,7 @@ export default class CatanGame extends Phaser.Scene { this._devTooltip?.setPosition(-9999, -9999); } - // Generic auto-sizing hover tooltip (title + wrapped description) used by the - // Longest Road / Largest Army cards and the harbor markers. + // Generic auto-sizing hover tooltip (title + wrapped description). buildInfoTooltip() { const g = this.add.graphics(); const titleTxt = this.add.text(0, 0, '', { @@ -689,148 +622,225 @@ export default class CatanGame extends Phaser.Scene { this._infoTooltip?.setPosition(-9999, -9999); } - buildCostLegend() { - const panelRight = 1900; - const panelW = 320; - const cx = panelRight - panelW / 2; - - const rows = [ - { name: 'Road', resources: ['brick', 'lumber'] }, - { name: 'Settlement', resources: ['brick', 'lumber', 'wool', 'grain'] }, - { name: 'City', resources: ['grain', 'grain', 'ore', 'ore', 'ore'] }, - { name: 'Dev Card', resources: ['wool', 'grain', 'ore'] }, - ]; - if (this.expansion === 'seafarers') { - rows.push({ name: 'Ship', resources: ['lumber', 'wool'] }); + showCaddyTooltip(key, slot) { + if (!this.gs || this.handPiles.some((p) => p.dragging)) return; + const x = slot.x + slot.w / 2, y = slot.y; + if (key === 'dev') { + const left = this.gs.devDeck.length; + this.showInfoTooltip(x, y, 'Development Cards', `Left in the deck: ${left}\nBought so far: ${25 - left}`, 0xc9a24a); + return; } + const bank = this.gs.bank[key]; + const mine = this.gs.players[0].resources[key]; + const others = 19 - bank - mine; + let desc = `In the bank: ${bank}\nIn your hand: ${mine}\nWith opponents: ${others}`; + if (this.gs.phase === 'action' && this.gs.currentPlayer === 0 && !this.busy) { + desc += `\n\nDrag a hand pile here to trade (${L.bestTradeRatio(this.gs, 0, key)}:1 for ${RESOURCE_INFO[key].label.toLowerCase()}).`; + } + this.showInfoTooltip(x, y, RESOURCE_INFO[key].label, desc, RESOURCE_INFO[key].swatch); + } - // Base: original fixed values. Seafarers: taller panel to fit 5th row, still inside bar (y 893–1080). - const seafarers = this.expansion === 'seafarers'; - const bgH = seafarers ? 180 : 164; - const bgCy = seafarers ? 987 : 980; - const rowPad = 44; - const rowStep = (bgH - rowPad - 14) / (rows.length - 1); + // ── Building Costs card (click a lit row to build) ─────────────────────────── + buildCostCard() { + const C = COSTCARD; + this.add.image(C.x - PAD.costcard, C.y - PAD.costcard, 'catan-costcard').setOrigin(0, 0).setDepth(D.hud - 1); + this.add.text(C.x + C.w / 2, C.y + 16, 'Building Costs', { + fontFamily: 'Righteous', fontSize: '18px', color: '#5a3712', + }).setOrigin(0.5).setDepth(D.hud); + const rows = [ + { key: 'road', name: 'Road', cost: COSTS.road, piece: 'road' }, + { key: 'settlement', name: 'Settlement', cost: COSTS.settlement, piece: 'settlement' }, + { key: 'city', name: 'City', cost: COSTS.city, piece: 'city' }, + { key: 'buyDev', name: 'Dev Card', cost: COSTS.devCard, piece: null }, + ]; + if (this.expansion === 'seafarers') rows.splice(1, 0, { key: 'ship', name: 'Ship', cost: { lumber: 1, wool: 1 }, piece: 'ship' }); + const top = C.y + 32, step = (C.h - 40) / rows.length; + this.costRows = rows.map((row, i) => { + const cy = top + step * i + step / 2; + const hl = this.add.graphics().setDepth(D.hud - 0.5).setAlpha(0); + hl.fillStyle(0xffd34d, 0.35); hl.fillRoundedRect(C.x + 10, cy - step / 2 + 1, C.w - 20, step - 2, 6); + hl.lineStyle(1.5, 0xb8860b, 0.9); hl.strokeRoundedRect(C.x + 10, cy - step / 2 + 1, C.w - 20, step - 2, 6); + const name = this.add.text(C.x + 22, cy, row.name, { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: '#3a2408', + }).setOrigin(0, 0.5).setDepth(D.hud); + const res = []; + for (const [r, n] of Object.entries(row.cost)) for (let k = 0; k < n; k++) res.push(r); + res.forEach((r, k) => { + const ix = C.x + 160 + k * 20; + this.add.image(ix, cy, 'catan-cards', RESOURCE_TYPES.indexOf(r)).setDisplaySize(16, 23).setDepth(D.hud); + const b = this.add.graphics().setDepth(D.hud); + b.lineStyle(1.5, RESOURCE_INFO[r].swatch, 1); b.strokeRoundedRect(ix - 8, cy - 11.5, 16, 23, 2); + }); + const left = this.add.text(C.x + C.w - 18, cy, '', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#6b4a22', + }).setOrigin(1, 0.5).setDepth(D.hud); + const zone = this.add.zone(C.x + C.w / 2, cy, C.w - 20, step - 2).setDepth(D.hud + 1); + const entry = { ...row, hl, name, left, zone, enabled: false }; + zone.on('pointerdown', () => { + if (!entry.enabled) return; + if (entry.key === 'buyDev') this.onBuyDev(); else this.enterPlace(entry.key); + }); + return entry; + }); + } - const panel = this.add.container(0, 0).setDepth(D.hud); - panel.add(this.add.rectangle(cx, bgCy, panelW, bgH, 0x000000, 0.3).setStrokeStyle(1, COLORS.accent, 0.5)); - panel.add(this.add.text(cx, bgCy - bgH / 2 + 7, 'Build Costs', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.goldHex, - }).setOrigin(0.5, 0)); + updateCostCard() { + if (!this.costRows || !this.gs) return; + const left = L.piecesLeft(this.gs, 0); + for (const row of this.costRows) { + const on = !!this.btnState?.[row.key]; + row.enabled = on; + row.hl.setAlpha(on ? 1 : 0); + if (on) row.zone.setInteractive({ useHandCursor: true }); else row.zone.disableInteractive(); + if (row.piece) row.left.setText(`${left[row.piece]} left`).setColor(left[row.piece] === 0 ? '#a0281a' : '#6b4a22'); + else row.left.setText(`${this.gs.devDeck.length} left`); + } + } - const lx = panelRight - panelW + 14; - const rx = panelRight - 14; - const rowY0 = bgCy - bgH / 2 + rowPad; - const SW = 16, SH = 16, SG = 4, SR = 3; + // ── chalk roll histogram ───────────────────────────────────────────────────── + buildHistogram() { + const Hh = HISTO; + this.add.image(Hh.x - PAD.histo, Hh.y - PAD.histo, 'catan-histo').setOrigin(0, 0).setDepth(D.hud - 1); + this.add.text(Hh.x + 18, Hh.y + 13, 'Rolls', { + fontFamily: 'Righteous', fontSize: '15px', color: '#e8efe9', + }).setOrigin(0, 0).setAlpha(0.85).setDepth(D.hud); + this.histoTotal = this.add.text(Hh.x + Hh.w - 18, Hh.y + 13, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#cfe3d4', + }).setOrigin(1, 0).setAlpha(0.8).setDepth(D.hud); + this.histoG = this.add.graphics().setDepth(D.hud); + this.histoFlash = this.add.graphics().setDepth(D.hud + 0.5); + for (let n = 2; n <= 12; n++) { + const x = this.histoBarX(n); + this.add.text(x, Hh.y + Hh.h - 22, String(n), { + fontFamily: 'Righteous', fontSize: '12px', color: n === 6 || n === 8 ? '#ff9b8a' : '#dfe9e2', + }).setOrigin(0.5, 0).setAlpha(0.85).setDepth(D.hud); + } + this._histoLast = null; + } + histoBarX(n) { return HISTO.x + 26 + (n - 2) * ((HISTO.w - 52) / 10); } - const g = this.add.graphics(); - panel.add(g); - - rows.forEach(({ name, resources }, i) => { - const ry = rowY0 + i * rowStep; - panel.add(this.add.text(lx, ry, name, { - fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, - }).setOrigin(0, 0.5)); - const totalW = resources.length * SW + (resources.length - 1) * SG; - let sx = rx - totalW; - for (const r of resources) { - g.fillStyle(RESOURCE_INFO[r].swatch, 1); - g.fillRoundedRect(sx, ry - SH / 2, SW, SH, SR); - sx += SW + SG; + updateHistogram() { + const rolls = this.gs?.stats?.rolls; + if (!rolls) return; + const total = rolls.reduce((a, b) => a + b, 0); + const ways = (n) => 6 - Math.abs(7 - n); + let max = 1; + for (let n = 2; n <= 12; n++) max = Math.max(max, rolls[n], total * ways(n) / 36); + const base = HISTO.y + HISTO.h - 26, hMax = HISTO.h - 62, bw = 14; + const g = this.histoG; + g.clear(); + for (let n = 2; n <= 12; n++) { + const x = this.histoBarX(n); + const h = (rolls[n] / max) * hMax; + if (h > 0) { + g.fillStyle(n === 7 ? 0xb0b8b4 : (n === 6 || n === 8 ? 0xff9b8a : 0xeaf2ec), 0.85); + g.fillRect(x - bw / 2, base - h, bw, h); } - }); + // expected frequency: a faint chalk tick + if (total > 0) { + const eh = (total * ways(n) / 36 / max) * hMax; + g.lineStyle(2, 0xffe27a, 0.5); + g.lineBetween(x - bw / 2 - 3, base - eh, x + bw / 2 + 3, base - eh); + } + } + g.lineStyle(1.5, 0xeaf2ec, 0.5); g.lineBetween(HISTO.x + 16, base + 1, HISTO.x + HISTO.w - 16, base + 1); + this.histoTotal.setText(total ? `${total} rolled` : ''); + const key = total; + if (key !== this._histoLast && this.gs.diceTotal && total) { + this._histoLast = key; + const n = this.gs.diceTotal; + const x = this.histoBarX(n), h = (rolls[n] / max) * hMax; + const f = this.histoFlash; + f.clear(); f.fillStyle(0xffd34d, 1); f.fillRect(x - bw / 2 - 1, base - h - 1, bw + 2, h + 2); + this.tweens.killTweensOf(f); + f.setAlpha(1); + this.tweens.add({ targets: f, alpha: 0, duration: 1400, ease: 'Quad.In' }); + } } - // ── bank panel ─────────────────────────────────────────────────────────────── - buildBankPanel() { - this.bankText = {}; - // Panel flush against sea-circle right edge; wider to fit card + count text side by side - const panelX = 1489, panelW = 200, panelH = 632; - // Centre vertically in the playfield zone above the bottom bar (y=10..882) - const panelY = 10 + Math.round((872 - panelH) / 2); // 130 - const cardCx = panelX + 10 + 63; // 10px left pad + half of 126 - const textX = panelX + 10 + 126 + 12 + 15; // card right + 12 gap + half text ≈ 1637 - const panelCx = panelX + panelW / 2; // for BANK title - - const cardW = 126, cardH = 90, cardR = 6, borderW = 3, shadow = 4; - const imgW = 81, imgH = 117; // portrait in code; -90° rotation → landscape on screen - - // Stacks nearly touching: 6 × (90 + 6px gap), starting 46px below panel top - const step = 96; - const stackTops = Array.from({ length: 6 }, (_, i) => panelY + 46 + i * step); - const dividerY = stackTops[4] + cardH + 3; // 3px below resource-5 bottom - - this.bankCardPos = {}; - RESOURCE_TYPES.forEach((r, i) => { - this.bankCardPos[r] = { x: cardCx, y: stackTops[i] + cardH / 2 }; - }); - this.bankCardPos.dev = { x: cardCx, y: stackTops[5] + cardH / 2 }; - - // Layer 1: panel background + card shadow fills - const gBg = this.add.graphics().setDepth(D.hud - 1); - gBg.fillStyle(COLORS.panel, 0.92); - gBg.fillRect(panelX, panelY, panelW, panelH); - gBg.lineStyle(2, COLORS.accent, 0.7); - gBg.strokeRect(panelX, panelY, panelW, panelH); - - this.add.text(panelCx, panelY + 14, 'BANK', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.goldHex, - }).setOrigin(0.5, 0).setDepth(D.hud); - - [...RESOURCE_TYPES, 'dev'].forEach((_, i) => { - const top = stackTops[i]; - gBg.fillStyle(0x000000, 0.4); - gBg.fillRoundedRect(cardCx - cardW / 2 + shadow, top + shadow, cardW, cardH, cardR); - gBg.fillStyle(0x111111, 0.9); - gBg.fillRoundedRect(cardCx - cardW / 2, top, cardW, cardH, cardR); - }); - - gBg.lineStyle(1, COLORS.accent, 0.6); - gBg.lineBetween(panelX + 8, dividerY, panelX + panelW - 8, dividerY); - - // Layer 2: card artwork images, rotated 90° CCW - RESOURCE_TYPES.forEach((r, i) => { - this.add.image(cardCx, stackTops[i] + cardH / 2, 'catan-cards', i) - .setDisplaySize(imgW, imgH).setAngle(-90).setDepth(D.hud); - }); - this.add.image(cardCx, stackTops[5] + cardH / 2, 'catan-cards', 8) - .setDisplaySize(imgW, imgH).setAngle(-90).setDepth(D.hud); - - // Layer 3: colored borders - const gBorders = this.add.graphics().setDepth(D.hud); - RESOURCE_TYPES.forEach((r, i) => { - gBorders.lineStyle(borderW, RESOURCE_INFO[r].swatch, 1); - gBorders.strokeRoundedRect(cardCx - cardW / 2, stackTops[i], cardW, cardH, cardR); - }); - gBorders.lineStyle(borderW, COLORS.accent, 1); - gBorders.strokeRoundedRect(cardCx - cardW / 2, stackTops[5], cardW, cardH, cardR); - - // Layer 4: count text to the right of each card - const countStyle = { - fontFamily: 'Righteous', fontSize: '30px', color: '#ffffff', - stroke: '#000000', strokeThickness: 3, + // ── card sprites + flights ─────────────────────────────────────────────────── + // A portrait card at HAND_CARD size: { kind: 'res', res } | { kind: 'dev', type } + // | { kind: 'back' } (resource back) | { kind: 'devback' }. + makeCardSprite(spec, w = HAND_CARD.w, h = HAND_CARD.h) { + const bg = this.add.graphics(); + const img = this.add.image(0, 0, 'catan-cards', 0); + const border = this.add.graphics(); + const c = this.add.container(0, 0, [bg, img, border]); + c.paint = (sp) => { + bg.clear(); border.clear(); + bg.fillStyle(0x000000, 0.3); bg.fillRoundedRect(-w / 2 + 2, -h / 2 + 3, w, h, 6); + bg.fillStyle(0x111111, 0.95); bg.fillRoundedRect(-w / 2, -h / 2, w, h, 6); + let color = COLORS.accent; + if (sp.kind === 'res') { img.setTexture('catan-cards', RESOURCE_TYPES.indexOf(sp.res)); color = RESOURCE_INFO[sp.res].swatch; } + else if (sp.kind === 'dev') { img.setTexture('catan-cards', DEV_VISUAL[sp.type]?.frame ?? 7); color = DEV_VISUAL[sp.type]?.border ?? COLORS.accent; } + else if (sp.kind === 'devback') { img.setTexture('catan-cards', 8); color = 0xc9a24a; } + else { img.setTexture('cardbacks', this.cardBack?.spriteIndex ?? 0); color = 0x2a2118; } + img.setDisplaySize(w - 6, h - 6); + border.lineStyle(3, color, 1); border.strokeRoundedRect(-w / 2, -h / 2, w, h, 6); }; - RESOURCE_TYPES.forEach((r, i) => { - this.bankText[r] = this.add.text(textX, stackTops[i] + cardH / 2, '19', countStyle) - .setOrigin(0.5).setDepth(D.hud); + c.paint(spec); + return c; + } + + // Fly one card along an arc. Optional flip half-way (face-down → face-up). + flyCard({ from, to, face, back = null, delay = 0, duration = 640, arc = 110, angle = [0, 0], scale = [1, 1], onStart, onLand, sound = null }) { + return new Promise((resolve) => { + this.time.delayedCall(delay, () => { + onStart?.(); + const c = this.makeCardSprite(back ?? face).setDepth(D.flight).setPosition(from.x, from.y) + .setAngle(angle[0]).setScale(scale[0]); + const p = { t: 0 }; + let flipped = !back; + this.tweens.add({ + targets: p, t: 1, duration, ease: 'Sine.InOut', + onUpdate: () => { + const t = p.t; + c.x = from.x + (to.x - from.x) * t; + c.y = from.y + (to.y - from.y) * t - Math.sin(Math.PI * t) * arc; + c.angle = angle[0] + (angle[1] - angle[0]) * t; + const sc = scale[0] + (scale[1] - scale[0]) * t; + let sx = 1; + if (back) { + if (t > 0.3 && t < 0.7) sx = Math.abs(Math.cos(((t - 0.3) / 0.4) * Math.PI)); + if (!flipped && t >= 0.5) { flipped = true; c.paint(face); } + } + c.setScale(sc * sx, sc); + }, + onComplete: () => { + c.destroy(); + if (sound) playSound(this, sound); + onLand?.(); + resolve(); + }, + }); + }); }); - this.bankText.dev = this.add.text(textX, stackTops[5] + cardH / 2, '25', countStyle) - .setOrigin(0.5).setDepth(D.hud); } + // Where a seat's incoming cards land. + seatCardTarget(seat, res = null, resources = null) { + if (seat === 0) { + if (res) return this.handPileXY(res, resources ?? this.gs.players[0].resources); + return { x: HAND.x + HAND.w / 2, y: HAND.y + 84 }; + } + const panel = this.oppPanels.find((p) => p.seat === seat); + if (!panel) return { x: 240, y: 300 }; + const n = Math.min(10, L.handSize(this.gs.players[seat])); + return { x: panel.anchors.cards.x + n * 17, y: panel.anchors.cards.y }; + } + + // ── bank (caddy) ───────────────────────────────────────────────────────────── updateBank() { - if (!this.bankText) return; - const b = this.gs.bank; - for (const r of RESOURCE_TYPES) this.bankText[r]?.setText(String(b[r])); - this.bankText.dev?.setText(String(this.gs.devDeck.length)); + if (!this.caddy || !this.gs) return; + this.caddy.setCounts(this.gs.bank, this.gs.devDeck.length); } - // ── resource collection animations ────────────────────────────────────────── portraitPos(seat) { - if (seat === 0) return { x: 90, y: 980 }; - const panel = this.oppPanels.find(p => p.seat === seat); - return panel ? { x: panel.x, y: panel.y } : { x: 130, y: 300 }; + const p = this._seatPortraitPos(seat); + return p ? { x: p.x, y: p.y } : { x: 130, y: 300 }; } + // ── production ─────────────────────────────────────────────────────────────── async animateResourceCollection(oldGs, newGs) { if (newGs.diceTotal === 7) return; const cards = []; @@ -840,178 +850,109 @@ export default class CatanGame extends Phaser.Scene { for (let n = 0; n < delta; n++) cards.push({ seat, resource: r }); } } - if (cards.length === 0) return; - const matchingHexes = newGs.hexes.filter(h => h.number === newGs.diceTotal && !h.hasRobber); - await Promise.all(matchingHexes.map(h => this.animateChitPulse(h))); - for (const { seat, resource } of cards) await this.animateCardFlight(seat, resource); + const hexes = newGs.hexes.filter((h) => h.number === newGs.diceTotal); + const blocked = hexes.filter((h) => h.hasRobber && this.hexHasBuildings(newGs, h.id)); + const producing = hexes.filter((h) => !h.hasRobber); + if (!cards.length && !blocked.length && !producing.length) return; + await Promise.all([ + ...producing.map((h) => this.animateChitPulse(h)), + ...blocked.map((h) => this.animateBlocked(h)), + ]); + if (!cards.length) return; + const after = newGs.players[0].resources; + await Promise.all(cards.map(({ seat, resource }, i) => this.flyCard({ + from: this.caddy.topOf(resource), + to: this.seatCardTarget(seat, resource, after), + face: { kind: 'res', res: resource }, + delay: i * 150, duration: 720, arc: 140, + angle: [-90, seat === 0 ? 0 : -6], scale: [1.4, seat === 0 ? 1 : 0.55], + onStart: () => { this.caddy.nudge(resource, -1); this.caddy.bump(resource); }, + onLand: () => this.floatGain(seat, resource), + sound: SFX.CARD_PLACE, + }))); + } + + hexHasBuildings(gs, hexId) { + return this.geo.hexes[hexId].corners.some((c) => L.nodeBuilding(gs, c)); + } + + floatGain(seat, resource) { + const dst = seat === 0 ? this.seatCardTarget(0, resource) : this.seatCardTarget(seat); + const label = this.add.text(dst.x, dst.y - 40, `+1 ${RESOURCE_INFO[resource].label}`, { + fontFamily: 'Righteous', fontSize: '20px', color: '#ffe27a', stroke: '#1a0d04', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.banner); + this.tweens.add({ targets: label, alpha: 0, y: dst.y - 74, duration: 900, delay: 250, onComplete: () => label.destroy() }); } animateChitPulse(hex) { return new Promise(resolve => { const chit = this.chitByHexId?.[hex.id]; const { x, y } = this.hexPos(hex.id); - const color = RESOURCE_INFO[hex.resource]?.swatch ?? COLORS.accent; - const doParticles = () => { - const emitter = this.add.particles(x, y + 6, 'catanParticle', { - speed: { min: 80, max: 220 }, lifespan: 700, - scale: { start: 1.4, end: 0 }, alpha: { start: 1, end: 0 }, - quantity: 3, frequency: 25, - tint: [color, 0xffffff, 0xffd700], angle: { min: 0, max: 360 }, - }).setDepth(D.chit + 2); - this.time.delayedCall(650, () => emitter.destroy()); - }; - if (!chit) { doParticles(); this.time.delayedCall(800, resolve); return; } + const pf = PARTICLE_FOR[hex.resource]; + // the producing tile glows + const fx = this.hexFxGfx; + const glow = { a: 0.45 }; + const pts = this.hexPoints(hex.id, 0.92); this.tweens.add({ - targets: chit, scale: 1.6, duration: 200, ease: 'Back.easeOut', + targets: glow, a: 0, duration: 900, ease: 'Quad.Out', + onUpdate: () => { fx.clear(); fx.fillStyle(0xfff0c0, glow.a); fx.fillPoints(pts, true); }, + onComplete: () => fx.clear(), + }); + const doParticles = () => { + const emitter = this.add.particles(x, y + 6, pf?.key ?? 'catanParticle', { + speed: { min: 70, max: 190 }, lifespan: 950, + angle: { min: -160, max: -20 }, gravityY: pf?.gravity ?? 120, + rotate: { min: 0, max: 360 }, + scale: { start: 1.1, end: 0.3 }, alpha: { start: 1, end: 0 }, + tint: pf?.tint ?? [RESOURCE_INFO[hex.resource]?.swatch ?? COLORS.accent, 0xffffff, 0xffd700], + emitting: false, + }).setDepth(D.fx); + emitter.explode(22); + this.time.delayedCall(1100, () => emitter.destroy()); + }; + if (!chit) { doParticles(); this.time.delayedCall(700, resolve); return; } + const k = chit.scaleX || 1; + this.tweens.add({ + targets: chit, scale: k * 1.5, duration: 200, ease: 'Back.easeOut', onComplete: () => { doParticles(); - this.time.delayedCall(350, () => this.tweens.add({ - targets: chit, scale: 1, duration: 200, ease: 'Back.easeIn', - onComplete: () => this.time.delayedCall(80, resolve), + this.time.delayedCall(320, () => this.tweens.add({ + targets: chit, scale: k, duration: 200, ease: 'Back.easeIn', + onComplete: () => this.time.delayedCall(60, resolve), })); }, }); }); } - animateCardFlight(seat, resource) { - return new Promise(resolve => { - const frameIdx = RESOURCE_TYPES.indexOf(resource); - const src = this.bankCardPos?.[resource] ?? { x: 1562, y: 400 }; - const dst = this.portraitPos(seat); - const cardW = 81, cardH = 117; - - const img = this.add.image(0, 0, 'catan-cards', frameIdx).setDisplaySize(cardW, cardH); - const border = this.add.graphics(); - border.lineStyle(3, RESOURCE_INFO[resource].swatch, 1); - border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 5); - const container = this.add.container(src.x, src.y, [img, border]).setDepth(D.banner - 1); - + // The robber sits on a rolled hex: a red "blocked" stamp instead of production. + animateBlocked(hex) { + return new Promise((resolve) => { + const { x, y } = this.hexPos(hex.id); + const t = this.add.text(x, y - 10, 'BLOCKED', { + fontFamily: 'Righteous', fontSize: '22px', color: '#ff7a6a', stroke: '#1a0d04', strokeThickness: 5, + }).setOrigin(0.5).setDepth(D.fx).setScale(1.8).setAlpha(0).setAngle(-8); + if (this.robberObj) this.tweens.add({ targets: this.robberObj, x: this.robberObj.x + 4, duration: 50, yoyo: true, repeat: 3 }); this.tweens.add({ - targets: container, x: dst.x, y: dst.y, duration: 1000, ease: 'Quad.InOut', - onComplete: () => { - playSound(this, SFX.CASINO_WIN); - container.destroy(); - const radius = seat === 0 ? 64 : 56; - const label = this.add.text(dst.x + radius + 10, dst.y, - RESOURCE_INFO[resource].label.toUpperCase(), { - fontFamily: 'Righteous', fontSize: '26px', color: '#ffd700', - stroke: '#000000', strokeThickness: 3, - }).setOrigin(0, 0.5).setDepth(D.banner); - this.tweens.add({ - targets: label, alpha: 0, y: dst.y - 24, - duration: 700, delay: 300, - onComplete: () => label.destroy(), - }); - this.time.delayedCall(80, resolve); - }, + targets: t, scale: 1, alpha: 1, duration: 220, ease: 'Back.Out', + onComplete: () => this.time.delayedCall(500, () => this.tweens.add({ + targets: t, alpha: 0, y: y - 30, duration: 300, onComplete: () => { t.destroy(); resolve(); }, + })), }); }); } - // ── opponents (left column) ───────────────────────────────────────────────── - buildOpponentPanels() { - this.oppPanels = []; - const aiSeats = this.opponents.length; // human is seat 0 - } - + // ── opponents (left column) ────────────────────────────────────────────────── renderOpponentPanels() { - // build once we know player count - if (this.oppPanels.length) { this.updateOpponentPanels(); return; } - const n = this.gs.playerCount; - const seats = []; - for (let s = 1; s < n; s++) seats.push(s); - const startY = 170, gap = Math.min(250, (820) / seats.length); - seats.forEach((seat, i) => { - const x = 130, y = startY + i * gap; - const opp = this.opponents[seat - 1]; - const portrait = createOpponentPortrait(this, opp, x, y, 56, D.hud); - this.opponentPortraits[seat] = portrait; - const col = PLAYER_COLORS[this.gs.players[seat].colorIndex]; - this.add.circle(x, y, 62, col.hex, 0).setStrokeStyle(4, col.hex, 0.9).setDepth(D.hud + 4); - this.add.text(x, y + 70, this.pname(seat), { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - wordWrap: { width: 180 }, align: 'center', - backgroundColor: 'rgba(0,0,0,0.55)', padding: { x: 6, y: 3 }, - }).setOrigin(0.5, 0).setDepth(D.hud); - const info = this.add.text(x, y + 96, '', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, align: 'center', - backgroundColor: 'rgba(0,0,0,0.55)', padding: { x: 6, y: 3 }, - }).setOrigin(0.5, 0).setDepth(D.hud); - this.oppPanels.push({ seat, info, x, y, cardFan: [], vpBadge: null }); - }); - this.updateOpponentPanels(); - } - - updateOpponentPanels() { - for (const panel of this.oppPanels) { - const p = this.gs.players[panel.seat]; - const cards = L.handSize(p); - const dev = p.devCards.length + p.newDevCards.length; - panel.info.setText(`${dev} dev ${p.knightsPlayed} knights`); - - // VP badge circle above the portrait - if (panel.vpBadge) { panel.vpBadge.destroy(); panel.vpBadge = null; } - const vp = L.publicVictoryPoints(this.gs, panel.seat); - const col = PLAYER_COLORS[p.colorIndex]; - const badgeContainer = this.add.container(panel.x, panel.y - 74).setDepth(D.hud + 5); - const bg = this.add.graphics(); - bg.fillStyle(col.hexDark, 1); bg.fillCircle(0, 0, 18); - bg.lineStyle(2.5, col.hex, 0.9); bg.strokeCircle(0, 0, 18); - const vpText = this.add.text(0, 0, String(vp), { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: col.key === 'white' ? '#000000' : '#ffffff', fontStyle: 'bold', - }).setOrigin(0.5); - badgeContainer.add([bg, vpText]); - panel.vpBadge = badgeContainer; - - // Rebuild face-down card rows to the right of the portrait - if (!panel.cardFan) panel.cardFan = []; - panel.cardFan.forEach(o => o.destroy()); - panel.cardFan = []; - - const cardW = 30, cardH = 43, cardStep = cardW + 3; - const rowStartX = panel.x + 88; - const maxShow = 8; - - // ── Resource cards (side by side) ────────────────────────────────────── - if (cards > 0) { - const frameIdx = this.cardBack?.spriteIndex ?? 0; - const show = Math.min(cards, maxShow); - for (let i = 0; i < show; i++) { - const img = this.add.image(rowStartX + i * cardStep, panel.y, 'cardbacks', frameIdx) - .setDisplaySize(cardW, cardH) - .setDepth(D.hud + 1); - panel.cardFan.push(img); - } - if (cards > maxShow) { - const bx = rowStartX + maxShow * cardStep; - panel.cardFan.push(this.add.text(bx, panel.y, `+${cards - maxShow}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#ffd700', - stroke: '#000000', strokeThickness: 3, - }).setOrigin(0, 0.5).setDepth(D.hud + 20)); - } - } - - // ── Dev cards (face-down, using dev card back) ───────────────────────── - const devTotal = p.devCards.length + p.newDevCards.length + (p.vpCards ?? 0); - if (devTotal > 0) { - const devY = panel.y + cardH + 5; - const devShow = Math.min(devTotal, maxShow); - for (let i = 0; i < devShow; i++) { - const img = this.add.image(rowStartX + i * cardStep, devY, 'catan-cards', 8) - .setDisplaySize(cardW, cardH) - .setDepth(D.hud + 1); - panel.cardFan.push(img); - } - if (devTotal > maxShow) { - const bx = rowStartX + maxShow * cardStep; - panel.cardFan.push(this.add.text(bx, devY, `+${devTotal - maxShow}`, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#ffd700', - stroke: '#000000', strokeThickness: 3, - }).setOrigin(0, 0.5).setDepth(D.hud + 20)); - } - } + if (!this.boards) { + this.boards = new CatanBoards(this, D.hud, { + opponents: this.opponents, + cardBackFrame: this.cardBack?.spriteIndex ?? 0, + pname: (s) => this.pname(s), + }).build(this.gs); + return; } + this.boards.update(this.gs); } // ── full render ───────────────────────────────────────────────────────────── @@ -1023,508 +964,423 @@ export default class CatanGame extends Phaser.Scene { this.updateBank(); this.renderOpponentPanels(); this.updateButtons(); + this.updateCostCard(); this.updateStatus(); this.updateSpecialCards(); + this.updateHistogram(); } + // Pieces live in a keyed registry so only new pieces animate in. renderPieces() { - this.pieceObjs.forEach((o) => o.destroy()); - this.pieceObjs = []; const N = this.geo.nodes; - // roads + const want = new Map(); for (const p of this.gs.players) { - const col = PLAYER_COLORS[p.colorIndex]; - for (const eid of p.roads) { - const [a, b] = this.geo.edges[eid].nodes; - const g = this.add.graphics().setDepth(D.road); - const ax = N[a].x, ay = N[a].y, bx = N[b].x, by = N[b].y; - g.lineStyle(16, 0xffffff, 0.9); g.lineBetween(ax, ay, bx, by); - g.lineStyle(12, col.hexDark, 1); g.lineBetween(ax, ay, bx, by); - g.lineStyle(7, col.hex, 1); g.lineBetween(ax, ay, bx, by); - this.pieceObjs.push(g); - } - // ships (Seafarers): dashed maritime route in the player's colour - for (const eid of (p.ships ?? [])) { - const [a, b] = this.geo.edges[eid].nodes; - this.pieceObjs.push(this.makeShip(N[a].x, N[a].y, N[b].x, N[b].y, col)); + const ci = p.colorIndex; + for (const eid of p.roads) want.set(`r${eid}`, { kind: 'road', ci, id: eid }); + for (const eid of (p.ships ?? [])) want.set(`s${eid}`, { kind: 'ship', ci, id: eid }); + for (const nid of p.settlements) want.set(`S${nid}`, { kind: 'settlement', ci, id: nid }); + for (const nid of p.cities) want.set(`C${nid}`, { kind: 'city', ci, id: nid }); + } + if (this.gs.pirateHex != null) want.set(`P${this.gs.pirateHex}`, { kind: 'pirate', id: this.gs.pirateHex }); + for (const [key, obj] of this.pieceSprites) { + if (!want.has(key)) { obj.destroy(); this.pieceSprites.delete(key); } + } + for (const [key, spec] of want) { + if (this.pieceSprites.has(key)) continue; + const obj = this.makePiece(spec, N); + this.pieceSprites.set(key, obj); + if (spec.kind !== 'pirate') this.dropIn(obj, spec.kind); + } + this.ensureChimneySmoke(); + } + + makePiece(spec, N) { + const k = this.pieceK; + if (spec.kind === 'road' || spec.kind === 'ship') { + const [a, b] = this.geo.edges[spec.id].nodes; + const ax = N[a].x, ay = N[a].y, bx = N[b].x, by = N[b].y; + const mx = (ax + bx) / 2, my = (ay + by) / 2; + if (spec.kind === 'road') { + const len = Math.hypot(bx - ax, by - ay); + return this.add.image(mx, my, `catan-road-${spec.ci}`) + .setDisplaySize(len * 0.8, 22 * Math.max(0.8, k)).setRotation(Math.atan2(by - ay, bx - ax)) + .setDepth(D.road + my / 10000); } + return this.add.image(mx, my - 6 * k, `catan-ship-${spec.ci}`).setDisplaySize(48 * k, 48 * k) + .setDepth(D.road + 1 + my / 10000); } - // settlements + cities - for (const p of this.gs.players) { - const col = PLAYER_COLORS[p.colorIndex]; - for (const nid of p.settlements) this.pieceObjs.push(this.makeSettlement(N[nid].x, N[nid].y, col)); - for (const nid of p.cities) this.pieceObjs.push(this.makeCity(N[nid].x, N[nid].y, col)); + if (spec.kind === 'pirate') { + const { x, y } = this.hexPos(spec.id); + return this.add.image(x, y, 'catan-pirate').setOrigin(0.5).setDisplaySize(48, 48).setDepth(D.robber); } - // pirate (Seafarers): a sea-robber token on its hex - if (this.gs.pirateHex != null) { - const { x, y } = this.hexPos(this.gs.pirateHex); - this.pieceObjs.push( - this.add.image(x, y, 'catan-pirate').setOrigin(0.5).setDisplaySize(48, 48).setDepth(D.robber) - ); + const { x, y } = N[spec.id]; + if (spec.kind === 'settlement') { + const S = 56 * Math.max(0.75, k); + return this.add.image(x, y, `catan-set-${spec.ci}`).setOrigin(0.5, 0.74).setDisplaySize(S, S) + .setDepth(D.building + y / 10000); } + // city: the body plus two warm windows that breathe + const S = 72 * Math.max(0.75, k); + const img = this.add.image(0, 0, `catan-city-${spec.ci}`).setOrigin(0.5, 0.76).setDisplaySize(S, S); + const w1 = this.add.image(0.06 * S, -0.22 * S, 'catan-window').setDisplaySize(9, 9).setBlendMode(Phaser.BlendModes.ADD); + const w2 = this.add.image(-0.19 * S, -0.03 * S, 'catan-window').setDisplaySize(8, 8).setBlendMode(Phaser.BlendModes.ADD); + const c = this.add.container(x, y, [img, w1, w2]).setDepth(D.building + y / 10000); + for (const w of [w1, w2]) { + this.tweens.add({ targets: w, alpha: { from: 0.35, to: 0.95 }, duration: 1200 + Math.random() * 900, yoyo: true, repeat: -1, delay: Math.random() * 800 }); + } + return c; } - // A ship piece: a thick coloured bar along the sea edge with a sail nub. - makeShip(ax, ay, bx, by, col) { - const g = this.add.graphics().setDepth(D.road); - g.lineStyle(15, 0xffffff, 0.9); g.lineBetween(ax, ay, bx, by); - g.lineStyle(11, col.hexDark, 1); g.lineBetween(ax, ay, bx, by); - g.lineStyle(6, col.hex, 1); g.lineBetween(ax, ay, bx, by); - // sail at the midpoint - const mx = (ax + bx) / 2, my = (ay + by) / 2; - g.fillStyle(0xffffff, 0.95); - g.fillTriangle(mx, my - 16, mx, my + 4, mx + 14, my - 6); - g.lineStyle(2, col.hexDark, 1); - g.strokeTriangle(mx, my - 16, mx, my + 4, mx + 14, my - 6); - return g; + // New pieces drop onto the board with a little squash and a puff of dust. + dropIn(obj, kind) { + const y = obj.y; + const sx = obj.scaleX, sy = obj.scaleY; + obj.setAlpha(0).setY(y - 34).setScale(sx * 1.25, sy * 1.25); + this.tweens.add({ + targets: obj, y, alpha: 1, scaleX: sx, scaleY: sy, duration: 340, ease: 'Quad.In', + onComplete: () => { + this.tweens.add({ targets: obj, scaleY: sy * 0.86, scaleX: sx * 1.08, duration: 70, yoyo: true }); + const dust = this.add.particles(obj.x, y + (kind === 'road' ? 2 : 4), 'catan-p-puff', { + speed: { min: 30, max: 90 }, angle: { min: 0, max: 360 }, lifespan: 520, + scale: { start: 0.55, end: 1.2 }, alpha: { start: 0.7, end: 0 }, emitting: false, + }).setDepth(D.fx); + dust.explode(kind === 'road' ? 7 : 12); + this.time.delayedCall(600, () => dust.destroy()); + }, + }); } - makeSettlement(x, y, col) { - const g = this.add.graphics().setDepth(D.building); - // Drop shadow - g.fillStyle(0x000000, 0.55); g.fillRoundedRect(x - 13, y - 1, 34, 24, 4); - // White halo (3px border around the scaled-up shape) - g.fillStyle(0xffffff, 1); - g.fillRect(x - 16, y - 4, 32, 20); - g.fillTriangle(x - 19, y - 4, x + 19, y - 4, x, y - 21); - // Player color fill (~30% larger than original) - g.fillStyle(col.hex, 1); - g.fillRect(x - 13, y - 4, 26, 17); - g.fillTriangle(x - 16, y - 4, x + 16, y - 4, x, y - 18); - // Dark outline - g.lineStyle(2.5, col.hexDark, 1); g.strokeRect(x - 13, y - 4, 26, 17); - return g; - } - makeCity(x, y, col) { - const g = this.add.graphics().setDepth(D.building); - // Drop shadow - g.fillStyle(0x000000, 0.55); g.fillRoundedRect(x - 19, y - 7, 50, 38, 4); - // White halo (3px border around the scaled-up shape) - g.fillStyle(0xffffff, 1); - g.fillRect(x - 24, y, 27, 21); // lower block halo - g.fillRect(x - 8, y - 10, 32, 32); // tower halo - g.fillTriangle(x - 11, y - 10, x + 26, y - 10, x + 8, y - 26); // roof halo - // Player color fill (~30% larger than original) - g.fillStyle(col.hex, 1); - g.fillRect(x - 21, y, 21, 18); // lower block - g.fillRect(x - 5, y - 10, 26, 29); // tower - g.fillTriangle(x - 8, y - 10, x + 23, y - 10, x + 8, y - 23); // roof - // Dark outlines - g.lineStyle(2.5, col.hexDark, 1); - g.strokeRect(x - 21, y, 21, 18); - g.strokeRect(x - 5, y - 10, 26, 29); - return g; + // A thin curl of smoke from a random settlement or city every so often. + ensureChimneySmoke() { + if (this.smoke) return; + this.smoke = this.add.particles(0, 0, 'catan-p-smoke', { + speedY: { min: -26, max: -14 }, speedX: { min: -3, max: 9 }, lifespan: 2400, + scale: { start: 0.28, end: 0.95 }, alpha: { start: 0.42, end: 0 }, emitting: false, + }).setDepth(D.fx); + this.time.addEvent({ + delay: 650, loop: true, callback: () => { + const homes = [...this.pieceSprites.entries()].filter(([k]) => k[0] === 'S' || k[0] === 'C'); + if (!homes.length) return; + const [key, obj] = homes[Math.floor(Math.random() * homes.length)]; + if (obj.alpha < 1) return; + const S = (key[0] === 'S' ? 56 : 72) * Math.max(0.75, this.pieceK); + const cx = obj.x + (key[0] === 'S' ? 0.1 : 0.12) * S, cy = obj.y - (key[0] === 'S' ? 0.46 : 0.58) * S; + this.smoke.emitParticleAt(cx, cy, 1); + }, + }); } + // ── robber ─────────────────────────────────────────────────────────────────── renderRobber() { - if (this.robberObj) this.robberObj.destroy(); - const { x, y } = this.hexPos(this.gs.robberHex); - this.robberObj = this.add.image(x, y, 'catan-robber') - .setDisplaySize(64, 64) - .setDepth(D.robber); - this.robberObj.postFX.addGlow(0x000000, 8, 0, false, 0.1, 24); + if (this._robberMoving) return; + const id = this.gs.robberHex; + if (id === this._robberAt && this.robberObj?.active) return; + this._robberAt = id; + this.robberObj?.destroy(); this.robberShadow?.destroy(); this.robberDim?.destroy(); + if (id == null) return; + const { x, y } = this.hexPos(id); + this.robberDim = this.add.graphics().setDepth(D.robberDim); + this.robberDim.fillStyle(0x0a0604, 0.42); + this.robberDim.fillPoints(this.hexPoints(id, 0.9), true); + this.robberShadow = this.add.ellipse(x + 6, y + 26, 46, 14, 0x000000, 0.45).setDepth(D.robber - 0.5); + this.robberObj = this.add.image(x, y - 4, 'catan-robber').setDisplaySize(64, 64).setDepth(D.robber); + this.robberObj.postFX?.addGlow(0x000000, 8, 0, false, 0.1, 24); } + // Lift, glide in an arc, then land with a thud and a ring of dust. async animateRobber(fromHexId, toHexId) { const clip = `catan-robber-0${Phaser.Math.Between(1, 4)}`; enqueueSpeech(clip); - if (this.robberObj) this.robberObj.destroy(); + this._robberMoving = true; + this._robberAt = null; + this.robberObj?.destroy(); this.robberShadow?.destroy(); this.robberDim?.destroy(); const from = this.hexPos(fromHexId); const to = this.hexPos(toHexId); - this.robberObj = this.add.image(from.x, from.y, 'catan-robber') - .setDisplaySize(64, 64) - .setDepth(D.robber); - this.robberObj.postFX.addGlow(0x000000, 8, 0, false, 0.1, 24); - const base = this.robberObj.scaleX; - await new Promise(resolve => { - this.tweens.add({ - targets: this.robberObj, - x: to.x, y: to.y, - duration: 3000, - ease: 'Sine.InOut', - }); - this.tweens.chain({ - targets: this.robberObj, - tweens: [ - { scaleX: base * 2, scaleY: base * 2, duration: 1500, ease: 'Sine.Out' }, - { scaleX: base, scaleY: base, duration: 1500, ease: 'Sine.In', onComplete: resolve }, - ], - }); - }); + const robber = this.add.image(from.x, from.y - 4, 'catan-robber').setDisplaySize(64, 64).setDepth(D.flight); + robber.postFX?.addGlow(0x000000, 8, 0, false, 0.1, 24); + const shadow = this.add.ellipse(from.x + 6, from.y + 26, 46, 14, 0x000000, 0.45).setDepth(D.robber - 0.5); + const base = robber.scaleX; + await new Promise((resolve) => this.tweens.add({ targets: robber, y: from.y - 40, scale: base * 1.25, duration: 260, ease: 'Quad.Out', onComplete: resolve })); + const p = { t: 0 }; + const dist = Math.hypot(to.x - from.x, to.y - from.y); + await new Promise((resolve) => this.tweens.add({ + targets: p, t: 1, duration: Math.min(1300, 500 + dist * 1.1), ease: 'Sine.InOut', + onUpdate: () => { + const t = p.t; + const lift = 40 + Math.sin(Math.PI * t) * Math.min(120, dist * 0.35); + robber.setPosition(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t - lift); + shadow.setPosition(from.x + (to.x - from.x) * t + 6 + lift * 0.15, from.y + (to.y - from.y) * t + 26) + .setScale(1 - lift / 400).setAlpha(0.45 - lift / 600); + }, + onComplete: resolve, + })); + await new Promise((resolve) => this.tweens.add({ targets: robber, y: to.y - 4, scale: base, duration: 170, ease: 'Quad.In', onComplete: resolve })); + shadow.setScale(1).setAlpha(0.45); + this.cameras.main.shake(140, 0.0025); + playSound(this, SFX.PIECE_CLICK); + const dust = this.add.particles(to.x, to.y + 24, 'catan-p-puff', { + speed: { min: 60, max: 150 }, angle: { min: 0, max: 360 }, lifespan: 600, + scale: { start: 0.7, end: 1.5 }, alpha: { start: 0.6, end: 0 }, emitting: false, + }).setDepth(D.fx); + dust.explode(16); + this.time.delayedCall(700, () => dust.destroy()); + robber.destroy(); shadow.destroy(); + this._robberMoving = false; + this.renderRobber(); } + // ── paying / buying (cards fly to the caddy) ───────────────────────────────── async animateCostPayment(seat, type) { - const cost = COSTS[type]; + // Road Building's free roads (and any free ships) cost nothing. + if (type === 'road' && this.gs.freeRoads > 0) return; + if (type === 'ship' && this.gs.freeShips > 0) return; + const cost = type === 'ship' ? L.shipCost(this.gs) : COSTS[type]; if (!cost) return; const resources = []; for (const [r, n] of Object.entries(cost)) for (let i = 0; i < n; i++) resources.push(r); - const isHuman = seat === 0; - const usedHandIdxs = new Set(); - let oppCardOffset = 0; - for (const resource of resources) { - const frameIdx = RESOURCE_TYPES.indexOf(resource); - const bankPos = this.bankCardPos?.[resource] ?? { x: 1562, y: 400 }; - let srcX, srcY, startFaceUp; - if (isHuman) { - startFaceUp = true; - let ci = -1; - for (let i = 0; i < this.handDisplay.length; i++) { - if (!usedHandIdxs.has(i) && this.handDisplay[i] === resource) { ci = i; usedHandIdxs.add(i); break; } - } - srcX = (ci >= 0 && this.handCardObjs[ci]) ? this.handCardObjs[ci].x : 90; - srcY = (ci >= 0 && this.handCardObjs[ci]) ? this.handCardObjs[ci].y : 950; - } else { - startFaceUp = false; - const panel = this.oppPanels.find(p => p.seat === seat); - if (panel?.cardFan[oppCardOffset]) { - srcX = panel.cardFan[oppCardOffset].x; - srcY = panel.cardFan[oppCardOffset].y; - } else { - const pos = this._seatPortraitPos(seat); - srcX = (pos?.x ?? 130) + 88 + oppCardOffset * 33; - srcY = pos?.y ?? 300; - } - oppCardOffset++; - } - await this._flyCardToBank(srcX, srcY, frameIdx, bankPos, startFaceUp); - } + await this.flyCardsToBank(seat, resources); } - _flyCardToBank(srcX, srcY, frameIdx, bankPos, startFaceUp) { - return new Promise(resolve => { - const cardW = 60, cardH = 84; - const bigW = 90, bigH = 126; - const resource = RESOURCE_TYPES[frameIdx]; - - const makeBorder = (color) => { - const g = this.add.graphics(); - g.lineStyle(3, color, 1); - g.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 5); - return g; - }; - - if (startFaceUp) { - // Human card: already face-up, just fly to bank. - const img = this.add.image(0, 0, 'catan-cards', frameIdx).setDisplaySize(cardW, cardH); - const border = makeBorder(RESOURCE_INFO[resource]?.swatch ?? COLORS.accent); - const container = this.add.container(srcX, srcY, [img, border]).setDepth(D.banner); - this.tweens.add({ - targets: container, x: bankPos.x, y: bankPos.y, duration: 600, ease: 'Quad.InOut', - onComplete: () => this.tweens.add({ - targets: container, alpha: 0, duration: 200, - onComplete: () => { container.destroy(); resolve(); }, - }), - }); - return; - } - - // Opponent card: show face-down → flip → resize → fly. - const img = this.add.image(0, 0, 'cardbacks', this.cardBack?.spriteIndex ?? 0).setDisplaySize(cardW, cardH); - const border = makeBorder(COLORS.accent); - const container = this.add.container(srcX, srcY, [img, border]).setDepth(D.banner); - - // Brief beat so the player can register the face-down card. - this.time.delayedCall(120, () => { - // Flip first half: collapse container width to 0. - this.tweens.add({ - targets: container, scaleX: 0, duration: 110, ease: 'Linear', - onComplete: () => { - // Swap to face-up artwork and recolor border (hidden at scaleX=0). - img.setTexture('catan-cards', frameIdx).setDisplaySize(cardW, cardH); - border.clear(); - border.lineStyle(3, RESOURCE_INFO[resource]?.swatch ?? COLORS.accent, 1); - border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 5); - // Flip second half: restore width. - this.tweens.add({ - targets: container, scaleX: 1, duration: 110, ease: 'Linear', - onComplete: () => { - // Scale up to bank card size with a little bounce. - this.tweens.add({ - targets: container, scaleX: bigW / cardW, scaleY: bigH / cardH, - duration: 230, ease: 'Back.Out', - onComplete: () => { - // Now fly to the bank. - this.tweens.add({ - targets: container, x: bankPos.x, y: bankPos.y, duration: 720, ease: 'Quad.InOut', - onComplete: () => this.tweens.add({ - targets: container, alpha: 0, duration: 180, - onComplete: () => { container.destroy(); resolve(); }, - }), - }); - }, - }); - }, - }); - }, - }); + // Cards leave a hand (piles for the human, the face-down fan for an AI) and + // land on the top of their stack in the caddy, which grows card by card. + flyCardsToBank(seat, resources, gap = 120) { + const human = seat === 0; + const panel = this.oppPanels.find((p) => p.seat === seat); + return Promise.all(resources.map((resource, i) => { + const from = human + ? this.handPileXY(resource, this.gs.players[0].resources) + : (panel?.cardFan[Math.max(0, panel.cardFan.length - 1 - i)] ?? this.seatCardTarget(seat)); + return this.flyCard({ + from: { x: from.x, y: from.y }, + to: this.caddy.topOf(resource), + face: { kind: 'res', res: resource }, + back: human ? null : { kind: 'back' }, + delay: i * gap, duration: 620, arc: 90, + angle: [human ? 0 : -6, -90], scale: [human ? 1 : 0.6, 1.4], + onLand: () => { this.caddy.nudge(resource, +1); this.caddy.bump(resource); }, + sound: SFX.CARD_PLACE, }); - }); + })); } + // A pawn of the right kind arcs from its owner to the spot, then drops in. animatePiecePlacement(seat, type, destX, destY) { return new Promise(resolve => { const srcPos = this._seatPortraitPos(seat); if (!srcPos) { resolve(); return; } - const col = PLAYER_COLORS[this.gs.players[seat].colorIndex]; - const g = this.add.graphics(); - const container = this.add.container(srcPos.x, srcPos.y, [g]).setDepth(D.banner - 1); - if (type === 'road') { - g.lineStyle(10, 0xffffff, 0.9); g.lineBetween(-13, 0, 13, 0); - g.lineStyle(7, col.hexDark, 1); g.lineBetween(-13, 0, 13, 0); - g.lineStyle(4, col.hex, 1); g.lineBetween(-13, 0, 13, 0); - } else if (type === 'settlement') { - g.fillStyle(0xffffff, 1); - g.fillRect(-11, -3, 22, 15); g.fillTriangle(-14, -3, 14, -3, 0, -17); - g.fillStyle(col.hex, 1); - g.fillRect(-9, -3, 18, 12); g.fillTriangle(-11, -3, 11, -3, 0, -14); - g.lineStyle(2, col.hexDark, 1); g.strokeRect(-9, -3, 18, 12); - } else if (type === 'city') { - g.fillStyle(0xffffff, 1); - g.fillRect(-17, 0, 18, 15); g.fillRect(-6, -9, 21, 24); g.fillTriangle(-9, -9, 17, -9, 6, -22); - g.fillStyle(col.hex, 1); - g.fillRect(-15, 0, 15, 12); g.fillRect(-4, -8, 17, 20); g.fillTriangle(-7, -8, 15, -8, 6, -19); - g.lineStyle(2, col.hexDark, 1); g.strokeRect(-15, 0, 15, 12); g.strokeRect(-4, -8, 17, 20); - } - const emitter = this.add.particles(0, 0, 'catanParticle', { - follow: container, - speed: { min: 25, max: 70 }, - lifespan: 450, - scale: { start: 0.9, end: 0 }, - alpha: { start: 0.85, end: 0 }, - quantity: 2, - frequency: 28, - tint: [col.hex, 0xffffff, col.hexDark], - angle: { min: 0, max: 360 }, - }).setDepth(D.banner - 2); - const duration = 2000; - const arcHeight = Math.max(180, Math.abs(destY - srcPos.y) * 0.7 + 120); - const peakY = Math.min(srcPos.y, destY) - arcHeight; - const half = duration / 2; - this.tweens.add({ targets: container, x: destX, duration, ease: 'Quad.InOut' }); - this.tweens.chain({ - targets: container, tweens: [ - { y: peakY, duration: half, ease: 'Quad.Out' }, - { - y: destY, duration: half, ease: 'Quad.In', onComplete: () => { - emitter.stop(); - container.destroy(); - this.time.delayedCall(500, () => emitter.destroy()); - resolve(); - } - }, - ] + const ci = this.gs.players[seat].colorIndex; + const tex = { road: `catan-road-${ci}`, ship: `catan-ship-${ci}`, settlement: `catan-set-${ci}`, city: `catan-city-${ci}` }[type]; + const size = { road: [56, 16], ship: [44, 44], settlement: [50, 50], city: [62, 62] }[type] ?? [40, 40]; + const piece = this.add.image(srcPos.x, srcPos.y, tex).setDisplaySize(size[0], size[1]).setDepth(D.flight); + const duration = 900; + const arcHeight = Math.max(140, Math.abs(destY - srcPos.y) * 0.5 + 90); + const p = { t: 0 }; + this.tweens.add({ + targets: p, t: 1, duration, ease: 'Sine.InOut', + onUpdate: () => { + const t = p.t; + piece.setPosition(srcPos.x + (destX - srcPos.x) * t, srcPos.y + (destY - 36 - srcPos.y) * t - Math.sin(Math.PI * t) * arcHeight); + piece.setAngle(Math.sin(Math.PI * t * 2) * 12); + }, + onComplete: () => { + this.tweens.add({ targets: piece, alpha: 0, duration: 120, onComplete: () => piece.destroy() }); + resolve(); + }, }); }); } animateDevCardFromBank(seat) { - return new Promise(resolve => { - const bankPos = this.bankCardPos?.dev ?? { x: 1562, y: 701 }; - const destPos = this._seatPortraitPos(seat) ?? { x: 90, y: 980 }; - const cardW = 60, cardH = 84; - - const img = this.add.image(0, 0, 'cardbacks', this.cardBack?.spriteIndex ?? 0).setDisplaySize(cardW, cardH); - const border = this.add.graphics(); - border.lineStyle(3, COLORS.accent, 1); - border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 5); - const container = this.add.container(bankPos.x, bankPos.y, [img, border]).setDepth(D.banner); - - const duration = 1400; - const arcHeight = Math.max(150, Math.abs(destPos.y - bankPos.y) * 0.5 + 100); - const peakY = Math.min(bankPos.y, destPos.y) - arcHeight; - const half = duration / 2; - this.tweens.add({ targets: container, x: destPos.x, duration, ease: 'Quad.InOut' }); - this.tweens.chain({ - targets: container, tweens: [ - { y: peakY, duration: half, ease: 'Quad.Out' }, - { - y: destPos.y, duration: half, ease: 'Quad.In', onComplete: () => { - this.tweens.add({ - targets: container, alpha: 0, scaleX: 1.5, scaleY: 1.5, duration: 280, - onComplete: () => { container.destroy(); resolve(); }, - }); - } - }, - ] - }); + const dest = seat === 0 ? devCardPos(this.devCardCount(), this.devCardCount() + 1) : this.oppPanels.find((p) => p.seat === seat)?.anchors.dev ?? this.portraitPos(seat); + return this.flyCard({ + from: this.caddy.topOf('dev'), to: dest, + face: { kind: 'devback' }, duration: 760, arc: 160, + angle: [-90, 0], scale: [1.4, seat === 0 ? 1 : 0.5], + onStart: () => { this.caddy.nudge('dev', -1); this.caddy.bump('dev'); }, + sound: SFX.CARD_DEAL, }); } + devCardCount() { + const p = this.gs.players[0]; + return p.devCards.length + p.newDevCards.length + (p.vpCards ?? 0); + } + + // ── human hand: one pile per resource ─────────────────────────────────────── updateHand() { const p = this.gs.players[0]; - - // Sync handDisplay with game state, preserving drag order - const updated = [...this.handDisplay]; - for (const r of RESOURCE_TYPES) { - const have = updated.filter(x => x === r).length; - const need = p.resources[r]; - if (have > need) { - let removed = 0; - for (let i = updated.length - 1; i >= 0 && removed < have - need; i--) { - if (updated[i] === r) { updated.splice(i, 1); removed++; } - } - } else { - for (let k = 0; k < need - have; k++) updated.push(r); - } - } - if (JSON.stringify(updated) !== JSON.stringify(this.handDisplay)) this.handSelectedIdx = null; - this.handDisplay = updated; this.renderHand(); - - // VP badge + // VP badge on the portrait's shoulder const col = PLAYER_COLORS[p.colorIndex]; - this.playerVpBadgeGfx.clear(); - this.playerVpBadgeGfx.fillStyle(col.hexDark, 1); this.playerVpBadgeGfx.fillCircle(90, 906, 18); - this.playerVpBadgeGfx.lineStyle(2.5, col.hex, 0.9); this.playerVpBadgeGfx.strokeCircle(90, 906, 18); - this.playerVpText.setText(String(L.victoryPoints(this.gs, 0))); + const bx = PORTRAIT.x + 52, by = PORTRAIT.y - 50; + const g = this.playerVpBadgeGfx; + g.clear(); + g.fillStyle(0x000000, 0.35); g.fillCircle(bx + 1, by + 2, 20); + g.fillStyle(col.hexDark, 1); g.fillCircle(bx, by, 19); + g.lineStyle(2.5, 0xffd34d, 0.95); g.strokeCircle(bx, by, 19); + this.playerVpText.setPosition(bx, by).setText(String(L.victoryPoints(this.gs, 0))) + .setColor(col.key === 'white' ? '#000000' : '#ffffff'); + this.humanRing.clear(); + this.humanRing.lineStyle(4, col.hex, 0.95); this.humanRing.strokeCircle(PORTRAIT.x, PORTRAIT.y, PORTRAIT.r + 4); } - renderHand() { - this.handCardObjs.forEach(c => c.destroy()); - this.handCardObjs = []; - const N = this.handDisplay.length; - if (N === 0) return; - const cardW = 60, cardH = 84, cardR = 6, borderW = 3; - const step = Math.min(66, Math.max(34, 490 / Math.max(N - 1, 1))); + handPileXY(res, resources) { + const groups = handGroups(resources, this.handOrder); + let i = groups.findIndex((g) => g.res === res); + let n = groups.length; + if (i < 0) { + // where the pile will appear + const withIt = handGroups({ ...resources, [res]: Math.max(1, resources[res] + 1) }, this.handOrder); + i = withIt.findIndex((g) => g.res === res); n = withIt.length; + } + const pos = handPilePos(i, n); + const cnt = Math.max(1, resources[res]); + const top = pileCardPose(cnt - 1, cnt); + return { x: pos.x + top.dx, y: pos.y + top.dy }; + } - this.handDisplay.forEach((resource, idx) => { - const x = 220 + idx * step; - const frameIdx = RESOURCE_TYPES.indexOf(resource); - const c = this.add.container(x, 950).setDepth(D.hud + idx); - - const bg = this.add.graphics(); - bg.fillStyle(0x111111, 0.85); - bg.fillRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, cardR); - const img = this.add.image(0, 0, 'catan-cards', frameIdx).setDisplaySize(54, 78); - const border = this.add.graphics(); - border.lineStyle(borderW, RESOURCE_INFO[resource].swatch, 1); - border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, cardR); - c.add([bg, img, border]); - - if (idx === this.handSelectedIdx) { - const sel = this.add.graphics(); - sel.lineStyle(3, 0xffd700, 1); - sel.strokeRoundedRect(-cardW / 2 - 3, -cardH / 2 - 3, cardW + 6, cardH + 6, cardR + 2); - c.add(sel); - c.setScale(1.1).setDepth(D.hud + 20); + renderHand(force = false) { + const p = this.gs.players[0]; + const sig = JSON.stringify(p.resources) + this.handOrder.join(); + if (!force && sig === this._handSig && this.handPiles.every((c) => c.active)) return; + this._handSig = sig; + this.handPiles.forEach((c) => { this.tweens.killTweensOf(c); c.destroy(); }); + this.handPiles = []; + const groups = handGroups(p.resources, this.handOrder); + const n = groups.length; + groups.forEach((grp, i) => { + const pos = handPilePos(i, n); + const pile = this.add.container(pos.x, pos.y).setDepth(D.hud + 2 + i * 0.1); + const vis = Math.min(grp.n, 5); + for (let k = 0; k < vis; k++) { + const pose = pileCardPose(k, grp.n); + const card = this.makeCardSprite({ kind: 'res', res: grp.res }); + card.setPosition(pose.dx, pose.dy).setAngle(pose.rot); + pile.add(card); } - - c.setSize(cardW, cardH).setInteractive(); - this._setupHandDrag(c, idx); - this.handCardObjs.push(c); + if (grp.n > 1) { + const top = pileCardPose(vis - 1, grp.n); + const bx = top.dx + HAND_CARD.w / 2 - 6, by = top.dy - HAND_CARD.h / 2 + 6; + const badge = this.add.graphics(); + badge.fillStyle(0x000000, 0.4); badge.fillCircle(bx + 1, by + 2, 15); + badge.fillStyle(0x1a0f07, 1); badge.fillCircle(bx, by, 14); + badge.lineStyle(2, RESOURCE_INFO[grp.res].swatch, 1); badge.strokeCircle(bx, by, 14); + const t = this.add.text(bx, by, `×${grp.n}`, { fontFamily: 'Righteous', fontSize: '15px', color: '#ffe7a8' }).setOrigin(0.5); + pile.add([badge, t]); + } + pile.res = grp.res; + pile.homeX = pos.x; pile.homeY = pos.y; + pile.setSize(HAND_CARD.w + 12, HAND_CARD.h + 16); + pile.setInteractive({ useHandCursor: true, draggable: true }); + this.setupPileInput(pile, i, n); + this.handPiles.push(pile); }); } - _setupHandDrag(container, idx) { - const THRESHOLD = 8; - let dragging = false, origX = 0, pointerStartX = 0; - let slotIndicator = null; + canBankTrade(res) { + const s = this.gs; + return !this.busy && s.phase === 'action' && s.currentPlayer === 0 + && s.players[0].resources[res] >= L.bestTradeRatio(s, 0, res); + } - const cancelDrag = () => { - if (slotIndicator) { slotIndicator.destroy(); slotIndicator = null; } - this.input.off('pointermove', onSceneMove); - this.input.off('pointerup', onSceneUp); - }; - - const onSceneMove = (ptr) => { - container.x = origX + (ptr.x - pointerStartX); - const N = this.handDisplay.length; - const step = Math.min(66, Math.max(34, 490 / Math.max(N - 1, 1))); - const newIdx = Math.max(0, Math.min(N - 1, Math.round((ptr.x - 220) / step))); - if (!slotIndicator) slotIndicator = this.add.rectangle(0, 950, 6, 84, COLORS.accent, 0.8).setDepth(D.hud + 49); - slotIndicator.x = 220 + newIdx * step - step / 2; - }; - - const onSceneUp = (ptr) => { - cancelDrag(); - dragging = false; - const N = this.handDisplay.length; - const step = Math.min(66, Math.max(34, 490 / Math.max(N - 1, 1))); - const newIdx = Math.max(0, Math.min(N - 1, Math.round((ptr.x - 220) / step))); - if (newIdx !== idx) { - const [card] = this.handDisplay.splice(idx, 1); - this.handDisplay.splice(newIdx, 0, card); - } - this.handSelectedIdx = null; - this.renderHand(); - }; - - container.on('pointerdown', (ptr) => { - origX = container.x; pointerStartX = ptr.x; dragging = false; + setupPileInput(pile, idx, n) { + pile.on('pointerover', () => { + if (pile.dragging) return; + this.tweens.add({ targets: pile, y: pile.homeY - 12, duration: 120, ease: 'Quad.Out' }); + const r = pile.res; + const ratio = L.bestTradeRatio(this.gs, 0, r); + const hint = this.canBankTrade(r) ? `\nDrag to the bank (or click) to trade ${ratio}:1.` : '\nDrag to reorder.'; + this.showInfoTooltip(pile.x, pile.homeY - HAND_CARD.h / 2 - 8, RESOURCE_INFO[r].label, + `You hold ${this.gs.players[0].resources[r]}.${hint}`, RESOURCE_INFO[r].swatch); }); - - container.on('pointermove', (ptr) => { - if (this.handSelectedIdx !== idx) return; - if (!dragging && Math.abs(ptr.x - pointerStartX) >= THRESHOLD) { - dragging = true; - container.setDepth(D.hud + 50); - this.input.on('pointermove', onSceneMove); - this.input.on('pointerup', onSceneUp); - } + pile.on('pointerout', () => { + if (!pile.dragging) this.tweens.add({ targets: pile, y: pile.homeY, duration: 120, ease: 'Quad.Out' }); + this.hideInfoTooltip(); }); - - container.on('pointerup', () => { - if (!dragging) { - // Click: toggle selection - this.handSelectedIdx = this.handSelectedIdx === idx ? null : idx; - this.renderHand(); + pile.on('dragstart', () => { + pile.dragging = true; + this.hideInfoTooltip(); + pile.setDepth(D.flight); + if (this.canBankTrade(pile.res)) this.caddy.setDropHint(true); + }); + pile.on('drag', (ptr, dragX, dragY) => { pile.setPosition(dragX, dragY); }); + pile.on('dragend', (ptr) => { + pile.dragging = false; + this.caddy.setDropHint(false); + const overBank = this.caddy.slotAt(ptr.x, ptr.y); + if (overBank && this.canBankTrade(pile.res)) { + this.renderHand(true); + this.openQuickBankTrade(pile.res); + return; } + const to = handPileIndexAt(ptr.x, n); + if (to !== idx && Math.abs(ptr.y - pile.homeY) < 140) { + const order = this.handOrder.filter((r) => this.gs.players[0].resources[r] > 0); + const [moved] = order.splice(idx, 1); + order.splice(to, 0, moved); + const rest = this.handOrder.filter((r) => !order.includes(r)); + this.handOrder = [...order, ...rest]; + } + this.renderHand(true); + }); + pile.on('pointerup', () => { + if (pile.dragging) return; + if (this.canBankTrade(pile.res) && this.input.activePointer.getDistance() < 6) this.openQuickBankTrade(pile.res); }); } updateDevHand() { - this.devHandContainer.removeAll(true); const p = this.gs.players[0]; const cards = [...p.devCards, ...p.newDevCards.map((c) => c + '*')]; if (p.vpCards) for (let i = 0; i < p.vpCards; i++) cards.push('vp'); + const sig = cards.join() + '|' + cards.map((c) => this.canPlayDevNow(c.replace('*', ''), c.endsWith('*'))).join(); + if (sig === this._devSig) return; + this._devSig = sig; + this.tweens.killTweensOf(this.devHandContainer.list); + this.devHandContainer.removeAll(true); if (!cards.length) { - this.devHandContainer.add(this.add.text(740, 980, '—', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5)); + this.devHandContainer.add(this.add.text(DEV.x + DEV.w / 2, DEV.y + 84, 'none yet', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#9fb5a6', + }).setOrigin(0.5)); return; } - const DEV_VISUAL = { - knight: { frame: 5, border: 0xb03030 }, - roadBuilding: { frame: 6, border: 0x8b5a2b }, - vp: { frame: 7, border: 0xdaa520 }, - monopoly: { frame: 9, border: 0x7b2d8b }, - yearOfPlenty: { frame: 10, border: 0x2d8b57 }, - }; - - const cardW = 60, cardH = 84, cardR = 6, borderW = 3; - const step = 66; - const y = 980; - let x = 740; - - cards.forEach((card) => { + cards.forEach((card, i) => { const isNew = card.endsWith('*'); const type = isNew ? card.slice(0, -1) : card; const visual = DEV_VISUAL[type] ?? { frame: 7, border: COLORS.accent }; - - const bg = this.add.graphics(); - bg.fillStyle(0x111111, 0.85); - bg.fillRoundedRect(x - cardW / 2, y - cardH / 2, cardW, cardH, cardR); - - const img = this.add.image(x, y, 'catan-cards', visual.frame) - .setDisplaySize(54, 78) - .setAlpha(isNew ? 0.5 : 1); - - const border = this.add.graphics(); - border.lineStyle(borderW, visual.border, isNew ? 0.45 : 1); - border.strokeRoundedRect(x - cardW / 2, y - cardH / 2, cardW, cardH, cardR); - - const hit = this.add.rectangle(x, y, cardW, cardH, 0x000000, 0).setInteractive(); - const cx = x, topY = y - cardH / 2; - hit.on('pointerover', () => this.showDevCardTooltip(cx, topY, type, isNew, visual.border)); - hit.on('pointerout', () => this.hideDevCardTooltip()); - - this.devHandContainer.add([bg, img, border, hit]); - x += step; + const { x, y } = devCardPos(i, cards.length); + const c = this.makeCardSprite({ kind: 'dev', type }).setPosition(x, y).setAlpha(isNew ? 0.55 : 1); + const playable = this.canPlayDevNow(type, isNew); + if (playable) { + const glow = this.add.graphics(); + glow.lineStyle(3, 0xffd34d, 0.9); + glow.strokeRoundedRect(x - HAND_CARD.w / 2 - 3, y - HAND_CARD.h / 2 - 3, HAND_CARD.w + 6, HAND_CARD.h + 6, 8); + this.devHandContainer.add(glow); + this.tweens.add({ targets: glow, alpha: { from: 1, to: 0.35 }, duration: 700, yoyo: true, repeat: -1 }); + } + const hit = this.add.rectangle(x, y, HAND_CARD.w, HAND_CARD.h, 0x000000, 0).setInteractive({ useHandCursor: playable }); + const topY = y - HAND_CARD.h / 2; + hit.on('pointerover', () => { this.tweens.add({ targets: c, y: y - 10, duration: 110 }); this.showDevCardTooltip(x, topY - 10, type, isNew, visual.border, playable); }); + hit.on('pointerout', () => { this.tweens.add({ targets: c, y, duration: 110 }); this.hideDevCardTooltip(); }); + hit.on('pointerdown', () => { + if (!this.canPlayDevNow(type, isNew)) return; + this.hideDevCardTooltip(); + this.clearHighlights(); this.placeMode = null; + this.playHumanDev(type); + }); + this.devHandContainer.add([c, hit]); }); } + canPlayDevNow(type, isNew) { + const s = this.gs; + if (isNew || type === 'vp' || this.busy || s.currentPlayer !== 0) return false; + if (s.players[0].playedDevThisTurn) return false; + return s.phase === 'action' || (s.phase === 'rollPhase' && type === 'knight'); + } + updateStatus() { const s = this.gs; let msg = ''; @@ -1541,7 +1397,8 @@ export default class CatanGame extends Phaser.Scene { msg = me ? `Your turn — VP: ${L.victoryPoints(s, 0)}` : `${this.pname(s.currentPlayer)} is playing…`; } this.statusText.setText(msg); - this.logText.setText(s.log[s.log.length - 1] ?? ''); + const line = s.log[s.log.length - 1] ?? ''; + this.logText.setText(line).setVisible(!!line); this._updateTurnIndicator(); } @@ -1550,21 +1407,22 @@ export default class CatanGame extends Phaser.Scene { const me = s.currentPlayer === 0 && !this.busy; const p = s.players[0]; const action = me && s.phase === 'action'; - const set = (k, on) => this.buttons[k]?.setEnabled(!!on); + this.btnState = this.btnState ?? {}; + const set = (k, on) => { this.btnState[k] = !!on; this.buttons[k]?.setEnabled(!!on); }; const hasSettleSpot = action && L.legalSettlementNodes(s, 0, false).length > 0; - const DEBUG_FREE_ROADS_AND_SHIPS = false; const hasRoadSpot = action && L.legalRoadEdges(s, 0, false).length > 0; set('roll', me && s.phase === 'rollPhase'); - set('road', action && hasRoadSpot && (DEBUG_FREE_ROADS_AND_SHIPS && me || L.canAfford(p, COSTS.road) || s.freeRoads > 0)); + set('road', action && hasRoadSpot && (L.canAfford(p, COSTS.road) || s.freeRoads > 0)); const hasShipSpot = action && L.legalShipEdges(s, 0).length > 0; const sCost = L.shipCost(s); - set('ship', hasShipSpot && action && (DEBUG_FREE_ROADS_AND_SHIPS && me || !sCost || L.canAfford(p, sCost) || s.freeShips > 0)); + set('ship', hasShipSpot && action && (!sCost || L.canAfford(p, sCost) || s.freeShips > 0)); set('settlement', hasSettleSpot && L.canAfford(p, COSTS.settlement)); - set('city', action && p.settlements.length > 0 && L.canAfford(p, COSTS.city)); + set('city', action && L.legalCityNodes(s, 0).length > 0 && L.canAfford(p, COSTS.city)); set('buyDev', action && s.devDeck.length > 0 && L.canAfford(p, COSTS.devCard)); - set('playDev', action && p.devCards.some((c) => c !== 'vp')); + set('playDev', action && !p.playedDevThisTurn && p.devCards.some((c) => c !== 'vp')); set('trade', action && L.handSize(p) > 0); set('endTurn', action && (s.freeRoads === 0 || !hasRoadSpot)); + this.tray?.setEnabled(me && s.phase === 'rollPhase'); } // ── highlights ──────────────────────────────────────────────────────────────── @@ -1582,6 +1440,263 @@ export default class CatanGame extends Phaser.Scene { this.highlights.push(dot, zone); } + // ── card movements for trades, steals, dev cards ──────────────────────────── + expandCards(bag) { + const out = []; + for (const r of RESOURCE_TYPES) for (let i = 0; i < (bag[r] || 0); i++) out.push(r); + return out; + } + + // Cards leave the caddy for a seat (gold picks, Year of Plenty, bank trades). + flyCardsFromBank(seat, resources, gap = 140) { + const after = this.gs.players[0].resources; + return Promise.all(resources.map((r, i) => this.flyCard({ + from: this.caddy.topOf(r), + to: this.seatCardTarget(seat, r, after), + face: { kind: 'res', res: r }, + delay: i * gap, duration: 700, arc: 130, + angle: [-90, seat === 0 ? 0 : -6], scale: [1.4, seat === 0 ? 1 : 0.55], + onStart: () => { this.caddy.nudge(r, -1); this.caddy.bump(r); }, + sound: SFX.CARD_PLACE, + }))); + } + + // N of one resource into the caddy, then one of another back out. + async animateBankTrade(seat, give, get) { + const ratio = L.bestTradeRatio(this.gs, seat, give); + await this.flyCardsToBank(seat, Array(ratio).fill(give), 90); + await this.flyCard({ + from: this.caddy.topOf(get), to: this.seatCardTarget(seat, get, { ...this.gs.players[0].resources, [give]: this.gs.players[0].resources[give] - (seat === 0 ? ratio : 0) }), + face: { kind: 'res', res: get }, duration: 680, arc: 130, + angle: [-90, seat === 0 ? 0 : -6], scale: [1.4, seat === 0 ? 1 : 0.55], + onStart: () => { this.caddy.nudge(get, -1); this.caddy.bump(get); }, + sound: SFX.CHIP_BET, + }); + } + + async doBankTrade(give, get) { + if (this.busy) return; + this.busy = true; + this.clearHighlights(); this.placeMode = null; + this.updateButtons(); + await this.animateBankTrade(0, give, get); + this.gs = L.tradeWithBank(this.gs, 0, give, get); + this.busy = false; + this.advance(); + } + + // A compact picker beside the caddy: trade N of `res` for 1 of what? + openQuickBankTrade(res) { + if (!this.canBankTrade(res)) return; + this.hideInfoTooltip(); + const ratio = L.bestTradeRatio(this.gs, 0, res); + const objs = []; + const close = () => objs.forEach((o) => o.destroy()); + const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.35) + .setInteractive().setDepth(D.panel); + overlay.on('pointerdown', close); + objs.push(overlay); + const pw = 420, ph = 250, px = 1250, py = 340; + const g = this.add.graphics().setDepth(D.panel); + g.fillStyle(0x000000, 0.4); g.fillRoundedRect(px - pw / 2 + 4, py - ph / 2 + 6, pw, ph, 14); + g.fillStyle(0x2a190c, 0.98); g.fillRoundedRect(px - pw / 2, py - ph / 2, pw, ph, 14); + g.lineStyle(2.5, 0xc9a24a, 1); g.strokeRoundedRect(px - pw / 2, py - ph / 2, pw, ph, 14); + objs.push(g); + objs.push(this.add.text(px, py - ph / 2 + 28, `Trade ${ratio} ${RESOURCE_INFO[res].label} for…`, { + fontFamily: 'Righteous', fontSize: '22px', color: '#ffe7a8', + }).setOrigin(0.5).setDepth(D.panel + 1)); + const choices = RESOURCE_TYPES.filter((r) => r !== res); + choices.forEach((r, i) => { + const x = px - 1.5 * 92 + i * 92, y = py + 6; + const card = this.makeCardSprite({ kind: 'res', res: r }).setPosition(x, y).setDepth(D.panel + 1); + const ok = this.gs.bank[r] > 0; + card.setAlpha(ok ? 1 : 0.35); + const lbl = this.add.text(x, y + 56, ok ? RESOURCE_INFO[r].label : 'bank empty', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: ok ? '#f2ead8' : '#ff8a7a', + }).setOrigin(0.5).setDepth(D.panel + 1); + objs.push(card, lbl); + if (!ok) return; + const hit = this.add.zone(x, y, HAND_CARD.w + 10, HAND_CARD.h + 10).setInteractive({ useHandCursor: true }).setDepth(D.panel + 2); + hit.on('pointerover', () => card.setScale(1.08)); + hit.on('pointerout', () => card.setScale(1)); + hit.on('pointerdown', () => { close(); this.doBankTrade(res, r); }); + objs.push(hit); + }); + objs.push(new Button(this, px, py + ph / 2 - 26, 'Cancel', close, { variant: 'ghost', width: 140, height: 36, fontSize: 16 }).setDepth(D.panel + 1)); + } + + // The engine already moved a stolen card; show it travelling. + async animateSteal() { + const st = this.gs.lastSteal; + if (!st) return; + this.gs.lastSteal = null; + if (st.victim === 0) { + this._notifyStolenCard(st.resource, this.pname(st.thief), st.thief); + await this.delay(900); + return; + } + const vp = this.oppPanels.find((p) => p.seat === st.victim); + const from = vp?.cardFan[vp.cardFan.length - 1] ?? this.seatCardTarget(st.victim); + const toHuman = st.thief === 0; + await this.flyCard({ + from: { x: from.x, y: from.y }, + to: this.seatCardTarget(st.thief, st.resource, this.gs.players[0].resources), + face: toHuman ? { kind: 'res', res: st.resource } : { kind: 'back' }, + back: toHuman ? { kind: 'back' } : null, + duration: 820, arc: 120, scale: [0.6, toHuman ? 1 : 0.6], sound: SFX.CARD_PLACE, + }); + if (toHuman) this.floatText(this.seatCardTarget(0, st.resource), `Stole ${RESOURCE_INFO[st.resource].label}!`); + } + + floatText(at, msg, color = '#ffe27a') { + const t = this.add.text(at.x, at.y - 50, msg, { + fontFamily: 'Righteous', fontSize: '22px', color, stroke: '#1a0d04', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.banner); + this.tweens.add({ targets: t, y: at.y - 90, alpha: 0, duration: 1100, delay: 350, onComplete: () => t.destroy() }); + } + + // Monopoly pulls cards from every rival; Year of Plenty draws from the caddy. + async animateDevEffect(seat, card, pre, post) { + if (card === 'yearOfPlenty') { + const got = []; + for (const r of RESOURCE_TYPES) for (let i = 0; i < post.players[seat].resources[r] - pre.players[seat].resources[r]; i++) got.push(r); + await this.flyCardsFromBank(seat, got); + } else if (card === 'monopoly') { + const flights = []; + let i = 0; + for (let v = 0; v < pre.playerCount; v++) { + if (v === seat) continue; + for (const r of RESOURCE_TYPES) { + const n = pre.players[v].resources[r] - post.players[v].resources[r]; + for (let k = 0; k < Math.min(n, 5); k++) { + const from = v === 0 ? this.handPileXY(r, pre.players[0].resources) : this.seatCardTarget(v); + flights.push(this.flyCard({ + from, to: this.seatCardTarget(seat, r, post.players[0].resources), + face: { kind: 'res', res: r }, delay: (i++) * 110, duration: 760, arc: 140, + scale: [v === 0 ? 1 : 0.6, seat === 0 ? 1 : 0.6], sound: SFX.CARD_PLACE, + })); + } + } + } + await Promise.all(flights); + } + } + + // ── speech bubbles ─────────────────────────────────────────────────────────── + replyText(reply) { + const pick = (a) => a[Math.floor(Math.random() * a.length)]; + return { + deal: () => pick(['Deal!', 'You have a deal.', 'Sure, why not.']), + lacks: () => pick(["I don't have any.", 'None to spare.']), + needs: () => pick(['I need those.', 'Not giving that up.']), + leader: () => pick(["You're too close to winning!", 'Not helping the leader.']), + poor: () => pick(['Not worth it.', 'Sweeten the deal.', 'No thanks.']), + }[reply.reason]?.() ?? 'Hmm.'; + } + + // A bubble beside a seat. good=true tints it green; onClick makes it a button. + showBubble(seat, text, { duration = 1800, good = null, onClick = null } = {}) { + let ax, ay, tail; + if (seat === 0) { ax = PORTRAIT.x + 40; ay = RAIL.y - 64; tail = 'down'; } + else { + const p = this.oppPanels.find((q) => q.seat === seat); + if (!p) return null; + ax = p.rect.x + p.rect.w + 18; ay = p.y - 30; tail = 'left'; + } + const t = this.add.text(0, 0, text, { + fontFamily: 'Righteous', fontSize: '18px', color: '#2a1a0a', wordWrap: { width: 220 }, align: 'center', + }).setOrigin(0.5); + const w = Math.max(90, t.width + 28), h = t.height + 20; + const cx = tail === 'left' ? ax + w / 2 : ax + w / 2 - 20; + const cy = ay; + const g = this.add.graphics(); + const fill = good === true ? 0xd9f5d0 : good === false ? 0xf7e3d6 : 0xfbf3dd; + const edge = good === true ? 0x3d8b3d : good === false ? 0xa0503a : 0x8a6a34; + g.fillStyle(0x000000, 0.3); g.fillRoundedRect(-w / 2 + 3, -h / 2 + 4, w, h, 12); + g.fillStyle(fill, 1); g.fillRoundedRect(-w / 2, -h / 2, w, h, 12); + g.lineStyle(2, edge, 1); g.strokeRoundedRect(-w / 2, -h / 2, w, h, 12); + if (tail === 'left') { + g.fillStyle(fill, 1); g.fillTriangle(-w / 2 + 1, -8, -w / 2 + 1, 8, -w / 2 - 14, 4); + g.lineStyle(2, edge, 1); g.lineBetween(-w / 2 - 14, 4, -w / 2, -8); g.lineBetween(-w / 2 - 14, 4, -w / 2, 8); + } else { + g.fillStyle(fill, 1); g.fillTriangle(-w / 2 + 14, h / 2 - 1, -w / 2 + 34, h / 2 - 1, -w / 2 + 10, h / 2 + 16); + g.lineStyle(2, edge, 1); g.lineBetween(-w / 2 + 10, h / 2 + 16, -w / 2 + 14, h / 2); g.lineBetween(-w / 2 + 10, h / 2 + 16, -w / 2 + 34, h / 2); + } + const c = this.add.container(cx, cy, [g, t]).setDepth(D.banner + 2).setScale(0.4).setAlpha(0); + this.tweens.add({ targets: c, scale: 1, alpha: 1, duration: 200, ease: 'Back.Out' }); + if (onClick) { + c.setSize(w, h).setInteractive({ useHandCursor: true }); + c.on('pointerover', () => c.setScale(1.06)); + c.on('pointerout', () => c.setScale(1)); + c.on('pointerdown', onClick); + } + const kill = () => { if (c.active) this.tweens.add({ targets: c, alpha: 0, scale: 0.8, duration: 180, onComplete: () => c.destroy() }); }; + if (duration) this.time.delayedCall(duration, kill); + c.kill = kill; + return c; + } + + // The human offers a trade: every opponent answers in a bubble. One taker + // trades at once; several takers let the human click whom to trade with. + async offerToPlayers(give, get) { + this.busy = true; + this.updateButtons(); + const what = (bag) => this.expandCards(bag).reduce((m, r) => ({ ...m, [r]: (m[r] ?? 0) + 1 }), {}); + const desc = (bag) => Object.entries(what(bag)).map(([r, n]) => `${n} ${RESOURCE_INFO[r].label}`).join(' + '); + this.showBubble(0, `${desc(give)} for ${desc(get)}?`, { duration: 2200 }); + await this.delay(500); + const takers = []; + const bubbles = []; + for (let seat = 1; seat < this.gs.playerCount; seat++) { + // AI gives `get` (what we want), receives `give` (what we offer). + const reply = AI.tradeReply(this.gs, seat, get, give, 0); + if (reply.accept) takers.push(seat); + bubbles.push(this.showBubble(seat, this.replyText(reply), { duration: reply.accept ? 0 : 2200, good: reply.accept })); + await this.delay(330); + } + const finish = async (seat) => { + bubbles.forEach((b) => b?.kill?.()); + this.gs = L.executePlayerTrade(this.gs, 0, seat, give, get); + const flights = []; + let i = 0; + for (const r of this.expandCards(give)) flights.push(this.flyCard({ from: this.handPileXY(r, this.gs.players[0].resources), to: this.seatCardTarget(seat), face: { kind: 'res', res: r }, delay: (i++) * 110, duration: 700, arc: 110, scale: [1, 0.6], sound: SFX.CARD_PLACE })); + for (const r of this.expandCards(get)) flights.push(this.flyCard({ from: this.seatCardTarget(seat), to: this.seatCardTarget(0, r, this.gs.players[0].resources), face: { kind: 'res', res: r }, delay: (i++) * 110, duration: 700, arc: -80, scale: [0.6, 1] })); + await Promise.all(flights); + this.flashStatus(`${this.pname(seat)} accepted the trade.`); + this.busy = false; + this.advance(); + }; + if (!takers.length) { + this.flashStatus('No one took that offer — try a different one.'); + this.busy = false; + this.updateButtons(); + return; + } + if (takers.length === 1) { await this.delay(500); await finish(takers[0]); return; } + // several takers: the human picks one + this.flashStatus('Several takers — click whose deal to accept.'); + await new Promise((resolve) => { + const objs = []; + const done = (seat) => { objs.forEach((o) => o.destroy()); resolve(seat); }; + for (const seat of takers) { + const b = bubbles[seat - 1]; + if (!b) continue; + b.kill?.(); + objs.push(this.showBubble(seat, `Deal with ${this.pname(seat)}`, { duration: 0, good: true, onClick: () => done(seat) })); + } + objs.push(new Button(this, 1000, 140, 'Cancel offer', () => done(null), { variant: 'ghost', width: 200, height: 40, fontSize: 17 }).setDepth(D.banner + 2)); + }).then(async (seat) => { + if (seat == null) { + bubbles.forEach((b) => b?.kill?.()); + this.flashStatus('Offer withdrawn.'); + this.busy = false; + this.updateButtons(); + return; + } + await finish(seat); + }); + } + // ── new match / turn driver ───────────────────────────────────────────────── startNewMatch() { this.clearHighlights(); @@ -1596,6 +1711,7 @@ export default class CatanGame extends Phaser.Scene { const names = ['You', ...this.opponents.map((o) => o?.name ?? 'CPU')]; L.setPlayerNames(this.gs, names); this.hexTileFrames = {}; + this.drawFrame(); this.drawHexes(); this.drawPorts(); this.drawChits(); @@ -1677,17 +1793,14 @@ export default class CatanGame extends Phaser.Scene { const pre = AI.choosePreRoll(this.gs, seat); if (pre) { this.gs = L.playKnight(this.gs, seat); - this.renderAll(); await this.delay(400); + await this.animateOppDevCardPlay(seat, 'knight'); + this.renderAll(); await this.delay(300); const m = AI.chooseRobberMove(this.gs, seat); const preRobberHex = this.gs.robberHex; - const preRes0roll = { ...this.gs.players[0].resources }; this.gs = L.moveRobber(this.gs, m.hexId, m.targetSeat); - if (m.targetSeat === 0) { - const stolen = RESOURCE_TYPES.find(r => this.gs.players[0].resources[r] < preRes0roll[r]); - if (stolen) this._notifyStolenCard(stolen, this.pname(seat), seat); - } await this.animateRobber(preRobberHex, m.hexId); - this.renderAll(); await this.delay(400); + await this.animateSteal(); + this.renderAll(); await this.delay(300); } if (this.gs.phase === 'rollPhase') { const preGs = this.gs; @@ -1708,15 +1821,10 @@ export default class CatanGame extends Phaser.Scene { await this.delay(450); const m = AI.chooseRobberMove(this.gs, seat); const preRobberHex = this.gs.robberHex; - const preRes0 = { ...this.gs.players[0].resources }; this.gs = L.moveRobber(this.gs, m.hexId, m.targetSeat); - const animPromise = this.animateRobber(preRobberHex, m.hexId); if (m.targetSeat != null) this.opponentPortraits[seat]?.playEmotion?.('happy'); - if (m.targetSeat === 0) { - const stolen = RESOURCE_TYPES.find(r => this.gs.players[0].resources[r] < preRes0[r]); - if (stolen) this._notifyStolenCard(stolen, this.pname(seat), seat); - } - await animPromise; + await this.animateRobber(preRobberHex, m.hexId); + await this.animateSteal(); this.renderAll(); await this.delay(450); this.busy = false; @@ -1745,23 +1853,21 @@ export default class CatanGame extends Phaser.Scene { if (a.type === 'buyDev') { enqueueSpeech('catan-purchase-development-card'); await this.animateCostPayment(seat, 'devCard'); - playSound(this, SFX.CARD_DEAL); await this.animateDevCardFromBank(seat); } + if (a.type === 'bankTrade') await this.animateBankTrade(seat, a.give, a.get); + const preDev = this.gs; this.gs = this.applyAction(seat, a); if (a.type === 'playDev' && a.card !== 'vp') { await this.animateOppDevCardPlay(seat, a.card, a.resource); + await this.animateDevEffect(seat, a.card, preDev, this.gs); } if (this.gs.phase === 'moveRobber') { const m = AI.chooseRobberMove(this.gs, seat); const preRobberHex = this.gs.robberHex; - const preRes0action = { ...this.gs.players[0].resources }; this.gs = L.moveRobber(this.gs, m.hexId, m.targetSeat); - if (m.targetSeat === 0) { - const stolen = RESOURCE_TYPES.find(r => this.gs.players[0].resources[r] < preRes0action[r]); - if (stolen) this._notifyStolenCard(stolen, this.pname(seat), seat); - } await this.animateRobber(preRobberHex, m.hexId); + await this.animateSteal(); } this.renderAll(); await this.delay(480); @@ -1802,13 +1908,16 @@ export default class CatanGame extends Phaser.Scene { if (!offer) break; const { give, get } = offer; // requester gives `give`, wants `get` exclude.add(get); + this.showBubble(seat, `Anyone have ${RESOURCE_INFO[get].label}? I'll give ${RESOURCE_INFO[give].label}.`, { duration: 2400 }); + await this.delay(650); let done = false; if (this.gs.players[0].resources[get] > 0) { const accepted = await this.promptHumanTrade(seat, give, get); + this.showBubble(0, accepted ? 'Deal!' : 'No thanks.', { duration: 1400, good: accepted }); if (accepted) { this.gs = L.executePlayerTrade(this.gs, seat, 0, { [give]: 1 }, { [get]: 1 }); - playSound(this, SFX.CARD_PLACE); + await this.animateAiTrade(seat, 0, give, get); this.flashStatus(`You traded ${RESOURCE_INFO[get].label} for ${RESOURCE_INFO[give].label} with ${this.pname(seat)}.`); this.renderAll(); done = true; @@ -1820,7 +1929,10 @@ export default class CatanGame extends Phaser.Scene { for (let s = 1; s < this.gs.playerCount; s++) { if (s === seat) continue; // Accepter `s` gives the requested resource and gets the offered one. - if (AI.respondToTrade(this.gs, s, { [get]: 1 }, { [give]: 1 }, seat)) { acc = s; break; } + const reply = AI.tradeReply(this.gs, s, { [get]: 1 }, { [give]: 1 }, seat); + this.showBubble(s, this.replyText(reply), { duration: 1700, good: reply.accept }); + await this.delay(380); + if (reply.accept) { acc = s; break; } } if (acc != null) { this.gs = L.executePlayerTrade(this.gs, seat, acc, { [give]: 1 }, { [get]: 1 }); @@ -1888,30 +2000,13 @@ export default class CatanGame extends Phaser.Scene { } // Two cards crossing between the two seats' portraits. + // Two face-up cards cross between the traders (trades are public). animateAiTrade(fromSeat, toSeat, giveRes, getRes) { - playSound(this, SFX.CARD_PLACE); - const from = this._seatPortraitPos(fromSeat) ?? { x: 130, y: 300 }; - const to = this._seatPortraitPos(toSeat) ?? { x: 130, y: 300 }; - const cardW = 56, cardH = 78; - - const flyCard = (res, src, dst) => new Promise((resolve) => { - const img = this.add.image(0, 0, 'catan-cards', RESOURCE_TYPES.indexOf(res)).setDisplaySize(cardW, cardH); - const border = this.add.graphics(); - border.lineStyle(3, RESOURCE_INFO[res]?.swatch ?? COLORS.accent, 1); - border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 5); - const container = this.add.container(src.x, src.y, [img, border]).setDepth(D.banner + 3); - this.tweens.add({ - targets: container, x: dst.x, y: dst.y, duration: 700, ease: 'Quad.InOut', - onComplete: () => this.tweens.add({ - targets: container, alpha: 0, duration: 220, - onComplete: () => { container.destroy(); resolve(); }, - }), - }); - }); - + const res0 = this.gs.players[0].resources; + const at = (seat, res) => (seat === 0 ? this.seatCardTarget(0, res, res0) : this.seatCardTarget(seat)); return Promise.all([ - flyCard(giveRes, from, to), - flyCard(getRes, to, from), + this.flyCard({ from: at(fromSeat, giveRes), to: at(toSeat, giveRes), face: { kind: 'res', res: giveRes }, duration: 760, arc: 120, scale: [0.8, 0.8], sound: SFX.CARD_PLACE }), + this.flyCard({ from: at(toSeat, getRes), to: at(fromSeat, getRes), face: { kind: 'res', res: getRes }, duration: 760, arc: -90, scale: [0.8, 0.8], delay: 80 }), ]); } @@ -2022,14 +2117,18 @@ export default class CatanGame extends Phaser.Scene { if (entry.seat === 0) continue; const picks = AI.chooseGoldPick(this.gs, entry.seat, entry.amount); this.gs = L.resolveGoldPick(this.gs, entry.seat, picks); + await this.flyCardsFromBank(entry.seat, picks); } this.renderAll(); // If human has a pick, let them choose. const humanEntry = this.gs.goldPickQueue.find((e) => e.seat === 0); if (humanEntry) { this.busy = false; - this.pickResources(humanEntry.amount, `Gold Field! Choose ${humanEntry.amount} resource${humanEntry.amount > 1 ? 's' : ''}`, (rs) => { + this.pickResources(humanEntry.amount, `Gold Field! Choose ${humanEntry.amount} resource${humanEntry.amount > 1 ? 's' : ''}`, async (rs) => { this.gs = L.resolveGoldPick(this.gs, 0, rs); + this.busy = true; + await this.flyCardsFromBank(0, rs); + this.busy = false; this.advance(); }); return; @@ -2045,7 +2144,10 @@ export default class CatanGame extends Phaser.Scene { // AI discards first. for (const seat of [...this.gs.discardQueue]) { if (seat === 0) continue; - this.gs = L.applyDiscard(this.gs, seat, AI.chooseDiscard(this.gs, seat)); + const d = AI.chooseDiscard(this.gs, seat); + await this.flyCardsToBank(seat, this.expandCards(d), 70); + this.gs = L.applyDiscard(this.gs, seat, d); + this.renderAll(); } this.renderAll(); if (this.gs.discardQueue.includes(0)) { @@ -2071,6 +2173,7 @@ export default class CatanGame extends Phaser.Scene { const preRobberHex = this.gs.robberHex; this.gs = L.moveRobber(this.gs, hex.id, targets[0] ?? null); await this.animateRobber(preRobberHex, hex.id); + await this.animateSteal(); this.advance(); } else { this.pickStealTarget(hex.id, targets); @@ -2087,6 +2190,7 @@ export default class CatanGame extends Phaser.Scene { const preRobberHex = this.gs.robberHex; this.gs = L.moveRobber(this.gs, hexId, seat); await this.animateRobber(preRobberHex, hexId); + await this.animateSteal(); this.advance(); }); }); @@ -2190,13 +2294,21 @@ export default class CatanGame extends Phaser.Scene { this.gs = L.playRoadBuilding(this.gs, 0); this.advance(); } else if (card === 'monopoly') { - this.pickResources(1, 'Monopolize which resource?', (rs) => { + this.pickResources(1, 'Monopolize which resource?', async (rs) => { + const pre = this.gs; this.gs = L.playMonopoly(this.gs, 0, rs[0]); + this.busy = true; + await this.animateDevEffect(0, 'monopoly', pre, this.gs); + this.busy = false; this.advance(); }); } else if (card === 'yearOfPlenty') { - this.pickResources(2, 'Choose 2 resources', (rs) => { + this.pickResources(2, 'Choose 2 resources', async (rs) => { + const pre = this.gs; this.gs = L.playYearOfPlenty(this.gs, 0, rs[0], rs[1]); + this.busy = true; + await this.animateDevEffect(0, 'yearOfPlenty', pre, this.gs); + this.busy = false; this.advance(); }); } @@ -2264,11 +2376,9 @@ export default class CatanGame extends Phaser.Scene { const tKeys = RESOURCE_TYPES.filter((r) => get[r] > 0); if (gKeys.length === 1 && tKeys.length === 1 && get[tKeys[0]] === 1) { const r = gKeys[0]; - if (give[r] === L.bestTradeRatio(this.gs, 0, r)) { + if (give[r] === L.bestTradeRatio(this.gs, 0, r) && this.gs.bank[tKeys[0]] > 0) { close(); - this.gs = L.tradeWithBank(this.gs, 0, r, tKeys[0]); - playSound(this, SFX.CHIP_BET); - this.advance(); + this.doBankTrade(r, tKeys[0]); return; } } @@ -2279,17 +2389,9 @@ export default class CatanGame extends Phaser.Scene { const gCount = RESOURCE_TYPES.reduce((s, r) => s + give[r], 0); const tCount = RESOURCE_TYPES.reduce((s, r) => s + get[r], 0); if (!gCount || !tCount) { this.flashStatus('Set what you give and get.'); return; } - let accepted = null; - for (let seat = 1; seat < this.gs.playerCount; seat++) { - // AI gives `get` (what we want), receives `give` (what we offer). - if (AI.respondToTrade(this.gs, seat, get, give, 0)) { accepted = seat; break; } - } - if (accepted == null) { this.flashStatus('No opponent accepted that offer.'); return; } + for (const r of RESOURCE_TYPES) if (give[r] && get[r]) { this.flashStatus("You can't give and get the same resource."); return; } close(); - this.gs = L.executePlayerTrade(this.gs, 0, accepted, give, get); - playSound(this, SFX.CARD_PLACE); - this.flashStatus(`${this.pname(accepted)} accepted the trade.`); - this.advance(); + this.offerToPlayers({ ...give }, { ...get }); }, { width: 300, height: 48 }).setDepth(D.panel + 1); const cancelBtn = new Button(this, 1000, 726, 'Cancel', () => close(), { variant: 'ghost', width: 160, height: 44 }).setDepth(D.panel + 1); @@ -2321,9 +2423,11 @@ export default class CatanGame extends Phaser.Scene { objs.push(g, have, val, minus, plus); }); - const confirmBtn = new Button(this, 1000, 640, 'Discard', () => { + const confirmBtn = new Button(this, 1000, 640, 'Discard', async () => { if (sum() !== need) return; objs.forEach((o) => o.destroy()); confirmBtn.destroy(); + this.busy = true; + await this.flyCardsToBank(0, this.expandCards(discard), 70); this.gs = L.applyDiscard(this.gs, 0, discard); this.handleDiscardPhase(); }, { width: 200, height: 48 }).setDepth(D.panel + 1); @@ -2359,14 +2463,8 @@ export default class CatanGame extends Phaser.Scene { // Card animation: grow + spin, then fly to thief portrait const frameIdx = RESOURCE_TYPES.indexOf(resource); const cardW = 60, cardH = 84; - let srcX = 220, srcY = 950; - for (let i = 0; i < this.handDisplay.length; i++) { - if (this.handDisplay[i] === resource && this.handCardObjs[i]) { - srcX = this.handCardObjs[i].x; - srcY = this.handCardObjs[i].y; - break; - } - } + const src = this.handPileXY(resource, this.gs.players[0].resources); + const srcX = src.x, srcY = src.y; const destPos = this._seatPortraitPos(thiefSeat) ?? { x: 130, y: 300 }; const img = this.add.image(0, 0, 'catan-cards', frameIdx).setDisplaySize(cardW, cardH); const border = this.add.graphics(); @@ -2417,124 +2515,18 @@ export default class CatanGame extends Phaser.Scene { // ── game over ───────────────────────────────────────────────────────────────── onGameOver() { this.clearHighlights(); - const winner = this.gs.winner; - const isHuman = winner === 0; + this.tray?.setEnabled(false); this.recordHistory(); - - const PW = 760, PH = 660, PX = 1000, PY = 540; - const titleY = PY - PH / 2 + 70; // 280 - const RADIUS = 80; - const portraitY = titleY + 140; // 420 - const bodyY = portraitY + RADIUS + 95; // 595 - const buttonsY = PY + PH / 2 - 72; // 798 - - // Fireworks across the popup for all winners - const fwEmitter = this.add.particles(PX, PY, 'catanParticle', { - speed: { min: 80, max: 480 }, lifespan: 1400, - scale: { start: 1.2, end: 0 }, alpha: { start: 1, end: 0 }, - quantity: 3, frequency: 35, - tint: [0xffd700, 0xff6644, 0xffffff, 0x44aaff, 0xff44aa, 0x88ff44], - angle: { min: 0, max: 360 }, - emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(-PW / 2, -PH / 2, PW, PH) }, - }).setDepth(D.banner + 8); - this.time.delayedCall(3200, () => { - fwEmitter.stop(); - this.time.delayedCall(1400, () => fwEmitter.destroy()); + showCatanEndScreen(this, { + depth: D.banner, + revealAt: (seat) => { + if (seat === 0) return { x: DEV.x + 40, y: RAIL.y - 70 }; + const p = this.oppPanels.find((q) => q.seat === seat); + return p ? { x: p.rect.x + p.rect.w + 60, y: p.y } : { x: 600, y: 300 }; + }, + onPlayAgain: () => this.scene.restart(this.initData), + onLeave: () => this.scene.start('GameMenu'), }); - - const overlay = this.add.rectangle(PX, PY, PW, PH, 0x0a0e14, 0.94) - .setStrokeStyle(3, COLORS.accent).setDepth(D.banner); - - const title = this.add.text(PX, titleY, isHuman ? 'Victory!' : `${this.pname(winner)} wins`, { - fontFamily: 'Righteous', fontSize: '44px', color: isHuman ? '#ffd700' : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.banner + 1); - - // Portrait backing circle - const backingG = this.add.graphics().setDepth(D.banner + 1); - backingG.fillStyle(0x1a1a2e, 1); - backingG.fillCircle(PX, portraitY, RADIUS + 3); - backingG.fillStyle(COLORS.panel, 1); - backingG.fillCircle(PX, portraitY, RADIUS + 1); - - const size = RADIUS * 2; - let portraitDom = null; - let fallbackSprite = null; - let avatarActive = true; - - if (!isHuman) { - // AI winner: sprite fallback behind, happy video on top - const opp = this.opponents[winner - 1]; - if (opp?.id) { - if (this.textures.exists('opponents')) { - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); - maskG.fillCircle(PX, portraitY, RADIUS); - fallbackSprite = this.add.image(PX, portraitY, 'opponents', opp.spriteIndex ?? 0) - .setDisplaySize(size, size) - .setMask(maskG.createGeometryMask()) - .setDepth(D.banner + 2); - } - const videoEl = document.createElement('video'); - videoEl.muted = true; - videoEl.loop = true; - videoEl.playsInline = true; - videoEl.autoplay = true; - videoEl.style.cssText = `width:${size}px;height:${size}px;border-radius:50%;object-fit:cover;display:block;`; - videoEl.src = `assets/videos/${opp.id}-happy.mp4`; - videoEl.play().catch(() => { }); - videoEl.addEventListener('error', () => { videoEl.style.display = 'none'; }, { once: true }); - portraitDom = this.add.dom(PX, portraitY, videoEl).setDepth(D.banner + 3); - } - } else { - // Human winner: canvas initial placeholder, replaced by avatar if available - const canvasEl = document.createElement('canvas'); - canvasEl.width = size; canvasEl.height = size; - canvasEl.style.cssText = `width:${size}px;height:${size}px;border-radius:50%;display:block;`; - const ctx = canvasEl.getContext('2d'); - const initial = (auth.user?.username ?? 'You').charAt(0).toUpperCase(); - ctx.fillStyle = '#1a1a2e'; - ctx.fillRect(0, 0, size, size); - ctx.fillStyle = COLORS.accentHex; - ctx.font = `bold ${Math.round(RADIUS * 0.9)}px "Julius Sans One", sans-serif`; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - ctx.fillText(initial, size / 2, size / 2); - portraitDom = this.add.dom(PX, portraitY, canvasEl).setDepth(D.banner + 3); - - (async () => { - try { - const { profile } = await api.get('/profile'); - if (!avatarActive || !profile?.avatarPath) return; - const imgEl = document.createElement('img'); - imgEl.style.cssText = `width:${size}px;height:${size}px;border-radius:50%;object-fit:cover;display:block;`; - await new Promise((res, rej) => { imgEl.onload = res; imgEl.onerror = rej; imgEl.src = profile.avatarPath; }); - if (!avatarActive) return; - canvasEl.style.display = 'none'; - this.add.dom(PX, portraitY, imgEl).setDepth(D.banner + 3); - } catch { /* keep initial placeholder */ } - })(); - } - - const lines = this.gs.players - .map((p, i) => `${this.pname(i)}: ${L.victoryPoints(this.gs, i)} VP`) - .join('\n'); - const body = this.add.text(PX, bodyY, lines, { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, align: 'center', - }).setOrigin(0.5).setDepth(D.banner + 1); - - const cleanup = () => { - avatarActive = false; - overlay.destroy(); title.destroy(); body.destroy(); backingG.destroy(); - if (fallbackSprite) fallbackSprite.destroy(); - if (portraitDom) portraitDom.destroy(); - playAgain.destroy(); leave.destroy(); - }; - const playAgain = new Button(this, PX - 110, buttonsY, 'Play Again', () => { - cleanup(); this.startNewMatch(); - }, { width: 200, fontSize: 22 }).setDepth(D.banner + 1); - const leave = new Button(this, PX + 110, buttonsY, 'Leave', () => { - cleanup(); this.scene.start('GameMenu'); - }, { variant: 'ghost', width: 200, fontSize: 22 }).setDepth(D.banner + 1); } async recordHistory() { diff --git a/src/games/catan/CatanLayout.js b/src/games/catan/CatanLayout.js new file mode 100644 index 0000000..215d38d --- /dev/null +++ b/src/games/catan/CatanLayout.js @@ -0,0 +1,251 @@ +// CatanLayout.js — Phaser-free screen layout for the Catan table. +// +// Every piece of furniture has a rect here so tools/verifyCatan.js can check +// that it is on screen, that nothing overlaps, and that the board's wooden sea +// frame stays clear of the HUD for every board (base + Seafarers scenarios). +// +// ┌ left column ┐┌──────── board on the table ────────┐┌ caddy ┐┌ awards ┐ +// │ Leave ││ status / log ││ BANK ││ LR LA │ +// │ opp board 1 ││ ││ ▤ x6 ││buttons │ +// │ opp board 2 ││ wooden sea frame + island ││ ││ │ +// │ opp board 3 ││ │└───────┘└────────┘ +// │ ││ │┌──── dice tray ────┐ +// └─────────────┘└────────────────────────────────────┘└───────────────────┘ +// ═ rail: portrait │ hand │ dev cards │ pieces+awards │ histogram │ costs ═ + +export const W = 1920, H = 1080; + +// The near edge of the table where the human's things sit. +export const RAIL = { x: 0, y: 900, w: W, h: H - 900 }; + +export const LEAVE = { x: 22, y: 14, w: 120, h: 42 }; +export const STATUS = { x: 1000, y: 40 }; +export const LOG = { x: 1000, y: 86 }; + +// Opponent player-boards (left column). +export const OPP_COL = { x: 14, y: 70, w: 456, h: 820 }; +export const OPP_BOARD = { w: 456, h: 262 }; +export function oppBoardRects(count) { + const n = Math.max(1, count); + const gap = Math.min(40, (OPP_COL.h - n * OPP_BOARD.h) / Math.max(1, n - 1)); + const used = n * OPP_BOARD.h + (n - 1) * gap; + const y0 = OPP_COL.y + (OPP_COL.h - used) / 2; + return Array.from({ length: count }, (_, i) => ({ + x: OPP_COL.x, y: Math.round(y0 + i * (OPP_BOARD.h + gap)), w: OPP_BOARD.w, h: OPP_BOARD.h, + })); +} +// Anchor points inside an opponent board. +export function oppBoardAnchors(r) { + return { + portrait: { x: r.x + 82, y: r.y + 104, r: 54 }, + vp: { x: r.x + 30, y: r.y + 30 }, + name: { x: r.x + 82, y: r.y + 172 }, + cards: { x: r.x + 178, y: r.y + 52 }, // first face-down resource card centre + dev: { x: r.x + 178, y: r.y + 124 }, + pieces: { x: r.x + 168, y: r.y + 186 }, // left edge of the pieces-left strip + stats: { x: r.x + 168, y: r.y + 230 }, + }; +} +// Longest Road / Largest Army docked on an opponent's board. +export function oppAwardPos(r, kind) { + return { x: r.x + (kind === 'longestRoad' ? 376 : 418), y: r.y + 124, scale: 0.44 }; +} + +// The bank card caddy (right of the board). +export const CADDY = { x: 1478, y: 14, w: 222, h: 690 }; +export const CADDY_CARD = { w: 126, h: 90 }; // a resource card lying landscape +export const CADDY_SLOTS = ['brick', 'lumber', 'wool', 'grain', 'ore', 'dev']; +export function caddySlot(i) { + const top = CADDY.y + 50 + i * 104; + const x = CADDY.x + 14; + return { + x, y: top, w: CADDY_CARD.w + 22, h: CADDY_CARD.h + 12, + card: { x: x + 6 + CADDY_CARD.w / 2, y: top + 56 }, // the bottom card of the stack + plaque: { x: CADDY.x + CADDY.w - 30, y: top + 51 }, + }; +} + +// Card-edge layers under a stack, ~0.6 per card, capped — 19 reads thick, 1 a +// sliver. Each layer steps right and up, so a stack leans like a real one. +export const STACK_STEP = { dx: -1.0, dy: 0.55 }; +export function stackLayers(count) { + if (!(count > 0)) return 0; + return Math.min(12, Math.ceil(count * 0.6)); +} +// Where the top card of a stack sits (it rises as the stack grows). +export function stackTop(slotIndex, count) { + const { card } = caddySlot(slotIndex); + const n = stackLayers(count); + return { x: card.x - n * STACK_STEP.dx, y: card.y - n * STACK_STEP.dy }; +} + +// Unclaimed Longest Road / Largest Army sit in a pocket above the buttons. +export const AWARDS = { x: 1716, y: 20, w: 198, h: 196 }; +export const AWARD_CARD = { w: 76, h: 106 }; +export function awardHome(kind) { + return { x: AWARDS.x + (kind === 'longestRoad' ? 52 : 146), y: AWARDS.y + 112 }; +} + +// Action buttons (right column). +export const BUTTONS = { x: 1716, y: 228, w: 198, step: 53, h: 44 }; +export function buttonCenter(i) { + return { x: BUTTONS.x + BUTTONS.w / 2, y: BUTTONS.y + BUTTONS.h / 2 + i * BUTTONS.step }; +} +export function buttonsRect(count) { + return { x: BUTTONS.x, y: BUTTONS.y, w: BUTTONS.w, h: (count - 1) * BUTTONS.step + BUTTONS.h }; +} + +// The felt dice tray (lower right, beside the board's corner). +export const TRAY = { x: 1478, y: 734, w: 436, h: 152 }; +export const TRAY_WALL = 16; // wooden wall thickness +export const TRAY_FELT = { x: TRAY.x + TRAY_WALL, y: TRAY.y + TRAY_WALL, w: TRAY.w - TRAY_WALL * 2, h: TRAY.h - TRAY_WALL * 2 }; +export const DIE_SIZE = 34; +// The rolled-total chip: perched on the tray's top-right rim, above the felt +// where the dice land (and drawn beneath the dice, so it can never hide one). +export const TOTAL_CHIP = { x: TRAY.x + TRAY.w - 36, y: TRAY.y - 12, r: 24 }; + +// Camera for the tray: fairly top-down, so the top faces read clearly. +export const TRAY_CAM = { sin: 0.55, cos: 0.835 }; +// The felt in "world" units: depth is stretched so it projects onto the felt rect. +export const TRAY_WORLD = { w: TRAY_FELT.w, h: TRAY_FELT.h / TRAY_CAM.sin }; + +export function trayGround(u, v) { + return { x: TRAY_FELT.x + u, y: TRAY_FELT.y + v * TRAY_CAM.sin, s: 1 }; +} + +// Where a throw starts: the human throws from the near (bottom) side, the AI +// seats from the left (their side of the table). +export function throwOrigin(fromHuman) { + return fromHuman + ? { u: TRAY_WORLD.w * 0.42, v: TRAY_WORLD.h + 70, h: 70 } + : { u: -70, v: TRAY_WORLD.h * 0.5, h: 80 }; +} + + +// The rail (near table edge). +export const PORTRAIT = { x: 90, y: 984, r: 62 }; +export const HAND = { x: 170, y: 908, w: 492, h: 166 }; +export const DEV = { x: 674, y: 908, w: 326, h: 166 }; +export const HUMAN_INFO = { x: 1010, y: 908, w: 182, h: 166 }; +export const HISTO = { x: 1202, y: 908, w: 270, h: 166 }; +export const COSTCARD = { x: 1484, y: 908, w: 428, h: 166 }; + +export const HAND_CARD = { w: 62, h: 88 }; + +// Grouped hand: one pile per resource the player holds, in `order`. +export function handGroups(resources, order) { + return order.filter((r) => resources[r] > 0).map((r) => ({ res: r, n: resources[r] })); +} +// Centre of pile i of n in the hand zone. +export function handPilePos(i, n) { + const pitch = Math.min(96, (HAND.w - HAND_CARD.w - 24) / Math.max(1, n - 1)); + const x0 = HAND.x + HAND_CARD.w / 2 + 10; + return { x: x0 + i * pitch, y: HAND.y + 84, pitch }; +} +// Fan offset of card k inside a pile of n (up to 5 visible). +export function pileCardPose(k, n) { + const vis = Math.min(n, 5); + const kk = Math.min(k, vis - 1); + const spread = vis > 1 ? (kk - (vis - 1) / 2) : 0; + return { dx: spread * 5, dy: -kk * 2.2, rot: spread * 2.4 }; +} +export function handPileIndexAt(x, n) { + if (n <= 0) return -1; + const { pitch } = handPilePos(0, n); + const x0 = handPilePos(0, n).x; + return Math.max(0, Math.min(n - 1, Math.round((x - x0) / pitch))); +} + +// Dev cards on the rail. +export function devCardPos(i, n) { + const step = Math.min(66, (DEV.w - HAND_CARD.w) / Math.max(1, n - 1)); + return { x: DEV.x + HAND_CARD.w / 2 + i * step, y: DEV.y + 82 }; +} + +// Where the human's claimed awards rest on the rail. +export function humanAwardPos(kind) { + return { x: HUMAN_INFO.x + (kind === 'longestRoad' ? 44 : 138), y: HUMAN_INFO.y + 112, scale: 0.62 }; +} + +// ── board frame (hull of the active geometry) ──────────────────────────────── +export const FRAME = { sea: 46, rim: 14 }; + +function convexHull(points) { + const pts = [...points].sort((a, b) => a.x - b.x || a.y - b.y); + const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); + const lower = [], upper = []; + for (const p of pts) { + while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 1e-6) lower.pop(); + lower.push(p); + } + for (let i = pts.length - 1; i >= 0; i--) { + const p = pts[i]; + while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 1e-6) upper.pop(); + upper.push(p); + } + upper.pop(); lower.pop(); + return lower.concat(upper); +} + +// Offset a convex polygon outward by d (miter joins, capped for sharp corners). +export function offsetPolygon(poly, d) { + const n = poly.length; + // orientation + let area = 0; + for (let i = 0; i < n; i++) { const a = poly[i], b = poly[(i + 1) % n]; area += a.x * b.y - b.x * a.y; } + const s = area > 0 ? 1 : -1; + const lines = []; + for (let i = 0; i < n; i++) { + const a = poly[i], b = poly[(i + 1) % n]; + const dx = b.x - a.x, dy = b.y - a.y, l = Math.hypot(dx, dy) || 1; + const nx = (dy / l) * s, ny = (-dx / l) * s; // outward normal + lines.push({ ax: a.x + nx * d, ay: a.y + ny * d, dx, dy, nx, ny }); + } + const out = []; + for (let i = 0; i < n; i++) { + const L1 = lines[(i - 1 + n) % n], L2 = lines[i]; + const den = L1.dx * L2.dy - L1.dy * L2.dx; + const p = poly[i]; + if (Math.abs(den) < 1e-9) { out.push({ x: p.x + L2.nx * d, y: p.y + L2.ny * d }); continue; } + const t = ((L2.ax - L1.ax) * L2.dy - (L2.ay - L1.ay) * L2.dx) / den; + let x = L1.ax + L1.dx * t, y = L1.ay + L1.dy * t; + const k = Math.hypot(x - p.x, y - p.y); + if (k > d * 1.6) { x = p.x + ((x - p.x) / k) * d * 1.6; y = p.y + ((y - p.y) / k) * d * 1.6; } + out.push({ x, y }); + } + return out; +} + +// The island hull and its sea band / wooden rim polygons for a geometry. +export function boardFrame(geo) { + const hull = convexHull(geo.nodes.map((n) => ({ x: n.x, y: n.y }))); + const sea = offsetPolygon(hull, FRAME.sea); + const rim = offsetPolygon(hull, FRAME.sea + FRAME.rim); + const xs = rim.map((p) => p.x), ys = rim.map((p) => p.y); + const bounds = { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) }; + const cx = hull.reduce((t, p) => t + p.x, 0) / hull.length; + const cy = hull.reduce((t, p) => t + p.y, 0) / hull.length; + return { hull, sea, rim, bounds, center: { x: cx, y: cy } }; +} + +// ── checks ─────────────────────────────────────────────────────────────────── +export const rectsOverlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; +export const onScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H; + +// Named furniture rects for overlap checks. +export function hudFurniture({ opponents = 3, buttons = 8 } = {}) { + const f = [ + { name: 'leave', ...LEAVE }, + ...oppBoardRects(opponents).map((r, i) => ({ name: `opp${i + 1}`, ...r })), + { name: 'caddy', ...CADDY }, + { name: 'awards', ...AWARDS }, + { name: 'buttons', ...buttonsRect(buttons) }, + { name: 'tray', ...TRAY }, + { name: 'hand', ...HAND }, + { name: 'dev', ...DEV }, + { name: 'humanInfo', ...HUMAN_INFO }, + { name: 'histo', ...HISTO }, + { name: 'costcard', ...COSTCARD }, + ]; + return f; +} diff --git a/src/games/catan/CatanLogic.js b/src/games/catan/CatanLogic.js index 5393041..08c1785 100644 --- a/src/games/catan/CatanLogic.js +++ b/src/games/catan/CatanLogic.js @@ -35,6 +35,40 @@ export function cloneState(state) { const emptyResources = () => ({ brick: 0, lumber: 0, wool: 0, grain: 0, ore: 0 }); +// Each player's supply of pieces (official limits). A city returns its +// settlement to the supply, which falls out of counting p.settlements. +export const PIECES = { road: 15, settlement: 5, city: 4, ship: 15 }; + +export function piecesLeft(state, seat) { + const p = state.players[seat]; + return { + road: PIECES.road - p.roads.length, + settlement: PIECES.settlement - p.settlements.length, + city: PIECES.city - p.cities.length, + ship: PIECES.ship - (p.ships?.length ?? 0), + }; +} + +// Per-game statistics for the end screen and the roll histogram. JSON-safe. +export function emptyStats(n) { + const perSeat = () => Array.from({ length: n }, () => 0); + return { + rolls: Array.from({ length: 13 }, () => 0), // index = dice total (2..12) + produced: Array.from({ length: n }, () => emptyResources()), + blocked: perSeat(), // cards a seat would have collected but the robber sat on the hex + shortage: perSeat(), // cards withheld because the bank ran short + stolen: perSeat(), // cards this seat stole (robber) + lostToSteal: perSeat(), // cards stolen from this seat + monopolized: perSeat(), // cards taken via Monopoly + discarded: perSeat(), // cards discarded on a 7 + trades: perSeat(), // trades completed (bank or player) + }; +} +function statsOf(s) { + if (!s.stats) s.stats = emptyStats(s.playerCount); + return s.stats; +} + export function handSize(player) { return RESOURCE_TYPES.reduce((s, r) => s + player.resources[r], 0); } @@ -146,6 +180,7 @@ export function createInitialState(playerCount = 3, { tilePlacement = 'random', largestArmy: { owner: null, count: 0 }, winner: null, log: [], + stats: emptyStats(n), }; // Expansion + scenario setup rules (run once). @@ -162,6 +197,7 @@ function logEvent(state, msg) { // ── legality helpers ────────────────────────────────────────────────────────── export function legalSettlementNodes(state, seat, setup = false) { + if (state.players[seat].settlements.length >= PIECES.settlement) return []; const geo = geoFor(state); const out = []; for (const node of geo.nodes) { @@ -193,6 +229,7 @@ export function nodeOnLand(state, nodeId) { } export function legalCityNodes(state, seat) { + if (state.players[seat].cities.length >= PIECES.city) return []; return [...state.players[seat].settlements]; } @@ -225,6 +262,7 @@ function edgeIsLand(state, edgeId) { } export function legalRoadEdges(state, seat, setup = false, fromNode = null) { + if (state.players[seat].roads.length >= PIECES.road) return []; const geo = geoFor(state); const out = []; for (const e of geo.edges) { @@ -300,6 +338,7 @@ export function rollDice(state) { const d2 = 1 + Math.floor(Math.random() * 6); s.dice = [d1, d2]; s.diceTotal = d1 + d2; + statsOf(s).rolls[s.diceTotal]++; logEvent(s, `${playerName(s, s.currentPlayer)} rolled ${d1 + d2}.`); if (s.diceTotal === 7) { s.robberReturnPhase = 'action'; @@ -312,21 +351,66 @@ export function rollDice(state) { return s; } -function produceResources(s, total) { +// Production follows the official bank-shortage rule: tally what every player +// is owed per resource first. If the bank can cover it, everyone is paid. If not, +// nobody collects that resource, unless only one player is owed it, in which +// case they take whatever is left. +export function productionFor(s, total) { const geo = geoFor(s); + const owed = {}; // resource -> seat -> amount + const blocked = {}; // seat -> amount (robber) for (const hex of s.hexes) { - if (hex.number !== total || hex.hasRobber) continue; + if (hex.number !== total) continue; if (hex.kind && hex.kind !== 'land') continue; // sea/gold/fog handled elsewhere if (!RESOURCE_TYPES.includes(hex.resource)) continue; - const corners = geo.hexes[hex.id].corners; - for (const nodeId of corners) { + for (const nodeId of geo.hexes[hex.id].corners) { const bld = nodeBuilding(s, nodeId); if (!bld) continue; const amt = bld.type === 'city' ? 2 : 1; - const give = Math.min(amt, s.bank[hex.resource]); - if (give > 0) { s.players[bld.seat].resources[hex.resource] += give; s.bank[hex.resource] -= give; } + if (hex.hasRobber) { blocked[bld.seat] = (blocked[bld.seat] ?? 0) + amt; continue; } + owed[hex.resource] ??= {}; + owed[hex.resource][bld.seat] = (owed[hex.resource][bld.seat] ?? 0) + amt; } } + const pay = {}; // resource -> seat -> amount actually paid + const shortages = []; // resources nobody collected + for (const [res, bySeat] of Object.entries(owed)) { + const seats = Object.keys(bySeat).map(Number); + const need = seats.reduce((t, k) => t + bySeat[k], 0); + if (need <= s.bank[res]) { pay[res] = { ...bySeat }; continue; } + if (seats.length === 1) { + const left = s.bank[res]; + if (left > 0) pay[res] = { [seats[0]]: left }; + shortages.push({ res, owed: bySeat, paid: left, single: true }); + } else { + shortages.push({ res, owed: bySeat, paid: 0, single: false }); + } + } + return { owed, pay, blocked, shortages }; +} + +function produceResources(s, total) { + const geo = geoFor(s); + const st = statsOf(s); + const { pay: payout, blocked, shortages } = productionFor(s, total); + for (const [res, bySeat] of Object.entries(payout)) { + for (const [seat, amt] of Object.entries(bySeat)) { + s.players[seat].resources[res] += amt; + s.bank[res] -= amt; + st.produced[seat][res] += amt; + } + } + for (const [seat, amt] of Object.entries(blocked)) st.blocked[seat] += amt; + for (const sh of shortages) { + for (const [seat, amt] of Object.entries(sh.owed)) { + const got = sh.single ? sh.paid : 0; + st.shortage[seat] += amt - got; + } + const label = sh.res[0].toUpperCase() + sh.res.slice(1); + logEvent(s, sh.single + ? `Bank low on ${label} — ${playerName(s, Number(Object.keys(sh.owed)[0]))} takes the last ${sh.paid}.` + : `Bank out of ${label} — no one collects it.`); + } // Gold hexes: each settlement/city adjacent earns 1/2 free-choice resources. for (const hex of s.hexes) { if (hex.kind !== 'gold' || hex.number !== total || hex.hasRobber) continue; @@ -374,6 +458,7 @@ export function applyDiscard(state, seat, discard) { s.players[seat].resources[r] -= k; s.bank[r] += k; } + statsOf(s).discarded[seat] += total; s.discardQueue = s.discardQueue.filter((x) => x !== seat); if (s.discardQueue.length === 0) s.phase = 'moveRobber'; return s; @@ -393,6 +478,7 @@ export function moveRobber(state, hexId, targetSeat = null) { const s = cloneState(state); if (s.phase !== 'moveRobber') return s; if (hexId === s.robberHex) return s; + s.lastSteal = null; s.hexes[s.robberHex].hasRobber = false; s.hexes[hexId].hasRobber = true; s.robberHex = hexId; @@ -406,6 +492,9 @@ export function moveRobber(state, hexId, targetSeat = null) { const r = pool[Math.floor(Math.random() * pool.length)]; victim.resources[r]--; s.players[seat].resources[r]++; + statsOf(s).stolen[seat]++; + statsOf(s).lostToSteal[targetSeat]++; + s.lastSteal = { thief: seat, victim: targetSeat, resource: r }; logEvent(s, `${playerName(s, seat)} stole from ${playerName(s, targetSeat)}.`); } } @@ -485,6 +574,7 @@ function shipConnects(state, seat, edge) { export function legalShipEdges(state, seat) { if (!shipCost(state)) return []; + if ((state.players[seat].ships?.length ?? 0) >= PIECES.ship) return []; const geo = geoFor(state); const out = []; for (const e of geo.edges) { @@ -526,7 +616,7 @@ export function buildSettlement(state, seat, nodeId) { export function buildCity(state, seat, nodeId) { const s = cloneState(state); if (s.phase !== 'action' || s.currentPlayer !== seat) return s; - if (!s.players[seat].settlements.includes(nodeId)) return s; + if (!legalCityNodes(s, seat).includes(nodeId)) return s; if (!canAfford(s.players[seat], COSTS.city)) return s; pay(s, s.players[seat], COSTS.city); s.players[seat].settlements = s.players[seat].settlements.filter((x) => x !== nodeId); @@ -583,7 +673,8 @@ export function playRoadBuilding(state, seat) { const s = cloneState(state); if (!canPlayDev(s, seat, 'roadBuilding')) return s; consumeDev(s, seat, 'roadBuilding'); - s.freeRoads = 2; + // Only as many free roads as the supply still holds. + s.freeRoads = Math.min(2, PIECES.road - s.players[seat].roads.length); logEvent(s, `${playerName(s, seat)} played Road Building.`); return s; } @@ -611,6 +702,7 @@ export function playMonopoly(state, seat, resource) { p.resources[resource] = 0; } s.players[seat].resources[resource] += taken; + statsOf(s).monopolized[seat] += taken; logEvent(s, `${playerName(s, seat)} monopolized ${resource} (+${taken}).`); return s; } @@ -643,6 +735,7 @@ export function tradeWithBank(state, seat, giveRes, getRes) { s.bank[giveRes] += ratio; s.players[seat].resources[getRes] += 1; s.bank[getRes] -= 1; + statsOf(s).trades[seat]++; logEvent(s, `${playerName(s, seat)} traded ${ratio} ${giveRes} for 1 ${getRes}.`); return s; } @@ -659,6 +752,8 @@ export function executePlayerTrade(state, fromSeat, toSeat, give, get) { A.resources[r] -= (give[r] || 0); B.resources[r] += (give[r] || 0); B.resources[r] -= (get[r] || 0); A.resources[r] += (get[r] || 0); } + statsOf(s).trades[fromSeat]++; + statsOf(s).trades[toSeat]++; logEvent(s, `${playerName(s, fromSeat)} traded with ${playerName(s, toSeat)}.`); return s; } diff --git a/src/games/catan/CatanTray.js b/src/games/catan/CatanTray.js new file mode 100644 index 0000000..ec08e9b --- /dev/null +++ b/src/games/catan/CatanTray.js @@ -0,0 +1,106 @@ +// CatanTray.js — the felt dice tray with two real 3D dice (one red, one yellow). +// +// The engine rolls first (L.rollDice); roll(faces, from) then plays a planned +// boxed throw (src/ui/dice/Dice3D.js) whose dice are relabelled to land on those +// faces. Human throws come in over the near wall, AI throws over the left wall +// (from the opponents' side of the table). A 7 flashes the felt red. + +import { Die3D, planTrayThrow, poseFromPlan, restingQ } from '../../ui/dice/Dice3D.js'; +import { playSound, SFX } from '../../ui/Sounds.js'; +import { TRAY, TRAY_FELT, DIE_SIZE, TOTAL_CHIP, TRAY_CAM, TRAY_WORLD, trayGround, throwOrigin } from './CatanLayout.js'; +import { PAD } from './CatanArt.js'; + +const BODIES = [ + { body: [196, 36, 36], pip: 0xfdf6e6 }, // red + { body: [238, 196, 58], pip: 0x6b1d10 }, // yellow +]; + +export class CatanTray { + constructor(scene, depth, { onClick } = {}) { + this.scene = scene; + this.depth = depth; + this.onClick = onClick; + this.rolling = false; + this.last = [3, 4]; + } + + build() { + const s = this.scene; + s.add.image(TRAY.x - PAD.tray, TRAY.y - PAD.tray, 'catan-tray').setOrigin(0, 0).setDepth(this.depth); + this.hint = s.add.text(TRAY_FELT.x + TRAY_FELT.w * 0.68, TRAY_FELT.y + TRAY_FELT.h / 2, 'Click to roll', { + fontFamily: 'Righteous', fontSize: '24px', color: '#d9f2e2', + }).setOrigin(0.5).setAlpha(0).setDepth(this.depth + 1); + this.hintTween = s.tweens.add({ targets: this.hint, alpha: { from: 0.25, to: 0.85 }, duration: 800, yoyo: true, repeat: -1, paused: true }); + this.flash = s.add.graphics().setDepth(this.depth + 1).setAlpha(0); + this.flash.fillStyle(0xd02020, 0.6); + this.flash.fillRoundedRect(TRAY_FELT.x, TRAY_FELT.y, TRAY_FELT.w, TRAY_FELT.h, 9); + this.dice = BODIES.map((b) => new Die3D(s, this.depth + 3, { + size: DIE_SIZE, body: b.body, pip: b.pip, sin: TRAY_CAM.sin, cos: TRAY_CAM.cos, ground: trayGround, + })); + this.rest(this.last); + // total chip (pops after a roll) + const cx = TOTAL_CHIP.x, cy = TOTAL_CHIP.y; + const g = s.add.graphics(); + g.fillStyle(0x000000, 0.35); g.fillCircle(2, 3, 24); + g.fillStyle(0xf3e6c4, 1); g.fillCircle(0, 0, 23); + g.lineStyle(3, 0xa5864e, 1); g.strokeCircle(0, 0, 23); + this.totalText = s.add.text(0, -1, '', { fontFamily: 'Righteous', fontSize: '26px', color: '#2a2118' }).setOrigin(0.5); + this.total = s.add.container(cx, cy, [g, this.totalText]).setDepth(this.depth + 2).setScale(0); + // click-to-roll zone over the felt + this.zone = s.add.zone(TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, TRAY.w, TRAY.h).setDepth(this.depth + 6); + this.zone.on('pointerdown', () => { if (this.enabled && !this.rolling) this.onClick?.(); }); + return this; + } + + // Idle: the last roll lies in the left half of the tray. + rest(faces) { + const y = TRAY_WORLD.h * 0.5; + this.dice[0].set(DIE_SIZE * 1.6, y - 6, 0, restingQ(faces[0], 0.25)); + this.dice[1].set(DIE_SIZE * 3.4, y + 8, 0, restingQ(faces[1], -0.35)); + } + + setEnabled(on) { + this.enabled = !!on; + if (on) { this.zone.setInteractive({ useHandCursor: true }); if (this.hintTween.isPaused()) this.hintTween.resume(); } + else { this.zone.disableInteractive(); this.hintTween.pause(); this.hint.setAlpha(0); } + } + + // Throw both dice so they land on `faces`. Resolves after the settle. + roll(faces, fromHuman) { + const s = this.scene; + this.rolling = true; + this.setEnabled(false); + this.total.setScale(0); + const plan = planTrayThrow(TRAY_WORLD, throwOrigin(fromHuman), faces, Math.random, DIE_SIZE); + playSound(s, SFX.DICE_ROLL); + const prox = { t: 0 }; + const apply = (t) => this.dice.forEach((d, i) => { const p = poseFromPlan(plan, i, t); d.set(p.u, p.v, p.h, p.q); }); + apply(0); + return new Promise((resolve) => { + s.tweens.add({ + targets: prox, t: 1, duration: Math.max(700, plan.duration * 1000), ease: 'Linear', + onUpdate: () => apply(prox.t), + onComplete: () => { + apply(1); + this.last = faces; + // settle squash + const sq = { k: 1.12 }; + s.tweens.add({ + targets: sq, k: 1, duration: 160, ease: 'Back.Out', + onUpdate: () => this.dice.forEach((d) => { d.scale = sq.k; d.draw(); }), + }); + const sum = faces[0] + faces[1]; + this.totalText.setText(String(sum)).setColor(sum === 7 ? '#c0392b' : (sum === 6 || sum === 8 ? '#c0392b' : '#2a2118')); + s.tweens.add({ targets: this.total, scale: 1, duration: 260, ease: 'Back.Out' }); + if (sum === 7) { + s.tweens.add({ targets: this.flash, alpha: { from: 0.9, to: 0 }, duration: 700, ease: 'Quad.Out' }); + s.cameras.main.shake(180, 0.003); + } + s.time.delayedCall(220, () => { this.rolling = false; resolve(); }); + }, + }); + }); + } + + diceCenters() { return this.dice.map((d) => d.screenCenter()); } +} diff --git a/src/games/craps/CrapsDice.js b/src/games/craps/CrapsDice.js index b3ff556..b477d1f 100644 --- a/src/games/craps/CrapsDice.js +++ b/src/games/craps/CrapsDice.js @@ -10,6 +10,14 @@ // simulation can be verified under Node. import { P, lift, WALL_U, LANDING, NEAR_VISIBLE_V, VIEW } from './CrapsTable.js'; +// The cube math and renderer are shared (src/ui/dice/Dice3D.js); only the +// craps-specific throw (pyramid wall, landing zone) lives here. +import { + qmul, qaxis, qrot, qnorm, qslerp, randomQ, snapFlat, topFace, relabel, restingQ, poseFromPlan, + norm, Die3D as SharedDie3D, +} from '../../ui/dice/Dice3D.js'; + +export { qmul, qaxis, qrot, topFace, restingQ, poseFromPlan }; // ── Tuning ─────────────────────────────────────────────────────────────────── export const DIE = { size: 30 }; // edge length, px at s = 1 @@ -18,104 +26,6 @@ const VY = VIEW.halfW * (4 / 3); // px per v-unit (the felt is 4 ft deep const SIN_E = 0.7, COS_E = 0.71; // camera elevation used to draw the cubes const G = 2600; // gravity, px/s² const DT = 1 / 240; -const LIGHT = norm([-0.35, 0.45, 0.82]); - -// Local face normals and the pips on them (opposite faces add to 7). -const FACES = [ - { n: [0, 0, 1], label: 1, e1: [1, 0, 0], e2: [0, 1, 0] }, - { n: [0, 0, -1], label: 6, e1: [1, 0, 0], e2: [0, -1, 0] }, - { n: [0, 1, 0], label: 2, e1: [1, 0, 0], e2: [0, 0, 1] }, - { n: [0, -1, 0], label: 5, e1: [-1, 0, 0], e2: [0, 0, 1] }, - { n: [1, 0, 0], label: 3, e1: [0, 1, 0], e2: [0, 0, 1] }, - { n: [-1, 0, 0], label: 4, e1: [0, -1, 0], e2: [0, 0, 1] }, -]; -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]], -}; - -// ── Vector / quaternion helpers ────────────────────────────────────────────── -function norm(v) { const l = Math.hypot(...v) || 1; return v.map(x => x / l); } -const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; - -export function qmul(a, b) { - return [ - a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], - a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2], - a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1], - a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0], - ]; -} -function qnorm(q) { const l = Math.hypot(...q) || 1; return q.map(x => x / l); } -export function qaxis(axis, ang) { - const a = norm(axis), s = Math.sin(ang / 2); - return [Math.cos(ang / 2), a[0] * s, a[1] * s, a[2] * s]; -} -export function qrot(q, v) { - const [w, x, y, z] = q; - const ix = w * v[0] + y * v[2] - z * v[1]; - const iy = w * v[1] + z * v[0] - x * v[2]; - const iz = w * v[2] + x * v[1] - y * v[0]; - const iw = -x * v[0] - y * v[1] - z * v[2]; - return [ - ix * w + iw * -x + iy * -z - iz * -y, - iy * w + iw * -y + iz * -x - ix * -z, - iz * w + iw * -z + ix * -y - iy * -x, - ]; -} -function qslerp(a, b, t) { - let d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; - if (d < 0) { b = b.map(x => -x); d = -d; } - if (d > 0.9995) return qnorm(a.map((x, i) => x + (b[i] - x) * t)); - const th = Math.acos(d), s = Math.sin(th); - const wa = Math.sin((1 - t) * th) / s, wb = Math.sin(t * th) / s; - return a.map((x, i) => x * wa + b[i] * wb); -} -function randomQ(rng) { - const u1 = rng(), u2 = rng(), u3 = rng(); - return [ - Math.sqrt(1 - u1) * Math.sin(2 * Math.PI * u2), Math.sqrt(1 - u1) * Math.cos(2 * Math.PI * u2), - Math.sqrt(u1) * Math.sin(2 * Math.PI * u3), Math.sqrt(u1) * Math.cos(2 * Math.PI * u3), - ]; -} - -// Rotate q so the local axis nearest world-up points exactly up (keeps the yaw). -function snapFlat(q) { - let best = null; - for (const f of FACES) { - const w = qrot(q, f.n); - if (!best || w[2] > best.w[2]) best = { w, f }; - } - const up = [0, 0, 1]; - const ax = cross(best.w, up); - const l = Math.hypot(...ax); - if (l < 1e-9) return q; - return qnorm(qmul(qaxis(ax, Math.acos(Math.min(1, dot(best.w, up)))), q)); -} - -// The label on top for an orientation. -export function topFace(q) { - let best = null; - for (const f of FACES) { - const z = qrot(q, f.n)[2]; - if (!best || z > best.z) best = { z, label: f.label }; - } - return best.label; -} - -// Cube rotation (die frame) that moves the face labelled `target` onto local axis `a`. -function relabel(target, a) { - const t = FACES.find(f => f.label === target).n; - const d = dot(t, a); - if (d > 0.999) return [1, 0, 0, 0]; - if (d < -0.999) { - const perp = Math.abs(t[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; - return qaxis(cross(t, perp), Math.PI); - } - return qaxis(cross(t, a), Math.PI / 2); -} // ── Simulation ─────────────────────────────────────────────────────────────── // origin {u, v, h}; returns { frames: [{u, v, h, q}], u, v } at 120 fps. @@ -219,116 +129,14 @@ export function simulateThrow(origin, faces, rng = Math.random) { return { dice: out, duration: (len - 1) / 120, tries }; } -// A resting orientation showing `face` on top with a given yaw. -export function restingQ(face, yaw = 0) { - const base = relabel(face, [0, 0, 1]); - return qmul(qaxis([0, 0, 1], yaw), base); -} - // ── Rendering ──────────────────────────────────────────────────────────────── -const BODY = [196, 28, 40]; - -function shadeHex(rgb, k) { - const c = rgb.map(x => Math.max(0, Math.min(255, Math.round(x * k)))); - return (c[0] << 16) | (c[1] << 8) | c[2]; -} - -export class Die3D { +// The shared Die3D, wired to the craps tub projection and the red casino body. +export class Die3D extends SharedDie3D { constructor(scene, depth) { - this.scene = scene; - this.shadow = scene.add.graphics().setDepth(depth - 0.5); - this.g = scene.add.graphics().setDepth(depth); - this.state = { u: 0, v: 0, h: 0, q: [1, 0, 0, 0] }; - this.scale = 1; - this.glow = 0; - this.visible = true; + super(scene, depth, { + size: DIE.size, body: [196, 28, 40], pip: 0xfdf6e6, sin: SIN_E, cos: COS_E, + ground: (u, v) => lift(u, v, 0), + center: (u, v) => P.project(u, v), + }); } - - setVisible(v) { this.visible = v; this.g.setVisible(v); this.shadow.setVisible(v); return this; } - - set(u, v, h, q) { Object.assign(this.state, { u, v, h, q }); this.draw(); return this; } - - screenCenter() { - const { u, v, h } = this.state; - const p = P.project(u, v); - const half = DIE.size / 2; - return { x: p.x, y: p.y - (h + half) * COS_E * p.s * this.scale, s: p.s }; - } - - draw() { - const g = this.g, sh = this.shadow; - g.clear(); sh.clear(); - if (!this.visible) return; - const { u, v, h, q } = this.state; - const p = lift(u, v, 0); - const s = p.s * this.scale; - const half = DIE.size / 2; - const hc = h + half; - const proj = (w) => ({ x: p.x + s * w[0], y: p.y + s * (w[1] * SIN_E - (hc + w[2]) * COS_E) }); - - // shadow on the felt - const fade = Math.max(0.12, 0.42 - h / 500); - sh.fillStyle(0x000000, fade); - sh.fillEllipse(p.x + 4 * s + h * 0.04, p.y + 3 * s, DIE.size * 1.25 * s, DIE.size * 0.75 * s); - - if (this.glow > 0) { - g.lineStyle(3, 0xf5d020, this.glow); - g.strokeEllipse(p.x, p.y + 2 * s, DIE.size * 1.7 * s, DIE.size * 1.0 * s); - } - - const cam = [0, SIN_E, COS_E]; - for (const f of FACES) { - const n = qrot(q, f.n); - const facing = dot(n, cam); - if (facing <= 0.02) continue; - const e1 = qrot(q, f.e1), e2 = qrot(q, f.e2); - const c = n.map(x => x * half); - const corner = (a, b) => proj([ - c[0] + (e1[0] * a + e2[0] * b) * half, - c[1] + (e1[1] * a + e2[1] * b) * half, - c[2] + (e1[2] * a + e2[2] * b) * half, - ]); - // slightly chamfered square - const k = 0.82; - const pts = [ - corner(-k, -1), corner(k, -1), corner(1, -k), corner(1, k), - corner(k, 1), corner(-k, 1), corner(-1, k), corner(-1, -k), - ]; - const lit = 0.5 + 0.55 * Math.max(0, dot(n, LIGHT)); - g.fillStyle(shadeHex(BODY, lit), 0.97); - g.fillPoints(pts, true); - g.lineStyle(1, shadeHex(BODY, lit * 0.55), 0.9); - g.strokePoints(pts, true); - // gloss on the top-lit face - if (n[2] > 0.6) { - g.fillStyle(0xffffff, 0.08 + 0.1 * n[2]); - g.fillPoints([corner(-0.75, 0.2), corner(-0.2, 0.75), corner(-0.75, 0.75)], true); - } - // pips - const pipA = Math.min(1, facing * 2.4); - g.fillStyle(0xfdf6e6, 0.95 * pipA); - for (const [a, b] of PIPS[f.label]) { - const ring = []; - for (let i = 0; i < 8; i++) { - const t = (i / 8) * Math.PI * 2; - ring.push(corner(a * 0.52 + Math.cos(t) * 0.17, b * 0.52 + Math.sin(t) * 0.17)); - } - g.fillPoints(ring, true); - } - } - } - - destroy() { this.g.destroy(); this.shadow.destroy(); } -} - -// Play a planned throw on two Die3D objects. `progress` 0…1 drives the frames. -export function poseFromPlan(plan, i, progress) { - const fr = plan.dice[i].frames; - const f = Math.min(fr.length - 1, Math.max(0, progress * (fr.length - 1))); - const a = fr[Math.floor(f)], b = fr[Math.ceil(f)]; - const t = f - Math.floor(f); - return { - u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t, h: a.h + (b.h - a.h) * t, - q: t < 0.5 ? a.q : b.q, - }; } diff --git a/src/games/tickettoride/TicketToRideAI.js b/src/games/tickettoride/TicketToRideAI.js index 7ff8e9e..a23d837 100644 --- a/src/games/tickettoride/TicketToRideAI.js +++ b/src/games/tickettoride/TicketToRideAI.js @@ -1,12 +1,42 @@ -// TicketToRideAI.js — heuristic AI for Ticket to Ride. Pure synchronous -// choose*() functions returning action descriptors; no Phaser, no async. +// TicketToRideAI.js — heuristic AI for Ticket to Ride, scaled by skill (1..5). +// Pure synchronous choose*() functions returning action descriptors; no Phaser. +// +// chooseAction(s, seat, { skill, rng }) → { type:'claimRoute', routeId, payment } +// | { type:'drawTrain', source:'faceUp'|'deck', index? } +// | { type:'drawTickets' } | { type:'pass' } +// chooseSecondDraw(s, seat, { skill, rng }) → drawTrain descriptor or { type:'pass' } +// chooseTicketsToKeep(s, seat, drawn, minKeep, { skill, rng }) → ticket ids +// +// Skill ladder: +// 1–2 the original greedy bot: per-ticket shortest paths, points-minus-cost +// ticket picks, always grabs a face-up locomotive, plus random blunders. +// 3 plans one shared network for all tickets (owned track is free), picks +// ticket SETS against an estimate of how many trains it can still lay, +// draws toward its colour deficits, and saves up for long routes once +// its tickets are done. +// 4 + plans by turns rather than trains (long, high-scoring track wins), +// spends the cards it needs least, rushes contested choke routes, and +// steers spare claims into its longest trail. +// 5 + tighter capacity estimate, runs its trains down when ahead late, +// and blocks an opponent's one-route gap between two of their networks. +// Measured (tools/verifyTicketToRide.js, mirrored 2p): 3 beats 1 ≈ 73%, +// 4 beats 3 ≈ 66%, 5 beats 4 ≈ 55%. +// Every choice is legal: the AI reads L.legalActions() and falls back to a +// pass only when nothing at all is possible. import { - ROUTES, CITIES, ROUTE_ADJ, ROUTE_SCORE, TICKETS, + ROUTES, CITIES, ROUTE_ADJ, ROUTE_SCORE, TICKETS, TRAIN_COLORS, } from './TicketToRideBoard.js'; -import { legalClaims, canDrawTickets } from './TicketToRideLogic.js'; +import * as L from './TicketToRideLogic.js'; const TICKET_BY_ID = TICKETS.reduce((m, t) => { m[t.id] = t; return m; }, {}); +const TW = 0.05; // points nudge in turn-weighted planning +const NOISE = { 1: 0.35, 2: 0.2, 3: 0.06, 4: 0.02, 5: 0 }; + +export const clampSkill = (k) => Math.max(1, Math.min(5, Math.round(k ?? 3))); +const optsOf = (o = {}) => ({ skill: clampSkill(o.skill), rng: o.rng ?? Math.random }); + +export function ticketOf(id) { return TICKET_BY_ID[id]; } // ── connectivity helpers ─────────────────────────────────────────────────────── function seatComponents(s, seat) { @@ -19,29 +49,53 @@ function seatComponents(s, seat) { return find; } -function ticketDone(find, ticket) { - return find(ticket.a) === find(ticket.b); +const ticketDone = (find, t) => find(t.a) === find(t.b); + +// 'own' | 'open' | null — can `seat` use this route in a plan? Respects the +// double-route rules (one seat can't hold both halves; <4 players one side +// closes the pair), so plans never count on track that can't be claimed. +export function routeUse(s, seat, rid) { + const owner = s.claimed[rid]; + if (owner === seat) return 'own'; + if (owner != null) return null; + const r = ROUTES[rid]; + if (r.doubleGroup) { + for (const o of ROUTES) { + if (o.id === rid || o.doubleGroup !== r.doubleGroup) continue; + const oo = s.claimed[o.id]; + if (oo === seat) return null; + if (oo != null && s.playerCount < 4) return null; + } + } + return 'open'; } -// ── shortest path over available routes ──────────────────────────────────────── -// Dijkstra weighted by route length. A route is "available" to `seat` if it is -// unclaimed or already owned by `seat`. Returns { routeIds, cost } or null. -export function shortestRoutePath(s, from, to, seat) { +// ── shortest path over usable routes ─────────────────────────────────────────── +// Dijkstra weighted by route length. Owned track costs 0 (so `cost` is "trains +// still needed"); `free` is an optional Set of planned route ids also costing 0; +// `skip` an optional route id to pretend is gone. Returns +// { routeIds, cost, open: [routeIds still to claim] } or null. +export function shortestRoutePath(s, from, to, seat, { free = null, skip = -1, turns = false } = {}) { const dist = new Map([[from, 0]]); - const prev = new Map(); // cityId -> { routeId, fromCity } + const prev = new Map(); const visited = new Set(); while (true) { let u = null, best = Infinity; for (const [city, d] of dist) { if (!visited.has(city) && d < best) { best = d; u = city; } } - if (u == null) break; - if (u === to) break; + if (u == null || u === to) break; visited.add(u); for (const e of ROUTE_ADJ.get(u) || []) { - const owner = s.claimed[e.routeId]; - if (owner != null && owner !== seat) continue; // opponent owns it - const nd = best + e.length; + if (e.routeId === skip) continue; + const use = routeUse(s, seat, e.routeId); + if (!use) continue; + // A whisker per hop prefers fewer, longer routes among equal-cost paths. + // `turns` weighs a route by the turns it costs (cards to draw + the claim) + // less a nod to its points, so long, high-scoring track wins ties. + const w = (use === 'own' || free?.has(e.routeId)) ? 0 + : turns ? e.length / 2 + 1 - ROUTE_SCORE[e.length] * TW : e.length + 0.01; + const nd = best + w; if (nd < (dist.get(e.other) ?? Infinity)) { dist.set(e.other, nd); prev.set(e.other, { routeId: e.routeId, fromCity: u }); @@ -57,141 +111,354 @@ export function shortestRoutePath(s, from, to, seat) { routeIds.push(p.routeId); cur = p.fromCity; } - return { routeIds, cost: dist.get(to) }; + routeIds.reverse(); + const open = routeIds.filter((rid) => s.claimed[rid] == null); + return { routeIds, open, cost: open.reduce((t, rid) => t + ROUTES[rid].length, 0) }; +} + +// One shared network for a list of tickets: greedy, biggest ticket first, with +// already-planned track free for later tickets. Returns +// { planned:Set(open route ids), cost, unreachable:[ticket] }. +export function planRoutes(s, seat, tickets, { turns = false } = {}) { + const find = seatComponents(s, seat); + const planned = new Set(); + const unreachable = []; + const todo = tickets.filter((t) => !ticketDone(find, t)).sort((a, b) => b.points - a.points); + for (const t of todo) { + const p = shortestRoutePath(s, t.a, t.b, seat, { free: planned, turns }); + if (!p) { unreachable.push(t); continue; } + for (const rid of p.open) planned.add(rid); + } + let cost = 0; + for (const rid of planned) cost += ROUTES[rid].length; + return { planned, cost, unreachable }; +} + +// How many more trains `seat` can realistically lay before the game ends. +function trainCapacity(s, seat, skill) { + const minTrains = Math.min(...s.players.map((p) => p.trainsLeft)); + const turnsLeft = s.finalTurnsLeft != null ? 1 : Math.max(1, (minTrains - 2) / 1.7 + 1); + const hand = L.handCount(s.players[seat]); + const est = (turnsLeft + hand / 2) * 1.2; + const optimism = skill >= 5 ? 0.95 : skill === 4 ? 1.0 : 1.15; + return Math.min(s.players[seat].trainsLeft, est * optimism); +} + +function completionOdds(cost, cap) { + if (cost <= cap * 0.75) return 0.92; + if (cost <= cap) return 0.65; + if (cost <= cap * 1.25) return 0.3; + return 0.1; } // ── ticket selection ─────────────────────────────────────────────────────────── -// Returns the ticket ids to keep from `drawn` (at least minKeep). -export function chooseTicketsToKeep(s, seat, drawn, minKeep) { +export function chooseTicketsToKeep(s, seat, drawn, minKeep, opts) { + const { skill, rng } = optsOf(opts); + if (skill <= 2) return keepGreedy(s, seat, drawn, minKeep, skill, rng); + + const held = s.players[seat].tickets; + const cap = trainCapacity(s, seat, skill); + const value = (tickets) => { + const plan = planRoutes(s, seat, tickets, { turns: skill >= 4 }); + const p = completionOdds(plan.cost, cap); + const find = seatComponents(s, seat); + let v = 0; + for (const t of tickets) { + if (ticketDone(find, t)) { v += t.points; continue; } + const odds = plan.unreachable.includes(t) ? 0 : p; + v += t.points * (2 * odds - 1); + } + return v - plan.cost * 0.15; + }; + const base = value(held); + let best = null; + const n = drawn.length; + for (let mask = 1; mask < (1 << n); mask++) { + const pick = drawn.filter((_, i) => mask & (1 << i)); + if (pick.length < minKeep) continue; + const v = value([...held, ...pick.map(ticketOf)]) - base; + if (!best || v > best.v + 1e-9) best = { v, pick }; + } + return best ? best.pick : drawn.slice(0, minKeep); +} + +function keepGreedy(s, seat, drawn, minKeep, skill, rng) { const scored = drawn.map((id) => { - const t = { ...ticketOf(id) }; + const t = ticketOf(id); const path = shortestRoutePath(s, t.a, t.b, seat); const cost = path ? path.cost : 99; - // Value: reward points, penalise the train cars required to connect. - return { id, value: t.points - cost * 1.1, achievable: !!path, points: t.points }; + return { id, value: t.points - cost * 1.1 + (rng() - 0.5) * (skill === 1 ? 10 : 5), achievable: !!path }; }); scored.sort((a, b) => b.value - a.value); - const keep = scored.slice(0, minKeep).map((x) => x.id); - // Keep additional tickets only if they look clearly worthwhile. - for (const x of scored.slice(minKeep)) { - if (x.achievable && x.value > 0) keep.push(x.id); - } + for (const x of scored.slice(minKeep)) if (x.achievable && x.value > 0) keep.push(x.id); return keep; } -function ticketOf(id) { - // tickets carry resolved {id,a,b,points}; the AI receives ids during setup. - return TICKET_BY_ID[id]; -} - // ── per-turn action ───────────────────────────────────────────────────────────── -// Returns one of: -// { type:'claimRoute', routeId, payment } -// { type:'drawTrain', source:'faceUp'|'deck', index? } -// { type:'drawTickets' } -export function chooseAction(s, seat) { +function context(s, seat, skill) { const player = s.players[seat]; const find = seatComponents(s, seat); - const endgame = s.finalTurnsLeft != null; - - // 1. Wanted routes: union of shortest paths for unfulfilled kept tickets. - const wanted = new Set(); - const wantedColors = new Map(); // color -> desirability weight - for (const t of player.tickets) { - if (ticketDone(find, t)) continue; - const path = shortestRoutePath(s, t.a, t.b, seat); - if (!path) continue; - for (const rid of path.routeIds) { - if (s.claimed[rid] != null) continue; // already owned (by us) — skip - wanted.add(rid); - const col = ROUTES[rid].color; - if (col !== 'gray') wantedColors.set(col, (wantedColors.get(col) || 0) + ROUTES[rid].length); + const open = player.tickets.filter((t) => !ticketDone(find, t)); + let wanted; + if (skill <= 2) { + wanted = new Set(); + for (const t of open) { + const p = shortestRoutePath(s, t.a, t.b, seat); + if (p) p.open.forEach((rid) => wanted.add(rid)); } + } else { + wanted = planRoutes(s, seat, open, { turns: skill >= 4 }).planned; + } + // Colour deficits for the planned track (gray routes count separately). + const need = {}; let grayNeed = 0; + for (const rid of wanted) { + const r = ROUTES[rid]; + if (r.color === 'gray') grayNeed = Math.max(grayNeed, r.length); + else need[r.color] = (need[r.color] || 0) + r.length; + } + const deficit = {}; + for (const c of TRAIN_COLORS) deficit[c] = Math.max(0, (need[c] || 0) - player.hand[c]); + return { player, find, open, wanted, need, grayNeed, deficit }; +} + +export function chooseAction(s, seat, opts) { + const { skill, rng } = optsOf(opts); + const la = L.legalActions(s, seat); + if (!la.any) return { type: 'pass' }; + const ctx = context(s, seat, skill); + const { player, wanted } = ctx; + const endgame = s.finalTurnsLeft != null; + const claims = la.claims; + + // Random blunder (low skill): any legal action, weighted toward draws. + if (rng() < NOISE[skill] * 0.5) { + const r = rng(); + if (claims.length && r < 0.4) return claimDesc(s, seat, claims[Math.floor(rng() * claims.length)], ctx, skill); + return drawDecision(s, seat, ctx, skill, rng, la); } - const claims = legalClaims(s, seat); - const claimById = new Map(claims.map((c) => [c.routeId, c])); - - const scoreClaim = (routeId) => { - const r = ROUTES[routeId]; - return ROUTE_SCORE[r.length] + (wanted.has(routeId) ? 8 : 0) + r.length * 0.6; + const scoreClaim = (c) => { + const r = ROUTES[c.routeId]; + let v = ROUTE_SCORE[r.length] + (wanted.has(c.routeId) ? 8 : 0) + r.length * 0.6; + if (skill >= 4 && wanted.has(c.routeId)) v += contestBonus(s, seat, c.routeId); + return v; }; + const pickBest = (list) => list.reduce((a, b) => (scoreClaim(b) > scoreClaim(a) ? b : a)); - // 2. Claim a wanted route if we can afford one. + // 1. Claim planned track we can afford. const claimableWanted = claims.filter((c) => wanted.has(c.routeId)); - if (claimableWanted.length) { - const best = claimableWanted.reduce((a, b) => (scoreClaim(b.routeId) > scoreClaim(a.routeId) ? b : a)); - return { type: 'claimRoute', routeId: best.routeId, payment: best.payment }; - } + if (claimableWanted.length) return claimDesc(s, seat, pickBest(claimableWanted), ctx, skill); - // 3. Endgame: grab points wherever possible, otherwise draw cards. + // 2. Final round: grab the most points available, else draw. if (endgame) { if (claims.length) { - const best = claims.reduce((a, b) => (scoreClaim(b.routeId) > scoreClaim(a.routeId) ? b : a)); - return { type: 'claimRoute', routeId: best.routeId, payment: best.payment }; + const best = claims.reduce((a, b) => (ROUTE_SCORE[ROUTES[b.routeId].length] > ROUTE_SCORE[ROUTES[a.routeId].length] ? b : a)); + return claimDesc(s, seat, best, ctx, skill); } - return drawDecision(s, seat, wantedColors); + return drawDecision(s, seat, ctx, skill, rng, la); } - // 4. Still have goals but can't afford them yet -> accumulate cards. + // 3. Goals outstanding but unaffordable: maybe block, else build the hand. if (wanted.size > 0) { - return drawDecision(s, seat, wantedColors); + if (skill >= 5) { + const b = findBlock(s, seat, claims); + if (b && rng() < 0.6) return claimDesc(s, seat, b, ctx, skill); + } + return drawDecision(s, seat, ctx, skill, rng, la); } - // 5. All tickets fulfilled: chase more tickets early, else bank route points. - if (canDrawTickets(s) && player.trainsLeft > 15) { - return { type: 'drawTickets' }; - } + // 4. Every ticket done: more tickets while there is room to finish them. + if (la.tickets && wantsMoreTickets(s, seat, skill)) return { type: 'drawTickets' }; + + // 5. Bank route points. Strong players save up for long routes. if (claims.length) { - const best = claims.reduce((a, b) => (scoreClaim(b.routeId) > scoreClaim(a.routeId) ? b : a)); - return { type: 'claimRoute', routeId: best.routeId, payment: best.payment }; - } - return drawDecision(s, seat, wantedColors); -} - -// First train-card draw of the turn: prefer a useful face-up card or locomotive. -function drawDecision(s, seat, wantedColors) { - // A face-up locomotive (first draw) is strong — it counts as the whole turn. - const locoIdx = s.faceUp.indexOf('locomotive'); - if (locoIdx !== -1) return { type: 'drawTrain', source: 'faceUp', index: locoIdx }; - - const idx = bestFaceUpColorIndex(s, wantedColors); - if (idx !== -1) return { type: 'drawTrain', source: 'faceUp', index: idx }; - return { type: 'drawTrain', source: 'deck' }; -} - -// Second draw of the turn (cannot take a face-up locomotive here). -export function chooseSecondDraw(s, seat) { - const player = s.players[seat]; - const find = seatComponents(s, seat); - const wantedColors = new Map(); - for (const t of player.tickets) { - if (ticketDone(find, t)) continue; - const path = shortestRoutePath(s, t.a, t.b, seat); - if (!path) continue; - for (const rid of path.routeIds) { - const col = ROUTES[rid].color; - if (col !== 'gray' && s.claimed[rid] == null) wantedColors.set(col, (wantedColors.get(col) || 0) + 1); + if (skill <= 2) return claimDesc(s, seat, pickBest(claims), ctx, skill); + const handN = L.handCount(player); + const longOnes = claims.filter((c) => ROUTES[c.routeId].length >= 4); + const dumpTime = player.trainsLeft <= 8 || handN >= 14 || (!la.deck && !la.faceUp.length) + || (skill >= 5 && player.trainsLeft <= 14 && leadEstimate(s, seat) >= 0); + const pool = longOnes.length ? longOnes : (dumpTime ? claims : []); + if (pool.length) { + const trailBonus = skill >= 4 ? trailEnds(s, seat) : null; + const val = (c) => { + const r = ROUTES[c.routeId]; + let v = ROUTE_SCORE[r.length] * 2 - c.payment.locos * 2; + if (trailBonus && (trailBonus.has(r.a) || trailBonus.has(r.b))) v += r.length * 1.5; + return v; + }; + return claimDesc(s, seat, pool.reduce((a, b) => (val(b) > val(a) ? b : a)), ctx, skill); } } - const idx = bestFaceUpColorIndex(s, wantedColors); - if (idx !== -1) return { type: 'drawTrain', source: 'faceUp', index: idx }; - return { type: 'drawTrain', source: 'deck' }; + if (!la.deck && !la.faceUp.length) { + if (claims.length) return claimDesc(s, seat, pickBest(claims), ctx, skill); + if (la.tickets) return { type: 'drawTickets' }; + } + return drawDecision(s, seat, ctx, skill, rng, la); } -// Index of the most useful non-locomotive face-up card, or -1. -function bestFaceUpColorIndex(s, wantedColors) { +// Own route + known ticket points minus the best opponent's public score. +function leadEstimate(s, seat) { + const mine = L.routePoints(s, seat) + L.ticketScore(s, seat).points; + const best = Math.max(...s.players.filter((p) => p.seat !== seat).map((p) => L.routePoints(s, p.seat))); + return mine - best; +} + +function wantsMoreTickets(s, seat, skill) { + const player = s.players[seat]; + if (skill <= 2) return player.trainsLeft > 15; + const minOpp = Math.min(...s.players.filter((p) => p.seat !== seat).map((p) => p.trainsLeft)); + if (minOpp <= (skill >= 4 ? 9 : 6)) return false; + return trainCapacity(s, seat, skill) >= (skill >= 5 ? 13 : 11); +} + +// Cities at the ends of this seat's longest trail (spare claims extend it). +function trailEnds(s, seat) { + const t = L.longestTrail(s, seat); + if (!t.cities.length) return new Set(); + return new Set([t.cities[0], t.cities[t.cities.length - 1]]); +} + +// Urgency for planned routes others could take: a single track whose loss +// would force a long detour, next to an opponent's network. +function contestBonus(s, seat, rid) { + const r = ROUTES[rid]; + let bonus = 0; + const pairOpen = r.doubleGroup && s.playerCount >= 4 + && ROUTES.some((o) => o.id !== rid && o.doubleGroup === r.doubleGroup && s.claimed[o.id] == null); + if (!pairOpen) { + const alt = shortestRoutePath(s, r.a, r.b, seat, { skip: rid }); + const detour = alt ? alt.cost - r.length : 12; + bonus += Math.min(6, Math.max(0, detour) * 0.6); + } + for (const p of s.players) { + if (p.seat === seat) continue; + if (p.routes.some((x) => { const o = ROUTES[x]; return o.a === r.a || o.a === r.b || o.b === r.a || o.b === r.b; })) { + bonus += 3; break; + } + } + return bonus; +} + +// Skill 5: an opponent with two separate networks one short single route apart +// (and a long way round) is almost certainly trying to join them. +function findBlock(s, seat, claims) { + if (s.players[seat].trainsLeft < 16) return null; + const affordable = new Map(claims.map((c) => [c.routeId, c])); + for (const p of s.players) { + if (p.seat === seat || p.routes.length < 2) continue; + const find = seatComponents(s, p.seat); + const comps = new Set(); + for (const rid of p.routes) comps.add(find(ROUTES[rid].a)); + if (comps.size < 2) continue; + for (const [rid, c] of affordable) { + const r = ROUTES[rid]; + if (r.length > 3) continue; + const ca = find(r.a), cb = find(r.b); + if (ca === cb || !comps.has(ca) || !comps.has(cb)) continue; + const alt = shortestRoutePath(s, r.a, r.b, p.seat, { skip: rid }); + if (!alt || alt.cost >= r.length + 3) return c; + } + } + return null; +} + +// Pick the payment that hurts least: fewest locomotives, then (skill ≥ 4) the +// colour the rest of the plan needs least. +function claimDesc(s, seat, claim, ctx, skill) { + let payment = claim.payment; + if (skill >= 4) { + const opts = L.paymentOptions(s.players[seat], ROUTES[claim.routeId]); + const cost = (o) => o.locos * 3 + (o.color ? (ctx.need[o.color] || 0) * 0.4 * o.colorCount / Math.max(1, ROUTES[claim.routeId].length) : 0); + payment = opts.reduce((a, b) => (cost(b) < cost(a) ? b : a), opts[0]) ?? payment; + } + return { type: 'claimRoute', routeId: claim.routeId, payment }; +} + +// First train-card draw of the turn. +function drawDecision(s, seat, ctx, skill, rng, la) { + const faceUpOk = new Set(la.faceUp); + if (!la.deck && !faceUpOk.size) { + if (la.claims.length) return claimDesc(s, seat, la.claims[0], ctx, skill); + if (la.tickets) return { type: 'drawTickets' }; + return { type: 'pass' }; + } + if (rng() < NOISE[skill]) { + const pool = [...faceUpOk]; + if (la.deck && (rng() < 0.5 || !pool.length)) return { type: 'drawTrain', source: 'deck' }; + return { type: 'drawTrain', source: 'faceUp', index: pool[Math.floor(rng() * pool.length)] }; + } + const locoIdx = s.faceUp.findIndex((c, i) => c === 'locomotive' && faceUpOk.has(i)); + if (skill <= 2) { + if (locoIdx !== -1) return { type: 'drawTrain', source: 'faceUp', index: locoIdx }; + const idx = bestFaceUp(s, ctx.need, faceUpOk, 0.5); + if (idx !== -1) return { type: 'drawTrain', source: 'faceUp', index: idx }; + return la.deck ? { type: 'drawTrain', source: 'deck' } : { type: 'drawTrain', source: 'faceUp', index: [...faceUpOk][0] }; + } + const weights = drawWeights(s, seat, ctx); + const idx = bestFaceUp(s, weights, faceUpOk, 0.5); + if (idx !== -1) return { type: 'drawTrain', source: 'faceUp', index: idx }; + // No useful colour showing: a locomotive is worth it when the plan is short of + // cards in more than one colour (or needs gray), since a wild fills any gap. + if (locoIdx !== -1) { + const gaps = TRAIN_COLORS.filter((c) => ctx.deficit[c] > 0).length + (ctx.grayNeed > 0 ? 1 : 0); + if (gaps >= 2 || !la.deck) return { type: 'drawTrain', source: 'faceUp', index: locoIdx }; + } + if (la.deck) return { type: 'drawTrain', source: 'deck' }; + const any = [...faceUpOk].filter((i) => s.faceUp[i] !== 'locomotive'); + return { type: 'drawTrain', source: 'faceUp', index: (any.length ? any : [...faceUpOk])[0] }; +} + +// Colour wants: plan deficits; once tickets are done, colours that would open +// the longest still-open routes. +function drawWeights(s, seat, ctx) { + const w = new Map(); + for (const c of TRAIN_COLORS) if (ctx.deficit[c] > 0) w.set(c, ctx.deficit[c]); + if (ctx.grayNeed > 0) { + // Gray track: pile onto the colour we already hold most of. + const hand = s.players[seat].hand; + const top = TRAIN_COLORS.reduce((a, b) => (hand[b] > hand[a] ? b : a)); + w.set(top, (w.get(top) || 0) + ctx.grayNeed * 0.5); + } + if (w.size === 0) { + const hand = s.players[seat].hand; + for (const r of ROUTES) { + if (r.length < 4 || routeUse(s, seat, r.id) !== 'open') continue; + const cols = r.color === 'gray' ? TRAIN_COLORS : [r.color]; + for (const c of cols) { + const short = r.length - hand[c] - hand.locomotive; + if (short > 0 && short <= 3) w.set(c, Math.max(w.get(c) || 0, (4 - short) * 0.6 + r.length * 0.1)); + } + } + } + return w; +} + +function bestFaceUp(s, weights, faceUpOk, threshold) { + const get = (c) => (weights instanceof Map ? weights.get(c) : weights[c]) || 0; let bestIdx = -1, bestW = 0; s.faceUp.forEach((c, i) => { - if (c === 'locomotive') return; - const w = (wantedColors.get(c) || 0) + 0.1; // any colour has slight value + if (c === 'locomotive' || !faceUpOk.has(i)) return; + const w = get(c) + 0.1; if (w > bestW) { bestW = w; bestIdx = i; } }); - // Only divert to a face-up card if it is genuinely wanted; otherwise blind-draw - // (keeps more of the deck unseen). Take it when it matches a goal colour. - if (bestIdx !== -1 && bestW > 0.5) return bestIdx; - return -1; + return bestIdx !== -1 && bestW > threshold ? bestIdx : -1; } -export { ticketOf }; +// Second draw of the turn (a face-up locomotive is not allowed here). +export function chooseSecondDraw(s, seat, opts) { + const { skill, rng } = optsOf(opts); + const la = L.legalActions(s, seat); + const faceUpOk = new Set(la.faceUp); + if (!la.deck && !faceUpOk.size) return { type: 'pass' }; + if (rng() < NOISE[skill] && faceUpOk.size) { + const pool = [...faceUpOk]; + return { type: 'drawTrain', source: 'faceUp', index: pool[Math.floor(rng() * pool.length)] }; + } + const ctx = context(s, seat, skill); + const weights = skill <= 2 ? ctx.need : drawWeights(s, seat, ctx); + const idx = bestFaceUp(s, weights, faceUpOk, 0.5); + if (idx !== -1) return { type: 'drawTrain', source: 'faceUp', index: idx }; + if (la.deck) return { type: 'drawTrain', source: 'deck' }; + return { type: 'drawTrain', source: 'faceUp', index: [...faceUpOk][0] }; +} diff --git a/src/games/tickettoride/TicketToRideArt.js b/src/games/tickettoride/TicketToRideArt.js new file mode 100644 index 0000000..9296148 --- /dev/null +++ b/src/games/tickettoride/TicketToRideArt.js @@ -0,0 +1,982 @@ +// TicketToRideArt.js — procedural canvas art for the Ticket to Ride table. +// +// Everything is baked once into Phaser canvas textures (no image files): +// ttr-desk walnut desk, lamp pool, green leather pad (right), rail (bottom) +// ttr-map the antique parchment map: sea + coast ripples, watercolour +// land, Canada/Mexico beyond the borders, lakes, rivers, relief, +// printed route slots + rail beds, brass station pins + paper +// name tags, compass rose, cartouche, score track, folds +// ttr-car- a plastic train car in player colour ci (+ ttr-car-shadow) +// ttr-loco- the little locomotive that lays a claimed route +// ttr-marker- a wooden score-track marker +// ttr-plaque an opponent's wooden board +// ttr-rack the face-up card rack +// ttr-ticket a destination ticket (text is laid on by the scene) +// ttr-ticket-back the back of a ticket (ticket box stack) +// ttr-notepad the dispatch log pad; ttr-longest brass longest-route plate +// ttr-badge brass count badge; ttr-card-shadow soft card shadow +// ttr-glow / ttr-steam / ttr-cloud / ttr-spark FX sprites +// +// The map uses absolute canvas coordinates (TicketToRideBoard) translated into +// the sheet, so cities and routes land exactly where the scene expects them. + +import { canvas, rr, poly, mix, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { mulberry32 } from '../../ui/cardtable/AITiming.js'; +import { + CITIES, ROUTES, PLAYER_COLORS, LAND_OUTLINE, GREAT_LAKES, routeSegments, +} from './TicketToRideBoard.js'; +import { + W, H, SHEET, TRACK, TRACK_SQUARES, TRACK_STEP, TRACK_RECT, trackPos, + PAD, RAIL, RACK, OPP, CARD, DECK, DISCARD, TICKET_BOX, NOTEPAD, LONGEST, HAND, TICKETS_RAIL, +} from './TicketToRideLayout.js'; + +const RES = 2; +export const SERIF = 'Georgia, "Times New Roman", serif'; +export const DISPLAY = 'Caesar, Georgia, serif'; + +// Printed route colours (watercolour inks) — also used for hover tints. +export const ROUTE_INK = { + red: '#c4544c', orange: '#dc8b3c', yellow: '#e3c454', green: '#6f9d58', + blue: '#4f80b4', purple: '#9d6cab', black: '#45403a', white: '#f6f1e6', gray: '#c4b9a3', +}; + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); + return key; +} +const hex = (n) => `#${n.toString(16).padStart(6, '0')}`; +const P = (arr) => arr.map(([x, y]) => ({ x, y })); + +// ── shared painters ──────────────────────────────────────────────────────────── +function grain(ctx, x, y, w, h, rnd, { dark = 'rgba(40,22,8,0.16)', light = 'rgba(255,220,170,0.06)', spacing = 7, amp = 2.2 } = {}) { + ctx.save(); + ctx.lineWidth = 1; + for (let yy = y; yy < y + h; yy += spacing * (0.6 + rnd() * 0.8)) { + ctx.strokeStyle = rnd() < 0.7 ? dark : light; + ctx.beginPath(); + const ph = rnd() * 6, fq = 0.004 + rnd() * 0.01; + for (let xx = x; xx <= x + w; xx += 12) { + const yv = yy + Math.sin(xx * fq + ph) * amp + Math.sin(xx * fq * 3.1 + ph) * amp * 0.3; + if (xx === x) ctx.moveTo(xx, yv); else ctx.lineTo(xx, yv); + } + ctx.stroke(); + } + ctx.restore(); +} + +function woodFill(ctx, x, y, w, h, top, bottom, rnd, spacing = 7) { + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, top); g.addColorStop(1, bottom); + ctx.fillStyle = g; + ctx.fill(); + ctx.save(); + ctx.clip(); + grain(ctx, x, y, w, h, rnd, { spacing }); + ctx.fillStyle = noisePattern(ctx, 64, 22); + ctx.fillRect(x, y, w, h); + ctx.restore(); +} + +function brassScrew(ctx, x, y, r = 4) { + const g = ctx.createRadialGradient(x - r * 0.3, y - r * 0.3, 0, x, y, r); + g.addColorStop(0, '#fbe7a6'); g.addColorStop(0.6, '#c39a45'); g.addColorStop(1, '#6d5120'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(60,40,10,0.8)'; ctx.lineWidth = r * 0.25; + ctx.beginPath(); ctx.moveTo(x - r * 0.6, y + r * 0.2); ctx.lineTo(x + r * 0.6, y - r * 0.2); ctx.stroke(); +} + +function softShadow(ctx, x, y, w, h, r, blur, alpha) { + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; + ctx.shadowOffsetY = blur * 0.35; + ctx.fillStyle = '#000'; + rr(ctx, x, y, w, h, r); ctx.fill(); + ctx.restore(); +} + +// ── desk ─────────────────────────────────────────────────────────────────────── +function bakeDesk(scene) { + const key = 'ttr-desk'; + if (scene.textures.exists(key)) return key; + const rnd = mulberry32(17); + const c = canvas(W, H); + const ctx = c.getContext('2d'); + // Walnut planks. + const PH = 120; + const tones = ['#4a2e1a', '#50331d', '#472c18', '#553620', '#4c301b', '#4e311c']; + for (let i = 0, y = 0; y < H; i++, y += PH) { + ctx.beginPath(); ctx.rect(0, y, W, PH); + woodFill(ctx, 0, y, W, PH, tones[i % tones.length], mix(tones[i % tones.length], '#1a0e06', 0.3), rnd, 6); + ctx.fillStyle = 'rgba(12,6,2,0.6)'; ctx.fillRect(0, y, W, 2); + ctx.fillStyle = 'rgba(255,214,160,0.05)'; ctx.fillRect(0, y + 2, W, 1); + } + // Lamp pool over the map, vignette at the edges. + const lp = ctx.createRadialGradient(760, 420, 40, 760, 420, 1100); + lp.addColorStop(0, 'rgba(255,214,150,0.22)'); + lp.addColorStop(0.6, 'rgba(255,200,130,0.06)'); + lp.addColorStop(1, 'rgba(255,200,130,0)'); + ctx.fillStyle = lp; ctx.fillRect(0, 0, W, H); + const vg = ctx.createRadialGradient(900, 480, 500, 900, 480, 1300); + vg.addColorStop(0, 'rgba(0,0,0,0)'); vg.addColorStop(1, 'rgba(0,0,0,0.6)'); + ctx.fillStyle = vg; ctx.fillRect(0, 0, W, H); + + // Shadow the map sheet throws on the desk. + softShadow(ctx, SHEET.x + 4, SHEET.y + 6, SHEET.w - 8, SHEET.h - 6, 6, 26, 0.65); + + // Green leather desk pad (right) with gold tooling. + softShadow(ctx, PAD.x, PAD.y, PAD.w, PAD.h, 12, 18, 0.6); + ctx.save(); + rr(ctx, PAD.x, PAD.y, PAD.w, PAD.h, 12); + const lg = ctx.createLinearGradient(PAD.x, PAD.y, PAD.x + PAD.w, PAD.y + PAD.h); + lg.addColorStop(0, '#24402f'); lg.addColorStop(1, '#16291e'); + ctx.fillStyle = lg; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 96, 26); ctx.fillRect(PAD.x, PAD.y, PAD.w, PAD.h); + for (let i = 0; i < 40; i++) { // leather mottling + const x = PAD.x + rnd() * PAD.w, y = PAD.y + rnd() * PAD.h, r = 30 + rnd() * 90; + const m = ctx.createRadialGradient(x, y, 0, x, y, r); + m.addColorStop(0, rnd() < 0.5 ? 'rgba(0,0,0,0.12)' : 'rgba(120,170,120,0.06)'); m.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = m; ctx.fillRect(x - r, y - r, r * 2, r * 2); + } + ctx.restore(); + ctx.strokeStyle = 'rgba(214,176,92,0.75)'; ctx.lineWidth = 2; + rr(ctx, PAD.x + 7, PAD.y + 7, PAD.w - 14, PAD.h - 14, 8); ctx.stroke(); + ctx.strokeStyle = 'rgba(214,176,92,0.35)'; ctx.lineWidth = 1; + rr(ctx, PAD.x + 11, PAD.y + 11, PAD.w - 22, PAD.h - 22, 6); ctx.stroke(); + // Felt wells under the draw pile, discard and ticket box. + const well = (cx, cy, w, h) => { + ctx.save(); + rr(ctx, cx - w / 2, cy - h / 2, w, h, 8); + ctx.fillStyle = 'rgba(8,18,12,0.55)'; ctx.fill(); + ctx.clip(); + const ig = ctx.createLinearGradient(0, cy - h / 2, 0, cy - h / 2 + 14); + ig.addColorStop(0, 'rgba(0,0,0,0.45)'); ig.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = ig; ctx.fillRect(cx - w / 2, cy - h / 2, w, 14); + ctx.restore(); + ctx.strokeStyle = 'rgba(214,176,92,0.35)'; ctx.lineWidth = 1; + rr(ctx, cx - w / 2, cy - h / 2, w, h, 8); ctx.stroke(); + }; + well(DECK.x, DECK.y, CARD.w + 14, CARD.h + 14); + well(DISCARD.x, DISCARD.y, CARD.w + 14, CARD.h + 14); + well(TICKET_BOX.x, TICKET_BOX.y, TICKET_BOX.w + 14, TICKET_BOX.h + 14); + + // Bottom rail: dark wood with a brass inlay and a felt runner. + softShadow(ctx, 0, RAIL.y, W, RAIL.h + 20, 0, 22, 0.6); + ctx.beginPath(); ctx.rect(0, RAIL.y, W, RAIL.h); + woodFill(ctx, 0, RAIL.y, W, RAIL.h, '#432816', '#1f1209', rnd, 5); + const lip = ctx.createLinearGradient(0, RAIL.y, 0, RAIL.y + 12); + lip.addColorStop(0, 'rgba(255,220,170,0.3)'); lip.addColorStop(1, 'rgba(255,220,170,0)'); + ctx.fillStyle = lip; ctx.fillRect(0, RAIL.y, W, 12); + ctx.fillStyle = '#b8913f'; ctx.fillRect(0, RAIL.y + 2, W, 2); + ctx.fillStyle = 'rgba(255,240,190,0.5)'; ctx.fillRect(0, RAIL.y + 2, W, 1); + const runner = (x, w) => { + ctx.save(); + rr(ctx, x, HAND.y - 2, w, RAIL.h - 14, 12); + ctx.fillStyle = '#1d3426'; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 30); ctx.fillRect(x, HAND.y - 2, w, RAIL.h); + const inner = ctx.createLinearGradient(0, HAND.y - 2, 0, HAND.y + 18); + inner.addColorStop(0, 'rgba(0,0,0,0.5)'); inner.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = inner; ctx.fillRect(x, HAND.y - 2, w, 20); + ctx.restore(); + ctx.strokeStyle = 'rgba(184,145,63,0.5)'; ctx.lineWidth = 1.5; + rr(ctx, x, HAND.y - 2, w, RAIL.h - 14, 12); ctx.stroke(); + }; + runner(HAND.x - 4, HAND.w + 8); + runner(TICKETS_RAIL.x - 4, TICKETS_RAIL.w + 8); + return addCanvas(scene, key, c); +} + +// ── the map sheet ─────────────────────────────────────────────────────────────── +const SEA = '#a9c7c1'; +const SEA_INK = 'rgba(46,88,96,'; +const LAND = '#ecdcaa'; +const FOREIGN = '#e7ddc0'; +const INK = '#3b2a17'; + +// One continent: the traced coast of the play area, but with its northern edge +// opened up to the top of the sheet so Canada carries on (no false coastline). +const NORTH_FROM = LAND_OUTLINE.findIndex(([x, y]) => x === 1418 && y === 288); +const CONTINENT = P([ + [108, 218], [90, 196], [70, 160], [40, 120], [40, -10], [1470, -10], [1470, 200], [1440, 236], [1408, 250], + ...LAND_OUTLINE.slice(NORTH_FROM), +]); +const MEXICO = P([ + [600, 832], [565, 778], [540, 720], [488, 738], [418, 755], [340, 768], [250, 748], + [262, 790], [300, 842], [330, 900], [300, 930], [640, 930], [618, 880], +]); +const CUBA = P([[1150, 900], [1200, 884], [1262, 886], [1320, 900], [1300, 912], [1170, 914]]); +const US_CANADA_BORDER_PTS = [ + [96, 214], [250, 212], [450, 214], [640, 218], [726, 222], [728, 288], + [800, 238], [900, 222], [958, 236], [1004, 262], [1060, 300], [1112, 332], + [1150, 300], [1210, 268], [1290, 262], [1350, 258], [1404, 250], +]; +const US_CANADA_BORDER = P(US_CANADA_BORDER_PTS); +// Everything north of the border line (clipped to the land) gets a pale rose wash. +const CANADA_TINT = P([...US_CANADA_BORDER_PTS, [1470, 250], [1470, -10], [20, -10], [20, 214]]); +const RIVERS = [ + P([[760, 282], [790, 330], [830, 380], [860, 440], [872, 500], [880, 545], [890, 600], [872, 650], [862, 700], [884, 750], [905, 790]]), + P([[452, 332], [520, 360], [600, 392], [680, 420], [742, 445], [790, 490], [840, 530], [880, 545]]), + P([[1110, 428], [1080, 470], [1040, 505], [990, 545], [940, 570], [892, 580]]), + P([[520, 470], [610, 520], [700, 560], [760, 600], [800, 640], [845, 650]]), // Arkansas +]; +const RANGES = [ + { pts: P([[300, 180], [360, 240], [410, 330], [430, 420], [455, 500], [478, 560], [505, 640], [520, 690]]), width: 70, n: 70, size: 15 }, + { pts: P([[178, 290], [196, 380], [190, 450], [215, 540], [240, 600]]), width: 22, n: 18, size: 12 }, + { pts: P([[1005, 640], [1050, 570], [1100, 510], [1150, 460], [1205, 410], [1250, 370]]), width: 34, n: 30, size: 11 }, +]; + +function jitterPoly(pts, rnd, amt) { + return pts.map((p) => ({ x: p.x + (rnd() - 0.5) * amt, y: p.y + (rnd() - 0.5) * amt })); +} + +function smoothPath(ctx, pts, close = true) { + // Quadratic smoothing through midpoints — softens the hand-traced outline. + const n = pts.length; + ctx.beginPath(); + const mid = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); + if (!close) { + ctx.moveTo(pts[0].x, pts[0].y); + for (let i = 1; i < n - 1; i++) { const m = mid(pts[i], pts[i + 1]); ctx.quadraticCurveTo(pts[i].x, pts[i].y, m.x, m.y); } + ctx.lineTo(pts[n - 1].x, pts[n - 1].y); + return; + } + const s = mid(pts[n - 1], pts[0]); + ctx.moveTo(s.x, s.y); + for (let i = 0; i < n; i++) { const m = mid(pts[i], pts[(i + 1) % n]); ctx.quadraticCurveTo(pts[i].x, pts[i].y, m.x, m.y); } + ctx.closePath(); +} + +function washFill(ctx, pts, base, rnd, { layers = 5, jitter = 7, edge = 'rgba(150,108,52,0.2)' } = {}) { + ctx.fillStyle = base; + smoothPath(ctx, pts); ctx.fill(); + for (let i = 0; i < layers; i++) { + ctx.globalAlpha = 0.1 + rnd() * 0.08; + ctx.fillStyle = mix(base, i % 2 ? '#c9a86a' : '#f6ecd0', 0.5); + smoothPath(ctx, jitterPoly(pts, rnd, jitter)); ctx.fill(); + } + ctx.globalAlpha = 1; + // Pigment pools at the edge of a watercolour wash. + ctx.save(); + smoothPath(ctx, pts); ctx.clip(); + ctx.strokeStyle = edge; ctx.lineWidth = 18; smoothPath(ctx, pts); ctx.stroke(); + ctx.strokeStyle = edge.replace(/[\d.]+\)$/, '0.28)'); ctx.lineWidth = 5; smoothPath(ctx, pts); ctx.stroke(); + ctx.restore(); +} + +function coastRipples(ctx, pts, rings = 4, spacing = 9) { + for (let k = rings; k >= 1; k--) { + ctx.lineJoin = 'round'; + ctx.lineWidth = k * spacing * 2; + ctx.strokeStyle = `${SEA_INK}${0.12 + (rings - k) * 0.06})`; + smoothPath(ctx, pts); ctx.stroke(); + ctx.lineWidth = k * spacing * 2 - 2.2; + ctx.strokeStyle = SEA; + smoothPath(ctx, pts); ctx.stroke(); + } +} + +function mountain(ctx, x, y, s, rnd) { + const lean = (rnd() - 0.5) * s * 0.3; + ctx.fillStyle = 'rgba(140,105,60,0.22)'; + ctx.beginPath(); ctx.moveTo(x - s * 0.55, y); ctx.lineTo(x + lean, y - s); ctx.lineTo(x + s * 0.55, y); ctx.closePath(); ctx.fill(); + // Hatched shadow side. + ctx.strokeStyle = 'rgba(70,48,22,0.5)'; ctx.lineWidth = 0.8; + for (let t = 0.2; t < 1; t += 0.2) { + const px = x + lean + (s * 0.55 - lean) * t, py = y - s + s * t; + ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px - s * 0.12, y); ctx.stroke(); + } + ctx.strokeStyle = 'rgba(60,40,18,0.85)'; ctx.lineWidth = 1.1; + ctx.beginPath(); ctx.moveTo(x - s * 0.55, y); ctx.lineTo(x + lean, y - s); ctx.lineTo(x + s * 0.55, y); ctx.stroke(); +} + +function tree(ctx, x, y, s) { + ctx.strokeStyle = 'rgba(70,90,50,0.45)'; ctx.lineWidth = 0.9; + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x, y - s); ctx.stroke(); + ctx.fillStyle = 'rgba(90,115,60,0.3)'; + ctx.beginPath(); ctx.moveTo(x - s * 0.35, y - s * 0.3); ctx.lineTo(x, y - s * 1.1); ctx.lineTo(x + s * 0.35, y - s * 0.3); ctx.closePath(); ctx.fill(); +} + +function nearCity(x, y, r) { + return CITIES.some((c) => Math.hypot(c.x - x, c.y - y) < r || (Math.abs(c.x - x) < 60 && y < c.y && c.y - y < 34)); +} + +function compassRose(ctx, x, y, r) { + ctx.save(); + ctx.translate(x, y); + ctx.strokeStyle = 'rgba(59,42,23,0.85)'; ctx.lineWidth = 1.2; + ctx.beginPath(); ctx.arc(0, 0, r, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.arc(0, 0, r * 0.82, 0, Math.PI * 2); ctx.stroke(); + for (let i = 0; i < 32; i++) { + const a = (i / 32) * Math.PI * 2; + const r0 = r * (i % 4 === 0 ? 0.72 : 0.82); + ctx.beginPath(); ctx.moveTo(Math.cos(a) * r0, Math.sin(a) * r0); ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r); ctx.stroke(); + } + const point = (a, len, wide, dark, light) => { + const c = Math.cos(a), s = Math.sin(a), pc = Math.cos(a + Math.PI / 2), ps = Math.sin(a + Math.PI / 2); + ctx.fillStyle = dark; + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(c * len, s * len); ctx.lineTo(pc * wide, ps * wide); ctx.closePath(); ctx.fill(); + ctx.fillStyle = light; + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(c * len, s * len); ctx.lineTo(-pc * wide, -ps * wide); ctx.closePath(); ctx.fill(); + }; + for (let i = 0; i < 4; i++) point(Math.PI / 4 + i * Math.PI / 2, r * 0.6, r * 0.1, '#7a6040', '#d8c79c'); + for (let i = 0; i < 4; i++) point(-Math.PI / 2 + i * Math.PI / 2, r * 0.95, r * 0.15, i === 0 ? '#8e2c22' : '#3b2a17', '#efe3c2'); + ctx.fillStyle = '#c9a24a'; ctx.beginPath(); ctx.arc(0, 0, r * 0.08, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = INK; ctx.font = `bold ${Math.round(r * 0.34)}px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('N', 0, -r - r * 0.24); + ctx.restore(); +} + +function cartouche(ctx, cx, cy, w, h) { + ctx.save(); + // Scroll ends. + ctx.fillStyle = '#e6d3a2'; ctx.strokeStyle = INK; ctx.lineWidth = 1.2; + for (const side of [-1, 1]) { + ctx.beginPath(); ctx.ellipse(cx + side * (w / 2), cy, 10, h / 2 - 2, 0, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); + ctx.beginPath(); ctx.ellipse(cx + side * (w / 2 + 2), cy + 3, 5, h / 2 - 12, 0, 0, Math.PI * 2); ctx.stroke(); + } + ctx.fillStyle = '#f1e4bd'; + ctx.fillRect(cx - w / 2, cy - h / 2 + 2, w, h - 4); + ctx.strokeRect(cx - w / 2, cy - h / 2 + 2, w, h - 4); + ctx.strokeStyle = 'rgba(59,42,23,0.5)'; + ctx.strokeRect(cx - w / 2 + 5, cy - h / 2 + 7, w - 10, h - 14); + ctx.fillStyle = INK; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.font = `22px ${DISPLAY}`; + ctx.fillText('NORTH AMERICAN RAILWAYS', cx, cy - 8); + ctx.font = `italic 12px ${SERIF}`; + ctx.fillStyle = '#5a4428'; + ctx.fillText('Surveyed for the Grand Trunk Lines · Anno 1900', cx, cy + 13); + ctx.restore(); +} + +function seaLabel(ctx, text, x, y, size, rot = 0, spacing = 4) { + ctx.save(); + ctx.translate(x, y); ctx.rotate(rot); + ctx.fillStyle = 'rgba(40,80,90,0.55)'; + ctx.font = `italic ${size}px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + if ('letterSpacing' in ctx) ctx.letterSpacing = `${spacing}px`; + ctx.fillText(text, 0, 0); + ctx.restore(); +} + +function landLabel(ctx, text, x, y, size, rot = 0, color = 'rgba(110,80,40,0.45)') { + ctx.save(); + ctx.translate(x, y); ctx.rotate(rot); + ctx.fillStyle = color; + ctx.font = `${size}px ${DISPLAY}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + if ('letterSpacing' in ctx) ctx.letterSpacing = `${Math.round(size * 0.5)}px`; + ctx.fillText(text, 0, 0); + ctx.restore(); +} + +// Rail bed (two thin rails + sleepers) under each route, then the printed slots. +function printRoutes(ctx) { + for (const r of ROUTES) { + const segs = routeSegments(r); + // Rail bed between the cities, visible in the gaps between slots. + ctx.strokeStyle = 'rgba(59,42,23,0.32)'; ctx.lineWidth = 1; + for (let i = 0; i < segs.length - 1; i++) { + const a = segs[i], b = segs[i + 1]; + for (const o of [-3, 3]) { + const ax = a.cx - Math.sin(a.angle) * o, ay = a.cy + Math.cos(a.angle) * o; + const bx = b.cx - Math.sin(b.angle) * o, by = b.cy + Math.cos(b.angle) * o; + ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.stroke(); + } + } + for (const seg of segs) { + ctx.save(); + ctx.translate(seg.cx, seg.cy); ctx.rotate(seg.angle); + const w = seg.w, h = seg.h; + ctx.fillStyle = 'rgba(40,26,12,0.25)'; // ink shadow + rr(ctx, -w / 2 + 1, -h / 2 + 1.5, w, h, 3); ctx.fill(); + const ink = ROUTE_INK[r.color] ?? ROUTE_INK.gray; + const g = ctx.createLinearGradient(0, -h / 2, 0, h / 2); + g.addColorStop(0, mix(ink, '#ffffff', 0.25)); g.addColorStop(1, mix(ink, '#3b2a17', 0.12)); + ctx.fillStyle = g; + rr(ctx, -w / 2, -h / 2, w, h, 3); ctx.fill(); + // Paper texture shows through the watercolour. + ctx.fillStyle = 'rgba(255,248,230,0.12)'; + rr(ctx, -w / 2 + 2, -h / 2 + 2, w - 4, h * 0.35, 2); ctx.fill(); + ctx.strokeStyle = INK; ctx.lineWidth = 1.3; + if (r.color === 'gray') ctx.setLineDash([4, 2.5]); + rr(ctx, -w / 2, -h / 2, w, h, 3); ctx.stroke(); + ctx.setLineDash([]); + // Sleeper ticks. + ctx.strokeStyle = r.color === 'black' ? 'rgba(240,230,210,0.35)' : 'rgba(59,42,23,0.28)'; ctx.lineWidth = 1; + for (const fx of [-0.3, 0, 0.3]) { + ctx.beginPath(); ctx.moveTo(w * fx, -h / 2 + 3); ctx.lineTo(w * fx, h / 2 - 3); ctx.stroke(); + } + ctx.restore(); + } + } +} + +function printCities(ctx) { + for (const c of CITIES) { + // Station pin. + ctx.fillStyle = 'rgba(30,18,6,0.35)'; + ctx.beginPath(); ctx.arc(c.x + 1.5, c.y + 2, 10, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#3a2a16'; + ctx.beginPath(); ctx.arc(c.x, c.y, 10, 0, Math.PI * 2); ctx.fill(); + const g = ctx.createRadialGradient(c.x - 3, c.y - 3, 0, c.x, c.y, 8); + g.addColorStop(0, '#fff0b8'); g.addColorStop(0.5, '#d8b25a'); g.addColorStop(1, '#8a6a28'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(c.x, c.y, 7.5, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#3a2a16'; + ctx.beginPath(); ctx.arc(c.x, c.y, 2.4, 0, Math.PI * 2); ctx.fill(); + } + // Paper name tags (after all pins so tags sit on top). + ctx.font = `italic bold 14px ${SERIF}`; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (const c of CITIES) { + const tw = ctx.measureText(c.name).width + 10, th = 18; + const x = c.x - tw / 2, y = c.y - 16 - th; + ctx.fillStyle = 'rgba(30,18,6,0.25)'; + rr(ctx, x + 1, y + 1.5, tw, th, 3); ctx.fill(); + ctx.fillStyle = 'rgba(250,242,220,0.92)'; + rr(ctx, x, y, tw, th, 3); ctx.fill(); + ctx.strokeStyle = 'rgba(59,42,23,0.55)'; ctx.lineWidth = 0.8; + rr(ctx, x, y, tw, th, 3); ctx.stroke(); + ctx.fillStyle = '#2b1d0e'; + ctx.fillText(c.name, c.x, y + th / 2 + 0.5); + } +} + +function printTrack(ctx) { + const t = TRACK_RECT; + const half = TRACK.band / 2; + ctx.save(); + // Band background. + ctx.fillStyle = '#efe2bb'; + ctx.beginPath(); + ctx.rect(t.x0 - half, t.y0 - half, t.x1 - t.x0 + TRACK.band, t.y1 - t.y0 + TRACK.band); + ctx.rect(t.x0 + half, t.y0 + half, t.x1 - t.x0 - TRACK.band, t.y1 - t.y0 - TRACK.band); + ctx.fill('evenodd'); + ctx.strokeStyle = INK; ctx.lineWidth = 1.4; + ctx.strokeRect(t.x0 - half, t.y0 - half, t.x1 - t.x0 + TRACK.band, t.y1 - t.y0 + TRACK.band); + ctx.strokeRect(t.x0 + half, t.y0 + half, t.x1 - t.x0 - TRACK.band, t.y1 - t.y0 - TRACK.band); + // Square dividers + numbers. + ctx.font = `bold 10px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (let n = 0; n < TRACK_SQUARES; n++) { + const p = trackPos(n); + const horiz = p.side === 'top' || p.side === 'bottom'; + const sx = horiz ? TRACK_STEP : TRACK.band, sy = horiz ? TRACK.band : TRACK_STEP; + if (n % 10 === 0) { + ctx.fillStyle = 'rgba(160,120,60,0.22)'; + ctx.fillRect(p.x - sx / 2, p.y - sy / 2, sx, sy); + } + // Divider at the start edge of each square. + ctx.strokeStyle = 'rgba(59,42,23,0.45)'; ctx.lineWidth = 0.8; + ctx.beginPath(); + if (p.side === 'top') { ctx.moveTo(p.x - sx / 2, p.y - half); ctx.lineTo(p.x - sx / 2, p.y + half); } + if (p.side === 'bottom') { ctx.moveTo(p.x + sx / 2, p.y - half); ctx.lineTo(p.x + sx / 2, p.y + half); } + if (p.side === 'right') { ctx.moveTo(p.x - half, p.y - sy / 2); ctx.lineTo(p.x + half, p.y - sy / 2); } + if (p.side === 'left') { ctx.moveTo(p.x - half, p.y + sy / 2); ctx.lineTo(p.x + half, p.y + sy / 2); } + ctx.stroke(); + if (n % 5 === 0) { + ctx.fillStyle = n % 10 === 0 ? '#3b2a17' : 'rgba(59,42,23,0.6)'; + ctx.fillText(String(n), p.x, p.y + 0.5); + } + } + ctx.restore(); +} + +function bakeMap(scene) { + const key = 'ttr-map'; + if (scene.textures.exists(key)) return key; + const rnd = mulberry32(1869); + const c = canvas(SHEET.w, SHEET.h); + const ctx = c.getContext('2d'); + ctx.translate(-SHEET.x, -SHEET.y); + + // Parchment. + const pg = ctx.createRadialGradient(SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, 200, SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, 900); + pg.addColorStop(0, '#efe3c0'); pg.addColorStop(1, '#d9c595'); + ctx.fillStyle = pg; ctx.fillRect(SHEET.x, SHEET.y, SHEET.w, SHEET.h); + + // Inner map area (inside the score track). + const inner = { + x: SHEET.x + TRACK.inset + TRACK.band, y: SHEET.y + TRACK.inset + TRACK.band, + w: SHEET.w - 2 * (TRACK.inset + TRACK.band), h: SHEET.h - 2 * (TRACK.inset + TRACK.band), + }; + ctx.save(); + ctx.beginPath(); ctx.rect(inner.x, inner.y, inner.w, inner.h); ctx.clip(); + + // Sea + engraved wave hatching. + ctx.fillStyle = SEA; ctx.fillRect(inner.x, inner.y, inner.w, inner.h); + ctx.strokeStyle = `${SEA_INK}0.13)`; ctx.lineWidth = 1; + for (let y = inner.y + 6; y < inner.y + inner.h; y += 11) { + ctx.beginPath(); + for (let x = inner.x; x <= inner.x + inner.w; x += 8) { + const yy = y + Math.sin(x * 0.045 + y) * 1.6; + if (x === inner.x) ctx.moveTo(x, yy); else ctx.lineTo(x, yy); + } + ctx.stroke(); + } + + const landPts = P(LAND_OUTLINE); + // Coast ripples (drawn before land so only the sea side shows). + for (const shape of [CONTINENT, MEXICO, CUBA]) coastRipples(ctx, shape, shape === CUBA ? 2 : 4, 8); + + washFill(ctx, MEXICO, FOREIGN, rnd, { edge: 'rgba(150,120,80,0.16)' }); + washFill(ctx, CUBA, FOREIGN, rnd, { layers: 2, jitter: 3, edge: 'rgba(150,120,80,0.16)' }); + washFill(ctx, CONTINENT, LAND, rnd); + + // Political washes: Canada rose, and soft regional blooms across the States. + ctx.save(); + smoothPath(ctx, CONTINENT); ctx.clip(); + ctx.fillStyle = 'rgba(210,140,130,0.16)'; + smoothPath(ctx, CANADA_TINT); ctx.fill(); + ctx.restore(); + ctx.save(); + smoothPath(ctx, landPts); ctx.clip(); + const blobs = [ + [250, 300, 220, 'rgba(214,160,150,0.14)'], [450, 560, 220, 'rgba(200,180,120,0.14)'], + [700, 300, 200, 'rgba(160,190,140,0.12)'], [760, 650, 200, 'rgba(220,170,120,0.13)'], + [1000, 420, 210, 'rgba(170,170,200,0.12)'], [1150, 650, 190, 'rgba(190,200,140,0.13)'], + [1250, 300, 170, 'rgba(210,170,170,0.12)'], + ]; + for (const [x, y, r, col] of blobs) { + const g = ctx.createRadialGradient(x, y, 0, x, y, r); + g.addColorStop(0, col); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; ctx.fillRect(x - r, y - r, r * 2, r * 2); + } + ctx.restore(); + + // Coast ink lines. + ctx.strokeStyle = 'rgba(91,67,38,0.9)'; ctx.lineWidth = 1.6; + for (const shape of [MEXICO, CUBA, CONTINENT]) { smoothPath(ctx, shape); ctx.stroke(); } + + // Border lines (dash-dot). + ctx.save(); + ctx.strokeStyle = 'rgba(120,60,50,0.55)'; ctx.lineWidth = 1.4; ctx.setLineDash([7, 3, 2, 3]); + smoothPath(ctx, US_CANADA_BORDER, false); ctx.stroke(); + // The US–Mexico line follows the shared coast; dash it over the ink. + ctx.strokeStyle = 'rgba(120,60,50,0.45)'; + smoothPath(ctx, P(LAND_OUTLINE.slice(LAND_OUTLINE.findIndex(([x, y]) => x === 600 && y === 832), LAND_OUTLINE.findIndex(([x, y]) => x === 250 && y === 748) + 1)), false); + ctx.stroke(); + ctx.restore(); + + // Great Lakes. + const lakePts = P(GREAT_LAKES); + ctx.save(); + smoothPath(ctx, lakePts); ctx.clip(); + ctx.fillStyle = mix(SEA, '#ffffff', 0.1); ctx.fillRect(700, 180, 450, 220); + ctx.strokeStyle = `${SEA_INK}0.3)`; ctx.lineWidth = 1; + for (let k = 1; k <= 3; k++) { ctx.lineWidth = k * 12; ctx.strokeStyle = `${SEA_INK}${0.05 + 0.04 * (4 - k)})`; smoothPath(ctx, lakePts); ctx.stroke(); } + ctx.restore(); + ctx.strokeStyle = 'rgba(91,67,38,0.85)'; ctx.lineWidth = 1.4; smoothPath(ctx, lakePts); ctx.stroke(); + + // Rivers. + for (const r of RIVERS) { + ctx.strokeStyle = 'rgba(70,120,150,0.55)'; ctx.lineWidth = 1.8; + smoothPath(ctx, jitterPoly(r, rnd, 3), false); ctx.stroke(); + } + + // Relief and forests. + for (const range of RANGES) { + for (let i = 0; i < range.n; i++) { + const t = rnd() * (range.pts.length - 1); + const k = Math.floor(t), f = t - k; + const a = range.pts[k], b = range.pts[Math.min(k + 1, range.pts.length - 1)]; + const x = a.x + (b.x - a.x) * f + (rnd() - 0.5) * range.width; + const y = a.y + (b.y - a.y) * f + (rnd() - 0.5) * range.width * 0.6; + if (nearCity(x, y, 26)) continue; + mountain(ctx, x, y, range.size * (0.7 + rnd() * 0.6), rnd); + } + } + for (let i = 0; i < 70; i++) { + const x = 60 + rnd() * 1360, y = 50 + rnd() * 60; + if (x > 880 && x < 1290 && y > 96) continue; // the Canada label + tree(ctx, x, y, 7 + rnd() * 4); + } + for (let i = 0; i < 45; i++) { // eastern woodlands + const x = 980 + rnd() * 330, y = 300 + rnd() * 380; + if (nearCity(x, y, 30)) continue; + tree(ctx, x, y, 6 + rnd() * 3); + } + + // Names on the sea and beyond the borders. + seaLabel(ctx, 'PACIFIC OCEAN', 66, 640, 17, -Math.PI / 2 + 0.2, 6); + seaLabel(ctx, 'ATLANTIC OCEAN', 1386, 640, 17, Math.PI / 2 - 0.1, 6); + seaLabel(ctx, 'Gulf of Mexico', 1010, 852, 16, 0, 3); + landLabel(ctx, 'DOMINION OF CANADA', 1080, 132, 20); // clear of the status ribbon + music controls + landLabel(ctx, 'MEXICO', 470, 790, 16, -0.08); + compassRose(ctx, 112, 812, 42); + ctx.restore(); + + // Cartouche straddles Mexico and the Gulf (outside the clip so the scroll ends show). + cartouche(ctx, 430, 846, 252, 50); + + printRoutes(ctx); + printCities(ctx); + printTrack(ctx); + + // Paper ageing over everything: grain, foxing, folds, edge burn. + ctx.fillStyle = noisePattern(ctx, 128, 18); ctx.fillRect(SHEET.x, SHEET.y, SHEET.w, SHEET.h); + for (let i = 0; i < 26; i++) { + const x = SHEET.x + rnd() * SHEET.w, y = SHEET.y + rnd() * SHEET.h, r = 3 + rnd() * 16; + const g = ctx.createRadialGradient(x, y, 0, x, y, r); + g.addColorStop(0, 'rgba(140,90,40,0.12)'); g.addColorStop(1, 'rgba(140,90,40,0)'); + ctx.fillStyle = g; ctx.fillRect(x - r, y - r, r * 2, r * 2); + } + const fold = (x0, y0, x1, y1) => { + ctx.strokeStyle = 'rgba(90,60,30,0.16)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,250,235,0.22)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(x0 + 2, y0 + 2); ctx.lineTo(x1 + 2, y1 + 2); ctx.stroke(); + }; + fold(SHEET.x + SHEET.w / 2, SHEET.y, SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h); + fold(SHEET.x, SHEET.y + SHEET.h / 2, SHEET.x + SHEET.w, SHEET.y + SHEET.h / 2); + fold(SHEET.x + SHEET.w / 4, SHEET.y, SHEET.x + SHEET.w / 4, SHEET.y + SHEET.h); + fold(SHEET.x + SHEET.w * 3 / 4, SHEET.y, SHEET.x + SHEET.w * 3 / 4, SHEET.y + SHEET.h); + const eb = ctx.createRadialGradient(SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, 480, SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, 900); + eb.addColorStop(0, 'rgba(120,80,30,0)'); eb.addColorStop(1, 'rgba(120,80,30,0.28)'); + ctx.fillStyle = eb; ctx.fillRect(SHEET.x, SHEET.y, SHEET.w, SHEET.h); + ctx.strokeStyle = 'rgba(90,60,30,0.6)'; ctx.lineWidth = 2; + ctx.strokeRect(SHEET.x + 1, SHEET.y + 1, SHEET.w - 2, SHEET.h - 2); + + // Brass pins at the corners. + for (const [x, y] of [[SHEET.x + 6, SHEET.y + 6], [SHEET.x + SHEET.w - 6, SHEET.y + 6], [SHEET.x + 6, SHEET.y + SHEET.h - 6], [SHEET.x + SHEET.w - 6, SHEET.y + SHEET.h - 6]]) { + brassScrew(ctx, x, y, 5); + } + return addCanvas(scene, key, c); +} + +// ── pieces ────────────────────────────────────────────────────────────────────── +export const CAR_TEX = { w: 60, h: 18 }; + +function bakeCar(scene, ci) { + const key = `ttr-car-${ci}`; + if (scene.textures.exists(key)) return key; + const col = hex(PLAYER_COLORS[ci].hex); + const w = CAR_TEX.w * RES, h = CAR_TEX.h * RES; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + const W0 = CAR_TEX.w, H0 = CAR_TEX.h; + // Couplers. + ctx.fillStyle = '#2a2420'; + ctx.fillRect(0, H0 / 2 - 2, 3, 4); ctx.fillRect(W0 - 3, H0 / 2 - 2, 3, 4); + // Body (top-down, light from the upper left). + const g = ctx.createLinearGradient(0, 1, 0, H0 - 1); + g.addColorStop(0, mix(col, '#ffffff', 0.45)); g.addColorStop(0.45, col); g.addColorStop(1, mix(col, '#000000', 0.45)); + ctx.fillStyle = g; + rr(ctx, 2.5, 1, W0 - 5, H0 - 2, 3.5); ctx.fill(); + ctx.strokeStyle = mix(col, '#000000', 0.6); ctx.lineWidth = 1; + rr(ctx, 2.5, 1, W0 - 5, H0 - 2, 3.5); ctx.stroke(); + // Roof ridge + walkway. + ctx.fillStyle = 'rgba(255,255,255,0.28)'; + rr(ctx, 6, 3, W0 - 12, 3, 1.5); ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.18)'; + ctx.fillRect(6, H0 / 2 - 0.5, W0 - 12, 1); + // Window strip. + ctx.fillStyle = 'rgba(20,24,30,0.55)'; + for (let x = 9; x < W0 - 12; x += 8) { rr(ctx, x, H0 - 7, 5, 3, 1); ctx.fill(); } + // Plastic specular. + ctx.fillStyle = 'rgba(255,255,255,0.45)'; + rr(ctx, 5, 2, 10, 2, 1); ctx.fill(); + return addCanvas(scene, key, c); +} + +function bakeCarShadow(scene) { + const key = 'ttr-car-shadow'; + if (scene.textures.exists(key)) return key; + const pad = 8; + const w = (CAR_TEX.w + pad * 2) * RES, h = (CAR_TEX.h + pad * 2) * RES; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + ctx.filter = 'blur(3px)'; + ctx.fillStyle = 'rgba(30,16,4,0.6)'; + rr(ctx, pad, pad, CAR_TEX.w, CAR_TEX.h, 4); ctx.fill(); + return addCanvas(scene, key, c); +} + +function bakeLoco(scene, ci) { + const key = `ttr-loco-${ci}`; + if (scene.textures.exists(key)) return key; + const col = hex(PLAYER_COLORS[ci].hex); + const W0 = 46, H0 = 20; + const c = canvas(W0 * RES, H0 * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + // Boiler (front = +x). + const bg = ctx.createLinearGradient(0, 2, 0, H0 - 2); + bg.addColorStop(0, '#6a6a6a'); bg.addColorStop(0.5, '#262626'); bg.addColorStop(1, '#0c0c0c'); + ctx.fillStyle = bg; rr(ctx, 14, 3, 28, H0 - 6, 6); ctx.fill(); + // Cow-catcher. + ctx.fillStyle = '#3a3a3a'; + ctx.beginPath(); ctx.moveTo(42, 3); ctx.lineTo(46, H0 / 2); ctx.lineTo(42, H0 - 3); ctx.closePath(); ctx.fill(); + // Cab in player colour. + const cg = ctx.createLinearGradient(0, 1, 0, H0 - 1); + cg.addColorStop(0, mix(col, '#ffffff', 0.4)); cg.addColorStop(1, mix(col, '#000000', 0.45)); + ctx.fillStyle = cg; rr(ctx, 1, 1, 15, H0 - 2, 3); ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.lineWidth = 1; rr(ctx, 1, 1, 15, H0 - 2, 3); ctx.stroke(); + // Smokestack + dome + headlamp. + ctx.fillStyle = '#111'; ctx.beginPath(); ctx.arc(36, H0 / 2, 3.6, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#c9a24a'; ctx.beginPath(); ctx.arc(26, H0 / 2, 2.6, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#fff3c0'; ctx.beginPath(); ctx.arc(43, H0 / 2, 1.6, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = 'rgba(255,255,255,0.35)'; rr(ctx, 16, 4, 22, 2, 1); ctx.fill(); + return addCanvas(scene, key, c); +} + +function bakeMarker(scene, ci) { + const key = `ttr-marker-${ci}`; + if (scene.textures.exists(key)) return key; + const S = 24; + const c = canvas(S * RES, S * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + const col = hex(PLAYER_COLORS[ci].hex); + ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.beginPath(); ctx.arc(S / 2 + 1, S / 2 + 2, 9.5, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = mix(col, '#000000', 0.5); ctx.beginPath(); ctx.arc(S / 2, S / 2 + 1.5, 9.5, 0, Math.PI * 2); ctx.fill(); + const g = ctx.createRadialGradient(S / 2 - 3, S / 2 - 3, 0, S / 2, S / 2, 9.5); + g.addColorStop(0, mix(col, '#ffffff', 0.45)); g.addColorStop(1, col); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(S / 2, S / 2, 9, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 0.8; + ctx.beginPath(); ctx.arc(S / 2, S / 2, 5.5, 0, Math.PI * 2); ctx.stroke(); + return addCanvas(scene, key, c); +} + +// ── furniture ──────────────────────────────────────────────────────────────────── +function bakePlaque(scene) { + const key = 'ttr-plaque'; + if (scene.textures.exists(key)) return key; + const rnd = mulberry32(5); + const w = OPP.w * RES, h = OPP.h * RES; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + rr(ctx, 0, 0, OPP.w, OPP.h, 10); + woodFill(ctx, 0, 0, OPP.w, OPP.h, '#7a5130', '#4a2d16', rnd, 5); + ctx.strokeStyle = 'rgba(255,220,170,0.25)'; ctx.lineWidth = 1.5; + rr(ctx, 1.5, 1.5, OPP.w - 3, OPP.h - 3, 9); ctx.stroke(); + ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 1; + rr(ctx, 0.5, 0.5, OPP.w - 1, OPP.h - 1, 10); ctx.stroke(); + // Parchment inset for the stats. + ctx.fillStyle = 'rgba(240,226,190,0.92)'; + rr(ctx, 76, 34, OPP.w - 84, OPP.h - 42, 5); ctx.fill(); + ctx.strokeStyle = 'rgba(90,60,30,0.6)'; rr(ctx, 76, 34, OPP.w - 84, OPP.h - 42, 5); ctx.stroke(); + for (const [x, y] of [[8, 8], [OPP.w - 8, 8], [8, OPP.h - 8], [OPP.w - 8, OPP.h - 8]]) brassScrew(ctx, x, y, 3.2); + return addCanvas(scene, key, c); +} + +function bakeRack(scene) { + const key = 'ttr-rack'; + if (scene.textures.exists(key)) return key; + const rnd = mulberry32(9); + const w = RACK.w * RES, h = RACK.h * RES; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + // Back board. + rr(ctx, 0, 0, RACK.w, RACK.h - 14, 10); + woodFill(ctx, 0, 0, RACK.w, RACK.h, '#6b4527', '#3c2512', rnd, 5); + ctx.strokeStyle = 'rgba(0,0,0,0.55)'; ctx.lineWidth = 1; rr(ctx, 0.5, 0.5, RACK.w - 1, RACK.h - 15, 10); ctx.stroke(); + // Slots (darker recesses behind each card). + for (let i = 0; i < 5; i++) { + const x = 46 + i * 81.5; + ctx.fillStyle = 'rgba(0,0,0,0.35)'; + rr(ctx, x - 41, 12, 82, RACK.h - 30, 6); ctx.fill(); + } + // Front lip. + ctx.beginPath(); rr(ctx, -2, RACK.h - 26, RACK.w + 4, 26, 6); + woodFill(ctx, 0, RACK.h - 26, RACK.w, 26, '#8a5c34', '#4a2d16', rnd, 4); + ctx.fillStyle = 'rgba(255,220,170,0.25)'; ctx.fillRect(4, RACK.h - 25, RACK.w - 8, 2); + // Brass plate. + const pg = ctx.createLinearGradient(0, RACK.h - 20, 0, RACK.h - 6); + pg.addColorStop(0, '#f3d98a'); pg.addColorStop(1, '#9a7428'); + ctx.fillStyle = pg; rr(ctx, RACK.w / 2 - 70, RACK.h - 21, 140, 15, 3); ctx.fill(); + ctx.fillStyle = '#3b2a10'; ctx.font = `bold 10px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText('FREIGHT OFFICE', RACK.w / 2, RACK.h - 13); + return addCanvas(scene, key, c); +} + +export const TICKET_TEX = { w: 272, h: 132 }; + +function bakeTicket(scene) { + const key = 'ttr-ticket'; + if (scene.textures.exists(key)) return key; + const { w: W0, h: H0 } = TICKET_TEX; + const c = canvas(W0 * RES, H0 * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + // Card. + ctx.save(); + rr(ctx, 1, 1, W0 - 2, H0 - 2, 10); + const g = ctx.createLinearGradient(0, 0, W0, H0); + g.addColorStop(0, '#f6ead0'); g.addColorStop(1, '#e8d6ab'); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + ctx.fillStyle = noisePattern(ctx, 64, 18); ctx.fillRect(0, 0, W0, H0); + // Engraved guilloche band at the top. + ctx.strokeStyle = 'rgba(120,70,40,0.22)'; ctx.lineWidth = 0.7; + for (let k = 0; k < 6; k++) { + ctx.beginPath(); + for (let x = 0; x <= W0; x += 3) { + const y = 14 + Math.sin(x * 0.12 + k) * 5; + if (!x) ctx.moveTo(x, y); else ctx.lineTo(x, y); + } + ctx.stroke(); + } + ctx.restore(); + // Borders. + ctx.strokeStyle = '#7a4a2a'; ctx.lineWidth = 2; + rr(ctx, 1, 1, W0 - 2, H0 - 2, 10); ctx.stroke(); + ctx.strokeStyle = 'rgba(122,74,42,0.55)'; ctx.lineWidth = 1; + rr(ctx, 6, 6, W0 - 12, H0 - 12, 7); ctx.stroke(); + // Stub perforation + punch hole. + ctx.setLineDash([2, 3]); ctx.strokeStyle = 'rgba(122,74,42,0.6)'; + ctx.beginPath(); ctx.moveTo(W0 - 62, 8); ctx.lineTo(W0 - 62, H0 - 8); ctx.stroke(); + ctx.setLineDash([]); + ctx.fillStyle = 'rgba(40,24,10,0.85)'; + ctx.beginPath(); ctx.arc(W0 - 31, H0 - 22, 5, 0, Math.PI * 2); ctx.fill(); + // Header. + ctx.fillStyle = '#7a4a2a'; ctx.font = `11px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + if ('letterSpacing' in ctx) ctx.letterSpacing = '3px'; + ctx.fillText('DESTINATION', (W0 - 62) / 2 + 2, 30); + return addCanvas(scene, key, c); +} + +function bakeTicketBack(scene) { + const key = 'ttr-ticket-back'; + if (scene.textures.exists(key)) return key; + const W0 = TICKET_BOX.w, H0 = TICKET_BOX.h; + const c = canvas(W0 * RES, H0 * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + rr(ctx, 1, 1, W0 - 2, H0 - 2, 8); + const g = ctx.createLinearGradient(0, 0, 0, H0); + g.addColorStop(0, '#3f6b45'); g.addColorStop(1, '#244029'); + ctx.fillStyle = g; ctx.fill(); + ctx.strokeStyle = '#d6b05c'; ctx.lineWidth = 1.5; rr(ctx, 5, 5, W0 - 10, H0 - 10, 6); ctx.stroke(); + ctx.fillStyle = '#e8c86a'; ctx.font = `15px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + if ('letterSpacing' in ctx) ctx.letterSpacing = '2px'; + ctx.fillText('TICKETS', W0 / 2, H0 / 2 - 6); + ctx.font = `italic 9px ${SERIF}`; + ctx.fillText('Grand Trunk Lines', W0 / 2, H0 / 2 + 12); + return addCanvas(scene, key, c); +} + +function bakeNotepad(scene) { + const key = 'ttr-notepad'; + if (scene.textures.exists(key)) return key; + const W0 = NOTEPAD.w, H0 = NOTEPAD.h; + const c = canvas(W0 * RES, H0 * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; rr(ctx, 3, 5, W0 - 4, H0 - 5, 6); ctx.fill(); + ctx.fillStyle = '#f3ead2'; rr(ctx, 0, 0, W0 - 4, H0 - 6, 6); ctx.fill(); + ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(0, 0, W0 - 4, H0 - 6); + ctx.strokeStyle = 'rgba(80,120,170,0.3)'; ctx.lineWidth = 1; + for (let y = 40; y < H0 - 10; y += 22) { ctx.beginPath(); ctx.moveTo(8, y); ctx.lineTo(W0 - 12, y); ctx.stroke(); } + ctx.strokeStyle = 'rgba(190,70,70,0.35)'; ctx.beginPath(); ctx.moveTo(30, 28); ctx.lineTo(30, H0 - 8); ctx.stroke(); + // Header strip. + ctx.fillStyle = '#5b3b22'; rr(ctx, 0, 0, W0 - 4, 26, 6); ctx.fill(); ctx.fillRect(0, 14, W0 - 4, 12); + ctx.fillStyle = '#e8c86a'; ctx.font = `13px ${DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + if ('letterSpacing' in ctx) ctx.letterSpacing = '3px'; + ctx.fillText('DISPATCH LOG', (W0 - 4) / 2, 14); + return addCanvas(scene, key, c); +} + +function bakeLongest(scene) { + const key = 'ttr-longest'; + if (scene.textures.exists(key)) return key; + const W0 = LONGEST.w, H0 = LONGEST.h; + const c = canvas(W0 * RES, H0 * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + const g = ctx.createLinearGradient(0, 0, 0, H0); + g.addColorStop(0, '#f0d27e'); g.addColorStop(0.5, '#c79a3e'); g.addColorStop(1, '#8a6420'); + ctx.fillStyle = g; rr(ctx, 0, 0, W0, H0, 8); ctx.fill(); + ctx.strokeStyle = 'rgba(60,40,10,0.7)'; ctx.lineWidth = 1.2; rr(ctx, 4, 4, W0 - 8, H0 - 8, 6); ctx.stroke(); + for (const [x, y] of [[10, H0 / 2], [W0 - 10, H0 / 2]]) brassScrew(ctx, x, y, 3.5); + return addCanvas(scene, key, c); +} + +function bakeBadge(scene) { + const key = 'ttr-badge'; + if (scene.textures.exists(key)) return key; + const S = 30; + const c = canvas(S * RES, S * RES); + const ctx = c.getContext('2d'); + ctx.scale(RES, RES); + ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.beginPath(); ctx.arc(S / 2 + 1, S / 2 + 1.5, 13, 0, Math.PI * 2); ctx.fill(); + const g = ctx.createRadialGradient(S / 2 - 4, S / 2 - 4, 0, S / 2, S / 2, 13); + g.addColorStop(0, '#fff0b0'); g.addColorStop(0.55, '#d1a448'); g.addColorStop(1, '#7a5718'); + ctx.fillStyle = g; ctx.beginPath(); ctx.arc(S / 2, S / 2, 13, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(60,40,10,0.8)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(S / 2, S / 2, 10.5, 0, Math.PI * 2); ctx.stroke(); + return addCanvas(scene, key, c); +} + +function bakeCardShadow(scene) { + const key = 'ttr-card-shadow'; + if (scene.textures.exists(key)) return key; + const pad = 16; + const W0 = CARD.w + pad * 2, H0 = CARD.h + pad * 2; + const c = canvas(W0, H0); + const ctx = c.getContext('2d'); + ctx.filter = 'blur(5px)'; + ctx.fillStyle = 'rgba(0,0,0,0.55)'; + rr(ctx, pad, pad, CARD.w, CARD.h, 6); ctx.fill(); + return addCanvas(scene, key, c); +} + +function bakeFx(scene) { + const radial = (key, size, stops) => { + if (scene.textures.exists(key)) return; + const c = canvas(size, size); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2); + stops.forEach(([o, col]) => g.addColorStop(o, col)); + ctx.fillStyle = g; ctx.fillRect(0, 0, size, size); + addCanvas(scene, key, c); + }; + radial('ttr-glow', 64, [[0, 'rgba(255,255,255,1)'], [0.35, 'rgba(255,255,255,0.55)'], [1, 'rgba(255,255,255,0)']]); + radial('ttr-steam', 32, [[0, 'rgba(255,255,255,0.9)'], [0.6, 'rgba(240,240,240,0.35)'], [1, 'rgba(240,240,240,0)']]); + radial('ttr-spark', 12, [[0, 'rgba(255,250,220,1)'], [0.5, 'rgba(255,220,120,0.8)'], [1, 'rgba(255,200,80,0)']]); + if (!scene.textures.exists('ttr-cloud')) { + const c = canvas(320, 200); + const ctx = c.getContext('2d'); + const rnd = mulberry32(3); + for (let i = 0; i < 9; i++) { + const x = 70 + rnd() * 180, y = 60 + rnd() * 80, r = 40 + rnd() * 50; + const g = ctx.createRadialGradient(x, y, 0, x, y, r); + g.addColorStop(0, 'rgba(30,24,16,0.35)'); g.addColorStop(1, 'rgba(30,24,16,0)'); + ctx.fillStyle = g; ctx.fillRect(x - r, y - r, r * 2, r * 2); + } + addCanvas(scene, 'ttr-cloud', c); + } +} + +// ── entry point ────────────────────────────────────────────────────────────────── +// Waits (briefly) for the display fonts so canvas text bakes in the right face. +export async function prepareTicketToRideArt(scene) { + try { + if (document.fonts?.load) { + await Promise.race([ + Promise.all([document.fonts.load('20px Caesar'), document.fonts.load('14px "Julius Sans One"')]), + new Promise((res) => setTimeout(res, 1200)), + ]); + } + } catch (_) { /* fall back to Georgia */ } + bakeDesk(scene); + bakeMap(scene); + bakeCarShadow(scene); + PLAYER_COLORS.forEach((_, ci) => { bakeCar(scene, ci); bakeLoco(scene, ci); bakeMarker(scene, ci); }); + bakePlaque(scene); + bakeRack(scene); + bakeTicket(scene); + bakeTicketBack(scene); + bakeNotepad(scene); + bakeLongest(scene); + bakeBadge(scene); + bakeCardShadow(scene); + bakeFx(scene); +} diff --git a/src/games/tickettoride/TicketToRideDialogs.js b/src/games/tickettoride/TicketToRideDialogs.js new file mode 100644 index 0000000..b561700 --- /dev/null +++ b/src/games/tickettoride/TicketToRideDialogs.js @@ -0,0 +1,271 @@ +// TicketToRideDialogs.js — the table's pop-ups, styled as parchment in a +// wooden frame. Each opener returns { close() } and swallows clicks beneath it. +// +// openTicketChooser keep/return dealt tickets (sits on the desk pad so the +// map stays visible; hovering a ticket lights it up there) +// openPaymentChooser pick which cards pay for a route (card thumbnails) +// openPauseMenu resume · AI speed · helpers · rules · leave +// openLog the full dispatch log (wheel / drag scroll) +// confirmBox yes/no + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { CITIES, CARD_LABEL, TICKETS } from './TicketToRideBoard.js'; +import { PAD, SHEET } from './TicketToRideLayout.js'; +import { SERIF, DISPLAY, TICKET_TEX } from './TicketToRideArt.js'; +import { CARD_FRAME } from './TicketToRideHud.js'; + +const INK = '#3b2a17'; + +function frame(scene, x, y, w, h, depth) { + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 4, y + 8, w, h, 14); + g.fillStyle(0x4a2d16, 1).fillRoundedRect(x, y, w, h, 14); + g.lineStyle(2, 0xc9a24a, 0.9).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 11); + g.fillStyle(0xf1e4c0, 1).fillRoundedRect(x + 10, y + 10, w - 20, h - 20, 8); + g.lineStyle(1, 0x7a4a2a, 0.6).strokeRoundedRect(x + 16, y + 16, w - 32, h - 32, 6); + return g; +} + +function blocker(scene, depth, alpha = 0) { + const r = scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, alpha) + .setDepth(depth).setInteractive(); + return r; +} + +function title(scene, x, y, text, depth, size = 24) { + return scene.add.text(x, y, text, { fontFamily: DISPLAY, fontSize: `${size}px`, color: INK, align: 'center' }) + .setOrigin(0.5).setDepth(depth); +} + +function handle(objs, onClose) { + let closed = false; + return { + objs, + close() { + if (closed) return; + closed = true; + objs.forEach((o) => o?.destroy?.()); + onClose?.(); + }, + }; +} + +// ── destination tickets ──────────────────────────────────────────────────────── +export function openTicketChooser(scene, { pend, hud, depth, estimate, onHover, onToggle, onConfirm }) { + const setup = pend.context === 'setup'; + const selected = new Set(pend.drawn); + const objs = []; + objs.push(blocker(scene, depth - 1, 0.25)); + objs.push(frame(scene, PAD.x, PAD.y, PAD.w, PAD.h, depth)); + const cx = PAD.x + PAD.w / 2; + objs.push(title(scene, cx, PAD.y + 52, setup ? 'Your First Destinations' : 'New Destination Tickets', depth + 1, 24)); + objs.push(scene.add.text(cx, PAD.y + 88, `Keep at least ${pend.minKeep}. Returned tickets go to the bottom of the box.\nHover a ticket to see its route on the map.`, { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#5a4428', align: 'center', wordWrap: { width: PAD.w - 60 }, + }).setOrigin(0.5).setDepth(depth + 1)); + + const scale = 1.25; + const rows = []; + let confirm; + const refresh = () => { + rows.forEach(({ id, c, keep, ret }) => { + const on = selected.has(id); + c.setAlpha(on ? 1 : 0.55); + keep.setVisible(on); ret.setVisible(!on); + }); + confirm.setEnabled(selected.size >= pend.minKeep); + confirm.setLabel(`Keep ${selected.size} ticket${selected.size === 1 ? '' : 's'}`); + }; + pend.drawn.forEach((id, i) => { + const t = { ...TICKETS[id], done: false }; + const est = estimate(t); + const y = PAD.y + 230 + i * 196; + const c = hud.ticketMini(t, cx, y, depth + 2, null, scale); + const k = scale; + const left = -TICKET_TEX.w / 2 * k + 14 * k; + const estLine = est.need === Infinity ? 'No open path — cannot be completed' + : est.need === 0 ? 'Already connected!' : `About ${est.need} trains to connect`; + c.add(scene.add.text(left, 50 * k, estLine, { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: est.need === Infinity ? '#b0281a' : est.need === 0 ? '#2f7a3a' : '#6b4a2a', + }).setOrigin(0, 0.5)); + if (est.overlap?.length) { + c.add(scene.add.text(0, (TICKET_TEX.h / 2 + 14) * k, `Shares track with: ${est.overlap.join(', ')}`, { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#e8d6a8', backgroundColor: '#2e1d0fcc', padding: { x: 6, y: 2 }, + }).setOrigin(0.5, 0)); + } + const keep = scene.add.text(TICKET_TEX.w / 2 * k - 64 * k, 18 * k, 'KEEP', { + fontFamily: DISPLAY, fontSize: '22px', color: '#2f7a3a', stroke: '#f1e4c0', strokeThickness: 3, + }).setOrigin(0.5).setAngle(-12); + const ret = scene.add.text(TICKET_TEX.w / 2 * k - 64 * k, 18 * k, 'RETURN', { + fontFamily: DISPLAY, fontSize: '18px', color: '#8a3a2a', stroke: '#f1e4c0', strokeThickness: 3, + }).setOrigin(0.5).setAngle(-12); + c.add([keep, ret]); + c.setSize(TICKET_TEX.w * k, TICKET_TEX.h * k); + c.setInteractive({ useHandCursor: true }); + c.on('pointerover', () => { onHover?.(t); scene.tweens.add({ targets: c, scale: 1.04, duration: 100 }); }); + c.on('pointerout', () => { onHover?.(null); scene.tweens.add({ targets: c, scale: 1, duration: 100 }); }); + c.on('pointerdown', () => { + if (selected.has(id)) selected.delete(id); else selected.add(id); + onToggle?.(); + refresh(); + }); + // Deal-in. + c.setScale(0.2).setAlpha(0); + scene.tweens.add({ targets: c, scale: 1, alpha: 1, duration: 280, delay: 80 * i, ease: 'Back.easeOut' }); + rows.push({ id, c, keep, ret }); + objs.push(c); + }); + confirm = new Button(scene, cx, PAD.y + PAD.h - 64, 'Keep', () => { + if (selected.size < pend.minKeep) return; + h.close(); + onConfirm([...selected]); + }, { width: 260, height: 54, fontSize: 21, bg: 0x2f5a37 }).setDepth(depth + 3); + objs.push(confirm); + refresh(); + hud.hidePortraits(); + const h = handle(objs, () => { onHover?.(null); hud.showPortraits(); }); + return h; +} + +// ── payment ────────────────────────────────────────────────────────────────────── +export function openPaymentChooser(scene, { route, options, anchor, depth, onPick, onAlwaysFewest }) { + const objs = [blocker(scene, depth - 1, 0.2)]; + const rowH = 70; + const w = 380, h = 120 + options.length * rowH + 50; + const x = Math.max(SHEET.x + 20, Math.min(SHEET.x + SHEET.w - w - 20, anchor.x - w / 2)); + const y = Math.max(SHEET.y + 50, Math.min(SHEET.y + SHEET.h - h - 20, anchor.y - h - 30)); + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 40, `${CITIES[route.a].name} – ${CITIES[route.b].name}`, depth + 1, 19)); + objs.push(scene.add.text(x + w / 2, y + 66, 'Pay with which cards?', { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#5a4428', + }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + options.forEach((opt, i) => { + const ry = y + 104 + i * rowH; + const bg = scene.add.rectangle(x + w / 2, ry, w - 50, rowH - 10, 0xe6d3a2, 1) + .setStrokeStyle(1.5, 0x7a4a2a, 0.7).setDepth(depth + 1).setInteractive({ useHandCursor: true }); + bg.on('pointerover', () => bg.setFillStyle(0xf8e7b4, 1).setStrokeStyle(2.5, 0xc9a24a, 1)); + bg.on('pointerout', () => bg.setFillStyle(0xe6d3a2, 1).setStrokeStyle(1.5, 0x7a4a2a, 0.7)); + bg.on('pointerdown', () => { hRef.close(); onPick(opt); }); + objs.push(bg); + let cx = x + 50; + const group = (key, n) => { + for (let k = 0; k < Math.min(n, 6); k++) { + objs.push(scene.add.image(cx + k * 9, ry, 'ttr-cards', CARD_FRAME[key]).setDisplaySize(34, 49).setDepth(depth + 2)); + } + cx += Math.min(n, 6) * 9 + 30; + objs.push(scene.add.text(cx - 2, ry, `×${n}`, { fontFamily: 'Righteous', fontSize: '18px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 2)); + cx += 44; + }; + if (opt.colorCount > 0) group(opt.color, opt.colorCount); + if (opt.locos > 0) group('locomotive', opt.locos); + const label = [opt.colorCount ? `${opt.colorCount} ${CARD_LABEL[opt.color]}` : null, opt.locos ? `${opt.locos} Loco` : null].filter(Boolean).join(' + '); + objs.push(scene.add.text(x + w - 36, ry, label, { fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#5a4428' }) + .setOrigin(1, 0.5).setDepth(depth + 2)); + }); + const fy = y + h - 34; + const always = scene.add.text(x + 28, fy, '☐ Always pay with the fewest locomotives', { + fontFamily: SERIF, fontSize: '13px', color: '#5a4428', + }).setOrigin(0, 0.5).setDepth(depth + 1).setInteractive({ useHandCursor: true }); + always.on('pointerdown', () => { hRef.close(); onAlwaysFewest?.(); onPick(options[0]); }); + const cancel = scene.add.text(x + w - 28, fy, 'Cancel', { + fontFamily: 'Righteous', fontSize: '16px', color: '#8a3a2a', + }).setOrigin(1, 0.5).setDepth(depth + 1).setInteractive({ useHandCursor: true }); + cancel.on('pointerdown', () => { hRef.close(); onPick(null); }); + objs.push(always, cancel); + objs[0].on('pointerdown', () => { hRef.close(); onPick(null); }); + hRef = handle(objs); + return hRef; +} + +// ── pause / settings ────────────────────────────────────────────────────────────── +export function openPauseMenu(scene, { settings, depth, onChange, onRules, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.45)]; + const w = 460, h = 470; + const x = SHEET.x + SHEET.w / 2 - w / 2, y = SHEET.y + SHEET.h / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 48, 'Station Master', depth + 1, 26)); + const cx = x + w / 2; + let hRef = null; + const paceLabel = () => `Opponent speed: ${({ relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' })[settings.pace]}`; + const onOff = (v) => (v ? 'On' : 'Off'); + const rows = [ + ['Resume', () => hRef.close()], + [paceLabel(), (b) => { + const order = ['relaxed', 'normal', 'fast']; + onChange('pace', order[(order.indexOf(settings.pace) + 1) % order.length]); + b.setLabel(paceLabel()); + }], + [`Show claimable routes: ${onOff(settings.showAffordable)}`, (b) => { + onChange('showAffordable', !settings.showAffordable); + b.setLabel(`Show claimable routes: ${onOff(settings.showAffordable)}`); + }], + [`Ask which cards to pay: ${onOff(settings.askPayment)}`, (b) => { + onChange('askPayment', !settings.askPayment); + b.setLabel(`Ask which cards to pay: ${onOff(settings.askPayment)}`); + }], + ['How to Play', () => { onRules(); }], + ['Leave Game', () => { hRef.close(); onLeave(); }], + ]; + rows.forEach(([label, fn], i) => { + const btn = new Button(scene, cx, y + 110 + i * 56, label, () => fn(btn), { + width: 360, height: 46, fontSize: 18, bg: i === 0 ? 0x2f5a37 : 0x5a3820, + }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 34, 'Keys: 1–5 market · D deck · T tickets · R routes · L log · P pass · Esc menu', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#5a4428', + }).setOrigin(0.5).setDepth(depth + 1)); + hRef = handle(objs, onClose); + return hRef; +} + +// ── log ──────────────────────────────────────────────────────────────────────────── +export function openLog(scene, { log, depth, onClose }) { + const objs = [blocker(scene, depth - 1, 0.45)]; + const w = 720, h = 680; + const x = SHEET.x + SHEET.w / 2 - w / 2, y = SHEET.y + SHEET.h / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 46, 'Dispatch Log', depth + 1, 26)); + const viewY = y + 80, viewH = h - 150; + const body = scene.add.text(x + 40, viewY, log.slice().reverse().map((l, i) => `${String(log.length - i).padStart(3, ' ')}. ${l}`).join('\n'), { + fontFamily: SERIF, fontSize: '16px', color: '#2a3a5a', lineSpacing: 8, wordWrap: { width: w - 80 }, + }).setDepth(depth + 1); + const maskG = scene.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRect(x + 20, viewY, w - 40, viewH); + body.setMask(maskG.createGeometryMask()); + objs.push(body, { destroy: () => maskG.destroy() }); + const maxScroll = Math.max(0, body.height - viewH); + let off = 0; + const onWheel = (_p, _o, _dx, dy) => { off = Math.max(0, Math.min(maxScroll, off + dy * 0.6)); body.y = viewY - off; }; + scene.input.on('wheel', onWheel); + objs.push({ destroy: () => scene.input.off('wheel', onWheel) }); + if (maxScroll > 0) { + objs.push(scene.add.text(x + w - 40, viewY + viewH + 8, 'scroll for more ↓', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#5a4428', + }).setOrigin(1, 0).setDepth(depth + 1)); + } + let hRef = null; + objs.push(new Button(scene, x + w / 2, y + h - 40, 'Close', () => hRef.close(), { width: 200, height: 44, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + objs[0].on('pointerdown', () => hRef.close()); + hRef = handle(objs, onClose); + return hRef; +} + +// ── confirm ──────────────────────────────────────────────────────────────────────── +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 480, h = 230; + const x = SHEET.x + SHEET.w / 2 - w / 2, y = SHEET.y + SHEET.h / 2 - h / 2; + objs.push(frame(scene, x, y, w, h, depth)); + objs.push(title(scene, x + w / 2, y + 46, heading, depth + 1, 24)); + objs.push(scene.add.text(x + w / 2, y + 98, text, { + fontFamily: SERIF, fontSize: '16px', color: INK, align: 'center', wordWrap: { width: w - 70 }, + }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + objs.push(new Button(scene, x + w / 2 - 110, y + h - 50, yes, () => { hRef.close(); onYes?.(); }, { width: 190, height: 46, fontSize: 18, bg: 0x2f5a37 }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 110, y + h - 50, no, () => { hRef.close(); onNo?.(); }, { width: 190, height: 46, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} + diff --git a/src/games/tickettoride/TicketToRideEndScreen.js b/src/games/tickettoride/TicketToRideEndScreen.js new file mode 100644 index 0000000..3a1752d --- /dev/null +++ b/src/games/tickettoride/TicketToRideEndScreen.js @@ -0,0 +1,253 @@ +// TicketToRideEndScreen.js — the end-of-line scoring ceremony. +// +// 1. Each player's destination tickets turn over one at a time: a completed +// ticket lights its track and stamps +points, a missed one stamps −points; +// the player's marker hops round the score track as it goes. +// 2. The longest continuous route is traced in light and awarded +10. +// 3. A scoreboard: totals, points by source, and a few stats per player, +// with Play Again / Leave and a "view the map" toggle. +// A Skip button fast-forwards the ceremony. + +import { Button } from '../../ui/Button.js'; +import { playSound, SFX } from '../../ui/Sounds.js'; +import { PLAYER_COLORS, LONGEST_PATH_BONUS } from './TicketToRideBoard.js'; +import * as L from './TicketToRideLogic.js'; +import { SHEET, STATUS } from './TicketToRideLayout.js'; +import { SERIF, DISPLAY } from './TicketToRideArt.js'; +import { whistle } from './TicketToRideSound.js'; + +const INK = '#3b2a17'; + +export async function showTicketToRideEndScreen(scene, { depth, onPlayAgain, onLeave }) { + const gs = scene.gs; + const scores = gs.scores; + const objs = []; + const add = (o) => { objs.push(o); return o; }; + let skip = false; + const wait = (ms) => (skip ? Promise.resolve() : scene.wait(ms)); + scene.ui.holdScores = true; + whistle(scene, { dur: 1.4, vol: 0.14 }); + + const cx = SHEET.x + SHEET.w / 2, cy = SHEET.y + SHEET.h / 2; + const skipBtn = add(new Button(scene, SHEET.x + SHEET.w - 110, SHEET.y + 70, 'Skip ▶', () => { skip = true; skipBtn.setVisible(false); }, { + width: 150, height: 42, fontSize: 17, bg: 0x3a2414, + }).setDepth(depth + 6)); + + const banner = add(scene.add.text(cx, STATUS.y + 4, 'End of the Line', { + fontFamily: DISPLAY, fontSize: '34px', color: '#fff3c8', stroke: '#3b2a17', strokeThickness: 6, + }).setOrigin(0.5).setDepth(depth + 5).setAlpha(0)); + scene.tweens.add({ targets: banner, alpha: 1, duration: 400 }); + scene.setStatus(''); + await wait(900); + + // Running totals start from the route points already on the track. + const running = scores.map((sc) => sc.routePoints); + + // ── 1. tickets ────────────────────────────────────────────────────────────── + for (const sc of scores) { + const seat = sc.seat; + const name = seat === 0 ? 'Your' : `${L.playerName(gs, seat)}'s`; + const head = add(scene.add.text(cx, cy - 170, sc.tickets.length ? `${name} tickets` : `${name} tickets — none`, { + fontFamily: DISPLAY, fontSize: '26px', color: '#fff3c8', stroke: '#3b2a17', strokeThickness: 5, + }).setOrigin(0.5).setDepth(depth + 4)); + add(scene.add.image(cx, cy - 138, `ttr-car-${gs.players[seat].colorIndex}`).setDisplaySize(48, 15).setDepth(depth + 4)); + let n = 0; + for (const t of sc.tickets) { + const x = cx - (Math.min(sc.tickets.length, 5) - 1) * 70 + (n % 5) * 140; + const card = scene.hud.ticketMini({ ...t, done: false }, cx, cy, depth + 3, null, 0.9); + add(card); + card.setScale(0.3).setAlpha(0); + await scene.tw({ targets: card, scale: 1, alpha: 1, duration: skip ? 1 : 220, ease: 'Back.easeOut' }); + scene.cityGlow(t.a, t.done ? 0x9ff0a8 : 0xff8a6a); + scene.cityGlow(t.b, t.done ? 0x9ff0a8 : 0xff8a6a); + if (t.done && !skip) await traceRoutes(scene, scene.networkPath(seat, t.a, t.b), 0x9ff0a8, depth - 30, objs, 45); + const stamp = add(scene.add.text(cx + 70, cy + 4, t.done ? `+${t.points}` : `−${t.points}`, { + fontFamily: 'Righteous', fontSize: '40px', color: t.done ? '#2f9a44' : '#c0392b', stroke: '#f1e4c0', strokeThickness: 5, + }).setOrigin(0.5).setAngle(-12).setDepth(depth + 4).setScale(2.4).setAlpha(0)); + await scene.tw({ targets: stamp, scale: 1, alpha: 1, duration: skip ? 1 : 180, ease: 'Back.easeIn' }); + playSound(scene, t.done ? SFX.UI_CHIME : SFX.CARD_PLACE); + running[seat] += t.done ? t.points : -t.points; + scene.hud.setScoreText(seat, running[seat]); + await (skip ? Promise.resolve() : scene.moveMarker(seat, running[seat], { stepMs: 18 })); + await wait(380); + // Park the ticket in a row along the bottom of the map. + scene.cityGlows.forEach((g) => g.setVisible(false)); + clearTrace(objs); + const parkY = SHEET.y + SHEET.h - 120; + scene.tweens.add({ targets: [card], x, y: parkY, scale: 0.62, duration: skip ? 1 : 260 }); + scene.tweens.add({ targets: [stamp], x: x + 30, y: parkY - 4, scale: 0.55, duration: skip ? 1 : 260 }); + n++; + } + if (skip) { scene.markerScore[seat] = running[seat]; scene.placeMarkers(); } + await wait(sc.tickets.length ? 500 : 700); + // Clear this player's parked tickets. + const mine = objs.splice(objs.indexOf(head)); + mine.forEach((o) => o.destroy?.()); + } + + // ── 2. longest route ──────────────────────────────────────────────────────── + const leaders = scores.filter((sc) => sc.longestBonus > 0); + for (const sc of leaders) { + const seat = sc.seat; + const who = seat === 0 ? 'You' : L.playerName(gs, seat); + const lbl = add(scene.add.text(cx, cy - 170, `Longest Continuous Route\n${who} · ${sc.longestPath} cars`, { + fontFamily: DISPLAY, fontSize: '26px', color: '#ffe48a', stroke: '#3b2a17', strokeThickness: 5, align: 'center', + }).setOrigin(0.5).setDepth(depth + 4)); + whistle(scene, { dur: 0.8, vol: 0.1, pitch: 1.1 }); + if (!skip) await traceRoutes(scene, sc.longestRoutes, 0xffd36b, depth - 30, objs, 60); + const bonus = add(scene.add.text(cx, cy - 100, `+${LONGEST_PATH_BONUS}`, { + fontFamily: 'Righteous', fontSize: '46px', color: '#ffd36b', stroke: '#3b2a17', strokeThickness: 6, + }).setOrigin(0.5).setDepth(depth + 4).setScale(0.3)); + await scene.tw({ targets: bonus, scale: 1, duration: skip ? 1 : 260, ease: 'Back.easeOut' }); + playSound(scene, SFX.UI_CHIME); + running[seat] += LONGEST_PATH_BONUS; + scene.hud.setScoreText(seat, running[seat]); + if (skip) { scene.markerScore[seat] = running[seat]; scene.placeMarkers(); } + else await scene.moveMarker(seat, running[seat], { stepMs: 30 }); + await wait(700); + clearTrace(objs); + lbl.destroy(); bonus.destroy(); + } + + skipBtn.setVisible(false); + banner.destroy(); + scores.forEach((sc) => { scene.markerScore[sc.seat] = sc.total; scene.hud.setScoreText(sc.seat, sc.total); }); + scene.placeMarkers(); + + // ── 3. scoreboard ─────────────────────────────────────────────────────────── + scoreboard(scene, { gs, depth, onPlayAgain, onLeave }); +} + +function clearTrace(objs) { + for (let i = objs.length - 1; i >= 0; i--) { + if (objs[i]?.isTrace) { objs[i].destroy(); objs.splice(i, 1); } + } +} + +async function traceRoutes(scene, routeIds, tint, depth, objs, perSeg) { + for (const rid of routeIds) { + for (const seg of scene.segCache[rid]) { + const s = scene.add.image(seg.cx, seg.cy, 'ttr-glow').setDisplaySize(seg.w * 1.7, 36) + .setRotation(seg.angle).setTint(tint).setBlendMode('ADD').setDepth(depth).setAlpha(0); + s.isTrace = true; + objs.push(s); + scene.tweens.add({ targets: s, alpha: 0.85, duration: 140 }); + await scene.wait(perSeg); + } + } +} + +function scoreboard(scene, { gs, depth, onPlayAgain, onLeave }) { + const objs = []; + const add = (o) => { objs.push(o); return o; }; + const scores = gs.scores.slice().sort((a, b) => b.total - a.total || b.ticketsCompleted - a.ticketsCompleted || b.longestPath - a.longestPath); + const winner = gs.winner; + const human = winner === 0; + const rows = scores.length; + const W = 1040, rowH = 92, H = 230 + rows * rowH; + const x = SHEET.x + SHEET.w / 2 - W / 2, y = SHEET.y + SHEET.h / 2 - H / 2; + + const dim = add(scene.add.rectangle(960, 540, 1920, 1080, 0x000000, 0.45).setInteractive().setDepth(depth)); + const g = add(scene.add.graphics().setDepth(depth + 1)); + g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 6, y + 10, W, H, 16); + g.fillStyle(0x4a2d16, 1).fillRoundedRect(x, y, W, H, 16); + g.lineStyle(2, 0xc9a24a, 0.9).strokeRoundedRect(x + 5, y + 5, W - 10, H - 10, 12); + g.fillStyle(0xf1e4c0, 1).fillRoundedRect(x + 12, y + 12, W - 24, H - 24, 9); + g.lineStyle(1, 0x7a4a2a, 0.6).strokeRoundedRect(x + 18, y + 18, W - 36, H - 36, 7); + + add(scene.add.text(x + W / 2, y + 52, human ? 'Victory!' : `${L.playerName(gs, winner)} wins`, { + fontFamily: DISPLAY, fontSize: '42px', color: human ? '#8a5a10' : INK, + }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.text(x + W / 2, y + 90, `The line is closed after ${Math.ceil((gs.turn ?? 0) / gs.playerCount)} rounds`, { + fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#5a4428', + }).setOrigin(0.5).setDepth(depth + 2)); + + const cols = { name: x + 70, routes: x + 400, tickets: x + 520, longest: x + 660, total: x + 790, bar: x + 840 }; + const hy = y + 126; + const hdr = (t, cxp) => add(scene.add.text(cxp, hy, t, { fontFamily: SERIF, fontSize: '13px', fontStyle: 'bold', color: '#7a4a2a' }).setOrigin(0.5).setDepth(depth + 2)); + hdr('Routes', cols.routes); hdr('Tickets', cols.tickets); hdr('Longest', cols.longest); hdr('Total', cols.total); + hdr('Points by source', cols.bar + 85); + const maxTotal = Math.max(1, ...scores.map((s) => s.routePoints + Math.max(0, s.ticketPoints) + s.longestBonus)); + const bars = add(scene.add.graphics().setDepth(depth + 2)); + + scores.forEach((sc, i) => { + const ry = y + 168 + i * rowH; + const p = gs.players[sc.seat]; + const col = PLAYER_COLORS[p.colorIndex]; + if (i % 2 === 0) { g.fillStyle(0xe2cf9c, 0.6).fillRoundedRect(x + 24, ry - 30, W - 48, rowH - 8, 6); } + add(scene.add.text(x + 42, ry - 6, sc.seat === winner ? '♛' : `${i + 1}`, { + fontFamily: 'Righteous', fontSize: sc.seat === winner ? '28px' : '20px', color: sc.seat === winner ? '#b8860b' : '#7a4a2a', + }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.image(cols.name + 16, ry - 6, `ttr-car-${p.colorIndex}`).setDisplaySize(34, 11).setDepth(depth + 2)); + add(scene.add.text(cols.name + 42, ry - 8, sc.seat === 0 ? 'You' : L.playerName(gs, sc.seat), { + fontFamily: 'Righteous', fontSize: '21px', color: INK, + }).setOrigin(0, 0.5).setDepth(depth + 2)); + const st = p.stats ?? {}; + add(scene.add.text(cols.name + 4, ry + 22, `${p.routes.length} routes · ${45 - p.trainsLeft} trains · ${(st.deckDraws ?? 0) + (st.faceUpDraws ?? 0)} cards drawn · ${st.locosSpent ?? 0} locos spent · longest claim ${st.longestClaim ?? 0}`, { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6b4a2a', + }).setOrigin(0, 0.5).setDepth(depth + 2)); + add(scene.add.text(cols.routes, ry - 6, String(sc.routePoints), { fontFamily: 'Righteous', fontSize: '20px', color: INK }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.text(cols.tickets, ry - 6, `${sc.ticketPoints >= 0 ? '+' : ''}${sc.ticketPoints}`, { + fontFamily: 'Righteous', fontSize: '20px', color: sc.ticketPoints >= 0 ? '#2f7a3a' : '#b0281a', + }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.text(cols.tickets, ry + 16, `✓${sc.ticketsCompleted} ✗${sc.ticketsFailed}`, { + fontFamily: SERIF, fontSize: '12px', color: '#6b4a2a', + }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.text(cols.longest, ry - 6, `${sc.longestPath}${sc.longestBonus ? ' +10' : ''}`, { + fontFamily: 'Righteous', fontSize: '18px', color: sc.longestBonus ? '#b8860b' : INK, + }).setOrigin(0.5).setDepth(depth + 2)); + add(scene.add.text(cols.total, ry - 6, String(sc.total), { fontFamily: 'Righteous', fontSize: '28px', color: INK }).setOrigin(0.5).setDepth(depth + 2)); + // Points-by-source bar: routes (player colour), tickets (green / red), longest (gold). + const bw = 170, bh = 16, bx = cols.bar, by = ry - 14; + const k = bw / maxTotal; + let cxp = bx; + bars.fillStyle(0x000000, 0.12).fillRect(bx, by, bw, bh); + bars.fillStyle(col.hex, 1).fillRect(cxp, by, sc.routePoints * k, bh); cxp += sc.routePoints * k; + if (sc.ticketPoints > 0) { bars.fillStyle(0x3f9a50, 1).fillRect(cxp, by, sc.ticketPoints * k, bh); cxp += sc.ticketPoints * k; } + if (sc.longestBonus) { bars.fillStyle(0xd9a520, 1).fillRect(cxp, by, sc.longestBonus * k, bh); } + if (sc.ticketPoints < 0) { + const lw = Math.min(sc.routePoints * k, -sc.ticketPoints * k); + bars.fillStyle(0xb0281a, 0.75).fillRect(bx + sc.routePoints * k - lw, by + bh - 5, lw, 5); + } + bars.lineStyle(1, 0x3b2a17, 0.6).strokeRect(bx, by, bw, bh); + }); + // Legend. + const ly = y + H - 92; + const legend = [[0x888888, 'routes (player colour)'], [0x3f9a50, 'tickets'], [0xb0281a, 'missed tickets'], [0xd9a520, 'longest route']]; + legend.forEach(([c, t], i) => { + const lx = x + 70 + i * 230; + bars.fillStyle(c, 1).fillRect(lx, ly - 6, 14, 12); + add(scene.add.text(lx + 20, ly, t, { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6b4a2a' }).setOrigin(0, 0.5).setDepth(depth + 2)); + }); + + const panel = objs.slice(); + let shown = true; + const by = y + H - 46; + const viewBtn = new Button(scene, x + W / 2 - 250, by, 'View Map', () => { + shown = !shown; + panel.forEach((o) => o.setVisible?.(shown)); + viewBtn.setLabel(shown ? 'View Map' : 'Show Scores'); + viewBtn.setPosition(shown ? x + W / 2 - 250 : SHEET.x + SHEET.w - 120, shown ? by : SHEET.y + 70); + }, { width: 200, height: 46, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 6); + const again = new Button(scene, x + W / 2, by, 'Play Again', () => onPlayAgain(), { width: 220, height: 46, fontSize: 19, bg: 0x2f5a37 }).setDepth(depth + 3); + const leave = new Button(scene, x + W / 2 + 250, by, 'Leave', () => onLeave(), { width: 200, height: 46, fontSize: 18, bg: 0x5a3820 }).setDepth(depth + 3); + panel.push(again, leave); + + // Fade in. + panel.forEach((o) => o.setAlpha?.(0)); + scene.tweens.add({ targets: panel.filter((o) => o !== dim), alpha: 1, duration: 400 }); + scene.tweens.add({ targets: dim, alpha: 1, duration: 400 }); + + if (human) { + playSound(scene, SFX.VICTORY_SHORT); + let bursts = 0; + scene.time.addEvent({ + delay: 420, repeat: 9, + callback: () => { + const bx = SHEET.x + 200 + Math.random() * (SHEET.w - 400), byy = SHEET.y + 120 + Math.random() * 300; + scene.sparks.explode(28, bx, byy); + if (bursts++ % 3 === 0) playSound(scene, SFX.FIREWORK); + }, + }); + } +} diff --git a/src/games/tickettoride/TicketToRideGame.js b/src/games/tickettoride/TicketToRideGame.js index f9170f4..d85a7c8 100644 --- a/src/games/tickettoride/TicketToRideGame.js +++ b/src/games/tickettoride/TicketToRideGame.js @@ -1,1041 +1,1130 @@ +// TicketToRideGame.js — the Ticket to Ride table (USA). +// +// An antique watercolour railway map pinned to a station-master's desk: +// • the map (TicketToRideArt) carries printed route slots, station pins, +// name tags and the 0–99 score track; claimed routes get plastic cars, +// laid one by one by a little locomotive that steams along the route +// • the right-hand desk pad and the bottom rail are TicketToRideHud +// • pop-ups are TicketToRideDialogs; the scoring ceremony is +// TicketToRideEndScreen +// Game rules live in TicketToRideLogic (pure); opponents in TicketToRideAI +// (skill 1–5 from the opponent-select screen). + import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; -import { auth } from '../../services/auth.js'; import { api } from '../../services/api.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { Tooltip } from '../../ui/Tooltip.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { aiTiming, PACE, clampSkill } from '../../ui/cardtable/AITiming.js'; import { - CITIES, ROUTES, TICKETS, TRAIN_COLORS, CARD_COLOR_HEX, CARD_LABEL, - PLAYER_COLORS, ROUTE_SCORE, LONGEST_PATH_BONUS, - routeSegments, routeMidpoint, LAND_OUTLINE, GREAT_LAKES, + CITIES, ROUTES, PLAYER_COLORS, ROUTE_SCORE, CARD_LABEL, routeSegments, routeMidpoint, } from './TicketToRideBoard.js'; import * as L from './TicketToRideLogic.js'; import * as AI from './TicketToRideAI.js'; +import { prepareTicketToRideArt, ROUTE_INK, SERIF, DISPLAY, CAR_TEX } from './TicketToRideArt.js'; +import { TTRHud, CARD_FRAME } from './TicketToRideHud.js'; +import { + openTicketChooser, openPaymentChooser, openPauseMenu, openLog, confirmBox, +} from './TicketToRideDialogs.js'; +import { showTicketToRideEndScreen } from './TicketToRideEndScreen.js'; +import { whistle, chuff } from './TicketToRideSound.js'; +import { + SHEET, TRACK, CARD, HAND_CARD, marketPos, DECK, DISCARD, TICKET_BOX, PAD, STATUS, trackPos, + MENU_BTN, LOG_BTN, HELP_BTN, ROUTES_BTN, PASS_BTN, +} from './TicketToRideLayout.js'; const D = { - sea: 0, land: 1, lakes: 2, route: 6, train: 10, city: 14, label: 15, - hover: 18, zone: 19, hud: 30, market: 34, panel: 60, modal: 70, banner: 80, + desk: -20, map: -10, glow: 2, carShadow: 5, car: 6, cityGlow: 8, hover: 12, loco: 14, cloud: 16, + zone: 19, marker: 22, fx: 26, hud: 30, hudTop: 40, flight: 60, modal: 70, banner: 80, tooltip: 95, }; - -const HAND_ORDER = [...TRAIN_COLORS, 'locomotive']; - -const TTR_CARD_FRAME = { - red: 0, orange: 1, yellow: 2, green: 3, blue: 4, - purple: 5, black: 6, white: 7, locomotive: 8, back: 9, -}; - -// Muted palette for unclaimed route segments — desaturated so claimed (player-coloured) routes pop. -const TTR_ROUTE_HEX = { - red: 0x8c5050, // dusty brick - orange: 0x8c6030, // muted amber - yellow: 0x7a6820, // olive - green: 0x4a6840, // sage - blue: 0x3a5470, // slate - purple: 0x5a3a6c, // dusty plum - black: 0x383838, // dark charcoal - white: 0xd4cfc8, // bright warm gray - gray: 0x706860, // neutral warm gray -}; - -// Right-band + bottom-strip layout (1920×1080). The map occupies x<1400. -const RB = { x0: 1408, cx: 1660, w: 512 }; -const OPP_COL1_X = 1480, OPP_COL2_X = 1736, OPP_Y0 = 150, OPP_STEP = 150, OPP_R = 32; -const MK_X = 1476, MK_Y0 = 507, MK_STEP = 104, CARD_W = 78, CARD_H = 112; -const MINI_W = 22, MINI_H = 32, MINI_STEP = 14; -const PILE_X = 1646; -const BOT_Y = 980; +const SETTINGS_KEY = 'ttr-settings'; +const DEFAULT_SETTINGS = { pace: 'normal', showAffordable: false, askPayment: true }; +const hexStr = (n) => `#${n.toString(16).padStart(6, '0')}`; +const inkInt = (c) => parseInt((ROUTE_INK[c] ?? ROUTE_INK.gray).slice(1), 16); export default class TicketToRideGame extends Phaser.Scene { constructor() { super('TicketToRideGame'); } init(data) { + this.initData = data; this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; this.gs = null; - this._setBusy(false); - this._suppressHandRender = false; - this.opponentPortraits = []; - this.modalObjs = []; - this.marketObjs = []; - this.handObjs = []; - this.hoverRouteId = null; - this.bannerShownFor = -1; - this.playerScoreText = null; - this.scoreBadgeContainers = []; - this.oppScoreTexts = {}; - this.oppMiniHandGfx = []; - this.oppMiniHandCount = []; - this.marketSlotObjs = []; - this.trainCarObjs = []; + this.busy = false; + this.modal = null; + this.ended = false; + this.carSprites = new Map(); + this.animatingRoute = null; + this.hl = { route: null, pile: null, ticket: null, opp: null, longest: false }; + this.ui = { suppressHand: false, holdScores: false, hiddenMarket: new Set() }; + this.markerScore = []; + this.markers = []; + try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } } create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch (_) { /* no music json */ } - this.buildParticleTexture(); - this.buildTrainCarTexture(); - this.buildBackdrop(); - this.buildStaticBoard(); - this.buildRightPanel(); - this.buildHUD(); + // Music controls hang in the map's top-right corner (inside the score track), + // clear of the desk pad's Menu / Log / How to Play buttons. + try { + new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? [], undefined, { + right: SHEET.x + SHEET.w - TRACK.inset - TRACK.band - 2, + top: SHEET.y + TRACK.inset + TRACK.band - 4, + infoColor: '#5a4428', + }); + } catch (_) { /* no music json */ } + this.events.once('shutdown', () => { this.ended = true; }); + prepareTicketToRideArt(this).then(() => { + if (!this.sys?.isActive()) return; + this.build(); + }); + } + + build() { + this.tooltip = new Tooltip(this, { depth: D.tooltip, hoverDelay: 220 }); + this.buildTable(); + this.buildMapLayers(); + this.buildAmbient(); + this.buildButtons(); + this.buildStatus(); + this.buildKeys(); this.startNewMatch(); } - buildParticleTexture() { - const g = this.make.graphics({ x: 0, y: 0, add: false }); - g.fillStyle(0xffffff, 1); g.fillCircle(5, 5, 5); - g.generateTexture('ttrParticle', 10, 10); - g.destroy(); - } - - buildTrainCarTexture() { - const g = this.make.graphics({ x: 0, y: 0, add: false }); - g.fillStyle(0xffffff, 1); g.fillRoundedRect(1, 3, 118, 34, 4); // body - g.fillStyle(0xffffff, 1); g.fillRect(5, 3, 110, 9); // roof (white = full tint brightness) - g.fillStyle(0x181818, 1); g.fillRect(14, 14, 92, 12); // window glass (dark contrast detail) - g.fillStyle(0xffffff, 1); g.fillRect(42, 14, 4, 12); // mullion 1 - g.fillRect(74, 14, 4, 12); // mullion 2 - g.fillStyle(0xeeeeee, 1); g.fillRoundedRect(10, 30, 22, 9, 2); // left truck - g.fillRoundedRect(88, 30, 22, 9, 2); // right truck - g.fillStyle(0xeeeeee, 1); g.fillRect(30, 29, 60, 4); // underframe - g.fillStyle(0xffffff, 1); g.fillRect(1, 13, 3, 14); // left end cap - g.fillRect(116, 13, 3, 14); // right end cap - g.generateTexture('ttr-train-car', 120, 40); - g.destroy(); - } - - // ── backdrop: sea + land silhouette ───────────────────────────────────────── - buildBackdrop() { + // ── table + map ─────────────────────────────────────────────────────────────── + buildTable() { if (this.playfield?.key && this.textures.exists(this.playfield.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, this.playfield.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.sea - 1); + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, this.playfield.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.desk - 1); + // Keep the desk pad and the rail from the baked desk over the cloth. + const pad = this.add.image(0, 0, 'ttr-desk').setOrigin(0).setDepth(D.desk); + pad.setCrop(PAD.x - 10, PAD.y - 6, PAD.w + 20, GAME_HEIGHT); + const rail = this.add.image(0, 0, 'ttr-desk').setOrigin(0).setDepth(D.desk); + rail.setCrop(0, SHEET.y + SHEET.h, GAME_WIDTH, GAME_HEIGHT); + } else { + this.add.image(0, 0, 'ttr-desk').setOrigin(0).setDepth(D.desk); } - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x10384a).setDepth(D.sea); - - const land = this.add.graphics().setDepth(D.land); - const pts = LAND_OUTLINE.map(([x, y]) => ({ x, y })); - land.fillStyle(0xcdb585, 1); - land.fillPoints(pts, true); - land.lineStyle(5, 0x8a6f3e, 0.9); - land.strokePoints(pts, true); - // soft inland shading - land.fillStyle(0xd8c498, 0.4); - land.fillPoints(pts.map((p) => ({ x: p.x, y: p.y - 6 })), true); - - const lakes = this.add.graphics().setDepth(D.lakes); - lakes.fillStyle(0x2f6f8a, 0.85); - lakes.fillPoints(GREAT_LAKES.map(([x, y]) => ({ x, y })), true); + this.add.image(SHEET.x, SHEET.y, 'ttr-map').setOrigin(0).setDepth(D.map); + // Lamp: a slow, faint warm flicker over the map. + this.lamp = this.add.image(760, 430, 'ttr-glow').setDisplaySize(1900, 1300) + .setTint(0xffc070).setBlendMode('ADD').setAlpha(0.06).setDepth(D.cloud + 1); + this.time.addEvent({ + delay: 2400, loop: true, + callback: () => this.tweens.add({ targets: this.lamp, alpha: 0.045 + Math.random() * 0.035, duration: 900 + Math.random() * 900 }), + }); } - // ── cities + route segments ───────────────────────────────────────────────── - buildStaticBoard() { - // Precompute segment + midpoint geometry once. + buildMapLayers() { this.segCache = ROUTES.map((r) => routeSegments(r)); this.midCache = ROUTES.map((r) => routeMidpoint(r)); + this.glowGfx = this.add.graphics().setDepth(D.glow); + this.topGfx = this.add.graphics().setDepth(D.hover); + this.cityGlows = CITIES.map((c) => this.add.image(c.x, c.y, 'ttr-glow').setDisplaySize(58, 58) + .setBlendMode('ADD').setVisible(false).setDepth(D.cityGlow)); - this.routeGfx = this.add.graphics().setDepth(D.route); - this.trainStrokeGfx = this.add.graphics().setDepth(D.train + 1); - this.hoverGfx = this.add.graphics().setDepth(D.hover); - - // Invisible rotated hit-zone per route. this.routeZones = ROUTES.map((r, id) => { const m = this.midCache[id]; - const zone = this.add.zone(m.x, m.y, Math.max(m.length, 24), m.width + 12) - .setRotation(m.angle) - .setInteractive({ useHandCursor: true }) - .setDepth(D.zone); - zone.on('pointerover', () => this.onRouteHover(id)); - zone.on('pointerout', () => this.onRouteHover(null)); - zone.on('pointerdown', () => this.onRouteClick(id)); - return zone; + const z = this.add.zone(m.x, m.y, Math.max(m.length, 24), m.width + 6) + .setRotation(m.angle).setInteractive({ useHandCursor: true }).setDepth(D.zone); + z.on('pointerover', () => { this.hl.route = id; this.renderHighlights(); }); + z.on('pointerout', () => { if (this.hl.route === id) { this.hl.route = null; this.renderHighlights(); } }); + z.on('pointerdown', () => this.onRouteClick(id)); + return z; }); + this.routeZones.forEach((z, id) => this.tooltip.attachTo(z, () => this.routeTooltip(id))); - // Cities (static): dot + label. - for (const c of CITIES) { - const g = this.add.graphics().setDepth(D.city); - g.fillStyle(0x2a2118, 1); g.fillCircle(c.x, c.y, 9); - g.fillStyle(0xfdf3d8, 1); g.fillCircle(c.x, c.y, 5.5); - g.lineStyle(2, 0x2a2118, 1); g.strokeCircle(c.x, c.y, 9); - this.add.text(c.x, c.y - 16, c.name, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#241a0c', - backgroundColor: 'rgba(253,243,216,0.7)', padding: { x: 4, y: 1 }, - }).setOrigin(0.5, 1).setDepth(D.label); + this.steam = this.add.particles(0, 0, 'ttr-steam', { + lifespan: { min: 700, max: 1300 }, speed: { min: 6, max: 26 }, angle: { min: 230, max: 310 }, + scale: { start: 0.35, end: 1.3 }, alpha: { start: 0.7, end: 0 }, emitting: false, + }).setDepth(D.fx); + this.sparks = this.add.particles(0, 0, 'ttr-spark', { + lifespan: 700, speed: { min: 60, max: 220 }, angle: { min: 0, max: 360 }, + scale: { start: 1.2, end: 0 }, alpha: { start: 1, end: 0 }, gravityY: 160, emitting: false, + }).setDepth(D.fx); + } + + buildAmbient() { + // Cloud shadows drifting across the map, clipped to the sheet. + const maskG = this.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff).fillRect(SHEET.x, SHEET.y, SHEET.w, SHEET.h); + const mask = maskG.createGeometryMask(); + this.clouds = [0, 1, 2].map((i) => { + const c = this.add.image(SHEET.x + 200 + i * 520, SHEET.y + 160 + (i % 2) * 380, 'ttr-cloud') + .setScale(2.4 + i * 0.4).setAlpha(0.22).setDepth(D.cloud).setMask(mask); + c.vx = 6 + i * 2.5; + return c; + }); + // Steam wisps from busy junctions. + this.time.addEvent({ delay: 3200, loop: true, callback: () => this.hubSteam() }); + } + + hubSteam() { + if (!this.gs) return; + const touch = new Map(); + for (const [rid] of Object.entries(this.gs.claimed)) { + const r = ROUTES[rid]; + touch.set(r.a, (touch.get(r.a) ?? 0) + 1); + touch.set(r.b, (touch.get(r.b) ?? 0) + 1); + } + const hubs = [...touch.entries()].filter(([, n]) => n >= 3); + if (!hubs.length) return; + const [cid] = hubs[Math.floor(Math.random() * hubs.length)]; + const c = CITIES[cid]; + this.steam.explode(4, c.x + 6, c.y - 4); + } + + update(_t, dt) { + if (this.clouds) { + for (const c of this.clouds) { + c.x += c.vx * dt / 1000; + if (c.x - c.displayWidth / 2 > SHEET.x + SHEET.w) c.x = SHEET.x - c.displayWidth / 2; + } + } + if (this.cityGlows) { + const a = 0.55 + 0.35 * Math.sin(this.time.now / 220); + this.cityGlows.forEach((g) => { if (g.visible) g.setAlpha(a * (g.baseAlpha ?? 1)); }); } } - // ── right band: market, piles, ticket deck, opponent panels ─────────────────── - buildRightPanel() { - this.add.rectangle(RB.cx, GAME_HEIGHT / 2, RB.w, GAME_HEIGHT, COLORS.panel, 0.9).setDepth(D.hud - 2); - this.add.rectangle(RB.x0, GAME_HEIGHT / 2, 4, GAME_HEIGHT, COLORS.accent, 0.6).setDepth(D.hud - 2); - - // Opponent panels (seats 1..n-1) — built in buildOpponentPanels once names exist. - this.oppPanelText = []; - - // Market label. - this.add.text(RB.x0 + 24, MK_Y0 - 56, 'Train Card Market', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(0, 0.5).setDepth(D.hud); - - // Draw pile (face-down, rotated landscape) — clickable. - this.deckCard = this.add.image(PILE_X, MK_Y0, 'ttr-cards', TTR_CARD_FRAME.back) - .setDisplaySize(CARD_W, CARD_H).setAngle(-90).setDepth(D.hud); - this.deckCount = this.add.text(PILE_X, MK_Y0 + 4, '', { - fontFamily: 'Righteous', fontSize: '24px', color: '#fdf3d8', - }).setOrigin(0.5).setDepth(D.hud + 1); - this.add.text(PILE_X, MK_Y0 - CARD_W / 2 - 14, 'Draw', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.hud); - this.makeZone(PILE_X, MK_Y0, CARD_H, CARD_W, () => this.onDeckClick()); - - // Discard pile (display only, rotated landscape). - const discY = MK_Y0 + MK_STEP * 1.5; - this.discardCard = this.add.image(PILE_X, discY, 'ttr-cards', TTR_CARD_FRAME.back) - .setDisplaySize(CARD_W, CARD_H).setAngle(-90).setAlpha(0.3).setDepth(D.hud); - this.discardCount = this.add.text(PILE_X, discY + 4, '', { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.hud + 1); - this.add.text(PILE_X, discY - CARD_W / 2 - 14, 'Discard', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.hud); - - // Ticket deck — clickable. - const tY = MK_Y0 + MK_STEP * 3; - this.ticketCard = this.add.graphics().setDepth(D.hud); - this.ticketCard.fillStyle(0x4a7c3a, 1); - this.ticketCard.fillRoundedRect(PILE_X - CARD_W / 2, tY - CARD_H / 2, CARD_W, CARD_H, 8); - this.ticketCard.lineStyle(3, 0xfdf3d8, 0.9); - this.ticketCard.strokeRoundedRect(PILE_X - CARD_W / 2, tY - CARD_H / 2, CARD_W, CARD_H, 8); - this.add.text(PILE_X, tY - 14, '🎫', { fontSize: '26px' }).setOrigin(0.5).setDepth(D.hud + 1); - this.ticketCount = this.add.text(PILE_X, tY + 16, '', { - fontFamily: 'Righteous', fontSize: '16px', color: '#fdf3d8', - }).setOrigin(0.5).setDepth(D.hud + 1); - this.add.text(PILE_X, tY - CARD_H / 2 - 14, 'Destination Tickets', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.hud); - this.makeZone(PILE_X, tY, CARD_W, CARD_H, () => this.onTicketDeckClick()); - - const dimTop = MK_Y0 - 70; - const dimBot = MK_Y0 + MK_STEP * 3 + CARD_H / 2 + 30; - this.drawAreaDimOverlay = this.add.rectangle( - RB.cx, (dimTop + dimBot) / 2, RB.w, dimBot - dimTop, 0x000000, 0.55 - ).setDepth(D.hud + 5).setVisible(false); + // ── buttons, status, keys ────────────────────────────────────────────────────── + buildButtons() { + const mk = (r, label, fn, opts = {}) => new Button(this, r.x + r.w / 2, r.y + r.h / 2, label, fn, { + width: r.w, height: r.h, fontSize: 16, bg: 0x3a2414, ...opts, + }).setDepth(D.hud + 2); + mk(MENU_BTN, '☰ Menu', () => this.openMenu()); + mk(LOG_BTN, 'Log', () => this.openLogView()); + mk(HELP_BTN, 'How to Play', () => new TutorialModal(this.gameDef).open()); + this.routesBtn = new Button(this, ROUTES_BTN.x, ROUTES_BTN.y, '', () => this.toggleAffordable(), { + width: ROUTES_BTN.w, height: ROUTES_BTN.h, fontSize: 15, bg: 0x2f4a36, + }).setDepth(D.hud + 2); + this.refreshRoutesBtn(); + this.passBtn = new Button(this, PASS_BTN.x, PASS_BTN.y, 'Pass Turn', () => this.onPass(), { + width: PASS_BTN.w, height: PASS_BTN.h, fontSize: 18, bg: 0x7a2a1a, + }).setDepth(D.hud + 2).setVisible(false); } - _setBusy(val) { - this.busy = val; - this.drawAreaDimOverlay?.setVisible(val); + refreshRoutesBtn() { + this.routesBtn?.setLabel(this.settings.showAffordable ? 'Routes: shown' : 'Routes: hidden'); } - makeZone(x, y, w, h, fn) { - const z = this.add.zone(x, y, w, h).setInteractive({ useHandCursor: true }).setDepth(D.hud + 4); - z.on('pointerdown', fn); - return z; + buildStatus() { + this.statusBg = this.add.graphics().setDepth(D.banner - 2); + this.statusText = this.add.text(STATUS.x, STATUS.y, '', { + fontFamily: DISPLAY, fontSize: '19px', color: '#2b1a06', + }).setOrigin(0.5).setDepth(D.banner - 1); } - buildOpponentPanels() { - this.opponentPortraits.forEach((p) => p.destroy?.()); - this.opponentPortraits = []; - this.oppPanelText.forEach((t) => t?.destroy()); - this.oppPanelText = []; - this.oppRingGfx?.destroy(); - this.oppRingGfx = this.add.graphics().setDepth(D.hud + 3); - this.scoreBadgeContainers.forEach((c) => c.destroy()); - this.scoreBadgeContainers = []; - this.oppScoreTexts = {}; - this.oppMiniHandGfx.forEach((g) => g?.destroy()); - this.oppMiniHandGfx = []; - this.oppMiniHandCount.forEach((t) => t?.destroy()); - this.oppMiniHandCount = []; - - // Player score badge (above human portrait in the bottom HUD) - const pb = this._makeScoreBadge(80, BOT_Y - 64, this.playerColor(0).hex, 16); - this.playerScoreText = pb.text; - this.scoreBadgeContainers.push(pb.container); - - for (let seat = 1; seat < this.gs.playerCount; seat++) { - const { x, y } = this.oppPos(seat); - const opp = this.opponents[seat - 1]; - const portrait = createOpponentPortrait(this, opp, x, y, OPP_R, D.hud, { playIntro: seat === 1 }); - this.opponentPortraits.push(portrait); - const col = PLAYER_COLORS[this.gs.players[seat].colorIndex]; - this.add.circle(x, y, OPP_R + 4, col.hex, 0).setStrokeStyle(3, col.hex, 0.95).setDepth(D.hud + 2); - this.add.text(x + OPP_R + 12, y - 10, this.pname(seat), { - fontFamily: 'Righteous', fontSize: '15px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.hud + 1); - const info = this.add.text(x + OPP_R + 12, y + 10, '', { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex, lineSpacing: 2, - }).setOrigin(0, 0.5).setDepth(D.hud + 1); - this.oppPanelText[seat] = info; - - // Score badge above opponent portrait - const ob = this._makeScoreBadge(x, y - OPP_R - 14, col.hex, 13); - this.oppScoreTexts[seat] = ob.text; - this.scoreBadgeContainers.push(ob.container); - - // Mini face-down hand fan below portrait - const fanX = x - OPP_R; - const fanY = y + OPP_R + 20; - const miniGfx = this.add.graphics().setDepth(D.hud + 1); - this.oppMiniHandGfx[seat] = miniGfx; - const miniCount = this.add.text(fanX + 86, fanY, '×0', { - fontFamily: 'Righteous', fontSize: '13px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.hud + 2); - this.oppMiniHandCount[seat] = miniCount; - } + setStatus(text, tone = 'plain') { + if (this.statusText.text === text && this._statusTone === tone) return; + this._statusTone = tone; + this.statusText.setText(text); + const w = Math.max(260, this.statusText.width + 70), h = 38; + const g = this.statusBg; + g.clear(); + if (!text) return; + const fill = tone === 'final' ? 0x9a2a1e : tone === 'you' ? 0xf0dca4 : 0xe6d3a2; + const x = STATUS.x - w / 2, y = STATUS.y - h / 2; + g.fillStyle(0x000000, 0.35).fillRoundedRect(x + 3, y + 5, w, h, 6); + // Ribbon tails. + g.fillStyle(tone === 'final' ? 0x6a1a12 : 0xb89a5e, 1); + g.fillTriangle(x - 20, y + 6, x + 4, y + 6, x + 4, y + h + 4); + g.fillTriangle(x - 20, y + h + 4, x - 8, y + h / 2 + 5, x - 20, y + 6); + g.fillTriangle(x + w + 20, y + 6, x + w - 4, y + 6, x + w - 4, y + h + 4); + g.fillTriangle(x + w + 20, y + h + 4, x + w + 8, y + h / 2 + 5, x + w + 20, y + 6); + g.fillStyle(fill, 1).fillRoundedRect(x, y, w, h, 5); + g.lineStyle(1.5, tone === 'final' ? 0xffd0a0 : 0x7a4a2a, 0.9).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 3); + this.statusText.setColor(tone === 'final' ? '#fff0d0' : '#2b1a06'); } - _makeScoreBadge(x, y, color, radius = 16) { - const c = this.add.container(x, y).setDepth(D.hud + 3); - const g = this.add.graphics(); - g.fillStyle(color, 1); - g.fillCircle(0, 0, radius); - g.lineStyle(2, 0xffffff, 0.35); - g.strokeCircle(0, 0, radius); - const t = this.add.text(0, 0, '0', { - fontFamily: 'Righteous', fontSize: radius > 14 ? '13px' : '11px', color: '#ffffff', - }).setOrigin(0.5); - c.add([g, t]); - return { container: c, text: t }; + buildKeys() { + this.input.keyboard?.on('keydown', (e) => { + if (this.ended || !this.gs) return; + const k = e.key; + if (k === 'Escape') { + if (!this.modal) this.openMenu(); + else if (this.modal.onEsc) this.modal.onEsc(); + else if (!this.modal.sticky) this.closeModal(); + return; + } + if (this.modal) return; + if (k >= '1' && k <= '5') this.onMarketClick(Number(k) - 1); + else if (k === 'd' || k === 'D') this.onDeckClick(); + else if (k === 't' || k === 'T') this.onTicketDeckClick(); + else if (k === 'r' || k === 'R') this.toggleAffordable(); + else if (k === 'l' || k === 'L') this.openLogView(); + else if (k === 'p' || k === 'P') { if (this.passBtn.visible) this.onPass(); } + }); } - oppPos(seat) { - const row = Math.floor((seat - 1) / 2); - const col = (seat - 1) % 2; - return { x: col === 0 ? OPP_COL1_X : OPP_COL2_X, y: OPP_Y0 + row * OPP_STEP }; + saveSettings() { + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } } - // ── bottom HUD: human portrait, hand, status, leave ─────────────────────────── - buildHUD() { - this.add.rectangle(GAME_WIDTH / 2, BOT_Y + 30, GAME_WIDTH, 200, COLORS.panel, 0.92).setDepth(D.hud - 1); - this.add.rectangle(GAME_WIDTH / 2, BOT_Y - 70, GAME_WIDTH, 4, COLORS.accent, 0.6).setDepth(D.hud - 1); + get k() { return PACE[this.settings.pace] ?? 1; } + skillFor(seat) { return clampSkill(this.opponents[seat - 1]?.skill ?? 3); } - createPlayerPortrait(this, 80, BOT_Y, 46, D.hud, 'TicketToRideGame'); - this.add.text(80, BOT_Y + 60, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.hud); - this.add.text(180, BOT_Y, 'Your Trains', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.hud); - this.trainsText = this.add.text(300, BOT_Y, '', { - fontFamily: 'Righteous', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.hud); - - this.ticketsBtn = new Button(this, 1760, BOT_Y, 'My Tickets', () => this.showMyTickets(), - { width: 200, height: 50, fontSize: 20 }).setDepth(D.hud); - - this.statusText = this.add.text(GAME_WIDTH / 2, 38, '', { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - backgroundColor: '#111923cc', padding: { x: 18, y: 8 }, - }).setOrigin(0.5).setDepth(D.banner); - - this.logText = this.add.text(1760, BOT_Y + 32, '', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - wordWrap: { width: 300 }, align: 'center', - }).setOrigin(0.5, 0).setDepth(D.hud); - - new Button(this, 80, 40, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 120, height: 40, fontSize: 17 }).setDepth(D.banner); - - this._buildTurnTriangle(); - } - - // ── helpers ─────────────────────────────────────────────────────────────────── - playerColor(seat) { return PLAYER_COLORS[this.gs.players[seat].colorIndex]; } - pname(seat) { return L.playerName(this.gs, seat); } - - textColorFor(colorKey) { - return (colorKey === 'white' || colorKey === 'yellow') ? '#241a0c' : '#fdf3d8'; - } - - // ── new match / turn driver ─────────────────────────────────────────────────── + // ── match ───────────────────────────────────────────────────────────────────── startNewMatch() { - this._setBusy(false); - this.closeModal(); const playerCount = Math.min(5, Math.max(2, 1 + this.opponents.length)); this.gs = L.createInitialState(playerCount); - const names = ['You', ...this.opponents.map((o) => o?.name ?? 'CPU')]; - L.setPlayerNames(this.gs, names); - this.buildOpponentPanels(); + L.setPlayerNames(this.gs, ['You', ...this.opponents.map((o) => o?.name ?? 'CPU')]); + this.hud = new TTRHud(this, { hud: D.hud, hudTop: D.hudTop }, { + onMarket: (i) => this.onMarketClick(i), + onDeck: () => this.onDeckClick(), + onTickets: () => this.onTicketDeckClick(), + onPileHover: (c) => { this.hl.pile = c; this.renderHighlights(); }, + onTicketHover: (t) => { this.hl.ticket = t; this.renderHighlights(); }, + onOppHover: (s) => { this.hl.opp = s; this.renderHighlights(); }, + onLongestHover: (on) => { this.hl.longest = on; this.renderHighlights(); }, + onNotepad: () => this.openLogView(), + tooltip: (obj, fn) => this.tooltip.attachTo(obj, fn), + }); + this.hud.build(this.gs, this.opponents); + this.buildMarkers(); this.renderAll(); - this.time.delayedCall(600, () => this.advance()); + this.time.delayedCall(700, () => this.advance()); } + buildMarkers() { + this.gs.players.forEach((p, seat) => { + const m = this.add.image(0, 0, `ttr-marker-${p.colorIndex}`).setDisplaySize(22, 22).setDepth(D.marker + seat * 0.01); + const lap = this.add.text(0, 0, '', { fontFamily: 'Righteous', fontSize: '10px', color: '#fff', stroke: '#000', strokeThickness: 2 }) + .setOrigin(0.5).setDepth(D.marker + 0.5); + this.markers[seat] = { img: m, lap }; + this.markerScore[seat] = 0; + }); + this.placeMarkers(false); + } + + markerSpot(seat, score) { + const square = ((score % 100) + 100) % 100; + const same = this.gs.players.map((p) => p.seat).filter((s) => ((((this.markerScore[s] ?? 0) % 100) + 100) % 100) === square); + const k = same.indexOf(seat), n = same.length; + const p = trackPos(square); + return { x: p.x + (k - (n - 1) / 2) * 6, y: p.y - (k - (n - 1) / 2) * 5 }; + } + + placeMarkers() { + this.gs.players.forEach((p, seat) => { + const pos = this.markerSpot(seat, this.markerScore[seat]); + const m = this.markers[seat]; + m.img.setPosition(pos.x, pos.y); + m.lap.setPosition(pos.x, pos.y).setText(this.markerScore[seat] >= 100 ? '+100' : this.markerScore[seat] < 0 ? '−' : ''); + }); + } + + async moveMarker(seat, to, { stepMs = 34 } = {}) { + const from = this.markerScore[seat]; + if (from === to) return; + const dir = Math.sign(to - from); + const steps = Math.abs(to - from); + const m = this.markers[seat]; + m.img.setDepth(D.marker + 1); + if (steps > 30) { + this.markerScore[seat] = to; + const pos = this.markerSpot(seat, to); + await this.tw({ targets: [m.img, m.lap], x: pos.x, y: pos.y, duration: 500, ease: 'Cubic.easeInOut' }); + } else { + for (let i = 1; i <= steps; i++) { + const p = trackPos(from + dir * i); + await this.tw({ targets: [m.img, m.lap], x: p.x, y: p.y - 4, duration: stepMs, ease: 'Sine.easeOut' }); + } + this.markerScore[seat] = to; + } + m.img.setDepth(D.marker + seat * 0.01); + playSound(this, SFX.PIECE_CLICK); + this.placeMarkers(); + } + + // ── turn driver ─────────────────────────────────────────────────────────────── async advance() { + if (this.ended || !this.gs) return; const s = this.gs; this.renderAll(); - if (!s) return; if (s.phase === 'gameOver') { this.onGameOver(); return; } - if (s.pendingTickets) { - if (s.pendingTickets.seat === 0) this.promptTicketKeep(); + if (s.pendingTickets.seat === 0) this.promptTickets(); else await this.aiResolveTickets(); return; } - if (s.currentPlayer === 0) { - // Human turn — controls are always-on zones guarded by canHumanAct(). + if (!this._humanTurnSeen) { this._humanTurnSeen = true; this.yourTurnCue(); } return; } + this._humanTurnSeen = false; await this.aiTurn(); } canHumanAct() { const s = this.gs; - return !this.busy && s && (s.phase === 'turn' || s.phase === 'lastRound') + return !this.ended && !this.busy && !this.modal && s && (s.phase === 'turn' || s.phase === 'lastRound') && s.currentPlayer === 0 && !s.pendingTickets && s.winner == null; } - applyHuman(newGs, sfx) { - this.gs = newGs; - if (sfx) playSound(this, sfx); - this.advance(); + async runHuman(fn) { + this.busy = true; + this.tooltip.hide(); + try { await fn(); } finally { this.busy = false; } + if (!this.ended) this.advance(); } - // ── human input handlers ──────────────────────────────────────────────────── - async onMarketClick(i) { + yourTurnCue() { + const r = this.add.text(STATUS.x, STATUS.y + 44, 'Your turn', { + fontFamily: DISPLAY, fontSize: '28px', color: '#fff3c8', stroke: '#3b2a17', strokeThickness: 5, + }).setOrigin(0.5).setDepth(D.banner).setAlpha(0); + this.tweens.add({ + targets: r, alpha: 1, y: STATUS.y + 54, duration: 260, ease: 'Back.easeOut', + onComplete: () => this.tweens.add({ targets: r, alpha: 0, delay: 700, duration: 300, onComplete: () => r.destroy() }), + }); + } + + // ── human input ──────────────────────────────────────────────────────────────── + onMarketClick(i) { if (!this.canHumanAct()) return; - if (i >= this.gs.faceUp.length) return; - if (this.gs.faceUp[i] === 'locomotive' && this.gs.drawnThisTurn !== 0) { - this.flash('Take a face-up locomotive only as your first draw'); return; + const c = this.gs.faceUp[i]; + if (c == null) return; + if (c === 'locomotive' && this.gs.drawnThisTurn !== 0) { + this.flash('A face-up locomotive can only be your first draw'); return; } - const srcX = MK_X; - const srcY = MK_Y0 + i * (CARD_W + 10); - const color = this.gs.faceUp[i]; - const origFaceUpLength = this.gs.faceUp.length; - const newGs = L.drawTrainCard(this.gs, 0, 'faceUp', i); - const refillHappened = newGs.faceUp.length === origFaceUpLength; - const refillSlot = origFaceUpLength - 1; - const refillColor = refillHappened ? newGs.faceUp[refillSlot] : undefined; - this._suppressHandRender = true; - this._setBusy(true); - this.gs = newGs; - this.marketSlotObjs[i]?.forEach((o) => o.setVisible(false)); - this.renderAllExceptMarket(); - playSound(this, SFX.CARD_DEAL); - const dest = this.handDestForColor(color); - await this.animateCardDraw({ - srcX, srcY, srcAngle: -90, cardFrame: TTR_CARD_FRAME[color], - shouldFlip: false, destX: dest.x, destY: dest.y, destW: 97, destH: 140, - }); - await this.animateMarketSlideUp(i, origFaceUpLength - 1); - if (refillColor !== undefined) await this.animateRefillMarketSlot(refillSlot, refillColor); - this._suppressHandRender = false; - this.renderAll(); - this._setBusy(false); - this.advance(); + this.runHuman(() => this.doDraw(0, { source: 'faceUp', index: i })); } - async onDeckClick() { + onDeckClick() { if (!this.canHumanAct()) return; - if (!L.canDrawTrains(this.gs)) { this.flash('No cards left to draw'); return; } - const newGs = L.drawTrainCard(this.gs, 0, 'deck'); - const drawnColor = HAND_ORDER.find((k) => newGs.players[0].hand[k] > this.gs.players[0].hand[k]); - this._suppressHandRender = true; - this._setBusy(true); - this.gs = newGs; - this.renderAll(); - playSound(this, SFX.CARD_DEAL); - const dest = this.handDestForColor(drawnColor); - await this.animateCardDraw({ - srcX: PILE_X, srcY: MK_Y0, srcAngle: -90, cardFrame: TTR_CARD_FRAME[drawnColor], - shouldFlip: true, destX: dest.x, destY: dest.y, destW: 97, destH: 140, - }); - this._suppressHandRender = false; - this._setBusy(false); - this.advance(); + if (!L.canDrawFromDeck(this.gs)) { this.flash('The deck and discard are empty'); return; } + this.runHuman(() => this.doDraw(0, { source: 'deck' })); } onTicketDeckClick() { if (!this.canHumanAct()) return; - if (this.gs.drawnThisTurn > 0) { this.flash('Finish drawing train cards this turn'); return; } - if (!L.canDrawTickets(this.gs)) { this.flash('No tickets left'); return; } - this.gs = L.drawTickets(this.gs, 0); - this.advance(); + if (this.gs.drawnThisTurn > 0) { this.flash('Finish drawing train cards first'); return; } + if (!L.canDrawTickets(this.gs)) { this.flash('No destination tickets left'); return; } + const n = Math.min(3, this.gs.ticketDeck.length); + this.tooltip.hide(); + this.modal = confirmBox(this, { + heading: 'Draw destination tickets?', + text: `You'll draw ${n} ticket${n === 1 ? '' : 's'} and must keep at least 1. Unfinished tickets cost their points at the end, and this uses your whole turn.`, + yes: 'Draw Tickets', depth: D.modal, + onYes: () => { this.modal = null; this.drawHumanTickets(); }, + onNo: () => { this.modal = null; }, + }); } - onRouteHover(id) { - if (id != null && (!this.canHumanAct() || this.gs.drawnThisTurn > 0 || !L.routeClaimable(this.gs, 0, id))) { - id = null; - } - this.hoverRouteId = id; - this.renderHover(); - } - - async onRouteClick(id) { + drawHumanTickets() { if (!this.canHumanAct()) return; - if (this.gs.drawnThisTurn > 0) { this.flash('You are drawing cards this turn'); return; } - if (!L.routeClaimable(this.gs, 0, id)) { this.flash('That route is not available'); return; } - const opts = L.paymentOptions(this.gs.players[0], ROUTES[id]); - if (opts.length === 0) { this.flash('Not enough matching cards'); return; } - if (opts.length === 1) { - const payment = opts[0]; - const newGs = L.claimRoute(this.gs, 0, id, payment); - this._setBusy(true); - await this.animateClaimRoute(0, id, payment); - this.gs = newGs; - playSound(this, SFX.CARD_PLACE); - this._setBusy(false); - this.advance(); + this.runHuman(async () => { + this.gs = L.drawTickets(this.gs, 0); + playSound(this, SFX.CARD_SHUFFLE); + this.renderAll(); + await this.flyTickets(TICKET_BOX, { x: PAD.x + PAD.w / 2, y: PAD.y + 400 }, this.gs.pendingTickets.drawn.length, 1.2); + }); + } + + onPass() { + if (!this.canHumanAct() || L.legalActions(this.gs, 0).any) return; + this.runHuman(async () => { this.gs = L.passTurn(this.gs, 0); }); + } + + onRouteClick(id) { + if (!this.canHumanAct()) return; + const gs = this.gs; + if (gs.drawnThisTurn > 0) { this.flash('You are drawing cards this turn'); return; } + const why = L.routeLockReason(gs, 0, id); + if (why) { this.flash(why); return; } + const opts = L.paymentOptions(gs.players[0], ROUTES[id]); + if (!opts.length) { this.flash(this.shortfall(id)); return; } + if (opts.length === 1 || !this.settings.askPayment) { + this.runHuman(() => this.doClaim(0, id, opts[0])); return; } - this.promptClaimPayment(id, opts); + const m = this.midCache[id]; + const chooser = openPaymentChooser(this, { + route: ROUTES[id], options: opts, anchor: { x: m.x, y: m.y }, depth: D.modal, + onAlwaysFewest: () => { this.settings.askPayment = false; this.saveSettings(); }, + onPick: (opt) => { + this.modal = null; + if (opt) this.runHuman(() => this.doClaim(0, id, opt)); + }, + }); + chooser.onEsc = () => { chooser.close(); this.modal = null; }; + this.modal = chooser; } - // ── AI driver ───────────────────────────────────────────────────────────────── - async aiTurn() { - this._setBusy(true); - const seat = this.gs.currentPlayer; - this.showTurnBanner(`${this.pname(seat)}'s Turn`); - await this.delay(650); + shortfall(id) { + const r = ROUTES[id]; + const hand = this.gs.players[0].hand; + const best = r.color === 'gray' + ? Math.max(...['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black', 'white'].map((c) => hand[c])) + : hand[r.color]; + const short = r.length - best - hand.locomotive; + return `Need ${short} more ${r.color === 'gray' ? 'matching' : CARD_LABEL[r.color].toLowerCase()} card${short === 1 ? '' : 's'} (or locomotives)`; + } - const a = AI.chooseAction(this.gs, seat); + toggleAffordable() { + this.settings.showAffordable = !this.settings.showAffordable; + this.saveSettings(); + this.refreshRoutesBtn(); + this.renderHighlights(); + } + + // ── AI ───────────────────────────────────────────────────────────────────────── + async aiTurn() { + this.busy = true; + const seat = this.gs.currentPlayer; + const skill = this.skillFor(seat); + const t = aiTiming(skill, this.k); + this.renderAll(); + await this.wait(Math.max(300, t.think)); + if (this.ended) return; + const a = AI.chooseAction(this.gs, seat, { skill }); + const before = this.gs; if (a.type === 'claimRoute') { - const newGs = L.claimRoute(this.gs, seat, a.routeId, a.payment); - await this.animateClaimRoute(seat, a.routeId, a.payment); - this.gs = newGs; - playSound(this, SFX.CARD_PLACE); - this.opponentPortraits[seat - 1]?.playEmotion?.('happy'); + await this.doClaim(seat, a.routeId, a.payment); + const r = ROUTES[a.routeId]; + this.hud.caption(seat, `${CITIES[r.a].name} – ${CITIES[r.b].name} +${ROUTE_SCORE[r.length]}`); + if (r.length >= 5) this.hud.emote(seat, 'happy'); } else if (a.type === 'drawTickets') { this.gs = L.drawTickets(this.gs, seat); - // pendingTickets now set for this AI seat — advance() routes to aiResolveTickets. - } else { // drawTrain - const { x: dX, y: dY } = this.oppPos(seat); - const fanX = dX - OPP_R; - const fanY = dY + OPP_R + 20; - // First draw - const firstFaceUp = a.source === 'faceUp'; - const faceUpColor1 = firstFaceUp ? this.gs.faceUp[a.index] : null; - const srcX1 = firstFaceUp ? MK_X : PILE_X; - const srcY1 = firstFaceUp ? MK_Y0 + a.index * (CARD_W + 10) : MK_Y0; - const origFaceUpLen1 = firstFaceUp ? this.gs.faceUp.length : 0; - if (firstFaceUp) this.marketSlotObjs[a.index]?.forEach((o) => o.setVisible(false)); - this.gs = L.drawTrainCard(this.gs, seat, a.source, a.index); - const slot1 = Math.min(L.handCount(this.gs.players[seat]) - 1, 4); - const refillHappened1 = firstFaceUp && this.gs.faceUp.length === origFaceUpLen1; - const refillColor1 = refillHappened1 ? this.gs.faceUp[origFaceUpLen1 - 1] : undefined; - playSound(this, SFX.CARD_DEAL); - this._suppressHandRender = true; - if (firstFaceUp) this.renderAllExceptMarket(); else this.renderAll(); - await this.animateCardDraw({ - srcX: srcX1, srcY: srcY1, srcAngle: -90, - cardFrame: faceUpColor1 ? TTR_CARD_FRAME[faceUpColor1] : TTR_CARD_FRAME.back, - shouldFlip: false, - destX: fanX + slot1 * MINI_STEP + MINI_W / 2, destY: fanY, - destW: MINI_W, destH: MINI_H, - }); - this._suppressHandRender = false; - if (firstFaceUp) { - await this.animateMarketSlideUp(a.index, origFaceUpLen1 - 1); - if (refillColor1 !== undefined) await this.animateRefillMarketSlot(origFaceUpLen1 - 1, refillColor1); - this.renderAll(); - } - // Second draw if the turn is still in progress. - if ((this.gs.phase === 'turn' || this.gs.phase === 'lastRound') - && this.gs.currentPlayer === seat && this.gs.drawnThisTurn === 1 && !this.gs.pendingTickets) { - await this.delay(150); - const b = AI.chooseSecondDraw(this.gs, seat); - const secondFaceUp = b.source === 'faceUp'; - const faceUpColor2 = secondFaceUp ? this.gs.faceUp[b.index] : null; - const srcX2 = secondFaceUp ? MK_X : PILE_X; - const srcY2 = secondFaceUp ? MK_Y0 + b.index * (CARD_W + 10) : MK_Y0; - const origFaceUpLen2 = secondFaceUp ? this.gs.faceUp.length : 0; - if (secondFaceUp) this.marketSlotObjs[b.index]?.forEach((o) => o.setVisible(false)); - this.gs = L.drawTrainCard(this.gs, seat, b.source, b.index); - const slot2 = Math.min(L.handCount(this.gs.players[seat]) - 1, 4); - const refillHappened2 = secondFaceUp && this.gs.faceUp.length === origFaceUpLen2; - const refillColor2 = refillHappened2 ? this.gs.faceUp[origFaceUpLen2 - 1] : undefined; - playSound(this, SFX.CARD_DEAL); - this._suppressHandRender = true; - if (secondFaceUp) this.renderAllExceptMarket(); else this.renderAll(); - await this.animateCardDraw({ - srcX: srcX2, srcY: srcY2, srcAngle: -90, - cardFrame: faceUpColor2 ? TTR_CARD_FRAME[faceUpColor2] : TTR_CARD_FRAME.back, - shouldFlip: false, - destX: fanX + slot2 * MINI_STEP + MINI_W / 2, destY: fanY, - destW: MINI_W, destH: MINI_H, - }); - this._suppressHandRender = false; - if (secondFaceUp) { - await this.animateMarketSlideUp(b.index, origFaceUpLen2 - 1); - if (refillColor2 !== undefined) await this.animateRefillMarketSlot(origFaceUpLen2 - 1, refillColor2); - this.renderAll(); - } + this.renderAll(); + this.hud.caption(seat, 'Drawing tickets…'); + await this.flyTickets(TICKET_BOX, this.hud.oppAnchor(seat), this.gs.pendingTickets?.drawn.length ?? 3, 0.45); + } else if (a.type === 'pass') { + this.gs = L.passTurn(this.gs, seat); + this.hud.caption(seat, 'No moves — passes'); + } else { + const first = await this.doDraw(seat, a); + let label = first === 'locomotive-face' ? 'Took a face-up locomotive' : 'Drew a card'; + if (this.gs.currentPlayer === seat && this.gs.drawnThisTurn === 1 && !this.ended) { + await this.wait(Math.max(120, t.between)); + const b = AI.chooseSecondDraw(this.gs, seat, { skill }); + if (b.type === 'pass') this.gs = L.passTurn(this.gs, seat); + else { await this.doDraw(seat, b); label = 'Drew 2 cards'; } } + this.hud.caption(seat, label, 900); } - + if (this.ended) return; + this.afterAction(before); this.renderAll(); - await this.delay(200); - this._setBusy(false); + await this.wait(Math.round(180 * this.k)); + this.busy = false; this.advance(); } async aiResolveTickets() { - this._setBusy(true); - await this.delay(550); + this.busy = true; const pend = this.gs.pendingTickets; - const keep = AI.chooseTicketsToKeep(this.gs, pend.seat, pend.drawn, pend.minKeep); - this.gs = L.resolveTicketKeep(this.gs, pend.seat, keep); - this._setBusy(false); + const seat = pend.seat; + this.renderAll(); + if (pend.context === 'setup') await this.flyTickets(TICKET_BOX, this.hud.oppAnchor(seat), pend.drawn.length, 0.45); + await this.wait(Math.round(500 * this.k)); + if (this.ended) return; + const keep = AI.chooseTicketsToKeep(this.gs, seat, pend.drawn, pend.minKeep, { skill: this.skillFor(seat) }); + this.gs = L.resolveTicketKeep(this.gs, seat, keep); + const back = pend.drawn.length - keep.length; + this.hud.caption(seat, `Kept ${keep.length} ticket${keep.length === 1 ? '' : 's'}`); + if (back > 0) await this.flyTickets(this.hud.oppAnchor(seat), TICKET_BOX, back, 0.45, true); + this.renderAll(); + this.busy = false; this.advance(); } - // ── rendering ───────────────────────────────────────────────────────────────── - renderAll() { - if (!this.gs) return; - this.renderRoutes(); - this.renderHover(); - this.renderMarket(); - this.renderHand(); - this.renderPiles(); - this.renderPanels(); - this.renderStatus(); - } - - renderRoutes() { - this.trainCarObjs.forEach((o) => o.destroy()); - this.trainCarObjs = []; - const g = this.routeGfx; - const sg = this.trainStrokeGfx; - g.clear(); - sg.clear(); - ROUTES.forEach((r, id) => { - const owner = this.gs.claimed[id]; - const segs = this.segCache[id]; - if (owner != null) { - const col = this.playerColor(owner); - for (const seg of segs) { - const img = this.add.image(seg.cx, seg.cy, 'ttr-train-car') - .setDisplaySize(seg.w, seg.h) - .setRotation(seg.angle) - .setTint(col.hex) - .setDepth(D.train); - sg.save(); - sg.translateCanvas(seg.cx, seg.cy); - sg.rotateCanvas(seg.angle); - sg.lineStyle(2, 0xffffff, 1); - sg.strokeRoundedRect(-seg.w / 2, -seg.h / 2, seg.w, seg.h, 3); - sg.restore(); - this.trainCarObjs.push(img); - } + // ── actions (shared by human + AI) ───────────────────────────────────────────── + // Returns 'locomotive-face' when a face-up loco ended the turn. + async doDraw(seat, a) { + const prev = this.gs; + const next = L.drawTrainCard(prev, seat, a.source, a.index); + if (next.drawnThisTurn === prev.drawnThisTurn && next.currentPlayer === prev.currentPlayer) return null; + const human = seat === 0; + const k = human ? Math.min(1, this.k) : this.k; + const color = a.source === 'faceUp' ? prev.faceUp[a.index] : next.lastDeckCard; + const wipe = (next.marketWipes ?? 0) > (prev.marketWipes ?? 0); + playSound(this, SFX.CARD_DEAL); + this.gs = next; + if (human) this.ui.suppressHand = true; + if (a.source === 'faceUp') { + this.ui.hiddenMarket = wipe ? new Set([0, 1, 2, 3, 4]) : new Set([a.index]); + this.renderAll(); + const from = marketPos(a.index); + const to = human ? this.hud.pilePos(color) : this.hud.oppAnchor(seat); + await this.flyCard({ + frame: CARD_FRAME[color], from: { ...from, w: CARD.w, h: CARD.h }, + to: { ...to, w: human ? HAND_CARD.w : 34, h: human ? HAND_CARD.h : 49 }, duration: 340 * k, lift: true, + }); + if (human) { this.ui.suppressHand = false; this.renderAll(); this.hud.bumpPile(color); } + await this.refillMarket(prev, next, a.index, wipe, k); + } else { + this.ui.hiddenMarket = wipe ? new Set([0, 1, 2, 3, 4]) : new Set(); + this.renderAll(); + const from = { x: DECK.x, y: this.hud.deckTopY ?? DECK.y }; + if (human) { + await this.flyCard({ + frame: CARD_FRAME[color], back: true, from: { ...from, w: CARD.w, h: CARD.h }, + reveal: { x: DECK.x - 40, y: DECK.y - 150, w: CARD.w * 1.6, h: CARD.h * 1.6 }, + to: { ...this.hud.pilePos(color), w: HAND_CARD.w, h: HAND_CARD.h }, duration: 360, + }); + this.ui.suppressHand = false; this.renderAll(); this.hud.bumpPile(color); } else { - const fill = TTR_ROUTE_HEX[r.color] ?? TTR_ROUTE_HEX.gray; - for (const seg of segs) this.drawCar(g, seg, fill, 0x2a2118, null); + await this.flyCard({ + frame: CARD_FRAME.back, from: { ...from, w: CARD.w, h: CARD.h }, + to: { ...this.hud.oppAnchor(seat), w: 34, h: 49 }, duration: 340 * k, + }); } - }); + if (wipe) await this.refillMarket(prev, next, null, true, k); + } + this.ui.suppressHand = false; + this.ui.hiddenMarket = new Set(); + this.renderAll(); + return color === 'locomotive' && a.source === 'faceUp' ? 'locomotive-face' : color; } - renderHover() { - const g = this.hoverGfx; - g.clear(); - if (this.hoverRouteId == null) return; - for (const seg of this.segCache[this.hoverRouteId]) { - this.drawCar(g, seg, 0xffe680, 0xffffff, 0xffffff); + async refillMarket(prev, next, takenIdx, wipe, k) { + if (wipe) { + this.announce('Three locomotives! The market is swept and re-dealt.'); + playSound(this, SFX.CARD_SHUFFLE); + // The cards that were showing slide off to the discard… + const showing = prev.faceUp.map((c, i) => ({ c, i })).filter(({ i }) => i !== takenIdx); + await Promise.all(showing.map(({ c, i }, n) => this.flyCard({ + frame: CARD_FRAME[c], from: { ...marketPos(i), w: CARD.w, h: CARD.h }, + to: { ...DISCARD, w: CARD.w, h: CARD.h, angle: 4 }, duration: 300 * k, delay: n * 50, + }))); + // …and five fresh ones are dealt. + this.ui.hiddenMarket = new Set([0, 1, 2, 3, 4]); + this.renderAll(); + await this.dealSlots(next, [0, 1, 2, 3, 4], k); + return; + } + if (takenIdx != null && next.faceUp.length === prev.faceUp.length && next.faceUp[takenIdx] != null) { + await this.dealSlots(next, [takenIdx], k); } } - drawCar(g, seg, fill, stroke, halo) { - const w = seg.w, h = seg.h; - g.save(); - g.translateCanvas(seg.cx, seg.cy); - g.rotateCanvas(seg.angle); - if (halo != null) { g.fillStyle(halo, 1); g.fillRoundedRect(-w / 2 - 2, -h / 2 - 2, w + 4, h + 4, 4); } - g.fillStyle(fill, 1); - g.fillRoundedRect(-w / 2, -h / 2, w, h, 3); - g.lineStyle(1.5, stroke, 0.9); - g.strokeRoundedRect(-w / 2, -h / 2, w, h, 3); - g.restore(); + async dealSlots(state, slots, k) { + await Promise.all(slots.map((i, n) => this.flyCard({ + frame: CARD_FRAME[state.faceUp[i]], back: true, flipEnd: true, + from: { x: DECK.x, y: this.hud.deckTopY ?? DECK.y, w: CARD.w, h: CARD.h }, + to: { ...marketPos(i), w: CARD.w, h: CARD.h }, duration: 300 * k, delay: n * 70, + }).then(() => { this.ui.hiddenMarket.delete(i); this.hud.renderMarket(this.gs, this.uiState()); }))); } - renderMarket() { - this.marketObjs.forEach((o) => o.destroy()); - this.marketObjs = []; - this.marketSlotObjs = []; - const myTurn = this.canHumanAct(); - const mkStep = CARD_W + 10; // rotated visual height + padding - for (let i = 0; i < 5; i++) { - const y = MK_Y0 + i * mkStep; - const color = this.gs.faceUp[i]; - if (color == null) { - const g = this.add.graphics().setDepth(D.market); - g.lineStyle(2, COLORS.mutedHex, 0.5); - g.strokeRoundedRect(MK_X - CARD_H / 2, y - CARD_W / 2, CARD_H, CARD_W, 8); - this.marketSlotObjs[i] = [g]; - this.marketObjs.push(g); - continue; + async doClaim(seat, routeId, payment) { + const prev = this.gs; + const next = L.claimRoute(prev, seat, routeId, payment); + if (next.claimed[routeId] !== seat) return; + const human = seat === 0; + const k = human ? Math.min(1, this.k) : this.k; + this.tooltip.hide(); + this.hl.route = null; + + // 1. The payment flicks into the discard. + const cards = [...Array(payment.colorCount).fill(payment.color), ...Array(payment.locos).fill('locomotive')]; + await Promise.all(cards.map((c, i) => { + const from = human ? this.hud.pilePos(c) : this.hud.oppAnchor(seat); + return this.flyCard({ + frame: CARD_FRAME[c], from: { ...from, w: human ? HAND_CARD.w : 34, h: human ? HAND_CARD.h : 49 }, + to: { ...DISCARD, w: CARD.w, h: CARD.h, angle: -6 + Math.random() * 12 }, duration: 320 * k, delay: i * 55 * k, + }); + })); + playSound(this, SFX.CARD_PLACE); + this.animatingRoute = routeId; + this.ui.holdScores = true; + this.gs = next; + this.renderAll(); + + // 2. A locomotive steams along the route laying the cars. + await this.layRoute(seat, routeId, prev, k); + this.animatingRoute = null; + + // 3. Stations flash; the points float up and the marker hops round the track. + const r = ROUTES[routeId]; + for (const cid of [r.a, r.b]) this.flashCity(cid, PLAYER_COLORS[next.players[seat].colorIndex].hex); + const pts = ROUTE_SCORE[r.length]; + const m = this.midCache[routeId]; + await this.floatPoints(`+${pts}`, m.x, m.y - 10, this.markerSpot(seat, this.markerScore[seat])); + await this.moveMarker(seat, L.publicScore(next, seat), { stepMs: Math.round(30 * k) }); + this.ui.holdScores = false; + this.renderAll(); + + // 4. Tickets the human just completed get stamped (the rail does it) + a shimmer. + if (human) { + const was = new Set(L.ticketStatus(prev, 0).filter((t) => t.done).map((t) => t.id)); + const now = L.ticketStatus(next, 0).filter((t) => t.done && !was.has(t.id)); + for (const t of now) { + playSound(this, SFX.VICTORY_SHORT); + this.flash(`Ticket complete: ${CITIES[t.a].name} → ${CITIES[t.b].name} (+${t.points})`, '#9ff0a8'); + await this.shimmerTicket(t); } - const objs = this.makeCardFace(MK_X, y, CARD_W, CARD_H, color, D.market, ''); - objs.forEach((o) => o.setAngle(-90)); - const z = this.add.zone(MK_X, y, CARD_H, CARD_W).setDepth(D.market + 2); - if (myTurn) z.setInteractive({ useHandCursor: true }); - z.on('pointerdown', () => this.onMarketClick(i)); - this.marketSlotObjs[i] = [...objs, z]; - this.marketObjs.push(...objs, z); + } + this.afterAction(prev); + } + + async layRoute(seat, routeId, prev, k) { + const r = ROUTES[routeId]; + let segs = this.segCache[routeId].map((s) => ({ ...s })); + // Start from the end already joined to this player's network. + const touches = (cid) => prev.players[seat].routes.some((x) => ROUTES[x].a === cid || ROUTES[x].b === cid); + let start = CITIES[r.a], end = CITIES[r.b]; + if (!touches(r.a) && touches(r.b)) { segs = segs.reverse(); [start, end] = [end, start]; } + const ci = this.gs.players[seat].colorIndex; + const loco = this.add.image(start.x, start.y, `ttr-loco-${ci}`).setDisplaySize(32, 14).setDepth(D.loco); + if (r.length >= 4 || seat === 0) whistle(this, { dur: 0.7, vol: 0.08, pitch: 1 + (seat % 3) * 0.06 }); + const sprites = []; + this.carSprites.set(routeId, sprites); + let ang = Math.atan2(segs[0].cy - start.y, segs[0].cx - start.x); + loco.setRotation(ang); + let px = start.x, py = start.y; + for (const seg of segs) { + const dist = Math.hypot(seg.cx - px, seg.cy - py); + ang = Math.atan2(seg.cy - py, seg.cx - px); + loco.setRotation(ang); + await this.tw({ targets: loco, x: seg.cx, y: seg.cy, duration: Math.max(90, dist * 3.2) * k, ease: 'Linear' }); + if (this.ended) return; + sprites.push(...this.placeCar(seg, ci, true)); + this.steam.explode(2, seg.cx, seg.cy - 4); + playSound(this, SFX.PIECE_CLICK); + chuff(this); + px = seg.cx; py = seg.cy; + } + ang = Math.atan2(end.y - py, end.x - px); + loco.setRotation(ang); + await this.tw({ targets: loco, x: end.x, y: end.y, alpha: 0, duration: 260 * k, ease: 'Sine.easeIn' }); + this.steam.explode(6, end.x, end.y - 6); + loco.destroy(); + } + + placeCar(seg, ci, pop = false) { + const sw = seg.w * (CAR_TEX.w + 16) / CAR_TEX.w, sh = seg.h * (CAR_TEX.h + 16) / CAR_TEX.h; + const shadow = this.add.image(seg.cx + 2, seg.cy + 3, 'ttr-car-shadow').setDisplaySize(sw, sh).setRotation(seg.angle).setDepth(D.carShadow); + const car = this.add.image(seg.cx, seg.cy, `ttr-car-${ci}`).setDisplaySize(seg.w, seg.h + 1).setRotation(seg.angle).setDepth(D.car); + if (pop) { + const sx = car.scaleX, sy = car.scaleY; + car.setScale(sx * 1.35, sy * 1.35).setAlpha(0.4); + this.tweens.add({ targets: car, scaleX: sx, scaleY: sy, alpha: 1, duration: 160, ease: 'Back.easeOut' }); + shadow.setAlpha(0); + this.tweens.add({ targets: shadow, alpha: 1, duration: 200 }); + } + return [shadow, car]; + } + + afterAction(prev) { + if (!prev.endTriggered && this.gs.endTriggered && this.gs.triggerSeat != null) { + const who = this.gs.triggerSeat === 0 ? 'You are' : `${L.playerName(this.gs, this.gs.triggerSeat)} is`; + this.finalRoundBanner(`${who} down to ${this.gs.players[this.gs.triggerSeat].trainsLeft} trains — one last turn each!`); } } - makeCardFace(x, y, w, h, colorKey, depth, _label) { - const frame = TTR_CARD_FRAME[colorKey] ?? TTR_CARD_FRAME.back; - return [this.add.image(x, y, 'ttr-cards', frame).setDisplaySize(w, h).setDepth(depth)]; - } - - renderHand() { - if (this._suppressHandRender) return; - this.handObjs.forEach((o) => o.destroy()); - this.handObjs = []; - const hand = this.gs.players[0].hand; - const h = 140, w = 97, step = 105, x0 = 400, cy = 1000; - HAND_ORDER.forEach((colorKey, i) => { - const x = x0 + i * step; - const count = hand[colorKey]; - const objs = this.makeCardFace(x, cy, w, h, colorKey, D.hud, ''); - if (count === 0) objs.forEach((o) => o.setAlpha(0.3)); - this.handObjs.push(...objs); - this.handObjs.push(this.add.text(x, cy - h / 2 - 8, `×${count}`, { - fontFamily: 'Righteous', fontSize: '18px', color: count > 0 ? COLORS.textHex : COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.hud + 1)); + // ── tickets ──────────────────────────────────────────────────────────────────── + promptTickets() { + if (this.modal || this.busy) return; + const pend = this.gs.pendingTickets; + this.modal = openTicketChooser(this, { + pend, hud: this.hud, depth: D.modal, + estimate: (t) => this.estimateTicket(t), + onHover: (t) => { this.hl.ticket = t; this.renderHighlights(); }, + onToggle: () => playSound(this, SFX.PIECE_CLICK), + onConfirm: (keep) => { + this.modal = null; + const returned = pend.drawn.length - keep.length; + this.gs = L.resolveTicketKeep(this.gs, 0, keep); + playSound(this, SFX.CARD_PLACE); + this.runHuman(async () => { + this.renderAll(); + if (returned > 0) await this.flyTickets({ x: PAD.x + PAD.w / 2, y: PAD.y + 400 }, TICKET_BOX, returned, 0.8, true); + }); + }, }); + this.modal.sticky = true; // a decision is required — Esc can't dismiss it } - renderPiles() { - this.deckCount.setText(String(this.gs.trainDeck.length)); - const topCard = this.gs.discard.at(-1) ?? null; - this.discardCard.setFrame(topCard ? (TTR_CARD_FRAME[topCard] ?? TTR_CARD_FRAME.back) : TTR_CARD_FRAME.back); - this.discardCard.setAlpha(topCard ? 1 : 0.3); - this.discardCount.setText(String(this.gs.discard.length)); - this.ticketCount.setText(`${this.gs.ticketDeck.length} left`); + // After a menu/log closes: re-offer anything the human was owed meanwhile. + resumeIfNeeded() { + if (this.ended || this.modal || this.busy || !this.gs) return; + if (this.gs.pendingTickets?.seat === 0) this.promptTickets(); + else this.renderAll(); } - renderPanels() { - this.playerScoreText?.setText(String(L.publicScore(this.gs, 0))); - this.trainsText.setText(String(this.gs.players[0].trainsLeft)); + ticketNeed(t) { + if (t.done) return 0; + const p = AI.shortestRoutePath(this.gs, t.a, t.b, 0); + return p ? p.cost : Infinity; + } - this.oppRingGfx.clear(); - for (let seat = 1; seat < this.gs.playerCount; seat++) { - const p = this.gs.players[seat]; - const info = this.oppPanelText[seat]; - if (info) { - info.setText(`Trains ${p.trainsLeft}\nTickets ${p.tickets.length}`); + estimateTicket(t) { + const p = AI.shortestRoutePath(this.gs, t.a, t.b, 0); + const need = p ? p.cost : Infinity; + const overlap = []; + if (p) { + const mine = new Set(p.routeIds); + for (const h of L.ticketStatus(this.gs, 0)) { + if (h.done) continue; + const hp = AI.shortestRoutePath(this.gs, h.a, h.b, 0); + if (hp && hp.routeIds.some((rid) => mine.has(rid))) overlap.push(`${CITIES[h.a].name}–${CITIES[h.b].name}`); } - this.oppScoreTexts[seat]?.setText(String(L.publicScore(this.gs, seat))); - if (this.gs.currentPlayer === seat) { - const { x, y } = this.oppPos(seat); - this.oppRingGfx.lineStyle(4, COLORS.goldHex, 1); - this.oppRingGfx.strokeCircle(x, y, OPP_R + 8); - } - // Mini hand fan - const gfx = this.oppMiniHandGfx[seat]; - if (gfx && !this._suppressHandRender) { - const { x, y } = this.oppPos(seat); - const fanX = x - OPP_R; - const fanY = y + OPP_R + 20; - gfx.clear(); - const count = L.handCount(p); - const n = Math.min(count, 5); - for (let c = 0; c < n; c++) { - const cx = fanX + c * MINI_STEP; - gfx.fillStyle(0x1a2750, 1); - gfx.fillRoundedRect(cx, fanY - MINI_H / 2, MINI_W, MINI_H, 3); - gfx.lineStyle(1.5, 0x8aaad4, 0.9); - gfx.strokeRoundedRect(cx, fanY - MINI_H / 2, MINI_W, MINI_H, 3); - gfx.lineStyle(1, 0xfdf3d8, 0.12); - gfx.strokeRoundedRect(cx + 2, fanY - MINI_H / 2 + 2, MINI_W - 4, MINI_H - 4, 2); - } - this.oppMiniHandCount[seat]?.setText(`×${count}`); + } + return { need, overlap: overlap.slice(0, 2) }; + } + + async shimmerTicket(t) { + // Light the human's connecting track, city to city. + const path = this.networkPath(0, t.a, t.b); + for (const rid of path) { + for (const seg of this.segCache[rid]) { + const s = this.add.image(seg.cx, seg.cy, 'ttr-glow').setDisplaySize(seg.w * 1.6, 34) + .setRotation(seg.angle).setTint(0xfff1a0).setBlendMode('ADD').setDepth(D.fx).setAlpha(0); + this.tweens.add({ targets: s, alpha: 0.9, duration: 120, yoyo: true, hold: 120, onComplete: () => s.destroy() }); } + await this.wait(70); + } + this.flashCity(t.a, 0x9ff0a8); this.flashCity(t.b, 0x9ff0a8); + this.sparks.explode(18, CITIES[t.b].x, CITIES[t.b].y); + } + + // BFS over a seat's own routes between two cities → route ids. + networkPath(seat, a, b) { + const adj = new Map(); + for (const rid of this.gs.players[seat].routes) { + const r = ROUTES[rid]; + for (const [x, y] of [[r.a, r.b], [r.b, r.a]]) { if (!adj.has(x)) adj.set(x, []); adj.get(x).push([y, rid]); } + } + const prev = new Map([[a, null]]); + const q = [a]; + while (q.length) { + const u = q.shift(); + if (u === b) break; + for (const [v, rid] of adj.get(u) || []) if (!prev.has(v)) { prev.set(v, [u, rid]); q.push(v); } + } + if (!prev.has(b)) return []; + const out = []; + for (let c = b; prev.get(c); c = prev.get(c)[0]) out.unshift(prev.get(c)[1]); + return out; + } + + // ── rendering ─────────────────────────────────────────────────────────────────── + uiState() { + return { + myTurn: this.canHumanActIgnoringBusy(), + suppressHand: this.ui.suppressHand, + holdScores: this.ui.holdScores, + hiddenMarket: this.ui.hiddenMarket, + need: (t) => this.ticketNeed(t), + }; + } + + canHumanActIgnoringBusy() { + const s = this.gs; + return !!s && (s.phase === 'turn' || s.phase === 'lastRound') && s.currentPlayer === 0 && !s.pendingTickets && s.winner == null; + } + + renderAll() { + if (!this.gs || !this.hud) return; + this.renderCars(); + this.hud.render(this.gs, this.uiState()); + this.renderHighlights(); + this.renderStatus(); + if (!this.ui.holdScores) this.syncMarkers(); + } + + syncMarkers() { + let moved = false; + this.gs.players.forEach((p, seat) => { + const v = L.publicScore(this.gs, seat); + if (this.markerScore[seat] !== v && !this._ceremony) { this.markerScore[seat] = v; moved = true; } + }); + if (moved) this.placeMarkers(); + } + + renderCars() { + for (const [rid, owner] of Object.entries(this.gs.claimed)) { + const id = Number(rid); + if (this.carSprites.has(id) || id === this.animatingRoute) continue; + const ci = this.gs.players[owner].colorIndex; + this.carSprites.set(id, this.segCache[id].flatMap((seg) => this.placeCar(seg, ci))); } } renderStatus() { const s = this.gs; - let msg = ''; + let msg = '', tone = 'plain'; + const final = s.phase === 'lastRound' && s.finalTurnsLeft != null; if (s.phase === 'gameOver') msg = ''; - else if (s.pendingTickets && s.pendingTickets.seat === 0) msg = ''; - else if (s.currentPlayer === 0) { - if (s.drawnThisTurn === 1) msg = 'Draw one more train card (deck or face-up).'; - else msg = 'Your turn — claim a route, draw train cards, or draw tickets.'; - if (s.phase === 'lastRound') msg = 'FINAL ROUND! ' + msg; + else if (s.pendingTickets) { + msg = s.pendingTickets.seat === 0 + ? (s.pendingTickets.context === 'setup' ? 'Choose your first destination tickets' : 'Choose which tickets to keep') + : `${L.playerName(s, s.pendingTickets.seat)} is studying tickets…`; + tone = s.pendingTickets.seat === 0 ? 'you' : 'plain'; + } else if (s.currentPlayer === 0) { + const la = L.legalActions(s, 0); + tone = 'you'; + if (!la.any) msg = 'No moves left — press Pass'; + else if (s.drawnThisTurn === 1) msg = 'Draw one more train card'; + else msg = 'Your turn — claim a route, draw 2 cards, or draw tickets'; } else { - msg = `${this.pname(s.currentPlayer)} is thinking…`; + msg = `${L.playerName(s, s.currentPlayer)} is planning…`; } - this.statusText.setText(msg); - this.logText.setText(s.log[s.log.length - 1] ?? ''); - this._updateTurnIndicator(); - } - - _buildTurnTriangle() { - const g = this.add.graphics().setDepth(D.hud + 8); - g.fillStyle(0xffdd00, 1); - g.fillTriangle(-10, -13, -10, 13, 10, 0); - g.setPosition(-9999, -9999); - this.turnIndicator = g; - this._turnSeat = null; - this.tweens.add({ - targets: g, scaleX: 1.4, scaleY: 1.4, - duration: 700, yoyo: true, repeat: -1, ease: 'Sine.InOut', - }); - } - - _seatPortraitPos(seat) { - if (seat === 0) return { x: 80, y: BOT_Y, r: 46 }; - const { x, y } = this.oppPos(seat); - return { x, y, r: OPP_R }; - } - - _updateTurnIndicator() { - const seat = this.gs?.currentPlayer; - if (seat == null || !this.turnIndicator) return; - const pos = this._seatPortraitPos(seat); - if (!pos) return; - const tx = pos.x - pos.r - 20; - const ty = pos.y; - if (this._turnSeat === seat) return; - this._turnSeat = seat; - if (this.turnIndicator.x < 0) { - this.turnIndicator.setPosition(tx, ty); - } else { - this.tweens.add({ - targets: this.turnIndicator, x: tx, y: ty, - duration: 600, ease: 'Cubic.Out', - }); + if (final && msg) { msg = `FINAL ROUND · ${s.finalTurnsLeft} turn${s.finalTurnsLeft === 1 ? '' : 's'} left — ${msg}`; tone = 'final'; } + this.setStatus(msg, tone); + const stuck = this.canHumanActIgnoringBusy() && !L.legalActions(s, 0).any; + if (stuck !== this.passBtn.visible) { + this.passBtn.setVisible(stuck); + if (stuck) this.tweens.add({ targets: this.passBtn, scale: { from: 1.08, to: 1 }, duration: 500, yoyo: true, repeat: 3 }); } } - flash(message) { - const t = this.add.text(GAME_WIDTH / 2, 100, message, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: '#ffd86b', - backgroundColor: '#111923ee', padding: { x: 14, y: 8 }, - }).setOrigin(0.5).setDepth(D.banner + 2); - this.tweens.add({ targets: t, alpha: 0, y: 70, delay: 1100, duration: 500, onComplete: () => t.destroy() }); - } + // Map highlights: claimable routes, a hovered hand colour, a ticket's path, + // an opponent's network, the longest trail, and the hovered route itself. + renderHighlights() { + const g = this.glowGfx, top = this.topGfx; + if (!g || !this.gs) return; + g.clear(); top.clear(); + this.cityGlows.forEach((c) => c.setVisible(false)); + const gs = this.gs, me = gs.players[0]; + const freeTurn = this.canHumanActIgnoringBusy() && gs.drawnThisTurn === 0; - showTurnBanner(text) { - const banner = this.add.text(700, 120, text, { - fontFamily: 'Righteous', fontSize: '32px', color: COLORS.textHex, - backgroundColor: '#111923ee', padding: { x: 24, y: 12 }, - }).setOrigin(0.5).setDepth(D.banner); - banner.setAlpha(0); - this.tweens.add({ - targets: banner, alpha: 1, y: 140, duration: 260, ease: 'Back.easeOut', - onComplete: () => this.time.delayedCall(800, () => this.tweens.add({ - targets: banner, alpha: 0, y: 120, duration: 200, onComplete: () => banner.destroy(), - })), - }); - } - - // ── modals ───────────────────────────────────────────────────────────────────── - closeModal() { - this.modalObjs.forEach((o) => o.destroy()); - this.modalObjs = []; - // Block input for one tick so the click that closed the modal doesn't - // immediately fire on whatever is now exposed underneath it. - this.input.enabled = false; - this.time.delayedCall(80, () => { this.input.enabled = true; }); - } - - promptTicketKeep() { - this.closeModal(); - const pend = this.gs.pendingTickets; - const setup = pend.context === 'setup'; - const selected = new Set(pend.drawn); // pre-keep everything - const PX = RB.cx, PW = RB.w - 52; - const rowH = 70; - const PH = 200 + pend.drawn.length * rowH; - const PY = 540; - - const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setDepth(D.modal).setInteractive(); - const panel = this.add.rectangle(PX, PY, PW, PH, 0x14202c, 0.98).setStrokeStyle(3, COLORS.accent).setDepth(D.modal + 1); - const title = this.add.text(PX, PY - PH / 2 + 36, - setup ? 'Keep at least 2 destination tickets' : 'Keep at least 1 destination ticket', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - wordWrap: { width: PW - 32 }, align: 'center', - }).setOrigin(0.5).setDepth(D.modal + 2); - this.modalObjs.push(overlay, panel, title); - - const rowObjs = []; - const confirmRef = {}; - const redraw = () => { - const ok = selected.size >= pend.minKeep; - confirmRef.btn?.setEnabled(ok); - }; - - pend.drawn.forEach((id, i) => { - const t = TICKETS[id]; - const ry = PY - PH / 2 + 90 + i * rowH; - const box = this.add.rectangle(PX, ry, PW - 80, rowH - 12, 0x223344, 1) - .setStrokeStyle(3, COLORS.gold).setDepth(D.modal + 2).setInteractive({ useHandCursor: true }); - const label = this.add.text(PX - PW / 2 + 60, ry, `${CITIES[t.a].name} → ${CITIES[t.b].name}`, { - fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.modal + 3); - const pts = this.add.text(PX + PW / 2 - 46, ry, `${t.points} pts`, { - fontFamily: 'Righteous', fontSize: '17px', color: COLORS.goldHex, - }).setOrigin(1, 0.5).setDepth(D.modal + 3); - const mark = this.add.text(PX - PW / 2 + 32, ry, '✓', { - fontFamily: 'Righteous', fontSize: '22px', color: '#5fd97a', - }).setOrigin(0.5).setDepth(D.modal + 3); - const apply = () => { - const on = selected.has(id); - box.setStrokeStyle(3, on ? COLORS.gold : 0x55626f); - box.setFillStyle(on ? 0x2c4a2c : 0x223344, 1); - mark.setVisible(on); - }; - box.on('pointerdown', () => { - if (selected.has(id)) selected.delete(id); else selected.add(id); - apply(); redraw(); - }); - apply(); - rowObjs.push(box, label, pts, mark); - }); - this.modalObjs.push(...rowObjs); - - confirmRef.btn = new Button(this, PX, PY + PH / 2 - 44, 'Confirm', () => { - const keep = [...selected]; - this.closeModal(); - this.gs = L.resolveTicketKeep(this.gs, 0, keep); - this.advance(); - }, { width: 240, height: 54, fontSize: 22 }).setDepth(D.modal + 2); - this.modalObjs.push(confirmRef.btn); - redraw(); - } - - promptClaimPayment(routeId, options) { - this.closeModal(); - this._setBusy(true); // block other input while choosing - const route = ROUTES[routeId]; - const PX = RB.cx, PW = RB.w - 52; - const PH = 180 + options.length * 70; - const PY = 540; - const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setDepth(D.modal).setInteractive(); - const panel = this.add.rectangle(PX, PY, PW, PH, 0x14202c, 0.98).setStrokeStyle(3, COLORS.accent).setDepth(D.modal + 1); - const title = this.add.text(PX, PY - PH / 2 + 34, - `Claim ${CITIES[route.a].name} – ${CITIES[route.b].name}\nPay with:`, { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.textHex, align: 'center', - wordWrap: { width: PW - 32 }, - }).setOrigin(0.5).setDepth(D.modal + 2); - this.modalObjs.push(overlay, panel, title); - - const finish = async (payment) => { - this.closeModal(); - if (payment) { - const newGs = L.claimRoute(this.gs, 0, routeId, payment); - await this.animateClaimRoute(0, routeId, payment); - this.gs = newGs; - playSound(this, SFX.CARD_PLACE); - this._setBusy(false); - this.advance(); - } else { - this._setBusy(false); - this.advance(); + if (this.settings.showAffordable && freeTurn) { + for (const c of L.legalClaims(gs, 0)) this.glowRoute(g, c.routeId, 0x8fe39a, 0.85); + } + if (this.hl.pile) { + const pile = this.hl.pile; + const col = pile === 'locomotive' ? 0xffd36b : inkInt(pile); + for (const r of ROUTES) { + if (gs.claimed[r.id] != null || !L.routeClaimable(gs, 0, r.id)) continue; + const match = pile === 'locomotive' || r.color === pile || r.color === 'gray'; + if (!match) continue; + const opts = L.paymentOptions(me, r); + const payable = pile === 'locomotive' ? opts.length > 0 : opts.some((o) => o.color === pile); + this.glowRoute(g, r.id, col, payable ? 1 : 0.35); + } + } + if (this.hl.opp != null) { + for (const rid of gs.players[this.hl.opp].routes) this.glowRoute(top, rid, 0xffffff, 0.9, true); + } + if (this.hl.longest) { + const lead = L.longestLeaders(gs); + for (const s of lead.seats) for (const rid of L.longestTrail(gs, s).routes) this.glowRoute(top, rid, 0xffd36b, 1, true); + } + if (this.hl.ticket) { + const t = this.hl.ticket; + const p = AI.shortestRoutePath(gs, t.a, t.b, 0); + const ok = !!p; + this.cityGlow(t.a, ok ? 0xfff0a0 : 0xff6a5a); + this.cityGlow(t.b, ok ? 0xfff0a0 : 0xff6a5a); + if (p) for (const rid of p.routeIds) this.glowRoute(top, rid, gs.claimed[rid] === 0 ? 0x9ff0a8 : 0xffd36b, 1, gs.claimed[rid] === 0); + } + if (this.hl.route != null) { + const id = this.hl.route; + const r = ROUTES[id]; + if (gs.claimed[id] == null) { + const lock = L.routeLockReason(gs, 0, id); + const can = !lock && L.paymentOptions(me, r).length > 0; + const col = lock ? 0xb0a090 : can ? 0x6fe07f : 0xff8a6a; + this.glowRoute(top, id, col, 1, true); + this.cityGlow(r.a, 0xfff0c0, 0.6); this.cityGlow(r.b, 0xfff0c0, 0.6); + this.routeZones[id].input.cursor = freeTurn && can ? 'pointer' : 'default'; + } else { + this.glowRoute(top, id, 0xffffff, 0.8, true); } - }; - - options.forEach((opt, i) => { - const parts = []; - if (opt.colorCount > 0) parts.push(`${opt.colorCount} ${CARD_LABEL[opt.color]}`); - if (opt.locos > 0) parts.push(`${opt.locos} Locomotive`); - const by = PY - PH / 2 + 86 + i * 70; - this.modalObjs.push(new Button(this, PX, by, parts.join(' + '), () => finish(opt), - { width: PW - 120, height: 52, fontSize: 20 }).setDepth(D.modal + 2)); - }); - this.modalObjs.push(new Button(this, PX, PY + PH / 2 - 40, 'Cancel', () => finish(null), - { variant: 'ghost', width: 200, height: 46, fontSize: 18 }).setDepth(D.modal + 2)); - } - - showMyTickets() { - this.closeModal(); - const tickets = this.gs.players[0].tickets; - const find = (() => { - const parent = Array.from({ length: CITIES.length }, (_, i) => i); - const f = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }; - for (const rid of this.gs.players[0].routes) { const r = ROUTES[rid]; parent[f(r.a)] = f(r.b); } - return f; - })(); - const PX = RB.cx, PW = RB.w - 52, rowH = 64; - const PH = 170 + Math.max(1, tickets.length) * rowH; - const PY = 540; - const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) - .setDepth(D.modal).setInteractive(); - const panel = this.add.rectangle(PX, PY, PW, PH, 0x14202c, 0.98).setStrokeStyle(3, COLORS.accent).setDepth(D.modal + 1); - const title = this.add.text(PX, PY - PH / 2 + 34, 'Your Destination Tickets', { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal + 2); - this.modalObjs.push(overlay, panel, title); - - if (tickets.length === 0) { - this.modalObjs.push(this.add.text(PX, PY, 'No tickets.', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modal + 2)); } - tickets.forEach((t, i) => { - const ry = PY - PH / 2 + 84 + i * rowH; - const done = this.gs.players[0].routes.length > 0 && find(t.a) === find(t.b); - this.modalObjs.push(this.add.text(PX - PW / 2 + 28, ry, `${CITIES[t.a].name} → ${CITIES[t.b].name}`, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.modal + 2)); - this.modalObjs.push(this.add.text(PX + PW / 2 - 90, ry, `${t.points} pts`, { - fontFamily: 'Righteous', fontSize: '16px', color: COLORS.goldHex, - }).setOrigin(1, 0.5).setDepth(D.modal + 2)); - this.modalObjs.push(this.add.text(PX + PW / 2 - 18, ry, done ? '✓' : '…', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: done ? '#5fd97a' : COLORS.mutedHex, - }).setOrigin(1, 0.5).setDepth(D.modal + 2)); - }); - this.modalObjs.push(new Button(this, PX, PY + PH / 2 - 40, 'Close', () => this.closeModal(), - { variant: 'ghost', width: 200, height: 46, fontSize: 18 }).setDepth(D.modal + 2)); } - // ── game over ───────────────────────────────────────────────────────────────── - onGameOver() { - this.closeModal(); - this.hoverRouteId = null; this.renderHover(); - const scores = this.gs.scores; - const winner = this.gs.winner; - const isHuman = winner === 0; - this.recordHistory(); + glowRoute(g, id, color, alpha, strong = false) { + for (const seg of this.segCache[id]) { + const w = seg.w, h = seg.h; + g.save(); + g.translateCanvas(seg.cx, seg.cy); + g.rotateCanvas(seg.angle); + g.lineStyle(strong ? 7 : 6, color, alpha * 0.35); + g.strokeRoundedRect(-w / 2 - 4, -h / 2 - 4, w + 8, h + 8, 6); + g.lineStyle(2, color, alpha); + g.strokeRoundedRect(-w / 2 - 1.5, -h / 2 - 1.5, w + 3, h + 3, 4); + g.restore(); + } + } - const PW = 820, PH = 660, PX = 700, PY = 540; + cityGlow(cid, tint, alpha = 1) { + const g = this.cityGlows[cid]; + g.setVisible(true).setTint(tint); + g.baseAlpha = alpha; + } - const fw = this.add.particles(PX, PY, 'ttrParticle', { - speed: { min: 80, max: 460 }, lifespan: 1400, scale: { start: 1.1, end: 0 }, - alpha: { start: 1, end: 0 }, quantity: 3, frequency: 40, - tint: [0xffd700, 0xff6644, 0xffffff, 0x44aaff, 0x88ff44], - angle: { min: 0, max: 360 }, - emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(-PW / 2, -PH / 2, PW, PH) }, - }).setDepth(D.banner + 8); - this.time.delayedCall(3000, () => { fw.stop(); this.time.delayedCall(1400, () => fw.destroy()); }); + flashCity(cid, tint) { + const c = CITIES[cid]; + const g = this.add.image(c.x, c.y, 'ttr-glow').setTint(tint).setBlendMode('ADD').setDepth(D.fx).setDisplaySize(30, 30); + this.tweens.add({ targets: g, displayWidth: 110, displayHeight: 110, alpha: 0, duration: 650, onComplete: () => g.destroy() }); + } - const overlay = this.add.rectangle(PX, PY, PW, PH, 0x0a0e14, 0.95).setStrokeStyle(3, COLORS.accent).setDepth(D.banner); - const title = this.add.text(PX, PY - PH / 2 + 56, isHuman ? 'Victory!' : `${this.pname(winner)} wins`, { - fontFamily: 'Righteous', fontSize: '46px', color: isHuman ? '#ffd700' : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.banner + 1); + routeTooltip(id) { + const gs = this.gs; + if (!gs) return null; + const r = ROUTES[id]; + const title = `${CITIES[r.a].name} – ${CITIES[r.b].name}`; + const colorName = r.color === 'gray' ? 'Gray (any one colour)' : CARD_LABEL[r.color]; + const lines = [{ text: `${r.length} × ${colorName} · ${ROUTE_SCORE[r.length]} points` }]; + const owner = gs.claimed[id]; + if (owner != null) { + lines.push({ text: owner === 0 ? 'Your route.' : `Claimed by ${L.playerName(gs, owner)}.`, color: hexStr(PLAYER_COLORS[gs.players[owner].colorIndex].hex) }); + return { title, lines }; + } + const lock = L.routeLockReason(gs, 0, id); + if (lock) { lines.push({ text: lock, color: COLORS.dangerHex }); return { title, lines }; } + const opts = L.paymentOptions(gs.players[0], r); + if (opts.length) { + const o = opts[0]; + const pay = [o.colorCount ? `${o.colorCount} ${CARD_LABEL[o.color].toLowerCase()}` : null, o.locos ? `${o.locos} loco` : null].filter(Boolean).join(' + '); + lines.push({ text: `You can pay ${pay} ✓`, color: '#8fe39a' }); + if (gs.currentPlayer !== 0) lines.push({ text: 'Wait for your turn to claim it.', color: COLORS.mutedHex }); + else if (gs.drawnThisTurn > 0) lines.push({ text: 'Not this turn — you are drawing cards.', color: COLORS.mutedHex }); + else lines.push({ text: 'Click to claim.', color: COLORS.mutedHex }); + } else { + lines.push({ text: this.shortfall(id), color: '#ffb08a' }); + } + if (r.doubleGroup) lines.push({ text: gs.playerCount < 4 ? 'Double track: with 2–3 players only one side can be used.' : 'Double track: one player may own only one side.', color: COLORS.mutedHex }); + return { title, lines }; + } - // Score table. - const header = this.add.text(PX, PY - PH / 2 + 120, - 'Player Routes Tickets Longest Total', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.banner + 1); + // ── FX helpers ────────────────────────────────────────────────────────────────── + tw(cfg) { + return new Promise((res) => { + if (this.ended) { res(); return; } + this.tweens.add({ ...cfg, onComplete: () => { cfg.onDone?.(); res(); } }); + }); + } - const rows = scores.slice().sort((a, b) => b.total - a.total).map((sc) => { - const name = this.pname(sc.seat).padEnd(12).slice(0, 12); - const lp = `${sc.longestPath}${sc.longestBonus ? '+10' : ''}`; - return `${name} ${String(sc.routePoints).padStart(5)} ${String(sc.ticketPoints).padStart(6)} ${lp.padStart(7)} ${String(sc.total).padStart(5)}`; - }).join('\n'); - const body = this.add.text(PX, PY - 30, rows, { - fontFamily: 'monospace', fontSize: '22px', color: COLORS.textHex, align: 'left', lineSpacing: 8, - }).setOrigin(0.5).setDepth(D.banner + 1); + wait(ms) { return new Promise((res) => { if (this.ended) res(); else this.time.delayedCall(ms, res); }); } - const cleanup = () => { - overlay.destroy(); title.destroy(); header.destroy(); body.destroy(); - playAgain.destroy(); leave.destroy(); + // A card flight. from/to: {x,y,w,h,angle}. back: start face-down; flipEnd: + // flip on arrival (market deal), otherwise flip at `reveal` (or mid-flight). + async flyCard({ frame, from, to, duration = 320, delay = 0, back = false, flipEnd = false, reveal = null, lift = false }) { + if (delay) await this.wait(delay); + if (this.ended) return; + const img = this.add.image(from.x, from.y, 'ttr-cards', back ? CARD_FRAME.back : frame) + .setDisplaySize(from.w, from.h).setAngle(from.angle ?? 0).setDepth(D.flight); + const sh = this.add.image(from.x + 4, from.y + 8, 'ttr-card-shadow').setDisplaySize(from.w + 30, from.h + 30).setAlpha(0.6).setDepth(D.flight - 0.5); + const flip = async (w) => { + const sy = img.scaleY; + await this.tw({ targets: img, scaleX: 0, duration: 90 }); + img.setFrame(frame); + await this.tw({ targets: img, scaleX: w / 270, scaleY: sy, duration: 90 }); }; - const playAgain = new Button(this, PX - 120, PY + PH / 2 - 60, 'Play Again', () => { - cleanup(); this.startNewMatch(); - }, { width: 210, fontSize: 22 }).setDepth(D.banner + 1); - const leave = new Button(this, PX + 120, PY + PH / 2 - 60, 'Leave', () => { - cleanup(); this.scene.start('GameMenu'); - }, { variant: 'ghost', width: 210, fontSize: 22 }).setDepth(D.banner + 1); + const scaleOf = (r) => ({ scaleX: r.w / 270, scaleY: r.h / 390 }); + if (lift) await this.tw({ targets: img, y: from.y - 14, duration: 80 }); + if (back && reveal) { + await this.tw({ targets: [img], x: reveal.x, y: reveal.y, ...scaleOf(reveal), angle: 0, duration: duration * 0.6, ease: 'Cubic.easeOut' }); + sh.setVisible(false); + await flip(reveal.w); + await this.wait(140); + } else if (back && !flipEnd) { + sh.setVisible(false); + } + this.tweens.add({ targets: sh, x: to.x + 4, y: to.y + 8, displayWidth: to.w + 30, displayHeight: to.h + 30, duration, ease: 'Cubic.easeInOut' }); + await this.tw({ targets: img, x: to.x, y: to.y, ...scaleOf(to), angle: to.angle ?? 0, duration, ease: 'Cubic.easeInOut' }); + if (back && flipEnd) await flip(to.w); + img.destroy(); sh.destroy(); + } + + async flyTickets(from, to, n, scale, back = true) { + const w = 124 * scale, h = 76 * scale; + await Promise.all(Array.from({ length: n }, (_, i) => (async () => { + await this.wait(i * 70); + const img = this.add.image(from.x, from.y, 'ttr-ticket-back').setDisplaySize(124, 76).setDepth(D.flight); + await this.tw({ targets: img, x: to.x + (i - (n - 1) / 2) * 10, y: to.y + (i - (n - 1) / 2) * 6, displayWidth: w, displayHeight: h, angle: (i - 1) * 5, duration: 320 * (back ? 1 : 1), ease: 'Cubic.easeInOut' }); + img.destroy(); + })())); + } + + async floatPoints(text, x, y, dest) { + const t = this.add.text(x, y, text, { + fontFamily: 'Righteous', fontSize: '30px', color: '#ffe48a', stroke: '#3b2a17', strokeThickness: 5, + }).setOrigin(0.5).setDepth(D.banner).setScale(0.4); + await this.tw({ targets: t, scale: 1, y: y - 28, duration: 260, ease: 'Back.easeOut' }); + await this.wait(260); + await this.tw({ targets: t, x: dest.x, y: dest.y, scale: 0.45, alpha: 0.6, duration: 420, ease: 'Cubic.easeIn' }); + t.destroy(); + } + + flash(message, color = '#ffd86b') { + const t = this.add.text(STATUS.x, STATUS.y + 46, message, { + fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color, + backgroundColor: '#1d140bee', padding: { x: 14, y: 7 }, + }).setOrigin(0.5).setDepth(D.banner + 2); + this.tweens.add({ targets: t, alpha: 0, y: STATUS.y + 30, delay: 1500, duration: 450, onComplete: () => t.destroy() }); + } + + announce(text) { + const t = this.add.text(SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, text, { + fontFamily: DISPLAY, fontSize: '30px', color: '#fff3c8', stroke: '#3b2a17', strokeThickness: 6, align: 'center', + }).setOrigin(0.5).setDepth(D.banner).setAlpha(0).setScale(0.8); + this.tweens.add({ + targets: t, alpha: 1, scale: 1, duration: 260, ease: 'Back.easeOut', + onComplete: () => this.tweens.add({ targets: t, alpha: 0, delay: 1300, duration: 400, onComplete: () => t.destroy() }), + }); + } + + finalRoundBanner(text) { + whistle(this, { dur: 1.6, vol: 0.14 }); + const cx = SHEET.x + SHEET.w / 2, cy = SHEET.y + SHEET.h / 2; + const g = this.add.graphics().setDepth(D.banner); + g.fillStyle(0x000000, 0.4).fillRect(cx - 520, cy - 58, 1040, 128); + g.fillStyle(0x9a2a1e, 1).fillRect(cx - 500, cy - 64, 1000, 120); + g.lineStyle(2, 0xffd0a0, 0.9).strokeRect(cx - 492, cy - 56, 984, 104); + const t1 = this.add.text(cx, cy - 22, 'FINAL ROUND', { fontFamily: DISPLAY, fontSize: '44px', color: '#fff0d0' }).setOrigin(0.5).setDepth(D.banner + 1); + const t2 = this.add.text(cx, cy + 26, text, { fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: '#ffe0c0' }).setOrigin(0.5).setDepth(D.banner + 1); + const all = [g, t1, t2]; + all.forEach((o) => o.setAlpha(0)); + this.tweens.add({ + targets: all, alpha: 1, duration: 300, + onComplete: () => this.tweens.add({ targets: all, alpha: 0, delay: 2200, duration: 500, onComplete: () => all.forEach((o) => o.destroy()) }), + }); + } + + // ── menus ──────────────────────────────────────────────────────────────────────── + closeModal() { this.modal?.close(); this.modal = null; } + + openMenu() { + if (this.modal || !this.hud) return; + this.tooltip.hide(); + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, + onChange: (key, v) => { + this.settings[key] = v; this.saveSettings(); + if (key === 'showAffordable') { this.refreshRoutesBtn(); this.renderHighlights(); } + }, + onRules: () => new TutorialModal(this.gameDef).open(), + onLeave: () => { + this.modal = confirmBox(this, { + heading: 'Leave the game?', text: 'This game will be abandoned.', yes: 'Leave', depth: D.modal + 10, + onYes: () => { this.modal = null; this.scene.start('GameMenu'); }, + onNo: () => { this.modal = null; this.resumeIfNeeded(); }, + }); + }, + onClose: () => { this.modal = null; this.time.delayedCall(0, () => this.resumeIfNeeded()); }, + }); + } + + openLogView() { + if (this.modal || !this.gs) return; + this.tooltip.hide(); + this.modal = openLog(this, { + log: this.gs.log, depth: D.modal, + onClose: () => { this.modal = null; this.time.delayedCall(0, () => this.resumeIfNeeded()); }, + }); + } + + // ── game over ──────────────────────────────────────────────────────────────────── + onGameOver() { + if (this._ceremony) return; + this._ceremony = true; + this.closeModal(); + this.tooltip.hide(); + this.hl = { route: null, pile: null, ticket: null, opp: null, longest: false }; + this.renderHighlights(); + this.recordHistory(); + showTicketToRideEndScreen(this, { + depth: D.banner + 4, + onPlayAgain: () => this.scene.restart(this.initData), + onLeave: () => this.scene.start('GameMenu'), + }); } async recordHistory() { @@ -1047,203 +1136,5 @@ export default class TicketToRideGame extends Phaser.Scene { }); } catch (_) { /* offline / not signed in — ignore */ } } - - delay(ms) { return new Promise((res) => this.time.delayedCall(ms, res)); } - - renderAllExceptMarket() { - if (!this.gs) return; - this.renderRoutes(); - this.renderHover(); - this.renderHand(); - this.renderPiles(); - this.renderPanels(); - this.renderStatus(); - } - - handDestForColor(colorKey) { - const i = HAND_ORDER.indexOf(colorKey); - return { x: 400 + i * 105, y: 1000 }; - } - - async animateClaimRoute(seat, routeId, payment) { - const ANIM_DEPTH = D.banner + 10; - const CX = GAME_WIDTH / 2, CY = GAME_HEIGHT / 2; - const GAP = 20; - const segs = this.segCache[routeId]; - const playerCol = this.playerColor(seat); - - const cards = []; - for (let c = 0; c < (payment.colorCount ?? 0); c++) cards.push(payment.color); - for (let c = 0; c < (payment.locos ?? 0); c++) cards.push('locomotive'); - - const N = cards.length; - const totalW = N * 270 + (N - 1) * GAP; - const lineupStartX = CX - totalW / 2 + 135; - - const srcForColor = (colorKey) => { - if (seat === 0) return this.handDestForColor(colorKey); - const { x, y } = this.oppPos(seat); - return { x: x - OPP_R + 39, y: y + OPP_R + 20 }; - }; - - // Phase 1: cards fly to lineup one at a time - const cardObjs = []; - for (let i = 0; i < N; i++) { - const colorKey = cards[i]; - const src = srcForColor(colorKey); - const img = this.add.image(src.x, src.y, 'ttr-cards', TTR_CARD_FRAME[colorKey] ?? TTR_CARD_FRAME.back) - .setDisplaySize(270, 390) - .setDepth(ANIM_DEPTH + i); - cardObjs.push(img); - await new Promise((res) => this.tweens.add({ - targets: img, - x: lineupStartX + i * (270 + GAP), y: CY, - duration: 400, ease: 'Cubic.easeOut', onComplete: res, - })); - } - - // Phase 2: hold - await this.delay(500); - - // Phase 3: transform all cards to train cars simultaneously - await Promise.all(cardObjs.map((img) => this._transformToTrainCar(img, playerCol.hex))); - - // Phase 4: brief pause as train cars - await this.delay(150); - - // Phase 5: fly to route segments simultaneously - await Promise.all(segs.map((seg, i) => { - const img = cardObjs[i]; - if (!img) return Promise.resolve(); - return new Promise((res) => this.tweens.add({ - targets: img, - x: seg.cx, y: seg.cy, - scaleX: seg.w / 120, scaleY: 16 / 40, - rotation: seg.angle, - duration: 600, ease: 'Cubic.easeIn', onComplete: res, - })); - })); - - cardObjs.forEach((img) => img.destroy()); - } - - async _transformToTrainCar(img, tintColor) { - await new Promise((res) => this.tweens.add({ - targets: img, scaleX: 0, scaleY: 0, duration: 200, ease: 'Cubic.easeIn', onComplete: res, - })); - img.setTexture('ttr-train-car').setTint(tintColor); - await new Promise((res) => this.tweens.add({ - targets: img, scaleX: 1, scaleY: 1, duration: 200, ease: 'Cubic.easeOut', onComplete: res, - })); - } - - async animateMarketSlideUp(fromSlot, lastSlot) { - const mkStep = CARD_W + 10; - const targets = []; - for (let j = fromSlot + 1; j <= lastSlot; j++) { - if (this.marketSlotObjs[j]) targets.push(...this.marketSlotObjs[j]); - } - if (targets.length === 0) return; - await new Promise((res) => this.tweens.add({ - targets, y: `-=${mkStep}`, duration: 200, ease: 'Cubic.easeInOut', onComplete: res, - })); - } - - async animateRefillMarketSlot(slotIndex, color) { - const ANIM_DEPTH = D.banner + 10; - const destX = MK_X; - const destY = MK_Y0 + slotIndex * (CARD_W + 10); - const origScaleX = CARD_W / 270; - - const card = this.add.image(PILE_X, MK_Y0, 'ttr-cards', TTR_CARD_FRAME.back) - .setDisplaySize(CARD_W, CARD_H) - .setAngle(-90) - .setDepth(ANIM_DEPTH); - - // Slide from deck to market slot - await new Promise((res) => this.tweens.add({ - targets: card, x: destX, y: destY, duration: 350, ease: 'Cubic.easeOut', onComplete: res, - })); - - // Flip at slot: collapse scaleX (height at -90°), swap frame, restore - await new Promise((res) => this.tweens.add({ - targets: card, scaleX: 0, duration: 150, ease: 'Linear', onComplete: res, - })); - card.setFrame(TTR_CARD_FRAME[color] ?? TTR_CARD_FRAME.back); - await new Promise((res) => this.tweens.add({ - targets: card, scaleX: origScaleX, duration: 150, ease: 'Linear', onComplete: res, - })); - - card.destroy(); - } - - async animateCardDraw({ srcX, srcY, srcAngle = 0, cardFrame, shouldFlip = false, destX, destY, destW, destH }) { - const ANIM_DEPTH = D.banner + 10; - const CX = GAME_WIDTH / 2; - const CY = GAME_HEIGHT / 2; - const origScaleX = CARD_W / 270; - - const card = this.add.image(srcX, srcY, 'ttr-cards', shouldFlip ? TTR_CARD_FRAME.back : cardFrame) - .setDisplaySize(CARD_W, CARD_H) - .setAngle(srcAngle) - .setDepth(ANIM_DEPTH); - - // Phase 0: flip (player from deck only) - if (shouldFlip) { - // Straighten to portrait before flip - await new Promise((res) => this.tweens.add({ - targets: card, angle: 0, duration: 250, ease: 'Cubic.easeOut', onComplete: res, - })); - // First half: collapse width - await new Promise((res) => this.tweens.add({ - targets: card, scaleX: 0, duration: 180, ease: 'Linear', onComplete: res, - })); - card.setFrame(cardFrame); - // Second half: restore width - await new Promise((res) => this.tweens.add({ - targets: card, scaleX: origScaleX, duration: 180, ease: 'Linear', onComplete: res, - })); - await this.delay(150); - } - - // Phase 1: fly to center at full sprite size - await new Promise((res) => this.tweens.add({ - targets: card, - x: CX, y: CY, - scaleX: 1, scaleY: 1, - angle: 0, - duration: 600, - ease: 'Cubic.easeOut', - onComplete: res, - })); - - // Phase 2: hold at center with fireworks - const fw = this.add.particles(CX, CY, 'ttrParticle', { - speed: { min: 80, max: 420 }, - lifespan: 700, - scale: { start: 1, end: 0 }, - alpha: { start: 1, end: 0 }, - quantity: 2, - frequency: 35, - tint: [0xffd700, 0xff6644, 0xffffff, 0x44aaff, 0x88ff44], - angle: { min: 0, max: 360 }, - emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(-160, -220, 320, 440) }, - }).setDepth(ANIM_DEPTH + 1); - - await this.delay(500); - fw.stop(); - - // Phase 3: fly to destination at final size - await new Promise((res) => this.tweens.add({ - targets: card, - x: destX, y: destY, - scaleX: destW / 270, scaleY: destH / 390, - duration: 500, - ease: 'Cubic.easeIn', - onComplete: res, - })); - - fw.destroy(); - card.destroy(); - } } + diff --git a/src/games/tickettoride/TicketToRideHud.js b/src/games/tickettoride/TicketToRideHud.js new file mode 100644 index 0000000..1b5abb1 --- /dev/null +++ b/src/games/tickettoride/TicketToRideHud.js @@ -0,0 +1,614 @@ +// TicketToRideHud.js — the desk furniture and the human's rail. +// +// Right pad: opponent plaques (portrait, trains gauge, cards, tickets, score, +// turn spotlight, action captions), the face-up card rack, the draw pile +// (stack height tracks the count), the discard, the ticket box, the 2-draw +// pips, the longest-route plate and the dispatch-log notepad. +// Bottom rail: the human's portrait + info, grouped hand piles with brass count +// badges, and the destination-ticket rail with live progress. +// +// The scene owns game flow; the HUD only draws state and reports input through +// the callbacks passed to the constructor. + +import { COLORS } from '../../config.js'; +import { auth } from '../../services/auth.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { CITIES, TRAIN_COLORS, PLAYER_COLORS, CARD_LABEL } from './TicketToRideBoard.js'; +import * as L from './TicketToRideLogic.js'; +import { + oppRect, CARD, RACK, marketPos, DECK, DISCARD, TICKET_BOX, DRAW_PIPS, LONGEST, NOTEPAD, + PORTRAIT, HUMAN_INFO, HAND_CARD, handPilePos, TICKETS_RAIL, TICKET_MINI, ticketMiniPos, +} from './TicketToRideLayout.js'; +import { SERIF, DISPLAY, TICKET_TEX } from './TicketToRideArt.js'; + +export const HAND_ORDER = [...TRAIN_COLORS, 'locomotive']; +export const CARD_FRAME = { + red: 0, orange: 1, yellow: 2, green: 3, blue: 4, + purple: 5, black: 6, white: 7, locomotive: 8, back: 9, +}; +const INK = '#3b2a17'; +const SHADOW = { offsetX: 1, offsetY: 2, color: '#000000', blur: 3, fill: true }; + +export class TTRHud { + constructor(scene, depth, cb) { + this.scene = scene; + this.D = depth; // { hud, hudTop } + this.cb = cb; // onMarket(i), onDeck(), onTickets(), onPileHover(c), onTicketHover(t), onOppHover(seat), onLongestHover(on), onNotepad(), tooltip(obj, fn) + this.plaques = []; + this.portraits = []; + this.piles = []; + this.ticketObjs = []; + this.deckLayers = []; + this.ticketLayers = []; + this._stamped = new Set(); + } + + // ── build ──────────────────────────────────────────────────────────────────── + build(gs, opponents) { + this.gs = gs; + this.buildPlaques(gs, opponents); + this.buildRack(); + this.buildPiles(); + this.buildLongest(); + this.buildNotepad(); + this.buildRail(gs); + } + + buildPlaques(gs, opponents) { + const sc = this.scene, d = this.D.hud; + for (let seat = 1; seat < gs.playerCount; seat++) { + const r = oppRect(seat - 1); + const cx = r.x + r.w / 2, cy = r.y + r.h / 2; + const col = PLAYER_COLORS[gs.players[seat].colorIndex]; + const glow = sc.add.image(cx, cy, 'ttr-glow').setDisplaySize(r.w * 1.5, r.h * 1.9) + .setTint(0xffd27a).setBlendMode('ADD').setAlpha(0).setDepth(d - 1); + const img = sc.add.image(cx, cy, 'ttr-plaque').setDisplaySize(r.w, r.h).setDepth(d); + const ring = sc.add.graphics().setDepth(d + 1); + const name = sc.add.text(r.x + 76, r.y + 18, L.playerName(gs, seat), { + fontFamily: 'Righteous', fontSize: '15px', color: '#f6e7c4', shadow: SHADOW, + }).setOrigin(0, 0.5).setDepth(d + 2); + if (name.width > r.w - 112) name.setScale((r.w - 112) / name.width); + const car = sc.add.image(r.x + r.w - 22, r.y + 18, `ttr-car-${gs.players[seat].colorIndex}`) + .setDisplaySize(26, 9).setDepth(d + 2); + const score = sc.add.text(r.x + r.w - 14, r.y + 48, '0', { + fontFamily: 'Righteous', fontSize: '22px', color: INK, + }).setOrigin(1, 0.5).setDepth(d + 2); + const scoreLbl = sc.add.text(r.x + 84, r.y + 48, 'Score', { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: INK, + }).setOrigin(0, 0.5).setDepth(d + 2); + const gauge = sc.add.graphics().setDepth(d + 2); + const trains = sc.add.text(r.x + 84, r.y + 76, '', { + fontFamily: SERIF, fontSize: '11px', color: INK, + }).setOrigin(0, 0.5).setDepth(d + 3); + const info = sc.add.text(r.x + 84, r.y + 96, '', { + fontFamily: SERIF, fontSize: '12px', color: INK, + }).setOrigin(0, 0.5).setDepth(d + 2); + const caption = sc.add.text(cx, r.y + r.h + 2, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#ffe9b0', + backgroundColor: '#1d140bdd', padding: { x: 8, y: 3 }, + }).setOrigin(0.5, 0).setDepth(this.D.hudTop + 2).setAlpha(0); + const zone = sc.add.zone(cx, cy, r.w, r.h).setInteractive().setDepth(d + 4); + zone.isTableZone = true; + zone.on('pointerover', () => this.cb.onOppHover?.(seat)); + zone.on('pointerout', () => this.cb.onOppHover?.(null)); + this.cb.tooltip?.(zone, () => this.oppTooltip(seat)); + const portrait = createOpponentPortrait(sc, opponents[seat - 1], r.x + 40, r.y + 66, 28, d + 3, { playIntro: seat === 1 }); + this.portraits[seat] = portrait; + this.plaques[seat] = { r, glow, img, ring, name, car, score, scoreLbl, gauge, trains, info, caption, zone, col }; + } + } + + oppTooltip(seat) { + const gs = this.gs, p = gs.players[seat]; + const skill = this.scene.skillFor?.(seat); + return { + title: L.playerName(gs, seat), + lines: [ + { text: `Route points ${L.routePoints(gs, seat)}` }, + { text: `${p.trainsLeft} trains left · ${p.routes.length} routes` }, + { text: `${L.handCount(p)} train cards · ${p.tickets.length} tickets (hidden)` }, + { text: `Longest trail ${L.longestPathFor(gs, seat)} cars`, color: COLORS.mutedHex }, + ...(skill ? [{ text: `Skill ${skill} / 5`, color: COLORS.mutedHex }] : []), + { text: 'Their network is outlined on the map.', color: COLORS.mutedHex }, + ], + }; + } + + buildRack() { + const sc = this.scene, d = this.D.hud; + sc.add.image(RACK.x + RACK.w / 2, RACK.y + RACK.h / 2, 'ttr-rack').setDisplaySize(RACK.w, RACK.h).setDepth(d - 1); + this.market = []; + for (let i = 0; i < 5; i++) { + const p = marketPos(i); + const shadow = sc.add.image(p.x + 2, p.y + 4, 'ttr-card-shadow').setDepth(d) + .setDisplaySize(CARD.w + 32, CARD.h + 32); + const card = sc.add.image(p.x, p.y, 'ttr-cards', CARD_FRAME.back).setDisplaySize(CARD.w, CARD.h).setDepth(d + 1); + const glow = sc.add.image(p.x, p.y, 'ttr-glow').setDisplaySize(CARD.w * 1.7, CARD.h * 1.5) + .setBlendMode('ADD').setTint(0xffe08a).setAlpha(0).setDepth(d); + const key = sc.add.text(p.x, p.y + CARD.h / 2 + 7, String(i + 1), { + fontFamily: SERIF, fontSize: '11px', color: '#f0d68e', + }).setOrigin(0.5).setDepth(d + 2).setAlpha(0.7); + const zone = sc.add.zone(p.x, p.y, CARD.w, CARD.h).setInteractive({ useHandCursor: true }).setDepth(d + 4); + zone.on('pointerover', () => this.hoverMarket(i, true)); + zone.on('pointerout', () => this.hoverMarket(i, false)); + zone.on('pointerdown', () => this.cb.onMarket?.(i)); + this.cb.tooltip?.(zone, () => this.marketTooltip(i)); + this.market.push({ shadow, card, glow, key, zone, base: p, hovered: false }); + } + } + + marketTooltip(i) { + const c = this.gs.faceUp[i]; + if (!c) return { title: 'Empty slot', lines: [] }; + const lines = [{ text: `Key ${i + 1} takes it.` }]; + if (c === 'locomotive') { + lines.unshift({ text: 'Wild — counts as any colour.' }); + lines.push({ text: 'Face-up: only as your first draw, and it uses your whole turn.', color: COLORS.mutedHex }); + } + return { title: `${CARD_LABEL[c]} card`, lines }; + } + + hoverMarket(i, on) { + const m = this.market[i]; + m.hovered = on; + const live = on && this.marketLegal?.[i]; + this.scene.tweens.add({ targets: [m.card], y: m.base.y - (live ? 8 : 0), duration: 120 }); + m.glow.setAlpha(live ? 0.55 : 0); + } + + buildPiles() { + const sc = this.scene, d = this.D.hud; + // Draw pile: a stack of backs whose height follows the count. + for (let k = 0; k < 9; k++) { + this.deckLayers.push(sc.add.image(DECK.x, DECK.y, 'ttr-cards', CARD_FRAME.back) + .setDisplaySize(CARD.w, CARD.h).setDepth(d + k * 0.01)); + } + this.deckBadge = this.badge(DECK.x + CARD.w / 2 - 4, DECK.y + CARD.h / 2 - 6); + this.deckHint = sc.add.text(DECK.x, DECK.y - CARD.h / 2 - 10, 'Draw (D)', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#e8d6a8', + }).setOrigin(0.5).setDepth(d + 1); + const dz = sc.add.zone(DECK.x, DECK.y, CARD.w + 10, CARD.h + 10).setInteractive({ useHandCursor: true }).setDepth(d + 4); + dz.on('pointerdown', () => this.cb.onDeck?.()); + dz.on('pointerover', () => { this.deckHover = true; this.renderDeck(); }); + dz.on('pointerout', () => { this.deckHover = false; this.renderDeck(); }); + this.cb.tooltip?.(dz, () => ({ + title: 'Train card deck', + lines: [ + { text: `${this.gs.trainDeck.length} cards · discard ${this.gs.discard.length}` }, + { text: 'Draw blind. Two draws make a turn.', color: COLORS.mutedHex }, + ...(this.gs.trainDeck.length === 0 && this.gs.discard.length ? [{ text: 'Empty — the discard is reshuffled on the next draw.', color: COLORS.goldHex }] : []), + ], + })); + this.deckGlow = sc.add.image(DECK.x, DECK.y, 'ttr-glow').setDisplaySize(CARD.w * 1.7, CARD.h * 1.5) + .setBlendMode('ADD').setTint(0xffe08a).setAlpha(0).setDepth(d - 0.5); + + // Discard. + this.discardImg = sc.add.image(DISCARD.x, DISCARD.y, 'ttr-cards', CARD_FRAME.back) + .setDisplaySize(CARD.w, CARD.h).setDepth(d).setAngle(4); + this.discardBadge = this.badge(DISCARD.x + CARD.w / 2 - 4, DISCARD.y + CARD.h / 2 - 6); + sc.add.text(DISCARD.x, DISCARD.y - CARD.h / 2 - 10, 'Discard', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#e8d6a8', + }).setOrigin(0.5).setDepth(d + 1); + + // Ticket box. + for (let k = 0; k < 6; k++) { + this.ticketLayers.push(sc.add.image(TICKET_BOX.x, TICKET_BOX.y, 'ttr-ticket-back') + .setDisplaySize(TICKET_BOX.w, TICKET_BOX.h).setDepth(d + k * 0.01)); + } + this.ticketBadge = this.badge(TICKET_BOX.x + TICKET_BOX.w / 2 - 6, TICKET_BOX.y + TICKET_BOX.h / 2 - 4); + sc.add.text(TICKET_BOX.x, TICKET_BOX.y - TICKET_BOX.h / 2 - 10 - 8, 'Destination Tickets (T)', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#e8d6a8', + }).setOrigin(0.5).setDepth(d + 1); + this.ticketGlow = sc.add.image(TICKET_BOX.x, TICKET_BOX.y, 'ttr-glow').setDisplaySize(TICKET_BOX.w * 1.6, TICKET_BOX.h * 1.9) + .setBlendMode('ADD').setTint(0xffe08a).setAlpha(0).setDepth(d - 0.5); + const tz = sc.add.zone(TICKET_BOX.x, TICKET_BOX.y, TICKET_BOX.w + 10, TICKET_BOX.h + 20).setInteractive({ useHandCursor: true }).setDepth(d + 4); + tz.on('pointerdown', () => this.cb.onTickets?.()); + tz.on('pointerover', () => { this.ticketHover = true; this.renderTicketBox(); }); + tz.on('pointerout', () => { this.ticketHover = false; this.renderTicketBox(); }); + this.cb.tooltip?.(tz, () => ({ + title: 'Destination tickets', + lines: [ + { text: `${this.gs.ticketDeck.length} left in the box` }, + { text: 'Draw 3, keep at least 1. Uses your whole turn.', color: COLORS.mutedHex }, + { text: 'Completed tickets score their points; unfinished ones cost them.', color: COLORS.mutedHex }, + ], + })); + + // Two-draw pips. + this.pips = sc.add.graphics().setDepth(d + 2); + this.pipText = sc.add.text(DRAW_PIPS.x + 22, DRAW_PIPS.y, '', { + fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#ffe3a0', + }).setOrigin(0, 0.5).setDepth(d + 2); + } + + badge(x, y) { + const sc = this.scene, d = this.D.hud + 2; + const img = sc.add.image(x, y, 'ttr-badge').setDisplaySize(28, 28).setDepth(d); + const t = sc.add.text(x, y + 0.5, '', { fontFamily: 'Righteous', fontSize: '13px', color: '#2b1a06' }).setOrigin(0.5).setDepth(d + 0.1); + return { img, t, set: (v) => t.setText(String(v)), setVisible: (v) => { img.setVisible(v); t.setVisible(v); } }; + } + + buildLongest() { + const sc = this.scene, d = this.D.hud; + sc.add.image(LONGEST.x + LONGEST.w / 2, LONGEST.y + LONGEST.h / 2, 'ttr-longest').setDisplaySize(LONGEST.w, LONGEST.h).setDepth(d); + this.longestText = sc.add.text(LONGEST.x + LONGEST.w / 2, LONGEST.y + LONGEST.h / 2, '', { + fontFamily: DISPLAY, fontSize: '16px', color: '#2b1a06', align: 'center', + }).setOrigin(0.5).setDepth(d + 1); + const z = sc.add.zone(LONGEST.x + LONGEST.w / 2, LONGEST.y + LONGEST.h / 2, LONGEST.w, LONGEST.h).setInteractive().setDepth(d + 4); + z.on('pointerover', () => this.cb.onLongestHover?.(true)); + z.on('pointerout', () => this.cb.onLongestHover?.(false)); + this.cb.tooltip?.(z, () => ({ + title: 'Longest Continuous Route', + lines: [ + { text: '+10 points at the end for the longest unbroken trail of your trains (each route once).' }, + ...this.gs.players.map((p) => ({ text: `${L.playerName(this.gs, p.seat)}: ${L.longestPathFor(this.gs, p.seat)} cars`, color: COLORS.mutedHex })), + ], + })); + } + + buildNotepad() { + const sc = this.scene, d = this.D.hud; + sc.add.image(NOTEPAD.x + NOTEPAD.w / 2, NOTEPAD.y + NOTEPAD.h / 2, 'ttr-notepad').setDisplaySize(NOTEPAD.w, NOTEPAD.h).setDepth(d); + this.logLines = []; + for (let i = 0; i < 7; i++) { + this.logLines.push(sc.add.text(NOTEPAD.x + 36, NOTEPAD.y + 38 + i * 22 - 8, '', { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#2a3a5a', + }).setOrigin(0, 0.5).setDepth(d + 1)); + } + const z = sc.add.zone(NOTEPAD.x + NOTEPAD.w / 2, NOTEPAD.y + NOTEPAD.h / 2, NOTEPAD.w, NOTEPAD.h) + .setInteractive({ useHandCursor: true }).setDepth(d + 4); + z.on('pointerdown', () => this.cb.onNotepad?.()); + this.cb.tooltip?.(z, () => ({ title: 'Dispatch log', lines: [{ text: 'Click (or press L) for the full history.', color: COLORS.mutedHex }] })); + } + + buildRail(gs) { + const sc = this.scene, d = this.D.hud; + this.humanPortrait = createPlayerPortrait(sc, PORTRAIT.x, PORTRAIT.y, PORTRAIT.r, d, 'TicketToRideGame'); + const ci = gs.players[0].colorIndex; + sc.add.text(PORTRAIT.x, PORTRAIT.y + PORTRAIT.r + 16, auth.user?.username ?? 'You', { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.textHex, + }).setOrigin(0.5).setDepth(d); + sc.add.image(PORTRAIT.x, PORTRAIT.y + PORTRAIT.r + 34, `ttr-car-${ci}`).setDisplaySize(34, 11).setDepth(d); + + const hx = HUMAN_INFO.x + 8; + sc.add.text(hx, HUMAN_INFO.y + 10, 'SCORE', { fontFamily: SERIF, fontSize: '12px', color: '#d8c08a' }).setOrigin(0, 0.5).setDepth(d); + this.humanScore = sc.add.text(hx, HUMAN_INFO.y + 36, '0', { + fontFamily: 'Righteous', fontSize: '34px', color: '#f6e7c4', shadow: SHADOW, + }).setOrigin(0, 0.5).setDepth(d); + this.humanGauge = sc.add.graphics().setDepth(d); + this.humanTrains = sc.add.text(hx, HUMAN_INFO.y + 70, '', { + fontFamily: SERIF, fontSize: '13px', color: '#e8d6a8', + }).setOrigin(0, 0.5).setDepth(d); + this.humanInfo = sc.add.text(hx, HUMAN_INFO.y + 112, '', { + fontFamily: SERIF, fontSize: '13px', color: '#e8d6a8', lineSpacing: 3, + }).setOrigin(0, 0.5).setDepth(d); + + // Hand piles. + HAND_ORDER.forEach((color, i) => { + const p = handPilePos(i); + const layers = []; + for (let k = 0; k < 5; k++) { + layers.push(sc.add.image(p.x, p.y, 'ttr-cards', CARD_FRAME[color]).setDisplaySize(HAND_CARD.w, HAND_CARD.h).setDepth(d + 1 + k * 0.01)); + } + const b = this.badge(p.x + HAND_CARD.w / 2 - 6, p.y - HAND_CARD.h / 2 + 4); + const zone = sc.add.zone(p.x, p.y, HAND_CARD.w + 8, HAND_CARD.h + 8).setInteractive().setDepth(d + 4); + zone.isTableZone = true; + zone.on('pointerover', () => this.cb.onPileHover?.(color)); + zone.on('pointerout', () => this.cb.onPileHover?.(null)); + this.cb.tooltip?.(zone, () => { + const n = this.gs.players[0].hand[color]; + return { + title: `${CARD_LABEL[color]} ×${n}`, + lines: [{ + text: color === 'locomotive' + ? 'Wild: pays for any route. Highlighted: every route you could pay for right now.' + : `Highlighted: ${color} and gray routes${n ? ' (bright = you could claim it now)' : ''}.`, + color: COLORS.mutedHex, + }], + }; + }); + this.piles.push({ color, base: p, layers, badge: b, zone, shown: -1 }); + }); + } + + // ── render ─────────────────────────────────────────────────────────────────── + render(gs, ui) { + this.gs = gs; + this.ui = ui; + this.renderPlaques(gs, ui); + this.renderMarket(gs, ui); + this.renderDeck(); + this.renderDiscard(); + this.renderTicketBox(); + this.renderPips(gs, ui); + this.renderLongest(gs); + this.renderLog(gs); + this.renderHuman(gs); + if (!ui.suppressHand) this.renderHand(gs); + this.renderTickets(gs, ui); + } + + renderPlaques(gs, ui) { + for (let seat = 1; seat < gs.playerCount; seat++) { + const pq = this.plaques[seat]; + if (!pq) continue; + const p = gs.players[seat]; + if (!ui.holdScores) pq.score.setText(String(L.publicScore(gs, seat))); + pq.info.setText(`Cards ${L.handCount(p)} · Tickets ${p.tickets.length}`); + pq.trains.setText(`Trains ${p.trainsLeft}`); + const r = pq.r; + pq.gauge.clear(); + const gx = r.x + 128, gy = r.y + 72, gw = r.w - 140, gh = 8; + pq.gauge.fillStyle(0x3b2a17, 0.25).fillRoundedRect(gx, gy, gw, gh, 3); + pq.gauge.fillStyle(p.trainsLeft <= 6 ? 0xc0392b : pq.col.hex, 1).fillRoundedRect(gx, gy, Math.max(2, gw * (p.trainsLeft / 45)), gh, 3); + pq.gauge.lineStyle(1, 0x3b2a17, 0.6).strokeRoundedRect(gx, gy, gw, gh, 3); + const active = gs.currentPlayer === seat && gs.phase !== 'gameOver' && gs.phase !== 'ticketSetup' + || (gs.pendingTickets && gs.pendingTickets.seat === seat); + pq.ring.clear(); + if (active) { + pq.ring.lineStyle(3, 0xffd36b, 1).strokeRoundedRect(r.x - 2, r.y - 2, r.w + 4, r.h + 4, 11); + if (!pq.active) { + pq.glowTween?.remove(); + pq.glowTween = this.scene.tweens.add({ targets: pq.glow, alpha: { from: 0.25, to: 0.55 }, duration: 900, yoyo: true, repeat: -1 }); + } + } else if (pq.active) { + pq.glowTween?.remove(); pq.glowTween = null; + pq.glow.setAlpha(0); + } + pq.active = active; + } + } + + renderMarket(gs, ui) { + const legal = new Set(ui.myTurn ? L.legalFaceUp(gs) : []); + this.marketLegal = []; + for (let i = 0; i < 5; i++) { + const m = this.market[i]; + const c = gs.faceUp[i]; + const has = c != null && !(ui.hiddenMarket?.has(i)); + m.card.setVisible(has).setFrame(CARD_FRAME[c] ?? CARD_FRAME.back); + m.shadow.setVisible(has); + const ok = has && legal.has(i); + this.marketLegal[i] = ok; + const dim = has && ui.myTurn && !ok; // e.g. a face-up locomotive on the 2nd draw + m.card.setAlpha(dim ? 0.45 : 1); + if (dim) m.card.setTint(0x888888); else m.card.clearTint(); + m.zone.input.cursor = ok ? 'pointer' : 'default'; + if (!m.hovered) { m.card.y = m.base.y; m.glow.setAlpha(0); } + } + } + + renderDeck() { + const gs = this.gs; + if (!gs) return; + const n = gs.trainDeck.length; + const layers = n === 0 ? 0 : Math.max(1, Math.ceil(Math.min(n, 110) / 13)); + this.deckLayers.forEach((img, k) => { + img.setVisible(k < layers && !this.ui?.hideDeckTop?.(k, layers)); + img.setPosition(DECK.x - k * 0.4, DECK.y - k * 1.5); + }); + this.deckBadge.set(n); + this.deckTopY = DECK.y - (layers - 1) * 1.5; + const live = this.ui?.myTurn && L.canDrawFromDeck(gs); + this.deckGlow.setAlpha(live && this.deckHover ? 0.55 : 0); + this.deckHint.setText(n === 0 && gs.discard.length ? 'Reshuffle (D)' : 'Draw (D)'); + } + + renderDiscard() { + const gs = this.gs; + const top = gs.discard.at(-1); + this.discardImg.setFrame(top ? CARD_FRAME[top] : CARD_FRAME.back).setAlpha(top ? 1 : 0.18); + this.discardBadge.set(gs.discard.length); + this.discardBadge.setVisible(gs.discard.length > 0); + } + + renderTicketBox() { + const gs = this.gs; + const n = gs.ticketDeck.length; + const layers = n === 0 ? 0 : Math.max(1, Math.ceil(n / 5)); + this.ticketLayers.forEach((img, k) => { + img.setVisible(k < layers); + img.setPosition(TICKET_BOX.x + k * 0.6, TICKET_BOX.y - k * 2); + }); + this.ticketBadge.set(n); + const live = this.ui?.myTurn && gs.drawnThisTurn === 0 && n > 0; + this.ticketGlow.setAlpha(live && this.ticketHover ? 0.5 : 0); + } + + renderPips(gs, ui) { + this.pips.clear(); + if (!ui.myTurn) { this.pipText.setText(''); return; } + for (let k = 0; k < 2; k++) { + const x = DRAW_PIPS.x - 6 + k * 14, y = DRAW_PIPS.y; + this.pips.fillStyle(k < gs.drawnThisTurn ? 0xffd36b : 0x000000, k < gs.drawnThisTurn ? 1 : 0.35).fillCircle(x, y, 5); + this.pips.lineStyle(1.5, 0xffd36b, 0.9).strokeCircle(x, y, 5); + } + this.pipText.setText(gs.drawnThisTurn === 1 ? 'draw 1 more card' : ''); + } + + renderLongest(gs) { + const lead = L.longestLeaders(gs); + if (!lead.seats.length) { this.longestText.setText('LONGEST ROUTE · unclaimed'); return; } + const who = lead.seats.length > 1 ? `${lead.seats.length} tied` : L.playerName(gs, lead.seats[0]); + this.longestText.setText(`LONGEST ROUTE · ${who} · ${lead.length} cars`); + if (this.longestText.width > LONGEST.w - 40) this.longestText.setScale((LONGEST.w - 40) / this.longestText.width); + else this.longestText.setScale(1); + } + + renderLog(gs) { + const lines = gs.log.slice(-7).reverse(); + this.logLines.forEach((t, i) => { + const s = lines[i] ?? ''; + t.setText(s.length > 48 ? `${s.slice(0, 47)}…` : s); + t.setAlpha(i === 0 ? 1 : Math.max(0.35, 0.85 - i * 0.1)); + }); + } + + renderHuman(gs) { + const p = gs.players[0]; + if (!this.ui?.holdScores) this.humanScore.setText(String(L.publicScore(gs, 0))); + const gx = HUMAN_INFO.x + 8, gy = HUMAN_INFO.y + 84, gw = 160, gh = 9; + const col = PLAYER_COLORS[p.colorIndex]; + this.humanGauge.clear(); + this.humanGauge.fillStyle(0x000000, 0.4).fillRoundedRect(gx, gy, gw, gh, 4); + this.humanGauge.fillStyle(p.trainsLeft <= 6 ? 0xc0392b : col.hex, 1).fillRoundedRect(gx, gy, Math.max(3, gw * p.trainsLeft / 45), gh, 4); + this.humanGauge.lineStyle(1, 0xd6b05c, 0.7).strokeRoundedRect(gx, gy, gw, gh, 4); + this.humanTrains.setText(`Trains left ${p.trainsLeft} / 45`); + const st = L.ticketStatus(gs, 0); + this.humanInfo.setText(`Cards ${L.handCount(p)} · Tickets ${st.filter((t) => t.done).length}/${st.length}`); + } + + renderHand(gs) { + const hand = gs.players[0].hand; + this.piles.forEach((pile) => { + const n = hand[pile.color]; + const shown = Math.min(5, Math.max(1, n)); + pile.layers.forEach((img, k) => { + img.setVisible(k < shown); + img.setPosition(pile.base.x + k * 1.2, pile.base.y - k * 3); + img.setAlpha(n === 0 ? 0.2 : 1); + }); + pile.badge.set(n); + pile.badge.setVisible(n > 0); + pile.shown = n; + }); + } + + pilePos(color) { + const pile = this.piles.find((p) => p.color === color); + const n = Math.min(5, Math.max(1, pile.shown + 1)); + return { x: pile.base.x + (n - 1) * 1.2, y: pile.base.y - (n - 1) * 3 }; + } + + bumpPile(color) { + const pile = this.piles.find((p) => p.color === color); + if (!pile) return; + this.scene.tweens.add({ targets: pile.layers, scaleX: '*=1.08', scaleY: '*=1.08', duration: 90, yoyo: true }); + this.scene.tweens.add({ targets: [pile.badge.img], scale: { from: pile.badge.img.scale * 1.4, to: pile.badge.img.scale }, duration: 220 }); + } + + // ── tickets rail ───────────────────────────────────────────────────────────── + renderTickets(gs, ui) { + const st = L.ticketStatus(gs, 0); + const sig = JSON.stringify(st.map((t) => [t.id, t.done])) + JSON.stringify(Object.keys(gs.claimed).length); + if (sig === this._ticketSig) return; + this._ticketSig = sig; + if (this.ticketObjs.some((o) => o.t)) this.scene.tooltip?.hide(); // its owner is about to go + this.ticketObjs.forEach((o) => o.c.destroy()); + this.ticketObjs = []; + const sc = this.scene, d = this.D.hud + 1; + if (!st.length) { + const c = sc.add.container(TICKETS_RAIL.x + TICKETS_RAIL.w / 2, TICKETS_RAIL.y + TICKETS_RAIL.h / 2 - 6).setDepth(d); + c.add(sc.add.text(0, 0, 'Your destination tickets appear here', { + fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#a8c4a8', + }).setOrigin(0.5)); + this.ticketObjs.push({ c }); + return; + } + st.forEach((t, i) => { + const p = ticketMiniPos(i, st.length); + const c = this.ticketMini(t, p.x, p.y, d + i * 0.01, ui.need?.(t)); + c.setSize(TICKET_MINI.w, TICKET_MINI.h); + c.setInteractive({ useHandCursor: false }); // container hit area is centred (origin 0.5) + c.on('pointerover', () => { c.setDepth(this.D.hudTop); c.setScale(1.06); this.cb.onTicketHover?.(t); }); + c.on('pointerout', () => { c.setDepth(d + i * 0.01); c.setScale(1); this.cb.onTicketHover?.(null); }); + this.cb.tooltip?.(c, () => this.ticketTooltip(t, ui.need?.(t))); + this.ticketObjs.push({ c, t }); + if (t.done && !this._stamped.has(t.id) && this._seededStamps) { + this._stamped.add(t.id); + this.stampAnim(c); + } else if (t.done) this._stamped.add(t.id); + }); + this._seededStamps = true; + } + + // A ticket face at any scale (mini on the rail, large in the chooser). + ticketMini(t, x, y, depth, need, scale = TICKET_MINI.w / TICKET_TEX.w) { + const sc = this.scene; + const c = sc.add.container(x, y).setDepth(depth); + const W0 = TICKET_TEX.w, H0 = TICKET_TEX.h; + const img = sc.add.image(0, 0, 'ttr-ticket').setDisplaySize(W0 * scale, H0 * scale); + const k = scale; + const left = -W0 / 2 * k, stubX = (W0 / 2 - 31) * k; + const a = CITIES[t.a].name, b = CITIES[t.b].name; + const mainW = (W0 - 62 - 20) * k; + const fit = (txt) => { if (txt.width > mainW) txt.setScale(mainW / txt.width); return txt; }; + const l1 = fit(sc.add.text(left + 12 * k, -12 * k, a, { + fontFamily: SERIF, fontSize: `${Math.round(30 * k)}px`, fontStyle: 'bold', color: INK, + }).setOrigin(0, 0.5)); + const l2 = fit(sc.add.text(left + 12 * k, 22 * k, `→ ${b}`, { + fontFamily: SERIF, fontSize: `${Math.round(30 * k)}px`, fontStyle: 'bold', color: INK, + }).setOrigin(0, 0.5)); + const pts = sc.add.text(stubX, -14 * k, String(t.points), { + fontFamily: 'Righteous', fontSize: `${Math.round(40 * k)}px`, color: '#7a2a1a', + }).setOrigin(0.5); + const objs = [img, l1, l2, pts]; + if (need != null && !t.done) { + const txt = need === Infinity ? 'blocked!' : `${need} more`; + objs.push(sc.add.text(left + 12 * k, 50 * k, txt, { + fontFamily: SERIF, fontSize: `${Math.round(20 * k)}px`, fontStyle: 'italic', color: need === Infinity ? '#b0281a' : '#6b4a2a', + }).setOrigin(0, 0.5)); + } + if (t.done) objs.push(...this.doneStamp(stubX - 64 * k, 0, k)); + c.add(objs); + return c; + } + + doneStamp(x, y, k) { + const sc = this.scene; + const g = sc.add.graphics({ x, y }); + g.lineStyle(3 * k * 1.6, 0x2f7a3a, 0.85).strokeCircle(0, 0, 26 * k * 1.3); + g.lineStyle(1.5 * k * 1.6, 0x2f7a3a, 0.85).strokeCircle(0, 0, 21 * k * 1.3); + const t = sc.add.text(x, y, '✓', { fontFamily: 'Righteous', fontSize: `${Math.round(40 * k * 1.3)}px`, color: '#2f7a3a' }).setOrigin(0.5); + g.setAngle(-14); t.setAngle(-14); + g.isStamp = t.isStamp = true; + return [g, t]; + } + + stampAnim(c) { + const stamps = c.list.filter((o) => o.isStamp); + stamps.forEach((o) => { + const s = o.scale; + o.setScale(s * 2.6).setAlpha(0); + this.scene.tweens.add({ targets: o, scale: s, alpha: 1, duration: 260, ease: 'Back.easeIn' }); + }); + this.scene.tweens.add({ targets: c, angle: { from: -3, to: 0 }, duration: 300, delay: 240, ease: 'Bounce.easeOut' }); + } + + ticketTooltip(t, need) { + const lines = [{ text: `${t.points} points — ${t.done ? 'completed!' : 'lost at the end if unfinished'}`, color: t.done ? '#7fd88a' : COLORS.textHex }]; + if (!t.done && need != null) { + lines.push({ text: need === Infinity ? 'No open path left — this ticket can no longer be completed.' : `Cheapest open path needs ${need} more train${need === 1 ? '' : 's'}.`, color: need === Infinity ? COLORS.dangerHex : COLORS.mutedHex }); + } + lines.push({ text: 'The path is shown on the map.', color: COLORS.mutedHex }); + return { title: `${CITIES[t.a].name} → ${CITIES[t.b].name}`, lines }; + } + + ticketMiniPos(id) { + const o = this.ticketObjs.find((x) => x.t?.id === id); + return o ? { x: o.c.x, y: o.c.y } : { x: TICKETS_RAIL.x + TICKETS_RAIL.w / 2, y: TICKETS_RAIL.y + TICKETS_RAIL.h / 2 }; + } + + // ── plaques: anchors + captions ────────────────────────────────────────────── + oppAnchor(seat) { + const r = oppRect(seat - 1); + return { x: r.x + r.w / 2 + 30, y: r.y + r.h / 2 + 6 }; + } + + caption(seat, text, hold = 1600) { + const pq = this.plaques[seat]; + if (!pq) return; + pq.captionTween?.remove(); + pq.caption.setText(text).setAlpha(1); + pq.captionTween = this.scene.tweens.add({ targets: pq.caption, alpha: 0, delay: hold, duration: 400 }); + } + + setScoreText(seat, v) { + if (seat === 0) this.humanScore.setText(String(v)); + else this.plaques[seat]?.score.setText(String(v)); + } + + hidePortraits() { this.portraits.forEach((p) => p?.hide?.()); } + showPortraits() { this.portraits.forEach((p) => p?.show?.()); } + emote(seat, e) { this.portraits[seat]?.playEmotion?.(e); } +} diff --git a/src/games/tickettoride/TicketToRideLayout.js b/src/games/tickettoride/TicketToRideLayout.js new file mode 100644 index 0000000..f06c43c --- /dev/null +++ b/src/games/tickettoride/TicketToRideLayout.js @@ -0,0 +1,142 @@ +// TicketToRideLayout.js — every screen rect for the Ticket to Ride table. +// Phaser-free so tools/verifyTicketToRide.js can check on-screen + overlaps. +// +// ┌──────────────── map sheet (parchment, score track border) ─┬─ desk pad ──┐ +// │ │ buttons │ +// │ cities / routes in canvas coords │ opponents │ +// │ │ card rack │ +// │ │ piles │ +// │ │ longest/log │ +// ├──────── bottom rail: portrait · info · hand piles · tickets · actions ───┤ + +export const W = 1920, H = 1080; + +// The parchment map. City/route coordinates (TicketToRideBoard) are absolute +// canvas coords that sit inside this sheet. +export const SHEET = { x: 8, y: 6, w: 1456, h: 906 }; +export const TRACK = { inset: 10, band: 26 }; // score-track band inside the sheet edge +export const TRACK_SQUARES = 100; + +// Right-hand desk pad. +export const PAD = { x: 1474, y: 6, w: 438, h: 906 }; +export const TOPBAR = { x: 1486, y: 16, w: 414, h: 42 }; +export const MENU_BTN = { x: 1486, y: 16, w: 130, h: 42 }; +export const LOG_BTN = { x: 1626, y: 16, w: 130, h: 42 }; +export const HELP_BTN = { x: 1766, y: 16, w: 134, h: 42 }; + +// Opponent plaques: up to 4 in a 2×2 grid. +export const OPP = { x0: 1484, y0: 68, w: 206, h: 116, gapX: 12, gapY: 10 }; +export function oppRect(i) { + const col = i % 2, row = Math.floor(i / 2); + return { x: OPP.x0 + col * (OPP.w + OPP.gapX), y: OPP.y0 + row * (OPP.h + OPP.gapY), w: OPP.w, h: OPP.h }; +} +export function oppRects(n) { return Array.from({ length: n }, (_, i) => oppRect(i)); } + +// Face-up market: a wooden rack holding 5 upright cards. +export const CARD = { w: 74, h: 106 }; // table-size card (sheet frames are 270×390) +export const RACK = { x: 1484, y: 322, w: 418, h: 150 }; +export const MARKET_Y = 392; +export function marketPos(i) { return { x: RACK.x + 46 + i * 81.5, y: MARKET_Y }; } + +// Draw pile, discard, destination-ticket box. +export const PILES_Y = 560; +export const DECK = { x: 1548, y: PILES_Y }; +export const DISCARD = { x: 1664, y: PILES_Y }; +export const TICKET_BOX = { x: 1806, y: PILES_Y, w: 124, h: 76 }; +export const PILES = { x: 1484, y: 486, w: 418, h: 150 }; +export const DRAW_PIPS = { x: 1548, y: 636 }; + +// Longest-route tracker + dispatch log notepad. +export const LONGEST = { x: 1484, y: 650, w: 418, h: 52 }; +export const NOTEPAD = { x: 1484, y: 712, w: 418, h: 190 }; + +// Bottom rail. +export const RAIL = { x: 0, y: 916, w: 1920, h: 164 }; +export const PORTRAIT = { x: 66, y: 990, r: 42 }; +export const HUMAN_INFO = { x: 120, y: 928, w: 178, h: 140 }; +export const HAND = { x: 306, y: 924, w: 846, h: 150 }; +export const HAND_CARD = { w: 80, h: 115 }; +export function handPilePos(i) { return { x: HAND.x + 47 + i * 94, y: HAND.y + 82 }; } +export const TICKETS_RAIL = { x: 1164, y: 924, w: 584, h: 150 }; +export const TICKET_MINI = { w: 136, h: 66 }; +export function ticketMiniPos(i, n) { + const perRow = Math.max(4, Math.ceil(n / 2)); + const row = Math.floor(i / perRow), col = i % perRow; + const span = TICKETS_RAIL.w - TICKET_MINI.w - 8; + const step = perRow > 1 ? Math.min(TICKET_MINI.w + 8, span / (perRow - 1)) : 0; + return { + x: TICKETS_RAIL.x + 4 + TICKET_MINI.w / 2 + col * step, + y: TICKETS_RAIL.y + 38 + row * (TICKET_MINI.h + 10), + }; +} +export const ACTIONS = { x: 1760, y: 924, w: 150, h: 150 }; +export const ROUTES_BTN = { x: 1835, y: 958, w: 146, h: 44 }; +export const PASS_BTN = { x: 1835, y: 1032, w: 146, h: 48 }; + +// Status ribbon pinned to the top of the map (over the sea, clear of labels). +export const STATUS = { x: 736, y: 72 }; + +// ── score track ──────────────────────────────────────────────────────────────── +// Squares 0..99 run clockwise around the sheet's border band, starting at the +// top-left corner. trackPos(n) → { x, y, side } (centre of square n % 100). +const TR = { + x0: SHEET.x + TRACK.inset + TRACK.band / 2, + y0: SHEET.y + TRACK.inset + TRACK.band / 2, + x1: SHEET.x + SHEET.w - TRACK.inset - TRACK.band / 2, + y1: SHEET.y + SHEET.h - TRACK.inset - TRACK.band / 2, +}; +const TR_W = TR.x1 - TR.x0, TR_H = TR.y1 - TR.y0; +export const TRACK_PERIM = 2 * (TR_W + TR_H); +export const TRACK_STEP = TRACK_PERIM / TRACK_SQUARES; +export const TRACK_RECT = TR; + +export function trackPos(n) { + let d = (((n % TRACK_SQUARES) + TRACK_SQUARES) % TRACK_SQUARES) * TRACK_STEP; + if (d < TR_W) return { x: TR.x0 + d, y: TR.y0, side: 'top' }; + d -= TR_W; + if (d < TR_H) return { x: TR.x1, y: TR.y0 + d, side: 'right' }; + d -= TR_H; + if (d < TR_W) return { x: TR.x1 - d, y: TR.y1, side: 'bottom' }; + d -= TR_W; + return { x: TR.x0, y: TR.y1 - d, side: 'left' }; +} + +// ── helpers for verify / hit tests ───────────────────────────────────────────── +const centred = (c, w, h, name) => ({ name, x: c.x - w / 2, y: c.y - h / 2, w, h }); + +export function hudFurniture({ opponents = 3 } = {}) { + return [ + { name: 'menu', ...MENU_BTN }, + { name: 'log', ...LOG_BTN }, + { name: 'help', ...HELP_BTN }, + ...oppRects(opponents).map((r, i) => ({ name: `opp${i + 1}`, ...r })), + { name: 'rack', ...RACK }, + { name: 'piles', ...PILES }, + { name: 'longest', ...LONGEST }, + { name: 'notepad', ...NOTEPAD }, + { name: 'humanInfo', ...HUMAN_INFO }, + { name: 'hand', ...HAND }, + { name: 'tickets', ...TICKETS_RAIL }, + { name: 'actions', ...ACTIONS }, + ]; +} + +// Things that live inside a furniture rect (each must sit within its parent). +export function furnitureChildren() { + const kids = []; + for (let i = 0; i < 5; i++) kids.push({ parent: 'rack', ...centred(marketPos(i), CARD.w, CARD.h, `market${i}`) }); + kids.push({ parent: 'piles', ...centred(DECK, CARD.w, CARD.h, 'deck') }); + kids.push({ parent: 'piles', ...centred(DISCARD, CARD.w, CARD.h, 'discard') }); + kids.push({ parent: 'piles', ...centred(TICKET_BOX, TICKET_BOX.w, TICKET_BOX.h, 'ticketBox') }); + for (let i = 0; i < 9; i++) kids.push({ parent: 'hand', ...centred(handPilePos(i), HAND_CARD.w, HAND_CARD.h, `pile${i}`) }); + for (const n of [1, 4, 8, 12]) { + for (let i = 0; i < n; i++) kids.push({ parent: 'tickets', ...centred(ticketMiniPos(i, n), TICKET_MINI.w, TICKET_MINI.h, `ticket${i}/${n}`) }); + } + kids.push({ parent: 'actions', ...centred(ROUTES_BTN, ROUTES_BTN.w, ROUTES_BTN.h, 'routesBtn') }); + kids.push({ parent: 'actions', ...centred(PASS_BTN, PASS_BTN.w, PASS_BTN.h, 'passBtn') }); + return kids; +} + +export const onScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H; +export const rectsOverlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; +export const inside = (k, p) => k.x >= p.x - 0.5 && k.y >= p.y - 0.5 && k.x + k.w <= p.x + p.w + 0.5 && k.y + k.h <= p.y + p.h + 0.5; diff --git a/src/games/tickettoride/TicketToRideLogic.js b/src/games/tickettoride/TicketToRideLogic.js index 6db2f69..1b5c000 100644 --- a/src/games/tickettoride/TicketToRideLogic.js +++ b/src/games/tickettoride/TicketToRideLogic.js @@ -31,9 +31,20 @@ export function handCount(player) { return player.hand.locomotive + TRAIN_COLORS.reduce((s, c) => s + player.hand[c], 0); } +// The log keeps a long history (the scene's log drawer scrolls it); each entry +// is a plain string so older saves/tools that read `s.log` keep working. +export const LOG_LIMIT = 120; function logEvent(s, msg) { s.log.push(msg); - if (s.log.length > 12) s.log.shift(); + if (s.log.length > LOG_LIMIT) s.log.shift(); +} + +function emptyStats() { + return { + deckDraws: 0, faceUpDraws: 0, locosDrawn: 0, faceUpLocos: 0, + ticketDraws: 0, ticketsKept: 0, ticketsReturned: 0, + routesClaimed: 0, trainsPlaced: 0, locosSpent: 0, longestClaim: 0, passes: 0, + }; } // ── deck helpers (mutate working state) ────────────────────────────────────── @@ -64,12 +75,22 @@ function _refillFaceUp(s) { if (locos >= 3 && s.faceUp.length === FACE_UP_COUNT && available > FACE_UP_COUNT) { s.discard.push(...s.faceUp); s.faceUp = []; + s.marketWipes = (s.marketWipes ?? 0) + 1; // the scene animates the sweep + logEvent(s, 'Three locomotives face-up — the market is swept and re-dealt.'); continue; } break; } while (++guard < 10); } +// Take face-up card `index`: the replacement goes into the same slot so the +// market doesn't shuffle sideways (the 3-loco check runs in _refillFaceUp). +function _replaceFaceUp(s, index) { + const repl = _drawFromDeck(s); + if (repl != null) s.faceUp[index] = repl; + else s.faceUp.splice(index, 1); +} + // ── ticket dealing ──────────────────────────────────────────────────────────── function _dealTicketsToSeat(s, seat, count, minKeep, context) { const drawn = []; @@ -99,6 +120,9 @@ export function createInitialState(playerCount = 4) { winner: null, scores: null, log: [], + turn: 0, // completed turns (all seats) + marketWipes: 0, // bumps each 3-locomotive sweep + passStreak: 0, // consecutive forced passes (stall guard) }; for (let seat = 0; seat < n; seat++) { @@ -116,6 +140,7 @@ export function createInitialState(playerCount = 4) { tickets: [], trainsLeft: TRAINS_PER_PLAYER, routes: [], + stats: emptyStats(), }); } @@ -142,6 +167,8 @@ export function resolveTicketKeep(state, seat, keepIds) { for (const id of keep) s.players[seat].tickets.push({ ...TICKETS[id] }); s.ticketDeck.push(...discardIds); // returned to the bottom + const st = s.players[seat].stats; + if (st) { st.ticketsKept += keep.length; st.ticketsReturned += discardIds.length; } logEvent(s, `${playerName(s, seat)} kept ${keep.length} ticket${keep.length === 1 ? '' : 's'}.`); const wasSetup = pend.context === 'setup'; @@ -167,6 +194,50 @@ export function canDrawTrains(s) { return s.trainDeck.length + s.discard.length + s.faceUp.length > 0; } +// The blind draw pile is usable (the discard reshuffles into it when empty). +export function canDrawFromDeck(s) { + return s.trainDeck.length + s.discard.length > 0; +} + +// Face-up indices the current player may take right now (a face-up locomotive +// only as the first draw of the turn). +export function legalFaceUp(s) { + const out = []; + s.faceUp.forEach((c, i) => { if (c !== 'locomotive' || s.drawnThisTurn === 0) out.push(i); }); + return out; +} + +// Everything `seat` may legally do right now. `any` is false only when the +// player is completely stuck — then (and only then) passTurn() is allowed. +export function legalActions(s, seat) { + const none = { claims: [], deck: false, faceUp: [], tickets: false, any: false }; + if (!_isTurnPhase(s) || s.currentPlayer !== seat || s.pendingTickets || s.winner != null) return none; + const claims = legalClaims(s, seat); + const deck = canDrawFromDeck(s); + const faceUp = legalFaceUp(s); + const tickets = s.drawnThisTurn === 0 && canDrawTickets(s); + return { claims, deck, faceUp, tickets, any: claims.length > 0 || deck || faceUp.length > 0 || tickets }; +} + +// Forced pass: only when the player has no legal action at all (e.g. the deck +// and discard are exhausted, or the 2nd draw finds only face-up locomotives). +// If every seat in turn is forced to pass, the game can never progress, so it +// is scored as it stands. +export function passTurn(state, seat) { + const s = cloneState(state); + if (!_isTurnPhase(s) || s.currentPlayer !== seat || s.pendingTickets) return s; + if (legalActions(s, seat).any) return s; + s.players[seat].stats && s.players[seat].stats.passes++; + logEvent(s, `${playerName(s, seat)} has no move and passes.`); + // A pass after a first draw still made progress (a card was taken). + s.passStreak = s.drawnThisTurn > 0 ? 0 : (s.passStreak ?? 0) + 1; + if (s.passStreak >= s.playerCount) { + logEvent(s, 'Nobody can move — the line is closed and the game is scored.'); + return _finalize(s); + } + return _endTurn(s, { passed: s.drawnThisTurn === 0 }); +} + // source: 'deck' or 'faceUp'; index used only for 'faceUp'. export function drawTrainCard(state, seat, source, index = 0) { const s = cloneState(state); @@ -179,23 +250,28 @@ export function drawTrainCard(state, seat, source, index = 0) { if (card === 'locomotive') { // A face-up locomotive may only be taken as the first draw; it ends the turn. if (s.drawnThisTurn !== 0) return s; - s.faceUp.splice(index, 1); + _replaceFaceUp(s, index); s.players[seat].hand.locomotive++; s.drewLocoFaceUp = true; + _stat(s, seat, 'faceUpDraws'); _stat(s, seat, 'locosDrawn'); _stat(s, seat, 'faceUpLocos'); _refillFaceUp(s); logEvent(s, `${playerName(s, seat)} drew a locomotive.`); return _endTurn(s); } - s.faceUp.splice(index, 1); + _replaceFaceUp(s, index); s.players[seat].hand[card]++; s.drawnThisTurn++; + _stat(s, seat, 'faceUpDraws'); _refillFaceUp(s); - logEvent(s, `${playerName(s, seat)} drew a face-up card.`); + logEvent(s, `${playerName(s, seat)} took a face-up ${card}.`); } else { const card = _drawFromDeck(s); if (card == null) return s; s.players[seat].hand[card]++; s.drawnThisTurn++; + _stat(s, seat, 'deckDraws'); + if (card === 'locomotive') _stat(s, seat, 'locosDrawn'); + s.lastDeckCard = card; // the scene reads this for the flip logEvent(s, `${playerName(s, seat)} drew from the deck.`); } @@ -252,6 +328,24 @@ export function routeClaimable(s, seat, routeId) { return true; } +// Human-readable reason `seat` can't claim `routeId` (ignoring the hand), or +// null when it is open to them. Drives the route-hover tooltip. +export function routeLockReason(s, seat, routeId) { + const owner = s.claimed[routeId]; + if (owner != null) return owner === seat ? 'You own this route' : `Claimed by ${playerName(s, owner)}`; + const route = ROUTES[routeId]; + if (route.doubleGroup) { + for (const r of ROUTES) { + if (r.id === routeId || r.doubleGroup !== route.doubleGroup) continue; + const o = s.claimed[r.id]; + if (o === seat) return 'You already own the parallel track'; + if (o != null && s.playerCount < 4) return 'Double track closes once one side is taken (2–3 players)'; + } + } + if (s.players[seat].trainsLeft < route.length) return `Needs ${route.length} trains — you have ${s.players[seat].trainsLeft}`; + return null; +} + // Every route `seat` can claim now, with its default payment. export function legalClaims(s, seat) { if (!_isTurnPhase(s) || s.currentPlayer !== seat || s.pendingTickets || s.drawnThisTurn > 0) return []; @@ -296,6 +390,12 @@ export function claimRoute(state, seat, routeId, payment = null) { player.trainsLeft -= route.length; player.routes.push(routeId); s.claimed[routeId] = seat; + if (player.stats) { + player.stats.routesClaimed++; + player.stats.trainsPlaced += route.length; + player.stats.locosSpent += pay.locos; + player.stats.longestClaim = Math.max(player.stats.longestClaim, route.length); + } logEvent(s, `${playerName(s, seat)} claimed ${CITIES[route.a].name}–${CITIES[route.b].name} (+${ROUTE_SCORE[route.length]}).`); return _endTurn(s); } @@ -311,6 +411,7 @@ export function drawTickets(state, seat) { if (s.drawnThisTurn > 0) return s; // a full action only if (s.ticketDeck.length === 0) return s; _dealTicketsToSeat(s, seat, 3, 1, 'turn'); + _stat(s, seat, 'ticketDraws'); logEvent(s, `${playerName(s, seat)} is drawing tickets…`); return s; } @@ -320,9 +421,16 @@ function _isTurnPhase(s) { return s.phase === 'turn' || s.phase === 'lastRound'; } +function _stat(s, seat, key, n = 1) { + const st = s.players[seat].stats; + if (st) st[key] = (st[key] ?? 0) + n; +} + // Apply end-of-turn: end-game trigger, last-round countdown, hand off to next. -function _endTurn(s) { +function _endTurn(s, { passed = false } = {}) { const finishing = s.currentPlayer; + if (!passed) s.passStreak = 0; + s.turn = (s.turn ?? 0) + 1; const wasTriggeredBefore = s.endTriggered; if (!s.endTriggered && s.players[finishing].trainsLeft <= ENDGAME_TRAIN_THRESHOLD) { @@ -374,7 +482,13 @@ export function ticketScore(s, seat) { // Longest continuous path (trail): each claimed route used at most once, maximise // total train length. Per-player subgraphs are tiny, so exhaustive DFS is fine. export function longestPathFor(s, seat) { - const inc = new Map(); // cityId -> [{ routeId, other, len }] + return longestTrail(s, seat).length; +} + +// The best trail itself: { length, routes: [routeId…] in travel order, +// cities: [cityId…] (routes.length + 1 entries, or [] when no routes) }. +export function longestTrail(s, seat) { + const inc = new Map(); for (const rid of s.players[seat].routes) { const r = ROUTES[rid]; if (!inc.has(r.a)) inc.set(r.a, []); @@ -382,22 +496,38 @@ export function longestPathFor(s, seat) { inc.get(r.a).push({ routeId: rid, other: r.b, len: r.length }); inc.get(r.b).push({ routeId: rid, other: r.a, len: r.length }); } - let best = 0; + let best = { length: 0, routes: [], cities: [] }; let steps = 0; - const dfs = (node, used, total) => { - if (total > best) best = total; - if (++steps > 200000) return; // defensive guard + const pathR = [], pathC = []; + const used = new Set(); + const dfs = (node, total) => { + if (total > best.length) best = { length: total, routes: [...pathR], cities: [...pathC] }; + if (++steps > 200000) return; for (const e of inc.get(node) || []) { if (used.has(e.routeId)) continue; - used.add(e.routeId); - dfs(e.other, used, total + e.len); - used.delete(e.routeId); + used.add(e.routeId); pathR.push(e.routeId); pathC.push(e.other); + dfs(e.other, total + e.len); + used.delete(e.routeId); pathR.pop(); pathC.pop(); } }; - for (const node of inc.keys()) dfs(node, new Set(), 0); + for (const node of inc.keys()) { pathC.length = 0; pathC.push(node); dfs(node, 0); } return best; } +// Which seats currently hold (or share) the longest trail, and its length. +export function longestLeaders(s) { + const lens = s.players.map((p) => longestPathFor(s, p.seat)); + const max = Math.max(0, ...lens); + return { length: max, seats: max > 0 ? lens.map((l, i) => (l === max ? i : -1)).filter((i) => i >= 0) : [], lens }; +} + +// Per-ticket completion for a seat (union-find over its routes). +export function ticketStatus(s, seat) { + const uf = new UnionFind(CITIES.length); + for (const rid of s.players[seat].routes) { const r = ROUTES[rid]; uf.union(r.a, r.b); } + return s.players[seat].tickets.map((t) => ({ ...t, done: uf.find(t.a) === uf.find(t.b) && t.a !== t.b })); +} + // Compute final scores and decide the winner. Mutates+returns the working state. function _finalize(s) { const longest = s.players.map((p) => longestPathFor(s, p.seat)); @@ -411,6 +541,9 @@ function _finalize(s) { routePoints: rp, ticketPoints: ts.points, ticketsCompleted: ts.completed, + ticketsFailed: p.tickets.length - ts.completed, + tickets: ticketStatus(s, p.seat), + longestRoutes: longestTrail(s, p.seat).routes, longestPath: longest[p.seat], longestBonus, total: rp + ts.points + longestBonus, diff --git a/src/games/tickettoride/TicketToRideSound.js b/src/games/tickettoride/TicketToRideSound.js new file mode 100644 index 0000000..1b78851 --- /dev/null +++ b/src/games/tickettoride/TicketToRideSound.js @@ -0,0 +1,77 @@ +// TicketToRideSound.js — two tiny Web Audio synths for the railroad: a steam +// whistle (three-note chord with a breathy noise band) and a soft chuff. No +// audio files; silently does nothing without Web Audio or when muted. + +function ctxOf(scene) { + const sm = scene.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} + +function noiseBuffer(ac, secs) { + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * secs), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + return buf; +} + +// Route through Phaser's master volume/mute node when it exposes one. +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; +} + +export function whistle(scene, { dur = 1.1, vol = 0.12, pitch = 1 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const t0 = ac.currentTime + 0.01; + const master = out(scene, ac, vol); + const env = ac.createGain(); + env.gain.setValueAtTime(0, t0); + env.gain.linearRampToValueAtTime(1, t0 + 0.09); + env.gain.setValueAtTime(1, t0 + dur - 0.25); + env.gain.linearRampToValueAtTime(0, t0 + dur); + env.connect(master); + for (const f of [587.3, 740, 880]) { + const o = ac.createOscillator(); + o.type = 'triangle'; + o.frequency.setValueAtTime(f * pitch * 0.96, t0); + o.frequency.linearRampToValueAtTime(f * pitch, t0 + 0.12); + const vib = ac.createOscillator(); const vg = ac.createGain(); + vib.frequency.value = 5.5; vg.gain.value = f * 0.004; + vib.connect(vg); vg.connect(o.frequency); + const og = ac.createGain(); og.gain.value = 0.3; + o.connect(og); og.connect(env); + o.start(t0); o.stop(t0 + dur + 0.05); + vib.start(t0); vib.stop(t0 + dur + 0.05); + } + const n = ac.createBufferSource(); + n.buffer = noiseBuffer(ac, dur); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 1500 * pitch; bp.Q.value = 1.2; + const ng = ac.createGain(); ng.gain.value = 0.18; + n.connect(bp); bp.connect(ng); ng.connect(env); + n.start(t0); n.stop(t0 + dur); + } catch (_) { /* audio is decoration */ } +} + +export function chuff(scene, { vol = 0.05 } = {}) { + const ac = ctxOf(scene); + if (!ac) return; + try { + const t0 = ac.currentTime + 0.005; + const n = ac.createBufferSource(); + n.buffer = noiseBuffer(ac, 0.16); + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 900; + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(1, t0 + 0.015); + g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.15); + n.connect(lp); lp.connect(g); g.connect(out(scene, ac, vol)); + n.start(t0); n.stop(t0 + 0.16); + } catch (_) { /* audio is decoration */ } +} diff --git a/src/games/tickettoride/tutorial.md b/src/games/tickettoride/tutorial.md index 680afda..f59a3d2 100644 --- a/src/games/tickettoride/tutorial.md +++ b/src/games/tickettoride/tutorial.md @@ -134,6 +134,28 @@ The highest score wins. --- +## At This Table: Instruments of the Station Master + +This table has been furnished with a few conveniences. I approve of them. + +- **Hover a route** to see its length, its colour, the points it is worth, and whether your hand can pay for it. If you cannot claim it, you will be told why: a closed double track, too few trains, or the turn you have already spent drawing cards. +- **Hover a pile of cards in your hand** and every route that colour could pay for lights up on the map. The routes you could claim right now light up brightest. +- **Hover one of your tickets** on the rail at the bottom. Its two cities glow, and so does the cheapest open path between them. The ticket also tells you how many trains it still needs, or warns you if it can no longer be finished. +- **Hover an opponent's board** to see their network outlined on the map, and the **Longest Route plate** to trace the current leader's trail. +- **The Routes button** (or the **R** key) keeps every route you can claim right now glowing. +- **Keys:** + - **1–5** take a face-up card + - **D** draws from the deck + - **T** draws tickets + - **L** opens the dispatch log + - **P** passes, if no move remains at all + - **Esc** opens the Station Master's menu, where you may set how quickly your opponents move and how you pay for routes. +- **If you are ever truly stuck** (no card to draw, no route you can afford, no ticket left), a **Pass** button appears. If every player is stuck in turn, the line is closed and the game is scored. + +> *I once spent a century in a library without a catalogue. I do not recommend it. Use the instruments.* + +--- + ## A Final Word This game is, at its heart, about committing to a destination and building the path to reach it — despite obstacles, despite rivals, despite the slow drain of resources and opportunity. diff --git a/src/scenes/OpponentSelectScene.js b/src/scenes/OpponentSelectScene.js index f6c01cd..662338e 100644 --- a/src/scenes/OpponentSelectScene.js +++ b/src/scenes/OpponentSelectScene.js @@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene { // Skill control: pips always show the level; the +/- buttons appear only // when this opponent is selected. Enabled for games with a 1–5 AI skill. - if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg'].includes(this.gameDef.slug)) { + if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride'].includes(this.gameDef.slug)) { bio.style.webkitLineClamp = '1'; const skillRow = document.createElement('div'); diff --git a/src/ui/MusicPlayer.js b/src/ui/MusicPlayer.js index 32c98e7..3bee18d 100644 --- a/src/ui/MusicPlayer.js +++ b/src/ui/MusicPlayer.js @@ -16,8 +16,12 @@ function shuffle(arr) { } export class MusicPlayer { - constructor(scene, tracks, volume = 0.15) { + // opts (all optional) place the controls somewhere other than the screen's + // top-right corner: { right, top } is the corner they hang from, and + // infoColor tints the "artist — title" line (e.g. dark ink on a light map). + constructor(scene, tracks, volume = 0.15, opts = {}) { this.scene = scene; + this.opts = { right: GAME_WIDTH, top: 0, infoColor: COLORS.mutedHex, ...opts }; this.tracks = shuffle(tracks); this.idx = 0; this.muted = false; @@ -34,10 +38,11 @@ export class MusicPlayer { _buildUI() { const s = this.scene; - const muteX = GAME_WIDTH - PAD - BTN / 2; + const { right, top, infoColor } = this.opts; + const muteX = right - PAD - BTN / 2; const skipX = muteX - GAP - BTN; - const btnY = PAD + BTN / 2; - const infoY = PAD + BTN + GAP + 8; + const btnY = top + PAD + BTN / 2; + const infoY = top + PAD + BTN + GAP + 8; this._muteX = muteX; this._muteY = btnY; @@ -74,8 +79,8 @@ export class MusicPlayer { this._muteLine = s.add.graphics().setDepth(DEPTH + 2); - this._infoText = s.add.text(GAME_WIDTH - PAD, infoY, '', { - fontFamily: 'Righteous', fontSize: '13px', color: COLORS.mutedHex, + this._infoText = s.add.text(right - PAD, infoY, '', { + fontFamily: 'Righteous', fontSize: '13px', color: infoColor, }).setOrigin(1, 0).setDepth(DEPTH); this._objs.push(skipBg, skipIcon, muteBg, this._muteIcon, this._muteLine, this._infoText); diff --git a/src/ui/dice/Dice3D.js b/src/ui/dice/Dice3D.js new file mode 100644 index 0000000..77089e6 --- /dev/null +++ b/src/ui/dice/Dice3D.js @@ -0,0 +1,339 @@ +// Shared 3D dice — true cubes drawn live on a Phaser Graphics, plus a +// physics-lite boxed throw. +// +// Fairness: the result is decided by the game RNG first. A throw is simulated +// with a canonical die, snapped flat, and then the die is *relabelled* (a fixed +// cube rotation in its own frame) so the face that ends on top carries the +// rolled number. The animation agrees with the outcome; it never decides it. +// +// Everything except the Die3D Graphics objects is Phaser-free, so throws can be +// verified under Node. Craps (src/games/craps/CrapsDice.js) adapts this module +// with its own table projection and wall physics; Catan uses planTrayThrow(). + +// ── Faces ──────────────────────────────────────────────────────────────────── +// Local face normals and the pips on them (opposite faces add to 7). +export const FACES = [ + { n: [0, 0, 1], label: 1, e1: [1, 0, 0], e2: [0, 1, 0] }, + { n: [0, 0, -1], label: 6, e1: [1, 0, 0], e2: [0, -1, 0] }, + { n: [0, 1, 0], label: 2, e1: [1, 0, 0], e2: [0, 0, 1] }, + { n: [0, -1, 0], label: 5, e1: [-1, 0, 0], e2: [0, 0, 1] }, + { n: [1, 0, 0], label: 3, e1: [0, 1, 0], e2: [0, 0, 1] }, + { n: [-1, 0, 0], label: 4, e1: [0, -1, 0], e2: [0, 0, 1] }, +]; +export 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]], +}; + +// ── Vector / quaternion helpers ────────────────────────────────────────────── +export function norm(v) { const l = Math.hypot(...v) || 1; return v.map(x => x / l); } +export const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +export const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + +export function qmul(a, b) { + return [ + a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2], + a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1], + a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0], + ]; +} +export function qnorm(q) { const l = Math.hypot(...q) || 1; return q.map(x => x / l); } +export function qaxis(axis, ang) { + const a = norm(axis), s = Math.sin(ang / 2); + return [Math.cos(ang / 2), a[0] * s, a[1] * s, a[2] * s]; +} +export function qrot(q, v) { + const [w, x, y, z] = q; + const ix = w * v[0] + y * v[2] - z * v[1]; + const iy = w * v[1] + z * v[0] - x * v[2]; + const iz = w * v[2] + x * v[1] - y * v[0]; + const iw = -x * v[0] - y * v[1] - z * v[2]; + return [ + ix * w + iw * -x + iy * -z - iz * -y, + iy * w + iw * -y + iz * -x - ix * -z, + iz * w + iw * -z + ix * -y - iy * -x, + ]; +} +export function qslerp(a, b, t) { + let d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + if (d < 0) { b = b.map(x => -x); d = -d; } + if (d > 0.9995) return qnorm(a.map((x, i) => x + (b[i] - x) * t)); + const th = Math.acos(d), s = Math.sin(th); + const wa = Math.sin((1 - t) * th) / s, wb = Math.sin(t * th) / s; + return a.map((x, i) => x * wa + b[i] * wb); +} +export function randomQ(rng) { + const u1 = rng(), u2 = rng(), u3 = rng(); + return [ + Math.sqrt(1 - u1) * Math.sin(2 * Math.PI * u2), Math.sqrt(1 - u1) * Math.cos(2 * Math.PI * u2), + Math.sqrt(u1) * Math.sin(2 * Math.PI * u3), Math.sqrt(u1) * Math.cos(2 * Math.PI * u3), + ]; +} + +// Rotate q so the local axis nearest world-up points exactly up (keeps the yaw). +export function snapFlat(q) { + let best = null; + for (const f of FACES) { + const w = qrot(q, f.n); + if (!best || w[2] > best.w[2]) best = { w, f }; + } + const up = [0, 0, 1]; + const ax = cross(best.w, up); + const l = Math.hypot(...ax); + if (l < 1e-9) return q; + return qnorm(qmul(qaxis(ax, Math.acos(Math.min(1, dot(best.w, up)))), q)); +} + +// The label on top for an orientation. +export function topFace(q) { + let best = null; + for (const f of FACES) { + const z = qrot(q, f.n)[2]; + if (!best || z > best.z) best = { z, label: f.label }; + } + return best.label; +} + +// Cube rotation (die frame) that moves the face labelled `target` onto local axis `a`. +export function relabel(target, a) { + const t = FACES.find(f => f.label === target).n; + const d = dot(t, a); + if (d > 0.999) return [1, 0, 0, 0]; + if (d < -0.999) { + const perp = Math.abs(t[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + return qaxis(cross(t, perp), Math.PI); + } + return qaxis(cross(t, a), Math.PI / 2); +} + +// Relabel a finished flight so its last frame shows `face` on top. Mutates and +// returns the flight ({ frames, q }). +export function relabelFlight(flight, face) { + const q = flight.q; + const up = qrot([q[0], -q[1], -q[2], -q[3]], [0, 0, 1]).map(Math.round); + const Q = relabel(face, up); + flight.Q = Q; + flight.frames = flight.frames.map(f => ({ ...f, q: qmul(f.q, Q) })); + flight.top = topFace(flight.frames[flight.frames.length - 1].q); + return flight; +} + +// A resting orientation showing `face` on top with a given yaw. +export function restingQ(face, yaw = 0) { + const base = relabel(face, [0, 0, 1]); + return qmul(qaxis([0, 0, 1], yaw), base); +} + +// Interpolated pose from a planned throw. `progress` 0…1 drives the frames. +export function poseFromPlan(plan, i, progress) { + const fr = plan.dice[i].frames; + const f = Math.min(fr.length - 1, Math.max(0, progress * (fr.length - 1))); + const a = fr[Math.floor(f)], b = fr[Math.ceil(f)]; + const t = f - Math.floor(f); + return { + u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t, h: a.h + (b.h - a.h) * t, + q: t < 0.5 ? a.q : b.q, + }; +} + +// ── Boxed tray throw (Catan and any future tray game) ──────────────────────── +// tray: { w, h } in px (the felt well, origin at its top-left), u/v returned in +// px within the tray. origin: { u, v, h } in px; aim: { u, v } in px target. +const TRAY_G = 2400; +const TRAY_DT = 1 / 240; + +function flyTray(tray, size, origin, aim, rng) { + const half = size / 2; + const x0 = half + 2, x1 = tray.w - half - 2, y0 = half + 2, y1 = tray.h - half - 2; + let X = origin.u, Y = origin.v, Z = origin.h; + const dist = Math.hypot(aim.u - X, aim.v - Y); + const tf = Math.max(0.28, (dist / 900) * (0.85 + rng() * 0.3)); + let vx = (aim.u - X) / tf, vy = (aim.v - Y) / tf; + const zArrive = 10 + rng() * 25; + let vz = (zArrive - Z + 0.5 * TRAY_G * tf * tf) / tf; + let q = randomQ(rng); + let w = norm([rng() - 0.5, rng() - 0.5, rng() - 0.5]).map(x => x * (16 + rng() * 12)); + const frames = []; + let t = 0, grounded = false, bounces = 0, step = 0, hitWall = false; + const push = () => frames.push({ u: X, v: Y, h: Z, q }); + push(); + while (t < 3) { + vz -= grounded ? 0 : TRAY_G * TRAY_DT; + X += vx * TRAY_DT; Y += vy * TRAY_DT; Z += vz * TRAY_DT; + const wl = Math.hypot(...w); + if (wl > 1e-6) q = qnorm(qmul(qaxis(w, wl * TRAY_DT), q)); + if (Z <= 0 && !grounded) { + Z = 0; + bounces++; + if (bounces >= 3 || Math.abs(vz) < 120) { vz = 0; grounded = true; } + else { + vz = -vz * 0.38; + vx *= 0.72; vy *= 0.72; + w = w.map(x => x * 0.6 + (rng() - 0.5) * 14); + } + } + if (grounded) { + Z = 0; + const sp = Math.hypot(vx, vy); + const dec = Math.min(sp, 1500 * TRAY_DT); + if (sp > 0) { vx -= (vx / sp) * dec; vy -= (vy / sp) * dec; } + w = w.map(x => x * 0.96); + } + // the tray's four walls (only once the die has dropped inside the rim) + if (Z < 40) { + if (X <= x0) { X = x0; vx = Math.abs(vx) * 0.45; hitWall = true; w = w.map(x => x * 0.7 + (rng() - 0.5) * 10); } + if (X >= x1) { X = x1; vx = -Math.abs(vx) * 0.45; hitWall = true; w = w.map(x => x * 0.7 + (rng() - 0.5) * 10); } + if (Y <= y0) { Y = y0; vy = Math.abs(vy) * 0.45; hitWall = true; } + if (Y >= y1) { Y = y1; vy = -Math.abs(vy) * 0.45; hitWall = true; } + } + t += TRAY_DT; + if (++step % 2 === 0) push(); + if (grounded && Math.hypot(vx, vy) < 14 && Math.hypot(...w) < 4) break; + } + // settle flat over ~0.16 s with a little slide + const q0 = q, qf = snapFlat(q); + const n = 20; + for (let i = 1; i <= n; i++) { + const k = i / n, e = 1 - (1 - k) * (1 - k); + X = Math.min(x1, Math.max(x0, X + vx * TRAY_DT * 2 * (1 - k))); + Y = Math.min(y1, Math.max(y0, Y + vy * TRAY_DT * 2 * (1 - k))); + frames.push({ u: X, v: Y, h: Math.sin(k * Math.PI) * 2, q: qslerp(q0, qf, e) }); + } + return { frames, u: X, v: Y, q: qf, hitWall }; +} + +// Plan a throw of both dice into a rectangular tray landing on `faces` [a, b]. +// Returns { dice: [{frames, u, v, top}], duration } — frames are at 120 fps. +export function planTrayThrow(tray, origin, faces, rng = Math.random, size = 30) { + const out = []; + for (let i = 0; i < 2; i++) { + let best = null; + for (let k = 0; k < 40; k++) { + const aim = { + u: tray.w * (0.3 + rng() * 0.4) + (i ? 1 : -1) * size * 0.9, + v: tray.h * (0.3 + rng() * 0.4), + }; + const o = { u: origin.u + (i ? 1 : -1) * size * 0.4, v: origin.v, h: origin.h }; + const fly = flyTray(tray, size, o, aim, rng); + const inside = fly.u >= size / 2 && fly.u <= tray.w - size / 2 && fly.v >= size / 2 && fly.v <= tray.h - size / 2; + const sep = i ? Math.hypot(fly.u - out[0].u, fly.v - out[0].v) : Infinity; + const okSep = sep >= size * 1.6; + const score = (inside ? 2 : 0) + (okSep ? 2 : 0); + if (!best || score > best.score) best = { ...fly, score }; + if (score === 4) break; + } + relabelFlight(best, faces[i]); + out.push(best); + } + const len = Math.max(out[0].frames.length, out[1].frames.length); + for (const d of out) while (d.frames.length < len) d.frames.push(d.frames[d.frames.length - 1]); + return { dice: out, duration: (len - 1) / 120 }; +} + +// ── Rendering ──────────────────────────────────────────────────────────────── +function shadeHex(rgb, k) { + const c = rgb.map(x => Math.max(0, Math.min(255, Math.round(x * k)))); + return (c[0] << 16) | (c[1] << 8) | c[2]; +} + +const DEFAULT_LIGHT = norm([-0.35, 0.45, 0.82]); + +// opts: +// ground(u, v) → { x, y, s } screen point on the surface under the die +// center(u, v) → { x, y, s } (optional) point used by screenCenter(); defaults to ground +// size, body [r,g,b], pip 0xRRGGBB, sin/cos camera elevation, glowColor +export class Die3D { + constructor(scene, depth, opts = {}) { + this.scene = scene; + this.opts = { + size: 30, body: [196, 28, 40], pip: 0xfdf6e6, sin: 0.7, cos: 0.71, + glowColor: 0xf5d020, light: DEFAULT_LIGHT, ...opts, + }; + this.shadow = scene.add.graphics().setDepth(depth - 0.5); + this.g = scene.add.graphics().setDepth(depth); + this.state = { u: 0, v: 0, h: 0, q: [1, 0, 0, 0] }; + this.scale = 1; + this.glow = 0; + this.visible = true; + } + + setVisible(v) { this.visible = v; this.g.setVisible(v); this.shadow.setVisible(v); return this; } + setDepth(d) { this.g.setDepth(d); this.shadow.setDepth(d - 0.5); return this; } + + set(u, v, h, q) { Object.assign(this.state, { u, v, h, q }); this.draw(); return this; } + + screenCenter() { + const { u, v, h } = this.state; + const p = (this.opts.center ?? this.opts.ground)(u, v); + const half = this.opts.size / 2; + return { x: p.x, y: p.y - (h + half) * this.opts.cos * p.s * this.scale, s: p.s }; + } + + draw() { + const g = this.g, sh = this.shadow; + g.clear(); sh.clear(); + if (!this.visible) return; + const { size, body, pip, sin: SIN_E, cos: COS_E, light } = this.opts; + const { u, v, h, q } = this.state; + const p = this.opts.ground(u, v); + const s = p.s * this.scale; + const half = size / 2; + const hc = h + half; + const proj = (w) => ({ x: p.x + s * w[0], y: p.y + s * (w[1] * SIN_E - (hc + w[2]) * COS_E) }); + + // shadow on the surface + const fade = Math.max(0.12, 0.42 - h / 500); + sh.fillStyle(0x000000, fade); + sh.fillEllipse(p.x + 4 * s + h * 0.04, p.y + 3 * s, size * 1.25 * s, size * 0.75 * s); + + if (this.glow > 0) { + g.lineStyle(3, this.opts.glowColor, this.glow); + g.strokeEllipse(p.x, p.y + 2 * s, size * 1.7 * s, size * 1.0 * s); + } + + const cam = [0, SIN_E, COS_E]; + for (const f of FACES) { + const n = qrot(q, f.n); + const facing = dot(n, cam); + if (facing <= 0.02) continue; + const e1 = qrot(q, f.e1), e2 = qrot(q, f.e2); + const c = n.map(x => x * half); + const corner = (a, b) => proj([ + c[0] + (e1[0] * a + e2[0] * b) * half, + c[1] + (e1[1] * a + e2[1] * b) * half, + c[2] + (e1[2] * a + e2[2] * b) * half, + ]); + // slightly chamfered square + const k = 0.82; + const pts = [ + corner(-k, -1), corner(k, -1), corner(1, -k), corner(1, k), + corner(k, 1), corner(-k, 1), corner(-1, k), corner(-1, -k), + ]; + const lit = 0.5 + 0.55 * Math.max(0, dot(n, light)); + g.fillStyle(shadeHex(body, lit), 0.97); + g.fillPoints(pts, true); + g.lineStyle(1, shadeHex(body, lit * 0.55), 0.9); + g.strokePoints(pts, true); + // gloss on the top-lit face + if (n[2] > 0.6) { + g.fillStyle(0xffffff, 0.08 + 0.1 * n[2]); + g.fillPoints([corner(-0.75, 0.2), corner(-0.2, 0.75), corner(-0.75, 0.75)], true); + } + // pips + const pipA = Math.min(1, facing * 2.4); + g.fillStyle(pip, 0.95 * pipA); + for (const [a, b] of PIPS[f.label]) { + const ring = []; + for (let i = 0; i < 8; i++) { + const t = (i / 8) * Math.PI * 2; + ring.push(corner(a * 0.52 + Math.cos(t) * 0.17, b * 0.52 + Math.sin(t) * 0.17)); + } + g.fillPoints(ring, true); + } + } + } + + destroy() { this.g.destroy(); this.shadow.destroy(); } +} diff --git a/tools/verifyCatan.js b/tools/verifyCatan.js new file mode 100644 index 0000000..5eb204a --- /dev/null +++ b/tools/verifyCatan.js @@ -0,0 +1,369 @@ +#!/usr/bin/env node +// verifyCatan.js — headless checks for Settlers of Catan: +// • rules: piece limits (15/5/4 + ships), Road Building capped by supply, +// the official bank-shortage rule, stats bookkeeping +// • all-AI soak (base 3p/4p + every Seafarers scenario): games end (base), +// limits never exceeded, 95 resource cards conserved, no stalls +// • 3D dice tray throws: every face pair lands on the rolled faces, inside the +// tray, separated +// • screen layout: furniture on screen, no overlaps, board hull clear of HUD +// Usage: node tools/verifyCatan.js [--quick] + +import * as L from '../src/games/catan/CatanLogic.js'; +import * as AI from '../src/games/catan/CatanAI.js'; +import { RESOURCE_TYPES, COSTS } from '../src/games/catan/CatanBoard.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { planTrayThrow, topFace, restingQ } from '../src/ui/dice/Dice3D.js'; +import { + TRAY_WORLD, TRAY_FELT, DIE_SIZE, TOTAL_CHIP, trayGround, throwOrigin, hudFurniture, onScreen, rectsOverlap, + boardFrame, RAIL, stackLayers, stackTop, caddySlot, CADDY, CADDY_CARD, handPilePos, HAND, HAND_CARD, devCardPos, DEV, +} from '../src/games/catan/CatanLayout.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}`); + +// Deterministic Math.random for reproducible soaks. +function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; } + +const total = (res) => RESOURCE_TYPES.reduce((t, r) => t + res[r], 0); +function cardsInPlay(s) { + return RESOURCE_TYPES.reduce((t, r) => t + s.bank[r], 0) + s.players.reduce((t, p) => t + total(p.resources), 0); +} + +// ── An all-AI game driver mirroring CatanGame.advance() ────────────────────── +function playGame({ players = 4, expansion = 'base', scenario = null, maxTurns = 400 } = {}) { + let s = L.createInitialState(players, { tilePlacement: 'random', expansion, scenario }); + L.setPlayerNames(s, Array.from({ length: players }, (_, i) => `P${i}`)); + const problems = []; + let turns = 0, guard = 0; + const check = () => { + if (cardsInPlay(s) !== 95) problems.push(`cards ${cardsInPlay(s)} != 95`); + for (const p of s.players) { + const left = L.piecesLeft(s, p.seat); + for (const k of ['road', 'settlement', 'city', 'ship']) if (left[k] < 0) problems.push(`seat ${p.seat} ${k} over limit`); + for (const r of RESOURCE_TYPES) if (p.resources[r] < 0) problems.push(`seat ${p.seat} negative ${r}`); + } + for (const r of RESOURCE_TYPES) if (s.bank[r] < 0) problems.push(`bank negative ${r}`); + }; + while (s.phase !== 'gameOver' && turns < maxTurns && guard++ < 200000) { + const seat = s.currentPlayer; + if (s.phase === 'setup') { + s = s.setup.placing === 'settlement' + ? L.placeSetupSettlement(s, seat, AI.chooseSetupSettlement(s, seat)) + : L.placeSetupRoad(s, seat, AI.chooseSetupRoad(s, seat)); + } else if (s.phase === 'rollPhase') { + if (AI.choosePreRoll(s, seat)) { + s = L.playKnight(s, seat); + if (s.phase === 'moveRobber') { const m = AI.chooseRobberMove(s, seat); s = L.moveRobber(s, m.hexId, m.targetSeat); } + } + if (s.phase === 'rollPhase') s = L.rollDice(s); + } else if (s.phase === 'goldPick') { + for (const e of [...s.goldPickQueue]) s = L.resolveGoldPick(s, e.seat, AI.chooseGoldPick(s, e.seat, e.amount)); + } else if (s.phase === 'discard') { + for (const d of [...s.discardQueue]) s = L.applyDiscard(s, d, AI.chooseDiscard(s, d)); + } else if (s.phase === 'moveRobber') { + const m = AI.chooseRobberMove(s, seat); + s = L.moveRobber(s, m.hexId, m.targetSeat); + } else if (s.phase === 'action') { + let steps = 0; + while (s.phase === 'action' && steps++ < 60) { + const a = AI.chooseAction(s, seat); + if (a.type === 'endTurn') { s = L.endTurn(s); break; } + const before = JSON.stringify(s.players[seat]) + s.phase; + switch (a.type) { + case 'buildCity': s = L.buildCity(s, seat, a.nodeId); break; + case 'buildSettlement': s = L.buildSettlement(s, seat, a.nodeId); break; + case 'buildRoad': s = L.buildRoad(s, seat, a.edgeId); break; + case 'buyDev': s = L.buyDevCard(s, seat); break; + case 'bankTrade': s = L.tradeWithBank(s, seat, a.give, a.get); break; + case 'playDev': + if (a.card === 'knight') s = L.playKnight(s, seat); + else if (a.card === 'roadBuilding') s = L.playRoadBuilding(s, seat); + else if (a.card === 'yearOfPlenty') s = L.playYearOfPlenty(s, seat, a.r1, a.r2); + else if (a.card === 'monopoly') s = L.playMonopoly(s, seat, a.resource); + break; + default: break; + } + if (s.phase === 'moveRobber') { const m = AI.chooseRobberMove(s, seat); s = L.moveRobber(s, m.hexId, m.targetSeat); } + check(); + if (s.phase === 'gameOver') break; + const after = JSON.stringify(s.players[seat]) + s.phase; + if (before === after && a.type !== 'playDev') { s = L.endTurn(s); break; } + } + if (s.phase === 'action') s = L.endTurn(s); + turns++; + } + check(); + if (problems.length) break; + } + return { s, turns, problems, ended: s.phase === 'gameOver' }; +} + +// ── A tiny hand-built state for rule tests ─────────────────────────────────── +function freshAction(players = 3) { + seedRandom(7); + let s = L.createInitialState(players, { tilePlacement: 'standard' }); + // run setup with the AI + while (s.phase === 'setup') { + const seat = s.currentPlayer; + s = s.setup.placing === 'settlement' + ? L.placeSetupSettlement(s, seat, AI.chooseSetupSettlement(s, seat)) + : L.placeSetupRoad(s, seat, AI.chooseSetupRoad(s, seat)); + } + s.phase = 'action'; + s.currentPlayer = 0; + return s; +} +function give(s, seat, res) { + for (const [r, n] of Object.entries(res)) { s.players[seat].resources[r] += n; s.bank[r] -= n; } +} + +// ════════════════════════════════════════════════════════════════════════════ +section('Rules — piece limits'); +{ + const s0 = freshAction(); + ok('fresh supply', JSON.stringify(L.piecesLeft(s0, 0)) === JSON.stringify({ road: 13, settlement: 3, city: 4, ship: 15 }), + JSON.stringify(L.piecesLeft(s0, 0))); + + // 15 roads → no legal road edges + const s1 = L.cloneState(s0); + const extra = L.legalRoadEdges(s1, 0, false); + ok('has legal roads before limit', extra.length > 0); + s1.players[0].roads = Array.from({ length: 15 }, (_, i) => i); + ok('15 roads → no legal road edges', L.legalRoadEdges(s1, 0, false).length === 0); + give(s1, 0, COSTS.road); + const s1b = L.buildRoad(s1, 0, extra[0]); + ok('buildRoad refused at limit', s1b.players[0].roads.length === 15); + + // 5 settlements → no legal settlement nodes; city frees one + const s2 = L.cloneState(s0); + const p = s2.players[0]; + while (p.settlements.length < 5) p.settlements.push(1000 + p.settlements.length); // fake ids beyond geometry + ok('5 settlements → none legal', L.legalSettlementNodes(s2, 0, false).length === 0); + const s3 = L.cloneState(s0); + const nid = s3.players[0].settlements[0]; + give(s3, 0, COSTS.city); + const s4 = L.buildCity(s3, 0, nid); + ok('city upgrade returns a settlement to supply', L.piecesLeft(s4, 0).settlement === L.piecesLeft(s3, 0).settlement + 1 + && L.piecesLeft(s4, 0).city === 3); + + // 4 cities → no legal cities + const s5 = L.cloneState(s0); + s5.players[0].cities = [2001, 2002, 2003, 2004]; + ok('4 cities → no legal city nodes', L.legalCityNodes(s5, 0).length === 0); + give(s5, 0, COSTS.city); + const s6 = L.buildCity(s5, 0, s5.players[0].settlements[0]); + ok('buildCity refused at limit', s6.players[0].cities.length === 4); + + // Road Building capped by supply + const s7 = L.cloneState(s0); + s7.players[0].roads = Array.from({ length: 14 }, (_, i) => i); + s7.players[0].devCards = ['roadBuilding']; + const s8 = L.playRoadBuilding(s7, 0); + ok('Road Building with 1 road left grants 1', s8.freeRoads === 1, `freeRoads=${s8.freeRoads}`); + const s9 = L.cloneState(s0); + s9.players[0].devCards = ['roadBuilding']; + ok('Road Building normally grants 2', L.playRoadBuilding(s9, 0).freeRoads === 2); +} + +section('Rules — bank shortage'); +{ + // Find a number whose hexes produce for 2+ seats of one resource. + const base = freshAction(4); + let tested2 = false, tested1 = false, testedOk = false; + for (let n = 2; n <= 12 && !(tested2 && tested1 && testedOk); n++) { + if (n === 7) continue; + const pr = L.productionFor(base, n); + for (const [res, bySeat] of Object.entries(pr.owed)) { + const seats = Object.keys(bySeat); + const need = seats.reduce((t, k) => t + bySeat[k], 0); + // plenty in the bank → paid in full + if (!testedOk) { + const s = L.cloneState(base); s.phase = 'rollPhase'; + const pay = L.productionFor(s, n).pay[res]; + ok(`full bank pays everyone (${res} on ${n})`, JSON.stringify(pay) === JSON.stringify(bySeat)); + testedOk = true; + } + if (seats.length >= 2 && !tested2) { + const s = L.cloneState(base); + const take = s.bank[res] - (need - 1); // leave one short + s.bank[res] -= take; s.players[0].resources[res] += take; + const pr2 = L.productionFor(s, n); + ok(`2+ claimants, bank short → nobody gets ${res}`, !pr2.pay[res] && pr2.shortages.some((x) => x.res === res && !x.single)); + tested2 = true; + } + if (seats.length === 1 && need >= 2 && !tested1) { + const s = L.cloneState(base); + const take = s.bank[res] - 1; // bank holds exactly 1 + s.bank[res] -= take; s.players[(Number(seats[0]) + 1) % 4].resources[res] += take; + const pr2 = L.productionFor(s, n); + ok(`single claimant takes what's left of ${res}`, pr2.pay[res]?.[seats[0]] === 1); + tested1 = true; + } + } + } + ok('found a 2-claimant case', tested2); + // single-claimant with need>=2 needs a city; force one if the board didn't offer it + if (!tested1) { + const s = L.cloneState(base); + const seat = 0; + const nid = s.players[seat].settlements[0]; + s.players[seat].settlements = s.players[seat].settlements.filter((x) => x !== nid); + s.players[seat].cities.push(nid); + for (let n = 2; n <= 12 && !tested1; n++) { + if (n === 7) continue; + const pr = L.productionFor(s, n); + for (const [res, bySeat] of Object.entries(pr.owed)) { + const seats = Object.keys(bySeat); + if (seats.length !== 1 || bySeat[seats[0]] < 2) continue; + const t = L.cloneState(s); + const take = t.bank[res] - 1; + t.bank[res] -= take; t.players[(Number(seats[0]) + 1) % 4].resources[res] += take; + ok(`single claimant (city) takes the last ${res}`, L.productionFor(t, n).pay[res]?.[seats[0]] === 1); + tested1 = true; break; + } + } + } + ok('found a single-claimant case', tested1); +} + +section('Rules — stats'); +{ + seedRandom(11); + const r = playGame({ players: 4 }); + const st = r.s.stats; + const rolled = st.rolls.reduce((a, b) => a + b, 0); + ok('stats exist', !!st); + ok('rolls only on 2..12', st.rolls[0] === 0 && st.rolls[1] === 0); + ok('rolls counted', rolled > 10, `rolled ${rolled}`); + const produced = st.produced.reduce((t, x) => t + total(x), 0); + ok('production recorded', produced > 0); + ok('steals balance', st.stolen.reduce((a, b) => a + b, 0) === st.lostToSteal.reduce((a, b) => a + b, 0)); +} + +section('AI soak'); +{ + const N = QUICK ? 30 : 200; + for (const players of [3, 4]) { + let ended = 0, turnSum = 0, problems = 0, maxTurns = 0; + for (let g = 0; g < N; g++) { + seedRandom(1000 + g * 7 + players); + const r = playGame({ players }); + if (r.problems.length) { problems++; if (problems <= 3) console.error(` game ${g}: ${r.problems[0]}`); } + if (r.ended) { ended++; turnSum += r.turns; maxTurns = Math.max(maxTurns, r.turns); } + } + ok(`base ${players}p: all ${N} games end`, ended === N, `${ended}/${N}`); + ok(`base ${players}p: no invariant breaks`, problems === 0, `${problems} games`); + console.log(` base ${players}p: ${ended}/${N} ended, avg ${(turnSum / Math.max(1, ended)).toFixed(1)} turns, max ${maxTurns}`); + } + const M = QUICK ? 6 : 30; + for (const scenario of ['new-shores', 'four-islands', 'oceania', 'fog-island']) { + let ended = 0, problems = 0, crashes = 0; + for (let g = 0; g < M; g++) { + seedRandom(5000 + g); + try { + const r = playGame({ players: 4, expansion: 'seafarers', scenario, maxTurns: 300 }); + if (r.problems.length) { problems++; if (problems <= 2) console.error(` ${scenario} ${g}: ${r.problems[0]}`); } + if (r.ended) ended++; + } catch (e) { crashes++; if (crashes <= 2) console.error(` ${scenario} ${g}: ${e.stack}`); } + } + ok(`seafarers ${scenario}: no crashes`, crashes === 0, `${crashes}`); + ok(`seafarers ${scenario}: no invariant breaks`, problems === 0, `${problems}`); + console.log(` seafarers ${scenario}: ${ended}/${M} ended within 300 turns`); + } +} + +section('Dice tray throws'); +{ + const seeds = QUICK ? 3 : 12; + let wrong = 0, outside = 0, close = 0, n = 0, maxDur = 0; + const half = DIE_SIZE / 2; + for (const human of [true, false]) { + for (let a = 1; a <= 6; a++) for (let b = 1; b <= 6; b++) for (let k = 0; k < seeds; k++) { + const rng = mulberry32(a * 100 + b * 10 + k + (human ? 0 : 5000)); + const plan = planTrayThrow(TRAY_WORLD, throwOrigin(human), [a, b], rng, DIE_SIZE); + n++; + maxDur = Math.max(maxDur, plan.duration); + const ends = plan.dice.map((d) => d.frames[d.frames.length - 1]); + if (topFace(ends[0].q) !== a || topFace(ends[1].q) !== b) wrong++; + for (const e of ends) { + if (e.u < half - 0.5 || e.u > TRAY_WORLD.w - half + 0.5 || e.v < half - 0.5 || e.v > TRAY_WORLD.h - half + 0.5) outside++; + } + if (Math.hypot(ends[0].u - ends[1].u, ends[0].v - ends[1].v) < DIE_SIZE * 1.15) close++; + } + } + ok('every throw lands on the rolled faces', wrong === 0, `${wrong}/${n}`); + ok('both dice rest inside the tray', outside === 0, `${outside}`); + ok('dice rest apart (no overlap)', close === 0, `${close}/${n}`); + ok('throws finish within 3 s', maxDur <= 3.2, maxDur.toFixed(2)); + // the resting dice project onto the felt + const p0 = trayGround(0, 0), p1 = trayGround(TRAY_WORLD.w, TRAY_WORLD.h); + ok('tray projection maps the world onto the felt', Math.abs(p0.x - TRAY_FELT.x) < 1e-6 && Math.abs(p1.y - (TRAY_FELT.y + TRAY_FELT.h)) < 1e-6); + for (let f = 1; f <= 6; f++) ok(`restingQ shows ${f}`, topFace(restingQ(f, f * 0.7)) === f); +} + +section('Screen layout'); +{ + for (const opponents of [2, 3]) for (const buttons of [8, 9]) { + const furn = hudFurniture({ opponents, buttons }); + for (const r of furn) ok(`${r.name} on screen (${opponents} opp, ${buttons} btn)`, onScreen(r), JSON.stringify(r)); + for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) { + ok(`${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i], furn[j])); + } + } + for (const [expansion, scenario] of [['base', null], ['seafarers', 'new-shores'], ['seafarers', 'four-islands'], ['seafarers', 'oceania'], ['seafarers', 'fog-island']]) { + seedRandom(3); + const s = L.createInitialState(4, { expansion, scenario }); + const fr = boardFrame(L.geoFor(s)); + ok(`${scenario ?? 'base'}: frame on screen`, onScreen(fr.bounds), JSON.stringify(fr.bounds)); + for (const r of hudFurniture({ opponents: 3, buttons: expansion === 'base' ? 8 : 9 })) { + ok(`${scenario ?? 'base'}: frame clear of ${r.name}`, !rectsOverlap(fr.bounds, r), JSON.stringify(fr.bounds)); + } + ok(`${scenario ?? 'base'}: frame clear of the rail`, fr.bounds.y + fr.bounds.h <= RAIL.y); + // every port sits on the sea band (outside the hull, inside the frame) + for (const port of s.ports) { + const out = 30; + const px = port.x + Math.cos(port.angle) * out, py = port.y + Math.sin(port.angle) * out; + ok(`${scenario ?? 'base'}: port inside frame`, px > fr.bounds.x && px < fr.bounds.x + fr.bounds.w && py > fr.bounds.y && py < fr.bounds.y + fr.bounds.h); + } + } + // the rolled-total chip sits above the felt, clear of the buttons and caddy + const chip = { x: TOTAL_CHIP.x - TOTAL_CHIP.r, y: TOTAL_CHIP.y - TOTAL_CHIP.r, w: TOTAL_CHIP.r * 2, h: TOTAL_CHIP.r * 2 }; + ok('total chip on screen', onScreen(chip)); + for (const r of hudFurniture({ opponents: 3, buttons: 9 }).filter((f) => f.name !== 'tray')) { + ok(`total chip clear of ${r.name}`, !rectsOverlap(chip, r), JSON.stringify(r)); + } + ok('total chip centre is above the felt', TOTAL_CHIP.y < TRAY_FELT.y); + + // stacks: monotonic and capped + let mono = true; + for (let n = 1; n <= 25; n++) if (stackLayers(n) < stackLayers(n - 1)) mono = false; + ok('stack layers grow with the count', mono); + ok('stack layers are capped', stackLayers(25) <= 12 && stackLayers(19) >= 10); + ok('an empty stack has no layers', stackLayers(0) === 0); + for (let i = 0; i < 6; i++) { + const sl = caddySlot(i); + const full = stackTop(i, i === 5 ? 25 : 19), bottom = caddySlot(i).card; + ok(`caddy slot ${i} inside the caddy`, sl.x >= CADDY.x && sl.y + sl.h <= CADDY.y + CADDY.h && sl.x + sl.w <= CADDY.x + CADDY.w); + ok(`caddy slot ${i}: a full stack stays in its well`, full.y - CADDY_CARD.h / 2 >= sl.y && bottom.y + CADDY_CARD.h / 2 <= sl.y + sl.h + && full.x + CADDY_CARD.w / 2 <= sl.x + sl.w && bottom.x - CADDY_CARD.w / 2 >= sl.x); + if (i < 5) ok(`caddy slot ${i} clear of slot ${i + 1}`, sl.y + sl.h < caddySlot(i + 1).y); + } + // hand piles stay in the hand zone for 1..5 groups + for (let n = 1; n <= 5; n++) { + const last = handPilePos(n - 1, n); + ok(`hand: ${n} piles fit`, last.x + HAND_CARD.w / 2 + 14 <= HAND.x + HAND.w && handPilePos(0, n).x - HAND_CARD.w / 2 >= HAND.x); + } + for (let n = 1; n <= 9; n++) { + const last = devCardPos(n - 1, n); + ok(`dev: ${n} cards fit`, last.x + HAND_CARD.w / 2 <= DEV.x + DEV.w + 0.5); + } +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); diff --git a/tools/verifyTicketToRide.js b/tools/verifyTicketToRide.js new file mode 100644 index 0000000..a4b97a1 --- /dev/null +++ b/tools/verifyTicketToRide.js @@ -0,0 +1,380 @@ +#!/usr/bin/env node +// verifyTicketToRide.js — headless checks for Ticket to Ride (USA): +// • rules: payments, double-route lockout by player count, the 3-locomotive +// market sweep, end trigger + exactly one final turn each, longest trail vs a +// reference DFS, ticket scoring, forced passes + the all-stuck stall guard +// • all-AI soak across 2–5 players and mixed skills: every game finishes, +// 110 train cards conserved, trains never negative, no stalls +// • skill ladder: skill 5 vs skill 3 (mirrored seats/seeds) +// • screen layout: furniture on screen, no overlaps, map clear of the HUD +// Usage: node tools/verifyTicketToRide.js [--quick] + +import * as L from '../src/games/tickettoride/TicketToRideLogic.js'; +import * as AI from '../src/games/tickettoride/TicketToRideAI.js'; +import { ROUTES, CITIES, TICKETS, TRAIN_COLORS, ROUTE_SCORE } from '../src/games/tickettoride/TicketToRideBoard.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + W, H, SHEET, TRACK, PAD, RAIL, STATUS, hudFurniture, furnitureChildren, onScreen, rectsOverlap, inside, + trackPos, TRACK_SQUARES, +} from '../src/games/tickettoride/TicketToRideLayout.js'; +import { routeSegments, LAND_OUTLINE } from '../src/games/tickettoride/TicketToRideBoard.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; } + +const cardsInPlay = (s) => s.trainDeck.length + s.discard.length + s.faceUp.length + + s.players.reduce((t, p) => t + L.handCount(p), 0); +const route = (a, b, color) => ROUTES.find((r) => ((r.a === a && r.b === b) || (r.a === b && r.b === a)) && (!color || r.color === color)); +const cid = (name) => CITIES.find((c) => c.name === name).id; + +function blankHand(over = {}) { return { ...L.emptyHand(), ...over }; } + +// A started game (setup tickets resolved) for rule tests. +function started(n = 4) { + let s = L.createInitialState(n); + while (s.pendingTickets) s = L.resolveTicketKeep(s, s.pendingTickets.seat, s.pendingTickets.drawn.slice(0, 2)); + return s; +} + +// ── All-AI game driver (mirrors TicketToRideGame.advance / aiTurn) ───────────── +function playGame({ players = 4, skills = null, maxSteps = 4000 } = {}) { + let s = L.createInitialState(players); + L.setPlayerNames(s, Array.from({ length: players }, (_, i) => `P${i}`)); + const skillOf = (seat) => (skills ? skills[seat] : 3); + const problems = []; + let steps = 0, passes = 0; + const check = () => { + if (cardsInPlay(s) !== 110) problems.push(`cards ${cardsInPlay(s)} != 110`); + for (const p of s.players) { + if (p.trainsLeft < 0) problems.push(`seat ${p.seat} trains ${p.trainsLeft}`); + for (const k of [...TRAIN_COLORS, 'locomotive']) if (p.hand[k] < 0) problems.push(`seat ${p.seat} negative ${k}`); + const placed = p.routes.reduce((t, r) => t + ROUTES[r].length, 0); + if (placed + p.trainsLeft !== 45) problems.push(`seat ${p.seat} trains don't add up`); + } + if (s.faceUp.length > 5) problems.push('market overfull'); + }; + while (s.phase !== 'gameOver' && steps++ < maxSteps) { + const before = JSON.stringify(s); + if (s.pendingTickets) { + const pd = s.pendingTickets; + s = L.resolveTicketKeep(s, pd.seat, AI.chooseTicketsToKeep(s, pd.seat, pd.drawn, pd.minKeep, { skill: skillOf(pd.seat) })); + } else { + const seat = s.currentPlayer; + const a = AI.chooseAction(s, seat, { skill: skillOf(seat) }); + if (a.type === 'claimRoute') s = L.claimRoute(s, seat, a.routeId, a.payment); + else if (a.type === 'drawTickets') s = L.drawTickets(s, seat); + else if (a.type === 'pass') { s = L.passTurn(s, seat); passes++; } + else { + s = L.drawTrainCard(s, seat, a.source, a.index); + if (s.currentPlayer === seat && s.drawnThisTurn === 1 && s.phase !== 'gameOver') { + const b = AI.chooseSecondDraw(s, seat, { skill: skillOf(seat) }); + if (b.type === 'pass') { s = L.passTurn(s, seat); passes++; } + else s = L.drawTrainCard(s, seat, b.source, b.index); + if (s.currentPlayer === seat && s.drawnThisTurn === 1) problems.push(`second draw ignored (${JSON.stringify(b)})`); + } + } + if (JSON.stringify(s) === before) { problems.push(`stall: ${JSON.stringify(a)}`); break; } + } + check(); + if (problems.length) break; + } + if (s.phase !== 'gameOver') problems.push(`unfinished after ${steps} steps`); + return { s, problems, passes }; +} + +// ── Rules ────────────────────────────────────────────────────────────────────── +section('Rules'); +seedRandom(11); +{ + const r = route(cid('Denver'), cid('Omaha')); // 4 purple + ok('Denver–Omaha is purple 4', r && r.color === 'purple' && r.length === 4); + const p = { hand: blankHand({ purple: 3, locomotive: 2 }) }; + const opts = L.paymentOptions(p, r); + ok('payment: 3 purple + 1 loco first', opts[0].color === 'purple' && opts[0].colorCount === 3 && opts[0].locos === 1); + ok('payment: no pure-loco when only 2 locos', !opts.some((o) => o.colorCount === 0)); + const g = route(cid('Los Angeles'), cid('Las Vegas')); // 2 gray + const p2 = { hand: blankHand({ red: 1, blue: 2, locomotive: 2 }) }; + const o2 = L.paymentOptions(p2, g); + ok('gray: blue pair, red+loco, pure loco all offered', o2.length === 3 && o2[0].color === 'blue' && o2[0].locos === 0, JSON.stringify(o2)); + ok('cardsForRoute = first option', JSON.stringify(L.cardsForRoute(p2, g)) === JSON.stringify(o2[0])); +} +{ + // Double routes: <4 players one side closes the pair; 4+ the other stays open. + for (const n of [3, 4]) { + let s = started(n); + const [r0, r1] = ROUTES.filter((r) => r.doubleGroup === `${cid('Kansas City')}-${cid('Saint Louis')}`); + s.currentPlayer = 0; s.drawnThisTurn = 0; + s.players[0].hand = blankHand({ blue: 2, purple: 2 }); + s = L.claimRoute(s, 0, r0.id); + ok(`${n}p: claimed one side`, s.claimed[r0.id] === 0); + ok(`${n}p: owner can't take the other side`, !L.routeClaimable(s, 0, r1.id)); + ok(`${n}p: other seat ${n < 4 ? 'locked out' : 'may take it'}`, L.routeClaimable(s, 1, r1.id) === (n >= 4)); + ok(`${n}p: lock reason text`, n < 4 ? /Double track/.test(L.routeLockReason(s, 1, r1.id) ?? '') : L.routeLockReason(s, 1, r1.id) === null); + } +} +{ + // 3-locomotive sweep. + let s = started(3); + s.faceUp = ['red', 'locomotive', 'locomotive', 'blue', 'green']; + s.trainDeck[s.trainDeck.length - 1] = 'locomotive'; // next refill is the 3rd loco + const wipes = s.marketWipes; + s = L.drawTrainCard(s, 0, 'faceUp', 0); + ok('3 face-up locos sweep the market', s.marketWipes > wipes); + ok('market re-dealt to 5 with < 3 locos', s.faceUp.length === 5 && s.faceUp.filter((c) => c === 'locomotive').length < 3); + ok('cards conserved through a sweep', cardsInPlay(s) === 110); +} +{ + // Face-up loco: first draw only, ends the turn. + let s = started(3); + s.faceUp = ['locomotive', 'red', 'blue', 'green', 'white']; + ok('legalFaceUp includes loco on first draw', L.legalFaceUp(s).includes(0)); + const t = L.drawTrainCard(s, 0, 'faceUp', 0); + ok('face-up loco ends the turn', t.currentPlayer === 1); + let u = L.drawTrainCard(s, 0, 'faceUp', 1); + u.faceUp[0] = 'locomotive'; + ok('legalFaceUp excludes loco on 2nd draw', !L.legalFaceUp(u).includes(0)); + ok('2nd-draw face-up loco rejected', JSON.stringify(L.drawTrainCard(u, 0, 'faceUp', 0)) === JSON.stringify(u)); +} +{ + // End trigger: exactly one final turn for every player, including the trigger. + let s = started(3); + s.players[0].trainsLeft = 3; + s.players[0].hand = blankHand({ red: 5 }); + const r = ROUTES.find((x) => x.length === 1); + s.currentPlayer = 0; + s = L.claimRoute(s, 0, r.id, { color: 'red', colorCount: 1, locos: 0 }); + ok('≤2 trains triggers the last round', s.phase === 'lastRound' && s.endTriggered); + let turns = 0; + while (s.phase !== 'gameOver' && turns < 10) { + s = L.drawTrainCard(s, s.currentPlayer, 'deck'); + s = L.drawTrainCard(s, s.currentPlayer, 'deck'); + turns++; + } + ok('exactly 3 final turns in 3p', turns === 3, `got ${turns}`); + ok('scores computed', Array.isArray(s.scores) && s.winner != null); + ok('score rows carry ticket results + trail', s.scores.every((sc) => Array.isArray(sc.tickets) && Array.isArray(sc.longestRoutes))); +} +{ + // Longest trail vs a reference DFS on random networks. + const ref = (s, seat) => { + const inc = new Map(); + for (const rid of s.players[seat].routes) { + const r = ROUTES[rid]; + for (const [x, y] of [[r.a, r.b], [r.b, r.a]]) { if (!inc.has(x)) inc.set(x, []); inc.get(x).push({ rid, y, len: r.length }); } + } + let best = 0; + const dfs = (n, used, t) => { best = Math.max(best, t); for (const e of inc.get(n) || []) if (!used.has(e.rid)) { used.add(e.rid); dfs(e.y, used, t + e.len); used.delete(e.rid); } }; + for (const n of inc.keys()) dfs(n, new Set(), 0); + return best; + }; + let mismatch = 0, badTrail = 0; + for (let i = 0; i < 300; i++) { + const s = started(2); + const pick = ROUTES.filter(() => Math.random() < 0.12).map((r) => r.id); + s.players[0].routes = pick; + const t = L.longestTrail(s, 0); + if (t.length !== ref(s, 0)) mismatch++; + // The trail must be a real walk using each route once. + const len = t.routes.reduce((a, r) => a + ROUTES[r].length, 0); + let walk = t.routes.length === 0 || t.cities.length === t.routes.length + 1; + for (let k = 0; walk && k < t.routes.length; k++) { + const r = ROUTES[t.routes[k]]; + walk = (r.a === t.cities[k] && r.b === t.cities[k + 1]) || (r.b === t.cities[k] && r.a === t.cities[k + 1]); + } + if (len !== t.length || !walk || new Set(t.routes).size !== t.routes.length) badTrail++; + } + ok('longestTrail length = reference DFS (300 nets)', mismatch === 0, `${mismatch} mismatches`); + ok('longestTrail is a valid walk', badTrail === 0, `${badTrail} bad`); +} +{ + // Ticket scoring + status. + const s = started(2); + const t = TICKETS.find((x) => x.points === 4); // Denver–El Paso + s.players[0].tickets = [{ ...t }]; + s.players[0].routes = [route(cid('Denver'), cid('Santa Fe')).id, route(cid('Santa Fe'), cid('El Paso')).id]; + ok('ticket completed → +points', L.ticketScore(s, 0).points === t.points); + ok('ticketStatus marks it done', L.ticketStatus(s, 0)[0].done === true); + s.players[0].routes = []; + ok('ticket missed → −points', L.ticketScore(s, 0).points === -t.points); +} +{ + // Forced passes. + let s = started(3); + s.currentPlayer = 0; + ok('pass refused while a move exists', JSON.stringify(L.passTurn(s, 0)) === JSON.stringify(s)); + // Soft-lock: 2nd draw, deck + discard empty, only locomotives face-up. + s.drawnThisTurn = 1; + const stash = [...s.trainDeck, ...s.discard, ...s.faceUp]; + s.trainDeck = []; s.discard = []; s.faceUp = ['locomotive', 'locomotive']; + s.players[2].hand.red += stash.length - 2; // keep the 110 count honest + const la = L.legalActions(s, 0); + ok('stuck 2nd draw has no legal action', !la.any, JSON.stringify(la)); + ok('AI 2nd draw passes when stuck', AI.chooseSecondDraw(s, 0, { skill: 5 }).type === 'pass'); + const p = L.passTurn(s, 0); + ok('pass ends the turn', p.currentPlayer === 1 && p.drawnThisTurn === 0); + // Everyone stuck → stall guard scores the game. + let q = started(2); + const all = [...q.trainDeck, ...q.discard, ...q.faceUp]; + q.trainDeck = []; q.discard = []; q.faceUp = []; q.ticketDeck = []; + for (const pl of q.players) pl.hand = L.emptyHand(); + q.players[0].hand.red = all.length + 8; // red can't buy the remaining… keep count + q.players[1].hand = L.emptyHand(); + for (const pl of q.players) pl.trainsLeft = 0; // nobody can claim + let guard = 0; + while (q.phase !== 'gameOver' && guard++ < 10) q = L.passTurn(q, q.currentPlayer); + ok('all-stuck round ends the game', q.phase === 'gameOver' && guard <= 3, `guard ${guard}`); +} + +// ── Soak ─────────────────────────────────────────────────────────────────────── +section('All-AI soak'); +{ + const N = QUICK ? 60 : 400; + let bad = 0, totalPasses = 0, turns = 0, first = ''; + for (let i = 0; i < N; i++) { + seedRandom(1000 + i); + const players = 2 + (i % 4); + const skills = Array.from({ length: players }, (_, k) => 1 + ((i + k) % 5)); + const { s, problems, passes } = playGame({ players, skills }); + totalPasses += passes; turns += s.turn; + if (problems.length) { bad++; if (!first) first = `game ${i} (${players}p): ${problems[0]}`; } + } + ok(`${N} games finish cleanly`, bad === 0, `${bad} bad; first: ${first}`); + console.log(` avg turns ${(turns / N).toFixed(1)}, forced passes ${totalPasses}`); +} +{ + // Starved deck: tiny decks force the pass/stall paths through the AI. + let bad = 0, first = ''; + for (let i = 0; i < (QUICK ? 20 : 80); i++) { + seedRandom(5000 + i); + let s = L.createInitialState(5); + const { problems } = (() => { + // Hoard: move most of the deck into a phantom hand so the deck runs dry. + const keep = 12; + const moved = s.trainDeck.splice(0, Math.max(0, s.trainDeck.length - keep)); + for (const c of moved) s.players[4].hand[c]++; + s.players[4].trainsLeft = 45; + const probs = []; + let steps = 0; + while (s.phase !== 'gameOver' && steps++ < 4000) { + const before = JSON.stringify(s); + if (s.pendingTickets) { + const pd = s.pendingTickets; + s = L.resolveTicketKeep(s, pd.seat, AI.chooseTicketsToKeep(s, pd.seat, pd.drawn, pd.minKeep, { skill: 3 })); + continue; + } + const seat = s.currentPlayer; + const a = AI.chooseAction(s, seat, { skill: 1 + (seat % 5) }); + if (a.type === 'claimRoute') s = L.claimRoute(s, seat, a.routeId, a.payment); + else if (a.type === 'drawTickets') s = L.drawTickets(s, seat); + else if (a.type === 'pass') s = L.passTurn(s, seat); + else { + s = L.drawTrainCard(s, seat, a.source, a.index); + if (s.currentPlayer === seat && s.drawnThisTurn === 1) { + const b = AI.chooseSecondDraw(s, seat, { skill: 3 }); + s = b.type === 'pass' ? L.passTurn(s, seat) : L.drawTrainCard(s, seat, b.source, b.index); + } + } + if (JSON.stringify(s) === before) { probs.push(`stall ${JSON.stringify(a)}`); break; } + if (cardsInPlay(s) !== 110) { probs.push('cards'); break; } + } + if (s.phase !== 'gameOver') probs.push('unfinished'); + return { problems: probs }; + })(); + if (problems.length) { bad++; if (!first) first = `${i}: ${problems[0]}`; } + } + ok('starved-deck games never stall', bad === 0, first); +} + +// ── Skill ladder ─────────────────────────────────────────────────────────────── +section('Skill ladder (5 vs 3, mirrored)'); +for (const players of [2, 4]) { + const N = QUICK ? 40 : 300; + let wins5 = 0, games = 0, pts5 = 0, pts3 = 0; + for (let i = 0; i < N; i++) { + for (const flip of [0, 1]) { + seedRandom(9000 + i); + const skills = Array.from({ length: players }, (_, k) => ((k + flip) % 2 === 0 ? 5 : 3)); + const { s, problems } = playGame({ players, skills }); + if (problems.length) continue; + games++; + const w = s.winner; + if (skills[w] === 5) wins5++; + s.scores.forEach((sc) => { if (skills[sc.seat] === 5) pts5 += sc.total; else pts3 += sc.total; }); + } + } + const rate = wins5 / games; + const a5 = pts5 / games / (players / 2), a3 = pts3 / games / (players / 2); + console.log(` ${players}p: skill 5 wins ${(rate * 100).toFixed(1)}% of ${games} (avg pts 5:${a5.toFixed(1)} 3:${a3.toFixed(1)})`); + // With two of each skill at a 4p table the baseline is 50%; score margin is the steadier signal. + ok(`${players}p: skill 5 beats skill 3`, rate > (players === 2 ? 0.55 : 0.5) && a5 > a3 + 3, `${(rate * 100).toFixed(1)}%, +${(a5 - a3).toFixed(1)} pts`); +} +{ + const N = QUICK ? 40 : 200; + let wins = 0, games = 0; + for (let i = 0; i < N; i++) for (const flip of [0, 1]) { + seedRandom(7000 + i); + const skills = flip ? [1, 3] : [3, 1]; + const { s, problems } = playGame({ players: 2, skills }); + if (problems.length) continue; + games++; if (skills[s.winner] === 3) wins++; + } + console.log(` 2p: skill 3 beats skill 1 ${(wins / games * 100).toFixed(1)}%`); + ok('skill 3 beats skill 1', wins / games > 0.55); +} + +// ── Layout ───────────────────────────────────────────────────────────────────── +section('Layout'); +{ + for (const n of [1, 2, 3, 4]) { + const f = hudFurniture({ opponents: n }); + for (const r of f) ok(`${r.name} on screen (${n} opp)`, onScreen(r), JSON.stringify(r)); + for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) { + ok(`${f[i].name} ∩ ${f[j].name}`, !rectsOverlap(f[i], f[j]), `${JSON.stringify(f[i])} ${JSON.stringify(f[j])}`); + } + } + const f = hudFurniture({ opponents: 4 }); + const byName = Object.fromEntries(f.map((r) => [r.name, r])); + for (const k of furnitureChildren()) ok(`${k.name} inside ${k.parent}`, inside(k, byName[k.parent]), JSON.stringify(k)); + // Pad furniture stays on the pad; rail furniture on the rail; the sheet clears both. + for (const r of f) { + const onPad = inside(r, PAD), onRail = inside(r, RAIL); + ok(`${r.name} sits on the pad or the rail`, onPad || onRail, JSON.stringify(r)); + ok(`${r.name} clear of the map sheet`, !rectsOverlap(r, SHEET)); + } + ok('sheet clear of pad + rail', !rectsOverlap(SHEET, PAD) && !rectsOverlap(SHEET, RAIL)); + // Everything on the map sits inside the score track. + const innerX0 = SHEET.x + TRACK.inset + TRACK.band, innerY0 = SHEET.y + TRACK.inset + TRACK.band; + const innerX1 = SHEET.x + SHEET.w - TRACK.inset - TRACK.band, innerY1 = SHEET.y + SHEET.h - TRACK.inset - TRACK.band; + const inMap = (x, y, m = 0) => x >= innerX0 + m && x <= innerX1 - m && y >= innerY0 + m && y <= innerY1 - m; + let bad = 0; + for (const c of CITIES) if (!inMap(c.x, c.y, 12) || !inMap(c.x, c.y - 34)) bad++; + ok('cities + name tags inside the track', bad === 0, `${bad} out`); + bad = 0; + for (const r of ROUTES) for (const s of routeSegments(r)) if (!inMap(s.cx, s.cy, 6)) bad++; + ok('route slots inside the track', bad === 0, `${bad} out`); + ok('land inside the track', LAND_OUTLINE.every(([x, y]) => inMap(x, y)), ''); + // Status ribbon clear of city tags. + const ribbon = { x: STATUS.x - 330, y: STATUS.y - 20, w: 660, h: 40 }; + const tagHit = CITIES.filter((c) => rectsOverlap(ribbon, { x: c.x - 70, y: c.y - 36, w: 140, h: 22 })); + ok('status ribbon clear of city name tags', tagHit.length === 0, tagHit.map((c) => c.name).join(', ')); + // Score track: 100 distinct squares inside the band. + const seen = new Set(); + let outBand = 0; + for (let i = 0; i < TRACK_SQUARES; i++) { + const p = trackPos(i); + seen.add(`${Math.round(p.x)},${Math.round(p.y)}`); + if (p.x < SHEET.x || p.x > SHEET.x + SHEET.w || p.y < SHEET.y || p.y > SHEET.y + SHEET.h) outBand++; + } + ok('score track has 100 distinct squares on the sheet', seen.size === TRACK_SQUARES && outBand === 0); + ok('trackPos wraps', JSON.stringify(trackPos(103)) === JSON.stringify(trackPos(3)) && JSON.stringify(trackPos(-2)) === JSON.stringify(trackPos(98))); + ok('screen is 1920×1080', W === 1920 && H === 1080); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);