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
This commit is contained in:
parent
d7a873054c
commit
0b8affa1ff
|
|
@ -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: '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: '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: '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: '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: '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' });
|
registerGame({ slug: 'labyrinth', name: 'Labyrinth', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 43, defaultPlayfield: 'fantasy' });
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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
|
// The island is the only opponent, so the AI is a planner, not a minimax:
|
||||||
// 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
|
// • evalState() scores a position for the whole team. Its core is an
|
||||||
// also exposes describeIntent() so the partner can announce what it's doing in
|
// expected-loss model of the NEXT flood built from public knowledge only:
|
||||||
// the team-chat panel — the same decision data, rendered as speech.
|
// 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 {
|
import {
|
||||||
legalActions, applyAction, adjacentTiles, capturedCount, handTreasureCounts,
|
legalActions, applyAction, discardCard, adjacentTiles, capturedCount, handTreasureCounts,
|
||||||
|
playSandbags, playHelicopter, canEscape, floodDrawOdds, publicView, neighbourTable,
|
||||||
} from './IslandLogic.js';
|
} 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 = {
|
const SKILL_PROFILES = {
|
||||||
1: { topN: 5, blunder: 0.40, noise: 220, delay: [700, 1200] },
|
1: { width: 1, depth: 1, noise: 450, blunder: 0.25, delay: [700, 1200] },
|
||||||
2: { topN: 4, blunder: 0.24, noise: 140, delay: [650, 1100] },
|
2: { width: 2, depth: 2, noise: 220, blunder: 0.12, delay: [650, 1100] },
|
||||||
3: { topN: 3, blunder: 0.12, noise: 80, delay: [600, 1000] },
|
3: { width: 4, depth: 3, noise: 90, blunder: 0.05, delay: [600, 1000] },
|
||||||
4: { topN: 2, blunder: 0.04, noise: 35, delay: [520, 900] },
|
4: { width: 8, depth: 3, noise: 25, blunder: 0, delay: [520, 900] },
|
||||||
5: { topN: 1, blunder: 0.00, noise: 0, delay: [440, 820] },
|
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]; }
|
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);
|
return lo + Math.random() * (hi - lo);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- distance over the (non-sunk) island ----------------------------------
|
// ── value constants ─────────────────────────────────────────────────────────
|
||||||
function bfsDist(state, fromId, targetSet) {
|
const WIN = 1e8;
|
||||||
if (targetSet.has(fromId)) return 0;
|
const LOSS = 40000; // price of a tile whose sinking ends the game
|
||||||
const seen = new Set([fromId]);
|
const CAPTURED = 9000; // per treasure in hand
|
||||||
let frontier = [fromId], d = 0;
|
// 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) {
|
while (frontier.length) {
|
||||||
d++;
|
step++;
|
||||||
const next = [];
|
const next = [];
|
||||||
for (const id of frontier) {
|
for (const i of frontier) {
|
||||||
for (const nb of adjacentTiles(state, id)) {
|
for (const j of nbrs[i]) {
|
||||||
if (seen.has(nb) || state.tiles[nb].state === 'sunk') continue;
|
if (d[j] !== 99 || (crossed && crossed[j])) continue;
|
||||||
if (targetSet.has(nb)) return d;
|
if (sunk[j]) {
|
||||||
seen.add(nb); next.push(nb);
|
if (crossed) { crossed[j] = 1; next.push(j); } // the Diver may cross, never stop
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
d[j] = step;
|
||||||
|
next.push(j);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
frontier = next;
|
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) {
|
// ── tile pricing ────────────────────────────────────────────────────────────
|
||||||
return TREASURES[key].tiles.filter((id) => state.tiles[id].state !== 'sunk');
|
function treasureCaptured(state, key) { return state.players.some((p) => p.captured[key]); }
|
||||||
}
|
|
||||||
|
|
||||||
function isCaptured(state, key) { return state.players.some((p) => p.captured[key]); }
|
// What it costs the team if this tile sinks now.
|
||||||
|
function sinkCost(state, t, saveSet) {
|
||||||
// How costly it would be to let a given flooded tile sink. Shared by the state
|
if (t.state === 'sunk') return 0;
|
||||||
// evaluation and the special-card chooser so they agree on what's "critical".
|
let c = TUNE.NORMAL;
|
||||||
function floodWeight(state, t) {
|
if (t.landing) c = LOSS;
|
||||||
if (t.state !== 'flooded') return 0;
|
else if (t.treasure && !treasureCaptured(state, t.treasure)) {
|
||||||
if (t.landing) return 130;
|
|
||||||
if (t.treasure && !isCaptured(state, t.treasure)) {
|
|
||||||
const pair = TREASURES[t.treasure].tiles.find((id) => id !== t.id);
|
const pair = TREASURES[t.treasure].tiles.find((id) => id !== t.id);
|
||||||
if (state.tiles[pair].state === 'sunk') return 320; // last tile of the treasure
|
const ps = state.tiles[pair].state;
|
||||||
if (state.tiles[pair].state === 'flooded') return 120; // both temples flooded
|
c = ps === 'sunk' ? LOSS : (ps === 'flooded' ? TUNE.T2 : TUNE.T1);
|
||||||
return 55;
|
|
||||||
}
|
}
|
||||||
return 6;
|
if (saveSet?.has(t.id)) c += 600;
|
||||||
}
|
// Pawns standing here must swim; with nowhere to go they drown.
|
||||||
|
|
||||||
// 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) {
|
for (const p of state.players) {
|
||||||
const c = handTreasureCounts(p)[key];
|
if (p.tileId !== t.id) continue;
|
||||||
if (c > best) { best = c; bestSeat = p.seat; }
|
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;
|
||||||
}
|
}
|
||||||
out[key] = { seat: bestSeat, cards: best };
|
return c;
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- whole-team state evaluation ------------------------------------------
|
// Chance the acting player's 2-card treasure draw contains a Waters Rise.
|
||||||
// Higher is better. Greedy 1-ply over this drives competent co-op play.
|
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;
|
||||||
|
}
|
||||||
|
pOf[t.id] = p;
|
||||||
|
}
|
||||||
|
// 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 evaluation ───────────────────────────────────────────────────
|
||||||
export function evalState(state, seat) {
|
export function evalState(state, seat) {
|
||||||
if (state.phase === 'won') return 1e9;
|
if (state.phase === 'won') return WIN * 10;
|
||||||
if (state.phase === 'lost') return -1e9;
|
if (state.phase === 'lost') return -WIN;
|
||||||
|
if (canEscape(state)) return WIN;
|
||||||
|
|
||||||
const pr = state.priorities ?? {};
|
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 ?? []);
|
const saveSet = new Set(pr.saveTiles ?? []);
|
||||||
for (const t of Object.values(state.tiles)) {
|
const tab = neighbourTable(state);
|
||||||
if (t.state !== 'flooded') continue;
|
const sunk = tab.ids.map((id) => state.tiles[id].state === 'sunk');
|
||||||
let w = floodWeight(state, t);
|
const dists = {};
|
||||||
if (saveSet.has(t.id)) w += 50;
|
for (const p of state.players) dists[p.seat] = distMap(tab, sunk, p);
|
||||||
// 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;
|
const nCaptured = capturedCount(state);
|
||||||
v -= w;
|
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
|
// Special cards held by the team.
|
||||||
// everyone to Fools' Landing and reward holding a Helicopter Lift.
|
let helis = 0, bags = 0;
|
||||||
if (allCaptured || pr.regroup) {
|
for (const p of state.players) for (const c of p.hand) {
|
||||||
const landing = new Set(['fools-landing']);
|
if (c === SPECIAL.HELICOPTER) helis++;
|
||||||
for (const p of state.players) v -= bfsDist(state, p.tileId, landing) * (allCaptured ? 10 : 3);
|
else if (c === SPECIAL.SANDBAGS) bags++;
|
||||||
if (allCaptured && state.players.some((p) => p.hand.includes(SPECIAL.HELICOPTER))) v += 80;
|
}
|
||||||
|
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.
|
// Over the hand limit (only mid-discard).
|
||||||
for (const p of state.players) if (p.hand.length > HAND_LIMIT) v -= 25 * (p.hand.length - HAND_LIMIT);
|
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;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- pick one action (or null to end the turn) ----------------------------
|
// 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;
|
||||||
|
}
|
||||||
|
if (!isFinite(best)) best = 6;
|
||||||
|
return Math.min(best, 14) + missing * WAIT_PER_CARD;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 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('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
// 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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
export function chooseAction(state, seat, skill = 3) {
|
||||||
const acts = legalActions(state, seat);
|
if (!legalActions(state, seat).length) return null;
|
||||||
if (acts.length === 0) return null;
|
const view = publicView(state);
|
||||||
const prof = profileFor(skill);
|
const key = signature(view) + view.actionsLeft + ':' + seat + ':' + skill;
|
||||||
const base = evalState(state, seat);
|
let actions;
|
||||||
|
if (planCache && planCache.key === key) actions = planCache.rest;
|
||||||
let scored = acts.map((a) => ({ a, v: evalState(applyAction(state, seat, a), seat) }));
|
else actions = planTurn(view, seat, skill, { isView: true }).actions;
|
||||||
scored.sort((x, y) => y.v - x.v);
|
const next = actions[0] ?? null;
|
||||||
|
planCache = null;
|
||||||
// Nothing improves the team's position — bank the remaining actions.
|
if (next && actions.length > 1) {
|
||||||
const hold = state.priorities?.hold ? 12 : 1; // require a bigger gain when "hold position" is set
|
const after = settle(applyAction(view, seat, next));
|
||||||
if (scored[0].v <= base + hold) return null;
|
planCache = { key: signature(after) + after.actionsLeft + ':' + seat + ':' + skill, rest: actions.slice(1) };
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
const pool = scored.slice(0, Math.min(prof.topN, scored.length));
|
return next;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- free special-card plays (Sandbags / Helicopter Lift) -----------------
|
// The whole turn the partner intends, for the ghost-arrow preview. Primes the
|
||||||
// These cost no action and can be played any time, so the planner gets a chance
|
// plan cache so the following chooseAction calls play exactly this plan.
|
||||||
// to use them before/between its regular actions. Returns a descriptor the
|
export function previewPlan(state, seat, skill = 3) {
|
||||||
// caller applies via playSandbags / playHelicopter, or null. Only the current
|
if (!legalActions(state, seat).length) return [];
|
||||||
// seat's own specials are considered (a simplification of "any time").
|
const view = publicView(state);
|
||||||
export function chooseFreeCard(state, seat) {
|
const actions = planTurn(view, seat, skill, { isView: true }).actions;
|
||||||
if (state.phase !== 'actions' || state.current !== seat) return null;
|
planCache = actions.length ? { key: signature(view) + view.actionsLeft + ':' + seat + ':' + skill, rest: actions } : null;
|
||||||
const p = state.players[seat];
|
return actions;
|
||||||
|
}
|
||||||
|
|
||||||
// Sandbags: free-shore the single most critical flooded tile. Reserve them for
|
// ── free special-card plays ─────────────────────────────────────────────────
|
||||||
// genuine emergencies (a temple's last/second tile, or Fools' Landing) rather
|
// Any computer-controlled teammate may play a Sandbags / Helicopter Lift at any
|
||||||
// than spending them on routine flooding.
|
// time. Returns { type, seat, tileId } | { type, seat, pawnSeats, destTileId }
|
||||||
if (p.hand.includes(SPECIAL.SANDBAGS)) {
|
// or null. `minGain` raises the bar (e.g. outside anyone's action phase).
|
||||||
let best = null, bw = 0;
|
export function chooseFreeCard(state, seat, { minGain = 120, isView = false } = {}) {
|
||||||
for (const t of Object.values(state.tiles)) {
|
if (state.phase === 'won' || state.phase === 'lost') return null;
|
||||||
const w = floodWeight(state, t);
|
const view = isView ? state : publicView(state);
|
||||||
if (w > bw) { bw = w; best = t; }
|
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 }; }
|
||||||
}
|
}
|
||||||
if (best && bw >= 100) return { type: 'sandbags', tileId: best.id };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helicopter Lift: deliver a ready (4-card) carrier straight to its temple,
|
const heliHolder = holders.find((p) => p.hand.includes(SPECIAL.HELICOPTER));
|
||||||
// but only if the team can spare one (the last Helicopter is needed to escape).
|
if (heliHolder) {
|
||||||
if (p.hand.includes(SPECIAL.HELICOPTER)) {
|
// Destinations worth a flight: temples of treasures someone can now claim,
|
||||||
const heli = state.players.reduce((n, pl) => n + pl.hand.filter((c) => c === SPECIAL.HELICOPTER).length, 0);
|
// and the landing for the endgame.
|
||||||
if (heli >= 2) {
|
const dests = new Set();
|
||||||
for (const key of TREASURE_KEYS) {
|
for (const key of TREASURE_KEYS) {
|
||||||
if (isCaptured(state, key)) continue;
|
if (treasureCaptured(view, key)) continue;
|
||||||
let cs = -1, cc = 0;
|
if (!view.players.some((p) => handTreasureCounts(p)[key] >= CARDS_TO_CAPTURE)) continue;
|
||||||
for (const pl of state.players) { const c = handTreasureCounts(pl)[key]; if (c > cc) { cc = c; cs = pl.seat; } }
|
for (const id of TREASURES[key].tiles) if (view.tiles[id].state !== 'sunk') dests.add(id);
|
||||||
if (cc < CARDS_TO_CAPTURE || cs < 0) continue;
|
}
|
||||||
const live = liveTreasureTiles(state, key);
|
if (capturedCount(view) === 4 && view.tiles['fools-landing'].state !== 'sunk') dests.add('fools-landing');
|
||||||
const carrierTile = state.players[cs].tileId;
|
const groups = {};
|
||||||
if (!live.length || live.includes(carrierTile)) continue;
|
for (const p of view.players) (groups[p.tileId] ??= []).push(p.seat);
|
||||||
const templeFlooded = live.some((id) => state.tiles[id].state === 'flooded');
|
for (const [from, seats] of Object.entries(groups)) {
|
||||||
const d = bfsDist(state, carrierTile, new Set(live));
|
for (const dest of dests) {
|
||||||
// Lift yourself whenever it saves real travel; lift a teammate only when
|
if (dest === from) continue;
|
||||||
// their temple is actively flooding (urgent) — they capture next turn.
|
const ns = playHelicopter(view, heliHolder.seat, seats, dest);
|
||||||
if ((cs === seat && d >= 2) || templeFlooded) {
|
if (ns === view) continue;
|
||||||
let dest = live[0], dd = 99;
|
const g = evalState(ns, seat) - base;
|
||||||
for (const id of live) { const e = bfsDist(state, carrierTile, new Set([id])); if (e < dd) { dd = e; dest = id; } }
|
if (g > bestGain) { bestGain = g; best = { type: 'helicopter', seat: heliHolder.seat, pawnSeats: seats, destTileId: dest, carrierSeat: seats[0] }; }
|
||||||
return { type: 'helicopter', pawnSeats: [cs], destTileId: dest, carrierSeat: cs };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
return best;
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- discard choice (when a hand is over the limit) -----------------------
|
// ── discard choice ──────────────────────────────────────────────────────────
|
||||||
// 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.
|
|
||||||
export function chooseDiscard(state, seat) {
|
export function chooseDiscard(state, seat) {
|
||||||
const p = state.players[seat];
|
const p = state.players[seat];
|
||||||
const counts = handTreasureCounts(p);
|
let best = p.hand[0], bv = -Infinity;
|
||||||
const captured = (k) => state.players.some((pl) => pl.captured[k]);
|
for (const card of new Set(p.hand)) {
|
||||||
|
const ns = discardCard(state, seat, card);
|
||||||
// 1. Treasure cards whose treasure is already captured (pure dead weight).
|
if (ns === state) continue;
|
||||||
let dead = p.hand.find((c) => c.startsWith('treasure:') && captured(c.slice('treasure:'.length)));
|
// Score the hand that remains without recursing into further discards.
|
||||||
if (dead) return dead;
|
const v = evalState({ ...ns, phase: ns.phase === 'discard' ? 'actions' : ns.phase }, seat);
|
||||||
|
if (v > bv) { bv = v; best = card; }
|
||||||
// 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];
|
|
||||||
}
|
}
|
||||||
|
return best;
|
||||||
// 4. Last resort: Helicopter Lift.
|
|
||||||
return p.hand[0];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- describe the partner's plan for the chat panel ------------------------
|
// ── describe the partner's plan for the chat panel ──────────────────────────
|
||||||
// Pure read of the current state — returns a rationale object the chat library
|
export function describeIntent(state, seat, skill = 4) {
|
||||||
// turns into a spoken line.
|
|
||||||
export function describeIntent(state, seat) {
|
|
||||||
const p = state.players[seat];
|
const p = state.players[seat];
|
||||||
const role = p.role;
|
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);
|
const threats = topThreats(state);
|
||||||
if (threats.length) return { role, intent: 'SHORE', tile: threats[0].id, threats };
|
const plan = planTurn(state, seat, Math.max(3, skill));
|
||||||
return { role, intent: 'SUPPORT', threats };
|
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) {
|
export function topThreats(state) {
|
||||||
|
const view = publicView(state);
|
||||||
|
const odds = floodDrawOdds(view, floodDrawCount(view.waterLevel));
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const t of Object.values(state.tiles)) {
|
for (const t of Object.values(view.tiles)) {
|
||||||
if (t.state !== 'flooded') continue;
|
if (t.state !== 'flooded') continue;
|
||||||
let w = 1;
|
const sc = sinkCost(view, t, null);
|
||||||
if (t.landing) w = 5;
|
if (sc < 1000) continue;
|
||||||
else if (t.treasure && !state.players.some((p) => p.captured[t.treasure])) {
|
const risk = Math.max(odds[t.id] ?? 0, 0.05) * sc;
|
||||||
const pair = TREASURES[t.treasure].tiles.find((id) => id !== t.id);
|
out.push({ id: t.id, name: t.name, weight: risk, odds: odds[t.id] ?? 0, treasure: t.treasure ?? null, landing: !!t.landing });
|
||||||
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 });
|
|
||||||
}
|
}
|
||||||
return out.sort((a, b) => b.weight - a.weight).slice(0, 3);
|
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));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -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-<relic> wax seal marking a relic's shrines
|
||||||
|
// di-pawn-<role> 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-<w>x<h> 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 };
|
||||||
|
|
@ -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;
|
// The planner (IslandAI.describeIntent) produces a rationale object; this turns
|
||||||
// this turns it into a line of table talk in the speaking role's "voice".
|
// it into a line of table talk in the speaking crew member's voice. Each role
|
||||||
// Game events (a tile sinking, Waters Rise!, a capture) get their own lines so
|
// has a personality (ROLES[role].voice): the Bush Pilot is breezy, the Field
|
||||||
// the chat reads like a real co-op table.
|
// 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';
|
import { TREASURES, ROLES } from './IslandData.js';
|
||||||
|
|
||||||
const EMOJI = {
|
const EMOJI = {
|
||||||
pilot: '✈️', engineer: '🔧', messenger: '✉️', navigator: '🧭', diver: '🤿', explorer: '🧗',
|
pilot: '✈️', engineer: '🔧', messenger: '📻', navigator: '🧭', diver: '🤿', explorer: '🧗',
|
||||||
};
|
};
|
||||||
|
|
||||||
export function roleEmoji(role) { return EMOJI[role] ?? '🧩'; }
|
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'; }
|
export function roleColorHex(role) { return ROLES[role]?.colorHex ?? '#f2ead8'; }
|
||||||
|
|
||||||
const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
|
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 = {
|
const FLAVOR = {
|
||||||
pilot: ['Wings ready.', 'I can be anywhere in a heartbeat.', 'Just say the word.'],
|
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: ['Efficient as always.', 'On it.', 'Consider it done.'],
|
engineer: ['Mind the timbers.', 'Right. Get on with it.', 'I have seen worse. Not much worse.', 'Everything floods. Question is when.'],
|
||||||
messenger: ['Happy to help.', 'Cards incoming.', "I've got the network."],
|
messenger: ['Over.', 'Signal is clear, over.', 'Standing by on all frequencies.', 'Copy all, over.'],
|
||||||
navigator: ['Follow my lead.', 'I’ll route us.', 'Stay coordinated.'],
|
navigator: ['Fascinating, truly fascinating.', 'I have marked it in the survey.', 'Note the bearing, everyone.', 'The old maps did warn of this.'],
|
||||||
diver: ['The water doesn’t scare me.', 'Going deep.', 'I’ll take the wet path.'],
|
diver: ['Water is fine.', 'Seen deeper.', 'Mm.', 'I will go under if I have to.'],
|
||||||
explorer: ['I’ll take the diagonal.', 'Scouting ahead.', 'I see a way.'],
|
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 = {
|
const INTENT = {
|
||||||
CAPTURE: (r) => pick([
|
CAPTURE: (r) => {
|
||||||
`I'm standing on the temple with a full set — claiming ${tName(r.treasure)} now!`,
|
const v = voiceOf(r.role);
|
||||||
`Four cards in hand and feet on the tile. ${tName(r.treasure)} is ours this turn.`,
|
return pick([
|
||||||
`Securing ${tName(r.treasure)} — that's one less treasure to worry about.`,
|
`${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.`,
|
||||||
SEEK: (r) => {
|
`Securing ${tName(r.treasure)}. One less thing for the sea to take.`,
|
||||||
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.`,
|
|
||||||
]);
|
]);
|
||||||
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;
|
return base;
|
||||||
},
|
},
|
||||||
SHORE: (r) => pick([
|
GIVE: (r) => pick([
|
||||||
`Shoring up — we can't afford to lose ground here.`,
|
`Pooling the ${tShort(r.treasure)} cards. Mine goes to whoever is carrying the set.`,
|
||||||
`Patching the flooding before it spreads. Watch the map.`,
|
`Card hand-off this turn: ${tShort(r.treasure)} goes to our collector.`,
|
||||||
`Holding the line on the flooded tiles near me.`,
|
`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([
|
ESCAPE: () => pick([
|
||||||
`All four treasures are in. Regrouping at Fools' Landing — let's fly out together!`,
|
`All four relics are in! Everyone to the Expedition Dock. We need a Helicopter Lift.`,
|
||||||
`Treasures secured! Everyone to the helipad, we need a Helicopter Lift.`,
|
`That is the lot! Converge on the dock, and whoever holds the Helicopter Lift, keep it safe.`,
|
||||||
`This is the home stretch — converging on Fools' Landing.`,
|
`Home stretch, everyone. Make for the Expedition Dock.`,
|
||||||
]),
|
|
||||||
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.`,
|
|
||||||
]),
|
]),
|
||||||
|
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.
|
// A line announcing the AI partner's plan for the turn.
|
||||||
export function lineForIntent(rationale) {
|
export function lineForIntent(rationale) {
|
||||||
const make = INTENT[rationale.intent] ?? INTENT.SUPPORT;
|
const make = INTENT[rationale.intent] ?? INTENT.SUPPORT;
|
||||||
let text = make(rationale);
|
let text = make(rationale);
|
||||||
// Occasionally append a threat warning.
|
|
||||||
const t = rationale.threats?.[0];
|
const t = rationale.threats?.[0];
|
||||||
if (t && Math.random() < 0.5) {
|
if (t && Math.random() < 0.5) {
|
||||||
text += ` ${pick([
|
text += ` ${pick([
|
||||||
`Heads up — ${t.name} floods next, someone keep an eye on it.`,
|
`Heads up: ${t.name} could flood next. Someone watch it.`,
|
||||||
`Also: ${t.name} is in danger. Don't let it sink.`,
|
`Also, ${t.name} is in danger. Do not let it sink.`,
|
||||||
`Watch ${t.name}, it's one flood from trouble.`,
|
`Keep an eye on ${t.name}. It is one flood from trouble.`,
|
||||||
])}`;
|
])}`;
|
||||||
} else if (Math.random() < 0.25) {
|
} else if (Math.random() < 0.3) {
|
||||||
text += ` ${pick(FLAVOR[rationale.role] ?? [])}`;
|
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.
|
// Lines for notable game events. `ctx` carries the names already resolved.
|
||||||
export function lineForEvent(kind, ctx = {}) {
|
export function lineForEvent(kind, ctx = {}) {
|
||||||
|
const say = (arr) => radio(ctx.role, pick(arr));
|
||||||
switch (kind) {
|
switch (kind) {
|
||||||
case 'sink': return { role: ctx.role ?? null, text: pick([
|
case 'sink': return { role: ctx.role ?? null, text: pick([
|
||||||
`${ctx.tileName} just sank beneath the waves.`,
|
`${ctx.tileName} slid beneath the waves.`,
|
||||||
`We lost ${ctx.tileName} — it's gone for good.`,
|
`${ctx.tileName} is gone. The sea has it now.`,
|
||||||
|
`We have lost ${ctx.tileName}.`,
|
||||||
]) };
|
]) };
|
||||||
case 'watersRise': return { role: ctx.role ?? null, text: pick([
|
case 'watersRise': return { role: ctx.role ?? null, text: pick([
|
||||||
`Waters Rise! The flood is accelerating — water level ${ctx.waterLevel}.`,
|
`The Waters Rise! The gauge reads ${ctx.waterLevel}, and every flooded tile goes back on top of the flood deck.`,
|
||||||
`That's a Waters Rise card. Everything we flooded is coming back around.`,
|
`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([
|
case 'capture': return { role: ctx.role, text: say([
|
||||||
`Got it! ${tName(ctx.treasure)} is secured. ${4 - (ctx.remaining ?? 0)} of 4 down.`,
|
`Got it! ${tName(ctx.treasure)} is ours. ${4 - (ctx.remaining ?? 0)} of 4 relics recovered.`,
|
||||||
`${tName(ctx.treasure)} claimed — great teamwork.`,
|
`${tName(ctx.treasure)} is in the crate. Lovely work, everyone.`,
|
||||||
]) };
|
]) };
|
||||||
case 'sandbags': return { role: ctx.role, text: pick([
|
case 'sandbags': return { role: ctx.role, text: say([
|
||||||
`Dropping sandbags on ${ctx.tileName} — that holds the line, no action spent.`,
|
`Sandbags down on ${ctx.tileName}. That holds it, and it costs no action.`,
|
||||||
`Sandbags out on ${ctx.tileName}. We can't lose that one.`,
|
`Sandbagging ${ctx.tileName}. We cannot lose that one.`,
|
||||||
]) };
|
]) };
|
||||||
case 'heliMove': return { role: ctx.role, text: pick([
|
case 'heliMove': return { role: ctx.role, text: say([
|
||||||
`Helicopter lift — flying ${ctx.who} straight to ${ctx.tileName} for the capture.`,
|
`Helicopter Lift: flying ${ctx.who} straight to ${ctx.tileName}.`,
|
||||||
`Burning a Helicopter to get ${ctx.who} onto ${ctx.tileName} before it's too late.`,
|
`Calling in a Helicopter Lift to get ${ctx.who} onto ${ctx.tileName}.`,
|
||||||
]) };
|
]) };
|
||||||
case 'swim': return { role: ctx.role, text: pick([
|
case 'give': return { role: ctx.role, text: say([
|
||||||
`Tile sank under me — swimming to safety.`,
|
`Passing a ${tShort(ctx.card?.slice(9))} card to ${ctx.to}.`,
|
||||||
`Had to bail to ${ctx.tileName} as the ground gave way.`,
|
`${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([
|
case 'won': return { role: null, text: pick([
|
||||||
`We made it off the island — together! 🎉`,
|
`The helicopter lifts off the Expedition Dock with all four relics aboard. The expedition is saved!`,
|
||||||
`Helicopter's airborne with all four treasures. We win!`,
|
`Rotors turning, crates lashed down. We made it off the island, together.`,
|
||||||
]) };
|
]) };
|
||||||
case 'lost': return { role: null, text: ctx.reason ?? 'The island is lost.' };
|
case 'lost': return { role: null, text: ctx.reason ?? 'The island is lost.' };
|
||||||
default: return null;
|
default: return null;
|
||||||
|
|
@ -116,9 +152,14 @@ export function lineForEvent(kind, ctx = {}) {
|
||||||
|
|
||||||
// Acknowledgement when the human sets a strategy priority.
|
// Acknowledgement when the human sets a strategy priority.
|
||||||
export function lineForAck(role, label) {
|
export function lineForAck(role, label) {
|
||||||
return { role, text: pick([
|
return { role, text: radio(role, pick([
|
||||||
`Copy that — ${label}.`,
|
`Understood: ${label}.`,
|
||||||
`Understood. Re-planning around: ${label}.`,
|
`Re-planning around: ${label}.`,
|
||||||
`Roger. Prioritizing ${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}`;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 };
|
||||||
|
|
@ -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
|
// silhouette, the tile/treasure/role catalog, and deck composition. Everything
|
||||||
// dynamic lives in IslandLogic.js.
|
// dynamic lives in IslandLogic.js.
|
||||||
|
|
||||||
|
|
@ -28,63 +28,91 @@ export function isCell(r, c) {
|
||||||
return CELLS.some(([cr, cc]) => cr === r && cc === 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.
|
// Treasures, each tied to two island tiles. `element` keys the treasure cards.
|
||||||
export const TREASURES = {
|
export const TREASURES = {
|
||||||
earth: { key: 'earth', name: 'The Earth Stone', tiles: ['temple-moon', 'temple-sun'], color: 0x8d6e3c },
|
earth: { key: 'earth', name: 'The Hollow Orb', short: 'Hollow Orb', tiles: ['temple-moon', 'temple-sun'], color: 0xa8875a },
|
||||||
wind: { key: 'wind', name: 'The Statue of the Wind', tiles: ['whispering-garden', 'howling-garden'], color: 0x9aa7b0 },
|
wind: { key: 'wind', name: 'The Gale Gryphon', short: 'Gale Gryphon', tiles: ['whispering-garden', 'howling-garden'], color: 0x8fa0ae },
|
||||||
fire: { key: 'fire', name: 'The Crystal of Fire', tiles: ['cave-embers', 'cave-shadows'], color: 0xc0492f },
|
fire: { key: 'fire', name: 'The Ember Heart', short: 'Ember Heart', tiles: ['cave-embers', 'cave-shadows'], color: 0xc8432c },
|
||||||
ocean: { key: 'ocean', name: "The Ocean's Chalice", tiles: ['coral-palace', 'tidal-palace'], color: 0x2f7fb0 },
|
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'];
|
export const TREASURE_KEYS = ['earth', 'wind', 'fire', 'ocean'];
|
||||||
|
|
||||||
// All 24 tiles. `treasure` links a tile to a treasure; `landing` marks the
|
// 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 = [
|
export const TILES = [
|
||||||
{ id: 'temple-moon', name: 'Temple of the Moon', treasure: 'earth' },
|
{ id: 'temple-moon', name: 'Moonwell Sanctum', treasure: 'earth' },
|
||||||
{ id: 'temple-sun', name: 'Temple of the Sun', treasure: 'earth' },
|
{ id: 'temple-sun', name: 'Sunspire Shrine', treasure: 'earth' },
|
||||||
{ id: 'whispering-garden', name: 'Whispering Garden', treasure: 'wind' },
|
{ id: 'whispering-garden', name: 'The Verdant Nave', treasure: 'wind' },
|
||||||
{ id: 'howling-garden', name: 'Howling Garden', treasure: 'wind' },
|
{ id: 'howling-garden', name: 'Hollow of the Grey Wolf', treasure: 'wind' },
|
||||||
{ id: 'cave-embers', name: 'Cave of Embers', treasure: 'fire' },
|
{ id: 'cave-embers', name: 'Kiln of the Horned One', treasure: 'fire' },
|
||||||
{ id: 'cave-shadows', name: 'Cave of Shadows', treasure: 'fire' },
|
{ id: 'cave-shadows', name: 'Gloamwyrm Grotto', treasure: 'fire' },
|
||||||
{ id: 'coral-palace', name: 'Coral Palace', treasure: 'ocean' },
|
{ id: 'coral-palace', name: 'Coral Basilica', treasure: 'ocean' },
|
||||||
{ id: 'tidal-palace', name: 'Tidal Palace', treasure: 'ocean' },
|
{ id: 'tidal-palace', name: 'Stormbreak Citadel', treasure: 'ocean' },
|
||||||
{ id: 'fools-landing', name: "Fools' Landing", landing: true },
|
{ id: 'fools-landing', name: 'Expedition Dock', landing: true },
|
||||||
{ id: 'bronze-gate', name: 'Bronze Gate' },
|
{ id: 'bronze-gate', name: 'The Brazen Door' },
|
||||||
{ id: 'copper-gate', name: 'Copper Gate' },
|
{ id: 'copper-gate', name: 'Dragonseal Door' },
|
||||||
{ id: 'silver-gate', name: 'Silver Gate' },
|
{ id: 'silver-gate', name: 'Rimefrost Door' },
|
||||||
{ id: 'gold-gate', name: 'Gold Gate' },
|
{ id: 'gold-gate', name: 'Aurelian Door' },
|
||||||
{ id: 'iron-gate', name: 'Iron Gate' },
|
{ id: 'iron-gate', name: 'Gargoyle Gate' },
|
||||||
{ id: 'watchtower', name: 'Watchtower' },
|
{ id: 'watchtower', name: 'Lantern Keep' },
|
||||||
{ id: 'observatory', name: 'Observatory' },
|
{ id: 'observatory', name: "Stargazer's Dome" },
|
||||||
{ id: 'phantom-rock', name: 'Phantom Rock' },
|
{ id: 'phantom-rock', name: 'The Black Needle' },
|
||||||
{ id: 'misty-marsh', name: 'Misty Marsh' },
|
{ id: 'misty-marsh', name: 'Fogwater Fen' },
|
||||||
{ id: 'breakers-bridge', name: 'Breakers Bridge' },
|
{ id: 'breakers-bridge', name: 'Drowned Causeway' },
|
||||||
{ id: 'crimson-forest', name: 'Crimson Forest' },
|
{ id: 'crimson-forest', name: 'Bloodleaf Wood' },
|
||||||
{ id: 'dunes-deception', name: 'Dunes of Deception' },
|
{ id: 'dunes-deception', name: 'Mirage Dunes' },
|
||||||
{ id: 'lost-lagoon', name: 'Lost Lagoon' },
|
{ id: 'lost-lagoon', name: 'Glimmerwater Lagoon' },
|
||||||
{ id: 'twilight-hollow', name: 'Twilight Hollow' },
|
{ id: 'twilight-hollow', name: 'Dusk Harbour' },
|
||||||
{ id: 'cliffs-abandon', name: 'Cliffs of Abandon' },
|
{ id: 'cliffs-abandon', name: "Widow's Crags" },
|
||||||
];
|
];
|
||||||
|
|
||||||
// The six adventurer roles. `power` is read by the engine/AI to branch special
|
// The six adventurer roles. `power` is read by the engine/AI to branch special
|
||||||
// abilities; `color` is the pawn colour.
|
// abilities; `color` is the pawn colour.
|
||||||
export const ROLES = {
|
export const ROLES = {
|
||||||
pilot: { key: 'pilot', name: 'Pilot', color: 0x4a90d9, colorHex: '#4a90d9', power: 'Once per turn, fly to any tile.',
|
pilot: { key: 'pilot', name: 'Bush Pilot', short: 'Pilot', color: 0x4a86c8, colorHex: '#5b97d6', 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.' },
|
voice: 'breezy', motto: 'If it has wings, I can land it. Mostly.',
|
||||||
engineer: { key: 'engineer', name: 'Engineer', color: 0xd0473a, colorHex: '#d0473a', power: 'Shore up two tiles for one action.',
|
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.' },
|
||||||
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.' },
|
engineer: { key: 'engineer', name: 'Field Engineer', short: 'Engineer', color: 0xc4473a, colorHex: '#d65a4c', power: 'Shore up two tiles for one action.',
|
||||||
messenger: { key: 'messenger', name: 'Messenger', color: 0xb9bfc6, colorHex: '#b9bfc6', power: 'Give Treasure cards to anyone, any distance.',
|
voice: 'gruff', motto: 'Sandbag, timber, rope. In that order.',
|
||||||
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.' },
|
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.' },
|
||||||
navigator: { key: 'navigator', name: 'Navigator', color: 0xe2b53c, colorHex: '#e2b53c', power: 'Move another adventurer up to 2 tiles.',
|
messenger: { key: 'messenger', name: 'Wireless Operator', short: 'Wireless', color: 0xb9bfc6, colorHex: '#c3c9d0', power: 'Give Treasure cards to anyone, any distance.',
|
||||||
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.' },
|
voice: 'crisp', motto: 'Stand by, transmitting.',
|
||||||
diver: { key: 'diver', name: 'Diver', color: 0x2b2b30, colorHex: '#2b2b30', power: 'Swim through flooded and missing tiles.',
|
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.' },
|
||||||
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.' },
|
navigator: { key: 'navigator', name: 'Cartographer', short: 'Cartographer', color: 0xd9a93a, colorHex: '#e2b53c', power: 'Move another adventurer up to 2 tiles.',
|
||||||
explorer: { key: 'explorer', name: 'Explorer', color: 0x49a25a, colorHex: '#49a25a', power: 'Move and shore up diagonally.',
|
voice: 'professorial', motto: 'The map is never wrong. The island, occasionally.',
|
||||||
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.' },
|
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.
|
// Special (non-treasure) Treasure-deck cards.
|
||||||
export const SPECIAL = {
|
export const SPECIAL = {
|
||||||
|
|
@ -105,7 +133,7 @@ export function buildTreasureDeck() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Water-level track. Index = level (1..10); value = flood cards drawn per turn.
|
// 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 WATER_TRACK = [null, 2, 2, 3, 3, 3, 4, 4, 5, 5, 'skull'];
|
||||||
export const MAX_WATER = 10;
|
export const MAX_WATER = 10;
|
||||||
|
|
||||||
|
|
@ -152,3 +180,7 @@ export const CARD_FRAME = {
|
||||||
export function cardFrame(card) {
|
export function cardFrame(card) {
|
||||||
return CARD_FRAME[card] ?? null;
|
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';
|
||||||
|
|
|
||||||
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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 };
|
||||||
|
}
|
||||||
|
|
@ -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
|
// cooperative race against the board: players take 3 actions, draw 2 Treasure
|
||||||
// cards, then the island floods. Everyone wins or loses together.
|
// cards, then the island floods. Everyone wins or loses together.
|
||||||
//
|
//
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
// reproducible and unit-testable.
|
// reproducible and unit-testable.
|
||||||
|
|
||||||
import {
|
import {
|
||||||
CELLS, TILES, TREASURES, TREASURE_KEYS, ROLES, SPECIAL,
|
LAYOUTS, TILES, TREASURES, TREASURE_KEYS, ROLES, SPECIAL,
|
||||||
buildTreasureDeck, floodDrawCount, DIFFICULTY,
|
buildTreasureDeck, floodDrawCount, DIFFICULTY,
|
||||||
CARDS_TO_CAPTURE, HAND_LIMIT, ACTIONS_PER_TURN, MAX_WATER,
|
CARDS_TO_CAPTURE, HAND_LIMIT, ACTIONS_PER_TURN, MAX_WATER,
|
||||||
} from './IslandData.js';
|
} from './IslandData.js';
|
||||||
|
|
@ -48,12 +48,14 @@ function makeRng(state) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- construction ----------------------------------------------------------
|
// ---- 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 roleKeys = (roles && roles.length) ? roles.slice(0, 4) : ['pilot', 'engineer', 'navigator', 'diver'];
|
||||||
const s = {
|
const s = {
|
||||||
seed: (seed ?? Math.floor(Math.random() * 1e9)) >>> 0,
|
seed: (seed ?? Math.floor(Math.random() * 1e9)) >>> 0,
|
||||||
rngCursor: 0,
|
rngCursor: 0,
|
||||||
difficulty,
|
difficulty,
|
||||||
|
layout: LAYOUTS[layout] ? layout : 'diamond',
|
||||||
|
round: 1,
|
||||||
tiles: {},
|
tiles: {},
|
||||||
players: [],
|
players: [],
|
||||||
treasureDeck: [],
|
treasureDeck: [],
|
||||||
|
|
@ -63,9 +65,13 @@ export function createInitialState({ roles, difficulty = 'normal', seed, humanSe
|
||||||
waterLevel: DIFFICULTY[difficulty]?.start ?? 2,
|
waterLevel: DIFFICULTY[difficulty]?.start ?? 2,
|
||||||
current: 0,
|
current: 0,
|
||||||
actionsLeft: ACTIONS_PER_TURN,
|
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
|
pendingDiscard: null, // seat that must discard
|
||||||
pendingSwim: null, // { seat, options } a pawn forced to leave a sunk tile
|
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 },
|
priorities: { focusTreasure: null, saveTiles: [], regroup: false, hold: false },
|
||||||
lossReason: null,
|
lossReason: null,
|
||||||
log: [],
|
log: [],
|
||||||
|
|
@ -74,7 +80,7 @@ export function createInitialState({ roles, difficulty = 'normal', seed, humanSe
|
||||||
const rng = makeRng(s);
|
const rng = makeRng(s);
|
||||||
// Assign the 24 tiles to the 24 board cells.
|
// Assign the 24 tiles to the 24 board cells.
|
||||||
const shuffledTiles = shuffle(TILES, rng.next);
|
const shuffledTiles = shuffle(TILES, rng.next);
|
||||||
CELLS.forEach(([r, c], i) => {
|
LAYOUTS[s.layout].cells.forEach(([r, c], i) => {
|
||||||
const t = shuffledTiles[i];
|
const t = shuffledTiles[i];
|
||||||
s.tiles[t.id] = {
|
s.tiles[t.id] = {
|
||||||
id: t.id, name: t.name, r, c,
|
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) => {
|
roleKeys.forEach((rk, seat) => {
|
||||||
s.players.push({
|
s.players.push({
|
||||||
seat,
|
seat,
|
||||||
|
|
@ -196,28 +204,45 @@ export function cloneState(state) {
|
||||||
},
|
},
|
||||||
pendingSwim: state.pendingSwim ? { ...state.pendingSwim, options: state.pendingSwim.options.slice() } : null,
|
pendingSwim: state.pendingSwim ? { ...state.pendingSwim, options: state.pendingSwim.options.slice() } : null,
|
||||||
pendingFlood: (state.pendingFlood ?? []).slice(),
|
pendingFlood: (state.pendingFlood ?? []).slice(),
|
||||||
|
pendingSwims: (state.pendingSwims ?? []).slice(),
|
||||||
|
floodKnown: (state.floodKnown ?? []).map((seg) => seg.slice()),
|
||||||
log: state.log.slice(),
|
log: state.log.slice(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- geometry / adjacency --------------------------------------------------
|
// ---- geometry / adjacency --------------------------------------------------
|
||||||
function cellIndex(state) {
|
// 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 = {};
|
const map = {};
|
||||||
for (const t of Object.values(state.tiles)) map[`${t.r},${t.c}`] = t.id;
|
for (const t of Object.values(state.tiles)) map[`${t.r},${t.c}`] = t.id;
|
||||||
return map;
|
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 } = {}) {
|
export function adjacentTiles(state, tileId, { diagonal = false } = {}) {
|
||||||
const t = state.tiles[tileId];
|
if (!state.tiles[tileId]) return [];
|
||||||
if (!t) return [];
|
const tab = neighbourTable(state);
|
||||||
const map = cellIndex(state);
|
return (diagonal ? tab.all : tab.orth)[tileId].slice();
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function isSunk(state, id) { return state.tiles[id].state === 'sunk'; }
|
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.
|
// flooded/sunk tiles (orthogonally) from the start.
|
||||||
function diverDestinations(state, startId) {
|
function diverDestinations(state, startId) {
|
||||||
const start = state.tiles[startId];
|
const start = state.tiles[startId];
|
||||||
const map = cellIndex(state);
|
const orth = neighbourTable(state).orth;
|
||||||
const seen = new Set([startId]);
|
const seen = new Set([startId]);
|
||||||
const dest = new Set();
|
const dest = new Set();
|
||||||
const stack = [start];
|
const stack = [start];
|
||||||
while (stack.length) {
|
while (stack.length) {
|
||||||
const t = stack.pop();
|
const t = stack.pop();
|
||||||
for (const [dr, dc] of ORTH) {
|
for (const id of orth[t.id]) {
|
||||||
const id = map[`${t.r + dr},${t.c + dc}`];
|
if (seen.has(id)) continue;
|
||||||
if (!id || seen.has(id)) continue;
|
|
||||||
seen.add(id);
|
seen.add(id);
|
||||||
const nt = state.tiles[id];
|
const nt = state.tiles[id];
|
||||||
if (nt.state === 'sunk') { stack.push(nt); } // swim through
|
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 });
|
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.
|
// Navigator: move another adventurer up to 2 tiles.
|
||||||
if (p.role === 'navigator') {
|
if (p.role === 'navigator') {
|
||||||
for (const other of state.players) {
|
for (const other of state.players) {
|
||||||
|
|
@ -348,6 +380,21 @@ export function applyAction(state, seat, action) {
|
||||||
s.players[action.targetSeat].tileId = action.tileId;
|
s.players[action.targetSeat].tileId = action.tileId;
|
||||||
s.log.push({ kind: 'navMove', seat, targetSeat: action.targetSeat, tileId: action.tileId });
|
s.log.push({ kind: 'navMove', seat, targetSeat: action.targetSeat, tileId: action.tileId });
|
||||||
break;
|
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:
|
default:
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|
@ -357,41 +404,55 @@ export function applyAction(state, seat, action) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- special cards (free, any time) ---------------------------------------
|
// ---- 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) {
|
export function playSandbags(state, seat, tileId) {
|
||||||
const p = state.players[seat];
|
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);
|
const s = cloneState(state);
|
||||||
s.players[seat].hand.splice(s.players[seat].hand.indexOf(SPECIAL.SANDBAGS), 1);
|
s.players[seat].hand.splice(s.players[seat].hand.indexOf(SPECIAL.SANDBAGS), 1);
|
||||||
s.tiles[tileId].state = 'dry';
|
s.tiles[tileId].state = 'dry';
|
||||||
s.treasureDiscard.push(SPECIAL.SANDBAGS);
|
s.treasureDiscard.push(SPECIAL.SANDBAGS);
|
||||||
s.log.push({ kind: 'sandbags', seat, tileId });
|
s.log.push({ kind: 'sandbags', seat, tileId });
|
||||||
|
settleDiscard(s);
|
||||||
return 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) {
|
export function playHelicopter(state, seat, pawnSeats, destTileId) {
|
||||||
const p = state.players[seat];
|
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);
|
const s = cloneState(state);
|
||||||
s.players[seat].hand.splice(s.players[seat].hand.indexOf(SPECIAL.HELICOPTER), 1);
|
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.treasureDiscard.push(SPECIAL.HELICOPTER);
|
||||||
s.log.push({ kind: 'helicopter', seat, pawnSeats: pawnSeats.slice(), destTileId });
|
s.log.push({ kind: 'helicopter', seat, pawnSeats: seats, fromTileId: from, destTileId });
|
||||||
return s;
|
settleDiscard(s);
|
||||||
}
|
// A lift can rescue a pawn that was waiting to swim off a sunk tile.
|
||||||
|
if (s.phase === 'swim') {
|
||||||
// Swap one card between two players — free action (no action cost, no tile check).
|
s.pendingSwims = s.pendingSwims.filter((ps) => isSunk(s, s.players[ps].tileId));
|
||||||
export function swapCards(state, seatA, cardA, seatB, cardB) {
|
s.pendingSwim = null;
|
||||||
if (seatA === seatB) return state;
|
return finishFlood(s);
|
||||||
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 });
|
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -405,8 +466,12 @@ export function canEscape(state) {
|
||||||
export function attemptEscape(state) {
|
export function attemptEscape(state) {
|
||||||
if (!canEscape(state)) return state;
|
if (!canEscape(state)) return state;
|
||||||
const s = cloneState(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.phase = 'won';
|
||||||
s.log.push({ kind: 'won' });
|
s.log.push({ kind: 'won', seat: liftSeat });
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -430,11 +495,12 @@ export function endActions(state) {
|
||||||
s.waterLevel = Math.min(MAX_WATER, s.waterLevel + 1);
|
s.waterLevel = Math.min(MAX_WATER, s.waterLevel + 1);
|
||||||
// Reshuffle the flood discard back on TOP of the flood deck.
|
// Reshuffle the flood discard back on TOP of the flood deck.
|
||||||
if (s.floodDiscard.length) {
|
if (s.floodDiscard.length) {
|
||||||
|
s.floodKnown = [s.floodDiscard.slice().sort(), ...(s.floodKnown ?? [])];
|
||||||
s.floodDeck = [...shuffle(s.floodDiscard, rng.next), ...s.floodDeck];
|
s.floodDeck = [...shuffle(s.floodDiscard, rng.next), ...s.floodDeck];
|
||||||
s.floodDiscard = [];
|
s.floodDiscard = [];
|
||||||
}
|
}
|
||||||
s.log.push({ kind: 'watersRise', waterLevel: s.waterLevel });
|
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 {
|
} else {
|
||||||
p.hand.push(card);
|
p.hand.push(card);
|
||||||
s.log.push({ kind: 'drawTreasure', seat: p.seat, 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);
|
const [card] = hand.splice(idx, 1);
|
||||||
if (card.startsWith('treasure:') || card === SPECIAL.SANDBAGS || card === SPECIAL.HELICOPTER) s.treasureDiscard.push(card);
|
if (card.startsWith('treasure:') || card === SPECIAL.SANDBAGS || card === SPECIAL.HELICOPTER) s.treasureDiscard.push(card);
|
||||||
s.log.push({ kind: 'discard', seat, 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;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -465,7 +531,7 @@ export function discardCard(state, seat, cardId) {
|
||||||
// Draws flood cards equal to the water level, flooding/sinking tiles, then
|
// 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
|
// auto-resolves forced swims and advances to the next player. Returns the new
|
||||||
// state; inspect `state.log` (entries since the call) to animate.
|
// 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;
|
if (state.phase !== 'flood') return state;
|
||||||
let s = cloneState(state);
|
let s = cloneState(state);
|
||||||
const count = floodDrawCount(s.waterLevel);
|
const count = floodDrawCount(s.waterLevel);
|
||||||
|
|
@ -480,8 +546,10 @@ export function resolveFlood(state) {
|
||||||
if (s.floodDiscard.length === 0) break;
|
if (s.floodDiscard.length === 0) break;
|
||||||
s.floodDeck = shuffle(s.floodDiscard, rng.next);
|
s.floodDeck = shuffle(s.floodDiscard, rng.next);
|
||||||
s.floodDiscard = [];
|
s.floodDiscard = [];
|
||||||
|
s.floodKnown = [];
|
||||||
}
|
}
|
||||||
const id = s.floodDeck.shift();
|
const id = s.floodDeck.shift();
|
||||||
|
forgetKnown(s, id);
|
||||||
const tile = s.tiles[id];
|
const tile = s.tiles[id];
|
||||||
if (tile.state === 'dry') {
|
if (tile.state === 'dry') {
|
||||||
tile.state = 'flooded';
|
tile.state = 'flooded';
|
||||||
|
|
@ -499,36 +567,133 @@ export function resolveFlood(state) {
|
||||||
s.floodDiscard.push(...phaseDiscard);
|
s.floodDiscard.push(...phaseDiscard);
|
||||||
rng.commit();
|
rng.commit();
|
||||||
|
|
||||||
// Forced swims for any pawn whose tile has sunk.
|
// A lost landing or treasure ends the game before anyone swims.
|
||||||
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 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const lost = checkLoss(s);
|
const lost = checkLoss(s);
|
||||||
if (lost) return lost;
|
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);
|
advanceTurn(s);
|
||||||
return 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) {
|
function swimOptions(state, player) {
|
||||||
if (player.role === 'diver') return diverDestinations(state, player.tileId);
|
if (player.role === 'pilot') {
|
||||||
const diagonal = player.role === 'explorer' || 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' })
|
return adjacentTiles(state, player.tileId, { diagonal: player.role === 'explorer' })
|
||||||
.filter((id) => !isSunk(state, id));
|
.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) {
|
function bestSwim(state, opts) {
|
||||||
const dry = opts.filter((id) => state.tiles[id].state === 'dry');
|
const dry = opts.filter((id) => state.tiles[id].state === 'dry');
|
||||||
const pool = dry.length ? dry : opts;
|
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'];
|
const fl = state.tiles['fools-landing'];
|
||||||
if (!fl || isSunk(state, 'fools-landing')) return pool[0];
|
if (!fl || isSunk(state, 'fools-landing')) return pool[0];
|
||||||
let best = pool[0], bestD = Infinity;
|
let best = pool[0], bestD = Infinity;
|
||||||
|
|
@ -542,6 +707,7 @@ function bestSwim(state, opts) {
|
||||||
|
|
||||||
function advanceTurn(state) {
|
function advanceTurn(state) {
|
||||||
state.current = (state.current + 1) % state.players.length;
|
state.current = (state.current + 1) % state.players.length;
|
||||||
|
if (state.current === 0) state.round = (state.round ?? 1) + 1;
|
||||||
state.actionsLeft = ACTIONS_PER_TURN;
|
state.actionsLeft = ACTIONS_PER_TURN;
|
||||||
state.phase = 'actions';
|
state.phase = 'actions';
|
||||||
state.players[state.current].pilotFlew = false;
|
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
|
// Returns a `lost`-phase clone if the game is over, else null. Safe to call on
|
||||||
// any state.
|
// any state.
|
||||||
export function checkLoss(state) {
|
export function checkLoss(state) {
|
||||||
// Fools' Landing sunk.
|
// The Expedition Dock sunk.
|
||||||
if (isSunk(state, 'fools-landing')) {
|
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.
|
// A treasure became unreachable (both tiles sunk) and was never captured.
|
||||||
for (const key of TREASURE_KEYS) {
|
for (const key of TREASURE_KEYS) {
|
||||||
|
|
@ -561,11 +727,11 @@ export function checkLoss(state) {
|
||||||
if (captured) continue;
|
if (captured) continue;
|
||||||
const bothSunk = TREASURES[key].tiles.every((id) => isSunk(state, id));
|
const bothSunk = TREASURES[key].tiles.every((id) => isSunk(state, id));
|
||||||
if (bothSunk) {
|
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) {
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 };
|
||||||
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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 (_) { /* */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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 };
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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 = {}; }
|
||||||
|
}
|
||||||
|
|
@ -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 });
|
||||||
|
};
|
||||||
|
|
@ -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.*
|
*From the field journal of Professor A. Pike, Cartographer to the monsoon expedition. Pages loosened by damp; read quickly.*
|
||||||
|
|
||||||
*Come. I will teach you. Pay attention — the island does not wait.*
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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:
|
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.
|
||||||
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
|
|
||||||
|
|
||||||
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 |
|
| The Hollow Orb | Moonwell Sanctum, Sunspire Shrine |
|
||||||
| **Flooded** | Water is rising — shore it up or it sinks |
|
| The Gale Gryphon | The Verdant Nave, Hollow of the Grey Wolf |
|
||||||
| **Sunk** | Gone. Beneath the waves. Do not go there. |
|
| 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.
|
| Role | Special ability |
|
||||||
|
|------|-----------------|
|
||||||
| Treasure | Tiles Where It Is Found |
|
| **Bush Pilot** | Once per turn, fly to *any* tile for one action. |
|
||||||
|----------|-------------------------|
|
| **Field Engineer** | Shore up *two* tiles for one action. |
|
||||||
| The Earth Stone | Temple of the Moon, Temple of the Sun |
|
| **Wireless Operator** | Give Treasure cards to a teammate *anywhere* on the island. |
|
||||||
| The Statue of the Wind | Whispering Garden, Howling Garden |
|
| **Cartographer** | Spend an action to move another crew member up to two tiles. |
|
||||||
| The Crystal of Fire | Cave of Embers, Cave of Shadows |
|
| **Hard-Hat Diver** | Move through any number of flooded and sunken tiles in one move. |
|
||||||
| The Ocean's Chalice | Coral Palace, Tidal Palace |
|
| **Mountaineer** | Move and shore up *diagonally* as well as straight. |
|
||||||
|
|
||||||
*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.*
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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 |
|
Each of these costs one action:
|
||||||
|------|-------|---------------|
|
|
||||||
| **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 |
|
|
||||||
|
|
||||||
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:
|
Watch the storm too. The sky darkens and the rain thickens as the gauge climbs, and from level six there is lightning.
|
||||||
|
|
||||||
- **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.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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.
|
1. **The Expedition Dock sinks.** No helicopter can land on open water.
|
||||||
|
2. **Both shrines of a relic you have not recovered sink.**
|
||||||
| Difficulty | Starting Level | Flood Cards Per Turn |
|
3. **A crew member has nowhere to swim.**
|
||||||
|------------|---------------|----------------------|
|
4. **The tide gauge reaches the drowned mark** at the top.
|
||||||
| 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.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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.
|
- 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.
|
||||||
2. **Both tiles for an uncaptured treasure sink** — the treasure is lost forever.
|
- 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.
|
||||||
3. **An adventurer cannot swim to safety** when their tile sinks beneath them.
|
- Use the **Auto ▼** tag beside a partner's name to set a priority: a relic to focus on, regrouping, or defending the shrines.
|
||||||
4. **The water level reaches the skull marker** — the sea wins.
|
- 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.
|
*Good luck. Write everything down. If the pages get wet, write faster.*
|
||||||
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.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Balam's Notes from the Field
|
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.
|
||||||
|
|
||||||
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*
|
|
||||||
|
|
|
||||||
|
|
@ -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);
|
||||||
Loading…
Reference in New Issue