1249 lines
53 KiB
JavaScript
1249 lines
53 KiB
JavaScript
import { createTradeTransition } from "./trade-transition.js";
|
||
import { exportGoodHelp, exportReference } from "./export-reference.js";
|
||
import { mountBoard3D } from "./three/board.js";
|
||
import { playerSymbolGlyph } from "@boardgamers/protocol/player-symbols";
|
||
import {
|
||
blockingHtml,
|
||
blockingText,
|
||
cellHtml,
|
||
planText,
|
||
proseHtml,
|
||
} from "./blocking.js";
|
||
import { markerBlockers } from "../engine/marker-blockers.js";
|
||
import {
|
||
playerColorState,
|
||
playerColorText,
|
||
playerColorInk,
|
||
} from "./player-colors.js";
|
||
import { FIRST_HELP, RETRIEVE_CHOICE } from "./learning.js";
|
||
import { EXTEND_WHO, EXTEND_HOW, REMAINING_TILES } from "./learning.js";
|
||
import { createRenderer } from "./dom.js";
|
||
import {
|
||
ACTIONS,
|
||
CHARACTERS,
|
||
TILES,
|
||
PRICES,
|
||
VALUES,
|
||
} from "../engine/catalog.js";
|
||
import { goodsAvailable, actionsAfterExchanges } from "../engine/index.js";
|
||
import { assets } from "./assets.js";
|
||
import {
|
||
icon as renderIcon,
|
||
token as renderToken,
|
||
iconLabel,
|
||
esc,
|
||
} from "./art.js";
|
||
import { boardSvg, center, tilePreviewSvg } from "./board.js";
|
||
import { mountMapZoom } from "./map-zoom.js";
|
||
import { translator, characterHelp } from "./labels.js";
|
||
import { mountActivity } from "./activity.js";
|
||
import { pictogramText } from "./prose.js";
|
||
import { rulesHtml } from "./rules.js";
|
||
import { createMoveSound } from "./sound.js";
|
||
import { createEffects, liveEvents } from "./effects.js";
|
||
import {
|
||
languages,
|
||
resolveLocale,
|
||
translateText,
|
||
} from "./localization/index.js";
|
||
const total = (a) => a.reduce((a, b) => a + b, 0);
|
||
const unique = (a) => [...new Set(a)];
|
||
function coastArrow(cell, edge) {
|
||
const a = center(cell),
|
||
b = center(edge),
|
||
angle = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
|
||
return `<svg class="icon" viewBox="0 0 32 32" role="img" aria-label="Coast"><path d="M6 16h20m-8-8 8 8-8 8" fill="none" stroke="currentColor" stroke-width="2.5" transform="rotate(${angle} 16 16)"/></svg>`;
|
||
}
|
||
const actionHelp = {
|
||
sail: "Sail 1–3 ocean spaces, paying 1 vatu per space.",
|
||
fish: "Take a fish tile from your ocean space. Its value equals the fish remaining there.",
|
||
explore:
|
||
"Take a treasure tile from your ocean space. Treasures can be sold for vatus or kept for final scoring.",
|
||
sell: "Sell fish beside one of your huts at the current market price. The price then falls by 1.",
|
||
build:
|
||
"Build a hut on an adjacent island for 3 vatus. Each hut scores 2 prosperity per tourist at game end.",
|
||
buy: "Export a good from an adjacent island to a ship that needs it. Pay 1/2/3 vatus for kava/copra/beef and earn 1/3/5 prosperity.",
|
||
draw: "Make a sand drawing on an adjacent island to earn 3 prosperity.",
|
||
tourist:
|
||
"Bring a tourist to an adjacent island and earn 1 vatu for every hut there, of any colour.",
|
||
rest: "Choose a rest token. Its bonus is resolved at the end of the round.",
|
||
};
|
||
const defaultSymbols = ["●", "◆", "▲", "■", "✦"];
|
||
export function mountGame(target, options = {}) {
|
||
const root = document.createElement("div");
|
||
root.className = "vanuatu";
|
||
root.innerHTML =
|
||
'<div class="play"></div><div class="activity-root"></div><dialog class="help-dialog"></dialog><div class="feedback" role="alert" hidden></div>';
|
||
target.append(root);
|
||
const play = root.querySelector(".play"),
|
||
dialog = root.querySelector("dialog"),
|
||
feedback = root.querySelector(".feedback");
|
||
let avatars = [];
|
||
let appearance = {};
|
||
const symbol = (i) =>
|
||
playerSymbolGlyph(appearance.playerSymbols?.[i], defaultSymbols[i]);
|
||
const playerBadge = (i) => {
|
||
const badge = appearance.players?.[i]?.pro && appearance.supporterBadge;
|
||
return badge
|
||
? `<img class="supporter-badge" src="${esc(badge.url)}" alt="${esc(badge.label)}" title="${esc(badge.label)}">`
|
||
: "";
|
||
};
|
||
let playerColors = [];
|
||
let rawState;
|
||
const displayState = (state) =>
|
||
playerColorState(state, playerColors, colorBlind);
|
||
let s,
|
||
player,
|
||
enabled = true,
|
||
analysis = false,
|
||
pending = false,
|
||
selected = null,
|
||
action = null,
|
||
draft = [],
|
||
tile = null,
|
||
bonus = true,
|
||
exportHelpOpen = false,
|
||
lang = resolveLocale(options.language ?? "en"),
|
||
hostedLocale = false,
|
||
colorBlind = false,
|
||
sound = false,
|
||
animations = true,
|
||
autoRetrieve = false,
|
||
undoAvailable = false,
|
||
revision,
|
||
stateKey,
|
||
focusReturn;
|
||
let board3D,
|
||
threeUnavailable = false,
|
||
mapView = "2d",
|
||
mapLive = false,
|
||
journalCells = [];
|
||
try {
|
||
const savedView = localStorage.getItem("vanuatu-map-view");
|
||
if (savedView === "2d" || savedView === "3d") mapView = savedView;
|
||
} catch {}
|
||
root.dataset.mapView = mapView;
|
||
const patch = createRenderer(
|
||
".map-3d, .game-header, .action-dock, .market-info, .demand-ships, .export-reference, .map-scroll, .map-tools, .upcoming, .turn-tray, .player-card, .play-footer",
|
||
(from, to) => {
|
||
// These attributes belong to the layout/zoom controllers, not the state.
|
||
const attr = from.matches(".sea-board, .map-canvas, .archipelago")
|
||
? "style"
|
||
: from.matches(".map-scroll")
|
||
? "data-zoom"
|
||
: from.matches("[data-zoom-in], [data-zoom-out]")
|
||
? "aria-disabled"
|
||
: null;
|
||
if (attr && from.hasAttribute(attr))
|
||
to.setAttribute(attr, from.getAttribute(attr));
|
||
},
|
||
);
|
||
const icon = (name, label) =>
|
||
renderIcon(
|
||
name,
|
||
label ?? iconLabel(name, lang),
|
||
label !== undefined,
|
||
colorBlind,
|
||
);
|
||
const token = (name, n, label) =>
|
||
renderToken(name, n, label ?? `${iconLabel(name, lang)}: ${n}`, colorBlind);
|
||
let t = translator(lang);
|
||
const moveSound = createMoveSound();
|
||
const effects = createEffects(root, { icon, sound: moveSound, center });
|
||
const events = new AbortController();
|
||
const listener = { signal: events.signal };
|
||
root.addEventListener(
|
||
"pointerdown",
|
||
() => {
|
||
moveSound.unlock();
|
||
board3D?.unlock();
|
||
},
|
||
{
|
||
...listener,
|
||
passive: true,
|
||
},
|
||
);
|
||
root.addEventListener(
|
||
"keydown",
|
||
() => {
|
||
moveSound.unlock();
|
||
board3D?.unlock();
|
||
},
|
||
listener,
|
||
);
|
||
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
|
||
const mapZoom = mountMapZoom(play);
|
||
const tradeTransition = createTradeTransition(root, () => {
|
||
const node = play.querySelector(".demand-ships");
|
||
if (node && s) patch(node, tradeShips());
|
||
});
|
||
function syncMotion() {
|
||
animations = !reducedMotion.matches;
|
||
effects.setEnabled(animations);
|
||
mapZoom.setEnabled(animations);
|
||
tradeTransition.setEnabled(animations);
|
||
root.dataset.animations = String(animations);
|
||
syncBoard3D();
|
||
}
|
||
reducedMotion.addEventListener("change", syncMotion, listener);
|
||
syncMotion();
|
||
const trayObserver = new ResizeObserver(([entry]) => {
|
||
const parent = entry.target.parentElement;
|
||
const height = `${entry.borderBoxSize?.[0]?.blockSize ?? entry.target.getBoundingClientRect().height}px`;
|
||
if (parent && parent.style.getPropertyValue("--tray-height") !== height)
|
||
parent.style.setProperty("--tray-height", height);
|
||
});
|
||
let observedTray;
|
||
function observeTray() {
|
||
const tray = play.querySelector(".turn-tray");
|
||
// Size the map from the final panel before either renderer frames it.
|
||
// Waiting for ResizeObserver used to trigger a second camera fit.
|
||
if (tray) {
|
||
const height = `${tray.getBoundingClientRect().height}px`;
|
||
if (tray.parentElement.style.getPropertyValue("--tray-height") !== height)
|
||
tray.parentElement.style.setProperty("--tray-height", height);
|
||
}
|
||
if (tray === observedTray) return;
|
||
trayObserver.disconnect();
|
||
if (tray) trayObserver.observe(tray, { box: "border-box" });
|
||
observedTray = tray;
|
||
}
|
||
const activity = mountActivity(root.querySelector(".activity-root"), {
|
||
chat: options.chat,
|
||
openPlayer: options.onOpenPlayer,
|
||
avatarForPlayer: (index) => avatars[index],
|
||
onBack: () =>
|
||
play.scrollIntoView({
|
||
block: "start",
|
||
behavior:
|
||
animations && !matchMedia("(prefers-reduced-motion: reduce)").matches
|
||
? "smooth"
|
||
: "instant",
|
||
}),
|
||
onHighlight(cells) {
|
||
journalCells = cells;
|
||
updateMapFocus();
|
||
syncBoard3D();
|
||
},
|
||
language: lang,
|
||
});
|
||
activity.setLanguage(lang);
|
||
const legal = () => (enabled && !pending ? (s?.legal ?? []) : []);
|
||
const working = () =>
|
||
legal().filter((m) => !["treasure", "beg"].includes(m.type));
|
||
const actMoves = () =>
|
||
working().filter(
|
||
(m) =>
|
||
m.type === "act" &&
|
||
m.action === action &&
|
||
(action !== "sail" || m.path.at(-1) !== own()?.boat),
|
||
);
|
||
const actualTargets = () =>
|
||
action === "sail"
|
||
? unique(actMoves().map((m) => m.path.at(-1)))
|
||
: unique(
|
||
actMoves()
|
||
.map((m) => m.cell)
|
||
.filter(Boolean),
|
||
);
|
||
const own = () => s?.players[player];
|
||
const charName = (c) => esc(CHARACTERS[c]?.["name"] ?? c);
|
||
const charHelp = (c) => esc(characterHelp[c]?.[0] ?? "");
|
||
const charHelpHtml = (c) =>
|
||
`<span data-character-help="${esc(c)}" data-prose-locale="${lang}:${colorBlind}" translate="no">${pictogramText(translateText(characterHelp[c]?.[0] ?? "", lang), lang, colorBlind)}</span>`;
|
||
function btn(content, attr = "", className = "") {
|
||
return `<button type="button" class="${className}" ${attr}>${content}</button>`;
|
||
}
|
||
const titled = (name, content, attr = "", cls = "") =>
|
||
btn(content, `title="${esc(name)}" aria-label="${esc(name)}" ${attr}`, cls);
|
||
function actionDetail(m) {
|
||
if (m.type === "place") return `${t("choose")} ${icon("check")}`;
|
||
if (m.type === "character") return charName(m.character);
|
||
if (m.type === "plan" || m.type === "neutral")
|
||
return m.actions.map((a) => icon(a)).join("");
|
||
if (m.type === "discard")
|
||
return `${icon("warning", "Retrieve without acting")} ${icon(m.action)}`;
|
||
if (m.type === "rest") return restContent(m.token);
|
||
if (m.type === "governor") return `${icon(m.from)} → ${icon(m.to)}`;
|
||
if (m.type === "treasure")
|
||
return `${token("explore", total(m.values))} → ${token("coin", total(m.values))}`;
|
||
if (m.type === "beg")
|
||
return `${token("point", m.amount)} → ${token("coin", m.amount)}`;
|
||
if (m.action === "sail")
|
||
return `${token("sail", m.path.length)} · ${token("coin", m.bonus ? 0 : m.path.length)}`;
|
||
if (m.action === "fish")
|
||
return `${token("fish", s.board[own().boat].fish)}${m.bonus ? " + " + token("point", s.board[own().boat].fish) : ""}`;
|
||
if (m.action === "explore")
|
||
return `${token("explore", s.board[own().boat].treasure)}${m.bonus ? " + " + token("coin", s.board[own().boat].treasure) : ""}`;
|
||
if (m.action === "sell")
|
||
return `${m.fish.map((n) => token("fish", n)).join("")} → ${token("coin", total(m.fish) * s.market)}`;
|
||
if (m.action === "build")
|
||
return `${m.hut ? token("build", 1) : ""}${m.dike ? token("dike", 1) : ""} · ${token("coin", (m.hut ? (m.bonus ? 1 : 3) : 0) + (m.dike ? 1 : 0))}${m.dike ? ` <small>${coastArrow(m.cell, m.dike)}</small>` : ""}`;
|
||
if (m.action === "buy") {
|
||
const { gain, count } = exportPreview(m);
|
||
return `${token(m.good, count)} · ${esc(translateText("Cost", lang))} ${token("coin", `−${PRICES[m.good]}`)} → ${token("point", `+${gain}`)}`;
|
||
}
|
||
if (m.action === "draw")
|
||
return `${icon("draw")} → ${token("point", m.bonus ? 5 : 3)}`;
|
||
if (m.action === "tourist")
|
||
return `${icon("tourist")} → ${token("coin", s.board[m.cell].huts.length)}${m.bonus ? " + " + token("point", s.board[m.cell].drawings * 2) : ""}`;
|
||
return `${icon(m.action)} ${t(m.action)}`;
|
||
}
|
||
function exportPreview(m) {
|
||
let gain = 0,
|
||
count = 0,
|
||
completed = 0;
|
||
const ships = s.demands.map((d) => ({ ...d, filled: [...d.filled] }));
|
||
const quantity = m.bonus && goodsAvailable(s, m.good) > 0 ? 2 : 1;
|
||
for (let n = 0; n < quantity; n++) {
|
||
const d = ships.find((d) =>
|
||
d.goods.some((g, i) => g === m.good && !d.filled[i]),
|
||
);
|
||
if (!d) break;
|
||
d.filled[d.goods.findIndex((g, i) => g === m.good && !d.filled[i])] =
|
||
true;
|
||
count++;
|
||
gain += VALUES[m.good] + (d.filled.every(Boolean) ? 2 : 0);
|
||
if (d.filled.every(Boolean)) completed++;
|
||
}
|
||
return { gain, count, completed };
|
||
}
|
||
function exportHelp(m) {
|
||
const { gain, completed } = exportPreview(m);
|
||
const help = translateText(
|
||
"Vatus paid: {p0}. Prosperity gained: {p1}.",
|
||
lang,
|
||
)
|
||
.replace("{p0}", PRICES[m.good])
|
||
.replace("{p1}", gain);
|
||
return `${translateText(iconLabel(m.good), lang)}. ${help}${completed ? " " + translateText("Includes {p0} prosperity for completing ships.", lang).replace("{p0}", completed * 2) : ""}`;
|
||
}
|
||
function moveButton(m, primary = false) {
|
||
const idx = (s.legal ?? []).indexOf(m);
|
||
const exportLabel =
|
||
m.action === "buy" && m.type === "act" ? exportHelp(m) : "";
|
||
return btn(
|
||
actionDetail(m),
|
||
`title="${esc(exportLabel || (m.type === "discard" ? translateText("Retrieve without acting", lang) : m.action ? translateText(actionHelp[m.action], lang) : t(m.type === "plan" || m.type === "neutral" ? "plan" : m.type)))}" ${exportLabel ? `aria-label="${esc(exportLabel)}"` : ""} data-move="${idx}" ${m.type === "discard" ? `aria-label="${esc(translateText("Retrieve without acting", lang))} — ${esc(translateText(t(m.action), lang))}"` : ""} ${pending ? "disabled" : ""}`,
|
||
m.type === "discard"
|
||
? "move-option retrieve-warning"
|
||
: primary
|
||
? "primary move-option"
|
||
: "move-option",
|
||
);
|
||
}
|
||
function restContent(key) {
|
||
return key === "first"
|
||
? icon("first")
|
||
: key === "both"
|
||
? `${token("coin", 1)} + ${token("point", 1)}`
|
||
: token(key, 1);
|
||
}
|
||
function playerCard(p, i) {
|
||
const c = CHARACTERS[p.character];
|
||
return `<section data-player-card="${i}" class="player-card ${i === s.actor && !s.finished ? "active" : ""} ${i === player ? "own" : ""}" style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}"><div class="player-name">${btn(`${avatars[i] ? `<img class="player-avatar" src="${esc(avatars[i])}" alt="">` : ""}<span>${colorBlind ? symbol(i) + " " : ""}${esc(p.name)}</span>${playerBadge(i)}`, `data-bgs-player="${i}" title="${esc(p.name)}"`, "profile")} ${s.first === i ? btn(icon("first", translateText(FIRST_HELP, lang)), `data-first-help aria-label="${t("first")}"`, "icon-button") : ""}<strong class="score">${token("point", p.score)}</strong></div><div class="player-supplies">${token("coin", p.money)}<span class="hand" title="${t("fishStock")}">${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)}</span><span class="hand" title="${t("treasure")}">${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)}</span>${token("build", p.hutsLeft)}</div>${c ? `<button type="button" class="character-owned ${p.used ? "used" : ""}" data-character="${p.character}" title="${charName(p.character)}"><img src="${assets["character-" + c.art]}" alt=""><span>${charName(p.character)}</span>${p.used ? icon("check") : icon(c.action ?? "point")}</button>` : ""}${i === player ? `<div class="free-actions">${legal().some((m) => m.type === "treasure") ? btn(`${icon("explore")} → ${icon("coin")}`, `data-free="treasure" title="${t("treasure")}"`) : ""}${legal().some((m) => m.type === "beg") ? btn(`${icon("point")} → ${icon("coin")}`, `data-free="beg" title="${t("beg")}"`) : ""}</div>` : ""}</section>`;
|
||
}
|
||
function dock() {
|
||
const planning = ["plan", "neutral"].includes(s.phase) && working().length;
|
||
return `<nav class="action-dock" aria-label="${t("actions")}">${ACTIONS.map(
|
||
(a) => {
|
||
const emptySupply = a === "tourist" && s.tourists === 0;
|
||
const countDraft = draft.filter((x) => x === a).length;
|
||
const allowed = planning
|
||
? working().some((m) =>
|
||
s.phase === "neutral"
|
||
? draft.length < m.actions.length &&
|
||
[...draft, a].every(
|
||
(x) =>
|
||
[...draft, a].filter((y) => y === x).length <=
|
||
m.actions.filter((y) => y === x).length,
|
||
)
|
||
: m.actions
|
||
?.slice(0, draft.length)
|
||
.every((x, i) => x === draft[i]) &&
|
||
m.actions[draft.length] === a,
|
||
)
|
||
: working().some(
|
||
(m) =>
|
||
(m.type === "act" || m.type === "discard") && m.action === a,
|
||
);
|
||
const retrieveOnly =
|
||
!planning &&
|
||
allowed &&
|
||
working().some((m) => m.type === "discard" && m.action === a) &&
|
||
!working().some((m) => m.type === "act" && m.action === a);
|
||
const explain =
|
||
(s.phase === "actions" && own()?.markers[a] > 0 && !allowed) ||
|
||
(planning &&
|
||
s.phase === "plan" &&
|
||
!allowed &&
|
||
draft.length < (s.planningPass === 2 ? 1 : 2));
|
||
const hint = emptySupply
|
||
? "No tourists available this round."
|
||
: explain && s.phase === "actions"
|
||
? s.actor === player || markerBlockers(s, player, a).length
|
||
? blockingText(s, player, a, lang)
|
||
: "Wait for your turn."
|
||
: explain
|
||
? planText(s, player, a, lang, {
|
||
...own()?.markers,
|
||
...Object.fromEntries(
|
||
draft.map((x) => [
|
||
x,
|
||
(own()?.markers[x] ?? 0) +
|
||
draft.filter((y) => y === x).length,
|
||
]),
|
||
),
|
||
}) ||
|
||
({
|
||
fish: "Fishing requires fish on your boat's space. Plan Sail first if needed.",
|
||
explore:
|
||
"Exploring requires treasure on your boat's space. Plan Sail first if needed.",
|
||
sell: own()?.fish.length
|
||
? undefined
|
||
: "Selling requires fish. Plan Fish first if your hold is empty.",
|
||
}[a] ??
|
||
"This action is not possible with your current resources and planned actions. Plan its prerequisites first.")
|
||
: "";
|
||
const help = [
|
||
translateText(actionHelp[a], lang),
|
||
hint && translateText(hint, lang),
|
||
retrieveOnly && translateText("Retrieve without acting", lang),
|
||
retrieveOnly && blockingText(s, player, a, lang),
|
||
]
|
||
.filter(Boolean)
|
||
.join("\n");
|
||
const stacks = s.players
|
||
.map((p, i) =>
|
||
p.markers[a]
|
||
? `<span data-marker-player="${i}" class="marker-stack ${s.majorities?.[i]?.includes(a) ? "majority" : ""}" style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}" title="${esc(p.name)}: ${p.markers[a]}">${colorBlind ? symbol(i) : ""}${p.markers[a]}</span>`
|
||
: "",
|
||
)
|
||
.join("");
|
||
return btn(
|
||
`<span class="action-symbol">${icon(a)}</span><span class="action-content"><span class="action-label">${t(a)}</span><span class="action-stacks">${stacks}${retrieveOnly ? `<span class="retrieve-only-icon">${icon("warning", "Retrieve without acting")}</span>` : ""}${s.neutral[a] ? `<span class="marker-stack neutral" title="${"Neutral markers"}">${s.neutral[a]}</span>` : ""}${countDraft ? `<span class="draft-marker" title="${"Markers being placed"}">+${countDraft}</span>` : ""}</span></span>`,
|
||
`data-action="${a}" title="${esc(help)}" ${allowed ? "" : explain ? `aria-disabled="true" data-unavailable="${esc(hint)}"` : "disabled"} aria-pressed="${action === a}"`,
|
||
`${action === a ? "chosen" : ""} ${allowed ? "available" : ""} ${retrieveOnly ? "retrieve-only" : ""} ${emptySupply ? "supply-empty" : ""}`,
|
||
);
|
||
},
|
||
).join("")}</nav>`;
|
||
}
|
||
function tray() {
|
||
const moves = working();
|
||
if (s.finished)
|
||
return `<div class="turn-tray end-tray"><strong>${s.lost ? t("lost") : t("finished")}</strong>${btn(`${icon("point")} ${t("ended")}`, "data-scores", "primary")}</div>`;
|
||
if (!moves.length)
|
||
return `<div class="turn-tray waiting"><span class="turn-dot" style="background:${s.players[s.actor]?.color}"></span>${pending ? t("pending") : `${t("waiting")} <strong>${esc(s.players[s.actor]?.name ?? "")}</strong>`}</div>`;
|
||
if (s.phase === "character")
|
||
return `<div class="turn-tray character-tray"><div class="tray-title">${t("character")}</div><div class="character-choices">${moves
|
||
.filter((m) => m.type === "character")
|
||
.map((m) => {
|
||
const c = CHARACTERS[m.character];
|
||
return btn(
|
||
`<img src="${assets["character-" + c.art]}" alt=""><strong>${charName(m.character)}</strong>${charHelpHtml(m.character)}`,
|
||
`data-character-choice="${m.character}"`,
|
||
"character-choice",
|
||
);
|
||
})
|
||
.join("")}</div></div>`;
|
||
if (["plan", "neutral"].includes(s.phase)) {
|
||
const prefix = (m) =>
|
||
m.actions?.slice(0, draft.length).every((x, i) => x === draft[i]);
|
||
const complete = moves.find(
|
||
(m) => prefix(m) && m.actions.length === draft.length,
|
||
);
|
||
const count = moves[0]?.actions?.length ?? 0;
|
||
return `<div class="turn-tray"><div class="tray-title">${t(s.phase)} <small>${draft.length}/${count}</small></div><div class="draft-slots">${Array.from({ length: count }, (_, i) => `<span class="draft-slot">${draft[i] ? icon(draft[i]) : icon("marker")}</span>`).join("")}</div>${titled(t("undo"), icon("undo"), `data-undo ${draft.length ? "" : "disabled"}`, "icon-button")}${complete ? btn(`${icon("check")} ${t("confirm")}`, `data-move="${s.legal.indexOf(complete)}"`, "primary") : ""}</div>`;
|
||
}
|
||
if (s.phase === "expand") {
|
||
const tileChoices = unique(
|
||
moves.filter((m) => m.type === "place").map((m) => m.tile),
|
||
);
|
||
if (!tileChoices.includes(tile)) tile = tileChoices[0];
|
||
const m = moves.find(
|
||
(m) => m.type === "place" && m.tile === tile && m.cell === selected,
|
||
);
|
||
return `<div class="turn-tray"><div class="tray-title">${t("expand")} <small>${esc(translateText(REMAINING_TILES, lang))}: ${s.upcoming.length}</small></div><details class="expand-help"><summary>${t("help")}</summary><p>${esc(t(EXTEND_WHO))}</p><p>${esc(t(EXTEND_HOW))}</p></details><div class="tile-choices">${tileChoices.map((id) => btn(tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "choice-" + id }), `data-tile="${id}" aria-pressed="${tile === id}"`)).join("")}</div>${m ? moveButton(m, true) : ""}</div>`;
|
||
}
|
||
if (s.phase === "rest")
|
||
return `<div class="turn-tray"><strong>${t("restChoice")}</strong>${moves
|
||
.filter((m) => m.type === "rest")
|
||
.map((m) => moveButton(m, true))
|
||
.join("")}</div>`;
|
||
let opts = actMoves().sort(
|
||
(a, b) => (a.path?.length ?? 0) - (b.path?.length ?? 0),
|
||
);
|
||
const selectedAction = !!action;
|
||
const hasBonus = opts.some((m) => m.bonus),
|
||
hasNormal = opts.some((m) => !m.bonus);
|
||
opts = opts.filter((m) => !hasBonus || !hasNormal || m.bonus === bonus);
|
||
const targets = actualTargets();
|
||
if (targets.length)
|
||
opts = opts.filter((m) => (m.cell ?? m.path?.at(-1)) === selected);
|
||
// Only the destination and cost matter: longer routes have no added effect.
|
||
if (action === "sail") opts = opts.slice(0, 1);
|
||
const discard = moves.find(
|
||
(m) => m.type === "discard" && m.action === action,
|
||
);
|
||
const governor = moves.some((m) => m.type === "governor");
|
||
const pickText =
|
||
targets.length && !selected ? `${icon("sail")} ${"Choose a space"}` : "";
|
||
return `<div class="turn-tray ${discard ? "retrieval-tray" : ""}"><div class="tray-title">${selectedAction ? `${icon(action)} ${t(action)}` : t("actions")}</div>${discard ? `<p class="retrieval-help obstacles">${blockingHtml(s, player, action, lang, undefined, colorBlind)}</p>` : !selectedAction && moves.some((m) => m.type === "discard") ? `<p class="retrieval-help">${esc(translateText(RETRIEVE_CHOICE, lang))}</p>` : ""}${hasBonus && hasNormal ? `<label class="bonus-switch" title="${charHelp(own()?.character)}"><input type="checkbox" data-bonus ${bonus ? "checked" : ""}>${charName(own()?.character)}</label>` : ""}<span class="pick-hint">${pickText}</span><div class="move-options">${opts.map((m) => moveButton(m, true)).join("")}${discard ? moveButton(discard) : ""}</div>${governor ? btn(`${icon("marker")} ↔`, `data-governor title="${t("governor")}"`) : ""}${selectedAction ? titled(t("cancel"), icon("close"), "data-cancel", "icon-button") : ""}</div>`;
|
||
}
|
||
function tradeShips() {
|
||
const help =
|
||
"First ship needing the good (1 → 3). Complete ship: +2 prosperity.";
|
||
return `<div class="demand-ships" role="group" aria-label="Foreign trade">${tradeTransition
|
||
.demands(s.demands)
|
||
.map(
|
||
(d, i) =>
|
||
`<div class="demand-ship" data-ship="${d.id}" title="${esc(help)}"><small>${i + 1}</small>${d.goods
|
||
.map((g, j) => {
|
||
const goodHelp = exportGoodHelp(
|
||
g,
|
||
d.filled[j] ? "delivered" : "available",
|
||
);
|
||
return `<span class="${d.filled[j] ? "filled" : ""}" data-good="${g}" role="img" aria-label="${esc(goodHelp)}" title="${esc(goodHelp)}">${icon(g, goodHelp)}${d.filled[j] ? icon("check", goodHelp) : ""}</span>`;
|
||
})
|
||
.join("")}${icon("buy", help)}</div>`,
|
||
)
|
||
.join("")}</div>`;
|
||
}
|
||
function renderControls() {
|
||
const focus = document.activeElement?.getAttribute("data-action");
|
||
patch(play.querySelector(".action-dock"), dock());
|
||
patch(play.querySelector(".turn-tray"), tray());
|
||
observeTray();
|
||
// The highlights below are updated outside the HTML renderer.
|
||
patch.invalidate(play.querySelector(".map-scroll"));
|
||
const targets = new Set(actualTargets());
|
||
for (const cell of play.querySelectorAll(".map-cell[data-cell]")) {
|
||
const id = cell.dataset.cell;
|
||
const selectable = targets.has(id);
|
||
cell.classList.toggle("legal", selectable);
|
||
cell.classList.toggle("selected", selected === id);
|
||
const highlight = play.querySelector(`[data-highlight-cell="${id}"]`);
|
||
highlight?.classList.toggle("legal", selectable);
|
||
highlight?.classList.toggle("selected", selected === id);
|
||
if (selectable) {
|
||
cell.setAttribute("role", "button");
|
||
cell.setAttribute("tabindex", "0");
|
||
cell.setAttribute(
|
||
"aria-label",
|
||
`${t(s.board[id]?.type === "island" ? "island" : "sea")} ${id}`,
|
||
);
|
||
} else {
|
||
for (const attribute of ["role", "tabindex", "aria-label"])
|
||
cell.removeAttribute(attribute);
|
||
}
|
||
}
|
||
updateMapFocus();
|
||
syncBoard3D();
|
||
if (focus)
|
||
play
|
||
.querySelector(`[data-action="${focus}"]`)
|
||
?.focus({ preventScroll: true });
|
||
}
|
||
function setMapView(value, notify = false) {
|
||
if (value !== "2d" && value !== "3d") return;
|
||
mapView = threeUnavailable ? "2d" : value;
|
||
root.dataset.mapView = mapView;
|
||
try {
|
||
localStorage.setItem("vanuatu-map-view", mapView);
|
||
} catch {}
|
||
const select = dialog.querySelector("[data-map-preference]");
|
||
if (select) select.value = mapView;
|
||
effects.cancel();
|
||
moveSound.stop();
|
||
if (notify) options.onPreference?.("mapView", mapView);
|
||
}
|
||
function syncBoard3D() {
|
||
if (!s) return;
|
||
const host = play.querySelector(".map-3d");
|
||
if (mapView === "3d" && !board3D && !threeUnavailable) {
|
||
try {
|
||
board3D = mountBoard3D(host, { onSelect: cellClick });
|
||
} catch (error) {
|
||
console.warn("3D unavailable; using 2D", error);
|
||
threeUnavailable = true;
|
||
mapView = "2d";
|
||
root.dataset.mapView = mapView;
|
||
for (const button of play.querySelectorAll("[data-map-view]")) {
|
||
button.setAttribute(
|
||
"aria-pressed",
|
||
String(button.dataset.mapView === mapView),
|
||
);
|
||
if (button.dataset.mapView === "3d") button.disabled = true;
|
||
}
|
||
}
|
||
}
|
||
play
|
||
.querySelector(".map-scroll")
|
||
?.toggleAttribute("inert", mapView === "3d");
|
||
if (!board3D) return;
|
||
const targets =
|
||
s.phase === "expand"
|
||
? working()
|
||
.filter((m) => m.type === "place" && m.tile === tile)
|
||
.map((m) => m.cell)
|
||
: actualTargets();
|
||
board3D.setVisible(mapView === "3d");
|
||
board3D.update(s, {
|
||
selected,
|
||
targets,
|
||
hoverTile: tile,
|
||
player,
|
||
colorBlind,
|
||
journalCells,
|
||
symbols: s.players.map((_, i) => symbol(i)),
|
||
language: lang,
|
||
animations,
|
||
sound,
|
||
live: mapLive,
|
||
});
|
||
mapLive = false;
|
||
}
|
||
let boardKey, boardHtml;
|
||
function renderBoard(targets) {
|
||
const hoverTile = s.phase === "expand" ? tile : null;
|
||
const next = JSON.stringify([
|
||
s.boardLayout,
|
||
s.board,
|
||
s.players.map(({ boat, name, color }) => [boat, name, color]),
|
||
player,
|
||
colorBlind,
|
||
appearance.playerSymbols,
|
||
lang,
|
||
selected,
|
||
targets,
|
||
hoverTile,
|
||
]);
|
||
if (boardKey !== next) {
|
||
boardKey = next;
|
||
boardHtml = boardSvg(s, {
|
||
player,
|
||
colorBlind,
|
||
playerSymbols: appearance.playerSymbols,
|
||
language: lang,
|
||
selected,
|
||
targets,
|
||
hoverTile,
|
||
t,
|
||
});
|
||
}
|
||
return boardHtml;
|
||
}
|
||
function render() {
|
||
if (!s) {
|
||
play.innerHTML = `<p class="loading">${t("connected")}</p>`;
|
||
return;
|
||
}
|
||
const focus = play.contains(document.activeElement)
|
||
? document.activeElement?.getAttribute("data-action")
|
||
: null;
|
||
const mapAnchor = mapZoom.capture();
|
||
const trayHtml = tray();
|
||
const marketHelp = `Fish price: ${s.market} vatus per fish value. Falls by 1 after each sale (minimum 1); resets to 3 next round.`;
|
||
const targets =
|
||
s.phase === "expand"
|
||
? working()
|
||
.filter((m) => m.type === "place" && m.tile === tile)
|
||
.map((m) => m.cell)
|
||
: actualTargets();
|
||
const html = `<header class="game-header"><div class="brand">${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}<div class="game-credits"><span>Designed by Alain Epron</span><span>Published by Quined Games</span></div></div><div class="round-track" aria-label="${t("round")} ${s.round}/8">${Array.from({ length: 8 }, (_, i) => `<span title="${t("round")} ${i + 1}/8" class="${i + 1 === s.round ? "current" : i + 1 < s.round ? "past" : ""}">${i + 1}</span>`).join("")}</div><nav class="header-tools">${undoAvailable && enabled && !analysis ? titled(t("undoMove"), icon("undo"), "data-undo-move", "icon-button") : ""}${analysis || !options.chat ? "" : titled(t("chat"), `${icon("chat")}<span class="unread-badge" hidden></span>`, 'data-activity="chat"', "icon-button")}${titled(t("journal"), icon("journal"), 'data-activity="journal"', "icon-button")}${titled(t("colorBlind"), icon("colorBlind"), `data-color-blind aria-pressed="${colorBlind}"`, "icon-button")}${titled(t("help"), icon("help"), "data-help", "icon-button")}${titled(t("full"), icon("fullscreen"), "data-fullscreen", "icon-button")}</nav></header>
|
||
<div class="table">${dock()}<section class="sea-board" data-export-help-open="${exportHelpOpen}"><div class="sea-dashboard"><div class="market-info"><span class="fish-price" title="${esc(marketHelp)}">${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}</span><span title="${t("tourist")}">${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}</span>${s.waterCountdown !== null ? `<span title="${t("waterLeft")}">${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}</span>` : ""}${titled("Export goods", icon("buy"), `data-export-help aria-expanded="${exportHelpOpen}"`, "export-help-toggle icon-button")}</div><div class="trade-info">${tradeShips()}${exportReference(colorBlind)}</div></div><div class="map-scroll"><div class="map-canvas">${renderBoard(targets)}</div></div><div class="map-3d"></div><div class="map-tools"><span class="map-view-switch">${btn("2D", `data-map-view="2d" aria-pressed="${mapView === "2d"}"`)}${btn("3D", `data-map-view="3d" aria-pressed="${mapView === "3d"}" ${threeUnavailable ? "disabled" : ""}`)}</span><span class="three-tools">${titled(translateText("Overview", lang), icon("overview"), "data-three-home", "icon-button")}${titled("Zoom out", icon("zoomOut"), "data-three-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-three-in", "icon-button")}</span>${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}</div>${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}</section></div><section class="players">${s.players.map(playerCard).join("")}</section><footer class="play-footer"><span title="${"Automatic conversion"}">${token("coin", 10)} → ${token("point", 5)}</span>${btn(t("help"), "data-help", "text-button")}</footer>`;
|
||
// Patch in place so cached SVG tile images and focused controls survive
|
||
// preference changes and incoming state updates.
|
||
patch(play, `<div class="play">${html}</div>`, true);
|
||
updateMapFocus();
|
||
observeTray();
|
||
mapZoom.update(mapAnchor);
|
||
syncBoard3D();
|
||
if (focus)
|
||
play
|
||
.querySelector(`[data-action="${focus}"]`)
|
||
?.focus({ preventScroll: true });
|
||
const rules = dialog.querySelector("[data-rules-content]");
|
||
const rulesKey = `${lang}:${colorBlind}`;
|
||
if (rules && rules.dataset.presentation !== rulesKey) {
|
||
rules.innerHTML = rulesHtml(lang, colorBlind);
|
||
rules.dataset.presentation = rulesKey;
|
||
}
|
||
for (const help of dialog.querySelectorAll("[data-character-help]")) {
|
||
if (help.dataset.proseLocale === rulesKey) continue;
|
||
help.innerHTML = pictogramText(
|
||
translateText(
|
||
characterHelp[help.dataset.characterHelp]?.[0] ?? "",
|
||
lang,
|
||
),
|
||
lang,
|
||
colorBlind,
|
||
);
|
||
help.dataset.proseLocale = rulesKey;
|
||
}
|
||
activity.update(s, analysis, colorBlind);
|
||
updateUnread();
|
||
}
|
||
let chatNotifications = true;
|
||
function updateUnread() {
|
||
const n = options.chat?.snapshot.unreadIds.length ?? 0;
|
||
const badge = play.querySelector(".unread-badge");
|
||
if (badge) {
|
||
if (badge.textContent !== String(n)) badge.textContent = n;
|
||
if (badge.hidden !== !n) badge.hidden = !n;
|
||
}
|
||
activity.setUnread(n, chatNotifications);
|
||
}
|
||
const offChat = options.chat?.subscribe(updateUnread);
|
||
function showDialog(html) {
|
||
focusReturn = document.activeElement;
|
||
dialog.innerHTML = `<button type="button" class="dialog-close icon-button" data-close aria-label="${t("cancel")}">${icon("close")}</button>${html}`;
|
||
if (!dialog.open) dialog.showModal();
|
||
}
|
||
function closeDialog() {
|
||
dialog.close();
|
||
focusReturn?.isConnected && focusReturn.focus({ preventScroll: true });
|
||
}
|
||
function confirmRetrieval(move) {
|
||
const actions = unique(
|
||
legal()
|
||
.filter((m) => m.type === "act")
|
||
.map((m) => m.action),
|
||
);
|
||
const governor = legal().some((m) => m.type === "governor");
|
||
const exchanges = actionsAfterExchanges(s, player);
|
||
if (!actions.length && !governor && !exchanges.length) return false;
|
||
const actionLabel = (a) => `${icon(a)} ${esc(translateText(t(a), lang))}`;
|
||
const now = actions.map((a) => btn(actionLabel(a), `data-action="${a}"`));
|
||
if (governor)
|
||
now.push(
|
||
btn(
|
||
`${icon("marker")} ↔ ${esc(translateText(t("governor"), lang))}`,
|
||
"data-governor",
|
||
),
|
||
);
|
||
const funded = exchanges
|
||
.map(
|
||
(route) =>
|
||
`<div class="retrieval-route">${btn(route.exchanges.map((type) => esc(translateText(t(type), lang))).join(" + "), `data-free="${route.exchanges[0]}"`)}<span aria-hidden="true">→</span><span class="retrieval-unlocks">${route.actions.map((a) => `<span>${actionLabel(a)}</span>`).join("")}</span></div>`,
|
||
)
|
||
.join("");
|
||
showDialog(
|
||
`<h2>${icon("warning", "Retrieve without acting")} ${esc(translateText("Retrieve without acting", lang))} — ${esc(translateText(t(move.action), lang))}</h2>${now.length ? `<h3>${esc(translateText("Available now", lang))}</h3><div class="move-options retrieval-alternatives">${now.join("")}</div>` : ""}${funded ? `<h3>${esc(translateText("After free exchanges", lang))}</h3>${funded}<p>${esc(translateText("Free exchanges are optional and do not use markers or end your turn.", lang))}</p>` : ""}<p class="retrieval-question">${esc(translateText("Retrieve this stack without acting?", lang))}</p><div class="move-options">${btn(t("cancel"), "data-close")}${btn(icon("warning", "Retrieve without acting") + " " + t("confirm"), `data-move="${s.legal.indexOf(move)}" data-confirmed-retrieval`, "retrieve-warning")}</div>`,
|
||
);
|
||
return true;
|
||
}
|
||
async function send(m) {
|
||
if (!m || pending || !enabled) return;
|
||
moveSound.unlock();
|
||
pending = true;
|
||
feedback.hidden = true;
|
||
render();
|
||
try {
|
||
// A tutorial rejection is already explained by its guide. Keep the draft
|
||
// available to correct, without playing a move sound or a second alert.
|
||
if ((await options.onMove?.(m)) === false) {
|
||
closeDialog();
|
||
return;
|
||
}
|
||
selected = null;
|
||
action = null;
|
||
draft = [];
|
||
closeDialog();
|
||
} catch (e) {
|
||
feedback.textContent = e?.message ?? String(e);
|
||
feedback.hidden = false;
|
||
} finally {
|
||
pending = false;
|
||
render();
|
||
}
|
||
}
|
||
function cellClick(id) {
|
||
if (s.phase === "expand") {
|
||
if (working().some((m) => m.cell === id && m.tile === tile))
|
||
selected = id;
|
||
} else if (actualTargets().includes(id)) selected = id;
|
||
else {
|
||
const b = s.board[id];
|
||
// Say why a space cannot be chosen for the selected action.
|
||
const why =
|
||
action && s.phase === "actions"
|
||
? cellHtml(s, player, action, id, lang, colorBlind)
|
||
: "";
|
||
const reason = why
|
||
? `<p class="cell-unavailable obstacles">${why}</p>`
|
||
: "";
|
||
if (b?.type === "island")
|
||
showDialog(
|
||
`<h2>${t("island")}</h2>${reason}<div class="island-detail"><img src="${assets[TILES[b.id].art]}" alt=""><div>${token("build", `${b.huts.length}/${TILES[b.id].huts}`)} ${token("tourist", `${b.tourists}/${TILES[b.id].tourists}`)} ${token("draw", `${b.drawings}/${TILES[b.id].drawings}`)}<p>${Object.entries(
|
||
b.goods,
|
||
)
|
||
.map(([g, n]) => token(g, n))
|
||
.join("")}</p></div></div>`,
|
||
);
|
||
else if (why)
|
||
showDialog(`<h2>${icon(action)} ${t(action)}</h2>${reason}`);
|
||
}
|
||
if (s.phase === "expand") render();
|
||
else renderControls();
|
||
}
|
||
function updateMapFocus() {
|
||
for (const cell of play.querySelectorAll("[data-highlight-cell]"))
|
||
cell.classList.toggle(
|
||
"journal-highlight",
|
||
journalCells.includes(cell.dataset.highlightCell),
|
||
);
|
||
const cell = play.querySelector('.map-cell[role="button"]:focus-visible');
|
||
const highlight =
|
||
cell &&
|
||
play.querySelector(`[data-highlight-cell="${cell.dataset.cell}"]`);
|
||
for (const previous of play.querySelectorAll(".cell-highlight.focused"))
|
||
if (previous !== highlight) previous.classList.remove("focused");
|
||
if (highlight && !highlight.classList.contains("focused"))
|
||
highlight.classList.add("focused");
|
||
}
|
||
for (const event of ["focusin", "focusout"])
|
||
root.addEventListener(event, updateMapFocus, listener);
|
||
for (const event of ["pointerover", "pointerout"])
|
||
root.addEventListener(
|
||
event,
|
||
(e) => {
|
||
const cell = e.target.closest(".map-cell[data-cell]");
|
||
if (!cell || cell.contains(e.relatedTarget)) return;
|
||
play
|
||
.querySelector(`[data-highlight-cell="${cell.dataset.cell}"]`)
|
||
?.classList.toggle("hovered", event === "pointerover");
|
||
},
|
||
listener,
|
||
);
|
||
root.addEventListener(
|
||
"click",
|
||
(e) => {
|
||
const button = e.target.closest("button");
|
||
const cell = e.target.closest("[data-cell]");
|
||
if (cell) {
|
||
cellClick(cell.dataset.cell);
|
||
return;
|
||
}
|
||
if (!button || button.disabled) return;
|
||
const d = button.dataset;
|
||
if ("mapView" in d) {
|
||
setMapView(d.mapView, true);
|
||
render();
|
||
return;
|
||
}
|
||
if ("threeHome" in d) {
|
||
board3D?.reset();
|
||
return;
|
||
}
|
||
if ("threeIn" in d) {
|
||
board3D?.zoom(0.8);
|
||
return;
|
||
}
|
||
if ("threeOut" in d) {
|
||
board3D?.zoom(1.25);
|
||
return;
|
||
}
|
||
if ("undoMove" in d) {
|
||
options.onUndo?.();
|
||
return;
|
||
}
|
||
if ("upcoming" in d) {
|
||
showDialog(
|
||
`<h2>${t("next")}</h2><div class="upcoming-details">${s.upcoming
|
||
.map(
|
||
(id) =>
|
||
`<div class="tile-preview">${tilePreviewSvg(id, { t, colorBlind, language: lang })}</div>`,
|
||
)
|
||
.join("")}</div>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("exportHelp" in d) {
|
||
exportHelpOpen = !exportHelpOpen;
|
||
render();
|
||
return;
|
||
}
|
||
if ("firstHelp" in d) {
|
||
showDialog(
|
||
`<h2>${t("first")}</h2><p>${esc(translateText(FIRST_HELP, lang))}</p>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("unavailable" in d) {
|
||
const blocked =
|
||
s.phase === "actions" &&
|
||
(s.actor === player ||
|
||
markerBlockers(s, player, d.action).length > 0);
|
||
showDialog(
|
||
`<h2>${icon(d.action)} ${t(d.action)}</h2><p class="obstacles">${blocked ? blockingHtml(s, player, d.action, lang, undefined, colorBlind) : proseHtml(translateText(d.unavailable, lang), lang, colorBlind)}</p>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("move" in d) {
|
||
const move = s.legal[Number(d.move)];
|
||
if (
|
||
move?.type === "discard" &&
|
||
!("confirmedRetrieval" in d) &&
|
||
confirmRetrieval(move)
|
||
) {
|
||
return;
|
||
}
|
||
send(move);
|
||
return;
|
||
}
|
||
if ("bgsPlayer" in d) {
|
||
options.onOpenPlayer?.(Number(d.bgsPlayer));
|
||
return;
|
||
}
|
||
if ("boardgame" in d) {
|
||
options.onOpenBoardgame?.();
|
||
return;
|
||
}
|
||
if ("close" in d) {
|
||
closeDialog();
|
||
return;
|
||
}
|
||
if ("action" in d) {
|
||
if (button.closest("dialog")) closeDialog();
|
||
if (["plan", "neutral"].includes(s.phase)) {
|
||
draft.push(d.action);
|
||
if (s.phase === "neutral")
|
||
draft.sort((a, b) => ACTIONS.indexOf(a) - ACTIONS.indexOf(b));
|
||
renderControls();
|
||
effects.drop(
|
||
play.querySelector(`[data-action="${d.action}"] .draft-marker`),
|
||
);
|
||
moveSound.unlock();
|
||
void moveSound.play("marker");
|
||
return;
|
||
} else {
|
||
action = d.action;
|
||
selected = null;
|
||
const targets = actualTargets();
|
||
if (targets.length === 1) selected = targets[0];
|
||
}
|
||
renderControls();
|
||
return;
|
||
}
|
||
if ("undo" in d) {
|
||
draft.pop();
|
||
renderControls();
|
||
return;
|
||
}
|
||
if ("tile" in d) {
|
||
tile = d.tile;
|
||
selected = null;
|
||
render();
|
||
return;
|
||
}
|
||
if ("cancel" in d) {
|
||
action = null;
|
||
selected = null;
|
||
renderControls();
|
||
return;
|
||
}
|
||
if ("zoomIn" in d || "zoomOut" in d) {
|
||
mapZoom.step("zoomIn" in d ? 1 : -1);
|
||
return;
|
||
}
|
||
if ("characterChoice" in d) {
|
||
const m = s.legal.find(
|
||
(m) => m.type === "character" && m.character === d.characterChoice,
|
||
);
|
||
showDialog(
|
||
`<div class="character-detail"><img src="${assets["character-" + CHARACTERS[m.character].art]}" alt=""><div><h2>${charName(m.character)}</h2><p>${charHelpHtml(m.character)}</p>${moveButton(m, true)}</div></div>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("character" in d) {
|
||
showDialog(
|
||
`<div class="character-detail"><img src="${assets["character-" + CHARACTERS[d.character].art]}" alt=""><div><h2>${charName(d.character)}</h2><p>${charHelpHtml(d.character)}</p><small>${"Once per round."}</small></div></div>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("free" in d) {
|
||
showDialog(
|
||
`<h2>${t(d.free)}</h2><div class="move-options">${legal()
|
||
.filter((m) => m.type === d.free)
|
||
.map((m) => moveButton(m, true))
|
||
.join("")}</div>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("governor" in d) {
|
||
showDialog(
|
||
`<h2>${t("governor")}</h2><div class="move-options">${working()
|
||
.filter((m) => m.type === "governor")
|
||
.map((m) => moveButton(m, true))
|
||
.join("")}</div>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("activity" in d) {
|
||
activity.open(d.activity);
|
||
return;
|
||
}
|
||
if ("colorBlind" in d) {
|
||
colorBlind = !colorBlind;
|
||
options.onPreference?.("colorBlind", colorBlind);
|
||
render();
|
||
play
|
||
.querySelector("[data-color-blind]")
|
||
?.focus({ preventScroll: true });
|
||
return;
|
||
}
|
||
if ("fullscreen" in d) {
|
||
if (document.fullscreenElement) document.exitFullscreen?.();
|
||
else root.requestFullscreen?.().catch(() => {});
|
||
return;
|
||
}
|
||
if ("help" in d) {
|
||
showDialog(
|
||
`<h2>${t("help")}</h2><div class="preferences"><label><input type="checkbox" data-pref="colorBlind" ${colorBlind ? "checked" : ""}>${t("colorBlind")}</label><select data-map-preference aria-label="2D / 3D"><option value="2d" ${mapView === "2d" ? "selected" : ""}>2D</option><option value="3d" ${mapView === "3d" ? "selected" : ""} ${threeUnavailable ? "disabled" : ""}>3D</option></select><label><input type="checkbox" data-pref="sound" ${sound ? "checked" : ""}>${t("sound")}</label>${options.onSetting && Number.isInteger(player) && !analysis ? `<label><input type="checkbox" data-setting="autoRetrieve" ${autoRetrieve ? "checked" : ""}>${esc(translateText("Auto-retrieve when forced", lang))}</label>` : ""}${
|
||
hostedLocale
|
||
? ""
|
||
: `<select data-language aria-label="Language">${Object.entries(
|
||
languages,
|
||
)
|
||
.map(
|
||
([locale, name]) =>
|
||
`<option value="${locale}" ${lang === locale ? "selected" : ""}>${name}</option>`,
|
||
)
|
||
.join("")}</select>`
|
||
}</div><div data-rules-content>${rulesHtml(lang, colorBlind)}</div><hr><h3>${t("credit")}</h3><p>Alain Epron · <a href="https://www.quined.nl/featured_item/vanuatu-2nd-edition/" target="_blank" rel="noopener">Quined Games</a><br>Art: Konstantin Vohwinkel · Rafaël Theunis</p><p><a href="https://codeberg.org/boardgamers/vanuatu" target="_blank" rel="noopener">${t("source")}</a></p>`,
|
||
);
|
||
return;
|
||
}
|
||
if ("scores" in d) {
|
||
showDialog(
|
||
`<h2>${t("ended")}</h2><div class="final-scores">${[...s.players]
|
||
.map((p, i) => ({ ...p, i }))
|
||
.sort((a, b) => b.score - a.score)
|
||
.map(
|
||
(p) =>
|
||
`<div style="--player:${p.color};--player-ink:${playerColorInk(p.color)};--player-text:${playerColorText(p.color)}"><b>${esc(p.name)}</b>${token("point", p.score)}${
|
||
p.final
|
||
? `<small>${Object.entries(p.final)
|
||
.filter(([, v]) => v !== 0)
|
||
.map(([k, v]) =>
|
||
token(
|
||
{
|
||
wealth: "coin",
|
||
treasure: "explore",
|
||
tourists: "tourist",
|
||
first: "first",
|
||
water: "water",
|
||
}[k],
|
||
v,
|
||
),
|
||
)
|
||
.join(" · ")}</small>`
|
||
: ""
|
||
}</div>`,
|
||
)
|
||
.join("")}</div>`,
|
||
);
|
||
}
|
||
},
|
||
listener,
|
||
);
|
||
root.addEventListener(
|
||
"change",
|
||
(e) => {
|
||
if (e.target.matches("[data-bonus]")) {
|
||
bonus = e.target.checked;
|
||
renderControls();
|
||
}
|
||
if (e.target.matches("[data-pref]")) {
|
||
const key = e.target.dataset.pref,
|
||
value = e.target.checked;
|
||
if (key === "colorBlind") {
|
||
colorBlind = value;
|
||
}
|
||
if (key === "sound") {
|
||
sound = value;
|
||
moveSound.setEnabled(value);
|
||
syncBoard3D();
|
||
moveSound.unlock();
|
||
}
|
||
options.onPreference?.(key, value);
|
||
render();
|
||
}
|
||
if (e.target.matches("[data-map-preference]")) {
|
||
setMapView(e.target.value, true);
|
||
render();
|
||
}
|
||
if (e.target.matches("[data-setting]")) {
|
||
options.onSetting?.(e.target.dataset.setting, e.target.checked);
|
||
e.target.checked = autoRetrieve;
|
||
}
|
||
if (e.target.matches("[data-language]")) {
|
||
lang = e.target.value;
|
||
t = translator(lang);
|
||
closeDialog();
|
||
activity.setLanguage(lang);
|
||
render();
|
||
options.onPreference?.("language", lang);
|
||
}
|
||
},
|
||
listener,
|
||
);
|
||
root.addEventListener(
|
||
"keydown",
|
||
(e) => {
|
||
const cell = e.target.closest("[data-cell]");
|
||
if (cell && ["Enter", " "].includes(e.key)) {
|
||
e.preventDefault();
|
||
cellClick(cell.dataset.cell);
|
||
}
|
||
},
|
||
listener,
|
||
);
|
||
dialog.addEventListener(
|
||
"click",
|
||
(e) => {
|
||
if (e.target === dialog && e.offsetX >= 0 && e.offsetY >= 0) {
|
||
const r = dialog.getBoundingClientRect();
|
||
if (
|
||
e.clientX < r.left ||
|
||
e.clientX > r.right ||
|
||
e.clientY < r.top ||
|
||
e.clientY > r.bottom
|
||
)
|
||
closeDialog();
|
||
}
|
||
},
|
||
listener,
|
||
);
|
||
return {
|
||
root,
|
||
render(state, { live = true } = {}) {
|
||
const before = s;
|
||
const incoming = live && !analysis ? liveEvents(before, state) : [];
|
||
const captured = incoming.length ? effects.capture() : null;
|
||
const next = `${state.historyLength ?? state.round + ":" + state.phase}:${player}`;
|
||
const key = JSON.stringify(state);
|
||
mapLive = live && !analysis;
|
||
rawState = state;
|
||
s = displayState(state);
|
||
if (stateKey === key && next === revision) return;
|
||
stateKey = key;
|
||
effects.cancel();
|
||
tradeTransition.prepare(before, s, incoming);
|
||
if (!incoming.length) moveSound.stop();
|
||
if (next !== revision) {
|
||
selected = null;
|
||
action = null;
|
||
draft = [];
|
||
revision = next;
|
||
}
|
||
render();
|
||
if (incoming.length) effects.show(incoming, before, s, captured, player);
|
||
void tradeTransition.run();
|
||
},
|
||
setAvatars(value) {
|
||
if (JSON.stringify(avatars) === JSON.stringify(value)) return;
|
||
avatars = value;
|
||
render();
|
||
activity.refreshAvatars();
|
||
},
|
||
setPlayer(p) {
|
||
if (player === p) return;
|
||
player = p;
|
||
draft = [];
|
||
action = null;
|
||
selected = null;
|
||
render();
|
||
},
|
||
whenIdle: () =>
|
||
Promise.all([
|
||
board3D?.whenIdle(),
|
||
mapZoom.whenIdle(),
|
||
tradeTransition.whenIdle(),
|
||
effects.whenIdle(),
|
||
]),
|
||
stopEffects() {
|
||
board3D?.settle();
|
||
mapZoom.settle();
|
||
tradeTransition.cancel();
|
||
effects.cancel();
|
||
moveSound.stop();
|
||
},
|
||
setEnabled(v) {
|
||
if (enabled === v) return;
|
||
enabled = v;
|
||
render();
|
||
},
|
||
// BGS takes back the player's last move in games against bots (protocol `undo`).
|
||
setUndoAvailable(v) {
|
||
if (undoAvailable === v) return;
|
||
undoAvailable = v;
|
||
render();
|
||
},
|
||
setSettings(settings) {
|
||
autoRetrieve = settings?.autoRetrieve === true;
|
||
const checkbox = dialog.querySelector('[data-setting="autoRetrieve"]');
|
||
if (checkbox) checkbox.checked = autoRetrieve;
|
||
},
|
||
setPreferences(p) {
|
||
const previous = `${analysis}:${colorBlind}:${lang}:${mapView}:${playerColors.join()}:${JSON.stringify(appearance)}`;
|
||
appearance = p.bgs ?? {};
|
||
chatNotifications = p.chatNotifications !== false;
|
||
analysis = p.analysis === true;
|
||
colorBlind = p.colorBlind === true;
|
||
playerColors = Array.isArray(p.bgs?.playerColors)
|
||
? p.bgs.playerColors.map((c) =>
|
||
typeof c === "string" && /^#[a-f0-9]{6}$/i.test(c) ? c : undefined,
|
||
)
|
||
: [];
|
||
s = displayState(rawState);
|
||
if (
|
||
(p.mapView === "2d" || p.mapView === "3d") &&
|
||
p.mapView !== mapView &&
|
||
!threeUnavailable
|
||
)
|
||
setMapView(p.mapView);
|
||
syncMotion();
|
||
sound = p.sound === true;
|
||
moveSound.setEnabled(sound);
|
||
for (const [name, value] of Object.entries({
|
||
colorBlind,
|
||
sound,
|
||
})) {
|
||
const checkbox = dialog.querySelector(`[data-pref="${name}"]`);
|
||
if (checkbox && checkbox.checked !== value) checkbox.checked = value;
|
||
}
|
||
hostedLocale = typeof p.locale === "string";
|
||
if (hostedLocale || typeof p.language === "string") {
|
||
const nextLang = resolveLocale(p.locale ?? p.language);
|
||
if (lang !== nextLang) {
|
||
lang = nextLang;
|
||
t = translator(lang);
|
||
activity.setLanguage(lang);
|
||
}
|
||
}
|
||
if (
|
||
previous !==
|
||
`${analysis}:${colorBlind}:${lang}:${mapView}:${playerColors.join()}:${JSON.stringify(appearance)}`
|
||
)
|
||
render();
|
||
else {
|
||
updateUnread();
|
||
syncBoard3D();
|
||
}
|
||
},
|
||
destroy() {
|
||
events.abort();
|
||
mapZoom.destroy();
|
||
tradeTransition.destroy();
|
||
board3D?.destroy();
|
||
trayObserver.disconnect();
|
||
effects.destroy();
|
||
moveSound.destroy();
|
||
offChat?.();
|
||
activity.destroy();
|
||
root.remove();
|
||
},
|
||
};
|
||
}
|