Overhaul Catan and Ticket to Ride with procedural art tables, shared 3D dice, skill-scaled AI, end screens, and headless verification tools
- 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
This commit is contained in:
parent
07c1d7ba04
commit
8ef312ef45
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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-<id> 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-<ci> / catan-city-<ci> / catan-road-<ci> / catan-ship-<ci> 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 };
|
||||
|
|
@ -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); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -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));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()); }
|
||||
}
|
||||
|
|
@ -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,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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] };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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-<ci> a plastic train car in player colour ci (+ ttr-car-shadow)
|
||||
// ttr-loco-<ci> the little locomotive that lays a claimed route
|
||||
// ttr-marker-<ci> 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);
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
@ -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);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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); }
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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 */ }
|
||||
}
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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(); }
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
@ -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);
|
||||
Loading…
Reference in New Issue