Build Vanuatu private beta viewer, tutorials and BGS integration

This commit is contained in:
coyotte508 2026-09-25 13:46:51 +02:00
commit 7b037fe6d7
25 changed files with 3786 additions and 25 deletions

View file

@ -6,7 +6,7 @@ This repository and the BGS listing remain **private**. Supplied artwork and gam
## Development
Node 24+, pnpm. `pnpm install`, `pnpm build`, `pnpm dev` (port 5238). `pnpm test` runs rules tests; `pnpm test:browser` checks the viewer.
Node 24+, pnpm. `pnpm install`, `pnpm build`, `pnpm dev` (port 5246). `pnpm test` runs rules tests; install the browser once with `pnpm exec playwright install chromium`; `pnpm test:browser` checks the viewer.
Supported scope: 2–5 players, all eleven characters, the official two-player variant, optional Rising Waters, replay and finished-game analysis, bots, BGS chat, player hover cards and board thumbnails.
@ -18,3 +18,11 @@ Supported scope: 2–5 players, all eleven characters, the official two-player v
- [BoardGameGeek](https://boardgamegeek.com/boardgame/193927/vanuatu-second-edition)
Component uncertainties and implementation validation are recorded in the beta report.
## Beta review
Read [the beta report](docs/BETA-REPORT.md) before public release: the supplied ocean values and one outer board location still need confirmation. Bots are suitable for practice and automated coverage, not a claim of strong competitive play.
Guided lessons are available locally at `/?lesson=planning`, `/?lesson=fishing` and `/?lesson=islands`. Add `?players=2&new`, `?water&new` or `?hotseat&new` for practice variants. Practice progress stays in this browser.
Release: `pnpm build && pnpm test && pnpm test:browser`, then `node scripts/publish-private.mjs`. The publisher reads the admin token from `~/.bgs`, keeps the version private and checks the unlisted flag. It refuses to overwrite a public version. `node test/simulations.mjs` runs the longer complete-game sweep.

67
docs/BETA-REPORT.md Normal file
View file

@ -0,0 +1,67 @@
# Vanuatu private beta — implementation and open questions
25 September 2026 · Second edition, Quined Games (2016)
## Available
- Private, unlisted [BGS game](https://boardgamers.space/boardgame/vanuatu), access granted to **coyotte508**.
- Private [Codeberg repository](https://codeberg.org/boardgamers/vanuatu).
- Local practice: `http://127.0.0.1:5246/` (start with `pnpm build && pnpm dev`).
- Three guided lessons: planning, fishing/trade, and island development.
The engine covers eight rounds, 2–5 players, all eleven characters, the official two-player rules, optional play without characters for 3–5 players, and Rising Waters. It automates setup, replenishment, income conversion, turn order, mandatory retrieval when no decision remains, floods and final scoring. Free treasure sales and the Beggar remain available out of turn.
The viewer uses a large interactive map, a compact action dock and player supplies below the board. It supports tap-based mobile play, legal destination highlights, character bonuses, resource pictograms, shared sound/color-blind preferences, English/French game text, BGS chat with translation and editing, journal, replay, finished-game analysis, player hover cards, fullscreen and board-thumbnail rendering. Tutorial text is currently English.
## Points requiring publisher confirmation
These are explicit beta assumptions, **not resolved official errata**. They should be checked before a public release; changing a tile value or board footprint may require starting fresh beta games.
| Question | Evidence | Implemented choice |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Fish and treasure quantities | The rulebook lists 14 fish tiles (8×1, 4×2, 2×3) and 10 treasure tiles (4×1, 4×2, 2×3). The supplied cut-tile faces instead total **16 fish markers and 8 treasure markers**. | Use the readable values on the supplied tile faces. Fish/treasure rewards follow the remaining count on the ocean tile; no artificial shortage of reward tiles. |
| Exact outer board outline | The supplied board has faint, irregular tile outlines. The rules establish 15 placed tiles plus the fixed island, but do not enumerate their coordinates. | A 16-location footprint traced from that board, rendered as regular hexagons. In particular, the far upper-right location (`3,0` in the source) remains provisional. Please compare against a physical final board. |
| Governor during Rising Waters | The Governor moves markers **instead of** performing an action. The flood rule counts performed actions; no explicit Governor exception was found. | Governor transfers and discarded stacks do **not** decrease the flood die. Normal actions do. |
The supplied demand art also contains repeated patterns: cards 1/10 have one of each good; cards 2/8 have two kava and one copra. Duplicates can be intentional; they are preserved, not “corrected” speculatively.
### Tile values currently used
The fixed starting island is additional to this table. Two tiles of each letter A–F are split between the two ordered stacks, following the rulebook.
| Tile | Source cut image | Fish | Treasure | Island capacity: huts / drawings / tourists | Goods |
| -------------- | ---------------- | ---: | -------: | ------------------------------------------- | ----------- |
| Starting fish | 1 | 2 | 0 | — | — |
| Starting wreck | 3 | 1 | 2 | — | — |
| Starting boats | 5 | 0 | 0 | — | — |
| A1 | 7 | — | — | 3 / 2 / 4 | kava, beef |
| A2 | 9 | — | — | 3 / 2 / 4 | kava, copra |
| B1 | 11 | 1 | 3 | — | — |
| B2 | 13 | 3 | 0 | — | — |
| C1 | 15 | 0 | 0 | — | — |
| C2 | 17 | 1 | 2 | — | — |
| D1 | 19 | — | — | 2 / 3 / 3 | 2 kava |
| D2 | 21 | — | — | 3 / 1 / 4 | kava, copra |
| E1 | 23 | 0 | 0 | — | — |
| E2 | 25 | 2 | 0 | — | — |
| F1 | 27 | 3 | 1 | — | — |
| F2 | 29 | 3 | 0 | — | — |
## Validation
- 22 focused engine/tutorial tests: majorities, prerequisites, optional powers, money conversion, two-player blocking, illegal-move immutability, hidden information, dropped players, deterministic replay, floods and complete tutorials.
- 80 full simulated games (14,653 moves in the final sweep), across 2/3/4/5 players with and without Rising Waters. Both purposeful bots and varied legal choices exercise all nine actions and the Governor. These check termination, resource invariants and deterministic reconstruction; they do not establish strategic bot strength or resolve component discrepancies.
- Browser checks at **1440 px** and **390 px**: all nine actions, planning, tile placement, final scores, no page-width overflow, color symbols, replay, analysis chat hiding, player hover, board thumbnails, chat scroll-to-bottom, translation controls and ↑ editing.
- The installed production engine completed an eight-round bot game and reconstructed its history. The uploaded viewer is checked through a protocol harness. A signed-out browser correctly cannot open the private game; a real multi-account online session remains a useful beta playtest.
## Sources
Rules take precedence over artwork where they specify the behavior. Supplied component faces are used for values not individually listed in the rules.
- [Publisher’s English rulebook](https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_UK_WEBversion-4.pdf), especially setup, actions, characters and Rising Waters.
- [Publisher’s French rulebook](https://quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_FR-WEBversion.pdf).
- [Official two-player rules](https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf).
- [BGG second-edition page](https://boardgamegeek.com/boardgame/193927/vanuatu-second-edition), including its listing of the publisher’s corrected English rulebook. BGG’s direct page fetch was blocked, so no unverified forum clarification has been treated as authoritative.
- [BGG discussion of fish sales and optional treasure sales](https://boardgamegeek.com/thread/1883649/fish-price-and-treasure), consistent with the English rulebook: the market decreases once per sale action; treasure liquidation is optional.
Artwork remains the property of its rights holders. The private repository and beta are not permission to redistribute the supplied materials.

View file

@ -445,7 +445,50 @@ function freeVariants(s, p) {
}
return out;
}
const planningCache = new WeakMap();
export function canPlan(s, p, target, markers = s.players[p].markers) {
return canPlanUncached(s, p, target, markers);
}
function cachedCanPlan(s, p, target, markers = s.players[p].markers) {
const cacheKey = `${p}:${target}:${ACTIONS.map((a) => (markers[a] > 0 ? 1 : 0)).join("")}`;
let cache = planningCache.get(s);
if (!cache) {
cache = new Map();
planningCache.set(s, cache);
}
if (cache.has(cacheKey)) return cache.get(cacheKey);
const result = canPlanUncached(s, p, target, markers);
cache.set(cacheKey, result);
return result;
}
function canPlanUncached(s, p, target, markers) {
const islands = Object.values(s.board).filter(
(t) => t.type === "island" && !t.submerged,
);
if (target === "fish" && !Object.values(s.board).some((t) => t.fish > 0))
return false;
if (
target === "explore" &&
!Object.values(s.board).some((t) => t.treasure > 0)
)
return false;
if (
target === "draw" &&
!islands.some((t) => t.drawings < TILES[t.id].drawings)
)
return false;
if (
target === "tourist" &&
(!s.tourists || !islands.some((t) => t.tourists < TILES[t.id].tourists))
)
return false;
if (
target === "buy" &&
!islands.some((t) => Object.values(t.goods).some((n) => n > 0))
)
return false;
if (target === "sell" && !s.players[p].fish.length && !markers.fish)
return false;
const actions = ACTIONS.filter(
(a) => markers[a] > 0 && a !== target && a !== "rest",
);
@ -541,16 +584,17 @@ export function availableMoves(s, p = s.actor) {
}));
break;
case "plan": {
planningCache.delete(s);
const count = s.planningPass === 2 ? 1 : 2;
for (const action of ACTIONS) {
if (!canPlan(s, p, action)) continue;
if (!cachedCanPlan(s, p, action)) continue;
if (count === 1) {
moves.push({ type: "plan", actions: [action] });
continue;
}
const markers = { ...a.markers, [action]: a.markers[action] + 1 };
for (const next of ACTIONS)
if (canPlan(s, p, next, markers))
if (cachedCanPlan(s, p, next, markers))
moves.push({ type: "plan", actions: [action, next] });
}
break;
@ -824,7 +868,7 @@ function execute(s, m, p) {
a.markers[m.from] = 0;
a.used = true;
a.governorAction = m.to;
actionDone(s, p);
actionDone(s, p, false);
return;
case "rest":
a.rest = m.token;
@ -854,7 +898,11 @@ function automate(s) {
const moves = availableMoves(s).filter(
(m) => !["beg", "treasure"].includes(m.type),
);
if (moves.length === 1 && moves[0].type === "discard") {
if (
moves.length === 1 &&
moves[0].type === "discard" &&
freeMoves(s, s.actor).length === 0
) {
execute(s, moves[0], s.actor);
continue;
}
@ -862,7 +910,7 @@ function automate(s) {
}
check(guard < 100, "Automatic turn limit");
}
export function move(data, input, p) {
function applyMove(data, input, p) {
check(!data.finished, "The game has ended");
check(
Number.isInteger(p) && p >= 0 && p < data.players.length,
@ -884,6 +932,17 @@ export function move(data, input, p) {
saveFrame(s);
return s;
}
function playDropped(data) {
let s = data,
n = 0;
while (!s.finished && s.players[s.actor]?.dropped && n++ < 1000)
s = applyMove(s, chooseAI(s, s.actor), s.actor);
check(n < 1000, "Dropped player automation limit");
return s;
}
export function move(data, input, p) {
return playDropped(applyMove(data, input, p));
}
export const ended = (s) => s.finished;
export const scores = (s) => s.players.map((p) => p.score);
export function rankings(s) {
@ -922,6 +981,9 @@ function publicFrame(frame, p, finished = false) {
if (q !== p && !finished) a.rest = a.rest ? "hidden" : null;
if (!(out.phase === "rest" && out.actor === p) && !finished)
delete out.restAvailable;
out.lastEvents = (out.lastEvents ?? []).map((e) =>
e.type === "rest" && e.p !== p && !finished ? { ...e, token: "hidden" } : e,
);
return out;
}
export function stripSecret(s, p) {
@ -958,7 +1020,7 @@ export function replay(s, { to = logLength(s) } = {}) {
);
const b = s._setup;
let r = init(b.count, b.expansions, b.options, b.seed);
for (const h of s._history.slice(0, to - 1)) r = move(r, h.move, h.p);
for (const h of s._history.slice(0, to - 1)) r = applyMove(r, h.move, h.p);
s.players.forEach((p, i) => {
r.players[i].name = p.name;
r.players[i].dropped = p.dropped;
@ -970,7 +1032,7 @@ export function createAnalysis(s, { to }) {
r.players.forEach((p) => (p.dropped = false));
return r;
}
export function moveAI(s, p) {
function chooseAI(s, p) {
check(p === s.actor);
const moves = availableMoves(s, p);
check(moves.length, "No legal bot move");
@ -995,11 +1057,6 @@ export function moveAI(s, p) {
s.neutral[action]),
0,
);
if (false)
return (
({ sail: 4, sell: 3, fish: 2, rest: 1 }[m.action] ?? 0) -
s.neutral[m.action]
);
if (m.type === "character")
return (
({
@ -1086,16 +1143,14 @@ export function moveAI(s, p) {
const ranked = moves
.map((m, i) => ({ m, i, value: value(m) }))
.sort((a, b) => b.value - a.value || a.i - b.i);
return move(s, ranked[0].m, p);
return ranked[0].m;
}
export function moveAI(s, p) {
return move(s, chooseAI(s, p), p);
}
export function dropPlayer(s, p) {
check(Number.isInteger(p) && !!s.players[p], "Unknown player");
const out = copy(s);
out.players[p].dropped = true;
let n = 0;
while (!out.finished && out.players[out.actor]?.dropped && n++ < 1000) {
const next = moveAI(out, out.actor);
Object.assign(out, next);
}
check(n < 1000, "Dropped player automation limit");
return out;
return playDropped(out);
}

View file

@ -11,7 +11,8 @@
"build": "node scripts/build.mjs",
"test": "node --test test/*.test.js",
"dev": "node scripts/dev.mjs",
"test:browser": "node test/browser.mjs"
"test:browser": "node test/browser.mjs",
"check": "pnpm build && pnpm test && pnpm test:browser"
},
"dependencies": {
"@boardgamers/protocol": "0.6.0",

View file

@ -2,7 +2,7 @@ import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { resolve, extname } from "node:path";
const root = resolve("dist");
const port = Number(process.env.PORT ?? 5238);
const port = Number(process.env.PORT ?? 5246);
createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://local");

View file

@ -18,7 +18,9 @@ for n in range(1,11):save('demand-'+str(n),root/'Demand'/f'Demand{n}.jpg',(400,2
for n in range(1,5):save('rest-'+str(n),root/'rest_tokens'/f'REST{n}.jpg',(220,220))
board=root/'Game Board/Game_Board_Vanuatu_RGB.jpg'
save('efate',board,(480,480),(3030,2450,4280,3700))
save('ocean',root/'archipelagos/archipelago03.jpg',(600,600),(150,150,1070,1070))
ocean=root/'archipelagos/archipelago03.jpg'
w,h=Image.open(ocean).size
save('ocean',ocean,(480,480),(int(w*.3),int(h*.3),int(w*.7),int(h*.7)))
save('sand',root/'Demand/BACKSIDE_Demand.jpg',(500,280))
save('cover',root/'Game Box/Vanuatu_box_FRONT_NEW_small.jpg',(1100,1100))
for i,action in enumerate(['buy','explore','sail','build','rest','tourist','fish','sell','draw']):

166
scripts/publish-private.mjs Normal file
View file

@ -0,0 +1,166 @@
import { chapterMetadata } from "../viewer/tutorials.js";
import { readFile, mkdir, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import assert from "node:assert/strict";
const token = (await readFile(`${homedir()}/.bgs`, "utf8")).trim();
const base = "https://admin.boardgamers.space/api/admin/gameinfo/vanuatu";
async function api(path, method = "GET", body, contentType) {
const response = await fetch(base + path, {
method,
headers: {
Authorization: `Bearer ${token}`,
...(body ? { "Content-Type": contentType ?? "application/json" } : {}),
},
body: body ? (contentType ? body : JSON.stringify(body)) : undefined,
});
if (!response.ok)
throw Error(
`${method} ${path}: ${response.status} ${await response.text()}`,
);
const text = await response.text();
return text ? JSON.parse(text) : null;
}
const versions = await api("/versions");
const existing = versions.some((v) => v.version === 1) ? await api("/1") : null;
if (existing?.public)
throw Error(
"Refusing to change a public release with the private-beta publisher.",
);
const defaults = {
public: false,
meta: { botsPublic: true },
label: "Vanuatu",
players: [2, 3, 4, 5],
unlisted: true,
description:
"Compete for prosperity in a growing Pacific archipelago. Plan actions, sail, trade and welcome tourists. Includes all eleven characters, the official two-player variant and Rising Waters.",
credits:
"Designed by **Alain Epron**. Artwork by **Konstantin Vohwinkel**; graphic design and rulebook by **Rafaël Theunis**.\n\n[Vanuatu — Quined Games, second edition (2016)](https://www.quined.nl/featured_item/vanuatu-2nd-edition/). Supplied artwork used with permission for this adaptation.\n\n[Source code (private beta)](https://codeberg.org/boardgamers/vanuatu).",
links: {
source: "https://codeberg.org/boardgamers/vanuatu",
publisher: "https://www.quined.nl/featured_item/vanuatu-2nd-edition/",
bgg: "https://boardgamegeek.com/boardgame/193927/vanuatu-second-edition",
},
rules:
"[Original rules (English PDF)](https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_UK_WEBversion-4.pdf) · [Règles originales (PDF français)](https://quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_FR-WEBversion.pdf) · [Official two-player rules](https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf)\n\n**Eight rounds to prosper.** Choose a character, then place five action markers in batches of 2, 2 and 1. Resolve one action at a time where you have the most markers; ties follow player order. Retrieve all your markers from that action. With no majority, retrieve a stack without acting.\n\nSail to reach fish and treasure, or trade and build beside islands. Every 10 vatus becomes 5 prosperity immediately. At the end, remaining money and treasure score points; every hut earns 2 prosperity per tourist on its island. Most prosperity wins.",
viewer: {
url: "",
topLevelVariable: "vanuatu",
fullScreen: true,
fullScreenMobile: true,
replayable: true,
chat: true,
thumbnail: true,
dependencies: { scripts: [], stylesheets: [] },
},
preferences: [
{
name: "colorBlind",
label: "Color-blind mode",
type: "checkbox",
default: false,
},
{ name: "sound", label: "Game sounds", type: "checkbox", default: false },
{
name: "language",
label: "Language",
type: "select",
default: "auto",
items: [
{ name: "auto", label: "Automatic" },
{ name: "en", label: "English" },
{ name: "fr", label: "Français" },
],
},
],
tutorial: { chapters: chapterMetadata },
options: [
{
name: "characters",
label: "Character powers",
type: "checkbox",
default: true,
},
],
expansions: [{ name: "rising-waters", label: "Rising Waters" }],
};
if (!existing) {
const { unlisted, ...initial } = defaults;
await api("/1", "PUT", initial);
}
await mkdir(".local/release", { recursive: true });
if (existing)
await writeFile(
".local/release/before.json",
JSON.stringify(existing, null, 2),
);
execFileSync("pnpm", ["pack", "--pack-destination", ".local/release"], {
stdio: "inherit",
});
const pkg = JSON.parse(await readFile("package.json", "utf8"));
const engine = await api(
"/1/engine",
"POST",
await readFile(`.local/release/boardgamers-vanuatu-${pkg.version}.tgz`),
"application/octet-stream",
);
const js = await readFile("dist/viewer.js"),
css = await readFile("dist/viewer.css");
const hash = createHash("sha256")
.update(js)
.update(css)
.digest("hex")
.slice(0, 16);
const viewer = await api(
`/1/viewer/file?filename=viewer.js&bundle=${hash}`,
"POST",
js,
"application/octet-stream",
);
const style = await api(
`/1/viewer/file?filename=viewer.css&bundle=${hash}`,
"POST",
css,
"application/octet-stream",
);
await api("/1", "PUT", {
...existing,
...defaults,
engine: { ...engine.engine, entryPoint: "dist/engine.js" },
viewer: {
...defaults.viewer,
url: viewer.url,
dependencies: { scripts: [], stylesheets: [style.url] },
},
});
await api("/meta", "PUT", { unlisted: true });
await api(
"/assets/cover?name=Vanuatu",
"PUT",
await readFile("viewer/assets/cover.webp"),
"image/webp",
);
const access = await api("/beta-users");
if (!access.some((u) => u.username === "coyotte508"))
await api("/beta-users", "POST", { usernameOrEmail: "coyotte508" });
const published = await api("/1"),
meta = await api("/meta");
assert.equal(published.public, false);
assert.equal(meta.unlisted, true);
assert.equal(published.engine.package.version, pkg.version);
assert.equal(published.viewer.chat, true);
await writeFile(
".local/release/published.json",
JSON.stringify(published, null, 2),
);
console.log(
JSON.stringify({
private: !published.public,
unlisted: meta.unlisted,
engine: published.engine.package.version,
viewer: published.viewer.url,
betaUsers: (await api("/beta-users")).map((u) => u.username),
}),
);

224
test/browser.mjs Normal file
View file

@ -0,0 +1,224 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { mkdir, readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { resolve, extname } from "node:path";
import * as E from "../engine/index.js";
await mkdir(".local/qa", { recursive: true });
const dist = resolve("dist");
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost");
const path = resolve(
dist,
"." + (url.pathname === "/" ? "/index.html" : url.pathname),
);
if (!path.startsWith(dist + "/")) throw Error("Invalid path");
const body = await readFile(path);
res.setHeader(
"Content-Type",
{ ".js": "text/javascript", ".css": "text/css", ".html": "text/html" }[
extname(path)
] ?? "application/octet-stream",
);
res.end(body);
} catch {
res.writeHead(404);
res.end();
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
server.unref();
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({
headless: true,
...(process.env.CHROME_PATH
? { executablePath: process.env.CHROME_PATH }
: {}),
});
const errors = [];
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(base + "/?new&hotseat");
await page.waitForSelector("[data-character-choice]");
await page.locator("[data-character-choice]").first().click();
assert.equal(await page.locator("dialog[open]").count(), 1);
await page.locator("dialog [data-move]").click();
assert.equal(await page.locator("dialog[open]").count(), 0);
for (let n = 0; n < 2; n++) {
await page.locator("[data-character-choice]").first().click();
await page.locator("dialog [data-move]").click();
}
await page.locator('[data-action="sail"]').click();
await page.locator('[data-action="fish"]').click();
await page.locator(".turn-tray [data-move]").click();
const after = await page.evaluate(() => window.vanuatuDemo.state);
assert.equal(after.players[after.first].markers.sail, 1);
assert.equal(after.players[after.first].markers.fish, 1);
// Every action can be selected and committed with pointer/touch controls, no dragging.
function actionState() {
const s = E.init(3, [], {}, "ui-actions");
s.actor = 0;
s.first = 0;
s.phase = "actions";
s.players.forEach((p, i) => {
p.markers = Object.fromEntries(E.ACTIONS.map((a) => [a, i === 0 ? 1 : 0]));
p.money = 9;
p.boat = "1,0";
});
s.board["1,0"] = E.tileState("startWreck");
s.board["0,1"] = E.tileState("startFish");
s.board["1,1"] = E.tileState("startBoat");
s.board["0,0"].huts = [0];
s.tourists = 2;
s.players[0].fish = [1, 2];
s.players[0].treasures = [1];
return s;
}
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 });
for (const action of E.ACTIONS) {
const s = actionState();
await page.evaluate((s) => window.vanuatuDemo.setState(s), s);
await page.locator(`[data-action="${action}"]`).click();
const targets = page.locator(".map-cell.legal");
if (await targets.count()) await targets.first().click();
const option = page.locator(".turn-tray [data-move]").first();
assert.ok(await option.count(), `No UI choice ${width}/${action}`);
await option.click();
if (action === "rest")
await page.locator(".turn-tray [data-move]").first().click();
assert.equal(
await page.locator(".feedback:not([hidden])").count(),
0,
`${action} feedback`,
);
assert.ok(
(await page.evaluate(() => window.vanuatuDemo.state._history.length)) > 0,
);
}
await page.evaluate((s) => window.vanuatuDemo.setState(s), actionState());
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth + 1,
),
"Page overflows horizontally",
);
await page.screenshot({
path: `.local/qa/actions-${width}.png`,
fullPage: true,
});
await page.locator("[data-help]").first().click();
await page.locator('[data-pref="colorBlind"]').check();
await page.locator("[data-close]").click();
assert.ok(await page.locator(".color-symbol").count());
}
// Extension placement and optional expansion remain usable.
let expansion = E.init(3, [], {}, "expand");
while (expansion.round < 2) expansion = E.moveAI(expansion, expansion.actor);
await page.evaluate((s) => window.vanuatuDemo.setState(s), expansion);
await page.locator(".map-cell.legal").first().click();
await page.locator(".turn-tray [data-move]").click();
// Ended games and spectator states must not reference a missing actor.
let final = E.init(3, [], {}, "finish");
while (!final.finished) final = E.moveAI(final, final.actor);
await page.evaluate((s) => window.vanuatuDemo.setState(s), final);
await page.locator("[data-scores]").click();
assert.equal(await page.locator(".final-scores>div").count(), 3);
await page.locator("[data-close]").click();
// Hosted protocol: replay, names, analysis chat visibility, hover anchors and board thumbnail.
await page.goto(base + "/");
await page.evaluate(() => {
document.body.innerHTML = '<div id="host"></div>';
});
await page.addStyleTag({ url: base + "/viewer.css" });
await page.addScriptTag({ url: base + "/viewer.js" });
await page.evaluate(() => {
window.emitter = window.vanuatu.launch("#host");
window.hostEvents = [];
for (const kind of [
"player:hovered",
"boardgame:clicked",
"replay:info",
"thumbnail:ready",
])
window.emitter.on(kind, (v) => window.hostEvents.push({ kind, v }));
});
await page.evaluate(
(s) => {
emitter.receive("player", { index: 0 });
emitter.receive("state", s);
emitter.receive("preferences", { analysis: true, colorBlind: true });
},
E.stripSecret(final, 0),
);
assert.equal(await page.locator('[data-activity="chat"]').count(), 0);
await page.evaluate(
(s) => {
emitter.receive("replay:start");
emitter.receive("replay:to", 1);
emitter.receive("gamelog", { start: 0, data: s });
},
E.logSlice(final, { player: 0, start: 0, end: 0 }),
);
assert.equal(await page.locator("[data-scores]").count(), 0);
await page.locator('[data-bgs-player="0"]').hover();
assert.ok(
await page.evaluate(() =>
hostEvents.some((e) => e.kind === "player:hovered"),
),
);
await page.evaluate(() => {
emitter.receive("replay:end");
emitter.receive("preferences", { analysis: false });
emitter.receive("chat:state", {
canSend: true,
canEdit: true,
translationTarget: "fr",
});
emitter.receive(
"chat:messages",
Array.from({ length: 80 }, (_, i) => ({
_id: i.toString(16).padStart(24, "0"),
type: "text",
author: "You",
playerIndex: 0,
createdAt: new Date().toISOString(),
editableUntil: new Date(Date.now() + 600000).toISOString(),
text: "Practice message " + i,
language: "en",
})),
);
});
await page.locator('[data-tab="chat"]').click();
const messageList = page.locator(".chat-messages");
await messageList.scrollIntoViewIfNeeded();
await page.waitForTimeout(250);
await messageList.evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
await page.screenshot({ path: ".local/qa/chat-mobile.png", fullPage: true });
assert.ok(
await messageList.evaluate(
(el) => Math.abs(el.scrollHeight - el.scrollTop - el.clientHeight) < 2,
),
);
await page.locator(".chat-composer input").press("ArrowUp");
assert.equal(
await page.locator(".chat-composer input").inputValue(),
"Practice message 79",
);
assert.ok(await page.locator(".chat-translate").count());
await page.screenshot({ path: ".local/qa/chat-mobile.png", fullPage: true });
await page.evaluate(() =>
emitter.receive("thumbnail:render", { width: 1000, height: 600 }),
);
await page.waitForTimeout(200);
assert.ok(await page.locator(".bgs-board-thumbnail svg").count());
await page.screenshot({ path: ".local/qa/thumbnail.png" });
assert.deepEqual(errors, []);
await browser.close();
await new Promise((resolve) => server.close(resolve));
console.log(
"Desktop, mobile, all nine actions, expansion, endgame, replay, hover cards and thumbnail checks passed.",
);

View file

@ -177,3 +177,71 @@ test("Rising Waters floods after its action countdown and dikes protect edges",
assert.equal(s.board["0,0"].water, 2);
assert.equal(s.waterTriggered, true);
});
test("rest choices stay secret in replay events as well as state", () => {
let s = actionState();
s.phase = "rest";
s.actor = 0;
s._restAvailable = ["first", "coin"];
s = E.move(s, { type: "rest", token: "first" }, 0);
const last = E.logSlice(s, { player: 1, start: E.logLength(s) - 1 })
.frames[0];
assert.equal(last.players[0].rest, "hidden");
assert.equal(last.lastEvents.find((e) => e.type === "rest").token, "hidden");
assert.equal(
E.stripSecret(s, 0).lastEvents.find((e) => e.type === "rest").token,
"first",
);
});
test("dropped players are automated on future turns and replay boundaries remain valid", () => {
let s = E.init(3, [], {}, "drop");
const dropped = (s.actor + 1) % 3;
s = E.dropPlayer(s, dropped);
for (let n = 0; n < 22 && !s.finished; n++) {
assert.notEqual(s.actor, dropped);
s = E.moveAI(s, s.actor);
}
assert.ok(s._history.some((h) => h.p === dropped));
for (let n = 1; n <= E.logLength(s); n++)
assert.deepEqual(
E.createAnalysis(s, { to: n }).board,
s._frames[n - 1].board,
);
});
test("batched planning accounts for the first new marker as a prerequisite", () => {
const s = actionState();
s.phase = "plan";
s.planningPass = 0;
s.players[0].markers = Object.fromEntries(E.ACTIONS.map((a) => [a, 0]));
s.board["0,0"].huts = [0];
s.players[0].fish = [];
assert.ok(
E.availableMoves(s).some(
(m) =>
m.type === "plan" && m.actions[0] === "fish" && m.actions[1] === "sell",
),
);
});
test("an optional treasure sale is not skipped by automatic marker retrieval", () => {
let s = actionState();
s.actor = 0;
s.players[0].markers = { ...s.players[0].markers, fish: 1 };
s.players[1].markers = Object.fromEntries(
E.ACTIONS.map((a) => [a, a === "sail" ? 1 : 0]),
);
s.players[1].money = 0;
s.players[1].treasures = [2];
s = E.move(s, act(s, 0, "fish"), 0);
assert.equal(s.actor, 1);
assert.ok(E.availableMoves(s, 1).some((m) => m.type === "treasure"));
s = E.move(s, { type: "treasure", values: [2] }, 1);
assert.ok(E.availableMoves(s, 1).some((m) => m.action === "sail"));
});
test("Governor marker movement does not perform an action or advance the flood die", () => {
let s = actionState();
s.players[0].character = "governor";
s.options.risingWaters = true;
s.waterCountdown = 1;
s = E.move(s, { type: "governor", from: "fish", to: "explore" }, 0);
assert.equal(s.waterCountdown, 1);
assert.equal(s.waterTriggered, false);
});

47
test/simulations.mjs Normal file
View file

@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import * as E from "../engine/index.js";
const counts = {};
let games = 0,
turns = 0;
for (let seed = 0; seed < 10; seed++)
for (const n of [2, 3, 4, 5])
for (const water of [false, true]) {
let s = E.init(n, water ? ["rising-waters"] : [], {}, `qa-${seed}`),
k = 0;
while (!s.finished && k++ < 600) {
const legal = E.availableMoves(s);
assert.ok(legal.length, `${seed}/${n}/${water}/${s.round}/${s.phase}`);
// Alternate purposeful bots with varied legal choices to exercise uncommon characters/actions.
if (seed % 3 === 0) {
const moves = legal.filter(
(m) => !["beg", "treasure"].includes(m.type),
);
const m = moves[(k * 73 + seed * 41) % moves.length];
counts[m.action ?? m.type] = (counts[m.action ?? m.type] ?? 0) + 1;
s = E.move(s, m, s.actor);
} else s = E.moveAI(s, s.actor);
assert.ok(
s.players.every(
(p) => p.money >= 0 && p.money < 10 && p.hutsLeft >= 0,
),
);
assert.ok(
Object.values(s.board).every(
(t) =>
t.fish >= 0 &&
t.treasure >= 0 &&
Object.values(t.goods).every((x) => x >= 0),
),
);
assert.ok(s.round <= 8);
turns++;
}
assert.ok(s.finished, `Unfinished ${seed}/${n}/${water}`);
assert.equal(E.currentPlayer(s), undefined);
const restored = E.replay(s);
assert.deepEqual(E.scores(restored), E.scores(s));
assert.deepEqual(restored.board, s.board);
games++;
if (games % 8 === 0) console.log(`${games} full games passed`);
}
console.log(JSON.stringify({ games, turns, coverage: counts }));

25
test/tutorial.test.js Normal file
View file

@ -0,0 +1,25 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createTutorial } from "@boardgamers/protocol/tutorial";
import { chapters } from "../viewer/tutorials.js";
import { availableMoves } from "../engine/index.js";
for (const [id, chapter] of Object.entries(chapters))
test(`tutorial ${id} is completable with real engine moves`, async () => {
const lesson = await createTutorial(chapter);
let count = 0;
while (!lesson.snapshot.completed && count++ < 20) {
const snap = lesson.snapshot;
if (snap.canContinue) {
await lesson.continue();
continue;
}
const step = chapter.steps[snap.step];
const moves = availableMoves(snap.state, 0).filter(
(m) => !step.validateMove?.(snap.state, m),
);
assert.ok(moves.length, `${id}/${snap.step}`);
assert.equal(await lesson.play(moves[0]), true);
}
assert.equal(lesson.snapshot.completed, true);
lesson.destroy();
});

173
viewer/activity.js Normal file
View file

@ -0,0 +1,173 @@
import { mountChat } from "@boardgamers/protocol/chat/dom";
import { icon, token, esc } from "./art.js";
import { translator } from "./labels.js";
import { CHARACTERS } from "../engine/catalog.js";
export function mountActivity(
target,
{ chat, openPlayer, onBack, language = "en" } = {},
) {
const root = document.createElement("section");
root.className = "activity";
root.innerHTML = `<header><div role="tablist"><button type="button" role="tab" data-tab="journal">${icon("journal")} <span>Journal</span></button><button type="button" role="tab" data-tab="chat" ${chat ? "" : "hidden"}>${icon("chat")} <span>Chat</span> <b class="unread" hidden></b></button></div><button type="button" class="text-button" data-back>↑ <span>Board</span></button></header><div class="journal-panel" role="tabpanel"><ol class="event-list" tabindex="0"></ol></div><div class="chat-panel" role="tabpanel" hidden></div>`;
const shortcut = document.createElement("button");
shortcut.className = "chat-shortcut";
shortcut.hidden = true;
shortcut.type = "button";
target.append(root, shortcut);
const list = root.querySelector("ol"),
journal = root.querySelector(".journal-panel"),
panel = root.querySelector(".chat-panel");
let mode = "journal",
analysis = false,
state,
lang = language,
t = translator(lang),
following = true,
key = "",
visible = false;
const view = chat
? mountChat(panel, {
chat,
openPlayer,
styles: true,
labels:
language === "fr"
? {
send: "Envoyer",
sending: "Envoi…",
empty: "Aucun message",
message: "Message",
edited: "modifié",
}
: undefined,
})
: null;
const observer = new IntersectionObserver(
(entries) => {
visible = entries[0]?.isIntersecting ?? false;
syncVisibility();
},
{ threshold: 0.15 },
);
observer.observe(panel);
function syncVisibility() {
chat?.setOpen(mode === "chat" && !analysis && visible);
}
function select(kind) {
mode = kind === "chat" && chat && !analysis ? "chat" : "journal";
journal.hidden = mode !== "journal";
panel.hidden = mode !== "chat";
for (const b of root.querySelectorAll("[data-tab]")) {
b.setAttribute("aria-selected", String(b.dataset.tab === mode));
b.tabIndex = b.dataset.tab === mode ? 0 : -1;
}
if (mode === "chat") view?.open();
else if (view) view.element.open = false;
syncVisibility();
}
function open(kind) {
select(kind);
root.scrollIntoView({ behavior: "smooth", block: "start" });
if (kind === "journal") list.focus({ preventScroll: true });
}
function eventHtml(e) {
const name = state?.players[e.p]?.name ?? "";
const actor = name
? `<strong style="color:${state.players[e.p].color}">${esc(name)}</strong>`
: "";
switch (e.type) {
case "action":
return `${actor} ${icon(e.action)}${e.good ? icon(e.good) : ""}${e.fish ? e.fish.map((n) => token("fish", n)).join("") : ""}${e.path ? ` ${e.path.length} ${icon("sail")}` : ""}${e.bonus ? ` <small>${esc(CHARACTERS[state.players[e.p]?.character]?.[lang === "fr" ? "fr" : "name"] ?? "")}</small>` : ""}`;
case "plan":
case "neutral":
return `${actor} ${e.actions.map((a) => icon(a)).join("")}${e.type === "neutral" ? ` <span class="neutral-key">●</span>` : ""}`;
case "character":
return `${actor} <span>${esc(CHARACTERS[e.character]?.[lang === "fr" ? "fr" : "name"] ?? e.character)}</span>`;
case "conversion":
return `${actor} ${token("coin", e.points * 2)} → ${token("point", e.points)}`;
case "treasure":
return `${actor} ${token(
"explore",
e.values.reduce((a, b) => a + b, 0),
)} → ${token(
"coin",
e.values.reduce((a, b) => a + b, 0),
)}`;
case "beg":
return `${actor} ${token("point", e.amount)} → ${token("coin", e.amount)}`;
case "discard":
return `${actor} ${icon("undo")} ${icon(e.action)}`;
case "governor":
return `${actor} ${icon(e.from)} → ${icon(e.to)}`;
case "rest":
return `${actor} ${icon("rest")}`;
case "restBonus":
return `${actor} ${e.token === "first" ? icon("first") : e.token === "both" ? token("coin", 1) + token("point", 1) : token(e.token, 1)}`;
case "round":
return `<b>${t("round")} ${e.round}/8</b>`;
case "place":
return `${actor} ${t("expand")}`;
case "flood":
return `${icon("water")} ${t("water")}`;
case "end":
return `<b>${t("finished")}</b>`;
default:
return "";
}
}
function refresh() {
if (!state) return;
const next = JSON.stringify(state.events ?? state.lastEvents ?? []) + lang;
if (next === key) return;
key = next;
list.innerHTML = (state.events ?? state.lastEvents ?? [])
.map((e) => ({ e, html: eventHtml(e) }))
.filter((x) => x.html)
.map(({ e, html }) => `<li><small>${e.round}</small>${html}</li>`)
.join("");
if (following)
requestAnimationFrame(() => (list.scrollTop = list.scrollHeight));
}
root.addEventListener("click", (e) => {
const b = e.target.closest("button");
if (!b) return;
if (b.dataset.tab) open(b.dataset.tab);
if ("back" in b.dataset) onBack?.();
});
shortcut.onclick = () => open("chat");
list.addEventListener("scroll", () => {
following = list.scrollHeight - list.scrollTop - list.clientHeight < 40;
});
select("journal");
return {
open,
update(s, isAnalysis) {
state = s;
analysis = isAnalysis;
root.querySelector('[data-tab="chat"]').hidden = !chat || analysis;
if (analysis && mode === "chat") select("journal");
refresh();
},
setUnread(n) {
const badge = root.querySelector(".unread");
badge.textContent = n;
badge.hidden = !n;
shortcut.hidden = !n || analysis;
shortcut.innerHTML = `${icon("chat")} ${n}`;
shortcut.setAttribute("aria-label", `${t("chat")}: ${n}`);
},
setLanguage(l) {
lang = l;
t = translator(l);
root.querySelector("[data-back] span").textContent = t("board");
root.querySelector('[data-tab="chat"] span').textContent = t("chat");
refresh();
},
destroy() {
observer.disconnect();
view?.destroy();
root.remove();
shortcut.remove();
},
};
}

59
viewer/art.js Normal file
View file

@ -0,0 +1,59 @@
export const esc = (x) =>
String(x ?? "").replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
const paths = {
sail: '<path d="M3 17h26l-5 8H9z" fill="currentColor"/><path d="M16 3v13H5z" fill="#f8e3a4" stroke="currentColor"/><path d="M18 4v12h9z" fill="#fcf5df" stroke="currentColor"/>',
fish: '<path d="M4 16C10 4 21 5 26 12l5-5v18l-5-5C18 28 10 27 4 16Z" fill="#df83a4" stroke="#a6426a"/><circle cx="10" cy="14" r="1.5" fill="#713847"/>',
sell: '<path d="M3 10h26l-2 17H5z" fill="#d3a163" stroke="#754627"/><path d="M8 5h16l4 6H4z" fill="#f4bc65"/><path d="M8 16h16M8 21h16" stroke="#805938"/>',
explore:
'<path d="M6 4h20l5 12-5 12H6L1 16z" fill="#eab343" stroke="#8d5a1d"/><path d="M9 12h14v11H9zM9 12a7 7 0 0 1 14 0" fill="#b57132" stroke="#754a25"/><path d="M16 12v8" stroke="#ffe9a3" stroke-width="3"/>',
build:
'<path d="M4 15 16 4l12 11v14H5z" fill="currentColor" stroke="#684b2d"/><path d="m1 15 15-13 15 13" fill="none" stroke="#876031" stroke-width="3"/><path d="M13 20h7v9h-7z" fill="#f8e7ba"/>',
draw: '<circle cx="16" cy="16" r="14" fill="#ead293"/><path d="M8 13q7-12 15 0t-15 0m0 6q7-12 15 0t-15 0M11 5v22m10-22v22" fill="none" stroke="#91663d" stroke-width="1.5"/>',
tourist:
'<circle cx="16" cy="7" r="5" fill="#fff4d4" stroke="#977c57"/><path d="M12 12h8l5 16H7z" fill="#fff4d4" stroke="#977c57"/>',
rest: '<path d="M2 13q14-22 28 0H2z" fill="#e5983b" stroke="#935b26"/><path d="M16 13v17" stroke="#795431" stroke-width="2"/><path d="m4 25 20-7 4 4-22 8z" fill="#eeebcf" stroke="#82764e"/>',
coin: '<path d="M4 7q12-5 24 0v18q-12 5-24 0z" fill="#e1c48c" stroke="#826749"/><path d="M5 8q11 5 22 0M6 25l19-16" stroke="#fff0ce"/><text x="16" y="23" text-anchor="middle" font-size="17" font-weight="bold" fill="#725939">V</text>',
point:
'<path d="M3 9Q16 0 29 9L20 29h-8z" fill="#ecd7b0" stroke="#9d7950"/><path d="m7 10 7 15m2-17v17m9-15-7 15" stroke="#b69a72"/>',
first:
'<path d="M9 30V3m0 1h18l-5 7 5 7H9" fill="#e88743" stroke="#5a5b52" stroke-width="2.5"/>',
water:
'<path d="M16 2S5 14 5 21a11 11 0 0 0 22 0C27 14 16 2 16 2Z" fill="#419ed2" stroke="#236b9b"/><path d="M10 20q0 7 6 7" fill="none" stroke="#bfeafa" stroke-width="2"/>',
dike: '<path d="m2 23 23-17 5 5L7 28z" fill="#987450" stroke="#674527"/>',
kava: '<path d="m4 7 18-3 7 4-18 4z" fill="#b9e26a"/><path d="M4 7v20l7 3V12z" fill="#77ae35"/><path d="m11 12 18-4v19l-18 3z" fill="#90ce40" stroke="#649b2a"/>',
copra:
'<path d="m4 7 18-3 7 4-18 4z" fill="#fffbed"/><path d="M4 7v20l7 3V12z" fill="#cecbba"/><path d="m11 12 18-4v19l-18 3z" fill="#f7f4df" stroke="#b7b6a2"/>',
beef: '<path d="m4 7 18-3 7 4-18 4z" fill="#f59274"/><path d="M4 7v20l7 3V12z" fill="#b94b40"/><path d="m11 12 18-4v19l-18 3z" fill="#e76754" stroke="#b84437"/>',
buy: '<path d="M3 23h27l-5 6H8zM16 2v20M17 5l12 15H17z" fill="#986541" stroke="#725234"/><path d="M5 13h9v9H5z" fill="#90ce40"/>',
marker:
'<ellipse cx="16" cy="19" rx="12" ry="8" fill="currentColor" stroke="#ffffff" stroke-width="2"/><ellipse cx="16" cy="14" rx="12" ry="8" fill="currentColor" stroke="#ffffff" stroke-width="2"/>',
chat: '<path d="M4 5h24v18H13l-7 6v-6H4zM10 12h12M10 17h8" fill="none" stroke="currentColor" stroke-width="2"/>',
journal:
'<path d="M6 3h20v26H6zM11 9h10M11 15h10M11 21h7" fill="none" stroke="currentColor" stroke-width="2"/>',
help: '<circle cx="16" cy="16" r="13" fill="none" stroke="currentColor" stroke-width="2"/><path d="M11 10c0-6 13-6 12 1 0 4-7 4-7 8M16 23v2" fill="none" stroke="currentColor" stroke-width="2.5"/>',
fullscreen:
'<path d="M3 12V3h9m8 0h9v9M3 20v9h9m8 0h9v-9" fill="none" stroke="currentColor" stroke-width="2.5"/>',
close:
'<path d="m8 8 16 16M8 24 24 8" fill="none" stroke="currentColor" stroke-width="2.5"/>',
undo: '<path d="M9 5 2 12l7 7M3 12h15a8 8 0 0 1 0 16" fill="none" stroke="currentColor" stroke-width="2.5"/>',
check:
'<path d="m5 16 8 8L28 7" fill="none" stroke="currentColor" stroke-width="3"/>',
eye: '<path d="M2 16Q16-2 30 16 16 34 2 16z" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="16" cy="16" r="5" fill="currentColor"/>',
zoom: '<circle cx="13" cy="13" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="m20 20 9 9M8 13h10m-5-5v10" stroke="currentColor" stroke-width="2"/>',
sound:
'<path d="M3 12h7l8-7v22l-8-7H3zM23 10q8 6 0 12" fill="none" stroke="currentColor" stroke-width="2"/>',
};
export function icon(name, label = "") {
return `<svg class="icon icon-${esc(name)}" viewBox="0 0 32 32" ${label ? `role="img" aria-label="${esc(label)}"` : 'aria-hidden="true"'}>${paths[name] ?? paths.point}</svg>`;
}
export function svgIcon(name, x, y, size = 26, color = "currentColor") {
return `<svg x="${x}" y="${y}" width="${size}" height="${size}" viewBox="0 0 32 32" style="color:${color}" aria-hidden="true">${paths[name] ?? paths.point}</svg>`;
}
export const token = (name, n) =>
`<span class="token" role="img" aria-label="${esc(name)}: ${esc(n)}">${icon(name)}<b>${esc(n)}</b></span>`;

View file

@ -56,4 +56,63 @@ import action_tourist from "./assets/action-tourist.webp";
import action_fish from "./assets/action-fish.webp";
import action_sell from "./assets/action-sell.webp";
import action_draw from "./assets/action-draw.webp";
export const assets={"tile-1":tile_1,"tile-3":tile_3,"tile-5":tile_5,"tile-7":tile_7,"tile-9":tile_9,"tile-11":tile_11,"tile-13":tile_13,"tile-15":tile_15,"tile-17":tile_17,"tile-19":tile_19,"tile-21":tile_21,"tile-23":tile_23,"tile-25":tile_25,"tile-27":tile_27,"tile-29":tile_29,"tile-31":tile_31,"tile-33":tile_33,"tile-35":tile_35,"tile-37":tile_37,"tile-39":tile_39,"character-diver":character_diver,"character-preacher":character_preacher,"character-drawer":character_drawer,"character-purchaser":character_purchaser,"character-fisher":character_fisher,"character-merchant":character_merchant,"character-governess":character_governess,"character-guide":character_guide,"character-worker":character_worker,"character-baggar":character_baggar,"character-navigator":character_navigator,"demand-1":demand_1,"demand-2":demand_2,"demand-3":demand_3,"demand-4":demand_4,"demand-5":demand_5,"demand-6":demand_6,"demand-7":demand_7,"demand-8":demand_8,"demand-9":demand_9,"demand-10":demand_10,"rest-1":rest_1,"rest-2":rest_2,"rest-3":rest_3,"rest-4":rest_4,"efate":efate,"ocean":ocean,"sand":sand,"cover":cover,"action-buy":action_buy,"action-explore":action_explore,"action-sail":action_sail,"action-build":action_build,"action-rest":action_rest,"action-tourist":action_tourist,"action-fish":action_fish,"action-sell":action_sell,"action-draw":action_draw};
export const assets = {
"tile-1": tile_1,
"tile-3": tile_3,
"tile-5": tile_5,
"tile-7": tile_7,
"tile-9": tile_9,
"tile-11": tile_11,
"tile-13": tile_13,
"tile-15": tile_15,
"tile-17": tile_17,
"tile-19": tile_19,
"tile-21": tile_21,
"tile-23": tile_23,
"tile-25": tile_25,
"tile-27": tile_27,
"tile-29": tile_29,
"tile-31": tile_31,
"tile-33": tile_33,
"tile-35": tile_35,
"tile-37": tile_37,
"tile-39": tile_39,
"character-diver": character_diver,
"character-preacher": character_preacher,
"character-drawer": character_drawer,
"character-purchaser": character_purchaser,
"character-fisher": character_fisher,
"character-merchant": character_merchant,
"character-governess": character_governess,
"character-guide": character_guide,
"character-worker": character_worker,
"character-baggar": character_baggar,
"character-navigator": character_navigator,
"demand-1": demand_1,
"demand-2": demand_2,
"demand-3": demand_3,
"demand-4": demand_4,
"demand-5": demand_5,
"demand-6": demand_6,
"demand-7": demand_7,
"demand-8": demand_8,
"demand-9": demand_9,
"demand-10": demand_10,
"rest-1": rest_1,
"rest-2": rest_2,
"rest-3": rest_3,
"rest-4": rest_4,
efate: efate,
ocean: ocean,
sand: sand,
cover: cover,
"action-buy": action_buy,
"action-explore": action_explore,
"action-sail": action_sail,
"action-build": action_build,
"action-rest": action_rest,
"action-tourist": action_tourist,
"action-fish": action_fish,
"action-sell": action_sell,
"action-draw": action_draw,
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Before After
Before After

99
viewer/board.js Normal file
View file

@ -0,0 +1,99 @@
import { CELLS, TILES, COLORS, DIRECTIONS } from "../engine/catalog.js";
import { assets } from "./assets.js";
import { esc, svgIcon } from "./art.js";
export const center = (id) => {
const [q, r] = id.split(",").map(Number);
return { x: 355 + q * 162 - r * 81, y: 150 + r * 140.3 };
};
function hex(x, y, r = 94) {
return Array.from({ length: 6 }, (_, i) => {
const a = ((60 * i - 30) * Math.PI) / 180;
return `${x + Math.cos(a) * r},${y + Math.sin(a) * r}`;
}).join(" ");
}
const symbols = ["●", "◆", "▲", "■", "✦"];
export function boardSvg(
s,
{ selected, targets = [], hoverTile, player, colorBlind = false, t } = {},
) {
const targetSet = new Set(targets);
const all = CELLS.map((c) => ({ ...c, ...center(c.id) }));
const visible = all.filter((c) => s.board[c.id] || targetSet.has(c.id));
const x0 = Math.min(...visible.map((c) => c.x)) - 120,
x1 = Math.max(...visible.map((c) => c.x)) + 120,
y0 = Math.min(...visible.map((c) => c.y)) - 120,
y1 = Math.max(...visible.map((c) => c.y)) + 120;
const defs = all
.map(
(c) =>
`<clipPath id="cell-${c.q + 2}-${c.r}"><polygon points="${hex(c.x, c.y)}"/></clipPath>`,
)
.join("");
let svg = `<svg class="archipelago" viewBox="${x0} ${y0} ${x1 - x0} ${y1 - y0}" role="group" aria-label="Vanuatu"><defs>${defs}<filter id="boat-shadow"><feDropShadow dx="0" dy="2" stdDeviation="2" flood-opacity=".3"/></filter></defs>`;
for (const c of all) {
const tile = s.board[c.id],
legal = targetSet.has(c.id),
spec = tile ? TILES[tile.id] : null;
svg += `<g class="map-cell ${legal ? "legal" : ""} ${selected === c.id ? "selected" : ""}" data-cell="${c.id}" ${legal ? `role="button" tabindex="0" aria-label="${esc(t(tile?.type === "island" ? "island" : "sea"))} ${c.id}"` : ""}>`;
svg += `<polygon class="cell-surface" points="${hex(c.x, c.y)}"/>`;
if (tile) {
svg += `<image href="${assets[spec.art]}" x="${c.x - 111}" y="${c.y - 111}" width="222" height="222" clip-path="url(#cell-${c.q + 2}-${c.r})"/>`;
if (tile.submerged) {
svg += `<polygon points="${hex(c.x, c.y)}" fill="#1c708ca6"/>${svgIcon("water", c.x - 25, c.y - 25, 50)}`;
} else if (tile.type === "sea") {
const res = [
...(spec.fish ? [["fish", tile.fish]] : []),
...(spec.treasure ? [["explore", tile.treasure]] : []),
];
if (res.length)
svg += `<rect x="${c.x - 16}" y="${c.y - 85}" width="92" height="40" rx="18" fill="#edf5ddec"/>`;
for (const [i, [kind, n]] of res.entries()) {
const x = c.x + 30 - (res.length * 45) / 2 + i * 45;
svg += `<rect x="${x - 6}" y="${c.y - 80}" width="44" height="29" rx="14" fill="#fff9dfeb"/>${svgIcon(kind, x - 4, c.y - 80, 27)}<text x="${x + 26}" y="${c.y - 60}" class="resource-n">${n}</text>`;
}
} else {
const goods = Object.entries(tile.goods).filter(([, n]) => n > 0);
let j = 0;
for (const [good, n] of goods)
for (let k = 0; k < n; k++, j++)
svg += svgIcon(good, c.x - 45 + j * 28, c.y + 48, 29);
const huts = tile.huts;
for (let i = 0; i < spec.huts; i++) {
const x = c.x - 40 + i * 32,
y = c.y - 29;
svg +=
huts[i] !== undefined
? svgIcon("build", x, y, 30, COLORS[huts[i]])
: `<rect x="${x + 3}" y="${y + 5}" width="24" height="23" rx="4" fill="#ffffff77" stroke="#786344" stroke-dasharray="3 2"/>`;
if (colorBlind && huts[i] !== undefined)
svg += `<text x="${x + 16}" y="${y + 26}" class="color-symbol">${symbols[huts[i]]}</text>`;
}
svg += `<rect x="${c.x - 44}" y="${c.y + 10}" width="88" height="28" rx="14" fill="#fff9dfeb"/>${svgIcon("tourist", c.x - 42, c.y + 11, 24)}<text x="${c.x - 17}" y="${c.y + 30}" class="resource-n">${tile.tourists}/${spec.tourists}</text>${svgIcon("draw", c.x + 7, c.y + 13, 22)}<text x="${c.x + 32}" y="${c.y + 30}" class="resource-n">${tile.drawings}</text>`;
if (tile.water)
svg += `${svgIcon("water", c.x - 74, c.y - 20, 25)}<text x="${c.x - 59}" y="${c.y + 20}" class="resource-n">${tile.water}</text>`;
for (const edge of tile.dikes) {
const o = center(edge);
const dx = o.x - c.x,
dy = o.y - c.y;
const mx = c.x + dx * 0.48,
my = c.y + dy * 0.48,
l = Math.hypot(dx, dy);
svg += `<line x1="${mx - (dy / l) * 22}" y1="${my + (dx / l) * 22}" x2="${mx + (dy / l) * 22}" y2="${my - (dx / l) * 22}" stroke="#654429" stroke-width="9" stroke-linecap="round"/><line x1="${mx - (dy / l) * 22}" y1="${my + (dx / l) * 22}" x2="${mx + (dy / l) * 22}" y2="${my - (dx / l) * 22}" stroke="#d1aa67" stroke-width="5" stroke-linecap="round"/>`;
}
}
} else if (hoverTile && legal)
svg += `<image class="tile-ghost" href="${assets[TILES[hoverTile].art]}" x="${c.x - 103}" y="${c.y - 103}" width="206" height="206" clip-path="url(#cell-${c.q + 2}-${c.r})"/>`;
if (!tile)
svg += `<text x="${c.x}" y="${c.y + 7}" class="empty-label">${legal ? "+" : "·"}</text>`;
svg += `<polygon class="cell-ring" points="${hex(c.x, c.y, 92)}"/></g>`;
const boats = s.players
.map((p, i) => ({ p, i }))
.filter(({ p }) => p.boat === c.id);
for (const [i, { p, i: pi }] of boats.entries()) {
const x = c.x + (i - (boats.length - 1) / 2) * 37,
y = c.y + (tile?.type === "sea" ? 11 : 0);
svg += `<g class="boat ${pi === player ? "own" : ""}" transform="translate(${x - 24} ${y - 24})" style="color:${p.color}" filter="url(#boat-shadow)">${svgIcon("sail", 0, 0, 48, p.color)}${colorBlind ? `<text x="25" y="40" class="color-symbol">${symbols[pi]}</text>` : ""}<title>${esc(p.name)}</title></g>`;
}
}
return svg + "</svg>";
}

131
viewer/host-presentation.js Normal file
View file

@ -0,0 +1,131 @@
function installPlayerCards(root, commands) {
let active = null;
function show(event) {
const name =
event.target instanceof Element
? event.target.closest("[data-bgs-player]")
: null;
if (!name || !root.contains(name) || name === active) return;
const index = Number(name.getAttribute("data-bgs-player"));
if (!Number.isInteger(index) || index < 0) return;
active = name;
commands.hoverPlayer(index, name.getBoundingClientRect());
}
function hide(event) {
if (!active) return;
const related = event.relatedTarget;
if (related instanceof Node && active.contains(related)) return;
active = null;
commands.leavePlayer();
}
root.addEventListener("mouseover", show);
root.addEventListener("focusin", show);
root.addEventListener("mouseout", hide);
root.addEventListener("focusout", hide);
return () => {
root.removeEventListener("mouseover", show);
root.removeEventListener("focusin", show);
root.removeEventListener("mouseout", hide);
root.removeEventListener("focusout", hide);
if (active) commands.leavePlayer();
};
}
function createBoardThumbnail(root) {
let preview;
function destroy() {
preview?.remove();
preview = void 0;
}
async function render(source, size, background, omit) {
destroy();
if (!source?.isConnected || !root.contains(source)) return null;
await document.fonts.ready;
preview = document.createElement("div");
preview.className = "bgs-board-thumbnail";
preview.setAttribute("aria-hidden", "true");
preview.style.cssText = `position:fixed;inset:0 auto auto 0;width:${size.width}px;height:${size.height}px;z-index:2147483647;overflow:hidden;pointer-events:none;background:${background};`;
const freeze = document.createElement("style");
freeze.textContent =
".bgs-board-thumbnail *{animation:none!important;transition:none!important;caret-color:transparent!important}";
preview.append(freeze);
let content;
if (source instanceof SVGElement) {
const svg =
source instanceof SVGSVGElement ? source : source.ownerSVGElement;
if (!svg) return null;
content = svg.cloneNode(false);
content.removeAttribute("id");
const box =
source instanceof SVGSVGElement
? source.viewBox.baseVal
: source.getBBox();
if (!box.width || !box.height) return null;
const padding =
source === svg ? 0 : Math.max(box.width, box.height) * 0.02;
content.setAttribute(
"viewBox",
`${box.x - padding} ${box.y - padding} ${box.width + padding * 2} ${box.height + padding * 2}`,
);
if (source === svg) {
for (const child of Array.from(source.childNodes))
content.append(child.cloneNode(true));
} else {
for (const defs of Array.from(svg.querySelectorAll("defs")))
content.append(defs.cloneNode(true));
const copy = source.cloneNode(true);
copy.removeAttribute("transform");
content.append(copy);
}
content.setAttribute("preserveAspectRatio", "xMidYMid meet");
content.style.cssText =
"display:block;position:static;width:100%;height:100%;max-width:none;max-height:none;min-width:0;margin:0;transform:none";
} else {
content = source.cloneNode(true);
content.style.cssText = `display:flex;flex-direction:column;gap:14px;position:relative;width:${source.getBoundingClientRect().width}px;height:${source.getBoundingClientRect().height}px;max-width:none;margin:0;transform-origin:top left;`;
}
if (omit)
for (const element of Array.from(content.querySelectorAll(omit)))
element.remove();
let parent = preview;
const ancestors = [];
for (
let ancestor = source.parentElement;
ancestor && ancestor !== document.body;
ancestor = ancestor.parentElement
) {
if (!(ancestor instanceof SVGElement)) {
ancestors.unshift(ancestor);
}
}
for (const ancestor of ancestors) {
const context = ancestor.cloneNode(false);
context.removeAttribute("id");
context.style.cssText =
"display:contents!important;transform:none!important;filter:none!important;contain:none!important";
parent.append(context);
parent = context;
}
parent.append(content);
document.body.append(preview);
if (!(content instanceof SVGSVGElement)) {
const box = content.getBoundingClientRect();
const scale = Math.min(
1,
size.width / box.width,
size.height / box.height,
);
content.style.transform = `translate(${(size.width - box.width * scale) / 2}px, ${(size.height - box.height * scale) / 2}px) scale(${scale})`;
}
await Promise.all(
Array.from(preview.querySelectorAll("img")).map((img) =>
img.decode().catch(() => {}),
),
);
await new Promise((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
return preview;
}
return { render, destroy };
}
export { createBoardThumbnail, installPlayerCards };

123
viewer/index.js Normal file
View file

@ -0,0 +1,123 @@
import { mountLesson } from "./tutorial-mount.js";
import "./style.css";
import { registerViewer } from "@boardgamers/protocol/viewer";
import { ChatController } from "@boardgamers/protocol/chat";
import { mountGame } from "./ui.js";
import {
createBoardThumbnail,
installPlayerCards,
} from "./host-presentation.js";
registerViewer(
"vanuatu",
(ctx) => {
const chat = new ChatController();
let live,
replaying = false,
position = 1,
pending,
timeout;
const ui = mountGame(ctx.target, {
chat,
onOpenPlayer: ctx.openPlayer,
onOpenBoardgame: ctx.openBoardgame,
onPreference: ctx.updatePreference,
onMove: (m) =>
new Promise((resolve, reject) => {
pending = { resolve, reject };
timeout = setTimeout(() => {
pending = undefined;
reject(
Error(
"Waiting for the server. Please refresh if your move has not appeared.",
),
);
}, 15000);
ctx.move(m);
}),
});
const thumbnail = createBoardThumbnail(ctx.target),
removeCards = installPlayerCards(ctx.target, ctx);
function info() {
if (live)
ctx.setReplayInfo({
start: 1,
current: position,
end: live.historyLength,
});
}
function seek(index) {
if (!live) return;
position = Math.max(1, Math.min(live.historyLength, index));
ctx.fetchLog({ start: position - 1, end: position - 1 });
info();
}
return {
chat,
onState(state) {
live = state;
if (!replaying) {
position = state.historyLength;
ui.render(state);
ui.setEnabled(true);
}
info();
if (pending) {
clearTimeout(timeout);
pending.resolve();
pending = undefined;
}
},
onPlayer(p) {
ui.setPlayer(p.index);
},
onPreferences: (p) => ui.setPreferences(p),
onAvatars() {},
onError(e) {
clearTimeout(timeout);
pending?.reject(e);
pending = undefined;
},
onLog(log) {
if (!replaying) return;
const data = log.data;
if (data?.frames?.length && log.start === position - 1) {
ui.render({ ...data.frames[0], legal: [], historyLength: position });
ui.setEnabled(false);
}
},
onReplayStart() {
replaying = true;
ui.setEnabled(false);
seek(live?.historyLength ?? 1);
},
onReplayTo(index) {
replaying = true;
seek(index);
},
onReplayEnd() {
replaying = false;
ui.setEnabled(true);
if (live) {
position = live.historyLength;
ui.render(live);
info();
}
ctx.fetchState();
},
onThumbnail: (size) =>
thumbnail.render(
ctx.target.querySelector(".archipelago"),
size,
"#8bcbd4",
),
destroy() {
clearTimeout(timeout);
pending?.resolve();
removeCards();
thumbnail.destroy();
ui.destroy();
},
};
},
{ tutorial: mountLesson },
);

142
viewer/labels.js Normal file
View file

@ -0,0 +1,142 @@
const entries = {
sail: ["Sail", "Naviguer"],
fish: ["Fish", "Pêcher"],
sell: ["Sell fish", "Vendre"],
explore: ["Explore", "Explorer"],
build: ["Build", "Construire"],
buy: ["Export", "Exporter"],
draw: ["Draw", "Dessiner"],
tourist: ["Tourists", "Touristes"],
rest: ["Rest", "Se reposer"],
round: ["Round", "Tour"],
character: ["Choose a character", "Choisir un personnage"],
plan: ["Plan your actions", "Programmer les actions"],
actions: ["Choose an action", "Choisir une action"],
expand: ["Extend the archipelago", "Agrandir l’archipel"],
neutral: ["Place the neutral markers", "Placer les pions neutres"],
ended: ["Final scores", "Scores finaux"],
confirm: ["Confirm", "Confirmer"],
choose: ["Choose", "Choisir"],
cancel: ["Cancel", "Annuler"],
undo: ["Undo", "Annuler"],
waiting: ["Waiting for", "Au tour de"],
you: ["You", "Vous"],
spectator: ["Spectator", "Spectateur"],
journal: ["Journal", "Journal"],
chat: ["Chat", "Discussion"],
help: ["Rules & help", "Règles et aide"],
first: ["First player", "Premier joueur"],
both: ["Vatu + prosperity", "Vatu + prospérité"],
point: ["Prosperity", "Prospérité"],
coin: ["Vatu", "Vatu"],
kava: ["Kava", "Kava"],
copra: ["Copra", "Coprah"],
beef: ["Beef", "Bœuf"],
water: ["Rising Waters", "La Montée des eaux"],
ability: ["Use character", "Utiliser le personnage"],
treasure: ["Sell treasures", "Vendre des trésors"],
beg: ["Exchange prosperity", "Échanger de la prospérité"],
governor: ["Move markers", "Déplacer les pions"],
discard: ["Retrieve markers", "Reprendre les pions"],
restChoice: ["Choose a rest token", "Choisir un jeton Repos"],
bonus: ["Character bonus", "Bonus du personnage"],
cost: ["Cost", "Coût"],
income: ["Income", "Revenus"],
gain: ["Gain", "Gain"],
island: ["Island", "Île"],
sea: ["Ocean", "Océan"],
hut: ["Hut", "Cabane"],
dike: ["Dike", "Digue"],
market: ["Fish price", "Prix du poisson"],
demand: ["Foreign trade", "Commerce extérieur"],
next: ["Next islands", "Prochaines tuiles"],
stock: ["Available", "Disponible"],
board: ["Back to board", "Retour au plateau"],
full: ["Full screen", "Plein écran"],
fit: ["Fit board", "Ajuster le plateau"],
zoom: ["Zoom board", "Agrandir le plateau"],
colorBlind: ["Color symbols", "Symboles de couleur"],
sound: ["Game sounds", "Sons du jeu"],
private: ["Private beta", "Bêta privée"],
credit: ["Credits", "Crédits"],
rules: ["Simplified rules", "Règles simplifiées"],
original: ["Original rulebook", "Règles originales"],
twoPlayer: ["Two-player rules", "Règles à deux joueurs"],
source: ["Source code", "Code source"],
noMoves: ["No action available", "Aucune action disponible"],
waterLeft: [
"Actions until the waters rise",
"Actions avant la montée des eaux",
],
finished: ["Game finished", "Partie terminée"],
lost: ["The islands were submerged", "Les îles ont été submergées"],
won: ["Winner", "Vainqueur"],
markers: ["Markers", "Pions"],
skip: [
"No legal effect: retrieve markers",
"Action impossible : reprendre les pions",
],
demo: ["Local practice", "Entraînement local"],
newGame: ["New game", "Nouvelle partie"],
bots: ["Play with bots", "Jouer avec des bots"],
hotseat: ["Control every seat", "Contrôler tous les joueurs"],
step: ["Bot move", "Coup automatique"],
auto: ["Autoplay", "Jeu automatique"],
saved: ["Saved locally", "Sauvegardé localement"],
selected: ["Selected", "Sélectionné"],
pending: ["Sending…", "Envoi…"],
connected: ["Waiting for the game…", "Chargement de la partie…"],
replay: ["Replay", "Replay"],
wealth: ["Wealth", "Richesse"],
touristScore: ["Visitors × huts", "Touristes × cabanes"],
preferences: ["Preferences", "Préférences"],
};
export function translator(lang) {
return (key) => entries[key]?.[lang === "fr" ? 1 : 0] ?? key;
}
export const characterHelp = {
navigator: [
"Sail 1–3 spaces for free.",
"Naviguer de 1 à 3 cases gratuitement.",
],
fisherman: [
"Fishing also earns prosperity equal to the fish tile.",
"La pêche rapporte aussi autant de prospérité que la tuile Poisson.",
],
vendor: [
"Sell fish without being beside one of your huts.",
"Vendre du poisson sans être près d’une de vos cabanes.",
],
diver: [
"Diving also earns vatus equal to the treasure tile.",
"Explorer rapporte aussi autant de vatus que la tuile Trésor.",
],
builder: [
"A hut costs 1 vatu instead of 3.",
"Une cabane coûte 1 vatu au lieu de 3.",
],
buyer: [
"Export a second matching good from the reserve for free.",
"Exporter gratuitement un second cube identique de la réserve.",
],
artist: [
"A drawing earns 5 prosperity instead of 3.",
"Un dessin rapporte 5 prospérité au lieu de 3.",
],
guide: [
"Transporting a tourist earns 2 prosperity per drawing on that island.",
"Transporter un touriste rapporte 2 prospérité par dessin sur cette île.",
],
beggar: [
"Once per round, exchange up to 3 prosperity for the same number of vatus.",
"Une fois par tour, échanger jusqu’à 3 prospérité contre autant de vatus.",
],
preacher: [
"If you hold no majority, perform one planned action anyway.",
"Sans aucune majorité, effectuer tout de même une action programmée.",
],
governor: [
"Instead of an action, move your entire stack to another action.",
"Au lieu d’une action, déplacer toute une pile vers une autre action.",
],
};

142
viewer/preview.js Normal file
View file

@ -0,0 +1,142 @@
import { mountLesson } from "./tutorial-mount.js";
import "./style.css";
import * as engine from "../engine/index.js";
import { mountGame } from "./ui.js";
const params = new URLSearchParams(location.search);
if (params.has("lesson")) {
const names = ["planning", "fishing", "islands"];
const chapter = params.get("lesson");
const next = names[names.indexOf(chapter) + 1];
await mountLesson(document.querySelector("#game"), {
chapter,
nextChapter: next
? {
title: next,
open: () => {
location.search = "?lesson=" + next;
},
}
: undefined,
});
} else {
const count = Math.max(2, Math.min(5, Number(params.get("players") ?? 3)));
let state,
hotseat = params.has("hotseat"),
timer;
const storageKey = "vanuatu-practice-v1";
try {
if (!params.has("new"))
state = JSON.parse(localStorage.getItem(storageKey));
} catch {}
if (!state?.version)
state = engine.init(
count,
params.has("water") ? ["rising-waters"] : [],
{},
params.get("seed") ?? "island-breeze",
);
state.players.forEach(
(p, i) => (p.name = ["You", "Maya", "Noa", "Leo", "Nina"][i]),
);
const control = document.createElement("div");
control.className = "preview-controls";
control.innerHTML =
'<span>Local practice · private beta</span><button data-new>New game</button><label><input type="checkbox" data-hotseat> Every seat</label><button data-step>Bot move</button><button data-auto>Autoplay</button><label>Players <select data-count><option>2</option><option selected>3</option><option>4</option><option>5</option></select></label><label><input type="checkbox" data-water> Rising Waters</label>';
document.body.prepend(control);
control.querySelector("[data-count]").value = state.players.length;
control.querySelector("[data-water]").checked = state.options.risingWaters;
control.querySelector("[data-hotseat]").checked = hotseat;
const ui = mountGame(document.querySelector("#game"), {
onMove: (m) => {
state = engine.move(state, m, hotseat ? state.actor : 0);
save();
show();
scheduleBots();
},
onPreference: (name, value) => {
preferences[name] = value;
localStorage.setItem("vanuatu-preferences", JSON.stringify(preferences));
ui.setPreferences(preferences);
},
});
let preferences = {};
try {
preferences = JSON.parse(localStorage.getItem("vanuatu-preferences")) ?? {};
} catch {}
ui.setPreferences(preferences);
function save() {
try {
localStorage.setItem(storageKey, JSON.stringify(state));
} catch {}
}
function show() {
const p = hotseat ? state.actor : 0;
ui.setPlayer(p);
ui.render(engine.stripSecret(state, p));
}
function scheduleBots() {
clearTimeout(timer);
if (!hotseat && !state.finished && state.actor !== 0)
timer = setTimeout(() => {
state = engine.moveAI(state, state.actor);
save();
show();
scheduleBots();
}, 450);
}
function bot() {
if (state.finished) return;
state = engine.moveAI(state, state.actor);
save();
show();
scheduleBots();
}
control.querySelector("[data-new]").onclick = () => {
clearTimeout(timer);
state = engine.init(
Number(control.querySelector("[data-count]").value),
control.querySelector("[data-water]").checked ? ["rising-waters"] : [],
{},
crypto.randomUUID(),
);
state.players.forEach(
(p, i) => (p.name = ["You", "Maya", "Noa", "Leo", "Nina"][i]),
);
save();
show();
scheduleBots();
};
control.querySelector("[data-hotseat]").onchange = (e) => {
hotseat = e.target.checked;
show();
scheduleBots();
};
control.querySelector("[data-step]").onclick = bot;
let autoplay = false;
control.querySelector("[data-auto]").onclick = async (e) => {
autoplay = !autoplay;
e.target.textContent = autoplay ? "Stop" : "Autoplay";
while (autoplay && !state.finished) {
clearTimeout(timer);
state = engine.moveAI(state, state.actor);
save();
show();
await new Promise((r) => setTimeout(r, 160));
}
autoplay = false;
e.target.textContent = "Autoplay";
};
window.vanuatuDemo = {
get state() {
return state;
},
setState(s) {
state = s;
show();
},
engine,
ui,
};
show();
scheduleBots();
}

82
viewer/rules.js Normal file
View file

@ -0,0 +1,82 @@
import { icon, token } from "./art.js";
export function rulesHtml(lang = "en") {
const fr = lang === "fr";
const paragraphs = fr
? [
[
"Vivre de l’archipel",
`En 8 tours, gagnez de la prospérité ${icon("point")} en commerçant, en accueillant des touristes et en créant des dessins de sable. ${token("coin", 10)} se convertissent immédiatement en ${token("point", 5)}.`,
],
[
"Programmer, puis agir",
`Choisissez un personnage, puis placez vos 5 pions en trois passages : 2, 2, 1. À votre tour, effectuez une action où vous avez le plus de pions. Les égalités se départagent depuis le premier joueur ${icon("first")}. Tous vos pions de cette action sont repris. Sans majorité, reprenez une pile sans effectuer l’action.`,
],
[
"Au bon endroit",
`Naviguez ${icon("sail")} de 1 à 3 cases d’océan pour autant de ${icon("coin")}. Pêchez ${icon("fish")} ou explorez ${icon("explore")} sur votre case : prenez la valeur encore présente, puis retirez un marqueur. Les autres actions concernent une île voisine.`,
],
[
"Faire du commerce",
`Vendez vos poissons près de l’une de vos cabanes ${icon("build")} : leur valeur × le prix du marché. Le prix diminue après chaque vente. Exportez ${icon("kava")} / ${icon("copra")} / ${icon("beef")} pour ${token("coin", "1 / 2 / 3")}, contre ${token("point", "1 / 3 / 5")} si un navire en demande. Compléter un navire rapporte ${token("point", 2)}.`,
],
[
"Développer les îles",
`Une cabane ${icon("build")} coûte ${token("coin", 3)}. Un dessin ${icon("draw")} rapporte ${token("point", 3)}. Transporter un touriste ${icon("tourist")} rapporte ${token("coin", 1)} par cabane sur cette île, quelle que soit sa couleur. Se reposer ${icon("rest")} permet de choisir un bonus secret, résolu en fin de tour.`,
],
[
"Personnages",
`Chaque personnage améliore une action, une fois par tour. Vous choisissez le nouveau personnage avant de rendre l’ancien : impossible de garder le même deux tours de suite. Les trésors ${icon("explore")} peuvent être vendus à tout moment pour leur valeur en ${icon("coin")}.`,
],
[
"Fin de partie",
`Après le 8e tour : poissons restants → autant de ${icon("coin")}, premier joueur → ${token("point", 3)}, chaque ${token("coin", 3)} → ${token("point", 1)}, trésors → deux fois leur valeur en ${icon("point")}, chaque cabane → ${token("point", 2)} par touriste sur son île. La plus grande prospérité l’emporte ; puis le plus de cabanes, puis de vatus.`,
],
[
"À deux joueurs",
`Placez d’abord 2, puis 3 pions neutres. Pour agir, il faut aussi dépasser leur nombre ; le personnage correspondant permet de les égaler. Les personnages disponibles changent chaque tour. Deux bateaux ne peuvent pas terminer leur déplacement sur la même case.`,
],
[
"La Montée des eaux",
`Aux tours pairs, le dé indique combien d’actions précèdent l’inondation. Chaque côte adjacente à un océan et sans digue ajoute 1 eau. Construisez une digue ${icon("dike")} pour ${token("coin", 1)} avec l’action Construire. À 5 eaux, l’île est submergée ; à 3 îles submergées, tout le monde perd. Chaque cabane sur une île avec 1 / 2 / 3 / 4 eaux perd 1 / 3 / 5 / 7 prospérité en fin de partie.`,
],
]
: [
[
"A living archipelago",
`Over 8 rounds, earn prosperity ${icon("point")} through trade, tourism and sand drawings. Every ${token("coin", 10)} immediately becomes ${token("point", 5)}.`,
],
[
"Plan, then act",
`Choose a character, then place your 5 markers in three passes: 2, 2, 1. On your turn, take an action where you have the most markers. Ties follow turn order from the first player ${icon("first")}. Retrieve all your markers from that action. Without a majority, retrieve one stack without performing its action.`,
],
[
"Be in the right place",
`Sail ${icon("sail")} 1–3 ocean spaces for that many ${icon("coin")}. Fish ${icon("fish")} or explore ${icon("explore")} on your space: take its remaining value, then remove one marker. Island actions need your boat beside the island.`,
],
[
"Trade",
`Sell fish beside one of your huts ${icon("build")}: fish values × the market price. The price falls after each sale. Export ${icon("kava")} / ${icon("copra")} / ${icon("beef")} for ${token("coin", "1 / 2 / 3")}, earning ${token("point", "1 / 3 / 5")} when a ship needs them. Completing a ship earns ${token("point", 2)}.`,
],
[
"Develop the islands",
`A hut ${icon("build")} costs ${token("coin", 3)}. A drawing ${icon("draw")} earns ${token("point", 3)}. Transporting a tourist ${icon("tourist")} earns ${token("coin", 1)} for every hut on that island, of any colour. Rest ${icon("rest")} lets you choose a secret bonus, resolved at the end of the round.`,
],
[
"Characters",
`Each character improves one action, once per round. Choose your next character before returning your old one; you cannot keep the same character for consecutive rounds. Treasures ${icon("explore")} may be sold at any time for their value in ${icon("coin")}.`,
],
[
"Final scoring",
`After round 8: remaining fish → their value in ${icon("coin")}; first player → ${token("point", 3)}; every ${token("coin", 3)} → ${token("point", 1)}; treasures → twice their value in ${icon("point")}; each hut → ${token("point", 2)} per tourist on its island. Most prosperity wins; ties favour more huts, then more vatus.`,
],
[
"Two players",
`Place 2, then 3 neutral markers before choosing characters. You must also beat the neutral stack to act; the matching character lets you tie it. Available characters change each round. Boats cannot end their movement on the same space.`,
],
[
"Rising Waters",
`On even rounds, the die gives the number of actions before flooding. Every adjacent ocean coast without a dike adds 1 water. Build a dike ${icon("dike")} for ${token("coin", 1)} with the Build action. At 5 waters an island sinks; if 3 islands sink, everyone loses. Each hut on an island with 1 / 2 / 3 / 4 waters loses 1 / 3 / 5 / 7 prosperity at game end.`,
],
];
return `<div class="rules">${paragraphs.map(([h, p]) => `<section><h3>${h}</h3><p>${p}</p></section>`).join("")}</div><p class="rules-links"><a href="https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_${fr ? "FR-WEBversion" : "UK_WEBversion-4"}.pdf" target="_blank" rel="noopener">${fr ? "Règles originales" : "Original rulebook"} ↗</a> · <a href="https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf" target="_blank" rel="noopener">${fr ? "Règles à deux" : "Two-player rules"} ↗</a></p>`;
}

1271
viewer/style.css Normal file

File diff suppressed because it is too large Load diff

50
viewer/tutorial-mount.js Normal file
View file

@ -0,0 +1,50 @@
import { createTutorial } from "@boardgamers/protocol/tutorial";
import { mountTutorialGuide } from "@boardgamers/protocol/tutorial/dom";
import { stripSecret } from "../engine/index.js";
import { chapters } from "./tutorials.js";
import { mountGame } from "./ui.js";
export async function mountLesson(target, options) {
const config = chapters[options.chapter];
if (!config) throw Error("Unknown chapter");
let storage;
try {
storage = window.localStorage;
} catch {}
const tutorial = await createTutorial({
...config,
storage,
onProgress: options.onProgress,
});
const guide = document.createElement("div");
guide.className = "vanuatu-tutorial";
target.append(guide);
const ui = mountGame(target, {
language: "en",
onMove: async (m) => {
const accepted = await tutorial.play(m);
if (!accepted)
throw Error(
tutorial.snapshot.error ||
tutorial.snapshot.feedback ||
"Try the action described in this step.",
);
},
});
ui.setPlayer(0);
const off = tutorial.subscribe((snapshot) => {
ui.render(stripSecret(snapshot.state, 0));
ui.setEnabled(
!snapshot.busy && !snapshot.completed && !snapshot.canContinue,
);
});
const unmount = mountTutorialGuide(guide, tutorial, {
nextChapter: options.nextChapter,
});
return () => {
off();
unmount();
tutorial.destroy();
ui.destroy();
guide.remove();
};
}

180
viewer/tutorials.js Normal file
View file

@ -0,0 +1,180 @@
import * as E from "../engine/index.js";
export const chapterMetadata = [
{
id: "planning",
version: 1,
title: "Plan your day",
description: "Place five markers and understand action majorities.",
},
{
id: "fishing",
version: 1,
title: "From sea to market",
description: "Sail, fish and sell your catch beside your hut.",
},
{
id: "islands",
version: 1,
title: "An island economy",
description: "Build a hut, draw in the sand and welcome a tourist.",
},
];
function prepared(phase = "actions") {
const s = E.init(3, [], {}, "vanuatu-lesson");
s.actor = 0;
s.first = 0;
s.phase = phase;
s.players.forEach((p, i) => {
p.name = ["You", "Maya", "Noa"][i];
p.markers = Object.fromEntries(E.ACTIONS.map((a) => [a, 0]));
p.character = null;
p.boat = "1,1";
});
s.board = {
"0,0": E.tileState("efate"),
"1,0": E.tileState("startFish"),
"0,1": E.tileState("startWreck"),
"1,1": E.tileState("startBoat"),
};
s.tourists = 2;
return s;
}
function play(s, m) {
let next = E.move(s, m, 0),
n = 0;
while (!next.finished && next.actor !== 0 && n++ < 100)
next = E.moveAI(next, next.actor);
return next;
}
const planCount = (s) =>
Object.values(s.players[0].markers).reduce((a, b) => a + b, 0);
const only = (action) => (s, m) =>
m.action === action ? undefined : `Choose ${action} for this step.`;
export const chapters = {
planning: {
game: "vanuatu",
id: "planning",
version: 1,
initialState: () => {
const s = prepared("plan");
s.characters = [];
s.options.characters = false;
return s;
},
move: play,
steps: [
{
id: "first-two",
title: "Plan two actions",
text: "Place your first two markers. Sailing opens up fishing and island actions; extra markers help win a majority.",
complete: (s) => planCount(s) >= 2,
validateMove: (s, m) =>
m.type === "plan" ? undefined : "Place the two markers first.",
},
{
id: "next-two",
title: "Two more markers",
text: "The others have placed their markers. Reinforce an action or plan something new. An action can be performed once, however many markers you place there.",
complete: (s) => planCount(s) >= 4,
},
{
id: "last",
title: "One last marker",
text: "Place your fifth marker. During the action phase, ties are broken in order from the first player.",
complete: (s) => s.phase === "actions",
},
],
completion: {
title: "Your plan is ready",
text: "Choose an action where you have the most markers, then retrieve your whole stack. Without a majority, retrieve one stack without acting.",
},
},
fishing: {
game: "vanuatu",
id: "fishing",
version: 1,
initialState: () => {
const s = prepared();
s.board["0,0"].huts = [0];
s.players[0].hutsLeft = 7;
s.players[0].markers.sail = 1;
s.players[0].markers.fish = 1;
s.players[0].markers.sell = 1;
return s;
},
move: play,
steps: [
{
id: "sail",
title: "Find a fishing ground",
text: "Choose Sail and move onto the ocean with 2 fish. Each space costs 1 vatu.",
complete: (s) => s.players[0].boat === "1,0",
validateMove: (s, m) =>
m.action === "sail" && m.path.at(-1) === "1,0"
? undefined
: "Sail to the ocean with 2 fish.",
},
{
id: "fish",
title: "Catch the fish",
text: "Choose Fish. The catch has value 2; the fishing ground then falls to 1.",
complete: (s) => s.players[0].fish.includes(2),
validateMove: only("fish"),
},
{
id: "sell",
title: "Sell your catch",
text: "Your boat is beside your orange hut. Sell the catch: 2 fish × a market price of 3 = 6 vatus.",
complete: (s) => s._history.some((h) => h.move.action === "sell"),
validateMove: only("sell"),
},
],
completion: {
title: "Trade keeps you moving",
text: "The fish market falls after a sale and resets next round. Every 10 vatus automatically becomes 5 prosperity.",
},
},
islands: {
game: "vanuatu",
id: "islands",
version: 1,
initialState: () => {
const s = prepared();
s.players[0].character = "builder";
s.players[0].boat = "1,0";
for (const a of ["build", "draw", "tourist"]) s.players[0].markers[a] = 1;
return s;
},
move: play,
steps: [
{
id: "hut",
title: "Build a beach hut",
text: "Build beside your boat. Use the Builder: your hut costs only 1 vatu instead of 3.",
complete: (s) => s.board["0,0"].huts.includes(0),
validateMove: (s, m) =>
m.action === "build" && m.bonus
? undefined
: "Build a hut with the Builder bonus enabled.",
},
{
id: "drawing",
title: "Draw in the sand",
text: "A sand drawing earns 3 prosperity. It stays on the island and may help a future Guide.",
complete: (s) => s.board["0,0"].drawings > 0,
validateMove: only("draw"),
},
{
id: "tourist",
title: "Welcome a visitor",
text: "Transport a tourist to the island. You earn 1 vatu per hut there. At game end, each of your huts earns 2 prosperity per tourist.",
complete: (s) => s.board["0,0"].tourists > 0,
validateMove: only("tourist"),
},
],
completion: {
title: "Ready to sail",
text: "Prosperity comes from trade, drawings, characters and endgame scoring. Keep enough vatus to fund the actions you plan.",
},
},
};

587
viewer/ui.js Normal file
View file

@ -0,0 +1,587 @@
import {
ACTIONS,
CHARACTERS,
TILES,
PRICES,
VALUES,
} from "../engine/catalog.js";
import { assets } from "./assets.js";
import { icon, token, esc } from "./art.js";
import { boardSvg, center } from "./board.js";
import { translator, characterHelp } from "./labels.js";
import { mountActivity } from "./activity.js";
import { rulesHtml } from "./rules.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 symbols = ["●", "◆", "▲", "■", "✦"];
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 s,
player,
enabled = true,
analysis = false,
pending = false,
selected = null,
action = null,
draft = [],
tile = null,
bonus = true,
zoom = false,
lang =
options.language ?? (navigator.language.startsWith("fr") ? "fr" : "en"),
colorBlind = false,
sound = false,
revision,
focusReturn;
let t = translator(lang);
const events = new AbortController();
const listener = { signal: events.signal };
const activity = mountActivity(root.querySelector(".activity-root"), {
chat: options.chat,
openPlayer: options.onOpenPlayer,
onBack: () => play.scrollIntoView({ block: "start" }),
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);
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]?.[lang === "fr" ? "fr" : "name"] ?? c);
const charHelp = (c) => esc(characterHelp[c]?.[lang === "fr" ? 1 : 0] ?? "");
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("undo")} ${t("discard")} ${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") {
let gain = 0;
const ships = s.demands.map((d) => ({ ...d, filled: [...d.filled] }));
for (let n = 0; n < (m.bonus ? 2 : 1); n++) {
const d = ships.find((d) =>
d.goods.some((g, i) => g === m.good && !d.filled[i]),
);
if (!d) continue;
d.filled[d.goods.findIndex((g, i) => g === m.good && !d.filled[i])] =
true;
gain += VALUES[m.good] + (d.filled.every(Boolean) ? 2 : 0);
}
return `${token(m.good, m.bonus ? 2 : 1)} · ${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 moveButton(m, primary = false) {
const idx = (s.legal ?? []).indexOf(m);
return btn(
actionDetail(m),
`data-move="${idx}" ${pending ? "disabled" : ""}`,
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 class="player-card ${i === s.actor && !s.finished ? "active" : ""} ${i === player ? "own" : ""}" style="--player:${p.color}"><div class="player-name">${btn(`${colorBlind ? symbols[i] + " " : ""}${esc(p.name)}`, `data-bgs-player="${i}"`, "profile")} ${s.first === i ? icon("first", t("first")) : ""}<strong class="score">${token("point", p.score)}</strong></div><div class="player-supplies">${token("coin", p.money)}<span class="hand" title="${t("fish")}">${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}"><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 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 stacks = s.players
.map((p, i) =>
p.markers[a]
? `<span class="marker-stack ${s.majorities?.[i]?.includes(a) ? "majority" : ""}" style="--player:${p.color}" title="${esc(p.name)}: ${p.markers[a]}">${colorBlind ? symbols[i] : ""}${p.markers[a]}</span>`
: "",
)
.join("");
return btn(
`<span class="action-symbol">${icon(a)}</span><span class="action-label">${t(a)}</span><span class="action-stacks">${stacks}${s.neutral[a] ? `<span class="marker-stack neutral">${s.neutral[a]}</span>` : ""}${countDraft ? `<span class="draft-marker">+${countDraft}</span>` : ""}</span>`,
`data-action="${a}" ${allowed ? "" : "disabled"} aria-pressed="${action === a}"`,
`${action === a ? "chosen" : ""} ${allowed ? "available" : ""}`,
);
},
).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><span>${charHelp(m.character)}</span>`,
`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")}</div><div class="tile-choices">${tileChoices.map((id) => btn(`<img src="${assets[TILES[id].art]}" alt="${TILES[id].type === "island" ? t("island") : t("sea")}">`, `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);
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")} ${lang === "fr" ? "Choisir une case" : "Choose a space"}`
: "";
return `<div class="turn-tray"><div class="tray-title">${selectedAction ? `${icon(action)} ${t(action)}` : t("actions")}</div>${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 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 scroll = play.querySelector(".map-scroll");
const sx = scroll?.scrollLeft ?? 0,
sy = scroll?.scrollTop ?? 0;
const trayHtml = tray();
const targets =
s.phase === "expand"
? working()
.filter((m) => m.type === "place" && m.tile === tile)
.map((m) => m.cell)
: actualTargets();
play.innerHTML = `<header class="game-header"><div class="brand">${btn("Vanuatu", "data-boardgame", "wordmark")}<span>Alain Epron · Quined Games</span></div><div class="round-track" aria-label="${t("round")} ${s.round}/8">${Array.from({ length: 8 }, (_, i) => `<span class="${i + 1 === s.round ? "current" : i + 1 < s.round ? "past" : ""}">${i + 1}</span>`).join("")}</div><nav class="header-tools">${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("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" style="--ocean:url('${assets.ocean}')"><div class="sea-dashboard"><div class="market-info"><span title="${t("market")}">${icon("fish")} = ${token("coin", s.market)}</span><span title="${t("tourist")}">${token("tourist", s.tourists)}</span>${s.waterCountdown !== null ? `<span title="${t("waterLeft")}">${token("water", s.waterCountdown)}</span>` : ""}</div><div class="demand-ships" aria-label="${t("demand")}">${s.demands.map((d, i) => `<div class="demand-ship" title="${t("demand")} ${i + 1} · +2 ${t("point")}"><small>${i + 1}</small>${d.goods.map((g, j) => `<span class="${d.filled[j] ? "filled" : ""}">${icon(g)}${d.filled[j] ? icon("check") : ""}</span>`).join("")}${icon("buy")}</div>`).join("")}</div></div><div class="map-scroll ${zoom ? "zoomed" : ""}">${boardSvg(s, { player, colorBlind, selected, targets, hoverTile: s.phase === "expand" ? tile : null, t })}</div><div class="map-tools">${titled(zoom ? t("fit") : t("zoom"), icon(zoom ? "eye" : "zoom"), "data-zoom", "icon-button")}</div>${s.upcoming.length && s.phase !== "expand" ? `<div class="upcoming" title="${t("next")}">${s.upcoming.map((id) => `<img src="${assets[TILES[id].art]}" alt="${t(TILES[id].type === "island" ? "island" : "sea")}">`).join("")}</div>` : ""}${trayHtml}</section></div><section class="players">${s.players.map(playerCard).join("")}</section><footer class="play-footer"><span>${t("private")}</span><span title="${lang === "fr" ? "Conversion automatique" : "Automatic conversion"}">${token("coin", 10)} → ${token("point", 5)}</span>${btn(t("help"), "data-help", "text-button")}</footer>`;
const newScroll = play.querySelector(".map-scroll");
if (newScroll) {
newScroll.scrollLeft = sx;
newScroll.scrollTop = sy;
}
if (focus)
play
.querySelector(`[data-action="${focus}"]`)
?.focus({ preventScroll: true });
activity.update(s, analysis);
updateUnread();
}
function updateUnread() {
const n = options.chat?.snapshot.unreadIds.length ?? 0;
const badge = play.querySelector(".unread-badge");
if (badge) {
badge.textContent = n;
badge.hidden = !n;
}
activity.setUnread(n);
}
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 });
}
async function send(m) {
if (!m || pending || !enabled) return;
pending = true;
feedback.hidden = true;
render();
try {
await options.onMove?.(m);
if (sound) {
try {
const context = new AudioContext();
const oscillator = context.createOscillator(),
gain = context.createGain();
gain.gain.setValueAtTime(0.025, context.currentTime);
gain.gain.exponentialRampToValueAtTime(
0.001,
context.currentTime + 0.13,
);
oscillator.frequency.value = 540;
oscillator.connect(gain).connect(context.destination);
oscillator.start();
oscillator.stop(context.currentTime + 0.13);
oscillator.onended = () => context.close();
} catch {}
}
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];
if (b?.type === "island")
showDialog(
`<h2>${t("island")}</h2><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>`,
);
}
render();
}
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 ("move" in d) {
send(s.legal[Number(d.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 (["plan", "neutral"].includes(s.phase)) {
draft.push(d.action);
if (s.phase === "neutral")
draft.sort((a, b) => ACTIONS.indexOf(a) - ACTIONS.indexOf(b));
} else {
action = d.action;
selected = null;
const targets = actualTargets();
if (targets.length === 1) selected = targets[0];
}
render();
return;
}
if ("undo" in d) {
draft.pop();
render();
return;
}
if ("tile" in d) {
tile = d.tile;
selected = null;
render();
return;
}
if ("cancel" in d) {
action = null;
selected = null;
render();
return;
}
if ("zoom" in d) {
zoom = !zoom;
render();
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>${charHelp(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>${charHelp(d.character)}</p><small>${lang === "fr" ? "Une fois par tour." : "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 ("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><label><input type="checkbox" data-pref="sound" ${sound ? "checked" : ""}>${t("sound")}</label><select data-language aria-label="Language"><option value="en" ${lang === "en" ? "selected" : ""}>English</option><option value="fr" ${lang === "fr" ? "selected" : ""}>Français</option></select></div>${rulesHtml(lang)}<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}"><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;
render();
}
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;
options.onPreference?.(key, value);
render();
}
if (e.target.matches("[data-language]")) {
lang = e.target.value;
t = translator(lang);
closeDialog();
activity.setLanguage(lang);
render();
}
},
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) {
const next = `${state.historyLength ?? state.round + ":" + state.phase}:${player}`;
if (next !== revision) {
selected = null;
action = null;
draft = [];
revision = next;
}
s = state;
render();
},
setPlayer(p) {
if (player !== p) {
player = p;
draft = [];
action = null;
selected = null;
}
render();
},
setEnabled(v) {
enabled = v;
render();
},
setPreferences(p) {
analysis = p.analysis === true;
colorBlind = p.colorBlind === true;
sound = p.sound === true;
if (["en", "fr"].includes(p.language)) {
lang = p.language;
t = translator(lang);
}
render();
},
destroy() {
events.abort();
offChat?.();
activity.destroy();
root.remove();
},
};
}