From 0b8affa1ff2f8a921c5af6be3bac266e824f9a31 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Wed, 2 Dec 2026 20:59:44 -0700 Subject: [PATCH] Rebuild Forbidden Island into The Drowning Isle - Renamed the game and re-themed every surface (tiles, relics, roles, tutorial, chat) around a monsoon-expedition narrative with a field-journal UI - Split the monolithic scene into focused modules: layout constants, procedural canvas art, living sea, storm, Web Audio synths, cinematics, briefing dialog, end-screen report, persistent store, worker-backed engine, and tile/figure pieces - Upgraded the AI from greedy 1-ply to a beam-search turn planner with an expected-loss flood model, role-aware distance maps, specialised treasure-collector valuation, and tuned constants from self-play random search - Added four island layouts (Diamond, Atoll, Hook Bay, Serpent), a seeded daily-expedition mode, and mid-game save/resume via localStorage - Added a headless verification script (tools/verifyForbiddenIsland.js) covering setup, give/swim/specials rules, Waters Rise, losses, determinism, public- knowledge fairness, and AI sanity positions --- src/data/gamesRegistry.js | 2 +- .../forbiddenisland/ForbiddenIslandGame.js | 1479 ++++++++++------- src/games/forbiddenisland/IslandAI.js | 694 +++++--- src/games/forbiddenisland/IslandArt.js | 669 ++++++++ src/games/forbiddenisland/IslandChat.js | 175 +- src/games/forbiddenisland/IslandCinematics.js | 224 +++ src/games/forbiddenisland/IslandData.js | 120 +- src/games/forbiddenisland/IslandDialogs.js | 138 ++ src/games/forbiddenisland/IslandEndScreen.js | 149 ++ src/games/forbiddenisland/IslandEngine.js | 85 + src/games/forbiddenisland/IslandLayout.js | 49 + src/games/forbiddenisland/IslandLogic.js | 300 +++- src/games/forbiddenisland/IslandPieces.js | 261 +++ src/games/forbiddenisland/IslandSea.js | 115 ++ src/games/forbiddenisland/IslandSound.js | 205 +++ src/games/forbiddenisland/IslandStore.js | 84 + src/games/forbiddenisland/IslandStorm.js | 86 + src/games/forbiddenisland/IslandTalk.js | 113 ++ src/games/forbiddenisland/IslandWorker.js | 11 + src/games/forbiddenisland/tutorial.md | 217 +-- tools/verifyForbiddenIsland.js | 344 ++++ 21 files changed, 4348 insertions(+), 1172 deletions(-) create mode 100644 src/games/forbiddenisland/IslandArt.js create mode 100644 src/games/forbiddenisland/IslandCinematics.js create mode 100644 src/games/forbiddenisland/IslandDialogs.js create mode 100644 src/games/forbiddenisland/IslandEndScreen.js create mode 100644 src/games/forbiddenisland/IslandEngine.js create mode 100644 src/games/forbiddenisland/IslandLayout.js create mode 100644 src/games/forbiddenisland/IslandPieces.js create mode 100644 src/games/forbiddenisland/IslandSea.js create mode 100644 src/games/forbiddenisland/IslandSound.js create mode 100644 src/games/forbiddenisland/IslandStore.js create mode 100644 src/games/forbiddenisland/IslandStorm.js create mode 100644 src/games/forbiddenisland/IslandTalk.js create mode 100644 src/games/forbiddenisland/IslandWorker.js create mode 100644 tools/verifyForbiddenIsland.js diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index e9104d7..2c7973b 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -67,7 +67,7 @@ registerGame({ slug: 'blokus', name: 'Blokus', category: 'tabletop', minPlayers: registerGame({ slug: 'spellingbee', name: 'Spelling Bee', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 37 }); registerGame({ slug: 'minicrossword', name: 'Mini Crossword', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 38 }); registerGame({ slug: 'tectonic', name: 'Tectonic', category: 'word', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 42 }); -registerGame({ slug: 'forbiddenisland', name: 'Forbidden Island', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 39 }); +registerGame({ slug: 'forbiddenisland', name: 'The Drowning Isle', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 39 }); registerGame({ slug: 'solitairetour', name: 'Solitaire Tour', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 40 }); registerGame({ slug: 'splendor', name: 'Splendor', category: 'cards', cardGame: true, minPlayers: 2, maxPlayers: 4, minOpponents: 1, hasTutorial: true, maxOpponents: 3, iconFrame: 41 }); registerGame({ slug: 'labyrinth', name: 'Labyrinth', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 43, defaultPlayfield: 'fantasy' }); diff --git a/src/games/forbiddenisland/ForbiddenIslandGame.js b/src/games/forbiddenisland/ForbiddenIslandGame.js index 6922544..1d90674 100644 --- a/src/games/forbiddenisland/ForbiddenIslandGame.js +++ b/src/games/forbiddenisland/ForbiddenIslandGame.js @@ -7,32 +7,34 @@ import { createInitialState, cloneState, applyPendingFlood, peekFloodDraw, peekTreasureDraw, legalActions, applyAction, endActions, discardCard, resolveFlood, playSandbags, playHelicopter, attemptEscape, canEscape, - isGameOver, setPriority, capturedCount, handTreasureCounts, swapCards, + isGameOver, setPriority, capturedCount, handTreasureCounts, resolveSwim, } from './IslandLogic.js'; import { TREASURES, TREASURE_KEYS, ROLES, ROLE_KEYS, SPECIAL, MAX_WATER, DIFFICULTY, - floodDrawCount, GRID, CARDS_TO_CAPTURE, HAND_LIMIT, TILE_FRAME_ROW, cardFrame, + floodDrawCount, CARDS_TO_CAPTURE, HAND_LIMIT, TILE_FRAME_ROW, cardFrame, GAME_TITLE, LAYOUTS, } from './IslandData.js'; -import { chooseAction, chooseFreeCard, chooseDiscard, describeIntent, nextThinkDelay } from './IslandAI.js'; -import { lineForIntent, lineForEvent, lineForAck, roleEmoji, roleName, roleColorHex } from './IslandChat.js'; +import { chooseDiscard, nextThinkDelay } from './IslandAI.js'; +import { Engine } from './IslandEngine.js'; +import { lineForIntent, lineForEvent, lineForAck, roleEmoji, roleName, roleColorHex, journalStamp } from './IslandChat.js'; -// ── Layout ────────────────────────────────────────────────────────────────── -const TILE = 110, GAP = 8, PITCH = TILE + GAP; -const BOARD_W = GRID * PITCH - GAP; // 700 -const BX0 = 70; // board left -const BY0 = 158; // board top -const RAIL_X = BX0 + BOARD_W + 50; // right rail left edge (~820) -const RAIL_W = GAME_WIDTH - RAIL_X - 110; // leaves room for water meter +import { + TILE, PITCH, BOARD_W, BX0, BY0, RAIL_X, RAIL_W, JOURNAL, GAUGE, DEPTH, + DISPLAY_FONT, BODY_FONT, TYPE_FONT, INK, tileCenter, +} from './IslandLayout.js'; +import { bakeIslandArt, bakeLeather, BACK, GAUGE_ART, GAUGE_TUBE } from './IslandArt.js'; +import { IslandSea } from './IslandSea.js'; +import { IslandStorm } from './IslandStorm.js'; +import { TileView, Figure } from './IslandPieces.js'; +import * as Sound from './IslandSound.js'; +import * as Cine from './IslandCinematics.js'; +import { reaction, Bubbles } from './IslandTalk.js'; +import { showBriefing } from './IslandDialogs.js'; +import { showEndScreen } from './IslandEndScreen.js'; +import * as Store from './IslandStore.js'; +import { floodForecast } from './IslandAI.js'; -const DEPTH = { bg: 0, board: 5, tile: 10, pawn: 20, ui: 40, popup: 60, banner: 90 }; - -// Tile state colours. -const TC = { - dry: 0x5c7d54, dryStone: 0x7a7059, - flooded: 0x2f6f9f, floodEdge: 0x67b6e0, - sunk: 0x0c2738, - border: 0x2b231a, -}; +// Brass buttons on the journal page. +const BRASS_BTN = { bg: 0x5a3f1a, bgHover: 0xd8b25a, textColor: '#f2e6cc', textHoverColor: '#2b1d08' }; export default class ForbiddenIslandGame extends Phaser.Scene { constructor() { super('ForbiddenIslandGame'); } @@ -73,12 +75,40 @@ export default class ForbiddenIslandGame extends Phaser.Scene { } create() { + this.engine = new Engine(); + this.events.once('shutdown', () => { this.engine?.destroy(); this.engine = null; }); try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch (e) { /* music optional */ } + bakeIslandArt(this); + this.sea = new IslandSea(this); + this.storm = new IslandStorm(this); + this.ambience = new Sound.Ambience(this); + this.bubbles = new Bubbles(this); + this.history = []; // { day, level, flooded, sunk } per day, for the tide chart + this.moments = []; // { day, kind, text } key moments, for the report + this.undoStack = []; // your own turn's earlier states + this.forecastOn = false; + this.daily = null; + this.figures = {}; this.buildBackground(); - - // Roster: human + up to 3 AI partners. Distinct random roles. const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); - const roles = Phaser.Utils.Array.Shuffle(ROLE_KEYS.slice()).slice(0, playerCount); + const saved = Store.loadSave(); + const usable = saved && saved.gs.players.length === playerCount ? saved : null; + this.briefing = showBriefing(this, { + difficulty: this.difficulty, playerCount, saved: usable, + onStart: (choice) => { this.briefing = null; return choice.resume ? this.resumeGame(usable) : this.setupGame(choice); }, + }); + } + + // Deal the island and crew for a new expedition, then play the opening floods. + setupGame({ layout = 'diamond', daily = null, role = null } = {}) { + const playerCount = Math.max(2, Math.min(4, 1 + this.opponents.length)); + this.daily = daily; + let roles; + if (daily) roles = daily.roles.slice(0, playerCount); + else { + const rest = Phaser.Utils.Array.Shuffle(ROLE_KEYS.filter((r) => r !== role)); + roles = role ? [role, ...rest.slice(0, playerCount - 1)] : rest.slice(0, playerCount); + } this.skillBySeat = {}; for (let seat = 0; seat < playerCount; seat++) { if (seat === this.humanSeat) { this.partnerNames[seat] = 'You'; this.skillBySeat[seat] = 5; } @@ -88,222 +118,286 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.skillBySeat[seat] = Math.max(1, Math.min(5, opp?.skill ?? 4)); } } - // All tiles start dry; the 6 initial floods are deferred for the animation. - this.gs = createInitialState({ roles, difficulty: this.difficulty, humanSeat: this.humanSeat, skipInitialFlood: true }); + this.gs = createInitialState({ + roles, difficulty: this.difficulty, humanSeat: this.humanSeat, skipInitialFlood: true, + layout, seed: daily ? daily.seed : undefined, + }); + this.buildTable(); + this.beginGame(); + } + // Pick up a saved expedition exactly where it was left. + resumeGame(saved) { + this.gs = saved.gs; + this.partnerNames = saved.partnerNames; + this.skillBySeat = saved.skillBySeat; + this.seatDirections = saved.seatDirections ?? {}; + this.history = saved.history ?? []; + this.moments = saved.moments ?? []; + this.daily = saved.daily ?? null; + this.messages = saved.messages ?? []; + this.buildTable(); + this.introComplete = true; + this.buildPartnerHUD(); + this.post(null, `Day ${this.gs.round ?? 1}. The expedition resumes. The journal picks up where it left off.`); + this.render(); + this.advance(); + } + + buildTable() { this.buildBoard(); this.buildRail(); this.buildWaterMeter(); this.buildDeckDisplay(); - this.pawnLayer = this.add.container(0, 0).setDepth(DEPTH.pawn); - + this.buildToolbar(); this.render(); - this.showBeginModal(); } - // ── Background ────────────────────────────────────────────────────────────── + // ── Backdrop: sea (IslandSea), storm (IslandStorm) and the field journal ──── buildBackground() { - const g = this.add.graphics().setDepth(DEPTH.bg); - g.fillGradientStyle(0x07314a, 0x07314a, 0x041824, 0x041824, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - this.add.text(GAME_WIDTH / 2, 26, 'Forbidden Island', { - fontFamily: 'Righteous', fontSize: '46px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - new Button(this, GAME_WIDTH - 200, GAME_HEIGHT - 46, 'Leave', () => this.scene.start('GameMenu'), { variant: 'ghost', width: 180, height: 52 }); + this.add.image(JOURNAL.x, JOURNAL.y, 'di-journal').setOrigin(0).setDepth(DEPTH.ui - 2) + .postFX?.addShadow(-4, 6, 0.006, 1.2, 0x000000, 10, 0.7); + this.add.text(RAIL_X, 30, GAME_TITLE, { + fontFamily: DISPLAY_FONT, fontSize: '40px', color: INK.ink, + }).setDepth(DEPTH.ui); + this.add.text(RAIL_X + 2, 74, 'Field journal of the monsoon expedition', { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '16px', color: INK.inkSoft, + }).setDepth(DEPTH.ui); + this.stampText = this.add.text(RAIL_X + RAIL_W - 6, 26, '', { + fontFamily: TYPE_FONT, fontSize: '17px', fontStyle: 'bold', color: INK.red, + }).setOrigin(1, 0).setDepth(DEPTH.ui).setAngle(-3); + new Button(this, GAME_WIDTH - 200, GAME_HEIGHT - 46, 'Leave', () => this.scene.start('GameMenu'), { variant: 'ghost', width: 180, height: 52, ...BRASS_BTN, textColor: INK.ink }).setDepth(DEPTH.ui); } // ── Board ─────────────────────────────────────────────────────────────────── - tileWorld(t) { return { x: BX0 + t.c * PITCH + TILE / 2, y: BY0 + t.r * PITCH + TILE / 2 }; } + tileWorld(t) { return tileCenter(t); } buildBoard() { - // soft island sea bed under the tiles - const sea = this.add.graphics().setDepth(DEPTH.board); - sea.fillStyle(0x062536, 0.6); - sea.fillRoundedRect(BX0 - 24, BY0 - 24, BOARD_W + 48, BOARD_W + 48, 30); - - const hasArt = this.textures.exists('forbiddenisland-tiles'); for (const t of Object.values(this.gs.tiles)) { const { x, y } = this.tileWorld(t); - const container = this.add.container(x, y).setDepth(DEPTH.tile); - const row = TILE_FRAME_ROW[t.id]; - const img = hasArt ? this.add.image(0, 0, 'forbiddenisland-tiles', row * 2).setDisplaySize(TILE, TILE) : null; - const bg = this.add.graphics(); - const label = this.add.text(0, TILE / 2 - 14, t.name, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#f4efe2', - align: 'center', wordWrap: { width: TILE - 12 }, - }).setOrigin(0.5, 1); - let gem = null; - if (t.treasure) { - gem = this.add.graphics(); - // small corner badge so it doesn't cover the tile art - const gx = hasArt ? -TILE / 2 + 15 : 0, gy = hasArt ? -TILE / 2 + 15 : -8; - gem.fillStyle(0x000000, 0.5); gem.fillCircle(gx, gy, 13); - gem.fillStyle(TREASURES[t.treasure].color, 1); gem.fillCircle(gx, gy, 11); - gem.lineStyle(2, 0xffffff, 0.85); gem.strokeCircle(gx, gy, 11); - } - // Input goes on an invisible, centered Rectangle child rather than a manual - // hitArea on the Container — the latter mis-aligns the hitbox (offset up/left). - const hit = this.add.rectangle(0, 0, TILE, TILE, 0x000000, 0).setInteractive({ useHandCursor: true }); - const layers = img ? [img, bg, label] : [bg, label]; - container.add(layers); if (gem) container.add(gem); - container.add(hit); - hit.on('pointerup', () => this.onTileClick(t.id)); - hit.on('pointerover', () => { if (!this.busy) container.setScale(1.03); }); - hit.on('pointerout', () => container.setScale(1)); - this.tileViews[t.id] = { container, img, bg, label, gem, row, hit }; + this.tileViews[t.id] = new TileView(this, this.sea, t, x, y, (id) => this.onTileClick(id)); } } drawTile(t) { - const v = this.tileViews[t.id]; - const g = v.bg; g.clear(); - const hw = TILE / 2; - - // Sprite-art path (with vector fallback below if the sheet didn't load). - if (v.img) { - const flooded = t.state === 'flooded'; - const sunk = t.state === 'sunk'; - v.img.setFrame(v.row * 2 + (sunk || flooded ? 1 : 0)); - if (sunk) { - v.img.setTint(0x21465a).setAlpha(0.5); - v.container.setAngle(0).setAlpha(0.9); - v.label.setAlpha(0.3); if (v.gem) v.gem.setAlpha(0.25); - g.lineStyle(2, TC.sunk, 0.8); g.strokeRect(-hw, -hw, TILE, TILE); - return; - } - v.img.clearTint().setAlpha(1); - v.container.setAlpha(1).setAngle(flooded ? -3 : 0); - v.label.setAlpha(1); if (v.gem) v.gem.setAlpha(1); - g.fillStyle(0x000000, 0.45); g.fillRect(-hw, hw - 22, TILE, 22); // label backing - g.lineStyle(t.landing ? 4 : (t.treasure ? 3 : 2), t.landing ? COLORS.gold : (t.treasure ? TREASURES[t.treasure].color : 0x10202a), 1); - g.strokeRect(-hw, -hw, TILE, TILE); - if (flooded) { g.lineStyle(2, TC.floodEdge, 0.55); g.strokeRect(-hw + 2, -hw + 2, TILE - 4, TILE - 4); } - return; - } - - // ---- vector fallback (no spritesheet) ---- - if (t.state === 'sunk') { - v.container.setAngle(0); - g.fillStyle(TC.sunk, 0.55); - g.fillRoundedRect(-hw, -hw, TILE, TILE, 14); - v.label.setAlpha(0.25); if (v.gem) v.gem.setAlpha(0.2); - v.container.setAlpha(0.85); - return; - } - v.container.setAlpha(1); v.label.setAlpha(1); if (v.gem) v.gem.setAlpha(1); - const flooded = t.state === 'flooded'; - g.fillStyle(flooded ? TC.flooded : (t.treasure || t.landing ? TC.dryStone : TC.dry), 1); - g.fillRoundedRect(-hw, -hw, TILE, TILE, 14); - if (flooded) { - g.fillStyle(TC.floodEdge, 0.28); g.fillRoundedRect(-hw, -hw, TILE, TILE, 14); - } - g.lineStyle(t.landing ? 4 : (t.treasure ? 3 : 2), t.landing ? COLORS.gold : (t.treasure ? TREASURES[t.treasure].color : TC.border), 1); - g.strokeRoundedRect(-hw, -hw, TILE, TILE, 14); - if (t.landing) { // helipad mark - g.lineStyle(3, COLORS.gold, 0.9); g.strokeCircle(0, -2, 22); - g.lineStyle(3, COLORS.gold, 0.9); - g.beginPath(); g.moveTo(-12, -12); g.lineTo(12, 8); g.moveTo(12, -12); g.lineTo(-12, 8); g.strokePath(); - } - v.container.setAngle(flooded ? -3 : 0); + this.tileViews[t.id]?.setState(t.state); } - // ── Right rail: banner, treasures, chat, priorities, hand, buttons ────────── + // ── Right rail: the field journal ───────────────────────────────────────── buildRail() { - // Turn banner + // Turn plate: a brass plaque screwed to the page. this.bannerBg = this.add.graphics().setDepth(DEPTH.ui); - this.bannerText = this.add.text(RAIL_X, 110, '', { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex, wordWrap: { width: RAIL_W }, - }).setDepth(DEPTH.ui); + this.bannerText = this.add.text(RAIL_X + 18, 124, '', { + fontFamily: BODY_FONT, fontSize: '22px', fontStyle: 'bold', color: '#2b1d08', wordWrap: { width: RAIL_W - 36 }, + }).setOrigin(0, 0.5).setDepth(DEPTH.ui); - // Treasure tracker + // Relic tracker: the user's relic paintings, faded until recovered. this.treasureChips = {}; + const hasCards = this.textures.exists('forbiddenisland-cards'); TREASURE_KEYS.forEach((k, i) => { - const x = RAIL_X + i * (RAIL_W / 4); - const cx = x + RAIL_W / 8; + const slotW = RAIL_W / 4; + const cx = RAIL_X + i * slotW + 34; + const cy = 196; const g = this.add.graphics().setDepth(DEPTH.ui); - const t = this.add.text(cx, 196, TREASURES[k].name, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex, - align: 'center', wordWrap: { width: RAIL_W / 4 - 8 }, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui); - this.treasureChips[k] = { g, t, cx }; + const img = hasCards ? this.add.image(cx, cy, 'forbiddenisland-cards', cardFrame(`treasure:${k}`)).setDisplaySize(40, 52).setDepth(DEPTH.ui) : null; + const stamp = this.add.text(cx, cy + 4, 'RECOVERED', { + fontFamily: TYPE_FONT, fontSize: '10px', fontStyle: 'bold', color: '#8e2a1e', backgroundColor: 'rgba(242,230,204,0.85)', + padding: { x: 2, y: 1 }, + }).setOrigin(0.5).setAngle(-14).setDepth(DEPTH.ui + 1).setVisible(false); + const t = this.add.text(cx + 28, cy - 20, TREASURES[k].name.replace(/^The /, ''), { + fontFamily: BODY_FONT, fontSize: '14px', fontStyle: 'bold', color: INK.ink, wordWrap: { width: slotW - 70 }, + }).setDepth(DEPTH.ui); + const sub = this.add.text(cx + 28, cy + 14, '', { + fontFamily: TYPE_FONT, fontSize: '11px', color: INK.inkSoft, + }).setDepth(DEPTH.ui); + this.treasureChips[k] = { g, t, sub, img, stamp, cx, cy }; }); - // Chat panel + // Expedition log (chat). const chatY = 248, chatH = 548; const cp = this.add.graphics().setDepth(DEPTH.ui); - cp.fillStyle(0x000000, 0.4); cp.fillRoundedRect(RAIL_X, chatY, RAIL_W, chatH, 12); - cp.lineStyle(2, COLORS.accent, 0.5); cp.strokeRoundedRect(RAIL_X, chatY, RAIL_W, chatH, 12); - this.add.text(RAIL_X + 14, chatY + 8, 'TEAM CHAT', { fontFamily: 'Righteous', fontSize: '15px', color: COLORS.accentHex }).setDepth(DEPTH.ui); - this.chatBox = { x: RAIL_X + 14, y: chatY + 34, w: RAIL_W - 28, h: chatH - 44 }; - this.chatText = this.add.text(this.chatBox.x, this.chatBox.y, '', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, - wordWrap: { width: this.chatBox.w }, lineSpacing: 4, - }).setDepth(DEPTH.ui); + cp.lineStyle(1, 0x5a4020, 0.35); + cp.lineBetween(RAIL_X, chatY, RAIL_X + RAIL_W, chatY); + cp.lineBetween(RAIL_X, chatY + chatH, RAIL_X + RAIL_W, chatY + chatH); + this.add.text(RAIL_X, chatY + 8, 'EXPEDITION LOG', { fontFamily: TYPE_FONT, fontSize: '15px', fontStyle: 'bold', color: INK.red }).setDepth(DEPTH.ui); + this.chatBox = { x: RAIL_X + 6, y: chatY + 36, w: RAIL_W - 12, h: chatH - 46 }; + this.chatObjs = []; // Hand - this.add.text(RAIL_X, 856, 'YOUR HAND', { fontFamily: 'Righteous', fontSize: '14px', color: COLORS.accentHex }).setDepth(DEPTH.ui); + this.add.text(RAIL_X, 856, 'YOUR HAND', { fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: INK.red }).setDepth(DEPTH.ui); this.handLayer = this.add.container(0, 0).setDepth(DEPTH.ui); // Action buttons - this.endBtn = new Button(this, RAIL_X + 110, 1030, 'End Turn', () => this.onEndTurn(), { width: 200, height: 50, fontSize: 20 }); - this.captureBtn = new Button(this, RAIL_X + 330, 1030, 'Capture', () => this.onCapture(), { width: 200, height: 50, fontSize: 20 }); - this.escapeBtn = new Button(this, RAIL_X + 550, 1030, 'Escape!', () => this.onEscape(), { width: 200, height: 50, fontSize: 20 }); - [this.endBtn, this.captureBtn, this.escapeBtn].forEach((b) => b.setDepth(DEPTH.ui)); + const bo = { width: 170, height: 50, fontSize: 19, ...BRASS_BTN }; + this.endBtn = new Button(this, RAIL_X + 92, 1030, 'End Turn', () => this.onEndTurn(), bo); + this.captureBtn = new Button(this, RAIL_X + 277, 1030, 'Capture', () => this.onCapture(), bo); + this.escapeBtn = new Button(this, RAIL_X + 462, 1030, 'Escape!', () => this.onEscape(), bo); + this.undoBtn = new Button(this, RAIL_X + 637, 1030, 'Undo', () => this.onUndo(), { ...bo, width: 150 }); + [this.endBtn, this.captureBtn, this.escapeBtn, this.undoBtn].forEach((b) => b.setDepth(DEPTH.ui)); } + // Brass tide gauge on the far right. The glass tube fills as the waters rise. buildWaterMeter() { - const x = GAME_WIDTH - 70, top = 160, bottom = 900; - this.add.text(x, top - 34, 'WATER', { fontFamily: 'Righteous', fontSize: '16px', color: COLORS.accentHex }).setOrigin(0.5).setDepth(DEPTH.ui); - this.waterX = x; this.waterTop = top; this.waterBottom = bottom; - this.waterG = this.add.graphics().setDepth(DEPTH.ui); - this.waterLabel = this.add.text(x, bottom + 18, '', { fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.textHex }).setOrigin(0.5).setDepth(DEPTH.ui); + const art = GAUGE_ART; + this.waterX = GAUGE.x; this.waterTop = GAUGE.top; this.waterBottom = GAUGE.bottom; + this.add.image(GAUGE.x, GAUGE.top - art.top, 'di-gauge').setOrigin(0.5, 0) + .setDisplaySize(art.w, art.h).setDepth(DEPTH.ui); + this.waterG = this.add.graphics().setDepth(DEPTH.ui + 1); + this.waterLabel = this.add.text(GAUGE.x, GAUGE.bottom + 34, '', { + fontFamily: TYPE_FONT, fontSize: '12px', fontStyle: 'bold', color: '#2b1d08', align: 'center', lineSpacing: 1, + }).setOrigin(0.5).setDepth(DEPTH.ui + 1); + this.waterLevelShown = null; + this.gaugeFill = { y: GAUGE.bottom }; + this.events.on('update', () => this.drawGaugeLiquid()); } - // ── Deck display (below board) ─────────────────────────────────────────────── + // Forecast toggle on the driftwood shelf. + buildToolbar() { + const y = BY0 + BOARD_W + 46 + 108; + this.forecastBtn = new Button(this, BX0 + BOARD_W - 62, y, 'Forecast', () => { + this.forecastOn = !this.forecastOn; + Sound.click(this); + this.forecastBtn.setAlpha(this.forecastOn ? 1 : 0.75); + this.renderForecast(); + if (this.forecastOn) this.flashHint('Danger forecast: each tile\'s chance of being drawn in the next flood. Red means it would sink.'); + }, { width: 128, height: 36, fontSize: 15, ...BRASS_BTN }); + this.forecastBtn.setDepth(DEPTH.ui).setAlpha(0.75); + this.forecastObjs = []; + } + + // Percent badges (and a red wash on tiles that would sink) for the coming flood. + renderForecast() { + for (const o of this.forecastObjs ?? []) o.destroy(); + this.forecastObjs = []; + if (!this.forecastOn || !this.gs || isGameOver(this.gs)) return; + let odds = {}; + try { odds = floodForecast(this.gs); } catch (_) { return; } + for (const t of Object.values(this.gs.tiles)) { + if (t.state === 'sunk') continue; + const p = odds[t.id] ?? 0; + if (p < 0.005) continue; + const { x, y } = this.tileWorld(t); + const sinks = t.state === 'flooded'; + const col = sinks ? 0xb5452e : 0x2f6f96; + const wash = this.add.rectangle(x, y, TILE, TILE, col, Math.min(0.5, 0.12 + p * 0.5)).setDepth(DEPTH.tileFx); + const pct = Math.round(p * 100); + const badge = this.add.text(x + TILE / 2 - 6, y - TILE / 2 + 6, `${pct}%${sinks ? ' ▼' : ''}`, { + fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: '#fff6e0', + backgroundColor: sinks ? 'rgba(142,42,30,0.92)' : 'rgba(31,74,102,0.92)', padding: { x: 4, y: 2 }, + }).setOrigin(1, 0).setDepth(DEPTH.tileFx + 1); + this.forecastObjs.push(wash, badge); + } + } + + // Ghost arrows: the turn an AI partner is about to play, drawn on the island. + drawPlanArrows(seat, actions) { + this.clearPlanArrows(); + if (!actions?.length) return; + const g = this.add.graphics().setDepth(DEPTH.pawn - 1); + const col = ROLES[this.gs.players[seat].role].color; + const pos = Object.fromEntries(this.gs.players.map((p) => [p.seat, p.tileId])); + const at = (id) => this.tileWorld(this.gs.tiles[id]); + const arrow = (a, b, dashed = true) => { + const dx = b.x - a.x, dy = b.y - a.y, L = Math.hypot(dx, dy) || 1, ux = dx / L, uy = dy / L; + const sx = a.x + ux * 18, sy = a.y + uy * 18, ex = b.x - ux * 22, ey = b.y - uy * 22; + const seg = dashed ? 10 : L; + g.lineStyle(9, 0x000000, 0.25); g.lineBetween(sx, sy + 3, ex, ey + 3); + g.lineStyle(5, col, 0.95); + for (let d = 0; d < Math.hypot(ex - sx, ey - sy); d += seg * 1.8) { + const d2 = Math.min(d + seg, Math.hypot(ex - sx, ey - sy)); + g.lineBetween(sx + ux * d, sy + uy * d, sx + ux * d2, sy + uy * d2); + } + g.fillStyle(col, 1); + g.fillTriangle(ex + ux * 12, ey + uy * 12, ex - uy * 9, ey + ux * 9, ex + uy * 9, ey - ux * 9); + g.lineStyle(1.5, 0x1a110a, 0.8); + g.strokeTriangle(ex + ux * 12, ey + uy * 12, ex - uy * 9, ey + ux * 9, ex + uy * 9, ey - ux * 9); + }; + const mark = (id, kind) => { + const { x, y } = at(id); + if (kind === 'shore') { g.lineStyle(4, 0xf0d070, 0.95); g.strokeRoundedRect(x - TILE / 2 + 8, y - TILE / 2 + 8, TILE - 16, TILE - 16, 8); } + if (kind === 'capture') { g.fillStyle(0xf0d070, 1); g.fillCircle(x, y - 18, 14); g.lineStyle(2, 0x3a2808, 1); g.strokeCircle(x, y - 18, 14); } + }; + actions.forEach((a, i) => { + if (a.type === 'move' || a.type === 'fly') { arrow(at(pos[seat]), at(a.tileId), a.type !== 'fly'); pos[seat] = a.tileId; } + else if (a.type === 'navMove') { arrow(at(pos[a.targetSeat]), at(a.tileId)); pos[a.targetSeat] = a.tileId; } + else if (a.type === 'shoreUp') a.tiles.forEach((id) => mark(id, 'shore')); + else if (a.type === 'capture') mark(pos[seat], 'capture'); + else if (a.type === 'give') arrow(at(pos[seat]), at(pos[a.targetSeat])); + void i; + }); + const label = this.add.text(BX0 + BOARD_W / 2, BY0 - 30, `${this.partnerNames[seat]}'s plan`, { + fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: '#fff6e0', backgroundColor: 'rgba(30,20,10,0.75)', padding: { x: 8, y: 3 }, + }).setOrigin(0.5).setDepth(DEPTH.ui + 1); + g.setAlpha(0); label.setAlpha(0); + this.tweens.add({ targets: [g, label], alpha: 1, duration: 300 }); + this.planArrows = [g, label]; + } + + clearPlanArrows() { + for (const o of this.planArrows ?? []) { this.tweens.killTweensOf(o); o.destroy(); } + this.planArrows = null; + } + + // ── Undo inside your own turn ────────────────────────────────────────────── + pushUndo() { + if (this.gs.current === this.humanSeat && this.gs.phase === 'actions') this.undoStack.push(this.gs); + } + + onUndo() { + if (this.busy || !this.undoStack.length || this.gs.current !== this.humanSeat || this.gs.phase !== 'actions') return; + Sound.click(this); + this.gs = this.undoStack.pop(); + this.mode = null; this.modeData = null; + this.closePopup(); + this.flashHint('Undone.'); + this.render(); + } + + // ── Deck display (below board): a driftwood shelf with the two decks ──────── buildDeckDisplay() { - const areaY = BY0 + BOARD_W + 46; // start well below the board hint area (~904) - const colW = BOARD_W / 3; // ~233px per column - const pileW = 80, pileH = 108, pileR = 8; + const areaY = BY0 + BOARD_W + 46; + const colW = BOARD_W / 3; + const pileW = BACK.w, pileH = BACK.h; + this.add.image(BX0 - 10, areaY - 4, 'di-shelf').setOrigin(0).setDepth(DEPTH.ui - 1); const slots = [ - { key: 'flood', label: 'Flood Deck', col: 0 }, - { key: 'treasure', label: 'Treasure Deck', col: 1 }, - { key: 'adventurer', label: 'Adventurer Cards', col: 2 }, + { key: 'flood', label: 'Flood Deck', sub: 'tide charts', col: 0, tex: 'di-back-flood' }, + { key: 'treasure', label: 'Supply Crate', sub: 'treasure deck', col: 1, tex: 'di-back-treasure' }, + { key: 'adventurer', label: 'Crew Roster', sub: 'unused roles', col: 2, tex: null }, ]; this.deckCountTexts = {}; - for (const { key, label, col } of slots) { - const cx = BX0 + col * colW; // left edge of column - const pileX = cx + 14; // left edge of pile - const pileY = areaY + 14; + for (const { key, label, sub, col, tex } of slots) { + const cx = BX0 + col * colW; + const pileX = cx + 14; + const pileY = areaY + 12; const pileCX = pileX + pileW / 2; const pileCY = pileY + pileH / 2; - // Stacked card pile (3 offset backs → depth illusion) - const g = this.add.graphics().setDepth(DEPTH.ui); - for (let i = 2; i >= 0; i--) { - const ox = i * 2, oy = i * -2; - g.fillStyle(0x0a2030, 1); - g.fillRoundedRect(pileX + ox, pileY + oy, pileW, pileH, pileR); - g.lineStyle(1, 0x2a4a60, 1); - g.strokeRoundedRect(pileX + ox, pileY + oy, pileW, pileH, pileR); + if (tex) { + for (let i = 2; i >= 0; i--) { + this.add.image(pileCX + i * 2, pileCY - i * 2, tex).setDisplaySize(pileW, pileH).setDepth(DEPTH.ui) + .setTint(i ? 0xb0a898 : 0xffffff); + } + } else { + // Roster: a stack of crew figurines not on this expedition. + const unused = ROLE_KEYS.filter((r) => !this.gs.players.some((p) => p.role === r)); + unused.forEach((r, i) => this.add.image(pileX + 14 + i * 26, pileY + pileH - 6, `di-pawn-${r}`).setOrigin(0.5, 1).setDisplaySize(35, 51).setDepth(DEPTH.ui).setAlpha(0.85)); } - // Subtle pattern on top card - g.lineStyle(1, 0x1a3a50, 0.6); - g.strokeRoundedRect(pileX + 8, pileY + 8, pileW - 16, pileH - 16, 4); - // Text to the right of pile - const tx = pileX + pileW + 14; - this.add.text(tx, pileY + 8, label, { - fontFamily: 'Righteous', fontSize: '14px', color: COLORS.accentHex, + const tx = tex ? pileX + pileW + 14 : pileX; + const ty = tex ? pileY + 8 : pileY - 2; + this.add.text(tx, ty, label.toUpperCase(), { + fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: '#f2e6cc', }).setDepth(DEPTH.ui); - - const countText = this.add.text(tx, pileY + 32, '', { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + if (tex) { + this.add.text(tx, ty + 18, sub, { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '13px', color: '#cdb994' }).setDepth(DEPTH.ui); + } + const countText = this.add.text(tex ? tx : pileX + 110, tex ? ty + 40 : ty + 22, '', { + fontFamily: TYPE_FONT, fontSize: '13px', color: '#e8d6ae', }).setDepth(DEPTH.ui); this.deckCountTexts[key] = countText; - // Store pile centers for card-deal animation origins if (key === 'flood') this.floodDeckPos = { x: pileCX, y: pileCY }; if (key === 'treasure') this.treasureDeckPos = { x: pileCX, y: pileCY }; } @@ -312,76 +406,60 @@ export default class ForbiddenIslandGame extends Phaser.Scene { updateDeckCounts() { if (!this.deckCountTexts || !this.gs) return; const pendingCount = (this.gs.pendingFlood ?? []).length; - this.deckCountTexts.flood.setText(`${this.gs.floodDeck.length + pendingCount} cards`); - this.deckCountTexts.treasure.setText(`${this.gs.treasureDeck.length} cards`); + this.deckCountTexts.flood.setText(`${this.gs.floodDeck.length + pendingCount} left · ${this.gs.floodDiscard.length} drawn`); + this.deckCountTexts.treasure.setText(`${this.gs.treasureDeck.length} left`); const unused = ROLE_KEYS.length - this.gs.players.length; - this.deckCountTexts.adventurer.setText(unused > 0 ? `${unused} cards` : 'All assigned'); + this.deckCountTexts.adventurer.setText(unused > 0 ? `${unused} stay at camp` : 'Full crew'); + } + + gaugeY(level) { + const segH = (this.waterBottom - this.waterTop) / MAX_WATER; + return this.waterTop + (MAX_WATER - level) * segH; } drawWaterMeter() { - const g = this.waterG; g.clear(); - const segH = (this.waterBottom - this.waterTop) / MAX_WATER; - const w = 40, x = this.waterX - w / 2; - for (let lvl = MAX_WATER; lvl >= 1; lvl--) { - const y = this.waterTop + (MAX_WATER - lvl) * segH; - const on = lvl <= this.gs.waterLevel; - const danger = lvl >= 8; - const skull = lvl === MAX_WATER; - g.fillStyle(on ? (skull ? 0xb22a2a : danger ? 0xd1632f : 0x2f8fd0) : 0x14313f, on ? 1 : 0.7); - g.fillRoundedRect(x, y + 2, w, segH - 4, 6); - g.lineStyle(1, 0x000000, 0.4); g.strokeRoundedRect(x, y + 2, w, segH - 4, 6); + const lvl = this.gs.waterLevel; + if (this.waterLevelShown !== lvl) { + this.waterLevelShown = lvl; + this.tweens.killTweensOf(this.gaugeFill); + this.tweens.add({ targets: this.gaugeFill, y: this.gaugeY(lvl), duration: 900, ease: 'Cubic.easeOut' }); } - // marker - const my = this.waterTop + (MAX_WATER - this.gs.waterLevel) * segH + segH / 2; - g.fillStyle(COLORS.gold, 1); - g.fillTriangle(x - 12, my - 8, x - 12, my + 8, x - 2, my); - this.waterLabel.setText(`Lvl ${this.gs.waterLevel} · draw ${floodDrawCount(this.gs.waterLevel)}`); + this.waterLabel.setText(`${floodDrawCount(lvl)} FLOODS\nPER TURN`); + this.sea.setLevel(lvl); + this.storm.setLevel(lvl); + this.stampText?.setText(journalStamp(this.gs.round ?? 1, lvl)); + this.ambience?.setLevel(lvl); + } + + // The liquid column, redrawn every frame so its surface can slosh. + drawGaugeLiquid() { + const g = this.waterG; if (!g || !this.gs) return; + g.clear(); + const tw = GAUGE_TUBE.w - 4, x0 = GAUGE.x - tw / 2; + const top = this.gaugeFill.y, bottom = this.waterBottom + 2; + const lvl = this.gs.waterLevel; + const col = lvl >= 8 ? 0xb5452e : lvl >= 6 ? 0x2f7a8a : 0x2f8fb0; + const t = this.time.now / 600; + g.fillStyle(col, 0.9); + g.beginPath(); + g.moveTo(x0, bottom); + for (let i = 0; i <= 8; i++) { + const x = x0 + (tw * i) / 8; + g.lineTo(x, top + Math.sin(t + i * 0.9) * 2.2); + } + g.lineTo(x0 + tw, bottom); + g.closePath(); g.fillPath(); + g.fillStyle(0xffffff, 0.22); g.fillRect(x0 + 3, top + 4, 4, Math.max(0, bottom - top - 8)); + // brass marker arrow on the current band + const my = this.gaugeY(lvl) + (this.waterBottom - this.waterTop) / MAX_WATER / 2; + g.fillStyle(0xf0d070, 1); + g.fillTriangle(x0 + tw + 8, my, x0 + tw + 20, my - 8, x0 + tw + 20, my + 8); + g.lineStyle(1, 0x3a2808, 1); g.strokeTriangle(x0 + tw + 8, my, x0 + tw + 20, my - 8, x0 + tw + 20, my + 8); } // ── Intro sequence ────────────────────────────────────────────────────────── - showBeginModal() { - const cx = GAME_WIDTH / 2, cy = GAME_HEIGHT / 2; - const pw = 800, ph = 380; - const diff = DIFFICULTY[this.difficulty]; - - const cont = this.add.container(0, 0).setDepth(DEPTH.popup + 1); - - const overlay = this.add.graphics(); - overlay.fillStyle(0x000000, 0.72); - overlay.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - cont.add(overlay); - - const panel = this.add.graphics(); - panel.fillStyle(0x061a2a, 1); - panel.fillRoundedRect(cx - pw / 2, cy - ph / 2, pw, ph, 20); - panel.lineStyle(3, COLORS.gold, 1); - panel.strokeRoundedRect(cx - pw / 2, cy - ph / 2, pw, ph, 20); - cont.add(panel); - - cont.add(this.add.text(cx, cy - 138, 'Forbidden Island', { - fontFamily: 'Righteous', fontSize: '52px', color: COLORS.goldHex, - }).setOrigin(0.5)); - - cont.add(this.add.text(cx, cy - 68, 'Gather your team and prepare to explore…', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0.5)); - - cont.add(this.add.text(cx, cy - 24, `Difficulty: ${diff.name}`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5)); - - const btn = new Button(this, cx, cy + 120, 'Begin Game', () => this.beginGame(), { - width: 280, height: 60, fontSize: 24, - }); - btn.setDepth(0); - cont.add(btn); - - this.beginModal = cont; - } - beginGame() { - this.beginModal.destroy(); - this.beginModal = null; + this.busy = true; this.runInitialFlood(this.gs.pendingFlood.slice(), () => { this.gs = applyPendingFlood(this.gs); this.updateDeckCounts(); @@ -405,71 +483,58 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.renderChat(); this.highlightTargets(); this.updateDeckCounts(); + this.renderForecast(); + const canUndo = this.undoStack.length > 0 && !this.busy && this.gs.current === this.humanSeat && this.gs.phase === 'actions'; + this.undoBtn?.setEnabled(canUndo).setAlpha(canUndo ? 1 : 0.4); + } + + // Where a crew figurine stands: crowded tiles spread their figures out. + pawnSpot(seat, tileId, players = this.gs.players) { + const t = this.gs.tiles[tileId]; + const { x, y } = this.tileWorld(t); + const group = players.filter((p) => p.tileId === tileId).map((p) => p.seat).sort((a, b) => a - b); + const n = group.length, i = Math.max(0, group.indexOf(seat)); + return { x: x + (i - (n - 1) / 2) * 24, y: y + 30 }; + } + + ensureFigures() { + for (const p of this.gs.players) { + if (!this.figures[p.seat]) this.figures[p.seat] = new Figure(this, p, { human: p.isHuman }); + } } renderPawns() { - this.pawnLayer.removeAll(true); - this.pawnObjects = {}; if (!this.introComplete) return; - // group pawns by tile to cluster - const byTile = {}; - for (const p of this.gs.players) (byTile[p.tileId] ??= []).push(p); - for (const [tileId, group] of Object.entries(byTile)) { - const t = this.gs.tiles[tileId]; if (!t) continue; - const { x, y } = this.tileWorld(t); - group.forEach((p, i) => { - const n = group.length; - const ox = (i - (n - 1) / 2) * 22; - const c = this.add.circle(x + ox, y + 12, 15, ROLES[p.role].color).setStrokeStyle(3, p.seat === this.gs.current ? 0xffffff : 0x000000, 1); - this.pawnLayer.add(c); - this.pawnObjects[p.seat] = [c]; - if (p.isHuman) { - const ring = this.add.circle(x + ox, y + 12, 19).setStrokeStyle(2, COLORS.gold, 0.9); - this.pawnLayer.add(ring); - this.pawnObjects[p.seat].push(ring); - } - }); + this.ensureFigures(); + for (const p of this.gs.players) { + const f = this.figures[p.seat]; + if (f.moving) continue; + const { x, y } = this.pawnSpot(p.seat, p.tileId); + f.place(x, y); + f.setActive(p.seat === this.gs.current && !isGameOver(this.gs)); } } - animatePawnMove(seat, fromTileId, toTileId, onDone) { + // kind: 'walk' | 'fly' | 'swim' | 'nav'; guessed from the role and distance when omitted. + animatePawnMove(seat, fromTileId, toTileId, onDone, kind = null) { const player = this.gs.players[seat]; - const role = ROLES[player.role]; - const { x: fx, y: fy } = this.tileWorld(this.gs.tiles[fromTileId]); - const { x: tx, y: ty } = this.tileWorld(this.gs.tiles[toTileId]); - const YOFF = 12; - const depth = DEPTH.pawn + 1; - - // Use the exact rendered position and hide the static pawn while flying. - const staticObjs = this.pawnObjects[seat] ?? []; - let startX = fx, startY = fy + YOFF; - if (staticObjs[0]) { startX = staticObjs[0].x; startY = staticObjs[0].y; } - for (const o of staticObjs) o.setAlpha(0); - - const pawn = this.add.circle(startX, startY, 15, role.color) - .setStrokeStyle(3, seat === this.gs.current ? 0xffffff : 0x000000, 1) - .setDepth(depth); - - const toDestroy = [pawn]; - - if (player.isHuman) { - const ring = this.add.circle(startX, startY, 19) - .setStrokeStyle(2, COLORS.gold, 0.9) - .setDepth(depth); - this.tweens.add({ targets: ring, x: tx, y: ty + YOFF, duration: 1200, ease: 'Cubic.easeInOut' }); - toDestroy.push(ring); + this.ensureFigures(); + const f = this.figures[seat]; + const a = this.gs.tiles[fromTileId], b = this.gs.tiles[toTileId]; + const far = Math.max(Math.abs(a.r - b.r), Math.abs(a.c - b.c)) > 1 || (a.r !== b.r && a.c !== b.c && player.role !== 'explorer'); + if (!kind) { + if (this.gs.phase === 'swim' || a.state === 'sunk') kind = 'swim'; + else if (player.role === 'pilot' && far) kind = 'fly'; + else if (player.role === 'diver' && far) kind = 'swim'; + else kind = 'walk'; } - - this.tweens.add({ - targets: pawn, - x: tx, y: ty + YOFF, - duration: 1200, - ease: 'Cubic.easeInOut', - onComplete: () => { - for (const o of toDestroy) o.destroy(); - onDone(); - }, - }); + const after = this.gs.players.map((p) => (p.seat === seat ? { ...p, tileId: toTileId } : p)); + const { x, y } = this.pawnSpot(seat, toTileId, after); + f.moving = true; + if (kind === 'swim') Sound.splash(this, 0.6); + else if (kind === 'fly') Sound.rotor(this, 1.2); + else Sound.step(this); + f.moveTo(x, y, kind, this.sea, () => { f.moving = false; onDone(); }); } animateShoreUp(tileId, onDone) { @@ -481,11 +546,11 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const img = this.add.image(0, 0, 'forbiddenisland-tiles', rowIdx * 2 + 1).setDisplaySize(200, 200); const borderGfx = this.add.graphics(); - borderGfx.lineStyle(3, 0x67b6e0, 1); + borderGfx.lineStyle(6, 0x67b6e0, 1); borderGfx.strokeRoundedRect(-100, -100, 200, 200, 12); const cont = this.add.container(tx, ty, [img, borderGfx]).setDepth(depth).setScale(tileScale); - if (this.cache.audio.exists('sfx-card-deal')) this.sound.play('sfx-card-deal', { volume: 0.4 }); + Sound.card(this); // 1. Fly from tile board position to center, scaling up this.tweens.add({ @@ -501,22 +566,22 @@ export default class ForbiddenIslandGame extends Phaser.Scene { onComplete: () => { img.setFrame(rowIdx * 2); borderGfx.clear(); - borderGfx.lineStyle(3, 0xd4c08a, 1); + borderGfx.lineStyle(6, 0xc9a14a, 1); borderGfx.strokeRoundedRect(-100, -100, 200, 200, 12); - if (this.cache.audio.exists('sfx-card-show')) this.sound.play('sfx-card-show', { volume: 0.35 }); - if (this.cache.audio.exists('sfx-water-dry')) this.sound.play('sfx-water-dry', { volume: 0.7 }); + Sound.card(this); + Sound.shore(this); this.tweens.add({ targets: cont, scaleX: 1, duration: 150, ease: 'Linear', onComplete: () => { // 3. Pause then fly back, shrinking this.time.delayedCall(800, () => { - if (this.cache.audio.exists('sfx-card-place')) this.sound.play('sfx-card-place', { volume: 0.3 }); + Sound.card(this); this.tweens.add({ targets: cont, x: tx, y: ty, scaleX: tileScale, scaleY: tileScale, duration: 400, ease: 'Cubic.easeIn', - onComplete: () => { cont.destroy(); onDone(); }, + onComplete: () => { cont.destroy(); this.tileViews[tileId]?.shore(); onDone(); }, }); }); }, @@ -551,11 +616,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Panel sized snugly around the content const panelTop = portCY - PAWN_R - 8; const panelBot = cardsY + CARD_H + 8; - const panelG = reg(this.add.graphics().setDepth(DEPTH.ui - 1)); - panelG.fillStyle(0x041824, 0.82); - panelG.fillRoundedRect(BX0 - 2, panelTop, BOARD_W + 4, panelBot - panelTop, 6); - panelG.lineStyle(1, 0x1a3a50, 0.5); - panelG.strokeRoundedRect(BX0 - 2, panelTop, BOARD_W + 4, panelBot - panelTop, 6); + reg(this.add.image(BX0 - 2, panelTop, 'di-strip').setOrigin(0).setDisplaySize(BOARD_W + 4, panelBot - panelTop).setDepth(DEPTH.ui - 1)); // Clickable zone over the whole panel — opens trade modal const hitZone = reg(this.add.zone(BX0 - 2, panelTop, BOARD_W + 4, panelBot - panelTop) @@ -568,9 +629,9 @@ export default class ForbiddenIslandGame extends Phaser.Scene { }); // Visual affordance label - reg(this.add.text(BX0 + BOARD_W - 6, panelTop + 4, '↔ TRADE', { - fontFamily: 'Righteous', fontSize: '10px', color: COLORS.accentHex, - }).setOrigin(1, 0).setDepth(DEPTH.ui + 2)); + reg(this.add.text(BX0 + BOARD_W - 8, panelBot - 6, '➜ GIVE A CARD', { + fontFamily: TYPE_FONT, fontSize: '11px', fontStyle: 'bold', color: INK.red, + }).setOrigin(1, 1).setDepth(DEPTH.ui + 2)); aiSeats.forEach((player, idx) => { const slotLeft = BX0 + idx * slotW; @@ -582,13 +643,13 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Slot divider (skip first) if (idx > 0) { const div = reg(this.add.graphics().setDepth(DEPTH.ui)); - div.lineStyle(1, 0x1a3a50, 0.6); + div.lineStyle(1, 0x5a4020, 0.35); div.lineBetween(slotLeft, panelTop + 4, slotLeft, panelBot - 4); } // Portrait dark circle + pawn-colour ring const portG = reg(this.add.graphics().setDepth(DEPTH.ui)); - portG.fillStyle(0x07202e, 1); + portG.fillStyle(0x2a1d14, 1); portG.fillCircle(portCX, portCY, PAWN_R); portG.lineStyle(4, role.color, 1); portG.strokeCircle(portCX, portCY, PAWN_R); @@ -605,21 +666,17 @@ export default class ForbiddenIslandGame extends Phaser.Scene { .setMask(mask)); reg(maskG); } else { - // Fallback: role initial in tinted circle - const avG = reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - avG.fillStyle(role.color, 0.35); - avG.fillCircle(portCX, portCY, PAWN_R - 3); - reg(this.add.text(portCX, portCY, role.name[0], { - fontFamily: 'Righteous', fontSize: '20px', color: '#ffffff', - }).setOrigin(0.5).setDepth(DEPTH.ui + 2)); + // Fallback: the crew member's figurine + reg(this.add.image(portCX, portCY + PAWN_R - 4, `di-pawn-${player.role}`).setOrigin(0.5, 1).setDisplaySize(30, 44).setDepth(DEPTH.ui + 2)); } // Name + role label reg(this.add.text(textX, nameY, this.partnerNames[player.seat], { - fontFamily: 'Righteous', fontSize: '13px', color: COLORS.textHex, + fontFamily: BODY_FONT, fontStyle: 'bold', fontSize: '14px', color: INK.ink, }).setDepth(DEPTH.ui + 1)); - reg(this.add.text(textX, roleY, role.name, { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: role.colorHex, + reg(this.add.image(textX + 5, roleY + 7, `di-pawn-${player.role}`).setDisplaySize(9, 13).setDepth(DEPTH.ui + 1)); + reg(this.add.text(textX + 13, roleY, role.name, { + fontFamily: TYPE_FONT, fontStyle: 'bold', fontSize: '11px', color: INK.inkSoft, }).setDepth(DEPTH.ui + 1)); // Direction pill (right-aligned in slot) @@ -627,13 +684,13 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const pillX = slotLeft + slotW - (idx < N - 1 ? 6 : 4); const pillY = nameY - 1; const pillBg = reg(this.add.graphics().setDepth(DEPTH.ui + 4)); - pillBg.fillStyle(0x0a2538, 1); + pillBg.fillStyle(0x3a2818, 1); pillBg.fillRoundedRect(pillX - pillW, pillY, pillW, pillH, 4); - pillBg.lineStyle(1, 0x2a5070, 1); + pillBg.lineStyle(1, 0xc9a14a, 1); pillBg.strokeRoundedRect(pillX - pillW, pillY, pillW, pillH, 4); const pillLabel = this.directionLabel(this.seatDirections[player.seat] ?? null) + ' ▼'; const pillText = reg(this.add.text(pillX - pillW / 2, pillY + pillH / 2, pillLabel, { - fontFamily: '"Julius Sans One"', fontSize: '10px', color: COLORS.mutedHex, + fontFamily: TYPE_FONT, fontSize: '10px', fontStyle: 'bold', color: '#f2e6cc', }).setOrigin(0.5).setDepth(DEPTH.ui + 5)); this.hudPillTexts[player.seat] = pillText; const pillZone = reg(this.add.zone(pillX - pillW, pillY, pillW, pillH) @@ -665,8 +722,8 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const { cardX, cardY } = slot; if (!player.hand.length) { - reg(this.add.text(cardX, cardY + CARD_H / 2, 'No cards', { - fontFamily: '"Julius Sans One"', fontSize: '10px', color: COLORS.mutedHex, + reg(this.add.text(cardX, cardY + CARD_H / 2, 'empty-handed', { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '11px', color: INK.faded, }).setOrigin(0, 0.5).setDepth(DEPTH.ui + 1)); continue; } @@ -686,29 +743,33 @@ export default class ForbiddenIslandGame extends Phaser.Scene { g.fillRoundedRect(cx - CARD_W / 2, cy - CARD_H / 2, CARD_W, CARD_H, 2); } const border = reg(this.add.graphics().setDepth(DEPTH.ui + 2)); - border.lineStyle(1, 0xffffff, 0.35); + border.lineStyle(1, 0x2b1d08, 0.8); border.strokeRoundedRect(cx - CARD_W / 2, cy - CARD_H / 2, CARD_W, CARD_H, 2); }); } } renderTreasures() { + const me = this.gs.players[this.humanSeat]; for (const k of TREASURE_KEYS) { const chip = this.treasureChips[k]; const g = chip.g; g.clear(); const captured = this.gs.players.some((p) => p.captured[k]); - g.fillStyle(TREASURES[k].color, captured ? 1 : 0.28); - g.fillCircle(chip.cx, 176, 15); - g.lineStyle(2, captured ? 0xffffff : COLORS.muted, 0.9); g.strokeCircle(chip.cx, 176, 15); - if (captured) { g.lineStyle(3, 0xffffff, 1); g.beginPath(); g.moveTo(chip.cx - 6, 176); g.lineTo(chip.cx - 1, 181); g.lineTo(chip.cx + 7, 170); g.strokePath(); } - chip.t.setColor(captured ? COLORS.textHex : COLORS.mutedHex); + const shrines = TREASURES[k].tiles.filter((id) => this.gs.tiles[id].state !== 'sunk').length; + const held = this.gs.players.reduce((n, p) => n + p.hand.filter((c) => c === `treasure:${k}`).length, 0); + g.fillStyle(0x000000, 0.3); g.fillRect(chip.cx - 21, chip.cy - 25, 44, 56); + g.lineStyle(2, captured ? 0xc9a14a : 0x5a4020, 1); g.strokeRect(chip.cx - 22, chip.cy - 28, 44, 56); + if (chip.img) chip.img.setAlpha(captured ? 1 : 0.55).setTint(captured ? 0xffffff : 0xb8a888); + chip.stamp.setVisible(captured); + chip.t.setColor(captured ? INK.ink : INK.inkSoft); + chip.sub.setText(captured ? 'in the crate' : shrines === 0 ? 'LOST' : `${held}/4 cards · ${shrines} shrine${shrines === 1 ? '' : 's'}`) + .setColor(!captured && shrines < 2 ? INK.red : INK.inkSoft); + void me; } } renderHand() { - // Clear any in-flight animated card images parked at hand positions. for (const img of this.tempHandImages) { try { img.destroy(); } catch { /* ignore */ } } this.tempHandImages = []; - // Destroy previous hand card containers (added directly to scene, not to handLayer). for (const c of this.handCards) { try { c.destroy(); } catch { /* ignore */ } } this.handCards = []; const me = this.gs.players[this.humanSeat]; @@ -718,45 +779,61 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const x = RAIL_X + 8 + i * (cardW + gap) + cardW / 2; const y = 884 + cardH / 2; const cont = this.add.container(x, y); + const shadow = this.add.rectangle(3, 5, cardW, cardH, 0x2b1d08, 0.35); const frame = hasArt ? cardFrame(card) : null; if (frame != null) { const img = this.add.image(0, 0, 'forbiddenisland-cards', frame).setDisplaySize(cardW, cardH); const border = this.add.graphics(); - border.lineStyle(2, 0xffffff, 0.6); border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 10); - cont.add([img, border]); + border.lineStyle(2, 0x2b1d08, 0.9); border.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 6); + cont.add([shadow, img, border]); } else { const g = this.add.graphics(); const info = cardInfo(card); g.fillStyle(info.color, 1); g.fillRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 10); g.lineStyle(2, 0xffffff, 0.6); g.strokeRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 10); const label = this.add.text(0, 0, info.label, { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: info.text, align: 'center', wordWrap: { width: cardW - 12 }, + fontFamily: BODY_FONT, fontSize: '14px', color: info.text, align: 'center', wordWrap: { width: cardW - 12 }, }).setOrigin(0.5); - cont.add([g, label]); + cont.add([shadow, g, label]); } + cont.setAngle((i - (me.hand.length - 1) / 2) * 1.2); // Add directly to scene (not to handLayer) so the hit area transform is // computed correctly — nested containers break Phaser's input matrix chain. cont.setDepth(DEPTH.ui) .setInteractive(new Phaser.Geom.Rectangle(-cardW / 2, -cardH / 2, cardW, cardH), Phaser.Geom.Rectangle.Contains); cont.on('pointerup', () => this.onCardClick(card, i)); - cont.on('pointerover', () => { if (!this.busy) cont.y = y - 8; }); + cont.on('pointerover', () => { if (!this.busy) cont.y = y - 10; }); cont.on('pointerout', () => { cont.y = y; }); this.handCards.push(cont); }); + if (!me.hand.length) { + const t = this.add.text(RAIL_X + 8, 930, 'Nothing in your pack yet.', { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '16px', color: INK.faded, + }).setDepth(DEPTH.ui); + this.handCards.push(t); + } } renderBanner() { const cur = this.gs.players[this.gs.current]; const isHuman = cur.seat === this.humanSeat; - this.bannerBg.clear(); - this.bannerBg.fillStyle(isHuman ? 0x2e5a2e : 0x3a2c14, 0.8); - this.bannerBg.fillRoundedRect(RAIL_X, 96, RAIL_W, 56, 10); + const g = this.bannerBg; g.clear(); + const x = RAIL_X, y = 100, w = RAIL_W, h = 48; + g.fillStyle(0x000000, 0.25); g.fillRoundedRect(x + 3, y + 4, w, h, 8); + g.fillGradientStyle(0xf0d58c, 0xf0d58c, 0x9a7428, 0x9a7428, 1); + g.fillRoundedRect(x, y, w, h, 8); + g.lineStyle(2, 0x3a2808, 1); g.strokeRoundedRect(x, y, w, h, 8); + g.lineStyle(1, 0xfff2c8, 0.6); g.strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 6); + g.fillStyle(isHuman ? 0x3a6a3a : ROLES[cur.role].color, 1); g.fillCircle(x + w - 22, y + h / 2, 7); + g.lineStyle(1.5, 0x3a2808, 1); g.strokeCircle(x + w - 22, y + h / 2, 7); + for (const sx of [x + 9, x + w - 9]) { g.fillStyle(0x5a3f14, 1); g.fillCircle(sx, y + h / 2, 2.5); } const name = this.partnerNames[cur.seat]; let msg; - if (this.gs.phase === 'discard') msg = `${this.partnerNames[this.gs.pendingDiscard]} must discard a card (hand limit ${HAND_LIMIT})`; - else if (isHuman) msg = `Your turn — ${ROLES[cur.role].name} · ${this.gs.actionsLeft} action${this.gs.actionsLeft === 1 ? '' : 's'} left`; - else msg = `${name}'s turn — ${ROLES[cur.role].name}`; - this.bannerText.setText(msg); + if (this.gs.phase === 'discard') msg = `${this.partnerNames[this.gs.pendingDiscard]} must discard a card (pack limit ${HAND_LIMIT})`; + else if (this.gs.phase === 'swim') msg = `Your tile sank. Choose where to swim.`; + else if (isHuman) msg = `Your turn, ${ROLES[cur.role].name}: ${this.gs.actionsLeft} action${this.gs.actionsLeft === 1 ? '' : 's'} left`; + else msg = `${name}'s turn, the ${ROLES[cur.role].name}`; + this.bannerText.setText(msg).setY(y + h / 2); } renderButtons() { @@ -770,15 +847,45 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.escapeBtn.setEnabled(esc).setAlpha(esc ? 1 : 0.4); } + // The expedition log: newest entries at the bottom, each with the speaker's + // figurine, name and words; narration in italics. renderChat() { - // Show the last messages that fit the box. - const lines = this.messages.map((m) => m.role ? `${roleEmoji(m.role)} ${this.speaker(m)}: ${m.text}` : `• ${m.text}`); - // keep last ~10 - this.chatText.setText(lines.slice(-10).join('\n')); - // if overflowing, trim from top until it fits - while (this.chatText.height > this.chatBox.h && this.messages.length > 1) { - this.messages.shift(); - this.chatText.setText(this.messages.slice(-10).map((m) => m.role ? `${roleEmoji(m.role)} ${this.speaker(m)}: ${m.text}` : `• ${m.text}`).join('\n')); + for (const o of this.chatObjs ?? []) o.destroy(); + this.chatObjs = []; + const { x, y, w, h } = this.chatBox; + let bottom = y + h; + for (let i = this.messages.length - 1; i >= 0; i--) { + const m = this.messages[i]; + const objs = []; + let blockH; + if (m.role) { + const who = this.add.text(x + 26, 0, this.speaker(m), { + fontFamily: BODY_FONT, fontStyle: 'bold', fontSize: '15px', color: INK.ink, + }).setDepth(DEPTH.ui); + const tag = this.add.text(x + 32 + who.width, 2, ROLES[m.role]?.name ?? '', { + fontFamily: TYPE_FONT, fontSize: '11px', color: INK.faded, + }).setDepth(DEPTH.ui); + const body = this.add.text(x + 26, 19, m.text, { + fontFamily: BODY_FONT, fontSize: '15px', color: INK.inkSoft, wordWrap: { width: w - 30 }, lineSpacing: 2, + }).setDepth(DEPTH.ui); + const fig = this.add.image(x + 10, 30, `di-pawn-${m.role}`).setOrigin(0.5, 1).setDisplaySize(19, 28).setDepth(DEPTH.ui); + objs.push(who, tag, body, fig); + blockH = 19 + body.height; + } else { + const body = this.add.text(x + 26, 0, m.text, { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '15px', color: INK.blue, wordWrap: { width: w - 30 }, lineSpacing: 2, + }).setDepth(DEPTH.ui); + const mark = this.add.text(x + 4, 0, '~', { fontFamily: BODY_FONT, fontSize: '18px', color: INK.blue }).setDepth(DEPTH.ui); + objs.push(body, mark); + blockH = body.height; + } + const top = bottom - blockH; + if (top < y) { objs.forEach((o) => o.destroy()); break; } + objs.forEach((o) => { o.y += top; }); + const age = this.messages.length - 1 - i; + objs.forEach((o) => o.setAlpha(Math.max(0.55, 1 - age * 0.07))); + this.chatObjs.push(...objs); + bottom = top - 12; } } @@ -789,12 +896,17 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // ── Target highlighting for the human ─────────────────────────────────────── highlightTargets() { - // clear previous for (const v of Object.values(this.tileViews)) if (v.hl) { v.hl.destroy(); v.hl = null; } if (this.busy) return; let tiles = new Set(); + let swimming = false; if (this.mode === 'sandbags') tiles = new Set(Object.values(this.gs.tiles).filter((t) => t.state === 'flooded').map((t) => t.id)); - else if (this.mode === 'helicopter') tiles = new Set(Object.values(this.gs.tiles).filter((t) => t.state !== 'sunk' && t.id !== this.gs.players[this.humanSeat].tileId).map((t) => t.id)); + else if (this.mode === 'helicopter') { + if (!this.modeData?.fromTileId) tiles = new Set(this.gs.players.map((p) => p.tileId)); + else tiles = new Set(Object.values(this.gs.tiles).filter((t) => t.state !== 'sunk' && t.id !== this.modeData.fromTileId).map((t) => t.id)); + } else if (this.gs.phase === 'swim' && this.gs.pendingSwim?.seat === this.humanSeat) { + tiles = new Set(this.gs.pendingSwim.options); + } else if (this.mode === 'navigate' && this.modeData?.targetSeat != null) { for (const a of legalActions(this.gs, this.humanSeat)) if (a.type === 'navMove' && a.targetSeat === this.modeData.targetSeat) tiles.add(a.tileId); } else if (this.gs.current === this.humanSeat && this.gs.phase === 'actions') { @@ -803,13 +915,19 @@ export default class ForbiddenIslandGame extends Phaser.Scene { if (a.type === 'shoreUp') a.tiles.forEach((id) => tiles.add(id)); } } + // Lantern light on every tile you can act on (sea-green for a swim). + const col = this.gs.phase === 'swim' ? 0x8ff0e0 : 0xffd77a; for (const id of tiles) { const v = this.tileViews[id]; - const hl = this.add.graphics().setDepth(DEPTH.tile - 1); const { x, y } = this.tileWorld(this.gs.tiles[id]); - hl.lineStyle(4, 0xfff3b0, 0.9); hl.strokeRoundedRect(x - TILE / 2 - 3, y - TILE / 2 - 3, TILE + 6, TILE + 6, 16); + const hl = this.add.graphics().setDepth(DEPTH.tile + 1).setPosition(x, y); + const S = TILE + 26; + hl.lineStyle(10, col, 0.22); hl.strokeRoundedRect(-S / 2, -S / 2, S, S, 12); + hl.lineStyle(3, col, 0.95); hl.strokeRoundedRect(-S / 2 + 2, -S / 2 + 2, S - 4, S - 4, 10); + this.tweens.add({ targets: hl, alpha: { from: 1, to: 0.45 }, duration: 750, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); v.hl = hl; } + void swimming; } // ── Human interactions ────────────────────────────────────────────────────── @@ -818,6 +936,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { if (this.mode === 'sandbags') return this.resolveSandbags(tileId); if (this.mode === 'helicopter') return this.resolveHelicopter(tileId); if (this.mode === 'navigate') return this.resolveNavigate(tileId); + if (this.gs.phase === 'swim' && this.gs.pendingSwim?.seat === this.humanSeat) return this.resolveHumanSwim(tileId); if (this.gs.current !== this.humanSeat || this.gs.phase !== 'actions') return; const acts = legalActions(this.gs, this.humanSeat).filter((a) => @@ -835,6 +954,17 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.showActionPopup(tileId, acts); } + resolveHumanSwim(tileId) { + if (!this.gs.pendingSwim.options.includes(tileId)) return; + const from = this.gs.players[this.humanSeat].tileId; + this.busy = true; + this.animatePawnMove(this.humanSeat, from, tileId, () => { + this.gs = resolveSwim(this.gs, this.humanSeat, tileId); + this.render(); + this.advance(); + }); + } + showActionPopup(tileId, acts) { this.closePopup(); const t = this.gs.tiles[tileId]; const { x, y } = this.tileWorld(t); @@ -859,8 +989,8 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const before = this.gs; this.gs = applyAction(this.gs, this.humanSeat, action); this.busy = false; - if (this.gs !== before) this.render(); - }); + if (this.gs !== before) { this.undoStack.push(before); this.render(); } + }, action.type === 'fly' ? 'fly' : null); return; } } @@ -872,7 +1002,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const before = this.gs; this.gs = applyAction(this.gs, this.humanSeat, action); this.busy = false; - if (this.gs !== before) this.render(); + if (this.gs !== before) { this.undoStack.push(before); this.render(); } return; } this.animateShoreUp(tiles.shift(), next); @@ -883,8 +1013,12 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const before = this.gs; this.gs = applyAction(this.gs, this.humanSeat, action); if (this.gs === before) return; + this.undoStack.push(before); if (action.type === 'capture') { - this.post(this.gs.players[this.humanSeat].role, lineForEvent('capture', { role: this.gs.players[this.humanSeat].role, treasure: action.treasure, remaining: 4 - capturedCount(this.gs) }).text, this.humanSeat); + this.undoStack = []; + this.render(); + this.playCapture(this.humanSeat, action.treasure, () => { this.busy = false; this.render(); }); + return; } this.render(); } @@ -901,12 +1035,16 @@ export default class ForbiddenIslandGame extends Phaser.Scene { if (this.gs.phase === 'discard' && this.gs.pendingDiscard === this.humanSeat) { this.gs = discardCard(this.gs, this.humanSeat, card); this.render(); - if (this.gs.phase !== 'discard') this.progress(); + if (this.gs.phase !== 'discard') { + const resume = this.resumeAiStep; this.resumeAiStep = null; + if (resume) { this.busy = true; resume(); } else this.progress(); + } return; } - if (this.gs.current !== this.humanSeat || this.gs.phase !== 'actions') return; + const swimming = this.gs.phase === 'swim' && this.gs.pendingSwim?.seat === this.humanSeat; + if (!swimming && (this.gs.current !== this.humanSeat || this.gs.phase !== 'actions')) return; if (card === SPECIAL.SANDBAGS) { this.mode = 'sandbags'; this.flashHint('Sandbags: click any flooded tile to shore it up.'); return this.render(); } - if (card === SPECIAL.HELICOPTER) { this.mode = 'helicopter'; this.flashHint('Helicopter Lift: click a tile to fly your pawn there.'); return this.render(); } + if (card === SPECIAL.HELICOPTER) { this.mode = 'helicopter'; this.modeData = null; this.flashHint('Helicopter Lift: click the tile whose adventurers should fly, then the destination.'); return this.render(); } } // ── Trade Modal ────────────────────────────────────────────────────────────── @@ -941,19 +1079,23 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Panel background + gold border const panelG = reg(this.add.graphics().setDepth(DEPTH.popup + 1)); - panelG.fillStyle(0x061a2a, 1); + panelG.fillStyle(0x2a1d14, 1); panelG.fillRoundedRect(panelX, panelY, panelW, panelH, 18); panelG.lineStyle(2, COLORS.gold, 1); panelG.strokeRoundedRect(panelX, panelY, panelW, panelH, 18); // Title - reg(this.add.text(cx, panelY + 20, 'Trade Cards', { - fontFamily: 'Righteous', fontSize: '28px', color: COLORS.goldHex, + reg(this.add.text(cx, panelY + 20, 'Give a Treasure Card', { + fontFamily: DISPLAY_FONT, fontSize: '28px', color: COLORS.goldHex, }).setOrigin(0.5, 0).setDepth(DEPTH.popup + 2)); // Instruction - reg(this.add.text(cx, panelY + 56, 'Click two cards from different players to trade', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, + const me = this.gs.players[this.humanSeat]; + const giveHint = me.role === 'messenger' + ? 'Pick one of your Treasure cards, then a teammate anywhere on the island (1 action)' + : 'Pick one of your Treasure cards, then a teammate on your tile (1 action)'; + reg(this.add.text(cx, panelY + 56, giveHint, { + fontFamily: BODY_FONT, fontSize: '14px', color: COLORS.mutedHex, }).setOrigin(0.5, 0).setDepth(DEPTH.popup + 2)); // Close button (top-right) @@ -965,7 +1107,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { for (let i = 1; i < N; i++) { const divX = panelX + i * colW; const divG = reg(this.add.graphics().setDepth(DEPTH.popup + 2)); - divG.lineStyle(1, 0x1a3a50, 0.6); + divG.lineStyle(1, 0x5a4020, 0.6); divG.lineBetween(divX, panelY + 8, divX, panelY + panelH - 8); } @@ -977,7 +1119,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Portrait circle + ring const portG = reg(this.add.graphics().setDepth(DEPTH.popup + 2)); - portG.fillStyle(0x07202e, 1); + portG.fillStyle(0x1e140c, 1); portG.fillCircle(portCX, portCY, portR); portG.lineStyle(4, role.color, 1); portG.strokeCircle(portCX, portCY, portR); @@ -999,17 +1141,17 @@ export default class ForbiddenIslandGame extends Phaser.Scene { avG.fillCircle(portCX, portCY, portR - 3); const initial = player.seat === this.humanSeat ? 'Y' : role.name[0]; reg(this.add.text(portCX, portCY, initial, { - fontFamily: 'Righteous', fontSize: '24px', color: '#ffffff', + fontFamily: DISPLAY_FONT, fontSize: '24px', color: '#ffffff', }).setOrigin(0.5).setDepth(DEPTH.popup + 4)); } // Name + role const displayName = player.seat === this.humanSeat ? 'You' : (this.partnerNames[player.seat] ?? `Player ${player.seat}`); reg(this.add.text(textX, nameY, displayName, { - fontFamily: 'Righteous', fontSize: '14px', color: COLORS.textHex, + fontFamily: DISPLAY_FONT, fontSize: '14px', color: COLORS.textHex, }).setDepth(DEPTH.popup + 3)); reg(this.add.text(textX, roleY, role.name, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: role.colorHex, + fontFamily: BODY_FONT, fontSize: '12px', color: role.colorHex, }).setDepth(DEPTH.popup + 3)); // Direction pill (AI players only, right-aligned in column) @@ -1020,11 +1162,11 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const pillBg = reg(this.add.graphics().setDepth(DEPTH.popup + 4)); pillBg.fillStyle(0x0a2538, 1); pillBg.fillRoundedRect(pillRight - pillW, pillTop, pillW, pillH, 4); - pillBg.lineStyle(1, 0x2a5070, 1); + pillBg.lineStyle(1, 0xc9a14a, 1); pillBg.strokeRoundedRect(pillRight - pillW, pillTop, pillW, pillH, 4); reg(this.add.text(pillRight - pillW / 2, pillTop + pillH / 2, this.directionLabel(this.seatDirections[player.seat] ?? null) + ' ▼', { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: COLORS.mutedHex, + fontFamily: BODY_FONT, fontSize: '11px', color: COLORS.mutedHex, }).setOrigin(0.5).setDepth(DEPTH.popup + 5)); const pillZone = reg(this.add.zone(pillRight - pillW, pillTop, pillW, pillH) .setOrigin(0, 0).setInteractive({ useHandCursor: true }).setDepth(DEPTH.popup + 5)); @@ -1033,10 +1175,23 @@ export default class ForbiddenIslandGame extends Phaser.Scene { }); } + // Whole column is a drop target for a selected card (works for empty hands). + if (player.seat !== this.humanSeat) { + const canReach = me.role === 'messenger' || player.tileId === me.tileId; + const colZone = reg(this.add.zone(panelX + i * colW, panelY + 90, colW, panelH - 90) + .setOrigin(0, 0).setInteractive().setDepth(DEPTH.popup + 2)); + colZone.on('pointerup', () => this.onTradeCardClick(player.seat, -1, null, null, textX + cardW / 2, cardsTop + cardH / 2)); + if (!canReach) { + reg(this.add.text(panelX + (i + 0.5) * colW, panelY + panelH - 14, 'not on your tile', { + fontFamily: BODY_FONT, fontSize: '11px', color: COLORS.mutedHex, + }).setOrigin(0.5, 1).setDepth(DEPTH.popup + 3)); + } + } + // Hand cards (wrap to second row after CARDS_PER_ROW) if (!player.hand.length) { reg(this.add.text(textX, cardsTop + cardH / 2, 'No cards', { - fontFamily: '"Julius Sans One"', fontSize: '11px', color: COLORS.mutedHex, + fontFamily: BODY_FONT, fontSize: '11px', color: COLORS.mutedHex, }).setOrigin(0, 0.5).setDepth(DEPTH.popup + 3)); } else { player.hand.forEach((card, ci) => { @@ -1084,24 +1239,52 @@ export default class ForbiddenIslandGame extends Phaser.Scene { } onTradeCardClick(seat, cardIdx, card, frame, wx, wy) { - if (!this.tradeSelection) { + if (this.busy) return; + if (seat === this.humanSeat) { + if (!card) return; + if (!card.startsWith('treasure:')) { this.flashHint('Only Treasure cards can be given.'); return; } this.tradeSelection = { seat, cardIdx, card, frame, worldX: wx, worldY: wy }; this.refreshTradeHighlight(); - } else if (this.tradeSelection.seat === seat) { - // Same player — change selection - this.tradeSelection = { seat, cardIdx, card, frame, worldX: wx, worldY: wy }; - this.refreshTradeHighlight(); - } else { - // Different player — animate swap then apply - const sel = this.tradeSelection; - this.tradeSelection = null; - this.animateCardSwap(sel.worldX, sel.worldY, sel.frame, sel.card, wx, wy, frame, card, () => { - this.gs = swapCards(this.gs, sel.seat, sel.card, seat, card); - this.closeTradeModal(); - this.openTradeModal(); - this.render(); - }); + return; } + const sel = this.tradeSelection; + if (!sel) { this.flashHint('First pick one of your own Treasure cards.'); return; } + if (this.gs.current !== this.humanSeat || this.gs.phase !== 'actions') { this.flashHint('You can only give cards on your turn.'); return; } + const act = legalActions(this.gs, this.humanSeat) + .find((a) => a.type === 'give' && a.targetSeat === seat && a.card === sel.card); + if (!act) { + this.flashHint(this.gs.actionsLeft <= 0 ? 'No actions left this turn.' : `${this.partnerNames[seat]} must be on your tile to receive a card.`); + return; + } + this.tradeSelection = null; + this.busy = true; + Sound.give(this); + this.animateCardGive(sel.worldX, sel.worldY, sel.frame, sel.card, wx, wy, () => { + const before = this.gs; + this.gs = applyAction(this.gs, this.humanSeat, act); + this.busy = false; + this.closeTradeModal(); + if (this.gs.phase === 'discard') this.undoStack = []; else this.undoStack.push(before); + this.react('thanks', { actorSeat: this.humanSeat, speakerSeat: seat, chance: 0.8 }); + this.render(); + if (this.gs.phase === 'discard') this.progress(); + }); + } + + animateCardGive(xA, yA, frame, card, xB, yB, onDone) { + const cardW = 70, cardH = 95; + const hasArt = this.textures.exists('forbiddenisland-cards'); + let inner; + if (frame != null && hasArt) inner = this.add.image(0, 0, 'forbiddenisland-cards', frame).setDisplaySize(cardW, cardH); + else { + inner = this.add.graphics(); + inner.fillStyle(cardInfo(card ?? '')?.color ?? 0x334455, 1); inner.fillRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 6); + } + const c = this.add.container(xA, yA, [inner]).setDepth(DEPTH.popup + 7); + this.tweens.add({ + targets: c, x: xB, y: yB, duration: 600, ease: 'Cubic.easeInOut', + onComplete: () => { c.destroy(); onDone(); }, + }); } refreshTradeHighlight() { @@ -1117,59 +1300,46 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.tradeHighlightObjs.push(glow); } - animateCardSwap(xA, yA, frameA, cardA, xB, yB, frameB, cardB, onDone) { - const D = DEPTH.popup + 7; - const cardW = 70, cardH = 95; - const hasArt = this.textures.exists('forbiddenisland-cards'); - - const makeCard = (x, y, frame, card) => { - const inner = (frame != null && hasArt) - ? this.add.image(0, 0, 'forbiddenisland-cards', frame).setDisplaySize(cardW, cardH) - : (() => { - const g = this.add.graphics(); - const info = cardInfo(card ?? ''); - g.fillStyle(info?.color ?? 0x334455, 1); g.fillRoundedRect(-cardW / 2, -cardH / 2, cardW, cardH, 6); - return g; - })(); - return this.add.container(x, y, [inner]).setDepth(D); - }; - - const imgA = makeCard(xA, yA, frameA, cardA); - const imgB = makeCard(xB, yB, frameB, cardB); - - this.tweens.add({ targets: imgA, x: xB, y: yB, duration: 700, ease: 'Cubic.easeInOut' }); - this.tweens.add({ - targets: imgB, x: xA, y: yA, duration: 700, ease: 'Cubic.easeInOut', - onComplete: () => { imgA.destroy(); imgB.destroy(); onDone(); }, - }); - } - resolveSandbags(tileId) { if (this.gs.tiles[tileId].state !== 'flooded') return; this.mode = null; this.busy = true; this.animateShoreUp(tileId, () => { + this.pushUndo(); this.gs = playSandbags(this.gs, this.humanSeat, tileId); + this.moment('bags', `You sandbagged ${this.gs.tiles[tileId].name}.`); this.busy = false; this.render(); }); } + // Helicopter Lift, two clicks: a tile with pawns (everyone there flies + // together), then the destination. resolveHelicopter(tileId) { - if (this.gs.tiles[tileId].state === 'sunk') return; - const fromTileId = this.gs.players[this.humanSeat].tileId; - this.mode = null; - if (fromTileId !== tileId) { - this.busy = true; - this.animatePawnMove(this.humanSeat, fromTileId, tileId, () => { - this.gs = playHelicopter(this.gs, this.humanSeat, [this.humanSeat], tileId); - this.busy = false; - this.render(); - }); - } else { - this.gs = playHelicopter(this.gs, this.humanSeat, [this.humanSeat], tileId); - this.render(); + const t = this.gs.tiles[tileId]; + if (!this.modeData?.fromTileId) { + const seats = this.gs.players.filter((p) => p.tileId === tileId).map((p) => p.seat); + if (!seats.length) { this.flashHint('Pick a tile with adventurers on it to lift.'); return; } + this.modeData = { fromTileId: tileId, seats }; + this.flashHint(`Lifting ${seats.map((s) => this.partnerNames[s]).join(' + ')} — now click the destination.`); + return this.render(); } + if (t.state === 'sunk' || tileId === this.modeData.fromTileId) return; + const { seats, fromTileId } = this.modeData; + this.mode = null; this.modeData = null; + this.busy = true; + let pending = seats.length; + const done = () => { + if (--pending > 0) return; + this.pushUndo(); + this.gs = playHelicopter(this.gs, this.humanSeat, seats, tileId); + this.moment('heli', `Helicopter Lift to ${this.gs.tiles[tileId].name}.`); + this.busy = false; + this.render(); + if (this.gs.phase !== 'swim' && this.gs.phase !== 'actions') this.advance(); + else if (this.gs.phase === 'actions' && this.gs.current !== this.humanSeat) this.advance(); + }; + for (const seat of seats) this.animatePawnMove(seat, fromTileId, tileId, done, 'fly'); } startNavigate(targetSeat) { @@ -1186,10 +1356,11 @@ export default class ForbiddenIslandGame extends Phaser.Scene { if (fromTileId !== tileId) { this.busy = true; this.animatePawnMove(act.targetSeat, fromTileId, tileId, () => { + this.pushUndo(); this.gs = applyAction(this.gs, this.humanSeat, act); this.busy = false; this.render(); - }); + }, 'nav'); } else { this.gs = applyAction(this.gs, this.humanSeat, act); this.render(); @@ -1262,9 +1433,9 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Popup container const ctr = this.add.container(clampedX, clampedY).setDepth(baseDepth); const bg = this.add.graphics(); - bg.fillStyle(0x061a2a, 1); + bg.fillStyle(0x2a1d14, 1); bg.fillRoundedRect(0, 0, menuW, menuH, 6); - bg.lineStyle(1, 0x2a5070, 1); + bg.lineStyle(1, 0xc9a14a, 1); bg.strokeRoundedRect(0, 0, menuW, menuH, 6); ctr.add(bg); @@ -1277,13 +1448,13 @@ export default class ForbiddenIslandGame extends Phaser.Scene { ctr.add(rowBg); const bullet = this.add.text(padX, ry + rowH / 2, isCurrent ? '●' : '○', { - fontFamily: '"Julius Sans One"', fontSize: '10px', - color: isCurrent ? COLORS.accentHex : COLORS.mutedHex, + fontFamily: BODY_FONT, fontSize: '10px', + color: isCurrent ? INK.brassHex : COLORS.mutedHex, }).setOrigin(0, 0.5); ctr.add(bullet); const lbl = this.add.text(padX + 14, ry + rowH / 2, opt.label, { - fontFamily: '"Julius Sans One"', fontSize: '12px', + fontFamily: BODY_FONT, fontSize: '12px', color: isCurrent ? COLORS.textHex : COLORS.mutedHex, }).setOrigin(0, 0.5); ctr.add(lbl); @@ -1319,20 +1490,12 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const willSink = this.gs.tiles[tileId].state === 'flooded'; // already flooded → will sink // 1. Face-down card at deck origin - const back = this.add.graphics().setDepth(depth); - const bw = 80, bh = 108; - back.fillStyle(0x0a2030, 1); - back.fillRoundedRect(-bw / 2, -bh / 2, bw, bh, 8); - back.lineStyle(2, 0x2a4a60, 1); - back.strokeRoundedRect(-bw / 2, -bh / 2, bw, bh, 8); - back.lineStyle(1, 0x1a3a50, 0.5); - back.strokeRoundedRect(-bw / 2 + 8, -bh / 2 + 8, bw - 16, bh - 16, 4); + const bw = BACK.w, bh = BACK.h; + const back = this.add.container(0, 0, [this.add.image(0, 0, 'di-back-flood').setDisplaySize(bw, bh)]).setDepth(depth); back.x = this.floodDeckPos.x; back.y = this.floodDeckPos.y; - if (this.sound.get('sfx-card-deal') || this.cache.audio.exists('sfx-card-deal')) { - this.sound.play('sfx-card-deal', { volume: 0.4 }); - } + Sound.card(this); // 2. Tween to center, scale up to 200×200 const scaleTarget = 200 / 200; // native size = 1.0 @@ -1356,12 +1519,10 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const img = this.add.image(0, 0, 'forbiddenisland-tiles', frameIdx) .setDisplaySize(200, 200); const borderGfx = this.add.graphics(); - borderGfx.lineStyle(3, 0xd4c08a, 1); + borderGfx.lineStyle(6, 0xc9a14a, 1); borderGfx.strokeRoundedRect(-100, -100, 200, 200, 12); const faceCard = this.add.container(cx, cy, [img, borderGfx]).setDepth(depth); - if (this.sound.get('sfx-card-show') || this.cache.audio.exists('sfx-card-show')) { - this.sound.play('sfx-card-show', { volume: 0.35 }); - } + Sound.card(this); // Flip open faceCard.scaleX = 0; this.tweens.add({ @@ -1383,22 +1544,17 @@ export default class ForbiddenIslandGame extends Phaser.Scene { ease: 'Cubic.easeIn', onComplete: () => { faceCard.destroy(); - // 6. Apply tile state (flooded or sunk) and animate + // 6. Apply tile state (flooded or sunk) and animate it on the island. this.gs.tiles[tileId].state = willSink ? 'sunk' : 'flooded'; - this.drawTile(this.gs.tiles[tileId]); - const sfxKey = willSink ? 'sfx-water-sink' : 'sfx-water-splash'; - if (this.cache.audio.exists(sfxKey)) this.sound.play(sfxKey, { volume: 0.7 }); + if (willSink) Sound.sink(this); else Sound.splash(this); const tileView = this.tileViews[tileId]; - if (willSink && tileView) { - // Brief shake on the tile to signal sinking - this.tweens.add({ - targets: tileView.container, - x: { from: tileView.container.x - 6, to: tileView.container.x }, - yoyo: true, repeat: 3, duration: 40, ease: 'Linear', - onComplete: () => this.time.delayedCall(150, onDone), - }); + if (!tileView) { this.time.delayedCall(200, onDone); return; } + if (willSink) { + const t = this.gs.tiles[tileId]; + if (t.treasure || t.landing) this.storm.strike({ x: tx, bright: 0.4 }); + tileView.sink(() => this.time.delayedCall(150, onDone)); } else { - this.time.delayedCall(200, onDone); + tileView.flood(() => this.time.delayedCall(120, onDone)); } }, }); @@ -1415,6 +1571,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { onEndTurn() { if (this.gs.current !== this.humanSeat || this.gs.phase !== 'actions' || this.busy) return; this.mode = null; + this.undoStack = []; this.busy = true; this.animateTreasureDraw(this.humanSeat, () => { this.gs = endActions(this.gs); @@ -1427,6 +1584,9 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // the human's action phase again (or the game ends). advance() { if (isGameOver(this.gs)) return this.endGame(); + this.noteDay(); + if (this.gs.phase === 'actions' && this.gs.current === this.humanSeat && !this.gs.pendingSwim) this.saveGame(); + if (this.gs.phase === 'swim') { this.busy = false; this.render(); return; } if (this.gs.phase === 'actions') { if (this.gs.current === this.humanSeat) { this.busy = false; this.render(); return; } return this.aiTurn(this.gs.current); @@ -1443,7 +1603,40 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.render(); return this.time.delayedCall(350, () => this.progress()); } - if (this.gs.phase === 'flood') return this.animateFlood(); + if (this.gs.phase === 'flood') { + // Last call before the flood: a partner may drop Sandbags or fly someone + // out if the coming draw threatens something vital. + if (!this._floodCardAsked && this.engine) { + this._floodCardAsked = true; + const engine = this.engine; + return engine.request('free', { state: this.gs, seat: this.gs.current, minGain: 300 }).then((free) => { + if (this.engine !== engine || !this.sys.isActive()) return; + if (free) { + const role = this.gs.players[free.seat].role; + const before = this.gs; + if (free.type === 'sandbags') this.gs = playSandbags(this.gs, free.seat, free.tileId); + else this.gs = playHelicopter(this.gs, free.seat, free.pawnSeats, free.destTileId); + if (this.gs !== before) { + if (free.type === 'sandbags') { this.tileViews[free.tileId]?.shore(); Sound.shore(this); } + this.moment(free.type === 'sandbags' ? 'bags' : 'heli', free.type === 'sandbags' + ? `${this.partnerNames[free.seat]} sandbagged ${this.gs.tiles[free.tileId].name} just before the flood.` + : `${this.partnerNames[free.seat]} flew the crew to ${this.gs.tiles[free.destTileId].name} just before the flood.`); + if (free.seat !== this.humanSeat) this.react('thanks', { actorSeat: free.seat, chance: 0.35 }); + const text = free.type === 'sandbags' + ? lineForEvent('sandbags', { role, tileName: this.gs.tiles[free.tileId].name }).text + : lineForEvent('heliMove', { role, who: free.pawnSeats.map((ps) => this.partnerNames[ps]).join(' + '), tileName: this.gs.tiles[free.destTileId].name }).text; + this.post(role, text, free.seat); + this.render(); + this._floodCardAsked = false; // allow a second emergency card + return this.time.delayedCall(450, () => this.progress()); + } + } + this.progress(); + }).catch(() => this.progress()); + } + this._floodCardAsked = false; + return this.animateFlood(); + } return this.advance(); } @@ -1464,13 +1657,23 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Voice notable events. for (const ev of events) { + const t = this.gs.tiles[ev.tileId]; if (ev.kind === 'sink') { - const name = this.gs.tiles[ev.tileId]?.name ?? ev.tileId; + const name = t?.name ?? ev.tileId; this.post(null, lineForEvent('sink', { tileName: name }).text); + this.moment('sink', `${name} sank${t?.treasure ? `, a shrine of ${TREASURES[t.treasure].name}` : ''}.`); + if (t?.treasure && !this.gs.players.some((p) => p.captured[t.treasure])) this.react('sinkShrine', { tile: name, relic: t.treasure, chance: 0.7 }); } + if (ev.kind === 'flood' && t?.landing) this.react('dockWet', { chance: 0.9 }); } this.render(); + if (this.gs.phase === 'swim') { + this.busy = false; + this.flashHint('Your tile sank! Click a highlighted tile to swim to safety.'); + this.render(); + return; + } this.time.delayedCall(200, () => { this.busy = false; this.advance(); }); }); } @@ -1510,17 +1713,11 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const frame = hasArt ? cardFrame(card) : null; // 1. Face-down back card at the treasure deck pile position - const back = this.add.graphics().setDepth(depth); - back.fillStyle(0x0a2030, 1); - back.fillRoundedRect(-BACK_W / 2, -BACK_H / 2, BACK_W, BACK_H, 8); - back.lineStyle(2, 0x2a4a60, 1); - back.strokeRoundedRect(-BACK_W / 2, -BACK_H / 2, BACK_W, BACK_H, 8); - back.lineStyle(1, 0x1a3a50, 0.5); - back.strokeRoundedRect(-BACK_W / 2 + 8, -BACK_H / 2 + 8, BACK_W - 16, BACK_H - 16, 4); + const back = this.add.container(0, 0, [this.add.image(0, 0, 'di-back-treasure').setDisplaySize(BACK_W, BACK_H)]).setDepth(depth); back.x = this.treasureDeckPos.x; back.y = this.treasureDeckPos.y; - if (this.cache.audio.exists('sfx-card-deal')) this.sound.play('sfx-card-deal', { volume: 0.4 }); + Sound.card(this); // 2. Tween to center, scale up to 270×390 this.tweens.add({ @@ -1547,7 +1744,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { if (frame != null) { const img = this.add.image(0, 0, 'forbiddenisland-cards', frame).setScale(SX_DRAW, SY_DRAW); const borderGfx = this.add.graphics(); - borderGfx.lineStyle(3, 0xd4c08a, 1); + borderGfx.lineStyle(6, 0xc9a14a, 1); borderGfx.strokeRoundedRect(-DRAW_W / 2, -DRAW_H / 2, DRAW_W, DRAW_H, 12); faceContent = [img, borderGfx]; } else { @@ -1559,14 +1756,14 @@ export default class ForbiddenIslandGame extends Phaser.Scene { g.lineStyle(3, 0xd4c08a, 1); g.strokeRoundedRect(-DRAW_W / 2, -DRAW_H / 2, DRAW_W, DRAW_H, 16); const lbl = this.add.text(0, 0, info.label, { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: info.text, align: 'center', + fontFamily: BODY_FONT, fontSize: '28px', color: info.text, align: 'center', }).setOrigin(0.5); faceContent = [g, lbl]; } const faceObj = this.add.container(cx, cy, faceContent).setDepth(depth); faceObj.scaleX = 0; - if (this.cache.audio.exists('sfx-card-show')) this.sound.play('sfx-card-show', { volume: 0.35 }); + Sound.card(this); // Flip open — container collapses to scaleX=0 then reopens to 1 this.tweens.add({ @@ -1590,7 +1787,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { duration: 350, ease: 'Cubic.easeIn', onComplete: () => { - if (this.cache.audio.exists('sfx-card-place')) this.sound.play('sfx-card-place', { volume: 0.3 }); + Sound.card(this); this.tempHandImages.push(faceObj); onDone(); }, @@ -1610,7 +1807,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { duration: 380, ease: 'Cubic.easeIn', onComplete: () => { - if (this.cache.audio.exists('sfx-card-place')) this.sound.play('sfx-card-place', { volume: 0.2 }); + Sound.card(this); faceObj.destroy(); onDone(); }, @@ -1647,61 +1844,41 @@ export default class ForbiddenIslandGame extends Phaser.Scene { }); } - // Animate the water level rising: fade in the new segment, slide the triangle marker up. + // The waters rise: lightning over the island, the tide gauge's liquid surges + // up a band and the sea darkens (drawWaterMeter runs on the next render). animateWaterRise(oldLevel, onDone) { - const D = DEPTH.ui + 2; const newLevel = Math.min(oldLevel + 1, MAX_WATER); - const segH = (this.waterBottom - this.waterTop) / MAX_WATER; - const w = 40, barX = this.waterX - w / 2; - - const segColor = newLevel >= MAX_WATER ? 0xb22a2a - : newLevel >= 8 ? 0xd1632f - : 0x2f8fd0; - - // New-level segment overlay fades in from transparent - const newSegY = this.waterTop + (MAX_WATER - newLevel) * segH; - const segG = this.add.graphics().setDepth(D); - segG.fillStyle(segColor, 1); - segG.fillRoundedRect(barX, newSegY + 2, w, segH - 4, 6); - segG.lineStyle(1, 0x000000, 0.4); - segG.strokeRoundedRect(barX, newSegY + 2, w, segH - 4, 6); - segG.alpha = 0; - - // Gold triangle marker slides from old-level center to new-level center - const oldMarkerY = this.waterTop + (MAX_WATER - oldLevel) * segH + segH / 2; - const newMarkerY = this.waterTop + (MAX_WATER - newLevel) * segH + segH / 2; - const markG = this.add.graphics().setDepth(D + 1); - markG.fillStyle(COLORS.gold, 1); - markG.fillTriangle(-12, -8, -12, 8, -2, 0); - markG.x = barX; - markG.y = oldMarkerY; - - if (this.cache.audio.exists('sfx-water-raise')) this.sound.play('sfx-water-raise', { volume: 0.7 }); - - // Marker slides up quickly, segment fades in slowly - this.tweens.add({ - targets: markG, y: newMarkerY, duration: 600, ease: 'Cubic.easeOut', - onComplete: () => markG.destroy(), - }); - this.tweens.add({ - targets: segG, alpha: 1, duration: 900, ease: 'Cubic.easeOut', - onComplete: () => { - // Call onDone first (triggers endActions + render → drawWaterMeter redraws the - // filled segment on waterG), then destroy the overlay so there's no flash. - onDone(); - segG.destroy(); - }, - }); + Cine.watersRise(this); + this.moment('rise', `The waters rose to ${newLevel}.`); + this.react('watersRise', {}); + this.storm.strike({ bright: 0.65 }); + this.time.delayedCall(260, () => this.storm.strike({ bright: 0.35 })); + this.post(null, lineForEvent('watersRise', { waterLevel: newLevel }).text); + this.tweens.killTweensOf(this.gaugeFill); + this.waterLevelShown = newLevel; + this.tweens.add({ targets: this.gaugeFill, y: this.gaugeY(newLevel) - 10, duration: 500, ease: 'Cubic.easeOut', + onComplete: () => this.tweens.add({ targets: this.gaugeFill, y: this.gaugeY(newLevel), duration: 500, ease: 'Bounce.easeOut' }) }); + const glow = this.add.image(GAUGE.x, this.gaugeY(newLevel), 'di-glow').setDepth(DEPTH.ui + 2) + .setBlendMode(Phaser.BlendModes.ADD).setDisplaySize(120, 120).setTint(0x8fd8ff).setAlpha(0); + this.tweens.add({ targets: glow, alpha: { from: 0.9, to: 0 }, duration: 1000, onComplete: () => glow.destroy() }); + for (const v of Object.values(this.tileViews)) if (v.state !== 'sunk') this.sea.ripple(v.x, v.y, { size: TILE * 1.4, alpha: 0.35, delay: Math.random() * 400 }); + this.time.delayedCall(1000, onDone); } aiTurn(seat) { this.busy = true; + this.undoStack = []; this.gs = setPriority(this.gs, this.directionToPriority(this.gs, this.seatDirections[seat] ?? null)); - // Announce the plan. - const intent = describeIntent(this.gs, seat); - const line = lineForIntent(intent); - this.post(line.role, line.text, seat); this.render(); + const engine = this.engine; + const alive = () => this.engine === engine && this.sys.isActive(); + + // Announce the plan. + engine.request('intent', { state: this.gs, seat }).then((intent) => { + if (!alive() || !intent) return; + const line = lineForIntent(intent); + this.post(line.role, line.text, seat); + }).catch(() => {}); const step = () => { if (isGameOver(this.gs)) { this.render(); return this.endGame(); } @@ -1709,22 +1886,50 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.gs = attemptEscape(this.gs); this.render(); return this.time.delayedCall(400, () => this.endGame()); } - // Free special-card plays (Sandbags / Helicopter) before regular actions. - const free = chooseFreeCard(this.gs, seat); - if (free) { - const role = this.gs.players[seat].role; + const asked = this.gs; + engine.request('step', { state: asked, seat, skill: this.skillBySeat[seat] }) + .then((res) => { if (alive()) act(res ?? { end: true }); }) + .catch(() => { if (alive()) this.finishAiTurn(); }); + }; + + const act = (res) => { + // Free special-card plays (Sandbags / Helicopter), by whichever partner holds one. + if (res.free) { + const free = res.free; + const role = this.gs.players[free.seat].role; + const before = this.gs; if (free.type === 'sandbags') { - this.gs = playSandbags(this.gs, seat, free.tileId); - this.post(role, lineForEvent('sandbags', { role, tileName: this.gs.tiles[free.tileId].name }).text, seat); + this.gs = playSandbags(this.gs, free.seat, free.tileId); + if (this.gs !== before) { + this.post(role, lineForEvent('sandbags', { role, tileName: this.gs.tiles[free.tileId].name }).text, free.seat); + this.moment('bags', `${this.partnerNames[free.seat]} sandbagged ${this.gs.tiles[free.tileId].name}.`); + this.tileViews[free.tileId]?.shore(); Sound.shore(this); + } } else { - const who = roleName(this.gs.players[free.carrierSeat].role); - this.gs = playHelicopter(this.gs, seat, free.pawnSeats, free.destTileId); - this.post(role, lineForEvent('heliMove', { role, who, tileName: this.gs.tiles[free.destTileId].name }).text, seat); + const who = free.pawnSeats.map((ps) => this.partnerNames[ps]).join(' + '); + this.gs = playHelicopter(this.gs, free.seat, free.pawnSeats, free.destTileId); + if (this.gs !== before) { + this.post(role, lineForEvent('heliMove', { role, who, tileName: this.gs.tiles[free.destTileId].name }).text, free.seat); + this.moment('heli', `${this.partnerNames[free.seat]} called a Helicopter Lift to ${this.gs.tiles[free.destTileId].name}.`); + // fly the figurines rather than snapping them + this.clearPlanArrows(); + const after = this.gs; this.gs = before; + let pending = free.pawnSeats.length; + for (const ps of free.pawnSeats) { + this.animatePawnMove(ps, before.players[ps].tileId, free.destTileId, () => { + if (--pending > 0) return; + this.gs = after; this.render(); + this.time.delayedCall(400, step); + }, 'fly'); + } + return; + } } + if (this.gs === before) return this.finishAiTurn(); this.render(); return this.time.delayedCall(560, step); } - const action = chooseAction(this.gs, seat, this.skillBySeat[seat]); + const action = res.action ?? null; if (action) { const isMoveAction = action.type === 'move' || action.type === 'fly' || action.type === 'navMove'; if (isMoveAction) { @@ -1738,7 +1943,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { if (this.gs === before) { this.finishAiTurn(); return; } this.render(); step(); - }); + }, action.type === 'navMove' ? 'nav' : action.type === 'fly' ? 'fly' : null); return; } } @@ -1761,17 +1966,44 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const before = this.gs; this.gs = applyAction(this.gs, seat, action); if (this.gs === before) { this.finishAiTurn(); return; } - if (action.type === 'capture') this.post(this.gs.players[seat].role, lineForEvent('capture', { role: this.gs.players[seat].role, treasure: action.treasure, remaining: 4 - capturedCount(this.gs) }).text, seat); + if (action.type === 'give') { + const role = this.gs.players[seat].role; + Sound.give(this); + this.post(role, lineForEvent('give', { role, card: action.card, to: this.partnerNames[action.targetSeat] }).text, seat); + this.react('thanks', { actorSeat: seat, speakerSeat: action.targetSeat, chance: 0.5 }); + if (this.gs.phase === 'discard') { + const ds = this.gs.pendingDiscard; + this.render(); + if (ds === this.humanSeat) { + this.resumeAiStep = step; + this.busy = false; + this.flashHint('You received a card and are over the hand limit — click a card to discard.'); + this.render(); + return; + } + this.gs = discardCard(this.gs, ds, chooseDiscard(this.gs, ds)); + } + } this.render(); + if (action.type === 'capture') { + this.clearPlanArrows(); + return this.playCapture(seat, action.treasure, () => this.time.delayedCall(300, step)); + } this.time.delayedCall(520, step); } else { this.finishAiTurn(); } }; - this.time.delayedCall(nextThinkDelay(this.skillBySeat[seat]), step); + // Show the planned turn as ghost arrows, give it a moment to read, then play it. + engine.request('plan', { state: this.gs, seat, skill: this.skillBySeat[seat] }).then((plan) => { + if (!alive()) return; + this.drawPlanArrows(seat, plan); + this.time.delayedCall(Math.max(900, nextThinkDelay(this.skillBySeat[seat])), step); + }).catch(() => { if (alive()) this.time.delayedCall(nextThinkDelay(this.skillBySeat[seat]), step); }); } finishAiTurn() { + this.clearPlanArrows(); const seat = this.gs.current; this.animateTreasureDraw(seat, () => { this.gs = endActions(this.gs); @@ -1784,14 +2016,42 @@ export default class ForbiddenIslandGame extends Phaser.Scene { post(role, text, seat = null) { this.messages.push({ role, text, seat }); if (this.messages.length > 40) this.messages.shift(); - if (this.chatText) this.renderChat(); + if (this.chatObjs) this.renderChat(); + // A speech bubble over the speaker's figurine (partners only). + const f = seat != null && seat !== this.humanSeat ? this.figures?.[seat] : null; + if (f && this.introComplete && f.container.visible) this.bubbles.show(seat, f.container.x, f.container.y - 40, text); + } + + // Another crew member's reaction, in their own voice. + react(kind, ctx) { + if (!this.introComplete) return; + const crew = this.gs.players.map((p) => ({ seat: p.seat, role: p.role, isHuman: p.isHuman })); + const who = ctx.actorSeat != null ? this.partnerNames[ctx.actorSeat] : null; + const r = reaction(kind, { ...ctx, who: who === 'You' ? 'partner' : who }, crew, ctx.chance ?? 0.55); + if (r) this.time.delayedCall(700, () => { if (!isGameOver(this.gs) || kind === 'capture') this.post(r.role, r.text, r.seat); }); + } + + // Relic recovered: the cinematic, then the journal line and a cheer. + playCapture(seat, treasure, onDone) { + this.busy = true; + const tracker = this.treasureChips[treasure]; + const from = this.tileWorld(this.gs.tiles[this.gs.players[seat].tileId]); + this.moment('capture', `${seat === this.humanSeat ? 'You' : this.partnerNames[seat]} recovered ${TREASURES[treasure].name}.`); + Cine.capture(this, treasure, from, seat === this.humanSeat ? 'you' : this.partnerNames[seat], { x: tracker.cx, y: tracker.cy }, () => { + const role = this.gs.players[seat].role; + this.post(role, lineForEvent('capture', { role, treasure, remaining: 4 - capturedCount(this.gs) }).text, seat); + this.react('capture', { actorSeat: seat, relic: treasure, chance: 0.8 }); + this.render(); + onDone(); + }); } flashHint(text) { if (this.hint) this.hint.destroy(); - this.hint = this.add.text(BX0 + BOARD_W / 2, BY0 + BOARD_W + 16, text, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.goldHex, align: 'center', wordWrap: { width: BOARD_W }, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui); + this.hint = this.add.text(BX0 + BOARD_W / 2, BY0 + BOARD_W + 12, text, { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '18px', color: '#f6e3b0', align: 'center', wordWrap: { width: BOARD_W }, + backgroundColor: 'rgba(30,20,10,0.78)', padding: { x: 12, y: 4 }, + }).setOrigin(0.5, 0).setDepth(DEPTH.ui + 1); this.time.delayedCall(4000, () => { if (this.hint) { this.hint.destroy(); this.hint = null; } }); } @@ -1832,13 +2092,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { overlay.fillStyle(0x000000, 0.82); overlay.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - const panel = reg(this.add.graphics().setDepth(D + 1)); - panel.fillStyle(0x061a2a, 1); - panel.fillRoundedRect(px, py, pw, ph, 20); - panel.lineStyle(3, COLORS.accent, 0.8); - panel.strokeRoundedRect(px, py, pw, ph, 20); - panel.lineStyle(2, role.color, 0.55); - panel.strokeRoundedRect(px + 4, py + 4, pw - 8, ph - 8, 17); + reg(this.add.image(cx, cy, bakeLeather(this, pw, ph)).setDepth(D + 1)); // ── Left column: portrait ─────────────────────────────────────────────── const portraitW = 300, portraitH = ph - 40; @@ -1848,7 +2102,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { const portraitR = Math.min(portraitW, portraitH) / 2 - 10; const pbg = reg(this.add.graphics().setDepth(D + 1)); - pbg.fillStyle(0x030f18, 1); + pbg.fillStyle(0x1a110a, 1); pbg.fillRoundedRect(portraitX, portraitY, portraitW, portraitH, 12); pbg.lineStyle(2, role.color, 0.45); pbg.strokeRoundedRect(portraitX, portraitY, portraitW, portraitH, 12); @@ -1942,13 +2196,13 @@ export default class ForbiddenIslandGame extends Phaser.Scene { } else { // Human player — role-colored avatar circle const avG = reg(this.add.graphics().setDepth(D + 2)); - avG.fillStyle(role.color, 0.85); + avG.fillStyle(0x0d3a46, 1); avG.fillCircle(portraitCX, portraitCY - 20, portraitR); - avG.lineStyle(3, 0xffffff, 0.35); + avG.lineStyle(4, 0xc9a14a, 1); avG.strokeCircle(portraitCX, portraitCY - 20, portraitR); - reg(this.add.text(portraitCX, portraitCY - 20, role.name[0], { - fontFamily: 'Righteous', fontSize: '72px', color: '#ffffff', - }).setOrigin(0.5).setDepth(D + 3)); + reg(this.add.image(portraitCX, portraitCY - 20, 'di-glow').setDisplaySize(portraitR * 2, portraitR * 2).setAlpha(0.35).setDepth(D + 2)); + reg(this.add.image(portraitCX, portraitCY - 20 + portraitR * 0.72, `di-pawn-${player.role}`).setOrigin(0.5, 1) + .setDisplaySize(portraitR * 1.0, portraitR * 1.45).setDepth(D + 3)); } // Intro speech for AI opponents (with visual overlay) @@ -1959,7 +2213,7 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Player name below portrait reg(this.add.text(portraitCX, portraitY + portraitH - 44, playerName, { - fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex, align: 'center', + fontFamily: DISPLAY_FONT, fontSize: '22px', color: COLORS.textHex, align: 'center', }).setOrigin(0.5).setDepth(D + 2)); // ── Right column: info ────────────────────────────────────────────────── @@ -1971,10 +2225,10 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // "PlayerName as The RoleName" const titleBase = reg(this.add.text(rightX, ry, `${playerName} as The `, { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, + fontFamily: DISPLAY_FONT, fontSize: '26px', color: COLORS.textHex, }).setDepth(textD)); reg(this.add.text(rightX + titleBase.width, ry, role.name, { - fontFamily: 'Righteous', fontSize: '26px', color: role.colorHex, + fontFamily: DISPLAY_FONT, fontSize: '26px', color: role.colorHex, }).setDepth(textD)); ry += 44; @@ -1986,20 +2240,26 @@ export default class ForbiddenIslandGame extends Phaser.Scene { // Description reg(this.add.text(rightX, ry, role.description, { - fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex, + fontFamily: BODY_FONT, fontSize: '17px', color: COLORS.textHex, wordWrap: { width: descW - 8 }, lineSpacing: 4, }).setDepth(textD)); ry += 148; // Ability reg(this.add.text(rightX, ry, 'SPECIAL ABILITY', { - fontFamily: 'Righteous', fontSize: '13px', color: COLORS.accentHex, + fontFamily: DISPLAY_FONT, fontSize: '13px', color: INK.brassHex, }).setDepth(textD)); ry += 22; reg(this.add.text(rightX, ry, role.power, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.goldHex, + fontFamily: BODY_FONT, fontSize: '18px', color: COLORS.goldHex, wordWrap: { width: descW - 8 }, }).setDepth(textD)); + if (role.motto) { + reg(this.add.text(rightX, ry + 70, `“${role.motto}”`, { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '18px', color: '#cdb994', + wordWrap: { width: descW - 8 }, + }).setDepth(textD)); + } // ── Adventurer card placeholder (270×390, scaled to fit) ──────────────── const cardW = 220, cardH = 316, cardR = 14; @@ -2029,18 +2289,17 @@ export default class ForbiddenIslandGame extends Phaser.Scene { cardG.lineStyle(2, COLORS.gold, 0.5); cardG.strokeCircle(iconCX, iconCY, iconR); - reg(this.add.text(iconCX, iconCY, role.name[0], { - fontFamily: 'Righteous', fontSize: '56px', color: '#ffffff', - }).setOrigin(0.5).setDepth(D + 3)); + reg(this.add.image(iconCX, iconCY + iconR * 0.8, `di-pawn-${player.role}`).setOrigin(0.5, 1) + .setDisplaySize(iconR * 1.05, iconR * 1.53).setDepth(D + 3)); reg(this.add.text(cardX + cardW / 2, cardY + 24, role.name.toUpperCase(), { - fontFamily: 'Righteous', fontSize: '15px', color: COLORS.goldHex, + fontFamily: DISPLAY_FONT, fontSize: '15px', color: COLORS.goldHex, }).setOrigin(0.5).setDepth(D + 3)); reg(this.add.text(cardX + cardW / 2, cardY + cardH * 0.68, role.power, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.textHex, + fontFamily: BODY_FONT, fontSize: '13px', color: COLORS.textHex, align: 'center', wordWrap: { width: cardW - 20 }, lineSpacing: 3, }).setOrigin(0.5).setDepth(D + 3)); - reg(this.add.text(cardX + cardW / 2, cardY + cardH - 18, 'FORBIDDEN ISLAND', { - fontFamily: 'Righteous', fontSize: '10px', color: COLORS.mutedHex, + reg(this.add.text(cardX + cardW / 2, cardY + cardH - 18, GAME_TITLE.toUpperCase(), { + fontFamily: DISPLAY_FONT, fontSize: '10px', color: COLORS.mutedHex, }).setOrigin(0.5, 1).setDepth(D + 3)); // ── Next / Let's Play button ───────────────────────────────────────────── @@ -2061,36 +2320,66 @@ export default class ForbiddenIslandGame extends Phaser.Scene { this.introComplete = true; this.buildPartnerHUD(); this.render(); - this.post(null, `Welcome to Forbidden Island — ${DIFFICULTY[this.difficulty].name} difficulty. Capture all four treasures, then fly out from Fools' Landing together.`); + const lay = LAYOUTS[this.gs.layout]?.name ?? 'the island'; + this.post(null, `Day 1. The crew is ashore at the Expedition Dock on ${lay}${this.daily ? ` (daily expedition ${this.daily.key})` : ''}, ${DIFFICULTY[this.difficulty].name}. Recover the four relics, then everyone back to the dock for a Helicopter Lift.`); this.advance(); } // ── End ───────────────────────────────────────────────────────────────────── endGame() { + if (this._ended) return; + this._ended = true; this.busy = true; + this.closeTradeModal?.(); + this.clearPlanArrows(); const won = this.gs.phase === 'won'; const ev = lineForEvent(won ? 'won' : 'lost', { reason: this.gs.lossReason }); this.post(null, ev.text); + this.noteDay(true); + this.moment(won ? 'escape' : 'loss', won ? 'Lift-off from the Expedition Dock.' : (this.gs.lossReason ?? 'The island was lost.')); + Store.clearSave(); + const result = Store.recordResult({ + won, days: this.gs.round ?? 1, relics: capturedCount(this.gs), layout: this.gs.layout, + difficulty: this.difficulty, daily: this.daily?.key ?? null, + }); + result.daily = this.daily?.key ?? null; this.render(); - const overlay = this.add.container(GAME_WIDTH / 2, GAME_HEIGHT / 2).setDepth(DEPTH.banner); - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.8); g.fillRoundedRect(-460, -200, 920, 400, 24); - g.lineStyle(4, won ? COLORS.gold : COLORS.danger, 1); g.strokeRoundedRect(-460, -200, 920, 400, 24); - overlay.add(g); - overlay.add(this.add.text(0, -120, won ? 'You Escaped!' : 'The Island Is Lost', { - fontFamily: 'Righteous', fontSize: '54px', color: won ? COLORS.goldHex : COLORS.dangerHex, - }).setOrigin(0.5)); - overlay.add(this.add.text(0, -30, won ? `All four treasures recovered — the adventurers fly to safety.` : (this.gs.lossReason ?? ''), { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, align: 'center', wordWrap: { width: 840 }, - }).setOrigin(0.5)); - overlay.add(this.add.text(0, 50, `Treasures recovered: ${capturedCount(this.gs)} / 4`, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5)); - const again = new Button(this, -150, 130, 'Play Again', () => this.scene.restart(this._restartData()), { width: 260, height: 56 }); - const leave = new Button(this, 150, 130, 'Leave Table', () => this.scene.start('GameMenu'), { width: 260, height: 56 }); - overlay.add([again, leave]); + for (const f of Object.values(this.figures ?? {})) f.setActive(false); + const report = () => { + Sound.sting(this, won ? 'win' : 'lose'); + showEndScreen(this, { + gs: this.gs, names: this.partnerNames, history: this.history, moments: this.moments, result, + onAgain: () => this.scene.restart(this._restartData()), + onLeave: () => this.scene.start('GameMenu'), + }); + }; + if (won) Cine.escape(this, this.tileWorld(this.gs.tiles['fools-landing']), report); + else Cine.loss(this, this.gs, report); } + // ── Persistence, history and key moments ───────────────────────────────────── + saveGame() { + if (!this.introComplete || isGameOver(this.gs)) return; + Store.save({ + gs: this.gs, opponents: this.opponents, difficulty: this.difficulty, + partnerNames: this.partnerNames, skillBySeat: this.skillBySeat, seatDirections: this.seatDirections, + messages: this.messages.slice(-14), history: this.history, moments: this.moments.slice(-30), daily: this.daily, + }); + } + + // One tide-chart point per day (and a final one at the end). + noteDay(final = false) { + if (!this.gs) return; + const day = this.gs.round ?? 1; + const last = this.history[this.history.length - 1]; + const tiles = Object.values(this.gs.tiles); + const pt = { day, level: this.gs.waterLevel, flooded: tiles.filter((t) => t.state === 'flooded').length, sunk: tiles.filter((t) => t.state === 'sunk').length }; + if (last && last.day === day) { if (final) this.history[this.history.length - 1] = pt; return; } + this.history.push(pt); + } + + moment(kind, text) { this.moments.push({ day: this.gs.round ?? 1, kind, text }); } + _restartData() { return { game: this.gameDef, opponents: this.opponents, difficulty: this.difficulty }; } diff --git a/src/games/forbiddenisland/IslandAI.js b/src/games/forbiddenisland/IslandAI.js index 92acd77..9213002 100644 --- a/src/games/forbiddenisland/IslandAI.js +++ b/src/games/forbiddenisland/IslandAI.js @@ -1,22 +1,49 @@ -// Forbidden Island — heuristic co-op planner. No Phaser, no network. +// The Drowning Isle — co-op planner. No Phaser, no network. // -// This is the "AI partner". Because the game is cooperative there is no -// opponent to model: the planner just evaluates the whole-team situation and -// greedily picks the action that most improves it, one action at a time. It -// also exposes describeIntent() so the partner can announce what it's doing in -// the team-chat panel — the same decision data, rendered as speech. +// The island is the only opponent, so the AI is a planner, not a minimax: +// +// • evalState() scores a position for the whole team. Its core is an +// expected-loss model of the NEXT flood built from public knowledge only: +// the flood deck's composition, the sets known to sit on top of it after a +// Waters Rise (state.floodKnown), and the chance the current player's own +// treasure draw turns up a Waters Rise (which piles the flooded discard on +// top — the classic way temples drown). Tiles are priced by what losing +// them costs: the landing or a treasure's last temple is the game. +// Treasure progress is valued by SPECIALISATION: with hands capped at +// five, each treasure has a collector whose count rises on a convex curve +// while scattered copies are worth less (they are what discards eat); a +// complete set is then worth more the fewer actions it is from a temple. +// • planTurn() beam-searches whole 3-action turns (move, fly, shore up, +// give, capture, navigate), so "walk, walk, capture" and "meet, hand over +// a card" are found as one plan instead of one greedy step at a time. +// • chooseFreeCard() lets any computer teammate play Sandbags / Helicopter +// Lift whenever the model says the card is worth more spent than held. +// • Skill scales beam width/depth and decision noise. (A round-ahead Monte +// Carlo layer was tried and measured: no gain over this evaluation at +// ~15× the cost, so it was left out.) +// +// The weights in TUNE came from random search over self-play; see +// tools/verifyForbiddenIsland.js for the strength ladder it checks. +// +// The planner only ever sees publicView(state): both draw piles' order is +// hidden from it. import { - legalActions, applyAction, adjacentTiles, capturedCount, handTreasureCounts, + legalActions, applyAction, discardCard, adjacentTiles, capturedCount, handTreasureCounts, + playSandbags, playHelicopter, canEscape, floodDrawOdds, publicView, neighbourTable, } from './IslandLogic.js'; -import { TREASURES, TREASURE_KEYS, ROLES, SPECIAL, CARDS_TO_CAPTURE, HAND_LIMIT } from './IslandData.js'; +import { + TREASURES, TREASURE_KEYS, SPECIAL, CARDS_TO_CAPTURE, HAND_LIMIT, floodDrawCount, MAX_WATER, +} from './IslandData.js'; +// width/depth: the turn beam. noise: per-evaluation jitter. blunder: chance +// of settling for a merely-okay first step. const SKILL_PROFILES = { - 1: { topN: 5, blunder: 0.40, noise: 220, delay: [700, 1200] }, - 2: { topN: 4, blunder: 0.24, noise: 140, delay: [650, 1100] }, - 3: { topN: 3, blunder: 0.12, noise: 80, delay: [600, 1000] }, - 4: { topN: 2, blunder: 0.04, noise: 35, delay: [520, 900] }, - 5: { topN: 1, blunder: 0.00, noise: 0, delay: [440, 820] }, + 1: { width: 1, depth: 1, noise: 450, blunder: 0.25, delay: [700, 1200] }, + 2: { width: 2, depth: 2, noise: 220, blunder: 0.12, delay: [650, 1100] }, + 3: { width: 4, depth: 3, noise: 90, blunder: 0.05, delay: [600, 1000] }, + 4: { width: 8, depth: 3, noise: 25, blunder: 0, delay: [520, 900] }, + 5: { width: 16, depth: 3, noise: 0, blunder: 0, delay: [440, 820] }, }; function profileFor(skill) { return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; } @@ -25,319 +52,440 @@ export function nextThinkDelay(skill) { return lo + Math.random() * (hi - lo); } -// ---- distance over the (non-sunk) island ---------------------------------- -function bfsDist(state, fromId, targetSet) { - if (targetSet.has(fromId)) return 0; - const seen = new Set([fromId]); - let frontier = [fromId], d = 0; +// ── value constants ───────────────────────────────────────────────────────── +const WIN = 1e8; +const LOSS = 40000; // price of a tile whose sinking ends the game +const CAPTURED = 9000; // per treasure in hand +// Tunables (exported so tools can sweep them; the defaults are the tuned set). +const CONC = [0, 1, 2.6, 4.6, 7]; +// Tuned by random search over self-play (2 and 4 players, Novice), then checked +// on held-out seeds. +export const TUNE = { + UNIT: 263, OTHER: 0.79, PREPOS: 8.56, HORIZON: 5.72, TEMPO: 413, WAIT: 4.43, EARLY_GIVE: 0.48, + T1: 732, T2: 1598, JOINT: 0.19, LINGER: 2.32, DRY: 0.5, + HELI1: 290, HELI2: 55, BAGS: 58, NORMAL: 147, +}; +let TEMPO = TUNE.TEMPO, WAIT_PER_CARD = TUNE.WAIT; +export function setTune(t) { Object.assign(TUNE, t); TEMPO = TUNE.TEMPO; WAIT_PER_CARD = TUNE.WAIT; } + +// ── distances ─────────────────────────────────────────────────────────────── + +// Steps from a pawn to every tile, honouring its role: Explorer moves +// diagonally, Diver passes through sunk water, Pilot is at most one hop away +// from anything (one flight per turn). Returns { d: Int8Array, ix } where +// d[ix[tileId]] is the distance (99 = unreachable / sunk). +function distMap(tab, sunk, player) { + const role = player.role; + const nbrs = role === 'explorer' ? tab.allI : tab.orthI; + const n = tab.ids.length; + const d = new Int8Array(n).fill(99); + const start = tab.index[player.tileId]; + d[start] = 0; + const crossed = role === 'diver' ? new Uint8Array(n) : null; + let frontier = [start], step = 0; while (frontier.length) { - d++; + step++; const next = []; - for (const id of frontier) { - for (const nb of adjacentTiles(state, id)) { - if (seen.has(nb) || state.tiles[nb].state === 'sunk') continue; - if (targetSet.has(nb)) return d; - seen.add(nb); next.push(nb); + for (const i of frontier) { + for (const j of nbrs[i]) { + if (d[j] !== 99 || (crossed && crossed[j])) continue; + if (sunk[j]) { + if (crossed) { crossed[j] = 1; next.push(j); } // the Diver may cross, never stop + continue; + } + d[j] = step; + next.push(j); } } frontier = next; } - return 99; // unreachable + if (role === 'pilot') for (let i = 0; i < n; i++) if (i !== start && !sunk[i] && d[i] > 1) d[i] = 1; + return { d, ix: tab.index }; } +const D = (m, id) => m.d[m.ix[id]] ?? 99; -function liveTreasureTiles(state, key) { - return TREASURES[key].tiles.filter((id) => state.tiles[id].state !== 'sunk'); -} +// ── tile pricing ──────────────────────────────────────────────────────────── +function treasureCaptured(state, key) { return state.players.some((p) => p.captured[key]); } -function isCaptured(state, key) { return state.players.some((p) => p.captured[key]); } - -// How costly it would be to let a given flooded tile sink. Shared by the state -// evaluation and the special-card chooser so they agree on what's "critical". -function floodWeight(state, t) { - if (t.state !== 'flooded') return 0; - if (t.landing) return 130; - if (t.treasure && !isCaptured(state, t.treasure)) { +// What it costs the team if this tile sinks now. +function sinkCost(state, t, saveSet) { + if (t.state === 'sunk') return 0; + let c = TUNE.NORMAL; + if (t.landing) c = LOSS; + else if (t.treasure && !treasureCaptured(state, t.treasure)) { const pair = TREASURES[t.treasure].tiles.find((id) => id !== t.id); - if (state.tiles[pair].state === 'sunk') return 320; // last tile of the treasure - if (state.tiles[pair].state === 'flooded') return 120; // both temples flooded - return 55; + const ps = state.tiles[pair].state; + c = ps === 'sunk' ? LOSS : (ps === 'flooded' ? TUNE.T2 : TUNE.T1); } - return 6; + if (saveSet?.has(t.id)) c += 600; + // Pawns standing here must swim; with nowhere to go they drown. + for (const p of state.players) { + if (p.tileId !== t.id) continue; + if (p.role === 'pilot') { c += 20; continue; } + const dirs = p.role === 'explorer' ? 8 : 4; + const exits = adjacentTiles(state, t.id, { diagonal: dirs === 8 }).filter((id) => state.tiles[id].state !== 'sunk').length; + c += exits === 0 && p.role !== 'diver' ? LOSS : 35; + } + return c; } -// Which seat is the lead carrier for each uncaptured treasure (holds the most -// matching cards). Returns { key -> { seat, cards } }. -// The lead carrier for each uncaptured treasure: the player holding the most of -// its cards (ties broken by seat order). -function carriers(state) { - const out = {}; - for (const key of TREASURE_KEYS) { - if (isCaptured(state, key)) continue; - let best = -1, bestSeat = -1; - for (const p of state.players) { - const c = handTreasureCounts(p)[key]; - if (c > best) { best = c; bestSeat = p.seat; } +// Chance the acting player's 2-card treasure draw contains a Waters Rise. +function watersRiseChance(state) { + if (state.phase !== 'actions') return 0; + const deck = state.treasureDeck; + const n = deck.length; + const w = deck.filter((c) => c === SPECIAL.WATERS_RISE).length; + if (n === 0) return 0; + if (n === 1) return w; + return 1 - ((n - w) * (n - w - 1)) / (n * (n - 1)); +} + +// Expected cost of the coming flood + lingering cost of tiles left flooded. +function floodRisk(state, saveSet, dists) { + const draws = floodDrawCount(state.waterLevel); + const base = floodDrawOdds(state, draws); + const pWR = watersRiseChance(state); + let wrOdds = null; + if (pWR > 0) { + const lvl = Math.min(MAX_WATER, state.waterLevel + 1); + const hyp = { + ...state, + floodKnown: state.floodDiscard.length ? [state.floodDiscard.slice(), ...(state.floodKnown ?? [])] : state.floodKnown, + floodDeck: [...state.floodDiscard, ...state.floodDeck], + floodDiscard: [], + }; + wrOdds = floodDrawOdds(hyp, floodDrawCount(lvl)); + } + let cost = 0; + const pOf = {}; + for (const t of Object.values(state.tiles)) { + if (t.state === 'sunk') continue; + const p = (1 - pWR) * (base[t.id] ?? 0) + pWR * (wrOdds?.[t.id] ?? 0); + const sc = sinkCost(state, t, saveSet); + if (t.state === 'flooded') { + // Not drawn now, it still sits exposed through the teammates' floods; + // less so if someone is close enough to shore it. + let near = 99; + for (const pl of state.players) near = Math.min(near, D(dists[pl.seat], t.id)); + const linger = (near <= 1 ? 0.03 : (near <= 3 ? 0.06 : 0.1)) * TUNE.LINGER; + cost += p * sc + (1 - p) * linger * sc; + } else { + cost += p * TUNE.DRY * sc; } - out[key] = { seat: bestSeat, cards: best }; + pOf[t.id] = p; } - return out; + // Both temples of a live treasure flooded: the one-flood double sink is the + // game, and the two draws are far from independent after a Waters Rise. + if (TUNE.JOINT) { + for (const key of TREASURE_KEYS) { + if (treasureCaptured(state, key)) continue; + const [a, b] = TREASURES[key].tiles.map((id) => state.tiles[id]); + if (a.state === 'flooded' && b.state === 'flooded') cost += TUNE.JOINT * (pOf[a.id] ?? 0) * (pOf[b.id] ?? 0) * LOSS; + } + } + return cost; } -// ---- whole-team state evaluation ------------------------------------------ -// Higher is better. Greedy 1-ply over this drives competent co-op play. +// ── whole-team evaluation ─────────────────────────────────────────────────── export function evalState(state, seat) { - if (state.phase === 'won') return 1e9; - if (state.phase === 'lost') return -1e9; + if (state.phase === 'won') return WIN * 10; + if (state.phase === 'lost') return -WIN; + if (canEscape(state)) return WIN; const pr = state.priorities ?? {}; - let v = capturedCount(state) * 5000; - const allCaptured = capturedCount(state) === 4; - const lead = carriers(state); - - // Total team cards per uncaptured treasure, and an automatic "team focus": - // rally everyone on the treasure nearest completion (or most threatened) - // rather than splitting effort four ways and finishing none in time. - const teamCards = {}; - for (const key of TREASURE_KEYS) { - if (!lead[key]) continue; - let t = 0; for (const p of state.players) t += handTreasureCounts(p)[key]; - teamCards[key] = t; - } - let autoFocus = null, bestFocus = -1; - for (const key of Object.keys(teamCards)) { - const live = liveTreasureTiles(state, key); - if (!live.length) continue; - const score = teamCards[key] * 2 + (live.length === 1 ? 4 : 0); - if (score > bestFocus) { bestFocus = score; autoFocus = key; } - } - - // Treasure progress + pulling carriers toward their tiles. - for (const key of TREASURE_KEYS) { - if (!lead[key]) continue; // already captured - const { seat: cs, cards } = lead[key]; - const focus = pr.focusTreasure === key ? 2.2 : (autoFocus === key ? 1.8 : 1); - v += Math.min(cards, CARDS_TO_CAPTURE) * 40 * focus; - const live = liveTreasureTiles(state, key); - if (!live.length || cs < 0) continue; - const liveSet = new Set(live); - const carrierTile = state.players[cs].tileId; - const d = bfsDist(state, carrierTile, liveSet); - if (cards >= CARDS_TO_CAPTURE) { - // Ready to capture — marching the carrier to the temple must out-weigh - // routine shoring, so this dominates everything short of a true emergency. - v += (1600 - d * 180) * focus; - } else if (cards > 0) { - // Pre-position the lead carrier near its temple while it gathers cards. - v -= d * 8 * focus; - // Card logistics: other holders should converge on the carrier to hand - // their matching cards over (the Messenger can do it from anywhere). - for (const o of state.players) { - if (o.seat === cs) continue; - const oc = handTreasureCounts(o)[key]; - if (oc > 0) v -= bfsDist(state, o.tileId, new Set([carrierTile])) * 5 * oc * focus; - } - } - // Defense: keep at least one adventurer near the live temple tiles so they - // can be shored before they sink (most losses are treasures drowning). - let nearest = 99; - for (const p of state.players) nearest = Math.min(nearest, bfsDist(state, p.tileId, liveSet)); - v -= nearest * 2 * focus; - } - - // Guard Fools' Landing — losing the helipad is an instant, common death. Keep - // someone within reach of it, and never leave it flooded if avoidable. - if (state.tiles['fools-landing'].state !== 'sunk') { - let nearLanding = 99; - for (const p of state.players) nearLanding = Math.min(nearLanding, bfsDist(state, p.tileId, new Set(['fools-landing']))); - v -= nearLanding * 6; - } - - // Threat: flooded tiles weighted by what their loss would cost. const saveSet = new Set(pr.saveTiles ?? []); - for (const t of Object.values(state.tiles)) { - if (t.state !== 'flooded') continue; - let w = floodWeight(state, t); - if (saveSet.has(t.id)) w += 50; - // A flooded tile a pawn stands on is more urgent (sinking forces a swim). - if (state.players.some((p) => p.tileId === t.id)) w += 10; - v -= w; + const tab = neighbourTable(state); + const sunk = tab.ids.map((id) => state.tiles[id].state === 'sunk'); + const dists = {}; + for (const p of state.players) dists[p.seat] = distMap(tab, sunk, p); + + const nCaptured = capturedCount(state); + let v = nCaptured * CAPTURED; + v -= floodRisk(state, saveSet, dists); + + const counts = state.players.map((p) => handTreasureCounts(p)); + + // Treasure progress. Hands are capped at five, so the team must SPECIALISE: + // each treasure has a collector (most cards), whose count is valued on a + // convex curve; the same cards scattered elsewhere are worth less (they are + // what the hand limit should eat). Once the team holds a complete set, the + // logistics take over: the estimated actions to bring the set to a temple + // and claim it, each action worth TEMPO. + for (const key of TREASURE_KEYS) { + if (treasureCaptured(state, key)) continue; + const live = TREASURES[key].tiles.filter((id) => state.tiles[id].state !== 'sunk'); + if (!live.length) continue; + const focus = pr.focusTreasure === key ? 1.5 : 1; + let total = 0, top = 0, collector = null; + for (const p of state.players) { + const c = counts[p.seat][key]; + total += c; + if (c > top) { top = c; collector = p; } + } + if (!collector) continue; + const others = Math.min(total - top, CARDS_TO_CAPTURE - Math.min(top, CARDS_TO_CAPTURE)); + v += focus * TUNE.UNIT * (CONC[Math.min(top, CARDS_TO_CAPTURE)] + TUNE.OTHER * others); + // A complete set is always worth more than an incomplete one, and more + // still the fewer actions it is from being claimed. + // (Capped by a short horizon so claiming the treasure stays far better.) + if (total >= CARDS_TO_CAPTURE) v += focus * TEMPO * Math.max(0, TUNE.HORIZON - actionsToCapture(state, key, live, counts, dists)); + else v -= focus * TUNE.PREPOS * Math.min(...live.map((id) => D(dists[collector.seat], id))); } - // Endgame: once everything's captured (or the human asked to regroup), pull - // everyone to Fools' Landing and reward holding a Helicopter Lift. - if (allCaptured || pr.regroup) { - const landing = new Set(['fools-landing']); - for (const p of state.players) v -= bfsDist(state, p.tileId, landing) * (allCaptured ? 10 : 3); - if (allCaptured && state.players.some((p) => p.hand.includes(SPECIAL.HELICOPTER))) v += 80; + // Special cards held by the team. + let helis = 0, bags = 0; + for (const p of state.players) for (const c of p.hand) { + if (c === SPECIAL.HELICOPTER) helis++; + else if (c === SPECIAL.SANDBAGS) bags++; + } + v += (helis ? TUNE.HELI1 + (helis - 1) * TUNE.HELI2 : 0) + bags * TUNE.BAGS; + + // Endgame: everyone to the landing, and a lift to leave on. + if (nCaptured === 4 || pr.regroup) { + const w = nCaptured === 4 ? 320 : 60; + for (const p of state.players) v -= w * Math.min(D(dists[p.seat], 'fools-landing'), 8); + if (nCaptured === 4 && !helis) v -= 2500; } - // Hand-limit risk. - for (const p of state.players) if (p.hand.length > HAND_LIMIT) v -= 25 * (p.hand.length - HAND_LIMIT); + // Over the hand limit (only mid-discard). + for (const p of state.players) if (p.hand.length > HAND_LIMIT) v -= 220 * (p.hand.length - HAND_LIMIT); - // "Hold position" damps wandering (handled by caller comparing to base). return v; } -// ---- pick one action (or null to end the turn) ---------------------------- -export function chooseAction(state, seat, skill = 3) { - const acts = legalActions(state, seat); - if (acts.length === 0) return null; - const prof = profileFor(skill); - const base = evalState(state, seat); - - let scored = acts.map((a) => ({ a, v: evalState(applyAction(state, seat, a), seat) })); - scored.sort((x, y) => y.v - x.v); - - // Nothing improves the team's position — bank the remaining actions. - const hold = state.priorities?.hold ? 12 : 1; // require a bigger gain when "hold position" is set - if (scored[0].v <= base + hold) return null; - - if (Math.random() < prof.blunder) { - // Blunder: still pick something that doesn't actively hurt, just not the best. - const ok = scored.filter((s) => s.v >= base); - return (ok[Math.floor(Math.random() * ok.length)] ?? scored[0]).a; +// Cheapest estimate (in actions) for the team to claim treasure `key`: pick a +// carrier, pull the missing cards from the nearest holders (a give is one +// action plus the walk to meet; the Messenger gives from anywhere), walk the +// carrier to a live temple, capture. Missing cards cost an expected wait. +function actionsToCapture(state, key, live, counts, dists) { + let total = 0; + for (const p of state.players) total += counts[p.seat][key]; + const missing = Math.max(0, CARDS_TO_CAPTURE - total); + let best = Infinity; + for (const x of state.players) { + const own = counts[x.seat][key]; + if (!own && total) continue; + const toTemple = Math.min(...live.map((id) => D(dists[x.seat], id))); + let need = Math.max(0, CARDS_TO_CAPTURE - own - missing); + const offers = []; + for (const o of state.players) { + if (o.seat === x.seat || !counts[o.seat][key]) continue; + // Both may walk: meeting takes about half the gap, or a walk to the temple. + const gap = Math.min(D(dists[o.seat], x.tileId), D(dists[x.seat], o.tileId)); + const meet = o.role === 'messenger' ? 0 : Math.min(Math.ceil(gap / 2) + Math.floor(gap / 2) * 0.5, live.reduce((m, id) => Math.min(m, D(dists[o.seat], id)), 99)); + offers.push({ n: counts[o.seat][key], meet }); + } + offers.sort((a, b) => a.meet - b.meet); + let cost = toTemple + 1; + for (const off of offers) { + if (need <= 0) break; + const take = Math.min(need, off.n); + // Until the set is complete the eventual carrier is uncertain, so early + // hand-offs only earn part of their tempo. + cost += (take + off.meet) * (missing ? TUNE.EARLY_GIVE : 1); + need -= take; + } + if (cost < best) best = cost; } - const pool = scored.slice(0, Math.min(prof.topN, scored.length)); - let best = pool[0], bestV = -Infinity; - for (const c of pool) { - const v = c.v + (prof.noise ? (Math.random() * 2 - 1) * prof.noise : 0); - if (v > bestV) { bestV = v; best = c; } - } - return best.a; + if (!isFinite(best)) best = 6; + return Math.min(best, 14) + missing * WAIT_PER_CARD; } -// ---- free special-card plays (Sandbags / Helicopter Lift) ----------------- -// These cost no action and can be played any time, so the planner gets a chance -// to use them before/between its regular actions. Returns a descriptor the -// caller applies via playSandbags / playHelicopter, or null. Only the current -// seat's own specials are considered (a simplification of "any time"). -export function chooseFreeCard(state, seat) { - if (state.phase !== 'actions' || state.current !== seat) return null; - const p = state.players[seat]; +// ── turn planner ──────────────────────────────────────────────────────────── +function signature(s) { + let k = s.players.map((p) => `${p.tileId}:${p.hand.length}:${p.hand.join('')}`).join('|'); + for (const t of Object.values(s.tiles)) if (t.state !== 'dry') k += t.id[0] + t.id.length + t.state[0]; + return k + Object.keys(s.players.reduce((a, p) => Object.assign(a, p.captured), {})).join(''); +} - // Sandbags: free-shore the single most critical flooded tile. Reserve them for - // genuine emergencies (a temple's last/second tile, or Fools' Landing) rather - // than spending them on routine flooding. - if (p.hand.includes(SPECIAL.SANDBAGS)) { - let best = null, bw = 0; - for (const t of Object.values(state.tiles)) { - const w = floodWeight(state, t); - if (w > bw) { bw = w; best = t; } - } - if (best && bw >= 100) return { type: 'sandbags', tileId: best.id }; - } +// A give can push a teammate over the limit; settle that the way the team would. +function settle(s) { + let guard = 0; + while (s.phase === 'discard' && guard++ < 4) s = discardCard(s, s.pendingDiscard, chooseDiscard(s, s.pendingDiscard)); + return s; +} - // Helicopter Lift: deliver a ready (4-card) carrier straight to its temple, - // but only if the team can spare one (the last Helicopter is needed to escape). - if (p.hand.includes(SPECIAL.HELICOPTER)) { - const heli = state.players.reduce((n, pl) => n + pl.hand.filter((c) => c === SPECIAL.HELICOPTER).length, 0); - if (heli >= 2) { - for (const key of TREASURE_KEYS) { - if (isCaptured(state, key)) continue; - let cs = -1, cc = 0; - for (const pl of state.players) { const c = handTreasureCounts(pl)[key]; if (c > cc) { cc = c; cs = pl.seat; } } - if (cc < CARDS_TO_CAPTURE || cs < 0) continue; - const live = liveTreasureTiles(state, key); - const carrierTile = state.players[cs].tileId; - if (!live.length || live.includes(carrierTile)) continue; - const templeFlooded = live.some((id) => state.tiles[id].state === 'flooded'); - const d = bfsDist(state, carrierTile, new Set(live)); - // Lift yourself whenever it saves real travel; lift a teammate only when - // their temple is actively flooding (urgent) — they capture next turn. - if ((cs === seat && d >= 2) || templeFlooded) { - let dest = live[0], dd = 99; - for (const id of live) { const e = bfsDist(state, carrierTile, new Set([id])); if (e < dd) { dd = e; dest = id; } } - return { type: 'helicopter', pawnSeats: [cs], destTileId: dest, carrierSeat: cs }; +// Best sequence of up to `actionsLeft` actions for `seat`. Returns +// { actions: [...], value, base }. +export function planTurn(state, seat, skill = 3, { profile = null, isView = false } = {}) { + const prof = profile ?? profileFor(skill); + const view = isView ? state : publicView(state); + const base = evalState(view, seat); + const jitter = () => (prof.noise ? (Math.random() * 2 - 1) * prof.noise : 0); + let best = { actions: [], value: base }; + let beam = [{ s: view, seq: [] }]; + const depth = Math.min(prof.depth, view.actionsLeft); + for (let d = 0; d < depth && beam.length; d++) { + const kids = []; + const seen = new Set(); + for (const node of beam) { + for (const a of legalActions(node.s, seat)) { + let ns = applyAction(node.s, seat, a); + if (ns === node.s) continue; + ns = settle(ns); + const sig = signature(ns) + ns.actionsLeft; + if (seen.has(sig)) continue; + seen.add(sig); + const v = evalState(ns, seat); + const kid = { s: ns, seq: [...node.seq, a], v, vn: v + jitter() }; + kids.push(kid); + // Shorter plans win ties: spare actions are never worse than wasted ones. + if (kid.vn > best.value + 1) { + best = { actions: kid.seq, value: kid.vn }; } } } + kids.sort((a, b) => b.vn - a.vn); + beam = kids.slice(0, prof.width); } - return null; + // Weak partners sometimes take a merely-okay first step. + if (prof.blunder && Math.random() < prof.blunder) { + const okay = legalActions(view, seat) + .map((a) => ({ a, v: evalState(settle(applyAction(view, seat, a)), seat) })) + .filter((x) => x.v >= base - 50); + if (okay.length) { + const pick = okay[Math.floor(Math.random() * okay.length)]; + return { actions: [pick.a], value: pick.v, base }; + } + } + // "Hold position": only move for a clearly worthwhile plan. + if (view.priorities?.hold && best.value - base < 150) return { actions: [], value: base, base }; + return { ...best, base }; } -// ---- discard choice (when a hand is over the limit) ----------------------- -// Sheds the least useful card without breaking a capture set. Dead cards of an -// already-captured treasure go first; Helicopter Lift is kept to the last. +// A turn's plan is made once and replayed while the board matches what the +// plan expected (so a noisy, weaker partner still plays a coherent turn); +// anything unexpected — a teammate's Sandbags, a forced discard — re-plans. +let planCache = null; +export function chooseAction(state, seat, skill = 3) { + if (!legalActions(state, seat).length) return null; + const view = publicView(state); + const key = signature(view) + view.actionsLeft + ':' + seat + ':' + skill; + let actions; + if (planCache && planCache.key === key) actions = planCache.rest; + else actions = planTurn(view, seat, skill, { isView: true }).actions; + const next = actions[0] ?? null; + planCache = null; + if (next && actions.length > 1) { + const after = settle(applyAction(view, seat, next)); + planCache = { key: signature(after) + after.actionsLeft + ':' + seat + ':' + skill, rest: actions.slice(1) }; + } + return next; +} + +// The whole turn the partner intends, for the ghost-arrow preview. Primes the +// plan cache so the following chooseAction calls play exactly this plan. +export function previewPlan(state, seat, skill = 3) { + if (!legalActions(state, seat).length) return []; + const view = publicView(state); + const actions = planTurn(view, seat, skill, { isView: true }).actions; + planCache = actions.length ? { key: signature(view) + view.actionsLeft + ':' + seat + ':' + skill, rest: actions } : null; + return actions; +} + +// ── free special-card plays ───────────────────────────────────────────────── +// Any computer-controlled teammate may play a Sandbags / Helicopter Lift at any +// time. Returns { type, seat, tileId } | { type, seat, pawnSeats, destTileId } +// or null. `minGain` raises the bar (e.g. outside anyone's action phase). +export function chooseFreeCard(state, seat, { minGain = 120, isView = false } = {}) { + if (state.phase === 'won' || state.phase === 'lost') return null; + const view = isView ? state : publicView(state); + const base = evalState(view, seat); + let best = null, bestGain = minGain; + const holders = view.players.filter((p) => !p.isHuman); + + const bagHolder = holders.find((p) => p.hand.includes(SPECIAL.SANDBAGS)); + if (bagHolder) { + for (const t of Object.values(view.tiles)) { + if (t.state !== 'flooded') continue; + const g = evalState(playSandbags(view, bagHolder.seat, t.id), seat) - base; + if (g > bestGain) { bestGain = g; best = { type: 'sandbags', seat: bagHolder.seat, tileId: t.id }; } + } + } + + const heliHolder = holders.find((p) => p.hand.includes(SPECIAL.HELICOPTER)); + if (heliHolder) { + // Destinations worth a flight: temples of treasures someone can now claim, + // and the landing for the endgame. + const dests = new Set(); + for (const key of TREASURE_KEYS) { + if (treasureCaptured(view, key)) continue; + if (!view.players.some((p) => handTreasureCounts(p)[key] >= CARDS_TO_CAPTURE)) continue; + for (const id of TREASURES[key].tiles) if (view.tiles[id].state !== 'sunk') dests.add(id); + } + if (capturedCount(view) === 4 && view.tiles['fools-landing'].state !== 'sunk') dests.add('fools-landing'); + const groups = {}; + for (const p of view.players) (groups[p.tileId] ??= []).push(p.seat); + for (const [from, seats] of Object.entries(groups)) { + for (const dest of dests) { + if (dest === from) continue; + const ns = playHelicopter(view, heliHolder.seat, seats, dest); + if (ns === view) continue; + const g = evalState(ns, seat) - base; + if (g > bestGain) { bestGain = g; best = { type: 'helicopter', seat: heliHolder.seat, pawnSeats: seats, destTileId: dest, carrierSeat: seats[0] }; } + } + } + } + return best; +} + +// ── discard choice ────────────────────────────────────────────────────────── export function chooseDiscard(state, seat) { const p = state.players[seat]; - const counts = handTreasureCounts(p); - const captured = (k) => state.players.some((pl) => pl.captured[k]); - - // 1. Treasure cards whose treasure is already captured (pure dead weight). - let dead = p.hand.find((c) => c.startsWith('treasure:') && captured(c.slice('treasure:'.length))); - if (dead) return dead; - - // 2. Sandbags before anything still in play. - if (p.hand.includes(SPECIAL.SANDBAGS)) return SPECIAL.SANDBAGS; - - // 3. A treasure card from the smallest (and not yet complete) pile. - const treasureCards = p.hand.filter((c) => c.startsWith('treasure:')); - if (treasureCards.length) { - treasureCards.sort((a, b) => counts[a.slice(9)] - counts[b.slice(9)]); - const safe = treasureCards.find((c) => counts[c.slice('treasure:'.length)] < CARDS_TO_CAPTURE); - if (safe) return safe; - return treasureCards[0]; + let best = p.hand[0], bv = -Infinity; + for (const card of new Set(p.hand)) { + const ns = discardCard(state, seat, card); + if (ns === state) continue; + // Score the hand that remains without recursing into further discards. + const v = evalState({ ...ns, phase: ns.phase === 'discard' ? 'actions' : ns.phase }, seat); + if (v > bv) { bv = v; best = card; } } - - // 4. Last resort: Helicopter Lift. - return p.hand[0]; + return best; } -// ---- describe the partner's plan for the chat panel ------------------------ -// Pure read of the current state — returns a rationale object the chat library -// turns into a spoken line. -export function describeIntent(state, seat) { +// ── describe the partner's plan for the chat panel ────────────────────────── +export function describeIntent(state, seat, skill = 4) { const p = state.players[seat]; const role = p.role; - const lead = carriers(state); - const counts = handTreasureCounts(p); - - // On a treasure tile with enough cards → capture. - const here = state.tiles[p.tileId]; - if (here.treasure && !p.captured[here.treasure] && counts[here.treasure] >= CARDS_TO_CAPTURE) { - return { role, intent: 'CAPTURE', treasure: here.treasure, tile: here.id, threats: topThreats(state) }; - } - - // Am I the lead carrier of an uncaptured treasure with at least one card? - let mine = null; - for (const key of TREASURE_KEYS) { - if (!lead[key] || lead[key].seat !== seat || lead[key].cards < 1) continue; - if (!mine || lead[key].cards > counts[mine]) mine = key; - } - if (mine) { - // Need more cards? Is a teammate holding some? - const need = CARDS_TO_CAPTURE - counts[mine]; - let request = null; - if (need > 0) { - const helper = state.players.find((o) => o.seat !== seat && handTreasureCounts(o)[mine] > 0); - if (helper) request = { treasure: mine, fromRole: helper.role }; - } - return { role, intent: 'SEEK', treasure: mine, cards: counts[mine], request, threats: topThreats(state) }; - } - - // Endgame. - if (capturedCount(state) === 4) { - return { role, intent: 'ESCAPE', threats: topThreats(state) }; - } - - // Otherwise: shore something critical / support. const threats = topThreats(state); - if (threats.length) return { role, intent: 'SHORE', tile: threats[0].id, threats }; - return { role, intent: 'SUPPORT', threats }; + const plan = planTurn(state, seat, Math.max(3, skill)); + const acts = plan.actions; + const cap = acts.find((a) => a.type === 'capture'); + if (cap) return { role, intent: 'CAPTURE', treasure: cap.treasure, threats, plan: acts }; + const give = acts.find((a) => a.type === 'give'); + if (give) return { role, intent: 'GIVE', treasure: give.card.slice(9), toSeat: give.targetSeat, threats, plan: acts }; + if (capturedCount(state) === 4) return { role, intent: 'ESCAPE', threats, plan: acts }; + const counts = handTreasureCounts(p); + const mine = TREASURE_KEYS.filter((k) => !treasureCaptured(state, k) && counts[k] >= 2) + .sort((a, b) => counts[b] - counts[a])[0]; + const shores = acts.filter((a) => a.type === 'shoreUp'); + if (shores.length && threats.length) return { role, intent: 'SHORE', tile: shores[0].tiles[0], threats, plan: acts }; + if (mine) { + const need = CARDS_TO_CAPTURE - counts[mine]; + const helper = need > 0 ? state.players.find((o) => o.seat !== seat && handTreasureCounts(o)[mine] > 0) : null; + return { role, intent: 'SEEK', treasure: mine, cards: counts[mine], request: helper ? { treasure: mine, fromRole: helper.role } : null, threats, plan: acts }; + } + if (shores.length) return { role, intent: 'SHORE', tile: shores[0].tiles[0], threats, plan: acts }; + return { role, intent: 'SUPPORT', threats, plan: acts }; } -// The flooded tiles whose loss would hurt most, worst first. +// The flooded tiles most likely to cost us, worst first (by expected loss). export function topThreats(state) { + const view = publicView(state); + const odds = floodDrawOdds(view, floodDrawCount(view.waterLevel)); const out = []; - for (const t of Object.values(state.tiles)) { + for (const t of Object.values(view.tiles)) { if (t.state !== 'flooded') continue; - let w = 1; - if (t.landing) w = 5; - else if (t.treasure && !state.players.some((p) => p.captured[t.treasure])) { - const pair = TREASURES[t.treasure].tiles.find((id) => id !== t.id); - w = state.tiles[pair].state === 'dry' ? 3 : 4; - } - if (w >= 3) out.push({ id: t.id, name: t.name, weight: w, treasure: t.treasure ?? null, landing: !!t.landing }); + const sc = sinkCost(view, t, null); + if (sc < 1000) continue; + const risk = Math.max(odds[t.id] ?? 0, 0.05) * sc; + out.push({ id: t.id, name: t.name, weight: risk, odds: odds[t.id] ?? 0, treasure: t.treasure ?? null, landing: !!t.landing }); } return out.sort((a, b) => b.weight - a.weight).slice(0, 3); } + +// Per-tile flood odds for the coming flood (for a "danger forecast" overlay). +export function floodForecast(state) { + const view = publicView(state); + return floodDrawOdds(view, floodDrawCount(view.waterLevel)); +} diff --git a/src/games/forbiddenisland/IslandArt.js b/src/games/forbiddenisland/IslandArt.js new file mode 100644 index 0000000..1373215 --- /dev/null +++ b/src/games/forbiddenisland/IslandArt.js @@ -0,0 +1,669 @@ +// The Drowning Isle: baked canvas textures. Everything here is procedural; the +// only image files are the user's own paintings (forbiddenisland-tiles.png and +// forbiddenisland-cards.png), which this module frames and never alters. +// +// di-water, di-caustic seamless sea surface + bright caustic lines (tiled) +// di-cloud seamless storm-cloud layer for the sky +// di-slab carved stone slab each tile painting sits in +// di-foam soft surf ring that laps around a tile +// di-plaque brass name plate under each tile painting +// di-seal- wax seal marking a relic's shrines +// di-pawn- painted wooden figurines, one per crew role +// di-shadow soft contact shadow for figurines and cards +// di-back-treasure supply-crate card back (treasure deck) +// di-back-flood tide-chart card back (flood deck) +// di-journal the field-journal page behind the right rail +// di-strip paper crew strip above the board +// di-shelf driftwood shelf the decks sit on +// di-gauge brass tide gauge body (liquid drawn live) +// di-leather-x leather panels for dialogs (bakeLeather) +// di-rain, di-drop, di-bubble, di-glow, di-ring, di-spark particles + +import { canvas, rr } from '../../ui/casino/CasinoArt.js'; +import { ROLE_KEYS, TREASURE_KEYS, TREASURES, ROLES, MAX_WATER } from './IslandData.js'; +import { TILE, BOARD_W, JOURNAL, GAUGE, TYPE_FONT, DISPLAY_FONT } from './IslandLayout.js'; + +export const RES = 2; +export const PAWN = { w: 44, h: 64 }; // figurine display size +export const BACK = { w: 80, h: 108 }; // deck card display size + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); +} + +function seeded(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const hex = (n) => `#${n.toString(16).padStart(6, '0')}`; +function shade(n, f) { + const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255; + const m = (v) => Math.max(0, Math.min(255, Math.round(f >= 0 ? v + (255 - v) * f : v * (1 + f)))); + return `rgb(${m(r)},${m(g)},${m(b)})`; +} + +// Tileable value noise: each octave is a wrapped lattice, so the result repeats +// exactly every w×h pixels and can scroll forever in a TileSprite. +function periodicNoise(w, h, rand, cells = [4, 8, 16, 32], weights = [0.5, 0.25, 0.15, 0.1]) { + const out = new Float32Array(w * h); + cells.forEach((n, o) => { + const lat = new Float32Array(n * n).map(() => rand()); + const sm = (t) => t * t * (3 - 2 * t); + for (let y = 0; y < h; y++) { + const fy = (y / h) * n, y0 = Math.floor(fy), ty = sm(fy - y0); + const r0 = (y0 % n) * n, r1 = ((y0 + 1) % n) * n; + for (let x = 0; x < w; x++) { + const fx = (x / w) * n, x0 = Math.floor(fx), tx = sm(fx - x0); + const c0 = x0 % n, c1 = (x0 + 1) % n; + const a = lat[r0 + c0] + (lat[r0 + c1] - lat[r0 + c0]) * tx; + const b = lat[r1 + c0] + (lat[r1 + c1] - lat[r1 + c0]) * tx; + out[y * w + x] += (a + (b - a) * ty) * weights[o]; + } + } + }); + return out; +} + +function speckle(ctx, w, h, rand, n, color, rMax = 1.2) { + ctx.fillStyle = color; + for (let i = 0; i < n; i++) { + ctx.globalAlpha = 0.05 + rand() * 0.12; + ctx.beginPath(); ctx.arc(rand() * w, rand() * h, 0.3 + rand() * rMax, 0, Math.PI * 2); ctx.fill(); + } + ctx.globalAlpha = 1; +} + +// ── sea and sky ────────────────────────────────────────────────────────────── +function bakeWater(scene) { + const S = 256, c = canvas(S, S), ctx = c.getContext('2d'); + const rand = seeded(1934); + const n = periodicNoise(S, S, rand); + const img = ctx.createImageData(S, S); + const dark = [8, 42, 54], light = [28, 96, 108]; + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const i = y * S + x; + // long swell lines, periodic on the tile (integer frequencies) + const swell = Math.sin(2 * Math.PI * (2 * x / S + 3 * y / S) + n[i] * 5); + let t = Math.min(1, Math.max(0, n[i] * 1.25 - 0.12 + swell * 0.08)); + if (swell > 0.93) t = Math.min(1, t + (swell - 0.93) * 3); + const p = i * 4; + img.data[p] = dark[0] + (light[0] - dark[0]) * t; + img.data[p + 1] = dark[1] + (light[1] - dark[1]) * t; + img.data[p + 2] = dark[2] + (light[2] - dark[2]) * t; + img.data[p + 3] = 255; + } + ctx.putImageData(img, 0, 0); + addCanvas(scene, 'di-water', c); + + // Caustics: bright where two wavy fields cross zero. + const c2 = canvas(S, S), x2 = c2.getContext('2d'); + const m = periodicNoise(S, S, seeded(77), [4, 8], [0.6, 0.4]); + const img2 = x2.createImageData(S, S); + for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { + const i = y * S + x; + const a = Math.sin(2 * Math.PI * (3 * x / S) + m[i] * 9); + const b = Math.sin(2 * Math.PI * (2 * y / S + x / S) + m[i] * 7); + const v = Math.pow(1 - Math.abs(a), 10) + Math.pow(1 - Math.abs(b), 12); + const p = i * 4; + img2.data[p] = 210; img2.data[p + 1] = 245; img2.data[p + 2] = 240; + img2.data[p + 3] = Math.min(255, v * 150); + } + x2.putImageData(img2, 0, 0); + addCanvas(scene, 'di-caustic', c2); +} + +function bakeCloud(scene) { + const Wc = 512, Hc = 256, c = canvas(Wc, Hc), ctx = c.getContext('2d'); + const n = periodicNoise(Wc, Hc, seeded(4242), [3, 6, 12, 24], [0.45, 0.3, 0.15, 0.1]); + const img = ctx.createImageData(Wc, Hc); + for (let i = 0; i < Wc * Hc; i++) { + const v = n[i]; + const a = Math.max(0, Math.min(1, (v - 0.38) / 0.32)); + const p = i * 4, g = 26 + v * 40; + img.data[p] = g * 0.8; img.data[p + 1] = g; img.data[p + 2] = g * 1.1; img.data[p + 3] = a * a * 235; + } + ctx.putImageData(img, 0, 0); + addCanvas(scene, 'di-cloud', c); +} + +// ── tiles ──────────────────────────────────────────────────────────────────── +function bakeSlab(scene) { + const B = 10, S = (TILE + B * 2) * RES, c = canvas(S, S), ctx = c.getContext('2d'); + const rand = seeded(11); + ctx.scale(RES, RES); + const s = TILE + B * 2; + // stone body + const g = ctx.createLinearGradient(0, 0, s, s); + g.addColorStop(0, '#8a8070'); g.addColorStop(0.5, '#5f574b'); g.addColorStop(1, '#3a342c'); + ctx.fillStyle = g; rr(ctx, 0, 0, s, s, 9); ctx.fill(); + speckle(ctx, s, s, rand, 260, '#1b1712', 1.4); + speckle(ctx, s, s, rand, 120, '#d8cdb5', 0.9); + // bevel: light top-left, dark bottom-right + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(255,240,210,0.35)'; + ctx.beginPath(); ctx.moveTo(2, s - 9); ctx.lineTo(2, 9); ctx.quadraticCurveTo(2, 2, 9, 2); ctx.lineTo(s - 9, 2); ctx.stroke(); + ctx.strokeStyle = 'rgba(0,0,0,0.5)'; + ctx.beginPath(); ctx.moveTo(s - 2, 9); ctx.lineTo(s - 2, s - 9); ctx.quadraticCurveTo(s - 2, s - 2, s - 9, s - 2); ctx.lineTo(9, s - 2); ctx.stroke(); + // recess the painting sits in + ctx.fillStyle = '#16120d'; ctx.fillRect(B - 2, B - 2, TILE + 4, TILE + 4); + // brass corner studs + for (const [x, y] of [[5, 5], [s - 5, 5], [5, s - 5], [s - 5, s - 5]]) { + const sg = ctx.createRadialGradient(x - 1, y - 1, 0.5, x, y, 3.5); + sg.addColorStop(0, '#fff0c0'); sg.addColorStop(0.5, '#c9a14a'); sg.addColorStop(1, '#5a3f14'); + ctx.fillStyle = sg; ctx.beginPath(); ctx.arc(x, y, 3.4, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, 'di-slab', c); +} + +function bakeFoam(scene) { + const P = 26, s = TILE + 20 + P * 2, S = s * RES, c = canvas(S, S), ctx = c.getContext('2d'); + const rand = seeded(5); + ctx.scale(RES, RES); + // soft halo + for (let i = 0; i < 9; i++) { + ctx.strokeStyle = `rgba(225,245,240,${0.05 + i * 0.012})`; + ctx.lineWidth = 14 - i * 1.4; + rr(ctx, P - 4 + i * 0.6, P - 4 + i * 0.6, s - 2 * P + 8 - i * 1.2, s - 2 * P + 8 - i * 1.2, 14); + ctx.stroke(); + } + // foam flecks around the rim + const per = 4 * (s - 2 * P); + for (let i = 0; i < 340; i++) { + let d = rand() * per, x, y; + const side = s - 2 * P; + if (d < side) { x = P + d; y = P; } else if (d < 2 * side) { x = P + side; y = P + d - side; } + else if (d < 3 * side) { x = P + 3 * side - d; y = P + side; } else { x = P; y = P + 4 * side - d; } + const off = (rand() - 0.3) * 14; + const nx = x === P ? -1 : x === P + side ? 1 : 0, ny = y === P ? -1 : y === P + side ? 1 : 0; + ctx.fillStyle = `rgba(240,252,250,${0.25 + rand() * 0.5})`; + ctx.beginPath(); ctx.arc(x + nx * off, y + ny * off, 0.6 + rand() * 1.8, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, 'di-foam', c); +} + +function bakePlaque(scene) { + const w = TILE - 6, h = 20, c = canvas(w * RES, h * RES), ctx = c.getContext('2d'); + ctx.scale(RES, RES); + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, '#f0d58c'); g.addColorStop(0.45, '#c9a14a'); g.addColorStop(1, '#7a5a20'); + ctx.fillStyle = g; rr(ctx, 0, 0, w, h, 4); ctx.fill(); + ctx.strokeStyle = 'rgba(60,40,10,0.9)'; ctx.lineWidth = 1; rr(ctx, 0.5, 0.5, w - 1, h - 1, 4); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,245,210,0.5)'; rr(ctx, 2, 2, w - 4, h - 4, 3); ctx.stroke(); + for (const x of [5, w - 5]) { + ctx.fillStyle = '#4a3410'; ctx.beginPath(); ctx.arc(x, h / 2, 1.6, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, 'di-plaque', c); +} + +// Relic glyphs pressed into the wax seals (simple original marks). +function glyph(ctx, key, r) { + ctx.lineWidth = 1.6; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; + ctx.beginPath(); + if (key === 'earth') { // cracked orb on a stand + ctx.arc(0, -1.5, r * 0.42, 0, Math.PI * 2); + ctx.moveTo(-r * 0.2, -r * 0.35); ctx.lineTo(0, -r * 0.1); ctx.lineTo(-r * 0.05, r * 0.1); + ctx.moveTo(-r * 0.3, r * 0.5); ctx.lineTo(r * 0.3, r * 0.5); + } else if (key === 'wind') { // spread wing + ctx.moveTo(-r * 0.5, r * 0.3); ctx.quadraticCurveTo(-r * 0.1, -r * 0.6, r * 0.55, -r * 0.45); + ctx.moveTo(-r * 0.3, r * 0.3); ctx.quadraticCurveTo(0, -r * 0.2, r * 0.5, -r * 0.15); + ctx.moveTo(-r * 0.1, r * 0.3); ctx.quadraticCurveTo(r * 0.1, r * 0.05, r * 0.45, r * 0.12); + } else if (key === 'fire') { // flame + ctx.moveTo(0, r * 0.55); + ctx.bezierCurveTo(-r * 0.6, r * 0.3, -r * 0.3, -r * 0.2, 0, -r * 0.6); + ctx.bezierCurveTo(r * 0.1, -r * 0.2, r * 0.6, r * 0.1, 0, r * 0.55); + } else { // chalice + ctx.moveTo(-r * 0.42, -r * 0.45); ctx.quadraticCurveTo(-r * 0.4, r * 0.1, 0, r * 0.12); + ctx.quadraticCurveTo(r * 0.4, r * 0.1, r * 0.42, -r * 0.45); ctx.closePath(); + ctx.moveTo(0, r * 0.12); ctx.lineTo(0, r * 0.45); + ctx.moveTo(-r * 0.25, r * 0.5); ctx.lineTo(r * 0.25, r * 0.5); + } + ctx.stroke(); +} + +function bakeSeals(scene) { + const s = 30, S = s * RES; + for (const k of TREASURE_KEYS) { + const c = canvas(S, S), ctx = c.getContext('2d'); + ctx.scale(RES, RES); ctx.translate(s / 2, s / 2); + const col = TREASURES[k].color; + const r = 12.5; + // wavy wax blob + ctx.beginPath(); + for (let i = 0; i <= 24; i++) { + const a = (i / 24) * Math.PI * 2, rr2 = r + Math.sin(i * 2.7) * 1.1; + i ? ctx.lineTo(Math.cos(a) * rr2, Math.sin(a) * rr2) : ctx.moveTo(Math.cos(a) * rr2, Math.sin(a) * rr2); + } + ctx.closePath(); + const g = ctx.createRadialGradient(-4, -4, 1, 0, 0, r + 2); + g.addColorStop(0, shade(col, 0.35)); g.addColorStop(0.7, hex(col)); g.addColorStop(1, shade(col, -0.45)); + ctx.fillStyle = g; ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 3; ctx.fill(); ctx.shadowBlur = 0; + ctx.strokeStyle = shade(col, -0.5); ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(0, 0, r * 0.72, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = shade(col, 0.6); glyph(ctx, k, r); + addCanvas(scene, `di-seal-${k}`, c); + } +} + +// ── figurines ──────────────────────────────────────────────────────────────── +function bakePawns(scene) { + const w = PAWN.w, h = PAWN.h; + for (const role of ROLE_KEYS) { + const col = ROLES[role].color; + const c = canvas(w * RES, h * RES), ctx = c.getContext('2d'); + ctx.scale(RES, RES); + const cx = w / 2; + ctx.lineJoin = 'round'; + // turned wooden base + const bg = ctx.createLinearGradient(cx - 18, 0, cx + 18, 0); + bg.addColorStop(0, '#4a2f18'); bg.addColorStop(0.4, '#8a5f34'); bg.addColorStop(1, '#2e1c0e'); + ctx.fillStyle = bg; + ctx.beginPath(); ctx.ellipse(cx, h - 7, 17, 5.5, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillRect(cx - 17, h - 11, 34, 4); + ctx.beginPath(); ctx.ellipse(cx, h - 11, 17, 5.5, 0, 0, Math.PI * 2); + ctx.fillStyle = '#9a6c3c'; ctx.fill(); + ctx.strokeStyle = shade(col, 0.1); ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.ellipse(cx, h - 11, 15, 4.5, 0, 0, Math.PI * 2); ctx.stroke(); + // body: a painted, slightly flared column + const body = ctx.createLinearGradient(cx - 12, 0, cx + 12, 0); + body.addColorStop(0, shade(col, 0.35)); body.addColorStop(0.45, hex(col)); body.addColorStop(1, shade(col, -0.55)); + ctx.fillStyle = body; + ctx.beginPath(); + ctx.moveTo(cx - 13, h - 12); + ctx.quadraticCurveTo(cx - 12, h - 30, cx - 9, h - 38); + ctx.quadraticCurveTo(cx, h - 43, cx + 9, h - 38); + ctx.quadraticCurveTo(cx + 12, h - 30, cx + 13, h - 12); + ctx.closePath(); ctx.fill(); + ctx.strokeStyle = 'rgba(20,12,6,0.85)'; ctx.lineWidth = 1.2; ctx.stroke(); + // belt + ctx.fillStyle = 'rgba(30,18,8,0.75)'; ctx.fillRect(cx - 11.5, h - 25, 23, 3); + ctx.fillStyle = '#d8b25a'; ctx.fillRect(cx - 1.5, h - 25, 3, 3); + // head + const hy = h - 47; + const hg = ctx.createRadialGradient(cx - 3, hy - 3, 1, cx, hy, 9); + hg.addColorStop(0, '#f3dcb8'); hg.addColorStop(1, '#a87a4e'); + ctx.fillStyle = hg; ctx.beginPath(); ctx.arc(cx, hy, 8, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(40,24,10,0.8)'; ctx.stroke(); + // role headgear / kit + ctx.lineWidth = 1.2; + if (role === 'pilot') { + ctx.fillStyle = '#5a3a1e'; + ctx.beginPath(); ctx.arc(cx, hy - 1, 8.6, Math.PI, 0); ctx.lineTo(cx + 9, hy + 4); ctx.lineTo(cx + 6, hy + 3); ctx.lineTo(cx + 6, hy); ctx.lineTo(cx - 6, hy); ctx.lineTo(cx - 6, hy + 3); ctx.lineTo(cx - 9, hy + 4); ctx.closePath(); ctx.fill(); ctx.stroke(); + for (const dx of [-3.5, 3.5]) { ctx.fillStyle = '#c9a14a'; ctx.beginPath(); ctx.arc(cx + dx, hy - 4, 2.8, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = '#9fd3e0'; ctx.beginPath(); ctx.arc(cx + dx, hy - 4, 1.6, 0, Math.PI * 2); ctx.fill(); } + ctx.fillStyle = '#efe6d2'; ctx.beginPath(); ctx.moveTo(cx - 7, h - 40); ctx.lineTo(cx + 9, h - 39); ctx.lineTo(cx + 13, h - 32); ctx.lineTo(cx + 5, h - 37); ctx.closePath(); ctx.fill(); // scarf + } else if (role === 'engineer') { + ctx.fillStyle = '#e0b33a'; + ctx.beginPath(); ctx.arc(cx, hy - 1, 9, Math.PI, 0); ctx.closePath(); ctx.fill(); ctx.stroke(); + ctx.fillRect(cx - 12, hy - 2, 24, 2.6); ctx.strokeRect(cx - 12, hy - 2, 24, 2.6); + ctx.strokeStyle = '#3a3a3a'; ctx.lineWidth = 2.2; ctx.beginPath(); ctx.moveTo(cx + 10, h - 18); ctx.lineTo(cx + 15, h - 32); ctx.stroke(); + ctx.beginPath(); ctx.arc(cx + 15.5, h - 33.5, 2.4, 0, Math.PI * 2); ctx.stroke(); + } else if (role === 'messenger') { + ctx.strokeStyle = '#2a2a2a'; ctx.lineWidth = 1.8; ctx.beginPath(); ctx.arc(cx, hy, 9.5, Math.PI * 1.1, Math.PI * 1.9); ctx.stroke(); + ctx.fillStyle = '#2a2a2a'; for (const dx of [-9, 9]) { ctx.beginPath(); ctx.ellipse(cx + dx, hy + 1, 2.6, 3.6, 0, 0, Math.PI * 2); ctx.fill(); } + ctx.fillStyle = '#6b5a3a'; ctx.fillRect(cx - 17, h - 36, 7, 14); ctx.strokeStyle = 'rgba(20,12,6,0.8)'; ctx.lineWidth = 1; ctx.strokeRect(cx - 17, h - 36, 7, 14); + ctx.strokeStyle = '#3a3a3a'; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(cx - 14, h - 36); ctx.lineTo(cx - 18, h - 58); ctx.stroke(); + ctx.fillStyle = '#c84a3a'; ctx.beginPath(); ctx.arc(cx - 18, h - 58, 1.8, 0, Math.PI * 2); ctx.fill(); + } else if (role === 'navigator') { + ctx.fillStyle = '#e8dcbc'; + ctx.beginPath(); ctx.ellipse(cx, hy - 1, 13, 3, 0, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); + const pg = ctx.createRadialGradient(cx - 3, hy - 8, 1, cx, hy - 4, 9); + pg.addColorStop(0, '#fffaf0'); pg.addColorStop(1, '#bfae86'); + ctx.fillStyle = pg; ctx.beginPath(); ctx.arc(cx, hy - 2, 8.5, Math.PI, 0); ctx.closePath(); ctx.fill(); ctx.stroke(); + ctx.fillStyle = '#7a5a2a'; ctx.fillRect(cx - 8.5, hy - 4, 17, 1.8); + ctx.fillStyle = '#f2e6cc'; ctx.save(); ctx.translate(cx + 13, h - 28); ctx.rotate(0.3); ctx.fillRect(-2, -8, 4, 16); ctx.strokeRect(-2, -8, 4, 16); ctx.restore(); // rolled chart + } else if (role === 'diver') { + const dg = ctx.createRadialGradient(cx - 4, hy - 4, 1, cx, hy, 13); + dg.addColorStop(0, '#fff1c0'); dg.addColorStop(0.45, '#c9963a'); dg.addColorStop(1, '#5a3a10'); + ctx.fillStyle = dg; ctx.beginPath(); ctx.arc(cx, hy, 11.5, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = 'rgba(40,24,6,0.9)'; ctx.stroke(); + ctx.fillStyle = '#163c46'; ctx.beginPath(); ctx.arc(cx, hy + 1, 5.2, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#e8c870'; ctx.lineWidth = 1.4; ctx.beginPath(); ctx.arc(cx, hy + 1, 5.2, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(cx - 5, hy + 1); ctx.lineTo(cx + 5, hy + 1); ctx.moveTo(cx, hy - 4); ctx.lineTo(cx, hy + 6); ctx.stroke(); + ctx.fillStyle = 'rgba(180,230,240,0.6)'; ctx.beginPath(); ctx.arc(cx - 2, hy - 1, 1.3, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#e8c870'; for (const a of [0.6, 2.5, 3.8, 5.6]) { ctx.beginPath(); ctx.arc(cx + Math.cos(a) * 9, hy + Math.sin(a) * 9, 1, 0, Math.PI * 2); ctx.fill(); } + } else if (role === 'explorer') { + ctx.fillStyle = '#b5392c'; + ctx.beginPath(); ctx.arc(cx, hy - 1, 8.8, Math.PI, 0); ctx.closePath(); ctx.fill(); ctx.stroke(); + ctx.fillStyle = '#f2e6cc'; ctx.beginPath(); ctx.arc(cx, hy - 10.5, 2.6, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#f2e6cc'; ctx.fillRect(cx - 9, hy - 2.5, 18, 2.4); + ctx.strokeStyle = '#c8b27a'; ctx.lineWidth = 2.4; // coiled rope across the chest + ctx.beginPath(); ctx.moveTo(cx - 11, h - 37); ctx.lineTo(cx + 12, h - 16); ctx.stroke(); + ctx.lineWidth = 1; ctx.strokeStyle = '#7a6438'; + for (let i = 0; i < 6; i++) { const t = i / 5; ctx.beginPath(); ctx.moveTo(cx - 11 + 23 * t - 1.5, h - 37 + 21 * t + 1.5); ctx.lineTo(cx - 11 + 23 * t + 1.5, h - 37 + 21 * t - 1.5); ctx.stroke(); } + } + // varnish highlight + ctx.fillStyle = 'rgba(255,255,255,0.18)'; + ctx.beginPath(); ctx.ellipse(cx - 6, h - 28, 2.2, 9, 0.1, 0, Math.PI * 2); ctx.fill(); + addCanvas(scene, `di-pawn-${role}`, c); + } + // contact shadow + const sc = canvas(64, 24), sx = sc.getContext('2d'); + const g = sx.createRadialGradient(32, 12, 1, 32, 12, 30); + g.addColorStop(0, 'rgba(0,0,0,0.55)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + sx.fillStyle = g; sx.save(); sx.scale(1, 0.4); sx.beginPath(); sx.arc(32, 30, 30, 0, Math.PI * 2); sx.fill(); sx.restore(); + addCanvas(scene, 'di-shadow', sc); +} + +// ── card backs ─────────────────────────────────────────────────────────────── +function bakeBacks(scene) { + const w = BACK.w, h = BACK.h, rand = seeded(88); + // Supply crate (treasure deck) + { + const c = canvas(w * RES, h * RES), ctx = c.getContext('2d'); + ctx.scale(RES, RES); + rr(ctx, 0, 0, w, h, 6); ctx.save(); ctx.clip(); + const planks = 4, pw = w / planks; + for (let i = 0; i < planks; i++) { + const g = ctx.createLinearGradient(i * pw, 0, (i + 1) * pw, 0); + const base = 0.85 + rand() * 0.25; + g.addColorStop(0, `rgb(${120 * base},${84 * base},${46 * base})`); + g.addColorStop(1, `rgb(${96 * base},${64 * base},${34 * base})`); + ctx.fillStyle = g; ctx.fillRect(i * pw, 0, pw, h); + ctx.strokeStyle = 'rgba(50,30,12,0.35)'; ctx.lineWidth = 0.6; + for (let k = 0; k < 5; k++) { + const x0 = i * pw + 2 + rand() * (pw - 4); + ctx.beginPath(); ctx.moveTo(x0, 0); + for (let y = 0; y <= h; y += 12) ctx.lineTo(x0 + Math.sin(y * 0.08 + k) * 1.2, y); + ctx.stroke(); + } + ctx.fillStyle = 'rgba(20,10,4,0.7)'; ctx.fillRect((i + 1) * pw - 0.8, 0, 1.2, h); + } + // cross battens + ctx.fillStyle = 'rgba(70,44,20,0.95)'; + ctx.fillRect(0, 12, w, 9); ctx.fillRect(0, h - 21, w, 9); + ctx.fillStyle = '#9a9a92'; + for (const y of [16.5, h - 16.5]) for (const x of [6, w - 6]) { ctx.beginPath(); ctx.arc(x, y, 1.6, 0, Math.PI * 2); ctx.fill(); } + // stencil + ctx.fillStyle = 'rgba(25,14,6,0.82)'; + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.font = `bold 11px ${TYPE_FONT}`; ctx.fillText('EXPEDITION', w / 2, h / 2 - 12); + ctx.font = `bold 13px ${TYPE_FONT}`; ctx.fillText('SUPPLIES', w / 2, h / 2 + 2); + ctx.fillStyle = 'rgba(140,30,20,0.85)'; ctx.font = `bold 9px ${TYPE_FONT}`; ctx.fillText('· 1934 ·', w / 2, h / 2 + 16); + ctx.restore(); + ctx.strokeStyle = '#3a240f'; ctx.lineWidth = 1.5; rr(ctx, 0.75, 0.75, w - 1.5, h - 1.5, 6); ctx.stroke(); + addCanvas(scene, 'di-back-treasure', c); + } + // Tide chart (flood deck) + { + const c = canvas(w * RES, h * RES), ctx = c.getContext('2d'); + ctx.scale(RES, RES); + rr(ctx, 0, 0, w, h, 6); ctx.save(); ctx.clip(); + const g = ctx.createLinearGradient(0, 0, w, h); + g.addColorStop(0, '#cfe0dc'); g.addColorStop(1, '#9fbcb8'); + ctx.fillStyle = g; ctx.fillRect(0, 0, w, h); + speckle(ctx, w, h, rand, 140, '#2a4a50', 0.8); + ctx.strokeStyle = 'rgba(30,70,80,0.25)'; ctx.lineWidth = 0.5; + for (let x = 6; x < w; x += 10) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); } + for (let y = 6; y < h; y += 10) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); } + ctx.strokeStyle = 'rgba(25,70,95,0.55)'; ctx.lineWidth = 0.9; + for (let k = 0; k < 5; k++) { + ctx.beginPath(); + for (let x = 0; x <= w; x += 2) { const y = 22 + k * 16 + Math.sin(x * 0.12 + k * 1.3) * 3; x ? ctx.lineTo(x, y) : ctx.moveTo(x, y); } + ctx.stroke(); + } + // compass rose + ctx.translate(w / 2, h / 2 + 4); + ctx.fillStyle = 'rgba(233,220,192,0.9)'; ctx.beginPath(); ctx.arc(0, 0, 17, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#1f4a66'; ctx.lineWidth = 1; ctx.stroke(); + for (let i = 0; i < 8; i++) { + const a = (i / 8) * Math.PI * 2, L = i % 2 ? 9 : 15; + ctx.fillStyle = i % 2 ? '#5a7a8a' : (i === 0 ? '#8e2a1e' : '#1f4a66'); + ctx.beginPath(); ctx.moveTo(Math.cos(a) * L, Math.sin(a) * L); + ctx.lineTo(Math.cos(a + 0.35) * 3, Math.sin(a + 0.35) * 3); ctx.lineTo(Math.cos(a - 0.35) * 3, Math.sin(a - 0.35) * 3); ctx.closePath(); ctx.fill(); + } + ctx.setTransform(RES, 0, 0, RES, 0, 0); + ctx.fillStyle = '#1f4a66'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.font = `bold 10px ${TYPE_FONT}`; ctx.fillText('TIDE CHART', w / 2, 12); + ctx.font = `8px ${TYPE_FONT}`; ctx.fillText('SURVEY · No. 7', w / 2, h - 10); + ctx.restore(); + ctx.strokeStyle = '#1f4a66'; ctx.lineWidth = 1.5; rr(ctx, 0.75, 0.75, w - 1.5, h - 1.5, 6); ctx.stroke(); + ctx.strokeStyle = 'rgba(31,74,102,0.5)'; ctx.lineWidth = 0.7; rr(ctx, 4, 4, w - 8, h - 8, 4); ctx.stroke(); + addCanvas(scene, 'di-back-flood', c); + } +} + +// ── paper, leather, wood ───────────────────────────────────────────────────── +function paper(ctx, w, h, rand, { edge = 0.45, tone = [233, 220, 192] } = {}) { + const [r, g, b] = tone; + ctx.fillStyle = `rgb(${r},${g},${b})`; ctx.fillRect(0, 0, w, h); + // blotchy fibres + for (let i = 0; i < (w * h) / 900; i++) { + const x = rand() * w, y = rand() * h, rad = 8 + rand() * 40; + const gg = ctx.createRadialGradient(x, y, 0, x, y, rad); + const d = rand() < 0.5 ? '120,90,50' : '255,250,235'; + gg.addColorStop(0, `rgba(${d},${0.03 + rand() * 0.04})`); gg.addColorStop(1, `rgba(${d},0)`); + ctx.fillStyle = gg; ctx.fillRect(x - rad, y - rad, rad * 2, rad * 2); + } + speckle(ctx, w, h, rand, (w * h) / 300, '#5a4020', 0.7); + // darkened, foxed edges + const vg = ctx.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.3, w / 2, h / 2, Math.max(w, h) * 0.75); + vg.addColorStop(0, 'rgba(90,60,25,0)'); vg.addColorStop(1, `rgba(90,60,25,${edge})`); + ctx.fillStyle = vg; ctx.fillRect(0, 0, w, h); +} + +function bakeJournal(scene) { + const { w, h } = JOURNAL, c = canvas(w, h), ctx = c.getContext('2d'); + const rand = seeded(1930); + // leather cover peeking out behind the page + ctx.fillStyle = '#2a1a10'; rr(ctx, 0, 0, w, h, 14); ctx.fill(); + speckle(ctx, w, h, rand, 1200, '#000', 1.5); + ctx.save(); rr(ctx, 10, 8, w - 18, h - 16, 6); ctx.clip(); + ctx.translate(10, 8); + paper(ctx, w - 18, h - 16, rand, { edge: 0.5 }); + // gutter shadow on the left (book spine) and a ruled red margin + const gg = ctx.createLinearGradient(0, 0, 40, 0); + gg.addColorStop(0, 'rgba(60,35,10,0.5)'); gg.addColorStop(1, 'rgba(60,35,10,0)'); + ctx.fillStyle = gg; ctx.fillRect(0, 0, 40, h); + ctx.strokeStyle = 'rgba(160,50,40,0.35)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(30, 0); ctx.lineTo(30, h); ctx.stroke(); + // coffee ring + ctx.strokeStyle = 'rgba(110,70,30,0.18)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.arc(w - 120, h - 210, 46, 0.3, Math.PI * 1.85); ctx.stroke(); + ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(w - 118, h - 208, 41, 0.1, Math.PI * 1.6); ctx.stroke(); + ctx.restore(); + // stitching along the cover edge + ctx.strokeStyle = 'rgba(201,161,74,0.55)'; ctx.setLineDash([6, 5]); ctx.lineWidth = 1.5; + rr(ctx, 4, 3, w - 8, h - 6, 12); ctx.stroke(); ctx.setLineDash([]); + addCanvas(scene, 'di-journal', c); +} + +function bakeStrip(scene) { + const w = BOARD_W + 4, h = 86, c = canvas(w, h), ctx = c.getContext('2d'); + const rand = seeded(31); + ctx.save(); rr(ctx, 0, 0, w, h, 6); ctx.clip(); + paper(ctx, w, h, rand, { edge: 0.55, tone: [226, 210, 178] }); + ctx.restore(); + ctx.strokeStyle = 'rgba(60,40,15,0.7)'; ctx.lineWidth = 1.5; rr(ctx, 0.75, 0.75, w - 1.5, h - 1.5, 6); ctx.stroke(); + // tape at the corners, as if pinned into the journal + for (const [x, a] of [[18, -0.5], [w - 18, 0.5]]) { + ctx.save(); ctx.translate(x, 4); ctx.rotate(a); + ctx.fillStyle = 'rgba(240,232,200,0.7)'; ctx.fillRect(-16, -6, 32, 12); ctx.restore(); + } + addCanvas(scene, 'di-strip', c); +} + +function bakeShelf(scene) { + const w = BOARD_W + 20, h = 138, c = canvas(w, h), ctx = c.getContext('2d'); + const rand = seeded(64); + const g = ctx.createLinearGradient(0, 0, 0, h); + g.addColorStop(0, '#6a5038'); g.addColorStop(0.5, '#4d3826'); g.addColorStop(1, '#2e2016'); + ctx.fillStyle = g; rr(ctx, 0, 0, w, h, 12); ctx.fill(); + ctx.save(); rr(ctx, 0, 0, w, h, 12); ctx.clip(); + ctx.strokeStyle = 'rgba(25,15,8,0.35)'; + for (let k = 0; k < 26; k++) { + ctx.lineWidth = 0.5 + rand() * 1.2; + const y0 = rand() * h; + ctx.beginPath(); + for (let x = 0; x <= w; x += 8) { const y = y0 + Math.sin(x * 0.01 + k) * 4 + Math.sin(x * 0.05 + k * 3) * 1.2; x ? ctx.lineTo(x, y) : ctx.moveTo(x, y); } + ctx.stroke(); + } + for (let i = 0; i < 3; i++) { // knots + const x = 60 + rand() * (w - 120), y = 20 + rand() * (h - 40); + ctx.strokeStyle = 'rgba(25,15,8,0.4)'; ctx.lineWidth = 1; + for (let r = 2; r < 10; r += 2.5) { ctx.beginPath(); ctx.ellipse(x, y, r * 2.2, r, 0, 0, Math.PI * 2); ctx.stroke(); } + } + ctx.restore(); + ctx.strokeStyle = 'rgba(255,230,180,0.18)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(12, 2); ctx.lineTo(w - 12, 2); ctx.stroke(); + addCanvas(scene, 'di-shelf', c); +} + +export function bakeLeather(scene, w, h) { + const key = `di-leather-${w}x${h}`; + if (scene.textures.exists(key)) return key; + const c = canvas(w, h), ctx = c.getContext('2d'); + const rand = seeded(w * 7 + h); + const g = ctx.createLinearGradient(0, 0, w, h); + g.addColorStop(0, '#3a2818'); g.addColorStop(0.5, '#2a1c11'); g.addColorStop(1, '#1a110a'); + ctx.fillStyle = g; rr(ctx, 0, 0, w, h, 18); ctx.fill(); + ctx.save(); rr(ctx, 0, 0, w, h, 18); ctx.clip(); + speckle(ctx, w, h, rand, (w * h) / 120, '#000', 1.6); + speckle(ctx, w, h, rand, (w * h) / 500, '#8a6a48', 1.0); + const vg = ctx.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.2, w / 2, h / 2, Math.max(w, h) * 0.7); + vg.addColorStop(0, 'rgba(120,80,40,0.12)'); vg.addColorStop(1, 'rgba(0,0,0,0.45)'); + ctx.fillStyle = vg; ctx.fillRect(0, 0, w, h); + ctx.restore(); + ctx.strokeStyle = '#c9a14a'; ctx.lineWidth = 3; rr(ctx, 1.5, 1.5, w - 3, h - 3, 17); ctx.stroke(); + ctx.strokeStyle = 'rgba(216,178,90,0.6)'; ctx.setLineDash([7, 5]); ctx.lineWidth = 1.4; + rr(ctx, 11, 11, w - 22, h - 22, 11); ctx.stroke(); ctx.setLineDash([]); + // brass corner pieces + for (const [x, y, sx, sy] of [[0, 0, 1, 1], [w, 0, -1, 1], [0, h, 1, -1], [w, h, -1, -1]]) { + ctx.save(); ctx.translate(x, y); ctx.scale(sx, sy); + const bg = ctx.createLinearGradient(0, 0, 34, 34); + bg.addColorStop(0, '#f6dc94'); bg.addColorStop(0.5, '#c9a14a'); bg.addColorStop(1, '#6e5222'); + ctx.fillStyle = bg; + ctx.beginPath(); ctx.moveTo(4, 4); ctx.lineTo(38, 4); ctx.quadraticCurveTo(18, 10, 4, 38); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#3a2a10'; ctx.beginPath(); ctx.arc(12, 12, 2, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + } + addCanvas(scene, key, c); + return key; +} + +// Parchment panel of any size (journal entries, plates and notes). +export function bakeParchment(scene, w, h, seed = 3) { + const key = `di-parch-${w}x${h}`; + if (scene.textures.exists(key)) return key; + const c = canvas(w, h), ctx = c.getContext('2d'); + ctx.save(); rr(ctx, 0, 0, w, h, 10); ctx.clip(); + paper(ctx, w, h, seeded(seed + w + h), { edge: 0.5 }); + ctx.restore(); + ctx.strokeStyle = 'rgba(70,45,15,0.7)'; ctx.lineWidth = 2; rr(ctx, 1, 1, w - 2, h - 2, 10); ctx.stroke(); + addCanvas(scene, key, c); + return key; +} + +// ── tide gauge ─────────────────────────────────────────────────────────────── +export const GAUGE_TUBE = { w: 30, pad: 46 }; +function bakeGauge(scene) { + const span = GAUGE.bottom - GAUGE.top, w = 92, h = span + 120; + const c = canvas(w * RES, h * RES), ctx = c.getContext('2d'); + ctx.scale(RES, RES); + const cx = w / 2, top = 60; // tube spans top..top+span in this canvas + // brass backing plate + const g = ctx.createLinearGradient(0, 0, w, 0); + g.addColorStop(0, '#6e5222'); g.addColorStop(0.25, '#e6c477'); g.addColorStop(0.55, '#b48a38'); g.addColorStop(1, '#5a4016'); + ctx.fillStyle = g; rr(ctx, 6, 0, w - 12, h, 20); ctx.fill(); + ctx.strokeStyle = '#3a2808'; ctx.lineWidth = 2; ctx.stroke(); + speckle(ctx, w, h, seeded(9), 300, '#3a2808', 0.9); + // rivets + for (let y = 18; y < h - 10; y += (h - 36) / 6) for (const x of [14, w - 14]) { + const rg = ctx.createRadialGradient(x - 1, y - 1, 0.5, x, y, 3.4); + rg.addColorStop(0, '#fff2c8'); rg.addColorStop(1, '#5a4016'); + ctx.fillStyle = rg; ctx.beginPath(); ctx.arc(x, y, 3, 0, Math.PI * 2); ctx.fill(); + } + // engraved title + ctx.fillStyle = '#3a2808'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.font = `bold 12px ${TYPE_FONT}`; ctx.fillText('TIDE', cx, 22); + ctx.font = `9px ${TYPE_FONT}`; ctx.fillText('GAUGE', cx, 36); + // glass channel + const tw = GAUGE_TUBE.w; + ctx.fillStyle = '#0c1a1e'; rr(ctx, cx - tw / 2 - 3, top - 6, tw + 6, span + 12, 14); ctx.fill(); + const gl = ctx.createLinearGradient(cx - tw / 2, 0, cx + tw / 2, 0); + gl.addColorStop(0, 'rgba(160,200,200,0.25)'); gl.addColorStop(0.3, 'rgba(255,255,255,0.08)'); gl.addColorStop(1, 'rgba(0,0,0,0.25)'); + ctx.fillStyle = gl; rr(ctx, cx - tw / 2, top - 3, tw, span + 6, 12); ctx.fill(); + // ticks and numbers on the left of the tube + const seg = span / MAX_WATER; + for (let lvl = 1; lvl <= MAX_WATER; lvl++) { + const y = top + (MAX_WATER - lvl) * seg + seg / 2; + ctx.strokeStyle = '#3a2808'; ctx.lineWidth = 1.2; + ctx.beginPath(); ctx.moveTo(cx - tw / 2 - 12, y); ctx.lineTo(cx - tw / 2 - 4, y); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(cx + tw / 2 + 4, y); ctx.lineTo(cx + tw / 2 + 12, y); ctx.stroke(); + if (lvl < MAX_WATER) { + ctx.fillStyle = lvl >= 8 ? '#8e2a1e' : '#3a2808'; + ctx.font = `bold 11px ${TYPE_FONT}`; ctx.fillText(String(lvl), cx - tw / 2 - 18 + (lvl >= 10 ? -2 : 0), y + 0.5); + } + const yb = top + (MAX_WATER - lvl) * seg; + ctx.strokeStyle = 'rgba(58,40,8,0.5)'; ctx.lineWidth = 0.7; + ctx.beginPath(); ctx.moveTo(cx - tw / 2 - 6, yb); ctx.lineTo(cx - tw / 2 - 2, yb); ctx.stroke(); + } + // drowned mark: a small skull at the top band + const sy = top + seg / 2; + ctx.save(); ctx.translate(cx - tw / 2 - 18, sy); + ctx.fillStyle = '#8e2a1e'; ctx.beginPath(); ctx.arc(0, -1.5, 5.5, 0, Math.PI * 2); ctx.fill(); ctx.fillRect(-3.5, 2, 7, 4); + ctx.fillStyle = '#e6c477'; ctx.beginPath(); ctx.arc(-2, -1.5, 1.5, 0, Math.PI * 2); ctx.arc(2, -1.5, 1.5, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + // danger band on the right + ctx.fillStyle = 'rgba(142,42,30,0.75)'; + ctx.fillRect(cx + tw / 2 + 14, top, 4, seg * 3); + ctx.fillStyle = 'rgba(200,120,40,0.7)'; + ctx.fillRect(cx + tw / 2 + 14, top + seg * 3, 4, seg * 2); + addCanvas(scene, 'di-gauge', c); + return { w, h, top }; +} + +// ── particles ──────────────────────────────────────────────────────────────── +function bakeParticles(scene) { + { // rain streak + const c = canvas(4, 40), ctx = c.getContext('2d'); + const g = ctx.createLinearGradient(0, 0, 0, 40); + g.addColorStop(0, 'rgba(210,235,240,0)'); g.addColorStop(1, 'rgba(210,235,240,0.85)'); + ctx.fillStyle = g; ctx.fillRect(1, 0, 2, 40); + addCanvas(scene, 'di-rain', c); + } + { const c = canvas(12, 12), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(6, 6, 0, 6, 6, 6); + g.addColorStop(0, 'rgba(235,250,250,1)'); g.addColorStop(1, 'rgba(235,250,250,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, 12, 12); addCanvas(scene, 'di-drop', c); } + { const c = canvas(16, 16), ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(230,250,250,0.9)'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(8, 8, 6, 0, Math.PI * 2); ctx.stroke(); + ctx.fillStyle = 'rgba(255,255,255,0.8)'; ctx.beginPath(); ctx.arc(6, 6, 1.6, 0, Math.PI * 2); ctx.fill(); + addCanvas(scene, 'di-bubble', c); } + { const c = canvas(128, 128), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(64, 64, 0, 64, 64, 64); + g.addColorStop(0, 'rgba(255,240,200,0.9)'); g.addColorStop(0.4, 'rgba(255,220,150,0.35)'); g.addColorStop(1, 'rgba(255,220,150,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, 128, 128); addCanvas(scene, 'di-glow', c); } + { const c = canvas(128, 128), ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(230,250,250,0.9)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.ellipse(64, 64, 60, 60, 0, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'di-ring', c); } + { const c = canvas(16, 16), ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(8, 8, 0, 8, 8, 8); + g.addColorStop(0, 'rgba(255,250,220,1)'); g.addColorStop(0.3, 'rgba(255,215,120,0.8)'); g.addColorStop(1, 'rgba(255,200,80,0)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, 16, 16); addCanvas(scene, 'di-spark', c); } +} + +export let GAUGE_ART = null; + +export function bakeIslandArt(scene) { + if (scene.textures.exists('di-water') && GAUGE_ART) return; + bakeWater(scene); + bakeCloud(scene); + bakeSlab(scene); + bakeFoam(scene); + bakePlaque(scene); + bakeSeals(scene); + bakePawns(scene); + bakeBacks(scene); + bakeJournal(scene); + bakeStrip(scene); + bakeShelf(scene); + GAUGE_ART = bakeGauge(scene); + bakeParticles(scene); +} + +export { DISPLAY_FONT }; diff --git a/src/games/forbiddenisland/IslandChat.js b/src/games/forbiddenisland/IslandChat.js index e581cad..6fdaccc 100644 --- a/src/games/forbiddenisland/IslandChat.js +++ b/src/games/forbiddenisland/IslandChat.js @@ -1,14 +1,17 @@ -// Forbidden Island — team-chat phrase library. 100% offline string templates. +// The Drowning Isle — expedition chat. 100% offline string templates. // -// The heuristic planner (IslandAI.describeIntent) produces a rationale object; -// this turns it into a line of table talk in the speaking role's "voice". -// Game events (a tile sinking, Waters Rise!, a capture) get their own lines so -// the chat reads like a real co-op table. +// The planner (IslandAI.describeIntent) produces a rationale object; this turns +// it into a line of table talk in the speaking crew member's voice. Each role +// has a personality (ROLES[role].voice): the Bush Pilot is breezy, the Field +// Engineer gruff, the Wireless Operator crisp radio-speak, the Cartographer +// professorial, the Hard-Hat Diver laconic, the Mountaineer eager. Game events +// (a tile sinking, a Waters Rise, a capture) get their own lines so the journal +// reads like an expedition log. import { TREASURES, ROLES } from './IslandData.js'; const EMOJI = { - pilot: '✈️', engineer: '🔧', messenger: '✉️', navigator: '🧭', diver: '🤿', explorer: '🧗', + pilot: '✈️', engineer: '🔧', messenger: '📻', navigator: '🧭', diver: '🤿', explorer: '🧗', }; export function roleEmoji(role) { return EMOJI[role] ?? '🧩'; } @@ -16,98 +19,131 @@ export function roleName(role) { return ROLES[role]?.name ?? role; } export function roleColorHex(role) { return ROLES[role]?.colorHex ?? '#f2ead8'; } const pick = (arr) => arr[Math.floor(Math.random() * arr.length)]; -const tName = (key) => TREASURES[key]?.name ?? 'the treasure'; +const tName = (key) => TREASURES[key]?.name ?? 'the relic'; +const tShort = (key) => TREASURES[key]?.short ?? 'relic'; -// Little role-specific interjections, sprinkled in for character. +// Sign-offs and asides in each crew member's voice. const FLAVOR = { - pilot: ['Wings ready.', 'I can be anywhere in a heartbeat.', 'Just say the word.'], - engineer: ['Efficient as always.', 'On it.', 'Consider it done.'], - messenger: ['Happy to help.', 'Cards incoming.', "I've got the network."], - navigator: ['Follow my lead.', 'I’ll route us.', 'Stay coordinated.'], - diver: ['The water doesn’t scare me.', 'Going deep.', 'I’ll take the wet path.'], - explorer: ['I’ll take the diagonal.', 'Scouting ahead.', 'I see a way.'], + pilot: ['Wheels up whenever you are.', 'Lovely weather for it. Not.', 'I can be anywhere in a heartbeat.', 'Keep the dock dry, chums. That is our ride home.'], + engineer: ['Mind the timbers.', 'Right. Get on with it.', 'I have seen worse. Not much worse.', 'Everything floods. Question is when.'], + messenger: ['Over.', 'Signal is clear, over.', 'Standing by on all frequencies.', 'Copy all, over.'], + navigator: ['Fascinating, truly fascinating.', 'I have marked it in the survey.', 'Note the bearing, everyone.', 'The old maps did warn of this.'], + diver: ['Water is fine.', 'Seen deeper.', 'Mm.', 'I will go under if I have to.'], + explorer: ['There is always another way across!', 'Diagonal is my favourite direction.', 'What a place!', 'Onward!'], }; +// Openers by voice for the same plan, so six crew don't all sound alike. +const VOICE = { + breezy: { go: 'Hopping over to', hold: 'I will keep the kite in the air and', yes: 'Easy as you like:' }, + gruff: { go: 'Heading for', hold: 'Not much for me. I will', yes: 'Right:' }, + crisp: { go: 'Moving to', hold: 'No traffic for me, will', yes: 'Confirmed:' }, + professorial: { go: 'By my reckoning I should make for', hold: 'Nothing pressing in my survey, so I shall', yes: 'Splendid:' }, + laconic: { go: 'Going to', hold: 'Nothing for me. I will', yes: 'Done:' }, + eager: { go: 'Off to', hold: 'Nothing for me yet, so I will', yes: 'Here we go:' }, +}; +const voiceOf = (role) => VOICE[ROLES[role]?.voice] ?? VOICE.crisp; +const radio = (role, text) => (ROLES[role]?.voice === 'crisp' && !/over\.$/i.test(text) ? `${text} Over.` : text); + const INTENT = { - CAPTURE: (r) => pick([ - `I'm standing on the temple with a full set — claiming ${tName(r.treasure)} now!`, - `Four cards in hand and feet on the tile. ${tName(r.treasure)} is ours this turn.`, - `Securing ${tName(r.treasure)} — that's one less treasure to worry about.`, - ]), - SEEK: (r) => { - const base = pick([ - `I've got ${r.cards} card${r.cards === 1 ? '' : 's'} toward ${tName(r.treasure)} — pushing for its temple.`, - `Working on ${tName(r.treasure)}. Heading for the tile, ${r.cards}/4 so far.`, - `${tName(r.treasure)} is my project — making my way there.`, + CAPTURE: (r) => { + const v = voiceOf(r.role); + return pick([ + `${v.yes} I am standing on the shrine with four cards. Claiming ${tName(r.treasure)} now!`, + `Four cards and my boots on the tile. ${tName(r.treasure)} comes with us this turn.`, + `Securing ${tName(r.treasure)}. One less thing for the sea to take.`, ]); - if (r.request) return `${base} ${roleName(r.request.fromRole)}, if you're holding a matching card, send it my way?`; + }, + SEEK: (r) => { + const v = voiceOf(r.role); + const base = pick([ + `I hold ${r.cards} of the 4 cards for the ${tShort(r.treasure)}. ${v.go} its shrine.`, + `The ${tShort(r.treasure)} is my job: ${r.cards}/4 so far. ${v.go} the shrine.`, + `${v.go} the ${tShort(r.treasure)} shrine, ${r.cards} cards in hand.`, + ]); + if (r.request) return `${base} ${roleName(r.request.fromRole)}, if you have a matching card, send it my way?`; return base; }, - SHORE: (r) => pick([ - `Shoring up — we can't afford to lose ground here.`, - `Patching the flooding before it spreads. Watch the map.`, - `Holding the line on the flooded tiles near me.`, + GIVE: (r) => pick([ + `Pooling the ${tShort(r.treasure)} cards. Mine goes to whoever is carrying the set.`, + `Card hand-off this turn: ${tShort(r.treasure)} goes to our collector.`, + `One of us should hold every ${tShort(r.treasure)} card. Passing mine along.`, ]), + SHORE: (r) => { + const v = voiceOf(r.role); + return pick([ + `${v.yes} shoring up. We cannot lose ground here.`, + `Bracing the flooded tiles near me before the next swell.`, + `Holding the line on the wet ground around me.`, + ]); + }, ESCAPE: () => pick([ - `All four treasures are in. Regrouping at Fools' Landing — let's fly out together!`, - `Treasures secured! Everyone to the helipad, we need a Helicopter Lift.`, - `This is the home stretch — converging on Fools' Landing.`, - ]), - SUPPORT: () => pick([ - `Nothing urgent for me — repositioning to help where it counts.`, - `Holding steady and keeping my options open.`, - `I'll back up whoever needs it this turn.`, + `All four relics are in! Everyone to the Expedition Dock. We need a Helicopter Lift.`, + `That is the lot! Converge on the dock, and whoever holds the Helicopter Lift, keep it safe.`, + `Home stretch, everyone. Make for the Expedition Dock.`, ]), + SUPPORT: (r) => { + const v = voiceOf(r.role); + return pick([ + `${v.hold} move to where I will be useful.`, + `${v.hold} keep my options open.`, + `${v.hold} back up whoever needs it.`, + ]); + }, }; // A line announcing the AI partner's plan for the turn. export function lineForIntent(rationale) { const make = INTENT[rationale.intent] ?? INTENT.SUPPORT; let text = make(rationale); - // Occasionally append a threat warning. const t = rationale.threats?.[0]; if (t && Math.random() < 0.5) { text += ` ${pick([ - `Heads up — ${t.name} floods next, someone keep an eye on it.`, - `Also: ${t.name} is in danger. Don't let it sink.`, - `Watch ${t.name}, it's one flood from trouble.`, + `Heads up: ${t.name} could flood next. Someone watch it.`, + `Also, ${t.name} is in danger. Do not let it sink.`, + `Keep an eye on ${t.name}. It is one flood from trouble.`, ])}`; - } else if (Math.random() < 0.25) { - text += ` ${pick(FLAVOR[rationale.role] ?? [])}`; + } else if (Math.random() < 0.3) { + text += ` ${pick(FLAVOR[rationale.role] ?? [''])}`; } - return { role: rationale.role, text }; + return { role: rationale.role, text: radio(rationale.role, text) }; } // Lines for notable game events. `ctx` carries the names already resolved. export function lineForEvent(kind, ctx = {}) { + const say = (arr) => radio(ctx.role, pick(arr)); switch (kind) { case 'sink': return { role: ctx.role ?? null, text: pick([ - `${ctx.tileName} just sank beneath the waves.`, - `We lost ${ctx.tileName} — it's gone for good.`, + `${ctx.tileName} slid beneath the waves.`, + `${ctx.tileName} is gone. The sea has it now.`, + `We have lost ${ctx.tileName}.`, ]) }; case 'watersRise': return { role: ctx.role ?? null, text: pick([ - `Waters Rise! The flood is accelerating — water level ${ctx.waterLevel}.`, - `That's a Waters Rise card. Everything we flooded is coming back around.`, + `The Waters Rise! The gauge reads ${ctx.waterLevel}, and every flooded tile goes back on top of the flood deck.`, + `Waters Rise. The tide climbs to ${ctx.waterLevel}, and the tiles we saw flood are coming round again.`, ]) }; - case 'capture': return { role: ctx.role, text: pick([ - `Got it! ${tName(ctx.treasure)} is secured. ${4 - (ctx.remaining ?? 0)} of 4 down.`, - `${tName(ctx.treasure)} claimed — great teamwork.`, + case 'capture': return { role: ctx.role, text: say([ + `Got it! ${tName(ctx.treasure)} is ours. ${4 - (ctx.remaining ?? 0)} of 4 relics recovered.`, + `${tName(ctx.treasure)} is in the crate. Lovely work, everyone.`, ]) }; - case 'sandbags': return { role: ctx.role, text: pick([ - `Dropping sandbags on ${ctx.tileName} — that holds the line, no action spent.`, - `Sandbags out on ${ctx.tileName}. We can't lose that one.`, + case 'sandbags': return { role: ctx.role, text: say([ + `Sandbags down on ${ctx.tileName}. That holds it, and it costs no action.`, + `Sandbagging ${ctx.tileName}. We cannot lose that one.`, ]) }; - case 'heliMove': return { role: ctx.role, text: pick([ - `Helicopter lift — flying ${ctx.who} straight to ${ctx.tileName} for the capture.`, - `Burning a Helicopter to get ${ctx.who} onto ${ctx.tileName} before it's too late.`, + case 'heliMove': return { role: ctx.role, text: say([ + `Helicopter Lift: flying ${ctx.who} straight to ${ctx.tileName}.`, + `Calling in a Helicopter Lift to get ${ctx.who} onto ${ctx.tileName}.`, ]) }; - case 'swim': return { role: ctx.role, text: pick([ - `Tile sank under me — swimming to safety.`, - `Had to bail to ${ctx.tileName} as the ground gave way.`, + case 'give': return { role: ctx.role, text: say([ + `Passing a ${tShort(ctx.card?.slice(9))} card to ${ctx.to}.`, + `${ctx.to}, here: one more for the ${tShort(ctx.card?.slice(9))}.`, + ]) }; + case 'swim': return { role: ctx.role, text: say([ + `The ground went out from under me. Swimming to ${ctx.tileName}.`, + `Had to swim for ${ctx.tileName} as the tile sank.`, ]) }; case 'won': return { role: null, text: pick([ - `We made it off the island — together! 🎉`, - `Helicopter's airborne with all four treasures. We win!`, + `The helicopter lifts off the Expedition Dock with all four relics aboard. The expedition is saved!`, + `Rotors turning, crates lashed down. We made it off the island, together.`, ]) }; case 'lost': return { role: null, text: ctx.reason ?? 'The island is lost.' }; default: return null; @@ -116,9 +152,14 @@ export function lineForEvent(kind, ctx = {}) { // Acknowledgement when the human sets a strategy priority. export function lineForAck(role, label) { - return { role, text: pick([ - `Copy that — ${label}.`, - `Understood. Re-planning around: ${label}.`, - `Roger. Prioritizing ${label}.`, - ]) }; + return { role, text: radio(role, pick([ + `Understood: ${label}.`, + `Re-planning around: ${label}.`, + `Right. Prioritising ${label}.`, + ])) }; +} + +// Journal heading for each new round, e.g. "Day 3 · Gauge 4". +export function journalStamp(round, level) { + return `Day ${round} · Gauge ${level}`; } diff --git a/src/games/forbiddenisland/IslandCinematics.js b/src/games/forbiddenisland/IslandCinematics.js new file mode 100644 index 0000000..318ce91 --- /dev/null +++ b/src/games/forbiddenisland/IslandCinematics.js @@ -0,0 +1,224 @@ +// The Drowning Isle: the big moments, staged over the island. +// +// watersRise(scene) a wave sweeps the island under a caption +// capture(scene, key, from, who, to, done) the relic painting rises from its +// shrine in a burst of light, then files +// itself in the journal's relic tracker +// escape(scene, dock, done) a helicopter drops onto the dock, the crew +// climbs in, and it lifts off as the +// island sinks behind it +// loss(scene, gs, done) a short scene for each way to lose +// +// Every function is skippable in spirit: the game state has already been +// decided, and `done` fires when the camera can move on. + +import * as Phaser from 'phaser'; +import { W, H, DEPTH, BX0, BY0, BOARD_W, TILE, DISPLAY_FONT, BODY_FONT, TYPE_FONT, RAIL_X } from './IslandLayout.js'; +import { TREASURES, cardFrame } from './IslandData.js'; +import * as Sound from './IslandSound.js'; + +const CX = BX0 + BOARD_W / 2, CY = BY0 + BOARD_W / 2; + +// A torn strip of journal paper across the island with a headline. +export function caption(scene, title, sub = '', { y = CY, hold = 1600, color = '#2b1d08' } = {}) { + const t = scene.add.text(0, -8, title, { fontFamily: DISPLAY_FONT, fontSize: '44px', color }).setOrigin(0.5); + const st = sub ? scene.add.text(0, 30, sub, { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '19px', color: '#5a4a35' }).setOrigin(0.5) : null; + const w = Math.max(t.width, st?.width ?? 0) + 90, h = sub ? 110 : 80; + const g = scene.add.graphics(); + g.fillStyle(0x000000, 0.35); g.fillRect(-w / 2 + 5, -h / 2 - 4 + 6, w, h); + g.fillStyle(0xe9dcc0, 1); + g.beginPath(); g.moveTo(-w / 2, -h / 2 - 4); + for (let x = -w / 2; x <= w / 2; x += 18) g.lineTo(x, -h / 2 - 4 + (Math.random() * 5)); + g.lineTo(w / 2, h / 2 - 4); + for (let x = w / 2; x >= -w / 2; x -= 18) g.lineTo(x, h / 2 - 4 - (Math.random() * 5)); + g.closePath(); g.fillPath(); + const c = scene.add.container(CX, y, st ? [g, t, st] : [g, t]).setDepth(DEPTH.banner - 5).setAngle(-2).setAlpha(0).setScale(1.15); + scene.tweens.add({ targets: c, alpha: 1, scale: 1, duration: 260, ease: 'Back.easeOut' }); + scene.tweens.add({ targets: c, alpha: 0, y: y - 20, delay: hold, duration: 400, onComplete: () => c.destroy() }); + return c; +} + +export function watersRise(scene) { + Sound.watersRise(scene); + caption(scene, 'The Waters Rise', 'Every flooded tile goes back on top of the flood deck', { hold: 1500, color: '#1f4a66' }); + // A wave front rolling across the island. + const wave = scene.add.tileSprite(BX0 - 340, BY0 - 30, 300, BOARD_W + 60, 'di-water').setOrigin(0) + .setDepth(DEPTH.tileFx + 2).setAlpha(0.5).setTint(0xbfe8f0); + const foam = scene.add.image(BX0 - 40, CY, 'di-glow').setDepth(DEPTH.tileFx + 3).setDisplaySize(90, BOARD_W + 80) + .setTint(0xffffff).setAlpha(0.6).setBlendMode(Phaser.BlendModes.ADD); + scene.tweens.add({ + targets: [wave, foam], x: `+=${BOARD_W + 420}`, duration: 1500, ease: 'Sine.easeInOut', + onUpdate: () => { wave.tilePositionY += 3; }, + onComplete: () => { wave.destroy(); foam.destroy(); }, + }); + scene.cameras.main.shake(500, 0.004); +} + +export function capture(scene, key, from, who, to, done = () => {}) { + Sound.capture(scene); + const objs = []; + const dim = scene.add.rectangle(0, 0, RAIL_X - 30, H, 0x05101a, 0).setOrigin(0).setDepth(DEPTH.popup); + objs.push(dim); + scene.tweens.add({ targets: dim, fillAlpha: 0.6, duration: 400 }); + // turning rays + const rays = scene.add.graphics().setPosition(CX, CY - 20).setDepth(DEPTH.popup + 1).setAlpha(0).setBlendMode(Phaser.BlendModes.ADD); + const col = TREASURES[key].color; + for (let i = 0; i < 16; i++) { + const a = (i / 16) * Math.PI * 2; + rays.fillStyle(i % 2 ? col : 0xffe7a8, 0.35); + rays.fillTriangle(0, 0, Math.cos(a - 0.09) * 420, Math.sin(a - 0.09) * 420, Math.cos(a + 0.09) * 420, Math.sin(a + 0.09) * 420); + } + objs.push(rays); + scene.tweens.add({ targets: rays, alpha: 1, duration: 500, delay: 200 }); + scene.tweens.add({ targets: rays, angle: 40, duration: 3000 }); + const glow = scene.add.image(CX, CY - 20, 'di-glow').setDepth(DEPTH.popup + 1).setDisplaySize(520, 520).setTint(col).setAlpha(0).setBlendMode(Phaser.BlendModes.ADD); + objs.push(glow); + scene.tweens.add({ targets: glow, alpha: 0.9, duration: 600, delay: 200 }); + let art; + if (scene.textures.exists('forbiddenisland-cards')) { + art = scene.add.image(from.x, from.y, 'forbiddenisland-cards', cardFrame(`treasure:${key}`)).setDisplaySize(40, 52); + } else { + art = scene.add.circle(from.x, from.y, 20, col); + } + art.setDepth(DEPTH.popup + 2); + const big = { w: 240, h: 315 }; + scene.tweens.add({ targets: art, x: CX, y: CY - 20, displayWidth: big.w, displayHeight: big.h, duration: 900, ease: 'Cubic.easeOut' }); + const sparks = scene.add.particles(CX, CY - 20, 'di-spark', { + speed: { min: 80, max: 340 }, lifespan: 1200, scale: { start: 1.4, end: 0 }, alpha: { start: 1, end: 0 }, + blendMode: 'ADD', emitting: false, + }).setDepth(DEPTH.popup + 3); + objs.push(sparks); + scene.time.delayedCall(850, () => sparks.explode(70)); + const title = scene.add.text(CX, CY + 175, TREASURES[key].name, { fontFamily: DISPLAY_FONT, fontSize: '40px', color: '#f0d58c' }) + .setOrigin(0.5).setDepth(DEPTH.popup + 3).setAlpha(0).setShadow(0, 3, '#000', 8); + const sub = scene.add.text(CX, CY + 220, `recovered by ${who}`, { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '20px', color: '#f2e6cc' }) + .setOrigin(0.5).setDepth(DEPTH.popup + 3).setAlpha(0); + objs.push(title, sub); + scene.tweens.add({ targets: [title, sub], alpha: 1, duration: 400, delay: 900 }); + scene.time.delayedCall(2700, () => { + scene.tweens.add({ targets: [dim], fillAlpha: 0, duration: 450 }); + scene.tweens.add({ targets: [rays, glow, title, sub], alpha: 0, duration: 400 }); + scene.tweens.add({ + targets: art, x: to.x, y: to.y, displayWidth: 40, displayHeight: 52, duration: 650, ease: 'Cubic.easeIn', + onComplete: () => { art.destroy(); objs.forEach((o) => o.destroy()); done(); }, + }); + }); +} + +// An original little expedition helicopter, drawn in a container. +function makeHelicopter(scene) { + const g = scene.add.graphics(); + g.fillStyle(0x000000, 0.0); + // tail boom + fin + g.fillStyle(0x4a5a3a, 1); g.fillRect(30, -10, 90, 9); + g.fillTriangle(112, -10, 128, -34, 126, -6); + // body + g.fillStyle(0x5d6e44, 1); g.fillEllipse(0, 0, 100, 52); + g.fillStyle(0x3d4a2c, 1); g.fillRect(-30, 12, 70, 8); + // cockpit glass + g.fillStyle(0x9fd3e0, 0.85); g.fillEllipse(-26, -6, 42, 32); + g.fillStyle(0xffffff, 0.35); g.fillEllipse(-32, -12, 14, 8); + // stencil and skids + g.fillStyle(0xe9dcc0, 1); g.fillRect(8, -6, 26, 3); + g.lineStyle(3, 0x2a2a22, 1); + g.lineBetween(-40, 36, 40, 36); g.lineBetween(-24, 22, -26, 36); g.lineBetween(22, 22, 24, 36); + g.lineBetween(-40, 36, -46, 31); + // mast + g.fillStyle(0x2a2a22, 1); g.fillRect(-4, -34, 8, 10); + const rotor = scene.add.ellipse(0, -36, 230, 10, 0x1a1a14, 0.45); + const tail = scene.add.ellipse(126, -20, 6, 30, 0x1a1a14, 0.45); + const shadow = scene.add.ellipse(0, 0, 120, 26, 0x000000, 0.35); + const body = scene.add.container(0, 0, [g, rotor, tail]); + const c = scene.add.container(0, 0, [body]).setDepth(DEPTH.rain - 2); + c.rotor = rotor; c.tail = tail; c.body = body; c.shadow = shadow; + shadow.setDepth(DEPTH.tileFx + 2); + const spin = scene.tweens.add({ targets: rotor, scaleX: { from: 1, to: 0.15 }, duration: 60, yoyo: true, repeat: -1 }); + const spin2 = scene.tweens.add({ targets: tail, scaleY: { from: 1, to: 0.2 }, duration: 45, yoyo: true, repeat: -1 }); + c.stopRotor = () => { spin.stop(); spin2.stop(); }; + return c; +} + +export function escape(scene, dock, done = () => {}) { + Sound.rotor(scene, 6); + const heli = makeHelicopter(scene); + heli.setPosition(-200, dock.y - 260).setScale(0.8); + heli.shadow.setPosition(-200, dock.y + 30); + const hover = { y: dock.y - 70 }; + scene.tweens.add({ targets: heli, x: dock.x, y: hover.y, scale: 1, duration: 1800, ease: 'Cubic.easeOut' }); + scene.tweens.add({ targets: heli.shadow, x: dock.x, duration: 1800, ease: 'Cubic.easeOut' }); + scene.tweens.add({ targets: heli.body, angle: { from: -4, to: 4 }, duration: 700, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + // the crew climbs aboard + scene.time.delayedCall(1900, () => { + const figs = Object.values(scene.figures ?? {}); + figs.forEach((f, i) => { + scene.tweens.add({ targets: f.container, x: dock.x, y: hover.y + 10, alpha: 0, scale: 0.6, duration: 600, delay: i * 220, ease: 'Cubic.easeIn' }); + }); + }); + // the island goes under behind them, furthest tiles first + scene.time.delayedCall(2600, () => { + const views = Object.values(scene.tileViews ?? {}).filter((v) => v.state !== 'sunk'); + views.sort((a, b) => Math.hypot(b.x - dock.x, b.y - dock.y) - Math.hypot(a.x - dock.x, a.y - dock.y)); + views.forEach((v, i) => scene.time.delayedCall(i * 90, () => v.sink())); + Sound.sink(scene); + }); + scene.time.delayedCall(3100, () => { + scene.tweens.add({ targets: heli, x: RAIL_X + 120, y: -160, scale: 0.55, duration: 2400, ease: 'Cubic.easeIn' }); + scene.tweens.add({ targets: heli.shadow, alpha: 0, duration: 900 }); + caption(scene, 'Lift-off', 'All four relics aboard, and the whole crew with them', { y: BY0 + BOARD_W - 80, hold: 2200 }); + }); + scene.time.delayedCall(5600, () => { heli.stopRotor(); heli.destroy(); heli.shadow.destroy(); done(); }); +} + +export function loss(scene, gs, done = () => {}) { + const kind = gs.lossKind ?? 'gauge'; + scene.storm?.strike({ bright: 0.75 }); + scene.cameras.main.shake(600, 0.006); + const views = Object.values(scene.tileViews ?? {}); + if (kind === 'gauge') { + watersRise(scene); + const rest = views.filter((v) => v.state !== 'sunk').sort((a, b) => a.x - b.x); + rest.forEach((v, i) => scene.time.delayedCall(500 + i * 70, () => v.sink())); + scene.time.delayedCall(2200, () => caption(scene, 'Swallowed by the Sea', 'The tide gauge reached the drowned mark', { hold: 1600, color: '#8e2a1e' })); + scene.time.delayedCall(4200, done); + return; + } + if (kind === 'relic' && gs.lossTreasure && scene.textures.exists('forbiddenisland-cards')) { + const art = scene.add.image(CX, CY - 30, 'forbiddenisland-cards', cardFrame(`treasure:${gs.lossTreasure}`)) + .setDisplaySize(200, 262).setDepth(DEPTH.popup + 2).setAlpha(0); + const crack = scene.add.graphics().setDepth(DEPTH.popup + 3).setPosition(CX, CY - 30); + scene.tweens.add({ targets: art, alpha: 1, duration: 400 }); + scene.time.delayedCall(700, () => { + crack.lineStyle(4, 0x1a110a, 1); + crack.beginPath(); crack.moveTo(-10, -131); + [[8, -80], [-14, -30], [12, 10], [-6, 60], [10, 131]].forEach(([x, y]) => crack.lineTo(x, y)); + crack.strokePath(); + art.setTint(0x777777); + Sound.sink(scene); + }); + scene.time.delayedCall(1300, () => { + scene.tweens.add({ targets: [art, crack], y: '+=260', alpha: 0, angle: 12, duration: 1100, ease: 'Cubic.easeIn' }); + caption(scene, 'A Relic Is Lost', `${TREASURES[gs.lossTreasure].name} sank with both of its shrines`, { hold: 1600, color: '#8e2a1e' }); + }); + scene.time.delayedCall(3600, () => { art.destroy(); crack.destroy(); done(); }); + return; + } + if (kind === 'crew' && gs.lossSeat != null && scene.figures?.[gs.lossSeat]) { + const f = scene.figures[gs.lossSeat]; + scene.sea?.bubbles(f.container.x, f.container.y - 10, 30, 20); + scene.tweens.add({ targets: f.container, y: f.container.y + 30, alpha: 0, duration: 1600, ease: 'Cubic.easeIn' }); + Sound.sink(scene); + caption(scene, 'Lost Beneath the Waves', 'There was no dry ground left to swim to', { hold: 1800, color: '#8e2a1e' }); + scene.time.delayedCall(2800, done); + return; + } + // the dock + const dock = scene.tileViews?.['fools-landing']; + if (dock) { + scene.sea?.ripple(dock.x, dock.y, { size: TILE * 3, duration: 1800 }); + scene.sea?.ripple(dock.x, dock.y, { size: TILE * 2, duration: 1500, delay: 300 }); + } + caption(scene, 'The Dock Is Gone', 'No helicopter can land on open water', { hold: 1800, color: '#8e2a1e' }); + scene.time.delayedCall(2800, done); +} + +export { TYPE_FONT, W }; diff --git a/src/games/forbiddenisland/IslandData.js b/src/games/forbiddenisland/IslandData.js index e14c764..8530a4f 100644 --- a/src/games/forbiddenisland/IslandData.js +++ b/src/games/forbiddenisland/IslandData.js @@ -1,4 +1,4 @@ -// Forbidden Island — static data. No Phaser, no game state here: just the board +// The Drowning Isle — static data. No Phaser, no game state here: just the board // silhouette, the tile/treasure/role catalog, and deck composition. Everything // dynamic lives in IslandLogic.js. @@ -28,63 +28,91 @@ export function isCell(r, c) { return CELLS.some(([cr, cc]) => cr === r && cc === c); } +// Island shapes. Each is 24 cells inside the 6×6 grid; '#' is land. The tiles +// are dealt onto the cells at random, so every shape plays differently: the +// Atoll has a lagoon in the middle that nobody can cross on foot, Hook Bay +// bends the island round a bay, and the Serpent is long and thin. +const SHAPES = { + diamond: { name: 'The Diamond', blurb: 'The classic island: compact, with short walks between shrines.', + rows: ['..##..', '.####.', '######', '######', '.####.', '..##..'] }, + atoll: { name: 'The Atoll', blurb: 'A ring of land round a lagoon. The middle is open water from the start.', + rows: ['..##..', '######', '##..##', '##..##', '######', '..##..'] }, + hook: { name: 'Hook Bay', blurb: 'An island bent round a deep bay. The two arms are far apart by land.', + rows: ['####..', '#####.', '...###', '...###', '#####.', '####..'] }, + serpent: { name: 'The Serpent', blurb: 'A long diagonal ridge. Easy to cut in two as the sea comes in.', + rows: ['###...', '####..', '#####.', '.#####', '..####', '...###'] }, +}; + +export const LAYOUTS = Object.fromEntries(Object.entries(SHAPES).map(([key, v]) => { + const cells = []; + v.rows.forEach((row, r) => [...row].forEach((ch, c) => { if (ch === '#') cells.push([r, c]); })); + return [key, { key, name: v.name, blurb: v.blurb, cells }]; +})); +export const LAYOUT_KEYS = Object.keys(LAYOUTS); + // Treasures, each tied to two island tiles. `element` keys the treasure cards. export const TREASURES = { - earth: { key: 'earth', name: 'The Earth Stone', tiles: ['temple-moon', 'temple-sun'], color: 0x8d6e3c }, - wind: { key: 'wind', name: 'The Statue of the Wind', tiles: ['whispering-garden', 'howling-garden'], color: 0x9aa7b0 }, - fire: { key: 'fire', name: 'The Crystal of Fire', tiles: ['cave-embers', 'cave-shadows'], color: 0xc0492f }, - ocean: { key: 'ocean', name: "The Ocean's Chalice", tiles: ['coral-palace', 'tidal-palace'], color: 0x2f7fb0 }, + earth: { key: 'earth', name: 'The Hollow Orb', short: 'Hollow Orb', tiles: ['temple-moon', 'temple-sun'], color: 0xa8875a }, + wind: { key: 'wind', name: 'The Gale Gryphon', short: 'Gale Gryphon', tiles: ['whispering-garden', 'howling-garden'], color: 0x8fa0ae }, + fire: { key: 'fire', name: 'The Ember Heart', short: 'Ember Heart', tiles: ['cave-embers', 'cave-shadows'], color: 0xc8432c }, + ocean: { key: 'ocean', name: "The Tidewarden's Chalice", short: 'Tide Chalice', tiles: ['coral-palace', 'tidal-palace'], color: 0x3d8cc4 }, }; export const TREASURE_KEYS = ['earth', 'wind', 'fire', 'ocean']; // All 24 tiles. `treasure` links a tile to a treasure; `landing` marks the -// helipad you must escape from. The rest are neutral. +// dock you must escape from (its painting shows the jetty). The rest are neutral. export const TILES = [ - { id: 'temple-moon', name: 'Temple of the Moon', treasure: 'earth' }, - { id: 'temple-sun', name: 'Temple of the Sun', treasure: 'earth' }, - { id: 'whispering-garden', name: 'Whispering Garden', treasure: 'wind' }, - { id: 'howling-garden', name: 'Howling Garden', treasure: 'wind' }, - { id: 'cave-embers', name: 'Cave of Embers', treasure: 'fire' }, - { id: 'cave-shadows', name: 'Cave of Shadows', treasure: 'fire' }, - { id: 'coral-palace', name: 'Coral Palace', treasure: 'ocean' }, - { id: 'tidal-palace', name: 'Tidal Palace', treasure: 'ocean' }, - { id: 'fools-landing', name: "Fools' Landing", landing: true }, - { id: 'bronze-gate', name: 'Bronze Gate' }, - { id: 'copper-gate', name: 'Copper Gate' }, - { id: 'silver-gate', name: 'Silver Gate' }, - { id: 'gold-gate', name: 'Gold Gate' }, - { id: 'iron-gate', name: 'Iron Gate' }, - { id: 'watchtower', name: 'Watchtower' }, - { id: 'observatory', name: 'Observatory' }, - { id: 'phantom-rock', name: 'Phantom Rock' }, - { id: 'misty-marsh', name: 'Misty Marsh' }, - { id: 'breakers-bridge', name: 'Breakers Bridge' }, - { id: 'crimson-forest', name: 'Crimson Forest' }, - { id: 'dunes-deception', name: 'Dunes of Deception' }, - { id: 'lost-lagoon', name: 'Lost Lagoon' }, - { id: 'twilight-hollow', name: 'Twilight Hollow' }, - { id: 'cliffs-abandon', name: 'Cliffs of Abandon' }, + { id: 'temple-moon', name: 'Moonwell Sanctum', treasure: 'earth' }, + { id: 'temple-sun', name: 'Sunspire Shrine', treasure: 'earth' }, + { id: 'whispering-garden', name: 'The Verdant Nave', treasure: 'wind' }, + { id: 'howling-garden', name: 'Hollow of the Grey Wolf', treasure: 'wind' }, + { id: 'cave-embers', name: 'Kiln of the Horned One', treasure: 'fire' }, + { id: 'cave-shadows', name: 'Gloamwyrm Grotto', treasure: 'fire' }, + { id: 'coral-palace', name: 'Coral Basilica', treasure: 'ocean' }, + { id: 'tidal-palace', name: 'Stormbreak Citadel', treasure: 'ocean' }, + { id: 'fools-landing', name: 'Expedition Dock', landing: true }, + { id: 'bronze-gate', name: 'The Brazen Door' }, + { id: 'copper-gate', name: 'Dragonseal Door' }, + { id: 'silver-gate', name: 'Rimefrost Door' }, + { id: 'gold-gate', name: 'Aurelian Door' }, + { id: 'iron-gate', name: 'Gargoyle Gate' }, + { id: 'watchtower', name: 'Lantern Keep' }, + { id: 'observatory', name: "Stargazer's Dome" }, + { id: 'phantom-rock', name: 'The Black Needle' }, + { id: 'misty-marsh', name: 'Fogwater Fen' }, + { id: 'breakers-bridge', name: 'Drowned Causeway' }, + { id: 'crimson-forest', name: 'Bloodleaf Wood' }, + { id: 'dunes-deception', name: 'Mirage Dunes' }, + { id: 'lost-lagoon', name: 'Glimmerwater Lagoon' }, + { id: 'twilight-hollow', name: 'Dusk Harbour' }, + { id: 'cliffs-abandon', name: "Widow's Crags" }, ]; // The six adventurer roles. `power` is read by the engine/AI to branch special // abilities; `color` is the pawn colour. export const ROLES = { - pilot: { key: 'pilot', name: 'Pilot', color: 0x4a90d9, colorHex: '#4a90d9', power: 'Once per turn, fly to any tile.', - description: 'A fearless aviator who has logged more hours above the clouds than on solid ground. When the island is too treacherous to cross on foot, the Pilot takes to the skies — once per turn they may spend one action to fly directly to any tile on the island, no matter how far.' }, - engineer: { key: 'engineer', name: 'Engineer', color: 0xd0473a, colorHex: '#d0473a', power: 'Shore up two tiles for one action.', - description: 'A meticulous builder who arrived on the island with nothing but a toolkit and a plan. While others spend two actions to shore up two separate tiles, the Engineer patches them both in a single action — efficiency born of hard-won experience.' }, - messenger: { key: 'messenger', name: 'Messenger', color: 0xb9bfc6, colorHex: '#b9bfc6', power: 'Give Treasure cards to anyone, any distance.', - description: 'A seasoned courier who has crossed every terrain imaginable to deliver what matters most. Unlike other adventurers who must stand side-by-side to exchange cards, the Messenger can hand off Treasure cards to any teammate — regardless of where they are on the island.' }, - navigator: { key: 'navigator', name: 'Navigator', color: 0xe2b53c, colorHex: '#e2b53c', power: 'Move another adventurer up to 2 tiles.', - description: 'A brilliant strategist who can read the island like a map. The Navigator does not just chart their own path — each turn they can spend actions to move another adventurer up to two tiles, positioning teammates exactly where the team needs them most.' }, - diver: { key: 'diver', name: 'Diver', color: 0x2b2b30, colorHex: '#2b2b30', power: 'Swim through flooded and missing tiles.', - description: 'A deep-sea explorer who is equally at home beneath the surface as above it. Where the rising waters block every other adventurer, the Diver simply slips beneath the waves — swimming through flooded and even completely sunken tiles without a second thought.' }, - explorer: { key: 'explorer', name: 'Explorer', color: 0x49a25a, colorHex: '#49a25a', power: 'Move and shore up diagonally.', - description: 'A nimble trailblazer who has mapped uncharted territory on six continents. The Explorer refuses to be boxed in — while others are limited to the four cardinal directions, this adventurer can move and shore up tiles diagonally, opening paths no one else can take.' }, + pilot: { key: 'pilot', name: 'Bush Pilot', short: 'Pilot', color: 0x4a86c8, colorHex: '#5b97d6', power: 'Once per turn, fly to any tile.', + voice: 'breezy', motto: 'If it has wings, I can land it. Mostly.', + description: 'Flew mail runs over three jungles before the expedition hired the seaplane, and the pilot with it. When the causeways drown, the Bush Pilot simply takes to the air: once per turn, one action carries them to any tile on the island, no matter how far.' }, + engineer: { key: 'engineer', name: 'Field Engineer', short: 'Engineer', color: 0xc4473a, colorHex: '#d65a4c', power: 'Shore up two tiles for one action.', + voice: 'gruff', motto: 'Sandbag, timber, rope. In that order.', + description: 'Built bridges for the railway company until the railway company ran out of money. Where anyone else spends two actions shoring up two tiles, the Field Engineer braces both with a single action, with timber, rope and a great deal of muttering.' }, + messenger: { key: 'messenger', name: 'Wireless Operator', short: 'Wireless', color: 0xb9bfc6, colorHex: '#c3c9d0', power: 'Give Treasure cards to anyone, any distance.', + voice: 'crisp', motto: 'Stand by, transmitting.', + description: 'Hauls a field radio set nobody else could lift and keeps every party on the island in contact. Other crew must stand on the same tile to hand over a Treasure card; the Wireless Operator can send one to any teammate, wherever they are.' }, + navigator: { key: 'navigator', name: 'Cartographer', short: 'Cartographer', color: 0xd9a93a, colorHex: '#e2b53c', power: 'Move another adventurer up to 2 tiles.', + voice: 'professorial', motto: 'The map is never wrong. The island, occasionally.', + description: 'A professor of surveying who has charted every ruin the expedition found, usually from a safe distance. The Cartographer reads the island like a ledger, and for one action can direct another crew member up to two tiles along the best route.' }, + diver: { key: 'diver', name: 'Hard-Hat Diver', short: 'Diver', color: 0x3a3d44, colorHex: '#8d96a3', power: 'Swim through flooded and missing tiles.', + voice: 'laconic', motto: 'Water is just a slower kind of air.', + description: 'Salvaged wrecks in the Coral Sea in a brass helmet and lead boots. Where rising water stops everyone else, the Hard-Hat Diver walks straight through it, crossing flooded and even sunken tiles in a single move.' }, + explorer: { key: 'explorer', name: 'Mountaineer', short: 'Mountaineer', color: 0x4f9a5a, colorHex: '#5fb06a', power: 'Move and shore up diagonally.', + voice: 'eager', motto: 'There is always another way up. Or across.', + description: 'Has climbed on four continents and refuses to be told a route is impassable. The Mountaineer moves and shores up diagonally as well as straight, opening paths the rest of the crew cannot take.' }, }; -export const ROLE_KEYS = ['pilot', 'engineer', 'navigator', 'diver', 'explorer']; +export const ROLE_KEYS = ['pilot', 'engineer', 'messenger', 'navigator', 'diver', 'explorer']; // Special (non-treasure) Treasure-deck cards. export const SPECIAL = { @@ -105,7 +133,7 @@ export function buildTreasureDeck() { } // Water-level track. Index = level (1..10); value = flood cards drawn per turn. -// Level 10 is the skull: reaching it loses the game. +// Level 10 is the drowned mark: reaching it loses the game. export const WATER_TRACK = [null, 2, 2, 3, 3, 3, 4, 4, 5, 5, 'skull']; export const MAX_WATER = 10; @@ -152,3 +180,7 @@ export const CARD_FRAME = { export function cardFrame(card) { return CARD_FRAME[card] ?? null; } + +// Shown in the title, the begin screen and the journal. +export const GAME_TITLE = 'The Drowning Isle'; +export const LANDING_ID = 'fools-landing'; diff --git a/src/games/forbiddenisland/IslandDialogs.js b/src/games/forbiddenisland/IslandDialogs.js new file mode 100644 index 0000000..24735bd --- /dev/null +++ b/src/games/forbiddenisland/IslandDialogs.js @@ -0,0 +1,138 @@ +// The Drowning Isle: the expedition briefing (the pre-game dialog). Pick the +// island's shape, a standard or the daily expedition, and your crew role, or +// resume a saved expedition. Calls onStart({ layout, daily, role, resume }). + +import { Button } from '../../ui/Button.js'; +import { LAYOUTS, LAYOUT_KEYS, ROLES, ROLE_KEYS, DIFFICULTY, GAME_TITLE } from './IslandData.js'; +import { W, H, DEPTH, DISPLAY_FONT, BODY_FONT, TYPE_FONT, INK } from './IslandLayout.js'; +import { bakeLeather } from './IslandArt.js'; +import { readRecord, dailySetup, todayKey } from './IslandStore.js'; +import * as Sound from './IslandSound.js'; + +const BRASS = { bg: 0x5a3f1a, bgHover: 0xd8b25a, textColor: '#f2e6cc', textHoverColor: '#2b1d08' }; + +function shapePreview(scene, x, y, key, cell = 9) { + const g = scene.add.graphics(); + const cells = key === 'random' ? null : LAYOUTS[key].cells; + g.fillStyle(0x0d3a46, 1); g.fillRoundedRect(x - 3.2 * cell, y - 3.2 * cell, 6.4 * cell, 6.4 * cell, 5); + if (!cells) { + const t = scene.add.text(x, y, '?', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: '#d8b25a' }).setOrigin(0.5); + return [g, t]; + } + g.fillStyle(0xd8b25a, 1); + for (const [r, c] of cells) g.fillRect(x + (c - 3) * cell + 1, y + (r - 3) * cell + 1, cell - 2, cell - 2); + return [g]; +} + +export function showBriefing(scene, { difficulty, playerCount, saved, onStart }) { + const cx = W / 2, cy = H / 2, pw = 1120, ph = 780; + const root = scene.add.container(0, 0).setDepth(DEPTH.popup + 1); + const add = (o) => { root.add(o); return o; }; + const dim = add(scene.add.rectangle(0, 0, W, H, 0x020a10, 0.72).setOrigin(0).setInteractive()); + void dim; + add(scene.add.image(cx, cy, bakeLeather(scene, pw, ph))); + const top = cy - ph / 2; + add(scene.add.text(cx, top + 62, GAME_TITLE, { fontFamily: DISPLAY_FONT, fontSize: '56px', color: INK.brassHex }).setOrigin(0.5).setShadow(0, 3, '#000', 6)); + add(scene.add.text(cx, top + 112, 'Monsoon season. Somewhere past the edge of the charts.', { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '20px', color: INK.cream, + }).setOrigin(0.5)); + add(scene.add.text(cx, top + 150, + 'Recover the four relics from their shrines, then the whole crew meets at the Expedition Dock for a Helicopter Lift.', { + fontFamily: BODY_FONT, fontSize: '17px', color: '#e2d3b0', align: 'center', wordWrap: { width: pw - 160 }, + }).setOrigin(0.5)); + + const sel = { layout: 'diamond', daily: false, role: 'random' }; + const daily = dailySetup(); + const rec = readRecord(); + const todays = rec.daily[todayKey()]; + + const label = (x, y, text) => add(scene.add.text(x, y, text, { fontFamily: TYPE_FONT, fontSize: '15px', fontStyle: 'bold', color: '#cdb994' })); + const left = cx - pw / 2 + 70; + + // ── expedition type ───────────────────────────────────────────────────────── + label(left, top + 190, 'EXPEDITION'); + const typeBtns = []; + const typeOpts = [ + { key: false, title: 'Standard', note: 'A fresh island every time.' }, + { key: true, title: `Daily · ${daily.key}`, note: todays ? `Today: ${todays.won ? `escaped on day ${todays.days}` : `${todays.relics}/4 relics`}. Play again to beat it.` : 'Same island, crew and storm for everyone today.' }, + ]; + typeOpts.forEach((o, i) => { + const x = left + i * 500, y = top + 218; + const g = add(scene.add.graphics()); + const t = add(scene.add.text(x + 18, y + 12, o.title, { fontFamily: BODY_FONT, fontStyle: 'bold', fontSize: '20px', color: INK.cream })); + const n = add(scene.add.text(x + 18, y + 40, o.note, { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '15px', color: '#cdb994', wordWrap: { width: 440 } })); + const z = add(scene.add.zone(x, y, 470, 74).setOrigin(0).setInteractive({ useHandCursor: true })); + z.on('pointerup', () => { Sound.click(scene); sel.daily = o.key; refresh(); }); + typeBtns.push({ g, x, y, key: o.key, t, n }); + }); + + // ── island shape ──────────────────────────────────────────────────────────── + label(left, top + 318, 'ISLAND'); + const shapeBtns = []; + [...LAYOUT_KEYS, 'random'].forEach((key, i) => { + const x = left + i * 198, y = top + 346; + const g = add(scene.add.graphics()); + shapePreview(scene, x + 90, y + 52, key).forEach(add); + const name = key === 'random' ? 'Surprise me' : LAYOUTS[key].name; + const t = add(scene.add.text(x + 90, y + 112, name, { fontFamily: BODY_FONT, fontStyle: 'bold', fontSize: '16px', color: INK.cream }).setOrigin(0.5, 0)); + const z = add(scene.add.zone(x, y, 180, 140).setOrigin(0).setInteractive({ useHandCursor: true })); + z.on('pointerup', () => { if (sel.daily) return; Sound.click(scene); sel.layout = key; refresh(); }); + shapeBtns.push({ g, x, y, key, t }); + }); + const blurb = add(scene.add.text(cx, top + 500, '', { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '16px', color: '#e2d3b0' }).setOrigin(0.5)); + + // ── role ──────────────────────────────────────────────────────────────────── + label(left, top + 530, 'YOUR ROLE'); + const roleBtns = []; + ['random', ...ROLE_KEYS].forEach((key, i) => { + const x = left + i * 142, y = top + 556; + const g = add(scene.add.graphics()); + if (key === 'random') add(scene.add.text(x + 64, y + 40, '?', { fontFamily: DISPLAY_FONT, fontSize: '40px', color: '#d8b25a' }).setOrigin(0.5)); + else add(scene.add.image(x + 64, y + 72, `di-pawn-${key}`).setOrigin(0.5, 1).setDisplaySize(40, 58)); + const t = add(scene.add.text(x + 64, y + 80, key === 'random' ? 'Any role' : ROLES[key].name, { + fontFamily: TYPE_FONT, fontSize: '12px', fontStyle: 'bold', color: INK.cream, align: 'center', wordWrap: { width: 124 }, + }).setOrigin(0.5, 0)); + const z = add(scene.add.zone(x, y, 128, 112).setOrigin(0).setInteractive({ useHandCursor: true })); + z.on('pointerup', () => { if (sel.daily) return; Sound.click(scene); sel.role = key; refresh(); }); + roleBtns.push({ g, x, y, key, t }); + }); + const power = add(scene.add.text(cx, top + 680, '', { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '16px', color: '#e2d3b0' }).setOrigin(0.5)); + + // ── footer ────────────────────────────────────────────────────────────────── + const recLine = rec.played + ? `Expeditions ${rec.played} · escaped ${rec.won} · best ${rec.bestDays ?? 'n/a'}${rec.bestDays ? ' days' : ''} · streak ${rec.streak}` + : 'No expeditions yet.'; + add(scene.add.text(left, top + ph - 52, `${DIFFICULTY[difficulty].name.toUpperCase()} · ${playerCount} CREW · ${recLine}`, { + fontFamily: TYPE_FONT, fontSize: '13px', color: '#cdb994', + }).setOrigin(0, 0.5)); + const close = () => root.destroy(); + if (saved) { + const s = saved.gs; + const b = add(new Button(scene, cx + 180, top + ph - 52, `Resume (day ${s.round ?? 1})`, () => { close(); onStart({ resume: true }); }, { width: 250, height: 52, fontSize: 18, ...BRASS })); + b.setDepth(0); + } + const go = add(new Button(scene, cx + 430, top + ph - 52, 'Set Out', () => { + close(); + const layout = sel.daily ? daily.layout : sel.layout === 'random' ? LAYOUT_KEYS[Math.floor(Math.random() * LAYOUT_KEYS.length)] : sel.layout; + onStart({ layout, daily: sel.daily ? daily : null, role: sel.daily ? null : (sel.role === 'random' ? null : sel.role) }); + }, { width: 200, height: 56, fontSize: 22, ...BRASS })); + go.setDepth(0); + + function box(g, x, y, w, h, on, enabled = true) { + g.clear(); + g.fillStyle(on ? 0xd8b25a : 0x000000, on ? 0.18 : 0.25); g.fillRoundedRect(x, y, w, h, 10); + g.lineStyle(on ? 3 : 1.5, on ? 0xf0d070 : 0x8a6a3a, enabled ? 1 : 0.35); g.strokeRoundedRect(x, y, w, h, 10); + } + function refresh() { + typeBtns.forEach((b) => box(b.g, b.x, b.y, 470, 74, sel.daily === b.key)); + const lay = sel.daily ? daily.layout : sel.layout; + shapeBtns.forEach((b) => { box(b.g, b.x, b.y, 180, 140, b.key === lay, !sel.daily); b.t.setAlpha(sel.daily && b.key !== lay ? 0.4 : 1); }); + blurb.setText(sel.daily ? `Today's island: ${LAYOUTS[daily.layout].name}. ${LAYOUTS[daily.layout].blurb}` : lay === 'random' ? 'One of the four shapes, chosen when you set out.' : LAYOUTS[lay].blurb); + const role = sel.daily ? daily.roles[0] : sel.role; + roleBtns.forEach((b) => { box(b.g, b.x, b.y, 128, 112, b.key === role, !sel.daily); b.t.setAlpha(sel.daily && b.key !== role ? 0.4 : 1); }); + power.setText(sel.daily ? `Today you are the ${ROLES[role].name}: ${ROLES[role].power}` + : role === 'random' ? 'Your role is drawn from the crew roster.' : `${ROLES[role].name}: ${ROLES[role].power}`); + } + refresh(); + return root; +} diff --git a/src/games/forbiddenisland/IslandEndScreen.js b/src/games/forbiddenisland/IslandEndScreen.js new file mode 100644 index 0000000..7bd9cdc --- /dev/null +++ b/src/games/forbiddenisland/IslandEndScreen.js @@ -0,0 +1,149 @@ +// The Drowning Isle: the expedition report, shown when the game ends. +// +// ┌ headline + one-line story ──────────────────────────────────────────┐ +// │ tide chart by day │ expedition timeline (key moments) │ +// │ (gauge line, flooded and │ │ +// │ sunk tiles as bars) │ │ +// ├ crew cards: figurine, what each did, the expedition's MVP ──────────┤ +// │ relics · lifetime record · New Expedition / Leave │ +// └─────────────────────────────────────────────────────────────────────┘ + +import { Button } from '../../ui/Button.js'; +import { TREASURE_KEYS, TREASURES, ROLES, MAX_WATER, LAYOUTS, cardFrame } from './IslandData.js'; +import { W, H, DEPTH, DISPLAY_FONT, BODY_FONT, TYPE_FONT, INK } from './IslandLayout.js'; +import { bakeLeather } from './IslandArt.js'; + +const BRASS = { bg: 0x5a3f1a, bgHover: 0xd8b25a, textColor: '#f2e6cc', textHoverColor: '#2b1d08' }; + +// What each crew member did, from the game log. +export function crewStats(gs) { + const st = Object.fromEntries(gs.players.map((p) => [p.seat, { shored: 0, gave: 0, relics: 0, moves: 0, specials: 0, guided: 0 }])); + for (const e of gs.log) { + const s = st[e.seat]; if (!s) continue; + if (e.kind === 'shoreUp') s.shored += e.tiles.length; + else if (e.kind === 'give') s.gave++; + else if (e.kind === 'capture') s.relics++; + else if (e.kind === 'move' || e.kind === 'fly') s.moves++; + else if (e.kind === 'navMove') s.guided++; + else if (e.kind === 'sandbags' || e.kind === 'helicopter') { s.specials++; if (e.kind === 'sandbags') s.shored++; } + } + for (const s of Object.values(st)) s.score = s.relics * 6 + s.shored * 1.5 + s.gave * 2 + s.specials * 2 + s.guided; + return st; +} + +export function showEndScreen(scene, { gs, names, history, moments, result, onAgain, onLeave }) { + const won = gs.phase === 'won'; + const pw = 1500, ph = 900, cx = W / 2, cy = H / 2; + const left = cx - pw / 2, top = cy - ph / 2; + const root = scene.add.container(0, 0).setDepth(DEPTH.banner).setAlpha(0); + const add = (o) => { root.add(o); return o; }; + add(scene.add.rectangle(0, 0, W, H, 0x020a10, 0.7).setOrigin(0).setInteractive()); + add(scene.add.image(cx, cy, bakeLeather(scene, pw, ph))); + add(scene.add.text(cx, top + 58, won ? 'The Expedition Is Saved' : 'The Isle Has Drowned', { + fontFamily: DISPLAY_FONT, fontSize: '52px', color: won ? INK.brassHex : '#e07a5f', + }).setOrigin(0.5).setShadow(0, 3, '#000', 6)); + const days = gs.round ?? 1; + add(scene.add.text(cx, top + 110, won + ? `All four relics recovered and the whole crew lifted off on day ${days}.` + : `${gs.lossReason ?? 'The island is lost.'} Day ${days}.`, { + fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '21px', color: INK.cream, align: 'center', wordWrap: { width: pw - 160 }, + }).setOrigin(0.5)); + + // ── tide chart ────────────────────────────────────────────────────────────── + const chart = { x: left + 70, y: top + 170, w: 640, h: 300 }; + add(scene.add.text(chart.x, chart.y - 4, 'TIDE CHART', { fontFamily: TYPE_FONT, fontSize: '15px', fontStyle: 'bold', color: '#cdb994' })); + const g = add(scene.add.graphics()); + const px = chart.x + 36, py = chart.y + 30, pw2 = chart.w - 50, ph2 = chart.h - 70; + g.fillStyle(0xe9dcc0, 0.95); g.fillRoundedRect(chart.x, chart.y + 22, chart.w, chart.h - 22, 8); + g.lineStyle(1, 0x8a7658, 0.35); + for (let l = 0; l <= MAX_WATER; l += 2) { const y = py + ph2 - (l / MAX_WATER) * ph2; g.lineBetween(px, y, px + pw2, y); } + for (let l = 2; l <= MAX_WATER; l += 2) add(scene.add.text(px - 8, py + ph2 - (l / MAX_WATER) * ph2, String(l), { fontFamily: TYPE_FONT, fontSize: '11px', color: INK.inkSoft }).setOrigin(1, 0.5)); + const hist = history.length ? history : [{ day: 1, level: gs.waterLevel, flooded: 0, sunk: 0 }]; + const n = hist.length, step = pw2 / Math.max(1, n); + hist.forEach((h, i) => { + const x = px + i * step + step * 0.15, bw = Math.max(2, step * 0.7); + const sunkH = (h.sunk / 24) * ph2, floodH = (h.flooded / 24) * ph2; + g.fillStyle(0x2a3a44, 0.7); g.fillRect(x, py + ph2 - sunkH, bw, sunkH); + g.fillStyle(0x3d8cc4, 0.55); g.fillRect(x, py + ph2 - sunkH - floodH, bw, floodH); + }); + g.lineStyle(3, 0x8e2a1e, 1); g.beginPath(); + hist.forEach((h, i) => { const x = px + i * step + step / 2, y = py + ph2 - (h.level / MAX_WATER) * ph2; i ? g.lineTo(x, y) : g.moveTo(x, y); }); + g.strokePath(); + hist.forEach((h, i) => { const x = px + i * step + step / 2, y = py + ph2 - (h.level / MAX_WATER) * ph2; g.fillStyle(0x8e2a1e, 1); g.fillCircle(x, y, 3); }); + const every = Math.max(1, Math.ceil(n / 12)); + hist.forEach((h, i) => { if (i % every === 0) add(scene.add.text(px + i * step + step / 2, py + ph2 + 6, String(h.day), { fontFamily: TYPE_FONT, fontSize: '11px', color: INK.inkSoft }).setOrigin(0.5, 0)); }); + // legend: swatch + label, laid out left to right + let lx = chart.x + 14; + const ly = chart.y + chart.h - 22; + for (const [kind, col, text] of [['line', 0x8e2a1e, 'tide gauge'], ['bar', 0x3d8cc4, 'flooded tiles'], ['bar', 0x2a3a44, 'sunk tiles'], [null, 0, '(by day)']]) { + if (kind === 'line') { g.lineStyle(3, col, 1); g.lineBetween(lx, ly + 7, lx + 14, ly + 7); lx += 20; } + else if (kind === 'bar') { g.fillStyle(col, 0.85); g.fillRect(lx, ly + 1, 9, 12); lx += 15; } + const t = add(scene.add.text(lx, ly, text, { fontFamily: TYPE_FONT, fontSize: '11px', color: INK.inkSoft })); + lx += t.width + 18; + } + + // ── timeline ──────────────────────────────────────────────────────────────── + const tl = { x: left + 760, y: top + 170, w: 670 }; + add(scene.add.text(tl.x, tl.y - 4, 'EXPEDITION LOG', { fontFamily: TYPE_FONT, fontSize: '15px', fontStyle: 'bold', color: '#cdb994' })); + const keyMoments = moments.slice(-11); + let ty = tl.y + 28; + if (!keyMoments.length) add(scene.add.text(tl.x, ty, 'A quiet expedition. Too quiet.', { fontFamily: BODY_FONT, fontStyle: 'italic', fontSize: '17px', color: INK.cream })); + for (const m of keyMoments) { + const icon = { capture: '★', sink: '▼', rise: '≈', heli: '✈', bags: '▣', escape: '✈', loss: '✖' }[m.kind] ?? '•'; + const col = { capture: '#f0d58c', sink: '#e07a5f', rise: '#8fd0f0', loss: '#e07a5f' }[m.kind] ?? INK.cream; + add(scene.add.text(tl.x, ty, `DAY ${String(m.day).padStart(2, ' ')}`, { fontFamily: TYPE_FONT, fontSize: '13px', fontStyle: 'bold', color: '#cdb994' })); + add(scene.add.text(tl.x + 70, ty - 2, icon, { fontFamily: BODY_FONT, fontSize: '16px', color: col })); + const t = add(scene.add.text(tl.x + 96, ty - 1, m.text, { fontFamily: BODY_FONT, fontSize: '16px', color: INK.cream, wordWrap: { width: tl.w - 100 } })); + ty += Math.max(26, t.height + 6); + if (ty > top + 470) break; + } + + // ── crew cards ────────────────────────────────────────────────────────────── + const stats = crewStats(gs); + const mvp = Object.entries(stats).sort((a, b) => b[1].score - a[1].score)[0]?.[0]; + const cw = 330, cardY = top + 500; + const n2 = gs.players.length, cx0 = cx - (n2 * cw + (n2 - 1) * 20) / 2; + gs.players.forEach((p, i) => { + const x = cx0 + i * (cw + 20), s = stats[p.seat]; + const cg = add(scene.add.graphics()); + cg.fillStyle(0xe9dcc0, 0.95); cg.fillRoundedRect(x, cardY, cw, 170, 10); + cg.lineStyle(3, String(p.seat) === mvp ? 0xd8b25a : 0x5a4020, 1); cg.strokeRoundedRect(x, cardY, cw, 170, 10); + add(scene.add.image(x + 46, cardY + 120, `di-pawn-${p.role}`).setOrigin(0.5, 1).setDisplaySize(52, 76)); + add(scene.add.text(x + 90, cardY + 16, names[p.seat] ?? `Seat ${p.seat}`, { fontFamily: BODY_FONT, fontStyle: 'bold', fontSize: '20px', color: INK.ink })); + add(scene.add.text(x + 90, cardY + 44, ROLES[p.role].name, { fontFamily: TYPE_FONT, fontSize: '13px', fontStyle: 'bold', color: INK.inkSoft })); + const lines = [ + `${s.relics} relic${s.relics === 1 ? '' : 's'} recovered`, + `${s.shored} tile${s.shored === 1 ? '' : 's'} shored up`, + `${s.gave} card${s.gave === 1 ? '' : 's'} given${s.specials ? ` · ${s.specials} special${s.specials === 1 ? '' : 's'}` : ''}`, + ]; + add(scene.add.text(x + 90, cardY + 70, lines.join('\n'), { fontFamily: BODY_FONT, fontSize: '15px', color: INK.inkSoft, lineSpacing: 4 })); + if (String(p.seat) === mvp) { + add(scene.add.text(x + cw - 12, cardY + 12, 'MVP', { fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: '#8e2a1e', backgroundColor: 'rgba(216,178,90,0.6)', padding: { x: 6, y: 2 } }).setOrigin(1, 0).setAngle(6)); + } + }); + + // ── relics, record, buttons ───────────────────────────────────────────────── + const ry = top + 752; + TREASURE_KEYS.forEach((k, i) => { + const got = gs.players.some((p) => p.captured[k]); + const x = left + 110 + i * 70; + if (scene.textures.exists('forbiddenisland-cards')) { + add(scene.add.image(x, ry, 'forbiddenisland-cards', cardFrame(`treasure:${k}`)).setDisplaySize(54, 71).setAlpha(got ? 1 : 0.3).setTint(got ? 0xffffff : 0x777777)); + } else add(scene.add.circle(x, ry, 20, TREASURES[k].color, got ? 1 : 0.3)); + }); + const r = result?.record; + if (r) { + const flags = result.flags ?? {}; + const extra = [flags.bestDays ? 'NEW FASTEST ESCAPE!' : '', flags.bestStreak ? `NEW BEST STREAK (${r.bestStreak})!` : ''].filter(Boolean).join(' '); + add(scene.add.text(left + 420, ry - 22, `${LAYOUTS[gs.layout]?.name ?? ''}${result.daily ? ` · Daily ${result.daily}` : ''}`, { fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: '#cdb994' })); + add(scene.add.text(left + 420, ry + 4, `Expeditions ${r.played} · escaped ${r.won} (${Math.round((r.won / r.played) * 100)}%) · best ${r.bestDays ?? 'n/a'}${r.bestDays ? ' days' : ''} · streak ${r.streak}`, { + fontFamily: TYPE_FONT, fontSize: '14px', color: INK.cream, + })); + if (extra) add(scene.add.text(left + 420, ry + 28, extra, { fontFamily: TYPE_FONT, fontSize: '14px', fontStyle: 'bold', color: '#f0d58c' })); + } + const again = add(new Button(scene, cx + 380, top + ph - 70, 'New Expedition', onAgain, { width: 250, height: 56, fontSize: 21, ...BRASS })); + const leave = add(new Button(scene, cx + 610, top + ph - 70, 'Leave', onLeave, { width: 170, height: 56, fontSize: 21, ...BRASS })); + again.setDepth(0); leave.setDepth(0); + scene.tweens.add({ targets: root, alpha: 1, duration: 600 }); + return root; +} diff --git a/src/games/forbiddenisland/IslandEngine.js b/src/games/forbiddenisland/IslandEngine.js new file mode 100644 index 0000000..cf8d064 --- /dev/null +++ b/src/games/forbiddenisland/IslandEngine.js @@ -0,0 +1,85 @@ +// IslandEngine.js: runs the teammates' planner (IslandAI) off the main thread +// so the island keeps animating while partners think. +// +// handle(kind, payload) the actual work (shared by the worker and the +// inline fallback) +// class Engine main-thread client: request(kind, payload) → +// Promise. Uses a module Worker (IslandWorker.js); +// if that can't start, runs the same code inline. +// +// Kinds (the planner applies publicView itself: it never reads deck order): +// step { state, seat, skill } → { free } | { action } | { end: true } +// free { state, seat, minGain } → free-card play or null +// plan { state, seat, skill } → the turn's planned actions (primes step) +// discard { state, seat } → card id +// intent { state, seat } → rationale for the chat line + +import * as AI from './IslandAI.js'; + +export function handle(kind, p) { + switch (kind) { + case 'step': { + const free = AI.chooseFreeCard(p.state, p.seat); + if (free) return { free }; + const action = AI.chooseAction(p.state, p.seat, p.skill); + return action ? { action } : { end: true }; + } + case 'free': return AI.chooseFreeCard(p.state, p.seat, { minGain: p.minGain ?? 300 }); + case 'plan': return AI.previewPlan(p.state, p.seat, p.skill); + case 'discard': return AI.chooseDiscard(p.state, p.seat); + case 'intent': return AI.describeIntent(p.state, p.seat); + default: return null; + } +} + +export class Engine { + constructor() { + this.seq = 0; + this.pending = new Map(); + this.worker = null; + try { + if (typeof Worker !== 'undefined') { + this.worker = new Worker(new URL('./IslandWorker.js', import.meta.url), { type: 'module' }); + this.worker.onmessage = (e) => this.settle(e.data); + this.worker.onerror = (e) => { e?.preventDefault?.(); this.fallBack(); }; + } + } catch (_) { this.worker = null; } + } + + settle({ id, res, err }) { + const job = this.pending.get(id); + if (!job) return; + this.pending.delete(id); + if (err) job.reject(new Error(err)); else job.resolve(res); + } + + fallBack() { + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + for (const [id, job] of this.pending) this.runInline(id, job.kind, job.payload); + } + + runInline(id, kind, payload) { + setTimeout(() => { + let res = null, err = null; + try { res = handle(kind, payload); } catch (e) { err = String(e?.message ?? e); } + this.settle({ id, res, err }); + }, 0); + } + + request(kind, payload) { + const id = ++this.seq; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, kind, payload }); + if (this.worker) { + try { this.worker.postMessage({ id, kind, payload }); } catch (_) { this.fallBack(); } + } else this.runInline(id, kind, payload); + }); + } + + destroy() { + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + this.pending.clear(); + } +} diff --git a/src/games/forbiddenisland/IslandLayout.js b/src/games/forbiddenisland/IslandLayout.js new file mode 100644 index 0000000..5db44cb --- /dev/null +++ b/src/games/forbiddenisland/IslandLayout.js @@ -0,0 +1,49 @@ +// The Drowning Isle: screen geometry shared by the scene and the art modules. +// +// ┌ crew strip ─────────────┐ ┌ field journal ─────────────────────────┐ ┌──┐ +// │ │ │ title · day stamp │ │t │ +// │ the island │ │ turn plate · relic tracker │ │i │ +// │ (24 tiles on the │ │ expedition log (chat) │ │d │ +// │ open sea) │ │ your hand │ │e │ +// │ flood deck · supplies │ │ actions │ │ │ +// └─────────────────────────┘ └────────────────────────────────────────┘ └──┘ + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { GRID } from './IslandData.js'; + +export const W = GAME_WIDTH, H = GAME_HEIGHT; + +export const TILE = 110, GAP = 8, PITCH = TILE + GAP; +export const BOARD_W = GRID * PITCH - GAP; // 700 +export const BX0 = 70; // board left +export const BY0 = 158; // board top +export const RAIL_X = BX0 + BOARD_W + 50; // journal text column (~820) +export const RAIL_W = GAME_WIDTH - RAIL_X - 110; // leaves room for the tide gauge + +// The journal page drawn behind the rail text. +export const JOURNAL = { x: RAIL_X - 24, y: 10, w: RAIL_W + 46, h: H - 20 }; + +// Tide gauge on the far right. +export const GAUGE = { x: GAME_WIDTH - 62, top: 160, bottom: 900 }; + +export const DEPTH = { + sea: 0, sky: 1, foam: 3, board: 5, tile: 10, tileFx: 12, pawn: 20, + rain: 30, flash: 32, ui: 40, popup: 60, banner: 90, +}; + +// Typefaces: classical capitals for headings, a serif for journal prose and a +// typewriter face for stamps and figures. +export const DISPLAY_FONT = 'Caesar, Georgia, serif'; +export const BODY_FONT = 'Georgia, "Times New Roman", serif'; +export const TYPE_FONT = '"Courier New", Courier, monospace'; + +// Ink and brass palette. +export const INK = { + ink: '#2b2116', inkSoft: '#5a4a35', faded: '#8a7658', red: '#8e2a1e', blue: '#1f4a66', + paper: 0xe9dcc0, paperHex: '#e9dcc0', brass: 0xc9a14a, brassHex: '#d8b25a', brassDark: 0x6e5222, + leather: 0x2a1d14, teal: 0x0d3a46, foam: 0xdff4f2, cream: '#f2e6cc', +}; + +export function tileCenter(t) { + return { x: BX0 + t.c * PITCH + TILE / 2, y: BY0 + t.r * PITCH + TILE / 2 }; +} diff --git a/src/games/forbiddenisland/IslandLogic.js b/src/games/forbiddenisland/IslandLogic.js index 2f93eb0..26d41f8 100644 --- a/src/games/forbiddenisland/IslandLogic.js +++ b/src/games/forbiddenisland/IslandLogic.js @@ -1,4 +1,4 @@ -// Forbidden Island — pure state engine. No Phaser. The whole game is a +// The Drowning Isle — pure state engine. No Phaser. The whole game is a // cooperative race against the board: players take 3 actions, draw 2 Treasure // cards, then the island floods. Everyone wins or loses together. // @@ -7,7 +7,7 @@ // reproducible and unit-testable. import { - CELLS, TILES, TREASURES, TREASURE_KEYS, ROLES, SPECIAL, + LAYOUTS, TILES, TREASURES, TREASURE_KEYS, ROLES, SPECIAL, buildTreasureDeck, floodDrawCount, DIFFICULTY, CARDS_TO_CAPTURE, HAND_LIMIT, ACTIONS_PER_TURN, MAX_WATER, } from './IslandData.js'; @@ -48,12 +48,14 @@ function makeRng(state) { } // ---- construction ---------------------------------------------------------- -export function createInitialState({ roles, difficulty = 'normal', seed, humanSeat = 0, skipInitialFlood = false } = {}) { +export function createInitialState({ roles, difficulty = 'normal', seed, humanSeat = 0, skipInitialFlood = false, layout = 'diamond' } = {}) { const roleKeys = (roles && roles.length) ? roles.slice(0, 4) : ['pilot', 'engineer', 'navigator', 'diver']; const s = { seed: (seed ?? Math.floor(Math.random() * 1e9)) >>> 0, rngCursor: 0, difficulty, + layout: LAYOUTS[layout] ? layout : 'diamond', + round: 1, tiles: {}, players: [], treasureDeck: [], @@ -63,9 +65,13 @@ export function createInitialState({ roles, difficulty = 'normal', seed, humanSe waterLevel: DIFFICULTY[difficulty]?.start ?? 2, current: 0, actionsLeft: ACTIONS_PER_TURN, - phase: 'actions', // actions | discard | flood | won | lost + phase: 'actions', // actions | discard | flood | swim | won | lost pendingDiscard: null, // seat that must discard pendingSwim: null, // { seat, options } a pawn forced to leave a sunk tile + pendingSwims: [], // seats still to swim this flood (human pawns) + discardReturn: null, // phase to resume after a forced discard ('actions' after a give) + floodKnown: [], // public knowledge: sets of flood cards known to sit on top of the + // flood deck (top segment first), from Waters Rise reshuffles priorities: { focusTreasure: null, saveTiles: [], regroup: false, hold: false }, lossReason: null, log: [], @@ -74,7 +80,7 @@ export function createInitialState({ roles, difficulty = 'normal', seed, humanSe const rng = makeRng(s); // Assign the 24 tiles to the 24 board cells. const shuffledTiles = shuffle(TILES, rng.next); - CELLS.forEach(([r, c], i) => { + LAYOUTS[s.layout].cells.forEach(([r, c], i) => { const t = shuffledTiles[i]; s.tiles[t.id] = { id: t.id, name: t.name, r, c, @@ -84,7 +90,9 @@ export function createInitialState({ roles, difficulty = 'normal', seed, humanSe }; }); - // Pawns: everyone starts on Fools' Landing (safe, central rally point). + s.layoutKey = Object.values(s.tiles).map((t) => `${t.id}@${t.r},${t.c}`).sort().join(';'); + + // Pawns: everyone starts on the Expedition Dock (safe, central rally point). roleKeys.forEach((rk, seat) => { s.players.push({ seat, @@ -196,28 +204,45 @@ export function cloneState(state) { }, pendingSwim: state.pendingSwim ? { ...state.pendingSwim, options: state.pendingSwim.options.slice() } : null, pendingFlood: (state.pendingFlood ?? []).slice(), + pendingSwims: (state.pendingSwims ?? []).slice(), + floodKnown: (state.floodKnown ?? []).map((seg) => seg.slice()), log: state.log.slice(), }; } // ---- geometry / adjacency -------------------------------------------------- -function cellIndex(state) { - const map = {}; - for (const t of Object.values(state.tiles)) map[`${t.r},${t.c}`] = t.id; - return map; +// Tiles never move once dealt, so neighbour lists are computed once per deal +// and cached by the tiles' grid positions (planners call this constantly). +const NEIGHBOUR_CACHE = new Map(); +export function neighbourTable(state) { + let key = state.layoutKey; + if (!key) key = Object.values(state.tiles).map((t) => `${t.id}@${t.r},${t.c}`).sort().join(';'); + let tab = NEIGHBOUR_CACHE.get(key); + if (!tab) { + const map = {}; + for (const t of Object.values(state.tiles)) map[`${t.r},${t.c}`] = t.id; + const orth = {}, all = {}; + for (const t of Object.values(state.tiles)) { + orth[t.id] = ORTH.map(([dr, dc]) => map[`${t.r + dr},${t.c + dc}`]).filter(Boolean); + all[t.id] = [...ORTH, ...DIAG].map(([dr, dc]) => map[`${t.r + dr},${t.c + dc}`]).filter(Boolean); + } + const ids = Object.keys(state.tiles).sort(); + const index = Object.fromEntries(ids.map((id, i) => [id, i])); + tab = { + orth, all, ids, index, + orthI: ids.map((id) => orth[id].map((x) => index[x])), + allI: ids.map((id) => all[id].map((x) => index[x])), + }; + if (NEIGHBOUR_CACHE.size > 64) NEIGHBOUR_CACHE.clear(); + NEIGHBOUR_CACHE.set(key, tab); + } + return tab; } export function adjacentTiles(state, tileId, { diagonal = false } = {}) { - const t = state.tiles[tileId]; - if (!t) return []; - const map = cellIndex(state); - const dirs = diagonal ? [...ORTH, ...DIAG] : ORTH; - const out = []; - for (const [dr, dc] of dirs) { - const id = map[`${t.r + dr},${t.c + dc}`]; - if (id) out.push(id); - } - return out; + if (!state.tiles[tileId]) return []; + const tab = neighbourTable(state); + return (diagonal ? tab.all : tab.orth)[tileId].slice(); } function isSunk(state, id) { return state.tiles[id].state === 'sunk'; } @@ -227,15 +252,14 @@ function isFlooded(state, id) { return state.tiles[id].state === 'flooded'; } // flooded/sunk tiles (orthogonally) from the start. function diverDestinations(state, startId) { const start = state.tiles[startId]; - const map = cellIndex(state); + const orth = neighbourTable(state).orth; const seen = new Set([startId]); const dest = new Set(); const stack = [start]; while (stack.length) { const t = stack.pop(); - for (const [dr, dc] of ORTH) { - const id = map[`${t.r + dr},${t.c + dc}`]; - if (!id || seen.has(id)) continue; + for (const id of orth[t.id]) { + if (seen.has(id)) continue; seen.add(id); const nt = state.tiles[id]; if (nt.state === 'sunk') { stack.push(nt); } // swim through @@ -294,6 +318,14 @@ export function legalActions(state, seat) { if (have >= CARDS_TO_CAPTURE) out.push({ type: 'capture', seat, treasure: tile.treasure }); } + // Give a Treasure card: same tile (Messenger: any distance). Specials can't be given. + const giveable = [...new Set(p.hand.filter((c) => c.startsWith('treasure:')))]; + for (const other of state.players) { + if (other.seat === seat) continue; + if (p.role !== 'messenger' && other.tileId !== p.tileId) continue; + for (const card of giveable) out.push({ type: 'give', seat, targetSeat: other.seat, card }); + } + // Navigator: move another adventurer up to 2 tiles. if (p.role === 'navigator') { for (const other of state.players) { @@ -348,6 +380,21 @@ export function applyAction(state, seat, action) { s.players[action.targetSeat].tileId = action.tileId; s.log.push({ kind: 'navMove', seat, targetSeat: action.targetSeat, tileId: action.tileId }); break; + case 'give': { + const target = s.players[action.targetSeat]; + const idx = p.hand.indexOf(action.card); + if (!target || target.seat === seat || idx < 0 || !action.card.startsWith('treasure:')) return state; + if (p.role !== 'messenger' && target.tileId !== p.tileId) return state; + p.hand.splice(idx, 1); + target.hand.push(action.card); + s.log.push({ kind: 'give', seat, targetSeat: target.seat, card: action.card }); + s.actionsLeft -= 1; + // Receiving over the limit forces an immediate discard, then play resumes. + if (target.hand.length > HAND_LIMIT) { + s.phase = 'discard'; s.pendingDiscard = target.seat; s.discardReturn = 'actions'; + } + return checkLoss(s) ?? s; + } default: return state; } @@ -357,41 +404,55 @@ export function applyAction(state, seat, action) { } // ---- special cards (free, any time) --------------------------------------- +// Any player may play Sandbags / Helicopter Lift at any moment of the game — +// on anyone's turn, during a forced discard (instead of discarding), or while +// a swim is pending. Only finished games refuse them. +function canPlaySpecial(state) { return state.phase !== 'won' && state.phase !== 'lost'; } + +// After a card leaves a hand, a pending over-limit discard may be satisfied. +function settleDiscard(s) { + if (s.phase !== 'discard' || s.pendingDiscard == null) return; + if (s.players[s.pendingDiscard].hand.length <= HAND_LIMIT) { + s.phase = s.discardReturn ?? 'flood'; + s.pendingDiscard = null; s.discardReturn = null; + } +} + export function playSandbags(state, seat, tileId) { const p = state.players[seat]; - if (!p.hand.includes(SPECIAL.SANDBAGS) || !isFlooded(state, tileId)) return state; + if (!canPlaySpecial(state) || !p?.hand.includes(SPECIAL.SANDBAGS) || !state.tiles[tileId] || !isFlooded(state, tileId)) return state; const s = cloneState(state); s.players[seat].hand.splice(s.players[seat].hand.indexOf(SPECIAL.SANDBAGS), 1); s.tiles[tileId].state = 'dry'; s.treasureDiscard.push(SPECIAL.SANDBAGS); s.log.push({ kind: 'sandbags', seat, tileId }); + settleDiscard(s); return s; } +// Lift one or more pawns that share a tile to any other non-sunk tile. (With +// all four treasures held and the whole team on the landing, attemptEscape() +// is the winning lift instead.) export function playHelicopter(state, seat, pawnSeats, destTileId) { const p = state.players[seat]; - if (!p.hand.includes(SPECIAL.HELICOPTER) || isSunk(state, destTileId)) return state; + if (!canPlaySpecial(state) || !p?.hand.includes(SPECIAL.HELICOPTER)) return state; + if (!state.tiles[destTileId] || isSunk(state, destTileId)) return state; + const seats = [...new Set(pawnSeats ?? [])].filter((ps) => state.players[ps]); + if (!seats.length) return state; + const from = state.players[seats[0]].tileId; + if (from === destTileId || seats.some((ps) => state.players[ps].tileId !== from)) return state; const s = cloneState(state); s.players[seat].hand.splice(s.players[seat].hand.indexOf(SPECIAL.HELICOPTER), 1); - for (const ps of pawnSeats) s.players[ps].tileId = destTileId; + for (const ps of seats) s.players[ps].tileId = destTileId; s.treasureDiscard.push(SPECIAL.HELICOPTER); - s.log.push({ kind: 'helicopter', seat, pawnSeats: pawnSeats.slice(), destTileId }); - return s; -} - -// Swap one card between two players — free action (no action cost, no tile check). -export function swapCards(state, seatA, cardA, seatB, cardB) { - if (seatA === seatB) return state; - const pA = state.players[seatA]; - const pB = state.players[seatB]; - if (!pA || !pB) return state; - const iA = pA.hand.indexOf(cardA); - const iB = pB.hand.indexOf(cardB); - if (iA < 0 || iB < 0) return state; - const s = cloneState(state); - s.players[seatA].hand[iA] = cardB; - s.players[seatB].hand[iB] = cardA; - s.log.push({ kind: 'swapCards', seatA, cardA, seatB, cardB }); + s.log.push({ kind: 'helicopter', seat, pawnSeats: seats, fromTileId: from, destTileId }); + settleDiscard(s); + // A lift can rescue a pawn that was waiting to swim off a sunk tile. + if (s.phase === 'swim') { + s.pendingSwims = s.pendingSwims.filter((ps) => isSunk(s, s.players[ps].tileId)); + s.pendingSwim = null; + return finishFlood(s); + } return s; } @@ -405,8 +466,12 @@ export function canEscape(state) { export function attemptEscape(state) { if (!canEscape(state)) return state; const s = cloneState(state); + const liftSeat = s.players.find((p) => p.hand.includes(SPECIAL.HELICOPTER)).seat; + const hand = s.players[liftSeat].hand; + hand.splice(hand.indexOf(SPECIAL.HELICOPTER), 1); + s.treasureDiscard.push(SPECIAL.HELICOPTER); s.phase = 'won'; - s.log.push({ kind: 'won' }); + s.log.push({ kind: 'won', seat: liftSeat }); return s; } @@ -430,11 +495,12 @@ export function endActions(state) { s.waterLevel = Math.min(MAX_WATER, s.waterLevel + 1); // Reshuffle the flood discard back on TOP of the flood deck. if (s.floodDiscard.length) { + s.floodKnown = [s.floodDiscard.slice().sort(), ...(s.floodKnown ?? [])]; s.floodDeck = [...shuffle(s.floodDiscard, rng.next), ...s.floodDeck]; s.floodDiscard = []; } s.log.push({ kind: 'watersRise', waterLevel: s.waterLevel }); - if (s.waterLevel >= MAX_WATER) { rng.commit(); s.phase = 'lost'; s.lossReason = 'The water level reached the skull.'; return s; } + if (s.waterLevel >= MAX_WATER) { rng.commit(); s.phase = 'lost'; s.lossKind = 'gauge'; s.lossReason = 'The tide gauge hit the drowned mark. The island is gone.'; return s; } } else { p.hand.push(card); s.log.push({ kind: 'drawTreasure', seat: p.seat, card }); @@ -457,7 +523,7 @@ export function discardCard(state, seat, cardId) { const [card] = hand.splice(idx, 1); if (card.startsWith('treasure:') || card === SPECIAL.SANDBAGS || card === SPECIAL.HELICOPTER) s.treasureDiscard.push(card); s.log.push({ kind: 'discard', seat, card }); - if (s.players[seat].hand.length <= HAND_LIMIT) { s.phase = 'flood'; s.pendingDiscard = null; } + settleDiscard(s); return s; } @@ -465,7 +531,7 @@ export function discardCard(state, seat, cardId) { // Draws flood cards equal to the water level, flooding/sinking tiles, then // auto-resolves forced swims and advances to the next player. Returns the new // state; inspect `state.log` (entries since the call) to animate. -export function resolveFlood(state) { +export function resolveFlood(state, { autoSwim = false } = {}) { if (state.phase !== 'flood') return state; let s = cloneState(state); const count = floodDrawCount(s.waterLevel); @@ -480,8 +546,10 @@ export function resolveFlood(state) { if (s.floodDiscard.length === 0) break; s.floodDeck = shuffle(s.floodDiscard, rng.next); s.floodDiscard = []; + s.floodKnown = []; } const id = s.floodDeck.shift(); + forgetKnown(s, id); const tile = s.tiles[id]; if (tile.state === 'dry') { tile.state = 'flooded'; @@ -499,36 +567,133 @@ export function resolveFlood(state) { s.floodDiscard.push(...phaseDiscard); rng.commit(); - // Forced swims for any pawn whose tile has sunk. - for (const p of s.players) { - if (isSunk(s, p.tileId)) { - const opts = swimOptions(s, p); - if (opts.length === 0) { s.phase = 'lost'; s.lossReason = `${ROLES[p.role].name} was lost beneath the waves.`; return s; } - // Auto-swim to the safest option (nearest dry tile, else nearest tile). - p.tileId = bestSwim(s, opts); - s.log.push({ kind: 'swim', seat: p.seat, tileId: p.tileId }); - } - } - + // A lost landing or treasure ends the game before anyone swims. const lost = checkLoss(s); if (lost) return lost; - // Advance to next player. + // Forced swims for any pawn whose tile has sunk. A pawn with nowhere to go + // drowns (loss). Computer partners swim at once; the human chooses. + s.pendingSwims = []; + for (const p of s.players) { + if (!isSunk(s, p.tileId)) continue; + const opts = swimOptions(s, p); + if (opts.length === 0) { s.phase = 'lost'; s.lossKind = 'crew'; s.lossSeat = p.seat; s.lossReason = `The ${ROLES[p.role].name} was lost beneath the waves.`; return s; } + if (p.isHuman && !autoSwim) { s.pendingSwims.push(p.seat); continue; } + p.tileId = bestSwim(s, opts); + s.log.push({ kind: 'swim', seat: p.seat, tileId: p.tileId }); + } + return finishFlood(s); +} + +// A drawn flood card leaves whichever known top segment held it. +function forgetKnown(s, id) { + if (!s.floodKnown?.length) return; + s.floodKnown = s.floodKnown.map((seg) => seg.filter((x) => x !== id)).filter((seg) => seg.length); +} + +// What a player may see: the state with both draw piles' ORDER hidden (sorted). +// Composition stays public (it is derivable from the discards), and floodKnown +// carries the only order knowledge players legitimately have. +export function publicView(state) { + const s = cloneState({ ...state, log: [] }); // planners never need history + s.floodDeck.sort(); + s.treasureDeck.sort(); + return s; +} + +// Probability each tile's flood card comes up in the next `draws` flood draws, +// from public knowledge only. Returns { tileId: p }. +export function floodDrawOdds(state, draws) { + const odds = {}; + let k = draws; + const inDeck = new Set(state.floodDeck); + const placed = new Set(); + for (const seg of state.floodKnown ?? []) { + const ids = seg.filter((id) => inDeck.has(id) && !placed.has(id)); + if (!ids.length) continue; + const p = k <= 0 ? 0 : Math.min(1, k / ids.length); + for (const id of ids) { odds[id] = p; placed.add(id); } + k -= ids.length; + } + const rest = state.floodDeck.filter((id) => !placed.has(id)); + const pRest = k <= 0 || !rest.length ? 0 : Math.min(1, k / rest.length); + for (const id of rest) odds[id] = pRest; + k -= rest.length; + // Deck runs dry → the discard is reshuffled and the remainder drawn from it. + if (k > 0 && state.floodDiscard.length) { + const p = Math.min(1, k / state.floodDiscard.length); + for (const id of state.floodDiscard) odds[id] = Math.max(odds[id] ?? 0, p); + } + return odds; +} + +// Either hand control to a pending swimmer or advance to the next turn. +function finishFlood(s) { + if (s.pendingSwims?.length) { + const seat = s.pendingSwims[0]; + s.phase = 'swim'; + s.pendingSwim = { seat, options: swimOptions(s, s.players[seat]) }; + return s; + } + s.pendingSwims = []; + s.pendingSwim = null; advanceTurn(s); return s; } +// Resolve the pending swim to `tileId` (must be one of its options). +export function resolveSwim(state, seat, tileId) { + if (state.phase !== 'swim' || state.pendingSwim?.seat !== seat || !state.pendingSwim.options.includes(tileId)) return state; + const s = cloneState(state); + s.players[seat].tileId = tileId; + s.log.push({ kind: 'swim', seat, tileId }); + s.pendingSwims = s.pendingSwims.filter((x) => x !== seat); + s.pendingSwim = null; + return finishFlood(s); +} + +export function swimChoices(state, seat) { + const p = state.players[seat]; + return p ? swimOptions(state, p) : []; +} + +// Where a pawn on a sinking tile may swim: adjacent (Explorer: diagonals too), +// the Pilot flies anywhere, the Diver swims to the nearest tile(s) however far. function swimOptions(state, player) { - if (player.role === 'diver') return diverDestinations(state, player.tileId); - const diagonal = player.role === 'explorer' || player.role === 'pilot'; + if (player.role === 'pilot') { + return Object.values(state.tiles).filter((t) => t.state !== 'sunk' && t.id !== player.tileId).map((t) => t.id); + } + if (player.role === 'diver') return nearestTiles(state, player.tileId); return adjacentTiles(state, player.tileId, { diagonal: player.role === 'explorer' }) .filter((id) => !isSunk(state, id)); } +// Non-sunk tiles at the smallest orthogonal step distance from `fromId`, +// stepping freely over sunk tiles (the island's footprint never changes). +function nearestTiles(state, fromId) { + const orth = neighbourTable(state).orth; + const seen = new Set([fromId]); + let frontier = [state.tiles[fromId]]; + while (frontier.length) { + const next = [], found = []; + for (const t of frontier) { + for (const id of orth[t.id]) { + if (seen.has(id)) continue; + seen.add(id); + const nt = state.tiles[id]; + if (nt.state === 'sunk') next.push(nt); else found.push(id); + } + } + if (found.length) return found; + frontier = next; + } + return []; +} + function bestSwim(state, opts) { const dry = opts.filter((id) => state.tiles[id].state === 'dry'); const pool = dry.length ? dry : opts; - // Prefer the tile closest to Fools' Landing. + // Prefer the tile closest to the Expedition Dock. const fl = state.tiles['fools-landing']; if (!fl || isSunk(state, 'fools-landing')) return pool[0]; let best = pool[0], bestD = Infinity; @@ -542,6 +707,7 @@ function bestSwim(state, opts) { function advanceTurn(state) { state.current = (state.current + 1) % state.players.length; + if (state.current === 0) state.round = (state.round ?? 1) + 1; state.actionsLeft = ACTIONS_PER_TURN; state.phase = 'actions'; state.players[state.current].pilotFlew = false; @@ -551,9 +717,9 @@ function advanceTurn(state) { // Returns a `lost`-phase clone if the game is over, else null. Safe to call on // any state. export function checkLoss(state) { - // Fools' Landing sunk. + // The Expedition Dock sunk. if (isSunk(state, 'fools-landing')) { - const s = cloneState(state); s.phase = 'lost'; s.lossReason = "Fools' Landing sank — there is no way off the island."; return s; + const s = cloneState(state); s.phase = 'lost'; s.lossKind = 'dock'; s.lossReason = 'The Expedition Dock sank. There is no way off the island.'; return s; } // A treasure became unreachable (both tiles sunk) and was never captured. for (const key of TREASURE_KEYS) { @@ -561,11 +727,11 @@ export function checkLoss(state) { if (captured) continue; const bothSunk = TREASURES[key].tiles.every((id) => isSunk(state, id)); if (bothSunk) { - const s = cloneState(state); s.phase = 'lost'; s.lossReason = `${TREASURES[key].name} was lost forever as its temples sank.`; return s; + const s = cloneState(state); s.phase = 'lost'; s.lossKind = 'relic'; s.lossTreasure = key; s.lossReason = `${TREASURES[key].name} was lost forever as both of its shrines sank.`; return s; } } if (state.waterLevel >= MAX_WATER) { - const s = cloneState(state); s.phase = 'lost'; s.lossReason = 'The water level reached the skull.'; return s; + const s = cloneState(state); s.phase = 'lost'; s.lossKind = 'gauge'; s.lossReason = 'The tide gauge hit the drowned mark. The island is gone.'; return s; } return null; } diff --git a/src/games/forbiddenisland/IslandPieces.js b/src/games/forbiddenisland/IslandPieces.js new file mode 100644 index 0000000..945b01b --- /dev/null +++ b/src/games/forbiddenisland/IslandPieces.js @@ -0,0 +1,261 @@ +// The Drowning Isle: the pieces on the table, i.e. the island tiles (the +// user's paintings set in carved stone slabs) and the crew figurines. +// +// TileView keeps one tile's display objects and animates the state changes: +// flooding (water sheen, tile starts to float and bob), sinking (tilt, bubbles, +// slides under to a drowned silhouette) and shoring up (water drains, sparkle). +// Figure is a painted wooden figurine that idles, hops, flies and swims. + +import * as Phaser from 'phaser'; +import { DEPTH, TILE, BODY_FONT, INK } from './IslandLayout.js'; +import { PAWN } from './IslandArt.js'; +import { TREASURES, ROLES, TILE_FRAME_ROW } from './IslandData.js'; + +const SLAB = TILE + 20; + +export class TileView { + constructor(scene, sea, tile, x, y, onClick) { + this.scene = scene; this.sea = sea; this.tile = tile; + this.id = tile.id; this.x = x; this.y = y; + this.row = TILE_FRAME_ROW[tile.id]; + this.state = null; + this.bob = null; + this.baseScale = 1; + this.hasArt = scene.textures.exists('forbiddenisland-tiles'); + + const c = this.container = scene.add.container(x, y).setDepth(DEPTH.tile); + this.shadow = scene.add.rectangle(5, 7, SLAB, SLAB, 0x000000, 0.42); + this.slab = scene.add.image(0, 0, 'di-slab').setDisplaySize(SLAB, SLAB); + this.art = this.hasArt + ? scene.add.image(0, 0, 'forbiddenisland-tiles', this.row * 2).setDisplaySize(TILE, TILE) + : scene.add.rectangle(0, 0, TILE, TILE, tile.treasure ? 0x7a7059 : 0x5c7d54); + this.water = scene.add.rectangle(0, 0, TILE, TILE, 0x1f6f96, 0); + this.sheen = scene.add.tileSprite(0, 0, TILE, TILE, 'di-caustic').setAlpha(0).setTileScale(0.7); + this.vignette = scene.add.graphics(); + this.vignette.lineStyle(6, 0x000000, 0.25); this.vignette.strokeRect(-TILE / 2 + 3, -TILE / 2 + 3, TILE - 6, TILE - 6); + this.plaque = scene.add.image(0, TILE / 2 - 12, 'di-plaque').setDisplaySize(TILE - 6, 20); + this.label = scene.add.text(0, TILE / 2 - 12, tile.name, { + fontFamily: BODY_FONT, fontSize: '11px', fontStyle: 'bold', color: '#2b1d08', + }).setOrigin(0.5); + for (let fs = 11; fs > 8 && this.label.width > TILE - 18; fs -= 0.5) this.label.setFontSize(fs); + const parts = [this.shadow, this.slab, this.art, this.water, this.sheen, this.vignette, this.plaque, this.label]; + this.seal = null; + if (tile.treasure) { + this.seal = scene.add.image(-TILE / 2 + 13, -TILE / 2 + 13, `di-seal-${tile.treasure}`).setDisplaySize(26, 26); + parts.push(this.seal); + } else if (tile.landing) { + const g = scene.add.graphics(); + g.fillStyle(0x000000, 0.45); g.fillCircle(-TILE / 2 + 14, -TILE / 2 + 14, 13); + g.fillStyle(0xc9a14a, 1); g.fillCircle(-TILE / 2 + 14, -TILE / 2 + 14, 11); + g.lineStyle(1.5, 0x3a2808, 1); g.strokeCircle(-TILE / 2 + 14, -TILE / 2 + 14, 8); + const h = scene.add.text(-TILE / 2 + 14, -TILE / 2 + 14, 'H', { fontFamily: BODY_FONT, fontSize: '12px', fontStyle: 'bold', color: '#2b1d08' }).setOrigin(0.5); + this.seal = scene.add.container(0, 0, [g, h]); + parts.push(this.seal); + } + this.hit = scene.add.rectangle(0, 0, TILE, TILE, 0x000000, 0).setInteractive({ useHandCursor: true }); + parts.push(this.hit); + c.add(parts); + this.hit.on('pointerup', () => onClick(tile.id)); + this.hit.on('pointerover', () => { if (!scene.busy && this.state !== 'sunk') c.setScale(this.baseScale * 1.03); }); + this.hit.on('pointerout', () => c.setScale(this.baseScale)); + sea?.addFoam(tile.id, x, y); + scene.events.on('update', this.update, this); + scene.events.once('shutdown', () => scene.events.off('update', this.update, this)); + } + + update(time, delta) { + if (this.sheen.alpha > 0) { + this.sheen.tilePositionX += delta * 0.02; + this.sheen.tilePositionY += delta * 0.008; + } + } + + setFrame(flooded) { + if (this.hasArt) this.art.setFrame(this.row * 2 + (flooded ? 1 : 0)); + } + + stopBob() { + if (this.bob) { this.bob.stop(); this.bob = null; } + this.container.setAngle(0); this.container.y = this.y; + } + + startBob() { + if (this.bob) return; + const c = this.container; + this.bob = this.scene.tweens.add({ + targets: c, y: { from: this.y - 1.5, to: this.y + 1.5 }, angle: { from: -1.4, to: 1.0 }, + duration: 2200 + Math.random() * 900, yoyo: true, repeat: -1, ease: 'Sine.easeInOut', + delay: Math.random() * 600, + }); + } + + // Snap to a state without animation (render path). Idempotent. + setState(state) { + if (state === this.state) return; + this.state = state; + this.sea?.setTileState(this.id, state); + const c = this.container; + this.scene.tweens.killTweensOf([this.water, this.sheen, this.art, this.slab, this.plaque, this.label, this.shadow]); + if (state === 'sunk') { + this.stopBob(); + this.setFrame(true); + this.baseScale = 0.92; c.setScale(0.92).setAngle(0); + this.art.setAlpha(0.2); if (this.art.setTint) this.art.setTint(0x2a5a6a); + this.slab.setAlpha(0.12); this.shadow.setAlpha(0); + this.water.setFillStyle(0x0b3443, 0.35); this.sheen.setAlpha(0.18); + this.plaque.setAlpha(0.18); this.label.setAlpha(0.3); this.vignette.setAlpha(0); + this.seal?.setAlpha(0.25); + this.hit.input.cursor = 'default'; + return; + } + this.baseScale = 1; c.setScale(1); + this.art.setAlpha(1); if (this.art.clearTint) this.art.clearTint(); + this.slab.setAlpha(1); this.shadow.setAlpha(state === 'flooded' ? 0.2 : 0.42); + this.plaque.setAlpha(1); this.label.setAlpha(1); this.vignette.setAlpha(1); this.seal?.setAlpha(1); + this.hit.input.cursor = 'pointer'; + if (state === 'flooded') { + this.setFrame(true); + this.water.setFillStyle(0x1f6f96, 0.2); this.sheen.setAlpha(0.5); + this.startBob(); + } else { + this.setFrame(false); + this.water.setFillStyle(0x1f6f96, 0); this.sheen.setAlpha(0); + this.stopBob(); + } + } + + // Water washes over the tile. + flood(onDone) { + const s = this.scene; + this.sea?.splash(this.x, this.y + 10, 22); + this.sea?.ripple(this.x, this.y, { size: TILE * 1.6 }); + this.state = null; + this.setState('flooded'); + this.water.setFillStyle(0x1f6f96, 0.55); this.sheen.setAlpha(0.9); + s.tweens.add({ targets: this.water, fillAlpha: 0.2, duration: 700, ease: 'Cubic.easeOut' }); + s.tweens.add({ targets: this.sheen, alpha: 0.5, duration: 900 }); + s.time.delayedCall(450, () => onDone?.()); + } + + // The tile tilts, shudders, bubbles and slides beneath the surface. + sink(onDone) { + const s = this.scene, c = this.container; + this.stopBob(); + this.sea?.setTileState(this.id, 'sunk'); + this.sea?.bubbles(this.x, this.y, 30); + s.tweens.add({ + targets: c, angle: 7, duration: 260, ease: 'Back.easeOut', + onComplete: () => { + s.tweens.add({ targets: c, x: { from: this.x - 4, to: this.x + 4 }, yoyo: true, repeat: 3, duration: 45 }); + s.tweens.add({ + targets: c, angle: -3, scale: 0.9, y: this.y + 6, duration: 900, delay: 200, ease: 'Cubic.easeIn', + onComplete: () => { + c.x = this.x; c.y = this.y; + this.state = null; this.setState('sunk'); + this.art.setAlpha(0.5); + s.tweens.add({ targets: this.art, alpha: 0.2, duration: 700 }); + this.sea?.ripple(this.x, this.y, { size: TILE * 2, duration: 1400 }); + this.sea?.ripple(this.x, this.y, { size: TILE * 1.3, duration: 1200, delay: 250 }); + onDone?.(); + }, + }); + s.tweens.add({ targets: [this.art, this.slab, this.plaque, this.label, this.shadow], alpha: 0.25, duration: 900, delay: 200 }); + s.tweens.add({ targets: this.water, fillAlpha: 0.55, duration: 900, delay: 200 }); + }, + }); + } + + // Water drains away; a quick glint of brass light. + shore() { + const s = this.scene; + this.state = null; + this.setState('dry'); + this.water.setFillStyle(0x1f6f96, 0.35); this.sheen.setAlpha(0.45); + s.tweens.add({ targets: this.water, fillAlpha: 0, duration: 700 }); + s.tweens.add({ targets: this.sheen, alpha: 0, duration: 700 }); + const glow = s.add.image(this.x, this.y, 'di-glow').setDepth(DEPTH.tileFx).setBlendMode(Phaser.BlendModes.ADD).setDisplaySize(TILE * 1.6, TILE * 1.6).setAlpha(0.7); + s.tweens.add({ targets: glow, alpha: 0, duration: 800, onComplete: () => glow.destroy() }); + } +} + +// ── figurines ──────────────────────────────────────────────────────────────── +export class Figure { + constructor(scene, player, { human = false } = {}) { + this.scene = scene; + this.seat = player.seat; + this.role = player.role; + const c = this.container = scene.add.container(0, 0).setDepth(DEPTH.pawn); + this.glow = scene.add.image(0, -4, 'di-glow').setDisplaySize(70, 34).setAlpha(0).setBlendMode(Phaser.BlendModes.ADD); + this.shadow = scene.add.image(2, -2, 'di-shadow').setDisplaySize(44, 14); + this.body = scene.add.image(0, 0, `di-pawn-${player.role}`).setOrigin(0.5, 1).setDisplaySize(PAWN.w * 0.8, PAWN.h * 0.8); + const parts = [this.glow, this.shadow]; + if (human) { + this.ring = scene.add.ellipse(0, -5, 40, 13).setStrokeStyle(2, 0xf0d070, 0.95); + parts.push(this.ring); + } + parts.push(this.body); + c.add(parts); + this.idle = scene.tweens.add({ + targets: this.body, y: -2.5, duration: 1100 + Math.random() * 500, yoyo: true, repeat: -1, ease: 'Sine.easeInOut', + delay: Math.random() * 800, + }); + this.active = false; + this.glowTween = null; + } + + setActive(on) { + if (on === this.active) return; + this.active = on; + if (this.glowTween) { this.glowTween.stop(); this.glowTween = null; } + if (on) { + this.glow.setTint(ROLES[this.role].color); + this.glowTween = this.scene.tweens.add({ targets: this.glow, alpha: { from: 0.35, to: 0.85 }, duration: 900, yoyo: true, repeat: -1 }); + } else this.glow.setAlpha(0); + } + + place(x, y) { this.container.setPosition(x, y); this.container.setDepth(DEPTH.pawn + y / 1000); } + setVisible(v) { this.container.setVisible(v); } + + // kind: 'walk' (a hop), 'fly' (a long arc high over the board), 'swim' + // (low and wet, with splashes), 'nav' (pushed along by the Cartographer). + moveTo(tx, ty, kind = 'walk', sea = null, onDone = () => {}) { + const s = this.scene, c = this.container; + const fx = c.x, fy = c.y; + const dist = Math.hypot(tx - fx, ty - fy); + const peak = kind === 'fly' ? 90 + dist * 0.12 : kind === 'swim' ? 0 : kind === 'nav' ? 16 : 22 + Math.min(30, dist * 0.08); + const duration = kind === 'fly' ? 900 + dist * 0.9 : kind === 'swim' ? 800 + dist * 1.2 : 520 + dist * 1.1; + c.setDepth(DEPTH.pawn + 5); + if (kind === 'swim' && sea) { sea.splash(fx, fy - 6, 14); sea.ripple(fx, fy - 4, { size: 70 }); } + this.idle?.pause(); + const prog = { t: 0 }; + s.tweens.add({ + targets: prog, t: 1, duration, ease: 'Sine.easeInOut', + onUpdate: () => { + const t = prog.t; + c.x = fx + (tx - fx) * t; + c.y = fy + (ty - fy) * t; + const lift = Math.sin(t * Math.PI) * peak; + this.body.y = -lift - (kind === 'swim' ? -9 + Math.sin(t * Math.PI * 6) * 2 : 0); + const sc = kind === 'fly' ? 1 + Math.sin(t * Math.PI) * 0.35 : 1; + this.body.setDisplaySize(PAWN.w * 0.8 * sc, PAWN.h * 0.8 * sc); + this.shadow.setAlpha(1 - Math.min(0.7, lift / 140)).setDisplaySize(44 * (1 - Math.min(0.5, lift / 200)), 14); + if (kind === 'swim') this.body.setAlpha(0.75); + }, + onComplete: () => { + this.body.y = 0; this.body.setAlpha(1).setDisplaySize(PAWN.w * 0.8, PAWN.h * 0.8); + this.shadow.setAlpha(1).setDisplaySize(44, 14); + if (kind === 'swim' && sea) sea.splash(tx, ty - 6, 12); + if (sea && kind !== 'fly') sea.ripple(tx, ty - 4, { size: 54, duration: 600, alpha: 0.4 }); + this.place(tx, ty); + this.idle?.resume(); + onDone(); + }, + }); + } + + destroy() { this.idle?.stop(); this.glowTween?.stop(); this.container.destroy(); } +} + +// Relic accent colour for UI chips. +export function relicColor(key) { return TREASURES[key]?.color ?? 0xffffff; } +export { INK }; diff --git a/src/games/forbiddenisland/IslandSea.js b/src/games/forbiddenisland/IslandSea.js new file mode 100644 index 0000000..f760437 --- /dev/null +++ b/src/games/forbiddenisland/IslandSea.js @@ -0,0 +1,115 @@ +// The Drowning Isle: the living sea around the island. +// +// Three scrolling layers (base swell, two caustic sheets) cover the screen, a +// lighter shallows glow sits under the island, and every tile has a ring of surf +// that breathes with the swell. The sea darkens and quickens as the tide gauge +// climbs. Effects (ripples, splashes, bubbles) are fire-and-forget. + +import * as Phaser from 'phaser'; +import { W, H, DEPTH, TILE, BX0, BY0, BOARD_W } from './IslandLayout.js'; + +const lerp = (a, b, t) => a + (b - a) * t; +function lerpColor(a, b, t) { + const r = Math.round(lerp((a >> 16) & 255, (b >> 16) & 255, t)); + const g = Math.round(lerp((a >> 8) & 255, (b >> 8) & 255, t)); + const bl = Math.round(lerp(a & 255, b & 255, t)); + return (r << 16) | (g << 8) | bl; +} + +export class IslandSea { + constructor(scene) { + this.scene = scene; + this.level = 1; + this.t = 0; + this.base = scene.add.tileSprite(0, 0, W, H, 'di-water').setOrigin(0).setDepth(DEPTH.sea).setTileScale(1.8); + this.caustic = scene.add.tileSprite(0, 0, W, H, 'di-caustic').setOrigin(0).setDepth(DEPTH.sea) + .setTileScale(1.4).setAlpha(0.28).setBlendMode(Phaser.BlendModes.ADD); + this.caustic2 = scene.add.tileSprite(0, 0, W, H, 'di-caustic').setOrigin(0).setDepth(DEPTH.sea) + .setTileScale(2.3).setAlpha(0.16).setBlendMode(Phaser.BlendModes.ADD); + // Shallows: a pale turquoise glow under the island. + const cx = BX0 + BOARD_W / 2, cy = BY0 + BOARD_W / 2; + this.shallows = scene.add.image(cx, cy, 'di-glow').setDepth(DEPTH.sea) + .setDisplaySize(BOARD_W * 1.5, BOARD_W * 1.5).setTint(0x5fd0c0).setAlpha(0.32).setBlendMode(Phaser.BlendModes.ADD); + this.foams = {}; + scene.events.on('update', this.update, this); + scene.events.once('shutdown', () => this.destroy()); + } + + destroy() { + this.scene.events.off('update', this.update, this); + } + + addFoam(id, x, y) { + const f = this.scene.add.image(x, y, 'di-foam').setDepth(DEPTH.foam); + f.setDisplaySize(f.width / 2, f.height / 2); + f.baseScale = f.scaleX; + f.phase = Math.random() * Math.PI * 2; + f.strength = 0.7; + this.foams[id] = f; + } + + // dry: gentle surf; flooded: heavy surf; sunk: none. + setTileState(id, state) { + const f = this.foams[id]; if (!f) return; + f.strength = state === 'sunk' ? 0 : state === 'flooded' ? 1.25 : 0.7; + } + + setLevel(level) { + this.level = level; + const k = Math.min(1, (level - 1) / 8); + // calm teal → slate storm water + this.base.setTint(lerpColor(0xffffff, 0x8a9aa6, k)); + this.shallows.setAlpha(lerp(0.32, 0.12, k)); + this.caustic.setAlpha(lerp(0.28, 0.16, k)); + } + + update(time, delta) { + const dt = Math.min(delta, 100); + const speed = 1 + (this.level - 1) * 0.14; + this.t += dt; + this.base.tilePositionX += dt * 0.010 * speed; + this.base.tilePositionY += dt * 0.004 * speed; + this.caustic.tilePositionX -= dt * 0.016 * speed; + this.caustic.tilePositionY += dt * 0.007 * speed; + this.caustic2.tilePositionX += dt * 0.006 * speed; + this.caustic2.tilePositionY -= dt * 0.011 * speed; + const surge = 0.03 + this.level * 0.004; + for (const f of Object.values(this.foams)) { + const s = Math.sin(this.t / (1100 - this.level * 40) + f.phase); + const targetA = f.strength * (0.55 + 0.25 * s); + f.alpha += (targetA - f.alpha) * Math.min(1, dt / 300); + f.setScale(f.baseScale * (1 + surge * (0.5 + 0.5 * s) * f.strength)); + } + } + + // ── one-shot effects ─────────────────────────────────────────────────────── + ripple(x, y, { size = TILE * 1.2, duration = 1100, depth = DEPTH.tileFx, alpha = 0.7, delay = 0 } = {}) { + const r = this.scene.add.image(x, y, 'di-ring').setDepth(depth).setAlpha(0).setDisplaySize(16, 10); + this.scene.tweens.add({ + targets: r, displayWidth: size, displayHeight: size * 0.62, delay, + alpha: { from: alpha, to: 0 }, duration, ease: 'Cubic.easeOut', + onComplete: () => r.destroy(), + }); + } + + splash(x, y, n = 18) { + const p = this.scene.add.particles(x, y, 'di-drop', { + speed: { min: 80, max: 220 }, angle: { min: 200, max: 340 }, gravityY: 520, + lifespan: 700, scale: { start: 0.9, end: 0.2 }, alpha: { start: 0.95, end: 0 }, + emitting: false, + }).setDepth(DEPTH.tileFx + 1); + p.explode(n); + this.scene.time.delayedCall(900, () => p.destroy()); + } + + bubbles(x, y, n = 14, spread = TILE * 0.4) { + const p = this.scene.add.particles(x, y, 'di-bubble', { + x: { min: -spread, max: spread }, y: { min: -spread * 0.6, max: spread * 0.6 }, + speedY: { min: -60, max: -20 }, speedX: { min: -10, max: 10 }, + lifespan: { min: 600, max: 1300 }, scale: { start: 0.4, end: 1.1 }, alpha: { start: 0.9, end: 0 }, + frequency: 60, quantity: 2, + }).setDepth(DEPTH.tileFx + 1); + this.scene.time.delayedCall(Math.max(200, n * 30), () => p.stop()); + this.scene.time.delayedCall(Math.max(200, n * 30) + 1400, () => p.destroy()); + } +} diff --git a/src/games/forbiddenisland/IslandSound.js b/src/games/forbiddenisland/IslandSound.js new file mode 100644 index 0000000..b061149 --- /dev/null +++ b/src/games/forbiddenisland/IslandSound.js @@ -0,0 +1,205 @@ +// The Drowning Isle: Web Audio synths. No audio files; silent without Web +// Audio or when the game is muted. Every call is wrapped so audio can never +// break the game. +// +// Ambience surf on the reef, wind and rain. All three swell with +// the tide gauge (setLevel) +// splash(scene) water slapping over a tile +// sink(scene) a deep gurgle and a run of bubbles +// shore(scene) sandbags thumped into place and a shovel scrape +// card(scene) a card flicked off the deck +// give(scene) a card slid across to a teammate +// step(scene) boots on wet stone +// capture(scene) a brass chime arpeggio as a relic is recovered +// watersRise(scene) a low horn swell under a rush of water +// thunder(scene, near) a crack and a long rolling rumble +// rotor(scene, sec) helicopter blades, chopping and fading +// sting(scene, kind) 'win' | 'lose' +// click(scene) a typewriter key, for journal buttons + +function ctxOf(scene) { + const sm = scene?.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 3), ac.sampleRate); + const d = buf.getChannelData(0); + let b = 0; + for (let i = 0; i < d.length; i++) { const w = Math.random() * 2 - 1; b = 0.97 * b + 0.03 * w; d[i] = w * 0.6 + b * 2.2; } + noiseCache.set(ac, buf); + return buf; +} +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} +function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.004 } = {}) { + const o = ac.createOscillator(); o.type = type; + o.frequency.setValueAtTime(f, t0); + if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.05); +} +function hiss(ac, dest, t0, { f = 1000, q = 1, type = 'bandpass', a = 1, d = 0.2, attack = 0.005, fEnd = null } = {}) { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = type; bp.frequency.setValueAtTime(f, t0); bp.Q.value = q; + if (fEnd) bp.frequency.exponentialRampToValueAtTime(fEnd, t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + n.connect(bp); bp.connect(g); g.connect(dest); + n.start(t0, Math.random() * 2); n.stop(t0 + d + 0.05); +} +const play = (scene, gain, fn) => { + try { const ac = ctxOf(scene); if (!ac) return; fn(ac, out(scene, ac, gain), ac.currentTime + 0.01); } catch (_) { /* decoration */ } +}; + +export const splash = (scene, v = 1) => play(scene, 0.35 * v, (ac, o, t) => { + hiss(ac, o, t, { f: 2400, q: 0.7, a: 0.9, d: 0.35, fEnd: 700 }); + hiss(ac, o, t + 0.05, { f: 600, q: 1, a: 0.6, d: 0.5, fEnd: 250 }); + for (let i = 0; i < 4; i++) tone(ac, o, t + 0.08 + i * 0.05, 900 + Math.random() * 900, { a: 0.08, d: 0.05, glide: 1.6 }); +}); + +export const sink = (scene) => play(scene, 0.45, (ac, o, t) => { + hiss(ac, o, t, { f: 300, q: 2, type: 'lowpass', a: 1, d: 1.6, attack: 0.1, fEnd: 90 }); + tone(ac, o, t, 110, { type: 'sine', a: 0.5, d: 1.4, glide: 0.5, attack: 0.05 }); + for (let i = 0; i < 9; i++) { + const tt = t + 0.25 + i * 0.11 + Math.random() * 0.05; + tone(ac, o, tt, 260 + Math.random() * 500, { a: 0.12, d: 0.07, glide: 1.9 }); + } +}); + +export const shore = (scene) => play(scene, 0.4, (ac, o, t) => { + for (let i = 0; i < 2; i++) { + hiss(ac, o, t + i * 0.18, { f: 160, q: 1.5, type: 'lowpass', a: 1, d: 0.16 }); + tone(ac, o, t + i * 0.18, 70, { a: 0.6, d: 0.12, glide: 0.7 }); + } + hiss(ac, o, t + 0.42, { f: 3200, q: 2, a: 0.25, d: 0.25, fEnd: 1800 }); +}); + +export const card = (scene) => play(scene, 0.25, (ac, o, t) => { + hiss(ac, o, t, { f: 4200, q: 1.2, a: 0.7, d: 0.09, fEnd: 2000 }); +}); + +export const give = (scene) => play(scene, 0.25, (ac, o, t) => { + hiss(ac, o, t, { f: 2500, q: 0.8, a: 0.5, d: 0.35, attack: 0.08, fEnd: 5200 }); + tone(ac, o, t + 0.3, 880, { a: 0.12, d: 0.25 }); +}); + +export const step = (scene) => play(scene, 0.2, (ac, o, t) => { + hiss(ac, o, t, { f: 400, q: 1, a: 0.6, d: 0.08 }); + hiss(ac, o, t + 0.22, { f: 380, q: 1, a: 0.5, d: 0.08 }); +}); + +export const capture = (scene) => play(scene, 0.3, (ac, o, t) => { + const notes = [392, 494, 587, 784, 988]; + notes.forEach((f, i) => { + tone(ac, o, t + i * 0.11, f, { type: 'triangle', a: 0.5, d: 1.4 }); + tone(ac, o, t + i * 0.11, f * 2.01, { type: 'sine', a: 0.12, d: 0.9 }); + }); + tone(ac, o, t + 0.6, 196, { type: 'sine', a: 0.5, d: 2.2, attack: 0.2 }); +}); + +export const watersRise = (scene) => play(scene, 0.45, (ac, o, t) => { + tone(ac, o, t, 55, { type: 'sawtooth', a: 0.25, d: 2.4, glide: 1.12, attack: 0.6 }); + tone(ac, o, t, 82.4, { type: 'triangle', a: 0.35, d: 2.4, glide: 1.12, attack: 0.6 }); + hiss(ac, o, t + 0.1, { f: 500, q: 0.6, type: 'lowpass', a: 0.9, d: 2.2, attack: 0.7, fEnd: 1400 }); +}); + +export const thunder = (scene, near = 0.6) => play(scene, 0.5 * near + 0.15, (ac, o, t) => { + hiss(ac, o, t, { f: 2600, q: 0.5, a: near, d: 0.25, fEnd: 400 }); + const lag = (1 - near) * 0.8; + hiss(ac, o, t + lag, { f: 180, q: 0.7, type: 'lowpass', a: 1, d: 3.5, attack: 0.25, fEnd: 50 }); + hiss(ac, o, t + lag + 0.6, { f: 120, q: 0.7, type: 'lowpass', a: 0.7, d: 2.5, attack: 0.3, fEnd: 45 }); +}); + +export const rotor = (scene, sec = 3) => play(scene, 0.35, (ac, o, t) => { + const n = Math.floor(sec * 11); + for (let i = 0; i < n; i++) { + const k = i / n, amp = Math.sin(Math.PI * Math.min(1, k * 1.6)) * (1 - k * 0.5); + hiss(ac, o, t + i * 0.09, { f: 180, q: 1.4, type: 'lowpass', a: amp, d: 0.07 }); + } + tone(ac, o, t, 95, { type: 'sawtooth', a: 0.06, d: sec, glide: 1.3, attack: 0.5 }); +}); + +export const sting = (scene, kind) => play(scene, 0.3, (ac, o, t) => { + const seq = kind === 'win' ? [523, 659, 784, 1047, 784, 1047] : [392, 349, 311, 262]; + seq.forEach((f, i) => tone(ac, o, t + i * (kind === 'win' ? 0.14 : 0.32), f, { type: 'triangle', a: 0.45, d: kind === 'win' ? 0.9 : 1.4 })); + if (kind !== 'win') tone(ac, o, t, 65, { type: 'sine', a: 0.5, d: 3, attack: 0.4 }); +}); + +export const click = (scene) => play(scene, 0.18, (ac, o, t) => { + hiss(ac, o, t, { f: 3000, q: 3, a: 0.8, d: 0.03 }); + tone(ac, o, t, 1800, { type: 'square', a: 0.05, d: 0.02 }); +}); + +// Looped surf, wind and rain beds. Started once per scene; follows the tide +// gauge; stops on shutdown or when the game is muted. +export class Ambience { + constructor(scene) { + this.scene = scene; + this.level = 1; + this.nodes = null; + this.timer = scene.time.addEvent({ delay: 500, loop: true, callback: () => this.tick() }); + scene.events.once('shutdown', () => this.stop()); + } + + start() { + try { + const ac = ctxOf(this.scene); if (!ac || this.nodes) return; + const master = out(this.scene, ac, 0); + const bed = (f, type, q) => { + const n = ac.createBufferSource(); n.buffer = noise(ac); n.loop = true; + const flt = ac.createBiquadFilter(); flt.type = type; flt.frequency.value = f; flt.Q.value = q; + const g = ac.createGain(); g.gain.value = 0; + n.connect(flt); flt.connect(g); g.connect(master); n.start(); + return { n, flt, g }; + }; + this.nodes = { ac, master, surf: bed(420, 'lowpass', 0.7), wind: bed(700, 'bandpass', 1.6), rain: bed(5200, 'highpass', 0.4) }; + master.gain.linearRampToValueAtTime(0.5, ac.currentTime + 3); + this.apply(); + } catch (_) { this.nodes = null; } + } + + setLevel(level) { this.level = level; this.apply(); } + + apply() { + const n = this.nodes; if (!n) return; + const k = Math.min(1, (this.level - 1) / 8); + const t = n.ac.currentTime; + n.wind.g.gain.linearRampToValueAtTime(0.05 + k * 0.22, t + 2); + n.rain.g.gain.linearRampToValueAtTime(0.03 + k * 0.12, t + 2); + } + + // Slow swells on the surf and gusts on the wind. + tick() { + const sm = this.scene.sound; + if (sm?.mute) { this.stop(); return; } + if (!this.nodes) { this.start(); return; } + const n = this.nodes, t = n.ac.currentTime; + const k = Math.min(1, (this.level - 1) / 8); + const swell = 0.5 + 0.5 * Math.sin(t / 3.2); + n.surf.g.gain.linearRampToValueAtTime(0.18 + swell * (0.2 + k * 0.2), t + 0.5); + n.surf.flt.frequency.linearRampToValueAtTime(300 + swell * 500, t + 0.5); + n.wind.flt.frequency.linearRampToValueAtTime(500 + Math.random() * (500 + k * 900), t + 0.5); + } + + stop() { + const n = this.nodes; this.nodes = null; + if (!n) return; + try { + n.master.gain.linearRampToValueAtTime(0, n.ac.currentTime + 0.4); + setTimeout(() => { for (const b of [n.surf, n.wind, n.rain]) { try { b.n.stop(); } catch (_) { /* */ } } n.master.disconnect(); }, 600); + } catch (_) { /* */ } + } +} diff --git a/src/games/forbiddenisland/IslandStore.js b/src/games/forbiddenisland/IslandStore.js new file mode 100644 index 0000000..012b940 --- /dev/null +++ b/src/games/forbiddenisland/IslandStore.js @@ -0,0 +1,84 @@ +// The Drowning Isle: what persists between visits (localStorage, when there is +// one). Nothing here throws: storage is a convenience, never a requirement. +// +// save / loadSave / clearSave the expedition in progress, written at the +// start of each of your turns +// readRecord / recordResult lifetime stats: expeditions, escapes, best +// (fewest days), streaks, per island shape, +// and the daily expedition log +// dailySetup(date) the seed, island and crew for today's +// expedition, the same for everyone + +import { LAYOUT_KEYS, ROLE_KEYS } from './IslandData.js'; + +const SAVE_KEY = 'drowningisle.save.v1'; +const RECORD_KEY = 'drowningisle.record.v1'; +const ls = () => { try { return globalThis.localStorage ?? null; } catch (_) { return null; } }; + +export function save(data) { + try { ls()?.setItem(SAVE_KEY, JSON.stringify({ v: 1, savedAt: Date.now(), ...data })); return true; } catch (_) { return false; } +} +export function loadSave() { + try { + const d = JSON.parse(ls()?.getItem(SAVE_KEY) || 'null'); + return d && d.v === 1 && d.gs && d.gs.phase !== 'won' && d.gs.phase !== 'lost' ? d : null; + } catch (_) { return null; } +} +export function clearSave() { try { ls()?.removeItem(SAVE_KEY); } catch (_) { /* */ } } + +export function readRecord() { + try { + const r = JSON.parse(ls()?.getItem(RECORD_KEY) || '{}') || {}; + return { played: 0, won: 0, streak: 0, bestStreak: 0, bestDays: null, relics: 0, byLayout: {}, byDifficulty: {}, daily: {}, ...r }; + } catch (_) { return { played: 0, won: 0, streak: 0, bestStreak: 0, bestDays: null, relics: 0, byLayout: {}, byDifficulty: {}, daily: {} }; } +} + +// Returns the updated record plus flags for the end screen. +export function recordResult({ won, days, relics, layout, difficulty, daily = null }) { + const r = readRecord(); + const flags = {}; + r.played += 1; + r.relics += relics; + if (won) { + r.won += 1; r.streak += 1; + if (r.streak > r.bestStreak) { r.bestStreak = r.streak; flags.bestStreak = r.streak > 1; } + if (r.bestDays == null || days < r.bestDays) { flags.bestDays = r.bestDays != null; r.bestDays = days; } + } else r.streak = 0; + const bump = (obj, k) => { obj[k] = obj[k] ?? { played: 0, won: 0 }; obj[k].played += 1; if (won) obj[k].won += 1; }; + bump(r.byLayout, layout); + bump(r.byDifficulty, difficulty); + if (daily) { + const prev = r.daily[daily]; + if (!prev) flags.firstDaily = true; + if (!prev || (won && !prev.won) || (won && prev.won && days < prev.days)) r.daily[daily] = { won, days, relics }; + // keep the last 60 days only + const keys = Object.keys(r.daily).sort(); + while (keys.length > 60) delete r.daily[keys.shift()]; + } + try { ls()?.setItem(RECORD_KEY, JSON.stringify(r)); } catch (_) { /* */ } + return { record: r, flags }; +} + +// ── daily expedition ───────────────────────────────────────────────────────── +export function todayKey(date = new Date()) { + const p = (n) => String(n).padStart(2, '0'); + return `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())}`; +} + +function hash(str) { + let h = 2166136261 >>> 0; + for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; } + return h >>> 0; +} + +// Same date → same seed, island shape and crew order, on every machine. +export function dailySetup(date = new Date()) { + const key = todayKey(date); + const seed = hash(`drowning-isle:${key}`); + const layout = LAYOUT_KEYS[seed % LAYOUT_KEYS.length]; + let a = seed; + const rnd = () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + const roles = ROLE_KEYS.slice(); + for (let i = roles.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [roles[i], roles[j]] = [roles[j], roles[i]]; } + return { key, seed, layout, roles }; +} diff --git a/src/games/forbiddenisland/IslandStorm.js b/src/games/forbiddenisland/IslandStorm.js new file mode 100644 index 0000000..f9db38c --- /dev/null +++ b/src/games/forbiddenisland/IslandStorm.js @@ -0,0 +1,86 @@ +// The Drowning Isle: the monsoon. The storm follows the tide gauge: clouds +// thicken, the light drops, rain goes from drizzle to sheets, and from gauge 6 +// lightning starts to crack over the island. `strike()` is also called directly +// for dramatic moments (Waters Rise, a sinking shrine). + +import * as Phaser from 'phaser'; +import { W, H, DEPTH, RAIL_X } from './IslandLayout.js'; +import * as Sound from './IslandSound.js'; + +export class IslandStorm { + constructor(scene) { + this.scene = scene; + this.level = 0; + this.wind = 0; + this.clouds = scene.add.tileSprite(0, 0, W, H, 'di-cloud').setOrigin(0).setDepth(DEPTH.sky).setAlpha(0).setTileScale(2.2); + // Dims the sea, island and pawns, but never the journal or dialogs. + this.dim = scene.add.rectangle(0, 0, RAIL_X - 30, H, 0x061018, 0).setOrigin(0).setDepth(DEPTH.rain - 1); + this.flashRect = scene.add.rectangle(0, 0, W, H, 0xe8f4ff, 0).setOrigin(0).setDepth(DEPTH.flash); + this.rain = scene.add.particles(0, 0, 'di-rain', { + x: { min: -200, max: RAIL_X + 100 }, y: -50, + speedY: { min: 900, max: 1250 }, speedX: { min: -140, max: -80 }, + lifespan: 1300, alpha: { start: 0.45, end: 0.2 }, scaleY: { min: 0.6, max: 1.1 }, + rotate: 6, frequency: 80, quantity: 1, + }).setDepth(DEPTH.rain); + this.nextStrike = 0; + scene.events.on('update', this.update, this); + scene.events.once('shutdown', () => scene.events.off('update', this.update, this)); + } + + setLevel(level) { + if (level === this.level) return; + this.level = level; + const k = Math.min(1, (level - 1) / 8); + this.scene.tweens.add({ targets: this.clouds, alpha: 0.15 + k * 0.6, duration: 1800 }); + this.scene.tweens.add({ targets: this.dim, fillAlpha: k * 0.32, duration: 1800 }); + // drizzle → downpour + const freq = Math.round(Phaser.Math.Linear(70, 6, k)); + const qty = 1 + Math.round(k * 3); + this.rain.setFrequency(freq, qty); + this.rain.particleRotate = 6 + k * 10; + if (level >= 6 && !this.nextStrike) this.nextStrike = this.scene.time.now + 2500; + } + + update(time, delta) { + const k = Math.min(1, (this.level - 1) / 8); + this.clouds.tilePositionX -= delta * (0.012 + k * 0.03); + this.clouds.tilePositionY += delta * 0.002; + if (this.level >= 6 && this.nextStrike && time >= this.nextStrike) { + this.strike(); + const gap = Phaser.Math.Linear(14000, 5000, (this.level - 6) / 3); + this.nextStrike = time + gap * (0.6 + Math.random() * 0.8); + } + } + + // A lightning strike: double flicker plus a forked bolt somewhere over the sea. + strike({ x = 80 + Math.random() * (RAIL_X - 200), bright = 0.55 } = {}) { + const s = this.scene; + const g = s.add.graphics().setDepth(DEPTH.flash); + const yEnd = 260 + Math.random() * 520; + const pts = [[x, -10]]; + let cx = x, cy = -10; + while (cy < yEnd) { cy += 30 + Math.random() * 40; cx += (Math.random() - 0.5) * 70; pts.push([cx, cy]); } + const draw = (w, c, a) => { + g.lineStyle(w, c, a); g.beginPath(); g.moveTo(pts[0][0], pts[0][1]); + for (const p of pts.slice(1)) g.lineTo(p[0], p[1]); + g.strokePath(); + }; + draw(12, 0x9fd8ff, 0.18); draw(5, 0xcfeaff, 0.5); draw(2, 0xffffff, 1); + // a fork + const fi = 1 + Math.floor(Math.random() * (pts.length - 2)); + let fx = pts[fi][0], fy = pts[fi][1]; + g.lineStyle(1.5, 0xffffff, 0.8); g.beginPath(); g.moveTo(fx, fy); + for (let i = 0; i < 4; i++) { fx += (Math.random() < 0.5 ? -1 : 1) * (10 + Math.random() * 25); fy += 25 + Math.random() * 25; g.lineTo(fx, fy); } + g.strokePath(); + s.tweens.add({ targets: g, alpha: 0, duration: 420, delay: 90, onComplete: () => g.destroy() }); + this.flashRect.setFillStyle(0xe8f4ff, bright); + s.tweens.add({ + targets: this.flashRect, fillAlpha: 0, duration: 110, + onComplete: () => { + this.flashRect.setFillStyle(0xe8f4ff, bright * 0.6); + s.tweens.add({ targets: this.flashRect, fillAlpha: 0, duration: 380 }); + }, + }); + Sound.thunder(s, bright); + } +} diff --git a/src/games/forbiddenisland/IslandTalk.js b/src/games/forbiddenisland/IslandTalk.js new file mode 100644 index 0000000..e88bb37 --- /dev/null +++ b/src/games/forbiddenisland/IslandTalk.js @@ -0,0 +1,113 @@ +// The Drowning Isle: crew table talk. IslandChat writes each partner's own +// announcements; this module makes the crew react to one another (a cheer for +// a capture, thanks for Sandbags, alarm at a Waters Rise) in their own voices, +// and shows short speech bubbles over the figurines on the island. + +import { ROLES, TREASURES } from './IslandData.js'; +import { DEPTH, BODY_FONT } from './IslandLayout.js'; + +const pick = (arr) => arr[Math.floor(Math.random() * arr.length)]; + +// Reactions by voice. `{who}` is the crew member being reacted to, `{tile}` a +// tile name, `{relic}` a relic name. +const REACT = { + breezy: { + capture: ['Ha! Lovely flying, {who}.', 'That is one for the logbook, {who}!', 'Smashing. Three to go, or fewer!'], + sinkShrine: ['Well, that is one shrine fewer to land on.', 'Steady. We still have the other shrine for {relic}.'], + watersRise: ['Getting choppy out there, chaps.', 'Bit of weather. Keep your hats on.'], + thanks: ['Cheers, {who}. I owe you a drink at the club.', 'Much obliged, {who}!'], + dockWet: ['The dock is under water! That is our only runway home.', 'Someone keep the dock dry, please. I would rather not swim to Singapore.'], + }, + gruff: { + capture: ['Good. Next.', 'About time, {who}. Nicely done.', 'One less to worry about.'], + sinkShrine: ['Lost {tile}. The other shrine for {relic} had better hold.', 'There goes {tile}. Told you the footings were rotten.'], + watersRise: ['Water is coming up. Brace everything.', 'Here it comes. Shovels, everyone.'], + thanks: ['Ta, {who}.', 'Right. Good. Thanks, {who}.'], + dockWet: ['Dock is flooded. Somebody shore it, now.', 'If the dock goes we all go. Fix it.'], + }, + crisp: { + capture: ['Confirmed: {relic} recovered. Good work, {who}.', 'Logging the recovery, {who}. Well done.'], + sinkShrine: ['Report: {tile} is lost. {relic} has one shrine left.', 'Be advised, {tile} has gone under.'], + watersRise: ['Weather warning: the tide is rising.', 'All stations, the tide gauge is climbing.'], + thanks: ['Received, {who}. Thank you.', 'Copy that, {who}. Much appreciated.'], + dockWet: ['Priority: the Expedition Dock is flooded.', 'All stations: the dock needs shoring.'], + }, + professorial: { + capture: ['Remarkable! {relic}, intact. Bravo, {who}.', 'A find for the museum, {who}. Splendid.'], + sinkShrine: ['A tragedy for scholarship. {tile} is gone.', 'Note it in the survey: {tile}, lost. {relic} has one shrine remaining.'], + watersRise: ['The tide tables did not predict this. Most irregular.', 'Fascinating, and rather alarming. The sea is rising.'], + thanks: ['Most kind, {who}. Most kind.', 'Thank you, {who}. I shall mention you in the monograph.'], + dockWet: ['Our sole line of retreat, the dock, is awash.', 'The dock, colleagues! The dock is flooding!'], + }, + laconic: { + capture: ['Nice.', 'Good one, {who}.', 'Mm. Well done.'], + sinkShrine: ['{tile}. Gone.', 'Lost {tile}.'], + watersRise: ['Water is up.', 'Rising.'], + thanks: ['Thanks, {who}.', 'Mm. Thanks.'], + dockWet: ['Dock is wet.', 'Watch the dock.'], + }, + eager: { + capture: ['Yes! {relic}! Brilliant, {who}!', 'What a find, {who}!'], + sinkShrine: ['Oh no, {tile}! We still have the other shrine, though!', '{tile} has gone! Right, onward.'], + watersRise: ['Whoa, the sea is really coming in now!', 'Big swell! Hold on to something!'], + thanks: ['Thank you, {who}! You are a marvel!', 'Brilliant, {who}, thanks!'], + dockWet: ['The dock is flooding! I can get there if someone needs me!', 'Look, the dock! Somebody shore it up!'], + }, +}; + +function fill(text, ctx) { + return text.replace(/\{who\}/g, ctx.who ?? 'everyone') + .replace(/\{tile\}/g, ctx.tile ?? 'that tile') + .replace(/\{relic\}/g, TREASURES[ctx.relic]?.name ?? 'the relic'); +} + +// A reaction from one of the computer partners (never the human, never the +// actor), or null. `crew` is [{ seat, role, isHuman }]. `chance` keeps the +// log from filling with chatter. +export function reaction(kind, ctx, crew, chance = 0.55) { + if (Math.random() > chance) return null; + const pool = ctx.speakerSeat != null + ? crew.filter((c) => c.seat === ctx.speakerSeat && !c.isHuman) + : crew.filter((c) => !c.isHuman && c.seat !== ctx.actorSeat); + if (!pool.length) return null; + const c = pick(pool); + const lines = REACT[ROLES[c.role]?.voice]?.[kind]; + if (!lines) return null; + return { seat: c.seat, role: c.role, text: fill(pick(lines), ctx) }; +} + +// Short speech bubbles over the figurines. +export class Bubbles { + constructor(scene) { + this.scene = scene; + this.bySeat = {}; + } + + show(seat, x, y, text, ms = 2600) { + const s = this.scene; + this.bySeat[seat]?.destroy(); + let t = text.split(/(?<=[.!?])\s/)[0]; + if (t.length > 70) t = `${t.slice(0, 67)}…`; + const label = s.add.text(0, 0, t, { + fontFamily: BODY_FONT, fontSize: '14px', fontStyle: 'italic', color: '#2b1d08', + wordWrap: { width: 190 }, align: 'center', + }).setOrigin(0.5, 1); + const w = label.width + 20, h = label.height + 12; + const g = s.add.graphics(); + g.fillStyle(0x000000, 0.25); g.fillRoundedRect(-w / 2 + 3, -h - 10 + 3, w, h, 9); + g.fillStyle(0xf2e6cc, 0.97); g.fillRoundedRect(-w / 2, -h - 10, w, h, 9); + g.fillTriangle(-7, -11, 7, -11, 0, 0); + g.lineStyle(1.5, 0x5a4020, 0.9); g.strokeRoundedRect(-w / 2, -h - 10, w, h, 9); + label.setPosition(0, -16); + const bx = Math.max(w / 2 + 8, Math.min(780 - w / 2, x)); + const c = s.add.container(bx, y - 52, [g, label]).setDepth(DEPTH.popup - 2).setAlpha(0).setScale(0.8); + this.bySeat[seat] = c; + s.tweens.add({ targets: c, alpha: 1, scale: 1, duration: 180, ease: 'Back.easeOut' }); + s.time.delayedCall(ms, () => { + if (this.bySeat[seat] !== c) return; + s.tweens.add({ targets: c, alpha: 0, y: c.y - 10, duration: 300, onComplete: () => { c.destroy(); if (this.bySeat[seat] === c) delete this.bySeat[seat]; } }); + }); + } + + clear() { for (const c of Object.values(this.bySeat)) c.destroy(); this.bySeat = {}; } +} diff --git a/src/games/forbiddenisland/IslandWorker.js b/src/games/forbiddenisland/IslandWorker.js new file mode 100644 index 0000000..f18aef5 --- /dev/null +++ b/src/games/forbiddenisland/IslandWorker.js @@ -0,0 +1,11 @@ +// IslandWorker.js: the module worker the island teammates think in. +// See IslandEngine.js for the message kinds. + +import { handle } from './IslandEngine.js'; + +self.onmessage = (e) => { + const { id, kind, payload } = e.data ?? {}; + let res = null, err = null; + try { res = handle(kind, payload); } catch (ex) { err = String(ex?.message ?? ex); } + self.postMessage({ id, res, err }); +}; diff --git a/src/games/forbiddenisland/tutorial.md b/src/games/forbiddenisland/tutorial.md index e1641ec..d443ea1 100644 --- a/src/games/forbiddenisland/tutorial.md +++ b/src/games/forbiddenisland/tutorial.md @@ -1,173 +1,140 @@ -# Forbidden Island — A Guide by Balam +# Welcome to The Drowning Isle -*Greetings, mortals. I am Balam. Jaguar god. Keeper of the night sky, the crossroads, and what lives between them. I have walked eternity, yes, pero your little planet… it is fascinating to me. Especially these — how do you call them — "juegos." Your games. I have studied many. This one, Forbidden Island, it speaks to me in a language I recognize: the language of the world consuming itself.* - -*Come. I will teach you. Pay attention — the island does not wait.* +*From the field journal of Professor A. Pike, Cartographer to the monsoon expedition. Pages loosened by damp; read quickly.* --- -## What Is This Game? +## The Situation -Forbidden Island is a cooperative adventure for up to four players. You do not compete against each other. No, no — you compete against the island itself, which is slowly, inevitably, sinking into the sea. +Our seaplane is moored at the **Expedition Dock**. Behind it rises an island no chart agrees on: twenty-four ruined places, each one older than the last, and the monsoon has arrived early. The sea is coming in. -Together you must: -1. **Collect all four ancient treasures** hidden across the island -2. **Gather at Fools' Landing** — the one helicopter pad — with all treasures in hand -3. **Escape by helicopter** before the waters close over everything +Somewhere in those ruins are **four relics**. We mean to take all four home. This is a cooperative expedition: you and your partners win together or drown together. There is no other way to score it. -Everyone wins together, or everyone loses together. There is no in-between. *Como en la vida real,* yes? +**To win:** +1. Recover all four relics. +2. Get the whole crew back onto the Expedition Dock. +3. Play a **Helicopter Lift** card to fly out. --- -## The Island +## Before You Set Out -The island is made of **24 tiles** arranged in a diamond shape — a beautiful thing, like a jade mosaic. Each tile is a named location: temples, caves, gardens, palaces. At the start of the game, six tiles are already flooded. *El agua ya viene.* The water already comes. +The briefing lets you choose: -Each tile can be in one of three states: +- **Expedition**: a *Standard* expedition deals a fresh island each time. The *Daily* expedition is the same island, crew and storm for everyone on that date. Your best result for the day is kept in the journal. +- **Island**: four shapes. + - **The Diamond** is the classic, compact island. + - **The Atoll** is a ring of land round a lagoon. Nobody can walk across the middle. + - **Hook Bay** bends round a deep bay, so its two arms are far apart by land. + - **The Serpent** is a long diagonal ridge that the sea can easily cut in two. +- **Your role**: pick one of the six crew, or let the roster decide. +- **Resume**: an unfinished expedition is saved at the start of each of your turns. Leave whenever you like and pick it up later. -| State | Meaning | +--- + +## The Relics and Their Shrines + +Each relic can only be recovered at one of its **two shrines**. These are the tiles with a wax seal in the corner. Stand on either shrine with **four matching Treasure cards** and spend one action to recover it. + +| Relic | Shrines | |-------|---------| -| **Dry** | Safe to walk on, normal | -| **Flooded** | Water is rising — shore it up or it sinks | -| **Sunk** | Gone. Beneath the waves. Do not go there. | +| The Hollow Orb | Moonwell Sanctum, Sunspire Shrine | +| The Gale Gryphon | The Verdant Nave, Hollow of the Grey Wolf | +| The Ember Heart | Kiln of the Horned One, Gloamwyrm Grotto | +| The Tidewarden's Chalice | Coral Basilica, Stormbreak Citadel | -When a flooded tile is flooded again — it sinks. A sunk tile is removed from the game. *For ever.* +If **both shrines of a relic sink before you recover it**, that relic is lost and so is the expedition. The relic tracker in the journal counts the cards your crew holds and the shrines still standing. It turns red when a relic is down to its last shrine. --- -## The Four Treasures +## The Crew -Hidden on this island are four sacred relics. Each treasure can be found at **one of two special tiles**. You must stand on one of those tiles and discard four matching treasure cards from your hand to claim it. - -| Treasure | Tiles Where It Is Found | -|----------|-------------------------| -| The Earth Stone | Temple of the Moon, Temple of the Sun | -| The Statue of the Wind | Whispering Garden, Howling Garden | -| The Crystal of Fire | Cave of Embers, Cave of Shadows | -| The Ocean's Chalice | Coral Palace, Tidal Palace | - -*Mira* — if BOTH tiles for an unclaimed treasure sink before you capture it, the treasure is lost forever. And so are you. *Game over, mis amigos.* +| Role | Special ability | +|------|-----------------| +| **Bush Pilot** | Once per turn, fly to *any* tile for one action. | +| **Field Engineer** | Shore up *two* tiles for one action. | +| **Wireless Operator** | Give Treasure cards to a teammate *anywhere* on the island. | +| **Cartographer** | Spend an action to move another crew member up to two tiles. | +| **Hard-Hat Diver** | Move through any number of flooded and sunken tiles in one move. | +| **Mountaineer** | Move and shore up *diagonally* as well as straight. | --- -## The Adventurers +## Your Turn -Each player commands one of five adventurers, each with a unique power. These are not ordinary people, comprende? They are specialists. *Como yo.* +### 1. Take up to three actions -| Role | Color | Special Power | -|------|-------|---------------| -| **Pilot** | Blue | Once per turn: fly to ANY tile on the island for one action | -| **Engineer** | Red | Shore up TWO flooded tiles for the cost of ONE action | -| **Navigator** | Gold | Move another adventurer up to two tiles per action | -| **Diver** | Black | Swim through flooded AND sunk tiles to reach dry land | -| **Explorer** | Green | Move and shore up diagonally, not just the four cardinal directions | +Each of these costs one action: -Choose your team carefully. The island does not care how strong you are — only how smart. +- **Move** to an adjacent tile (up, down, left or right). Click a highlighted tile. +- **Shore up** a flooded tile next to you or under you. It flips back to dry. Click it. +- **Give a Treasure card** to a crew member on your tile. Click the crew strip above the island, pick your card, then pick your teammate. +- **Recover a relic** from a shrine with four matching cards, using the **Capture** button. + +Changed your mind? **Undo** takes back actions within your own turn, right up until you press **End Turn**. + +### 2. Draw two Treasure cards + +They come from the **Supply Crate**. Most are relic cards. You may also draw: + +- **Helicopter Lift**: fly any group of crew standing together to any tile, for free. Play yours on your turn, or while swimming. It is also your ticket off the island at the end. +- **Sandbags**: shore up *any* flooded tile, for free, on your turn or while swimming. +- **Water Level Rises**: see below. + +You may hold five cards. Draw a sixth and you must discard or play one. + +### 3. Flood the island + +Draw as many **Tide Chart** cards from the flood deck as the tide gauge shows. Each one names a tile: + +- A **dry** tile floods. Its painting turns to the flooded side and it starts to bob in the swell. +- A **flooded** tile **sinks**. It is gone for good. + +If your tile sinks under you, you must **swim** to a neighbouring tile, highlighted in sea-green. The Pilot may fly anywhere, the Diver swims to the nearest dry land, and the Mountaineer may also swim diagonally. With nowhere to go, the crew member drowns and the expedition is lost. --- -## On Your Turn +## When the Waters Rise -Each adventurer takes a turn with **three phases**: +Drawing **Water Level Rises** does two things: -### Phase 1 — Take 3 Actions +1. The brass **tide gauge** goes up a notch. You may now draw more flood cards each turn. +2. Every Tide Chart already drawn is shuffled and **put back on top of the flood deck**. The tiles that flooded recently are about to come round again, and this time they would sink. -You have exactly **three actions** to spend. Each of the following costs one action: - -- **Move** — step to any adjacent tile (up, down, left, right). The tile must not be sunk. -- **Shore Up** — flip a flooded tile back to dry. You may shore up your own tile or an adjacent one. -- **Capture a Treasure** — if you stand on a treasure tile AND hold four matching treasure cards in your hand, discard those four cards and claim the treasure. *Magnifico.* -- **Give a Card** — pass one treasure card from your hand to another player **on the same tile** as you. -- **Navigator: Move Another** — if you are the Navigator, spend an action to move any other adventurer up to two tiles. -- **Pilot: Fly** — if you are the Pilot, spend one action to fly to any tile on the island. You may do this only once per turn. - -You may take the same action multiple times. You may pass (do nothing) if you wish, pero *¿por qué?* - -### Phase 2 — Draw 2 Treasure Cards - -After your actions, draw two cards from the Treasure Deck. These are handed to you — you do not choose them. Most cards are treasure cards in four types (earth, wind, fire, ocean). But some cards are special: - -- **Helicopter Lift** — play at any time to fly any group of adventurers to any non-sunk tile. Or, if all four treasures are claimed and everyone is at Fools' Landing, use it to escape and WIN. -- **Sandbags** — play at any time to shore up any one flooded tile on the island, from wherever you stand. -- **Waters Rise!** — not a gift. The water level rises one step, and the flood discard pile is shuffled back on top of the flood deck. *Dios mío.* The same tiles flood again. - -Your hand limit is **five cards**. If you draw past five, you must immediately discard down to five. Choose wisely what you keep. - -### Phase 3 — Flood the Island - -Draw a number of Flood Cards equal to the current water level. Each card names a tile: - -- If that tile is **dry**, it becomes **flooded**. -- If that tile is **flooded**, it **sinks** — remove it from the island permanently. - -Flooded tiles go to the Flood Discard pile. When the Flood Deck runs out, the discard pile is reshuffled and reused. *The same tiles flood again and again, more and more often.* That is the horror of this game, yes? - -After the flood phase, your turn ends and the next adventurer begins. +Watch the storm too. The sky darkens and the rain thickens as the gauge climbs, and from level six there is lightning. --- -## The Water Level +## How the Expedition Is Lost -On the side of the board sits the **Water Level track**. It starts at your chosen difficulty and climbs whenever a Waters Rise! card is drawn. - -| Difficulty | Starting Level | Flood Cards Per Turn | -|------------|---------------|----------------------| -| Novice | 1 | 2 | -| Normal | 2 | 2 | -| Elite | 3 | 3 | -| Legendary | 4 | 3 | - -As the water rises, more flood cards are drawn each turn. At the highest levels, five cards per turn. If the water level reaches the skull marker — *the maximum* — the island is consumed and everyone loses. +1. **The Expedition Dock sinks.** No helicopter can land on open water. +2. **Both shrines of a relic you have not recovered sink.** +3. **A crew member has nowhere to swim.** +4. **The tide gauge reaches the drowned mark** at the top. --- -## The Ways to Lose +## Working With Your Partners -There are four ways the island defeats you. *I have seen them all.* +Your partners play their own turns, and they talk: -1. **Fools' Landing sinks** — your only way off the island is gone. -2. **Both tiles for an uncaptured treasure sink** — the treasure is lost forever. -3. **An adventurer cannot swim to safety** when their tile sinks beneath them. -4. **The water level reaches the skull marker** — the sea wins. +- At the start of each partner's turn, **ghost arrows** show what they plan to do: dashed routes, gold outlines on tiles they will shore up, a gold disc where they mean to recover a relic. +- Partners hand cards to whoever is collecting each relic. They play their own Sandbags and Helicopter Lifts when something important is about to go under, even during the flood. +- Use the **Auto ▼** tag beside a partner's name to set a priority: a relic to focus on, regrouping, or defending the shrines. +- Press **Forecast** on the driftwood shelf to see each tile's chance of being drawn in the next flood. Red badges are tiles that would sink. The forecast only uses what any player could know, such as which cards are left and what a Waters Rise put back on top. It never peeks at the deck. --- -## How to Win +## Notes From the Professor -All four conditions must be met: +1. **Guard the dock above all.** If it floods, shore it up at once. Losing it ends everything. +2. **One collector per relic.** Hands hold only five cards. Decide who gathers each relic and pass that kind of card to them. +3. **Keep a Helicopter Lift for the end.** It rescues and it wins, but you need one at the dock when the fourth relic is in. +4. **After a Waters Rise, read the Forecast.** The tiles that just flooded are the ones about to sink. +5. **The Wireless Operator, Pilot and Diver ignore distance** in different ways. Plan your routes round them. -1. All four treasures have been captured — by any player, in any combination. -2. All adventurers have gathered at **Fools' Landing**. -3. One adventurer plays a **Helicopter Lift** card to escape. - -*Then* you win. *Todos juntos* — together, or not at all. +*Good luck. Write everything down. If the pages get wet, write faster.* --- -## Balam's Notes from the Field - -I have observed your kind play this game. I offer you what I have learned: - -1. **Shore up early, before you need to.** A flooded tile is a warning. An ignored warning becomes a sunken tile. Do not wait for disaster — prevent it. *Your ancestors knew this. Some of them, anyway.* - -2. **The Messenger's gift crosses any distance.** If you have the Messenger on your team, they can hand cards to anyone on the island regardless of position. Use this to concentrate four matching cards in one hand quickly. - -3. **The Helicopter Lift does two things.** It rescues — and it wins. Do not play your last one just to reposition a player. Save at least one for the escape. - -4. **Flood cards cycle.** The tiles that flood once will flood again. Watch the discard pile. When Waters Rise! hits, whatever was recently flooded goes back on top of the deck — and floods first. *The island has a memory.* - -5. **Capture treasures early, not late.** In the endgame, the island is shrinking fast. Take treasures when you have four cards and a chance. You may not get another one. - -6. **The Diver is worth more than they look.** When half the island is sunk or flooded, the Diver swims through it like it is nothing. In the late game, they become the only one who can reach certain tiles at all. - -7. **Regroup before the final escape.** Getting everyone to Fools' Landing while it is still above water is harder than it sounds. The Navigator can pull teammates in. The Pilot can fly in alone. Plan this move before the island forces your hand. - ---- - -*And so, adventurers — that is Forbidden Island. A game of water, time, and trust. I find it muy hermoso, in its terrible way. It reminds me of things I have watched — civilizations reaching for what they treasure most, racing against a tide they cannot stop.* - -*I will be watching from the shadows, sí? Always watching.* - -*Now go. The island does not wait.* - -*— Balam, Jaguar God, Keeper of Crossroads, Occasional Visitor to the Realm of Earth* +When an expedition ends, the **expedition report** shows a tide chart day by day, the key moments, what each crew member did (and who was most valuable), and your lifetime record. diff --git a/tools/verifyForbiddenIsland.js b/tools/verifyForbiddenIsland.js new file mode 100644 index 0000000..966c0e1 --- /dev/null +++ b/tools/verifyForbiddenIsland.js @@ -0,0 +1,344 @@ +#!/usr/bin/env node +// verifyForbiddenIsland.js: headless checks for the co-op island engine + AI. +// • setup: 24 tiles on the diamond, deck composition, opening hands, 6 floods +// • give: costs an action, same tile only (Messenger: anywhere), treasure +// cards only, over-limit receiver discards and play resumes +// • swim: human chooses (phase 'swim'), AI auto-swims, Pilot/Diver/Explorer +// swim rules, drowning loses +// • specials: Sandbags any phase, Helicopter lifts a same-tile group only and +// can rescue a pending swimmer; escape spends the Helicopter +// • Waters Rise puts the reshuffled flood discard on top of the flood deck +// • losses: landing sunk, both temples sunk, skull +// • determinism: same seed + same actions → same state +// • fuzz: AI-vs-island games run to completion with only legal actions; +// win rate reported per skill +// Usage: node tools/verifyForbiddenIsland.js [--quick] + +import * as D from '../src/games/forbiddenisland/IslandData.js'; +import * as L from '../src/games/forbiddenisland/IslandLogic.js'; +import * as AI from '../src/games/forbiddenisland/IslandAI.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}`); + +// A fresh dry board with chosen roles; hands cleared so tests set them exactly. +function fresh(roles = ['pilot', 'engineer', 'messenger', 'diver'], seed = 1234) { + const s = L.createInitialState({ roles, seed, skipInitialFlood: true }); + s.pendingFlood = []; + for (const p of s.players) p.hand = []; + return s; +} +const tileAt = (s, r, c) => Object.values(s.tiles).find((t) => t.r === r && t.c === c).id; +const T = (k) => `treasure:${k}`; + +// ── setup ─────────────────────────────────────────────────────────────────── +section('setup'); +{ + ok('24 cells', D.CELLS.length === 24 && D.TILES.length === 24); + ok('messenger is dealable', D.ROLE_KEYS.includes('messenger') && D.ROLE_KEYS.length === 6); + const deck = D.buildTreasureDeck(); + ok('treasure deck 28', deck.length === 28); + const s = L.createInitialState({ seed: 7 }); + ok('6 flooded at start', Object.values(s.tiles).filter((t) => t.state === 'flooded').length === 6); + ok('2 cards each, no Waters Rise', s.players.every((p) => p.hand.length === 2 && !p.hand.includes(D.SPECIAL.WATERS_RISE))); + ok('all start on landing', s.players.every((p) => p.tileId === 'fools-landing')); + const total = s.treasureDeck.length + s.players.reduce((n, p) => n + p.hand.length, 0); + ok('no cards lost in deal', total === 28); +} + +// ── give ──────────────────────────────────────────────────────────────────── +section('give card'); +{ + let s = fresh(['pilot', 'engineer', 'messenger', 'diver']); + s.players[0].hand = [T('fire'), D.SPECIAL.SANDBAGS]; + const gives = L.legalActions(s, 0).filter((a) => a.type === 'give'); + ok('give only treasure cards', gives.every((a) => a.card === T('fire'))); + ok('give to all 3 on same tile', new Set(gives.map((a) => a.targetSeat)).size === 3); + const s2 = L.applyAction(s, 0, gives[0]); + ok('give costs an action', s2.actionsLeft === D.ACTIONS_PER_TURN - 1); + ok('card moved', s2.players[0].hand.length === 1 && s2.players[gives[0].targetSeat].hand.includes(T('fire'))); + // Different tile: no give unless Messenger. + s = fresh(['pilot', 'engineer', 'messenger', 'diver']); + s.players[0].hand = [T('fire')]; + s.players[1].tileId = tileAt(s, 0, 2); + ok('no give across tiles', !L.legalActions(s, 0).some((a) => a.type === 'give' && a.targetSeat === 1)); + ok('illegal give refused', L.applyAction(s, 0, { type: 'give', seat: 0, targetSeat: 1, card: T('fire') }) === s); + s.current = 2; s.players[2].hand = [T('wind')]; + ok('messenger gives anywhere', L.legalActions(s, 2).some((a) => a.type === 'give' && a.targetSeat === 1)); + // Over the limit: receiver discards, then play resumes. + s = fresh(); + s.players[0].hand = [T('earth')]; + s.players[1].hand = [T('wind'), T('wind'), T('fire'), T('fire'), T('ocean')]; + let g = L.applyAction(s, 0, { type: 'give', seat: 0, targetSeat: 1, card: T('earth') }); + ok('overflow → discard phase', g.phase === 'discard' && g.pendingDiscard === 1 && g.discardReturn === 'actions'); + g = L.discardCard(g, 1, T('ocean')); + ok('discard returns to actions', g.phase === 'actions' && g.current === 0 && g.actionsLeft === 2); +} + +// ── swimming ──────────────────────────────────────────────────────────────── +section('swim'); +function sinkUnder(s, seat) { s.tiles[s.players[seat].tileId].state = 'sunk'; } +{ + // Human pawn on a tile that sinks during flood → swim phase with options. + let s = fresh(['engineer', 'pilot']); + const here = tileAt(s, 2, 2); + s.players[0].tileId = here; s.players[1].tileId = tileAt(s, 3, 3); + s.tiles[here].state = 'flooded'; + s.floodDeck = [here, ...s.floodDeck.filter((x) => x !== here)]; + s.waterLevel = 1; s.phase = 'flood'; + let f = L.resolveFlood(s); + if (f.phase !== 'lost') { + ok('human swim pending', f.phase === 'swim' && f.pendingSwim?.seat === 0); + const opt = f.pendingSwim.options[0]; + ok('swim options adjacent', f.pendingSwim.options.every((id) => { + const a = f.tiles[id], b = f.tiles[here]; return Math.abs(a.r - b.r) + Math.abs(a.c - b.c) === 1; + })); + const g = L.resolveSwim(f, 0, opt); + ok('swim resolves + advances', g.players[0].tileId === opt && g.phase === 'actions' && g.current === 1); + ok('bad swim refused', L.resolveSwim(f, 0, here) === f); + // Helicopter rescue during a pending swim. + f.players[1].hand.push(D.SPECIAL.HELICOPTER); + const dest = tileAt(f, 3, 0); + const h = L.playHelicopter(f, 1, [0], dest); + ok('helicopter rescues swimmer', h.players[0].tileId === dest && h.phase === 'actions' && !h.pendingSwim); + } else ok('swim setup lost unexpectedly', false, f.lossReason); + // autoSwim moves the human too. + const a = L.resolveFlood(s, { autoSwim: true }); + ok('autoSwim', a.phase === 'actions' && a.tiles[a.players[0].tileId].state !== 'sunk'); + + // Role swim rules (via swimChoices). + s = fresh(['pilot', 'diver', 'explorer', 'engineer']); + const c = tileAt(s, 2, 2); + for (const p of s.players) p.tileId = c; + sinkUnder(s, 0); + ok('pilot flies anywhere', L.swimChoices(s, 0).length === 23); + ok('explorer diagonals', L.swimChoices(s, 2).length === 8); + ok('engineer orthogonal', L.swimChoices(s, 3).length === 4); + // Diver: sink the ring around → nearest tiles are two steps away. + for (const id of L.adjacentTiles(s, c)) s.tiles[id].state = 'sunk'; + const dv = L.swimChoices(s, 1); + ok('diver swims to nearest', dv.length > 0 && dv.every((id) => { + const t = s.tiles[id], o = s.tiles[c]; return Math.abs(t.r - o.r) + Math.abs(t.c - o.c) === 2; + })); + ok('engineer boxed in', L.swimChoices(s, 3).length === 0); +} + +// ── specials ──────────────────────────────────────────────────────────────── +section('specials'); +{ + let s = fresh(); + const fl = tileAt(s, 1, 1); s.tiles[fl].state = 'flooded'; + s.players[2].hand = [D.SPECIAL.SANDBAGS]; + const sb = L.playSandbags(s, 2, fl); + ok('sandbags off-turn', sb !== s && sb.tiles[fl].state === 'dry'); + s.phase = 'flood'; + ok('sandbags during flood step', L.playSandbags(s, 2, fl) !== s); + // Helicopter: same-tile group only. + s = fresh(); + s.players[0].hand = [D.SPECIAL.HELICOPTER]; + s.players[1].tileId = tileAt(s, 0, 2); + const dest = tileAt(s, 5, 2); + ok('heli refuses split group', L.playHelicopter(s, 0, [0, 1], dest) === s); + const h = L.playHelicopter(s, 0, [0, 2, 3], dest); + ok('heli lifts group', [0, 2, 3].every((i) => h.players[i].tileId === dest) && !h.players[0].hand.length); + // Escape spends the Helicopter. + s = fresh(); + for (const k of D.TREASURE_KEYS) s.players[0].captured[k] = true; + ok('no escape without lift', !L.canEscape(s)); + s.players[3].hand = [D.SPECIAL.HELICOPTER]; + const w = L.attemptEscape(s); + ok('escape wins, spends lift', w.phase === 'won' && !w.players[3].hand.length); +} + +// ── Waters Rise ───────────────────────────────────────────────────────────── +section('waters rise'); +{ + const s = fresh(); + s.floodDiscard = ['bronze-gate', 'iron-gate', 'watchtower']; + s.floodDeck = s.floodDeck.filter((x) => !s.floodDiscard.includes(x)); + s.treasureDeck = [D.SPECIAL.WATERS_RISE, T('fire'), T('wind'), ...s.treasureDeck]; + const lvl = s.waterLevel; + const e = L.endActions(s); + ok('level +1', e.waterLevel === lvl + 1); + ok('discard on top of flood deck', new Set(e.floodDeck.slice(0, 3)).size === 3 && e.floodDeck.slice(0, 3).every((x) => s.floodDiscard.includes(x))); + ok('Waters Rise counts as one of the two draws', e.players[0].hand.length === 1); +} + +// ── losses ────────────────────────────────────────────────────────────────── +section('losses'); +{ + let s = fresh(); s.tiles['fools-landing'].state = 'sunk'; + ok('landing sunk', L.checkLoss(s)?.phase === 'lost'); + s = fresh(); for (const id of D.TREASURES.fire.tiles) s.tiles[id].state = 'sunk'; + ok('both temples sunk', L.checkLoss(s)?.phase === 'lost'); + s.players[0].captured.fire = true; + ok('captured treasure safe', L.checkLoss(s) === null); + s = fresh(); s.waterLevel = D.MAX_WATER; + ok('skull', L.checkLoss(s)?.phase === 'lost'); +} + +section('layouts'); +{ + for (const key of D.LAYOUT_KEYS) { + const cells = D.LAYOUTS[key].cells; + const set = new Set(cells.map(([r, c]) => `${r},${c}`)); + // flood-fill orthogonally from the first cell: every shape must be one island + const seen = new Set([`${cells[0][0]},${cells[0][1]}`]); const q = [cells[0]]; + while (q.length) { const [r, c] = q.pop(); for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const k = `${r + dr},${c + dc}`; if (set.has(k) && !seen.has(k)) { seen.add(k); q.push([r + dr, c + dc]); } } } + ok(`${key}: 24 connected cells in the 6×6 grid`, cells.length === 24 && seen.size === 24 && cells.every(([r, c]) => r >= 0 && r < 6 && c >= 0 && c < 6)); + const s = L.createInitialState({ seed: 5, layout: key }); + ok(`${key}: tiles dealt onto the shape`, s.layout === key && Object.values(s.tiles).every((t) => set.has(`${t.r},${t.c}`))); + } + const a = L.createInitialState({ seed: 5, layout: 'atoll' }), b = L.createInitialState({ seed: 5, layout: 'hook' }); + ok('layouts have their own neighbour tables', JSON.stringify(L.adjacentTiles(a, 'fools-landing')) !== JSON.stringify(L.adjacentTiles(b, 'fools-landing')) || a.tiles['fools-landing'].r !== b.tiles['fools-landing'].r); + let s = fresh(); s.tiles['fools-landing'].state = 'sunk'; + ok('loss kind: dock', L.checkLoss(s)?.lossKind === 'dock'); + s = fresh(); for (const id of D.TREASURES.wind.tiles) s.tiles[id].state = 'sunk'; + const lr = L.checkLoss(s); + ok('loss kind: relic + which', lr?.lossKind === 'relic' && lr.lossTreasure === 'wind'); + s = fresh(); s.actionsLeft = 0; const r0 = s.round; s.current = s.players.length - 1; + s = L.resolveFlood(L.endActions(s), { autoSwim: true }); + ok('round advances when the turn wraps to the first seat', s.current === 0 && s.round === r0 + 1); +} + +// ── determinism ───────────────────────────────────────────────────────────── +section('determinism'); +{ + const a = L.createInitialState({ seed: 99 }), b = L.createInitialState({ seed: 99 }); + ok('same seed same setup', JSON.stringify(a) === JSON.stringify(b)); + const ea = L.resolveFlood(L.endActions(a), { autoSwim: true }), eb = L.resolveFlood(L.endActions(b), { autoSwim: true }); + ok('same seed same turn', JSON.stringify(ea) === JSON.stringify(eb)); +} + +// ── public knowledge / fairness ───────────────────────────────────────────── +section('public knowledge'); +{ + const s = fresh(); + const v = L.publicView(s); + ok('view hides flood order', JSON.stringify(v.floodDeck) === JSON.stringify(s.floodDeck.slice().sort())); + ok('view hides treasure order', JSON.stringify(v.treasureDeck) === JSON.stringify(s.treasureDeck.slice().sort())); + // Waters Rise: the reshuffled discard becomes a known top segment. + const w = fresh(); + w.floodDiscard = ['bronze-gate', 'iron-gate', 'watchtower', 'observatory']; + w.floodDeck = w.floodDeck.filter((x) => !w.floodDiscard.includes(x)); + w.treasureDeck = [D.SPECIAL.WATERS_RISE, T('fire'), ...w.treasureDeck]; + const e = L.endActions(w); + ok('known segment recorded', e.floodKnown.length === 1 && e.floodKnown[0].length === 4); + const odds = L.floodDrawOdds(e, 2); + ok('top segment odds = 2/4', w.floodDiscard.every((id) => Math.abs(odds[id] - 0.5) < 1e-9)); + ok('rest of deck odds = 0', Object.entries(odds).filter(([id]) => !w.floodDiscard.includes(id)).every(([, p]) => p === 0)); + const odds5 = L.floodDrawOdds(e, 5); + const rest = e.floodDeck.length - 4; + ok('overflow spreads to rest', Math.abs(odds5['bronze-gate'] - 1) < 1e-9 && Math.abs(odds5[e.floodDeck.find((x) => !w.floodDiscard.includes(x))] - 1 / rest) < 1e-9); + const f = L.resolveFlood({ ...e, phase: 'flood' }, { autoSwim: true }); + ok('drawn cards leave the segment', f.floodKnown.flat().length === Math.max(0, 4 - D.WATER_TRACK[e.waterLevel])); + + // Same public position, different hidden deck order → same decision. + + let same = 0, trials = 0; + for (let seed = 1; seed <= 12; seed++) { + const a = L.createInitialState({ seed, humanSeat: -1 }); + const b = L.cloneState(a); + b.floodDeck = b.floodDeck.slice().reverse(); + b.treasureDeck = b.treasureDeck.slice().reverse(); + trials++; + if (JSON.stringify(AI.chooseAction(a, 0, 5)) === JSON.stringify(AI.chooseAction(b, 0, 5))) same++; + } + + ok('AI ignores hidden deck order', same === trials, `${same}/${trials}`); +} + +// ── AI sanity positions ───────────────────────────────────────────────────── +section('AI positions'); +{ + + // Carrier with a full set next to its temple walks over and captures. + let s = fresh(['engineer', 'pilot']); + const temple = D.TREASURES.fire.tiles[0]; + const nb = L.adjacentTiles(s, temple).find((id) => !s.tiles[id].treasure && !s.tiles[id].landing); + s.players[0].tileId = nb; + s.players[0].hand = [T('fire'), T('fire'), T('fire'), T('fire')]; + const a1 = AI.chooseAction(s, 0, 5); + ok('walks to temple', a1?.type === 'move' && a1.tileId === temple, JSON.stringify(a1)); + s = L.applyAction(s, 0, a1); + ok('captures', AI.chooseAction(s, 0, 5)?.type === 'capture'); + // Flooded landing within reach gets shored. + s = fresh(['engineer', 'pilot']); + s.tiles['fools-landing'].state = 'flooded'; + const plan = AI.planTurn(s, 0, 5).actions; + ok('shores the landing', plan.some((a) => a.type === 'shoreUp' && a.tiles.includes('fools-landing')), JSON.stringify(plan)); + // Never breaks a full set by giving into a full hand. + s = fresh(['messenger', 'engineer']); + s.players[0].hand = [T('wind'), T('wind'), T('wind'), T('wind')]; + s.players[1].hand = [T('fire'), T('fire'), T('ocean'), T('earth'), T('earth')]; + const p2 = AI.planTurn(s, 0, 5).actions; + ok('keeps the full set', !p2.some((a) => a.type === 'give' && a.card === T('wind')), JSON.stringify(p2)); + +} + +// ── fuzz: AI plays every seat ─────────────────────────────────────────────── +section('fuzz + AI'); +function playGame(seed, skill, difficulty = 'novice', nPlayers = 4) { + const roles = D.ROLE_KEYS.slice().sort(() => 0.5 - ((seed * 9301 + 49297) % 233280) / 233280).slice(0, nPlayers); + let s = L.createInitialState({ roles, seed, difficulty, humanSeat: -1, layout: D.LAYOUT_KEYS[seed % D.LAYOUT_KEYS.length] }); + let guard = 0; + while (!L.isGameOver(s) && guard++ < 4000) { + if (L.canEscape(s)) { s = L.attemptEscape(s); break; } + if (s.phase === 'actions') { + const seat = s.current; + const free = AI.chooseFreeCard(s, seat); + if (free) { + const n = free.type === 'sandbags' ? L.playSandbags(s, free.seat, free.tileId) : L.playHelicopter(s, free.seat, free.pawnSeats, free.destTileId); + if (n === s) return { error: `free card refused ${JSON.stringify(free)}` }; + s = n; continue; + } + const act = AI.chooseAction(s, seat, skill); + if (!act) { s = L.endActions(s); continue; } + const legal = L.legalActions(s, seat).some((a) => JSON.stringify(a) === JSON.stringify(act)); + if (!legal) return { error: `illegal ${JSON.stringify(act)}` }; + s = L.applyAction(s, seat, act); + } else if (s.phase === 'discard') { + s = L.discardCard(s, s.pendingDiscard, AI.chooseDiscard(s, s.pendingDiscard)); + } else if (s.phase === 'flood') { + s = L.resolveFlood(s, { autoSwim: true }); + } else return { error: `stuck in ${s.phase}` }; + // invariants + // Captured-treasure cards go to the discard pile, so all 28 stay in circulation. + const cards = s.treasureDeck.length + s.treasureDiscard.length + s.players.reduce((n, p) => n + p.hand.length, 0); + if (cards !== 28) return { error: `card count ${cards}` }; + if (s.phase !== 'lost' && s.players.some((p) => s.tiles[p.tileId].state === 'sunk') && s.phase !== 'swim') return { error: 'pawn on sunk tile' }; + } + if (!L.isGameOver(s)) return { error: 'did not finish' }; + return { won: s.phase === 'won', reason: s.lossReason }; +} +{ + // Full mode plays enough games for the ladder to be meaningful (all-AI teams, + // Novice, alternating 4- and 2-player); quick mode only checks legality. + const N = QUICK ? 12 : 80; + const wins = {}; + for (const skill of [1, 3, 5]) { + let w = 0, errors = 0; const reasons = {}; + for (let i = 0; i < N; i++) { + const r = playGame(1000 + i, skill, 'novice', i % 2 ? 2 : 4); + if (r.error) { errors++; if (errors <= 3) console.error(` seed ${1000 + i}: ${r.error}`); continue; } + if (r.won) w++; else reasons[r.reason] = (reasons[r.reason] ?? 0) + 1; + } + wins[skill] = w; + ok(`skill ${skill}: no engine/AI errors`, errors === 0, `${errors} errors`); + const top = Object.entries(reasons).sort((a, b) => b[1] - a[1]).slice(0, 2).map(([r, n]) => `${n}× ${r}`).join('; '); + console.log(` skill ${skill} (novice, 2p/4p): won ${w}/${N} ${top ? `— losses: ${top}` : ''}`); + } + if (!QUICK) { + ok('ladder: skill 5 beats skill 3', wins[5] > wins[3], JSON.stringify(wins)); + ok('ladder: skill 3 beats skill 1', wins[3] > wins[1], JSON.stringify(wins)); + ok('skill 5 wins at least a third on Novice', wins[5] >= N / 3, `${wins[5]}/${N}`); + } +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);