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 ` `;
}
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 =
'
';
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
? ` `
: "";
};
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) =>
`${pictogramText(translateText(characterHelp[c]?.[0] ?? "", lang), lang, colorBlind)} `;
function btn(content, attr = "", className = "") {
return `${content} `;
}
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 ? ` ${coastArrow(m.cell, m.dike)} ` : ""}`;
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 `${btn(`${avatars[i] ? `
` : ""}
${colorBlind ? symbol(i) + " " : ""}${esc(p.name)} ${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") : ""}
${token("point", p.score)} ${token("coin", p.money)}${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)} ${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)} ${token("build", p.hutsLeft)}
${c ? `${charName(p.character)} ${p.used ? icon("check") : icon(c.action ?? "point")} ` : ""}${i === player ? `${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")}"`) : ""}
` : ""} `;
}
function dock() {
const planning = ["plan", "neutral"].includes(s.phase) && working().length;
return `${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]
? `${colorBlind ? symbol(i) : ""}${p.markers[a]} `
: "",
)
.join("");
return btn(
`${icon(a)} ${t(a)} ${stacks}${retrieveOnly ? `${icon("warning", "Retrieve without acting")} ` : ""}${s.neutral[a] ? `${s.neutral[a]} ` : ""}${countDraft ? `+${countDraft} ` : ""} `,
`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("")} `;
}
function tray() {
const moves = working();
if (s.finished)
return `${s.lost ? t("lost") : t("finished")} ${btn(`${icon("point")} ${t("ended")}`, "data-scores", "primary")}
`;
if (!moves.length)
return ` ${pending ? t("pending") : `${t("waiting")} ${esc(s.players[s.actor]?.name ?? "")} `}
`;
if (s.phase === "character")
return `${t("character")}
${moves
.filter((m) => m.type === "character")
.map((m) => {
const c = CHARACTERS[m.character];
return btn(
`
${charName(m.character)} ${charHelpHtml(m.character)}`,
`data-character-choice="${m.character}"`,
"character-choice",
);
})
.join("")}
`;
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 `${t(s.phase)} ${draft.length}/${count}
${Array.from({ length: count }, (_, i) => `${draft[i] ? icon(draft[i]) : icon("marker")} `).join("")}
${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") : ""}
`;
}
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 `${t("expand")} ${esc(translateText(REMAINING_TILES, lang))}: ${s.upcoming.length}
${t("help")} ${esc(t(EXTEND_WHO))}
${esc(t(EXTEND_HOW))}
${tileChoices.map((id) => btn(tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "choice-" + id }), `data-tile="${id}" aria-pressed="${tile === id}"`)).join("")}
${m ? moveButton(m, true) : ""}
`;
}
if (s.phase === "rest")
return `${t("restChoice")} ${moves
.filter((m) => m.type === "rest")
.map((m) => moveButton(m, true))
.join("")}
`;
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 `${selectedAction ? `${icon(action)} ${t(action)}` : t("actions")}
${discard ? `
${blockingHtml(s, player, action, lang, undefined, colorBlind)}
` : !selectedAction && moves.some((m) => m.type === "discard") ? `
${esc(translateText(RETRIEVE_CHOICE, lang))}
` : ""}${hasBonus && hasNormal ? `
${charName(own()?.character)}` : ""}
${pickText} ${opts.map((m) => moveButton(m, true)).join("")}${discard ? moveButton(discard) : ""}
${governor ? btn(`${icon("marker")} ↔`, `data-governor title="${t("governor")}"`) : ""}${selectedAction ? titled(t("cancel"), icon("close"), "data-cancel", "icon-button") : ""}
`;
}
function tradeShips() {
const help =
"First ship needing the good (1 → 3). Complete ship: +2 prosperity.";
return `${tradeTransition
.demands(s.demands)
.map(
(d, i) =>
`
${i + 1} ${d.goods
.map((g, j) => {
const goodHelp = exportGoodHelp(
g,
d.filled[j] ? "delivered" : "available",
);
return `${icon(g, goodHelp)}${d.filled[j] ? icon("check", goodHelp) : ""} `;
})
.join("")}${icon("buy", help)}
`,
)
.join("")}
`;
}
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 = `${t("connected")}
`;
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 = `
${dock()}
${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)} ${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)} ${s.waterCountdown !== null ? `${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)} ` : ""}${titled("Export goods", icon("buy"), `data-export-help aria-expanded="${exportHelpOpen}"`, "export-help-toggle icon-button")}
${tradeShips()}${exportReference(colorBlind)}
${btn("2D", `data-map-view="2d" aria-pressed="${mapView === "2d"}"`)}${btn("3D", `data-map-view="3d" aria-pressed="${mapView === "3d"}" ${threeUnavailable ? "disabled" : ""}`)} ${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")} ${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}
${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}${s.players.map(playerCard).join("")} `;
// Patch in place so cached SVG tile images and focused controls survive
// preference changes and incoming state updates.
patch(play, `${html}
`, 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 = `${icon("close")} ${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) =>
`${btn(route.exchanges.map((type) => esc(translateText(t(type), lang))).join(" + "), `data-free="${route.exchanges[0]}"`)}→ ${route.actions.map((a) => `${actionLabel(a)} `).join("")}
`,
)
.join("");
showDialog(
`${icon("warning", "Retrieve without acting")} ${esc(translateText("Retrieve without acting", lang))} — ${esc(translateText(t(move.action), lang))} ${now.length ? `${esc(translateText("Available now", lang))} ${now.join("")}
` : ""}${funded ? `${esc(translateText("After free exchanges", lang))} ${funded}${esc(translateText("Free exchanges are optional and do not use markers or end your turn.", lang))}
` : ""}${esc(translateText("Retrieve this stack without acting?", lang))}
${btn(t("cancel"), "data-close")}${btn(icon("warning", "Retrieve without acting") + " " + t("confirm"), `data-move="${s.legal.indexOf(move)}" data-confirmed-retrieval`, "retrieve-warning")}
`,
);
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
? `${why}
`
: "";
if (b?.type === "island")
showDialog(
`${t("island")} ${reason}${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}`)}
${Object.entries(
b.goods,
)
.map(([g, n]) => token(g, n))
.join("")}
`,
);
else if (why)
showDialog(`${icon(action)} ${t(action)} ${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(
`${t("next")} ${s.upcoming
.map(
(id) =>
`
${tilePreviewSvg(id, { t, colorBlind, language: lang })}
`,
)
.join("")}
`,
);
return;
}
if ("exportHelp" in d) {
exportHelpOpen = !exportHelpOpen;
render();
return;
}
if ("firstHelp" in d) {
showDialog(
`${t("first")} ${esc(translateText(FIRST_HELP, lang))}
`,
);
return;
}
if ("unavailable" in d) {
const blocked =
s.phase === "actions" &&
(s.actor === player ||
markerBlockers(s, player, d.action).length > 0);
showDialog(
`${icon(d.action)} ${t(d.action)} ${blocked ? blockingHtml(s, player, d.action, lang, undefined, colorBlind) : proseHtml(translateText(d.unavailable, lang), lang, colorBlind)}
`,
);
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(
`${charName(m.character)} ${charHelpHtml(m.character)}
${moveButton(m, true)}
`,
);
return;
}
if ("character" in d) {
showDialog(
`${charName(d.character)} ${charHelpHtml(d.character)}
${"Once per round."} `,
);
return;
}
if ("free" in d) {
showDialog(
`${t(d.free)} ${legal()
.filter((m) => m.type === d.free)
.map((m) => moveButton(m, true))
.join("")}
`,
);
return;
}
if ("governor" in d) {
showDialog(
`${t("governor")} ${working()
.filter((m) => m.type === "governor")
.map((m) => moveButton(m, true))
.join("")}
`,
);
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(
`${t("help")} ${t("colorBlind")}2D 3D ${t("sound")} ${options.onSetting && Number.isInteger(player) && !analysis ? ` ${esc(translateText("Auto-retrieve when forced", lang))} ` : ""}${
hostedLocale
? ""
: `${Object.entries(
languages,
)
.map(
([locale, name]) =>
`${name} `,
)
.join("")} `
}
${rulesHtml(lang, colorBlind)}
${t("credit")} Alain Epron · Quined Games Art: Konstantin Vohwinkel · Rafaël Theunis
${t("source")}
`,
);
return;
}
if ("scores" in d) {
showDialog(
`${t("ended")} ${[...s.players]
.map((p, i) => ({ ...p, i }))
.sort((a, b) => b.score - a.score)
.map(
(p) =>
`
${esc(p.name)} ${token("point", p.score)}${
p.final
? `${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(" · ")} `
: ""
}
`,
)
.join("")}
`,
);
}
},
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();
},
};
}