Release Vanuatu 0.2.0 with 3D board and saved view preferences

This commit is contained in:
coyotte508 2026-11-01 17:41:05 +01:00
commit 33c9f2a59a
62 changed files with 4047 additions and 128 deletions

View file

@ -12,7 +12,7 @@ The repository is public; the game is listed on BGS as a beta. Supplied artwork
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.
BGS supplies the shared `colorBlind` and `sound` preferences. Color-blind mode adds player symbols and K/C/B resource labels; game sounds give a quiet confirmation after successful moves. The toggles in Rules & help update the same BGS account settings. Standalone practice stores its own preferences locally.
BGS supplies the shared `colorBlind` and `sound` preferences. Color-blind mode adds player symbols and K/C/B resource labels; game sounds give a quiet confirmation after successful moves. The toggles in Rules & help update the same BGS account settings. Standalone practice stores its own preferences locally. The 2D/3D switch saves the `mapView` preference through BGS; 3D is the default, with a 2D fallback when WebGL is unavailable. Motion follows the browser’s reduced-motion setting.
Marker retrieval is manual by default, including the last unusable action stack. Each player can opt into automatic retrieval when retrieving one stack is the only available move in Rules & help; this setting is saved separately for each game. Automatic retrieval never skips optional treasure exchanges or chooses between multiple stacks. Guided lessons always use manual retrieval.

View file

