// TicketToRideGame.js — the Ticket to Ride table (USA). // // An antique watercolour railway map pinned to a station-master's desk: // • the map (TicketToRideArt) carries printed route slots, station pins, // name tags and the 0–99 score track; claimed routes get plastic cars, // laid one by one by a little locomotive that steams along the route // • the right-hand desk pad and the bottom rail are TicketToRideHud // • pop-ups are TicketToRideDialogs; the scoring ceremony is // TicketToRideEndScreen // Game rules live in TicketToRideLogic (pure); opponents in TicketToRideAI // (skill 1–5 from the opponent-select screen). import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { api } from '../../services/api.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { Tooltip } from '../../ui/Tooltip.js'; import { TutorialModal } from '../../ui/TutorialModal.js'; import { aiTiming, PACE, clampSkill } from '../../ui/cardtable/AITiming.js'; import { CITIES, ROUTES, PLAYER_COLORS, ROUTE_SCORE, CARD_LABEL, routeSegments, routeMidpoint, } from './TicketToRideBoard.js'; import * as L from './TicketToRideLogic.js'; import * as AI from './TicketToRideAI.js'; import { prepareTicketToRideArt, ROUTE_INK, SERIF, DISPLAY, CAR_TEX } from './TicketToRideArt.js'; import { TTRHud, CARD_FRAME } from './TicketToRideHud.js'; import { openTicketChooser, openPaymentChooser, openPauseMenu, openLog, confirmBox, } from './TicketToRideDialogs.js'; import { showTicketToRideEndScreen } from './TicketToRideEndScreen.js'; import { whistle, chuff } from './TicketToRideSound.js'; import { SHEET, TRACK, CARD, HAND_CARD, marketPos, DECK, DISCARD, TICKET_BOX, PAD, STATUS, trackPos, MENU_BTN, LOG_BTN, HELP_BTN, ROUTES_BTN, PASS_BTN, } from './TicketToRideLayout.js'; const D = { desk: -20, map: -10, glow: 2, carShadow: 5, car: 6, cityGlow: 8, hover: 12, loco: 14, cloud: 16, zone: 19, marker: 22, fx: 26, hud: 30, hudTop: 40, flight: 60, modal: 70, banner: 80, tooltip: 95, }; const SETTINGS_KEY = 'ttr-settings'; const DEFAULT_SETTINGS = { pace: 'normal', showAffordable: false, askPayment: true }; const hexStr = (n) => `#${n.toString(16).padStart(6, '0')}`; const inkInt = (c) => parseInt((ROUTE_INK[c] ?? ROUTE_INK.gray).slice(1), 16); export default class TicketToRideGame extends Phaser.Scene { constructor() { super('TicketToRideGame'); } init(data) { this.initData = data; this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; this.gs = null; this.busy = false; this.modal = null; this.ended = false; this.carSprites = new Map(); this.animatingRoute = null; this.hl = { route: null, pile: null, ticket: null, opp: null, longest: false }; this.ui = { suppressHand: false, holdScores: false, hiddenMarket: new Set() }; this.markerScore = []; this.markers = []; try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } } create() { // Music controls hang in the map's top-right corner (inside the score track), // clear of the desk pad's Menu / Log / How to Play buttons. try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? [], undefined, { right: SHEET.x + SHEET.w - TRACK.inset - TRACK.band - 2, top: SHEET.y + TRACK.inset + TRACK.band - 4, infoColor: '#5a4428', }); } catch (_) { /* no music json */ } this.events.once('shutdown', () => { this.ended = true; }); prepareTicketToRideArt(this).then(() => { if (!this.sys?.isActive()) return; this.build(); }); } build() { this.tooltip = new Tooltip(this, { depth: D.tooltip, hoverDelay: 220 }); this.buildTable(); this.buildMapLayers(); this.buildAmbient(); this.buildButtons(); this.buildStatus(); this.buildKeys(); this.startNewMatch(); } // ── table + map ─────────────────────────────────────────────────────────────── buildTable() { if (this.playfield?.key && this.textures.exists(this.playfield.key)) { this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, this.playfield.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.desk - 1); // Keep the desk pad and the rail from the baked desk over the cloth. const pad = this.add.image(0, 0, 'ttr-desk').setOrigin(0).setDepth(D.desk); pad.setCrop(PAD.x - 10, PAD.y - 6, PAD.w + 20, GAME_HEIGHT); const rail = this.add.image(0, 0, 'ttr-desk').setOrigin(0).setDepth(D.desk); rail.setCrop(0, SHEET.y + SHEET.h, GAME_WIDTH, GAME_HEIGHT); } else { this.add.image(0, 0, 'ttr-desk').setOrigin(0).setDepth(D.desk); } this.add.image(SHEET.x, SHEET.y, 'ttr-map').setOrigin(0).setDepth(D.map); // Lamp: a slow, faint warm flicker over the map. this.lamp = this.add.image(760, 430, 'ttr-glow').setDisplaySize(1900, 1300) .setTint(0xffc070).setBlendMode('ADD').setAlpha(0.06).setDepth(D.cloud + 1); this.time.addEvent({ delay: 2400, loop: true, callback: () => this.tweens.add({ targets: this.lamp, alpha: 0.045 + Math.random() * 0.035, duration: 900 + Math.random() * 900 }), }); } buildMapLayers() { this.segCache = ROUTES.map((r) => routeSegments(r)); this.midCache = ROUTES.map((r) => routeMidpoint(r)); this.glowGfx = this.add.graphics().setDepth(D.glow); this.topGfx = this.add.graphics().setDepth(D.hover); this.cityGlows = CITIES.map((c) => this.add.image(c.x, c.y, 'ttr-glow').setDisplaySize(58, 58) .setBlendMode('ADD').setVisible(false).setDepth(D.cityGlow)); this.routeZones = ROUTES.map((r, id) => { const m = this.midCache[id]; const z = this.add.zone(m.x, m.y, Math.max(m.length, 24), m.width + 6) .setRotation(m.angle).setInteractive({ useHandCursor: true }).setDepth(D.zone); z.on('pointerover', () => { this.hl.route = id; this.renderHighlights(); }); z.on('pointerout', () => { if (this.hl.route === id) { this.hl.route = null; this.renderHighlights(); } }); z.on('pointerdown', () => this.onRouteClick(id)); return z; }); this.routeZones.forEach((z, id) => this.tooltip.attachTo(z, () => this.routeTooltip(id))); this.steam = this.add.particles(0, 0, 'ttr-steam', { lifespan: { min: 700, max: 1300 }, speed: { min: 6, max: 26 }, angle: { min: 230, max: 310 }, scale: { start: 0.35, end: 1.3 }, alpha: { start: 0.7, end: 0 }, emitting: false, }).setDepth(D.fx); this.sparks = this.add.particles(0, 0, 'ttr-spark', { lifespan: 700, speed: { min: 60, max: 220 }, angle: { min: 0, max: 360 }, scale: { start: 1.2, end: 0 }, alpha: { start: 1, end: 0 }, gravityY: 160, emitting: false, }).setDepth(D.fx); } buildAmbient() { // Cloud shadows drifting across the map, clipped to the sheet. const maskG = this.make.graphics({ x: 0, y: 0, add: false }); maskG.fillStyle(0xffffff).fillRect(SHEET.x, SHEET.y, SHEET.w, SHEET.h); const mask = maskG.createGeometryMask(); this.clouds = [0, 1, 2].map((i) => { const c = this.add.image(SHEET.x + 200 + i * 520, SHEET.y + 160 + (i % 2) * 380, 'ttr-cloud') .setScale(2.4 + i * 0.4).setAlpha(0.22).setDepth(D.cloud).setMask(mask); c.vx = 6 + i * 2.5; return c; }); // Steam wisps from busy junctions. this.time.addEvent({ delay: 3200, loop: true, callback: () => this.hubSteam() }); } hubSteam() { if (!this.gs) return; const touch = new Map(); for (const [rid] of Object.entries(this.gs.claimed)) { const r = ROUTES[rid]; touch.set(r.a, (touch.get(r.a) ?? 0) + 1); touch.set(r.b, (touch.get(r.b) ?? 0) + 1); } const hubs = [...touch.entries()].filter(([, n]) => n >= 3); if (!hubs.length) return; const [cid] = hubs[Math.floor(Math.random() * hubs.length)]; const c = CITIES[cid]; this.steam.explode(4, c.x + 6, c.y - 4); } update(_t, dt) { if (this.clouds) { for (const c of this.clouds) { c.x += c.vx * dt / 1000; if (c.x - c.displayWidth / 2 > SHEET.x + SHEET.w) c.x = SHEET.x - c.displayWidth / 2; } } if (this.cityGlows) { const a = 0.55 + 0.35 * Math.sin(this.time.now / 220); this.cityGlows.forEach((g) => { if (g.visible) g.setAlpha(a * (g.baseAlpha ?? 1)); }); } } // ── buttons, status, keys ────────────────────────────────────────────────────── buildButtons() { const mk = (r, label, fn, opts = {}) => new Button(this, r.x + r.w / 2, r.y + r.h / 2, label, fn, { width: r.w, height: r.h, fontSize: 16, bg: 0x3a2414, ...opts, }).setDepth(D.hud + 2); mk(MENU_BTN, '☰ Menu', () => this.openMenu()); mk(LOG_BTN, 'Log', () => this.openLogView()); mk(HELP_BTN, 'How to Play', () => new TutorialModal(this.gameDef).open()); this.routesBtn = new Button(this, ROUTES_BTN.x, ROUTES_BTN.y, '', () => this.toggleAffordable(), { width: ROUTES_BTN.w, height: ROUTES_BTN.h, fontSize: 15, bg: 0x2f4a36, }).setDepth(D.hud + 2); this.refreshRoutesBtn(); this.passBtn = new Button(this, PASS_BTN.x, PASS_BTN.y, 'Pass Turn', () => this.onPass(), { width: PASS_BTN.w, height: PASS_BTN.h, fontSize: 18, bg: 0x7a2a1a, }).setDepth(D.hud + 2).setVisible(false); } refreshRoutesBtn() { this.routesBtn?.setLabel(this.settings.showAffordable ? 'Routes: shown' : 'Routes: hidden'); } buildStatus() { this.statusBg = this.add.graphics().setDepth(D.banner - 2); this.statusText = this.add.text(STATUS.x, STATUS.y, '', { fontFamily: DISPLAY, fontSize: '19px', color: '#2b1a06', }).setOrigin(0.5).setDepth(D.banner - 1); } setStatus(text, tone = 'plain') { if (this.statusText.text === text && this._statusTone === tone) return; this._statusTone = tone; this.statusText.setText(text); const w = Math.max(260, this.statusText.width + 70), h = 38; const g = this.statusBg; g.clear(); if (!text) return; const fill = tone === 'final' ? 0x9a2a1e : tone === 'you' ? 0xf0dca4 : 0xe6d3a2; const x = STATUS.x - w / 2, y = STATUS.y - h / 2; g.fillStyle(0x000000, 0.35).fillRoundedRect(x + 3, y + 5, w, h, 6); // Ribbon tails. g.fillStyle(tone === 'final' ? 0x6a1a12 : 0xb89a5e, 1); g.fillTriangle(x - 20, y + 6, x + 4, y + 6, x + 4, y + h + 4); g.fillTriangle(x - 20, y + h + 4, x - 8, y + h / 2 + 5, x - 20, y + 6); g.fillTriangle(x + w + 20, y + 6, x + w - 4, y + 6, x + w - 4, y + h + 4); g.fillTriangle(x + w + 20, y + h + 4, x + w + 8, y + h / 2 + 5, x + w + 20, y + 6); g.fillStyle(fill, 1).fillRoundedRect(x, y, w, h, 5); g.lineStyle(1.5, tone === 'final' ? 0xffd0a0 : 0x7a4a2a, 0.9).strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 3); this.statusText.setColor(tone === 'final' ? '#fff0d0' : '#2b1a06'); } buildKeys() { this.input.keyboard?.on('keydown', (e) => { if (this.ended || !this.gs) return; const k = e.key; if (k === 'Escape') { if (!this.modal) this.openMenu(); else if (this.modal.onEsc) this.modal.onEsc(); else if (!this.modal.sticky) this.closeModal(); return; } if (this.modal) return; if (k >= '1' && k <= '5') this.onMarketClick(Number(k) - 1); else if (k === 'd' || k === 'D') this.onDeckClick(); else if (k === 't' || k === 'T') this.onTicketDeckClick(); else if (k === 'r' || k === 'R') this.toggleAffordable(); else if (k === 'l' || k === 'L') this.openLogView(); else if (k === 'p' || k === 'P') { if (this.passBtn.visible) this.onPass(); } }); } saveSettings() { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } } get k() { return PACE[this.settings.pace] ?? 1; } skillFor(seat) { return clampSkill(this.opponents[seat - 1]?.skill ?? 3); } // ── match ───────────────────────────────────────────────────────────────────── startNewMatch() { const playerCount = Math.min(5, Math.max(2, 1 + this.opponents.length)); this.gs = L.createInitialState(playerCount); L.setPlayerNames(this.gs, ['You', ...this.opponents.map((o) => o?.name ?? 'CPU')]); this.hud = new TTRHud(this, { hud: D.hud, hudTop: D.hudTop }, { onMarket: (i) => this.onMarketClick(i), onDeck: () => this.onDeckClick(), onTickets: () => this.onTicketDeckClick(), onPileHover: (c) => { this.hl.pile = c; this.renderHighlights(); }, onTicketHover: (t) => { this.hl.ticket = t; this.renderHighlights(); }, onOppHover: (s) => { this.hl.opp = s; this.renderHighlights(); }, onLongestHover: (on) => { this.hl.longest = on; this.renderHighlights(); }, onNotepad: () => this.openLogView(), tooltip: (obj, fn) => this.tooltip.attachTo(obj, fn), }); this.hud.build(this.gs, this.opponents); this.buildMarkers(); this.renderAll(); this.time.delayedCall(700, () => this.advance()); } buildMarkers() { this.gs.players.forEach((p, seat) => { const m = this.add.image(0, 0, `ttr-marker-${p.colorIndex}`).setDisplaySize(22, 22).setDepth(D.marker + seat * 0.01); const lap = this.add.text(0, 0, '', { fontFamily: 'Righteous', fontSize: '10px', color: '#fff', stroke: '#000', strokeThickness: 2 }) .setOrigin(0.5).setDepth(D.marker + 0.5); this.markers[seat] = { img: m, lap }; this.markerScore[seat] = 0; }); this.placeMarkers(false); } markerSpot(seat, score) { const square = ((score % 100) + 100) % 100; const same = this.gs.players.map((p) => p.seat).filter((s) => ((((this.markerScore[s] ?? 0) % 100) + 100) % 100) === square); const k = same.indexOf(seat), n = same.length; const p = trackPos(square); return { x: p.x + (k - (n - 1) / 2) * 6, y: p.y - (k - (n - 1) / 2) * 5 }; } placeMarkers() { this.gs.players.forEach((p, seat) => { const pos = this.markerSpot(seat, this.markerScore[seat]); const m = this.markers[seat]; m.img.setPosition(pos.x, pos.y); m.lap.setPosition(pos.x, pos.y).setText(this.markerScore[seat] >= 100 ? '+100' : this.markerScore[seat] < 0 ? '−' : ''); }); } async moveMarker(seat, to, { stepMs = 34 } = {}) { const from = this.markerScore[seat]; if (from === to) return; const dir = Math.sign(to - from); const steps = Math.abs(to - from); const m = this.markers[seat]; m.img.setDepth(D.marker + 1); if (steps > 30) { this.markerScore[seat] = to; const pos = this.markerSpot(seat, to); await this.tw({ targets: [m.img, m.lap], x: pos.x, y: pos.y, duration: 500, ease: 'Cubic.easeInOut' }); } else { for (let i = 1; i <= steps; i++) { const p = trackPos(from + dir * i); await this.tw({ targets: [m.img, m.lap], x: p.x, y: p.y - 4, duration: stepMs, ease: 'Sine.easeOut' }); } this.markerScore[seat] = to; } m.img.setDepth(D.marker + seat * 0.01); playSound(this, SFX.PIECE_CLICK); this.placeMarkers(); } // ── turn driver ─────────────────────────────────────────────────────────────── async advance() { if (this.ended || !this.gs) return; const s = this.gs; this.renderAll(); if (s.phase === 'gameOver') { this.onGameOver(); return; } if (s.pendingTickets) { if (s.pendingTickets.seat === 0) this.promptTickets(); else await this.aiResolveTickets(); return; } if (s.currentPlayer === 0) { if (!this._humanTurnSeen) { this._humanTurnSeen = true; this.yourTurnCue(); } return; } this._humanTurnSeen = false; await this.aiTurn(); } canHumanAct() { const s = this.gs; return !this.ended && !this.busy && !this.modal && s && (s.phase === 'turn' || s.phase === 'lastRound') && s.currentPlayer === 0 && !s.pendingTickets && s.winner == null; } async runHuman(fn) { this.busy = true; this.tooltip.hide(); try { await fn(); } finally { this.busy = false; } if (!this.ended) this.advance(); } yourTurnCue() { const r = this.add.text(STATUS.x, STATUS.y + 44, 'Your turn', { fontFamily: DISPLAY, fontSize: '28px', color: '#fff3c8', stroke: '#3b2a17', strokeThickness: 5, }).setOrigin(0.5).setDepth(D.banner).setAlpha(0); this.tweens.add({ targets: r, alpha: 1, y: STATUS.y + 54, duration: 260, ease: 'Back.easeOut', onComplete: () => this.tweens.add({ targets: r, alpha: 0, delay: 700, duration: 300, onComplete: () => r.destroy() }), }); } // ── human input ──────────────────────────────────────────────────────────────── onMarketClick(i) { if (!this.canHumanAct()) return; const c = this.gs.faceUp[i]; if (c == null) return; if (c === 'locomotive' && this.gs.drawnThisTurn !== 0) { this.flash('A face-up locomotive can only be your first draw'); return; } this.runHuman(() => this.doDraw(0, { source: 'faceUp', index: i })); } onDeckClick() { if (!this.canHumanAct()) return; if (!L.canDrawFromDeck(this.gs)) { this.flash('The deck and discard are empty'); return; } this.runHuman(() => this.doDraw(0, { source: 'deck' })); } onTicketDeckClick() { if (!this.canHumanAct()) return; if (this.gs.drawnThisTurn > 0) { this.flash('Finish drawing train cards first'); return; } if (!L.canDrawTickets(this.gs)) { this.flash('No destination tickets left'); return; } const n = Math.min(3, this.gs.ticketDeck.length); this.tooltip.hide(); this.modal = confirmBox(this, { heading: 'Draw destination tickets?', text: `You'll draw ${n} ticket${n === 1 ? '' : 's'} and must keep at least 1. Unfinished tickets cost their points at the end, and this uses your whole turn.`, yes: 'Draw Tickets', depth: D.modal, onYes: () => { this.modal = null; this.drawHumanTickets(); }, onNo: () => { this.modal = null; }, }); } drawHumanTickets() { if (!this.canHumanAct()) return; this.runHuman(async () => { this.gs = L.drawTickets(this.gs, 0); playSound(this, SFX.CARD_SHUFFLE); this.renderAll(); await this.flyTickets(TICKET_BOX, { x: PAD.x + PAD.w / 2, y: PAD.y + 400 }, this.gs.pendingTickets.drawn.length, 1.2); }); } onPass() { if (!this.canHumanAct() || L.legalActions(this.gs, 0).any) return; this.runHuman(async () => { this.gs = L.passTurn(this.gs, 0); }); } onRouteClick(id) { if (!this.canHumanAct()) return; const gs = this.gs; if (gs.drawnThisTurn > 0) { this.flash('You are drawing cards this turn'); return; } const why = L.routeLockReason(gs, 0, id); if (why) { this.flash(why); return; } const opts = L.paymentOptions(gs.players[0], ROUTES[id]); if (!opts.length) { this.flash(this.shortfall(id)); return; } if (opts.length === 1 || !this.settings.askPayment) { this.runHuman(() => this.doClaim(0, id, opts[0])); return; } const m = this.midCache[id]; const chooser = openPaymentChooser(this, { route: ROUTES[id], options: opts, anchor: { x: m.x, y: m.y }, depth: D.modal, onAlwaysFewest: () => { this.settings.askPayment = false; this.saveSettings(); }, onPick: (opt) => { this.modal = null; if (opt) this.runHuman(() => this.doClaim(0, id, opt)); }, }); chooser.onEsc = () => { chooser.close(); this.modal = null; }; this.modal = chooser; } shortfall(id) { const r = ROUTES[id]; const hand = this.gs.players[0].hand; const best = r.color === 'gray' ? Math.max(...['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black', 'white'].map((c) => hand[c])) : hand[r.color]; const short = r.length - best - hand.locomotive; return `Need ${short} more ${r.color === 'gray' ? 'matching' : CARD_LABEL[r.color].toLowerCase()} card${short === 1 ? '' : 's'} (or locomotives)`; } toggleAffordable() { this.settings.showAffordable = !this.settings.showAffordable; this.saveSettings(); this.refreshRoutesBtn(); this.renderHighlights(); } // ── AI ───────────────────────────────────────────────────────────────────────── async aiTurn() { this.busy = true; const seat = this.gs.currentPlayer; const skill = this.skillFor(seat); const t = aiTiming(skill, this.k); this.renderAll(); await this.wait(Math.max(300, t.think)); if (this.ended) return; const a = AI.chooseAction(this.gs, seat, { skill }); const before = this.gs; if (a.type === 'claimRoute') { await this.doClaim(seat, a.routeId, a.payment); const r = ROUTES[a.routeId]; this.hud.caption(seat, `${CITIES[r.a].name} – ${CITIES[r.b].name} +${ROUTE_SCORE[r.length]}`); if (r.length >= 5) this.hud.emote(seat, 'happy'); } else if (a.type === 'drawTickets') { this.gs = L.drawTickets(this.gs, seat); this.renderAll(); this.hud.caption(seat, 'Drawing tickets…'); await this.flyTickets(TICKET_BOX, this.hud.oppAnchor(seat), this.gs.pendingTickets?.drawn.length ?? 3, 0.45); } else if (a.type === 'pass') { this.gs = L.passTurn(this.gs, seat); this.hud.caption(seat, 'No moves — passes'); } else { const first = await this.doDraw(seat, a); let label = first === 'locomotive-face' ? 'Took a face-up locomotive' : 'Drew a card'; if (this.gs.currentPlayer === seat && this.gs.drawnThisTurn === 1 && !this.ended) { await this.wait(Math.max(120, t.between)); const b = AI.chooseSecondDraw(this.gs, seat, { skill }); if (b.type === 'pass') this.gs = L.passTurn(this.gs, seat); else { await this.doDraw(seat, b); label = 'Drew 2 cards'; } } this.hud.caption(seat, label, 900); } if (this.ended) return; this.afterAction(before); this.renderAll(); await this.wait(Math.round(180 * this.k)); this.busy = false; this.advance(); } async aiResolveTickets() { this.busy = true; const pend = this.gs.pendingTickets; const seat = pend.seat; this.renderAll(); if (pend.context === 'setup') await this.flyTickets(TICKET_BOX, this.hud.oppAnchor(seat), pend.drawn.length, 0.45); await this.wait(Math.round(500 * this.k)); if (this.ended) return; const keep = AI.chooseTicketsToKeep(this.gs, seat, pend.drawn, pend.minKeep, { skill: this.skillFor(seat) }); this.gs = L.resolveTicketKeep(this.gs, seat, keep); const back = pend.drawn.length - keep.length; this.hud.caption(seat, `Kept ${keep.length} ticket${keep.length === 1 ? '' : 's'}`); if (back > 0) await this.flyTickets(this.hud.oppAnchor(seat), TICKET_BOX, back, 0.45, true); this.renderAll(); this.busy = false; this.advance(); } // ── actions (shared by human + AI) ───────────────────────────────────────────── // Returns 'locomotive-face' when a face-up loco ended the turn. async doDraw(seat, a) { const prev = this.gs; const next = L.drawTrainCard(prev, seat, a.source, a.index); if (next.drawnThisTurn === prev.drawnThisTurn && next.currentPlayer === prev.currentPlayer) return null; const human = seat === 0; const k = human ? Math.min(1, this.k) : this.k; const color = a.source === 'faceUp' ? prev.faceUp[a.index] : next.lastDeckCard; const wipe = (next.marketWipes ?? 0) > (prev.marketWipes ?? 0); playSound(this, SFX.CARD_DEAL); this.gs = next; if (human) this.ui.suppressHand = true; if (a.source === 'faceUp') { this.ui.hiddenMarket = wipe ? new Set([0, 1, 2, 3, 4]) : new Set([a.index]); this.renderAll(); const from = marketPos(a.index); const to = human ? this.hud.pilePos(color) : this.hud.oppAnchor(seat); await this.flyCard({ frame: CARD_FRAME[color], from: { ...from, w: CARD.w, h: CARD.h }, to: { ...to, w: human ? HAND_CARD.w : 34, h: human ? HAND_CARD.h : 49 }, duration: 340 * k, lift: true, }); if (human) { this.ui.suppressHand = false; this.renderAll(); this.hud.bumpPile(color); } await this.refillMarket(prev, next, a.index, wipe, k); } else { this.ui.hiddenMarket = wipe ? new Set([0, 1, 2, 3, 4]) : new Set(); this.renderAll(); const from = { x: DECK.x, y: this.hud.deckTopY ?? DECK.y }; if (human) { await this.flyCard({ frame: CARD_FRAME[color], back: true, from: { ...from, w: CARD.w, h: CARD.h }, reveal: { x: DECK.x - 40, y: DECK.y - 150, w: CARD.w * 1.6, h: CARD.h * 1.6 }, to: { ...this.hud.pilePos(color), w: HAND_CARD.w, h: HAND_CARD.h }, duration: 360, }); this.ui.suppressHand = false; this.renderAll(); this.hud.bumpPile(color); } else { await this.flyCard({ frame: CARD_FRAME.back, from: { ...from, w: CARD.w, h: CARD.h }, to: { ...this.hud.oppAnchor(seat), w: 34, h: 49 }, duration: 340 * k, }); } if (wipe) await this.refillMarket(prev, next, null, true, k); } this.ui.suppressHand = false; this.ui.hiddenMarket = new Set(); this.renderAll(); return color === 'locomotive' && a.source === 'faceUp' ? 'locomotive-face' : color; } async refillMarket(prev, next, takenIdx, wipe, k) { if (wipe) { this.announce('Three locomotives! The market is swept and re-dealt.'); playSound(this, SFX.CARD_SHUFFLE); // The cards that were showing slide off to the discard… const showing = prev.faceUp.map((c, i) => ({ c, i })).filter(({ i }) => i !== takenIdx); await Promise.all(showing.map(({ c, i }, n) => this.flyCard({ frame: CARD_FRAME[c], from: { ...marketPos(i), w: CARD.w, h: CARD.h }, to: { ...DISCARD, w: CARD.w, h: CARD.h, angle: 4 }, duration: 300 * k, delay: n * 50, }))); // …and five fresh ones are dealt. this.ui.hiddenMarket = new Set([0, 1, 2, 3, 4]); this.renderAll(); await this.dealSlots(next, [0, 1, 2, 3, 4], k); return; } if (takenIdx != null && next.faceUp.length === prev.faceUp.length && next.faceUp[takenIdx] != null) { await this.dealSlots(next, [takenIdx], k); } } async dealSlots(state, slots, k) { await Promise.all(slots.map((i, n) => this.flyCard({ frame: CARD_FRAME[state.faceUp[i]], back: true, flipEnd: true, from: { x: DECK.x, y: this.hud.deckTopY ?? DECK.y, w: CARD.w, h: CARD.h }, to: { ...marketPos(i), w: CARD.w, h: CARD.h }, duration: 300 * k, delay: n * 70, }).then(() => { this.ui.hiddenMarket.delete(i); this.hud.renderMarket(this.gs, this.uiState()); }))); } async doClaim(seat, routeId, payment) { const prev = this.gs; const next = L.claimRoute(prev, seat, routeId, payment); if (next.claimed[routeId] !== seat) return; const human = seat === 0; const k = human ? Math.min(1, this.k) : this.k; this.tooltip.hide(); this.hl.route = null; // 1. The payment flicks into the discard. const cards = [...Array(payment.colorCount).fill(payment.color), ...Array(payment.locos).fill('locomotive')]; await Promise.all(cards.map((c, i) => { const from = human ? this.hud.pilePos(c) : this.hud.oppAnchor(seat); return this.flyCard({ frame: CARD_FRAME[c], from: { ...from, w: human ? HAND_CARD.w : 34, h: human ? HAND_CARD.h : 49 }, to: { ...DISCARD, w: CARD.w, h: CARD.h, angle: -6 + Math.random() * 12 }, duration: 320 * k, delay: i * 55 * k, }); })); playSound(this, SFX.CARD_PLACE); this.animatingRoute = routeId; this.ui.holdScores = true; this.gs = next; this.renderAll(); // 2. A locomotive steams along the route laying the cars. await this.layRoute(seat, routeId, prev, k); this.animatingRoute = null; // 3. Stations flash; the points float up and the marker hops round the track. const r = ROUTES[routeId]; for (const cid of [r.a, r.b]) this.flashCity(cid, PLAYER_COLORS[next.players[seat].colorIndex].hex); const pts = ROUTE_SCORE[r.length]; const m = this.midCache[routeId]; await this.floatPoints(`+${pts}`, m.x, m.y - 10, this.markerSpot(seat, this.markerScore[seat])); await this.moveMarker(seat, L.publicScore(next, seat), { stepMs: Math.round(30 * k) }); this.ui.holdScores = false; this.renderAll(); // 4. Tickets the human just completed get stamped (the rail does it) + a shimmer. if (human) { const was = new Set(L.ticketStatus(prev, 0).filter((t) => t.done).map((t) => t.id)); const now = L.ticketStatus(next, 0).filter((t) => t.done && !was.has(t.id)); for (const t of now) { playSound(this, SFX.VICTORY_SHORT); this.flash(`Ticket complete: ${CITIES[t.a].name} → ${CITIES[t.b].name} (+${t.points})`, '#9ff0a8'); await this.shimmerTicket(t); } } this.afterAction(prev); } async layRoute(seat, routeId, prev, k) { const r = ROUTES[routeId]; let segs = this.segCache[routeId].map((s) => ({ ...s })); // Start from the end already joined to this player's network. const touches = (cid) => prev.players[seat].routes.some((x) => ROUTES[x].a === cid || ROUTES[x].b === cid); let start = CITIES[r.a], end = CITIES[r.b]; if (!touches(r.a) && touches(r.b)) { segs = segs.reverse(); [start, end] = [end, start]; } const ci = this.gs.players[seat].colorIndex; const loco = this.add.image(start.x, start.y, `ttr-loco-${ci}`).setDisplaySize(32, 14).setDepth(D.loco); if (r.length >= 4 || seat === 0) whistle(this, { dur: 0.7, vol: 0.08, pitch: 1 + (seat % 3) * 0.06 }); const sprites = []; this.carSprites.set(routeId, sprites); let ang = Math.atan2(segs[0].cy - start.y, segs[0].cx - start.x); loco.setRotation(ang); let px = start.x, py = start.y; for (const seg of segs) { const dist = Math.hypot(seg.cx - px, seg.cy - py); ang = Math.atan2(seg.cy - py, seg.cx - px); loco.setRotation(ang); await this.tw({ targets: loco, x: seg.cx, y: seg.cy, duration: Math.max(90, dist * 3.2) * k, ease: 'Linear' }); if (this.ended) return; sprites.push(...this.placeCar(seg, ci, true)); this.steam.explode(2, seg.cx, seg.cy - 4); playSound(this, SFX.PIECE_CLICK); chuff(this); px = seg.cx; py = seg.cy; } ang = Math.atan2(end.y - py, end.x - px); loco.setRotation(ang); await this.tw({ targets: loco, x: end.x, y: end.y, alpha: 0, duration: 260 * k, ease: 'Sine.easeIn' }); this.steam.explode(6, end.x, end.y - 6); loco.destroy(); } placeCar(seg, ci, pop = false) { const sw = seg.w * (CAR_TEX.w + 16) / CAR_TEX.w, sh = seg.h * (CAR_TEX.h + 16) / CAR_TEX.h; const shadow = this.add.image(seg.cx + 2, seg.cy + 3, 'ttr-car-shadow').setDisplaySize(sw, sh).setRotation(seg.angle).setDepth(D.carShadow); const car = this.add.image(seg.cx, seg.cy, `ttr-car-${ci}`).setDisplaySize(seg.w, seg.h + 1).setRotation(seg.angle).setDepth(D.car); if (pop) { const sx = car.scaleX, sy = car.scaleY; car.setScale(sx * 1.35, sy * 1.35).setAlpha(0.4); this.tweens.add({ targets: car, scaleX: sx, scaleY: sy, alpha: 1, duration: 160, ease: 'Back.easeOut' }); shadow.setAlpha(0); this.tweens.add({ targets: shadow, alpha: 1, duration: 200 }); } return [shadow, car]; } afterAction(prev) { if (!prev.endTriggered && this.gs.endTriggered && this.gs.triggerSeat != null) { const who = this.gs.triggerSeat === 0 ? 'You are' : `${L.playerName(this.gs, this.gs.triggerSeat)} is`; this.finalRoundBanner(`${who} down to ${this.gs.players[this.gs.triggerSeat].trainsLeft} trains — one last turn each!`); } } // ── tickets ──────────────────────────────────────────────────────────────────── promptTickets() { if (this.modal || this.busy) return; const pend = this.gs.pendingTickets; this.modal = openTicketChooser(this, { pend, hud: this.hud, depth: D.modal, estimate: (t) => this.estimateTicket(t), onHover: (t) => { this.hl.ticket = t; this.renderHighlights(); }, onToggle: () => playSound(this, SFX.PIECE_CLICK), onConfirm: (keep) => { this.modal = null; const returned = pend.drawn.length - keep.length; this.gs = L.resolveTicketKeep(this.gs, 0, keep); playSound(this, SFX.CARD_PLACE); this.runHuman(async () => { this.renderAll(); if (returned > 0) await this.flyTickets({ x: PAD.x + PAD.w / 2, y: PAD.y + 400 }, TICKET_BOX, returned, 0.8, true); }); }, }); this.modal.sticky = true; // a decision is required — Esc can't dismiss it } // After a menu/log closes: re-offer anything the human was owed meanwhile. resumeIfNeeded() { if (this.ended || this.modal || this.busy || !this.gs) return; if (this.gs.pendingTickets?.seat === 0) this.promptTickets(); else this.renderAll(); } ticketNeed(t) { if (t.done) return 0; const p = AI.shortestRoutePath(this.gs, t.a, t.b, 0); return p ? p.cost : Infinity; } estimateTicket(t) { const p = AI.shortestRoutePath(this.gs, t.a, t.b, 0); const need = p ? p.cost : Infinity; const overlap = []; if (p) { const mine = new Set(p.routeIds); for (const h of L.ticketStatus(this.gs, 0)) { if (h.done) continue; const hp = AI.shortestRoutePath(this.gs, h.a, h.b, 0); if (hp && hp.routeIds.some((rid) => mine.has(rid))) overlap.push(`${CITIES[h.a].name}–${CITIES[h.b].name}`); } } return { need, overlap: overlap.slice(0, 2) }; } async shimmerTicket(t) { // Light the human's connecting track, city to city. const path = this.networkPath(0, t.a, t.b); for (const rid of path) { for (const seg of this.segCache[rid]) { const s = this.add.image(seg.cx, seg.cy, 'ttr-glow').setDisplaySize(seg.w * 1.6, 34) .setRotation(seg.angle).setTint(0xfff1a0).setBlendMode('ADD').setDepth(D.fx).setAlpha(0); this.tweens.add({ targets: s, alpha: 0.9, duration: 120, yoyo: true, hold: 120, onComplete: () => s.destroy() }); } await this.wait(70); } this.flashCity(t.a, 0x9ff0a8); this.flashCity(t.b, 0x9ff0a8); this.sparks.explode(18, CITIES[t.b].x, CITIES[t.b].y); } // BFS over a seat's own routes between two cities → route ids. networkPath(seat, a, b) { const adj = new Map(); for (const rid of this.gs.players[seat].routes) { const r = ROUTES[rid]; for (const [x, y] of [[r.a, r.b], [r.b, r.a]]) { if (!adj.has(x)) adj.set(x, []); adj.get(x).push([y, rid]); } } const prev = new Map([[a, null]]); const q = [a]; while (q.length) { const u = q.shift(); if (u === b) break; for (const [v, rid] of adj.get(u) || []) if (!prev.has(v)) { prev.set(v, [u, rid]); q.push(v); } } if (!prev.has(b)) return []; const out = []; for (let c = b; prev.get(c); c = prev.get(c)[0]) out.unshift(prev.get(c)[1]); return out; } // ── rendering ─────────────────────────────────────────────────────────────────── uiState() { return { myTurn: this.canHumanActIgnoringBusy(), suppressHand: this.ui.suppressHand, holdScores: this.ui.holdScores, hiddenMarket: this.ui.hiddenMarket, need: (t) => this.ticketNeed(t), }; } canHumanActIgnoringBusy() { const s = this.gs; return !!s && (s.phase === 'turn' || s.phase === 'lastRound') && s.currentPlayer === 0 && !s.pendingTickets && s.winner == null; } renderAll() { if (!this.gs || !this.hud) return; this.renderCars(); this.hud.render(this.gs, this.uiState()); this.renderHighlights(); this.renderStatus(); if (!this.ui.holdScores) this.syncMarkers(); } syncMarkers() { let moved = false; this.gs.players.forEach((p, seat) => { const v = L.publicScore(this.gs, seat); if (this.markerScore[seat] !== v && !this._ceremony) { this.markerScore[seat] = v; moved = true; } }); if (moved) this.placeMarkers(); } renderCars() { for (const [rid, owner] of Object.entries(this.gs.claimed)) { const id = Number(rid); if (this.carSprites.has(id) || id === this.animatingRoute) continue; const ci = this.gs.players[owner].colorIndex; this.carSprites.set(id, this.segCache[id].flatMap((seg) => this.placeCar(seg, ci))); } } renderStatus() { const s = this.gs; let msg = '', tone = 'plain'; const final = s.phase === 'lastRound' && s.finalTurnsLeft != null; if (s.phase === 'gameOver') msg = ''; else if (s.pendingTickets) { msg = s.pendingTickets.seat === 0 ? (s.pendingTickets.context === 'setup' ? 'Choose your first destination tickets' : 'Choose which tickets to keep') : `${L.playerName(s, s.pendingTickets.seat)} is studying tickets…`; tone = s.pendingTickets.seat === 0 ? 'you' : 'plain'; } else if (s.currentPlayer === 0) { const la = L.legalActions(s, 0); tone = 'you'; if (!la.any) msg = 'No moves left — press Pass'; else if (s.drawnThisTurn === 1) msg = 'Draw one more train card'; else msg = 'Your turn — claim a route, draw 2 cards, or draw tickets'; } else { msg = `${L.playerName(s, s.currentPlayer)} is planning…`; } if (final && msg) { msg = `FINAL ROUND · ${s.finalTurnsLeft} turn${s.finalTurnsLeft === 1 ? '' : 's'} left — ${msg}`; tone = 'final'; } this.setStatus(msg, tone); const stuck = this.canHumanActIgnoringBusy() && !L.legalActions(s, 0).any; if (stuck !== this.passBtn.visible) { this.passBtn.setVisible(stuck); if (stuck) this.tweens.add({ targets: this.passBtn, scale: { from: 1.08, to: 1 }, duration: 500, yoyo: true, repeat: 3 }); } } // Map highlights: claimable routes, a hovered hand colour, a ticket's path, // an opponent's network, the longest trail, and the hovered route itself. renderHighlights() { const g = this.glowGfx, top = this.topGfx; if (!g || !this.gs) return; g.clear(); top.clear(); this.cityGlows.forEach((c) => c.setVisible(false)); const gs = this.gs, me = gs.players[0]; const freeTurn = this.canHumanActIgnoringBusy() && gs.drawnThisTurn === 0; if (this.settings.showAffordable && freeTurn) { for (const c of L.legalClaims(gs, 0)) this.glowRoute(g, c.routeId, 0x8fe39a, 0.85); } if (this.hl.pile) { const pile = this.hl.pile; const col = pile === 'locomotive' ? 0xffd36b : inkInt(pile); for (const r of ROUTES) { if (gs.claimed[r.id] != null || !L.routeClaimable(gs, 0, r.id)) continue; const match = pile === 'locomotive' || r.color === pile || r.color === 'gray'; if (!match) continue; const opts = L.paymentOptions(me, r); const payable = pile === 'locomotive' ? opts.length > 0 : opts.some((o) => o.color === pile); this.glowRoute(g, r.id, col, payable ? 1 : 0.35); } } if (this.hl.opp != null) { for (const rid of gs.players[this.hl.opp].routes) this.glowRoute(top, rid, 0xffffff, 0.9, true); } if (this.hl.longest) { const lead = L.longestLeaders(gs); for (const s of lead.seats) for (const rid of L.longestTrail(gs, s).routes) this.glowRoute(top, rid, 0xffd36b, 1, true); } if (this.hl.ticket) { const t = this.hl.ticket; const p = AI.shortestRoutePath(gs, t.a, t.b, 0); const ok = !!p; this.cityGlow(t.a, ok ? 0xfff0a0 : 0xff6a5a); this.cityGlow(t.b, ok ? 0xfff0a0 : 0xff6a5a); if (p) for (const rid of p.routeIds) this.glowRoute(top, rid, gs.claimed[rid] === 0 ? 0x9ff0a8 : 0xffd36b, 1, gs.claimed[rid] === 0); } if (this.hl.route != null) { const id = this.hl.route; const r = ROUTES[id]; if (gs.claimed[id] == null) { const lock = L.routeLockReason(gs, 0, id); const can = !lock && L.paymentOptions(me, r).length > 0; const col = lock ? 0xb0a090 : can ? 0x6fe07f : 0xff8a6a; this.glowRoute(top, id, col, 1, true); this.cityGlow(r.a, 0xfff0c0, 0.6); this.cityGlow(r.b, 0xfff0c0, 0.6); this.routeZones[id].input.cursor = freeTurn && can ? 'pointer' : 'default'; } else { this.glowRoute(top, id, 0xffffff, 0.8, true); } } } glowRoute(g, id, color, alpha, strong = false) { for (const seg of this.segCache[id]) { const w = seg.w, h = seg.h; g.save(); g.translateCanvas(seg.cx, seg.cy); g.rotateCanvas(seg.angle); g.lineStyle(strong ? 7 : 6, color, alpha * 0.35); g.strokeRoundedRect(-w / 2 - 4, -h / 2 - 4, w + 8, h + 8, 6); g.lineStyle(2, color, alpha); g.strokeRoundedRect(-w / 2 - 1.5, -h / 2 - 1.5, w + 3, h + 3, 4); g.restore(); } } cityGlow(cid, tint, alpha = 1) { const g = this.cityGlows[cid]; g.setVisible(true).setTint(tint); g.baseAlpha = alpha; } flashCity(cid, tint) { const c = CITIES[cid]; const g = this.add.image(c.x, c.y, 'ttr-glow').setTint(tint).setBlendMode('ADD').setDepth(D.fx).setDisplaySize(30, 30); this.tweens.add({ targets: g, displayWidth: 110, displayHeight: 110, alpha: 0, duration: 650, onComplete: () => g.destroy() }); } routeTooltip(id) { const gs = this.gs; if (!gs) return null; const r = ROUTES[id]; const title = `${CITIES[r.a].name} – ${CITIES[r.b].name}`; const colorName = r.color === 'gray' ? 'Gray (any one colour)' : CARD_LABEL[r.color]; const lines = [{ text: `${r.length} × ${colorName} · ${ROUTE_SCORE[r.length]} points` }]; const owner = gs.claimed[id]; if (owner != null) { lines.push({ text: owner === 0 ? 'Your route.' : `Claimed by ${L.playerName(gs, owner)}.`, color: hexStr(PLAYER_COLORS[gs.players[owner].colorIndex].hex) }); return { title, lines }; } const lock = L.routeLockReason(gs, 0, id); if (lock) { lines.push({ text: lock, color: COLORS.dangerHex }); return { title, lines }; } const opts = L.paymentOptions(gs.players[0], r); if (opts.length) { const o = opts[0]; const pay = [o.colorCount ? `${o.colorCount} ${CARD_LABEL[o.color].toLowerCase()}` : null, o.locos ? `${o.locos} loco` : null].filter(Boolean).join(' + '); lines.push({ text: `You can pay ${pay} ✓`, color: '#8fe39a' }); if (gs.currentPlayer !== 0) lines.push({ text: 'Wait for your turn to claim it.', color: COLORS.mutedHex }); else if (gs.drawnThisTurn > 0) lines.push({ text: 'Not this turn — you are drawing cards.', color: COLORS.mutedHex }); else lines.push({ text: 'Click to claim.', color: COLORS.mutedHex }); } else { lines.push({ text: this.shortfall(id), color: '#ffb08a' }); } if (r.doubleGroup) lines.push({ text: gs.playerCount < 4 ? 'Double track: with 2–3 players only one side can be used.' : 'Double track: one player may own only one side.', color: COLORS.mutedHex }); return { title, lines }; } // ── FX helpers ────────────────────────────────────────────────────────────────── tw(cfg) { return new Promise((res) => { if (this.ended) { res(); return; } this.tweens.add({ ...cfg, onComplete: () => { cfg.onDone?.(); res(); } }); }); } wait(ms) { return new Promise((res) => { if (this.ended) res(); else this.time.delayedCall(ms, res); }); } // A card flight. from/to: {x,y,w,h,angle}. back: start face-down; flipEnd: // flip on arrival (market deal), otherwise flip at `reveal` (or mid-flight). async flyCard({ frame, from, to, duration = 320, delay = 0, back = false, flipEnd = false, reveal = null, lift = false }) { if (delay) await this.wait(delay); if (this.ended) return; const img = this.add.image(from.x, from.y, 'ttr-cards', back ? CARD_FRAME.back : frame) .setDisplaySize(from.w, from.h).setAngle(from.angle ?? 0).setDepth(D.flight); const sh = this.add.image(from.x + 4, from.y + 8, 'ttr-card-shadow').setDisplaySize(from.w + 30, from.h + 30).setAlpha(0.6).setDepth(D.flight - 0.5); const flip = async (w) => { const sy = img.scaleY; await this.tw({ targets: img, scaleX: 0, duration: 90 }); img.setFrame(frame); await this.tw({ targets: img, scaleX: w / 270, scaleY: sy, duration: 90 }); }; const scaleOf = (r) => ({ scaleX: r.w / 270, scaleY: r.h / 390 }); if (lift) await this.tw({ targets: img, y: from.y - 14, duration: 80 }); if (back && reveal) { await this.tw({ targets: [img], x: reveal.x, y: reveal.y, ...scaleOf(reveal), angle: 0, duration: duration * 0.6, ease: 'Cubic.easeOut' }); sh.setVisible(false); await flip(reveal.w); await this.wait(140); } else if (back && !flipEnd) { sh.setVisible(false); } this.tweens.add({ targets: sh, x: to.x + 4, y: to.y + 8, displayWidth: to.w + 30, displayHeight: to.h + 30, duration, ease: 'Cubic.easeInOut' }); await this.tw({ targets: img, x: to.x, y: to.y, ...scaleOf(to), angle: to.angle ?? 0, duration, ease: 'Cubic.easeInOut' }); if (back && flipEnd) await flip(to.w); img.destroy(); sh.destroy(); } async flyTickets(from, to, n, scale, back = true) { const w = 124 * scale, h = 76 * scale; await Promise.all(Array.from({ length: n }, (_, i) => (async () => { await this.wait(i * 70); const img = this.add.image(from.x, from.y, 'ttr-ticket-back').setDisplaySize(124, 76).setDepth(D.flight); await this.tw({ targets: img, x: to.x + (i - (n - 1) / 2) * 10, y: to.y + (i - (n - 1) / 2) * 6, displayWidth: w, displayHeight: h, angle: (i - 1) * 5, duration: 320 * (back ? 1 : 1), ease: 'Cubic.easeInOut' }); img.destroy(); })())); } async floatPoints(text, x, y, dest) { const t = this.add.text(x, y, text, { fontFamily: 'Righteous', fontSize: '30px', color: '#ffe48a', stroke: '#3b2a17', strokeThickness: 5, }).setOrigin(0.5).setDepth(D.banner).setScale(0.4); await this.tw({ targets: t, scale: 1, y: y - 28, duration: 260, ease: 'Back.easeOut' }); await this.wait(260); await this.tw({ targets: t, x: dest.x, y: dest.y, scale: 0.45, alpha: 0.6, duration: 420, ease: 'Cubic.easeIn' }); t.destroy(); } flash(message, color = '#ffd86b') { const t = this.add.text(STATUS.x, STATUS.y + 46, message, { fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color, backgroundColor: '#1d140bee', padding: { x: 14, y: 7 }, }).setOrigin(0.5).setDepth(D.banner + 2); this.tweens.add({ targets: t, alpha: 0, y: STATUS.y + 30, delay: 1500, duration: 450, onComplete: () => t.destroy() }); } announce(text) { const t = this.add.text(SHEET.x + SHEET.w / 2, SHEET.y + SHEET.h / 2, text, { fontFamily: DISPLAY, fontSize: '30px', color: '#fff3c8', stroke: '#3b2a17', strokeThickness: 6, align: 'center', }).setOrigin(0.5).setDepth(D.banner).setAlpha(0).setScale(0.8); this.tweens.add({ targets: t, alpha: 1, scale: 1, duration: 260, ease: 'Back.easeOut', onComplete: () => this.tweens.add({ targets: t, alpha: 0, delay: 1300, duration: 400, onComplete: () => t.destroy() }), }); } finalRoundBanner(text) { whistle(this, { dur: 1.6, vol: 0.14 }); const cx = SHEET.x + SHEET.w / 2, cy = SHEET.y + SHEET.h / 2; const g = this.add.graphics().setDepth(D.banner); g.fillStyle(0x000000, 0.4).fillRect(cx - 520, cy - 58, 1040, 128); g.fillStyle(0x9a2a1e, 1).fillRect(cx - 500, cy - 64, 1000, 120); g.lineStyle(2, 0xffd0a0, 0.9).strokeRect(cx - 492, cy - 56, 984, 104); const t1 = this.add.text(cx, cy - 22, 'FINAL ROUND', { fontFamily: DISPLAY, fontSize: '44px', color: '#fff0d0' }).setOrigin(0.5).setDepth(D.banner + 1); const t2 = this.add.text(cx, cy + 26, text, { fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: '#ffe0c0' }).setOrigin(0.5).setDepth(D.banner + 1); const all = [g, t1, t2]; all.forEach((o) => o.setAlpha(0)); this.tweens.add({ targets: all, alpha: 1, duration: 300, onComplete: () => this.tweens.add({ targets: all, alpha: 0, delay: 2200, duration: 500, onComplete: () => all.forEach((o) => o.destroy()) }), }); } // ── menus ──────────────────────────────────────────────────────────────────────── closeModal() { this.modal?.close(); this.modal = null; } openMenu() { if (this.modal || !this.hud) return; this.tooltip.hide(); this.modal = openPauseMenu(this, { settings: this.settings, depth: D.modal, onChange: (key, v) => { this.settings[key] = v; this.saveSettings(); if (key === 'showAffordable') { this.refreshRoutesBtn(); this.renderHighlights(); } }, onRules: () => new TutorialModal(this.gameDef).open(), onLeave: () => { this.modal = confirmBox(this, { heading: 'Leave the game?', text: 'This game will be abandoned.', yes: 'Leave', depth: D.modal + 10, onYes: () => { this.modal = null; this.scene.start('GameMenu'); }, onNo: () => { this.modal = null; this.resumeIfNeeded(); }, }); }, onClose: () => { this.modal = null; this.time.delayedCall(0, () => this.resumeIfNeeded()); }, }); } openLogView() { if (this.modal || !this.gs) return; this.tooltip.hide(); this.modal = openLog(this, { log: this.gs.log, depth: D.modal, onClose: () => { this.modal = null; this.time.delayedCall(0, () => this.resumeIfNeeded()); }, }); } // ── game over ──────────────────────────────────────────────────────────────────── onGameOver() { if (this._ceremony) return; this._ceremony = true; this.closeModal(); this.tooltip.hide(); this.hl = { route: null, pile: null, ticket: null, opp: null, longest: false }; this.renderHighlights(); this.recordHistory(); showTicketToRideEndScreen(this, { depth: D.banner + 4, onPlayAgain: () => this.scene.restart(this.initData), onLeave: () => this.scene.start('GameMenu'), }); } async recordHistory() { const totals = this.gs.scores.map((sc) => sc.total); const result = this.gs.winner === 0 ? 'win' : 'loss'; try { await api.post('/history/single-player', { slug: 'tickettoride', score: totals[0], opponentScores: totals.slice(1), result, }); } catch (_) { /* offline / not signed in — ignore */ } } }