// Civilization (Civ II-lite) — main Phaser scene. // // Phases: setup -> playing -> over. Setup picks a leader character (the // standard opponents double as civilizations), world size, rival count and // difficulty. The engine (CivilizationLogic) is headless; this scene drives it // and renders through CivilizationMapView. AI rivals play via CivilizationAI. import * as Phaser from 'phaser'; import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; import { Button } from '../../ui/Button.js'; import { TextInput } from '../../ui/TextInput.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; import { compileRules, turnToYear, formatYear } from './CivilizationRules.js'; import * as Logic from './CivilizationLogic.js'; import { runAITurn, respondToProposal } from './CivilizationAI.js'; import { CivilizationMapView } from './CivilizationMapView.js'; import { openCityScreen } from './CivilizationCityScreen.js'; import { openTechScreen, openDiplomacyScreen, openSpaceshipScreen, showVictoryOverlay, } from './CivilizationScreens.js'; const FONT = '"Julius Sans One"'; const SAVE_KEY = 'civilization-save'; const D = { hud: 30, modal: 60, toast: 80 }; export default class CivilizationGame extends Phaser.Scene { constructor() { super('CivilizationGame'); } init(data) { this.gameDef = data.game ?? { slug: 'civilization', name: 'Civilization' }; this.state = null; this.view = null; this.phase = 'setup'; this.modalOpen = false; this.busy = false; this.endTurnFlashTween = null; } create() { this.rules = compileRules(this.cache.json.get('civilization-rules')); this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x0a0d12) .setDepth(-10); this.hudRoot = this.add.container(0, 0).setDepth(D.hud); this.modalRoot = this.add.container(0, 0).setDepth(D.modal); this.toastRoot = this.add.container(0, 0).setDepth(D.toast); this.setupRoot = null; this.toasts = []; this.keys = this.input.keyboard.addKeys('UP,DOWN,LEFT,RIGHT,Q,E,Z,C,W,A,S,D,B,F,G,I,M,N,O,R,T,SPACE,ENTER'); this.escHandler = () => this.onEscape(); this.input.keyboard.on('keydown-ESC', this.escHandler); this.events.once('shutdown', () => { this.input.keyboard.off('keydown-ESC', this.escHandler); this.view?.destroy(); }); try { const music = this.cache.json.get('music'); if (music?.tracks) this.music = new MusicPlayer(this, music.tracks); } catch (_) { /* optional */ } this.opponentsData = []; fetch('data/opponents.json') .then((r) => r.json()) .then((json) => { this.opponentsData = json.opponents ?? []; this.showSetup(); }) .catch(() => { this.opponentsData = []; this.showSetup(); }); } onEscape() { if (this.modalOpen) return; // modals close themselves if (this.phase === 'playing') this.openMenu(); else this.scene.start('GameMenu'); } // =========================================================================== // Setup phase showSetup() { this.phase = 'setup'; this.setupRoot?.destroy(true); this.setupRoot = this.add.container(0, 0).setDepth(10); const root = this.setupRoot; const cx = GAME_WIDTH / 2; root.add(this.add.text(cx, 52, 'CIVILIZATION', { fontFamily: 'Righteous', fontSize: '54px', color: COLORS.accentHex, }).setOrigin(0.5)); root.add(this.add.text(cx, 100, 'Build an empire to stand the test of time', { fontFamily: FONT, fontSize: '20px', color: COLORS.mutedHex, }).setOrigin(0.5)); // --- leader pick grid root.add(this.add.text(cx, 150, 'CHOOSE YOUR LEADER', { fontFamily: FONT, fontSize: '24px', color: COLORS.textHex, }).setOrigin(0.5)); const leaders = this.opponentsData.length ? this.opponentsData : Array.from({ length: 8 }, (_, i) => ({ id: `leader${i}`, name: `Leader ${i + 1}`, spriteIndex: 0 })); this.setupLeaders = leaders; this.pickedLeader = this.pickedLeader ?? 0; const perRow = 15; const cell = 96; const gridW = Math.min(leaders.length, perRow) * cell; const gx = cx - gridW / 2 + cell / 2; const gy = 214; this.leaderMarks = []; leaders.forEach((op, i) => { const x = gx + (i % perRow) * cell; const y = gy + Math.floor(i / perRow) * (cell + 18); const ring = this.add.circle(x, y, 40, COLORS.panel) .setStrokeStyle(3, i === this.pickedLeader ? COLORS.gold : COLORS.muted); let face; if (this.textures.exists('opponents')) { face = this.add.image(x, y, 'opponents', op.spriteIndex ?? 0).setDisplaySize(72, 72); const maskShape = this.make.graphics({ add: false }); maskShape.fillStyle(0xffffff); maskShape.fillCircle(x, y, 36); face.setMask(maskShape.createGeometryMask()); } else { face = this.add.text(x, y, op.name[0], { fontFamily: 'Righteous', fontSize: '34px', color: COLORS.textHex, }).setOrigin(0.5); } const label = this.add.text(x, y + 52, op.name, { fontFamily: FONT, fontSize: '14px', color: i === this.pickedLeader ? COLORS.goldHex : COLORS.mutedHex, }).setOrigin(0.5); ring.setInteractive({ useHandCursor: true }); ring.on('pointerdown', () => { this.pickedLeader = i; this.leaderMarks.forEach((m, j) => { m.ring.setStrokeStyle(3, j === i ? COLORS.gold : COLORS.muted); m.label.setColor(j === i ? COLORS.goldHex : COLORS.mutedHex); }); }); this.leaderMarks.push({ ring, label }); root.add([ring, face, label]); }); const rowsUsed = Math.ceil(leaders.length / perRow); let oy = gy + rowsUsed * (cell + 18) + 40; // --- option rows this.setupOpts = this.setupOpts ?? { sizeId: 'medium', opponents: 3, difficultyId: 'prince' }; const mkRow = (label, options, current, onPick) => { root.add(this.add.text(cx - 560, oy, label, { fontFamily: FONT, fontSize: '22px', color: COLORS.textHex, }).setOrigin(0, 0.5)); const marks = []; const startX = cx - 260; options.forEach((opt, i) => { const w = Math.max(90, opt.label.length * 13 + 30); const x = startX + options.slice(0, i).reduce((a, o) => a + Math.max(90, o.label.length * 13 + 30) + 14, 0); const rect = this.add.rectangle(x + w / 2, oy, w, 44, COLORS.panel) .setStrokeStyle(2, opt.value === current ? COLORS.gold : COLORS.muted); const txt = this.add.text(x + w / 2, oy, opt.label, { fontFamily: FONT, fontSize: '19px', color: opt.value === current ? COLORS.goldHex : COLORS.textHex, }).setOrigin(0.5); rect.setInteractive({ useHandCursor: true }); rect.on('pointerdown', () => { onPick(opt.value); marks.forEach((m, j) => { m.rect.setStrokeStyle(2, options[j].value === opt.value ? COLORS.gold : COLORS.muted); m.txt.setColor(options[j].value === opt.value ? COLORS.goldHex : COLORS.textHex); }); }); marks.push({ rect, txt }); root.add([rect, txt]); }); oy += 62; }; mkRow('World Size', this.rules.worldSizeList.map((w) => ({ label: `${w.name} (${w.cols}×${w.rows})`, value: w.id })), this.setupOpts.sizeId, (v) => { this.setupOpts.sizeId = v; }); mkRow('Rival Civilizations', [2, 3, 4, 5, 6, 7].map((n) => ({ label: `${n}`, value: n })), this.setupOpts.opponents, (v) => { this.setupOpts.opponents = v; }); mkRow('Difficulty', this.rules.difficultyList.map((d) => ({ label: d.name, value: d.id })), this.setupOpts.difficultyId, (v) => { this.setupOpts.difficultyId = v; }); oy += 8; const startBtn = new Button(this, cx - (this.hasSave() ? 160 : 0), oy + 20, 'BEGIN', () => { this.startNewGame(); }, { width: 280, height: 64, fontSize: 30 }); root.add(startBtn); if (this.hasSave()) { const resumeBtn = new Button(this, cx + 160, oy + 20, 'RESUME GAME', () => { this.resumeGame(); }, { width: 280, height: 64, fontSize: 26, variant: 'ghost' }); root.add(resumeBtn); } } hasSave() { try { return !!localStorage.getItem(SAVE_KEY); } catch (_) { return false; } } startNewGame() { const { sizeId, opponents, difficultyId } = this.setupOpts; const pool = this.setupLeaders; const me = pool[this.pickedLeader]; const rivals = pool.filter((_, i) => i !== this.pickedLeader); // Shuffle rivals with Math.random (game determinism starts at engine seed). for (let i = rivals.length - 1; i > 0; i -= 1) { const j = Math.floor(Math.random() * (i + 1)); [rivals[i], rivals[j]] = [rivals[j], rivals[i]]; } const leaders = [me, ...rivals.slice(0, opponents)] .map((op) => ({ id: op.id, name: op.name })); const seed = (Date.now() % 1000000) + 1; try { this.state = Logic.createGame(this.rules, { sizeId, seed, difficultyId, leaders, humanIndex: 0, }); } catch (err) { this.toast(`World generation failed — try again (${err.message})`); return; } this.leaderPool = leaders; this.beginPlaying(); } resumeGame() { try { const state = Logic.deserialize(localStorage.getItem(SAVE_KEY)); if (!state) { this.toast('Saved game is from an old version'); localStorage.removeItem(SAVE_KEY); return; } this.state = state; this.beginPlaying(true); } catch (_) { this.toast('Could not load the save'); } } saveGame() { try { localStorage.setItem(SAVE_KEY, Logic.serialize(this.state)); } catch (_) { /* full */ } } clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* noop */ } } // =========================================================================== // Playing phase beginPlaying(resumed = false) { this.phase = 'playing'; this.setupRoot?.destroy(true); this.setupRoot = null; this.view = new CivilizationMapView(this, this.rules, this.state, { onCityClick: (city) => this.onCityClick(city), }); this.view.buildMinimap(16, GAME_HEIGHT - 260, 300); this.buildHud(); this.bindPointer(); const human = this.state.civs[this.state.humanIndex]; const capital = Logic.civCities(this.state, human.id)[0]; const firstUnit = Logic.civUnits(this.state, human.id)[0]; const focus = capital ?? firstUnit; if (focus) this.view.centerOn(focus.x, focus.y); if (!resumed || this.state.current !== this.state.humanIndex) { // Fresh games (and saves mid-AI-round) run up to the human turn. this.runToHumanTurn(); } else { this.startHumanTurn(false); } } buildHud() { this.hudRoot.removeAll(true); const bar = this.add.rectangle(GAME_WIDTH / 2, 28, GAME_WIDTH, 56, COLORS.panel, 0.95) .setStrokeStyle(1, COLORS.accent, 0.6); this.hudRoot.add(bar); this.hudText = this.add.text(20, 28, '', { fontFamily: FONT, fontSize: '21px', color: COLORS.textHex, }).setOrigin(0, 0.5); this.hudRoot.add(this.hudText); const mkBtn = (x, label, fn, w = 150) => { const b = new Button(this, x, 28, label, fn, { width: w, height: 42, fontSize: 18 }); this.hudRoot.add(b); return b; }; mkBtn(GAME_WIDTH - 860, 'TECH', () => this.openTech()); mkBtn(GAME_WIDTH - 700, 'DIPLOMACY', () => this.openDiplomacy(), 170); mkBtn(GAME_WIDTH - 530, 'SPACESHIP', () => this.openSpaceship(), 170); mkBtn(GAME_WIDTH - 370, 'MENU', () => this.openMenu(), 120); this.endTurnBtn = new Button(this, GAME_WIDTH - 210, 28, 'END TURN', () => this.onEndTurn(), { width: 180, height: 42, fontSize: 18, bg: COLORS.gold, textColor: COLORS.textDarkHex }); this.hudRoot.add(this.endTurnBtn); // Right-side unit/terrain panel. this.unitPanel = this.add.container(GAME_WIDTH - 300, 80); const panelBg = this.add.rectangle(0, 0, 284, 240, COLORS.panel, 0.92) .setOrigin(0, 0).setStrokeStyle(2, COLORS.accent, 0.7); this.unitPanelText = this.add.text(14, 14, '', { fontFamily: FONT, fontSize: '17px', color: COLORS.textHex, wordWrap: { width: 256 }, lineSpacing: 5, }); this.unitPanel.add([panelBg, this.unitPanelText]); this.hudRoot.add(this.unitPanel); this.hintText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT - 24, 'Arrows/QEZC move · B found city · R road · I irrigate · M mine · O fortress · F fortify · Space skip · N next · Enter end turn', { fontFamily: FONT, fontSize: '15px', color: COLORS.mutedHex }).setOrigin(0.5); this.hudRoot.add(this.hintText); this.refreshHud(); } refreshHud() { if (!this.state || this.phase !== 'playing') return; const civ = this.state.civs[this.state.humanIndex]; const year = formatYear(turnToYear(this.state.turn, this.rules.yearCurve)); const gov = this.rules.governments[civ.government].name; const research = civ.researching ? `${this.rules.techs[civ.researching].name} ${civ.beakers}/${Logic.currentResearchCost(this.rules, this.state, civ)}` : '— pick research —'; this.hudText.setText(`${year} Gold: ${civ.gold} Science: ${research} ${gov}`); this.refreshUnitPanel(); } refreshUnitPanel() { const unit = this.selectedUnit(); if (!unit) { this.unitPanelText.setText(this.busy ? 'Rivals are moving…' : 'No unit selected.\nClick a unit or press N.'); return; } const def = this.rules.units[unit.type]; const terr = Logic.terrainAt(this.rules, this.state.world, unit.x, unit.y); const idx = Logic.tileIndex(this.state.world, unit.x, unit.y); const spec = this.state.world.special[idx] >= 0 ? this.rules.specialList[this.state.world.special[idx]].name : null; const lines = [ `${def.name}${unit.vet ? ' (V)' : ''}`, `A${def.attack} D${def.defense} HP ${unit.hp}/${def.hp}`, `Moves: ${(unit.mp / 3).toFixed(unit.mp % 3 ? 1 : 0)}`, `Terrain: ${terr.name}${spec ? ` (${spec})` : ''}`, ]; if (unit.order?.kind === 'work') { lines.push(`Working: ${this.rules.improvements[unit.order.imp].name}`); } if (unit.fortified) lines.push('Fortified'); this.unitPanelText.setText(lines.join('\n')); } // --------------------------------------------------------------------------- // Pointer + keyboard input bindPointer() { let dragStart = null; let dragged = false; this.input.on('pointerdown', (pointer) => { if (this.modalOpen || this.phase !== 'playing') return; dragStart = { x: pointer.x, y: pointer.y, rx: this.view.root.x, ry: this.view.root.y }; dragged = false; }); this.input.on('pointermove', (pointer) => { if (!pointer.isDown || !dragStart || this.modalOpen) return; const dx = pointer.x - dragStart.x; const dy = pointer.y - dragStart.y; if (Math.abs(dx) + Math.abs(dy) > 8) dragged = true; if (dragged) { this.view.root.x = dragStart.rx + dx; this.view.root.y = dragStart.ry + dy; this.view.clampPan(); } }); this.input.on('pointerup', (pointer) => { const wasDrag = dragged; dragStart = null; dragged = false; if (wasDrag || this.modalOpen || this.phase !== 'playing' || this.busy) return; if (pointer.y < 56 || pointer.y > GAME_HEIGHT - 44) return; // HUD bands // Clicks that landed on any interactive object (buttons, minimap, city // banners) are theirs, not the map's. if (this.input.hitTestPointer(pointer).length > 0) return; const tile = this.view.screenToTile(pointer.x, pointer.y); if (tile) this.onTileClick(tile[0], tile[1]); }); this.input.on('wheel', (pointer, objs, dx, dy) => { if (this.modalOpen || this.phase !== 'playing') return; this.view.zoomBy(dy > 0 ? -1 : 1, pointer.x, pointer.y); }); } onTileClick(c, r) { const state = this.state; const human = state.humanIndex; const city = Logic.cityAt(state, c, r); // Fortified units in a city are hidden on the map (see CivilizationMapView) — // clicking the tile should open the city, not select an invisible unit. const myUnits = Logic.unitsAt(state, c, r) .filter((u) => u.civ === human && !(city && u.fortified)); const sel = this.selectedUnit(); // A movable selected unit clicking a different owned city is ambiguous — // ask whether to move it in or just inspect the city. if (city && city.civ === human && sel && sel.mp > 0 && state.current === human && (sel.x !== c || sel.y !== r)) { this.confirmMoveOrInspectCity(sel, city, c, r); return; } if (myUnits.length && (!sel || sel.x !== c || sel.y !== r)) { this.selectUnit(myUnits[0]); return; } if (myUnits.length && sel && sel.x === c && sel.y === r) { // Cycle the stack. const i = myUnits.indexOf(sel); this.selectUnit(myUnits[(i + 1) % myUnits.length]); return; } if (city && city.civ === human && !myUnits.length) { this.onCityClick(city); return; } // Move the selected unit toward the clicked tile. if (sel) this.moveTo(sel, c, r); } moveTo(unit, c, r) { if (this.state.current !== this.state.humanIndex) return; if (Logic.cheb(unit.x, unit.y, c, r) === 1) { this.tryStep(unit, c - unit.x, r - unit.y, true); return; } const path = Logic.findPath(this.rules, this.state, unit, c, r); if (!path) { this.toast('No route there'); return; } this.view.showPath(path); this.walkPath(unit, path); } confirmMoveOrInspectCity(unit, city, c, r) { const name = this.rules.units[unit.type].name; this.confirmDialog(`Move ${name} into ${city.name}, or inspect the city?`, () => this.moveTo(unit, c, r), () => this.onCityClick(city), 'MOVE', 'INSPECT'); } onCityClick(city) { if (city.civ !== this.state.humanIndex || this.modalOpen) return; this.modalOpen = true; openCityScreen(this, this.rules, this.state, city, () => { this.modalOpen = false; this.view.refresh(); this.refreshHud(); }); } update() { if (this.phase !== 'playing' || this.modalOpen || this.busy) return; // Edge-of-keyboard panning. const k = this.keys; const pan = 14; if (k.W.isDown) this.view.panBy(0, pan); if (k.S.isDown && !k.S.shiftKey) this.view.panBy(0, -pan); if (k.A.isDown) this.view.panBy(pan, 0); if (k.D.isDown) this.view.panBy(-pan, 0); if (this.state?.current !== this.state?.humanIndex) return; const sel = this.selectedUnit(); const just = (key) => Phaser.Input.Keyboard.JustDown(key); if (just(k.N)) this.selectNextUnit(); if (just(k.ENTER)) this.onEndTurn(); if (!sel) return; if (just(k.UP)) this.tryStep(sel, 0, -1); else if (just(k.DOWN)) this.tryStep(sel, 0, 1); else if (just(k.LEFT)) this.tryStep(sel, -1, 0); else if (just(k.RIGHT)) this.tryStep(sel, 1, 0); else if (just(k.Q)) this.tryStep(sel, -1, -1); else if (just(k.E)) this.tryStep(sel, 1, -1); else if (just(k.Z)) this.tryStep(sel, -1, 1); else if (just(k.C)) this.tryStep(sel, 1, 1); else if (just(k.SPACE)) { sel.mp = 0; this.selectNextUnit(); } else if (just(k.F)) { sel.fortified = true; sel.mp = 0; this.afterAction(); this.selectNextUnit(); } else if (just(k.B)) this.tryFound(sel); else if (just(k.R)) this.tryWork(sel, this.canRail(sel) ? 'railroad' : 'road'); else if (just(k.I)) this.tryWork(sel, 'irrigation'); else if (just(k.M)) this.tryWork(sel, 'mine'); else if (just(k.O)) this.tryWork(sel, 'fortress'); else if (just(k.T)) this.tryWork(sel, 'transform'); else if (just(k.G)) this.tryCaravan(sel); } canRail(unit) { const bits = this.state.world.improvements[Logic.tileIndex(this.state.world, unit.x, unit.y)]; return (bits & Logic.IMP.ROAD) && this.state.civs[unit.civ].known.railroad; } selectedUnit() { if (!this.state || this.selectedUnitId == null) return null; const u = Logic.unitById(this.state, this.selectedUnitId); if (!u || u.civ !== this.state.humanIndex) return null; return u; } selectUnit(unit) { this.selectedUnitId = unit?.id ?? null; this.view.selectedUnitId = this.selectedUnitId; this.view.showPath(null); if (unit) this.view.centerOnIfOffscreen?.(unit.x, unit.y); this.view.refresh(); this.refreshUnitPanel(); // Nothing left to move this turn — nudge the player toward End Turn. const noneLeft = !unit && this.phase === 'playing' && !this.busy && this.state?.current === this.state?.humanIndex; this.setEndTurnFlash(noneLeft); } setEndTurnFlash(on) { if (on === !!this.endTurnFlashTween) return; if (!on) { this.endTurnFlashTween?.stop(); this.endTurnFlashTween = null; this.endTurnBtn?.setAlpha(1); return; } this.endTurnFlashTween = this.tweens.add({ targets: this.endTurnBtn, alpha: 0.55, duration: 550, yoyo: true, repeat: -1, ease: 'Sine.easeInOut', }); } selectNextUnit() { const units = Logic.civUnits(this.state, this.state.humanIndex) .filter((u) => u.mp > 0 && !u.fortified && !u.sentry && !u.order && !u.carriedBy && this.rules.units[u.type].domain !== 'project'); if (!units.length) { this.selectUnit(null); return; } const curIdx = units.findIndex((u) => u.id === this.selectedUnitId); const next = units[(curIdx + 1) % units.length]; this.selectUnit(next); this.view.centerOn(next.x, next.y); } tryStep(unit, dx, dy, animate = false) { if (this.state.current !== this.state.humanIndex) return; const from = [unit.x, unit.y]; const out = unit.carriedBy ? Logic.disembark(this.rules, this.state, unit, dx, dy) : Logic.tryMove(this.rules, this.state, unit, dx, dy); if (out.result === 'blocked' && out.needsWar !== undefined) { this.confirmWar(out.needsWar, () => { Logic.declareWar(this.rules, this.state, this.state.humanIndex, out.needsWar); this.tryStep(unit, dx, dy, animate); }); return; } if (out.result === 'invalid') return; if (out.hut) this.toastHut(out.hut); const finish = () => { this.afterAction(); if (unit.mp <= 0 && this.state.units.includes(unit)) this.selectNextUnit(); if (!this.state.units.includes(unit)) this.selectNextUnit(); }; const combatEvents = this.collectNewCombatEvents(); if (combatEvents.length) { this.busy = true; this.view.animateCombat(combatEvents, () => { this.busy = false; finish(); }); return; } const moved = unit.x !== from[0] || unit.y !== from[1]; if (!animate || !moved) { finish(); return; } this.animateMoveThen([from, [unit.x, unit.y]], finish); } walkPath(unit, path) { // Resolve the whole turn's worth of movement instantly (combat, huts, // etc. all need the real logic), then replay the tiles actually crossed // as a smooth glide so the player sees continuous motion, not a snap. // A combat step always ends the walk — the rest of the original path // no longer applies once a fight breaks out. const visited = [[unit.x, unit.y]]; let i = 0; let hutEvent = null; while (i < path.length && unit.mp > 0 && this.state.units.includes(unit) && !this.state.over) { const [nx, ny] = path[i]; i += 1; const out = Logic.tryMove(this.rules, this.state, unit, Math.sign(nx - unit.x), Math.sign(ny - unit.y)); if (out.result === 'invalid' || out.result === 'blocked' || out.result === 'combat') break; if (out.hut) hutEvent = out.hut; visited.push([unit.x, unit.y]); } if (hutEvent) this.toastHut(hutEvent); const finish = () => { this.view.showPath(null); this.afterAction(); if (!this.state.units.includes(unit) || unit.mp <= 0) this.selectNextUnit(); }; const combatEvents = this.collectNewCombatEvents(); if (combatEvents.length) { // Walk the peaceful leg of the path first, then play the clash. this.animateMoveThen(visited, () => { this.busy = true; this.view.animateCombat(combatEvents, () => { this.busy = false; finish(); }); }); return; } this.animateMoveThen(visited, finish); } // Picks up any 'combat' events pushed since the last time this ran // (marking them consumed so they never replay), for the caller to animate. collectNewCombatEvents() { const found = []; for (const e of this.state.events) { if (e.type === 'combat' && !e.animated) { e.animated = true; found.push(e); } } return found; } // Glides the selected unit's marker smoothly across `tiles` // ([[c,r], ...], already-resolved positions) over 1s, pauses 250ms at the // destination, then invokes `finish`. Falls straight through to `finish` // when there's nothing to animate (unit didn't actually move). animateMoveThen(tiles, finish) { if (tiles.length < 2) { finish(); return; } this.view.refresh(); this.busy = true; this.view.animateUnitAlong(tiles, 1000, 250, () => { this.busy = false; finish(); }); } tryFound(unit) { const def = this.rules.units[unit.type]; if (!def.flags.includes('settler')) return; if (!Logic.canFoundCity(this.rules, this.state, unit.x, unit.y)) { this.toast('Cannot found a city here'); return; } if (this.modalOpen) return; const defaultName = Logic.peekCityName(this.rules, this.state, unit.civ); this.promptCityName(defaultName, (name) => { const city = Logic.foundCity(this.rules, this.state, unit, name); if (city) { this.toast(`${city.name} founded!`); this.view.repaintTileAndNeighbors(city.x, city.y); this.afterAction(); this.selectNextUnit(); } }); } promptCityName(defaultName, onConfirm) { this.modalOpen = true; const cx = GAME_WIDTH / 2; const cy = GAME_HEIGHT / 2; const root = this.add.container(0, 0).setDepth(D.modal); const dim = this.add.rectangle(cx, cy, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55).setInteractive(); const panel = this.add.rectangle(cx, cy, 560, 240, COLORS.panel).setStrokeStyle(2, COLORS.accent); const title = this.add.text(cx, cy - 84, 'Found City', { fontFamily: 'Righteous', fontSize: '26px', color: COLORS.accentHex, }).setOrigin(0.5); const label = this.add.text(cx, cy - 40, 'Name this city:', { fontFamily: FONT, fontSize: '18px', color: COLORS.textHex, }).setOrigin(0.5); root.add([dim, panel, title, label]); const input = new TextInput(this, cx, cy + 4, { width: 380, height: 48, value: defaultName, maxLength: 24, autocomplete: 'off', }); input.focus(); input.el.select(); const close = () => { input.destroy(); root.destroy(true); this.modalOpen = false; }; const confirm = () => { const name = input.value.trim() || defaultName; close(); onConfirm(name); }; input.on('keydown', (e) => { if (e.key === 'Enter') confirm(); else if (e.key === 'Escape') close(); }); const found = new Button(this, cx - 110, cy + 68, 'FOUND', confirm, { width: 180, height: 52 }); const cancel = new Button(this, cx + 110, cy + 68, 'CANCEL', close, { width: 180, height: 52, variant: 'ghost' }); root.add([found, cancel]); } tryWork(unit, impId) { if (Logic.startWork(this.rules, this.state, unit, impId)) { this.toast(`${this.rules.units[unit.type].name}: building ${this.rules.improvements[impId].name}`); this.afterAction(); this.selectNextUnit(); } else { this.toast(`Cannot build ${this.rules.improvements[impId]?.name ?? impId} here`); } } tryCaravan(unit) { const pair = Logic.canEstablishRoute(this.rules, this.state, unit); if (!pair) { this.toast('Caravans need a city 8+ tiles from home'); return; } const out = Logic.establishTradeRoute(this.rules, this.state, unit); if (out) { this.toast(`Trade route: ${out.from.name} ↔ ${out.to.name} (+${out.bonus} gold & beakers)`); this.afterAction(); this.selectNextUnit(); } } afterAction() { // Repaint tiles that may have changed (work orders complete on turn start, // but roads from engineers etc. show up next refresh — cheap full check // is unnecessary; unit/city layer + HUD is enough here). this.view.refresh(); this.refreshHud(); if (this.state.over) this.onGameOver(); } // --------------------------------------------------------------------------- // Turn cycle startHumanTurn(process = true) { const human = this.state.humanIndex; if (process) Logic.beginCivTurn(this.rules, this.state, human); this.repaintFromEvents(); this.busy = false; this.endTurnBtn?.setAlpha(1); const civ = this.state.civs[human]; if (!civ.alive) { this.onGameOver(); return; } // Research prompt. if (!civ.researching && Logic.availableTechs(this.rules, civ).length) { this.openTech(); } this.presentAIProposals(); this.announceEvents(); this.view.refresh(); this.refreshHud(); this.selectNextUnit(); } onEndTurn() { if (this.busy || this.modalOpen || this.phase !== 'playing') return; if (this.state.current !== this.state.humanIndex) return; Logic.endCivTurn(this.rules, this.state, this.state.humanIndex); this.saveGame(); this.runToHumanTurn(); } runToHumanTurn() { this.setEndTurnFlash(false); this.busy = true; this.endTurnBtn?.setAlpha(0.4); this.refreshUnitPanel(); const stepCiv = () => { if (this.phase !== 'playing') return; if (this.state.over) { this.onGameOver(); return; } if (!this.state.civs[this.state.humanIndex].alive) { this.onGameOver(); return; } const cur = this.state.current; if (cur === this.state.humanIndex) { this.startHumanTurn(true); return; } Logic.beginCivTurn(this.rules, this.state, cur); const before = new Map(Logic.civUnits(this.state, cur).map((u) => [u.id, [u.x, u.y]])); runAITurn(this.rules, this.state, cur); Logic.endCivTurn(this.rules, this.state, cur); // Resolve the whole civ's turn instantly (as ever). Combats play first, // from whatever's still on screen from before this civ acted (no // refresh yet, so a ghost can stand in for a unit that's already dead // or already moved); then one refresh syncs everyone else, and the // remaining units' start/end tiles are diffed and glided — same // "resolve now, animate after" trick as the player's own moves, just // via a before/after snapshot instead of a waypoint path. const combatEvents = this.collectNewCombatEvents(); const visibleCombat = combatEvents.filter((e) => this.view.isTileVisible(e.ax, e.ay) || this.view.isTileVisible(e.x, e.y)); const combatUnitIds = new Set(combatEvents.flatMap((e) => [e.attackerId, e.defenderId])); const moves = []; for (const [id, from] of before) { if (combatUnitIds.has(id)) continue; const u = Logic.unitById(this.state, id); if (!u || u.carriedBy) continue; if (u.x !== from[0] || u.y !== from[1]) moves.push({ unitId: id, from, to: [u.x, u.y] }); } const afterCombat = () => { this.view.refresh(); this.refreshHud(); this.view.animateUnitsAlong(moves, 1000, 250, () => { this.time.delayedCall(90, stepCiv); }); }; if (visibleCombat.length) this.view.animateCombat(visibleCombat, afterCombat); else afterCombat(); }; stepCiv(); } // --------------------------------------------------------------------------- // Events, proposals, toasts // Terrain changes (work orders, founded cities' roads) arrive as engine // events; repaint just those tiles instead of rebaking the world. repaintFromEvents() { for (const e of this.state.events) { if (e.painted) continue; e.painted = true; if (e.type === 'workDone') { this.view.repaintTileAndNeighbors(e.x, e.y); } else if (e.type === 'cityFounded' || e.type === 'cityDestroyed') { const city = Logic.cityById(this.state, e.cityId); if (city) this.view.repaintTileAndNeighbors(city.x, city.y); } } } announceEvents() { const human = this.state.humanIndex; for (const e of this.state.events) { if (e.announced) continue; e.announced = true; if (e.type === 'war' && e.b === human) { this.toast(`${this.state.civs[e.a].name} declares WAR on you!`); } else if (e.type === 'techDone' && e.civ === human) { this.toast(`Research complete: ${this.rules.techs[e.tech].name}`); } else if (e.type === 'cityCaptured' && (e.from === human || e.to === human)) { this.toast(e.to === human ? `You captured ${e.name}!` : `${e.name} has fallen!`); } else if (e.type === 'civEliminated') { this.toast(`${this.state.civs[e.civ].name} has been destroyed`); } else if (e.type === 'spaceshipLaunched') { this.toast(`${this.state.civs[e.civ].name} launched a spaceship!`); } else if (e.type === 'contact' && (e.a === human || e.b === human)) { const other = e.a === human ? e.b : e.a; this.toast(`You have made contact with ${this.state.civs[other].name}`); } } } presentAIProposals() { const human = this.state.humanIndex; const proposals = this.state.events.filter((e) => e.type === 'aiProposal' && e.to === human); this.state.events = this.state.events.filter((e) => !(e.type === 'aiProposal' && e.to === human)); const next = () => { const p = proposals.shift(); if (!p) return; if (!Logic.canPropose(this.state, p.from, human, p.kind)) { next(); return; } const from = this.state.civs[p.from]; this.confirmDialog( `${from.name} proposes a ${p.kind === 'ceasefire' ? 'cease-fire' : p.kind}. Accept?`, () => { Logic.applyTreaty(this.state, p.from, human, p.kind); this.refreshHud(); next(); }, () => next(), ); }; next(); } toastHut(hut) { const msgs = { gold: `You found ${hut.gold} gold in the hut!`, tech: hut.tech ? `The tribe teaches you ${this.rules.techs[hut.tech].name}!` : 'A gift!', unit: `A band of ${hut.unit} joins you!`, ambushWon: 'Hostile tribe! Your unit fought them off.', ambushLost: 'Hostile tribe! Your unit was lost!', }; this.toast(msgs[hut.outcome] ?? 'An empty hut.'); } toast(msg) { const y = 90 + this.toasts.length * 40; const t = this.add.text(GAME_WIDTH / 2, y, msg, { fontFamily: FONT, fontSize: '20px', color: COLORS.textHex, backgroundColor: '#1e1a12ee', padding: { x: 16, y: 7 }, }).setOrigin(0.5).setDepth(D.toast); this.toastRoot.add(t); this.toasts.push(t); this.tweens.add({ targets: t, alpha: 0, delay: 2600, duration: 500, onComplete: () => { this.toasts = this.toasts.filter((x) => x !== t); t.destroy(); }, }); } confirmWar(civIdx, onYes) { const name = this.state.civs[civIdx].name; this.confirmDialog(`Attack ${name}? This means WAR!`, onYes, () => {}); } confirmDialog(message, onYes, onNo, yesLabel = 'YES', noLabel = 'NO') { this.modalOpen = true; const root = this.add.container(0, 0).setDepth(D.modal); const dim = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) .setInteractive(); const panel = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, 640, 220, COLORS.panel) .setStrokeStyle(2, COLORS.accent); const txt = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2 - 40, message, { fontFamily: FONT, fontSize: '24px', color: COLORS.textHex, wordWrap: { width: 580 }, align: 'center', }).setOrigin(0.5); const close = (fn) => () => { root.destroy(true); this.modalOpen = false; fn?.(); }; const yes = new Button(this, GAME_WIDTH / 2 - 110, GAME_HEIGHT / 2 + 50, yesLabel, close(onYes), { width: 180, height: 52 }); const no = new Button(this, GAME_WIDTH / 2 + 110, GAME_HEIGHT / 2 + 50, noLabel, close(onNo), { width: 180, height: 52, variant: 'ghost' }); root.add([dim, panel, txt, yes, no]); } // --------------------------------------------------------------------------- // Screens openTech() { if (this.modalOpen) return; this.modalOpen = true; openTechScreen(this, this.rules, this.state, () => { this.modalOpen = false; this.refreshHud(); }); } openDiplomacy() { if (this.modalOpen) return; this.modalOpen = true; openDiplomacyScreen(this, this.rules, this.state, this.opponentsData, respondToProposal, () => { this.modalOpen = false; this.view.refresh(); this.refreshHud(); }); } openSpaceship() { if (this.modalOpen) return; this.modalOpen = true; openSpaceshipScreen(this, this.rules, this.state, () => { this.modalOpen = false; this.refreshHud(); if (this.state.over) this.onGameOver(); }); } openMenu() { if (this.modalOpen) return; this.modalOpen = true; const root = this.add.container(0, 0).setDepth(D.modal); const dim = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55) .setInteractive(); const panel = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, 460, 340, COLORS.panel) .setStrokeStyle(2, COLORS.accent); const title = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2 - 120, 'MENU', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.accentHex, }).setOrigin(0.5); const close = () => { root.destroy(true); this.modalOpen = false; }; const resume = new Button(this, GAME_WIDTH / 2, GAME_HEIGHT / 2 - 50, 'RESUME', close, { width: 320, height: 56 }); const save = new Button(this, GAME_WIDTH / 2, GAME_HEIGHT / 2 + 20, 'SAVE GAME', () => { this.saveGame(); this.toast('Game saved'); close(); }, { width: 320, height: 56, variant: 'ghost' }); const quit = new Button(this, GAME_WIDTH / 2, GAME_HEIGHT / 2 + 90, 'SAVE & QUIT', () => { this.saveGame(); this.scene.start('GameMenu'); }, { width: 320, height: 56, variant: 'ghost' }); root.add([dim, panel, title, resume, save, quit]); } onGameOver() { if (this.phase === 'over') return; this.phase = 'over'; this.busy = false; this.clearSave(); showVictoryOverlay(this, this.rules, this.state, this.opponentsData, () => { this.scene.restart({ game: this.gameDef }); }); } }