@ -810,13 +810,17 @@ function endRound(s) {
s._demandDiscards.push(d);
s.demands = s.demands.filter((d) => !d.filled.every(Boolean));
while (s.demands.length < 3) s.demands.push(revealDemand(s));
for (const t of Object.values(s.board))
const refills = [];
for (const [cell, t] of Object.entries(s.board))
if (
t.type === "island" &&
!t.submerged &&
sum(Object.values(t.goods)) === 0
)
) {
t.goods = { ...TILES[t.id].goods };
if (sum(Object.values(t.goods)))
refills.push({ cell, goods: { ...t.goods } });
}
if (s.players.length === 2) {
const previous = new Set([
...s.characters,
@ -838,7 +842,12 @@ function endRound(s) {
s.planningPass = 0;
s.neutral = emptyMarkers();
s.neutralPlaced = 0;
say(s, "round", { round: s.round, first: s.first, tourists: s.tourists });
say(s, "round", {
round: s.round,
first: s.first,
tourists: s.tourists,
refills,
});
}
function finish(s) {
for (const [p, a] of s.players.entries()) {

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/vanuatu",
"version": "0.1.10",
"version": "0.2.0",
"private": true,
"type": "module",
"main": "dist/engine.js",
@ -11,7 +11,7 @@
"build": "node scripts/build.mjs",
"test": "node --test test/*.test.js",
"dev": "node scripts/dev.mjs",
"test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/map-drag-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs && node test/effects-browser.mjs",
"test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/map-drag-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs && node test/effects-browser.mjs && node test/three-viewer-browser.mjs",
"check": "pnpm test:locales && pnpm build && pnpm test && pnpm test:browser && pnpm test:tutorial:browser",
"test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs",
"test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs && node test/tutorial-errors-browser.mjs"
@ -19,7 +19,8 @@
"dependencies": {
"@boardgamers/protocol": "0.10.0",
"@noble/hashes": "2.0.1",
"morphdom": "2.7.8"
"morphdom": "2.7.8",
"three": "0.186.1"
},
"devDependencies": {
"esbuild": "0.25.12",

8
pnpm-lock.yaml generated
View file

@ -17,6 +17,9 @@ importers:
morphdom:
specifier: 2.7.8
version: 2.7.8
three:
specifier: 0.186.1
version: 0.186.1
devDependencies:
esbuild:
specifier: 0.25.12
@ -221,6 +224,9 @@ packages:
engines: {node: '>=14'}
hasBin: true
three@0.186.1:
resolution: {integrity: sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==}
zod@4.6.5:
resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}
@ -354,4 +360,6 @@ snapshots:
prettier@3.6.2: {}
three@0.186.1: {}
zod@4.6.5: {}

View file

@ -1,3 +1,7 @@
import {
mapViewPreference,
releasePreferences,
} from "./release-preferences.mjs";
import { uploadViewerFiles } from "./viewer-files.mjs";
import { chapterMetadata } from "../viewer/tutorials.js";
import { readFile, mkdir, writeFile } from "node:fs/promises";
@ -68,12 +72,7 @@ const defaults = {
default: false,
},
{ name: "sound", label: "Game sounds", type: "checkbox", default: true },
{
name: "animations",
label: "Animations",
type: "checkbox",
default: true,
},
mapViewPreference,
{
name: "language",
label: "Language",
@ -123,17 +122,9 @@ const files = await uploadViewerFiles(
const viewer = { url: files.url },
style = { url: files.stylesheets[0] };
const patch = {
preferences: [
...(existing?.preferences ?? defaults.preferences).filter(
(preference) => preference.name !== "animations",
),
existing?.preferences?.find(
(preference) => preference.name === "animations",
) ??
defaults.preferences.find(
(preference) => preference.name === "animations",
),
],
preferences: releasePreferences(
existing?.preferences ?? defaults.preferences,
),
settings: [
...(existing?.settings ?? []).filter(
(setting) => setting.name !== "autoRetrieve",
@ -207,6 +198,10 @@ if (existing) {
} else assert.ok(!meta.unlisted);
assert.equal(published.engine.package.version, pkg.version);
assert.equal(published.viewer.chat, true);
assert.deepEqual(
published.preferences,
releasePreferences(existing?.preferences ?? defaults.preferences),
);
await writeFile(
".local/release/published.json",
JSON.stringify(published, null, 2),

View file

@ -0,0 +1,24 @@
export const mapViewPreference = {
name: "mapView",
label: "2D / 3D",
type: "select",
default: "3d",
items: [
{ name: "2d", label: "2D" },
{ name: "3d", label: "3D" },
],
};
export function releasePreferences(existing) {
const preferences = existing.filter(
({ name }) => name !== "animations" && name !== "mapView",
);
if (!preferences.some(({ name }) => name === "sound"))
preferences.push({
name: "sound",
label: "Game sounds",
type: "checkbox",
default: true,
});
return [...preferences, mapViewPreference];
}

View file

@ -42,6 +42,7 @@ const page = await browser.newPage({
locale: "fr-FR",
});
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await page.goto(base + "/?new&hotseat");
await page.waitForSelector("[data-character-choice]");
// Decorative motion must never move a tile's clickable/focusable SVG bounds.
@ -94,6 +95,9 @@ for (const locale of [
"utf8",
),
);
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`${base}/?new&hotseat&locale=${locale}`);
await page.waitForFunction(
(expected) =>
@ -116,6 +120,7 @@ for (const locale of [
);
}
}
await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await page.goto(base + "/?new&hotseat");
await page.waitForSelector("[data-character-choice]");
// Action descriptions remain available even before an action can be selected.
@ -763,6 +768,7 @@ 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.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await page.goto(base + "/");
await page.evaluate(() => {
document.body.innerHTML = '<div id="host"></div>';

View file

@ -93,6 +93,7 @@ try {
}
};
});
await p.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await p.goto(`http://127.0.0.1:${server.address().port}/`);
if (width === 1440) {
const samples = await p.evaluate(async () => {
@ -293,13 +294,8 @@ try {
0,
"Reduced motion suppresses overlays",
);
await p.emulateMedia({ reducedMotion: "no-preference" });
await p.evaluate(() =>
host.emit("preferences", {
locale: "fr",
sound: false,
animations: false,
}),
host.emit("preferences", { locale: "fr", sound: false, mapView: "2d" }),
);
await emit(s);
const mutedAt = await p.evaluate(() => window.played);
@ -311,11 +307,9 @@ try {
"Muted incoming moves are silent",
);
await p.locator("[data-help]").first().click();
assert.equal(
await p.locator('[data-pref="animations"]').isChecked(),
false,
);
await p.locator('[data-pref="animations"]').check();
assert.equal(await p.locator('[data-pref="animations"]').count(), 0);
assert.equal(await p.locator("[data-map-preference]").inputValue(), "2d");
await p.emulateMedia({ reducedMotion: "no-preference" });
await p.locator("dialog [data-close]").click();
await emit(s);
await emit(sailed);

View file

@ -108,6 +108,9 @@ try {
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`http://127.0.0.1:${server.address().port}`);
await page.evaluate((state) => {
window.fixture = state;

View file

@ -38,6 +38,9 @@ try {
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(base + "/?new&hotseat");
await page.waitForFunction(() => window.vanuatuDemo);
const state = E.init(3, [], {}, "mouse-pan");
@ -156,15 +159,13 @@ try {
await page.evaluate((type) => {
if (type === "blur") window.dispatchEvent(new Event("blur"));
else
document
.querySelector(".map-scroll")
.dispatchEvent(
new PointerEvent(type, {
bubbles: true,
pointerId: window.lastPointer,
pointerType: "mouse",
}),
);
document.querySelector(".map-scroll").dispatchEvent(
new PointerEvent(type, {
bubbles: true,
pointerId: window.lastPointer,
pointerType: "mouse",
}),
);
}, cancel);
await page.mouse.up();
assert.equal(await map.getAttribute("data-pan"), "ready");

View file

@ -98,6 +98,9 @@ try {
const page = await browser.newPage({ viewport: { width, height } });
page.on("pageerror", (error) => errors.push(error.message));
for (const state of [E.init(3, [], {}, "map-fit"), partial, expanded]) {
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(base + "/?hotseat");
await page.evaluate(
(s) => localStorage.setItem("vanuatu-practice-v1", JSON.stringify(s)),
@ -230,6 +233,9 @@ try {
viewport: { width: 390, height: 844 },
});
resizedPage.on("pageerror", (error) => errors.push(error.message));
await resizedPage.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await resizedPage.goto(base + "/?hotseat");
await resizedPage.evaluate(
(s) => localStorage.setItem("vanuatu-practice-v1", JSON.stringify(s)),
@ -264,6 +270,9 @@ try {
hasTouch: true,
});
page.on("pageerror", (error) => errors.push(error.message));
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(base + "/?new&hotseat&locale=fr");
await page.waitForSelector(".map-scroll[data-zoom]");
assert.equal(

View file

@ -43,6 +43,9 @@ try {
});
page.on("pageerror", (error) => errors.push(error.message));
for (const count of [2, 3, 5]) {
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`${base}/?new&hotseat&players=${count}&locale=fr`);
await page.waitForFunction(() => window.vanuatuDemo);
await page.evaluate(() => {

145
test/navigation.test.js Normal file
View file

@ -0,0 +1,145 @@
import assert from "node:assert/strict";
import {
seaRoute,
routePosition,
giveWay,
passingSide,
arrivalFraction,
stepYield,
} from "../viewer/three/navigation.js";
import * as engine from "../engine/index.js";
const opening = engine.init(3, [], {}, "navigation");
const expanded = structuredClone(opening);
for (const cell of ["2,0", "2,1", "2,2", "1,2", "0,2", "-1,1", "-1,0"])
expanded.board[cell] = engine.tileState("c1");
const scenes = { opening, expanded };
const tilt = Math.PI / 9;
function position(id) {
const [q, r] = id.split(",").map(Number),
x = q * 162 - r * 81,
z = r * 140.3;
return {
x: (x * Math.cos(tilt) - z * Math.sin(tilt)) / 60,
z: (x * Math.sin(tilt) + z * Math.cos(tilt)) / 60,
};
}
let checks = 0;
for (const state of Object.values(scenes)) {
const seas = Object.keys(state.board).filter(
(id) => state.board[id].type === "sea",
);
for (const from of seas)
for (const to of seas) {
if (from === to) continue;
for (let count = 1; count <= 3; count++) {
const a = position(from),
b = position(to),
start = { x: a.x, z: a.z - 0.15 },
end = { x: b.x + (count - 1) * 0.47, z: b.z - 0.15 };
const path = seaRoute(state.board, from, to, start, end, position);
assert.ok(
path.length >= 2,
"Every sea destination has an animation even when crowded",
);
assert.deepEqual(routePosition(path, 0), start);
assert.deepEqual(routePosition(path, 1), end);
for (let i = 0; i <= 100; i++) {
const p = routePosition(path, i / 100);
assert.ok(Number.isFinite(p.x) && Number.isFinite(p.z));
}
checks++;
}
}
}
const path = [
{ x: 0, z: 0 },
{ x: 5, z: 0 },
],
near = { x: 2.5, z: 0.2 };
const boat = { minX: -0.28, maxX: 0.46, minZ: -0.52, maxZ: 0.3 };
const fish = { minX: -0.43, maxX: 0.43, minZ: -0.26, maxZ: 0.26 };
const side = passingSide(path, near, 0);
const offset = giveWay(
near,
{ x: 2.5, z: 0 },
{ x: 1, z: 0 },
side,
boat,
fish,
);
assert.ok(
near.z + offset.z + fish.minZ > boat.maxZ,
"An intersecting fish moves far enough aside",
);
assert.deepEqual(
giveWay(near, { x: 5, z: 0 }, { x: 1, z: 0 }, side, boat, fish),
{ x: 0, z: 0 },
"It returns after the boat passes",
);
for (const direction of [
{ x: 1, z: 0 },
{ x: 0, z: 1 },
{ x: 1, z: 1 },
{ x: -1, z: 1 },
]) {
for (const sign of [-1, 1]) {
for (const point of [
{ x: 0, z: -10 },
{ x: 0, z: 10 },
{ x: -10, z: 0 },
{ x: 10, z: 0 },
{ x: 2.7, z: 0 },
]) {
assert.deepEqual(
giveWay(point, { x: 0, z: 0 }, direction, sign, boat, fish),
{ x: 0, z: 0 },
"Remote and neighbouring-tile resources stay still, even on the opposite side of the route",
);
}
}
}
assert.equal(
arrivalFraction(6),
0,
"No destination rearrangement at departure",
);
assert.equal(
arrivalFraction(1.1),
0,
"Wait until the boat is actually approaching its berth",
);
assert.ok(
arrivalFraction(0.6) > 0 && arrivalFraction(0.6) < 1,
"Rearrange progressively on approach",
);
assert.equal(arrivalFraction(0), 1, "Berths settle completely on arrival");
console.log(
`${checks} routes checked; local contact only, remote pieces stay still, destination waits for arrival.`,
);
const pose = { x: 0, z: 0, yaw: 0, vx: 0, vz: 0, vyaw: 0 };
let previous = 0;
for (let i = 0; i < 40; i++) {
stepYield(pose, { x: 0.5, z: 0, yaw: 0.2 }, 1 / 60);
assert.ok(
pose.x >= previous && pose.x <= 0.5,
"Yielding approaches its target without reversing or overshooting",
);
previous = pose.x;
}
assert.ok(pose.yaw > 0.19, "The piece pivots while giving way");
for (let i = 0; i < 60; i++) {
stepYield(pose, { x: 0, z: 0, yaw: 0 }, 1 / 60);
assert.ok(
pose.x >= 0 && pose.x <= previous,
"Returning home never overshoots or oscillates",
);
previous = pose.x;
}
assert.ok(
Math.hypot(pose.x, pose.z, pose.yaw) < 0.0001,
"Position and orientation settle completely",
);
console.log(
"Yielding: gradual pivot, damped slide, no oscillation and complete restoration passed.",
);

View file

@ -36,6 +36,9 @@ try {
p.setDefaultTimeout(5000);
const errors = [];
p.on("pageerror", (e) => errors.push(e.message));
await p.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await p.goto(`http://127.0.0.1:${server.address().port}/`);
await p.evaluate(async (id) => {
window.progress = null;
@ -139,6 +142,7 @@ try {
const p = await browser.newPage({ viewport: { width, height: 1000 } });
const errors = [];
p.on("pageerror", (error) => errors.push(error.message));
await p.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await p.goto(`http://127.0.0.1:${server.address().port}/`);
const state = init(3, [], {}, "persian-switch");
state.players[0].name = "Draw";

View file

@ -0,0 +1,157 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as engine from "../engine/index.js";
import { tradeFrames } from "../viewer/trade-transition.js";
import { eventCells, journalRows } from "../viewer/journal.js";
import { goodsSlots } from "../viewer/goods-slots.js";
function lastExport() {
const s = engine.init(3, [], {}, "smooth-transitions");
s.phase = "actions";
s.actor = s.first = 0;
s.players.forEach((p) => {
p.character = null;
p.markers = Object.fromEntries(engine.ACTIONS.map((a) => [a, 0]));
});
s.players[0].markers.buy = 1;
s.players[0].money = 3;
s.players[0].boat = "1,0";
s.board["0,0"].goods = { kava: 0, copra: 0, beef: 1 };
s.demands[0] = {
id: 101,
goods: ["kava", "copra", "beef"],
filled: [true, true, false],
};
return s;
}
function exportLast(s) {
return engine.move(
s,
engine
.availableMoves(s)
.find(
(m) =>
m.type === "act" &&
m.action === "buy" &&
m.good === "beef" &&
!m.bonus,
),
0,
);
}
test("last export keeps the completed ship available for presentation after the next round starts", () => {
const before = lastExport(),
unchanged = structuredClone(before),
after = exportLast(before);
assert.equal(after.round, 2);
const events = after.events.slice(before.events.length),
frames = tradeFrames(before, after, events);
assert.deepEqual(frames.departing, [101]);
assert.deepEqual(frames.initial[0].filled, [true, true, false]);
assert.deepEqual(frames.delivered[0].filled, [true, true, true]);
assert.ok(!after.demands.some((d) => d.id === 101));
assert.deepEqual(
before,
unchanged,
"presentation never mutates the engine state",
);
assert.equal(
tradeFrames(before, after, []),
null,
"loading or replaying does not animate",
);
});
test("a Buyer delivering twice fills distinct slots in order", () => {
const before = {
demands: [{ id: 1, goods: ["kava", "kava"], filled: [false, false] }],
},
after = structuredClone(before);
const frame = tradeFrames(before, after, [
{
good: "kava",
details: { shipments: [{ ship: 1 }, { ship: 1, complete: true }] },
},
]);
assert.deepEqual(frame.delivered[0].filled, [true, true]);
assert.deepEqual(frame.completed, [1]);
});
test("only fully empty islands refill, and each refill is logged with exact goods", () => {
const s = lastExport();
s.board["2,1"] = engine.tileState("a1");
s.board["2,1"].goods = { kava: 1, copra: 0, beef: 0 };
const after = exportLast(s),
round = after.events.findLast((e) => e.type === "round");
assert.deepEqual(round.refills, [
{ cell: "0,0", goods: engine.TILES.efate.goods },
]);
assert.deepEqual(after.board["2,1"].goods, s.board["2,1"].goods);
const rows = journalRows(engine.stripSecret(after, 0)).filter(
(r) => r.event?.type === "restock",
);
assert.deepEqual(
rows.map((r) => [r.event.cell, r.event.goods]),
[["0,0", engine.TILES.efate.goods]],
);
});
test("older complete journals reconstruct refill locations without guessing from current stock", () => {
const s = engine.init(3, [], {}, "legacy-refill");
s.events = [
{ type: "start", round: 1, p: 0 },
...["kava", "copra", "beef"].map((good) => ({
type: "action",
action: "buy",
cell: "0,0",
p: 0,
round: 1,
good,
})),
{ type: "round", round: 2, first: 0 },
];
const before = structuredClone(s);
const rows = journalRows(s).filter((r) => r.event?.type === "restock");
assert.deepEqual(
rows.map((r) => r.event.cell),
["0,0"],
);
assert.deepEqual(rows[0].event.goods, engine.TILES.efate.goods);
assert.deepEqual(s, before);
const incomplete = { ...s, events: s.events.slice(1) };
assert.equal(
journalRows(incomplete).filter((r) => r.event?.type === "restock").length,
0,
);
});
test("journal highlights the actual route and affected tile, never malformed coordinates", () => {
assert.deepEqual(
eventCells({ path: ["1,0", "2,0"], details: { from: "0,0", cell: "2,0" } }),
["0,0", "1,0", "2,0"],
);
assert.deepEqual(eventCells({ type: "restock", cell: "-1,0" }), ["-1,0"]);
assert.deepEqual(eventCells({ cell: "<script>", details: { from: 1 } }), []);
assert.deepEqual(eventCells({ type: "plan" }), []);
});
test("goods positions remain fixed as cubes are bought and replenished", () => {
const t = engine.tileState("efate");
assert.deepEqual(
goodsSlots(t).map((s) => [s.good, s.filled]),
[
["kava", true],
["copra", true],
["beef", true],
],
);
t.goods.copra = 0;
assert.deepEqual(
goodsSlots(t).map((s) => [s.good, s.filled]),
[
["kava", true],
["copra", false],
["beef", true],
],
);
t.goods = { kava: 0, copra: 0, beef: 0 };
assert.ok(goodsSlots(t).every((s) => !s.filled));
t.submerged = true;
assert.deepEqual(goodsSlots(t), []);
});

View file

@ -43,6 +43,9 @@ try {
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
for (const locale of Object.keys(languages)) {
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`${base}/?lesson=beggar&locale=${locale}`);
const prose = page.locator(".bgs-tutorial-body > p").first();
for (const name of ["coin", "point", "draw", "build"])
@ -100,6 +103,9 @@ try {
[...saved],
);
for (const locale of ["en", "fr"]) {
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`${base}/?lesson=trade&locale=${locale}`);
const prose = page.locator(".bgs-tutorial-body > p").first();
await prose.locator(".icon-copra").waitFor();
@ -123,6 +129,9 @@ try {
.locator(".vanuatu-tutorial")
.screenshot({ path: `.local/qa/prose-export-${locale}.png` });
}
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`${base}/?new&hotseat&locale=fr`);
await page.locator('[data-character-choice="beggar"]').click();
const help = page.locator('dialog [data-character-help="beggar"]');

View file

@ -55,6 +55,9 @@ try {
game.players[0].markers.fish = 1;
game.board["1,0"] = E.tileState("startFish");
const state = E.stripSecret(game, 0);
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.evaluate((s) => {
window.fixture = s;

View file

@ -0,0 +1,31 @@
import test from "node:test";
import assert from "node:assert/strict";
import { releasePreferences } from "../scripts/release-preferences.mjs";
test("release replaces animation preference with a persistent view selector, preserving existing sound and shared options", () => {
const existing = [
{ name: "colorBlind", type: "checkbox", default: false },
{ name: "sound", type: "checkbox", default: false, label: "Sound" },
{ name: "animations", type: "checkbox", default: true },
];
const before = structuredClone(existing);
const next = releasePreferences(existing);
assert.deepEqual(next.slice(0, 2), existing.slice(0, 2));
assert.equal(
next.some((p) => p.name === "animations"),
false,
);
assert.equal(next.at(-1).default, "3d");
assert.deepEqual(
next.at(-1).items.map((p) => p.name),
["2d", "3d"],
);
assert.deepEqual(existing, before);
assert.deepEqual(releasePreferences(next), next);
});
test("a missing sound preference is added once", () => {
const next = releasePreferences([]);
assert.equal(next.find((p) => p.name === "sound").default, true);
assert.deepEqual(releasePreferences(next), next);
});

View file

@ -0,0 +1,96 @@
import assert from "node:assert/strict";
import { createSailingSound } from "../viewer/three/sailing-sound.js";
const sources = [],
gains = [];
const param = () => ({
value: 0.1,
setValueAtTime() {},
exponentialRampToValueAtTime() {},
cancelScheduledValues() {},
setTargetAtTime(value, time, constant) {
this.target = value;
this.timeConstant = constant;
},
});
const node = () => ({
connect(next) {
return next;
},
disconnect() {},
});
const context = {
state: "running",
currentTime: 0,
sampleRate: 100,
destination: {},
createBuffer: (_, n) => ({ getChannelData: () => new Float32Array(n) }),
createGain: () => {
const gain = param();
gains.push(gain);
return { ...node(), gain };
},
createBiquadFilter: () => ({ ...node(), frequency: {} }),
createBufferSource() {
const s = {
...node(),
start() {
this.started = true;
},
stop(time) {
this.stopped = time;
},
};
sources.push(s);
return s;
},
};
const sound = createSailingSound(() => context);
await sound.start();
assert.equal(sources.length, 2);
assert.ok(sources.every((s) => s.loop && s.started && s.stopped === undefined));
context.currentTime = 12;
assert.ok(
sources.every((s) => s.stopped === undefined),
"No fixed short duration: still playing after a long movement",
);
sound.setRemainingTime(0.3);
assert.ok(
gains[0].target > 0 && gains[0].target < 0.095,
"Volume drops progressively as the boat slows",
);
sound.setRemainingTime(0);
assert.ok(
gains[0].target > 0,
"The cue remains audible until the boat arrives",
);
sound.stop();
assert.ok(
sources.every((s) => s.stopped === 12.72),
"A soft water tail continues after arrival",
);
assert.ok(
gains.every((g) => g.timeConstant >= 0.15),
"The tail fades gently instead of cutting off in a few milliseconds",
);
await sound.start();
const recent = sources.slice(-2);
assert.ok(recent.every((s) => s.started && s.stopped === undefined));
sound.stop();
let resume;
const delayed = createSailingSound(() => ({
...context,
state: "suspended",
resume: () => new Promise((r) => (resume = r)),
}));
const attempt = delayed.start();
delayed.stop();
resume();
await attempt;
assert.equal(
sources.length,
4,
"A cancelled animation cannot start stale audio after unlock",
);
console.log(
"Sailing sound: continuous loop, approach fade, soft arrival tail and cancelled unlock passed.",
);

74
test/sand-drawing.test.js Normal file
View file

@ -0,0 +1,74 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as engine from "../engine/index.js";
import {
createSandDrawing,
setDrawingProgress,
newDrawingSlots,
} from "../viewer/three/sand-drawing.js";
test("sand groove draws progressively, then the tip settles", () => {
const drawing = createSandDrawing(0, 1),
full = drawing.groove.geometry.index.count;
assert.equal(drawing.groove.geometry.drawRange.count, full);
// The sand extrusion includes a .035 top bevel above its .225 surface.
assert.ok(
drawing.group.position.y - 0.01 > 0.26,
"groove stays above the beach bevel",
);
for (const progress of [0, 0.2, 0.5, 0.88, 1]) {
setDrawingProgress(drawing, progress);
assert.ok(drawing.groove.geometry.drawRange.count <= full);
assert.equal(
drawing.rim.geometry.drawRange.count,
drawing.groove.geometry.drawRange.count,
);
assert.equal(drawing.tip.visible, progress > 0 && progress < 1);
if (progress === 0)
assert.equal(drawing.groove.geometry.drawRange.count, 0);
else if (progress < 0.88)
assert.ok(
drawing.groove.geometry.drawRange.count > 0 &&
drawing.groove.geometry.drawRange.count < full,
);
else assert.equal(drawing.groove.geometry.drawRange.count, full);
}
});
test("all three drawings have stable separate places on the beach", () => {
const drawings = Array.from({ length: 3 }, (_, i) => createSandDrawing(i, 3));
assert.deepEqual(
drawings.map((d) => d.group.position.x),
[-0.43, 0, 0.43],
);
for (let i = 0; i < 2; i++)
assert.ok(
drawings[i + 1].group.position.x - drawings[i].group.position.x >
0.34 + 0.034,
);
});
test("a real draw move animates only its newly added drawing, never a reload", () => {
let before = engine.init(3, [], {}, "drawing-check"),
move;
for (let i = 0; i < 100 && !move; i++) {
move = engine
.availableMoves(before)
.find((m) => m.type === "act" && m.action === "draw");
if (!move) before = engine.moveAI(before, before.actor);
}
assert.ok(move, "fixture reaches a legal draw");
const after = engine.move(before, move, before.actor);
const events = after.events.slice(before.events.length);
assert.deepEqual(newDrawingSlots(events, before, after), [
{ cell: move.cell, slot: before.board[move.cell].drawings },
]);
assert.deepEqual(newDrawingSlots([], before, after), []);
assert.deepEqual(newDrawingSlots(events, after, after), []);
assert.deepEqual(newDrawingSlots(events, null, after), []);
assert.deepEqual(
newDrawingSlots(
[{ type: "action", action: "draw", cell: "x" }],
{ board: { x: { drawings: 2 } } },
{ board: { x: { drawings: 3 } } },
),
[{ cell: "x", slot: 2 }],
);
});

View file

@ -0,0 +1,82 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { serveViewerCheck } from "./three-viewer-fixture.mjs";
const { server, base } = await serveViewerCheck();
const browser = await chromium.launch();
try {
for (const width of [390, 1440]) {
const page = await browser.newPage({ viewport: { width, height: 1000 } }),
errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(base + "/qa/hosted.html");
await page.locator(".map-3d canvas").waitFor();
const state = () => page.locator("#status").textContent().then(JSON.parse);
assert.equal(
(await state()).updates.length,
0,
"Receiving preferences never echoes them",
);
await page.locator('[data-map-view="2d"]').click();
assert.equal(
await page.locator(".vanuatu").getAttribute("data-map-view"),
"2d",
);
assert.deepEqual((await state()).updates.at(-1), {
name: "mapView",
value: "2d",
});
assert.equal(
await page.locator(".goods-slot.empty").first().getAttribute("opacity"),
"0.55",
);
await page.locator("[data-help]").first().click();
assert.equal(await page.locator('[data-pref="animations"]').count(), 0);
await page.locator("[data-map-preference]").selectOption("3d");
assert.deepEqual((await state()).updates.at(-1), {
name: "mapView",
value: "3d",
});
await page.locator('[data-pref="sound"]').check();
assert.deepEqual((await state()).updates.at(-1), {
name: "sound",
value: true,
});
await page.locator("dialog [data-close]").click();
const count = (await state()).updates.length;
await page.locator("[data-remote]").click();
assert.equal(
await page.locator(".vanuatu").getAttribute("data-map-view"),
"2d",
);
assert.equal((await state()).updates.length, count);
await page.goto(base + "/qa/hosted.html?saved");
assert.equal((await state()).preferences.mapView, "3d");
await page.locator(".map-3d canvas").waitFor();
await page.locator("[data-export]").click();
await page.locator("[data-trade-transition]").waitFor();
await page.waitForFunction(
() => !document.querySelector("[data-trade-transition]"),
);
assert.equal((await state()).round, 2);
assert.equal(await page.locator(".goods-slot.empty").count(), 0);
await page.emulateMedia({ reducedMotion: "reduce" });
await page.waitForFunction(
() => document.querySelector(".vanuatu").dataset.animations === "false",
);
assert.deepEqual(errors, []);
await page.close();
}
const page = await browser.newPage();
await page.goto(base + "/qa/hosted.html?no-webgl");
await page.waitForFunction(
() => document.querySelector(".vanuatu")?.dataset.mapView === "2d",
);
assert.equal(await page.locator('[data-map-view="3d"]').isDisabled(), true);
await page.close();
console.log(
"Hosted 2D/3D persistence, remote changes, sound, refill transitions, reduced motion and WebGL fallback passed.",
);
} finally {
await browser.close();
server.close();
}

View file

@ -0,0 +1,52 @@
import { build } from "esbuild";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { resolve, extname } from "node:path";
export async function serveViewerCheck({ port = 0, published } = {}) {
await mkdir(".local/qa", { recursive: true });
await build({
entryPoints: ["test/three-viewer-harness.js"],
bundle: true,
format: "esm",
outfile: ".local/qa/hosted-check.js",
});
const script = published?.viewer.url ?? "/viewer.js",
style = published?.viewer.dependencies.stylesheets[0] ?? "/viewer.css";
const html = `<!doctype html><html lang="fr"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vanuatu release checks</title><link rel="stylesheet" href="${style}"><style>body{margin:0}#qa{padding:8px;background:#faf5e1}#status{display:block;white-space:pre-wrap;font-size:11px}#game{min-height:90vh}</style><div id="qa"><button data-reset>Reset fixture</button><button data-export>Last export</button><button data-remote>Remote view preference</button><button data-german>Deutsch</button><button data-place>Place next tile</button><output id="status"></output></div><div id="game"></div><script src="${script}"></script><script type="module" src="/qa/hosted-check.js"></script></html>`;
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://local");
if (url.pathname === "/qa/hosted.html") {
res.setHeader("Content-Type", "text/html");
return res.end(html);
}
const base = resolve(
url.pathname.startsWith("/qa/") ? ".local/qa" : "dist",
);
const name = url.pathname.startsWith("/qa/")
? url.pathname.slice(3)
: url.pathname === "/"
? "/index.html"
: url.pathname;
const file = resolve(base, "." + name);
if (!file.startsWith(base + "/")) throw Error("Invalid path");
res.setHeader(
"Content-Type",
{
".js": "text/javascript",
".css": "text/css",
".html": "text/html",
".json": "application/json",
".webp": "image/webp",
}[extname(file)] ?? "application/octet-stream",
);
res.setHeader("Cache-Control", "no-store");
res.end(await readFile(file));
} catch {
res.writeHead(404);
res.end("Not found");
}
});
await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));
return { server, base: `http://127.0.0.1:${server.address().port}` };
}

View file

@ -0,0 +1,106 @@
import * as engine from "../engine/index.js";
let host,
state,
preferences = { locale: "fr", sound: false, mapView: "3d" },
updates = [];
const root = document.querySelector("#game"),
status = document.querySelector("#status");
const params = new URLSearchParams(location.search);
if (params.has("saved"))
preferences =
JSON.parse(localStorage.getItem("qa-bgs-preferences")) ?? preferences;
function fixture() {
const s = engine.init(3, [], {}, "hosted-3d-release");
s.phase = "actions";
s.actor = s.first = 0;
s.players.forEach((p) => {
p.character = null;
p.markers = Object.fromEntries(engine.ACTIONS.map((a) => [a, 0]));
});
s.players[0].markers.buy = 1;
s.players[0].money = 3;
s.players[0].boat = "1,0";
s.board["0,0"].goods = { kava: 0, copra: 0, beef: 1 };
s.demands[0] = {
id: 101,
goods: ["kava", "copra", "beef"],
filled: [true, true, false],
};
return s;
}
function report() {
status.textContent = JSON.stringify({
preferences,
updates,
round: state.round,
phase: state.phase,
});
}
function show() {
host.emit("state", engine.stripSecret(state, 0));
report();
}
function launch() {
host = window.vanuatu.launch("#game");
host.on("update:preference", (value) => {
updates.push(value);
preferences = { ...preferences, [value.name]: value.value };
localStorage.setItem("qa-bgs-preferences", JSON.stringify(preferences));
host.emit("preferences", preferences);
report();
});
host.on("move", (move) => {
state = engine.move(state, move, 0);
show();
});
host.emit("player", { index: 0 });
host.emit("preferences", preferences);
show();
}
document.querySelector("[data-reset]").onclick = () => {
state = fixture();
show();
};
document.querySelector("[data-export]").onclick = () => {
const move = engine
.availableMoves(state)
.find(
(m) =>
m.type === "act" && m.action === "buy" && m.good === "beef" && !m.bonus,
);
if (move) {
state = engine.move(state, move, 0);
show();
}
};
document.querySelector("[data-remote]").onclick = () => {
preferences = {
...preferences,
mapView: preferences.mapView === "3d" ? "2d" : "3d",
};
host.emit("preferences", preferences);
report();
};
document.querySelector("[data-german]").onclick = () => {
preferences = { ...preferences, locale: "de" };
host.emit("preferences", preferences);
report();
};
document.querySelector("[data-place]").onclick = () => {
const move = engine.availableMoves(state).find((m) => m.type === "place");
if (move) {
state = engine.move(state, move, state.actor);
show();
}
};
if (params.has("no-webgl")) {
const getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function (kind, ...args) {
return kind.startsWith("webgl")
? null
: getContext.call(this, kind, ...args);
};
}
state = fixture();
launch();

View file

@ -35,6 +35,9 @@ try {
errors.push(e.message);
console.error(e.message);
});
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.evaluate(async () => {
window.progress = null;
@ -113,6 +116,9 @@ try {
["nl", "Varen", "Als je bij geen enkele actie de meerderheid hebt"],
]) {
const page = await browser.newPage();
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.evaluate(async (locale) => {
await window.vanuatu.launchTutorial("#game", {
@ -168,6 +174,9 @@ try {
});
}, locale);
};
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await launch();
assert.equal(await page.locator(".fish-price b").innerText(), "3");
@ -246,6 +255,9 @@ try {
const page = await browser.newPage({
viewport: { width: 1440, height: 1000 },
});
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`http://127.0.0.1:${server.address().port}/`);
await page.evaluate(
async (entries) => {

View file

@ -41,6 +41,9 @@ try {
const page = await browser.newPage({ viewport: { width, height: 844 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await page.goto(`${base}/?lesson=full-round&locale=${locale}`);
const guide = page.locator(".vanuatu-tutorial");
const instruction = guide.locator(".bgs-tutorial-body > p").first();

View file

@ -36,6 +36,9 @@ try {
p.setDefaultTimeout(5000);
const errors = [];
p.on("pageerror", (e) => errors.push(e.message));
await p.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await p.goto(`http://127.0.0.1:${server.address().port}/`);
await p.evaluate(async (id) => {
window.progress = null;

View file

@ -37,6 +37,7 @@ const browser = await chromium.launch({
const errors = [];
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await page.goto(`http://127.0.0.1:${server.address().port}/?new&hotseat`);
await page.waitForSelector("[data-character-choice]");

View file

@ -36,6 +36,9 @@ try {
p.setDefaultTimeout(5000);
const errors = [];
p.on("pageerror", (e) => errors.push(e.message));
await p.addInitScript(() =>
localStorage.setItem("vanuatu-map-view", "2d"),
);
await p.goto(`http://127.0.0.1:${server.address().port}/`);
await p.evaluate(async (id) => {
window.progress = null;
@ -139,6 +142,7 @@ try {
const p = await browser.newPage({ viewport: { width, height: 1000 } });
const errors = [];
p.on("pageerror", (error) => errors.push(error.message));
await p.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d"));
await p.goto(`http://127.0.0.1:${server.address().port}/`);
const state = init(3, [], {}, "zh-cn-switch");
state.players[0].name = "Draw";

View file

@ -12,11 +12,18 @@ import {
esc,
} from "./art.js";
import { translator } from "./labels.js";
import { journalRows } from "./journal.js";
import { journalRows, eventCells } from "./journal.js";
import { ACTIONS, CHARACTERS, COLORS } from "../engine/catalog.js";
export function mountActivity(
target,
{ chat, openPlayer, avatarForPlayer, onBack, language = "en" } = {},
{
chat,
openPlayer,
avatarForPlayer,
onBack,
onHighlight,
language = "en",
} = {},
) {
let colorBlind = false,
lang = language;
@ -166,6 +173,17 @@ export function mountActivity(
function eventHtml(e) {
const d = e.details ?? {};
switch (e.type) {
case "restock":
return (
heading(e, text("Goods replenished"), "buy") +
details(
Object.entries(e.goods)
.filter(([, n]) => n > 0)
.map(([good, n]) => gain(good, n))
.join(""),
) +
location(e.cell)
);
case "touristDraw":
return (
heading(e, text("Tourist tile")) +
@ -367,8 +385,12 @@ export function mountActivity(
return `<li class="phase-divider">${symbol ? icon(symbol) : ""}<b>${text(label)}</b>${row.pass ? `<span>${row.pass}/3</span>` : ""}</li>`;
}
const html = eventHtml(row.event);
const cells = eventCells(row.event);
const button = cells.length
? `<button type="button" class="journal-location" data-journal-cells="${esc(cells.join(" "))}" aria-pressed="false" title="${esc(t("board"))}">${html}<span class="journal-locate" aria-hidden="true">${icon("overview")}</span></button>`
: html;
return html
? `<li class="journal-event event-${esc(row.event.type === "character" ? "select-character" : row.event.type)}">${html}</li>`
? `<li class="journal-event event-${esc(row.event.type === "character" ? "select-character" : row.event.type)}">${button}</li>`
: "";
}
function refresh() {
@ -395,6 +417,83 @@ export function mountActivity(
if (following) list.scrollTop = list.scrollHeight;
});
}
const interactions = new AbortController(),
listener = { signal: interactions.signal };
let pinned, hovered, focused;
function highlight() {
const row = hovered ?? focused ?? pinned;
for (const button of list.querySelectorAll("[data-journal-cells]")) {
button.classList.toggle("inspected", button === row);
button.setAttribute("aria-pressed", String(button === pinned));
}
onHighlight?.(row?.dataset.journalCells.split(" ") ?? []);
}
function clearHighlight() {
pinned = hovered = focused = null;
highlight();
}
list.addEventListener(
"pointerover",
(e) => {
if (e.pointerType === "touch") return;
const row = e.target.closest("[data-journal-cells]");
if (row !== hovered) {
hovered = row;
highlight();
}
},
listener,
);
list.addEventListener(
"pointerleave",
() => {
hovered = null;
highlight();
},
listener,
);
list.addEventListener(
"focusin",
(e) => {
focused = e.target.closest("[data-journal-cells]");
highlight();
},
listener,
);
list.addEventListener(
"focusout",
() => {
focused = null;
highlight();
},
listener,
);
list.addEventListener(
"click",
(e) => {
const row = e.target.closest("[data-journal-cells]");
if (!row) return;
pinned = pinned === row ? null : row;
hovered = focused = null;
highlight();
if (pinned) onBack?.();
},
listener,
);
document.addEventListener(
"pointerdown",
(e) => {
if (pinned && !e.target.closest("[data-journal-cells]")) clearHighlight();
},
listener,
);
document.addEventListener(
"keydown",
(e) => {
if (e.key === "Escape") clearHighlight();
},
listener,
);
root.addEventListener("click", (e) => {
const b = e.target.closest("button");
if (!b) return;
@ -410,6 +509,7 @@ export function mountActivity(
open,
update(s, isAnalysis, isColorBlind = false) {
colorBlind = isColorBlind;
if (state && s.historyLength < state.historyLength) clearHighlight();
state = s;
const changed = analysis !== isAnalysis;
analysis = isAnalysis;
@ -443,6 +543,7 @@ export function mountActivity(
refresh();
},
destroy() {
interactions.abort();
cancelAnimationFrame(followFrame);
wide.removeEventListener("change", resize);
view?.destroy();

View file

@ -1,3 +1,4 @@
import { goodsSlots } from "./goods-slots.js";
import { playerSymbolGlyph } from "@boardgamers/protocol/player-symbols";
import { boardCells, tileState, TILES, COLORS } from "../engine/catalog.js";
import { esc, svgIcon, iconLabel } from "./art.js";
@ -143,22 +144,16 @@ export function boardSvg(
})),
);
} else {
const goods = Object.entries(tile.goods).filter(([, n]) => n > 0);
const slots = goodsSlots(tile);
svg += '<g class="island-goods">';
let j = 0;
for (const [good, n] of goods)
for (let k = 0; k < n; k++, j++)
svg += svgIcon(
good,
c.x -
goods.reduce((sum, [, count]) => sum + count, 0) * 14 +
j * 28,
c.y + 34,
29,
"currentColor",
`${label(good)} · ${"available to export"}`,
colorBlind,
);
for (const [j, { good, filled }] of slots.entries()) {
const x = c.x - slots.length * 14 + j * 28,
y = c.y + 34;
const help = `${label(good)} · ${filled ? "available to export" : "Empty goods space"}`;
svg += `<g class="goods-slot ${filled ? "stocked" : "empty"}" data-good="${good}" opacity="${filled ? 1 : 0.55}"><title>${esc(help)}</title>`;
svg += svgIcon(good, x, y, 29, "currentColor", help, colorBlind);
svg += "</g>";
}
svg += "</g>";
const huts = tile.huts;
for (let i = 0; i < spec.huts; i++) {

32
viewer/effects.js vendored
View file

@ -80,11 +80,17 @@ export function createEffects(root, { icon, sound, center }) {
root.append(layer);
const animations = new Set();
let frame = 0,
enabled = true;
enabled = true,
ready = Promise.resolve(),
resolveReady;
const allowed = () => enabled && !motion.matches && !doc.hidden;
const query = (selector) => root.querySelector(selector);
const point = (element) => {
if (!element) return null;
if (
!element ||
(root.dataset.mapView === "3d" && element.closest(".map-scroll"))
)
return null;
const r = element.getBoundingClientRect();
if (
!r.width ||
@ -121,6 +127,8 @@ export function createEffects(root, { icon, sound, center }) {
for (const animation of animations) animation.cancel();
animations.clear();
layer.replaceChildren();
resolveReady?.();
resolveReady = null;
}
function animate(
node,
@ -142,6 +150,10 @@ export function createEffects(root, { icon, sound, center }) {
const finish = () => {
animations.delete(animation);
if (remove) node.remove();
if (!animations.size && !frame) {
resolveReady?.();
resolveReady = null;
}
};
animation.onfinish = () => {
animation.cancel();
@ -237,16 +249,22 @@ export function createEffects(root, { icon, sound, center }) {
cancel();
if (doc.hidden) return;
const cue = soundFor(events);
if (cue) void sound.play(cue);
if (cue && !(cue === "sail" && root.dataset.mapView === "3d"))
void sound.play(cue);
if (!allowed()) return;
// Pending controls and dialog closure can render again in the same turn.
// Position effects once, after that work, without a per-frame layout loop.
ready = new Promise((resolve) => (resolveReady = resolve));
frame = view.requestAnimationFrame(() => {
frame = 0;
if (!allowed()) return;
for (const event of events) {
const p = event.p;
const d = event.details ?? {};
if (event.type === "place" && root.dataset.mapView !== "3d") {
const placed = query(`.map-cell[data-cell="${event.cell}"]`);
if (placed) animate(placed, [{ opacity: 0 }, { opacity: 1 }], 650);
}
if (["plan", "neutral"].includes(event.type)) {
for (const action of new Set(event.actions))
drop(
@ -316,7 +334,6 @@ export function createEffects(root, { icon, sound, center }) {
for (const shipment of d.shipments ?? []) {
const ship = query(`[data-ship="${shipment.ship}"]`);
fly(icon(event.good), source, point(ship));
if (shipment.complete) pulse(ship);
}
const changes = rewards(event);
if (changes.length)
@ -328,7 +345,7 @@ export function createEffects(root, { icon, sound, center }) {
`<span>${value > 0 ? "+" : "−"}${Math.abs(value)}${icon(name)}</span>`,
)
.join(""),
event.action === "sail" ? 500 : 130,
["sail", "buy"].includes(event.action) ? 500 : 130,
);
if (event.type === "conversion")
gain(
@ -357,6 +374,10 @@ export function createEffects(root, { icon, sound, center }) {
)
pulse(query(`[data-action="${action}"]`));
}
if (!animations.size) {
resolveReady?.();
resolveReady = null;
}
});
}
// Cancel overlays on scrolling instead of tracking layout on every frame.
@ -377,6 +398,7 @@ export function createEffects(root, { icon, sound, center }) {
motion.addEventListener("change", cancel);
return {
capture,
whenIdle: () => ready,
show,
cancel,
drop,

11
viewer/goods-slots.js Normal file
View file

@ -0,0 +1,11 @@
import { TILES } from "../engine/catalog.js";
// The original assortment defines stable positions, including bought cubes.
export function goodsSlots(tile) {
if (tile.type !== "island" || tile.submerged) return [];
return Object.entries(TILES[tile.id].goods).flatMap(([good, count]) =>
Array.from({ length: count }, (_, i) => ({
good,
filled: i < (tile.goods[good] ?? 0),
})),
);
}

View file

@ -7,6 +7,17 @@ const total = (values) => values.reduce((a, b) => a + b, 0);
// Old saves contain the moves, but not their outcomes. Reconstruct only public,
// deterministic information. In particular, never guess old trade-ship bonuses
// or use today's character, fish price or board contents for an earlier action.
export function eventCells(event) {
const d = event.details ?? {};
return [
...new Set(
[d.from, ...(event.path ?? []), d.cell, event.cell].filter(
(cell) => typeof cell === "string" && /^-?\d+,-?\d+$/.test(cell),
),
),
];
}
export function journalRows(state) {
const events = state.events ?? state.lastEvents ?? [];
const completeHistory = events[0]?.type === "start";
@ -52,6 +63,36 @@ export function journalRows(state) {
tourists: e.tourists,
},
});
if (e.type === "round") {
const refills =
e.refills ??
(completeHistory
? Object.entries(board)
.filter(
([, tile]) =>
tile.type === "island" &&
!tile.submerged &&
Object.values(tile.goods).every((n) => n === 0),
)
.map(([cell, tile]) => ({
cell,
goods: { ...tileState(tile.id).goods },
}))
: []);
for (const refill of refills) {
if (board[refill.cell])
board[refill.cell].goods = { ...refill.goods };
rows.push({
kind: "event",
event: {
type: "restock",
round: e.round,
cell: refill.cell,
goods: refill.goods,
},
});
}
}
continue;
}
const player = players[e.p];
@ -108,6 +149,7 @@ export function journalRows(state) {
fallback.income = total(e.fish) * context.market;
}
}
if (e.action === "sell" && completeHistory) fallback.cell = player.boat;
e.details = { ...fallback, ...e.details };
const tile = board[e.cell ?? player.boat];
if (e.action === "sail") player.boat = e.path.at(-1);
@ -118,6 +160,8 @@ export function journalRows(state) {
if (e.action === "explore") tile.treasure--;
if (e.action === "build" && e.hut) tile.huts.push(e.p);
if (e.action === "draw") tile.drawings++;
if (e.action === "buy")
tile.goods[e.good] = Math.max(0, (tile.goods[e.good] ?? 0) - 1);
}
player.markers[e.action] = 0;
}
@ -131,6 +175,8 @@ export function journalRows(state) {
player.markers[e.from] = 0;
}
if (e.type === "submerged" && board[e.cell]) {
board[e.cell].submerged = true;
board[e.cell].goods = {};
board[e.cell].huts = [];
board[e.cell].drawings = 0;
}

View file

@ -24,3 +24,6 @@ export const EXTEND_RULE =
export const EXPORT_RULE =
"The coloured cubes on islands are goods. Buy one beside your boat and send it straight to the first ship that needs it. Pay vatus; gain prosperity. No hut or cargo space is needed.";
export const REFILL_RULE =
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.";

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Vent på din tur.",
"Choose an action to take back its markers without acting.": "Vælg en handling, hvis markører du tager tilbage uden at handle.",
"Undo my move": "Fortryd mit træk",
"Automatically retrieve markers when there is no choice": "Tag automatisk markører tilbage, når der ikke er noget valg"
"Automatically retrieve markers when there is no choice": "Tag automatisk markører tilbage, når der ikke er noget valg",
"Goods replenished": "Varer genopfyldt",
"Empty goods space": "Tom vareplads",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Ved begyndelsen af hver runde udskiftes fyldte skibe. En ø uden varer får sit oprindelige udvalg igen. Hvis blot én terning er tilbage, genopfyldes intet."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Warte, bis du am Zug bist.",
"Choose an action to take back its markers without acting.": "Wähle eine Aktion, deren Marker du ohne Aktion zurücknimmst.",
"Undo my move": "Zug zurücknehmen",
"Automatically retrieve markers when there is no choice": "Marker automatisch zurücknehmen, wenn es keine Wahl gibt"
"Automatically retrieve markers when there is no choice": "Marker automatisch zurücknehmen, wenn es keine Wahl gibt",
"Goods replenished": "Waren aufgefüllt",
"Empty goods space": "Leerer Warenplatz",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Zu Beginn jeder Runde werden volle Schiffe ersetzt. Eine Insel ohne Waren erhält ihren ursprünglichen Warenbestand zurück. Solange auch nur ein Würfel übrig ist, wird nichts aufgefüllt."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Περιμένετε τη σειρά σας.",
"Choose an action to take back its markers without acting.": "Επίλεξε μια ενέργεια για να πάρεις πίσω τους δείκτες της χωρίς να την εκτελέσεις.",
"Undo my move": "Αναίρεση κίνησης",
"Automatically retrieve markers when there is no choice": "Αυτόματη ανάκτηση δεικτών όταν δεν υπάρχει επιλογή"
"Automatically retrieve markers when there is no choice": "Αυτόματη ανάκτηση δεικτών όταν δεν υπάρχει επιλογή",
"Goods replenished": "Αναπλήρωση αγαθών",
"Empty goods space": "Κενή θέση αγαθού",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Στην αρχή κάθε γύρου, τα γεμάτα πλοία αντικαθίστανται. Ένα νησί χωρίς κανένα αγαθό λαμβάνει ξανά την αρχική του συλλογή. Αν απομένει έστω ένας κύβος, δεν αναπληρώνεται τίποτα."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Wait for your turn.",
"Choose an action to take back its markers without acting.": "Choose an action to take back its markers without acting.",
"Undo my move": "Undo my move",
"Automatically retrieve markers when there is no choice": "Automatically retrieve markers when there is no choice"
"Automatically retrieve markers when there is no choice": "Automatically retrieve markers when there is no choice",
"Goods replenished": "Goods replenished",
"Empty goods space": "Empty goods space",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "منتظر نوبت خود باشید.",
"Choose an action to take back its markers without acting.": "اقدامی را انتخاب کنید تا مهره‌هایش را بدون انجام آن پس بگیرید.",
"Undo my move": "بازگرداندن حرکت",
"Automatically retrieve markers when there is no choice": "پس‌گرفتن خودکار نشانگرها وقتی انتخابی وجود ندارد"
"Automatically retrieve markers when there is no choice": "پس‌گرفتن خودکار نشانگرها وقتی انتخابی وجود ندارد",
"Goods replenished": "کالاها دوباره تأمین شدند",
"Empty goods space": "جای خالی کالا",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "در آغاز هر دور، کشتی‌های تکمیل‌شده جایگزین می‌شوند. جزیره‌ای که هیچ کالایی در آن نمانده، دوباره مجموعهٔ اولیهٔ کالاهایش را دریافت می‌کند. اگر حتی یک مکعب باقی مانده باشد، هیچ کالایی اضافه نمی‌شود."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Attendez votre tour.",
"Choose an action to take back its markers without acting.": "Choisissez une action dont vous reprenez les marqueurs sans agir.",
"Undo my move": "Annuler mon coup",
"Automatically retrieve markers when there is no choice": "Reprendre automatiquement les marqueurs lorsqu'il n'y a pas de choix"
"Automatically retrieve markers when there is no choice": "Reprendre automatiquement les marqueurs lorsqu'il n'y a pas de choix",
"Goods replenished": "Marchandises réapprovisionnées",
"Empty goods space": "Emplacement de marchandise vide",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Au début de chaque manche, les navires complets sont remplacés. Une île sans aucune marchandise retrouve son assortiment initial. S’il reste ne serait-ce qu’un cube, rien n’est réapprovisionné."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "अपनी बारी का इंतज़ार करें।",
"Choose an action to take back its markers without acting.": "एक कार्रवाई चुनें जिसके मार्कर आप बिना कार्रवाई किए वापस लेंगे।",
"Undo my move": "अपनी चाल वापस लें",
"Automatically retrieve markers when there is no choice": "कोई विकल्प न होने पर मार्कर अपने-आप वापस लें"
"Automatically retrieve markers when there is no choice": "कोई विकल्प न होने पर मार्कर अपने-आप वापस लें",
"Goods replenished": "माल फिर भरा गया",
"Empty goods space": "माल की खाली जगह",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "हर दौर की शुरुआत में भरे हुए जहाज़ बदल दिए जाते हैं। जिस द्वीप पर कोई माल नहीं बचा है, वहाँ शुरुआती माल फिर रख दिया जाता है। अगर एक भी घन बचा हो, तो कोई माल नहीं भरा जाता।"
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Attendi il tuo turno.",
"Choose an action to take back its markers without acting.": "Scegli un’azione di cui riprendere i segnalini senza agire.",
"Undo my move": "Annulla la mossa",
"Automatically retrieve markers when there is no choice": "Ritirare automaticamente i segnalini quando non c'è scelta"
"Automatically retrieve markers when there is no choice": "Ritirare automaticamente i segnalini quando non c'è scelta",
"Goods replenished": "Merci rifornite",
"Empty goods space": "Spazio merce vuoto",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "All’inizio di ogni round, le navi complete vengono sostituite. Un’isola senza più merci riceve nuovamente il suo assortimento iniziale. Se rimane anche un solo cubetto, non viene rifornito nulla."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "차례를 기다리세요.",
"Choose an action to take back its markers without acting.": "행동하지 않고 마커를 회수할 행동을 선택하세요.",
"Undo my move": "내 수 되돌리기",
"Automatically retrieve markers when there is no choice": "선택의 여지가 없을 때 마커 자동 회수"
"Automatically retrieve markers when there is no choice": "선택의 여지가 없을 때 마커 자동 회수",
"Goods replenished": "상품 보충",
"Empty goods space": "빈 상품 자리",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "매 라운드 시작 시 가득 찬 배를 교체합니다. 상품이 하나도 남지 않은 섬은 처음의 상품 구성을 다시 받습니다. 큐브가 하나라도 남아 있으면 보충하지 않습니다."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Wacht op je beurt.",
"Choose an action to take back its markers without acting.": "Kies een actie waarvan je de markers zonder actie terugneemt.",
"Undo my move": "Zet ongedaan maken",
"Automatically retrieve markers when there is no choice": "Markeringen automatisch terugnemen als er geen keuze is"
"Automatically retrieve markers when there is no choice": "Markeringen automatisch terugnemen als er geen keuze is",
"Goods replenished": "Goederen aangevuld",
"Empty goods space": "Lege goederenplek",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Aan het begin van elke ronde worden volle schepen vervangen. Een eiland zonder goederen krijgt zijn oorspronkelijke assortiment terug. Als er ook maar één blokje over is, wordt niets aangevuld."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Poczekaj na swoją turę.",
"Choose an action to take back its markers without acting.": "Wybierz akcję, z której zabierasz znaczniki bez jej wykonywania.",
"Undo my move": "Cofnij ruch",
"Automatically retrieve markers when there is no choice": "Automatycznie zabieraj znaczniki, gdy nie ma wyboru"
"Automatically retrieve markers when there is no choice": "Automatycznie zabieraj znaczniki, gdy nie ma wyboru",
"Goods replenished": "Uzupełniono towary",
"Empty goods space": "Puste miejsce na towar",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Na początku każdej rundy pełne statki są zastępowane nowymi. Wyspa, na której nie ma już żadnych towarów, odzyskuje swój początkowy zestaw. Jeśli pozostała choć jedna kostka, niczego się nie uzupełnia."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Aguarde sua vez.",
"Choose an action to take back its markers without acting.": "Escolha uma ação para recolher os marcadores dela sem agir.",
"Undo my move": "Desfazer jogada",
"Automatically retrieve markers when there is no choice": "Recolher marcadores automaticamente quando não há escolha"
"Automatically retrieve markers when there is no choice": "Recolher marcadores automaticamente quando não há escolha",
"Goods replenished": "Mercadorias reabastecidas",
"Empty goods space": "Espaço vazio de mercadoria",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "No início de cada rodada, os navios completos são substituídos. Uma ilha sem nenhuma mercadoria recebe novamente seu conjunto original. Se restar um único cubo, nada é reabastecido."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Așteaptă-ți rândul.",
"Choose an action to take back its markers without acting.": "Alege o acțiune ale cărei marcaje le retragi fără a acționa.",
"Undo my move": "Anulează mutarea",
"Automatically retrieve markers when there is no choice": "Retrage automat marcatorii când nu există altă opțiune"
"Automatically retrieve markers when there is no choice": "Retrage automat marcatorii când nu există altă opțiune",
"Goods replenished": "Mărfuri reaprovizionate",
"Empty goods space": "Loc gol pentru marfă",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "La începutul fiecărei runde, navele complete sunt înlocuite. O insulă fără nicio marfă primește din nou sortimentul inițial. Dacă a rămas chiar și un singur cub, nu se reaprovizionează nimic."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Дождитесь своего хода.",
"Choose an action to take back its markers without acting.": "Выберите действие, маркеры которого вы заберёте без выполнения действия.",
"Undo my move": "Отменить ход",
"Automatically retrieve markers when there is no choice": "Автоматически забирать маркеры, когда нет выбора"
"Automatically retrieve markers when there is no choice": "Автоматически забирать маркеры, когда нет выбора",
"Goods replenished": "Товары пополнены",
"Empty goods space": "Пустое место для товара",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "В начале каждого раунда заполненные корабли заменяются. Остров, на котором не осталось товаров, снова получает исходный набор. Если остался хотя бы один кубик, товары не пополняются."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "Hãy chờ đến lượt bạn.",
"Choose an action to take back its markers without acting.": "Chọn một hành động để thu hồi dấu của nó mà không thực hiện hành động.",
"Undo my move": "Hoàn tác nước đi",
"Automatically retrieve markers when there is no choice": "Tự động thu hồi dấu khi không có lựa chọn"
"Automatically retrieve markers when there is no choice": "Tự động thu hồi dấu khi không có lựa chọn",
"Goods replenished": "Đã bổ sung hàng hóa",
"Empty goods space": "Ô hàng hóa trống",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Ở đầu mỗi vòng, các tàu đã đầy được thay thế. Một đảo không còn hàng hóa nào sẽ được bổ sung lại đúng loại và số lượng ban đầu. Nếu vẫn còn dù chỉ một khối, sẽ không bổ sung gì."
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "请等待你的回合。",
"Choose an action to take back its markers without acting.": "选择一个行动,收回其标记而不执行。",
"Undo my move": "撤销我的行动",
"Automatically retrieve markers when there is no choice": "没有选择时自动收回标记"
"Automatically retrieve markers when there is no choice": "没有选择时自动收回标记",
"Goods replenished": "货物已补充",
"Empty goods space": "空货物格",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "每轮开始时,已装满的船会被替换。完全没有货物的岛屿会重新补上原本的货物组合。只要还剩一颗方块,就不会补充任何货物。"
}

View file

@ -948,5 +948,8 @@
"Wait for your turn.": "請等待輪到你。",
"Choose an action to take back its markers without acting.": "選擇一個行動,收回其標記但不執行行動。",
"Undo my move": "撤回我的行動",
"Automatically retrieve markers when there is no choice": "無其他選擇時自動收回標記"
"Automatically retrieve markers when there is no choice": "無其他選擇時自動收回標記",
"Goods replenished": "貨物已補充",
"Empty goods space": "空貨物格",
"At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "每輪開始時,已裝滿的船會被替換。完全沒有貨物的島嶼會重新補上原本的貨物組合。只要還剩一顆方塊,就不會補充任何貨物。"
}

View file

@ -17,6 +17,32 @@ export function mountMapZoom(root) {
autoFit = true,
suppressClick = false;
const events = new AbortController();
const motion = matchMedia("(prefers-reduced-motion: reduce)");
let enabled = true,
flight,
ready = Promise.resolve(),
resolveReady;
function settle() {
flight?.cancel();
flight = null;
const map = elements()?.map;
if (map) delete map.dataset.mapTransition;
resolveReady?.();
resolveReady = null;
}
const canAnimate = () =>
enabled &&
!motion.matches &&
!document.hidden &&
root.closest("[data-map-view]")?.dataset.mapView !== "3d";
motion.addEventListener("change", settle, { signal: events.signal });
document.addEventListener(
"visibilitychange",
() => {
if (document.hidden) settle();
},
{ signal: events.signal },
);
const observer = new ResizeObserver(() => update(capture()));
const elements = () => {
const map = root.querySelector(".map-scroll");
@ -72,9 +98,9 @@ export function mountMapZoom(root) {
const world = new DOMPoint(client.x, client.y).matrixTransform(
matrix.inverse(),
);
return { world, client: point };
return { world, client: point, matrix: matrix };
}
function update(anchor) {
function update(anchor, { smooth = true } = {}) {
const el = elements();
if (!el) return;
const { map, canvas, svg } = el,
@ -122,6 +148,18 @@ export function mountMapZoom(root) {
viewport,
size + 2 * Math.max(0, viewport / 2 - Math.min(middle, size - middle)),
);
const nextLayout = [
box.x,
box.y,
box.width,
box.height,
svg.dataset.focusBox,
f.width,
f.height,
zoom,
].join();
const changed = layoutKey !== nextLayout;
if (changed) settle();
let resized = false;
for (const [node, property, value] of [
[
@ -151,16 +189,6 @@ export function mountMapZoom(root) {
resized = true;
}
}
const nextLayout = [
box.x,
box.y,
box.width,
box.height,
svg.dataset.focusBox,
f.width,
f.height,
zoom,
].join();
if (map.dataset.zoom !== String(zoom)) map.dataset.zoom = String(zoom);
if (!autoFit && anchor && (resized || layoutKey !== nextLayout)) {
const client = anchor.client ?? center(map);
@ -175,6 +203,35 @@ export function mountMapZoom(root) {
map.scrollLeft += middle.x - (f.x + f.width / 2);
map.scrollTop += middle.y - (f.y + f.height / 2);
}
if (
changed &&
!initial &&
smooth &&
anchor?.matrix &&
canAnimate() &&
svg.animate
) {
const next = svg.getScreenCTM(),
r = svg.getBoundingClientRect();
const ratio = anchor.matrix.a / next.a;
const dx = anchor.matrix.e - ratio * next.e + (ratio - 1) * r.left;
const dy = anchor.matrix.f - ratio * next.f + (ratio - 1) * r.top;
if (Math.abs(ratio - 1) > 0.001 || Math.hypot(dx, dy) > 1) {
map.dataset.mapTransition = "reframe";
ready = new Promise((resolve) => (resolveReady = resolve));
flight = svg.animate(
[
{
transformOrigin: "0 0",
transform: `translate(${dx}px,${dy}px) scale(${ratio})`,
},
{ transformOrigin: "0 0", transform: "none" },
],
{ duration: 850, easing: "cubic-bezier(.22,.61,.36,1)" },
);
flight.onfinish = settle;
}
}
layoutKey = nextLayout;
updatePanCursor(map);
for (const [selector, disabled] of [
@ -195,6 +252,7 @@ export function mountMapZoom(root) {
map.addEventListener(
type,
() => {
settle();
autoFit = false;
},
{
@ -225,11 +283,11 @@ export function mountMapZoom(root) {
observed = map;
}
}
function setZoom(value, anchor = capture()) {
function setZoom(value, anchor = capture(), smooth = true) {
endDrag();
autoFit = false;
zoom = clamp(value, minZoom, MAX_ZOOM);
update(anchor);
update(anchor, { smooth });
}
function endDrag(event) {
if (
@ -335,10 +393,14 @@ export function mountMapZoom(root) {
if (!pinch || event.touches.length !== 2) return;
if (event.cancelable) event.preventDefault();
const { distance, point } = geometry(event.touches);
setZoom((pinch.zoom * distance) / pinch.distance, {
...pinch.anchor,
client: point,
});
setZoom(
(pinch.zoom * distance) / pinch.distance,
{
...pinch.anchor,
client: point,
},
false,
);
}
root.addEventListener(
"pointerdown",
@ -365,10 +427,19 @@ export function mountMapZoom(root) {
return {
capture,
update,
settle,
whenIdle: async () => {
while (flight) await ready;
},
setEnabled(value) {
enabled = value;
if (!enabled) settle();
},
step(direction) {
setZoom((zoom ?? 1) * STEP ** direction);
},
destroy() {
settle();
endPinch();
endDrag();
mapEvents?.abort();

View file

@ -58,10 +58,11 @@ if (params.has("lesson")) {
let undoRequests = 0;
const ui = mountGame(document.querySelector("#game"), {
onUndo: () => (undoRequests += 1),
onMove: (m) => {
onMove: async (m) => {
state = engine.move(state, m, hotseat ? state.actor : 0);
save();
show();
await ui.whenIdle();
scheduleBots();
},
onSetting: (name, value) => {
@ -101,10 +102,11 @@ if (params.has("lesson")) {
function scheduleBots() {
clearTimeout(timer);
if (!hotseat && !state.finished && state.actor !== 0)
timer = setTimeout(() => {
timer = setTimeout(async () => {
state = engine.moveAI(state, state.actor);
save();
show();
await ui.whenIdle();
scheduleBots();
}, 450);
}
@ -145,6 +147,7 @@ if (params.has("lesson")) {
state = engine.moveAI(state, state.actor);
save();
show();
await ui.whenIdle();
await new Promise((r) => setTimeout(r, 160));
}
autoplay = false;

View file

@ -1,5 +1,6 @@
import {
EXPORT_RULE,
REFILL_RULE,
EXTEND_TITLE,
EXTEND_RULE,
ROUND_TITLE,
@ -90,7 +91,8 @@ export function rulesHtml(lang = "en", colorBlind = false) {
"</span>" +
message("Completing a ship adds {p0} to the good's reward.", [
token("point", "+2"),
]),
]) +
`<br><br>${prose(REFILL_RULE)}`,
],
[
"Develop the islands",

View file

@ -2020,3 +2020,45 @@ body:has(.vanuatu) {
.vanuatu .obstacles .obstacle:not(:has(> .icon)) {
padding-inline-start: calc(1.4em + 6px);
}
/* Journal locations are ordinary buttons: touch scrolling stays native. */
.vanuatu .journal-location {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 5px 8px;
width: 100%;
text-align: start;
color: inherit;
font: inherit;
border: 0;
border-radius: 4px;
padding: 5px 7px;
background: transparent;
box-shadow: none;
touch-action: pan-x pan-y;
}
.vanuatu .journal-location.inspected,
.vanuatu .journal-location:focus-visible {
background: #78c8df26;
outline: 1px solid #357fb3;
}
.vanuatu .journal-locate {
margin-inline-start: auto;
opacity: 0.6;
}
.vanuatu .journal-locate .icon {
width: 19px;
height: 19px;
}
.vanuatu .cell-highlight.journal-highlight {
fill: #8ad9ff30;
stroke: #256cae;
stroke-width: 5;
stroke-dasharray: 9 5;
}
.vanuatu .map-3d .map-label.journal-highlight {
outline: 2px solid #256cae;
outline-offset: 3px;
background: #e1f5ff;
}

1866
viewer/three/board.js Normal file

File diff suppressed because it is too large Load diff

180
viewer/three/navigation.js Normal file
View file

@ -0,0 +1,180 @@
const distance = (a, b) => Math.hypot(a.x - b.x, a.z - b.z);
const neighbours = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
[1, 1],
[-1, -1],
];
// Only the game's sea topology guides the illustration. Pieces never block it.
export function seaRoute(board, from, to, start, end, position, cellPath) {
const queue = [from],
parent = new Map([[from, null]]);
for (let i = 0; i < queue.length && !parent.has(to); i++) {
const [q, r] = queue[i].split(",").map(Number);
for (const [dq, dr] of neighbours) {
const id = `${q + dq},${r + dr}`;
if (board[id]?.type === "sea" && !parent.has(id)) {
parent.set(id, queue[i]);
queue.push(id);
}
}
}
const cells = cellPath?.length ? [from, ...cellPath] : [];
if (!cells.length && parent.has(to))
for (let id = to; id; id = parent.get(id)) cells.unshift(id);
const points = [
start,
...cells.slice(1, -1).map((id) => {
const p = position(id);
return { x: p.x, z: p.z - 0.15 };
}),
end,
];
const path = [start];
for (let i = 1; i < points.length - 1; i++) {
const a = points[i - 1],
b = points[i],
c = points[i + 1];
const radius = Math.min(0.28, distance(a, b) * 0.25, distance(b, c) * 0.25);
if (!radius) continue;
const entry = {
x: b.x + ((a.x - b.x) * radius) / distance(a, b),
z: b.z + ((a.z - b.z) * radius) / distance(a, b),
};
const exit = {
x: b.x + ((c.x - b.x) * radius) / distance(b, c),
z: b.z + ((c.z - b.z) * radius) / distance(b, c),
};
for (let j = 0; j <= 8; j++) {
const t = j / 8,
u = 1 - t;
path.push({
x: u * u * entry.x + 2 * u * t * b.x + t * t * exit.x,
z: u * u * entry.z + 2 * u * t * b.z + t * t * exit.z,
});
}
}
path.push(end);
return path;
}
export function routePosition(path, progress) {
if (progress <= 0) return path[0];
if (progress >= 1) return path.at(-1);
const lengths = path.slice(1).map((p, i) => distance(path[i], p));
let remaining = progress * lengths.reduce((a, b) => a + b, 0);
for (let i = 0; i < lengths.length; i++) {
if (remaining <= lengths[i]) {
const t = lengths[i] ? remaining / lengths[i] : 1;
return {
x: path[i].x + (path[i + 1].x - path[i].x) * t,
z: path[i].z + (path[i + 1].z - path[i].z) * t,
};
}
remaining -= lengths[i];
}
return path.at(-1);
}
export function passingSide(path, point, index) {
let nearest = Infinity,
side = index % 2 ? 1 : -1;
for (let i = 1; i < path.length; i++) {
const a = path[i - 1],
b = path[i],
dx = b.x - a.x,
dz = b.z - a.z,
length = Math.hypot(dx, dz);
if (!length) continue;
const t = Math.max(
0,
Math.min(
1,
((point.x - a.x) * dx + (point.z - a.z) * dz) / (length * length),
),
);
const x = a.x + dx * t,
z = a.z + dz * t,
d = Math.hypot(point.x - x, point.z - z);
if (d < nearest) {
nearest = d;
const cross = (point.x - x) * -dz + (point.z - z) * dx;
if (Math.abs(cross) > 0.02) side = Math.sign(cross);
}
}
return side;
}
export function arrivalFraction(remaining) {
const t = Math.max(0, Math.min(1, 1 - remaining / 1.1));
return t * t * (3 - 2 * t);
}
export function giveWay(point, vessel, direction, side, boat, piece) {
const gap = 0.055;
const a = {
minX: point.x + piece.minX,
maxX: point.x + piece.maxX,
minZ: point.z + piece.minZ,
maxZ: point.z + piece.maxZ,
};
const b = {
minX: vessel.x + boat.minX - gap,
maxX: vessel.x + boat.maxX + gap,
minZ: vessel.z + boat.minZ - gap,
maxZ: vessel.z + boat.maxZ + gap,
};
// Both axes must overlap. An infinite strip perpendicular to the route was
// making remote pieces move, especially when the route changed direction.
if (
a.maxX <= b.minX ||
a.minX >= b.maxX ||
a.maxZ <= b.minZ ||
a.minZ >= b.maxZ
)
return { x: 0, z: 0 };
const length = Math.hypot(direction.x, direction.z);
if (!length) return { x: 0, z: 0 };
const normal = { x: -direction.z / length, z: direction.x / length };
function clearance(sign) {
const x = normal.x * sign,
z = normal.z * sign;
return Math.min(
x > 1e-6
? (b.maxX - a.minX) / x
: x < -1e-6
? (a.maxX - b.minX) / -x
: Infinity,
z > 1e-6
? (b.maxZ - a.minZ) / z
: z < -1e-6
? (a.maxZ - b.minZ) / -z
: Infinity,
);
}
const left = clearance(1),
right = clearance(-1);
const sign = Math.abs(left - right) < 0.08 ? side : left < right ? 1 : -1;
const amount = sign === 1 ? left : right;
return { x: normal.x * sign * amount, z: normal.z * sign * amount };
}
// Critically damped: accelerate and settle without oscillating back and forth.
export function stepYield(pose, target, seconds) {
const omega = 23,
decay = Math.exp(-omega * seconds);
for (const [key, velocity] of [
["x", "vx"],
["z", "vz"],
["yaw", "vyaw"],
]) {
const change = pose[key] - target[key],
step = (pose[velocity] + omega * change) * seconds;
pose[key] = target[key] + (change + step) * decay;
pose[velocity] = (pose[velocity] - omega * step) * decay;
}
return pose;
}

View file

@ -0,0 +1,95 @@
// Continuous filtered water noise, tied to animation start/stop rather than a
// fixed-length cue. No ambience runs while the board is idle.
export function createSailingSound(
createContext = () =>
new (globalThis.AudioContext ?? globalThis.webkitAudioContext)(),
) {
let context,
buffer,
voices = [],
generation = 0,
ready = Promise.resolve(),
level = 1;
function unlock() {
try {
context ??= createContext();
if (context.state === "suspended")
ready = context.resume().catch(() => {});
} catch {}
}
function stop(fade = 0.72) {
generation++;
const current = voices;
voices = [];
for (const { source, gain } of current) {
const now = context.currentTime;
if (gain.gain.cancelAndHoldAtTime) gain.gain.cancelAndHoldAtTime(now);
else {
gain.gain.cancelScheduledValues(now);
gain.gain.setValueAtTime(Math.max(0.0001, gain.gain.value), now);
}
gain.gain.setTargetAtTime(0.0001, now, fade / 4.5);
try {
source.stop(now + fade);
} catch {}
}
}
async function start() {
if (voices.length) return;
stop(0.12);
level = 1;
const request = generation;
unlock();
await ready;
if (request !== generation || context?.state !== "running") return;
try {
if (!buffer) {
buffer = context.createBuffer(
1,
context.sampleRate * 2,
context.sampleRate,
);
const data = buffer.getChannelData(0);
let seed = 9173;
for (let i = 0; i < data.length; i++) {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
data[i] = seed / 2147483648 - 1;
}
}
for (const [frequency, volume] of [
[700, 0.095],
[1100, 0.045],
]) {
const source = context.createBufferSource(),
filter = context.createBiquadFilter(),
gain = context.createGain();
source.buffer = buffer;
source.loop = true;
filter.type = "lowpass";
filter.frequency.value = frequency;
source.connect(filter).connect(gain).connect(context.destination);
const now = context.currentTime;
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(volume * level, now + 0.12);
source.onended = () => {
source.disconnect();
filter.disconnect();
gain.disconnect();
};
voices.push({ source, gain, volume });
source.start();
}
} catch {
stop();
}
}
function setRemainingTime(seconds) {
const t = Math.max(0, Math.min(1, seconds / 0.6)),
next = 0.35 + 0.65 * t * t * (3 - 2 * t);
if (Math.abs(level - next) < 0.005) return;
level = next;
for (const { gain, volume } of voices)
gain.gain.setTargetAtTime(volume * level, context.currentTime, 0.045);
}
return { unlock, start, stop, setRemainingTime };
}

View file

@ -0,0 +1,74 @@
import * as THREE from "three";
export const DRAW_DURATION = 1500;
const SEGMENTS = 160;
const SIDES = 5;
// Stable slots: adding a drawing never slides the ones already in the sand.
export function createSandDrawing(slot, capacity) {
const group = new THREE.Group();
group.position.set((slot - (capacity - 1) / 2) * 0.43, 0.271, 0.94);
const points = Array.from({ length: 121 }, (_, i) => {
const t = (i / 120) * Math.PI * 4;
return new THREE.Vector3(Math.sin(t) * 0.17, 0, Math.sin(t * 1.5) * 0.105);
});
const curve = new THREE.CatmullRomCurve3(points, false, "centripetal");
const groove = new THREE.Mesh(
new THREE.TubeGeometry(curve, SEGMENTS, 0.01, SIDES, false),
new THREE.MeshBasicMaterial({ color: "#906437" }),
);
const rim = new THREE.Mesh(
new THREE.TubeGeometry(curve, SEGMENTS, 0.017, SIDES, false),
new THREE.MeshBasicMaterial({ color: "#ffe8b4" }),
);
rim.position.y = -0.008;
group.add(rim, groove);
const tip = new THREE.Group();
const grains = new THREE.MeshBasicMaterial({
color: "#fff0c7",
transparent: true,
opacity: 0,
});
for (let i = 0; i < 3; i++) {
const grain = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.018 - i * 0.003, 0),
grains,
);
grain.position.set((i - 1) * 0.025, 0.027 + i * 0.009, -i * 0.016);
tip.add(grain);
}
group.add(tip);
tip.visible = false;
const drawing = { group, groove, rim, tip, curve, grains };
setDrawingProgress(drawing, 1);
return drawing;
}
export function setDrawingProgress(drawing, progress) {
const p = Math.max(0, Math.min(1, progress));
// Leave time for the fresh sand at the tip to settle after the line closes.
const trace = Math.min(1, p / 0.88);
const count = Math.floor(trace * SEGMENTS) * SIDES * 6;
for (const mesh of [drawing.groove, drawing.rim])
mesh.geometry.setDrawRange(0, count);
drawing.tip.visible = p > 0 && p < 1;
if (drawing.tip.visible) {
drawing.tip.position.copy(drawing.curve.getPointAt(trace));
drawing.grains.opacity = Math.min(1, p / 0.08, (1 - p) / 0.12);
}
}
// Call only with adjacent live events. Loading/replaying a state does not draw
// its old patterns again, and a third drawing is as visible as the first two.
export function newDrawingSlots(events, before, after) {
const slots = [];
for (const event of events) {
if (event.type !== "action" || event.action !== "draw") continue;
const cell = event.cell ?? event.details?.cell;
const start = before?.board[cell]?.drawings;
const end = after?.board[cell]?.drawings;
if (!Number.isInteger(start) || !Number.isInteger(end)) continue;
for (let slot = start; slot < end; slot++) slots.push({ cell, slot });
}
return slots;
}

166
viewer/three/style.css Normal file
View file

@ -0,0 +1,166 @@
.vanuatu .map-3d {
position: absolute;
inset: 0 0 var(--tray-height, 73px);
isolation: isolate;
overflow: hidden;
touch-action: none;
display: none;
}
.vanuatu[data-map-view="3d"] .map-3d {
display: block;
}
.vanuatu[data-map-view="3d"] .map-scroll {
visibility: hidden;
pointer-events: none;
}
.vanuatu .map-3d .world,
.vanuatu .map-3d canvas,
.vanuatu .map-3d .labels {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
.vanuatu .map-3d canvas {
display: block;
cursor: grab;
}
.vanuatu .map-3d canvas:active {
cursor: grabbing;
}
.vanuatu .map-3d .labels {
pointer-events: none;
overflow: hidden;
}
.vanuatu .map-3d .map-label-link {
position: absolute;
left: 0;
top: 0;
border-top: 1px dashed #fff9df;
filter: drop-shadow(0 1px 1px #31595788);
transform-origin: 0 0;
pointer-events: none;
}
.vanuatu .map-3d .map-label {
position: absolute;
left: 0;
top: 0;
display: flex;
align-items: center;
gap: 7px;
white-space: nowrap;
pointer-events: auto;
background: #fffae6f5;
border: 1px solid #f8f9dacc;
color: #244d4e;
border-radius: 14px;
padding: 3px 7px;
box-shadow: 0 2px 3px #194e4c22;
font-size: 13px;
touch-action: none;
}
.vanuatu .map-3d .map-label .icon {
width: 21px;
height: 21px;
}
.vanuatu .map-3d .map-label .token {
gap: 1px;
}
.vanuatu .map-3d .map-label[aria-pressed="true"] {
outline: 2px solid #a7692f;
outline-offset: 2px;
}
.vanuatu .map-3d .map-label.legal {
border-color: #a7692f;
}
.vanuatu .map-3d .map-label[hidden] {
display: none;
}
.vanuatu .map-3d .map-label.model-label {
min-width: 24px;
min-height: 24px;
justify-content: center;
padding: 1px 6px;
border-radius: 50%;
font-size: 13px;
}
.vanuatu .map-3d .map-label.placement-label {
font-size: 15px;
padding: 4px 8px;
border-color: #f8f9dacc;
}
.vanuatu .map-3d .map-label.placement-label .icon {
width: 24px;
height: 24px;
}
.vanuatu .map-3d .map-label.placement-label[aria-pressed="true"] {
outline: none;
}
.vanuatu .map-3d .map-label.placement-label:focus-visible {
outline: 2px solid #a7692f;
outline-offset: 2px;
}
.vanuatu .map-3d .map-label.empty-placement {
width: 44px;
height: 44px;
border: 0;
background: none;
box-shadow: none;
}
.vanuatu .map-view-switch,
.vanuatu .three-tools {
display: flex;
gap: 4px;
}
.vanuatu .map-view-switch {
margin-right: 6px;
}
.vanuatu .map-view-switch button {
font-weight: 700;
min-width: 40px;
padding: 6px 8px;
}
.vanuatu .map-view-switch button[aria-pressed="true"] {
background: #fdf9e7;
border-color: #876c3b;
}
.vanuatu[data-map-view="2d"] .three-tools {
display: none;
}
.vanuatu[data-map-view="3d"] .map-tools > [data-zoom-in],
.vanuatu[data-map-view="3d"] .map-tools > [data-zoom-out] {
display: none;
}
@media (max-width: 700px) {
.vanuatu .map-3d .map-label {
font-size: 11px;
gap: 4px;
padding: 2px 4px;
}
.vanuatu .map-3d .map-label .icon {
width: 17px;
height: 17px;
}
.vanuatu .map-3d .map-label.model-label {
min-width: 20px;
min-height: 20px;
padding: 1px 5px;
font-size: 11px;
}
.vanuatu .map-3d .map-label.placement-label {
flex-direction: column;
gap: 1px;
padding: 3px 5px;
font-size: 14px;
}
.vanuatu .map-3d .map-label.placement-label .icon {
width: 20px;
height: 20px;
}
.vanuatu .map-view-switch {
margin-right: 2px;
}
.vanuatu .map-view-switch button {
min-width: 34px;
}
}

188
viewer/trade-transition.js Normal file
View file

@ -0,0 +1,188 @@
// Reconstruct deliveries from the public event; never delay the actual game state.
export function tradeFrames(before, after, events) {
if (!before || !events.length) return null;
const initial = before.demands.map((d) => ({
...d,
goods: [...d.goods],
filled: [...d.filled],
}));
const delivered = initial.map((d) => ({ ...d, filled: [...d.filled] }));
const touched = new Set(),
completed = new Set();
for (const event of events)
for (const shipment of event.details?.shipments ?? []) {
const ship = delivered.find((d) => d.id === shipment.ship);
const slot = ship?.goods.findIndex(
(good, i) => good === event.good && !ship.filled[i],
);
if (slot >= 0) {
ship.filled[slot] = true;
touched.add(ship.id);
}
if (shipment.complete) completed.add(shipment.ship);
}
const departing = initial
.filter((d) => !after.demands.some((n) => n.id === d.id))
.map((d) => d.id);
return touched.size || departing.length
? {
initial,
delivered,
touched: [...touched],
completed: [...completed],
departing,
}
: null;
}
export function createTradeTransition(root, repaint) {
const motion = matchMedia("(prefers-reduced-motion: reduce)");
let enabled = true,
plan,
visual,
epoch = 0,
ready = Promise.resolve(),
resolveReady;
const timers = new Map(),
animations = new Set();
const allowed = () => enabled && !motion.matches && !document.hidden;
const ships = () => [...root.querySelectorAll(".demand-ship")];
const animate = (node, frames, duration, fill = "none") => {
const a = node.animate(frames, {
duration,
fill,
easing: "cubic-bezier(.22,.61,.36,1)",
});
animations.add(a);
a.onfinish = () => {
if (fill === "none") {
animations.delete(a);
a.cancel();
}
};
};
const wait = (ms) =>
new Promise((resolve) => {
const id = setTimeout(() => {
timers.delete(id);
resolve();
}, ms);
timers.set(id, resolve);
});
function cancel(render = true) {
epoch++;
for (const [id, resolve] of timers) {
clearTimeout(id);
resolve();
}
timers.clear();
for (const a of animations) a.cancel();
animations.clear();
const changed = !!visual;
visual = plan = null;
delete root.dataset.tradeTransition;
resolveReady?.();
resolveReady = null;
if (changed && render) repaint();
}
function prepare(before, after, events) {
cancel(false);
plan = allowed() ? tradeFrames(before, after, events) : null;
if (plan) visual = plan.touched.length ? plan.initial : plan.delivered;
}
async function run() {
if (!plan) return;
const current = epoch,
frame = plan;
ready = new Promise((resolve) => (resolveReady = resolve));
root.dataset.tradeTransition = "delivery";
if (frame.touched.length) {
await wait(420);
if (epoch !== current) return;
visual = frame.delivered;
repaint();
for (const ship of ships().filter((n) =>
frame.touched.includes(Number(n.dataset.ship)),
))
animate(
ship,
[
{ boxShadow: "0 0 0 3px #ba913866", background: "#fff4bd" },
{ boxShadow: "0 0 0 0 transparent" },
],
800,
);
}
if (frame.departing.length) {
root.dataset.tradeTransition = "completed";
await wait(650);
if (epoch !== current) return;
root.dataset.tradeTransition = "departure";
for (const ship of ships().filter((n) =>
frame.departing.includes(Number(n.dataset.ship)),
))
animate(
ship,
[
{ opacity: 1, transform: "translateX(0)" },
{ opacity: 0, transform: "translateX(32px)" },
],
360,
"forwards",
);
await wait(360);
if (epoch !== current) return;
const positions = new Map(
ships().map((n) => [n.dataset.ship, n.getBoundingClientRect()]),
);
for (const a of animations) a.cancel();
animations.clear();
visual = null;
repaint();
root.dataset.tradeTransition = "arrival";
for (const ship of ships()) {
const old = positions.get(ship.dataset.ship),
next = ship.getBoundingClientRect();
animate(
ship,
old
? [
{
transform: `translate(${old.left - next.left}px,${old.top - next.top}px)`,
},
{ transform: "none" },
]
: [
{ opacity: 0, transform: "translateX(-20px)" },
{ opacity: 1, transform: "none" },
],
360,
);
}
await wait(360);
} else await wait(frame.completed.length ? 800 : 300);
if (epoch === current) cancel();
}
const stop = () => cancel();
const visibility = () => {
if (document.hidden) cancel();
};
motion.addEventListener("change", stop);
document.addEventListener("visibilitychange", visibility);
return {
prepare,
run,
cancel,
demands: (fallback) => visual ?? fallback,
whenIdle: () => ready,
setEnabled(value) {
enabled = value;
if (!allowed()) cancel();
},
destroy() {
cancel(false);
motion.removeEventListener("change", stop);
document.removeEventListener("visibilitychange", visibility);
},
};
}

View file

@ -1,3 +1,5 @@
import { createTradeTransition } from "./trade-transition.js";
import { mountBoard3D } from "./three/board.js";
import { playerSymbolGlyph } from "@boardgamers/protocol/player-symbols";
import {
blockingHtml,
@ -109,8 +111,17 @@ export function mountGame(target, options = {}) {
revision,
stateKey,
focusReturn;
let board3D,
threeUnavailable = false,
mapView = "3d",
mapLive = false,
journalCells = [];
try {
if (localStorage.getItem("vanuatu-map-view") === "2d") mapView = "2d";
} catch {}
root.dataset.mapView = mapView;
const patch = createRenderer(
".game-header, .action-dock, .market-info, .demand-ships, .map-scroll, .map-tools, .upcoming, .turn-tray, .player-card, .play-footer",
".map-3d, .game-header, .action-dock, .market-info, .demand-ships, .map-scroll, .map-tools, .upcoming, .turn-tray, .player-card, .play-footer",
(from, to) => {
// These attributes belong to the layout/zoom controllers, not the state.
const attr = from.matches(".sea-board, .map-canvas, .archipelago")
@ -138,12 +149,41 @@ export function mountGame(target, options = {}) {
const effects = createEffects(root, { icon, sound: moveSound, center });
const events = new AbortController();
const listener = { signal: events.signal };
root.addEventListener("pointerdown", () => moveSound.unlock(), {
...listener,
passive: true,
});
root.addEventListener("keydown", () => moveSound.unlock(), listener);
root.addEventListener(
"pointerdown",
() => {
moveSound.unlock();
board3D?.unlock();
},
{
...listener,
passive: true,
},
);
root.addEventListener(
"keydown",
() => {
moveSound.unlock();
board3D?.unlock();
},
listener,
);
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
const mapZoom = mountMapZoom(play);
const tradeTransition = createTradeTransition(root, () => {
const node = play.querySelector(".demand-ships");
if (node && s) patch(node, tradeShips());
});
function syncMotion() {
animations = !reducedMotion.matches;
effects.setEnabled(animations);
mapZoom.setEnabled(animations);
tradeTransition.setEnabled(animations);
root.dataset.animations = String(animations);
syncBoard3D();
}
reducedMotion.addEventListener("change", syncMotion, listener);
syncMotion();
const trayObserver = new ResizeObserver(([entry]) => {
const parent = entry.target.parentElement;
const height = `${entry.borderBoxSize?.[0]?.blockSize ?? entry.target.getBoundingClientRect().height}px`;
@ -153,6 +193,13 @@ export function mountGame(target, options = {}) {
let observedTray;
function observeTray() {
const tray = play.querySelector(".turn-tray");
// Size the map from the final panel before either renderer frames it.
// Waiting for ResizeObserver used to trigger a second camera fit.
if (tray) {
const height = `${tray.getBoundingClientRect().height}px`;
if (tray.parentElement.style.getPropertyValue("--tray-height") !== height)
tray.parentElement.style.setProperty("--tray-height", height);
}
if (tray === observedTray) return;
trayObserver.disconnect();
if (tray) trayObserver.observe(tray, { box: "border-box" });
@ -162,7 +209,19 @@ export function mountGame(target, options = {}) {
chat: options.chat,
openPlayer: options.onOpenPlayer,
avatarForPlayer: (index) => avatars[index],
onBack: () => play.scrollIntoView({ block: "start" }),
onBack: () =>
play.scrollIntoView({
block: "start",
behavior:
animations && !matchMedia("(prefers-reduced-motion: reduce)").matches
? "smooth"
: "instant",
}),
onHighlight(cells) {
journalCells = cells;
updateMapFocus();
syncBoard3D();
},
language: lang,
});
activity.setLanguage(lang);
@ -430,7 +489,13 @@ export function mountGame(target, options = {}) {
}
function tradeShips() {
const help = `Foreign trade\n${colorBlind ? "K: kava · C: copra · B: beef." : "Green: kava · White: copra · Red: beef."}\nEach export fills the first ship (1 → 3) still needing that good. ✓ = already delivered.\nCompleting a ship adds 2 prosperity points.`;
return `<div class="demand-ships" title="${esc(help)}" aria-label="${esc(help)}">${s.demands.map((d, i) => `<div class="demand-ship" data-ship="${d.id}"><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>`;
return `<div class="demand-ships" title="${esc(help)}" aria-label="${esc(help)}">${tradeTransition
.demands(s.demands)
.map(
(d, i) =>
`<div class="demand-ship" data-ship="${d.id}"><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>`;
}
function renderControls() {
const focus = document.activeElement?.getAttribute("data-action");
@ -461,11 +526,71 @@ export function mountGame(target, options = {}) {
}
}
updateMapFocus();
syncBoard3D();
if (focus)
play
.querySelector(`[data-action="${focus}"]`)
?.focus({ preventScroll: true });
}
function setMapView(value, notify = false) {
if (value !== "2d" && value !== "3d") return;
mapView = threeUnavailable ? "2d" : value;
root.dataset.mapView = mapView;
try {
localStorage.setItem("vanuatu-map-view", mapView);
} catch {}
const select = dialog.querySelector("[data-map-preference]");
if (select) select.value = mapView;
effects.cancel();
moveSound.stop();
if (notify) options.onPreference?.("mapView", mapView);
}
function syncBoard3D() {
if (!s) return;
const host = play.querySelector(".map-3d");
if (mapView === "3d" && !board3D && !threeUnavailable) {
try {
board3D = mountBoard3D(host, { onSelect: cellClick });
} catch (error) {
console.warn("3D unavailable; using 2D", error);
threeUnavailable = true;
mapView = "2d";
root.dataset.mapView = mapView;
for (const button of play.querySelectorAll("[data-map-view]")) {
button.setAttribute(
"aria-pressed",
String(button.dataset.mapView === mapView),
);
if (button.dataset.mapView === "3d") button.disabled = true;
}
}
}
play
.querySelector(".map-scroll")
?.toggleAttribute("inert", mapView === "3d");
if (!board3D) return;
const targets =
s.phase === "expand"
? working()
.filter((m) => m.type === "place" && m.tile === tile)
.map((m) => m.cell)
: actualTargets();
board3D.setVisible(mapView === "3d");
board3D.update(s, {
selected,
targets,
hoverTile: tile,
player,
colorBlind,
journalCells,
symbols: s.players.map((_, i) => symbol(i)),
language: lang,
animations,
sound,
live: mapLive,
});
mapLive = false;
}
let boardKey, boardHtml;
function renderBoard(targets) {
const hoverTile = s.phase === "expand" ? tile : null;
@ -514,13 +639,14 @@ export function mountGame(target, options = {}) {
.map((m) => m.cell)
: actualTargets();
const html = `<header class="game-header"><div class="brand">${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}<div class="game-credits"><span>Designed by Alain Epron</span><span>Published by Quined Games</span></div></div><div class="round-track" aria-label="${t("round")} ${s.round}/8">${Array.from({ length: 8 }, (_, i) => `<span title="${t("round")} ${i + 1}/8" class="${i + 1 === s.round ? "current" : i + 1 < s.round ? "past" : ""}">${i + 1}</span>`).join("")}</div><nav class="header-tools">${undoAvailable && enabled && !analysis ? titled(t("undoMove"), icon("undo"), "data-undo-move", "icon-button") : ""}${analysis || !options.chat ? "" : titled(t("chat"), `${icon("chat")}<span class="unread-badge" hidden></span>`, 'data-activity="chat"', "icon-button")}${titled(t("journal"), icon("journal"), 'data-activity="journal"', "icon-button")}${titled(t("colorBlind"), icon("colorBlind"), `data-color-blind aria-pressed="${colorBlind}"`, "icon-button")}${titled(t("help"), icon("help"), "data-help", "icon-button")}${titled(t("full"), icon("fullscreen"), "data-fullscreen", "icon-button")}</nav></header>
<div class="table">${dock()}<section class="sea-board"><div class="sea-dashboard"><div class="market-info"><span class="fish-price" title="${esc(marketHelp)}">${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}</span><span title="${t("tourist")}">${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}</span>${s.waterCountdown !== null ? `<span title="${t("waterLeft")}">${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}</span>` : ""}</div>${tradeShips()}</div><div class="map-scroll"><div class="map-canvas">${renderBoard(targets)}</div></div><div class="map-tools">${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}</div>${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}</section></div><section class="players">${s.players.map(playerCard).join("")}</section><footer class="play-footer"><span title="${"Automatic conversion"}">${token("coin", 10)} → ${token("point", 5)}</span>${btn(t("help"), "data-help", "text-button")}</footer>`;
<div class="table">${dock()}<section class="sea-board"><div class="sea-dashboard"><div class="market-info"><span class="fish-price" title="${esc(marketHelp)}">${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}</span><span title="${t("tourist")}">${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}</span>${s.waterCountdown !== null ? `<span title="${t("waterLeft")}">${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}</span>` : ""}</div>${tradeShips()}</div><div class="map-scroll"><div class="map-canvas">${renderBoard(targets)}</div></div><div class="map-3d"></div><div class="map-tools"><span class="map-view-switch">${btn("2D", `data-map-view="2d" aria-pressed="${mapView === "2d"}"`)}${btn("3D", `data-map-view="3d" aria-pressed="${mapView === "3d"}" ${threeUnavailable ? "disabled" : ""}`)}</span><span class="three-tools">${titled(translateText("Overview", lang), icon("overview"), "data-three-home", "icon-button")}${titled("Zoom out", icon("zoomOut"), "data-three-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-three-in", "icon-button")}</span>${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}</div>${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}</section></div><section class="players">${s.players.map(playerCard).join("")}</section><footer class="play-footer"><span title="${"Automatic conversion"}">${token("coin", 10)} → ${token("point", 5)}</span>${btn(t("help"), "data-help", "text-button")}</footer>`;
// Patch in place so cached SVG tile images and focused controls survive
// preference changes and incoming state updates.
patch(play, `<div class="play">${html}</div>`, true);
updateMapFocus();
observeTray();
mapZoom.update(mapAnchor);
syncBoard3D();
if (focus)
play
.querySelector(`[data-action="${focus}"]`)
@ -650,6 +776,11 @@ export function mountGame(target, options = {}) {
else renderControls();
}
function updateMapFocus() {
for (const cell of play.querySelectorAll("[data-highlight-cell]"))
cell.classList.toggle(
"journal-highlight",
journalCells.includes(cell.dataset.highlightCell),
);
const cell = play.querySelector('.map-cell[role="button"]:focus-visible');
const highlight =
cell &&
@ -684,6 +815,23 @@ export function mountGame(target, options = {}) {
}
if (!button || button.disabled) return;
const d = button.dataset;
if ("mapView" in d) {
setMapView(d.mapView, true);
render();
return;
}
if ("threeHome" in d) {
board3D?.reset();
return;
}
if ("threeIn" in d) {
board3D?.zoom(0.8);
return;
}
if ("threeOut" in d) {
board3D?.zoom(1.25);
return;
}
if ("undoMove" in d) {
options.onUndo?.();
return;
@ -835,7 +983,7 @@ export function mountGame(target, options = {}) {
}
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="animations" ${animations ? "checked" : ""}>${esc(translateText("Animations", lang))}</label><label><input type="checkbox" data-pref="sound" ${sound ? "checked" : ""}>${t("sound")}</label>${options.onSetting && Number.isInteger(player) && !analysis ? `<label><input type="checkbox" data-setting="autoRetrieve" ${autoRetrieve ? "checked" : ""}>${esc(translateText("Automatically retrieve markers when there is no choice", lang))}</label>` : ""}${
`<h2>${t("help")}</h2><div class="preferences"><label><input type="checkbox" data-pref="colorBlind" ${colorBlind ? "checked" : ""}>${t("colorBlind")}</label><select data-map-preference aria-label="2D / 3D"><option value="2d" ${mapView === "2d" ? "selected" : ""}>2D</option><option value="3d" ${mapView === "3d" ? "selected" : ""} ${threeUnavailable ? "disabled" : ""}>3D</option></select><label><input type="checkbox" data-pref="sound" ${sound ? "checked" : ""}>${t("sound")}</label>${options.onSetting && Number.isInteger(player) && !analysis ? `<label><input type="checkbox" data-setting="autoRetrieve" ${autoRetrieve ? "checked" : ""}>${esc(translateText("Automatically retrieve markers when there is no choice", lang))}</label>` : ""}${
hostedLocale
? ""
: `<select data-language aria-label="Language">${Object.entries(
@ -896,19 +1044,19 @@ export function mountGame(target, options = {}) {
if (key === "colorBlind") {
colorBlind = value;
}
if (key === "animations") {
animations = value;
effects.setEnabled(value);
root.dataset.animations = String(value);
}
if (key === "sound") {
sound = value;
moveSound.setEnabled(value);
syncBoard3D();
moveSound.unlock();
}
options.onPreference?.(key, value);
render();
}
if (e.target.matches("[data-map-preference]")) {
setMapView(e.target.value, true);
render();
}
if (e.target.matches("[data-setting]")) {
options.onSetting?.(e.target.dataset.setting, e.target.checked);
e.target.checked = autoRetrieve;
@ -959,11 +1107,13 @@ export function mountGame(target, options = {}) {
const captured = incoming.length ? effects.capture() : null;
const next = `${state.historyLength ?? state.round + ":" + state.phase}:${player}`;
const key = JSON.stringify(state);
mapLive = live && !analysis;
rawState = state;
s = displayState(state);
if (stateKey === key && next === revision) return;
stateKey = key;
effects.cancel();
tradeTransition.prepare(before, s, incoming);
if (!incoming.length) moveSound.stop();
if (next !== revision) {
selected = null;
@ -973,6 +1123,7 @@ export function mountGame(target, options = {}) {
}
render();
if (incoming.length) effects.show(incoming, before, s, captured, player);
void tradeTransition.run();
},
setAvatars(value) {
if (JSON.stringify(avatars) === JSON.stringify(value)) return;
@ -988,7 +1139,17 @@ export function mountGame(target, options = {}) {
selected = null;
render();
},
whenIdle: () =>
Promise.all([
board3D?.whenIdle(),
mapZoom.whenIdle(),
tradeTransition.whenIdle(),
effects.whenIdle(),
]),
stopEffects() {
board3D?.settle();
mapZoom.settle();
tradeTransition.cancel();
effects.cancel();
moveSound.stop();
},
@ -1009,7 +1170,7 @@ export function mountGame(target, options = {}) {
if (checkbox) checkbox.checked = autoRetrieve;
},
setPreferences(p) {
const previous = `${analysis}:${colorBlind}:${lang}:${playerColors.join()}:${JSON.stringify(appearance)}`;
const previous = `${analysis}:${colorBlind}:${lang}:${mapView}:${playerColors.join()}:${JSON.stringify(appearance)}`;
appearance = p.bgs ?? {};
chatNotifications = p.chatNotifications !== false;
analysis = p.analysis === true;
@ -1020,16 +1181,18 @@ export function mountGame(target, options = {}) {
)
: [];
s = displayState(rawState);
animations = p.animations !== false;
effects.setEnabled(animations);
if (root.dataset.animations !== String(animations))
root.dataset.animations = String(animations);
if (
(p.mapView === "2d" || p.mapView === "3d") &&
p.mapView !== mapView &&
!threeUnavailable
)
setMapView(p.mapView);
syncMotion();
sound = p.sound === true;
moveSound.setEnabled(sound);
for (const [name, value] of Object.entries({
colorBlind,
sound,
animations,
})) {
const checkbox = dialog.querySelector(`[data-pref="${name}"]`);
if (checkbox && checkbox.checked !== value) checkbox.checked = value;
@ -1045,14 +1208,19 @@ export function mountGame(target, options = {}) {
}
if (
previous !==
`${analysis}:${colorBlind}:${lang}:${playerColors.join()}:${JSON.stringify(appearance)}`
`${analysis}:${colorBlind}:${lang}:${mapView}:${playerColors.join()}:${JSON.stringify(appearance)}`
)
render();
else updateUnread();
else {
updateUnread();
syncBoard3D();
}
},
destroy() {
events.abort();
mapZoom.destroy();
tradeTransition.destroy();
board3D?.destroy();
trayObserver.disconnect();
effects.destroy();
moveSound.destroy();